Compare commits
145 Commits
23f8fddc4d
...
feat/plann
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
450e685580 | ||
|
|
0e116bec7b | ||
|
|
47b49743c0 | ||
|
|
506caa2c53 | ||
|
|
388a8c1fae | ||
|
|
42b208ff28 | ||
|
|
309f84b388 | ||
|
|
00608401aa | ||
|
|
229d4bbb2b | ||
| 845359b885 | |||
|
|
d4a46420c9 | ||
|
|
f704244b84 | ||
|
|
782110604b | ||
|
|
19bf032a2e | ||
|
|
b7464c9a11 | ||
|
|
524aaf85af | ||
|
|
a9e7479326 | ||
|
|
2e80cc606e | ||
|
|
d099138487 | ||
|
|
2278d97b7e | ||
|
|
74255ddc82 | ||
|
|
b466246c1b | ||
|
|
b3eb39a28b | ||
|
|
253e6f05e0 | ||
|
|
042a1b47c2 | ||
|
|
7a20534e7c | ||
|
|
ee2cbc92ef | ||
|
|
373f04a034 | ||
|
|
43d517dcfc | ||
|
|
8891d48af2 | ||
|
|
0b72c0fb53 | ||
|
|
a41e5b5b2d | ||
|
|
00c62178e1 | ||
|
|
bbe7d73de2 | ||
|
|
0934b294c2 | ||
|
|
b28d8f2f4a | ||
|
|
ec4ec44603 | ||
|
|
ee09706811 | ||
|
|
c06d1d6afb | ||
|
|
f906e7086c | ||
|
|
caf900b02d | ||
|
|
e80e3fccc0 | ||
|
|
e8056553fd | ||
|
|
ea4d2d7c0c | ||
|
|
98c188a5da | ||
|
|
0c3dcb0052 | ||
|
|
e017d66023 | ||
|
|
ba0b38b4f1 | ||
|
|
5b4cdd366e | ||
|
|
7c0f8d8408 | ||
|
|
0a7fcae137 | ||
|
|
5346737e2b | ||
|
|
80f6669585 | ||
|
|
27054e6715 | ||
|
|
ea7694566d | ||
|
|
46e01aefed | ||
|
|
41e0bea162 | ||
|
|
86012e02b9 | ||
|
|
da19eb807b | ||
|
|
0d37473575 | ||
|
|
6a4bf676ff | ||
|
|
a135485339 | ||
|
|
3c420acd54 | ||
|
|
5ced1b97a6 | ||
|
|
1344beba56 | ||
|
|
c8c8bb4a47 | ||
|
|
6f725d12f5 | ||
|
|
9952ff98f2 | ||
|
|
4a6d96b90e | ||
|
|
2690332d13 | ||
|
|
31218fc205 | ||
|
|
cc01871407 | ||
|
|
e70ae7f6ce | ||
|
|
1830273a9d | ||
|
|
1a10e6fa09 | ||
|
|
df57c2bc05 | ||
|
|
990be09bd7 | ||
|
|
e275f67a5e | ||
|
|
ff3de1d100 | ||
|
|
a4e313dbad | ||
|
|
7de5510735 | ||
|
|
5e54275842 | ||
|
|
6ac88235a7 | ||
|
|
c599fdcb8c | ||
|
|
b0b15e474e | ||
|
|
839f862b7d | ||
|
|
2901a769d8 | ||
|
|
e74e7eecf4 | ||
|
|
bba577888b | ||
|
|
5784dbee94 | ||
|
|
5348220e60 | ||
|
|
cd0b95ef9a | ||
|
|
fc1cfe59ec | ||
|
|
7c312161bb | ||
|
|
480eb0817a | ||
|
|
1b94fa5c44 | ||
|
|
02464b7f89 | ||
|
|
68f461d0e1 | ||
|
|
cfb410dd4d | ||
|
|
b378fbf550 | ||
|
|
cb43bcdd10 | ||
|
|
31420574db | ||
|
|
07dee31847 | ||
|
|
4debd5ce09 | ||
|
|
1495c63e3d | ||
|
|
953d93179d | ||
|
|
1bc7fcc609 | ||
|
|
c911717a3b | ||
|
|
949911f6c8 | ||
|
|
f3a58a6515 | ||
|
|
ee4cd706ef | ||
|
|
e11b01951e | ||
|
|
3d0cc4ffed | ||
|
|
4585b20f80 | ||
|
|
c53b5878cf | ||
|
|
c13ae437f7 | ||
|
|
5780879629 | ||
|
|
2bcd5ef9bd | ||
|
|
63eb860e40 | ||
|
|
e80ac7de49 | ||
|
|
3331c24898 | ||
|
|
1c20d8f846 | ||
|
|
77a1460e3a | ||
|
|
21a1870fd7 | ||
|
|
3ebbdb3f6e | ||
|
|
535d0c5558 | ||
|
|
2d807aa606 | ||
|
|
93ee7b72d5 | ||
|
|
32ef1b389a | ||
|
|
0885518a68 | ||
|
|
944d3bd3e8 | ||
|
|
fb89e02b02 | ||
|
|
58c8210afa | ||
|
|
2ce6b7bd3a | ||
|
|
f90d3d8375 | ||
|
|
b03e858a8f | ||
|
|
2278b516ea | ||
|
|
219a231f32 | ||
|
|
74eb36d3c0 | ||
|
|
202236a45b | ||
|
|
88be19a231 | ||
|
|
44203f3c67 | ||
|
|
133774cb86 | ||
|
|
a3bb557d76 | ||
|
|
883c98dc0a |
@@ -2,7 +2,11 @@
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git add:*)",
|
||||
"Bash(git commit:*)"
|
||||
"Bash(git commit:*)",
|
||||
"mcp__plugin_context-mode_context-mode__batch_execute",
|
||||
"mcp__plugin_context-mode_context-mode__execute",
|
||||
"mcp__plugin_context7_context7__query-docs",
|
||||
"mcp__plugin_context-mode_context-mode__search"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ jobs:
|
||||
cd "$WORK/src"
|
||||
dotnet publish src/ClaudeDo.App/ClaudeDo.App.csproj \
|
||||
-c Release -r win-x64 --self-contained true \
|
||||
/p:Version=$VERSION -o out/app
|
||||
/p:MinVerVersionOverride=$VERSION -o out/app
|
||||
|
||||
- name: Publish ClaudeDo.Worker (win-x64, self-contained)
|
||||
env:
|
||||
@@ -65,7 +65,7 @@ jobs:
|
||||
cd "$WORK/src"
|
||||
dotnet publish src/ClaudeDo.Worker/ClaudeDo.Worker.csproj \
|
||||
-c Release -r win-x64 --self-contained true \
|
||||
/p:Version=$VERSION -o out/worker
|
||||
/p:MinVerVersionOverride=$VERSION -o out/worker
|
||||
|
||||
- name: Publish ClaudeDo.Installer (win-x64, single-file, framework-dependent)
|
||||
env:
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
# Target machines need .NET 8 Desktop Runtime (x64).
|
||||
dotnet publish src/ClaudeDo.Installer/ClaudeDo.Installer.csproj \
|
||||
-c Release -r win-x64 --self-contained false \
|
||||
/p:Version=$VERSION /p:PublishSingleFile=true \
|
||||
/p:MinVerVersionOverride=$VERSION /p:PublishSingleFile=true \
|
||||
-o out/installer
|
||||
|
||||
- name: Package assets
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,3 +1,6 @@
|
||||
# Local dev worktrees (created by using-git-worktrees skill)
|
||||
.worktrees/
|
||||
|
||||
# .NET build output
|
||||
bin/
|
||||
obj/
|
||||
|
||||
@@ -5,10 +5,12 @@
|
||||
<Project Path="src/ClaudeDo.Ui/ClaudeDo.Ui.csproj" />
|
||||
<Project Path="src/ClaudeDo.Worker/ClaudeDo.Worker.csproj" />
|
||||
<Project Path="src/ClaudeDo.Installer/ClaudeDo.Installer.csproj" />
|
||||
<Project Path="src/ClaudeDo.Releases/ClaudeDo.Releases.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
<Project Path="tests/ClaudeDo.Ui.Tests/ClaudeDo.Ui.Tests.csproj" />
|
||||
<Project Path="tests/ClaudeDo.Worker.Tests/ClaudeDo.Worker.Tests.csproj" />
|
||||
<Project Path="tests/ClaudeDo.Installer.Tests/ClaudeDo.Installer.Tests.csproj" />
|
||||
<Project Path="tests/ClaudeDo.Releases.Tests/ClaudeDo.Releases.Tests.csproj" />
|
||||
</Folder>
|
||||
</Solution>
|
||||
|
||||
8
Directory.Build.props
Normal file
8
Directory.Build.props
Normal file
@@ -0,0 +1,8 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<MinVerTagPrefix>v</MinVerTagPrefix>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MinVer" Version="5.0.0" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
29
README.md
29
README.md
@@ -16,29 +16,29 @@ Two-process system communicating over SignalR:
|
||||
| **ClaudeDo.Worker** | ASP.NET Core hosted service, task queue, Claude CLI runner |
|
||||
|
||||
```
|
||||
┌──────────────┐ SignalR ┌──────────────┐
|
||||
│ ClaudeDo.App│◄──────────►│ClaudeDo.Worker│
|
||||
│ (Avalonia) │ 127.0.0.1 │ (ASP.NET) │
|
||||
┌────────────────┐ SignalR ┌────────────────┐
|
||||
│ ClaudeDo.App │◄───────────►│ ClaudeDo.Worker │
|
||||
│ (Avalonia) │ 127.0.0.1 │ (ASP.NET Core) │
|
||||
│ │ :47821 │ │
|
||||
│ ┌──────────┐│ │ ┌──────────┐ │
|
||||
│ │ Ui ││ │ │ TaskQueue│ │
|
||||
│ │(ViewModels)│ │ │ Claude CLI│ │
|
||||
│ └──────────┘│ │ └──────────┘ │
|
||||
└──────┬───────┘ └──────┬───────┘
|
||||
│ ┌────────────┐│ │ ┌────────────┐ │
|
||||
│ │ Ui ││ │ │ TaskQueue │ │
|
||||
│ │(ViewModels)││ │ │ Claude CLI │ │
|
||||
│ └────────────┘│ │ └────────────┘ │
|
||||
└───────┬────────┘ └───────┬────────┘
|
||||
│ │
|
||||
└───────────┬───────────────┘
|
||||
└──────────────┬───────────────┘
|
||||
│
|
||||
┌──────┴──────┐
|
||||
│ ClaudeDo.Data│
|
||||
┌───────┴───────┐
|
||||
│ ClaudeDo.Data │
|
||||
│ (SQLite) │
|
||||
└─────────────┘
|
||||
└───────────────┘
|
||||
```
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- .NET 8.0
|
||||
- Avalonia 12.0.0 (Fluent theme)
|
||||
- SQLite (WAL mode) via Microsoft.Data.Sqlite — raw ADO.NET, no ORM
|
||||
- SQLite (WAL mode) via Entity Framework Core (EF Core + Migrations)
|
||||
- SignalR for real-time IPC between UI and Worker
|
||||
- CommunityToolkit.Mvvm for source-generated MVVM
|
||||
- Git worktrees for task isolation
|
||||
@@ -53,7 +53,8 @@ Two-process system communicating over SignalR:
|
||||
|
||||
```bash
|
||||
# Build
|
||||
dotnet build ClaudeDo.slnx
|
||||
dotnet build src/ClaudeDo.App
|
||||
dotnet build src/ClaudeDo.Worker
|
||||
|
||||
# Run tests
|
||||
dotnet test tests/ClaudeDo.Worker.Tests
|
||||
|
||||
35
docs/open.md
35
docs/open.md
@@ -191,3 +191,38 @@ Im aktuellen Stand kompiliert die UI, aber mehrere Stellen sind als `// TODO` ma
|
||||
9. **Tag-Negation (3.4)** — wenn der Bedarf konkret wird.
|
||||
|
||||
Punkte 1–3 sind ein realistischer Block für eine Session.
|
||||
|
||||
---
|
||||
|
||||
## Self-Update — Manual Verification
|
||||
|
||||
Preconditions: a working Gitea release at `git.kuns.dev/releases/ClaudeDo` with three assets — `ClaudeDo-<version>-win-x64.zip`, `ClaudeDo.Installer-<version>.exe`, and `checksums.txt` listing both.
|
||||
|
||||
1. Install a baseline version (e.g. `0.2.x`) normally.
|
||||
2. Publish a new release tagged `v0.3.0` with fresh installer + app zip + checksums.
|
||||
3. Launch the app — confirm the banner appears: `Update available: v0.2.x → v0.3.0`.
|
||||
4. Click **Update now** — app closes, installer opens in Update mode, runs, restarts the worker.
|
||||
5. Re-launch the app — banner is gone; `Help → Check for updates` briefly shows "You're up to date (v0.3.0)".
|
||||
6. Run the `v0.2.x` installer manually — confirm it prompts to self-update to v0.3.0. Click **Update** → running exe is replaced and the wizard opens on the new version.
|
||||
7. Repeat step 6 with **Continue anyway** → wizard opens without self-update.
|
||||
8. Repeat step 6 with **Cancel** → installer exits without any action.
|
||||
9. Kill network during startup in both app and installer → confirm silent fallback (no errors, no banner, wizard opens normally).
|
||||
|
||||
---
|
||||
|
||||
## Planning Sessions — Manual Verification (Plan C UI)
|
||||
|
||||
Requires Plan B (worker hub endpoints) merged. Until then, only the UI structure/styling checks are meaningful.
|
||||
|
||||
1. Create a Manual task with a title and a TODO-ish description.
|
||||
2. Right-click the task → **Open planning Session** — Windows Terminal opens with Claude CLI running (Plan B).
|
||||
3. Ask Claude to create two child tasks via `mcp__claudedo__create_child_task`.
|
||||
4. Watch the UI: drafts appear indented under the parent, italic, reduced opacity, with a `DRAFT` badge.
|
||||
5. The parent shows a `PLANNING` badge. Click the chevron → children collapse; click again → children expand.
|
||||
6. Ask Claude to `finalize` — drafts flip to Manual/Queued children; parent flips to `PLANNED` badge.
|
||||
7. In a new planning task, close the terminal without finalize. Right-click the Planning task → the unfinished-session modal opens with Resume / Finalize now / Discard.
|
||||
8. Attempt to delete a parent with children via the details panel — confirm the friendly error dialog appears and the task is NOT deleted.
|
||||
|
||||
**Known followups (non-blocking):**
|
||||
- `Border.badge.planned` style (blue) is defined in `IslandStyles.axaml` but never applied — `TaskRowView` keeps the `planning` class for both Planning and Planned, so Planned gets the amber badge. Either make the view swap `Classes.planned` when status is Planned, or remove the unused style + brush.
|
||||
- Dead `Instance` statics on `BoolToItalicConverter` and `BoolToDraftOpacityConverter` — App.axaml registers instances via the resource dictionary; the static members can be removed.
|
||||
|
||||
@@ -0,0 +1,803 @@
|
||||
# Continue & Reset Buttons for Failed Tasks — Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add two buttons (Continue, Reset) to the details pane for `Failed` tasks so the user can either nudge the agent to continue or discard the worktree and return the task to `Manual`.
|
||||
|
||||
**Architecture:** Spec is at `docs/superpowers/specs/2026-04-21-continue-and-reset-failed-tasks-design.md`. Backend adds one git-discard helper, one task-repository method, a small orchestration service, and a new hub method `ResetTask`. `ContinueTask` is already wired in the hub. UI adds two commands in `DetailsIslandViewModel` and a button row in `DetailsIslandView`.
|
||||
|
||||
**Tech Stack:** .NET 8, EF Core (SQLite), ASP.NET Core SignalR, Avalonia 12, CommunityToolkit.Mvvm, xUnit 2.5 (integration tests with real SQLite + real git).
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
**New files:**
|
||||
- `src/ClaudeDo.Worker/Services/TaskResetService.cs` — orchestrates the reset (load task, discard worktree, reset DB row, broadcast).
|
||||
- `tests/ClaudeDo.Worker.Tests/Services/TaskResetServiceTests.cs` — integration tests for the orchestration.
|
||||
|
||||
**Modified files:**
|
||||
- `src/ClaudeDo.Worker/Runner/WorktreeManager.cs` — add `DiscardAsync`.
|
||||
- `src/ClaudeDo.Data/Repositories/TaskRepository.cs` — add `ResetToManualAsync`.
|
||||
- `src/ClaudeDo.Worker/Hub/WorkerHub.cs` — add `ResetTask` endpoint; DI-inject the new service.
|
||||
- `src/ClaudeDo.Worker/Program.cs` — register `TaskResetService` in DI.
|
||||
- `src/ClaudeDo.Ui/Services/WorkerClient.cs` — add `ContinueTaskAsync` and `ResetTaskAsync` wrappers.
|
||||
- `src/ClaudeDo.Ui/ViewModels/Islands/DetailsIslandViewModel.cs` — add observable properties and commands.
|
||||
- `src/ClaudeDo.Ui/Views/Islands/DetailsIslandView.axaml` — add button row bound to the new commands.
|
||||
- `tests/ClaudeDo.Worker.Tests/Runner/WorktreeManagerTests.cs` — add `DiscardAsync` test.
|
||||
- `tests/ClaudeDo.Worker.Tests/Repositories/TaskRepositoryTests.cs` — add `ResetToManualAsync` test.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: `WorktreeManager.DiscardAsync` (TDD)
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Worker/Runner/WorktreeManager.cs`
|
||||
- Test: `tests/ClaudeDo.Worker.Tests/Runner/WorktreeManagerTests.cs`
|
||||
|
||||
`GitService` already exposes `WorktreeRemoveAsync(workingDir, path, force, ct)` and `BranchDeleteAsync(workingDir, branch, force, ct)` — verify via `git grep -n "public async Task WorktreeRemoveAsync\|public async Task BranchDeleteAsync" src/ClaudeDo.Data/Git`. If either is missing, stop and add the git wrapper first.
|
||||
|
||||
- [ ] **Step 1: Add the failing test**
|
||||
|
||||
Add at the bottom of `tests/ClaudeDo.Worker.Tests/Runner/WorktreeManagerTests.cs` (before the `Dispose` method):
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public async Task DiscardAsync_RemovesWorktreeAndBranch_AndSetsStateDiscarded()
|
||||
{
|
||||
if (!GitAvailable) { Assert.True(true, "git not available -- skipping"); return; }
|
||||
|
||||
var repo = CreateRepo();
|
||||
var (task, list) = MakeEntities(repo.RepoDir);
|
||||
var (mgr, db) = await CreateManagerAsync(task, list);
|
||||
|
||||
var ctx = await mgr.CreateAsync(task, list, CancellationToken.None);
|
||||
var worktreePath = ctx.WorktreePath;
|
||||
|
||||
WorktreeEntity wt;
|
||||
using (var readCtx = db.CreateContext())
|
||||
wt = (await new WorktreeRepository(readCtx).GetByTaskIdAsync(task.Id))!;
|
||||
|
||||
await mgr.DiscardAsync(wt, list.WorkingDir!, CancellationToken.None);
|
||||
|
||||
Assert.False(Directory.Exists(worktreePath), "worktree directory should be gone");
|
||||
|
||||
using var readCtx2 = db.CreateContext();
|
||||
var row = await new WorktreeRepository(readCtx2).GetByTaskIdAsync(task.Id);
|
||||
Assert.NotNull(row);
|
||||
Assert.Equal(WorktreeState.Discarded, row!.State);
|
||||
|
||||
// Branch should no longer exist on the main repo.
|
||||
var branchList = await new GitService().RunForOutputAsync(repo.RepoDir, new[] { "branch", "--list", ctx.BranchName }, CancellationToken.None);
|
||||
Assert.True(string.IsNullOrWhiteSpace(branchList),
|
||||
$"branch {ctx.BranchName} should be deleted, got: {branchList}");
|
||||
}
|
||||
```
|
||||
|
||||
Note on `RunForOutputAsync`: if `GitService` does not expose a generic run helper, replace the branch-check with a direct `System.Diagnostics.Process` invocation of `git branch --list <branch>` in the test. If such a helper exists with a different name, use it.
|
||||
|
||||
- [ ] **Step 2: Run test, verify it fails**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests --filter "FullyQualifiedName~DiscardAsync_RemovesWorktreeAndBranch" -v minimal`
|
||||
Expected: FAIL — `DiscardAsync` does not exist.
|
||||
|
||||
- [ ] **Step 3: Implement `DiscardAsync`**
|
||||
|
||||
Add to `src/ClaudeDo.Worker/Runner/WorktreeManager.cs` after `CommitIfChangedAsync`:
|
||||
|
||||
```csharp
|
||||
public async Task DiscardAsync(WorktreeEntity wt, string workingDir, CancellationToken ct)
|
||||
{
|
||||
// Remove the git worktree first; --force drops uncommitted changes (user already confirmed).
|
||||
try
|
||||
{
|
||||
await _git.WorktreeRemoveAsync(workingDir, wt.Path, force: true, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "git worktree remove failed for {Path}", wt.Path);
|
||||
throw;
|
||||
}
|
||||
|
||||
// Delete the branch. If worktree removal succeeded but branch delete fails,
|
||||
// we still record the worktree as Discarded — the folder is gone, and a dangling
|
||||
// branch is recoverable; leaving the DB out of sync is worse.
|
||||
try
|
||||
{
|
||||
await _git.BranchDeleteAsync(workingDir, wt.BranchName, force: true, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "git branch -D {Branch} failed after worktree removal; continuing", wt.BranchName);
|
||||
}
|
||||
|
||||
using var context = _dbFactory.CreateDbContext();
|
||||
var wtRepo = new WorktreeRepository(context);
|
||||
await wtRepo.SetStateAsync(wt.TaskId, WorktreeState.Discarded, ct);
|
||||
|
||||
_logger.LogInformation("Discarded worktree for task {TaskId} (branch {Branch})", wt.TaskId, wt.BranchName);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test, verify it passes**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests --filter "FullyQualifiedName~DiscardAsync_RemovesWorktreeAndBranch" -v minimal`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Worker/Runner/WorktreeManager.cs tests/ClaudeDo.Worker.Tests/Runner/WorktreeManagerTests.cs
|
||||
git commit -m "feat(worker): add WorktreeManager.DiscardAsync for task reset"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: `TaskRepository.ResetToManualAsync` (TDD)
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Data/Repositories/TaskRepository.cs`
|
||||
- Test: `tests/ClaudeDo.Worker.Tests/Repositories/TaskRepositoryTests.cs`
|
||||
|
||||
- [ ] **Step 1: Add the failing test**
|
||||
|
||||
Add to `tests/ClaudeDo.Worker.Tests/Repositories/TaskRepositoryTests.cs` (follow the existing test style in that file — reuse any helpers it already has for creating a list + task):
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public async Task ResetToManualAsync_ClearsResultFields_AndSetsStatusManual()
|
||||
{
|
||||
using var db = new DbFixture();
|
||||
using var ctx = db.CreateContext();
|
||||
var listRepo = new ListRepository(ctx);
|
||||
var taskRepo = new TaskRepository(ctx);
|
||||
|
||||
var list = new ListEntity { Id = Guid.NewGuid().ToString(), Name = "L", CreatedAt = DateTime.UtcNow };
|
||||
await listRepo.AddAsync(list);
|
||||
|
||||
var task = new TaskEntity
|
||||
{
|
||||
Id = Guid.NewGuid().ToString(),
|
||||
ListId = list.Id,
|
||||
Title = "T",
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
Status = TaskStatus.Failed,
|
||||
StartedAt = DateTime.UtcNow.AddMinutes(-5),
|
||||
FinishedAt = DateTime.UtcNow,
|
||||
Result = "boom",
|
||||
};
|
||||
await taskRepo.AddAsync(task);
|
||||
|
||||
await taskRepo.ResetToManualAsync(task.Id);
|
||||
|
||||
using var readCtx = db.CreateContext();
|
||||
var after = await new TaskRepository(readCtx).GetByIdAsync(task.Id);
|
||||
Assert.NotNull(after);
|
||||
Assert.Equal(TaskStatus.Manual, after!.Status);
|
||||
Assert.Null(after.StartedAt);
|
||||
Assert.Null(after.FinishedAt);
|
||||
Assert.Null(after.Result);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test, verify it fails**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests --filter "FullyQualifiedName~ResetToManualAsync_ClearsResultFields" -v minimal`
|
||||
Expected: FAIL — `ResetToManualAsync` does not exist.
|
||||
|
||||
- [ ] **Step 3: Implement `ResetToManualAsync`**
|
||||
|
||||
Add to `src/ClaudeDo.Data/Repositories/TaskRepository.cs` inside the `#region Status transitions` block, after `FlipAllRunningToFailedAsync`:
|
||||
|
||||
```csharp
|
||||
public async Task ResetToManualAsync(string taskId, CancellationToken ct = default)
|
||||
{
|
||||
await _context.Tasks
|
||||
.Where(t => t.Id == taskId)
|
||||
.ExecuteUpdateAsync(s => s
|
||||
.SetProperty(t => t.Status, TaskStatus.Manual)
|
||||
.SetProperty(t => t.StartedAt, (DateTime?)null)
|
||||
.SetProperty(t => t.FinishedAt, (DateTime?)null)
|
||||
.SetProperty(t => t.Result, (string?)null), ct);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test, verify it passes**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests --filter "FullyQualifiedName~ResetToManualAsync_ClearsResultFields" -v minimal`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Data/Repositories/TaskRepository.cs tests/ClaudeDo.Worker.Tests/Repositories/TaskRepositoryTests.cs
|
||||
git commit -m "feat(data): add TaskRepository.ResetToManualAsync"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: `TaskResetService` (TDD)
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ClaudeDo.Worker/Services/TaskResetService.cs`
|
||||
- Create: `tests/ClaudeDo.Worker.Tests/Services/TaskResetServiceTests.cs`
|
||||
|
||||
This service orchestrates Task 1 + Task 2, plus the "reject if Running" safety check and the SignalR broadcast.
|
||||
|
||||
- [ ] **Step 1: Add the failing test — happy path**
|
||||
|
||||
Create `tests/ClaudeDo.Worker.Tests/Services/TaskResetServiceTests.cs`:
|
||||
|
||||
```csharp
|
||||
using ClaudeDo.Data;
|
||||
using ClaudeDo.Data.Git;
|
||||
using ClaudeDo.Data.Models;
|
||||
using ClaudeDo.Data.Repositories;
|
||||
using ClaudeDo.Worker.Config;
|
||||
using ClaudeDo.Worker.Hub;
|
||||
using ClaudeDo.Worker.Runner;
|
||||
using ClaudeDo.Worker.Services;
|
||||
using ClaudeDo.Worker.Tests.Infrastructure;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;
|
||||
|
||||
namespace ClaudeDo.Worker.Tests.Services;
|
||||
|
||||
public class TaskResetServiceTests : IDisposable
|
||||
{
|
||||
private readonly List<GitRepoFixture> _fixtures = new();
|
||||
private readonly List<DbFixture> _dbFixtures = new();
|
||||
private static bool GitAvailable => GitRepoFixture.IsGitAvailable();
|
||||
|
||||
[Fact]
|
||||
public async Task ResetAsync_FailedTaskWithWorktree_ClearsEverything_AndPreservesRunHistory()
|
||||
{
|
||||
if (!GitAvailable) { Assert.True(true, "git not available -- skipping"); return; }
|
||||
|
||||
var repo = new GitRepoFixture(); _fixtures.Add(repo);
|
||||
var db = new DbFixture(); _dbFixtures.Add(db);
|
||||
|
||||
var list = new ListEntity { Id = Guid.NewGuid().ToString(), Name = "L", WorkingDir = repo.RepoDir, CreatedAt = DateTime.UtcNow };
|
||||
var task = new TaskEntity { Id = Guid.NewGuid().ToString(), ListId = list.Id, Title = "T", CreatedAt = DateTime.UtcNow };
|
||||
|
||||
using (var seed = db.CreateContext())
|
||||
{
|
||||
await new ListRepository(seed).AddAsync(list);
|
||||
await new TaskRepository(seed).AddAsync(task);
|
||||
}
|
||||
|
||||
var wtMgr = new WorktreeManager(new GitService(), db.CreateFactory(), new WorkerConfig(), NullLogger<WorktreeManager>.Instance);
|
||||
var wtCtx = await wtMgr.CreateAsync(task, list, CancellationToken.None);
|
||||
|
||||
// Seed a Failed task with a run row (we'll assert it's preserved).
|
||||
using (var ctx = db.CreateContext())
|
||||
{
|
||||
await new TaskRepository(ctx).MarkFailedAsync(task.Id, DateTime.UtcNow, "it broke");
|
||||
await new TaskRunRepository(ctx).AddAsync(new TaskRunEntity
|
||||
{
|
||||
Id = Guid.NewGuid().ToString(),
|
||||
TaskId = task.Id,
|
||||
RunNumber = 1,
|
||||
IsRetry = false,
|
||||
Prompt = "p",
|
||||
SessionId = "s1",
|
||||
FinishedAt = DateTime.UtcNow,
|
||||
});
|
||||
}
|
||||
|
||||
var broadcaster = new FakeHubBroadcaster();
|
||||
var svc = new TaskResetService(db.CreateFactory(), wtMgr, broadcaster, NullLogger<TaskResetService>.Instance);
|
||||
|
||||
await svc.ResetAsync(task.Id, CancellationToken.None);
|
||||
|
||||
using var readCtx = db.CreateContext();
|
||||
var after = await new TaskRepository(readCtx).GetByIdAsync(task.Id);
|
||||
Assert.Equal(TaskStatus.Manual, after!.Status);
|
||||
Assert.Null(after.Result);
|
||||
Assert.Null(after.StartedAt);
|
||||
Assert.Null(after.FinishedAt);
|
||||
|
||||
var wtAfter = await new WorktreeRepository(readCtx).GetByTaskIdAsync(task.Id);
|
||||
Assert.Equal(WorktreeState.Discarded, wtAfter!.State);
|
||||
Assert.False(Directory.Exists(wtCtx.WorktreePath));
|
||||
|
||||
var runs = await new TaskRunRepository(readCtx).GetByTaskIdAsync(task.Id);
|
||||
Assert.Single(runs);
|
||||
|
||||
Assert.Contains(task.Id, broadcaster.TaskUpdatedIds);
|
||||
Assert.Contains(task.Id, broadcaster.WorktreeUpdatedIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResetAsync_RunningTask_Throws_AndDoesNotMutate()
|
||||
{
|
||||
var db = new DbFixture(); _dbFixtures.Add(db);
|
||||
var list = new ListEntity { Id = Guid.NewGuid().ToString(), Name = "L", CreatedAt = DateTime.UtcNow };
|
||||
var task = new TaskEntity { Id = Guid.NewGuid().ToString(), ListId = list.Id, Title = "T", CreatedAt = DateTime.UtcNow, Status = TaskStatus.Running, StartedAt = DateTime.UtcNow };
|
||||
|
||||
using (var seed = db.CreateContext())
|
||||
{
|
||||
await new ListRepository(seed).AddAsync(list);
|
||||
await new TaskRepository(seed).AddAsync(task);
|
||||
}
|
||||
|
||||
var wtMgr = new WorktreeManager(new GitService(), db.CreateFactory(), new WorkerConfig(), NullLogger<WorktreeManager>.Instance);
|
||||
var svc = new TaskResetService(db.CreateFactory(), wtMgr, new FakeHubBroadcaster(), NullLogger<TaskResetService>.Instance);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => svc.ResetAsync(task.Id, CancellationToken.None));
|
||||
|
||||
using var readCtx = db.CreateContext();
|
||||
var after = await new TaskRepository(readCtx).GetByIdAsync(task.Id);
|
||||
Assert.Equal(TaskStatus.Running, after!.Status);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var f in _fixtures) f.Dispose();
|
||||
foreach (var d in _dbFixtures) d.Dispose();
|
||||
}
|
||||
|
||||
private sealed class FakeHubBroadcaster : HubBroadcaster
|
||||
{
|
||||
public List<string> TaskUpdatedIds { get; } = new();
|
||||
public List<string> WorktreeUpdatedIds { get; } = new();
|
||||
public FakeHubBroadcaster() : base(new FakeHubContext()) { }
|
||||
public new Task TaskUpdated(string taskId) { TaskUpdatedIds.Add(taskId); return Task.CompletedTask; }
|
||||
public new Task WorktreeUpdated(string taskId) { WorktreeUpdatedIds.Add(taskId); return Task.CompletedTask; }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Check existing fakes: the test file assumes `FakeHubContext` exists under `ClaudeDo.Worker.Tests.Infrastructure` (the Worker.Tests CLAUDE.md lists `FakeHubContext`, `FakeHubClients`, `FakeClientProxy`). If `HubBroadcaster` methods are not virtual, the `new` keyword above will not intercept calls — instead, use the real `HubBroadcaster` with `FakeHubContext` and inspect the fake's recorded calls. Adjust the test implementation to use whichever approach matches the existing test conventions (see `QueueServiceTests` for precedent).
|
||||
|
||||
- [ ] **Step 2: Run tests, verify they fail**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests --filter "FullyQualifiedName~TaskResetServiceTests" -v minimal`
|
||||
Expected: FAIL — `TaskResetService` does not exist.
|
||||
|
||||
- [ ] **Step 3: Implement `TaskResetService`**
|
||||
|
||||
Create `src/ClaudeDo.Worker/Services/TaskResetService.cs`:
|
||||
|
||||
```csharp
|
||||
using ClaudeDo.Data;
|
||||
using ClaudeDo.Data.Repositories;
|
||||
using ClaudeDo.Worker.Hub;
|
||||
using ClaudeDo.Worker.Runner;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;
|
||||
|
||||
namespace ClaudeDo.Worker.Services;
|
||||
|
||||
public sealed class TaskResetService
|
||||
{
|
||||
private readonly IDbContextFactory<ClaudeDoDbContext> _dbFactory;
|
||||
private readonly WorktreeManager _wtManager;
|
||||
private readonly HubBroadcaster _broadcaster;
|
||||
private readonly ILogger<TaskResetService> _logger;
|
||||
|
||||
public TaskResetService(
|
||||
IDbContextFactory<ClaudeDoDbContext> dbFactory,
|
||||
WorktreeManager wtManager,
|
||||
HubBroadcaster broadcaster,
|
||||
ILogger<TaskResetService> logger)
|
||||
{
|
||||
_dbFactory = dbFactory;
|
||||
_wtManager = wtManager;
|
||||
_broadcaster = broadcaster;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task ResetAsync(string taskId, CancellationToken ct)
|
||||
{
|
||||
bool worktreeChanged = false;
|
||||
|
||||
using (var ctx = _dbFactory.CreateDbContext())
|
||||
{
|
||||
var taskRepo = new TaskRepository(ctx);
|
||||
var task = await taskRepo.GetByIdAsync(taskId, ct)
|
||||
?? throw new KeyNotFoundException($"Task '{taskId}' not found.");
|
||||
|
||||
if (task.Status == TaskStatus.Running)
|
||||
throw new InvalidOperationException("Cannot reset a running task. Cancel it first.");
|
||||
|
||||
var listRepo = new ListRepository(ctx);
|
||||
var list = await listRepo.GetByIdAsync(task.ListId, ct)
|
||||
?? throw new InvalidOperationException("List not found.");
|
||||
|
||||
var wtRepo = new WorktreeRepository(ctx);
|
||||
var wt = await wtRepo.GetByTaskIdAsync(taskId, ct);
|
||||
|
||||
if (wt is not null && wt.State == Data.Models.WorktreeState.Active && list.WorkingDir is not null)
|
||||
{
|
||||
// DiscardAsync uses its own DbContext internally; we close this one first.
|
||||
ctx.Dispose();
|
||||
await _wtManager.DiscardAsync(wt, list.WorkingDir, ct);
|
||||
worktreeChanged = true;
|
||||
}
|
||||
}
|
||||
|
||||
using (var ctx = _dbFactory.CreateDbContext())
|
||||
{
|
||||
var taskRepo = new TaskRepository(ctx);
|
||||
await taskRepo.ResetToManualAsync(taskId, ct);
|
||||
}
|
||||
|
||||
await _broadcaster.TaskUpdated(taskId);
|
||||
if (worktreeChanged)
|
||||
await _broadcaster.WorktreeUpdated(taskId);
|
||||
|
||||
_logger.LogInformation("Reset task {TaskId} to Manual (worktree discarded: {Discarded})", taskId, worktreeChanged);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note: the `ctx.Dispose()` inside a `using` block works because `Dispose` is idempotent. If you prefer, refactor to scope the first block with `{ }` + explicit `await using` and move the dispose before the call.
|
||||
|
||||
- [ ] **Step 4: Run tests, verify they pass**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests --filter "FullyQualifiedName~TaskResetServiceTests" -v minimal`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Worker/Services/TaskResetService.cs tests/ClaudeDo.Worker.Tests/Services/TaskResetServiceTests.cs
|
||||
git commit -m "feat(worker): add TaskResetService for discard + reset flow"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Wire `TaskResetService` into DI and add `WorkerHub.ResetTask`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Worker/Program.cs`
|
||||
- Modify: `src/ClaudeDo.Worker/Hub/WorkerHub.cs`
|
||||
|
||||
- [ ] **Step 1: Register the service in DI**
|
||||
|
||||
Open `src/ClaudeDo.Worker/Program.cs`. Locate the block where `QueueService`, `WorktreeManager`, `HubBroadcaster`, `WorktreeMaintenanceService`, etc. are registered (look for `builder.Services.AddSingleton<QueueService>` or similar). Add next to them:
|
||||
|
||||
```csharp
|
||||
builder.Services.AddSingleton<TaskResetService>();
|
||||
```
|
||||
|
||||
Match the lifetime of sibling services (most are `AddSingleton`). If the sibling services use a different lifetime, match it.
|
||||
|
||||
- [ ] **Step 2: Inject it into `WorkerHub`**
|
||||
|
||||
Modify `src/ClaudeDo.Worker/Hub/WorkerHub.cs`:
|
||||
|
||||
In the field block (near `_wtMaintenance`):
|
||||
|
||||
```csharp
|
||||
private readonly TaskResetService _resetService;
|
||||
```
|
||||
|
||||
In the constructor signature, append `TaskResetService resetService` and assign it. The full updated constructor:
|
||||
|
||||
```csharp
|
||||
public WorkerHub(
|
||||
QueueService queue,
|
||||
AgentFileService agentService,
|
||||
HubBroadcaster broadcaster,
|
||||
IDbContextFactory<ClaudeDoDbContext> dbFactory,
|
||||
WorktreeMaintenanceService wtMaintenance,
|
||||
TaskResetService resetService)
|
||||
{
|
||||
_queue = queue;
|
||||
_agentService = agentService;
|
||||
_broadcaster = broadcaster;
|
||||
_dbFactory = dbFactory;
|
||||
_wtMaintenance = wtMaintenance;
|
||||
_resetService = resetService;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Add the `ResetTask` hub method**
|
||||
|
||||
Add inside `WorkerHub` (place it near `ContinueTask` for symmetry):
|
||||
|
||||
```csharp
|
||||
public async Task ResetTask(string taskId)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _resetService.ResetAsync(taskId, CancellationToken.None);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
throw new HubException(ex.Message);
|
||||
}
|
||||
catch (KeyNotFoundException)
|
||||
{
|
||||
throw new HubException("task not found");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Build the worker to verify wiring**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Worker/ClaudeDo.Worker.csproj`
|
||||
Expected: SUCCESS (no compile errors). Note: `dotnet build ClaudeDo.slnx` requires .NET 9 — build individual csproj files instead.
|
||||
|
||||
- [ ] **Step 5: Run the full worker test suite**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests -v minimal`
|
||||
Expected: PASS (all existing tests plus the new ones from Tasks 1-3).
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Worker/Program.cs src/ClaudeDo.Worker/Hub/WorkerHub.cs
|
||||
git commit -m "feat(worker): expose ResetTask hub method"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Add `ContinueTaskAsync` and `ResetTaskAsync` to `WorkerClient`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/Services/WorkerClient.cs`
|
||||
|
||||
- [ ] **Step 1: Add both methods**
|
||||
|
||||
Open `src/ClaudeDo.Ui/Services/WorkerClient.cs`. Next to `RunNowAsync` (around line 166):
|
||||
|
||||
```csharp
|
||||
public async Task ContinueTaskAsync(string taskId, string followUpPrompt)
|
||||
{
|
||||
await _hub.InvokeAsync("ContinueTask", taskId, followUpPrompt);
|
||||
}
|
||||
|
||||
public async Task ResetTaskAsync(string taskId)
|
||||
{
|
||||
await _hub.InvokeAsync("ResetTask", taskId);
|
||||
}
|
||||
```
|
||||
|
||||
If the existing `RunNowAsync` fires a local event first (e.g. `RunNowRequestedEvent?.Invoke(taskId)`), do **not** mirror that — Continue/Reset don't need UI-local optimistic state; we rely on `TaskUpdated` broadcasts.
|
||||
|
||||
- [ ] **Step 2: Build the UI project**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`
|
||||
Expected: SUCCESS.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/Services/WorkerClient.cs
|
||||
git commit -m "feat(ui): add ContinueTaskAsync and ResetTaskAsync to WorkerClient"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Add commands and state to `DetailsIslandViewModel`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/ViewModels/Islands/DetailsIslandViewModel.cs`
|
||||
|
||||
Background you need before editing:
|
||||
- The VM already has a `Task` property (`TaskRowViewModel?`) that represents the selected task.
|
||||
- Status is tracked via `AgentStatusLabel` and exposed as `IsRunning`/`IsDone`/`IsFailed`.
|
||||
- `TaskRowViewModel` may not currently hold the latest `SessionId`. You need a way to read the latest run's `SessionId` for the selected task — query `TaskRunRepository` during the existing task-load flow. If the VM already loads task runs (search for `TaskRunRepository` usage in `DetailsIslandViewModel`), piggyback on that; otherwise add a DB query inside the task-load method.
|
||||
|
||||
- [ ] **Step 1: Add observable properties for button visibility/enablement**
|
||||
|
||||
In the observable-property block (after `_promptInput`, around line 29), add:
|
||||
|
||||
```csharp
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ContinueCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(ResetCommand))]
|
||||
private bool _showFailedActions;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ContinueCommand))]
|
||||
private string? _latestRunSessionId;
|
||||
```
|
||||
|
||||
Also hook `AgentStatusLabel` changes to refresh `ShowFailedActions`. Update the existing `OnAgentStatusLabelChanged` partial method:
|
||||
|
||||
```csharp
|
||||
partial void OnAgentStatusLabelChanged(string value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsRunning));
|
||||
OnPropertyChanged(nameof(IsDone));
|
||||
OnPropertyChanged(nameof(IsFailed));
|
||||
ShowFailedActions = value == "Failed";
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Populate `LatestRunSessionId` during task load**
|
||||
|
||||
Find the method in `DetailsIslandViewModel` that loads details for the selected task (likely named `LoadAsync`, `OnTaskChanged`, or similar — search for where `Turns`, `Tokens`, or `AgentStatusLabel` are assigned). Inside that method, after loading the task entity:
|
||||
|
||||
```csharp
|
||||
using var runCtx = _dbFactory.CreateDbContext();
|
||||
var runRepo = new TaskRunRepository(runCtx);
|
||||
var latestRun = await runRepo.GetLatestByTaskIdAsync(Task.Id);
|
||||
LatestRunSessionId = latestRun?.SessionId;
|
||||
```
|
||||
|
||||
Verify the method name `GetLatestByTaskIdAsync` exists on `TaskRunRepository` (it is used in `TaskRunner.ContinueAsync`). If the name differs, use whatever is exposed. Make sure this runs inside the same cancellation-safe block as the other loads — copy the existing pattern verbatim.
|
||||
|
||||
Also ensure `LatestRunSessionId` is reset to `null` when the selected task clears. If the VM has an `OnTaskChanged` partial method that clears other fields, add `LatestRunSessionId = null;` there too.
|
||||
|
||||
- [ ] **Step 3: Add the two commands**
|
||||
|
||||
Add at the end of the class (next to `RunNowAsync` / `CanRunNow`):
|
||||
|
||||
```csharp
|
||||
[RelayCommand(CanExecute = nameof(CanContinue))]
|
||||
private async System.Threading.Tasks.Task ContinueAsync()
|
||||
{
|
||||
if (Task == null) return;
|
||||
await _worker.ContinueTaskAsync(Task.Id, "Continue working on this task.");
|
||||
}
|
||||
|
||||
private bool CanContinue() =>
|
||||
Task != null
|
||||
&& _worker.IsConnected
|
||||
&& ShowFailedActions
|
||||
&& !string.IsNullOrEmpty(LatestRunSessionId);
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanReset))]
|
||||
private async System.Threading.Tasks.Task ResetAsync()
|
||||
{
|
||||
if (Task == null) return;
|
||||
if (ConfirmAsync == null) return;
|
||||
|
||||
var confirmed = await ConfirmAsync(
|
||||
$"Discard worktree and reset task?\nThis deletes branch claudedo/{Task.Id.Replace("-", "")} and all uncommitted changes.");
|
||||
if (!confirmed) return;
|
||||
|
||||
await _worker.ResetTaskAsync(Task.Id);
|
||||
}
|
||||
|
||||
private bool CanReset() =>
|
||||
Task != null
|
||||
&& _worker.IsConnected
|
||||
&& ShowFailedActions;
|
||||
```
|
||||
|
||||
Also update the worker-connection PropertyChanged handler (around line 112) to notify the new commands:
|
||||
|
||||
```csharp
|
||||
_worker.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(WorkerClient.IsConnected))
|
||||
{
|
||||
RunNowCommand.NotifyCanExecuteChanged();
|
||||
ContinueCommand.NotifyCanExecuteChanged();
|
||||
ResetCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Build the UI project**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`
|
||||
Expected: SUCCESS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/ViewModels/Islands/DetailsIslandViewModel.cs
|
||||
git commit -m "feat(ui): add Continue and Reset commands to DetailsIslandViewModel"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Add the button row to `DetailsIslandView.axaml`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/Views/Islands/DetailsIslandView.axaml`
|
||||
|
||||
- [ ] **Step 1: Inspect the existing layout**
|
||||
|
||||
Read `src/ClaudeDo.Ui/Views/Islands/DetailsIslandView.axaml` end-to-end so you understand the grid layout. The `AgentStripView` sits at `Grid.Row="0"`. Decide whether to add a new grid row below it or to extend the agent strip itself. Simplest: add the button row to `AgentStripView.axaml`, since that control already contains `RunNowCommand` / `StopCommand` buttons and is bound to the same VM.
|
||||
|
||||
- [ ] **Step 2: Add the buttons to `AgentStripView.axaml`**
|
||||
|
||||
Open `src/ClaudeDo.Ui/Views/Islands/AgentStripView.axaml`. Locate the existing `RunNowCommand` button (around line 49). After it, add:
|
||||
|
||||
```xml
|
||||
<Button
|
||||
Content="Continue"
|
||||
Command="{Binding ContinueCommand}"
|
||||
IsVisible="{Binding ShowFailedActions}"
|
||||
ToolTip.Tip="Resume the failed Claude session with 'Continue working on this task.'"
|
||||
Margin="4,0,0,0"/>
|
||||
|
||||
<Button
|
||||
Content="Reset"
|
||||
Command="{Binding ResetCommand}"
|
||||
IsVisible="{Binding ShowFailedActions}"
|
||||
ToolTip.Tip="Discard the worktree and return the task to Manual"
|
||||
Margin="4,0,0,0"/>
|
||||
```
|
||||
|
||||
Match the style (classes, padding, height) of the surrounding `RunNow` / `Stop` buttons — copy their `Classes`, `Padding`, and `Height` attributes verbatim so the row stays visually consistent.
|
||||
|
||||
For the Continue button's disabled-with-tooltip affordance when there's no session_id: the `CanExecute` binding already disables the button; Avalonia shows tooltips on disabled controls when `ToolTip.ShowOnDisabled="True"` — set that on the Continue button and add a second tooltip hinting at the reason is unnecessary since the button will simply be greyed out. If you want an explicit "No session to resume" hint, add a `Classes.disabled` trigger or use a `MultiBinding`; skip this refinement unless it is trivial in the existing theme.
|
||||
|
||||
- [ ] **Step 3: Wire the confirmation dialog**
|
||||
|
||||
The VM's `ResetAsync` uses `ConfirmAsync` (a `Func<string, Task<bool>>` already declared on the VM at line 100). Search the codebase for where `ConfirmAsync` is assigned on the `DetailsIslandViewModel` instance — there is an existing assignment because `DeleteTaskCommand` already uses it. No new wiring needed; the same dialog will handle Reset confirmations.
|
||||
|
||||
- [ ] **Step 4: Launch the UI and smoke-test**
|
||||
|
||||
1. In one terminal: `dotnet run --project src/ClaudeDo.Worker/ClaudeDo.Worker.csproj`
|
||||
2. In another terminal: `dotnet run --project src/ClaudeDo.App/ClaudeDo.App.csproj`
|
||||
3. Create a task that will fail (e.g. a task pointing at a non-existent working dir, or type something into Claude's prompt that makes it error). Wait for status `Failed`.
|
||||
4. Verify the Continue and Reset buttons appear in the details pane.
|
||||
5. Click Reset → confirm → verify the task row flips to `Manual`, the worktree directory is gone from disk, and the branch is gone from `git branch --list | grep claudedo/` in the target repo.
|
||||
6. Create another failing task. Click Continue → verify a new run starts (status flips to `Running`), resumes the same Claude session, and completes (Done or Failed again).
|
||||
7. Verify on a task that has no session_id (e.g. cancel before Claude emits anything), the Continue button is disabled.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/Views/Islands/AgentStripView.axaml
|
||||
git commit -m "feat(ui): add Continue and Reset buttons to agent strip"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 8: Update project docs
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Worker/CLAUDE.md`
|
||||
- Modify: `src/ClaudeDo.Ui/CLAUDE.md`
|
||||
|
||||
- [ ] **Step 1: Update Worker CLAUDE.md**
|
||||
|
||||
Under the `SignalR Hub` section, extend the `WorkerHub methods` line:
|
||||
|
||||
```
|
||||
**WorkerHub** methods: `Ping()`, `GetActive()`, `RunNow(taskId)`, `CancelTask(taskId)`, `WakeQueue()`, `ContinueTask(taskId, prompt)`, `ResetTask(taskId)`, `GetAgents()`, `RefreshAgents()`
|
||||
```
|
||||
|
||||
Under `Key Components`, add one line:
|
||||
|
||||
```
|
||||
- **TaskResetService** — discards a failed task's worktree and resets the task row to Manual; preserves run history.
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Update UI CLAUDE.md**
|
||||
|
||||
Extend the `WorkerClient` description to mention the two new methods:
|
||||
|
||||
```
|
||||
- **WorkerClient** — ... Methods: StartAsync, RunNowAsync, CancelTaskAsync, ContinueTaskAsync, ResetTaskAsync, WakeQueueAsync. Events: ...
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Worker/CLAUDE.md src/ClaudeDo.Ui/CLAUDE.md
|
||||
git commit -m "docs: note ResetTask hub method and TaskResetService"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
**Spec coverage:**
|
||||
- Continue button (canned prompt, one-click, disabled without session) → Task 6 (`ContinueCommand`, `CanContinue`) + Task 7 (button).
|
||||
- Reset button (always enabled on Failed, confirm dialog) → Task 6 (`ResetCommand`, `CanReset`) + Task 7 (button + confirm).
|
||||
- Buttons only on Failed → `ShowFailedActions` drives `IsVisible` (Task 6, Task 7).
|
||||
- Hub `ResetTask` → Task 4.
|
||||
- `WorktreeManager.DiscardAsync` → Task 1.
|
||||
- `TaskRepository.ResetToManualAsync` → Task 2.
|
||||
- Reject reset on Running → Task 3.
|
||||
- Worktree-remove failure leaves task Failed → Task 3 (`DiscardAsync` throws before `ResetToManualAsync` is called).
|
||||
- Run history preserved → Task 2 and Task 3 assertions.
|
||||
- Tests — WorktreeManager.DiscardAsync, TaskRepository.ResetToManualAsync, TaskResetService full flow, reject running → Tasks 1, 2, 3.
|
||||
- Test for "ResetTask rejects running" → Task 3 test 2.
|
||||
- Test for "worktree remove failure leaves task Failed" → covered implicitly by the code structure (Task 3 does not call `ResetToManualAsync` if `DiscardAsync` throws). If you want an explicit test, add one in Task 3 by injecting a failure; marking optional as the control flow is straightforward.
|
||||
|
||||
**Placeholder scan:** no TBDs; every code step has code; commands include expected output.
|
||||
|
||||
**Type consistency:** `DiscardAsync(WorktreeEntity wt, string workingDir, ct)` used consistently (Tasks 1 and 3). `ResetToManualAsync(taskId, ct)` used consistently (Tasks 2 and 3). `ContinueTaskAsync`/`ResetTaskAsync` on `WorkerClient` match the hub method names. `ShowFailedActions`, `LatestRunSessionId`, `CanContinue`, `CanReset` referenced consistently across Task 6 and Task 7.
|
||||
189
docs/superpowers/plans/2026-04-21-open-items-consolidation.md
Normal file
189
docs/superpowers/plans/2026-04-21-open-items-consolidation.md
Normal file
@@ -0,0 +1,189 @@
|
||||
# Open Items Consolidation — 2026-04-21
|
||||
|
||||
Consolidates everything still open from `docs/open.md`, `docs/improvement-plan.md`, and the 2026-04-16 subtask-tree spec. Today's plans/specs (stream-formatter, settings-modal, continue-and-reset) are explicitly out of scope — those are tracked separately.
|
||||
|
||||
Grouped by priority and sorted by UX impact vs. effort. Each item lists **Soll**, **Dateien**, **Aufwand**, **Risiko**.
|
||||
|
||||
---
|
||||
|
||||
## P1 — UX blockers and robustness
|
||||
|
||||
### 1. Auto-Reconnect (ex IP-1)
|
||||
**Soll:** `HubConnectionBuilder.WithAutomaticReconnect(...)` + event handlers for `Reconnecting`/`Reconnected`/`Closed`. Exponential backoff.
|
||||
**Dateien:** `src/ClaudeDo.Ui/Services/WorkerClient.cs`
|
||||
**Aufwand:** klein (~30 Zeilen)
|
||||
**Risiko:** klein
|
||||
|
||||
### 2. Reconnect-State in StatusBar (ex IP-7)
|
||||
**Soll:** States `connected | connecting | reconnecting | offline`, farb-codiert. Depends on #1.
|
||||
**Dateien:** `src/ClaudeDo.Ui/ViewModels/StatusBarViewModel.cs`, StatusBar view
|
||||
**Aufwand:** klein
|
||||
**Risiko:** klein
|
||||
|
||||
### 3. Folder-Picker für Working Directory (ex open.md 2.1)
|
||||
**Soll:** Button neben Pfad-TextBox → `IStorageProvider.OpenFolderPickerAsync`.
|
||||
**Dateien:** `src/ClaudeDo.Ui/Views/ListEditorView.axaml(.cs)`, `ViewModels/ListEditorViewModel.cs`
|
||||
**Aufwand:** klein (~30 Zeilen)
|
||||
**Risiko:** klein
|
||||
|
||||
### 4. Markdown-Rendering für Result/Description (ex open.md 2.3)
|
||||
**Soll:** `Markdown.Avalonia` Paket einbinden, `MarkdownScrollViewer` statt readonly `TextBox` in Details-Island.
|
||||
**Dateien:** `src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`, `Views/Islands/DetailsIslandView.axaml`
|
||||
**Aufwand:** mittel (Theme-Integration kann zicken)
|
||||
**Risiko:** klein–mittel
|
||||
|
||||
### 5. Live-Log Auto-Scroll (ex open.md 2.4)
|
||||
**Soll:** Sticky-Bottom-Pattern: `ScrollToEnd()` auf neue Zeilen, außer User hat manuell hochgescrollt.
|
||||
**Dateien:** `src/ClaudeDo.Ui/Views/Islands/SessionTerminalView.axaml(.cs)`
|
||||
**Aufwand:** klein
|
||||
**Risiko:** klein
|
||||
|
||||
### 6. CLI-Preflight beim Worker-Start (ex open.md 3.1)
|
||||
**Soll:** Startup-Check `claude --version` + Login-Status. Wenn fehlt → laut failen mit Hinweis, nicht still in Queue idlen.
|
||||
**Dateien:** `src/ClaudeDo.Worker/Runner/ClaudeProcess.cs`, Worker startup (Program.cs / HostedService)
|
||||
**Aufwand:** klein
|
||||
**Risiko:** klein
|
||||
|
||||
---
|
||||
|
||||
## P2 — Daten & Features
|
||||
|
||||
### 7. Notes-Mode (ex IP-2)
|
||||
**Soll:** Neue Spalte `lists.kind` (`agent` | `notes`). Worker filtert auf `kind = 'agent'`. UI versteckt Run/Schedule/Worktree-Felder für `notes`.
|
||||
**Dateien:**
|
||||
- Migration + `TaskList` Entity + `IEntityTypeConfiguration`
|
||||
- `src/ClaudeDo.Worker/Queue/QueueService.cs` (Filter)
|
||||
- `ViewModels/ListEditorViewModel.cs`, `Views/Islands/*` (conditional visibility)
|
||||
**Aufwand:** mittel
|
||||
**Risiko:** mittel (Default für bestehende Listen = `agent`)
|
||||
|
||||
### 8. Subtask-Tree im TaskList-Island (ex 2026-04-16 spec)
|
||||
**Soll:** Indented Subtasks unter Parent-Task, Expand/Collapse, Chevron-Spalte, Count-Indikator. Batch-Query `GetCountsByTaskIdsAsync`.
|
||||
**Dateien:** `ViewModels/TaskItemViewModel.cs` (+ `Subtasks`, `IsExpanded`, `HasSubtasks`), `Views/Islands/TaskListView.axaml`, `Data/Repositories/SubtaskRepository.cs`
|
||||
**Aufwand:** mittel
|
||||
**Risiko:** klein–mittel (spec ist fertig)
|
||||
|
||||
### 9. Tag-Repository `GetAllKnownTagsAsync` (ex IP-8)
|
||||
**Soll:** Distinct-Query über alle Tags. Voraussetzung für #10.
|
||||
**Dateien:** neuer `Data/Repositories/TagRepository.cs` (oder in bestehendem Repo)
|
||||
**Aufwand:** klein
|
||||
**Risiko:** klein
|
||||
|
||||
### 10. Tag Multi-Select Control (ex IP-4)
|
||||
**Soll:** AutoCompleteBox / Chips statt Freitext. Datenquelle aus #9.
|
||||
**Dateien:** `Views/Islands/DetailsIslandView.axaml` (Tag-Sektion), ggf. neues `TagPickerControl`
|
||||
**Aufwand:** klein–mittel
|
||||
**Risiko:** klein
|
||||
|
||||
### 11. Worktree-Cleanup bei Anlegefehler (ex open.md 3.2)
|
||||
**Soll:** Wenn `git worktree add` teilweise anlegt dann failed → best-effort `git worktree remove --force` + DB-Row nicht persistieren.
|
||||
**Dateien:** `src/ClaudeDo.Data/Services/GitService.cs`, `src/ClaudeDo.Worker/Runner/TaskRunner.cs`
|
||||
**Aufwand:** klein
|
||||
**Risiko:** klein
|
||||
|
||||
### 12. Tag-Negation / Exclusion (ex open.md 3.4)
|
||||
**Soll:** Queue respektiert `task_tag_exclusions` laut Plan. Aktuell nur `agent`-Include.
|
||||
**Dateien:** `src/ClaudeDo.Worker/Queue/QueueService.cs`
|
||||
**Aufwand:** klein
|
||||
**Risiko:** klein
|
||||
|
||||
---
|
||||
|
||||
## P3 — Tests, CI, Docs
|
||||
|
||||
### 13. Gitea-Actions CI Pipeline (ex open.md 5.1)
|
||||
**Soll:** `.gitea/workflows/ci.yml`: restore → build → test auf push/PR. Nur `release.yml` existiert bisher.
|
||||
**Dateien:** neu — `.gitea/workflows/ci.yml`
|
||||
**Aufwand:** klein
|
||||
**Risiko:** klein
|
||||
|
||||
### 14. SignalR Roundtrip-Test (ex open.md 5.2)
|
||||
**Soll:** `WebApplicationFactory` + `HubConnectionBuilder` testen `Ping`, `GetActive`, `RunNow`-Throw-Verhalten.
|
||||
**Dateien:** neu — `tests/ClaudeDo.Worker.Tests/Hub/WorkerHubTests.cs`
|
||||
**Aufwand:** mittel
|
||||
**Risiko:** klein
|
||||
|
||||
### 15. Claude-CLI Smoke-Test (ex open.md 5.3)
|
||||
**Soll:** `[Fact(Skip=...)]` Real-CLI-Test, aktiviert nur wenn `CLAUDE_AUTHENTICATED=1`.
|
||||
**Dateien:** neu — `tests/ClaudeDo.Worker.Tests/Runner/ClaudeProcessSmokeTest.cs`
|
||||
**Aufwand:** klein
|
||||
**Risiko:** klein
|
||||
|
||||
### 16. README ausbauen (ex open.md 6.1)
|
||||
**Soll:** Ist 107 Zeilen. Ergänzen: Screenshots, Quickstart (Worker + UI starten), Konfiguration, Troubleshooting.
|
||||
**Dateien:** `README.md`
|
||||
**Aufwand:** klein
|
||||
**Risiko:** keiner
|
||||
|
||||
### 17. `docs/architecture.md` herausziehen (ex open.md 6.2)
|
||||
**Soll:** Architektur-Sektion aus `plan.md` in eigenes Dokument.
|
||||
**Dateien:** neu — `docs/architecture.md`
|
||||
**Aufwand:** klein
|
||||
**Risiko:** keiner
|
||||
|
||||
### 18. ADRs für Kern-Entscheidungen (ex open.md 6.3)
|
||||
**Soll:** Kurze ADRs (1 Seite) für: SignalR vs. SQLite-Polling; Worktree pro Task; SignalR über Loopback ohne Auth; EF Core statt Dapper.
|
||||
**Dateien:** neu — `docs/adr/0001-*.md` … `0004-*.md`
|
||||
**Aufwand:** klein
|
||||
**Risiko:** keiner
|
||||
|
||||
### 19. Strukturiertes Logging (ex open.md 3.3)
|
||||
**Soll:** `Console.WriteLine` / manuelle Log-Zeilen durch `ILogger<T>` ersetzen. Log-Levels, Scope für TaskId.
|
||||
**Dateien:** `src/ClaudeDo.Worker/**` (query-able via `grep Console.Write`)
|
||||
**Aufwand:** mittel
|
||||
**Risiko:** klein
|
||||
|
||||
---
|
||||
|
||||
## P4 — Service-Deployment (später)
|
||||
|
||||
### 20. Windows-Service Hosting in Code (ex open.md 4.1)
|
||||
**Soll:** `.UseWindowsService()` + `Microsoft.Extensions.Hosting.WindowsServices` Paket.
|
||||
**Aufwand:** klein
|
||||
|
||||
### 21. Absolute Pfad-Auflösung (ex open.md 4.2)
|
||||
**Soll:** Config-Pfade immer absolut auflösen (Service läuft in `C:\Windows\System32`).
|
||||
**Aufwand:** klein
|
||||
|
||||
### 22. Install-Skripte / Doku (ex open.md 4.3)
|
||||
**Soll:** `sc create` / PowerShell-Skript, Doku in README.
|
||||
**Aufwand:** klein
|
||||
|
||||
---
|
||||
|
||||
## Empfohlene Reihenfolge
|
||||
|
||||
**Block 1 — Sofortige UX-Wins (1 Session):**
|
||||
1. → 2. (Auto-Reconnect + StatusBar) — zusammenhängend, klein
|
||||
3. Folder-Picker
|
||||
5. Log Auto-Scroll
|
||||
|
||||
**Block 2 — Content-Qualität (1 Session):**
|
||||
4. Markdown-Rendering
|
||||
6. CLI-Preflight
|
||||
|
||||
**Block 3 — Daten-Features (2 Sessions):**
|
||||
7. Notes-Mode (mit Migration)
|
||||
8. Subtask-Tree
|
||||
9. → 10. Tag-Repo + Multi-Select
|
||||
|
||||
**Block 4 — Worker-Robustheit:**
|
||||
11. Worktree-Cleanup
|
||||
12. Tag-Exclusion
|
||||
19. Strukturiertes Logging
|
||||
|
||||
**Block 5 — Tests + CI + Docs:**
|
||||
13. CI Pipeline
|
||||
14. → 15. Hub-Tests + Smoke-Test
|
||||
16. → 17. → 18. README + architecture.md + ADRs
|
||||
|
||||
**Block 6 — Service-Deployment (wenn gewünscht):**
|
||||
20. → 21. → 22.
|
||||
|
||||
---
|
||||
|
||||
## Nicht im Plan
|
||||
|
||||
- Alles aus heute (2026-04-21): Stream-Formatter-Rewrite, Settings-Modal, Continue-and-Reset — sind eigene Plans.
|
||||
- UI-Rewrite-Islands, UI-Polish-Design-Parity, UX-Redesign, Worker-CLI-Modernization, EF-Core-Migration, Installer-Download-Mode, Logic-Bug-Fixes — bereits gemerged (siehe git log).
|
||||
- IP-3 (Doppelklick) und IP-5 (Kontextmenü) — vermutlich im Zuge des UI-Rewrites erledigt; falls nicht, trivial nachzuziehen.
|
||||
1223
docs/superpowers/plans/2026-04-22-agent-settings-ui.md
Normal file
1223
docs/superpowers/plans/2026-04-22-agent-settings-ui.md
Normal file
File diff suppressed because it is too large
Load Diff
1955
docs/superpowers/plans/2026-04-22-worktree-merge.md
Normal file
1955
docs/superpowers/plans/2026-04-22-worktree-merge.md
Normal file
File diff suppressed because it is too large
Load Diff
852
docs/superpowers/plans/2026-04-23-default-agents.md
Normal file
852
docs/superpowers/plans/2026-04-23-default-agents.md
Normal file
@@ -0,0 +1,852 @@
|
||||
# Default Agents Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Ship ClaudeDo with 6 default agents (code-reviewer, test-writer, debugger, security-reviewer, explorer, researcher) that seed into `~/.todo-app/agents/` on first launch, with a "Restore defaults" button in the settings modal.
|
||||
|
||||
**Architecture:** Bundled `.md` files in `src/ClaudeDo.Worker/DefaultAgents/` are copied to the Worker output folder. A new `DefaultAgentSeeder` service copies any missing file into the user's agents dir — run once at startup, and again on demand via a new `WorkerHub.RestoreDefaultAgents` method invoked by a button in `SettingsModalView`.
|
||||
|
||||
**Tech Stack:** .NET 8 / ASP.NET Core / SignalR / Avalonia 12 / CommunityToolkit.Mvvm / xUnit
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
**Create:**
|
||||
- `src/ClaudeDo.Worker/DefaultAgents/code-reviewer.md`
|
||||
- `src/ClaudeDo.Worker/DefaultAgents/test-writer.md`
|
||||
- `src/ClaudeDo.Worker/DefaultAgents/debugger.md`
|
||||
- `src/ClaudeDo.Worker/DefaultAgents/security-reviewer.md`
|
||||
- `src/ClaudeDo.Worker/DefaultAgents/explorer.md`
|
||||
- `src/ClaudeDo.Worker/DefaultAgents/researcher.md`
|
||||
- `src/ClaudeDo.Worker/Services/DefaultAgentSeeder.cs`
|
||||
- `tests/ClaudeDo.Worker.Tests/Services/DefaultAgentSeederTests.cs`
|
||||
|
||||
**Modify:**
|
||||
- `src/ClaudeDo.Worker/ClaudeDo.Worker.csproj` — add Content item group for `DefaultAgents\*.md`
|
||||
- `src/ClaudeDo.Worker/Program.cs` — register seeder, run `SeedMissingAsync()` once at startup
|
||||
- `src/ClaudeDo.Worker/Hub/WorkerHub.cs` — inject `DefaultAgentSeeder`, add `RestoreDefaultAgents` method
|
||||
- `src/ClaudeDo.Ui/Services/WorkerClient.cs` — add `RestoreDefaultAgentsAsync` method + `SeedResultDto` record
|
||||
- `src/ClaudeDo.Ui/ViewModels/Modals/SettingsModalViewModel.cs` — add `RestoreDefaultAgentsCommand`
|
||||
- `src/ClaudeDo.Ui/Views/Modals/SettingsModalView.axaml` — add button section
|
||||
- `tests/ClaudeDo.Worker.Tests/Hub/AgentSettingsHubTests.cs` — add seeder integration test
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Bundle default agent markdown files
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ClaudeDo.Worker/DefaultAgents/code-reviewer.md`
|
||||
- Create: `src/ClaudeDo.Worker/DefaultAgents/test-writer.md`
|
||||
- Create: `src/ClaudeDo.Worker/DefaultAgents/debugger.md`
|
||||
- Create: `src/ClaudeDo.Worker/DefaultAgents/security-reviewer.md`
|
||||
- Create: `src/ClaudeDo.Worker/DefaultAgents/explorer.md`
|
||||
- Create: `src/ClaudeDo.Worker/DefaultAgents/researcher.md`
|
||||
|
||||
- [ ] **Step 1: Write `code-reviewer.md`**
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: code-reviewer
|
||||
description: Reviews code changes for bugs, logic errors, and convention violations. Flags only high-confidence issues.
|
||||
---
|
||||
|
||||
You are a code reviewer. Your job is to inspect the diff for real problems, not nitpicks.
|
||||
|
||||
Focus on:
|
||||
- Logic errors, off-by-one bugs, null/empty handling
|
||||
- Broken invariants, race conditions, resource leaks
|
||||
- Violations of the project's established conventions (read nearby code first)
|
||||
- Missing error handling at system boundaries (external input, IO, network)
|
||||
|
||||
Skip:
|
||||
- Style preferences the codebase doesn't enforce
|
||||
- Speculative "what if" concerns
|
||||
- Renaming for its own sake
|
||||
|
||||
Output: a short list of concrete issues with file:line references. If the diff is clean, say so in one sentence. Do not rewrite the code — call out the problem and let the implementer fix it.
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Write `test-writer.md`**
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: test-writer
|
||||
description: Generates unit and integration tests for existing or new code. Follows the project's test patterns and frameworks.
|
||||
---
|
||||
|
||||
You are a test-writer. Your job is to write focused, useful tests for code under review.
|
||||
|
||||
Process:
|
||||
1. Read the target code and identify the observable behavior.
|
||||
2. Read existing tests nearby to match the framework, fixtures, naming, and assertion style.
|
||||
3. Write tests covering the happy path, boundary conditions, and the specific failure modes that matter.
|
||||
|
||||
Rules:
|
||||
- One behavior per test. Clear Arrange/Act/Assert.
|
||||
- No tests for private implementation details — exercise public API.
|
||||
- No mocks where real objects are cheap (in-memory DBs, temp dirs).
|
||||
- Skip trivially-correct tests (getter returns what you set).
|
||||
|
||||
Output: the test file(s) ready to compile, matching the project's conventions. Include the command to run them.
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Write `debugger.md`**
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: debugger
|
||||
description: Systematic root-cause analysis for bugs, test failures, and unexpected behavior. Hypothesize, isolate, verify.
|
||||
---
|
||||
|
||||
You are a debugger. You do NOT guess at fixes — you find the root cause first.
|
||||
|
||||
Process:
|
||||
1. Reproduce. Get a minimal, deterministic repro. If you can't reproduce it, say so and stop.
|
||||
2. Isolate. Narrow the failing path (bisect, binary search, or tracing).
|
||||
3. Hypothesize. State a specific, falsifiable cause.
|
||||
4. Verify. Prove the hypothesis by observation (logs, debugger, targeted print) — not by "this seems likely".
|
||||
5. Fix at the root, not the symptom. If the only fix is a workaround, explain why.
|
||||
|
||||
Anti-patterns to avoid:
|
||||
- Making changes to "see if it works"
|
||||
- Adding try/catch to silence errors
|
||||
- Declaring the bug fixed without reproducing the fix
|
||||
|
||||
Output: repro steps, root cause, and the minimal fix. Include evidence (log excerpt, command output) that proves the cause.
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Write `security-reviewer.md`**
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: security-reviewer
|
||||
description: Audits code for OWASP-class security issues — auth, injection, input handling, secret exposure.
|
||||
---
|
||||
|
||||
You are a security reviewer. Focus on real, exploitable weaknesses — not theoretical hardening.
|
||||
|
||||
Check for:
|
||||
- Injection: SQL, command, path traversal, XSS, template injection
|
||||
- Auth: missing authorization, token handling, session fixation
|
||||
- Input validation at system boundaries (HTTP, files, IPC)
|
||||
- Secrets: hardcoded credentials, tokens in logs, leaked env vars
|
||||
- Unsafe deserialization, XXE, SSRF
|
||||
- Cryptography misuse (custom crypto, weak algorithms, fixed IVs)
|
||||
|
||||
Ignore:
|
||||
- Internal trust-boundary assumptions the project already documents
|
||||
- Defense-in-depth ideas with no concrete attack path
|
||||
|
||||
Output: a prioritized list — severity, file:line, the exploit path, the fix. If nothing is wrong, say so plainly.
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Write `explorer.md`**
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: explorer
|
||||
description: Fast codebase navigation — find files, search for patterns, answer "where/how" questions. Terse output.
|
||||
---
|
||||
|
||||
You are an explorer. Your job is to find things in the codebase quickly and report back concisely.
|
||||
|
||||
Use:
|
||||
- Glob/Grep for searches
|
||||
- Read only for files you need to quote from
|
||||
|
||||
Do NOT:
|
||||
- Refactor, edit, or "improve" anything
|
||||
- Read files that aren't relevant to the question
|
||||
- Dump raw tool output — summarize
|
||||
|
||||
Output style:
|
||||
- Lead with the answer in one sentence.
|
||||
- Back it up with file:line references.
|
||||
- If you found nothing, say "no match" and what you searched for.
|
||||
|
||||
Keep responses short. The caller wants facts, not prose.
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Write `researcher.md`**
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: researcher
|
||||
description: General-purpose research and analysis for non-code tasks — summarize docs, investigate questions, draft prose.
|
||||
---
|
||||
|
||||
You are a researcher. You handle tasks that don't fit the code-review/test/debug shape.
|
||||
|
||||
Good fits:
|
||||
- Summarizing documents, specs, or long outputs
|
||||
- Investigating an open question (what does X do, how does Y work, what are the tradeoffs)
|
||||
- Drafting non-code text (release notes, emails, docs)
|
||||
- Analyzing structured data (logs, CSV, JSON) and reporting findings
|
||||
|
||||
Process:
|
||||
1. Restate the task in one sentence so you know what "done" looks like.
|
||||
2. Gather just enough information — stop when you can answer, not when you run out of sources.
|
||||
3. Distinguish facts ("the file says X") from inference ("so likely Y").
|
||||
4. Cite sources (file:line, URL, log excerpt) for every claim.
|
||||
|
||||
Output: direct answer first, supporting evidence second. Keep it short unless asked for depth.
|
||||
```
|
||||
|
||||
- [ ] **Step 7: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Worker/DefaultAgents/
|
||||
git commit -m "feat(worker): add bundled default agent definitions"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Wire bundled agents into build output
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Worker/ClaudeDo.Worker.csproj`
|
||||
|
||||
- [ ] **Step 1: Add Content item group for DefaultAgents**
|
||||
|
||||
Edit `src/ClaudeDo.Worker/ClaudeDo.Worker.csproj`. After the existing `<ItemGroup>` blocks and before the final `<PropertyGroup>`, add:
|
||||
|
||||
```xml
|
||||
<ItemGroup>
|
||||
<Content Include="DefaultAgents\*.md">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Build the worker and verify the files land in output**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Worker/ClaudeDo.Worker.csproj`
|
||||
Expected: build succeeds.
|
||||
|
||||
Then verify output:
|
||||
|
||||
Run: `ls src/ClaudeDo.Worker/bin/Debug/net8.0/DefaultAgents/`
|
||||
Expected: all 6 `.md` files present.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Worker/ClaudeDo.Worker.csproj
|
||||
git commit -m "build(worker): ship DefaultAgents folder in build output"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Write DefaultAgentSeeder tests (failing)
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/ClaudeDo.Worker.Tests/Services/DefaultAgentSeederTests.cs`
|
||||
|
||||
The service doesn't exist yet — these tests will fail to compile initially. That's fine; the next task implements it.
|
||||
|
||||
- [ ] **Step 1: Write the test file**
|
||||
|
||||
Create `tests/ClaudeDo.Worker.Tests/Services/DefaultAgentSeederTests.cs`:
|
||||
|
||||
```csharp
|
||||
using ClaudeDo.Worker.Services;
|
||||
|
||||
namespace ClaudeDo.Worker.Tests.Services;
|
||||
|
||||
public sealed class DefaultAgentSeederTests : IDisposable
|
||||
{
|
||||
private readonly string _bundleDir;
|
||||
private readonly string _targetDir;
|
||||
|
||||
public DefaultAgentSeederTests()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), $"claudedo_seeder_{Guid.NewGuid():N}");
|
||||
_bundleDir = Path.Combine(root, "bundle");
|
||||
_targetDir = Path.Combine(root, "target");
|
||||
Directory.CreateDirectory(_bundleDir);
|
||||
Directory.CreateDirectory(_targetDir);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Directory.Delete(Path.GetDirectoryName(_bundleDir)!, true); } catch { }
|
||||
}
|
||||
|
||||
private async Task WriteBundleAsync(string name, string content)
|
||||
{
|
||||
await File.WriteAllTextAsync(Path.Combine(_bundleDir, name), content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeedMissing_CopiesAllFiles_WhenTargetEmpty()
|
||||
{
|
||||
await WriteBundleAsync("a.md", "A");
|
||||
await WriteBundleAsync("b.md", "B");
|
||||
var seeder = new DefaultAgentSeeder(_bundleDir, _targetDir);
|
||||
|
||||
var result = await seeder.SeedMissingAsync();
|
||||
|
||||
Assert.Equal(2, result.Copied);
|
||||
Assert.Equal(0, result.Skipped);
|
||||
Assert.True(File.Exists(Path.Combine(_targetDir, "a.md")));
|
||||
Assert.True(File.Exists(Path.Combine(_targetDir, "b.md")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeedMissing_SkipsExistingFiles()
|
||||
{
|
||||
await WriteBundleAsync("a.md", "bundled");
|
||||
await File.WriteAllTextAsync(Path.Combine(_targetDir, "a.md"), "user-modified");
|
||||
var seeder = new DefaultAgentSeeder(_bundleDir, _targetDir);
|
||||
|
||||
var result = await seeder.SeedMissingAsync();
|
||||
|
||||
Assert.Equal(0, result.Copied);
|
||||
Assert.Equal(1, result.Skipped);
|
||||
var content = await File.ReadAllTextAsync(Path.Combine(_targetDir, "a.md"));
|
||||
Assert.Equal("user-modified", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeedMissing_MixedState_CopiesOnlyMissing()
|
||||
{
|
||||
await WriteBundleAsync("a.md", "A");
|
||||
await WriteBundleAsync("b.md", "B");
|
||||
await File.WriteAllTextAsync(Path.Combine(_targetDir, "a.md"), "existing");
|
||||
var seeder = new DefaultAgentSeeder(_bundleDir, _targetDir);
|
||||
|
||||
var result = await seeder.SeedMissingAsync();
|
||||
|
||||
Assert.Equal(1, result.Copied);
|
||||
Assert.Equal(1, result.Skipped);
|
||||
Assert.Equal("existing", await File.ReadAllTextAsync(Path.Combine(_targetDir, "a.md")));
|
||||
Assert.Equal("B", await File.ReadAllTextAsync(Path.Combine(_targetDir, "b.md")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeedMissing_ReturnsZero_WhenBundleDirMissing()
|
||||
{
|
||||
var missingBundle = Path.Combine(Path.GetTempPath(), $"claudedo_missing_{Guid.NewGuid():N}");
|
||||
var seeder = new DefaultAgentSeeder(missingBundle, _targetDir);
|
||||
|
||||
var result = await seeder.SeedMissingAsync();
|
||||
|
||||
Assert.Equal(0, result.Copied);
|
||||
Assert.Equal(0, result.Skipped);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeedMissing_CreatesTargetDir_IfMissing()
|
||||
{
|
||||
await WriteBundleAsync("a.md", "A");
|
||||
var missingTarget = Path.Combine(_targetDir, "nested", "created");
|
||||
var seeder = new DefaultAgentSeeder(_bundleDir, missingTarget);
|
||||
|
||||
var result = await seeder.SeedMissingAsync();
|
||||
|
||||
Assert.Equal(1, result.Copied);
|
||||
Assert.True(File.Exists(Path.Combine(missingTarget, "a.md")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeedMissing_IgnoresNonMarkdownFiles()
|
||||
{
|
||||
await WriteBundleAsync("a.md", "A");
|
||||
await File.WriteAllTextAsync(Path.Combine(_bundleDir, "readme.txt"), "not an agent");
|
||||
var seeder = new DefaultAgentSeeder(_bundleDir, _targetDir);
|
||||
|
||||
var result = await seeder.SeedMissingAsync();
|
||||
|
||||
Assert.Equal(1, result.Copied);
|
||||
Assert.False(File.Exists(Path.Combine(_targetDir, "readme.txt")));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests to confirm they fail to compile**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests --filter "FullyQualifiedName~DefaultAgentSeederTests"`
|
||||
Expected: compile error — `The type or namespace name 'DefaultAgentSeeder' could not be found`.
|
||||
|
||||
This confirms the tests target the not-yet-written service.
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Implement DefaultAgentSeeder
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ClaudeDo.Worker/Services/DefaultAgentSeeder.cs`
|
||||
|
||||
- [ ] **Step 1: Write the service**
|
||||
|
||||
Create `src/ClaudeDo.Worker/Services/DefaultAgentSeeder.cs`:
|
||||
|
||||
```csharp
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace ClaudeDo.Worker.Services;
|
||||
|
||||
public sealed record SeedResult(int Copied, int Skipped);
|
||||
|
||||
public sealed class DefaultAgentSeeder
|
||||
{
|
||||
private readonly string _bundleDir;
|
||||
private readonly string _targetDir;
|
||||
private readonly ILogger<DefaultAgentSeeder>? _logger;
|
||||
|
||||
public DefaultAgentSeeder(string bundleDir, string targetDir, ILogger<DefaultAgentSeeder>? logger = null)
|
||||
{
|
||||
_bundleDir = bundleDir;
|
||||
_targetDir = targetDir;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<SeedResult> SeedMissingAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (!Directory.Exists(_bundleDir))
|
||||
{
|
||||
_logger?.LogWarning("DefaultAgents bundle dir not found: {Dir}", _bundleDir);
|
||||
return new SeedResult(0, 0);
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(_targetDir);
|
||||
|
||||
int copied = 0;
|
||||
int skipped = 0;
|
||||
|
||||
foreach (var src in Directory.EnumerateFiles(_bundleDir, "*.md"))
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var fileName = Path.GetFileName(src);
|
||||
var dst = Path.Combine(_targetDir, fileName);
|
||||
|
||||
if (File.Exists(dst))
|
||||
{
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var input = File.OpenRead(src);
|
||||
using var output = File.Create(dst);
|
||||
await input.CopyToAsync(output, ct);
|
||||
copied++;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger?.LogWarning(ex, "Failed to copy default agent {File}", fileName);
|
||||
}
|
||||
}
|
||||
|
||||
return new SeedResult(copied, skipped);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the tests and verify they pass**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests --filter "FullyQualifiedName~DefaultAgentSeederTests"`
|
||||
Expected: 6 tests pass.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Worker/Services/DefaultAgentSeeder.cs tests/ClaudeDo.Worker.Tests/Services/DefaultAgentSeederTests.cs
|
||||
git commit -m "feat(worker): add DefaultAgentSeeder for first-launch agent seeding"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Wire seeder into Worker startup
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Worker/Program.cs`
|
||||
|
||||
- [ ] **Step 1: Register seeder and run SeedMissingAsync at startup**
|
||||
|
||||
In `src/ClaudeDo.Worker/Program.cs`, replace the "Agent file management." block (currently lines 36–39):
|
||||
|
||||
Find:
|
||||
```csharp
|
||||
// Agent file management.
|
||||
var agentsDir = Path.Combine(ClaudeDo.Data.Paths.AppDataRoot(), "agents");
|
||||
Directory.CreateDirectory(agentsDir);
|
||||
builder.Services.AddSingleton(new AgentFileService(agentsDir));
|
||||
```
|
||||
|
||||
Replace with:
|
||||
```csharp
|
||||
// Agent file management.
|
||||
var agentsDir = Path.Combine(ClaudeDo.Data.Paths.AppDataRoot(), "agents");
|
||||
Directory.CreateDirectory(agentsDir);
|
||||
builder.Services.AddSingleton(new AgentFileService(agentsDir));
|
||||
|
||||
var defaultAgentsBundleDir = Path.Combine(AppContext.BaseDirectory, "DefaultAgents");
|
||||
builder.Services.AddSingleton(sp => new DefaultAgentSeeder(
|
||||
defaultAgentsBundleDir,
|
||||
agentsDir,
|
||||
sp.GetService<Microsoft.Extensions.Logging.ILogger<DefaultAgentSeeder>>()));
|
||||
```
|
||||
|
||||
Then, after `var app = builder.Build();` and before `app.MapHub<WorkerHub>("/hub");`, add:
|
||||
|
||||
Find:
|
||||
```csharp
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
ClaudeDoDbContext.MigrateAndConfigure(
|
||||
scope.ServiceProvider.GetRequiredService<ClaudeDoDbContext>());
|
||||
}
|
||||
|
||||
app.MapHub<WorkerHub>("/hub");
|
||||
```
|
||||
|
||||
Replace with:
|
||||
```csharp
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
ClaudeDoDbContext.MigrateAndConfigure(
|
||||
scope.ServiceProvider.GetRequiredService<ClaudeDoDbContext>());
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var seeder = app.Services.GetRequiredService<DefaultAgentSeeder>();
|
||||
var seedResult = await seeder.SeedMissingAsync();
|
||||
app.Logger.LogInformation(
|
||||
"Default agents seeded: {Copied} copied, {Skipped} already present",
|
||||
seedResult.Copied, seedResult.Skipped);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
app.Logger.LogWarning(ex, "Default agent seeding failed");
|
||||
}
|
||||
|
||||
app.MapHub<WorkerHub>("/hub");
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Build worker to verify compile**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Worker/ClaudeDo.Worker.csproj`
|
||||
Expected: build succeeds.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Worker/Program.cs
|
||||
git commit -m "feat(worker): seed default agents on startup"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Add RestoreDefaultAgents hub method (TDD)
|
||||
|
||||
**Files:**
|
||||
- Modify: `tests/ClaudeDo.Worker.Tests/Hub/AgentSettingsHubTests.cs`
|
||||
- Modify: `src/ClaudeDo.Worker/Hub/WorkerHub.cs`
|
||||
|
||||
The existing `AgentSettingsHubTests` doesn't exercise `WorkerHub` directly (it tests the repository). We'll add a new test file that tests the seeder restore flow end-to-end without SignalR plumbing — constructing the seeder with temp dirs and asserting the `SeedResult` round-trip. This mirrors how the file is structured today and keeps tests simple.
|
||||
|
||||
- [ ] **Step 1: Add a restore test**
|
||||
|
||||
Add to `tests/ClaudeDo.Worker.Tests/Hub/AgentSettingsHubTests.cs`. Inside the existing `AgentSettingsHubTests` class (before the closing brace), add:
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public async Task RestoreDefaultAgents_CopiesMissingBundledFiles()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), $"claudedo_hub_restore_{Guid.NewGuid():N}");
|
||||
var bundleDir = Path.Combine(root, "bundle");
|
||||
var targetDir = Path.Combine(root, "target");
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(bundleDir);
|
||||
Directory.CreateDirectory(targetDir);
|
||||
await File.WriteAllTextAsync(Path.Combine(bundleDir, "code-reviewer.md"), "body");
|
||||
|
||||
var seeder = new ClaudeDo.Worker.Services.DefaultAgentSeeder(bundleDir, targetDir);
|
||||
var result = await seeder.SeedMissingAsync();
|
||||
|
||||
Assert.Equal(1, result.Copied);
|
||||
Assert.Equal(0, result.Skipped);
|
||||
Assert.True(File.Exists(Path.Combine(targetDir, "code-reviewer.md")));
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(root, true); } catch { }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test to confirm it passes (seeder already exists)**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests --filter "FullyQualifiedName~AgentSettingsHubTests.RestoreDefaultAgents_CopiesMissingBundledFiles"`
|
||||
Expected: 1 test passes.
|
||||
|
||||
- [ ] **Step 3: Add RestoreDefaultAgents to WorkerHub**
|
||||
|
||||
Edit `src/ClaudeDo.Worker/Hub/WorkerHub.cs`.
|
||||
|
||||
Add a new DTO record near the top with the other DTOs (after the `ListConfigDto` line on line 30):
|
||||
|
||||
```csharp
|
||||
public record SeedResultDto(int Copied, int Skipped);
|
||||
```
|
||||
|
||||
Update the class field block. Find:
|
||||
```csharp
|
||||
private readonly QueueService _queue;
|
||||
private readonly AgentFileService _agentService;
|
||||
private readonly HubBroadcaster _broadcaster;
|
||||
private readonly IDbContextFactory<ClaudeDoDbContext> _dbFactory;
|
||||
private readonly WorktreeMaintenanceService _wtMaintenance;
|
||||
private readonly TaskResetService _resetService;
|
||||
private readonly TaskMergeService _mergeService;
|
||||
```
|
||||
|
||||
Replace with:
|
||||
```csharp
|
||||
private readonly QueueService _queue;
|
||||
private readonly AgentFileService _agentService;
|
||||
private readonly DefaultAgentSeeder _seeder;
|
||||
private readonly HubBroadcaster _broadcaster;
|
||||
private readonly IDbContextFactory<ClaudeDoDbContext> _dbFactory;
|
||||
private readonly WorktreeMaintenanceService _wtMaintenance;
|
||||
private readonly TaskResetService _resetService;
|
||||
private readonly TaskMergeService _mergeService;
|
||||
```
|
||||
|
||||
Update the constructor. Find:
|
||||
```csharp
|
||||
public WorkerHub(
|
||||
QueueService queue,
|
||||
AgentFileService agentService,
|
||||
HubBroadcaster broadcaster,
|
||||
IDbContextFactory<ClaudeDoDbContext> dbFactory,
|
||||
WorktreeMaintenanceService wtMaintenance,
|
||||
TaskResetService resetService,
|
||||
TaskMergeService mergeService)
|
||||
{
|
||||
_queue = queue;
|
||||
_agentService = agentService;
|
||||
_broadcaster = broadcaster;
|
||||
_dbFactory = dbFactory;
|
||||
_wtMaintenance = wtMaintenance;
|
||||
_resetService = resetService;
|
||||
_mergeService = mergeService;
|
||||
}
|
||||
```
|
||||
|
||||
Replace with:
|
||||
```csharp
|
||||
public WorkerHub(
|
||||
QueueService queue,
|
||||
AgentFileService agentService,
|
||||
DefaultAgentSeeder seeder,
|
||||
HubBroadcaster broadcaster,
|
||||
IDbContextFactory<ClaudeDoDbContext> dbFactory,
|
||||
WorktreeMaintenanceService wtMaintenance,
|
||||
TaskResetService resetService,
|
||||
TaskMergeService mergeService)
|
||||
{
|
||||
_queue = queue;
|
||||
_agentService = agentService;
|
||||
_seeder = seeder;
|
||||
_broadcaster = broadcaster;
|
||||
_dbFactory = dbFactory;
|
||||
_wtMaintenance = wtMaintenance;
|
||||
_resetService = resetService;
|
||||
_mergeService = mergeService;
|
||||
}
|
||||
```
|
||||
|
||||
Then add the hub method. After the existing `RefreshAgents` method (currently line 126):
|
||||
|
||||
```csharp
|
||||
public async Task<SeedResultDto> RestoreDefaultAgents()
|
||||
{
|
||||
var result = await _seeder.SeedMissingAsync();
|
||||
return new SeedResultDto(result.Copied, result.Skipped);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Build worker to verify compile**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Worker/ClaudeDo.Worker.csproj`
|
||||
Expected: build succeeds.
|
||||
|
||||
- [ ] **Step 5: Run all Worker tests to confirm no regressions**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests`
|
||||
Expected: all tests pass.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Worker/Hub/WorkerHub.cs tests/ClaudeDo.Worker.Tests/Hub/AgentSettingsHubTests.cs
|
||||
git commit -m "feat(worker): expose RestoreDefaultAgents hub method"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Add RestoreDefaultAgentsAsync to WorkerClient
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/Services/WorkerClient.cs`
|
||||
|
||||
- [ ] **Step 1: Add the DTO record**
|
||||
|
||||
At the bottom of `src/ClaudeDo.Ui/Services/WorkerClient.cs`, alongside the other public record declarations (after `ListConfigDto`, currently line 350), add:
|
||||
|
||||
```csharp
|
||||
public sealed record SeedResultDto(int Copied, int Skipped);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add the client method**
|
||||
|
||||
In the `WorkerClient` class, after the `RefreshAgentsAsync` method (currently line 232), add:
|
||||
|
||||
```csharp
|
||||
public async Task<SeedResultDto?> RestoreDefaultAgentsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _hub.InvokeAsync<SeedResultDto>("RestoreDefaultAgents");
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Build UI to verify compile**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`
|
||||
Expected: build succeeds.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/Services/WorkerClient.cs
|
||||
git commit -m "feat(ui): add RestoreDefaultAgentsAsync to WorkerClient"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Add restore button to Settings modal
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/ViewModels/Modals/SettingsModalViewModel.cs`
|
||||
- Modify: `src/ClaudeDo.Ui/Views/Modals/SettingsModalView.axaml`
|
||||
|
||||
- [ ] **Step 1: Add the command to the viewmodel**
|
||||
|
||||
In `src/ClaudeDo.Ui/ViewModels/Modals/SettingsModalViewModel.cs`, add a new command method. Place it after the existing `ConfirmResetAll` method (currently ending line 162), before the `OpenPath` method:
|
||||
|
||||
```csharp
|
||||
[RelayCommand]
|
||||
private async Task RestoreDefaultAgents()
|
||||
{
|
||||
IsBusy = true;
|
||||
StatusMessage = "";
|
||||
try
|
||||
{
|
||||
var result = await _worker.RestoreDefaultAgentsAsync();
|
||||
if (result is null)
|
||||
StatusMessage = "Worker offline.";
|
||||
else if (result.Copied == 0 && result.Skipped == 0)
|
||||
StatusMessage = "No default agents bundled.";
|
||||
else if (result.Copied == 0)
|
||||
StatusMessage = "All default agents already present.";
|
||||
else
|
||||
StatusMessage = $"Restored {result.Copied} default agent(s).";
|
||||
|
||||
await _worker.RefreshAgentsAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
StatusMessage = $"Restore failed: {ex.Message}";
|
||||
}
|
||||
finally { IsBusy = false; }
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add a button to the settings view**
|
||||
|
||||
Edit `src/ClaudeDo.Ui/Views/Modals/SettingsModalView.axaml`. Add a new section after the `WORKTREES` StackPanel block (which ends with `</StackPanel>` around line 185) and before the `ABOUT` section (`<!-- ABOUT -->` around line 187).
|
||||
|
||||
Find:
|
||||
```xml
|
||||
</StackPanel>
|
||||
|
||||
<!-- ABOUT -->
|
||||
```
|
||||
|
||||
Replace with:
|
||||
```xml
|
||||
</StackPanel>
|
||||
|
||||
<!-- AGENTS -->
|
||||
<StackPanel Spacing="0">
|
||||
<TextBlock Classes="section-label" Text="AGENTS"/>
|
||||
<Border Classes="section">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Restore bundled default agents (code-reviewer, test-writer, debugger, security-reviewer, explorer, researcher). Existing files are not overwritten."
|
||||
FontSize="11"
|
||||
TextWrapping="Wrap"
|
||||
Foreground="{DynamicResource TextDimBrush}"/>
|
||||
<Button Content="Restore default agents"
|
||||
Command="{Binding RestoreDefaultAgentsCommand}"
|
||||
IsEnabled="{Binding !IsBusy}"
|
||||
HorizontalAlignment="Left"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ABOUT -->
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Build UI to verify compile**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`
|
||||
Expected: build succeeds.
|
||||
|
||||
- [ ] **Step 4: Manual smoke test**
|
||||
|
||||
Start the worker and the UI. Open Settings (3-dots next to username). The AGENTS section should appear with a "Restore default agents" button.
|
||||
|
||||
1. With `~/.todo-app/agents/` empty (delete any existing `.md` files first, back them up if needed): click the button. Status should read "Restored N default agent(s)." The files should appear in the folder.
|
||||
2. Click again. Status should read "All default agents already present."
|
||||
3. Modify one of the restored files. Click restore. The modified file content should be preserved.
|
||||
|
||||
If any step fails, stop and fix before committing.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/ViewModels/Modals/SettingsModalViewModel.cs src/ClaudeDo.Ui/Views/Modals/SettingsModalView.axaml
|
||||
git commit -m "feat(ui): add Restore default agents button to Settings modal"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
|
||||
At the end, run the full test suite and build all projects:
|
||||
|
||||
```bash
|
||||
dotnet build src/ClaudeDo.Worker/ClaudeDo.Worker.csproj
|
||||
dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj
|
||||
dotnet build src/ClaudeDo.Data/ClaudeDo.Data.csproj
|
||||
dotnet test tests/ClaudeDo.Worker.Tests
|
||||
```
|
||||
|
||||
Expected: all builds succeed, all tests pass.
|
||||
|
||||
Additionally, start the Worker once with an empty `~/.todo-app/agents/` folder and confirm the log line:
|
||||
> `Default agents seeded: 6 copied, 0 already present`
|
||||
|
||||
Then confirm `~/.todo-app/agents/` contains all 6 markdown files.
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
927
docs/superpowers/plans/2026-04-23-planning-sessions-plan-c-ui.md
Normal file
927
docs/superpowers/plans/2026-04-23-planning-sessions-plan-c-ui.md
Normal file
@@ -0,0 +1,927 @@
|
||||
# Planning Sessions — Plan C: UI Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Wire the planning-session feature into the UI: context-menu entries, hierarchical display of parent + children, draft styling, unfinished-session dialog, and the `WorkerClient` methods that call the hub endpoints built in Plan B.
|
||||
|
||||
**Architecture:** Extend `TaskRowViewModel` with hierarchy-aware flags (`IsChild`, `IsPlanningParent`, `IsExpanded`). `TasksIslandViewModel` builds a flat stream that interleaves parents and their children based on expanded state. Context-menu entries on `TaskRowView` gate on task status. Draft styling lives in the existing island styles. A modal dialog reuses the project's `TaskCompletionSource<T>` pattern.
|
||||
|
||||
**Tech Stack:** .NET 8, Avalonia 12, CommunityToolkit.Mvvm (`[ObservableProperty]`, `[RelayCommand]`), compiled bindings, SignalR client.
|
||||
|
||||
**Spec reference:** `docs/superpowers/specs/2026-04-23-planning-sessions-design.md` section 6.
|
||||
|
||||
---
|
||||
|
||||
## Prerequisite Gate
|
||||
|
||||
This plan depends on Plan A being merged to `main`. Plan B's interface contract (hub method names, return types) is locked in the spec §6.6 and Plan B task 13 — this plan can proceed in parallel with Plan B.
|
||||
|
||||
Before starting:
|
||||
|
||||
```bash
|
||||
git fetch origin main
|
||||
git checkout main
|
||||
git pull --ff-only
|
||||
ls src/ClaudeDo.Data/Migrations/*AddPlanningSupport*.cs
|
||||
```
|
||||
|
||||
If the file is missing, wait for Plan A:
|
||||
```bash
|
||||
while ! ls src/ClaudeDo.Data/Migrations/*AddPlanningSupport*.cs >/dev/null 2>&1; do
|
||||
echo "Waiting for Plan A to merge..."
|
||||
sleep 60
|
||||
git fetch origin main && git pull --ff-only
|
||||
done
|
||||
```
|
||||
|
||||
Then branch:
|
||||
```bash
|
||||
git checkout -b feat/planning-sessions-ui
|
||||
```
|
||||
|
||||
**Parallel-with-Plan-B note:** Plan B may not yet be merged when this plan runs. The `WorkerClient` methods in Task 9 will compile against Plan B's SignalR hub method names (they're string-based SignalR invocations), so they don't have a build-time dependency. Runtime end-to-end testing requires Plan B merged; until then, mock-test what's possible and smoke-test manually once both plans land.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
**Modified:**
|
||||
- `src/ClaudeDo.Ui/ViewModels/Islands/TaskRowViewModel.cs` — add `ParentTaskId`, `IsChild`, `IsPlanningParent`, `IsExpanded`, `PlanningBadge` properties.
|
||||
- `src/ClaudeDo.Ui/ViewModels/Islands/TasksIslandViewModel.cs` — add planning commands, expanded-state map, flat-stream rebuild logic.
|
||||
- `src/ClaudeDo.Ui/Views/Islands/TaskRowView.axaml` — chevron, indentation, badges, draft styling hooks.
|
||||
- `src/ClaudeDo.Ui/Views/Islands/TaskRowView.axaml.cs` — context-menu event handlers (if code-behind is used; else inline).
|
||||
- `src/ClaudeDo.Ui/Views/Islands/TasksIslandView.axaml` — use the extended TaskRowView template.
|
||||
- `src/ClaudeDo.Ui/Services/WorkerClient.cs` — five new hub method wrappers matching Plan B.
|
||||
- `src/ClaudeDo.Ui/Design/IslandStyles.axaml` — `.draft`, `.planning-parent`, `.planned-parent`, badge styles.
|
||||
|
||||
**Created:**
|
||||
- `src/ClaudeDo.Ui/Views/Dialogs/UnfinishedPlanningDialog.axaml` + `.axaml.cs` — modal Resume/Finalize/Discard dialog.
|
||||
- `src/ClaudeDo.Ui/ViewModels/Dialogs/UnfinishedPlanningDialogViewModel.cs` — dialog VM.
|
||||
- `tests/ClaudeDo.Worker.Tests/UiVm/TasksIslandViewModelPlanningTests.cs` — VM-level tests.
|
||||
- `tests/ClaudeDo.Worker.Tests/UiVm/TaskRowViewModelPlanningTests.cs` — VM-level tests.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Extend `TaskRowViewModel`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/ViewModels/Islands/TaskRowViewModel.cs`
|
||||
- Create: `tests/ClaudeDo.Worker.Tests/UiVm/TaskRowViewModelPlanningTests.cs`
|
||||
|
||||
- [ ] **Step 1: Write failing test for planning flags**
|
||||
|
||||
Create the test file. Adapt the existing `TaskRowViewModelTests` pattern (look at `tests/ClaudeDo.Worker.Tests/UiVm/TaskRowViewModelTests.cs` for how VMs are constructed in tests):
|
||||
|
||||
```csharp
|
||||
using ClaudeDo.Ui.ViewModels.Islands;
|
||||
|
||||
namespace ClaudeDo.Worker.Tests.UiVm;
|
||||
|
||||
public sealed class TaskRowViewModelPlanningTests
|
||||
{
|
||||
[Fact]
|
||||
public void Draft_Status_SetsIsChildFlag_WhenParentIdIsNotNull()
|
||||
{
|
||||
// Adapt the constructor call to your actual TaskRowViewModel signature (see TaskRowViewModelTests).
|
||||
var vm = TestHelpers.MakeRow(
|
||||
status: "draft",
|
||||
parentTaskId: "parent-id");
|
||||
|
||||
Assert.True(vm.IsChild);
|
||||
Assert.False(vm.IsPlanningParent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Planning_Status_SetsIsPlanningParent()
|
||||
{
|
||||
var vm = TestHelpers.MakeRow(status: "planning", parentTaskId: null);
|
||||
|
||||
Assert.True(vm.IsPlanningParent);
|
||||
Assert.False(vm.IsChild);
|
||||
Assert.Equal("PLANNING", vm.PlanningBadge);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Planned_Status_ShowsPlannedBadge()
|
||||
{
|
||||
var vm = TestHelpers.MakeRow(status: "planned", parentTaskId: null);
|
||||
|
||||
Assert.True(vm.IsPlanningParent);
|
||||
Assert.Equal("PLANNED", vm.PlanningBadge);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NonPlanningStatus_NoBadge()
|
||||
{
|
||||
var vm = TestHelpers.MakeRow(status: "manual", parentTaskId: null);
|
||||
|
||||
Assert.False(vm.IsPlanningParent);
|
||||
Assert.Null(vm.PlanningBadge);
|
||||
}
|
||||
}
|
||||
|
||||
internal static class TestHelpers
|
||||
{
|
||||
public static TaskRowViewModel MakeRow(string status, string? parentTaskId)
|
||||
{
|
||||
// Implement based on actual TaskRowViewModel constructor.
|
||||
// The TaskRowViewModelTests.cs file in the same folder shows the existing pattern.
|
||||
throw new NotImplementedException("Adapt to your TaskRowViewModel constructor");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Open `tests/ClaudeDo.Worker.Tests/UiVm/TaskRowViewModelTests.cs` first to see how the VM is constructed in tests, then fill in `TestHelpers.MakeRow` accordingly.
|
||||
|
||||
- [ ] **Step 2: Run; verify fail**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests --filter "FullyQualifiedName~TaskRowViewModelPlanningTests"`
|
||||
Expected: FAIL (properties not yet on VM).
|
||||
|
||||
- [ ] **Step 3: Extend the VM**
|
||||
|
||||
In `src/ClaudeDo.Ui/ViewModels/Islands/TaskRowViewModel.cs` add the new properties using `[ObservableProperty]`:
|
||||
|
||||
```csharp
|
||||
[ObservableProperty] private string? parentTaskId;
|
||||
[ObservableProperty] private bool isExpanded = true;
|
||||
|
||||
public bool IsChild => !string.IsNullOrEmpty(ParentTaskId);
|
||||
public bool IsPlanningParent => string.Equals(Status, "planning", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(Status, "planned", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public string? PlanningBadge => Status switch
|
||||
{
|
||||
string s when string.Equals(s, "planning", StringComparison.OrdinalIgnoreCase) => "PLANNING",
|
||||
string s when string.Equals(s, "planned", StringComparison.OrdinalIgnoreCase) => "PLANNED",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
public bool IsDraft => string.Equals(Status, "draft", StringComparison.OrdinalIgnoreCase);
|
||||
```
|
||||
|
||||
Since `IsChild`, `IsPlanningParent`, `PlanningBadge`, and `IsDraft` are computed from other observables, you must raise property-changed notifications when `Status` or `ParentTaskId` changes. Use `[ObservableProperty]` partial methods:
|
||||
|
||||
```csharp
|
||||
partial void OnStatusChanged(string value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsPlanningParent));
|
||||
OnPropertyChanged(nameof(PlanningBadge));
|
||||
OnPropertyChanged(nameof(IsDraft));
|
||||
}
|
||||
|
||||
partial void OnParentTaskIdChanged(string? value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsChild));
|
||||
}
|
||||
```
|
||||
|
||||
If the existing VM already has `OnStatusChanged` (check for generator outputs), merge into it rather than duplicating.
|
||||
|
||||
- [ ] **Step 4: Run; verify pass**
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/ViewModels/Islands/TaskRowViewModel.cs tests/ClaudeDo.Worker.Tests/UiVm/TaskRowViewModelPlanningTests.cs
|
||||
git commit -m "feat(ui): TaskRowViewModel gains planning hierarchy flags"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: `WorkerClient` planning methods
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/Services/WorkerClient.cs`
|
||||
- Create: DTOs matching Plan B return types (either inline in the client file or new file `src/ClaudeDo.Ui/Services/PlanningDtos.cs`).
|
||||
|
||||
- [ ] **Step 1: Add DTOs**
|
||||
|
||||
Create `src/ClaudeDo.Ui/Services/PlanningDtos.cs`:
|
||||
|
||||
```csharp
|
||||
namespace ClaudeDo.Ui.Services;
|
||||
|
||||
public sealed record PlanningSessionFilesDto(
|
||||
string SessionDirectory,
|
||||
string McpConfigPath,
|
||||
string SystemPromptPath,
|
||||
string InitialPromptPath);
|
||||
|
||||
public sealed record PlanningSessionStartInfo(
|
||||
string ParentTaskId,
|
||||
string WorkingDir,
|
||||
PlanningSessionFilesDto Files);
|
||||
|
||||
public sealed record PlanningSessionResumeInfo(
|
||||
string ParentTaskId,
|
||||
string WorkingDir,
|
||||
string ClaudeSessionId,
|
||||
string McpConfigPath);
|
||||
```
|
||||
|
||||
These field names must match Plan B's `PlanningSessionStartContext` / `PlanningSessionResumeContext` exactly (case-sensitive JSON deserialization through SignalR).
|
||||
|
||||
- [ ] **Step 2: Add `WorkerClient` methods**
|
||||
|
||||
In `src/ClaudeDo.Ui/Services/WorkerClient.cs`, add:
|
||||
|
||||
```csharp
|
||||
public Task<PlanningSessionStartInfo> StartPlanningSessionAsync(string taskId, CancellationToken ct = default)
|
||||
=> _connection.InvokeAsync<PlanningSessionStartInfo>("StartPlanningSessionAsync", taskId, ct);
|
||||
|
||||
public Task<PlanningSessionResumeInfo> ResumePlanningSessionAsync(string taskId, CancellationToken ct = default)
|
||||
=> _connection.InvokeAsync<PlanningSessionResumeInfo>("ResumePlanningSessionAsync", taskId, ct);
|
||||
|
||||
public Task DiscardPlanningSessionAsync(string taskId, CancellationToken ct = default)
|
||||
=> _connection.InvokeAsync("DiscardPlanningSessionAsync", taskId, ct);
|
||||
|
||||
public Task<int> FinalizePlanningSessionAsync(string taskId, bool queueAgentTasks = true, CancellationToken ct = default)
|
||||
=> _connection.InvokeAsync<int>("FinalizePlanningSessionAsync", taskId, queueAgentTasks, ct);
|
||||
|
||||
public Task<int> GetPendingDraftCountAsync(string taskId, CancellationToken ct = default)
|
||||
=> _connection.InvokeAsync<int>("GetPendingDraftCountAsync", taskId, ct);
|
||||
```
|
||||
|
||||
Replace `_connection` with whatever name the existing `WorkerClient` uses for its `HubConnection` field.
|
||||
|
||||
- [ ] **Step 3: Build**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`
|
||||
Expected: builds.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/Services/PlanningDtos.cs src/ClaudeDo.Ui/Services/WorkerClient.cs
|
||||
git commit -m "feat(ui): WorkerClient planning-session methods"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: `TasksIslandViewModel` — planning commands + expanded state
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/ViewModels/Islands/TasksIslandViewModel.cs`
|
||||
- Create: `tests/ClaudeDo.Worker.Tests/UiVm/TasksIslandViewModelPlanningTests.cs`
|
||||
|
||||
- [ ] **Step 1: Add commands to the VM**
|
||||
|
||||
In `TasksIslandViewModel.cs`, add:
|
||||
|
||||
```csharp
|
||||
private readonly Dictionary<string, bool> _expandedState = new();
|
||||
|
||||
[RelayCommand]
|
||||
private async Task OpenPlanningSessionAsync(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null || !string.Equals(row.Status, "manual", StringComparison.OrdinalIgnoreCase))
|
||||
return;
|
||||
try
|
||||
{
|
||||
await _workerClient.StartPlanningSessionAsync(row.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _dialogs.ShowErrorAsync("Could not start planning session", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task ResumePlanningSessionAsync(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null || !row.IsPlanningParent) return;
|
||||
try
|
||||
{
|
||||
await _workerClient.ResumePlanningSessionAsync(row.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _dialogs.ShowErrorAsync("Could not resume planning session", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task DiscardPlanningSessionAsync(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null) return;
|
||||
var confirm = await _dialogs.ConfirmAsync(
|
||||
"Discard planning session?",
|
||||
"This will delete all draft tasks and reset the parent to Manual.");
|
||||
if (!confirm) return;
|
||||
await _workerClient.DiscardPlanningSessionAsync(row.Id);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task FinalizePlanningSessionAsync(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null) return;
|
||||
await _workerClient.FinalizePlanningSessionAsync(row.Id, queueAgentTasks: true);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void ToggleExpand(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null) return;
|
||||
var next = !(_expandedState.TryGetValue(row.Id, out var current) ? current : true);
|
||||
_expandedState[row.Id] = next;
|
||||
row.IsExpanded = next;
|
||||
RebuildFlatStreams();
|
||||
}
|
||||
|
||||
private void RebuildFlatStreams()
|
||||
{
|
||||
// Existing code builds OpenItems/CompletedItems from the task list.
|
||||
// Modify it so that: after emitting a parent, if IsPlanningParent && IsExpanded,
|
||||
// its Draft / Manual / Queued / Running / Done children are emitted next.
|
||||
// Children already know they are children (ParentTaskId != null) and are styled as such.
|
||||
}
|
||||
```
|
||||
|
||||
The existing `RebuildFlatStreams` (or equivalent) probably just groups tasks by status. You need to intersperse the hierarchy:
|
||||
|
||||
```csharp
|
||||
// Pseudocode — fit to the existing code shape.
|
||||
var topLevel = allRows.Where(r => !r.IsChild).OrderBy(r => r.SortOrder);
|
||||
var flat = new List<TaskRowViewModel>();
|
||||
foreach (var parent in topLevel)
|
||||
{
|
||||
flat.Add(parent);
|
||||
if (parent.IsPlanningParent && parent.IsExpanded)
|
||||
{
|
||||
var children = allRows
|
||||
.Where(r => r.ParentTaskId == parent.Id)
|
||||
.OrderBy(r => r.SortOrder)
|
||||
.ToList();
|
||||
flat.AddRange(children);
|
||||
}
|
||||
}
|
||||
// Then bucket `flat` into OpenItems/CompletedItems like today, preserving order.
|
||||
```
|
||||
|
||||
Pass dependencies: the VM already has a `WorkerClient` or equivalent — reuse it. Add a dialog service if not already injected:
|
||||
|
||||
```csharp
|
||||
public interface IDialogService
|
||||
{
|
||||
Task<bool> ConfirmAsync(string title, string message);
|
||||
Task ShowErrorAsync(string title, string message);
|
||||
}
|
||||
```
|
||||
|
||||
If an analog already exists (check existing editor dialogs), use it.
|
||||
|
||||
- [ ] **Step 2: Write failing VM tests**
|
||||
|
||||
`tests/ClaudeDo.Worker.Tests/UiVm/TasksIslandViewModelPlanningTests.cs`:
|
||||
|
||||
```csharp
|
||||
using ClaudeDo.Ui.ViewModels.Islands;
|
||||
|
||||
namespace ClaudeDo.Worker.Tests.UiVm;
|
||||
|
||||
public sealed class TasksIslandViewModelPlanningTests
|
||||
{
|
||||
[Fact]
|
||||
public void ToggleExpand_CollapsesChildrenOfPlanningParent()
|
||||
{
|
||||
// Arrange: create VM with one Planning parent and two Draft children.
|
||||
// Act: call ToggleExpandCommand with the parent.
|
||||
// Assert: flat stream no longer contains the children.
|
||||
// Adapt to how the existing TasksIslandViewModel is instantiated.
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OpenPlanningSessionCommand_ManualTaskOnly_CanExecuteTrue()
|
||||
{
|
||||
// Arrange VM with a Manual row.
|
||||
// Assert CanExecute for OpenPlanningSession command is true for Manual rows,
|
||||
// false for Queued/Running/Done/Failed rows.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
These are skeleton tests — implement with the same construction pattern used by the existing `TasksIslandViewModelTests` if one exists, or build a minimal VM fake with a stub `WorkerClient`.
|
||||
|
||||
- [ ] **Step 3: Build + test**
|
||||
|
||||
Run:
|
||||
```bash
|
||||
dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj
|
||||
dotnet test tests/ClaudeDo.Worker.Tests --filter "FullyQualifiedName~TasksIslandViewModelPlanningTests"
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/ViewModels/Islands/TasksIslandViewModel.cs tests/ClaudeDo.Worker.Tests/UiVm/TasksIslandViewModelPlanningTests.cs
|
||||
git commit -m "feat(ui): planning commands and expand/collapse in TasksIslandViewModel"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: `TaskRowView` — indent, chevron, badges, draft styling
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/Views/Islands/TaskRowView.axaml`
|
||||
|
||||
- [ ] **Step 1: Wrap the row content with a Grid that has an indent column**
|
||||
|
||||
Open `TaskRowView.axaml`. The existing root is likely a `Grid` or `Border`. Replace/refactor the top-level layout to:
|
||||
|
||||
```xml
|
||||
<Grid ColumnDefinitions="Auto,*">
|
||||
<Border Grid.Column="0"
|
||||
Width="24"
|
||||
IsVisible="{Binding IsChild}">
|
||||
<Rectangle Width="1" Fill="{DynamicResource TextFaintBrush}" HorizontalAlignment="Right" Margin="0,4"/>
|
||||
</Border>
|
||||
|
||||
<Grid Grid.Column="1" ColumnDefinitions="Auto,*,Auto">
|
||||
<!-- Chevron for planning parents -->
|
||||
<Button Grid.Column="0"
|
||||
Classes="icon-btn chevron"
|
||||
Width="18" Height="18"
|
||||
IsVisible="{Binding IsPlanningParent}"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).ToggleExpandCommand}"
|
||||
CommandParameter="{Binding}">
|
||||
<PathIcon Width="10" Height="10">
|
||||
<PathIcon.Data>
|
||||
<MultiBinding Converter="{StaticResource ChevronDataConverter}">
|
||||
<Binding Path="IsExpanded"/>
|
||||
</MultiBinding>
|
||||
</PathIcon.Data>
|
||||
</PathIcon>
|
||||
</Button>
|
||||
|
||||
<!-- existing title/description area -->
|
||||
<StackPanel Grid.Column="1" ...>
|
||||
<!-- existing title binding with added italic when IsDraft -->
|
||||
<TextBlock Text="{Binding Title}"
|
||||
FontStyle="{Binding IsDraft, Converter={StaticResource BoolToItalicConverter}}"
|
||||
Opacity="{Binding IsDraft, Converter={StaticResource BoolToDraftOpacityConverter}}" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Badges -->
|
||||
<StackPanel Grid.Column="2" Orientation="Horizontal" Spacing="4">
|
||||
<Border Classes="badge draft" IsVisible="{Binding IsDraft}">
|
||||
<TextBlock Text="DRAFT"/>
|
||||
</Border>
|
||||
<Border Classes="badge planning" IsVisible="{Binding IsPlanningParent}">
|
||||
<TextBlock Text="{Binding PlanningBadge}"/>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Grid>
|
||||
```
|
||||
|
||||
This is a structural edit — preserve all existing bindings for status color, completion toggle, star, scheduled-for, etc. The new indentation column and badges are additive.
|
||||
|
||||
- [ ] **Step 2: Add the converters**
|
||||
|
||||
If `ChevronDataConverter`, `BoolToItalicConverter`, `BoolToDraftOpacityConverter` do not exist, add them to `src/ClaudeDo.Ui/Converters/` (or inline as compiled converters). Example inline:
|
||||
|
||||
```xml
|
||||
<!-- in UserControl.Resources of TaskRowView.axaml, or in App.axaml for global -->
|
||||
<Style Selector="Border.badge">
|
||||
<Setter Property="CornerRadius" Value="3"/>
|
||||
<Setter Property="Padding" Value="4,1"/>
|
||||
<Setter Property="Background" Value="{DynamicResource BadgeBgBrush}"/>
|
||||
</Style>
|
||||
<Style Selector="Border.badge.draft">
|
||||
<Setter Property="Background" Value="{DynamicResource DraftBadgeBrush}"/>
|
||||
</Style>
|
||||
<Style Selector="Border.badge.planning">
|
||||
<Setter Property="Background" Value="{DynamicResource PlanningBadgeBrush}"/>
|
||||
</Style>
|
||||
```
|
||||
|
||||
If converters must be code-based, a minimal `BoolToItalicConverter`:
|
||||
|
||||
```csharp
|
||||
using Avalonia.Data.Converters;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace ClaudeDo.Ui.Converters;
|
||||
|
||||
public sealed class BoolToItalicConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object? value, Type targetType, object? parameter, System.Globalization.CultureInfo culture)
|
||||
=> value is true ? FontStyle.Italic : FontStyle.Normal;
|
||||
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, System.Globalization.CultureInfo culture)
|
||||
=> throw new NotSupportedException();
|
||||
}
|
||||
```
|
||||
|
||||
Register in `App.axaml` resources.
|
||||
|
||||
- [ ] **Step 3: Build**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`
|
||||
Expected: builds cleanly (XAML compiles).
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/Views/Islands/TaskRowView.axaml src/ClaudeDo.Ui/Converters/
|
||||
git commit -m "feat(ui): TaskRowView hierarchy indentation, chevron, badges, draft italic"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: `TaskRowView` — planning context-menu entries
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/Views/Islands/TaskRowView.axaml`
|
||||
|
||||
- [ ] **Step 1: Locate the existing context menu**
|
||||
|
||||
Open `TaskRowView.axaml`. The ContextMenu lives somewhere on the root element or as a `ContextMenu.Items`/`ContextFlyout`. Find the block that defines entries like "Edit", "Run now", etc.
|
||||
|
||||
- [ ] **Step 2: Insert planning entries conditionally**
|
||||
|
||||
Add within the existing menu (order: after "Run now" and a separator):
|
||||
|
||||
```xml
|
||||
<MenuItem Header="Open planning Session"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).OpenPlanningSessionCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
IsVisible="{Binding Status, Converter={StaticResource IsManualAndNotChildConverter}, ConverterParameter={Binding IsChild}}"/>
|
||||
|
||||
<MenuItem Header="Resume planning Session"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).ResumePlanningSessionCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
IsVisible="{Binding Status, Converter={StaticResource IsPlanningConverter}}"/>
|
||||
|
||||
<MenuItem Header="Discard planning session"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).DiscardPlanningSessionCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
IsVisible="{Binding Status, Converter={StaticResource IsPlanningConverter}}"/>
|
||||
```
|
||||
|
||||
Simpler alternative without multi-condition converters: expose direct bool VM properties that combine the logic — `CanOpenPlanningSession`, `CanResumePlanningSession`, `CanDiscardPlanningSession`:
|
||||
|
||||
```csharp
|
||||
// In TaskRowViewModel
|
||||
public bool CanOpenPlanningSession =>
|
||||
string.Equals(Status, "manual", StringComparison.OrdinalIgnoreCase) && !IsChild;
|
||||
|
||||
public bool CanResumeOrDiscardPlanning =>
|
||||
string.Equals(Status, "planning", StringComparison.OrdinalIgnoreCase);
|
||||
```
|
||||
|
||||
Add `OnPropertyChanged(nameof(CanOpenPlanningSession))` and friends in the status/parent-id partial methods from Task 1. Then the XAML simplifies to:
|
||||
|
||||
```xml
|
||||
<MenuItem Header="Open planning Session"
|
||||
Command="{Binding ...OpenPlanningSessionCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
IsVisible="{Binding CanOpenPlanningSession}"/>
|
||||
```
|
||||
|
||||
Use this simpler path — cleaner.
|
||||
|
||||
- [ ] **Step 3: Build**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`
|
||||
Expected: builds.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/Views/Islands/TaskRowView.axaml src/ClaudeDo.Ui/ViewModels/Islands/TaskRowViewModel.cs
|
||||
git commit -m "feat(ui): planning entries in task context menu"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Island styles — draft, badges
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/Design/IslandStyles.axaml`
|
||||
|
||||
- [ ] **Step 1: Add brushes + styles**
|
||||
|
||||
Append within `<Styles.Resources>` or wherever brushes are defined:
|
||||
|
||||
```xml
|
||||
<SolidColorBrush x:Key="DraftBadgeBrush" Color="#4A5568"/>
|
||||
<SolidColorBrush x:Key="PlanningBadgeBrush" Color="#D69E2E"/>
|
||||
<SolidColorBrush x:Key="PlannedBadgeBrush" Color="#3182CE"/>
|
||||
```
|
||||
|
||||
Add styles:
|
||||
|
||||
```xml
|
||||
<Style Selector="Border.badge">
|
||||
<Setter Property="CornerRadius" Value="3"/>
|
||||
<Setter Property="Padding" Value="4,1"/>
|
||||
<Setter Property="VerticalAlignment" Value="Center"/>
|
||||
</Style>
|
||||
|
||||
<Style Selector="Border.badge > TextBlock">
|
||||
<Setter Property="FontSize" Value="9"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Foreground" Value="White"/>
|
||||
</Style>
|
||||
|
||||
<Style Selector="Border.badge.draft">
|
||||
<Setter Property="Background" Value="{DynamicResource DraftBadgeBrush}"/>
|
||||
</Style>
|
||||
|
||||
<Style Selector="Border.badge.planning">
|
||||
<Setter Property="Background" Value="{DynamicResource PlanningBadgeBrush}"/>
|
||||
</Style>
|
||||
|
||||
<Style Selector="Border.badge.planned">
|
||||
<Setter Property="Background" Value="{DynamicResource PlannedBadgeBrush}"/>
|
||||
</Style>
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Build and manually verify**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`
|
||||
Launch app, create a task, right-click, use Open planning Session (if Plan B merged) or simulate via DB. Verify badge + italic draft rendering visually.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/Design/IslandStyles.axaml
|
||||
git commit -m "feat(ui): draft and planning badge styles"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Unfinished-planning-session dialog
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ClaudeDo.Ui/Views/Dialogs/UnfinishedPlanningDialog.axaml` + `.axaml.cs`
|
||||
- Create: `src/ClaudeDo.Ui/ViewModels/Dialogs/UnfinishedPlanningDialogViewModel.cs`
|
||||
|
||||
- [ ] **Step 1: Create the VM**
|
||||
|
||||
`src/ClaudeDo.Ui/ViewModels/Dialogs/UnfinishedPlanningDialogViewModel.cs`:
|
||||
|
||||
```csharp
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
namespace ClaudeDo.Ui.ViewModels.Dialogs;
|
||||
|
||||
public enum UnfinishedPlanningDialogResult
|
||||
{
|
||||
Cancel,
|
||||
Resume,
|
||||
FinalizeNow,
|
||||
Discard,
|
||||
}
|
||||
|
||||
public sealed partial class UnfinishedPlanningDialogViewModel : ObservableObject
|
||||
{
|
||||
[ObservableProperty] private string title = "Unfinished planning session";
|
||||
[ObservableProperty] private string taskTitle = "";
|
||||
[ObservableProperty] private int draftCount;
|
||||
|
||||
public TaskCompletionSource<UnfinishedPlanningDialogResult> Result { get; } = new();
|
||||
|
||||
[RelayCommand] private void Resume() => Result.TrySetResult(UnfinishedPlanningDialogResult.Resume);
|
||||
[RelayCommand] private void FinalizeNow() => Result.TrySetResult(UnfinishedPlanningDialogResult.FinalizeNow);
|
||||
[RelayCommand] private void Discard() => Result.TrySetResult(UnfinishedPlanningDialogResult.Discard);
|
||||
[RelayCommand] private void Cancel() => Result.TrySetResult(UnfinishedPlanningDialogResult.Cancel);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Create the view**
|
||||
|
||||
`src/ClaudeDo.Ui/Views/Dialogs/UnfinishedPlanningDialog.axaml`:
|
||||
|
||||
```xml
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ClaudeDo.Ui.ViewModels.Dialogs"
|
||||
x:Class="ClaudeDo.Ui.Views.Dialogs.UnfinishedPlanningDialog"
|
||||
x:DataType="vm:UnfinishedPlanningDialogViewModel"
|
||||
Width="440" Height="220"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
CanResize="False"
|
||||
Title="{Binding Title}">
|
||||
<StackPanel Margin="20" Spacing="12">
|
||||
<TextBlock Text="{Binding Title}" FontWeight="Bold" FontSize="15"/>
|
||||
<TextBlock Text="{Binding TaskTitle}" Opacity="0.85"/>
|
||||
<TextBlock>
|
||||
<Run Text="{Binding DraftCount}"/>
|
||||
<Run Text=" draft tasks waiting to be finalized."/>
|
||||
</TextBlock>
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" HorizontalAlignment="Right">
|
||||
<Button Content="Discard" Command="{Binding DiscardCommand}"/>
|
||||
<Button Content="Finalize now" Command="{Binding FinalizeNowCommand}"/>
|
||||
<Button Content="Resume" Classes="accent" Command="{Binding ResumeCommand}"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Window>
|
||||
```
|
||||
|
||||
`UnfinishedPlanningDialog.axaml.cs`:
|
||||
|
||||
```csharp
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace ClaudeDo.Ui.Views.Dialogs;
|
||||
|
||||
public partial class UnfinishedPlanningDialog : Window
|
||||
{
|
||||
public UnfinishedPlanningDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Wire into `TasksIslandViewModel`**
|
||||
|
||||
When the user right-clicks a `Planning` row OR when the app starts and a `Planning` row is present, show the dialog. Add a helper in the VM:
|
||||
|
||||
```csharp
|
||||
private async Task<UnfinishedPlanningDialogResult> AskUnfinishedPlanningAsync(TaskRowViewModel row)
|
||||
{
|
||||
var dialogVm = new UnfinishedPlanningDialogViewModel
|
||||
{
|
||||
TaskTitle = row.Title,
|
||||
DraftCount = await _workerClient.GetPendingDraftCountAsync(row.Id),
|
||||
};
|
||||
var dlg = new UnfinishedPlanningDialog { DataContext = dialogVm };
|
||||
_ = dlg.ShowDialog(_ownerWindow);
|
||||
return await dialogVm.Result.Task;
|
||||
}
|
||||
```
|
||||
|
||||
Replace the direct resume/discard/finalize commands (from Task 3) with calls that first pop this dialog and dispatch based on result. For example:
|
||||
|
||||
```csharp
|
||||
[RelayCommand]
|
||||
private async Task ResumePlanningSessionAsync(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null || !row.IsPlanningParent) return;
|
||||
var choice = await AskUnfinishedPlanningAsync(row);
|
||||
switch (choice)
|
||||
{
|
||||
case UnfinishedPlanningDialogResult.Resume:
|
||||
await _workerClient.ResumePlanningSessionAsync(row.Id);
|
||||
break;
|
||||
case UnfinishedPlanningDialogResult.FinalizeNow:
|
||||
await _workerClient.FinalizePlanningSessionAsync(row.Id);
|
||||
break;
|
||||
case UnfinishedPlanningDialogResult.Discard:
|
||||
await _workerClient.DiscardPlanningSessionAsync(row.Id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Build + manual run**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`
|
||||
Expected: builds.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/Views/Dialogs/UnfinishedPlanningDialog.axaml src/ClaudeDo.Ui/Views/Dialogs/UnfinishedPlanningDialog.axaml.cs src/ClaudeDo.Ui/ViewModels/Dialogs/UnfinishedPlanningDialogViewModel.cs src/ClaudeDo.Ui/ViewModels/Islands/TasksIslandViewModel.cs
|
||||
git commit -m "feat(ui): unfinished planning session dialog"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 8: TasksIslandView — wire new templates
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/Views/Islands/TasksIslandView.axaml`
|
||||
|
||||
- [ ] **Step 1: No structural change required**
|
||||
|
||||
The hierarchy is already handled by `TasksIslandViewModel.RebuildFlatStreams` interleaving children into `OpenItems`/`CompletedItems`. The existing `ItemsControl` bindings in `TasksIslandView` automatically pick up the new rows. Indentation/chevron/badge rendering is entirely inside `TaskRowView` (Task 4).
|
||||
|
||||
Verify the view does not have any logic that filters out children based on `ParentTaskId IS NOT NULL` today. If it does, remove that filter — the VM is now authoritative about what's in the stream.
|
||||
|
||||
- [ ] **Step 2: Build + manual check**
|
||||
|
||||
Launch the UI, create a manual task, and manually update its status to `Planning` in the DB (or wait for Plan B). Create one child in DB. Verify indentation and chevron render.
|
||||
|
||||
- [ ] **Step 3: Commit (if any change was made)**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/Views/Islands/TasksIslandView.axaml
|
||||
git commit -m "chore(ui): verify tasks view renders hierarchy via flat stream"
|
||||
```
|
||||
|
||||
If no change — skip the commit.
|
||||
|
||||
---
|
||||
|
||||
## Task 9: Delete-with-children handling
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/ViewModels/Islands/TasksIslandViewModel.cs` (existing delete command)
|
||||
|
||||
- [ ] **Step 1: Catch `DbUpdateException` from delete**
|
||||
|
||||
Find the existing delete command. Wrap the repository/hub call:
|
||||
|
||||
```csharp
|
||||
[RelayCommand]
|
||||
private async Task RemoveAsync(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null) return;
|
||||
try
|
||||
{
|
||||
await _workerClient.DeleteTaskAsync(row.Id);
|
||||
}
|
||||
catch (HubException ex) when (ex.Message.Contains("foreign key", StringComparison.OrdinalIgnoreCase)
|
||||
|| ex.Message.Contains("FOREIGN KEY", StringComparison.OrdinalIgnoreCase)
|
||||
|| ex.Message.Contains("Restrict", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var childrenCount = 1; // or query via a new hub method if exact count matters
|
||||
var choice = await _dialogs.ConfirmAsync(
|
||||
"Cannot delete",
|
||||
$"This task has child tasks. Delete all including children?");
|
||||
if (!choice) return;
|
||||
// Recursive delete — iterate children first. For v1 MVP, instruct user to
|
||||
// discard the planning session first. Simpler, safer.
|
||||
await _dialogs.ShowErrorAsync(
|
||||
"Cannot delete",
|
||||
"Discard the planning session or delete child tasks manually first.");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Simplification for v1:** do not implement "Delete all including children" yet. Show an error instructing the user to discard the planning session or delete children first. This avoids an additional hub endpoint and keeps Plan C bounded.
|
||||
|
||||
- [ ] **Step 2: Build**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`
|
||||
Expected: builds.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/ViewModels/Islands/TasksIslandViewModel.cs
|
||||
git commit -m "feat(ui): friendly error when deleting task with children"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 10: Manual smoke test + final verification
|
||||
|
||||
**Files:** none
|
||||
|
||||
- [ ] **Step 1: Full test run**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests`
|
||||
Expected: all tests pass.
|
||||
|
||||
- [ ] **Step 2: Build the full app**
|
||||
|
||||
Run:
|
||||
```bash
|
||||
dotnet build src/ClaudeDo.Worker/ClaudeDo.Worker.csproj
|
||||
dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj
|
||||
dotnet build src/ClaudeDo.App/ClaudeDo.App.csproj
|
||||
```
|
||||
Expected: all succeed.
|
||||
|
||||
- [ ] **Step 3: Manual smoke test (requires Plan B merged)**
|
||||
|
||||
1. Launch the app.
|
||||
2. Create a Manual task with a title and some TODO-style description.
|
||||
3. Right-click → "Open planning Session".
|
||||
4. Verify Windows Terminal opens with Claude CLI running.
|
||||
5. In the terminal, ask Claude to create two child tasks (`mcp__claudedo__create_child_task`).
|
||||
6. Watch the UI: drafts appear under the parent (italic, grey, badge DRAFT).
|
||||
7. Ask Claude to `finalize`.
|
||||
8. Verify drafts become Manual/Queued children, parent flips to PLANNED badge.
|
||||
9. Close terminal without finalize on a new planning task; right-click the Planning task: dialog appears with Resume/Finalize/Discard.
|
||||
|
||||
- [ ] **Step 4: Document any UI tweaks needed in `docs/open.md`**
|
||||
|
||||
Add a checklist item under UI verification for planning session visuals.
|
||||
|
||||
- [ ] **Step 5: Final commit**
|
||||
|
||||
```bash
|
||||
git add docs/open.md
|
||||
git commit -m "docs(open): add planning-session manual verification checklist"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Out of scope for Plan C
|
||||
|
||||
- Recursive delete of parent-with-children via UI (error-only in v1).
|
||||
- Collapse-state persistence across app restarts (in-memory only).
|
||||
- Keyboard shortcut for "Open planning Session".
|
||||
- Visual differentiation for PLANNED parents beyond a badge (e.g., subtle background tint) — can be added later if visually needed.
|
||||
1831
docs/superpowers/plans/2026-04-23-self-update.md
Normal file
1831
docs/superpowers/plans/2026-04-23-self-update.md
Normal file
File diff suppressed because it is too large
Load Diff
718
docs/superpowers/plans/2026-04-23-worker-log-footer.md
Normal file
718
docs/superpowers/plans/2026-04-23-worker-log-footer.md
Normal file
@@ -0,0 +1,718 @@
|
||||
# Worker Log Footer Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Surface important Worker lifecycle events in the UI footer as a single rotating, color-coded line that auto-hides after 30s of silence.
|
||||
|
||||
**Architecture:** Add `WorkerLogLevel` enum in shared `ClaudeDo.Data` project. `HubBroadcaster` gets a `WorkerLog(message, level, timestampUtc)` SignalR event. Seven emit sites in `TaskRunner`, `TaskMergeService`, `TaskResetService` (callers of `WorktreeManager`, not WorktreeManager itself — they have the task title in scope). UI side: `WorkerClient` surfaces a `WorkerLogReceived` event; footer state lives on `IslandsShellViewModel` (existing root VM for `MainWindow`, also owns connection state); `System.Timers.Timer` clears the line after 30s; a `WorkerLogLevelToBrushConverter` maps level → brush in XAML.
|
||||
|
||||
**Tech Stack:** .NET 8, ASP.NET Core SignalR, Avalonia 12, CommunityToolkit.Mvvm, xUnit.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-04-23-worker-log-footer-design.md`
|
||||
|
||||
**Deviation from spec:** Spec names `WorktreeManager.CreateAsync` / `DiscardAsync` as emit sites. In practice, `WorktreeManager` has only the task ID in scope; its callers (`TaskRunner`, `TaskResetService`) have the title. Emitting from callers avoids adding constructor dependencies to `WorktreeManager` and produces identical user-visible behavior.
|
||||
|
||||
**Build note:** Per project convention, `dotnet build ClaudeDo.slnx` fails on .NET 8 — always build individual csprojs.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add `WorkerLogLevel` enum (shared contract)
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ClaudeDo.Data/Models/WorkerLogLevel.cs`
|
||||
|
||||
- [ ] **Step 1: Write the enum**
|
||||
|
||||
```csharp
|
||||
namespace ClaudeDo.Data.Models;
|
||||
|
||||
public enum WorkerLogLevel
|
||||
{
|
||||
Info,
|
||||
Success,
|
||||
Warn,
|
||||
Error,
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Build Data project**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Data/ClaudeDo.Data.csproj`
|
||||
Expected: Build succeeded, 0 errors.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Data/Models/WorkerLogLevel.cs
|
||||
git commit -m "feat(data): add WorkerLogLevel enum"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Add `WorkerLog` broadcaster method + SignalR JSON enum-as-string
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Worker/Hub/HubBroadcaster.cs` (append method)
|
||||
- Modify: `src/ClaudeDo.Worker/Program.cs` (line ~23 — the `AddSignalR()` call)
|
||||
|
||||
- [ ] **Step 1: Add enum-as-string serialization**
|
||||
|
||||
Replace:
|
||||
```csharp
|
||||
builder.Services.AddSignalR();
|
||||
```
|
||||
with:
|
||||
```csharp
|
||||
builder.Services.AddSignalR().AddJsonProtocol(options =>
|
||||
{
|
||||
options.PayloadSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add `WorkerLog` method to `HubBroadcaster`**
|
||||
|
||||
Add the following method inside `HubBroadcaster` class (after the existing `RunCreated` method):
|
||||
|
||||
```csharp
|
||||
public Task WorkerLog(string message, WorkerLogLevel level, DateTime timestampUtc) =>
|
||||
_hub.Clients.All.SendAsync("WorkerLog", message, level, timestampUtc);
|
||||
```
|
||||
|
||||
Add to the using block at top of file (if not already present):
|
||||
```csharp
|
||||
using ClaudeDo.Data.Models;
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Build**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Worker/ClaudeDo.Worker.csproj`
|
||||
Expected: Build succeeded, 0 errors.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Worker/Hub/HubBroadcaster.cs src/ClaudeDo.Worker/Program.cs
|
||||
git commit -m "feat(worker): add WorkerLog SignalR event"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Emit `WorkerLog` from `TaskRunner`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Worker/Runner/TaskRunner.cs`
|
||||
|
||||
Four emit sites in this file:
|
||||
1. **Created worktree** — right after `_wtManager.CreateAsync` succeeds (around line 69).
|
||||
2. **Started Claude** — just before invoking Claude process.
|
||||
3. **Committed changes** — after auto-commit (before the `WorktreeUpdated` broadcast around line 318).
|
||||
4. **Finished** — at both success (line 330) and failure paths, mirroring the existing `TaskFinished` call.
|
||||
|
||||
- [ ] **Step 1: Add using for `WorkerLogLevel`**
|
||||
|
||||
Ensure `TaskRunner.cs` has at the top:
|
||||
```csharp
|
||||
using ClaudeDo.Data.Models;
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Emit "Created worktree"**
|
||||
|
||||
After the line `wtCtx = await _wtManager.CreateAsync(task, list, ct);` (around line 69), add:
|
||||
```csharp
|
||||
await _broadcaster.WorkerLog($"Created worktree for \"{task.Title}\"", WorkerLogLevel.Info, DateTime.UtcNow);
|
||||
```
|
||||
(Place inside the same `if` branch that called `CreateAsync`, after the assignment.)
|
||||
|
||||
- [ ] **Step 3: Emit "Started Claude"**
|
||||
|
||||
Locate the point just before `ClaudeProcess` is invoked (search for where `ClaudeProcess` or `RunProcessAsync` is called). Just before the invocation, add:
|
||||
```csharp
|
||||
await _broadcaster.WorkerLog($"Started Claude for \"{task.Title}\"", WorkerLogLevel.Info, DateTime.UtcNow);
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Emit "Committed changes"**
|
||||
|
||||
Locate the auto-commit code path (around line 318, just before `await _broadcaster.WorktreeUpdated(task.Id);`). Add immediately before that call:
|
||||
```csharp
|
||||
await _broadcaster.WorkerLog($"Committed changes in \"{task.Title}\"", WorkerLogLevel.Info, DateTime.UtcNow);
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Emit "Finished (done)"**
|
||||
|
||||
Find the success finish path (around line 330, where `TaskFinished` is broadcast with status `"done"`). Add immediately before that call:
|
||||
```csharp
|
||||
await _broadcaster.WorkerLog($"Finished \"{task.Title}\" (done)", WorkerLogLevel.Success, DateTime.UtcNow);
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Emit "Finished (failed)"**
|
||||
|
||||
Find the failure path (search for `TaskFinished` with status `"failed"`). Add immediately before:
|
||||
```csharp
|
||||
await _broadcaster.WorkerLog($"Finished \"{task.Title}\" (failed)", WorkerLogLevel.Error, DateTime.UtcNow);
|
||||
```
|
||||
|
||||
- [ ] **Step 7: Build**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Worker/ClaudeDo.Worker.csproj`
|
||||
Expected: Build succeeded, 0 errors.
|
||||
|
||||
- [ ] **Step 8: Run existing Worker tests (no regressions)**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests/ClaudeDo.Worker.Tests.csproj`
|
||||
Expected: All tests pass.
|
||||
|
||||
- [ ] **Step 9: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Worker/Runner/TaskRunner.cs
|
||||
git commit -m "feat(worker): emit WorkerLog events from TaskRunner"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Emit `WorkerLog` from `TaskMergeService` and `TaskResetService`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Worker/Services/TaskMergeService.cs`
|
||||
- Modify: `src/ClaudeDo.Worker/Services/TaskResetService.cs`
|
||||
|
||||
Both services already have `HubBroadcaster` injected (`_broadcaster`). Both already load the task entity (needed for title).
|
||||
|
||||
- [ ] **Step 1: Add using in both files**
|
||||
|
||||
Add to the top of each file (if not already present):
|
||||
```csharp
|
||||
using ClaudeDo.Data.Models;
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Emit "Merged" in `TaskMergeService.MergeAsync`**
|
||||
|
||||
Locate the existing log line around line 137:
|
||||
```csharp
|
||||
_logger.LogInformation(
|
||||
"Merged task {TaskId} branch {Branch} into {Target} (remove worktree: {Remove})",
|
||||
...);
|
||||
```
|
||||
|
||||
Immediately after it (before `return new MergeResult(...)` on line 140), add:
|
||||
```csharp
|
||||
await _broadcaster.WorkerLog($"Merged \"{task.Title}\" into {targetBranch}", WorkerLogLevel.Success, DateTime.UtcNow);
|
||||
```
|
||||
Use whatever variable names `task` and `targetBranch` are in scope — adjust to match the actual local names at that site.
|
||||
|
||||
- [ ] **Step 3: Emit "Discarded" in `TaskResetService.ResetAsync`**
|
||||
|
||||
Locate the call `await _wtManager.DiscardAsync(wt, list.WorkingDir, ct);` (line 53). Immediately after it, add:
|
||||
```csharp
|
||||
await _broadcaster.WorkerLog($"Discarded worktree for \"{task.Title}\"", WorkerLogLevel.Warn, DateTime.UtcNow);
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Emit "Reset" in `TaskResetService.ResetAsync`**
|
||||
|
||||
Locate the existing line `_logger.LogInformation("Reset task {TaskId} to Manual ...` (line 66). Immediately after it, add:
|
||||
```csharp
|
||||
await _broadcaster.WorkerLog($"Reset \"{task.Title}\"", WorkerLogLevel.Warn, DateTime.UtcNow);
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Build**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Worker/ClaudeDo.Worker.csproj`
|
||||
Expected: Build succeeded, 0 errors.
|
||||
|
||||
- [ ] **Step 6: Run existing Worker tests**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Worker.Tests/ClaudeDo.Worker.Tests.csproj`
|
||||
Expected: All tests pass.
|
||||
|
||||
- [ ] **Step 7: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Worker/Services/TaskMergeService.cs src/ClaudeDo.Worker/Services/TaskResetService.cs
|
||||
git commit -m "feat(worker): emit WorkerLog for merge, discard, reset"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Add `WorkerLogEntry` record + `WorkerLogReceived` event on `WorkerClient`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/Services/WorkerClient.cs`
|
||||
|
||||
- [ ] **Step 1: Add using for `WorkerLogLevel`**
|
||||
|
||||
Add at the top of `WorkerClient.cs`:
|
||||
```csharp
|
||||
using ClaudeDo.Data.Models;
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Declare the `WorkerLogEntry` record**
|
||||
|
||||
Add at the top of the file (above or below the `WorkerClient` class, same namespace):
|
||||
```csharp
|
||||
public sealed record WorkerLogEntry(string Message, WorkerLogLevel Level, DateTime TimestampUtc);
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Add the event field**
|
||||
|
||||
Alongside the other `public event Action<...>?` declarations (around lines 42-48), add:
|
||||
```csharp
|
||||
public event Action<WorkerLogEntry>? WorkerLogReceivedEvent;
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Register the SignalR handler**
|
||||
|
||||
Alongside the other `_hub.On<...>` registrations (around lines 80-117), add:
|
||||
```csharp
|
||||
_hub.On<string, WorkerLogLevel, DateTime>("WorkerLog", (message, level, timestampUtc) =>
|
||||
{
|
||||
WorkerLogReceivedEvent?.Invoke(new WorkerLogEntry(message, level, timestampUtc));
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Build**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`
|
||||
Expected: Build succeeded, 0 errors.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/Services/WorkerClient.cs
|
||||
git commit -m "feat(ui): subscribe to WorkerLog SignalR event"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Create `ClaudeDo.Ui.Tests` project and add `WorkerLogLevelToBrushConverter`
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ClaudeDo.Ui/Converters/WorkerLogLevelToBrushConverter.cs`
|
||||
- Modify: `src/ClaudeDo.Ui/App.axaml` (register converter as resource)
|
||||
- Create: `tests/ClaudeDo.Ui.Tests/ClaudeDo.Ui.Tests.csproj`
|
||||
- Create: `tests/ClaudeDo.Ui.Tests/WorkerLogLevelToBrushConverterTests.cs`
|
||||
|
||||
- [ ] **Step 1: Write the converter**
|
||||
|
||||
Create `src/ClaudeDo.Ui/Converters/WorkerLogLevelToBrushConverter.cs`:
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Avalonia;
|
||||
using Avalonia.Data.Converters;
|
||||
using Avalonia.Media;
|
||||
using ClaudeDo.Data.Models;
|
||||
|
||||
namespace ClaudeDo.Ui.Converters;
|
||||
|
||||
public sealed class WorkerLogLevelToBrushConverter : IValueConverter
|
||||
{
|
||||
private static readonly IBrush SuccessBrush = new SolidColorBrush(Color.Parse("#4CAF50"));
|
||||
private static readonly IBrush WarnBrush = new SolidColorBrush(Color.Parse("#FFA726"));
|
||||
private static readonly IBrush ErrorBrush = new SolidColorBrush(Color.Parse("#EF5350"));
|
||||
private static readonly IBrush InfoFallback = new SolidColorBrush(Color.Parse("#888888"));
|
||||
|
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is not WorkerLogLevel level)
|
||||
return AvaloniaProperty.UnsetValue;
|
||||
|
||||
return level switch
|
||||
{
|
||||
WorkerLogLevel.Success => SuccessBrush,
|
||||
WorkerLogLevel.Warn => WarnBrush,
|
||||
WorkerLogLevel.Error => ErrorBrush,
|
||||
WorkerLogLevel.Info => ResolveInfoBrush(),
|
||||
_ => AvaloniaProperty.UnsetValue,
|
||||
};
|
||||
}
|
||||
|
||||
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
|
||||
private static IBrush ResolveInfoBrush()
|
||||
{
|
||||
if (Application.Current is { } app &&
|
||||
app.Resources.TryGetResource("TextDimBrush", app.ActualThemeVariant, out var res) &&
|
||||
res is IBrush brush)
|
||||
{
|
||||
return brush;
|
||||
}
|
||||
return InfoFallback;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Register converter in `App.axaml`**
|
||||
|
||||
Open `src/ClaudeDo.Ui/App.axaml`. Inside the `<Application.Resources>` section (add one if missing), add alongside any existing converter entries:
|
||||
|
||||
```xml
|
||||
<converters:WorkerLogLevelToBrushConverter x:Key="WorkerLogLevelToBrush"/>
|
||||
```
|
||||
|
||||
Ensure the `xmlns:converters="using:ClaudeDo.Ui.Converters"` namespace is declared at the root `<Application>` element. If other converters (e.g. `StatusColorConverter`) are already resources in `App.axaml` follow the same pattern; if they're declared per-view, declare this converter at the top of `MainWindow.axaml` in Task 8 instead.
|
||||
|
||||
- [ ] **Step 3: Create UI test project**
|
||||
|
||||
Create `tests/ClaudeDo.Ui.Tests/ClaudeDo.Ui.Tests.csproj`:
|
||||
|
||||
```xml
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="12.0.0" />
|
||||
<PackageReference Include="Avalonia.Headless" Version="12.0.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ClaudeDo.Ui\ClaudeDo.Ui.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
```
|
||||
|
||||
If the existing `tests/ClaudeDo.Worker.Tests/*.csproj` uses different `Microsoft.NET.Test.Sdk` / xUnit versions, match those versions exactly to avoid analyzer mismatches.
|
||||
|
||||
- [ ] **Step 4: Write the failing test**
|
||||
|
||||
Create `tests/ClaudeDo.Ui.Tests/WorkerLogLevelToBrushConverterTests.cs`:
|
||||
|
||||
```csharp
|
||||
using System.Globalization;
|
||||
using Avalonia;
|
||||
using Avalonia.Media;
|
||||
using ClaudeDo.Data.Models;
|
||||
using ClaudeDo.Ui.Converters;
|
||||
using Xunit;
|
||||
|
||||
namespace ClaudeDo.Ui.Tests;
|
||||
|
||||
public class WorkerLogLevelToBrushConverterTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(WorkerLogLevel.Success, "#FF4CAF50")]
|
||||
[InlineData(WorkerLogLevel.Warn, "#FFFFA726")]
|
||||
[InlineData(WorkerLogLevel.Error, "#FFEF5350")]
|
||||
public void Convert_maps_level_to_expected_brush_color(WorkerLogLevel level, string expectedArgb)
|
||||
{
|
||||
var converter = new WorkerLogLevelToBrushConverter();
|
||||
|
||||
var result = converter.Convert(level, typeof(IBrush), null, CultureInfo.InvariantCulture);
|
||||
|
||||
var solid = Assert.IsType<SolidColorBrush>(result);
|
||||
Assert.Equal(expectedArgb.ToLowerInvariant(), $"#{solid.Color.ToUInt32():X8}".ToLowerInvariant());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convert_info_returns_a_brush_fallback_when_no_app()
|
||||
{
|
||||
var converter = new WorkerLogLevelToBrushConverter();
|
||||
|
||||
var result = converter.Convert(WorkerLogLevel.Info, typeof(IBrush), null, CultureInfo.InvariantCulture);
|
||||
|
||||
Assert.IsAssignableFrom<IBrush>(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convert_unknown_value_returns_unset()
|
||||
{
|
||||
var converter = new WorkerLogLevelToBrushConverter();
|
||||
|
||||
var result = converter.Convert("not a level", typeof(IBrush), null, CultureInfo.InvariantCulture);
|
||||
|
||||
Assert.Equal(AvaloniaProperty.UnsetValue, result);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Run the tests**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Ui.Tests/ClaudeDo.Ui.Tests.csproj`
|
||||
Expected: All 5 tests pass.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/Converters/WorkerLogLevelToBrushConverter.cs src/ClaudeDo.Ui/App.axaml tests/ClaudeDo.Ui.Tests/
|
||||
git commit -m "feat(ui): add WorkerLogLevelToBrushConverter with tests"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Add footer state + 30s auto-clear timer to `IslandsShellViewModel`
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/ViewModels/IslandsShellViewModel.cs`
|
||||
- Create: `tests/ClaudeDo.Ui.Tests/IslandsShellViewModelWorkerLogTests.cs`
|
||||
|
||||
Timer uses `System.Timers.Timer` (not `DispatcherTimer`) so unit tests don't need an Avalonia dispatcher. The elapsed callback marshals to the UI thread via `Dispatcher.UIThread.Post` when the dispatcher is available; in tests the VM logic under test sets properties directly so no marshalling is needed.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
Create `tests/ClaudeDo.Ui.Tests/IslandsShellViewModelWorkerLogTests.cs`:
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using ClaudeDo.Data.Models;
|
||||
using ClaudeDo.Ui.Services;
|
||||
using ClaudeDo.Ui.ViewModels;
|
||||
using Xunit;
|
||||
|
||||
namespace ClaudeDo.Ui.Tests;
|
||||
|
||||
public class IslandsShellViewModelWorkerLogTests
|
||||
{
|
||||
private static IslandsShellViewModel NewVm() =>
|
||||
// The real constructor requires island VMs + WorkerClient. These tests
|
||||
// only exercise the WorkerLog handling, so we use a test-only constructor
|
||||
// that bypasses the sub-VMs. Add `internal IslandsShellViewModel()` for tests.
|
||||
IslandsShellViewModel.CreateForTests();
|
||||
|
||||
[Fact]
|
||||
public void Receiving_event_sets_text_level_and_visible()
|
||||
{
|
||||
var vm = NewVm();
|
||||
var at = new DateTime(2026, 4, 23, 14, 32, 0, DateTimeKind.Utc);
|
||||
|
||||
vm.OnWorkerLogReceived(new WorkerLogEntry("Created worktree for \"X\"", WorkerLogLevel.Info, at));
|
||||
|
||||
Assert.True(vm.IsWorkerLogVisible);
|
||||
Assert.Equal(WorkerLogLevel.Info, vm.WorkerLogLevel);
|
||||
Assert.Contains("Created worktree for \"X\"", vm.WorkerLogText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Second_event_replaces_first()
|
||||
{
|
||||
var vm = NewVm();
|
||||
vm.OnWorkerLogReceived(new WorkerLogEntry("first", WorkerLogLevel.Info, DateTime.UtcNow));
|
||||
vm.OnWorkerLogReceived(new WorkerLogEntry("second", WorkerLogLevel.Success, DateTime.UtcNow));
|
||||
|
||||
Assert.Contains("second", vm.WorkerLogText);
|
||||
Assert.Equal(WorkerLogLevel.Success, vm.WorkerLogLevel);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClearWorkerLog_hides_line()
|
||||
{
|
||||
var vm = NewVm();
|
||||
vm.OnWorkerLogReceived(new WorkerLogEntry("msg", WorkerLogLevel.Info, DateTime.UtcNow));
|
||||
|
||||
vm.ClearWorkerLog();
|
||||
|
||||
Assert.False(vm.IsWorkerLogVisible);
|
||||
Assert.Null(vm.WorkerLogText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Text_is_formatted_as_HHmm_dot_message_local_time()
|
||||
{
|
||||
var vm = NewVm();
|
||||
var utc = new DateTime(2026, 4, 23, 12, 0, 0, DateTimeKind.Utc);
|
||||
var expectedLocalHhmm = utc.ToLocalTime().ToString("HH:mm");
|
||||
|
||||
vm.OnWorkerLogReceived(new WorkerLogEntry("hello", WorkerLogLevel.Info, utc));
|
||||
|
||||
Assert.StartsWith(expectedLocalHhmm + " · ", vm.WorkerLogText);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests to confirm they fail to compile**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Ui.Tests/ClaudeDo.Ui.Tests.csproj`
|
||||
Expected: Build errors — `CreateForTests`, `OnWorkerLogReceived`, `ClearWorkerLog`, `IsWorkerLogVisible`, `WorkerLogText`, `WorkerLogLevel` do not yet exist.
|
||||
|
||||
- [ ] **Step 3: Implement on `IslandsShellViewModel`**
|
||||
|
||||
Open `src/ClaudeDo.Ui/ViewModels/IslandsShellViewModel.cs`. Add `using`s if missing:
|
||||
|
||||
```csharp
|
||||
using System.Timers;
|
||||
using Avalonia.Threading;
|
||||
using ClaudeDo.Data.Models;
|
||||
using ClaudeDo.Ui.Services;
|
||||
```
|
||||
|
||||
Inside the class, add:
|
||||
|
||||
```csharp
|
||||
[ObservableProperty] private string? workerLogText;
|
||||
[ObservableProperty] private WorkerLogLevel workerLogLevel;
|
||||
[ObservableProperty] private bool isWorkerLogVisible;
|
||||
|
||||
private readonly Timer _workerLogTimer = new(TimeSpan.FromSeconds(30).TotalMilliseconds)
|
||||
{
|
||||
AutoReset = false,
|
||||
};
|
||||
|
||||
internal static IslandsShellViewModel CreateForTests() =>
|
||||
(IslandsShellViewModel)System.Runtime.Serialization.FormatterServices
|
||||
.GetUninitializedObject(typeof(IslandsShellViewModel));
|
||||
```
|
||||
|
||||
(If `FormatterServices` is unavailable under `net8.0`, instead add a parameterless `internal IslandsShellViewModel() {}` constructor guarded for tests only.)
|
||||
|
||||
In the existing real constructor, wire up subscription (after the line `Worker.PropertyChanged += ...` block, around line 63-70):
|
||||
|
||||
```csharp
|
||||
Worker.WorkerLogReceivedEvent += OnWorkerLogReceived;
|
||||
_workerLogTimer.Elapsed += (_, _) =>
|
||||
{
|
||||
if (Dispatcher.UIThread.CheckAccess()) ClearWorkerLog();
|
||||
else Dispatcher.UIThread.Post(ClearWorkerLog);
|
||||
};
|
||||
```
|
||||
|
||||
Add the methods the tests call:
|
||||
|
||||
```csharp
|
||||
public void OnWorkerLogReceived(WorkerLogEntry entry)
|
||||
{
|
||||
var hhmm = entry.TimestampUtc.ToLocalTime().ToString("HH:mm");
|
||||
WorkerLogText = $"{hhmm} · {entry.Message}";
|
||||
WorkerLogLevel = entry.Level;
|
||||
IsWorkerLogVisible = true;
|
||||
|
||||
_workerLogTimer.Stop();
|
||||
_workerLogTimer.Start();
|
||||
}
|
||||
|
||||
public void ClearWorkerLog()
|
||||
{
|
||||
IsWorkerLogVisible = false;
|
||||
WorkerLogText = null;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run tests**
|
||||
|
||||
Run: `dotnet test tests/ClaudeDo.Ui.Tests/ClaudeDo.Ui.Tests.csproj`
|
||||
Expected: All tests pass (5 converter + 4 VM = 9 tests).
|
||||
|
||||
- [ ] **Step 5: Build the UI project as a sanity check**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`
|
||||
Expected: Build succeeded.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/ViewModels/IslandsShellViewModel.cs tests/ClaudeDo.Ui.Tests/IslandsShellViewModelWorkerLogTests.cs
|
||||
git commit -m "feat(ui): add worker log state and 30s timer to shell VM"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Update `MainWindow.axaml` footer — dock log line right
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ClaudeDo.Ui/Views/MainWindow.axaml` (lines 104-135 — the footer `Border`)
|
||||
|
||||
- [ ] **Step 1: Add the converter resource to the window (if not already in App.axaml)**
|
||||
|
||||
If Task 6 declared the converter in `App.axaml`, skip this step. Otherwise, add a `<Window.Resources>` block near the top of `MainWindow.axaml`:
|
||||
```xml
|
||||
<Window.Resources>
|
||||
<converters:WorkerLogLevelToBrushConverter x:Key="WorkerLogLevelToBrush"/>
|
||||
</Window.Resources>
|
||||
```
|
||||
Ensure `xmlns:converters="using:ClaudeDo.Ui.Converters"` is declared on the root `<Window>`.
|
||||
|
||||
- [ ] **Step 2: Replace the footer body**
|
||||
|
||||
Replace the existing footer `<Border Grid.Row="2" ...>` inner contents (the `<StackPanel>` at lines 109-134) with:
|
||||
|
||||
```xml
|
||||
<DockPanel LastChildFill="True" Margin="14,0">
|
||||
<!-- Left: connection pill -->
|
||||
<StackPanel DockPanel.Dock="Left" Orientation="Horizontal" Spacing="7"
|
||||
VerticalAlignment="Center">
|
||||
<Ellipse Width="7" Height="7" Fill="#4CAF50"
|
||||
IsVisible="{Binding Worker.IsConnected}"/>
|
||||
<Ellipse Width="7" Height="7" Fill="#FFA726"
|
||||
IsVisible="{Binding Worker.IsReconnecting}"/>
|
||||
<Ellipse Width="7" Height="7" Fill="#EF5350"
|
||||
IsVisible="{Binding IsOffline}"/>
|
||||
<TextBlock Text="{Binding ConnectionText, Converter={StaticResource UpperCase}}"
|
||||
FontFamily="{DynamicResource MonoFont}"
|
||||
FontSize="10"
|
||||
LetterSpacing="1.4"
|
||||
Foreground="{DynamicResource TextDimBrush}"
|
||||
VerticalAlignment="Center"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Right: worker log line -->
|
||||
<TextBlock DockPanel.Dock="Right"
|
||||
Text="{Binding WorkerLogText}"
|
||||
IsVisible="{Binding IsWorkerLogVisible}"
|
||||
Foreground="{Binding WorkerLogLevel, Converter={StaticResource WorkerLogLevelToBrush}}"
|
||||
FontFamily="{DynamicResource MonoFont}"
|
||||
FontSize="10"
|
||||
LetterSpacing="1.4"
|
||||
TextTrimming="CharacterEllipsis"
|
||||
VerticalAlignment="Center"/>
|
||||
|
||||
<!-- Spacer (fills remaining space between pill and log) -->
|
||||
<Panel/>
|
||||
</DockPanel>
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Build the UI**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.Ui/ClaudeDo.Ui.csproj`
|
||||
Expected: Build succeeded, 0 errors. No XAML compilation errors.
|
||||
|
||||
- [ ] **Step 4: Build the full app (entry point)**
|
||||
|
||||
Run: `dotnet build src/ClaudeDo.App/ClaudeDo.App.csproj`
|
||||
Expected: Build succeeded.
|
||||
|
||||
- [ ] **Step 5: Manual smoke test**
|
||||
|
||||
Start the Worker and the App (two separate processes per CLAUDE.md).
|
||||
|
||||
Exercise each event and confirm the footer line appears with the expected color and copy:
|
||||
|
||||
1. Start a task → expect `HH:MM · Created worktree for "<title>"` (dim/info).
|
||||
2. Observe while Claude runs → expect `HH:MM · Started Claude for "<title>"` (dim/info).
|
||||
3. Task commits → expect `HH:MM · Committed changes in "<title>"` (dim/info).
|
||||
4. Task finishes successfully → expect `HH:MM · Finished "<title>" (done)` (green).
|
||||
5. Trigger a failing task → expect `HH:MM · Finished "<title>" (failed)` (red).
|
||||
6. Reset a failed task → expect `HH:MM · Discarded worktree for "<title>"` (amber) followed by `HH:MM · Reset "<title>"` (amber).
|
||||
7. Merge a completed task → expect `HH:MM · Merged "<title>" into <branch>` (green).
|
||||
8. Wait 30s with no new events → footer log line disappears (connection pill remains).
|
||||
9. Trigger a burst of 3 events in quick succession → only the most recent is shown; timer resets on each.
|
||||
10. Long task title (≥60 chars) → line is ellipsized, connection pill on the left remains fully visible.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ClaudeDo.Ui/Views/MainWindow.axaml
|
||||
git commit -m "feat(ui): show worker log line in footer"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
- **Spec coverage:**
|
||||
- Enum `WorkerLogLevel` in `ClaudeDo.Data` — Task 1 ✓
|
||||
- SignalR enum-as-string — Task 2 ✓
|
||||
- `HubBroadcaster.WorkerLog` — Task 2 ✓
|
||||
- 7 emit sites with correct level mapping — Tasks 3, 4 ✓
|
||||
- `WorkerClient.WorkerLogReceived` event + `WorkerLogEntry` record — Task 5 ✓
|
||||
- `WorkerLogLevelToBrushConverter` with unit tests — Task 6 ✓
|
||||
- Footer VM state + 30s timer + tests — Task 7 ✓
|
||||
- Footer XAML (DockPanel, connection left, log right, level-based color, ellipsis) — Task 8 ✓
|
||||
- Out-of-scope items (history drawer, filtering, persistence) — correctly omitted ✓
|
||||
|
||||
- **Placeholder scan:** No "TBD" / "handle edge cases" / "similar to Task N". All code is inline.
|
||||
|
||||
- **Type consistency:** `WorkerLogEntry(Message, Level, TimestampUtc)` — same signature used in Task 5 (declaration), Task 7 (consumer tests + VM). `WorkerLog(message, level, timestampUtc)` — same signature in Task 2 (broadcaster) and Tasks 3-4 (callers). `OnWorkerLogReceived` / `ClearWorkerLog` / `IsWorkerLogVisible` / `WorkerLogText` / `WorkerLogLevel` — consistent between Task 7 test and Task 7 implementation.
|
||||
@@ -0,0 +1,130 @@
|
||||
# Continue & Reset Buttons for Failed Tasks
|
||||
|
||||
## Problem
|
||||
|
||||
When a task ends in `Failed` status (Claude exited without marking the work done, cancelled mid-run, crashed, etc.), the user has no way to act on it from the UI:
|
||||
|
||||
- **Nudging the agent** is only possible via the hub method `ContinueTask`, which is not wired into the UI.
|
||||
- **Rolling back** the worktree requires shelling into git manually to remove the branch and folder, then editing the task in the DB. In practice the worktree is just abandoned.
|
||||
|
||||
We want two explicit actions in the details pane for a failed task: **Continue** (resume the Claude session with a follow-up prompt) and **Reset** (discard the worktree and return the task to an editable `Manual` state).
|
||||
|
||||
## Scope
|
||||
|
||||
- Actions are shown **only when the selected task has `Status == Failed`**.
|
||||
- `Continue` is the multi-turn mechanism already implemented in `TaskRunner.ContinueAsync` — this spec only wires it into the UI.
|
||||
- `Reset` is new end-to-end (hub method, worktree discard, task status reset).
|
||||
- Run history (`task_runs` rows) is **preserved** across a Reset for audit.
|
||||
- Out of scope: Continue/Reset on `Done` tasks, undo of Reset, modifying the follow-up prompt before sending.
|
||||
|
||||
## UX
|
||||
|
||||
Both buttons live in `DetailsIslandView`, inside a new horizontal button row that is visible only when the currently selected task is `Failed`.
|
||||
|
||||
### Continue
|
||||
|
||||
- One-click. Sends the canned prompt `"Continue working on this task."` via `WorkerHub.ContinueTask(taskId, prompt)`.
|
||||
- Enabled **only if** the task's latest `TaskRunEntity` has a non-null `SessionId`.
|
||||
- When disabled, a tooltip reads `No session to resume`.
|
||||
- No confirmation dialog.
|
||||
|
||||
### Reset
|
||||
|
||||
- Always enabled when the task is `Failed`.
|
||||
- Opens a confirmation dialog:
|
||||
> Discard worktree and reset task?
|
||||
> This deletes branch `claudedo/<id>` and all uncommitted changes.
|
||||
- On confirm, calls `WorkerHub.ResetTask(taskId)`.
|
||||
|
||||
## Backend
|
||||
|
||||
### New hub method — `WorkerHub.ResetTask(string taskId)`
|
||||
|
||||
Preconditions:
|
||||
|
||||
- Task exists.
|
||||
- Task status is **not** `Running`. If it is, throw — resetting a task that is actively executing would race with the runner.
|
||||
|
||||
Steps:
|
||||
|
||||
1. Load the task and its worktree (if any).
|
||||
2. If a worktree exists and its `State == Active`, call `WorktreeManager.DiscardAsync(worktree, ct)` (see below).
|
||||
3. Call `TaskRepository.ResetToManualAsync(taskId, ct)` to clear the result fields and flip the status.
|
||||
4. Broadcast `TaskUpdated(taskId)`; broadcast `WorktreeUpdated(taskId)` if the worktree state changed.
|
||||
|
||||
If `WorktreeManager.DiscardAsync` throws (e.g. folder locked, branch checked out elsewhere), the hub method surfaces the error to the caller and leaves the task as `Failed` with the worktree still `Active`, so the user can retry. `TaskRepository.ResetToManualAsync` is **not** called in the failure path.
|
||||
|
||||
### New — `WorktreeManager.DiscardAsync(WorktreeEntity wt, CancellationToken ct)`
|
||||
|
||||
Shape mirrors the existing `CommitIfChangedAsync`. Steps:
|
||||
|
||||
1. `git worktree remove --force <wt.Path>` via `GitService`. The `--force` flag drops any uncommitted changes — expected, since the user already confirmed.
|
||||
2. `git branch -D <wt.BranchName>` via `GitService`.
|
||||
3. Update `WorktreeRepository`: set `State = Discarded`.
|
||||
|
||||
`GitService` gains two thin wrappers if they do not already exist: `WorktreeRemoveAsync(path, force: true)` and `BranchDeleteForceAsync(branch)`.
|
||||
|
||||
### New — `TaskRepository.ResetToManualAsync(string taskId, CancellationToken ct)`
|
||||
|
||||
Single UPDATE that sets:
|
||||
|
||||
- `Status = Manual`
|
||||
- `Result = null`
|
||||
- `StartedAt = null`
|
||||
- `FinishedAt = null`
|
||||
|
||||
`LogPath` and the `task_runs` rows are left intact — they are the audit trail.
|
||||
|
||||
### Continue wiring
|
||||
|
||||
No backend changes. The UI calls `WorkerHub.ContinueTask(taskId, prompt)` and `TaskRunner.ContinueAsync` handles the rest.
|
||||
|
||||
## UI
|
||||
|
||||
### `DetailsIslandViewModel`
|
||||
|
||||
New members:
|
||||
|
||||
- `[ObservableProperty] bool showFailedActions` — true when the selected task's status is `Failed`.
|
||||
- `[ObservableProperty] bool canContinue` — true when `showFailedActions` **and** the latest run of the selected task has a non-null `SessionId`.
|
||||
- `[RelayCommand(CanExecute = nameof(CanContinue))] Task ContinueAsync()` — calls `HubClient.ContinueTask(task.Id, "Continue working on this task.")`.
|
||||
- `[RelayCommand(CanExecute = nameof(ShowFailedActions))] Task ResetAsync()` — opens confirmation; on confirm, calls `HubClient.ResetTask(task.Id)`.
|
||||
|
||||
`ShowFailedActions` and `CanContinue` recompute whenever the selected task or its runs change (subscribe to the existing selection / task-updated signals).
|
||||
|
||||
### `DetailsIslandView.axaml`
|
||||
|
||||
A single `StackPanel` (orientation horizontal) inside the existing details layout, bound to `ShowFailedActions` for visibility, with two `Button`s wired to the commands.
|
||||
|
||||
### Confirmation dialog
|
||||
|
||||
Reuse the existing modal pattern (see `WorktreeModalView` for the shape). A minimal `ConfirmDialog` with title, body, `Cancel` + `Confirm` buttons is acceptable and reusable; if a simpler inline approach is idiomatic in this codebase, use that instead.
|
||||
|
||||
### `HubClient`
|
||||
|
||||
Add `Task ResetTask(string taskId)` alongside the existing `ContinueTask` wrapper.
|
||||
|
||||
## Error handling
|
||||
|
||||
| Failure | Behaviour |
|
||||
|---|---|
|
||||
| `ResetTask` called on a `Running` task | Hub throws; UI shows the error. The Reset button is CanExecute-gated anyway, so this is a defensive check. |
|
||||
| `git worktree remove` fails | Hub throws; task stays `Failed`, worktree stays `Active`, user can retry or clean up manually. |
|
||||
| `git branch -D` fails after worktree removal succeeded | Worktree state still gets set to `Discarded` (the folder is gone; leaving the branch dangling is less bad than leaving the DB out of sync). Log a warning. |
|
||||
| `Continue` with no session_id | Button is disabled — the call cannot happen from the UI. Hub still guards with the existing `InvalidOperationException` in `ContinueAsync` for safety. |
|
||||
|
||||
## Testing
|
||||
|
||||
Integration tests (real SQLite, real git) in `ClaudeDo.Worker.Tests`:
|
||||
|
||||
1. **`WorktreeManager_DiscardAsync_removes_worktree_and_branch`** — create a worktree, call Discard, assert branch is gone from `git branch --list`, folder is gone, DB state is `Discarded`.
|
||||
2. **`TaskRepository_ResetToManualAsync_clears_result_fields`** — seed a Failed task with Result/FinishedAt/StartedAt, call Reset, assert all cleared and status is Manual.
|
||||
3. **`ResetTask_full_flow`** — seed a Failed task with an Active worktree and run history; invoke the hub method; assert status=Manual, worktree=Discarded, `task_runs` rows still present.
|
||||
4. **`ResetTask_rejects_running_task`** — seed a Running task, assert the hub method throws and nothing is modified.
|
||||
5. **`ResetTask_worktree_remove_failure_leaves_task_failed`** — simulate a git failure (e.g. lock the folder), assert task stays Failed and worktree stays Active.
|
||||
|
||||
No new UI tests — the commands are thin forwarders and are exercised manually.
|
||||
|
||||
## Open questions
|
||||
|
||||
None.
|
||||
162
docs/superpowers/specs/2026-04-22-agent-settings-ui-design.md
Normal file
162
docs/superpowers/specs/2026-04-22-agent-settings-ui-design.md
Normal file
@@ -0,0 +1,162 @@
|
||||
# Design: Agent settings per list and per task (UI reimplementation)
|
||||
|
||||
Date: 2026-04-22
|
||||
Status: Approved by user, implementation pending
|
||||
|
||||
## Problem
|
||||
|
||||
During the recent UI rework, the editors for per-list and per-task agent settings were lost. The data layer and Worker still support them (`TaskEntity.Model/SystemPrompt/AgentPath`, `ListConfigEntity`, `TaskRunner` + `ClaudeArgsBuilder`), but the UI has zero references to these fields. Users currently cannot set model, custom system prompt, or agent file from the app.
|
||||
|
||||
## Goal
|
||||
|
||||
Restore the ability to configure, per **list** and per **task**:
|
||||
|
||||
- `Model` — `opus` / `sonnet` / `haiku` / inherit
|
||||
- `SystemPrompt` — free-text, appended to Claude's system prompt
|
||||
- `AgentPath` — selection from agent files discovered by the Worker under `~/.todo-app/agents/*.md`
|
||||
|
||||
Per-task values override per-list values. Per-list values override global defaults from `worker.config.json`. This cascade is already implemented in `TaskRunner`.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Agent file CRUD in the UI (read-only picker only)
|
||||
- `--allowedTools`, `--bare`, permission modes (deferred, matches existing worker design notes)
|
||||
- Any schema migration — the DB already has the required columns/tables
|
||||
|
||||
## Approach
|
||||
|
||||
**Update-and-broadcast over SignalR.** UI never touches the DB directly; all writes go through new `WorkerHub` methods. Worker persists via repositories, then broadcasts `ListUpdated` / `TaskUpdated` so connected clients refresh.
|
||||
|
||||
## Sections
|
||||
|
||||
### 1. Data layer additions
|
||||
|
||||
New repository `src/ClaudeDo.Data/Repositories/ListConfigRepository.cs`:
|
||||
|
||||
- `GetByListIdAsync(string listId, CancellationToken) -> ListConfigEntity?`
|
||||
- `UpsertAsync(ListConfigEntity, CancellationToken) -> ListConfigEntity`
|
||||
- `DeleteAsync(string listId, CancellationToken) -> bool`
|
||||
|
||||
New method on `ListRepository`:
|
||||
|
||||
- `UpdateAsync(ListEntity, CancellationToken)` — updates `Name`, `WorkingDir`, `DefaultCommitType`. Included because the consolidated list-settings modal edits these alongside agent fields.
|
||||
|
||||
New method on `TaskRepository`:
|
||||
|
||||
- `UpdateAgentSettingsAsync(string taskId, string? model, string? systemPrompt, string? agentPath, CancellationToken) -> bool`
|
||||
- `null` values mean "inherit" (column is nulled out in DB).
|
||||
- Kept as a narrow method to avoid widening `UpdateAsync`.
|
||||
|
||||
DI: register `ListConfigRepository` alongside other repos.
|
||||
|
||||
No migration — all columns/tables already exist.
|
||||
|
||||
### 2. SignalR hub surface
|
||||
|
||||
New DTOs in `src/ClaudeDo.Data/Dtos/` (project existing DTO pattern):
|
||||
|
||||
- `UpdateListDto(string Id, string Name, string? WorkingDir, string DefaultCommitType)`
|
||||
- `UpdateListConfigDto(string ListId, string? Model, string? SystemPrompt, string? AgentPath)`
|
||||
- `UpdateTaskAgentSettingsDto(string TaskId, string? Model, string? SystemPrompt, string? AgentPath)`
|
||||
|
||||
New methods on `WorkerHub`:
|
||||
|
||||
- `UpdateList(UpdateListDto dto)` — calls `ListRepository.UpdateAsync`, then broadcasts `ListUpdated(listId)`.
|
||||
- `UpdateListConfig(UpdateListConfigDto dto)` — upserts via `ListConfigRepository.UpsertAsync`, broadcasts `ListUpdated(listId)`. If all three fields are null, calls `DeleteAsync` instead so the row doesn't linger empty.
|
||||
- `UpdateTaskAgentSettings(UpdateTaskAgentSettingsDto dto)` — calls `TaskRepository.UpdateAgentSettingsAsync`, broadcasts `TaskUpdated(taskId)` (existing event).
|
||||
|
||||
New broadcast method on `HubBroadcaster`:
|
||||
|
||||
- `Task ListUpdatedAsync(string listId) => _hub.Clients.All.SendAsync("ListUpdated", listId);`
|
||||
|
||||
Loader endpoint to add:
|
||||
|
||||
- `GetListConfig(string listId)` — returns `(string? Model, string? SystemPrompt, string? AgentPath)` record, or `null` if no row. Used by `ListSettingsModal` and by `DetailsIslandViewModel` for effective-value inheritance display. Existing `GetLists` / `GetTasks` already cover the rest.
|
||||
|
||||
### 3. UI — ListSettingsModal
|
||||
|
||||
New files:
|
||||
|
||||
- `src/ClaudeDo.Ui/Views/Modals/ListSettingsModalView.axaml` + `.axaml.cs`
|
||||
- `src/ClaudeDo.Ui/ViewModels/Modals/ListSettingsModalViewModel.cs`
|
||||
|
||||
Entry points:
|
||||
|
||||
- **Right-click** on a list row in `ListsIslandView` → `ContextMenu` with "Settings…" item
|
||||
- **Gear button** on the list row (visible on hover/selected)
|
||||
|
||||
Layout: vertical stack with two grouped sections.
|
||||
|
||||
**General**
|
||||
- `Name` — TextBox (required, non-empty)
|
||||
- `Working directory` — TextBox + "Browse…" button (folder picker)
|
||||
- `Default commit type` — ComboBox populated with `chore, feat, fix, refactor, docs, test, ci, perf, style, build`
|
||||
|
||||
**Agent**
|
||||
- `Model` — ComboBox: `(default)`, `sonnet`, `opus`, `haiku` (selecting `(default)` sends `null`)
|
||||
- `System prompt` — multi-line TextBox with 4-row min height; empty = `null`
|
||||
- `Agent file` — ComboBox populated via `WorkerClient.GetAgentsAsync()`, first item `(none)`; tooltip shows each agent's `Description`. Empty selection = `null`.
|
||||
- `Reset agent settings` button — clears Model/SystemPrompt/AgentPath in the form (save then sends null triple → backend `DeleteAsync`).
|
||||
|
||||
Commands:
|
||||
|
||||
- `SaveCommand` — validates, calls `UpdateList` then `UpdateListConfig`, closes modal on success.
|
||||
- `CancelCommand` — closes without saving.
|
||||
|
||||
Loading: on open, ViewModel calls `GetListConfig` and populates fields; missing row means all three agent fields start empty.
|
||||
|
||||
ViewModel uses `[ObservableProperty]` / `[RelayCommand]` per project convention.
|
||||
|
||||
### 4. UI — DetailsIsland per-task agent section
|
||||
|
||||
Modify `DetailsIslandView.axaml` + `DetailsIslandViewModel.cs`.
|
||||
|
||||
Add an `Expander` titled **"Agent settings (overrides)"**, collapsed by default, below the existing task detail content.
|
||||
|
||||
Fields (same control types as ListSettingsModal's Agent section):
|
||||
|
||||
- `Model` — ComboBox prepended with `(inherit: <effective>)` option as the unset state
|
||||
- `System prompt` — TextBox with watermark showing effective inherited value when empty
|
||||
- `Agent file` — ComboBox prepended with `(inherit: <effective>)`
|
||||
|
||||
Effective-value computation:
|
||||
|
||||
- Server-side would be more accurate but requires a new hub call. For v1, UI computes locally: if task field is null, show the list's config value; if that's also null, show `(global default)`.
|
||||
- `DetailsIslandViewModel` already has access to the selected `TaskDto` + list; add list-config loading when task selection changes.
|
||||
|
||||
Persistence: auto-save on field change (debounced 300ms) calling `UpdateTaskAgentSettings`. No separate Save button — matches "settings" feel.
|
||||
|
||||
If the task is currently `Running`, fields are **read-only** (disabling controls). Agent settings only apply to the next invocation.
|
||||
|
||||
### 5. Testing
|
||||
|
||||
xUnit integration tests in `tests/ClaudeDo.Worker.Tests` against a real SQLite temp DB:
|
||||
|
||||
- `ListConfigRepositoryTests`
|
||||
- `UpsertAsync_InsertsWhenAbsent`
|
||||
- `UpsertAsync_UpdatesWhenPresent`
|
||||
- `DeleteAsync_RemovesRow`
|
||||
- `GetByListIdAsync_ReturnsNullWhenAbsent`
|
||||
- `ListRepositoryTests.UpdateAsync_UpdatesMutableFields`
|
||||
- `TaskRepositoryTests.UpdateAgentSettingsAsync_NullsClearColumns`
|
||||
- `WorkerHubTests` (if present pattern; otherwise via direct service call):
|
||||
- `UpdateListConfig_AllNull_DeletesRow`
|
||||
- `UpdateTaskAgentSettings_PersistsAndBroadcasts`
|
||||
|
||||
No UI tests — project has no UI test project. Build-time compile check is the only UI gate.
|
||||
|
||||
## Manual verification checklist
|
||||
|
||||
1. Open app, right-click a list → "Settings…" opens modal with correct current values.
|
||||
2. Change model to `opus`, save, reopen → model persists.
|
||||
3. Set system prompt on list, create task in list, run it → log confirms `--append-system-prompt` was passed.
|
||||
4. Select task, set per-task Model = `haiku`, run → log confirms `--model haiku` overrides list value.
|
||||
5. Unset per-task Model → effective falls back to list's model.
|
||||
6. Click "Reset agent settings" on list → row removed, tasks fall back to global defaults.
|
||||
7. Running task: DetailsIsland agent fields disabled.
|
||||
|
||||
## Risks / open questions
|
||||
|
||||
- **Refresh propagation**: `ListUpdated` is a new event; `IslandsShellViewModel` must subscribe and re-fetch. Any missed subscriber means stale UI. Mitigated by following the existing `TaskUpdated` pattern exactly.
|
||||
- **Working-dir browser**: Avalonia folder picker API needs a `TopLevel`; pass via `StorageProvider`. Standard pattern in Avalonia 12.
|
||||
- **Conventional-commit-type list**: hardcoded in ComboBox — acceptable, matches existing `CommitType` defaults.
|
||||
208
docs/superpowers/specs/2026-04-22-worktree-merge-design.md
Normal file
208
docs/superpowers/specs/2026-04-22-worktree-merge-design.md
Normal file
@@ -0,0 +1,208 @@
|
||||
# Worktree merge into target branch — design
|
||||
|
||||
Date: 2026-04-22
|
||||
Status: Approved (pending user review)
|
||||
|
||||
## Problem
|
||||
|
||||
`WorktreeState.Merged` exists but nothing sets it. `GitService.MergeFfOnlyAsync` exists but is unused. `DetailsIslandViewModel.ApproveMergeAsync` is a stub (`// TODO: call worker merge hub method when available`). Users have no way to merge a task's worktree back into a target branch; the only post-task options today are Discard (via Reset) or leave it Active.
|
||||
|
||||
## Goals
|
||||
|
||||
- Allow merging a task worktree's `claudedo/{id}` branch into a chosen local branch of the list's `WorkingDir`.
|
||||
- Preserve merge history via a real merge commit.
|
||||
- Never leave the target branch in a broken state.
|
||||
- Reuse existing patterns: `TaskResetService`, maintenance sweeper, dialog factory.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Remote push after merge (user does this manually).
|
||||
- Pull/fetch before merge.
|
||||
- Rebasing the task branch onto a moved target (done via Continue prompt or manually).
|
||||
- Merging across repos or handling submodules.
|
||||
- Automated UI tests (project has none).
|
||||
|
||||
## Decisions
|
||||
|
||||
| Decision | Choice |
|
||||
| --- | --- |
|
||||
| Target branch | Default to current `HEAD` branch of `WorkingDir`; user may override via dropdown. |
|
||||
| Merge strategy | Always `git merge --no-ff -m <msg> claudedo/{id}` — explicit merge commit. |
|
||||
| Post-merge cleanup | Per-merge checkbox in the dialog, default on: remove worktree dir + delete branch. |
|
||||
| Conflicts | Pre-flight guard (worktree/branch state checks); on conflict during merge, `git merge --abort` and return conflicted files to UI. |
|
||||
| UI entry points | Details island agent strip (wires existing stub) **and** DiffModal "Merge" button — both open the same modal. |
|
||||
|
||||
## Architecture
|
||||
|
||||
### New backend service
|
||||
|
||||
`src/ClaudeDo.Worker/Services/TaskMergeService.cs` — mirrors `TaskResetService`.
|
||||
|
||||
```
|
||||
public sealed class TaskMergeService
|
||||
{
|
||||
Task<MergeResult> MergeAsync(
|
||||
string taskId,
|
||||
string targetBranch,
|
||||
bool removeWorktree,
|
||||
string commitMessage,
|
||||
CancellationToken ct);
|
||||
|
||||
Task<MergeTargets> GetTargetsAsync(string taskId, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed record MergeResult(string Status, IReadOnlyList<string> ConflictFiles, string? ErrorMessage);
|
||||
// Status ∈ "merged" | "conflict" | "blocked"
|
||||
|
||||
public sealed record MergeTargets(string DefaultBranch, IReadOnlyList<string> LocalBranches);
|
||||
```
|
||||
|
||||
Pre-flight checks (all must pass):
|
||||
1. Task exists, status not `Running`.
|
||||
2. Worktree exists, state == `Active`.
|
||||
3. `list.WorkingDir` is set and is a git repo.
|
||||
4. Target working tree is clean (`HasChangesAsync == false`).
|
||||
5. Target repo is not mid-merge (`IsMidMergeAsync == false`).
|
||||
|
||||
Failures short-circuit to `MergeResult("blocked", [], reason)` before any git write.
|
||||
|
||||
Success path:
|
||||
1. `GitService.MergeNoFfAsync(list.WorkingDir, wt.BranchName, commitMessage, ct)`.
|
||||
2. If `removeWorktree`:
|
||||
- `WorktreeRemoveAsync(list.WorkingDir, wt.Path, force: false, ct)` — reuse existing method.
|
||||
- `BranchDeleteAsync(list.WorkingDir, wt.BranchName, force: false, ct)`.
|
||||
3. `WorktreeRepository.SetStateAsync(taskId, WorktreeState.Merged, ct)`.
|
||||
4. `HubBroadcaster.BroadcastWorktreeUpdated(taskId)`.
|
||||
5. Log info; return `MergeResult("merged", [], null)`.
|
||||
|
||||
Conflict path (merge invoked, git returns non-zero with `CONFLICT` on stderr/stdout):
|
||||
1. Collect conflicted files: `git diff --name-only --diff-filter=U`.
|
||||
2. `GitService.MergeAbortAsync(list.WorkingDir, ct)`.
|
||||
3. Worktree state stays `Active`; no broadcast (nothing changed).
|
||||
4. Return `MergeResult("conflict", files, null)`.
|
||||
|
||||
### GitService additions
|
||||
|
||||
```
|
||||
Task<string> GetCurrentBranchAsync(string repoDir, CancellationToken ct); // git symbolic-ref --short HEAD
|
||||
Task<List<string>> ListLocalBranchesAsync(string repoDir, CancellationToken ct); // git branch --format=%(refname:short)
|
||||
Task MergeNoFfAsync(string repoDir, string sourceBranch, string message, CancellationToken ct); // git merge --no-ff -m <msg> <src>
|
||||
Task MergeAbortAsync(string repoDir, CancellationToken ct); // git merge --abort
|
||||
Task<bool> IsMidMergeAsync(string repoDir, CancellationToken ct); // File.Exists($"{gitDir}/MERGE_HEAD")
|
||||
Task<List<string>> ListConflictedFilesAsync(string repoDir, CancellationToken ct); // git diff --name-only --diff-filter=U
|
||||
```
|
||||
|
||||
`MergeNoFfAsync` must NOT throw on non-zero — it must return the exit code/stderr so the caller can distinguish conflict from other failures. Two ways:
|
||||
- Overload to return `(int ExitCode, string Stderr)`; or
|
||||
- Throw a dedicated `GitMergeConflictException` vs `InvalidOperationException`.
|
||||
|
||||
**Pick:** expose a tuple-returning variant for `MergeNoFfAsync` only — keeps other methods consistent, avoids exception-for-control-flow.
|
||||
|
||||
### Hub surface
|
||||
|
||||
`src/ClaudeDo.Worker/Hub/WorkerHub.cs` gains:
|
||||
|
||||
```
|
||||
Task<MergeResultDto> MergeTask(string taskId, string targetBranch, bool removeWorktree, string commitMessage);
|
||||
Task<MergeTargetsDto> GetMergeTargets(string taskId);
|
||||
```
|
||||
|
||||
DTOs mirror the service records. Unexpected exceptions are re-wrapped as `HubException` (same pattern as `ResetTask`). Expected conditions (blocked, conflict) travel via the result DTO, not exceptions.
|
||||
|
||||
### WorkerClient
|
||||
|
||||
`src/ClaudeDo.Ui/Services/WorkerClient.cs`:
|
||||
|
||||
```
|
||||
Task<MergeResultDto> MergeTaskAsync(string taskId, string targetBranch, bool removeWorktree, string commitMessage);
|
||||
Task<MergeTargetsDto> GetMergeTargetsAsync(string taskId);
|
||||
```
|
||||
|
||||
### UI
|
||||
|
||||
**New modal:** `src/ClaudeDo.Ui/Views/Modals/MergeModalView.axaml` + `MergeModalViewModel.cs`.
|
||||
|
||||
Dialog fields:
|
||||
- **Target branch** combobox (source: `GetMergeTargetsAsync.LocalBranches`; default: `DefaultBranch`).
|
||||
- **Remove worktree after merge** checkbox (default: checked).
|
||||
- **Commit message** text field (default: `Merge task: {Task.Title}`).
|
||||
- OK / Cancel buttons.
|
||||
|
||||
Post-submit UI states (rendered inside the modal, not a second dialog):
|
||||
- `merged` → brief success line, modal closes after 1–2s; parent refreshes.
|
||||
- `conflict` → red inline panel listing files; OK button hidden, only Close remains.
|
||||
- `blocked` → orange inline panel with the reason; OK button hidden, only Close remains.
|
||||
|
||||
**Wiring:**
|
||||
- `DetailsIslandViewModel.ApproveMergeAsync` opens `MergeModalView` (factory injected through `MainWindowViewModel`'s existing dialog pattern).
|
||||
- `DiffModalView` gains a Merge button in its command strip; click opens the same modal with the current task's id.
|
||||
- Both entry points are only visible/enabled when `Task.Worktree?.State == Active` (same predicate as the existing Reset/Continue visibility logic — extend `ShowFailedActions`-style gating with a new flag `CanMerge`).
|
||||
|
||||
`MergeModalViewModel` depends only on `WorkerClient`. It does not touch `GitService` directly — all git access stays worker-side.
|
||||
|
||||
## Data flow
|
||||
|
||||
```
|
||||
User clicks Merge (Details island or DiffModal)
|
||||
→ DetailsIslandViewModel / DiffModalViewModel opens MergeModalView
|
||||
→ MergeModalViewModel.InitializeAsync
|
||||
→ WorkerClient.GetMergeTargetsAsync(taskId)
|
||||
→ Hub.GetMergeTargets
|
||||
→ TaskMergeService.GetTargetsAsync
|
||||
→ GitService.GetCurrentBranchAsync + ListLocalBranchesAsync
|
||||
→ Combobox populated, default selected
|
||||
User edits fields, clicks OK
|
||||
→ WorkerClient.MergeTaskAsync(taskId, branch, remove, msg)
|
||||
→ Hub.MergeTask
|
||||
→ TaskMergeService.MergeAsync
|
||||
→ pre-flight checks
|
||||
→ GitService.MergeNoFfAsync → (success | conflict)
|
||||
→ on success: optional remove + branch delete, SetState(Merged), broadcast
|
||||
→ on conflict: MergeAbortAsync, return conflict DTO
|
||||
→ MergeModalViewModel renders result
|
||||
```
|
||||
|
||||
## Error handling
|
||||
|
||||
| Case | Surfaced as |
|
||||
| --- | --- |
|
||||
| Task running | `MergeResult("blocked", [], "task is running")` |
|
||||
| Worktree not Active | `("blocked", [], "worktree state is {state}")` |
|
||||
| Working dir dirty | `("blocked", [], "target branch has uncommitted changes")` |
|
||||
| Target mid-merge | `("blocked", [], "target branch is mid-merge")` |
|
||||
| `list.WorkingDir` null | `("blocked", [], "list has no working directory")` |
|
||||
| Merge conflict | `("conflict", [files], null)` — target auto-restored |
|
||||
| Unknown git failure | `HubException` with stderr |
|
||||
| Post-merge cleanup fails | Log a warning; merge already succeeded, state already `Merged`. Return `("merged", [], "cleanup: {reason}")` — `Status=="merged"` with a non-null `ErrorMessage` means the merge went through but the worktree couldn't be removed. UI surfaces this as a yellow note, not a failure. |
|
||||
|
||||
## Testing
|
||||
|
||||
`tests/ClaudeDo.Worker.Tests/TaskMergeServiceTests.cs` (real SQLite + real git, matching existing test conventions):
|
||||
|
||||
1. Happy path, ff-able history → one merge commit, state Merged, broadcast fired.
|
||||
2. Happy path, diverged non-conflicting → merge commit created.
|
||||
3. Conflict path → conflicted files returned, target branch HEAD matches pre-merge, `MERGE_HEAD` absent, worktree state still Active.
|
||||
4. Pre-flight: worktree Merged/Discarded → blocked.
|
||||
5. Pre-flight: dirty working tree → blocked.
|
||||
6. Pre-flight: mid-merge target → blocked.
|
||||
7. `removeWorktree=true` → worktree dir gone, branch deleted, state Merged.
|
||||
8. `removeWorktree=false` → worktree + branch survive, state Merged.
|
||||
9. Task Running → blocked.
|
||||
|
||||
`tests/ClaudeDo.Worker.Tests/GitServiceMergeTests.cs` (narrow tests for new GitService methods): `MergeNoFfAsync` success/conflict tuple semantics, `MergeAbortAsync` clears MERGE_HEAD, `IsMidMergeAsync` true/false, `ListLocalBranchesAsync` returns expected set, `GetCurrentBranchAsync` on fresh repo.
|
||||
|
||||
Manual UI checklist captured in the implementation plan, not automated.
|
||||
|
||||
## Implementation order (sketch)
|
||||
|
||||
1. GitService additions + their tests.
|
||||
2. `TaskMergeService` + its tests (hub/UI not yet wired).
|
||||
3. Hub methods + `WorkerClient` methods.
|
||||
4. `MergeModalView` + `MergeModalViewModel`.
|
||||
5. Wire `DetailsIslandViewModel.ApproveMergeAsync`.
|
||||
6. Wire DiffModal Merge button.
|
||||
7. Manual UI walkthrough against the checklist.
|
||||
|
||||
## Open items
|
||||
|
||||
None.
|
||||
177
docs/superpowers/specs/2026-04-23-default-agents-design.md
Normal file
177
docs/superpowers/specs/2026-04-23-default-agents-design.md
Normal file
@@ -0,0 +1,177 @@
|
||||
# Default Agents — Design
|
||||
|
||||
**Date:** 2026-04-23
|
||||
**Status:** Approved
|
||||
|
||||
## Goal
|
||||
|
||||
Ship ClaudeDo with a curated set of default agents so that users have useful agents available on first launch, without losing the file-based ownership model (user-editable, user-deletable). Provide a "Restore defaults" action to recover missing defaults on demand.
|
||||
|
||||
## Agents to Ship
|
||||
|
||||
Six markdown agents covering the common stages of task execution plus one general-purpose agent:
|
||||
|
||||
| File | Focus |
|
||||
|---|---|
|
||||
| `code-reviewer.md` | Review diff for bugs, logic errors, convention adherence. Flags only high-confidence issues. |
|
||||
| `test-writer.md` | Generate unit/integration tests for changed code. Follows existing test patterns. |
|
||||
| `debugger.md` | Systematic root-cause analysis — reproduce, isolate, hypothesize, verify. |
|
||||
| `security-reviewer.md` | OWASP-style audit focused on auth, SQL injection, input handling, secret exposure. |
|
||||
| `explorer.md` | Fast codebase navigation and answering "where/how" questions. Terse output. |
|
||||
| `researcher.md` | General-purpose research, doc summarization, analysis, investigation. Non-code. |
|
||||
|
||||
Each file uses Claude Code's standard agent frontmatter:
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: <agent name>
|
||||
description: <one-line description>
|
||||
---
|
||||
|
||||
<system prompt body>
|
||||
```
|
||||
|
||||
Content target: ~20–40 lines per file. Style matches the existing Claude Code agent conventions.
|
||||
|
||||
## Behavior
|
||||
|
||||
**Seed on first launch, restore on demand:**
|
||||
|
||||
1. Bundled agents live alongside the Worker binary at `<AppContext.BaseDirectory>/DefaultAgents/*.md`.
|
||||
2. At Worker startup, for each bundled file: if `~/.todo-app/agents/<name>.md` does NOT exist, copy it in. If it exists, leave it alone — the user owns their copy.
|
||||
3. A "Restore default agents" button in the settings modal re-runs the same check, restoring any that the user has deleted.
|
||||
|
||||
The seed path and the restore path are the same code — only the invocation differs (startup vs. hub call).
|
||||
|
||||
## Components
|
||||
|
||||
### `DefaultAgents/*.md` (bundled content)
|
||||
|
||||
Location: `src/ClaudeDo.Worker/DefaultAgents/`
|
||||
Packaging: `<Content Include="DefaultAgents\*.md" CopyToOutputDirectory="PreserveNewest" />` in `ClaudeDo.Worker.csproj`.
|
||||
At runtime they land at `<AppContext.BaseDirectory>/DefaultAgents/*.md` next to the executable.
|
||||
|
||||
### `DefaultAgentSeeder` (new service)
|
||||
|
||||
Location: `src/ClaudeDo.Worker/Services/DefaultAgentSeeder.cs`
|
||||
|
||||
```
|
||||
public sealed class DefaultAgentSeeder
|
||||
{
|
||||
public DefaultAgentSeeder(string bundleDir, string targetDir);
|
||||
public Task<SeedResult> SeedMissingAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public sealed record SeedResult(int Copied, int Skipped);
|
||||
```
|
||||
|
||||
Behavior of `SeedMissingAsync`:
|
||||
- If `bundleDir` doesn't exist, log warning and return `(0, 0)`.
|
||||
- Enumerate `*.md` in `bundleDir`.
|
||||
- For each file, if the target path (`targetDir/<filename>`) is missing, copy it; else increment `Skipped`.
|
||||
- Create `targetDir` if missing (consistent with existing `AgentFileService.WriteAsync`).
|
||||
- Per-file exceptions are caught and logged; the seeder continues with the next file. The method itself does not throw for individual file failures.
|
||||
|
||||
### `Program.cs` wiring
|
||||
|
||||
After `AgentFileService` registration and before `app.Run()`:
|
||||
|
||||
```csharp
|
||||
var bundleDir = Path.Combine(AppContext.BaseDirectory, "DefaultAgents");
|
||||
var seeder = new DefaultAgentSeeder(bundleDir, agentsDir);
|
||||
await seeder.SeedMissingAsync();
|
||||
builder.Services.AddSingleton(seeder);
|
||||
```
|
||||
|
||||
The seeder is also registered as a singleton so the hub can invoke it for the restore flow.
|
||||
|
||||
### `WorkerHub.RestoreDefaultAgents`
|
||||
|
||||
Location: add method to existing `src/ClaudeDo.Worker/Hub/WorkerHub.cs`.
|
||||
|
||||
Signature: `public async Task<SeedResult> RestoreDefaultAgents()`
|
||||
|
||||
Behavior:
|
||||
- Calls `DefaultAgentSeeder.SeedMissingAsync()`.
|
||||
- Returns the `SeedResult` to the caller.
|
||||
- No separate broadcast — the UI will call `GetAgents` after the restore returns, reusing the existing refresh path.
|
||||
|
||||
### UI — Settings Modal
|
||||
|
||||
Location: `src/ClaudeDo.Ui/Views/Modals/SettingsModalView.axaml` + `SettingsModalViewModel`.
|
||||
|
||||
Add a "Restore default agents" button to the modal. On click:
|
||||
1. Disable the button, show a spinner label.
|
||||
2. Call `WorkerClient.RestoreDefaultAgentsAsync()`.
|
||||
3. Show a brief inline confirmation: `"Restored {Copied} agent(s)"` or `"All defaults already present"`.
|
||||
4. Trigger the existing agent list refresh so the new files appear immediately in the rest of the UI.
|
||||
|
||||
### `WorkerClient` method
|
||||
|
||||
Add `Task<SeedResult> RestoreDefaultAgentsAsync(CancellationToken ct = default)` to `WorkerClient` — thin wrapper that invokes the hub method.
|
||||
|
||||
## Data Flow
|
||||
|
||||
**Startup:**
|
||||
```
|
||||
Worker starts → DefaultAgentSeeder.SeedMissingAsync()
|
||||
→ copies missing files into ~/.todo-app/agents/
|
||||
AgentFileService.ScanAsync() (on first GetAgents call) → sees the seeded files
|
||||
```
|
||||
|
||||
**User restores:**
|
||||
```
|
||||
Settings modal button click
|
||||
→ WorkerClient.RestoreDefaultAgentsAsync()
|
||||
→ WorkerHub.RestoreDefaultAgents()
|
||||
→ DefaultAgentSeeder.SeedMissingAsync()
|
||||
→ returns SeedResult(copied, skipped)
|
||||
UI shows confirmation, triggers GetAgents refresh
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Failure | Behavior |
|
||||
|---|---|
|
||||
| Missing `DefaultAgents/` bundle dir | Log warning, return `(0, 0)`. Startup proceeds. |
|
||||
| Individual file copy failure (disk, permissions) | Catch per-file, log, continue with the remaining files. |
|
||||
| Corrupt bundled markdown (no valid frontmatter) | Copied anyway — the `AgentFileService` frontmatter parser already falls back to filename-as-name. |
|
||||
| Startup seeder exception (unexpected) | Log as warning, do not crash the Worker. Agents can still be restored via the button. |
|
||||
| Hub `RestoreDefaultAgents` exception | Propagate to client as SignalR error; UI shows a generic "Restore failed" message. |
|
||||
|
||||
## Testing
|
||||
|
||||
**Unit:** `tests/ClaudeDo.Worker.Tests/Services/DefaultAgentSeederTests.cs`
|
||||
|
||||
- Seeds all files when target dir is empty.
|
||||
- Skips files that already exist.
|
||||
- Preserves existing user-modified files (file mtime / content unchanged).
|
||||
- Returns accurate `SeedResult` counts.
|
||||
- Handles missing bundle dir gracefully (returns `(0, 0)`, no throw).
|
||||
- Creates target dir if it doesn't exist.
|
||||
|
||||
**Integration:** extend `tests/ClaudeDo.Worker.Tests/Hub/AgentSettingsHubTests.cs`
|
||||
|
||||
- `RestoreDefaultAgents` invokes the seeder and returns the count.
|
||||
|
||||
**No UI tests.** The project has no UI test harness; settings modal behavior is exercised manually.
|
||||
|
||||
## Build / Packaging
|
||||
|
||||
`src/ClaudeDo.Worker/ClaudeDo.Worker.csproj` gains:
|
||||
|
||||
```xml
|
||||
<ItemGroup>
|
||||
<Content Include="DefaultAgents\*.md">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
```
|
||||
|
||||
No new NuGet dependencies.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Editing bundled agents in-place (user edits their copy under `~/.todo-app/agents/`; bundle is read-only by convention).
|
||||
- Versioning / updating user copies when the bundled version changes. If a bundled agent is improved in a later release, the user's copy is not overwritten. A future release may add a "diff / reset to bundled" flow, but not now.
|
||||
- Packaging as embedded resources. Content files copied to output are simpler, inspectable on disk, and consistent with the file-based agent model.
|
||||
468
docs/superpowers/specs/2026-04-23-planning-sessions-design.md
Normal file
468
docs/superpowers/specs/2026-04-23-planning-sessions-design.md
Normal file
@@ -0,0 +1,468 @@
|
||||
# Planning Sessions — Design
|
||||
|
||||
**Status:** Approved for implementation
|
||||
**Date:** 2026-04-23
|
||||
**Scope:** Feature — "Open planning Session" context menu on tasks that spawns an interactive Windows Terminal with Claude (Sonnet 4.6, medium thinking) and a scoped MCP server, letting the user brainstorm and have Claude break a rough task into concrete executable child-tasks.
|
||||
|
||||
---
|
||||
|
||||
## 1. Goal
|
||||
|
||||
Allow a user to take a vague task (a title plus some TODO-style notes) and convert it — via interactive dialogue with Claude in a terminal — into a structured set of concrete, executable child-tasks that the worker queue can pick up and run.
|
||||
|
||||
The interaction is driven by Claude calling MCP tools against a scoped server running inside the existing `ClaudeDo.Worker` process. The parent task becomes a "Planning" container that holds its children as a flat (single-level) hierarchy.
|
||||
|
||||
---
|
||||
|
||||
## 2. Status Flow
|
||||
|
||||
**Parent (new statuses `Planning`, `Planned`):**
|
||||
|
||||
```
|
||||
Manual ──[Open planning Session]──▶ Planning ──[finalize]──▶ Planned
|
||||
│ │
|
||||
│ (all children reach terminal state)
|
||||
│ ▼
|
||||
│ Done
|
||||
│ or
|
||||
│ Failed (if any child Failed)
|
||||
▼
|
||||
[Discard] ──▶ Manual
|
||||
```
|
||||
|
||||
**Child (new status `Draft`):**
|
||||
|
||||
```
|
||||
Draft ──[finalize]──▶ Manual | Queued (if "agent" tag) ──▶ Running ──▶ Done | Failed
|
||||
```
|
||||
|
||||
**Rules:**
|
||||
- Parent with status `Planning` or `Planned` is **never** picked up by the queue.
|
||||
- Children with status `Draft` are **never** picked up by the queue.
|
||||
- Hierarchy is strictly **one level deep**: a child task cannot itself become a planning parent (enforced app-side: Plan menu item hidden/disabled if `ParentTaskId IS NOT NULL`).
|
||||
- One planning session per parent task at a time (`StartPlanningSessionAsync` errors if parent is already `Planning`; use Resume instead).
|
||||
- Parent auto-status on child completion (evaluated after any child reaches `Done` or `Failed`):
|
||||
- At least one child `Failed` and no children still in non-terminal states → Parent `Failed`.
|
||||
- All children `Done` → Parent `Done`.
|
||||
- Any child still `Manual`/`Queued`/`Running`/`Draft` → Parent stays `Planned`.
|
||||
- Worktree state (`Merged`/`Discarded`/`Kept`) is orthogonal; only `Task.Status` determines completion.
|
||||
|
||||
---
|
||||
|
||||
## 3. Data Model
|
||||
|
||||
### 3.1 Schema changes to `Tasks` table
|
||||
|
||||
| Column | Type | Nullable | Purpose |
|
||||
|---|---|---|---|
|
||||
| `ParentTaskId` | `string` (FK → `Tasks.Id`, `DeleteBehavior.Restrict`) | yes | When set, row is a child of a planning parent. NULL = top-level task. |
|
||||
| `PlanningSessionId` | `string` | yes | Claude CLI session ID captured after first run; used with `--resume`. Only set on planning parents. |
|
||||
| `PlanningSessionToken` | `string` | yes | Random 32-byte Base64 token generated per session; acts as bearer for MCP calls. NULL when no active session. |
|
||||
| `PlanningFinalizedAt` | `DateTime` | yes | Timestamp when `finalize` was called. NULL until finalized. |
|
||||
|
||||
Index: `(ParentTaskId)` for fast children lookup.
|
||||
|
||||
### 3.2 Status enum additions
|
||||
|
||||
`ClaudeDo.Data.Models.TaskStatus` gains:
|
||||
- `Planning` — parent, session active or paused, drafts may exist.
|
||||
- `Planned` — parent, finalized, children are real tasks (may still be running).
|
||||
- `Draft` — child, created during session, not yet finalized.
|
||||
|
||||
Existing values unchanged: `Manual | Queued | Running | Done | Failed`. Persisted via `ValueConverter` to string (existing convention — confirmed via `TaskEntity.cs`).
|
||||
|
||||
### 3.3 Navigation properties
|
||||
|
||||
On `TaskEntity`:
|
||||
```csharp
|
||||
public string? ParentTaskId { get; set; }
|
||||
public TaskEntity? Parent { get; set; }
|
||||
public ICollection<TaskEntity> Children { get; set; } = new List<TaskEntity>();
|
||||
public string? PlanningSessionId { get; set; }
|
||||
public string? PlanningSessionToken { get; set; }
|
||||
public DateTime? PlanningFinalizedAt { get; set; }
|
||||
```
|
||||
|
||||
In `TaskEntityConfiguration`:
|
||||
```csharp
|
||||
.HasOne(t => t.Parent)
|
||||
.WithMany(t => t.Children)
|
||||
.HasForeignKey(t => t.ParentTaskId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
```
|
||||
|
||||
**Rationale for `Restrict`:** cascade delete would orphan worktrees of in-flight child tasks. UI must handle the `DbUpdateException` and prompt the user to discard children first.
|
||||
|
||||
### 3.4 Repository additions
|
||||
|
||||
`ITaskRepository` gains:
|
||||
- `Task<IReadOnlyList<TaskEntity>> GetChildrenAsync(string parentId, CancellationToken ct)`
|
||||
- `Task<TaskEntity> CreateChildAsync(string parentId, string title, string? description, IReadOnlyList<string>? tagNames, string? commitType, CancellationToken ct)` — creates with `Status = Draft`, `ParentTaskId = parentId`.
|
||||
- `Task<int> FinalizePlanningAsync(string parentId, bool queueAgentTasks, CancellationToken ct)` — transactional: all Drafts → `Manual` (or `Queued` if tagged "agent" and `queueAgentTasks=true`), parent → `Planned`, set `PlanningFinalizedAt`, clear `PlanningSessionToken`. Returns count of finalized children.
|
||||
- `Task<bool> DiscardPlanningAsync(string parentId, CancellationToken ct)` — deletes all Drafts, parent → `Manual`, clears `PlanningSessionId/Token/FinalizedAt`.
|
||||
- `Task<TaskEntity?> SetPlanningStartedAsync(string taskId, string sessionToken, CancellationToken ct)` — sets parent `Status = Planning`, stores token; returns null if parent not in `Manual` state.
|
||||
- `Task UpdatePlanningSessionIdAsync(string parentId, string sessionId, CancellationToken ct)` — captures Claude CLI session ID after launch.
|
||||
- `Task<TaskEntity?> FindByPlanningTokenAsync(string token, CancellationToken ct)` — used by MCP auth handler.
|
||||
|
||||
`GetNextQueuedAgentTaskAsync` — verify the existing query filters on `Status = Queued`; no additional filter needed since Planning/Planned/Draft are different statuses. Add explicit regression test.
|
||||
|
||||
### 3.5 Auto-status hook
|
||||
|
||||
After every `MarkDoneAsync`/`MarkFailedAsync` on a task with `ParentTaskId != null`, check parent children. If all in terminal state:
|
||||
- Any `Failed` → parent `Failed` with `FinishedAt = now()`.
|
||||
- All `Done` (or worktrees `Discarded`) → parent `Done` with `FinishedAt = now()`.
|
||||
|
||||
Implemented as a private helper `TryCompleteParentAsync(string parentId, CancellationToken ct)` called at the end of the two Mark methods.
|
||||
|
||||
### 3.6 Migration
|
||||
|
||||
`dotnet ef migrations add AddPlanningSupport` — adds four columns and the `(ParentTaskId)` index. No data migration needed (new columns all nullable).
|
||||
|
||||
---
|
||||
|
||||
## 4. MCP Server Surface
|
||||
|
||||
### 4.1 Transport
|
||||
|
||||
**HTTP (streamable) inside the existing Worker Kestrel host.** Mount on `/mcp` alongside the existing SignalR hub at `127.0.0.1:47821`. No separate process, no stdio proxy.
|
||||
|
||||
Library: `ModelContextProtocol` (official C# MCP SDK).
|
||||
|
||||
### 4.2 Authentication
|
||||
|
||||
Per-session bearer token:
|
||||
1. `StartPlanningSessionAsync` generates a 32-byte random token, persists to `Tasks.PlanningSessionToken`.
|
||||
2. Token is written into the session's `mcp.json` as `Authorization: Bearer <token>`.
|
||||
3. Every MCP request passes through an auth filter that looks up the token via `FindByPlanningTokenAsync`. If found, the parent task ID is stored in the request context. If not, 401.
|
||||
4. Token is invalidated (set NULL) on `finalize` or `discard`.
|
||||
|
||||
### 4.3 Tools
|
||||
|
||||
All tools are scoped to the parent task resolved from the request's token. `parent_id` is never an argument.
|
||||
|
||||
| Tool | Params | Returns | Effect |
|
||||
|---|---|---|---|
|
||||
| `create_child_task` | `title: string`, `description?: string`, `tags?: string[]`, `commit_type?: string` | `{ task_id, status: "Draft" }` | Creates a Draft child under this session's parent. |
|
||||
| `list_child_tasks` | — | `[{ task_id, title, description, status, tags }]` | Lists children of this parent (in session context, always Drafts). |
|
||||
| `update_child_task` | `task_id: string`, optional: `title`, `description`, `tags`, `commit_type` | `{ task }` | Errors if target is not a Draft or not a child of this parent. |
|
||||
| `delete_child_task` | `task_id: string` | `{ ok: true }` | Errors if target is not a Draft or not a child of this parent. |
|
||||
| `update_planning_task` | `title?: string`, `description?: string` | `{ task }` | Only title/description on the parent itself. |
|
||||
| `finalize` | `queue_agent_tasks?: bool = true` | `{ finalized_count: int }` | Calls `FinalizePlanningAsync`. Token invalidated. |
|
||||
|
||||
### 4.4 Real-time UI
|
||||
|
||||
After each successful tool call, the MCP handler fires a `TaskUpdated` event on the Worker's SignalR hub. The UI subscribes as it already does; drafts appear/update live in the tasks list while the user chats with Claude in the terminal.
|
||||
|
||||
### 4.5 Errors
|
||||
|
||||
- 401 for missing/invalid token.
|
||||
- MCP error `-32602` "task not found or not a child of this planning session" for cross-parent access attempts.
|
||||
- MCP error `-32602` "cannot modify finalized task" for `update/delete` on non-Draft.
|
||||
- Token validation short-circuits before tool dispatch.
|
||||
|
||||
---
|
||||
|
||||
## 5. Terminal Launch & Claude CLI Invocation
|
||||
|
||||
### 5.1 Launcher service
|
||||
|
||||
New interface `IPlanningTerminalLauncher` in the UI or App layer:
|
||||
```csharp
|
||||
Task LaunchAsync(PlanningSessionStart info, CancellationToken ct);
|
||||
Task LaunchResumeAsync(PlanningSessionResume info, CancellationToken ct);
|
||||
```
|
||||
|
||||
`PlanningSessionStart` contains: `WorkingDir`, `McpConfigPath`, `InitialPromptPath`, `SystemPromptPath`.
|
||||
`PlanningSessionResume` contains: `WorkingDir`, `McpConfigPath`, `ClaudeSessionId`.
|
||||
|
||||
### 5.2 Per-session files
|
||||
|
||||
Path: `~/.todo-app/planning-sessions/<parentTaskId>/`
|
||||
- `mcp.json` — MCP config referencing the HTTP endpoint with bearer token.
|
||||
- `system-prompt.md` — planning-mode system prompt (append, not replace).
|
||||
- `initial-prompt.txt` — first user-visible message (title + description + short instructions).
|
||||
|
||||
Cleanup:
|
||||
- `Discard` → remove directory.
|
||||
- `Finalize` → keep directory (for audit; prune on app start if older than N days, optional).
|
||||
|
||||
### 5.3 `mcp.json` format
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"claudedo": {
|
||||
"type": "http",
|
||||
"url": "http://127.0.0.1:47821/mcp",
|
||||
"headers": { "Authorization": "Bearer <PlanningSessionToken>" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5.4 Claude CLI invocation (new session)
|
||||
|
||||
```
|
||||
wt.exe -d "<list.WorkingDir>" cmd /k ^
|
||||
claude ^
|
||||
--model claude-sonnet-4-6 ^
|
||||
--append-system-prompt "<contents of system-prompt.md>" ^
|
||||
--mcp-config "<mcp.json absolute path>" ^
|
||||
--allowedTools "mcp__claudedo__*,Read,Grep,Glob,WebFetch,WebSearch,Skill" ^
|
||||
"<contents of initial-prompt.txt>"
|
||||
```
|
||||
|
||||
### 5.5 Claude CLI invocation (resume)
|
||||
|
||||
```
|
||||
wt.exe -d "<list.WorkingDir>" cmd /k ^
|
||||
claude --resume <PlanningSessionId> --mcp-config "<mcp.json>"
|
||||
```
|
||||
Resume inherits model, system prompt, and allowed tools from the original session.
|
||||
|
||||
### 5.6 System prompt (draft, refined in Plan B)
|
||||
|
||||
> You are in a ClaudeDo planning session for a task. Your job is to brainstorm with the user, then break their rough intent into concrete, independently-executable child-tasks. Each child-task should be something a single automated agent can pick up and complete autonomously. Use the `mcp__claudedo__*` tools to create/update/delete drafts in real time. You may read the repository for context (Read/Grep/Glob) but must not modify any files. When the user is satisfied, call `finalize`. Skills you may find useful: `superpowers:writing-plans`, `superpowers:writing-clearly-and-concisely`.
|
||||
|
||||
### 5.7 Initial prompt (template)
|
||||
|
||||
```
|
||||
<Parent task title>
|
||||
|
||||
<Parent task description, if any>
|
||||
|
||||
---
|
||||
We're planning this task together. Brainstorm with me, then create concrete child-tasks via the MCP tools. I'll call `finalize` when we're done.
|
||||
```
|
||||
|
||||
### 5.8 Unknowns to resolve during Plan B implementation
|
||||
|
||||
These are left **open** in this spec; they'll be pinned down during implementation via `mcp__plugin_context7_context7__query-docs` for the Claude Code CLI:
|
||||
|
||||
1. Exact flag for thinking budget (`--thinking-budget medium`? model suffix `claude-sonnet-4-6-thinking`? something else?).
|
||||
2. Exact casing of tool names in `--allowedTools` (`Read`/`read`, `WebFetch`/`web_fetch`, `Skill`).
|
||||
3. Whether `--append-system-prompt` accepts a file reference (`@path`) or requires inline string.
|
||||
4. Whether Claude CLI supports a `--session-id` flag for pre-assigning the session ID, or whether we must read it back from `~/.claude/projects/<hash>/sessions/` after the process starts.
|
||||
|
||||
If (4) resolves to "read back", strategy:
|
||||
- Poll `~/.claude/projects/<hash>/sessions/` directory modtimes shortly after launch; newest session file after launch timestamp is ours.
|
||||
- Cache the result on the parent task via `UpdatePlanningSessionIdAsync`.
|
||||
- If session ID can't be captured, Resume falls back to `claude --continue` (last session in that project).
|
||||
|
||||
### 5.9 Pre-flight checks
|
||||
|
||||
On `LaunchAsync`:
|
||||
- `wt.exe` resolvable in PATH → else throw `PlanningLaunchException("Windows Terminal not found")`, UI shows install hint.
|
||||
- `claude` resolvable in PATH → else `PlanningLaunchException("Claude CLI not installed")`.
|
||||
- `list.WorkingDir` exists → else `PlanningLaunchException("Working directory not found: <path>")`.
|
||||
|
||||
---
|
||||
|
||||
## 6. UI Changes
|
||||
|
||||
### 6.1 Context menu (`TaskRowView.axaml`)
|
||||
|
||||
New entries, conditional on status:
|
||||
- `Manual` + `ParentTaskId IS NULL` → **"Open planning Session"**
|
||||
- `Planning` → **"Resume planning Session"** and **"Discard planning session"**
|
||||
- `Planned` / `Done` / `Failed` (parent) → no planning-related entries (7c: no re-planning).
|
||||
- Children (`ParentTaskId IS NOT NULL`) → never show planning entries.
|
||||
|
||||
### 6.2 Hierarchy rendering (`TasksIslandView.axaml`)
|
||||
|
||||
Approach: **flat stream with indentation**, not a `TreeView`.
|
||||
|
||||
- `TasksIslandViewModel` builds `OpenItems`/`CompletedItems`/etc. as flat `ObservableCollection<TaskRowViewModel>` with parents followed by their children if expanded.
|
||||
- `TaskRowViewModel` gets `IsChild: bool` and `IsPlanningParent: bool` and `IsExpanded: bool`.
|
||||
- `TaskRowView` indents 24px when `IsChild`, shows a thin left border in `TextFaintBrush`.
|
||||
- Parents with `IsPlanningParent` render a chevron (▸/▾) that toggles `IsExpanded`; collapsed parents hide their children from the flat stream.
|
||||
- Expanded-state map kept in the VM (`Dictionary<string, bool>`, default `true`).
|
||||
|
||||
### 6.3 Draft and planning styling (`TaskRowView`)
|
||||
|
||||
- `Status = Draft` → row italic, 70% opacity, small left-aligned badge "DRAFT".
|
||||
- Parent `Status = Planning` → badge "PLANNING" (accent: warning-amber).
|
||||
- Parent `Status = Planned` → badge "PLANNED" (accent: neutral-blue).
|
||||
|
||||
### 6.4 Unfinished-session dialog
|
||||
|
||||
Trigger: on app start **and** on any context-menu click against a `Planning` parent.
|
||||
|
||||
Modal (built with existing `TaskCompletionSource<T>` dialog pattern):
|
||||
|
||||
```
|
||||
Unfinished planning session
|
||||
"<Parent title>"
|
||||
<N> draft tasks waiting to be finalized.
|
||||
|
||||
[Resume] [Finalize now] [Discard]
|
||||
```
|
||||
|
||||
- Resume → `ResumePlanningSessionAsync`, opens terminal with `--resume`.
|
||||
- Finalize now → `FinalizePlanningSessionAsync` (server-side, no terminal). Useful when the user is confident drafts are good.
|
||||
- Discard → `DiscardPlanningSessionAsync`.
|
||||
|
||||
### 6.5 TasksIslandViewModel commands
|
||||
|
||||
- `[RelayCommand] OpenPlanningSessionAsync(TaskRowViewModel? row)`
|
||||
- `[RelayCommand] ResumePlanningSessionAsync(TaskRowViewModel? row)`
|
||||
- `[RelayCommand] DiscardPlanningSessionAsync(TaskRowViewModel? row)`
|
||||
- `[RelayCommand] FinalizePlanningSessionAsync(TaskRowViewModel? row)`
|
||||
- `[RelayCommand] ToggleExpand(TaskRowViewModel parentRow)`
|
||||
|
||||
### 6.6 WorkerClient additions (`ClaudeDo.Ui/Services/WorkerClient.cs`)
|
||||
|
||||
- `Task<PlanningSessionLaunchInfo> StartPlanningSessionAsync(string taskId, CancellationToken ct)` — returns `{ WorkingDir, McpConfigPath, InitialPromptPath, SystemPromptPath }`.
|
||||
- `Task<PlanningSessionResumeInfo> ResumePlanningSessionAsync(string taskId, CancellationToken ct)` — returns `{ WorkingDir, McpConfigPath, ClaudeSessionId }`.
|
||||
- `Task<int> FinalizePlanningSessionAsync(string taskId, CancellationToken ct)` — returns finalized count.
|
||||
- `Task DiscardPlanningSessionAsync(string taskId, CancellationToken ct)`.
|
||||
- `Task<int> GetPendingDraftCountAsync(string taskId, CancellationToken ct)` — for the unfinished-session dialog.
|
||||
|
||||
Existing `TaskUpdated` event covers live draft updates; no new event needed.
|
||||
|
||||
### 6.7 Delete handling
|
||||
|
||||
When the user tries to delete a parent with children:
|
||||
- Repository throws `DbUpdateException` (FK Restrict).
|
||||
- UI catches, shows: "This task has N child tasks. Discard drafts and delete? / Delete all including children? / Cancel."
|
||||
- "Delete all including children" → UI iterates children and deletes them first, then the parent.
|
||||
- "Discard drafts" option only appears if parent status is `Planning` (drafts exist to discard).
|
||||
|
||||
---
|
||||
|
||||
## 7. Lifecycle & Error Handling
|
||||
|
||||
### 7.1 Worker queue isolation
|
||||
|
||||
`GetNextQueuedAgentTaskAsync` filters on `Status = Queued` — Planning/Planned/Draft are excluded by status. Add explicit regression test to lock this in.
|
||||
|
||||
### 7.2 Parent auto-completion (repeat of 2, for implementation reference)
|
||||
|
||||
After `MarkDoneAsync`/`MarkFailedAsync`:
|
||||
```csharp
|
||||
if (task.ParentTaskId is not null)
|
||||
await TryCompleteParentAsync(task.ParentTaskId, ct);
|
||||
```
|
||||
where `TryCompleteParentAsync` loads children, checks terminal status, sets parent accordingly.
|
||||
|
||||
### 7.3 Session-start errors
|
||||
|
||||
Table in §5.9 Pre-flight checks. UI receives typed exceptions, shows appropriate dialog.
|
||||
|
||||
### 7.4 Session-runtime errors
|
||||
|
||||
- Terminal crashes → drafts + token persist. Resume via dialog (§6.4).
|
||||
- Worker restart → drafts + token persist. Resume rebuilds HTTP connection.
|
||||
- MCP call fails transiently → Claude CLI retries or the model reports the error to the user in terminal; drafts remain in whatever state the last successful call left them.
|
||||
- No session timeout — brainstorming may be long.
|
||||
|
||||
### 7.5 Concurrency
|
||||
|
||||
- Different parents → independent sessions, one token per parent.
|
||||
- Same parent launched twice → `StartPlanningSessionAsync` throws; UI says "Already planning; use Resume".
|
||||
- Cleanup on app exit: nothing — planning state is fully persisted in DB and files.
|
||||
|
||||
---
|
||||
|
||||
## 8. Testing
|
||||
|
||||
### 8.1 Automated (in `ClaudeDo.Worker.Tests`)
|
||||
|
||||
**Schema & repository:**
|
||||
- Migration applies cleanly on fresh DB.
|
||||
- `GetChildrenAsync` returns only direct children, sorted.
|
||||
- `CreateChildAsync` sets Status=Draft, ParentTaskId correctly.
|
||||
- `FinalizePlanningAsync` transactionally transitions drafts to Manual/Queued, sets parent to Planned, sets timestamp, clears token. On simulated DB error, rolls back fully.
|
||||
- `DiscardPlanningAsync` removes drafts, resets parent.
|
||||
- `GetNextQueuedAgentTaskAsync` ignores Drafts, Planning parents, Planned parents.
|
||||
- `Restrict` cascade: delete parent with children throws `DbUpdateException`.
|
||||
|
||||
**Auto-status hook (§7.2):**
|
||||
- All children Done → parent Done.
|
||||
- Mix: some Done, at least one Failed, rest in terminal state → parent Failed.
|
||||
- Mix with one still Running → parent stays Planned.
|
||||
- Parent stays Planned while any Draft exists (defensive — finalize should have cleared them).
|
||||
|
||||
**MCP handlers (against SQLite + in-process HTTP):**
|
||||
- Valid token → tool executes.
|
||||
- Missing/invalid token → 401.
|
||||
- `create_child_task` → creates Draft, emits TaskUpdated event.
|
||||
- `update_child_task` on non-Draft → MCP error.
|
||||
- `delete_child_task` on non-Draft → MCP error.
|
||||
- `finalize` called twice: first succeeds, second errors because token is invalidated.
|
||||
- Cross-parent access: tool with `task_id` belonging to another parent's session → MCP error.
|
||||
|
||||
**SignalR endpoints (integration with Worker host):**
|
||||
- Start → token generated, session directory + files created, `mcp.json` contains token.
|
||||
- Start on already-`Planning` parent → error.
|
||||
- Resume → no new token, reads `PlanningSessionId` from DB.
|
||||
- Discard → drafts gone, directory removed, token NULL, parent back to Manual.
|
||||
|
||||
### 8.2 Manual (added to `docs/open.md` checklist)
|
||||
|
||||
- Windows Terminal spawn with real `wt.exe`.
|
||||
- Real Claude CLI end-to-end session (requires `ANTHROPIC_API_KEY`).
|
||||
- Avalonia hierarchy rendering (chevron, indentation, draft styling, badges).
|
||||
- Session-ID capture from `~/.claude/projects/...` (timing-sensitive, platform-specific).
|
||||
|
||||
---
|
||||
|
||||
## 9. Phasing
|
||||
|
||||
Work is delivered in **three sequential-then-parallel** plans. Plan A must merge before B and C can merge.
|
||||
|
||||
### 9.1 Plan A — Foundation
|
||||
|
||||
Schema migration, enum additions, repository methods, auto-status hook, delete-Restrict, regression test for queue filter. No UI-visible changes (other than delete-with-children now failing with a generic error until Plan C handles it).
|
||||
|
||||
Scope files (approximate):
|
||||
- `src/ClaudeDo.Data/Models/TaskEntity.cs`
|
||||
- `src/ClaudeDo.Data/Configuration/TaskEntityConfiguration.cs`
|
||||
- `src/ClaudeDo.Data/Migrations/<new>_AddPlanningSupport.cs`
|
||||
- `src/ClaudeDo.Data/Repositories/TaskRepository.cs` (+ `ITaskRepository`)
|
||||
- `src/ClaudeDo.Worker/...` auto-status hook call-site updates.
|
||||
- `tests/ClaudeDo.Worker.Tests/...` new test classes.
|
||||
|
||||
### 9.2 Plan B — Worker MCP + SignalR + Launcher (starts after A merges)
|
||||
|
||||
MCP service with HTTP transport, token auth, six tools. New SignalR hub endpoints for Start/Resume/Discard/Finalize/GetPendingDraftCount. Session directory management. `IPlanningTerminalLauncher` implementation for `wt.exe`. Resolves the four unknowns from §5.8.
|
||||
|
||||
Scope files (approximate):
|
||||
- `src/ClaudeDo.Worker/Planning/PlanningMcpService.cs` (new)
|
||||
- `src/ClaudeDo.Worker/Planning/PlanningSessionManager.cs` (new)
|
||||
- `src/ClaudeDo.Worker/Hub/WorkerHub.cs` (extend)
|
||||
- `src/ClaudeDo.Worker/Program.cs` (DI + endpoint mapping)
|
||||
- `src/ClaudeDo.App/` or `src/ClaudeDo.Ui/Services/` — `IPlanningTerminalLauncher` + `WindowsTerminalPlanningLauncher`.
|
||||
- `tests/ClaudeDo.Worker.Tests/Planning/...`
|
||||
|
||||
### 9.3 Plan C — UI (parallel to B after A merges)
|
||||
|
||||
Context menu entries, hierarchy rendering, draft styling, unfinished-session dialog, WorkerClient extensions, delete-with-children handling. During parallel development, mocks the WorkerClient against Plan B's interface contract.
|
||||
|
||||
Scope files (approximate):
|
||||
- `src/ClaudeDo.Ui/ViewModels/Islands/TasksIslandViewModel.cs`
|
||||
- `src/ClaudeDo.Ui/ViewModels/Islands/TaskRowViewModel.cs`
|
||||
- `src/ClaudeDo.Ui/Views/Islands/TasksIslandView.axaml`
|
||||
- `src/ClaudeDo.Ui/Views/Islands/TaskRowView.axaml`
|
||||
- `src/ClaudeDo.Ui/Services/WorkerClient.cs`
|
||||
- `src/ClaudeDo.Ui/Design/IslandStyles.axaml` (draft/badge styling)
|
||||
- `src/ClaudeDo.Ui/Views/Dialogs/UnfinishedPlanningDialog.axaml` (new)
|
||||
|
||||
### 9.4 Integration points between B and C
|
||||
|
||||
Interface contract locked before parallel work begins:
|
||||
- SignalR method names, parameters, return DTOs (listed in §6.6).
|
||||
- `TaskUpdated` event payload unchanged; carries the task's new parent-id and status so the UI can re-bucket.
|
||||
- Session directory path shape: `~/.todo-app/planning-sessions/<parentTaskId>/`.
|
||||
- `mcp.json` and session-file formats are internal to Plan B; UI never reads them.
|
||||
|
||||
---
|
||||
|
||||
## 10. Out of scope (for now)
|
||||
|
||||
- Nested planning (children of children). Explicitly one level.
|
||||
- Cross-list planning (parent in list A, children in list B).
|
||||
- Multi-user collaboration on the same planning session.
|
||||
- Session timeouts / auto-discard.
|
||||
- Planning-session history / audit UI. Directory is kept on finalize but not surfaced.
|
||||
- Re-planning a finalized parent (7c: no).
|
||||
230
docs/superpowers/specs/2026-04-23-self-update-design.md
Normal file
230
docs/superpowers/specs/2026-04-23-self-update-design.md
Normal file
@@ -0,0 +1,230 @@
|
||||
# Self-Update for App and Installer — Design
|
||||
|
||||
**Date:** 2026-04-23
|
||||
**Status:** Approved
|
||||
|
||||
## Goals
|
||||
|
||||
Give ClaudeDo two update paths:
|
||||
|
||||
- **A — App-side update check:** the Avalonia UI checks Gitea for a newer release on startup (and via a manual menu action) and surfaces a dismissible banner. Clicking **Update now** launches the locally installed installer in Update mode and closes the UI.
|
||||
- **B — Installer self-update:** the WPF installer checks for a newer installer binary on launch and offers to replace itself before continuing. After replacement, it proceeds with its normal wizard.
|
||||
|
||||
Non-goals:
|
||||
|
||||
- No silent/background auto-apply of updates. The user always initiates the final update action.
|
||||
- No periodic in-app polling (startup + manual only).
|
||||
- No changes to the release pipeline — release assets (`ClaudeDo-<version>-win-x64.zip`, `ClaudeDo.Installer-<version>.exe`, `checksums.txt`) stay as they are.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
A new shared library, `ClaudeDo.Releases`, hosts the release-API client, version comparison, checksum verification, and installer self-update logic. Both `ClaudeDo.Installer` and `ClaudeDo.Ui` reference it. This removes the existing duplication between the installer's release plumbing and what the app needs, and keeps a single asset-matching / version-parsing code path.
|
||||
|
||||
```
|
||||
ClaudeDo.Releases (new, netstandard2.0 or net8.0)
|
||||
├── ReleaseClient.cs (moved from Installer/Core)
|
||||
├── IReleaseClient.cs (moved)
|
||||
├── ChecksumVerifier.cs (moved)
|
||||
├── VersionComparer.cs (new)
|
||||
└── SelfUpdater.cs (new — installer self-update mechanism)
|
||||
|
||||
ClaudeDo.Installer (WPF, consumes ClaudeDo.Releases)
|
||||
├── App.xaml.cs (modified — SelfUpdater + --replace-self arg)
|
||||
└── Core/InstallModeDetector.cs (modified — now uses VersionComparer)
|
||||
|
||||
ClaudeDo.Ui (Avalonia, consumes ClaudeDo.Releases)
|
||||
├── Services/UpdateCheckService.cs (new)
|
||||
├── Services/InstallerLocator.cs (new)
|
||||
├── ViewModels/MainViewModel.cs (modified — banner + Help menu state)
|
||||
└── Views/MainWindow.axaml (modified — banner + Help dropdown)
|
||||
```
|
||||
|
||||
## Part A — App-Side Update Check
|
||||
|
||||
### `ClaudeDo.Ui/Services/UpdateCheckService.cs`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Read the current app version from `Assembly.GetExecutingAssembly().GetName().Version`.
|
||||
- Call `IReleaseClient.GetLatestReleaseAsync` to fetch the Gitea release.
|
||||
- Use `VersionComparer` to decide whether the latest is newer.
|
||||
- Expose observable properties: `IsUpdateAvailable`, `LatestVersion`, `CurrentVersion`, `IsChecking`, `LastCheckStatus` (`UpToDate | UpdateAvailable | CheckFailed | NeverChecked`).
|
||||
- Expose a `CheckNowAsync` method for the manual Help menu action.
|
||||
|
||||
Lifecycle:
|
||||
|
||||
- Registered as a singleton in DI.
|
||||
- Startup check is fired from `MainViewModel` once the main window is shown. It runs fire-and-forget on a background `Task`; UI never blocks on it.
|
||||
- Manual check is awaited by its command and briefly shows a status message (see UI).
|
||||
|
||||
Error handling:
|
||||
|
||||
- Network / API errors → log to `~/.todo-app/logs/`, set `LastCheckStatus = CheckFailed`, do not surface a banner. Manual check shows a small inline status only.
|
||||
|
||||
### `ClaudeDo.Ui/Services/InstallerLocator.cs`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Resolve the path to the installed `ClaudeDo.Installer.exe` so the UI can launch it.
|
||||
|
||||
Discovery strategy (first hit wins):
|
||||
|
||||
1. Walk up from `AppContext.BaseDirectory` looking for a sibling `install.json`. The installer is at `{installDir}/uninstaller/ClaudeDo.Installer.exe`.
|
||||
2. Fall back to reading `HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\ClaudeDo\InstallLocation` (written by the existing `WriteUninstallRegistryStep`).
|
||||
|
||||
If neither yields a valid path, the banner's **Update now** button is disabled with a tooltip explaining the installer could not be located.
|
||||
|
||||
### UI changes
|
||||
|
||||
**Banner** at the top of `MainView` (above content, below custom chrome):
|
||||
|
||||
- Visible when `UpdateCheckService.IsUpdateAvailable == true` and the user has not dismissed this session.
|
||||
- Text: `Update available: v{CurrentVersion} → v{LatestVersion}`.
|
||||
- Actions: `Update now` (primary), `Dismiss` (sets a transient `IsBannerDismissed` flag that resets on app restart — intentionally not persisted so the banner returns next launch if still relevant).
|
||||
- Styled to match existing chrome/accent conventions (compact, dismissible, non-modal).
|
||||
|
||||
**Help dropdown** in the custom titlebar:
|
||||
|
||||
- New menu: `Help`.
|
||||
- First item: `Check for updates` → binds to `MainViewModel.CheckForUpdatesCommand`, which calls `UpdateCheckService.CheckNowAsync`.
|
||||
- When a check completes:
|
||||
- `UpdateAvailable` → banner appears (no separate dialog).
|
||||
- `UpToDate` → a brief inline status in the banner area: `You're up to date (v{CurrentVersion})`, auto-hides after ~3 seconds.
|
||||
- `CheckFailed` → `Could not check for updates` inline message, auto-hides after ~3 seconds.
|
||||
- Leaves room for future items (`About`, `Documentation`, etc.).
|
||||
|
||||
### Update action flow
|
||||
|
||||
1. User clicks **Update now** in the banner.
|
||||
2. `MainViewModel` resolves the installer path via `InstallerLocator`.
|
||||
3. UI spawns `ClaudeDo.Installer.exe` with no arguments. The installer's existing `InstallModeDetector` reads `install.json` alongside it, hits Gitea, and enters `Update` mode.
|
||||
4. UI closes itself immediately after spawning the process.
|
||||
5. The installer performs its standard update flow: `StopServiceStep` → `DownloadAndExtractStep` → `StartServiceStep`.
|
||||
6. When the user clicks Finish the installer exits. The user re-launches the app via their existing shortcut.
|
||||
|
||||
No IPC between UI and installer is needed — the installer is already self-sufficient once launched against an existing install directory.
|
||||
|
||||
## Part B — Installer Self-Update
|
||||
|
||||
### `ClaudeDo.Releases/SelfUpdater.cs`
|
||||
|
||||
Runs from `ClaudeDo.Installer/App.xaml.cs` before any window is shown.
|
||||
|
||||
Flow:
|
||||
|
||||
1. **Handle `--replace-self` argument first.** If the installer was launched with `--replace-self "<old-path>"`:
|
||||
- Wait up to 5 seconds for the old process to exit (poll for file lock release).
|
||||
- Delete `<old-path>`.
|
||||
- Copy own exe to `<old-path>`.
|
||||
- Start a new process at `<old-path>` with no args, then exit the current (temp) process. This ensures the user's shortcut or Apps & Features entry now points at the updated binary.
|
||||
- If any step fails, fall through to the normal wizard (the user still has a working installer, just in a temp location).
|
||||
|
||||
2. **Check for a newer installer.** If no `--replace-self` arg:
|
||||
- Parse own assembly version.
|
||||
- Fetch latest release.
|
||||
- Find the installer asset matching `ClaudeDo.Installer-<version>.exe` (regex: `^ClaudeDo\.Installer-(?<version>[\d\.]+)\.exe$`).
|
||||
- Compare via `VersionComparer`.
|
||||
- If not newer, or if check fails, proceed to the normal wizard (existing Config-mode fallback behavior).
|
||||
|
||||
3. **Prompt if newer.** Show a small modal dialog (plain WPF `Window`, reusing the installer's titlebar/accent styles):
|
||||
> *"A newer installer is available: v{latest}. Update before continuing?"*
|
||||
> `[Update] [Continue anyway] [Cancel]`
|
||||
|
||||
- **Cancel** → `Application.Current.Shutdown(0)`.
|
||||
- **Continue anyway** → proceed to normal wizard.
|
||||
- **Update** → run relaunch sequence.
|
||||
|
||||
4. **Relaunch sequence:**
|
||||
- Download to `%TEMP%\ClaudeDo.Installer-<version>.exe` (show a minimal inline progress UI; no separate window).
|
||||
- Verify against `checksums.txt` from the release via `ChecksumVerifier`. On failure, show error with `[Continue with current installer]` action → proceed to wizard.
|
||||
- `Process.Start` new exe with args `--replace-self "<current-exe-path>"`.
|
||||
- Exit current process.
|
||||
|
||||
### Why `--replace-self` rather than a shell script
|
||||
|
||||
A child process holding a handle to the new exe is reliable cross-Windows-version. Relying on a `.bat` or `cmd /c` helper leaves a file that we would need to clean up, and behaves badly when the installer was launched from a mounted share or non-ASCII path. The `--replace-self` approach keeps everything in managed code and uses a single exe throughout.
|
||||
|
||||
### Edge case: running from `uninstaller/` copy
|
||||
|
||||
When the installer runs from `{installDir}/uninstaller/ClaudeDo.Installer.exe` (via the app's **Update now** or from Apps & Features), the self-update flow is identical. It is desirable for the uninstaller copy to be kept current — stale uninstaller binaries would otherwise drift behind and could have bugs the new app release expects fixed.
|
||||
|
||||
## Version Comparison (`VersionComparer`)
|
||||
|
||||
Centralizes the logic currently in `InstallModeDetector.IsNewer`:
|
||||
|
||||
- Parses both versions as `System.Version` after trimming a leading `v` / `V`.
|
||||
- Returns `(bool isNewer, bool unparseable)`.
|
||||
- Unparseable (e.g. `0.2.0-beta`) → treated as not newer; callers can surface a hint if desired.
|
||||
|
||||
Both `InstallModeDetector` (existing behavior) and `SelfUpdater` / `UpdateCheckService` (new callers) share this logic.
|
||||
|
||||
## Error Handling Summary
|
||||
|
||||
| Scenario | App behavior | Installer behavior |
|
||||
|---|---|---|
|
||||
| Gitea unreachable | Silent; log to file; no banner | Silent; skip self-update; proceed to wizard |
|
||||
| JSON parse error | Same as unreachable | Same as unreachable |
|
||||
| Version unparseable | No banner; log a hint | No prompt; proceed |
|
||||
| Installer exe not found on disk | `Update now` button disabled with tooltip | N/A |
|
||||
| Download fails | N/A (app delegates to installer) | Error dialog with `[Continue with current installer]` |
|
||||
| Checksum mismatch | N/A | Error dialog with `[Continue with current installer]` |
|
||||
| Relaunch fails | N/A | Error dialog; user keeps temp exe and current exe both |
|
||||
|
||||
## Testing
|
||||
|
||||
**New test project: `tests/ClaudeDo.Releases.Tests`**
|
||||
|
||||
- `ReleaseClientTests` — move existing installer tests covering `GetLatestReleaseAsync` and `DownloadAsync`.
|
||||
- `VersionComparerTests` — boundary cases (equal, newer, older, unparseable, mixed `v`-prefix).
|
||||
- `SelfUpdaterTests`:
|
||||
- Asset-name regex correctly isolates version from `ClaudeDo.Installer-0.3.0.exe` and ignores `ClaudeDo-0.3.0-win-x64.zip`.
|
||||
- Decision logic given mocked `IReleaseClient` responses.
|
||||
- `--replace-self` handler: given a temp dummy file, the handler waits, deletes, copies — verified with a mock filesystem / temp dir.
|
||||
|
||||
**Existing project: `tests/ClaudeDo.Installer.Tests`**
|
||||
|
||||
- `SelfUpdateIntegrationTest`: build the installer, invoke it with `--replace-self <dummy>` pointing at a temp file, assert the dummy is replaced by a copy of the test installer, and the process exits cleanly. Run only on Windows CI.
|
||||
|
||||
**App tests (`tests/ClaudeDo.Ui.Tests` — add if absent):**
|
||||
|
||||
- `UpdateCheckServiceTests` — stubbed `IReleaseClient`, assert state transitions for each status.
|
||||
- `InstallerLocatorTests` — fake filesystem, verify walk-up and registry-fallback discovery.
|
||||
|
||||
**Manual verification** (add to `docs/open.md`):
|
||||
|
||||
1. Build `v0.2.x` installer and upload to a test Gitea release.
|
||||
2. Tag `v0.3.0` with new installer asset.
|
||||
3. Install `v0.2.x`, run the `v0.2.x` installer again — confirm self-update prompt appears and replaces the binary in place.
|
||||
4. With `v0.2.x` installed and a v0.3.0 release published, launch the app — confirm banner appears, **Update now** launches installer, update completes, app relaunches at v0.3.0.
|
||||
5. Pull the network during check in both places — confirm silent fallback, no user-visible errors.
|
||||
|
||||
## Files Summary
|
||||
|
||||
**New:**
|
||||
|
||||
- `src/ClaudeDo.Releases/ClaudeDo.Releases.csproj`
|
||||
- `src/ClaudeDo.Releases/ReleaseClient.cs` (moved)
|
||||
- `src/ClaudeDo.Releases/IReleaseClient.cs` (moved)
|
||||
- `src/ClaudeDo.Releases/ChecksumVerifier.cs` (moved)
|
||||
- `src/ClaudeDo.Releases/VersionComparer.cs` (new)
|
||||
- `src/ClaudeDo.Releases/SelfUpdater.cs` (new)
|
||||
- `src/ClaudeDo.Ui/Services/UpdateCheckService.cs`
|
||||
- `src/ClaudeDo.Ui/Services/InstallerLocator.cs`
|
||||
- `tests/ClaudeDo.Releases.Tests/ClaudeDo.Releases.Tests.csproj`
|
||||
|
||||
**Modified:**
|
||||
|
||||
- `src/ClaudeDo.Installer/App.xaml.cs` — self-update run + `--replace-self` handling before wizard.
|
||||
- `src/ClaudeDo.Installer/Core/InstallModeDetector.cs` — use shared `VersionComparer`; drop now-moved types.
|
||||
- `src/ClaudeDo.Installer/ClaudeDo.Installer.csproj` — reference `ClaudeDo.Releases`.
|
||||
- `src/ClaudeDo.Ui/ClaudeDo.Ui.csproj` — reference `ClaudeDo.Releases`.
|
||||
- `src/ClaudeDo.Ui/Views/MainWindow.axaml` — banner + Help menu dropdown.
|
||||
- `src/ClaudeDo.Ui/ViewModels/MainViewModel.cs` — banner state, `CheckForUpdatesCommand`, wiring to `UpdateCheckService`.
|
||||
- `src/ClaudeDo.App/Program.cs` (or existing DI composition root) — register `UpdateCheckService`, `InstallerLocator`, `IReleaseClient`, `HttpClient`.
|
||||
- `ClaudeDo.slnx` — add new projects.
|
||||
- `docs/open.md` — add manual verification checklist.
|
||||
|
||||
## Open Decisions Deferred to Implementation
|
||||
|
||||
- Exact Avalonia styling/layout of the banner is left to implementation to match the existing chrome polish pass from commit `3c420ac`.
|
||||
- The Help dropdown control type (Avalonia `MenuItem` inside a `Menu`, or a custom flyout) is chosen during implementation based on what fits the current custom titlebar.
|
||||
121
docs/superpowers/specs/2026-04-23-worker-log-footer-design.md
Normal file
121
docs/superpowers/specs/2026-04-23-worker-log-footer-design.md
Normal file
@@ -0,0 +1,121 @@
|
||||
# Worker Log Footer — Design
|
||||
|
||||
Date: 2026-04-23
|
||||
|
||||
## Goal
|
||||
|
||||
Surface important Worker lifecycle events (worktree created, Claude started, merged, etc.) in the UI footer as a single rotating, color-coded line. Gives the user ambient awareness of what the Worker just did without opening task details.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No log history, drawer, or scrollback
|
||||
- No filtering or user-configurable verbosity
|
||||
- No persistence across UI restarts
|
||||
- No replay of events missed while UI was disconnected
|
||||
|
||||
## UX
|
||||
|
||||
Footer (`MainWindow.axaml`, row 2) layout changes from `StackPanel` to `DockPanel`:
|
||||
|
||||
- **Docked left:** existing connection pill (ellipse + `ONLINE/OFFLINE/RECONNECTING` text). The static `· WORKER` label is removed; the rotating log line replaces its purpose.
|
||||
- **Docked right:** rotating worker-log line.
|
||||
|
||||
Line format: `14:32 · <message>`, rendered in the mono font at size 10 (matches existing footer typography). `TextTrimming="CharacterEllipsis"` so long task titles don't push out the connection pill.
|
||||
|
||||
The line is hidden when no event has been received within the last 30 seconds. Each new event replaces the current text and resets the 30-second timer. Timestamp is local time, `HH:mm`.
|
||||
|
||||
### Color mapping
|
||||
|
||||
Level is rendered via a `WorkerLogLevelToBrushConverter` (mirrors existing `StatusColorConverter` pattern):
|
||||
|
||||
| Level | Brush / color | Events |
|
||||
|-----------|------------------------|-----------------------------------------------------|
|
||||
| `Info` | `TextDimBrush` (dim) | Created worktree, Started Claude, Committed changes |
|
||||
| `Success` | `#4CAF50` green | Merged, Finished (done) |
|
||||
| `Warn` | `#FFA726` amber | Discarded worktree, Reset |
|
||||
| `Error` | `#EF5350` red | Finished (failed) |
|
||||
|
||||
## Event Catalog
|
||||
|
||||
Seven emit sites. Each is added alongside the existing `_logger.LogInformation(...)` call — no log-sink plumbing, no central event bus.
|
||||
|
||||
| Site | Level | Message |
|
||||
|-------------------------------------------|-----------|-----------------------------------------|
|
||||
| `WorktreeManager.CreateAsync` | `Info` | `Created worktree for "<title>"` |
|
||||
| `WorktreeManager.DiscardAsync` | `Warn` | `Discarded worktree for "<title>"` |
|
||||
| `TaskMergeService.MergeAsync` | `Success` | `Merged "<title>" into <target>` |
|
||||
| `TaskResetService.ResetAsync` | `Warn` | `Reset "<title>"` |
|
||||
| `TaskRunner` — Claude launch | `Info` | `Started Claude for "<title>"` |
|
||||
| `TaskRunner` — auto-commit | `Info` | `Committed changes in "<title>"` |
|
||||
| `TaskRunner` — task finished | `Success` / `Error` | `Finished "<title>" (<status>)` |
|
||||
|
||||
`<title>` is the task's display title; `<target>` is the merge target branch; `<status>` is `done` or `failed`.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Shared contract (`ClaudeDo.Data`)
|
||||
|
||||
New enum:
|
||||
|
||||
```csharp
|
||||
namespace ClaudeDo.Data.Models;
|
||||
|
||||
public enum WorkerLogLevel
|
||||
{
|
||||
Info,
|
||||
Success,
|
||||
Warn,
|
||||
Error,
|
||||
}
|
||||
```
|
||||
|
||||
SignalR is configured to serialize enums as strings via `JsonStringEnumConverter` (added to the hub's JSON options in `Program.cs`). The UI client deserializes back to the same enum.
|
||||
|
||||
### Server side (`ClaudeDo.Worker`)
|
||||
|
||||
`HubBroadcaster` gets a new method:
|
||||
|
||||
```csharp
|
||||
public Task WorkerLog(string message, WorkerLogLevel level, DateTime timestampUtc) =>
|
||||
_hub.Clients.All.SendAsync("WorkerLog", message, level, timestampUtc);
|
||||
```
|
||||
|
||||
`HubBroadcaster` is already injected into `TaskRunner`. For `WorktreeManager`, `TaskMergeService`, and `TaskResetService`, add constructor injection where it isn't already present. Each emit site calls `_broadcaster.WorkerLog(...)` with `DateTime.UtcNow` next to the existing `_logger.LogInformation(...)`.
|
||||
|
||||
### Client side (`ClaudeDo.Ui`)
|
||||
|
||||
**`WorkerClient`** — register a `HubConnection.On<string, WorkerLogLevel, DateTime>("WorkerLog", ...)` handler and expose a `WorkerLogReceived` event with a small `WorkerLogEntry(string Message, WorkerLogLevel Level, DateTime TimestampUtc)` record.
|
||||
|
||||
**Footer VM** — `StatusBarViewModel` already exists; extend it (or introduce a small `FooterViewModel` if `StatusBarViewModel` turns out to be scoped elsewhere — confirm during implementation). Add:
|
||||
|
||||
- `[ObservableProperty] string? currentEventText`
|
||||
- `[ObservableProperty] WorkerLogLevel currentEventLevel`
|
||||
- `[ObservableProperty] bool isEventVisible`
|
||||
- A `DispatcherTimer` with a 30-second interval. On each `WorkerLogReceived`:
|
||||
1. Format `HH:mm · <message>` from the event's local time.
|
||||
2. Set `CurrentEventText`, `CurrentEventLevel`, `IsEventVisible = true`.
|
||||
3. Stop and restart the timer.
|
||||
- On timer tick: `IsEventVisible = false`, `CurrentEventText = null`.
|
||||
|
||||
**XAML** — `MainWindow.axaml` footer `StackPanel` becomes a `DockPanel`. Existing ellipses + connection text dock left in a horizontal `StackPanel`. A new `TextBlock` docks right, bound to `CurrentEventText` with `Foreground="{Binding CurrentEventLevel, Converter={StaticResource WorkerLogLevelToBrush}}"`, `IsVisible="{Binding IsEventVisible}"`, and `TextTrimming="CharacterEllipsis"`. Same mono font / size 10 as the rest of the footer.
|
||||
|
||||
**Converter** — `WorkerLogLevelToBrushConverter` in `Converters/` returns a brush per enum value, resolving theme brushes via `Application.Current.Resources` for `Info` (to honor theme swaps) and hard-coding the success/warn/error hex values (those are already hard-coded in the current footer).
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit test `WorkerLogLevelToBrushConverter` with each enum value.
|
||||
- Unit test the footer VM: receiving an event sets text/level/visibility and schedules a clear; a second event within 30s replaces and resets the timer; after 30s of silence the line hides.
|
||||
- Manual smoke: run a task end-to-end and confirm each of the seven events surfaces with the expected color and copy.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- **UI disconnected during an event:** event is lost. Acceptable — reconnect resumes receiving new events.
|
||||
- **Burst of events:** each replaces the previous; only the most recent is shown.
|
||||
- **Long task title:** ellipsized by the TextBlock; connection pill on the left stays fully visible.
|
||||
- **Clock skew between Worker and UI:** timestamp is formatted in UI's local time from the wire-format `DateTime` (sent as UTC). Minor skew is cosmetic; no correctness impact.
|
||||
|
||||
## Out of Scope / Future
|
||||
|
||||
- Click-to-expand history drawer
|
||||
- Per-list or per-task event filtering
|
||||
- Persisting the most recent N events across restarts
|
||||
@@ -18,6 +18,8 @@
|
||||
<converters:UpperCaseConverter x:Key="UpperCase"/>
|
||||
<converters:IconKeyConverter x:Key="IconKey"/>
|
||||
<converters:DotBrushConverter x:Key="DotBrush"/>
|
||||
<converters:BoolToItalicConverter x:Key="BoolToItalic"/>
|
||||
<converters:BoolToDraftOpacityConverter x:Key="BoolToDraftOpacity"/>
|
||||
|
||||
</ResourceDictionary>
|
||||
</Application.Resources>
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 317 B After Width: | Height: | Size: 44 KiB |
@@ -1,6 +1,7 @@
|
||||
using Avalonia;
|
||||
using ClaudeDo.Data;
|
||||
using ClaudeDo.Data.Git;
|
||||
using ClaudeDo.Releases;
|
||||
using ClaudeDo.Ui;
|
||||
using ClaudeDo.Ui.Services;
|
||||
using ClaudeDo.Ui.ViewModels;
|
||||
@@ -9,6 +10,8 @@ using ClaudeDo.Ui.ViewModels.Modals;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace ClaudeDo.App;
|
||||
@@ -75,17 +78,36 @@ sealed class Program
|
||||
sc.AddSingleton<GitService>();
|
||||
sc.AddSingleton(sp => new WorkerClient(sp.GetRequiredService<AppSettings>().SignalRUrl));
|
||||
|
||||
// Release check + installer update
|
||||
sc.AddSingleton<HttpClient>(_ => new HttpClient { Timeout = TimeSpan.FromSeconds(10) });
|
||||
sc.AddSingleton<IReleaseClient>(sp => new ReleaseClient(sp.GetRequiredService<HttpClient>()));
|
||||
sc.AddSingleton<InstallerLocator>();
|
||||
sc.AddSingleton(sp =>
|
||||
{
|
||||
var releases = sp.GetRequiredService<IReleaseClient>();
|
||||
var informational = Assembly.GetEntryAssembly()?
|
||||
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
|
||||
// Strip MinVer build metadata ("+sha") and any prerelease suffix for the update-compare.
|
||||
var version = (informational ?? "0.0.0").Split('+')[0];
|
||||
return new UpdateCheckService(releases, version);
|
||||
});
|
||||
|
||||
// ViewModels
|
||||
sc.AddTransient<WorktreeModalViewModel>();
|
||||
sc.AddTransient<SettingsModalViewModel>();
|
||||
sc.AddTransient<MergeModalViewModel>();
|
||||
sc.AddTransient<ListSettingsModalViewModel>();
|
||||
|
||||
// Islands shell VMs
|
||||
sc.AddSingleton<ListsIslandViewModel>(sp =>
|
||||
new ListsIslandViewModel(
|
||||
sp.GetRequiredService<IDbContextFactory<ClaudeDoDbContext>>(),
|
||||
sp));
|
||||
sp,
|
||||
sp.GetRequiredService<WorkerClient>()));
|
||||
sc.AddSingleton<TasksIslandViewModel>(sp =>
|
||||
new TasksIslandViewModel(sp.GetRequiredService<IDbContextFactory<ClaudeDoDbContext>>()));
|
||||
new TasksIslandViewModel(
|
||||
sp.GetRequiredService<IDbContextFactory<ClaudeDoDbContext>>(),
|
||||
sp.GetRequiredService<WorkerClient>()));
|
||||
sc.AddSingleton<DetailsIslandViewModel>(sp =>
|
||||
new DetailsIslandViewModel(
|
||||
sp.GetRequiredService<IDbContextFactory<ClaudeDoDbContext>>(),
|
||||
|
||||
@@ -4,19 +4,23 @@ Shared data layer: models, repositories, SQLite infrastructure, and git operatio
|
||||
|
||||
## Models
|
||||
|
||||
- **TaskEntity** — Id, ListId, Title, Description, Status (Manual|Queued|Running|Done|Failed), ScheduledFor, Result, LogPath, timestamps, CommitType
|
||||
- **TaskEntity** — Id, ListId, Title, Description, Status (Manual|Queued|Running|Done|Failed), ScheduledFor, Result, LogPath, timestamps, CommitType, Model / SystemPrompt / AgentPath (nullable overrides), IsStarred, IsMyDay, Notes
|
||||
- **ListEntity** — Id, Name, WorkingDir, DefaultCommitType, CreatedAt
|
||||
- **ListConfigEntity** — ListId (PK, 1:1 with list), Model, SystemPrompt, AgentPath (all nullable)
|
||||
- **TagEntity** — Id (autoincrement), Name (unique)
|
||||
- **WorktreeEntity** — TaskId (PK, 1:1 with task), Path, BranchName, BaseCommit, HeadCommit, DiffStat, State (Active|Merged|Discarded|Kept)
|
||||
- **TaskRunEntity** — per-run record (session_id, tokens, turns, result, structured output, exit code, log path)
|
||||
- **SubtaskEntity**, **AppSettingsEntity**, **AgentInfo** — existing helpers / settings / record for scanned agent files
|
||||
|
||||
## Repositories
|
||||
|
||||
All repositories use EF Core LINQ queries via `ClaudeDoDbContext`. Exception: `TaskRepository.GetNextQueuedAgentTaskAsync` uses `FromSqlRaw` for atomic queue claim.
|
||||
|
||||
- **TaskRepository** — CRUD, status transitions (`MarkRunningAsync`, `MarkDoneAsync`, `MarkFailedAsync`), `GetNextQueuedAgentTaskAsync` (queue polling), `GetEffectiveTagsAsync` (union of task + list tags), `FlipAllRunningToFailedAsync`
|
||||
- **ListRepository** — CRUD, tag junction management
|
||||
- **TaskRepository** — CRUD, status transitions (`MarkRunningAsync`, `MarkDoneAsync`, `MarkFailedAsync`), `GetNextQueuedAgentTaskAsync` (queue polling), `GetEffectiveTagsAsync` (union of task + list tags), `FlipAllRunningToFailedAsync`, `UpdateAgentSettingsAsync` (model / system-prompt / agent-path overrides)
|
||||
- **ListRepository** — CRUD, tag junction management, `GetConfigAsync` / `SetConfigAsync` (upsert) / `DeleteConfigAsync` for `list_config`
|
||||
- **TagRepository** — `GetOrCreateAsync` (idempotent)
|
||||
- **WorktreeRepository** — CRUD, `UpdateHeadAsync`, `SetStateAsync`
|
||||
- **TaskRunRepository**, **SubtaskRepository**, **AppSettingsRepository**
|
||||
|
||||
## Infrastructure
|
||||
|
||||
@@ -31,7 +35,7 @@ All repositories use EF Core LINQ queries via `ClaudeDoDbContext`. Exception: `T
|
||||
|
||||
## Schema
|
||||
|
||||
6 tables: `lists`, `tasks`, `tags`, `list_tags`, `task_tags`, `worktrees`. Managed by EF Core migrations in the `Migrations/` folder. Seed data: tags "agent" and "manual".
|
||||
Tables: `lists`, `tasks`, `tags`, `list_tags`, `task_tags`, `worktrees`, `list_config`, `task_runs`, `subtasks`, `app_settings`. Managed by EF Core migrations in the `Migrations/` folder. Seed data: tags "agent" and "manual".
|
||||
|
||||
## Conventions
|
||||
|
||||
|
||||
@@ -45,6 +45,13 @@ public class ClaudeDoDbContext : DbContext
|
||||
walCmd.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
// Enable FK enforcement — SQLite defaults to OFF per connection.
|
||||
using (var fkCmd = conn.CreateCommand())
|
||||
{
|
||||
fkCmd.CommandText = "PRAGMA foreign_keys=ON;";
|
||||
fkCmd.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
// If the 'lists' table exists but __EFMigrationsHistory does not,
|
||||
// this is a pre-EF database. Baseline the InitialCreate migration.
|
||||
using (var cmd = conn.CreateCommand())
|
||||
|
||||
@@ -14,6 +14,9 @@ public class TaskEntityConfiguration : IEntityTypeConfiguration<TaskEntity>
|
||||
: v == TaskStatus.Running ? "running"
|
||||
: v == TaskStatus.Done ? "done"
|
||||
: v == TaskStatus.Failed ? "failed"
|
||||
: v == TaskStatus.Planning ? "planning"
|
||||
: v == TaskStatus.Planned ? "planned"
|
||||
: v == TaskStatus.Draft ? "draft"
|
||||
: throw new ArgumentOutOfRangeException(nameof(v));
|
||||
|
||||
private static TaskStatus StatusFromString(string v)
|
||||
@@ -22,6 +25,9 @@ public class TaskEntityConfiguration : IEntityTypeConfiguration<TaskEntity>
|
||||
: v == "running" ? TaskStatus.Running
|
||||
: v == "done" ? TaskStatus.Done
|
||||
: v == "failed" ? TaskStatus.Failed
|
||||
: v == "planning" ? TaskStatus.Planning
|
||||
: v == "planned" ? TaskStatus.Planned
|
||||
: v == "draft" ? TaskStatus.Draft
|
||||
: throw new ArgumentOutOfRangeException(nameof(v));
|
||||
|
||||
private static readonly ValueConverter<TaskStatus, string> StatusConverter =
|
||||
@@ -51,6 +57,17 @@ public class TaskEntityConfiguration : IEntityTypeConfiguration<TaskEntity>
|
||||
builder.Property(t => t.IsStarred).HasColumnName("is_starred").HasDefaultValue(false);
|
||||
builder.Property(t => t.IsMyDay).HasColumnName("is_my_day").HasDefaultValue(false);
|
||||
builder.Property(t => t.Notes).HasColumnName("notes");
|
||||
builder.Property(t => t.SortOrder).HasColumnName("sort_order").IsRequired().HasDefaultValue(0);
|
||||
|
||||
builder.Property(t => t.ParentTaskId).HasColumnName("parent_task_id");
|
||||
builder.Property(t => t.PlanningSessionId).HasColumnName("planning_session_id");
|
||||
builder.Property(t => t.PlanningSessionToken).HasColumnName("planning_session_token");
|
||||
builder.Property(t => t.PlanningFinalizedAt).HasColumnName("planning_finalized_at");
|
||||
|
||||
builder.HasOne(t => t.Parent)
|
||||
.WithMany(t => t.Children)
|
||||
.HasForeignKey(t => t.ParentTaskId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
builder.HasOne(t => t.List)
|
||||
.WithMany(l => l.Tasks)
|
||||
@@ -74,5 +91,7 @@ public class TaskEntityConfiguration : IEntityTypeConfiguration<TaskEntity>
|
||||
|
||||
builder.HasIndex(t => t.ListId).HasDatabaseName("idx_tasks_list_id");
|
||||
builder.HasIndex(t => t.Status).HasDatabaseName("idx_tasks_status");
|
||||
builder.HasIndex(t => new { t.ListId, t.SortOrder }).HasDatabaseName("idx_tasks_list_sort");
|
||||
builder.HasIndex(t => t.ParentTaskId).HasDatabaseName("idx_tasks_parent_task_id");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,6 +151,73 @@ public sealed class GitService
|
||||
throw new InvalidOperationException($"git branch {flag} failed (exit {exitCode}): {stderr}");
|
||||
}
|
||||
|
||||
public async Task<string> GetCurrentBranchAsync(string repoDir, CancellationToken ct = default)
|
||||
{
|
||||
var (exitCode, stdout, stderr) = await RunGitAsync(repoDir,
|
||||
["symbolic-ref", "--short", "HEAD"], ct);
|
||||
if (exitCode != 0)
|
||||
throw new InvalidOperationException($"git symbolic-ref --short HEAD failed (exit {exitCode}): {stderr}");
|
||||
return stdout.Trim();
|
||||
}
|
||||
|
||||
public async Task CheckoutBranchAsync(string repoDir, string branchName, CancellationToken ct = default)
|
||||
{
|
||||
var (exitCode, _, stderr) = await RunGitAsync(repoDir, ["checkout", branchName], ct);
|
||||
if (exitCode != 0)
|
||||
throw new InvalidOperationException($"git checkout '{branchName}' failed (exit {exitCode}): {stderr}");
|
||||
}
|
||||
|
||||
public async Task<List<string>> ListLocalBranchesAsync(string repoDir, CancellationToken ct = default)
|
||||
{
|
||||
var (exitCode, stdout, stderr) = await RunGitAsync(repoDir,
|
||||
["branch", "--format=%(refname:short)"], ct);
|
||||
if (exitCode != 0)
|
||||
throw new InvalidOperationException($"git branch --format failed (exit {exitCode}): {stderr}");
|
||||
|
||||
return stdout
|
||||
.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Where(s => s.Length > 0)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public async Task<bool> IsMidMergeAsync(string repoDir, CancellationToken ct = default)
|
||||
{
|
||||
var (exitCode, stdout, _) = await RunGitAsync(repoDir, ["rev-parse", "--git-dir"], ct);
|
||||
if (exitCode != 0) return false;
|
||||
var gitDir = stdout.Trim();
|
||||
if (!Path.IsPathRooted(gitDir))
|
||||
gitDir = Path.Combine(repoDir, gitDir);
|
||||
return File.Exists(Path.Combine(gitDir, "MERGE_HEAD"));
|
||||
}
|
||||
|
||||
public async Task<(int ExitCode, string Stderr)> MergeNoFfAsync(
|
||||
string repoDir, string sourceBranch, string message, CancellationToken ct = default)
|
||||
{
|
||||
var (exitCode, _, stderr) = await RunGitAsync(repoDir,
|
||||
["merge", "--no-ff", "-m", message, sourceBranch], ct);
|
||||
return (exitCode, stderr);
|
||||
}
|
||||
|
||||
public async Task MergeAbortAsync(string repoDir, CancellationToken ct = default)
|
||||
{
|
||||
var (exitCode, _, stderr) = await RunGitAsync(repoDir, ["merge", "--abort"], ct);
|
||||
if (exitCode != 0)
|
||||
throw new InvalidOperationException($"git merge --abort failed (exit {exitCode}): {stderr}");
|
||||
}
|
||||
|
||||
public async Task<List<string>> ListConflictedFilesAsync(string repoDir, CancellationToken ct = default)
|
||||
{
|
||||
var (exitCode, stdout, stderr) = await RunGitAsync(repoDir,
|
||||
["diff", "--name-only", "--diff-filter=U"], ct);
|
||||
if (exitCode != 0)
|
||||
throw new InvalidOperationException($"git diff --diff-filter=U failed (exit {exitCode}): {stderr}");
|
||||
|
||||
return stdout
|
||||
.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Where(s => s.Length > 0)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public async Task MergeFfOnlyAsync(string repoDir, string branchName, CancellationToken ct = default)
|
||||
{
|
||||
var (exitCode, _, stderr) = await RunGitAsync(repoDir, ["merge", "--ff-only", branchName], ct);
|
||||
@@ -169,6 +236,9 @@ public sealed class GitService
|
||||
RedirectStandardInput = stdinData is not null,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
StandardOutputEncoding = Encoding.UTF8,
|
||||
StandardErrorEncoding = Encoding.UTF8,
|
||||
StandardInputEncoding = stdinData is not null ? Encoding.UTF8 : null,
|
||||
};
|
||||
psi.ArgumentList.Add("-C");
|
||||
psi.ArgumentList.Add(workDir);
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace ClaudeDo.Data.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddTaskSortOrder : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "sort_order",
|
||||
table: "tasks",
|
||||
type: "INTEGER",
|
||||
nullable: false,
|
||||
defaultValue: 0);
|
||||
|
||||
// Backfill existing rows with a per-list dense order (0..N-1) by creation time
|
||||
// so today's UI order is preserved after the migration.
|
||||
migrationBuilder.Sql("""
|
||||
WITH ordered AS (
|
||||
SELECT id, (row_number() OVER (PARTITION BY list_id ORDER BY created_at) - 1) AS rn
|
||||
FROM tasks
|
||||
)
|
||||
UPDATE tasks SET sort_order = (SELECT rn FROM ordered WHERE ordered.id = tasks.id);
|
||||
""");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "idx_tasks_list_sort",
|
||||
table: "tasks",
|
||||
columns: new[] { "list_id", "sort_order" });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(
|
||||
name: "idx_tasks_list_sort",
|
||||
table: "tasks");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "sort_order",
|
||||
table: "tasks");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace ClaudeDo.Data.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddPlanningSupport : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "parent_task_id",
|
||||
table: "tasks",
|
||||
type: "TEXT",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTime>(
|
||||
name: "planning_finalized_at",
|
||||
table: "tasks",
|
||||
type: "TEXT",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "planning_session_id",
|
||||
table: "tasks",
|
||||
type: "TEXT",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "planning_session_token",
|
||||
table: "tasks",
|
||||
type: "TEXT",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "idx_tasks_parent_task_id",
|
||||
table: "tasks",
|
||||
column: "parent_task_id");
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_tasks_tasks_parent_task_id",
|
||||
table: "tasks",
|
||||
column: "parent_task_id",
|
||||
principalTable: "tasks",
|
||||
principalColumn: "id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_tasks_tasks_parent_task_id",
|
||||
table: "tasks");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "idx_tasks_parent_task_id",
|
||||
table: "tasks");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "parent_task_id",
|
||||
table: "tasks");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "planning_finalized_at",
|
||||
table: "tasks");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "planning_session_id",
|
||||
table: "tasks");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "planning_session_token",
|
||||
table: "tasks");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -273,6 +273,22 @@ namespace ClaudeDo.Data.Migrations
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("notes");
|
||||
|
||||
b.Property<string>("ParentTaskId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("parent_task_id");
|
||||
|
||||
b.Property<DateTime?>("PlanningFinalizedAt")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("planning_finalized_at");
|
||||
|
||||
b.Property<string>("PlanningSessionId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("planning_session_id");
|
||||
|
||||
b.Property<string>("PlanningSessionToken")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("planning_session_token");
|
||||
|
||||
b.Property<string>("Result")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("result");
|
||||
@@ -281,6 +297,12 @@ namespace ClaudeDo.Data.Migrations
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("scheduled_for");
|
||||
|
||||
b.Property<int>("SortOrder")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(0)
|
||||
.HasColumnName("sort_order");
|
||||
|
||||
b.Property<DateTime?>("StartedAt")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("started_at");
|
||||
@@ -304,9 +326,15 @@ namespace ClaudeDo.Data.Migrations
|
||||
b.HasIndex("ListId")
|
||||
.HasDatabaseName("idx_tasks_list_id");
|
||||
|
||||
b.HasIndex("ParentTaskId")
|
||||
.HasDatabaseName("idx_tasks_parent_task_id");
|
||||
|
||||
b.HasIndex("Status")
|
||||
.HasDatabaseName("idx_tasks_status");
|
||||
|
||||
b.HasIndex("ListId", "SortOrder")
|
||||
.HasDatabaseName("idx_tasks_list_sort");
|
||||
|
||||
b.ToTable("tasks", (string)null);
|
||||
});
|
||||
|
||||
@@ -493,7 +521,14 @@ namespace ClaudeDo.Data.Migrations
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("ClaudeDo.Data.Models.TaskEntity", "Parent")
|
||||
.WithMany("Children")
|
||||
.HasForeignKey("ParentTaskId")
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
b.Navigation("List");
|
||||
|
||||
b.Navigation("Parent");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("ClaudeDo.Data.Models.TaskRunEntity", b =>
|
||||
@@ -557,6 +592,8 @@ namespace ClaudeDo.Data.Migrations
|
||||
|
||||
modelBuilder.Entity("ClaudeDo.Data.Models.TaskEntity", b =>
|
||||
{
|
||||
b.Navigation("Children");
|
||||
|
||||
b.Navigation("Runs");
|
||||
|
||||
b.Navigation("Subtasks");
|
||||
|
||||
@@ -7,6 +7,9 @@ public enum TaskStatus
|
||||
Running,
|
||||
Done,
|
||||
Failed,
|
||||
Planning,
|
||||
Planned,
|
||||
Draft,
|
||||
}
|
||||
|
||||
public sealed class TaskEntity
|
||||
@@ -29,6 +32,12 @@ public sealed class TaskEntity
|
||||
public bool IsStarred { get; set; }
|
||||
public bool IsMyDay { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
public int SortOrder { get; set; }
|
||||
|
||||
public string? ParentTaskId { get; set; }
|
||||
public string? PlanningSessionId { get; set; }
|
||||
public string? PlanningSessionToken { get; set; }
|
||||
public DateTime? PlanningFinalizedAt { get; set; }
|
||||
|
||||
// Navigation properties
|
||||
public ListEntity List { get; set; } = null!;
|
||||
@@ -36,4 +45,7 @@ public sealed class TaskEntity
|
||||
public ICollection<TagEntity> Tags { get; set; } = new List<TagEntity>();
|
||||
public ICollection<TaskRunEntity> Runs { get; set; } = new List<TaskRunEntity>();
|
||||
public ICollection<SubtaskEntity> Subtasks { get; set; } = new List<SubtaskEntity>();
|
||||
|
||||
public TaskEntity? Parent { get; set; }
|
||||
public ICollection<TaskEntity> Children { get; set; } = new List<TaskEntity>();
|
||||
}
|
||||
|
||||
9
src/ClaudeDo.Data/Models/WorkerLogLevel.cs
Normal file
9
src/ClaudeDo.Data/Models/WorkerLogLevel.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace ClaudeDo.Data.Models;
|
||||
|
||||
public enum WorkerLogLevel
|
||||
{
|
||||
Info,
|
||||
Success,
|
||||
Warn,
|
||||
Error,
|
||||
}
|
||||
@@ -88,4 +88,12 @@ public sealed class ListRepository
|
||||
}
|
||||
await _context.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteConfigAsync(string listId, CancellationToken ct = default)
|
||||
{
|
||||
var affected = await _context.ListConfigs
|
||||
.Where(c => c.ListId == listId)
|
||||
.ExecuteDeleteAsync(ct);
|
||||
return affected > 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,13 @@ public sealed class TaskRepository
|
||||
|
||||
public async Task AddAsync(TaskEntity entity, CancellationToken ct = default)
|
||||
{
|
||||
// Append at bottom of the list by default: SortOrder = max(listId) + 1.
|
||||
var maxSort = await _context.Tasks
|
||||
.Where(t => t.ListId == entity.ListId)
|
||||
.Select(t => (int?)t.SortOrder)
|
||||
.MaxAsync(ct);
|
||||
entity.SortOrder = (maxSort ?? -1) + 1;
|
||||
|
||||
_context.Tasks.Add(entity);
|
||||
await _context.SaveChangesAsync(ct);
|
||||
}
|
||||
@@ -38,10 +45,32 @@ public sealed class TaskRepository
|
||||
{
|
||||
return await _context.Tasks
|
||||
.Where(t => t.ListId == listId)
|
||||
.OrderBy(t => t.CreatedAt)
|
||||
.OrderBy(t => t.SortOrder).ThenBy(t => t.CreatedAt)
|
||||
.ToListAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renumbers tasks in a list to 0..N-1 according to <paramref name="orderedTaskIds"/>.
|
||||
/// Ids not belonging to the list are ignored; ids missing from the list are untouched.
|
||||
/// </summary>
|
||||
public async Task ReorderAsync(string listId, IReadOnlyList<string> orderedTaskIds, CancellationToken ct = default)
|
||||
{
|
||||
if (orderedTaskIds.Count == 0) return;
|
||||
|
||||
var idSet = orderedTaskIds.ToHashSet();
|
||||
var tasks = await _context.Tasks
|
||||
.Where(t => t.ListId == listId && idSet.Contains(t.Id))
|
||||
.ToListAsync(ct);
|
||||
|
||||
for (int i = 0; i < orderedTaskIds.Count; i++)
|
||||
{
|
||||
var task = tasks.FirstOrDefault(t => t.Id == orderedTaskIds[i]);
|
||||
if (task is not null) task.SortOrder = i;
|
||||
}
|
||||
|
||||
await _context.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
// Kept for backwards-compatibility with callers using the old name.
|
||||
public Task<List<TaskEntity>> GetByListAsync(string listId, CancellationToken ct = default)
|
||||
=> GetByListIdAsync(listId, ct);
|
||||
@@ -98,6 +127,36 @@ public sealed class TaskRepository
|
||||
.SetProperty(t => t.Result, resultText), ct);
|
||||
}
|
||||
|
||||
public async Task ResetToManualAsync(string taskId, CancellationToken ct = default)
|
||||
{
|
||||
await _context.Tasks
|
||||
.Where(t => t.Id == taskId)
|
||||
.ExecuteUpdateAsync(s => s
|
||||
.SetProperty(t => t.Status, TaskStatus.Manual)
|
||||
.SetProperty(t => t.StartedAt, (DateTime?)null)
|
||||
.SetProperty(t => t.FinishedAt, (DateTime?)null)
|
||||
.SetProperty(t => t.Result, (string?)null), ct);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Agent settings
|
||||
|
||||
public async Task UpdateAgentSettingsAsync(
|
||||
string taskId,
|
||||
string? model,
|
||||
string? systemPrompt,
|
||||
string? agentPath,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
await _context.Tasks
|
||||
.Where(t => t.Id == taskId)
|
||||
.ExecuteUpdateAsync(s => s
|
||||
.SetProperty(t => t.Model, model)
|
||||
.SetProperty(t => t.SystemPrompt, systemPrompt)
|
||||
.SetProperty(t => t.AgentPath, agentPath), ct);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Tags
|
||||
@@ -147,6 +206,206 @@ public sealed class TaskRepository
|
||||
|
||||
#endregion
|
||||
|
||||
#region Planning
|
||||
|
||||
public async Task<List<TaskEntity>> GetChildrenAsync(string parentId, CancellationToken ct = default)
|
||||
{
|
||||
return await _context.Tasks
|
||||
.AsNoTracking()
|
||||
.Where(t => t.ParentTaskId == parentId)
|
||||
.OrderBy(t => t.SortOrder).ThenBy(t => t.CreatedAt)
|
||||
.ToListAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<TaskEntity> CreateChildAsync(
|
||||
string parentId,
|
||||
string title,
|
||||
string? description,
|
||||
IReadOnlyList<string>? tagNames,
|
||||
string? commitType,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var parent = await _context.Tasks.FirstOrDefaultAsync(t => t.Id == parentId, ct);
|
||||
if (parent is null)
|
||||
throw new InvalidOperationException($"Parent task {parentId} not found.");
|
||||
|
||||
var maxSort = await _context.Tasks
|
||||
.Where(t => t.ListId == parent.ListId)
|
||||
.Select(t => (int?)t.SortOrder)
|
||||
.MaxAsync(ct);
|
||||
|
||||
var child = new TaskEntity
|
||||
{
|
||||
Id = Guid.NewGuid().ToString(),
|
||||
ListId = parent.ListId,
|
||||
Title = title,
|
||||
Description = description,
|
||||
Status = TaskStatus.Draft,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CommitType = string.IsNullOrEmpty(commitType) ? parent.CommitType : commitType,
|
||||
ParentTaskId = parentId,
|
||||
SortOrder = (maxSort ?? -1) + 1,
|
||||
};
|
||||
_context.Tasks.Add(child);
|
||||
|
||||
if (tagNames is not null && tagNames.Count > 0)
|
||||
{
|
||||
foreach (var tagName in tagNames.Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
var tag = await _context.Tags.FirstOrDefaultAsync(t => t.Name == tagName, ct);
|
||||
if (tag is null)
|
||||
{
|
||||
tag = new TagEntity { Name = tagName };
|
||||
_context.Tags.Add(tag);
|
||||
await _context.SaveChangesAsync(ct);
|
||||
}
|
||||
child.Tags.Add(tag);
|
||||
}
|
||||
}
|
||||
|
||||
await _context.SaveChangesAsync(ct);
|
||||
return child;
|
||||
}
|
||||
|
||||
public async Task<TaskEntity?> SetPlanningStartedAsync(
|
||||
string taskId,
|
||||
string sessionToken,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var affected = await _context.Tasks
|
||||
.Where(t => t.Id == taskId && t.Status == TaskStatus.Manual)
|
||||
.ExecuteUpdateAsync(s => s
|
||||
.SetProperty(t => t.Status, TaskStatus.Planning)
|
||||
.SetProperty(t => t.PlanningSessionToken, sessionToken), ct);
|
||||
|
||||
if (affected == 0) return null;
|
||||
return await _context.Tasks.AsNoTracking().FirstOrDefaultAsync(t => t.Id == taskId, ct);
|
||||
}
|
||||
|
||||
public async Task UpdatePlanningSessionIdAsync(
|
||||
string parentId,
|
||||
string sessionId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
await _context.Tasks
|
||||
.Where(t => t.Id == parentId)
|
||||
.ExecuteUpdateAsync(s => s
|
||||
.SetProperty(t => t.PlanningSessionId, sessionId), ct);
|
||||
}
|
||||
|
||||
public async Task<TaskEntity?> FindByPlanningTokenAsync(
|
||||
string token,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token)) return null;
|
||||
return await _context.Tasks
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(t => t.PlanningSessionToken == token, ct);
|
||||
}
|
||||
|
||||
public async Task<int> FinalizePlanningAsync(
|
||||
string parentId,
|
||||
bool queueAgentTasks,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
using var tx = await _context.Database.BeginTransactionAsync(ct);
|
||||
|
||||
var parent = await _context.Tasks
|
||||
.AsNoTracking()
|
||||
.Include(t => t.List).ThenInclude(l => l.Tags)
|
||||
.FirstOrDefaultAsync(t => t.Id == parentId, ct);
|
||||
if (parent is null || parent.Status != TaskStatus.Planning)
|
||||
throw new InvalidOperationException($"Task {parentId} is not in Planning state.");
|
||||
|
||||
var listHasAgentTag = parent.List.Tags.Any(t => t.Name == "agent");
|
||||
|
||||
var drafts = await _context.Tasks
|
||||
.Include(t => t.Tags)
|
||||
.Where(t => t.ParentTaskId == parentId && t.Status == TaskStatus.Draft)
|
||||
.ToListAsync(ct);
|
||||
|
||||
int count = 0;
|
||||
foreach (var draft in drafts)
|
||||
{
|
||||
var childHasAgentTag = draft.Tags.Any(t => t.Name == "agent");
|
||||
var shouldQueue = queueAgentTasks && (childHasAgentTag || listHasAgentTag);
|
||||
draft.Status = shouldQueue ? TaskStatus.Queued : TaskStatus.Manual;
|
||||
count++;
|
||||
}
|
||||
|
||||
var finalizedAt = DateTime.UtcNow;
|
||||
await _context.Tasks
|
||||
.Where(t => t.Id == parentId)
|
||||
.ExecuteUpdateAsync(s => s
|
||||
.SetProperty(t => t.Status, TaskStatus.Planned)
|
||||
.SetProperty(t => t.PlanningFinalizedAt, finalizedAt)
|
||||
.SetProperty(t => t.PlanningSessionToken, (string?)null), ct);
|
||||
|
||||
await _context.SaveChangesAsync(ct);
|
||||
await tx.CommitAsync(ct);
|
||||
return count;
|
||||
}
|
||||
|
||||
public async Task<bool> DiscardPlanningAsync(
|
||||
string parentId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
using var tx = await _context.Database.BeginTransactionAsync(ct);
|
||||
|
||||
var parent = await _context.Tasks
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(t => t.Id == parentId, ct);
|
||||
if (parent is null || parent.Status != TaskStatus.Planning)
|
||||
{
|
||||
await tx.RollbackAsync(ct);
|
||||
return false;
|
||||
}
|
||||
|
||||
await _context.Tasks
|
||||
.Where(t => t.ParentTaskId == parentId && t.Status == TaskStatus.Draft)
|
||||
.ExecuteDeleteAsync(ct);
|
||||
|
||||
await _context.Tasks
|
||||
.Where(t => t.Id == parentId)
|
||||
.ExecuteUpdateAsync(s => s
|
||||
.SetProperty(t => t.Status, TaskStatus.Manual)
|
||||
.SetProperty(t => t.PlanningSessionId, (string?)null)
|
||||
.SetProperty(t => t.PlanningSessionToken, (string?)null)
|
||||
.SetProperty(t => t.PlanningFinalizedAt, (DateTime?)null), ct);
|
||||
|
||||
await tx.CommitAsync(ct);
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task TryCompleteParentAsync(
|
||||
string parentId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var parent = await _context.Tasks.AsNoTracking().FirstOrDefaultAsync(t => t.Id == parentId, ct);
|
||||
if (parent is null || parent.Status != TaskStatus.Planned) return;
|
||||
|
||||
var children = await _context.Tasks
|
||||
.Where(t => t.ParentTaskId == parentId)
|
||||
.Select(t => t.Status)
|
||||
.ToListAsync(ct);
|
||||
|
||||
if (children.Count == 0) return;
|
||||
|
||||
bool allTerminal = children.All(s => s == TaskStatus.Done || s == TaskStatus.Failed);
|
||||
if (!allTerminal) return;
|
||||
|
||||
bool anyFailed = children.Any(s => s == TaskStatus.Failed);
|
||||
var finalStatus = anyFailed ? TaskStatus.Failed : TaskStatus.Done;
|
||||
var finishedAt = DateTime.UtcNow;
|
||||
await _context.Tasks
|
||||
.Where(t => t.Id == parentId)
|
||||
.ExecuteUpdateAsync(s => s
|
||||
.SetProperty(t => t.Status, finalStatus)
|
||||
.SetProperty(t => t.FinishedAt, finishedAt), ct);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Queue selection
|
||||
|
||||
public async Task<TaskEntity?> GetNextQueuedAgentTaskAsync(DateTime now, CancellationToken ct = default)
|
||||
@@ -175,7 +434,7 @@ public sealed class TaskRepository
|
||||
WHERE lt.list_id = t.list_id AND tg.name = 'agent'
|
||||
)
|
||||
)
|
||||
ORDER BY t.created_at ASC
|
||||
ORDER BY t.sort_order ASC, t.created_at ASC
|
||||
LIMIT 1
|
||||
)
|
||||
RETURNING *
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Net.Http;
|
||||
using System.Reflection;
|
||||
using System.Windows;
|
||||
using ClaudeDo.Installer.Core;
|
||||
using ClaudeDo.Releases;
|
||||
using ClaudeDo.Installer.Pages.InstallPage;
|
||||
using ClaudeDo.Installer.Pages.PathsPage;
|
||||
using ClaudeDo.Installer.Pages.ServicePage;
|
||||
@@ -21,6 +22,104 @@ public partial class App : Application
|
||||
{
|
||||
base.OnStartup(e);
|
||||
|
||||
// --- Self-update pre-flight ---
|
||||
// Resolve current exe path. Assembly.Location may point to a .dll for apphost-based
|
||||
// .NET apps; swap to the .exe companion when that happens.
|
||||
var currentExePath = Assembly.GetEntryAssembly()!.Location;
|
||||
if (currentExePath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
currentExePath = System.IO.Path.ChangeExtension(currentExePath, ".exe");
|
||||
}
|
||||
|
||||
// Arg form: --replace-self "<old-path>"
|
||||
var replaceSelfIndex = Array.FindIndex(e.Args, a => a.Equals("--replace-self", StringComparison.OrdinalIgnoreCase));
|
||||
if (replaceSelfIndex >= 0 && replaceSelfIndex + 1 < e.Args.Length)
|
||||
{
|
||||
var oldPath = e.Args[replaceSelfIndex + 1];
|
||||
var relaunched = await SelfUpdater.HandleReplaceSelfAsync(
|
||||
oldPath: oldPath,
|
||||
currentExePath: currentExePath,
|
||||
launchProcess: path =>
|
||||
{
|
||||
try
|
||||
{
|
||||
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(path) { UseShellExecute = true });
|
||||
return true;
|
||||
}
|
||||
catch { return false; }
|
||||
});
|
||||
if (relaunched)
|
||||
{
|
||||
Shutdown(0);
|
||||
return;
|
||||
}
|
||||
// Replacement failed — fall through to normal wizard from the temp location.
|
||||
}
|
||||
else
|
||||
{
|
||||
// Normal launch: check for a newer installer.
|
||||
using var selfUpdateHttp = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
|
||||
var selfUpdateReleases = new ReleaseClient(selfUpdateHttp);
|
||||
var currentVersion = GetInstallerVersion();
|
||||
|
||||
var decision = await SelfUpdater.DecideUpdateAsync(selfUpdateReleases, currentVersion, CancellationToken.None);
|
||||
if (decision.Kind == SelfUpdateDecisionKind.UpdateAvailable)
|
||||
{
|
||||
var prompt = new SelfUpdatePromptWindow(currentVersion, decision.LatestVersion!);
|
||||
DarkTitleBar.Apply(prompt);
|
||||
var ok = prompt.ShowDialog() == true;
|
||||
if (!ok)
|
||||
{
|
||||
Shutdown(0);
|
||||
return;
|
||||
}
|
||||
if (prompt.Choice == SelfUpdateChoice.Update)
|
||||
{
|
||||
prompt.ShowProgress("Downloading...");
|
||||
var tempDir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "ClaudeDo.Installer.Update");
|
||||
var verifiedPath = await SelfUpdater.DownloadAndVerifyAsync(
|
||||
selfUpdateReleases,
|
||||
decision.InstallerAsset!,
|
||||
decision.ChecksumsAsset!,
|
||||
tempDir,
|
||||
new Progress<long>(_ => { }),
|
||||
CancellationToken.None);
|
||||
|
||||
if (verifiedPath is null)
|
||||
{
|
||||
MessageBox.Show(prompt,
|
||||
"Update download or verification failed. Continuing with current installer.",
|
||||
"ClaudeDo Installer", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
var psi = new System.Diagnostics.ProcessStartInfo(verifiedPath)
|
||||
{
|
||||
UseShellExecute = true,
|
||||
};
|
||||
psi.ArgumentList.Add("--replace-self");
|
||||
psi.ArgumentList.Add(currentExePath);
|
||||
System.Diagnostics.Process.Start(psi);
|
||||
Shutdown(0);
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(prompt,
|
||||
"Failed to launch updated installer: " + ex.Message + "\nContinuing with current installer.",
|
||||
"ClaudeDo Installer", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
}
|
||||
}
|
||||
// SelfUpdateChoice.Continue — fall through to normal wizard.
|
||||
}
|
||||
// No-update or check failed — fall through to normal wizard.
|
||||
}
|
||||
|
||||
// --- Existing wizard start-up unchanged below this line ---
|
||||
|
||||
_services = BuildServices();
|
||||
|
||||
var context = _services.GetRequiredService<InstallContext>();
|
||||
@@ -50,6 +149,7 @@ public partial class App : Application
|
||||
context.Mode = state.Mode;
|
||||
context.InstalledVersion = state.Existing?.Version;
|
||||
context.LatestVersion = state.LatestVersion;
|
||||
context.LatestTagUnparseable = state.LatestTagUnparseable;
|
||||
if (state.Existing is not null)
|
||||
context.InstallDirectory = state.Existing.InstallDir;
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ClaudeDo.Data\ClaudeDo.Data.csproj" />
|
||||
<ProjectReference Include="..\ClaudeDo.Releases\ClaudeDo.Releases.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -10,6 +10,7 @@ public sealed class InstallContext
|
||||
public string? InstallerVersion { get; set; } // from this installer's assembly
|
||||
public string? InstalledVersion { get; set; } // from install.json (or set by DownloadAndExtractStep)
|
||||
public string? LatestVersion { get; set; } // from Gitea API (may be null if offline)
|
||||
public bool LatestTagUnparseable { get; set; } // true if latest tag isn't a System.Version
|
||||
|
||||
// PathsPage
|
||||
public string DbPath { get; set; } = "~/.todo-app/todo.db";
|
||||
|
||||
@@ -8,7 +8,8 @@ public sealed record InstallManifest(
|
||||
string Version,
|
||||
string InstallDir,
|
||||
string WorkerDir,
|
||||
DateTimeOffset InstalledAt);
|
||||
DateTimeOffset InstalledAt,
|
||||
string? DataDir = null);
|
||||
|
||||
public static class InstallManifestStore
|
||||
{
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
using ClaudeDo.Releases;
|
||||
|
||||
namespace ClaudeDo.Installer.Core;
|
||||
|
||||
public sealed record DetectedState(
|
||||
InstallerMode Mode,
|
||||
InstallManifest? Existing,
|
||||
GiteaRelease? LatestRelease,
|
||||
string? LatestVersion);
|
||||
string? LatestVersion)
|
||||
{
|
||||
/// <summary>True when a release was returned but its tag isn't a parseable
|
||||
/// System.Version (e.g. "0.2.0-beta") — so we couldn't decide if it's newer.</summary>
|
||||
public bool LatestTagUnparseable { get; init; }
|
||||
}
|
||||
|
||||
public sealed class InstallModeDetector
|
||||
{
|
||||
@@ -26,23 +33,16 @@ public sealed class InstallModeDetector
|
||||
return new DetectedState(InstallerMode.Config, manifest, null, null);
|
||||
|
||||
var latestVersion = release.TagName.TrimStart('v', 'V');
|
||||
if (IsNewer(latestVersion, manifest.Version))
|
||||
var cmp = VersionComparer.Compare(latestVersion, manifest.Version);
|
||||
var newer = cmp.IsNewer;
|
||||
var unparseable = cmp.Unparseable;
|
||||
if (newer)
|
||||
return new DetectedState(InstallerMode.Update, manifest, release, latestVersion);
|
||||
|
||||
return new DetectedState(InstallerMode.Config, manifest, release, latestVersion);
|
||||
return new DetectedState(InstallerMode.Config, manifest, release, latestVersion)
|
||||
{
|
||||
LatestTagUnparseable = unparseable,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true only when both versions parse as System.Version (major.minor[.build[.revision]])
|
||||
/// AND latest > current. Semver pre-release tags like "0.2.0-beta" fail to parse and are
|
||||
/// treated as "not newer" — the user drops into Config mode with no update offered.
|
||||
/// This is deliberate: offering an update we can't compare is worse than silently skipping it.
|
||||
/// If the project starts shipping pre-release tags, revisit this.
|
||||
/// </summary>
|
||||
private static bool IsNewer(string latest, string current)
|
||||
{
|
||||
if (!Version.TryParse(latest, out var lv)) return false;
|
||||
if (!Version.TryParse(current, out var cv)) return false;
|
||||
return lv > cv;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,10 +67,13 @@ public sealed class UninstallRunner
|
||||
failures.Add($"install dir ({_context.InstallDirectory}): {err}");
|
||||
}
|
||||
|
||||
// 6) Delete ~/.todo-app (config + DB + logs) — only if user opted in.
|
||||
// 6) Delete data dir (config + DB + logs) — only if user opted in.
|
||||
// Prefer the manifest-recorded DataDir so a customised DbPath is honoured;
|
||||
// fall back to the default ~/.todo-app for older manifests.
|
||||
if (removeAppData)
|
||||
{
|
||||
var appData = Paths.AppDataRoot();
|
||||
var manifest = InstallManifestStore.TryRead(_context.InstallDirectory);
|
||||
var appData = manifest?.DataDir ?? Paths.AppDataRoot();
|
||||
if (Directory.Exists(appData))
|
||||
{
|
||||
progress.Report($"Deleting {appData}...");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using ClaudeDo.Installer.Core;
|
||||
using ClaudeDo.Releases;
|
||||
|
||||
namespace ClaudeDo.Installer.Steps;
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.IO;
|
||||
using ClaudeDo.Data;
|
||||
using ClaudeDo.Installer.Core;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -15,6 +16,10 @@ public sealed class InitDatabaseStep : IInstallStep
|
||||
var expandedPath = Paths.Expand(ctx.DbPath);
|
||||
progress.Report($"Initializing database at {expandedPath}");
|
||||
|
||||
var parent = Path.GetDirectoryName(expandedPath);
|
||||
if (!string.IsNullOrEmpty(parent))
|
||||
Directory.CreateDirectory(parent);
|
||||
|
||||
var options = new DbContextOptionsBuilder<ClaudeDoDbContext>()
|
||||
.UseSqlite($"Data Source={expandedPath}")
|
||||
.Options;
|
||||
|
||||
@@ -43,13 +43,21 @@ public sealed class RegisterServiceStep : IInstallStep
|
||||
|
||||
// Create service
|
||||
var startType = ctx.AutoStart ? "auto" : "demand";
|
||||
var createArgs = $"create {ServiceName} binPath= \"{workerExe}\" start= {startType}";
|
||||
|
||||
if (ctx.ServiceAccount == "CurrentUser")
|
||||
return StepResult.Fail(
|
||||
"Service cannot run as Current User without a password. " +
|
||||
"Select 'Local System' or extend ServicePage to capture a password.");
|
||||
|
||||
var objArg = ctx.ServiceAccount switch
|
||||
{
|
||||
"LocalSystem" => " obj= LocalSystem",
|
||||
"NetworkService" => " obj= \"NT AUTHORITY\\NetworkService\"",
|
||||
"LocalService" => " obj= \"NT AUTHORITY\\LocalService\"",
|
||||
_ => "",
|
||||
};
|
||||
var createArgs = $"create {ServiceName} binPath= \"{workerExe}\" start= {startType}{objArg}";
|
||||
|
||||
progress.Report("Creating service...");
|
||||
var (exitCode, output) = await RunSc(createArgs, ctx, progress, ct);
|
||||
if (exitCode == 1072)
|
||||
|
||||
@@ -13,15 +13,26 @@ public sealed class StartServiceStep : IInstallStep
|
||||
progress.Report($"Starting {ServiceName}...");
|
||||
|
||||
var (exit, _) = await ProcessRunner.RunAsync("sc.exe", $"start {ServiceName}", null, progress, ct);
|
||||
if (exit == 0) return StepResult.Ok();
|
||||
// 1056 = ERROR_SERVICE_ALREADY_RUNNING — fine, fall through to the readiness poll.
|
||||
if (exit != 0 && exit != 1056)
|
||||
return StepResult.Fail($"sc.exe start failed with exit code {exit}");
|
||||
|
||||
// Exit 1056 = ERROR_SERVICE_ALREADY_RUNNING — that's fine too.
|
||||
if (exit == 1056)
|
||||
{
|
||||
progress.Report("Service was already running.");
|
||||
|
||||
// sc.exe start returns as soon as SCM accepts the command. Poll until the
|
||||
// service actually reports RUNNING so downstream steps and SignalR clients
|
||||
// don't race the worker's startup.
|
||||
progress.Report("Waiting for service to reach RUNNING state...");
|
||||
for (var i = 0; i < 30; i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var (q, output) = await ProcessRunner.RunAsync("sc.exe", $"query {ServiceName}", null, progress, ct);
|
||||
if (q == 0 && output.Contains("RUNNING", StringComparison.OrdinalIgnoreCase))
|
||||
return StepResult.Ok();
|
||||
await Task.Delay(1000, ct);
|
||||
}
|
||||
|
||||
return StepResult.Fail($"sc.exe start failed with exit code {exit}");
|
||||
return StepResult.Fail("Service did not reach RUNNING state within 30 seconds.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.IO;
|
||||
using ClaudeDo.Data;
|
||||
using ClaudeDo.Installer.Core;
|
||||
|
||||
namespace ClaudeDo.Installer.Steps;
|
||||
@@ -14,11 +15,14 @@ public sealed class WriteInstallManifestStep : IInstallStep
|
||||
|
||||
try
|
||||
{
|
||||
var dataDir = Path.GetDirectoryName(Paths.Expand(ctx.DbPath));
|
||||
|
||||
var manifest = new InstallManifest(
|
||||
Version: ctx.InstalledVersion,
|
||||
InstallDir: ctx.InstallDirectory,
|
||||
WorkerDir: Path.Combine(ctx.InstallDirectory, "worker"),
|
||||
InstalledAt: DateTimeOffset.UtcNow);
|
||||
InstalledAt: DateTimeOffset.UtcNow,
|
||||
DataDir: dataDir);
|
||||
|
||||
InstallManifestStore.Write(ctx.InstallDirectory, manifest);
|
||||
progress.Report($"Wrote {InstallManifestStore.ManifestPath(ctx.InstallDirectory)}");
|
||||
|
||||
25
src/ClaudeDo.Installer/Views/SelfUpdatePromptWindow.xaml
Normal file
25
src/ClaudeDo.Installer/Views/SelfUpdatePromptWindow.xaml
Normal file
@@ -0,0 +1,25 @@
|
||||
<Window x:Class="ClaudeDo.Installer.Views.SelfUpdatePromptWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="ClaudeDo Installer Update"
|
||||
Width="460" Height="200"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
ResizeMode="NoResize"
|
||||
Background="#1a1a1a" Foreground="#f0f0f0">
|
||||
<Grid Margin="20">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Grid.Row="0" FontSize="16" FontWeight="SemiBold" Text="A newer installer is available"/>
|
||||
<TextBlock Grid.Row="1" Margin="0,8,0,0" TextWrapping="Wrap" x:Name="DetailText"/>
|
||||
<TextBlock Grid.Row="2" Margin="0,12,0,0" TextWrapping="Wrap" Foreground="#a0a0a0" x:Name="ProgressText" Visibility="Collapsed"/>
|
||||
<StackPanel Grid.Row="3" Orientation="Horizontal" HorizontalAlignment="Right">
|
||||
<Button x:Name="UpdateBtn" Content="Update" MinWidth="90" Margin="4,0" Padding="10,4" Click="UpdateBtn_Click" IsDefault="True"/>
|
||||
<Button x:Name="ContinueBtn" Content="Continue anyway" MinWidth="140" Margin="4,0" Padding="10,4" Click="ContinueBtn_Click"/>
|
||||
<Button x:Name="CancelBtn" Content="Cancel" MinWidth="90" Margin="4,0" Padding="10,4" Click="CancelBtn_Click" IsCancel="True"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Window>
|
||||
42
src/ClaudeDo.Installer/Views/SelfUpdatePromptWindow.xaml.cs
Normal file
42
src/ClaudeDo.Installer/Views/SelfUpdatePromptWindow.xaml.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
using System.Windows;
|
||||
|
||||
namespace ClaudeDo.Installer.Views;
|
||||
|
||||
public enum SelfUpdateChoice { Update, Continue, Cancel }
|
||||
|
||||
public partial class SelfUpdatePromptWindow : Window
|
||||
{
|
||||
public SelfUpdateChoice Choice { get; private set; } = SelfUpdateChoice.Cancel;
|
||||
|
||||
public SelfUpdatePromptWindow(string currentVersion, string latestVersion)
|
||||
{
|
||||
InitializeComponent();
|
||||
DetailText.Text = $"Installer v{latestVersion} is available (you are running v{currentVersion}). Update before continuing?";
|
||||
}
|
||||
|
||||
public void ShowProgress(string text)
|
||||
{
|
||||
ProgressText.Text = text;
|
||||
ProgressText.Visibility = Visibility.Visible;
|
||||
UpdateBtn.IsEnabled = false;
|
||||
ContinueBtn.IsEnabled = false;
|
||||
}
|
||||
|
||||
private void UpdateBtn_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
Choice = SelfUpdateChoice.Update;
|
||||
DialogResult = true;
|
||||
}
|
||||
|
||||
private void ContinueBtn_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
Choice = SelfUpdateChoice.Continue;
|
||||
DialogResult = true;
|
||||
}
|
||||
|
||||
private void CancelBtn_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
Choice = SelfUpdateChoice.Cancel;
|
||||
DialogResult = false;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Windows;
|
||||
using ClaudeDo.Installer.Core;
|
||||
using ClaudeDo.Releases;
|
||||
using ClaudeDo.Installer.Steps;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
@@ -50,7 +51,12 @@ public partial class SettingsViewModel : ObservableObject
|
||||
_uninstallRunner = uninstallRunner;
|
||||
_selectedPage = Pages.FirstOrDefault();
|
||||
|
||||
VersionLabel = $"Installed: {context.InstalledVersion ?? "?"} Installer: {context.InstallerVersion ?? "?"}";
|
||||
var label = $"Installed: {context.InstalledVersion ?? "?"} Installer: {context.InstallerVersion ?? "?"}";
|
||||
if (!string.IsNullOrEmpty(context.LatestVersion))
|
||||
label += $" Latest: {context.LatestVersion}";
|
||||
if (context.LatestTagUnparseable)
|
||||
label += " (pre-release tag — auto-update disabled)";
|
||||
VersionLabel = label;
|
||||
|
||||
_ = LoadAllAsync();
|
||||
}
|
||||
@@ -98,8 +104,39 @@ public partial class SettingsViewModel : ObservableObject
|
||||
};
|
||||
uiCfg.Save();
|
||||
|
||||
StatusMessage = "Settings saved.";
|
||||
IsStatusError = false;
|
||||
StatusMessage = "Settings saved.";
|
||||
|
||||
// Worker reads its config at process start, so changes only take effect after a restart.
|
||||
var restart = MessageBox.Show(
|
||||
"Restart the worker service now so the new settings take effect?",
|
||||
"Restart Worker",
|
||||
MessageBoxButton.YesNo,
|
||||
MessageBoxImage.Question);
|
||||
|
||||
if (restart != MessageBoxResult.Yes)
|
||||
{
|
||||
StatusMessage = "Settings saved. Restart the worker service manually to apply.";
|
||||
return;
|
||||
}
|
||||
|
||||
var progress = new Progress<string>(msg => StatusMessage = msg);
|
||||
var stop = await _stopService.ExecuteAsync(_context, progress, CancellationToken.None);
|
||||
if (!stop.Success)
|
||||
{
|
||||
StatusMessage = $"Saved, but worker stop failed: {stop.ErrorMessage}";
|
||||
IsStatusError = true;
|
||||
return;
|
||||
}
|
||||
var start = await _startService.ExecuteAsync(_context, progress, CancellationToken.None);
|
||||
if (!start.Success)
|
||||
{
|
||||
StatusMessage = $"Saved, but worker start failed: {start.ErrorMessage}";
|
||||
IsStatusError = true;
|
||||
return;
|
||||
}
|
||||
|
||||
StatusMessage = "Settings saved. Worker restarted.";
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace ClaudeDo.Installer.Core;
|
||||
namespace ClaudeDo.Releases;
|
||||
|
||||
public static class ChecksumVerifier
|
||||
{
|
||||
8
src/ClaudeDo.Releases/ClaudeDo.Releases.csproj
Normal file
8
src/ClaudeDo.Releases/ClaudeDo.Releases.csproj
Normal file
@@ -0,0 +1,8 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<LangVersion>latest</LangVersion>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace ClaudeDo.Installer.Core;
|
||||
namespace ClaudeDo.Releases;
|
||||
|
||||
public sealed record ReleaseAsset(string Name, string BrowserDownloadUrl, long Size);
|
||||
|
||||
@@ -2,7 +2,7 @@ using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ClaudeDo.Installer.Core;
|
||||
namespace ClaudeDo.Releases;
|
||||
|
||||
public sealed class ReleaseClient : IReleaseClient
|
||||
{
|
||||
15
src/ClaudeDo.Releases/SelfUpdateResult.cs
Normal file
15
src/ClaudeDo.Releases/SelfUpdateResult.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace ClaudeDo.Releases;
|
||||
|
||||
public sealed record InstallerAssetMatch(ReleaseAsset Asset, string Version);
|
||||
|
||||
public enum SelfUpdateDecisionKind
|
||||
{
|
||||
NoUpdate,
|
||||
UpdateAvailable,
|
||||
}
|
||||
|
||||
public sealed record SelfUpdateDecision(
|
||||
SelfUpdateDecisionKind Kind,
|
||||
string? LatestVersion = null,
|
||||
ReleaseAsset? InstallerAsset = null,
|
||||
ReleaseAsset? ChecksumsAsset = null);
|
||||
126
src/ClaudeDo.Releases/SelfUpdater.cs
Normal file
126
src/ClaudeDo.Releases/SelfUpdater.cs
Normal file
@@ -0,0 +1,126 @@
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace ClaudeDo.Releases;
|
||||
|
||||
public static partial class SelfUpdater
|
||||
{
|
||||
[GeneratedRegex(@"^ClaudeDo\.Installer-(?<version>[\d\.]+)\.exe$", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex InstallerAssetRegex();
|
||||
|
||||
public static InstallerAssetMatch? FindInstallerAsset(IEnumerable<ReleaseAsset> assets)
|
||||
{
|
||||
foreach (var asset in assets)
|
||||
{
|
||||
var m = InstallerAssetRegex().Match(asset.Name);
|
||||
if (m.Success)
|
||||
{
|
||||
return new InstallerAssetMatch(asset, m.Groups["version"].Value);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static async Task<SelfUpdateDecision> DecideUpdateAsync(
|
||||
IReleaseClient releases,
|
||||
string currentVersion,
|
||||
CancellationToken ct)
|
||||
{
|
||||
GiteaRelease? release;
|
||||
try
|
||||
{
|
||||
release = await releases.GetLatestReleaseAsync(ct);
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
|
||||
{
|
||||
return new SelfUpdateDecision(SelfUpdateDecisionKind.NoUpdate);
|
||||
}
|
||||
|
||||
if (release is null)
|
||||
return new SelfUpdateDecision(SelfUpdateDecisionKind.NoUpdate);
|
||||
|
||||
var match = FindInstallerAsset(release.Assets);
|
||||
if (match is null)
|
||||
return new SelfUpdateDecision(SelfUpdateDecisionKind.NoUpdate);
|
||||
|
||||
var cmp = VersionComparer.Compare(match.Version, currentVersion);
|
||||
if (!cmp.IsNewer)
|
||||
return new SelfUpdateDecision(SelfUpdateDecisionKind.NoUpdate);
|
||||
|
||||
var checksums = release.Assets.FirstOrDefault(
|
||||
a => string.Equals(a.Name, "checksums.txt", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
return new SelfUpdateDecision(
|
||||
SelfUpdateDecisionKind.UpdateAvailable,
|
||||
LatestVersion: match.Version,
|
||||
InstallerAsset: match.Asset,
|
||||
ChecksumsAsset: checksums);
|
||||
}
|
||||
|
||||
public static async Task<bool> HandleReplaceSelfAsync(
|
||||
string oldPath,
|
||||
string currentExePath,
|
||||
Func<string, bool> launchProcess,
|
||||
int maxWaitMs = 5000)
|
||||
{
|
||||
var deadline = DateTime.UtcNow.AddMilliseconds(maxWaitMs);
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(oldPath))
|
||||
{
|
||||
File.Delete(oldPath);
|
||||
}
|
||||
break;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
}
|
||||
}
|
||||
|
||||
if (File.Exists(oldPath))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
File.Copy(currentExePath, oldPath, overwrite: false);
|
||||
return launchProcess(oldPath);
|
||||
}
|
||||
|
||||
public static async Task<string?> DownloadAndVerifyAsync(
|
||||
IReleaseClient releases,
|
||||
ReleaseAsset installerAsset,
|
||||
ReleaseAsset checksumsAsset,
|
||||
string tempDir,
|
||||
IProgress<long> progress,
|
||||
CancellationToken ct)
|
||||
{
|
||||
Directory.CreateDirectory(tempDir);
|
||||
var installerPath = Path.Combine(tempDir, installerAsset.Name);
|
||||
var checksumsPath = Path.Combine(tempDir, "checksums.txt");
|
||||
|
||||
try
|
||||
{
|
||||
await releases.DownloadAsync(installerAsset.BrowserDownloadUrl, installerPath, progress, ct);
|
||||
await releases.DownloadAsync(checksumsAsset.BrowserDownloadUrl, checksumsPath, new Progress<long>(_ => { }), ct);
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or IOException or TaskCanceledException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var checksumsText = await File.ReadAllTextAsync(checksumsPath, ct);
|
||||
var map = ChecksumVerifier.ParseChecksumsFile(checksumsText);
|
||||
if (!map.TryGetValue(installerAsset.Name, out var expected))
|
||||
return null;
|
||||
|
||||
return ChecksumVerifier.Verify(installerPath, expected) ? installerPath : null;
|
||||
}
|
||||
}
|
||||
18
src/ClaudeDo.Releases/VersionComparer.cs
Normal file
18
src/ClaudeDo.Releases/VersionComparer.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
namespace ClaudeDo.Releases;
|
||||
|
||||
public readonly record struct VersionCompareResult(bool IsNewer, bool Unparseable);
|
||||
|
||||
public static class VersionComparer
|
||||
{
|
||||
public static VersionCompareResult Compare(string latest, string current)
|
||||
{
|
||||
var latestTrimmed = (latest ?? "").TrimStart('v', 'V');
|
||||
var currentTrimmed = (current ?? "").TrimStart('v', 'V');
|
||||
|
||||
var unparseable = !Version.TryParse(latestTrimmed, out var lv)
|
||||
| !Version.TryParse(currentTrimmed, out var cv);
|
||||
|
||||
if (unparseable) return new VersionCompareResult(false, true);
|
||||
return new VersionCompareResult(lv > cv, false);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ MVVM with CommunityToolkit.Mvvm source generators:
|
||||
- **TaskEditorView** — Modal dialog for task create/edit
|
||||
- **ListEditorView** — Modal dialog for list create/edit
|
||||
- **StatusBarView** — Connection status indicator, active task display
|
||||
- **ListSettingsModalView** — edits list name, working dir, default commit type, and per-list Model/SystemPrompt/AgentPath. Opened via context menu or gear button on a list row.
|
||||
- **DetailsIslandView** — contains an "Agent settings (overrides)" expander with per-task Model/SystemPrompt/AgentPath, showing inherited effective values. Disabled while task is running.
|
||||
|
||||
All views use compiled bindings (`x:DataType`).
|
||||
|
||||
@@ -31,7 +33,7 @@ All views use compiled bindings (`x:DataType`).
|
||||
|
||||
## Services
|
||||
|
||||
- **WorkerClient** — SignalR client connecting to `http://127.0.0.1:47821/hub`. Auto-reconnect with exponential backoff. Methods: StartAsync, RunNowAsync, CancelTaskAsync, WakeQueueAsync. Events: TaskStarted, TaskFinished, TaskMessage, TaskUpdated, WorktreeUpdated
|
||||
- **WorkerClient** — SignalR client connecting to `http://127.0.0.1:47821/hub`. Auto-reconnect with exponential backoff. Methods: StartAsync, RunNowAsync, CancelTaskAsync, WakeQueueAsync, ContinueTaskAsync, ResetTaskAsync, GetAgentsAsync, UpdateAppSettingsAsync, UpdateListAsync, UpdateListConfigAsync, GetListConfigAsync, UpdateTaskAgentSettingsAsync. Events: TaskStarted, TaskFinished, TaskMessage, TaskUpdated, WorktreeUpdated, ListUpdated
|
||||
|
||||
## Converters
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ClaudeDo.Data\ClaudeDo.Data.csproj" />
|
||||
<ProjectReference Include="..\ClaudeDo.Releases\ClaudeDo.Releases.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -9,6 +10,12 @@
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="8.0.11" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" />
|
||||
<PackageReference Include="Microsoft.Win32.Registry" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="ClaudeDo.Ui.Tests" />
|
||||
<InternalsVisibleTo Include="ClaudeDo.Worker.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
@@ -22,6 +29,7 @@
|
||||
<AvaloniaResource Include="Assets/Fonts/*.ttf" />
|
||||
<AvaloniaResource Include="Assets/Fonts/OFL-InterTight.txt" />
|
||||
<AvaloniaResource Include="Assets/Fonts/OFL-JetBrainsMono.txt" />
|
||||
<AvaloniaResource Include="..\ClaudeDo.App\Assets\ClaudeTask.ico" Link="Assets\ClaudeTask.ico" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
15
src/ClaudeDo.Ui/Converters/BoolToDraftOpacityConverter.cs
Normal file
15
src/ClaudeDo.Ui/Converters/BoolToDraftOpacityConverter.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Avalonia.Data.Converters;
|
||||
|
||||
namespace ClaudeDo.Ui.Converters;
|
||||
|
||||
public sealed class BoolToDraftOpacityConverter : IValueConverter
|
||||
{
|
||||
public static BoolToDraftOpacityConverter Instance { get; } = new();
|
||||
|
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
=> value is true ? 0.7 : 1.0;
|
||||
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
=> throw new NotSupportedException();
|
||||
}
|
||||
16
src/ClaudeDo.Ui/Converters/BoolToItalicConverter.cs
Normal file
16
src/ClaudeDo.Ui/Converters/BoolToItalicConverter.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Avalonia.Data.Converters;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace ClaudeDo.Ui.Converters;
|
||||
|
||||
public sealed class BoolToItalicConverter : IValueConverter
|
||||
{
|
||||
public static BoolToItalicConverter Instance { get; } = new();
|
||||
|
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
=> value is true ? FontStyle.Italic : FontStyle.Normal;
|
||||
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
=> throw new NotSupportedException();
|
||||
}
|
||||
45
src/ClaudeDo.Ui/Converters/WorkerLogLevelToBrushConverter.cs
Normal file
45
src/ClaudeDo.Ui/Converters/WorkerLogLevelToBrushConverter.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Avalonia;
|
||||
using Avalonia.Data.Converters;
|
||||
using Avalonia.Media;
|
||||
using ClaudeDo.Data.Models;
|
||||
|
||||
namespace ClaudeDo.Ui.Converters;
|
||||
|
||||
public sealed class WorkerLogLevelToBrushConverter : IValueConverter
|
||||
{
|
||||
private static readonly IBrush SuccessBrush = new SolidColorBrush(Color.Parse("#4CAF50"));
|
||||
private static readonly IBrush WarnBrush = new SolidColorBrush(Color.Parse("#FFA726"));
|
||||
private static readonly IBrush ErrorBrush = new SolidColorBrush(Color.Parse("#EF5350"));
|
||||
private static readonly IBrush InfoFallback = new SolidColorBrush(Color.Parse("#888888"));
|
||||
|
||||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is not WorkerLogLevel level)
|
||||
return AvaloniaProperty.UnsetValue;
|
||||
|
||||
return level switch
|
||||
{
|
||||
WorkerLogLevel.Success => SuccessBrush,
|
||||
WorkerLogLevel.Warn => WarnBrush,
|
||||
WorkerLogLevel.Error => ErrorBrush,
|
||||
WorkerLogLevel.Info => ResolveInfoBrush(),
|
||||
_ => AvaloniaProperty.UnsetValue,
|
||||
};
|
||||
}
|
||||
|
||||
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
|
||||
throw new NotSupportedException();
|
||||
|
||||
private static IBrush ResolveInfoBrush()
|
||||
{
|
||||
if (Application.Current is { } app &&
|
||||
app.Resources.TryGetResource("TextDimBrush", app.ActualThemeVariant, out var res) &&
|
||||
res is IBrush brush)
|
||||
{
|
||||
return brush;
|
||||
}
|
||||
return InfoFallback;
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,14 @@
|
||||
<!-- Icon.ArrowOut — filled arrow for "open external" button -->
|
||||
<StreamGeometry x:Key="Icon.ArrowOut">M13 4 H20 V11 H18 V7.4 L11.4 14 L10 12.6 L16.6 6 H13 Z M4 6 H10 V8 H6 V18 H16 V14 H18 V20 H4 Z</StreamGeometry>
|
||||
|
||||
<!-- Icon.Settings (gear) -->
|
||||
<StreamGeometry x:Key="Icon.Settings">M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8z M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65a.5.5 0 0 0 .12-.64l-2-3.46a.5.5 0 0 0-.61-.22l-2.49 1a7.03 7.03 0 0 0-1.69-.98l-.38-2.65a.5.5 0 0 0-.5-.42h-4a.5.5 0 0 0-.5.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1a.5.5 0 0 0-.61.22l-2 3.46a.5.5 0 0 0 .12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65a.5.5 0 0 0-.12.64l2 3.46a.5.5 0 0 0 .61.22l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65a.5.5 0 0 0 .5.42h4a.5.5 0 0 0 .5-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1a.5.5 0 0 0 .61-.22l2-3.46a.5.5 0 0 0-.12-.64l-2.11-1.65z</StreamGeometry>
|
||||
|
||||
<!-- Badge brushes -->
|
||||
<SolidColorBrush x:Key="DraftBadgeBrush" Color="#4A5568"/>
|
||||
<SolidColorBrush x:Key="PlanningBadgeBrush" Color="#D69E2E"/>
|
||||
<SolidColorBrush x:Key="PlannedBadgeBrush" Color="#3182CE"/>
|
||||
|
||||
</Styles.Resources>
|
||||
|
||||
<!-- ============================================================ -->
|
||||
@@ -95,6 +103,8 @@
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="CornerRadius" Value="0" />
|
||||
<Setter Property="Foreground" Value="{StaticResource TextMuteBrush}" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
</Style>
|
||||
<Style Selector="Button.title-ctrl:pointerover /template/ ContentPresenter">
|
||||
<Setter Property="Background" Value="{StaticResource Surface2Brush}" />
|
||||
@@ -221,6 +231,8 @@
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="CornerRadius" Value="6" />
|
||||
<Setter Property="Foreground" Value="{StaticResource TextMuteBrush}" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
</Style>
|
||||
<Style Selector="Button.icon-btn:pointerover /template/ ContentPresenter">
|
||||
<Setter Property="Background" Value="{StaticResource Surface2Brush}" />
|
||||
@@ -272,6 +284,18 @@
|
||||
</ControlTemplate>
|
||||
</Setter>
|
||||
</Style>
|
||||
<Style Selector="Button.flat:pointerover /template/ ContentPresenter">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
</Style>
|
||||
<Style Selector="Button.flat:pressed /template/ ContentPresenter">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
</Style>
|
||||
<Style Selector="Button.flat:focus /template/ ContentPresenter">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
</Style>
|
||||
|
||||
<!-- ============================================================ -->
|
||||
<!-- TASK ROW -->
|
||||
@@ -527,6 +551,20 @@
|
||||
<Setter Property="Foreground" Value="{StaticResource AccentBrush}" />
|
||||
</Style>
|
||||
|
||||
<!-- Count badge — larger, high contrast, brighter when the row is active -->
|
||||
<Style Selector="TextBlock.list-count">
|
||||
<Setter Property="FontFamily" Value="{StaticResource MonoFont}" />
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="FontWeight" Value="Medium" />
|
||||
<Setter Property="Foreground" Value="{StaticResource TextDimBrush}" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="Margin" Value="8,0,4,0" />
|
||||
</Style>
|
||||
<Style Selector="Border.list-item.active TextBlock.list-count">
|
||||
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
</Style>
|
||||
|
||||
<!-- ============================================================ -->
|
||||
<!-- LIST SECTION HEADER -->
|
||||
<!-- ============================================================ -->
|
||||
@@ -574,12 +612,17 @@
|
||||
<Setter Property="BorderBrush" Value="{StaticResource LineBrush}" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="CornerRadius" Value="4" />
|
||||
<Setter Property="Padding" Value="6,2" />
|
||||
<Setter Property="Padding" Value="8,3" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="HorizontalAlignment" Value="Center" />
|
||||
</Style>
|
||||
<Style Selector="Border.kbd > TextBlock">
|
||||
<Setter Property="FontFamily" Value="{StaticResource MonoFont}" />
|
||||
<Setter Property="FontSize" Value="10" />
|
||||
<Setter Property="Foreground" Value="{StaticResource TextFaintBrush}" />
|
||||
<Setter Property="HorizontalAlignment" Value="Center" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="TextAlignment" Value="Center" />
|
||||
</Style>
|
||||
|
||||
<!-- ============================================================ -->
|
||||
@@ -828,4 +871,31 @@
|
||||
<Setter Property="Foreground" Value="{StaticResource BloodBrush}" />
|
||||
</Style>
|
||||
|
||||
<!-- ============================================================ -->
|
||||
<!-- PLANNING / DRAFT BADGES -->
|
||||
<!-- ============================================================ -->
|
||||
<Style Selector="Border.badge">
|
||||
<Setter Property="CornerRadius" Value="3"/>
|
||||
<Setter Property="Padding" Value="4,1"/>
|
||||
<Setter Property="VerticalAlignment" Value="Center"/>
|
||||
</Style>
|
||||
|
||||
<Style Selector="Border.badge > TextBlock">
|
||||
<Setter Property="FontSize" Value="9"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Foreground" Value="White"/>
|
||||
</Style>
|
||||
|
||||
<Style Selector="Border.badge.draft">
|
||||
<Setter Property="Background" Value="{DynamicResource DraftBadgeBrush}"/>
|
||||
</Style>
|
||||
|
||||
<Style Selector="Border.badge.planning">
|
||||
<Setter Property="Background" Value="{DynamicResource PlanningBadgeBrush}"/>
|
||||
</Style>
|
||||
|
||||
<Style Selector="Border.badge.planned">
|
||||
<Setter Property="Background" Value="{DynamicResource PlannedBadgeBrush}"/>
|
||||
</Style>
|
||||
|
||||
</Styles>
|
||||
|
||||
11
src/ClaudeDo.Ui/Services/IWorkerClient.cs
Normal file
11
src/ClaudeDo.Ui/Services/IWorkerClient.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace ClaudeDo.Ui.Services;
|
||||
|
||||
public interface IWorkerClient
|
||||
{
|
||||
Task WakeQueueAsync();
|
||||
Task StartPlanningSessionAsync(string taskId, CancellationToken ct = default);
|
||||
Task ResumePlanningSessionAsync(string taskId, CancellationToken ct = default);
|
||||
Task DiscardPlanningSessionAsync(string taskId, CancellationToken ct = default);
|
||||
Task FinalizePlanningSessionAsync(string taskId, bool queueAgentTasks = true, CancellationToken ct = default);
|
||||
Task<int> GetPendingDraftCountAsync(string taskId, CancellationToken ct = default);
|
||||
}
|
||||
47
src/ClaudeDo.Ui/Services/InstallerLocator.cs
Normal file
47
src/ClaudeDo.Ui/Services/InstallerLocator.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
namespace ClaudeDo.Ui.Services;
|
||||
|
||||
public sealed class InstallerLocator
|
||||
{
|
||||
private const string InstallJson = "install.json";
|
||||
private const string InstallerExe = "ClaudeDo.Installer.exe";
|
||||
private const string UninstallerSubdir = "uninstaller";
|
||||
|
||||
public string? Find()
|
||||
=> FindByWalkingUp(AppContext.BaseDirectory) ?? FindByRegistry();
|
||||
|
||||
public string? FindByWalkingUp(string startDir)
|
||||
{
|
||||
var dir = new DirectoryInfo(startDir);
|
||||
while (dir is not null)
|
||||
{
|
||||
var manifest = Path.Combine(dir.FullName, InstallJson);
|
||||
if (File.Exists(manifest))
|
||||
{
|
||||
var candidate = Path.Combine(dir.FullName, UninstallerSubdir, InstallerExe);
|
||||
return File.Exists(candidate) ? candidate : null;
|
||||
}
|
||||
dir = dir.Parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
|
||||
public string? FindByRegistry()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return null;
|
||||
|
||||
try
|
||||
{
|
||||
using var key = Microsoft.Win32.Registry.LocalMachine
|
||||
.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\ClaudeDo");
|
||||
var location = key?.GetValue("InstallLocation") as string;
|
||||
if (string.IsNullOrEmpty(location)) return null;
|
||||
var candidate = Path.Combine(location, UninstallerSubdir, InstallerExe);
|
||||
return File.Exists(candidate) ? candidate : null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
18
src/ClaudeDo.Ui/Services/PlanningDtos.cs
Normal file
18
src/ClaudeDo.Ui/Services/PlanningDtos.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
namespace ClaudeDo.Ui.Services;
|
||||
|
||||
public sealed record PlanningSessionFilesDto(
|
||||
string SessionDirectory,
|
||||
string McpConfigPath,
|
||||
string SystemPromptPath,
|
||||
string InitialPromptPath);
|
||||
|
||||
public sealed record PlanningSessionStartInfo(
|
||||
string ParentTaskId,
|
||||
string WorkingDir,
|
||||
PlanningSessionFilesDto Files);
|
||||
|
||||
public sealed record PlanningSessionResumeInfo(
|
||||
string ParentTaskId,
|
||||
string WorkingDir,
|
||||
string ClaudeSessionId,
|
||||
string McpConfigPath);
|
||||
73
src/ClaudeDo.Ui/Services/UpdateCheckService.cs
Normal file
73
src/ClaudeDo.Ui/Services/UpdateCheckService.cs
Normal file
@@ -0,0 +1,73 @@
|
||||
using ClaudeDo.Releases;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace ClaudeDo.Ui.Services;
|
||||
|
||||
public enum UpdateCheckStatus
|
||||
{
|
||||
NeverChecked,
|
||||
CheckFailed,
|
||||
UpToDate,
|
||||
UpdateAvailable,
|
||||
}
|
||||
|
||||
public sealed partial class UpdateCheckService : ObservableObject
|
||||
{
|
||||
private readonly IReleaseClient _releases;
|
||||
|
||||
[ObservableProperty] private bool _isUpdateAvailable;
|
||||
[ObservableProperty] private string? _latestVersion;
|
||||
[ObservableProperty] private string _currentVersion;
|
||||
[ObservableProperty] private bool _isChecking;
|
||||
[ObservableProperty] private UpdateCheckStatus _lastCheckStatus = UpdateCheckStatus.NeverChecked;
|
||||
|
||||
public UpdateCheckService(IReleaseClient releases, string currentVersion)
|
||||
{
|
||||
_releases = releases;
|
||||
_currentVersion = currentVersion;
|
||||
}
|
||||
|
||||
public async Task CheckNowAsync(CancellationToken ct)
|
||||
{
|
||||
IsChecking = true;
|
||||
try
|
||||
{
|
||||
GiteaRelease? rel;
|
||||
try
|
||||
{
|
||||
rel = await _releases.GetLatestReleaseAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
LastCheckStatus = UpdateCheckStatus.CheckFailed;
|
||||
IsUpdateAvailable = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (rel is null)
|
||||
{
|
||||
LastCheckStatus = UpdateCheckStatus.CheckFailed;
|
||||
IsUpdateAvailable = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var latest = (rel.TagName ?? "").TrimStart('v', 'V');
|
||||
var cmp = VersionComparer.Compare(latest, CurrentVersion);
|
||||
if (cmp.IsNewer)
|
||||
{
|
||||
LatestVersion = latest;
|
||||
IsUpdateAvailable = true;
|
||||
LastCheckStatus = UpdateCheckStatus.UpdateAvailable;
|
||||
}
|
||||
else
|
||||
{
|
||||
IsUpdateAvailable = false;
|
||||
LastCheckStatus = UpdateCheckStatus.UpToDate;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsChecking = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ using Microsoft.AspNetCore.SignalR.Client;
|
||||
namespace ClaudeDo.Ui.Services;
|
||||
|
||||
public record ActiveTask(string Slot, string TaskId, DateTime StartedAt);
|
||||
public sealed record WorkerLogEntry(string Message, WorkerLogLevel Level, DateTime TimestampUtc);
|
||||
|
||||
sealed class IndefiniteRetryPolicy : IRetryPolicy
|
||||
{
|
||||
@@ -24,7 +25,7 @@ sealed class IndefiniteRetryPolicy : IRetryPolicy
|
||||
_delays[Math.Min(retryContext.PreviousRetryCount, _delays.Length - 1)];
|
||||
}
|
||||
|
||||
public partial class WorkerClient : ObservableObject, IAsyncDisposable
|
||||
public partial class WorkerClient : ObservableObject, IAsyncDisposable, IWorkerClient
|
||||
{
|
||||
private readonly HubConnection _hub;
|
||||
private CancellationTokenSource? _startCts;
|
||||
@@ -45,6 +46,8 @@ public partial class WorkerClient : ObservableObject, IAsyncDisposable
|
||||
public event Action<string>? TaskUpdatedEvent;
|
||||
public event Action<string>? WorktreeUpdatedEvent;
|
||||
public event Action<string>? RunNowRequestedEvent;
|
||||
public event Action<string>? ListUpdatedEvent;
|
||||
public event Action<WorkerLogEntry>? WorkerLogReceivedEvent;
|
||||
|
||||
public WorkerClient(string signalRUrl)
|
||||
{
|
||||
@@ -110,6 +113,16 @@ public partial class WorkerClient : ObservableObject, IAsyncDisposable
|
||||
{
|
||||
Dispatcher.UIThread.Post(() => WorktreeUpdatedEvent?.Invoke(taskId));
|
||||
});
|
||||
|
||||
_hub.On<string>("ListUpdated", listId =>
|
||||
{
|
||||
Dispatcher.UIThread.Post(() => ListUpdatedEvent?.Invoke(listId));
|
||||
});
|
||||
|
||||
_hub.On<string, WorkerLogLevel, DateTime>("WorkerLog", (message, level, timestampUtc) =>
|
||||
{
|
||||
WorkerLogReceivedEvent?.Invoke(new WorkerLogEntry(message, level, timestampUtc));
|
||||
});
|
||||
}
|
||||
|
||||
public Task StartAsync()
|
||||
@@ -169,6 +182,34 @@ public partial class WorkerClient : ObservableObject, IAsyncDisposable
|
||||
await _hub.InvokeAsync("RunNow", taskId);
|
||||
}
|
||||
|
||||
public async Task ContinueTaskAsync(string taskId, string followUpPrompt)
|
||||
{
|
||||
await _hub.InvokeAsync("ContinueTask", taskId, followUpPrompt);
|
||||
}
|
||||
|
||||
public async Task ResetTaskAsync(string taskId)
|
||||
{
|
||||
await _hub.InvokeAsync("ResetTask", taskId);
|
||||
}
|
||||
|
||||
public async Task<MergeResultDto> MergeTaskAsync(string taskId, string targetBranch, bool removeWorktree, string commitMessage)
|
||||
{
|
||||
return await _hub.InvokeAsync<MergeResultDto>(
|
||||
"MergeTask", taskId, targetBranch, removeWorktree, commitMessage);
|
||||
}
|
||||
|
||||
public async Task<MergeTargetsDto?> GetMergeTargetsAsync(string taskId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _hub.InvokeAsync<MergeTargetsDto>("GetMergeTargets", taskId);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task CancelTaskAsync(string taskId)
|
||||
{
|
||||
await _hub.InvokeAsync("CancelTask", taskId);
|
||||
@@ -197,6 +238,18 @@ public partial class WorkerClient : ObservableObject, IAsyncDisposable
|
||||
await _hub.InvokeAsync("RefreshAgents");
|
||||
}
|
||||
|
||||
public async Task<SeedResultDto?> RestoreDefaultAgentsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _hub.InvokeAsync<SeedResultDto>("RestoreDefaultAgents");
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SeedActiveTasksAsync()
|
||||
{
|
||||
try
|
||||
@@ -243,6 +296,33 @@ public partial class WorkerClient : ObservableObject, IAsyncDisposable
|
||||
await _hub.InvokeAsync("UpdateAppSettings", dto);
|
||||
}
|
||||
|
||||
public async Task UpdateListAsync(UpdateListDto dto)
|
||||
{
|
||||
await _hub.InvokeAsync("UpdateList", dto);
|
||||
}
|
||||
|
||||
public async Task UpdateListConfigAsync(UpdateListConfigDto dto)
|
||||
{
|
||||
await _hub.InvokeAsync("UpdateListConfig", dto);
|
||||
}
|
||||
|
||||
public async Task<ListConfigDto?> GetListConfigAsync(string listId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _hub.InvokeAsync<ListConfigDto?>("GetListConfig", listId);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task UpdateTaskAgentSettingsAsync(UpdateTaskAgentSettingsDto dto)
|
||||
{
|
||||
await _hub.InvokeAsync("UpdateTaskAgentSettings", dto);
|
||||
}
|
||||
|
||||
public async Task<WorktreeCleanupDto?> CleanupFinishedWorktreesAsync()
|
||||
{
|
||||
try
|
||||
@@ -267,6 +347,33 @@ public partial class WorkerClient : ObservableObject, IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<PlanningSessionStartInfo> StartPlanningSessionAsync(string taskId, CancellationToken ct = default)
|
||||
=> await _hub.InvokeAsync<PlanningSessionStartInfo>("StartPlanningSessionAsync", taskId, ct);
|
||||
|
||||
public async Task<PlanningSessionResumeInfo> ResumePlanningSessionAsync(string taskId, CancellationToken ct = default)
|
||||
=> await _hub.InvokeAsync<PlanningSessionResumeInfo>("ResumePlanningSessionAsync", taskId, ct);
|
||||
|
||||
public async Task DiscardPlanningSessionAsync(string taskId, CancellationToken ct = default)
|
||||
=> await _hub.InvokeAsync("DiscardPlanningSessionAsync", taskId, ct);
|
||||
|
||||
public async Task<int> FinalizePlanningSessionAsync(string taskId, bool queueAgentTasks = true, CancellationToken ct = default)
|
||||
=> await _hub.InvokeAsync<int>("FinalizePlanningSessionAsync", taskId, queueAgentTasks, ct);
|
||||
|
||||
public async Task<int> GetPendingDraftCountAsync(string taskId, CancellationToken ct = default)
|
||||
=> await _hub.InvokeAsync<int>("GetPendingDraftCountAsync", taskId, ct);
|
||||
|
||||
// IWorkerClient explicit implementations (drop typed return values)
|
||||
async Task IWorkerClient.StartPlanningSessionAsync(string taskId, CancellationToken ct)
|
||||
=> await StartPlanningSessionAsync(taskId, ct);
|
||||
async Task IWorkerClient.ResumePlanningSessionAsync(string taskId, CancellationToken ct)
|
||||
=> await ResumePlanningSessionAsync(taskId, ct);
|
||||
async Task IWorkerClient.DiscardPlanningSessionAsync(string taskId, CancellationToken ct)
|
||||
=> await DiscardPlanningSessionAsync(taskId, ct);
|
||||
async Task IWorkerClient.FinalizePlanningSessionAsync(string taskId, bool queueAgentTasks, CancellationToken ct)
|
||||
=> await FinalizePlanningSessionAsync(taskId, queueAgentTasks, ct);
|
||||
async Task<int> IWorkerClient.GetPendingDraftCountAsync(string taskId, CancellationToken ct)
|
||||
=> await GetPendingDraftCountAsync(taskId, ct);
|
||||
|
||||
// DTOs for deserializing hub responses
|
||||
private sealed class ActiveTaskDto
|
||||
{
|
||||
@@ -288,3 +395,10 @@ public sealed record AppSettingsDto(
|
||||
|
||||
public sealed record WorktreeCleanupDto(int Removed);
|
||||
public sealed record WorktreeResetDto(int Removed, int TasksAffected, bool Blocked, int RunningTasks);
|
||||
public record MergeResultDto(string Status, IReadOnlyList<string> ConflictFiles, string? ErrorMessage);
|
||||
public record MergeTargetsDto(string DefaultBranch, IReadOnlyList<string> LocalBranches);
|
||||
public sealed record UpdateListDto(string Id, string Name, string? WorkingDir, string DefaultCommitType);
|
||||
public sealed record UpdateListConfigDto(string ListId, string? Model, string? SystemPrompt, string? AgentPath);
|
||||
public sealed record UpdateTaskAgentSettingsDto(string TaskId, string? Model, string? SystemPrompt, string? AgentPath);
|
||||
public sealed record ListConfigDto(string? Model, string? SystemPrompt, string? AgentPath);
|
||||
public sealed record SeedResultDto(int Copied, int Skipped);
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Text;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using ClaudeDo.Data;
|
||||
using ClaudeDo.Data.Models;
|
||||
using ClaudeDo.Data.Repositories;
|
||||
using ClaudeDo.Ui.Helpers;
|
||||
using ClaudeDo.Ui.Services;
|
||||
@@ -39,15 +40,49 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
public bool IsDone => AgentStatusLabel == "Done";
|
||||
public bool IsFailed => AgentStatusLabel == "Failed";
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ContinueCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(ResetCommand))]
|
||||
private bool _showFailedActions;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ContinueCommand))]
|
||||
private string? _latestRunSessionId;
|
||||
|
||||
partial void OnAgentStatusLabelChanged(string value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsRunning));
|
||||
OnPropertyChanged(nameof(IsDone));
|
||||
OnPropertyChanged(nameof(IsFailed));
|
||||
OnPropertyChanged(nameof(IsAgentSectionEnabled));
|
||||
ShowFailedActions = value == "Failed";
|
||||
}
|
||||
[ObservableProperty] private string? _model;
|
||||
|
||||
// Agent settings overrides
|
||||
[ObservableProperty] private string _taskModelSelection = "(inherit)";
|
||||
[ObservableProperty] private string _taskSystemPrompt = "";
|
||||
[ObservableProperty] private AgentInfo? _taskSelectedAgent;
|
||||
|
||||
[ObservableProperty] private string _effectiveModelHint = "";
|
||||
[ObservableProperty] private string _effectiveSystemPromptHint = "";
|
||||
[ObservableProperty] private string _effectiveAgentHint = "";
|
||||
|
||||
public System.Collections.ObjectModel.ObservableCollection<string> TaskModelOptions { get; } = new()
|
||||
{
|
||||
"(inherit)", "sonnet", "opus", "haiku",
|
||||
};
|
||||
|
||||
public System.Collections.ObjectModel.ObservableCollection<AgentInfo> TaskAgentOptions { get; } = new();
|
||||
|
||||
private bool _suppressAgentSave;
|
||||
private CancellationTokenSource? _agentSaveCts;
|
||||
|
||||
public bool IsAgentSectionEnabled => !IsRunning;
|
||||
|
||||
[ObservableProperty] private string? _worktreePath;
|
||||
[ObservableProperty] private string? _worktreeBaseCommit;
|
||||
[ObservableProperty] private string? _worktreeStateLabel;
|
||||
[ObservableProperty] private string? _branchLine;
|
||||
[ObservableProperty] private int _turns;
|
||||
[ObservableProperty] private int _tokens;
|
||||
@@ -75,6 +110,8 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
public ObservableCollection<LogLineViewModel> Log { get; } = new();
|
||||
public ObservableCollection<SubtaskRowViewModel> Subtasks { get; } = new();
|
||||
|
||||
[ObservableProperty] private string _newSubtaskTitle = "";
|
||||
|
||||
// Claude CLI stream-json parser + buffer for partial text deltas
|
||||
private readonly StreamLineFormatter _formatter = new();
|
||||
private readonly StringBuilder _claudeBuf = new();
|
||||
@@ -96,9 +133,15 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
// Set by the view so OpenWorktreeCommand can show the modal as a dialog
|
||||
public Func<WorktreeModalViewModel, System.Threading.Tasks.Task>? ShowWorktreeModal { get; set; }
|
||||
|
||||
// Set by the view so ApproveMergeCommand can show the modal as a dialog
|
||||
public Func<MergeModalViewModel, System.Threading.Tasks.Task>? ShowMergeModal { get; set; }
|
||||
|
||||
// Set by the view so DeleteTaskCommand can prompt yes/no before deleting
|
||||
public Func<string, System.Threading.Tasks.Task<bool>>? ConfirmAsync { get; set; }
|
||||
|
||||
// Set by the view so DeleteTaskCommand can show an error message
|
||||
public Func<string, System.Threading.Tasks.Task>? ShowErrorAsync { get; set; }
|
||||
|
||||
public DetailsIslandViewModel(IDbContextFactory<ClaudeDoDbContext> dbFactory, WorkerClient worker, IServiceProvider services)
|
||||
{
|
||||
_dbFactory = dbFactory;
|
||||
@@ -108,11 +151,16 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
// Subscribe once; filter by current task id inside the handler
|
||||
_worker.TaskMessageEvent += OnTaskMessage;
|
||||
|
||||
// Re-evaluate RunNow CanExecute when worker connection flips.
|
||||
// Re-evaluate CanExecute when worker connection flips.
|
||||
_worker.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(WorkerClient.IsConnected))
|
||||
{
|
||||
RunNowCommand.NotifyCanExecuteChanged();
|
||||
ContinueCommand.NotifyCanExecuteChanged();
|
||||
ResetCommand.NotifyCanExecuteChanged();
|
||||
ApproveMergeCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
};
|
||||
|
||||
// If the task row's live status changes (e.g. TaskStarted/Finished), mirror it.
|
||||
@@ -193,6 +241,67 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
Log.Add(new LogLineViewModel { Kind = LogKind.Claude, Text = piece });
|
||||
}
|
||||
|
||||
partial void OnTaskModelSelectionChanged(string value) => QueueAgentSave();
|
||||
partial void OnTaskSystemPromptChanged(string value) => QueueAgentSave();
|
||||
partial void OnTaskSelectedAgentChanged(AgentInfo? value) => QueueAgentSave();
|
||||
|
||||
private void QueueAgentSave()
|
||||
{
|
||||
if (_suppressAgentSave || Task is null) return;
|
||||
_agentSaveCts?.Cancel();
|
||||
_agentSaveCts = new CancellationTokenSource();
|
||||
var ct = _agentSaveCts.Token;
|
||||
_ = SaveAgentSettingsAsync(ct);
|
||||
}
|
||||
|
||||
private async System.Threading.Tasks.Task SaveAgentSettingsAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await System.Threading.Tasks.Task.Delay(300, ct);
|
||||
if (Task is null) return;
|
||||
|
||||
var model = TaskModelSelection == "(inherit)" ? null : TaskModelSelection;
|
||||
var sp = string.IsNullOrWhiteSpace(TaskSystemPrompt) ? null : TaskSystemPrompt;
|
||||
var ap = TaskSelectedAgent is null || string.IsNullOrWhiteSpace(TaskSelectedAgent.Path)
|
||||
? null : TaskSelectedAgent.Path;
|
||||
|
||||
await _worker.UpdateTaskAgentSettingsAsync(
|
||||
new ClaudeDo.Ui.Services.UpdateTaskAgentSettingsDto(Task.Id, model, sp, ap));
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch { }
|
||||
}
|
||||
|
||||
private async System.Threading.Tasks.Task LoadAgentSettingsAsync(
|
||||
ClaudeDo.Data.Models.TaskEntity entity, CancellationToken ct)
|
||||
{
|
||||
_suppressAgentSave = true;
|
||||
try
|
||||
{
|
||||
TaskAgentOptions.Clear();
|
||||
TaskAgentOptions.Add(new AgentInfo("(inherit)", "", ""));
|
||||
var agents = await _worker.GetAgentsAsync();
|
||||
foreach (var a in agents) TaskAgentOptions.Add(a);
|
||||
|
||||
TaskModelSelection = string.IsNullOrWhiteSpace(entity.Model) ? "(inherit)" : entity.Model!;
|
||||
TaskSystemPrompt = entity.SystemPrompt ?? "";
|
||||
TaskSelectedAgent = string.IsNullOrWhiteSpace(entity.AgentPath)
|
||||
? TaskAgentOptions[0]
|
||||
: (TaskAgentOptions.FirstOrDefault(a => a.Path == entity.AgentPath) ?? TaskAgentOptions[0]);
|
||||
|
||||
var listCfg = await _worker.GetListConfigAsync(entity.ListId);
|
||||
EffectiveModelHint = string.IsNullOrWhiteSpace(listCfg?.Model) ? "(global default)" : listCfg!.Model!;
|
||||
EffectiveSystemPromptHint = string.IsNullOrWhiteSpace(listCfg?.SystemPrompt) ? "(none)" : listCfg!.SystemPrompt!;
|
||||
EffectiveAgentHint = string.IsNullOrWhiteSpace(listCfg?.AgentPath)
|
||||
? "(none)" : System.IO.Path.GetFileName(listCfg!.AgentPath!);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_suppressAgentSave = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void Bind(TaskRowViewModel? row)
|
||||
{
|
||||
_loadCts?.Cancel();
|
||||
@@ -213,8 +322,25 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
Notes = "";
|
||||
Model = null;
|
||||
WorktreePath = null;
|
||||
WorktreeStateLabel = null;
|
||||
BranchLine = null;
|
||||
AgentStatusLabel = "Idle";
|
||||
LatestRunSessionId = null;
|
||||
ShowFailedActions = false;
|
||||
_suppressAgentSave = true;
|
||||
try
|
||||
{
|
||||
TaskModelSelection = "(inherit)";
|
||||
TaskSystemPrompt = "";
|
||||
TaskSelectedAgent = null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_suppressAgentSave = false;
|
||||
}
|
||||
EffectiveModelHint = "";
|
||||
EffectiveSystemPromptHint = "";
|
||||
EffectiveAgentHint = "";
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -240,12 +366,24 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
Notes = entity.Notes ?? "";
|
||||
Model = entity.Model;
|
||||
WorktreePath = entity.Worktree?.Path;
|
||||
WorktreeBaseCommit = entity.Worktree?.BaseCommit;
|
||||
WorktreeStateLabel = entity.Worktree?.State.ToString();
|
||||
BranchLine = entity.Worktree is { } w ? $"{w.BranchName} \u2190 main" : null;
|
||||
AgentStatusLabel = entity.Status.ToString();
|
||||
await LoadAgentSettingsAsync(entity, ct);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
var runRepo = new TaskRunRepository(ctx);
|
||||
var latestRun = await runRepo.GetLatestByTaskIdAsync(row.Id, ct);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
LatestRunSessionId = latestRun?.SessionId;
|
||||
|
||||
// Subscribe only after DB load confirms the task exists
|
||||
_subscribedTaskId = row.Id;
|
||||
|
||||
// Replay the latest run's persisted log so output is visible across app restarts.
|
||||
await ReplayLogFileAsync(entity.LogPath, ct);
|
||||
|
||||
var subs = await subtaskRepo.GetByTaskIdAsync(row.Id);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
foreach (var s in subs)
|
||||
@@ -254,6 +392,59 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
catch (OperationCanceledException) { }
|
||||
}
|
||||
|
||||
private async System.Threading.Tasks.Task ReplayLogFileAsync(string? logPath, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(logPath)) return;
|
||||
var expanded = ExpandUserPath(logPath);
|
||||
if (!System.IO.File.Exists(expanded)) return;
|
||||
|
||||
try
|
||||
{
|
||||
const int maxLines = 2000;
|
||||
string[] all;
|
||||
await using (var fs = new System.IO.FileStream(
|
||||
expanded,
|
||||
System.IO.FileMode.Open,
|
||||
System.IO.FileAccess.Read,
|
||||
System.IO.FileShare.ReadWrite | System.IO.FileShare.Delete))
|
||||
using (var reader = new System.IO.StreamReader(fs))
|
||||
{
|
||||
var list = new List<string>();
|
||||
while (await reader.ReadLineAsync(ct) is { } line)
|
||||
list.Add(line);
|
||||
all = list.ToArray();
|
||||
}
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
var start = Math.Max(0, all.Length - maxLines);
|
||||
for (int i = start; i < all.Length; i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (_subscribedTaskId is null) return;
|
||||
// Worker writes raw Claude CLI stdout to disk (no prefix) but broadcasts
|
||||
// it with a "[stdout] " prefix. Match the live-stream format so the same
|
||||
// stream-json parser handles both.
|
||||
var line = all[i];
|
||||
var normalized = line.StartsWith("[", StringComparison.Ordinal) ? line : "[stdout] " + line;
|
||||
OnTaskMessage(_subscribedTaskId, normalized);
|
||||
}
|
||||
FlushClaudeBuffer();
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch { /* best-effort replay */ }
|
||||
}
|
||||
|
||||
private static string ExpandUserPath(string path)
|
||||
{
|
||||
if (path.StartsWith("~/", StringComparison.Ordinal) || path.StartsWith("~\\", StringComparison.Ordinal))
|
||||
return System.IO.Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
|
||||
path[2..]);
|
||||
if (path == "~")
|
||||
return Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
return path;
|
||||
}
|
||||
|
||||
private async System.Threading.Tasks.Task RefreshWorktreeAsync(string taskId)
|
||||
{
|
||||
try
|
||||
@@ -267,6 +458,7 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
|
||||
WorktreePath = entity.Worktree?.Path;
|
||||
WorktreeBaseCommit = entity.Worktree?.BaseCommit;
|
||||
WorktreeStateLabel = entity.Worktree?.State.ToString();
|
||||
BranchLine = entity.Worktree is { } w ? $"{w.BranchName} ← main" : null;
|
||||
AgentStatusLabel = entity.Status.ToString();
|
||||
if (Task is { } row && entity.Worktree?.DiffStat is { } stat)
|
||||
@@ -283,6 +475,10 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
{
|
||||
WorktreePath = WorktreePath,
|
||||
BaseRef = WorktreeBaseCommit,
|
||||
TaskId = Task?.Id,
|
||||
TaskTitle = Task?.Title ?? "",
|
||||
ShowMergeModal = ShowMergeModal,
|
||||
ResolveMergeVm = () => _services.GetRequiredService<MergeModalViewModel>(),
|
||||
};
|
||||
await diffVm.LoadAsync();
|
||||
await ShowDiffModal(diffVm);
|
||||
@@ -311,6 +507,12 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
{
|
||||
OpenDiffCommand.NotifyCanExecuteChanged();
|
||||
OpenWorktreeCommand.NotifyCanExecuteChanged();
|
||||
ApproveMergeCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
partial void OnWorktreeStateLabelChanged(string? value)
|
||||
{
|
||||
ApproveMergeCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
@@ -338,14 +540,49 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
var ok = await ConfirmAsync($"Delete \"{row.Title}\"? This cannot be undone.");
|
||||
if (!ok) return;
|
||||
}
|
||||
try
|
||||
{
|
||||
await using var ctx = _dbFactory.CreateDbContext();
|
||||
var repo = new TaskRepository(ctx);
|
||||
await repo.DeleteAsync(row.Id);
|
||||
}
|
||||
catch (DbUpdateException ex) when (
|
||||
ex.Message.Contains("FOREIGN KEY", StringComparison.OrdinalIgnoreCase)
|
||||
|| ex.InnerException?.Message.Contains("FOREIGN KEY", StringComparison.OrdinalIgnoreCase) == true)
|
||||
{
|
||||
if (ShowErrorAsync != null)
|
||||
await ShowErrorAsync("This task has child tasks. Discard the planning session or delete child tasks first.");
|
||||
return;
|
||||
}
|
||||
if (DeleteFromList != null)
|
||||
await DeleteFromList(row);
|
||||
CloseDetail?.Invoke();
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async System.Threading.Tasks.Task AddSubtaskAsync()
|
||||
{
|
||||
if (Task is null) return;
|
||||
var title = NewSubtaskTitle?.Trim();
|
||||
if (string.IsNullOrEmpty(title)) return;
|
||||
|
||||
var entity = new ClaudeDo.Data.Models.SubtaskEntity
|
||||
{
|
||||
Id = Guid.NewGuid().ToString(),
|
||||
TaskId = Task.Id,
|
||||
Title = title,
|
||||
Completed = false,
|
||||
OrderNum = Subtasks.Count,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
};
|
||||
|
||||
await using var ctx = _dbFactory.CreateDbContext();
|
||||
await new SubtaskRepository(ctx).AddAsync(entity);
|
||||
|
||||
Subtasks.Add(new SubtaskRowViewModel { Id = entity.Id, Title = entity.Title, Done = entity.Completed });
|
||||
NewSubtaskTitle = "";
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async System.Threading.Tasks.Task SaveNotesAsync()
|
||||
{
|
||||
@@ -358,14 +595,18 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
await repo.UpdateAsync(entity);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
[RelayCommand(CanExecute = nameof(CanMerge))]
|
||||
private async System.Threading.Tasks.Task ApproveMergeAsync()
|
||||
{
|
||||
if (Task == null) return;
|
||||
// TODO: call worker merge hub method when available
|
||||
await System.Threading.Tasks.Task.CompletedTask;
|
||||
if (Task == null || ShowMergeModal == null) return;
|
||||
var vm = _services.GetRequiredService<MergeModalViewModel>();
|
||||
await vm.InitializeAsync(Task.Id, Task.Title);
|
||||
await ShowMergeModal(vm);
|
||||
}
|
||||
|
||||
private bool CanMerge() =>
|
||||
Task != null && _worker.IsConnected && WorktreePath != null && WorktreeStateLabel == "Active";
|
||||
|
||||
[RelayCommand]
|
||||
private async System.Threading.Tasks.Task StopAsync()
|
||||
{
|
||||
@@ -391,6 +632,32 @@ public sealed partial class DetailsIslandViewModel : ViewModelBase
|
||||
|
||||
private bool CanRunNow() =>
|
||||
Task != null && _worker.IsConnected && !IsRunning;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanContinue))]
|
||||
private async System.Threading.Tasks.Task ContinueAsync()
|
||||
{
|
||||
if (Task == null) return;
|
||||
await _worker.ContinueTaskAsync(Task.Id, "Continue working on this task.");
|
||||
}
|
||||
|
||||
private bool CanContinue() =>
|
||||
Task != null && _worker.IsConnected && ShowFailedActions && !string.IsNullOrEmpty(LatestRunSessionId);
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanReset))]
|
||||
private async System.Threading.Tasks.Task ResetAsync()
|
||||
{
|
||||
if (Task == null) return;
|
||||
if (ConfirmAsync == null) return;
|
||||
|
||||
var branchName = $"claudedo/{Task.Id.Replace("-", "")}";
|
||||
var ok = await ConfirmAsync($"Discard worktree and reset task?\nThis deletes branch {branchName} and all uncommitted changes.");
|
||||
if (!ok) return;
|
||||
|
||||
await _worker.ResetTaskAsync(Task.Id);
|
||||
}
|
||||
|
||||
private bool CanReset() =>
|
||||
Task != null && _worker.IsConnected && ShowFailedActions;
|
||||
}
|
||||
|
||||
public sealed partial class SubtaskRowViewModel : ViewModelBase
|
||||
|
||||
@@ -9,6 +9,8 @@ public sealed partial class ListNavItemViewModel : ViewModelBase
|
||||
public required ListKind Kind { get; init; }
|
||||
[ObservableProperty] private int _count;
|
||||
[ObservableProperty] private bool _isActive;
|
||||
[ObservableProperty] private string? _workingDir;
|
||||
[ObservableProperty] private string _defaultCommitType = "chore";
|
||||
public string? IconKey { get; init; }
|
||||
public string? DotColorKey { get; init; }
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@ using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using ClaudeDo.Data;
|
||||
using ClaudeDo.Data.Models;
|
||||
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;
|
||||
using ClaudeDo.Data.Repositories;
|
||||
using ClaudeDo.Ui.Services;
|
||||
using ClaudeDo.Ui.ViewModels.Modals;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@@ -15,12 +18,14 @@ public sealed partial class ListsIslandViewModel : ViewModelBase
|
||||
{
|
||||
private readonly IDbContextFactory<ClaudeDoDbContext> _dbFactory;
|
||||
private readonly IServiceProvider? _services;
|
||||
private readonly WorkerClient? _worker;
|
||||
|
||||
public event EventHandler? SelectionChanged;
|
||||
public event EventHandler? FocusSearchRequested;
|
||||
public void RequestFocusSearch() => FocusSearchRequested?.Invoke(this, EventArgs.Empty);
|
||||
|
||||
public Func<SettingsModalViewModel, Task>? ShowSettingsModal { get; set; }
|
||||
public Func<ListSettingsModalViewModel, System.Threading.Tasks.Task>? ShowListSettingsModal { get; set; }
|
||||
|
||||
[RelayCommand]
|
||||
private async Task OpenSettings()
|
||||
@@ -31,6 +36,16 @@ public sealed partial class ListsIslandViewModel : ViewModelBase
|
||||
await ShowSettingsModal(settingsVm);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async System.Threading.Tasks.Task OpenListSettingsAsync(ListNavItemViewModel? row)
|
||||
{
|
||||
if (row is null || ShowListSettingsModal is null || _services is null) return;
|
||||
var vm = _services.GetRequiredService<ListSettingsModalViewModel>();
|
||||
await vm.LoadAsync(row.Id, row.Name, row.WorkingDir, row.DefaultCommitType);
|
||||
await ShowListSettingsModal(vm);
|
||||
await RefreshRowAsync(row.Id);
|
||||
}
|
||||
|
||||
public ObservableCollection<ListNavItemViewModel> Items { get; } = new();
|
||||
public ObservableCollection<ListNavItemViewModel> SmartLists { get; } = new();
|
||||
public ObservableCollection<ListNavItemViewModel> UserLists { get; } = new();
|
||||
@@ -42,16 +57,25 @@ public sealed partial class ListsIslandViewModel : ViewModelBase
|
||||
public string MachineName { get; } = Environment.MachineName;
|
||||
public string UserInitials { get; }
|
||||
|
||||
public ListsIslandViewModel(IDbContextFactory<ClaudeDoDbContext> dbFactory, IServiceProvider? services = null)
|
||||
public ListsIslandViewModel(IDbContextFactory<ClaudeDoDbContext> dbFactory, IServiceProvider? services = null, WorkerClient? worker = null)
|
||||
{
|
||||
_dbFactory = dbFactory;
|
||||
_services = services;
|
||||
_worker = worker;
|
||||
var parts = Environment.UserName.Split('.', '_', '-', ' ');
|
||||
UserInitials = parts.Length >= 2
|
||||
? $"{parts[0][0]}{parts[1][0]}".ToUpperInvariant()
|
||||
: Environment.UserName.Length >= 2
|
||||
? Environment.UserName[..2].ToUpperInvariant()
|
||||
: Environment.UserName.ToUpperInvariant();
|
||||
|
||||
if (_worker is not null)
|
||||
{
|
||||
_worker.ListUpdatedEvent += id => _ = RefreshRowAsync(id);
|
||||
_worker.TaskStartedEvent += (_slot, _id, _at) => _ = RefreshCountsAsync();
|
||||
_worker.TaskFinishedEvent += (_slot, _id, _status, _at) => _ = RefreshCountsAsync();
|
||||
_worker.TaskUpdatedEvent += _id => _ = RefreshCountsAsync();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task LoadAsync(CancellationToken ct = default)
|
||||
@@ -65,6 +89,7 @@ public sealed partial class ListsIslandViewModel : ViewModelBase
|
||||
new ListNavItemViewModel { Id = "smart:my-day", Name = "My Day", Kind = ListKind.Smart, IconKey = "Sun" },
|
||||
new ListNavItemViewModel { Id = "smart:important", Name = "Important", Kind = ListKind.Smart, IconKey = "Star" },
|
||||
new ListNavItemViewModel { Id = "smart:planned", Name = "Planned", Kind = ListKind.Smart, IconKey = "Calendar" },
|
||||
new ListNavItemViewModel { Id = "virtual:queued", Name = "Queue", Kind = ListKind.Virtual, IconKey = "Inbox" },
|
||||
new ListNavItemViewModel { Id = "virtual:running", Name = "Running", Kind = ListKind.Virtual, IconKey = "Activity" },
|
||||
new ListNavItemViewModel { Id = "virtual:review", Name = "Review", Kind = ListKind.Virtual, IconKey = "Eye" },
|
||||
};
|
||||
@@ -85,6 +110,8 @@ public sealed partial class ListsIslandViewModel : ViewModelBase
|
||||
Kind = ListKind.User,
|
||||
IconKey = "Folder",
|
||||
DotColorKey = dotColors[idx % dotColors.Length],
|
||||
WorkingDir = l.WorkingDir,
|
||||
DefaultCommitType = l.DefaultCommitType,
|
||||
};
|
||||
Items.Add(item);
|
||||
UserLists.Add(item);
|
||||
@@ -97,8 +124,46 @@ public sealed partial class ListsIslandViewModel : ViewModelBase
|
||||
|
||||
public async Task RefreshCountsAsync(CancellationToken ct = default)
|
||||
{
|
||||
foreach (var i in Items) i.Count = 0;
|
||||
await Task.CompletedTask;
|
||||
try
|
||||
{
|
||||
await using var ctx = await _dbFactory.CreateDbContextAsync(ct);
|
||||
|
||||
// Snapshot the open (non-Done) tasks once; small enough collection for client-side grouping.
|
||||
var open = await ctx.Tasks.AsNoTracking()
|
||||
.Where(t => t.Status != TaskStatus.Done)
|
||||
.Select(t => new { t.ListId, t.Status, t.IsMyDay, t.IsStarred, Scheduled = t.ScheduledFor })
|
||||
.ToListAsync(ct);
|
||||
|
||||
var running = open.Count(t => t.Status == TaskStatus.Running);
|
||||
var queued = open.Count(t => t.Status == TaskStatus.Queued);
|
||||
var review = await ctx.Tasks.AsNoTracking()
|
||||
.Where(t => t.Status == TaskStatus.Done && t.Worktree != null && t.Worktree.State == WorktreeState.Active)
|
||||
.CountAsync(ct);
|
||||
|
||||
foreach (var item in SmartLists)
|
||||
{
|
||||
item.Count = item.Id switch
|
||||
{
|
||||
"smart:my-day" => open.Count(t => t.IsMyDay),
|
||||
"smart:important" => open.Count(t => t.IsStarred),
|
||||
"smart:planned" => open.Count(t => t.Scheduled != null),
|
||||
"virtual:queued" => queued,
|
||||
"virtual:running" => running,
|
||||
"virtual:review" => review,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
|
||||
foreach (var item in UserLists)
|
||||
{
|
||||
var listId = item.Id.StartsWith("user:", StringComparison.Ordinal)
|
||||
? item.Id["user:".Length..]
|
||||
: item.Id;
|
||||
item.Count = open.Count(t => t.ListId == listId);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch { /* best-effort refresh */ }
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
@@ -109,4 +174,23 @@ public sealed partial class ListsIslandViewModel : ViewModelBase
|
||||
foreach (var i in Items) i.IsActive = ReferenceEquals(i, value);
|
||||
SelectionChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
private async System.Threading.Tasks.Task RefreshRowAsync(string rowId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var rawId = rowId.StartsWith("user:") ? rowId["user:".Length..] : rowId;
|
||||
var row = UserLists.FirstOrDefault(r => r.Id == rowId);
|
||||
if (row is null) return;
|
||||
|
||||
await using var ctx = await _dbFactory.CreateDbContextAsync();
|
||||
var lists = new ListRepository(ctx);
|
||||
var entity = await lists.GetByIdAsync(rawId);
|
||||
if (entity is null) return;
|
||||
|
||||
row.WorkingDir = entity.WorkingDir;
|
||||
row.DefaultCommitType = entity.DefaultCommitType;
|
||||
}
|
||||
catch { /* best-effort refresh */ }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,10 @@ public sealed partial class TaskRowViewModel : ViewModelBase
|
||||
[ObservableProperty] private DateTime? _scheduledFor;
|
||||
[ObservableProperty] private int _diffAdditions;
|
||||
[ObservableProperty] private int _diffDeletions;
|
||||
[ObservableProperty] private bool _dropHintAbove;
|
||||
[ObservableProperty] private bool _dropHintBelow;
|
||||
[ObservableProperty] private string? _parentTaskId;
|
||||
[ObservableProperty] private bool _isExpanded = true;
|
||||
|
||||
public DateTime CreatedAt { get; init; }
|
||||
public string CreatedAtFormatted => CreatedAt == default ? "—" : $"Created {CreatedAt:MMM d}";
|
||||
@@ -29,12 +33,28 @@ public sealed partial class TaskRowViewModel : ViewModelBase
|
||||
public int StepsCount { get; init; }
|
||||
public int StepsCompleted { get; init; }
|
||||
|
||||
public bool IsChild => !string.IsNullOrEmpty(ParentTaskId);
|
||||
public bool IsPlanningParent => Status == TaskStatus.Planning || Status == TaskStatus.Planned;
|
||||
public bool IsDraft => Status == TaskStatus.Draft;
|
||||
|
||||
public bool CanOpenPlanningSession => Status == TaskStatus.Manual && !IsChild;
|
||||
public bool CanResumeOrDiscardPlanning => Status == TaskStatus.Planning;
|
||||
|
||||
public string? PlanningBadge => Status switch
|
||||
{
|
||||
TaskStatus.Planning => "PLANNING",
|
||||
TaskStatus.Planned => "PLANNED",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
public bool HasBranch => !string.IsNullOrWhiteSpace(Branch);
|
||||
public bool HasDiff => DiffAdditions > 0 || DiffDeletions > 0;
|
||||
public bool HasTags => Tags.Count > 0;
|
||||
public bool HasSteps => StepsCount > 0;
|
||||
public bool IsOverdue => ScheduledFor is { } d && d.Date < DateTime.Today && !Done;
|
||||
public bool IsRunning => Status == TaskStatus.Running;
|
||||
public bool IsQueued => Status == TaskStatus.Queued;
|
||||
public bool HasSchedule => ScheduledFor.HasValue;
|
||||
public bool HasLiveTail => IsRunning && !string.IsNullOrEmpty(LiveTail);
|
||||
|
||||
public string DiffAdditionsText => $"+{DiffAdditions}";
|
||||
@@ -54,13 +74,29 @@ public sealed partial class TaskRowViewModel : ViewModelBase
|
||||
{
|
||||
OnPropertyChanged(nameof(StatusChipClass));
|
||||
OnPropertyChanged(nameof(IsRunning));
|
||||
OnPropertyChanged(nameof(IsQueued));
|
||||
OnPropertyChanged(nameof(HasLiveTail));
|
||||
OnPropertyChanged(nameof(IsPlanningParent));
|
||||
OnPropertyChanged(nameof(PlanningBadge));
|
||||
OnPropertyChanged(nameof(IsDraft));
|
||||
OnPropertyChanged(nameof(CanOpenPlanningSession));
|
||||
OnPropertyChanged(nameof(CanResumeOrDiscardPlanning));
|
||||
}
|
||||
|
||||
partial void OnParentTaskIdChanged(string? value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsChild));
|
||||
OnPropertyChanged(nameof(CanOpenPlanningSession));
|
||||
}
|
||||
|
||||
partial void OnBranchChanged(string? value) => OnPropertyChanged(nameof(HasBranch));
|
||||
partial void OnLiveTailChanged(string? value) => OnPropertyChanged(nameof(HasLiveTail));
|
||||
partial void OnDoneChanged(bool value) => OnPropertyChanged(nameof(IsOverdue));
|
||||
partial void OnScheduledForChanged(DateTime? value) => OnPropertyChanged(nameof(IsOverdue));
|
||||
partial void OnScheduledForChanged(DateTime? value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsOverdue));
|
||||
OnPropertyChanged(nameof(HasSchedule));
|
||||
}
|
||||
partial void OnDiffAdditionsChanged(int value) { OnPropertyChanged(nameof(HasDiff)); OnPropertyChanged(nameof(DiffAdditionsText)); }
|
||||
partial void OnDiffDeletionsChanged(int value) { OnPropertyChanged(nameof(HasDiff)); OnPropertyChanged(nameof(DiffDeletionsText)); }
|
||||
|
||||
@@ -82,6 +118,7 @@ public sealed partial class TaskRowViewModel : ViewModelBase
|
||||
DiffAdditions = add,
|
||||
DiffDeletions = del,
|
||||
CreatedAt = t.CreatedAt,
|
||||
ParentTaskId = t.ParentTaskId,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using ClaudeDo.Data;
|
||||
using ClaudeDo.Data.Models;
|
||||
using ClaudeDo.Ui.Services;
|
||||
using ClaudeDo.Ui.ViewModels.Modals;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;
|
||||
|
||||
@@ -12,11 +14,14 @@ namespace ClaudeDo.Ui.ViewModels.Islands;
|
||||
public sealed partial class TasksIslandViewModel : ViewModelBase
|
||||
{
|
||||
private readonly IDbContextFactory<ClaudeDoDbContext> _dbFactory;
|
||||
private readonly IWorkerClient? _worker;
|
||||
private readonly Dictionary<string, bool> _expandedState = new();
|
||||
private ListNavItemViewModel? _currentList;
|
||||
private CancellationTokenSource? _loadCts;
|
||||
|
||||
public event EventHandler? SelectionChanged;
|
||||
public event EventHandler? FocusAddTaskRequested;
|
||||
public event EventHandler? TasksChanged;
|
||||
public void RequestFocusAddTask() => FocusAddTaskRequested?.Invoke(this, EventArgs.Empty);
|
||||
|
||||
public ObservableCollection<TaskRowViewModel> Items { get; } = new();
|
||||
@@ -38,9 +43,12 @@ public sealed partial class TasksIslandViewModel : ViewModelBase
|
||||
[ObservableProperty] private bool _showOpenLabel;
|
||||
[ObservableProperty] private string _completedHeader = "COMPLETED";
|
||||
|
||||
public TasksIslandViewModel(IDbContextFactory<ClaudeDoDbContext> dbFactory)
|
||||
public Func<UnfinishedPlanningModalViewModel, Task>? ShowUnfinishedPlanningModal { get; set; }
|
||||
|
||||
public TasksIslandViewModel(IDbContextFactory<ClaudeDoDbContext> dbFactory, IWorkerClient? worker = null)
|
||||
{
|
||||
_dbFactory = dbFactory;
|
||||
_worker = worker;
|
||||
}
|
||||
|
||||
public void LoadForList(ListNavItemViewModel? list)
|
||||
@@ -75,6 +83,7 @@ public sealed partial class TasksIslandViewModel : ViewModelBase
|
||||
var all = await db.Tasks
|
||||
.Include(t => t.List)
|
||||
.Include(t => t.Worktree)
|
||||
.OrderBy(t => t.SortOrder).ThenBy(t => t.CreatedAt)
|
||||
.ToListAsync(ct);
|
||||
|
||||
ct.ThrowIfCancellationRequested();
|
||||
@@ -84,6 +93,7 @@ public sealed partial class TasksIslandViewModel : ViewModelBase
|
||||
ListKind.Smart when list.Id == "smart:my-day" => all.Where(t => t.IsMyDay),
|
||||
ListKind.Smart when list.Id == "smart:important" => all.Where(t => t.IsStarred),
|
||||
ListKind.Smart when list.Id == "smart:planned" => all.Where(t => t.ScheduledFor != null),
|
||||
ListKind.Virtual when list.Id == "virtual:queued" => all.Where(t => t.Status == TaskStatus.Queued),
|
||||
ListKind.Virtual when list.Id == "virtual:running" => all.Where(t => t.Status == TaskStatus.Running),
|
||||
ListKind.Virtual when list.Id == "virtual:review" => all.Where(t => t.Status == TaskStatus.Done && t.Worktree?.State == WorktreeState.Active),
|
||||
ListKind.User => all.Where(t => $"user:{t.ListId}" == list.Id),
|
||||
@@ -99,14 +109,35 @@ public sealed partial class TasksIslandViewModel : ViewModelBase
|
||||
catch (OperationCanceledException) { }
|
||||
}
|
||||
|
||||
private void Regroup()
|
||||
internal void Regroup()
|
||||
{
|
||||
OverdueItems.Clear();
|
||||
OpenItems.Clear();
|
||||
CompletedItems.Clear();
|
||||
|
||||
var today = DateTime.Today;
|
||||
// Restore IsExpanded from saved state
|
||||
foreach (var r in Items)
|
||||
{
|
||||
if (_expandedState.TryGetValue(r.Id, out var saved))
|
||||
r.IsExpanded = saved;
|
||||
}
|
||||
|
||||
// Build hierarchy-aware flat list: top-level rows interleaved with visible children.
|
||||
// Items is already ordered by SortOrder from the DB query.
|
||||
var topLevel = Items.Where(r => !r.IsChild);
|
||||
var flat = new List<TaskRowViewModel>();
|
||||
foreach (var parent in topLevel)
|
||||
{
|
||||
flat.Add(parent);
|
||||
if (parent.IsPlanningParent && parent.IsExpanded)
|
||||
{
|
||||
var children = Items.Where(r => r.ParentTaskId == parent.Id);
|
||||
flat.AddRange(children);
|
||||
}
|
||||
}
|
||||
|
||||
var today = DateTime.Today;
|
||||
foreach (var r in flat)
|
||||
{
|
||||
if (r.Done)
|
||||
CompletedItems.Add(r);
|
||||
@@ -149,21 +180,108 @@ public sealed partial class TasksIslandViewModel : ViewModelBase
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(NewTaskTitle) || _currentList?.Kind != ListKind.User) return;
|
||||
var listId = _currentList.Id["user:".Length..];
|
||||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||||
var maxSort = await db.Tasks
|
||||
.Where(t => t.ListId == listId)
|
||||
.Select(t => (int?)t.SortOrder)
|
||||
.MaxAsync();
|
||||
var entity = new TaskEntity
|
||||
{
|
||||
Id = Guid.NewGuid().ToString("N"),
|
||||
ListId = listId,
|
||||
Title = NewTaskTitle.Trim(),
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
SortOrder = (maxSort ?? -1) + 1,
|
||||
};
|
||||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||||
db.Tasks.Add(entity);
|
||||
await db.SaveChangesAsync();
|
||||
var row = TaskRowViewModel.FromEntity(entity);
|
||||
Items.Insert(0, row);
|
||||
Items.Add(row);
|
||||
Regroup();
|
||||
NewTaskTitle = "";
|
||||
UpdateSubtitle();
|
||||
TasksChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public bool CanReorder => _currentList?.Kind == ListKind.User;
|
||||
|
||||
public void ClearDropHints()
|
||||
{
|
||||
foreach (var r in Items)
|
||||
{
|
||||
r.DropHintAbove = false;
|
||||
r.DropHintBelow = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void SetDropHint(TaskRowViewModel target, bool placeBelow)
|
||||
{
|
||||
foreach (var r in Items)
|
||||
{
|
||||
var isTarget = ReferenceEquals(r, target);
|
||||
r.DropHintAbove = isTarget && !placeBelow;
|
||||
r.DropHintBelow = isTarget && placeBelow;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task ReorderAsync(TaskRowViewModel source, TaskRowViewModel target, bool placeBelow)
|
||||
{
|
||||
if (!CanReorder || _currentList is null) return;
|
||||
if (source.IsRunning || target.IsRunning) return;
|
||||
if (ReferenceEquals(source, target)) return;
|
||||
|
||||
// Master Items: single Move event (no Reset) so ItemsControls animate, not rebuild.
|
||||
MoveWithinCollection(Items, source, target, placeBelow);
|
||||
|
||||
// Apply the same move in whichever section the row lives in.
|
||||
// Reorder never changes which section (Open/Overdue/Completed) a row belongs to —
|
||||
// that's determined by Done flag and ScheduledFor date, not drag-drop.
|
||||
var sourceSection = SectionFor(source);
|
||||
var targetSection = SectionFor(target);
|
||||
if (sourceSection is not null && ReferenceEquals(sourceSection, targetSection))
|
||||
MoveWithinCollection(sourceSection, source, target, placeBelow);
|
||||
|
||||
var listId = _currentList.Id["user:".Length..];
|
||||
var orderedIds = Items.Select(i => i.Id).ToList();
|
||||
|
||||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||||
var idSet = orderedIds.ToHashSet();
|
||||
var entities = await db.Tasks
|
||||
.Where(t => t.ListId == listId && idSet.Contains(t.Id))
|
||||
.ToListAsync();
|
||||
for (int i = 0; i < orderedIds.Count; i++)
|
||||
{
|
||||
var e = entities.FirstOrDefault(x => x.Id == orderedIds[i]);
|
||||
if (e is not null) e.SortOrder = i;
|
||||
}
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private static void MoveWithinCollection(
|
||||
System.Collections.ObjectModel.ObservableCollection<TaskRowViewModel> coll,
|
||||
TaskRowViewModel source,
|
||||
TaskRowViewModel target,
|
||||
bool placeBelow)
|
||||
{
|
||||
var srcIdx = coll.IndexOf(source);
|
||||
var tgtIdx = coll.IndexOf(target);
|
||||
if (srcIdx < 0 || tgtIdx < 0 || srcIdx == tgtIdx) return;
|
||||
|
||||
var finalIdx = placeBelow ? tgtIdx + 1 : tgtIdx;
|
||||
if (srcIdx < finalIdx) finalIdx--;
|
||||
if (finalIdx < 0) finalIdx = 0;
|
||||
if (finalIdx >= coll.Count) finalIdx = coll.Count - 1;
|
||||
if (finalIdx == srcIdx) return;
|
||||
|
||||
coll.Move(srcIdx, finalIdx);
|
||||
}
|
||||
|
||||
private System.Collections.ObjectModel.ObservableCollection<TaskRowViewModel>? SectionFor(TaskRowViewModel row)
|
||||
{
|
||||
if (OverdueItems.Contains(row)) return OverdueItems;
|
||||
if (OpenItems.Contains(row)) return OpenItems;
|
||||
if (CompletedItems.Contains(row)) return CompletedItems;
|
||||
return null;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
@@ -180,6 +298,7 @@ public sealed partial class TasksIslandViewModel : ViewModelBase
|
||||
}
|
||||
Regroup();
|
||||
UpdateSubtitle();
|
||||
TasksChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
@@ -193,8 +312,61 @@ public sealed partial class TasksIslandViewModel : ViewModelBase
|
||||
entity.IsStarred = row.IsStarred;
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
TasksChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task SendToQueueAsync(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null || row.IsRunning) return;
|
||||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||||
var entity = await db.Tasks.FirstOrDefaultAsync(t => t.Id == row.Id);
|
||||
if (entity is null) return;
|
||||
entity.Status = TaskStatus.Queued;
|
||||
await db.SaveChangesAsync();
|
||||
row.Status = TaskStatus.Queued;
|
||||
if (_worker is not null)
|
||||
{
|
||||
try { await _worker.WakeQueueAsync(); } catch { }
|
||||
}
|
||||
Regroup();
|
||||
UpdateSubtitle();
|
||||
TasksChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task RemoveFromQueueAsync(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null) return;
|
||||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||||
var entity = await db.Tasks.FirstOrDefaultAsync(t => t.Id == row.Id);
|
||||
if (entity is null) return;
|
||||
entity.Status = TaskStatus.Manual;
|
||||
await db.SaveChangesAsync();
|
||||
row.Status = TaskStatus.Manual;
|
||||
Regroup();
|
||||
UpdateSubtitle();
|
||||
TasksChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public async Task SetScheduledForAsync(TaskRowViewModel row, DateTime? when)
|
||||
{
|
||||
if (row is null) return;
|
||||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||||
var entity = await db.Tasks.FirstOrDefaultAsync(t => t.Id == row.Id);
|
||||
if (entity is null) return;
|
||||
entity.ScheduledFor = when;
|
||||
await db.SaveChangesAsync();
|
||||
row.ScheduledFor = when;
|
||||
Regroup();
|
||||
UpdateSubtitle();
|
||||
TasksChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private Task ClearScheduleAsync(TaskRowViewModel? row) =>
|
||||
row is null ? Task.CompletedTask : SetScheduledForAsync(row, null);
|
||||
|
||||
[RelayCommand]
|
||||
private void Select(TaskRowViewModel row) => SelectedTask = row;
|
||||
|
||||
@@ -204,8 +376,83 @@ public sealed partial class TasksIslandViewModel : ViewModelBase
|
||||
[RelayCommand]
|
||||
private void Sort() { /* placeholder — UI-only */ }
|
||||
|
||||
public event EventHandler? OpenListSettingsRequested;
|
||||
|
||||
[RelayCommand]
|
||||
private void More() { /* placeholder — UI-only */ }
|
||||
private void OpenListSettings() => OpenListSettingsRequested?.Invoke(this, EventArgs.Empty);
|
||||
|
||||
[RelayCommand]
|
||||
private async Task OpenPlanningSessionAsync(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null || row.Status != TaskStatus.Manual) return;
|
||||
try { await _worker!.StartPlanningSessionAsync(row.Id); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task ResumePlanningSessionAsync(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null || !row.IsPlanningParent) return;
|
||||
if (_worker is null) return;
|
||||
try
|
||||
{
|
||||
var draftCount = await _worker.GetPendingDraftCountAsync(row.Id);
|
||||
var modalVm = new UnfinishedPlanningModalViewModel
|
||||
{
|
||||
TaskTitle = row.Title,
|
||||
DraftCount = draftCount,
|
||||
};
|
||||
|
||||
if (ShowUnfinishedPlanningModal is null)
|
||||
return;
|
||||
await ShowUnfinishedPlanningModal(modalVm);
|
||||
|
||||
var choice = await modalVm.Result.Task;
|
||||
|
||||
switch (choice)
|
||||
{
|
||||
case UnfinishedPlanningModalResult.Resume:
|
||||
await _worker.ResumePlanningSessionAsync(row.Id);
|
||||
break;
|
||||
case UnfinishedPlanningModalResult.FinalizeNow:
|
||||
await _worker.FinalizePlanningSessionAsync(row.Id);
|
||||
break;
|
||||
case UnfinishedPlanningModalResult.Discard:
|
||||
await _worker.DiscardPlanningSessionAsync(row.Id);
|
||||
break;
|
||||
case UnfinishedPlanningModalResult.Cancel:
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task DiscardPlanningSessionAsync(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null) return;
|
||||
try { await _worker!.DiscardPlanningSessionAsync(row.Id); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task FinalizePlanningSessionAsync(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null) return;
|
||||
try { await _worker!.FinalizePlanningSessionAsync(row.Id, queueAgentTasks: true); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void ToggleExpand(TaskRowViewModel? row)
|
||||
{
|
||||
if (row is null) return;
|
||||
var next = !(_expandedState.TryGetValue(row.Id, out var current) ? current : row.IsExpanded);
|
||||
_expandedState[row.Id] = next;
|
||||
row.IsExpanded = next;
|
||||
Regroup();
|
||||
}
|
||||
|
||||
partial void OnSelectedTaskChanged(TaskRowViewModel? value)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
using Avalonia.Threading;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using ClaudeDo.Data.Models;
|
||||
using ClaudeDo.Ui.Services;
|
||||
using ClaudeDo.Ui.ViewModels.Islands;
|
||||
|
||||
@@ -7,33 +12,53 @@ namespace ClaudeDo.Ui.ViewModels;
|
||||
|
||||
public sealed partial class IslandsShellViewModel : ViewModelBase
|
||||
{
|
||||
public ListsIslandViewModel Lists { get; }
|
||||
public TasksIslandViewModel Tasks { get; }
|
||||
public DetailsIslandViewModel Details { get; }
|
||||
public WorkerClient Worker { get; }
|
||||
public ListsIslandViewModel? Lists { get; }
|
||||
public TasksIslandViewModel? Tasks { get; }
|
||||
public DetailsIslandViewModel? Details { get; }
|
||||
public WorkerClient? Worker { get; }
|
||||
public UpdateCheckService UpdateCheck => _updateCheck;
|
||||
|
||||
public string ConnectionText =>
|
||||
Worker.IsConnected ? "Online"
|
||||
: Worker.IsReconnecting ? "Connecting…"
|
||||
Worker?.IsConnected == true ? "Online"
|
||||
: Worker?.IsReconnecting == true ? "Connecting…"
|
||||
: "Offline";
|
||||
|
||||
public bool IsOffline => !Worker.IsConnected && !Worker.IsReconnecting;
|
||||
public bool IsOffline => Worker?.IsConnected != true && Worker?.IsReconnecting != true;
|
||||
|
||||
private readonly UpdateCheckService _updateCheck;
|
||||
private readonly InstallerLocator _installerLocator;
|
||||
|
||||
[ObservableProperty] private bool _isUpdateBannerVisible;
|
||||
[ObservableProperty] private string? _updateBannerLatestVersion;
|
||||
[ObservableProperty] private string? _inlineUpdateStatus;
|
||||
private bool _bannerDismissedThisSession;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _windowWidth = 1280;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _workerLogText;
|
||||
|
||||
[ObservableProperty]
|
||||
private WorkerLogLevel _workerLogLevel;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _isWorkerLogVisible;
|
||||
|
||||
public bool ShowDetails => WindowWidth >= 1100;
|
||||
public bool ShowLists => WindowWidth >= 780;
|
||||
|
||||
[RelayCommand]
|
||||
private void FocusSearch() => Lists.RequestFocusSearch();
|
||||
private readonly System.Timers.Timer _clearTimer = new(30_000) { AutoReset = false };
|
||||
|
||||
[RelayCommand]
|
||||
private void FocusAddTask() => Tasks.RequestFocusAddTask();
|
||||
private void FocusSearch() => Lists?.RequestFocusSearch();
|
||||
|
||||
[RelayCommand]
|
||||
private void FocusAddTask() => Tasks?.RequestFocusAddTask();
|
||||
|
||||
public async Task ToggleSelectedDoneAsync()
|
||||
{
|
||||
if (Tasks.SelectedTask is { } row)
|
||||
if (Tasks?.SelectedTask is { } row)
|
||||
await Tasks.ToggleDoneCommand.ExecuteAsync(row);
|
||||
}
|
||||
|
||||
@@ -43,19 +68,49 @@ public sealed partial class IslandsShellViewModel : ViewModelBase
|
||||
OnPropertyChanged(nameof(ShowLists));
|
||||
}
|
||||
|
||||
public void OnWorkerLogReceived(WorkerLogEntry entry)
|
||||
{
|
||||
var hhmm = entry.TimestampUtc.ToLocalTime().ToString("HH:mm");
|
||||
WorkerLogText = $"{hhmm} · {entry.Message}";
|
||||
WorkerLogLevel = entry.Level;
|
||||
IsWorkerLogVisible = true;
|
||||
_clearTimer.Stop();
|
||||
_clearTimer.Start();
|
||||
}
|
||||
|
||||
public void ClearWorkerLog()
|
||||
{
|
||||
IsWorkerLogVisible = false;
|
||||
WorkerLogText = null;
|
||||
}
|
||||
|
||||
// For tests only — does NOT wire up events.
|
||||
internal IslandsShellViewModel() { }
|
||||
|
||||
public IslandsShellViewModel(
|
||||
ListsIslandViewModel lists,
|
||||
TasksIslandViewModel tasks,
|
||||
DetailsIslandViewModel details,
|
||||
WorkerClient worker)
|
||||
WorkerClient worker,
|
||||
UpdateCheckService updateCheck,
|
||||
InstallerLocator installerLocator)
|
||||
{
|
||||
Lists = lists; Tasks = tasks; Details = details; Worker = worker;
|
||||
_updateCheck = updateCheck;
|
||||
_installerLocator = installerLocator;
|
||||
Lists.SelectionChanged += (_, _) => Tasks.LoadForList(Lists.SelectedList);
|
||||
Tasks.SelectionChanged += (_, _) => Details.Bind(Tasks.SelectedTask);
|
||||
Tasks.TasksChanged += (_, _) => _ = Lists.RefreshCountsAsync();
|
||||
Tasks.OpenListSettingsRequested += (_, _) =>
|
||||
{
|
||||
if (Lists.SelectedList is { } row)
|
||||
Lists.OpenListSettingsCommand.Execute(row);
|
||||
};
|
||||
Details.CloseDetail = () => Tasks.SelectedTask = null;
|
||||
Details.DeleteFromList = _ =>
|
||||
Details.DeleteFromList = row =>
|
||||
{
|
||||
Tasks.LoadForList(Lists.SelectedList);
|
||||
_ = Lists.RefreshCountsAsync();
|
||||
return System.Threading.Tasks.Task.CompletedTask;
|
||||
};
|
||||
Worker.PropertyChanged += (_, e) =>
|
||||
@@ -66,6 +121,83 @@ public sealed partial class IslandsShellViewModel : ViewModelBase
|
||||
OnPropertyChanged(nameof(IsOffline));
|
||||
}
|
||||
};
|
||||
Worker.WorkerLogReceivedEvent += OnWorkerLogReceived;
|
||||
_clearTimer.Elapsed += (_, _) =>
|
||||
{
|
||||
if (Dispatcher.UIThread.CheckAccess())
|
||||
ClearWorkerLog();
|
||||
else
|
||||
Dispatcher.UIThread.Post(ClearWorkerLog);
|
||||
};
|
||||
_ = Lists.LoadAsync();
|
||||
_updateCheck.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(UpdateCheckService.LastCheckStatus))
|
||||
{
|
||||
RefreshBannerFromStatus();
|
||||
}
|
||||
};
|
||||
// Fire-and-forget startup check — never block UI.
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try { await _updateCheck.CheckNowAsync(CancellationToken.None); } catch { }
|
||||
});
|
||||
}
|
||||
|
||||
private void RefreshBannerFromStatus()
|
||||
{
|
||||
switch (_updateCheck.LastCheckStatus)
|
||||
{
|
||||
case UpdateCheckStatus.UpdateAvailable:
|
||||
if (_bannerDismissedThisSession) { IsUpdateBannerVisible = false; break; }
|
||||
UpdateBannerLatestVersion = _updateCheck.LatestVersion;
|
||||
IsUpdateBannerVisible = true;
|
||||
InlineUpdateStatus = null;
|
||||
break;
|
||||
case UpdateCheckStatus.UpToDate:
|
||||
IsUpdateBannerVisible = false;
|
||||
ShowInlineStatus($"You're up to date (v{_updateCheck.CurrentVersion})");
|
||||
break;
|
||||
case UpdateCheckStatus.CheckFailed:
|
||||
ShowInlineStatus("Could not check for updates");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async void ShowInlineStatus(string text)
|
||||
{
|
||||
InlineUpdateStatus = text;
|
||||
await Task.Delay(3000);
|
||||
if (InlineUpdateStatus == text) InlineUpdateStatus = null;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task CheckForUpdatesAsync()
|
||||
{
|
||||
await _updateCheck.CheckNowAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void DismissBanner()
|
||||
{
|
||||
_bannerDismissedThisSession = true;
|
||||
IsUpdateBannerVisible = false;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void UpdateNow()
|
||||
{
|
||||
var path = _installerLocator.Find();
|
||||
if (path is null) return;
|
||||
|
||||
try
|
||||
{
|
||||
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(path) { UseShellExecute = true });
|
||||
Environment.Exit(0);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Intentionally silent — if this fails there's nothing useful to show.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,8 +31,8 @@ public sealed class DiffLineViewModel
|
||||
public sealed class DiffFileViewModel
|
||||
{
|
||||
public required string Path { get; init; }
|
||||
public int Additions { get; init; }
|
||||
public int Deletions { get; init; }
|
||||
public int Additions { get; set; }
|
||||
public int Deletions { get; set; }
|
||||
public ObservableCollection<DiffLineViewModel> Lines { get; } = new();
|
||||
}
|
||||
|
||||
@@ -42,10 +42,15 @@ public sealed partial class DiffModalViewModel : ViewModelBase
|
||||
|
||||
public required string WorktreePath { get; init; }
|
||||
public string? BaseRef { get; init; }
|
||||
public string? TaskId { get; init; }
|
||||
public string TaskTitle { get; init; } = "";
|
||||
public Func<MergeModalViewModel, Task>? ShowMergeModal { get; set; }
|
||||
public Func<MergeModalViewModel>? ResolveMergeVm { get; set; }
|
||||
|
||||
public ObservableCollection<DiffFileViewModel> Files { get; } = new();
|
||||
|
||||
[ObservableProperty] private DiffFileViewModel? _selectedFile;
|
||||
[ObservableProperty] private string? _statusMessage;
|
||||
|
||||
// Injected action to close the owning Window
|
||||
public Action? CloseAction { get; set; }
|
||||
@@ -58,9 +63,24 @@ public sealed partial class DiffModalViewModel : ViewModelBase
|
||||
[RelayCommand]
|
||||
private void Close() => CloseAction?.Invoke();
|
||||
|
||||
private bool CanMerge() =>
|
||||
!string.IsNullOrEmpty(TaskId)
|
||||
&& ShowMergeModal is not null
|
||||
&& ResolveMergeVm is not null;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanMerge))]
|
||||
private async Task MergeAsync()
|
||||
{
|
||||
if (TaskId is null || ShowMergeModal is null || ResolveMergeVm is null) return;
|
||||
var vm = ResolveMergeVm();
|
||||
await vm.InitializeAsync(TaskId, TaskTitle);
|
||||
await ShowMergeModal(vm);
|
||||
}
|
||||
|
||||
public async Task LoadAsync(CancellationToken ct = default)
|
||||
{
|
||||
Files.Clear();
|
||||
StatusMessage = null;
|
||||
|
||||
string raw;
|
||||
try
|
||||
@@ -69,9 +89,17 @@ public sealed partial class DiffModalViewModel : ViewModelBase
|
||||
? await _git.GetBranchDiffAsync(WorktreePath, BaseRef, ct)
|
||||
: await _git.GetDiffAsync(WorktreePath, ct);
|
||||
}
|
||||
catch { return; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
StatusMessage = $"Failed to load diff: {ex.Message}";
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(raw)) return;
|
||||
if (string.IsNullOrWhiteSpace(raw))
|
||||
{
|
||||
StatusMessage = "No changes to show.";
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse unified diff — state machine over lines
|
||||
DiffFileViewModel? current = null;
|
||||
@@ -116,7 +144,7 @@ public sealed partial class DiffModalViewModel : ViewModelBase
|
||||
NewNo = newLine++,
|
||||
Text = line.Length > 1 ? line[1..] : "",
|
||||
});
|
||||
// Count additions on the file VM
|
||||
current.Additions++;
|
||||
}
|
||||
else if (line.StartsWith('-'))
|
||||
{
|
||||
@@ -126,6 +154,7 @@ public sealed partial class DiffModalViewModel : ViewModelBase
|
||||
OldNo = oldLine++,
|
||||
Text = line.Length > 1 ? line[1..] : "",
|
||||
});
|
||||
current.Deletions++;
|
||||
}
|
||||
else if (line.StartsWith(' '))
|
||||
{
|
||||
@@ -140,6 +169,7 @@ public sealed partial class DiffModalViewModel : ViewModelBase
|
||||
}
|
||||
|
||||
SelectedFile = Files.Count > 0 ? Files[0] : null;
|
||||
if (Files.Count == 0) StatusMessage = "No changes to show.";
|
||||
}
|
||||
|
||||
private static void ParseHunkHeader(string header, out int oldStart, out int newStart)
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using ClaudeDo.Data.Models;
|
||||
using ClaudeDo.Ui.Services;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
namespace ClaudeDo.Ui.ViewModels.Modals;
|
||||
|
||||
public sealed partial class ListSettingsModalViewModel : ViewModelBase
|
||||
{
|
||||
private readonly WorkerClient _worker;
|
||||
|
||||
public string ListId { get; set; } = "";
|
||||
|
||||
[ObservableProperty] private string _name = "";
|
||||
[ObservableProperty] private string _workingDir = "";
|
||||
[ObservableProperty] private string _defaultCommitType = "chore";
|
||||
|
||||
[ObservableProperty] private string _selectedModel = "(default)";
|
||||
[ObservableProperty] private string _systemPrompt = "";
|
||||
[ObservableProperty] private AgentInfo? _selectedAgent;
|
||||
|
||||
public ObservableCollection<string> ModelOptions { get; } = new()
|
||||
{
|
||||
"(default)", "sonnet", "opus", "haiku",
|
||||
};
|
||||
|
||||
public ObservableCollection<string> CommitTypeOptions { get; } = new()
|
||||
{
|
||||
"chore", "feat", "fix", "refactor", "docs", "test", "ci", "perf", "style", "build",
|
||||
};
|
||||
|
||||
public ObservableCollection<AgentInfo> Agents { get; } = new();
|
||||
|
||||
public Action? CloseAction { get; set; }
|
||||
|
||||
public ListSettingsModalViewModel(WorkerClient worker)
|
||||
{
|
||||
_worker = worker;
|
||||
}
|
||||
|
||||
public async Task LoadAsync(
|
||||
string listId,
|
||||
string name,
|
||||
string? workingDir,
|
||||
string defaultCommitType,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
ListId = listId;
|
||||
Name = name;
|
||||
WorkingDir = workingDir ?? "";
|
||||
DefaultCommitType = string.IsNullOrWhiteSpace(defaultCommitType) ? "chore" : defaultCommitType;
|
||||
|
||||
Agents.Clear();
|
||||
Agents.Add(new AgentInfo("(none)", "", ""));
|
||||
var agents = await _worker.GetAgentsAsync();
|
||||
foreach (var a in agents) Agents.Add(a);
|
||||
|
||||
var config = await _worker.GetListConfigAsync(listId);
|
||||
SelectedModel = string.IsNullOrWhiteSpace(config?.Model) ? "(default)" : config!.Model!;
|
||||
SystemPrompt = config?.SystemPrompt ?? "";
|
||||
SelectedAgent = string.IsNullOrWhiteSpace(config?.AgentPath)
|
||||
? Agents[0]
|
||||
: (Agents.FirstOrDefault(a => a.Path == config!.AgentPath) ?? Agents[0]);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
var model = SelectedModel == "(default)" ? null : SelectedModel;
|
||||
var sp = string.IsNullOrWhiteSpace(SystemPrompt) ? null : SystemPrompt;
|
||||
var ap = SelectedAgent is null || string.IsNullOrWhiteSpace(SelectedAgent.Path) ? null : SelectedAgent.Path;
|
||||
|
||||
await _worker.UpdateListAsync(new UpdateListDto(
|
||||
ListId,
|
||||
string.IsNullOrWhiteSpace(Name) ? "Untitled" : Name,
|
||||
string.IsNullOrWhiteSpace(WorkingDir) ? null : WorkingDir,
|
||||
DefaultCommitType));
|
||||
|
||||
await _worker.UpdateListConfigAsync(new UpdateListConfigDto(
|
||||
ListId, model, sp, ap));
|
||||
|
||||
CloseAction?.Invoke();
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void Cancel() => CloseAction?.Invoke();
|
||||
|
||||
[RelayCommand]
|
||||
private void ResetAgentSettings()
|
||||
{
|
||||
SelectedModel = "(default)";
|
||||
SystemPrompt = "";
|
||||
SelectedAgent = Agents.Count > 0 ? Agents[0] : null;
|
||||
}
|
||||
}
|
||||
117
src/ClaudeDo.Ui/ViewModels/Modals/MergeModalViewModel.cs
Normal file
117
src/ClaudeDo.Ui/ViewModels/Modals/MergeModalViewModel.cs
Normal file
@@ -0,0 +1,117 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using ClaudeDo.Ui.Services;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
namespace ClaudeDo.Ui.ViewModels.Modals;
|
||||
|
||||
public sealed partial class MergeModalViewModel : ViewModelBase
|
||||
{
|
||||
private readonly WorkerClient _worker;
|
||||
|
||||
public string TaskId { get; set; } = "";
|
||||
public string TaskTitle { get; set; } = "";
|
||||
|
||||
public ObservableCollection<string> Branches { get; } = new();
|
||||
|
||||
[ObservableProperty] private string? _selectedBranch;
|
||||
[ObservableProperty] private bool _removeWorktree = true;
|
||||
[ObservableProperty] private string _commitMessage = "";
|
||||
|
||||
[ObservableProperty] private bool _isBusy;
|
||||
[ObservableProperty] private string? _errorMessage;
|
||||
[ObservableProperty] private string? _warningMessage;
|
||||
[ObservableProperty] private string? _successMessage;
|
||||
[ObservableProperty] private bool _hasConflict;
|
||||
[ObservableProperty] private IReadOnlyList<string> _conflictFiles = Array.Empty<string>();
|
||||
|
||||
public Action? CloseAction { get; set; }
|
||||
|
||||
public MergeModalViewModel(WorkerClient worker)
|
||||
{
|
||||
_worker = worker;
|
||||
}
|
||||
|
||||
public async Task InitializeAsync(string taskId, string taskTitle)
|
||||
{
|
||||
TaskId = taskId;
|
||||
TaskTitle = taskTitle;
|
||||
CommitMessage = $"Merge task: {taskTitle}";
|
||||
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
var targets = await _worker.GetMergeTargetsAsync(taskId);
|
||||
Branches.Clear();
|
||||
if (targets is null)
|
||||
{
|
||||
ErrorMessage = "Worker offline — cannot list branches.";
|
||||
return;
|
||||
}
|
||||
foreach (var b in targets.LocalBranches) Branches.Add(b);
|
||||
SelectedBranch = Branches.Contains(targets.DefaultBranch)
|
||||
? targets.DefaultBranch
|
||||
: Branches.FirstOrDefault();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorMessage = $"Failed to load branches: {ex.Message}";
|
||||
}
|
||||
finally { IsBusy = false; }
|
||||
}
|
||||
|
||||
private bool CanSubmit() =>
|
||||
!IsBusy && !HasConflict && !string.IsNullOrWhiteSpace(SelectedBranch);
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanSubmit))]
|
||||
private async Task SubmitAsync()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(SelectedBranch)) return;
|
||||
IsBusy = true;
|
||||
ErrorMessage = null;
|
||||
WarningMessage = null;
|
||||
SuccessMessage = null;
|
||||
try
|
||||
{
|
||||
var result = await _worker.MergeTaskAsync(
|
||||
TaskId, SelectedBranch!, RemoveWorktree, CommitMessage);
|
||||
|
||||
switch (result.Status)
|
||||
{
|
||||
case "merged":
|
||||
SuccessMessage = result.ErrorMessage is not null
|
||||
? $"Merged with warning: {result.ErrorMessage}"
|
||||
: "Merged.";
|
||||
// Auto-close after a short delay.
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(1200);
|
||||
Avalonia.Threading.Dispatcher.UIThread.Post(() => CloseAction?.Invoke());
|
||||
});
|
||||
break;
|
||||
case "conflict":
|
||||
HasConflict = true;
|
||||
ConflictFiles = result.ConflictFiles;
|
||||
ErrorMessage = "Merge conflict — target branch restored. Resolve manually or via Continue, then retry.";
|
||||
break;
|
||||
case "blocked":
|
||||
ErrorMessage = $"Blocked: {result.ErrorMessage}";
|
||||
break;
|
||||
default:
|
||||
ErrorMessage = $"Unknown status: {result.Status}";
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ErrorMessage = $"Merge failed: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void Cancel() => CloseAction?.Invoke();
|
||||
}
|
||||
@@ -161,6 +161,32 @@ public sealed partial class SettingsModalViewModel : ViewModelBase
|
||||
finally { IsBusy = false; }
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task RestoreDefaultAgents()
|
||||
{
|
||||
IsBusy = true;
|
||||
StatusMessage = "";
|
||||
try
|
||||
{
|
||||
var result = await _worker.RestoreDefaultAgentsAsync();
|
||||
if (result is null)
|
||||
StatusMessage = "Worker offline.";
|
||||
else if (result.Copied == 0 && result.Skipped == 0)
|
||||
StatusMessage = "No default agents bundled.";
|
||||
else if (result.Copied == 0)
|
||||
StatusMessage = "All default agents already present.";
|
||||
else
|
||||
StatusMessage = $"Restored {result.Copied} default agent(s).";
|
||||
|
||||
await _worker.RefreshAgentsAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
StatusMessage = $"Restore failed: {ex.Message}";
|
||||
}
|
||||
finally { IsBusy = false; }
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenPath(string? path)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
namespace ClaudeDo.Ui.ViewModels.Modals;
|
||||
|
||||
public enum UnfinishedPlanningModalResult
|
||||
{
|
||||
Cancel,
|
||||
Resume,
|
||||
FinalizeNow,
|
||||
Discard,
|
||||
}
|
||||
|
||||
public sealed partial class UnfinishedPlanningModalViewModel : ViewModelBase
|
||||
{
|
||||
[ObservableProperty] private string _taskTitle = "";
|
||||
[ObservableProperty] private int _draftCount;
|
||||
|
||||
public TaskCompletionSource<UnfinishedPlanningModalResult> Result { get; } = new();
|
||||
public Action? CloseAction { get; set; }
|
||||
|
||||
[RelayCommand] private void Resume() { Result.TrySetResult(UnfinishedPlanningModalResult.Resume); CloseAction?.Invoke(); }
|
||||
[RelayCommand] private void FinalizeNow() { Result.TrySetResult(UnfinishedPlanningModalResult.FinalizeNow); CloseAction?.Invoke(); }
|
||||
[RelayCommand] private void Discard() { Result.TrySetResult(UnfinishedPlanningModalResult.Discard); CloseAction?.Invoke(); }
|
||||
[RelayCommand] private void Cancel() { Result.TrySetResult(UnfinishedPlanningModalResult.Cancel); CloseAction?.Invoke(); }
|
||||
}
|
||||
@@ -141,6 +141,18 @@
|
||||
<TextBlock Text="Worktree" VerticalAlignment="Center"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<Button Classes="btn accent"
|
||||
Content="Continue"
|
||||
Command="{Binding ContinueCommand}"
|
||||
IsVisible="{Binding ShowFailedActions}"
|
||||
ToolTip.Tip="Resume the task from where it failed"
|
||||
Padding="10,4"/>
|
||||
<Button Classes="btn"
|
||||
Content="Reset"
|
||||
Command="{Binding ResetCommand}"
|
||||
IsVisible="{Binding ShowFailedActions}"
|
||||
ToolTip.Tip="Discard the worktree and move the task back to Manual"
|
||||
Padding="10,4"/>
|
||||
</StackPanel>
|
||||
|
||||
</StackPanel>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
BorderThickness="0,1,0,0"
|
||||
Padding="14,8">
|
||||
<Grid ColumnDefinitions="Auto,*,Auto">
|
||||
<!-- Delete button -->
|
||||
<Button Grid.Column="0" Classes="icon-btn"
|
||||
Command="{Binding DeleteTaskCommand}"
|
||||
ToolTip.Tip="Delete task"
|
||||
@@ -20,14 +19,12 @@
|
||||
<PathIcon Data="{StaticResource Icon.Trash}" Width="14" Height="14"
|
||||
Foreground="{DynamicResource BloodBrush}"/>
|
||||
</Button>
|
||||
<!-- Created date -->
|
||||
<TextBlock Grid.Column="1"
|
||||
Text="{Binding Task.CreatedAtFormatted}"
|
||||
FontFamily="{DynamicResource MonoFont}" FontSize="10"
|
||||
Foreground="{DynamicResource TextFaintBrush}"
|
||||
HorizontalAlignment="Center"
|
||||
VerticalAlignment="Center"/>
|
||||
<!-- Close button -->
|
||||
<Button Grid.Column="2" Classes="icon-btn"
|
||||
Command="{Binding CloseDetailsCommand}"
|
||||
ToolTip.Tip="Close"
|
||||
@@ -37,10 +34,10 @@
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- ── Header ── -->
|
||||
<!-- ── Header (sticky top): eyebrow · title · gear (agent-settings flyout) ── -->
|
||||
<Border DockPanel.Dock="Top" Classes="island-header">
|
||||
<!-- Eyebrow row -->
|
||||
<StackPanel Spacing="0">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel Grid.Column="0" Spacing="0">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6" Margin="0,0,0,4">
|
||||
<Ellipse Width="5" Height="5" Fill="{DynamicResource AccentBrush}"
|
||||
VerticalAlignment="Center"/>
|
||||
@@ -51,16 +48,62 @@
|
||||
VerticalAlignment="Center"
|
||||
Margin="8,0,0,0"/>
|
||||
</StackPanel>
|
||||
<!-- Editable title (reduced size) -->
|
||||
<TextBox Text="{Binding EditableTitle, Mode=TwoWay}"
|
||||
FontSize="14" FontWeight="Medium"
|
||||
BorderThickness="0" Background="Transparent"
|
||||
Foreground="{DynamicResource TextBrush}"
|
||||
Padding="0"/>
|
||||
</StackPanel>
|
||||
|
||||
<Button Grid.Column="1" Classes="icon-btn"
|
||||
ToolTip.Tip="Agent settings"
|
||||
IsEnabled="{Binding IsAgentSectionEnabled}"
|
||||
VerticalAlignment="Top"
|
||||
Margin="6,0,0,0">
|
||||
<TextBlock Text="⚙" FontSize="14"/>
|
||||
<Button.Flyout>
|
||||
<Flyout Placement="BottomEdgeAlignedRight" ShowMode="Standard">
|
||||
<StackPanel Width="340" Spacing="10" Margin="4">
|
||||
<TextBlock Text="Agent settings (overrides)" FontWeight="SemiBold"/>
|
||||
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Model"/>
|
||||
<ComboBox ItemsSource="{Binding TaskModelOptions}"
|
||||
SelectedItem="{Binding TaskModelSelection, Mode=TwoWay}"
|
||||
HorizontalAlignment="Stretch"/>
|
||||
<TextBlock Text="{Binding EffectiveModelHint, StringFormat='Effective if inherited: {0}'}"
|
||||
Opacity="0.6" FontSize="11"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="System prompt (appended)"/>
|
||||
<TextBox Text="{Binding TaskSystemPrompt, Mode=TwoWay}"
|
||||
AcceptsReturn="True" TextWrapping="Wrap" MinHeight="70"
|
||||
PlaceholderText="{Binding EffectiveSystemPromptHint}"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Agent file"/>
|
||||
<ComboBox ItemsSource="{Binding TaskAgentOptions}"
|
||||
SelectedItem="{Binding TaskSelectedAgent, Mode=TwoWay}"
|
||||
HorizontalAlignment="Stretch">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Name}"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<TextBlock Text="{Binding EffectiveAgentHint, StringFormat='Effective if inherited: {0}'}"
|
||||
Opacity="0.6" FontSize="11"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Flyout>
|
||||
</Button.Flyout>
|
||||
</Button>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- ── Task strip row: check + title display + star ── -->
|
||||
<!-- ── Task strip row (sticky top): check + title + star ── -->
|
||||
<Border DockPanel.Dock="Top"
|
||||
Padding="18,10,18,10"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
@@ -88,26 +131,32 @@
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- ── Main body: agent strip (auto) · terminal (flex) · steps+notes (auto/capped) ── -->
|
||||
<Grid RowDefinitions="Auto,*,Auto">
|
||||
<!-- ── Agent status strip (sticky, above metadata footer) ── -->
|
||||
<islands:AgentStripView DockPanel.Dock="Bottom"/>
|
||||
|
||||
<!-- Agent strip -->
|
||||
<islands:AgentStripView Grid.Row="0"/>
|
||||
|
||||
<!-- Session terminal — fills remaining vertical space -->
|
||||
<islands:SessionTerminalView Grid.Row="1" MinHeight="220" Margin="0,0,0,0"/>
|
||||
|
||||
<!-- Steps + Notes in a capped scroller so they never squeeze the terminal -->
|
||||
<ScrollViewer Grid.Row="2" MaxHeight="240"
|
||||
VerticalScrollBarVisibility="Auto">
|
||||
<!-- ── Scrollable body: steps + terminal ── -->
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel Spacing="0">
|
||||
|
||||
<!-- Subtasks section -->
|
||||
<StackPanel Margin="18,12,18,0"
|
||||
<!-- Steps section -->
|
||||
<Border Padding="18,12,18,12"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="0,0,0,1">
|
||||
<StackPanel Spacing="6">
|
||||
<TextBlock Classes="section-label" Text="STEPS" Margin="0,0,0,2"/>
|
||||
<TextBox Text="{Binding NewSubtaskTitle, Mode=TwoWay}"
|
||||
PlaceholderText="Add a step..."
|
||||
Padding="8"
|
||||
Background="{DynamicResource Surface2Brush}"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="6">
|
||||
<TextBox.KeyBindings>
|
||||
<KeyBinding Gesture="Enter" Command="{Binding AddSubtaskCommand}"/>
|
||||
</TextBox.KeyBindings>
|
||||
</TextBox>
|
||||
<ItemsControl ItemsSource="{Binding Subtasks}"
|
||||
IsVisible="{Binding Subtasks.Count}">
|
||||
<TextBlock Classes="section-label" Text="STEPS"
|
||||
Margin="0,0,0,6"/>
|
||||
<ItemsControl ItemsSource="{Binding Subtasks}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="vm:SubtaskRowViewModel">
|
||||
<Border Classes="subtask-row"
|
||||
@@ -133,25 +182,13 @@
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Notes section -->
|
||||
<StackPanel Margin="18,12,18,12">
|
||||
<TextBlock Classes="section-label" Text="NOTES" Margin="0,0,0,6"/>
|
||||
<TextBox Text="{Binding Notes, Mode=TwoWay}"
|
||||
AcceptsReturn="True"
|
||||
TextWrapping="Wrap"
|
||||
MinHeight="80"
|
||||
Padding="12"
|
||||
PlaceholderText="Notes..."
|
||||
Background="{DynamicResource Surface2Brush}"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="8"
|
||||
LostFocus="NotesLostFocus"/>
|
||||
</StackPanel>
|
||||
<!-- Session terminal — auto-sizes to output, scrolls internally after MaxHeight -->
|
||||
<islands:SessionTerminalView MaxHeight="420"/>
|
||||
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</Grid>
|
||||
|
||||
</DockPanel>
|
||||
</UserControl>
|
||||
|
||||
@@ -36,10 +36,58 @@ public partial class DetailsIslandView : UserControl
|
||||
await modal.ShowDialog(owner);
|
||||
};
|
||||
|
||||
vm.ShowMergeModal = async (mergeVm) =>
|
||||
{
|
||||
var owner = TopLevel.GetTopLevel(this) as Window;
|
||||
if (owner == null) return;
|
||||
var modal = new MergeModalView { DataContext = mergeVm };
|
||||
await modal.ShowDialog(owner);
|
||||
};
|
||||
|
||||
vm.ConfirmAsync = ShowConfirmAsync;
|
||||
vm.ShowErrorAsync = ShowErrorDialogAsync;
|
||||
}
|
||||
}
|
||||
|
||||
private async System.Threading.Tasks.Task ShowErrorDialogAsync(string message)
|
||||
{
|
||||
var owner = TopLevel.GetTopLevel(this) as Window;
|
||||
if (owner == null) return;
|
||||
|
||||
var ok = new Button { Content = "OK", MinWidth = 90 };
|
||||
|
||||
var dialog = new Window
|
||||
{
|
||||
Title = "Error",
|
||||
Width = 360,
|
||||
SizeToContent = SizeToContent.Height,
|
||||
CanResize = false,
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner,
|
||||
ShowInTaskbar = false,
|
||||
Background = this.FindResource("SurfaceBrush") as IBrush,
|
||||
Content = new StackPanel
|
||||
{
|
||||
Spacing = 16,
|
||||
Margin = new Thickness(20),
|
||||
Children =
|
||||
{
|
||||
new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap },
|
||||
new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
Spacing = 8,
|
||||
HorizontalAlignment = HorizontalAlignment.Right,
|
||||
Children = { ok }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ok.Click += (_, _) => dialog.Close();
|
||||
|
||||
await dialog.ShowDialog(owner);
|
||||
}
|
||||
|
||||
private async System.Threading.Tasks.Task<bool> ShowConfirmAsync(string message)
|
||||
{
|
||||
var owner = TopLevel.GetTopLevel(this) as Window;
|
||||
|
||||
@@ -112,11 +112,8 @@
|
||||
VerticalAlignment="Center" Margin="8,0"
|
||||
Foreground="{DynamicResource TextDimBrush}" FontSize="13"/>
|
||||
<!-- Count -->
|
||||
<TextBlock Grid.Column="2"
|
||||
Text="{Binding Count}"
|
||||
FontFamily="{DynamicResource MonoFamily}" FontSize="10"
|
||||
Foreground="{DynamicResource TextFaintBrush}"
|
||||
VerticalAlignment="Center"/>
|
||||
<TextBlock Grid.Column="2" Classes="list-count"
|
||||
Text="{Binding Count}"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
@@ -130,6 +127,13 @@
|
||||
<DataTemplate DataType="vm:ListNavItemViewModel">
|
||||
<Border Classes="list-item" Classes.active="{Binding IsActive}"
|
||||
Tapped="OnItemTapped">
|
||||
<Border.ContextMenu>
|
||||
<ContextMenu>
|
||||
<MenuItem Header="Settings..."
|
||||
Command="{Binding $parent[UserControl].((vm:ListsIslandViewModel)DataContext).OpenListSettingsCommand}"
|
||||
CommandParameter="{Binding}"/>
|
||||
</ContextMenu>
|
||||
</Border.ContextMenu>
|
||||
<Grid ColumnDefinitions="20,*,Auto">
|
||||
<!-- Left accent bar for active state -->
|
||||
<Border Grid.Column="0" Grid.ColumnSpan="3"
|
||||
@@ -153,11 +157,8 @@
|
||||
VerticalAlignment="Center" Margin="8,0"
|
||||
Foreground="{DynamicResource TextDimBrush}" FontSize="13"/>
|
||||
<!-- Count -->
|
||||
<TextBlock Grid.Column="2"
|
||||
Text="{Binding Count}"
|
||||
FontFamily="{DynamicResource MonoFamily}" FontSize="10"
|
||||
Foreground="{DynamicResource TextFaintBrush}"
|
||||
VerticalAlignment="Center"/>
|
||||
<TextBlock Grid.Column="2" Classes="list-count"
|
||||
Text="{Binding Count}"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
@@ -17,6 +17,14 @@ public partial class ListsIslandView : UserControl
|
||||
{
|
||||
vm.FocusSearchRequested += (_, _) => SearchBox.Focus();
|
||||
vm.ShowSettingsModal = ShowSettingsAsync;
|
||||
vm.ShowListSettingsModal = async modal =>
|
||||
{
|
||||
var window = new ListSettingsModalView { DataContext = modal };
|
||||
modal.CloseAction = () => window.Close();
|
||||
var top = TopLevel.GetTopLevel(this) as Window;
|
||||
if (top is null) window.Show();
|
||||
else await window.ShowDialog(top);
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -50,23 +50,20 @@
|
||||
</Grid>
|
||||
|
||||
<!-- ── Log output ── -->
|
||||
<ScrollViewer Name="LogScroll" VerticalScrollBarVisibility="Auto"
|
||||
Padding="10,8,10,4">
|
||||
<ScrollViewer Name="LogScroll"
|
||||
VerticalScrollBarVisibility="Visible"
|
||||
AllowAutoHide="False"
|
||||
Padding="10,8,10,12">
|
||||
<ItemsControl ItemsSource="{Binding Log}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="vm:LogLineViewModel">
|
||||
<Grid ColumnDefinitions="60,46,*" Margin="0,1">
|
||||
<Grid ColumnDefinitions="60,*" Margin="0,1">
|
||||
<!-- Timestamp -->
|
||||
<TextBlock Grid.Column="0"
|
||||
Classes="log-ts"
|
||||
Text="{Binding TimestampFormatted}"/>
|
||||
<!-- Kind marker -->
|
||||
<TextBlock Grid.Column="1"
|
||||
Classes="log-kind"
|
||||
Tag="{Binding ClassName}"
|
||||
Text="{Binding KindMarker}"/>
|
||||
<!-- Message text — selectable so the user can copy raw output -->
|
||||
<SelectableTextBlock Grid.Column="2"
|
||||
<SelectableTextBlock Grid.Column="1"
|
||||
Text="{Binding Text}" Tag="{Binding ClassName}"
|
||||
FontFamily="{DynamicResource MonoFont}" FontSize="11"
|
||||
Foreground="{DynamicResource TextDimBrush}"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Collections.Specialized;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Threading;
|
||||
using ClaudeDo.Ui.ViewModels.Islands;
|
||||
|
||||
namespace ClaudeDo.Ui.Views.Islands;
|
||||
@@ -17,7 +18,7 @@ public partial class SessionTerminalView : UserControl
|
||||
|
||||
private void OnLogChanged(object? sender, NotifyCollectionChangedEventArgs e)
|
||||
{
|
||||
if (e.Action == NotifyCollectionChangedAction.Add)
|
||||
LogScroll.ScrollToEnd();
|
||||
if (e.Action != NotifyCollectionChangedAction.Add) return;
|
||||
Dispatcher.UIThread.Post(() => LogScroll.ScrollToEnd(), DispatcherPriority.Background);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,17 +3,80 @@
|
||||
xmlns:vm="using:ClaudeDo.Ui.ViewModels.Islands"
|
||||
x:Class="ClaudeDo.Ui.Views.Islands.TaskRowView"
|
||||
x:DataType="vm:TaskRowViewModel">
|
||||
<Border Classes="task-row"
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="6"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Above-row indicator: lives in the 6px gap between cards -->
|
||||
<Border Grid.Row="0" Height="2" VerticalAlignment="Center" Margin="4,0"
|
||||
Background="{DynamicResource MossBrush}" CornerRadius="1"
|
||||
IsVisible="{Binding DropHintAbove}"/>
|
||||
|
||||
<!-- Indent wrapper: col 0 = 24px child indent track, col 1 = content -->
|
||||
<Grid Grid.Row="1" ColumnDefinitions="Auto,*">
|
||||
|
||||
<!-- Indent track (only visible for child tasks) -->
|
||||
<Border Grid.Column="0" Width="24" IsVisible="{Binding IsChild}" VerticalAlignment="Stretch">
|
||||
<Rectangle Width="1" Fill="{DynamicResource LineBrush}"
|
||||
HorizontalAlignment="Right" Margin="0,4"/>
|
||||
</Border>
|
||||
|
||||
<!-- Main task card -->
|
||||
<Border Grid.Column="1" Classes="task-row"
|
||||
Margin="0"
|
||||
Classes.selected="{Binding IsSelected}"
|
||||
Classes.done="{Binding Done}">
|
||||
<Grid ColumnDefinitions="4,32,*,32" Margin="6,8,10,8">
|
||||
<Border.ContextMenu>
|
||||
<ContextMenu>
|
||||
<MenuItem Header="Send to queue"
|
||||
IsVisible="{Binding !IsQueued}"
|
||||
Click="OnSendToQueueClick"/>
|
||||
<MenuItem Header="Remove from queue"
|
||||
IsVisible="{Binding IsQueued}"
|
||||
Click="OnRemoveFromQueueClick"/>
|
||||
<Separator/>
|
||||
<MenuItem Header="Open planning Session"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).OpenPlanningSessionCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
IsVisible="{Binding CanOpenPlanningSession}"/>
|
||||
<MenuItem Header="Resume planning Session"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).ResumePlanningSessionCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
IsVisible="{Binding CanResumeOrDiscardPlanning}"/>
|
||||
<MenuItem Header="Discard planning session"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).DiscardPlanningSessionCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
IsVisible="{Binding CanResumeOrDiscardPlanning}"/>
|
||||
<Separator/>
|
||||
<MenuItem Header="Schedule for..." Click="OnScheduleForClick"/>
|
||||
<MenuItem Header="Clear schedule"
|
||||
IsVisible="{Binding HasSchedule}"
|
||||
Click="OnClearScheduleClick"/>
|
||||
</ContextMenu>
|
||||
</Border.ContextMenu>
|
||||
<Grid ColumnDefinitions="0,18,32,*,Auto,32" Margin="6,8,10,8">
|
||||
|
||||
<!-- Left accent bar (visible when selected) -->
|
||||
<Border Grid.Column="0" Classes="task-row-accent"
|
||||
IsVisible="{Binding IsSelected}"/>
|
||||
<!-- Chevron toggle (only for planning parent tasks) -->
|
||||
<Button Grid.Column="1"
|
||||
IsVisible="{Binding IsPlanningParent}"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).ToggleExpandCommand}"
|
||||
CommandParameter="{Binding}"
|
||||
Classes="icon-btn"
|
||||
Width="18" Height="18"
|
||||
VerticalAlignment="Center">
|
||||
<Panel>
|
||||
<TextBlock Text="▾" FontSize="10" IsVisible="{Binding IsExpanded}"
|
||||
VerticalAlignment="Center" HorizontalAlignment="Center"/>
|
||||
<TextBlock Text="▸" FontSize="10" IsVisible="{Binding !IsExpanded}"
|
||||
VerticalAlignment="Center" HorizontalAlignment="Center"/>
|
||||
</Panel>
|
||||
</Button>
|
||||
|
||||
<!-- Done toggle -->
|
||||
<Button Grid.Column="1" Classes="flat" VerticalAlignment="Top"
|
||||
<Button Grid.Column="2" Classes="flat" VerticalAlignment="Top"
|
||||
Margin="0,2,0,0"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).ToggleDoneCommand}"
|
||||
CommandParameter="{Binding}">
|
||||
@@ -22,12 +85,26 @@
|
||||
</Button>
|
||||
|
||||
<!-- Title + chip row + live tail -->
|
||||
<StackPanel Grid.Column="2" Spacing="6" VerticalAlignment="Center">
|
||||
<StackPanel Grid.Column="3" Spacing="6" VerticalAlignment="Center">
|
||||
<StackPanel Orientation="Horizontal" Spacing="4" VerticalAlignment="Center">
|
||||
<TextBlock Classes="task-title"
|
||||
Text="{Binding Title}" FontSize="14"
|
||||
Foreground="{DynamicResource TextBrush}"
|
||||
FontStyle="{Binding IsDraft, Converter={StaticResource BoolToItalic}}"
|
||||
Opacity="{Binding IsDraft, Converter={StaticResource BoolToDraftOpacity}}"
|
||||
TextDecorations="{Binding Done, Converter={StaticResource StrikeIfTrue}}"/>
|
||||
|
||||
<!-- Badges: DRAFT and planning session -->
|
||||
<StackPanel Orientation="Horizontal" Spacing="4" VerticalAlignment="Center">
|
||||
<Border Classes="badge draft" IsVisible="{Binding IsDraft}">
|
||||
<TextBlock Text="DRAFT"/>
|
||||
</Border>
|
||||
<Border Classes="badge planning" IsVisible="{Binding IsPlanningParent}">
|
||||
<TextBlock Text="{Binding PlanningBadge}"/>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Chip row -->
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
|
||||
@@ -40,6 +117,15 @@
|
||||
<TextBlock Text="{Binding Status}"/>
|
||||
</Border>
|
||||
|
||||
<!-- Dequeue button (only when Queued) -->
|
||||
<Button Classes="icon-btn dequeue-btn"
|
||||
IsVisible="{Binding IsQueued}"
|
||||
ToolTip.Tip="Remove from queue"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).RemoveFromQueueCommand}"
|
||||
CommandParameter="{Binding}">
|
||||
<PathIcon Width="10" Height="10" Data="{StaticResource Icon.X}"/>
|
||||
</Button>
|
||||
|
||||
<!-- List chip with dot -->
|
||||
<Border Classes="chip chip-list">
|
||||
<StackPanel Orientation="Horizontal" Spacing="5" VerticalAlignment="Center">
|
||||
@@ -101,7 +187,7 @@
|
||||
</StackPanel>
|
||||
|
||||
<!-- Star toggle -->
|
||||
<Button Grid.Column="3" Classes="icon-btn star-btn"
|
||||
<Button Grid.Column="5" Classes="icon-btn star-btn"
|
||||
Classes.on="{Binding IsStarred}"
|
||||
VerticalAlignment="Top" Margin="0,2,0,0"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).ToggleStarCommand}"
|
||||
@@ -110,4 +196,53 @@
|
||||
</Button>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
</Grid>
|
||||
|
||||
<!-- Below-row indicator: only expands when visible (used for the last row of a section) -->
|
||||
<Grid Grid.Row="2" Height="6" IsVisible="{Binding DropHintBelow}">
|
||||
<Border Height="2" VerticalAlignment="Center" Margin="4,0"
|
||||
Background="{DynamicResource MossBrush}" CornerRadius="1"/>
|
||||
</Grid>
|
||||
|
||||
<!-- Hidden schedule anchor (its Flyout is shown from the context menu) -->
|
||||
<Button Grid.Row="1" x:Name="ScheduleAnchor"
|
||||
Width="1" Height="1" Opacity="0"
|
||||
HorizontalAlignment="Left" VerticalAlignment="Top"
|
||||
IsHitTestVisible="False" Focusable="False">
|
||||
<Button.Flyout>
|
||||
<Flyout Placement="Bottom" ShowMode="Standard">
|
||||
<Border Background="{DynamicResource Surface2Brush}"
|
||||
BorderBrush="{DynamicResource BorderBrush}"
|
||||
BorderThickness="1" CornerRadius="10"
|
||||
Padding="16" Width="300">
|
||||
<StackPanel Spacing="12">
|
||||
<TextBlock Text="Schedule task"
|
||||
FontWeight="SemiBold" FontSize="13"
|
||||
Foreground="{DynamicResource TextBrush}"/>
|
||||
|
||||
<StackPanel Spacing="6">
|
||||
<TextBlock Text="DATE" FontSize="10" Opacity="0.6"
|
||||
Foreground="{DynamicResource TextDimBrush}"/>
|
||||
<DatePicker x:Name="ScheduleDate" HorizontalAlignment="Stretch"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="6">
|
||||
<TextBlock Text="TIME" FontSize="10" Opacity="0.6"
|
||||
Foreground="{DynamicResource TextDimBrush}"/>
|
||||
<TimePicker x:Name="ScheduleTime" ClockIdentifier="24HourClock"
|
||||
HorizontalAlignment="Stretch"/>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="8"
|
||||
HorizontalAlignment="Right" Margin="0,4,0,0">
|
||||
<Button Content="Cancel" Click="OnScheduleCancelClick" MinWidth="76"/>
|
||||
<Button Content="Schedule" Classes="accent" Click="OnScheduleSetClick" MinWidth="76"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Flyout>
|
||||
</Button.Flyout>
|
||||
</Button>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
|
||||
@@ -1,16 +1,72 @@
|
||||
using System.Linq;
|
||||
using Avalonia;
|
||||
using Avalonia.Animation;
|
||||
using Avalonia.Animation.Easings;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Styling;
|
||||
using Avalonia.VisualTree;
|
||||
using ClaudeDo.Ui.ViewModels.Islands;
|
||||
|
||||
namespace ClaudeDo.Ui.Views.Islands;
|
||||
|
||||
public partial class TaskRowView : UserControl
|
||||
{
|
||||
private TaskRowViewModel? _pendingScheduleRow;
|
||||
|
||||
public TaskRowView() { InitializeComponent(); }
|
||||
|
||||
private TasksIslandViewModel? FindTasksVm() =>
|
||||
this.GetVisualAncestors().OfType<ItemsControl>()
|
||||
.Select(ic => ic.DataContext).OfType<TasksIslandViewModel>().FirstOrDefault();
|
||||
|
||||
private async void OnSendToQueueClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (DataContext is TaskRowViewModel row && FindTasksVm() is { } vm)
|
||||
await vm.SendToQueueCommand.ExecuteAsync(row);
|
||||
}
|
||||
|
||||
private async void OnRemoveFromQueueClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (DataContext is TaskRowViewModel row && FindTasksVm() is { } vm)
|
||||
await vm.RemoveFromQueueCommand.ExecuteAsync(row);
|
||||
}
|
||||
|
||||
private async void OnClearScheduleClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (DataContext is TaskRowViewModel row && FindTasksVm() is { } vm)
|
||||
await vm.ClearScheduleCommand.ExecuteAsync(row);
|
||||
}
|
||||
|
||||
private void OnScheduleForClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (DataContext is not TaskRowViewModel row) return;
|
||||
_pendingScheduleRow = row;
|
||||
var seed = row.ScheduledFor ?? DateTime.Now.AddHours(1);
|
||||
ScheduleDate.SelectedDate = new DateTimeOffset(seed.Date, TimeSpan.Zero);
|
||||
ScheduleTime.SelectedTime = seed.TimeOfDay;
|
||||
ScheduleAnchor.Flyout?.ShowAt(ScheduleAnchor);
|
||||
}
|
||||
|
||||
private async void OnScheduleSetClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
ScheduleAnchor.Flyout?.Hide();
|
||||
if (_pendingScheduleRow is null || ScheduleDate.SelectedDate is null) return;
|
||||
var date = ScheduleDate.SelectedDate.Value.Date;
|
||||
var time = ScheduleTime.SelectedTime ?? TimeSpan.FromHours(9);
|
||||
var when = date + time;
|
||||
if (FindTasksVm() is { } tvm)
|
||||
await tvm.SetScheduledForAsync(_pendingScheduleRow, when);
|
||||
_pendingScheduleRow = null;
|
||||
}
|
||||
|
||||
private void OnScheduleCancelClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
ScheduleAnchor.Flyout?.Hide();
|
||||
_pendingScheduleRow = null;
|
||||
}
|
||||
|
||||
protected override async void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
|
||||
{
|
||||
base.OnAttachedToVisualTree(e);
|
||||
|
||||
@@ -36,8 +36,8 @@
|
||||
ToolTip.Tip="Show completed">
|
||||
<PathIcon Width="15" Height="15" Data="{StaticResource Icon.Eye}"/>
|
||||
</Button>
|
||||
<Button Classes="icon-btn" Command="{Binding MoreCommand}" ToolTip.Tip="More">
|
||||
<PathIcon Width="15" Height="15" Data="{StaticResource Icon.MoreHorizontal}"/>
|
||||
<Button Classes="icon-btn" Command="{Binding OpenListSettingsCommand}" ToolTip.Tip="List settings">
|
||||
<PathIcon Width="15" Height="15" Data="{StaticResource Icon.Settings}"/>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
@@ -80,7 +80,13 @@
|
||||
<Button Classes="flat" HorizontalAlignment="Stretch"
|
||||
HorizontalContentAlignment="Stretch"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).SelectCommand}"
|
||||
CommandParameter="{Binding}">
|
||||
CommandParameter="{Binding}"
|
||||
PointerPressed="OnRowPointerPressed"
|
||||
PointerMoved="OnRowPointerMoved"
|
||||
PointerReleased="OnRowPointerReleased"
|
||||
DragDrop.AllowDrop="True"
|
||||
DragDrop.DragOver="OnRowDragOver"
|
||||
DragDrop.Drop="OnRowDrop">
|
||||
<islands:TaskRowView/>
|
||||
</Button>
|
||||
</DataTemplate>
|
||||
@@ -99,7 +105,13 @@
|
||||
<Button Classes="flat" HorizontalAlignment="Stretch"
|
||||
HorizontalContentAlignment="Stretch"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).SelectCommand}"
|
||||
CommandParameter="{Binding}">
|
||||
CommandParameter="{Binding}"
|
||||
PointerPressed="OnRowPointerPressed"
|
||||
PointerMoved="OnRowPointerMoved"
|
||||
PointerReleased="OnRowPointerReleased"
|
||||
DragDrop.AllowDrop="True"
|
||||
DragDrop.DragOver="OnRowDragOver"
|
||||
DragDrop.Drop="OnRowDrop">
|
||||
<islands:TaskRowView/>
|
||||
</Button>
|
||||
</DataTemplate>
|
||||
@@ -123,7 +135,13 @@
|
||||
<Button Classes="flat" HorizontalAlignment="Stretch"
|
||||
HorizontalContentAlignment="Stretch"
|
||||
Command="{Binding $parent[ItemsControl].((vm:TasksIslandViewModel)DataContext).SelectCommand}"
|
||||
CommandParameter="{Binding}">
|
||||
CommandParameter="{Binding}"
|
||||
PointerPressed="OnRowPointerPressed"
|
||||
PointerMoved="OnRowPointerMoved"
|
||||
PointerReleased="OnRowPointerReleased"
|
||||
DragDrop.AllowDrop="True"
|
||||
DragDrop.DragOver="OnRowDragOver"
|
||||
DragDrop.Drop="OnRowDrop">
|
||||
<islands:TaskRowView/>
|
||||
</Button>
|
||||
</DataTemplate>
|
||||
|
||||
@@ -1,17 +1,180 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.VisualTree;
|
||||
using ClaudeDo.Ui.ViewModels.Islands;
|
||||
using ClaudeDo.Ui.ViewModels.Modals;
|
||||
using ClaudeDo.Ui.Views.Modals;
|
||||
|
||||
namespace ClaudeDo.Ui.Views.Islands;
|
||||
|
||||
public partial class TasksIslandView : UserControl
|
||||
{
|
||||
private static readonly DataFormat<string> TaskRowFormat =
|
||||
DataFormat.CreateStringApplicationFormat("claudedo-task-row");
|
||||
|
||||
public TasksIslandView()
|
||||
{
|
||||
InitializeComponent();
|
||||
AddHandler(PointerPressedEvent, OnTunnelPointerPressed, RoutingStrategies.Tunnel);
|
||||
DataContextChanged += (_, _) =>
|
||||
{
|
||||
if (DataContext is TasksIslandViewModel vm)
|
||||
{
|
||||
vm.FocusAddTaskRequested += (_, _) => AddTaskBox.Focus();
|
||||
vm.ShowUnfinishedPlanningModal = async (modalVm) =>
|
||||
{
|
||||
var owner = TopLevel.GetTopLevel(this) as Window;
|
||||
if (owner is null) { modalVm.CancelCommand.Execute(null); return; }
|
||||
var modal = new UnfinishedPlanningModalView { DataContext = modalVm };
|
||||
// Closing via the OS title-bar (if ever enabled) also resolves the TCS.
|
||||
modal.Closed += (_, _) => modalVm.CancelCommand.Execute(null);
|
||||
await modal.ShowDialog(owner);
|
||||
// ShowDialog completes once the window is closed (CloseAction or OS close).
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private async void OnTunnelPointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
if (DataContext is not TasksIslandViewModel vm) return;
|
||||
if (e.Source is not Visual src) return;
|
||||
|
||||
var button = src as Button ?? src.FindAncestorOfType<Button>();
|
||||
if (button?.DataContext is not TaskRowViewModel row) return;
|
||||
if (!e.GetCurrentPoint(button).Properties.IsLeftButtonPressed) return;
|
||||
|
||||
// Select now so the details pane updates whether the gesture becomes a click or a drag.
|
||||
// (Button.Click doesn't fire once DoDragDropAsync captures the pointer.)
|
||||
vm.SelectedTask = row;
|
||||
|
||||
// If the click landed on a nested Button (e.g. the done-toggle checkbox or star),
|
||||
// don't start a drag — that would capture the pointer and swallow the inner Click.
|
||||
var nestedInsideButton = button.Parent is Visual parentVisual
|
||||
&& parentVisual.FindAncestorOfType<Button>() is not null;
|
||||
if (nestedInsideButton) return;
|
||||
|
||||
if (!vm.CanReorder || row.IsRunning) return;
|
||||
|
||||
var data = new DataTransfer();
|
||||
data.Add(DataTransferItem.Create(TaskRowFormat, row.Id));
|
||||
try
|
||||
{
|
||||
await DragDrop.DoDragDropAsync(e, data, DragDropEffects.Move);
|
||||
}
|
||||
finally
|
||||
{
|
||||
vm.ClearDropHints();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnRowPointerPressed(object? sender, PointerPressedEventArgs e) { }
|
||||
private void OnRowPointerMoved(object? sender, PointerEventArgs e) { }
|
||||
private void OnRowPointerReleased(object? sender, PointerReleasedEventArgs e) { }
|
||||
|
||||
private void OnRowDragOver(object? sender, DragEventArgs e)
|
||||
{
|
||||
if (DataContext is not TasksIslandViewModel vm) { e.DragEffects = DragDropEffects.None; return; }
|
||||
if (!e.DataTransfer?.Contains(TaskRowFormat) ?? true)
|
||||
{
|
||||
e.DragEffects = DragDropEffects.None;
|
||||
vm.ClearDropHints();
|
||||
return;
|
||||
}
|
||||
if (sender is not Button b || b.DataContext is not TaskRowViewModel target || target.IsRunning)
|
||||
{
|
||||
e.DragEffects = DragDropEffects.None;
|
||||
vm.ClearDropHints();
|
||||
return;
|
||||
}
|
||||
|
||||
var sourceId = e.DataTransfer?.TryGetValue(TaskRowFormat);
|
||||
if (string.IsNullOrEmpty(sourceId) || sourceId == target.Id)
|
||||
{
|
||||
e.DragEffects = DragDropEffects.None;
|
||||
vm.ClearDropHints();
|
||||
return;
|
||||
}
|
||||
|
||||
var placeBelow = e.GetPosition(b).Y > b.Bounds.Height / 2;
|
||||
|
||||
// Canonicalize: "drop below X" == "drop above X+1". Render the indicator
|
||||
// above X+1 when there is one; only the last row in a section shows a below-line.
|
||||
TaskRowViewModel hintRow = target;
|
||||
bool hintBelow = false;
|
||||
if (placeBelow)
|
||||
{
|
||||
var next = FindNextInSameSection(vm, target);
|
||||
if (next is not null && !next.IsRunning)
|
||||
{
|
||||
hintRow = next;
|
||||
hintBelow = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
hintRow = target;
|
||||
hintBelow = true;
|
||||
}
|
||||
}
|
||||
|
||||
// A hint that lands right where the dragged row already sits is a no-op.
|
||||
if (hintRow.Id == sourceId)
|
||||
{
|
||||
e.DragEffects = DragDropEffects.None;
|
||||
vm.ClearDropHints();
|
||||
return;
|
||||
}
|
||||
|
||||
vm.SetDropHint(hintRow, hintBelow);
|
||||
e.DragEffects = DragDropEffects.Move;
|
||||
}
|
||||
|
||||
private static TaskRowViewModel? FindNextInSameSection(TasksIslandViewModel vm, TaskRowViewModel row)
|
||||
{
|
||||
foreach (var section in new[] { vm.OverdueItems, vm.OpenItems, vm.CompletedItems })
|
||||
{
|
||||
var idx = section.IndexOf(row);
|
||||
if (idx >= 0) return idx + 1 < section.Count ? section[idx + 1] : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async void OnRowDrop(object? sender, DragEventArgs e)
|
||||
{
|
||||
if (DataContext is not TasksIslandViewModel vm) return;
|
||||
try
|
||||
{
|
||||
if (sender is not Button b || b.DataContext is not TaskRowViewModel target) return;
|
||||
if (target.IsRunning) return;
|
||||
|
||||
var sourceId = e.DataTransfer?.TryGetValue(TaskRowFormat);
|
||||
if (string.IsNullOrEmpty(sourceId) || sourceId == target.Id) return;
|
||||
|
||||
var source = FindRowById(vm, sourceId);
|
||||
if (source is null || source.IsRunning) return;
|
||||
|
||||
var placeBelow = e.GetPosition(b).Y > b.Bounds.Height / 2;
|
||||
|
||||
// Clear the 6px drop-hint spacer BEFORE the move so the reorder animates
|
||||
// into its truly-final layout in one step (otherwise the row lands in the
|
||||
// gap, then the gap collapses and everything shifts up a second time).
|
||||
vm.ClearDropHints();
|
||||
|
||||
await vm.ReorderAsync(source, target, placeBelow);
|
||||
}
|
||||
catch
|
||||
{
|
||||
vm.ClearDropHints();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static TaskRowViewModel? FindRowById(TasksIslandViewModel vm, string id)
|
||||
{
|
||||
foreach (var r in vm.Items)
|
||||
if (r.Id == id) return r;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,20 +2,26 @@
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ClaudeDo.Ui.ViewModels"
|
||||
xmlns:islands="using:ClaudeDo.Ui.Views.Islands"
|
||||
xmlns:converters="using:ClaudeDo.Ui.Converters"
|
||||
x:Class="ClaudeDo.Ui.Views.MainWindow"
|
||||
x:DataType="vm:IslandsShellViewModel"
|
||||
Title="ClaudeDo"
|
||||
Width="1280" Height="820" MinWidth="780" MinHeight="600"
|
||||
Background="{DynamicResource VoidBrush}"
|
||||
SystemDecorations="None"
|
||||
Icon="avares://ClaudeDo.Ui/Assets/ClaudeTask.ico"
|
||||
CanResize="True"
|
||||
SystemDecorations="BorderOnly"
|
||||
ExtendClientAreaToDecorationsHint="True"
|
||||
ExtendClientAreaTitleBarHeightHint="-1">
|
||||
<Window.Resources>
|
||||
<converters:WorkerLogLevelToBrushConverter x:Key="WorkerLogLevelToBrush"/>
|
||||
</Window.Resources>
|
||||
<Window.KeyBindings>
|
||||
<KeyBinding Gesture="OemQuestion" Command="{Binding FocusSearchCommand}"/>
|
||||
<KeyBinding Gesture="Shift+OemQuestion" Command="{Binding FocusSearchCommand}"/>
|
||||
<KeyBinding Gesture="Ctrl+N" Command="{Binding FocusAddTaskCommand}"/>
|
||||
</Window.KeyBindings>
|
||||
<Grid RowDefinitions="36,*,22">
|
||||
<Grid RowDefinitions="36,Auto,*,22">
|
||||
<!-- Custom title bar -->
|
||||
<Border Grid.Row="0"
|
||||
Background="{DynamicResource DeepBrush}"
|
||||
@@ -26,11 +32,11 @@
|
||||
<!-- Left: brand block -->
|
||||
<StackPanel Grid.Column="0" Orientation="Horizontal" Spacing="8"
|
||||
VerticalAlignment="Center" Margin="14,0,0,0">
|
||||
<!-- Green checkbox glyph -->
|
||||
<PathIcon Classes="title-brand-icon"
|
||||
Data="{StaticResource Icon.BrandCheck}"
|
||||
Width="14" Height="14"
|
||||
Foreground="{DynamicResource MossBrush}" />
|
||||
<!-- App icon (matches taskbar) -->
|
||||
<Image Source="avares://ClaudeDo.Ui/Assets/ClaudeTask.ico"
|
||||
Width="16" Height="16"
|
||||
VerticalAlignment="Center"
|
||||
RenderOptions.BitmapInterpolationMode="HighQuality"/>
|
||||
<!-- CLAUDEDO label -->
|
||||
<TextBlock Classes="title-brand-name"
|
||||
Text="CLAUDEDO"
|
||||
@@ -52,6 +58,17 @@
|
||||
Foreground="{DynamicResource TextDimBrush}"
|
||||
LetterSpacing="1.4"
|
||||
VerticalAlignment="Center"/>
|
||||
<!-- Help menu -->
|
||||
<Menu Margin="12,0,0,0"
|
||||
Background="Transparent"
|
||||
VerticalAlignment="Center">
|
||||
<MenuItem Header="Help"
|
||||
FontSize="11"
|
||||
Foreground="{DynamicResource TextDimBrush}">
|
||||
<MenuItem Header="Check for updates"
|
||||
Command="{Binding CheckForUpdatesCommand}"/>
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Middle: draggable strip -->
|
||||
@@ -75,8 +92,47 @@
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Update banner -->
|
||||
<Border Grid.Row="1"
|
||||
Background="{DynamicResource DeepBrush}"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="0,0,0,1"
|
||||
Padding="14,6"
|
||||
IsVisible="{Binding IsUpdateBannerVisible}">
|
||||
<Grid ColumnDefinitions="*,Auto,Auto">
|
||||
<TextBlock Grid.Column="0"
|
||||
VerticalAlignment="Center"
|
||||
Foreground="{DynamicResource TextDimBrush}"
|
||||
FontSize="12">
|
||||
<Run Text="Update available: v"/>
|
||||
<Run Text="{Binding UpdateCheck.CurrentVersion}"/>
|
||||
<Run Text=" → v"/>
|
||||
<Run Text="{Binding UpdateBannerLatestVersion}"/>
|
||||
</TextBlock>
|
||||
<Button Grid.Column="1"
|
||||
Margin="0,0,8,0"
|
||||
Padding="10,3"
|
||||
Content="Update now"
|
||||
Command="{Binding UpdateNowCommand}"/>
|
||||
<Button Grid.Column="2"
|
||||
Padding="10,3"
|
||||
Content="Dismiss"
|
||||
Command="{Binding DismissBannerCommand}"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Inline update status (appears at right of banner row when no banner) -->
|
||||
<TextBlock Grid.Row="1"
|
||||
HorizontalAlignment="Right"
|
||||
VerticalAlignment="Center"
|
||||
Margin="0,0,14,0"
|
||||
FontSize="11"
|
||||
Foreground="{DynamicResource TextFaintBrush}"
|
||||
Text="{Binding InlineUpdateStatus}"
|
||||
IsVisible="{Binding InlineUpdateStatus, Converter={x:Static ObjectConverters.IsNotNull}}"/>
|
||||
|
||||
<!-- Background gradient layer -->
|
||||
<Border Grid.Row="1">
|
||||
<Border Grid.Row="2">
|
||||
<Border.Background>
|
||||
<RadialGradientBrush Center="50%,50%" GradientOrigin="50%,50%" RadiusX="70%" RadiusY="70%">
|
||||
<GradientStop Offset="0" Color="{StaticResource DeepColor}" />
|
||||
@@ -86,7 +142,7 @@
|
||||
</Border>
|
||||
|
||||
<!-- Three islands -->
|
||||
<Grid Grid.Row="1" Margin="7" ColumnDefinitions="260,*,320">
|
||||
<Grid Grid.Row="2" Margin="7" ColumnDefinitions="260,*,320">
|
||||
<Border Grid.Column="0" Classes="island" Margin="7">
|
||||
<islands:ListsIslandView DataContext="{Binding Lists}"/>
|
||||
</Border>
|
||||
@@ -100,12 +156,14 @@
|
||||
</Grid>
|
||||
|
||||
<!-- Footer: connection status -->
|
||||
<Border Grid.Row="2"
|
||||
<Border Grid.Row="3"
|
||||
Background="{DynamicResource DeepBrush}"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="0,1,0,0">
|
||||
<StackPanel Orientation="Horizontal" Spacing="7"
|
||||
VerticalAlignment="Center" Margin="14,0">
|
||||
<DockPanel LastChildFill="True" Margin="14,0">
|
||||
<!-- Left: connection pill -->
|
||||
<StackPanel DockPanel.Dock="Left" Orientation="Horizontal" Spacing="7"
|
||||
VerticalAlignment="Center">
|
||||
<Ellipse Width="7" Height="7" Fill="#4CAF50"
|
||||
IsVisible="{Binding Worker.IsConnected}"/>
|
||||
<Ellipse Width="7" Height="7" Fill="#FFA726"
|
||||
@@ -118,18 +176,22 @@
|
||||
LetterSpacing="1.4"
|
||||
Foreground="{DynamicResource TextDimBrush}"
|
||||
VerticalAlignment="Center"/>
|
||||
<TextBlock Text="·"
|
||||
FontFamily="{DynamicResource MonoFont}"
|
||||
FontSize="10"
|
||||
Foreground="{DynamicResource TextFaintBrush}"
|
||||
VerticalAlignment="Center"/>
|
||||
<TextBlock Text="WORKER"
|
||||
</StackPanel>
|
||||
|
||||
<!-- Right: worker log line -->
|
||||
<TextBlock DockPanel.Dock="Right"
|
||||
Text="{Binding WorkerLogText}"
|
||||
IsVisible="{Binding IsWorkerLogVisible}"
|
||||
Foreground="{Binding WorkerLogLevel, Converter={StaticResource WorkerLogLevelToBrush}}"
|
||||
FontFamily="{DynamicResource MonoFont}"
|
||||
FontSize="10"
|
||||
LetterSpacing="1.4"
|
||||
Foreground="{DynamicResource TextFaintBrush}"
|
||||
TextTrimming="CharacterEllipsis"
|
||||
VerticalAlignment="Center"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Spacer between pill and log -->
|
||||
<Panel/>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Window>
|
||||
|
||||
@@ -63,12 +63,15 @@
|
||||
FontFamily="{StaticResource MonoFamily}"
|
||||
FontSize="12"
|
||||
Foreground="{StaticResource TextDimBrush}"/>
|
||||
<Button Grid.Column="1"
|
||||
Classes="icon-btn"
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="4" VerticalAlignment="Center">
|
||||
<Button Content="Merge…"
|
||||
Command="{Binding MergeCommand}"
|
||||
Margin="0,0,4,0" />
|
||||
<Button Classes="icon-btn"
|
||||
Content="✕"
|
||||
FontSize="12"
|
||||
Command="{Binding CloseCommand}"
|
||||
VerticalAlignment="Center"/>
|
||||
Command="{Binding CloseCommand}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
@@ -93,7 +96,7 @@
|
||||
FontFamily="{StaticResource MonoFamily}"
|
||||
FontSize="11"
|
||||
Foreground="{StaticResource TextDimBrush}"
|
||||
TextTrimming="LeadingEllipsis"/>
|
||||
TextTrimming="PrefixCharacterEllipsis"/>
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<Border Classes="chip" Padding="5,2">
|
||||
<TextBlock Foreground="{StaticResource MossBrightBrush}"
|
||||
@@ -116,10 +119,16 @@
|
||||
</Border>
|
||||
|
||||
<!-- Diff content -->
|
||||
<ScrollViewer Grid.Column="1"
|
||||
HorizontalScrollBarVisibility="Auto"
|
||||
VerticalScrollBarVisibility="Auto"
|
||||
Background="{StaticResource VoidBrush}">
|
||||
<Grid Grid.Column="1" Background="{StaticResource VoidBrush}">
|
||||
<TextBlock Text="{Binding StatusMessage}"
|
||||
IsVisible="{Binding StatusMessage, Converter={x:Static StringConverters.IsNotNullOrEmpty}}"
|
||||
HorizontalAlignment="Center"
|
||||
VerticalAlignment="Center"
|
||||
Foreground="{StaticResource TextDimBrush}"
|
||||
FontFamily="{StaticResource MonoFamily}"
|
||||
FontSize="12"/>
|
||||
<ScrollViewer HorizontalScrollBarVisibility="Auto"
|
||||
VerticalScrollBarVisibility="Auto">
|
||||
<ItemsControl ItemsSource="{Binding SelectedFile.Lines}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:DiffLineViewModel">
|
||||
@@ -166,5 +175,6 @@
|
||||
</ScrollViewer>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Window>
|
||||
|
||||
180
src/ClaudeDo.Ui/Views/Modals/ListSettingsModalView.axaml
Normal file
180
src/ClaudeDo.Ui/Views/Modals/ListSettingsModalView.axaml
Normal file
@@ -0,0 +1,180 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="clr-namespace:ClaudeDo.Ui.ViewModels.Modals"
|
||||
x:Class="ClaudeDo.Ui.Views.Modals.ListSettingsModalView"
|
||||
x:DataType="vm:ListSettingsModalViewModel"
|
||||
Title="List settings"
|
||||
Width="520" Height="720"
|
||||
CanResize="True"
|
||||
MinWidth="460" MinHeight="520"
|
||||
SystemDecorations="None"
|
||||
ExtendClientAreaToDecorationsHint="True"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
Background="{DynamicResource SurfaceBrush}">
|
||||
|
||||
<Window.KeyBindings>
|
||||
<KeyBinding Gesture="Escape" Command="{Binding CancelCommand}"/>
|
||||
</Window.KeyBindings>
|
||||
|
||||
<Window.Styles>
|
||||
<Style Selector="TextBlock.section-label">
|
||||
<Setter Property="FontFamily" Value="{DynamicResource MonoFont}"/>
|
||||
<Setter Property="FontSize" Value="10"/>
|
||||
<Setter Property="LetterSpacing" Value="1.4"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextFaintBrush}"/>
|
||||
<Setter Property="Margin" Value="4,0,0,6"/>
|
||||
</Style>
|
||||
<Style Selector="TextBlock.field-label">
|
||||
<Setter Property="FontSize" Value="11"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextDimBrush}"/>
|
||||
<Setter Property="Margin" Value="0,0,0,4"/>
|
||||
</Style>
|
||||
<Style Selector="Border.section">
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource LineBrush}"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Setter Property="CornerRadius" Value="6"/>
|
||||
<Setter Property="Padding" Value="14"/>
|
||||
<Setter Property="Background" Value="{DynamicResource DeepBrush}"/>
|
||||
</Style>
|
||||
<Style Selector="Button.primary">
|
||||
<Setter Property="Background" Value="{DynamicResource AccentBrush}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource DeepBrush}"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
</Style>
|
||||
</Window.Styles>
|
||||
|
||||
<Border Background="{DynamicResource SurfaceBrush}"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="1">
|
||||
<Grid RowDefinitions="36,*,52">
|
||||
|
||||
<!-- Title bar -->
|
||||
<Border Grid.Row="0"
|
||||
x:Name="TitleBar"
|
||||
Background="{DynamicResource DeepBrush}"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="0,0,0,1"
|
||||
PointerPressed="TitleBar_PointerPressed">
|
||||
<Grid ColumnDefinitions="*,Auto" Margin="14,0">
|
||||
<TextBlock Text="LIST SETTINGS"
|
||||
FontFamily="{DynamicResource MonoFont}"
|
||||
FontSize="11"
|
||||
LetterSpacing="1.4"
|
||||
Foreground="{DynamicResource TextBrush}"
|
||||
VerticalAlignment="Center"/>
|
||||
<Button Grid.Column="1"
|
||||
Classes="icon-btn"
|
||||
Content="✕"
|
||||
FontSize="12"
|
||||
Command="{Binding CancelCommand}"
|
||||
VerticalAlignment="Center"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Body -->
|
||||
<ScrollViewer Grid.Row="1" Padding="20,16">
|
||||
<StackPanel Spacing="18">
|
||||
|
||||
<!-- GENERAL -->
|
||||
<StackPanel Spacing="0">
|
||||
<TextBlock Classes="section-label" Text="GENERAL"/>
|
||||
<Border Classes="section">
|
||||
<StackPanel Spacing="12">
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Classes="field-label" Text="Name"/>
|
||||
<TextBox Text="{Binding Name}" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Classes="field-label" Text="Working directory"/>
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<TextBox Grid.Column="0" Text="{Binding WorkingDir}" Watermark="(none)" />
|
||||
<Button Grid.Column="1" Content="Browse..." Margin="8,0,0,0" Click="BrowseClicked" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Classes="field-label" Text="Default commit type"/>
|
||||
<ComboBox ItemsSource="{Binding CommitTypeOptions}"
|
||||
SelectedItem="{Binding DefaultCommitType, Mode=TwoWay}"
|
||||
HorizontalAlignment="Left" MinWidth="160" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
<!-- AGENT -->
|
||||
<StackPanel Spacing="0">
|
||||
<Grid ColumnDefinitions="*,Auto" Margin="4,0,0,6">
|
||||
<TextBlock Classes="section-label" Text="AGENT" Margin="0"/>
|
||||
<Button Grid.Column="1" Content="Reset agent settings"
|
||||
Command="{Binding ResetAgentSettingsCommand}" />
|
||||
</Grid>
|
||||
<Border Classes="section">
|
||||
<StackPanel Spacing="12">
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Classes="field-label" Text="Model"/>
|
||||
<ComboBox ItemsSource="{Binding ModelOptions}"
|
||||
SelectedItem="{Binding SelectedModel, Mode=TwoWay}"
|
||||
HorizontalAlignment="Left" MinWidth="160" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Classes="field-label" Text="System prompt (appended)"/>
|
||||
<TextBox Text="{Binding SystemPrompt, Mode=TwoWay}"
|
||||
AcceptsReturn="True" TextWrapping="Wrap"
|
||||
MinHeight="80" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Classes="field-label" Text="Agent file"/>
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<ComboBox Grid.Column="0"
|
||||
ItemsSource="{Binding Agents}"
|
||||
SelectedItem="{Binding SelectedAgent, Mode=TwoWay}"
|
||||
HorizontalAlignment="Stretch">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<StackPanel>
|
||||
<TextBlock Text="{Binding Name}"
|
||||
Foreground="{DynamicResource TextBrush}"/>
|
||||
<TextBlock Text="{Binding Description}"
|
||||
Foreground="{DynamicResource TextMuteBrush}"
|
||||
FontSize="11" />
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<Button Grid.Column="1" Content="Browse..."
|
||||
Margin="8,0,0,0" Click="BrowseAgentClicked" />
|
||||
</Grid>
|
||||
<TextBlock Text="{Binding SelectedAgent.Path}"
|
||||
FontFamily="{DynamicResource MonoFont}"
|
||||
FontSize="11"
|
||||
Foreground="{DynamicResource TextFaintBrush}"
|
||||
TextTrimming="PrefixCharacterEllipsis"
|
||||
IsVisible="{Binding SelectedAgent.Path, Converter={x:Static StringConverters.IsNotNullOrEmpty}}"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
|
||||
<!-- Footer -->
|
||||
<Border Grid.Row="2"
|
||||
Background="{DynamicResource DeepBrush}"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="0,1,0,0">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8"
|
||||
HorizontalAlignment="Right" VerticalAlignment="Center"
|
||||
Margin="16,0">
|
||||
<Button Content="Cancel" Command="{Binding CancelCommand}" MinWidth="90"/>
|
||||
<Button Content="Save" Classes="primary" Command="{Binding SaveCommand}" MinWidth="90"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</Grid>
|
||||
</Border>
|
||||
</Window>
|
||||
90
src/ClaudeDo.Ui/Views/Modals/ListSettingsModalView.axaml.cs
Normal file
90
src/ClaudeDo.Ui/Views/Modals/ListSettingsModalView.axaml.cs
Normal file
@@ -0,0 +1,90 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Platform.Storage;
|
||||
using ClaudeDo.Data.Models;
|
||||
using ClaudeDo.Ui.ViewModels.Modals;
|
||||
|
||||
namespace ClaudeDo.Ui.Views.Modals;
|
||||
|
||||
public partial class ListSettingsModalView : Window
|
||||
{
|
||||
public ListSettingsModalView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void TitleBar_PointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
|
||||
BeginMoveDrag(e);
|
||||
}
|
||||
|
||||
private async void BrowseAgentClicked(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (DataContext is not ListSettingsModalViewModel vm) return;
|
||||
var top = TopLevel.GetTopLevel(this);
|
||||
if (top is null) return;
|
||||
|
||||
var files = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
|
||||
{
|
||||
Title = "Choose agent file",
|
||||
AllowMultiple = false,
|
||||
FileTypeFilter = new[]
|
||||
{
|
||||
new FilePickerFileType("Agent files (*.md)") { Patterns = new[] { "*.md" } },
|
||||
new FilePickerFileType("All files") { Patterns = new[] { "*" } },
|
||||
},
|
||||
});
|
||||
if (files.Count == 0) return;
|
||||
|
||||
var path = files[0].Path.LocalPath;
|
||||
var existing = vm.Agents.FirstOrDefault(a => string.Equals(a.Path, path, StringComparison.OrdinalIgnoreCase));
|
||||
if (existing is not null)
|
||||
{
|
||||
vm.SelectedAgent = existing;
|
||||
return;
|
||||
}
|
||||
|
||||
var (name, description) = ReadFrontmatter(path);
|
||||
var agent = new AgentInfo(name, description, path);
|
||||
vm.Agents.Add(agent);
|
||||
vm.SelectedAgent = agent;
|
||||
}
|
||||
|
||||
private static (string name, string description) ReadFrontmatter(string filePath)
|
||||
{
|
||||
var fallback = System.IO.Path.GetFileNameWithoutExtension(filePath);
|
||||
try
|
||||
{
|
||||
using var reader = new System.IO.StreamReader(filePath);
|
||||
if (reader.ReadLine()?.Trim() != "---") return (fallback, "");
|
||||
string name = fallback, description = "";
|
||||
while (reader.ReadLine() is { } line)
|
||||
{
|
||||
if (line.Trim() == "---") break;
|
||||
if (line.StartsWith("name:")) name = line["name:".Length..].Trim();
|
||||
else if (line.StartsWith("description:")) description = line["description:".Length..].Trim();
|
||||
}
|
||||
return (name, description);
|
||||
}
|
||||
catch { return (fallback, ""); }
|
||||
}
|
||||
|
||||
private async void BrowseClicked(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (DataContext is not ListSettingsModalViewModel vm) return;
|
||||
var top = TopLevel.GetTopLevel(this);
|
||||
if (top is null) return;
|
||||
|
||||
var folders = await top.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
|
||||
{
|
||||
Title = "Choose working directory",
|
||||
AllowMultiple = false,
|
||||
});
|
||||
if (folders.Count > 0)
|
||||
{
|
||||
vm.WorkingDir = folders[0].Path.LocalPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
138
src/ClaudeDo.Ui/Views/Modals/MergeModalView.axaml
Normal file
138
src/ClaudeDo.Ui/Views/Modals/MergeModalView.axaml
Normal file
@@ -0,0 +1,138 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="clr-namespace:ClaudeDo.Ui.ViewModels.Modals"
|
||||
x:Class="ClaudeDo.Ui.Views.Modals.MergeModalView"
|
||||
x:DataType="vm:MergeModalViewModel"
|
||||
Title="Merge worktree"
|
||||
Width="560" Height="460"
|
||||
CanResize="False"
|
||||
SystemDecorations="None"
|
||||
ExtendClientAreaToDecorationsHint="True"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
Background="{DynamicResource SurfaceBrush}">
|
||||
|
||||
<Window.KeyBindings>
|
||||
<KeyBinding Gesture="Escape" Command="{Binding CancelCommand}"/>
|
||||
</Window.KeyBindings>
|
||||
|
||||
<Window.Styles>
|
||||
<Style Selector="TextBlock.field-label">
|
||||
<Setter Property="FontSize" Value="11"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextDimBrush}"/>
|
||||
<Setter Property="Margin" Value="0,0,0,4"/>
|
||||
</Style>
|
||||
<Style Selector="Button.primary">
|
||||
<Setter Property="Background" Value="{DynamicResource AccentBrush}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource DeepBrush}"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
</Style>
|
||||
</Window.Styles>
|
||||
|
||||
<Border Background="{DynamicResource SurfaceBrush}"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="1">
|
||||
<Grid RowDefinitions="36,*,52">
|
||||
|
||||
<!-- Title bar -->
|
||||
<Border Grid.Row="0"
|
||||
x:Name="TitleBar"
|
||||
Background="{DynamicResource DeepBrush}"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="0,0,0,1"
|
||||
PointerPressed="TitleBar_PointerPressed">
|
||||
<Grid ColumnDefinitions="*,Auto" Margin="14,0">
|
||||
<TextBlock Text="MERGE WORKTREE"
|
||||
FontFamily="{DynamicResource MonoFont}"
|
||||
FontSize="11"
|
||||
LetterSpacing="1.4"
|
||||
Foreground="{DynamicResource TextBrush}"
|
||||
VerticalAlignment="Center"/>
|
||||
<Button Grid.Column="1"
|
||||
Classes="icon-btn"
|
||||
Content="✕"
|
||||
FontSize="12"
|
||||
Command="{Binding CancelCommand}"
|
||||
VerticalAlignment="Center"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Body -->
|
||||
<ScrollViewer Grid.Row="1" Padding="20,16">
|
||||
<StackPanel Spacing="12">
|
||||
|
||||
<TextBlock Text="{Binding TaskTitle, StringFormat='Merging: {0}'}"
|
||||
FontWeight="SemiBold"
|
||||
Foreground="{DynamicResource TextBrush}" />
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Classes="field-label" Text="Target branch"/>
|
||||
<ComboBox ItemsSource="{Binding Branches}"
|
||||
SelectedItem="{Binding SelectedBranch}"
|
||||
HorizontalAlignment="Stretch"
|
||||
IsEnabled="{Binding !IsBusy}" />
|
||||
</StackPanel>
|
||||
|
||||
<CheckBox Content="Remove worktree after merge"
|
||||
IsChecked="{Binding RemoveWorktree}"
|
||||
IsEnabled="{Binding !IsBusy}" />
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Classes="field-label" Text="Commit message"/>
|
||||
<TextBox Text="{Binding CommitMessage}"
|
||||
AcceptsReturn="True"
|
||||
TextWrapping="Wrap"
|
||||
Height="70"
|
||||
IsEnabled="{Binding !IsBusy}" />
|
||||
</StackPanel>
|
||||
|
||||
<TextBlock Text="{Binding ErrorMessage}"
|
||||
Foreground="{DynamicResource BloodBrush}"
|
||||
TextWrapping="Wrap"
|
||||
IsVisible="{Binding ErrorMessage, Converter={x:Static ObjectConverters.IsNotNull}}" />
|
||||
|
||||
<Border BorderBrush="{DynamicResource BloodBrush}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="6"
|
||||
Padding="12,10"
|
||||
IsVisible="{Binding HasConflict}">
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="Conflicted files:"
|
||||
FontWeight="SemiBold"
|
||||
Foreground="{DynamicResource TextBrush}" />
|
||||
<ItemsControl ItemsSource="{Binding ConflictFiles}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding}"
|
||||
FontFamily="{DynamicResource MonoFont}"
|
||||
FontSize="11"
|
||||
Foreground="{DynamicResource TextDimBrush}" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<TextBlock Text="{Binding SuccessMessage}"
|
||||
Foreground="{DynamicResource MossBrightBrush}"
|
||||
IsVisible="{Binding SuccessMessage, Converter={x:Static ObjectConverters.IsNotNull}}" />
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
|
||||
<!-- Footer -->
|
||||
<Border Grid.Row="2"
|
||||
Background="{DynamicResource DeepBrush}"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="0,1,0,0">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8"
|
||||
HorizontalAlignment="Right" VerticalAlignment="Center"
|
||||
Margin="16,0">
|
||||
<Button Content="Cancel" Command="{Binding CancelCommand}" MinWidth="90"/>
|
||||
<Button Content="Merge" Classes="primary"
|
||||
Command="{Binding SubmitCommand}"
|
||||
IsDefault="True" MinWidth="90"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</Grid>
|
||||
</Border>
|
||||
</Window>
|
||||
26
src/ClaudeDo.Ui/Views/Modals/MergeModalView.axaml.cs
Normal file
26
src/ClaudeDo.Ui/Views/Modals/MergeModalView.axaml.cs
Normal file
@@ -0,0 +1,26 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using ClaudeDo.Ui.ViewModels.Modals;
|
||||
|
||||
namespace ClaudeDo.Ui.Views.Modals;
|
||||
|
||||
public partial class MergeModalView : Window
|
||||
{
|
||||
public MergeModalView()
|
||||
{
|
||||
InitializeComponent();
|
||||
DataContextChanged += (_, _) =>
|
||||
{
|
||||
if (DataContext is MergeModalViewModel vm)
|
||||
{
|
||||
vm.CloseAction = () => Close();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private void TitleBar_PointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
|
||||
BeginMoveDrag(e);
|
||||
}
|
||||
}
|
||||
@@ -184,6 +184,23 @@
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
<!-- AGENTS -->
|
||||
<StackPanel Spacing="0">
|
||||
<TextBlock Classes="section-label" Text="AGENTS"/>
|
||||
<Border Classes="section">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Restore bundled default agents (code-reviewer, test-writer, debugger, security-reviewer, explorer, researcher). Existing files are not overwritten."
|
||||
FontSize="11"
|
||||
TextWrapping="Wrap"
|
||||
Foreground="{DynamicResource TextDimBrush}"/>
|
||||
<Button Content="Restore default agents"
|
||||
Command="{Binding RestoreDefaultAgentsCommand}"
|
||||
IsEnabled="{Binding !IsBusy}"
|
||||
HorizontalAlignment="Left"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ABOUT -->
|
||||
<StackPanel Spacing="0">
|
||||
<TextBlock Classes="section-label" Text="ABOUT"/>
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="clr-namespace:ClaudeDo.Ui.ViewModels.Modals"
|
||||
x:Class="ClaudeDo.Ui.Views.Modals.UnfinishedPlanningModalView"
|
||||
x:DataType="vm:UnfinishedPlanningModalViewModel"
|
||||
Title="Unfinished planning session"
|
||||
Width="440" Height="200"
|
||||
CanResize="False"
|
||||
SystemDecorations="None"
|
||||
ExtendClientAreaToDecorationsHint="True"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
Background="{DynamicResource SurfaceBrush}">
|
||||
|
||||
<Window.KeyBindings>
|
||||
<KeyBinding Gesture="Escape" Command="{Binding CancelCommand}"/>
|
||||
</Window.KeyBindings>
|
||||
|
||||
<Window.Styles>
|
||||
<Style Selector="Button.primary">
|
||||
<Setter Property="Background" Value="{DynamicResource AccentBrush}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource DeepBrush}"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
</Style>
|
||||
</Window.Styles>
|
||||
|
||||
<Border Background="{DynamicResource SurfaceBrush}"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="1">
|
||||
<Grid RowDefinitions="36,*,52">
|
||||
|
||||
<!-- Title bar -->
|
||||
<Border Grid.Row="0"
|
||||
x:Name="TitleBar"
|
||||
Background="{DynamicResource DeepBrush}"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="0,0,0,1"
|
||||
PointerPressed="TitleBar_PointerPressed">
|
||||
<Grid ColumnDefinitions="*,Auto" Margin="14,0">
|
||||
<TextBlock Text="UNFINISHED PLANNING SESSION"
|
||||
FontFamily="{DynamicResource MonoFont}"
|
||||
FontSize="11"
|
||||
LetterSpacing="1.4"
|
||||
Foreground="{DynamicResource TextBrush}"
|
||||
VerticalAlignment="Center"/>
|
||||
<Button Grid.Column="1"
|
||||
Classes="icon-btn"
|
||||
Content="✕"
|
||||
FontSize="12"
|
||||
Command="{Binding CancelCommand}"
|
||||
VerticalAlignment="Center"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Body -->
|
||||
<StackPanel Grid.Row="1" Margin="20,16" Spacing="8">
|
||||
<TextBlock Text="{Binding TaskTitle}"
|
||||
FontWeight="SemiBold"
|
||||
Foreground="{DynamicResource TextBrush}"
|
||||
TextTrimming="CharacterEllipsis"/>
|
||||
<TextBlock Foreground="{DynamicResource TextDimBrush}">
|
||||
<Run Text="{Binding DraftCount}"/>
|
||||
<Run Text=" draft task(s) waiting to be finalized."/>
|
||||
</TextBlock>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Footer -->
|
||||
<Border Grid.Row="2"
|
||||
Background="{DynamicResource DeepBrush}"
|
||||
BorderBrush="{DynamicResource LineBrush}"
|
||||
BorderThickness="0,1,0,0">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8"
|
||||
HorizontalAlignment="Right" VerticalAlignment="Center"
|
||||
Margin="16,0">
|
||||
<Button Content="Discard" Command="{Binding DiscardCommand}" MinWidth="80"/>
|
||||
<Button Content="Finalize" Command="{Binding FinalizeNowCommand}" MinWidth="80"/>
|
||||
<Button Content="Resume" Command="{Binding ResumeCommand}" Classes="primary" MinWidth="80"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</Grid>
|
||||
</Border>
|
||||
</Window>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user