Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7312 LARI-10: Desktop PATH fix + CodeBuddy Claude-parity stream-json guards (#8340)

SeaSand10244d4cae7753f3
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 0d19e3a4f1..a2f7bbc7b9 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -27,6 +27,7 @@ import {
type RendererRecoveryWindow,
} from "./renderer-recovery";
import { createBestEffortDevLog } from "./dev-log";
+import { appendMissingPathDirs } from "./path-fallback";
import {
writeFreezeBreadcrumb,
readFreezeBreadcrumb,
@@ -107,15 +108,17 @@ const BUNDLED_ICON_PATH = join(__dirname, "../../resources/icon.png").replace(
// or any daemon-manager spawn.
if (process.platform !== "win32") {
fixPath();
- // Fallback: prepend common install locations in case fix-path came up
- // short (broken shell rc, non-interactive $SHELL, missing entries). Safe
- // to duplicate — PATH lookups short-circuit on first match.
- const fallbackPaths = [
+ // Fallback: ensure common install locations are on PATH when fix-path came
+ // up short (broken shell rc, non-interactive $SHELL, missing entries).
+ // Append only missing dirs — never prepend. Prepending /usr/local/bin over
+ // a recovered login PATH shadows nvm/fnm Node with a stale system binary
+ // (e.g. Node 12), which breaks shebang CLIs (`#!/usr/bin/env node`) such as
+ // CodeBuddy and OpenClaw during daemon --version probes.
+ process.env.PATH = appendMissingPathDirs(process.env.PATH ?? "", [
"/opt/homebrew/bin",
"/usr/local/bin",
join(homedir(), ".local/bin"),
- ];
- process.env.PATH = `${fallbackPaths.join(":")}:${process.env.PATH ?? ""}`;
+ ]);
}
const PROTOCOL = "multica";
diff --git a/apps/desktop/src/main/path-fallback.test.ts b/apps/desktop/src/main/path-fallback.test.ts
new file mode 100644
index 0000000000..4d07d5dace
--- /dev/null
+++ b/apps/desktop/src/main/path-fallback.test.ts
@@ -0,0 +1,47 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { appendMissingPathDirs } from "./path-fallback";
+
+describe("appendMissingPathDirs", () => {
+ const fallbacks = [
+ "/opt/homebrew/bin",
+ "/usr/local/bin",
+ "/Users/me/.local/bin",
+ ];
+
+ it("appends only dirs that are not already present", () => {
+ const current = "/Users/me/.nvm/versions/node/v22.0.0/bin:/usr/bin";
+ expect(appendMissingPathDirs(current, fallbacks)).toBe(
+ [
+ "/Users/me/.nvm/versions/node/v22.0.0/bin",
+ "/usr/bin",
+ "/opt/homebrew/bin",
+ "/usr/local/bin",
+ "/Users/me/.local/bin",
+ ].join(":"),
+ );
+ });
+
+ it("leaves PATH unchanged when every fallback is already present", () => {
+ const current = [
+ "/opt/homebrew/bin",
+ "/usr/local/bin",
+ "/Users/me/.local/bin",
+ "/usr/bin",
+ ].join(":");
+ expect(appendMissingPathDirs(current, fallbacks)).toBe(current);
+ });
+
+ it("still adds every fallback when PATH is empty", () => {
+ expect(appendMissingPathDirs("", fallbacks)).toBe(fallbacks.join(":"));
+ });
+
+ it("never prepends — recovered nvm Node stays ahead of /usr/local/bin", () => {
+ const current = "/Users/me/.nvm/versions/node/v22.0.0/bin";
+ const next = appendMissingPathDirs(current, ["/usr/local/bin"]);
+ expect(next.startsWith("/Users/me/.nvm/versions/node/v22.0.0/bin")).toBe(
+ true,
+ );
+ expect(next.endsWith("/usr/local/bin")).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/main/path-fallback.ts b/apps/desktop/src/main/path-fallback.ts
new file mode 100644
index 0000000000..1eab913c57
--- /dev/null
+++ b/apps/desktop/src/main/path-fallback.ts
@@ -0,0 +1,15 @@
+/**
+ * Append missing fallback directories onto a PATH string without prepending.
+ * Prepending (e.g. /usr/local/bin before nvm) shadows a recovered login-shell
+ * Node with a stale system binary and breaks shebang CLIs during daemon probes.
+ */
+export function appendMissingPathDirs(
+ currentPath: string,
+ fallbackDirs: readonly string[],
+ separator = ":",
+): string {
+ const current = currentPath.split(separator).filter(Boolean);
+ const existing = new Set(current);
+ const missing = fallbackDirs.filter((p) => !existing.has(p));
+ return [...current, ...missing].join(separator);
+}
diff --git a/server/pkg/agent/codebuddy.go b/server/pkg/agent/codebuddy.go
index 83c82acf85..f0d6e0dce6 100644
--- a/server/pkg/agent/codebuddy.go
+++ b/server/pkg/agent/codebuddy.go
@@ -142,7 +142,11 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
if opts.Cwd != "" {
cmd.Dir = opts.Cwd
}
- cmd.Env = buildEnv(b.cfg.Env)
+ // Multica closes stdin after the first result and cannot wait for
+ // cross-turn task_notification events. Force CodeBuddy's documented
+ // headless disable so Bash/PowerShell/Agent never take the background
+ // path (CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS; see CLI headless docs).
+ cmd.Env = buildCodebuddyEnv(b.cfg.Env)
stdout, err := cmd.StdoutPipe()
if err != nil {
@@ -201,6 +205,7 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
var finalResultText string
sawResult := false
resultIsError := false
+ sawBackgroundTask := false
var sessionID string
usage := make(map[string]TokenUsage)
seenUsage := make(map[string]struct{})
@@ -247,6 +252,14 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
if msg.SessionID != "" {
sessionID = msg.SessionID
}
+ // CodeBuddy background lifecycle rides on system subtypes
+ // (task_started / task_progress / task_updated /
+ // task_notification), not Claude's async_launched tool_result.
+ // With CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS these should
+ // never appear; if they do, fail rather than report success.
+ if codebuddySystemIsBackgroundTask(msg.Subtype) {
+ sawBackgroundTask = true
+ }
trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sessionID})
case "result":
sawResult = true
@@ -287,6 +300,10 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
// broken pipe, or been unblocked by the kill that ended cmd.
writeErr := <-writeDone
+ completionGuardError := ""
+ if sawBackgroundTask {
+ completionGuardError = "codebuddy emitted a background task system event; Multica-managed runs require foreground execution (set CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS=1)"
+ }
finalStatus, finalOutput, finalError := finalizeStreamResult(
"codebuddy",
timeout,
@@ -301,11 +318,14 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
resultIsError: resultIsError,
scanErr: scanErr,
},
- "",
+ completionGuardError,
)
+ // cmd.Wait() has returned — stderrBuf.Tail() is complete. Resume
+ // rejection phrases often land only on stderr (mirror Claude MUL-4966).
+ stderrTail := stderrBuf.Tail()
if finalError != "" {
- finalError = withAgentStderr(finalError, "codebuddy", stderrBuf.Tail())
+ finalError = withAgentStderr(finalError, "codebuddy", stderrTail)
}
logStreamProtocolObservation(b.cfg.Logger, streamProtocolObservation{
provider: "codebuddy",
@@ -327,8 +347,8 @@ func (b *codebuddyBackend) Execute(ctx context.Context, prompt string, opts Exec
b.cfg.Logger.Info("codebuddy finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
- resumeRejected := resumeWasRejected(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError)
- reportedSessionID := resolveSessionID(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError)
+ resumeRejected := resumeWasRejected(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError, stderrTail)
+ reportedSessionID := resolveSessionID(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError, stderrTail)
if resumeRejected {
b.cfg.Logger.Info("codebuddy resume was rejected; dropping session id and signalling fresh-session retry",
"requested_resume", opts.ResumeSessionID,
@@ -455,6 +475,10 @@ func (b *codebuddyBackend) handleControlRequest(msg codebuddySDKMessage, stdin i
if inputMap == nil {
inputMap = map[string]any{}
}
+ // Do not rewrite run_in_background here: under bypassPermissions most
+ // tools never emit control_request, and CodeBuddy does not use Claude's
+ // async_launched tool_result shape. Background work is disabled via
+ // CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS before tool execution.
response := map[string]any{
"type": "control_response",
@@ -508,6 +532,32 @@ func writeCodebuddyInput(w io.Writer, prompt string) error {
return nil
}
+const codebuddyDisableBackgroundTasksEnv = "CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS"
+
+// buildCodebuddyEnv merges task env and always forces background tasks off.
+// Multica's adapter closes stdin after the first result; CodeBuddy's
+// background lifecycle can push task_notification after that point, which we
+// cannot observe. The official CLI documents this variable for exactly that
+// headless shape (https://www.codebuddy.ai/docs/cli/headless).
+//
+// Append the forced entry last so os/exec's platform-aware dedup
+// (case-insensitive on Windows, last-wins) keeps our "=1" even when the
+// inherited or custom_env key differs only by case.
+func buildCodebuddyEnv(extra map[string]string) []string {
+ return append(buildEnv(extra), codebuddyDisableBackgroundTasksEnv+"=1")
+}
+
+// codebuddySystemIsBackgroundTask reports CodeBuddy's real background-task
+// system subtypes (not Claude's async_launched tool_result).
+func codebuddySystemIsBackgroundTask(subtype string) bool {
+ switch strings.TrimSpace(subtype) {
+ case "task_started", "task_progress", "task_updated", "task_notification":
+ return true
+ default:
+ return false
+ }
+}
+
// ── Codebuddy SDK JSON types ──
type codebuddySDKMessage struct {
@@ -518,7 +568,9 @@ type codebuddySDKMessage struct {
Model string `json:"model,omitempty"`
ParentToolUseID string `json:"parent_tool_use_id,omitempty"`
- // result fields
+ // result fields — CodeBuddy failures use is_error + errors/errors_info;
+ // there is no Claude-style terminal_reason=prompt_too_long signal in the
+ // shipped @tencent-ai/codebuddy-code 2.150.0 protocol.
ResultText string `json:"result,omitempty"`
IsError bool `json:"is_error,omitempty"`
DurationMs float64 `json:"duration_ms,omitempty"`
diff --git a/server/pkg/agent/codebuddy_test.go b/server/pkg/agent/codebuddy_test.go
index 9863a8230f..e8707a09f4 100644
--- a/server/pkg/agent/codebuddy_test.go
+++ b/server/pkg/agent/codebuddy_test.go
@@ -520,3 +520,163 @@ func TestCodebuddyHandleControlRequestApprovesInCodebuddyShape(t *testing.T) {
t.Fatalf("expected the original tool input to be preserved, got %v", updatedInput["command"])
}
}
+
+func TestBuildCodebuddyEnvDisablesBackgroundTasks(t *testing.T) {
+ t.Parallel()
+
+ env := buildCodebuddyEnv(map[string]string{"FOO": "bar"})
+ if got := lastEnvValueFold(env, codebuddyDisableBackgroundTasksEnv); got != "1" {
+ t.Fatalf("expected %s=1 in child env, got %q (env=%v)", codebuddyDisableBackgroundTasksEnv, got, env)
+ }
+
+ // Exact-key override in caller env must still lose to the appended force.
+ env = buildCodebuddyEnv(map[string]string{codebuddyDisableBackgroundTasksEnv: "0"})
+ if got := lastEnvValueFold(env, codebuddyDisableBackgroundTasksEnv); got != "1" {
+ t.Fatalf("expected forced %s=1 even when caller passes 0, got %q", codebuddyDisableBackgroundTasksEnv, got)
+ }
+
+ // Windows os/exec dedups case-insensitively and keeps the last entry. A
+ // lowercase custom_env key must not outvote the forced disable.
+ env = buildCodebuddyEnv(map[string]string{
+ strings.ToLower(codebuddyDisableBackgroundTasksEnv): "0",
+ })
+ if got := lastEnvValueFold(env, codebuddyDisableBackgroundTasksEnv); got != "1" {
+ t.Fatalf("expected forced %s=1 to win over lowercase override, got %q (env=%v)",
+ codebuddyDisableBackgroundTasksEnv, got, env)
+ }
+ lastExact := ""
+ for _, entry := range env {
+ key, value, ok := strings.Cut(entry, "=")
+ if ok && key == codebuddyDisableBackgroundTasksEnv {
+ lastExact = value
+ }
+ }
+ if lastExact != "1" {
+ t.Fatalf("forced entry must be last exact key so os/exec Windows dedup keeps it, got last=%q env=%v", lastExact, env)
+ }
+}
+
+// lastEnvValueFold mirrors os/exec's Windows dedup: case-insensitive key match,
+// last occurrence wins.
+func lastEnvValueFold(env []string, key string) string {
+ got := ""
+ for _, entry := range env {
+ k, v, ok := strings.Cut(entry, "=")
+ if ok && strings.EqualFold(k, key) {
+ got = v
+ }
+ }
+ return got
+}
+
+func TestCodebuddySystemIsBackgroundTask(t *testing.T) {
+ t.Parallel()
+
+ for _, subtype := range []string{"task_started", "task_progress", "task_updated", "task_notification"} {
+ if !codebuddySystemIsBackgroundTask(subtype) {
+ t.Fatalf("expected %q to be a background-task system subtype", subtype)
+ }
+ }
+ for _, subtype := range []string{"init", "status", "", "session_started"} {
+ if codebuddySystemIsBackgroundTask(subtype) {
+ t.Fatalf("did not expect %q to be treated as background-task", subtype)
+ }
+ }
+}
+
+func TestCodebuddyExecuteResumeRejectedFromStderr(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ fakePath := filepath.Join(t.TempDir(), "codebuddy")
+ script := "#!/bin/sh\n" +
+ "IFS= read -r _\n" +
+ "echo \"No conversation found with session ID: sess-dead\" >&2\n" +
+ "exit 1\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ b := &codebuddyBackend{cfg: Config{ExecutablePath: fakePath, Logger: slog.Default()}}
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := b.Execute(ctx, "prompt", ExecOptions{
+ Timeout: 5 * time.Second,
+ ResumeSessionID: "sess-dead",
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result, ok := <-session.Result:
+ if !ok {
+ t.Fatal("result channel closed without a value")
+ }
+ if result.Status != "failed" {
+ t.Fatalf("expected failed, got %q (%q)", result.Status, result.Error)
+ }
+ if !result.ResumeRejected {
+ t.Fatalf("expected ResumeRejected when stderr reports missing session, got %+v", result)
+ }
+ if result.SessionID != "" {
+ t.Fatalf("expected empty SessionID after resume rejection, got %q", result.SessionID)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}
+
+func TestCodebuddyExecuteFailsOnBackgroundTaskStarted(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+
+ // Replay the CodeBuddy 2.150.0 background-task shape from the headless
+ // docs: Bash tool_use → system/task_started → text tool_result → success
+ // result. Without a completion guard this used to report completed.
+ fakePath := filepath.Join(t.TempDir(), "codebuddy")
+ script := "#!/bin/sh\n" +
+ "IFS= read -r _\n" +
+ `printf '%s\n' '{"type":"system","subtype":"init","session_id":"sess-bg"}'` + "\n" +
+ `printf '%s\n' '{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_01","name":"Bash","input":{"command":"sleep 60","run_in_background":true}}]}}'` + "\n" +
+ `printf '%s\n' '{"type":"system","subtype":"task_started","task_id":"bash-1","tool_use_id":"toolu_01","description":"sleep 60","task_type":"Bash","session_id":"sess-bg"}'` + "\n" +
+ `printf '%s\n' '{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01","content":"Started the build in the background."}]}}'` + "\n" +
+ `printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id":"sess-bg","result":"Started the build in the background."}'` + "\n" +
+ "exit 0\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ b := &codebuddyBackend{cfg: Config{ExecutablePath: fakePath, Logger: slog.Default()}}
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := b.Execute(ctx, "prompt", ExecOptions{Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result, ok := <-session.Result:
+ if !ok {
+ t.Fatal("result channel closed without a value")
+ }
+ if result.Status != "failed" {
+ t.Fatalf("expected failed when system/task_started appears, got %q (%q)", result.Status, result.Error)
+ }
+ if !strings.Contains(result.Error, "background task") {
+ t.Fatalf("expected background-task error, got %q", result.Error)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timeout waiting for result")
+ }
+}