Skip to content
Open
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
8 changes: 4 additions & 4 deletions internal/engine/browser.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package engine
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"

"agentflow/internal/domain"
Expand Down Expand Up @@ -70,7 +70,7 @@ func (e *Engine) BrowserWorkspaceRequest(run domain.Run, req *domain.BrowserRequ
// and the stage agents drive the same browser the user watches.
func (e *Engine) ensureRunBrowser(ctx context.Context, run domain.Run) error {
if !runtime.BrowserEnabled() {
return errors.New("平台已关闭 Agent 浏览器")
return runtime.ErrBrowserDisabled
}
// Starting from the panel counts as conversation use: it restores a
// reclaimed workspace and leaves the run to the idle conversation cleanup,
Expand All @@ -97,8 +97,8 @@ func (e *Engine) ensureRunBrowser(ctx context.Context, run domain.Run) error {
if err != nil {
return err
}
if runtime.EnsureSandboxBrowser(ctx, env.sandbox, env.Workspace(), run.ID, nil) == nil {
return errors.New("Agent 浏览器启动失败:当前运行环境不支持,或 Chromium 不可用")
if _, err := runtime.EnsureSandboxBrowserWithError(ctx, env.sandbox, env.Workspace(), run.ID, nil); err != nil {
return fmt.Errorf("Agent 浏览器启动失败:%w", err)
}
return nil
}
37 changes: 31 additions & 6 deletions internal/runtime/browser.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,30 @@ func BrowserRunning(ctx context.Context, runID string) bool {
return ok
}

// ErrBrowserDisabled reports that the deployment switched the Agent browser off.
var ErrBrowserDisabled = errors.New("平台已关闭 Agent 浏览器")

// EnsureSandboxBrowser gives the invocation its run browser and returns the
// MCP server the agent drives it through. A docker sandbox gets a sidecar
// sharing its network namespace whatever image the user picked; host drivers
// get a host Chromium. Failures only warn: the node still runs without it.
func EnsureSandboxBrowser(ctx context.Context, sb Sandbox, workspace, runID string, sink EventSink) *domain.MCPServerDefinition {
if !BrowserEnabled() || strings.TrimSpace(runID) == "" {
return nil
server, _ := EnsureSandboxBrowserWithError(ctx, sb, workspace, runID, sink)
return server
}

// EnsureSandboxBrowserWithError prepares the same run browser as
// EnsureSandboxBrowser but also returns why it is unavailable. Interactive
// callers (opening the Agent browser panel) use it to surface the real cause,
// for example a failed sidecar image build, instead of a generic
// "unsupported environment" message. Node execution keeps using
// EnsureSandboxBrowser, which ignores the error and only emits the warning.
func EnsureSandboxBrowserWithError(ctx context.Context, sb Sandbox, workspace, runID string, sink EventSink) (*domain.MCPServerDefinition, error) {
if !BrowserEnabled() {
return nil, ErrBrowserDisabled
}
if strings.TrimSpace(runID) == "" {
return nil, errors.New("未指定运行的工作区")
}
var (
server domain.MCPServerDefinition
Expand All @@ -102,15 +119,15 @@ func EnsureSandboxBrowser(ctx context.Context, sb Sandbox, workspace, runID stri
case *processSandbox:
server, err = ensureHostBrowser(ctx, inner.workspace, runID)
default:
return nil
return nil, fmt.Errorf("当前运行环境不支持 Agent 浏览器(sandbox %T)", sb)
}
if err != nil {
if sink != nil {
sink(domain.TelemetryEvent{Category: "sandbox", Name: "browser.unavailable", Level: "warn", Message: "Agent 浏览器未就绪,本节点不提供浏览器工具:" + err.Error()})
}
return nil
return nil, err
}
return &server
return &server, nil
}

func unwrapSandbox(sb Sandbox) Sandbox {
Expand Down Expand Up @@ -239,12 +256,20 @@ func (s *dockerSandbox) ensureBrowser(ctx context.Context, runID string, sink Ev
if !dockerImageExists(ctx, image) && sink != nil {
sink(domain.TelemetryEvent{Category: "sandbox", Name: "browser.prepare", Phase: "start", Message: "首次准备 Agent 浏览器镜像(Chromium + Playwright MCP),可能需要几分钟"})
}
buildCtx, cancel := context.WithTimeout(ctx, 15*time.Minute)
// The first browser of a host still needs its sidecar image built. Keep the
// build running when the caller goes away: an interactive panel request has
// a short timeout, and cancelling docker build with it leaves a defunct
// builder and rebuilds from scratch on the next attempt.
buildCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Minute)
image, err = EnsureBrowserImage(buildCtx)
cancel()
if err != nil {
return domain.MCPServerDefinition{}, err
}
if ctxErr := ctx.Err(); ctxErr != nil {
// The image is ready; only this request ran out of time waiting for it.
return domain.MCPServerDefinition{}, fmt.Errorf("Agent 浏览器镜像已就绪,请重新打开浏览器(%w)", ctxErr)
}
name := dockerBrowserContainerName(s.name)
out, inspectErr := exec.CommandContext(ctx, "docker", "inspect", "-f", "{{.State.Running}}|{{.Config.Image}}|{{index .Config.Labels \""+browserRunLabel+"\"}}", name).Output()
if inspectErr != nil || strings.TrimSpace(string(out)) != "true|"+image+"|"+runID {
Expand Down
120 changes: 120 additions & 0 deletions internal/runtime/browser_failure_cases_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package runtime

import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"

"agentflow/internal/domain"
)

// browserFakeDocker installs a docker CLI stub for the sidecar image cases and
// points the given markers at files in the test's temp dir.
func browserFakeDocker(t *testing.T, script string) (buildStarted, imageReady string) {
t.Helper()
bin := t.TempDir()
dir := t.TempDir()
buildStarted = filepath.Join(dir, "build-started")
imageReady = filepath.Join(dir, "image-ready")
path := filepath.Join(bin, "docker")
if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("CVR_BROWSER_BUILD_STARTED", buildStarted)
t.Setenv("CVR_BROWSER_IMAGE_READY", imageReady)
t.Setenv("AGENTFLOW_BROWSER_IMAGE", "")
t.Setenv("AGENTFLOW_BROWSER", "")
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
return buildStarted, imageReady
}

// TestAgentBrowserBuildOutlivesRequestTimeout covers an interactive panel
// request timing out while the first sidecar image build is still running: the
// build must run to completion instead of being cancelled with the request, so
// the next attempt finds the image instead of rebuilding from scratch.
func TestAgentBrowserBuildOutlivesRequestTimeout(t *testing.T) {
buildStarted, imageReady := browserFakeDocker(t, `#!/bin/sh
set -u
case "${1-}" in
build)
: > "$CVR_BROWSER_BUILD_STARTED"
sleep 1
: > "$CVR_BROWSER_IMAGE_READY"
exit 0 ;;
image)
[ "${2-}" = inspect ] || exit 0
[ -f "$CVR_BROWSER_IMAGE_READY" ] && exit 0
exit 1 ;;
inspect)
[ "${2-}" = -f ] && printf 'false||\n'
exit 0 ;;
esac
exit 0
`)
workspace := t.TempDir()
sb := &dockerSandbox{name: "box", workspace: workspace, started: true}
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if _, err := EnsureSandboxBrowserWithError(ctx, sb, workspace, "run", nil); err == nil {
t.Fatal("want the timed-out request to fail")
} else if !strings.Contains(err.Error(), "镜像已就绪") {
t.Fatalf("want a retry hint after the build completes, got: %v", err)
}
if _, err := os.Stat(buildStarted); err != nil {
t.Fatalf("image build did not start: %v", err)
}
if _, err := os.Stat(imageReady); err != nil {
t.Fatalf("image build was cancelled with the request: %v", err)
}
server, err := EnsureSandboxBrowserWithError(context.Background(), sb, workspace, "run", nil)
if err != nil || server == nil {
t.Fatalf("second attempt after the build: server=%v err=%v", server, err)
}
}

// TestEnsureSandboxBrowserWithErrorKeepsBuildFailure covers the panel path
// surfacing the real sidecar failure instead of a generic unsupported
// environment message; the node path keeps its failure-tolerant helper.
func TestEnsureSandboxBrowserWithErrorKeepsBuildFailure(t *testing.T) {
browserFakeDocker(t, `#!/bin/sh
set -u
case "${1-}" in
build)
echo "deb.debian.org: connection timed out" >&2
exit 1 ;;
image)
[ "${2-}" = inspect ] && exit 1
exit 0 ;;
esac
exit 0
`)
workspace := t.TempDir()
sb := &dockerSandbox{name: "box", workspace: workspace, started: true}
server, err := EnsureSandboxBrowserWithError(context.Background(), sb, workspace, "run", nil)
if server != nil || err == nil {
t.Fatalf("server=%v err=%v, want a build failure", server, err)
}
if !strings.Contains(err.Error(), "docker build browser image") || !strings.Contains(err.Error(), "connection timed out") {
t.Fatalf("build failure lost its cause: %v", err)
}
if got := EnsureSandboxBrowser(context.Background(), sb, workspace, "run", nil); got != nil {
t.Fatalf("failure-tolerant helper returned %v, want nil", got)
}
}

// TestEnsureSandboxBrowserWithErrorDisabled keeps the disabled deployment and
// missing workspace cases explicit for interactive callers.
func TestEnsureSandboxBrowserWithErrorDisabled(t *testing.T) {
t.Setenv("AGENTFLOW_BROWSER", "off")
if _, err := EnsureSandboxBrowserWithError(context.Background(), nil, "", "run", nil); err != ErrBrowserDisabled {
t.Fatalf("want ErrBrowserDisabled, got %v", err)
}
t.Setenv("AGENTFLOW_BROWSER", "")
sink := func(domain.TelemetryEvent) {}
if _, err := EnsureSandboxBrowserWithError(context.Background(), nil, "", " ", sink); err == nil {
t.Fatal("want a missing-workspace error")
}
}