Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7995: fix(openclaw): report actionable state ownership lock error (#9222)
Basuotiane7dfbe83bdee
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex b3ee761b1e..41c76fe646 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -163,6 +163,9 @@ func TestIsBlockedEnvKey(t *testing.T) {{key: "CURSOR_MCP_AUTH_SOURCE", want: true},{key: "OPENCLAW_CONFIG_PATH", want: true},{key: "OPENCLAW_INCLUDE_ROOTS", want: true},+ // OPENCLAW_STATE_DIR is intentionally NOT blocked so users can give an+ // agent a dedicated OpenClaw state directory when the default is locked.+ {key: "OPENCLAW_STATE_DIR", want: false},{key: "ANTHROPIC_API_KEY", want: false},{key: "CURSOR_AGENT", want: false},// HERMES_HOME is intentionally NOT blocked: a skill-less Hermes taskdiff --git a/server/pkg/agent/openclaw.go b/server/pkg/agent/openclaw.goindex 00bbb082d4..7d7851c8dd 100644--- a/server/pkg/agent/openclaw.go+++ b/server/pkg/agent/openclaw.go@@ -29,6 +29,10 @@ const openclawNoParseableOutput = "openclaw returned no parseable output"// of "openclaw returned no parseable output".const minOpenclawVersion = "2026.5.5"+const openclawStateOwnershipLockError = "OpenClaw could not acquire ownership of its state directory because another OpenClaw process owns it. Stop that process, or configure a dedicated state directory through backends.openclaw.state_dir / OPENCLAW_STATE_DIR and retry. A dedicated directory has separate credentials and sessions."++const openclawResidentGatewayLocalRefusalError = "OpenClaw Gateway is already running for this state directory. Switch this OpenClaw runtime's runtime_config.mode to gateway so Multica uses the resident Gateway, or stop it with openclaw gateway stop before retrying in local mode. To keep local mode, configure a dedicated state directory through backends.openclaw.state_dir / OPENCLAW_STATE_DIR; that directory has separate credentials and sessions."+// openclawVersionPattern extracts a three-segment dotted version from// arbitrary `openclaw --version` output (e.g. "openclaw 2026.5.5",// "openclaw v2026.5.5 c37871e").@@ -108,7 +112,8 @@ func (b *openclawBackend) Execute(ctx context.Context, prompt string, opts ExecOcancel()return nil, fmt.Errorf("openclaw stdout pipe: %w", err)}- cmd.Stderr = newLogWriter(b.cfg.Logger, "[openclaw:stderr] ")+ stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[openclaw:stderr] "), agentStderrTailBytes)+ cmd.Stderr = stderrBufif err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {cancel()@@ -189,6 +194,18 @@ func (b *openclawBackend) Execute(ctx context.Context, prompt string, opts ExecOscanResult.errMsg = fmt.Sprintf("openclaw exited with error: %v", exitErr)}+ // A resident OpenClaw Gateway may already own the default ~/.openclaw+ // state directory. Local mode cannot share that ownership lock; surface+ // the configuration needed to use an isolated state directory instead of+ // leaving users with the generic "no parseable output" failure. Gateway+ // mode talks to the resident Gateway and is unaffected by this lock.+ if opts.OpenclawMode != "gateway" && scanResult.status == "failed" {+ stderr := stderrBuf.Tail()+ if guidance, ok := openclawStateLockGuidance(stderr); ok {+ scanResult.errMsg = withAgentStderr(guidance, "OpenClaw", sanitizeAgentDiagnostic(stderr))+ }+ }+b.cfg.Logger.Info("openclaw finished", "pid", cmd.Process.Pid, "status", scanResult.status, "duration", duration.Round(time.Millisecond).String())// Build usage map. Prefer the model openclaw reported in@@ -218,6 +235,53 @@ func (b *openclawBackend) Execute(ctx context.Context, prompt string, opts ExecOreturn &Session{Messages: msgCh, Result: resCh}, nil}+type openclawStateLockFailure int++const (+ openclawStateLockNone openclawStateLockFailure = iota+ openclawStateLockOwnership+ openclawStateLockResidentGateway+)++// openclawStateLockGuidance recognizes the two ways `openclaw agent --local`+// can be refused by a state directory that is already in use. Keep the match+// anchored to state ownership or the resident-Gateway refusal so unrelated+// lock failures are not rewritten.+func openclawStateLockGuidance(message string) (string, bool) {+ switch classifyOpenclawStateLockFailure(message) {+ case openclawStateLockResidentGateway:+ return openclawResidentGatewayLocalRefusalError, true+ case openclawStateLockOwnership:+ return openclawStateOwnershipLockError, true+ default:+ return "", false+ }+}++func classifyOpenclawStateLockFailure(message string) openclawStateLockFailure {+ normalized := strings.ToLower(strings.Join(strings.Fields(message), " "))+ if normalized == "" {+ return openclawStateLockNone+ }+ if strings.Contains(normalized, "a gateway is running for this state directory") {+ return openclawStateLockResidentGateway+ }+ if strings.Contains(normalized, "gatewaylockerror") && strings.Contains(normalized, "state ownership") {+ return openclawStateLockOwnership+ }+ if strings.Contains(normalized, "failed to acquire gateway state ownership") {+ return openclawStateLockOwnership+ }+ if strings.Contains(normalized, "ownership lock") {+ if strings.Contains(normalized, "state-directory") ||+ strings.Contains(normalized, "state directory") ||+ strings.Contains(normalized, "state dir") {+ return openclawStateLockOwnership+ }+ }+ return openclawStateLockNone+}+// buildOpenclawArgs assembles the argv for a one-shot `openclaw agent` invocation.//// The CLI accepts separate --agent and --model flags. Multica intentionallydiff --git a/server/pkg/agent/openclaw_test.go b/server/pkg/agent/openclaw_test.goindex 79a77be776..8d1968fecc 100644--- a/server/pkg/agent/openclaw_test.go+++ b/server/pkg/agent/openclaw_test.go@@ -1606,3 +1606,207 @@ func TestOpenclawExecuteAllowsCurrentVersion(t *testing.T) {t.Fatal("timeout waiting for result")}}++func TestClassifyOpenclawStateLockFailure(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ message string+ want openclawStateLockFailure+ }{+ {+ name: "ownership acquisition timeout",+ message: `GatewayLockError("failed to acquire gateway state ownership; waited 10000ms for Gateway state ownership")`,+ want: openclawStateLockOwnership,+ },+ {+ name: "resident gateway refusal",+ message: `GatewayLockError("A Gateway is running for this state directory (pid 123, port 18789). Run without --local to use it, or stop the Gateway first (openclaw gateway stop).")`,+ want: openclawStateLockResidentGateway,+ },+ {+ name: "state directory ownership lock",+ message: "OpenClaw could not acquire the state-directory ownership lock",+ want: openclawStateLockOwnership,+ },+ {+ name: "state dir ownership lock",+ message: "failed to acquire state dir ownership lock",+ want: openclawStateLockOwnership,+ },+ {+ name: "unrelated lock error",+ message: "failed to acquire workspace ownership lock",+ want: openclawStateLockNone,+ },+ {+ name: "unrelated openclaw error",+ message: "openclaw returned no parseable output",+ want: openclawStateLockNone,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()+ if got := classifyOpenclawStateLockFailure(tt.message); got != tt.want {+ t.Fatalf("classifyOpenclawStateLockFailure(%q) = %v, want %v", tt.message, got, tt.want)+ }+ })+ }+}++func TestOpenclawStateLockGuidance(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ message string+ wantContains []string+ wantNotContain []string+ }{+ {+ name: "resident gateway recommends gateway mode",+ message: `GatewayLockError("A Gateway is running for this state directory (pid 123, port 18789). Run without --local to use it, or stop the Gateway first (openclaw gateway stop).")`,+ wantContains: []string{+ "runtime_config.mode",+ "gateway",+ "openclaw gateway stop",+ },+ },+ {+ name: "ownership lock recommends dedicated directory",+ message: `GatewayLockError("failed to acquire gateway state ownership; waited 10000ms for Gateway state ownership")`,+ wantContains: []string{+ "backends.openclaw.state_dir",+ "OPENCLAW_STATE_DIR",+ "separate credentials and sessions",+ },+ wantNotContain: []string{"runtime_config.mode"},+ },+ {+ name: "unrelated error",+ message: "openclaw returned no parseable output",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()+ guidance, ok := openclawStateLockGuidance(tt.message)+ if len(tt.wantContains) == 0 && len(tt.wantNotContain) == 0 {+ if ok || guidance != "" {+ t.Fatalf("openclawStateLockGuidance(%q) = %q, %v; want no guidance", tt.message, guidance, ok)+ }+ return+ }+ if !ok {+ t.Fatalf("openclawStateLockGuidance(%q) returned no guidance", tt.message)+ }+ for _, want := range tt.wantContains {+ if !strings.Contains(guidance, want) {+ t.Errorf("guidance missing %q: %s", want, guidance)+ }+ }+ for _, unwanted := range tt.wantNotContain {+ if strings.Contains(guidance, unwanted) {+ t.Errorf("guidance unexpectedly contains %q: %s", unwanted, guidance)+ }+ }+ })+ }+}++func TestOpenclawExecuteReportsStateOwnershipLockAction(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ tests := []struct {+ name string+ mode string+ stderr string+ wantContains []string+ wantAbsent []string+ }{+ {+ name: "local ownership timeout",+ stderr: `GatewayLockError("failed to acquire gateway state ownership; waited 10000ms for Gateway state ownership")`,+ wantContains: []string{+ "backends.openclaw.state_dir",+ "OPENCLAW_STATE_DIR",+ "failed to acquire gateway state ownership",+ },+ },+ {+ name: "local resident gateway",+ stderr: `GatewayLockError("A Gateway is running for this state directory (pid 123, port 18789). Run without --local to use it, or stop the Gateway first (openclaw gateway stop).")`,+ wantContains: []string{+ "runtime_config.mode",+ "openclaw gateway stop",+ "A Gateway is running for this state directory",+ },+ },+ {+ name: "gateway mode unchanged",+ mode: "gateway",+ stderr: `GatewayLockError("A Gateway is running for this state directory (pid 123, port 18789). Run without --local to use it, or stop the Gateway first (openclaw gateway stop).")`,+ wantAbsent: []string{"runtime_config.mode", "backends.openclaw.state_dir", "openclaw gateway stop"},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()+ fakePath := filepath.Join(t.TempDir(), "openclaw")+ script := "#!/bin/sh\n" ++ "if [ \"$1\" = \"--version\" ]; then\n" ++ " echo 'openclaw 2026.5.5 c37871e'\n" ++ " exit 0\n" ++ "fi\n" ++ "echo '" + tt.stderr + "' >&2\n" ++ "exit 1\n"+ writeTestExecutable(t, fakePath, []byte(script))++ backend, err := New("openclaw", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new openclaw backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "prompt", ExecOptions{+ Timeout: 5 * time.Second,+ OpenclawMode: tt.mode,+ })+ if err != nil {+ t.Fatalf("Execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result := <-session.Result:+ if result.Status != "failed" {+ t.Fatalf("status = %q, want failed", result.Status)+ }+ for _, want := range tt.wantContains {+ if !strings.Contains(result.Error, want) {+ t.Errorf("error missing %q: %s", want, result.Error)+ }+ }+ for _, unwanted := range tt.wantAbsent {+ if strings.Contains(result.Error, unwanted) {+ t.Errorf("error unexpectedly contains %q: %s", unwanted, result.Error)+ }+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ }+ })+ }+}