Skip to content

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

Go

fix(agent): stop agents shipping local-path links, make Desktop 404 recoverable (MUL-4899) (#5557)

Naiyuan Qing1507997272a1
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 7c517a6ad3..0006a3412e 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -1,6 +1,7 @@
import { app, BrowserWindow, dialog, ipcMain, nativeImage, Notification } from "electron";
import { homedir } from "os";
import { join } from "path";
+import { pathToFileURL } from "url";
import { electronApp, optimizer, is } from "@electron-toolkit/utils";
import fixPath from "fix-path";
import { setupAutoUpdater } from "./updater";
@@ -10,6 +11,7 @@ import { openExternalSafely, downloadURLSafely } from "./external-url";
import { installContextMenu } from "./context-menu";
import { handleAppShortcut } from "./keyboard-shortcuts";
import { installNavigationGestures } from "./navigation-gestures";
+import { installNavigationGuard } from "./navigation-guard";
import { getAppVersion } from "./app-version";
import { loadRuntimeConfig } from "./runtime-config-loader";
import type { RuntimeConfigResult } from "../shared/runtime-config";
@@ -242,10 +244,22 @@ function createRendererWebPreferences(
}
function loadRenderer(window: BrowserWindow): void {
+ const rendererEntry = join(__dirname, "../renderer/index.html");
+ const rendererURL =
+ is.dev && process.env["ELECTRON_RENDERER_URL"]
+ ? process.env["ELECTRON_RENDERER_URL"]
+ : pathToFileURL(rendererEntry).toString();
+
+ // Installed before the load so the very first navigation is already covered.
+ // Both the main window and every issue window load through here, so guarding
+ // this one site covers both — see navigation-guard.ts for what is and is not
+ // in scope (it is origin hardening; in-app routing never reaches it).
+ installNavigationGuard(window, rendererURL);
+
if (is.dev && process.env["ELECTRON_RENDERER_URL"]) {
void window.loadURL(process.env["ELECTRON_RENDERER_URL"]);
} else {
- void window.loadFile(join(__dirname, "../renderer/index.html"));
+ void window.loadFile(rendererEntry);
}
}
diff --git a/apps/desktop/src/main/navigation-guard.test.ts b/apps/desktop/src/main/navigation-guard.test.ts
new file mode 100644
index 0000000000..8c12f6de12
--- /dev/null
+++ b/apps/desktop/src/main/navigation-guard.test.ts
@@ -0,0 +1,108 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ describeBlockedNavigation,
+ installNavigationGuard,
+ isTrustedRendererURL,
+ type NavigationGuardWindow,
+} from "./navigation-guard";
+
+const DEV_RENDERER = "http://localhost:5173/";
+const PROD_RENDERER = "file:///Applications/Multica.app/Contents/renderer/index.html";
+
+describe("isTrustedRendererURL", () => {
+ describe("dev server origin", () => {
+ it("trusts the renderer origin, including deeper paths on it", () => {
+ expect(isTrustedRendererURL(DEV_RENDERER, DEV_RENDERER)).toBe(true);
+ expect(isTrustedRendererURL("http://localhost:5173/index.html", DEV_RENDERER)).toBe(true);
+ });
+
+ it("rejects a different origin", () => {
+ expect(isTrustedRendererURL("https://evil.example/", DEV_RENDERER)).toBe(false);
+ // Same host, different port — a different origin.
+ expect(isTrustedRendererURL("http://localhost:9999/", DEV_RENDERER)).toBe(false);
+ // Same host and port, different scheme.
+ expect(isTrustedRendererURL("https://localhost:5173/", DEV_RENDERER)).toBe(false);
+ });
+
+ it("rejects a file URL while the dev server is the trusted origin", () => {
+ expect(isTrustedRendererURL("file:///Users/me/shot.png", DEV_RENDERER)).toBe(false);
+ });
+ });
+
+ describe("packaged renderer", () => {
+ it("trusts the exact renderer document", () => {
+ expect(isTrustedRendererURL(PROD_RENDERER, PROD_RENDERER)).toBe(true);
+ });
+
+ it("rejects any other file, including a sibling of the renderer", () => {
+ // A file:// document has an opaque origin, so origin equality would say
+ // "same origin" for every file on disk. Path comparison is what makes
+ // this safe.
+ expect(
+ isTrustedRendererURL(
+ "file:///Applications/Multica.app/Contents/renderer/other.html",
+ PROD_RENDERER,
+ ),
+ ).toBe(false);
+ expect(isTrustedRendererURL("file:///Users/me/Desktop/shot.png", PROD_RENDERER)).toBe(false);
+ expect(isTrustedRendererURL("file:///etc/passwd", PROD_RENDERER)).toBe(false);
+ });
+
+ it("rejects a remote origin", () => {
+ expect(isTrustedRendererURL("https://evil.example/", PROD_RENDERER)).toBe(false);
+ });
+ });
+
+ it("rejects unparseable input", () => {
+ expect(isTrustedRendererURL("not a url", PROD_RENDERER)).toBe(false);
+ expect(isTrustedRendererURL("", PROD_RENDERER)).toBe(false);
+ });
+});
+
+describe("describeBlockedNavigation", () => {
+ it("logs the origin only, never the path", () => {
+ // A blocked URL is attacker- or agent-controlled; its path can spell out a
+ // local filesystem layout.
+ expect(describeBlockedNavigation("https://evil.example/secret/path?token=abc")).toBe(
+ "https://evil.example",
+ );
+ expect(describeBlockedNavigation("file:///Users/me/Desktop/private.png")).toBe("file:");
+ expect(describeBlockedNavigation("nonsense")).toBe("invalid URL");
+ });
+});
+
+describe("installNavigationGuard", () => {
+ let listener: (event: { preventDefault(): void }, url: string) => void;
+ let window: NavigationGuardWindow;
+
+ beforeEach(() => {
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ window = {
+ webContents: {
+ on: (_event, fn) => {
+ listener = fn;
+ return window;
+ },
+ },
+ };
+ installNavigationGuard(window, PROD_RENDERER);
+ });
+
+ function navigate(url: string): boolean {
+ const preventDefault = vi.fn();
+ listener({ preventDefault }, url);
+ return preventDefault.mock.calls.length > 0;
+ }
+
+ it("allows a navigation to the renderer document itself", () => {
+ expect(navigate(PROD_RENDERER)).toBe(false);
+ });
+
+ it("blocks a navigation to a foreign origin", () => {
+ expect(navigate("https://evil.example/")).toBe(true);
+ });
+
+ it("blocks a navigation to an arbitrary local file", () => {
+ expect(navigate("file:///Users/me/Desktop/shot.png")).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/main/navigation-guard.ts b/apps/desktop/src/main/navigation-guard.ts
new file mode 100644
index 0000000000..5258ca26fe
--- /dev/null
+++ b/apps/desktop/src/main/navigation-guard.ts
@@ -0,0 +1,89 @@
+/**
+ * Top-level navigation hardening for renderer windows.
+ *
+ * Scope note (MUL-4899) — this is origin hardening ONLY, and deliberately NOT
+ * the mechanism that handles in-app links.
+ *
+ * Client-side routing never fires `will-navigate`: React Router pushes history
+ * entries without a document load. So an in-app path — a good one like
+ * `/acme/issues/1` or a bad one like `/Users/me/shot.png` pasted by an agent —
+ * never reaches this guard at all. Bad in-app paths are a routing concern,
+ * answered by the renderer's 404 page. Trying to police application paths here
+ * would be both ineffective (the hook does not see them) and wrong (it would
+ * break legitimate reloads).
+ *
+ * What it does catch is a real document-level navigation away from the trusted
+ * renderer: `window.location = 'https://evil.example'`, an anchor Chromium
+ * resolves to a remote URL in the same window, a dropped file URL. These windows
+ * run with `webSecurity: false` and `sandbox: false`, so a foreign document
+ * landing in one would inherit privileged context. New windows and external
+ * links already route through `setWindowOpenHandler` → `openExternalSafely`;
+ * this closes the same-window path.
+ */
+
+/** The subset of BrowserWindow this module needs — keeps it unit-testable. */
+export type NavigationGuardWindow = {
+ webContents: {
+ on(
+ event: "will-navigate",
+ listener: (event: { preventDefault(): void }, url: string) => void,
+ ): unknown;
+ };
+};
+
+/**
+ * Report whether `url` is the trusted renderer document itself.
+ *
+ * `trustedURL` is whatever the caller is about to load: the dev server origin in
+ * development, the packaged renderer's file URL in production. Deriving trust
+ * from the same value we load keeps this from drifting out of sync.
+ */
+export function isTrustedRendererURL(url: string, trustedURL: string): boolean {
+ let target: URL;
+ let trusted: URL;
+ try {
+ target = new URL(url);
+ trusted = new URL(trustedURL);
+ } catch {
+ return false;
+ }
+
+ if (trusted.protocol === "file:") {
+ // A file:// document has an opaque ("null") origin, so origin equality is
+ // useless here — compare the document path instead. Only the exact renderer
+ // entry point is trusted: a sibling file in the same directory is not the
+ // renderer, and neither is any other path on disk.
+ return target.protocol === "file:" && target.pathname === trusted.pathname;
+ }
+ return target.protocol !== "file:" && target.origin === trusted.origin;
+}
+
+/**
+ * Describe a blocked navigation for the log.
+ *
+ * Origin only, never the path: a blocked URL is attacker- or agent-controlled
+ * and its path may spell out a local filesystem layout. Scheme and host are
+ * enough to diagnose what was blocked.
+ */
+export function describeBlockedNavigation(url: string): string {
+ try {
+ const { protocol, host } = new URL(url);
+ return host ? `${protocol}//${host}` : protocol;
+ } catch {
+ return "invalid URL";
+ }
+}
+
+/** Install the guard. Call before loading the window so the first load is covered. */
+export function installNavigationGuard(
+ window: NavigationGuardWindow,
+ trustedURL: string,
+): void {
+ window.webContents.on("will-navigate", (event, url) => {
+ if (isTrustedRendererURL(url, trustedURL)) return;
+ event.preventDefault();
+ console.warn(
+ `[security] blocked will-navigate to a non-renderer origin: ${describeBlockedNavigation(url)}`,
+ );
+ });
+}
diff --git a/apps/desktop/src/renderer/src/components/route-error-page.test.tsx b/apps/desktop/src/renderer/src/components/route-error-page.test.tsx
index 83b58b12ee..4edc8c50c3 100644
--- a/apps/desktop/src/renderer/src/components/route-error-page.test.tsx
+++ b/apps/desktop/src/renderer/src/components/route-error-page.test.tsx
@@ -5,6 +5,9 @@ import { createMemoryRouter, RouterProvider } from "react-router-dom";
const openModal = vi.fn();
const reloadActiveTab = vi.fn();
const closeActiveTab = vi.fn();
+const navigateActiveSession = vi.fn();
+
+let activeWorkspaceSlug: string | null = "acme";
vi.mock("@multica/core/modals", () => ({
useModalStore: {
@@ -12,11 +15,19 @@ vi.mock("@multica/core/modals", () => ({
},
}));
-vi.mock("@/stores/tab-store", () => ({
- useTabStore: {
- getState: () => ({ reloadActiveTab, closeActiveTab }),
- },
-}));
+vi.mock("@/stores/tab-store", () => {
+ const state = () => ({
+ reloadActiveTab,
+ closeActiveTab,
+ navigateActiveSession,
+ activeWorkspaceSlug,
+ });
+ // Callable-store shape: selector call for the hook, getState for imperatives.
+ const useTabStore = (selector: (s: ReturnType<typeof state>) => unknown) =>
+ selector(state());
+ useTabStore.getState = state;
+ return { useTabStore };
+});
import { DesktopRouteErrorPage, formatRouteErrorReport } from "./route-error-page";
@@ -25,11 +36,32 @@ function Boom(): null {
return null;
}
+/**
+ * Render a router whose only route does NOT match `path`, which is how React
+ * Router produces a real 404 ErrorResponse — the same object shape the desktop
+ * shell sees when a tab opens an unroutable URL.
+ */
+function renderUnmatchedRoute(path: string) {
+ const router = createMemoryRouter(
+ [
+ {
+ path: "/:workspaceSlug/issues",
+ element: <div>issues</div>,
+ errorElement: <DesktopRouteErrorPage />,
+ },
+ ],
+ { initialEntries: [path] },
+ );
+ return render(<RouterProvider router={router} />);
+}
+
describe("DesktopRouteErrorPage", () => {
beforeEach(() => {
openModal.mockReset();
reloadActiveTab.mockReset();
closeActiveTab.mockReset();
+ navigateActiveSession.mockReset();
+ activeWorkspaceSlug = "acme";
vi.spyOn(console, "error").mockImplementation(() => {});
});
@@ -96,4 +128,79 @@ describe("DesktopRouteErrorPage", () => {
expect(report).toContain("trigger: route-errorElement");
expect(report).toContain("TODO: promote error context to structured feedback fields");
});
-});
\ No newline at end of file
+
+ // --- 404 as a first-class product state (MUL-4899) -----------------------
+
+ describe("404 Not Found", () => {
+ it("renders a Not Found page, not a crash report, for an unroutable path", async () => {
+ renderUnmatchedRoute("/Users/whoever/Desktop/shot.png");
+
+ const alert = await screen.findByRole("alert");
+ expect(alert).toHaveTextContent("This page doesn't exist");
+ // The reported defect: a 404 was presented as an app crash and the user
+ // was invited to file a bug for a link that was simply wrong.
+ expect(alert).not.toHaveTextContent("Something went wrong");
+ expect(alert).not.toHaveTextContent("Unknown route error");
+ expect(
+ screen.queryByRole("button", { name: /report error/i }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /reload tab/i }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows the unroutable path so the user can see what was wrong with the link", async () => {
+ renderUnmatchedRoute("/Users/whoever/Desktop/shot.png");
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "/Users/whoever/Desktop/shot.png",
+ );
+ });
+
+ it("always offers Close tab", async () => {
+ renderUnmatchedRoute("/Users/whoever/Desktop/shot.png");
+ fireEvent.click(await screen.findByRole("button", { name: /close tab/i }));
+ expect(closeActiveTab).toHaveBeenCalledTimes(1);
+ });
+
+ it("takes the recovery entry from the active workspace, NEVER from the bad pathname", async () => {
+ // The whole point: deriving a slug from this pathname yields "Users" and a
+ // "recovery" button pointing at /Users/issues — a second 404.
+ renderUnmatchedRoute("/Users/whoever/Desktop/shot.png");
+
+ fireEvent.click(await screen.findByRole("button", { name: /go to issues/i }));
+ expect(navigateActiveSession).toHaveBeenCalledWith("/acme/issues", {
+ replace: true,
+ });
+ expect(navigateActiveSession).not.toHaveBeenCalledWith(
+ "/Users/issues",
+ expect.anything(),
+ );
+ });
+
+ it("offers no recovery entry at all when there is no active workspace", async () => {
+ // Rather than guess one from the failed URL.
+ activeWorkspaceSlug = null;
+ renderUnmatchedRoute("/Users/whoever/Desktop/shot.png");
+
+ await screen.findByRole("alert");
+ expect(
+ screen.queryByRole("button", { name: /go to issues/i }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /close tab/i }),
+ ).toBeInTheDocument();
+ });
+
+ it("keeps the crash page for a non-404 route error", async () => {
+ const router = createMemoryRouter(
+ [{ path: "/acme/issues", element: <Boom />, errorElement: <DesktopRouteErrorPage /> }],
+ { initialEntries: ["/acme/issues"] },
+ );
+ render(<RouterProvider router={router} />);
+
+ const alert = await screen.findByRole("alert");
+ expect(alert).toHaveTextContent("Something went wrong in this tab");
+ expect(alert).not.toHaveTextContent("This page doesn't exist");
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/src/components/route-error-page.tsx b/apps/desktop/src/renderer/src/components/route-error-page.tsx
index ccf9abac50..80c4a56b8e 100644
--- a/apps/desktop/src/renderer/src/components/route-error-page.tsx
+++ b/apps/desktop/src/renderer/src/components/route-error-page.tsx
@@ -1,6 +1,6 @@
import { useMemo } from "react";
-import { useLocation, useRouteError } from "react-router-dom";
-import { AlertTriangle, RotateCw, Send, X } from "lucide-react";
+import { isRouteErrorResponse, useLocation, useRouteError } from "react-router-dom";
+import { AlertTriangle, Compass, RotateCw, Send, X } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
import { useModalStore } from "@multica/core/modals";
import { useTabStore } from "@/stores/tab-store";
@@ -42,11 +42,94 @@ export function formatRouteErrorReport({
].join("\n");
}
+/**
+ * Resolve the workspace the user is actually in, for a recovery entry point.
+ *
+ * Reads the tab store's `activeWorkspaceSlug` — the real session context —
+ * rather than the failed URL. This is load-bearing, not stylistic: the routes
+ * that land here most often are the ones whose first segment is not a workspace
+ * at all. Deriving a slug from `/Users/me/shot.png` yields "Users" and a
+ * "recovery" button pointing at `/Users/issues`, i.e. a second 404 (MUL-4899).
+ * A pathname we already failed to route cannot be a source of truth about where
+ * the user belongs.
+ *
+ * Returns null when there is no active workspace, in which case the caller
+ * offers only unconditionally-safe actions (close the tab).
+ */
+function useRecoveryRoute(): string | null {
+ const activeWorkspaceSlug = useTabStore((state) => state.activeWorkspaceSlug);
+ return activeWorkspaceSlug ? `/${activeWorkspaceSlug}/issues` : null;
+}
+
export function DesktopRouteErrorPage() {
const error = useRouteError();
+
+ // A 404 is not a crash — it is a route that does not exist, which is a normal
+ // and fully recoverable product state. It reaches this boundary because React
+ // Router routes "no route matched" to the nearest errorElement, the same place
+ // a thrown render error lands. Splitting them here is the whole point of
+ // MUL-4899: 8 of 18 desktop_route_error reports were users clicking an agent's
+ // `/Users/...` link and being told the app broke and to report a bug.
+ if (isRouteErrorResponse(error) && error.status === 404) {
+ return <DesktopNotFoundPage />;
+ }
+ return <DesktopUnexpectedErrorPage error={error} />;
+}
+
+function DesktopNotFoundPage() {
+ const location = useLocation();
+ const recoveryRoute = useRecoveryRoute();
+
+ return (
+ <div
+ role="alert"
+ className="flex h-full min-h-[20rem] flex-col items-center justify-center gap-4 p-8 text-center"
+ >
+ <div className="rounded-full bg-muted p-3 text-muted-foreground">
+ <Compass className="h-6 w-6" aria-hidden="true" />
+ </div>
+ <div className="space-y-2">
+ <h2 className="text-lg font-semibold">This page doesn&apos;t exist</h2>
+ <p className="max-w-lg text-sm text-muted-foreground">
+ Nothing in Multica matches this address. If you got here from a link,
+ it probably points at a file on someone else&apos;s computer rather
+ than a page.
+ </p>
+ <p className="max-w-lg truncate font-mono text-xs text-muted-foreground">
+ {location.pathname}
+ </p>
+ </div>
+ <div className="flex gap-2">
+ {recoveryRoute ? (
+ <Button
+ type="button"
+ variant="outline"
+ // Session mutation, not a router call: the Coordinator projects
+ // the new session URL into the router (MUL-4741 invariant 1).
+ onClick={() =>
+ useTabStore
+ .getState()
+ .navigateActiveSession(recoveryRoute, { replace: true })
+ }
+ >
+ Go to issues
+ </Button>
+ ) : null}
+ <Button
+ type="button"
+ onClick={() => useTabStore.getState().closeActiveTab()}
+ >
+ <X className="mr-2 h-4 w-4" aria-hidden="true" />
+ Close tab
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function DesktopUnexpectedErrorPage({ error }: { error: unknown }) {
const location = useLocation();
- const workspaceSlug = location.pathname.split("/").filter(Boolean)[0];
- const safeRoute = workspaceSlug ? `/${workspaceSlug}/issues` : null;
+ const recoveryRoute = useRecoveryRoute();
const report = useMemo(
() =>
formatRouteErrorReport({
@@ -87,7 +170,7 @@ export function DesktopRouteErrorPage() {
<RotateCw className="mr-2 h-4 w-4" aria-hidden="true" />
Reload tab
</Button>
- {safeRoute ? (
+ {recoveryRoute ? (
<Button
type="button"
variant="outline"
@@ -96,7 +179,7 @@ export function DesktopRouteErrorPage() {
onClick={() =>
useTabStore
.getState()
- .navigateActiveSession(safeRoute, { replace: true })
+ .navigateActiveSession(recoveryRoute, { replace: true })
}
>
Go to issues
@@ -147,4 +230,4 @@ function safeJson(value: unknown) {
} catch {
return String(value);
}
-}
\ No newline at end of file
+}
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index 33369c32d1..ebd09d3130 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -1087,6 +1087,10 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {
return err
}
if hasDesc {
+ if err := guardLocalPathLinks(desc, "issue description",
+ "Deliver the file itself with `multica issue create --attachment <path>` (repeatable) and drop the link."); err != nil {
+ return err
+ }
body["description"] = desc
}
if statusFlag != "" {
@@ -1261,6 +1265,13 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
+ // `issue update` has no --attachment flag, so the hint must point at the
+ // command that does. Telling the agent to "pass --attachment" here would
+ // name an argument this command rejects.
+ if err := guardLocalPathLinks(desc, "issue description",
+ "`multica issue update` cannot carry files — deliver the file with `multica issue comment add <issue-id> --attachment <path>` instead, and drop the link."); err != nil {
+ return err
+ }
body["description"] = desc
}
if statusChanged {
@@ -1914,6 +1925,10 @@ func runIssueCommentAdd(cmd *cobra.Command, args []string) error {
if !hasContent {
return fmt.Errorf("--content, --content-stdin, or --content-file is required")
}
+ if err := guardLocalPathLinks(content, "comment body",
+ "Deliver the file itself with `multica issue comment add <issue-id> --attachment <path>` (repeatable) and drop the link."); err != nil {
+ return err
+ }
client, err := newAPIClient(cmd)
if err != nil {
diff --git a/server/cmd/multica/local_path_link_lint.go b/server/cmd/multica/local_path_link_lint.go
new file mode 100644
index 0000000000..35d8c9ffa3
--- /dev/null
+++ b/server/cmd/multica/local_path_link_lint.go
@@ -0,0 +1,155 @@
+package main
+
+import (
+ "fmt"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/yuin/goldmark"
+ "github.com/yuin/goldmark/ast"
+ "github.com/yuin/goldmark/text"
+)
+
+// Agent deliverables must never carry a link to the runtime's own filesystem
+// (MUL-4899). The runtime brief now states that contract, but a prompt is
+// advisory; this is the enforcement backstop on the three commands that publish
+// agent-authored markdown to a human reader.
+//
+// Scope is deliberately narrow on three axes, because a false positive here
+// blocks a legitimate deliverable outright:
+//
+// 1. Agent task context only. A human running the CLI with a PAT is not
+// linting-eligible: their links are their own business, and they may well
+// have a shared path the reader really can open.
+// 2. Real markdown link/image destinations only. The body is parsed as
+// CommonMark and only Link / Image / AutoLink destinations are examined, so
+// a path inside a code span or fenced block — the normal way an agent quotes
+// a path it is *discussing* — is structurally invisible here. A full-text
+// scan cannot make that distinction and would fail exactly the comments that
+// explain this bug.
+// 3. High-confidence targets only. See classifyLocalPathTarget.
+
+// localPathLinkFinding is one markdown link/image destination that resolves to
+// this machine's filesystem. Reason states the evidence, so the error message
+// can tell the agent WHY its link was rejected rather than just that it was.
+type localPathLinkFinding struct {
+ Target string
+ Reason string
+}
+
+// findLocalPathLinks parses body as CommonMark and returns every link, image, or
+// autolink destination that is high-confidence a runtime-local path.
+//
+// Only the destination is inspected — never the link text, and never the
+// surrounding prose. Findings are de-duplicated by target so a path linked five
+// times reports once.
+func findLocalPathLinks(body string) []localPathLinkFinding {
+ source := []byte(body)
+ doc := goldmark.New().Parser().Parse(text.NewReader(source))
+
+ var findings []localPathLinkFinding
+ seen := make(map[string]struct{})
+ _ = ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
+ if !entering {
+ return ast.WalkContinue, nil
+ }
+ var target string
+ switch node := n.(type) {
+ case *ast.Link:
+ target = string(node.Destination)
+ case *ast.Image:
+ target = string(node.Destination)
+ case *ast.AutoLink:
+ // `<file:///Users/me/shot.png>` renders as a clickable link just like
+ // an inline one, so it is the same defect and belongs in scope.
+ target = string(node.URL(source))
+ default:
+ return ast.WalkContinue, nil
+ }
+
+ reason := classifyLocalPathTarget(target)
+ if reason == "" {
+ return ast.WalkContinue, nil
+ }
+ if _, dup := seen[target]; dup {
+ return ast.WalkContinue, nil
+ }
+ seen[target] = struct{}{}
+ findings = append(findings, localPathLinkFinding{Target: target, Reason: reason})
+ return ast.WalkContinue, nil
+ })
+ return findings
+}
+
+// classifyLocalPathTarget returns the evidence that target is a runtime-local
+// path, or "" when it is not — or when we cannot tell.
+//
+// Only three signals count, all of them positive evidence that the target names
+// THIS machine:
+//
+// 1. A `file://` URL. Unresolvable for any reader by construction.
+// 2. An absolute path inside the current working directory — the task workdir,
+// which is per-task and private.
+// 3. An absolute path that names a file existing on this machine right now.
+//
+// Everything else is allowed through, and the omissions are the point. A bare
+// `/foo` is a valid origin-relative URI reference (RFC 3986 §4.2) and is exactly
+// how `/acme/issues/123` is written, so an absolute-looking target that neither
+// lives in the workdir nor exists on disk is indistinguishable from a legitimate
+// in-app link and must not be guessed at. Relative targets are left alone for
+// the same reason. The prompt contract in the runtime brief — not this lint — is
+// what covers the residue.
+func classifyLocalPathTarget(target string) string {
+ target = strings.TrimSpace(target)
+ if target == "" {
+ return ""
+ }
+
+ // Order matters: a Windows drive-absolute path ("C:\Users\me\shot.png")
+ // parses as scheme "c" under RFC 3986, so the filesystem test has to run
+ // before any scheme sniffing or Windows paths would be dismissed as URLs.
+ if filepath.IsAbs(target) {
+ if within, err := fileWithinWorkingDir(target); err == nil && within {
+ return "it is inside this task's working directory"
+ }
+ if info, err := os.Stat(target); err == nil && !info.IsDir() {
+ return "it names a file that exists only on this machine"
+ }
+ return ""
+ }
+
+ if parsed, err := url.Parse(target); err == nil && strings.EqualFold(parsed.Scheme, "file") {
+ return "it is a file:// URL"
+ }
+ return ""
+}
+
+// guardLocalPathLinks fails the command when an agent-authored body publishes a
+// link to a runtime-local path. Returns nil outside an agent task context.
+//
+// deliveryHint is the caller's own fix instruction. It is a parameter rather
+// than a constant because the right answer differs per command, and one of them
+// is a trap: `multica issue update` has no --attachment flag, so a shared
+// "pass --attachment" message would send the agent to an argument that does not
+// exist and turn one failure into two.
+func guardLocalPathLinks(body, field, deliveryHint string) error {
+ if !inAgentExecutionContext() {
+ return nil
+ }
+ findings := findLocalPathLinks(body)
+ if len(findings) == 0 {
+ return nil
+ }
+
+ var b strings.Builder
+ fmt.Fprintf(&b, "%s links %d runtime-local path(s), which no reader can open:\n", field, len(findings))
+ for _, f := range findings {
+ fmt.Fprintf(&b, " - %q — %s\n", f.Target, f.Reason)
+ }
+ b.WriteString("\nThe path exists only on the machine running you; for everyone else the link is dead. ")
+ b.WriteString(deliveryHint)
+ b.WriteString("\nTo merely reference a code location, use inline code instead of a link (`path/to/file.ts:42`) — code spans and fenced blocks are not checked.")
+ return fmt.Errorf("%s", b.String())
+}
diff --git a/server/cmd/multica/local_path_link_lint_test.go b/server/cmd/multica/local_path_link_lint_test.go
new file mode 100644
index 0000000000..5e7854724e
--- /dev/null
+++ b/server/cmd/multica/local_path_link_lint_test.go
@@ -0,0 +1,267 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// withAgentContext makes inAgentExecutionContext() report true for one test.
+func withAgentContext(t *testing.T) {
+ t.Helper()
+ t.Setenv("MULTICA_TASK_ID", "task-1")
+}
+
+// withWorkdir chdirs into a fresh temp dir so workdir-prefix classification has
+// a real, isolated root to resolve against.
+func withWorkdir(t *testing.T) string {
+ t.Helper()
+ dir := t.TempDir()
+ t.Chdir(dir)
+ // EvalSymlinks: macOS temp dirs live under a symlinked /var, and the
+ // classifier canonicalizes both sides. Return the resolved path so tests
+ // build targets that match what it compares against.
+ resolved, err := filepath.EvalSymlinks(dir)
+ if err != nil {
+ t.Fatalf("resolve temp dir: %v", err)
+ }
+ return resolved
+}
+
+func targets(findings []localPathLinkFinding) []string {
+ out := make([]string, 0, len(findings))
+ for _, f := range findings {
+ out = append(out, f.Target)
+ }
+ return out
+}
+
+// The three high-confidence signals, each proven by a positive case.
+func TestFindLocalPathLinksHighConfidenceSignals(t *testing.T) {
+ workdir := withWorkdir(t)
+
+ shot := filepath.Join(workdir, "shot.png")
+ if err := os.WriteFile(shot, []byte("x"), 0o600); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+
+ outside := filepath.Join(t.TempDir(), "outside.png")
+ if err := os.WriteFile(outside, []byte("x"), 0o600); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ resolvedOutside, err := filepath.EvalSymlinks(outside)
+ if err != nil {
+ t.Fatalf("resolve fixture: %v", err)
+ }
+
+ cases := []struct {
+ name string
+ body string
+ want []string
+ }{
+ {
+ name: "file:// URL in a link",
+ body: "see [the chart](file:///tmp/chart.png)",
+ want: []string{"file:///tmp/chart.png"},
+ },
+ {
+ name: "file:// URL in an autolink renders clickable too",
+ body: "see <file:///tmp/chart.png>",
+ want: []string{"file:///tmp/chart.png"},
+ },
+ {
+ name: "absolute path inside the task workdir",
+ body: "![screenshot](" + shot + ")",
+ want: []string{shot},
+ },
+ {
+ name: "absolute path to a file that exists on this machine",
+ body: "[log](" + resolvedOutside + ")",
+ want: []string{resolvedOutside},
+ },
+ {
+ name: "the reported repro: image link to a workdir file",
+ body: "Done. Screenshot: [点我](" + shot + ")",
+ want: []string{shot},
+ },
+ {
+ name: "one path linked repeatedly reports once",
+ body: "[a](" + shot + ") and [b](" + shot + ")",
+ want: []string{shot},
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := targets(findLocalPathLinks(tc.body))
+ if len(got) != len(tc.want) {
+ t.Fatalf("got %v, want %v", got, tc.want)
+ }
+ for i := range got {
+ if got[i] != tc.want[i] {
+ t.Errorf("got[%d]=%q, want %q", i, got[i], tc.want[i])
+ }
+ }
+ })
+ }
+}
+
+// Everything the lint must let through. Each of these is a legitimate
+// deliverable that a full-text scan or a looser rule would break — the reason
+// the lint parses markdown and limits itself to three positive signals.
+func TestFindLocalPathLinksAllowsLegitimateContent(t *testing.T) {
+ workdir := withWorkdir(t)
+ shot := filepath.Join(workdir, "shot.png")
+ if err := os.WriteFile(shot, []byte("x"), 0o600); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+
+ cases := []struct {
+ name string
+ body string
+ }{
+ {
+ // The canonical in-app link. Absolute-looking, but a valid
+ // origin-relative URI reference (RFC 3986 §4.2) — blocking it would
+ // break every issue link an agent writes.
+ name: "origin-relative in-app link",
+ body: "see [MUL-1](/acme/issues/MUL-1) and [inbox](/issues/123)",
+ },
+ {
+ name: "external http link",
+ body: "the PR is at [#42](https://github.com/multica-ai/multica/pull/42)",
+ },
+ {
+ name: "mention link",
+ body: "[@Nevi](mention://member/abc-123)",
+ },
+ {
+ // The whole point of parsing an AST: an agent explaining THIS bug
+ // quotes local paths constantly. None of these are link nodes.
+ name: "path inside a code span",
+ body: "the repro is `[x](" + shot + ")` — note the local path",
+ },
+ {
+ name: "path inside a fenced code block",
+ body: "```md\n[screenshot](" + shot + ")\n![x](file:///tmp/x.png)\n```",
+ },
+ {
+ name: "path inside an indented code block",
+ body: " [screenshot](" + shot + ")\n",
+ },
+ {
+ name: "path as plain prose is not a link",
+ body: "I wrote the screenshot to " + shot + " on my machine.",
+ },
+ {
+ name: "relative link is left alone",
+ body: "[readme](docs/readme.md)",
+ },
+ {
+ // Absolute, does not exist, not in the workdir → indistinguishable
+ // from an in-app route. Deliberately allowed; the prompt contract
+ // covers this residue, not the lint.
+ name: "absolute path that does not exist",
+ body: "[x](/Users/someone-else/never-existed.png)",
+ },
+ {
+ name: "link text mentioning a path is not a destination",
+ body: "[" + shot + "](/acme/issues/1)",
+ },
+ {
+ name: "empty body",
+ body: "",
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := targets(findLocalPathLinks(tc.body)); len(got) != 0 {
+ t.Errorf("expected no findings, got %v\n--- body ---\n%s", got, tc.body)
+ }
+ })
+ }
+}
+
+// A directory is not a deliverable file; stat-ing one must not trip the lint.
+func TestFindLocalPathLinksIgnoresDirectories(t *testing.T) {
+ dir := t.TempDir()
+ resolved, err := filepath.EvalSymlinks(dir)
+ if err != nil {
+ t.Fatalf("resolve: %v", err)
+ }
+ t.Chdir(t.TempDir())
+ if got := targets(findLocalPathLinks("[dir](" + resolved + ")")); len(got) != 0 {
+ t.Errorf("a directory target should not be reported, got %v", got)
+ }
+}
+
+func TestGuardLocalPathLinksOnlyFiresInAgentContext(t *testing.T) {
+ workdir := withWorkdir(t)
+ shot := filepath.Join(workdir, "shot.png")
+ if err := os.WriteFile(shot, []byte("x"), 0o600); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ body := "[screenshot](" + shot + ")"
+
+ t.Run("human PAT context is never linted", func(t *testing.T) {
+ // No MULTICA_AGENT_ID / MULTICA_TASK_ID: a person running the CLI. Their
+ // links are their own business — they may well have a path the reader
+ // really can open.
+ t.Setenv("MULTICA_AGENT_ID", "")
+ t.Setenv("MULTICA_TASK_ID", "")
+ if err := guardLocalPathLinks(body, "comment body", "hint"); err != nil {
+ t.Errorf("expected no error outside agent context, got: %v", err)
+ }
+ })
+
+ t.Run("agent task context hard-fails", func(t *testing.T) {
+ withAgentContext(t)
+ err := guardLocalPathLinks(body, "comment body", "hint")
+ if err == nil {
+ t.Fatal("expected a hard failure inside agent context")
+ }
+ if !strings.Contains(err.Error(), shot) {
+ t.Errorf("error should name the offending target, got: %v", err)
+ }
+ })
+
+ t.Run("agent context with a clean body passes", func(t *testing.T) {
+ withAgentContext(t)
+ if err := guardLocalPathLinks("all good — see [MUL-1](/acme/issues/MUL-1)", "comment body", "hint"); err != nil {
+ t.Errorf("expected no error for a clean body, got: %v", err)
+ }
+ })
+}
+
+// The per-command fix hint. `issue update` is the trap: it has no --attachment
+// flag, so a shared "pass --attachment" message would point the agent at an
+// argument the command rejects and turn one failure into two.
+func TestGuardLocalPathLinksHintIsPerCommand(t *testing.T) {
+ workdir := withWorkdir(t)
+ shot := filepath.Join(workdir, "shot.png")
+ if err := os.WriteFile(shot, []byte("x"), 0o600); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ withAgentContext(t)
+
+ err := guardLocalPathLinks(
+ "[screenshot]("+shot+")",
+ "issue description",
+ "`multica issue update` cannot carry files — deliver the file with `multica issue comment add <issue-id> --attachment <path>` instead, and drop the link.",
+ )
+ if err == nil {
+ t.Fatal("expected a hard failure")
+ }
+ msg := err.Error()
+ if !strings.Contains(msg, "`multica issue update` cannot carry files") {
+ t.Errorf("update hint missing, got: %v", msg)
+ }
+ if !strings.Contains(msg, "multica issue comment add <issue-id> --attachment <path>") {
+ t.Errorf("update hint must redirect to comment add, got: %v", msg)
+ }
+ if strings.Contains(msg, "multica issue update --attachment") {
+ t.Errorf("update hint must never name a flag `issue update` does not have, got: %v", msg)
+ }
+}
diff --git a/server/go.mod b/server/go.mod
index 9f2e8c9192..644cec45ec 100644
--- a/server/go.mod
+++ b/server/go.mod
@@ -29,6 +29,7 @@ require (
github.com/slack-go/slack v0.26.0
github.com/spf13/cobra v1.10.2
github.com/spf13/pflag v1.0.9
+ github.com/yuin/goldmark v1.8.4
golang.org/x/sync v0.20.0
golang.org/x/sys v0.35.0
google.golang.org/protobuf v1.36.8
diff --git a/server/go.sum b/server/go.sum
index b880426295..192781f5f2 100644
--- a/server/go.sum
+++ b/server/go.sum
@@ -152,6 +152,8 @@ github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
+github.com/yuin/goldmark v1.8.4 h1:oat/nd3U6NeQqFEL3xpEJq7d7c86NI+DbSNGAs4xnjA=
+github.com/yuin/goldmark v1.8.4/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index f80800788d..a38aa61498 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -3893,6 +3893,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
ProjectDescription: task.ProjectDescription,
ProjectResources: convertProjectResourcesForEnv(task.ProjectResources),
ChatSessionID: task.ChatSessionID,
+ ChatChannelType: task.ChatChannelType,
AutopilotRunID: task.AutopilotRunID,
AutopilotID: task.AutopilotID,
AutopilotTitle: task.AutopilotTitle,
diff --git a/server/internal/daemon/execenv/channel_type.go b/server/internal/daemon/execenv/channel_type.go
new file mode 100644
index 0000000000..2f07b8cc52
--- /dev/null
+++ b/server/internal/daemon/execenv/channel_type.go
@@ -0,0 +1,32 @@
+package execenv
+
+// Chat channel discriminators as they arrive on the task payload. The server
+// stamps `chat_channel_type` from the channel_chat_session_binding row
+// (handler/daemon.go); an empty value means a web/mobile chat session with no
+// IM channel behind it.
+//
+// These are plain string constants on purpose: the daemon compares a value the
+// server already serialized to JSON, and must not pull the server-side
+// integration packages (integrations/slack, integrations/lark) into its own
+// build just to read one discriminator. The canonical definitions live with
+// their adapters — slack.TypeSlack and channel.TypeFeishu — and both sides
+// agree on the wire strings below.
+const (
+ ChannelTypeSlack = "slack"
+ ChannelTypeFeishu = "feishu"
+)
+
+// ChannelDisplayName renders a chat_channel_type for prompt / brief copy.
+// Unknown types fall through to the raw discriminator rather than a generic
+// placeholder, so a channel added server-side without a mapping here still
+// names itself in the prompt instead of silently reading as "unknown".
+func ChannelDisplayName(channelType string) string {
+ switch channelType {
+ case ChannelTypeSlack:
+ return "Slack"
+ case ChannelTypeFeishu:
+ return "Feishu/Lark"
+ default:
+ return channelType
+ }
+}
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index ff0857c833..5bab43d24b 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -119,15 +119,23 @@ type TaskContextForEnv struct {
ProjectDescription string // durable project-level context, rendered into the brief's Project Context section
ProjectResources []ProjectResourceForEnv // resources attached to the project
ChatSessionID string // non-empty for chat tasks
- AutopilotRunID string // non-empty for autopilot run_only tasks
- AutopilotID string
- AutopilotTitle string
- AutopilotDescription string
- AutopilotSource string
- AutopilotTriggerPayload string
- QuickCreatePrompt string // non-empty for quick-create tasks
- HandoffNote string // assignment handoff instruction; rendered into issue_context.md (MUL-3375)
- IsSquadLeader bool // true when the agent is acting as a squad leader (may exit silently on no_action)
+ // ChatChannelType is the IM platform behind a chat session ("slack",
+ // "feishu"); empty for a web/mobile chat. The brief reads it for DELIVERY
+ // policy only: any non-empty value means the reply leaves Multica for an
+ // external channel, so `multica attachment upload` cannot deliver a file and
+ // the Output section says text-only instead (MUL-4899). The orthogonal
+ // history-command policy is Slack-only and lives in the per-turn chat prompt
+ // (daemon/prompt.go) — the server has no Feishu history reader.
+ ChatChannelType string
+ AutopilotRunID string // non-empty for autopilot run_only tasks
+ AutopilotID string
+ AutopilotTitle string
+ AutopilotDescription string
+ AutopilotSource string
+ AutopilotTriggerPayload string
+ QuickCreatePrompt string // non-empty for quick-create tasks
+ HandoffNote string // assignment handoff instruction; rendered into issue_context.md (MUL-3375)
+ IsSquadLeader bool // true when the agent is acting as a squad leader (may exit silently on no_action)
// WorkspaceContext is the workspace-level system prompt (workspace.context
// in the DB). Rendered into the brief as `## Workspace Context` when
// non-empty so every agent in the workspace sees the same shared context,
diff --git a/server/internal/daemon/execenv/runtime_config_delivery_test.go b/server/internal/daemon/execenv/runtime_config_delivery_test.go
new file mode 100644
index 0000000000..b6450326ef
--- /dev/null
+++ b/server/internal/daemon/execenv/runtime_config_delivery_test.go
@@ -0,0 +1,160 @@
+package execenv
+
+import (
+ "strings"
+ "testing"
+)
+
+// The MUL-4899 delivery contract. Two orthogonal properties are pinned here and
+// must not be collapsed:
+//
+// - The invariant ("never link a local path") is ALWAYS-ON — every task kind,
+// no exceptions. It lives outside writeOutput's kind switch so a future kind
+// cannot silently inherit no invariant at all; this test is what keeps that
+// true.
+// - The surface policy ("here is how a file actually gets delivered HERE") is
+// PER-KIND, and there are five surfaces, not four — web/mobile chat and IM
+// chat are the same taskKind but opposite answers.
+
+// deliveryInvariantFixtures covers all five task kinds. The chat kind appears
+// twice because ChatChannelType splits it into two surfaces.
+func deliveryInvariantFixtures() map[string]TaskContextForEnv {
+ return map[string]TaskContextForEnv{
+ "comment": {IssueID: "i-1", TriggerCommentID: "tc-1", AgentName: "Eve", AgentID: "eve-1"},
+ "assignment": {IssueID: "i-1", AgentName: "Eve", AgentID: "eve-1"},
+ "autopilot": {AutopilotRunID: "r-1", AgentName: "Eve", AgentID: "eve-1"},
+ "quickcreate": {QuickCreatePrompt: "p", AgentName: "Eve", AgentID: "eve-1"},
+ "chat_direct": {ChatSessionID: "c-1", AgentName: "Eve", AgentID: "eve-1"},
+ "chat_slack": {ChatSessionID: "c-1", ChatChannelType: ChannelTypeSlack, AgentName: "Eve", AgentID: "eve-1"},
+ "chat_feishu": {ChatSessionID: "c-1", ChatChannelType: ChannelTypeFeishu, AgentName: "Eve", AgentID: "eve-1"},
+ }
+}
+
+func TestBriefDeliveryInvariantIsAlwaysOn(t *testing.T) {
+ t.Parallel()
+
+ // Phrases every kind must carry, whatever its surface can or cannot deliver.
+ wantAll := []string{
+ "Runtime-local paths are never deliverables",
+ "NEVER write an absolute path or a `file://` URL as a clickable link",
+ "`path/to/file.ts:42`",
+ }
+
+ for name, ctx := range deliveryInvariantFixtures() {
+ out := buildMetaSkillContent("claude", ctx)
+ for _, want := range wantAll {
+ if !strings.Contains(out, want) {
+ t.Errorf("kind=%s: brief is missing always-on delivery invariant %q", name, want)
+ }
+ }
+ }
+}
+
+func TestBriefSurfaceDeliveryPolicy(t *testing.T) {
+ t.Parallel()
+
+ cases := map[string]struct {
+ mustHave []string
+ mustNot []string
+ }{
+ // Issue surfaces: files ride the comment.
+ "comment": {
+ mustHave: []string{"`--attachment <path>` to `multica issue comment add`"},
+ mustNot: []string{"multica attachment upload"},
+ },
+ "assignment": {
+ mustHave: []string{"`--attachment <path>` to `multica issue comment add`"},
+ mustNot: []string{"multica attachment upload"},
+ },
+ // Direct chat is the ONLY surface where `attachment upload` works.
+ "chat_direct": {
+ mustHave: []string{"`multica attachment upload <local-path>`"},
+ mustNot: []string{"text-only"},
+ },
+ // IM surfaces are text-only. The upload command must not appear: it binds
+ // to a Multica chat reply, which an IM reply is not, so suggesting it
+ // would have the agent upload a file and report it as delivered.
+ "chat_slack": {
+ mustHave: []string{"Slack conversation is text-only", "does NOT apply"},
+ mustNot: []string{"run `multica attachment upload"},
+ },
+ "chat_feishu": {
+ mustHave: []string{"Feishu/Lark conversation is text-only", "does NOT apply"},
+ mustNot: []string{"run `multica attachment upload"},
+ },
+ "autopilot": {
+ mustHave: []string{"this surface is text-only"},
+ mustNot: []string{"multica attachment upload"},
+ },
+ "quickcreate": {
+ mustHave: []string{"your stdout is text-only", "`multica issue create` call itself via `--attachment <path>`"},
+ mustNot: []string{"multica attachment upload"},
+ },
+ }
+
+ fixtures := deliveryInvariantFixtures()
+ for name, want := range cases {
+ ctx, ok := fixtures[name]
+ if !ok {
+ t.Fatalf("no fixture for surface %q", name)
+ }
+ out := buildMetaSkillContent("claude", ctx)
+ for _, phrase := range want.mustHave {
+ if !strings.Contains(out, phrase) {
+ t.Errorf("surface=%s: brief missing surface policy %q\n--- Output section ---\n%s",
+ name, phrase, outputSection(out))
+ }
+ }
+ for _, phrase := range want.mustNot {
+ if strings.Contains(out, phrase) {
+ t.Errorf("surface=%s: brief must NOT carry %q (wrong surface's delivery mechanism)\n--- Output section ---\n%s",
+ name, phrase, outputSection(out))
+ }
+ }
+ }
+}
+
+// TestBriefInboundAttachmentIsNotADeliverable locks the inbound half: a
+// downloaded attachment's local path is a private working copy, and the most
+// tempting one to echo back because it arrived from the conversation.
+func TestBriefInboundAttachmentIsNotADeliverable(t *testing.T) {
+ t.Parallel()
+
+ out := buildMetaSkillContent("claude", TaskContextForEnv{
+ IssueID: "i-1", TriggerCommentID: "tc-1", AgentName: "Eve", AgentID: "eve-1",
+ })
+ for _, want := range []string{
+ "private working copy",
+ "Never echo it back into a deliverable as a link",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("Attachments section missing %q\n---\n%s", want, out)
+ }
+ }
+}
+
+func TestChannelDisplayName(t *testing.T) {
+ t.Parallel()
+
+ cases := map[string]string{
+ ChannelTypeSlack: "Slack",
+ ChannelTypeFeishu: "Feishu/Lark",
+ "": "",
+ // An unmapped channel names itself rather than reading as "unknown".
+ "discord": "discord",
+ }
+ for in, want := range cases {
+ if got := ChannelDisplayName(in); got != want {
+ t.Errorf("ChannelDisplayName(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+// outputSection extracts the brief's `## Output` section for readable failures.
+func outputSection(brief string) string {
+ idx := strings.Index(brief, "\n## Output\n")
+ if idx < 0 {
+ return "<no ## Output section>"
+ }
+ return brief[idx:]
+}
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 2c7ee802ee..52a75b5386 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -475,7 +475,12 @@ func writeMentions(b *strings.Builder) {
func writeAttachments(b *strings.Builder) {
b.WriteString("## Attachments\n\n")
b.WriteString("Issues and comments may include file attachments (images, documents, etc.).\n")
- b.WriteString("When a task includes attachment IDs and you need the files, inspect `multica attachment --help` and use the authenticated CLI path. Do not open Multica resource URLs directly.\n\n")
+ b.WriteString("When a task includes attachment IDs and you need the files, inspect `multica attachment --help` and use the authenticated CLI path. Do not open Multica resource URLs directly.\n")
+ // Closes the inbound half of the MUL-4899 loop: an attachment the agent
+ // just downloaded is the most tempting local path to echo back, because it
+ // came from the conversation and *feels* shared. It is not — the download
+ // landed in this run's private workdir.
+ b.WriteString("An attachment you download lands in your own workdir: that local path is a private working copy, not something the reader can open. Never echo it back into a deliverable as a link — re-deliver the file itself if it needs to travel (see `## Output`).\n\n")
}
// writeAlwaysUseCLI emits the "must go through the multica CLI" guardrail
@@ -485,19 +490,54 @@ func writeAlwaysUseCLI(b *strings.Builder) {
b.WriteString("Access Multica platform resources (issues, comments, attachments, files) only through the `multica` CLI — never `curl` / `wget`. For any operation the CLI doesn't cover, post a comment mentioning the workspace owner rather than working around it.\n\n")
}
-// writeOutput emits the kind-specific Output section.
+// writeDeliveryInvariant emits the always-on delivery contract, shared by every
+// task kind.
+//
+// MUL-4899: agents were writing runtime-local paths into deliverables as
+// clickable links (`[screenshot](/Users/agent/work/shot.png)`). Two things were
+// wrong with that and the brief stated neither: the link is dead for every
+// reader (the path exists only on the machine that ran the agent), and on
+// macOS/Linux Desktop clicking it opened a tab at that path and hit a router
+// 404. The Desktop side is fixed separately; this is the source fix — the
+// contract the brief never carried.
+//
+// Deliberately emitted OUTSIDE writeOutput's kind switch: the invariant holds on
+// every surface, and the per-kind line inside the switch only answers "how do I
+// deliver a file HERE". Keeping them apart stops a new task kind from silently
+// inheriting no invariant at all.
+func writeDeliveryInvariant(b *strings.Builder) {
+ b.WriteString("**Runtime-local paths are never deliverables.** Your working directory exists only on the machine running you. Readers do not have it, so a local path in a deliverable is dead for everyone but you.\n\n")
+ b.WriteString("- NEVER write an absolute path or a `file://` URL as a clickable link or an embedded image — not `[screenshot](/Users/you/shot.png)`, not `![chart](file:///tmp/chart.png)`. This is wrong on every surface, including when the file really does exist on your machine right now.\n")
+ b.WriteString("- To reference a code location, use inline code and never a link: `path/to/file.ts:42`.\n")
+ b.WriteString("- To deliver a file you produced, use this surface's mechanism (below). If this surface has no file mechanism, say so in words — never link the path and imply the file was delivered.\n\n")
+}
+
+// writeOutput emits the kind-specific Output section: the always-on delivery
+// invariant plus one per-surface file-delivery policy line per kind.
func writeOutput(b *strings.Builder, kind taskKind, ctx TaskContextForEnv) {
b.WriteString("## Output\n\n")
switch kind {
case kindAutopilotRunOnly:
- b.WriteString("This is a run-only autopilot task, so there may be no issue comment to post. Your final assistant output is captured automatically as the autopilot run result. Keep it concise and state the outcome.\n")
+ b.WriteString("This is a run-only autopilot task, so there may be no issue comment to post. Your final assistant output is captured automatically as the autopilot run result. Keep it concise and state the outcome.\n\n")
+ b.WriteString("**Delivering files here:** this surface is text-only — the run result carries no attachments. Describe what you produced; do not link its path.\n")
case kindQuickCreate:
b.WriteString("This is a quick-create task. There is NO existing issue to comment on. Your final stdout is captured automatically and the platform writes the user's success/failure inbox notification based on whether `multica issue create` succeeded.\n\n")
b.WriteString("- Do NOT call `multica issue comment add` — the issue you just created has no conversation context for this run.\n")
b.WriteString("- Print exactly one final line: `Created <identifier-or-id>: <title>` after a successful `multica issue create`. Use the created issue's `identifier` from JSON output when available; otherwise use its `id`. Do not assume any workspace issue prefix such as `MUL-`; workspaces can use custom prefixes.\n")
- b.WriteString("- On CLI failure, exit with the CLI error as the only output. The platform translates that into a `quick_create_failed` inbox item carrying the original prompt for the user.\n")
+ b.WriteString("- On CLI failure, exit with the CLI error as the only output. The platform translates that into a `quick_create_failed` inbox item carrying the original prompt for the user.\n\n")
+ b.WriteString("**Delivering files here:** your stdout is text-only. A file that belongs to the new issue goes on the `multica issue create` call itself via `--attachment <path>`; never put its path in the description or in your stdout line.\n")
case kindChat:
- b.WriteString("This is a chat session. Your reply is delivered directly to the chat window the user is reading.\n")
+ b.WriteString("This is a chat session. Your reply is delivered directly to the chat window the user is reading.\n\n")
+ // Two-layer channel policy (MUL-4899). This is the DELIVERY layer: any
+ // non-empty channel type means the reply leaves Multica for an external
+ // IM platform, where `attachment upload` has nothing to bind to. The
+ // orthogonal HISTORY layer (which read commands exist) is Slack-only and
+ // lives in the per-turn chat prompt — do not collapse the two.
+ if ctx.ChatChannelType != "" {
+ fmt.Fprintf(b, "**Delivering files here:** this %s conversation is text-only — Multica cannot push a file you produced back into it. `multica attachment upload` does NOT apply: it binds to a Multica chat reply, which this is not. Say in words what you produced and where it can be obtained; never upload and then write as though the file arrived, and never link its local path.\n", ChannelDisplayName(ctx.ChatChannelType))
+ } else {
+ b.WriteString("**Delivering files here:** run `multica attachment upload <local-path>` — it binds the file to your reply and it renders as an attachment card. That command is the ONLY way a file reaches the user; a path written into your reply text is not.\n")
+ }
default:
if ctx.IsSquadLeader {
b.WriteString("⚠️ **Final results MUST be delivered via `multica issue comment add`** — unless your outcome is `no_action`. When you evaluate a trigger and decide no action is needed, calling `multica squad activity <issue-id> no_action --reason \"...\"` alone is sufficient; you MUST exit without posting any comment. DO NOT post a comment that announces no_action, acknowledges another agent, or says you are exiting silently — such comments are noise. For all other outcomes (`action`, `failed`), a comment is still mandatory.\n\n")
@@ -505,8 +545,11 @@ func writeOutput(b *strings.Builder, kind taskKind, ctx TaskContextForEnv) {
b.WriteString("⚠️ **Final results MUST be delivered via `multica issue comment add`.** The user does NOT see your terminal output, assistant chat text, or run logs — only comments on the issue. A task that finishes without a result comment is invisible to the user, even if the work itself was correct.\n\n")
}
b.WriteString("**Post exactly ONE comment per run — your final result, before this turn exits.** Do NOT post progress updates, plans, or \"here's what I'm about to do next\" as comments while you work; keep all planning and progress in your own reasoning.\n\n")
- b.WriteString("Keep comments concise and natural — state the outcome, not the process (good: \"Fixed the login redirect. PR: https://...\"; bad: numbered process logs).\n")
+ b.WriteString("Keep comments concise and natural — state the outcome, not the process (good: \"Fixed the login redirect. PR: https://...\"; bad: numbered process logs).\n\n")
+ b.WriteString("**Delivering files here:** pass `--attachment <path>` to `multica issue comment add` (repeatable). The file uploads and renders on the comment; that is the only way a screenshot or artifact reaches the reader.\n")
}
+ b.WriteString("\n")
+ writeDeliveryInvariant(b)
}
// buildMetaSkillContentSlim is the post-MUL-3560 brief assembler.
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index 2a7892421b..ba340f07f6 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -321,24 +321,37 @@ func buildChatPrompt(task Task) string {
// Channel awareness (MUL-3871). When the session is backed by an IM channel,
// the agent must KNOW it is operating inside that channel — otherwise an ask
// like "what did you just talk about" sends it to read Multica instead of the
- // Slack conversation. State it explicitly, point reads at the channel (not
- // Multica), and teach the two read commands, telling the agent which to start
- // with based on where it was @mentioned. A web-only chat session gets no such
- // block — its history is the Multica chat_session the agent already resumes.
+ // channel conversation. A web-only chat session gets no such block — its
+ // history is the Multica chat_session the agent already resumes.
+ //
+ // The history half is Slack-only, and that is a real server constraint, not a
+ // simplification: `multica chat history` / `multica chat thread` are served by
+ // handlers hardwired to h.SlackHistory (handler/chat_history.go), so on a
+ // Feishu session both commands return "no channel integration". Teaching them
+ // there would send the agent down a path that always fails. A Feishu run works
+ // from the context the inbound enricher already injected, so it gets the
+ // awareness statement without the commands, and ChatInThread — which only ever
+ // picks between those two commands — does not apply to it (MUL-4899).
if task.ChatChannelType != "" {
platform := channelDisplayName(task.ChatChannelType)
- fmt.Fprintf(&b, "You are operating inside a %s conversation — not the Multica web app. This conversation and its history live in %s, NOT in Multica; never look in Multica issues or comments for it. The message below may be only what triggered you. Read the conversation with:\n", platform, platform)
- b.WriteString("- `multica chat history --output json` — the channel overview: recent top-level messages, each thread tagged with a `thread_id` and `reply_count`. It does NOT expand thread contents.\n")
- b.WriteString("- `multica chat thread [<thread_id>] --output json` — read one thread's messages; omit the id to read the thread you are in, or pass a `thread_id` from the overview to read a specific thread.\n")
- if task.ChatInThread {
- b.WriteString("You were @mentioned inside a thread: start with `multica chat thread` to read it; if you need the wider channel, run `multica chat history` and open a specific thread with `multica chat thread <thread_id>`.\n")
+ fmt.Fprintf(&b, "You are operating inside a %s conversation — not the Multica web app. This conversation and its history live in %s, NOT in Multica; never look in Multica issues or comments for it.\n", platform, platform)
+ if task.ChatChannelType == execenv.ChannelTypeSlack {
+ b.WriteString("The message below may be only what triggered you. Read the conversation with:\n")
+ b.WriteString("- `multica chat history --output json` — the channel overview: recent top-level messages, each thread tagged with a `thread_id` and `reply_count`. It does NOT expand thread contents.\n")
+ b.WriteString("- `multica chat thread [<thread_id>] --output json` — read one thread's messages; omit the id to read the thread you are in, or pass a `thread_id` from the overview to read a specific thread.\n")
+ if task.ChatInThread {
+ b.WriteString("You were @mentioned inside a thread: start with `multica chat thread` to read it; if you need the wider channel, run `multica chat history` and open a specific thread with `multica chat thread <thread_id>`.\n")
+ } else {
+ b.WriteString("You were @mentioned at the channel top level: start with `multica chat history` to see the channel, then read a specific thread's contents with `multica chat thread <thread_id>`.\n")
+ }
+ // These reads are the agent's private context-gathering; narrating them
+ // into a chat reply reads as noise (the user reported every reply being
+ // prefixed with "我先读取…"). Tell the agent to keep them out of its answer.
+ b.WriteString("Do these reads SILENTLY as an internal step — they are how you gather context, not part of your answer. Do NOT narrate them: your reply must not begin with what you are about to read or just read (no \"我先读取…\" / \"let me read the history / open the thread\"). Reply to the user with your answer only.\n")
} else {
- b.WriteString("You were @mentioned at the channel top level: start with `multica chat history` to see the channel, then read a specific thread's contents with `multica chat thread <thread_id>`.\n")
+ fmt.Fprintf(&b, "Work from the context already provided to you below — Multica has no history reader for %s, so there is no command that can fetch more of this conversation. If you genuinely need earlier context that is not here, ask the user for it rather than guessing.\n", platform)
}
- // These reads are the agent's private context-gathering; narrating them
- // into a chat reply reads as noise (the user reported every reply being
- // prefixed with "我先读取…"). Tell the agent to keep them out of its answer.
- b.WriteString("Do these reads SILENTLY as an internal step — they are how you gather context, not part of your answer. Do NOT narrate them: your reply must not begin with what you are about to read or just read (no \"我先读取…\" / \"let me read the history / open the thread\"). Reply to the user with your answer only.\n\n")
+ b.WriteString("\n")
}
if task.Agent != nil && len(task.Agent.Skills) > 0 {
refs := ExtractSlashSkills(task.ChatMessage)
@@ -393,20 +406,23 @@ func buildChatPrompt(task Task) string {
// Outbound attachments: how the agent puts an image/file INTO its reply.
// Web/mobile chat only — for IM-channel chats the reply is delivered to
// that platform, not the Multica chat UI, so this binding does not apply.
+ // This is the DELIVERY layer of the channel policy and keys off "is there a
+ // channel at all", unlike the history block above which is Slack-only; the
+ // two layers must not be collapsed into one condition (MUL-4899). The brief's
+ // `## Output` section states the same policy for every surface.
if task.ChatChannelType == "" {
b.WriteString("\nTo include a file or image you produced in your reply, run `multica attachment upload <local-path>`. The file binds to your reply automatically and appears as an attachment card below it even if you paste nothing. The command also returns a `markdown` snippet you may paste on its own line to place the item where you want it (files render as a card, images inline).\n")
+ } else {
+ fmt.Fprintf(&b, "\nThis reply is delivered to %s as text. You cannot attach a file to it: `multica attachment upload` binds to a Multica chat reply, which this is not. If you produce a file, describe it in words — never write its local path as a link, and never upload it and then write as though it arrived.\n", channelDisplayName(task.ChatChannelType))
}
return b.String()
}
-// channelDisplayName renders a chat_channel_type for prompt copy.
+// channelDisplayName renders a chat_channel_type for prompt copy. The mapping
+// itself lives in execenv so the per-turn prompt (here) and the runtime brief
+// (execenv.writeOutput) cannot drift into naming the same platform differently.
func channelDisplayName(channelType string) string {
- switch channelType {
- case "slack":
- return "Slack"
- default:
- return channelType
- }
+ return execenv.ChannelDisplayName(channelType)
}
// buildAutopilotPrompt constructs a prompt for run_only autopilot tasks.
diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.go
index d850731bea..b4393e17f7 100644
--- a/server/internal/daemon/prompt_test.go
+++ b/server/internal/daemon/prompt_test.go
@@ -3,6 +3,8 @@ package daemon
import (
"strings"
"testing"
+
+ "github.com/multica-ai/multica/server/internal/daemon/execenv"
)
// TestBuildQuickCreatePromptRules locks in the rules that govern how the
@@ -329,6 +331,101 @@ func TestBuildChatPromptChannelAwareness(t *testing.T) {
})
}
+// TestBuildChatPromptTwoLayerChannelPolicy pins the two INDEPENDENT axes of the
+// chat channel policy (MUL-4899). Collapsing them into one condition is exactly
+// the bug this matrix exists to catch:
+//
+// - delivery: `attachment upload` guidance is injected iff there is NO channel.
+// Any IM reply leaves Multica, where the upload has nothing to bind to.
+// - history: the `chat history` / `chat thread` commands are injected iff the
+// channel is Slack. Those endpoints are hardwired to h.SlackHistory
+// (handler/chat_history.go) — on Feishu they answer "no channel
+// integration", so teaching them there sends the agent down a dead path.
+//
+// Feishu is the case that proves the axes are separate: no upload AND no
+// history. A single `ChatChannelType != ""` gate cannot express it.
+func TestBuildChatPromptTwoLayerChannelPolicy(t *testing.T) {
+ // Match the IMPERATIVE, not the bare command name. An IM prompt names
+ // `multica attachment upload` on purpose — to state that it does not apply
+ // here. That negation is the useful copy (the agent knows the command exists
+ // from the brief's Available Commands; silence would leave it guessing), so
+ // asserting on the bare name would forbid the very sentence we want.
+ const uploadGuidance = "run `multica attachment upload <local-path>`"
+ const historyGuidance = "multica chat history"
+
+ cases := []struct {
+ name string
+ channelType string
+ wantUpload bool
+ wantHistory bool
+ wantPhrases []string
+ }{
+ {
+ name: "direct chat: upload, no history",
+ channelType: "",
+ wantUpload: true,
+ wantHistory: false,
+ },
+ {
+ name: "slack: no upload, has history",
+ channelType: execenv.ChannelTypeSlack,
+ wantUpload: false,
+ wantHistory: true,
+ wantPhrases: []string{"Slack", "delivered to Slack as text", "You cannot attach a file to it"},
+ },
+ {
+ name: "feishu: no upload, no history",
+ channelType: execenv.ChannelTypeFeishu,
+ wantUpload: false,
+ wantHistory: false,
+ wantPhrases: []string{
+ "Feishu/Lark",
+ "no history reader for Feishu/Lark",
+ "delivered to Feishu/Lark as text",
+ "You cannot attach a file to it",
+ },
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ out := buildChatPrompt(Task{
+ ChatSessionID: "sess-1",
+ ChatChannelType: tc.channelType,
+ ChatMessage: "hi",
+ })
+ if got := strings.Contains(out, uploadGuidance); got != tc.wantUpload {
+ t.Errorf("upload guidance present=%v, want %v\n--- output ---\n%s", got, tc.wantUpload, out)
+ }
+ if got := strings.Contains(out, historyGuidance); got != tc.wantHistory {
+ t.Errorf("history guidance present=%v, want %v\n--- output ---\n%s", got, tc.wantHistory, out)
+ }
+ for _, phrase := range tc.wantPhrases {
+ if !strings.Contains(out, phrase) {
+ t.Errorf("missing %q\n--- output ---\n%s", phrase, out)
+ }
+ }
+ })
+ }
+}
+
+// ChatInThread only ever selects between `chat history` and `chat thread`. With
+// no Feishu history reader there is nothing to select between, so the flag must
+// not leak either command into a Feishu prompt even if the server sets it.
+func TestBuildChatPromptFeishuIgnoresChatInThread(t *testing.T) {
+ out := buildChatPrompt(Task{
+ ChatSessionID: "sess-1",
+ ChatChannelType: execenv.ChannelTypeFeishu,
+ ChatInThread: true,
+ ChatMessage: "hi",
+ })
+ for _, unwanted := range []string{"multica chat thread", "multica chat history"} {
+ if strings.Contains(out, unwanted) {
+ t.Errorf("feishu prompt must not teach %q (no Feishu history reader exists)\n--- output ---\n%s", unwanted, out)
+ }
+ }
+}
+
func TestBuildChatPromptAgentIntro(t *testing.T) {
// The proactive self-introduction chat (MUL-4230) has no user message: the
// prompt must tell the agent to open the conversation itself, and must NOT
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 15a2628452..f0bcaf4eed 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -20,6 +20,7 @@ import (
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/daemonws"
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
"github.com/multica-ai/multica/server/internal/integrations/slack"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
@@ -2040,21 +2041,39 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
resp.ChatIntro = !hasUser
}
}
- // Flag a channel-backed session so the daemon makes the agent aware
- // it is operating inside Slack — read this conversation's history
- // from the channel via `multica chat history` / `multica chat thread`,
- // not from Multica (MUL-3871). Empty for a web-only chat session.
- // ChatInThread tells the agent which command to start with: the
- // latest trigger was a thread reply iff its reply-target thread
- // (last_thread_id) differs from its own message id (a top-level
- // @mention records its own ts as both).
- if binding, berr := h.Queries.GetChannelChatSessionBindingBySession(r.Context(), db.GetChannelChatSessionBindingBySessionParams{
- ChatSessionID: cs.ID,
- ChannelType: string(slack.TypeSlack),
- }); berr == nil {
- resp.ChatChannelType = string(slack.TypeSlack)
- resp.ChatInThread = binding.LastThreadID.Valid && binding.LastThreadID.String != "" &&
- binding.LastThreadID.String != binding.LastMessageID.String
+ // Flag a channel-backed session so the daemon makes the agent aware it
+ // is operating inside an IM conversation and not the Multica web app
+ // (MUL-3871). Empty for a web-only chat session.
+ //
+ // Every registered channel type is probed, not just Slack: a Feishu
+ // session writes the same channel_chat_session_binding row under
+ // channel_type='feishu' (lark/channel_store.go), so the Slack-only
+ // lookup used to report a Feishu chat as web-backed. Downstream that
+ // mis-flag made the brief inject `multica attachment upload` guidance
+ // into a conversation that cannot carry attachments at all (MUL-4899).
+ //
+ // ChatInThread stays Slack-only on purpose. It selects between
+ // `multica chat history` and `multica chat thread`, and those two
+ // endpoints are hardwired to h.SlackHistory (chat_history.go) — there
+ // is no Feishu history reader, so the flag has nothing to select
+ // between on any other channel and must not imply one exists.
+ for _, channelType := range []channel.Type{slack.TypeSlack, channel.TypeFeishu} {
+ binding, berr := h.Queries.GetChannelChatSessionBindingBySession(r.Context(), db.GetChannelChatSessionBindingBySessionParams{
+ ChatSessionID: cs.ID,
+ ChannelType: string(channelType),
+ })
+ if berr != nil {
+ continue
+ }
+ resp.ChatChannelType = string(channelType)
+ if channelType == slack.TypeSlack {
+ // The latest trigger was a thread reply iff its reply-target
+ // thread (last_thread_id) differs from its own message id (a
+ // top-level @mention records its own ts as both).
+ resp.ChatInThread = binding.LastThreadID.Valid && binding.LastThreadID.String != "" &&
+ binding.LastThreadID.String != binding.LastMessageID.String
+ }
+ break
}
if ws, err := h.Queries.GetWorkspace(r.Context(), cs.WorkspaceID); err == nil && ws.Repos != nil {
var repos []RepoData
diff --git a/server/internal/handler/daemon_claim_channel_type_test.go b/server/internal/handler/daemon_claim_channel_type_test.go
new file mode 100644
index 0000000000..a47f9e8efe
--- /dev/null
+++ b/server/internal/handler/daemon_claim_channel_type_test.go
@@ -0,0 +1,151 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+// Claim must report the chat session's real channel type for EVERY registered
+// channel, not just Slack (MUL-4899).
+//
+// The binding lookup used to hardcode channel_type='slack', so a Feishu session
+// — which writes the same channel_chat_session_binding row under
+// channel_type='feishu' (lark/channel_store.go) — came back with an empty
+// chat_channel_type, i.e. indistinguishable from a web chat. Downstream that
+// mis-flag made the daemon inject `multica attachment upload` guidance into a
+// conversation that cannot carry attachments at all.
+//
+// chat_in_thread stays Slack-only and is asserted as such: it selects between
+// `multica chat history` and `multica chat thread`, and both endpoints are
+// hardwired to h.SlackHistory (chat_history.go). There is no Feishu reader, so
+// the flag has nothing to select between and must not imply one exists.
+
+// seedChannelBinding binds sessionID to an IM channel of channelType, creating
+// the installation the binding requires. This is the row shape both the Slack
+// binder (slack/binding.go) and the Feishu store (lark/channel_store.go) write —
+// identical but for channel_type, which is exactly why the claim lookup must not
+// hardcode one value.
+func seedChannelBinding(t *testing.T, ctx context.Context, agentID, sessionID, channelType, lastMessageID, lastThreadID string) {
+ t.Helper()
+ var installationID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO channel_installation (workspace_id, agent_id, channel_type, installer_user_id)
+ VALUES ($1, $2, $3, $4)
+ RETURNING id
+ `, testWorkspaceID, agentID, channelType, testUserID).Scan(&installationID); err != nil {
+ t.Fatalf("seed %s installation: %v", channelType, err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO channel_chat_session_binding
+ (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id)
+ VALUES ($1, $2, $3, $4, 'group', $5, $6)
+ `, sessionID, installationID, channelType, "C-TEST-"+channelType, lastMessageID, lastThreadID); err != nil {
+ t.Fatalf("seed %s binding: %v", channelType, err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, sessionID)
+ testPool.Exec(ctx, `DELETE FROM channel_installation WHERE id = $1`, installationID)
+ })
+}
+
+// claimChatChannelFields claims the queued task for runtimeID and returns the
+// channel-awareness fields the daemon reads off the claim response.
+func claimChatChannelFields(t *testing.T, runtimeID string) (channelType string, inThread bool) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "claim-channel-type")
+ req = withURLParam(req, "runtimeId", runtimeID)
+
+ testHandler.ClaimTaskByRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp struct {
+ Task *struct {
+ ChatChannelType string `json:"chat_channel_type"`
+ ChatInThread bool `json:"chat_in_thread"`
+ } `json:"task"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode claim response: %v", err)
+ }
+ if resp.Task == nil {
+ t.Fatal("expected a claimed task")
+ }
+ return resp.Task.ChatChannelType, resp.Task.ChatInThread
+}
+
+func TestClaim_FeishuBoundSessionReportsChannelType(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "feishu-backed chat")
+ // last_thread_id != last_message_id: the shape that would set ChatInThread on
+ // Slack. Feishu must still report false — there is no reader to thread into.
+ seedChannelBinding(t, ctx, agentID, sessionID, "feishu", "msg-1", "thread-9")
+ insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ requeueTaskForClaim(t, ctx, sessionID)
+
+ channelType, inThread := claimChatChannelFields(t, runtimeID)
+ if channelType != "feishu" {
+ t.Errorf("chat_channel_type = %q, want %q — a Feishu session must not look like a web chat", channelType, "feishu")
+ }
+ if inThread {
+ t.Error("chat_in_thread must stay false on Feishu: it selects between two Slack-only read commands")
+ }
+}
+
+func TestClaim_SlackBoundSessionStillReportsThreadState(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "slack-backed chat")
+ seedChannelBinding(t, ctx, agentID, sessionID, "slack", "msg-1", "thread-9")
+ insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ requeueTaskForClaim(t, ctx, sessionID)
+
+ channelType, inThread := claimChatChannelFields(t, runtimeID)
+ if channelType != "slack" {
+ t.Errorf("chat_channel_type = %q, want %q", channelType, "slack")
+ }
+ if !inThread {
+ t.Error("chat_in_thread should be true when last_thread_id differs from last_message_id")
+ }
+}
+
+func TestClaim_UnboundSessionReportsNoChannelType(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "web chat")
+ insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ requeueTaskForClaim(t, ctx, sessionID)
+
+ channelType, inThread := claimChatChannelFields(t, runtimeID)
+ if channelType != "" {
+ t.Errorf("chat_channel_type = %q, want empty for a web-only session", channelType)
+ }
+ if inThread {
+ t.Error("chat_in_thread must be false for a web-only session")
+ }
+}
+
+// requeueTaskForClaim puts the session's task back in the queue so the claim
+// endpoint can hand it out (insertChannelChatTask creates it already running).
+func requeueTaskForClaim(t *testing.T, ctx context.Context, sessionID string) {
+ t.Helper()
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent_task_queue
+ SET status = 'queued', started_at = NULL, dispatched_at = NULL
+ WHERE chat_session_id = $1
+ `, sessionID); err != nil {
+ t.Fatalf("requeue task: %v", err)
+ }
+}
diff --git a/server/internal/metrics/business_events.go b/server/internal/metrics/business_events.go
index 10ee90f1bf..67edefb1fd 100644
--- a/server/internal/metrics/business_events.go
+++ b/server/internal/metrics/business_events.go
@@ -62,6 +62,7 @@ type businessEventMetrics struct {
cloudRuntimeRequestDurationSecs *prometheus.HistogramVec
feedbackSubmitted *prometheus.CounterVec
contactSalesSubmitted *prometheus.CounterVec
+ chatOutputLocalPath *prometheus.CounterVec
}
func newBusinessEventMetrics() *businessEventMetrics {
@@ -197,6 +198,10 @@ func newBusinessEventMetrics() *businessEventMetrics {
Name: "multica_contact_sales_submitted_total",
Help: "Total contact-sales inquiries submitted.",
}, metricLabels("multica_contact_sales_submitted_total")),
+ chatOutputLocalPath: prometheus.NewCounterVec(prometheus.CounterOpts{
+ Name: "multica_chat_output_local_path_total",
+ Help: "Total agent chat replies that referenced a runtime-local path, by evidence kind. Observation only — the reply is still delivered.",
+ }, metricLabels("multica_chat_output_local_path_total")),
}
}
@@ -237,6 +242,7 @@ func (e *businessEventMetrics) collectors() []prometheus.Collector {
e.cloudRuntimeRequestDurationSecs,
e.feedbackSubmitted,
e.contactSalesSubmitted,
+ e.chatOutputLocalPath,
}
}
@@ -436,6 +442,22 @@ func (m *BusinessMetrics) RecordCloudRuntimeRequest(op, status string, durationS
}
}
+// RecordChatOutputLocalPath counts a chat reply that referenced a runtime-local
+// path, by evidence kind ("file_url" / "workdir_path").
+//
+// Observation only: the reply is delivered either way. The server cannot judge
+// these paths the way the CLI lint can — it has no access to the daemon's
+// filesystem to stat them — so this measures whether the MUL-4899 prompt
+// contract is landing, and must never gate delivery on a lexical guess. The
+// label is a closed enum precisely so no fragment of the path or reply body can
+// reach Prometheus.
+func (m *BusinessMetrics) RecordChatOutputLocalPath(kind string) {
+ if m == nil || m.events == nil {
+ return
+ }
+ m.events.chatOutputLocalPath.WithLabelValues(NormalizeChatOutputLocalPathKind(kind)).Inc()
+}
+
// RecordDaemonWSMessageReceived counts an inbound daemon WS message by handler kind.
func (m *BusinessMetrics) RecordDaemonWSMessageReceived(kind string) {
if m == nil || m.events == nil {
diff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.go
index 70b8f32542..18d27aaff3 100644
--- a/server/internal/metrics/business_test.go
+++ b/server/internal/metrics/business_test.go
@@ -145,6 +145,7 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {
m.ObserveGithubPRMergeSeconds(120)
m.RecordCloudRuntimeRequest("provision", "ok", 0.5)
m.RecordDaemonWSMessageReceived("heartbeat")
+ m.RecordChatOutputLocalPath("file_url")
families, err := registry.Gather()
if err != nil {
diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.go
index 04776501ff..4bfa055c31 100644
--- a/server/internal/metrics/labels.go
+++ b/server/internal/metrics/labels.go
@@ -84,6 +84,7 @@ var businessMetricLabels = map[string][]string{
"multica_cloudruntime_request_duration_seconds": {labelOp},
"multica_feedback_submitted_total": {labelKind, labelPlatform},
"multica_contact_sales_submitted_total": {labelSource},
+ "multica_chat_output_local_path_total": {labelKind},
}
var forbiddenMetricLabels = map[string]struct{}{
diff --git a/server/internal/metrics/labels_pr3.go b/server/internal/metrics/labels_pr3.go
index 71d3753621..d1c9f783bb 100644
--- a/server/internal/metrics/labels_pr3.go
+++ b/server/internal/metrics/labels_pr3.go
@@ -206,6 +206,14 @@ var (
"other": "other",
}
+ // Evidence kinds for multica_chat_output_local_path_total (MUL-4899). A
+ // closed allowlist is what keeps the offending path out of Prometheus: the
+ // caller passes a classification, never a fragment of the reply.
+ knownChatOutputLocalPathKinds = map[string]string{
+ "file_url": "file_url",
+ "workdir_path": "workdir_path",
+ }
+
knownContactSalesSources = map[string]string{
"page": "page",
"onboarding": "onboarding",
@@ -405,3 +413,7 @@ func NormalizeFeedbackKind(value string) string {
func NormalizeContactSalesSource(value string) string {
return normalizeFromAllowList(value, knownContactSalesSources, "other")
}
+
+func NormalizeChatOutputLocalPathKind(value string) string {
+ return normalizeFromAllowList(value, knownChatOutputLocalPathKinds, "other")
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 4aa357c66c..3b08eb215d 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2778,6 +2778,11 @@ func (s *TaskService) writeChatCompletionOutcome(ctx context.Context, qtx *db.Qu
body := util.UnescapeBackslashEscapes(payload.Output)
isEmpty := strings.TrimSpace(body) == ""
+ // MUL-4899 completion-boundary observation. Measures whether the delivery
+ // contract in the runtime brief is actually landing on the chat surface.
+ // Strictly non-blocking: the reply is written either way.
+ s.observeChatOutputLocalPath(task, body)
+
// Attachments the agent uploaded during this task (tagged with task_id, not
// yet bound to any owner) are part of this reply. They make an empty-text
// turn a real image/file response — NOT a no_response — and need a row to
@@ -2850,6 +2855,39 @@ func (s *TaskService) writeChatCompletionOutcome(ctx context.Context, qtx *db.Qu
return &row, nil
}
+// observeChatOutputLocalPath records a metric when a chat reply references a
+// runtime-local path (MUL-4899). Observation only — it never mutates the reply,
+// never fails the completion, and makes no claim to have fixed anything.
+//
+// Two hard constraints shape it:
+//
+// 1. Lexical only. The path lives on the daemon's machine, so the server cannot
+// os.Stat it the way the CLI lint can. That leaves two signals it can be
+// confident about without guessing: a `file://` URL, and the task's own
+// recorded work_dir as a prefix. Anything subtler would be a guess, and a
+// guess is not worth a false signal on a dashboard.
+// 2. No path, no body text, and no fragment of either may reach the metric or
+// the log — only the classification and the task id.
+func (s *TaskService) observeChatOutputLocalPath(task db.AgentTaskQueue, body string) {
+ if s.Metrics == nil || strings.TrimSpace(body) == "" {
+ return
+ }
+ kind := ""
+ switch {
+ case strings.Contains(strings.ToLower(body), "file://"):
+ kind = "file_url"
+ case task.WorkDir.Valid && task.WorkDir.String != "" && strings.Contains(body, task.WorkDir.String):
+ kind = "workdir_path"
+ default:
+ return
+ }
+ s.Metrics.RecordChatOutputLocalPath(kind)
+ slog.Warn("chat reply references a runtime-local path",
+ "task_id", util.UUIDToString(task.ID),
+ "kind", kind,
+ )
+}
+
// FailTask marks a task as failed.
// Issue status is NOT changed here — the agent manages it via the CLI.
//