Stop background tasks separately from chat turns
Keep Esc and /stop scoped to the foreground turn while exposing an explicit stop-tasks operation for supported chat backends. Add the protocol, server routing, app command, and coverage for task stopping and unsupported harnesses.
This commit is contained in:
@@ -426,6 +426,44 @@ func (c *Chat) Interrupt(ctx context.Context, id string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// StopTasks uses Claude Code's separate stop_task control request. It does not
|
||||
// send interrupt, so the foreground turn and its queued prompts remain alive.
|
||||
func (c *Chat) StopTasks(ctx context.Context, id string) (int, error) {
|
||||
s := c.session(id)
|
||||
if s == nil {
|
||||
return 0, nil
|
||||
}
|
||||
s.awaitReady(ctx)
|
||||
s.mu.Lock()
|
||||
proc := s.proc
|
||||
var tasks []string
|
||||
for toolID, snapshot := range s.shells {
|
||||
if !snapshot.background || snapshot.shell.Status != protocol.ChatShellRunning {
|
||||
continue
|
||||
}
|
||||
taskID := snapshot.taskID
|
||||
if taskID == "" {
|
||||
taskID = toolID
|
||||
}
|
||||
tasks = append(tasks, taskID)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if proc == nil {
|
||||
return 0, nil
|
||||
}
|
||||
stopped := 0
|
||||
for _, taskID := range tasks {
|
||||
requestCtx, cancel := context.WithTimeout(ctx, controlRequestTimeout)
|
||||
_, err := proc.request(requestCtx, "stop_task", map[string]any{"task_id": taskID})
|
||||
cancel()
|
||||
if err != nil {
|
||||
return stopped, err
|
||||
}
|
||||
stopped++
|
||||
}
|
||||
return stopped, nil
|
||||
}
|
||||
|
||||
// ActivateSkill has no out-of-band equivalent in Claude Code; skills resolve
|
||||
// through the CLI's own /skill mechanism.
|
||||
func (c *Chat) ActivateSkill(context.Context, string, string) error {
|
||||
|
||||
@@ -257,6 +257,57 @@ func TestInterruptSettlesTheTurn(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInterruptLeavesBackgroundTaskAndStopTasksEndsIt(t *testing.T) {
|
||||
chat := testChat(t)
|
||||
session := newCreatedChat(t, chat)
|
||||
if err := chat.Prompt(context.Background(), session.ID, "background task"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
eventually(t, "background shell", func() bool {
|
||||
shells, err := chat.Shells(context.Background(), session.ID)
|
||||
return err == nil && len(shells) == 1 && shells[0].Status == protocol.ChatShellRunning
|
||||
})
|
||||
|
||||
// The fake turn has already yielded its result, so mark the session running
|
||||
// to exercise the same control path used by an active foreground turn.
|
||||
s := chat.session(session.ID)
|
||||
s.mu.Lock()
|
||||
s.running = true
|
||||
s.mu.Unlock()
|
||||
if err := chat.Interrupt(context.Background(), session.ID); err != nil {
|
||||
t.Fatalf("interrupt: %v", err)
|
||||
}
|
||||
if shells, err := chat.Shells(context.Background(), session.ID); err != nil || len(shells) != 1 || shells[0].Status != protocol.ChatShellRunning {
|
||||
t.Fatalf("interrupt ended background task: shells=%+v err=%v", shells, err)
|
||||
}
|
||||
|
||||
// A foreground tool may still be running while the operator stops
|
||||
// background work. It must not be included in the stop_task requests.
|
||||
s.mu.Lock()
|
||||
s.shells["toolu_foreground"] = &shellSnapshot{
|
||||
shell: protocol.ChatShell{
|
||||
ID: "toolu_foreground",
|
||||
Status: protocol.ChatShellRunning,
|
||||
Command: "foreground command",
|
||||
},
|
||||
}
|
||||
s.mu.Unlock()
|
||||
stopped, err := chat.StopTasks(context.Background(), session.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("stop tasks: %v", err)
|
||||
}
|
||||
if stopped != 1 {
|
||||
t.Fatalf("stopped tasks = %d, want only the background task", stopped)
|
||||
}
|
||||
eventually(t, "stopped shell", func() bool {
|
||||
shells, err := chat.Shells(context.Background(), session.ID)
|
||||
if err != nil || len(shells) != 1 {
|
||||
return false
|
||||
}
|
||||
return shells[0].ID == "toolu_foreground" && shells[0].Status == protocol.ChatShellRunning
|
||||
})
|
||||
}
|
||||
|
||||
func TestModelChoiceIsAppliedAndProcessResumes(t *testing.T) {
|
||||
chat := testChat(t)
|
||||
session := newCreatedChat(t, chat)
|
||||
|
||||
+5
@@ -243,6 +243,11 @@ def handle(line):
|
||||
state["pending"] = None
|
||||
send({"type": "result", "subtype": "error_during_execution", "is_error": True,
|
||||
"result": "Interrupted", "session_id": state["session"]})
|
||||
elif subtype == "stop_task":
|
||||
respond(value.get("request_id"), {})
|
||||
send({"type": "system", "subtype": "task_notification",
|
||||
"task_id": request.get("task_id"), "tool_use_id": "toolu_bg_fake",
|
||||
"status": "stopped", "summary": "Background task stopped"})
|
||||
elif subtype == "get_usage":
|
||||
respond(value.get("request_id"), {"session": {
|
||||
"total_cost_usd": 0.25,
|
||||
|
||||
@@ -550,6 +550,10 @@ func (c *Chat) Interrupt(ctx context.Context, id string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Chat) StopTasks(context.Context, string) (int, error) {
|
||||
return 0, errors.New("Codex does not expose a separate background-task stop operation")
|
||||
}
|
||||
|
||||
// ReleaseSession stops an active Codex turn while preserving the thread and
|
||||
// its transcript. Codex has no separate per-thread process to reap.
|
||||
func (c *Chat) ReleaseSession(ctx context.Context, id string) error {
|
||||
|
||||
@@ -322,6 +322,26 @@ func (c *Chat) Interrupt(ctx context.Context, id string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// StopTasks terminates background shell operations, without interrupting the
|
||||
// session's foreground turn.
|
||||
func (c *Chat) StopTasks(ctx context.Context, id string) (int, error) {
|
||||
shells, err := c.Shells(ctx, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
stopped := 0
|
||||
for _, shell := range shells {
|
||||
if shell.Status != protocol.ChatShellRunning {
|
||||
continue
|
||||
}
|
||||
if _, err := c.call(ctx, "delete", "/api/shell/"+url.PathEscape(shell.ID), nil); err != nil {
|
||||
return stopped, fmt.Errorf("stop shell %s: %w", shell.ID, err)
|
||||
}
|
||||
stopped++
|
||||
}
|
||||
return stopped, nil
|
||||
}
|
||||
|
||||
// ReleaseSession stops active and background work for an explicit operator
|
||||
// close or /new without deleting the persisted native conversation. OpenCode
|
||||
// interrupt only stops the foreground drain; running shells are separate native
|
||||
|
||||
@@ -410,6 +410,42 @@ func TestChatReleaseSessionStopsRunningShells(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatStopTasksDeletesOnlyRunningShells(t *testing.T) {
|
||||
var requests []string
|
||||
var mu sync.Mutex
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
requests = append(requests, r.Method+" "+r.URL.Path)
|
||||
mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/api/shell":
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"sh_running","status":"running","metadata":{"sessionID":"ses_1"}},{"id":"sh_done","status":"exited","metadata":{"sessionID":"ses_1"}}]}`))
|
||||
case "/api/shell/sh_running":
|
||||
_, _ = w.Write([]byte(`{}`))
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
stopped, err := chat.StopTasks(context.Background(), "ses_1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stopped != 1 {
|
||||
t.Fatalf("stopped = %d, want 1", stopped)
|
||||
}
|
||||
mu.Lock()
|
||||
got := append([]string(nil), requests...)
|
||||
mu.Unlock()
|
||||
want := []string{"GET /api/shell", "DELETE /api/shell/sh_running"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("stop requests = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDecodeChatMessages loads a seeded user + assistant session in both
|
||||
// response envelopes the two surfaces return and asserts the turns come back
|
||||
// with role, id, part order, part ids and the completed tool's input, content
|
||||
|
||||
@@ -28,6 +28,9 @@ const (
|
||||
ChatPrompt = "chat_prompt"
|
||||
ChatMessages = "chat_messages"
|
||||
ChatInterrupt = "chat_interrupt"
|
||||
// ChatStopTasks stops background tasks without interrupting the current turn.
|
||||
// Older clients ignore this additive command.
|
||||
ChatStopTasks = "chat_stop_tasks"
|
||||
ChatReply = "chat_reply"
|
||||
// ChatClose finishes an operator session and records it as closed on the
|
||||
// server: any in-flight turn is interrupted through the existing interrupt,
|
||||
@@ -149,6 +152,13 @@ const (
|
||||
ChatPermission = "chat_permission"
|
||||
)
|
||||
|
||||
// ChatStopTasksResult reports the result of an explicit background-task stop.
|
||||
type ChatStopTasksResult struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Stopped int `json:"stopped"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
const (
|
||||
ChatAutomationSupported = "supported"
|
||||
ChatAutomationUnavailable = "unavailable"
|
||||
|
||||
@@ -262,8 +262,9 @@ type Message struct {
|
||||
// body names the session like ChatQuery. A chat_prompt response sets
|
||||
// ChatQueued when the prompt had to wait for an in-flight turn and was
|
||||
// accepted into the session's queue instead of being sent immediately.
|
||||
ChatSubscribe *ChatQuery `json:"chat_subscribe,omitempty"`
|
||||
ChatQueued bool `json:"chat_queued,omitempty"`
|
||||
ChatSubscribe *ChatQuery `json:"chat_subscribe,omitempty"`
|
||||
ChatQueued bool `json:"chat_queued,omitempty"`
|
||||
ChatStopTasks *ChatStopTasksResult `json:"chat_stop_tasks,omitempty"`
|
||||
// ChatSteered means the prompt was handed to the turn already running; its
|
||||
// reply is that turn's continuing output.
|
||||
ChatSteered bool `json:"chat_steered,omitempty"`
|
||||
|
||||
@@ -49,6 +49,10 @@ type chatPromptWithMessageID interface {
|
||||
PromptWithMessageID(context.Context, string, string, string) error
|
||||
}
|
||||
|
||||
type chatTaskStopper interface {
|
||||
StopTasks(context.Context, string) (int, error)
|
||||
}
|
||||
|
||||
// chatPromptWithFiles is implemented by a broker that can hand local files to
|
||||
// the agent with a prompt. The server writes browser attachment bytes to private
|
||||
// temporary files first; a browser URI is not readable by the agent service.
|
||||
@@ -195,6 +199,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
case protocol.ChatInterrupt:
|
||||
handleChatSimple(ctx, request, broker, hub, write)
|
||||
return true
|
||||
case protocol.ChatStopTasks:
|
||||
handleChatStopTasks(ctx, request, broker, write)
|
||||
return true
|
||||
case protocol.ChatReply:
|
||||
handleChatSimple(ctx, request, broker, hub, write)
|
||||
return true
|
||||
|
||||
@@ -746,6 +746,18 @@ func (m *chatManager) Shells(ctx context.Context, sessionID string) ([]protocol.
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *chatManager) StopTasks(ctx context.Context, sessionID string) (int, error) {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
stopper, ok := adapter.(chatTaskStopper)
|
||||
if !ok {
|
||||
return 0, errors.New("this chat backend cannot stop background tasks separately")
|
||||
}
|
||||
return stopper.StopTasks(ctx, sessionID)
|
||||
}
|
||||
|
||||
func (m *chatManager) Reply(ctx context.Context, request protocol.ChatReplyRequest) error {
|
||||
adapter, err := m.brokerFor(ctx, request.SessionID)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func handleChatStopTasks(ctx context.Context, request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
|
||||
query := request.ChatQuery
|
||||
if query == nil || !validChatSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"})
|
||||
return
|
||||
}
|
||||
if broker == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
|
||||
return
|
||||
}
|
||||
stopper, ok := broker.(chatTaskStopper)
|
||||
if !ok {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "this chat backend cannot stop background tasks separately"})
|
||||
return
|
||||
}
|
||||
stopped, err := stopper.StopTasks(ctx, query.SessionID)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
message := "No background tasks are running in this chat."
|
||||
if stopped > 0 {
|
||||
message = "Stopped background tasks."
|
||||
}
|
||||
_ = write(protocol.Message{
|
||||
Type: protocol.ChatStopTasks, ID: request.ID,
|
||||
ChatStopTasks: &protocol.ChatStopTasksResult{
|
||||
SessionID: query.SessionID, Stopped: stopped, Message: message,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -211,6 +211,16 @@ func (f *fakeChat) Interrupt(context.Context, string) error {
|
||||
return f.interruptErr
|
||||
}
|
||||
|
||||
type fakeTaskStopChat struct {
|
||||
*fakeChat
|
||||
stopped int
|
||||
}
|
||||
|
||||
func (f *fakeTaskStopChat) StopTasks(context.Context, string) (int, error) {
|
||||
f.stopped++
|
||||
return f.stopped, nil
|
||||
}
|
||||
|
||||
func (f *fakeChat) ReleaseSession(_ context.Context, sessionID string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
@@ -850,6 +860,27 @@ func TestChatInterruptAndReply(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatStopTasksRepliesWithStoppedCount(t *testing.T) {
|
||||
broker := &fakeTaskStopChat{fakeChat: scriptedChat()}
|
||||
ctx, _, conn := dialChat(t, broker)
|
||||
if err := wsjson.Write(ctx, conn, protocol.Message{
|
||||
Type: protocol.ChatStopTasks, ID: "st1",
|
||||
ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response protocol.Message
|
||||
if err := readTestFrame(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Type != protocol.ChatStopTasks || response.ID != "st1" || response.ChatStopTasks == nil {
|
||||
t.Fatalf("stop tasks response = %+v", response)
|
||||
}
|
||||
if response.ChatStopTasks.Stopped != 1 || response.ChatStopTasks.Message != "Stopped background tasks." {
|
||||
t.Fatalf("stop tasks result = %+v", response.ChatStopTasks)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatInterruptEndsRunningPrompt is the task evidence: it starts a
|
||||
// long-running turn through the real opencode.Chat adapter over an httptest SSE
|
||||
// fixture, sends chat_interrupt, and asserts the run ends. The fixture records
|
||||
|
||||
Reference in New Issue
Block a user