Skip to content

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

Go

feat(notifications): server reports each subscription's delivery tier (MUL-9360) (#10694)

Jiayuan Zhang30880f03b9be
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.search-workspace.test.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.search-workspace.test.tsx
index 17def03aef..5e9e27324e 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.search-workspace.test.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.search-workspace.test.tsx
@@ -53,6 +53,12 @@ let baseUrl = "";
let queryClient: QueryClient;
const originalDesktopAPI = window.desktopAPI;
const originalScrollIntoView = Element.prototype.scrollIntoView;
+// Every row and route here waits on the real fixture server, which shares its
+// event loop with the whole shell. In CI, turbo runs other packages' suites
+// beside this one, and the first search has queued behind the shell's startup
+// requests for over five seconds.
+const NETWORK_WAIT = { timeout: 15_000 };
+const TEST_TIMEOUT = 60_000;
function payloadFor(path: string, workspace: string): unknown {
if (path === "/api/config") return { feature_flags: {}, allow_signup: false };
@@ -121,7 +127,7 @@ async function notify(workspace: string) {
listener({ slug: workspace, issueKey: workspace === "synthetic-b" ? "B-1" : "A-1" });
}
});
- await waitFor(() => expect(getAppRouter().state.location.pathname).toMatch(new RegExp(`^/${workspace}/(inbox|issues/)`)));
+ await waitFor(() => expect(getAppRouter().state.location.pathname).toMatch(new RegExp(`^/${workspace}/(inbox|issues/)`)), NETWORK_WAIT);
}
async function mountShell() {
@@ -132,7 +138,7 @@ async function mountShell() {
<ReadyShell />
</CoreProvider>,
);
- await waitFor(() => expect(document.querySelector('[data-slot="app-rail"]')).toBeInTheDocument());
+ await waitFor(() => expect(document.querySelector('[data-slot="app-rail"]')).toBeInTheDocument(), NETWORK_WAIT);
}
beforeAll(async () => {
@@ -182,26 +188,26 @@ it("resets completed search rows through a native notification workspace switch"
await mountShell();
await openSearch();
fireEvent.change(input(), { target: { value: "alpha" } });
- await screen.findByRole("option", { name: /Alpha A result/ });
+ await screen.findByRole("option", { name: /Alpha A result/ }, NETWORK_WAIT);
await notify("synthetic-b");
expect(input()).toHaveValue("");
expect(screen.queryByRole("option", { name: /Alpha A result/ })).not.toBeInTheDocument();
fireEvent.change(input(), { target: { value: "alpha" } });
- await screen.findByRole("option", { name: /Alpha B result/ });
+ await screen.findByRole("option", { name: /Alpha B result/ }, NETWORK_WAIT);
expect(requests.some((request) => request.path === "/api/issues/search" && request.workspace === "synthetic-b")).toBe(true);
fireEvent.keyDown(input(), { key: "ArrowDown" });
fireEvent.keyDown(input(), { key: "ArrowUp" });
expect(screen.getByRole("option", { name: /Alpha B result/ })).toHaveAttribute("aria-selected", "true");
fireEvent.keyDown(input(), { key: "Enter" });
- await waitFor(() => expect(getAppRouter().state.location.pathname).toBe("/synthetic-b/issues/B-1"));
-});
+ await waitFor(() => expect(getAppRouter().state.location.pathname).toBe("/synthetic-b/issues/B-1"), NETWORK_WAIT);
+}, TEST_TIMEOUT);
it("cancels an in-flight search when the production router switches workspace", async () => {
await mountShell();
await openSearch();
holdA = true;
fireEvent.change(input(), { target: { value: "alpha" } });
- await waitFor(() => expect(held.length).toBe(2));
+ await waitFor(() => expect(held.length).toBe(2), NETWORK_WAIT);
await notify("synthetic-b");
await act(async () => {
for (const { response, payload } of held.splice(0)) response.end(JSON.stringify(payload));
@@ -209,14 +215,14 @@ it("cancels an in-flight search when the production router switches workspace",
expect(input()).toHaveValue("");
expect(screen.queryByRole("option", { name: /Alpha A result/ })).not.toBeInTheDocument();
fireEvent.change(input(), { target: { value: "alpha" } });
- await screen.findByRole("option", { name: /Alpha B result/ });
-});
+ await screen.findByRole("option", { name: /Alpha B result/ }, NETWORK_WAIT);
+}, TEST_TIMEOUT);
it("resets a returning workspace while preserving same-workspace search navigation", async () => {
await mountShell();
await openSearch();
fireEvent.change(input(), { target: { value: "alpha" } });
- await screen.findByRole("option", { name: /Alpha A result/ });
+ await screen.findByRole("option", { name: /Alpha A result/ }, NETWORK_WAIT);
// Notifications within A preserve the query and its results.
await notify("synthetic-a");
expect(input()).toHaveValue("alpha");
@@ -224,11 +230,11 @@ it("resets a returning workspace while preserving same-workspace search navigati
await notify("synthetic-b");
expect(input()).toHaveValue("");
fireEvent.change(input(), { target: { value: "alpha" } });
- await screen.findByRole("option", { name: /Alpha B result/ });
+ await screen.findByRole("option", { name: /Alpha B result/ }, NETWORK_WAIT);
await notify("synthetic-a");
expect(input()).toHaveValue("");
expect(screen.queryByRole("option", { name: /Alpha B result/ })).not.toBeInTheDocument();
fireEvent.keyDown(input(), { key: "Escape" });
await openSearch();
expect(input()).toHaveValue("");
-});
+}, TEST_TIMEOUT);
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index 75788597c4..6e9b57777d 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -1092,6 +1092,36 @@ describe("ApiClient schema fallback", () => {
const subs = await client.listIssueSubscribers("issue-1");
expect(subs).toEqual([]);
});
+
+ const subscriber = (delivery?: unknown) => ({
+ issue_id: "issue-1",
+ user_type: "member",
+ user_id: "user-1",
+ reason: "commenter",
+ created_at: "2026-01-01T00:00:00Z",
+ ...(delivery === undefined ? {} : { delivery }),
+ });
+
+ it("keeps each valid delivery tier", async () => {
+ stubFetchJson(["all", "key_updates", "delegated"].map(subscriber));
+ const client = new ApiClient("https://api.example.test");
+ const subs = await client.listIssueSubscribers("issue-1");
+ expect(subs.map((s) => s.delivery)).toEqual(["all", "key_updates", "delegated"]);
+ });
+
+ it.each([
+ { name: "missing", delivery: undefined },
+ { name: "unknown", delivery: "muted" },
+ { name: "malformed", delivery: 42 },
+ { name: "null", delivery: null },
+ ])("keeps the row without a tier when delivery is $name", async ({ delivery }) => {
+ stubFetchJson([subscriber(delivery)]);
+ const client = new ApiClient("https://api.example.test");
+ const subs = await client.listIssueSubscribers("issue-1");
+ expect(subs).toHaveLength(1);
+ expect(subs[0]).toMatchObject({ user_id: "user-1", reason: "commenter" });
+ expect(subs[0]!.delivery).toBeUndefined();
+ });
});
describe("listChildIssues", () => {
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 092595a49c..3b3dad2345 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -2081,6 +2081,9 @@ const SubscriberSchema = z.object({
user_id: z.string(),
reason: z.string(),
created_at: z.string(),
+ // An unknown or malformed tier shows no badge; it must not drop the row,
+ // which would read as "not subscribed".
+ delivery: z.enum(["all", "key_updates", "delegated"]).optional().catch(undefined),
}).loose();
export const SubscribersListSchema = z.array(SubscriberSchema);
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index f66ab456d5..9331a3c955 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -1222,7 +1222,8 @@ export function useToggleIssueSubscriber(issueId: string) {
issueKeys.subscribers(issueId),
(old) => {
// An explicit subscribe rewrites an existing row's reason to
- // manual, which lifts it out of the delegated and bystander tiers.
+ // manual. The delivery tier is the server's to report, so it is
+ // dropped until onSettled refetches it.
if (
old?.some(
(s) => s.user_id === userId && s.user_type === userType,
@@ -1230,7 +1231,7 @@ export function useToggleIssueSubscriber(issueId: string) {
)
return old.map((s) =>
s.user_id === userId && s.user_type === userType
- ? { ...s, reason: "manual" as const }
+ ? { ...s, reason: "manual" as const, delivery: undefined }
: s,
);
return [...(old ?? []), temp];
diff --git a/packages/core/notification-preferences/bystander.test.ts b/packages/core/notification-preferences/bystander.test.ts
deleted file mode 100644
index 083d5a67e5..0000000000
--- a/packages/core/notification-preferences/bystander.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { receivesKeyUpdatesOnly } from "./bystander";
-
-const me = "user-me";
-const agents = [
- { id: "agent-mine", owner_id: me },
- { id: "agent-theirs", owner_id: "user-other" },
-];
-
-function check(
- reason: Parameters<typeof receivesKeyUpdatesOnly>[0]["reason"],
- issue: Parameters<typeof receivesKeyUpdatesOnly>[0]["issue"],
- preferences = {},
-) {
- return receivesKeyUpdatesOnly({ reason, issue, userId: me, agents, preferences });
-}
-
-describe("receivesKeyUpdatesOnly", () => {
- it("narrows a passive subscription to someone else's issue", () => {
- expect(check("commenter", { assignee_type: "member", assignee_id: "user-other" })).toBe(true);
- expect(check("creator", { assignee_type: "agent", assignee_id: "agent-theirs" })).toBe(true);
- expect(check("mentioned", { assignee_type: "squad", assignee_id: "squad-1" })).toBe(true);
- });
-
- it("keeps full delivery on the member's own issue or an unassigned one", () => {
- expect(check("commenter", { assignee_type: "member", assignee_id: me })).toBe(false);
- expect(check("creator", { assignee_type: "agent", assignee_id: "agent-mine" })).toBe(false);
- expect(check("creator", { assignee_type: null, assignee_id: null })).toBe(false);
- });
-
- it("keeps full delivery for explicit subscriptions and the all preference", () => {
- const theirs = { assignee_type: "member", assignee_id: "user-other" } as const;
- expect(check("manual", theirs)).toBe(false);
- expect(check("autopilot", theirs)).toBe(false);
- expect(check("delegated", theirs)).toBe(false);
- expect(check("project", theirs)).toBe(false);
- expect(check("commenter", theirs, { others_issues: "all" })).toBe(false);
- });
-
- it("keeps full delivery when the member also watches the project", () => {
- expect(
- receivesKeyUpdatesOnly({
- reason: "commenter",
- projectCovered: true,
- issue: { assignee_type: "member", assignee_id: "user-other" },
- userId: me,
- agents,
- preferences: {},
- }),
- ).toBe(false);
- });
-});
diff --git a/packages/core/notification-preferences/bystander.ts b/packages/core/notification-preferences/bystander.ts
deleted file mode 100644
index 9e7f605ad1..0000000000
--- a/packages/core/notification-preferences/bystander.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import type {
- Agent,
- IssueAssigneeType,
- IssueSubscriber,
- NotificationPreferences,
-} from "../types";
-import { notificationPreferenceValue } from "./patch";
-
-/**
- * Subscriptions picked up as a side effect of acting on an issue. manual and
- * autopilot are explicit and keep every event; delegated has its own tier.
- */
-const BYSTANDER_REASONS: ReadonlySet<IssueSubscriber["reason"]> = new Set([
- "creator",
- "assignee",
- "commenter",
- "mentioned",
-]);
-
-/**
- * Whether the server delivers only key updates of this issue to this member:
- * a passive subscription, on an issue assigned to someone other than them or
- * an agent they own, with "Other people's issues" left at key updates, and
- * no subscription to the issue's project (that path delivers every event).
- * Mirrors deliverToBystander in server/cmd/server/notification_listeners.go.
- */
-export function receivesKeyUpdatesOnly({
- reason,
- projectCovered = false,
- issue,
- userId,
- agents,
- preferences,
-}: {
- reason: IssueSubscriber["reason"] | undefined;
- projectCovered?: boolean;
- issue: { assignee_type?: IssueAssigneeType | null; assignee_id?: string | null };
- userId: string | null | undefined;
- agents: readonly Pick<Agent, "id" | "owner_id">[];
- preferences: NotificationPreferences;
-}): boolean {
- if (!userId || !reason || !BYSTANDER_REASONS.has(reason)) return false;
- if (projectCovered) return false;
- if (notificationPreferenceValue(preferences, "others_issues") === "all") return false;
- if (!issue.assignee_id) return false;
- switch (issue.assignee_type) {
- case "member":
- return issue.assignee_id !== userId;
- case "agent":
- return !agents.some((a) => a.id === issue.assignee_id && a.owner_id === userId);
- default:
- return true;
- }
-}
diff --git a/packages/core/notification-preferences/index.ts b/packages/core/notification-preferences/index.ts
index 87686c0bd9..4b3efba544 100644
--- a/packages/core/notification-preferences/index.ts
+++ b/packages/core/notification-preferences/index.ts
@@ -1,4 +1,3 @@
export * from "./queries";
export * from "./mutations";
export * from "./patch";
-export * from "./bystander";
diff --git a/packages/core/notification-preferences/mutations.test.tsx b/packages/core/notification-preferences/mutations.test.tsx
index 4a5e247df7..87c1a7172b 100644
--- a/packages/core/notification-preferences/mutations.test.tsx
+++ b/packages/core/notification-preferences/mutations.test.tsx
@@ -12,6 +12,7 @@ import type {
NotificationPreferenceResponse,
NotificationPreferences,
} from "../types";
+import { issueKeys } from "../issues/queries";
import { useUpdateNotificationPreferences } from "./mutations";
import { notificationPreferenceKeys } from "./queries";
@@ -261,7 +262,13 @@ describe("useUpdateNotificationPreferences", () => {
preferences: { comments: "muted", updates: "muted" },
});
await waitFor(() => {
- expect(invalidateQueries).toHaveBeenCalledTimes(1);
+ expect(invalidateQueries).toHaveBeenCalledTimes(2);
});
+ // Subscriber lists carry the server's delivery tier, which reads
+ // others_issues, so they refetch with the preferences.
+ expect(invalidateQueries.mock.calls.map(([filters]) => filters?.queryKey)).toEqual([
+ notificationPreferenceKeys.all(WORKSPACE_ID),
+ issueKeys.subscribersAll(),
+ ]);
});
});
diff --git a/packages/core/notification-preferences/mutations.ts b/packages/core/notification-preferences/mutations.ts
index 1b822d526e..f86bdd51cc 100644
--- a/packages/core/notification-preferences/mutations.ts
+++ b/packages/core/notification-preferences/mutations.ts
@@ -7,6 +7,7 @@ import { useCallback, useRef } from "react";
import { api } from "../api";
import { useWorkspaceId } from "../hooks";
import { useRequiredWorkspaceSlug } from "../paths";
+import { issueKeys } from "../issues/queries";
import { notificationPreferenceKeys } from "./queries";
import type {
NotificationPreferences,
@@ -121,6 +122,9 @@ export function useUpdateNotificationPreferences() {
// only after every queued optimistic patch for this workspace finishes.
if (qc.isMutating({ mutationKey }) > 1) return;
qc.invalidateQueries({ queryKey: context?.key ?? mutationKey });
+ // Subscriber lists carry the server's delivery tier, which depends on
+ // these preferences (MUL-9360).
+ qc.invalidateQueries({ queryKey: issueKeys.subscribersAll() });
},
});
diff --git a/packages/core/package.json b/packages/core/package.json
index ea6711d5b8..1517941556 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -81,7 +81,6 @@
"./notification-preferences/queries": "./notification-preferences/queries.ts",
"./notification-preferences/mutations": "./notification-preferences/mutations.ts",
"./notification-preferences/patch": "./notification-preferences/patch.ts",
- "./notification-preferences/bystander": "./notification-preferences/bystander.ts",
"./chat": "./chat/index.ts",
"./chat/queries": "./chat/queries.ts",
"./chat/mutations": "./chat/mutations.ts",
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index 97d05fcf50..d9dc530c76 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -379,6 +379,17 @@ describe("useRealtimeSync — ws instance change", () => {
expect(qc.getQueryState(issueKeys.tasks("parent"))?.isInvalidated).toBe(false);
});
+ it("refetches the issue's subscribers on a reassignment, which can change their delivery tier", () => {
+ const emit = subtreeEvents();
+ qc.setQueryData(issueKeys.subscribers("child"), []);
+ qc.setQueryData(issueKeys.subscribers("other"), []);
+ emit("issue:updated", { priority_changed: true, issue: { id: "child" } });
+ expect(qc.getQueryState(issueKeys.subscribers("child"))?.isInvalidated).toBe(false);
+ emit("issue:updated", { assignee_changed: true, issue: { id: "child" } });
+ expect(qc.getQueryState(issueKeys.subscribers("child"))?.isInvalidated).toBe(true);
+ expect(qc.getQueryState(issueKeys.subscribers("other"))?.isInvalidated).toBe(false);
+ });
+
it("patches matching owning-issue titles across subtree caches without refetching", () => {
const emit = subtreeEvents();
const fetchRuns = vi.fn(async () => []);
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 57bc40a4f0..f4b6eb7328 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -1271,6 +1271,11 @@ export function useRealtimeSync(
task.issue_id === issue.id ? { ...task, issue_title: issue.title } : task,
));
}
+ // Whose issue it is decides each subscriber's delivery tier, and a
+ // reassignment can change that without any subscriber event (MUL-9360).
+ if (payload.assignee_changed) {
+ qc.invalidateQueries({ queryKey: issueKeys.subscribers(issue.id) });
+ }
const wsId = getCurrentWsId();
if (wsId) {
onIssueUpdated(qc, wsId, issue, {
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index d74c8d589b..3e566465b1 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -166,7 +166,7 @@ export type {
TimelineEntry,
AssigneeFrequencyEntry,
} from "./activity";
-export type { IssueSubscriber } from "./subscriber";
+export type { IssueSubscriber, IssueSubscriberDelivery } from "./subscriber";
export type * from "./events";
export type * from "./api";
export type { Attachment } from "./attachment";
diff --git a/packages/core/types/subscriber.ts b/packages/core/types/subscriber.ts
index 2907963c82..d5ecc87c31 100644
--- a/packages/core/types/subscriber.ts
+++ b/packages/core/types/subscriber.ts
@@ -22,6 +22,14 @@ export type IssueSubscriberReason =
| "delegated"
| "project";
+/**
+ * How much of the issue a member subscription actually delivers, as the
+ * server's notification fanout decides it. `key_updates` is the bystander
+ * tier on someone else's issue (MUL-9343); `delegated` is the tier of an issue
+ * an agent created on the member's behalf (MUL-5483).
+ */
+export type IssueSubscriberDelivery = "all" | "key_updates" | "delegated";
+
export interface IssueSubscriber {
issue_id: string;
user_type: "member" | "agent";
@@ -29,9 +37,9 @@ export interface IssueSubscriber {
reason: IssueSubscriberReason;
created_at: string;
/**
- * A direct row whose member also subscribes to the issue's project. The
- * project delivers every event, so the direct reason does not narrow what
- * reaches them.
+ * Absent on agent rows, from servers that predate it, and on rows patched
+ * locally until the list is refetched. Show no tier then rather than
+ * derive one: only the server knows what it delivers.
*/
- project_covered?: boolean;
+ delivery?: IssueSubscriberDelivery;
}
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index b4fc22d609..17de7833e7 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -2422,7 +2422,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
} = useIssueReactions(id, user?.id);
const {
- subscribers, isSubscribed, subscriptionReason, subscriptionProjectCovered, subscriptionKnown,
+ subscribers, isSubscribed, subscriptionReason, subscriptionDelivery, subscriptionKnown,
togglePending, subtreePending,
toggleSubscribe: handleToggleSubscribe, toggleSubscriber, followAllActivity,
unsubscribeFromSubtree: handleUnsubscribeSubtree,
@@ -4082,8 +4082,10 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
{/* 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" && (
+ adding them to things (MUL-5483). The server's delivery
+ tier decides it: a project watcher's delegated row still
+ gets every event (MUL-9360). */}
+ {isSubscribed && subscriptionDelivery === "delegated" && (
<Tooltip>
{/* Quiet surface, not plain body text: this is metadata
explaining a state, and must not read as a second
@@ -4099,10 +4101,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
)}
{isSubscribed && (
<KeyUpdatesSubscriptionBadge
- issue={issue}
- userId={user?.id}
- reason={subscriptionReason}
- projectCovered={subscriptionProjectCovered}
+ delivery={subscriptionDelivery}
pending={togglePending}
onFollowAll={followAllActivity}
/>
diff --git a/packages/views/issues/components/key-updates-subscription-badge.test.tsx b/packages/views/issues/components/key-updates-subscription-badge.test.tsx
index 1b4bf2be3c..b260baf9e5 100644
--- a/packages/views/issues/components/key-updates-subscription-badge.test.tsx
+++ b/packages/views/issues/components/key-updates-subscription-badge.test.tsx
@@ -1,15 +1,11 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@multica/core/i18n/react";
-import { notificationPreferenceKeys } from "@multica/core/notification-preferences/queries";
-import { agentListOptions } from "@multica/core/workspace/queries";
-import type { Agent } from "@multica/core/types";
+import type { IssueSubscriberDelivery } from "@multica/core/types";
import enIssues from "../../locales/en/issues.json";
import { KeyUpdatesSubscriptionBadge } from "./key-updates-subscription-badge";
const push = vi.fn();
-vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-a" }));
vi.mock("@multica/core/paths", () => ({
useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),
}));
@@ -20,87 +16,50 @@ afterEach(() => {
push.mockReset();
});
-const me = "user-me";
-
function renderBadge({
- assignee,
- reason = "commenter",
- projectCovered = false,
- preferences = {},
+ delivery,
onFollowAll = vi.fn(),
}: {
- assignee: { assignee_type: "member" | "agent" | null; assignee_id: string | null };
- reason?: "commenter" | "manual" | "creator";
- projectCovered?: boolean;
- preferences?: Record<string, string>;
+ delivery: IssueSubscriberDelivery | undefined;
onFollowAll?: () => void;
}) {
- const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } });
- qc.setQueryData(notificationPreferenceKeys.all("ws-a"), { workspace_id: "ws-a", preferences });
- qc.setQueryData(agentListOptions("ws-a").queryKey, [{ id: "agent-mine", owner_id: me } as Agent]);
render(
- <QueryClientProvider client={qc}>
- <I18nProvider locale="en" resources={{ en: { issues: enIssues } }}>
- <KeyUpdatesSubscriptionBadge
- issue={assignee}
- userId={me}
- reason={reason}
- projectCovered={projectCovered}
- pending={false}
- onFollowAll={onFollowAll}
- />
- </I18nProvider>
- </QueryClientProvider>,
+ <I18nProvider locale="en" resources={{ en: { issues: enIssues } }}>
+ <KeyUpdatesSubscriptionBadge delivery={delivery} pending={false} onFollowAll={onFollowAll} />
+ </I18nProvider>,
);
}
describe("KeyUpdatesSubscriptionBadge", () => {
- it("offers all activity on someone else's issue", async () => {
+ it("offers all activity when the server delivers key updates only", async () => {
const onFollowAll = vi.fn();
- renderBadge({ assignee: { assignee_type: "member", assignee_id: "user-other" }, onFollowAll });
+ renderBadge({ delivery: "key_updates", onFollowAll });
fireEvent.click(screen.getByRole("button", { name: "Key updates only" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Get all activity" }));
expect(onFollowAll).toHaveBeenCalledOnce();
});
it("links to the default in settings", async () => {
- renderBadge({ assignee: { assignee_type: "member", assignee_id: "user-other" } });
+ renderBadge({ delivery: "key_updates" });
fireEvent.click(screen.getByRole("button", { name: "Key updates only" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Change the default" }));
expect(push).toHaveBeenCalledWith("/acme/settings?tab=notifications&section=others_issues");
});
+ // undefined is a server that predates `delivery`, or a row patched locally
+ // and not yet refetched: no tier is known, so no badge.
it.each([
- { name: "own issue", assignee: { assignee_type: "member" as const, assignee_id: me } },
- { name: "own agent", assignee: { assignee_type: "agent" as const, assignee_id: "agent-mine" } },
- { name: "unassigned", assignee: { assignee_type: null, assignee_id: null } },
- ])("stays hidden on the $name", ({ assignee }) => {
- renderBadge({ assignee });
- expect(screen.queryByRole("button", { name: "Key updates only" })).toBeNull();
- });
-
- it("stays hidden for an explicit subscription or the all preference", () => {
- const theirs = { assignee_type: "member" as const, assignee_id: "user-other" };
- renderBadge({ assignee: theirs, reason: "manual" });
- expect(screen.queryByRole("button", { name: "Key updates only" })).toBeNull();
- cleanup();
- renderBadge({ assignee: theirs, preferences: { others_issues: "all" } });
- expect(screen.queryByRole("button", { name: "Key updates only" })).toBeNull();
- });
-
- // Commenting on someone else's issue in a project the member watches leaves
- // a commenter row, but the project still delivers every event (MUL-9343).
- it("stays hidden when the project already delivers everything", () => {
- renderBadge({
- assignee: { assignee_type: "member", assignee_id: "user-other" },
- projectCovered: true,
- });
+ { delivery: "all" as const },
+ { delivery: "delegated" as const },
+ { delivery: undefined },
+ ])("stays hidden for delivery $delivery", ({ delivery }) => {
+ renderBadge({ delivery });
expect(screen.queryByRole("button", { name: "Key updates only" })).toBeNull();
});
// Clickable chips use rounded-md (packages/ui/docs/button.md).
it("uses the clickable chip radius", () => {
- renderBadge({ assignee: { assignee_type: "member", assignee_id: "user-other" } });
+ renderBadge({ delivery: "key_updates" });
const trigger = screen.getByRole("button", { name: "Key updates only" });
expect(trigger.className).toContain("rounded-md");
expect(trigger.className).not.toContain("rounded-full");
diff --git a/packages/views/issues/components/key-updates-subscription-badge.tsx b/packages/views/issues/components/key-updates-subscription-badge.tsx
index 5f5b5b0235..620f2889a2 100644
--- a/packages/views/issues/components/key-updates-subscription-badge.tsx
+++ b/packages/views/issues/components/key-updates-subscription-badge.tsx
@@ -1,13 +1,8 @@
"use client";
-import { useQuery } from "@tanstack/react-query";
import { Bell, Settings2 } from "@multica/ui/icons";
-import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
-import { receivesKeyUpdatesOnly } from "@multica/core/notification-preferences/bystander";
-import { notificationPreferenceOptions } from "@multica/core/notification-preferences/queries";
-import { agentListOptions } from "@multica/core/workspace/queries";
-import type { IssueAssigneeType, IssueSubscriber } from "@multica/core/types";
+import type { IssueSubscriberDelivery } from "@multica/core/types";
import {
DropdownMenu,
DropdownMenuContent,
@@ -23,47 +18,23 @@ import { useNavigation } from "../../navigation";
/**
* Says that this issue reaches the viewer as key updates only — someone
* else's issue they follow passively (MUL-9343) — and offers the way back to
- * every event for this one issue. Renders nothing until the preference and the
- * agent list resolve, so it never flashes on the viewer's own issue.
+ * every event for this one issue. The tier is the server's `delivery` for the
+ * viewer's subscription; without one it renders nothing.
*/
export function KeyUpdatesSubscriptionBadge({
- issue,
- userId,
- reason,
- projectCovered,
+ delivery,
pending,
onFollowAll,
}: {
- issue: { assignee_type?: IssueAssigneeType | null; assignee_id?: string | null };
- userId: string | undefined;
- reason: IssueSubscriber["reason"] | undefined;
- projectCovered: boolean;
+ delivery: IssueSubscriberDelivery | undefined;
pending: boolean;
onFollowAll: () => void;
}) {
const { t } = useT("issues");
- const wsId = useWorkspaceId();
const paths = useWorkspacePaths();
const { push } = useNavigation();
- const { data: preferences, isSuccess: preferencesKnown } = useQuery(
- notificationPreferenceOptions(wsId),
- );
- const { data: agents, isSuccess: agentsKnown } = useQuery(agentListOptions(wsId));
- if (
- !preferencesKnown ||
- !agentsKnown ||
- !receivesKeyUpdatesOnly({
- reason,
- projectCovered,
- issue,
- userId,
- agents: agents ?? [],
- preferences: preferences?.preferences ?? {},
- })
- ) {
- return null;
- }
+ if (delivery !== "key_updates") return null;
return (
<DropdownMenu>
diff --git a/packages/views/issues/hooks/use-issue-subscribers.test.tsx b/packages/views/issues/hooks/use-issue-subscribers.test.tsx
index b831db740f..93e50fdb57 100644
--- a/packages/views/issues/hooks/use-issue-subscribers.test.tsx
+++ b/packages/views/issues/hooks/use-issue-subscribers.test.tsx
@@ -283,12 +283,11 @@ describe("useIssueSubscribers subscriptionKnown", () => {
});
/**
- * A project watcher who comments gets a direct commenter row. The project
- * still delivers every event to them, so the hook must keep saying so, or the
- * issue page claims "key updates only" for a subscription that is not narrowed
- * (MUL-9343).
+ * The delivery tier is the server's: the hook passes it through, and drops it
+ * from a row whose reason a realtime event changed locally, so no badge claims
+ * a tier the server has not confirmed (MUL-9360).
*/
-describe("useIssueSubscribers project coverage", () => {
+describe("useIssueSubscribers delivery", () => {
afterEach(() => {
cleanup();
wsHandlers.clear();
@@ -303,44 +302,33 @@ describe("useIssueSubscribers project coverage", () => {
...extra,
});
- it("reads project_covered from the server", async () => {
+ it("reads delivery from the server", async () => {
setApiInstance({
- listIssueSubscribers: async () => [row("commenter", { project_covered: true })],
+ listIssueSubscribers: async () => [row("commenter", { delivery: "key_updates" })],
} as unknown as ApiClient);
const { result } = renderSubscribers();
- await waitFor(() => expect(result.current.subscriptionKnown).toBe(true));
- await waitFor(() => expect(result.current.subscriptionReason).toBe("commenter"));
- expect(result.current.subscriptionProjectCovered).toBe(true);
+ await waitFor(() => expect(result.current.subscriptionDelivery).toBe("key_updates"));
+ expect(result.current.subscriptionReason).toBe("commenter");
});
- it("keeps the coverage when a project row turns into a direct one", async () => {
+ it("is undefined from a server that predates it", async () => {
setApiInstance({
- listIssueSubscribers: async () => [row("project")],
+ listIssueSubscribers: async () => [row("commenter")],
} as unknown as ApiClient);
const { result } = renderSubscribers();
- await waitFor(() => expect(result.current.subscriptionReason).toBe("project"));
- act(() => {
- wsHandlers.get("subscriber:added")?.({
- issue_id: "issue-1",
- user_type: "member",
- user_id: "user-1",
- reason: "commenter",
- });
- });
-
await waitFor(() => expect(result.current.subscriptionReason).toBe("commenter"));
- expect(result.current.subscriptionProjectCovered).toBe(true);
+ expect(result.current.subscriptionDelivery).toBeUndefined();
});
- it("is false for a plain direct subscription", async () => {
+ it("drops the tier when a realtime event changes the reason", async () => {
setApiInstance({
- listIssueSubscribers: async () => [row("manual")],
+ listIssueSubscribers: async () => [row("delegated", { delivery: "delegated" })],
} as unknown as ApiClient);
const { result } = renderSubscribers();
- await waitFor(() => expect(result.current.subscriptionKnown).toBe(true));
+ await waitFor(() => expect(result.current.subscriptionDelivery).toBe("delegated"));
act(() => {
wsHandlers.get("subscriber:added")?.({
issue_id: "issue-1",
@@ -349,7 +337,8 @@ describe("useIssueSubscribers project coverage", () => {
reason: "commenter",
});
});
+
await waitFor(() => expect(result.current.subscriptionReason).toBe("commenter"));
- expect(result.current.subscriptionProjectCovered).toBe(false);
+ expect(result.current.subscriptionDelivery).toBeUndefined();
});
});
diff --git a/packages/views/issues/hooks/use-issue-subscribers.ts b/packages/views/issues/hooks/use-issue-subscribers.ts
index 87c1d754f1..290f1a7635 100644
--- a/packages/views/issues/hooks/use-issue-subscribers.ts
+++ b/packages/views/issues/hooks/use-issue-subscribers.ts
@@ -70,21 +70,18 @@ export function useIssueSubscribers(issueId: string, userId?: string) {
);
// 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).
+ // commented is upgraded out of the reduced tier. Patch the reason
+ // and drop the delivery tier it no longer describes, so no badge
+ // claims a tier until the refetch the global handler starts brings
+ // the server's (MUL-5483, MUL-9360).
if (existing) {
if (existing.reason === p.reason) return old;
- // A project watcher who now has a direct row (they commented,
- // say) still receives everything through the project.
- const projectCovered =
- existing.project_covered || existing.reason === "project";
return old.map((s) =>
s.user_id === p.user_id && s.user_type === p.user_type
? {
...s,
reason: p.reason as IssueSubscriber["reason"],
- ...(projectCovered ? { project_covered: true } : {}),
+ delivery: undefined,
}
: s,
);
@@ -144,7 +141,9 @@ export function useIssueSubscribers(issueId: string, userId?: string) {
// 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 subscriptionProjectCovered = !!ownSubscription?.project_covered;
+ // How much of this issue actually reaches the viewer, as the server decides
+ // it. The tier badges read only this (MUL-9360).
+ const subscriptionDelivery = ownSubscription?.delivery;
// Serializes direct toggles. Disabling the button covers the ordinary case,
// but React Query flushes `isPending` in a microtask, so two clicks in the
@@ -238,7 +237,7 @@ export function useIssueSubscribers(issueId: string, userId?: string) {
subscriptionKnown,
isSubscribed,
subscriptionReason,
- subscriptionProjectCovered,
+ subscriptionDelivery,
// Serializing the UI on these is what keeps the whole-list optimistic
// snapshot in useToggleIssueSubscriber safe: concurrent toggles would each
// snapshot the other's in-flight patch and roll back to the wrong list.
diff --git a/server/cmd/server/delegated_subscriber_test.go b/server/cmd/server/delegated_subscriber_test.go
index 5e3d5b1fce..8e6bc546d0 100644
--- a/server/cmd/server/delegated_subscriber_test.go
+++ b/server/cmd/server/delegated_subscriber_test.go
@@ -449,7 +449,7 @@ func TestUnsubscribeIsDurableAgainstAutoRules(t *testing.T) {
}
}
-// TestDeliverToSubscriber_DelegatedTier pins the noise contract. The tier drops
+// TestDeliverDelegated 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
@@ -458,34 +458,30 @@ func TestUnsubscribeIsDurableAgainstAutoRules(t *testing.T) {
//
// Which statuses ARE handoffs is issueStatusIsHandoff's job and is covered by
// TestIssueStatusIsHandoff; this table covers the routing on top of that answer.
-func TestDeliverToSubscriber_DelegatedTier(t *testing.T) {
+func TestDeliverDelegated(t *testing.T) {
cases := []struct {
name string
- reason string
notifType string
handoff bool
want bool
}{
- {"direct subscriber keeps every event", "creator", "status_changed", false, true},
- {"direct subscriber keeps comments", "assignee", "new_comment", false, true},
+ {"delegated skips routine progress", "status_changed", false, false},
+ {"delegated skips assignee churn", "assignee_changed", false, false},
+ {"delegated skips date churn", "due_date_changed", false, false},
+ {"delegated skips non-status events even on a handoff", "due_date_changed", true, false},
- {"delegated skips routine progress", "delegated", "status_changed", false, false},
- {"delegated skips assignee churn", "delegated", "assignee_changed", false, false},
- {"delegated skips date churn", "delegated", "due_date_changed", false, false},
- {"delegated skips non-status events even on a handoff", "delegated", "due_date_changed", true, false},
+ {"delegated gets the handoff", "status_changed", true, true},
- {"delegated gets the handoff", "delegated", "status_changed", true, true},
-
- {"delegated always gets direct mentions", "delegated", "mentioned", false, true},
- {"delegated always gets comments", "delegated", "new_comment", false, true},
- {"delegated always gets failures", "delegated", "task_failed", false, true},
+ {"delegated always gets direct mentions", "mentioned", false, true},
+ {"delegated always gets comments", "new_comment", false, true},
+ {"delegated always gets failures", "task_failed", false, true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- if got := deliverToSubscriber(tc.reason, tc.notifType, tc.handoff); got != tc.want {
- t.Fatalf("deliverToSubscriber(%q, %q, %v) = %v, want %v",
- tc.reason, tc.notifType, tc.handoff, got, tc.want)
+ if got := deliverDelegated(tc.notifType, tc.handoff); got != tc.want {
+ t.Fatalf("deliverDelegated(%q, %v) = %v, want %v",
+ tc.notifType, tc.handoff, got, tc.want)
}
})
}
@@ -569,7 +565,7 @@ func TestIssueStatusIsHandoff(t *testing.T) {
}
// TestDelegatedTier_ChildCompletionDeliversExactlyOnce is the case a unit test of
-// deliverToSubscriber alone cannot catch. status_changed bubbles from a child to
+// deliverDelegated 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.
@@ -642,16 +638,6 @@ func TestDelegatedTier_ChildCompletionDeliversExactlyOnce(t *testing.T) {
}
}
-// 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", false) {
- t.Fatal("an unrecognized subscription reason must default to full delivery")
- }
-}
-
// TestDelegatedIssueCreated_NotifiesTheHumanOwner: an issue an agent files on a
// human's behalf reaches that human's inbox when it is created, unless a parent
// they already watch leads there (MUL-9314).
diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.go
index 28e9716b0b..66cc0a88d0 100644
--- a/server/cmd/server/notification_listeners.go
+++ b/server/cmd/server/notification_listeners.go
@@ -56,7 +56,7 @@ var parentBubbleNotifTypes = map[string]bool{
// comment lands on the row a handoff would light anyway.
//
// An agent that cannot proceed reaches the human as a blocked status change,
-// which the handoff rule in deliverToSubscriber already delivers.
+// which the handoff rule in deliverDelegated already delivers.
var delegatedAlwaysNotifTypes = map[string]bool{
"mentioned": true,
"new_comment": true,
@@ -115,12 +115,9 @@ func issueStatusIsHandoff(
}
}
-// deliverToSubscriber reports whether a subscriber row should receive this
-// notification type. Direct subscriptions (creator / assignee / commenter /
-// mentioned / manual / autopilot) pass — they opted in to this issue,
-// explicitly or by acting on it; the passive ones are narrowed separately on
-// someone else's issue (deliverToBystander). Only the delegated tier is
-// narrowed here, and only to drop churn.
+// deliverDelegated reports whether a subscription in the delegated tier
+// (inbox.DeliveryDelegated) receives this notification type. The tier only
+// drops 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.
@@ -134,10 +131,7 @@ func issueStatusIsHandoff(
// statusIsHandoff is the resolved issueStatusIsHandoff answer for the issue's
// current status, so the catalog is read once per notification rather than once
// per subscriber row.
-func deliverToSubscriber(reason, notifType string, statusIsHandoff bool) bool {
- if reason != "delegated" {
- return true
- }
+func deliverDelegated(notifType string, statusIsHandoff bool) bool {
if delegatedAlwaysNotifTypes[notifType] {
return true
}
@@ -147,29 +141,12 @@ func deliverToSubscriber(reason, notifType string, statusIsHandoff bool) bool {
return statusIsHandoff
}
-// othersIssuesPref is the preference key for how much of SOMEONE ELSE'S issue
-// reaches a member who is only passively subscribed to it. Absent or
-// "key_updates" applies the bystander tier; "all" turns it off (MUL-9343).
-const othersIssuesPref = "others_issues"
-
-// bystanderReasons are the subscription reasons a member picks up as a side
-// effect of acting on an issue — filing it, once being its assignee,
-// commenting, being mentioned. On an issue assigned to someone else these
-// narrow to the bystander tier. manual and autopilot are explicit requests to
-// follow the issue and keep every event; delegated has its own tier.
-var bystanderReasons = map[string]bool{
- "creator": true,
- "assignee": true,
- "commenter": true,
- "mentioned": true,
-}
-
-// deliverToBystander reports whether a bystander — a passive subscriber of an
-// issue assigned to someone else — receives this notification type. They hear
-// what is addressed at them or needs them: a mention, a reply in a comment
-// thread they took part in, and a status that hands the issue back to a human
-// (statusIsHandoff, as in deliverToSubscriber). The rest of the issue's
-// back-and-forth stays on the issue page.
+// deliverToBystander reports whether a bystander — a subscription in the
+// key-updates tier (inbox.DeliveryKeyUpdates) — receives this notification
+// type. They hear what is addressed at them or needs them: a mention, a reply
+// in a comment thread they took part in, and a status that hands the issue
+// back to a human (statusIsHandoff, as in deliverDelegated). The rest of the
+// issue's back-and-forth stays on the issue page.
func deliverToBystander(notifType string, statusIsHandoff, threadParticipant bool) bool {
switch notifType {
case "mentioned":
@@ -183,47 +160,6 @@ func deliverToBystander(notifType string, statusIsHandoff, threadParticipant boo
}
}
-// issueOwner is who an issue is assigned to, resolved to the human behind it:
-// the assigned member, or the owner of the assigned agent. A squad assignee
-// has no single owner, so a squad's issue is nobody's own.
-type issueOwner struct {
- assigned bool
- ownerID string
-}
-
-// isSomeoneElses reports whether the issue is assigned, and not to userID or
-// an agent userID owns. An unassigned issue is nobody else's: its creator is
-// the closest thing it has to an owner, and nothing about it is routine yet.
-func (o issueOwner) isSomeoneElses(userID string) bool {
- return o.assigned && o.ownerID != userID
-}
-
-func loadIssueOwner(ctx context.Context, queries *db.Queries, issueID string) (issueOwner, error) {
- issue, err := queries.GetIssue(ctx, parseUUID(issueID))
- if err != nil {
- return issueOwner{}, err
- }
- if !issue.AssigneeID.Valid {
- return issueOwner{}, nil
- }
- switch issue.AssigneeType.String {
- case "member":
- return issueOwner{assigned: true, ownerID: util.UUIDToString(issue.AssigneeID)}, nil
- case "agent":
- agent, err := queries.GetAgent(ctx, issue.AssigneeID)
- if err != nil {
- return issueOwner{}, err
- }
- owner := ""
- if agent.OwnerID.Valid {
- owner = util.UUIDToString(agent.OwnerID)
- }
- return issueOwner{assigned: true, ownerID: owner}, nil
- default:
- return issueOwner{assigned: true}, nil
- }
-}
-
// loadThreadParticipants returns the members who wrote another comment in the
// thread the notified comment belongs to, read from the new_comment details.
func loadThreadParticipants(ctx context.Context, queries *db.Queries, workspaceID string, details []byte) (map[string]bool, error) {
@@ -247,6 +183,14 @@ func loadThreadParticipants(ctx context.Context, queries *db.Queries, workspaceI
return participants, nil
}
+func loadIssueOwner(ctx context.Context, queries *db.Queries, issueID string) (inbox.IssueOwner, error) {
+ issue, err := queries.GetIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ return inbox.IssueOwner{}, err
+ }
+ return inbox.LoadIssueOwner(ctx, queries, issue)
+}
+
// bystanderTier applies deliverToBystander across one subscriber list. It
// reads the issue's owner, and for a comment its thread, at most once and only
// when a passive subscriber reaches it.
@@ -261,14 +205,16 @@ type bystanderTier struct {
details []byte
ownerLoaded bool
- owner issueOwner
+ owner inbox.IssueOwner
ownerErr error
threadLoaded bool
thread map[string]bool
threadErr error
}
-func (b *bystanderTier) deliver(userID, notifType string, statusIsHandoff bool) bool {
+// isSomeoneElses answers inbox.SubscriptionDelivery's owner question for
+// userID. An unreadable owner reads as the member's own issue: every event.
+func (b *bystanderTier) isSomeoneElses(userID string) bool {
if !b.ownerLoaded {
b.ownerLoaded = true
b.owner, b.ownerErr = loadIssueOwner(b.ctx, b.queries, b.issueID)
@@ -277,10 +223,10 @@ func (b *bystanderTier) deliver(userID, notifType string, statusIsHandoff bool)
"issue_id", b.issueID, "error", b.ownerErr)
}
}
- if b.ownerErr != nil || !b.owner.isSomeoneElses(userID) {
- return true
- }
+ return b.ownerErr == nil && b.owner.IsSomeoneElses(userID)
+}
+func (b *bystanderTier) deliver(userID, notifType string, statusIsHandoff bool) bool {
participant := false
if notifType == "new_comment" {
if !b.threadLoaded {
@@ -757,20 +703,23 @@ func notifyIssueSubscribers(
continue
}
- // Delegated subscriptions deliver a narrower event set than direct
- // ones — see deliverToSubscriber.
- if !deliverToSubscriber(sub.Reason, notifType, statusIsHandoff) {
- tierSuppressed[subID] = true
- continue
- }
-
- // A passive subscription to someone else's issue delivers the
- // bystander tier unless the member asked for everything. This is not
- // added to tierSuppressed: the parent bubble judges the parent's own
- // subscription, and the parent may well be this member's issue.
- if bystanderReasons[sub.Reason] && userPrefs[subID][othersIssuesPref] != "all" &&
- !bystander.deliver(subID, notifType, statusIsHandoff) {
- continue
+ // ListIssueSubscribers reports this same tier, so the issue page
+ // shows what the fanout actually delivers.
+ delivery := inbox.SubscriptionDelivery(sub.Reason, userPrefs[subID],
+ func() bool { return bystander.isSomeoneElses(subID) })
+ switch delivery {
+ case inbox.DeliveryDelegated:
+ if !deliverDelegated(notifType, statusIsHandoff) {
+ tierSuppressed[subID] = true
+ continue
+ }
+ case inbox.DeliveryKeyUpdates:
+ // Not added to tierSuppressed: the parent bubble judges the
+ // parent's own subscription, and the parent may well be this
+ // member's issue.
+ if !bystander.deliver(subID, notifType, statusIsHandoff) {
+ continue
+ }
}
if createMemberInboxItem(ctx, queries, bus, subID, workspaceID, e, targetIssueID, issueStatus,
diff --git a/server/cmd/server/subscription_delivery_test.go b/server/cmd/server/subscription_delivery_test.go
new file mode 100644
index 0000000000..6d7f2d7994
--- /dev/null
+++ b/server/cmd/server/subscription_delivery_test.go
@@ -0,0 +1,120 @@
+package main
+
+import (
+ "net/http"
+ "slices"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/internal/inbox"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// The tier GET /api/issues/{id}/subscribers reports for each member is the
+// tier the fanout delivers to them. The issue page badges read that field, so
+// a mismatch here is a badge telling someone the wrong thing (MUL-9360).
+func TestSubscriberDeliveryMatchesFanout(t *testing.T) {
+ queries := db.New(testPool)
+ bus := newNotificationBus(t, queries)
+
+ member := func(email string) string {
+ id := createNotificationMember(t, email)
+ t.Cleanup(func() { cleanupTestUser(t, email) })
+ return id
+ }
+ owner := member("[email protected]")
+ bystander := member("[email protected]")
+ follower := member("[email protected]")
+ projectWatcher := member("[email protected]")
+ delegate := member("[email protected]")
+ optedIn := member("[email protected]")
+ setOthersIssuesPref(t, optedIn, "all")
+
+ projectID := createTestProject(t)
+ f := workspaceFixture(t)
+ issueID := f.Issue(t, "delivery tier issue", testutil.Cols{
+ "assignee_type": "member",
+ "assignee_id": owner,
+ "project_id": projectID,
+ })
+ t.Cleanup(func() { cleanupInboxForIssue(t, issueID) })
+
+ addTestSubscriber(t, issueID, "member", owner, "assignee")
+ addTestSubscriber(t, issueID, "member", bystander, "commenter")
+ addTestSubscriber(t, issueID, "member", follower, "manual")
+ addTestSubscriber(t, issueID, "member", projectWatcher, "commenter")
+ addProjectSubscribers(t, projectID, projectWatcher)
+ addTestSubscriber(t, issueID, "member", delegate, "delegated")
+ addTestSubscriber(t, issueID, "member", optedIn, "creator")
+
+ cases := []struct {
+ name string
+ id string
+ want inbox.Delivery
+ }{
+ {"own issue", owner, inbox.DeliveryAll},
+ {"someone else's issue", bystander, inbox.DeliveryKeyUpdates},
+ {"manual follow", follower, inbox.DeliveryAll},
+ {"project subscription on top", projectWatcher, inbox.DeliveryAll},
+ {"delegated", delegate, inbox.DeliveryDelegated},
+ {"others_issues=all", optedIn, inbox.DeliveryAll},
+ }
+
+ resp := authRequest(t, http.MethodGet, "/api/issues/"+issueID+"/subscribers", nil)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("list subscribers: status %d", resp.StatusCode)
+ }
+ var rows []handler.SubscriberResponse
+ readJSON(t, resp, &rows)
+ listed := map[string]inbox.Delivery{}
+ for _, row := range rows {
+ if row.UserType == "member" {
+ listed[row.UserID] = row.Delivery
+ }
+ }
+ for _, c := range cases {
+ if got := listed[c.id]; got != c.want {
+ t.Errorf("%s: listed delivery %q, want %q", c.name, got, c.want)
+ }
+ }
+
+ // A routine status move and a top-level comment, both by someone outside
+ // the subscriber list, separate the three tiers.
+ publishStatusChange(bus, issueID, "in_progress", "todo")
+ content := "a routine update"
+ commentID := f.Comment(t, issueID, content, testutil.Cols{"author_id": testUserID})
+ bus.Publish(events.Event{
+ Type: protocol.EventCommentCreated,
+ WorkspaceID: testWorkspaceID,
+ ActorType: "member",
+ ActorID: testUserID,
+ Payload: map[string]any{
+ "comment": handler.CommentResponse{
+ ID: commentID,
+ IssueID: issueID,
+ AuthorType: "member",
+ AuthorID: testUserID,
+ Content: content,
+ Type: "comment",
+ },
+ "issue_title": "delivery tier issue",
+ "issue_status": "in_progress",
+ },
+ })
+
+ received := map[inbox.Delivery][]string{
+ inbox.DeliveryAll: {"new_comment", "status_changed"},
+ inbox.DeliveryKeyUpdates: {},
+ inbox.DeliveryDelegated: {"new_comment"},
+ }
+ for _, c := range cases {
+ got := inboxTypes(t, queries, c.id)
+ slices.Sort(got)
+ if want := received[listed[c.id]]; !slices.Equal(got, want) {
+ t.Errorf("%s: listed %q but received %v, want %v", c.name, listed[c.id], got, want)
+ }
+ }
+}
diff --git a/server/internal/handler/subscriber.go b/server/internal/handler/subscriber.go
index 944d8aeb8d..d0e67b9fc4 100644
--- a/server/internal/handler/subscriber.go
+++ b/server/internal/handler/subscriber.go
@@ -4,11 +4,13 @@ import (
"context"
"encoding/json"
"errors"
+ "log/slog"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/inbox"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -21,9 +23,12 @@ type SubscriberResponse struct {
Reason string `json:"reason"`
CreatedAt string `json:"created_at"`
// ProjectCovered marks a direct row whose member also subscribes to the
- // issue's project. The project path delivers every event regardless of the
- // direct reason, so clients must not read that reason as a reduced tier.
+ // issue's project. Delivery already accounts for it; clients that predate
+ // Delivery still read it.
ProjectCovered bool `json:"project_covered,omitempty"`
+ // Delivery is how much of this issue the member actually receives, as the
+ // notification fanout decides it. Absent on agent rows, which get no inbox.
+ Delivery inbox.Delivery `json:"delivery,omitempty"`
}
func subscriberToResponse(s db.IssueSubscriber) SubscriberResponse {
@@ -64,6 +69,28 @@ func (h *Handler) ListIssueSubscribers(w http.ResponseWriter, r *http.Request) {
projectCovered[uuidToString(ps.UserID)] = true
}
+ var memberIDs []pgtype.UUID
+ for _, s := range subscribers {
+ if s.UserType == "member" {
+ memberIDs = append(memberIDs, s.UserID)
+ }
+ }
+ prefs := inbox.LoadPreferences(r.Context(), h.Queries, issue.WorkspaceID, memberIDs)
+ ownerLoaded := false
+ var owner inbox.IssueOwner
+ var ownerErr error
+ // Fails open like the fanout: an unreadable owner delivers every event.
+ isSomeoneElses := func(userID string) bool {
+ if !ownerLoaded {
+ ownerLoaded = true
+ owner, ownerErr = inbox.LoadIssueOwner(r.Context(), h.Queries, issue)
+ if ownerErr != nil {
+ slog.Warn("resolve issue owner for subscriber delivery", "issue_id", issueID, "error", ownerErr)
+ }
+ }
+ return ownerErr == nil && owner.IsSomeoneElses(userID)
+ }
+
resp := make([]SubscriberResponse, 0, len(subscribers)+len(projectSubscribers))
direct := make(map[string]bool, len(subscribers))
for _, s := range subscribers {
@@ -71,6 +98,15 @@ func (h *Handler) ListIssueSubscribers(w http.ResponseWriter, r *http.Request) {
if s.UserType == "member" {
direct[row.UserID] = true
row.ProjectCovered = projectCovered[row.UserID]
+ // The project fanout delivers every event to a project watcher on
+ // top of whatever the direct row narrows to.
+ if row.ProjectCovered {
+ row.Delivery = inbox.DeliveryAll
+ } else {
+ userID := row.UserID
+ row.Delivery = inbox.SubscriptionDelivery(s.Reason, prefs[userID],
+ func() bool { return isSomeoneElses(userID) })
+ }
}
resp = append(resp, row)
}
@@ -85,6 +121,7 @@ func (h *Handler) ListIssueSubscribers(w http.ResponseWriter, r *http.Request) {
UserID: userID,
Reason: subscriberReasonProject,
CreatedAt: timestampToString(ps.CreatedAt),
+ Delivery: inbox.DeliveryAll,
})
}
diff --git a/server/internal/inbox/tier.go b/server/internal/inbox/tier.go
new file mode 100644
index 0000000000..a8ef933739
--- /dev/null
+++ b/server/internal/inbox/tier.go
@@ -0,0 +1,101 @@
+package inbox
+
+import (
+ "context"
+
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Delivery is how much of an issue one member's subscription to it delivers.
+// The notification fanout narrows by it, and the subscriber list reports it so
+// clients show the tier without re-deriving these rules (MUL-9360).
+type Delivery string
+
+const (
+ // DeliveryAll delivers every event.
+ DeliveryAll Delivery = "all"
+ // DeliveryKeyUpdates is the bystander tier on someone else's issue:
+ // mentions, replies in the member's threads, and handoff statuses.
+ DeliveryKeyUpdates Delivery = "key_updates"
+ // DeliveryDelegated is the tier of an issue an agent created on the
+ // member's behalf: mentions, comments, failures and handoff statuses.
+ DeliveryDelegated Delivery = "delegated"
+)
+
+// OthersIssuesPref is the preference key for how much of SOMEONE ELSE'S issue
+// reaches a member who is only passively subscribed to it. Absent or
+// "key_updates" applies the bystander tier; "all" turns it off (MUL-9343).
+const OthersIssuesPref = "others_issues"
+
+// bystanderReasons are the subscription reasons a member picks up as a side
+// effect of acting on an issue — filing it, once being its assignee,
+// commenting, being mentioned. On an issue assigned to someone else these
+// narrow to the bystander tier. manual and autopilot are explicit requests to
+// follow the issue and keep every event; delegated has its own tier.
+var bystanderReasons = map[string]bool{
+ "creator": true,
+ "assignee": true,
+ "commenter": true,
+ "mentioned": true,
+}
+
+// SubscriptionDelivery is the tier a member's direct subscription row delivers.
+// prefs are the member's parsed notification preferences. isSomeoneElses is
+// only called for a passive reason the member has not widened to "all", so a
+// fanout reads the issue's owner only when it matters.
+//
+// A project subscription delivers every event through its own fanout, so a
+// member who also watches the issue's project receives DeliveryAll whatever
+// this returns; callers reporting the effective tier apply that on top.
+func SubscriptionDelivery(reason string, prefs map[string]string, isSomeoneElses func() bool) Delivery {
+ if reason == "delegated" {
+ return DeliveryDelegated
+ }
+ if !bystanderReasons[reason] || prefs[OthersIssuesPref] == "all" {
+ return DeliveryAll
+ }
+ if !isSomeoneElses() {
+ return DeliveryAll
+ }
+ return DeliveryKeyUpdates
+}
+
+// IssueOwner is who an issue is assigned to, resolved to the human behind it:
+// the assigned member, or the owner of the assigned agent. A squad assignee
+// has no single owner, so a squad's issue is nobody's own.
+type IssueOwner struct {
+ assigned bool
+ ownerID string
+}
+
+// IsSomeoneElses reports whether the issue is assigned, and not to userID or
+// an agent userID owns. An unassigned issue is nobody else's: its creator is
+// the closest thing it has to an owner, and nothing about it is routine yet.
+func (o IssueOwner) IsSomeoneElses(userID string) bool {
+ return o.assigned && o.ownerID != userID
+}
+
+// LoadIssueOwner resolves the owner of issue, reading the assigned agent when
+// there is one.
+func LoadIssueOwner(ctx context.Context, queries *db.Queries, issue db.Issue) (IssueOwner, error) {
+ if !issue.AssigneeID.Valid {
+ return IssueOwner{}, nil
+ }
+ switch issue.AssigneeType.String {
+ case "member":
+ return IssueOwner{assigned: true, ownerID: util.UUIDToString(issue.AssigneeID)}, nil
+ case "agent":
+ agent, err := queries.GetAgent(ctx, issue.AssigneeID)
+ if err != nil {
+ return IssueOwner{}, err
+ }
+ owner := ""
+ if agent.OwnerID.Valid {
+ owner = util.UUIDToString(agent.OwnerID)
+ }
+ return IssueOwner{assigned: true, ownerID: owner}, nil
+ default:
+ return IssueOwner{assigned: true}, nil
+ }
+}
diff --git a/server/internal/inbox/tier_test.go b/server/internal/inbox/tier_test.go
new file mode 100644
index 0000000000..e6e219306d
--- /dev/null
+++ b/server/internal/inbox/tier_test.go
@@ -0,0 +1,59 @@
+package inbox
+
+import "testing"
+
+func TestSubscriptionDelivery(t *testing.T) {
+ cases := []struct {
+ name string
+ reason string
+ prefs map[string]string
+ someones bool
+ want Delivery
+ }{
+ {"passive on someone else's issue", "commenter", nil, true, DeliveryKeyUpdates},
+ {"creator on someone else's issue", "creator", nil, true, DeliveryKeyUpdates},
+ {"explicit key_updates preference", "mentioned", map[string]string{OthersIssuesPref: "key_updates"}, true, DeliveryKeyUpdates},
+ {"passive on own issue", "assignee", nil, false, DeliveryAll},
+ {"passive with others_issues=all", "commenter", map[string]string{OthersIssuesPref: "all"}, true, DeliveryAll},
+ {"manual follow", "manual", nil, true, DeliveryAll},
+ {"autopilot", "autopilot", nil, true, DeliveryAll},
+ {"delegated", "delegated", nil, false, DeliveryDelegated},
+ {"delegated ignores others_issues", "delegated", map[string]string{OthersIssuesPref: "all"}, true, DeliveryDelegated},
+ // An unrecognized reason must fall back to full delivery: silently
+ // dropping a member's notifications is the worse failure.
+ {"unknown reason", "some_future_reason", nil, true, DeliveryAll},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ if got := SubscriptionDelivery(c.reason, c.prefs, func() bool { return c.someones }); got != c.want {
+ t.Fatalf("SubscriptionDelivery(%q) = %q, want %q", c.reason, got, c.want)
+ }
+ })
+ }
+}
+
+func TestSubscriptionDelivery_ReadsOwnerOnlyWhenNeeded(t *testing.T) {
+ calls := 0
+ owner := func() bool { calls++; return true }
+ SubscriptionDelivery("manual", nil, owner)
+ SubscriptionDelivery("delegated", nil, owner)
+ SubscriptionDelivery("commenter", map[string]string{OthersIssuesPref: "all"}, owner)
+ if calls != 0 {
+ t.Fatalf("owner read %d times for subscriptions it cannot narrow, want 0", calls)
+ }
+}
+
+func TestIssueOwner_IsSomeoneElses(t *testing.T) {
+ if (IssueOwner{}).IsSomeoneElses("u1") {
+ t.Error("an unassigned issue is nobody else's")
+ }
+ if (IssueOwner{assigned: true, ownerID: "u1"}).IsSomeoneElses("u1") {
+ t.Error("an issue assigned to u1 is u1's own")
+ }
+ if !(IssueOwner{assigned: true, ownerID: "u2"}).IsSomeoneElses("u1") {
+ t.Error("an issue assigned to u2 is someone else's for u1")
+ }
+ if !(IssueOwner{assigned: true}).IsSomeoneElses("u1") {
+ t.Error("a squad's issue is someone else's")
+ }
+}