From e7d39254e7599672f1c7bf081287cadb49d90822 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 29 Jul 2026 19:19:04 +1000 Subject: [PATCH] feat: make /stop reach running agent tasks /stop cancelled the chat turn but could not touch a task the daemon was executing, and /cancel refused outright: case statusRunning: return fmt.Errorf("task is actively running; cannot cancel until it reaches a waiting state") So the one case worth interrupting was the one case neither command would touch. The daemon now holds a cancel function for every executing task, registered in process() -- the single point every dispatch path reaches -- so a task is stoppable for its whole life, including the slow clone, worktree prepare and image pull that is exactly when someone realises they asked for the wrong thing. - /cancel interrupts the work first, then records the terminal state. That order matters: writing the state while the task still runs invites it to write its own afterwards and win. A task the store calls running that nothing is executing (crashed daemon) still gets its state recorded, which is what unsticks it. - bare /stop now stops the reply, the queue behind it, and every running task for the identity, reporting which of those it actually did. Nobody reaching for the brake should have to look up a task ID first. - StopRunning deliberately writes no terminal state: a stopped task unwinds to parked, which is resumable. Forcing rejected would discard work worth keeping. - Without a runtime wired, cancelling a running task is still refused -- recording it as cancelled while it carries on would be a lie. Container teardown detaches from the task context. Release runs on the way out, and the main reason a task is on its way out is cancellation -- at which point the graceful ContainerStop failed instantly and the container was left to the forced remove. Cleanup gets its own deadline. process() gained two statements and crossed the funlen limit, so the container setup block is extracted rather than suppressed. --- cmd/archied/main.go | 6 ++ internal/channels/telegram/dangerous.go | 73 +++++++++++--- internal/container/pool.go | 8 +- internal/daemon/daemon.go | 104 +++++++++++++------- internal/daemon/running.go | 120 ++++++++++++++++++++++++ internal/daemon/running_test.go | 114 ++++++++++++++++++++++ internal/gateway/gateway.go | 13 ++- internal/gateway/gateway_test.go | 9 ++ internal/gateway/tasks.go | 53 ++++++++++- internal/gateway/tasks_test.go | 90 +++++++++++++++++- internal/gateway/turns_test.go | 3 +- 11 files changed, 533 insertions(+), 60 deletions(-) create mode 100644 internal/daemon/running.go create mode 100644 internal/daemon/running_test.go diff --git a/cmd/archied/main.go b/cmd/archied/main.go index f5e571570..ad8dbc397 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -581,6 +581,12 @@ func run() int { Identities: identityRunners, } + // Give /cancel and /stop a handle on work already in flight. The + // controller is built before the daemon exists, so the runtime is + // attached here; gateways start further down, after d.Startup, so no + // command can arrive before this is wired. + chatController.WithRuntime(d) + defer func() { stopCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() diff --git a/internal/channels/telegram/dangerous.go b/internal/channels/telegram/dangerous.go index f97ada7ff..0f8dc89d3 100644 --- a/internal/channels/telegram/dangerous.go +++ b/internal/channels/telegram/dangerous.go @@ -436,18 +436,69 @@ func (g *Gateway) stopCurrentTurn(ctx context.Context, b *bot.Bot, msg *models.M g.log.Info("stop requested", "session", session, "cancelled", cancelled, "dropped", dropped) } - switch { - case cancelled && dropped > 0: - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, - fmt.Sprintf("🛑 Stopped. %d queued message(s) discarded.", dropped)) - case cancelled: - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "🛑 Stopped.") - case dropped > 0: - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, - fmt.Sprintf("🛑 Nothing was running. %d queued message(s) discarded.", dropped)) + // The brake covers agent tasks as well as the conversation. Someone + // reaching for it wants everything to stop, and should not have to + // know a task ID -- or which of the two is currently misbehaving. + stoppedTasks := g.stopRunningTasks(ctx, router) + + g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, + stopReport(cancelled, dropped, stoppedTasks)) +} + +// stopRunningTasks interrupts the agent tasks currently executing and +// returns their IDs. A failure here is logged and reported as none +// stopped: /stop must still do whatever else it can. +func (g *Gateway) stopRunningTasks(ctx context.Context, router *gateway.Router) []int64 { + if router == nil || router.Controller == nil { + return nil + } + stopped, err := router.Controller.StopRunning(ctx, router.Identity) + if err != nil { + g.log.Warn("stop running tasks failed", "error", err) + return nil + } + if len(stopped) > 0 { + g.log.Info("stopped running tasks", "tasks", stopped) + } + return stopped +} + +// stopReport describes what a /stop actually stopped. +// +// It names the parts rather than saying "stopped" unconditionally. +// Claiming success when nothing was running teaches the operator to +// distrust the command at exactly the moment they need to believe it. +func stopReport(cancelled bool, dropped int, tasks []int64) string { + var parts []string + if cancelled { + parts = append(parts, "the running reply") + } + if dropped > 0 { + parts = append(parts, fmt.Sprintf("%d queued message(s)", dropped)) + } + if len(tasks) > 0 { + ids := make([]string, len(tasks)) + for i, id := range tasks { + ids[i] = fmt.Sprintf("#%d", id) + } + parts = append(parts, "task(s) "+strings.Join(ids, ", ")) + } + + if len(parts) == 0 { + return "Nothing is running.\n\nUse /stop to terminate a background process." + } + return "🛑 Stopped " + joinWithAnd(parts) + "." +} + +// joinWithAnd renders a list the way it would be read aloud. +func joinWithAnd(parts []string) string { + switch len(parts) { + case 1: + return parts[0] + case 2: + return parts[0] + " and " + parts[1] default: - g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, - "Nothing is running.\n\nUse /stop to terminate a background process.") + return strings.Join(parts[:len(parts)-1], ", ") + " and " + parts[len(parts)-1] } } diff --git a/internal/container/pool.go b/internal/container/pool.go index 74d0a35e2..d94e57560 100644 --- a/internal/container/pool.go +++ b/internal/container/pool.go @@ -218,7 +218,13 @@ func (p *Pool) Release(ctx context.Context, c *Container) { time.Sleep(p.cfg.GracePeriod) } - stopCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + // Detach from ctx before stopping. Release runs on the way out of a + // task, and the most important reason a task is on its way out is + // that it was cancelled -- at which point ctx is already dead, the + // graceful stop fails immediately, and the container is left to the + // forced remove below. Teardown is cleanup, so it gets its own + // deadline rather than inheriting the caller's cancellation. + stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) defer cancel() if _, err := p.cli.ContainerStop(stopCtx, c.ID, client.ContainerStopOptions{}); err != nil { diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 3f7598f31..222b2765b 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -111,6 +111,11 @@ type Daemon struct { // and passed as CaptureTools in agent requests. Nil means no dynamic // tool discovery (backward compatible). ToolRegistry *tools.Registry + + // running holds a cancel function for every task currently executing, + // so /stop can reach work already in flight. Its zero value is ready + // to use. + running runningTasks } // memoryPrompt returns the memory manager's system prompt block, or an empty @@ -898,6 +903,14 @@ func clip(s string, n int) string { } func (d *Daemon) process(ctx context.Context, task *store.Task) { + // Register before any work starts so the task is stoppable for its + // whole life, including the slow setup -- clone, worktree prepare, + // image pull -- which is exactly when someone realises they asked for + // the wrong thing. Every caller reaches execution through here, so + // this is the one place that has to do it. + ctx, finished := d.running.begin(ctx, task.ID, task.Identity) + defer finished() + fg := d.forgeFor(task) trees := d.treesFor(task) repo, ok := d.repoFor(task) @@ -948,42 +961,8 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) { // Acquire a container for the task when Docker sandboxing is enabled. if d.ContainerPool != nil { - // Write task.json -- the container's boot-time brief. - if err := container.WriteTaskJSON(workDir, container.TaskPayload{ - ID: task.ID, Owner: task.Owner, Repo: task.Repo, - Number: task.IssueNumber, Title: task.Title, Body: task.Body, - Labels: strings.Split(task.Labels, ","), - Workflow: task.Workflow, Branch: task.Branch, Plan: task.Plan, - }); err != nil { - d.Log.Error("task.json write failed", "err", err) - _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "task.json write failed: "+err.Error()) - return - } - - // Build the mount list from the storage backend. - // Guard: Storage may be nil if the daemon was wired incorrectly. - // In normal operation, Storage is always set when ContainerPool is set. - if d.Storage == nil { - d.Log.Error("storage backend is nil -- cannot acquire container") - _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "storage backend not configured") - return - } - mounts, err := d.Storage.Setup(ctx, storage.TaskRef{ - WorktreeDir: workDir, - Ecosystem: repo.Ecosystem, - PersistentStorage: repo.PersistentStorage, - Owner: task.Owner, - Repo: task.Repo, - }) - if err != nil { - d.Log.Error("storage setup failed", "err", err) - _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "storage setup failed: "+err.Error()) - return - } - ctr, err := d.ContainerPool.Acquire(ctx, mounts, d.containerEnv()) - if err != nil { - d.Log.Error("container acquire failed", "err", err) - _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "container acquire failed: "+err.Error()) + ctr, ok := d.acquireTaskContainer(ctx, task, repo, workDir) + if !ok { return } defer d.ContainerPool.Release(ctx, ctr) @@ -1040,6 +1019,59 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) { } } +// acquireTaskContainer prepares and acquires the sandbox container for a +// task, reporting false when it could not -- having already parked the +// task and logged why. The caller releases the container it returns. +func (d *Daemon) acquireTaskContainer( + ctx context.Context, + task *store.Task, + repo config.Repo, + workDir string, +) (*container.Container, bool) { + park := func(reason string, err error) { + d.Log.Error(reason, "err", err) + _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, reason+": "+err.Error()) + } + + // Write task.json -- the container's boot-time brief. + if err := container.WriteTaskJSON(workDir, container.TaskPayload{ + ID: task.ID, Owner: task.Owner, Repo: task.Repo, + Number: task.IssueNumber, Title: task.Title, Body: task.Body, + Labels: strings.Split(task.Labels, ","), + Workflow: task.Workflow, Branch: task.Branch, Plan: task.Plan, + }); err != nil { + park("task.json write failed", err) + return nil, false + } + + // Guard: Storage may be nil if the daemon was wired incorrectly. In + // normal operation, Storage is always set when ContainerPool is set. + if d.Storage == nil { + d.Log.Error("storage backend is nil -- cannot acquire container") + _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "storage backend not configured") + return nil, false + } + + mounts, err := d.Storage.Setup(ctx, storage.TaskRef{ + WorktreeDir: workDir, + Ecosystem: repo.Ecosystem, + PersistentStorage: repo.PersistentStorage, + Owner: task.Owner, + Repo: task.Repo, + }) + if err != nil { + park("storage setup failed", err) + return nil, false + } + + ctr, err := d.ContainerPool.Acquire(ctx, mounts, d.containerEnv()) + if err != nil { + park("container acquire failed", err) + return nil, false + } + return ctr, true +} + // containerEnv returns the environment variables passed to agent containers. // runViaAgent publishes a full-task handoff to archie-agent over // archie.taskrun. and waits for its completion report. Every durable diff --git a/internal/daemon/running.go b/internal/daemon/running.go new file mode 100644 index 000000000..5d9026246 --- /dev/null +++ b/internal/daemon/running.go @@ -0,0 +1,120 @@ +package daemon + +import ( + "context" + "sort" + "sync" +) + +// RunningTask identifies a task the daemon is currently executing. +type RunningTask struct { + ID int64 + Identity string +} + +// runningTasks tracks the tasks currently executing so they can be stopped +// on request. +// +// A task's cancel function is the only handle that reaches work already in +// flight. Without it the store can record that a task was cancelled while +// the task carries on -- which is what /cancel did: it refused outright +// when a task was running, so the one case worth interrupting was the one +// case it would not touch. +type runningTasks struct { + mu sync.Mutex + entries map[int64]*runningEntry +} + +type runningEntry struct { + identity string + cancel context.CancelFunc +} + +// begin registers a task as running and returns a context that [stop] can +// cancel, together with the function that retires it. +func (r *runningTasks) begin(ctx context.Context, id int64, identity string) (context.Context, func()) { + taskCtx, cancel := context.WithCancel(ctx) + + r.mu.Lock() + if r.entries == nil { + r.entries = make(map[int64]*runningEntry) + } + r.entries[id] = &runningEntry{identity: identity, cancel: cancel} + r.mu.Unlock() + + return taskCtx, func() { + r.mu.Lock() + delete(r.entries, id) + r.mu.Unlock() + cancel() + } +} + +// stop cancels one running task, reporting whether it was running. +func (r *runningTasks) stop(id int64) bool { + r.mu.Lock() + entry, ok := r.entries[id] + r.mu.Unlock() + if !ok { + return false + } + entry.cancel() + return true +} + +// stopAll cancels every running task belonging to identity, or all of them +// when identity is empty. It returns the IDs it cancelled, in order. +func (r *runningTasks) stopAll(identity string) []int64 { + r.mu.Lock() + var ( + ids []int64 + cancels []context.CancelFunc + ) + for id, entry := range r.entries { + if identity != "" && entry.identity != identity { + continue + } + ids = append(ids, id) + cancels = append(cancels, entry.cancel) + } + r.mu.Unlock() + + // Cancel outside the lock: a cancel can synchronously unwind a task + // whose cleanup calls back in here to retire itself. + for _, cancel := range cancels { + cancel() + } + sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] }) + return ids +} + +// list returns the tasks currently running, for reporting. +func (r *runningTasks) list() []RunningTask { + r.mu.Lock() + defer r.mu.Unlock() + + out := make([]RunningTask, 0, len(r.entries)) + for id, entry := range r.entries { + out = append(out, RunningTask{ID: id, Identity: entry.identity}) + } + sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) + return out +} + +// CancelTask stops a task that is currently executing, reporting whether +// it was running. A task that is not running is not an error here: the +// caller decides what a miss means. +func (d *Daemon) CancelTask(id int64) bool { + return d.running.stop(id) +} + +// CancelRunningTasks stops every task running for identity, or all of them +// when identity is empty, and returns the IDs it stopped. +func (d *Daemon) CancelRunningTasks(identity string) []int64 { + return d.running.stopAll(identity) +} + +// RunningTasks lists the tasks currently executing. +func (d *Daemon) RunningTasks() []RunningTask { + return d.running.list() +} diff --git a/internal/daemon/running_test.go b/internal/daemon/running_test.go new file mode 100644 index 000000000..85cab6df2 --- /dev/null +++ b/internal/daemon/running_test.go @@ -0,0 +1,114 @@ +package daemon + +import ( + "context" + "errors" + "testing" + "time" +) + +// TestRunningTaskIsInterruptible is the guarantee /stop rests on for +// agents. Cancelling a task must reach the work in flight, not merely +// record an intention in the store. +func TestRunningTaskIsInterruptible(t *testing.T) { + t.Parallel() + + var r runningTasks + started := make(chan struct{}) + observed := make(chan error, 1) + + go func() { + taskCtx, finished := r.begin(context.Background(), 7, "archie") + defer finished() + close(started) + <-taskCtx.Done() + observed <- taskCtx.Err() + }() + <-started + + if !r.stop(7) { + t.Fatal("stop reported that task 7 was not running") + } + select { + case err := <-observed: + if !errors.Is(err, context.Canceled) { + t.Errorf("task context error = %v, want context.Canceled", err) + } + case <-time.After(2 * time.Second): + t.Fatal("the task never observed cancellation") + } +} + +// TestStopUnknownTaskIsReported keeps a stale store row distinguishable +// from a live task: the caller has to be able to tell the difference to +// decide whether recording a terminal state is safe. +func TestStopUnknownTaskIsReported(t *testing.T) { + t.Parallel() + + var r runningTasks + if r.stop(99) { + t.Error("stop claimed to cancel a task that was never running") + } +} + +// TestFinishedTaskIsNotCancellable guards the retirement in begin's +// cleanup. A stale entry would let a later /stop report success against a +// task that had already completed. +func TestFinishedTaskIsNotCancellable(t *testing.T) { + t.Parallel() + + var r runningTasks + _, finished := r.begin(context.Background(), 3, "archie") + finished() + + if r.stop(3) { + t.Error("a completed task was reported as stopped") + } + if got := r.list(); len(got) != 0 { + t.Errorf("list() = %v, want empty after the task finished", got) + } +} + +// TestStopAllIsIdentityScoped keeps one identity's /stop from reaching +// another's work. +func TestStopAllIsIdentityScoped(t *testing.T) { + t.Parallel() + + var r runningTasks + base := context.Background() + + first, doneFirst := r.begin(base, 1, "archie") + defer doneFirst() + other, doneOther := r.begin(base, 2, "winter") + defer doneOther() + third, doneThird := r.begin(base, 3, "archie") + defer doneThird() + + stopped := r.stopAll("archie") + if len(stopped) != 2 || stopped[0] != 1 || stopped[1] != 3 { + t.Fatalf("stopAll = %v, want [1 3] in order", stopped) + } + if other.Err() != nil { + t.Error("another identity's task was cancelled") + } + if first.Err() == nil || third.Err() == nil { + t.Error("a task reported as stopped still has a live context") + } +} + +// TestStopAllEmptyIdentityStopsEverything covers the operator-wide brake. +func TestStopAllEmptyIdentityStopsEverything(t *testing.T) { + t.Parallel() + + var r runningTasks + base := context.Background() + + _, doneArchie := r.begin(base, 1, "archie") + defer doneArchie() + _, doneWinter := r.begin(base, 2, "winter") + defer doneWinter() + + if got := r.stopAll(""); len(got) != 2 { + t.Errorf("stopAll(\"\") = %v, want both tasks", got) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 6adfea873..b36407387 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -132,11 +132,16 @@ type TaskController interface { // error (surfaced to the user, not the LLM) if the task doesn't // exist, isn't owned by identity, or isn't in waiting_human. Approve(ctx context.Context, taskID int64, identity string) error - // Cancel moves an active (non-terminal, non-running) task to a - // rejected/cancelled terminal state. Returns an error if the task - // doesn't exist, isn't owned by identity, or is already terminal - // or actively running. + // Cancel moves an active task to a rejected/cancelled terminal + // state, interrupting it first if it is running. Returns an error if + // the task doesn't exist, isn't owned by identity, or is already + // terminal. Cancel(ctx context.Context, taskID int64, identity string) error + // StopRunning interrupts every task currently executing for + // identity and returns the IDs it stopped. It is the agent half of + // /stop, so it must not require knowing a task ID: someone reaching + // for the brake is not in a position to look one up. + StopRunning(ctx context.Context, identity string) ([]int64, error) } // Router dispatches inbound messages. Gateway-local commands (like diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index f34a5dc71..335925603 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -453,6 +453,10 @@ type fakeTaskController struct { approved []int64 cancelled []int64 identities []string + + stopRunning []int64 + stopRunningErr error + stoppedIdentities []string } func (f *fakeTaskController) Approve(ctx context.Context, taskID int64, identity string) error { @@ -473,6 +477,11 @@ func (f *fakeTaskController) Cancel(ctx context.Context, taskID int64, identity return nil } +func (f *fakeTaskController) StopRunning(_ context.Context, identity string) ([]int64, error) { + f.stoppedIdentities = append(f.stoppedIdentities, identity) + return f.stopRunning, f.stopRunningErr +} + func TestRouteApproveParsesIdentity(t *testing.T) { fc := &fakeTaskController{} r := NewRouter(nil, nil, "test-gw") diff --git a/internal/gateway/tasks.go b/internal/gateway/tasks.go index 4d86b62df..d303dfc6e 100644 --- a/internal/gateway/tasks.go +++ b/internal/gateway/tasks.go @@ -172,11 +172,27 @@ type chatTaskController interface { CancelChatTask(ctx context.Context, taskID int64, reason string) error } +// TaskRuntime reaches tasks that are currently executing. The daemon +// implements it; the store cannot, because a row records what a task is +// meant to be doing, not the goroutine doing it. +type TaskRuntime interface { + // CancelTask interrupts one running task, reporting whether it was + // running. + CancelTask(taskID int64) bool + // CancelRunningTasks interrupts every task running for identity, or + // all of them when identity is empty, returning the IDs stopped. + CancelRunningTasks(identity string) []int64 +} + // StoreTaskController implements TaskController backed by a store // interface. Authorization requires the caller identity to exactly // match the task identity, including the empty legacy identity. type StoreTaskController struct { store chatTaskController + // runtime interrupts running work. Nil leaves running tasks + // uninterruptible, which is the pre-existing behaviour and is + // reported as such rather than silently succeeding. + runtime TaskRuntime } // NewStoreTaskController returns a TaskController backed by c. @@ -184,6 +200,12 @@ func NewStoreTaskController(c chatTaskController) *StoreTaskController { return &StoreTaskController{store: c} } +// WithRuntime returns a controller that can also interrupt running tasks. +func (c *StoreTaskController) WithRuntime(rt TaskRuntime) *StoreTaskController { + c.runtime = rt + return c +} + func (c *StoreTaskController) Approve(ctx context.Context, taskID int64, identity string) error { st, err := c.authorize(ctx, taskID, identity) if err != nil { @@ -201,14 +223,41 @@ func (c *StoreTaskController) Cancel(ctx context.Context, taskID int64, identity return err } switch st.Status { - case statusRunning: - return fmt.Errorf("task is actively running; cannot cancel until it reaches a waiting state") case statusMerged, statusParked, statusRejected, statusDead, statusClosedWontDo: return fmt.Errorf("task is already %s", st.Status) + case statusRunning: + // Cancelling a running task used to be refused outright, which + // left the only case worth interrupting as the one case that + // could not be. Interrupt the work first, then record it: the + // order matters, because writing the terminal state while the + // task is still executing invites it to write its own state + // afterwards and win. + if c.runtime == nil { + return fmt.Errorf("task is running and no runtime control is configured") + } + if !c.runtime.CancelTask(taskID) { + // The store says running but nothing is executing -- a + // crashed or migrated daemon. Recording the terminal state + // is still right, and is what unsticks the task. + break + } } return c.store.CancelChatTask(ctx, taskID, "cancelled via chat by "+identity) } +// StopRunning interrupts every task executing for identity. +// +// It deliberately does not write terminal states. A stopped task unwinds +// through its own error paths and lands wherever that leaves it, usually +// parked, which is recoverable. Forcing every one to rejected would +// discard work the operator may well want to resume. +func (c *StoreTaskController) StopRunning(_ context.Context, identity string) ([]int64, error) { + if c.runtime == nil { + return nil, fmt.Errorf("no runtime control is configured") + } + return c.runtime.CancelRunningTasks(identity), nil +} + func (c *StoreTaskController) authorize(ctx context.Context, taskID int64, identity string) (ChatTaskStatus, error) { st, ok, err := c.store.ChatTaskStatus(ctx, taskID) if err != nil { diff --git a/internal/gateway/tasks_test.go b/internal/gateway/tasks_test.go index 5c4055b36..d56938ac2 100644 --- a/internal/gateway/tasks_test.go +++ b/internal/gateway/tasks_test.go @@ -275,15 +275,97 @@ func TestStoreTaskControllerCancelActiveStates(t *testing.T) { } } -func TestStoreTaskControllerCancelRejectsRunning(t *testing.T) { +// fakeTaskRuntime records the interruptions a controller asks for. +type fakeTaskRuntime struct { + cancelled []int64 + running bool + stopped []int64 + identity string +} + +func (f *fakeTaskRuntime) CancelTask(taskID int64) bool { + f.cancelled = append(f.cancelled, taskID) + return f.running +} + +func (f *fakeTaskRuntime) CancelRunningTasks(identity string) []int64 { + f.identity = identity + return f.stopped +} + +// TestStoreTaskControllerCancelInterruptsRunning covers the case that used +// to be refused. A running task is the only one worth interrupting, so +// cancelling it must reach the work and then record the outcome. +func TestStoreTaskControllerCancelInterruptsRunning(t *testing.T) { + store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: statusRunning}}} + rt := &fakeTaskRuntime{running: true} + c := NewStoreTaskController(store).WithRuntime(rt) + + if err := c.Cancel(context.Background(), 1, ""); err != nil { + t.Fatalf("Cancel: %v", err) + } + if len(rt.cancelled) != 1 || rt.cancelled[0] != 1 { + t.Errorf("runtime cancellations = %v, want [1]; the task kept running", rt.cancelled) + } + if len(store.cancelled) != 1 { + t.Error("the cancellation was not recorded in the store") + } +} + +// TestStoreTaskControllerCancelRecordsStaleRunning covers a task the store +// calls running that nothing is executing -- a crashed or replaced daemon. +// Recording the terminal state is what unsticks it. +func TestStoreTaskControllerCancelRecordsStaleRunning(t *testing.T) { + store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: statusRunning}}} + rt := &fakeTaskRuntime{running: false} + c := NewStoreTaskController(store).WithRuntime(rt) + + if err := c.Cancel(context.Background(), 1, ""); err != nil { + t.Fatalf("Cancel: %v", err) + } + if len(store.cancelled) != 1 { + t.Error("a stale running task was left stuck") + } +} + +// TestStoreTaskControllerCancelWithoutRuntimeRefusesRunning keeps the +// refusal honest when nothing can interrupt the work: recording the task +// as cancelled while it carries on would be a lie. +func TestStoreTaskControllerCancelWithoutRuntimeRefusesRunning(t *testing.T) { store := &fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{1: {Status: statusRunning}}} c := NewStoreTaskController(store) + err := c.Cancel(context.Background(), 1, "") - if err == nil || !strings.Contains(err.Error(), "actively running") { - t.Errorf("err = %v, want running-task rejection", err) + if err == nil || !strings.Contains(err.Error(), "no runtime control") { + t.Errorf("err = %v, want a refusal naming the missing runtime", err) } if len(store.cancelled) != 0 { - t.Error("CancelChatTask must not be called for a running task") + t.Error("CancelChatTask must not be called when the task cannot be interrupted") + } +} + +// TestStoreTaskControllerStopRunningIsIdentityScoped checks the agent half +// of /stop reaches the runtime and stays within the caller's identity. +func TestStoreTaskControllerStopRunningIsIdentityScoped(t *testing.T) { + rt := &fakeTaskRuntime{stopped: []int64{4, 7}} + c := NewStoreTaskController(&fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{}}).WithRuntime(rt) + + stopped, err := c.StopRunning(context.Background(), "archie") + if err != nil { + t.Fatalf("StopRunning: %v", err) + } + if len(stopped) != 2 || stopped[0] != 4 || stopped[1] != 7 { + t.Errorf("stopped = %v, want [4 7]", stopped) + } + if rt.identity != "archie" { + t.Errorf("identity = %q, want the caller's identity", rt.identity) + } +} + +func TestStoreTaskControllerStopRunningWithoutRuntime(t *testing.T) { + c := NewStoreTaskController(&fakeChatTaskStore{statuses: map[int64]ChatTaskStatus{}}) + if _, err := c.StopRunning(context.Background(), ""); err == nil { + t.Error("StopRunning reported success with no runtime wired") } } diff --git a/internal/gateway/turns_test.go b/internal/gateway/turns_test.go index c58617d42..36f582a5f 100644 --- a/internal/gateway/turns_test.go +++ b/internal/gateway/turns_test.go @@ -3,7 +3,6 @@ package gateway_test import ( "context" "errors" - "io" "log/slog" "sync" "sync/atomic" @@ -15,7 +14,7 @@ import ( func testTurns(t *testing.T) *gateway.Turns { t.Helper() - return gateway.NewTurns(slog.New(slog.NewTextHandler(io.Discard, nil))) + return gateway.NewTurns(slog.New(slog.DiscardHandler)) } // TestSubmitDoesNotBlockCaller is the whole reason this type exists: the