Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions e2e/api/69-assistant-sessions.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,30 @@ test('archive flags the conversation and can be undone', async () => {
});

test('generation endpoints answer for an idle conversation', async () => {
await api('GET', `${S}/${session.id}/generation`, undefined, { expect: 404 });
await api('POST', `${S}/${session.id}/generation/cancel`, {}, { expect: [404, 409] });
const path = `${S}/${session.id}`;
await get(`${path}/generation`, { expect: 404 });
await post(`${path}/generation/cancel`, {}, { expect: [404, 409] });
const steer = await post(`${path}/generation/steer`, { content: 'This should require a running turn' }, { expect: 409 });
assert.match(steer.error, /没有进行中的回复/);
const diagnostics = await get(`${path}/generations/${newId('missing-generation')}/diagnostics`, { expect: 404 });
assert.match(diagnostics.error, /没有可用的诊断记录/);
assert.deepEqual((await get(path)).messages, session.messages);
// No native CLI approvals are pending without a generation.
assert.deepEqual(list(await get(`${S}/${session.id}/native-approvals`)), []);
assert.deepEqual(list(await get(`${path}/native-approvals`)), []);
});

test('workspace sandbox selection persists and can return to the project default', async () => {
const path = `${S}/${session.id}`;
const selected = await put(`${path}/sandbox`, { sandboxProfileId: cfg.sandbox });
assert.equal(selected.sandboxProfileId, cfg.sandbox);
await put(`${path}/sandbox`, { sandboxProfileId: newId('missing-sandbox') }, { expect: 400 });
const stored = await get(path);
assert.equal(stored.sandboxProfileId, cfg.sandbox);
assert.deepEqual(stored.messages, session.messages);
const reset = await put(`${path}/sandbox`, { sandboxProfileId: '' });
assert.equal(reset.sandboxProfileId ?? '', '');
session = await get(path);
assert.equal(session.sandboxProfileId ?? '', '');
});

test('runtime mode: platform is accepted, workspace needs an open workspace, unknown is refused', async () => {
Expand Down
6 changes: 3 additions & 3 deletions internal/engine/sop_executors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ func TestExecutorCredentialsFollowTheProjectDefaultRunner(t *testing.T) {
check := func(projectID string, want map[string]bool) {
t.Helper()
execution := domain.TelemetryContext{ProjectID: projectID, ResponsibleUserID: 42}
(&Engine{repo: st}).selectSOPExecutionTarget(&execution)
(&Engine{repo: st}).selectSOPExecutionTarget(&execution, true)
hasCredential := ExecutorCredentials(st, 42, projectID)
for kind, expected := range want {
if got := hasCredential(kind); got != expected {
Expand Down Expand Up @@ -528,7 +528,7 @@ func TestExecutorCredentialsFollowTheCloudPool(t *testing.T) {
// Whatever pool runner a run picks, its login matches a CLI the picker offered.
for i := 0; i < 20; i++ {
execution := domain.TelemetryContext{ProjectID: "pool-served", ResponsibleUserID: 42}
e.selectSOPExecutionTarget(&execution)
e.selectSOPExecutionTarget(&execution, true)
if execution.ExecutionPool != domain.ExecutionModeCloud || execution.ExecutionRunnerID == "" {
t.Fatalf("run did not use the pool: %+v", execution)
}
Expand All @@ -553,7 +553,7 @@ func TestExecutorCredentialsFollowTheCloudPool(t *testing.T) {
e.ConfigureCloudRunnerPool(CloudRunnerPool{Label: "pool", Projects: []string{"*"}})
check("personal default", "", map[string]bool{"codex": false, "claude-code": true})
execution := domain.TelemetryContext{ResponsibleUserID: 42}
e.selectSOPExecutionTarget(&execution)
e.selectSOPExecutionTarget(&execution, true)
if execution.ExecutionRunnerID != own.ID {
t.Fatalf("personal SOP ran on %q, want the default machine", execution.ExecutionRunnerID)
}
Expand Down
17 changes: 14 additions & 3 deletions internal/httpapi/assistant.go
Original file line number Diff line number Diff line change
Expand Up @@ -1700,6 +1700,10 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U
missingText := "No conversation found with session ID: " + inv.sessionRef
var handle func(string)
sink := func(event domain.TelemetryEvent) {
if event.Name == runtime.CodeBuddyBackgroundTimeoutEvent {
assistantDiagnosticsFrom(ctx).platform(event.Name, event.Message, user)
return
}
attempt.process(event)
if event.Name == "process.stderr" {
attempt.stderr(event.Message)
Expand Down Expand Up @@ -1759,6 +1763,9 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U
if json.Unmarshal([]byte(line), &result) == nil {
switch result.Type {
case "result":
if engine == assistantEngineCodeBuddy && result.ParentToolUseID != "" {
break
}
final, resultError = result.Result, result.IsError
claudeResultText = ""
if captureClaudeText && result.ParentToolUseID == "" {
Expand Down Expand Up @@ -1990,6 +1997,10 @@ func prepareAssistantCommand(opts assistantCommandOpts) (runtime.CommandSpec, er
if sys == "" {
sys = assistantSystemPromptText()
}
workspace := opts.Workspace && !opts.ReviewOnly && !opts.ReportOnly
if workspace {
sys += "\n\n" + runtime.CodeBuddyBackgroundAgentInstructions
}
// Use the CLI's unlimited value; omitting the flag retains a finite default.
// A turn has no deadline; explicit cancellation still stops execution.
args := []string{"-p", "--max-turns", nativeAssistantUnlimitedTurns, "--system-prompt", sys, "--output-format", "stream-json", "--include-partial-messages", "--mcp-config", opts.Config}
Expand Down Expand Up @@ -2019,17 +2030,17 @@ func prepareAssistantCommand(opts assistantCommandOpts) (runtime.CommandSpec, er
command.Argv = replaceArgValue(command.Argv, "--disallowedTools", nativeDisallowedTools+",Read,Grep,Glob,Skill,TodoWrite,AskUserQuestion,EnterPlanMode,ExitPlanMode")
command.Argv = replaceArgValue(command.Argv, "--setting-sources", "")
command.Argv = appendNativeArgs(command.Argv, "--no-session-persistence")
} else if !opts.Workspace {
} else if !workspace {
command.Argv = applyNativeToolSafety(command.Argv, AgentToolAssistant)
} else {
command.Argv = replaceArgValue(command.Argv, "--setting-sources", "user")
command.Argv = appendNativeArgs(command.Argv, "--strict-mcp-config")
}
command.CredentialBindings = []runtime.CredentialBinding{runtime.BindCodeBuddy}
command.Telemetry = nil
if len(opts.ImagePaths) > 0 {
if workspace || len(opts.ImagePaths) > 0 {
command.Argv = appendNativeArgs(command.Argv, "--verbose")
command, err = withAssistantStreamImageInput(command, opts.Prompt, opts.ImagePaths, 0)
command, err = withAssistantStreamInput(command, opts.Prompt, opts.ImagePaths, 0)
if err != nil {
return runtime.CommandSpec{}, err
}
Expand Down
4 changes: 2 additions & 2 deletions internal/httpapi/assistant_engine_cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ func prepareAssistantClaudeInvocation(o assistantEngineInvocationOpts) (assistan
if o.RunnerLogin {
frameLimit = runtime.ClaudeLoginMaxInputLine
}
command, err = withAssistantStreamImageInput(command, o.Prompt, o.ImagePaths, frameLimit)
command, err = withAssistantStreamInput(command, o.Prompt, o.ImagePaths, frameLimit)
if err != nil {
return assistantCLIInvocation{}, err
}
Expand All @@ -259,7 +259,7 @@ func prepareAssistantClaudeInvocation(o assistantEngineInvocationOpts) (assistan
}, nil
}

func withAssistantStreamImageInput(command runtime.CommandSpec, prompt string, imagePaths []string, frameLimit int) (runtime.CommandSpec, error) {
func withAssistantStreamInput(command runtime.CommandSpec, prompt string, imagePaths []string, frameLimit int) (runtime.CommandSpec, error) {
input, err := assistantStreamImageInput(prompt, imagePaths)
if err != nil {
return runtime.CommandSpec{}, err
Expand Down
19 changes: 19 additions & 0 deletions internal/httpapi/assistant_failure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,25 @@ func TestAssistantClaudeRecoversReplyFromEmptySuccessfulResult(t *testing.T) {
}
}

func TestAssistantWorkspaceCodeBuddyKeepsParentReplyAfterChildResult(t *testing.T) {
reply, _, err := runAssistantCLI(t.Context(), assistantCLIRequest{
Executor: "codebuddy", Prompt: "test", SessionRoot: t.TempDir(),
Workspace: true, Native: true, RemoteBinary: true,
Execute: func(_ context.Context, _ string, _ runtime.CommandSpec, _ runtime.RunCredentials, sink runtime.EventSink) (string, error) {
for _, line := range []string{
`{"type":"result","result":"parent reply"}`,
`{"type":"result","parent_tool_use_id":"child","result":"child result","is_error":true}`,
} {
sink(domain.TelemetryEvent{Name: "process.stdout", Message: line})
}
return "", nil
},
}, domain.User{ID: 1, CodeBuddyAPIKey: "test"}, nil)
if err != nil || reply != "parent reply" {
t.Fatalf("got reply = %q, error = %v", reply, err)
}
}

func TestAssistantGenerationFailurePreservesCancellationAndDeadline(t *testing.T) {
for _, cause := range []error{context.Canceled, context.DeadlineExceeded} {
_, err := decodeAssistantCLIResult("", false, cause, []string{"process stopped"})
Expand Down
48 changes: 43 additions & 5 deletions internal/httpapi/assistant_prompt_stdin_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package httpapi

import (
"encoding/json"
"io"
"os"
"path/filepath"
"slices"
"strings"
"testing"

Expand Down Expand Up @@ -42,11 +44,10 @@ func assertPromptOnStdin(t *testing.T, name string, command runtime.CommandSpec,
func TestAssistantCodeBuddyOversizedPromptUsesStdin(t *testing.T) {
prompt := oversizedAssistantPrompt()
cases := map[string]assistantCommandOpts{
"platform": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true},
"workspace": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true, Workspace: true},
"resume": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true, Resume: true},
"report": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, ReportOnly: true},
"review": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, ReviewOnly: true},
"platform": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true},
"resume": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true, Resume: true},
"report": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, ReportOnly: true},
"review": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, ReviewOnly: true},
}
for name, opts := range cases {
command, err := prepareAssistantCommand(opts)
Expand All @@ -60,6 +61,43 @@ func TestAssistantCodeBuddyOversizedPromptUsesStdin(t *testing.T) {
}
}

func TestAssistantCodeBuddyWorkspaceStreamsPrompt(t *testing.T) {
for name, prompt := range map[string]string{"short": "你好\n第二行", "oversized": oversizedAssistantPrompt()} {
t.Run(name, func(t *testing.T) {
command, err := prepareAssistantCommand(assistantCommandOpts{
Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true, Workspace: true,
})
if err != nil {
t.Fatal(err)
}
for _, flag := range []string{"--input-format", "--output-format"} {
i := slices.Index(command.Argv, flag)
if i < 0 || i+1 >= len(command.Argv) || command.Argv[i+1] != "stream-json" {
t.Fatalf("%s must be stream-json", flag)
}
}
if slices.Contains(command.Argv, prompt) || command.Argv[len(command.Argv)-1] != "--" ||
!runtime.ConversationCommandFor(command, runtime.RunCredentials{}).Interactive {
t.Fatal("workspace prompt must be sent as interactive stdin")
}
var frame struct {
Type string
Message struct {
Role string
Content []struct{ Type, Text string }
}
}
if err := json.NewDecoder(command.Stdin).Decode(&frame); err != nil {
t.Fatal(err)
}
parts := frame.Message.Content
if frame.Type != "user" || frame.Message.Role != "user" || len(parts) != 1 || parts[0].Type != "text" || parts[0].Text != prompt {
t.Fatal("stream-json frame did not preserve the workspace prompt")
}
})
}
}

func TestAssistantCodeBuddyShortPromptStaysOnArgv(t *testing.T) {
command, err := prepareAssistantCommand(assistantCommandOpts{Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: "你好", SessionID: "s1", Native: true})
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions internal/runner/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -993,13 +993,13 @@ func (d *Daemon) executeInvocation(ctx context.Context, task domain.RunnerTask)
argv = runtime.BindMCPCallArgv(sandbox, argv)
}
var result execResult
command := prepared.Command
command.Argv = argv
if sandbox != nil {
command := prepared.Command
command.Argv = argv
command = runtime.WithCommandEnvironment(command, commandEnv)
result = d.executeSandboxProcess(ctx, task, sandbox, command)
} else {
result = d.executeProcess(ctx, task, argv, commandEnv)
result = d.executeHostCommand(ctx, task, command, commandEnv)
}
result.outputs = collectTaskOutputs(workspace, inv)
if result.status != domain.RunnerTaskSuccess {
Expand Down
53 changes: 47 additions & 6 deletions internal/runner/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,17 @@ type eventBatcher struct {
// process events back to the control plane.
func (d *Daemon) executeSandboxProcess(ctx context.Context, task domain.RunnerTask, sandbox flowruntime.Sandbox, command flowruntime.CommandSpec) execResult {
batcher := newEventBatcher(task, d.client)
command, closeInput, err := batcher.observer.OpenSOPInput(command)
if err != nil {
return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()}
}
defer closeInput()
if err := d.client.StartTask(ctx, task.ID); err != nil {
return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("start: %v", err)}
}
execCtx, cancel := context.WithCancel(ctx)
defer cancel()
drainDeadline := batcher.observer.CodeBuddySOPDrainDeadline(execCtx)
type outcome struct {
output string
err error
Expand Down Expand Up @@ -81,26 +87,32 @@ func (d *Daemon) executeSandboxProcess(ctx context.Context, task domain.RunnerTa
flushTicker := time.NewTicker(eventFlushInterval)
defer flushTicker.Stop()
canceled := false
stoppedAfterDrain := false
ctxDone := ctx.Done()
for {
select {
case <-ctxDone:
ctxDone = nil
canceled = true
cancel()
case <-drainDeadline:
drainDeadline = nil
stoppedAfterDrain = true
cancel()
case completed := <-done:
batcher.finalizeProtocol(completed.err == nil)
err := batcher.protocolProcessError(completed.err, stoppedAfterDrain)
batcher.finalizeProtocol(err == nil)
batcher.flush(context.Background())
result := execResult{result: batcher.taskResult(completed.output)}
if canceled {
if canceled || (stoppedAfterDrain && ctx.Err() != nil) {
result.status = domain.RunnerTaskCanceled
result.errMsg = "runner stopped"
return result
}
result.exitCode = exitCode(completed.err)
if completed.err != nil {
result.exitCode = exitCode(err)
if err != nil {
result.status = domain.RunnerTaskFailed
result.errMsg = completed.err.Error()
result.errMsg = err.Error()
} else {
result.status = domain.RunnerTaskSuccess
}
Expand Down Expand Up @@ -203,6 +215,13 @@ func (b *eventBatcher) finalizeProtocol(success bool) {
}
}

func (b *eventBatcher) protocolProcessError(err error, stoppedAfterDrain bool) error {
if err == nil || stoppedAfterDrain {
return b.observer.CodeBuddySOPResultError()
}
return err
}

func (b *eventBatcher) flush(ctx context.Context) {
b.mu.Lock()
pending := b.buf
Expand Down Expand Up @@ -269,7 +288,16 @@ type execResult struct {
// requested through the lease renewal response. extraEnv injects
// task-scoped credentials (e.g. CODEBUDDY_API_KEY for CodeBuddy tasks).
func (d *Daemon) executeProcess(ctx context.Context, task domain.RunnerTask, argv []string, extraEnv ...map[string]string) execResult {
return d.executeHostCommand(ctx, task, flowruntime.CommandSpec{Argv: argv}, extraEnv...)
}

func (d *Daemon) executeHostCommand(ctx context.Context, task domain.RunnerTask, command flowruntime.CommandSpec, extraEnv ...map[string]string) execResult {
batcher := newEventBatcher(task, d.client)
command, closeInput, err := batcher.observer.OpenSOPInput(command)
if err != nil {
return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()}
}
defer closeInput()
if err := d.client.StartTask(ctx, task.ID); err != nil {
if err == ErrUnauthorized {
return execResult{status: domain.RunnerTaskFailed, errMsg: "runner session rejected"}
Expand All @@ -282,8 +310,10 @@ func (d *Daemon) executeProcess(ctx context.Context, task domain.RunnerTask, arg
return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("workspace %s: %v", dir, err)}
}

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

drainCtx, stopDrain := context.WithCancel(ctx)
defer stopDrain()
drainDeadline := batcher.observer.CodeBuddySOPDrainDeadline(drainCtx)
canceled := false
stoppedAfterDrain := false
ctxDone := ctx.Done()
for {
select {
Expand All @@ -352,8 +386,15 @@ func (d *Daemon) executeProcess(ctx context.Context, task domain.RunnerTask, arg
canceled = true
terminateProcessGroup(cmd, processDone)
}
case <-drainDeadline:
drainDeadline = nil
if !canceled {
stoppedAfterDrain = true
terminateProcessGroup(cmd, processDone)
}
case <-processDone:
err := processErr
err := batcher.protocolProcessError(processErr, stoppedAfterDrain)
canceled = canceled || (stoppedAfterDrain && ctx.Err() != nil)
if canceled {
err = nil
}
Expand Down
Loading
Loading