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
6 changes: 6 additions & 0 deletions docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ Use a project-specific name for any credential that would otherwise share a vari

### Docker sandboxes

LoopForge starts Docker workspace containers with `--entrypoint sh IMAGE -c 'cd /workspace && exec sleep infinity'`. The image must provide `sh` and `sleep infinity`, and its runtime user must be able to enter `/workspace` and execute a command in a login shell. The workspace ignores image `ENTRYPOINT` and `CMD`; image builds, caches, and standalone image startup are unchanged. Put tool installation in Dockerfile `RUN`, static settings in `ENV`, and per-run initialization in an explicit workflow or workspace preparation step. Set the runtime user's bind-mount permissions before startup; preparation runs only after the workspace is ready.

The readiness probe runs a fresh login shell, so login profiles may run again and should be safe to repeat. The probe's random output marker distinguishes normal login output from successful probe execution; it is not an integrity check on the image.

Back up needed container-local state before upgrading the Worker or Runner that actually runs the workspace, or before rerunning the whole LOOP. Binding rejects an existing container with a different startup command without replacing it, but the existing full LOOP rerun and failed-run idle cleanup can still remove it. To rebuild deliberately, wait until the workspace is idle, run `docker rm -f <container-name-from-error>` on the execution host, then prepare the workspace again or start the next run. This preserves the host `/workspace` bind and its uncommitted files, but does not carry over the old writable layer or reattach anonymous volumes.

The platform exposes a built-in default sandbox (`generic-docker`, built from its own Dockerfile) even when the catalog SQL has not been installed. It is an in-memory fallback and does not insert database rows. An existing saved `generic-docker` profile takes priority, including its configured driver and environment. The default cannot be deleted; edit its configuration or create another profile to change how tasks run. LOOPs that do not choose a sandbox run in it. The full installer still imports starter LOOPs and the welcome project; the seeded `generic-docker` Dockerfile matches the platform image, so Compose sandboxes reuse `AGENTFLOW_ISOLATED_IMAGE` instead of building. Without the catalog SQL, the first run builds the built-in Dockerfile once.

`native` sandboxes use the execution machine's toolchains and the configured environment variables. For native LOOP checkouts, the host refreshes a private per-repository cache using the checkout's Git credentials and copies objects into each working tree. Docker sandboxes clone directly from the remote. The Compose platform image has no bwrap, so run native work on Runners or a natively installed platform. See [conversation workspaces](conversation-workspaces.md#仓库缓存). Migration `041_native_sandbox_inline_assets.sql` converts local profiles to native, preserves ordinary environment variables, and moves LOOPs relying on the old default to `generic-docker`.
Expand Down
14 changes: 11 additions & 3 deletions internal/engine/browser.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,12 @@ func (e *Engine) HandleBrowserRequest(ctx context.Context, run domain.Run, req *
}
return response
}
if req.Ensure && !runtime.BrowserRunning(ctx, run.ID) {
if err := e.ensureRunBrowser(ctx, run); err != nil {
if req.Ensure {
profile, _, err := e.workspaceSandboxProfile(run)
if err == nil && runtime.BrowserNeedsStart(ctx, run.ID, profile.Driver == domain.SandboxDriverDocker) {
err = e.ensureRunBrowser(ctx, run)
}
if err != nil {
payload, _ := json.Marshal(domain.BrowserState{Reason: err.Error()})
return domain.RunnerWorkspaceResponse{Payload: payload}
}
Expand Down Expand Up @@ -97,7 +101,11 @@ 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 {
browser, err := runtime.PrepareSandboxBrowser(ctx, env.sandbox, env.Workspace(), run.ID, nil)
if err != nil {
return err
}
if browser == nil {
return errors.New("Agent 浏览器启动失败:当前运行环境不支持,或 Chromium 不可用")
}
return nil
Expand Down
11 changes: 11 additions & 0 deletions internal/engine/conversation_workspace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,7 @@ func TestAcquireConversationEnvironmentRefusesUnrestoredReclaimedWorkspace(t *te
}

func TestEnsureRunBrowserRestoresReclaimedWorkspaceWithStaleRun(t *testing.T) {
t.Setenv("AGENTFLOW_BROWSER", "always")
bin := t.TempDir()
chromium := filepath.Join(bin, "chromium")
script := `#!/bin/sh
Expand All @@ -641,6 +642,16 @@ exec sleep 30
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))

e, id := checkpointFixture(t)
run, ok := e.repo.RunState(id)
if !ok {
t.Fatal("missing checkpoint run")
}
run.WorkflowSnapshot.SandboxSnapshot = &domain.RunnerSandboxSpec{
Profile: domain.SandboxProfile{ID: repo.TestNativeSandboxID, Driver: domain.SandboxDriverNative},
}
if err := e.repo.PutRun(run); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = runtime.HandleBrowser(context.Background(), id, domain.BrowserRequest{Operation: "stop"})
_ = e.releaseRunEnvironment(id, true)
Expand Down
50 changes: 50 additions & 0 deletions internal/engine/execution_cleanup_cases_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ package engine
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"

Expand All @@ -12,6 +15,53 @@ import (
"agentflow/internal/runtime"
)

func TestDockerWorkspaceProbeTimeoutFailsNodeInsteadOfRequeueing(t *testing.T) {
bin := t.TempDir()
entered := filepath.Join(bin, "entered")
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("PROBE_ENTERED", entered)
t.Setenv("AGENTFLOW_ISOLATED_IMAGE", "fixture-workspace-image")
if err := os.WriteFile(filepath.Join(bin, "docker"), []byte(`#!/bin/sh
case "$1" in
inspect) echo "Error response from daemon: No such container: $6" >&2; exit 1;;
exec) [ "$6" = workspace-probe ] || exit 99; touch "$PROBE_ENTERED"; exec sleep 60;;
ps|image|create|start|rm) exit 0;;
*) exit 99;;
esac`), 0o755); err != nil {
t.Fatal(err)
}
e, st := cvEEngine(t)
e.sandboxes = runtime.NewManagerWithLimit(t.TempDir(), 1)
e.ConfigureExecution("probe-timeout", "probe-timeout-host", time.Minute, true)
node := domain.WorkflowNode{ID: "script", Type: "script", ScriptLanguage: "shell", Script: "false", MaxAttempts: 1}
wf := domain.WorkflowDefinition{ID: "probe-timeout", Nodes: []domain.WorkflowNode{node}, SandboxSnapshot: &domain.RunnerSandboxSpec{
Profile: domain.SandboxProfile{Driver: domain.SandboxDriverDocker},
Dockerfile: &domain.DockerfileDefinition{Content: runtime.IsolatedDockerfile},
}}
run := domain.Run{ID: "probe-timeout", Status: "running", WorkflowID: wf.ID, WorkflowSnapshot: wf,
Nodes: map[string]*domain.NodeRun{node.ID: {NodeID: node.ID, Status: "pending"}}}
if err := st.PutRun(run); err != nil {
t.Fatal(err)
}
if _, err := e.acquireLease(run); err != nil {
t.Fatal(err)
}
e.executeNode(t.Context(), run.ID, wf, node)
if _, err := os.Stat(entered); err != nil || t.Context().Err() != nil {
t.Fatalf("expected a Docker login probe timeout with a live parent: %v", err)
}
got, _ := st.RunState(run.ID)
failed := got.Nodes[node.ID]
if failed.Status != "failed" || failed.Attempt != 1 || runtime.IsSandboxInterrupt(errors.New(failed.Error)) || strings.Contains(failed.Error, "signal: killed") {
t.Fatalf("startup timeout must fail the current attempt: status=%s attempt=%d error=%q", failed.Status, failed.Attempt, failed.Error)
}
for _, want := range []string{"workspace shell probe", "fixture-workspace-image", "agentflow-", "timed out"} {
if !strings.Contains(failed.Error, want) {
t.Errorf("missing %q from %q", want, failed.Error)
}
}
}

func TestDirectScriptNodeSuccessFailureAndResolution(t *testing.T) {
st, err := repo.OpenTest()
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion internal/engine/workspace_preparation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ func TestWorkspacePreparationRefreshesIdleLegacyDocker(t *testing.T) {
}
t.Cleanup(func() { _ = e.releaseRunEnvironment(run.ID, false) })
if out, err := exec.CommandContext(ctx, "docker", "run", "-d", "--name", "agentflow-"+env.ID(),
"-v", env.Workspace()+":/workspace", "--entrypoint", "sh", image, "-c", "exec sleep infinity").CombinedOutput(); err != nil {
"-v", env.Workspace()+":/workspace", "--entrypoint", "sh", image, "-c", "cd /workspace && exec sleep infinity").CombinedOutput(); err != nil {
t.Fatalf("create legacy Docker container: %v (%s)", err, out)
}
dirty := filepath.Join(env.Workspace(), "uncommitted.txt")
Expand Down
15 changes: 12 additions & 3 deletions internal/procwatch/procwatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ type Options struct {
Timeout time.Duration
TimeoutEnv string
// Redact scrubs secrets from every line before it is kept or reported.
Redact func(string) string
Redact func(string) string
HideOutput bool
// OnLine receives each nonempty line after redaction, independently of
// the throttled progress events. The callback should return promptly.
OnLine func(string)
Expand Down Expand Up @@ -135,7 +136,11 @@ func RunWithOutput(ctx context.Context, run func(context.Context, io.Writer) err
return
}
out.lastEmit = now
emit(Progress, opts.Label+":"+line, now.Sub(started))
message := opts.Label + ":" + line
if opts.HideOutput {
message = "正在" + opts.Label
}
emit(Progress, message, now.Sub(started))
}
emit(Started, "正在"+opts.Label, 0)

Expand All @@ -156,7 +161,11 @@ func RunWithOutput(ctx context.Context, run func(context.Context, io.Writer) err
return tail, nil
}
err = stopError(context.Cause(runCtx), opts, elapsed, err)
emit(Failed, failureMessage(opts.Label, elapsed, err, tail), elapsed)
publicTail := tail
if opts.HideOutput {
publicTail = ""
}
emit(Failed, failureMessage(opts.Label, elapsed, err, publicTail), elapsed)
return tail, err
}

Expand Down
8 changes: 6 additions & 2 deletions internal/runner/workspace.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,11 @@ func (d *Daemon) ensureRunnerBrowser(ctx context.Context, request domain.RunnerW
return "执行机无法打开该任务的沙箱:" + err.Error()
}
defer release()
if runtime.EnsureSandboxBrowser(ctx, sandbox, root, request.RunID, nil) == nil {
browser, err := runtime.PrepareSandboxBrowser(ctx, sandbox, root, request.RunID, nil)
if err != nil {
return err.Error()
}
if browser == nil {
return "Agent 浏览器启动失败:当前运行环境不支持,或 Chromium 不可用"
}
return ""
Expand All @@ -100,7 +104,7 @@ func (d *Daemon) handleRunnerWorkspaceBrowser(ctx context.Context, request domai
if request.Browser == nil {
return domain.RunnerWorkspaceResponse{Status: 400, Error: "invalid browser request"}
}
if request.Browser.Ensure && !runtime.BrowserRunning(ctx, request.RunID) {
if request.Browser.Ensure && runtime.BrowserNeedsStart(ctx, request.RunID, request.Sandbox != nil && request.Sandbox.Profile.Driver == domain.SandboxDriverDocker) {
if reason := d.ensureRunnerBrowser(ctx, request); reason != "" {
return runnerWorkspacePayload(domain.BrowserState{Reason: reason})
}
Expand Down
35 changes: 35 additions & 0 deletions internal/runner/workspace_browser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -58,6 +59,40 @@ func TestHandleRunnerWorkspaceBrowserReportsEnsureFailure(t *testing.T) {
}
}

func TestNativeBrowserEnsureWithDockerDaemonUnavailable(t *testing.T) {
root := t.TempDir()
t.Setenv("AGENTFLOW_BROWSER", "always")
t.Setenv("TMPDIR", root)
t.Setenv("PATH", root+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("AGENTFLOW_CHROMIUM", filepath.Join(root, "chromium"))
t.Setenv("CHROMIUM_LAUNCHED", filepath.Join(root, "chromium-launched"))
for name, script := range map[string]string{
"docker": "#!/bin/sh\necho 'Cannot connect to the Docker daemon' >&2\nexit 1\n",
"chromium": "#!/bin/sh\ntouch \"$CHROMIUM_LAUNCHED\"\nexit 1\n",
} {
if err := os.WriteFile(filepath.Join(root, name), []byte(script), 0o755); err != nil {
t.Fatal(err)
}
}
const runID = "native-browser-without-docker"
if err := os.MkdirAll(filepath.Join(root, "runs", runID, "workspace"), 0o700); err != nil {
t.Fatal(err)
}
d := &Daemon{cfg: Config{DefaultWorkspaceRoot: root}}
request := domain.RunnerWorkspaceRequest{
RunID: runID, WorkspaceLayout: domain.RunnerWorkspaceLayoutShared,
Browser: &domain.BrowserRequest{Operation: "start", Ensure: true},
Sandbox: &domain.RunnerSandboxSpec{Profile: domain.SandboxProfile{Driver: domain.SandboxDriverNative}},
Workflow: &domain.WorkflowDefinition{},
}
got := d.handleRunnerWorkspaceBrowser(t.Context(), request)
var state domain.BrowserState
_, launched := os.Stat(os.Getenv("CHROMIUM_LAUNCHED"))
if got.Status != http.StatusOK || json.Unmarshal(got.Payload, &state) != nil || !strings.Contains(state.Reason, "Chromium 启动后立即退出") || launched != nil {
t.Fatalf("native Ensure did not launch Chromium: response=%+v reason=%q launched=%v", got, state.Reason, launched)
}
}

func TestDockerBrowserRequestsDoNotWaitForRunnerHelper(t *testing.T) {
root := t.TempDir()
t.Setenv("AGENTFLOW_BROWSER", "always")
Expand Down
2 changes: 1 addition & 1 deletion internal/runner/workspace_preparation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ func TestRunnerWorkspacePreparationRefreshesLegacyDockerGitMount(t *testing.T) {
}
release()
if out, err := exec.CommandContext(ctx, "docker", "run", "-d", "--name", "agentflow-"+sb.ID(),
"-v", root+":/workspace", "--entrypoint", "sh", image, "-c", "exec sleep infinity").CombinedOutput(); err != nil {
"-v", root+":/workspace", "--entrypoint", "sh", image, "-c", "cd /workspace && exec sleep infinity").CombinedOutput(); err != nil {
t.Fatalf("create legacy Docker container: %v (%s)", err, out)
}
legacy, err := runtime.ReadSandboxEnvironmentIdentity(ctx, sb)
Expand Down
Loading
Loading