Skip to content

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

Go

fix(subscribers): notify the human an agent files sub-issues for (MUL-5483) (#6209)

Jiayuan Zhang28b6105edc6f
diff --git a/apps/mobile/data/inbox-schema.test.ts b/apps/mobile/data/inbox-schema.test.ts
new file mode 100644
index 0000000000..df2a633fad
--- /dev/null
+++ b/apps/mobile/data/inbox-schema.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from "vitest";
+import { InboxListSchema } from "./schemas";
+
+/**
+ * Tests for mobile's CLIENT-SIDE parsing of GET /api/inbox.
+ *
+ * Scope, stated precisely because the name of this file used to overclaim:
+ * these are hand-written fixtures run against `InboxListSchema`. They pin how
+ * this client REACTS to a given payload. They cannot fail when the Go server
+ * starts sending something new — nothing here executes server code.
+ *
+ * The matching server-side guarantee is structural rather than a test: every
+ * `details` map in server/cmd/server/notification_listeners.go is typed
+ * `map[string]string`, so a non-string value is a compile error there.
+ *
+ * Why both halves exist: during MUL-5483 a new inbox type was added and the
+ * mobile label map was updated so `tsc` passed — but a NUMBER went into
+ * `details.child_count`, and `details` is `z.record(z.string(), z.string())`.
+ * Because the endpoint parses an ARRAY, one bad row fails the whole parse and
+ * `listInbox` falls back to `EMPTY_INBOX_LIST`: the entire mobile inbox
+ * renders empty, not just that row. The blast radius is what these tests
+ * document; the compile-time type is what prevents it.
+ */
+describe("inbox list schema", () => {
+ it("parses a row shaped like the documented server payload", () => {
+ const serverRow = {
+ id: "inbox-1",
+ workspace_id: "ws-1",
+ recipient_type: "member",
+ recipient_id: "user-1",
+ type: "status_changed",
+ severity: "info",
+ issue_id: "issue-1",
+ title: "P0: delegated subscription rule",
+ body: "",
+ actor_type: "agent",
+ actor_id: "agent-1",
+ read: false,
+ archived: false,
+ created_at: "2026-07-30T00:00:00Z",
+ // Every value is a string. A number here drops the whole list.
+ details: { from: "in_progress", to: "in_review" },
+ };
+
+ const parsed = InboxListSchema.safeParse([serverRow]);
+ expect(parsed.success).toBe(true);
+ expect(parsed.success && parsed.data[0]?.type).toBe("status_changed");
+ expect(parsed.success && parsed.data[0]?.details?.to).toBe("in_review");
+ });
+
+ it("rejects a numeric details value", () => {
+ const badRow = {
+ id: "inbox-2",
+ recipient_type: "member",
+ type: "status_changed",
+ details: { child_count: 3 },
+ };
+
+ expect(InboxListSchema.safeParse([badRow]).success).toBe(false);
+ });
+
+ it("keeps one malformed row from emptying the entire list observable", () => {
+ // Documents the blast radius that made this a P1 rather than a cosmetic bug:
+ // the schema is an array, so a single bad row invalidates every good one.
+ const good = {
+ id: "inbox-3",
+ recipient_type: "member",
+ type: "status_changed",
+ details: { from: "todo", to: "in_review" },
+ };
+ const bad = {
+ id: "inbox-4",
+ recipient_type: "member",
+ type: "status_changed",
+ details: { child_count: 3 },
+ };
+
+ expect(InboxListSchema.safeParse([good]).success).toBe(true);
+ expect(InboxListSchema.safeParse([good, bad]).success).toBe(false);
+ });
+
+ it("renders an unknown server type instead of dropping the row", () => {
+ // Mirrors the root CLAUDE.md API-compatibility rule and mobile's own
+ // "render every inbox type, never silently drop a category" parity rule: a
+ // type this build has never heard of must still parse.
+ const future = {
+ id: "inbox-5",
+ recipient_type: "member",
+ type: "some_future_type",
+ details: { anything: "still a string" },
+ };
+
+ const parsed = InboxListSchema.safeParse([future]);
+ expect(parsed.success).toBe(true);
+ });
+});
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 631ec5e8d7..d79a1d165a 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -1641,3 +1641,68 @@ describe("ApiClient model discovery response schema", () => {
expect(result.status).toBe("completed");
});
});
+
+/**
+ * Mixed-version contract for subtree unsubscribe (MUL-5483).
+ *
+ * Web/desktop staging deploys on merge while the backend is deployed by hand,
+ * so this client routinely runs against an older server. Subtree unsubscribe
+ * must therefore be carried by its own PATH, never by a body field: Go's JSON
+ * decoder drops unknown fields, so an old server would unsubscribe only the
+ * root and still answer 200 — telling the user the whole tree was muted while
+ * every child kept notifying. An unknown path 404s, which surfaces as a
+ * rejected mutation the user can act on.
+ */
+describe("ApiClient unsubscribe endpoints", () => {
+ function stubOK() {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+ }
+
+ function requestOf(fetchMock: ReturnType<typeof vi.fn>) {
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
+ return { url, body: JSON.parse(String(init.body ?? "{}")) as Record<string, unknown> };
+ }
+
+ it("sends the subtree variant to its own endpoint", async () => {
+ const fetchMock = stubOK();
+
+ await new ApiClient("https://api.example.test")
+ .unsubscribeFromIssueSubtree("issue-1", "user-1", "member");
+
+ const { url, body } = requestOf(fetchMock);
+ expect(url).toBe("https://api.example.test/api/issues/issue-1/unsubscribe/subtree");
+ expect(body).toEqual({ user_id: "user-1", user_type: "member" });
+ });
+
+ it("never encodes subtree as a body field on the shared endpoint", async () => {
+ const fetchMock = stubOK();
+
+ await new ApiClient("https://api.example.test")
+ .unsubscribeFromIssue("issue-1", "user-1", "member");
+
+ const { url, body } = requestOf(fetchMock);
+ expect(url).toBe("https://api.example.test/api/issues/issue-1/unsubscribe");
+ // A `subtree` key here would be silently ignored by an older backend,
+ // which is the exact silent-success failure this split exists to prevent.
+ expect(body).not.toHaveProperty("subtree");
+ });
+
+ it("rejects when the backend does not know the subtree route", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ error: "not found" }), {
+ status: 404,
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ );
+
+ await expect(
+ new ApiClient("https://api.example.test")
+ .unsubscribeFromIssueSubtree("issue-1", "user-1", "member"),
+ ).rejects.toBeInstanceOf(ApiError);
+ });
+});
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index da4ad9502e..ce4ba2c99a 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -410,6 +410,20 @@ export class PreviewUnsupportedError extends Error {
*/
export const CHAT_DRAFT_RESTORE_CAPABILITY = "chat-draft-restore-v1";
+/**
+ * Body shared by both unsubscribe endpoints: an omitted target means "the
+ * caller", which the server resolves from the request actor.
+ */
+function subscriberTarget(
+ userId?: string,
+ userType?: string,
+): Record<string, string> {
+ const body: Record<string, string> = {};
+ if (userId) body.user_id = userId;
+ if (userType) body.user_type = userType;
+ return body;
+}
+
export class ApiClient {
private baseUrl: string;
private token: string | null = null;
@@ -1060,13 +1074,37 @@ export class ApiClient {
});
}
- async unsubscribeFromIssue(issueId: string, userId?: string, userType?: string): Promise<void> {
- const body: Record<string, string> = {};
- if (userId) body.user_id = userId;
- if (userType) body.user_type = userType;
+ async unsubscribeFromIssue(
+ issueId: string,
+ userId?: string,
+ userType?: string,
+ ): Promise<void> {
await this.fetch(`/api/issues/${issueId}/unsubscribe`, {
method: "POST",
- body: JSON.stringify(body),
+ body: JSON.stringify(subscriberTarget(userId, userType)),
+ });
+ }
+
+ /**
+ * Leaves this issue and every descendant, and keeps future children of the
+ * tree from re-subscribing the user — the escape hatch for an agent-built
+ * tree that keeps growing (MUL-5483).
+ *
+ * Deliberately its own endpoint rather than a `subtree` flag on
+ * `unsubscribeFromIssue`. Web/desktop staging ships on merge while the
+ * backend is deployed by hand, so this client regularly runs against an
+ * older server; one that predates the feature would ignore an unknown body
+ * field, unsubscribe only the root, and still answer 200. A distinct path
+ * 404s there, which surfaces as a failed mutation instead of a silent lie.
+ */
+ async unsubscribeFromIssueSubtree(
+ issueId: string,
+ userId?: string,
+ userType?: string,
+ ): Promise<void> {
+ await this.fetch(`/api/issues/${issueId}/unsubscribe/subtree`, {
+ method: "POST",
+ body: JSON.stringify(subscriberTarget(userId, userType)),
});
}
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index d42333a74d..5862af2aa3 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -1131,3 +1131,27 @@ export function useToggleIssueSubscriber(issueId: string) {
},
});
}
+
+/**
+ * Leave an issue AND its whole sub-tree (MUL-5483). Not optimistic: it writes
+ * to an unknown number of other issues' subscriber lists, so there is nothing
+ * determinate to patch — invalidate every subscriber query instead and let the
+ * server be the source of truth.
+ */
+export function useUnsubscribeFromIssueSubtree(issueId: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: async ({
+ userId,
+ userType,
+ }: {
+ userId: string;
+ userType: "member" | "agent";
+ }) => {
+ await api.unsubscribeFromIssueSubtree(issueId, userId, userType);
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: issueKeys.subscribersAll() });
+ },
+ });
+}
diff --git a/packages/core/types/subscriber.ts b/packages/core/types/subscriber.ts
index 09ab40eaf4..92184113be 100644
--- a/packages/core/types/subscriber.ts
+++ b/packages/core/types/subscriber.ts
@@ -1,7 +1,26 @@
+/**
+ * Why someone is subscribed to an issue. `delegated` means an agent created
+ * the issue on this member's behalf (MUL-5483) — they never touched it
+ * themselves, so the UI has to explain the subscription, and delivery for it
+ * is narrower than for the direct reasons.
+ *
+ * Server-driven and open-ended by design: the API parses `reason` as a plain
+ * string, so treat an unrecognized value as a direct subscription rather than
+ * dropping the row.
+ */
+export type IssueSubscriberReason =
+ | "creator"
+ | "assignee"
+ | "commenter"
+ | "mentioned"
+ | "manual"
+ | "autopilot"
+ | "delegated";
+
export interface IssueSubscriber {
issue_id: string;
user_type: "member" | "agent";
user_id: string;
- reason: "creator" | "assignee" | "commenter" | "mentioned" | "manual";
+ reason: IssueSubscriberReason;
created_at: string;
}
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index bb92b3261c..8bfd27b41a 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -37,6 +37,12 @@ import {
TooltipTrigger,
TooltipContent,
} from "@multica/ui/components/ui/tooltip";
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+} from "@multica/ui/components/ui/dropdown-menu";
import { Popover, PopoverTrigger, PopoverContent } from "@multica/ui/components/ui/popover";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@multica/ui/components/ui/dialog";
import { Checkbox } from "@multica/ui/components/ui/checkbox";
@@ -1461,7 +1467,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
} = useIssueReactions(id, user?.id);
const {
- subscribers, isSubscribed, toggleSubscribe: handleToggleSubscribe, toggleSubscriber,
+ subscribers, isSubscribed, subscriptionReason,
+ toggleSubscribe: handleToggleSubscribe, toggleSubscriber,
+ unsubscribeFromSubtree: handleUnsubscribeSubtree,
} = useIssueSubscribers(id, user?.id);
// Token usage
@@ -2617,13 +2625,47 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
<h2 className="text-title-sm font-semibold">{t(($) => $.detail.activity_section)}</h2>
</div>
<div className="flex items-center gap-2">
- <button
- type="button"
- onClick={handleToggleSubscribe}
- className="text-caption text-muted-foreground hover:text-foreground transition-colors"
- >
- {isSubscribed ? t(($) => $.detail.unsubscribe) : t(($) => $.detail.subscribe)}
- </button>
+ {/* A delegated subscription is one the user never opted into
+ by hand — their agent created this issue for them. Saying
+ so is what keeps it from reading as the product quietly
+ adding them to things (MUL-5483). */}
+ {isSubscribed && subscriptionReason === "delegated" && (
+ <Tooltip>
+ {/* Quiet surface, not plain body text: this is metadata
+ explaining a state, and must not read as a second
+ action sitting next to Unsubscribe. Uses the shared
+ caption role rather than an ad-hoc size (MUL-5451). */}
+ <TooltipTrigger className="cursor-default rounded-full bg-muted px-2 py-0.5 text-caption text-muted-foreground">
+ {t(($) => $.detail.delegated_subscription_badge)}
+ </TooltipTrigger>
+ <TooltipContent side="top" className="max-w-64">
+ {t(($) => $.detail.delegated_subscription_hint)}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ {isSubscribed ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger className="text-caption text-muted-foreground hover:text-foreground transition-colors">
+ {t(($) => $.detail.unsubscribe)}
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onSelect={handleToggleSubscribe}>
+ {t(($) => $.detail.unsubscribe_this)}
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={handleUnsubscribeSubtree}>
+ {t(($) => $.detail.unsubscribe_subtree)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <button
+ type="button"
+ onClick={handleToggleSubscribe}
+ className="text-caption text-muted-foreground hover:text-foreground transition-colors"
+ >
+ {t(($) => $.detail.subscribe)}
+ </button>
+ )}
<Popover>
<PopoverTrigger className="cursor-pointer hover:opacity-80 transition-opacity">
{subscribers.length > 0 ? (
diff --git a/packages/views/issues/hooks/use-issue-subscribers.test.tsx b/packages/views/issues/hooks/use-issue-subscribers.test.tsx
new file mode 100644
index 0000000000..b997ba9efc
--- /dev/null
+++ b/packages/views/issues/hooks/use-issue-subscribers.test.tsx
@@ -0,0 +1,137 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { setApiInstance } from "@multica/core/api";
+import { ApiError } from "@multica/core/api/client";
+import type { ApiClient } from "@multica/core/api/client";
+
+const toastError = vi.fn();
+vi.mock("sonner", () => ({ toast: { error: (msg: string) => toastError(msg) } }));
+
+// Return the key path so an assertion can tell the two failure messages apart
+// without depending on the English copy.
+vi.mock("../../i18n", () => ({
+ useT: () => ({
+ t: (sel: (d: Record<string, Record<string, string>>) => string) =>
+ sel(
+ new Proxy(
+ {},
+ {
+ get: (_t, section: string) =>
+ new Proxy(
+ {},
+ { get: (_s, key: string) => `${section}.${key}` },
+ ),
+ },
+ ) as Record<string, Record<string, string>>,
+ ),
+ }),
+}));
+
+vi.mock("@multica/core/realtime", () => ({
+ useWSEvent: () => undefined,
+ useWSReconnect: () => undefined,
+}));
+
+import { useIssueSubscribers } from "./use-issue-subscribers";
+
+function wrapper(queryClient: QueryClient) {
+ return function Wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ };
+}
+
+function renderSubscribers() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ return renderHook(() => useIssueSubscribers("issue-1", "user-1"), {
+ wrapper: wrapper(queryClient),
+ });
+}
+
+/**
+ * Subtree unsubscribe is not optimistic — nothing on screen changes when it
+ * fails — so without an explicit message a failure is indistinguishable from a
+ * dead button. The 404 case specifically means the backend predates the
+ * feature (web/desktop staging deploys on merge, backend by hand), which the
+ * user can only wait out, so it must not read as a generic error
+ * (MUL-5483 review round 7).
+ */
+describe("useIssueSubscribers subtree unsubscribe failures", () => {
+ afterEach(() => {
+ cleanup();
+ toastError.mockClear();
+ });
+
+ it("tells the user when the backend has no subtree route yet", async () => {
+ setApiInstance({
+ listIssueSubscribers: async () => [],
+ unsubscribeFromIssueSubtree: async () => {
+ // chi answers an unknown route with plain text, so parseErrorBody
+ // leaves body undefined. That is the deploy-skew signature.
+ throw new ApiError("not found", 404, "Not Found");
+ },
+ } as unknown as ApiClient);
+
+ const { result } = renderSubscribers();
+ result.current.unsubscribeFromSubtree();
+
+ await waitFor(() => expect(toastError).toHaveBeenCalledTimes(1));
+ expect(toastError).toHaveBeenCalledWith(
+ "detail.unsubscribe_subtree_unsupported",
+ );
+ });
+
+ it("does not blame deploy skew for a structured 404 from a current backend", async () => {
+ setApiInstance({
+ listIssueSubscribers: async () => [],
+ unsubscribeFromIssueSubtree: async () => {
+ // The route exists; the ISSUE is gone or not visible. Telling this user
+ // to wait for the next deploy would be wrong advice.
+ throw new ApiError("issue not found", 404, "Not Found", {
+ error: "issue not found",
+ });
+ },
+ } as unknown as ApiClient);
+
+ const { result } = renderSubscribers();
+ result.current.unsubscribeFromSubtree();
+
+ await waitFor(() => expect(toastError).toHaveBeenCalledTimes(1));
+ expect(toastError).toHaveBeenCalledWith("detail.unsubscribe_subtree_failed");
+ });
+
+ it("falls back to a generic failure for any other error", async () => {
+ setApiInstance({
+ listIssueSubscribers: async () => [],
+ unsubscribeFromIssueSubtree: async () => {
+ throw new ApiError("boom", 500, "Internal Server Error");
+ },
+ } as unknown as ApiClient);
+
+ const { result } = renderSubscribers();
+ result.current.unsubscribeFromSubtree();
+
+ await waitFor(() => expect(toastError).toHaveBeenCalledTimes(1));
+ expect(toastError).toHaveBeenCalledWith("detail.unsubscribe_subtree_failed");
+ });
+
+ it("stays silent when the unsubscribe succeeds", async () => {
+ setApiInstance({
+ listIssueSubscribers: async () => [],
+ unsubscribeFromIssueSubtree: async () => undefined,
+ } as unknown as ApiClient);
+
+ const { result } = renderSubscribers();
+ result.current.unsubscribeFromSubtree();
+
+ await waitFor(() => expect(toastError).not.toHaveBeenCalled());
+ });
+});
diff --git a/packages/views/issues/hooks/use-issue-subscribers.ts b/packages/views/issues/hooks/use-issue-subscribers.ts
index 5cf572d3d5..57342a103d 100644
--- a/packages/views/issues/hooks/use-issue-subscribers.ts
+++ b/packages/views/issues/hooks/use-issue-subscribers.ts
@@ -8,16 +8,43 @@ import type {
SubscriberRemovedPayload,
} from "@multica/core/types";
import { issueSubscribersOptions, issueKeys } from "@multica/core/issues/queries";
-import { useToggleIssueSubscriber } from "@multica/core/issues/mutations";
+import {
+ useToggleIssueSubscriber,
+ useUnsubscribeFromIssueSubtree,
+} from "@multica/core/issues/mutations";
import { useWSEvent, useWSReconnect } from "@multica/core/realtime";
+// Imported from the defining module, not the "@multica/core/api" barrel: the
+// barrel drags the client singleton and ws-client into the module graph of
+// every consumer of this hook, which measurably slowed test startup and tipped
+// an unrelated timing-sensitive suite over its waitFor budget.
+import { ApiError } from "@multica/core/api/client";
+import { toast } from "sonner";
+import { useT } from "../../i18n";
+
+/**
+ * True only for the deploy-skew 404: a backend that predates
+ * /unsubscribe/subtree, where chi answers an unknown ROUTE with plain text.
+ *
+ * Not every 404 means that. The same endpoint on a current backend returns a
+ * structured JSON 404 when the issue is deleted or not visible, and telling
+ * that user to "wait for the next update" is wrong advice. ApiError.body is the
+ * discriminator: parseErrorBody leaves it undefined when the response was not
+ * JSON, and populated when the server sent a real error document
+ * (MUL-5483 review round 8).
+ */
+function isMissingRouteError(err: unknown): boolean {
+ return err instanceof ApiError && err.status === 404 && err.body === undefined;
+}
export function useIssueSubscribers(issueId: string, userId?: string) {
const qc = useQueryClient();
+ const { t } = useT("issues");
const { data: subscribers = [], isLoading: loading } = useQuery(
issueSubscribersOptions(issueId),
);
const toggleMutation = useToggleIssueSubscriber(issueId);
+ const subtreeMutation = useUnsubscribeFromIssueSubtree(issueId);
// Reconnect recovery
useWSReconnect(
@@ -38,13 +65,22 @@ export function useIssueSubscribers(issueId: string, userId?: string) {
issueKeys.subscribers(issueId),
(old) => {
if (!old) return old;
- if (
- old.some(
- (s) =>
- s.user_id === p.user_id && s.user_type === p.user_type,
- )
- )
- return old;
+ const existing = old.find(
+ (s) => s.user_id === p.user_id && s.user_type === p.user_type,
+ );
+ // The server re-broadcasts for an existing subscriber only when the
+ // reason changed — a delegate who got assigned, mentioned, or
+ // commented is upgraded out of the reduced tier. Patch it rather
+ // than bailing, or the "Watching via agent" badge keeps claiming a
+ // delegation that no longer applies (MUL-5483).
+ if (existing) {
+ if (existing.reason === p.reason) return old;
+ return old.map((s) =>
+ s.user_id === p.user_id && s.user_type === p.user_type
+ ? { ...s, reason: p.reason as IssueSubscriber["reason"] }
+ : s,
+ );
+ }
return [
...old,
{
@@ -83,9 +119,14 @@ export function useIssueSubscribers(issueId: string, userId?: string) {
// --- Mutations ---
- const isSubscribed = subscribers.some(
+ const ownSubscription = subscribers.find(
(s) => s.user_type === "member" && s.user_id === userId,
);
+ const isSubscribed = !!ownSubscription;
+ // Why the current user is watching. Drives the "your agent created this on
+ // your behalf" explanation — a subscription nobody remembers opting into
+ // reads as the product being creepy unless it says why (MUL-5483).
+ const subscriptionReason = ownSubscription?.reason;
const toggleSubscriber = useCallback(
async (
@@ -106,11 +147,31 @@ export function useIssueSubscribers(issueId: string, userId?: string) {
if (userId) toggleSubscriber(userId, "member", isSubscribed);
}, [userId, isSubscribed, toggleSubscriber]);
+ // Subscription state is server-owned and the row simply does not change on
+ // failure, so nothing on screen moves. Without an explicit message the user
+ // reads a failed unsubscribe as a no-op button and tries again forever.
+ const unsubscribeFromSubtree = useCallback(() => {
+ if (!userId) return;
+ subtreeMutation.mutate(
+ { userId, userType: "member" },
+ {
+ onError: (err) =>
+ toast.error(
+ isMissingRouteError(err)
+ ? t(($) => $.detail.unsubscribe_subtree_unsupported)
+ : t(($) => $.detail.unsubscribe_subtree_failed),
+ ),
+ },
+ );
+ }, [userId, subtreeMutation, t]);
+
return {
subscribers,
loading,
isSubscribed,
+ subscriptionReason,
toggleSubscribe,
toggleSubscriber,
+ unsubscribeFromSubtree,
};
}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 3219855bbd..1ccf84ae5c 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -303,6 +303,12 @@
"activity_section": "Activity",
"subscribe": "Subscribe",
"unsubscribe": "Unsubscribe",
+ "delegated_subscription_badge": "Watching via agent",
+ "delegated_subscription_hint": "Your agent created this issue on your behalf, so you're subscribed to it. You'll get notified when it needs review, finishes, or gets stuck.",
+ "unsubscribe_this": "Unsubscribe from this issue",
+ "unsubscribe_subtree": "Unsubscribe from this issue and its sub-issues",
+ "unsubscribe_subtree_failed": "Could not unsubscribe from the sub-issues. Please try again.",
+ "unsubscribe_subtree_unsupported": "This workspace's server does not support unsubscribing from sub-issues yet. Try again after the next update.",
"no_subscribers_results": "No results found",
"change_subscribers_placeholder": "Change subscribers...",
"members_group": "Members",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index be2f6241b7..293b2037ed 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -300,6 +300,12 @@
"activity_section": "アクティビティ",
"subscribe": "購読",
"unsubscribe": "購読解除",
+ "delegated_subscription_badge": "エージェント経由で購読中",
+ "delegated_subscription_hint": "エージェントがあなたに代わってこの課題を作成したため、購読しています。レビュー待ち・完了・ブロック時に通知されます。",
+ "unsubscribe_this": "この課題の購読を解除",
+ "unsubscribe_subtree": "この課題とサブ課題の購読を解除",
+ "unsubscribe_subtree_failed": "サブ課題の購読解除に失敗しました。もう一度お試しください。",
+ "unsubscribe_subtree_unsupported": "現在のサーバーはサブ課題の購読解除にまだ対応していません。次回の更新後にお試しください。",
"no_subscribers_results": "結果が見つかりません",
"change_subscribers_placeholder": "購読者を変更...",
"members_group": "メンバー",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 48ae3896d2..701a5212dd 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -300,6 +300,12 @@
"activity_section": "활동",
"subscribe": "구독",
"unsubscribe": "구독 해제",
+ "delegated_subscription_badge": "에이전트를 통해 구독 중",
+ "delegated_subscription_hint": "에이전트가 회원님을 대신해 이 이슈를 만들었기 때문에 구독 중입니다. 검토 필요, 완료, 차단 시 알림을 받습니다.",
+ "unsubscribe_this": "이 이슈 구독 해제",
+ "unsubscribe_subtree": "이 이슈와 하위 이슈 구독 해제",
+ "unsubscribe_subtree_failed": "하위 이슈 구독 해제에 실패했습니다. 다시 시도해 주세요.",
+ "unsubscribe_subtree_unsupported": "현재 서버는 아직 하위 이슈 구독 해제를 지원하지 않습니다. 다음 업데이트 후 다시 시도해 주세요.",
"no_subscribers_results": "결과를 찾을 수 없습니다",
"change_subscribers_placeholder": "구독자 변경...",
"members_group": "멤버",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index cf353de8b3..d4b5d569a7 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -300,6 +300,12 @@
"activity_section": "动态",
"subscribe": "订阅",
"unsubscribe": "取消订阅",
+ "delegated_subscription_badge": "由智能体代你关注",
+ "delegated_subscription_hint": "你的智能体代你创建了这个 issue,因此你在关注它。待评审、完成或受阻时会通知你。",
+ "unsubscribe_this": "取消订阅此 issue",
+ "unsubscribe_subtree": "取消订阅此 issue 及其子 issue",
+ "unsubscribe_subtree_failed": "取消订阅子 issue 失败,请重试。",
+ "unsubscribe_subtree_unsupported": "当前服务端还不支持取消订阅子 issue,请在下次更新后再试。",
"no_subscribers_results": "未找到结果",
"change_subscribers_placeholder": "更改订阅者...",
"members_group": "成员",
diff --git a/server/cmd/server/delegated_subscriber_concurrency_test.go b/server/cmd/server/delegated_subscriber_concurrency_test.go
new file mode 100644
index 0000000000..80627b756a
--- /dev/null
+++ b/server/cmd/server/delegated_subscriber_concurrency_test.go
@@ -0,0 +1,200 @@
+package main
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Concurrency regressions for MUL-5483 review round 7.
+//
+// The earlier cut checked membership and ancestor opt-out in their own round
+// trips and then inserted in another, so a competing request could invalidate
+// either answer in between. These tests drive that window deliberately: a
+// competing transaction takes the shared (workspace, user) lock and performs
+// its write, and the delegated rule is fired while that transaction is still
+// OPEN. Each test asserts two things — that the rule blocks rather than reading
+// stale state, and that it reaches the correct decision once released.
+//
+// The two races are closed by different mechanisms, and the tests were checked
+// against each one individually:
+//
+// - the subtree opt-out race needs the ADVISORY LOCK. Its tombstone can land
+// on an issue the rule never reads, and the child being subscribed did not
+// exist when the opt-out was written, so no row lock reaches it. Removing
+// LockSubscriberWrites makes TestDelegatedSubscribe_BlocksOnConcurrentSubtreeOptOut
+// fail — the rule reads the pre-tombstone snapshot and subscribes.
+// - the member revoke race is closed by the FOR SHARE in AddDelegatedSubscriber,
+// which is why its test still passes with the advisory lock removed. The
+// lock is what additionally orders the rule against revoke's subscription
+// cleanup, so a row inserted just before a revoke cannot outlive it.
+
+// blockedTx holds the serialization lock and whatever write the scenario needs,
+// without committing. Call release() to commit and let the waiter through.
+func blockedTx(t *testing.T, userID string, write func(*db.Queries) error) (release func()) {
+ t.Helper()
+ ctx := context.Background()
+
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin competing tx: %v", err)
+ }
+ committed := false
+ t.Cleanup(func() {
+ if !committed {
+ tx.Rollback(context.Background())
+ }
+ })
+
+ qtx := db.New(testPool).WithTx(tx)
+ if err := qtx.LockSubscriberWrites(ctx, db.LockSubscriberWritesParams{
+ WorkspaceID: util.MustParseUUID(testWorkspaceID),
+ UserID: util.MustParseUUID(userID),
+ }); err != nil {
+ t.Fatalf("competing tx lock: %v", err)
+ }
+ if err := write(qtx); err != nil {
+ t.Fatalf("competing tx write: %v", err)
+ }
+
+ return func() {
+ if err := tx.Commit(context.Background()); err != nil {
+ t.Fatalf("commit competing tx: %v", err)
+ }
+ committed = true
+ }
+}
+
+// fireDelegatedRule runs the listener chain in the background and reports when
+// it finished, so a test can assert on whether it is blocked.
+func fireDelegatedRule(bus *events.Bus, issueID, agentID string) <-chan struct{} {
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ publishAgentIssueCreated(bus, issueID, agentID)
+ }()
+ return done
+}
+
+func assertBlocked(t *testing.T, done <-chan struct{}, what string) {
+ t.Helper()
+ select {
+ case <-done:
+ t.Fatalf("%s completed while a competing transaction still held the serialization lock: "+
+ "the eligibility check read a snapshot that was about to become false", what)
+ case <-time.After(400 * time.Millisecond):
+ }
+}
+
+func assertFinishes(t *testing.T, done <-chan struct{}, what string) {
+ t.Helper()
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ t.Fatalf("%s never completed after the competing transaction committed", what)
+ }
+}
+
+// TestDelegatedSubscribe_BlocksOnConcurrentSubtreeOptOut is the escape-hatch
+// race. A user unsubscribes from a tree while an agent is still decomposing it;
+// the child the agent files next did not exist when the tombstone was written,
+// so there is no row a row-lock could have protected. If the rule reads the
+// pre-tombstone snapshot, the user silently becomes a watcher again on exactly
+// the tree they just left.
+func TestDelegatedSubscribe_BlocksOnConcurrentSubtreeOptOut(t *testing.T) {
+ queries := db.New(testPool)
+ bus := events.New()
+ registerSubscriberListeners(bus, testPool)
+
+ agentID, runtimeID := firstFixtureAgent(t)
+ parentID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() { cleanupTestIssue(t, parentID) })
+
+ task := createAgentTaskWithOriginator(t, agentID, runtimeID, util.MustParseUUID(testUserID))
+
+ // The user leaves the whole tree. Still uncommitted.
+ release := blockedTx(t, testUserID, func(qtx *db.Queries) error {
+ _, err := qtx.UnsubscribeFromIssueSubtree(context.Background(), db.UnsubscribeFromIssueSubtreeParams{
+ ID: util.MustParseUUID(parentID),
+ UserType: "member",
+ UserID: util.MustParseUUID(testUserID),
+ })
+ return err
+ })
+
+ // The agent files a NEW child under that tree, after the opt-out was
+ // written but before it committed.
+ childID := createAgentOriginIssue(t, agentID, "agent_create", task, util.MustParseUUID(parentID))
+
+ done := fireDelegatedRule(bus, childID, agentID)
+ assertBlocked(t, done, "delegated subscribe")
+
+ release()
+ assertFinishes(t, done, "delegated subscribe")
+
+ if isSubscribed(t, queries, childID, "member", testUserID) {
+ t.Fatal("a child filed during a concurrent subtree unsubscribe must not resurrect the subscription: " +
+ "this is the escape hatch the feature depends on")
+ }
+}
+
+// TestDelegatedSubscribe_BlocksOnConcurrentMemberRevoke is the membership race.
+// Round 6 moved the membership check to write time, but the check and the
+// insert were still two statements, so a revoke landing between them produced
+// exactly the ghost subscriber the check existed to prevent.
+func TestDelegatedSubscribe_BlocksOnConcurrentMemberRevoke(t *testing.T) {
+ queries := db.New(testPool)
+ bus := events.New()
+ registerSubscriberListeners(bus, testPool)
+
+ const email = "[email protected]"
+ cleanupTestUser(t, email)
+ userID := createTestUser(t, email)
+ t.Cleanup(func() { cleanupTestUser(t, email) })
+ addWorkspaceMember(t, userID)
+
+ agentID, runtimeID := firstFixtureAgent(t)
+ task := createAgentTaskWithOriginator(t, agentID, runtimeID, util.MustParseUUID(userID))
+
+ // The member is being revoked. Still uncommitted.
+ release := blockedTx(t, userID, func(qtx *db.Queries) error {
+ return revokeMemberInTx(qtx, userID)
+ })
+
+ issueID := createAgentOriginIssue(t, agentID, "agent_create", task, util.MustParseUUID(createTestIssue(t, testWorkspaceID, testUserID)))
+
+ done := fireDelegatedRule(bus, issueID, agentID)
+ assertBlocked(t, done, "delegated subscribe")
+
+ release()
+ assertFinishes(t, done, "delegated subscribe")
+
+ if isSubscribed(t, queries, issueID, "member", userID) {
+ t.Fatal("a member revoked concurrently with the delegated rule must not end up subscribed")
+ }
+}
+
+// revokeMemberInTx mirrors what revokeAndRemoveMember does to subscriber state,
+// through the transaction the competing writer holds, so the member row the
+// rule's FOR SHARE would observe is deleted but not yet committed.
+func revokeMemberInTx(qtx *db.Queries, userID string) error {
+ ctx := context.Background()
+ if err := qtx.DeleteSubscriptionsByMember(ctx, db.DeleteSubscriptionsByMemberParams{
+ WorkspaceID: util.MustParseUUID(testWorkspaceID),
+ UserID: util.MustParseUUID(userID),
+ }); err != nil {
+ return err
+ }
+ member, err := qtx.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: util.MustParseUUID(userID),
+ WorkspaceID: util.MustParseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ return err
+ }
+ return qtx.DeleteMember(ctx, member.ID)
+}
diff --git a/server/cmd/server/delegated_subscriber_membership_test.go b/server/cmd/server/delegated_subscriber_membership_test.go
new file mode 100644
index 0000000000..3829396c6d
--- /dev/null
+++ b/server/cmd/server/delegated_subscriber_membership_test.go
@@ -0,0 +1,107 @@
+package main
+
+import (
+ "context"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// addWorkspaceMember joins a user to the test workspace and returns a function
+// that revokes that membership, modelling the workspace_revoke path without
+// dragging its runtime teardown into a subscriber test.
+func addWorkspaceMember(t *testing.T, userID string) (revoke func()) {
+ t.Helper()
+ ctx := context.Background()
+ if _, err := testPool.Exec(ctx,
+ `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
+ testWorkspaceID, userID,
+ ); err != nil {
+ t.Fatalf("add workspace member: %v", err)
+ }
+ revoked := false
+ revoke = func() {
+ if revoked {
+ return
+ }
+ revoked = true
+ if _, err := testPool.Exec(context.Background(),
+ `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`,
+ testWorkspaceID, userID,
+ ); err != nil {
+ t.Fatalf("revoke workspace member: %v", err)
+ }
+ }
+ t.Cleanup(revoke)
+ return revoke
+}
+
+// TestDelegatedSubscribe_SkipsOriginatorRemovedFromWorkspace covers review
+// round 6 finding 2.
+//
+// originator_user_id is stamped when the task is QUEUED and never revisited.
+// GetAgentTaskInWorkspace proves the task's agent still belongs to the
+// workspace, which is a different claim from "the human does". A member can be
+// revoked while their tasks keep running on a shared runtime, and every child
+// those tasks file afterwards would write a subscriber row for a non-member:
+// a ghost watcher accumulating inbox rows, and restored history if they ever
+// rejoin. Membership has to be re-checked at write time.
+func TestDelegatedSubscribe_SkipsOriginatorRemovedFromWorkspace(t *testing.T) {
+ queries := db.New(testPool)
+ bus := events.New()
+ registerSubscriberListeners(bus, testPool)
+
+ const email = "[email protected]"
+ cleanupTestUser(t, email)
+ userID := createTestUser(t, email)
+ t.Cleanup(func() { cleanupTestUser(t, email) })
+
+ // Member at the moment the run is queued — this is what stamps the task.
+ revoke := addWorkspaceMember(t, userID)
+
+ agentID, runtimeID := firstFixtureAgent(t)
+ task := createAgentTaskWithOriginator(t, agentID, runtimeID, util.MustParseUUID(userID))
+
+ // Revoked mid-run. The task survives and keeps decomposing.
+ revoke()
+
+ issueID := createAgentOriginIssue(t, agentID, "agent_create", task, pgtype.UUID{})
+ publishAgentIssueCreated(bus, issueID, agentID)
+
+ if isSubscribed(t, queries, issueID, "member", userID) {
+ t.Fatal("a revoked member must not be auto-subscribed by the delegated rule: " +
+ "the subscription is a ghost that keeps accruing inbox rows outside the workspace's membership boundary")
+ }
+}
+
+// TestDelegatedSubscribe_SubscribesOriginatorStillInWorkspace is the positive
+// control for the test above. Without it, a membership check that rejected
+// EVERYONE would still pass the negative case.
+func TestDelegatedSubscribe_SubscribesOriginatorStillInWorkspace(t *testing.T) {
+ queries := db.New(testPool)
+ bus := events.New()
+ registerSubscriberListeners(bus, testPool)
+
+ const email = "[email protected]"
+ cleanupTestUser(t, email)
+ userID := createTestUser(t, email)
+ t.Cleanup(func() { cleanupTestUser(t, email) })
+
+ addWorkspaceMember(t, userID)
+
+ agentID, runtimeID := firstFixtureAgent(t)
+ task := createAgentTaskWithOriginator(t, agentID, runtimeID, util.MustParseUUID(userID))
+ issueID := createAgentOriginIssue(t, agentID, "agent_create", task, pgtype.UUID{})
+
+ publishAgentIssueCreated(bus, issueID, agentID)
+
+ if !isSubscribed(t, queries, issueID, "member", userID) {
+ t.Fatal("an originator who is still a workspace member must be subscribed")
+ }
+ if got := subscriberReason(t, queries, issueID, "member", userID); got != "delegated" {
+ t.Fatalf("reason = %q, want delegated", got)
+ }
+}
diff --git a/server/cmd/server/delegated_subscriber_review_test.go b/server/cmd/server/delegated_subscriber_review_test.go
new file mode 100644
index 0000000000..8b9c99bc18
--- /dev/null
+++ b/server/cmd/server/delegated_subscriber_review_test.go
@@ -0,0 +1,232 @@
+package main
+
+import (
+ "context"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Regressions for the MUL-5483 code review. Each test pins one behavior that
+// the first cut got wrong.
+
+// countSubscriberAddedEvents subscribes to the bus and counts subscriber:added
+// broadcasts for a given issue, so a test can assert on what CLIENTS were told
+// rather than only on what the DB holds.
+func countSubscriberAddedEvents(bus *events.Bus, issueID string) *int {
+ n := 0
+ bus.Subscribe(protocol.EventSubscriberAdded, func(e events.Event) {
+ p, ok := e.Payload.(map[string]any)
+ if !ok {
+ return
+ }
+ if id, _ := p["issue_id"].(string); id == issueID {
+ n++
+ }
+ })
+ return &n
+}
+
+// TestAddSubscriber_NoBroadcastWhenTombstoneRefusesWrite covers the review's
+// finding 3. AddIssueSubscriber correctly refuses to resurrect an opt-out, but
+// addSubscriber used to publish subscriber:added regardless. Clients insert the
+// user into their cache on that event, so the UI claimed "watching" while the
+// DB said otherwise — and the user kept receiving nothing.
+func TestAddSubscriber_NoBroadcastWhenTombstoneRefusesWrite(t *testing.T) {
+ ctx := context.Background()
+ queries := db.New(testPool)
+ bus := events.New()
+
+ issueID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() { cleanupTestIssue(t, issueID) })
+
+ if _, err := queries.AddIssueSubscriber(ctx, db.AddIssueSubscriberParams{
+ IssueID: util.MustParseUUID(issueID), UserType: "member",
+ UserID: util.MustParseUUID(testUserID), Reason: "creator",
+ }); err != nil {
+ t.Fatalf("seed subscriber: %v", err)
+ }
+ if err := queries.RemoveIssueSubscriber(ctx, db.RemoveIssueSubscriberParams{
+ IssueID: util.MustParseUUID(issueID), UserType: "member",
+ UserID: util.MustParseUUID(testUserID),
+ }); err != nil {
+ t.Fatalf("unsubscribe: %v", err)
+ }
+
+ events := countSubscriberAddedEvents(bus, issueID)
+ addSubscriber(bus, queries, testWorkspaceID, issueID, "member", testUserID, "commenter")
+
+ if isSubscribed(t, queries, issueID, "member", testUserID) {
+ t.Fatal("tombstone was resurrected")
+ }
+ if *events != 0 {
+ t.Fatalf("published %d subscriber:added event(s) for a write the DB refused — clients would show a subscription that does not exist", *events)
+ }
+}
+
+// TestAddSubscriber_BroadcastsOnRealInsert is the other half: the suppression
+// above must not silence legitimate subscriptions.
+func TestAddSubscriber_BroadcastsOnRealInsert(t *testing.T) {
+ queries := db.New(testPool)
+ bus := events.New()
+
+ issueID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() { cleanupTestIssue(t, issueID) })
+
+ events := countSubscriberAddedEvents(bus, issueID)
+ addSubscriber(bus, queries, testWorkspaceID, issueID, "member", testUserID, "creator")
+
+ if !isSubscribed(t, queries, issueID, "member", testUserID) {
+ t.Fatal("expected the subscriber to be written")
+ }
+ if *events != 1 {
+ t.Fatalf("expected exactly 1 subscriber:added event, got %d", *events)
+ }
+}
+
+// TestDelegatedUpgradesToDirectReason covers finding 4. Once the user is
+// actually participating — assigned, mentioned, or commenting — they are no
+// longer a passive delegate, so the reduced delivery tier must stop applying.
+// ON CONFLICT DO NOTHING pinned reason at 'delegated' forever.
+func TestDelegatedUpgradesToDirectReason(t *testing.T) {
+ ctx := context.Background()
+ queries := db.New(testPool)
+
+ issueID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() { cleanupTestIssue(t, issueID) })
+
+ add := func(reason string) {
+ t.Helper()
+ if _, err := queries.AddIssueSubscriber(ctx, db.AddIssueSubscriberParams{
+ IssueID: util.MustParseUUID(issueID), UserType: "member",
+ UserID: util.MustParseUUID(testUserID), Reason: reason,
+ }); err != nil {
+ t.Fatalf("AddIssueSubscriber(%s): %v", reason, err)
+ }
+ }
+
+ add("delegated")
+ if got := subscriberReason(t, queries, issueID, "member", testUserID); got != "delegated" {
+ t.Fatalf("reason = %q, want delegated", got)
+ }
+
+ add("commenter")
+ if got := subscriberReason(t, queries, issueID, "member", testUserID); got != "commenter" {
+ t.Fatalf("reason = %q after commenting, want commenter — a delegate who joins in must leave the reduced tier", got)
+ }
+
+ // A direct reason must never be downgraded back to delegated by a later
+ // agent-created sibling pass.
+ add("delegated")
+ if got := subscriberReason(t, queries, issueID, "member", testUserID); got != "commenter" {
+ t.Fatalf("reason = %q, want commenter — a direct subscription must not be downgraded", got)
+ }
+}
+
+// TestUnsubscribeIssueScopeLeavesFutureChildrenAlone covers finding 2. Both menu
+// items wrote an indistinguishable tombstone, and HasAncestorOptOut treated any
+// ancestor tombstone as a subtree opt-out — so "unsubscribe from this issue"
+// silently suppressed every child the agent would ever file underneath it. The
+// two choices then differed only for descendants that already existed.
+func TestUnsubscribeIssueScopeLeavesFutureChildrenAlone(t *testing.T) {
+ ctx := context.Background()
+ queries := db.New(testPool)
+ bus := events.New()
+ registerSubscriberListeners(bus, testPool)
+
+ agentID, runtimeID := firstFixtureAgent(t)
+ parentID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() { cleanupTestIssue(t, parentID) })
+
+ if _, err := queries.AddIssueSubscriber(ctx, db.AddIssueSubscriberParams{
+ IssueID: util.MustParseUUID(parentID), UserType: "member",
+ UserID: util.MustParseUUID(testUserID), Reason: "creator",
+ }); err != nil {
+ t.Fatalf("seed parent subscriber: %v", err)
+ }
+ // Narrow opt-out: this issue only.
+ if err := queries.RemoveIssueSubscriber(ctx, db.RemoveIssueSubscriberParams{
+ IssueID: util.MustParseUUID(parentID), UserType: "member",
+ UserID: util.MustParseUUID(testUserID),
+ }); err != nil {
+ t.Fatalf("RemoveIssueSubscriber: %v", err)
+ }
+
+ task := createAgentTaskWithOriginator(t, agentID, runtimeID, util.MustParseUUID(testUserID))
+ childID := createAgentOriginIssue(t, agentID, "agent_create", task, util.MustParseUUID(parentID))
+ publishAgentIssueCreated(bus, childID, agentID)
+
+ if !isSubscribed(t, queries, childID, "member", testUserID) {
+ t.Fatal("leaving one issue must not suppress future children — that is what the subtree option is for")
+ }
+ if isSubscribed(t, queries, parentID, "member", testUserID) {
+ t.Fatal("the narrow opt-out must still hold on the issue it targeted")
+ }
+}
+
+// TestUnsubscribeSubtreeReportsEveryAffectedIssue covers finding 5. The SQL
+// retires the whole subtree, but the handler published one subscriber:removed
+// for the root only, so a client with a CHILD open kept rendering a
+// subscription the server had already dropped. The query has to report every
+// issue it touched for the handler to broadcast per issue.
+func TestUnsubscribeSubtreeReportsEveryAffectedIssue(t *testing.T) {
+ ctx := context.Background()
+ queries := db.New(testPool)
+
+ parentID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() { cleanupTestIssue(t, parentID) })
+ childID := createChildIssue(t, testWorkspaceID, testUserID, util.MustParseUUID(parentID))
+ grandchildID := createChildIssue(t, testWorkspaceID, testUserID, util.MustParseUUID(childID))
+
+ for _, id := range []string{parentID, childID, grandchildID} {
+ if _, err := queries.AddIssueSubscriber(ctx, db.AddIssueSubscriberParams{
+ IssueID: util.MustParseUUID(id), UserType: "member",
+ UserID: util.MustParseUUID(testUserID), Reason: "delegated",
+ }); err != nil {
+ t.Fatalf("seed subscriber on %s: %v", id, err)
+ }
+ }
+
+ affected, err := queries.UnsubscribeFromIssueSubtree(ctx, db.UnsubscribeFromIssueSubtreeParams{
+ ID: util.MustParseUUID(parentID), UserType: "member",
+ UserID: util.MustParseUUID(testUserID),
+ })
+ if err != nil {
+ t.Fatalf("UnsubscribeFromIssueSubtree: %v", err)
+ }
+
+ got := map[string]bool{}
+ for _, id := range affected {
+ got[util.UUIDToString(id)] = true
+ }
+ for _, want := range []string{parentID, childID, grandchildID} {
+ if !got[want] {
+ t.Fatalf("subtree unsubscribe did not report issue %s; clients with it open keep a stale subscription", want)
+ }
+ if isSubscribed(t, queries, want, "member", testUserID) {
+ t.Fatalf("issue %s is still subscribed after a subtree unsubscribe", want)
+ }
+ }
+}
+
+// createChildIssue inserts an issue under the given parent.
+func createChildIssue(t *testing.T, workspaceID, creatorID string, parent pgtype.UUID) string {
+ t.Helper()
+ var issueID string
+ err := testPool.QueryRow(context.Background(), `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id,
+ position, number, parent_issue_id)
+ VALUES ($1, 'child issue', 'todo', 'medium', 'member', $2, 0,
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1), $3)
+ RETURNING id
+ `, workspaceID, creatorID, parent).Scan(&issueID)
+ if err != nil {
+ t.Fatalf("createChildIssue: %v", err)
+ }
+ t.Cleanup(func() { cleanupTestIssue(t, issueID) })
+ return issueID
+}
diff --git a/server/cmd/server/delegated_subscriber_test.go b/server/cmd/server/delegated_subscriber_test.go
new file mode 100644
index 0000000000..d8e6a2ff92
--- /dev/null
+++ b/server/cmd/server/delegated_subscriber_test.go
@@ -0,0 +1,389 @@
+package main
+
+import (
+ "context"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// firstFixtureAgent returns an agent in the test workspace along with its
+// runtime; the delegated rule only cares that the issue creator IS an agent,
+// but agent_task_queue.runtime_id is NOT NULL so the task insert needs both.
+func firstFixtureAgent(t *testing.T) (agentID, runtimeID string) {
+ t.Helper()
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT id::text, runtime_id::text FROM agent
+ WHERE workspace_id = $1 AND runtime_id IS NOT NULL
+ ORDER BY created_at ASC LIMIT 1`,
+ testWorkspaceID,
+ ).Scan(&agentID, &runtimeID); err != nil {
+ t.Fatalf("load fixture agent: %v", err)
+ }
+ return agentID, runtimeID
+}
+
+// createAgentTaskWithOriginator inserts a queued task attributed to the given
+// human, standing in for the run an agent is executing when it files an issue.
+// An invalid originator models an unattributed / autopilot-rooted chain.
+func createAgentTaskWithOriginator(t *testing.T, agentID, runtimeID string, originator pgtype.UUID) pgtype.UUID {
+ t.Helper()
+ ctx := context.Background()
+ var taskID pgtype.UUID
+ err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, originator_user_id, accountable_user_id)
+ VALUES ($1, $2, 'queued', 0, $3, $3)
+ RETURNING id
+ `, agentID, runtimeID, originator).Scan(&taskID)
+ if err != nil {
+ t.Fatalf("create agent task: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ })
+ return taskID
+}
+
+// createAgentOriginIssue inserts an issue whose creator is an agent and whose
+// provenance points at originTask — the exact row shape the ordinary agent
+// `issue create` path produces (MUL-4305).
+func createAgentOriginIssue(t *testing.T, agentID, originType string, originTask pgtype.UUID, parent pgtype.UUID) string {
+ t.Helper()
+ ctx := context.Background()
+ var issueID string
+ err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id,
+ position, number, origin_type, origin_id, parent_issue_id)
+ VALUES ($1, 'delegated subscriber test issue', 'todo', 'medium', 'agent', $2, 0,
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1),
+ $3, $4, $5)
+ RETURNING id
+ `, testWorkspaceID, agentID, originType, originTask, parent).Scan(&issueID)
+ if err != nil {
+ t.Fatalf("create agent-origin issue: %v", err)
+ }
+ t.Cleanup(func() { cleanupTestIssue(t, issueID) })
+ return issueID
+}
+
+// publishAgentIssueCreated fires the event the create path publishes, so the
+// test exercises the real listener chain rather than calling the rule directly.
+func publishAgentIssueCreated(bus *events.Bus, issueID, agentID string) {
+ bus.Publish(events.Event{
+ Type: protocol.EventIssueCreated,
+ WorkspaceID: testWorkspaceID,
+ ActorType: "agent",
+ ActorID: agentID,
+ Payload: map[string]any{
+ "issue": handler.IssueResponse{
+ ID: issueID,
+ WorkspaceID: testWorkspaceID,
+ Title: "delegated subscriber test issue",
+ Status: "todo",
+ Priority: "medium",
+ CreatorType: "agent",
+ CreatorID: agentID,
+ },
+ },
+ })
+}
+
+func subscriberReason(t *testing.T, queries *db.Queries, issueID, userType, userID string) string {
+ t.Helper()
+ subs, err := queries.ListIssueSubscribers(context.Background(), util.MustParseUUID(issueID))
+ if err != nil {
+ t.Fatalf("ListIssueSubscribers: %v", err)
+ }
+ for _, s := range subs {
+ if s.UserType == userType && util.UUIDToString(s.UserID) == userID {
+ return s.Reason
+ }
+ }
+ return ""
+}
+
+// TestDelegatedSubscribe_AgentCreatedSubIssue is MUL-5483's headline case. Every
+// pre-existing auto-subscribe rule keys on ACTOR identity, so an agent-created,
+// agent-assigned sub-issue ends up with a full subscriber list and zero members
+// to notify. The human the run is attributed to must be subscribed instead.
+func TestDelegatedSubscribe_AgentCreatedSubIssue(t *testing.T) {
+ queries := db.New(testPool)
+ bus := events.New()
+ registerSubscriberListeners(bus, testPool)
+
+ agentID, runtimeID := firstFixtureAgent(t)
+ parentID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() { cleanupTestIssue(t, parentID) })
+
+ task := createAgentTaskWithOriginator(t, agentID, runtimeID, util.MustParseUUID(testUserID))
+ issueID := createAgentOriginIssue(t, agentID, "agent_create", task, util.MustParseUUID(parentID))
+
+ publishAgentIssueCreated(bus, issueID, agentID)
+
+ if !isSubscribed(t, queries, issueID, "member", testUserID) {
+ t.Fatal("expected the human the run is attributed to to be subscribed to the agent-created sub-issue")
+ }
+ if got := subscriberReason(t, queries, issueID, "member", testUserID); got != "delegated" {
+ t.Fatalf("reason = %q, want delegated", got)
+ }
+}
+
+// TestDelegatedSubscribe_QuickCreateKeepsDirectReason: quick create is direct
+// human intent and must keep the full-notification 'creator' tier. This also
+// covers the path that used to be hand-written at task completion and now
+// resolves through the same shared rule.
+func TestDelegatedSubscribe_QuickCreateKeepsDirectReason(t *testing.T) {
+ queries := db.New(testPool)
+ bus := events.New()
+ registerSubscriberListeners(bus, testPool)
+
+ agentID, runtimeID := firstFixtureAgent(t)
+ task := createAgentTaskWithOriginator(t, agentID, runtimeID, util.MustParseUUID(testUserID))
+ issueID := createAgentOriginIssue(t, agentID, "quick_create", task, pgtype.UUID{})
+
+ publishAgentIssueCreated(bus, issueID, agentID)
+
+ if got := subscriberReason(t, queries, issueID, "member", testUserID); got != "creator" {
+ t.Fatalf("reason = %q, want creator — quick create must not be downgraded to the delegated tier", got)
+ }
+}
+
+// TestDelegatedSubscribe_UnattributedOriginSubscribesNobody: when the origin run
+// carries no human (degraded attribution), we must not invent one to notify.
+func TestDelegatedSubscribe_UnattributedOriginSubscribesNobody(t *testing.T) {
+ queries := db.New(testPool)
+ bus := events.New()
+ registerSubscriberListeners(bus, testPool)
+
+ agentID, runtimeID := firstFixtureAgent(t)
+ task := createAgentTaskWithOriginator(t, agentID, runtimeID, pgtype.UUID{})
+ issueID := createAgentOriginIssue(t, agentID, "agent_create", task, pgtype.UUID{})
+
+ publishAgentIssueCreated(bus, issueID, agentID)
+
+ if isSubscribed(t, queries, issueID, "member", testUserID) {
+ t.Fatal("an unattributed origin task must not subscribe any member")
+ }
+}
+
+// TestDelegatedSubscribe_RespectsSubtreeOptOut is the reason the tombstone
+// exists. Without it "stop watching this tree" is undone by the very next child
+// the agent files under it: the rule fires per issue, and an agent-built tree
+// keeps growing after the user has already said no.
+func TestDelegatedSubscribe_RespectsSubtreeOptOut(t *testing.T) {
+ ctx := context.Background()
+ queries := db.New(testPool)
+ bus := events.New()
+ registerSubscriberListeners(bus, testPool)
+
+ agentID, runtimeID := firstFixtureAgent(t)
+ parentID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() { cleanupTestIssue(t, parentID) })
+
+ // The user leaves the parent tree.
+ if _, err := queries.UnsubscribeFromIssueSubtree(ctx, db.UnsubscribeFromIssueSubtreeParams{
+ ID: util.MustParseUUID(parentID),
+ UserType: "member",
+ UserID: util.MustParseUUID(testUserID),
+ }); err != nil {
+ t.Fatalf("UnsubscribeFromIssueSubtree: %v", err)
+ }
+
+ // The agent then files a NEW child under that same parent.
+ task := createAgentTaskWithOriginator(t, agentID, runtimeID, util.MustParseUUID(testUserID))
+ childID := createAgentOriginIssue(t, agentID, "agent_create", task, util.MustParseUUID(parentID))
+ publishAgentIssueCreated(bus, childID, agentID)
+
+ if isSubscribed(t, queries, childID, "member", testUserID) {
+ t.Fatal("a child created after a sub-tree opt-out must not re-subscribe the user")
+ }
+}
+
+// TestUnsubscribeIsDurableAgainstAutoRules: unsubscribing used to be row
+// ABSENCE, which any later auto-subscribe rule silently overwrote. It must now
+// survive a rule that would otherwise re-add the same person.
+func TestUnsubscribeIsDurableAgainstAutoRules(t *testing.T) {
+ ctx := context.Background()
+ queries := db.New(testPool)
+
+ issueID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() { cleanupTestIssue(t, issueID) })
+
+ if _, err := queries.AddIssueSubscriber(ctx, db.AddIssueSubscriberParams{
+ IssueID: util.MustParseUUID(issueID),
+ UserType: "member",
+ UserID: util.MustParseUUID(testUserID),
+ Reason: "creator",
+ }); err != nil {
+ t.Fatalf("AddIssueSubscriber: %v", err)
+ }
+ if err := queries.RemoveIssueSubscriber(ctx, db.RemoveIssueSubscriberParams{
+ IssueID: util.MustParseUUID(issueID),
+ UserType: "member",
+ UserID: util.MustParseUUID(testUserID),
+ }); err != nil {
+ t.Fatalf("RemoveIssueSubscriber: %v", err)
+ }
+ if isSubscribed(t, queries, issueID, "member", testUserID) {
+ t.Fatal("expected the user to be unsubscribed")
+ }
+
+ // A later rule pass (commented, mentioned, delegated, …) tries to re-add.
+ if _, err := queries.AddIssueSubscriber(ctx, db.AddIssueSubscriberParams{
+ IssueID: util.MustParseUUID(issueID),
+ UserType: "member",
+ UserID: util.MustParseUUID(testUserID),
+ Reason: "commenter",
+ }); err != nil {
+ t.Fatalf("AddIssueSubscriber (second pass): %v", err)
+ }
+ if isSubscribed(t, queries, issueID, "member", testUserID) {
+ t.Fatal("an auto-subscribe rule must not resurrect an explicit unsubscribe")
+ }
+
+ // An explicit subscribe IS allowed to override the user's own opt-out.
+ if err := queries.SubscribeToIssueExplicitly(ctx, db.SubscribeToIssueExplicitlyParams{
+ IssueID: util.MustParseUUID(issueID),
+ UserType: "member",
+ UserID: util.MustParseUUID(testUserID),
+ Reason: "manual",
+ }); err != nil {
+ t.Fatalf("SubscribeToIssueExplicitly: %v", err)
+ }
+ if !isSubscribed(t, queries, issueID, "member", testUserID) {
+ t.Fatal("an explicit subscribe must clear the opt-out tombstone")
+ }
+}
+
+// TestDeliverToSubscriber_DelegatedTier pins the noise contract. The tier drops
+// churn and nothing else: a child FINISHING is real signal, one per piece of work
+// a reviewer has to act on. An earlier cut suppressed those in favour of a
+// synthesized "whole batch finished" roll-up; that machinery is gone (see the
+// MUL-5483 thread), and the tree-level signal comes from the parent's own status
+// transition, which this same rule delivers.
+func TestDeliverToSubscriber_DelegatedTier(t *testing.T) {
+ cases := []struct {
+ name string
+ reason string
+ notifType string
+ issueStatus string
+ want bool
+ }{
+ {"direct subscriber keeps every event", "creator", "status_changed", "in_progress", true},
+ {"direct subscriber keeps comments", "assignee", "new_comment", "todo", true},
+
+ {"delegated skips routine progress", "delegated", "status_changed", "in_progress", false},
+ {"delegated skips backlog parking", "delegated", "status_changed", "backlog", false},
+ {"delegated skips todo", "delegated", "status_changed", "todo", false},
+ {"delegated skips comment churn", "delegated", "new_comment", "in_progress", false},
+ {"delegated skips assignee churn", "delegated", "assignee_changed", "in_progress", false},
+ {"delegated skips date churn", "delegated", "due_date_changed", "in_progress", false},
+
+ {"delegated gets the review handoff", "delegated", "status_changed", "in_review", true},
+ {"delegated gets completion", "delegated", "status_changed", "done", true},
+ {"delegated gets cancellation", "delegated", "status_changed", "cancelled", true},
+ {"delegated gets blocked", "delegated", "status_changed", "blocked", true},
+
+ {"delegated always gets direct mentions", "delegated", "mentioned", "in_progress", true},
+ {"delegated always gets failures", "delegated", "task_failed", "in_progress", true},
+ {"delegated always gets agent_blocked", "delegated", "agent_blocked", "in_progress", true},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := deliverToSubscriber(tc.reason, tc.notifType, tc.issueStatus); got != tc.want {
+ t.Fatalf("deliverToSubscriber(%q, %q, %q) = %v, want %v",
+ tc.reason, tc.notifType, tc.issueStatus, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestDelegatedTier_ChildCompletionDeliversExactlyOnce is the case a unit test of
+// deliverToSubscriber alone cannot catch. status_changed bubbles from a child to
+// the parent's subscribers, and the common shape is a human who is BOTH a direct
+// subscriber of the parent and a delegate on the child. They must be told the
+// child finished, and told once — not twice via the bubble, and not zero times.
+func TestDelegatedTier_ChildCompletionDeliversExactlyOnce(t *testing.T) {
+ ctx := context.Background()
+ queries := db.New(testPool)
+ bus := events.New()
+
+ agentID, runtimeID := firstFixtureAgent(t)
+ parentID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() { cleanupTestIssue(t, parentID) })
+
+ // Direct on the parent — the human filed the epic themselves.
+ if _, err := queries.AddIssueSubscriber(ctx, db.AddIssueSubscriberParams{
+ IssueID: util.MustParseUUID(parentID),
+ UserType: "member",
+ UserID: util.MustParseUUID(testUserID),
+ Reason: "creator",
+ }); err != nil {
+ t.Fatalf("subscribe parent: %v", err)
+ }
+
+ // Agent files a child; the delegated rule subscribes the human to it.
+ registerSubscriberListeners(bus, testPool)
+ task := createAgentTaskWithOriginator(t, agentID, runtimeID, util.MustParseUUID(testUserID))
+ childID := createAgentOriginIssue(t, agentID, "agent_create", task, util.MustParseUUID(parentID))
+ publishAgentIssueCreated(bus, childID, agentID)
+ if got := subscriberReason(t, queries, childID, "member", testUserID); got != "delegated" {
+ t.Fatalf("child subscription reason = %q, want delegated", got)
+ }
+
+ countInbox := func() int {
+ t.Helper()
+ var n int
+ if err := testPool.QueryRow(ctx,
+ `SELECT COUNT(*) FROM inbox_item WHERE recipient_type='member' AND recipient_id=$1 AND issue_id=$2`,
+ testUserID, childID,
+ ).Scan(&n); err != nil {
+ t.Fatalf("count inbox: %v", err)
+ }
+ return n
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM inbox_item WHERE issue_id = $1`, childID)
+ })
+
+ // The new status travels as notifySubscribers' issueStatus argument, not on
+ // the event. The agent actor matters: notifyIssueSubscribers skips the actor,
+ // and a human-actored event would skip the recipient under test.
+ agentEvent := events.Event{
+ Type: protocol.EventIssueUpdated,
+ WorkspaceID: testWorkspaceID,
+ ActorType: "agent",
+ ActorID: agentID,
+ }
+
+ // Routine progress on the child stays suppressed for the delegate, and the
+ // parent bubble must not smuggle it back in.
+ notifySubscribers(ctx, queries, bus, childID, "in_progress", testWorkspaceID,
+ agentEvent, nil, "status_changed", "info", "child", "", emptyDetails)
+ if n := countInbox(); n != 0 {
+ t.Fatalf("routine child progress reached the inbox %d time(s) — the parent bubble bypassed the tier", n)
+ }
+
+ // Completion delivers, exactly once despite two paths to the same person.
+ notifySubscribers(ctx, queries, bus, childID, "in_review", testWorkspaceID,
+ agentEvent, nil, "status_changed", "info", "child", "", emptyDetails)
+ if n := countInbox(); n != 1 {
+ t.Fatalf("expected exactly 1 inbox row for the child completion, got %d", n)
+ }
+}
+
+// TestDeliverToSubscriber_UnknownReasonIsDirect: 'reason' is an open vocabulary
+// (a new rule can add one without a migration touching this file). An
+// unrecognized reason must fall back to FULL delivery — silently dropping a
+// user's notifications is the worse failure.
+func TestDeliverToSubscriber_UnknownReasonIsDirect(t *testing.T) {
+ if !deliverToSubscriber("some_future_reason", "new_comment", "in_progress") {
+ t.Fatal("an unrecognized subscription reason must default to full delivery")
+ }
+}
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 9c55d8231f..1b6dd1bbed 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -329,7 +329,7 @@ func main() {
// Order matters: subscriber listeners must register BEFORE notification listeners.
// The notification listener queries the subscriber table to determine recipients,
// so subscribers must be written first within the same synchronous event dispatch.
- registerSubscriberListeners(bus, queries)
+ registerSubscriberListeners(bus, pool)
registerActivityListeners(bus, queries)
registerNotificationListeners(bus, queries)
diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.go
index 5761ee7a1a..e94c95f471 100644
--- a/server/cmd/server/notification_listeners.go
+++ b/server/cmd/server/notification_listeners.go
@@ -19,7 +19,6 @@ type mention struct {
ID string // user_id, agent_id, issue_id, or "all"
}
-
// statusLabels maps DB status values to human-readable labels for notifications.
var statusLabels = map[string]string{
"backlog": "Backlog",
@@ -75,22 +74,77 @@ var parentBubbleNotifTypes = map[string]bool{
"status_changed": true,
}
+// delegatedAlwaysNotifTypes are the events a DELEGATED subscriber (reason=
+// 'delegated' — an agent created this issue on their behalf, MUL-5483) receives
+// unconditionally: they are either addressed at the human directly, or they are
+// exceptions that stall the work until a human looks.
+var delegatedAlwaysNotifTypes = map[string]bool{
+ "mentioned": true,
+ "task_failed": true,
+ "agent_blocked": true,
+}
+
+// delegatedStatusNotify are the statuses whose ARRIVAL is worth an inbox item
+// for a delegated subscriber — someone whose agent filed this issue on their
+// behalf.
+//
+// in_review is the important one: in Multica's agent flow an agent parks
+// completed work in in_review, so that is the dominant "this needs you now"
+// transition, not done.
+//
+// Everything absent from this set is churn for someone who never asked for this
+// specific issue: routine forward progress (todo, in_progress), deliberate
+// parking (backlog), comment traffic, and field edits.
+var delegatedStatusNotify = map[string]bool{
+ "in_review": true,
+ "done": true,
+ "cancelled": true,
+ "blocked": true,
+}
+
+// deliverToSubscriber reports whether a subscriber row should receive this
+// notification type. Direct subscriptions (creator / assignee / commenter /
+// mentioned / manual / autopilot) are unchanged — they opted in to this issue,
+// explicitly or by acting on it. Only the delegated tier is narrowed, and only
+// to drop churn.
+//
+// A child finishing is NOT churn: "sub-issue X is ready for review" is exactly
+// the signal a delegated watcher needs, and there is one per piece of real work.
+// An earlier cut suppressed those and synthesized a single "the whole batch
+// finished" roll-up from sibling state instead. That was both the wrong shape
+// (see the MUL-5483 thread) and redundant: the human is subscribed to the PARENT
+// as well, so when the agent moves the parent to in_review/done that transition
+// delivers here — which is the natural "the tree is done" signal. Deriving it
+// from children was reinventing a notification the platform already sends.
+func deliverToSubscriber(reason, notifType, issueStatus string) bool {
+ if reason != "delegated" {
+ return true
+ }
+ if delegatedAlwaysNotifTypes[notifType] {
+ return true
+ }
+ if notifType != "status_changed" {
+ return false
+ }
+ return delegatedStatusNotify[issueStatus]
+}
+
// notifTypeToGroup maps each InboxItemType to a user-configurable preference
// group. Types not in this map are always delivered (not configurable).
var notifTypeToGroup = map[string]string{
- "issue_assigned": "assignments",
- "unassigned": "assignments",
- "assignee_changed": "assignments",
- "status_changed": "status_changes",
- "new_comment": "comments",
- "mentioned": "comments",
- "priority_changed": "updates",
+ "issue_assigned": "assignments",
+ "unassigned": "assignments",
+ "assignee_changed": "assignments",
+ "status_changed": "status_changes",
+ "new_comment": "comments",
+ "mentioned": "comments",
+ "priority_changed": "updates",
"start_date_changed": "updates",
- "due_date_changed": "updates",
- "task_completed": "agent_activity",
- "task_failed": "agent_activity",
- "agent_blocked": "agent_activity",
- "agent_completed": "agent_activity",
+ "due_date_changed": "updates",
+ "task_completed": "agent_activity",
+ "task_failed": "agent_activity",
+ "agent_blocked": "agent_activity",
+ "agent_completed": "agent_activity",
}
// isNotifMuted returns true if the given notification type is muted for a user
@@ -230,7 +284,7 @@ func notifySubscribers(
body string,
details []byte,
) {
- notified := notifyIssueSubscribers(ctx, queries, bus,
+ notified, tierSuppressed := notifyIssueSubscribers(ctx, queries, bus,
issueID, issueID, issueStatus, workspaceID, e, exclude,
notifType, severity, title, body, details)
@@ -251,13 +305,23 @@ func notifySubscribers(
}
// Merge already-notified IDs into exclude set for parent subscribers.
- parentExclude := make(map[string]bool, len(exclude)+len(notified))
+ parentExclude := make(map[string]bool, len(exclude)+len(notified)+len(tierSuppressed))
for id := range exclude {
parentExclude[id] = true
}
for id := range notified {
parentExclude[id] = true
}
+ // Recipients the delegated tier just filtered out for THIS child must not
+ // get the same event smuggled back in through the parent's subscriber list.
+ // The common shape is exactly that: the human directly created the parent
+ // (reason='creator', full delivery) while their agent filed the children
+ // (reason='delegated', reduced). Without this the tier suppresses nothing
+ // in the one case it exists for — an agent-built tree under a parent the
+ // human is watching (MUL-5483).
+ for id := range tierSuppressed {
+ parentExclude[id] = true
+ }
// Query subscribers from the parent issue, but the inbox item still
// points to the sub-issue so the user navigates to the actual change.
@@ -271,7 +335,11 @@ func notifySubscribers(
// subscriberIssueID, but creates inbox items pointing to targetIssueID.
// This allows querying subscribers from a parent issue while the notification
// links to the sub-issue where the change actually occurred.
-// Returns the set of member IDs that were notified.
+//
+// Returns two sets of member IDs: those that were notified, and those the
+// delegated delivery tier deliberately filtered out. The caller propagates the
+// second set into the parent bubble so a suppressed event cannot be
+// re-delivered through an ancestor subscription (see notifySubscribers).
func notifyIssueSubscribers(
ctx context.Context,
queries *db.Queries,
@@ -287,14 +355,15 @@ func notifyIssueSubscribers(
title string,
body string,
details []byte,
-) map[string]bool {
+) (map[string]bool, map[string]bool) {
notified := map[string]bool{}
+ tierSuppressed := map[string]bool{}
subs, err := queries.ListIssueSubscribers(ctx, parseUUID(subscriberIssueID))
if err != nil {
slog.Error("failed to list subscribers for notification",
"issue_id", subscriberIssueID, "error", err)
- return notified
+ return notified, tierSuppressed
}
// Batch-load notification preferences for all member subscribers.
@@ -329,6 +398,13 @@ func notifyIssueSubscribers(
continue
}
+ // Delegated subscriptions deliver a narrower event set than direct
+ // ones — see deliverToSubscriber.
+ if !deliverToSubscriber(sub.Reason, notifType, issueStatus) {
+ tierSuppressed[subID] = true
+ continue
+ }
+
item, err := queries.CreateInboxItem(ctx, db.CreateInboxItemParams{
WorkspaceID: parseUUID(workspaceID),
RecipientType: "member",
@@ -360,7 +436,7 @@ func notifyIssueSubscribers(
})
}
- return notified
+ return notified, tierSuppressed
}
// notifyDirect creates an inbox item for a specific recipient. Skips if the
@@ -597,8 +673,16 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {
prevDescription, _ := payload["prev_description"].(*string)
if assigneeChanged {
- // Build structured details for assignee change
- detailsMap := map[string]any{}
+ // Build structured details for assignee change.
+ //
+ // map[string]string, not map[string]any: every client parses inbox
+ // `details` as a string->string map, and because the inbox endpoint
+ // returns an ARRAY, one non-string value fails the whole parse and
+ // blanks the entire list rather than one row. `any` let that be a
+ // convention a reviewer had to notice; the concrete type makes it a
+ // compile error. This is the only details map in this file that was
+ // not already string-typed.
+ detailsMap := map[string]string{}
if prevAssigneeType != nil {
detailsMap["prev_assignee_type"] = *prevAssigneeType
}
diff --git a/server/cmd/server/notification_listeners_test.go b/server/cmd/server/notification_listeners_test.go
index 7267bbddc6..6de35127cc 100644
--- a/server/cmd/server/notification_listeners_test.go
+++ b/server/cmd/server/notification_listeners_test.go
@@ -71,7 +71,7 @@ func createTestSubIssue(t *testing.T, workspaceID, creatorID, parentIssueID stri
func newNotificationBus(t *testing.T, queries *db.Queries) *events.Bus {
t.Helper()
bus := events.New()
- registerSubscriberListeners(bus, queries)
+ registerSubscriberListeners(bus, testPool)
registerNotificationListeners(bus, queries)
return bus
}
@@ -519,7 +519,7 @@ func TestNotification_SystemCommentSkipsInboxAndMentions(t *testing.T) {
func TestSubscriberSystemCommentDoesNotSubscribe(t *testing.T) {
queries := db.New(testPool)
bus := events.New()
- registerSubscriberListeners(bus, queries)
+ registerSubscriberListeners(bus, testPool)
issueID := createTestIssue(t, testWorkspaceID, testUserID)
t.Cleanup(func() { cleanupTestIssue(t, issueID) })
diff --git a/server/cmd/server/quick_create_subscriber_test.go b/server/cmd/server/quick_create_subscriber_test.go
index f5d5c7fd40..b9623f4307 100644
--- a/server/cmd/server/quick_create_subscriber_test.go
+++ b/server/cmd/server/quick_create_subscriber_test.go
@@ -11,88 +11,21 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/service"
- "github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-// TestQuickCreateCompletion_SubscribesRequester locks in the fix for the
-// quick-create requester not being subscribed to the issue: the agent runs
-// the CLI and is recorded as the issue's creator, so the issue:created event
-// only auto-subscribes the agent. The completion path must explicitly
-// subscribe the human requester so they receive follow-up notifications.
-func TestQuickCreateCompletion_SubscribesRequester(t *testing.T) {
- ctx := context.Background()
- queries := db.New(testPool)
- bus := events.New()
- taskSvc := service.NewTaskService(queries, testPool, nil, bus)
-
- var agentID string
- if err := testPool.QueryRow(ctx,
- `SELECT id::text FROM agent WHERE workspace_id = $1 ORDER BY created_at ASC LIMIT 1`,
- testWorkspaceID,
- ).Scan(&agentID); err != nil {
- t.Fatalf("load fixture agent: %v", err)
- }
-
- task, err := taskSvc.EnqueueQuickCreateTask(ctx,
- parseUUID(testWorkspaceID),
- parseUUID(testUserID),
- parseUUID(agentID),
- pgtype.UUID{},
- "please file a bug",
- "",
- "",
- pgtype.UUID{},
- pgtype.UUID{},
- nil,
- )
- if err != nil {
- t.Fatalf("EnqueueQuickCreateTask: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, task.ID)
- })
-
- if _, err := testPool.Exec(ctx,
- `UPDATE agent_task_queue SET status = 'dispatched', dispatched_at = now() WHERE id = $1`,
- task.ID,
- ); err != nil {
- t.Fatalf("dispatch task: %v", err)
- }
- if _, err := queries.StartAgentTask(ctx, task.ID); err != nil {
- t.Fatalf("StartAgentTask: %v", err)
- }
-
- number, err := queries.IncrementIssueCounter(ctx, parseUUID(testWorkspaceID))
- if err != nil {
- t.Fatalf("IncrementIssueCounter: %v", err)
- }
- issue, err := queries.CreateIssueWithOrigin(ctx, db.CreateIssueWithOriginParams{
- WorkspaceID: parseUUID(testWorkspaceID),
- Title: "agent-filed bug",
- Status: "todo",
- Priority: "none",
- CreatorType: "agent",
- CreatorID: parseUUID(agentID),
- Number: number,
- OriginType: pgtype.Text{String: "quick_create", Valid: true},
- OriginID: task.ID,
- })
- if err != nil {
- t.Fatalf("CreateIssueWithOrigin: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issue.ID)
- })
-
- if _, err := taskSvc.CompleteTask(ctx, task.ID, []byte(`{"output":"done"}`), "", "", false, ""); err != nil {
- t.Fatalf("CompleteTask: %v", err)
- }
-
- if !isSubscribed(t, queries, util.UUIDToString(issue.ID), "member", testUserID) {
- t.Fatal("expected requester to be subscribed after quick-create completion")
- }
-}
+// Subscribing the quick-create requester moved OFF the completion path in
+// MUL-5483. It now happens at issue-creation time in the shared
+// delegated-subscriber rule, which resolves the human from
+// origin_type='quick_create' + the origin task's originator_user_id — the same
+// origin waterfall attribution uses. That behavior is covered by
+// TestDelegatedSubscribe_QuickCreateKeepsDirectReason in
+// delegated_subscriber_test.go, including the assertion that quick create keeps
+// the direct 'creator' tier rather than the reduced delegated one.
+//
+// The failure-path test below stays here: "no issue created ⇒ no subscriber
+// row" is a property of the quick-create completion flow itself and holds
+// regardless of which layer writes the subscription.
// TestQuickCreateFailure_DoesNotSubscribeRequester confirms the failure path
// (agent finished without producing an issue) does not invent a subscriber
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index ba6d348590..89604b43ea 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1147,6 +1147,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/subscribers", h.ListIssueSubscribers)
r.Post("/subscribe", h.SubscribeToIssue)
r.Post("/unsubscribe", h.UnsubscribeFromIssue)
+ r.Post("/unsubscribe/subtree", h.UnsubscribeFromIssueSubtree)
r.Get("/active-task", h.GetActiveTaskForIssue)
r.Post("/tasks/{taskId}/cancel", h.CancelTask)
r.Post("/rerun", h.RerunIssue)
diff --git a/server/cmd/server/subscriber_listeners.go b/server/cmd/server/subscriber_listeners.go
index 3fe392d230..f50e9314f1 100644
--- a/server/cmd/server/subscriber_listeners.go
+++ b/server/cmd/server/subscriber_listeners.go
@@ -4,8 +4,11 @@ import (
"context"
"log/slog"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/attribution"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -13,7 +16,12 @@ import (
// registerSubscriberListeners wires up event bus listeners that auto-subscribe
// relevant users to issues. This ensures creators, assignees, and commenters
// are automatically tracked as issue subscribers.
-func registerSubscriberListeners(bus *events.Bus, queries *db.Queries) {
+//
+// Takes the pool rather than *db.Queries because the delegated rule needs a
+// transaction: its eligibility checks and its write must sit inside one
+// serialization boundary (see subscribeDelegatedHuman).
+func registerSubscriberListeners(bus *events.Bus, pool *pgxpool.Pool) {
+ queries := db.New(pool)
// issue:created — subscribe creator + assignee (if different)
bus.Subscribe(protocol.EventIssueCreated, func(e events.Event) {
payload, ok := e.Payload.(map[string]any)
@@ -42,6 +50,13 @@ func registerSubscriberListeners(bus *events.Bus, queries *db.Queries) {
addSubscriber(bus, queries, e.WorkspaceID, issue.ID, m.Type, m.ID, "mentioned")
}
}
+
+ // Subscribe the human this issue was created ON BEHALF OF. Every rule
+ // above keys on ACTOR identity, so when an agent creates an issue and
+ // assigns it to an agent, every subscriber is an agent — and
+ // notifyIssueSubscribers only delivers to members. The result is a full
+ // subscriber list with zero recipients (MUL-5483).
+ subscribeDelegatedHuman(bus, pool, queries, e.WorkspaceID, issue.ID)
})
// issue:updated — subscribe new assignee or @mentioned users
@@ -119,6 +134,112 @@ func registerSubscriberListeners(bus *events.Bus, queries *db.Queries) {
})
}
+// subscribeDelegatedHuman auto-subscribes the accountable human behind an
+// agent-created issue, so a delegated chain keeps the visibility its
+// attribution already records (MUL-5483).
+//
+// The facts are read here and classified by the pure
+// attribution.DelegatedSubscriber rule, which is the SAME origin waterfall
+// ClassifyDirect uses to decide who a derived run is attributed to. That shared
+// rule is the point: the defect being fixed is attribution and notification
+// disagreeing about whose behalf an issue exists on.
+//
+// Everything is best-effort and logged, never fatal — the issue is already
+// committed and a subscription hiccup must not look like a creation failure.
+func subscribeDelegatedHuman(bus *events.Bus, pool *pgxpool.Pool, queries *db.Queries, workspaceID, issueID string) {
+ ctx := context.Background()
+ issueUUID := parseUUID(issueID)
+
+ // The event payload carries no origin columns (they are platform-internal
+ // and not part of IssueResponse), so re-read the row.
+ issue, err := queries.GetIssue(ctx, issueUUID)
+ if err != nil {
+ slog.Error("delegated subscribe: load issue failed", "issue_id", issueID, "error", err)
+ return
+ }
+ if issue.CreatorType != "agent" || !issue.OriginType.Valid || !issue.OriginID.Valid {
+ return
+ }
+
+ // Workspace-scoped so a foreign origin id can never resolve a human from
+ // another tenant (the MUL-4252 guard the comment chain already applies).
+ originTask, err := queries.GetAgentTaskInWorkspace(ctx, db.GetAgentTaskInWorkspaceParams{
+ ID: issue.OriginID,
+ WorkspaceID: parseUUID(workspaceID),
+ })
+ if err != nil {
+ // A missing origin task is normal (cancelled/reaped run), not an error
+ // worth alerting on; there is simply no human to inherit.
+ slog.Debug("delegated subscribe: origin task not resolvable",
+ "issue_id", issueID, "origin_type", issue.OriginType.String)
+ return
+ }
+
+ human, reason, ok := attribution.DelegatedSubscriber(attribution.SubscriptionFacts{
+ CreatorType: issue.CreatorType,
+ OriginType: issue.OriginType.String,
+ OriginOriginator: originTask.OriginatorUserID,
+ })
+ if !ok {
+ return
+ }
+
+ // Two conditions decide whether this subscription may exist, and BOTH can
+ // be invalidated by a concurrent request between a check and the write:
+ //
+ // * the originator must still be a workspace member — originator_user_id
+ // is stamped at queue time and never revisited, so a revoked member's
+ // still-running tasks would keep filing ghost subscribers;
+ // * no opt-out may cover this issue — otherwise the next child an agent
+ // files silently undoes "stop watching this sub-tree", which is the
+ // escape hatch this whole feature depends on.
+ //
+ // Both live in AddDelegatedSubscriber as a single statement, under a
+ // transaction-scoped lock that member revoke and subtree unsubscribe also
+ // take. Checking in one round trip and writing in another cannot be made
+ // correct here: the losing interleaving subscribes an issue that did not
+ // exist when the opt-out was written, so there is no row for a row lock to
+ // protect (MUL-5483 review round 7).
+ tx, err := pool.Begin(ctx)
+ if err != nil {
+ slog.Error("delegated subscribe: begin failed", "issue_id", issueID, "error", err)
+ return
+ }
+ defer tx.Rollback(ctx)
+ qtx := queries.WithTx(tx)
+
+ if err := qtx.LockSubscriberWrites(ctx, db.LockSubscriberWritesParams{
+ WorkspaceID: parseUUID(workspaceID),
+ UserID: human,
+ }); err != nil {
+ slog.Error("delegated subscribe: lock failed", "issue_id", issueID, "error", err)
+ return
+ }
+
+ affected, err := qtx.AddDelegatedSubscriber(ctx, db.AddDelegatedSubscriberParams{
+ IssueID: issueUUID,
+ UserID: human,
+ Reason: reason,
+ WorkspaceID: parseUUID(workspaceID),
+ })
+ if err != nil {
+ slog.Error("delegated subscribe: insert failed", "issue_id", issueID, "error", err)
+ return
+ }
+ if err := tx.Commit(ctx); err != nil {
+ slog.Error("delegated subscribe: commit failed", "issue_id", issueID, "error", err)
+ return
+ }
+
+ // Broadcast only for a write the DB actually accepted, and only AFTER the
+ // commit — publishing from inside the transaction would let clients observe
+ // a subscriber a rollback then removed.
+ if affected == 0 {
+ return
+ }
+ publishSubscriberAdded(bus, workspaceID, issueID, "member", util.UUIDToString(human), reason)
+}
+
// extractIssueFields normalizes an issue payload that may be either a
// handler.IssueResponse struct (HTTP handler path) or a map[string]any
// (autopilot service path) into a common shape.
@@ -147,7 +268,7 @@ func extractIssueFields(v any) (handler.IssueResponse, bool) {
// addSubscriber adds a user as an issue subscriber and publishes a
// subscriber:added event for real-time frontend sync.
func addSubscriber(bus *events.Bus, queries *db.Queries, workspaceID, issueID, userType, userID, reason string) {
- err := queries.AddIssueSubscriber(context.Background(), db.AddIssueSubscriberParams{
+ affected, err := queries.AddIssueSubscriber(context.Background(), db.AddIssueSubscriberParams{
IssueID: parseUUID(issueID),
UserType: userType,
UserID: parseUUID(userID),
@@ -163,7 +284,22 @@ func addSubscriber(bus *events.Bus, queries *db.Queries, workspaceID, issueID, u
)
return
}
+ // Nothing changed — either an identical active row already existed, or the
+ // insert hit an opt-out tombstone and was correctly refused. Broadcasting
+ // subscriber:added anyway made every open client insert a subscriber the DB
+ // does not have: the UI claimed the user was watching while they stayed
+ // unsubscribed and kept receiving nothing.
+ if affected == 0 {
+ return
+ }
+
+ publishSubscriberAdded(bus, workspaceID, issueID, userType, userID, reason)
+}
+// publishSubscriberAdded broadcasts a subscription the DB actually accepted.
+// Shared by the plain auto-subscribe rules and the transactional delegated
+// path so both describe an added subscriber identically to clients.
+func publishSubscriberAdded(bus *events.Bus, workspaceID, issueID, userType, userID, reason string) {
bus.Publish(events.Event{
Type: protocol.EventSubscriberAdded,
WorkspaceID: workspaceID,
diff --git a/server/cmd/server/subscriber_listeners_test.go b/server/cmd/server/subscriber_listeners_test.go
index 871068004b..5d0e27a348 100644
--- a/server/cmd/server/subscriber_listeners_test.go
+++ b/server/cmd/server/subscriber_listeners_test.go
@@ -85,7 +85,7 @@ func subscriberCount(t *testing.T, queries *db.Queries, issueID string) int {
func TestSubscriberIssueCreated_CreatorSubscribed(t *testing.T) {
queries := db.New(testPool)
bus := events.New()
- registerSubscriberListeners(bus, queries)
+ registerSubscriberListeners(bus, testPool)
issueID := createTestIssue(t, testWorkspaceID, testUserID)
t.Cleanup(func() { cleanupTestIssue(t, issueID) })
@@ -120,7 +120,7 @@ func TestSubscriberIssueCreated_CreatorSubscribed(t *testing.T) {
func TestSubscriberIssueCreated_CreatorAndAssignee(t *testing.T) {
queries := db.New(testPool)
bus := events.New()
- registerSubscriberListeners(bus, queries)
+ registerSubscriberListeners(bus, testPool)
assigneeEmail := "[email protected]"
assigneeID := createTestUser(t, assigneeEmail)
@@ -164,7 +164,7 @@ func TestSubscriberIssueCreated_CreatorAndAssignee(t *testing.T) {
func TestSubscriberIssueCreated_SelfAssign(t *testing.T) {
queries := db.New(testPool)
bus := events.New()
- registerSubscriberListeners(bus, queries)
+ registerSubscriberListeners(bus, testPool)
issueID := createTestIssue(t, testWorkspaceID, testUserID)
t.Cleanup(func() { cleanupTestIssue(t, issueID) })
@@ -204,7 +204,7 @@ func TestSubscriberIssueCreated_SelfAssign(t *testing.T) {
func TestSubscriberIssueUpdated_AssigneeChanged(t *testing.T) {
queries := db.New(testPool)
bus := events.New()
- registerSubscriberListeners(bus, queries)
+ registerSubscriberListeners(bus, testPool)
assigneeEmail := "[email protected]"
assigneeID := createTestUser(t, assigneeEmail)
@@ -243,7 +243,7 @@ func TestSubscriberIssueUpdated_AssigneeChanged(t *testing.T) {
func TestSubscriberIssueUpdated_NoAssigneeChange(t *testing.T) {
queries := db.New(testPool)
bus := events.New()
- registerSubscriberListeners(bus, queries)
+ registerSubscriberListeners(bus, testPool)
issueID := createTestIssue(t, testWorkspaceID, testUserID)
t.Cleanup(func() { cleanupTestIssue(t, issueID) })
@@ -278,7 +278,7 @@ func TestSubscriberIssueUpdated_NoAssigneeChange(t *testing.T) {
func TestSubscriberCommentCreated_CommenterSubscribed(t *testing.T) {
queries := db.New(testPool)
bus := events.New()
- registerSubscriberListeners(bus, queries)
+ registerSubscriberListeners(bus, testPool)
commenterEmail := "[email protected]"
commenterID := createTestUser(t, commenterEmail)
@@ -310,9 +310,8 @@ func TestSubscriberCommentCreated_CommenterSubscribed(t *testing.T) {
}
func TestSubscriberAddedEventPublished(t *testing.T) {
- queries := db.New(testPool)
bus := events.New()
- registerSubscriberListeners(bus, queries)
+ registerSubscriberListeners(bus, testPool)
issueID := createTestIssue(t, testWorkspaceID, testUserID)
t.Cleanup(func() { cleanupTestIssue(t, issueID) })
@@ -365,7 +364,7 @@ func TestSubscriberAddedEventPublished(t *testing.T) {
func TestSubscriberIssueCreated_AutopilotMapPayload(t *testing.T) {
queries := db.New(testPool)
bus := events.New()
- registerSubscriberListeners(bus, queries)
+ registerSubscriberListeners(bus, testPool)
issueID := createTestIssue(t, testWorkspaceID, testUserID)
t.Cleanup(func() { cleanupTestIssue(t, issueID) })
diff --git a/server/cmd/server/subscriber_lock_key_test.go b/server/cmd/server/subscriber_lock_key_test.go
new file mode 100644
index 0000000000..669a2782b0
--- /dev/null
+++ b/server/cmd/server/subscriber_lock_key_test.go
@@ -0,0 +1,90 @@
+package main
+
+import (
+ "context"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/util"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestLockSubscriberWrites_KeyedOnUUIDValueNotSpelling covers MUL-5483 review
+// round 8, finding 1.
+//
+// The lock key used to be hashtext() over the caller's raw string. PostgreSQL
+// treats 'AB…' and 'ab…' as the SAME uuid — every membership query and every
+// issue_subscriber row matches either spelling — but hashtext does not, so an
+// uppercase request took a DIFFERENT lock from the canonical holder and the two
+// paths stopped excluding each other. The serialization boundary silently had a
+// hole in it exactly when two clients disagreed about case.
+//
+// Casting to uuid before hashing makes the key a function of the VALUE. This
+// test pins that: a competing transaction holds the lock under the canonical
+// lowercase spelling, and an uppercase acquisition of the same UUID must block.
+func TestLockSubscriberWrites_KeyedOnUUIDValueNotSpelling(t *testing.T) {
+ ctx := context.Background()
+ queries := db.New(testPool)
+
+ // Holder takes the lock with the canonical (lowercase) spelling.
+ holder, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin holder: %v", err)
+ }
+ defer holder.Rollback(context.Background())
+
+ if err := queries.WithTx(holder).LockSubscriberWrites(ctx, db.LockSubscriberWritesParams{
+ WorkspaceID: util.MustParseUUID(testWorkspaceID),
+ UserID: util.MustParseUUID(testUserID),
+ }); err != nil {
+ t.Fatalf("holder lock: %v", err)
+ }
+
+ // A second transaction asks for the same UUIDs spelled in UPPERCASE. This
+ // is what a client sending a non-canonical UUID produces.
+ upperWorkspace := strings.ToUpper(testWorkspaceID)
+ upperUser := strings.ToUpper(testUserID)
+ if upperWorkspace == testWorkspaceID || upperUser == testUserID {
+ t.Fatal("fixture UUIDs have no letters to upper-case; this test cannot detect the bug")
+ }
+
+ blocked := make(chan error, 1)
+ go func() {
+ waiter, err := testPool.Begin(context.Background())
+ if err != nil {
+ blocked <- err
+ return
+ }
+ defer waiter.Rollback(context.Background())
+ blocked <- queries.WithTx(waiter).LockSubscriberWrites(
+ context.Background(),
+ db.LockSubscriberWritesParams{
+ WorkspaceID: util.MustParseUUID(upperWorkspace),
+ UserID: util.MustParseUUID(upperUser),
+ },
+ )
+ }()
+
+ select {
+ case err := <-blocked:
+ t.Fatalf("an uppercase-spelled UUID acquired the lock while the canonical spelling held it "+
+ "(err=%v): the two spellings are the same UUID everywhere else, so this reopens the race "+
+ "the lock exists to close", err)
+ case <-time.After(400 * time.Millisecond):
+ // Correctly blocked.
+ }
+
+ if err := holder.Commit(context.Background()); err != nil {
+ t.Fatalf("commit holder: %v", err)
+ }
+ select {
+ case err := <-blocked:
+ if err != nil {
+ t.Fatalf("waiter failed after release: %v", err)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("waiter never acquired the lock after the holder committed")
+ }
+}
diff --git a/server/internal/attribution/attribution.go b/server/internal/attribution/attribution.go
index 3f7c0a0349..78bb575139 100644
--- a/server/internal/attribution/attribution.go
+++ b/server/internal/attribution/attribution.go
@@ -396,6 +396,61 @@ func TriggerOwner(creatorUserID pgtype.UUID, evidenceKind EvidenceKind, evidence
return finalizeAttribution(r)
}
+// SubscriptionFacts are the already-fetched facts about an agent-created issue,
+// used to decide who inherits VISIBILITY of it (MUL-5483). Same shape of
+// contract as the Classify* inputs: the caller does the DB reads, the rule
+// stays pure.
+type SubscriptionFacts struct {
+ // CreatorType is the issue's own creator_type. Only agent-created issues
+ // can carry a delegated subscription; a member-created issue already
+ // subscribes its human through the ordinary 'creator' rule.
+ CreatorType string
+
+ // OriginType / OriginOriginator mirror DirectFacts: the issue's provenance
+ // stamp and the origin task's originator_user_id, loaded by the caller.
+ OriginType string
+ OriginOriginator pgtype.UUID
+}
+
+// DelegatedSubscriber resolves the human who should be auto-subscribed to an
+// agent-created issue, and the reason label to record.
+//
+// It deliberately mirrors ClassifyDirect's origin branch rather than inventing
+// a second notion of "whose behalf is this" — the whole defect this fixes was
+// attribution and notification disagreeing about that (MUL-5483). The waterfall
+// is narrower than ClassifyDirect's on purpose:
+//
+// - OriginOriginator valid → subscribe. A human authorized this chain, and
+// because attribution COPIES the accountable human across every agent hop
+// rather than chaining it (see SourceDelegation), this resolves the ORIGINAL
+// human at any depth. No depth cap: depth is exactly where a lost signal
+// hurts most, and the delivery tier — not a cap — is what bounds the noise.
+//
+// - quick_create → reason 'creator', agent_create → reason 'delegated'. The
+// quick-create human asked for THAT issue by name, so it is direct intent and
+// keeps full notifications; an agent_create child is the agent's own decision
+// made under a broader mandate, so it takes the reduced delegated tier.
+//
+// - Anything else → no subscription. Notably origin_type='autopilot' is
+// excluded: an autopilot already has an explicitly configured
+// autopilot_subscriber template, and that list — not the member who happened
+// to arm the trigger — is the intended audience for its issues. Degraded
+// attribution (owner_fallback / unattributed) is excluded for the same
+// reason it is degraded: we do not fabricate a human to notify.
+func DelegatedSubscriber(f SubscriptionFacts) (pgtype.UUID, string, bool) {
+ if f.CreatorType != "agent" || !f.OriginOriginator.Valid {
+ return pgtype.UUID{}, "", false
+ }
+ switch f.OriginType {
+ case "quick_create":
+ return f.OriginOriginator, "creator", true
+ case "agent_create":
+ return f.OriginOriginator, "delegated", true
+ default:
+ return pgtype.UUID{}, "", false
+ }
+}
+
// OwnerFallback degrades an UNATTRIBUTED result to owner_fallback (MUL-4302 §3.5):
// the agent owner becomes the accountable human so no run is left without one, but
// this is a DEGRADED label (Source.Precise() == false) and must be surfaced
diff --git a/server/internal/attribution/delegated_subscriber_test.go b/server/internal/attribution/delegated_subscriber_test.go
new file mode 100644
index 0000000000..eee4b67dda
--- /dev/null
+++ b/server/internal/attribution/delegated_subscriber_test.go
@@ -0,0 +1,103 @@
+package attribution
+
+import (
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+// TestDelegatedSubscriber_AgentCreateInheritsHuman is the core MUL-5483 case:
+// an agent files a sub-issue while running on a human's behalf, so that human
+// inherits visibility of it under the reduced 'delegated' tier.
+func TestDelegatedSubscriber_AgentCreateInheritsHuman(t *testing.T) {
+ got, reason, ok := DelegatedSubscriber(SubscriptionFacts{
+ CreatorType: "agent",
+ OriginType: "agent_create",
+ OriginOriginator: human,
+ })
+
+ if !ok {
+ t.Fatal("expected an agent_create issue with a resolved originator to subscribe someone")
+ }
+ if got != human {
+ t.Fatalf("subscriber = %v, want the origin task's human %v", got, human)
+ }
+ if reason != "delegated" {
+ t.Fatalf("reason = %q, want delegated", reason)
+ }
+}
+
+// TestDelegatedSubscriber_QuickCreateIsDirectIntent locks in the deliberate
+// asymmetry: the quick-create human asked for THAT issue by name, so it keeps
+// the direct 'creator' tier and full notifications. Collapsing it into
+// 'delegated' would quietly downgrade an existing flow.
+func TestDelegatedSubscriber_QuickCreateIsDirectIntent(t *testing.T) {
+ got, reason, ok := DelegatedSubscriber(SubscriptionFacts{
+ CreatorType: "agent",
+ OriginType: "quick_create",
+ OriginOriginator: human,
+ })
+
+ if !ok {
+ t.Fatal("expected a quick_create issue to subscribe its requester")
+ }
+ if got != human {
+ t.Fatalf("subscriber = %v, want %v", got, human)
+ }
+ if reason != "creator" {
+ t.Fatalf("reason = %q, want creator — quick create is direct human intent", reason)
+ }
+}
+
+// TestDelegatedSubscriber_AutopilotExcluded: an autopilot has an explicitly
+// configured subscriber template, and THAT list is the intended audience for
+// its issues. Subscribing whoever armed the trigger to every issue the rule
+// ever spawns would be a different product decision, made silently.
+func TestDelegatedSubscriber_AutopilotExcluded(t *testing.T) {
+ if _, _, ok := DelegatedSubscriber(SubscriptionFacts{
+ CreatorType: "agent",
+ OriginType: "autopilot",
+ OriginOriginator: human,
+ }); ok {
+ t.Fatal("autopilot issues must not take a delegated subscription")
+ }
+}
+
+// TestDelegatedSubscriber_NoHumanNoSubscription: degraded attribution
+// (owner_fallback / unattributed) leaves no originator. We surface that as "no
+// human resolved" rather than fabricating one to notify.
+func TestDelegatedSubscriber_NoHumanNoSubscription(t *testing.T) {
+ if _, _, ok := DelegatedSubscriber(SubscriptionFacts{
+ CreatorType: "agent",
+ OriginType: "agent_create",
+ OriginOriginator: pgtype.UUID{},
+ }); ok {
+ t.Fatal("an unattributed origin task must not produce a subscriber")
+ }
+}
+
+// TestDelegatedSubscriber_MemberCreatedIssueUnaffected: a human-created issue
+// already subscribes its human through the ordinary 'creator' rule. Firing
+// here too would write a second, wrong-tier row for the same person.
+func TestDelegatedSubscriber_MemberCreatedIssueUnaffected(t *testing.T) {
+ if _, _, ok := DelegatedSubscriber(SubscriptionFacts{
+ CreatorType: "member",
+ OriginType: "agent_create",
+ OriginOriginator: human,
+ }); ok {
+ t.Fatal("member-created issues must not take a delegated subscription")
+ }
+}
+
+// TestDelegatedSubscriber_UnknownOriginIsInert guards the open-ended origin
+// vocabulary: a newly-modeled origin type must not silently start subscribing
+// people before someone decides that is what it should do.
+func TestDelegatedSubscriber_UnknownOriginIsInert(t *testing.T) {
+ if _, _, ok := DelegatedSubscriber(SubscriptionFacts{
+ CreatorType: "agent",
+ OriginType: "some_future_origin",
+ OriginOriginator: human,
+ }); ok {
+ t.Fatal("an unrecognized origin_type must not subscribe anyone")
+ }
+}
diff --git a/server/internal/handler/subscriber.go b/server/internal/handler/subscriber.go
index ee2996a415..9729d861a0 100644
--- a/server/internal/handler/subscriber.go
+++ b/server/internal/handler/subscriber.go
@@ -1,10 +1,14 @@
package handler
import (
+ "context"
"encoding/json"
+ "errors"
"net/http"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -84,7 +88,10 @@ func (h *Handler) SubscribeToIssue(w http.ResponseWriter, r *http.Request) {
return
}
- err := h.Queries.AddIssueSubscriber(r.Context(), db.AddIssueSubscriberParams{
+ // Explicit action, so this CLEARS any earlier opt-out tombstone — the user
+ // is overriding their own unsubscribe. Rule-driven subscribes deliberately
+ // cannot do that (see AddIssueSubscriber).
+ err := h.Queries.SubscribeToIssueExplicitly(r.Context(), db.SubscribeToIssueExplicitlyParams{
IssueID: issue.ID,
UserType: targetUserType,
UserID: parseUUID(targetUserID),
@@ -108,6 +115,26 @@ func (h *Handler) SubscribeToIssue(w http.ResponseWriter, r *http.Request) {
// UnsubscribeFromIssue removes a user's subscription from an issue.
// If request body contains user_id, unsubscribes that user; otherwise unsubscribes the caller.
func (h *Handler) UnsubscribeFromIssue(w http.ResponseWriter, r *http.Request) {
+ h.unsubscribeFromIssue(w, r, false)
+}
+
+// UnsubscribeFromIssueSubtree leaves this issue AND every descendant, and —
+// via the ancestor opt-out check the delegated rule runs — keeps future
+// children of this tree from re-subscribing the user (MUL-5483).
+//
+// This is a SEPARATE ROUTE rather than a flag on /unsubscribe on purpose.
+// Frontend staging deploys automatically on merge while backend staging is
+// deployed by hand, so a new client routinely talks to an older server. A
+// server that predates this feature decodes an unknown "subtree": true into
+// nothing, unsubscribes the root only, and answers 200 — the user is told the
+// whole tree is muted while every existing and future child keeps notifying.
+// An unknown ROUTE 404s instead, so the client fails loudly and the user can
+// retry rather than trusting a silent no-op.
+func (h *Handler) UnsubscribeFromIssueSubtree(w http.ResponseWriter, r *http.Request) {
+ h.unsubscribeFromIssue(w, r, true)
+}
+
+func (h *Handler) unsubscribeFromIssue(w http.ResponseWriter, r *http.Request, subtree bool) {
issueID := chi.URLParam(r, "id")
issue, ok := h.loadIssueForUser(w, r, issueID)
if !ok {
@@ -139,21 +166,116 @@ func (h *Handler) UnsubscribeFromIssue(w http.ResponseWriter, r *http.Request) {
return
}
- err := h.Queries.RemoveIssueSubscriber(r.Context(), db.RemoveIssueSubscriberParams{
+ // Canonicalize before the target reaches either the advisory lock or a
+ // broadcast. The lock keys on the UUID value, and clients dedupe on the
+ // user_id string, so an uppercase request must not spell either one
+ // differently from the delegated rule's canonical form
+ // (MUL-5483 review round 8).
+ targetUserID = uuidToString(parseUUID(targetUserID))
+
+ // Every issue this call actually left. The subtree variant reports the whole
+ // set so each one gets its own broadcast: a client with a CHILD issue open
+ // never sees the root's event, and would otherwise keep showing a
+ // subscription the server has already retired.
+ removed := []string{issueID}
+ if subtree {
+ // A subtree opt-out is only meaningful if it also covers children the
+ // agent files a moment later, so it must not interleave with the
+ // delegated rule's eligibility check. Both take the same
+ // (workspace, user) lock for the length of their transaction; without
+ // it a child created between the tombstone write and the rule's read
+ // comes back as an active watcher (MUL-5483 review round 7).
+ ids, err := h.unsubscribeSubtreeSerialized(r.Context(), workspaceID, issue.ID, targetUserType, targetUserID)
+ if errors.Is(err, errTargetNoLongerMember) {
+ writeError(w, http.StatusForbidden, "target user is not a member of this workspace")
+ return
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to unsubscribe")
+ return
+ }
+ removed = removed[:0]
+ for _, id := range ids {
+ removed = append(removed, uuidToString(id))
+ }
+ } else if err := h.Queries.RemoveIssueSubscriber(r.Context(), db.RemoveIssueSubscriberParams{
IssueID: issue.ID,
UserType: targetUserType,
UserID: parseUUID(targetUserID),
- })
- if err != nil {
+ }); err != nil {
writeError(w, http.StatusInternalServerError, "failed to unsubscribe")
return
}
- h.publish(protocol.EventSubscriberRemoved, workspaceID, callerActorType, callerActorID, map[string]any{
- "issue_id": issueID,
- "user_type": targetUserType,
- "user_id": targetUserID,
- })
+ for _, id := range removed {
+ h.publish(protocol.EventSubscriberRemoved, workspaceID, callerActorType, callerActorID, map[string]any{
+ "issue_id": id,
+ "user_type": targetUserType,
+ "user_id": targetUserID,
+ })
+ }
writeJSON(w, http.StatusOK, map[string]bool{"subscribed": false})
}
+
+// errTargetNoLongerMember reports that the target left the workspace between
+// the handler's pre-check and the serialized write, so the caller can answer
+// 403 exactly as the pre-check would have.
+var errTargetNoLongerMember = errors.New("target user is no longer a workspace member")
+
+// unsubscribeSubtreeSerialized tombstones the tree inside the same
+// (workspace, user) serialization boundary the delegated auto-subscribe rule
+// uses, and returns every issue it actually retired.
+func (h *Handler) unsubscribeSubtreeSerialized(
+ ctx context.Context, workspaceID string, rootID pgtype.UUID, userType, userID string,
+) ([]pgtype.UUID, error) {
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback(ctx)
+ qtx := h.Queries.WithTx(tx)
+
+ if err := qtx.LockSubscriberWrites(ctx, db.LockSubscriberWritesParams{
+ WorkspaceID: parseUUID(workspaceID),
+ UserID: parseUUID(userID),
+ }); err != nil {
+ return nil, err
+ }
+
+ // The membership pre-check in the caller ran against its own snapshot,
+ // before this transaction existed — it describes the past. A revoke that
+ // commits in between clears this user's subscriptions and deletes their
+ // member row, and writing a tombstone behind it would leave an opt-out that
+ // outlives the membership and is inherited on re-invite. Re-assert it here,
+ // holding the row, now that the lock guarantees no revoke can interleave
+ // (MUL-5483 review round 8).
+ //
+ // Members only: an agent target has no member row, and revoke's subscription
+ // cleanup is member-scoped, so the outlives-membership problem does not
+ // arise for agents.
+ if userType == "member" {
+ if _, err := qtx.LockActiveMember(ctx, db.LockActiveMemberParams{
+ UserID: parseUUID(userID),
+ WorkspaceID: parseUUID(workspaceID),
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, errTargetNoLongerMember
+ }
+ return nil, err
+ }
+ }
+
+ ids, err := qtx.UnsubscribeFromIssueSubtree(ctx, db.UnsubscribeFromIssueSubtreeParams{
+ ID: rootID,
+ UserType: userType,
+ UserID: parseUUID(userID),
+ })
+ if err != nil {
+ return nil, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return nil, err
+ }
+ return ids, nil
+}
diff --git a/server/internal/handler/subscriber_revoke_race_test.go b/server/internal/handler/subscriber_revoke_race_test.go
new file mode 100644
index 0000000000..1a9cf183a8
--- /dev/null
+++ b/server/internal/handler/subscriber_revoke_race_test.go
@@ -0,0 +1,164 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestSubtreeUnsubscribe_LosesToConcurrentRevoke covers MUL-5483 review round 8,
+// finding 2.
+//
+// The handler validated membership from its own MVCC snapshot and only opened
+// the serialized transaction afterwards, while UnsubscribeFromIssueSubtree
+// upserts the root tombstone unconditionally. So:
+//
+// subtree request reads "still a member" → revoke takes the lock, deletes
+// their subscriptions and their member row, commits → subtree finally gets
+// the lock and writes a fresh tombstone
+//
+// leaving an opt-out that outlives the membership. Because a tombstone means
+// "this person chose to leave this issue" and is never resurrected by a rule,
+// re-inviting them silently inherits it: the delegated rule refuses to
+// subscribe them to a tree they never opted out of.
+//
+// Re-asserting membership inside the transaction, after the lock, is what makes
+// the losing request a no-op instead.
+func TestSubtreeUnsubscribe_LosesToConcurrentRevoke(t *testing.T) {
+ ctx := context.Background()
+
+ email := "[email protected]"
+ testPool.Exec(ctx, `DELETE FROM "user" WHERE email = $1`, email)
+ var userID string
+ if err := testPool.QueryRow(ctx,
+ `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,
+ "Subtree Revoke Race", email,
+ ).Scan(&userID); err != nil {
+ t.Fatalf("create user: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM "user" WHERE email = $1`, email)
+ })
+
+ if _, err := testPool.Exec(ctx,
+ `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')`,
+ testWorkspaceID, userID,
+ ); err != nil {
+ t.Fatalf("add member: %v", err)
+ }
+
+ issueID := createRaceIssue(t)
+
+ // The member is subscribed, as the delegated rule would have left them.
+ if _, err := testHandler.Queries.AddIssueSubscriber(ctx, db.AddIssueSubscriberParams{
+ IssueID: parseUUID(issueID),
+ UserType: "member",
+ UserID: parseUUID(userID),
+ Reason: "delegated",
+ }); err != nil {
+ t.Fatalf("seed subscriber: %v", err)
+ }
+
+ // A revoke is in flight: it holds the serialization lock, has already
+ // cleared this member's subscriptions and deleted the member row, and has
+ // NOT committed.
+ revokeTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin revoke tx: %v", err)
+ }
+ defer revokeTx.Rollback(context.Background())
+ rq := testHandler.Queries.WithTx(revokeTx)
+
+ if err := rq.LockSubscriberWrites(ctx, db.LockSubscriberWritesParams{
+ WorkspaceID: parseUUID(testWorkspaceID),
+ UserID: parseUUID(userID),
+ }); err != nil {
+ t.Fatalf("revoke lock: %v", err)
+ }
+ if err := rq.DeleteSubscriptionsByMember(ctx, db.DeleteSubscriptionsByMemberParams{
+ WorkspaceID: parseUUID(testWorkspaceID),
+ UserID: parseUUID(userID),
+ }); err != nil {
+ t.Fatalf("revoke cleanup: %v", err)
+ }
+ if _, err := revokeTx.Exec(ctx,
+ `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`,
+ testWorkspaceID, userID,
+ ); err != nil {
+ t.Fatalf("revoke member delete: %v", err)
+ }
+
+ // The subtree unsubscribe arrives now, while the revoke is still open. Its
+ // pre-check sees a member that is about to stop existing.
+ done := make(chan int, 1)
+ go func() {
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues/"+issueID+"/unsubscribe/subtree", map[string]any{
+ "user_id": userID,
+ "user_type": "member",
+ })
+ req = withURLParam(req, "id", issueID)
+ testHandler.UnsubscribeFromIssueSubtree(w, req)
+ done <- w.Code
+ }()
+
+ select {
+ case code := <-done:
+ t.Fatalf("subtree unsubscribe completed (status %d) while the revoke still held the lock", code)
+ case <-time.After(400 * time.Millisecond):
+ }
+
+ if err := revokeTx.Commit(context.Background()); err != nil {
+ t.Fatalf("commit revoke: %v", err)
+ }
+
+ select {
+ case code := <-done:
+ if code != http.StatusForbidden {
+ t.Fatalf("expected 403 once the target stopped being a member, got %d", code)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("subtree unsubscribe never returned after the revoke committed")
+ }
+
+ // The real assertion: revoke's cleanup must be the final state. A tombstone
+ // here would outlive the membership and be inherited on re-invite.
+ var rows int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*) FROM issue_subscriber s
+ JOIN issue i ON i.id = s.issue_id
+ WHERE i.workspace_id = $1 AND s.user_type = 'member' AND s.user_id = $2
+ `, testWorkspaceID, userID).Scan(&rows); err != nil {
+ t.Fatalf("count subscriber rows: %v", err)
+ }
+ if rows != 0 {
+ t.Fatalf("revoked member still has %d issue_subscriber row(s); a tombstone written after "+
+ "revoke is inherited when they are re-invited and suppresses future delegated subscriptions", rows)
+ }
+}
+
+func createRaceIssue(t *testing.T) string {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "subtree revoke race",
+ })
+ testHandler.CreateIssue(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var issue IssueResponse
+ json.NewDecoder(w.Body).Decode(&issue)
+ t.Cleanup(func() {
+ dw := httptest.NewRecorder()
+ dreq := newRequest("DELETE", "/api/issues/"+issue.ID, nil)
+ dreq = withURLParam(dreq, "id", issue.ID)
+ testHandler.DeleteIssue(dw, dreq)
+ })
+ return issue.ID
+}
diff --git a/server/internal/handler/subscriber_subtree_endpoint_test.go b/server/internal/handler/subscriber_subtree_endpoint_test.go
new file mode 100644
index 0000000000..f6f7c235b9
--- /dev/null
+++ b/server/internal/handler/subscriber_subtree_endpoint_test.go
@@ -0,0 +1,142 @@
+package handler
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Mixed-version contract for subtree unsubscribe (MUL-5483 review round 6,
+// finding 1).
+//
+// Web/desktop staging deploys automatically when a PR merges; the backend is
+// deployed by hand. A new client therefore routinely runs against a server
+// that predates whatever it just learned to send. Subtree unsubscribe was
+// originally a `subtree: true` FIELD on POST /unsubscribe — and a field is
+// exactly the wrong carrier for a capability across that skew, because Go's
+// json.Decode ignores unknown fields: the old server would unsubscribe the
+// root, answer 200, and the user would be told the whole tree was muted while
+// every existing and future child kept notifying them.
+//
+// Moving it to its own ROUTE converts that silent wrong answer into a 404 the
+// client can surface. These tests pin both halves of that contract.
+
+// TestUnsubscribeEndpoints_SubtreeIsASeparateRoute pins the shape the fix
+// depends on: the shared endpoint must have NO subtree behavior of its own, so
+// that an old server and a new server answer a plain /unsubscribe identically.
+func TestUnsubscribeEndpoints_SubtreeIsASeparateRoute(t *testing.T) {
+ parentID, childID := createSubscriberTreeFixture(t)
+
+ subscribeTo(t, parentID)
+ subscribeTo(t, childID)
+
+ // A body field named "subtree" must be inert on the shared endpoint. If it
+ // ever regains meaning here, an old backend and a new backend disagree
+ // about what the same request does — which is the whole defect.
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues/"+parentID+"/unsubscribe", map[string]any{
+ "subtree": true,
+ })
+ req = withURLParam(req, "id", parentID)
+ testHandler.UnsubscribeFromIssue(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UnsubscribeFromIssue: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ if isSubscriberOf(t, parentID) {
+ t.Fatal("the plain endpoint must still unsubscribe the issue it targets")
+ }
+ if !isSubscriberOf(t, childID) {
+ t.Fatal("a 'subtree' body field must be INERT on POST /unsubscribe: " +
+ "if it works here, an older backend silently ignoring it is indistinguishable from success")
+ }
+}
+
+// TestUnsubscribeEndpoints_SubtreeRouteLeavesDescendants is the positive half:
+// the dedicated route does reach descendants, so the capability really did
+// move rather than disappear.
+func TestUnsubscribeEndpoints_SubtreeRouteLeavesDescendants(t *testing.T) {
+ parentID, childID := createSubscriberTreeFixture(t)
+
+ subscribeTo(t, parentID)
+ subscribeTo(t, childID)
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues/"+parentID+"/unsubscribe/subtree", nil)
+ req = withURLParam(req, "id", parentID)
+ testHandler.UnsubscribeFromIssueSubtree(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UnsubscribeFromIssueSubtree: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ if isSubscriberOf(t, parentID) {
+ t.Fatal("subtree unsubscribe must leave the root issue")
+ }
+ if isSubscriberOf(t, childID) {
+ t.Fatal("subtree unsubscribe must leave descendants too")
+ }
+}
+
+// --- fixtures ---
+
+// createSubscriberTreeFixture builds a parent issue with one child and returns
+// both ids, cleaning up after the test.
+func createSubscriberTreeFixture(t *testing.T) (parentID, childID string) {
+ t.Helper()
+
+ create := func(title string, parent *string) string {
+ w := httptest.NewRecorder()
+ body := map[string]any{"title": title}
+ if parent != nil {
+ body["parent_issue_id"] = *parent
+ }
+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, body)
+ testHandler.CreateIssue(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateIssue(%s): expected 201, got %d: %s", title, w.Code, w.Body.String())
+ }
+ var issue IssueResponse
+ json.NewDecoder(w.Body).Decode(&issue)
+ return issue.ID
+ }
+
+ parentID = create("subtree endpoint parent", nil)
+ childID = create("subtree endpoint child", &parentID)
+
+ t.Cleanup(func() {
+ for _, id := range []string{childID, parentID} {
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/issues/"+id, nil)
+ req = withURLParam(req, "id", id)
+ testHandler.DeleteIssue(w, req)
+ }
+ })
+ return parentID, childID
+}
+
+func subscribeTo(t *testing.T, issueID string) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues/"+issueID+"/subscribe", nil)
+ req = withURLParam(req, "id", issueID)
+ testHandler.SubscribeToIssue(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("SubscribeToIssue(%s): expected 200, got %d: %s", issueID, w.Code, w.Body.String())
+ }
+}
+
+func isSubscriberOf(t *testing.T, issueID string) bool {
+ t.Helper()
+ subscribed, err := testHandler.Queries.IsIssueSubscriber(t.Context(), db.IsIssueSubscriberParams{
+ IssueID: parseUUID(issueID),
+ UserType: "member",
+ UserID: parseUUID(testUserID),
+ })
+ if err != nil {
+ t.Fatalf("IsIssueSubscriber(%s): %v", issueID, err)
+ }
+ return subscribed
+}
diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.go
index a0823b2096..5ef3886072 100644
--- a/server/internal/handler/workspace_revoke.go
+++ b/server/internal/handler/workspace_revoke.go
@@ -50,6 +50,19 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userID
qtx := h.Queries.WithTx(tx)
+ // Taken FIRST, before this tx touches member or issue_subscriber. The
+ // delegated auto-subscribe rule takes the same (workspace, user) lock, so
+ // a run that is mid-decomposition cannot slip a new subscriber row in
+ // between this tx's membership delete and its subscription cleanup below.
+ // First also means every holder acquires it in the same order, so these
+ // paths cannot deadlock against each other (MUL-5483 review round 7).
+ if err := qtx.LockSubscriberWrites(ctx, db.LockSubscriberWritesParams{
+ WorkspaceID: workspaceID,
+ UserID: userID,
+ }); err != nil {
+ return empty, err
+ }
+
runtimes, err := qtx.ListAgentRuntimesByOwner(ctx, db.ListAgentRuntimesByOwnerParams{
WorkspaceID: workspaceID,
OwnerID: userID,
@@ -151,6 +164,18 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userID
return empty, err
}
+ // issue_subscriber carries no FK either (same MUL-3515 rule as the two
+ // prunes above), and MUL-5483 gave agents a path that writes member
+ // subscriber rows on their own initiative. Dropping them in this tx is what
+ // stops a departed member from accruing inbox rows, and stops a re-invite
+ // from silently restoring visibility of everything they used to watch.
+ if err := qtx.DeleteSubscriptionsByMember(ctx, db.DeleteSubscriptionsByMemberParams{
+ WorkspaceID: workspaceID,
+ UserID: userID,
+ }); err != nil {
+ return empty, err
+ }
+
// Member row deletion lives inside the same tx so a successful revoke is
// never followed by a failed member-delete (which would leave the user
// still a member with a dead runtime), and a failed revoke never leaves
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index 03831e0e16..c4aeaace42 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -653,7 +653,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi
return fmt.Errorf("list autopilot subscribers: %w", err)
}
for _, sub := range templateSubs {
- if err := qtx.AddIssueSubscriber(ctx, db.AddIssueSubscriberParams{
+ if _, err := qtx.AddIssueSubscriber(ctx, db.AddIssueSubscriberParams{
IssueID: issue.ID,
UserType: sub.UserType,
UserID: sub.UserID,
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 93341dd9b8..d7ed240650 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -4777,38 +4777,17 @@ func (s *TaskService) notifyQuickCreateCompleted(ctx context.Context, task db.Ag
)
}
- // Subscribe the requester so they receive notifications for follow-up
- // comments and updates. The DB row's creator_type/creator_id is the
- // agent (it ran the CLI), but the human who triggered the quick-create
- // is the semantic creator from a UX perspective — without this they
- // only see the one-shot completion inbox and miss everything after.
- // Best-effort: log on failure but don't block the inbox notification.
- if err := s.Queries.AddIssueSubscriber(ctx, db.AddIssueSubscriberParams{
- IssueID: issue.ID,
- UserType: "member",
- UserID: requesterID,
- Reason: "creator",
- }); err != nil {
- slog.Warn("quick-create completion: subscribe requester failed",
- "task_id", util.UUIDToString(task.ID),
- "issue_id", util.UUIDToString(issue.ID),
- "requester_id", qc.RequesterID,
- "error", err,
- )
- } else {
- s.Bus.Publish(events.Event{
- Type: protocol.EventSubscriberAdded,
- WorkspaceID: qc.WorkspaceID,
- ActorType: "agent",
- ActorID: util.UUIDToString(task.AgentID),
- Payload: map[string]any{
- "issue_id": util.UUIDToString(issue.ID),
- "user_type": "member",
- "user_id": qc.RequesterID,
- "reason": "creator",
- },
- })
- }
+ // Subscribing the requester used to happen here, at completion. It now
+ // happens at issue-creation time in the shared delegated-subscriber rule
+ // (cmd/server/subscriber_listeners.go → subscribeDelegatedHuman), which
+ // resolves the human from origin_type='quick_create' + the origin task's
+ // originator_user_id — the same origin waterfall attribution uses.
+ //
+ // This was one of three separate hand-rolled fixes for "an agent created
+ // this issue and no human is subscribed" (quick-create here, the autopilot
+ // subscriber template, and — missing entirely until MUL-5483 — ordinary
+ // agent-created sub-issues). Keeping a second write here would leave the
+ // same decision encoded in two places that can drift.
prefix := s.getIssuePrefix(workspaceID)
identifier := fmt.Sprintf("%s-%d", prefix, issue.Number)
details, _ := json.Marshal(map[string]any{
diff --git a/server/migrations/249_issue_subscriber_delegated.down.sql b/server/migrations/249_issue_subscriber_delegated.down.sql
new file mode 100644
index 0000000000..2be4eb68d0
--- /dev/null
+++ b/server/migrations/249_issue_subscriber_delegated.down.sql
@@ -0,0 +1,19 @@
+-- Drop the tombstone first: rows that were opted out become plain absences
+-- again, which is what the pre-235 code means by "not subscribed".
+DELETE FROM issue_subscriber WHERE unsubscribed_at IS NOT NULL;
+ALTER TABLE issue_subscriber DROP COLUMN unsubscribed_at;
+
+-- 'delegated' has no pre-235 equivalent. 'manual' is the closest surviving
+-- label (a subscription that is neither creator/assignee nor derived from a
+-- comment or mention) and matches how 120_autopilot_subscriber.down.sql
+-- retires its own added reason.
+UPDATE issue_subscriber SET reason = 'manual' WHERE reason = 'delegated';
+
+-- Same two-step as the up migration: the UPDATE above already retired every
+-- 'delegated' row, so the narrowed CHECK holds for all existing data. A
+-- rollback runs under production load by definition, which is exactly when a
+-- full-table ACCESS EXCLUSIVE scan is least affordable.
+ALTER TABLE issue_subscriber DROP CONSTRAINT IF EXISTS issue_subscriber_reason_check;
+ALTER TABLE issue_subscriber ADD CONSTRAINT issue_subscriber_reason_check
+ CHECK (reason IN ('creator', 'assignee', 'commenter', 'mentioned', 'manual', 'autopilot')) NOT VALID;
+ALTER TABLE issue_subscriber VALIDATE CONSTRAINT issue_subscriber_reason_check;
diff --git a/server/migrations/249_issue_subscriber_delegated.up.sql b/server/migrations/249_issue_subscriber_delegated.up.sql
new file mode 100644
index 0000000000..437a5ef520
--- /dev/null
+++ b/server/migrations/249_issue_subscriber_delegated.up.sql
@@ -0,0 +1,36 @@
+-- MUL-5483: an agent creating an issue on a human's behalf must carry that
+-- human's visibility with it.
+--
+-- Two changes, both required by the same rule ("delegation preserves
+-- accountability, so it must preserve visibility"):
+--
+-- 1. reason='delegated' — a new provenance label for "your agent created this
+-- on your behalf". It is deliberately NOT folded into 'creator': the DB
+-- creator really is the agent, and the notification tier for a delegated
+-- subscription is narrower than a direct one (see notification_listeners.go
+-- delegatedNotifTypes). A distinct reason is what lets the UI explain the
+-- subscription and lets delivery treat it differently.
+--
+-- 2. unsubscribed_at — an explicit opt-out tombstone. Until now unsubscribing
+-- was row ABSENCE, which was survivable only because auto-subscribe rules
+-- fired rarely. The delegated rule fires on every agent-created issue, so a
+-- deleted row would be silently re-created by the next rule pass and
+-- unsubscribe would not stick. Auto-subscribe uses ON CONFLICT DO NOTHING,
+-- so a tombstoned row is never resurrected by a rule; only an explicit user
+-- subscribe clears it.
+-- The CHECK is only WIDENED (one new allowed value), so every existing row
+-- already satisfies it. A plain ADD CONSTRAINT would still hold ACCESS
+-- EXCLUSIVE on issue_subscriber for a full scan, blocking subscriber reads and
+-- writes on a hot table for the duration. Use the two-step NOT VALID +
+-- VALIDATE CONSTRAINT pattern from migration 060: the add takes the strong
+-- lock only briefly (no scan), and VALIDATE does the scan under SHARE UPDATE
+-- EXCLUSIVE, which does not block concurrent reads or writes. The constraint
+-- still ends up fully validated, so no un-trusted constraint is left behind.
+ALTER TABLE issue_subscriber DROP CONSTRAINT IF EXISTS issue_subscriber_reason_check;
+ALTER TABLE issue_subscriber ADD CONSTRAINT issue_subscriber_reason_check
+ CHECK (reason IN ('creator', 'assignee', 'commenter', 'mentioned', 'manual', 'autopilot', 'delegated')) NOT VALID;
+ALTER TABLE issue_subscriber VALIDATE CONSTRAINT issue_subscriber_reason_check;
+
+-- Nullable, no default, so this is a catalog-only change in PostgreSQL 11+
+-- and does not rewrite the table.
+ALTER TABLE issue_subscriber ADD COLUMN unsubscribed_at TIMESTAMPTZ;
diff --git a/server/migrations/250_issue_subscriber_opt_out_scope.down.sql b/server/migrations/250_issue_subscriber_opt_out_scope.down.sql
new file mode 100644
index 0000000000..6358abc90f
--- /dev/null
+++ b/server/migrations/250_issue_subscriber_opt_out_scope.down.sql
@@ -0,0 +1 @@
+ALTER TABLE issue_subscriber DROP COLUMN opt_out_scope;
diff --git a/server/migrations/250_issue_subscriber_opt_out_scope.up.sql b/server/migrations/250_issue_subscriber_opt_out_scope.up.sql
new file mode 100644
index 0000000000..39dbaedec6
--- /dev/null
+++ b/server/migrations/250_issue_subscriber_opt_out_scope.up.sql
@@ -0,0 +1,17 @@
+-- MUL-5483 review follow-up: an opt-out has to remember HOW FAR it reaches.
+--
+-- 249 gave every unsubscribe a tombstone, and HasAncestorOptOut treats any
+-- ancestor tombstone as "do not re-subscribe below here". That made the two UI
+-- choices — "unsubscribe from this issue" and "…and its sub-issues" — differ
+-- only for descendants that already exist: both silently suppressed FUTURE
+-- children. Recording the scope is what makes the narrow choice actually narrow.
+--
+-- NULL means "not opted out" (the row is an active subscription). Only a
+-- tombstoned row carries a scope.
+ALTER TABLE issue_subscriber ADD COLUMN opt_out_scope TEXT
+ CHECK (opt_out_scope IN ('issue', 'subtree'));
+
+-- Rows tombstoned by 249 predate the distinction. They were all written by a
+-- path that suppressed future children, so 'subtree' preserves their observed
+-- behavior rather than silently widening or narrowing it.
+UPDATE issue_subscriber SET opt_out_scope = 'subtree' WHERE unsubscribed_at IS NOT NULL;
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index a8a061b2eb..e332a30f4b 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -696,11 +696,13 @@ type IssueReaction struct {
}
type IssueSubscriber struct {
- IssueID pgtype.UUID `json:"issue_id"`
- UserType string `json:"user_type"`
- UserID pgtype.UUID `json:"user_id"`
- Reason string `json:"reason"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ UserType string `json:"user_type"`
+ UserID pgtype.UUID `json:"user_id"`
+ Reason string `json:"reason"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UnsubscribedAt pgtype.Timestamptz `json:"unsubscribed_at"`
+ OptOutScope pgtype.Text `json:"opt_out_scope"`
}
type IssueToLabel struct {
diff --git a/server/pkg/db/generated/subscriber.sql.go b/server/pkg/db/generated/subscriber.sql.go
index 125c840e0e..d696c398ef 100644
--- a/server/pkg/db/generated/subscriber.sql.go
+++ b/server/pkg/db/generated/subscriber.sql.go
@@ -11,10 +11,86 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
-const addIssueSubscriber = `-- name: AddIssueSubscriber :exec
+const addDelegatedSubscriber = `-- name: AddDelegatedSubscriber :execrows
+WITH RECURSIVE ancestors(node_id, parent_id, depth) AS (
+ SELECT root.id, root.parent_issue_id, 0 FROM issue root WHERE root.id = $1
+ UNION ALL
+ SELECT i.id, i.parent_issue_id, a.depth + 1
+ FROM issue i JOIN ancestors a ON i.id = a.parent_id
+),
+active_member AS (
+ SELECT m.user_id FROM member m
+ WHERE m.user_id = $2 AND m.workspace_id = $4
+ FOR SHARE
+)
+INSERT INTO issue_subscriber (issue_id, user_type, user_id, reason)
+SELECT $1, 'member', am.user_id, $3
+FROM active_member am
+WHERE NOT EXISTS (
+ SELECT 1
+ FROM issue_subscriber s
+ JOIN ancestors a ON a.node_id = s.issue_id
+ WHERE s.user_type = 'member' AND s.user_id = $2
+ AND s.unsubscribed_at IS NOT NULL
+ AND (a.depth = 0 OR s.opt_out_scope = 'subtree')
+)
+ON CONFLICT (issue_id, user_type, user_id) DO UPDATE
+SET reason = EXCLUDED.reason
+WHERE issue_subscriber.unsubscribed_at IS NULL
+ AND issue_subscriber.reason = 'delegated'
+ AND EXCLUDED.reason <> 'delegated'
+`
+
+type AddDelegatedSubscriberParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ UserID pgtype.UUID `json:"user_id"`
+ Reason string `json:"reason"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// The delegated rule's write (MUL-5483). Eligibility and insert are ONE
+// statement so they share a snapshot; callers must hold LockSubscriberWrites
+// for the same (workspace, user), which is what makes that snapshot stable.
+//
+// Eligibility is two conditions the previous version checked in separate
+// round trips:
+//
+// 1. active_member — the originator must STILL be a workspace member.
+// originator_user_id is stamped when the task is queued and never
+// revisited, so a revoked member's still-running tasks would otherwise
+// keep filing ghost subscribers. FOR SHARE also blocks a concurrent
+// DELETE of that member row for the rest of this transaction, so the
+// check cannot go stale between here and the insert.
+//
+// 2. NOT EXISTS (...) — the ancestor opt-out walk from HasAncestorOptOut,
+// inlined for the same reason: a subtree tombstone committed between a
+// separate check and this insert would silently undo the user's opt-out
+// on every child the agent files next.
+//
+// ON CONFLICT keeps AddIssueSubscriber's two rules: never resurrect a
+// tombstone, and upgrade an active 'delegated' row when the user becomes
+// directly involved.
+func (q *Queries) AddDelegatedSubscriber(ctx context.Context, arg AddDelegatedSubscriberParams) (int64, error) {
+ result, err := q.db.Exec(ctx, addDelegatedSubscriber,
+ arg.IssueID,
+ arg.UserID,
+ arg.Reason,
+ arg.WorkspaceID,
+ )
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const addIssueSubscriber = `-- name: AddIssueSubscriber :execrows
INSERT INTO issue_subscriber (issue_id, user_type, user_id, reason)
VALUES ($1, $2, $3, $4)
-ON CONFLICT (issue_id, user_type, user_id) DO NOTHING
+ON CONFLICT (issue_id, user_type, user_id) DO UPDATE
+SET reason = EXCLUDED.reason
+WHERE issue_subscriber.unsubscribed_at IS NULL
+ AND issue_subscriber.reason = 'delegated'
+ AND EXCLUDED.reason <> 'delegated'
`
type AddIssueSubscriberParams struct {
@@ -24,20 +100,112 @@ type AddIssueSubscriberParams struct {
Reason string `json:"reason"`
}
-func (q *Queries) AddIssueSubscriber(ctx context.Context, arg AddIssueSubscriberParams) error {
- _, err := q.db.Exec(ctx, addIssueSubscriber,
+// Auto-subscribe path (creator / assignee / commenter / mentioned / autopilot /
+// delegated).
+//
+// Two behaviors are load-bearing here:
+//
+// 1. A tombstoned row is NEVER resurrected. The WHERE on the DO UPDATE fails
+// for an opted-out row, which degrades to DO NOTHING — so unsubscribe still
+// sticks on a tree an agent keeps adding to (MUL-5483).
+//
+// 2. An ACTIVE 'delegated' row is upgraded when the user becomes directly
+// involved (assigned / mentioned / commented). Without this the reason
+// stays 'delegated' forever and someone who is now a real participant keeps
+// getting the reduced delivery tier.
+//
+// Returns rows affected so the caller only broadcasts subscriber:added when an
+// active subscription actually changed. Publishing unconditionally made the
+// frontend insert a subscriber the DB had refused to write.
+func (q *Queries) AddIssueSubscriber(ctx context.Context, arg AddIssueSubscriberParams) (int64, error) {
+ result, err := q.db.Exec(ctx, addIssueSubscriber,
arg.IssueID,
arg.UserType,
arg.UserID,
arg.Reason,
)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const deleteSubscriptionsByMember = `-- name: DeleteSubscriptionsByMember :exec
+DELETE FROM issue_subscriber s
+USING issue i
+WHERE s.issue_id = i.id
+ AND i.workspace_id = $1
+ AND s.user_type = 'member'
+ AND s.user_id = $2
+`
+
+type DeleteSubscriptionsByMemberParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+}
+
+// Drop a departing member's subscriptions across the workspace, in the same tx
+// as the member-row delete (MUL-5483 review round 7).
+//
+// Same application-layer cleanup rule the surrounding revoke path already
+// applies to channel bindings and invocation grants: issue_subscriber carries
+// no FK, so nothing removes these implicitly. Without it a revoked member keeps
+// accruing inbox rows, and re-inviting them silently restores visibility of
+// every issue they used to watch.
+//
+// A hard DELETE, not a tombstone: a tombstone means "this person chose to
+// leave this issue" and would suppress re-subscription if they rejoin, which
+// is not what a workspace revoke means.
+func (q *Queries) DeleteSubscriptionsByMember(ctx context.Context, arg DeleteSubscriptionsByMemberParams) error {
+ _, err := q.db.Exec(ctx, deleteSubscriptionsByMember, arg.WorkspaceID, arg.UserID)
return err
}
+const hasAncestorOptOut = `-- name: HasAncestorOptOut :one
+WITH RECURSIVE ancestors(node_id, parent_id, depth) AS (
+ SELECT root.id, root.parent_issue_id, 0 FROM issue root WHERE root.id = $1
+ UNION ALL
+ SELECT i.id, i.parent_issue_id, a.depth + 1 FROM issue i JOIN ancestors a ON i.id = a.parent_id
+)
+SELECT EXISTS(
+ SELECT 1
+ FROM issue_subscriber s
+ JOIN ancestors a ON a.node_id = s.issue_id
+ WHERE s.user_type = $2 AND s.user_id = $3
+ AND s.unsubscribed_at IS NOT NULL
+ AND (a.depth = 0 OR s.opt_out_scope = 'subtree')
+) AS opted_out
+`
+
+type HasAncestorOptOutParams struct {
+ ID pgtype.UUID `json:"id"`
+ UserType string `json:"user_type"`
+ UserID pgtype.UUID `json:"user_id"`
+}
+
+// True when the user has opted out in a way that should keep them off THIS
+// issue.
+//
+// Two distinct cases, and the distinction is the whole point of opt_out_scope:
+//
+// - a tombstone on this issue itself, at any scope — they left this issue;
+// - a 'subtree'-scoped tombstone on a STRICT ancestor — they left a tree this
+// issue belongs to, so a child created an hour later is still covered.
+//
+// An 'issue'-scoped tombstone on an ancestor deliberately does NOT match: the
+// user declined that one issue, not everything the agent files beneath it.
+func (q *Queries) HasAncestorOptOut(ctx context.Context, arg HasAncestorOptOutParams) (bool, error) {
+ row := q.db.QueryRow(ctx, hasAncestorOptOut, arg.ID, arg.UserType, arg.UserID)
+ var opted_out bool
+ err := row.Scan(&opted_out)
+ return opted_out, err
+}
+
const isIssueSubscriber = `-- name: IsIssueSubscriber :one
SELECT EXISTS(
SELECT 1 FROM issue_subscriber
WHERE issue_id = $1 AND user_type = $2 AND user_id = $3
+ AND unsubscribed_at IS NULL
) AS subscribed
`
@@ -55,8 +223,8 @@ func (q *Queries) IsIssueSubscriber(ctx context.Context, arg IsIssueSubscriberPa
}
const listIssueSubscribers = `-- name: ListIssueSubscribers :many
-SELECT issue_id, user_type, user_id, reason, created_at FROM issue_subscriber
-WHERE issue_id = $1
+SELECT issue_id, user_type, user_id, reason, created_at, unsubscribed_at, opt_out_scope FROM issue_subscriber
+WHERE issue_id = $1 AND unsubscribed_at IS NULL
ORDER BY created_at
`
@@ -75,6 +243,8 @@ func (q *Queries) ListIssueSubscribers(ctx context.Context, issueID pgtype.UUID)
&i.UserID,
&i.Reason,
&i.CreatedAt,
+ &i.UnsubscribedAt,
+ &i.OptOutScope,
); err != nil {
return nil, err
}
@@ -86,9 +256,84 @@ func (q *Queries) ListIssueSubscribers(ctx context.Context, issueID pgtype.UUID)
return items, nil
}
+const lockActiveMember = `-- name: LockActiveMember :one
+SELECT id FROM member
+WHERE user_id = $1 AND workspace_id = $2
+FOR SHARE
+`
+
+type LockActiveMemberParams struct {
+ UserID pgtype.UUID `json:"user_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Re-assert workspace membership INSIDE a serialized transaction, holding the
+// row so a concurrent revoke cannot complete underneath the caller
+// (MUL-5483 review round 8).
+//
+// The subtree-unsubscribe handler validates membership from its own MVCC
+// snapshot before it opens a transaction, which is only a statement about the
+// past. A revoke that commits in between clears the user's subscriptions and
+// deletes the member row, and the handler would then write a fresh tombstone
+// behind it — leaving an opt-out that outlives the membership and is inherited
+// if the person is ever re-invited.
+func (q *Queries) LockActiveMember(ctx context.Context, arg LockActiveMemberParams) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, lockActiveMember, arg.UserID, arg.WorkspaceID)
+ var id pgtype.UUID
+ err := row.Scan(&id)
+ return id, err
+}
+
+const lockSubscriberWrites = `-- name: LockSubscriberWrites :exec
+SELECT pg_advisory_xact_lock(
+ hashtext(($1::uuid)::text),
+ hashtext(($2::uuid)::text)
+)
+`
+
+type LockSubscriberWritesParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+}
+
+// Transaction-scoped serialization boundary for (workspace, user) subscriber
+// state (MUL-5483 review round 7).
+//
+// Three paths race over the same question — "should this user be an active
+// watcher?" — and each one is a check in one statement followed by a write in
+// another:
+//
+// - the delegated rule: is the user a member / not opted out, then insert;
+// - subtree unsubscribe: tombstone the tree, which must cover children the
+// agent files a moment later;
+// - member revoke: delete the member row and their subscriptions.
+//
+// Row locks cannot close this. The interleaving that breaks the escape hatch
+// inserts a subscriber for an issue that did not exist when the opt-out was
+// written, so there is no row to lock — a phantom, which under READ COMMITTED
+// needs an explicit lock object. Every path above takes THIS lock first, so
+// their lock ordering is identical and they cannot deadlock against each other.
+//
+// Keyed on (workspace, user) rather than the issue: an opt-out is about a
+// person and a tree, and the tree's membership is exactly what is changing.
+//
+// The key is derived from the UUID VALUE, not from however the caller happened
+// to spell it. ::uuid parses the input and the outer ::text renders PostgreSQL's
+// canonical lowercase form, so 'AB…' and 'ab…' — the same UUID everywhere else
+// in this file, and to every membership query — also produce the same lock.
+// Hashing the raw string instead let an uppercase request take a DIFFERENT lock
+// from the canonical holder, which silently reopened the very race this lock
+// exists to close. Casting at the DB boundary keeps that guarantee even if a
+// future caller forgets to canonicalize.
+func (q *Queries) LockSubscriberWrites(ctx context.Context, arg LockSubscriberWritesParams) error {
+ _, err := q.db.Exec(ctx, lockSubscriberWrites, arg.WorkspaceID, arg.UserID)
+ return err
+}
+
const removeIssueSubscriber = `-- name: RemoveIssueSubscriber :exec
-DELETE FROM issue_subscriber
-WHERE issue_id = $1 AND user_type = $2 AND user_id = $3
+UPDATE issue_subscriber
+SET unsubscribed_at = now(), opt_out_scope = 'issue'
+WHERE issue_id = $1 AND user_type = $2 AND user_id = $3 AND unsubscribed_at IS NULL
`
type RemoveIssueSubscriberParams struct {
@@ -97,7 +342,105 @@ type RemoveIssueSubscriberParams struct {
UserID pgtype.UUID `json:"user_id"`
}
+// Leave THIS issue only. Tombstone rather than delete, so auto-subscribe rules
+// can tell "never subscribed" (no row) from "chose to leave" (row with
+// unsubscribed_at). scope='issue' keeps the opt-out from reaching descendants:
+// future children of this issue are still allowed to subscribe the user.
func (q *Queries) RemoveIssueSubscriber(ctx context.Context, arg RemoveIssueSubscriberParams) error {
_, err := q.db.Exec(ctx, removeIssueSubscriber, arg.IssueID, arg.UserType, arg.UserID)
return err
}
+
+const subscribeToIssueExplicitly = `-- name: SubscribeToIssueExplicitly :exec
+INSERT INTO issue_subscriber (issue_id, user_type, user_id, reason)
+VALUES ($1, $2, $3, $4)
+ON CONFLICT (issue_id, user_type, user_id)
+DO UPDATE SET unsubscribed_at = NULL, opt_out_scope = NULL, reason = EXCLUDED.reason
+`
+
+type SubscribeToIssueExplicitlyParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ UserType string `json:"user_type"`
+ UserID pgtype.UUID `json:"user_id"`
+ Reason string `json:"reason"`
+}
+
+// Explicit user action (the Subscribe button). Unlike the rule-driven path this
+// CLEARS an existing opt-out tombstone and its scope: the user is overriding
+// their own earlier unsubscribe, which is the one thing that should bring them
+// back.
+func (q *Queries) SubscribeToIssueExplicitly(ctx context.Context, arg SubscribeToIssueExplicitlyParams) error {
+ _, err := q.db.Exec(ctx, subscribeToIssueExplicitly,
+ arg.IssueID,
+ arg.UserType,
+ arg.UserID,
+ arg.Reason,
+ )
+ return err
+}
+
+const unsubscribeFromIssueSubtree = `-- name: UnsubscribeFromIssueSubtree :many
+WITH RECURSIVE subtree(node_id) AS (
+ SELECT root.id FROM issue root WHERE root.id = $1
+ UNION ALL
+ SELECT i.id FROM issue i JOIN subtree s ON i.parent_issue_id = s.node_id
+),
+retire_descendants AS (
+ UPDATE issue_subscriber sub
+ SET unsubscribed_at = now(), opt_out_scope = 'subtree'
+ WHERE sub.issue_id IN (SELECT node_id FROM subtree WHERE node_id <> $1)
+ AND sub.user_type = $2 AND sub.user_id = $3
+ AND sub.unsubscribed_at IS NULL
+ RETURNING sub.issue_id
+),
+retire_root AS (
+ INSERT INTO issue_subscriber (issue_id, user_type, user_id, reason, unsubscribed_at, opt_out_scope)
+ VALUES ($1, $2, $3, 'manual', now(), 'subtree')
+ ON CONFLICT (issue_id, user_type, user_id)
+ DO UPDATE SET unsubscribed_at = now(), opt_out_scope = 'subtree'
+ RETURNING issue_id
+)
+SELECT issue_id FROM retire_descendants
+UNION ALL
+SELECT issue_id FROM retire_root
+`
+
+type UnsubscribeFromIssueSubtreeParams struct {
+ ID pgtype.UUID `json:"id"`
+ UserType string `json:"user_type"`
+ UserID pgtype.UUID `json:"user_id"`
+}
+
+// Leave an issue AND every descendant in one action. An agent-built tree is
+// the unit a user actually wants to stop watching; leaving 30 sub-issues one
+// at a time is not a real escape hatch.
+//
+// The root gets an UPSERTED tombstone rather than a conditional UPDATE, because
+// "I don't want this tree" has to persist even when the user holds no
+// subscription on the root itself — otherwise the opt-out records nothing and
+// the next child the agent files re-subscribes them. That root tombstone is
+// also what covers FUTURE descendants: HasAncestorOptOut walks up to it and
+// honors it because its scope is 'subtree'.
+//
+// Returns every issue id it actually tombstoned so the caller can broadcast one
+// subscriber:removed per issue; publishing only the root left other open tabs
+// showing a stale subscription on the children.
+func (q *Queries) UnsubscribeFromIssueSubtree(ctx context.Context, arg UnsubscribeFromIssueSubtreeParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, unsubscribeFromIssueSubtree, arg.ID, arg.UserType, arg.UserID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var issue_id pgtype.UUID
+ if err := rows.Scan(&issue_id); err != nil {
+ return nil, err
+ }
+ items = append(items, issue_id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
diff --git a/server/pkg/db/queries/subscriber.sql b/server/pkg/db/queries/subscriber.sql
index b741b576af..fe8ce9f9a4 100644
--- a/server/pkg/db/queries/subscriber.sql
+++ b/server/pkg/db/queries/subscriber.sql
@@ -1,19 +1,242 @@
--- name: AddIssueSubscriber :exec
+-- name: AddIssueSubscriber :execrows
+-- Auto-subscribe path (creator / assignee / commenter / mentioned / autopilot /
+-- delegated).
+--
+-- Two behaviors are load-bearing here:
+--
+-- 1. A tombstoned row is NEVER resurrected. The WHERE on the DO UPDATE fails
+-- for an opted-out row, which degrades to DO NOTHING — so unsubscribe still
+-- sticks on a tree an agent keeps adding to (MUL-5483).
+--
+-- 2. An ACTIVE 'delegated' row is upgraded when the user becomes directly
+-- involved (assigned / mentioned / commented). Without this the reason
+-- stays 'delegated' forever and someone who is now a real participant keeps
+-- getting the reduced delivery tier.
+--
+-- Returns rows affected so the caller only broadcasts subscriber:added when an
+-- active subscription actually changed. Publishing unconditionally made the
+-- frontend insert a subscriber the DB had refused to write.
INSERT INTO issue_subscriber (issue_id, user_type, user_id, reason)
VALUES ($1, $2, $3, $4)
-ON CONFLICT (issue_id, user_type, user_id) DO NOTHING;
+ON CONFLICT (issue_id, user_type, user_id) DO UPDATE
+SET reason = EXCLUDED.reason
+WHERE issue_subscriber.unsubscribed_at IS NULL
+ AND issue_subscriber.reason = 'delegated'
+ AND EXCLUDED.reason <> 'delegated';
+
+-- name: LockSubscriberWrites :exec
+-- Transaction-scoped serialization boundary for (workspace, user) subscriber
+-- state (MUL-5483 review round 7).
+--
+-- Three paths race over the same question — "should this user be an active
+-- watcher?" — and each one is a check in one statement followed by a write in
+-- another:
+--
+-- * the delegated rule: is the user a member / not opted out, then insert;
+-- * subtree unsubscribe: tombstone the tree, which must cover children the
+-- agent files a moment later;
+-- * member revoke: delete the member row and their subscriptions.
+--
+-- Row locks cannot close this. The interleaving that breaks the escape hatch
+-- inserts a subscriber for an issue that did not exist when the opt-out was
+-- written, so there is no row to lock — a phantom, which under READ COMMITTED
+-- needs an explicit lock object. Every path above takes THIS lock first, so
+-- their lock ordering is identical and they cannot deadlock against each other.
+--
+-- Keyed on (workspace, user) rather than the issue: an opt-out is about a
+-- person and a tree, and the tree's membership is exactly what is changing.
+--
+-- The key is derived from the UUID VALUE, not from however the caller happened
+-- to spell it. ::uuid parses the input and the outer ::text renders PostgreSQL's
+-- canonical lowercase form, so 'AB…' and 'ab…' — the same UUID everywhere else
+-- in this file, and to every membership query — also produce the same lock.
+-- Hashing the raw string instead let an uppercase request take a DIFFERENT lock
+-- from the canonical holder, which silently reopened the very race this lock
+-- exists to close. Casting at the DB boundary keeps that guarantee even if a
+-- future caller forgets to canonicalize.
+SELECT pg_advisory_xact_lock(
+ hashtext((sqlc.arg(workspace_id)::uuid)::text),
+ hashtext((sqlc.arg(user_id)::uuid)::text)
+);
+
+-- name: AddDelegatedSubscriber :execrows
+-- The delegated rule's write (MUL-5483). Eligibility and insert are ONE
+-- statement so they share a snapshot; callers must hold LockSubscriberWrites
+-- for the same (workspace, user), which is what makes that snapshot stable.
+--
+-- Eligibility is two conditions the previous version checked in separate
+-- round trips:
+--
+-- 1. active_member — the originator must STILL be a workspace member.
+-- originator_user_id is stamped when the task is queued and never
+-- revisited, so a revoked member's still-running tasks would otherwise
+-- keep filing ghost subscribers. FOR SHARE also blocks a concurrent
+-- DELETE of that member row for the rest of this transaction, so the
+-- check cannot go stale between here and the insert.
+--
+-- 2. NOT EXISTS (...) — the ancestor opt-out walk from HasAncestorOptOut,
+-- inlined for the same reason: a subtree tombstone committed between a
+-- separate check and this insert would silently undo the user's opt-out
+-- on every child the agent files next.
+--
+-- ON CONFLICT keeps AddIssueSubscriber's two rules: never resurrect a
+-- tombstone, and upgrade an active 'delegated' row when the user becomes
+-- directly involved.
+WITH RECURSIVE ancestors(node_id, parent_id, depth) AS (
+ SELECT root.id, root.parent_issue_id, 0 FROM issue root WHERE root.id = $1
+ UNION ALL
+ SELECT i.id, i.parent_issue_id, a.depth + 1
+ FROM issue i JOIN ancestors a ON i.id = a.parent_id
+),
+active_member AS (
+ SELECT m.user_id FROM member m
+ WHERE m.user_id = $2 AND m.workspace_id = $4
+ FOR SHARE
+)
+INSERT INTO issue_subscriber (issue_id, user_type, user_id, reason)
+SELECT $1, 'member', am.user_id, $3
+FROM active_member am
+WHERE NOT EXISTS (
+ SELECT 1
+ FROM issue_subscriber s
+ JOIN ancestors a ON a.node_id = s.issue_id
+ WHERE s.user_type = 'member' AND s.user_id = $2
+ AND s.unsubscribed_at IS NOT NULL
+ AND (a.depth = 0 OR s.opt_out_scope = 'subtree')
+)
+ON CONFLICT (issue_id, user_type, user_id) DO UPDATE
+SET reason = EXCLUDED.reason
+WHERE issue_subscriber.unsubscribed_at IS NULL
+ AND issue_subscriber.reason = 'delegated'
+ AND EXCLUDED.reason <> 'delegated';
+
+-- name: LockActiveMember :one
+-- Re-assert workspace membership INSIDE a serialized transaction, holding the
+-- row so a concurrent revoke cannot complete underneath the caller
+-- (MUL-5483 review round 8).
+--
+-- The subtree-unsubscribe handler validates membership from its own MVCC
+-- snapshot before it opens a transaction, which is only a statement about the
+-- past. A revoke that commits in between clears the user's subscriptions and
+-- deletes the member row, and the handler would then write a fresh tombstone
+-- behind it — leaving an opt-out that outlives the membership and is inherited
+-- if the person is ever re-invited.
+SELECT id FROM member
+WHERE user_id = $1 AND workspace_id = $2
+FOR SHARE;
+
+-- name: DeleteSubscriptionsByMember :exec
+-- Drop a departing member's subscriptions across the workspace, in the same tx
+-- as the member-row delete (MUL-5483 review round 7).
+--
+-- Same application-layer cleanup rule the surrounding revoke path already
+-- applies to channel bindings and invocation grants: issue_subscriber carries
+-- no FK, so nothing removes these implicitly. Without it a revoked member keeps
+-- accruing inbox rows, and re-inviting them silently restores visibility of
+-- every issue they used to watch.
+--
+-- A hard DELETE, not a tombstone: a tombstone means "this person chose to
+-- leave this issue" and would suppress re-subscription if they rejoin, which
+-- is not what a workspace revoke means.
+DELETE FROM issue_subscriber s
+USING issue i
+WHERE s.issue_id = i.id
+ AND i.workspace_id = $1
+ AND s.user_type = 'member'
+ AND s.user_id = $2;
+
+-- name: SubscribeToIssueExplicitly :exec
+-- Explicit user action (the Subscribe button). Unlike the rule-driven path this
+-- CLEARS an existing opt-out tombstone and its scope: the user is overriding
+-- their own earlier unsubscribe, which is the one thing that should bring them
+-- back.
+INSERT INTO issue_subscriber (issue_id, user_type, user_id, reason)
+VALUES ($1, $2, $3, $4)
+ON CONFLICT (issue_id, user_type, user_id)
+DO UPDATE SET unsubscribed_at = NULL, opt_out_scope = NULL, reason = EXCLUDED.reason;
-- name: RemoveIssueSubscriber :exec
-DELETE FROM issue_subscriber
-WHERE issue_id = $1 AND user_type = $2 AND user_id = $3;
+-- Leave THIS issue only. Tombstone rather than delete, so auto-subscribe rules
+-- can tell "never subscribed" (no row) from "chose to leave" (row with
+-- unsubscribed_at). scope='issue' keeps the opt-out from reaching descendants:
+-- future children of this issue are still allowed to subscribe the user.
+UPDATE issue_subscriber
+SET unsubscribed_at = now(), opt_out_scope = 'issue'
+WHERE issue_id = $1 AND user_type = $2 AND user_id = $3 AND unsubscribed_at IS NULL;
+
+-- name: UnsubscribeFromIssueSubtree :many
+-- Leave an issue AND every descendant in one action. An agent-built tree is
+-- the unit a user actually wants to stop watching; leaving 30 sub-issues one
+-- at a time is not a real escape hatch.
+--
+-- The root gets an UPSERTED tombstone rather than a conditional UPDATE, because
+-- "I don't want this tree" has to persist even when the user holds no
+-- subscription on the root itself — otherwise the opt-out records nothing and
+-- the next child the agent files re-subscribes them. That root tombstone is
+-- also what covers FUTURE descendants: HasAncestorOptOut walks up to it and
+-- honors it because its scope is 'subtree'.
+--
+-- Returns every issue id it actually tombstoned so the caller can broadcast one
+-- subscriber:removed per issue; publishing only the root left other open tabs
+-- showing a stale subscription on the children.
+WITH RECURSIVE subtree(node_id) AS (
+ SELECT root.id FROM issue root WHERE root.id = $1
+ UNION ALL
+ SELECT i.id FROM issue i JOIN subtree s ON i.parent_issue_id = s.node_id
+),
+retire_descendants AS (
+ UPDATE issue_subscriber sub
+ SET unsubscribed_at = now(), opt_out_scope = 'subtree'
+ WHERE sub.issue_id IN (SELECT node_id FROM subtree WHERE node_id <> $1)
+ AND sub.user_type = $2 AND sub.user_id = $3
+ AND sub.unsubscribed_at IS NULL
+ RETURNING sub.issue_id
+),
+retire_root AS (
+ INSERT INTO issue_subscriber (issue_id, user_type, user_id, reason, unsubscribed_at, opt_out_scope)
+ VALUES ($1, $2, $3, 'manual', now(), 'subtree')
+ ON CONFLICT (issue_id, user_type, user_id)
+ DO UPDATE SET unsubscribed_at = now(), opt_out_scope = 'subtree'
+ RETURNING issue_id
+)
+SELECT issue_id FROM retire_descendants
+UNION ALL
+SELECT issue_id FROM retire_root;
+
+-- name: HasAncestorOptOut :one
+-- True when the user has opted out in a way that should keep them off THIS
+-- issue.
+--
+-- Two distinct cases, and the distinction is the whole point of opt_out_scope:
+--
+-- * a tombstone on this issue itself, at any scope — they left this issue;
+-- * a 'subtree'-scoped tombstone on a STRICT ancestor — they left a tree this
+-- issue belongs to, so a child created an hour later is still covered.
+--
+-- An 'issue'-scoped tombstone on an ancestor deliberately does NOT match: the
+-- user declined that one issue, not everything the agent files beneath it.
+WITH RECURSIVE ancestors(node_id, parent_id, depth) AS (
+ SELECT root.id, root.parent_issue_id, 0 FROM issue root WHERE root.id = $1
+ UNION ALL
+ SELECT i.id, i.parent_issue_id, a.depth + 1 FROM issue i JOIN ancestors a ON i.id = a.parent_id
+)
+SELECT EXISTS(
+ SELECT 1
+ FROM issue_subscriber s
+ JOIN ancestors a ON a.node_id = s.issue_id
+ WHERE s.user_type = $2 AND s.user_id = $3
+ AND s.unsubscribed_at IS NOT NULL
+ AND (a.depth = 0 OR s.opt_out_scope = 'subtree')
+) AS opted_out;
-- name: ListIssueSubscribers :many
SELECT * FROM issue_subscriber
-WHERE issue_id = $1
+WHERE issue_id = $1 AND unsubscribed_at IS NULL
ORDER BY created_at;
-- name: IsIssueSubscriber :one
SELECT EXISTS(
SELECT 1 FROM issue_subscriber
WHERE issue_id = $1 AND user_type = $2 AND user_id = $3
+ AND unsubscribed_at IS NULL
) AS subscribed;