Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(issues): unsubscribe in one click when an issue has no sub-issues (MUL-5714) (#6380)
Naiyuan Qingc98a01b3df91
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex dae29a63f2..f772ce929e 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -4,6 +4,7 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import type { Issue, Label, TimelineEntry } from "@multica/core/types";import { I18nProvider } from "@multica/core/i18n/react";+import { toast } from "sonner";import { useResolvedExpandStore } from "@multica/core/issues/stores/resolved-expand-store";import {DEFAULT_SUB_ISSUE_ROW_PROPERTIES,@@ -1697,6 +1698,12 @@ describe("IssueDetail (shared)", () => {beforeEach(() => {mockApiObj.listIssueSubscribers.mockResolvedValue(subscribedAsMember);+ // The menu only exists when there is a sub-tree for its second item to+ // act on. A childless issue renders a direct button instead — covered+ // by the "no sub-issues" tests below (MUL-5714).+ mockApiObj.listChildIssues.mockResolvedValue({+ issues: [{ ...mockIssue, id: "child-1", parent_issue_id: "issue-1" }],+ });});// Base UI portals the popup onto document.body; RTL unmounts it, but wipe@@ -1746,6 +1753,257 @@ describe("IssueDetail (shared)", () => {);expect(mockApiObj.unsubscribeFromIssue).not.toHaveBeenCalled();});++ it("still offers the menu while the child count is unknown", async () => {+ // Children never resolve, so the component cannot yet tell a childless+ // issue from one with a sub-tree. The menu is the safe answer: unlike+ // the direct button it never picks an opt-out scope for the user.+ mockApiObj.listChildIssues.mockReturnValue(new Promise(() => {}));+ renderIssueDetail();++ const control = await screen.findByText("Unsubscribe");++ expect(control.getAttribute("aria-haspopup")).toBe("menu");+ });+ });++ // The reported bug: on an issue with no sub-issues the only way to leave was+ // a menu whose second item pointed at a sub-tree that does not exist+ // (MUL-5714).+ describe("unsubscribe without sub-issues", () => {+ const subscribedAsMember = [+ {+ issue_id: "issue-1",+ user_type: "member" as const,+ user_id: "user-1",+ reason: "manual" as const,+ created_at: "2026-01-01T00:00:00Z",+ },+ ];++ beforeEach(() => {+ mockApiObj.listIssueSubscribers.mockResolvedValue(subscribedAsMember);+ mockApiObj.listChildIssues.mockResolvedValue({ issues: [] });+ });++ afterEach(() => {+ document.body.innerHTML = "";+ });++ // The label is the same either way, so aria-haspopup is what separates the+ // menu trigger from the plain button. The subscribers query resolves first,+ // so the control is briefly the trigger before the child count settles —+ // wait for the collapsed form rather than grabbing the first match.+ async function findDirectUnsubscribeButton() {+ return waitFor(() => {+ const el = screen.getByText("Unsubscribe");+ expect(el.getAttribute("aria-haspopup")).toBeNull();+ return el;+ });+ }++ it("unsubscribes in one click, with no menu", async () => {+ renderIssueDetail();++ fireEvent.click(await findDirectUnsubscribeButton());++ await waitFor(() =>+ expect(mockApiObj.unsubscribeFromIssue).toHaveBeenCalledWith(+ "issue-1",+ "user-1",+ "member",+ ),+ );+ expect(screen.queryByRole("menu")).toBeNull();+ });++ // The scope choice, pinned. RemoveIssueSubscriber writes+ // opt_out_scope='issue'; the subtree route writes 'subtree', which also+ // blocks FUTURE children from re-subscribing the user. Collapsing the menu+ // must not quietly upgrade a one-issue opt-out into a whole-tree one+ // (server/pkg/db/queries/subscriber.sql).+ it("uses the root-only route, never the subtree one", async () => {+ renderIssueDetail();++ fireEvent.click(await findDirectUnsubscribeButton());++ await waitFor(() =>+ expect(mockApiObj.unsubscribeFromIssue).toHaveBeenCalled(),+ );+ expect(mockApiObj.unsubscribeFromIssueSubtree).not.toHaveBeenCalled();+ });++ it("sends one request for a rapid double-click", async () => {+ let release: (() => void) | undefined;+ mockApiObj.unsubscribeFromIssue.mockReturnValue(+ new Promise<void>((resolve) => {+ release = () => resolve();+ }),+ );+ renderIssueDetail();+ const button = await findDirectUnsubscribeButton();++ // Same tick, no await between. React Query flushes isPending in a+ // microtask, so `disabled` has not landed yet and the second click still+ // reaches an enabled button — the in-flight guard is what stops it. Two+ // overlapping toggles is the one case the mutation's whole-list snapshot+ // cannot survive: the second snapshots the first one's optimistic patch+ // and rolls back to it (MUL-5714).+ fireEvent.click(button);+ fireEvent.click(button);++ // Both handlers already ran synchronously; only the request dispatch is+ // async. So once any call has landed, the count is final.+ await waitFor(() =>+ expect(mockApiObj.unsubscribeFromIssue).toHaveBeenCalled(),+ );+ expect(mockApiObj.unsubscribeFromIssue).toHaveBeenCalledTimes(1);+ release?.();+ });++ it("disables the button while the toggle is in flight, then reports failure", async () => {+ let reject: ((err: Error) => void) | undefined;+ mockApiObj.unsubscribeFromIssue.mockReturnValue(+ new Promise<void>((_resolve, rej) => {+ reject = (err) => rej(err);+ }),+ );+ renderIssueDetail();+ const button = await findDirectUnsubscribeButton();++ fireEvent.click(button);++ await waitFor(() =>+ expect((button as HTMLButtonElement).disabled).toBe(true),+ );++ reject?.(new Error("boom"));++ // The optimistic patch rolls itself back, restoring the exact row the+ // user started from — without this message that is indistinguishable+ // from a button that never fired.+ await waitFor(() =>+ expect(toast.error).toHaveBeenCalledWith(+ enIssues.detail.subscription_update_failed,+ ),+ );+ await waitFor(() =>+ expect((button as HTMLButtonElement).disabled).toBe(false),+ );+ });+ });++ // Before the subscribers query resolves the hook's list defaults to empty,+ // which reads as "not subscribed" for everyone. Rendering that default+ // showed a Subscribe button to people who were already subscribed, and a+ // click landing in that window sent a subscribe instead of the unsubscribe+ // they meant (MUL-5714).+ describe("subscription state before the query resolves", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ });++ it("renders no subscribe control while subscribers are loading", async () => {+ mockApiObj.listIssueSubscribers.mockReturnValue(new Promise(() => {}));+ renderIssueDetail();++ // Wait for the issue itself, so this asserts on a rendered page rather+ // than on the loading skeleton.+ await screen.findByText("Implement authentication");++ expect(screen.queryByText("Subscribe")).toBeNull();+ expect(screen.queryByText("Unsubscribe")).toBeNull();+ });++ it("renders Subscribe once the query says the user is not subscribed", async () => {+ mockApiObj.listIssueSubscribers.mockResolvedValue([]);+ renderIssueDetail();++ expect(await screen.findByText("Subscribe")).toBeTruthy();+ });+ });++ // Same cold-cache hazard as the Subscribe button, but worse to act on. Every+ // checkbox here is drawn from the subscribers list, so an unresolved query+ // renders everyone — including people who ARE subscribed — as unchecked.+ // Clicking one of those rows sends an explicit subscribe, which rewrites the+ // target's reason to 'manual' and clears any opt-out scope+ // (server/pkg/db/queries/subscriber.sql), discarding a delegated+ // subscription or a deliberate opt-out (MUL-5714).+ describe("subscriber picker before the query resolves", () => {+ // The picker sits next to the subscribe control in the Activity header.+ // Anchor on the heading, not on that control — the whole point of these+ // cases is that it is not rendered yet.+ async function openSubscriberPicker() {+ const heading = await screen.findByText("Activity");+ const header = heading.parentElement?.parentElement;+ const trigger = header?.querySelector('[data-slot="popover-trigger"]');+ if (!trigger) throw new Error("subscriber picker trigger not found");+ fireEvent.click(trigger);+ return waitFor(() => {+ const content = document.querySelector('[data-slot="popover-content"]');+ if (!content) throw new Error("picker did not open");+ return content;+ });+ }++ function memberRow(content: Element) {+ const row = Array.from(+ content.querySelectorAll('[data-slot="command-item"]'),+ ).find((el) => el.textContent?.includes("Test User"));+ if (!row) throw new Error("member row not found");+ return row;+ }++ it("disables the rows while subscribers are loading", async () => {+ mockApiObj.listIssueSubscribers.mockReturnValue(new Promise(() => {}));+ renderIssueDetail();++ const row = memberRow(await openSubscriberPicker());++ expect(row.getAttribute("data-disabled")).toBe("true");++ fireEvent.click(row);++ expect(mockApiObj.subscribeToIssue).not.toHaveBeenCalled();+ expect(mockApiObj.unsubscribeFromIssue).not.toHaveBeenCalled();+ });++ it("disables the rows when the subscribers query failed", async () => {+ mockApiObj.listIssueSubscribers.mockRejectedValue(new Error("boom"));+ renderIssueDetail();++ const row = memberRow(await openSubscriberPicker());++ expect(row.getAttribute("data-disabled")).toBe("true");++ fireEvent.click(row);++ expect(mockApiObj.subscribeToIssue).not.toHaveBeenCalled();+ expect(mockApiObj.unsubscribeFromIssue).not.toHaveBeenCalled();+ });++ it("enables the rows once the query has a real answer", async () => {+ mockApiObj.listIssueSubscribers.mockResolvedValue([]);+ renderIssueDetail();+ // Wait for the resolved state before opening, so this is not just the+ // pending case passing by accident.+ await screen.findByText("Subscribe");++ const row = memberRow(await openSubscriberPicker());++ expect(row.getAttribute("data-disabled")).not.toBe("true");++ fireEvent.click(row);++ await waitFor(() =>+ expect(mockApiObj.subscribeToIssue).toHaveBeenCalledWith(+ "issue-1",+ "user-1",+ "member",+ ),+ );+ });});});diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex ebefdcc17e..63f4c1021b 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -122,17 +122,34 @@ import {useAnimatedRightSidebarState,} from "../../layout/animated-right-sidebar";+// Shared by the subscribe button and the unsubscribe menu trigger so the two+// stay one control visually — they occupy the same slot and only differ in+// what a click does.+const SUBSCRIPTION_ACTION_CLASS =+ "text-caption text-muted-foreground hover:text-foreground transition-colors disabled:pointer-events-none disabled:opacity-50";+function SubscriberPopoverContent({members,agents,subscribers,toggleSubscriber,+ togglesDisabled,t,}: {members: { user_id: string; name: string }[];agents: { id: string; name: string; archived_at?: string | null }[];subscribers: { user_type: string; user_id: string }[];toggleSubscriber: (id: string, type: "member" | "agent", subscribed: boolean) => void;+ /**+ * Every checkbox here is drawn from `subscribers`, which defaults to an empty+ * list until the query resolves — so an unresolved query renders everyone as+ * unsubscribed. Acting on that is not a harmless no-op: an explicit subscribe+ * rewrites the target's reason to 'manual' and clears any opt-out scope+ * (server/pkg/db/queries/subscriber.sql), which would quietly discard a+ * delegated subscription or someone's deliberate opt-out. So these rows wait+ * for a real answer, not just for the in-flight mutation (MUL-5714).+ */+ togglesDisabled: boolean;t: ActivityT;}) {const [search, setSearch] = useState("");@@ -169,6 +186,7 @@ function SubscriberPopoverContent({<CommandItemkey={`member-${m.user_id}`}onSelect={() => toggleSubscriber(m.user_id, "member", isSubbed)}+ disabled={togglesDisabled}className="flex items-center gap-2.5"><Checkbox checked={isSubbed} className="pointer-events-none" />@@ -188,6 +206,7 @@ function SubscriberPopoverContent({<CommandItemkey={`agent-${a.id}`}onSelect={() => toggleSubscriber(a.id, "agent", isSubbed)}+ disabled={togglesDisabled}className="flex items-center gap-2.5"><Checkbox checked={isSubbed} className="pointer-events-none" />@@ -1467,7 +1486,8 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr} = useIssueReactions(id, user?.id);const {- subscribers, isSubscribed, subscriptionReason,+ subscribers, isSubscribed, subscriptionReason, subscriptionKnown,+ togglePending, subtreePending,toggleSubscribe: handleToggleSubscribe, toggleSubscriber,unsubscribeFromSubtree: handleUnsubscribeSubtree,} = useIssueSubscribers(id, user?.id);@@ -1496,10 +1516,21 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr...projectDetailOptions(wsId, issueProjectId ?? ""),enabled: !!issueProjectId,});- const { data: childIssues = [] } = useQuery({+ const {+ data: childIssues = [],+ isSuccess: childIssuesLoaded,+ isFetching: childIssuesFetching,+ } = useQuery({...childIssuesOptions(wsId, id),enabled: !!issue,});+ // Whether this issue has sub-issues, as opposed to "we have not looked yet".+ // childIssuesOptions sets refetchOnMount: "always", so a cached snapshot is+ // re-fetched on every mount and isSuccess alone still describes the previous+ // visit. The unsubscribe control below picks a different server write from+ // this answer, so a defaulted or stale empty array must not count as "no+ // sub-issues" (MUL-5714).+ const childCountKnown = childIssuesLoaded && !childIssuesFetching;// Parent's children — used to render the "x/y" progress next to the// "Sub-issue of …" breadcrumb under the title.const { data: parentChildIssues = [] } = useQuery({@@ -2646,35 +2677,66 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr</TooltipContent></Tooltip>)}- {isSubscribed ? (- <DropdownMenu>- <DropdownMenuTrigger className="text-caption text-muted-foreground hover:text-foreground transition-colors">- {t(($) => $.detail.unsubscribe)}- </DropdownMenuTrigger>- {/* onClick, not onSelect: Base UI's Menu.Item exposes no- onSelect (that is the Radix spelling), and because its- props extend the full div attribute set, an onSelect- typechecks and silently lands on the DOM node as the- native text-selection event — the handler never runs- (MUL-5710). */}- <DropdownMenuContent align="end">- <DropdownMenuItem onClick={handleToggleSubscribe}>- {t(($) => $.detail.unsubscribe_this)}- </DropdownMenuItem>- <DropdownMenuItem onClick={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>- )}+ {/* Nothing until the subscribers query resolves: the default+ empty list reads as "not subscribed" for everyone, so+ rendering it flashes Subscribe at someone who is already+ subscribed, and a click landing in that window sends a+ subscribe instead of the unsubscribe they meant. An+ unresolved state is better shown as no control than as the+ wrong one (MUL-5714). */}+ {subscriptionKnown &&+ (!isSubscribed || (childCountKnown && childIssues.length === 0) ? (+ /* One button, no menu, when there is nothing for the+ subtree option to cover. This is the root-only path+ (opt_out_scope='issue'), NOT the subtree one: even at+ zero children the two are different server writes,+ because a subtree tombstone also keeps FUTURE children+ from re-subscribing the user+ (server/pkg/db/queries/subscriber.sql). Declining one+ issue must not silently opt someone out of a tree that+ does not exist yet. While the child count is unknown we+ keep the menu below — it never picks a scope for the+ user. */+ <button+ type="button"+ onClick={handleToggleSubscribe}+ disabled={togglePending || !user?.id}+ className={SUBSCRIPTION_ACTION_CLASS}+ >+ {isSubscribed+ ? t(($) => $.detail.unsubscribe)+ : t(($) => $.detail.subscribe)}+ </button>+ ) : (+ <DropdownMenu>+ <DropdownMenuTrigger+ disabled={togglePending || subtreePending || !user?.id}+ className={SUBSCRIPTION_ACTION_CLASS}+ >+ {t(($) => $.detail.unsubscribe)}+ </DropdownMenuTrigger>+ {/* onClick, not onSelect: Base UI's Menu.Item exposes no+ onSelect (that is the Radix spelling), and because its+ props extend the full div attribute set, an onSelect+ typechecks and silently lands on the DOM node as the+ native text-selection event — the handler never runs+ (MUL-5710). */}+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ onClick={handleToggleSubscribe}+ disabled={togglePending}+ >+ {t(($) => $.detail.unsubscribe_this)}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={handleUnsubscribeSubtree}+ disabled={subtreePending}+ >+ {t(($) => $.detail.unsubscribe_subtree)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ))}<Popover><PopoverTrigger className="cursor-pointer hover:opacity-80 transition-opacity">{subscribers.length > 0 ? (@@ -2703,6 +2765,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tragents={agents}subscribers={subscribers}toggleSubscriber={toggleSubscriber}+ togglesDisabled={+ !subscriptionKnown || togglePending || !user?.id+ }t={t}/></Popover>diff --git a/packages/views/issues/hooks/use-issue-subscribers.test.tsx b/packages/views/issues/hooks/use-issue-subscribers.test.tsxindex b997ba9efc..f62ad41903 100644--- a/packages/views/issues/hooks/use-issue-subscribers.test.tsx+++ b/packages/views/issues/hooks/use-issue-subscribers.test.tsx@@ -6,11 +6,18 @@ 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 { issueKeys } from "@multica/core/issues/queries";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) } }));+const toastSuccess = vi.fn();+vi.mock("sonner", () => ({+ toast: {+ error: (msg: string) => toastError(msg),+ success: (msg: string) => toastSuccess(msg),+ },+}));// Return the key path so an assertion can tell the two failure messages apart// without depending on the English copy.@@ -51,9 +58,12 @@ function renderSubscribers() {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false }, mutations: { retry: false } },});- return renderHook(() => useIssueSubscribers("issue-1", "user-1"), {- wrapper: wrapper(queryClient),- });+ return {+ ...renderHook(() => useIssueSubscribers("issue-1", "user-1"), {+ wrapper: wrapper(queryClient),+ }),+ queryClient,+ };}/**@@ -68,6 +78,7 @@ describe("useIssueSubscribers subtree unsubscribe failures", () => {afterEach(() => {cleanup();toastError.mockClear();+ toastSuccess.mockClear();});it("tells the user when the backend has no subtree route yet", async () => {@@ -123,7 +134,11 @@ describe("useIssueSubscribers subtree unsubscribe failures", () => {expect(toastError).toHaveBeenCalledWith("detail.unsubscribe_subtree_failed");});- it("stays silent when the unsubscribe succeeds", async () => {+ // Unlike the direct toggle, this mutation is not optimistic — no label or+ // avatar flips to confirm the click landed, and the descendants it retired+ // are not on screen at all. Silence here is indistinguishable from a dead+ // button, which is the MUL-5710 complaint (MUL-5714).+ it("confirms a successful subtree unsubscribe", async () => {setApiInstance({listIssueSubscribers: async () => [],unsubscribeFromIssueSubtree: async () => undefined,@@ -132,6 +147,134 @@ describe("useIssueSubscribers subtree unsubscribe failures", () => {const { result } = renderSubscribers();result.current.unsubscribeFromSubtree();- await waitFor(() => expect(toastError).not.toHaveBeenCalled());+ await waitFor(() =>+ expect(toastSuccess).toHaveBeenCalledWith(+ "detail.unsubscribe_subtree_succeeded",+ ),+ );+ expect(toastError).not.toHaveBeenCalled();+ });+});++const SUBSCRIBED_AS_MEMBER = [+ {+ issue_id: "issue-1",+ user_type: "member",+ user_id: "user-1",+ reason: "manual",+ created_at: "2026-01-01T00:00:00Z",+ },+];++/**+ * useToggleIssueSubscriber patches the cache optimistically and rolls that+ * patch back when the request fails, which restores the exact row the user+ * started from. Without a message that is pixel-identical to a button that+ * never fired — the same symptom MUL-5710 was reported as (MUL-5714).+ */+describe("useIssueSubscribers direct toggle feedback", () => {+ afterEach(() => {+ cleanup();+ toastError.mockClear();+ toastSuccess.mockClear();+ });++ it("reports a failed unsubscribe", async () => {+ setApiInstance({+ listIssueSubscribers: async () => SUBSCRIBED_AS_MEMBER,+ unsubscribeFromIssue: async () => {+ throw new ApiError("boom", 500, "Internal Server Error");+ },+ } as unknown as ApiClient);++ const { result } = renderSubscribers();+ await waitFor(() => expect(result.current.isSubscribed).toBe(true));+ result.current.toggleSubscribe();++ await waitFor(() =>+ expect(toastError).toHaveBeenCalledWith(+ "detail.subscription_update_failed",+ ),+ );+ });++ it("reports a failed subscribe", async () => {+ setApiInstance({+ listIssueSubscribers: async () => [],+ subscribeToIssue: async () => {+ throw new ApiError("boom", 500, "Internal Server Error");+ },+ } as unknown as ApiClient);++ const { result } = renderSubscribers();+ await waitFor(() => expect(result.current.subscriptionKnown).toBe(true));+ result.current.toggleSubscribe();++ await waitFor(() =>+ expect(toastError).toHaveBeenCalledWith(+ "detail.subscription_update_failed",+ ),+ );+ });++ // The optimistic patch IS the success feedback here; a toast on top of a+ // button that already flipped is noise on a control people press often.+ it("stays quiet when the toggle succeeds", async () => {+ setApiInstance({+ listIssueSubscribers: async () => SUBSCRIBED_AS_MEMBER,+ unsubscribeFromIssue: async () => undefined,+ } as unknown as ApiClient);++ const { result } = renderSubscribers();+ await waitFor(() => expect(result.current.isSubscribed).toBe(true));+ result.current.toggleSubscribe();++ await waitFor(() => expect(result.current.togglePending).toBe(false));+ expect(toastError).not.toHaveBeenCalled();+ expect(toastSuccess).not.toHaveBeenCalled();+ });+});++/**+ * `isSubscribed` is derived from `data ?? []`, so it reads false for everyone+ * until the query resolves. `subscriptionKnown` is what lets the UI tell that+ * default apart from a real answer (MUL-5714).+ */+describe("useIssueSubscribers subscriptionKnown", () => {+ afterEach(() => {+ cleanup();+ toastError.mockClear();+ toastSuccess.mockClear();+ });++ it("is false until the subscribers query resolves", async () => {+ setApiInstance({+ listIssueSubscribers: async () => SUBSCRIBED_AS_MEMBER,+ } as unknown as ApiClient);++ const { result } = renderSubscribers();+ // The very first render already carries the misleading default.+ expect(result.current.isSubscribed).toBe(false);+ expect(result.current.subscriptionKnown).toBe(false);++ await waitFor(() => expect(result.current.subscriptionKnown).toBe(true));+ expect(result.current.isSubscribed).toBe(true);+ });++ it("stays false when the subscribers query fails", async () => {+ setApiInstance({+ listIssueSubscribers: async () => {+ throw new ApiError("boom", 500, "Internal Server Error");+ },+ } as unknown as ApiClient);++ const { result, queryClient } = renderSubscribers();++ await waitFor(() =>+ expect(+ queryClient.getQueryState(issueKeys.subscribers("issue-1"))?.status,+ ).toBe("error"),+ );+ expect(result.current.subscriptionKnown).toBe(false);});});diff --git a/packages/views/issues/hooks/use-issue-subscribers.ts b/packages/views/issues/hooks/use-issue-subscribers.tsindex 57342a103d..17c3070ef0 100644--- a/packages/views/issues/hooks/use-issue-subscribers.ts+++ b/packages/views/issues/hooks/use-issue-subscribers.ts@@ -1,6 +1,6 @@"use client";-import { useCallback } from "react";+import { useCallback, useRef } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";import type { IssueSubscriber } from "@multica/core/types";import type {@@ -39,7 +39,7 @@ function isMissingRouteError(err: unknown): boolean {export function useIssueSubscribers(issueId: string, userId?: string) {const qc = useQueryClient();const { t } = useT("issues");- const { data: subscribers = [], isLoading: loading } = useQuery(+ const { data: subscribers = [], isSuccess } = useQuery(issueSubscribersOptions(issueId),);@@ -123,24 +123,57 @@ export function useIssueSubscribers(issueId: string, userId?: string) {(s) => s.user_type === "member" && s.user_id === userId,);const isSubscribed = !!ownSubscription;+ // Both `subscribers` and `isSubscribed` come from `data ?? []`, so before the+ // query resolves they read "nobody is subscribed" — including for people who+ // are. EVERY control derived from them must gate on this rather than render+ // the default, and that means the subscriber picker too, not just the+ // subscribe button: an unchecked row for someone already subscribed sends an+ // explicit subscribe, which rewrites their reason to 'manual' and clears any+ // opt-out scope (server/pkg/db/queries/subscriber.sql). A failed query stays+ // unknown as well; only a resolved one is truth (MUL-5714).+ const subscriptionKnown = isSuccess;// 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;+ // Serializes direct toggles. Disabling the button covers the ordinary case,+ // but React Query flushes `isPending` in a microtask, so two clicks in the+ // same tick both reach a still-enabled control. Overlapping toggles are the+ // one thing useToggleIssueSubscriber's whole-list optimistic snapshot cannot+ // survive: the second call snapshots the first one's patch and, on failure,+ // rolls back to it instead of to the server's state (MUL-5714).+ const toggleInFlight = useRef(false);++ // The optimistic patch in useToggleIssueSubscriber rolls itself back on+ // failure, which puts the row back exactly as it was — indistinguishable from+ // a button that never fired. Say so instead (MUL-5714).const toggleSubscriber = useCallback(- async (+ (subUserId: string,userType: "member" | "agent",currentlySubscribed: boolean,) => {- toggleMutation.mutate({- userId: subUserId,- userType,- subscribed: currentlySubscribed,- });+ if (toggleInFlight.current) return;+ toggleInFlight.current = true;+ toggleMutation.mutate(+ {+ userId: subUserId,+ userType,+ subscribed: currentlySubscribed,+ },+ {+ onError: () =>+ toast.error(t(($) => $.detail.subscription_update_failed)),+ // Runs after the mutation's own onSettled, so the cache has already+ // been invalidated by the time the next toggle can start.+ onSettled: () => {+ toggleInFlight.current = false;+ },+ },+ );},- [toggleMutation],+ [toggleMutation, t],);const toggleSubscribe = useCallback(() => {@@ -150,11 +183,18 @@ export function useIssueSubscribers(issueId: string, userId?: string) {// 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.+ //+ // Success needs a message for the same reason, and only here: this mutation+ // is deliberately not optimistic (it retires an unknown number of descendant+ // subscriptions), so unlike the direct toggle there is no label or avatar+ // flipping to confirm the click landed (MUL-5714).const unsubscribeFromSubtree = useCallback(() => {if (!userId) return;subtreeMutation.mutate({ userId, userType: "member" },{+ onSuccess: () =>+ toast.success(t(($) => $.detail.unsubscribe_subtree_succeeded)),onError: (err) =>toast.error(isMissingRouteError(err)@@ -167,9 +207,14 @@ export function useIssueSubscribers(issueId: string, userId?: string) {return {subscribers,- loading,+ subscriptionKnown,isSubscribed,subscriptionReason,+ // 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.+ togglePending: toggleMutation.isPending,+ subtreePending: subtreeMutation.isPending,toggleSubscribe,toggleSubscriber,unsubscribeFromSubtree,diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex c2034411d9..37f607f752 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -308,7 +308,9 @@"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_succeeded": "Unsubscribed from this issue and its sub-issues.","unsubscribe_subtree_unsupported": "This workspace's server does not support unsubscribing from sub-issues yet. Try again after the next update.",+ "subscription_update_failed": "Could not update the subscription. Please try again.","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.jsonindex fa9a1c3be7..c25f938386 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -305,7 +305,9 @@"unsubscribe_this": "この課題の購読を解除","unsubscribe_subtree": "この課題とサブ課題の購読を解除","unsubscribe_subtree_failed": "サブ課題の購読解除に失敗しました。もう一度お試しください。",+ "unsubscribe_subtree_succeeded": "この課題とサブ課題の購読を解除しました。","unsubscribe_subtree_unsupported": "現在のサーバーはサブ課題の購読解除にまだ対応していません。次回の更新後にお試しください。",+ "subscription_update_failed": "購読状態を更新できませんでした。もう一度お試しください。","no_subscribers_results": "結果が見つかりません","change_subscribers_placeholder": "購読者を変更...","members_group": "メンバー",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 6e077857ef..685e84523f 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -305,7 +305,9 @@"unsubscribe_this": "이 이슈 구독 해제","unsubscribe_subtree": "이 이슈와 하위 이슈 구독 해제","unsubscribe_subtree_failed": "하위 이슈 구독 해제에 실패했습니다. 다시 시도해 주세요.",+ "unsubscribe_subtree_succeeded": "이 이슈와 하위 이슈 구독을 해제했습니다.","unsubscribe_subtree_unsupported": "현재 서버는 아직 하위 이슈 구독 해제를 지원하지 않습니다. 다음 업데이트 후 다시 시도해 주세요.",+ "subscription_update_failed": "구독 상태를 업데이트하지 못했습니다. 다시 시도해 주세요.","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.jsonindex e560014c53..9949ebca9e 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -305,7 +305,9 @@"unsubscribe_this": "取消订阅此 issue","unsubscribe_subtree": "取消订阅此 issue 及其子 issue","unsubscribe_subtree_failed": "取消订阅子 issue 失败,请重试。",+ "unsubscribe_subtree_succeeded": "已取消订阅此 issue 及其子 issue。","unsubscribe_subtree_unsupported": "当前服务端还不支持取消订阅子 issue,请在下次更新后再试。",+ "subscription_update_failed": "无法更新订阅状态,请重试。","no_subscribers_results": "未找到结果","change_subscribers_placeholder": "更改订阅者...","members_group": "成员",