Skip to content

Commit 78cdab4

Browse files
authored
fix(runtime): enable CodeBuddy background subagents in SOP and chat (#1343)
* fix(sop): keep CodeBuddy background agent streams open * fix(chat): keep CodeBuddy background agents running in workspaces * fix(runtime): bound CodeBuddy shutdown and recover failed resumes * test: fix platform CI after main integration --------- Co-authored-by: crispinhu27 <353173575+crispinhu27@users.noreply.github.com>
1 parent cea420e commit 78cdab4

20 files changed

Lines changed: 836 additions & 98 deletions

‎e2e/api/69-assistant-sessions.test.mjs‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -107,10 +107,30 @@ test('archive flags the conversation and can be undone', async () => {
107107
});
108108

109109
test('generation endpoints answer for an idle conversation', async () => {
110-
await api('GET', `${S}/${session.id}/generation`, undefined, { expect: 404 });
111-
await api('POST', `${S}/${session.id}/generation/cancel`, {}, { expect: [404, 409] });
110+
const path = `${S}/${session.id}`;
111+
await get(`${path}/generation`, { expect: 404 });
112+
await post(`${path}/generation/cancel`, {}, { expect: [404, 409] });
113+
const steer = await post(`${path}/generation/steer`, { content: 'This should require a running turn' }, { expect: 409 });
114+
assert.match(steer.error, /没有进行中的回复/);
115+
const diagnostics = await get(`${path}/generations/${newId('missing-generation')}/diagnostics`, { expect: 404 });
116+
assert.match(diagnostics.error, /没有可用的诊断记录/);
117+
assert.deepEqual((await get(path)).messages, session.messages);
112118
// No native CLI approvals are pending without a generation.
113-
assert.deepEqual(list(await get(`${S}/${session.id}/native-approvals`)), []);
119+
assert.deepEqual(list(await get(`${path}/native-approvals`)), []);
120+
});
121+
122+
test('workspace sandbox selection persists and can return to the project default', async () => {
123+
const path = `${S}/${session.id}`;
124+
const selected = await put(`${path}/sandbox`, { sandboxProfileId: cfg.sandbox });
125+
assert.equal(selected.sandboxProfileId, cfg.sandbox);
126+
await put(`${path}/sandbox`, { sandboxProfileId: newId('missing-sandbox') }, { expect: 400 });
127+
const stored = await get(path);
128+
assert.equal(stored.sandboxProfileId, cfg.sandbox);
129+
assert.deepEqual(stored.messages, session.messages);
130+
const reset = await put(`${path}/sandbox`, { sandboxProfileId: '' });
131+
assert.equal(reset.sandboxProfileId ?? '', '');
132+
session = await get(path);
133+
assert.equal(session.sandboxProfileId ?? '', '');
114134
});
115135

116136
test('runtime mode: platform is accepted, workspace needs an open workspace, unknown is refused', async () => {

‎internal/httpapi/assistant.go‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1700,6 +1700,10 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U
17001700
missingText := "No conversation found with session ID: " + inv.sessionRef
17011701
var handle func(string)
17021702
sink := func(event domain.TelemetryEvent) {
1703+
if event.Name == runtime.CodeBuddyBackgroundTimeoutEvent {
1704+
assistantDiagnosticsFrom(ctx).platform(event.Name, event.Message, user)
1705+
return
1706+
}
17031707
attempt.process(event)
17041708
if event.Name == "process.stderr" {
17051709
attempt.stderr(event.Message)
@@ -1759,6 +1763,9 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U
17591763
if json.Unmarshal([]byte(line), &result) == nil {
17601764
switch result.Type {
17611765
case "result":
1766+
if engine == assistantEngineCodeBuddy && result.ParentToolUseID != "" {
1767+
break
1768+
}
17621769
final, resultError = result.Result, result.IsError
17631770
claudeResultText = ""
17641771
if captureClaudeText && result.ParentToolUseID == "" {
@@ -1990,6 +1997,10 @@ func prepareAssistantCommand(opts assistantCommandOpts) (runtime.CommandSpec, er
19901997
if sys == "" {
19911998
sys = assistantSystemPromptText()
19921999
}
2000+
workspace := opts.Workspace && !opts.ReviewOnly && !opts.ReportOnly
2001+
if workspace {
2002+
sys += "\n\n" + runtime.CodeBuddyBackgroundAgentInstructions
2003+
}
19932004
// Use the CLI's unlimited value; omitting the flag retains a finite default.
19942005
// A turn has no deadline; explicit cancellation still stops execution.
19952006
args := []string{"-p", "--max-turns", nativeAssistantUnlimitedTurns, "--system-prompt", sys, "--output-format", "stream-json", "--include-partial-messages", "--mcp-config", opts.Config}
@@ -2019,17 +2030,17 @@ func prepareAssistantCommand(opts assistantCommandOpts) (runtime.CommandSpec, er
20192030
command.Argv = replaceArgValue(command.Argv, "--disallowedTools", nativeDisallowedTools+",Read,Grep,Glob,Skill,TodoWrite,AskUserQuestion,EnterPlanMode,ExitPlanMode")
20202031
command.Argv = replaceArgValue(command.Argv, "--setting-sources", "")
20212032
command.Argv = appendNativeArgs(command.Argv, "--no-session-persistence")
2022-
} else if !opts.Workspace {
2033+
} else if !workspace {
20232034
command.Argv = applyNativeToolSafety(command.Argv, AgentToolAssistant)
20242035
} else {
20252036
command.Argv = replaceArgValue(command.Argv, "--setting-sources", "user")
20262037
command.Argv = appendNativeArgs(command.Argv, "--strict-mcp-config")
20272038
}
20282039
command.CredentialBindings = []runtime.CredentialBinding{runtime.BindCodeBuddy}
20292040
command.Telemetry = nil
2030-
if len(opts.ImagePaths) > 0 {
2041+
if workspace || len(opts.ImagePaths) > 0 {
20312042
command.Argv = appendNativeArgs(command.Argv, "--verbose")
2032-
command, err = withAssistantStreamImageInput(command, opts.Prompt, opts.ImagePaths, 0)
2043+
command, err = withAssistantStreamInput(command, opts.Prompt, opts.ImagePaths, 0)
20332044
if err != nil {
20342045
return runtime.CommandSpec{}, err
20352046
}

‎internal/httpapi/assistant_engine_cli.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ func prepareAssistantClaudeInvocation(o assistantEngineInvocationOpts) (assistan
246246
if o.RunnerLogin {
247247
frameLimit = runtime.ClaudeLoginMaxInputLine
248248
}
249-
command, err = withAssistantStreamImageInput(command, o.Prompt, o.ImagePaths, frameLimit)
249+
command, err = withAssistantStreamInput(command, o.Prompt, o.ImagePaths, frameLimit)
250250
if err != nil {
251251
return assistantCLIInvocation{}, err
252252
}
@@ -259,7 +259,7 @@ func prepareAssistantClaudeInvocation(o assistantEngineInvocationOpts) (assistan
259259
}, nil
260260
}
261261

262-
func withAssistantStreamImageInput(command runtime.CommandSpec, prompt string, imagePaths []string, frameLimit int) (runtime.CommandSpec, error) {
262+
func withAssistantStreamInput(command runtime.CommandSpec, prompt string, imagePaths []string, frameLimit int) (runtime.CommandSpec, error) {
263263
input, err := assistantStreamImageInput(prompt, imagePaths)
264264
if err != nil {
265265
return runtime.CommandSpec{}, err

‎internal/httpapi/assistant_failure_test.go‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,25 @@ func TestAssistantClaudeRecoversReplyFromEmptySuccessfulResult(t *testing.T) {
129129
}
130130
}
131131

132+
func TestAssistantWorkspaceCodeBuddyKeepsParentReplyAfterChildResult(t *testing.T) {
133+
reply, _, err := runAssistantCLI(t.Context(), assistantCLIRequest{
134+
Executor: "codebuddy", Prompt: "test", SessionRoot: t.TempDir(),
135+
Workspace: true, Native: true, RemoteBinary: true,
136+
Execute: func(_ context.Context, _ string, _ runtime.CommandSpec, _ runtime.RunCredentials, sink runtime.EventSink) (string, error) {
137+
for _, line := range []string{
138+
`{"type":"result","result":"parent reply"}`,
139+
`{"type":"result","parent_tool_use_id":"child","result":"child result","is_error":true}`,
140+
} {
141+
sink(domain.TelemetryEvent{Name: "process.stdout", Message: line})
142+
}
143+
return "", nil
144+
},
145+
}, domain.User{ID: 1, CodeBuddyAPIKey: "test"}, nil)
146+
if err != nil || reply != "parent reply" {
147+
t.Fatalf("got reply = %q, error = %v", reply, err)
148+
}
149+
}
150+
132151
func TestAssistantGenerationFailurePreservesCancellationAndDeadline(t *testing.T) {
133152
for _, cause := range []error{context.Canceled, context.DeadlineExceeded} {
134153
_, err := decodeAssistantCLIResult("", false, cause, []string{"process stopped"})

‎internal/httpapi/assistant_prompt_stdin_test.go‎

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package httpapi
22

33
import (
4+
"encoding/json"
45
"io"
56
"os"
67
"path/filepath"
8+
"slices"
79
"strings"
810
"testing"
911

@@ -42,11 +44,10 @@ func assertPromptOnStdin(t *testing.T, name string, command runtime.CommandSpec,
4244
func TestAssistantCodeBuddyOversizedPromptUsesStdin(t *testing.T) {
4345
prompt := oversizedAssistantPrompt()
4446
cases := map[string]assistantCommandOpts{
45-
"platform": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true},
46-
"workspace": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true, Workspace: true},
47-
"resume": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true, Resume: true},
48-
"report": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, ReportOnly: true},
49-
"review": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, ReviewOnly: true},
47+
"platform": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true},
48+
"resume": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true, Resume: true},
49+
"report": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, ReportOnly: true},
50+
"review": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, ReviewOnly: true},
5051
}
5152
for name, opts := range cases {
5253
command, err := prepareAssistantCommand(opts)
@@ -60,6 +61,43 @@ func TestAssistantCodeBuddyOversizedPromptUsesStdin(t *testing.T) {
6061
}
6162
}
6263

64+
func TestAssistantCodeBuddyWorkspaceStreamsPrompt(t *testing.T) {
65+
for name, prompt := range map[string]string{"short": "你好\n第二行", "oversized": oversizedAssistantPrompt()} {
66+
t.Run(name, func(t *testing.T) {
67+
command, err := prepareAssistantCommand(assistantCommandOpts{
68+
Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true, Workspace: true,
69+
})
70+
if err != nil {
71+
t.Fatal(err)
72+
}
73+
for _, flag := range []string{"--input-format", "--output-format"} {
74+
i := slices.Index(command.Argv, flag)
75+
if i < 0 || i+1 >= len(command.Argv) || command.Argv[i+1] != "stream-json" {
76+
t.Fatalf("%s must be stream-json", flag)
77+
}
78+
}
79+
if slices.Contains(command.Argv, prompt) || command.Argv[len(command.Argv)-1] != "--" ||
80+
!runtime.ConversationCommandFor(command, runtime.RunCredentials{}).Interactive {
81+
t.Fatal("workspace prompt must be sent as interactive stdin")
82+
}
83+
var frame struct {
84+
Type string
85+
Message struct {
86+
Role string
87+
Content []struct{ Type, Text string }
88+
}
89+
}
90+
if err := json.NewDecoder(command.Stdin).Decode(&frame); err != nil {
91+
t.Fatal(err)
92+
}
93+
parts := frame.Message.Content
94+
if frame.Type != "user" || frame.Message.Role != "user" || len(parts) != 1 || parts[0].Type != "text" || parts[0].Text != prompt {
95+
t.Fatal("stream-json frame did not preserve the workspace prompt")
96+
}
97+
})
98+
}
99+
}
100+
63101
func TestAssistantCodeBuddyShortPromptStaysOnArgv(t *testing.T) {
64102
command, err := prepareAssistantCommand(assistantCommandOpts{Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: "你好", SessionID: "s1", Native: true})
65103
if err != nil {

‎internal/runner/daemon.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -993,13 +993,13 @@ func (d *Daemon) executeInvocation(ctx context.Context, task domain.RunnerTask)
993993
argv = runtime.BindMCPCallArgv(sandbox, argv)
994994
}
995995
var result execResult
996+
command := prepared.Command
997+
command.Argv = argv
996998
if sandbox != nil {
997-
command := prepared.Command
998-
command.Argv = argv
999999
command = runtime.WithCommandEnvironment(command, commandEnv)
10001000
result = d.executeSandboxProcess(ctx, task, sandbox, command)
10011001
} else {
1002-
result = d.executeProcess(ctx, task, argv, commandEnv)
1002+
result = d.executeHostCommand(ctx, task, command, commandEnv)
10031003
}
10041004
result.outputs = collectTaskOutputs(workspace, inv)
10051005
if result.status != domain.RunnerTaskSuccess {

‎internal/runner/exec.go‎

Lines changed: 47 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,17 @@ type eventBatcher struct {
4949
// process events back to the control plane.
5050
func (d *Daemon) executeSandboxProcess(ctx context.Context, task domain.RunnerTask, sandbox flowruntime.Sandbox, command flowruntime.CommandSpec) execResult {
5151
batcher := newEventBatcher(task, d.client)
52+
command, closeInput, err := batcher.observer.OpenSOPInput(command)
53+
if err != nil {
54+
return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()}
55+
}
56+
defer closeInput()
5257
if err := d.client.StartTask(ctx, task.ID); err != nil {
5358
return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("start: %v", err)}
5459
}
5560
execCtx, cancel := context.WithCancel(ctx)
5661
defer cancel()
62+
drainDeadline := batcher.observer.CodeBuddySOPDrainDeadline(execCtx)
5763
type outcome struct {
5864
output string
5965
err error
@@ -81,26 +87,32 @@ func (d *Daemon) executeSandboxProcess(ctx context.Context, task domain.RunnerTa
8187
flushTicker := time.NewTicker(eventFlushInterval)
8288
defer flushTicker.Stop()
8389
canceled := false
90+
stoppedAfterDrain := false
8491
ctxDone := ctx.Done()
8592
for {
8693
select {
8794
case <-ctxDone:
8895
ctxDone = nil
8996
canceled = true
9097
cancel()
98+
case <-drainDeadline:
99+
drainDeadline = nil
100+
stoppedAfterDrain = true
101+
cancel()
91102
case completed := <-done:
92-
batcher.finalizeProtocol(completed.err == nil)
103+
err := batcher.protocolProcessError(completed.err, stoppedAfterDrain)
104+
batcher.finalizeProtocol(err == nil)
93105
batcher.flush(context.Background())
94106
result := execResult{result: batcher.taskResult(completed.output)}
95-
if canceled {
107+
if canceled || (stoppedAfterDrain && ctx.Err() != nil) {
96108
result.status = domain.RunnerTaskCanceled
97109
result.errMsg = "runner stopped"
98110
return result
99111
}
100-
result.exitCode = exitCode(completed.err)
101-
if completed.err != nil {
112+
result.exitCode = exitCode(err)
113+
if err != nil {
102114
result.status = domain.RunnerTaskFailed
103-
result.errMsg = completed.err.Error()
115+
result.errMsg = err.Error()
104116
} else {
105117
result.status = domain.RunnerTaskSuccess
106118
}
@@ -203,6 +215,13 @@ func (b *eventBatcher) finalizeProtocol(success bool) {
203215
}
204216
}
205217

218+
func (b *eventBatcher) protocolProcessError(err error, stoppedAfterDrain bool) error {
219+
if err == nil || stoppedAfterDrain {
220+
return b.observer.CodeBuddySOPResultError()
221+
}
222+
return err
223+
}
224+
206225
func (b *eventBatcher) flush(ctx context.Context) {
207226
b.mu.Lock()
208227
pending := b.buf
@@ -269,7 +288,16 @@ type execResult struct {
269288
// requested through the lease renewal response. extraEnv injects
270289
// task-scoped credentials (e.g. CODEBUDDY_API_KEY for CodeBuddy tasks).
271290
func (d *Daemon) executeProcess(ctx context.Context, task domain.RunnerTask, argv []string, extraEnv ...map[string]string) execResult {
291+
return d.executeHostCommand(ctx, task, flowruntime.CommandSpec{Argv: argv}, extraEnv...)
292+
}
293+
294+
func (d *Daemon) executeHostCommand(ctx context.Context, task domain.RunnerTask, command flowruntime.CommandSpec, extraEnv ...map[string]string) execResult {
272295
batcher := newEventBatcher(task, d.client)
296+
command, closeInput, err := batcher.observer.OpenSOPInput(command)
297+
if err != nil {
298+
return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()}
299+
}
300+
defer closeInput()
273301
if err := d.client.StartTask(ctx, task.ID); err != nil {
274302
if err == ErrUnauthorized {
275303
return execResult{status: domain.RunnerTaskFailed, errMsg: "runner session rejected"}
@@ -282,8 +310,10 @@ func (d *Daemon) executeProcess(ctx context.Context, task domain.RunnerTask, arg
282310
return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("workspace %s: %v", dir, err)}
283311
}
284312

313+
argv := command.Argv
285314
cmd := exec.Command(argv[0], argv[1:]...)
286315
cmd.Dir = dir
316+
cmd.Stdin = command.Stdin
287317
// Agent CLI credentials live in the user environment on this machine;
288318
// the platform additionally injects task-scoped credentials (currently
289319
// the CodeBuddy API key, which cannot come from a local CLI login).
@@ -342,7 +372,11 @@ func (d *Daemon) executeProcess(ctx context.Context, task domain.RunnerTask, arg
342372
flushTicker := time.NewTicker(eventFlushInterval)
343373
defer flushTicker.Stop()
344374

375+
drainCtx, stopDrain := context.WithCancel(ctx)
376+
defer stopDrain()
377+
drainDeadline := batcher.observer.CodeBuddySOPDrainDeadline(drainCtx)
345378
canceled := false
379+
stoppedAfterDrain := false
346380
ctxDone := ctx.Done()
347381
for {
348382
select {
@@ -352,8 +386,15 @@ func (d *Daemon) executeProcess(ctx context.Context, task domain.RunnerTask, arg
352386
canceled = true
353387
terminateProcessGroup(cmd, processDone)
354388
}
389+
case <-drainDeadline:
390+
drainDeadline = nil
391+
if !canceled {
392+
stoppedAfterDrain = true
393+
terminateProcessGroup(cmd, processDone)
394+
}
355395
case <-processDone:
356-
err := processErr
396+
err := batcher.protocolProcessError(processErr, stoppedAfterDrain)
397+
canceled = canceled || (stoppedAfterDrain && ctx.Err() != nil)
357398
if canceled {
358399
err = nil
359400
}

‎internal/runner/exec_edges_cases_test.go‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,34 @@ func TestExecuteProcessAndSandboxCancellation(t *testing.T) {
122122
}
123123
}
124124

125+
func TestExecuteCodeBuddySOPStopsAtDrainDeadline(t *testing.T) {
126+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }))
127+
defer server.Close()
128+
ctx, cancel := context.WithTimeout(t.Context(), 12*time.Second)
129+
defer cancel()
130+
d := &Daemon{cfg: Config{DefaultWorkspaceRoot: t.TempDir()}, client: NewClient(server.URL)}
131+
executor := domain.ExecutorDefinition{Kind: "codebuddy", Binary: "codebuddy", Protocol: "stream-json"}
132+
agent := domain.AgentDefinition{ID: "test", Name: "Test"}
133+
prepared, err := flowruntime.NewExecutorRunner().PrepareRemote(t.TempDir(), flowruntime.RemoteInvocation{
134+
InvocationID: "test", Executor: executor, Agent: agent, Prompt: "test",
135+
})
136+
if err != nil {
137+
t.Fatal(err)
138+
}
139+
task := domain.RunnerTask{ID: "codebuddy-drain", Invocation: &domain.RunnerInvocation{Executor: executor}}
140+
command := prepared.Command
141+
command.Argv = []string{"sh", "-c", `
142+
IFS= read -r prompt || exit 1
143+
printf '%s\n' '{"type":"result","result":"parent done"}'
144+
if IFS= read -r extra; then exit 1; fi
145+
exec sleep 60
146+
`}
147+
result := d.executeHostCommand(ctx, task, command)
148+
if result.status != domain.RunnerTaskSuccess || result.result != "parent done" || ctx.Err() != nil {
149+
t.Fatalf("Runner did not preserve the parent result after stopping the process: %+v, context=%v", result, ctx.Err())
150+
}
151+
}
152+
125153
func TestEventBatcherRequeuesFailedFlush(t *testing.T) {
126154
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "fail", http.StatusInternalServerError) }))
127155
defer server.Close()

0 commit comments

Comments
 (0)