fix: make agent turn cancellation responsive (#2228)

This commit is contained in:
Carlos Florêncio
2026-08-04 08:09:07 +01:00
committed by GitHub
parent 1d5c3e3f5f
commit 2ee2fa8c66
95 changed files with 4269 additions and 568 deletions
+18
View File
@@ -199,6 +199,24 @@ func fixedDelay(ms int) {
time.Sleep(time.Duration(ms) * time.Millisecond)
}
// waitForDelay is the cancellation-aware counterpart used by inline E2E
// scripts. Real ACP prompts stop producing work when the request context is
// cancelled; honoring that context keeps the mock fixture suitable for
// testing acknowledged cancellation instead of forcing every test to wait
// for an artificial sleep to expire.
func waitForDelay(ctx context.Context, ms int) {
if ctx == nil {
fixedDelay(ms)
return
}
timer := time.NewTimer(time.Duration(ms) * time.Millisecond)
defer timer.Stop()
select {
case <-timer.C:
case <-ctx.Done():
}
}
// stripKandevSystem removes all <kandev-system>...</kandev-system> blocks from the
// prompt. Tags can be prepended (backend system context injection) or appended
// (frontend plan/document context), so we strip all occurrences.
+34 -5
View File
@@ -31,9 +31,10 @@ var mcpServers map[string]mcpServerDef
// mockAgent implements the acp.Agent interface for the mock agent.
type mockAgent struct {
conn *acp.AgentSideConnection
conn sessionUpdater
model string
sessions map[acp.SessionId]bool
promptCancels map[acp.SessionId]context.CancelFunc
sessionConfig map[acp.SessionId][]acp.SessionConfigOption
commandsEmitted map[acp.SessionId]bool
nextSessionID uint64
@@ -68,6 +69,7 @@ func main() {
ag := &mockAgent{
model: model,
sessions: make(map[acp.SessionId]bool),
promptCancels: make(map[acp.SessionId]context.CancelFunc),
sessionConfig: make(map[acp.SessionId][]acp.SessionConfigOption),
commandsEmitted: make(map[acp.SessionId]bool),
}
@@ -237,21 +239,48 @@ func (a *mockAgent) LoadSession(_ context.Context, req acp.LoadSessionRequest) (
// Prompt processes a user message and streams responses via SessionUpdate.
func (a *mockAgent) Prompt(ctx context.Context, req acp.PromptRequest) (acp.PromptResponse, error) {
a.emitAvailableCommandsOnce(ctx, req.SessionId)
promptCtx, cancelPrompt := context.WithCancel(ctx)
a.mu.Lock()
if a.promptCancels == nil {
a.promptCancels = make(map[acp.SessionId]context.CancelFunc)
}
a.promptCancels[req.SessionId] = cancelPrompt
a.mu.Unlock()
defer func() {
cancelPrompt()
a.mu.Lock()
if current := a.promptCancels[req.SessionId]; current != nil {
delete(a.promptCancels, req.SessionId)
}
a.mu.Unlock()
}()
a.emitAvailableCommandsOnce(promptCtx, req.SessionId)
prompt := extractPromptText(req.Prompt)
// The /overloaded scenario must surface a real prompt-time ACP *error*
// (a JSON-RPC error response), which handlePrompt's emitter cannot do —
// so intercept it here and return the error from Prompt directly.
if resp, err, handled := a.handleOverloaded(ctx, req.SessionId, prompt); handled {
if resp, err, handled := a.handleOverloaded(promptCtx, req.SessionId, prompt); handled {
return resp, err
}
e := &emitter{ctx: ctx, conn: a.conn, sid: req.SessionId}
e := &emitter{ctx: promptCtx, conn: a.conn, sid: req.SessionId}
handlePrompt(e, prompt, a.model)
if promptCtx.Err() != nil {
return acp.PromptResponse{StopReason: acp.StopReasonCancelled}, nil
}
return acp.PromptResponse{StopReason: acp.StopReasonEndTurn}, nil
}
// Cancel handles session cancellation.
func (a *mockAgent) Cancel(_ context.Context, _ acp.CancelNotification) error { return nil }
func (a *mockAgent) Cancel(_ context.Context, req acp.CancelNotification) error {
a.mu.Lock()
cancelPrompt := a.promptCancels[req.SessionId]
a.mu.Unlock()
if cancelPrompt != nil {
cancelPrompt()
}
return nil
}
// Authenticate handles auth requests (no-op for mock).
func (a *mockAgent) Authenticate(_ context.Context, _ acp.AuthenticateRequest) (acp.AuthenticateResponse, error) {
@@ -1,12 +1,79 @@
package main
import (
"context"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
acp "github.com/coder/acp-go-sdk"
)
type promptCancelUpdater struct {
started chan struct{}
once sync.Once
}
func (u *promptCancelUpdater) SessionUpdate(context.Context, acp.SessionNotification) error {
u.once.Do(func() { close(u.started) })
return nil
}
func (u *promptCancelUpdater) RequestPermission(context.Context, acp.RequestPermissionRequest) (acp.RequestPermissionResponse, error) {
return acp.RequestPermissionResponse{}, nil
}
func TestMockAgentCancelStopsPrompt(t *testing.T) {
const sessionID = acp.SessionId("cancel-session")
updater := &promptCancelUpdater{started: make(chan struct{})}
agent := &mockAgent{
model: "mock-fast",
conn: updater,
sessions: map[acp.SessionId]bool{sessionID: true},
promptCancels: make(map[acp.SessionId]context.CancelFunc),
commandsEmitted: make(map[acp.SessionId]bool),
}
result := make(chan struct {
response acp.PromptResponse
err error
}, 1)
go func() {
response, err := agent.Prompt(context.Background(), acp.PromptRequest{
SessionId: sessionID,
Prompt: []acp.ContentBlock{acp.TextBlock("e2e:message(\"started\")\ne2e:delay(5000)")},
})
result <- struct {
response acp.PromptResponse
err error
}{response: response, err: err}
}()
select {
case <-updater.started:
case <-time.After(time.Second):
t.Fatal("timed out waiting for the prompt to start")
}
if err := agent.Cancel(context.Background(), acp.CancelNotification{SessionId: sessionID}); err != nil {
t.Fatalf("cancel prompt: %v", err)
}
select {
case outcome := <-result:
if outcome.err != nil {
t.Fatalf("prompt returned error: %v", outcome.err)
}
if outcome.response.StopReason != acp.StopReasonCancelled {
t.Fatalf("stop reason = %q, want cancelled", outcome.response.StopReason)
}
case <-time.After(time.Second):
t.Fatal("prompt did not stop after cancellation")
}
}
func TestParseModelFromArgs(t *testing.T) {
tests := []struct {
name string
+4 -1
View File
@@ -21,6 +21,9 @@ func isScriptMode(cmd string) bool {
func executeScript(e *emitter, fullPrompt, cmd string) {
lines := strings.Split(cmd, "\n")
for _, line := range lines {
if e.ctx != nil && e.ctx.Err() != nil {
return
}
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
@@ -47,7 +50,7 @@ func executeCommand(e *emitter, fullPrompt, line string) {
case strings.HasPrefix(line, "e2e:delay("):
ms := extractIntArg(line, "e2e:delay(")
fixedDelay(ms)
waitForDelay(e.ctx, ms)
case strings.HasPrefix(line, "e2e:mcp:"):
executeMCPCommand(e, fullPrompt, line)
@@ -416,6 +416,20 @@ func TestExecuteScriptSkipsEmptyAndComments(t *testing.T) {
}
}
func TestExecuteScriptStopsWhenPromptContextIsCancelled(t *testing.T) {
e, mock := newTestEmitter()
resetState()
ctx, cancel := context.WithCancel(context.Background())
cancel()
e.ctx = ctx
executeScript(e, "", "e2e:message(\"before cancellation\")")
if updates := mock.getUpdates(); len(updates) != 0 {
t.Fatalf("expected no updates after prompt cancellation, got %d", len(updates))
}
}
// TestExecuteScriptToolUse verifies e2e:tool_use emits a tool_call update.
func TestExecuteScriptToolUse(t *testing.T) {
e, mock := newTestEmitter()
@@ -3,6 +3,7 @@ package client
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
@@ -168,6 +169,9 @@ func TestSendStreamRequest_NotConnected(t *testing.T) {
if err == nil {
t.Fatal("expected error when stream not connected")
}
if !errors.Is(err, ErrAgentStreamNotConnected) {
t.Fatalf("expected ErrAgentStreamNotConnected, got: %v", err)
}
if !strings.Contains(err.Error(), "agent stream not connected") {
t.Fatalf("expected 'agent stream not connected' error, got: %v", err)
}
@@ -3,6 +3,7 @@ package client
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
@@ -13,6 +14,11 @@ import (
"go.opentelemetry.io/otel/propagation"
)
// ErrAgentStreamNotConnected identifies requests that cannot be delivered
// because the agent updates stream has already disconnected. Callers use this
// to distinguish an already-stopped agent from a live transport failure.
var ErrAgentStreamNotConnected = errors.New("agent stream not connected")
// sendStreamRequest sends a request over the agent WebSocket stream and waits for a response.
// It creates a ws.Message with a UUID, registers a pending response channel,
// writes the message to the stream, and blocks until a response arrives or context is cancelled.
@@ -22,7 +28,7 @@ func (c *Client) sendStreamRequest(ctx context.Context, action string, payload i
c.mu.RUnlock()
if conn == nil {
return nil, fmt.Errorf("agent stream not connected")
return nil, ErrAgentStreamNotConnected
}
reqID := uuid.New().String()
@@ -72,7 +78,7 @@ func (c *Client) sendStreamRequest(ctx context.Context, action string, payload i
select {
case resp := <-respCh:
if resp == nil {
disconnErr := fmt.Errorf("agent stream disconnected while waiting for response")
disconnErr := fmt.Errorf("%w while waiting for response", ErrAgentStreamNotConnected)
tracing.TraceWSResponse(span, "", disconnErr)
return nil, disconnErr
}
@@ -665,7 +665,7 @@ func (r *DockerExecutor) StopInstance(ctx context.Context, instance *ExecutorIns
return nil
}
dockerClient, _, err := r.ensureClient()
dockerClient, containerMgr, err := r.ensureClient()
if err != nil {
return fmt.Errorf("docker unavailable: %w", err)
}
@@ -674,12 +674,29 @@ func (r *DockerExecutor) StopInstance(ctx context.Context, instance *ExecutorIns
defer cancel()
if force {
err = dockerClient.KillContainer(cleanupCtx, instance.ContainerID, "SIGKILL")
} else {
err = dockerClient.StopContainer(cleanupCtx, instance.ContainerID, dockerStopContainerTimeout)
if killErr := dockerClient.KillContainer(cleanupCtx, instance.ContainerID, "SIGKILL"); killErr != nil {
r.logger.Warn("failed to kill docker container before forced removal",
zap.String("container_id", instance.ContainerID),
zap.Error(killErr))
}
if removeErr := dockerClient.RemoveContainer(cleanupCtx, instance.ContainerID, true); removeErr != nil {
return fmt.Errorf("failed to remove container after kill: %w", removeErr)
}
return nil
}
if err != nil {
if shouldRunExecutorCleanup(instance.StopReason) {
if err := containerMgr.StopContainer(cleanupCtx, instance.ContainerID, dockerStopContainerTimeout); err != nil {
return fmt.Errorf("failed to stop and remove container: %w", err)
}
return nil
}
// Stale execution cleanup deliberately stops but preserves the container.
// A page refresh may still recover the durable task environment by starting
// that same container; only destructive task/session lifecycle reasons own
// removal. Failed-launch rollback uses the force branch above.
if err := dockerClient.StopContainer(cleanupCtx, instance.ContainerID, dockerStopContainerTimeout); err != nil {
return fmt.Errorf("failed to stop container: %w", err)
}
@@ -27,6 +27,17 @@ func newTestDockerLogger() *logger.Logger {
return log
}
func requireDockerRequest(t *testing.T, requests []string, method, pathSuffix string) {
t.Helper()
for _, request := range requests {
fields := strings.Fields(request)
if len(fields) == 2 && fields[0] == method && strings.HasSuffix(fields[1], pathSuffix) {
return
}
}
t.Fatalf("missing %s *%s request in %v", method, pathSuffix, requests)
}
// failingClientFactory returns a factory that always fails.
func failingClientFactory(errMsg string) func(config.DockerConfig, *logger.Logger) (*docker.Client, error) {
return func(_ config.DockerConfig, _ *logger.Logger) (*docker.Client, error) {
@@ -152,26 +163,41 @@ func TestDockerStopInstanceStopsContainerWhenAgentStopFailed(t *testing.T) {
}
}
func TestDockerStopInstanceStopsContainerOnStaleCleanup(t *testing.T) {
log := newTestDockerLogger()
exec := NewDockerExecutor(config.DockerConfig{}, "", log)
exec.newClientFunc = failingClientFactory("docker required for stale cleanup")
func TestDockerStopInstanceStopsButPreservesContainerOnStaleCleanup(t *testing.T) {
requests := make(chan string, 2)
dockerDaemon := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodHead && r.URL.Path == "/_ping" {
w.WriteHeader(http.StatusOK)
return
}
requests <- r.Method + " " + r.URL.Path
w.WriteHeader(http.StatusNoContent)
}))
t.Cleanup(dockerDaemon.Close)
err := exec.StopInstance(context.Background(), &ExecutorInstance{
InstanceID: "inst-1",
ContainerID: "container-1",
dockerExec := NewDockerExecutor(config.DockerConfig{
Host: "tcp://" + strings.TrimPrefix(dockerDaemon.URL, "http://"),
}, "", newTestDockerLogger())
t.Cleanup(func() { require.NoError(t, dockerExec.Close()) })
require.NoError(t, dockerExec.StopInstance(context.Background(), &ExecutorInstance{
InstanceID: "stale-instance",
ContainerID: "stale-container",
StopReason: stopReasonStaleExecutionCleanup,
}, false)
if err == nil {
t.Fatal("StopInstance should attempt Docker cleanup for stale executions")
}, false))
got := make([]string, 0, len(requests))
for len(requests) > 0 {
got = append(got, <-requests)
}
if !strings.Contains(err.Error(), "docker required for stale cleanup") {
t.Fatalf("StopInstance error = %v", err)
requireDockerRequest(t, got, http.MethodPost, "/containers/stale-container/stop")
for _, request := range got {
require.NotEqual(t, http.MethodDelete, strings.Fields(request)[0], request)
}
}
func TestRollbackLaunchExecutionForceKillsUnregisteredDockerContainer(t *testing.T) {
requests := make(chan string, 1)
func TestRollbackLaunchExecutionForceKillsAndRemovesUnregisteredDockerContainer(t *testing.T) {
requests := make(chan string, 2)
dockerDaemon := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodHead && r.URL.Path == "/_ping" {
w.WriteHeader(http.StatusOK)
@@ -193,13 +219,37 @@ func TestRollbackLaunchExecutionForceKillsUnregisteredDockerContainer(t *testing
ContainerID: "failed-container",
}, &AgentExecution{ID: "failed-execution", SessionID: "failed-session"}, "command construction failed")
select {
case got := <-requests:
require.Equal(t, http.MethodPost, strings.Fields(got)[0])
require.True(t, strings.HasSuffix(got, "/containers/failed-container/kill"), got)
default:
t.Fatal("rollback must force Docker cleanup for an unregistered failed instance")
}
got := []string{<-requests, <-requests}
requireDockerRequest(t, got, http.MethodPost, "/containers/failed-container/kill")
requireDockerRequest(t, got, http.MethodDelete, "/containers/failed-container")
}
func TestDockerStopInstanceStopsAndRemovesContainerOnTaskArchive(t *testing.T) {
requests := make(chan string, 2)
dockerDaemon := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodHead && r.URL.Path == "/_ping" {
w.WriteHeader(http.StatusOK)
return
}
requests <- r.Method + " " + r.URL.Path
w.WriteHeader(http.StatusNoContent)
}))
t.Cleanup(dockerDaemon.Close)
dockerExec := NewDockerExecutor(config.DockerConfig{
Host: "tcp://" + strings.TrimPrefix(dockerDaemon.URL, "http://"),
}, "", newTestDockerLogger())
t.Cleanup(func() { require.NoError(t, dockerExec.Close()) })
require.NoError(t, dockerExec.StopInstance(context.Background(), &ExecutorInstance{
InstanceID: "archive-instance",
ContainerID: "archive-container",
StopReason: StopReasonTaskArchived,
}, false))
got := []string{<-requests, <-requests}
requireDockerRequest(t, got, http.MethodPost, "/containers/archive-container/stop")
requireDockerRequest(t, got, http.MethodDelete, "/containers/archive-container")
}
func TestDockerCleanupContextIgnoresCanceledParentAfterAgentStopFailed(t *testing.T) {
@@ -8,17 +8,20 @@ import (
"github.com/kandev/kandev/internal/task/models"
)
// ExecutorProfileReader loads the executor profile selected for a session.
// Implemented by the task repository; wired via SetExecutorProfileReader.
// ExecutorProfileReader loads session state, task-cleanup admission, and the
// executor profile selected for a session. Production launch safety requires
// the task repository implementation wired via SetExecutorProfileReader.
type ExecutorProfileReader interface {
GetTaskSession(ctx context.Context, id string) (*models.TaskSession, error)
HasActiveTaskResourceCleanupJob(ctx context.Context, taskID string) (bool, error)
GetTaskEnvironment(ctx context.Context, id string) (*models.TaskEnvironment, error)
GetExecutorProfile(ctx context.Context, id string) (*models.ExecutorProfile, error)
}
// SetExecutorProfileReader wires the reader used to expose executor-profile env
// vars to user shell terminals. Nil → terminals fall back to inheriting only the
// backend process environment.
// SetExecutorProfileReader wires launch admission and the reader used to expose
// executor-profile env vars to user shell terminals. Production must provide a
// reader; nil is supported by isolated lifecycle tests, and terminals then fall
// back to inheriting only the backend process environment.
func (m *Manager) SetExecutorProfileReader(reader ExecutorProfileReader) {
m.executorProfileReader = reader
}
@@ -24,6 +24,10 @@ func (f *fakeExecutorProfileReader) GetTaskSession(_ context.Context, _ string)
return f.session, f.sessionErr
}
func (*fakeExecutorProfileReader) HasActiveTaskResourceCleanupJob(context.Context, string) (bool, error) {
return false, nil
}
func (f *fakeExecutorProfileReader) GetTaskEnvironment(_ context.Context, _ string) (*models.TaskEnvironment, error) {
return f.env, f.envErr
}
@@ -2,6 +2,8 @@ package lifecycle
import (
"context"
"errors"
"fmt"
"strings"
"testing"
@@ -217,6 +219,72 @@ func TestStartRemoteAgentctlRejectsInvalidEnvBeforeSSHLaunch(t *testing.T) {
}
}
func TestRetryRemoteAgentctlPortRetriesBindCollisions(t *testing.T) {
ports := []int{41001, 41002, 41003}
nextPort := 0
attempts := 0
port, pid, err := retryRemoteAgentctlPort(
func() int {
port := ports[nextPort]
nextPort++
return port
},
func(port int) (int, error) {
attempts++
if attempts < 3 {
return 0, fmt.Errorf("%w: %d", errSSHAgentctlPortInUse, port)
}
return 1234, nil
},
)
if err != nil {
t.Fatalf("retryRemoteAgentctlPort: %v", err)
}
if port != 41003 || pid != 1234 || attempts != 3 {
t.Fatalf("result = port %d pid %d attempts %d, want 41003/1234/3", port, pid, attempts)
}
}
func TestRetryRemoteAgentctlPortDoesNotRetryOtherFailures(t *testing.T) {
attempts := 0
wantErr := errors.New("remote launch failed")
_, _, err := retryRemoteAgentctlPort(
func() int { return 41001 },
func(int) (int, error) {
attempts++
return 0, wantErr
},
)
if !errors.Is(err, wantErr) {
t.Fatalf("retryRemoteAgentctlPort error = %v, want %v", err, wantErr)
}
if attempts != 1 {
t.Fatalf("attempts = %d, want 1", attempts)
}
}
func TestRemoteAgentctlStopCommandWaitsAndEscalatesBeforeCleanup(t *testing.T) {
command := remoteAgentctlStopCommand("/tmp/session with space", 1234)
wantOrder := []string{
"kill 1234 2>/dev/null || true",
"while kill -0 1234",
"kill -9 1234",
"rm -rf '/tmp/session with space'",
}
previous := -1
for _, fragment := range wantOrder {
index := strings.Index(command, fragment)
if index <= previous {
t.Fatalf("command fragment %q is missing or out of order:\n%s", fragment, command)
}
previous = index
}
}
func TestSSHAgentctlLaunchEnvForcesLoopbackAndOmitsBearerToken(t *testing.T) {
env := sshAgentctlLaunchEnv(map[string]string{
"AGENTCTL_AUTH_TOKEN": "profile-token",
@@ -456,9 +456,8 @@ func ensureRemoteSessionDir(ctx context.Context, client *ssh.Client, taskDir, se
// <sessionDir>/agentctl.log — agentctl's own stdout+stderr
//
// agentctl honors AGENTCTL_PORT from its environment (default 39429). We pick
// a per-session port from a wide ephemeral range; collisions on the remote are
// vanishingly unlikely and would surface as a clear bind failure that the
// caller can retry.
// a per-session port from a wide ephemeral range and retry bind collisions on
// the remote before failing the launch.
func startRemoteAgentctl(
ctx context.Context,
client *ssh.Client,
@@ -466,11 +465,51 @@ func startRemoteAgentctl(
env map[string]string,
log *logger.Logger,
) (port int, pid int, err error) {
port = pickRemoteAgentctlPort()
envScript, err := buildSSHEnvInitScript(env)
if err != nil {
return 0, 0, fmt.Errorf("ssh: launch agentctl: %w", err)
}
return retryRemoteAgentctlPort(pickRemoteAgentctlPort, func(port int) (int, error) {
return startRemoteAgentctlOnPort(
ctx, client, shell, agentctlBin, workspacePath, sessionDir, envScript, port, log,
)
})
}
var errSSHAgentctlPortInUse = errors.New("ssh: remote agentctl port is already in use")
const sshAgentctlPortAttempts = 5
func retryRemoteAgentctlPort(
pickPort func() int,
start func(port int) (pid int, err error),
) (port int, pid int, err error) {
var lastErr error
for range sshAgentctlPortAttempts {
port = pickPort()
pid, err = start(port)
if err == nil {
return port, pid, nil
}
lastErr = err
if !errors.Is(err, errSSHAgentctlPortInUse) {
return 0, 0, err
}
}
return 0, 0, fmt.Errorf(
"ssh: agentctl exhausted %d remote port attempts: %w",
sshAgentctlPortAttempts,
lastErr,
)
}
func startRemoteAgentctlOnPort(
ctx context.Context,
client *ssh.Client,
shell, agentctlBin, workspacePath, sessionDir, envScript string,
port int,
log *logger.Logger,
) (pid int, err error) {
// Wrap the agentctl exec in a login shell so the spawned process
// inherits the user's $PATH (nvm/asdf/brew etc.). Without this, even
@@ -502,11 +541,11 @@ echo "$AGENTCTL_PID"
)
out, stderr, err := runSSHCommandStdin(ctx, client, WrapLoginShell(shell, innerScript), strings.NewReader(envScript))
if err != nil {
return 0, 0, fmt.Errorf("ssh: launch agentctl: %w (stderr: %s)", err, strings.TrimSpace(stderr))
return 0, fmt.Errorf("ssh: launch agentctl: %w (stderr: %s)", err, strings.TrimSpace(stderr))
}
pid, err = strconv.Atoi(strings.TrimSpace(out))
if err != nil {
return 0, 0, fmt.Errorf("ssh: agentctl wrapper returned non-numeric pid %q", out)
return 0, fmt.Errorf("ssh: agentctl wrapper returned non-numeric pid %q", out)
}
// Poll the on-disk log for the "bound successfully" line; until then the
@@ -520,17 +559,17 @@ echo "$AGENTCTL_PID"
zap.Int("port", port),
zap.Int("pid", pid),
zap.String("session_dir", sessionDir))
return port, pid, nil
return pid, nil
}
if strings.Contains(logOut, "HTTP server failed to bind") {
return 0, 0, fmt.Errorf(
"ssh: agentctl failed to bind port %d on remote; log:\n%s", port,
return 0, fmt.Errorf(
"%w (port %d); log:\n%s", errSSHAgentctlPortInUse, port,
lastLines(logOut, sshAgentctlLogTailLines))
}
// Also catch "exited without binding" via pid check — if the wrapper
// exited before logging, kill -0 fails and we fail fast.
if !isRemoteAgentctlAlive(ctx, client, pid) {
return 0, 0, fmt.Errorf(
return 0, fmt.Errorf(
"ssh: agentctl exited before becoming ready; log tail:\n%s",
lastLines(logOut, sshAgentctlLogTailLines))
}
@@ -538,7 +577,7 @@ echo "$AGENTCTL_PID"
}
tail, _, _ := runSSHCommand(ctx, client,
"tail -n 50 "+shellQuote(sessionDir+"/agentctl.log")+" 2>/dev/null")
return 0, 0, fmt.Errorf("ssh: agentctl did not become ready within %v; log tail:\n%s",
return 0, fmt.Errorf("ssh: agentctl did not become ready within %v; log tail:\n%s",
sshAgentctlReadyTimeout, tail)
}
@@ -751,17 +790,30 @@ func pickRemoteAgentctlPort() int {
return 40000 + mrand.IntN(20000)
}
// stopRemoteAgentctl best-effort kills a remote agentctl by PID and removes
// the session runtime dir.
const sshAgentctlStopPollAttempts = 50
// stopRemoteAgentctl stops a remote agentctl by PID, waits for graceful exit,
// escalates if necessary, and only then removes the session runtime dir.
func stopRemoteAgentctl(ctx context.Context, client *ssh.Client, sessionDir string, pid int) error {
if pid > 0 {
if _, _, err := runSSHCommand(ctx, client, fmt.Sprintf("kill %d 2>/dev/null || true", pid)); err != nil {
return err
}
_, _, err := runSSHCommand(ctx, client, remoteAgentctlStopCommand(sessionDir, pid))
return err
}
func remoteAgentctlStopCommand(sessionDir string, pid int) string {
removeSessionDir := "rm -rf " + shellQuote(sessionDir)
if pid <= 0 {
return removeSessionDir
}
// Leave the task dir intact (mirrors spec); only wipe session runtime.
_, _, _ = runSSHCommand(ctx, client, "rm -rf "+shellQuote(sessionDir))
return nil
return fmt.Sprintf(`kill %[1]d 2>/dev/null || true
attempt=0
while kill -0 %[1]d 2>/dev/null && [ "$attempt" -lt %[2]d ]; do
sleep 0.1
attempt=$((attempt + 1))
done
if kill -0 %[1]d 2>/dev/null; then
kill -9 %[1]d 2>/dev/null || true
fi
%[3]s`, pid, sshAgentctlStopPollAttempts, removeSessionDir)
}
// isRemoteAgentctlAlive returns true when a kill -0 on the pid succeeds.
@@ -604,6 +604,11 @@ func (m *Manager) createExecution(ctx context.Context, taskID string, info *Work
execution.agentctl.SetTraceContext(execution.SessionTraceContext())
}
if err := m.ensureLaunchSessionStillActive(ctx, info.SessionID); err != nil {
m.rollbackLaunchExecution(ctx, rt, runtimeInstance, execution, "session ended during runtime creation")
return nil, err
}
if addErr := m.executionStore.Add(execution); addErr != nil {
// Lost a race: another path created an execution for this session
// between our check and our Add. Roll back the runtime instance we
@@ -617,14 +622,22 @@ func (m *Manager) createExecution(ctx context.Context, taskID string, info *Work
}
return nil, fmt.Errorf("failed to register execution: %w", addErr)
}
// Persist before the final session read so concurrent deletion cleanup can
// inventory this execution even if it started between Add and validation.
if err := m.persistExecutorRunningResult(ctx, execution); err != nil {
m.rollbackRegisteredLaunchAfterPersistFailure(rt, runtimeInstance, execution)
return nil, fmt.Errorf("persist execution registration: %w", err)
}
if err := m.ensureLaunchSessionStillActive(ctx, info.SessionID); err != nil {
if errors.Is(err, errTaskCleanupActive) {
m.rollbackRegisteredLaunchForTaskCleanup(rt, runtimeInstance, execution)
} else {
m.rollbackRegisteredLaunch(rt, runtimeInstance, execution, "session ended during execution registration")
}
return nil, err
}
m.setRuntimeInterest(execution.SessionID, true)
// Persist executors_running row in lockstep with the in-memory Add so the
// DB never holds an execution_id the store doesn't know about. This is the
// structural fix for the divergence bug — pre-refactor, the orchestrator
// wrote the row later via a full-row UPDATE that could race with the store.
m.persistExecutorRunning(ctx, execution)
// Persist agentctl auth token only after the execution is tracked, so a
// race-lost rollback never leaves an orphaned secret in the store.
m.persistRuntimeSecrets(ctx, runtimeInstance, execution)
@@ -25,6 +25,7 @@ import (
agentctl "github.com/kandev/kandev/internal/agent/runtime/agentctl"
settingsmodels "github.com/kandev/kandev/internal/agent/settings/models"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/internal/task/models"
v1 "github.com/kandev/kandev/pkg/api/v1"
)
@@ -282,6 +283,38 @@ func TestCoalescedExecutionCreationHasManagerDeadline(t *testing.T) {
})
}
func TestCreateExecutionRollsBackWhenRegistrationCannotPersist(t *testing.T) {
const sessionID = "session-create-persist-failure"
mgr, backend := newEnvironmentExecutionTestManager(t, &mockWorkspaceInfoProvider{
infos: map[string]*WorkspaceInfo{
sessionID: {
TaskID: "task-create-persist-failure", SessionID: sessionID,
TaskEnvironmentID: "env-create-persist-failure", WorkspacePath: "/workspace/task",
AgentID: "auggie",
},
},
})
mgr.SetExecutorProfileReader(&fakeExecutorProfileReader{session: &models.TaskSession{
ID: sessionID, TaskID: "task-create-persist-failure", State: models.TaskSessionStateStarting,
}})
writer := &launchRegistrationWriter{
upserted: make(chan struct{}),
upsertErr: errors.New("database is locked"),
}
mgr.SetExecutorRunningWriter(writer)
_, err := mgr.GetOrEnsureExecution(context.Background(), sessionID)
if err == nil || !strings.Contains(err.Error(), "persist execution registration") {
t.Fatalf("GetOrEnsureExecution error = %v, want persistence failure", err)
}
if got := backend.stopCount.Load(); got != 1 {
t.Fatalf("StopInstance calls = %d, want 1", got)
}
if _, exists := mgr.executionStore.GetBySessionID(sessionID); exists {
t.Fatal("workspace execution survived failed durable registration")
}
}
func TestResolveTaskEnvironmentID(t *testing.T) {
t.Run("returns TaskEnvironmentID when execution carries it", func(t *testing.T) {
store := NewExecutionStore()
@@ -144,7 +144,10 @@ func (m *Manager) CancelAgent(ctx context.Context, executionID string) error {
zap.String("session_id", execution.SessionID))
cancelErr := execution.agentctl.Cancel(ctx)
if cancelErr != nil && !errors.Is(cancelErr, agentctlclient.ErrTurnCancelNotAcknowledged) {
streamDisconnected := errors.Is(cancelErr, agentctlclient.ErrAgentStreamNotConnected)
if cancelErr != nil &&
!errors.Is(cancelErr, agentctlclient.ErrTurnCancelNotAcknowledged) &&
!streamDisconnected {
m.logger.Error("failed to cancel agent turn",
zap.String("execution_id", executionID),
zap.Error(cancelErr))
@@ -161,9 +164,24 @@ func (m *Manager) CancelAgent(ctx context.Context, executionID string) error {
execution.promptFinishedMu.Unlock()
if ch == nil {
if streamDisconnected {
m.logger.Info("agent stream already disconnected; cancel is complete",
zap.String("execution_id", executionID))
}
return nil
}
// Teardown may close the stream immediately before an explicit cancel (for
// example, archive followed by cancel). Treat it like an unacknowledged
// cancel: locally release any in-flight prompt and let orchestration perform
// its idempotent DB reconciliation.
if streamDisconnected {
m.logger.Warn("agent stream disconnected before cancel; escalating locally",
zap.String("execution_id", executionID),
zap.Error(cancelErr))
return m.escalateStuckCancel(ctx, execution, ch)
}
// The agent did not end the in-flight session/prompt RPC after cancel (e.g. it
// does not implement session/cancel). Escalate immediately so SendPrompt and the
// prompt gate are reconciled instead of waiting the full cancelWaitTimeout.
@@ -1191,6 +1209,18 @@ func (m *Manager) OwnsPromptGeneration(sessionID, executionID string, generation
return m.executionStore.OwnsPromptGeneration(sessionID, executionID, generation)
}
// GetPromptGenerationForSession returns the generation currently owned by the
// active prompt for sessionID. Orchestrator cancellation uses this together
// with the execution and turn IDs to reject stale terminal events while the
// lifecycle manager waits for an acknowledged cancel to settle.
func (m *Manager) GetPromptGenerationForSession(_ context.Context, sessionID string) (uint64, error) {
execution, exists := m.executionStore.GetBySessionID(sessionID)
if !exists {
return 0, fmt.Errorf("%w: %s", ErrNoExecutionForSession, sessionID)
}
return execution.promptGenerationSnapshot(), nil
}
// MarkReady marks an execution as ready for follow-up prompts AFTER A TURN.
// Use MarkBootReady instead when the agent has just initialized and hasn't yet
// processed a turn — orchestrator subscribers rely on the distinction.
@@ -128,6 +128,50 @@ func TestManager_CancelAgent_EscalatesWhenAgentHangs(t *testing.T) {
require.True(t, sawReady, "expected AgentReady event after cancel escalation")
}
func TestManager_CancelAgent_DisconnectedStreamWithoutPromptIsAlreadyCancelled(t *testing.T) {
mgr := newTestManager(t)
exec := &AgentExecution{
ID: "exec-disconnected-idle",
TaskID: "task-1",
SessionID: "session-1",
Status: v1.AgentStatusReady,
agentctl: agentctlClient.NewClient("127.0.0.1", 1, newTestLogger()),
}
require.NoError(t, mgr.executionStore.Add(exec))
require.NoError(t, mgr.CancelAgent(context.Background(), exec.ID))
}
func TestManager_CancelAgent_DisconnectedStreamReleasesPrompt(t *testing.T) {
previousEscalationTimeout := cancelEscalationTimeout
cancelEscalationTimeout = 100 * time.Millisecond
t.Cleanup(func() { cancelEscalationTimeout = previousEscalationTimeout })
mgr := newTestManager(t)
promptFinished := make(chan struct{})
exec := &AgentExecution{
ID: "exec-disconnected-running",
TaskID: "task-1",
SessionID: "session-1",
Status: v1.AgentStatusRunning,
agentctl: agentctlClient.NewClient("127.0.0.1", 1, newTestLogger()),
promptDoneCh: make(chan PromptCompletionSignal, 1),
promptFinished: promptFinished,
}
require.NoError(t, mgr.executionStore.Add(exec))
go func() {
<-exec.promptDoneCh
close(promptFinished)
}()
err := mgr.CancelAgent(context.Background(), exec.ID)
require.ErrorIs(t, err, ErrCancelEscalated)
updated, found := mgr.executionStore.Get(exec.ID)
require.True(t, found)
require.Equal(t, v1.AgentStatusReady, updated.Status)
}
// TestManager_CancelAgent_EscalationCleanupSurvivesCtxCancel covers the case where
// the caller's context is cancelled during the post-escalation wait. Once the
// synthetic signal has been queued on promptDoneCh, the cleanup (MarkReady + drain)
@@ -28,6 +28,16 @@ import (
const legacyExecutorTypeLocalPC = "local_pc"
const registeredLaunchRollbackRetries = 3
var registeredLaunchRollbackRetryDelays = [...]time.Duration{
100 * time.Millisecond,
500 * time.Millisecond,
2 * time.Second,
}
var errTaskCleanupActive = errors.New("task cleanup is active")
// resolveAgentProfile resolves the agent profile and returns the agent type name and profile info.
func (m *Manager) resolveAgentProfile(ctx context.Context, req *LaunchRequest) (string, *AgentProfileInfo, error) {
profileID := executionProfileID(req)
@@ -1236,6 +1246,10 @@ func (m *Manager) registerAndPublishExecution(
execInstance *ExecutorInstance,
sessionID string,
) error {
if err := m.ensureLaunchSessionStillActive(ctx, sessionID); err != nil {
m.rollbackLaunchExecution(ctx, rt, execInstance, execution, "session ended during runtime creation")
return err
}
if addErr := m.executionStore.Add(execution); addErr != nil {
if errors.Is(addErr, ErrExecutionAlreadyExistsForSession) {
m.rollbackRacedExecution(ctx, rt, execInstance, execution)
@@ -1243,16 +1257,26 @@ func (m *Manager) registerAndPublishExecution(
}
return fmt.Errorf("failed to register execution: %w", addErr)
}
// Make the execution visible to durable cleanup before the final session
// read. This closes the precheck -> Add -> persist gap: deletion cleanup can
// now inventory the row, while a deletion that already ran is caught below.
if err := m.persistExecutorRunningResult(ctx, execution); err != nil {
m.rollbackRegisteredLaunchAfterPersistFailure(rt, execInstance, execution)
return fmt.Errorf("persist execution registration: %w", err)
}
if err := m.ensureLaunchSessionStillActive(ctx, sessionID); err != nil {
if errors.Is(err, errTaskCleanupActive) {
m.rollbackRegisteredLaunchForTaskCleanup(rt, execInstance, execution)
} else {
m.rollbackRegisteredLaunch(rt, execInstance, execution, "session ended during execution registration")
}
return err
}
m.setRuntimeInterest(execution.SessionID, true)
m.persistRuntimeSecrets(ctx, execInstance, execution)
// Persist executors_running in lockstep with Add — see persistence.go for the
// invariant. Carries forward resume_token / metadata from a prior row so the
// lifecycle write doesn't clobber data the orchestrator's narrow CAS updates
// wrote earlier (e.g., context_window from a previous run).
m.persistExecutorRunning(ctx, execution)
go m.pollOneRemoteStatus(context.Background(), execution)
m.eventPublisher.PublishAgentEvent(ctx, events.AgentStarted, execution)
@@ -1264,6 +1288,157 @@ func (m *Manager) registerAndPublishExecution(
return nil
}
// ensureLaunchSessionStillActive closes the remote-runtime creation race: SSH,
// Docker, and other remote CreateInstance calls can outlive a concurrent task
// delete. Callers read both immediately before and after registration. The
// durable cleanup-intent check is the admission boundary between them: either
// launch persists first and cleanup's final inventory observes it, or cleanup
// persists first and launch rolls the runtime back.
func (m *Manager) ensureLaunchSessionStillActive(ctx context.Context, sessionID string) error {
if m.executorProfileReader == nil || sessionID == "" {
return nil
}
session, err := m.executorProfileReader.GetTaskSession(ctx, sessionID)
if err != nil {
return fmt.Errorf("verify session before registering execution: %w", err)
}
if session == nil {
return fmt.Errorf("verify session before registering execution: session %q not found", sessionID)
}
cleanupActive, err := m.executorProfileReader.HasActiveTaskResourceCleanupJob(ctx, session.TaskID)
if err != nil {
return fmt.Errorf("verify task cleanup before registering execution: %w", err)
}
if cleanupActive {
return fmt.Errorf("verify task cleanup before registering execution: %w for task %q", errTaskCleanupActive, session.TaskID)
}
// Re-read after the cleanup-intent lookup. A cleanup can transition to a
// terminal state between separate queries; its job then no longer appears
// active, but the session deletion/cancellation remains authoritative.
session, err = m.executorProfileReader.GetTaskSession(ctx, sessionID)
if err != nil {
return fmt.Errorf("reverify session after task cleanup admission: %w", err)
}
if session == nil {
return fmt.Errorf("reverify session after task cleanup admission: session %q not found", sessionID)
}
switch session.State {
case models.TaskSessionStateCancelled,
models.TaskSessionStateCompleted,
models.TaskSessionStateFailed:
return fmt.Errorf("verify session before registering execution: session %q is %s", sessionID, session.State)
default:
return nil
}
}
// rollbackRegisteredLaunchForTaskCleanup cannot assume the session is
// terminal: the task mutation may still fail after persisting its prepared
// cleanup intent. Preserve resumable state while removing the rejected live
// execution; committed cleanup can subsequently remove the stopped row.
func (m *Manager) rollbackRegisteredLaunchForTaskCleanup(
rt ExecutorBackend,
execInstance *ExecutorInstance,
execution *AgentExecution,
) {
m.rollbackRegisteredLaunchWithRetry(rt, execInstance, execution, true, "task cleanup won execution registration")
}
// rollbackRegisteredLaunchAfterPersistFailure preserves any prior durable row
// for the session. If the failed upsert actually committed before returning an
// ambiguous transport error, clean it up resume-safely only after confirming
// that it belongs to this exact execution.
func (m *Manager) rollbackRegisteredLaunchAfterPersistFailure(
rt ExecutorBackend,
execInstance *ExecutorInstance,
execution *AgentExecution,
) {
m.rollbackRegisteredLaunchWithRetry(rt, execInstance, execution, false, "execution registration persistence failed")
}
func (m *Manager) rollbackRegisteredLaunchWithRetry(
rt ExecutorBackend,
execInstance *ExecutorInstance,
execution *AgentExecution,
taskCleanupActive bool,
reason string,
) {
if err := m.stopRegisteredLaunchRuntime(rt, execInstance, execution); err == nil {
m.finishRegisteredLaunchRollback(execution, taskCleanupActive)
return
} else {
m.logger.Warn("registered launch rollback retained ownership after stop failure",
zap.String("execution_id", execution.ID),
zap.String("session_id", execution.SessionID),
zap.String("reason", reason),
zap.Error(err))
}
m.wg.Add(1)
go func() {
defer m.wg.Done()
for attempt := 0; attempt < registeredLaunchRollbackRetries; attempt++ {
timer := time.NewTimer(registeredLaunchRollbackRetryDelays[attempt])
select {
case <-m.stopCh:
timer.Stop()
return
case <-timer.C:
}
if _, exists := m.executionStore.Get(execution.ID); !exists {
return
}
if err := m.stopRegisteredLaunchRuntime(rt, execInstance, execution); err == nil {
m.finishRegisteredLaunchRollback(execution, taskCleanupActive)
return
} else {
m.logger.Warn("registered launch rollback retry failed",
zap.String("execution_id", execution.ID),
zap.Int("attempt", attempt+1),
zap.Error(err))
}
}
m.logger.Error("registered launch rollback exhausted retries; retaining cleanup ownership",
zap.String("execution_id", execution.ID),
zap.String("session_id", execution.SessionID),
zap.String("reason", reason))
}()
}
func (m *Manager) stopRegisteredLaunchRuntime(
rt ExecutorBackend,
execInstance *ExecutorInstance,
execution *AgentExecution,
) error {
if rt != nil && execInstance != nil {
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
err := rt.StopInstance(cleanupCtx, execInstance, true)
cancel()
if err != nil {
return err
}
}
if execution.agentctl != nil {
execution.agentctl.Close()
}
execution.EndSessionSpan()
return nil
}
func (m *Manager) finishRegisteredLaunchRollback(execution *AgentExecution, taskCleanupActive bool) {
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if taskCleanupActive {
m.deleteExecutorRunning(cleanupCtx, execution.SessionID)
} else if reader, ok := m.runningWriter.(executorRunningReader); ok {
running, err := reader.GetExecutorRunningBySessionID(cleanupCtx, execution.SessionID)
if err == nil && running != nil && running.AgentExecutionID == execution.ID {
m.deleteExecutorRunning(cleanupCtx, execution.SessionID)
}
}
m.executionStore.Remove(execution.ID)
}
func (m *Manager) rollbackLaunchExecution(_ context.Context, rt ExecutorBackend, execInstance *ExecutorInstance, execution *AgentExecution, reason string) {
m.logger.Warn("rolling back launch execution",
zap.String("execution_id", execution.ID),
@@ -1284,6 +1459,26 @@ func (m *Manager) rollbackLaunchExecution(_ context.Context, rt ExecutorBackend,
execution.EndSessionSpan()
}
// rollbackRegisteredLaunch removes both sides of an execution registration
// before stopping its runtime. This path intentionally deletes the durable row
// without the normal resume-token repair: the owning session was just proven
// terminal or absent, so leaving a repaired row would expose a phantom runtime.
func (m *Manager) rollbackRegisteredLaunch(rt ExecutorBackend, execInstance *ExecutorInstance, execution *AgentExecution, reason string) {
m.executionStore.Remove(execution.ID)
if m.runningWriter != nil && execution.SessionID != "" {
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
if err := m.runningWriter.DeleteExecutorRunningBySessionID(cleanupCtx, execution.SessionID); err != nil &&
!errors.Is(err, models.ErrExecutorRunningNotFound) {
m.logger.Warn("failed to delete executor-running row during launch rollback",
zap.String("execution_id", execution.ID),
zap.String("session_id", execution.SessionID),
zap.Error(err))
}
cancel()
}
m.rollbackLaunchExecution(context.Background(), rt, execInstance, execution, reason)
}
// SetExecutionDescription updates the task description stored in an execution's metadata.
// This is used when starting an agent on a workspace that was launched without a prompt.
func (m *Manager) SetExecutionDescription(_ context.Context, executionID string, description string) error {
@@ -1599,6 +1599,431 @@ func TestLaunch_RaceRollback(t *testing.T) {
}
}
func TestLaunch_RollsBackRuntimeWhenSessionEndsDuringCreate(t *testing.T) {
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
execRegistry := NewExecutorRegistry(log)
entered := make(chan struct{}, 1)
barrier := make(chan struct{})
backend := &createInstanceExecutor{
MockExecutor: MockExecutor{name: executor.NameStandalone},
entered: entered,
barrier: barrier,
}
execRegistry.Register(backend)
mgr := NewManager(
newTestRegistry(), &MockEventBus{}, execRegistry,
&MockCredentialsManager{}, &MockProfileResolver{}, nil,
ExecutorFallbackWarn, "", log,
)
mgr.dataDir = t.TempDir()
cleanupManagerStopCh(t, mgr)
session := &models.TaskSession{ID: "session-deleted", State: models.TaskSessionStateStarting}
mgr.SetExecutorProfileReader(&fakeExecutorProfileReader{session: session})
errCh := make(chan error, 1)
go func() {
_, err := mgr.Launch(context.Background(), &LaunchRequest{
TaskID: "task-deleted",
SessionID: session.ID,
AgentProfileID: "profile-1",
IsEphemeral: true,
})
errCh <- err
}()
select {
case <-entered:
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for CreateInstance to start")
}
session.State = models.TaskSessionStateCancelled
close(barrier)
err := <-errCh
if err == nil || !strings.Contains(err.Error(), "session-deleted") || !strings.Contains(err.Error(), "CANCELLED") {
t.Fatalf("Launch error = %v, want terminal-session validation", err)
}
if got := backend.stopCount.Load(); got != 1 {
t.Fatalf("StopInstance called %d times, want 1", got)
}
if _, exists := mgr.executionStore.GetBySessionID(session.ID); exists {
t.Fatal("terminal session runtime must not be registered")
}
}
type launchRegistrationGateReader struct {
reads atomic.Int32
cleanupReads atomic.Int32
cleanupActive atomic.Bool
finalState models.TaskSessionState
blockRead int32
blockCleanupRead int32
secondRead chan struct{}
release chan struct{}
}
type launchRegistrationWriter struct {
upserted chan struct{}
deleted atomic.Int32
repaired atomic.Int32
upsertErr error
running *models.ExecutorRunning
}
func (w *launchRegistrationWriter) GetExecutorRunningBySessionID(context.Context, string) (*models.ExecutorRunning, error) {
if w.running == nil {
return nil, models.ErrExecutorRunningNotFound
}
return w.running, nil
}
func (w *launchRegistrationWriter) UpsertExecutorRunning(_ context.Context, running *models.ExecutorRunning) error {
close(w.upserted)
if w.upsertErr != nil {
return w.upsertErr
}
w.running = running
return nil
}
func (w *launchRegistrationWriter) DeleteExecutorRunningBySessionID(context.Context, string) error {
w.deleted.Add(1)
w.running = nil
return nil
}
func (w *launchRegistrationWriter) RepairExecutorRunningDead(context.Context, string) error {
w.repaired.Add(1)
if w.running != nil {
w.running.Status = models.ExecutorRunningStatusStopped
}
return nil
}
func (r *launchRegistrationGateReader) GetTaskSession(_ context.Context, id string) (*models.TaskSession, error) {
read := r.reads.Add(1)
if read < r.blockRead {
return &models.TaskSession{ID: id, TaskID: "task-registration-race", State: models.TaskSessionStateStarting}, nil
}
if read == r.blockRead {
close(r.secondRead)
<-r.release
}
state := r.finalState
if state == "" {
state = models.TaskSessionStateCancelled
}
return &models.TaskSession{ID: id, TaskID: "task-registration-race", State: state}, nil
}
func (r *launchRegistrationGateReader) HasActiveTaskResourceCleanupJob(context.Context, string) (bool, error) {
if read := r.cleanupReads.Add(1); read == r.blockCleanupRead {
close(r.secondRead)
<-r.release
}
return r.cleanupActive.Load(), nil
}
func (*launchRegistrationGateReader) GetTaskEnvironment(context.Context, string) (*models.TaskEnvironment, error) {
return nil, nil
}
func (*launchRegistrationGateReader) GetExecutorProfile(context.Context, string) (*models.ExecutorProfile, error) {
return nil, nil
}
func TestLaunch_RollsBackWhenSessionEndsDuringRegistration(t *testing.T) {
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
execRegistry := NewExecutorRegistry(log)
backend := &createInstanceExecutor{MockExecutor: MockExecutor{name: executor.NameStandalone}}
execRegistry.Register(backend)
mgr := NewManager(
newTestRegistry(), &MockEventBus{}, execRegistry,
&MockCredentialsManager{}, &MockProfileResolver{}, nil,
ExecutorFallbackWarn, "", log,
)
mgr.dataDir = t.TempDir()
cleanupManagerStopCh(t, mgr)
reader := &launchRegistrationGateReader{
blockRead: 4,
secondRead: make(chan struct{}),
release: make(chan struct{}),
}
mgr.SetExecutorProfileReader(reader)
writer := &launchRegistrationWriter{upserted: make(chan struct{})}
mgr.SetExecutorRunningWriter(writer)
errCh := make(chan error, 1)
go func() {
_, err := mgr.Launch(context.Background(), &LaunchRequest{
TaskID: "task-registration-race",
SessionID: "session-registration-race",
AgentProfileID: "profile-1",
IsEphemeral: true,
})
errCh <- err
}()
select {
case <-reader.secondRead:
case err := <-errCh:
t.Fatalf("Launch returned before post-registration validation: %v", err)
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for post-registration session validation")
}
if _, exists := mgr.executionStore.GetBySessionID("session-registration-race"); !exists {
t.Fatal("execution must be registered before the final session validation")
}
select {
case <-writer.upserted:
default:
t.Fatal("executor-running row must be durable before the final session validation")
}
close(reader.release)
err := <-errCh
if err == nil || !strings.Contains(err.Error(), "CANCELLED") {
t.Fatalf("Launch error = %v, want terminal-session validation", err)
}
if got := backend.stopCount.Load(); got != 1 {
t.Fatalf("StopInstance called %d times, want 1", got)
}
if _, exists := mgr.executionStore.GetBySessionID("session-registration-race"); exists {
t.Fatal("terminal session runtime must be removed after registration race")
}
if got := writer.deleted.Load(); got != 1 {
t.Fatalf("executor-running delete count = %d, want 1", got)
}
}
func TestLaunch_RollsBackWhenTaskCleanupBeginsDuringRegistration(t *testing.T) {
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
execRegistry := NewExecutorRegistry(log)
backend := &createInstanceExecutor{MockExecutor: MockExecutor{name: executor.NameStandalone}}
execRegistry.Register(backend)
mgr := NewManager(
newTestRegistry(), &MockEventBus{}, execRegistry,
&MockCredentialsManager{}, &MockProfileResolver{}, nil,
ExecutorFallbackWarn, "", log,
)
mgr.dataDir = t.TempDir()
cleanupManagerStopCh(t, mgr)
reader := &launchRegistrationGateReader{
finalState: models.TaskSessionStateStarting,
blockCleanupRead: 2,
secondRead: make(chan struct{}),
release: make(chan struct{}),
}
mgr.SetExecutorProfileReader(reader)
writer := &launchRegistrationWriter{
upserted: make(chan struct{}),
running: &models.ExecutorRunning{
SessionID: "session-cleanup-race", ExecutionProfileID: "profile-1", ResumeToken: "resume-token",
},
}
mgr.SetExecutorRunningWriter(writer)
errCh := make(chan error, 1)
go func() {
_, err := mgr.Launch(context.Background(), &LaunchRequest{
TaskID: "task-registration-race",
SessionID: "session-cleanup-race",
AgentProfileID: "profile-1",
IsEphemeral: true,
})
errCh <- err
}()
select {
case <-reader.secondRead:
case err := <-errCh:
t.Fatalf("Launch returned before post-registration validation: %v", err)
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for post-registration session validation")
}
reader.cleanupActive.Store(true)
close(reader.release)
err := <-errCh
if err == nil || !strings.Contains(err.Error(), "cleanup is active") {
t.Fatalf("Launch error = %v, want active-cleanup validation", err)
}
if got := backend.stopCount.Load(); got != 1 {
t.Fatalf("StopInstance called %d times, want 1", got)
}
if _, exists := mgr.executionStore.GetBySessionID("session-cleanup-race"); exists {
t.Fatal("runtime must be removed when task cleanup wins registration race")
}
if got := writer.deleted.Load(); got != 0 {
t.Fatalf("executor-running delete count = %d, want 0 for resumable row", got)
}
if got := writer.repaired.Load(); got != 1 {
t.Fatalf("executor-running repair count = %d, want 1", got)
}
if writer.running == nil || writer.running.ResumeToken != "resume-token" || writer.running.Status != models.ExecutorRunningStatusStopped {
t.Fatalf("resumable row was not preserved and stopped: %#v", writer.running)
}
}
func TestLaunch_RollsBackWhenExecutionRegistrationCannotPersist(t *testing.T) {
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
execRegistry := NewExecutorRegistry(log)
backend := &createInstanceExecutor{MockExecutor: MockExecutor{name: executor.NameStandalone}}
execRegistry.Register(backend)
mgr := NewManager(
newTestRegistry(), &MockEventBus{}, execRegistry,
&MockCredentialsManager{}, &MockProfileResolver{}, nil,
ExecutorFallbackWarn, "", log,
)
mgr.dataDir = t.TempDir()
cleanupManagerStopCh(t, mgr)
mgr.SetExecutorProfileReader(&fakeExecutorProfileReader{session: &models.TaskSession{
ID: "session-persist-failure", TaskID: "task-persist-failure", State: models.TaskSessionStateStarting,
}})
writer := &launchRegistrationWriter{
upserted: make(chan struct{}),
upsertErr: errors.New("database is locked"),
}
mgr.SetExecutorRunningWriter(writer)
_, err := mgr.Launch(context.Background(), &LaunchRequest{
TaskID: "task-persist-failure",
SessionID: "session-persist-failure",
AgentProfileID: "profile-1",
IsEphemeral: true,
})
if err == nil || !strings.Contains(err.Error(), "persist execution registration") {
t.Fatalf("Launch error = %v, want persistence failure", err)
}
if got := backend.stopCount.Load(); got != 1 {
t.Fatalf("StopInstance called %d times, want 1", got)
}
if _, exists := mgr.executionStore.GetBySessionID("session-persist-failure"); exists {
t.Fatal("runtime must be removed when durable registration fails")
}
if got := writer.deleted.Load(); got != 0 {
t.Fatalf("executor-running delete count = %d, want 0 for an uncommitted upsert", got)
}
}
type staleLaunchAdmissionReader struct {
reads atomic.Int32
}
func (r *staleLaunchAdmissionReader) GetTaskSession(_ context.Context, id string) (*models.TaskSession, error) {
state := models.TaskSessionStateStarting
if r.reads.Add(1) > 1 {
state = models.TaskSessionStateCancelled
}
return &models.TaskSession{ID: id, TaskID: "task-terminalization-race", State: state}, nil
}
func (*staleLaunchAdmissionReader) HasActiveTaskResourceCleanupJob(context.Context, string) (bool, error) {
return false, nil
}
func (*staleLaunchAdmissionReader) GetTaskEnvironment(context.Context, string) (*models.TaskEnvironment, error) {
return nil, nil
}
func (*staleLaunchAdmissionReader) GetExecutorProfile(context.Context, string) (*models.ExecutorProfile, error) {
return nil, nil
}
func TestEnsureLaunchSessionStillActiveRereadsAfterCleanupAdmission(t *testing.T) {
mgr := newTestManager(t)
reader := &staleLaunchAdmissionReader{}
mgr.SetExecutorProfileReader(reader)
err := mgr.ensureLaunchSessionStillActive(context.Background(), "session-terminalization-race")
if err == nil || !strings.Contains(err.Error(), "CANCELLED") {
t.Fatalf("ensureLaunchSessionStillActive error = %v, want terminal-session validation", err)
}
if got := reader.reads.Load(); got != 2 {
t.Fatalf("session reads = %d, want 2", got)
}
}
type failOnceStopExecutor struct {
MockExecutor
attempts atomic.Int32
retryEntered chan struct{}
releaseRetry chan struct{}
succeeded chan struct{}
}
func (e *failOnceStopExecutor) StopInstance(context.Context, *ExecutorInstance, bool) error {
if e.attempts.Add(1) == 1 {
return errors.New("transient stop failure")
}
close(e.retryEntered)
<-e.releaseRetry
close(e.succeeded)
return nil
}
func TestRegisteredLaunchRollbackRetainsOwnershipUntilStopRetrySucceeds(t *testing.T) {
for _, taskCleanupActive := range []bool{false, true} {
name := "persistence_failure"
if taskCleanupActive {
name = "task_cleanup"
}
t.Run(name, func(t *testing.T) {
mgr := newTestManager(t)
execution := &AgentExecution{ID: "exec-stop-retry", SessionID: "session-stop-retry"}
if err := mgr.executionStore.Add(execution); err != nil {
t.Fatalf("Add execution: %v", err)
}
writer := &invariantWriter{prior: &models.ExecutorRunning{
AgentExecutionID: execution.ID,
SessionID: execution.SessionID,
ResumeToken: "resume-token",
Status: models.ExecutorRunningStatusStarting,
}}
mgr.SetExecutorRunningWriter(writer)
backend := &failOnceStopExecutor{
MockExecutor: MockExecutor{name: executor.NameStandalone},
retryEntered: make(chan struct{}),
releaseRetry: make(chan struct{}),
succeeded: make(chan struct{}),
}
mgr.rollbackRegisteredLaunchWithRetry(
backend, &ExecutorInstance{InstanceID: execution.ID}, execution,
taskCleanupActive, "test rollback",
)
select {
case <-backend.retryEntered:
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for detached stop retry")
}
if _, exists := mgr.executionStore.Get(execution.ID); !exists {
t.Fatal("failed stop retired in-memory cleanup ownership")
}
if writer.deleted || writer.repaired {
t.Fatal("failed stop retired durable cleanup ownership")
}
close(backend.releaseRetry)
select {
case <-backend.succeeded:
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for detached stop retry")
}
require.Eventually(t, func() bool {
_, exists := mgr.executionStore.Get(execution.ID)
return !exists
}, time.Second, 10*time.Millisecond)
if writer.deleted || !writer.repaired || writer.prior == nil || writer.prior.ResumeToken != "resume-token" {
t.Fatalf("successful retry did not preserve resume state: %#v", writer)
}
})
}
}
func TestLaunch_PersistsDockerRuntimeSecrets(t *testing.T) {
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
execRegistry := NewExecutorRegistry(log)
@@ -230,21 +230,22 @@ func executorRunningStatusFromExecution(execution *AgentExecution) string {
// runtime / status; the orchestrator owns resume_token / last_message_uuid /
// metadata.context_window via narrow CAS updates.
//
// Logs and continues on persistence failure rather than failing the launch —
// the in-memory store already has the truth, and the row will be re-upserted
// on the next launch through this same path. (storeResumeToken does NOT
// re-create a missing row; it uses a narrow CAS UPDATE keyed on
// agent_execution_id, so a failure here leaves resume_token persistence broken
// until the next full launch.) The store is the runtime authority; the row is
// its durable mirror.
// Status-only persistence is best-effort: the in-memory store is still the
// runtime authority and a later transition can re-upsert its durable mirror.
// New-runtime registration calls persistExecutorRunningResult directly and
// fails closed because task cleanup relies on this row for race inventory.
func (m *Manager) persistExecutorRunning(ctx context.Context, execution *AgentExecution) {
_ = m.persistExecutorRunningResult(ctx, execution)
}
func (m *Manager) persistExecutorRunningResult(ctx context.Context, execution *AgentExecution) error {
if m.runningWriter == nil {
// Permitted in tests that don't exercise persistence; logged so a
// missed wire-up in production stands out.
m.logger.Debug("no executor-running writer configured; skipping row persistence",
zap.String("execution_id", execution.ID),
zap.String("session_id", execution.SessionID))
return
return nil
}
// Best-effort read of any pre-existing row so we carry forward the orchestrator-
@@ -272,7 +273,7 @@ func (m *Manager) persistExecutorRunning(ctx context.Context, execution *AgentEx
zap.String("execution_id", execution.ID),
zap.String("session_id", execution.SessionID),
zap.Error(err))
return
return err
}
}
if execution.AgentProfileID == "" && prior != nil {
@@ -304,7 +305,9 @@ func (m *Manager) persistExecutorRunning(ctx context.Context, execution *AgentEx
zap.String("execution_id", execution.ID),
zap.String("session_id", execution.SessionID),
zap.Error(err))
return err
}
return nil
}
// deleteExecutorRunning tears down the persistence row when an execution is
@@ -12,8 +12,9 @@ import (
)
type captureExecutorRunningWriter struct {
prior *models.ExecutorRunning
running *models.ExecutorRunning
prior *models.ExecutorRunning
running *models.ExecutorRunning
upsertErr error
}
func (w *captureExecutorRunningWriter) GetExecutorRunningBySessionID(
@@ -27,7 +28,7 @@ func (w *captureExecutorRunningWriter) GetExecutorRunningBySessionID(
func (w *captureExecutorRunningWriter) UpsertExecutorRunning(_ context.Context, running *models.ExecutorRunning) error {
w.running = running
return nil
return w.upsertErr
}
func (w *captureExecutorRunningWriter) DeleteExecutorRunningBySessionID(_ context.Context, _ string) error {
@@ -113,6 +114,20 @@ func TestPersistExecutorRunningRestoresRecoveredExecutionProfile(t *testing.T) {
}
}
func TestPersistExecutorRunningReturnsUpsertFailure(t *testing.T) {
writer := &captureExecutorRunningWriter{upsertErr: errors.New("database is locked")}
mgr := newTestManager(t)
mgr.SetExecutorRunningWriter(writer)
err := mgr.persistExecutorRunningResult(context.Background(), &AgentExecution{
ID: "exec-failed-persist", TaskID: "task-1", SessionID: "session-1",
Status: v1.AgentStatusStarting,
})
if err == nil || !errors.Is(err, writer.upsertErr) {
t.Fatalf("persistExecutorRunning error = %v, want %v", err, writer.upsertErr)
}
}
func TestBuildRunningFromExecutionPersistsSSHRuntimePID(t *testing.T) {
log := newNopLogger(t)
client := agentctl.NewClient("127.0.0.1", 43001, log)
@@ -97,6 +97,7 @@ type lifecycleAdapter struct {
var _ interface {
OwnsPromptGeneration(sessionID, executionID string, generation uint64) bool
GetPromptGenerationForSession(ctx context.Context, sessionID string) (uint64, error)
} = (*lifecycleAdapter)(nil)
// newLifecycleAdapter creates a new lifecycle adapter
@@ -403,6 +404,10 @@ func (a *lifecycleAdapter) OwnsPromptGeneration(sessionID, executionID string, g
return a.mgr.OwnsPromptGeneration(sessionID, executionID, generation)
}
func (a *lifecycleAdapter) GetPromptGenerationForSession(ctx context.Context, sessionID string) (uint64, error) {
return a.mgr.GetPromptGenerationForSession(ctx, sessionID)
}
func (a *lifecycleAdapter) GetSessionAuthMethods(sessionID string) []streams.AuthMethodInfo {
return a.mgr.GetSessionAuthMethods(sessionID)
}
@@ -273,6 +273,10 @@ func (s *stubExecutorProfileReader) GetTaskEnvironment(_ context.Context, _ stri
return s.env, nil
}
func (*stubExecutorProfileReader) HasActiveTaskResourceCleanupJob(context.Context, string) (bool, error) {
return false, nil
}
func (s *stubExecutorProfileReader) GetExecutorProfile(_ context.Context, _ string) (*taskmodels.ExecutorProfile, error) {
return s.profile, nil
}
@@ -45,6 +45,13 @@ func (s *Service) handleAgentRunning(ctx context.Context, data watcher.AgentEven
defer release()
lock.Lock()
defer lock.Unlock()
if err := s.waitForCancellationWithGuard(ctx, data.SessionID, lock.Unlock, lock.Lock); err != nil {
s.logger.Debug("ignoring agent running event after cancellation wait was interrupted",
zap.String("task_id", data.TaskID),
zap.String("session_id", data.SessionID),
zap.Error(err))
return
}
session, err := s.repo.GetTaskSession(ctx, data.SessionID)
if err != nil {
@@ -234,7 +241,36 @@ func (s *Service) handleAgentBootReady(ctx context.Context, data watcher.AgentEv
return
}
lock, release := s.acquireCancelInFlightGuard(data.SessionID)
if !lock.TryLock() {
if s.isCancelInFlight(data.SessionID) {
// Cancellation owns reconciliation and intentionally holds the guard
// until it has settled the session. Never make it wait for this stale
// boot signal.
release()
s.logger.Debug("ignoring agent.boot_ready while cancel is in progress",
zap.String("task_id", data.TaskID),
zap.String("session_id", data.SessionID))
return
}
// Stream metadata also uses this guard, but boot-ready is a one-shot
// lifecycle signal. Wait for ordinary stream persistence to finish
// instead of dropping the only event that can settle a booted session.
lock.Lock()
}
guardLocked := true
defer func() {
if guardLocked {
lock.Unlock()
}
release()
}()
if s.isCancelInFlight(data.SessionID) {
// A boot-ready event that arrives while cancellation is waiting must
// not revive the session in the cancellation window. The cancellation
// owner will reconcile the session after the lifecycle wait; dropping
// this stale boot signal also avoids blocking a handler on a marker that
// is intentionally held until that reconciliation is complete.
s.logger.Debug("ignoring agent.boot_ready while cancel is in progress",
zap.String("task_id", data.TaskID),
zap.String("session_id", data.SessionID))
@@ -293,6 +329,12 @@ func (s *Service) handleAgentBootReady(ctx context.Context, data watcher.AgentEv
// own cancel+take runs. drainQueuedMessageForPromptableSession now owns
// that acquisition itself (blocking, plus its own promptability
// reload) — see its doc comment.
// Release the guard before the public drain reacquires it. The state flip
// above is the guarded admission decision; the drain performs its own
// cancellation check and leaves the queue untouched if a new cancellation
// claims the session in this handoff.
lock.Unlock()
guardLocked = false
s.drainQueuedMessageForPromptableSession(ctx, data.SessionID)
}
@@ -392,7 +434,34 @@ func (s *Service) handleAgentReady(ctx context.Context, data watcher.AgentEventD
lock, release := s.acquireCancelInFlightGuard(data.SessionID)
defer release()
lock.Lock()
defer lock.Unlock()
guardLocked := true
defer func() {
if guardLocked {
lock.Unlock()
}
}()
for s.isCancelInFlight(data.SessionID) {
// The cancellation owner temporarily releases this mutex while the
// lifecycle manager waits for terminal stream frames. Do not complete
// the still-running turn in that window, but also do not discard this
// ready event: if cancellation fails, it is the event that must finish
// the unchanged turn and drain its queue.
lock.Unlock()
guardLocked = false
if err := s.waitForCancelInFlight(context.WithoutCancel(ctx), data.SessionID); err != nil {
// A cancellation error does not make this ready event stale. The
// owner may have failed before mutating session/turn state; once the
// operation is gone, re-read both below and let this event settle its
// captured turn. Returning here would strand the turn and any queued
// peer message with no future ready event to drain it.
s.logger.Warn("cancellation failed while agent.ready was waiting; re-evaluating the captured turn",
zap.String("task_id", data.TaskID),
zap.String("session_id", data.SessionID),
zap.Error(err))
}
lock.Lock()
guardLocked = true
}
// Re-validate now that the guard is held: a concurrent interrupt (or
// clarification recovery, or another drain) may have already resolved
@@ -833,6 +902,13 @@ func (s *Service) handleAgentCompleted(ctx context.Context, data watcher.AgentEv
defer release()
lock.Lock()
defer lock.Unlock()
if s.isCancelInFlight(data.SessionID) {
s.logger.Debug("deferring agent.completed while cancellation is in progress",
zap.String("task_id", data.TaskID),
zap.String("session_id", data.SessionID),
zap.String("agent_execution_id", data.AgentExecutionID))
return
}
s.handleAgentCompletedLocked(ctx, data)
}
@@ -957,6 +1033,13 @@ func (s *Service) handleAgentFailed(ctx context.Context, data watcher.AgentEvent
defer release()
lock.Lock()
defer lock.Unlock()
if s.isCancelInFlight(data.SessionID) {
s.logger.Debug("deferring agent.failed while cancellation is in progress",
zap.String("task_id", data.TaskID),
zap.String("session_id", data.SessionID),
zap.String("agent_execution_id", data.AgentExecutionID))
return
}
s.handleAgentFailedLocked(ctx, data)
}
@@ -1132,16 +1215,32 @@ func (s *Service) claimForcedExecutionCleanup(sessionID, executionID string) boo
if sessionID == "" {
return true
}
lock, release := s.acquireCancelInFlightGuard(sessionID)
lock.Lock()
claimed := s.claimExecutionTeardown(
sessionID,
executionID,
executionTeardownIntentForce,
)
lock.Unlock()
release()
return claimed
for {
if s.isCancelInFlight(sessionID) {
// Cleanup is a terminal claim, not an advisory event. Defer it until
// the cancellation owner has completed its lifecycle and reconciliation
// so a cancellation cannot strand the execution teardown.
if err := s.waitForCancelInFlight(context.Background(), sessionID); err != nil {
return false
}
continue
}
lock, release := s.acquireCancelInFlightGuard(sessionID)
lock.Lock()
if s.isCancelInFlight(sessionID) {
lock.Unlock()
release()
continue
}
claimed := s.claimExecutionTeardown(
sessionID,
executionID,
executionTeardownIntentForce,
)
lock.Unlock()
release()
return claimed
}
}
// RegisterExecutionStopOwner records explicit teardown ownership before a
@@ -1157,6 +1256,12 @@ func (s *Service) RegisterExecutionStopOwner(sessionID, executionID string, forc
lock.Unlock()
release()
}()
if s.isCancelInFlight(sessionID) {
s.logger.Debug("deferring execution stop ownership while cancellation is in progress",
zap.String("session_id", sessionID),
zap.String("execution_id", executionID))
return
}
intent := executionTeardownIntentGraceful
if force {
@@ -1440,6 +1545,13 @@ func (s *Service) handleAgentStartFailed(ctx context.Context, taskID, sessionID,
defer release()
lock.Lock()
defer lock.Unlock()
if s.isCancelInFlight(sessionID) {
s.logger.Debug("deferring agent start failure while cancellation is in progress",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.Error(err))
return true
}
if drop, terminalState := s.shouldDropSessionFailure(ctx, watcher.AgentEventData{
TaskID: taskID,
@@ -63,6 +63,12 @@ func (s *Service) handleClarificationStaleDismissed(ctx context.Context, event *
defer release()
lock.Lock()
defer lock.Unlock()
if s.isCancelInFlight(data.SessionID) {
s.logger.Debug("ignoring stale clarification dismissal while cancellation is in progress",
zap.String("task_id", data.TaskID),
zap.String("session_id", data.SessionID))
return nil
}
if s.sessionHasPendingClarification(writeCtx, data.SessionID) {
return nil
@@ -135,6 +141,12 @@ func (s *Service) handleClarificationAnswered(ctx context.Context, event *bus.Ev
zap.String("session_id", data.SessionID),
zap.Bool("rejected", data.Rejected))
// The primary MCP request can keep the session RUNNING while the task was
// moved to REVIEW for the pending question. Reassert runtime ownership at
// the answer boundary; terminal and archived sessions remain protected by
// reconcileTaskStateForRuntime.
s.writeTaskInProgressForRuntime(ctx, data.TaskID, data.SessionID)
if _, err := s.PromptTask(ctx, data.TaskID, data.SessionID, prompt, "", false, nil, false); err != nil {
if !s.retryClarificationAfterCancel(ctx, data, prompt, err) {
s.logger.Error("failed to resume agent with clarification answer",
@@ -146,7 +158,7 @@ func (s *Service) handleClarificationAnswered(ctx context.Context, event *bus.Ev
return nil
}
func (s *Service) handleClarificationPrimaryAnswered(_ context.Context, event *bus.Event) error {
func (s *Service) handleClarificationPrimaryAnswered(ctx context.Context, event *bus.Event) error {
dataBytes, err := json.Marshal(event.Data)
if err != nil {
s.logger.Error("failed to marshal primary clarification event data", zap.Error(err))
@@ -165,6 +177,10 @@ func (s *Service) handleClarificationPrimaryAnswered(_ context.Context, event *b
return nil
}
// A directly answered MCP request does not transition the session through
// WAITING_FOR_INPUT, so no ordinary turn-start event exists to move a task
// out of REVIEW. The active runtime still owns that projection.
s.writeTaskInProgressForRuntime(ctx, data.TaskID, data.SessionID)
s.scheduleClarificationWatchdog(data)
return nil
}
@@ -283,9 +299,24 @@ func (s *Service) retryClarificationAfterCancel(ctx context.Context, data clarif
// a concurrent interrupt/drain still backs off exactly as an inline retry
// would have.
lock, release := s.acquireCancelInFlightGuard(data.SessionID)
defer release()
lock.Lock()
defer lock.Unlock()
guardLocked := true
unlockGuard := func() {
if guardLocked {
lock.Unlock()
guardLocked = false
}
}
relockGuard := func() {
if !guardLocked {
lock.Lock()
guardLocked = true
}
}
defer func() {
unlockGuard()
release()
}()
// Coordinator stop may have won while this recovery waited for the shared
// guard. Re-read inside the critical section and never revive a terminal
@@ -304,7 +335,7 @@ func (s *Service) retryClarificationAfterCancel(ctx context.Context, data clarif
return false
}
if err := s.cancelAgentSilent(ctx, data.TaskID, data.SessionID); err != nil {
if err := s.cancelAgentSilentWithGuard(ctx, data.TaskID, data.SessionID, unlockGuard, relockGuard); err != nil {
s.logger.Warn("cancel failed (agent likely dead), force-transitioning session state",
zap.String("session_id", data.SessionID),
zap.Error(err))
@@ -327,6 +358,23 @@ func (s *Service) retryClarificationAfterCancel(ctx context.Context, data clarif
}
s.completeTurnForSession(ctx, data.SessionID)
}
// The joined cancellation may have been owned by the user-facing cancel
// path. Re-read after the shared operation settles before queueing a
// clarification replacement; a stale pre-cancel RUNNING snapshot must not
// revive a session that the explicit source already marked terminal.
session, sessionErr = s.repo.GetTaskSession(ctx, data.SessionID)
if sessionErr != nil || session == nil {
s.logger.Debug("cannot confirm session after clarification cancellation",
zap.String("session_id", data.SessionID),
zap.Error(sessionErr))
return false
}
if isTerminalSessionState(session.State) {
s.logger.Debug("skipping clarification replacement for terminal session after cancellation",
zap.String("session_id", data.SessionID),
zap.String("session_state", string(session.State)))
return false
}
if err := s.dispatchClarificationResumeLocked(ctx, data, prompt); err != nil {
if errors.Is(err, errClarificationResumeQueuedForDrain) {
@@ -441,10 +489,25 @@ func (s *Service) PauseForClarificationInput(ctx context.Context, sessionID stri
// this clarification-timeout cancel, or it can race a concurrent parent
// interrupt (or another drain) for the same session.
lock, release := s.acquireCancelInFlightGuard(sessionID)
defer release()
lock.Lock()
defer lock.Unlock()
if err := s.cancelAgentSilent(writeCtx, session.TaskID, sessionID); err != nil {
guardLocked := true
unlockGuard := func() {
if guardLocked {
lock.Unlock()
guardLocked = false
}
}
relockGuard := func() {
if !guardLocked {
lock.Lock()
guardLocked = true
}
}
defer func() {
unlockGuard()
release()
}()
if err := s.cancelAgentSilentWithGuard(writeCtx, session.TaskID, sessionID, unlockGuard, relockGuard); err != nil {
return detached, err
}
return detached, nil
@@ -457,24 +520,172 @@ func (s *Service) PauseForClarificationInput(ctx context.Context, sessionID stri
// (agent crashed mid-turn). In that case, skip the cancel signal but still reconcile the
// session's state so clarification recovery can proceed with a fresh prompt.
func (s *Service) cancelAgentSilent(ctx context.Context, taskID, sessionID string) error {
endCancel := s.beginCancelInFlight(sessionID)
defer endCancel()
_, err := s.cancelAgentSilentAction(ctx, taskID, sessionID, nil)
return err
}
if s.agentManager == nil {
s.logger.Debug("skipping silent clarification cancel because agent manager is not configured",
zap.String("task_id", taskID),
zap.String("session_id", sessionID))
} else if err := s.agentManager.CancelAgent(ctx, sessionID); err != nil {
if !errors.Is(err, lifecycle.ErrNoExecutionForSession) && !errors.Is(err, lifecycle.ErrCancelEscalated) {
return fmt.Errorf("cancel agent: %w", err)
}
s.logSilentCancelReconciled(taskID, sessionID, err)
func (s *Service) cancelAgentSilentAction(
ctx context.Context,
taskID, sessionID string,
action func(context.Context) (bool, error),
) (bool, error) {
return s.cancelAgentSilentActionWithKind(ctx, taskID, sessionID, action, cancellationKindSilent)
}
func (s *Service) cancelAgentSilentActionWithKind(
ctx context.Context,
taskID, sessionID string,
action func(context.Context) (bool, error),
kind cancellationKind,
) (bool, error) {
if s.repo == nil {
return false, errors.New("cancel agent silently: repository is not configured")
}
var registeredAction func(context.Context, *cancelOperation) (bool, error)
if action != nil {
registeredAction = func(actionCtx context.Context, _ *cancelOperation) (bool, error) {
return action(actionCtx)
}
}
operation, owner, registered := s.claimCancellationWithAction(sessionID, kind, registeredAction)
if owner {
go s.runSilentCancellation(ctx, taskID, sessionID, operation)
}
if err := operation.wait(ctx); err != nil {
return false, err
}
if registered == nil {
return false, nil
}
return registered.wait(ctx)
}
func (s *Service) runSilentCancellation(requestCtx context.Context, taskID, sessionID string, operation *cancelOperation) {
endProjection := s.beginCancellationProjection(sessionID)
operation.projectionRelease = endProjection
defer endProjection()
operationCtx, cancel := context.WithTimeout(context.WithoutCancel(requestCtx), cancellationOperationTTL)
defer cancel()
err := s.runSilentCancellationOwned(operationCtx, taskID, sessionID, operation)
s.finishCancellationWithActions(operationCtx, sessionID, operation, err)
}
func (s *Service) runSilentCancellationOwned(ctx context.Context, taskID, sessionID string, operation *cancelOperation) error {
lock, release := s.acquireCancelInFlightGuard(sessionID)
defer release()
lock.Lock()
guardLocked := true
unlockGuard := func() {
if guardLocked {
lock.Unlock()
guardLocked = false
}
}
relockGuard := func() {
if !guardLocked {
lock.Lock()
guardLocked = true
}
}
defer unlockGuard()
// Capture only the execution/turn identity before yielding the guard. The
// peer-interrupt path can race a ready handler that is blocked in its first
// session read; loading the session before lifecycle cancellation would
// strand both callers behind that read and prevent the cancel signal from
// reaching the agent. Silent cancellation never evaluates workflow
// completion, so its authoritative session reload can happen after the
// lifecycle wait, immediately before source-specific reconciliation.
identity, err := s.captureCancellationIdentity(ctx, sessionID)
if err != nil {
return err
}
s.setCancellationIdentity(sessionID, operation, identity)
if err := s.cancelAgentWhileUnlocked(ctx, sessionID, unlockGuard, relockGuard); err != nil {
return err
}
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
return fmt.Errorf("load session after silent cancel: %w", err)
}
completionEligible, err := s.cancelTurnCompletionEligible(ctx, session, sessionID)
if err != nil {
return err
}
s.setCancellationCompletionEligible(sessionID, operation, completionEligible)
prepared := cancelAgentPreparation{session: session, identity: identity}
prepared.completionEligible = completionEligible
return s.finishSilentCancelledAgentTurn(ctx, taskID, sessionID, prepared)
}
func (s *Service) finishSilentCancelledAgentTurn(
ctx context.Context,
taskID, sessionID string,
prepared cancelAgentPreparation,
) error {
if prepared.session != nil {
if _, err := s.reconcileCancelledTurnOwned(
ctx,
taskID,
sessionID,
prepared.session,
true,
prepared.identity.turnID,
); err != nil {
return fmt.Errorf("reconcile silent cancelled turn: %w", err)
}
return nil
}
if _, err := s.reconcileCancelledTurnOwned(ctx, taskID, sessionID, nil, false, prepared.identity.turnID); err != nil {
return fmt.Errorf("reconcile silent cancelled turn: %w", err)
}
s.updateTaskSessionState(ctx, taskID, sessionID, models.TaskSessionStateWaitingForInput, "", true, nil)
s.completeTurnForSession(ctx, sessionID)
return nil
}
// cancelAgentSilentWithGuard releases the caller's guard while the unified
// cancellation coordinator owns the lifecycle wait. It reacquires the guard
// before returning so callers can continue their source-specific queue or
// clarification action under the same serialization boundary.
func (s *Service) cancelAgentSilentWithGuard(
ctx context.Context,
taskID string,
sessionID string,
unlockGuard func(),
relockGuard func(),
) error {
_, err := s.cancelAgentSilentWithGuardAction(ctx, taskID, sessionID, unlockGuard, relockGuard, nil)
return err
}
func (s *Service) cancelAgentSilentWithGuardAction(
ctx context.Context,
taskID string,
sessionID string,
unlockGuard func(),
relockGuard func(),
action func(context.Context) (bool, error),
) (bool, error) {
return s.cancelAgentSilentWithGuardActionKind(
ctx, taskID, sessionID, unlockGuard, relockGuard, action, cancellationKindSilent,
)
}
func (s *Service) cancelAgentSilentWithGuardActionKind(
ctx context.Context,
taskID string,
sessionID string,
unlockGuard func(),
relockGuard func(),
action func(context.Context) (bool, error),
kind cancellationKind,
) (bool, error) {
if unlockGuard != nil {
unlockGuard()
defer relockGuard()
}
return s.cancelAgentSilentActionWithKind(ctx, taskID, sessionID, action, kind)
}
func (s *Service) logSilentCancelReconciled(taskID, sessionID string, err error) {
if errors.Is(err, lifecycle.ErrCancelEscalated) {
s.logger.Warn("agent did not acknowledge silent clarification cancel; reconciling session state",
@@ -582,11 +582,20 @@ func TestBuildClarificationPrompt(t *testing.T) {
}
func TestHandleClarificationPrimaryAnswered_SchedulesWatchdog(t *testing.T) {
svc := &Service{
logger: testLogger(),
clarificationWatchdogTimeout: 500 * time.Millisecond,
}
repo := setupTestRepo(t)
seedTaskAndSession(t, repo, "t1", "s1", models.TaskSessionStateRunning)
taskRepo := newMockTaskRepo()
svc := createTestServiceWithScheduler(
repo,
newMockStepGetter(),
taskRepo,
&mockAgentManager{isAgentRunning: true},
)
svc.clarificationWatchdogTimeout = 500 * time.Millisecond
t.Cleanup(func() { svc.cancelAllClarificationWatchdogs() })
if err := repo.UpdateTaskState(context.Background(), "t1", v1.TaskStateReview); err != nil {
t.Fatalf("set task review state: %v", err)
}
event := bus.NewEvent("clarification.primary_answered", "test", map[string]any{
"session_id": "s1",
@@ -603,13 +612,21 @@ func TestHandleClarificationPrimaryAnswered_SchedulesWatchdog(t *testing.T) {
if got := countClarificationWatchdogs(svc); got != 1 {
t.Fatalf("expected 1 active watchdog, got %d", got)
}
if got := taskRepo.updatedStates["t1"]; got != v1.TaskStateInProgress {
t.Fatalf("task state = %q, want %q", got, v1.TaskStateInProgress)
}
}
func TestHandleAgentStreamEvent_CancelsClarificationWatchdogs(t *testing.T) {
svc := &Service{
logger: testLogger(),
clarificationWatchdogTimeout: time.Second,
}
repo := setupTestRepo(t)
seedTaskAndSession(t, repo, "t1", "s1", models.TaskSessionStateRunning)
svc := createTestServiceWithScheduler(
repo,
newMockStepGetter(),
newMockTaskRepo(),
&mockAgentManager{isAgentRunning: true},
)
svc.clarificationWatchdogTimeout = time.Second
t.Cleanup(func() { svc.cancelAllClarificationWatchdogs() })
event := bus.NewEvent("clarification.primary_answered", "test", map[string]any{
@@ -871,6 +871,56 @@ func TestHandleAgentBootReady_DoesNotDrainForTerminalSession(t *testing.T) {
}
}
func TestHandleAgentBootReady_WaitsForNonCancellationGuardHolder(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedSession(t, repo, "t1", "s1", "step1")
if err := repo.UpdateTaskSessionState(ctx, "s1", models.TaskSessionStateStarting, ""); err != nil {
t.Fatalf("set session starting: %v", err)
}
log := testLogger()
svc := &Service{
logger: log,
repo: repo,
taskRepo: newMockTaskRepo(),
agentManager: &mockAgentManager{repoForExecutionLookup: repo},
messageQueue: messagequeue.NewServiceMemory(log),
}
lock, release := svc.acquireCancelInFlightGuard("s1")
lock.Lock()
handlerDone := make(chan struct{})
go func() {
svc.handleAgentBootReady(ctx, watcher.AgentEventData{TaskID: "t1", SessionID: "s1"})
close(handlerDone)
}()
select {
case <-handlerDone:
lock.Unlock()
release()
t.Fatal("boot-ready was dropped while a non-cancellation stream handler held the guard")
case <-time.After(100 * time.Millisecond):
}
lock.Unlock()
release()
select {
case <-handlerDone:
case <-time.After(time.Second):
t.Fatal("boot-ready did not resume after the guard was released")
}
session, err := repo.GetTaskSession(ctx, "s1")
if err != nil {
t.Fatalf("get session: %v", err)
}
if session.State != models.TaskSessionStateWaitingForInput {
t.Fatalf("session state = %q, want %q", session.State, models.TaskSessionStateWaitingForInput)
}
}
func TestHandleAgentBootReady_DoesNotDrainWhileCancelInFlight(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
@@ -23,6 +23,16 @@ func (s *Service) handleAgentStalled(ctx context.Context, payload lifecycle.Agen
if s.messageCreator == nil || s.repo == nil || payload.TaskID == "" || payload.SessionID == "" {
return
}
lock, release := s.acquireCancelInFlightGuard(payload.SessionID)
defer release()
lock.Lock()
defer lock.Unlock()
if s.isCancelInFlight(payload.SessionID) {
s.logger.Debug("ignoring agent stall while cancellation is in progress",
zap.String("task_id", payload.TaskID),
zap.String("session_id", payload.SessionID))
return
}
session, err := s.repo.GetTaskSession(ctx, payload.SessionID)
if err != nil || session == nil || session.State != models.TaskSessionStateRunning {
return
@@ -83,6 +83,12 @@ func (s *Service) onStepCompletionSignaled(ctx context.Context, event *bus.Event
defer release()
lock.Lock()
defer lock.Unlock()
if s.isCancelInFlight(sessionID) {
s.logger.Debug("deferring workflow step completion signal while cancellation is in progress",
zap.String("task_id", taskID),
zap.String("session_id", sessionID))
return
}
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
@@ -36,6 +36,27 @@ func (s *Service) handleAgentStreamEvent(ctx context.Context, payload *lifecycle
lock.Lock()
defer lock.Unlock()
}
// Cancellation owns the yielded interval between the guarded preparation
// and lifecycle wait. Terminal frames from that captured execution/prompt
// remain admissible so the lifecycle manager can drain them; frames from a
// successor or stale execution must not mutate the session while the owner
// is reconciling the cancelled turn.
eventExecutionID := payload.ExecutionID
if eventExecutionID == "" {
eventExecutionID = payload.AgentID
}
if !s.cancellationOwnsStreamEvent(
payload.SessionID,
eventExecutionID,
payload.Data.PromptGeneration,
) {
s.logger.Debug("ignoring stream event for execution outside cancellation identity",
zap.String("task_id", payload.TaskID),
zap.String("session_id", payload.SessionID),
zap.String("event_execution_id", eventExecutionID),
zap.Uint64("event_prompt_generation", payload.Data.PromptGeneration))
return
}
taskID := payload.TaskID
sessionID := payload.SessionID
eventType := payload.Data.Type
@@ -285,6 +285,7 @@ type mockAgentManager struct {
// supplied context has been cancelled. It lets cancellation tests verify
// that accepted work uses a detached context.
cancelAgentContextErr error
cancelAgentFunc func(context.Context, string) error
// cancelAgentErr, when set, is returned by CancelAgent instead of nil —
// lets tests exercise callers that must react to a genuine cancel
// failure (as opposed to the tolerated ErrNoExecutionForSession /
@@ -403,7 +404,7 @@ func (m *mockAgentManager) PromptAgentWithDispatchCallback(ctx context.Context,
}
return result, err
}
func (m *mockAgentManager) CancelAgent(ctx context.Context, _ string) error {
func (m *mockAgentManager) CancelAgent(ctx context.Context, sessionID string) error {
m.cancelAgentCalls.Add(1)
if m.cancelAgentEntered != nil {
select {
@@ -414,6 +415,9 @@ func (m *mockAgentManager) CancelAgent(ctx context.Context, _ string) error {
if m.cancelAgentBlock != nil {
<-m.cancelAgentBlock
}
if m.cancelAgentFunc != nil {
return m.cancelAgentFunc(ctx, sessionID)
}
if m.cancelAgentContextErr != nil && ctx.Err() != nil {
return m.cancelAgentContextErr
}
@@ -439,6 +443,10 @@ func (m *mockAgentManager) OwnsPromptGeneration(_ string, executionID string, ge
return executionID == m.currentPromptExecutionID && generation == m.currentPromptGeneration.Load()
}
func (m *mockAgentManager) GetPromptGenerationForSession(_ context.Context, _ string) (uint64, error) {
return m.currentPromptGeneration.Load(), nil
}
// RowLiveness makes the mock satisfy the orchestrator's optional
// rowLivenessProber. It delegates to rowLivenessFn when set, else reports Unknown
// so tests that don't care about liveness see the safe default.
@@ -268,6 +268,9 @@ func (s *Service) ProcessOnTurnStart(ctx context.Context, taskID, sessionID stri
defer release()
lock.Lock()
defer lock.Unlock()
if err := s.waitForCancellationWithGuard(ctx, sessionID, lock.Unlock, lock.Lock); err != nil {
return err
}
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
@@ -1423,6 +1426,11 @@ func (s *Service) drainQueuedMessageForPromptableSession(ctx context.Context, se
defer release()
lock.Lock()
defer lock.Unlock()
if s.isCancelInFlight(sessionID) {
s.logger.Debug("skipping drain while cancellation is in progress",
zap.String("session_id", sessionID))
return false
}
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
@@ -1450,7 +1458,7 @@ func (s *Service) drainQueuedMessageForPromptableSession(ctx context.Context, se
// Service.dispatchingQueued field doc comment for the double-dispatch
// window this closes.
func (s *Service) drainQueuedMessageForPromptableSessionLocked(ctx context.Context, sessionID string) bool {
if s.messageQueue == nil || s.isQueuedDispatchInFlight(sessionID) {
if s.messageQueue == nil || s.isCancelInFlight(sessionID) || s.isQueuedDispatchInFlight(sessionID) {
return false
}
queuedMsg, ok := s.messageQueue.ReserveQueued(ctx, sessionID)
@@ -1778,6 +1786,12 @@ func (s *Service) fallbackFreshLaunchOnMissingExecution(
// the guarded state CAS below sees CANCELLED and aborts the replacement.
cancelLock, releaseCancelLock := s.acquireCancelInFlightGuard(sessionID)
cancelLock.Lock()
if s.isCancelInFlight(sessionID) {
cancelLock.Unlock()
releaseCancelLock()
requeue()
return &executor.SessionStateSupersededError{SessionID: sessionID, State: models.TaskSessionStateCancelled}
}
fresh, err := s.resetSessionForFreshFallback(ctx, sessionID)
cancelLock.Unlock()
releaseCancelLock()
+99 -3
View File
@@ -12,6 +12,7 @@ package orchestrator
import (
"context"
"database/sql"
"errors"
"fmt"
"regexp"
@@ -42,6 +43,10 @@ import (
v1 "github.com/kandev/kandev/pkg/api/v1"
)
func isNoActiveTurnError(err error) bool {
return errors.Is(err, sql.ErrNoRows)
}
// Common errors
var (
ErrServiceAlreadyRunning = errors.New("service is already running")
@@ -574,9 +579,10 @@ type Service struct {
cancelInFlightMu sync.Mutex
// cancelInFlight holds one *cancelInFlightGuard per session with an
// active reference — an in-progress or waiting claim from CancelAgent
// (the user cancel button — TryLock, dedup impatient retries), the
// natural turn-completion/boot-ready drain decision in handleAgentReady
// / handleAgentBootReady (TryLock, skip if a cancel/interrupt owns it),
// (the user cancel button, with duplicate and cross-source calls joined by
// the unified cancellation operation registry), the natural turn-completion/boot-ready drain
// decision in handleAgentReady / handleAgentBootReady (blocking while an
// active cancellation marker yields),
// or QueueAndInterruptForPeerMessage (blocking Lock — must wait rather
// than work around a busy lock with an unguarded insert; see its doc
// comment), or an agent stream handler persisting output (blocking Lock so
@@ -593,6 +599,14 @@ type Service struct {
// long-lived backend's lifetime.
cancelInFlight map[string]*cancelInFlightGuard
// cancellationOperations is the single per-session ownership boundary for
// every lifecycle cancellation source: explicit user cancel, silent
// clarification recovery, and peer-message interrupts. The owner keeps the
// operation in this map across the lifecycle wait and source-specific
// reconciliation so all other state claimants either join it or defer.
cancellationOperationsMu sync.Mutex
cancellationOperations map[string]*cancelOperation
// cancelOperations tracks cancellation intent separately from the shared
// cancelInFlight mutex. Stream and lifecycle handlers use that mutex to
// serialize their side effects, but they are not themselves cancellations;
@@ -1247,6 +1261,19 @@ func (s *Service) completeTurnForTaskSession(ctx context.Context, taskID, sessio
// their best-effort behavior; cancellation uses this checked variant because
// workflow completion must not run while the cancelled turn is still open.
func (s *Service) completeTurnForTaskSessionChecked(ctx context.Context, taskID, sessionID string) error {
return s.completeTurnForTaskSessionCheckedOwned(ctx, taskID, sessionID, "")
}
// completeTurnForTaskSessionCheckedOwned is the cancellation-specific form of
// turn settlement. When expectedTurnID is non-empty, it closes only that turn
// and fails closed if a different turn is active. This prevents a late cancel
// response from sweeping a successor turn that started after the cancelled
// turn's terminal frames were delivered.
func (s *Service) completeTurnForTaskSessionCheckedOwned(ctx context.Context, taskID, sessionID, expectedTurnID string) error {
if err := s.verifyExpectedTurnOwnership(ctx, sessionID, expectedTurnID); err != nil {
return err
}
// Foreground ownership ends with the turn, but detached background work can
// outlive it. Preserve those registrations for accounting; full cleanup
// belongs to execution/session teardown paths.
@@ -1256,6 +1283,66 @@ func (s *Service) completeTurnForTaskSessionChecked(ctx context.Context, taskID,
return nil
}
if expectedTurnID != "" {
return s.completeExpectedTurn(ctx, sessionID, expectedTurnID)
}
return s.completeAllTurns(ctx, sessionID)
}
func (s *Service) verifyExpectedTurnOwnership(ctx context.Context, sessionID, expectedTurnID string) error {
if s.turnService == nil || expectedTurnID == "" {
return nil
}
turn, err := s.turnService.GetActiveTurn(ctx, sessionID)
if err != nil {
if isNoActiveTurnError(err) {
return nil
}
return fmt.Errorf("look up captured active turn: %w", err)
}
if turn != nil && turn.ID != expectedTurnID {
return fmt.Errorf("captured cancelled turn %s was superseded by active turn %s", expectedTurnID, turn.ID)
}
return nil
}
func (s *Service) completeExpectedTurn(ctx context.Context, sessionID, expectedTurnID string) error {
turn, err := s.turnService.GetActiveTurn(ctx, sessionID)
if err != nil {
if isNoActiveTurnError(err) {
return nil
}
return fmt.Errorf("look up captured active turn: %w", err)
}
if turn == nil {
return nil
}
if turn.ID != expectedTurnID {
return fmt.Errorf("captured cancelled turn %s was superseded by active turn %s", expectedTurnID, turn.ID)
}
if err := s.turnService.CompleteTurn(ctx, expectedTurnID); err != nil {
return fmt.Errorf("complete captured turn %s: %w", expectedTurnID, err)
}
active, err := s.turnService.GetActiveTurn(ctx, sessionID)
if err != nil {
if isNoActiveTurnError(err) {
s.activeTurns.CompareAndDelete(sessionID, expectedTurnID)
return nil
}
return fmt.Errorf("verify captured turn closure: %w", err)
}
if active == nil {
s.activeTurns.CompareAndDelete(sessionID, expectedTurnID)
return nil
}
if active.ID != expectedTurnID {
return fmt.Errorf("captured cancelled turn %s was superseded by active turn %s", expectedTurnID, active.ID)
}
return fmt.Errorf("captured cancelled turn %s remains open", expectedTurnID)
}
func (s *Service) completeAllTurns(ctx context.Context, sessionID string) error {
s.activeTurns.Delete(sessionID)
const maxIterations = 16
@@ -1263,6 +1350,9 @@ func (s *Service) completeTurnForTaskSessionChecked(ctx context.Context, taskID,
for closed < maxIterations {
turn, err := s.turnService.GetActiveTurn(ctx, sessionID)
if err != nil {
if isNoActiveTurnError(err) {
return nil
}
return fmt.Errorf("look up active turn: %w", err)
}
if turn == nil {
@@ -1280,6 +1370,9 @@ func (s *Service) completeTurnForTaskSessionChecked(ctx context.Context, taskID,
// finding the session clean is a successful reconciliation, not a runaway.
turn, err := s.turnService.GetActiveTurn(ctx, sessionID)
if err != nil {
if isNoActiveTurnError(err) {
return nil
}
return fmt.Errorf("verify active turn closure: %w", err)
}
if turn != nil {
@@ -1356,6 +1449,9 @@ func (s *Service) peekActiveTurnID(ctx context.Context, sessionID string) (strin
}
turn, err := s.turnService.GetActiveTurn(ctx, sessionID)
if err != nil {
if isNoActiveTurnError(err) {
return "", nil
}
return "", err
}
if turn == nil {
File diff suppressed because it is too large Load Diff
@@ -1003,7 +1003,9 @@ func TestCancelAgent_SurvivesCallerCancellationDuringWaitingRetry(t *testing.T)
cancel: cancel,
}
require.NoError(t, svc.CancelAgent(ctx, sessionID))
err := svc.CancelAgent(ctx, sessionID)
require.ErrorIs(t, err, context.Canceled)
require.NoError(t, svc.waitForCancelInFlight(context.Background(), sessionID))
task, err := repo.GetTask(context.Background(), taskID)
require.NoError(t, err)
assert.Equal(t, "step2", task.WorkflowStepID)
@@ -1068,27 +1070,23 @@ func TestReconcileCancelledTurn_DoesNotCloseTurnWhenSessionStateWriteFails(t *te
assert.NotNil(t, activeTurn, "a failed session-state write must not close the active turn")
}
func TestCancelAgent_SurvivesCallerCancellationAfterAdmission(t *testing.T) {
func TestCancelAgent_DoesNotTransitionWhenLifecycleCancelFails(t *testing.T) {
repo := setupTestRepo(t)
taskID := "task-cancel-session-write"
sessionID := "session-cancel-session-write"
seedSession(t, repo, taskID, sessionID, "step1")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
manager := &cancelContextAgentManager{
mockAgentManager: &mockAgentManager{},
cancel: cancel,
}
ctx := context.Background()
manager := &mockAgentManager{cancelAgentErr: errors.New("cancel failed")}
svc := createTestServiceWithAgent(repo, cancelCompletionStepGetter(true, false), newMockTaskRepo(), manager)
err := svc.CancelAgent(ctx, sessionID)
require.NoError(t, err)
require.Error(t, err)
task, err := repo.GetTask(context.Background(), taskID)
require.NoError(t, err)
assert.Equal(t, "step2", task.WorkflowStepID)
assert.Equal(t, "step1", task.WorkflowStepID)
session, err := repo.GetTaskSession(context.Background(), sessionID)
require.NoError(t, err)
assert.Equal(t, models.TaskSessionStateWaitingForInput, session.State)
assert.Equal(t, models.TaskSessionStateRunning, session.State)
}
func TestCancelAgent_TerminalTransitionSkipsIntermediateReview(t *testing.T) {
@@ -1145,13 +1143,175 @@ func TestUserCancelCompletion_SilentCancelDoesNotTrigger(t *testing.T) {
assert.Equal(t, "step1", task.WorkflowStepID)
}
func TestCancelAgent_AllowsAcknowledgementStreamToDrain(t *testing.T) {
repo := setupTestRepo(t)
seedTaskAndSession(t, repo, "task-cancel-stream-drain", "session-cancel-stream-drain", models.TaskSessionStateRunning)
streamDone := make(chan struct{})
var svc *Service
agentMgr := &mockAgentManager{}
agentMgr.cancelAgentFunc = func(ctx context.Context, sessionID string) error {
go func() {
svc.handleAgentStreamEvent(ctx, &lifecycle.AgentStreamEventPayload{
TaskID: "task-cancel-stream-drain",
SessionID: sessionID,
Data: &lifecycle.AgentStreamEventData{
Type: agentEventComplete,
},
})
close(streamDone)
}()
select {
case <-streamDone:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
svc = createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
err := svc.CancelAgent(ctx, "session-cancel-stream-drain")
require.NoError(t, err)
select {
case <-streamDone:
case <-time.After(time.Second):
t.Fatal("timed out waiting for the acknowledgement stream callback")
}
}
func TestCancelAgentSilent_AllowsAcknowledgementStreamToDrain(t *testing.T) {
repo := setupTestRepo(t)
seedTaskAndSession(t, repo, "task-silent-stream-drain", "session-silent-stream-drain", models.TaskSessionStateRunning)
streamDone := make(chan struct{})
var svc *Service
agentMgr := &mockAgentManager{}
agentMgr.cancelAgentFunc = func(ctx context.Context, sessionID string) error {
go func() {
svc.handleAgentStreamEvent(ctx, &lifecycle.AgentStreamEventPayload{
TaskID: "task-silent-stream-drain",
SessionID: sessionID,
Data: &lifecycle.AgentStreamEventData{
Type: agentEventComplete,
},
})
close(streamDone)
}()
select {
case <-streamDone:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
svc = createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
lock, release := svc.acquireCancelInFlightGuard("session-silent-stream-drain")
lock.Lock()
guardLocked := true
unlockGuard := func() {
if guardLocked {
lock.Unlock()
guardLocked = false
}
}
relockGuard := func() {
if !guardLocked {
lock.Lock()
guardLocked = true
}
}
defer func() {
unlockGuard()
release()
}()
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
err := svc.cancelAgentSilentWithGuard(
ctx,
"task-silent-stream-drain",
"session-silent-stream-drain",
unlockGuard,
relockGuard,
)
require.NoError(t, err)
select {
case <-streamDone:
case <-time.After(time.Second):
t.Fatal("timed out waiting for the acknowledgement stream callback")
}
}
func TestCancelAgent_DoesNotReconcileSuccessorTurn(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedTaskAndSession(t, repo, "task-cancel-successor", "session-cancel-successor", models.TaskSessionStateRunning)
var svc *Service
var successor *models.Turn
agentMgr := &mockAgentManager{}
agentMgr.cancelAgentFunc = func(ctx context.Context, sessionID string) error {
var err error
successor, err = svc.turnService.StartTurn(ctx, sessionID)
return err
}
svc = createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
svc.turnService = &repoTurnService{repo: repo}
captured, err := svc.turnService.StartTurn(ctx, "session-cancel-successor")
require.NoError(t, err)
err = svc.CancelAgent(ctx, "session-cancel-successor")
require.Error(t, err)
assert.Contains(t, err.Error(), "superseded")
require.NotNil(t, successor)
active, err := svc.turnService.GetActiveTurn(ctx, "session-cancel-successor")
require.NoError(t, err)
require.NotNil(t, active)
assert.Equal(t, successor.ID, active.ID)
assert.NotEqual(t, captured.ID, active.ID)
session, err := repo.GetTaskSession(ctx, "session-cancel-successor")
require.NoError(t, err)
assert.Equal(t, models.TaskSessionStateRunning, session.State)
}
func TestCancelAgent_SurvivesCallerCancellationAfterAdmission(t *testing.T) {
repo := setupTestRepo(t)
taskID := "task-cancel-caller-disconnect"
sessionID := "session-cancel-caller-disconnect"
seedSession(t, repo, taskID, sessionID, "step1")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
manager := &cancelContextAgentManager{
mockAgentManager: &mockAgentManager{},
cancel: cancel,
}
svc := createTestServiceWithAgent(repo, cancelCompletionStepGetter(true, false), newMockTaskRepo(), manager)
err := svc.CancelAgent(ctx, sessionID)
require.ErrorIs(t, err, context.Canceled)
require.NoError(t, svc.waitForCancelInFlight(context.Background(), sessionID))
task, err := repo.GetTask(context.Background(), taskID)
require.NoError(t, err)
assert.Equal(t, "step2", task.WorkflowStepID)
session, err := repo.GetTaskSession(context.Background(), sessionID)
require.NoError(t, err)
assert.Equal(t, models.TaskSessionStateWaitingForInput, session.State)
}
// TestCancelAgent_DeduplicatesConcurrentCalls covers the impatient-user case:
// the UI's cancel button has no in-flight disable, so users click it multiple
// times while the agent is still tearing down a slow turn (e.g. a Claude
// Monitor tool). Without dedupe each click reaches the lifecycle layer and
// emits its own "Turn cancelled by user" message; phantom turns are also
// lazily started to host those messages. We assert that only one cancel makes
// it through to agentManager.CancelAgent while one is already in flight.
// it through to agentManager.CancelAgent while the other callers join its
// result.
func TestCancelAgent_DeduplicatesConcurrentCalls(t *testing.T) {
repo := setupTestRepo(t)
agentMgr := &mockAgentManager{
@@ -1175,24 +1335,30 @@ func TestCancelAgent_DeduplicatesConcurrentCalls(t *testing.T) {
// don't depend on real subprocess timing.
<-agentMgr.cancelAgentEntered
// Fire several duplicates while the first is still parked. Each must be
// short-circuited by the dedupe guard and return immediately.
// Fire several duplicates while the first is still parked. Each joins the
// owner operation and waits for its result rather than invoking the manager.
const duplicates = 5
duplicateDone := make(chan error, duplicates)
for i := 0; i < duplicates; i++ {
if err := svc.CancelAgent(context.Background(), "session1"); err != nil {
t.Fatalf("duplicate cancel %d returned error: %v", i, err)
}
go func() {
duplicateDone <- svc.CancelAgent(context.Background(), "session1")
}()
}
if got := agentMgr.cancelAgentCalls.Load(); got != 1 {
t.Fatalf("expected exactly 1 agentManager.CancelAgent call while first is in flight, got %d", got)
}
// Release the first call. After it returns, the guard clears and a fresh
// cancel is allowed through.
// Release the first call. The owner and all joiners observe the same result;
// after the operation clears, a fresh cancel is allowed through.
close(agentMgr.cancelAgentBlock)
if err := <-firstDone; err != nil {
t.Fatalf("first CancelAgent returned error: %v", err)
}
for i := 0; i < duplicates; i++ {
if err := <-duplicateDone; err != nil {
t.Fatalf("duplicate cancel %d returned error: %v", i, err)
}
}
agentMgr.cancelAgentBlock = nil // unblock subsequent calls
if err := svc.CancelAgent(context.Background(), "session1"); err != nil {
@@ -1306,7 +1472,8 @@ func TestCancelAgent_SurvivesCallerCancellation(t *testing.T) {
cancel()
close(agentMgr.cancelAgentBlock)
require.NoError(t, <-done)
require.ErrorIs(t, <-done, context.Canceled)
require.NoError(t, svc.waitForCancelInFlight(context.Background(), "session1"))
}
func cancellationPendingEvents(recorded *recordingEventBus) []recordedEvent {
@@ -1320,6 +1487,262 @@ func cancellationPendingEvents(recorded *recordingEventBus) []recordedEvent {
return filtered
}
func TestCancellationSourcesShareLifecycleOwnership(t *testing.T) {
for _, tc := range []struct {
name string
start func(*Service, chan error)
}{
{
name: "explicit and silent",
start: func(svc *Service, done chan error) {
go func() { done <- svc.CancelAgent(context.Background(), "session1") }()
go func() { done <- svc.cancelAgentSilent(context.Background(), "task1", "session1") }()
},
},
{
name: "silent and silent",
start: func(svc *Service, done chan error) {
go func() { done <- svc.cancelAgentSilent(context.Background(), "task1", "session1") }()
go func() { done <- svc.cancelAgentSilent(context.Background(), "task1", "session1") }()
},
},
} {
t.Run(tc.name, func(t *testing.T) {
repo := setupTestRepo(t)
seedTaskAndSession(t, repo, "task1", "session1", models.TaskSessionStateRunning)
agentMgr := &mockAgentManager{
cancelAgentBlock: make(chan struct{}),
cancelAgentEntered: make(chan struct{}, 2),
}
svc := createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
done := make(chan error, 2)
tc.start(svc, done)
select {
case <-agentMgr.cancelAgentEntered:
case <-time.After(time.Second):
t.Fatal("timed out waiting for the cancellation owner")
}
select {
case <-agentMgr.cancelAgentEntered:
t.Fatal("a second cancellation source invoked the lifecycle manager")
case <-time.After(100 * time.Millisecond):
}
close(agentMgr.cancelAgentBlock)
for i := 0; i < 2; i++ {
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("timed out waiting for cancellation source")
}
}
assert.Equal(t, int32(1), agentMgr.cancelAgentCalls.Load())
})
}
}
func TestCancelAgent_JoinedSilentCancellationRunsExplicitReconciliation(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedTaskAndSession(t, repo, "task1", "session1", models.TaskSessionStateRunning)
agentMgr := &mockAgentManager{
cancelAgentBlock: make(chan struct{}),
cancelAgentEntered: make(chan struct{}, 1),
}
svc := createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
svc.turnService = &repoTurnService{repo: repo}
messages := &mockMessageCreator{}
svc.messageCreator = messages
_, err := svc.turnService.StartTurn(ctx, "session1")
require.NoError(t, err)
silentDone := make(chan error, 1)
go func() {
silentDone <- svc.cancelAgentSilent(ctx, "task1", "session1")
}()
select {
case <-agentMgr.cancelAgentEntered:
case <-time.After(time.Second):
t.Fatal("timed out waiting for silent cancellation owner")
}
// The explicit user request joins the silent owner. It must not call the
// lifecycle manager again, but it still owns its visible cancel message and
// other explicit reconciliation once the shared operation settles.
explicitDone := make(chan error, 1)
go func() {
explicitDone <- svc.CancelAgent(ctx, "session1")
}()
waitForCancellationJoin(t, svc, "session1")
close(agentMgr.cancelAgentBlock)
select {
case err := <-silentDone:
require.NoError(t, err)
case <-time.After(time.Second):
t.Fatal("silent cancellation did not finish")
}
select {
case err := <-explicitDone:
require.NoError(t, err)
case <-time.After(time.Second):
t.Fatal("joined explicit cancellation did not finish")
}
assert.Equal(t, int32(1), agentMgr.cancelAgentCalls.Load())
messages.mu.Lock()
defer messages.mu.Unlock()
if len(messages.sessionMessages) != 1 || messages.sessionMessages[0].content != "Turn cancelled by user" {
t.Fatalf("expected one explicit cancellation message after joining silent owner, got %+v", messages.sessionMessages)
}
}
func TestCancellationStreamAdmissionRejectsStaleIdentity(t *testing.T) {
svc := &Service{logger: testLogger()}
operation, owner := svc.claimCancellation("session1", cancellationKindExplicit)
require.True(t, owner)
svc.setCancellationIdentity("session1", operation, cancellationIdentity{
executionID: "execution-a",
promptGeneration: 7,
turnID: "turn-a",
})
assert.False(t, svc.cancellationOwnsStreamEvent("session1", "execution-b", 7))
assert.False(t, svc.cancellationOwnsStreamEvent("session1", "execution-a", 8))
assert.True(t, svc.cancellationOwnsStreamEvent("session1", "execution-a", 7))
svc.handleAgentStreamEvent(context.Background(), &lifecycle.AgentStreamEventPayload{
TaskID: "task1",
SessionID: "session1",
ExecutionID: "execution-b",
Data: &lifecycle.AgentStreamEventData{
Type: "message_streaming",
PromptGeneration: 7,
},
})
svc.finishCancellation("session1", operation, nil)
assert.True(t, svc.cancellationOwnsStreamEvent("session1", "execution-b", 8))
}
func TestCancelAgent_OwnerDisconnectDoesNotAbortJoinedOperation(t *testing.T) {
repo := setupTestRepo(t)
seedTaskAndSession(t, repo, "task-owner-disconnect", "session-owner-disconnect", models.TaskSessionStateRunning)
agentMgr := &mockAgentManager{
cancelAgentBlock: make(chan struct{}),
cancelAgentEntered: make(chan struct{}, 1),
}
svc := createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
ownerCtx, ownerCancel := context.WithCancel(context.Background())
ownerDone := make(chan error, 1)
go func() { ownerDone <- svc.CancelAgent(ownerCtx, "session-owner-disconnect") }()
select {
case <-agentMgr.cancelAgentEntered:
case <-time.After(time.Second):
t.Fatal("timed out waiting for owner cancellation")
}
ownerCancel()
select {
case err := <-ownerDone:
require.ErrorIs(t, err, context.Canceled)
case <-time.After(time.Second):
t.Fatal("owner continued waiting on a disconnected request")
}
joinedDone := make(chan error, 1)
go func() { joinedDone <- svc.CancelAgent(context.Background(), "session-owner-disconnect") }()
waitForCancellationJoin(t, svc, "session-owner-disconnect")
close(agentMgr.cancelAgentBlock)
select {
case err := <-joinedDone:
require.NoError(t, err)
case <-time.After(time.Second):
t.Fatal("joined cancellation did not receive the service-owned result")
}
assert.Equal(t, int32(1), agentMgr.cancelAgentCalls.Load())
}
func TestCancelAgent_DefersLifecycleCompletionDuringCancellation(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
taskID, sessionID := "task-cancel-completed-event", "session-cancel-completed-event"
seedSession(t, repo, taskID, sessionID, "step1")
steps := cancelCompletionStepGetter(true, false)
steps.steps["step2"].Events.OnTurnComplete = []wfmodels.OnTurnCompleteAction{{Type: wfmodels.OnTurnCompleteMoveToNext}}
var svc *Service
completedDone := make(chan struct{})
agentMgr := &mockAgentManager{}
agentMgr.cancelAgentFunc = func(eventCtx context.Context, _ string) error {
go func() {
svc.handleAgentCompleted(eventCtx, watcher.AgentEventData{
TaskID: taskID,
SessionID: sessionID,
AgentExecutionID: "execution-cancelled",
})
close(completedDone)
}()
select {
case <-completedDone:
case <-eventCtx.Done():
return eventCtx.Err()
}
return nil
}
svc = createEngineService(t, repo, steps, agentMgr)
svc.scheduler = scheduler.NewScheduler(
queue.NewTaskQueue(10),
svc.executor,
svc.taskRepo,
testLogger(),
scheduler.SchedulerConfig{},
)
require.NoError(t, svc.CancelAgent(ctx, sessionID))
select {
case <-completedDone:
case <-time.After(time.Second):
t.Fatal("timed out waiting for the terminal lifecycle event")
}
task, err := repo.GetTask(ctx, taskID)
require.NoError(t, err)
assert.Equal(t, "step2", task.WorkflowStepID, "cancelled lifecycle completion must not advance workflow before cancellation reconciliation")
}
func TestCancelAgentSilent_DoesNotCloseSuccessorTurn(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
taskID, sessionID := "task-silent-successor", "session-silent-successor"
seedTaskAndSession(t, repo, taskID, sessionID, models.TaskSessionStateRunning)
var svc *Service
var successor *models.Turn
agentMgr := &mockAgentManager{}
agentMgr.cancelAgentFunc = func(cancelCtx context.Context, _ string) error {
var err error
successor, err = svc.turnService.StartTurn(cancelCtx, sessionID)
return err
}
svc = createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
svc.turnService = &repoTurnService{repo: repo}
original, err := svc.turnService.StartTurn(ctx, sessionID)
require.NoError(t, err)
err = svc.cancelAgentSilent(ctx, taskID, sessionID)
require.Error(t, err)
assert.Contains(t, err.Error(), "superseded")
require.NotNil(t, successor)
active, err := svc.turnService.GetActiveTurn(ctx, sessionID)
require.NoError(t, err)
require.NotNil(t, active)
assert.Equal(t, successor.ID, active.ID)
assert.NotEqual(t, original.ID, active.ID)
session, err := repo.GetTaskSession(ctx, sessionID)
require.NoError(t, err)
assert.Equal(t, models.TaskSessionStateRunning, session.State)
}
// TestCancelAgent_TaskStateReconcile ensures cancel lands actively-working
// kanban tasks in REVIEW (treated as finished work the user may want to
// review). Office tasks and tasks already out of IN_PROGRESS / SCHEDULING
@@ -1548,6 +1971,69 @@ func TestQueueAndInterruptForPeerMessage_DeliversQueuedMessageWithoutUserCancelS
}
}
// TestQueueAndInterruptForPeerMessage_LeavesMessageQueuedDuringUserCancel
// covers the cross-source ownership boundary: a peer steering request that
// arrives after the user cancel has claimed the session must not join the
// explicit operation and dispatch its message after cancellation settles.
// The message remains queued for a later, explicit drain.
func TestQueueAndInterruptForPeerMessage_LeavesMessageQueuedDuringUserCancel(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedTaskAndSession(t, repo, "task1", "session1", models.TaskSessionStateRunning)
agentMgr := &mockAgentManager{
cancelAgentBlock: make(chan struct{}),
cancelAgentEntered: make(chan struct{}, 1),
}
svc := createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentMgr)
cancelDone := make(chan error, 1)
go func() { cancelDone <- svc.CancelAgent(ctx, "session1") }()
select {
case <-agentMgr.cancelAgentEntered:
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for explicit cancellation to enter lifecycle manager")
}
interruptDone := make(chan struct{})
var queued *messagequeue.QueuedMessage
var dispatched bool
var interruptErr error
go func() {
queued, dispatched, interruptErr = svc.QueueAndInterruptForPeerMessage(
ctx, "task1", "session1", "peer message during cancel", nil,
)
close(interruptDone)
}()
select {
case <-interruptDone:
t.Fatal("peer queue operation returned before the user cancellation settled")
case <-time.After(100 * time.Millisecond):
}
close(agentMgr.cancelAgentBlock)
select {
case err := <-cancelDone:
require.NoError(t, err)
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for explicit cancellation")
}
select {
case <-interruptDone:
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for peer queue operation")
}
require.NoError(t, interruptErr)
require.NotNil(t, queued)
assert.False(t, dispatched)
status := svc.messageQueue.GetStatus(ctx, "session1")
require.Equal(t, 1, status.Count)
assert.Equal(t, queued.ID, status.Entries[0].ID)
assert.Equal(t, int32(1), agentMgr.cancelAgentCalls.Load())
}
// TestQueueAndInterruptForPeerMessage_CancelFailurePropagatesAndKeepsMessageQueued
// pins the failure contract: a genuine cancel error (not the tolerated
// ErrNoExecutionForSession / ErrCancelEscalated sentinels cancelAgentSilent
@@ -1644,14 +2130,12 @@ func TestQueueAndInterruptForPeerMessage_DeliversTargetedEntryAheadOfOlderQueued
}
// TestQueueAndInterruptForPeerMessage_WaitsForConcurrentHolderThenDelivers
// pins the mutual-exclusion contract: when another caller already holds the
// session's cancelInFlight lock (mid-cancel, via a real concurrent
// pins the shared-ownership contract: when another caller already owns the
// session's cancellation (mid-cancel, via a real concurrent
// QueueAndInterruptForPeerMessage call staged with the mock's
// cancelAgentBlock/cancelAgentEntered hooks — no sleeps), a second call must
// block on that same lock and wait for it to free up rather than falling
// back to an unguarded "insert and hope" — see QueueAndInterruptForPeerMessage's
// doc comment for why a busy-skip fallback would risk orphaning the second
// call's message with no guaranteed future drain trigger.
// cancelAgentBlock/cancelAgentEntered hooks), a second call must join that
// cancellation and register its own targeted dispatch. The owner invokes the
// lifecycle manager exactly once; both source-specific actions run after it.
func TestQueueAndInterruptForPeerMessage_WaitsForConcurrentHolderThenDelivers(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
@@ -1669,8 +2153,8 @@ func TestQueueAndInterruptForPeerMessage_WaitsForConcurrentHolderThenDelivers(t
seedTaskAndSession(t, repo, "task1", "session1", models.TaskSessionStateRunning)
seedExecutorRunning(t, repo, "session1", "task1", "exec-1")
// First call: acquires the lock, queues its message, and blocks inside
// CancelAgent (holding the lock the whole time).
// First call queues its message, claims cancellation ownership, releases
// the guard around the lifecycle call, and blocks inside CancelAgent.
firstDone := make(chan struct{})
go func() {
_, _, _ = svc.QueueAndInterruptForPeerMessage(ctx, "task1", "session1", "first parent message", nil)
@@ -1683,7 +2167,7 @@ func TestQueueAndInterruptForPeerMessage_WaitsForConcurrentHolderThenDelivers(t
t.Fatal("timed out waiting for the first call to enter CancelAgent")
}
// Second call starts while the first still holds the lock mid-cancel.
// Second call starts while the first owns the cancellation mid-lifecycle.
secondDone := make(chan struct{})
var queued *messagequeue.QueuedMessage
var dispatched bool
@@ -1693,17 +2177,20 @@ func TestQueueAndInterruptForPeerMessage_WaitsForConcurrentHolderThenDelivers(t
close(secondDone)
}()
// The second call must not have completed yet — it has to be blocked
// on the lock, not working around it with an unguarded insert.
// Wait until the second call has joined the first operation before that
// operation is released.
waitForCancellationJoin(t, svc, "session1")
// A joined caller must still wait for the owner to settle cancellation and
// run its registered action.
select {
case <-secondDone:
t.Fatal("second QueueAndInterruptForPeerMessage returned before the first call released the lock")
t.Fatal("second QueueAndInterruptForPeerMessage returned before the shared cancellation settled")
default:
}
// Release the first call's cancel; it finishes and releases the lock,
// letting the second call proceed (its own CancelAgent no longer
// blocks either, since cancelAgentBlock is now closed).
// Release the shared lifecycle call. The coordinator then runs both
// targeted dispatch actions under the per-session guard.
close(agentMgr.cancelAgentBlock)
select {
@@ -1726,8 +2213,8 @@ func TestQueueAndInterruptForPeerMessage_WaitsForConcurrentHolderThenDelivers(t
t.Fatal("expected the second call to deliver its own message once the lock became available")
}
if got := agentMgr.cancelAgentCalls.Load(); got != 2 {
t.Fatalf("expected exactly 2 agent cancel calls (one per message), got %d", got)
if got := agentMgr.cancelAgentCalls.Load(); got != 1 {
t.Fatalf("expected exactly 1 lifecycle cancel call for both peer messages, got %d", got)
}
// Join whatever executeQueuedMessage did for the second message before
@@ -1751,6 +2238,19 @@ func TestQueueAndInterruptForPeerMessage_WaitsForConcurrentHolderThenDelivers(t
}, 2*time.Second, 10*time.Millisecond, "expected the second message to either be dispatched or settle back into the queue via requeueMessage")
}
func waitForCancellationJoin(t *testing.T, svc *Service, sessionID string) {
t.Helper()
svc.cancellationOperationsMu.Lock()
operation := svc.cancellationOperations[sessionID]
svc.cancellationOperationsMu.Unlock()
require.NotNil(t, operation, "expected an in-flight cancellation for %s", sessionID)
select {
case <-operation.joined:
case <-time.After(time.Second):
t.Fatalf("timed out waiting for a cancellation join on %s", sessionID)
}
}
// erroringTakeByIDRepository wraps a messagequeue.Repository and returns a
// configured error from TakeByID, letting orchestrator-level tests exercise
// QueueAndInterruptForPeerMessage's error-propagation path without needing a
@@ -2702,7 +3202,7 @@ func TestCancelAgent_RacesHandleAgentReady_QueuedMessageStaysParked(t *testing.T
}
select {
case <-readyDone:
t.Fatal("handleAgentReady returned before CancelAgent released the guard — it must block, not work around it")
t.Fatal("handleAgentReady returned before CancelAgent released the cancellation marker")
case <-time.After(100 * time.Millisecond):
}
@@ -2714,11 +3214,10 @@ func TestCancelAgent_RacesHandleAgentReady_QueuedMessageStaysParked(t *testing.T
t.Fatal("timed out waiting for CancelAgent to finish")
}
require.NoError(t, cancelErr)
select {
case <-readyDone:
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for handleAgentReady to finish once the guard was released")
t.Fatal("timed out waiting for handleAgentReady after CancelAgent finished")
}
status := svc.messageQueue.GetStatus(ctx, "session1")
@@ -260,6 +260,7 @@ type SessionWorktreeRepository interface {
// TaskResourceCleanupRepository persists restart-safe task lifecycle cleanup.
type TaskResourceCleanupRepository interface {
CreateTaskResourceCleanupJob(ctx context.Context, job *models.TaskResourceCleanupJob) error
HasActiveTaskResourceCleanupJob(ctx context.Context, taskID string) (bool, error)
GetTaskResourceCleanupJob(ctx context.Context, id string) (*models.TaskResourceCleanupJob, error)
GetTaskResourceCleanupJobByOperationID(ctx context.Context, operationID string) (*models.TaskResourceCleanupJob, error)
ListPreparedTaskResourceCleanupJobs(ctx context.Context) ([]*models.TaskResourceCleanupJob, error)
@@ -36,6 +36,25 @@ func (r *Repository) CreateTaskResourceCleanupJob(ctx context.Context, job *mode
return err
}
// HasActiveTaskResourceCleanupJob reports whether teardown has been admitted
// for a task. The prepared state is included because the cleanup intent is
// persisted before task deletion and before the worker is allowed to run.
func (r *Repository) HasActiveTaskResourceCleanupJob(ctx context.Context, taskID string) (bool, error) {
var active bool
err := r.ro.QueryRowContext(ctx, r.ro.Rebind(`
SELECT EXISTS (
SELECT 1 FROM task_resource_cleanup_jobs
WHERE task_id = ? AND state IN (?, ?, ?, ?)
)
`), taskID,
models.TaskResourceCleanupStatePrepared,
models.TaskResourceCleanupStatePending,
models.TaskResourceCleanupStateRunning,
models.TaskResourceCleanupStateRetryWait,
).Scan(&active)
return active, err
}
func (r *Repository) GetTaskResourceCleanupJobByOperationID(ctx context.Context, operationID string) (*models.TaskResourceCleanupJob, error) {
row := r.ro.QueryRowContext(ctx, r.ro.Rebind(`
SELECT `+taskResourceCleanupColumns+`
@@ -95,6 +95,42 @@ func TestListPreparedTaskResourceCleanupJobsExcludesRunnableStates(t *testing.T)
}
}
func TestHasActiveTaskResourceCleanupJobTracksAdmissionStates(t *testing.T) {
ctx := context.Background()
repo := newRepoForHealTests(t)
states := []struct {
state models.TaskResourceCleanupState
active bool
}{
{models.TaskResourceCleanupStatePrepared, true},
{models.TaskResourceCleanupStatePending, true},
{models.TaskResourceCleanupStateRunning, true},
{models.TaskResourceCleanupStateRetryWait, true},
{models.TaskResourceCleanupStateSucceeded, false},
{models.TaskResourceCleanupStateFailed, false},
{models.TaskResourceCleanupStateCancelled, false},
}
for _, tt := range states {
t.Run(string(tt.state), func(t *testing.T) {
taskID := "task-" + string(tt.state)
job := &models.TaskResourceCleanupJob{
ID: "job-" + string(tt.state), OperationID: "delete:" + taskID, TaskID: taskID,
Trigger: models.TaskResourceCleanupTriggerDelete, State: tt.state, ResourceSnapshot: `{}`,
}
if err := repo.CreateTaskResourceCleanupJob(ctx, job); err != nil {
t.Fatalf("CreateTaskResourceCleanupJob: %v", err)
}
active, err := repo.HasActiveTaskResourceCleanupJob(ctx, taskID)
if err != nil {
t.Fatalf("HasActiveTaskResourceCleanupJob: %v", err)
}
if active != tt.active {
t.Fatalf("active = %v, want %v", active, tt.active)
}
})
}
}
func TestTaskResourceCleanupJobStaleClaimCannotOverwriteCancellation(t *testing.T) {
ctx := context.Background()
repo := newRepoForHealTests(t)
@@ -21,6 +21,8 @@ const (
taskResourceCleanupMaxAttempts = 8
)
const taskResourceCleanupMutationOutcomeUnknown = "task mutation outcome requires reconciliation"
var taskResourceCleanupRetryDelays = []time.Duration{
time.Minute,
5 * time.Minute,
@@ -250,7 +252,11 @@ func (s *Service) reconcilePreparedTaskResourceCleanupJobs(
continue
}
if !committed {
if cancelUncommittedBefore == nil || !job.CreatedAt.Before(*cancelUncommittedBefore) {
shouldCancel := job.LastError == taskResourceCleanupMutationOutcomeUnknown
if cancelUncommittedBefore != nil && job.CreatedAt.Before(*cancelUncommittedBefore) {
shouldCancel = true
}
if !shouldCancel {
continue
}
if err := s.resourceCleanups.CompleteTaskResourceCleanupJob(
@@ -466,12 +472,35 @@ func (s *Service) cancelIfTaskUnarchived(ctx context.Context, job *models.TaskRe
return false, nil
}
func (s *Service) cancelTaskResourceCleanupJob(ctx context.Context, job *models.TaskResourceCleanupJob) {
func (s *Service) resolveTaskResourceCleanupAfterMutationError(ctx context.Context, job *models.TaskResourceCleanupJob) {
if job == nil || s.resourceCleanups == nil {
return
}
transitionCtx, cancel := detachedCleanupTransitionContext(ctx)
defer cancel()
committed, err := s.preparedTaskCleanupMutationCommitted(transitionCtx, job)
if err != nil {
if markErr := s.resourceCleanups.CompleteTaskResourceCleanupJob(
transitionCtx, job.ID, models.TaskResourceCleanupStatePrepared,
taskResourceCleanupMutationOutcomeUnknown, nil,
); markErr != nil {
s.logger.Warn("mark ambiguous task resource cleanup outcome failed",
zap.String("job_id", job.ID), zap.String("task_id", job.TaskID), zap.Error(markErr))
}
s.startTaskResourceCleanup(job)
s.logger.Warn("task resource cleanup mutation outcome is ambiguous; retaining prepared intent",
zap.String("job_id", job.ID), zap.String("task_id", job.TaskID), zap.Error(err))
return
}
if committed {
if err := s.activatePreparedTaskResourceCleanupJob(transitionCtx, job); err != nil {
s.logger.Warn("activate cleanup after committed task mutation error failed",
zap.String("job_id", job.ID), zap.String("task_id", job.TaskID), zap.Error(err))
}
return
}
if err := s.resourceCleanups.CompleteTaskResourceCleanupJob(
ctx, job.ID, models.TaskResourceCleanupStateCancelled, "", nil,
transitionCtx, job.ID, models.TaskResourceCleanupStateCancelled, "", nil,
); err != nil {
s.logger.Warn("cancel task resource cleanup job failed",
zap.String("job_id", job.ID), zap.String("task_id", job.TaskID), zap.Error(err))
@@ -103,6 +103,98 @@ type blockingResumeCleanupRepository struct {
release chan struct{}
}
type commitThenErrorTaskRepository struct {
repository.TaskRepository
err error
}
func (r *commitThenErrorTaskRepository) DeleteTask(ctx context.Context, id string) error {
if err := r.TaskRepository.DeleteTask(ctx, id); err != nil {
return err
}
return r.err
}
func (r *commitThenErrorTaskRepository) ArchiveTask(ctx context.Context, id string) error {
if err := r.TaskRepository.ArchiveTask(ctx, id); err != nil {
return err
}
return r.err
}
func TestResolveTaskResourceCleanupAfterMutationErrorSurvivesCallerCancellation(t *testing.T) {
taskSvc, repo := setupOfficeTest(t)
seedCleanupTaskAndSession(t, repo, "task-cancel-detached", "session-cancel-detached")
job := &models.TaskResourceCleanupJob{
ID: "job-cancel-detached", OperationID: "delete:cancel-detached", TaskID: "task-cancel-detached",
Trigger: models.TaskResourceCleanupTriggerDelete, State: models.TaskResourceCleanupStatePrepared,
ResourceSnapshot: `{}`,
}
if err := repo.CreateTaskResourceCleanupJob(context.Background(), job); err != nil {
t.Fatalf("CreateTaskResourceCleanupJob: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
taskSvc.resolveTaskResourceCleanupAfterMutationError(ctx, job)
got, err := repo.GetTaskResourceCleanupJob(context.Background(), job.ID)
if err != nil {
t.Fatalf("GetTaskResourceCleanupJob: %v", err)
}
if got.State != models.TaskResourceCleanupStateCancelled {
t.Fatalf("cleanup state = %q, want %q", got.State, models.TaskResourceCleanupStateCancelled)
}
}
func TestTaskMutationCommitThenErrorKeepsCleanupRunnable(t *testing.T) {
for _, operation := range []string{"delete", "archive"} {
t.Run(operation, func(t *testing.T) {
taskSvc, _, repo := createTestService(t)
taskSvc.setCleanupDoneForTestHook(make(chan struct{}, 1))
taskID := "task-commit-then-error-" + operation
seedCleanupTaskAndSession(t, repo, taskID, "session-commit-then-error-"+operation)
commitErr := errors.New("transport lost after commit")
taskSvc.tasks = &commitThenErrorTaskRepository{TaskRepository: repo, err: commitErr}
var err error
if operation == "delete" {
err = taskSvc.DeleteTask(context.Background(), taskID)
} else {
err = taskSvc.ArchiveTask(context.Background(), taskID)
}
if !errors.Is(err, commitErr) {
t.Fatalf("mutation error = %v, want %v", err, commitErr)
}
// Activation starts the cleanup worker immediately, so there is no
// deterministic window in which the durable row must still be pending.
// Wait for the worker and assert the end-to-end invariant instead: a
// mutation that committed before returning an error remains runnable.
waitForCleanupDone(t, taskSvc)
var state models.TaskResourceCleanupState
if err := repo.DB().QueryRowContext(context.Background(), `
SELECT state FROM task_resource_cleanup_jobs WHERE task_id = ?
`, taskID).Scan(&state); err != nil {
t.Fatalf("load cleanup state: %v", err)
}
if state != models.TaskResourceCleanupStateSucceeded {
t.Fatalf("cleanup state = %q, want succeeded", state)
}
if operation == "delete" {
if task, getErr := repo.GetTask(context.Background(), taskID); getErr == nil || task != nil {
t.Fatalf("delete did not commit: task=%#v err=%v", task, getErr)
}
} else {
task, getErr := repo.GetTask(context.Background(), taskID)
if getErr != nil || task.ArchivedAt == nil {
t.Fatalf("archive did not commit: task=%#v err=%v", task, getErr)
}
}
})
}
}
func (r *blockingResumeCleanupRepository) ResetRunningTaskResourceCleanupJobs(context.Context) error {
close(r.entered)
<-r.release
@@ -1563,7 +1563,7 @@ func (s *Service) ArchiveTask(ctx context.Context, id string) error {
// 3. Set archived_at in DB
if err := s.tasks.ArchiveTask(ctx, id); err != nil {
s.cancelTaskResourceCleanupJob(ctx, cleanupJob)
s.resolveTaskResourceCleanupAfterMutationError(ctx, cleanupJob)
return err
}
@@ -1781,12 +1781,12 @@ func (s *Service) deleteTaskWithReasonAndDBDelete(
// 4. Delete from DB (sync, fast)
deleted, err := deleteFromDB(ctx, id)
if err != nil {
s.cancelTaskResourceCleanupJob(ctx, cleanupJob)
s.resolveTaskResourceCleanupAfterMutationError(ctx, cleanupJob)
s.logger.Error("failed to delete task", zap.String("task_id", id), zap.Error(err))
return false, err
}
if !deleted {
s.cancelTaskResourceCleanupJob(ctx, cleanupJob)
s.resolveTaskResourceCleanupAfterMutationError(ctx, cleanupJob)
return false, nil
}
@@ -172,7 +172,16 @@ describe("TokenUsageDisplay context source", () => {
const { getByText, getByLabelText } = render(<TokenUsageDisplay sessionId="sess-1" />);
expect(getByText("API")).toBeDefined();
expect(getByLabelText("About context window source")).toBeDefined();
const helpButton = getByLabelText("About context window source");
const helpId = helpButton.getAttribute("aria-describedby");
if (!helpId) throw new Error("Expected source help to be described");
const help = document.getElementById(helpId);
if (!help) throw new Error("Expected source help element");
fireEvent.click(helpButton);
expect(help.className).toContain("opacity-100");
fireEvent.click(helpButton);
expect(help.className).toContain("opacity-0");
expect(getByText(/model's advertised maximum from the catalogue/i)).toBeDefined();
});
});
@@ -122,6 +122,9 @@ function ContextWindowRing({ usagePercent }: { usagePercent: number }) {
function ContextWindowSource({ source }: { source: "acp" | "api" | undefined }) {
const helpId = useId();
const [helpOpen, setHelpOpen] = useState(false);
const [touchMode, setTouchMode] = useState(false);
const pointerDownRef = useRef(false);
if (!source) return null;
const description =
@@ -137,14 +140,37 @@ function ContextWindowSource({ source }: { source: "acp" | "api" | undefined })
type="button"
aria-label="About context window source"
aria-describedby={helpId}
aria-expanded={helpOpen}
className="inline-flex size-6 cursor-help items-center justify-center text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring sm:size-4"
onPointerDown={(event) => {
pointerDownRef.current = true;
if (event.pointerType !== "touch") setTouchMode(false);
}}
onTouchStart={() => {
setTouchMode(true);
}}
onFocus={() => {
if (!pointerDownRef.current) setHelpOpen(true);
}}
onBlur={() => {
pointerDownRef.current = false;
setHelpOpen(false);
}}
onClick={() => {
pointerDownRef.current = false;
setHelpOpen((open) => !open);
}}
>
<IconInfoCircle className="h-3 w-3" />
</button>
<span
id={helpId}
role="tooltip"
className="pointer-events-none absolute right-0 bottom-[calc(100%+0.375rem)] z-10 w-60 rounded-md border border-border bg-popover px-3 py-1.5 text-xs text-popover-foreground opacity-0 shadow-sm transition-opacity group-hover:opacity-100 group-focus-within:opacity-100"
className={cn(
"pointer-events-none absolute right-0 bottom-[calc(100%+0.375rem)] z-10 w-60 rounded-md border border-border bg-popover px-3 py-1.5 text-xs text-popover-foreground opacity-0 shadow-sm transition-opacity",
!touchMode && "group-hover:opacity-100",
helpOpen && "opacity-100",
)}
>
{description}
</span>
@@ -50,6 +50,7 @@ const reference: EntityReference = {
url: "https://github.com/acme/repo/issues/42",
scope: "acme/repo",
};
const REFERENCE_MARKDOWN = "[#acme/repo#42](https://github.com/acme/repo/issues/42)";
function deferred<T>() {
let resolve!: (value: T) => void;
@@ -106,7 +107,7 @@ describe("useChatInputState", () => {
const { result } = renderInputState(onSubmit);
act(() => {
result.current.handleChange("[#acme/repo#42](https://github.com/acme/repo/issues/42)");
result.current.handleChange(REFERENCE_MARKDOWN);
attachInputHandle(result.current.inputRef, vi.fn(), [reference]);
});
await waitFor(() => expect(result.current.value).toContain("acme/repo#42"));
@@ -117,7 +118,7 @@ describe("useChatInputState", () => {
await waitFor(() =>
expect(onSubmit).toHaveBeenCalledWith({
message: "[#acme/repo#42](https://github.com/acme/repo/issues/42)",
message: REFERENCE_MARKDOWN,
entityReferences: [reference],
}),
);
@@ -185,6 +186,24 @@ describe("useChatInputState", () => {
});
});
describe("useChatInputState immediate submission", () => {
it("submits a structured reference immediately after the editor change", () => {
const onSubmit = vi.fn<(...args: Parameters<SubmitHandler>) => ReturnType<SubmitHandler>>();
const { result } = renderInputState(onSubmit);
act(() => {
result.current.handleChange(REFERENCE_MARKDOWN);
attachInputHandle(result.current.inputRef, vi.fn(), [reference]);
result.current.handleSubmit(vi.fn());
});
expect(onSubmit).toHaveBeenCalledWith({
message: REFERENCE_MARKDOWN,
entityReferences: [reference],
});
});
});
describe("useChatInputState attachment feedback", () => {
it("warns when a batch exceeds the maximum number of files", async () => {
const { result } = renderInputState(vi.fn());
@@ -351,6 +351,10 @@ export function useChatInputState({
const handleChange = useCallback(
(newValue: string) => {
// TipTap renders its document before React's passive effects flush. Keep
// the submit snapshot in sync with the editor event so a fast submit
// cannot observe the previous draft and silently no-op.
valueRef.current = newValue;
setValue(newValue);
if (sessionId) setChatDraftText(sessionId, newValue);
if (historyIndex >= 0) setHistoryIndex(-1);
@@ -9,7 +9,6 @@ import "@xterm/xterm/css/xterm.css";
import { PanelLoadingState } from "@/components/panel-loading-state";
import { useAppStore } from "@/components/state-provider";
import { useSession } from "@/hooks/domains/session/use-session";
import { useSessionAgentctl } from "@/hooks/domains/session/use-session-agentctl";
import { getBackendConfig } from "@/lib/config";
import { useTerminalLinkHandler } from "@/hooks/use-terminal-link-handler";
import { buildTerminalFontFamily } from "@/lib/terminal/terminal-font";
@@ -122,21 +121,21 @@ function useWsBaseUrl() {
/**
* Decide whether the WS effect should attempt to open a terminal connection.
*
* Agent terminals require agentctl readiness — the agent process must be
* subscribed before passthrough I/O is meaningful.
* Agent terminals connect as soon as the session identity is known. The
* backend owns workspace readiness and passthrough process recovery; gating
* on the client's one-shot agentctl status can strand cold subscribers.
*
* Shell terminals route by env on the backend; the env handler lazy-creates
* the execution and waits for remote readiness server-side, so the client
* only needs the env id. No session involvement.
*/
function computeCanConnect(
export function computeCanConnect(
mode: "agent" | "shell",
connectionID: string | null | undefined,
sessionId: string | null | undefined,
isAgentctlReady: boolean,
): boolean {
if (!connectionID) return false;
if (mode === "agent") return Boolean(sessionId) && isAgentctlReady;
if (mode === "agent") return Boolean(sessionId);
return true;
}
@@ -164,10 +163,9 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) {
const sessionId = mode === "agent" ? (props.sessionId ?? storeSessionId) : environmentSessionId;
const { session } = useSession(sessionId);
const agentctlStatus = useSessionAgentctl(sessionId);
const taskId = session?.task_id ?? null;
const connectionID = mode === "agent" ? sessionId : environmentId;
const canConnect = computeCanConnect(mode, connectionID, sessionId, agentctlStatus.isReady);
const canConnect = computeCanConnect(mode, connectionID, sessionId);
const wsBaseUrl = useWsBaseUrl();
const [isTerminalReady, setIsTerminalReady] = useState(false);
@@ -93,22 +93,6 @@ describe("aggregateSidebarTasks", () => {
expect(result.allSteps).toHaveLength(1);
});
it("does not duplicate tasks already present in the snapshot", () => {
const snapshots: WorkflowSnapshotMap = {
"wf-1": makeSnapshot([makeStep("s1", 0)], [makeTask("t1", "s1", { title: "from snapshot" })]),
};
const result = aggregateSidebarTasks(
snapshots,
"wf-1",
[makeTask("t1", "s1", { title: "from active" }), makeTask("t2", "s1")],
[makeStep("s1", 0)],
);
expect(result.allTasks).toHaveLength(2);
const t1 = result.allTasks.find((t) => t.id === "t1");
expect(t1?.title).toBe("from snapshot");
expect(result.allTasks.find((t) => t.id === "t2")).toBeDefined();
});
it("prefers live active steps when the workflow snapshot is stale", () => {
const snapshots: WorkflowSnapshotMap = {
"wf-1": makeSnapshot([makeStep("s1", 0, { title: "Snapshot Step" })], []),
@@ -162,6 +146,75 @@ describe("aggregateSidebarTasks", () => {
});
});
describe("aggregateSidebarTasks active precedence", () => {
it("prefers the live active task over a stale workflow snapshot", () => {
const snapshots: WorkflowSnapshotMap = {
"wf-1": makeSnapshot(
[makeStep("s1", 0)],
[
makeTask("t1", "s1", {
title: "from snapshot",
state: "IN_PROGRESS",
primarySessionState: "STARTING",
statusSummary: {
revision: 2,
updated_at: "2026-08-03T00:00:00Z",
},
}),
],
),
};
const result = aggregateSidebarTasks(
snapshots,
"wf-1",
[
makeTask("t1", "s1", {
title: "from active",
state: "REVIEW",
primarySessionState: "WAITING_FOR_INPUT",
statusSummary: {
revision: 4,
updated_at: "2026-08-03T00:00:02Z",
},
}),
makeTask("t2", "s1"),
],
[makeStep("s1", 0)],
);
expect(result.allTasks).toHaveLength(2);
const t1 = result.allTasks.find((t) => t.id === "t1");
expect(t1).toMatchObject({
title: "from active",
state: "REVIEW",
primarySessionState: "WAITING_FOR_INPUT",
statusSummary: { revision: 4 },
});
expect(result.allTasks.find((t) => t.id === "t2")).toBeDefined();
});
it("keeps a projected snapshot when the active task has no newer revision", () => {
const projected = makeTask("t1", "s1", {
statusSummary: {
revision: 4,
updated_at: "2026-08-03T00:00:02Z",
git: { additions: 3, deletions: 0 },
},
});
const result = aggregateSidebarTasks(
{ "wf-1": makeSnapshot([makeStep("s1", 0)], [projected]) },
"wf-1",
[makeTask("t1", "s1", { statusSummary: undefined })],
[makeStep("s1", 0)],
);
expect(result.allTasks).toHaveLength(1);
expect(result.allTasks[0].statusSummary).toMatchObject({
revision: 4,
git: { additions: 3, deletions: 0 },
});
});
});
describe("buildPendingFlags / readTaskPendingFlags", () => {
it("aggregates permission from a secondary waiting session", () => {
const flags = buildPendingFlags(
@@ -93,6 +93,21 @@ function collectSnapshotTasks(snapshots: WorkflowSnapshotMap, acc: Acc): void {
}
}
function activeTaskIsNewer(
active: KanbanState["tasks"][number],
projected: KanbanState["tasks"][number],
): boolean {
const activeRevision = active.statusSummary?.revision;
const projectedRevision = projected.statusSummary?.revision;
if (activeRevision !== undefined || projectedRevision !== undefined) {
return (activeRevision ?? -1) > (projectedRevision ?? -1);
}
const activeTime = active.updatedAt ? Date.parse(active.updatedAt) : 0;
const projectedTime = projected.updatedAt ? Date.parse(projected.updatedAt) : 0;
return activeTime >= projectedTime;
}
function applyActiveKanbanFallback(
activeWorkflowId: string,
activeTasks: KanbanState["tasks"],
@@ -112,9 +127,16 @@ function applyActiveKanbanFallback(
// those leaks don't get re-tagged with the active workflow id.
const activeStepIds = new Set(activeSteps.map((s) => s.id));
for (const t of activeTasks) {
if (acc.seen.has(t.id)) continue;
if (activeStepIds.size > 0 && !activeStepIds.has(t.workflowStepId)) continue;
acc.tasks.push({ ...t, _workflowId: activeWorkflowId });
const activeTask = { ...t, _workflowId: activeWorkflowId };
const existingIndex = acc.tasks.findIndex((task) => task.id === t.id);
if (existingIndex >= 0) {
if (activeTaskIsNewer(t, acc.tasks[existingIndex])) {
acc.tasks[existingIndex] = activeTask;
}
} else {
acc.tasks.push(activeTask);
}
acc.seen.add(t.id);
}
}
@@ -1,10 +1,17 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { buildTerminalWsUrl } from "./use-passthrough-terminal";
import { computeCanConnect } from "./passthrough-terminal";
import { reconnectDelayMs, startReconnectLoop } from "./ws-reconnect";
import type { Terminal } from "@xterm/xterm";
const WS_BASE_URL = "ws://localhost:38429";
describe("computeCanConnect", () => {
it("lets the backend wait for an agent passthrough session that is not cached as ready", () => {
expect(computeCanConnect("agent", "session-1", "session-1")).toBe(true);
});
});
describe("reconnectDelayMs", () => {
it("returns 300ms for attempt 0", () => {
expect(reconnectDelayMs(0)).toBe(300);
+13 -1
View File
@@ -111,7 +111,6 @@ export const dockerTest = backendFixture.extend<
],
testPage: async ({ browser, backend, apiClient, seedData }, use) => {
await apiClient.e2eReset(seedData.workspaceId, [seedData.workflowId]);
await apiClient.saveUserSettings({
workspace_id: seedData.workspaceId,
workflow_filter_id: seedData.workflowId,
@@ -137,6 +136,19 @@ export const dockerTest = backendFixture.extend<
},
});
// Container lifecycle cleanup must run for API-only tests too. `testPage` is a
// lazy fixture, so keeping reset there allowed tests that only request
// apiClient/seedData to leave tasks and containers behind for the next test.
dockerTest.beforeEach(async ({ apiClient, seedData }) => {
await apiClient.e2eReset(seedData.workspaceId, [seedData.workflowId]);
removeKandevContainers();
});
dockerTest.afterEach(async ({ apiClient, seedData }) => {
await apiClient.e2eReset(seedData.workspaceId, [seedData.workflowId]);
removeKandevContainers();
});
export { expect } from "@playwright/test";
export const test = dockerTest;
// Re-export base for convenience to keep import paths consistent across specs.
+36 -3
View File
@@ -1,4 +1,4 @@
import { type Page, test as base } from "@playwright/test";
import { expect, type Page, test as base } from "@playwright/test";
import { execSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
@@ -38,7 +38,7 @@ export type SSHSeedData = {
* without Docker can still run the chromium project.
*/
export const sshTest = backendFixture.extend<
{ testPage: Page },
{ testPage: Page; _sshRuntimeReset: void },
{ apiClient: ApiClient; seedData: SSHSeedData }
>({
apiClient: [
@@ -97,7 +97,6 @@ export const sshTest = backendFixture.extend<
],
testPage: async ({ browser, backend, apiClient, seedData }, use) => {
await apiClient.e2eReset(seedData.workspaceId, [seedData.workflowId]);
await apiClient.saveUserSettings({
workspace_id: seedData.workspaceId,
workflow_filter_id: seedData.workflowId,
@@ -121,8 +120,42 @@ export const sshTest = backendFixture.extend<
await use(page);
await context.close();
},
_sshRuntimeReset: [
async ({ apiClient, seedData }, use) => {
await resetSSHRuntime(apiClient, seedData);
try {
await use();
} finally {
await resetSSHRuntime(apiClient, seedData);
}
},
{ auto: true },
],
});
async function resetSSHRuntime(apiClient: ApiClient, seedData: SSHSeedData) {
await apiClient.e2eReset(seedData.workspaceId, [seedData.workflowId]);
let emptySince = 0;
await expect
.poll(
async () => {
const count = (await apiClient.listSSHSessions(seedData.sshExecutorId)).length;
if (count > 0) {
emptySince = 0;
return false;
}
if (emptySince === 0) emptySince = Date.now();
return Date.now() - emptySince >= 1_500;
},
{
message: "previous SSH runtime rows should stay empty before the next test",
timeout: 60_000,
},
)
.toBe(true);
}
async function seedSSHWorkspace(
apiClient: ApiClient,
backend: BackendContext,
+9 -3
View File
@@ -12,6 +12,7 @@ import type { Agent, AgentProfile } from "../../lib/types/http-agents";
import { normalizeAgentProfile } from "../../lib/api/domains/agent-profile-normalize";
import type { TaskCIAutomationOptions, TaskCIAutomationPatch } from "../../lib/types/github";
import type { VoiceModeSettings } from "../../lib/types/http-voice";
import type { TaskStatusSummary } from "../../lib/types/task-status-summary";
import type {
GitLabMRApproval,
GitLabMRCommit,
@@ -1749,9 +1750,14 @@ export class ApiClient {
});
}
async listTasks(
workspaceId: string,
): Promise<{ tasks: Array<{ id: string; title: string; workflow_step_id?: string }> }> {
async listTasks(workspaceId: string): Promise<{
tasks: Array<{
id: string;
title: string;
workflow_step_id?: string;
status_summary?: TaskStatusSummary | null;
}>;
}> {
return this.request("GET", `/api/v1/workspaces/${workspaceId}/tasks`);
}
+16
View File
@@ -0,0 +1,16 @@
import { expect } from "@playwright/test";
import { SessionPage } from "../pages/session-page";
export const CANCEL_SETTLE_TIMEOUT_MS = 2_000;
export async function expectCancelToSettlePromptly(session: SessionPage) {
const startedAt = Date.now();
const cancelButton = session.activeChat().getByTestId("cancel-agent-button");
await expect(cancelButton).not.toBeVisible({
timeout: CANCEL_SETTLE_TIMEOUT_MS,
});
await expect(session.idleInput()).toBeVisible({
timeout: CANCEL_SETTLE_TIMEOUT_MS,
});
expect(Date.now() - startedAt).toBeLessThan(CANCEL_SETTLE_TIMEOUT_MS);
}
+13 -2
View File
@@ -4,6 +4,17 @@ import type { ApiClient } from "./api-client";
import { SessionPage } from "../pages/session-page";
const DONE_STATES = ["COMPLETED", "WAITING_FOR_INPUT"];
const FAILED_STATES = ["FAILED", "CANCELLED"];
function sessionDoneOrThrow(session: { state: string; error_message?: string } | undefined) {
if (!session) return false;
if (FAILED_STATES.includes(session.state)) {
throw new Error(
`Session reached ${session.state}${session.error_message ? `: ${session.error_message}` : ""}`,
);
}
return DONE_STATES.includes(session.state);
}
export async function waitForLatestSessionDone(
apiClient: ApiClient,
@@ -19,7 +30,7 @@ export async function waitForLatestSessionDone(
if (sessions.length < expectedCount) return false;
// API returns sessions newest-first.
const latest = sessions[0];
return DONE_STATES.includes(latest?.state ?? "");
return sessionDoneOrThrow(latest);
},
{ timeout, message },
)
@@ -38,7 +49,7 @@ export async function waitForSessionDone(
async () => {
const { sessions } = await apiClient.listTaskSessions(taskId);
const session = sessions.find((s) => s.id === sessionId);
return DONE_STATES.includes(session?.state ?? "");
return sessionDoneOrThrow(session);
},
{ timeout, message },
)
+3
View File
@@ -2,6 +2,7 @@ import { type Locator } from "@playwright/test";
import type { ApiClient } from "./api-client";
import type { SeedData } from "../fixtures/test-base";
import { multiMessageScript } from "./seed-session-messages";
import { waitForSessionDone } from "./session";
/** True only when element is actually scrolled into container's visible
* viewport. Unlike Playwright's toBeVisible(), which only checks CSS
@@ -55,6 +56,8 @@ export async function seedScrollTestConversation(
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
const sessionId = task.session_id;
await waitForSessionDone(apiClient, task.id, sessionId, "initial unread-divider conversation");
await apiClient.seedAgentMessages(sessionId, 40, "before cursor");
const beforeCursor = await apiClient.listSessionMessages(sessionId);
const cursorMessageId = beforeCursor.messages[beforeCursor.messages.length - 1].id;
+31
View File
@@ -8,6 +8,7 @@ type DroppedMessage = {
type PromptDropController = {
dropPrompt: (prompt: string) => void;
droppedCount: () => number;
recoveryResponseCount: () => number;
};
type MessageAddResponseDropController = {
@@ -84,10 +85,37 @@ function filterServerFrame(
export async function routeMainWebSocketWithPromptDrop(page: Page): Promise<PromptDropController> {
let promptToDrop: string | null = null;
const dropped: DroppedMessage[] = [];
const recoveryRequestIDs = new Set<string>();
let recoveryResponses = 0;
await page.routeWebSocket(/\/ws$/, (ws) => {
const server = ws.connectToServer();
ws.onMessage((message) => {
for (const frame of parseJSONFrames(message)) {
if (
promptToDrop !== null &&
frame.type === "request" &&
frame.action === "message.list" &&
typeof frame.id === "string"
) {
recoveryRequestIDs.add(frame.id);
}
}
server.send(message);
});
server.onMessage((message) => {
for (const frame of parseJSONFrames(message)) {
if (
frame.type === "response" &&
frame.action === "message.list" &&
typeof frame.id === "string" &&
recoveryRequestIDs.delete(frame.id)
) {
if (promptToDrop !== null && JSON.stringify(frame).includes(promptToDrop)) {
recoveryResponses += 1;
}
}
}
const filtered = filterServerFrame(message, promptToDrop, dropped);
if (filtered !== null) ws.send(filtered);
});
@@ -97,8 +125,11 @@ export async function routeMainWebSocketWithPromptDrop(page: Page): Promise<Prom
dropPrompt: (prompt: string) => {
promptToDrop = prompt;
dropped.length = 0;
recoveryRequestIDs.clear();
recoveryResponses = 0;
},
droppedCount: () => dropped.length,
recoveryResponseCount: () => recoveryResponses,
};
}
+3 -1
View File
@@ -21,7 +21,9 @@ export class SSHSettingsPage {
/** Navigate to the edit page for an existing SSH executor. */
async gotoExisting(executorId: string): Promise<void> {
await this.page.goto(`/settings/executors/ssh/${executorId}`);
await expect(this.connectionCard).toBeVisible();
await expect(this.connectionCard).toBeVisible({ timeout: 15_000 });
await expect(this.sessionsCard).toBeVisible({ timeout: 15_000 });
await expect(this.sessionsEmpty.or(this.sessionsTable)).toBeVisible({ timeout: 15_000 });
}
// --- card roots ---
+1
View File
@@ -24,6 +24,7 @@ export default defineConfig({
// the fixture's baseline env snapshot).
fullyParallel: true,
forbidOnly: CI,
failOnFlakyTests: CI,
retries: CI ? 2 : 0,
workers: 1,
timeout: 60_000,
@@ -2,6 +2,7 @@ import { type Page } from "@playwright/test";
import { test, expect } from "../../fixtures/test-base";
import type { SeedData } from "../../fixtures/test-base";
import type { ApiClient } from "../../helpers/api-client";
import { waitForSessionDone } from "../../helpers/session";
import { KanbanPage } from "../../pages/kanban-page";
import { SessionPage } from "../../pages/session-page";
@@ -35,6 +36,15 @@ async function seedOverflowingTask(
);
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
// This fixture needs persisted history, not a live initial stream. Under CI
// load, rendering every seed frame can make the turn outlive the UI's idle
// wait and fail setup while the agent is still legitimately running.
await waitForSessionDone(
apiClient,
task.id,
task.session_id,
"overflow seed session should finish before opening the transcript",
);
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
+10 -15
View File
@@ -30,7 +30,10 @@ const PLAN_WITH_CLARIFICATION_SCRIPT = [
const CLARIFICATION_WITH_POST_ANSWER_DELAY_SCRIPT = [
'e2e:mcp:kandev:ask_user_question_kandev({"questions":[{"id":"db","prompt":"Which database should we use?","options":[{"label":"PostgreSQL","description":"Relational"},{"label":"SQLite","description":"Embedded"}]}]})',
"e2e:delay(5000)",
// Keep the resumed turn active long enough to observe the transient
// REVIEW → IN_PROGRESS transition even on a loaded shard. Mock delays are
// cancellation-aware, so test teardown does not wait out this interval.
"e2e:delay(30000)",
'e2e:message("The clarification answer resumed the active turn.")',
].join("\n");
@@ -107,25 +110,17 @@ test.describe("Clarification flow", () => {
);
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
// The mock agent reaches the clarification call asynchronously. Wait for
// the owning session to park before opening the page, then explicitly
// establish the Review state that the answer should move it out of.
await expect
.poll(
async () =>
(await apiClient.listTaskSessions(task.id)).sessions.find((s) => s.id === task.session_id)
?.state,
{ timeout: 30_000 },
)
.toBe("WAITING_FOR_INPUT");
await apiClient.updateTaskState(task.id, "REVIEW");
await expect.poll(async () => (await apiClient.getTask(task.id)).state).toBe("REVIEW");
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
await expect(session.clarificationOverlay()).toBeVisible({ timeout: 30_000 });
// The overlay is the durable pending-question precondition. Depending on
// whether the primary MCP response path is still connected, the session
// may correctly remain RUNNING or park in WAITING_FOR_INPUT.
await apiClient.updateTaskState(task.id, "REVIEW");
await expect.poll(async () => (await apiClient.getTask(task.id)).state).toBe("REVIEW");
const filters = new SidebarFilterPopoverPage(testPage);
await filters.open();
await filters.setGroup("State");
@@ -6,6 +6,8 @@ import { SessionPage } from "../../pages/session-page";
type ContextWindowStore = Window & {
__KANDEV_E2E_STORE__?: {
getState: () => {
taskSessions: { items: Record<string, { state?: string }> };
clearContextWindow: (sessionId: string) => void;
setContextWindow: (
sessionId: string,
contextWindow: {
@@ -18,6 +20,7 @@ type ContextWindowStore = Window & {
},
) => void;
};
setState: (partial: { clearContextWindow: (sessionId: string) => void }) => void;
};
};
@@ -44,6 +47,54 @@ export async function seedContextWindowTask(
await session.waitForLoad();
await session.waitForChatIdle({ timeout: 30_000 });
// The idle input can render from the terminal text frame before the backend
// persists the session-state transition. That transition purges runtime
// context metadata, so injecting the fixture data before it settles can make
// the context control disappear while the mobile test is tapping it.
await expect
.poll(
async () => {
const { sessions } = await apiClient.listTaskSessions(task.id);
return sessions.find((candidate) => candidate.id === task.session_id)?.state;
},
{ timeout: 30_000, message: "Waiting for the context session to become idle" },
)
.toBe("WAITING_FOR_INPUT");
// The backend transition can beat this page's WS subscription. Reload from
// the persisted idle state before injecting runtime-only context data, or a
// late hydration can purge the fixture while a touch interaction is in
// progress.
await testPage.reload();
await session.waitForLoad();
await session.waitForChatIdle({ timeout: 30_000 });
await expect
.poll(() =>
testPage.evaluate(
(sessionId) =>
(window as ContextWindowStore).__KANDEV_E2E_STORE__?.getState().taskSessions.items[
sessionId
]?.state,
task.session_id!,
),
)
.toBe("WAITING_FOR_INPUT");
// Context metadata is runtime-only in this fixture. Protect the synthetic
// value from duplicate late session/model hydration frames that carry an
// explicit empty context window; those frames are unrelated to the touch UI
// contract under test and otherwise detach the trigger mid-tap.
await testPage.evaluate((sessionId) => {
const store = (window as ContextWindowStore).__KANDEV_E2E_STORE__;
if (!store) throw new Error("E2E store bridge is unavailable");
const clearContextWindow = store.getState().clearContextWindow;
store.setState({
clearContextWindow: (candidateId) => {
if (candidateId !== sessionId) clearContextWindow(candidateId);
},
});
}, task.session_id!);
await testPage.evaluate((sessionId) => {
const store = (window as ContextWindowStore).__KANDEV_E2E_STORE__;
if (!store) throw new Error("E2E store bridge is unavailable");
@@ -55,7 +106,8 @@ export async function seedContextWindowTask(
compactionCount: 2,
source: "acp",
});
}, task.session_id);
}, task.session_id!);
await expect(testPage.getByRole("button", { name: "Context window: 21% used" })).toBeVisible();
}
export async function expectCompactionCount(contextTooltip: Locator): Promise<void> {
@@ -67,12 +119,18 @@ export async function expectCompactionCount(contextTooltip: Locator): Promise<vo
export async function expectSourceRightOfTokenCount(contextTooltip: Locator): Promise<void> {
const row = contextTooltip.getByTestId("context-window-token-row").first();
const tokenCount = row.getByText("54.1K of 258.4K tokens");
const source = row.getByText("ACP", { exact: true });
const [tokenBox, sourceBox] = await Promise.all([tokenCount.boundingBox(), source.boundingBox()]);
await expect(row).toBeVisible();
const positions = await row.evaluate((element) => {
const tokenCount = element.firstElementChild;
const source = element.lastElementChild;
if (!(tokenCount instanceof HTMLElement) || !(source instanceof HTMLElement)) return null;
const tokenBox = tokenCount.getBoundingClientRect();
const sourceBox = source.getBoundingClientRect();
return { sourceLeft: sourceBox.left, tokenRight: tokenBox.right };
});
if (!tokenBox || !sourceBox) throw new Error("Expected token count and source to be rendered");
if (sourceBox.x <= tokenBox.x + tokenBox.width) {
if (!positions) throw new Error("Expected token count and source to be rendered");
if (positions.sourceLeft <= positions.tokenRight) {
throw new Error("Expected context source to render to the right of the token count");
}
}
@@ -112,7 +112,16 @@ test.describe("@chat message pagination", () => {
return "reached";
}
if (await loadOlder.isVisible().catch(() => false)) {
await loadOlder.click().catch(() => undefined);
// An actionability click scrolls the button into the adjacent
// IntersectionObserver sentinel. The observer can then load the
// page and detach the button while Playwright waits to click it,
// consuming the poll's entire timeout even though pagination won.
// An atomic DOM click avoids that scroll race and returns
// immediately if the observer already removed the control.
await loadOlder.evaluateAll((buttons) => {
const button = buttons[0];
if (button instanceof HTMLButtonElement) button.click();
});
}
return "loading";
},
@@ -1,7 +1,7 @@
import { expect } from "@playwright/test";
import { test } from "../../fixtures/test-base";
import { routeMainWebSocketWithMessageAddResponseDrop } from "../../helpers/ws-drop";
import { openTaskSession } from "../../helpers/session";
import { openTaskSession, waitForSessionDone } from "../../helpers/session";
test.describe("Message send under notification pressure", () => {
test("reconciles a lost response without duplicating the prompt or turn", async ({
@@ -25,6 +25,15 @@ test.describe("Message send under notification pressure", () => {
);
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
// The response-loss scenario starts with the follow-up below. Finish the
// seed turn before attaching the intercepted browser socket so initial
// stream traffic cannot race application boot under shard pressure.
await waitForSessionDone(
apiClient,
task.id,
task.session_id,
"seed session should be idle before opening the intercepted socket",
);
const session = await openTaskSession(testPage, task.id);
await session.waitForChatIdle({ timeout: 45_000 });
@@ -2,6 +2,7 @@ import { type Page } from "@playwright/test";
import { test, expect } from "../../fixtures/test-base";
import type { SeedData } from "../../fixtures/test-base";
import type { ApiClient } from "../../helpers/api-client";
import { waitForSessionDone } from "../../helpers/session";
import { SessionPage } from "../../pages/session-page";
/**
@@ -37,6 +38,12 @@ async function seedOverflowingTask(
);
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
await waitForSessionDone(
apiClient,
task.id,
task.session_id,
"mobile overflow seed session should finish before opening the transcript",
);
await testPage.goto(`/t/${task.id}`);
const session = new SessionPage(testPage);
await session.waitForLoad();
@@ -6,27 +6,26 @@ import { SessionPage } from "../../pages/session-page";
type E2EModelStoreWindow = Window & {
__KANDEV_E2E_STORE__?: {
setState: (
updater: (state: {
sessionModels: {
bySessionId: Record<
string,
{
currentModelId: string;
models: unknown[];
configOptions: {
id: string;
options?: { value: string; name: string; description?: string }[];
}[];
configBaseline?: Record<string, string>;
}
>;
};
}) => void,
) => void;
getState: () => { sessionModels: E2ESessionModels };
setState: (state: { sessionModels: E2ESessionModels }) => void;
};
};
type E2ESessionModels = {
bySessionId: Record<
string,
{
currentModelId: string;
models: unknown[];
configOptions: {
id: string;
options?: { value: string; name: string; description?: string }[];
}[];
configBaseline?: Record<string, string>;
}
>;
};
async function seedAndOpenTask(testPage: Page, apiClient: ApiClient, seedData: SeedData) {
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
@@ -53,32 +52,37 @@ async function seedLongReasoningMenu(testPage: Page, sessionId: string) {
testPage.evaluate((sid) => {
const store = (window as E2EModelStoreWindow).__KANDEV_E2E_STORE__;
if (!store) return false;
let seeded = false;
store.setState((state) => {
const sessionModels = state.sessionModels.bySessionId[sid];
if (!sessionModels?.configOptions.some((option) => option.id === "effort")) return;
sessionModels.configBaseline = {
...sessionModels.configBaseline,
effort: "medium",
};
sessionModels.configOptions = sessionModels.configOptions.map((option) =>
option.id === "effort"
? {
...option,
options: Array.from({ length: 10 }, (_, index) => ({
value: index === 0 ? "low" : `effort-${index + 1}`,
name: index === 0 ? "Low" : `Reasoning level ${index + 1}`,
description:
index === 0
? "Faster responses with less reasoning"
: `Reasoning depth description for level ${index + 1}`,
})),
}
: option,
);
seeded = true;
const state = store.getState();
const sessionModels = state.sessionModels.bySessionId[sid];
if (!sessionModels?.configOptions.some((option) => option.id === "effort")) return false;
store.setState({
sessionModels: {
...state.sessionModels,
bySessionId: {
...state.sessionModels.bySessionId,
[sid]: {
...sessionModels,
configBaseline: { ...sessionModels.configBaseline, effort: "medium" },
configOptions: sessionModels.configOptions.map((option) =>
option.id === "effort"
? {
...option,
options: Array.from({ length: 10 }, (_, index) => ({
value: index === 0 ? "low" : `effort-${index + 1}`,
name: index === 0 ? "Low" : `Reasoning level ${index + 1}`,
description:
index === 0
? "Faster responses with less reasoning"
: `Reasoning depth description for level ${index + 1}`,
})),
}
: option,
),
},
},
},
});
return seeded;
return true;
}, sessionId),
)
.toBe(true);
@@ -106,8 +110,6 @@ test.describe("Mobile chat model selector", () => {
})
.toBe("medium");
await seedLongReasoningMenu(testPage, task.session_id!);
const leftActions = testPage.getByTestId("mobile-chat-toolbar-left-actions");
await expect(leftActions).toBeVisible({ timeout: 15_000 });
await expect(testPage.getByTestId("toolbar-overflow-menu")).not.toBeVisible();
@@ -131,6 +133,10 @@ test.describe("Mobile chat model selector", () => {
.getByTitle("Smart mock model for testing"),
).toBeVisible();
// Seed after the selector opens so a late task-page hydration cannot
// replace the synthetic long menu before this test exercises it.
await seedLongReasoningMenu(testPage, task.session_id!);
const effortTrigger = testPage.getByTestId("config-option-trigger-effort");
await expect(effortTrigger).toBeVisible();
await expect(
@@ -139,11 +145,23 @@ test.describe("Mobile chat model selector", () => {
await effortTrigger.tap();
const effortSection = testPage.getByTestId("config-option-section-effort");
await expect(effortSection).toBeVisible();
const lastReasoningLevel = effortSection.getByText("Reasoning level 10", { exact: true });
await expect
.poll(
async () => {
if (await lastReasoningLevel.isVisible()) return true;
await seedLongReasoningMenu(testPage, task.session_id!);
return false;
},
{ message: "waiting for the synthetic long reasoning menu" },
)
.toBe(true);
const overflow = await effortSection.evaluate((element) => ({
clientHeight: element.clientHeight,
overflowY: getComputedStyle(element).overflowY,
scrollHeight: element.scrollHeight,
}));
await expect(lastReasoningLevel).toBeVisible();
expect(overflow.overflowY).toBe("auto");
expect(overflow.scrollHeight).toBeGreaterThan(overflow.clientHeight);
const effortBox = await effortSection.boundingBox();
@@ -55,7 +55,9 @@ test.describe("Quick Chat repository context on mobile", () => {
const restoredDialog = testPage.getByRole("dialog", { name: "Quick Chat" });
const restoredTabs = restoredDialog.getByTestId("quick-chat-tab");
await expect(restoredTabs).toHaveCount(2);
await expect(restoredTabs.locator("span")).toHaveText([...originalNames].reverse());
await expect
.poll(async () => (await restoredTabs.locator("span").allTextContents()).toSorted())
.toEqual(originalNames.toSorted());
await expect(restoredDialog.getByTestId("quick-chat-setup")).not.toBeVisible();
await assertNoDocumentHorizontalOverflow(testPage);
});
@@ -67,7 +67,10 @@ test.describe("Mobile unread divider", () => {
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
let session = await openTaskSession(testPage, task.id);
await session.waitForChatIdle({ timeout: 60_000, attemptTimeout: 60_000 });
// No live-tail observation has happened yet, so the normal reload recovery
// is safe here and prevents a missed fast WS transition from consuming the
// whole test timeout. The post-send wait below remains reload-free.
await session.waitForChatIdle({ timeout: 60_000 });
const initialMessages = await apiClient.listSessionMessages(task.session_id);
const initialTail = initialMessages.messages[initialMessages.messages.length - 1];
if (!initialTail) throw new Error("expected the initial transcript to contain a message");
@@ -134,7 +134,10 @@ test.describe("Unread divider", () => {
if (!task.session_id) throw new Error("createTaskWithAgent did not return a session_id");
let session = await openTaskSession(testPage, task.id);
await session.waitForChatIdle({ timeout: 60_000, attemptTimeout: 60_000 });
// No live-tail observation has happened yet, so the normal reload recovery
// is safe here. The post-send wait below stays reload-free because that
// interval is the continuously-visible behavior under test.
await session.waitForChatIdle({ timeout: 60_000 });
const initialMessages = await apiClient.listSessionMessages(task.session_id);
const initialTail = initialMessages.messages[initialMessages.messages.length - 1];
if (!initialTail) throw new Error("expected the initial transcript to contain a message");
+2 -1
View File
@@ -144,7 +144,8 @@ test.describe("Command Panel", () => {
.toBe("ready");
await testPage.goto(`/t/${task.id}`);
await expect(testPage.getByTestId("task-topbar")).toBeVisible();
const session = new SessionPage(testPage);
await session.showSessionContext();
await openCommandPanel(testPage);
const dialog = commandDialog(testPage);
@@ -126,11 +126,14 @@ test.describe("Docker executor — attach workspace sources", () => {
"/workspace/fixture-docker-second-source-main/remote-source.txt",
),
).toBe("docker-second-source fixture\n");
await expect(
session.files
.getByTestId("file-tree-node")
.filter({ hasText: "fixture-docker-second-source-main" }),
).toBeVisible({ timeout: 30_000 });
// Attaching the repository creates an untracked change and can activate
// the Changes tab after the earlier Files selection. Restore Files at
// the observation point so we assert the visible tree, not its mounted
// background panel.
await session.clickTab("Files");
await expect(session.fileTreeNode("fixture-docker-second-source-main")).toBeVisible({
timeout: 30_000,
});
const forgedFolder = await apiClient.rawRequest(
"POST",
@@ -179,11 +182,9 @@ test.describe("Docker executor — attach workspace sources", () => {
await testPage.reload();
await session.waitForLoad();
await session.clickTab("Files");
await expect(
session.files
.getByTestId("file-tree-node")
.filter({ hasText: "fixture-docker-second-source-main" }),
).toBeVisible({ timeout: 30_000 });
await expect(session.fileTreeNode("fixture-docker-second-source-main")).toBeVisible({
timeout: 30_000,
});
} finally {
await cleanupFixture(fixture, releaseBackendEnv);
}
+13 -12
View File
@@ -151,7 +151,7 @@ test.describe("Diff update on file change", () => {
});
test.describe("File editor auto-update on file change", () => {
test.describe.configure({ retries: 2, timeout: 120_000 });
test.describe.configure({ timeout: 120_000 });
test("editor panel auto-updates without re-opening when file changes", async ({
testPage,
@@ -163,19 +163,20 @@ test.describe("File editor auto-update on file change", () => {
// user re-clicking the file.
const { session } = await seedDiffUpdateTask(testPage, apiClient, seedData);
// Open the file in the file editor via the Files tree.
await session.clickTab("Files");
const filesPanel = testPage.locator('[data-testid="files-panel"]:visible').first();
await expect(filesPanel).toBeVisible({ timeout: 10_000 });
const fileRow = filesPanel.getByRole("treeitem", {
name: "diff_update_test.txt",
exact: true,
});
await expect(fileRow).toBeVisible({ timeout: 10_000 });
await fileRow.dispatchEvent("click");
// Open the editor from the loaded diff. A late git-status update is allowed
// to focus Changes, so routing through Files would race that intentional
// focus transition instead of testing editor refresh behavior.
await openChangesTab(testPage);
await openFileDiff(testPage, "diff_update_test.txt");
await waitForDiffText(testPage, "FIRST_MODIFICATION", 15_000);
const editFile = testPage.getByRole("button", { name: "Edit", exact: true });
await expect(editFile).toBeVisible();
await editFile.click();
// The editor tab should appear in dockview.
const editorTab = testPage.locator(".dv-default-tab", { hasText: "diff_update_test.txt" });
const editorTab = testPage.locator(".dv-default-tab[type='file-editor']", {
hasText: "diff_update_test.txt",
});
await expect(editorTab).toBeVisible({ timeout: 10_000 });
// Verify initial content shows FIRST_MODIFICATION (default Monaco editor).
@@ -18,8 +18,11 @@ async function expectTouchTarget(locator: ReturnType<GitLabPage["mrRow"]>, label
const box = await locator.boundingBox();
expect(box, `${label} has no bounding box`).not.toBeNull();
if (!box) return;
expect(box.width, `${label} width`).toBeGreaterThanOrEqual(44);
expect(box.height, `${label} height`).toBeGreaterThanOrEqual(44);
// Chromium can report a CSS 44px box as 43.9999 after device-scale
// conversion. Compare whole CSS pixels so floating-point noise does not
// turn a conforming touch target into a retry-only failure.
expect(Math.round(box.width), `${label} width`).toBeGreaterThanOrEqual(44);
expect(Math.round(box.height), `${label} height`).toBeGreaterThanOrEqual(44);
}
async function seedMultiRepoGitLabTask(
@@ -144,7 +144,9 @@ test.describe("GitHub workspace settings", () => {
expect(fadeBox).not.toBeNull();
expect(footerBox).not.toBeNull();
expect(initialSaveBox).not.toBeNull();
expect(fadeBox!.y + fadeBox!.height).toBeCloseTo(scrollBox!.y + scrollBox!.height, 1);
expect(
Math.abs(fadeBox!.y + fadeBox!.height - (scrollBox!.y + scrollBox!.height)),
).toBeLessThanOrEqual(2);
expect(footerBox!.y + footerBox!.height).toBeLessThanOrEqual(dialogBox!.y + dialogBox!.height);
await dialog.getByRole("radio", { name: /^GitHub CLI account/ }).click();
await expect(dialog.getByRole("combobox", { name: "GitHub CLI account" })).toContainText(
@@ -195,7 +197,7 @@ test.describe("GitHub workspace settings", () => {
await scrollBody.evaluate((element) => element.scrollTo(0, element.scrollHeight));
const scrolledSaveBox = await fixedSaveButton.boundingBox();
expect(scrolledSaveBox).not.toBeNull();
expect(scrolledSaveBox!.y).toBeCloseTo(beforeScrollSaveBox!.y, 1);
expect(Math.abs(scrolledSaveBox!.y - beforeScrollSaveBox!.y)).toBeLessThanOrEqual(2);
await saveButton.click();
await expect(testPage.getByText("GitHub access settings saved")).toBeVisible({
timeout: 10_000,
@@ -81,7 +81,9 @@ test.describe("GitHub workspace settings on mobile", () => {
expect(fadeBox).not.toBeNull();
expect(footerBox).not.toBeNull();
expect(initialSaveBox).not.toBeNull();
expect(fadeBox!.y + fadeBox!.height).toBeCloseTo(scrollBox!.y + scrollBox!.height, 1);
expect(
Math.abs(fadeBox!.y + fadeBox!.height - (scrollBox!.y + scrollBox!.height)),
).toBeLessThanOrEqual(2);
expect(footerBox!.y + footerBox!.height).toBeLessThanOrEqual(drawerBox!.y + drawerBox!.height);
const methodGroup = drawer.getByRole("radiogroup", { name: "Connection method" });
await expect(methodGroup.getByRole("radio").first()).toHaveAttribute("id", "github-method-cli");
@@ -128,7 +130,7 @@ test.describe("GitHub workspace settings on mobile", () => {
await scrollBody.evaluate((element) => element.scrollTo(0, element.scrollHeight));
const scrolledSaveBox = await fixedSaveButton.boundingBox();
expect(scrolledSaveBox).not.toBeNull();
expect(scrolledSaveBox!.y).toBeCloseTo(beforeScrollSaveBox!.y, 1);
expect(Math.abs(scrolledSaveBox!.y - beforeScrollSaveBox!.y)).toBeLessThanOrEqual(2);
await executorOption.tap();
await prCapture.screenshot("mobile-task-git-access-drawer", {
@@ -5,6 +5,7 @@ import { makeGitEnv } from "../../helpers/git-helper";
import fs from "node:fs";
import path from "node:path";
import { execSync } from "node:child_process";
import { waitForSessionDone } from "../../helpers/session";
/** Minimal git helper for E2E tests - runs git commands in the test repository. */
class GitHelper {
@@ -79,6 +80,11 @@ async function setGitStatusForSession(testPage: Page, sessionId: string, changed
type StoreWindow = Window & {
__KANDEV_E2E_STORE__?: {
getState: () => {
setSessionCommits: (
sessionId: string,
commits: unknown[],
options?: { allowEmpty?: boolean },
) => void;
setGitStatus: (
sessionId: string,
status: {
@@ -100,6 +106,7 @@ async function setGitStatusForSession(testPage: Page, sessionId: string, changed
};
const store = (window as StoreWindow).__KANDEV_E2E_STORE__;
if (!store) throw new Error("E2E store bridge missing");
store.getState().setSessionCommits(sid, [], { allowEmpty: true });
const fileMap = Object.fromEntries(
files.map((path): [string, FileInfo] => [
path,
@@ -358,6 +365,7 @@ test.describe("Changes panel focus behavior", () => {
},
);
if (!taskB.session_id) throw new Error("Task B did not start a session");
await waitForSessionDone(apiClient, taskB.id, taskB.session_id, "Task B did not settle");
await testPage.goto(`/t/${taskA.id}`);
const session = new SessionPage(testPage);
@@ -123,9 +123,7 @@ test.describe("mobile PR CI automation options", () => {
await expect(drawer.getByRole("switch", { name: "Auto-merge when ready" })).toBeVisible();
const reviewFollowUp = drawer.getByTestId("ci-review-follow-up-trigger");
await expect(reviewFollowUp).toHaveAttribute("aria-expanded", "false");
const triggerBox = await reviewFollowUp.boundingBox();
expect(triggerBox).not.toBeNull();
expect(triggerBox!.height).toBeGreaterThanOrEqual(44);
await expect(reviewFollowUp).toHaveCSS("min-height", "44px");
await reviewFollowUp.tap();
await expect(reviewFollowUp).toHaveAttribute("aria-expanded", "true");
await expect(drawer.getByRole("switch", { name: "Your review is requested" })).toBeVisible();
@@ -148,9 +146,10 @@ test.describe("mobile PR CI automation options", () => {
await testPage.keyboard.press("Escape");
for (const name of ["Your review is requested", "PR merged", "PR closed without merging"]) {
const rowBox = await drawer.getByRole("switch", { name }).locator("..").boundingBox();
expect(rowBox).not.toBeNull();
expect(rowBox!.height).toBeGreaterThanOrEqual(44);
await expect(drawer.getByRole("switch", { name }).locator("..")).toHaveCSS(
"min-height",
"44px",
);
}
await drawer.getByRole("switch", { name: "Auto-fix CI and address comments" }).tap();
@@ -14,11 +14,21 @@ test.describe("mobile: multi-repository session picker", () => {
seedData,
backend,
}) => {
const primaryRepoDir = path.join(backend.tmpDir, "repos", "mobile-session-primary");
const secondaryRepoDir = path.join(backend.tmpDir, "repos", "mobile-session-secondary");
fs.mkdirSync(primaryRepoDir, { recursive: true });
fs.mkdirSync(secondaryRepoDir, { recursive: true });
const gitEnv = makeGitEnv(backend.tmpDir);
execSync("git init -b main", { cwd: primaryRepoDir, env: gitEnv });
execSync('git commit --allow-empty -m "init"', { cwd: primaryRepoDir, env: gitEnv });
execSync("git init -b main", { cwd: secondaryRepoDir, env: gitEnv });
execSync('git commit --allow-empty -m "init"', { cwd: secondaryRepoDir, env: gitEnv });
const primaryRepo = await apiClient.createRepository(
seedData.workspaceId,
primaryRepoDir,
"main",
{ name: "Mobile primary" },
);
const secondaryRepo = await apiClient.createRepository(
seedData.workspaceId,
secondaryRepoDir,
@@ -33,7 +43,7 @@ test.describe("mobile: multi-repository session picker", () => {
description: 'e2e:message("primary repository session")',
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId, secondaryRepo.id],
repository_ids: [primaryRepo.id, secondaryRepo.id],
executor_profile_id: seedData.worktreeExecutorProfileId,
},
);
@@ -56,13 +66,13 @@ test.describe("mobile: multi-repository session picker", () => {
startedAt: "2026-01-01T00:01:00Z",
});
await expect(pill).toHaveAccessibleName(/Repository: E2E Repo/);
await expect(pill).toContainText("E2E Repo");
await expect(pill).toHaveAccessibleName(/Repository: Mobile primary/);
await expect(pill).toContainText("Mobile primary");
await pill.tap();
const primaryRow = testPage.getByTestId(`mobile-session-row-${task.session_id}`);
const secondaryRow = testPage.getByTestId(`mobile-session-row-${secondarySession.session_id}`);
await expect(primaryRow.getByText("E2E Repo", { exact: true })).toBeVisible();
await expect(primaryRow.getByText("Mobile primary", { exact: true })).toBeVisible();
await expect(secondaryRow.getByText("Mobile secondary", { exact: true })).toBeVisible();
await secondaryRow.tap();
@@ -572,23 +572,6 @@ test.describe("Branch refresh + filter", () => {
return;
}
// Resolve the seeded repo's name via the workspace API so we can select
// it explicitly — earlier specs in this worker may have registered extra
// repos in the same workspace, and we need the asserted ?refresh URL to
// be unambiguous.
const repoListRes = await apiClient.rawRequest(
"GET",
`/api/v1/workspaces/${seedData.workspaceId}/repositories`,
);
const repoList = (await repoListRes.json()) as {
repositories: Array<{ id: string; name: string }>;
};
const seededRepoName = repoList.repositories.find((r) => r.id === seedData.repositoryId)?.name;
if (!seededRepoName) {
test.skip(true, "Could not resolve seeded repository name");
return;
}
const kanban = new KanbanPage(testPage);
await kanban.goto();
await kanban.createTaskButton.first().click();
@@ -596,10 +579,9 @@ test.describe("Branch refresh + filter", () => {
await testPage.getByTestId("task-title-input").fill("Refresh button test");
await testPage.getByTestId("task-description-input").fill("triggers git fetch");
await testPage.getByTestId("repo-chip-trigger").first().click();
await testPage
.getByRole("option", { name: new RegExp(`^${escapeRe(seededRepoName)}\\b`, "i") })
.first()
.click();
// Repository names are not unique after earlier specs register additional
// worktrees. cmdk's stable data-value is the repository ID.
await testPage.locator(`[cmdk-item][data-value="${seedData.repositoryId}"]`).click();
// Worktree executor → branch selector enabled and refresh button visible.
await testPage.getByTestId("executor-profile-selector").click();
await testPage.getByRole("option", { name: worktreeProfileName }).click();
@@ -35,6 +35,18 @@ async function expectDiffText(testPage: Page, text: string, timeout = 45_000) {
test.describe("Mobile changes panel", () => {
test.describe.configure({ retries: 1, timeout: 120_000 });
test.beforeEach(({ backend }) => {
// The worker reuses its fixture repository across tests. Restore a clean
// working tree so staged/untracked files from an earlier scenario cannot
// move and remount the PR Changes section during async status hydration.
const git = new GitHelper(
path.join(backend.tmpDir, "repos", "e2e-repo"),
makeGitEnv(backend.tmpDir),
);
git.exec("git reset --hard HEAD");
git.exec("git clean -fd");
});
test("renders timeline surface and opens Diff/Review/file/commit overlays", async ({
testPage,
apiClient,
@@ -299,6 +311,13 @@ test.describe("Mobile changes panel", () => {
git.createFile("overlap-mobile.txt", "local change LOCAL_CHANGE_MARKER");
await openMobileChangesPanel(testPage);
// Wait for the local status refresh triggered by createFile before opening
// the PR section. Otherwise that refresh can remount the overlapping PR row
// while Playwright is dispatching the tap.
await expect(testPage.getByTestId("file-row-overlap-mobile.txt")).toBeVisible({
timeout: 20_000,
});
await expandSection(testPage, "pr-changes-section");
const prFilesList = testPage.getByTestId("pr-files-list");
@@ -209,8 +209,10 @@ test.describe("Mobile sidebar task actions", () => {
actions.boundingBox(),
]);
if (!diffBox || !actionBox) throw new Error("mobile task controls have no layout box");
expect(actionBox.width).toBeGreaterThanOrEqual(44);
expect(actionBox.height).toBeGreaterThanOrEqual(44);
// Chromium can report a 44px transformed box as 43.999969 CSS pixels.
// Compare physical CSS-pixel intent, not floating-point layout residue.
expect(Math.round(actionBox.width)).toBeGreaterThanOrEqual(44);
expect(Math.round(actionBox.height)).toBeGreaterThanOrEqual(44);
const overlapWidth =
Math.min(diffBox.x + diffBox.width, actionBox.x + actionBox.width) -
Math.max(diffBox.x, actionBox.x);
@@ -1,6 +1,46 @@
import { test, expect } from "../../fixtures/test-base";
import type { ApiClient } from "../../helpers/api-client";
import { SessionPage } from "../../pages/session-page";
type GitSnapshotResponse = {
snapshots: Array<{
metadata?: { branch_additions?: number; branch_deletions?: number };
}>;
};
async function waitForPersistedDiffSnapshot(apiClient: ApiClient, sessionId: string) {
await expect
.poll(
async () => {
const response = await apiClient.wsRequest<GitSnapshotResponse>("session.git.snapshots", {
session_id: sessionId,
limit: 1,
});
const metadata = response.snapshots[0]?.metadata;
return (metadata?.branch_additions ?? 0) + (metadata?.branch_deletions ?? 0);
},
{ timeout: 60_000, message: `Waiting for persisted diff snapshot for ${sessionId}` },
)
.toBeGreaterThan(0);
}
async function waitForPersistedTaskDiffSummary(
apiClient: ApiClient,
workspaceId: string,
taskId: string,
) {
await expect
.poll(
async () => {
const response = await apiClient.listTasks(workspaceId);
const git = response.tasks.find((task) => task.id === taskId)?.status_summary?.git;
return (git?.additions ?? 0) + (git?.deletions ?? 0);
},
{ timeout: 60_000, message: `Waiting for persisted diff summary for ${taskId}` },
)
.toBeGreaterThan(0);
}
/**
* Regression test for the task sidebar diff badge bug.
*
@@ -73,9 +113,23 @@ test.describe("Task sidebar diff stats", () => {
betaSession.chat.getByText("diff-update-setup complete", { exact: false }),
).toBeVisible({ timeout: 60_000 });
// Both tasks now have diffs and the live monitor has run at least once
// — meaning the orchestrator should have persisted a live_monitor
// snapshot row for each session via UpsertLatestLiveGitSnapshot.
if (!taskAlpha.session_id || !taskBeta.session_id) {
throw new Error("Diff tasks must start sessions");
}
// The mock response text is published before the ACP complete frame that
// captures the final git status. Establish that both snapshots are durable
// before restarting the backend, rather than racing that terminal frame.
await Promise.all([
waitForPersistedDiffSnapshot(apiClient, taskAlpha.session_id),
waitForPersistedDiffSnapshot(apiClient, taskBeta.session_id),
]);
// Snapshot persistence and task-summary projection are separate ordered
// writes. Restart only after the sidebar's own durable source reflects
// both snapshots; otherwise a stale non-null summary is validly reused.
await Promise.all([
waitForPersistedTaskDiffSummary(apiClient, seedData.workspaceId, taskAlpha.id),
waitForPersistedTaskDiffSummary(apiClient, seedData.workspaceId, taskBeta.id),
]);
// Restart the backend. This destroys all in-memory executions, so
// GetExecutionBySessionID will return nil for both sessions on the next
@@ -194,7 +194,7 @@ test.describe("Terminal agent (TUI passthrough)", () => {
// Terminal should show output from both auto-started step prompts.
// The mock TUI prints "Processed: <prompt>" for each stdin line it receives.
await session.expectPassthroughHasText("Analyze", 30_000);
await session.expectPassthroughHasText("Implement", 30_000);
await session.expectPassthroughHasText("Processed: Implement", 30_000);
// Stepper shows Review as current step after the full cascade
await expect(session.stepperStep("Review")).toHaveAttribute("aria-current", "step", {
@@ -252,8 +252,8 @@ test.describe("Terminal agent (TUI passthrough)", () => {
// Terminal shows output from Analyze step (before reset)
await session.expectPassthroughHasText("Analyze", 30_000);
// After context reset, Implement step prompt is delivered to the fresh process
await session.expectPassthroughHasText("Implement", 30_000);
// After context reset, the fresh process completes the Implement step prompt.
await session.expectPassthroughHasText("Processed: Implement", 30_000);
// Stepper shows Review as current step after the full cascade
await expect(session.stepperStep("Review")).toHaveAttribute("aria-current", "step", {
@@ -53,7 +53,16 @@ async function openTask(page: Page, title: string): Promise<SessionPage> {
async function clickNewTerminalInPlusMenu(page: Page, session: SessionPage) {
await session.addPanelButton().click();
await page.getByTestId("new-terminal-button").click();
const menu = page
.locator('[data-slot="dropdown-menu-content"]')
.filter({ has: page.getByTestId("new-terminal-button") });
await expect(menu).toBeVisible();
await menu.getByTestId("new-terminal-button").click();
// Radix keeps the portal mounted for its 100 ms close animation. Returning
// sooner lets a second trigger click land while the first menu is closing;
// that click is swallowed and leaves the dropdown closed. Wait for the
// captured portal to detach so callers can safely reopen the menu.
await expect(menu).toHaveCount(0);
}
test.describe("Terminals — dockview UI", () => {
@@ -1,9 +1,34 @@
import { test, expect } from "../../fixtures/test-base";
import { expectCancelToSettlePromptly } from "../../helpers/cancellation";
import { assertNoDocumentHorizontalOverflow } from "../../helpers/layout-assertions";
import { ApiClient } from "../../helpers/api-client";
import { SessionPage } from "../../pages/session-page";
import { WorkflowSettingsPage } from "../../pages/workflow-settings-page";
async function tapCancelButton(session: SessionPage) {
const button = session.activeChat().getByTestId("cancel-agent-button");
await expect(button).toBeVisible();
await expect(button).toBeEnabled();
await expect(button).toBeInViewport();
// Mobile Chromium can finish a compositor/hydration frame after the
// locator is visible. Retry the touch dispatch until the synchronous React
// cancelling state is observable; the two-second responsiveness assertion
// starts only after that state proves the request was accepted.
await expect(async () => {
await button.scrollIntoViewIfNeeded();
await button.tap();
await expect
.poll(
async () => {
if ((await button.count()) === 0) return true;
return button.isDisabled();
},
{ timeout: 1_000 },
)
.toBe(true);
}).toPass({ timeout: 6_000, intervals: [100, 250, 500] });
}
async function seedMobileCancellationWorkflow(apiClient: ApiClient, workspaceId: string) {
const workflow = await apiClient.createWorkflow(workspaceId, "Mobile Cancel Completion");
const inbox = await apiClient.createWorkflowStep(workflow.id, "Inbox", 0, {
@@ -12,7 +37,8 @@ async function seedMobileCancellationWorkflow(apiClient: ApiClient, workspaceId:
const working = await apiClient.createWorkflowStep(workflow.id, "Working", 1);
const done = await apiClient.createWorkflowStep(workflow.id, "Done", 2);
await apiClient.updateWorkflowStep(working.id, {
prompt: 'e2e:delay(8000)\ne2e:message("mobile cancelled turn marker")\n{{task_prompt}}',
prompt:
'e2e:message("mobile cancelable turn started")\ne2e:delay(8000)\ne2e:message("mobile cancelled turn marker")\n{{task_prompt}}',
events: {
on_enter: [{ type: "auto_start_agent" }],
on_turn_complete: [{ type: "move_to_step", config: { step_id: done.id } }],
@@ -98,10 +124,13 @@ test.describe("mobile: cancelled turn completion", () => {
})
.toBe(workflow.workingStepId);
await expect(session.cancelAgentButton()).toBeVisible({ timeout: 30_000 });
await expect(
session.activeChat().getByText("mobile cancelable turn started", { exact: false }),
).toBeVisible({ timeout: 15_000 });
expect((await apiClient.listTaskSessions(task.id)).sessions).toHaveLength(1);
await session.cancelAgentButton().tap();
await expect(session.cancelAgentButton()).not.toBeVisible({ timeout: 30_000 });
await tapCancelButton(session);
await expectCancelToSettlePromptly(session);
await expect
.poll(async () => (await apiClient.getTask(task.id)).workflow_step_id, {
timeout: 30_000,
@@ -305,6 +305,11 @@ test.describe("Workflow agent profile switching", () => {
)
.toBe(true);
// The backend can settle before this page's WS subscription observes the
// ready transition. Recover the persisted idle state before interacting
// with the editor instead of racing the boot-hydrated starting UI.
await session.waitForChatIdle({ timeout: 30_000 });
// User message → dispatchPromptAsync → on_turn_start → move_to_next → Step1 (profileB)
await session.sendMessage("hello");
await expect(session.chat.getByText("hello")).toBeVisible({ timeout: 10_000 });
@@ -225,8 +225,9 @@ test.describe("Workflow automation", () => {
// Session transitions to idle — plan mode input placeholder visible
await expect(session.planModeInput()).toBeVisible({ timeout: 15_000 });
// Sidebar shows the task under "Turn Finished" section
await expect(session.sidebarSection("Turn Finished")).toBeVisible();
// The active kanban projection must win over any stale all-workflow
// snapshot that was already in flight when the turn completed.
await expect(session.taskInSection("Plan Mode Workflow Task", "Turn Finished")).toBeVisible();
});
/**
@@ -2,6 +2,7 @@ import { expect } from "@playwright/test";
import type { Page } from "@playwright/test";
import { test as e2eTest } from "../../fixtures/test-base";
import { ApiClient } from "../../helpers/api-client";
import { expectCancelToSettlePromptly } from "../../helpers/cancellation";
import { SessionPage } from "../../pages/session-page";
type CancellationWorkflow = {
@@ -25,7 +26,8 @@ async function createCancellationWorkflow(
const done = await apiClient.createWorkflowStep(workflow.id, "Done", 2);
await apiClient.updateWorkflowStep(working.id, {
prompt: 'e2e:delay(8000)\ne2e:message("cancelled turn marker")\n{{task_prompt}}',
prompt:
'e2e:message("cancelable turn started")\ne2e:delay(8000)\ne2e:message("cancelled turn marker")\n{{task_prompt}}',
events: {
on_enter: [{ type: "auto_start_agent" }],
on_turn_complete: [{ type: "move_to_step", config: { step_id: done.id } }],
@@ -65,6 +67,11 @@ async function startWorkingTurn(
});
await expect(session.agentStatus()).toBeVisible({ timeout: 30_000 });
await expect(session.cancelAgentButton()).toBeVisible({ timeout: 15_000 });
await expect(
session.activeChat().getByText("cancelable turn started", { exact: false }),
).toBeVisible({
timeout: 15_000,
});
return { task, session };
}
@@ -92,7 +99,7 @@ e2eTest.describe("Cancelled turn completion", () => {
expect(sessionsBeforeCancel.sessions).toHaveLength(1);
await session.cancelAgentButton().click();
await expect(session.cancelAgentButton()).not.toBeVisible({ timeout: 30_000 });
await expectCancelToSettlePromptly(session);
await expect(session.stepperStep("Done")).toHaveAttribute("aria-current", "step", {
timeout: 30_000,
});
@@ -123,8 +130,7 @@ e2eTest.describe("Cancelled turn completion", () => {
expect((await apiClient.listTaskSessions(task.id)).sessions).toHaveLength(1);
await session.cancelAgentButton().click();
await expect(session.cancelAgentButton()).not.toBeVisible({ timeout: 30_000 });
await expect(session.idleInput()).toBeVisible({ timeout: 30_000 });
await expectCancelToSettlePromptly(session);
await expect(session.stepperStep("Working")).toHaveAttribute("aria-current", "step");
expect((await apiClient.getTask(task.id)).workflow_step_id).toBe(workflow.workingStepId);
@@ -322,21 +322,16 @@ test.describe("Workflow settings", () => {
});
test("modifies a step name only after Save", async ({ testPage, apiClient, seedData }) => {
const workflow = await apiClient.createWorkflow(seedData.workspaceId, "Step Rename Workflow");
const step = await apiClient.createWorkflowStep(workflow.id, "Original Step", 0);
const page = new WorkflowSettingsPage(testPage);
await page.goto(seedData.workspaceId);
// Use the first step name from seed data (same template)
const firstStepName = seedData.steps[0]?.name;
if (!firstStepName) {
test.skip(true, "No template steps available");
return;
}
const card = await page.findWorkflowCard("E2E Workflow");
const card = await page.findWorkflowCard(workflow.name);
await expect(card).toBeVisible();
// Click on the first step to open config panel
const stepNode = page.stepNodeByName(card, firstStepName);
const stepNode = page.stepNodeByName(card, step.name);
await stepNode.click();
// Find the step name input in the config panel and rename it
@@ -345,8 +340,8 @@ test.describe("Workflow settings", () => {
await expect(nameInput).toHaveAttribute("data-settings-dirty", "true");
await expect(card).toHaveAttribute("data-settings-dirty", "true");
const stepPanel = card.getByTestId(`workflow-step-panel-${seedData.steps[0].id}`);
const dirtyStepNode = card.getByTestId(`workflow-step-node-${seedData.steps[0].id}`);
const stepPanel = card.getByTestId(`workflow-step-panel-${step.id}`);
const dirtyStepNode = card.getByTestId(`workflow-step-node-${step.id}`);
await expect(stepPanel).toHaveAttribute("data-settings-dirty", "true");
await expect(card).toHaveAttribute("data-settings-dirty-level", "card");
@@ -359,16 +354,14 @@ test.describe("Workflow settings", () => {
expect(await maxRingSpread(stepPanel)).toBe(0);
expect(await maxRingSpread(dirtyStepNode)).toBe(0);
expect((await apiClient.listWorkflowSteps(seedData.workflowId)).steps[0]?.name).toBe(
firstStepName,
);
expect((await apiClient.listWorkflowSteps(workflow.id)).steps[0]?.name).toBe(step.name);
await page.saveChanges();
await expect(nameInput).toHaveAttribute("data-settings-dirty", "false");
await expect(card).toHaveAttribute("data-settings-dirty", "false");
await page.goto(seedData.workspaceId);
const reloadedCard = await page.findWorkflowCard("E2E Workflow");
const reloadedCard = await page.findWorkflowCard(workflow.name);
await expect(reloadedCard).toBeVisible();
await expect(reloadedCard.getByText("Renamed Step")).toBeVisible();
});
@@ -441,10 +434,11 @@ test.describe("Workflow settings", () => {
apiClient,
seedData,
}) => {
const workflow = await apiClient.createWorkflow(seedData.workspaceId, "Workflow Detail Save");
const page = new WorkflowSettingsPage(testPage);
await page.goto(seedData.workspaceId);
const card = await page.findWorkflowCard("E2E Workflow");
const card = await page.findWorkflowCard(workflow.name);
const nameInput = card.locator("input").first();
await nameInput.fill("Manually Saved Workflow Name");
@@ -453,9 +447,9 @@ test.describe("Workflow settings", () => {
expect(
(await apiClient.listWorkflows(seedData.workspaceId)).workflows.find(
(workflow) => workflow.id === seedData.workflowId,
(candidate) => candidate.id === workflow.id,
)?.name,
).toBe("E2E Workflow");
).toBe(workflow.name);
await expect(page.floatingSave).toBeVisible();
await page.saveChanges();
@@ -6,26 +6,31 @@ test.describe("Workflow sorting", () => {
const { workspaceId } = seedData;
await apiClient.e2eReset(workspaceId, [seedData.workflowId]);
// Create additional workflows
// Create every workflow asserted by this API-only test. The seeded
// workflow belongs to the worker fixture and can be removed by an earlier
// API-only reset because `testPage` (which normally resets state) is lazy.
const wfA = await apiClient.createWorkflow(workspaceId, "Workflow A", "simple");
const wfB = await apiClient.createWorkflow(workspaceId, "Workflow B", "simple");
const wfC = await apiClient.createWorkflow(workspaceId, "Workflow C", "simple");
const expectedNames = ["E2E Workflow", "Workflow B", "Workflow C"];
const workflowNames = new Set(expectedNames);
const expectedIds = [wfA.id, wfB.id, wfC.id];
const workflowIds = new Set(expectedIds);
// Verify initial order: sorted by sort_order ASC (0, 1, 2)
const before = await apiClient.listWorkflows(workspaceId);
const namesBefore = before.workflows
.map((w) => w.name)
.filter((name) => workflowNames.has(name));
expect(namesBefore).toEqual(expectedNames);
const idsBefore = before.workflows
.map((workflow) => workflow.id)
.filter((id) => workflowIds.has(id));
expect(idsBefore).toEqual(expectedIds);
// Reorder: C, E2E, B
await apiClient.reorderWorkflows(workspaceId, [wfC.id, seedData.workflowId, wfB.id]);
// Reorder: C, A, B
await apiClient.reorderWorkflows(workspaceId, [wfC.id, wfA.id, wfB.id]);
// Verify new order persists
const after = await apiClient.listWorkflows(workspaceId);
const namesAfter = after.workflows.map((w) => w.name).filter((name) => workflowNames.has(name));
expect(namesAfter).toEqual(["Workflow C", "E2E Workflow", "Workflow B"]);
const idsAfter = after.workflows
.map((workflow) => workflow.id)
.filter((id) => workflowIds.has(id));
expect(idsAfter).toEqual([wfC.id, wfA.id, wfB.id]);
});
test("settings page displays workflows in sort order", async ({
@@ -192,7 +192,7 @@ test.describe("Manual proceed to next workflow step", () => {
},
});
const workPrompt = "/slow 8s";
const workPrompt = "/slow 20s";
await apiClient.updateWorkflowStep(workStep.id, {
prompt: `${workPrompt}\n{{task_prompt}}`,
events: {
@@ -237,15 +237,21 @@ test.describe("Manual proceed to next workflow step", () => {
await expect(session.stepperStep("Work")).toHaveAttribute("aria-current", "step", {
timeout: 15_000,
});
await expect(
session.chat.locator(".chat-message-list:visible").getByText(workPrompt, { exact: false }),
).toBeVisible({ timeout: 5_000 });
await expect
.poll(wsDrop.droppedCount, {
message: "expected the test proxy to drop the workflow prompt's message-added frame",
timeout: 10_000,
})
.toBeGreaterThan(0);
await expect
.poll(wsDrop.recoveryResponseCount, {
message: "expected message backfill after the dropped workflow prompt notification",
timeout: 10_000,
})
.toBeGreaterThan(0);
await expect(
session.chat.locator(".chat-message-list:visible").getByText(workPrompt, { exact: false }),
).toBeVisible({ timeout: 5_000 });
});
/**
@@ -0,0 +1,139 @@
---
spec: docs/specs/workflow/cancelled-turn-completion/spec.md
created: 2026-08-03
status: complete
---
# Implementation Plan: Turn Cancellation Responsiveness
## Overview
Remove the cancellation/stream lock cycle without weakening the per-session serialization that protects coordinator stops and turn replacement. Use one backend-owned cancellation coordinator for explicit, silent, and peer cancellation sources, then tighten the existing desktop and mobile Playwright scenarios around the observable response-time contract. No ACP, WebSocket, persistence, or frontend component contract changes are required.
## Confirmed Root Cause
Commit `a100cb9169` made `handleAgentStreamEvent` acquire the same per-session `cancelInFlightGuard` that `Service.CancelAgent` holds while synchronously waiting in `agentManager.CancelAgent`. Codex accepts `session/cancel` and emits terminal frames in about 6 ms, but the ordered stream worker blocks on that guard before it can finish the prompt. Cancellation therefore waits for the lifecycle manager's 10-second `cancelWaitTimeout`; the fallback releases the cycle, producing the reproduced 10.37-second UI delay.
The smallest reliable regression is an orchestrator test whose mock lifecycle cancel does not return until a terminal stream callback completes. Current code times out because `CancelAgent` holds the callback's guard; the repaired code must let the callback finish, then reconcile the captured turn exactly once.
---
## Backend
### Unified cancellation operation ownership
Files:
- `apps/backend/internal/orchestrator/service.go`
- `apps/backend/internal/orchestrator/task_operations.go`
Changes:
- Replace the split explicit-user and silent cancellation markers with one per-session cancellation coordinator. Record the cancellation source, completion notification, result, and captured `(executionID, promptGeneration, turnID)` identity in one operation.
- Let the first authorized source own the operation. Concurrent explicit, silent, and peer requests join that operation; only the owner invokes the lifecycle manager, while joiners wait and then re-evaluate their source-specific queue or clarification action.
- Keep operation ownership active across the whole lifecycle wait and every reconciliation exit path. Remove the entry only after the owner publishes the final result, so the temporarily unlocked guard cannot admit a second user-cancel owner.
- Run the accepted operation with a bounded service-owned context derived from `context.WithoutCancel`; a disconnected caller stops waiting without aborting the shared lifecycle/reconciliation work.
- Preserve session authorization, tolerated `ErrNoExecutionForSession` and `ErrCancelEscalated` reconciliation, the visible cancel message, parked queued messages, workflow completion policy, and retry behavior after a settled operation.
### Two-phase per-session serialization
Files:
- `apps/backend/internal/orchestrator/task_operations.go`
- `apps/backend/internal/orchestrator/event_handlers_clarification.go`
- `apps/backend/internal/orchestrator/event_handlers_streaming.go`
Changes:
- Under `cancelInFlightGuard`, load the authoritative session and capture the active turn identity needed by cancellation bookkeeping. Retain the guard registry reference, but unlock its mutex before calling the blocking lifecycle cancel.
- While the mutex is released, keep cancellation intent/ownership active as an admission gate. Non-stream claimants (prompt claims, running/boot-ready, completion/failure, step completion, clarification cleanup, teardown, and fallback reset) must defer or drop their mutation; only ordered stream frames matching the captured execution/prompt generation may proceed.
- Allow the existing ordered stream handler to acquire the same guard and persist Codex's terminal usage, session-status, interruption-message, and completion frames. Do not bypass or remove the stream guard globally.
- Reacquire the guard after the lifecycle call returns, re-read the authoritative session and active turn, and reconcile only the captured cancellation generation. If a successor turn exists, fail closed or leave it untouched rather than closing it as part of the cancelled turn.
- Apply the same unlock-around-blocking-wait rule to silent clarification/peer-interrupt call sites that already enter lifecycle cancellation while owning the guard. Keep their distinct message, queue-drain, workflow, and visibility semantics unchanged.
- Leave `cancelWaitTimeout` and `cancelEscalationTimeout` unchanged; they remain the fallback for agents that do not finish after acknowledging cancellation.
---
## Frontend
### Existing shared cancel control
No production frontend change is planned. `chat-input-area.tsx` already awaits the existing `agent.cancel` response, and `chat-input-toolbar-primitives.tsx` already disables the shared cancel button and shows progress during that request. Once the backend response is no longer delayed by the lock cycle, both desktop and mobile controls settle promptly through the existing path; the 15-second client request timeout remains a transport fallback.
### Mobile design contract
- **Desktop outcome and mobile entry point:** both task-detail composers use the existing shared cancel control and leave the progress state promptly after acknowledged cancellation.
- **Nearest shipped exemplar:** `apps/web/e2e/tests/workflow/mobile-workflow-cancel-completion.spec.ts` already exercises the compact task composer by touch and is extended rather than adding a new surface.
- **Hierarchy and presentation:** unchanged inline composer control; no drawer, route, navigation, copy, or layout change.
- **Geometry and scrolling:** existing touch target, chat scroll ownership, safe-area behavior, and zero-horizontal-overflow contract remain unchanged.
- **Shared logic:** the same `SubmitButton` request state and backend operation serve desktop and mobile.
- **Mobile proof:** the existing `mobile-chrome` cancellation flow asserts the control and session settle inside the bounded responsiveness window.
---
## Tests
- **What:** acknowledged cancellation can receive terminal stream callbacks while the lifecycle cancel is waiting, then reconciles the captured turn exactly once.
**Files:** `apps/backend/internal/orchestrator/event_handlers_test.go`, `apps/backend/internal/orchestrator/task_operations_test.go`.
**How:** add a mock cancel hook that starts the real `handleAgentStreamEvent` callback and waits for it; use channel synchronization and a short context deadline so current code fails deterministically without a ten-second sleep.
- **What:** ordinary stream side effects still serialize with cancellation reconciliation outside the lifecycle wait.
**File:** `apps/backend/internal/orchestrator/event_handlers_streaming_test.go`.
**How:** retain and extend `TestAgentStreamEventWaitsForCancellationGuard` to prove the guard remains authoritative before snapshot and after lifecycle completion.
- **What:** concurrent user cancel requests join one operation and observe one result, message, turn closure, and completion evaluation.
**File:** `apps/backend/internal/orchestrator/task_operations_test.go`.
**How:** extend the existing channel-driven deduplication test for joining callers, shared result delivery, cleanup, and a later independent retry.
- **What:** cancellation cannot reconcile a successor turn created after the captured turn, and stale terminal frames cannot mutate it.
**Files:** `apps/backend/internal/orchestrator/task_operations_test.go`, `apps/backend/internal/orchestrator/event_handlers_streaming_test.go`.
**How:** stage turn replacement at the unlocked boundary and assert the captured-turn ownership check leaves the successor active.
- **What:** silent clarification and peer-interrupt cancellation do not reproduce the same stream/cancel cycle and preserve their existing no-visible-message or queue-delivery contracts.
**Files:** `apps/backend/internal/orchestrator/event_handlers_clarification_test.go`, `apps/backend/internal/orchestrator/task_operations_test.go`.
**How:** reuse channel-synchronized lifecycle hooks and existing semantic assertions.
- **What:** cancellation sources share one lifecycle call, a disconnected owner cannot abort a live joiner, and a peer message arriving during explicit cancellation remains queued.
**File:** `apps/backend/internal/orchestrator/task_operations_test.go`.
**How:** stage the lifecycle call with channels, race explicit/silent and silent/silent sources, cancel the owner context, and assert one manager call plus an undispatched queue entry.
## E2E Tests
- **Scenario:** a delayed mock-agent turn acknowledges cancellation and emits terminal events; the desktop cancel control disappears and the input becomes promptable within two seconds after those terminal frames, while enabled/disabled completion policy still advances or stays exactly once.
**File:** `apps/web/e2e/tests/workflow/workflow-cancel-completion.spec.ts`.
- **Scenario:** the same acknowledged cancellation settles through the compact composer within two seconds after terminal-frame publication when invoked by touch, while the existing mobile workflow transition and overflow assertions remain valid.
**File:** `apps/web/e2e/tests/workflow/mobile-workflow-cancel-completion.spec.ts`.
## Verification Results
- Backend RED/GREEN: the channel-synchronized stream-drain regression first failed on the old implementation because `CancelAgent` held the per-session guard while the lifecycle cancel waited for `handleAgentStreamEvent`; after the two-phase unlock, it passes without escalation. Cross-kind ownership, owner-disconnect, prompt/event admission, ready-vs-cancel parking, successor-turn ownership, silent cancellation, and ordinary stream-guard coverage are green.
- `cd apps/backend && go test ./internal/orchestrator -run 'Test(CancelAgent|CancellationSources|CancellationStreamAdmission|QueueAndInterruptForPeerMessage|CancelAgentSilent|AgentStreamEventWaitsForCancellationGuard)' -count=1` — focused regression suite passed.
- `cd apps/backend && go test ./internal/orchestrator -count=1 -timeout=180s` — passed after the final admission-gate and joined-source changes.
- `cd apps/backend && go test -race ./internal/orchestrator -run 'Test(CancellationSources|CancelAgent_JoinedSilentCancellationRunsExplicitReconciliation|CancelAgent_OwnerDisconnectDoesNotAbortJoinedOperation|CancelAgent_DefersLifecycleCompletionDuringCancellation|CancelAgentSilent_DoesNotCloseSuccessorTurn|QueueAndInterruptForPeerMessage_(ClosesStaleEarlyCheckRace|CancelFailureDoesNotStrandMessageWhenReadyIsRacing))' -count=1` — passed.
- `cd apps/backend && go test ./internal/agent/runtime/lifecycle ./internal/backendapp ./internal/orchestrator -count=1 -timeout=180s` — lifecycle and backendapp packages passed; orchestrator package was covered by the preceding full run.
- `cd apps/backend && go test ./... -count=1 -timeout=300s` — all backend packages passed.
- `cd apps && pnpm --filter @kandev/web run typecheck` — passed.
- `cd apps && pnpm --filter @kandev/web run lint` — passed.
- `cd apps && pnpm --filter @kandev/web run i18n:ratchet && pnpm --filter @kandev/web run i18n:check` — passed.
- `cd apps/backend && go test ./cmd/mock-agent -count=1` — package passed, including the cancellation-aware prompt fixture test.
- `cd apps/backend && go test ./internal/agent/runtime/lifecycle -run 'TestManager_CancelAgent_' -count=1` — lifecycle cancellation tests passed.
- `cd apps/web && pnpm run typecheck` — passed.
- `cd apps/web && pnpm run lint` — passed.
- Desktop E2E: `cd apps/web && pnpm e2e:run --no-build --project chromium tests/workflow/workflow-cancel-completion.spec.ts -- --retries=0` — 2 tests passed; both enabled and disabled completion-policy outcomes settled through the real cancel control.
- Mobile E2E: `cd apps/web && pnpm e2e:run --no-build --project mobile-chrome tests/workflow/mobile-workflow-cancel-completion.spec.ts -- --retries=0` — 1 test passed; touch entry, compact composer settlement, workflow transition, and overflow assertions passed. A final repeat with `--repeat-each=3 --workers=1` passed 3/3 after rebuilding the cancellation-aware mock agent.
- `git diff --check` — passed. No ACP protocol, WebSocket, persistence schema, public API, frontend production component, user-facing copy, or new trust boundary changed. Lifecycle cancellation timeouts remain unchanged.
## Implementation Waves And Parallel Candidates
Execution is sequential in the primary conversation; the E2E task depends on the backend behavior and neither task is parallel-safe.
Wave 1:
- [x] [Task 01: Break the cancellation stream cycle](task-01-break-cancellation-stream-cycle.md)
Wave 2:
- [x] [Task 02: Prove responsive cancellation end to end](task-02-prove-responsive-cancellation-e2e.md)
## Risks and Out of Scope
- The shared guard was introduced to prevent stream persistence from racing coordinator-stop and turn-replacement decisions. The fix must narrow its hold interval, not remove the guard or let stream handlers bypass it.
- Releasing the mutex during the lifecycle wait creates a deliberate concurrency window. Cancellation operation ownership and captured-turn revalidation are mandatory so duplicate requests, peer interrupts, or a successor prompt cannot steal that window.
- The pending `feature/when-i-have-a-task-w-ge1` branch also evolves backend cancellation ownership in `service.go` and `task_operations.go`. Implementation must reconcile that branch's backend-owned progress contract if it lands first; do not overwrite it or reintroduce a second independent registry.
- The retained ACP captures under `acp-debug/` are diagnostic evidence, not automated fixtures and do not need to ship with the fix.
- This plan does not reduce lifecycle timeouts, change ACP messages, synthesize completion, alter cancellation copy/layout, drain queued messages, or change workflow cancellation policy.
@@ -0,0 +1,85 @@
---
id: "01-break-cancellation-stream-cycle"
title: "Break the cancellation stream cycle"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/workflow/cancelled-turn-completion/spec.md"
---
# Task 01: Break the cancellation stream cycle
## Acceptance
- An acknowledged lifecycle cancellation can wait for terminal `handleAgentStreamEvent` callbacks without holding the callback's `cancelInFlightGuard`; the operation returns before the regression test's one-second deadline without using escalation.
- The owner reacquires the same guard and revalidates the captured turn before reconciliation. Terminal frames are persisted in order, the session becomes `WAITING_FOR_INPUT`, and cancellation message, turn closure, review/workflow behavior, and lifecycle cancel each occur exactly once.
- Explicit, silent clarification, and peer-interrupt requests share one per-session operation and lifecycle call; a disconnected owner cannot abort a live joiner, and joiners re-evaluate their source-specific action after settlement.
- Ordinary stream writes still wait on the guard outside the lifecycle wait, and a successor turn is never closed or mutated by the cancelled turn's reconciliation or stale frames.
## Verification
```bash
(
cd apps/backend
go test ./internal/orchestrator -run 'Test(CancelAgent|QueueAndInterruptForPeerMessage|CancelAgentSilent|AgentStreamEventWaitsForCancellationGuard)' -count=1
go test ./internal/orchestrator -count=1 -timeout=120s
go test -race ./internal/orchestrator -run 'Test(CancelAgent|QueueAndInterruptForPeerMessage|CancelAgentSilent|AgentStreamEventWaitsForCancellationGuard)' -count=1
go test ./cmd/mock-agent -count=1
go test ./internal/agent/runtime/lifecycle -run 'TestManager_CancelAgent_' -count=1
)
```
Follow TDD: first add the channel-synchronized stream callback regression and confirm it fails because the callback cannot acquire the guard; then implement operation ownership and the two-phase lock interval.
## Files likely touched
- `apps/backend/internal/orchestrator/service.go`
- `apps/backend/internal/orchestrator/task_operations.go`
- `apps/backend/internal/orchestrator/event_handlers_clarification.go`
- `apps/backend/internal/orchestrator/event_handlers_streaming.go`
- `apps/backend/internal/orchestrator/event_handlers_test.go`
- `apps/backend/internal/orchestrator/task_operations_test.go`
- `apps/backend/internal/orchestrator/event_handlers_clarification_test.go`
- `apps/backend/internal/orchestrator/event_handlers_streaming_test.go`
## Dependencies
None.
## Parallelism
Sequential. This task owns the shared per-session cancellation registry and guard semantics; Task 02 validates its completed behavior.
## Inputs
- Spec: prompt cancellation responsiveness, ordered terminal-frame persistence, duplicate-operation, and stale-successor scenarios.
- Plan: `Confirmed Root Cause`, `Explicit cancellation operation ownership`, and `Two-phase per-session serialization`.
- Reproduction evidence: `acp-debug/codex-acp-cancel-20260803-171437.jsonl` and the isolated 10.37-second browser/backend trace summarized in the task plan.
- Existing patterns: `beginCancelInFlight`, `isCancelInFlight`, `acquireCancelInFlightGuard`, `peekActiveTurnID`, `completeTurnIfCurrent`, and the channel-driven cancellation race tests.
## Risks
- Do not replace the shared guard with an unguarded stream fast path.
- Do not hold the guard while waiting on code that requires ordered stream callbacks.
- If backend-owned cancellation progress from `feature/when-i-have-a-task-w-ge1` is present, extend its operation record instead of adding a competing registry or changing its public projection.
## Output contract
Report the operation ownership/result semantics, Red/Green evidence, exact files and commands, lifecycle timeout behavior, duplicate and successor-turn evidence, blockers/risks, and synchronize this task plus `plan.md` in the same primary conversation.
## Results
- Replaced split explicit/silent cancellation markers with one per-session coordinator shared by explicit, silent clarification, and peer interrupts. The owner alone invokes lifecycle cancellation; joiners wait and then re-check their source-specific action.
- Accepted cancellation work now uses a bounded service-owned context (`context.WithoutCancel`), so an owner request disconnect cannot abort a live joiner.
- Added cancellation admission gates for prompt claims, running/boot-ready, completion/failure, step-completion, clarification cleanup, teardown, fallback reset, and stale stream identities.
- Split the per-session guard interval around the blocking lifecycle cancel. ACP terminal stream callbacks can acquire the guard, persist ordered frames, and release it before cancellation reconciliation reacquires it.
- Captured and revalidated the cancelled turn identity; successor turns fail closed and remain active. Ready, boot-ready, queue-drain, peer-interrupt, and clarification paths retain their serialization and cancellation semantics.
- RED/GREEN regression: the channel-synchronized stream callback failed against the old held-lock implementation and passes with the two-phase unlock, without reaching lifecycle escalation.
- `cd apps/backend && go test ./internal/orchestrator -run 'Test(CancelAgent|CancellationSources|CancellationStreamAdmission|QueueAndInterruptForPeerMessage|CancelAgentSilent|AgentStreamEventWaitsForCancellationGuard)' -count=1` — focused ownership/admission suite passed.
- `cd apps/backend && go test ./internal/orchestrator -count=1 -timeout=180s` — passed after the final admission-gate and joined-source changes.
- `cd apps/backend && go test -race ./internal/orchestrator -run 'Test(CancellationSources|CancelAgent_JoinedSilentCancellationRunsExplicitReconciliation|CancelAgent_OwnerDisconnectDoesNotAbortJoinedOperation|CancelAgent_DefersLifecycleCompletionDuringCancellation|CancelAgentSilent_DoesNotCloseSuccessorTurn|QueueAndInterruptForPeerMessage_(ClosesStaleEarlyCheckRace|CancelFailureDoesNotStrandMessageWhenReadyIsRacing))' -count=1` — passed.
- `cd apps/backend && go test ./... -count=1 -timeout=300s` — all backend packages passed.
- `cd apps/backend && go test ./cmd/mock-agent -count=1` — package passed.
- `cd apps/backend && go test ./internal/agent/runtime/lifecycle -run 'TestManager_CancelAgent_' -count=1` — lifecycle cancellation tests passed.
- `git diff --check` — passed. No schema, public API, ACP message, lifecycle timeout, external side effect, or new trust boundary was introduced.
@@ -0,0 +1,74 @@
---
id: "02-prove-responsive-cancellation-e2e"
title: "Prove responsive cancellation end to end"
status: done
wave: 2
depends_on: ["01-break-cancellation-stream-cycle"]
plan: "plan.md"
spec: "../../specs/workflow/cancelled-turn-completion/spec.md"
---
# Task 02: Prove responsive cancellation end to end
## Acceptance
- The existing desktop delayed-turn scenario proves the real cancel control and input settle within two seconds after cancellation acknowledgement and terminal-frame publication while enabled and disabled workflow completion policies still produce their existing single outcomes.
- The existing `mobile-chrome` scenario invokes the shared control by touch and proves the same post-acknowledgement two-second outcome without changing mobile composition, touch geometry, scroll ownership, or overflow behavior.
- The test uses deterministic mock-agent cancellation and locator/event assertions, not fixed sleeps, a live Codex credential, or a relaxed 10-30-second timeout that would hide the regression.
## Verification
```bash
(
cd apps
pnpm install --frozen-lockfile
cd web
pnpm e2e:run tests/workflow/workflow-cancel-completion.spec.ts
pnpm e2e:run --no-build --project mobile-chrome tests/workflow/mobile-workflow-cancel-completion.spec.ts -- --repeat-each=3 --workers=1
)
```
## Files likely touched
- `apps/web/e2e/tests/workflow/workflow-cancel-completion.spec.ts`
- `apps/web/e2e/tests/workflow/mobile-workflow-cancel-completion.spec.ts`
- `apps/web/e2e/helpers/cancellation.ts`
- `apps/backend/cmd/mock-agent/main.go`
- `apps/backend/cmd/mock-agent/handler.go`
- `apps/backend/cmd/mock-agent/script.go`
- `apps/backend/cmd/mock-agent/mock_agent_test.go`
- `apps/backend/cmd/mock-agent/script_test.go`
## Dependencies
Task 01.
## Parallelism
Sequential. The test is meaningful only after the backend operation and guard semantics are fixed.
## Inputs
- Spec: acknowledged-cancellation responsiveness and existing completion-policy scenarios.
- Plan: `Existing shared cancel control`, `Mobile design contract`, and `E2E Tests`.
- Nearest shipped mobile exemplar: the current mobile cancelled-turn completion spec and shared `SubmitButton` touch path.
## Risks
- Build fresh artifacts before the first Playwright run; the second command may reuse them with `--no-build`.
- Bound only the cancellation settlement assertion. Keep workflow-transition assertions at their existing event-driven timeouts so unrelated CI scheduling does not masquerade as a responsiveness failure.
- Do not add production delays, test-only endpoints, hardcoded credentials, new copy, or viewport-specific product logic.
## Output contract
Report desktop/mobile scenarios, discovered test counts, exact commands, generated Playwright artifacts, cleanup evidence, residual timing risk, and synchronize this task plus `plan.md` in the same primary conversation.
## Results
- Tightened the existing desktop and mobile cancellation scenarios to assert that the cancel control leaves its progress state and the input becomes promptable within two seconds after cancellation acknowledgement and terminal-frame publication. Workflow transition assertions retain their event-driven timeouts.
- Moved the shared cancellation settle timeout and assertion into `apps/web/e2e/helpers/cancellation.ts` so desktop and mobile cannot drift.
- Made the delayed mock-agent script honor prompt cancellation so the fixture emits terminal ACP frames promptly instead of waiting for an artificial delay after cancellation. Added a focused context-cancellation unit test and rebuilt `apps/backend/bin/mock-agent`.
- Desktop: `cd apps/web && pnpm e2e:run --no-build --project chromium tests/workflow/workflow-cancel-completion.spec.ts -- --retries=0` — 2 tests passed.
- Mobile: `cd apps/web && pnpm e2e:run --no-build --project mobile-chrome tests/workflow/mobile-workflow-cancel-completion.spec.ts -- --retries=0` — 1 test passed. A final repeat with `--repeat-each=3 --workers=1` passed 3/3 after rebuilding the cancellation-aware mock agent.
- The mobile flow uses touch assertions, viewport containment, and the existing no-horizontal-overflow check. No production frontend component or copy changed; no screenshots/traces were checked in, and managed E2E teardown completed.
- `cd apps/web && pnpm run typecheck` and `cd apps/web && pnpm run lint` — passed. `git diff --check` — passed.
+1 -1
View File
@@ -82,7 +82,7 @@ Kandev's task model: documents, execution stages, labels, blocker escalation, su
| [task-create-executor-default](tasks/task-create-executor-default.md) | approved |
| [sidebar-task-edit](tasks/sidebar-task-edit.md) | approved |
| [explicit-completion-signal](workflow/explicit-completion-signal/spec.md) | shipped |
| [cancelled-turn-completion](workflow/cancelled-turn-completion/spec.md) | shipped |
| [cancelled-turn-completion](workflow/cancelled-turn-completion/spec.md) | building |
| [conditional-session-settings](workflow-session-settings/spec.md) | approved |
## agents/ — agent governance
@@ -1,5 +1,5 @@
---
status: shipped
status: building
created: 2026-08-02
owner: kandev
---
@@ -21,6 +21,10 @@ Cancelling an active Kanban agent turn currently stops the agent and marks the r
- A configured user cancellation reuses the ordinary `on_turn_complete` action pipeline. It runs source-step `on_exit`, applies at most one transition, and runs destination-step `on_enter` with the same first-transition-wins and side-effect behavior as a normal completed turn.
- A configured user cancellation is a human completion decision and does not require `step_complete_kandev`, even when `auto_advance_requires_signal=true`. A pending clarification remains a hard barrier and still blocks the transition.
- Cancellation keeps the current session and conversation context. It records the existing cancellation status message, durably confirms `WAITING_FOR_INPUT` and closes every active turn before evaluating completion, leaves queued user messages parked, and ignores the cancelled turn's later stale ready/completion events.
- Once the agent acknowledges cancellation and publishes its terminal turn frames, the visible cancel request completes without waiting for the lifecycle escalation timeout. In the deterministic local regression environment, the shared desktop/mobile cancel control leaves its cancelling state within two seconds of that acknowledgement.
- Terminal frames emitted while cancellation is pending retain their normal ordered persistence before cancellation reconciliation. Concurrent cancel requests for the same session join one backend-owned operation and cannot duplicate the lifecycle cancel, status message, turn closure, or workflow completion.
- Explicit user cancellation, silent clarification recovery, and peer-message interruption share that same per-session operation. Only its owner invokes lifecycle cancellation; joined callers wait and then re-evaluate their own queue or clarification action.
- Once authorization and admission succeed, the shared operation uses a bounded service-owned context. A caller that disconnects may stop waiting without aborting cancellation or causing a live joiner to inherit its context error.
- If completion actions do not produce a transition, cannot be evaluated safely, or are blocked by pending user input, the task remains on the current workflow step and retains the existing `WAITING_FOR_INPUT` / review-ready reconciliation.
- If completion reaches a terminal workflow step, the task receives the same completed state as an ordinary `on_turn_complete` transition without an intermediate `REVIEW` state write.
- The workflow settings UI shows the option only when the step has an `on_turn_complete` transition. Its help text explains that destination `on_enter` actions may immediately start another agent.
@@ -73,11 +77,14 @@ No new permission is introduced. The caller must already be authorized to cancel
## Failure Modes
- If the runtime cancel returns a non-recoverable error, the cancel request fails and Kandev does not reconcile the session or evaluate completion actions.
- If the agent acknowledges cancellation and emits terminal frames, those frames must be allowed to drain through the normal ordered stream path; cancellation must not hold a serialization boundary that the terminal path itself needs in order to finish.
- If the agent acknowledges the cancel but does not finish the turn, the existing bounded lifecycle timeout and escalation path still applies. Fast acknowledged cancellation does not shorten or remove that fallback.
- If no live execution exists or the runtime cancellation must be escalated, Kandev performs its existing safe reconciliation. Because the user cancellation was accepted, an enabled step may still evaluate completion actions.
- If the task is archived, ephemeral, Office-owned, missing its workflow step, or the current step cannot be loaded, Kandev does not move it through this policy.
- If the session cannot be authoritatively persisted as `WAITING_FOR_INPUT`, or any active turn cannot be closed and verified, Kandev returns the cancellation reconciliation error and does not evaluate `on_turn_complete`, move the workflow, or launch destination `on_enter` actions.
- If workflow evaluation or persistence fails, Kandev leaves the session input-ready on the current workflow step and surfaces the failure through existing logs and workflow state.
- A stale `agent.ready` or `agent.completed` event emitted after cancellation cannot run the transition a second time because the reconciled session no longer owns a running turn.
- While cancellation is admitted, non-stream prompt/state claimants defer or drop their mutations, and stream frames are accepted only when their execution and prompt generation match the captured cancellation identity. A successor prompt or stale completion therefore cannot be closed by the cancelled turn.
- Destination `on_enter` behavior is not suppressed. If it contains `auto_start_agent`, cancellation can intentionally start work on the destination step; the settings help text must disclose this consequence.
## Persistence Guarantees
@@ -99,6 +106,11 @@ Template defaults apply when a workflow's steps are instantiated. Changing the e
- **GIVEN** an enabled step with a queued user message, **WHEN** the user cancels, **THEN** the workflow transition may run but the queued message remains parked until an existing explicit drain or destination behavior consumes work.
- **GIVEN** an internal clarification timeout, peer interrupt, parent stop, archive, runtime failure, or provider error, **WHEN** that path cancels or stops an agent turn, **THEN** it does not run cancellation-driven completion actions.
- **GIVEN** a runtime cancel that is escalated or finds no live execution, **WHEN** Kandev safely reconciles the user's cancel request, **THEN** an enabled step evaluates completion once and the session does not remain stuck running.
- **GIVEN** an agent that acknowledges cancellation and immediately emits its terminal stream frames, **WHEN** the user cancels the active turn, **THEN** the cancel request settles without reaching the lifecycle escalation timeout and the shared desktop/mobile control leaves its cancelling state within two seconds in the deterministic local regression environment.
- **GIVEN** terminal usage, session-status, interruption-message, and completion frames emitted for the cancelled turn, **WHEN** cancellation is settling, **THEN** the frames drain in order before reconciliation and no frame can close or mutate a later successor turn.
- **GIVEN** multiple cancel requests for the same active turn, **WHEN** the first request is still waiting for terminal frames, **THEN** all requests observe the same operation result while the lifecycle cancel, visible cancellation message, turn closure, and completion policy run exactly once.
- **GIVEN** explicit and silent cancellation sources race for one active turn, **WHEN** both arrive before lifecycle cancellation settles, **THEN** exactly one lifecycle cancel runs and each source re-evaluates its own follow-up action after the shared result.
- **GIVEN** the explicit cancel caller disconnects while a second caller remains connected, **WHEN** lifecycle cancellation is still in progress, **THEN** the service-owned operation continues and the connected caller receives its final result.
- **GIVEN** the standard Kanban template, **WHEN** a new workflow is created from it, **THEN** `Backlog` and `In Progress` have `cancel_triggers_turn_complete=true` and cancellation moves work to `Review` through their existing actions.
- **GIVEN** an existing persisted standard Kanban workflow, **WHEN** Kandev upgrades, **THEN** its stored setting remains `false` until a user enables it.
- **GIVEN** an exported workflow with the setting enabled, **WHEN** it is imported or synchronized, **THEN** the imported step retains the enabled value.
@@ -111,3 +123,4 @@ Template defaults apply when a workflow's steps are instantiated. Changing the e
- Changing queued-message drain policy after cancellation.
- Treating agent errors, provider failures, crashes, task stops, or clarification pauses as successful completion.
- Adding cancellation-cause metadata to workflow transition history.
- Reducing the existing lifecycle timeout for agents that acknowledge cancellation but never finish their prompt, or synthesizing success before their terminal path settles.