Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8550: feat(issues): add "Subscribed by me" relation filter (#9877)
Jiayuan Zhang9b807053175c
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 66cd2a0664..917a8fe595 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -417,6 +417,7 @@ import {EMPTY_INBOX_UNREAD_SUMMARY,IssueUnreadPageSchema,EMPTY_ISSUE_UNREAD_PAGE,+ SubscribedIssueIdsSchema,InboxItemListSchema,ArchivedInboxPageSchema,ArchivedInboxFacetsSchema,@@ -2954,6 +2955,15 @@ export class ApiClient {return items;}+ async listSubscribedIssueIds(): Promise<string[]> {+ const raw = await this.fetch<unknown>("/api/issues/subscribed");+ const parsed = parseWithFallback<{ issue_ids: string[] } | null>(raw, SubscribedIssueIdsSchema, null, {+ endpoint: "GET /api/issues/subscribed",+ });+ if (!parsed) throw new Error("GET /api/issues/subscribed returned a malformed body");+ return parsed.issue_ids;+ }+async markIssueRead(issueId: string): Promise<void> {await this.fetch(`/api/issues/${issueId}/read`, { method: "POST" });}diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex a2eb3b73e0..d0aced8f2e 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2794,6 +2794,18 @@ export const EMPTY_ISSUE_UNREAD_PAGE: { items: IssueUnread[]; next_cursor: strinnext_cursor: null,};+// The viewer's subscribed issue ids (`/api/issues/subscribed` GET), behind the+// "subscribed" relation filter on client-filtered surfaces. A non-string entry+// is dropped; a body without the list has no safe fallback — an empty set+// would hide every row under the filter — so the client fails the request.+export const SubscribedIssueIdsSchema = z+ .object({+ issue_ids: z+ .array(z.unknown())+ .transform((ids) => ids.filter((id): id is string => typeof id === "string" && id.length > 0)),+ })+ .loose();+// Inbox items (`/api/inbox` and `/api/inbox/archived` GET).// Lenient per the usual rules: `severity` / `type` / `recipient_type` stay// `z.string()` so a notification kind this client doesn't know yet stilldiff --git a/packages/core/api/subscribed-issues.test.ts b/packages/core/api/subscribed-issues.test.tsnew file mode 100644index 0000000000..87d6f46dfe--- /dev/null+++ b/packages/core/api/subscribed-issues.test.ts@@ -0,0 +1,30 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from "vitest";+import { ApiClient } from "./client";++afterEach(() => vi.unstubAllGlobals());++const list = (body: unknown) => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json(body)));+ return new ApiClient("https://api.example.test").listSubscribedIssueIds();+};++describe("listSubscribedIssueIds", () => {+ it("returns the ids and tolerates extra fields", async () => {+ await expect(list({ issue_ids: ["i-1", "i-2"], extra: true })).resolves.toEqual(["i-1", "i-2"]);+ });++ it("drops entries that are not ids", async () => {+ await expect(list({ issue_ids: ["i-1", 7, null, "", "i-2"] })).resolves.toEqual(["i-1", "i-2"]);+ });++ // An empty fallback would make "subscribed" hide every row; failing lets the+ // surface show its retryable error instead.+ it.each([+ ["a missing list", {}],+ ["a non-array list", { issue_ids: "i-1" }],+ ["a null body", null],+ ])("fails for %s", async (_name, body) => {+ await expect(list(body)).rejects.toThrow("malformed");+ });+});diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.tsindex 51bbf6a858..ba41c15468 100644--- a/packages/core/issues/mutations.ts+++ b/packages/core/issues/mutations.ts@@ -36,6 +36,8 @@ import {pruneDeletedIssueFromParentChildrenCaches,} from "./delete-cache";import { useWorkspaceId } from "../hooks";+import { refreshSubscribedIssues } from "./subscribed";+import { getCurrentWsId } from "../platform/workspace-storage";import { useRecentContextStore } from "../chat/recent-context-store";import { useRecentIssuesStore } from "./stores";import type { InboxItem, Issue, IssueReaction } from "../types";@@ -1191,8 +1193,10 @@ export function useToggleIssueSubscriber(issueId: string) {if (ctx?.prev)qc.setQueryData(issueKeys.subscribers(issueId), ctx.prev);},- onSettled: () => {+ onSettled: (_data, _err, { userType }) => {qc.invalidateQueries({ queryKey: issueKeys.subscribers(issueId) });+ const wsId = getCurrentWsId();+ if (wsId && userType === "member") void refreshSubscribedIssues(qc, wsId);},});}@@ -1215,8 +1219,10 @@ export function useUnsubscribeFromIssueSubtree(issueId: string) {}) => {await api.unsubscribeFromIssueSubtree(issueId, userId, userType);},- onSettled: () => {+ onSettled: (_data, _err, { userType }) => {qc.invalidateQueries({ queryKey: issueKeys.subscribersAll() });+ const wsId = getCurrentWsId();+ if (wsId && userType === "member") void refreshSubscribedIssues(qc, wsId);},});}diff --git a/packages/core/issues/stores/filter-tree.ts b/packages/core/issues/stores/filter-tree.tsindex 7e6dbeb97f..ed5345b7bb 100644--- a/packages/core/issues/stores/filter-tree.ts+++ b/packages/core/issues/stores/filter-tree.ts@@ -17,12 +17,13 @@ import { createSafeId } from "../../utils";/** How the viewer relates to an issue. Unlike the "my issues" scope axis this* is an ordinary filter dimension: OR within, AND with everything else. */-export type IssueRelationFilter = "assigned" | "created" | "my_agents";+export type IssueRelationFilter = "assigned" | "created" | "my_agents" | "subscribed";export const ISSUE_RELATION_FILTERS: readonly IssueRelationFilter[] = ["assigned","created","my_agents",+ "subscribed",];/** Relative due-date buckets. A view stores the bucket, never a date, so it@@ -563,6 +564,20 @@ export function advancedFilterUsesField();}+/** Whether a (pruned) tree tests this value of a dimension anywhere. */+export function advancedFilterUsesValue(+ group: AdvancedFilterGroup | null | undefined,+ field: NegatableFilterDimension,+ value: string,+): boolean {+ if (!group) return false;+ return group.children.some((child) =>+ child.type === "group"+ ? advancedFilterUsesValue(child, field, value)+ : child.field === field && (child.values as readonly unknown[]).includes(value),+ );+}+/** The table-query form of a tree, or undefined when it constrains nothing. */export function advancedFilterToTableQuery(group: AdvancedFilterGroup | null | undefined,diff --git a/packages/core/issues/subscribed.test.ts b/packages/core/issues/subscribed.test.tsnew file mode 100644index 0000000000..40b3940a5c--- /dev/null+++ b/packages/core/issues/subscribed.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import { QueryClient } from "@tanstack/react-query";+import { issueKeys } from "./queries";+import { refreshSubscribedIssues, subscribedIssueKeys } from "./subscribed";++describe("refreshSubscribedIssues", () => {+ it("invalidates the id set and only the issue queries filtered by subscribed", async () => {+ const qc = new QueryClient();+ const subscribedRows = [...issueKeys.tableAll("ws-1"), "rows", { filters: { relations: ["subscribed"] } }];+ const subscribedTree = [+ ...issueKeys.tableAll("ws-1"),+ "facets",+ { filters: { advanced: { match: "all", children: [{ field: "relations", values: ["subscribed"] }] } } },+ ];+ const assignedRows = [...issueKeys.tableAll("ws-1"), "rows", { filters: { relations: ["assigned"] } }];+ const otherWorkspace = [...issueKeys.tableAll("ws-2"), "rows", { filters: { relations: ["subscribed"] } }];+ for (const key of [subscribedRows, subscribedTree, assignedRows, otherWorkspace]) qc.setQueryData(key, {});+ qc.setQueryData(subscribedIssueKeys.all("ws-1"), ["issue-1"]);++ await refreshSubscribedIssues(qc, "ws-1");++ const stale = (key: readonly unknown[]) => qc.getQueryState(key)?.isInvalidated;+ expect(stale(subscribedRows)).toBe(true);+ expect(stale(subscribedTree)).toBe(true);+ expect(stale(subscribedIssueKeys.all("ws-1"))).toBe(true);+ expect(stale(assignedRows)).toBe(false);+ expect(stale(otherWorkspace)).toBe(false);+ });+});diff --git a/packages/core/issues/subscribed.ts b/packages/core/issues/subscribed.tsnew file mode 100644index 0000000000..79e6b4f09b--- /dev/null+++ b/packages/core/issues/subscribed.ts@@ -0,0 +1,38 @@+import { queryOptions, type Query, type QueryClient } from "@tanstack/react-query";+import { api } from "../api";+import { issueKeys } from "./queries";++/**+ * The ids of the issues the viewer subscribes to, for evaluating the+ * "subscribed" relation on rows the client filters itself. Kept outside+ * `issueKeys` so the broad issue invalidations do not refetch it; it changes+ * only with the viewer's own subscriptions.+ */+export const subscribedIssueKeys = {+ all: (wsId: string) => ["issue-subscribed", wsId] as const,+};++export function subscribedIssueIdsOptions(wsId: string) {+ return queryOptions({+ queryKey: subscribedIssueKeys.all(wsId),+ queryFn: () => api.listSubscribedIssueIds(),+ });+}++function filtersBySubscribed(query: Query): boolean {+ return JSON.stringify(query.queryKey).includes('"subscribed"');+}++/**+ * Re-reads what depends on the viewer's subscriptions after one changed: the+ * id set, and every issue query (rows, groups, facets, sidebar lists) whose+ * filter names the relation. Cancels the+ * set first so a change during its first load is not answered by the request+ * already on the wire (see `refreshIssueUnread`).+ */+export async function refreshSubscribedIssues(qc: QueryClient, wsId: string) {+ qc.invalidateQueries({ queryKey: issueKeys.all(wsId), predicate: filtersBySubscribed });+ const queryKey = subscribedIssueKeys.all(wsId);+ await qc.cancelQueries({ queryKey });+ await qc.invalidateQueries({ queryKey });+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 091bafff92..bb5abf90e5 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -49,6 +49,7 @@"./issues/comment-trigger-outcomes": "./issues/comment-trigger-outcomes.ts","./issues/run-steering": "./issues/run-steering.ts","./issues/unread": "./issues/unread.ts",+ "./issues/subscribed": "./issues/subscribed.ts","./issues/date": "./issues/date.ts","./issues/ws-updaters": "./issues/ws-updaters.ts","./issues/sidebar-list": "./issues/sidebar-list.ts",diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex d07c35814e..ba1932e5c1 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -133,13 +133,13 @@ describe("useRealtimeSync — ws instance change", () => {// (19 workspace-scoped [incl. property definitions, workflows, saved views// and view preferences] + 6 per-issue prefixes + the workspace// working-agents projection + 5 per-chat prefixes + 1 workspaceKeys.list()- // + 1 cross-workspace inbox unread summary + 1 issue unread marks = 35- // calls).+ // + 1 cross-workspace inbox unread summary + 1 issue unread marks + 1+ // subscribed issue ids = 36 calls).//// Awaited rather than counted synchronously: the inbox unread summary// refresh cancels any in-flight request before invalidating (see// onInboxSummaryInvalidate), so that one lands after the synchronous ones.- await waitFor(() => expect(invalidateSpy).toHaveBeenCalledTimes(35));+ await waitFor(() => expect(invalidateSpy).toHaveBeenCalledTimes(36));});it("does not re-invalidate when rerendered with the same ws instance", () => {@@ -660,6 +660,29 @@ describe("useRealtimeSync — Table server membership invalidation", () => {queryKey: issueKeys.tableAll("ws-1"),});});++ it("refreshes subscribed-filtered queries only for the viewer's own subscription", async () => {+ const ws = createMockWs();+ renderHook(() => useRealtimeSync(ws, stores), {+ wrapper: createWrapper(qc),+ });+ const handler = (event: string) =>+ vi.mocked(ws.on).mock.calls.find(([name]) => name === event)?.[1] as (payload: unknown) => void;+ const rows = [...issueKeys.tableAll("ws-1"), "rows", { filters: { relations: ["subscribed"] } }];+ const isStale = () => qc.getQueryState(rows)?.isInvalidated;++ qc.setQueryData(rows, {});+ handler("subscriber:added")({ issue_id: "i-1", user_type: "member", user_id: "someone-else", reason: "manual" });+ handler("subscriber:added")({ issue_id: "i-1", user_type: "agent", user_id: "u1", reason: "manual" });+ expect(isStale()).toBe(false);++ handler("subscriber:added")({ issue_id: "i-1", user_type: "member", user_id: "u1", reason: "manual" });+ await waitFor(() => expect(isStale()).toBe(true));++ qc.setQueryData(rows, {});+ handler("subscriber:removed")({ issue_id: "i-1", user_type: "member", user_id: "u1" });+ await waitFor(() => expect(isStale()).toBe(true));+ });});describe("useRealtimeSync — workspace:deleted self-initiated suppression", () => {diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 660359c837..13e35a8ad5 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -13,6 +13,7 @@ import { getCurrentWsId, getCurrentSlug } from "../platform/workspace-storage";import { issueKeys } from "../issues/queries";import { isSidebarTableRequest, type SidebarIssuesRequest } from "../issues/sidebar-list";import { refreshIssueUnread } from "../issues/unread";+import { refreshSubscribedIssues, subscribedIssueKeys } from "../issues/subscribed";import { projectKeys } from "../projects/queries";import { pinKeys } from "../pins/queries";import { autopilotKeys } from "../autopilots/queries";@@ -652,6 +653,7 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {if (wsId) {qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });void refreshIssueUnread(qc, wsId);+ qc.invalidateQueries({ queryKey: subscribedIssueKeys.all(wsId) });// Through the inbox's own entry point, not a plain invalidate: a reconnect// can land during the list's first load, and a plain invalidate would be// answered by the request already on the wire (see refreshInboxQuery).@@ -1344,15 +1346,22 @@ export function useRealtimeSync(}});- const unsubSubscriberAdded = ws.on("subscriber:added", (p) => {- const { issue_id } = p as SubscriberAddedPayload;- if (issue_id) qc.invalidateQueries({ queryKey: issueKeys.subscribers(issue_id) });- });-- const unsubSubscriberRemoved = ws.on("subscriber:removed", (p) => {- const { issue_id } = p as SubscriberRemovedPayload;- if (issue_id) qc.invalidateQueries({ queryKey: issueKeys.subscribers(issue_id) });- });+ // The viewer's own subscription changing also moves issues in and out of+ // views filtered by the "subscribed" relation.+ const onSubscriberChanged = (p: SubscriberAddedPayload | SubscriberRemovedPayload) => {+ if (!p.issue_id) return;+ qc.invalidateQueries({ queryKey: issueKeys.subscribers(p.issue_id) });+ const wsId = getCurrentWsId();+ if (wsId && p.user_type === "member" && p.user_id === authStore.getState().user?.id) {+ void refreshSubscribedIssues(qc, wsId);+ }+ };+ const unsubSubscriberAdded = ws.on("subscriber:added", (p) =>+ onSubscriberChanged(p as SubscriberAddedPayload),+ );+ const unsubSubscriberRemoved = ws.on("subscriber:removed", (p) =>+ onSubscriberChanged(p as SubscriberRemovedPayload),+ );// --- Side-effect handlers (toast, navigation) ---diff --git a/packages/core/types/api.ts b/packages/core/types/api.tsindex 5548882e10..de9a396fc2 100644--- a/packages/core/types/api.ts+++ b/packages/core/types/api.ts@@ -312,7 +312,7 @@ export type IssueTableScope =| { kind: "creator"; actor: IssueActorRef }| { kind: "my"; relation: "assigned" | "created" | "involved" | "any" };-export type IssueTableRelation = "assigned" | "created" | "my_agents";+export type IssueTableRelation = "assigned" | "created" | "my_agents" | "subscribed";export type IssueTableNegatableFilter =| "statuses"diff --git a/packages/views/issues/components/filter-field-options.tsx b/packages/views/issues/components/filter-field-options.tsxindex 496688559d..3eb74e825f 100644--- a/packages/views/issues/components/filter-field-options.tsx+++ b/packages/views/issues/components/filter-field-options.tsx@@ -3,6 +3,7 @@import { useMemo, type ReactNode } from "react";import { useQuery } from "@tanstack/react-query";import {+ BellRing,Bot,CalendarClock,CircleDashed,@@ -57,6 +58,7 @@ const RELATION_ICONS: Record<IssueRelationFilter, IconComponent> = {assigned: CircleUser,created: UserPen,my_agents: Bot,+ subscribed: BellRing,};export const DUE_DATE_LABEL_KEY: Record<@@ -72,11 +74,12 @@ export const DUE_DATE_LABEL_KEY: Record<export const RELATION_LABEL_KEY: Record<IssueRelationFilter,- "relation_assigned" | "relation_created" | "relation_my_agents"+ "relation_assigned" | "relation_created" | "relation_my_agents" | "relation_subscribed"> = {assigned: "relation_assigned",created: "relation_created",my_agents: "relation_my_agents",+ subscribed: "relation_subscribed",};export function useFilterFieldLabels(): Record<NegatableFilterDimension, string> {diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsxindex 5916cbe878..01d1d6bcef 100644--- a/packages/views/issues/components/issues-header.tsx+++ b/packages/views/issues/components/issues-header.tsx@@ -3,6 +3,7 @@import { cloneElement, useEffect, useMemo, useRef, useState } from "react";import {Activity,+ BellRing,Bot,CalendarClock,CalendarDays,@@ -938,6 +939,7 @@ const RELATION_ICONS: Record<IssueRelationFilter, typeof User> = {assigned: CircleUser,created: UserPen,my_agents: Bot,+ subscribed: BellRing,};/** Read-only sentence form of the active filters, shown on hover so a closed@@ -1379,8 +1381,8 @@ export function IssueFilterMenu({</DropdownMenuSub>)}- {/* Relation to me — OR across assigned / created / my agents,- which no single actor dimension can express. */}+ {/* Relation to me — OR across assigned / created / my agents /+ subscribed, which no single actor dimension can express. */}{showRelation && show("relation") && (<DropdownMenuSub><DropdownMenuSubTrigger>diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsxindex 1d0e3af7a8..a2cc6ab1f4 100644--- a/packages/views/issues/surface/issue-surface.tsx+++ b/packages/views/issues/surface/issue-surface.tsx@@ -296,6 +296,8 @@ function IssueSurfaceContent({<FilterDependencyErrorState kind="working" onRetry={controller.retryWorkingFilter} />) : controller.isUnreadFilterError ? (<FilterDependencyErrorState kind="unread" onRetry={controller.retryUnreadFilter} />+ ) : controller.isRelationFilterError ? (+ <FilterDependencyErrorState kind="relation" onRetry={controller.retryRelationFilter} />) : controller.isLoading ? (renderLoading ? (renderLoading(renderContext)@@ -422,7 +424,7 @@ function FilterDependencyErrorState({kind,onRetry,}: {- kind: "status" | "working" | "unread";+ kind: "status" | "working" | "unread" | "relation";onRetry: () => void;}) {const { t } = useT("issues");@@ -436,9 +438,17 @@ function FilterDependencyErrorState({? t(($) => $.working_filter_error.title): kind === "unread"? t(($) => $.unread_filter_error.title)- : t(($) => $.status_catalog_error.title)+ : kind === "relation"+ ? t(($) => $.relation_filter_error.title)+ : t(($) => $.status_catalog_error.title)+ }+ description={+ kind === "status"+ ? t(($) => $.status_catalog_error.hint)+ : kind === "relation"+ ? t(($) => $.relation_filter_error.hint)+ : undefined}- description={kind === "status" ? t(($) => $.status_catalog_error.hint) : undefined}actions={<Button variant="outline" size="sm" onClick={onRetry}>{t(($) => $.status_catalog_error.retry)}diff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsxindex cc4ef5bd1f..12e48a31d5 100644--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx@@ -14,7 +14,9 @@ import {pruneIssueSurfaceViewStates,} from "@multica/core/issues/stores/surface-view-store";import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";+import type { IssueRelationFilter } from "@multica/core/issues/stores/view-store";import type {+ Agent,AgentTask,Issue,IssueStatus,@@ -162,6 +164,8 @@ describe("useIssueSurfaceController", () => {let listIssueTableRows: ReturnType<typeof vi.fn>;let listIssueUnread: ReturnType<typeof vi.fn>;let listIssueTableFacets: ReturnType<typeof vi.fn>;+ let listSubscribedIssueIds: ReturnType<typeof vi.fn<() => Promise<string[]>>>;+ let listAgents: ReturnType<typeof vi.fn<() => Promise<Agent[]>>>;// Every row the current fixture holds, kept outside the mocked list endpoint// so the working-agents facet stand-in can read it without registering a// call that Table-isolation tests assert never happens.@@ -187,6 +191,8 @@ describe("useIssueSurfaceController", () => {listIssueTableRows = vi.fn(tableMethods.listIssueTableRows);listIssueTableFacets = vi.fn(tableMethods.listIssueTableFacets);listIssueUnread = vi.fn(() => Promise.resolve([]));+ listSubscribedIssueIds = vi.fn(() => never<string[]>());+ listAgents = vi.fn(() => Promise.resolve([] satisfies Agent[]));setApiInstance({// The board pages by category, so every surface stub answers the catalog// read. Empty is the real shape for a workspace with no custom statuses:@@ -202,6 +208,8 @@ describe("useIssueSurfaceController", () => {getWorkspaceWorkingAgents,listIssueUnread,getChildIssueProgress: vi.fn(() => never()),+ listAgents,+ listSubscribedIssueIds,} as unknown as ApiClient);pruneIssueSurfaceViewStates([]);updateIssueMutate.mockClear();@@ -1913,6 +1921,97 @@ describe("useIssueSurfaceController", () => {}),];+ describe("Gantt filtered by subscribed", () => {+ const renderSubscribedGantt = (relations: IssueRelationFilter[] = ["subscribed"]) => {+ mockGanttIssues(ganttFixture);+ const store = getIssueSurfaceViewStore("project:p1");+ act(() => {+ store.getState().setViewMode("gantt");+ for (const relation of relations) store.getState().toggleRelationFilter(relation);+ });+ return renderHook(+ () => useIssueSurfaceController({ scope: { type: "project", projectId: "p1" }, modes: ["gantt"] }),+ { wrapper: makeWrapper(qc, "project:p1") },+ );+ };++ it("holds loading until the subscriptions arrive, then draws only subscribed rows", async () => {+ let finish!: (ids: string[]) => void;+ listSubscribedIssueIds.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ const { result } = renderSubscribedGantt();++ // The canvas rows are in; only the subscriptions are outstanding.+ await waitFor(() => expect(result.current.ganttIssues).toHaveLength(ganttFixture.length));+ expect(listSubscribedIssueIds).toHaveBeenCalled();+ expect(result.current.isLoading).toBe(true);+ expect(result.current.isRelationFilterError).toBe(false);++ await act(async () => finish([]));+ await waitFor(() => expect(result.current.isLoading).toBe(false));+ expect(result.current.filteredGanttIssues).toEqual([]);+ });++ it("offers a retry instead of unfiltered rows when the subscriptions fail", async () => {+ listSubscribedIssueIds.mockRejectedValueOnce(new Error("offline"));+ const { result } = renderSubscribedGantt();++ await waitFor(() => expect(result.current.isRelationFilterError).toBe(true));+ expect(result.current.isEmpty).toBe(false);++ listSubscribedIssueIds.mockResolvedValue(["gantt-open"]);+ act(() => result.current.retryRelationFilter());+ await waitFor(() => expect(result.current.isRelationFilterError).toBe(false));+ await waitFor(() =>+ expect(result.current.filteredGanttIssues.map((issue) => issue.id)).toEqual(["gantt-open"]),+ );+ });++ it.each([+ { name: "never arrives", agents: () => never<Agent[]>() },+ { name: "fails", agents: () => Promise.reject(new Error("offline")) },+ ])("filters by subscriptions when the agent list $name", async ({ agents }) => {+ listAgents.mockImplementation(agents);+ listSubscribedIssueIds.mockResolvedValue([]);+ const { result } = renderSubscribedGantt();++ await waitFor(() => expect(result.current.ganttIssues).toHaveLength(ganttFixture.length));+ await waitFor(() => expect(result.current.isLoading).toBe(false));+ expect(result.current.isRelationFilterError).toBe(false);+ expect(result.current.filteredGanttIssues).toEqual([]);+ });++ it("holds loading while the agents behind \"my agents\" load", async () => {+ let finish!: (agents: Agent[]) => void;+ listAgents.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ listSubscribedIssueIds.mockResolvedValue([]);+ const { result } = renderSubscribedGantt(["subscribed", "my_agents"]);++ await waitFor(() => expect(result.current.ganttIssues).toHaveLength(ganttFixture.length));+ await waitFor(() => expect(listSubscribedIssueIds).toHaveBeenCalled());+ expect(result.current.isLoading).toBe(true);++ await act(async () => finish([{ id: "agent-1", owner_id: "user-1" } as Agent]));+ await waitFor(() => expect(result.current.isLoading).toBe(false));+ expect(result.current.filteredGanttIssues.map((issue) => issue.id)).toEqual(["gantt-open"]);+ });++ it("offers a retry when the agents behind \"my agents\" fail", async () => {+ listAgents.mockRejectedValueOnce(new Error("offline"));+ listSubscribedIssueIds.mockResolvedValue([]);+ const { result } = renderSubscribedGantt(["subscribed", "my_agents"]);++ await waitFor(() => expect(result.current.isRelationFilterError).toBe(true));+ expect(result.current.isEmpty).toBe(false);++ listAgents.mockResolvedValue([{ id: "agent-1", owner_id: "user-1" } as Agent]);+ act(() => result.current.retryRelationFilter());+ await waitFor(() => expect(result.current.isRelationFilterError).toBe(false));+ await waitFor(() =>+ expect(result.current.filteredGanttIssues.map((issue) => issue.id)).toEqual(["gantt-open"]),+ );+ });+ });+it("still loads Gantt's canvas projection without the working filter and leaves its count unknown until ready", async () => {mockGanttIssues(ganttFixture);let finish!: (agents: WorkspaceWorkingAgent[]) => void;diff --git a/packages/views/issues/surface/use-issue-surface-controller.ts b/packages/views/issues/surface/use-issue-surface-controller.tsindex b000a315f2..d09e14e3da 100644--- a/packages/views/issues/surface/use-issue-surface-controller.ts+++ b/packages/views/issues/surface/use-issue-surface-controller.ts@@ -24,6 +24,7 @@ import { useIssueUnreadIds } from "@multica/core/issues/unread";import {advancedFilterToTableQuery,advancedFilterUsesField,+ advancedFilterUsesValue,FILTER_DIMENSION_TABLE_FIELD,statusColumnFilter,propertyIdOfField,@@ -52,6 +53,7 @@ import {import { useViewStore } from "@multica/core/issues/stores/view-store-context";import { useAuthStore } from "@multica/core/auth";import { agentListOptions } from "@multica/core/workspace/queries";+import { subscribedIssueIdsOptions } from "@multica/core/issues/subscribed";import { useShallow } from "zustand/react/shallow";import type { IssueFilters, IssueRelationContext } from "../utils/filter";import type { ChildProgress } from "../components/list-row";@@ -154,6 +156,11 @@ export interface IssueSurfaceController {retryWorkingFilter: () => void;isUnreadFilterError: boolean;retryUnreadFilter: () => void;+ /** The viewer's subscriptions or agents behind a "subscribed" /+ * "my_agents" relation failed to load on a surface that filters by them+ * itself. */+ isRelationFilterError: boolean;+ retryRelationFilter: () => void;openCreateIssue: (defaults?: IssueCreateDefaults) => void;moveIssue: (issueId: string,@@ -321,19 +328,47 @@ export function useIssueSurfaceController({dueDateFilters.length > 0 || advancedFilterUsesField(advancedFilter, "dueDate");const today = usesDueDates ? todayDateOnly() : undefined;const userId = useAuthStore((s) => s.user?.id);- const { data: agents } = useQuery({+ // Each relation value reads only its own dependency, so a slow or failed+ // agent list never switches off "subscribed" (and vice versa).+ const usesMyAgents =+ relationFilters.includes("my_agents") ||+ advancedFilterUsesValue(advancedFilter, "relation", "my_agents");+ const usesSubscribed =+ relationFilters.includes("subscribed") ||+ advancedFilterUsesValue(advancedFilter, "relation", "subscribed");+ const agentsQuery = useQuery({...agentListOptions(wsId),- enabled: relationFilters.length > 0 || advancedFilterUsesField(advancedFilter, "relation"),+ enabled: usesMyAgents,});+ const agents = agentsQuery.data;+ const subscribedIssueIdsQuery = useQuery({+ ...subscribedIssueIdsOptions(wsId),+ enabled: usesSubscribed,+ });+ const subscribedIssueIds = subscribedIssueIdsQuery.data;+ const agentsUnresolved = usesMyAgents && agents === undefined;+ const subscribedIdsUnresolved = usesSubscribed && subscribedIssueIds === undefined;+ const relationDepsError =+ (agentsUnresolved && agentsQuery.isError) ||+ (subscribedIdsUnresolved && subscribedIssueIdsQuery.isError);+ const relationDepsPending =+ !relationDepsError && (agentsUnresolved || subscribedIdsUnresolved);const relationContext = useMemo<IssueRelationContext | undefined>(() => {- if (!userId || !agents) return undefined;+ if (!userId) return undefined;return {userId,- myAgentIds: new Set(- agents.filter((agent) => agent.owner_id === userId).map((agent) => agent.id),- ),+ ...(usesMyAgents && agents+ ? {+ myAgentIds: new Set(+ agents.filter((agent) => agent.owner_id === userId).map((agent) => agent.id),+ ),+ }+ : {}),+ ...(usesSubscribed && subscribedIssueIds+ ? { subscribedIssueIds: new Set(subscribedIssueIds) }+ : {}),};- }, [agents, userId]);+ }, [agents, subscribedIssueIds, userId, usesMyAgents, usesSubscribed]);const allowedModes = useMemo(() => new Set<IssueSurfaceMode>(modes), [modes]);const fallbackMode = modes[0] ?? "list";@@ -918,6 +953,8 @@ export function useIssueSurfaceController({labelFilters,relationFilters,relationContext,+ relationDepsPending,+ relationDepsError,dueDateFilters,advancedFilter,today,@@ -1061,6 +1098,11 @@ export function useIssueSurfaceController({retryUnreadFilter: () => {void unreadProjection.refetch();},+ isRelationFilterError: data.isRelationFilterError,+ retryRelationFilter: () => {+ if (agentsQuery.isError) void agentsQuery.refetch();+ if (subscribedIssueIdsQuery.isError) void subscribedIssueIdsQuery.refetch();+ },sort,actions,selection,diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.tsindex 38c7f95370..7df48abc58 100644--- a/packages/views/issues/surface/use-issue-surface-data.ts+++ b/packages/views/issues/surface/use-issue-surface-data.ts@@ -97,6 +97,10 @@ export interface IssueSurfaceData {/** Re-runs the project list behind the project-status half of* {@link isStatusCatalogError}. */retryProjectCatalog: () => void;+ /** The viewer's subscriptions or agents behind a "subscribed" /+ * "my_agents" relation failed to load and this surface applies the+ * relation itself. */+ isRelationFilterError: boolean;/** The window's data is being revalidated while the previous snapshot is* shown as a placeholder (sort/date change, or any grouped-board filter* change). Drives the header's deferred refresh indicator — content stays@@ -130,6 +134,8 @@ export function useIssueSurfaceData({labelFilters,relationFilters,relationContext,+ relationDepsPending,+ relationDepsError,dueDateFilters,advancedFilter,today,@@ -168,6 +174,10 @@ export function useIssueSurfaceData({labelFilters: string[];relationFilters: IssueRelationFilter[];relationContext: IssueRelationContext | undefined;+ /** A filter uses "subscribed" or "my_agents" and the data it reads (the+ * viewer's subscriptions / agents) has not loaded yet / failed to load. */+ relationDepsPending: boolean;+ relationDepsError: boolean;dueDateFilters: DueDateFilter[];/** The scoped, pruned rule tree. */advancedFilter: AdvancedFilterGroup | null;@@ -227,6 +237,10 @@ export function useIssueSurfaceData({(usesGantt || !serverStatusBranches.enabled);const projectCatalogPending = usesClientProjectStatusFilter && projectsPending;const projectCatalogError = usesClientProjectStatusFilter && projectsError;+ // Same contract for the subscriptions / agents behind the relation filter.+ const usesClientRelationFilter = !usesTable && (usesGantt || !serverStatusBranches.enabled);+ const relationFilterPending = usesClientRelationFilter && relationDepsPending;+ const relationFilterError = usesClientRelationFilter && relationDepsError;const workingFilterContext = useMemo(() => ({@@ -509,6 +523,7 @@ export function useIssueSurfaceData({const isLoading =statusFilterPending ||projectCatalogPending ||+ relationFilterPending ||(serverGroupBranches.enabled? serverGroupBranches.isLoading: usesGantt@@ -555,6 +570,7 @@ export function useIssueSurfaceData({!isLoading &&!statusFilterError &&!projectCatalogError &&+ !relationFilterError &&!usesGantt &&!usesTable &&(serverStatusBranches.enabled@@ -568,5 +584,6 @@ export function useIssueSurfaceData({// either one. `retryStatusCatalog` refetches both.isStatusCatalogError: statusFilterError || projectCatalogError,retryProjectCatalog: refetchProjects,+ isRelationFilterError: relationFilterError,};}diff --git a/packages/views/issues/utils/filter.test.ts b/packages/views/issues/utils/filter.test.tsindex eb2c5a79d0..6d8237328e 100644--- a/packages/views/issues/utils/filter.test.ts+++ b/packages/views/issues/utils/filter.test.ts@@ -809,6 +809,36 @@ describe("relation filters", () => {filterIssues(issues, { ...NO_FILTER, relationFilters: ["assigned"] }).map((i) => i.id),).toEqual(["1", "2", "3", "4"]);});++ it("matches subscribed against the viewer's subscriptions", () => {+ const withSubscriptions = { ...relationContext, subscribedIssueIds: new Set(["2", "3"]) };+ expect(ids({ relationContext: withSubscriptions, relationFilters: ["subscribed"] })).toEqual(["2", "3"]);+ expect(+ ids({ relationContext: withSubscriptions, relationFilters: ["subscribed"], negatedFilters: ["relation"] }),+ ).toEqual(["1", "4"]);+ });++ it("leaves subscribed to the server without the subscriptions, either way round", () => {+ expect(ids({ relationFilters: ["subscribed"] })).toEqual(["1", "2", "3", "4"]);+ expect(ids({ relationFilters: ["subscribed"], negatedFilters: ["relation"] })).toEqual(["1", "2", "3", "4"]);+ });++ it("still decides an issue a known relation matches alongside subscribed", () => {+ expect(+ ids({ relationFilters: ["assigned", "subscribed"], negatedFilters: ["relation"] }),+ ).toEqual(["2", "3", "4"]);+ });++ it("answers subscribed without the viewer's agents, leaving only my_agents open", () => {+ const subscriptionsOnly = { userId: "u-1", subscribedIssueIds: new Set(["3"]) };+ expect(ids({ relationContext: subscriptionsOnly, relationFilters: ["subscribed"] })).toEqual(["3"]);+ expect(ids({ relationContext: subscriptionsOnly, relationFilters: ["my_agents"] })).toEqual([+ "1",+ "2",+ "3",+ "4",+ ]);+ });});describe("due date filters", () => {@@ -877,6 +907,31 @@ describe("advanced filter", () => {expect(ids(tree, { relationContext: { userId: "u-1", myAgentIds: new Set(["a-1"]) } })).toEqual(["2", "3"]);});+ describe("subscribed", () => {+ const viewer = { userId: "u-1", myAgentIds: new Set(["a-1"]) };+ const subscribedNotMine = createFilterGroup("all", [+ createFilterCondition("relation", ["subscribed"]),+ createFilterCondition("relation", ["assigned", "my_agents"], true),+ ]);+ const subscribedOrUrgent = createFilterGroup("any", [+ createFilterCondition("relation", ["subscribed"]),+ createFilterCondition("priority", ["urgent"]),+ ]);+ const relationContext = { ...viewer, subscribedIssueIds: new Set(["2", "3"]) };++ it("answers 'subscribed, not mine' with the viewer's subscriptions", () => {+ expect(ids(subscribedNotMine, { relationContext })).toEqual(["3"]);+ });++ it("keeps subscribed issues an OR sibling does not match", () => {+ expect(ids(subscribedOrUrgent, { relationContext })).toEqual(["2", "3", "4"]);+ });++ it("drops out without the subscriptions", () => {+ expect(ids(subscribedNotMine, { relationContext: viewer })).toEqual(["3", "4"]);+ });+ });+it("is ANDed with the simple filters", () => {const tree = createFilterGroup("all", [createFilterCondition("project", ["p-1"])]);expect(ids(tree, { priorityFilters: ["high"] })).toEqual(["1"]);diff --git a/packages/views/issues/utils/filter.ts b/packages/views/issues/utils/filter.tsindex 8f7ebc9ef5..59f8427053 100644--- a/packages/views/issues/utils/filter.ts+++ b/packages/views/issues/utils/filter.ts@@ -113,8 +113,12 @@ export interface IssueFilterContext {export interface IssueRelationContext {userId: string;- /** Agents the viewer owns. */- myAgentIds: ReadonlySet<string>;+ /** Agents the viewer owns. Loaded only while a filter tests "my_agents";+ * without it that relation is left to the server. */+ myAgentIds?: ReadonlySet<string>;+ /** Issues the viewer subscribes to. Loaded only while a filter tests the+ * relation; without it "subscribed" is left to the server. */+ subscribedIssueIds?: ReadonlySet<string>;}/**@@ -349,10 +353,8 @@ export function applyIssueFilters(}if (hasRelationFilter) {- const matched = relationFilters.some((relation) =>- issueMatchesRelation(issue, relation, relationContext),- );- if (!passes("relation", matched)) return false;+ const matched = issueMatchesRelations(issue, relationFilters, relationContext);+ if (matched !== undefined && !passes("relation", matched)) return false;}if (dueDateFilters.length > 0) {@@ -369,17 +371,36 @@ export function applyIssueFilters(});}+/** OR across relations, or undefined when no listed relation matches and one+ * of them cannot be answered with this context. */+function issueMatchesRelations(+ issue: Issue,+ relations: readonly IssueRelationFilter[],+ context: IssueRelationContext,+): boolean | undefined {+ let unknown = false;+ for (const relation of relations) {+ const matched = issueMatchesRelation(issue, relation, context);+ if (matched) return true;+ if (matched === undefined) unknown = true;+ }+ return unknown ? undefined : false;+}+function issueMatchesRelation(issue: Issue,relation: IssueRelationFilter,context: IssueRelationContext,-): boolean {+): boolean | undefined {switch (relation) {+ case "subscribed":+ return context.subscribedIssueIds?.has(issue.id);case "assigned":return issue.assignee_type === "member" && issue.assignee_id === context.userId;case "created":return issue.creator_type === "member" && issue.creator_id === context.userId;case "my_agents":+ if (!context.myAgentIds) return undefined;return (issue.assignee_type === "agent" &&!!issue.assignee_id &&@@ -463,9 +484,9 @@ function issueMatchesFilterCondition(case "relation": {const relation = context.relation;if (!relation) return undefined;- matched = values.some((value) =>- issueMatchesRelation(issue, value as IssueRelationFilter, relation),- );+ const answer = issueMatchesRelations(issue, values as IssueRelationFilter[], relation);+ if (answer === undefined) return undefined;+ matched = answer;break;}case "dueDate":diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex aaaf0ea631..2b5693ec34 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -47,6 +47,10 @@"hint": "Issues can't be shown until statuses load.","retry": "Try again"},+ "relation_filter_error": {+ "title": "Couldn't load the \"Relation to me\" filter",+ "hint": "Issues filtered by \"Subscribed by me\" or \"Assigned to my agents\" can't be shown until your subscriptions and agents load."+ },"source_context": {"create_action": "Create sub-issue from here","preview_loading": "Loading captured source preview…",@@ -184,6 +188,7 @@"relation_assigned": "Assigned to me","relation_created": "Created by me","relation_my_agents": "Assigned to my agents",+ "relation_subscribed": "Subscribed by me","section_agent_status": "Agent status","agent_status_running": "Running","section_read_state": "Read state",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex b9e2f3dfda..be0119d3df 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -47,6 +47,10 @@"hint": "Les tâches ne peuvent pas s’afficher tant que les statuts ne sont pas chargés.","retry": "Réessayer"},+ "relation_filter_error": {+ "title": "Impossible de charger le filtre « Lien avec moi »",+ "hint": "Les tâches filtrées par « Auxquels je suis abonné » ou « Assignés à mes agents » s'affichent une fois vos abonnements et agents chargés."+ },"source_context": {"create_action": "Créer une sous-tâche à partir d'ici","preview_loading": "Chargement de l'aperçu de la source capturée…",@@ -184,6 +188,7 @@"relation_assigned": "Qui me sont assignés","relation_created": "Créés par moi","relation_my_agents": "Assignés à mes agents",+ "relation_subscribed": "Auxquels je suis abonné","section_agent_status": "Statut de l'agent","agent_status_running": "En cours d'exécution","section_read_state": "État de lecture",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 23ea4071bd..315d6e5efb 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -46,6 +46,10 @@"hint": "ステータスを読み込むまでタスクを表示できません。","retry": "再試行"},+ "relation_filter_error": {+ "title": "「自分との関係」フィルターを読み込めませんでした",+ "hint": "「自分が購読中」または「自分のエージェントが担当」で絞り込んだタスクは、購読とエージェントを読み込むまで表示できません。"+ },"source_context": {"create_action": "このコメントからサブタスクを作成","preview_loading": "参照コンテキストのプレビューを読み込み中…",@@ -182,6 +186,7 @@"relation_assigned": "自分が担当","relation_created": "自分が作成","relation_my_agents": "自分のエージェントが担当",+ "relation_subscribed": "自分が購読中","section_agent_status": "エージェントの状態","agent_status_running": "実行中","section_read_state": "既読状態",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 471c100ff1..d32d4e35d9 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -46,6 +46,10 @@"hint": "상태를 불러와야 태스크를 표시할 수 있습니다.","retry": "다시 시도"},+ "relation_filter_error": {+ "title": "'나와의 관계' 필터를 불러오지 못했습니다",+ "hint": "구독과 에이전트를 불러온 후에 '내가 구독 중' 또는 '내 에이전트가 담당' 필터의 태스크를 표시할 수 있습니다."+ },"source_context": {"create_action": "이 댓글에서 하위 태스크 만들기","preview_loading": "원본 컨텍스트 미리보기를 불러오는 중…",@@ -182,6 +186,7 @@"relation_assigned": "내가 담당","relation_created": "내가 생성","relation_my_agents": "내 에이전트가 담당",+ "relation_subscribed": "내가 구독 중","section_agent_status": "에이전트 상태","agent_status_running": "실행 중","section_read_state": "읽음 상태",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex d353524b15..84dabec649 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -46,6 +46,10 @@"hint": "加载状态后才能显示任务。","retry": "重试"},+ "relation_filter_error": {+ "title": "“与我的关系”筛选加载失败",+ "hint": "加载订阅和智能体后才能显示按“我订阅的”或“分配给我的智能体的”筛选的任务。"+ },"source_context": {"create_action": "从这条评论创建子任务","preview_loading": "正在加载来源上下文预览...",@@ -182,6 +186,7 @@"relation_assigned": "分配给我的","relation_created": "我创建的","relation_my_agents": "分配给我的智能体的",+ "relation_subscribed": "我订阅的","section_agent_status": "智能体状态","agent_status_running": "运行中","section_read_state": "阅读状态",diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.jsonindex 34e7cae1dd..b2276ff633 100644--- a/packages/views/locales/zh-Hant/issues.json+++ b/packages/views/locales/zh-Hant/issues.json@@ -46,6 +46,10 @@"hint": "載入狀態後才能顯示任務。","retry": "重試"},+ "relation_filter_error": {+ "title": "「與我的關係」篩選載入失敗",+ "hint": "載入訂閱和 AI 代理後才能顯示按「我訂閱的」或「分配給我的 AI 代理的」篩選的任務。"+ },"source_context": {"create_action": "從這條評論建立子任務","preview_loading": "正在載入來源上下文預覽...",@@ -182,6 +186,7 @@"relation_assigned": "分配給我的","relation_created": "我建立的","relation_my_agents": "分配給我的 AI 代理的",+ "relation_subscribed": "我訂閱的","section_agent_status": "AI 代理狀態","agent_status_running": "執行中","section_read_state": "閱讀狀態",diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex ac6cd49dc5..572bb11877 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2097,6 +2097,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// The caller's issues with an agent result they have not seen// yet; backs the sidebar's unread dot.r.Get("/unread", h.ListIssueUnread)+ // The caller's subscribed issue ids; backs the "subscribed"+ // relation filter on client-filtered surfaces.+ r.Get("/subscribed", h.ListSubscribedIssueIDs)r.Get("/", h.ListIssues)// POST twin of GET /api/issues for oversized filter sets// (agents-working ids facet) — see QueryIssues.diff --git a/server/internal/handler/issue_table_negation_test.go b/server/internal/handler/issue_table_negation_test.goindex 1d2e363f16..2bce2e7d63 100644--- a/server/internal/handler/issue_table_negation_test.go+++ b/server/internal/handler/issue_table_negation_test.go@@ -37,6 +37,17 @@ func TestIssueTableRowsNegationAndRelations(t *testing.T) {"status": "in_progress", "creator_id": otherUser,})+ subscribe := func(issueID, userType, userID string) {+ dbfx.InsertNoID(t, "issue_subscriber", testutil.Cols{+ "issue_id": issueID, "user_type": userType, "user_id": userID, "reason": "manual",+ }, "issue_id = $1", issueID)+ }+ // Only the test user's own member rows count as "subscribed".+ subscribe(assignedToMe, "member", testUserID)+ subscribe(theirAgent, "member", testUserID)+ subscribe(unassignedByOther, "member", otherUser)+ subscribe(mineByAgent, "agent", myAgent)+fixture := map[string]struct{}{assignedToMe: {}, mineByAgent: {}, theirAgent: {}, unassignedByOther: {},}@@ -101,6 +112,19 @@ func TestIssueTableRowsNegationAndRelations(t *testing.T) {assertRows("relations OR within the dimension",issueTableFiltersRequest{Relations: []string{"assigned", "my_agents"}},assignedToMe, mineByAgent)+ assertRows("relation subscribed matches only my member subscriptions",+ issueTableFiltersRequest{Relations: []string{"subscribed"}},+ assignedToMe, theirAgent)+ assertRows("relation is not subscribed",+ issueTableFiltersRequest{Relations: []string{"subscribed"}, Negate: []string{"relations"}},+ mineByAgent, unassignedByOther)+ subscribedNotMine := issueTableFilterNode{Match: "all", Children: []issueTableFilterNode{+ {Field: "relations", Values: rawValues("subscribed")},+ {Field: "relations", Negate: true, Values: rawValues("assigned", "my_agents")},+ }}+ assertRows("subscribed but not assigned to me or my agents",+ issueTableFiltersRequest{Advanced: &subscribedNotMine},+ theirAgent)assertRows("relation is not created by me",issueTableFiltersRequest{Relations: []string{"created"}, Negate: []string{"relations"}},mineByAgent, theirAgent, unassignedByOther)diff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.goindex d80c541b96..072cae2efb 100644--- a/server/internal/handler/issue_table_query.go+++ b/server/internal/handler/issue_table_query.go@@ -422,7 +422,7 @@ func parseIssueTableActor(w http.ResponseWriter, actor issueTableActorRef, field}// issueTableRelations are the viewer relations `filters.relations` accepts.-var issueTableRelations = []string{"assigned", "created", "my_agents"}+var issueTableRelations = []string{"assigned", "created", "my_agents", "subscribed"}// issueTableNegatableFilters are the `filters` fields `filters.negate` may name.var issueTableNegatableFilters = []string{@@ -437,6 +437,14 @@ func issueTableRelationPredicate(relation string, userRef string) string {return fmt.Sprintf("(i.assignee_type = 'member' AND i.assignee_id = %s::uuid)", userRef)case "created":return fmt.Sprintf("(i.creator_type = 'member' AND i.creator_id = %s::uuid)", userRef)+ case "subscribed":+ return fmt.Sprintf(`EXISTS (+ SELECT 1 FROM issue_subscriber isub+ WHERE isub.issue_id = i.id+ AND isub.user_type = 'member'+ AND isub.user_id = %s::uuid+ AND isub.unsubscribed_at IS NULL+ )`, userRef)default: // my_agentsreturn fmt.Sprintf(`(i.assignee_type = 'agent' AND i.assignee_id IN (SELECT a.id FROM agent adiff --git a/server/internal/handler/issue_table_subscribed_test.go b/server/internal/handler/issue_table_subscribed_test.gonew file mode 100644index 0000000000..3b794ecaf4--- /dev/null+++ b/server/internal/handler/issue_table_subscribed_test.go@@ -0,0 +1,122 @@+package handler++import (+ "fmt"+ "net/http"+ "net/http/httptest"+ "sort"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Unsubscribing leaves an opt-out tombstone row behind, so "subscribed" must+// mean an active row — through the real unsubscribe endpoints, for the table+// filter both ways round and for the id list clients filter with.+func TestSubscribedRelationIgnoresUnsubscribed(t *testing.T) {+ suffix := time.Now().UnixNano()+ // Through CreateIssue: fixture-numbered issues would collide with the+ // workspace issue counter the subtree fixture advances.+ create := func(title string, parent string) string {+ body := map[string]any{"title": fmt.Sprintf("subscribed %s %d", title, suffix)}+ if parent != "" {+ body["parent_issue_id"] = parent+ }+ var issue IssueResponse+ testutil.Call(t, testHandler.CreateIssue,+ newRequest(http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, body),+ ).Want(http.StatusCreated).JSON(&issue)+ t.Cleanup(func() {+ testHandler.DeleteIssue(httptest.NewRecorder(),+ withURLParam(newRequest(http.MethodDelete, "/api/issues/"+issue.ID, nil), "id", issue.ID))+ })+ return issue.ID+ }+ kept := create("kept", "")+ left := create("left", "")+ parentID := create("parent", "")+ childID := create("child", parentID)+ for _, id := range []string{kept, left, parentID, childID} {+ subscribeTo(t, id)+ }++ req := withURLParam(newRequest(http.MethodPost, "/api/issues/"+left+"/unsubscribe", nil), "id", left)+ testutil.Call(t, testHandler.UnsubscribeFromIssue, req).Want(http.StatusOK)+ w := httptest.NewRecorder()+ testHandler.UnsubscribeFromIssueSubtree(w,+ withURLParam(newRequest(http.MethodPost, "/api/issues/"+parentID+"/unsubscribe/subtree", nil), "id", parentID))+ if w.Code != http.StatusOK {+ t.Fatalf("UnsubscribeFromIssueSubtree: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ fixture := map[string]struct{}{kept: {}, left: {}, parentID: {}, childID: {}}+ assertRows := func(name string, filters issueTableFiltersRequest, want ...string) {+ t.Helper()+ got := issueTableFixtureRows(t, fixture, filters)+ sort.Strings(want)+ if fmt.Sprint(got) != fmt.Sprint(want) {+ t.Fatalf("%s: ids = %v, want %v", name, got, want)+ }+ }+ assertRows("subscribed", issueTableFiltersRequest{Relations: []string{"subscribed"}}, kept)+ assertRows("not subscribed",+ issueTableFiltersRequest{Relations: []string{"subscribed"}, Negate: []string{"relations"}},+ left, parentID, childID)++ ids := subscribedIssueIDs(t)+ for _, id := range []string{left, parentID, childID} {+ if _, ok := ids[id]; ok {+ t.Fatalf("unsubscribed issue %s is still listed as subscribed", id)+ }+ }+ if _, ok := ids[kept]; !ok {+ t.Fatalf("subscribed issue %s is missing from the list", kept)+ }+}++// The id list covers the caller's own member subscriptions in this workspace+// only.+func TestListSubscribedIssueIDsIsScopedToCallerAndWorkspace(t *testing.T) {+ suffix := time.Now().UnixNano()+ otherUser := dbfx.User(t, fmt.Sprintf("sub other %d", suffix), fmt.Sprintf("sub-other-%[email protected]", suffix))+ otherWorkspace := dbfx.Workspace(t, fmt.Sprintf("sub ws %d", suffix), fmt.Sprintf("sub-ws-%d", suffix))+ mine := dbfx.Issue(t, fmt.Sprintf("sub mine %d", suffix))+ theirs := dbfx.Issue(t, fmt.Sprintf("sub theirs %d", suffix))+ elsewhere := dbfx.Issue(t, fmt.Sprintf("sub elsewhere %d", suffix), testutil.Cols{"workspace_id": otherWorkspace})+ subscribe := func(issueID, userID string) {+ dbfx.InsertNoID(t, "issue_subscriber", testutil.Cols{+ "issue_id": issueID, "user_type": "member", "user_id": userID, "reason": "manual",+ }, "issue_id = $1", issueID)+ }+ subscribe(mine, testUserID)+ subscribe(theirs, otherUser)+ subscribe(elsewhere, testUserID)++ ids := subscribedIssueIDs(t)+ if _, ok := ids[mine]; !ok {+ t.Fatalf("own subscription %s is missing", mine)+ }+ for _, id := range []string{theirs, elsewhere} {+ if _, ok := ids[id]; ok {+ t.Fatalf("issue %s is not the caller's subscription in this workspace", id)+ }+ }+}++func subscribedIssueIDs(t *testing.T) map[string]struct{} {+ t.Helper()+ var out struct {+ IssueIDs []string `json:"issue_ids"`+ }+ req := newRequest(http.MethodGet, "/api/issues/subscribed", nil)+ req = req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, db.Member{}))+ testutil.Call(t, testHandler.ListSubscribedIssueIDs, req).Want(http.StatusOK).JSON(&out)+ ids := make(map[string]struct{}, len(out.IssueIDs))+ for _, id := range out.IssueIDs {+ ids[id] = struct{}{}+ }+ return ids+}diff --git a/server/internal/handler/subscriber.go b/server/internal/handler/subscriber.goindex 9729d861a0..7ae54d5f80 100644--- a/server/internal/handler/subscriber.go+++ b/server/internal/handler/subscriber.go@@ -54,6 +54,33 @@ func (h *Handler) ListIssueSubscribers(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, resp)}+// ListSubscribedIssueIDs returns the ids of every issue in the workspace the+// caller subscribes to, so clients can evaluate the "subscribed" relation on+// rows they filter themselves.+func (h *Handler) ListSubscribedIssueIDs(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, ctxWorkspaceID(r.Context()), "workspace id")+ if !ok {+ return+ }+ ids, err := h.Queries.ListSubscribedIssueIDs(r.Context(), db.ListSubscribedIssueIDsParams{+ WorkspaceID: wsUUID,+ UserID: parseUUID(userID),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list subscribed issues")+ return+ }+ issueIDs := make([]string, len(ids))+ for i, id := range ids {+ issueIDs[i] = uuidToString(id)+ }+ writeJSON(w, http.StatusOK, map[string][]string{"issue_ids": issueIDs})+}+// SubscribeToIssue subscribes a user to an issue with reason "manual".// If request body contains user_id, subscribes that user; otherwise subscribes the caller.func (h *Handler) SubscribeToIssue(w http.ResponseWriter, r *http.Request) {diff --git a/server/pkg/db/generated/subscriber.sql.go b/server/pkg/db/generated/subscriber.sql.goindex 5cae8907b9..dd6be0225b 100644--- a/server/pkg/db/generated/subscriber.sql.go+++ b/server/pkg/db/generated/subscriber.sql.go@@ -338,6 +338,43 @@ func (q *Queries) ListIssueSubscribers(ctx context.Context, issueID pgtype.UUID)return items, nil}+const listSubscribedIssueIDs = `-- name: ListSubscribedIssueIDs :many+SELECT s.issue_id+FROM issue_subscriber s+JOIN issue i ON i.id = s.issue_id+WHERE i.workspace_id = $1+ AND s.user_type = 'member'+ AND s.user_id = $2+ AND s.unsubscribed_at IS NULL+`++type ListSubscribedIssueIDsParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+}++// Every issue in the workspace the member actively subscribes to; opt-out+// tombstones do not count.+func (q *Queries) ListSubscribedIssueIDs(ctx context.Context, arg ListSubscribedIssueIDsParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listSubscribedIssueIDs, arg.WorkspaceID, arg.UserID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var issue_id pgtype.UUID+ if err := rows.Scan(&issue_id); err != nil {+ return nil, err+ }+ items = append(items, issue_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const lockActiveMember = `-- name: LockActiveMember :oneSELECT id FROM memberWHERE user_id = $1 AND workspace_id = $2diff --git a/server/pkg/db/queries/subscriber.sql b/server/pkg/db/queries/subscriber.sqlindex 612ad11fd1..85ccfd1e77 100644--- a/server/pkg/db/queries/subscriber.sql+++ b/server/pkg/db/queries/subscriber.sql@@ -234,6 +234,17 @@ SELECT * FROM issue_subscriberWHERE issue_id = $1 AND unsubscribed_at IS NULLORDER BY created_at;+-- name: ListSubscribedIssueIDs :many+-- Every issue in the workspace the member actively subscribes to; opt-out+-- tombstones do not count.+SELECT s.issue_id+FROM issue_subscriber s+JOIN issue i ON i.id = s.issue_id+WHERE i.workspace_id = sqlc.arg(workspace_id)+ AND s.user_type = 'member'+ AND s.user_id = sqlc.arg(user_id)+ AND s.unsubscribed_at IS NULL;+-- name: IsIssueSubscriber :oneSELECT EXISTS(SELECT 1 FROM issue_subscriber