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:
2026-11-13 16:47:41 +00:00
parent c3c2c1bbc9
commit 2a182d7f17
19 changed files with 331 additions and 2 deletions
@@ -596,6 +596,9 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
} else { } else {
_showCommandNotice('No turn is running in this chat.', failed: true); _showCommandNotice('No turn is running in this chat.', failed: true);
} }
} else if (command.name == chatCommandStopTasks) {
_consumeCommandDraft();
unawaited(_stopTasksFromCommand());
} else if (command.name == chatCommandHelp) { } else if (command.name == chatCommandHelp) {
_consumeCommandDraft(); _consumeCommandDraft();
_showCommandNotice(chatCommandHelpText()); _showCommandNotice(chatCommandHelpText());
@@ -624,6 +627,16 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
_showCommandNotice(chatStopCommandNotice); _showCommandNotice(chatStopCommandNotice);
} }
Future<void> _stopTasksFromCommand() async {
try {
if (mounted) {
_showCommandNotice(await widget.composer.stopTasks());
}
} catch (error) {
if (mounted) _showCommandNotice('$error', failed: true);
}
}
void _consumeCommandDraft() { void _consumeCommandDraft() {
_text.clear(); _text.clear();
unawaited(widget.composer.setDraft('')); unawaited(widget.composer.setDraft(''));
@@ -373,6 +373,17 @@ class ChatComposerController extends ChangeNotifier {
} }
} }
/// Stops background tasks without interrupting the current turn.
Future<String> stopTasks() async {
final reply = await _repository.stopTasks(sessionId);
final result = reply['chat_stop_tasks'];
if (result is Map) {
final message = '${result['message'] ?? ''}'.trim();
if (message.isNotEmpty) return message;
}
return 'Background tasks stop request accepted.';
}
/// Follows the server's queue report: a prompt it lists is the server's /// Follows the server's queue report: a prompt it lists is the server's
/// (any stored device copy is dropped) and shows "Queued"; one that left /// (any stored device copy is dropped) and shows "Queued"; one that left
/// the queue shows what happened to it. /// the queue shows what happened to it.
@@ -272,6 +272,11 @@ class ChatRepository {
'chat_query': {'session_id': sessionId}, 'chat_query': {'session_id': sessionId},
}); });
Future<JsonMap> stopTasks(String sessionId) =>
gateway.call('chat_stop_tasks', {
'chat_query': {'session_id': sessionId},
});
/// Removes one prompt the server still holds in the session's queue. The /// Removes one prompt the server still holds in the session's queue. The
/// reply's `chat_queue` is the queue afterwards; a prompt already handed to /// reply's `chat_queue` is the queue afterwards; a prompt already handed to
/// the harness is refused. /// the harness is refused.
@@ -25,6 +25,7 @@ const String chatCommandNew = 'new';
const String chatCommandClose = 'close'; const String chatCommandClose = 'close';
const String chatCommandRename = 'rename'; const String chatCommandRename = 'rename';
const String chatCommandStop = 'stop'; const String chatCommandStop = 'stop';
const String chatCommandStopTasks = 'stop_tasks';
const String chatCommandHelp = 'help'; const String chatCommandHelp = 'help';
/// The recorded command list, in the order the palette shows it. /// The recorded command list, in the order the palette shows it.
@@ -50,6 +51,11 @@ const List<ChatCommand> chatCommands = <ChatCommand>[
summary: 'Stop the turn that is running', summary: 'Stop the turn that is running',
usage: '/stop', usage: '/stop',
), ),
ChatCommand(
name: chatCommandStopTasks,
summary: 'Stop all background tasks in this chat',
usage: '/stop_tasks',
),
ChatCommand( ChatCommand(
name: chatCommandHelp, name: chatCommandHelp,
summary: 'List every command', summary: 'List every command',
@@ -249,6 +249,7 @@ void main() {
'/close — Finish this session for every client, keeping its history\n' '/close — Finish this session for every client, keeping its history\n'
'/rename <title> — Rename this session\n' '/rename <title> — Rename this session\n'
'/stop — Stop the turn that is running\n' '/stop — Stop the turn that is running\n'
'/stop_tasks — Stop all background tasks in this chat\n'
'/help — List every command\n' '/help — List every command\n'
'!<command> — Run a shell command in this chat’s folder; ' '!<command> — Run a shell command in this chat’s folder; '
'the agent does not see it unless you send it', 'the agent does not see it unless you send it',
@@ -294,6 +295,34 @@ void main() {
variant: _desktop, variant: _desktop,
); );
testWidgets(
'/stop_tasks stops background tasks without interrupting the turn',
(tester) async {
gateway.stopTasks = () async => {
'chat_stop_tasks': {
'stopped': 2,
'message': 'Stopped background tasks.',
},
};
await pumpComposer(tester);
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
'/stop_tasks',
);
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(gateway.stopTasksBodies, [
<String, dynamic>{'session_id': 's'},
]);
expect(gateway.interruptBodies, isEmpty);
expect(gateway.promptBodies, isEmpty);
expect(find.text('Stopped background tasks.'), findsOneWidget);
},
variant: _desktop,
);
testWidgets('/stop interrupts the current session through the composer', ( testWidgets('/stop interrupts the current session through the composer', (
tester, tester,
) async { ) async {
@@ -16,6 +16,7 @@ class ComposerBarGateway implements ApiGateway {
JsonMap page = chatPage(const []); JsonMap page = chatPage(const []);
Future<JsonMap> Function(String text, String operationId)? prompt; Future<JsonMap> Function(String text, String operationId)? prompt;
Future<JsonMap> Function()? interrupt; Future<JsonMap> Function()? interrupt;
Future<JsonMap> Function()? stopTasks;
@override @override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async { Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
@@ -32,6 +33,8 @@ class ComposerBarGateway implements ApiGateway {
: prompt!('${body['text'] ?? ''}', '${body['operation_id'] ?? ''}'); : prompt!('${body['text'] ?? ''}', '${body['operation_id'] ?? ''}');
case 'chat_interrupt': case 'chat_interrupt':
return interrupt == null ? <String, dynamic>{} : interrupt!(); return interrupt == null ? <String, dynamic>{} : interrupt!();
case 'chat_stop_tasks':
return stopTasks == null ? <String, dynamic>{} : stopTasks!();
} }
return <String, dynamic>{}; return <String, dynamic>{};
} }
@@ -49,6 +52,11 @@ class ComposerBarGateway implements ApiGateway {
.map((call) => call.fields['chat_query'] as JsonMap) .map((call) => call.fields['chat_query'] as JsonMap)
.toList(); .toList();
List<JsonMap> get stopTasksBodies => calls
.where((call) => call.type == 'chat_stop_tasks')
.map((call) => call.fields['chat_query'] as JsonMap)
.toList();
void emitEvent(JsonMap body) => void emitEvent(JsonMap body) =>
_frames.add({'type': 'chat_event', 'chat_event': body}); _frames.add({'type': 'chat_event', 'chat_event': body});
@@ -8,6 +8,7 @@ void main() {
'close', 'close',
'rename', 'rename',
'stop', 'stop',
'stop_tasks',
'help', 'help',
]); ]);
expect(chatCommands.map((command) => command.usage), [ expect(chatCommands.map((command) => command.usage), [
@@ -15,6 +16,7 @@ void main() {
'/close', '/close',
'/rename <title>', '/rename <title>',
'/stop', '/stop',
'/stop_tasks',
'/help', '/help',
]); ]);
expect(chatCommands.map((command) => command.summary), [ expect(chatCommands.map((command) => command.summary), [
@@ -22,6 +24,7 @@ void main() {
'Finish this session for every client, keeping its history', 'Finish this session for every client, keeping its history',
'Rename this session', 'Rename this session',
'Stop the turn that is running', 'Stop the turn that is running',
'Stop all background tasks in this chat',
'List every command', 'List every command',
]); ]);
expect( expect(
+38
View File
@@ -426,6 +426,44 @@ func (c *Chat) Interrupt(ctx context.Context, id string) error {
return err 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 // ActivateSkill has no out-of-band equivalent in Claude Code; skills resolve
// through the CLI's own /skill mechanism. // through the CLI's own /skill mechanism.
func (c *Chat) ActivateSkill(context.Context, string, string) error { func (c *Chat) ActivateSkill(context.Context, string, string) error {
+51
View File
@@ -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) { func TestModelChoiceIsAppliedAndProcessResumes(t *testing.T) {
chat := testChat(t) chat := testChat(t)
session := newCreatedChat(t, chat) session := newCreatedChat(t, chat)
+5
View File
@@ -243,6 +243,11 @@ def handle(line):
state["pending"] = None state["pending"] = None
send({"type": "result", "subtype": "error_during_execution", "is_error": True, send({"type": "result", "subtype": "error_during_execution", "is_error": True,
"result": "Interrupted", "session_id": state["session"]}) "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": elif subtype == "get_usage":
respond(value.get("request_id"), {"session": { respond(value.get("request_id"), {"session": {
"total_cost_usd": 0.25, "total_cost_usd": 0.25,
+4
View File
@@ -550,6 +550,10 @@ func (c *Chat) Interrupt(ctx context.Context, id string) error {
return err 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 // ReleaseSession stops an active Codex turn while preserving the thread and
// its transcript. Codex has no separate per-thread process to reap. // its transcript. Codex has no separate per-thread process to reap.
func (c *Chat) ReleaseSession(ctx context.Context, id string) error { func (c *Chat) ReleaseSession(ctx context.Context, id string) error {
+20
View File
@@ -322,6 +322,26 @@ func (c *Chat) Interrupt(ctx context.Context, id string) error {
return nil 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 // ReleaseSession stops active and background work for an explicit operator
// close or /new without deleting the persisted native conversation. OpenCode // close or /new without deleting the persisted native conversation. OpenCode
// interrupt only stops the foreground drain; running shells are separate native // interrupt only stops the foreground drain; running shells are separate native
+36
View File
@@ -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 // TestDecodeChatMessages loads a seeded user + assistant session in both
// response envelopes the two surfaces return and asserts the turns come back // 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 // with role, id, part order, part ids and the completed tool's input, content
+10
View File
@@ -28,6 +28,9 @@ const (
ChatPrompt = "chat_prompt" ChatPrompt = "chat_prompt"
ChatMessages = "chat_messages" ChatMessages = "chat_messages"
ChatInterrupt = "chat_interrupt" 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" ChatReply = "chat_reply"
// ChatClose finishes an operator session and records it as closed on the // ChatClose finishes an operator session and records it as closed on the
// server: any in-flight turn is interrupted through the existing interrupt, // server: any in-flight turn is interrupted through the existing interrupt,
@@ -149,6 +152,13 @@ const (
ChatPermission = "chat_permission" 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 ( const (
ChatAutomationSupported = "supported" ChatAutomationSupported = "supported"
ChatAutomationUnavailable = "unavailable" ChatAutomationUnavailable = "unavailable"
+3 -2
View File
@@ -262,8 +262,9 @@ type Message struct {
// body names the session like ChatQuery. A chat_prompt response sets // 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 // 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. // accepted into the session's queue instead of being sent immediately.
ChatSubscribe *ChatQuery `json:"chat_subscribe,omitempty"` ChatSubscribe *ChatQuery `json:"chat_subscribe,omitempty"`
ChatQueued bool `json:"chat_queued,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 // ChatSteered means the prompt was handed to the turn already running; its
// reply is that turn's continuing output. // reply is that turn's continuing output.
ChatSteered bool `json:"chat_steered,omitempty"` ChatSteered bool `json:"chat_steered,omitempty"`
+7
View File
@@ -49,6 +49,10 @@ type chatPromptWithMessageID interface {
PromptWithMessageID(context.Context, string, string, string) error 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 // 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 // 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. // 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: case protocol.ChatInterrupt:
handleChatSimple(ctx, request, broker, hub, write) handleChatSimple(ctx, request, broker, hub, write)
return true return true
case protocol.ChatStopTasks:
handleChatStopTasks(ctx, request, broker, write)
return true
case protocol.ChatReply: case protocol.ChatReply:
handleChatSimple(ctx, request, broker, hub, write) handleChatSimple(ctx, request, broker, hub, write)
return true return true
+12
View File
@@ -746,6 +746,18 @@ func (m *chatManager) Shells(ctx context.Context, sessionID string) ([]protocol.
return nil, nil 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 { func (m *chatManager) Reply(ctx context.Context, request protocol.ChatReplyRequest) error {
adapter, err := m.brokerFor(ctx, request.SessionID) adapter, err := m.brokerFor(ctx, request.SessionID)
if err != nil { if err != nil {
+39
View File
@@ -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,
},
})
}
+31
View File
@@ -211,6 +211,16 @@ func (f *fakeChat) Interrupt(context.Context, string) error {
return f.interruptErr 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 { func (f *fakeChat) ReleaseSession(_ context.Context, sessionID string) error {
f.mu.Lock() f.mu.Lock()
defer f.mu.Unlock() 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 // TestChatInterruptEndsRunningPrompt is the task evidence: it starts a
// long-running turn through the real opencode.Chat adapter over an httptest SSE // 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 // fixture, sends chat_interrupt, and asserts the run ends. The fixture records