feat(agents): add explicit branch recovery for resumed sessions (#3216)

This commit is contained in:
Carlos Florêncio
2026-08-31 21:52:46 +00:00
committed by GitHub
parent f13a4533de
commit 4e3dc91607
73 changed files with 5208 additions and 430 deletions
+6 -4
View File
@@ -17,10 +17,12 @@ Start from intent and evidence: read the spec/task first when available, then ch
### Architecture discussion gate
For a large architectural change, require a linked issue with maintainer
discussion before the PR opens. If the issue or discussion is missing, report a
blocker. Prefer one logical change and a small diff because this limits risk and
maintainer burden.
For a large architectural change, verify the authenticated actor's repository
permission before the PR opens. Maintainers and collaborators with `push`,
`maintain`, or `admin` permission may proceed without a linked issue. For an
actor without write access, require a linked issue with maintainer discussion;
if the issue or discussion is missing, report a blocker. Prefer one logical
change and a small diff because this limits risk and maintainer burden.
## Available skills
+11 -5
View File
@@ -71,11 +71,17 @@ explicitly requests task tracking.
when the user explicitly requests separate PRs. Use `--draft` if requested,
otherwise create as ready-for-review.
**Architecture and scope gate:** Before running any PR creation command, check
large changes for a linked issue with maintainer discussion. If it is missing,
stop and report the blocker. Do not open a PR to start the discussion. Prefer
one logical change and the smallest practical diff; split unrelated cleanup,
refactoring, and feature work into separate PRs.
**Architecture and scope gate:** Before running any PR creation command, verify
the authenticated actor's repository permission. On GitHub, query
`gh api repos/{owner}/{repo}/collaborators/{login}/permission`; `push`,
`maintain`, and `admin` permissions are write-authorized, so those actors may
open large or architectural PRs directly. On other hosts, use the equivalent
repository permission check. For an actor without write access, require a
linked issue with maintainer discussion before opening a large or architectural
PR. If that issue or discussion is missing, stop and report the blocker. Do not
open a PR to start the discussion. Prefer one logical change and the smallest
practical diff; split unrelated cleanup, refactoring, and feature work into
separate PRs.
**PR title** must follow Conventional Commits format (see `/commit` for full rules). CI validates via `pr-title.yml` — the PR title becomes the squash-merge commit used for release notes.
+3 -3
View File
@@ -15,10 +15,10 @@ LANGUAGE
Keep the surrounding explanation in English.
ARCHITECTURE AND SCOPE
If the change is large or architectural, require a linked issue with maintainer discussion before opening the PR.
For contributors without repository write access, if the change is large or architectural, require a linked issue with maintainer discussion before opening the PR. Maintainers and collaborators with `push`, `maintain`, or `admin` permission may open the PR directly; verify the authenticated actor's repository permission before applying this gate.
Large changes include new subsystems, public API or protocol changes, persistence changes, new execution boundaries,
authentication or permission-model changes, and cross-cutting changes across subsystems.
If the issue or discussion is missing, stop and report the blocker. Do not open a PR to start the discussion.
If a non-write contributor is missing the issue or discussion, stop and report the blocker. Do not open a PR to start the discussion.
Prefer one logical change and the smallest practical diff. Split unrelated cleanup, refactoring, and feature work.
IMPORTANT CHANGES (optional)
@@ -65,7 +65,7 @@ RULES
## Checklist
- [ ] If this is a large architectural change, I discussed the direction in a linked issue before opening this PR.
- [ ] If I do not have repository write access and this is a large architectural change, I discussed the direction in a linked issue before opening this PR.
- [ ] This PR contains one logical change; unrelated work is split into separate PRs.
- [ ] I have performed a self-review of my code.
- [ ] I have manually tested my changes and they work as expected.
@@ -82,6 +82,9 @@ type RepoPrepareSpec struct {
// environment. It forbids worktree creation/recreation and all repository
// mutating setup paths.
WorkspaceReuseRequired bool
// AllowBranchReplacement is set only for the explicit user recovery action.
// It permits a missing persisted branch to be replaced with a fresh branch.
AllowBranchReplacement bool
WorktreeBranch string
WorktreeBranchPrefix string
WorktreeBranchTemplate string
@@ -133,6 +136,9 @@ type EnvPrepareRequest struct {
// in this request. RepoPrepareSpec carries the same value so multi-repo
// callers can retain it while requests are split.
WorkspaceReuseRequired bool
// AllowBranchReplacement permits the explicit new-branch recovery action to
// materialize a replacement while retaining the environment record.
AllowBranchReplacement bool
WorktreeBranchPrefix string
WorktreeBranchTemplate string
@@ -185,6 +191,7 @@ func (r *EnvPrepareRequest) RepoSpecs() []RepoPrepareSpec {
RemoteContribution: r.RemoteContribution,
WorktreeID: r.WorktreeID,
WorkspaceReuseRequired: r.WorkspaceReuseRequired,
AllowBranchReplacement: r.AllowBranchReplacement,
WorktreeBranch: r.WorktreeBranch,
WorktreeBranchPrefix: r.WorktreeBranchPrefix,
WorktreeBranchTemplate: r.WorktreeBranchTemplate,
@@ -306,7 +306,8 @@ func buildWorktreeCreateRequest(req *EnvPrepareRequest) worktree.CreateRequest {
RefreshRepositoryWithState: req.RefreshRepositoryWithState,
RemoteRefState: req.RemoteRefState,
WorktreeID: req.WorktreeID,
ReuseRequired: req.WorkspaceReuseRequired,
ReuseRequired: req.WorkspaceReuseRequired && !req.AllowBranchReplacement,
AllowBranchReplacement: req.AllowBranchReplacement,
TaskDirName: req.TaskDirName,
RepoName: req.RepoName,
BranchSlug: req.BranchSlug,
@@ -532,6 +533,7 @@ func (p *WorktreePreparer) prepareOneRepo(
subReq.ContributionDestination = spec.ContributionDestination
subReq.WorktreeID = spec.WorktreeID
subReq.WorkspaceReuseRequired = req.WorkspaceReuseRequired || spec.WorkspaceReuseRequired
subReq.AllowBranchReplacement = req.AllowBranchReplacement || spec.AllowBranchReplacement
subReq.WorktreeBranchPrefix = spec.WorktreeBranchPrefix
subReq.WorktreeBranchTemplate = spec.WorktreeBranchTemplate
subReq.WorktreeBranchTicket = spec.WorktreeBranchTicket
@@ -23,3 +23,21 @@ func TestBuildWorktreeCreateRequestForwardsProfileEnv(t *testing.T) {
t.Fatalf("CreateRequest.ScriptEnv = %#v, want profile env forwarded", got.ScriptEnv)
}
}
func TestBuildWorktreeCreateRequestAllowsExplicitBranchReplacement(t *testing.T) {
req := &EnvPrepareRequest{
WorkspaceReuseRequired: true,
AllowBranchReplacement: true,
RepositoryID: "repo-1",
RepositoryPath: "/repo",
}
got := buildWorktreeCreateRequest(req)
if !got.AllowBranchReplacement {
t.Fatal("CreateRequest.AllowBranchReplacement = false, want true")
}
if got.ReuseRequired {
t.Fatal("explicit branch replacement must not use attach-only ReuseRequired")
}
}
@@ -602,6 +602,13 @@ func (m *Manager) launchResolveWorkspacePath(ctx context.Context, req *LaunchReq
return
}
func shouldPrepareEnvironment(req *LaunchRequest) bool {
if req == nil || req.ACPSessionID == "" {
return true
}
return req.UseWorktree && req.RepositoryPath != ""
}
// resolveScratchWorkspace creates and returns the scratch workspace path for a
// repo-less task. Returns empty string when the path could not be created.
func (m *Manager) resolveScratchWorkspace(ctx context.Context, req *LaunchRequest) string {
@@ -1028,6 +1035,7 @@ func buildEnvPrepareRequest(req *LaunchRequest, workspacePath string, execName e
TaskRepositoryID: req.TaskRepositoryID,
UseWorktree: req.UseWorktree,
WorkspaceReuseRequired: req.WorkspaceReuseRequired,
AllowBranchReplacement: req.AllowBranchReplacement,
WorktreeID: req.WorktreeID,
SetupScript: req.SetupScript,
RepoSetupScript: repoSetupScript,
@@ -1073,6 +1081,7 @@ func buildEnvPrepareRequest(req *LaunchRequest, workspacePath string, execName e
PRNumber: r.PRNumber,
RemoteContribution: r.RemoteContribution,
WorktreeID: r.WorktreeID,
AllowBranchReplacement: req.AllowBranchReplacement || r.AllowBranchReplacement,
WorktreeBranchPrefix: r.WorktreeBranchPrefix,
WorktreeBranchTemplate: r.WorktreeBranchTemplate,
WorktreeBranchTicket: r.WorktreeBranchTicket,
@@ -1391,9 +1400,11 @@ func (m *Manager) launchInternal(ctx context.Context, req *LaunchRequest) (*Agen
reqWithWorktree.EnvironmentFinalized = true
// 4b. Run environment preparation (if preparer registered for this executor type).
// Skip on resume (ACPSessionID set) — workspace was already prepared during initial launch.
// Native ACP resume normally reuses the already-prepared workspace, but a
// worktree resume must re-enter preparation so a missing branch can be
// reported and an explicit replacement action can materialize it.
var prepResult *EnvPrepareResult
if req.ACPSessionID == "" {
if shouldPrepareEnvironment(req) {
prepResult = m.runEnvironmentPreparerWithProgress(ctx, &reqWithWorktree, workspacePath, progressRecorder.Callback(0))
} else {
m.logger.Debug("skipping environment preparation for resumed session",
@@ -1419,7 +1430,7 @@ func (m *Manager) launchInternal(ctx context.Context, req *LaunchRequest) (*Agen
// 7. Build runtime request and create instance (agent not started yet)
var runtimeProgress PrepareProgressCallback
if req.ACPSessionID == "" {
if shouldPrepareEnvironment(req) {
runtimeProgress = progressRecorder.Callback(progressRecorder.Len())
}
execReq, execInstance, rt, err := m.launchBuildExecutorRequest(ctx, executionID, &reqWithWorktree, agentConfig, profileInfo, mainRepoGitDir, worktreeID, worktreeBranch, runtimeProgress)
@@ -765,17 +765,20 @@ func (ae *AgentExecution) EndSessionSpan() {
// the top level. When LaunchRequest.Repositories is set, each entry produces
// one prepared worktree under the shared TaskDirName.
type RepoLaunchSpec struct {
TaskRepositoryID string
RepositoryID string
RepositoryPath string
RepositoryURL string // Clone URL for remote executors that need to clone
RepoName string // Repository name used as subdirectory inside TaskDirName
BaseBranch string
DefaultBranch string // Repository's default_branch, used as fallback when BaseBranch is missing
CheckoutBranch string
PRNumber int // GitHub PR number when CheckoutBranch is a PR head; enables refs/pull/<N>/head fetch for fork PRs.
RemoteContribution *models.RemoteContribution
WorktreeID string // Existing worktree ID to reuse (skip creation if set)
TaskRepositoryID string
RepositoryID string
RepositoryPath string
RepositoryURL string // Clone URL for remote executors that need to clone
RepoName string // Repository name used as subdirectory inside TaskDirName
BaseBranch string
DefaultBranch string // Repository's default_branch, used as fallback when BaseBranch is missing
CheckoutBranch string
PRNumber int // GitHub PR number when CheckoutBranch is a PR head; enables refs/pull/<N>/head fetch for fork PRs.
RemoteContribution *models.RemoteContribution
WorktreeID string // Existing worktree ID to reuse (skip creation if set)
// AllowBranchReplacement permits the explicit new-branch recovery action for
// this repository while retaining its environment record.
AllowBranchReplacement bool
WorktreeBranchPrefix string
WorktreeBranchTemplate string
WorktreeBranchTicket string
@@ -849,6 +852,9 @@ type LaunchRequest struct {
TaskEnvironmentID string // Env this session belongs to (shared across sessions in same task)
// WorkspaceReuseRequired selects attach-only environment preparation.
WorkspaceReuseRequired bool
// AllowBranchReplacement is an explicit user-selected recovery permission.
// Normal resume leaves it false so a missing branch remains a visible error.
AllowBranchReplacement bool
TaskTitle string // Human-readable task title for semantic worktree naming
// AgentProfileID is the stable Office identity for routed Office launches.
// For non-Office launches it is also the concrete execution profile.
@@ -977,6 +983,7 @@ func (r *LaunchRequest) RepoSpecs() []RepoLaunchSpec {
ComparisonTarget: r.ComparisonTarget,
ContributionDestination: r.ContributionDestination,
WorktreeID: r.WorktreeID,
AllowBranchReplacement: r.AllowBranchReplacement,
WorktreeBranchPrefix: r.WorktreeBranchPrefix,
WorktreeBranchTemplate: r.WorktreeBranchTemplate,
WorktreeBranchTicket: r.WorktreeBranchTicket,
@@ -224,6 +224,7 @@ func buildLifecycleLaunchRequest(
SessionID: req.SessionID,
TaskEnvironmentID: req.TaskEnvironmentID,
WorkspaceReuseRequired: req.WorkspaceReuseRequired,
AllowBranchReplacement: req.AllowBranchReplacement,
TaskTitle: req.TaskTitle,
AgentProfileID: officeProfileID,
ExecutionProfileID: req.AgentProfileID,
@@ -326,6 +327,7 @@ func lifecycleRepoLaunchSpecs(repos []executor.RepoSpec) []lifecycle.RepoLaunchS
ContributionDestination: r.ContributionDestination,
ComparisonTarget: r.ComparisonTarget,
WorktreeID: r.WorktreeID,
AllowBranchReplacement: r.AllowBranchReplacement,
WorktreeBranchPrefix: r.WorktreeBranchPrefix,
WorktreeBranchTemplate: r.WorktreeBranchTemplate,
WorktreeBranchTicket: r.WorktreeBranchTicket,
@@ -371,6 +371,9 @@ type LaunchAgentRequest struct {
// WorkspaceReuseRequired selects attach-only preparation of an already-ready
// task environment. It must never be inferred from a sibling execution ID.
WorkspaceReuseRequired bool
// AllowBranchReplacement is granted only by the explicit new-branch recovery
// action. It permits lifecycle to replace a confirmed missing worktree branch.
AllowBranchReplacement bool
TaskTitle string // Human-readable task title for semantic worktree naming
AgentProfileID string
TurnID string // Durable Kandev turn for the initial prompt, when present
@@ -489,11 +492,13 @@ type RepoSpec struct {
ContributionDestination *models.ContributionDestination
ComparisonTarget *models.ComparisonTarget
WorktreeID string
WorktreeBranchPrefix string
WorktreeBranchTemplate string
WorktreeBranchTicket string
PullBeforeWorktree bool
RemoteSyncHandled bool
// AllowBranchReplacement permits explicit branch replacement for this repo.
AllowBranchReplacement bool
WorktreeBranchPrefix string
WorktreeBranchTemplate string
WorktreeBranchTicket string
PullBeforeWorktree bool
RemoteSyncHandled bool
// RefreshRepository is an optional provider-authenticated refresh deferred
// until worktree materialization. A valid reusable worktree bypasses it.
RefreshRepository func(context.Context) error
@@ -738,9 +738,37 @@ func buildPrepareResultMetadata(result *lifecycle.EnvPrepareResult) map[string]i
return lifecycle.SerializePrepareResult(result)
}
// ResumeOptions controls explicit recovery behavior for a session resume.
// Branch replacement is intentionally opt-in; ordinary resume preserves the
// original worktree branch and reports when it is unrecoverable.
type ResumeOptions struct {
AllowBranchReplacement bool
}
// ResumeSession restarts an existing task session using its stored worktree.
// When startAgent is false, only the executor runtime is started (agent process is not launched).
func (e *Executor) ResumeSession(ctx context.Context, session *models.TaskSession, startAgent bool) (*TaskExecution, error) {
return e.resumeSession(ctx, session, startAgent, ResumeOptions{})
}
// ResumeSessionWithOptions restarts an existing task session with an explicit
// recovery permission. It keeps the same session and provider resume identity.
func (e *Executor) ResumeSessionWithOptions(
ctx context.Context,
session *models.TaskSession,
startAgent bool,
options ResumeOptions,
) (*TaskExecution, error) {
return e.resumeSession(ctx, session, startAgent, options)
}
//nolint:cyclop,gocognit,funlen // Resume coordinates the established launch, rollback, and stale-execution recovery sequence.
func (e *Executor) resumeSession(
ctx context.Context,
session *models.TaskSession,
startAgent bool,
options ResumeOptions,
) (*TaskExecution, error) {
if session != nil {
resumeSnapshot := *session
resumeSnapshot.Metadata = cloneMetadata(session.Metadata)
@@ -778,8 +806,8 @@ func (e *Executor) ResumeSession(ctx context.Context, session *models.TaskSessio
return nil
}
}
req, _, execCfg, existingEnv, _, err := e.buildResumeRequestAtCredentialBoundary(
ctx, task, session, startAgent, beforeCredentialLease,
req, _, execCfg, existingEnv, _, err := e.buildResumeRequestAtCredentialBoundaryWithOptions(
ctx, task, session, startAgent, beforeCredentialLease, options,
)
if err != nil {
if resumeStatePersisted {
@@ -1085,7 +1113,7 @@ func (e *Executor) validateAndLockResume(ctx context.Context, session *models.Ta
// repository details, worktree settings, and ACP resume token.
// Returns the request, repository ID, executor config, existing ExecutorRunning record (may be nil), and error.
func (e *Executor) buildResumeRequest(ctx context.Context, task *v1.Task, session *models.TaskSession, startAgent bool) (*LaunchAgentRequest, string, executorConfig, *models.TaskEnvironment, *models.ExecutorRunning, error) {
return e.buildResumeRequestAtCredentialBoundary(ctx, task, session, startAgent, nil)
return e.buildResumeRequestAtCredentialBoundaryWithOptions(ctx, task, session, startAgent, nil, ResumeOptions{})
}
// buildResumeRequestAtCredentialBoundary prepares a resume request and invokes
@@ -1099,23 +1127,72 @@ func (e *Executor) buildResumeRequestAtCredentialBoundary(
startAgent bool,
beforeCredentialLease func() error,
) (*LaunchAgentRequest, string, executorConfig, *models.TaskEnvironment, *models.ExecutorRunning, error) {
return e.buildResumeRequestAtCredentialBoundaryWithOptions(
ctx, task, session, startAgent, beforeCredentialLease, ResumeOptions{},
)
}
func (e *Executor) buildResumeRequestAtCredentialBoundaryWithOptions(
ctx context.Context,
task *v1.Task,
session *models.TaskSession,
startAgent bool,
beforeCredentialLease func() error,
options ResumeOptions,
) (*LaunchAgentRequest, string, executorConfig, *models.TaskEnvironment, *models.ExecutorRunning, error) {
req, metadata := newResumeLaunchRequest(task, session, startAgent, options)
execConfig := e.applyExecutorConfigToResumeRequest(ctx, req, task, session, metadata)
repositoryID, existingEnv, allRepos, err := e.prepareResumeRepositorySettings(
ctx, task, session, req,
)
if err != nil {
return nil, "", execConfig, existingEnv, nil, err
}
if err := e.applyResumeMCPSettings(ctx, task.ID, session, req); err != nil {
return nil, "", execConfig, existingEnv, nil, err
}
existingRunning := e.applyRunningRecordToResumeRequest(ctx, req, task, session, startAgent)
if err := e.applyResumeWorkspaceFolders(ctx, task.ID, req); err != nil {
return nil, "", execConfig, existingEnv, existingRunning, err
}
if err := e.configureResumeGitHubCredentials(
ctx, req, session, allRepos, beforeCredentialLease,
); err != nil {
return nil, "", execConfig, existingEnv, existingRunning, err
}
e.injectGitLabWorkspaceCredentials(ctx, req)
if err := e.resolveLaunchEnvironment(ctx, req, execConfig.ProfileEnvVars, allRepos); err != nil {
return nil, "", execConfig, existingEnv, existingRunning, err
}
return req, repositoryID, execConfig, existingEnv, existingRunning, nil
}
func newResumeLaunchRequest(
task *v1.Task,
session *models.TaskSession,
startAgent bool,
options ResumeOptions,
) (*LaunchAgentRequest, map[string]interface{}) {
executionProfileID := session.ExecutionProfileID
if executionProfileID == "" {
executionProfileID = session.AgentProfileID
}
req := &LaunchAgentRequest{
TaskID: task.ID,
WorkspaceID: task.WorkspaceID,
SessionID: session.ID,
TaskTitle: task.Title,
AgentProfileID: executionProfileID,
OfficeAgentProfileID: session.AgentProfileID,
StartAgent: startAgent,
TaskDescription: task.Description,
Priority: task.Priority,
IsEphemeral: task.IsEphemeral,
IsPassthrough: session.IsPassthrough,
TaskEnvironmentID: session.TaskEnvironmentID,
TaskID: task.ID,
WorkspaceID: task.WorkspaceID,
SessionID: session.ID,
TaskTitle: task.Title,
AgentProfileID: executionProfileID,
OfficeAgentProfileID: session.AgentProfileID,
StartAgent: startAgent,
TaskDescription: task.Description,
Priority: task.Priority,
IsEphemeral: task.IsEphemeral,
IsPassthrough: session.IsPassthrough,
TaskEnvironmentID: session.TaskEnvironmentID,
AllowBranchReplacement: options.AllowBranchReplacement,
}
metadata := map[string]interface{}{}
@@ -1131,12 +1208,18 @@ func (e *Executor) buildResumeRequestAtCredentialBoundary(
metadata["worktree_id"] = session.Worktrees[0].WorktreeID
}
req.WorktreeBranchTicket = worktree.TicketForBranchName(task.Identifier, metadata)
return req, metadata
}
execConfig := e.applyExecutorConfigToResumeRequest(ctx, req, task, session, metadata)
func (e *Executor) prepareResumeRepositorySettings(
ctx context.Context,
task *v1.Task,
session *models.TaskSession,
req *LaunchAgentRequest,
) (string, *models.TaskEnvironment, []*repoInfo, error) {
existingEnv, err := e.resolveResumeTaskEnvironment(ctx, task.ID, session)
if err != nil {
return nil, "", execConfig, nil, nil, err
return "", nil, nil, err
}
if session.TaskEnvironmentID != "" {
req.TaskEnvironmentID = session.TaskEnvironmentID
@@ -1150,52 +1233,52 @@ func (e *Executor) buildResumeRequestAtCredentialBoundary(
allRepos, err := e.resolveAllRepoInfoForSession(ctx, task.ID, session.ID)
if err != nil {
return nil, "", execConfig, nil, nil, err
return "", nil, nil, err
}
req.McpProviders = deriveMCPProviders(allRepos)
repositoryID, err := e.applyResumeRepoConfig(ctx, task, session, req, existingEnv, allRepos)
if err != nil {
return nil, "", execConfig, nil, nil, err
}
if len(allRepos) > 0 {
req.PullBeforeWorktree = allRepos[0].PullBeforeWorktree
req.RemoteSyncHandled = allRepos[0].RemoteSyncHandled
req.RefreshRepository = allRepos[0].RefreshRepository
req.RefreshRepositoryWithState = allRepos[0].RefreshRepositoryWithState
req.RemoteRefState = allRepos[0].RemoteRefState
return "", nil, nil, err
}
applyResumeRepositoryFlags(req, allRepos)
if err := e.validateReuseEnvironmentInventory(ctx, req, existingEnv); err != nil {
return nil, "", execConfig, existingEnv, nil, err
return "", existingEnv, nil, err
}
e.reuseExistingEnvironment(ctx, req, existingEnv)
return repositoryID, existingEnv, allRepos, nil
}
req.McpMode, err = e.resolveTaskSessionMCPMode(ctx, task.ID, session, true)
if err != nil {
return nil, "", execConfig, nil, nil, err
func applyResumeRepositoryFlags(req *LaunchAgentRequest, repositories []*repoInfo) {
if len(repositories) == 0 {
return
}
profileContext, err := e.resolveTaskSessionMCPProfile(ctx, task.ID, session, true)
first := repositories[0]
req.PullBeforeWorktree = first.PullBeforeWorktree
req.RemoteSyncHandled = first.RemoteSyncHandled
req.RefreshRepository = first.RefreshRepository
req.RefreshRepositoryWithState = first.RefreshRepositoryWithState
req.RemoteRefState = first.RemoteRefState
}
func (e *Executor) applyResumeMCPSettings(
ctx context.Context,
taskID string,
session *models.TaskSession,
req *LaunchAgentRequest,
) error {
mode, err := e.resolveTaskSessionMCPMode(ctx, taskID, session, true)
if err != nil {
return nil, "", execConfig, nil, nil, err
return err
}
profileContext, err := e.resolveTaskSessionMCPProfile(ctx, taskID, session, true)
if err != nil {
return err
}
req.McpMode = mode
profileContext.Providers = req.McpProviders
req.McpProfile = &profileContext
existingRunning := e.applyRunningRecordToResumeRequest(ctx, req, task, session, startAgent)
if err := e.applyResumeWorkspaceFolders(ctx, task.ID, req); err != nil {
return nil, "", execConfig, existingEnv, nil, err
}
if err := e.configureResumeGitHubCredentials(
ctx, req, session, allRepos, beforeCredentialLease,
); err != nil {
return nil, "", execConfig, existingEnv, existingRunning, err
}
e.injectGitLabWorkspaceCredentials(ctx, req)
if err := e.resolveLaunchEnvironment(ctx, req, execConfig.ProfileEnvVars, allRepos); err != nil {
return nil, "", execConfig, existingEnv, existingRunning, err
}
return req, repositoryID, execConfig, existingEnv, existingRunning, nil
return nil
}
func (e *Executor) applyResumeWorkspaceFolders(
@@ -106,6 +106,31 @@ func setupLiveResumeTestFixture(repo *mockRepository) {
}
}
func TestBuildResumeRequestWithOptions_ForwardsBranchReplacementPermission(t *testing.T) {
repo := newMockRepository()
setupLiveResumeTestFixture(repo)
exec := newTestExecutor(t, &mockAgentManager{}, repo)
req, _, _, _, _, err := exec.buildResumeRequestAtCredentialBoundaryWithOptions(
context.Background(), repo.tasks["task-1"].ToAPI(), repo.sessions["sess-1"], true, nil,
ResumeOptions{AllowBranchReplacement: true},
)
if err != nil {
t.Fatalf("buildResumeRequestWithOptions returned error: %v", err)
}
if !req.AllowBranchReplacement {
t.Fatal("resume request lost explicit branch replacement permission")
}
normalReq, _, _, _, _, err := exec.buildResumeRequest(context.Background(), repo.tasks["task-1"].ToAPI(), repo.sessions["sess-1"], true)
if err != nil {
t.Fatalf("normal buildResumeRequest returned error: %v", err)
}
if normalReq.AllowBranchReplacement {
t.Fatal("normal resume unexpectedly enabled branch replacement")
}
}
type resumeCredentialStateIssuer struct {
repo *mockRepository
observedState models.TaskSessionState
@@ -245,7 +245,15 @@ func (h *Handlers) wsSetPlanMode(ctx context.Context, msg *ws.Message) (*ws.Mess
type wsRecoverSessionRequest struct {
TaskID string `json:"task_id"`
SessionID string `json:"session_id"`
Action string `json:"action"` // "resume", "fresh_start", "runtime_retry", or "cancel_retry"
Action string `json:"action"` // "resume", "resume_new_branch", "fresh_start", "runtime_retry", or "cancel_retry"
}
func branchRecoveryConflictResponse(msg *ws.Message, err error) (*ws.Message, error) {
var branchRecoveryErr *orchestrator.BranchRecoveryError
if !errors.As(err, &branchRecoveryErr) {
return nil, nil
}
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeConflict, err.Error(), branchRecoveryErr.Details())
}
// wsRecoverSession recovers a session by id (resume or fresh start).
@@ -268,12 +276,15 @@ func (h *Handlers) wsRecoverSession(ctx context.Context, msg *ws.Message) (*ws.M
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"cancelled": cancelled})
}
if req.Action != "resume" && req.Action != "fresh_start" && req.Action != "runtime_retry" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "action must be 'resume', 'fresh_start', 'runtime_retry', or 'cancel_retry'", nil)
if req.Action != "resume" && req.Action != "resume_new_branch" && req.Action != "fresh_start" && req.Action != "runtime_retry" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "action must be 'resume', 'resume_new_branch', 'fresh_start', 'runtime_retry', or 'cancel_retry'", nil)
}
resp, err := h.service.RecoverSession(ctx, req.TaskID, req.SessionID, req.Action)
if err != nil {
if recoveryResponse, responseErr := branchRecoveryConflictResponse(msg, err); recoveryResponse != nil || responseErr != nil {
return recoveryResponse, responseErr
}
h.logger.Error("failed to recover session",
zap.String("task_id", req.TaskID),
zap.String("session_id", req.SessionID),
@@ -3,6 +3,7 @@ package handlers
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/kandev/kandev/internal/common/logger"
@@ -38,6 +39,26 @@ func TestWsRecoverSessionCancelRetryReportsServiceResult(t *testing.T) {
require.False(t, payload.Cancelled)
}
func TestBranchRecoveryConflictResponsePreservesRecoveryDetails(t *testing.T) {
msg := createTestMessage(t, ws.ActionSessionRecover, map[string]interface{}{})
err := &orchestrator.BranchRecoveryError{
Cause: errors.New("branch is gone"),
SessionID: "session-1",
RepositoryID: "repo-1",
OriginalBranch: "feature/lost",
BaseBranch: "main",
}
response, responseErr := branchRecoveryConflictResponse(msg, err)
require.NoError(t, responseErr)
require.NotNil(t, response)
payload := parseError(t, response)
require.Equal(t, ws.ErrorCodeConflict, payload.Code)
require.Equal(t, "feature/lost", payload.Details["original_branch"])
require.Equal(t, "main", payload.Details["base_branch"])
require.Equal(t, "resume_new_branch", payload.Details["recovery_action"])
}
func TestWsEnsureSessionRequestParsesAutoStartOverride(t *testing.T) {
tests := []struct {
name string
@@ -0,0 +1,460 @@
package orchestrator
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/kandev/kandev/internal/task/models"
"github.com/kandev/kandev/internal/worktree"
v1 "github.com/kandev/kandev/pkg/api/v1"
"go.uber.org/zap"
)
// BranchRecoveryError identifies a worktree branch that cannot be restored.
// It wraps the original error so callers can still use errors.Is/errors.As.
type BranchRecoveryError struct {
Cause error
SessionID string
RepositoryID string
OriginalBranch string
BaseBranch string
}
func (e *BranchRecoveryError) Error() string {
if e == nil {
return "the worktree branch is no longer available"
}
branch := strings.TrimSpace(e.OriginalBranch)
if branch == "" {
return "the worktree branch is no longer available; continue on a new branch to keep the conversation history"
}
return fmt.Sprintf(
"the worktree branch %q is no longer available; continue on a new branch to keep the conversation history, but code changes from the lost branch cannot be recovered",
branch,
)
}
func (e *BranchRecoveryError) Unwrap() error {
if e == nil {
return nil
}
return e.Cause
}
// Details returns the stable WebSocket recovery contract for this error.
func (e *BranchRecoveryError) Details() map[string]interface{} {
if e == nil {
return nil
}
return map[string]interface{}{
"kind": "branch_unrecoverable",
"recovery_action": "resume_new_branch",
"original_branch": e.OriginalBranch,
"base_branch": e.BaseBranch,
"repository_id": e.RepositoryID,
"session_id": e.SessionID,
}
}
type branchRecoveryRepoSnapshot struct {
RowID string
RepositoryID string
BranchSlug string
WorktreeID string
WorktreeBranch string
BaseBranch string
Position int
}
type branchRecoverySnapshot struct {
TaskID string
SessionID string
EnvironmentID string
Repositories []branchRecoveryRepoSnapshot
}
const (
branchRecoveryWarningKeyPrefix = "branch_recreated_warning:"
branchRecoveryWarningClaimStaleAfter = 5 * time.Minute
)
type branchRecoveryWarningClaim struct {
ClaimedAt time.Time `json:"claimed_at"`
}
type branchRecoveryStore interface {
ListTaskRepositories(ctx context.Context, taskID string) ([]*models.TaskRepository, error)
ListTaskEnvironmentRepos(ctx context.Context, envID string) ([]*models.TaskEnvironmentRepo, error)
}
func (s *Service) captureBranchRecoverySnapshot(
ctx context.Context,
taskID, sessionID string,
) (*branchRecoverySnapshot, error) {
store, env, err := s.loadBranchRecoverySnapshotContext(ctx, taskID, sessionID)
if err != nil {
return nil, err
}
snapshot := &branchRecoverySnapshot{
TaskID: taskID,
SessionID: sessionID,
}
if env == nil {
return snapshot, nil
}
rows, err := s.branchRecoveryEnvironmentRepos(ctx, store, env)
if err != nil {
return nil, err
}
baseBranches, err := s.branchRecoveryBaseBranches(ctx, store, taskID)
if err != nil {
return nil, err
}
snapshot.EnvironmentID = env.ID
snapshot.Repositories = branchRecoveryRepoSnapshots(rows, baseBranches)
return snapshot, nil
}
func (s *Service) loadBranchRecoverySnapshotContext(
ctx context.Context,
taskID, sessionID string,
) (branchRecoveryStore, *models.TaskEnvironment, error) {
if s.repo == nil {
return nil, nil, fmt.Errorf("repository is not configured")
}
store, ok := s.repo.(branchRecoveryStore)
if !ok {
return nil, nil, fmt.Errorf("repository does not support branch recovery snapshots")
}
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
return nil, nil, fmt.Errorf("load session for branch recovery: %w", err)
}
if session == nil {
return nil, nil, fmt.Errorf("session %q was not found", sessionID)
}
env, err := s.repo.GetTaskEnvironmentByTaskID(ctx, taskID)
if err != nil {
return nil, nil, fmt.Errorf("load task environment for branch recovery: %w", err)
}
if env == nil && session.TaskEnvironmentID != "" {
env, err = s.repo.GetTaskEnvironment(ctx, session.TaskEnvironmentID)
if err != nil {
return nil, nil, fmt.Errorf("load session environment for branch recovery: %w", err)
}
}
return store, env, nil
}
func (s *Service) branchRecoveryEnvironmentRepos(
ctx context.Context,
store branchRecoveryStore,
env *models.TaskEnvironment,
) ([]*models.TaskEnvironmentRepo, error) {
if len(env.Repos) > 0 {
return env.Repos, nil
}
rows, err := store.ListTaskEnvironmentRepos(ctx, env.ID)
if err != nil {
return nil, fmt.Errorf("load environment repositories for branch recovery: %w", err)
}
return rows, nil
}
func (s *Service) branchRecoveryBaseBranches(
ctx context.Context,
store branchRecoveryStore,
taskID string,
) (map[string]string, error) {
taskRepos, err := store.ListTaskRepositories(ctx, taskID)
if err != nil {
return nil, fmt.Errorf("load task repositories for branch recovery: %w", err)
}
baseBranches := make(map[string]string, len(taskRepos))
for _, taskRepo := range taskRepos {
if taskRepo != nil && taskRepo.RepositoryID != "" {
baseBranches[taskRepo.RepositoryID] = taskRepo.BaseBranch
}
}
return baseBranches, nil
}
func branchRecoveryRepoSnapshots(
rows []*models.TaskEnvironmentRepo,
baseBranches map[string]string,
) []branchRecoveryRepoSnapshot {
snapshots := make([]branchRecoveryRepoSnapshot, 0, len(rows))
for _, row := range rows {
if row == nil || row.WorktreeID == "" || row.WorktreeBranch == "" {
continue
}
snapshots = append(snapshots, branchRecoveryRepoSnapshot{
RowID: row.ID,
RepositoryID: row.RepositoryID,
BranchSlug: row.BranchSlug,
WorktreeID: row.WorktreeID,
WorktreeBranch: row.WorktreeBranch,
BaseBranch: baseBranches[row.RepositoryID],
Position: row.Position,
})
}
return snapshots
}
func (s *Service) branchRecoveryError(ctx context.Context, taskID, sessionID string, cause error) error {
if cause == nil || !errors.Is(cause, worktree.ErrBranchUnrecoverable) {
return cause
}
var existing *BranchRecoveryError
if errors.As(cause, &existing) {
return cause
}
originalBranch := ""
var branchErr *worktree.BranchUnrecoverableError
if errors.As(cause, &branchErr) {
originalBranch = branchErr.BranchName()
}
snapshot, snapshotErr := s.captureBranchRecoverySnapshot(ctx, taskID, sessionID)
if snapshotErr != nil {
snapshot = nil
}
repositoryID, baseBranch := branchRecoveryContext(snapshot, originalBranch)
return &BranchRecoveryError{
Cause: cause,
SessionID: sessionID,
RepositoryID: repositoryID,
OriginalBranch: originalBranch,
BaseBranch: baseBranch,
}
}
func branchRecoveryContext(snapshot *branchRecoverySnapshot, originalBranch string) (string, string) {
if snapshot == nil {
return "", ""
}
for _, repo := range snapshot.Repositories {
if repo.WorktreeBranch == originalBranch {
return repo.RepositoryID, repo.BaseBranch
}
}
if len(snapshot.Repositories) == 1 {
return snapshot.Repositories[0].RepositoryID, snapshot.Repositories[0].BaseBranch
}
return "", ""
}
func (s *Service) persistBranchRecoveryWarnings(
ctx context.Context,
taskID, sessionID string,
before *branchRecoverySnapshot,
) {
if before == nil || len(before.Repositories) == 0 || s.messageCreator == nil {
return
}
after, err := s.captureBranchRecoverySnapshot(ctx, taskID, sessionID)
if err != nil {
s.logger.Warn("failed to inspect branch recovery result", zapFieldsBranchRecovery(taskID, sessionID, err)...)
return
}
for _, previous := range before.Repositories {
current, found := findBranchRecoveryRepo(after, previous)
if !found || current.WorktreeBranch == "" || current.WorktreeBranch == previous.WorktreeBranch || previous.WorktreeBranch == "" {
continue
}
s.persistBranchRecoveryWarning(ctx, taskID, sessionID, previous, current)
}
}
func findBranchRecoveryRepo(snapshot *branchRecoverySnapshot, previous branchRecoveryRepoSnapshot) (branchRecoveryRepoSnapshot, bool) {
if snapshot == nil {
return branchRecoveryRepoSnapshot{}, false
}
for _, current := range snapshot.Repositories {
if previous.RowID != "" && current.RowID == previous.RowID {
return current, true
}
if current.RepositoryID == previous.RepositoryID && current.BranchSlug == previous.BranchSlug && current.Position == previous.Position {
return current, true
}
}
return branchRecoveryRepoSnapshot{}, false
}
func (s *Service) persistBranchRecoveryWarning(
ctx context.Context,
taskID, sessionID string,
previous, current branchRecoveryRepoSnapshot,
) {
decisionID := branchRecoveryDecisionID(taskID, sessionID, previous.RepositoryID, previous.WorktreeBranch, current.WorktreeBranch, current.BaseBranch)
key := branchRecoveryWarningKeyPrefix + decisionID
release, claimed := s.claimBranchRecoveryWarning(ctx, sessionID, key)
if !claimed {
return
}
metadata := map[string]interface{}{
"variant": "warning",
"kind": "branch_recreated",
"original_branch": previous.WorktreeBranch,
"new_branch": current.WorktreeBranch,
"base_branch": current.BaseBranch,
"session_id": sessionID,
"repository_id": current.RepositoryID,
"decision_id": decisionID,
}
err := s.messageCreator.CreateSessionMessage(
context.WithoutCancel(ctx),
taskID,
"branch_recreated",
sessionID,
string(v1.MessageTypeStatus),
s.getActiveTurnID(sessionID),
metadata,
false,
)
if err != nil {
release()
s.logger.Warn("failed to persist branch recovery warning", zapFieldsBranchRecovery(taskID, sessionID, err)...)
}
}
func (s *Service) claimBranchRecoveryWarning(ctx context.Context, sessionID, key string) (func(), bool) {
if s.repo == nil {
return func() {}, false
}
claimCtx := context.WithoutCancel(ctx)
if claimer, ok := s.repo.(failedSessionMetadataClaimer); ok {
return s.claimBranchRecoveryWarningWithState(claimCtx, sessionID, key, claimer)
}
return s.claimBranchRecoveryWarningWithoutState(claimCtx, sessionID, key)
}
func (s *Service) claimBranchRecoveryWarningWithState(
ctx context.Context,
sessionID, key string,
claimer failedSessionMetadataClaimer,
) (func(), bool) {
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil || session == nil {
return func() {}, false
}
claim := branchRecoveryWarningClaim{ClaimedAt: time.Now().UTC()}
claimed, err := claimer.SetSessionMetadataKeyIfAbsentIfState(ctx, sessionID, key, claim, session.State)
if err != nil {
return func() {}, false
}
if !claimed {
session, claimed = s.reclaimBranchRecoveryWarningClaim(ctx, sessionID, key, session.State)
if claimed {
claimed, err = claimer.SetSessionMetadataKeyIfAbsentIfState(ctx, sessionID, key, claim, session.State)
}
}
if err != nil || !claimed {
return func() {}, false
}
return func() {
s.releaseBranchRecoveryWarningClaim(ctx, sessionID, key, session.State)
}, true
}
func (s *Service) claimBranchRecoveryWarningWithoutState(ctx context.Context, sessionID, key string) (func(), bool) {
claimed, err := s.repo.SetSessionMetadataKeyIfAbsent(
ctx, sessionID, key, branchRecoveryWarningClaim{ClaimedAt: time.Now().UTC()},
)
return func() {}, err == nil && claimed
}
func (s *Service) reclaimBranchRecoveryWarningClaim(
ctx context.Context,
sessionID, key string,
expectedState models.TaskSessionState,
) (*models.TaskSession, bool) {
if !s.reclaimStaleBranchRecoveryWarningClaim(ctx, sessionID, key, expectedState) {
return nil, false
}
session, err := s.repo.GetTaskSession(ctx, sessionID)
return session, err == nil && session != nil
}
func (s *Service) releaseBranchRecoveryWarningClaim(ctx context.Context, sessionID, key string, expectedState models.TaskSessionState) {
releaser, ok := s.repo.(failedSessionMetadataClaimReleaser)
if !ok {
return
}
_, _ = releaser.RemoveSessionMetadataKeyIfState(ctx, sessionID, key, expectedState)
}
// reclaimStaleBranchRecoveryWarningClaim releases a timestamped claim left by
// a crashed process. A matching persisted warning wins over reclamation so a
// crash after message insertion cannot cause a duplicate warning.
func (s *Service) reclaimStaleBranchRecoveryWarningClaim(
ctx context.Context,
sessionID, key string,
expectedState models.TaskSessionState,
) bool {
releaser, ok := s.repo.(failedSessionMetadataClaimReleaser)
if !ok {
return false
}
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil || session == nil || session.State != expectedState || session.Metadata == nil {
return false
}
claim, ok := branchRecoveryWarningClaimFromMetadata(session.Metadata[key])
if !ok || time.Since(claim.ClaimedAt) < branchRecoveryWarningClaimStaleAfter {
return false
}
decisionID := strings.TrimPrefix(key, branchRecoveryWarningKeyPrefix)
if decisionID == "" || decisionID == key {
return false
}
messages, err := s.repo.ListMessages(ctx, sessionID)
if err != nil || branchRecoveryWarningMessageExists(messages, decisionID) {
return false
}
removed, err := releaser.RemoveSessionMetadataKeyIfState(ctx, sessionID, key, session.State)
return err == nil && removed
}
func branchRecoveryWarningClaimFromMetadata(value interface{}) (branchRecoveryWarningClaim, bool) {
data, err := json.Marshal(value)
if err != nil {
return branchRecoveryWarningClaim{}, false
}
var claim branchRecoveryWarningClaim
if err := json.Unmarshal(data, &claim); err != nil || claim.ClaimedAt.IsZero() {
return branchRecoveryWarningClaim{}, false
}
return claim, true
}
func branchRecoveryWarningMessageExists(messages []*models.Message, decisionID string) bool {
for _, message := range messages {
if message == nil || message.Metadata == nil {
continue
}
if message.Metadata["kind"] != "branch_recreated" || message.Metadata["decision_id"] != decisionID {
continue
}
return true
}
return false
}
func branchRecoveryDecisionID(parts ...string) string {
sum := sha256.Sum256([]byte(strings.Join(parts, "\x00")))
return fmt.Sprintf("branch-recreated-%x", sum[:12])
}
func zapFieldsBranchRecovery(taskID, sessionID string, err error) []zap.Field {
return []zap.Field{
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.Error(err),
}
}
@@ -0,0 +1,199 @@
package orchestrator
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/kandev/kandev/internal/task/models"
"github.com/kandev/kandev/internal/worktree"
v1 "github.com/kandev/kandev/pkg/api/v1"
"github.com/stretchr/testify/require"
)
func TestBranchRecoveryErrorPreservesTypedCauseAndDetails(t *testing.T) {
cause := fmt.Errorf("restore worktree: %w", &worktree.BranchUnrecoverableError{Branch: "feature/lost"})
service := &Service{}
err := service.branchRecoveryError(context.Background(), "task-1", "session-1", cause)
var recoveryErr *BranchRecoveryError
require.ErrorAs(t, err, &recoveryErr)
require.ErrorIs(t, err, worktree.ErrBranchUnrecoverable)
require.Equal(t, "session-1", recoveryErr.SessionID)
require.Equal(t, "feature/lost", recoveryErr.OriginalBranch)
require.Equal(t, map[string]interface{}{
"kind": "branch_unrecoverable",
"recovery_action": "resume_new_branch",
"original_branch": "feature/lost",
"base_branch": "",
"repository_id": "",
"session_id": "session-1",
}, recoveryErr.Details())
require.Contains(t, recoveryErr.Error(), "continue on a new branch")
}
func TestPersistBranchRecoveryWarningsIsIdempotent(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedSession(t, repo, "task-branch-recovery", "session-branch-recovery", "step1")
now := time.Now().UTC()
require.NoError(t, repo.CreateRepository(ctx, &models.Repository{
ID: "repo-branch-recovery", WorkspaceID: "ws1", Name: "backend", DefaultBranch: "main",
CreatedAt: now, UpdatedAt: now,
}))
require.NoError(t, repo.CreateTaskRepository(ctx, &models.TaskRepository{
ID: "task-repo-branch-recovery", TaskID: "task-branch-recovery", RepositoryID: "repo-branch-recovery",
BaseBranch: "main", Position: 0, CreatedAt: now, UpdatedAt: now,
}))
require.NoError(t, repo.CreateTaskEnvironment(ctx, &models.TaskEnvironment{
ID: "env-branch-recovery", TaskID: "task-branch-recovery",
ExecutorType: string(models.ExecutorTypeWorktree), WorkspacePath: t.TempDir(), Status: models.TaskEnvironmentStatusReady,
Repos: []*models.TaskEnvironmentRepo{{
ID: "env-repo-branch-recovery", RepositoryID: "repo-branch-recovery", BranchSlug: "task-branch-recovery",
WorktreeID: "worktree-branch-recovery", WorktreeBranch: "feature/lost", Position: 0,
CreatedAt: now, UpdatedAt: now,
}},
}))
session, err := repo.GetTaskSession(ctx, "session-branch-recovery")
require.NoError(t, err)
session.TaskEnvironmentID = "env-branch-recovery"
require.NoError(t, repo.UpdateTaskSession(ctx, session))
service := createTestService(repo, newMockStepGetter(), newMockTaskRepo())
messages := &mockMessageCreator{}
service.messageCreator = messages
before, err := service.captureBranchRecoverySnapshot(ctx, "task-branch-recovery", "session-branch-recovery")
require.NoError(t, err)
row, err := repo.ListTaskEnvironmentRepos(ctx, "env-branch-recovery")
require.NoError(t, err)
require.Len(t, row, 1)
row[0].WorktreeBranch = "feature/recreated"
require.NoError(t, repo.UpdateTaskEnvironmentRepo(ctx, row[0]))
service.persistBranchRecoveryWarnings(ctx, "task-branch-recovery", "session-branch-recovery", before)
service.persistBranchRecoveryWarnings(ctx, "task-branch-recovery", "session-branch-recovery", before)
require.Len(t, messages.sessionMessages, 1)
warning := messages.sessionMessages[0]
require.Equal(t, "branch_recreated", warning.content)
require.Equal(t, string(v1.MessageTypeStatus), warning.messageType)
require.Equal(t, "warning", warning.metadata["variant"])
require.Equal(t, "branch_recreated", warning.metadata["kind"])
require.Equal(t, "feature/lost", warning.metadata["original_branch"])
require.Equal(t, "feature/recreated", warning.metadata["new_branch"])
require.Equal(t, "main", warning.metadata["base_branch"])
require.Equal(t, "session-branch-recovery", warning.metadata["session_id"])
require.Equal(t, "repo-branch-recovery", warning.metadata["repository_id"])
}
func TestPersistBranchRecoveryWarningsReclaimsStaleClaim(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedSession(t, repo, "task-stale-claim", "session-stale-claim", "step1")
now := time.Now().UTC()
require.NoError(t, repo.CreateRepository(ctx, &models.Repository{
ID: "repo-stale-claim", WorkspaceID: "ws1", Name: "backend", DefaultBranch: "main",
CreatedAt: now, UpdatedAt: now,
}))
require.NoError(t, repo.CreateTaskRepository(ctx, &models.TaskRepository{
ID: "task-repo-stale-claim", TaskID: "task-stale-claim", RepositoryID: "repo-stale-claim",
BaseBranch: "main", Position: 0, CreatedAt: now, UpdatedAt: now,
}))
require.NoError(t, repo.CreateTaskEnvironment(ctx, &models.TaskEnvironment{
ID: "env-stale-claim", TaskID: "task-stale-claim",
ExecutorType: string(models.ExecutorTypeWorktree), WorkspacePath: t.TempDir(), Status: models.TaskEnvironmentStatusReady,
Repos: []*models.TaskEnvironmentRepo{{
ID: "env-repo-stale-claim", RepositoryID: "repo-stale-claim", BranchSlug: "task-stale-claim",
WorktreeID: "worktree-stale-claim", WorktreeBranch: "feature/lost", Position: 0,
CreatedAt: now, UpdatedAt: now,
}},
}))
session, err := repo.GetTaskSession(ctx, "session-stale-claim")
require.NoError(t, err)
session.TaskEnvironmentID = "env-stale-claim"
require.NoError(t, repo.UpdateTaskSession(ctx, session))
decisionID := branchRecoveryDecisionID(
"task-stale-claim", "session-stale-claim", "repo-stale-claim", "feature/lost", "feature/recreated", "main",
)
claimed, err := repo.SetSessionMetadataKeyIfAbsent(
ctx,
"session-stale-claim",
branchRecoveryWarningKeyPrefix+decisionID,
branchRecoveryWarningClaim{ClaimedAt: time.Now().Add(-(branchRecoveryWarningClaimStaleAfter + time.Minute))},
)
require.NoError(t, err)
require.True(t, claimed)
service := createTestService(repo, newMockStepGetter(), newMockTaskRepo())
messages := &mockMessageCreator{}
service.messageCreator = messages
before, err := service.captureBranchRecoverySnapshot(ctx, "task-stale-claim", "session-stale-claim")
require.NoError(t, err)
row, err := repo.ListTaskEnvironmentRepos(ctx, "env-stale-claim")
require.NoError(t, err)
require.Len(t, row, 1)
row[0].WorktreeBranch = "feature/recreated"
require.NoError(t, repo.UpdateTaskEnvironmentRepo(ctx, row[0]))
service.persistBranchRecoveryWarnings(ctx, "task-stale-claim", "session-stale-claim", before)
require.Len(t, messages.sessionMessages, 1)
require.Equal(t, "branch_recreated", messages.sessionMessages[0].metadata["kind"])
}
func TestPersistBranchRecoveryWarningReleasesClaimWhenMessageWriteFails(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedSession(t, repo, "task-warning-write-failure", "session-warning-write-failure", "step1")
writeErr := errors.New("message write failed")
messages := &mockMessageCreator{sessionMessageErr: writeErr}
service := createTestService(repo, newMockStepGetter(), newMockTaskRepo())
service.messageCreator = messages
previous := branchRecoveryRepoSnapshot{
RepositoryID: "repo-warning-write-failure",
BranchSlug: "primary",
WorktreeBranch: "feature/lost",
BaseBranch: "main",
}
current := previous
current.WorktreeBranch = "feature/recreated"
service.persistBranchRecoveryWarning(
ctx,
"task-warning-write-failure",
"session-warning-write-failure",
previous,
current,
)
if len(messages.sessionMessages) != 0 {
t.Fatalf("failed message write was recorded as a success: %+v", messages.sessionMessages)
}
messages.sessionMessageErr = nil
service.persistBranchRecoveryWarning(
ctx,
"task-warning-write-failure",
"session-warning-write-failure",
previous,
current,
)
if len(messages.sessionMessages) != 1 {
t.Fatalf("warning messages = %d, want one retry after the initial write failure", len(messages.sessionMessages))
}
if messages.sessionMessageAttempts != 2 {
t.Fatalf("message write attempts = %d, want one failed attempt and one retry", messages.sessionMessageAttempts)
}
}
func TestBranchRecoveryErrorLeavesOrdinaryErrorsUntouched(t *testing.T) {
cause := errors.New("ordinary resume failure")
service := &Service{}
require.Same(t, cause, service.branchRecoveryError(context.Background(), "task-1", "session-1", cause))
}
@@ -79,6 +79,9 @@ type LaunchSessionRequest struct {
// <kandev-system> block that survives first-turn canonicalization, so a WS
// client must not be able to forge one and fabricate server authority.
SpawnOrigin *SpawnOrigin `json:"-"`
// AllowBranchReplacement is set only by RecoverSession for the explicit
// resume_new_branch action. Clients cannot grant this permission directly.
AllowBranchReplacement bool `json:"-"`
}
// SpawnOrigin describes the agent session that spawned a new sibling session.
@@ -317,7 +320,9 @@ func (s *Service) launchStartCreated(ctx context.Context, req *LaunchSessionRequ
// launchResume resumes a stopped session.
func (s *Service) launchResume(ctx context.Context, req *LaunchSessionRequest) (*LaunchSessionResponse, error) {
execution, err := s.ResumeTaskSession(ctx, req.TaskID, req.SessionID)
execution, err := s.ResumeTaskSessionWithOptions(ctx, req.TaskID, req.SessionID, executor.ResumeOptions{
AllowBranchReplacement: req.AllowBranchReplacement,
})
if err != nil {
return nil, err
}
@@ -376,7 +381,9 @@ func (s *Service) launchRestoreWorkspace(ctx context.Context, req *LaunchSession
}
// RecoverSession handles user-initiated recovery after an agent CLI failure.
// action is "resume" (retry with existing ACP session) or "fresh_start" (clear token, start fresh).
// action is "resume" (retry with existing ACP session), "resume_new_branch"
// (retry after replacing a confirmed missing branch), or "fresh_start" (clear
// token, start fresh).
func (s *Service) RecoverSession(ctx context.Context, taskID, sessionID, action string) (*LaunchSessionResponse, error) {
// Guard before the switch: "fresh_start" clears the resume token, so an
// unauthorized call would mutate the session even if the launch failed.
@@ -400,14 +407,18 @@ func (s *Service) RecoverSession(ctx context.Context, taskID, sessionID, action
}
case "resume":
// no-op — relaunch with existing resume token
case "resume_new_branch":
// The launch carries the explicit permission. It is not persisted on the
// session and cannot be inferred from a previous failed attempt.
default:
return nil, fmt.Errorf("invalid recovery action: %s", action)
}
resp, err := s.LaunchSession(ctx, &LaunchSessionRequest{
TaskID: taskID,
SessionID: sessionID,
Intent: IntentResume,
TaskID: taskID,
SessionID: sessionID,
Intent: IntentResume,
AllowBranchReplacement: action == "resume_new_branch",
})
if err != nil {
return nil, normalizeRecoverSessionError(err)
@@ -1915,6 +1915,18 @@ func (s *Service) expandPromptReferencesWithContext(
// ResumeTaskSession restarts a specific task session using its stored worktree.
func (s *Service) ResumeTaskSession(ctx context.Context, taskID, sessionID string) (*executor.TaskExecution, error) {
return s.ResumeTaskSessionWithOptions(ctx, taskID, sessionID, executor.ResumeOptions{})
}
// ResumeTaskSessionWithOptions restarts a task session with an explicit
// recovery permission. The default ResumeTaskSession path remains unchanged.
//
//nolint:cyclop,gocognit,funlen // Resume coordinates state validation, launch recovery, and ready-state persistence.
func (s *Service) ResumeTaskSessionWithOptions(
ctx context.Context,
taskID, sessionID string,
options executor.ResumeOptions,
) (*executor.TaskExecution, error) {
s.logger.Debug("resuming task session",
zap.String("task_id", taskID),
zap.String("session_id", sessionID))
@@ -1937,6 +1949,7 @@ func (s *Service) ResumeTaskSession(ctx context.Context, taskID, sessionID strin
return nil, fmt.Errorf("session is not resumable: no executor record")
}
s.noteMissingWorktreesBeforeResume(sessionID, session)
branchRecoveryBefore := s.captureBranchRecoveryBeforeResume(ctx, taskID, sessionID, options)
// Completed sessions cannot be restarted — they require a new session.
// Failed and cancelled sessions keep the resume token so the relaunched
@@ -1980,13 +1993,19 @@ func (s *Service) ResumeTaskSession(ctx context.Context, taskID, sessionID strin
// Use context.WithoutCancel to prevent WebSocket request timeout from canceling the resume.
// Session resume can take time and shouldn't be tied to the WS request lifecycle.
resumeCtx := context.WithoutCancel(ctx)
execution, err := s.executor.ResumeSession(resumeCtx, session, true)
persistBranchRecovery := func() {
if options.AllowBranchReplacement {
s.persistBranchRecoveryWarnings(resumeCtx, taskID, sessionID, branchRecoveryBefore)
}
}
execution, err := s.executor.ResumeSessionWithOptions(resumeCtx, session, true, options)
var readySession *models.TaskSession
if err != nil {
// If the execution is already running (duplicate resume request), return it as success.
if errors.Is(err, executor.ErrExecutionAlreadyRunning) {
execution, readySession, err = s.recoverAlreadyRunningResume(resumeCtx, taskID, sessionID)
execution, readySession, err = s.recoverAlreadyRunningResume(resumeCtx, taskID, sessionID, options)
if err != nil && errors.Is(err, ErrAgentNotReadyForPrompt) {
persistBranchRecovery()
return nil, err
}
}
@@ -2001,6 +2020,7 @@ func (s *Service) ResumeTaskSession(ctx context.Context, taskID, sessionID strin
if task, taskErr := s.repo.GetTask(resumeCtx, taskID); taskErr == nil && task != nil && task.ArchivedAt != nil {
return nil, executor.ErrTaskArchived
}
persistBranchRecovery()
// Use resumeCtx (WithoutCancel) for the failure-recording writes too —
// if the caller's ctx was already cancelled (e.g. WS client navigated
// away), the SessionStateFailed and TaskStateFailed updates would
@@ -2009,6 +2029,7 @@ func (s *Service) ResumeTaskSession(ctx context.Context, taskID, sessionID strin
// ResumeSession launches the workspace directly rather than through
// LaunchPreparedSession. Record this failure with the same state CAS,
// persisted recovery claim, and archive-safe task CAS as early launch.
err = s.branchRecoveryError(resumeCtx, taskID, sessionID, err)
return nil, s.handleSessionLaunchFailure(
resumeCtx, taskID, sessionID, err, session,
)
@@ -2017,10 +2038,12 @@ func (s *Service) ResumeTaskSession(ctx context.Context, taskID, sessionID strin
if readySession == nil {
readySession, err = s.waitForResumedSessionReady(resumeCtx, sessionID)
if err != nil {
persistBranchRecovery()
return nil, err
}
}
execution.SessionState = v1.TaskSessionState(readySession.State)
persistBranchRecovery()
// Backfill the initial user message when a prior failed launch never got
// to recordInitialMessage. Without this, the resume can succeed and the
@@ -2051,6 +2074,25 @@ func (s *Service) ResumeTaskSession(ctx context.Context, taskID, sessionID strin
return execution, nil
}
func (s *Service) captureBranchRecoveryBeforeResume(
ctx context.Context,
taskID, sessionID string,
options executor.ResumeOptions,
) *branchRecoverySnapshot {
if !options.AllowBranchReplacement {
return nil
}
snapshot, err := s.captureBranchRecoverySnapshot(ctx, taskID, sessionID)
if err != nil {
s.logger.Warn("failed to capture branch recovery state before resume",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.Error(err))
return nil
}
return snapshot
}
func (s *Service) waitForResumedSessionReady(ctx context.Context, sessionID string) (*models.TaskSession, error) {
return s.waitForSessionAndAgentReady(ctx, sessionID, "after resume")
}
@@ -2059,6 +2101,7 @@ func (s *Service) recoverAlreadyRunningResume(
resumeCtx context.Context,
taskID string,
sessionID string,
options executor.ResumeOptions,
) (*executor.TaskExecution, *models.TaskSession, error) {
existing, ok := s.executor.GetExecutionBySession(sessionID)
if !ok || existing == nil {
@@ -2086,7 +2129,7 @@ func (s *Service) recoverAlreadyRunningResume(
return nil, nil, fmt.Errorf("task session does not belong to task")
}
execution, err := s.executor.ResumeSession(resumeCtx, session, true)
execution, err := s.executor.ResumeSessionWithOptions(resumeCtx, session, true, options)
if err != nil {
return nil, nil, err
}
@@ -4390,23 +4390,24 @@ func TestIssue1884_StepProfileSignalGateStaysInTaskMode(t *testing.T) {
// mockMessageCreator implements MessageCreator for testing.
// Only CreateUserMessage is tracked; all other methods are no-op stubs.
type mockMessageCreator struct {
mu sync.Mutex
userMessages []mockUserMessage
sessionMessages []mockSessionMessage
sessionMessageDone chan struct{}
sessionMessageOnce sync.Once
sessionMessageErr error
agentMessages []mockAgentMessage
agentMessageWrites int
agentStreamWrites int
thinkingWrites int
toolCallWrites int
toolUpdateWrites int
userMessageErr error
permissionClaimFn func(context.Context, models.PermissionResolutionClaimRequest) (*models.PermissionResolutionClaimResult, error)
permissionFinishFn func(context.Context, models.PermissionResolutionFinalizeRequest) (*models.PermissionResolutionFinalizeResult, error)
permissionAuditFn func(context.Context, string, string, string, string) (*models.PermissionResolutionAudit, error)
permissionUpdateFn func(context.Context, string, string, string, string, models.PermissionStatus) error
mu sync.Mutex
userMessages []mockUserMessage
sessionMessages []mockSessionMessage
sessionMessageAttempts int
sessionMessageDone chan struct{}
sessionMessageOnce sync.Once
sessionMessageErr error
agentMessages []mockAgentMessage
agentMessageWrites int
agentStreamWrites int
thinkingWrites int
toolCallWrites int
toolUpdateWrites int
userMessageErr error
permissionClaimFn func(context.Context, models.PermissionResolutionClaimRequest) (*models.PermissionResolutionClaimResult, error)
permissionFinishFn func(context.Context, models.PermissionResolutionFinalizeRequest) (*models.PermissionResolutionFinalizeResult, error)
permissionAuditFn func(context.Context, string, string, string, string) (*models.PermissionResolutionAudit, error)
permissionUpdateFn func(context.Context, string, string, string, string, models.PermissionStatus) error
}
type mockUserMessage struct {
@@ -4451,6 +4452,7 @@ func (m *mockMessageCreator) UpdateToolCallMessage(context.Context, string, stri
func (m *mockMessageCreator) CreateSessionMessage(_ context.Context, taskID, content, sessionID, messageType, turnID string, metadata map[string]interface{}, requestsInput bool) error {
m.mu.Lock()
defer m.mu.Unlock()
m.sessionMessageAttempts++
if m.sessionMessageErr != nil {
return m.sessionMessageErr
}
@@ -5438,6 +5440,109 @@ func TestResumeTaskSession_FailedKeepsResumeToken(t *testing.T) {
}
}
// TestRecoverSession_ResumeNewBranchPreservesSessionAndProviderIdentity proves
// the service-level recovery action carries the explicit replacement permission
// without turning it into a fresh session or provider conversation. Worktree
// materialization itself is covered by the lifecycle tests; this boundary test
// verifies the request that reaches that materializer.
func TestRecoverSession_ResumeNewBranchPreservesSessionAndProviderIdentity(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
taskRepo := newMockTaskRepo()
var captured *executor.LaunchAgentRequest
startAgentProcessCalled := false
agentMgr := &sessionUpdatingAgentManager{
mockAgentManager: &mockAgentManager{
launchAgentFunc: func(_ context.Context, req *executor.LaunchAgentRequest) (*executor.LaunchAgentResponse, error) {
captured = req
return &executor.LaunchAgentResponse{
AgentExecutionID: "exec-recovered",
Status: v1.AgentStatusStarting,
}, nil
},
},
repo: repo,
sessionID: "session-recover-new-branch",
taskID: "task-recover-new-branch",
onStartCalled: &startAgentProcessCalled,
}
svc := createTestServiceWithAgent(repo, newMockStepGetter(), taskRepo, agentMgr)
svc.executor = executor.NewExecutor(agentMgr, repo, testLogger(), executor.ExecutorConfig{})
seedTaskAndSession(t, repo, "task-recover-new-branch", "session-recover-new-branch", models.TaskSessionStateFailed)
now := time.Now().UTC()
require.NoError(t, repo.CreateExecutor(ctx, &models.Executor{
ID: "executor-recover-new-branch",
Name: "Worktree",
Type: models.ExecutorTypeWorktree,
Status: models.ExecutorStatusActive,
Resumable: true,
}))
require.NoError(t, repo.CreateRepository(ctx, &models.Repository{
ID: "repo-recover-new-branch",
WorkspaceID: "ws1",
Name: "backend",
SourceType: "local",
LocalPath: t.TempDir(),
DefaultBranch: "main",
CreatedAt: now,
UpdatedAt: now,
}))
require.NoError(t, repo.CreateTaskRepository(ctx, &models.TaskRepository{
ID: "task-repo-recover-new-branch",
TaskID: "task-recover-new-branch",
RepositoryID: "repo-recover-new-branch",
BaseBranch: "main",
Position: 0,
CreatedAt: now,
UpdatedAt: now,
}))
session, err := repo.GetTaskSession(ctx, "session-recover-new-branch")
require.NoError(t, err)
session.AgentProfileID = "profile-recover-new-branch"
session.ExecutorID = "executor-recover-new-branch"
session.RepositoryID = "repo-recover-new-branch"
session.BaseBranch = "main"
require.NoError(t, repo.UpdateTaskSession(ctx, session))
require.NoError(t, repo.UpsertExecutorRunning(ctx, &models.ExecutorRunning{
ID: "running-recover-new-branch",
SessionID: "session-recover-new-branch",
TaskID: "task-recover-new-branch",
AgentExecutionID: "exec-before-recovery",
ResumeToken: "acp-session-recover-new-branch",
Resumable: true,
CreatedAt: now,
UpdatedAt: now,
}))
response, err := svc.RecoverSession(ctx, "task-recover-new-branch", "session-recover-new-branch", "resume_new_branch")
require.NoError(t, err)
require.NotNil(t, response)
require.Equal(t, "task-recover-new-branch", response.TaskID)
require.Equal(t, "session-recover-new-branch", response.SessionID)
require.NotNil(t, captured)
require.Equal(t, "session-recover-new-branch", captured.SessionID)
require.Equal(t, "acp-session-recover-new-branch", captured.ACPSessionID)
require.True(t, captured.AllowBranchReplacement)
require.True(t, captured.UseWorktree)
require.Equal(t, "main", captured.Branch)
require.Equal(t, "main", captured.BaseBranch)
require.True(t, startAgentProcessCalled)
reloadedSession, err := repo.GetTaskSession(ctx, "session-recover-new-branch")
require.NoError(t, err)
require.Equal(t, session.ID, reloadedSession.ID)
require.Equal(t, models.TaskSessionStateWaitingForInput, reloadedSession.State)
reloadedRunning, err := repo.GetExecutorRunningBySessionID(ctx, "session-recover-new-branch")
require.NoError(t, err)
require.Equal(t, "acp-session-recover-new-branch", reloadedRunning.ResumeToken)
sessions, err := repo.ListTaskSessions(ctx, "task-recover-new-branch")
require.NoError(t, err)
require.Len(t, sessions, 1)
}
// TestResumeTaskSession_ArchiveCancelledSessionResumesSuccessfully is the
// end-to-end regression for "Can't resume this un-archived task": a session
// cancelled by an archive (Service.ArchiveTask / cascade archive) must resume
@@ -5662,6 +5767,78 @@ func TestResumeTaskSession_AlreadyFailedMissingRemoteRefCreatesNeutralRecoveryMe
}
}
func TestResumeTaskSession_PersistsBranchRecoveryWarningWhenPreparationFailsLater(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
taskRepo := newMockTaskRepo()
seedTaskAndSession(t, repo, "task-partial-recovery", "session-partial-recovery", models.TaskSessionStateFailed)
now := time.Now().UTC()
if err := repo.CreateRepository(ctx, &models.Repository{
ID: "repo-partial-recovery", WorkspaceID: "ws1", Name: "backend", DefaultBranch: "main",
CreatedAt: now, UpdatedAt: now,
}); err != nil {
t.Fatalf("CreateRepository: %v", err)
}
if err := repo.CreateTaskRepository(ctx, &models.TaskRepository{
ID: "task-repo-partial-recovery", TaskID: "task-partial-recovery", RepositoryID: "repo-partial-recovery",
BaseBranch: "main", Position: 0, CreatedAt: now, UpdatedAt: now,
}); err != nil {
t.Fatalf("CreateTaskRepository: %v", err)
}
if err := repo.CreateTaskEnvironment(ctx, &models.TaskEnvironment{
ID: "env-partial-recovery", TaskID: "task-partial-recovery",
ExecutorType: string(models.ExecutorTypeWorktree), WorkspacePath: t.TempDir(), Status: models.TaskEnvironmentStatusReady,
Repos: []*models.TaskEnvironmentRepo{{
ID: "env-repo-partial-recovery", RepositoryID: "repo-partial-recovery", BranchSlug: "backend",
WorktreeID: "worktree-partial-recovery", WorktreeBranch: "feature/lost", Position: 0,
CreatedAt: now, UpdatedAt: now,
}},
}); err != nil {
t.Fatalf("CreateTaskEnvironment: %v", err)
}
session, err := repo.GetTaskSession(ctx, "session-partial-recovery")
if err != nil {
t.Fatalf("GetTaskSession: %v", err)
}
session.AgentProfileID = "profile-partial-recovery"
session.TaskEnvironmentID = "env-partial-recovery"
if err := repo.UpdateTaskSession(ctx, session); err != nil {
t.Fatalf("UpdateTaskSession: %v", err)
}
launchErr := errors.New("second repository preparation failed")
agentMgr := &mockAgentManager{
launchAgentFunc: func(context.Context, *executor.LaunchAgentRequest) (*executor.LaunchAgentResponse, error) {
rows, err := repo.ListTaskEnvironmentRepos(ctx, "env-partial-recovery")
if err != nil {
return nil, err
}
rows[0].WorktreeBranch = "feature/replaced"
if err := repo.UpdateTaskEnvironmentRepo(ctx, rows[0]); err != nil {
return nil, err
}
return nil, launchErr
},
}
svc := createTestServiceWithAgent(repo, newMockStepGetter(), taskRepo, agentMgr)
svc.executor = executor.NewExecutor(agentMgr, repo, testLogger(), executor.ExecutorConfig{})
messages := &mockMessageCreator{}
svc.messageCreator = messages
_, err = svc.ResumeTaskSessionWithOptions(ctx, "task-partial-recovery", "session-partial-recovery", executor.ResumeOptions{
AllowBranchReplacement: true,
})
if !errors.Is(err, launchErr) {
t.Fatalf("ResumeTaskSessionWithOptions error = %v, want %v", err, launchErr)
}
if len(messages.sessionMessages) != 1 {
t.Fatalf("warning messages = %d, want one warning after partial preparation", len(messages.sessionMessages))
}
if got := messages.sessionMessages[0].metadata["kind"]; got != "branch_recreated" {
t.Fatalf("warning kind = %v, want branch_recreated", got)
}
}
func TestResumeTaskSession_UnrelatedLaunchFailureDoesNotCreateRecoveryMessage(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
+51
View File
@@ -26,6 +26,11 @@ var (
// ErrInvalidBaseBranch is returned when the base branch does not exist.
ErrInvalidBaseBranch = errors.New("base branch does not exist")
// ErrRemoteRefMissing is returned when Git confirms that the requested
// remote ref is unavailable. It is narrower than ErrInvalidBaseBranch so
// callers can distinguish a deleted branch from a failed fetch.
ErrRemoteRefMissing = errors.New("remote ref does not exist")
// ErrWorktreeCorrupted is returned when the worktree directory is corrupted or invalid.
ErrWorktreeCorrupted = errors.New("worktree directory is corrupted")
@@ -101,6 +106,51 @@ var (
ErrWorktreePathOwnedByAnotherTask = errors.New("worktree path is owned by another task")
)
// BranchUnrecoverableError identifies the branch that could not be restored.
// It wraps ErrBranchUnrecoverable so callers can preserve the existing
// sentinel check while presenting a branch-specific recovery action.
type BranchUnrecoverableError struct {
Branch string
}
type confirmedRemoteRefMissingError struct {
detail string
}
func (e *confirmedRemoteRefMissingError) Error() string {
if e == nil || e.detail == "" {
return ErrRemoteRefMissing.Error()
}
return fmt.Sprintf("%s: %s", ErrRemoteRefMissing, e.detail)
}
func (e *confirmedRemoteRefMissingError) Unwrap() []error {
return []error{ErrRemoteRefMissing, ErrInvalidBaseBranch}
}
func newConfirmedRemoteRefMissingError(detail string) error {
return &confirmedRemoteRefMissingError{detail: strings.TrimSpace(detail)}
}
func (e *BranchUnrecoverableError) Error() string {
if e == nil || e.Branch == "" {
return ErrBranchUnrecoverable.Error()
}
return fmt.Sprintf("%s: %q", ErrBranchUnrecoverable, e.Branch)
}
func (e *BranchUnrecoverableError) Unwrap() error {
return ErrBranchUnrecoverable
}
// BranchName returns the branch that was requested by the persisted worktree.
func (e *BranchUnrecoverableError) BranchName() string {
if e == nil {
return ""
}
return e.Branch
}
// containsAuthFailure checks if git output indicates an authentication failure.
func containsAuthFailure(lowerOutput string) bool {
return strings.Contains(lowerOutput, "authentication failed") ||
@@ -138,6 +188,7 @@ func isRemoteRefMissingError(err error) bool {
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") ||
strings.Contains(msg, "no remote configured") ||
strings.Contains(msg, "cannot determine remote head") ||
strings.Contains(msg, "remote head refers to nonexistent ref")
}
@@ -14,6 +14,27 @@ func TestInvalidBaseBranchRemainsSentinelDetectable(t *testing.T) {
}
}
func TestIsRemoteRefMissingErrorRequiresConfirmedRemoteEvidence(t *testing.T) {
tests := []struct {
name string
err error
want bool
}{
{name: "missing ref", err: errors.New("fatal: couldn't find remote ref feature/lost"), want: true},
{name: "no remote", err: errors.New("fatal: no remote configured"), want: true},
{name: "authentication failure", err: errors.New("fatal: Authentication failed"), want: false},
{name: "network failure", err: errors.New("fatal: unable to access remote: connection timed out"), want: false},
{name: "generic invalid branch", err: fmt.Errorf("%w: feature/lost", ErrInvalidBaseBranch), want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isRemoteRefMissingError(tt.err); got != tt.want {
t.Fatalf("isRemoteRefMissingError(%v) = %v, want %v", tt.err, got, tt.want)
}
})
}
}
func TestClassifyGitError_BranchCheckedOut(t *testing.T) {
output := "fatal: 'feature/pr-branch' is already checked out at '/tmp/worktree-123'"
err := ClassifyGitError(output, fmt.Errorf("exit status 128"))
@@ -70,6 +70,49 @@ func (m *Manager) branchExists(ctx context.Context, repoPath, branch string) (bo
return true, nil
}
// remoteBranchExists performs an authoritative, bounded probe for a branch on
// origin. A successful `ls-remote --exit-code` with exit status 2 means the
// remote answered and did not advertise the requested ref. Any other failure
// remains an error because transport, authentication, and timeout failures do
// not prove that the branch was deleted.
func (m *Manager) remoteBranchExists(ctx context.Context, repoPath, branch string) (bool, error) {
branch = normalizeOriginBranchName(branch)
if branch == "" {
return false, fmt.Errorf("remote branch name is empty: %w", ErrGitCommandFailed)
}
output, err := m.runBoundedGitInspect(
ctx,
repoPath,
"ls-remote",
"--exit-code",
"--heads",
"origin",
"refs/heads/"+branch,
)
if err == nil {
return true, nil
}
var exitErr *exec.ExitError
if errors.As(err, &exitErr) && exitErr.ExitCode() == 2 {
return false, nil
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return false, err
}
if containsAuthFailure(strings.ToLower(output)) {
return false, ErrAuthFailed
}
return false, ErrGitCommandFailed
}
func normalizeOriginBranchName(branch string) string {
branch = strings.TrimSpace(branch)
for _, prefix := range []string{"refs/remotes/origin/", "refs/heads/", "origin/"} {
branch = strings.TrimPrefix(branch, prefix)
}
return branch
}
// runBoundedGitInspect runs a non-interactive local git inspection after
// acquiring the lifecycle throttle. The timeout starts after admission so
// queue wait does not consume the command's inspection budget.
@@ -1,3 +1,5 @@
//revive:disable:file-length-limit // Legacy lifecycle coordination remains in one file; replacement recovery lives in manager_replacement.go.
package worktree
import (
@@ -293,11 +295,52 @@ func (m *Manager) reuseRequiredWorktree(ctx context.Context, req CreateRequest)
defer func() { _ = handle.Close() }()
}
if !valid {
if err := m.classifyUnavailableReusableWorktree(ctx, req, wt); err != nil {
return nil, err
}
return nil, ErrReuseWorktreeUnavailable
}
return wt, nil
}
// classifyUnavailableReusableWorktree distinguishes a missing checkout from a
// branch that no longer exists in either the local repository or its
// remote-tracking refs. Attach-only reuse must not recreate a checkout, but a
// confirmed missing branch still needs the typed recovery signal used by the
// explicit new-branch action.
func (m *Manager) classifyUnavailableReusableWorktree(
ctx context.Context,
req CreateRequest,
wt *Worktree,
) error {
if wt == nil || wt.Branch == "" || !m.isGitRepo(req.RepositoryPath) {
return nil
}
localExists, err := m.branchExists(ctx, req.RepositoryPath, wt.Branch)
if err != nil {
return fmt.Errorf("%w: verify saved branch %q: %w", ErrReuseWorktreeUnavailable, wt.Branch, err)
}
if localExists {
return nil
}
branch := normalizeOriginBranchName(wt.Branch)
remoteExists, err := m.branchExists(ctx, req.RepositoryPath, "refs/remotes/origin/"+branch)
if err != nil {
return fmt.Errorf("%w: verify saved remote branch %q: %w", ErrReuseWorktreeUnavailable, wt.Branch, err)
}
if remoteExists {
return nil
}
remoteExists, err = m.remoteBranchExists(ctx, req.RepositoryPath, branch)
if err != nil {
return fmt.Errorf("%w: verify authoritative remote branch %q: %w", ErrReuseWorktreeUnavailable, wt.Branch, err)
}
if remoteExists {
return nil
}
return fmt.Errorf("%w: %w", ErrReuseWorktreeUnavailable, &BranchUnrecoverableError{Branch: wt.Branch})
}
// tryReuseExisting looks for an existing worktree to reuse, recreating it if
// the on-disk directory is missing. Returns (wt, true, err) when fully handled
// (caller should return immediately). Returns (nil, false, nil) when no reuse
@@ -729,7 +772,8 @@ func (m *Manager) createInTaskDir(ctx context.Context, req CreateRequest, baseRe
}
if selectedRef == "" {
if req.PRNumber > 0 {
return nil, fmt.Errorf("%w: refreshed pull request head %d was not materialized", ErrBranchUnrecoverable, req.PRNumber)
err := &BranchUnrecoverableError{Branch: req.CheckoutBranch}
return nil, fmt.Errorf("%w: refreshed pull request head %d was not materialized", err, req.PRNumber)
}
branchName = req.CheckoutBranch
checkoutMode.CheckoutBranch = ""
@@ -1032,10 +1076,10 @@ func (m *Manager) fetchBranchToLocalWithPolicy(
}
if required {
if isRemoteBranchMissingError(outputStr) {
if isRemoteBranchMissingError(outputStr) || isRemoteRefMissingError(errors.New(outputStr)) {
return nil, fmt.Errorf(
"required refresh of checkout branch %q found no remote ref: %w",
branch, ErrInvalidBaseBranch,
branch, newConfirmedRemoteRefMissingError(outputStr),
)
}
reason := classifyGitFallbackReason(err, outputStr, fetchCtxErr)
@@ -1056,7 +1100,17 @@ func (m *Manager) fetchBranchToLocalWithPolicy(
return nil, fmt.Errorf("could not verify local branch %q after fetch failure (%s): %w", branch, strings.TrimSpace(outputStr), existsErr)
}
if !exists {
return nil, fmt.Errorf("%w: branch %q not found locally or on remote: %s", ErrInvalidBaseBranch, branch, outputStr)
if isRemoteRefMissingError(errors.New(outputStr)) {
return nil, fmt.Errorf(
"branch %q not found locally or on remote: %w",
branch, newConfirmedRemoteRefMissingError(outputStr),
)
}
reason := classifyGitFallbackReason(err, outputStr, fetchCtxErr)
return nil, fmt.Errorf(
"could not fetch branch %q and no local branch is available (%s): %w",
branch, reason, syncFailureCause(reason, err, fetchCtxErr),
)
}
reason := classifyGitFallbackReason(err, outputStr, fetchCtxErr)
@@ -1887,7 +1941,11 @@ func (m *Manager) recreate(ctx context.Context, existing *Worktree, req CreateRe
return nil, prepareErr
}
if selectedRef == "" {
return nil, fmt.Errorf("%w: refreshed branch %q was not materialized", ErrBranchUnrecoverable, sourceBranch)
err := &BranchUnrecoverableError{Branch: sourceBranch}
if req.AllowBranchReplacement {
return m.replaceUnrecoverableWorktree(ctx, existing, req, err)
}
return nil, fmt.Errorf("%w: refreshed branch %q was not materialized", err, sourceBranch)
}
if selectedRef != existing.Branch {
refreshedStartPoint = selectedRef
@@ -1917,8 +1975,12 @@ func (m *Manager) recreate(ctx context.Context, existing *Worktree, req CreateRe
// 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)
if errors.Is(fetchErr, ErrRemoteRefMissing) || isRemoteRefMissingError(fetchErr) {
err := &BranchUnrecoverableError{Branch: existing.Branch}
if req.AllowBranchReplacement {
return m.replaceUnrecoverableWorktree(ctx, existing, req, err)
}
return nil, err
}
return nil, fetchErr
}
@@ -187,6 +187,210 @@ func TestRecreate_BranchGoneEverywhereReturnsUnrecoverable(t *testing.T) {
if !errors.Is(err, ErrBranchUnrecoverable) {
t.Fatalf("recreate() err = %v, want ErrBranchUnrecoverable", err)
}
var branchErr interface{ BranchName() string }
if !errors.As(err, &branchErr) {
t.Fatalf("recreate() err = %v, want a typed branch recovery error", err)
}
if got := branchErr.BranchName(); got != existing.Branch {
t.Fatalf("branch recovery error names %q, want %q", got, existing.Branch)
}
}
func TestRecreate_DoesNotReplaceAfterTransientFetchFailure(t *testing.T) {
repoPath := initGitRepoWithRemote(t)
runGit(t, repoPath, "remote", "set-url", "origin", "https://127.0.0.1:1/unavailable.git")
archiveDeletesLocalBranch(t, repoPath, "feature/pr-branch")
cfg := newTestConfig(t)
store := newMockStore()
mgr, err := NewManager(cfg, store, newTestLogger())
if err != nil {
t.Fatalf("NewManager failed: %v", err)
}
existing := &Worktree{
ID: "wt-transient-fetch",
SessionID: "session-transient-fetch",
TaskID: "task-transient-fetch",
TaskDirName: "task-transient-fetch",
TaskEnvironmentID: "env-transient-fetch",
RepositoryID: "repo-1",
RepositoryPath: repoPath,
Path: filepath.Join(cfg.TasksBasePath, "task-transient-fetch", "repo-1"),
Branch: "feature/pr-branch",
Status: StatusDeleted,
}
store.worktrees[existing.ID] = existing
_, err = mgr.recreate(context.Background(), existing, CreateRequest{
SessionID: existing.SessionID,
TaskID: existing.TaskID,
TaskEnvironmentID: existing.TaskEnvironmentID,
RepositoryID: existing.RepositoryID,
RepositoryPath: repoPath,
TaskDirName: existing.TaskDirName,
RepoName: "repo-1",
BaseBranch: "main",
AllowBranchReplacement: true,
})
if err == nil {
t.Fatal("recreate() succeeded after a transient fetch failure")
}
if errors.Is(err, ErrBranchUnrecoverable) {
t.Fatalf("recreate() misclassified transient fetch failure as branch loss: %v", err)
}
if errors.Is(err, ErrInvalidBaseBranch) {
t.Fatalf("recreate() misclassified transient fetch failure as invalid branch: %v", err)
}
if errors.Is(err, ErrRemoteRefMissing) {
t.Fatalf("recreate() reported confirmed remote ref loss for transient fetch failure: %v", err)
}
}
func TestRecreate_AllowsExplicitReplacementWithFreshBranchAndPath(t *testing.T) {
repoPath := initGitRepoWithRemote(t)
runGit(t, repoPath, "push", "origin", "--delete", "feature/pr-branch")
archiveDeletesLocalBranch(t, repoPath, "feature/pr-branch")
runGit(t, repoPath, "fetch", "--prune", "origin")
cfg := newTestConfig(t)
store := newMockStore()
mgr, err := NewManager(cfg, store, newTestLogger())
if err != nil {
t.Fatalf("NewManager failed: %v", err)
}
existing := &Worktree{
ID: "wt-replace",
SessionID: "session-replace",
TaskID: "task-replace",
TaskDirName: "task-replace",
TaskEnvironmentID: "env-replace",
RepositoryID: "repo-1",
RepositoryPath: repoPath,
Path: filepath.Join(cfg.TasksBasePath, "task-replace", "repo-1-primary"),
Branch: "feature/pr-branch",
BranchSlug: "primary",
BaseBranch: "main",
Status: StatusDeleted,
}
store.worktrees[existing.ID] = existing
wt, err := mgr.recreate(context.Background(), existing, CreateRequest{
SessionID: existing.SessionID,
TaskID: existing.TaskID,
TaskEnvironmentID: existing.TaskEnvironmentID,
RepositoryID: existing.RepositoryID,
RepositoryPath: repoPath,
BaseBranch: "main",
TaskDirName: existing.TaskDirName,
RepoName: "repo-1",
BranchIdentitySlug: existing.BranchSlug,
PullBeforeWorktree: true,
AllowBranchReplacement: true,
})
if err != nil {
t.Fatalf("recreate() explicit replacement: %v", err)
}
if wt.ID != existing.ID {
t.Fatalf("replacement worktree ID = %q, want stable ID %q", wt.ID, existing.ID)
}
if wt.Branch == existing.Branch {
t.Fatalf("replacement branch = %q, want a fresh branch", wt.Branch)
}
if wt.Path == existing.Path {
t.Fatalf("replacement path = %q, want a fresh path", wt.Path)
}
if wt.BranchSlug != existing.BranchSlug {
t.Fatalf("replacement branch slug = %q, want stable identity %q", wt.BranchSlug, existing.BranchSlug)
}
if wt.Status != StatusActive || wt.DeletedAt != nil {
t.Fatalf("replacement status = %q, deleted_at = %v, want active and nil", wt.Status, wt.DeletedAt)
}
if got := strings.TrimSpace(runGit(t, wt.Path, "rev-parse", "--abbrev-ref", "HEAD")); got != wt.Branch {
t.Fatalf("replacement HEAD branch = %q, want %q", got, wt.Branch)
}
mainSHA := strings.TrimSpace(runGit(t, repoPath, "rev-parse", "main"))
if got := strings.TrimSpace(runGit(t, wt.Path, "rev-parse", "HEAD")); got != mainSHA {
t.Fatalf("replacement HEAD = %q, want main SHA %q", got, mainSHA)
}
stored := store.worktrees[existing.ID]
if stored == nil || stored.Branch != wt.Branch || stored.Path != wt.Path {
t.Fatalf("stored replacement = %#v, want branch %q and path %q", stored, wt.Branch, wt.Path)
}
}
type replacementUpdateErrorStore struct {
*mockStore
err error
attempted *Worktree
}
func (s *replacementUpdateErrorStore) UpdateWorktree(_ context.Context, wt *Worktree) error {
copy := *wt
s.attempted = &copy
return s.err
}
func TestRecreate_CleansReplacementWhenPersistenceFails(t *testing.T) {
repoPath := initGitRepoWithRemote(t)
runGit(t, repoPath, "push", "origin", "--delete", "feature/pr-branch")
archiveDeletesLocalBranch(t, repoPath, "feature/pr-branch")
runGit(t, repoPath, "fetch", "--prune", "origin")
cfg := newTestConfig(t)
storeErr := errors.New("replacement persistence failed")
store := &replacementUpdateErrorStore{mockStore: newMockStore(), err: storeErr}
existing := &Worktree{
ID: "wt-replace-persist-failure",
SessionID: "session-replace-persist-failure",
TaskID: "task-replace-persist-failure",
TaskDirName: "task-replace-persist-failure",
TaskEnvironmentID: "env-replace-persist-failure",
RepositoryID: "repo-1",
RepositoryPath: repoPath,
Path: filepath.Join(cfg.TasksBasePath, "task-replace-persist-failure", "repo-1-old"),
Branch: "feature/pr-branch",
BaseBranch: "main",
Status: StatusDeleted,
}
store.worktrees[existing.ID] = existing
mgr, err := NewManager(cfg, store, newTestLogger())
if err != nil {
t.Fatalf("NewManager() error = %v", err)
}
_, err = mgr.recreate(context.Background(), existing, CreateRequest{
SessionID: existing.SessionID,
TaskID: existing.TaskID,
TaskEnvironmentID: existing.TaskEnvironmentID,
RepositoryID: existing.RepositoryID,
RepositoryPath: repoPath,
BaseBranch: existing.BaseBranch,
TaskDirName: existing.TaskDirName,
RepoName: "repo-1",
BranchIdentitySlug: "primary",
PullBeforeWorktree: true,
AllowBranchReplacement: true,
})
if !errors.Is(err, storeErr) {
t.Fatalf("recreate() error = %v, want %v", err, storeErr)
}
if store.attempted == nil {
t.Fatal("replacement persistence was not attempted")
}
if _, statErr := os.Stat(store.attempted.Path); !errors.Is(statErr, os.ErrNotExist) {
t.Fatalf("replacement worktree path still exists after persistence failure: %q (%v)", store.attempted.Path, statErr)
}
branchExists, branchErr := mgr.branchExists(context.Background(), repoPath, "refs/heads/"+store.attempted.Branch)
if branchErr != nil {
t.Fatalf("verify replacement branch cleanup: %v", branchErr)
}
if branchExists {
t.Fatalf("replacement branch %q still exists after persistence failure", store.attempted.Branch)
}
stored := store.worktrees[existing.ID]
if stored == nil || stored.Path != existing.Path || stored.Branch != existing.Branch || stored.Status != StatusDeleted {
t.Fatalf("stored worktree = %#v, want the original deleted record %#v", stored, existing)
}
}
// TestBranchRecoveryStatus covers the three probe outcomes used by the
@@ -0,0 +1,215 @@
package worktree
import (
"context"
"errors"
"fmt"
"os"
"strings"
"time"
"go.uber.org/zap"
)
const replacementBranchAttempts = 20
// replaceUnrecoverableWorktree creates a fresh branch and worktree while
// retaining the existing task-environment repository record. The caller holds
// the repository lock from recreate, so this helper must not acquire it again.
func (m *Manager) replaceUnrecoverableWorktree(
ctx context.Context,
existing *Worktree,
req CreateRequest,
branchErr *BranchUnrecoverableError,
) (*Worktree, error) {
if existing == nil {
return nil, branchErr
}
replacementReq, err := replacementRequest(existing, req)
if err != nil {
return nil, err
}
baseRef, fallbackWarning, fallbackDetail, err := m.resolveBaseRefWithFallback(ctx, &replacementReq)
if err != nil {
return nil, fmt.Errorf("resolve replacement base branch: %w", err)
}
branchName, worktreePath, err := m.replacementTarget(ctx, replacementReq)
if err != nil {
return nil, err
}
if _, err := m.gitAddWorktree(ctx, replacementReq.RepositoryPath, branchName, worktreePath, baseRef); err != nil {
return nil, fmt.Errorf("create replacement worktree for %q: %w", branchErr.BranchName(), err)
}
replacement := replacementRecord(existing, replacementReq, branchName, worktreePath, fallbackWarning, fallbackDetail)
if err := m.persistReplacementWorktree(ctx, &replacement); err != nil {
if cleanupErr := m.cleanupFailedReplacement(ctx, &replacement); cleanupErr != nil {
return nil, errors.Join(err, fmt.Errorf("cleanup replacement after persistence failure: %w", cleanupErr))
}
return nil, err
}
m.copyConfiguredFiles(ctx, replacementReq, &replacement)
m.runWorktreeSetupScript(ctx, &replacement, replacementReq.ScriptEnv)
m.logger.Info("replaced unrecoverable worktree branch",
zap.String("session_id", replacement.SessionID),
zap.String("task_id", replacement.TaskID),
zap.String("original_branch", branchErr.BranchName()),
zap.String("new_branch", replacement.Branch),
zap.String("path", replacement.Path))
return &replacement, nil
}
// cleanupFailedReplacement removes the physical checkout and the branch that
// gitAddWorktree created before the replacement record could be persisted. The
// original record remains authoritative when this compensation runs.
func (m *Manager) cleanupFailedReplacement(ctx context.Context, replacement *Worktree) error {
if replacement == nil {
return nil
}
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), m.inspectTimeout)
defer cancel()
var cleanupErrs []error
if err := m.removeWorktreeDir(cleanupCtx, replacement.Path, replacement.RepositoryPath); err != nil {
cleanupErrs = append(cleanupErrs, fmt.Errorf("remove replacement worktree: %w", err))
}
if err := m.cleanupFailedReplacementBranch(cleanupCtx, replacement); err != nil {
cleanupErrs = append(cleanupErrs, err)
}
return errors.Join(cleanupErrs...)
}
func (m *Manager) cleanupFailedReplacementBranch(ctx context.Context, replacement *Worktree) error {
branchRef := "refs/heads/" + replacement.Branch
exists, err := m.branchExists(ctx, replacement.RepositoryPath, branchRef)
if err != nil {
return fmt.Errorf("verify replacement branch: %w", err)
}
if !exists {
return nil
}
output, err := m.runBoundedGitInspect(
ctx,
replacement.RepositoryPath,
"rev-parse",
"--verify",
branchRef+"^{commit}",
)
if err != nil {
return fmt.Errorf("resolve replacement branch: %w", err)
}
_, err = deleteBranchRefIfOwned(ctx, replacement.RepositoryPath, newBranchAddSnapshot{
branchRef: branchRef,
branchOID: strings.TrimSpace(output),
})
if err != nil {
return fmt.Errorf("delete replacement branch: %w", err)
}
return nil
}
func replacementRequest(existing *Worktree, req CreateRequest) (CreateRequest, error) {
replacementReq := req
if replacementReq.BaseBranch == "" {
replacementReq.BaseBranch = existing.BaseBranch
}
if replacementReq.TaskDirName == "" {
replacementReq.TaskDirName = existing.TaskDirName
}
if replacementReq.TaskEnvironmentID == "" {
replacementReq.TaskEnvironmentID = existing.TaskEnvironmentID
}
if replacementReq.BaseBranch == "" || replacementReq.TaskDirName == "" || replacementReq.RepoName == "" {
return CreateRequest{}, fmt.Errorf("replace unrecoverable worktree: %w", ErrTaskDirRequired)
}
return replacementReq, nil
}
func replacementRecord(
existing *Worktree,
req CreateRequest,
branchName, worktreePath, fallbackWarning, fallbackDetail string,
) Worktree {
identitySlug := existing.BranchSlug
if identitySlug == "" {
identitySlug = requestBranchIdentitySlug(req)
}
replacement := *existing
replacement.TaskDirName = req.TaskDirName
replacement.TaskEnvironmentID = req.TaskEnvironmentID
replacement.BranchSlug = identitySlug
replacement.RepositoryPath = req.RepositoryPath
replacement.Path = worktreePath
replacement.Branch = branchName
replacement.BaseBranch = req.BaseBranch
replacement.Status = StatusActive
replacement.DeletedAt = nil
replacement.FetchWarning = ""
replacement.FetchWarningDetail = ""
replacement.BaseBranchFallbackWarning = fallbackWarning
replacement.BaseBranchFallbackDetail = fallbackDetail
replacement.UpdatedAt = time.Now()
if replacement.SessionID == "" {
replacement.SessionID = req.SessionID
}
if replacement.TaskID == "" {
replacement.TaskID = req.TaskID
}
return replacement
}
func (m *Manager) persistReplacementWorktree(ctx context.Context, replacement *Worktree) error {
if m.store != nil {
if err := m.store.UpdateWorktree(ctx, replacement); err != nil {
return fmt.Errorf("persist replacement worktree: %w", err)
}
}
if replacement.SessionID != "" {
m.mu.Lock()
m.worktrees[cacheKey(replacement.SessionID, replacement.RepositoryID, replacement.BranchSlug)] = replacement
m.mu.Unlock()
}
return nil
}
func (m *Manager) replacementTarget(ctx context.Context, req CreateRequest) (string, string, error) {
_, branchBase := m.buildWorktreeNames(req)
for attempt := 0; attempt < replacementBranchAttempts; attempt++ {
branchName := replacementBranchName(branchBase, attempt)
exists, err := m.branchExists(ctx, req.RepositoryPath, branchName)
if err != nil {
return "", "", fmt.Errorf("check replacement branch %q: %w", branchName, err)
}
if exists {
continue
}
path, err := m.replacementPath(req, branchName)
if err != nil {
return "", "", err
}
if _, err := os.Lstat(path); errors.Is(err, os.ErrNotExist) {
return branchName, path, nil
} else if err != nil {
return "", "", fmt.Errorf("inspect replacement worktree path: %w", err)
}
}
return "", "", fmt.Errorf("unable to find a unique replacement branch after %d attempts: %w", replacementBranchAttempts, ErrBranchExists)
}
func replacementBranchName(branchBase string, attempt int) string {
if attempt == 0 {
return branchBase
}
return branchBase + "-" + SmallSuffix(3)
}
func (m *Manager) replacementPath(req CreateRequest, branchName string) (string, error) {
pathReq := req
pathReq.BranchSlug = SanitizeBranchSlug(branchName)
pathReq.BranchIdentitySlug = requestBranchIdentitySlug(req)
path, err := m.prepareTaskWorktreePath(pathReq)
if err != nil {
return "", fmt.Errorf("prepare replacement worktree path: %w", err)
}
return path, nil
}
@@ -28,6 +28,140 @@ func TestCreate_ReuseRequiredRejectsMissingCanonicalWorktree(t *testing.T) {
}
}
func TestCreate_ReuseRequiredReportsUnrecoverableBranch(t *testing.T) {
repoPath := initGitRepoWithRemote(t)
runGit(t, repoPath, "push", "origin", "--delete", "feature/pr-branch")
runGit(t, repoPath, "branch", "-D", "feature/pr-branch")
runGit(t, repoPath, "fetch", "--prune", "origin")
store := newMockStore()
store.worktrees["canonical-worktree"] = &Worktree{
ID: "canonical-worktree",
TaskID: "task-1",
TaskEnvironmentID: "environment-1",
RepositoryID: "repository-1",
Path: filepath.Join(t.TempDir(), "missing-worktree"),
Branch: "feature/pr-branch",
Status: StatusActive,
}
mgr, err := NewManager(newTestConfig(t), store, newTestLogger())
if err != nil {
t.Fatalf("NewManager() error = %v", err)
}
_, err = mgr.Create(context.Background(), CreateRequest{
TaskID: "task-1",
TaskEnvironmentID: "environment-1",
RepositoryID: "repository-1",
RepositoryPath: repoPath,
BaseBranch: "main",
WorktreeID: "canonical-worktree",
ReuseRequired: true,
})
if !errors.Is(err, ErrBranchUnrecoverable) {
t.Fatalf("Create() error = %v, want ErrBranchUnrecoverable", err)
}
if !errors.Is(err, ErrReuseWorktreeUnavailable) {
t.Fatalf("Create() error = %v, want ErrReuseWorktreeUnavailable context", err)
}
var branchErr *BranchUnrecoverableError
if !errors.As(err, &branchErr) || branchErr.BranchName() != "feature/pr-branch" {
t.Fatalf("Create() error = %v, want branch-specific unrecoverable error", err)
}
}
func TestCreate_ReuseRequiredDoesNotReportBranchLossWhenTrackingRefWasPruned(t *testing.T) {
repoPath := initGitRepoWithRemote(t)
runGit(t, repoPath, "update-ref", "-d", "refs/remotes/origin/feature/pr-branch")
runGit(t, repoPath, "branch", "-D", "feature/pr-branch")
store := newMockStore()
store.worktrees["canonical-worktree"] = &Worktree{
ID: "canonical-worktree",
TaskID: "task-1",
TaskEnvironmentID: "environment-1",
RepositoryID: "repository-1",
Path: filepath.Join(t.TempDir(), "missing-worktree"),
Branch: "feature/pr-branch",
Status: StatusActive,
}
mgr, err := NewManager(newTestConfig(t), store, newTestLogger())
if err != nil {
t.Fatalf("NewManager() error = %v", err)
}
_, err = mgr.Create(context.Background(), CreateRequest{
TaskID: "task-1",
TaskEnvironmentID: "environment-1",
RepositoryID: "repository-1",
RepositoryPath: repoPath,
BaseBranch: "main",
WorktreeID: "canonical-worktree",
ReuseRequired: true,
})
if !errors.Is(err, ErrReuseWorktreeUnavailable) {
t.Fatalf("Create() error = %v, want ErrReuseWorktreeUnavailable", err)
}
if errors.Is(err, ErrBranchUnrecoverable) {
t.Fatalf("Create() misclassified a branch that still exists on origin as unrecoverable: %v", err)
}
}
func TestCreate_ReuseRequiredDoesNotReportBranchLossWhenRemoteProbeFails(t *testing.T) {
scriptDir := writeFakeGitScript(t, `
case "${1:-}" in
rev-parse)
exit 1
;;
ls-remote)
echo "fatal: Authentication failed" >&2
exit 128
;;
*)
exit 0
;;
esac`)
t.Setenv("PATH", scriptDir+string(os.PathListSeparator)+os.Getenv("PATH"))
repoPath := t.TempDir()
if err := os.MkdirAll(filepath.Join(repoPath, ".git"), 0755); err != nil {
t.Fatalf("create fake repository: %v", err)
}
store := newMockStore()
store.worktrees["canonical-worktree"] = &Worktree{
ID: "canonical-worktree",
TaskID: "task-1",
TaskEnvironmentID: "environment-1",
RepositoryID: "repository-1",
Path: filepath.Join(t.TempDir(), "missing-worktree"),
Branch: "feature/pr-branch",
Status: StatusActive,
}
mgr, err := NewManager(newTestConfig(t), store, newTestLogger())
if err != nil {
t.Fatalf("NewManager() error = %v", err)
}
_, err = mgr.Create(context.Background(), CreateRequest{
TaskID: "task-1",
TaskEnvironmentID: "environment-1",
RepositoryID: "repository-1",
RepositoryPath: repoPath,
BaseBranch: "main",
WorktreeID: "canonical-worktree",
ReuseRequired: true,
})
if !errors.Is(err, ErrReuseWorktreeUnavailable) {
t.Fatalf("Create() error = %v, want ErrReuseWorktreeUnavailable", err)
}
if errors.Is(err, ErrBranchUnrecoverable) {
t.Fatalf("Create() misclassified an authentication failure as branch loss: %v", err)
}
if !errors.Is(err, ErrAuthFailed) {
t.Fatalf("Create() error = %v, want ErrAuthFailed from the remote probe", err)
}
}
// TestCreate_RecreatesPersistedWorktreeWhenTasksBaseWasRemoved verifies that
// normal reuse treats a removed managed tasks root as a missing worktree. The
// persisted task-root identity still identifies the original safe slot, so the
@@ -1042,6 +1042,9 @@ esac
if !errors.Is(err, ErrInvalidBaseBranch) {
t.Fatalf("error = %v, want ErrInvalidBaseBranch", err)
}
if !errors.Is(err, ErrRemoteRefMissing) {
t.Fatalf("error = %v, want confirmed remote-ref-missing sentinel", err)
}
}
func TestFetchBranchToLocal_FetchFailsNoBranch(t *testing.T) {
@@ -160,6 +160,12 @@ type CreateRequest struct {
// recreate a worktree in this mode.
ReuseRequired bool
// AllowBranchReplacement explicitly permits recovery to create a new branch
// when the persisted worktree branch no longer exists. It is only set by the
// user-selected resume-new-branch action; ordinary resume keeps the original
// branch and returns ErrBranchUnrecoverable.
AllowBranchReplacement bool
// TaskTitle is the human-readable task title (optional).
// If provided, it will be used to generate semantic worktree/branch names.
// The title is sanitized and truncated to 20 characters.
@@ -4,6 +4,7 @@ import { useAppStore } from "@/components/state-provider";
import { useEnsureTaskSession } from "@/hooks/use-ensure-task-session";
import { useSessionResumption } from "@/hooks/domains/session/use-session-resumption";
import { PassthroughTerminal } from "@/components/task/passthrough-terminal";
import { SessionRecoveryFeedback } from "@/components/task/ensure-session-error";
import type { QuickChatSession } from "@/lib/state/slices/ui/types";
import { QuickChatContent } from "./quick-chat-content";
import { useTranslation } from "react-i18next";
@@ -32,23 +33,38 @@ export function QuickChatSessionView({ session, onInitialPromptSent }: QuickChat
useEnsureTaskSession(session.sessionId);
const taskSession = useAppStore((state) => state.taskSessions.items[session.sessionId] ?? null);
const taskId = taskSession ? (session.taskId ?? taskSession.task_id ?? null) : null;
useSessionResumption(taskId, session.sessionId);
const resumption = useSessionResumption(taskId, session.sessionId);
const isPassthrough = useIsQuickChatPassthrough(session.sessionId);
const recoveryFeedback = (
<SessionRecoveryFeedback
error={resumption.error}
notice={resumption.notice}
onRetry={() => void resumption.resumeSession()}
/>
);
if (isPassthrough) {
return (
<div className="min-h-0 flex-1 overflow-hidden">
<PassthroughTerminal key={session.sessionId} sessionId={session.sessionId} mode="agent" />
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
{recoveryFeedback}
<div className="min-h-0 flex-1">
<PassthroughTerminal key={session.sessionId} sessionId={session.sessionId} mode="agent" />
</div>
</div>
);
}
const isConfig = session.kind === "config";
return (
<QuickChatContent
sessionId={session.sessionId}
minimalToolbar={isConfig}
placeholderOverride={isConfig ? t("chat:configChatPlaceholder") : undefined}
initialPrompt={session.initialPrompt}
onInitialPromptSent={onInitialPromptSent}
/>
<div className="flex min-h-0 flex-1 flex-col">
{recoveryFeedback}
<div className="min-h-0 flex-1">
<QuickChatContent
sessionId={session.sessionId}
minimalToolbar={isConfig}
placeholderOverride={isConfig ? t("chat:configChatPlaceholder") : undefined}
initialPrompt={session.initialPrompt}
onInitialPromptSent={onInitialPromptSent}
/>
</div>
</div>
);
}
@@ -9,6 +9,7 @@ import type { MCPAttachmentHistory } from "@/lib/state/slices/session-runtime/ty
import type { EntityReference } from "@/lib/types/entity-reference";
import { useChatInputContainer } from "./use-chat-input-container";
import { SessionStoppedBanner } from "./session-stopped-banner";
import { useSessionRecoveryActions } from "@/hooks/domains/session/use-session-recovery-actions";
import {
ChatInputBody,
type ChatInputContextAreaProps,
@@ -279,6 +280,7 @@ function useChatPromptEnhancement({
}
export const ChatInputContainer = forwardRef<ChatInputContainerHandle, ChatInputContainerProps>(
// eslint-disable-next-line complexity -- top-level component chooses the stopped or editor surface after shared hook setup.
function ChatInputContainer(props, ref) {
const { sessionId, taskId, taskTitle, taskDescription, isAgentBusy, isStarting, isSending } =
props;
@@ -312,6 +314,11 @@ export const ChatInputContainer = forwardRef<ChatInputContainerHandle, ChatInput
onSubmit: props.onSubmit,
});
const recoveryActions = useSessionRecoveryActions({
taskId: taskId ?? "",
sessionId: sessionId ?? "",
});
const promptEnhancement = useChatPromptEnhancement({
inputRef: s.inputRef,
taskId,
@@ -329,6 +336,7 @@ export const ChatInputContainer = forwardRef<ChatInputContainerHandle, ChatInput
taskId={taskId}
sessionId={sessionId}
workspaceId={props.workspaceId}
recoveryActions={recoveryActions}
{...buildStoppedBannerProps(props)}
/>
);
@@ -0,0 +1,167 @@
"use client";
import { useCallback, useState, type ElementType, type ReactElement } from "react";
import {
IconAlertTriangle,
IconArchive,
IconGitCommit,
IconPlayerPlay,
IconRefresh,
IconSparkles,
IconTrash,
IconX,
} from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { cn } from "@/lib/utils";
import { getWebSocketClient } from "@/lib/ws/connection";
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
import { useArchiveAndSwitchTask } from "@/hooks/use-task-actions";
import { useTaskRemoval } from "@/hooks/use-task-removal";
import { deleteTask } from "@/lib/api/domains/kanban-api";
import type { MessageAction } from "@/components/task/chat/types";
export const ACTION_ICON_MAP: Record<string, ElementType> = {
archive: IconArchive,
trash: IconTrash,
refresh: IconRefresh,
"player-play": IconPlayerPlay,
sparkles: IconSparkles,
"git-commit": IconGitCommit,
"alert-triangle": IconAlertTriangle,
x: IconX,
};
export function ActionButtons({
actions,
taskId,
onRecoveryRequested,
compact = false,
labelOverride,
}: {
actions: MessageAction[];
taskId?: string;
onRecoveryRequested?: () => void;
compact?: boolean;
labelOverride?: string;
}) {
return (
<div
className={cn(
compact
? "flex shrink-0 items-center"
: "mt-2 flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center",
)}
>
{actions.map((action, i) => (
<ActionButton
key={action.test_id ?? i}
action={action}
messageTaskId={taskId}
onCompleted={onRecoveryRequested}
compact={compact}
labelOverride={labelOverride}
/>
))}
</div>
);
}
export function ActionButton({
action,
messageTaskId,
onCompleted,
compact = false,
labelOverride,
}: {
action: MessageAction;
messageTaskId?: string;
onCompleted?: () => void;
compact?: boolean;
labelOverride?: string;
}): ReactElement | null {
const [state, setState] = useState<"idle" | "busy" | "done" | "error">("idle");
const activeTaskId = useAppStore((s) => s.tasks.activeTaskId);
const taskId = messageTaskId || activeTaskId;
const store = useAppStoreApi();
const archiveAndSwitch = useArchiveAndSwitchTask();
const { removeTaskFromBoard } = useTaskRemoval({ store });
const execute = useCallback(async () => {
if (state === "busy") return;
setState("busy");
try {
switch (action.type) {
case "archive_task": {
if (taskId) await archiveAndSwitch(taskId);
break;
}
case "delete_task": {
if (taskId) {
const { activeTaskId, activeSessionId } = store.getState().tasks;
await deleteTask(taskId);
await removeTaskFromBoard(taskId, {
wasActiveTaskId: activeTaskId,
wasActiveSessionId: activeSessionId,
});
}
break;
}
case "ws_request": {
const client = getWebSocketClient();
const params = action.params as
| { method: string; payload: Record<string, unknown> }
| undefined;
// i18n-exempt: technical error for unavailable WebSocket recovery client.
if (!client || !params) throw new Error("WebSocket recovery request is unavailable");
await client.request(params.method, params.payload);
break;
}
}
setState("done");
if (action.type === "ws_request") onCompleted?.();
} catch {
setState("error");
setTimeout(() => setState("idle"), 3000);
}
}, [action, state, taskId, store, archiveAndSwitch, removeTaskFromBoard, onCompleted]);
// Once a ws_request has been fired, hide this button: it's no longer
// actionable. If the recovery succeeds the whole ActionMessage unmounts via
// isSessionActive; if it fails, a newer status/error message renders fresh
// buttons, so this stale one would just confuse the user.
if (state === "done" && action.type === "ws_request") return null;
const Icon = action.icon ? ACTION_ICON_MAP[action.icon] : null;
const disabled = state === "busy" || state === "done";
const isDestructive = action.variant === "destructive";
const button = (
<Button
variant={compact ? "ghost" : "outline"}
size="sm"
className={cn(
compact
? "h-auto min-h-11 shrink-0 px-2 text-xs cursor-pointer sm:min-h-8"
: "h-auto min-h-11 w-full gap-1.5 text-xs cursor-pointer sm:min-h-8 sm:w-auto",
isDestructive && "text-destructive hover:text-destructive",
)}
disabled={disabled}
onClick={execute}
data-testid={action.test_id}
>
{Icon && <Icon className="h-3 w-3" />}
{labelOverride ?? action.label}
</Button>
);
if (action.tooltip) {
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent side="top">{action.tooltip}</TooltipContent>
</Tooltip>
);
}
return button;
}
@@ -11,6 +11,7 @@ import {
type TaskSessionState,
} from "@/lib/types/http";
import type { AppState } from "@/lib/state/store";
import { WebSocketRequestError } from "@/lib/ws/client";
const requestMock = vi.fn().mockResolvedValue({});
@@ -26,6 +27,8 @@ afterEach(() => {
const RECOVERY_MESSAGE = "Agent encountered an error";
const RESUME_TEST_ID = "recovery-resume-button";
const FRESH_TEST_ID = "recovery-fresh-button";
const BRANCH_FAILURE_MESSAGE = "The saved branch is no longer available.";
const RECOVERY_ERROR_TEST_ID = "session-recovery-error";
const TEST_SESSION_ID = "sess-1";
const TEST_TASK_ID = "task-1";
const FAILED_AT = "2026-05-30T00:00:00Z";
@@ -174,6 +177,90 @@ describe("ActionMessage — recovery card retires once the agent is back", () =>
expect(screen.queryByTestId(RESUME_TEST_ID)).toBeNull();
expect(screen.queryByTestId(FRESH_TEST_ID)).toBeNull();
});
it("keeps a typed branch failure visible with explicit recovery choices", async () => {
requestMock.mockRejectedValueOnce(
new WebSocketRequestError(BRANCH_FAILURE_MESSAGE, "CONFLICT", {
kind: "branch_unrecoverable",
recovery_action: "resume_new_branch",
original_branch: "feature/lost",
base_branch: "main",
}),
);
renderWithTranscript("WAITING_FOR_INPUT", []);
fireEvent.click(screen.getByTestId(RESUME_TEST_ID));
expect(await screen.findByTestId(RECOVERY_ERROR_TEST_ID)).toBeTruthy();
expect(screen.getByText(BRANCH_FAILURE_MESSAGE)).toBeTruthy();
expect(screen.getByTestId("recovery-new-branch-button")).toBeTruthy();
expect(screen.getByTestId("recovery-restore-workspace-button")).toBeTruthy();
});
it("retains both causes when manual resume and read-only restore fail", async () => {
requestMock
.mockRejectedValueOnce(
new WebSocketRequestError(BRANCH_FAILURE_MESSAGE, "CONFLICT", {
kind: "branch_unrecoverable",
recovery_action: "resume_new_branch",
original_branch: "feature/lost",
base_branch: "main",
}),
)
.mockRejectedValueOnce(new Error("Workspace restore failed."));
renderWithTranscript("WAITING_FOR_INPUT", []);
fireEvent.click(screen.getByTestId(RESUME_TEST_ID));
expect(await screen.findByTestId(RECOVERY_ERROR_TEST_ID)).toBeTruthy();
fireEvent.click(screen.getByTestId("recovery-restore-workspace-button"));
const recoveryError = await screen.findByTestId(RECOVERY_ERROR_TEST_ID);
expect(recoveryError.textContent).toContain(`Resume failed: ${BRANCH_FAILURE_MESSAGE}`);
expect(recoveryError.textContent).toContain(
"Workspace restore failed: Workspace restore failed.",
);
expect(screen.getByTestId("recovery-new-branch-button")).toBeTruthy();
});
it("does not offer branch continuation for an ordinary recovery failure", async () => {
requestMock.mockRejectedValueOnce(new Error("Provider is unavailable"));
renderWithTranscript("WAITING_FOR_INPUT", []);
fireEvent.click(screen.getByTestId(RESUME_TEST_ID));
expect(await screen.findByText("Provider is unavailable")).toBeTruthy();
expect(screen.queryByTestId("recovery-new-branch-button")).toBeNull();
expect(screen.getByTestId("recovery-restore-workspace-button")).toBeTruthy();
});
});
describe("ActionMessage recovery retry", () => {
it("disables Retry while a repeated recovery request is pending", async () => {
let resolveRetry: (() => void) | undefined;
requestMock.mockRejectedValueOnce(new Error("Initial resume failed")).mockImplementationOnce(
() =>
new Promise<void>((resolve) => {
resolveRetry = resolve;
}),
);
renderWithTranscript("WAITING_FOR_INPUT", []);
fireEvent.click(screen.getByTestId(RESUME_TEST_ID));
expect(await screen.findByTestId(RECOVERY_ERROR_TEST_ID)).toBeTruthy();
fireEvent.click(screen.getByTestId("ensure-session-error-retry"));
await waitFor(() =>
expect((screen.getByTestId("ensure-session-error-retry") as HTMLButtonElement).disabled).toBe(
true,
),
);
fireEvent.click(screen.getByTestId("ensure-session-error-retry"));
expect(requestMock).toHaveBeenCalledTimes(2);
resolveRetry?.();
await waitFor(() => expect(screen.queryByTestId(RECOVERY_ERROR_TEST_ID)).toBeNull());
});
});
/** Renders the card with a live store handle so a spec can land transcript rows and
@@ -0,0 +1,153 @@
"use client";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@kandev/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import {
EnsureSessionErrorBanner,
SessionRecoveryNotice,
} from "@/components/task/ensure-session-error";
import {
useSessionRecoveryActions,
type SessionRecoveryBusyAction,
} from "@/hooks/domains/session/use-session-recovery-actions";
import type { SessionRecoveryAction } from "@/lib/services/session-recovery-service";
import type { MessageAction } from "@/components/task/chat/types";
import { ACTION_ICON_MAP, ActionButton } from "./action-message-actions";
export function sessionRecoveryAction(action: MessageAction): SessionRecoveryAction | null {
if (action.type !== "ws_request" || !action.params) return null;
if (action.params.method !== "session.recover") return null;
const payload = action.params.payload;
if (!payload || typeof payload !== "object") return null;
const recoveryAction = (payload as { action?: unknown }).action;
switch (recoveryAction) {
case "resume":
case "resume_new_branch":
case "fresh_start":
case "runtime_retry":
return recoveryAction;
default:
return null;
}
}
export function SessionRecoveryActionButtons({
actions,
taskId,
sessionId,
onRecoveryRequested,
}: {
actions: MessageAction[];
taskId: string;
sessionId: string;
onRecoveryRequested: () => void;
}) {
const { t } = useTranslation();
const {
busyAction,
recoveryError,
branchDetails,
recoveryNotice,
handleRecover,
handleRestore,
handleRetry,
handleNewBranch,
} = useSessionRecoveryActions({ taskId, sessionId });
const onRecoveryAction = useCallback(
async (action: SessionRecoveryAction) => {
if (await handleRecover(action)) onRecoveryRequested();
},
[handleRecover, onRecoveryRequested],
);
const onRetry = useCallback(async () => {
if (await handleRetry()) onRecoveryRequested();
}, [handleRetry, onRecoveryRequested]);
const restoreAction = {
label: t("task:restoreReadOnlyWorkspace"),
onClick: () => void handleRestore(),
testId: "recovery-restore-workspace-button",
disabled: busyAction !== null,
};
return (
<>
{recoveryError ? (
<EnsureSessionErrorBanner
error={recoveryError}
onRetry={() => void onRetry()}
retryDisabled={busyAction !== null}
compact
action={
branchDetails
? {
label: t("task:continueOnNewBranch"),
onClick: () =>
void handleNewBranch().then((success) => {
if (success) onRecoveryRequested();
}),
testId: "recovery-new-branch-button",
disabled: busyAction !== null,
}
: restoreAction
}
secondaryAction={branchDetails ? restoreAction : undefined}
testId="session-recovery-error"
/>
) : null}
{recoveryNotice ? <SessionRecoveryNotice message={recoveryNotice} /> : null}
<div className="mt-2 flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center">
{actions.map((action, i) => {
const recoveryAction = sessionRecoveryAction(action);
return recoveryAction ? (
<SessionRecoveryActionButton
key={action.test_id ?? i}
action={action}
busyAction={busyAction}
onClick={() => void onRecoveryAction(recoveryAction)}
/>
) : (
<ActionButton key={action.test_id ?? i} action={action} messageTaskId={taskId} />
);
})}
</div>
</>
);
}
function SessionRecoveryActionButton({
action,
busyAction,
onClick,
}: {
action: MessageAction;
busyAction: SessionRecoveryBusyAction;
onClick: () => void;
}) {
const Icon = action.icon ? ACTION_ICON_MAP[action.icon] : null;
const button = (
<Button
variant="outline"
size="sm"
className="h-auto min-h-11 w-full gap-1.5 text-xs cursor-pointer sm:min-h-8 sm:w-auto"
disabled={busyAction !== null}
onClick={onClick}
data-testid={action.test_id}
>
{Icon && <Icon className="h-3 w-3" />}
{action.label}
</Button>
);
if (action.tooltip) {
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent side="top">{action.tooltip}</TooltipContent>
</Tooltip>
);
}
return button;
}
@@ -1,43 +1,18 @@
"use client";
import { useState, useCallback, useEffect, useMemo, memo, type ReactElement } from "react";
import { useState, useEffect, useMemo, memo, type ReactElement } from "react";
import { Trans, useTranslation } from "react-i18next";
import {
IconAlertTriangle,
IconArchive,
IconTrash,
IconRefresh,
IconPlayerPlay,
IconSparkles,
IconGitCommit,
IconX,
} from "@tabler/icons-react";
import { IconAlertTriangle } from "@tabler/icons-react";
import { cn } from "@/lib/utils";
import { Button } from "@kandev/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { getWebSocketClient } from "@/lib/ws/connection";
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
import { useActionMessageSession, useAgentBootOutcomeAfterMessage } from "./action-message-state";
import { useArchiveAndSwitchTask } from "@/hooks/use-task-actions";
import { useTaskRemoval } from "@/hooks/use-task-removal";
import { deleteTask } from "@/lib/api/domains/kanban-api";
import type { Message, TaskSessionState } from "@/lib/types/http";
import type { MessageAction } from "@/components/task/chat/types";
import { ActionMessageDetails, type ActionMeta } from "./action-message-details";
import { formatDateTime } from "@/lib/i18n/formats";
import { parseRetryAt, retryCountdownLabel } from "./transient-retry";
import { hasSessionRecoveryResolutionAfter } from "@/hooks/processed-message-filtering";
const ICON_MAP: Record<string, React.ElementType> = {
archive: IconArchive,
trash: IconTrash,
refresh: IconRefresh,
"player-play": IconPlayerPlay,
sparkles: IconSparkles,
"git-commit": IconGitCommit,
"alert-triangle": IconAlertTriangle,
x: IconX,
};
import { ActionButtons } from "./action-message-actions";
import { SessionRecoveryActionButtons, sessionRecoveryAction } from "./action-message-recovery";
function isSessionActive(state?: TaskSessionState) {
return state === "RUNNING" || state === "STARTING" || state === "COMPLETED";
@@ -101,6 +76,7 @@ export const ActionMessage = memo(function ActionMessage({ comment }: { comment:
sessionError={sessionError}
sessionState={sessionState}
taskId={comment.task_id}
sessionId={comment.session_id}
recoveryResolved={
recoveryResolvedDurably || agentRebooted || (recoveryRequested && !recoveryFailedAgain)
}
@@ -115,6 +91,7 @@ function SettledActionMessage({
sessionError,
sessionState,
taskId,
sessionId,
recoveryResolved,
onRecoveryRequested,
}: {
@@ -123,6 +100,7 @@ function SettledActionMessage({
sessionError?: string;
sessionState?: TaskSessionState;
taskId?: string;
sessionId?: string;
recoveryResolved: boolean;
onRecoveryRequested: () => void;
}) {
@@ -141,6 +119,7 @@ function SettledActionMessage({
sessionError={sessionError}
sessionState={sessionState}
taskId={taskId}
sessionId={sessionId}
recoveryResolved={recoveryResolved}
onRecoveryRequested={onRecoveryRequested}
/>
@@ -153,6 +132,7 @@ function SettledFailureMessage({
sessionError,
sessionState,
taskId,
sessionId,
recoveryResolved,
onRecoveryRequested,
}: {
@@ -161,6 +141,7 @@ function SettledFailureMessage({
sessionError?: string;
sessionState?: TaskSessionState;
taskId?: string;
sessionId?: string;
recoveryResolved: boolean;
onRecoveryRequested: () => void;
}) {
@@ -187,7 +168,6 @@ function SettledFailureMessage({
metadata?.variant === "warning"
? "text-amber-600 dark:text-amber-400"
: "text-red-600 dark:text-red-400";
return (
<div className="w-full">
<div className="flex items-start gap-3 w-full rounded px-2 py-1 -mx-2">
@@ -197,19 +177,53 @@ function SettledFailureMessage({
<div className="flex-1 min-w-0 pt-0.5">
<div className={cn("text-xs break-words", textClass)}>{message}</div>
<ActionMessageDetails metadata={metadata} />
{metadata?.actions && metadata.actions.length > 0 && (
<ActionButtons
actions={metadata.actions}
taskId={taskId}
onRecoveryRequested={metadata.recovery_actions ? onRecoveryRequested : undefined}
/>
)}
{renderSettledActionButtons({
actions: metadata?.actions,
taskId,
sessionId,
isRecoveryMessage: metadata?.recovery_actions === true,
onRecoveryRequested,
})}
</div>
</div>
</div>
);
}
function renderSettledActionButtons({
actions,
taskId,
sessionId,
isRecoveryMessage,
onRecoveryRequested,
}: {
actions?: MessageAction[];
taskId?: string;
sessionId?: string;
isRecoveryMessage: boolean;
onRecoveryRequested: () => void;
}): ReactElement | null {
if (!actions || actions.length === 0) return null;
const hasSessionRecoveryAction = actions.some((action) => sessionRecoveryAction(action));
if (hasSessionRecoveryAction && taskId && sessionId) {
return (
<SessionRecoveryActionButtons
actions={actions}
taskId={taskId}
sessionId={sessionId}
onRecoveryRequested={onRecoveryRequested}
/>
);
}
return (
<ActionButtons
actions={actions}
taskId={taskId}
onRecoveryRequested={isRecoveryMessage ? onRecoveryRequested : undefined}
/>
);
}
function transientRetryReasonKey(failureCode?: string) {
switch (failureCode) {
case "model_capacity":
@@ -502,136 +516,3 @@ function MissingBranchRecovery({
</section>
);
}
function ActionButtons({
actions,
taskId,
onRecoveryRequested,
compact = false,
labelOverride,
}: {
actions: MessageAction[];
taskId?: string;
onRecoveryRequested?: () => void;
compact?: boolean;
labelOverride?: string;
}) {
return (
<div
className={cn(
compact
? "flex shrink-0 items-center"
: "mt-2 flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center",
)}
>
{actions.map((action, i) => (
<ActionButton
key={action.test_id ?? i}
action={action}
messageTaskId={taskId}
onCompleted={onRecoveryRequested}
compact={compact}
labelOverride={labelOverride}
/>
))}
</div>
);
}
function ActionButton({
action,
messageTaskId,
onCompleted,
compact = false,
labelOverride,
}: {
action: MessageAction;
messageTaskId?: string;
onCompleted?: () => void;
compact?: boolean;
labelOverride?: string;
}): ReactElement | null {
const [state, setState] = useState<"idle" | "busy" | "done" | "error">("idle");
const activeTaskId = useAppStore((s) => s.tasks.activeTaskId);
const taskId = messageTaskId || activeTaskId;
const store = useAppStoreApi();
const archiveAndSwitch = useArchiveAndSwitchTask();
const { removeTaskFromBoard } = useTaskRemoval({ store });
const execute = useCallback(async () => {
if (state === "busy") return;
setState("busy");
try {
switch (action.type) {
case "archive_task": {
if (taskId) await archiveAndSwitch(taskId);
break;
}
case "delete_task": {
if (taskId) {
const { activeTaskId, activeSessionId } = store.getState().tasks;
await deleteTask(taskId);
await removeTaskFromBoard(taskId, {
wasActiveTaskId: activeTaskId,
wasActiveSessionId: activeSessionId,
});
}
break;
}
case "ws_request": {
const client = getWebSocketClient();
const params = action.params as
| { method: string; payload: Record<string, unknown> }
| undefined;
if (!client || !params) throw new Error("WebSocket recovery request is unavailable");
await client.request(params.method, params.payload);
break;
}
}
setState("done");
if (action.type === "ws_request") onCompleted?.();
} catch {
setState("error");
setTimeout(() => setState("idle"), 3000);
}
}, [action, state, taskId, store, archiveAndSwitch, removeTaskFromBoard]);
// Once a ws_request has been fired, hide this button: it's no longer
// actionable. If the recovery succeeds the whole ActionMessage unmounts via
// isSessionActive; if it fails, a newer status/error message renders fresh
// buttons, so this stale one would just confuse the user.
if (state === "done" && action.type === "ws_request") return null;
const Icon = action.icon ? ICON_MAP[action.icon] : null;
const disabled = state === "busy" || state === "done";
const isDestructive = action.variant === "destructive";
const button = (
<Button
variant={compact ? "ghost" : "outline"}
size="sm"
className={cn(
compact
? "h-auto min-h-11 shrink-0 px-2 text-xs cursor-pointer sm:min-h-8"
: "h-auto min-h-11 w-full gap-1.5 text-xs cursor-pointer sm:min-h-8 sm:w-auto",
isDestructive && "text-destructive hover:text-destructive",
)}
disabled={disabled}
onClick={execute}
data-testid={action.test_id}
>
{Icon && <Icon className="h-3 w-3" />}
{labelOverride ?? action.label}
</Button>
);
if (action.tooltip) {
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent side="top">{action.tooltip}</TooltipContent>
</Tooltip>
);
}
return button;
}
@@ -43,3 +43,33 @@ describe("StatusMessage model selection warnings", () => {
expect(screen.getByText("The saved model was not advertised by the executor.")).toBeTruthy();
});
});
describe("StatusMessage branch replacement warnings", () => {
it("states that conversation history continued but lost code did not", () => {
const comment: Message = {
id: "status-branch-1",
session_id: toSessionId("session-1"),
task_id: toTaskId("task-1"),
author_type: "agent",
content: "branch_recreated",
type: "status",
created_at: "2026-08-15T00:00:00Z",
metadata: {
variant: "warning",
kind: "branch_recreated",
original_branch: "feature/lost",
new_branch: "kandev/task-recovery-1",
base_branch: "main",
},
};
render(<StatusMessage comment={comment} />);
expect(screen.getByTestId("branch-recreated-warning")).toBeTruthy();
expect(screen.getByText("feature/lost")).toBeTruthy();
expect(screen.getByText("kandev/task-recovery-1")).toBeTruthy();
expect(screen.getByText("main")).toBeTruthy();
expect(screen.getByText(/conversation history continues/i)).toBeTruthy();
expect(screen.getByText(/code changes.*not recovered/i)).toBeTruthy();
});
});
@@ -14,6 +14,8 @@ import type { StatusMetadata } from "@/components/task/chat/types";
import { useTranslation } from "react-i18next";
import { t } from "@/lib/i18n";
const UNKNOWN_TASK_KEY = "task:unknown";
interface ErrorMetadata extends StatusMetadata {
error?: string;
text?: string;
@@ -31,6 +33,9 @@ interface ErrorMetadata extends StatusMetadata {
executor_type?: string;
executor_profile_id?: string;
remediation?: string[];
original_branch?: string;
new_branch?: string;
base_branch?: string;
}
function getStatusStyle(isError: boolean, isWarning: boolean) {
@@ -181,11 +186,12 @@ function modelSelectionReasonLabel(reason: string | undefined): string {
};
return reason
? t(keyByReason[reason] ?? "task:modelSelectionReasonUnknown", { reason })
: t("task:unknown");
: t(UNKNOWN_TASK_KEY);
}
function ModelSelectionWarningDetails({ metadata }: { metadata: ErrorMetadata }) {
const requested = metadata.requested_model || t("task:unknown");
const unknown = t(UNKNOWN_TASK_KEY);
const requested = metadata.requested_model || unknown;
const effective = metadata.effective_model || t("task:modelSelectionProviderDefault");
const remediation = Array.isArray(metadata.remediation) ? metadata.remediation : [];
const remediationKey: Record<string, string> = {
@@ -243,6 +249,41 @@ function ModelSelectionWarningDetails({ metadata }: { metadata: ErrorMetadata })
);
}
function BranchRecreatedWarning({ metadata }: { metadata: ErrorMetadata }) {
const { t } = useTranslation();
const unknown = t(UNKNOWN_TASK_KEY);
const originalBranch = metadata.original_branch || unknown;
const newBranch = metadata.new_branch || unknown;
const baseBranch = metadata.base_branch || unknown;
return (
<div
className="flex items-start gap-3 rounded border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs"
data-testid="branch-recreated-warning"
>
<IconAlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-500" />
<div className="min-w-0 space-y-2 text-muted-foreground">
<p className="font-medium text-amber-600 dark:text-amber-400">
{t("task:branchRecreatedWarning")}
</p>
<div className="grid gap-1">
<p>
{t("task:branchRecreatedOriginal")}: <code>{originalBranch}</code>
</p>
<p>
{t("task:branchRecreatedNew")}: <code>{newBranch}</code>
</p>
<p>
{t("task:branchRecreatedBase")}: <code>{baseBranch}</code>
</p>
</div>
<p>{t("task:branchRecreatedConversation")}</p>
<p>{t("task:branchRecreatedCodeNotRecovered")}</p>
</div>
</div>
);
}
function computeExpandableContent(isError: boolean, metadata: ErrorMetadata | undefined) {
if (!isError)
return { hasExpandableContent: false, errorDetails: [] as { label: string; value: string }[] };
@@ -336,6 +377,9 @@ export const StatusMessage = memo(function StatusMessage({ comment }: { comment:
const [isExpanded, setIsExpanded] = useState(false);
const { metadata, progress, statusLine, message, isError, isWarning } =
parseStatusMetadata(comment);
if (metadata?.kind === "branch_recreated") {
return <BranchRecreatedWarning metadata={metadata} />;
}
const { hasExpandableContent, errorDetails } = computeExpandableContent(isError, metadata);
const isSimpleStatus =
!isError && !isWarning && progress === null && !statusLine && !metadata?.message;
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useState } from "react";
import { TooltipProvider } from "@kandev/ui/tooltip";
import type { SessionStoppedBannerProps } from "./session-stopped-banner";
import { WebSocketRequestError } from "@/lib/ws/client";
const mocks = vi.hoisted(() => ({
request: vi.fn(),
@@ -48,6 +49,10 @@ vi.mock("react-i18next", () => ({
"task:starting": "Starting...",
"task:startFreshSession": "Start fresh session",
"task:agentProfileNoLongerExists": "The agent profile no longer exists.",
"task:continueOnNewBranch": "Continue on a new branch",
"task:restoreReadOnlyWorkspace": "Restore read-only workspace",
"task:retry": "Retry",
"task:couldnTStartASession": "Session recovery failed",
})[key] ?? key,
}),
}));
@@ -59,6 +64,8 @@ const baseProps: Omit<SessionStoppedBannerProps, "mode" | "onShowDialog" | "show
sessionId: "session-1",
workspaceId: "workspace-1",
};
const RESUME_BUTTON_TEST_ID = "recovery-resume-button";
const FRESH_BUTTON_TEST_ID = "recovery-fresh-button";
function BannerHarness({
mode,
@@ -85,15 +92,15 @@ beforeEach(() => {
afterEach(cleanup);
describe("SessionStoppedBanner", () => {
describe("SessionStoppedBanner basics", () => {
it("offers only New Agent for a completed session and opens the new-session dialog", async () => {
render(<BannerHarness mode="completed" />);
expect(screen.getByTestId("completed-session-banner")).toBeTruthy();
expect(screen.getByText("This session is complete.")).toBeTruthy();
expect(screen.getByRole("button", { name: "New Agent" })).toBeTruthy();
expect(screen.queryByTestId("recovery-resume-button")).toBeNull();
expect(screen.queryByTestId("recovery-fresh-button")).toBeNull();
expect(screen.queryByTestId(RESUME_BUTTON_TEST_ID)).toBeNull();
expect(screen.queryByTestId(FRESH_BUTTON_TEST_ID)).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "New Agent" }));
@@ -126,7 +133,7 @@ describe("SessionStoppedBanner", () => {
it("keeps resume and fresh-start recovery actions for a recoverable session", async () => {
render(<BannerHarness mode="recoverable" />);
fireEvent.click(screen.getByTestId("recovery-resume-button"));
fireEvent.click(screen.getByTestId(RESUME_BUTTON_TEST_ID));
await waitFor(() =>
expect(mocks.request).toHaveBeenCalledWith(
"session.recover",
@@ -135,7 +142,7 @@ describe("SessionStoppedBanner", () => {
),
);
fireEvent.click(screen.getByTestId("recovery-fresh-button"));
fireEvent.click(screen.getByTestId(FRESH_BUTTON_TEST_ID));
await waitFor(() =>
expect(mocks.request).toHaveBeenCalledWith(
"session.recover",
@@ -149,8 +156,8 @@ describe("SessionStoppedBanner", () => {
mocks.agentProfiles.splice(0, mocks.agentProfiles.length);
render(<BannerHarness mode="recoverable" />);
expect(screen.getByTestId("recovery-resume-button").getAttribute("disabled")).not.toBeNull();
fireEvent.click(screen.getByTestId("recovery-fresh-button"));
expect(screen.getByTestId(RESUME_BUTTON_TEST_ID).getAttribute("disabled")).not.toBeNull();
fireEvent.click(screen.getByTestId(FRESH_BUTTON_TEST_ID));
expect(await screen.findByTestId("new-session-dialog")).toBeTruthy();
expect(mocks.request).not.toHaveBeenCalled();
@@ -173,3 +180,48 @@ describe("SessionStoppedBanner", () => {
expect(screen.getByRole("button", { name: "Start fresh session" })).toBeTruthy();
});
});
describe("SessionStoppedBanner recovery failures", () => {
it("keeps a typed branch error visible and offers explicit continuation", async () => {
const branchError = new WebSocketRequestError(
"The saved branch is no longer available.",
"CONFLICT",
{
kind: "branch_unrecoverable",
recovery_action: "resume_new_branch",
original_branch: "feature/lost",
base_branch: "main",
},
);
mocks.request.mockRejectedValueOnce(branchError);
render(<BannerHarness mode="recoverable" />);
fireEvent.click(screen.getByTestId(RESUME_BUTTON_TEST_ID));
expect(await screen.findByText("The saved branch is no longer available.")).toBeTruthy();
expect(screen.getByTestId("recovery-new-branch-button")).toBeTruthy();
expect(screen.getByTestId("recovery-restore-workspace-button")).toBeTruthy();
fireEvent.click(screen.getByTestId("recovery-new-branch-button"));
await waitFor(() =>
expect(mocks.request).toHaveBeenLastCalledWith(
"session.recover",
{ task_id: "task-1", session_id: "session-1", action: "resume_new_branch" },
30000,
),
);
expect(screen.queryByText("The saved branch is no longer available.")).toBeNull();
});
it("does not offer branch continuation for an ordinary resume error", async () => {
mocks.request.mockRejectedValueOnce(new Error("Provider is unavailable"));
render(<BannerHarness mode="recoverable" />);
fireEvent.click(screen.getByTestId(RESUME_BUTTON_TEST_ID));
expect(await screen.findByText("Provider is unavailable")).toBeTruthy();
expect(screen.queryByTestId("recovery-new-branch-button")).toBeNull();
expect(screen.getByTestId("recovery-restore-workspace-button")).toBeTruthy();
});
});
@@ -1,6 +1,6 @@
"use client";
import { useCallback, useState } from "react";
import { useCallback } from "react";
import {
IconAlertTriangle,
IconCircleCheck,
@@ -12,8 +12,17 @@ import { Button } from "@kandev/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useTranslation } from "react-i18next";
import { NewSessionDialog } from "@/components/task/new-session-dialog";
import {
EnsureSessionErrorBanner,
SessionRecoveryNotice,
} from "@/components/task/ensure-session-error";
import { useAppStore } from "@/components/state-provider";
import { getWebSocketClient } from "@/lib/ws/connection";
import {
useSessionRecoveryActions,
type SessionRecoveryBusyAction,
type SessionRecoveryActions,
} from "@/hooks/domains/session/use-session-recovery-actions";
import type { BranchRecoveryDetails } from "@/lib/services/session-recovery-service";
export type SessionStoppedBannerMode = "recoverable" | "completed";
@@ -28,42 +37,99 @@ export type SessionStoppedBannerProps = {
detail?: string;
resumeLabel?: string;
resumingLabel?: string;
recoveryActions?: SessionRecoveryActions;
};
async function requestSessionRecover(
taskId: string,
sessionId: string,
action: "resume" | "fresh_start",
): Promise<boolean> {
const client = getWebSocketClient();
if (!client) return false;
try {
await client.request(
"session.recover",
{ task_id: taskId, session_id: sessionId, action },
30000,
);
return true;
} catch {
return false;
}
function StoppedRecoveryFeedback({
workspaceId,
recoveryError,
recoveryNotice,
branchDetails,
busyAction,
onRetry,
onRestore,
onNewBranch,
}: {
workspaceId?: string | null;
recoveryError: Error | null;
recoveryNotice: string | null;
branchDetails: BranchRecoveryDetails | null;
busyAction: SessionRecoveryBusyAction;
onRetry: () => void;
onRestore: () => void;
onNewBranch: () => void;
}) {
const { t } = useTranslation();
if (!recoveryError && !recoveryNotice) return null;
const restoreAction = {
label: t("task:restoreReadOnlyWorkspace"),
onClick: onRestore,
testId: "recovery-restore-workspace-button",
disabled: busyAction !== null,
};
return (
<>
{recoveryError ? (
<EnsureSessionErrorBanner
error={recoveryError}
onRetry={onRetry}
retryDisabled={busyAction !== null}
workspaceId={workspaceId}
compact
action={
branchDetails
? {
label: t("task:continueOnNewBranch"),
onClick: onNewBranch,
testId: "recovery-new-branch-button",
disabled: busyAction !== null,
}
: restoreAction
}
secondaryAction={branchDetails ? restoreAction : undefined}
testId="session-recovery-error"
/>
) : null}
{recoveryNotice ? <SessionRecoveryNotice message={recoveryNotice} /> : null}
</>
);
}
function RecoverableSessionActions({
onShowDialog,
taskId,
sessionId,
workspaceId,
resumeLabel,
resumingLabel,
recoveryActions,
}: Pick<
SessionStoppedBannerProps,
"onShowDialog" | "taskId" | "sessionId" | "resumeLabel" | "resumingLabel"
| "onShowDialog"
| "taskId"
| "sessionId"
| "workspaceId"
| "resumeLabel"
| "resumingLabel"
| "recoveryActions"
>) {
const { t } = useTranslation();
const resumeText = resumeLabel ?? t("task:resume");
const resumingText = resumingLabel ?? t("task:resuming");
const [isResuming, setIsResuming] = useState(false);
const [isStartingFresh, setIsStartingFresh] = useState(false);
const localRecoveryActions = useSessionRecoveryActions({
taskId: taskId ?? "",
sessionId: sessionId ?? "",
});
const {
busyAction,
recoveryError,
branchDetails,
recoveryNotice,
handleRecover,
handleRestore,
handleRetry,
handleNewBranch,
} = recoveryActions ?? localRecoveryActions;
const profileExists = useAppStore((s) => {
if (!sessionId) return false;
@@ -73,26 +139,63 @@ function RecoverableSessionActions({
);
});
const handleRecover = useCallback(
async (action: "resume" | "fresh_start") => {
if (!sessionId || !taskId) return;
const setBusy = action === "resume" ? setIsResuming : setIsStartingFresh;
setBusy(true);
const ok = await requestSessionRecover(taskId, sessionId, action);
if (!ok) setBusy(false);
},
[sessionId, taskId],
);
const handleResume = useCallback(() => handleRecover("resume"), [handleRecover]);
const handleResume = useCallback(() => {
if (taskId && sessionId) void handleRecover("resume");
}, [handleRecover, sessionId, taskId]);
const handleFreshStart = useCallback(() => {
if (!profileExists) {
onShowDialog(true);
return;
}
void handleRecover("fresh_start");
if (taskId && sessionId) void handleRecover("fresh_start");
}, [profileExists, onShowDialog, handleRecover]);
return (
<div className="flex w-full flex-col gap-2 sm:w-auto">
<StoppedRecoveryFeedback
workspaceId={workspaceId}
recoveryError={recoveryError}
recoveryNotice={recoveryNotice}
branchDetails={branchDetails}
busyAction={busyAction}
onRetry={handleRetry}
onRestore={() => void handleRestore()}
onNewBranch={handleNewBranch}
/>
<RecoverableSessionButtons
taskId={taskId}
sessionId={sessionId}
profileExists={profileExists}
busyAction={busyAction}
resumeText={resumeText}
resumingText={resumingText}
onResume={handleResume}
onFreshStart={handleFreshStart}
/>
</div>
);
}
function RecoverableSessionButtons({
taskId,
sessionId,
profileExists,
busyAction,
resumeText,
resumingText,
onResume,
onFreshStart,
}: {
taskId: string | null;
sessionId: string | null;
profileExists: boolean;
busyAction: SessionRecoveryBusyAction;
resumeText: string;
resumingText: string;
onResume: () => void;
onFreshStart: () => void;
}) {
const { t } = useTranslation();
return (
<div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
{sessionId && taskId && (
@@ -107,11 +210,11 @@ function RecoverableSessionActions({
size="sm"
data-testid="recovery-resume-button"
className="min-h-11 w-full shrink-0 gap-1.5 cursor-pointer sm:w-auto"
onClick={handleResume}
disabled={isResuming || !profileExists}
onClick={onResume}
disabled={busyAction !== null || !profileExists}
>
<IconPlayerPlay className="h-3.5 w-3.5" />
{isResuming ? resumingText : resumeText}
{busyAction === "resume" ? resumingText : resumeText}
</Button>
</span>
</TooltipTrigger>
@@ -124,12 +227,12 @@ function RecoverableSessionActions({
variant="outline"
size="sm"
className="min-h-11 w-full shrink-0 gap-1.5 cursor-pointer sm:w-auto"
onClick={handleFreshStart}
disabled={isStartingFresh}
onClick={onFreshStart}
disabled={busyAction !== null}
data-testid="recovery-fresh-button"
>
<IconRefresh className="h-3.5 w-3.5" />
{isStartingFresh ? t("task:starting") : t("task:startFreshSession")}
{busyAction === "fresh_start" ? t("task:starting") : t("task:startFreshSession")}
</Button>
</div>
);
@@ -146,6 +249,7 @@ export function SessionStoppedBanner({
detail,
resumeLabel,
resumingLabel,
recoveryActions,
}: SessionStoppedBannerProps) {
const { t } = useTranslation();
const isCompleted = mode === "completed";
@@ -192,8 +296,10 @@ export function SessionStoppedBanner({
onShowDialog={onShowDialog}
taskId={taskId}
sessionId={sessionId}
workspaceId={workspaceId}
resumeLabel={resumeLabel}
resumingLabel={resumingLabel}
recoveryActions={recoveryActions}
/>
)}
</div>
@@ -82,6 +82,22 @@ describe("EnsureSessionErrorBanner", () => {
fireEvent.click(screen.getByTestId("ensure-session-error-retry"));
expect(onRetry).toHaveBeenCalledTimes(1);
});
it("disables retry while another recovery action is pending", () => {
const onRetry = vi.fn();
render(
<EnsureSessionErrorBanner
error={new Error("recovery pending")}
onRetry={onRetry}
retryDisabled
/>,
);
const retry = screen.getByTestId("ensure-session-error-retry") as HTMLButtonElement;
expect(retry.disabled).toBe(true);
fireEvent.click(retry);
expect(onRetry).not.toHaveBeenCalled();
});
});
describe("EnsureSessionErrorEmptyState", () => {
@@ -1,11 +1,12 @@
"use client";
import Link from "@/components/routing/app-link";
import { IconAlertTriangle, IconRefresh } from "@tabler/icons-react";
import { IconAlertTriangle, IconInfoCircle, IconRefresh } from "@tabler/icons-react";
import { Alert, AlertDescription, AlertTitle } from "@kandev/ui/alert";
import { Button } from "@kandev/ui/button";
import { useTranslation } from "react-i18next";
import { t } from "@/lib/i18n";
import { cn } from "@/lib/utils";
// EnsureSessionErrorInfo wraps a parsed ensure error so UI can offer a targeted action for the missing-agent-profile case.
export type EnsureSessionErrorInfo = {
@@ -47,19 +48,40 @@ export function describeEnsureError(
};
}
type RecoveryAction = {
label: string;
onClick: () => void;
testId: string;
disabled?: boolean;
};
type BannerProps = {
error: Error | null;
onRetry: () => void;
workspaceId?: string | null;
action?: RecoveryAction;
secondaryAction?: RecoveryAction;
retryDisabled?: boolean;
testId?: string;
compact?: boolean;
};
/** Slim banner for the task page, rendered above the layout. */
export function EnsureSessionErrorBanner({ error, onRetry, workspaceId }: BannerProps) {
export function EnsureSessionErrorBanner({
error,
onRetry,
workspaceId,
action,
secondaryAction,
retryDisabled,
testId = "ensure-session-error-banner",
compact = false,
}: BannerProps) {
const { t } = useTranslation();
const info = describeEnsureError(error, workspaceId);
if (!info) return null;
return (
<div className="px-3 pt-2" data-testid="ensure-session-error-banner">
<div className={cn(!compact && "px-3 pt-2")} data-testid={testId}>
<Alert variant="destructive">
<IconAlertTriangle />
<AlertTitle>{info.title}</AlertTitle>
@@ -75,11 +97,36 @@ export function EnsureSessionErrorBanner({ error, onRetry, workspaceId }: Banner
{info.action.label}
</Link>
) : null}
{action ? (
<Button
variant="outline"
size="sm"
className="min-h-11 cursor-pointer px-2 text-xs"
onClick={action.onClick}
disabled={action.disabled}
data-testid={action.testId}
>
{action.label}
</Button>
) : null}
{secondaryAction ? (
<Button
variant="outline"
size="sm"
className="min-h-11 cursor-pointer px-2 text-xs"
onClick={secondaryAction.onClick}
disabled={secondaryAction.disabled}
data-testid={secondaryAction.testId}
>
{secondaryAction.label}
</Button>
) : null}
<Button
variant="outline"
size="sm"
className="h-6 cursor-pointer px-2 text-xs"
className="min-h-11 cursor-pointer px-2 text-xs"
onClick={onRetry}
disabled={retryDisabled}
data-testid="ensure-session-error-retry"
>
<IconRefresh className="size-3" />
@@ -92,8 +139,61 @@ export function EnsureSessionErrorBanner({ error, onRetry, workspaceId }: Banner
);
}
/** Non-blocking result notice used when the workspace remains available read-only. */
export function SessionRecoveryNotice({ message }: { message: string }) {
return (
<div className="px-3 pt-2" data-testid="session-recovery-notice">
<Alert>
<IconInfoCircle />
<AlertDescription>{message}</AlertDescription>
</Alert>
</div>
);
}
/** Shared inline rendering for automatic resume failures and read-only notices. */
export function SessionRecoveryFeedback({
error,
notice,
onRetry,
workspaceId,
action,
secondaryAction,
retryDisabled,
testId = "session-recovery-error",
}: {
error: string | null;
notice: string | null;
onRetry: () => void;
workspaceId?: string | null;
action?: RecoveryAction;
secondaryAction?: RecoveryAction;
retryDisabled?: boolean;
testId?: string;
}) {
return (
<>
<EnsureSessionErrorBanner
error={error ? new Error(error) : null}
onRetry={onRetry}
workspaceId={workspaceId}
action={action}
secondaryAction={secondaryAction}
retryDisabled={retryDisabled}
testId={testId}
/>
{notice ? <SessionRecoveryNotice message={notice} /> : null}
</>
);
}
/** Full-panel centered state for the kanban preview's empty-sessions slot. */
export function EnsureSessionErrorEmptyState({ error, onRetry, workspaceId }: BannerProps) {
export function EnsureSessionErrorEmptyState({
error,
onRetry,
workspaceId,
retryDisabled,
}: BannerProps) {
const { t } = useTranslation();
const info = describeEnsureError(error, workspaceId);
if (!info) return null;
@@ -119,6 +219,7 @@ export function EnsureSessionErrorEmptyState({ error, onRetry, workspaceId }: Ba
size="sm"
className="cursor-pointer"
onClick={onRetry}
disabled={retryDisabled}
data-testid="ensure-session-error-retry"
>
{t("task:retry")}
@@ -13,7 +13,7 @@ import type { AgentProfileOption } from "@/lib/state/slices";
import type { TaskSession } from "@/lib/types/http";
import { sendMessageRequest } from "@/hooks/use-message-handler";
import type { ChatSubmitPayload } from "./chat/chat-input-container";
import { EnsureSessionErrorEmptyState } from "./ensure-session-error";
import { EnsureSessionErrorEmptyState, SessionRecoveryFeedback } from "./ensure-session-error";
import { PassthroughToolbar } from "./passthrough-toolbar";
import { TaskChatPanel } from "./task-chat-panel";
import {
@@ -71,7 +71,7 @@ export function PreviewSessionTabs({
// Mirrors the full-page task view: ensure the backend execution for the
// active session is ready (resumes / restores workspace after a kandev
// restart where the session row is persisted but agentctl isn't alive).
useSessionResumption(taskId, activeSessionId);
const resumption = useSessionResumption(taskId, activeSessionId);
const tabs = useMemo<SessionTab[]>(
() =>
@@ -102,11 +102,19 @@ export function PreviewSessionTabs({
}
if (ensureSession?.status === "error") {
return (
<EnsureSessionErrorEmptyState
error={ensureSession.error}
onRetry={ensureSession.retry}
workspaceId={workspaceId ?? null}
/>
<>
<SessionRecoveryFeedback
error={resumption.error}
notice={resumption.notice}
onRetry={() => void resumption.resumeSession()}
workspaceId={workspaceId ?? null}
/>
<EnsureSessionErrorEmptyState
error={ensureSession.error}
onRetry={ensureSession.retry}
workspaceId={workspaceId ?? null}
/>
</>
);
}
return <PreviewEmptyState />;
@@ -114,6 +122,12 @@ export function PreviewSessionTabs({
return (
<div className="flex h-full flex-col min-h-0" data-testid="preview-session-tabs">
<SessionRecoveryFeedback
error={resumption.error}
notice={resumption.notice}
onRetry={() => void resumption.resumeSession()}
workspaceId={workspaceId ?? null}
/>
<div className="border-b px-2 py-1">
<SessionTabs
tabs={tabs}
@@ -1,6 +1,7 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { RunError } from "@/app/office/tasks/[id]/types";
import { WebSocketRequestError } from "@/lib/ws/client";
import { RunErrorEntry } from "./run-error-entry";
const { requestMock } = vi.hoisted(() => ({ requestMock: vi.fn() }));
@@ -46,4 +47,29 @@ describe("RunErrorEntry", () => {
expect(screen.queryByTestId("task-launch-error-entry")).toBeNull();
},
);
it("retains a manual recovery error and exposes the typed branch action", async () => {
requestMock.mockRejectedValueOnce(
new WebSocketRequestError("The saved branch is no longer available.", "CONFLICT", {
kind: "branch_unrecoverable",
recovery_action: "resume_new_branch",
original_branch: "feature/lost",
base_branch: "main",
}),
);
render(
<RunErrorEntry
taskId="task-1"
workspaceId="workspace-1"
error={runError("provider_auth_required")}
/>,
);
screen.getByTestId("run-error-resume-button").click();
expect(await screen.findByText("The saved branch is no longer available.")).toBeTruthy();
expect(screen.getByTestId("run-error-continue-new-branch-button")).toBeTruthy();
expect(screen.getByTestId("run-error-restore-workspace-button")).toBeTruthy();
});
});
@@ -11,10 +11,18 @@ import { Button } from "@kandev/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@kandev/ui/collapsible";
import { useAppStore } from "@/components/state-provider";
import { selectOfficeAgentProfiles } from "@/lib/state/slices/office/selectors";
import { getWebSocketClient } from "@/lib/ws/connection";
import { formatRelativeTime } from "@/lib/utils";
import { AgentAvatar } from "@/app/office/components/agent-avatar";
import { RemediationLink } from "@/components/task/remediation-link";
import {
EnsureSessionErrorBanner,
SessionRecoveryNotice,
} from "@/components/task/ensure-session-error";
import { useSessionRecoveryActions } from "@/hooks/domains/session/use-session-recovery-actions";
import type {
BranchRecoveryDetails,
SessionRecoveryAction,
} from "@/lib/services/session-recovery-service";
import type { RunError } from "@/app/office/tasks/[id]/types";
import type { TaskRepository } from "@/lib/types/http";
import { ManagedRuntimeNpmRunError } from "./managed-runtime-npm-run-error";
@@ -53,14 +61,93 @@ function TypedRunLaunchErrorEntry({
);
}
function RunErrorRecoveryFeedback({
workspaceId,
recoveryError,
recoveryNotice,
branchDetails,
busyAction,
onRetry,
onRestore,
onNewBranch,
}: {
workspaceId: string;
recoveryError: Error | null;
recoveryNotice: string | null;
branchDetails: BranchRecoveryDetails | null;
busyAction: SessionRecoveryAction | "restore" | null;
onRetry: () => void;
onRestore: () => void;
onNewBranch: () => void;
}) {
const { t } = useTranslation();
if (!recoveryError && !recoveryNotice) return null;
return (
<>
{recoveryError ? (
<EnsureSessionErrorBanner
error={recoveryError}
onRetry={onRetry}
retryDisabled={busyAction !== null}
workspaceId={workspaceId}
compact
action={
branchDetails
? {
label: t("task:continueOnNewBranch"),
onClick: onNewBranch,
testId: "run-error-continue-new-branch-button",
disabled: busyAction !== null,
}
: {
label: t("task:restoreReadOnlyWorkspace"),
onClick: onRestore,
testId: "run-error-restore-workspace-button",
disabled: busyAction !== null,
}
}
secondaryAction={
branchDetails
? {
label: t("task:restoreReadOnlyWorkspace"),
onClick: onRestore,
testId: "run-error-restore-workspace-button",
disabled: busyAction !== null,
}
: undefined
}
testId="run-error-recovery-error"
/>
) : null}
{recoveryNotice ? <SessionRecoveryNotice message={recoveryNotice} /> : null}
</>
);
}
function LegacyRunErrorEntry({
agentName,
error,
onRecover,
onRetry,
onRestore,
onNewBranch,
workspaceId,
recoveryError,
recoveryNotice,
branchDetails,
busyAction,
}: {
agentName: string;
error: RunError;
onRecover: (action: "resume" | "fresh_start") => Promise<void>;
onRecover: (action: SessionRecoveryAction) => Promise<boolean>;
onRetry: () => void;
onRestore: () => void;
onNewBranch: () => void;
workspaceId: string;
recoveryError: Error | null;
recoveryNotice: string | null;
branchDetails: BranchRecoveryDetails | null;
busyAction: SessionRecoveryAction | "restore" | null;
}) {
const { t } = useTranslation();
const [showDetails, setShowDetails] = useState(false);
@@ -80,6 +167,16 @@ function LegacyRunErrorEntry({
</span>
</div>
<p className="mt-1 text-sm text-muted-foreground">{t("task:theAgentStoppedWithAnError")}</p>
<RunErrorRecoveryFeedback
workspaceId={workspaceId}
recoveryError={recoveryError}
recoveryNotice={recoveryNotice}
branchDetails={branchDetails}
busyAction={busyAction}
onRetry={onRetry}
onRestore={onRestore}
onNewBranch={onNewBranch}
/>
{error.rawPayload && (
<Collapsible open={showDetails} onOpenChange={setShowDetails} className="mt-2">
<CollapsibleTrigger className="flex items-center gap-1 text-xs text-muted-foreground cursor-pointer hover:text-foreground transition-colors">
@@ -103,8 +200,9 @@ function LegacyRunErrorEntry({
<Button
variant="outline"
size="sm"
className="h-7 text-xs cursor-pointer gap-1.5"
className="h-auto min-h-11 cursor-pointer gap-1.5 text-xs sm:min-h-8"
onClick={() => onRecover("resume")}
disabled={busyAction !== null}
data-testid="run-error-resume-button"
>
<IconRefresh className="h-3 w-3" />
@@ -113,8 +211,9 @@ function LegacyRunErrorEntry({
<Button
variant="outline"
size="sm"
className="h-7 text-xs cursor-pointer gap-1.5"
className="h-auto min-h-11 cursor-pointer gap-1.5 text-xs sm:min-h-8"
onClick={() => onRecover("fresh_start")}
disabled={busyAction !== null}
data-testid="run-error-fresh-button"
>
<IconPlayerPlay className="h-3 w-3" />
@@ -146,6 +245,16 @@ export function RunErrorEntry({
selectOfficeAgentProfiles(s).find((a) => a.id === error.agentProfileId)?.name ??
t("task:agent"),
);
const {
busyAction,
recoveryError,
branchDetails,
recoveryNotice,
handleRecover,
handleRestore,
handleRetry,
handleNewBranch,
} = useSessionRecoveryActions({ taskId, sessionId: error.sessionId });
if (isLaunchErrorCategory(error.failureCode) && error.errorStamp) {
return (
@@ -159,29 +268,29 @@ export function RunErrorEntry({
);
}
const handleRecover = async (action: "resume" | "fresh_start" | "runtime_retry") => {
const client = getWebSocketClient();
if (!client) return;
try {
await client.request("session.recover", {
task_id: taskId,
session_id: error.sessionId,
action,
});
} catch {
// No-op — the chat will reflect any subsequent state via WS.
}
};
if (error.failureCode === "managed_runtime_npm_resolution") {
return (
<ManagedRuntimeNpmRunError
error={error}
agentName={agentName}
onRetry={() => handleRecover("runtime_retry")}
onRetry={() => void handleRecover("runtime_retry")}
/>
);
}
return <LegacyRunErrorEntry agentName={agentName} error={error} onRecover={handleRecover} />;
return (
<LegacyRunErrorEntry
agentName={agentName}
error={error}
onRecover={handleRecover}
onRetry={handleRetry}
onRestore={() => void handleRestore()}
onNewBranch={handleNewBranch}
workspaceId={workspaceId}
recoveryError={recoveryError}
recoveryNotice={recoveryNotice}
branchDetails={branchDetails}
busyAction={busyAction}
/>
);
}
+10 -1
View File
@@ -10,7 +10,10 @@ import { isDebugUI } from "@/lib/config";
import { TooltipProvider } from "@kandev/ui/tooltip";
import { useAppStore } from "@/components/state-provider";
import type { UseEnsureTaskSessionResult } from "@/hooks/domains/session/use-ensure-task-session";
import { EnsureSessionErrorBanner } from "@/components/task/ensure-session-error";
import {
EnsureSessionErrorBanner,
SessionRecoveryFeedback,
} from "@/components/task/ensure-session-error";
import { TaskMoveErrorBanner } from "@/components/task/task-move-error-banner";
import type { Layout } from "react-resizable-panels";
import { TaskArchivedProvider } from "./task-archived-context";
@@ -330,6 +333,12 @@ export function TaskPageInner(props: TaskPageInnerProps) {
workspaceId={task?.workspace_id ?? null}
/>
)}
<SessionRecoveryFeedback
error={props.resumption.error}
notice={props.resumption.notice}
onRetry={() => void props.resumption.resumeSession()}
workspaceId={task?.workspace_id ?? null}
/>
<TaskArchivedProvider value={archivedValue}>
<TaskLaunchErrorProvider
value={{
@@ -0,0 +1,102 @@
import { expect, type Page } from "@playwright/test";
import type { SeedData } from "../fixtures/test-base";
import type { CreateTaskResponse } from "../../lib/types/http";
import type { ApiClient } from "./api-client";
import { GitHelper, makeGitEnv } from "./git-helper";
import { SessionPage } from "../pages/session-page";
type TaskEnvironmentRepository = {
repository_id?: string;
worktree_id?: string;
worktree_path?: string;
worktree_branch?: string;
status?: string;
};
type TaskEnvironment = {
id: string;
status: string;
repos?: TaskEnvironmentRepository[];
};
export type WorktreeRecoveryFixture = {
task: CreateTaskResponse;
session: SessionPage;
environment: TaskEnvironment;
repository: TaskEnvironmentRepository;
};
/** Create a real worktree-backed session and wait until its first turn is idle. */
export async function seedWorktreeRecoveryFixture(
page: Page,
apiClient: ApiClient,
seedData: SeedData,
title: string,
): Promise<WorktreeRecoveryFixture> {
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
title,
seedData.agentProfileId,
{
description: "/e2e:simple-message",
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repositories: [{ repository_id: seedData.repositoryId, base_branch: "main" }],
executor_profile_id: seedData.worktreeExecutorProfileId,
},
);
if (!task.session_id) throw new Error("worktree recovery task has no session_id");
await page.goto(`/t/${task.id}`);
const session = new SessionPage(page);
await session.waitForLoad();
await session.waitForChatIdle({ timeout: 60_000 });
let environment: TaskEnvironment | null = null;
await expect
.poll(
async () => {
environment = (await apiClient.getTaskEnvironment(task.id)) as TaskEnvironment | null;
return environment?.repos?.some(
(repository) =>
repository.repository_id === seedData.repositoryId &&
repository.worktree_path &&
repository.worktree_branch,
);
},
{ timeout: 60_000, message: "Waiting for the worktree recovery fixture" },
)
.toBe(true);
const repository = environment?.repos?.find(
(candidate) => candidate.repository_id === seedData.repositoryId,
);
if (!environment || !repository?.worktree_path || !repository.worktree_branch) {
throw new Error("worktree recovery fixture did not expose a repository worktree");
}
return { task, session, environment, repository };
}
/** Remove the branch from both the local repository and its disposable origin. */
export function removeRecoveryBranch(
repositoryPath: string,
tmpDir: string,
repository: TaskEnvironmentRepository,
): { originalPath: string; originalBranch: string } {
if (!repository.worktree_path || !repository.worktree_branch) {
throw new Error("cannot remove a recovery branch without a worktree path and branch");
}
const git = new GitHelper(repositoryPath, makeGitEnv(tmpDir));
const branch = repository.worktree_branch;
const worktreePath = repository.worktree_path;
// Publish the branch first so the test proves the normal remote-ref lookup
// also observes the branch deletion, rather than relying on a never-pushed
// local-only branch.
git.exec(`git push origin "${branch}"`);
git.exec(`git worktree remove --force "${worktreePath}"`);
git.exec(`git branch -D "${branch}"`);
git.exec(`git push origin --delete "${branch}"`);
return { originalPath: worktreePath, originalBranch: branch };
}
+25
View File
@@ -659,6 +659,31 @@ export class SessionPage {
return this.page.getByTestId("recovery-resume-button");
}
/** Error returned by a manual session recovery action. */
recoveryError(): Locator {
return this.activeChat().getByTestId("session-recovery-error");
}
/** Explicit action for continuing a conversation on a replacement branch. */
recoveryNewBranchButton(): Locator {
return this.activeChat().getByTestId("recovery-new-branch-button");
}
/** Read-only workspace restore action shown after a recovery failure. */
recoveryRestoreWorkspaceButton(): Locator {
return this.activeChat().getByTestId("recovery-restore-workspace-button");
}
/** Non-blocking notice shown after automatic read-only workspace restore. */
recoveryReadOnlyNotice(): Locator {
return this.activeChat().getByTestId("session-recovery-notice");
}
/** Persisted warning shown after the original branch is replaced. */
branchRecreatedWarning(): Locator {
return this.activeChat().getByTestId("branch-recreated-warning");
}
/** "Start fresh session" button shown after agent crash. */
recoveryFreshButton(): Locator {
return this.page.getByTestId("recovery-fresh-button");
@@ -0,0 +1,140 @@
// Filename starts with "mobile-" so this runs on the mobile-chrome project.
import { test, expect } from "../../fixtures/test-base";
import { assertNoDocumentHorizontalOverflow } from "../../helpers/layout-assertions";
import { waitForSessionState } from "../../helpers/session";
import {
removeRecoveryBranch,
seedWorktreeRecoveryFixture,
} from "../../helpers/session-resume-recovery";
test.describe("mobile: worktree branch resume recovery", () => {
test.describe.configure({ retries: 1 });
test("keeps branch recovery touch-safe and reload-stable", async ({
testPage,
apiClient,
seedData,
backend,
prCapture,
}, testInfo) => {
test.setTimeout(180_000);
const fixture = await seedWorktreeRecoveryFixture(
testPage,
apiClient,
seedData,
`Mobile worktree branch recovery ${Date.now()}`,
);
const sessionId = fixture.task.session_id!;
const originalBranch = fixture.repository.worktree_branch!;
const originalPath = fixture.repository.worktree_path!;
const beforeEnvironment = await apiClient.getTaskEnvironment(fixture.task.id);
const beforeRepository = beforeEnvironment?.repos?.find(
(repository) => repository.repository_id === seedData.repositoryId,
);
const stopResponse = await apiClient.stopSession({
session_id: sessionId,
reason: "mobile e2e branch recovery",
force: true,
});
expect(stopResponse.success).toBe(true);
await waitForSessionState(apiClient, {
taskId: fixture.task.id,
sessionId,
expectedState: "CANCELLED",
message: "Waiting for the mobile worktree recovery session to stop",
timeout: 30_000,
});
await expect(fixture.session.recoveryResumeButton()).toBeVisible({ timeout: 30_000 });
removeRecoveryBranch(seedData.repositoryPath, backend.tmpDir, fixture.repository);
await fixture.session.recoveryResumeButton().tap();
await expect(fixture.session.recoveryError()).toBeVisible({ timeout: 30_000 });
await expect(fixture.session.recoveryError()).toContainText("no longer available");
await expect(fixture.session.recoveryNewBranchButton()).toBeVisible();
await expect(fixture.session.recoveryRestoreWorkspaceButton()).toBeVisible();
for (const button of [
fixture.session.recoveryNewBranchButton(),
fixture.session.recoveryRestoreWorkspaceButton(),
]) {
await expect(button).toBeInViewport();
const box = await button.boundingBox();
expect(box).not.toBeNull();
expect(box!.height).toBeGreaterThanOrEqual(44);
}
await fixture.session.recoveryRestoreWorkspaceButton().focus();
await expect(fixture.session.recoveryRestoreWorkspaceButton()).toBeFocused();
await assertNoDocumentHorizontalOverflow(testPage, "mobile lost branch recovery error");
// The normal action remains retryable and cannot alter the persisted branch
// until the user taps the explicit replacement action.
await fixture.session.recoveryResumeButton().tap();
await expect(fixture.session.recoveryError()).toBeVisible({ timeout: 30_000 });
await expect
.poll(
async () =>
(await apiClient.getTaskEnvironment(fixture.task.id))?.repos?.find(
(repository) => repository.repository_id === seedData.repositoryId,
)?.worktree_branch ?? null,
{ timeout: 15_000, message: "Mobile Resume changed the branch before explicit consent" },
)
.toBe(originalBranch);
await fixture.session.recoveryNewBranchButton().tap();
await expect(fixture.session.branchRecreatedWarning()).toBeVisible({ timeout: 60_000 });
await fixture.session.waitForChatIdle({ timeout: 30_000 });
let afterEnvironment: Awaited<ReturnType<typeof apiClient.getTaskEnvironment>> = null;
let newBranch = "";
await expect
.poll(
async () => {
afterEnvironment = await apiClient.getTaskEnvironment(fixture.task.id);
newBranch =
afterEnvironment?.repos?.find(
(repository) => repository.repository_id === seedData.repositoryId,
)?.worktree_branch ?? "";
return newBranch && newBranch !== originalBranch ? newBranch : null;
},
{ timeout: 30_000, message: "Waiting for the mobile replacement worktree branch" },
)
.toBeTruthy();
const afterRepository = afterEnvironment?.repos?.find(
(repository) => repository.repository_id === seedData.repositoryId,
);
expect(afterEnvironment?.id).toBe(beforeEnvironment?.id);
expect(afterRepository?.worktree_id).toBe(beforeRepository?.worktree_id);
expect(afterRepository?.worktree_path).not.toBe(originalPath);
expect(newBranch).not.toBe("");
await expect(fixture.session.branchRecreatedWarning()).toContainText(newBranch);
await expect(fixture.session.recoveryError()).toHaveCount(0);
await assertNoDocumentHorizontalOverflow(testPage, "mobile replacement branch warning");
// Verify the recovered provider accepts a follow-up turn on the same
// session after the replacement worktree is ready.
await fixture.session.sendMessageViaButton("/e2e:simple-message");
await fixture.session.expectChatResponseVisible("simple mock response", 1, {
timeout: 60_000,
});
await testPage.screenshot({
path: testInfo.outputPath("session-resume-recovery-mobile.png"),
fullPage: true,
});
await prCapture.screenshot("session-resume-recovery-mobile", {
caption: "Mobile branch recovery keeps explicit actions touch-safe",
fullPage: true,
});
await testPage.reload();
await fixture.session.waitForLoad();
await expect(fixture.session.branchRecreatedWarning()).toHaveCount(1, { timeout: 30_000 });
await expect(fixture.session.branchRecreatedWarning()).toContainText(newBranch);
await expect(fixture.session.recoveryError()).toHaveCount(0);
await assertNoDocumentHorizontalOverflow(testPage, "reloaded mobile branch warning");
});
});
@@ -0,0 +1,141 @@
import { test, expect } from "../../fixtures/test-base";
import { assertNoDocumentHorizontalOverflow } from "../../helpers/layout-assertions";
import { waitForSessionState } from "../../helpers/session";
import {
removeRecoveryBranch,
seedWorktreeRecoveryFixture,
} from "../../helpers/session-resume-recovery";
test.describe("worktree branch resume recovery", () => {
test.describe.configure({ retries: 1 });
test("keeps normal resume unchanged and explicitly replaces a lost branch", async ({
testPage,
apiClient,
seedData,
backend,
prCapture,
}, testInfo) => {
test.setTimeout(180_000);
const fixture = await seedWorktreeRecoveryFixture(
testPage,
apiClient,
seedData,
`Worktree branch recovery ${Date.now()}`,
);
const sessionId = fixture.task.session_id!;
const originalBranch = fixture.repository.worktree_branch!;
const originalPath = fixture.repository.worktree_path!;
const beforeEnvironment = await apiClient.getTaskEnvironment(fixture.task.id);
const beforeRepository = beforeEnvironment?.repos?.find(
(repository) => repository.repository_id === seedData.repositoryId,
);
expect(beforeEnvironment?.id).toBe(fixture.environment.id);
expect(beforeRepository?.worktree_id).toBe(fixture.repository.worktree_id);
const stopResponse = await apiClient.stopSession({
session_id: sessionId,
reason: "e2e branch recovery",
force: true,
});
expect(stopResponse.success).toBe(true);
await waitForSessionState(apiClient, {
taskId: fixture.task.id,
sessionId,
expectedState: "CANCELLED",
message: "Waiting for the worktree recovery session to stop",
timeout: 30_000,
});
await expect(fixture.session.recoveryResumeButton()).toBeVisible({ timeout: 30_000 });
removeRecoveryBranch(seedData.repositoryPath, backend.tmpDir, fixture.repository);
// A normal Resume must report the lost branch and leave the environment
// untouched. The replacement is only available from the typed failure.
await fixture.session.recoveryResumeButton().click();
await expect(fixture.session.recoveryError()).toBeVisible({ timeout: 30_000 });
await expect(fixture.session.recoveryError()).toContainText("no longer available");
await expect(fixture.session.recoveryNewBranchButton()).toBeVisible();
await expect(fixture.session.recoveryRestoreWorkspaceButton()).toBeVisible();
await assertNoDocumentHorizontalOverflow(testPage, "lost branch recovery error");
// A second ordinary attempt remains retryable and must not silently switch
// the branch or consume the explicit replacement decision.
await fixture.session.recoveryResumeButton().click();
await expect(fixture.session.recoveryError()).toBeVisible({ timeout: 30_000 });
await expect
.poll(
async () =>
(await apiClient.getTaskEnvironment(fixture.task.id))?.repos?.find(
(repository) => repository.repository_id === seedData.repositoryId,
)?.worktree_branch ?? null,
{ timeout: 15_000, message: "Normal resume changed the branch before explicit consent" },
)
.toBe(originalBranch);
// The typed action preserves the existing session and environment identity
// while creating a new branch and worktree path.
await fixture.session.recoveryNewBranchButton().click();
await expect(fixture.session.branchRecreatedWarning()).toBeVisible({ timeout: 60_000 });
await fixture.session.waitForChatIdle({ timeout: 30_000 });
let afterEnvironment: Awaited<ReturnType<typeof apiClient.getTaskEnvironment>> = null;
let newBranch = "";
await expect
.poll(
async () => {
afterEnvironment = await apiClient.getTaskEnvironment(fixture.task.id);
newBranch =
afterEnvironment?.repos?.find(
(repository) => repository.repository_id === seedData.repositoryId,
)?.worktree_branch ?? "";
return newBranch && newBranch !== originalBranch ? newBranch : null;
},
{ timeout: 30_000, message: "Waiting for the replacement worktree branch" },
)
.toBeTruthy();
const afterRepository = afterEnvironment?.repos?.find(
(repository) => repository.repository_id === seedData.repositoryId,
);
expect(afterEnvironment?.id).toBe(beforeEnvironment?.id);
expect(afterRepository?.worktree_id).toBe(beforeRepository?.worktree_id);
expect(afterRepository?.worktree_path).not.toBe(originalPath);
expect(newBranch).not.toBe("");
expect(newBranch).not.toBe(originalBranch);
await expect(fixture.session.branchRecreatedWarning()).toContainText(originalBranch);
await expect(fixture.session.branchRecreatedWarning()).toContainText(newBranch);
await expect(fixture.session.branchRecreatedWarning()).toContainText("main");
await expect(fixture.session.recoveryError()).toHaveCount(0);
await assertNoDocumentHorizontalOverflow(testPage, "replacement branch warning");
// A resumed session must accept a real follow-up turn after the branch
// replacement. The original response remains visible, and the second
// response proves the provider session continued instead of stopping at
// workspace preparation.
await fixture.session.sendMessage("/e2e:simple-message");
await fixture.session.expectChatResponseVisible("simple mock response", 1, {
timeout: 60_000,
});
await testPage.screenshot({
path: testInfo.outputPath("session-resume-recovery-desktop.png"),
fullPage: true,
});
await prCapture.screenshot("session-resume-recovery-desktop", {
caption: "Explicit worktree branch recovery keeps the session and warns about lost code",
fullPage: true,
});
// The warning is a persisted status message, not a transient component
// state. Reloading must preserve exactly one honest warning and no blocker.
await testPage.reload();
await fixture.session.waitForLoad();
await expect(fixture.session.branchRecreatedWarning()).toHaveCount(1, { timeout: 30_000 });
await expect(fixture.session.branchRecreatedWarning()).toContainText(newBranch);
await expect(fixture.session.recoveryError()).toHaveCount(0);
await expect(fixture.session.activeChat()).toContainText("simple mock response");
await assertNoDocumentHorizontalOverflow(testPage, "reloaded replacement branch warning");
});
});
@@ -0,0 +1,105 @@
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
asRecoveryError,
branchRecoveryDetails,
requestSessionRecover,
restoreSessionWorkspace,
type BranchRecoveryDetails,
type SessionRecoveryAction,
} from "@/lib/services/session-recovery-service";
export type SessionRecoveryBusyAction = SessionRecoveryAction | "restore" | null;
type SessionRecoveryActionsOptions = {
taskId: string;
sessionId: string;
};
/** Owns shared manual recovery state while a failed session remains visible. */
export function useSessionRecoveryActions({ taskId, sessionId }: SessionRecoveryActionsOptions) {
const { t } = useTranslation();
const [busyAction, setBusyAction] = useState<SessionRecoveryBusyAction>(null);
const [resumeError, setResumeError] = useState<Error | null>(null);
const [restoreError, setRestoreError] = useState<Error | null>(null);
const [branchDetails, setBranchDetails] = useState<BranchRecoveryDetails | null>(null);
const [lastFailedAction, setLastFailedAction] = useState<SessionRecoveryAction | null>(null);
const [recoveryNotice, setRecoveryNotice] = useState<string | null>(null);
const recoveryError = useMemo(() => {
if (resumeError && restoreError) {
return new Error(
t("task:resumeAndRestoreFailed", {
resumeError: resumeError.message,
restoreError: restoreError.message,
}),
);
}
return restoreError ?? resumeError;
}, [restoreError, resumeError, t]);
const handleRecover = useCallback(
async (action: SessionRecoveryAction) => {
setBusyAction(action);
try {
await requestSessionRecover(taskId, sessionId, action, t("task:failedToResumeSession"));
setResumeError(null);
setRestoreError(null);
setBranchDetails(null);
setLastFailedAction(null);
setRecoveryNotice(null);
} catch (cause) {
setResumeError(asRecoveryError(cause, t("task:failedToResumeSession")));
setRestoreError(null);
setBranchDetails(branchRecoveryDetails(cause));
setLastFailedAction(action);
setRecoveryNotice(null);
return false;
} finally {
setBusyAction(null);
}
return true;
},
[sessionId, taskId, t],
);
const handleRestore = useCallback(async () => {
const failedMessage = resumeError?.message ?? t("task:failedToResumeSession");
setBusyAction("restore");
setRestoreError(null);
try {
await restoreSessionWorkspace(taskId, sessionId, t("task:failedToRestoreWorkspace"));
setResumeError(null);
setRestoreError(null);
setBranchDetails(null);
setLastFailedAction(null);
setRecoveryNotice(t("task:resumeFailedWorkspaceReadOnly", { error: failedMessage }));
} catch (cause) {
setRestoreError(asRecoveryError(cause, t("task:failedToRestoreWorkspace")));
setRecoveryNotice(null);
} finally {
setBusyAction(null);
}
}, [resumeError, sessionId, taskId, t]);
const handleRetry = useCallback(() => {
return handleRecover(lastFailedAction ?? "resume");
}, [handleRecover, lastFailedAction]);
const handleNewBranch = useCallback(() => {
return handleRecover("resume_new_branch");
}, [handleRecover]);
return {
busyAction,
recoveryError,
branchDetails,
recoveryNotice,
handleRecover,
handleRestore,
handleRetry,
handleNewBranch,
};
}
export type SessionRecoveryActions = ReturnType<typeof useSessionRecoveryActions>;
@@ -0,0 +1,38 @@
import { useEffect, useRef } from "react";
type RecoveryResumptionState = "resumed" | "running";
type RecoveryFeedbackSetters = {
setError: (value: string | null) => void;
setNotice?: (value: string | null) => void;
setResumptionState: (value: RecoveryResumptionState) => void;
};
function isActiveSessionState(state: string | undefined): boolean {
return state === "STARTING" || state === "RUNNING" || state === "WAITING_FOR_INPUT";
}
/** Clear automatic recovery feedback after another recovery makes the session active. */
export function useSessionRecoveryFeedback(
sessionId: string | null,
sessionState: string | undefined,
error: string | null,
notice: string | null,
setters: RecoveryFeedbackSetters,
): void {
const { setError, setNotice, setResumptionState } = setters;
const lastObservedSessionRef = useRef<{ id: string | null; state?: string }>({
id: sessionId,
state: sessionState,
});
useEffect(() => {
const previous = lastObservedSessionRef.current;
const stateChanged = previous.id === sessionId && previous.state !== sessionState;
lastObservedSessionRef.current = { id: sessionId, state: sessionState };
if (!stateChanged || !isActiveSessionState(sessionState)) return;
if (error !== null) setError(null);
if (notice !== null) setNotice?.(null);
setResumptionState(sessionState === "RUNNING" ? "running" : "resumed");
}, [error, notice, sessionId, sessionState, setError, setNotice, setResumptionState]);
}
@@ -48,6 +48,7 @@ import {
type SetterCalls = {
resumptionStates: ResumptionState[];
errors: (string | null)[];
notices: (string | null)[];
worktreePaths: (string | null)[];
worktreeBranches: (string | null)[];
taskSessionStates: string[];
@@ -57,6 +58,7 @@ function createSetters(): { setters: ResumeStateSetter; calls: SetterCalls } {
const calls: SetterCalls = {
resumptionStates: [],
errors: [],
notices: [],
worktreePaths: [],
worktreeBranches: [],
taskSessionStates: [],
@@ -68,6 +70,9 @@ function createSetters(): { setters: ResumeStateSetter; calls: SetterCalls } {
setError: (e: string | null) => {
calls.errors.push(e);
},
setNotice: (notice: string | null) => {
calls.notices.push(notice);
},
setWorktreePath: (p: string | null) => {
calls.worktreePaths.push(p);
},
@@ -120,7 +125,12 @@ describe("resumeWithSilentFallback", () => {
it("falls back to restore_workspace silently when resume returns success=false", async () => {
// 1st call: resume fails. 2nd call: restore_workspace succeeds.
mockRequest
.mockResolvedValueOnce({ success: false, task_id: TASK_ID, state: FAILED_STATE })
.mockResolvedValueOnce({
success: false,
task_id: TASK_ID,
state: FAILED_STATE,
error: "Resume transport failed",
})
.mockResolvedValueOnce({
success: true,
task_id: TASK_ID,
@@ -148,6 +158,9 @@ describe("resumeWithSilentFallback", () => {
// Final state is "resumed" (from successful restore), no error surfaced.
expect(calls.resumptionStates.at(-1)).toBe("resumed");
expect(calls.errors.filter((e) => typeof e === "string")).toHaveLength(0);
expect(calls.notices.at(-1)).toBe(
"Resume failed: Resume transport failed. The workspace was restored in read-only mode.",
);
});
it("falls back to restore_workspace silently when resume throws", async () => {
@@ -168,8 +181,18 @@ describe("resumeWithSilentFallback", () => {
it("surfaces an error only when BOTH resume and restore_workspace fail", async () => {
mockRequest
.mockResolvedValueOnce({ success: false, task_id: TASK_ID, state: FAILED_STATE })
.mockResolvedValueOnce({ success: false, task_id: TASK_ID, state: FAILED_STATE });
.mockResolvedValueOnce({
success: false,
task_id: TASK_ID,
state: FAILED_STATE,
error: "Resume transport failed",
})
.mockResolvedValueOnce({
success: false,
task_id: TASK_ID,
state: FAILED_STATE,
error: "Workspace restore failed",
});
const { setters, calls } = createSetters();
await resumeWithSilentFallback(TASK_ID, SESSION_ID, null, setters);
@@ -177,7 +200,7 @@ describe("resumeWithSilentFallback", () => {
expect(mockRequest).toHaveBeenCalledTimes(2);
expect(calls.resumptionStates.at(-1)).toBe("error");
expect(calls.errors.at(-1)).toBe(
"Failed to resume session - workspace restore also unavailable",
"Resume failed: Resume transport failed. Workspace restore failed: Workspace restore failed.",
);
});
@@ -192,7 +215,7 @@ describe("resumeWithSilentFallback", () => {
expect(mockRequest).toHaveBeenCalledTimes(2);
expect(calls.resumptionStates.at(-1)).toBe("error");
expect(calls.errors.at(-1)).toBe(
"Failed to resume session - workspace restore also unavailable",
"Resume failed: ws closed. Workspace restore failed: still closed.",
);
});
@@ -297,6 +320,47 @@ describe("useSessionResumption", () => {
session_id: SESSION_ID,
});
});
it("clears stale feedback when an external recovery makes the live session active", async () => {
mockPreventAutoStart = true;
mockSessionItems = {
s1: {
started_at: STARTED_AT,
updated_at: STARTED_AT,
state: FAILED_STATE,
},
};
mockRequest.mockResolvedValueOnce({
session_id: SESSION_ID,
task_id: TASK_ID,
state: FAILED_STATE,
is_agent_running: false,
is_resumable: true,
needs_resume: true,
updated_at: STARTED_AT,
});
const { result, rerender } = renderHook(() => useSessionResumption(TASK_ID, SESSION_ID));
await waitFor(() => expect(mockSetResumeSkipped).toHaveBeenCalledWith(SESSION_ID, true));
mockRequest.mockResolvedValueOnce({
success: false,
task_id: TASK_ID,
session_id: SESSION_ID,
state: FAILED_STATE,
error: "Stale automatic recovery failure",
});
await act(async () => {
await result.current.resumeSession();
});
expect(result.current.error).toBe("Stale automatic recovery failure");
mockSessionItems.s1.state = "RUNNING";
rerender();
await waitFor(() => expect(result.current.error).toBeNull());
expect(result.current.notice).toBeNull();
});
});
describe("useSessionResumption prevent-auto-start gate", () => {
@@ -1,10 +1,11 @@
import { useCallback, useEffect, useState, useRef } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { getWebSocketClient } from "@/lib/ws/connection";
import { launchSession } from "@/lib/services/session-launch-service";
import {
buildResumeRequest,
buildRestoreWorkspaceRequest,
} from "@/lib/services/session-launch-helpers";
import { useSessionRecoveryFeedback } from "./use-session-recovery-feedback";
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
import {
sessionId as toSessionId,
@@ -58,6 +59,7 @@ type ResumeResponse = {
export type ResumeStateSetter = {
setResumptionState: (s: ResumptionState) => void;
setError: (e: string | null) => void;
setNotice?: (notice: string | null) => void;
setWorktreePath: (p: string | null) => void;
setWorktreeBranch: (p: string | null) => void;
setTaskSession: (s: {
@@ -156,48 +158,69 @@ export async function resumeWithSilentFallback(
setters: ResumeStateSetter,
): Promise<boolean> {
setters.setResumptionState("resuming");
if (
await tryLaunch(
buildResumeRequest(taskId, sessionId).request,
taskId,
sessionId,
session,
setters,
)
) {
const resumeAttempt = await tryLaunch(
buildResumeRequest(taskId, sessionId).request,
taskId,
sessionId,
session,
setters,
);
if (resumeAttempt.ok) {
setters.setNotice?.(null);
return true;
}
// Resume failed (returned success=false OR threw). Fall back to read-only
// workspace restore so the user keeps file/terminal/git access.
if (
await tryLaunch(
buildRestoreWorkspaceRequest(taskId, sessionId).request,
taskId,
sessionId,
session,
setters,
)
) {
const restoreAttempt = await tryLaunch(
buildRestoreWorkspaceRequest(taskId, sessionId).request,
taskId,
sessionId,
session,
setters,
);
if (restoreAttempt.ok) {
setters.setError(null);
setters.setNotice?.(
t("task:resumeFailedWorkspaceReadOnly", { error: resumeAttempt.error.message }),
);
return true;
}
setters.setResumptionState("error");
setters.setError(t("task:failedToResumeAndRestore"));
setters.setNotice?.(null);
setters.setError(
t("task:resumeAndRestoreFailed", {
resumeError: resumeAttempt.error.message,
restoreError: restoreAttempt.error.message,
}),
);
return false;
}
/** Run a single launch attempt; returns true on success, false on any failure.
type LaunchAttempt = { ok: true } | { ok: false; error: Error };
/** Run a single launch attempt and retain its failure for the fallback notice.
* Logs caught errors to the console so silent fallback paths remain debuggable
* (errors otherwise vanish into the implicit `false` return). */
* (errors otherwise vanish into the fallback state). */
async function tryLaunch(
request: import("@/lib/services/session-launch-service").LaunchSessionRequest,
taskId: string,
sessionId: string,
session: SessionLike,
setters: ResumeStateSetter,
): Promise<boolean> {
): Promise<LaunchAttempt> {
try {
const resp = await launchSession(request);
if (!resp.success) return false;
if (!resp.success) {
return {
ok: false,
error: new Error(
resp.error ??
(request.intent === "restore_workspace"
? t("task:failedToRestoreWorkspace")
: t("task:failedToResumeSession")),
),
};
}
applyResumeResponse(
{
success: true,
@@ -216,14 +239,17 @@ async function tryLaunch(
if (request.intent === "restore_workspace" && setters.setAgentctlReady) {
setters.setAgentctlReady(sessionId);
}
return true;
return { ok: true };
} catch (err) {
console.error("[tryLaunch] session launch failed", {
intent: request.intent,
sessionId,
err,
});
return false;
return {
ok: false,
error: err instanceof Error ? err : new Error(t("common:unknownError")),
};
}
}
@@ -370,6 +396,7 @@ async function checkAndResume({
if (!client) return;
setters.setResumptionState("checking");
setters.setError(null);
setters.setNotice?.(null);
try {
const status = await client.request<SessionStatus>("task.session.status", {
task_id: taskId,
@@ -425,6 +452,7 @@ async function checkAndResume({
} catch (err) {
setters.setResumptionState("error");
setters.setError(err instanceof Error ? err.message : t("common:unknownError"));
setters.setNotice?.(null);
}
}
@@ -432,6 +460,7 @@ interface UseSessionResumptionReturn {
resumptionState: ResumptionState;
sessionStatus: SessionStatus | null;
error: string | null;
notice: string | null;
taskSessionState: TaskSessionState | null;
worktreePath: string | null;
worktreeBranch: string | null;
@@ -483,6 +512,7 @@ function useSessionResetAndCheck({
remoteStatusRetryCount.current = 0;
setters.setResumptionState("idle");
setters.setError(null);
setters.setNotice?.(null);
setters.setWorktreePath(null);
setters.setWorktreeBranch(null);
}, [sessionId, taskId]); // eslint-disable-line react-hooks/exhaustive-deps -- intentional reset on dep change
@@ -549,6 +579,9 @@ function buildGuardedSetters(
setError: (e) => {
if (guard()) setters.setError(e);
},
setNotice: (notice) => {
if (guard()) setters.setNotice?.(notice);
},
setWorktreePath: (p) => {
if (guard()) setters.setWorktreePath(p);
},
@@ -577,6 +610,7 @@ export function useSessionResumption(
): UseSessionResumptionReturn {
const [resumptionState, setResumptionState] = useState<ResumptionState>("idle");
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [worktreePath, setWorktreePath] = useState<string | null>(null);
const [worktreeBranch, setWorktreeBranch] = useState<string | null>(null);
const connectionStatus = useAppStore((state) => state.connection.status);
@@ -594,6 +628,7 @@ export function useSessionResumption(
const setters: ResumeStateSetter = {
setResumptionState,
setError,
setNotice,
setWorktreePath,
setWorktreeBranch,
setTaskSession,
@@ -602,6 +637,8 @@ export function useSessionResumption(
getLiveSession: (sid: string) => storeApi.getState().taskSessions.items[sid] ?? null,
};
useSessionRecoveryFeedback(sessionId, session?.state, error, notice, setters);
const { sessionStatus } = useSessionResetAndCheck({
taskId,
sessionId,
@@ -616,11 +653,13 @@ export function useSessionResumption(
if (!taskId || !sessionId) return false;
setResumptionState("resuming");
setError(null);
setNotice(null);
try {
const { request } = buildResumeRequest(taskId, sessionId);
const response = await launchSession(request);
if (response.success) {
setResumptionState("resumed");
setNotice(null);
if (response.state) {
setTaskSession({
id: toSessionId(sessionId),
@@ -643,7 +682,7 @@ export function useSessionResumption(
return true;
}
setResumptionState("error");
setError(t("task:failedToResumeSession"));
setError(response.error ?? t("task:failedToResumeSession"));
return false;
} catch (err) {
setResumptionState("error");
@@ -655,6 +694,7 @@ export function useSessionResumption(
sessionId,
session,
setTaskSession,
setNotice,
setWorktreePath,
setWorktreeBranch,
setResumeSkipped,
@@ -664,6 +704,7 @@ export function useSessionResumption(
resumptionState,
sessionStatus,
error,
notice,
taskSessionState: session?.state ?? null,
worktreePath,
worktreeBranch,
@@ -46,6 +46,7 @@ export type LaunchSessionResponse = {
state: string;
worktree_path?: string;
worktree_branch?: string;
error?: string;
};
export async function launchSession(
@@ -0,0 +1,82 @@
import { buildRestoreWorkspaceRequest } from "./session-launch-helpers";
import { launchSession } from "./session-launch-service";
import { getWebSocketClient } from "@/lib/ws/connection";
import { WebSocketRequestError, type WebSocketRequestErrorDetails } from "@/lib/ws/client";
export type SessionRecoveryAction =
| "resume"
| "resume_new_branch"
| "fresh_start"
| "runtime_retry";
export type BranchRecoveryDetails = WebSocketRequestErrorDetails & {
kind: "branch_unrecoverable";
recovery_action: "resume_new_branch";
original_branch?: string;
base_branch?: string;
repository_id?: string;
session_id?: string;
};
type RecoveryResponse = { success?: boolean; error?: string };
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function responseFailure(response: unknown, fallback: string): Error | null {
if (!isRecord(response) || response.success !== false) return null;
const message = typeof response.error === "string" && response.error ? response.error : fallback;
return new Error(message);
}
/** Returns the structured branch-loss context that authorizes replacement. */
export function branchRecoveryDetails(error: unknown): BranchRecoveryDetails | null {
if (!(error instanceof WebSocketRequestError) || !isRecord(error.details)) return null;
if (
error.details.kind !== "branch_unrecoverable" ||
error.details.recovery_action !== "resume_new_branch"
) {
return null;
}
return error.details as BranchRecoveryDetails;
}
/** Converts unknown request failures into an Error for an inline recovery alert. */
export function asRecoveryError(error: unknown, fallback: string): Error {
return error instanceof Error ? error : new Error(fallback);
}
/** Send one of the explicit session.recover actions. */
export async function requestSessionRecover(
taskId: string,
sessionId: string,
action: SessionRecoveryAction,
failureMessage: string,
): Promise<void> {
const client = getWebSocketClient();
if (!client) throw new Error(failureMessage);
const response = await client.request<RecoveryResponse>(
"session.recover",
{
task_id: taskId,
session_id: sessionId,
action,
},
30_000,
);
const failure = responseFailure(response, failureMessage);
if (failure) throw failure;
}
/** Restore the existing task workspace without starting the provider. */
export async function restoreSessionWorkspace(
taskId: string,
sessionId: string,
failureMessage: string,
): Promise<void> {
const { request } = buildRestoreWorkspaceRequest(taskId, sessionId);
const response = await launchSession(request);
const failure = responseFailure(response, failureMessage);
if (failure) throw failure;
}
+35 -1
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { WebSocketClient } from "./client";
import { WebSocketClient, WebSocketRequestError } from "./client";
type SentRequest = {
id: string;
@@ -169,6 +169,40 @@ describe("session subscription readiness", () => {
});
});
describe("request errors", () => {
it("retains the backend code and details when a request fails", async () => {
const { client, socket } = connectClient();
const request = client.request("session.recover", { action: "resume" });
const sent = socket.sent.at(-1);
if (!sent) throw new Error("No request was sent");
socket.receive({
id: sent.id,
type: "error",
payload: {
code: "CONFLICT",
message: "The saved branch is no longer available.",
details: {
kind: "branch_unrecoverable",
recovery_action: "resume_new_branch",
original_branch: "feature/lost",
},
},
});
await expect(request).rejects.toBeInstanceOf(WebSocketRequestError);
await expect(request).rejects.toMatchObject({
message: "The saved branch is no longer available.",
code: "CONFLICT",
details: {
kind: "branch_unrecoverable",
recovery_action: "resume_new_branch",
original_branch: "feature/lost",
},
});
});
});
describe("session subscription reconnect recovery", () => {
it("keeps queued hydration behind the reconnect subscription acknowledgement", async () => {
vi.useFakeTimers();
+3 -5
View File
@@ -3,6 +3,8 @@ import type { ConnectionStatus } from "@/lib/types/connection";
import { generateUUID } from "@/lib/utils";
import { createDebugLogger, isDebug } from "@/lib/debug/log";
import { dispatchToPluginWsHandlers } from "@/lib/ws/plugin-bridge";
import { toWebSocketRequestError } from "./request-error";
export { WebSocketRequestError, type WebSocketRequestErrorDetails } from "./request-error";
const debugDispatch = createDebugLogger("ws:dispatch");
@@ -494,11 +496,7 @@ export class WebSocketClient {
if (!pending) return;
clearTimeout(pending.timeout);
this.pendingRequests.delete(msgId);
const errorMessage =
typeof payload === "object" && payload && "message" in payload
? String((payload as { message?: string }).message)
: "WebSocket request failed";
pending.reject(new Error(errorMessage));
pending.reject(toWebSocketRequestError(payload));
}
private handleDisconnect(event: CloseEvent) {
+33
View File
@@ -0,0 +1,33 @@
export type WebSocketRequestErrorDetails = Record<string, unknown>;
/** Error returned when the backend rejects a request with a typed payload. */
export class WebSocketRequestError extends Error {
readonly code?: string;
readonly details?: WebSocketRequestErrorDetails;
constructor(message: string, code?: string, details?: WebSocketRequestErrorDetails) {
super(message);
this.name = "WebSocketRequestError";
this.code = code;
this.details = details;
}
}
/** Preserve the structured fields from a rejected WebSocket request. */
export function toWebSocketRequestError(payload: unknown): WebSocketRequestError {
const record =
typeof payload === "object" && payload !== null
? (payload as { code?: unknown; message?: unknown; details?: unknown })
: undefined;
// i18n-exempt: transport fallback used when the backend supplies no message.
const message =
typeof record?.message === "string" && record.message
? record.message
: "WebSocket request failed";
const code = typeof record?.code === "string" ? record.code : undefined;
const details =
typeof record?.details === "object" && record.details !== null
? (record.details as WebSocketRequestErrorDetails)
: undefined;
return new WebSocketRequestError(message, code, details);
}
+11
View File
@@ -492,6 +492,7 @@
"failedToRenameItem": "Failed to rename item",
"failedToRenameTask": "Failed to rename task",
"failedToRestorePlan": "Failed to restore plan",
"failedToRestoreWorkspace": "Failed to restore workspace",
"failedToResumeSession": "Failed to resume session",
"failedToRevokeShare": "Failed to revoke share.",
"failedToSaveDocument": "Failed to save document",
@@ -810,6 +811,12 @@
"modelSelectionRemediationUnknown": "Check the executor configuration.",
"modelSelectionRequested": "Requested model",
"modelSelectionWarning": "The executor could not use the saved model selection.",
"branchRecreatedWarning": "The saved branch was unavailable, so a new branch was created.",
"branchRecreatedOriginal": "Original branch",
"branchRecreatedNew": "New branch",
"branchRecreatedBase": "Base branch",
"branchRecreatedConversation": "Conversation history continues on the new branch.",
"branchRecreatedCodeNotRecovered": "Code changes from the unavailable branch were not recovered.",
"monitor": "Monitor",
"monitorCommand": "Monitor: {{command}}",
"moreActions": "More actions",
@@ -1818,6 +1825,10 @@
"failedToLoadFileContent": "Failed to load file content",
"openFileInProvider": "Open file in {{provider}}",
"failedToResumeAndRestore": "Failed to resume session - workspace restore also unavailable",
"resumeAndRestoreFailed": "Resume failed: {{resumeError}}. Workspace restore failed: {{restoreError}}.",
"resumeFailedWorkspaceReadOnly": "Resume failed: {{error}}. The workspace was restored in read-only mode.",
"continueOnNewBranch": "Continue on a new branch",
"restoreReadOnlyWorkspace": "Restore read-only workspace",
"sessionStatusGenerating": "Generating",
"branchDisabledLocalExecutor": "The local executor uses your repository's current checkout, so the branch can't change here. Toggle 'Fork a new branch' to pick a different base.",
"branchDisabledNoBranches": "No branches available for this repository.",
+11
View File
@@ -492,6 +492,7 @@
"failedToRenameItem": "Ƒàĩĺēď ţō ŕēńàḿē ĩţēḿ",
"failedToRenameTask": "Ƒàĩĺēď ţō ŕēńàḿē ţàśķ",
"failedToRestorePlan": "Ƒàĩĺēď ţō ŕēśţōŕē ƥĺàń",
"failedToRestoreWorkspace": "Ƒàĩĺēď ţō ŕēśţōŕē ŵōŕķśƥàćē",
"failedToResumeSession": "Ƒàĩĺēď ţō ŕēśũḿē śēśśĩōń",
"failedToRevokeShare": "Ƒàĩĺēď ţō ŕēvōķē śĥàŕē.",
"failedToSaveDocument": "Ƒàĩĺēď ţō śàvē ďōćũḿēńţ",
@@ -810,6 +811,12 @@
"modelSelectionRemediationUnknown": "Ćĥēćķ ţĥē ēxēćũţōŕ ćōńƒĩĝũŕàţĩōń.",
"modelSelectionRequested": "Ŕēqũēśţēď ḿōďēĺ",
"modelSelectionWarning": "Ţĥē ēxēćũţōŕ ćōũĺď ńōţ ũśē ţĥē śàvēď ḿōďēĺ śēĺēćţĩōń.",
"branchRecreatedWarning": "Ţĥē śàvēď ƀŕàńćĥ ŵàś ũńàvàĩĺàƀĺē, śō à ńēŵ ƀŕàńćĥ ŵàś ćŕēàţēď.",
"branchRecreatedOriginal": "Őŕĩĝĩńàĺ ƀŕàńćĥ",
"branchRecreatedNew": "Ńēŵ ƀŕàńćĥ",
"branchRecreatedBase": "Ɓàśē ƀŕàńćĥ",
"branchRecreatedConversation": "Ćōńvēŕśàţĩōń ĥĩśţōŕŷ ćōńţĩńũēś ōń ţĥē ńēŵ ƀŕàńćĥ.",
"branchRecreatedCodeNotRecovered": "Ćōďē ćĥàńĝēś ƒŕōḿ ţĥē ũńàvàĩĺàƀĺē ƀŕàńćĥ ŵēŕē ńōţ ŕēćōvēŕēď.",
"monitor": "Ḿōńĩţōŕ",
"monitorCommand": "Ḿōńĩţōŕ: {{command}}",
"moreActions": "Ḿōŕē àćţĩōńś",
@@ -1818,6 +1825,10 @@
"failedToLoadFileContent": "Ƒàĩĺēď ţō ĺōàď ƒĩĺē ćōńţēńţ",
"openFileInProvider": "Ōƥēń ƒĩĺē ĩń {{provider}}",
"failedToResumeAndRestore": "Ƒàĩĺēď ţō ŕēśũḿē śēśśĩōń - ŵōŕķśƥàćē ŕēśţōŕē àĺśō ũńàvàĩĺàƀĺē",
"resumeAndRestoreFailed": "Ŕēśũḿē ƒàĩĺēď: {{resumeError}}. Ŵōŕķśƥàćē ŕēśţōŕē ƒàĩĺēď: {{restoreError}}.",
"resumeFailedWorkspaceReadOnly": "Ŕēśũḿē ƒàĩĺēď: {{error}}. Ţĥē ŵōŕķśƥàćē ŵàś ŕēśţōŕēď ĩń ŕēàď-ōńĺŷ ḿōďē.",
"continueOnNewBranch": "Ćōńţĩńũē ōń à ńēŵ ƀŕàńćĥ",
"restoreReadOnlyWorkspace": "Ŕēśţōŕē ŕēàď-ōńĺŷ ŵōŕķśƥàćē",
"sessionStatusGenerating": "Ĝēńēŕàţĩńĝ",
"branchDisabledLocalExecutor": "Ţĥē ĺōćàĺ ēxēćũţōŕ ũśēś ŷōũŕ ŕēƥōśĩţōŕŷ'ś ćũŕŕēńţ ćĥēćķōũţ, śō ţĥē ƀŕàńćĥ ćàń'ţ ćĥàńĝē ĥēŕē. Ţōĝĝĺē 'Ƒōŕķ à ńēŵ ƀŕàńćĥ' ţō ƥĩćķ à ďĩƒƒēŕēńţ ƀàśē.",
"branchDisabledNoBranches": "Ńō ƀŕàńćĥēś àvàĩĺàƀĺē ƒōŕ ţĥĩś ŕēƥōśĩţōŕŷ.",
+11
View File
@@ -477,6 +477,7 @@
"failedToRenameItem": "Falha ao mudar o nome do item",
"failedToRenameTask": "Não foi possível mudar o nome da tarefa",
"failedToRestorePlan": "Não foi possível restaurar o plano",
"failedToRestoreWorkspace": "Não foi possível restaurar o workspace",
"failedToResumeSession": "Não foi possível retomar a sessão",
"failedToRevokeShare": "Não foi possível revogar a partilha.",
"failedToSaveDocument": "Não foi possível guardar o documento",
@@ -1793,6 +1794,10 @@
"failedToLoadFileContent": "Falha ao carregar o conteúdo do ficheiro",
"failedToLoadFileTree": "Falha ao carregar a árvore de ficheiros",
"failedToResumeAndRestore": "Falha ao retomar a sessão - o restauro do workspace também está indisponível",
"resumeAndRestoreFailed": "Falha ao retomar: {{resumeError}}. Falha ao restaurar o workspace: {{restoreError}}.",
"resumeFailedWorkspaceReadOnly": "Falha ao retomar: {{error}}. O workspace foi restaurado em modo só de leitura.",
"continueOnNewBranch": "Continuar numa nova branch",
"restoreReadOnlyWorkspace": "Restaurar workspace só de leitura",
"gitOperationFailedGeneric": "A operação falhou",
"invalidGitHubUrl": "URL do GitHub inválido - esperava-se github.com/owner/repo ou .../pull/123",
"invalidRegex": "Expressão regular inválida",
@@ -1849,6 +1854,12 @@
"modelSelectionRemediationUnknown": "Verifique a configuração do executor.",
"modelSelectionRequested": "Modelo pedido",
"modelSelectionWarning": "O executor não conseguiu usar a seleção de modelo guardada.",
"branchRecreatedWarning": "A branch guardada não estava disponível, por isso foi criada uma nova branch.",
"branchRecreatedOriginal": "Branch original",
"branchRecreatedNew": "Nova branch",
"branchRecreatedBase": "Branch base",
"branchRecreatedConversation": "O histórico da conversa continua na nova branch.",
"branchRecreatedCodeNotRecovered": "As alterações de código da branch indisponível não foram recuperadas.",
"dynamicRouteWaiting": "Não existe um agente elegível disponível.",
"dynamicRouteActionRequired": "Esta rota precisa de uma ação de recuperação.",
"dynamicRouteRetry": "Repetir agente atual",
+11
View File
@@ -476,6 +476,7 @@
"failedToRenameBranch": "重命名分支失败",
"failedToRenameTask": "重命名任务失败",
"failedToRestorePlan": "恢复计划失败",
"failedToRestoreWorkspace": "还原工作区失败",
"failedToResumeSession": "无法恢复会话",
"failedToRevokeShare": "撤销分享失败。",
"failedToSaveDocument": "保存文档失败",
@@ -1793,6 +1794,10 @@
"failedToLoadFileContent": "加载文件内容失败",
"failedToLoadFileTree": "加载文件树失败",
"failedToResumeAndRestore": "恢复会话失败 - 工作区还原同样不可用",
"resumeAndRestoreFailed": "恢复失败:{{resumeError}}。还原工作区失败:{{restoreError}}。",
"resumeFailedWorkspaceReadOnly": "恢复失败:{{error}}。工作区已以只读模式还原。",
"continueOnNewBranch": "在新分支上继续",
"restoreReadOnlyWorkspace": "还原只读工作区",
"gitOperationFailedGeneric": "操作失败",
"invalidGitHubUrl": "GitHub 链接无效 - 应为 github.com/owner/repo 或 .../pull/123",
"invalidRegex": "正则表达式无效",
@@ -1849,6 +1854,12 @@
"modelSelectionRemediationUnknown": "请检查执行器配置。",
"modelSelectionRequested": "请求的模型",
"modelSelectionWarning": "执行器无法使用已保存的模型选择。",
"branchRecreatedWarning": "保存的分支不可用,因此已创建新分支。",
"branchRecreatedOriginal": "原始分支",
"branchRecreatedNew": "新分支",
"branchRecreatedBase": "基础分支",
"branchRecreatedConversation": "对话历史会在新分支上继续。",
"branchRecreatedCodeNotRecovered": "不可用分支中的代码更改未恢复。",
"dynamicRouteWaiting": "没有可用的合格代理。",
"dynamicRouteActionRequired": "此路由需要恢复操作。",
"dynamicRouteRetry": "重试当前代理",
+18 -7
View File
@@ -476,6 +476,7 @@
"failedToRenameBranch": "重命名分支失敗",
"failedToRenameTask": "重命名任務失敗",
"failedToRestorePlan": "恢復計劃失敗",
"failedToRestoreWorkspace": "還原工作區失敗",
"failedToResumeSession": "無法恢復工作階段",
"failedToRevokeShare": "撤銷分享失敗。",
"failedToSaveDocument": "儲存文檔失敗",
@@ -563,7 +564,7 @@
"groupExecutorType": "執行器類型",
"groupExecutorTypeDescription": "按執行器類型分開任務。",
"groupNone": "無",
"groupNoneDescription": "將所有任務保留在同一個清單中。",
"groupNoneDescription": "將所有任務保留在同一個列表中。",
"groupRepository": "儲存庫",
"groupRepositoryDescription": "按儲存庫分開任務。",
"groupState": "狀態",
@@ -1317,7 +1318,7 @@
"sidebarFilters": "側邊欄篩選",
"taskRow": "任務行",
"taskRowChangeRequestStatus": "變更請求狀態",
"taskRowChangeRequestStatusDescription": "顯示拉取請求或合併請求的狀態。",
"taskRowChangeRequestStatusDescription": "顯示拉取要求或合併請求的狀態。",
"taskRowDetails": "詳情行",
"taskRowDetailsCount_one": "{{count}} 項詳情",
"taskRowDetailsCount_other": "{{count}} 項詳情",
@@ -1337,7 +1338,7 @@
"taskRowRelativeTimeLastUpdate": "使用任務的最近更新時間。",
"taskRowRepository": "程式碼庫",
"taskRowRightSide": "右側",
"taskRowShownOnRight": "顯示於右側",
"taskRowShownOnRight": "顯示在右側",
"taskRowToggleDetail": "{{label}} 詳情可見性",
"taskRowToggleDetails": "顯示任務詳情",
"skipAllQuestions": "跳過全部問題",
@@ -1665,7 +1666,7 @@
"repositoryProviderVerificationPending": "請等待提供者檢查完成後再建立任務。",
"repositorySelectionInvalid": "無法驗證所選儲存庫。",
"repositorySelectionNotFound": "找不到所選儲存庫。",
"repositorySelectionUnavailable": "儲存庫提供者不可用。請檢查連線後重試。",
"repositorySelectionUnavailable": "儲存庫提供者不可用。請檢查連接後重試。",
"failedToCreateFile": "建立檔案失敗",
"failedToCreateSession": "建立工作階段失敗",
"failedToCreateTask": "建立任務失敗",
@@ -1694,8 +1695,8 @@
"failedToMoveTask": "移動任務失敗",
"taskMoveErrorGeneric": "無法移動任務。請重試。",
"taskMoveErrorActiveSession": "請先停止活動工作階段,再移動任務。",
"taskMoveErrorArchived": "已封存的任務無法移動。",
"taskMoveErrorDifferentWorkspace": "任務與目標工作流程必須使用相同的工作區。",
"taskMoveErrorArchived": "已歸檔的任務無法移動。",
"taskMoveErrorDifferentWorkspace": "任務和目標工作流程必須使用同一工作區。",
"taskMoveErrorWorkflowStep": "目標步驟不屬於目標工作流程。",
"taskMoveErrorWipLimit": "目標工作流程步驟已達到 WIP 限制。",
"movedTasksStepDescription_one": "任務現已位於所選步驟中。",
@@ -1793,6 +1794,10 @@
"failedToLoadFileContent": "載入檔案內容失敗",
"failedToLoadFileTree": "載入檔案樹失敗",
"failedToResumeAndRestore": "恢復工作階段失敗 - 工作區還原同樣不可用",
"resumeAndRestoreFailed": "恢復失敗:{{resumeError}}。還原工作區失敗:{{restoreError}}。",
"resumeFailedWorkspaceReadOnly": "恢復失敗:{{error}}。工作區已以只讀模式還原。",
"continueOnNewBranch": "在新分支上繼續",
"restoreReadOnlyWorkspace": "還原只讀工作區",
"gitOperationFailedGeneric": "操作失敗",
"invalidGitHubUrl": "GitHub 連結無效 - 應為 github.com/owner/repo 或 .../pull/123",
"invalidRegex": "正則表達式無效",
@@ -1849,6 +1854,12 @@
"modelSelectionRemediationUnknown": "請檢查執行器設定檔。",
"modelSelectionRequested": "請求的模型",
"modelSelectionWarning": "執行器無法使用已儲存的模型選擇。",
"branchRecreatedWarning": "儲存的分支不可用,因此已建立新分支。",
"branchRecreatedOriginal": "原始分支",
"branchRecreatedNew": "新分支",
"branchRecreatedBase": "基礎分支",
"branchRecreatedConversation": "對話歷史會在新分支上繼續。",
"branchRecreatedCodeNotRecovered": "不可用分支中的程式碼更改未恢復。",
"dynamicRouteWaiting": "沒有可用的合格代理。",
"dynamicRouteActionRequired": "此路由需要恢復操作。",
"dynamicRouteRetry": "重試目前代理",
@@ -1899,5 +1910,5 @@
"branchPolicyOptionSummary": "從 {{base}} 到 {{target}}",
"branchPolicySelected": "{{name}}(從 {{base}})",
"branchPolicyUnavailable": "基礎分支不可用。請刷新分支或編輯此策略。",
"branchPolicyRequiresSingleRepository": "使用本機執行器時,分支策略需要單一儲存庫。"
"branchPolicyRequiresSingleRepository": "使用本地執行器時,分支策略需要單個儲存庫。"
}
+16 -5
View File
@@ -476,6 +476,7 @@
"failedToRenameBranch": "重新命名分支失敗",
"failedToRenameTask": "重新命名任務失敗",
"failedToRestorePlan": "恢復計劃失敗",
"failedToRestoreWorkspace": "還原工作區失敗",
"failedToResumeSession": "無法恢復工作階段",
"failedToRevokeShare": "撤銷分享失敗。",
"failedToSaveDocument": "儲存檔案失敗",
@@ -1317,7 +1318,7 @@
"sidebarFilters": "側邊欄篩選",
"taskRow": "任務行",
"taskRowChangeRequestStatus": "變更請求狀態",
"taskRowChangeRequestStatusDescription": "顯示拉取請求或合併請求的狀態。",
"taskRowChangeRequestStatusDescription": "顯示提取要求或合併請求的狀態。",
"taskRowDetails": "詳情行",
"taskRowDetailsCount_one": "{{count}} 項詳情",
"taskRowDetailsCount_other": "{{count}} 項詳情",
@@ -1337,7 +1338,7 @@
"taskRowRelativeTimeLastUpdate": "使用任務的最近更新時間。",
"taskRowRepository": "程式碼庫",
"taskRowRightSide": "右側",
"taskRowShownOnRight": "顯示於右側",
"taskRowShownOnRight": "顯示在右側",
"taskRowToggleDetail": "{{label}} 詳情可見性",
"taskRowToggleDetails": "顯示任務詳情",
"skipAllQuestions": "跳過全部問題",
@@ -1694,8 +1695,8 @@
"failedToMoveTask": "移動任務失敗",
"taskMoveErrorGeneric": "無法移動任務。請重試。",
"taskMoveErrorActiveSession": "請先停止活動工作階段,再移動任務。",
"taskMoveErrorArchived": "已封存的任務無法移動。",
"taskMoveErrorDifferentWorkspace": "任務與目標工作流程必須使用相同的工作區。",
"taskMoveErrorArchived": "已歸檔的任務無法移動。",
"taskMoveErrorDifferentWorkspace": "任務和目標工作流程必須使用同一工作區。",
"taskMoveErrorWorkflowStep": "目標步驟不屬於目標工作流程。",
"taskMoveErrorWipLimit": "目標工作流程步驟已達到 WIP 限制。",
"movedTasksStepDescription_one": "任務現已位於所選步驟中。",
@@ -1793,6 +1794,10 @@
"failedToLoadFileContent": "載入檔案內容失敗",
"failedToLoadFileTree": "載入檔案樹失敗",
"failedToResumeAndRestore": "恢復工作階段失敗 - 工作區還原同樣不可用",
"resumeAndRestoreFailed": "恢復失敗:{{resumeError}}。還原工作區失敗:{{restoreError}}。",
"resumeFailedWorkspaceReadOnly": "恢復失敗:{{error}}。工作區已以只讀模式還原。",
"continueOnNewBranch": "在新分支上繼續",
"restoreReadOnlyWorkspace": "還原只讀工作區",
"gitOperationFailedGeneric": "操作失敗",
"invalidGitHubUrl": "GitHub 連結無效 - 應為 github.com/owner/repo 或 .../pull/123",
"invalidRegex": "正規表示式無效",
@@ -1849,6 +1854,12 @@
"modelSelectionRemediationUnknown": "請檢查執行器設定檔。",
"modelSelectionRequested": "請求的模型",
"modelSelectionWarning": "執行器無法使用已儲存的模型選擇。",
"branchRecreatedWarning": "儲存的分支不可用,因此已建立新分支。",
"branchRecreatedOriginal": "原始分支",
"branchRecreatedNew": "新分支",
"branchRecreatedBase": "基礎分支",
"branchRecreatedConversation": "對話歷史會在新分支上繼續。",
"branchRecreatedCodeNotRecovered": "不可用分支中的程式碼更改未恢復。",
"dynamicRouteWaiting": "沒有可用的合格代理。",
"dynamicRouteActionRequired": "此路由需要恢復操作。",
"dynamicRouteRetry": "重試目前代理",
@@ -1899,5 +1910,5 @@
"branchPolicyOptionSummary": "從 {{base}} 到 {{target}}",
"branchPolicySelected": "{{name}}(從 {{base}})",
"branchPolicyUnavailable": "基礎分支不可用。請重新整理分支或編輯此策略。",
"branchPolicyRequiresSingleRepository": "使用本機執行器時,分支策略需要單一儲存庫。"
"branchPolicyRequiresSingleRepository": "使用本地執行器時,分支策略需要單個儲存庫。"
}
@@ -0,0 +1,74 @@
# ADR-2026-08-31-explicit-new-branch-session-recovery: Require Explicit User Action Before Continuing a Session on a Replacement Branch
**Status:** accepted
**Date:** 2026-08-31
**Area:** backend, frontend, protocol
## Context
A stopped or failed task session can retain a valid provider resume token after
its Git worktree branch disappears locally and on the configured remote. The
conversation can still contain valuable context, but the commits and files
that existed only on the lost branch cannot be recovered.
Normal resume currently fails when the worktree manager returns
`ErrBranchUnrecoverable`. The web client also hides several resume errors. An
automatic branch switch would preserve the conversation, but it could make the
user believe that the prior code also returned.
The recovery path must keep task-environment worktree ownership, normal branch
naming, and provider session identity. It must distinguish confirmed branch
loss from network, authentication, and transient Git failures.
## Decision
Kandev requires an explicit user action before it continues a session on a
replacement branch.
A normal `resume` first runs the existing worktree recovery checks. If the
error chain matches `worktree.ErrBranchUnrecoverable`, the WebSocket response
contains typed recovery details and the UI offers **Continue on a new branch**.
Kandev does not replace the branch during that failed request.
The new `resume_new_branch` action authorizes replacement only after the same
worktree checks confirm that the branch is unrecoverable. The worktree manager
creates a unique branch from the configured task base branch with the normal
branch template and suffix helpers. It updates the task environment repository
record and then resumes the same `TaskSession` with the stored provider resume
identity.
The action does not clear the resume token. **Start fresh** remains the only
user recovery action that intentionally discards the stored conversation
identity before launch.
After successful replacement, the orchestrator persists an idempotent warning
status message. The message states that conversation history continues and
that code changes from the lost branch were not recovered. Structured metadata
records the old branch, new branch, base branch, session, and repository.
## Consequences
- A user sees the branch-loss cause before any irreversible recovery choice.
- The provider conversation can continue without claiming that lost code was
restored.
- Recovery requires one additional user action.
- Existing clients can display the descriptive error without reading the
structured details.
- Task environments remain the single owner of physical worktrees.
- Multi-repository tasks can replace one confirmed lost branch while retaining
valid worktrees.
- Branch replacement cannot hide authentication, network, or transient remote
failures.
## Alternatives Considered
- **Automatically create a replacement branch.** Rejected because the user
could mistake conversation recovery for code recovery.
- **Keep branch loss as a hard failure.** Rejected because a valid provider
conversation can still contain useful history.
- **Use Start fresh for branch loss.** Rejected because it clears the resume
identity and loses the provider conversation that this recovery must keep.
- **Restore only a read-only workspace.** Rejected as the only option because
it does not let the existing conversation continue agent work.
- **Reconstruct commits from session history.** Rejected because conversation
history is not an authoritative or complete Git object store.
+1
View File
@@ -222,6 +222,7 @@ Read individual ADRs for full context. Create new ones via `/record decision` or
| 2026-08-30-bound-untracked-dependency-enumeration | [Bound Untracked Dependency Enumeration](2026-08-30-bound-untracked-dependency-enumeration.md) | accepted | backend | 2026-08-30 |
| 2026-08-30-e2e-browser-cache | [Cache host-runner E2E browser provisioning](2026-08-30-e2e-browser-cache.md) | accepted | infra, workflow | 2026-08-30 |
| 2026-08-30-environment-owned-git-status | [Project Current Git Status From the Task Environment](2026-08-30-environment-owned-git-status.md) | proposed | backend, frontend, protocol | 2026-08-30 |
| 2026-08-31-explicit-new-branch-session-recovery | [Require Explicit User Action Before Continuing a Session on a Replacement Branch](2026-08-31-explicit-new-branch-session-recovery.md) | accepted | backend, frontend, protocol | 2026-08-31 |
| 2026-08-31-local-worktree-refresh-best-effort | [Local Worktree Refresh Is Best Effort](2026-08-31-local-worktree-refresh-best-effort.md) | accepted | backend, security, operations | 2026-08-31 |
| 2026-08-31-revoke-merge-approval-after-untrusted-push | [Revoke merge approval after an untrusted pull-request push](2026-08-31-revoke-merge-approval-after-untrusted-push.md) | accepted | workflow, security | 2026-08-31 |
| 2026-08-31-passthrough-running-publication | [Defer Passthrough Running Publication Until Guard Release](2026-08-31-passthrough-running-publication.md) | accepted | backend | 2026-08-31 |
+191
View File
@@ -0,0 +1,191 @@
---
created: 2026-08-31
status: implemented
requirements:
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-001
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003
system_design:
- ../../specs/agents/system-design/agent-resume-runtime-recovery.md
legacy_specs: []
---
# Implementation Plan: Visible Session Resume Recovery
## Overview
Make every session recovery failure visible. Add an explicit path that creates
a new branch after confirmed branch loss while it keeps the same provider
conversation. Persist an honest warning that separates conversation recovery
from code recovery.
## Confirmed root cause
- `session.recover` already returns a descriptive backend error, but
`SessionStoppedBanner` and `RunErrorEntry` catch and discard it.
- `useSessionResumption` discards the first resume cause, silently substitutes
read-only workspace restore, and returns a generic error only if both calls
fail.
- The WebSocket client rejects requests with a plain `Error`, so it drops the
backend error code and details that can authorize a specific recovery action.
- The worktree manager returns a wrapped `ErrBranchUnrecoverable` after local
and remote branch recovery fail. The resume launch path preserves that error
chain through workspace preparation.
- Normal worktree creation already owns unique branch templates and suffixes.
- The model-selection warning path provides the existing pattern for an
idempotent warning status message and localized chat rendering.
## Scope
### In scope
- Preserve WebSocket error code and structured details in the web client.
- Show the real recovery failure near each manual Resume control.
- Keep errors visible after busy state ends and after repeated attempts.
- Keep automatic read-only restore, but show the resume cause and read-only
result.
- Show both causes when resume and read-only restore fail.
- Add the explicit `resume_new_branch` recovery action.
- Create a unique branch from the configured task base after confirmed branch
loss.
- Confirm branch loss with a bounded authoritative remote probe when local and
remote-tracking refs are absent.
- Compensate replacement checkout and branch creation if environment-record
persistence fails.
- Keep the same task session, ACP session ID, and resume token.
- Persist one `branch_recreated` warning per replaced repository branch.
- Persist that warning on every terminal path after replacement materializes.
- Disable shared Retry controls while recovery requests are pending.
- Render honest localized warning copy in desktop and mobile chat.
- Add backend, frontend, desktop E2E, and mobile E2E regressions.
### Out of scope
- Recovering commits, files, or uncommitted work from the lost branch.
- Automatically switching branches after resume fails.
- Treating network, authentication, timeout, or unknown Git errors as branch
loss.
- Changing the provider conversation after branch replacement.
- Changing task-environment worktree ownership.
- Adding a new page, navigation flow, modal, or mobile-only recovery path.
## Technical approach
The first work order adds a TDD boundary at the worktree and resume layers.
Normal resume continues to return `ErrBranchUnrecoverable`. The explicit action
passes a narrow replacement permission through executor workspace preparation.
The worktree manager then uses its normal base selection and branch-name
generation to replace only a confirmed lost branch. Attach-only preflight uses
authoritative remote evidence, and replacement persistence compensates newly
created filesystem and Git state if its database update fails.
The second work order adds the typed recovery protocol and durable warning.
The WebSocket handler maps confirmed branch loss to a conflict with structured
recovery details. The orchestrator compares repository branch state around
workspace preparation, persists one claimed warning for each replacement on
every terminal resume path even when a later repository or provider step
fails, and reclaims timestamped claims left by a crash when no matching warning
exists.
The third work order makes every frontend recovery path observable. It retains
WebSocket error details, uses the existing alert pattern, and exposes explicit
actions. It also renders automatic read-only fallback as a notice and maps the
persisted warning metadata to localized copy.
The final work order verifies the complete user path on desktop and mobile and
runs the requested repository gates.
## Work orders
- [x] [Task 01: Create replacement worktrees without changing sessions](task-01-create-replacement-worktrees.md)
- [x] [Task 02: Expose typed branch recovery and persist warnings](task-02-persist-branch-recovery-warning.md)
- [x] [Task 03: Show recovery errors and actions](task-03-show-recovery-errors.md)
- [x] [Task 04: Verify desktop and mobile recovery](task-04-verify-recovery-flows.md)
## Dependency order
```text
Task 01 -> Task 02 -> Task 03 -> Task 04
```
The package is sequential. Each work order starts with a failing test. Task 02
depends on the explicit backend action from Task 01. Task 03 consumes the typed
protocol and warning metadata from Task 02. Task 04 verifies the integrated
behavior and full quality gates.
## Verification strategy
- Worktree tests prove normal error propagation and explicit branch creation
from the configured base, authoritative remote classification, transient
probe handling, and compensation after persistence failure.
- Executor and orchestrator tests prove service-level session, ACP identity, and
token preservation for `resume_new_branch`.
- Persistence tests prove complete warning metadata, state-guarded claims,
retry after write failure or a stale claim, partial multi-repository failure
handling, and duplicate suppression.
- Frontend unit tests prove errors are not swallowed and typed recovery actions
appear only for the matching backend details.
- Status-message tests prove honest localized branch warning rendering.
- Playwright tests prove visible errors, explicit continuation, reload
persistence, keyboard use, touch targets, and no horizontal overflow.
- Backend test, lint, changed-file complexity, Go formatting, frontend
typecheck, lint, and internationalization gates cover the full change.
## Risks
- A broad fallback flag could turn transient Git failures into fresh branches.
Keep the permission narrow and require `errors.Is` at the worktree boundary.
- A branch replacement can accidentally clear the provider identity if it
reuses Start fresh logic. Test the stored token and ACP session ID before and
after the action.
- Multi-repository preparation can partially update task environment records.
Preserve the existing launch failure boundary and test valid repository
reuse beside one replaced repository.
- Warning creation can duplicate on replay, disappear after a transient
database error, or leave a claim behind if the process crashes before the
message write. Use state-guarded timestamped claims, release on write
failure, and reclaim only stale claims without a matching warning message.
- Localized copy can imply code recovery. Keep the conversation and code
outcomes in separate sentences in every locale.
- Recovery actions can overflow narrow chat cards. Reuse the stacked mobile
layout and assert target size and document width.
- Remote branch probes can be mistaken for proof of deletion if their failure
class is collapsed. Keep confirmed absence distinct from auth and transport
failures.
- A persistence error after filesystem mutation can orphan a replacement. Keep
cleanup exact to the new path and branch tip so the prior record stays safe.
- A retry button that ignores the shared busy state can overlap recovery
requests and repeat branch preparation.
## Package handoff
The work orders are implemented in dependency order with TDD. Focused and full
verification results are recorded below.
## Results
- Task 01 preserves normal resume behavior and adds the explicit
`resume_new_branch` path. Race-enabled worktree, lifecycle, executor, and
orchestrator tests pass, including 17 worktree, 124 lifecycle, and 87
executor/orchestrator tests.
- Task 02 preserves typed branch-loss causes through the WebSocket conflict
response and persists idempotent `branch_recreated` warnings. The focused
race-enabled recovery tests pass with 3 tests; the handler selector exits
cleanly with no matching test names.
- Task 03 retains manual and automatic recovery causes, exposes typed branch
continuation only for confirmed branch loss, and renders localized warning
metadata. The focused frontend suite passes 73 tests; typecheck, lint, and
both internationalization gates pass.
- Task 04 passes the desktop and mobile branch-recovery E2E scenarios. Fresh
PR evidence is available in `apps/web/.pr-assets/` with one manifest entry
for each viewport.
- PR fixup hardens replacement eligibility against transient fetch failures,
preserves warnings after partial preparation failure, retains both manual
recovery causes, clears stale automatic feedback after an external recovery,
reclaims crash-stale warning claims, compensates failed replacement
persistence, and prevents overlapping retry requests.
- PR fixup adds a service-level `resume_new_branch` regression that reloads one
task session and its original ACP resume token after the action.
- Full backend tests pass with the managed-process configuration variables
cleared, backend lint and changed-file golangci-lint pass, the production
web build passes, and specification lint passes.
@@ -0,0 +1,158 @@
---
id: "01-create-replacement-worktrees"
title: "Create replacement worktrees without changing sessions"
status: done
wave: 1
depends_on: []
plan: "plan.md"
requirements:
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-001
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003
acceptance_criteria:
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-001.1
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-001.2
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.1
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.2
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.3
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.7
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.8
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.9
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.10
system_design:
- ../../specs/agents/system-design/agent-resume-runtime-recovery.md
---
# Task 01: Create Replacement Worktrees Without Changing Sessions
## Summary
Prove that normal resume propagates confirmed branch loss. Add the narrow
backend permission that creates a fresh worktree from the task base branch
without clearing the existing provider conversation identity.
## In scope
- Start with a failing resume test that matches
`worktree.ErrBranchUnrecoverable` through the executor and orchestrator error
chain.
- Add `resume_new_branch` to `Service.RecoverSession` validation.
- Keep the `runtime_retry`, `resume`, and `fresh_start` behavior unchanged.
- Pass a branch-replacement permission from explicit recovery through the
executor resume request and lifecycle workspace preparation.
- Add the permission to `worktree.CreateRequest`.
- Run normal local and remote branch recovery before replacement is eligible.
- When local and tracking refs are absent, run a bounded authoritative remote
probe and distinguish confirmed absence from authentication or network
failure.
- Generate the replacement directory and branch with the existing branch
template and suffix helpers.
- Create the new worktree from the configured task base branch.
- Update the existing task environment repository record.
- Remove a newly created checkout and branch if that record update fails.
- Preserve valid worktrees in a multi-repository task.
- Prove that the task session, ACP session ID, and stored resume token remain
unchanged.
- Prove the service-level `resume_new_branch` request keeps one task session,
the configured base branch, and the original provider identity.
## Out of scope
- WebSocket error details.
- Warning message persistence.
- Frontend changes or localized copy.
- Automatic branch replacement.
- Recovery from any error other than confirmed `ErrBranchUnrecoverable`.
## Acceptance
- Normal resume returns an error that matches `ErrBranchUnrecoverable` and does
not change the branch.
- `resume_new_branch` creates a unique normal-format branch from the configured
base branch after the same recovery checks confirm branch loss.
- The same `TaskSession`, ACP session ID, and resume token reach provider
launch.
- **Start fresh** remains the only action that clears the stored conversation
identity before launch.
- A multi-repository task retains each valid worktree and replaces only each
confirmed lost branch.
- Network and authentication failures remain errors and create no branch.
- A missing tracking ref does not advertise branch replacement when the remote
branch still exists.
- Failed replacement persistence leaves the old environment record in place
and no replacement checkout or branch on disk or in Git.
## Verification
Add the failing tests first and record the failure. Then run:
```bash
# From apps/backend:
rtk go test ./internal/worktree -run 'Test.*(Recreate|BranchUnrecoverable|ReplacementBranch)' -race
rtk go test ./internal/agent/runtime/lifecycle -run 'Test.*(Workspace|Worktree|ReplacementBranch)' -race
rtk go test ./internal/orchestrator/executor ./internal/orchestrator -run 'Test.*(Resume|RecoverSession).*(Branch|Token|Session)' -race
```
## Files likely touched
- `apps/backend/internal/worktree/worktree.go`
- `apps/backend/internal/worktree/manager_lifecycle.go`
- `apps/backend/internal/worktree/manager_lifecycle_test.go`
- `apps/backend/internal/agent/runtime/lifecycle/manager_execution.go`
- `apps/backend/internal/agent/runtime/lifecycle/manager_execution_test.go`
- `apps/backend/internal/orchestrator/executor/executor_resume.go`
- `apps/backend/internal/orchestrator/executor/executor_resume_test.go`
- `apps/backend/internal/orchestrator/session_launch.go`
- `apps/backend/internal/orchestrator/session_launch_test.go`
- `apps/backend/internal/orchestrator/task_operations.go`
- `apps/backend/internal/orchestrator/task_operations_test.go`
## Dependencies
None.
## Risks
- Branch templates can omit a suffix. Use the same collision checks and retry
behavior as normal worktree creation.
- Reusing contribution or pull-request refs as the replacement start point can
restore the wrong code. Resolve only the configured task base branch.
- Updating a session-owned path would violate task-environment ownership. Keep
all physical worktree changes in the existing task repository record.
- A token assertion only in memory can miss persistence changes. Reload the
session and executor records in the test.
- Remote-tracking refs can be pruned while the authoritative remote branch
remains. Probe the remote before emitting typed branch loss.
- Persistence can fail after `git worktree add`; compensate the exact new path
and branch without deleting the old recorded checkout.
## Parallelism
`sequential`
## Inputs
- `REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-001`.
- `REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003`.
- `docs/specs/agents/system-design/agent-resume-runtime-recovery.md`.
- `ADR-2026-08-31-explicit-new-branch-session-recovery`.
- Existing worktree recreate and executor resume tests.
## Results
- Implemented typed unrecoverable-branch errors and the explicit
`resume_new_branch` replacement path. Normal resume still returns the typed
error without changing the saved branch; explicit recovery creates a unique
branch from the configured base and updates the existing task environment
repository record.
- Preserved the task session, ACP session ID, resume token, and valid sibling
worktrees through the executor and lifecycle request chain.
- Added service-level coverage for `RecoverSession("resume_new_branch")`,
including one-session identity, configured base branch, ACP request identity,
and persisted resume-token assertions.
- GREEN: `rtk go test ./internal/worktree -run
'Test.*(Recreate|BranchUnrecoverable|ReplacementBranch)' -race` (17 passed).
- GREEN: `rtk go test ./internal/agent/runtime/lifecycle -run
'Test.*(Workspace|Worktree|ReplacementBranch)' -race` (124 passed).
- GREEN: `rtk go test ./internal/orchestrator/executor ./internal/orchestrator
-run 'Test.*(Resume|RecoverSession).*(Branch|Token|Session)' -race` (87
passed across 2 packages).
@@ -0,0 +1,149 @@
---
id: "02-persist-branch-recovery-warning"
title: "Expose typed branch recovery and persist warnings"
status: done
wave: 2
depends_on:
- "01-create-replacement-worktrees"
plan: "plan.md"
requirements:
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003
acceptance_criteria:
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.1
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.1
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.4
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.5
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.6
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.7
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.8
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.11
system_design:
- ../../specs/agents/system-design/agent-resume-runtime-recovery.md
---
# Task 02: Expose Typed Branch Recovery and Persist Warnings
## Summary
Map confirmed branch loss to structured recovery details. Persist one warning
status message after each confirmed explicit branch replacement, including a
replacement committed before a later repository preparation failure.
## In scope
- Add a typed orchestrator recovery error that wraps
`worktree.ErrBranchUnrecoverable` and retains repository branch context.
- Map the typed error to a WebSocket conflict with
`kind = branch_unrecoverable` and
`recovery_action = resume_new_branch`.
- Keep the descriptive message for clients that use only `Error.message`.
- Capture task environment repository branch state before explicit recovery.
- Compare repository state after successful recovery.
- Build a stable decision ID from session, repository, original branch, new
branch, and base branch.
- Claim warning persistence with a state-guarded
`SetSessionMetadataKeyIfAbsentIfState` value that includes a timestamp.
- Create a `status` message with `variant = warning`,
`kind = branch_recreated`, and complete structured metadata.
- Release the claim after message creation fails.
- Reclaim a stale timestamped claim only when no matching warning message
exists, covering a process crash between the claim and message write.
- Persist one warning for each replaced repository in a multi-repository task.
- Persist the branch transition on every terminal resume path after workspace
preparation can materialize it, including provider startup/readiness failure.
- Publish the created message through the existing message adapter path.
## Out of scope
- A new runtime stream event.
- Frontend error handling and warning rendering.
- Worktree creation logic.
- Database schema changes.
- Raw Git output in WebSocket details or persisted messages.
## Acceptance
- Only an error chain that matches `ErrBranchUnrecoverable` advertises the
explicit branch action.
- The recovery details identify the session, repository, old branch, and base
branch without exposing secrets or raw Git output.
- Successful branch continuation persists one status message with the exact
warning kind and required metadata.
- Repeated persistence, event replay, and reload do not create a duplicate.
- A failed message write releases the claim and a later attempt can succeed.
- A crash before message creation leaves a reclaimable claim, while a matching
persisted warning prevents duplicate creation.
- A later preparation failure does not lose warnings for earlier replacements.
- A provider startup or readiness failure after replacement still leaves one
warning persisted or retryable.
- Each replaced repository in a multi-repository task receives its own warning.
## Verification
Start with handler and persistence tests that fail against the current generic
error and missing message. Then run:
```bash
# From apps/backend:
rtk go test ./internal/orchestrator/handlers -run 'Test.*RecoverSession.*Branch' -race
rtk go test ./internal/orchestrator -run 'Test.*(BranchRecovery|BranchRecreated|WarningClaim)' -race
```
## Files likely touched
- `apps/backend/internal/orchestrator/session_launch.go`
- `apps/backend/internal/orchestrator/session_launch_test.go`
- `apps/backend/internal/orchestrator/handlers/handlers.go`
- `apps/backend/internal/orchestrator/handlers/handlers_test.go`
- `apps/backend/internal/orchestrator/session_branch_recovery.go`
- `apps/backend/internal/orchestrator/session_branch_recovery_test.go`
- `apps/backend/internal/orchestrator/service.go`
- `apps/backend/internal/backendapp/adapters.go`
## Dependencies
- Task 01 provides the explicit action and records the replacement in the task
environment repository state.
## Risks
- A claim made before launch can suppress a warning for a failed replacement.
Claim only after the old and new branches differ, and persist it even when a
later repository fails so committed replacements remain visible.
- A process can stop between the claim and message write. Timestamp the claim
and reclaim it only after it is stale and no matching message exists.
- A decision ID without repository identity can collapse distinct warnings in
a multi-repository task.
- Persisted content can bypass localization if it contains user-facing prose.
Keep the content neutral and render localized text from structured metadata.
- A generic internal error code prevents safe action selection. Return a
conflict only for the typed branch-loss error.
## Parallelism
`sequential`
## Inputs
- Completed Task 01 behavior.
- `REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002`.
- `REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003`.
- Existing model-selection warning claim and persistence helpers.
- Existing WebSocket `ErrorPayload` contract.
## Results
- Implemented typed branch-recovery details with the descriptive backend
message preserved for generic clients. Only an error chain matching
`ErrBranchUnrecoverable` advertises `resume_new_branch`.
- Implemented before-and-after repository branch snapshots, atomic warning
claims, claim release after write failure, stale-claim reclamation after a
crash, and idempotent status-message persistence for each replaced repository,
including partial preparation failures.
- GREEN: `rtk go test ./internal/orchestrator -run
'Test.*(BranchRecovery|BranchRecreated|WarningClaim)' -race` (3 passed).
- GREEN: focused handler and orchestrator recovery tests pass with
`rtk go test ./internal/orchestrator ./internal/orchestrator/handlers -run
'BranchRecovery|RecoverSession'`. The narrower handler race selector matched
no tests and exited successfully.
@@ -0,0 +1,158 @@
---
id: "03-show-recovery-errors"
title: "Show recovery errors and actions"
status: done
wave: 3
depends_on:
- "02-persist-branch-recovery-warning"
plan: "plan.md"
requirements:
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003
acceptance_criteria:
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.1
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.2
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.3
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.4
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.5
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.6
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.1
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.4
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.5
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.8
system_design:
- ../../specs/agents/system-design/agent-resume-runtime-recovery.md
---
# Task 03: Show Recovery Errors and Actions
## Summary
Stop discarding resume errors. Reuse the existing inline alert and status
message patterns to show causes, read-only outcomes, and the explicit branch
continuation action.
## In scope
- Start with failing tests in all three known error-swallowing paths.
- Add a typed WebSocket request error that retains backend code and details.
- Keep existing callers compatible with the standard `Error` interface.
- Make the shared session recovery helper reject with the typed error.
- Retain the last error in `SessionStoppedBanner` after busy state ends.
- Retain the last error in `RunErrorEntry` after busy state ends.
- Disable the shared Retry control while a recovery request is pending on all
recovery surfaces.
- Reuse `EnsureSessionErrorBanner` alert anatomy and error description rules.
- Show **Continue on a new branch** only for the typed branch-loss details.
- Offer visible read-only workspace restore after manual resume failure.
- Retain manual resume and read-only restore causes independently, including
branch details associated with the resume failure.
- Keep automatic read-only fallback and return a visible notice with the first
failure cause.
- Return both causes when automatic resume and restore fail.
- Clear stale automatic feedback when the shared session state becomes active
after an external manual recovery.
- Render the hook result in task, preview, and Quick Chat consumers.
- Map `branch_recreated` status metadata to localized honest warning copy.
- Add every new key to all six locale catalogs. Generate Traditional Chinese
values with `pnpm run i18n:zh-hant`.
## Out of scope
- A new alert component library or recovery page.
- Automatic branch replacement.
- Translation of branch names or other metadata values.
- A new WebSocket event handler for the persisted warning.
- Changes to Start fresh confirmation semantics.
## Acceptance
- A failed manual Resume or Start fresh request shows the backend message near
the clicked control and leaves it visible after the request finishes.
- A repeated click updates or retains visible feedback and never becomes a
no-op with no explanation.
- A successful automatic read-only restore states why resume failed and that
the workspace is read-only.
- A double failure displays the resume cause and the restore cause.
- A manual resume failure followed by a restore failure displays both causes
and keeps any branch-continuation action tied to the resume failure.
- Only branch-loss details expose **Continue on a new branch**.
- A successful branch replacement clears the blocking error and the persisted
warning states that conversation history continued while old code did not.
- Desktop and mobile use the same capabilities and existing responsive action
layout.
- Repeated Retry clicks while a request is pending do not overlap recovery
requests.
## Verification
Add failing tests first. Then run:
```bash
# From apps/web:
rtk pnpm test -- lib/ws/client.test.ts components/task/chat/session-stopped-banner.test.tsx components/task/simple/components/run-error-entry.test.tsx hooks/domains/session/use-session-resumption.test.ts components/task/chat/messages/status-message.test.tsx
rtk pnpm run typecheck
rtk pnpm run i18n:check
rtk pnpm run i18n:ratchet
# From apps:
rtk pnpm --filter @kandev/web lint
```
## Files likely touched
- `apps/web/lib/ws/client.ts`
- `apps/web/lib/ws/client.test.ts`
- `apps/web/components/task/chat/session-stopped-banner.tsx`
- `apps/web/components/task/chat/session-stopped-banner.test.tsx`
- `apps/web/components/task/simple/components/run-error-entry.tsx`
- `apps/web/components/task/simple/components/run-error-entry.test.tsx`
- `apps/web/hooks/domains/session/use-session-resumption.ts`
- `apps/web/hooks/domains/session/use-session-resumption.test.ts`
- Task, preview, and Quick Chat consumers of `useSessionResumption`
- `apps/web/components/task/ensure-session-error.tsx`
- `apps/web/components/task/chat/messages/status-message.tsx`
- `apps/web/components/task/chat/messages/status-message.test.tsx`
- `apps/web/src/locales/*/task.json`
- `apps/web/src/locales/*/chat.json`
## Dependencies
- Task 02 provides the typed error details and persisted warning metadata.
## Risks
- A broad error-state reset can hide the cause before the user can read it.
Clear it only on a later success or explicit dismissal.
- Rendering raw details can expose internal fields. Render the backend message
and only the approved branch metadata.
- A module-scope translation call freezes the boot locale. Translate only
during render or hook execution.
- A translated confirmation token can break exact input comparisons. Keep any
persisted token stable and translate only its explanation.
- Locale catalogs fail the build if keys or placeholders differ. Run all
internationalization gates after `zh-hant` generation.
## Parallelism
`sequential`
## Inputs
- Completed Task 02 protocol and metadata.
- Existing `EnsureSessionErrorBanner`.
- Existing model-selection warning status rendering.
- Existing session recovery component and hook tests.
- Mobile UI language reference for inline alerts and action layout.
## Results
- Implemented typed WebSocket request errors, persistent manual recovery
feedback, automatic read-only fallback notices, and typed branch-continuation
actions in the stopped-session, run-error, and automatic-resume surfaces.
- Added localized branch-recreated warning rendering and completed all six
locale catalogs using the Traditional Chinese generator.
- GREEN: focused frontend recovery suite, 6 files and 73 tests passed.
- GREEN: `rtk pnpm run typecheck`, `rtk pnpm run i18n:check`,
`rtk pnpm run i18n:ratchet`, and `rtk pnpm --filter @kandev/web lint`.
- GREEN: `rtk pnpm run i18n:zh-hant -- --namespace task`.
@@ -0,0 +1,160 @@
---
id: "04-verify-recovery-flows"
title: "Verify desktop and mobile recovery"
status: done
wave: 4
depends_on:
- "03-show-recovery-errors"
plan: "plan.md"
requirements:
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003
acceptance_criteria:
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.1
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.2
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.3
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.4
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.5
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.1
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.2
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.4
- AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.6
system_design:
- ../../specs/agents/system-design/agent-resume-runtime-recovery.md
---
# Task 04: Verify Desktop and Mobile Recovery
## Summary
Verify the complete user journey on desktop and mobile. Run the full backend,
frontend, formatting, complexity, and internationalization gates requested for
delivery.
## In scope
- Extend the session page object with error, read-only, new-branch, and warning
locators.
- Add a deterministic E2E fixture for a session whose stored branch is absent
locally and on its configured remote.
- Prove the first Resume click shows the descriptive error.
- Prove repeated Resume clicks retain visible feedback.
- Prove the branch action is explicit and resumes the same conversation on a
new branch from the configured base.
- Prove the warning survives page reload and appears only once.
- Prove automatic read-only restore shows its notice and failure cause.
- Add an equivalent `mobile-*.spec.ts` path for the recovery surface.
- Assert mobile touch targets, keyboard reachability, and no horizontal
overflow.
- Run all requested repository validation commands.
## Out of scope
- Screenshot documentation or public documentation changes.
- Performance benchmarks unrelated to recovery.
- Provider-specific remote branch deletion outside the deterministic Git
fixture.
- Visual redesign of the stopped-session banner or status message.
## Acceptance
- Desktop E2E covers failure feedback, explicit continuation, conversation
continuity, honest warning copy, idempotency after reload, and read-only
notice behavior.
- Mobile E2E covers the same recovery capabilities in the existing chat
surface.
- Mobile recovery actions have at least 44 by 44 CSS pixels and remain usable
without document-level horizontal overflow.
- Keyboard focus reaches each visible recovery action and activation works.
- Backend, frontend, formatting, complexity, and internationalization gates
pass from the current PR base.
## Verification
Install workspace dependencies once if this worktree does not have them. Run:
```bash
# From apps:
rtk pnpm install --frozen-lockfile
# From apps/web:
rtk pnpm e2e:run --host tests/session/session-resume-recovery.spec.ts
rtk pnpm e2e:run --host --project mobile-chrome tests/session/mobile-session-resume-recovery.spec.ts
rtk pnpm run typecheck
rtk pnpm run i18n:check
rtk pnpm run i18n:ratchet
# From apps:
rtk pnpm --filter @kandev/web lint
# From the repository root:
rtk bash -lc 'unset KANDEV_INTERNAL_CONFIG_FILE KANDEV_INTERNAL_CONFIG_HOME_FILE KANDEV_SERVER_PORT KANDEV_BACKEND_PORT KANDEV_PORT
export HOME=/tmp/kandev-task-test-home
exec make -C apps/backend test'
rtk make -C apps/backend lint
# From apps/backend. Refresh the SHA if the branch is rebased:
rtk golangci-lint run ./... --new-from-rev="fd2c7dcdff0cd7a1292653c2199f4945d796873b" --timeout=5m
# From the repository root after staging Go files:
rtk bash -lc 'git diff --cached --name-only --diff-filter=ACMR | grep "\.go$" | xargs -r gofmt -l'
rtk git diff --check
```
The Go formatting command must produce no output. Run `gofmt -w` on each
reported file, stage it again, and rerun the check.
## Files likely touched
- `apps/web/e2e/pages/session-page.ts`
- `apps/web/e2e/tests/session/session-recovery.spec.ts`
- `apps/web/e2e/tests/session/mobile-session-resume-recovery.spec.ts`
- E2E API helpers or fixtures needed for deterministic branch deletion
- `docs/plans/session-resume-recovery/plan.md`
- Completed work orders in this plan directory
## Dependencies
- Task 03 completes the visible desktop and mobile recovery surface.
## Risks
- A mock that returns only a frontend error does not prove the worktree path.
Seed real local Git state and remove both recoverable refs.
- A desktop test that only narrows the viewport does not select the mobile
shell. Use the `mobile-chrome` project and a `mobile-*.spec.ts` file.
- Reload can race message history. Wait for persisted session history before
asserting the single warning count.
- The recorded base SHA can become stale after rebase. Recompute the PR
merge-base before the changed-file complexity gate.
- Full backend tests can reveal unrelated failures. Record exact evidence and
separate it from focused recovery regressions.
## Parallelism
`sequential`
## Inputs
- Completed Tasks 01 through 03.
- Existing `session-recovery.spec.ts` and `SessionPage` recovery locators.
- Existing mobile model-warning and recovery E2E patterns.
- PR base SHA `fd2c7dcdff0cd7a1292653c2199f4945d796873b` at plan creation.
## Results
- GREEN: desktop branch-recovery E2E, 1 passed in 20.1s. It covers visible
failure feedback, explicit new-branch continuation, session continuity,
persisted warning metadata, reload idempotency, and automatic restore
feedback.
- GREEN: mobile branch-recovery E2E, 1 passed in 20.1s. It covers the same
actions with mobile shell behavior, keyboard focus, touch targets, and
horizontal-overflow checks.
- Fresh PR screenshots were captured and reviewed at
`apps/web/.pr-assets/session-resume-recovery--session-resume-recovery-desktop.png`
and
`apps/web/.pr-assets/mobile-session-resume-recovery--session-resume-recovery-mobile.png`.
The manifest validates both files.
- GREEN: isolated full backend tests, backend lint, changed-file
`golangci-lint`, frontend lint, typecheck, i18n checks, production Vite
build, and `python3 scripts/lint-spec-files.py --all`.
+1
View File
@@ -62,6 +62,7 @@ surface shared by task and Office consumers.
### System design
- [Agent Resume and Runtime Recovery](system-design/agent-resume-runtime-recovery.md)
- [Dynamic Agent Routing System Design Part 1](system-design/dynamic-agent-routing-01.md)
- [Dynamic Agent Routing System Design Part 2](system-design/dynamic-agent-routing-02.md)
- [Agent Profile Recent Use](system-design/profile-recent-use.md)
@@ -28,6 +28,37 @@ Preserve the observable behavior documented for Agent Resume and Runtime Recover
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-001.7:** The explicit managed-runtime update path may invalidate only the deterministic `_npx` execution directory for the selected built-in package after an initial update failure, then retry once and run the normal ACP capability probe.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-001.8:** **GIVEN** a valid OpenCode resume token, **WHEN** the OpenCode child exits before answering ACP `initialize`, **THEN** Kandev shows the normal recovery action and retains the same token for the next Resume attempt.
### REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002: Visible resume failure feedback
**Intent:** Give the user the real failure cause and a visible next action when session recovery fails.
#### Acceptance criteria
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.1:** A failed `session.recover` request shows the backend error near the recovery controls. The error remains visible after the request ends and after repeated attempts.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.2:** A failed automatic resume that restores the workspace in read-only mode shows a nonblocking notice. The notice includes the resume failure cause and states that the restored workspace is read-only.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.3:** If resume and read-only workspace restore both fail, the recovery surface shows both causes. It does not replace them with only a generic message.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.4:** A user can select read-only workspace restore after a manual resume failure. Kandev does not silently replace a manual Resume request with read-only restore.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.5:** Desktop, narrow desktop, and mobile task views use the existing inline alert and chat recovery patterns. Recovery actions remain reachable by keyboard and touch without horizontal overflow.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002.6:** A Retry recovery control is disabled while its recovery request is in flight on every recovery surface. A repeated attempt cannot create overlapping `session.recover` requests.
### REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003: Explicit continuation after branch loss
**Intent:** Continue the same provider conversation on a new branch when the old branch cannot be recovered.
#### Acceptance criteria
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.1:** When resume returns an error that matches `worktree.ErrBranchUnrecoverable`, Kandev offers an explicit **Continue on a new branch** action. Kandev does not switch branches before the user selects this action.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.2:** The action keeps the same `TaskSession`, stored resume token, and ACP session identity. It creates a fresh worktree on a unique branch from the task repository's configured base branch.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.3:** The new branch uses the normal worktree branch template and suffix generation. It remains owned by the task environment and does not create a session-owned worktree record.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.4:** After continuation succeeds, the chat contains a persisted warning. The warning states that the original branch is gone, the conversation history continues, and code changes from the lost branch were not recovered.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.5:** The warning has `variant = "warning"` and `kind = "branch_recreated"`. Its structured metadata contains the original branch, new branch, base branch, task session ID, and repository ID.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.6:** Warning persistence is idempotent for one branch replacement. Reconnect, replay, and page reload do not create duplicate messages.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.7:** In a task with multiple repositories, Kandev replaces only worktrees whose branches are confirmed unrecoverable. Valid worktrees continue to use their current branches. Kandev persists one warning for each replaced branch.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.8:** Other resume failures do not offer branch replacement. **Start fresh** keeps its current behavior and remains the only recovery action that intentionally clears the stored conversation identity.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.9:** Attach-only worktree preflight treats a branch as unrecoverable only after a bounded noninteractive probe confirms that the configured remote does not contain it. Authentication, network, timeout, and other probe failures remain ordinary recovery failures.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.10:** If replacement checkout creation succeeds but persistence of the existing task-environment repository record fails, Kandev removes the replacement checkout and its newly created branch. The prior record remains authoritative for retry.
- **AC-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003.11:** Once explicit replacement has materialized, Kandev attempts warning persistence on every terminal resume path, including provider startup and readiness failures. A later retry can recover a warning after a failed message write.
## Migrated source detail
## Broken behavior
@@ -76,6 +107,12 @@ without repairing it.
deterministic `_npx` execution directory for the selected built-in package
after an initial update failure, then retry once and run the normal ACP
capability probe.
- A failed resume stays visible with the backend cause and a recovery action.
- An automatic read-only restore states that resume failed and that the
restored workspace is read-only.
- A confirmed missing branch offers explicit continuation on a new branch from
the task base branch. The same conversation continues, but lost code does
not return.
## Persistence and security constraints
@@ -92,6 +129,21 @@ without repairing it.
resolves npm's cache root through direct argv, and removes only
`<cache>/_npx/<package-key>`. It never accepts a caller-provided path or runs
a global cache clean.
- Branch replacement updates the task environment repository record. It does
not introduce a session-owned worktree record.
- Branch replacement does not clear or replace the stored resume token before
the provider resumes the existing conversation.
- The branch replacement option is available only for a typed error that wraps
`worktree.ErrBranchUnrecoverable`. Network, authentication, and transient Git
errors remain failures.
- Attach-only branch-loss classification uses a bounded noninteractive remote
probe when local and remote-tracking refs are absent. A missing tracking ref
alone is not proof that the configured remote branch was deleted.
- Replacement persistence is compensating: if the existing task-environment
repository update fails after checkout creation, the new checkout and branch
are removed and the old database record is left unchanged.
- The persisted warning uses an atomic metadata claim before message creation.
A failed message write releases the claim so a later retry can persist it.
## Regression scenarios
@@ -124,6 +176,35 @@ without repairing it.
- **GIVEN** the targeted cache repair or retry also fails, **WHEN** the update
job becomes terminal, **THEN** it reports the bounded failure and performs no
additional retry or broad cache deletion.
- **GIVEN** a manual Resume request fails, **WHEN** the backend returns a
descriptive error, **THEN** the recovery surface keeps that message visible
and offers the applicable next actions.
- **GIVEN** automatic resume fails and read-only restore succeeds, **WHEN** the
task view loads, **THEN** it shows the resume cause and states that the
workspace is read-only.
- **GIVEN** automatic resume and read-only restore both fail, **WHEN** the task
view loads, **THEN** it shows both failure causes.
- **GIVEN** the stored worktree branch is absent locally and on its configured
remote, **WHEN** Resume fails, **THEN** the UI offers **Continue on a new
branch** and does not run it automatically.
- **GIVEN** the user selects **Continue on a new branch**, **WHEN** recovery
succeeds, **THEN** the same task session resumes through its stored provider
identity on a unique branch from the configured base branch.
- **GIVEN** branch continuation succeeds, **WHEN** the chat reloads or replays
events, **THEN** one warning identifies the old branch, new branch, and base
branch and states that the old code was not recovered.
- **GIVEN** local and remote-tracking refs are absent but the configured remote
still contains the branch, **WHEN** attach-only preflight runs, **THEN** it
returns an ordinary reuse failure and does not advertise branch replacement.
- **GIVEN** attach-only preflight cannot authenticate to or reach the remote,
**WHEN** the branch refs are absent locally, **THEN** it returns the probe
failure and does not classify the branch as unrecoverable.
- **GIVEN** replacement checkout creation succeeds but the task-environment
update fails, **WHEN** recovery returns, **THEN** no replacement checkout or
branch remains and the prior environment record is unchanged.
- **GIVEN** replacement materializes before provider startup or readiness fails,
**WHEN** the resume attempt reaches a terminal path, **THEN** one warning is
persisted or remains retryable without changing the session identity.
## Out of scope
@@ -133,4 +214,9 @@ without repairing it.
- Global npm cache cleanup, exact runtime-version pins, rollback, or selection
of historical runtime versions.
- Relaxing credential-broker authorization for terminal sessions.
- New recovery buttons or other frontend behavior.
- Reconstructing commits, uncommitted files, or other code from a branch that
no longer exists locally or on the configured remote.
- Automatic continuation on a new branch after branch loss.
- Branch replacement for an authentication, network, timeout, or other
unconfirmed Git failure.
- New navigation, a new recovery page, or a new mobile-only recovery workflow.
@@ -0,0 +1,282 @@
---
status: current
system: agents
requirements:
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-001
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002
- REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003
---
# Agent resume and runtime recovery system design
## Purpose and boundaries
This design preserves a provider conversation when session launch fails. It
also defines visible recovery errors and explicit continuation after confirmed
Git branch loss.
The orchestrator owns recovery authorization, session identity, and warning
persistence. The worktree manager owns branch verification and fresh branch
creation. The web client owns error presentation and recovery choices.
The task environment remains the owner of worktrees. A task session refers to
that environment and does not acquire its own worktree lifecycle.
## Requirement mapping
| Requirement | Design section |
| --- | --- |
| `REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-001` | [Session identity](#session-identity) |
| `REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-002` | [Visible recovery errors](#visible-recovery-errors) |
| `REQ-AGENTS-AGENT-RESUME-RUNTIME-RECOVERY-003` | [Explicit branch replacement](#explicit-branch-replacement), [Warning persistence](#warning-persistence) |
## Current failure path
`Service.ResumeTaskSession` calls `executor.Executor.ResumeSession`. The
executor builds the existing resume request and asks the lifecycle manager to
prepare the task workspace. Worktree preparation calls
`worktree.Manager.Create`, which can recreate an invalid worktree.
`Manager.recreate` returns a wrapped `worktree.ErrBranchUnrecoverable` only
after it cannot find the branch locally and receives the distinct
`worktree.ErrRemoteRefMissing` sentinel from confirmed missing-ref evidence
at the configured remote. Authentication, network, timeout, and other fetch
failures remain their original failure class and cannot authorize replacement.
The wrapped error already reaches `Service.RecoverSession` and the
`session.recover` WebSocket handler.
Attach-only reuse has one additional evidence boundary. If the local branch and
`refs/remotes/origin/<branch>` are both absent, the manager runs a bounded,
noninteractive `git ls-remote` probe against the configured remote. Only a
confirmed missing remote ref produces `ErrBranchUnrecoverable`; an
authentication, network, timeout, or other probe failure remains an ordinary
reuse failure. A pruned tracking ref therefore cannot be mistaken for remote
branch deletion.
The web client currently converts WebSocket failures to a plain `Error` and
several resume call sites then discard that error. Automatic resume also hides
the resume error when read-only workspace restore succeeds.
## Recovery protocol
`session.recover` accepts these actions:
- `resume` retries the current worktree and provider conversation.
- `fresh_start` keeps its current behavior and clears the provider resume
identity before a new conversation starts.
- `runtime_retry` keeps its current managed-runtime behavior.
- `resume_new_branch` resumes the current provider conversation and permits
replacement of only a confirmed unrecoverable worktree branch.
`resume_new_branch` is explicit. A failed `resume` never changes the branch.
The handler returns a typed WebSocket conflict when the error chain matches
`worktree.ErrBranchUnrecoverable`. The error details contain:
```text
kind: branch_unrecoverable
recovery_action: resume_new_branch
original_branch: <branch>
base_branch: <configured task base>
repository_id: <workspace repository>
session_id: <task session>
```
The public error message remains descriptive for clients that do not inspect
details. Other failures retain their existing error codes and do not advertise
branch replacement.
The web WebSocket client retains `code`, `message`, and `details` in a typed
request error. Existing consumers can still treat it as an `Error`.
## Session identity
`resume_new_branch` uses the existing `TaskSession`. It does not clear
`task_sessions.metadata.acp.session_id` or `executors_running.resume_token`.
The executor passes the same provider resume identity to agent launch after
workspace preparation succeeds.
The existing guarded transition to `STARTING`, resume lock, failure rollback,
and successful token replacement rules remain unchanged. Only **Start fresh**
can intentionally remove the stored provider identity before launch.
## Explicit branch replacement
The resume request carries an internal permission to replace a confirmed
unrecoverable branch. The permission flows through executor workspace
preparation into `worktree.CreateRequest`. Normal resume leaves it disabled.
`Manager.recreate` first runs the normal local and remote recovery checks. If
those checks return `ErrBranchUnrecoverable` and replacement permission is
disabled, it returns the error without changing branch identity. If permission
is enabled, the manager performs these steps:
1. Resolve the task repository's configured base branch through the existing
base-ref selection and required refresh rules.
2. Keep the existing task directory and repository association.
3. Generate a new worktree directory and Git branch with the existing branch
template, `TaskBranchNameWithSuffix`, and random suffix helpers.
4. Create the worktree from the resolved base branch.
5. Update the existing task environment repository record with the new path,
branch, and ready state.
6. Continue normal agent launch with the original session resume identity.
The update is compensating. If the existing task-environment repository record
cannot be persisted after the new checkout is created, the manager removes the
new checkout and deletes its newly created branch with an exact-tip check. The
previous record remains authoritative, so a retry does not accumulate orphan
checkouts or branches.
This path does not copy commits, uncommitted files, or Git state from the lost
branch. It does not reuse the lost branch name. Pull-request and contribution
refs from the lost branch do not become the starting ref for the replacement.
For a task with multiple repositories, each `Create` call evaluates its own
worktree. A valid worktree is reused. A confirmed unrecoverable worktree is
replaced only when the explicit permission is present. Any unrelated failure
stops launch through the existing atomic preparation boundary.
## Warning persistence
The orchestrator captures repository branch state before explicit recovery and
loads it again after workspace preparation completes. Each confirmed branch
replacement produces one `status` message through `CreateSessionMessage`, even
when a later repository preparation failure aborts the overall resume. The
message metadata is:
```text
variant: warning
kind: branch_recreated
original_branch: <lost branch>
new_branch: <created branch>
base_branch: <configured task base>
session_id: <task session>
repository_id: <workspace repository>
decision_id: <stable replacement identity>
```
The content is a neutral internal status value. The frontend selects localized
copy from `metadata.kind` and the structured branch fields.
Before message creation, the orchestrator uses a state-guarded
`SetSessionMetadataKeyIfAbsentIfState` claim with a timestamp and a key derived
from the session, repository, original branch, new branch, and base branch.
This follows the model-selection warning claim pattern. A duplicate active
claim skips message creation. A stale timestamped claim is reclaimed only
when the session state still matches and no matching warning message exists,
so a process crash between claiming and message creation can be retried. A
failed message write releases the claim so a later retry can persist the
warning.
The comparison and warning attempt happen on every terminal path after resume
workspace preparation can materialize a replacement. Provider startup and
readiness failures therefore cannot bypass the warning, and a later retry does
not lose the old branch identity by taking the already-replaced branch as its
new baseline.
Direct orchestrator persistence is preferred over a runtime stream event. The
orchestrator makes the branch decision and already owns the old and new branch
state. A runtime event would add a second source without adding evidence.
## Visible recovery errors
The manual recovery controls use one shared request helper that rejects with
the typed WebSocket error. `SessionStoppedBanner` and `RunErrorEntry` retain the
last error in component state and render the existing destructive alert
pattern. The busy state ends after the request, but the error stays visible.
The alert shows the backend message and these applicable actions:
- **Retry resume** for a normal recoverable failure.
- **Restore read-only workspace** when workspace restoration remains useful.
- **Continue on a new branch** only for `branch_unrecoverable` details.
- **Start fresh** with the existing confirmation because it loses provider
conversation history.
The shared Retry control is disabled while its corresponding recovery request
is pending. All three recovery surfaces use the same busy state, so repeated
clicks cannot overlap resume requests.
Automatic page-load resume can keep its current read-only fallback. If restore
succeeds, the hook returns a nonblocking notice with the resume cause and the
read-only state. If restore also fails, it returns both causes. Task, preview,
and Quick Chat consumers render this state instead of ignoring it.
The recovery result uses separate error and notice fields. Manual resume and
read-only restore retain separate causes, so a second failure does not hide the
first cause or its branch details. A later successful resume clears both. A
read-only restore clears the blocking error and keeps the informational notice
until the session state changes or the user dismisses it. The automatic
resumption hook also clears stale feedback when the shared live session state
transitions to `STARTING`, `RUNNING`, or `WAITING_FOR_INPUT` after an external
manual recovery.
## Frontend status rendering
`StatusMessage` maps `metadata.kind === "branch_recreated"` to localized
warning copy. The visible text names the original branch, new branch, and base
branch. It states both outcomes:
- The provider conversation history continues in the same task session.
- Code changes and commits that existed only on the lost branch were not
recovered.
The status entry uses the same warning layout as model-selection warnings. It
does not depend on a live WebSocket event, so reload and replay show the same
message.
## Responsive and accessible behavior
Recovery remains inside the existing chat and stopped-session surfaces. This
change adds no navigation, modal, drawer, or mobile-only workflow.
On wide screens, related actions can share a row and wrap. On narrow screens,
actions use the existing stacked layout. Each action keeps a minimum 44-pixel
touch target. The alert stays in the chat scroll owner and does not create
horizontal page overflow. Error text and button labels remain available to
assistive technology and keyboard navigation.
## Internationalization
All new labels, error titles, read-only notices, confirmations, and branch
warning text use the `task` or `chat` namespace. Keys exist in `en`, `pseudo`,
`pt-pt`, `zh-cn`, `zh-hk`, and `zh-tw`. Branch names are interpolation values,
not translated strings. User-facing copy does not use a Unicode em dash.
## Testing strategy
Backend tests start with the current failure:
- Normal resume returns an error that matches `ErrBranchUnrecoverable` and does
not mutate the branch.
- Explicit replacement keeps the session and resume token, creates a unique
branch from the configured base, and leaves valid repositories unchanged.
- `RecoverSession` validates `resume_new_branch` and passes replacement
permission only for that action.
- Successful replacement persists complete warning metadata once. Replay and
retry do not duplicate it, a failed write releases the claim, and a stale
claim left by a crash can be reclaimed when no warning exists.
- Attach-only reuse probes the authoritative remote before classifying missing
local and tracking refs as branch loss; transient probe failures do not
authorize replacement.
- Replacement persistence failure removes the newly created checkout and branch
while retaining the old task-environment repository record.
- Warning persistence is attempted after every terminal resume path that can
follow materialization, including provider startup and readiness failure.
- A warning from an earlier repository replacement survives a later
multi-repository preparation failure.
- The WebSocket handler maps the sentinel to a conflict with recovery details.
Frontend unit tests cover the typed WebSocket error, both manual recovery
surfaces, visible automatic fallback, dual failure detail, and
`branch_recreated` status rendering.
Desktop and mobile Playwright tests cover the user sequence from a failed
Resume request through explicit branch continuation and the persisted warning.
They also cover read-only fallback feedback, repeated attempts, touch target
size, keyboard reachability, and horizontal overflow.
## Related decisions
- [Keep Worktrees Owned by Task Environments](../../../decisions/2026-08-08-task-owned-worktree-lifetime.md)
- [Configurable worktree branch names](../../../decisions/0032-configurable-worktree-branch-names.md)
- [Require Explicit User Action Before Continuing a Session on a Replacement Branch](../../../decisions/2026-08-31-explicit-new-branch-session-recovery.md)