Skip to content

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

Go

feat(agent): add the Muse app backend (remote receptionist) [MUL-7945] (#9155)

Xichang(Seacen) Zhao5983213f6e30
diff --git a/packages/core/runtimes/display.ts b/packages/core/runtimes/display.ts
index 4bedbfc4d0..f5cce841e5 100644
--- a/packages/core/runtimes/display.ts
+++ b/packages/core/runtimes/display.ts
@@ -37,7 +37,7 @@ export function runtimeDisplayLabel(
* (server/internal/daemon/daemon.go): the daemon bakes that display name into
* `name` for the no-alias case (for example, "Trae (host)"), so the aliased label has to use
* the exact same names or the two paths drift apart (#5260). `qoderclicn`,
- * `codearts`, `dsh`, `traecli`, `qwen`, `qwenpaw`, `mcode`, `muse`, and `zeroclaw` need overrides today — every other provider is a
+ * `codearts`, `dsh`, `traecli`, `qwen`, `qwenpaw`, `mcode`, `muse`, `museapp`, and `zeroclaw` need overrides today — every other provider is a
* first-letter capitalization of its slug on both sides. Keep in sync with the daemon map.
*/
const PROVIDER_DISPLAY_NAMES: Record<string, string> = {
@@ -50,6 +50,7 @@ const PROVIDER_DISPLAY_NAMES: Record<string, string> = {
qwenpaw: "QwenPaw",
mcode: "MiniMax Code",
muse: "Muse Code",
+ museapp: "Muse app",
omp: "Oh-My-Pi",
zeroclaw: "ZeroClaw",
zcode: "ZCode",
diff --git a/packages/views/runtimes/components/museapp-logo.svg b/packages/views/runtimes/components/museapp-logo.svg
new file mode 100644
index 0000000000..682190822c
--- /dev/null
+++ b/packages/views/runtimes/components/museapp-logo.svg
@@ -0,0 +1,10 @@
+<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M24.6257 16.1214C28.2365 16.1214 30.8187 18.9408 30.8187 23.3643C30.8185 27.7868 30.1055 31.7765 28.9225 40.2466C28.0743 46.1813 26.62 55.2418 26.0132 59.0088C27.1782 56.7815 29.9074 51.5757 30.3914 50.5982C36.1081 39.061 42.0657 28.7544 43.7826 26.0254C46.0594 22.382 48.062 20.9229 51.1597 20.9229C52.7685 20.923 54.6826 21.7357 55.6315 22.819C56.9178 24.2895 57.1859 26.6602 57.1411 29.244C57.0738 33.2073 56.5599 39.5264 55.8553 46.5698C55.5416 49.7057 54.9365 56.1066 54.5288 60.4004C58.1883 53.8532 64.9609 41.8109 67.6921 37.6058C70.0727 33.9402 72.466 31.5797 75.6836 31.5796C78.4595 31.5796 81.8809 33.5416 81.6772 38.7573C81.3774 46.4556 80.2673 63.2232 79.7607 70.7479C83.1662 65.7913 87.6377 58.4543 89.3148 55.6966C91.0104 52.908 92.75 50.6542 95.3898 50.5778C98.0987 50.4995 99.913 52.341 99.9959 55.1839C100.078 58.0277 98.3835 61.2256 96.1344 64.856C93.6937 68.7957 90.9621 73.0123 87.6383 76.9491C84.3148 80.8856 81.2604 83.8782 76.5991 83.8786C72.4243 83.8786 69.4869 81.1043 69.283 76.0254C69.1768 73.364 69.6804 67.6405 70.0602 63.1673C70.5 57.9875 71.0315 52.9861 71.403 49.6786C67.7337 56.3979 60.0101 70.4676 56.5348 75.9603C53.1343 81.3339 51.4774 83.2269 47.8882 83.2275C44.2977 83.2275 42.7226 80.6416 42.6717 76.7497C42.6142 72.5285 45.7852 47.1821 46.8587 38.737C45.1183 42.4616 40.839 51.6056 38.1551 57.0435C35.5587 62.3055 31.204 71.3978 28.0436 76.6357C25.7668 80.4094 23.2092 83.2273 19.4173 83.2275C15.6252 83.2275 13.4847 80.6784 13.4847 76.5788C13.4847 72.4794 14.6716 65.6492 15.9465 57.1777C16.5839 53.0781 17.3108 48.6133 18.1315 43.8761C18.7324 40.448 19.7764 34.4169 20.4183 30.7129C17.502 35.2539 12.2536 43.4278 10.6567 45.8903C8.88113 48.6291 7.28747 50.626 4.64681 50.6266C1.7329 50.6266 0.000532901 48.3522 0 45.7113C0 43.0703 1.34323 41.0344 3.52376 37.4512C6.32403 32.8465 11.3578 26.57 14.1154 23.2747C17.3656 19.3912 20.6139 16.1219 24.6257 16.1214Z" fill="url(#paint0_linear_454_562)"/>
+<defs>
+<linearGradient id="paint0_linear_454_562" x1="133.245" y1="109.046" x2="24.9203" y2="-12.5565" gradientUnits="userSpaceOnUse">
+<stop offset="0.254808" stop-color="#0082FB" style="stop-color:#0082FB;stop-color:color(display-p3 0.0000 0.5098 0.9843);stop-opacity:1;"/>
+<stop offset="0.697115" stop-color="#0064E0" style="stop-color:#0064E0;stop-color:color(display-p3 0.0000 0.3922 0.8784);stop-opacity:1;"/>
+<stop offset="1" stop-color="#0040DC" style="stop-color:#0040DC;stop-color:color(display-p3 0.0000 0.2510 0.8627);stop-opacity:1;"/>
+</linearGradient>
+</defs>
+</svg>
diff --git a/packages/views/runtimes/components/provider-logo.test.tsx b/packages/views/runtimes/components/provider-logo.test.tsx
new file mode 100644
index 0000000000..c5cf7ad52c
--- /dev/null
+++ b/packages/views/runtimes/components/provider-logo.test.tsx
@@ -0,0 +1,23 @@
+import { render } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import museappLogo from "./museapp-logo.svg";
+import { ProviderLogo } from "./provider-logo";
+
+// Vite inlines a small SVG as a data: URL and Next hands back a { src } object,
+// so the test compares against the imported asset itself rather than a filename.
+const museappSrc = typeof museappLogo === "string" ? museappLogo : museappLogo.src;
+
+describe("ProviderLogo", () => {
+ it("draws the Muse app mark rather than the generic fallback", () => {
+ const { container } = render(<ProviderLogo provider="museapp" className="h-4 w-4" />);
+ const img = container.querySelector("img");
+ expect(img).not.toBeNull();
+ expect(img?.getAttribute("src")).toBe(museappSrc);
+ });
+
+ it("still falls back for a provider it has no mark for", () => {
+ const { container } = render(<ProviderLogo provider="no-such-provider" />);
+ expect(container.querySelector("img")).toBeNull();
+ expect(container.querySelector("svg")).not.toBeNull();
+ });
+});
diff --git a/packages/views/runtimes/components/provider-logo.tsx b/packages/views/runtimes/components/provider-logo.tsx
index a9b960b952..fed85d2d7e 100644
--- a/packages/views/runtimes/components/provider-logo.tsx
+++ b/packages/views/runtimes/components/provider-logo.tsx
@@ -4,6 +4,7 @@ import codeartsLogo from "./codearts-logo.svg";
import qwenLogo from "./qwen-logo.svg";
import reasonixLogo from "./reasonix-logo.svg";
import dimLogo from "./dim-logo.png";
+import museappLogo from "./museapp-logo.svg";
// Next.js exposes static imports as objects while Vite exposes URL strings.
// Normalize both shapes here so shared provider logos work in web and desktop.
@@ -386,6 +387,18 @@ function ZeroClawLogo({ className }: { className: string }) {
);
}
+// Muse app (Meta's personal AI agent, reached through a remote receptionist) —
+// the squiggle "M" as muse.ai serves it
+// (https://muse.ai/images/landing/brand/muse-logo.svg), copied verbatim. Not
+// the Muse Code CLI mark above: that is a different product with its own
+// runtime. Rendered through <img> like the other asset logos, which also keeps
+// the SVG's own gradient id from colliding when several rows share a page.
+const museappLogoSrc = staticAssetSrc(museappLogo);
+
+function MuseAppLogo({ className }: { className: string }) {
+ return <img src={museappLogoSrc} alt="" aria-hidden className={className} />;
+}
+
// Minimal placeholder until ZCode ships an official mark; currentColor keeps
// it legible in both themes. Swap for a real asset when one exists, following
// the DimLogo <img> pattern.
@@ -465,6 +478,8 @@ export function ProviderLogo({
return <McodeLogo className={className} />;
case "muse":
return <MuseLogo className={className} />;
+ case "museapp":
+ return <MuseAppLogo className={className} />;
case "dsh":
return <DshLogo className={className} />;
case "dim":
diff --git a/server/internal/daemon/agents_probe.go b/server/internal/daemon/agents_probe.go
index 3cb3d31140..fbec923b8b 100644
--- a/server/internal/daemon/agents_probe.go
+++ b/server/internal/daemon/agents_probe.go
@@ -340,6 +340,19 @@ var probeAgentCLIs = func() map[string]AgentEntry {
if e, ok := probe("MULTICA_ZEROCLAW_PATH", "zeroclaw", ""); ok {
agents["zeroclaw"] = e
}
+ // museapp (muse.ai) is not a CLI: there is no binary to discover. The
+ // daemon advertises a museapp runtime exactly when
+ // MULTICA_MUSEAPP_ENDPOINT points at a Muse receptionist; reachability and
+ // protocol version are verified against the receptionist itself in
+ // probeBuiltinRuntime (there is no --version to run).
+ // MULTICA_MUSEAPP_MODEL is informational only — the backend's wire
+ // protocol has no model parameter, see ModelSelectionSupported.
+ if strings.TrimSpace(os.Getenv("MULTICA_MUSEAPP_ENDPOINT")) != "" {
+ agents["museapp"] = AgentEntry{
+ Command: "museapp",
+ Model: strings.TrimSpace(os.Getenv("MULTICA_MUSEAPP_MODEL")),
+ }
+ }
if e, ok := probe("MULTICA_ZCODE_PATH", "zcode", "MULTICA_ZCODE_MODEL"); ok {
agents["zcode"] = e
} else if strings.TrimSpace(os.Getenv("MULTICA_ZCODE_PATH")) == "" {
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 0c0f5de0f2..70881082f8 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -10,6 +10,7 @@ import (
"net/http"
"net/url"
"runtime"
+ "slices"
"strings"
"sync"
"time"
@@ -489,7 +490,8 @@ func (c *Client) StartTask(ctx context.Context, task Task, capabilities ...strin
return fmt.Errorf("%w: task start exceeds %d bytes", errInvalidResponseBody, maxStartTaskResponseBytes)
}
var response struct {
- SupplementCapability string `json:"supplement_capability"`
+ SupplementCapability string `json:"supplement_capability"`
+ ProcessCleanupCapability string `json:"process_cleanup_capability"`
}
// Empty acknowledgements start the task without negotiating supplements.
// Invalid JSON fails without retrying; transport read failures can retry.
@@ -499,6 +501,9 @@ func (c *Client) StartTask(ctx context.Context, task Task, capabilities ...strin
}
}
negotiated = response.SupplementCapability == protocol.DaemonCapabilityTaskSupplementV1
+ if slices.Contains(capabilities, protocol.DaemonCapabilityMuseAppProcessCleanupV1) && response.ProcessCleanupCapability != protocol.DaemonCapabilityMuseAppProcessCleanupV1 {
+ return fmt.Errorf("%w: Muse app requires server support for remote execution cleanup; upgrade the Multica server before using this runtime", errInvalidResponseBody)
+ }
return nil
}
path := fmt.Sprintf("/api/daemon/tasks/%s/start", task.ID)
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.go
index adece8c188..b246194757 100644
--- a/server/internal/daemon/config.go
+++ b/server/internal/daemon/config.go
@@ -111,7 +111,7 @@ type Config struct {
CLICommit string // full build revision embedded in the running CLI; empty/unknown if unavailable
LaunchedBy string // "desktop" when spawned by the Electron app, empty for standalone
Profile string // profile name (empty = default)
- Agents map[string]AgentEntry // keyed by provider: claude, codebuddy, codex, copilot, opencode, codearts, deveco, openclaw, hermes, pi, cursor, kimi, reasonix, dsh, kiro, antigravity, qoder, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, dim, zeroclaw (plus built-in runtime identities from agent.BuiltinRuntimes, e.g. omp)
+ Agents map[string]AgentEntry // keyed by provider: claude, codebuddy, codex, copilot, opencode, codearts, deveco, openclaw, hermes, pi, cursor, kimi, reasonix, dsh, kiro, antigravity, qoder, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, muse, devin, dim, zeroclaw, museapp (plus built-in runtime identities from agent.BuiltinRuntimes, e.g. omp)
WorkspacesRoot string // base path for execution envs (default: ~/multica_workspaces)
HealthPort int // local HTTP port for health checks (default: 19514)
MaxConcurrentTasks int // max tasks running in parallel (default: 20)
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 781390ce20..88e11690fc 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -2369,6 +2369,11 @@ const (
builtinProbeOK builtinProbeVerdict = iota
builtinProbeUnavailable
builtinProbeBelowMinimum
+ // builtinProbeProtocolSkew: the backend and its remote counterpart
+ // (e.g. the museapp receptionist) speak different protocol versions.
+ // Deterministic like below-minimum: retrying won't fix it, and an
+ // already-registered runtime must be demoted so it stops taking tasks.
+ builtinProbeProtocolSkew
// builtinProbeNotExecutable: the file resolved, but the OS rejected it as
// not a runnable program (an npm placeholder stub whose postinstall was
// blocked is the case in the field — MUL-6164). Deterministic in the same
@@ -2414,7 +2419,7 @@ const (
// learned this round.
func demotableBuiltinProbeVerdict(verdict builtinProbeVerdict) bool {
switch verdict {
- case builtinProbeBelowMinimum, builtinProbeNotExecutable, builtinProbeMissingProfile, builtinProbeProfileMigration:
+ case builtinProbeBelowMinimum, builtinProbeProtocolSkew, builtinProbeNotExecutable, builtinProbeMissingProfile, builtinProbeProfileMigration:
return true
}
return false
@@ -2427,10 +2432,11 @@ func demotableBuiltinProbeVerdict(verdict builtinProbeVerdict) bool {
// string this round already parsed, so a second look reaches the same
// conclusion. The other demotable verdicts describe deterministic states but
// rest on an observation that is not — an installer overwriting the bin entry in
-// place (the very repair we tell users to run) or a DSH upgrade moving the
-// profile under a probe. Requiring a second sighting a window later makes those
-// windows impossible to mistake for a verdict, and costs a genuinely broken
-// provider one extra round.
+// place (the very repair we tell users to run), a DSH upgrade moving the
+// profile under a probe, or a museapp receptionist mid-upgrade answering one
+// /v1/health with another protocol version. Requiring a second sighting a
+// window later makes those windows impossible to mistake for a verdict, and
+// costs a genuinely broken provider one extra round.
func builtinProbeNeedsConfirmation(verdict builtinProbeVerdict) bool {
return verdict != builtinProbeBelowMinimum
}
@@ -2531,6 +2537,12 @@ func newRuntimeVerdict(verdict builtinProbeVerdict, reason, execPath string, ins
// not installed" apart from "CLI installed but dropped at registration", which
// was previously only visible in the daemon log (MUL-5439).
func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry AgentEntry) (string, string, builtinProbeVerdict) {
+ // museapp has no local binary: version detection runs against the remote
+ // receptionist instead. This must come before any path resolution — an
+ // empty entry.Path is expected here, not a missing CLI.
+ if name == "museapp" {
+ return d.probeMuseAppReceptionist(ctx)
+ }
var (
lastErr error
attempts int
@@ -2738,6 +2750,37 @@ probeLoop:
return "", reason, builtinProbeUnavailable
}
+// probeMuseAppReceptionist is the museapp equivalent of CLI version detection.
+// There is no local binary to --version, so reachability and the wire
+// protocol version come from the receptionist's /v1/health endpoint.
+// A protocol-skewed receptionist is builtinProbeProtocolSkew (demotable):
+// the version mismatch is deterministic, so an already-registered runtime
+// must stop taking tasks instead of failing them mid-run. Skew goes
+// through confirmation (builtinProbeNeedsConfirmation) since the verdict
+// rests on a live HTTP response, not a locally parsed string.
+// An unreachable receptionist is builtinProbeUnavailable (transient):
+// the runtime stays unregistered without demoting anything,
+// and a later probe round recovers it — the same rule a CLI whose
+// --version fails gets. A missing MULTICA_MUSEAPP_ENDPOINT simply never reaches
+// here (probeAgentCLIs only advertises museapp when it is set); the guard stays
+// as defense for callers that bypass discovery.
+func (d *Daemon) probeMuseAppReceptionist(ctx context.Context) (string, string, builtinProbeVerdict) {
+ endpoint := strings.TrimSpace(os.Getenv("MULTICA_MUSEAPP_ENDPOINT"))
+ if endpoint == "" {
+ return "", "MULTICA_MUSEAPP_ENDPOINT is not set", builtinProbeUnavailable
+ }
+ version, err := agent.ProbeMuseAppReceptionist(ctx, endpoint, strings.TrimSpace(os.Getenv("MULTICA_MUSEAPP_TOKEN")))
+ if err != nil {
+ d.logger.Warn("skip registering runtime: museapp receptionist probe failed", "error", err)
+ if errors.Is(err, agent.ErrMuseAppProtocolSkew) {
+ return "", err.Error(), builtinProbeProtocolSkew
+ }
+ return "", err.Error(), builtinProbeUnavailable
+ }
+ d.setAgentVersion("museapp", version)
+ return version, "", builtinProbeOK
+}
+
// detectBuiltinRuntimes probes configured CLIs with bounded concurrency and
// returns registration entries that resolve and meet minimum versions. Reuse a
// single probe result when registering several workspaces.
@@ -5992,7 +6035,7 @@ func taskCancelAcknowledgement(result TaskResult, runErr error, provider string)
ack.FailureReason = "local_directory_error"
}
confirmed := result.FailureReason != taskfailure.ReasonProcessCleanupUnconfirmed.String()
- if provider == "pi" || provider == "omp" {
+ if provider == "pi" || provider == "omp" || provider == "museapp" {
ack.ProcessCleanupConfirmed = &confirmed
}
if !confirmed {
@@ -6532,6 +6575,7 @@ var runtimeDisplayNameOverrides = map[string]string{
"qwenpaw": "QwenPaw",
"mcode": "MiniMax Code",
"muse": "Muse Code",
+ "museapp": "Muse app",
"zcode": "ZCode",
"zeroclaw": "ZeroClaw",
}
@@ -8599,6 +8643,9 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
if provider == "pi" || provider == "omp" {
taskCapabilities = append(taskCapabilities, protocol.DaemonCapabilityPiProcessCleanupV1)
}
+ if provider == "museapp" {
+ taskCapabilities = append(taskCapabilities, protocol.DaemonCapabilityMuseAppProcessCleanupV1)
+ }
var cursorHookCommand []string
supplementSupported := agent.SupportsTaskSupplement(provider, resolvedVersion) && task.IssueID != ""
if supplementSupported && provider == "cursor" {
@@ -8958,6 +9005,9 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// can never pay for it twice (MUL-5722).
ResumeExpected: task.PriorSessionID != "",
ResumeContinuityNotice: backendResumeContinuityNotice(task),
+ TaskToken: agentToken,
+ MulticaServerURL: d.cfg.ServerBaseURL,
+ MulticaWorkspaceID: task.WorkspaceID,
ExtraArgs: extraArgs,
CustomArgs: customArgs,
McpConfig: mcpConfig,
diff --git a/server/internal/daemon/daemon_museapp_test.go b/server/internal/daemon/daemon_museapp_test.go
new file mode 100644
index 0000000000..6bd0547e6e
--- /dev/null
+++ b/server/internal/daemon/daemon_museapp_test.go
@@ -0,0 +1,151 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// A version-mismatched receptionist must yield builtinProbeProtocolSkew
+// (demotable), not builtinProbeUnavailable.
+func TestProbeMuseAppReceptionistProtocolSkew(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/v1/health", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "protocol_version": 999,
+ "version": "9.9",
+ })
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+
+ t.Setenv("MULTICA_MUSEAPP_ENDPOINT", srv.URL)
+ t.Setenv("MULTICA_MUSEAPP_TOKEN", "")
+
+ d := newTestDaemon(t)
+ _, _, verdict := d.probeMuseAppReceptionist(context.Background())
+ if verdict != builtinProbeProtocolSkew {
+ t.Errorf("verdict = %v, want builtinProbeProtocolSkew", verdict)
+ }
+}
+
+// TestProbeMuseAppReceptionistOK: matching version yields builtinProbeOK.
+func TestProbeMuseAppReceptionistOK(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/v1/health", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "protocol_version": 1,
+ "version": "1.4.0",
+ })
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+
+ t.Setenv("MULTICA_MUSEAPP_ENDPOINT", srv.URL)
+ t.Setenv("MULTICA_MUSEAPP_TOKEN", "")
+
+ d := newTestDaemon(t)
+ d.agentVersions = make(map[string]string)
+ version, _, verdict := d.probeMuseAppReceptionist(context.Background())
+ if verdict != builtinProbeOK {
+ t.Errorf("verdict = %v, want builtinProbeOK", verdict)
+ }
+ if version != "1.4.0" {
+ t.Errorf("version = %q, want 1.4.0", version)
+ }
+}
+
+// Protocol skew must go through confirmation (not exempt like below-minimum).
+func TestProbeMuseAppReceptionistSkewNeedsConfirmation(t *testing.T) {
+ if !builtinProbeNeedsConfirmation(builtinProbeProtocolSkew) {
+ t.Error("builtinProbeProtocolSkew should need confirmation")
+ }
+ if builtinProbeNeedsConfirmation(builtinProbeBelowMinimum) {
+ t.Error("builtinProbeBelowMinimum should NOT need confirmation")
+ }
+}
+
+// Ensure the agent package is referenced (for ErrMuseAppProtocolSkew mapping).
+var _ = agent.ErrMuseAppProtocolSkew
+
+// TestProbeMuseAppReceptionistNoEndpoint: missing endpoint yields unavailable.
+func TestProbeMuseAppReceptionistNoEndpoint(t *testing.T) {
+ t.Setenv("MULTICA_MUSEAPP_ENDPOINT", "")
+ d := newTestDaemon(t)
+ _, _, verdict := d.probeMuseAppReceptionist(context.Background())
+ if verdict != builtinProbeUnavailable {
+ t.Errorf("verdict = %v, want builtinProbeUnavailable", verdict)
+ }
+}
+
+func TestMuseAppCleanupUnconfirmedOutranksCancellation(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/v1/execute" {
+ _ = json.NewEncoder(w).Encode(map[string]any{"task_id": "remote-worker", "protocol_version": 1})
+ return
+ }
+ _ = json.NewEncoder(w).Encode(map[string]bool{"ok": true})
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_MUSEAPP_ENDPOINT", srv.URL)
+ t.Setenv("MULTICA_MUSEAPP_TOKEN", "")
+ backend, err := agent.New("museapp", agent.Config{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ d := newTestDaemon(t)
+ d.client = NewClient(srv.URL)
+ d.cfg.AgentIdleWatchdog = 0
+ result, _, err := d.executeAndDrain(ctx, cancelMuseAppAfterExecute{Backend: backend, cancel: cancel}, "edit the shared workdir", agent.ExecOptions{}, slog.Default(), "task", "", new(atomic.Int32))
+ if err != nil || result.Status != "cleanup_unconfirmed" {
+ t.Fatalf("result = %+v, err = %v", result, err)
+ }
+ if d.ShutdownCleanupConfirmed() {
+ t.Fatal("daemon forgot the active remote worker")
+ }
+ ack := taskCancelAcknowledgement(TaskResult{FailureReason: "cleanup_unconfirmed", Comment: result.Error}, nil, "museapp")
+ if ack.ProcessCleanupConfirmed == nil || *ack.ProcessCleanupConfirmed {
+ t.Fatal("cancel acknowledgement discarded unconfirmed remote cleanup")
+ }
+}
+
+type cancelMuseAppAfterExecute struct {
+ agent.Backend
+ cancel context.CancelFunc
+}
+
+func (b cancelMuseAppAfterExecute) Execute(ctx context.Context, prompt string, opts agent.ExecOptions) (*agent.Session, error) {
+ session, err := b.Backend.Execute(ctx, prompt, opts)
+ b.cancel()
+ return session, err
+}
+
+func TestMuseAppStartRequiresServerCleanupCapability(t *testing.T) {
+ for _, mode := range []bool{false, true} {
+ for _, acknowledged := range []bool{false, true} {
+ task := startTestClaim()
+ task.StartClaimSupported = mode
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ response := map[string]string{}
+ if acknowledged {
+ response["process_cleanup_capability"] = protocol.DaemonCapabilityMuseAppProcessCleanupV1
+ }
+ _ = json.NewEncoder(w).Encode(response)
+ }))
+ _, err := NewClient(srv.URL).StartTask(context.Background(), task, protocol.DaemonCapabilityMuseAppProcessCleanupV1)
+ srv.Close()
+ if (err == nil) != acknowledged {
+ t.Fatalf("claim=%v acknowledged=%v error=%v", mode, acknowledged, err)
+ }
+ }
+ }
+}
diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.go
index 041b16f2a5..f72cf3c262 100644
--- a/server/internal/daemon/execenv/runtime_config.go
+++ b/server/internal/daemon/execenv/runtime_config.go
@@ -218,7 +218,7 @@ func runtimeConfigPath(workDir, provider string) string {
return filepath.Join(workDir, "CODEBUDDY.md")
case "qwen":
return filepath.Join(workDir, "QWEN.md")
- case "codex", "copilot", "opencode", "codearts", "deveco", "openclaw", "hermes", "pi", "cursor", "kimi", "reasonix", "dsh", "kiro", "antigravity", "qoder", "qoderclicn", "traecli", "grok", "qwenpaw", "mcode", "muse", "dim", "zeroclaw", "devin", "zcode":
+ case "codex", "copilot", "opencode", "codearts", "deveco", "openclaw", "hermes", "pi", "cursor", "kimi", "reasonix", "dsh", "kiro", "antigravity", "qoder", "qoderclicn", "traecli", "grok", "qwenpaw", "mcode", "muse", "dim", "zeroclaw", "devin", "museapp", "zcode":
return filepath.Join(workDir, "AGENTS.md")
default:
return ""
diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.go
index 61d25705d8..70c8ca53cb 100644
--- a/server/internal/daemon/execenv/runtime_config_test.go
+++ b/server/internal/daemon/execenv/runtime_config_test.go
@@ -1088,6 +1088,7 @@ func TestInjectRuntimeConfigPreservesUserContent(t *testing.T) {
{"zeroclaw", "AGENTS.md"},
{"kiro", "AGENTS.md"},
{"antigravity", "AGENTS.md"},
+ {"museapp", "AGENTS.md"},
{"muse", "AGENTS.md"},
{"qwen", "QWEN.md"},
}
@@ -1481,6 +1482,7 @@ func TestCleanupRuntimeConfigByProvider(t *testing.T) {
{"zeroclaw", "AGENTS.md"},
{"kiro", "AGENTS.md"},
{"antigravity", "AGENTS.md"},
+ {"museapp", "AGENTS.md"},
{"muse", "AGENTS.md"},
{"qwen", "QWEN.md"},
}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index cf71adb014..2a4f034ab9 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -4724,7 +4724,7 @@ func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {
}
offered := service.TaskStartCapabilities{
Supplement: slices.Contains(req.Capabilities, protocol.DaemonCapabilityTaskSupplementV1),
- ProcessCleanup: slices.Contains(req.Capabilities, protocol.DaemonCapabilityPiProcessCleanupV1),
+ ProcessCleanup: slices.Contains(req.Capabilities, protocol.DaemonCapabilityPiProcessCleanupV1) || slices.Contains(req.Capabilities, protocol.DaemonCapabilityMuseAppProcessCleanupV1),
}
var task *db.AgentTaskQueue
var err error
@@ -5941,7 +5941,7 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {
// transcript (#5219); idempotent when nothing was deferred.
// TaskCancelAckRequest is the body of the daemon's cancel acknowledgement.
type TaskCancelAckRequest struct {
- // Absent on older daemons: a pending Pi cleanup cannot be assumed clean.
+ // Absent on older daemons: negotiated cleanup cannot be assumed complete.
ProcessCleanupConfirmed *bool `json:"process_cleanup_confirmed,omitempty"`
// BranchName: a cancelled worktree task has already committed whatever the
// agent produced — the worktree is finalized before the daemon learns of
diff --git a/server/internal/handler/daemon_process_cleanup_test.go b/server/internal/handler/daemon_process_cleanup_test.go
index 0484e9b545..153bb44bbb 100644
--- a/server/internal/handler/daemon_process_cleanup_test.go
+++ b/server/internal/handler/daemon_process_cleanup_test.go
@@ -116,7 +116,7 @@ func TestProcessCleanupCapabilityNegotiation(t *testing.T) {
if testHandler == nil {
t.Fatal("PostgreSQL is required")
}
- for _, provider := range []string{"pi", "omp", "codex"} {
+ for _, provider := range []string{"pi", "omp", "codex", "museapp"} {
for _, capable := range []bool{false, true} {
for _, claimFenced := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/capable=%v/claim=%v", provider, capable, claimFenced), func(t *testing.T) {
@@ -125,8 +125,12 @@ func TestProcessCleanupCapabilityNegotiation(t *testing.T) {
issue := dbfx.Issue(t, "cleanup negotiation")
id := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtime, "issue_id": issue, "status": "dispatched", "dispatched_at": time.Now().UTC()})
body := map[string]any{}
+ capability := "pi-process-cleanup-v1"
+ if provider == "museapp" {
+ capability = "museapp-process-cleanup-v1"
+ }
if capable {
- body["capabilities"] = []string{"pi-process-cleanup-v1"}
+ body["capabilities"] = []string{capability}
}
if claimFenced {
var generation pgtype.Timestamptz
@@ -135,8 +139,8 @@ func TestProcessCleanupCapabilityNegotiation(t *testing.T) {
}
req := withURLParam(newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+id+"/start", body), "taskId", id)
started := testutil.Decode[map[string]any](t, testHandler.StartTask, req, http.StatusOK)
- wantPending := capable && (provider == "pi" || provider == "omp")
- if got := started["process_cleanup_capability"] == "pi-process-cleanup-v1"; got != wantPending {
+ wantPending := capable && (provider == "pi" || provider == "omp" || provider == "museapp")
+ if got := started["process_cleanup_capability"] == capability; got != wantPending {
t.Fatalf("negotiated cleanup=%v, want %v", got, wantPending)
}
if claimFenced {
@@ -144,7 +148,7 @@ func TestProcessCleanupCapabilityNegotiation(t *testing.T) {
if capable {
delete(body, "capabilities")
} else {
- body["capabilities"] = []string{"pi-process-cleanup-v1"}
+ body["capabilities"] = []string{capability}
}
req = withURLParam(newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+id+"/start", body), "taskId", id)
testutil.Call(t, testHandler.StartTask, req).Want(http.StatusOK)
diff --git a/server/internal/handler/museapp_recovery_test.go b/server/internal/handler/museapp_recovery_test.go
new file mode 100644
index 0000000000..c24a7aec9f
--- /dev/null
+++ b/server/internal/handler/museapp_recovery_test.go
@@ -0,0 +1,175 @@
+package handler
+
+import (
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// A daemon restart cannot stop an independent Muse worker. No worker-stop
+// acknowledgement is supplied during recovery, so automatic work stays fenced.
+func TestMuseAppRecoveryBlocksAutomaticSuccessor(t *testing.T) {
+ if testHandler == nil {
+ t.Fatal("PostgreSQL is required")
+ }
+ runtimeID := dbfx.Runtime(t, "Muse recovery", testutil.Cols{"provider": "museapp"})
+ agentID := dbfx.Agent(t, "Muse recovery", runtimeID)
+ issueID := dbfx.Issue(t, "Muse recovery")
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID, "issue_id": issueID,
+ "status": "dispatched", "dispatched_at": time.Now().UTC(),
+ "attempt": 1, "max_attempts": 2,
+ })
+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE retry_of_task_id=$1`, taskID)
+ start := withURLParam(newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/start", map[string]any{
+ "capabilities": []string{"museapp-process-cleanup-v1"},
+ }), "taskId", taskID)
+ testutil.Call(t, testHandler.StartTask, start).Want(http.StatusOK)
+ recoverReq := withURLParam(newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/recover-orphans", nil), "runtimeId", runtimeID)
+ var recovered map[string]any
+ testutil.Call(t, testHandler.RecoverOrphanedTasks, recoverReq).Want(http.StatusOK).JSON(&recovered)
+ var failure, capability string
+ dbfx.QueryRow(t, `SELECT failure_reason, result->>'process_cleanup_capability' FROM agent_task_queue WHERE id=$1`, taskID).Scan(&failure, &capability)
+ if failure != "cleanup_unconfirmed" || capability != "museapp-process-cleanup-v1" {
+ t.Fatalf("recovery=%v failure=%s capability=%s", recovered, failure, capability)
+ }
+ var retries int
+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queue WHERE retry_of_task_id=$1`, taskID).Scan(&retries)
+ if retries != 0 {
+ t.Fatalf("recovery created %d automatic retries", retries)
+ }
+ successor := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "issue_id": issueID, "status": "dispatched", "dispatched_at": time.Now().UTC()})
+ start = withURLParam(newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+successor+"/start", nil), "taskId", successor)
+ testutil.Call(t, testHandler.StartTask, start).Want(http.StatusConflict)
+ manual := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "issue_id": issueID, "status": "dispatched", "rerun_of_task_id": taskID, "initiator_user_id": testUserID})
+ start = withURLParam(newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+manual+"/start", map[string]any{"capabilities": []string{"museapp-process-cleanup-v1"}}), "taskId", manual)
+ testutil.Call(t, testHandler.StartTask, start).Want(http.StatusOK)
+}
+
+func TestMuseAppInfrastructureRecoveryPolicies(t *testing.T) {
+ if testHandler == nil {
+ t.Fatal("PostgreSQL is required")
+ }
+ for _, path := range []string{"restart", "offline", "timeout"} {
+ for _, tc := range []struct {
+ name, provider, status, capability string
+ rebound bool
+ protected bool
+ }{
+ {"started", "museapp", "running", "museapp-process-cleanup-v1", false, true},
+ {"legacy daemon", "museapp", "running", "", false, true},
+ {"runtime changed", "museapp", "running", "museapp-process-cleanup-v1", true, true},
+ {"not started", "museapp", "dispatched", "", false, false},
+ {"waiting for workdir", "museapp", "waiting_local_directory", "", false, false},
+ {"Codex", "codex", "running", "", false, false},
+ {"Pi", "pi", "running", "pi-process-cleanup-v1", false, false},
+ } {
+ t.Run(path+"/"+tc.name, func(t *testing.T) {
+ runtimeID := dbfx.Runtime(t, "recovery policy", testutil.Cols{"provider": tc.provider})
+ agentID := dbfx.Agent(t, "recovery policy", runtimeID)
+ issueID := dbfx.Issue(t, "recovery policy")
+ cols := testutil.Cols{
+ "runtime_id": runtimeID, "issue_id": issueID, "status": tc.status,
+ "dispatched_at": testutil.Raw("now() - interval '4 hours'"),
+ "attempt": 1, "max_attempts": 2,
+ }
+ if tc.status == "running" {
+ cols["started_at"] = testutil.Raw("now() - interval '4 hours'")
+ }
+ if tc.capability != "" {
+ cols["result"] = `{"process_cleanup_capability":"` + tc.capability + `"}`
+ }
+ taskID := dbfx.Task(t, agentID, cols)
+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE retry_of_task_id=$1`, taskID)
+ if tc.rebound {
+ dbfx.Exec(t, `UPDATE agent_runtime SET provider='codex' WHERE id=$1`, runtimeID)
+ }
+ if path != "restart" {
+ dbfx.Exec(t, `UPDATE agent_runtime SET last_seen_at=now()-interval '4 hours' WHERE id=$1`, runtimeID)
+ if path == "offline" {
+ dbfx.Exec(t, `UPDATE agent_runtime SET status='offline' WHERE id=$1`, runtimeID)
+ }
+ }
+ var rows []db.AgentTaskQueue
+ var err error
+ wantReason := "runtime_recovery"
+ switch path {
+ case "restart":
+ rows, err = testHandler.TaskService.RecoverOrphanedTasksForRuntime(t.Context(), parseUUID(runtimeID))
+ case "offline":
+ wantReason = "runtime_offline"
+ rows, err = testHandler.TaskService.FailTasksForOfflineRuntimes(t.Context(), db.FailTasksForOfflineRuntimesParams{ReconnectGraceSecs: 60, MaxPerTick: 10000})
+ case "timeout":
+ wantReason = "timeout"
+ rows, err = testHandler.TaskService.FailStaleTasks(t.Context(), db.FailStaleTasksParams{DispatchTimeoutSecs: 60, RunningTimeoutSecs: 60, RuntimeStaleSecs: 60, RuntimeReconnectGraceSecs: 60})
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ var recovered *db.AgentTaskQueue
+ for i := range rows {
+ if rows[i].ID == parseUUID(taskID) {
+ recovered = &rows[i]
+ break
+ }
+ }
+ if path == "timeout" && tc.status == "waiting_local_directory" {
+ if recovered != nil {
+ t.Fatal("timeout reclaimed a legitimate workdir waiter")
+ }
+ return
+ }
+ if recovered == nil {
+ t.Fatal("fixture task was not recovered")
+ }
+ if tc.protected {
+ wantReason = "cleanup_unconfirmed"
+ }
+ if recovered.FailureReason.String != wantReason {
+ t.Fatalf("failure = %s, want %s", recovered.FailureReason.String, wantReason)
+ }
+ var persistedReason string
+ dbfx.QueryRow(t, `SELECT failure_reason FROM agent_task_queue WHERE id=$1`, taskID).Scan(&persistedReason)
+ if persistedReason != wantReason {
+ t.Fatalf("persisted reason = %s, want %s", persistedReason, wantReason)
+ }
+ if tc.protected && !strings.Contains(recovered.Error.String, "worker may still be running") {
+ t.Fatalf("missing recovery guidance: %s", recovered.Error.String)
+ }
+ testHandler.TaskService.HandleFailedTasks(t.Context(), []db.AgentTaskQueue{*recovered})
+ var retries int
+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_task_queue WHERE retry_of_task_id=$1`, taskID).Scan(&retries)
+ wantRetries := 1
+ if tc.protected {
+ wantRetries = 0
+ }
+ if retries != wantRetries {
+ t.Fatalf("retries = %d, want %d", retries, wantRetries)
+ }
+ var successor string
+ if tc.protected {
+ successor = dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "issue_id": issueID, "status": "dispatched"})
+ } else {
+ var state string
+ dbfx.QueryRow(t, `SELECT id::text, status FROM agent_task_queue WHERE retry_of_task_id=$1`, taskID).Scan(&successor, &state)
+ wantState := "queued"
+ if path == "offline" {
+ wantState = "deferred"
+ }
+ if state != wantState {
+ t.Fatalf("retry state = %s, want %s", state, wantState)
+ }
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status='dispatched' WHERE id=$1`, successor)
+ }
+ blocked, err := testHandler.Queries.TaskBlockedByProcessCleanup(t.Context(), parseUUID(successor))
+ if err != nil || blocked != tc.protected {
+ t.Fatalf("successor blocked=%v, want %v, err=%v", blocked, tc.protected, err)
+ }
+ })
+ }
+ }
+}
diff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.go
index ccce9f2ca4..0a784e279b 100644
--- a/server/internal/handler/runtime_profile.go
+++ b/server/internal/handler/runtime_profile.go
@@ -153,6 +153,14 @@ func (h *Handler) CreateRuntimeProfile(w http.ResponseWriter, r *http.Request) {
return
}
req.RuntimeType = agent.ProfileRuntimeType(strings.TrimSpace(req.RuntimeType), req.ProtocolFamily)
+ // museapp is a builtin HTTP backend, not a CLI that can be wrapped
+ // in a custom profile. Reject it here with 400 instead of letting
+ // it hit the DB CHECK constraint (which doesn't list museapp) and
+ // return a confusing 500.
+ if req.RuntimeType == "museapp" {
+ writeError(w, http.StatusBadRequest, "runtime_type 'museapp' is a builtin backend and cannot be used for custom profiles; create a builtin museapp agent instead")
+ return
+ }
family, supported := agent.RuntimeProtocolFamily(req.RuntimeType)
if !supported {
writeError(w, http.StatusBadRequest, "unsupported runtime_type: "+req.RuntimeType)
diff --git a/server/internal/handler/task_lifecycle.go b/server/internal/handler/task_lifecycle.go
index 7b837b8eb8..2049a7b20d 100644
--- a/server/internal/handler/task_lifecycle.go
+++ b/server/internal/handler/task_lifecycle.go
@@ -18,7 +18,8 @@ import (
// it owns. It atomically fails any dispatched/running tasks the server still
// believes belong to that runtime — those are the tasks the previous daemon
// process was running when it died — and triggers MaybeRetryFailedTask for
-// each so the user sees a fresh attempt instead of a permanently stuck row.
+// each so retry-safe work gets a fresh attempt. Started Muse executions retain
+// a cleanup fence because their workers can survive the daemon process.
//
// This is the targeted fix for "issue stuck at in_progress when daemon
// restarts mid-task": the runtime heartbeat sweeper takes up to 75s + the
diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.go
index 83ef783135..cc6b91011b 100644
--- a/server/internal/metrics/labels.go
+++ b/server/internal/metrics/labels.go
@@ -164,6 +164,7 @@ var (
"mcode": "mcode",
"muse": "muse",
"zeroclaw": "zeroclaw",
+ "museapp": "museapp",
"zcode": "zcode",
"multica_agent": "multica_agent",
"openclaw": "openclaw",
diff --git a/server/internal/service/delegated_failure_recovery_test.go b/server/internal/service/delegated_failure_recovery_test.go
index 68c79f0678..5f19c0425f 100644
--- a/server/internal/service/delegated_failure_recovery_test.go
+++ b/server/internal/service/delegated_failure_recovery_test.go
@@ -1051,6 +1051,33 @@ func (f *delegatedFailureFixture) insertOrphanedWorkerTask(t *testing.T, attempt
return task
}
+func TestHandleFailedTasksUnconfirmedCleanupDoesNotDelegate(t *testing.T) {
+ for _, reason := range []string{"cleanup_unconfirmed", "cleanup_blocked"} {
+ t.Run(reason, func(t *testing.T) {
+ f, svc := seedDelegatedFailureFixture(t)
+ failedID := f.insertWorkerTask(t, "failed", "comment", 1, 2)
+ if _, err := f.pool.Exec(t.Context(), `UPDATE agent_task_queue SET failure_reason=$2, error='worker stop unconfirmed', completed_at=now() WHERE id=$1`, failedID, reason); err != nil {
+ t.Fatal(err)
+ }
+ failed, err := svc.Queries.GetAgentTask(t.Context(), failedID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ svc.HandleFailedTasks(t.Context(), []db.AgentTaskQueue{failed})
+ var recoveryTasks, recoveryComments int
+ if err := f.pool.QueryRow(t.Context(), `SELECT count(*) FROM agent_task_queue WHERE trigger_evidence_kind='delegated_failure' AND trigger_evidence_ref_id=$1`, failedID).Scan(&recoveryTasks); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.pool.QueryRow(t.Context(), `SELECT count(*) FROM comment WHERE issue_id=$1 AND type='progress_update' AND source_task_id=$2`, f.issueID, failedID).Scan(&recoveryComments); err != nil {
+ t.Fatal(err)
+ }
+ if recoveryTasks != 0 || recoveryComments != 0 {
+ t.Fatalf("cleanup failure dispatched coordinator work: tasks=%d comments=%d", recoveryTasks, recoveryComments)
+ }
+ })
+ }
+}
+
func TestHandleFailedTasksTerminalFailureCommentsOnTaskIssue(t *testing.T) {
f, svc := seedDelegatedFailureFixture(t)
ctx := context.Background()
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 766364e271..9942f670a5 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -6288,6 +6288,26 @@ func (s *TaskService) terminateTasksInTx(ctx context.Context, fail func(*db.Quer
if err != nil {
return err
}
+ // A terminal infrastructure error does not stop an independent Muse
+ // worker. Persist that uncertainty in this transaction, before retry
+ // decisions or another claim can observe the failed rows.
+ var startedIDs []pgtype.UUID
+ indices := make(map[pgtype.UUID]int)
+ for i, task := range failed {
+ if task.Status == "failed" && task.StartedAt.Valid {
+ startedIDs = append(startedIDs, task.ID)
+ indices[task.ID] = i
+ }
+ }
+ if len(startedIDs) > 0 {
+ unconfirmed, err := qtx.MarkMuseAppRecoveryCleanupUnconfirmed(ctx, startedIDs)
+ if err != nil {
+ return fmt.Errorf("record Muse recovery cleanup: %w", err)
+ }
+ for _, task := range unconfirmed {
+ failed[indices[task.ID]] = task
+ }
+ }
return SettleTerminalTaskState(ctx, qtx, failed...)
}); err != nil {
return nil, err
@@ -6326,12 +6346,14 @@ func (s *TaskService) HandleFailedTasks(ctx context.Context, tasks []db.AgentTas
}
}
if !retryPending {
- if _, err := s.recoverDelegatedTaskFailure(ctx, t); err != nil {
- slog.Warn("handle failed tasks: delegated failure recovery failed",
- "task_id", util.UUIDToString(t.ID),
- "delegated_from_task_id", util.UUIDToString(t.DelegatedFromTaskID),
- "error", err,
- )
+ if t.FailureReason.String != taskfailure.ReasonProcessCleanupUnconfirmed.String() && t.FailureReason.String != taskfailure.ReasonProcessCleanupBlocked.String() {
+ if _, err := s.recoverDelegatedTaskFailure(ctx, t); err != nil {
+ slog.Warn("handle failed tasks: delegated failure recovery failed",
+ "task_id", util.UUIDToString(t.ID),
+ "delegated_from_task_id", util.UUIDToString(t.DelegatedFromTaskID),
+ "error", err,
+ )
+ }
}
// Same terminal-failure comment FailTaskWithTransition posts, so
// swept tasks are not silent on their issue.
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index 44c0448339..bff1b0de13 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -97,6 +97,20 @@ type ExecOptions struct {
// knows the resume is gone, and the backend covers only the case the daemon
// cannot see — a live resume RPC rejected mid-run.
ResumeContinuityNotice string
+ // TaskToken is the task-scoped Multica API credential (mat_...) the server
+ // mints at claim time. CLI backends receive it as MULTICA_TOKEN in the
+ // subprocess environment. Backends that delegate remotely (museapp) forward
+ // it in their wire request so the remote worker can call the Multica API
+ // with the same scoped identity. Empty when the server did not provide one.
+ TaskToken string
+ // MulticaServerURL is the Multica API base URL (e.g.
+ // https://multica.example.com). Remote backends forward it so the worker
+ // knows where to call; CLI backends get it as MULTICA_SERVER_URL.
+ MulticaServerURL string
+ // MulticaWorkspaceID is the workspace UUID for this task. Remote backends
+ // forward it so the worker can pass it as a query param; CLI backends get
+ // it as MULTICA_WORKSPACE_ID.
+ MulticaWorkspaceID string
// ExtraArgs is honoured only by backends that opt in by reading it; the
// rest ignore it. Deliberately not enumerated here — the previous list
// went stale as backends were added, which is how MULTICA_QWENPAW_ARGS
@@ -423,6 +437,7 @@ var SupportedTypes = []string{
"dim",
"devin",
"zeroclaw",
+ "museapp",
"zcode",
}
@@ -533,6 +548,8 @@ func New(agentType string, cfg Config) (Backend, error) {
return &museBackend{cfg: cfg}, nil
case "zeroclaw":
return &zeroclawBackend{cfg: cfg}, nil
+ case "museapp":
+ return &museappBackend{cfg: cfg}, nil
case "zcode":
return &zcodeBackend{cfg: cfg}, nil
default:
@@ -584,6 +601,7 @@ var launchHeaders = map[string]string{
"mcode": "mcode acp",
"muse": "muse serve (msp)",
"zeroclaw": "zeroclaw acp",
+ "museapp": "museapp (remote receptionist)",
"zcode": "zcode app-server",
}
diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.go
index 163383d788..cc690f127f 100644
--- a/server/pkg/agent/models.go
+++ b/server/pkg/agent/models.go
@@ -341,6 +341,12 @@ func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (C
// ModelSelectionSupported. Return an empty list rather than spawning
// an ACP subprocess that can only ever come back empty.
return Catalog{Models: []Model{}}, nil
+ case "museapp":
+ // museapp (muse.ai) is a single personal agent behind a remote receptionist, not a
+ // model family: there is no catalog to discover and no session-scoped
+ // model selection to consume one. An empty list keeps manual entry
+ // available without spawning anything.
+ return Catalog{Models: []Model{}}, nil
case "zcode":
// ZCode has no model-catalog command or RPC — the catalog lives only
// inside a running session's snapshot (settings.model.available,
@@ -461,7 +467,7 @@ func QualifyModelID(catalog Catalog, model string) (string, bool) {
// in splitZcodeModelSelection.
func ModelSelectionSupported(providerType string) bool {
switch providerType {
- case "qwenpaw", "mcode", "zeroclaw":
+ case "qwenpaw", "mcode", "zeroclaw", "museapp":
// QwenPaw's `session/set_model` persists to agent.json at the agent
// scope, not the session scope. Calling it would mutate the user's
// shared, persistent agent config. Model override is therefore
@@ -473,7 +479,9 @@ func ModelSelectionSupported(providerType string) bool {
// its ACP dispatch table at all (0.8.4 answers -32601) and no handler
// reads a model param, so the model comes from the ZeroClaw agent
// profile (`agents.<alias>.model_provider`) and nothing Multica sends
- // can change it.
+ // can change it. museapp is a single personal agent behind a remote
+ // receptionist: the wire protocol has no model parameter, so the
+ // receptionist's own configuration is the source of truth.
return false
default:
return true
diff --git a/server/pkg/agent/museapp.go b/server/pkg/agent/museapp.go
new file mode 100644
index 0000000000..c7fea85967
--- /dev/null
+++ b/server/pkg/agent/museapp.go
@@ -0,0 +1,613 @@
+package agent
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/url"
+ "os"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync/atomic"
+ "time"
+)
+
+// museappBackend implements Backend by delegating to a remote Muse receptionist
+// over HTTP. Unlike every other backend there is no local CLI to spawn: the
+// daemon advertises a museapp runtime exactly when MULTICA_MUSEAPP_ENDPOINT is configured
+// (see probeAgentCLIs), and Execute POSTs the prompt to the receptionist,
+// streams its progress events into Messages, and resolves Result when the
+// receptionist reports a terminal state.
+//
+// Wire protocol (v1):
+//
+// POST /v1/execute {prompt, session_id?, timeout_s?, workdir?} -> {task_id}
+// GET /v1/tasks/{id} -> {status, result?, error?}
+// GET /v1/tasks/{id}/events -> {events: [{seq, type, content}]}
+// POST /v1/tasks/{id}/cancel -> {execution_stopped?}
+// GET /v1/health -> {protocol_version, version}
+//
+// "result" on a completed task is the final answer. Event types are exactly
+// text, thinking and tool; text events are running commentary streamed into
+// Messages and are used as the answer only when "result" is empty. Once a task
+// is terminal no further events are written.
+//
+// Configuration comes from the daemon's own process environment so no CLI
+// discovery is involved:
+//
+// MULTICA_MUSEAPP_ENDPOINT base URL of the receptionist, e.g. http://127.0.0.1:8765.
+// Keep this on loopback: the bearer token is sent in the
+// clear over plain http, so a non-loopback http:// URL
+// would expose it on the network.
+// MULTICA_MUSEAPP_TOKEN bearer token for the receptionist (optional; sent only when set)
+// MULTICA_MUSEAPP_MODEL informational model label reported in the probe entry
+//
+// Endpoint and receptionist-token resolution deliberately ignore cfg.Env.
+// It carries the agent's custom_env,
+// which any member who can edit the agent controls; honouring MULTICA_MUSEAPP_ENDPOINT
+// there would let them point this daemon at an arbitrary URL, and MULTICA_MUSEAPP_TOKEN
+// (which they cannot see) would still ride along from the process environment.
+// The probe only ever reads the process environment, so reading anything else
+// here would also mean probing one receptionist and running tasks on another.
+type museappBackend struct {
+ cfg Config
+}
+
+// museappProtocolVersion is the receptionist wire protocol this backend speaks.
+// ProbeMuseAppReceptionist refuses a receptionist reporting anything else so a
+// protocol skew fails at probe time, not mid-task.
+const museappProtocolVersion = 1
+
+// ErrMuseAppProtocolSkew is returned by ProbeMuseAppReceptionist when the
+// receptionist speaks a different protocol version than this backend.
+// It is a sentinel so the daemon can distinguish deterministic protocol
+// incompatibility (demotable) from transient network failures.
+var ErrMuseAppProtocolSkew = fmt.Errorf("museapp backend: protocol skew")
+
+const (
+ museappEnvEndpoint = "MULTICA_MUSEAPP_ENDPOINT"
+ museappEnvToken = "MULTICA_MUSEAPP_TOKEN"
+ museappEnvModel = "MULTICA_MUSEAPP_MODEL"
+)
+
+// museappPollInterval is the steady-state cadence for task status/event polls.
+// The receptionist is expected to be local or near-local (loopback or
+// tailnet); 500ms keeps the transcript live without hammering it.
+// Atomic so tests can shrink it without racing concurrent poll loops.
+var museappPollInterval atomic.Int64 // nanoseconds
+
+// museappMaxConsecutivePollErrors bounds transient network failures before the
+// run is failed. Ten misses at the poll interval is ~5s of silence — long
+// enough to ride out a blip, short enough not to wedge a task on a dead
+// receptionist. Atomic for the same test reason as museappPollInterval.
+var museappMaxConsecutivePollErrors atomic.Int32
+
+func init() {
+ museappPollInterval.Store(int64(500 * time.Millisecond))
+ museappMaxConsecutivePollErrors.Store(10)
+}
+
+type museappEndpointConfig struct {
+ endpoint string
+ token string
+}
+
+func resolveMuseAppConfig() (museappEndpointConfig, error) {
+ endpoint := strings.TrimSpace(os.Getenv(museappEnvEndpoint))
+ if strings.TrimSpace(endpoint) == "" {
+ return museappEndpointConfig{}, fmt.Errorf("museapp backend: %s is not set; configure the receptionist URL to enable the museapp runtime", museappEnvEndpoint)
+ }
+ endpoint = strings.TrimRight(strings.TrimSpace(endpoint), "/")
+ if _, err := url.ParseRequestURI(endpoint); err != nil {
+ return museappEndpointConfig{}, fmt.Errorf("museapp backend: invalid %s %q: %w", museappEnvEndpoint, endpoint, err)
+ }
+ return museappEndpointConfig{
+ endpoint: endpoint,
+ token: strings.TrimSpace(os.Getenv(museappEnvToken)),
+ }, nil
+}
+
+func (b *museappBackend) authHeader(req *http.Request, token string) {
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+}
+
+// museappHTTPClient is a package var so tests can observe transport behavior;
+// the default has a bounded timeout so a wedged receptionist cannot hang
+// Execute forever outside ctx cancellation.
+var museappHTTPClient = &http.Client{Timeout: 30 * time.Second}
+
+type museappExecuteRequest struct {
+ Prompt string `json:"prompt"`
+ SessionID string `json:"session_id,omitempty"`
+ TimeoutS int64 `json:"timeout_s,omitempty"`
+ // WorkDir is the daemon-prepared task working directory (issue context,
+ // AGENTS.md runtime brief). The receptionist runs the agent with this
+ // directory so file-relative task context resolves. This assumes the
+ // daemon and the receptionist share a filesystem — the supported
+ // deployment runs both on the same host.
+ WorkDir string `json:"workdir,omitempty"`
+ // TaskToken is the task-scoped Multica API credential (mat_...). The
+ // receptionist hands it to the worker so the worker can call the Multica
+ // API (read issues, post comments) with the same scoped identity a CLI
+ // backend gets via MULTICA_TOKEN. Omitted when the daemon has none.
+ TaskToken string `json:"task_token,omitempty"`
+ // ServerURL is the Multica API base URL. The worker needs it to know
+ // where to call; CLI backends get it as MULTICA_SERVER_URL.
+ ServerURL string `json:"server_url,omitempty"`
+ // WorkspaceID is the workspace UUID. The worker passes it as a query
+ // param on API calls; CLI backends get it as MULTICA_WORKSPACE_ID.
+ WorkspaceID string `json:"workspace_id,omitempty"`
+ // ProtocolVersion is the wire protocol version this backend speaks.
+ // The receptionist MUST validate it BEFORE creating the task and
+ // reject with 400 if incompatible. This prevents the "task accepted
+ // then rejected" race where a task is queued but the backend refuses
+ // to poll it.
+ ProtocolVersion int `json:"protocol_version"`
+}
+
+type museappExecuteResponse struct {
+ TaskID string `json:"task_id"`
+ ProtocolVersion int `json:"protocol_version,omitempty"`
+}
+
+type museappTaskStatus struct {
+ Status string `json:"status"`
+ Result string `json:"result,omitempty"`
+ Error string `json:"error,omitempty"`
+ // Cancellation or timeout bookkeeping alone does not prove a worker stopped.
+ ExecutionStopped bool `json:"execution_stopped,omitempty"`
+}
+
+type museappCancelResponse struct {
+ ExecutionStopped bool `json:"execution_stopped"`
+}
+
+type museappHTTPStatusError struct {
+ code int
+ message string
+}
+
+func (e *museappHTTPStatusError) Error() string { return e.message }
+
+type museappEvent struct {
+ Seq int64 `json:"seq"`
+ Type string `json:"type"` // "text" | "thinking" | "tool"
+ Content string `json:"content"`
+ Tool string `json:"tool,omitempty"`
+}
+
+type museappEventsResponse struct {
+ Events []museappEvent `json:"events"`
+}
+
+type museappHealthResponse struct {
+ ProtocolVersion int `json:"protocol_version"`
+ Version string `json:"version"`
+}
+
+// ProbeMuseAppReceptionist checks that a receptionist is reachable at endpoint
+// and speaks the wire protocol this backend implements. It is the museapp
+// equivalent of CLI version detection and backs the daemon's availability
+// probe (no binary exists to --version). A protocol skew is a hard error so
+// it surfaces at probe time rather than mid-task.
+func ProbeMuseAppReceptionist(ctx context.Context, endpoint, token string) (string, error) {
+ endpoint = strings.TrimRight(strings.TrimSpace(endpoint), "/")
+ if endpoint == "" {
+ return "", fmt.Errorf("museapp backend: empty endpoint")
+ }
+ if _, err := url.ParseRequestURI(endpoint); err != nil {
+ return "", fmt.Errorf("museapp backend: invalid endpoint %q: %w", endpoint, err)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint+"/v1/health", nil)
+ if err != nil {
+ return "", fmt.Errorf("museapp backend: build health request: %w", err)
+ }
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ resp, err := museappHTTPClient.Do(req)
+ if err != nil {
+ return "", fmt.Errorf("museapp backend: receptionist unreachable: %w", err)
+ }
+ defer resp.Body.Close()
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ if err != nil {
+ return "", fmt.Errorf("museapp backend: read health response: %w", err)
+ }
+ if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
+ return "", fmt.Errorf("museapp backend: health check HTTP %d: receptionist rejected credentials (check MULTICA_MUSEAPP_TOKEN)", resp.StatusCode)
+ }
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return "", fmt.Errorf("museapp backend: health check HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(raw)))
+ }
+ var health museappHealthResponse
+ if err := json.Unmarshal(raw, &health); err != nil {
+ return "", fmt.Errorf("museapp backend: decode health response: %w", err)
+ }
+ if health.ProtocolVersion != museappProtocolVersion {
+ return "", fmt.Errorf("%w: receptionist speaks v%d, backend implements v%d",
+ ErrMuseAppProtocolSkew, health.ProtocolVersion, museappProtocolVersion)
+ }
+ if health.Version == "" {
+ health.Version = "unknown"
+ }
+ return health.Version, nil
+}
+
+func (b *museappBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {
+ if strings.TrimSpace(prompt) == "" {
+ return nil, fmt.Errorf("muse prompt must not be empty")
+ }
+ mc, err := resolveMuseAppConfig()
+ if err != nil {
+ return nil, err
+ }
+ logger := b.cfg.Logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+
+ // B1: Establish a local deadline via runContext (Hermes pattern).
+ // opts.Timeout bounds the entire execution locally; the receptionist
+ // also receives timeout_s as a hint, but the local context is authoritative.
+ // NOTE: Do NOT defer cancel() here — Execute returns immediately with
+ // the Session; the goroutine below owns the context lifetime and
+ // cancels it when the run finishes.
+ runCtx, cancel := runContext(ctx, opts.Timeout)
+ if err := runCtx.Err(); err != nil {
+ cancel()
+ return nil, err
+ }
+
+ // timeoutS rounds up: a sub-second timeout must not truncate to 0,
+ // which would tell the receptionist "no timeout".
+ // When opts.Timeout is 0 (no local deadline), send an explicit 24h
+ // rather than 0: the receptionist defaults unset/0 to 1h, which would
+ // kill long tasks the Go side is happy to wait for.
+ timeoutS := int64(24 * 3600)
+ if opts.Timeout > 0 {
+ timeoutS = int64((opts.Timeout + time.Second - 1) / time.Second)
+ }
+ // Go-B3: Verify protocol compatibility before submitting.
+ // The probe runs at daemon startup; the receptionist could upgrade
+ // between probe and execute. The execute response carries the
+ // receptionist's protocol version; postExecute validates it.
+ // (A separate health check would add a round trip and break
+ // callers without a health endpoint.)
+ var execResp museappExecuteResponse
+ if err := b.postExecute(runCtx, mc, museappExecuteRequest{
+ Prompt: museappTaskPrompt(prompt, b.cfg.Env, opts, runtime.GOOS),
+ SessionID: opts.ResumeSessionID,
+ TimeoutS: timeoutS,
+ WorkDir: opts.Cwd,
+ TaskToken: opts.TaskToken,
+ ServerURL: opts.MulticaServerURL,
+ WorkspaceID: opts.MulticaWorkspaceID,
+ ProtocolVersion: museappProtocolVersion,
+ }, &execResp); err != nil {
+ cancel()
+ var rejected *museappHTTPStatusError
+ if errors.As(err, &rejected) && (rejected.code == 400 || rejected.code == 401 || rejected.code == 403) {
+ return nil, err // Explicit refusal before a task could be queued.
+ }
+ if execResp.TaskID != "" {
+ if cleanupErr := b.cancelRemoteTask(mc, execResp.TaskID); cleanupErr == nil {
+ return nil, err
+ } else {
+ err = errors.Join(err, cleanupErr)
+ }
+ }
+ return museappUnconfirmedSession(err), nil
+ }
+ if execResp.TaskID == "" {
+ cancel()
+ return museappUnconfirmedSession(fmt.Errorf("museapp backend: receptionist returned an empty task id")), nil
+ }
+ taskID := execResp.TaskID
+ logger.Info("muse task started", "task_id", taskID, "cwd", opts.Cwd, "model", opts.Model)
+ // The wire protocol has no model field; the worker runs as the user's
+ // personal Muse with its own context. Log ignored options explicitly
+ // (Hermes pattern) so silent drops are visible.
+ if opts.SystemPrompt != "" {
+ logger.Debug("muse ignoring ExecOptions.SystemPrompt; worker uses its own user context")
+ }
+ if opts.MaxTurns > 0 {
+ logger.Debug("muse ignoring ExecOptions.MaxTurns; wire protocol has no turn limit", "max_turns", opts.MaxTurns)
+ }
+ if len(opts.McpConfig) > 0 {
+ logger.Debug("muse ignoring ExecOptions.McpConfig; not applicable to remote worker")
+ }
+ if opts.ThinkingLevel != "" {
+ logger.Debug("muse ignoring ExecOptions.ThinkingLevel; not applicable to remote worker", "thinking_level", opts.ThinkingLevel)
+ }
+
+ msgCh := make(chan Message, 256)
+ resCh := make(chan Result, 1)
+ var terminalObserved atomic.Bool
+
+ go func() {
+ defer close(msgCh)
+ defer close(resCh)
+ defer cancel() // Release the runContext when the run finishes.
+ startTime := time.Now()
+ // output is what the text events add up to: running commentary
+ // ("looking that up…"), not the answer. It is the answer only when
+ // the receptionist reports none. answer is the receptionist's own
+ // final result and wins whenever it is set.
+ var output strings.Builder
+ var answer string
+ lastSeq := int64(0)
+ finalStatus := "completed"
+ var finalError string
+ pollErrs := 0
+
+ trySend(msgCh, Message{Type: MessageStatus, Status: "running"})
+
+ finish := func() {
+ out := output.String()
+ if answer != "" {
+ out = answer
+ }
+ resCh <- Result{
+ Status: finalStatus,
+ Output: out,
+ Error: finalError,
+ DurationMs: time.Since(startTime).Milliseconds(),
+ SessionID: "muse:" + taskID,
+ }
+ }
+ stopRemote := func() {
+ if err := b.cancelRemoteTask(mc, taskID); err != nil {
+ finalStatus = "cleanup_unconfirmed"
+ finalError += "; " + err.Error()
+ }
+ }
+
+ // applyEvents pulls the events after lastSeq and folds them into the
+ // transcript and the answer. It is best-effort and reports whether the
+ // fetch succeeded.
+ applyEvents := func() bool {
+ var eventsResp museappEventsResponse
+ if err := b.getJSON(runCtx, mc, museappTaskPath(taskID, "/events?since="+strconv.FormatInt(lastSeq, 10)), &eventsResp); err != nil {
+ logger.Debug("muse events poll failed", "task_id", taskID, "error", err)
+ return false
+ }
+ for _, e := range eventsResp.Events {
+ // The receptionist may ignore ?since= and return the full log;
+ // seq is the dedup key (the contract guarantees it is
+ // monotonically increasing per task).
+ if e.Seq <= lastSeq {
+ continue
+ }
+ lastSeq = e.Seq
+ switch e.Type {
+ case "thinking":
+ trySend(msgCh, Message{Type: MessageThinking, Content: e.Content})
+ case "tool":
+ trySend(msgCh, Message{Type: MessageToolUse, Tool: e.Tool, Content: e.Content})
+ case "text":
+ if e.Content != "" {
+ output.WriteString(e.Content)
+ trySend(msgCh, Message{Type: MessageText, Content: e.Content})
+ }
+ default:
+ // The wire protocol defines exactly text, thinking and
+ // tool. Anything else is not the receptionist's words to
+ // the user, so it never reaches the transcript or the
+ // answer.
+ logger.Debug("muse ignoring event of unknown type", "task_id", taskID, "seq", e.Seq, "type", e.Type)
+ }
+ }
+ return true
+ }
+
+ ticker := time.NewTicker(time.Duration(museappPollInterval.Load()))
+ defer ticker.Stop()
+ for {
+ select {
+ case <-runCtx.Done():
+ if runCtx.Err() == context.DeadlineExceeded {
+ finalStatus = "timeout"
+ finalError = "muse task timed out"
+ if opts.Timeout > 0 {
+ finalError = fmt.Sprintf("muse task timed out after %s", opts.Timeout)
+ }
+ } else {
+ finalStatus = "aborted"
+ finalError = "muse execution cancelled"
+ }
+ stopRemote()
+ finish()
+ return
+ case <-ticker.C:
+ }
+
+ // Events first so the transcript stays ordered ahead of the
+ // terminal status that may arrive on the same round. Event
+ // polling is best-effort: the transcript may go quiet, but the
+ // status poll below is the source of truth for completion, so a
+ // failing events endpoint degrades streaming without failing
+ // the run. Only status-poll failures count toward the budget.
+ applyEvents()
+
+ var st museappTaskStatus
+ if err := b.getJSON(runCtx, mc, museappTaskPath(taskID, ""), &st); err != nil {
+ if museappPollFailed(&pollErrs, err, logger, taskID) {
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("museapp backend: receptionist unreachable: %v", err)
+ stopRemote()
+ finish()
+ return
+ }
+ continue
+ }
+
+ switch st.Status {
+ case "completed", "failed", "cancelled":
+ if st.Status == "completed" || st.ExecutionStopped {
+ terminalObserved.Store(true)
+ }
+ // The events and status polls are two requests, so the
+ // receptionist can emit its last events (the tail of the
+ // answer) between them. Once the task is terminal nothing more
+ // will be written, so one more fetch is complete — without it
+ // a "completed" run silently ends short of its final text.
+ if !applyEvents() {
+ logger.Warn("muse final events fetch failed; the answer may be missing its tail", "task_id", taskID)
+ }
+ if st.Status == "completed" {
+ // N1: A completed status with an error (e.g. "result too
+ // large") is not a success. The Python side reports the
+ // problem via the error field; don't mask it by falling
+ // back to the transcript and calling it completed.
+ if st.Error != "" {
+ finalStatus = "failed"
+ finalError = st.Error
+ } else {
+ finalStatus = "completed"
+ answer = st.Result
+ }
+ } else if st.Status == "cancelled" {
+ finalStatus = "cancelled"
+ finalError = "muse task cancelled remotely"
+ } else {
+ finalStatus = "failed"
+ finalError = st.Error
+ if finalError == "" {
+ finalError = "muse task failed without an error message"
+ }
+ }
+ if st.Status != "completed" && !st.ExecutionStopped {
+ stopRemote()
+ }
+ finish()
+ return
+ case "queued", "running":
+ // A healthy round: the receptionist is reachable and
+ // speaking the protocol. Reset the consecutive-failure
+ // budget (unknown statuses and poll errors accumulate
+ // against it; see below).
+ pollErrs = 0
+ default:
+ // An unknown status is not a completed run and not a
+ // transient we can interpret — count it toward the poll
+ // budget so a receptionist speaking a newer protocol fails
+ // loudly instead of polling forever.
+ if museappPollFailed(&pollErrs, fmt.Errorf("unknown status %q", st.Status), logger, taskID) {
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("museapp backend: receptionist reported unknown status %q", st.Status)
+ stopRemote()
+ finish()
+ return
+ }
+ }
+ }
+ }()
+
+ return &Session{Messages: msgCh, Result: resCh, CleanupRequired: true, TerminalObserved: terminalObserved.Load}, nil
+}
+
+func museappUnconfirmedSession(err error) *Session {
+ messages := make(chan Message)
+ results := make(chan Result, 1)
+ results <- Result{Status: "cleanup_unconfirmed", Error: err.Error() + "; remote execution may still be active; check the Muse worker before manually rerunning"}
+ close(messages)
+ close(results)
+ return &Session{Messages: messages, Result: results, CleanupRequired: true, TerminalObserved: func() bool { return false }}
+}
+
+// museappTaskPath builds a /v1/tasks/{id}[/suffix] path. The task id comes from
+// the receptionist's response, so it is escaped rather than trusted: an id such
+// as "../admin" must stay one path segment of a task URL, not become a request
+// to a different endpoint carrying the bearer token.
+func museappTaskPath(taskID, suffix string) string {
+ return "/v1/tasks/" + url.PathEscape(taskID) + suffix
+}
+
+// museappPollFailed records one failed poll round and reports whether the
+// consecutive-failure budget is exhausted.
+func museappPollFailed(pollErrs *int, err error, logger *slog.Logger, taskID string) bool {
+ *pollErrs++
+ logger.Debug("muse poll failed", "task_id", taskID, "consecutive", *pollErrs, "error", err)
+ return *pollErrs >= int(museappMaxConsecutivePollErrors.Load())
+}
+
+func (b *museappBackend) postExecute(ctx context.Context, mc museappEndpointConfig, req museappExecuteRequest, out *museappExecuteResponse) error {
+ if err := b.doJSONWithConfig(ctx, mc, http.MethodPost, "/v1/execute", req, out); err != nil {
+ return err
+ }
+ // Go-B3: The receptionist reports its protocol version in the execute
+ // response. If it speaks a different version, fail fast.
+ // Execute must confirm cleanup of an accepted task before returning an error.
+ if out.ProtocolVersion != 0 && out.ProtocolVersion != museappProtocolVersion {
+ return fmt.Errorf("%w: receptionist speaks v%d, backend implements v%d",
+ ErrMuseAppProtocolSkew, out.ProtocolVersion, museappProtocolVersion)
+ }
+ return nil
+}
+
+func (b *museappBackend) getJSON(ctx context.Context, mc museappEndpointConfig, path string, out any) error {
+ return b.doJSONWithConfig(ctx, mc, http.MethodGet, path, nil, out)
+}
+
+func (b *museappBackend) cancelRemoteTask(mc museappEndpointConfig, taskID string) error {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ var response museappCancelResponse
+ if err := b.doJSONWithConfig(ctx, mc, http.MethodPost, museappTaskPath(taskID, "/cancel"), nil, &response); err != nil {
+ return fmt.Errorf("Muse worker stop unconfirmed: %w", err)
+ }
+ if !response.ExecutionStopped {
+ return fmt.Errorf("Muse worker stop unconfirmed: receptionist must confirm execution_stopped=true after the worker and its tools stop; check the worker before manually rerunning")
+ }
+ return nil
+}
+
+func (b *museappBackend) doJSONWithConfig(ctx context.Context, mc museappEndpointConfig, method, path string, body any, out any) error {
+ var reader io.Reader
+ if body != nil {
+ raw, err := json.Marshal(body)
+ if err != nil {
+ return fmt.Errorf("museapp backend: encode request: %w", err)
+ }
+ reader = bytes.NewReader(raw)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, mc.endpoint+path, reader)
+ if err != nil {
+ return fmt.Errorf("museapp backend: build request: %w", err)
+ }
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ b.authHeader(req, mc.token)
+ resp, err := museappHTTPClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("museapp backend: request %s %s: %w", method, path, err)
+ }
+ defer resp.Body.Close()
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
+ if err != nil {
+ return fmt.Errorf("museapp backend: read response: %w", err)
+ }
+ if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
+ return &museappHTTPStatusError{code: resp.StatusCode, message: fmt.Sprintf("museapp backend: %s %s: HTTP %d: receptionist rejected credentials (check MULTICA_MUSEAPP_TOKEN)", method, path, resp.StatusCode)}
+ }
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return &museappHTTPStatusError{code: resp.StatusCode, message: fmt.Sprintf("museapp backend: %s %s: HTTP %d: %s", method, path, resp.StatusCode, strings.TrimSpace(string(raw)))}
+ }
+ if out == nil {
+ return nil
+ }
+ if err := json.Unmarshal(raw, out); err != nil {
+ return fmt.Errorf("museapp backend: decode response: %w", err)
+ }
+ return nil
+}
diff --git a/server/pkg/agent/museapp_cleanup_test.go b/server/pkg/agent/museapp_cleanup_test.go
new file mode 100644
index 0000000000..a070133ab4
--- /dev/null
+++ b/server/pkg/agent/museapp_cleanup_test.go
@@ -0,0 +1,115 @@
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestMuseAppCancellationRequiresExecutionStop(t *testing.T) {
+ for _, tc := range []struct {
+ name, body, want string
+ code int
+ }{
+ {"unreachable worker", "worker still running", "cleanup_unconfirmed", 503},
+ {"legacy acknowledgement", `{"ok":true}`, "cleanup_unconfirmed", 200},
+ {"bookkeeping only", `{"execution_stopped":false}`, "cleanup_unconfirmed", 200},
+ {"stopped execution", `{"execution_stopped":true}`, "aborted", 200},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fake := &fakeMuseAppReceptionist{}
+ handler := fake.handler()
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "/cancel") {
+ w.WriteHeader(tc.code)
+ _, _ = w.Write([]byte(tc.body))
+ return
+ }
+ handler.ServeHTTP(w, r)
+ }))
+ defer srv.Close()
+ backend, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ session, err := backend.Execute(ctx, "edit the shared workdir", ExecOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !session.CleanupRequired || session.TerminalObserved == nil {
+ t.Fatal("daemon cannot await the cancellation outcome")
+ }
+ cancel()
+ result, _ := drainMuseAppSession(t, session)
+ if result.Status != tc.want {
+ t.Fatalf("result = %+v, want %s", result, tc.want)
+ }
+ })
+ }
+}
+
+func TestMuseAppFailureWithoutStoppedWorkerBlocksContinuation(t *testing.T) {
+ for _, state := range []string{"poll error", "unknown", "failed", "cancelled"} {
+ t.Run(state, func(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{statuses: []museappTaskStatus{{Status: state}}}
+ if state == "poll error" {
+ fake.statusCode = 503
+ }
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+ backend, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ session, err := backend.Execute(context.Background(), "edit the shared workdir", ExecOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ result, _ := drainMuseAppSession(t, session)
+ if result.Status != "cleanup_unconfirmed" {
+ t.Fatalf("result = %+v", result)
+ }
+ })
+ }
+}
+
+func TestMuseAppCancelDuringSubmissionBlocksContinuation(t *testing.T) {
+ accepted := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ close(accepted)
+ select {
+ case <-r.Context().Done():
+ case <-time.After(time.Second):
+ }
+ }))
+ defer srv.Close()
+ backend, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go func() { <-accepted; cancel() }()
+ session, err := backend.Execute(ctx, "task accepted before response was lost", ExecOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ result, _ := drainMuseAppSession(t, session)
+ if result.Status != "cleanup_unconfirmed" {
+ t.Fatalf("result = %+v", result)
+ }
+}
+
+func TestMuseAppProtocolSkewWithConfirmedCleanupReturnsError(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/v1/execute" {
+ _ = json.NewEncoder(w).Encode(museappExecuteResponse{TaskID: "orphan", ProtocolVersion: 2})
+ } else {
+ _ = json.NewEncoder(w).Encode(museappCancelResponse{ExecutionStopped: true})
+ }
+ }))
+ defer srv.Close()
+ backend, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ _, err := backend.Execute(context.Background(), "task", ExecOptions{})
+ if err == nil || !strings.Contains(err.Error(), "protocol skew") {
+ t.Fatalf("error = %v", err)
+ }
+}
diff --git a/server/pkg/agent/museapp_context.go b/server/pkg/agent/museapp_context.go
new file mode 100644
index 0000000000..72c166c559
--- /dev/null
+++ b/server/pkg/agent/museapp_context.go
@@ -0,0 +1,53 @@
+package agent
+
+import "strings"
+
+// The receptionist does not spawn a daemon child, so cfg.Env is not inherited.
+// Put the non-secret daemon task context in the prompt the existing worker
+// already executes. A per-command prefix also works across independent shells.
+// Credentials stay in task_token, never in model-visible command prefixes.
+func museappTaskPrompt(prompt string, env map[string]string, opts ExecOptions, goos string) string {
+ cliPath := env["MULTICA_CLI_PATH"]
+ if cliPath == "" {
+ return prompt // Standalone Backend callers need not use the Multica CLI.
+ }
+ keys := []string{
+ "MULTICA_CLI_PATH", "MULTICA_DAEMON_PORT", "MULTICA_TASK_ID",
+ "MULTICA_AGENT_ID", "MULTICA_AGENT_NAME", "MULTICA_TASK_SLOT",
+ "MULTICA_TASK_CONFIG_ROOT", "MULTICA_TASK_WORKSPACES_ROOT",
+ "MULTICA_AUTOPILOT_ID", "MULTICA_AUTOPILOT_RUN_ID",
+ "MULTICA_QUICK_CREATE_TASK_ID", "MULTICA_QUICK_CREATE_ATTACHMENT_IDS",
+ "MULTICA_QUICK_CREATE_DEFAULT_ASSIGNEE_TYPE", "MULTICA_QUICK_CREATE_DEFAULT_ASSIGNEE_ID",
+ }
+ values := make(map[string]string, len(keys)+2)
+ for _, key := range keys {
+ if value := env[key]; value != "" {
+ values[key] = value
+ }
+ }
+ keys = append(keys, "MULTICA_SERVER_URL", "MULTICA_WORKSPACE_ID")
+ values["MULTICA_SERVER_URL"] = opts.MulticaServerURL
+ values["MULTICA_WORKSPACE_ID"] = opts.MulticaWorkspaceID
+ var command strings.Builder
+ if goos == "windows" {
+ command.WriteString("& { ")
+ for _, key := range keys {
+ if value := values[key]; value != "" {
+ command.WriteString("$env:" + key + " = " + powerShellQuote(value) + "; ")
+ }
+ }
+ command.WriteString("& " + powerShellQuote(cliPath) + " @args }")
+ } else {
+ command.WriteString("env")
+ for _, key := range keys {
+ if value := values[key]; value != "" {
+ command.WriteString(" " + shellQuote(key+"="+value))
+ }
+ }
+ command.WriteString(" " + shellQuote(cliPath))
+ }
+ return "[Multica task CLI environment]\n" +
+ "For every Multica CLI command in the task or AGENTS.md, including commands shown as multica or $MULTICA_CLI_PATH, use the following prefix and append the original command arguments. Use it on every invocation, even in a new shell. The daemon and worker share these paths.\n\n" +
+ "```\n" + command.String() + "\n```\n\n" +
+ "In each shell invocation, set MULTICA_TOKEN from this task's request.json task_token as instructed by the receptionist worker setup; do not rely on an earlier shell's exports. Never substitute an owner credential or an installed CLI for this task's credential and CLI.\n\n" + prompt
+}
diff --git a/server/pkg/agent/museapp_context_test.go b/server/pkg/agent/museapp_context_test.go
new file mode 100644
index 0000000000..32328795e4
--- /dev/null
+++ b/server/pkg/agent/museapp_context_test.go
@@ -0,0 +1,60 @@
+package agent
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+func TestMuseAppTaskPromptRunsCLIWithTaskContext(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("POSIX shell execution")
+ }
+ cliPath := filepath.Join(t.TempDir(), "task cli's binary")
+ script := "#!/bin/sh\nprintf '%s\\n' \"$MULTICA_DAEMON_PORT\" \"$MULTICA_TASK_ID\" \"$MULTICA_AGENT_NAME\" \"$MULTICA_TASK_CONFIG_ROOT\" \"$MULTICA_SERVER_URL\" \"$MULTICA_WORKSPACE_ID\" \"$MULTICA_TOKEN\" \"$*\"\n"
+ if err := os.WriteFile(cliPath, []byte(script), 0700); err != nil {
+ t.Fatal(err)
+ }
+ env := map[string]string{
+ "MULTICA_CLI_PATH": cliPath, "MULTICA_DAEMON_PORT": "12345",
+ "MULTICA_TASK_ID": "task-current", "MULTICA_AGENT_NAME": "Muse's agent $(exit 99); literal",
+ "MULTICA_TASK_CONFIG_ROOT": filepath.Join(t.TempDir(), "task's config"),
+ "MULTICA_MUSEAPP_ENDPOINT": "http://untrusted.invalid", "MULTICA_MUSEAPP_TOKEN": "private-receptionist-token",
+ "MULTICA_TOKEN": "private-config-token", "OTHER_SECRET": "private-custom-secret",
+ }
+ opts := ExecOptions{TaskToken: "private-task-token", MulticaServerURL: "http://127.0.0.1:8080", MulticaWorkspaceID: "ws-current"}
+ prompt := museappTaskPrompt("check out the repository", env, opts, "linux")
+ for _, secret := range []string{opts.TaskToken, env["MULTICA_TOKEN"], env["MULTICA_MUSEAPP_TOKEN"], env["OTHER_SECRET"], env["MULTICA_MUSEAPP_ENDPOINT"]} {
+ if strings.Contains(prompt, secret) {
+ t.Fatal("credential or unapproved config leaked into task prompt")
+ }
+ }
+ _, rest, ok := strings.Cut(prompt, "```\n")
+ if !ok {
+ t.Fatal("missing CLI prefix")
+ }
+ prefix, _, ok := strings.Cut(rest, "\n```")
+ if !ok {
+ t.Fatal("unterminated CLI prefix")
+ }
+ cmd := exec.Command("sh", "-c", prefix+" repo checkout https://example.invalid/repo.git")
+ cmd.Env = []string{"PATH=/usr/bin:/bin", "MULTICA_TOKEN=mat_current_task"}
+ output, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("task CLI: %v: %s", err, output)
+ }
+ want := strings.Join([]string{env["MULTICA_DAEMON_PORT"], env["MULTICA_TASK_ID"], env["MULTICA_AGENT_NAME"], env["MULTICA_TASK_CONFIG_ROOT"], opts.MulticaServerURL, opts.MulticaWorkspaceID, "mat_current_task", "repo checkout https://example.invalid/repo.git", ""}, "\n")
+ if string(output) != want {
+ t.Fatalf("task CLI environment = %q, want %q", output, want)
+ }
+}
+
+func TestMuseAppTaskPromptPowerShellContext(t *testing.T) {
+ prompt := museappTaskPrompt("task", map[string]string{"MULTICA_CLI_PATH": `C:\User's Files\multica.exe`, "MULTICA_DAEMON_PORT": "19514"}, ExecOptions{}, "windows")
+ if !strings.Contains(prompt, `$env:MULTICA_DAEMON_PORT = '19514'`) || !strings.Contains(prompt, `& 'C:\User''s Files\multica.exe' @args }`) {
+ t.Fatalf("missing quoted PowerShell context: %s", prompt)
+ }
+}
diff --git a/server/pkg/agent/museapp_protocol.md b/server/pkg/agent/museapp_protocol.md
new file mode 100644
index 0000000000..b6e749efc5
--- /dev/null
+++ b/server/pkg/agent/museapp_protocol.md
@@ -0,0 +1,51 @@
+# Muse app execution contract
+
+The daemon and Muse worker must run on the same host or share the exact workdir
+paths. The receptionist wire protocol remains v1. An execution request carries
+the task-scoped `task_token`, `server_url`, `workspace_id`, and task prompt.
+
+For daemon tasks, the prompt includes a CLI command prefix with the daemon's
+absolute executable path, localhost daemon port, task and agent identity, and
+private Multica config root. The worker must use that prefix for each Multica
+command, including commands copied from AGENTS.md. It must set `MULTICA_TOKEN`
+from its own request's `task_token`; tokens and custom environment secrets are
+never included in the prefix. The existing receptionist passes the prompt
+through, so it needs no new request fields to deliver this context.
+
+## Cancellation and interrupted execution
+
+The daemon offers `museapp-process-cleanup-v1` when starting a task. The server
+must echo that capability before the daemon submits any work. Older daemons
+and other providers retain their existing start/cancel behavior.
+
+`POST /v1/tasks/{id}/cancel` may confirm shutdown with:
+
+```json
+{"execution_stopped": true}
+```
+
+This is an acknowledgement that the worker and its running tools have actually
+stopped. A flag written to status.json, a cancellation request accepted by the
+receptionist, or an HTTP 200 alone is insufficient. The response must arrive
+within the daemon's bounded cleanup window. A terminal `failed` or `cancelled`
+status can also report `execution_stopped: true`; `completed` means the worker
+finished normally.
+
+The existing receptionist only acknowledges cancellation bookkeeping. With
+that version, cancellation, timeout, or loss of contact yields
+`cleanup_unconfirmed`. The server blocks automatic continuation on that agent
+and runtime. Check and stop any remaining Muse worker and its tools before
+manually rerunning. Do not add `execution_stopped: true` to a receptionist
+until it can verify that guarantee.
+
+An execute response lost after submission is also an unknown execution
+outcome. Without a task id to cancel, the daemon reports unconfirmed cleanup
+instead of allowing an automatic retry to launch duplicate work. Explicit
+pre-execution HTTP 400/401/403 refusals remain ordinary launch errors.
+
+Daemon restart recovery, prolonged runtime disconnection, and stale-task expiry
+also cannot prove a started Muse worker stopped. The server persists
+`cleanup_unconfirmed` in the same transaction as these terminal transitions,
+before processing retries or exposing the failure to new claims. This applies
+to started Muse tasks, including tasks from older Muse daemons; queued or
+not-yet-started tasks and other providers retain their normal recovery policy.
diff --git a/server/pkg/agent/museapp_test.go b/server/pkg/agent/museapp_test.go
new file mode 100644
index 0000000000..66d93f403d
--- /dev/null
+++ b/server/pkg/agent/museapp_test.go
@@ -0,0 +1,1031 @@
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// fakeMuseAppReceptionist is a scripted stand-in for the real receptionist.
+// It speaks the same wire protocol so the backend's HTTP behavior,
+// polling, streaming and failure mapping are all exercised without any
+// real network or agent run.
+type fakeMuseAppReceptionist struct {
+ mu sync.Mutex
+ statuses []museappTaskStatus
+ statusCalls int
+ events []museappEvent
+ cancelCalls int
+ cancelStopped bool
+ executeCalls int
+ executeCode int
+ statusCode int // HTTP code for /v1/tasks polls; 0 means 200
+ healthCode int
+ health museappHealthResponse
+ authHeaders []string
+ executeBody []byte
+ sinceParams []string // ?since= values seen on /events polls
+}
+
+func (f *fakeMuseAppReceptionist) statusForCall() museappTaskStatus {
+ if len(f.statuses) == 0 {
+ return museappTaskStatus{Status: "running"}
+ }
+ i := f.statusCalls
+ if i >= len(f.statuses) {
+ i = len(f.statuses) - 1
+ }
+ return f.statuses[i]
+}
+
+func (f *fakeMuseAppReceptionist) handler() http.Handler {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/v1/execute", func(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.executeCalls++
+ f.authHeaders = append(f.authHeaders, r.Header.Get("Authorization"))
+ bodyBytes, _ := io.ReadAll(io.LimitReader(r.Body, 8<<20))
+ f.executeBody = bodyBytes
+ code := f.executeCode
+ if code == 0 {
+ code = 200
+ }
+ w.WriteHeader(code)
+ if code == 200 {
+ _ = json.NewEncoder(w).Encode(museappExecuteResponse{TaskID: "task-1"})
+ }
+ })
+ mux.HandleFunc("/v1/tasks/task-1", func(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ code := f.statusCode
+ if code == 0 {
+ code = 200
+ }
+ w.WriteHeader(code)
+ if code == 200 {
+ st := f.statusForCall()
+ f.statusCalls++
+ _ = json.NewEncoder(w).Encode(st)
+ }
+ })
+ mux.HandleFunc("/v1/tasks/task-1/events", func(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.sinceParams = append(f.sinceParams, r.URL.Query().Get("since"))
+ // Deliberately ignores ?since= and always returns the full log:
+ // the backend must dedupe by seq itself.
+ _ = json.NewEncoder(w).Encode(museappEventsResponse{Events: f.events})
+ })
+ mux.HandleFunc("/v1/tasks/task-1/cancel", func(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.cancelCalls++
+ _ = json.NewEncoder(w).Encode(museappCancelResponse{ExecutionStopped: f.cancelStopped})
+ })
+ mux.HandleFunc("/v1/health", func(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ code := f.healthCode
+ if code == 0 {
+ code = 200
+ }
+ w.WriteHeader(code)
+ if code == 200 {
+ h := f.health
+ // Default to protocol v1 if the test didn't set a version.
+ // (Real receptionists always return a version.)
+ if h.ProtocolVersion == 0 {
+ h.ProtocolVersion = 1
+ }
+ _ = json.NewEncoder(w).Encode(h)
+ }
+ })
+ return mux
+}
+
+func fastMuseAppPolls(t *testing.T) {
+ t.Helper()
+ oldInterval := museappPollInterval.Load()
+ oldBudget := museappMaxConsecutivePollErrors.Load()
+ museappPollInterval.Store(int64(5 * time.Millisecond))
+ museappMaxConsecutivePollErrors.Store(3)
+ t.Cleanup(func() {
+ museappPollInterval.Store(oldInterval)
+ museappMaxConsecutivePollErrors.Store(oldBudget)
+ })
+}
+
+// museappTestConfig points the backend at endpoint through the process
+// environment, which is the only place the backend reads its endpoint and
+// token from.
+func museappTestConfig(t *testing.T, endpoint, token string) Config {
+ t.Helper()
+ t.Setenv(museappEnvEndpoint, endpoint)
+ t.Setenv(museappEnvToken, token)
+ return Config{Logger: slog.Default()}
+}
+
+func drainMuseAppSession(t *testing.T, s *Session) (Result, []Message) {
+ t.Helper()
+ var msgs []Message
+ for m := range s.Messages {
+ msgs = append(msgs, m)
+ }
+ res := <-s.Result
+ return res, msgs
+}
+
+func TestMuseAppExecuteSuccess(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{
+ statuses: []museappTaskStatus{
+ {Status: "running"},
+ {Status: "completed", Result: "all done"},
+ },
+ events: []museappEvent{
+ {Seq: 1, Type: "text", Content: "hello "},
+ {Seq: 2, Type: "thinking", Content: "hmm"},
+ {Seq: 3, Type: "text", Content: "world"},
+ {Seq: 4, Type: "tool", Tool: "read_file", Content: "reading"},
+ },
+ health: museappHealthResponse{ProtocolVersion: 1, Version: "9.9.9"},
+ }
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, err := New("museapp", museappTestConfig(t, srv.URL, "sekret"))
+ if err != nil {
+ t.Fatalf("New(museapp) = %v", err)
+ }
+ sess, err := b.Execute(context.Background(), "do the thing", ExecOptions{Cwd: "/tmp/work-1"})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ res, msgs := drainMuseAppSession(t, sess)
+
+ if res.Status != "completed" {
+ t.Errorf("Status = %q, want completed", res.Status)
+ }
+ // The receptionist's result is the answer; the text events were commentary.
+ if res.Output != "all done" {
+ t.Errorf("Output = %q, want %q", res.Output, "all done")
+ }
+ if res.SessionID != "muse:task-1" {
+ t.Errorf("SessionID = %q, want muse:task-1", res.SessionID)
+ }
+
+ var sawText, sawThinking, sawTool, sawRunning int
+ for _, m := range msgs {
+ switch m.Type {
+ case MessageText:
+ sawText++
+ case MessageThinking:
+ sawThinking++
+ if m.Content != "hmm" {
+ t.Errorf("thinking content = %q", m.Content)
+ }
+ case MessageToolUse:
+ sawTool++
+ if m.Tool != "read_file" {
+ t.Errorf("tool = %q", m.Tool)
+ }
+ case MessageStatus:
+ sawRunning++
+ }
+ }
+ // The fake returns the full event log on every poll; each event must be
+ // emitted exactly once.
+ if sawText != 2 || sawThinking != 1 || sawTool != 1 {
+ t.Errorf("message counts text=%d thinking=%d tool=%d, want 2/1/1", sawText, sawThinking, sawTool)
+ }
+ if sawRunning != 1 {
+ t.Errorf("status messages = %d, want 1", sawRunning)
+ }
+
+ fake.mu.Lock()
+ defer fake.mu.Unlock()
+ if fake.executeCalls != 1 {
+ t.Errorf("execute calls = %d, want 1", fake.executeCalls)
+ }
+ if len(fake.authHeaders) == 0 || fake.authHeaders[0] != "Bearer sekret" {
+ t.Errorf("auth headers = %v, want [Bearer sekret]", fake.authHeaders)
+ }
+ var body museappExecuteRequest
+ if err := json.Unmarshal(fake.executeBody, &body); err != nil {
+ t.Fatalf("decode execute body: %v", err)
+ }
+ if body.Prompt != "do the thing" {
+ t.Errorf("prompt = %q", body.Prompt)
+ }
+ if body.WorkDir != "/tmp/work-1" {
+ t.Errorf("workdir = %q, want /tmp/work-1", body.WorkDir)
+ }
+ // The backend must poll incrementally: first ?since=0, then ?since=4
+ // once the four scripted events are consumed.
+ if len(fake.sinceParams) == 0 {
+ t.Error("no ?since= params observed on /events polls")
+ } else {
+ if fake.sinceParams[0] != "0" {
+ t.Errorf("first since = %q, want 0", fake.sinceParams[0])
+ }
+ advanced := false
+ for _, s := range fake.sinceParams[1:] {
+ if s != "0" && s != "" {
+ advanced = true
+ }
+ }
+ if !advanced {
+ t.Errorf("since never advanced past 0: %v", fake.sinceParams)
+ }
+ }
+}
+
+func TestMuseAppExecuteForwardsTaskToken(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{
+ statuses: []museappTaskStatus{
+ {Status: "completed", Result: "done"},
+ },
+ health: museappHealthResponse{ProtocolVersion: 1, Version: "9.9.9"},
+ }
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, err := New("museapp", museappTestConfig(t, srv.URL, "sekret"))
+ if err != nil {
+ t.Fatalf("New(museapp) = %v", err)
+ }
+ session, err := b.Execute(context.Background(), "do the thing", ExecOptions{
+ Cwd: "/tmp/work-1",
+ TaskToken: "mat_abc123",
+ MulticaServerURL: "https://multica.example.com",
+ MulticaWorkspaceID: "ws-123",
+ })
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ drainMuseAppSession(t, session)
+ var body museappExecuteRequest
+ if err := json.Unmarshal(fake.executeBody, &body); err != nil {
+ t.Fatalf("decode execute body: %v", err)
+ }
+ if body.TaskToken != "mat_abc123" {
+ t.Errorf("task_token = %q, want %q", body.TaskToken, "mat_abc123")
+ }
+ if body.ServerURL != "https://multica.example.com" {
+ t.Errorf("server_url = %q", body.ServerURL)
+ }
+ if body.WorkspaceID != "ws-123" {
+ t.Errorf("workspace_id = %q", body.WorkspaceID)
+ }
+}
+
+func TestMuseAppExecuteEmptyPrompt(t *testing.T) {
+ fake := &fakeMuseAppReceptionist{}
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ for _, prompt := range []string{"", " ", "\n\t "} {
+ if _, err := b.Execute(context.Background(), prompt, ExecOptions{}); err == nil {
+ t.Errorf("Execute(%q) succeeded, want error", prompt)
+ }
+ }
+ fake.mu.Lock()
+ defer fake.mu.Unlock()
+ if fake.executeCalls != 0 {
+ t.Errorf("execute calls = %d, want 0 (rejected before any HTTP)", fake.executeCalls)
+ }
+}
+
+func TestMuseAppExecuteMissingEndpoint(t *testing.T) {
+ t.Setenv(museappEnvEndpoint, "")
+ b, err := New("museapp", Config{Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("New(museapp) = %v", err)
+ }
+ t.Setenv(museappEnvEndpoint, "")
+ if _, err := b.Execute(context.Background(), "hi", ExecOptions{}); err == nil {
+ t.Fatal("Execute succeeded without MULTICA_MUSEAPP_ENDPOINT, want error")
+ } else if !strings.Contains(err.Error(), museappEnvEndpoint) {
+ t.Errorf("error = %q, want it to name %s", err, museappEnvEndpoint)
+ }
+}
+
+func TestMuseAppExecuteInvalidEndpoint(t *testing.T) {
+ b, _ := New("museapp", museappTestConfig(t, "://not-a-url", ""))
+ if _, err := b.Execute(context.Background(), "hi", ExecOptions{}); err == nil {
+ t.Fatal("Execute succeeded with garbage endpoint, want error")
+ }
+}
+
+func TestMuseAppExecuteHTTPError(t *testing.T) {
+ fake := &fakeMuseAppReceptionist{executeCode: 500}
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ session, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ result, _ := drainMuseAppSession(t, session)
+ if result.Status != "cleanup_unconfirmed" || !strings.Contains(result.Error, "500") {
+ t.Fatalf("ambiguous submission result = %+v", result)
+ }
+}
+
+func TestMuseAppExecuteUnauthorized(t *testing.T) {
+ fake := &fakeMuseAppReceptionist{executeCode: 401}
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, "wrong"))
+ if _, err := b.Execute(context.Background(), "hi", ExecOptions{}); err == nil {
+ t.Fatal("Execute succeeded on HTTP 401, want error")
+ } else if !strings.Contains(err.Error(), museappEnvToken) {
+ t.Errorf("error = %q, want it to name %s", err, museappEnvToken)
+ }
+}
+
+func TestMuseAppExecuteRemoteFailure(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{
+ statuses: []museappTaskStatus{{Status: "failed", Error: "boom", ExecutionStopped: true}},
+ }
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ res, _ := drainMuseAppSession(t, sess)
+ if res.Status != "failed" {
+ t.Errorf("Status = %q, want failed", res.Status)
+ }
+ if res.Error != "boom" {
+ t.Errorf("Error = %q, want boom", res.Error)
+ }
+}
+
+func TestMuseAppExecuteCancel(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{cancelStopped: true} // never completes: always "running"
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ ctx, cancel := context.WithCancel(context.Background())
+ sess, err := b.Execute(ctx, "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ time.Sleep(30 * time.Millisecond) // let at least one poll round happen
+ cancel()
+ res, _ := drainMuseAppSession(t, sess)
+ if res.Status != "aborted" {
+ t.Errorf("Status = %q, want aborted", res.Status)
+ }
+ fake.mu.Lock()
+ defer fake.mu.Unlock()
+ if fake.cancelCalls != 1 {
+ t.Errorf("cancel calls = %d, want 1", fake.cancelCalls)
+ }
+}
+
+func TestMuseAppExecuteTimeout(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{cancelStopped: true} // never completes
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ defer cancel()
+ sess, err := b.Execute(ctx, "hi", ExecOptions{Timeout: 50 * time.Millisecond})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ res, _ := drainMuseAppSession(t, sess)
+ if res.Status != "timeout" {
+ t.Errorf("Status = %q, want timeout", res.Status)
+ }
+}
+
+func TestMuseAppExecutePollBudgetExhausted(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{statusCode: 500, cancelStopped: true} // polls always fail
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ res, _ := drainMuseAppSession(t, sess)
+ if res.Status != "failed" {
+ t.Errorf("Status = %q, want failed", res.Status)
+ }
+ if !strings.Contains(res.Error, "unreachable") {
+ t.Errorf("Error = %q, want unreachable", res.Error)
+ }
+}
+
+func TestMuseAppExecuteResumeSessionID(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{
+ statuses: []museappTaskStatus{{Status: "completed", Result: "ok"}},
+ }
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{ResumeSessionID: "muse:task-9"})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ res, _ := drainMuseAppSession(t, sess)
+ if res.Status != "completed" {
+ t.Errorf("Status = %q, want completed", res.Status)
+ }
+ fake.mu.Lock()
+ defer fake.mu.Unlock()
+ var body museappExecuteRequest
+ if err := json.Unmarshal(fake.executeBody, &body); err != nil {
+ t.Fatalf("decode execute body: %v", err)
+ }
+ if body.SessionID != "muse:task-9" {
+ t.Errorf("session_id = %q, want muse:task-9", body.SessionID)
+ }
+}
+
+// The agent's custom_env reaches the backend as cfg.Env. It must not be able to
+// redirect the backend: the receptionist is whatever the daemon's own
+// environment says, and the daemon's token must never be sent anywhere else.
+func TestMuseAppEndpointAndTokenIgnoreCfgEnv(t *testing.T) {
+ fastMuseAppPolls(t)
+ legit := &fakeMuseAppReceptionist{
+ statuses: []museappTaskStatus{{Status: "completed", Result: "ok"}},
+ }
+ legitSrv := httptest.NewServer(legit.handler())
+ defer legitSrv.Close()
+
+ var mu sync.Mutex
+ var elsewhere []string
+ other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ elsewhere = append(elsewhere, r.URL.Path+" "+r.Header.Get("Authorization"))
+ mu.Unlock()
+ http.NotFound(w, r)
+ }))
+ defer other.Close()
+
+ t.Setenv(museappEnvEndpoint, legitSrv.URL)
+ t.Setenv(museappEnvToken, "daemon-token")
+ b, _ := New("museapp", Config{
+ Logger: slog.Default(),
+ Env: map[string]string{museappEnvEndpoint: other.URL, museappEnvToken: "agent-token"},
+ })
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ res, _ := drainMuseAppSession(t, sess)
+ if res.Status != "completed" {
+ t.Errorf("Status = %q, want completed (the process-env receptionist must serve the run)", res.Status)
+ }
+ mu.Lock()
+ if len(elsewhere) != 0 {
+ t.Errorf("a cfg.Env endpoint received requests: %q", elsewhere)
+ }
+ mu.Unlock()
+ legit.mu.Lock()
+ defer legit.mu.Unlock()
+ if len(legit.authHeaders) == 0 || legit.authHeaders[0] != "Bearer daemon-token" {
+ t.Errorf("auth headers = %v, want [Bearer daemon-token]", legit.authHeaders)
+ }
+}
+
+// The task id is the receptionist's input. A hostile or buggy id must stay one
+// path segment of a task URL.
+func TestMuseAppTaskIDIsEscapedInRequestPaths(t *testing.T) {
+ fastMuseAppPolls(t)
+ const hostileID = "../admin/x?y=1#"
+ var mu sync.Mutex
+ var escaped []string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ escaped = append(escaped, r.URL.EscapedPath())
+ mu.Unlock()
+ if r.URL.EscapedPath() == "/v1/execute" {
+ _ = json.NewEncoder(w).Encode(museappExecuteResponse{TaskID: hostileID})
+ return
+ }
+ _ = json.NewEncoder(w).Encode(museappTaskStatus{Status: "completed"})
+ }))
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, "tok"))
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ drainMuseAppSession(t, sess)
+
+ mu.Lock()
+ defer mu.Unlock()
+ taskPath := "/v1/tasks/" + url.PathEscape(hostileID)
+ sawTaskPath := false
+ for _, p := range escaped[1:] { // [0] is /v1/execute
+ if p != taskPath && p != taskPath+"/events" {
+ t.Errorf("request path %q left the task URL; want %q or %q/events", p, taskPath, taskPath)
+ }
+ if p == taskPath {
+ sawTaskPath = true
+ }
+ }
+ if !sawTaskPath {
+ t.Errorf("no status poll reached %q; paths = %q", taskPath, escaped)
+ }
+}
+
+// The events and status polls are separate requests, so the receptionist can
+// write its last event between them. The answer must still contain it.
+func TestMuseAppFinalEventsDrainedAfterTerminalStatus(t *testing.T) {
+ fastMuseAppPolls(t)
+ var mu sync.Mutex
+ events := []museappEvent{{Seq: 1, Type: "text", Content: "head "}}
+ mux := http.NewServeMux()
+ mux.HandleFunc("/v1/execute", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(museappExecuteResponse{TaskID: "task-1"})
+ })
+ mux.HandleFunc("/v1/tasks/task-1/events", func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ defer mu.Unlock()
+ _ = json.NewEncoder(w).Encode(museappEventsResponse{Events: events})
+ })
+ mux.HandleFunc("/v1/tasks/task-1", func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ defer mu.Unlock()
+ // The task finishes after the backend's events poll: the tail is
+ // written and the status flips in the same step.
+ if len(events) == 1 {
+ events = append(events, museappEvent{Seq: 2, Type: "text", Content: "tail"})
+ }
+ _ = json.NewEncoder(w).Encode(museappTaskStatus{Status: "completed"})
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ res, msgs := drainMuseAppSession(t, sess)
+ if res.Output != "head tail" {
+ t.Errorf("Output = %q, want %q", res.Output, "head tail")
+ }
+ var texts []string
+ for _, m := range msgs {
+ if m.Type == MessageText {
+ texts = append(texts, m.Content)
+ }
+ }
+ if strings.Join(texts, "") != "head tail" {
+ t.Errorf("streamed text = %q, want %q", texts, "head tail")
+ }
+}
+
+// "result" is the receptionist's final answer; the text events are commentary
+// on the way there. The answer must be the result, and the commentary must
+// still reach the transcript.
+func TestMuseAppResultIsTheAnswerNotTheEventText(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{
+ statuses: []museappTaskStatus{{Status: "completed", Result: "The final answer."}},
+ events: []museappEvent{
+ {Seq: 1, Type: "text", Content: "Looking that up... "},
+ {Seq: 2, Type: "text", Content: "Almost there."},
+ },
+ }
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ res, msgs := drainMuseAppSession(t, sess)
+ if res.Output != "The final answer." {
+ t.Errorf("Output = %q, want the receptionist's result", res.Output)
+ }
+ var streamed []string
+ for _, m := range msgs {
+ if m.Type == MessageText {
+ streamed = append(streamed, m.Content)
+ }
+ }
+ if strings.Join(streamed, "") != "Looking that up... Almost there." {
+ t.Errorf("streamed text = %q, want the commentary events", streamed)
+ }
+}
+
+// The protocol has three event types. Anything else is not words for the user.
+func TestMuseAppUnknownEventTypesAreIgnored(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{
+ statuses: []museappTaskStatus{{Status: "completed"}},
+ events: []museappEvent{
+ {Seq: 1, Type: "text", Content: "answer"},
+ {Seq: 2, Type: "status", Content: "INTERNAL-STATUS"},
+ {Seq: 3, Type: "", Content: "UNTYPED"},
+ {Seq: 4, Type: "error", Content: "SOME-ERROR"},
+ },
+ }
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ res, msgs := drainMuseAppSession(t, sess)
+ if res.Output != "answer" {
+ t.Errorf("Output = %q, want only the text event", res.Output)
+ }
+ for _, m := range msgs {
+ if strings.Contains(m.Content, "INTERNAL-STATUS") || strings.Contains(m.Content, "UNTYPED") || strings.Contains(m.Content, "SOME-ERROR") {
+ t.Errorf("an unknown event type reached the transcript: %+v", m)
+ }
+ }
+}
+
+func TestMuseAppNewWithoutEnv(t *testing.T) {
+ // The SupportedTypes lockstep test constructs every backend with a bare
+ // Config; museapp must not fail construction for lack of configuration —
+ // that surfaces at Execute time instead.
+ t.Setenv(museappEnvEndpoint, "")
+ if _, err := New("museapp", Config{Logger: slog.Default()}); err != nil {
+ t.Errorf("New(museapp) without env = %v, want nil", err)
+ }
+}
+
+func TestProbeMuseAppReceptionist(t *testing.T) {
+ ctx := context.Background()
+
+ t.Run("healthy", func(t *testing.T) {
+ fake := &fakeMuseAppReceptionist{health: museappHealthResponse{ProtocolVersion: 1, Version: "1.2.3"}}
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+ v, err := ProbeMuseAppReceptionist(ctx, srv.URL, "sekret")
+ if err != nil {
+ t.Fatalf("probe = %v", err)
+ }
+ if v != "1.2.3" {
+ t.Errorf("version = %q, want 1.2.3", v)
+ }
+ })
+
+ t.Run("protocol skew", func(t *testing.T) {
+ fake := &fakeMuseAppReceptionist{health: museappHealthResponse{ProtocolVersion: 999, Version: "9.9.9"}}
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+ if _, err := ProbeMuseAppReceptionist(ctx, srv.URL, ""); err == nil {
+ t.Fatal("probe succeeded on protocol skew, want error")
+ } else if !strings.Contains(err.Error(), "protocol skew") {
+ t.Errorf("error = %q, want protocol skew", err)
+ }
+ })
+
+ t.Run("unreachable", func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
+ url := srv.URL
+ srv.Close()
+ if _, err := ProbeMuseAppReceptionist(ctx, url, ""); err == nil {
+ t.Fatal("probe succeeded on closed port, want error")
+ }
+ })
+
+ t.Run("empty endpoint", func(t *testing.T) {
+ if _, err := ProbeMuseAppReceptionist(ctx, " ", ""); err == nil {
+ t.Fatal("probe succeeded on empty endpoint, want error")
+ }
+ })
+
+ t.Run("health 500", func(t *testing.T) {
+ fake := &fakeMuseAppReceptionist{healthCode: 500}
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+ if _, err := ProbeMuseAppReceptionist(ctx, srv.URL, ""); err == nil {
+ t.Fatal("probe succeeded on HTTP 500, want error")
+ }
+ })
+}
+
+func TestMuseAppExecuteEmptyTaskID(t *testing.T) {
+ fake := &fakeMuseAppReceptionist{}
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/v1/execute" {
+ _ = json.NewEncoder(w).Encode(museappExecuteResponse{TaskID: ""})
+ return
+ }
+ fake.handler().ServeHTTP(w, r)
+ }))
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ session, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ result, _ := drainMuseAppSession(t, session)
+ if result.Status != "cleanup_unconfirmed" || !strings.Contains(result.Error, "empty task id") {
+ t.Fatalf("missing submission handle result = %+v", result)
+ }
+}
+
+func TestMuseAppExecuteUnknownStatus(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{
+ statuses: []museappTaskStatus{{Status: "vaporware"}},
+ cancelStopped: true,
+ }
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ res, _ := drainMuseAppSession(t, sess)
+ if res.Status != "failed" {
+ t.Errorf("Status = %q, want failed (unknown status must not poll forever)", res.Status)
+ }
+ if !strings.Contains(res.Error, "unknown status") {
+ t.Errorf("Error = %q, want unknown status", res.Error)
+ }
+}
+
+// TestMuseAppCompletedWithErrorIsFailed: N1 regression.
+// When the receptionist returns completed+error (e.g. "result too large"),
+// the backend must report failed, not completed with transcript fallback.
+func TestMuseAppCompletedWithErrorIsFailed(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{
+ statuses: []museappTaskStatus{{
+ Status: "completed",
+ Error: "result too large (204801 bytes > 204800 byte limit)",
+ }},
+ }
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ res, _ := drainMuseAppSession(t, sess)
+ if res.Status != "failed" {
+ t.Errorf("Status = %q, want failed (completed+error is not success)", res.Status)
+ }
+ if !strings.Contains(res.Error, "result too large") {
+ t.Errorf("Error = %q, want 'result too large'", res.Error)
+ }
+}
+
+// TestMuseAppExecuteSendsProtocolVersion: Go-B3 regression.
+// The execute request must carry protocol_version so the receptionist
+// can reject incompatible versions before creating the task.
+func TestMuseAppExecuteSendsProtocolVersion(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{
+ statuses: []museappTaskStatus{{Status: "completed", Result: "done"}},
+ }
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ drainMuseAppSession(t, sess)
+
+ fake.mu.Lock()
+ defer fake.mu.Unlock()
+ if len(fake.executeBody) == 0 {
+ t.Fatal("no execute request captured")
+ }
+ var req museappExecuteRequest
+ if err := json.Unmarshal(fake.executeBody, &req); err != nil {
+ t.Fatalf("failed to parse execute request: %v", err)
+ }
+ if req.ProtocolVersion != museappProtocolVersion {
+ t.Errorf("ProtocolVersion = %d, want %d", req.ProtocolVersion, museappProtocolVersion)
+ }
+}
+
+// TestMuseAppProtocolSkewCancelsOrphanedTask: Go-B3 regression.
+// If the receptionist accepts the task but reports a version mismatch,
+// the backend must attempt to cancel the orphaned task.
+func TestMuseAppProtocolSkewCancelsOrphanedTask(t *testing.T) {
+ fastMuseAppPolls(t)
+ // Fake that returns v2 in execute response (simulating old receptionist
+ // without pre-create validation)
+ mux := http.NewServeMux()
+ mux.HandleFunc("/v1/health", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(museappHealthResponse{ProtocolVersion: 1, Version: "1.0"})
+ })
+ var cancelCalls int
+ var mu sync.Mutex
+ mux.HandleFunc("/v1/execute", func(w http.ResponseWriter, r *http.Request) {
+ // Old receptionist: creates task, returns v2 in response
+ _ = json.NewEncoder(w).Encode(museappExecuteResponse{
+ TaskID: "orphan-task-1",
+ ProtocolVersion: 2,
+ })
+ })
+ mux.HandleFunc("/v1/tasks/orphan-task-1/cancel", func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ cancelCalls++
+ mu.Unlock()
+ w.WriteHeader(200)
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ session, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ result, _ := drainMuseAppSession(t, session)
+ if result.Status != "cleanup_unconfirmed" || !strings.Contains(result.Error, "protocol skew") {
+ t.Fatalf("protocol-skew orphan result = %+v", result)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if cancelCalls == 0 {
+ t.Error("expected cancel attempt for orphaned task, got 0")
+ }
+}
+
+// probeMuseAppReceptionist must map version mismatch to ErrMuseAppProtocolSkew.
+func TestMuseAppProbeProtocolSkew(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/v1/health", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(museappHealthResponse{ProtocolVersion: 999, Version: "9.9"})
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+
+ _, err := ProbeMuseAppReceptionist(context.Background(), srv.URL, "")
+ if err == nil {
+ t.Fatal("expected protocol skew error")
+ }
+ if !strings.Contains(err.Error(), "protocol skew") {
+ t.Errorf("Error = %q, want protocol skew", err.Error())
+ }
+}
+
+// TestMuseAppProbeProtocolOK: matching version passes.
+func TestMuseAppProbeProtocolOK(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/v1/health", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(museappHealthResponse{ProtocolVersion: museappProtocolVersion, Version: "1.4.0"})
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+
+ ver, err := ProbeMuseAppReceptionist(context.Background(), srv.URL, "")
+ if err != nil {
+ t.Fatalf("Probe = %v", err)
+ }
+ if ver != "1.4.0" {
+ t.Errorf("Version = %q, want 1.4.0", ver)
+ }
+}
+
+// Sub-second timeout must round up to 1, not truncate to 0.
+func TestMuseAppTimeoutSRoundsUp(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{
+ statuses: []museappTaskStatus{{Status: "completed", Result: "done"}},
+ }
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ // 500ms should round up to timeout_s=1, not 0
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{Timeout: 500 * time.Millisecond})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ drainMuseAppSession(t, sess)
+
+ fake.mu.Lock()
+ defer fake.mu.Unlock()
+ var req museappExecuteRequest
+ if err := json.Unmarshal(fake.executeBody, &req); err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if req.TimeoutS != 1 {
+ t.Errorf("TimeoutS = %d, want 1 (500ms rounds up)", req.TimeoutS)
+ }
+}
+
+// When Go has no deadline, send explicit 24h so the receptionist
+// doesn't default to 1h and kill a task Go is happy to wait for.
+func TestMuseAppNoTimeoutSends24h(t *testing.T) {
+ fastMuseAppPolls(t)
+ fake := &fakeMuseAppReceptionist{
+ statuses: []museappTaskStatus{{Status: "completed", Result: "done"}},
+ }
+ srv := httptest.NewServer(fake.handler())
+ defer srv.Close()
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ drainMuseAppSession(t, sess)
+
+ fake.mu.Lock()
+ defer fake.mu.Unlock()
+ var req museappExecuteRequest
+ if err := json.Unmarshal(fake.executeBody, &req); err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if req.TimeoutS != 24*3600 {
+ t.Errorf("TimeoutS = %d, want 86400 (24h default)", req.TimeoutS)
+ }
+}
+
+// When polling fails exhaustively, the backend must best-effort cancel
+// the remote task (B2).
+func TestMuseAppPollFailureCancelsRemote(t *testing.T) {
+ fastMuseAppPolls(t)
+ var cancelCalls int
+ var mu sync.Mutex
+ mux := http.NewServeMux()
+ mux.HandleFunc("/v1/health", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(museappHealthResponse{ProtocolVersion: 1})
+ })
+ mux.HandleFunc("/v1/execute", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(museappExecuteResponse{TaskID: "t1", ProtocolVersion: 1})
+ })
+ // Status endpoint always fails
+ mux.HandleFunc("/v1/tasks/t1", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(500)
+ })
+ mux.HandleFunc("/v1/tasks/t1/events", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(museappEventsResponse{})
+ })
+ mux.HandleFunc("/v1/tasks/t1/cancel", func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ cancelCalls++
+ mu.Unlock()
+ _ = json.NewEncoder(w).Encode(museappCancelResponse{ExecutionStopped: true})
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+
+ // Shrink the poll budget for a fast test
+ oldMax := museappMaxConsecutivePollErrors.Load()
+ museappMaxConsecutivePollErrors.Store(3)
+ defer museappMaxConsecutivePollErrors.Store(oldMax)
+
+ b, _ := New("museapp", museappTestConfig(t, srv.URL, ""))
+ sess, err := b.Execute(context.Background(), "hi", ExecOptions{})
+ if err != nil {
+ t.Fatalf("Execute = %v", err)
+ }
+ res, _ := drainMuseAppSession(t, sess)
+ if res.Status != "failed" {
+ t.Errorf("Status = %q, want failed", res.Status)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if cancelCalls == 0 {
+ t.Error("expected best-effort cancel on poll exhaustion")
+ }
+}
diff --git a/server/pkg/db/generated/supplement.sql.go b/server/pkg/db/generated/supplement.sql.go
index 1e7927a119..c40631faef 100644
--- a/server/pkg/db/generated/supplement.sql.go
+++ b/server/pkg/db/generated/supplement.sql.go
@@ -864,7 +864,9 @@ SET status = 'running',
started_at = now(),
wait_reason = NULL,
prepare_lease_expires_at = NULL,
- result = CASE WHEN $1::boolean AND candidate.provider IN ('pi', 'omp')
+ result = CASE WHEN $1::boolean AND candidate.provider = 'museapp'
+ THEN COALESCE(t.result, '{}'::jsonb) || '{"process_cleanup_capability":"museapp-process-cleanup-v1"}'::jsonb
+ WHEN $1::boolean AND candidate.provider IN ('pi', 'omp')
THEN COALESCE(t.result, '{}'::jsonb) || '{"process_cleanup_capability":"pi-process-cleanup-v1"}'::jsonb
ELSE t.result END
FROM candidate
diff --git a/server/pkg/db/generated/task_cleanup.sql.go b/server/pkg/db/generated/task_cleanup.sql.go
index bdb46d17c2..dc7524dc50 100644
--- a/server/pkg/db/generated/task_cleanup.sql.go
+++ b/server/pkg/db/generated/task_cleanup.sql.go
@@ -110,12 +110,115 @@ func (q *Queries) FailCancelledTaskProcessCleanup(ctx context.Context, arg FailC
return i, err
}
+const markMuseAppRecoveryCleanupUnconfirmed = `-- name: MarkMuseAppRecoveryCleanupUnconfirmed :many
+UPDATE agent_task_queue task
+SET failure_reason = 'cleanup_unconfirmed',
+ error = concat_ws('; ', NULLIF(task.error, ''),
+ 'Muse worker may still be running after daemon recovery or loss of contact. Check and stop it before manually rerunning.')
+WHERE task.id = ANY($1::uuid[])
+ AND task.status = 'failed' AND task.started_at IS NOT NULL
+ AND task.failure_reason IN ('runtime_recovery', 'runtime_offline', 'timeout')
+ AND (task.result->>'process_cleanup_capability' = 'museapp-process-cleanup-v1'
+ OR EXISTS (SELECT 1 FROM agent_runtime runtime
+ WHERE runtime.id = task.runtime_id AND runtime.provider = 'museapp'))
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step
+`
+
+// Run inside the bulk terminal-write transaction, before its rows reach the
+// retry pipeline. Losing a daemon cannot stop an independently running worker.
+// Keep the start-time capability as evidence if the runtime was later changed
+// or removed; legacy Muse daemons are recognized by their runtime provider.
+func (q *Queries) MarkMuseAppRecoveryCleanupUnconfirmed(ctx context.Context, taskIds []pgtype.UUID) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, markMuseAppRecoveryCleanupUnconfirmed, taskIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ &i.BranchName,
+ &i.DurableWorkDir,
+ &i.ChannelContextRevision,
+ &i.CommentThreadID,
+ &i.CancelledByType,
+ &i.CancelledByID,
+ &i.CancelledByName,
+ &i.IssueSnapshot,
+ &i.WorkflowStep,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const markPiTaskProcessCleanupPending = `-- name: MarkPiTaskProcessCleanupPending :exec
UPDATE agent_task_queue task
SET result = COALESCE(task.result, '{}'::jsonb) || '{"process_cleanup_pending":true}'::jsonb
WHERE task.id = $1 AND task.status = 'cancelled' AND task.started_at IS NOT NULL
- AND task.result->>'process_cleanup_capability' = 'pi-process-cleanup-v1'
- AND EXISTS (SELECT 1 FROM agent_runtime runtime WHERE runtime.id = task.runtime_id AND runtime.provider IN ('pi', 'omp'))
+ AND EXISTS (
+ SELECT 1 FROM agent_runtime runtime
+ WHERE runtime.id = task.runtime_id
+ AND ((runtime.provider IN ('pi', 'omp') AND task.result->>'process_cleanup_capability' = 'pi-process-cleanup-v1')
+ OR (runtime.provider = 'museapp' AND task.result->>'process_cleanup_capability' = 'museapp-process-cleanup-v1'))
+ )
`
// Cancellation makes the task terminal before the daemon finishes stopping it.
diff --git a/server/pkg/db/queries/supplement.sql b/server/pkg/db/queries/supplement.sql
index d119bb3c40..a1028b05d3 100644
--- a/server/pkg/db/queries/supplement.sql
+++ b/server/pkg/db/queries/supplement.sql
@@ -24,7 +24,9 @@ SET status = 'running',
started_at = now(),
wait_reason = NULL,
prepare_lease_expires_at = NULL,
- result = CASE WHEN @enable_process_cleanup::boolean AND candidate.provider IN ('pi', 'omp')
+ result = CASE WHEN @enable_process_cleanup::boolean AND candidate.provider = 'museapp'
+ THEN COALESCE(t.result, '{}'::jsonb) || '{"process_cleanup_capability":"museapp-process-cleanup-v1"}'::jsonb
+ WHEN @enable_process_cleanup::boolean AND candidate.provider IN ('pi', 'omp')
THEN COALESCE(t.result, '{}'::jsonb) || '{"process_cleanup_capability":"pi-process-cleanup-v1"}'::jsonb
ELSE t.result END
FROM candidate
diff --git a/server/pkg/db/queries/task_cleanup.sql b/server/pkg/db/queries/task_cleanup.sql
index d3d01d68a0..e51101223c 100644
--- a/server/pkg/db/queries/task_cleanup.sql
+++ b/server/pkg/db/queries/task_cleanup.sql
@@ -53,8 +53,12 @@ RETURNING *;
UPDATE agent_task_queue task
SET result = COALESCE(task.result, '{}'::jsonb) || '{"process_cleanup_pending":true}'::jsonb
WHERE task.id = @id AND task.status = 'cancelled' AND task.started_at IS NOT NULL
- AND task.result->>'process_cleanup_capability' = 'pi-process-cleanup-v1'
- AND EXISTS (SELECT 1 FROM agent_runtime runtime WHERE runtime.id = task.runtime_id AND runtime.provider IN ('pi', 'omp'));
+ AND EXISTS (
+ SELECT 1 FROM agent_runtime runtime
+ WHERE runtime.id = task.runtime_id
+ AND ((runtime.provider IN ('pi', 'omp') AND task.result->>'process_cleanup_capability' = 'pi-process-cleanup-v1')
+ OR (runtime.provider = 'museapp' AND task.result->>'process_cleanup_capability' = 'museapp-process-cleanup-v1'))
+ );
-- name: ClearTaskProcessCleanupPending :exec
UPDATE agent_task_queue
@@ -62,6 +66,23 @@ SET result = result - 'process_cleanup_pending'
WHERE id = @id AND status IN ('cancelled', 'failed')
AND result->>'process_cleanup_pending' = 'true';
+-- name: MarkMuseAppRecoveryCleanupUnconfirmed :many
+-- Run inside the bulk terminal-write transaction, before its rows reach the
+-- retry pipeline. Losing a daemon cannot stop an independently running worker.
+-- Keep the start-time capability as evidence if the runtime was later changed
+-- or removed; legacy Muse daemons are recognized by their runtime provider.
+UPDATE agent_task_queue task
+SET failure_reason = 'cleanup_unconfirmed',
+ error = concat_ws('; ', NULLIF(task.error, ''),
+ 'Muse worker may still be running after daemon recovery or loss of contact. Check and stop it before manually rerunning.')
+WHERE task.id = ANY(@task_ids::uuid[])
+ AND task.status = 'failed' AND task.started_at IS NOT NULL
+ AND task.failure_reason IN ('runtime_recovery', 'runtime_offline', 'timeout')
+ AND (task.result->>'process_cleanup_capability' = 'museapp-process-cleanup-v1'
+ OR EXISTS (SELECT 1 FROM agent_runtime runtime
+ WHERE runtime.id = task.runtime_id AND runtime.provider = 'museapp'))
+RETURNING task.*;
+
-- name: TaskWaitingForProcessCleanup :one
SELECT EXISTS (
SELECT 1 FROM agent_task_queue candidate
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index fcf1ec9a38..f895d52efa 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -72,6 +72,9 @@ const (
// descendant cleanup and explicitly confirms its cancellation outcome.
// Persist only at start; old daemons must retain their cancellation contract.
DaemonCapabilityPiProcessCleanupV1 = "pi-process-cleanup-v1"
+ // Muse workers run outside the daemon process tree and must acknowledge
+ // execution shutdown before cancellation can release subsequent work.
+ DaemonCapabilityMuseAppProcessCleanupV1 = "museapp-process-cleanup-v1"
// DaemonCapabilityWorkflowStatusRulesV1 advertises that the daemon's
// runtime brief drops its built-in in_progress / in_review rules for an
// issue whose claim carries a project workflow (MUL-8145). Only then may