feat: unarchive tasks with worktree branch recovery (#1687)

* feat: unarchive tasks with worktree branch recovery

Archived tasks can now be restored. Unarchive works for manual/legacy
archives (empty cascade id, root-only) and cascade archives. Archive
deletes the local branch, so worktree recreate now falls back to
fetching the branch from origin, and unarchive writes the old branch
back as checkout_branch so a fresh session resumes the prior work.
Unrecoverable branches (never pushed) surface a warning. WS archive now
routes through the handoff cascade so it stays stamped and reversible.
UI: unarchive action on /tasks archived rows and the task top bar.

* fix: address PR review feedback on unarchive recovery

Forward PRNumber to the recreate fetch so fork-PR heads (only reachable
via pull/<N>/head) are recoverable, publish task.updated per task in the
cascade unarchive loop so the UI restores without a reload, and
re-publish task.updated after a checkout_branch restore since the
unarchive event goes out with the pre-restore repository rows.

* fix: harden unarchive recovery per review feedback

Propagate branch-probe errors instead of misreporting recoverable work
as gone, and reserve ErrBranchUnrecoverable for a confirmed-missing
remote ref (transient fetch failures keep their own error). Validate
the archive root exists so WS/HTTP archive no longer reports success
for unknown task IDs, CAS-guard manual unarchive on an empty cascade
stamp, detach branch recovery from the request context, and skip
checkout_branch restore for multi-branch repos. UI: in-flight guard on
the list unarchive button, pluralized unrecoverable-branch toast.

* docs: document CAS guard on UnarchiveTask interface contract

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
This commit is contained in:
João Salavisa
2026-07-14 19:15:51 +01:00
committed by GitHub
parent 79f280679a
commit 7bcb10bfef
24 changed files with 1202 additions and 8 deletions
@@ -131,6 +131,9 @@ func (m *mockRepository) ArchiveTaskIfActive(_ context.Context, _, _ string) (bo
func (m *mockRepository) UnarchiveTaskByCascade(_ context.Context, _, _ string) (bool, error) {
return false, nil
}
func (m *mockRepository) UnarchiveTask(_ context.Context, _ string) (bool, error) {
return false, nil
}
func (m *mockRepository) IncrementTaskSequence(_ context.Context, _ string) (int, error) {
return 0, nil
}
@@ -1220,12 +1220,25 @@ func (h *TaskHandlers) httpUnarchiveTask(c *gin.Context) {
handleNotFound(c, h.logger, err, "task not unarchived")
return
}
// Probe branch recoverability for every restored task: archive deleted
// the local branch + worktree, so report whether the branch still
// exists (locally or on origin) and restore checkout_branch so the
// next session picks the old work back up. Best-effort — an empty
// list just means nothing was recoverable. Detached from the request
// context: the tasks are already unarchived, so a client disconnect
// must not skip the checkout_branch restore.
recoveryCtx := context.WithoutCancel(c.Request.Context())
recovery := make([]service.BranchRecovery, 0)
for _, id := range outcome.ArchivedTaskIDs {
recovery = append(recovery, h.service.RecoverTaskBranches(recoveryCtx, id)...)
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"cascade_id": outcome.CascadeID,
"unarchived_ids": outcome.ArchivedTaskIDs,
"skipped_ids": outcome.SkippedTaskIDs,
"affected_group_ids": outcome.ReleasedGroupIDs,
"recovery": recovery,
})
}
@@ -0,0 +1,71 @@
package handlers
import (
"context"
"encoding/json"
"sync"
"testing"
"github.com/kandev/kandev/internal/task/models"
"github.com/kandev/kandev/internal/task/service"
ws "github.com/kandev/kandev/pkg/websocket"
)
// archiveStampRepo overrides just enough of mockRepository for the
// HandoffService archive path: GetTask returns a live task and
// ArchiveTaskIfActive records the cascade stamp.
type archiveStampRepo struct {
mockRepository
mu sync.Mutex
stamped map[string]string // taskID → cascadeID
}
func (r *archiveStampRepo) GetTask(_ context.Context, id string) (*models.Task, error) {
return &models.Task{ID: id, WorkspaceID: "ws-1"}, nil
}
func (r *archiveStampRepo) ArchiveTaskIfActive(_ context.Context, id, cascadeID string) (bool, error) {
r.mu.Lock()
defer r.mu.Unlock()
if r.stamped == nil {
r.stamped = map[string]string{}
}
r.stamped[id] = cascadeID
return true, nil
}
// TestWsArchiveTask_StampsCascadeID is the WS-side parity test: archives
// issued over the WebSocket action must route through HandoffService and
// receive a cascade stamp, otherwise WS-archived tasks were permanently
// unrecoverable (UnarchiveTaskByCascade requires the stamp; the manual
// fallback only exists for legacy rows).
func TestWsArchiveTask_StampsCascadeID(t *testing.T) {
repo := &archiveStampRepo{}
h := &TaskHandlers{
handoffSvc: service.NewHandoffService(repo, nil, nil, nil, nil, nil),
logger: newTestLogger(t),
}
msg := &ws.Message{
ID: "msg-1",
Action: ws.ActionTaskArchive,
Payload: json.RawMessage(`{"id":"task-1"}`),
}
resp, err := h.wsArchiveTask(context.Background(), msg)
if err != nil {
t.Fatalf("wsArchiveTask: %v", err)
}
if resp == nil || resp.Type == ws.MessageTypeError {
t.Fatalf("wsArchiveTask response = %+v, want success", resp)
}
repo.mu.Lock()
defer repo.mu.Unlock()
cascadeID, ok := repo.stamped["task-1"]
if !ok {
t.Fatal("task-1 was not archived through the handoff cascade path")
}
if cascadeID == "" {
t.Fatal("cascade ID must be stamped so the task stays unarchivable")
}
}
@@ -309,6 +309,17 @@ func (h *TaskHandlers) wsDeleteTask(ctx context.Context, msg *ws.Message) (*ws.M
func (h *TaskHandlers) wsArchiveTask(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
return wsHandleIDRequest(ctx, msg, h.logger, "failed to archive task",
func(ctx context.Context, id string) (any, error) {
// Route through HandoffService when wired (parity with the HTTP
// handler) so the archive gets a cascade stamp and group
// memberships are released — keeping WS-archived tasks fully
// unarchivable. cascade=false matches the WS payload, which has
// no cascade flag.
if h.handoffSvc != nil {
if _, err := h.handoffSvc.ArchiveTaskTree(ctx, id, false); err != nil {
return nil, err
}
return dto.SuccessResponse{Success: true}, nil
}
if err := h.service.ArchiveTask(ctx, id); err != nil {
return nil, err
}
@@ -45,6 +45,12 @@ type TaskRepository interface {
// UnarchiveTaskByCascade clears archived_at only when the task was
// archived by the named cascade. Returns whether the row was updated.
UnarchiveTaskByCascade(ctx context.Context, id, cascadeID string) (bool, error)
// UnarchiveTask clears archived_at only when the task carries no
// cascade stamp (archived_by_cascade_id empty/NULL) — the CAS keeps a
// delayed manual unarchive from erasing a newer cascade archive.
// Cascade-stamped rows are restored via UnarchiveTaskByCascade.
// Returns whether the row was updated.
UnarchiveTask(ctx context.Context, id string) (bool, error)
ListTasksForAutoArchive(ctx context.Context) ([]*models.Task, error)
ListExpiredQuickChatTasks(ctx context.Context, cutoff time.Time) ([]*models.Task, error)
DeleteExpiredQuickChatTask(ctx context.Context, id string, cutoff time.Time) (bool, error)
@@ -964,6 +964,25 @@ func (r *Repository) UnarchiveTaskByCascade(ctx context.Context, id, cascadeID s
return rows > 0, nil
}
// UnarchiveTask clears archived_at for a manually/legacy-archived task
// (no cascade stamp). The CAS guard on archived_by_cascade_id keeps a
// delayed manual unarchive from erasing a newer cascade archive that
// landed between the caller's read and this update — cascade-stamped
// rows are only restored via UnarchiveTaskByCascade. Returns whether a
// row was actually updated.
func (r *Repository) UnarchiveTask(ctx context.Context, id string) (bool, error) {
result, err := r.db.ExecContext(ctx, r.db.Rebind(`
UPDATE tasks SET archived_at = NULL, archived_by_cascade_id = '', updated_at = ?
WHERE id = ? AND archived_at IS NOT NULL
AND (archived_by_cascade_id = '' OR archived_by_cascade_id IS NULL)
`), time.Now().UTC(), id)
if err != nil {
return false, err
}
rows, _ := result.RowsAffected()
return rows > 0, nil
}
// ListTasksForAutoArchive returns tasks eligible for auto-archiving based on workflow step settings
func (r *Repository) ListTasksForAutoArchive(ctx context.Context) ([]*models.Task, error) {
drv := r.ro.DriverName()
@@ -168,6 +168,14 @@ func (s *HandoffService) ArchiveTaskTree(ctx context.Context, rootID string, cas
if s.tasks == nil {
return nil, errors.New("task repo not configured")
}
// Validate the root exists up front. The CAS archive below treats a
// zero-row update as "skipped" (idempotent re-archive), which would
// silently report success for a task ID that doesn't exist at all.
if root, err := s.tasks.GetTask(ctx, rootID); err != nil {
return nil, err
} else if root == nil {
return nil, fmt.Errorf("task %s not found", rootID)
}
cascadeID := uuid.New().String()
out := &CascadeOutcome{CascadeID: cascadeID}
@@ -345,7 +353,7 @@ func (s *HandoffService) UnarchiveTaskTree(ctx context.Context, rootID string) (
}
cascadeID := root.ArchivedByCascadeID
if cascadeID == "" {
return nil, errors.New("root task was not archived by a cascade; nothing to restore")
return s.unarchiveManualRoot(ctx, root)
}
out := &CascadeOutcome{CascadeID: cascadeID}
// The descendant walk below uses metadata.parent_id only; archived
@@ -364,6 +372,10 @@ func (s *HandoffService) UnarchiveTaskTree(ctx context.Context, rootID string) (
}
if ok {
out.ArchivedTaskIDs = append(out.ArchivedTaskIDs, id)
// Publish per restored task — the WS handler keys off
// archived_at=null to put the card back on the kanban, same
// as ArchiveTaskTree publishes per archived task.
s.publishUpdatedTask(ctx, id)
} else {
out.SkippedTaskIDs = append(out.SkippedTaskIDs, id)
}
@@ -394,6 +406,44 @@ func (s *HandoffService) UnarchiveTaskTree(ctx context.Context, rootID string) (
return out, nil
}
// unarchiveManualRoot restores a single task that was archived without a
// cascade stamp (legacy Service.ArchiveTask path or rows predating the
// cascade infrastructure). Only the root is restored — its descendants
// were archived independently, so resurrecting them here would reintroduce
// the resurrection bug the cascade scoping fixed.
func (s *HandoffService) unarchiveManualRoot(ctx context.Context, root *models.Task) (*CascadeOutcome, error) {
if root.ArchivedAt == nil {
return nil, errors.New("task is not archived")
}
out := &CascadeOutcome{}
ok, err := s.tasks.UnarchiveTask(ctx, root.ID)
if err != nil {
return out, fmt.Errorf("unarchive %s: %w", root.ID, err)
}
if !ok {
out.SkippedTaskIDs = append(out.SkippedTaskIDs, root.ID)
return out, nil
}
out.ArchivedTaskIDs = append(out.ArchivedTaskIDs, root.ID)
s.publishUpdatedTask(ctx, root.ID)
// Legacy archives never released group memberships, but the group may
// have been cleaned since (e.g. by a later cascade on another member).
// Restore the group's materialized workspace if it was cleaned. Best
// effort, like the cascade path: restoreCleanedGroups marks failures as
// restore_status=restore_failed so they surface via the context API.
if s.wsGroups != nil {
g, err := s.wsGroups.GetWorkspaceGroupForTask(ctx, root.ID)
if err != nil {
s.logf().Error("lookup workspace group for unarchived task",
zap.String("task_id", root.ID), zap.Error(err))
} else if g != nil {
out.ReleasedGroupIDs = []string{g.ID}
s.restoreCleanedGroups(ctx, []string{g.ID})
}
}
return out, nil
}
// resolveDeleteSet returns the set of task IDs DeleteTaskTree should
// remove. When cascade is true that's the full descendant tree
// (including archived rows). When cascade is false it's just rootID,
@@ -47,6 +47,19 @@ func (r *fakeCascadeRepo) UnarchiveTaskByCascade(_ context.Context, id, cascadeI
return true, nil
}
func (r *fakeCascadeRepo) UnarchiveTask(_ context.Context, id string) (bool, error) {
r.base.mu.Lock()
defer r.base.mu.Unlock()
t := r.base.tasks[id]
// Mirror the production CAS: only rows without a cascade stamp are
// restorable through the manual path.
if t == nil || t.ArchivedAt == nil || t.ArchivedByCascadeID != "" {
return false, nil
}
t.ArchivedAt = nil
return true, nil
}
// fakeWSGroupRepoCascade extends fakeWSGroupRepo with the phase 6
// release/restore/cleanup-status methods.
type fakeWSGroupRepoCascade struct {
@@ -0,0 +1,92 @@
package service
import (
"context"
"testing"
)
// Manual/legacy archives (empty cascade id — WS handler, MCP tool, or rows
// predating the cascade infrastructure) must be unarchivable root-only.
func TestUnarchiveTaskTree_ManualArchiveRestoresRootOnly(t *testing.T) {
tasks := newFakeTaskRepo()
tasks.addArchivedTask("root", "", "ws-1", "")
tasks.addArchivedTask("c1", "root", "ws-1", "")
groups := newCascadeWSGroupRepo()
svc := newCascadeService(t, tasks, groups)
pub := &fakeEventPublisher{}
svc.SetTaskEventPublisher(pub)
out, err := svc.UnarchiveTaskTree(context.Background(), "root")
if err != nil {
t.Fatalf("unarchive: %v", err)
}
if out.CascadeID != "" {
t.Errorf("cascade id = %q, want empty for manual unarchive", out.CascadeID)
}
if len(out.ArchivedTaskIDs) != 1 || out.ArchivedTaskIDs[0] != "root" {
t.Fatalf("unarchived = %v, want [root]", out.ArchivedTaskIDs)
}
root, _ := tasks.GetTask(context.Background(), "root")
if root.ArchivedAt != nil {
t.Error("root should be unarchived")
}
c1, _ := tasks.GetTask(context.Background(), "c1")
if c1.ArchivedAt == nil {
t.Error("c1 should remain archived (independent manual archive)")
}
pub.mu.Lock()
defer pub.mu.Unlock()
if len(pub.updated) != 1 || pub.updated[0] != "root" {
t.Errorf("PublishTaskUpdated calls = %v, want [root]", pub.updated)
}
}
// A non-archived root is a caller error, not a silent no-op.
func TestUnarchiveTaskTree_NotArchivedErrors(t *testing.T) {
tasks := newFakeTaskRepo()
tasks.addTask("root", "", "ws-1")
svc := newCascadeService(t, tasks, newCascadeWSGroupRepo())
if _, err := svc.UnarchiveTaskTree(context.Background(), "root"); err == nil {
t.Fatal("expected error when unarchiving a non-archived task")
}
}
// Cascade unarchive must publish task.updated per restored task — the WS
// handler keys off archived_at=null to put the card back on the kanban.
// Regression for the review finding that only the manual-root path
// published, leaving the UI stale after a cascade unarchive.
func TestUnarchiveTaskTree_CascadePublishesTaskUpdatedPerTask(t *testing.T) {
tasks := newFakeTaskRepo()
tasks.addTask("root", "", "ws-1")
tasks.addTask("c1", "root", "ws-1")
groups := newCascadeWSGroupRepo()
svc := newCascadeService(t, tasks, groups)
pub := &fakeEventPublisher{}
svc.SetTaskEventPublisher(pub)
if _, err := svc.ArchiveTaskTree(context.Background(), "root", true); err != nil {
t.Fatalf("archive: %v", err)
}
pub.mu.Lock()
pub.updated = nil
pub.archived = nil
pub.mu.Unlock()
if _, err := svc.UnarchiveTaskTree(context.Background(), "root"); err != nil {
t.Fatalf("unarchive: %v", err)
}
pub.mu.Lock()
defer pub.mu.Unlock()
want := map[string]bool{"root": true, "c1": true}
for i, id := range pub.updated {
if pub.archived[i] {
t.Errorf("task %s published while still archived — event must carry archived_at=null", id)
}
delete(want, id)
}
if len(want) > 0 {
t.Errorf("missing PublishTaskUpdated for: %v", want)
}
}
@@ -371,6 +371,10 @@ func (r *phase4TaskRepo) ArchiveTaskIfActive(context.Context, string, string) (b
func (r *phase4TaskRepo) UnarchiveTaskByCascade(context.Context, string, string) (bool, error) {
return false, nil
}
func (r *phase4TaskRepo) UnarchiveTask(context.Context, string) (bool, error) {
r.panicNotUsed("UnarchiveTask")
return false, nil
}
func (r *phase4TaskRepo) ListTasksForAutoArchive(context.Context) ([]*models.Task, error) {
r.panicNotUsed("ListTasksForAutoArchive")
return nil, nil
@@ -0,0 +1,142 @@
package service
import (
"context"
"go.uber.org/zap"
"github.com/kandev/kandev/internal/events"
"github.com/kandev/kandev/internal/task/models"
"github.com/kandev/kandev/internal/worktree"
)
// BranchRecovery reports, after an unarchive, whether a repo's prior
// worktree branch still exists somewhere and can be picked back up by the
// next session launch. Status values are worktree.BranchStatus*.
type BranchRecovery struct {
TaskID string `json:"task_id"`
RepositoryID string `json:"repository_id"`
Branch string `json:"branch"`
Status string `json:"status"`
}
// BranchStatusProber reports where a worktree branch still exists.
// Implemented by *worktree.Manager (BranchRecoveryStatus).
type BranchStatusProber interface {
BranchRecoveryStatus(ctx context.Context, repoPath, branch string) string
}
// RecoverTaskBranches inspects the task's historical worktree records
// (archive keeps the rows and deletes only the local branch + directory)
// and, per repository, probes whether the branch still exists locally or
// on origin. When it does and the task_repositories row has no
// checkout_branch yet, the branch is written back as checkout_branch so a
// brand-new session checks the old work back out instead of minting a
// fresh branch. Best-effort: failures are logged and reported as
// status=missing rather than blocking the unarchive.
func (s *Service) RecoverTaskBranches(ctx context.Context, taskID string) []BranchRecovery {
provider, okProvider := s.worktreeCleanup.(WorktreeProvider)
prober, okProber := s.worktreeCleanup.(BranchStatusProber)
if !okProvider || !okProber {
return nil
}
worktrees, err := provider.GetAllByTaskID(ctx, taskID)
if err != nil {
s.logger.Warn("branch recovery: failed to list worktrees",
zap.String("task_id", taskID), zap.Error(err))
return nil
}
latest := latestWorktreePerRepo(worktrees)
if len(latest) == 0 {
return nil
}
reposByID := s.taskRepositoriesByRepoID(ctx, taskID)
out := make([]BranchRecovery, 0, len(latest))
restored := false
for _, wt := range latest {
status := prober.BranchRecoveryStatus(ctx, wt.RepositoryPath, wt.Branch)
if status != worktree.BranchStatusMissing {
restored = s.restoreCheckoutBranch(ctx, reposByID[wt.RepositoryID], wt.Branch) || restored
}
out = append(out, BranchRecovery{
TaskID: taskID,
RepositoryID: wt.RepositoryID,
Branch: wt.Branch,
Status: status,
})
}
// checkout_branch rides along on task events (taskRepositoriesForEvent),
// so a successful restore must re-publish task.updated — the unarchive
// event already went out with the pre-restore repository rows. Mirrors
// the UpdateRepositoryBaseBranch flow.
if restored {
if task, err := s.tasks.GetTask(ctx, taskID); err == nil && task != nil {
s.publishTaskEvent(ctx, events.TaskUpdated, task, nil)
}
}
return out
}
// latestWorktreePerRepo picks the most recently created worktree record
// per repository. Multiple sessions leave multiple records; the newest
// branch is the one the user last worked on.
func latestWorktreePerRepo(worktrees []*worktree.Worktree) map[string]*worktree.Worktree {
latest := make(map[string]*worktree.Worktree)
for _, wt := range worktrees {
if wt == nil || wt.Branch == "" || wt.RepositoryPath == "" {
continue
}
cur, ok := latest[wt.RepositoryID]
if !ok || wt.CreatedAt.After(cur.CreatedAt) {
latest[wt.RepositoryID] = wt
}
}
return latest
}
func (s *Service) taskRepositoriesByRepoID(ctx context.Context, taskID string) map[string]*models.TaskRepository {
byID := map[string]*models.TaskRepository{}
taskRepos, err := s.taskRepos.ListTaskRepositories(ctx, taskID)
if err != nil {
s.logger.Warn("branch recovery: failed to list task repositories",
zap.String("task_id", taskID), zap.Error(err))
return byID
}
rowsPerRepo := map[string]int{}
for _, tr := range taskRepos {
rowsPerRepo[tr.RepositoryID]++
}
for _, tr := range taskRepos {
// Multi-branch tasks keep one task_repositories row per branch
// (add_branch flow). Restoring the newest worktree branch into an
// arbitrary sibling row could clobber another branch's identity, so
// leave multi-row repos alone — session resume still recovers those
// via the per-worktree records.
if rowsPerRepo[tr.RepositoryID] > 1 {
continue
}
byID[tr.RepositoryID] = tr
}
return byID
}
// restoreCheckoutBranch writes the recovered branch back as the task
// repository's checkout_branch so the next session launch checks it out
// (executor CheckoutBranch flow) instead of creating a new branch. An
// already-set checkout_branch (e.g. a PR head) is never overwritten.
// Returns whether the row was updated.
func (s *Service) restoreCheckoutBranch(ctx context.Context, tr *models.TaskRepository, branch string) bool {
if tr == nil || tr.CheckoutBranch != "" || branch == "" {
return false
}
tr.CheckoutBranch = branch
if err := s.taskRepos.UpdateTaskRepository(ctx, tr); err != nil {
s.logger.Warn("branch recovery: failed to restore checkout_branch",
zap.String("task_id", tr.TaskID),
zap.String("repository_id", tr.RepositoryID),
zap.String("branch", branch),
zap.Error(err))
return false
}
return true
}
@@ -0,0 +1,165 @@
package service
import (
"context"
"testing"
"time"
"github.com/kandev/kandev/internal/events"
"github.com/kandev/kandev/internal/task/models"
"github.com/kandev/kandev/internal/task/repository"
"github.com/kandev/kandev/internal/worktree"
)
// stubWorktreeRecovery implements WorktreeProvider + BranchStatusProber.
type stubWorktreeRecovery struct {
worktrees []*worktree.Worktree
statuses map[string]string // branch → status
}
func (s *stubWorktreeRecovery) OnTaskDeleted(context.Context, string) error { return nil }
func (s *stubWorktreeRecovery) GetAllByTaskID(context.Context, string) ([]*worktree.Worktree, error) {
return s.worktrees, nil
}
func (s *stubWorktreeRecovery) BranchRecoveryStatus(_ context.Context, _, branch string) string {
return s.statuses[branch]
}
// stubTaskRepoRepo overrides just the two methods RecoverTaskBranches uses.
type stubTaskRepoRepo struct {
repository.TaskRepoRepository
repos []*models.TaskRepository
updated []*models.TaskRepository
}
func (s *stubTaskRepoRepo) ListTaskRepositories(context.Context, string) ([]*models.TaskRepository, error) {
return s.repos, nil
}
func (s *stubTaskRepoRepo) UpdateTaskRepository(_ context.Context, tr *models.TaskRepository) error {
s.updated = append(s.updated, tr)
return nil
}
func recoveryTestService(t *testing.T, wt *stubWorktreeRecovery, repos *stubTaskRepoRepo) (*Service, *MockEventBus) {
t.Helper()
svc, eventBus, _ := createTestService(t)
svc.SetWorktreeCleanup(wt)
svc.taskRepos = repos
return svc, eventBus
}
func TestRecoverTaskBranches_RestoresCheckoutBranchWhenBranchSurvives(t *testing.T) {
wt := &stubWorktreeRecovery{
worktrees: []*worktree.Worktree{{
RepositoryID: "repo-1",
RepositoryPath: "/repos/one",
Branch: "feature/old-work",
}},
statuses: map[string]string{"feature/old-work": worktree.BranchStatusRemote},
}
repos := &stubTaskRepoRepo{
repos: []*models.TaskRepository{{TaskID: "task-1", RepositoryID: "repo-1"}},
}
svc, eventBus := recoveryTestService(t, wt, repos)
if err := svc.tasks.CreateTask(context.Background(), &models.Task{
ID: "task-1", WorkspaceID: "ws-1", WorkflowID: "wf-1", WorkflowStepID: "step-1", Title: "t",
}); err != nil {
t.Fatalf("seed task: %v", err)
}
eventBus.ClearEvents()
out := svc.RecoverTaskBranches(context.Background(), "task-1")
if len(out) != 1 {
t.Fatalf("recovery entries = %d, want 1", len(out))
}
if out[0].Status != worktree.BranchStatusRemote || out[0].Branch != "feature/old-work" {
t.Errorf("recovery = %+v, want remote feature/old-work", out[0])
}
if len(repos.updated) != 1 || repos.updated[0].CheckoutBranch != "feature/old-work" {
t.Fatalf("checkout_branch not restored: updated = %+v", repos.updated)
}
// checkout_branch rides on task events — a successful restore must
// re-publish task.updated so WS clients pick up the repository change.
published := eventBus.GetPublishedEvents()
found := false
for _, ev := range published {
if ev.Type == events.TaskUpdated {
found = true
}
}
if !found {
t.Errorf("expected a %s event after checkout_branch restore, got %d events", events.TaskUpdated, len(published))
}
}
func TestRecoverTaskBranches_MissingBranchReportsWithoutUpdate(t *testing.T) {
wt := &stubWorktreeRecovery{
worktrees: []*worktree.Worktree{{
RepositoryID: "repo-1",
RepositoryPath: "/repos/one",
Branch: "feature/never-pushed",
}},
statuses: map[string]string{"feature/never-pushed": worktree.BranchStatusMissing},
}
repos := &stubTaskRepoRepo{
repos: []*models.TaskRepository{{TaskID: "task-1", RepositoryID: "repo-1"}},
}
svc, _ := recoveryTestService(t, wt, repos)
out := svc.RecoverTaskBranches(context.Background(), "task-1")
if len(out) != 1 || out[0].Status != worktree.BranchStatusMissing {
t.Fatalf("recovery = %+v, want single missing entry", out)
}
if len(repos.updated) != 0 {
t.Errorf("checkout_branch must not be written for a missing branch: %+v", repos.updated)
}
}
func TestRecoverTaskBranches_NeverOverwritesExistingCheckoutBranch(t *testing.T) {
wt := &stubWorktreeRecovery{
worktrees: []*worktree.Worktree{{
RepositoryID: "repo-1",
RepositoryPath: "/repos/one",
Branch: "feature/old-work",
}},
statuses: map[string]string{"feature/old-work": worktree.BranchStatusLocal},
}
repos := &stubTaskRepoRepo{
repos: []*models.TaskRepository{{
TaskID: "task-1", RepositoryID: "repo-1", CheckoutBranch: "pr-head-branch",
}},
}
svc, _ := recoveryTestService(t, wt, repos)
svc.RecoverTaskBranches(context.Background(), "task-1")
if len(repos.updated) != 0 {
t.Errorf("existing checkout_branch (PR head) must not be overwritten: %+v", repos.updated)
}
}
func TestRecoverTaskBranches_PicksNewestWorktreePerRepo(t *testing.T) {
old := time.Now().Add(-2 * time.Hour)
recent := time.Now().Add(-time.Minute)
wt := &stubWorktreeRecovery{
worktrees: []*worktree.Worktree{
{RepositoryID: "repo-1", RepositoryPath: "/repos/one", Branch: "feature/first-session", CreatedAt: old},
{RepositoryID: "repo-1", RepositoryPath: "/repos/one", Branch: "feature/latest-session", CreatedAt: recent},
},
statuses: map[string]string{
"feature/first-session": worktree.BranchStatusLocal,
"feature/latest-session": worktree.BranchStatusLocal,
},
}
repos := &stubTaskRepoRepo{
repos: []*models.TaskRepository{{TaskID: "task-1", RepositoryID: "repo-1"}},
}
svc, _ := recoveryTestService(t, wt, repos)
out := svc.RecoverTaskBranches(context.Background(), "task-1")
if len(out) != 1 || out[0].Branch != "feature/latest-session" {
t.Fatalf("recovery = %+v, want single entry for the newest branch", out)
}
if len(repos.updated) != 1 || repos.updated[0].CheckoutBranch != "feature/latest-session" {
t.Fatalf("checkout_branch = %+v, want feature/latest-session", repos.updated)
}
}
+20
View File
@@ -58,6 +58,12 @@ var (
// used as a directory segment.
ErrInvalidRepoName = errors.New("repo name has no usable characters after sanitization")
// ErrBranchUnrecoverable is returned by recreate when the worktree's
// branch no longer exists locally (archive deletes it via `git branch
// -D`) and could not be fetched from origin either. Callers can treat
// this as "prior work is gone" and fall back to a fresh worktree.
ErrBranchUnrecoverable = errors.New("worktree branch no longer exists locally or on origin")
// ErrInvalidBranchSlug is returned when BranchSlug is set but contains no
// usable characters after sanitization. Callers that pass an explicit slug
// must populate something the filesystem can accept.
@@ -89,6 +95,20 @@ func isFetchRefusedCheckedOut(output string) bool {
return strings.Contains(strings.ToLower(output), "refusing to fetch into branch")
}
// isRemoteRefMissingError reports whether a fetch error indicates the
// requested ref genuinely does not exist on the remote (or there is no
// usable remote at all), as opposed to a transient network/auth failure
// where the branch may still exist and a retry could succeed.
func isRemoteRefMissingError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "couldn't find remote ref") ||
strings.Contains(msg, "does not appear to be a git repository") ||
strings.Contains(msg, "no such remote")
}
// ClassifyGitError wraps a raw git error with a user-friendly sentinel error
// based on the command output.
func ClassifyGitError(output string, _ error) error {
@@ -91,6 +91,33 @@ func (m *Manager) checkoutBranchExistsAnywhere(ctx context.Context, repoPath, br
return remote
}
// Branch recovery statuses reported by BranchRecoveryStatus.
const (
BranchStatusLocal = "local"
BranchStatusRemote = "remote"
BranchStatusMissing = "missing"
)
// BranchRecoveryStatus reports where a worktree branch still exists:
// "local" when refs/heads/<branch> resolves, "remote" when only the
// remote-tracking ref refs/remotes/origin/<branch> does, "missing"
// otherwise. Offline-friendly best-effort probe — it inspects local refs
// only (no network), so a remote-tracking ref that was deleted upstream
// but not yet pruned still reports "remote"; the recreate-time fetch is
// the authoritative check.
func (m *Manager) BranchRecoveryStatus(ctx context.Context, repoPath, branch string) string {
if repoPath == "" || branch == "" {
return BranchStatusMissing
}
if exists, err := m.branchExists(ctx, repoPath, "refs/heads/"+branch); err == nil && exists {
return BranchStatusLocal
}
if exists, err := m.branchExists(ctx, repoPath, "refs/remotes/origin/"+branch); err == nil && exists {
return BranchStatusRemote
}
return BranchStatusMissing
}
func (m *Manager) currentBranch(ctx context.Context, repoPath string) string {
// Same Acquire-then-build-execCtx ordering as branchExists.
release, err := subproc.Git().Acquire(ctx)
@@ -857,6 +857,34 @@ func (m *Manager) recreate(ctx context.Context, existing *Worktree, req CreateRe
return nil, fmt.Errorf("cannot recreate worktree: existing record has no path")
}
// Archive deletes the local branch (removeWorktree runs `git branch -D`),
// so a recreate after unarchive must restore it first. fetchBranchToLocal
// fetches origin <branch>:<branch> — or pull/<N>/head for fork PRs, whose
// head branch never exists on origin by name — and only errors when the
// branch exists neither locally nor on the remote.
exists, probeErr := m.branchExists(ctx, req.RepositoryPath, existing.Branch)
if probeErr != nil {
// "Could not tell" (timeout / fs stall) is not "missing" — reporting
// ErrBranchUnrecoverable here would misclassify recoverable work as
// gone. Propagate so the caller can retry the recreate.
return nil, fmt.Errorf("cannot verify worktree branch %q: %w", existing.Branch, probeErr)
}
if !exists {
if _, fetchErr := m.fetchBranchToLocal(ctx, req.RepositoryPath, existing.Branch, req.PRNumber); fetchErr != nil {
m.logger.Warn("failed to restore worktree branch during recreate",
zap.String("worktree_id", existing.ID),
zap.String("branch", existing.Branch),
zap.Error(fetchErr))
// Only a confirmed-missing remote ref means the work is gone;
// transient fetch failures (network, auth) keep their own error
// so callers don't treat a reachable branch as unrecoverable.
if isRemoteRefMissingError(fetchErr) {
return nil, fmt.Errorf("%w: %q", ErrBranchUnrecoverable, existing.Branch)
}
return nil, fetchErr
}
}
// Try to add worktree using existing branch
usesGitCrypt, err := m.gitAddWorktreeForRecreate(ctx, req.RepositoryPath, existing.Branch, worktreePath)
if err != nil {
@@ -0,0 +1,160 @@
package worktree
import (
"context"
"errors"
"path/filepath"
"strings"
"testing"
)
// archiveDeletesLocalBranch simulates what task archive does to a worktree's
// branch: the local ref is deleted (`git branch -D`), while origin and the
// remote-tracking ref are left alone.
func archiveDeletesLocalBranch(t *testing.T, repoPath, branch string) {
t.Helper()
runGit(t, repoPath, "branch", "-D", branch)
}
func newRecreateTestManager(t *testing.T) *Manager {
t.Helper()
mgr, err := NewManager(newTestConfig(t), newMockStore(), newTestLogger())
if err != nil {
t.Fatalf("NewManager failed: %v", err)
}
return mgr
}
// TestRecreate_FetchesBranchFromOriginWhenLocalDeleted is the
// unarchive-recovery path: archive deleted the local branch and the worktree
// directory, but the branch was pushed. recreate must fetch it back from
// origin and rebuild the worktree at the recorded path.
func TestRecreate_FetchesBranchFromOriginWhenLocalDeleted(t *testing.T) {
repoPath := initGitRepoWithRemote(t)
branchSHA := strings.TrimSpace(runGit(t, repoPath, "rev-parse", "feature/pr-branch"))
archiveDeletesLocalBranch(t, repoPath, "feature/pr-branch")
mgr := newRecreateTestManager(t)
existing := &Worktree{
ID: "wt-1",
SessionID: "session-1",
TaskID: "task-1",
RepositoryID: "repo-1",
RepositoryPath: repoPath,
Path: filepath.Join(t.TempDir(), "task-1", "repo-1"),
Branch: "feature/pr-branch",
Status: StatusDeleted,
}
wt, err := mgr.recreate(context.Background(), existing, CreateRequest{
SessionID: "session-1",
TaskID: "task-1",
RepositoryID: "repo-1",
RepositoryPath: repoPath,
})
if err != nil {
t.Fatalf("recreate() should fetch the branch from origin, got: %v", err)
}
if wt.Status != StatusActive {
t.Errorf("status = %q, want %q", wt.Status, StatusActive)
}
gotSHA := strings.TrimSpace(runGit(t, wt.Path, "rev-parse", "HEAD"))
if gotSHA != branchSHA {
t.Errorf("worktree HEAD = %q, want %q (pushed branch tip)", gotSHA, branchSHA)
}
}
// TestRecreate_BranchGoneEverywhereReturnsUnrecoverable pins the degraded
// path: local branch deleted AND the branch never made it to origin (or was
// deleted there too). recreate must return ErrBranchUnrecoverable so callers
// can fall back to a fresh worktree instead of failing opaquely.
func TestRecreate_BranchGoneEverywhereReturnsUnrecoverable(t *testing.T) {
repoPath := initGitRepoWithRemote(t)
// Delete the branch everywhere: on origin, locally, and prune the
// remote-tracking ref so no trace remains.
runGit(t, repoPath, "push", "origin", "--delete", "feature/pr-branch")
archiveDeletesLocalBranch(t, repoPath, "feature/pr-branch")
runGit(t, repoPath, "fetch", "--prune", "origin")
mgr := newRecreateTestManager(t)
existing := &Worktree{
ID: "wt-2",
SessionID: "session-2",
TaskID: "task-2",
RepositoryID: "repo-1",
RepositoryPath: repoPath,
Path: filepath.Join(t.TempDir(), "task-2", "repo-1"),
Branch: "feature/pr-branch",
Status: StatusDeleted,
}
_, err := mgr.recreate(context.Background(), existing, CreateRequest{
SessionID: "session-2",
TaskID: "task-2",
RepositoryID: "repo-1",
RepositoryPath: repoPath,
})
if !errors.Is(err, ErrBranchUnrecoverable) {
t.Fatalf("recreate() err = %v, want ErrBranchUnrecoverable", err)
}
}
// TestBranchRecoveryStatus covers the three probe outcomes used by the
// unarchive HTTP response: local, remote (only the remote-tracking ref
// remains after archive deleted the local branch), and missing.
func TestBranchRecoveryStatus(t *testing.T) {
repoPath := initGitRepoWithRemote(t)
mgr := newRecreateTestManager(t)
ctx := context.Background()
if got := mgr.BranchRecoveryStatus(ctx, repoPath, "feature/pr-branch"); got != BranchStatusLocal {
t.Errorf("status with local branch = %q, want %q", got, BranchStatusLocal)
}
archiveDeletesLocalBranch(t, repoPath, "feature/pr-branch")
if got := mgr.BranchRecoveryStatus(ctx, repoPath, "feature/pr-branch"); got != BranchStatusRemote {
t.Errorf("status after local delete = %q, want %q", got, BranchStatusRemote)
}
if got := mgr.BranchRecoveryStatus(ctx, repoPath, "feature/never-existed"); got != BranchStatusMissing {
t.Errorf("status for unknown branch = %q, want %q", got, BranchStatusMissing)
}
if got := mgr.BranchRecoveryStatus(ctx, "", "feature/pr-branch"); got != BranchStatusMissing {
t.Errorf("status with empty repo path = %q, want %q", got, BranchStatusMissing)
}
}
// TestRecreate_ForkPRFetchesPullHeadRef covers fork-PR tasks: the head
// branch never exists on origin by name, only under refs/pull/<N>/head.
// recreate must forward req.PRNumber so fetchBranchToLocal uses the pull
// refspec instead of failing with ErrBranchUnrecoverable.
func TestRecreate_ForkPRFetchesPullHeadRef(t *testing.T) {
repoPath, prHeadSHA := initGitRepoWithPullRef(t, 974, "feature/fork-pr")
mgr := newRecreateTestManager(t)
existing := &Worktree{
ID: "wt-3",
SessionID: "session-3",
TaskID: "task-3",
RepositoryID: "repo-1",
RepositoryPath: repoPath,
Path: filepath.Join(t.TempDir(), "task-3", "repo-1"),
Branch: "feature/fork-pr",
Status: StatusDeleted,
}
wt, err := mgr.recreate(context.Background(), existing, CreateRequest{
SessionID: "session-3",
TaskID: "task-3",
RepositoryID: "repo-1",
RepositoryPath: repoPath,
PRNumber: 974,
})
if err != nil {
t.Fatalf("recreate() should fetch the fork PR head via pull/<N>/head, got: %v", err)
}
gotSHA := strings.TrimSpace(runGit(t, wt.Path, "rev-parse", "HEAD"))
if gotSHA != prHeadSHA {
t.Errorf("worktree HEAD = %q, want %q (PR head)", gotSHA, prHeadSHA)
}
}
+59 -1
View File
@@ -8,7 +8,7 @@ import { Checkbox } from "@kandev/ui/checkbox";
import { Label } from "@kandev/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { IconArchive, IconLoader, IconTrash } from "@tabler/icons-react";
import { IconArchive, IconArchiveOff, IconLoader, IconTrash } from "@tabler/icons-react";
import { TaskArchiveConfirmDialog } from "@/components/task/task-archive-confirm-dialog";
import { TaskDeleteConfirmDialog } from "@/components/task/task-delete-confirm-dialog";
import { primaryTaskRepository, type Repository, type Task, type Workflow } from "@/lib/types/http";
@@ -42,6 +42,7 @@ export type TasksListViewProps = {
handleRowClick: (task: Task) => void;
deletingTaskId: string | null;
handleArchive: (taskId: string, opts?: { cascade?: boolean }) => Promise<void>;
handleUnarchive: (taskId: string) => Promise<void>;
handleDelete: (taskId: string, opts?: { cascade?: boolean }) => Promise<void>;
};
@@ -63,6 +64,7 @@ export function TasksListView({
handleRowClick,
deletingTaskId,
handleArchive,
handleUnarchive,
handleDelete,
}: TasksListViewProps) {
return (
@@ -84,6 +86,7 @@ export function TasksListView({
isLoading={isLoading}
deletingTaskId={deletingTaskId}
onArchive={handleArchive}
onUnarchive={handleUnarchive}
onDelete={handleDelete}
onRowClick={handleRowClick}
/>
@@ -193,6 +196,7 @@ function TaskRows({
isLoading,
deletingTaskId,
onArchive,
onUnarchive,
onDelete,
onRowClick,
}: {
@@ -203,6 +207,7 @@ function TaskRows({
isLoading: boolean;
deletingTaskId: string | null;
onArchive: (taskId: string, opts?: { cascade?: boolean }) => Promise<void>;
onUnarchive: (taskId: string) => Promise<void>;
onDelete: (taskId: string, opts?: { cascade?: boolean }) => Promise<void>;
onRowClick: (task: Task) => void;
}) {
@@ -236,6 +241,7 @@ function TaskRows({
section={section}
deletingTaskId={deletingTaskId}
onArchive={onArchive}
onUnarchive={onUnarchive}
onDelete={onDelete}
onRowClick={onRowClick}
/>
@@ -356,6 +362,7 @@ function TaskListRow({
level,
deletingTaskId,
onArchive,
onUnarchive,
onDelete,
onRowClick,
}: {
@@ -363,6 +370,7 @@ function TaskListRow({
level: number;
deletingTaskId: string | null;
onArchive: (taskId: string, opts?: { cascade?: boolean }) => Promise<void>;
onUnarchive: (taskId: string) => Promise<void>;
onDelete: (taskId: string, opts?: { cascade?: boolean }) => Promise<void>;
onRowClick: (task: Task) => void;
}) {
@@ -418,6 +426,7 @@ function TaskListRow({
onDeleteOpenChange={setShowDeleteConfirm}
onArchiveOpenChange={setShowArchiveConfirm}
onArchive={onArchive}
onUnarchive={onUnarchive}
onDelete={onDelete}
/>
</div>
@@ -429,12 +438,14 @@ function TaskListSectionView({
section,
deletingTaskId,
onArchive,
onUnarchive,
onDelete,
onRowClick,
}: {
section: TaskListSection;
deletingTaskId: string | null;
onArchive: (taskId: string, opts?: { cascade?: boolean }) => Promise<void>;
onUnarchive: (taskId: string) => Promise<void>;
onDelete: (taskId: string, opts?: { cascade?: boolean }) => Promise<void>;
onRowClick: (task: Task) => void;
}) {
@@ -455,6 +466,7 @@ function TaskListSectionView({
level={level}
deletingTaskId={deletingTaskId}
onArchive={onArchive}
onUnarchive={onUnarchive}
onDelete={onDelete}
onRowClick={onRowClick}
/>
@@ -464,6 +476,49 @@ function TaskListSectionView({
);
}
// Holds its own in-flight state so rapid clicks can't fire duplicate
// unarchive POSTs (each producing a toast + refetch).
function UnarchiveRowAction({
taskId,
onUnarchive,
}: {
taskId: string;
onUnarchive: (taskId: string) => Promise<void>;
}) {
const [isPending, setIsPending] = useState(false);
return (
<Tooltip>
<TooltipTrigger asChild>
<span tabIndex={isPending ? 0 : -1} className="inline-flex">
<Button
variant="ghost"
size="icon"
className="h-9 w-9 cursor-pointer"
data-testid="tasks-list-unarchive"
disabled={isPending}
onClick={async () => {
setIsPending(true);
try {
await onUnarchive(taskId);
} finally {
setIsPending(false);
}
}}
>
{isPending ? (
<IconLoader className="h-4 w-4 animate-spin" />
) : (
<IconArchiveOff className="h-4 w-4 text-muted-foreground" />
)}
<span className="sr-only">Unarchive task</span>
</Button>
</span>
</TooltipTrigger>
<TooltipContent>Unarchive</TooltipContent>
</Tooltip>
);
}
function TaskRowActions({
task,
isArchived,
@@ -473,6 +528,7 @@ function TaskRowActions({
onDeleteOpenChange,
onArchiveOpenChange,
onArchive,
onUnarchive,
onDelete,
}: {
task: Task;
@@ -483,6 +539,7 @@ function TaskRowActions({
onDeleteOpenChange: (open: boolean) => void;
onArchiveOpenChange: (open: boolean) => void;
onArchive: (taskId: string, opts?: { cascade?: boolean }) => Promise<void>;
onUnarchive: (taskId: string) => Promise<void>;
onDelete: (taskId: string, opts?: { cascade?: boolean }) => Promise<void>;
}) {
return (
@@ -503,6 +560,7 @@ function TaskRowActions({
<TooltipContent>Archive</TooltipContent>
</Tooltip>
)}
{isArchived && <UnarchiveRowAction taskId={task.id} onUnarchive={onUnarchive} />}
<Tooltip>
<TooltipTrigger asChild>
<span tabIndex={isDeleting ? 0 : -1} className="inline-flex">
+42 -6
View File
@@ -3,7 +3,13 @@
import { useState, useCallback, useMemo, useEffect, useRef } from "react";
import { useRouter, useSearchParams } from "@/lib/routing/client-router";
import type { PaginationState } from "@tanstack/react-table";
import { archiveTask, deleteTask, listTasksByWorkspace, updateUserSettings } from "@/lib/api";
import {
archiveTask,
deleteTask,
listTasksByWorkspace,
unarchiveTask,
updateUserSettings,
} from "@/lib/api";
import { KanbanHeader } from "@/components/kanban/kanban-header";
import { MobileSearchBar } from "@/components/kanban/mobile-search-bar";
import type { Task, Workspace, Workflow, Repository } from "@/lib/types/http";
@@ -13,6 +19,7 @@ import { useKanbanDisplaySettings } from "@/hooks/use-kanban-display-settings";
import { useDebounce } from "@/hooks/use-debounce";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import { linkToTask } from "@/lib/links";
import { unarchiveToastPayload } from "@/lib/tasks/unarchive-feedback";
import { shouldSkipInitialTasksFetch } from "./tasks-page-fetch-policy";
import { TasksListView } from "./tasks-list-view";
import {
@@ -82,7 +89,6 @@ function useTaskOperations({
}: UseTaskOperationsParams) {
const { toast } = useToast();
const [isLoading, setIsLoading] = useState(false);
const [deletingTaskId, setDeletingTaskId] = useState<string | null>(null);
const { beginRequest, isCurrentRequest } = useLatestWorkspaceRequest(activeWorkspaceId);
const fetchTasks = useCallback(async () => {
@@ -107,7 +113,7 @@ function useTaskOperations({
if (!shouldCommit()) return;
toast({
title: "Failed to load tasks",
description: err instanceof Error ? err.message : "Unknown error",
description: errorDescription(err),
variant: "error",
});
} finally {
@@ -129,6 +135,18 @@ function useTaskOperations({
setTotal,
]);
const mutations = useTaskMutations(fetchTasks);
return { isLoading, fetchTasks, ...mutations };
}
function errorDescription(err: unknown): string {
return err instanceof Error ? err.message : "Unknown error";
}
function useTaskMutations(fetchTasks: () => void) {
const { toast } = useToast();
const [deletingTaskId, setDeletingTaskId] = useState<string | null>(null);
const handleArchive = useCallback(
async (taskId: string, opts?: { cascade?: boolean }) => {
try {
@@ -138,7 +156,24 @@ function useTaskOperations({
} catch (err) {
toast({
title: "Failed to archive task",
description: err instanceof Error ? err.message : "Unknown error",
description: errorDescription(err),
variant: "error",
});
}
},
[fetchTasks, toast],
);
const handleUnarchive = useCallback(
async (taskId: string) => {
try {
const result = await unarchiveTask(taskId);
toast(unarchiveToastPayload(result));
fetchTasks();
} catch (err) {
toast({
title: "Failed to unarchive task",
description: errorDescription(err),
variant: "error",
});
}
@@ -155,7 +190,7 @@ function useTaskOperations({
} catch (err) {
toast({
title: "Failed to delete task",
description: err instanceof Error ? err.message : "Unknown error",
description: errorDescription(err),
variant: "error",
});
} finally {
@@ -165,7 +200,7 @@ function useTaskOperations({
[fetchTasks, toast],
);
return { isLoading, deletingTaskId, fetchTasks, handleArchive, handleDelete };
return { deletingTaskId, handleArchive, handleUnarchive, handleDelete };
}
function useTasksPageViewState({
@@ -498,6 +533,7 @@ export function TasksPageClient(props: TasksPageClientProps) {
handleRowClick={s.handleRowClick}
deletingTaskId={s.deletingTaskId}
handleArchive={s.handleArchive}
handleUnarchive={s.handleUnarchive}
handleDelete={s.handleDelete}
/>
</div>
@@ -17,6 +17,7 @@ import { useJiraAvailable } from "@/hooks/domains/jira/use-jira-availability";
import { useLinearAvailable } from "@/hooks/domains/linear/use-linear-availability";
import { PortForwardButton } from "@/components/task/port-forward-dialog";
import { ExecutorSettingsButton } from "@/components/task/executor-settings-button";
import { TaskUnarchiveButton } from "@/components/task/task-unarchive-button";
import { WorkflowStepper, type WorkflowStepperStep } from "@/components/task/workflow-stepper";
import { TopbarMetrics } from "@/components/system-metrics/topbar-metrics";
import { isDebugUI } from "@/lib/config";
@@ -362,6 +363,11 @@ function TopBarRight({
return (
<div className="flex items-center justify-self-end gap-2 [&_button]:whitespace-nowrap">
<TopbarMetrics activeSessionId={activeSessionId} />
{isArchived && (
<TopbarCluster label="Unarchive task" className="[&_button]:h-7 [&_button]:text-xs">
<TaskUnarchiveButton taskId={taskId} />
</TopbarCluster>
)}
{officeTaskHref && (
<TopbarCluster label="Open in office view" className="[&_a]:h-7 [&_a]:text-xs">
<Button asChild size="sm" variant="outline" className="h-7 cursor-pointer px-2">
@@ -0,0 +1,51 @@
"use client";
import { useState } from "react";
import { IconArchiveOff, IconLoader } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { unarchiveTask } from "@/lib/api";
import { unarchiveToastPayload } from "@/lib/tasks/unarchive-feedback";
import { useToast } from "@/components/toast-provider";
// Shown in the task top bar when the task is archived. On success the
// backend publishes task.updated with archived_at=null, which restores the
// task in the kanban/store — no manual refetch needed here.
export function TaskUnarchiveButton({ taskId }: { taskId?: string | null }) {
const { toast } = useToast();
const [isPending, setIsPending] = useState(false);
if (!taskId) return null;
const handleClick = async () => {
setIsPending(true);
try {
const result = await unarchiveTask(taskId);
toast(unarchiveToastPayload(result));
} catch (err) {
toast({
title: "Failed to unarchive task",
description: err instanceof Error ? err.message : "Unknown error",
variant: "error",
});
} finally {
setIsPending(false);
}
};
return (
<Button
size="sm"
variant="outline"
className="h-7 cursor-pointer px-2"
disabled={isPending}
onClick={handleClick}
data-testid="task-unarchive-button"
>
{isPending ? (
<IconLoader className="h-3.5 w-3.5 animate-spin" />
) : (
<IconArchiveOff className="h-3.5 w-3.5" />
)}
Unarchive
</Button>
);
}
+23
View File
@@ -190,6 +190,29 @@ export async function archiveTask(
});
}
export type BranchRecovery = {
task_id: string;
repository_id: string;
branch: string;
status: "local" | "remote" | "missing";
};
export type UnarchiveTaskResponse = {
success: boolean;
cascade_id: string;
unarchived_ids: string[];
skipped_ids: string[];
affected_group_ids: string[];
recovery: BranchRecovery[];
};
export async function unarchiveTask(taskId: string, options?: ApiRequestOptions) {
return fetchJson<UnarchiveTaskResponse>(`/api/v1/tasks/${taskId}/unarchive`, {
...options,
init: { method: "POST", ...(options?.init ?? {}) },
});
}
export async function getSubtaskCount(taskId: string, options?: ApiRequestOptions) {
return fetchJson<{ count: number }>(`/api/v1/tasks/${taskId}/subtask-count`, options);
}
@@ -0,0 +1,58 @@
import { describe, expect, it } from "vitest";
import type { UnarchiveTaskResponse } from "@/lib/api/domains/kanban-api";
import { unarchiveToastPayload } from "./unarchive-feedback";
function response(recovery: UnarchiveTaskResponse["recovery"]): UnarchiveTaskResponse {
return {
success: true,
cascade_id: "",
unarchived_ids: ["t1"],
skipped_ids: [],
affected_group_ids: [],
recovery,
};
}
describe("unarchiveToastPayload", () => {
it("reports success when every branch is recoverable", () => {
const payload = unarchiveToastPayload(
response([{ task_id: "t1", repository_id: "r1", branch: "feat/x", status: "remote" }]),
);
expect(payload.variant).toBe("success");
expect(payload.description).toBe("The task has been restored.");
});
it("reports success when there is no recovery info at all", () => {
const payload = unarchiveToastPayload(response([]));
expect(payload.variant).toBe("success");
});
it("warns with the branch names when a branch is unrecoverable", () => {
const payload = unarchiveToastPayload(
response([
{ task_id: "t1", repository_id: "r1", branch: "feat/gone", status: "missing" },
{ task_id: "t1", repository_id: "r2", branch: "feat/ok", status: "local" },
]),
);
expect(payload.variant).toBeUndefined();
expect(payload.description).toContain("feat/gone");
expect(payload.description).not.toContain("feat/ok");
});
it("pluralizes when multiple branches are unrecoverable", () => {
const payload = unarchiveToastPayload(
response([
{ task_id: "t1", repository_id: "r1", branch: "feat/one", status: "missing" },
{ task_id: "t1", repository_id: "r2", branch: "feat/two", status: "missing" },
]),
);
expect(payload.description).toContain("Branches feat/one, feat/two no longer exist");
});
it("tolerates a response without a recovery field", () => {
const payload = unarchiveToastPayload(
response(undefined as unknown as UnarchiveTaskResponse["recovery"]),
);
expect(payload.variant).toBe("success");
});
});
+28
View File
@@ -0,0 +1,28 @@
import type { UnarchiveTaskResponse } from "@/lib/api/domains/kanban-api";
export type UnarchiveToastPayload = {
title: string;
description: string;
variant?: "success";
};
// Builds the toast shown after a successful unarchive. When the archived
// branch no longer exists anywhere (never pushed, local copy deleted by
// archive), the prior work is unrecoverable and the user must be told the
// next session starts fresh.
export function unarchiveToastPayload(result: UnarchiveTaskResponse): UnarchiveToastPayload {
const missing = (result.recovery ?? []).filter((r) => r.status === "missing");
if (missing.length > 0) {
const branches = missing.map((r) => r.branch).join(", ");
const plural = missing.length > 1;
return {
title: "Task unarchived",
description: `${plural ? "Branches" : "Branch"} ${branches} no longer ${plural ? "exist" : "exists"} locally or on the remote — the next session starts fresh from the base branch.`,
};
}
return {
title: "Task unarchived",
description: "The task has been restored.",
variant: "success",
};
}
@@ -0,0 +1,110 @@
import { describe, expect, it, vi } from "vitest";
import type { StoreApi } from "zustand";
import type { AppState } from "@/lib/state/store";
import { registerTasksHandlers } from "./tasks";
vi.mock("@/lib/recent-tasks", () => ({
removeRecentTask: vi.fn(),
}));
type Listener = (state: AppState) => void;
const TASK_ID = "t1";
function makeStore(initial: Partial<AppState> = {}) {
let state = {
kanban: { workflowId: "wf1", steps: [], tasks: [] },
kanbanMulti: { snapshots: {}, isLoading: false },
tasks: {
activeTaskId: null,
activeSessionId: null,
pinnedSessionId: null,
lastSessionByTaskId: {},
},
taskSessionsByTask: { itemsByTaskId: {}, loadedByTaskId: {}, loadingByTaskId: {} },
environmentIdBySessionId: {},
setActiveSessionAuto: vi.fn(),
removeTaskFromSidebarPrefs: vi.fn(),
setTaskDeletedNotification: vi.fn(),
setOfficeRefetchTrigger: vi.fn(),
...initial,
} as unknown as AppState;
const listeners = new Set<Listener>();
return {
getState: () => state,
setState: (updater: AppState | ((s: AppState) => AppState)) => {
const next =
typeof updater === "function" ? (updater as (s: AppState) => AppState)(state) : updater;
state = { ...state, ...next };
for (const listener of listeners) listener(state);
},
subscribe: (listener: Listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
},
destroy: vi.fn(),
getInitialState: vi.fn(),
} as unknown as StoreApi<AppState> & { getState: () => AppState };
}
function makeUpdatedMessage(payload: Record<string, unknown>) {
return {
id: "msg-1",
type: "notification" as const,
action: "task.updated" as const,
payload,
} as Parameters<NonNullable<ReturnType<typeof registerTasksHandlers>["task.updated"]>>[0];
}
// Unarchive is delivered as task.updated with archived_at back to null. The
// handler must re-add the task to the kanban caches (mirror of the archive
// removal path).
describe("task.updated unarchive restore", () => {
it("re-adds the task to the active kanban when archived_at clears", () => {
const store = makeStore();
const handlers = registerTasksHandlers(store);
handlers["task.updated"]!(
makeUpdatedMessage({
task_id: TASK_ID,
workflow_id: "wf1",
workflow_step_id: "step1",
title: "Restored task",
state: "TODO",
is_ephemeral: false,
archived_at: null,
}),
);
const state = store.getState();
expect(state.kanban.tasks.map((t) => t.id)).toContain(TASK_ID);
});
it("re-adds the task to a multi-kanban snapshot when archived_at clears", () => {
const store = makeStore({
kanban: { workflowId: "wf-other", steps: [], tasks: [] } as unknown as AppState["kanban"],
kanbanMulti: {
isLoading: false,
snapshots: {
wf1: { workflowId: "wf1", workflowName: "WF1", steps: [], tasks: [] },
},
} as unknown as AppState["kanbanMulti"],
});
const handlers = registerTasksHandlers(store);
handlers["task.updated"]!(
makeUpdatedMessage({
task_id: TASK_ID,
workflow_id: "wf1",
workflow_step_id: "step1",
title: "Restored task",
state: "TODO",
is_ephemeral: false,
archived_at: null,
}),
);
const state = store.getState();
expect(state.kanbanMulti.snapshots.wf1.tasks.map((t) => t.id)).toContain(TASK_ID);
});
});