Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8969: feat: subscribe to every issue in a project (#10303)
kevineea447533421
diff --git a/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx b/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsxindex 0bef74efa7..2209438f02 100644--- a/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx+++ b/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx@@ -49,6 +49,11 @@ const INBOX_GROUPS: {labelKey: "groups.updates",descriptionKey: "groups.updates_description",},+ {+ key: "new_issues",+ labelKey: "groups.new_issues",+ descriptionKey: "groups.new_issues_description",+ },{key: "agent_activity",labelKey: "groups.agent_activity",diff --git a/apps/mobile/components/inbox/detail-label.tsx b/apps/mobile/components/inbox/detail-label.tsxindex 16aaca336e..a989cb0875 100644--- a/apps/mobile/components/inbox/detail-label.tsx+++ b/apps/mobile/components/inbox/detail-label.tsx@@ -37,6 +37,7 @@ const PRIORITY_LABEL: Record<IssuePriority, string> = {const TYPE_KEY: Record<InboxItemType, string> = {issue_assigned: "type.assigned",issue_subscribed: "type.subscribed",+ issue_created: "type.issue_created",unassigned: "type.unassigned",assignee_changed: "type.reassigned",status_changed: "type.status_changed",diff --git a/apps/mobile/locales/en/inbox.json b/apps/mobile/locales/en/inbox.jsonindex 65b8eac0fe..91b6cea631 100644--- a/apps/mobile/locales/en/inbox.json+++ b/apps/mobile/locales/en/inbox.json@@ -46,6 +46,7 @@"type": {"assigned": "Assigned","subscribed": "Subscribed",+ "issue_created": "New issue","unassigned": "Unassigned","reassigned": "Reassigned","status_changed": "Status changed",diff --git a/apps/mobile/locales/en/settings.json b/apps/mobile/locales/en/settings.jsonindex 83e97f3aae..28926f9637 100644--- a/apps/mobile/locales/en/settings.json+++ b/apps/mobile/locales/en/settings.json@@ -75,6 +75,8 @@"mentions_description": "When someone @mentions you, including @all and @squad.","updates": "Issue updates","updates_description": "Edits to title, description, labels, priority, or due date.",+ "new_issues": "New issues",+ "new_issues_description": "When an issue is created in a project you subscribe to.","agent_activity": "Agent activity","agent_activity_description": "When an agent run fails.","inbox_notifications": "Inbox notifications",diff --git a/apps/mobile/locales/zh-Hans/inbox.json b/apps/mobile/locales/zh-Hans/inbox.jsonindex 1a98f8f71c..b7e993ff10 100644--- a/apps/mobile/locales/zh-Hans/inbox.json+++ b/apps/mobile/locales/zh-Hans/inbox.json@@ -46,6 +46,7 @@"type": {"assigned": "已分配","subscribed": "已订阅",+ "issue_created": "新任务","unassigned": "已取消分配","reassigned": "重新分配","status_changed": "状态已更改",diff --git a/apps/mobile/locales/zh-Hans/settings.json b/apps/mobile/locales/zh-Hans/settings.jsonindex b347ca1ddc..bc9d2bedc3 100644--- a/apps/mobile/locales/zh-Hans/settings.json+++ b/apps/mobile/locales/zh-Hans/settings.json@@ -75,6 +75,8 @@"mentions_description": "有人用 @ 提到你时,包括 @all 和 @squad。","updates": "任务更新","updates_description": "标题、描述、标签、优先级或截止日期变更时。",+ "new_issues": "新任务",+ "new_issues_description": "你订阅的项目中有新任务创建时。","agent_activity": "智能体动态","agent_activity_description": "智能体运行失败时。","inbox_notifications": "收件箱通知",diff --git a/apps/mobile/locales/zh-Hant/inbox.json b/apps/mobile/locales/zh-Hant/inbox.jsonindex 6d39109bdd..de4277e17d 100644--- a/apps/mobile/locales/zh-Hant/inbox.json+++ b/apps/mobile/locales/zh-Hant/inbox.json@@ -46,6 +46,7 @@"type": {"assigned": "已分配","subscribed": "已訂閱",+ "issue_created": "新任務","unassigned": "已取消分配","reassigned": "重新分配","status_changed": "狀態已更改",diff --git a/apps/mobile/locales/zh-Hant/settings.json b/apps/mobile/locales/zh-Hant/settings.jsonindex 3b36d7b700..ced7545224 100644--- a/apps/mobile/locales/zh-Hant/settings.json+++ b/apps/mobile/locales/zh-Hant/settings.json@@ -75,6 +75,8 @@"mentions_description": "有人用 @ 提到你時,包括 @all 和 @squad。","updates": "任務更新","updates_description": "標題、描述、標籤、優先順序或截止日期變更時。",+ "new_issues": "新任務",+ "new_issues_description": "你訂閱的專案中有新任務建立時。","agent_activity": "AI 代理動態","agent_activity_description": "AI 代理執行失敗時。","inbox_notifications": "收件箱通知",diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 33fc715828..96d1e98453 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -376,6 +376,7 @@ import {SearchIssuesResponseSchema,ProjectSchema,ListProjectMembersResponseSchema,+ ProjectSubscriptionSchema,ListProjectsResponseSchema,EMPTY_PROJECT,EMPTY_LIST_PROJECTS_RESPONSE,@@ -4390,6 +4391,25 @@ export class ApiClient {});}+ async getProjectSubscription(id: string): Promise<boolean> {+ return this.parseProjectSubscription(+ await this.fetch<unknown>(`/api/projects/${id}/subscription`),+ "GET /api/projects/:id/subscription",+ );+ }++ async setProjectSubscription(id: string, subscribed: boolean): Promise<boolean> {+ const method = subscribed ? "PUT" : "DELETE";+ return this.parseProjectSubscription(+ await this.fetch<unknown>(`/api/projects/${id}/subscription`, { method }),+ `${method} /api/projects/:id/subscription`,+ );+ }++ private parseProjectSubscription(raw: unknown, endpoint: string): boolean {+ return parseWithFallback(raw, ProjectSubscriptionSchema, { subscribed: false }, { endpoint }).subscribed;+ }+async addProjectMembers(id: string, userIds: string[]): Promise<ListProjectMembersResponse> {const raw = await this.fetch<unknown>(`/api/projects/${id}/members`, {method: "POST", body: JSON.stringify({ user_ids: userIds }),diff --git a/packages/core/api/project-subscription.test.ts b/packages/core/api/project-subscription.test.tsnew file mode 100644index 0000000000..f8eed10ad8--- /dev/null+++ b/packages/core/api/project-subscription.test.ts@@ -0,0 +1,37 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from "vitest";+import { ApiClient } from "./client";++afterEach(() => vi.unstubAllGlobals());++function stub(body: unknown) {+ const fetch = vi.fn().mockResolvedValue(Response.json(body));+ vi.stubGlobal("fetch", fetch);+ return fetch;+}++describe("project subscription API", () => {+ it("reads the viewer's subscription", async () => {+ stub({ subscribed: true, extra: 1 });+ await expect(new ApiClient("https://api.example.test").getProjectSubscription("p")).resolves.toBe(true);+ });++ it.each([+ [true, "PUT"],+ [false, "DELETE"],+ ])("sets subscribed=%s with %s", async (subscribed, method) => {+ const fetch = stub({ subscribed });+ await expect(new ApiClient("https://api.example.test").setProjectSubscription("p", subscribed)).resolves.toBe(subscribed);+ expect(fetch.mock.calls[0]?.[0]).toContain("/api/projects/p/subscription");+ expect(fetch.mock.calls[0]?.[1]).toMatchObject({ method });+ });++ it.each([+ ["a missing flag", {}],+ ["a non-boolean flag", { subscribed: "yes" }],+ ["a null body", null],+ ])("reads %s as not subscribed", async (_name, body) => {+ stub(body);+ await expect(new ApiClient("https://api.example.test").getProjectSubscription("p")).resolves.toBe(false);+ });+});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 9b62c139b2..2bd9b7f083 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1814,6 +1814,12 @@ export const ListProjectMembersResponseSchema = z.object({total: z.number(),}).loose();+// The viewer's own project subscription (`/api/projects/:id/subscription`).+// Anything but an explicit `true` reads as not subscribed.+export const ProjectSubscriptionSchema = z.object({+ subscribed: z.boolean().catch(false),+}).loose();+const SearchProjectResultSchema = ProjectSchema.extend({match_source: z.string(),matched_snippet: z.string().optional(),diff --git a/packages/core/inbox/filters.ts b/packages/core/inbox/filters.tsindex 03ca3ae323..12492348dd 100644--- a/packages/core/inbox/filters.ts+++ b/packages/core/inbox/filters.ts@@ -41,6 +41,7 @@ const TYPE_GROUP: Partial<Record<InboxItemType, InboxTypeGroup>> = {assignee_changed: "assign",issue_subscribed: "assign",review_requested: "review",+ issue_created: "change",status_changed: "change",priority_changed: "change",start_date_changed: "change",diff --git a/packages/core/notification-preferences/patch.ts b/packages/core/notification-preferences/patch.tsindex c0c0a331de..cca2c0b024 100644--- a/packages/core/notification-preferences/patch.ts+++ b/packages/core/notification-preferences/patch.ts@@ -10,6 +10,7 @@ const NOTIFICATION_GROUP_KEYS: readonly NotificationGroupKey[] = ["comments","mentions","updates",+ "new_issues","agent_activity","system_notifications",];diff --git a/packages/core/projects/index.ts b/packages/core/projects/index.tsindex 1c88a674d0..00ef14c76e 100644--- a/packages/core/projects/index.ts+++ b/packages/core/projects/index.ts@@ -1,6 +1,6 @@export { canDeleteProject } from "./deletion-permissions";-export { projectKeys, projectListOptions, projectDetailOptions } from "./queries";-export { useCreateProject, useUpdateProject, useDeleteProject, ProjectDeletionOfflineError } from "./mutations";+export { projectKeys, projectListOptions, projectDetailOptions, projectSubscriptionOptions } from "./queries";+export { useCreateProject, useUpdateProject, useDeleteProject, useSetProjectSubscription, ProjectDeletionOfflineError } from "./mutations";export { useProjectDraftStore } from "./draft-store";export {useProjectViewStore,diff --git a/packages/core/projects/mutations.ts b/packages/core/projects/mutations.tsindex 93db8077b2..4dfe26fb3e 100644--- a/packages/core/projects/mutations.ts+++ b/packages/core/projects/mutations.ts@@ -102,3 +102,18 @@ export function useDeleteProject() {},});}++export function useSetProjectSubscription() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: ({ id, subscribed }: { id: string; subscribed: boolean }) =>+ api.setProjectSubscription(id, subscribed),+ onSuccess: (subscribed, { id }) => {+ qc.setQueryData(projectKeys.subscription(wsId, id), subscribed);+ // Issue subscriber lists include project subscribers, so any open issue+ // of this project may have just gained or lost the caller.+ qc.invalidateQueries({ queryKey: issueKeys.subscribersAll() });+ },+ });+}diff --git a/packages/core/projects/queries.ts b/packages/core/projects/queries.tsindex 0acbf6f409..b8d4820e25 100644--- a/packages/core/projects/queries.ts+++ b/packages/core/projects/queries.ts@@ -7,6 +7,8 @@ export const projectKeys = {detail: (wsId: string, id: string) =>[...projectKeys.all(wsId), "detail", id] as const,members: (wsId: string, id: string) => [...projectKeys.detail(wsId, id), "members"] as const,+ subscription: (wsId: string, id: string) =>+ [...projectKeys.detail(wsId, id), "subscription"] as const,};export function projectListOptions(wsId: string) {@@ -30,3 +32,10 @@ export function projectMembersOptions(wsId: string, id: string) {queryFn: () => api.getProjectMembers(id),});}++export function projectSubscriptionOptions(wsId: string, id: string) {+ return queryOptions({+ queryKey: projectKeys.subscription(wsId, id),+ queryFn: () => api.getProjectSubscription(id),+ });+}diff --git a/packages/core/types/inbox.ts b/packages/core/types/inbox.tsindex 0d61219cb9..e4587e29d1 100644--- a/packages/core/types/inbox.ts+++ b/packages/core/types/inbox.ts@@ -5,6 +5,8 @@ export type InboxSeverity = "action_required" | "attention" | "info";export type InboxItemType =| "issue_assigned"| "issue_subscribed"+ // A new issue in a project the recipient subscribes to.+ | "issue_created"| "unassigned"| "assignee_changed"| "status_changed"diff --git a/packages/core/types/notification-preference.ts b/packages/core/types/notification-preference.tsindex 204dbaa8ec..979df5ff3a 100644--- a/packages/core/types/notification-preference.ts+++ b/packages/core/types/notification-preference.ts@@ -4,6 +4,7 @@ export type NotificationGroupKey =| "comments"| "mentions"| "updates"+ | "new_issues"| "agent_activity"| "system_notifications";diff --git a/packages/core/types/subscriber.ts b/packages/core/types/subscriber.tsindex 92184113be..35c9927d58 100644--- a/packages/core/types/subscriber.ts+++ b/packages/core/types/subscriber.ts@@ -4,6 +4,10 @@* themselves, so the UI has to explain the subscription, and delivery for it* is narrower than for the direct reasons.*+ * `project` means the member subscribes to the issue's project; the server+ * lists them without storing a row, and unsubscribing from the issue records an+ * opt-out for this issue only.+ ** Server-driven and open-ended by design: the API parses `reason` as a plain* string, so treat an unrecognized value as a direct subscription rather than* dropping the row.@@ -15,7 +19,8 @@ export type IssueSubscriberReason =| "mentioned"| "manual"| "autopilot"- | "delegated";+ | "delegated"+ | "project";export interface IssueSubscriber {issue_id: string;diff --git a/packages/views/inbox/components/inbox-detail-label.tsx b/packages/views/inbox/components/inbox-detail-label.tsxindex 0f8af99907..85b359096f 100644--- a/packages/views/inbox/components/inbox-detail-label.tsx+++ b/packages/views/inbox/components/inbox-detail-label.tsx@@ -18,6 +18,7 @@ export function useTypeLabels(): Record<InboxItemType, string> {return {issue_assigned: t(($) => $.types.issue_assigned),issue_subscribed: t(($) => $.types.issue_subscribed),+ issue_created: t(($) => $.types.issue_created),unassigned: t(($) => $.types.unassigned),assignee_changed: t(($) => $.types.assignee_changed),status_changed: t(($) => $.types.status_changed),diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex 46f9c349d3..209282cff3 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -3935,6 +3935,46 @@ describe("IssueDetail (shared)", () => {// 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 inherited from the project", () => {+ beforeEach(() => {+ mockApiObj.listIssueSubscribers.mockResolvedValue([+ {+ issue_id: "issue-1",+ user_type: "member" as const,+ user_id: "user-1",+ reason: "project" as const,+ created_at: "2026-01-01T00:00:00Z",+ },+ ]);+ mockApiObj.listChildIssues.mockResolvedValue({ issues: [] });+ });++ afterEach(() => {+ document.body.innerHTML = "";+ });++ it("labels the project source and leaves only this issue", async () => {+ renderIssueDetail();++ expect(await screen.findByText("Via project")).toBeInTheDocument();+ const button = await waitFor(() => {+ const el = screen.getByText("Unsubscribe");+ expect(el.getAttribute("aria-haspopup")).toBeNull();+ return el;+ });+ fireEvent.click(button);++ await waitFor(() =>+ expect(mockApiObj.unsubscribeFromIssue).toHaveBeenCalledWith(+ "issue-1",+ "user-1",+ "member",+ ),+ );+ expect(mockApiObj.unsubscribeFromIssueSubtree).not.toHaveBeenCalled();+ });+ });+describe("subscription state before the query resolves", () => {afterEach(() => {document.body.innerHTML = "";diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 2541ad83b5..c81a4413fe 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -3972,6 +3972,19 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr</TooltipContent></Tooltip>)}+ {/* Inherited from the project: say so, and that leaving+ here only covers this issue, so Unsubscribe is not read as+ leaving the whole project. */}+ {isSubscribed && subscriptionReason === "project" && (+ <Tooltip>+ <TooltipTrigger className="cursor-default rounded-full bg-muted px-2 py-0.5 text-caption text-muted-foreground">+ {t(($) => $.detail.project_subscription_badge)}+ </TooltipTrigger>+ <TooltipContent side="top" className="max-w-64">+ {t(($) => $.detail.project_subscription_hint)}+ </TooltipContent>+ </Tooltip>+ )}{/* Nothing until the subscribers query resolves: the defaultempty list reads as "not subscribed" for everyone, sorendering it flashes Subscribe at someone who is alreadydiff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.jsonindex a0072fbb4f..74fda6318b 100644--- a/packages/views/locales/en/inbox.json+++ b/packages/views/locales/en/inbox.json@@ -76,6 +76,7 @@"types": {"issue_assigned": "Assigned","issue_subscribed": "Subscribed",+ "issue_created": "New issue","unassigned": "Unassigned","assignee_changed": "Assignee changed","status_changed": "Status changed",diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex f6e5aedbe2..c62e39b8f0 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -555,6 +555,8 @@"unsubscribe": "Unsubscribe","delegated_subscription_badge": "Watching via agent","delegated_subscription_hint": "Your agent created this issue on your behalf, so you're subscribed to it. You'll get notified when it needs review, finishes, or gets stuck.",+ "project_subscription_badge": "Via project",+ "project_subscription_hint": "You're subscribed to every issue in this project. Unsubscribing here stops notifications for this issue only.","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.",diff --git a/packages/views/locales/en/projects.json b/packages/views/locales/en/projects.jsonindex 3da4a97a03..40c50880ac 100644--- a/packages/views/locales/en/projects.json+++ b/packages/views/locales/en/projects.json@@ -62,6 +62,10 @@"icon_tooltip": "Change icon","pin_tooltip": "Pin to sidebar","unpin_tooltip": "Unpin from sidebar",+ "subscribe_action": "Subscribe to all issues",+ "unsubscribe_action": "Unsubscribe from project",+ "toast_subscribed": "Subscribed. You'll be notified about every issue in this project.",+ "toast_subscription_failed": "Failed to update subscription","sidebar_tooltip": "Toggle right sidebar","rename_action": "Rename project","copy_link": "Copy link",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 16d38be539..979b478a18 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -845,6 +845,10 @@"label": "Priority & Due date","description": "When priority or due date changes on issues you follow"},+ "new_issues": {+ "label": "New issues",+ "description": "When an issue is created in a project you subscribe to"+ },"agent_activity": {"label": "Agent activity","description": "When an agent run fails"diff --git a/packages/views/locales/es/inbox.json b/packages/views/locales/es/inbox.jsonindex 4563f8792b..2dbc65f457 100644--- a/packages/views/locales/es/inbox.json+++ b/packages/views/locales/es/inbox.json@@ -76,6 +76,7 @@"types": {"issue_assigned": "Asignada","issue_subscribed": "Suscrito",+ "issue_created": "Nueva tarea","unassigned": "Desasignada","assignee_changed": "Asignado cambiado","status_changed": "Estado cambiado",diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.jsonindex 0c57494c90..5caa84ce2c 100644--- a/packages/views/locales/es/issues.json+++ b/packages/views/locales/es/issues.json@@ -524,6 +524,8 @@"unsubscribe": "Darse de baja","delegated_subscription_badge": "Observando a través de un agente","delegated_subscription_hint": "Tu agente creó esta tarea en tu nombre, así que estás suscrito. Recibirás una notificación cuando necesite revisión, termine o se quede atascada.",+ "project_subscription_badge": "Suscrito a través del proyecto",+ "project_subscription_hint": "Estás suscrito a todas las tareas de este proyecto. Darte de baja aquí solo detiene las notificaciones de esta tarea.","unsubscribe_this": "Darse de baja de esta tarea","unsubscribe_subtree": "Darse de baja de esta tarea y sus subtareas","unsubscribe_subtree_failed": "No se ha podido dar de baja de las subtareas. Inténtalo de nuevo.",diff --git a/packages/views/locales/es/projects.json b/packages/views/locales/es/projects.jsonindex bc8443e58c..0dfdc8f84d 100644--- a/packages/views/locales/es/projects.json+++ b/packages/views/locales/es/projects.json@@ -60,6 +60,10 @@"icon_tooltip": "Cambiar icono","pin_tooltip": "Fijar en la barra lateral","unpin_tooltip": "Dejar de fijar de la barra lateral",+ "subscribe_action": "Suscribirse a todas las tareas",+ "unsubscribe_action": "Cancelar suscripción al proyecto",+ "toast_subscribed": "Suscrito. Recibirás avisos de cada tarea de este proyecto.",+ "toast_subscription_failed": "No se pudo actualizar la suscripción","sidebar_tooltip": "Mostrar u ocultar la barra lateral derecha","rename_action": "Renombrar proyecto","copy_link": "Copiar enlace",diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex ec13a2c0dd..d1a91765b0 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -845,6 +845,10 @@"label": "Prioridad y fecha de entrega","description": "Cuando cambian la prioridad o la fecha de entrega de tareas que sigues"},+ "new_issues": {+ "label": "Tareas nuevas",+ "description": "Cuando se crea una tarea en un proyecto al que estás suscrito"+ },"agent_activity": {"label": "Actividad de agentes","description": "Cuando falla una ejecución de agente"diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.jsonindex 0072619590..fe0ce2e087 100644--- a/packages/views/locales/fr/inbox.json+++ b/packages/views/locales/fr/inbox.json@@ -76,6 +76,7 @@"types": {"issue_assigned": "Assigné","issue_subscribed": "Abonné",+ "issue_created": "Nouvelle tâche","unassigned": "Désassigné","assignee_changed": "Assignation modifiée","status_changed": "Statut modifié",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex ee7a3a0f05..54e39d34fc 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -555,6 +555,8 @@"unsubscribe": "Se désabonner","delegated_subscription_badge": "Suivi via un agent","delegated_subscription_hint": "Votre agent a créé cette tâche en votre nom : vous y êtes donc abonné. Vous serez notifié lorsqu'elle demandera une relecture, se terminera ou se bloquera.",+ "project_subscription_badge": "Suivi via le projet",+ "project_subscription_hint": "Vous êtes abonné à toutes les tâches de ce projet. Vous désabonner ici arrête uniquement les notifications de cette tâche.","unsubscribe_this": "Se désabonner de cette tâche","unsubscribe_subtree": "Se désabonner de cette tâche et de ses sous-tâches","unsubscribe_subtree_failed": "Impossible de se désabonner des sous-tâches. Veuillez réessayer.",diff --git a/packages/views/locales/fr/projects.json b/packages/views/locales/fr/projects.jsonindex f2ae319366..67484fe495 100644--- a/packages/views/locales/fr/projects.json+++ b/packages/views/locales/fr/projects.json@@ -62,6 +62,10 @@"icon_tooltip": "Changer d'icône","pin_tooltip": "Épingler à la barre latérale","unpin_tooltip": "Détacher de la barre latérale",+ "subscribe_action": "S'abonner à toutes les tâches",+ "unsubscribe_action": "Se désabonner du projet",+ "toast_subscribed": "Abonné. Vous serez notifié de chaque tâche de ce projet.",+ "toast_subscription_failed": "Échec de la mise à jour de l'abonnement","sidebar_tooltip": "Afficher ou masquer la barre latérale droite","rename_action": "Renommer le projet","copy_link": "Copier le lien",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex 958913f869..2c3880113f 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -845,6 +845,10 @@"label": "Priorité et date d'échéance","description": "Quand la priorité ou la date d'échéance change sur les tâches que vous suivez"},+ "new_issues": {+ "label": "Nouvelles tâches",+ "description": "Quand une tâche est créée dans un projet auquel vous êtes abonné"+ },"agent_activity": {"label": "Activité des agents","description": "Lorsqu'une exécution d'agent échoue"diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.jsonindex a744076f1a..3e26e6622d 100644--- a/packages/views/locales/ja/inbox.json+++ b/packages/views/locales/ja/inbox.json@@ -74,6 +74,7 @@"types": {"issue_assigned": "割り当て済み","issue_subscribed": "購読済み",+ "issue_created": "新しいタスク","unassigned": "割り当て解除","assignee_changed": "担当者を変更","status_changed": "ステータスを変更",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex eeeba8c1aa..9f1a57a10c 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -547,6 +547,8 @@"unsubscribe": "購読解除","delegated_subscription_badge": "エージェント経由で購読中","delegated_subscription_hint": "エージェントがあなたに代わってこのタスクを作成したため、購読しています。レビュー待ち・完了・ブロック時に通知されます。",+ "project_subscription_badge": "プロジェクト経由で購読中",+ "project_subscription_hint": "このプロジェクトのすべてのタスクを購読しています。ここで購読解除すると、このタスクの通知だけが止まります。","unsubscribe_this": "このタスクの購読を解除","unsubscribe_subtree": "このタスクとサブタスクの購読を解除","unsubscribe_subtree_failed": "サブタスクの購読解除に失敗しました。もう一度お試しください。",diff --git a/packages/views/locales/ja/projects.json b/packages/views/locales/ja/projects.jsonindex a12168d910..fdf418c9aa 100644--- a/packages/views/locales/ja/projects.json+++ b/packages/views/locales/ja/projects.json@@ -62,6 +62,10 @@"icon_tooltip": "アイコンを変更","pin_tooltip": "サイドバーに固定","unpin_tooltip": "サイドバーの固定を解除",+ "subscribe_action": "すべてのタスクを購読",+ "unsubscribe_action": "プロジェクトの購読を解除",+ "toast_subscribed": "購読しました。このプロジェクトのタスクの変更をすべて通知します。",+ "toast_subscription_failed": "購読を更新できませんでした","sidebar_tooltip": "右サイドバーの開閉","rename_action": "プロジェクト名を変更","copy_link": "リンクをコピー",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex a24dd96503..50228e1967 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -836,6 +836,10 @@"label": "優先度と期限","description": "フォロー中のタスクの優先度や期限が変わったとき"},+ "new_issues": {+ "label": "新しいタスク",+ "description": "購読中のプロジェクトでタスクが作成されたとき"+ },"agent_activity": {"label": "エージェントのアクティビティ","description": "エージェントの実行が失敗したとき"diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.jsonindex a148deb243..b732e379fb 100644--- a/packages/views/locales/ko/inbox.json+++ b/packages/views/locales/ko/inbox.json@@ -74,6 +74,7 @@"types": {"issue_assigned": "할당됨","issue_subscribed": "구독됨",+ "issue_created": "새 태스크","unassigned": "할당 해제됨","assignee_changed": "담당자 변경됨","status_changed": "상태 변경됨",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 0a07d1b983..b1811b59f3 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -547,6 +547,8 @@"unsubscribe": "구독 해제","delegated_subscription_badge": "에이전트를 통해 구독 중","delegated_subscription_hint": "에이전트가 회원님을 대신해 이 태스크를 만들었기 때문에 구독 중입니다. 검토 필요, 완료, 차단 시 알림을 받습니다.",+ "project_subscription_badge": "프로젝트를 통해 구독 중",+ "project_subscription_hint": "이 프로젝트의 모든 태스크를 구독 중입니다. 여기서 구독을 해제하면 이 태스크의 알림만 중지됩니다.","unsubscribe_this": "이 태스크 구독 해제","unsubscribe_subtree": "이 태스크와 하위 태스크 구독 해제","unsubscribe_subtree_failed": "하위 태스크 구독 해제에 실패했습니다. 다시 시도해 주세요.",diff --git a/packages/views/locales/ko/projects.json b/packages/views/locales/ko/projects.jsonindex 37dbcd265b..f9a21beef4 100644--- a/packages/views/locales/ko/projects.json+++ b/packages/views/locales/ko/projects.json@@ -62,6 +62,10 @@"icon_tooltip": "아이콘 변경","pin_tooltip": "사이드바에 고정","unpin_tooltip": "사이드바 고정 해제",+ "subscribe_action": "모든 태스크 구독",+ "unsubscribe_action": "프로젝트 구독 취소",+ "toast_subscribed": "구독했습니다. 이 프로젝트의 모든 태스크 변경을 알려 드립니다.",+ "toast_subscription_failed": "구독을 업데이트하지 못했습니다","sidebar_tooltip": "오른쪽 사이드바 열기/닫기","rename_action": "프로젝트 이름 변경","copy_link": "링크 복사",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 9f176c1bc9..f8a5d5d89d 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -836,6 +836,10 @@"label": "우선순위 및 마감일","description": "팔로우 중인 태스크의 우선순위나 마감일이 바뀔 때"},+ "new_issues": {+ "label": "새 태스크",+ "description": "구독 중인 프로젝트에 태스크가 생성될 때"+ },"agent_activity": {"label": "에이전트 활동","description": "에이전트 실행이 실패할 때"diff --git a/packages/views/locales/ru/inbox.json b/packages/views/locales/ru/inbox.jsonindex e9fb2eec57..a0e0e53322 100644--- a/packages/views/locales/ru/inbox.json+++ b/packages/views/locales/ru/inbox.json@@ -80,6 +80,7 @@"types": {"issue_assigned": "Назначено","issue_subscribed": "Подписка оформлена",+ "issue_created": "Новая задача","unassigned": "Исполнитель снят","assignee_changed": "Исполнитель изменён","status_changed": "Статус изменён",diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.jsonindex 2d7336c020..556f748e44 100644--- a/packages/views/locales/ru/issues.json+++ b/packages/views/locales/ru/issues.json@@ -565,6 +565,8 @@"unsubscribe": "Отписаться","delegated_subscription_badge": "Отслеживается через агента","delegated_subscription_hint": "Ваш агент создал эту задачу от вашего имени, поэтому вы на неё подписаны. Вы получите уведомление, когда потребуется проверка, работа завершится или возникнет затруднение.",+ "project_subscription_badge": "Подписка через проект",+ "project_subscription_hint": "Вы подписаны на все задачи этого проекта. Отписка здесь остановит уведомления только по этой задаче.","unsubscribe_this": "Отписаться от этой задачи","unsubscribe_subtree": "Отписаться от этой задачи и её подзадач","unsubscribe_subtree_failed": "Не удалось отписаться от подзадач. Попробуйте ещё раз.",diff --git a/packages/views/locales/ru/projects.json b/packages/views/locales/ru/projects.jsonindex 5a6576bad2..a62cbdfb5f 100644--- a/packages/views/locales/ru/projects.json+++ b/packages/views/locales/ru/projects.json@@ -60,6 +60,10 @@"icon_tooltip": "Изменить иконку","pin_tooltip": "Закрепить в боковой панели","unpin_tooltip": "Открепить от боковой панели",+ "subscribe_action": "Подписаться на все задачи",+ "unsubscribe_action": "Отписаться от проекта",+ "toast_subscribed": "Подписка оформлена. Вы будете получать уведомления о каждой задаче проекта.",+ "toast_subscription_failed": "Не удалось обновить подписку","sidebar_tooltip": "Показать/скрыть правую панель","rename_action": "Переименовать проект","copy_link": "Скопировать ссылку",diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex 9a1757916a..dc2289a86e 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -877,6 +877,10 @@"updates": {"description": "Когда у задач, на которые вы подписаны, меняется приоритет или срок","label": "Приоритет и срок"+ },+ "new_issues": {+ "label": "Новые задачи",+ "description": "Когда в проекте, на который вы подписаны, создаётся задача"}}},diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.jsonindex c9fd8719db..edd833baec 100644--- a/packages/views/locales/zh-Hans/inbox.json+++ b/packages/views/locales/zh-Hans/inbox.json@@ -74,6 +74,7 @@"types": {"issue_assigned": "已分配","issue_subscribed": "已订阅",+ "issue_created": "新任务","unassigned": "已取消分配","assignee_changed": "分配人已更改","status_changed": "状态已更改",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 6e1afb4694..d9068c473d 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -547,6 +547,8 @@"unsubscribe": "取消订阅","delegated_subscription_badge": "由智能体代你关注","delegated_subscription_hint": "你的智能体代你创建了这个任务,因此你在关注它。待评审、完成或受阻时会通知你。",+ "project_subscription_badge": "通过项目订阅",+ "project_subscription_hint": "你订阅了这个项目的全部任务。在这里取消订阅只会停止这个任务的通知。","unsubscribe_this": "取消订阅此任务","unsubscribe_subtree": "取消订阅此任务及其子任务","unsubscribe_subtree_failed": "取消订阅子任务失败,请重试。",diff --git a/packages/views/locales/zh-Hans/projects.json b/packages/views/locales/zh-Hans/projects.jsonindex ad32329def..824c4457ce 100644--- a/packages/views/locales/zh-Hans/projects.json+++ b/packages/views/locales/zh-Hans/projects.json@@ -62,6 +62,10 @@"icon_tooltip": "更换图标","pin_tooltip": "固定到侧边栏","unpin_tooltip": "从侧边栏取消固定",+ "subscribe_action": "订阅全部任务",+ "unsubscribe_action": "取消订阅项目",+ "toast_subscribed": "已订阅。此项目中任务的变更都会通知你。",+ "toast_subscription_failed": "更新订阅失败","sidebar_tooltip": "切换右侧边栏","rename_action": "重命名项目","copy_link": "复制链接",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex beaf172459..aab5b34131 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -836,6 +836,10 @@"label": "优先级与截止日期","description": "你订阅的任务优先级或截止日期变更时"},+ "new_issues": {+ "label": "新任务",+ "description": "你订阅的项目中有新任务创建时"+ },"agent_activity": {"label": "智能体活动","description": "智能体运行失败时"diff --git a/packages/views/locales/zh-Hant/inbox.json b/packages/views/locales/zh-Hant/inbox.jsonindex 1e5985bbee..cc70b47927 100644--- a/packages/views/locales/zh-Hant/inbox.json+++ b/packages/views/locales/zh-Hant/inbox.json@@ -74,6 +74,7 @@"types": {"issue_assigned": "已分配","issue_subscribed": "已訂閱",+ "issue_created": "新任務","unassigned": "已取消分配","assignee_changed": "分配人已更改","status_changed": "狀態已更改",diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.jsonindex 598db81d82..0ed171f732 100644--- a/packages/views/locales/zh-Hant/issues.json+++ b/packages/views/locales/zh-Hant/issues.json@@ -547,6 +547,8 @@"unsubscribe": "取消訂閱","delegated_subscription_badge": "由 AI 代理代你關注","delegated_subscription_hint": "你的 AI 代理代你建立了這個任務,因此你在關注它。待評審、完成或受阻時會通知你。",+ "project_subscription_badge": "透過專案訂閱",+ "project_subscription_hint": "你訂閱了這個專案的全部任務。在這裡取消訂閱只會停止這個任務的通知。","unsubscribe_this": "取消訂閱此任務","unsubscribe_subtree": "取消訂閱此任務及其子任務","unsubscribe_subtree_failed": "取消訂閱子任務失敗,請重試。",diff --git a/packages/views/locales/zh-Hant/projects.json b/packages/views/locales/zh-Hant/projects.jsonindex 3c8ef387dc..2ded6be458 100644--- a/packages/views/locales/zh-Hant/projects.json+++ b/packages/views/locales/zh-Hant/projects.json@@ -62,6 +62,10 @@"icon_tooltip": "更換圖示","pin_tooltip": "固定到側邊欄","unpin_tooltip": "從側邊欄取消固定",+ "subscribe_action": "訂閱全部任務",+ "unsubscribe_action": "取消訂閱專案",+ "toast_subscribed": "已訂閱。此專案中任務的變更都會通知你。",+ "toast_subscription_failed": "更新訂閱失敗","sidebar_tooltip": "切換右側邊欄","rename_action": "重新命名專案","copy_link": "複製連結",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex 2ac5b77f81..c07a5c9166 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -836,6 +836,10 @@"label": "優先順序與截止日期","description": "你訂閱的任務優先順序或截止日期變更時"},+ "new_issues": {+ "label": "新任務",+ "description": "你訂閱的專案中有新任務建立時"+ },"agent_activity": {"label": "AI 代理活動","description": "AI 代理執行失敗時"diff --git a/packages/views/projects/components/project-detail.test.tsx b/packages/views/projects/components/project-detail.test.tsxindex 4118486d0e..d4778178ec 100644--- a/packages/views/projects/components/project-detail.test.tsx+++ b/packages/views/projects/components/project-detail.test.tsx@@ -17,6 +17,8 @@ const mocks = vi.hoisted(() => ({copyText: vi.fn(),deleteProject: vi.fn(),getProject: vi.fn(),+ getProjectSubscription: vi.fn(),+ setProjectSubscription: vi.fn(),getShareableUrl: vi.fn((path: string) => `https://app.example${path}`),push: vi.fn(),recordVisit: vi.fn(),@@ -272,7 +274,14 @@ beforeEach(() => {mocks.copyText.mockReset().mockResolvedValue(true);mocks.deleteProject.mockReset().mockReturnValue(pending.promise);mocks.getProject.mockReset().mockResolvedValue(PROJECT);- setApiInstance({ deleteProject: mocks.deleteProject, getProject: mocks.getProject } as unknown as ApiClient);+ mocks.getProjectSubscription.mockReset().mockResolvedValue(false);+ mocks.setProjectSubscription.mockReset().mockImplementation(async (_id: string, subscribed: boolean) => subscribed);+ setApiInstance({+ deleteProject: mocks.deleteProject,+ getProject: mocks.getProject,+ getProjectSubscription: mocks.getProjectSubscription,+ setProjectSubscription: mocks.setProjectSubscription,+ } as unknown as ApiClient);mocks.getShareableUrl.mockClear();mocks.push.mockReset();mocks.recordVisit.mockReset();@@ -335,6 +344,31 @@ describe("ProjectDetail sharing", () => {});});+describe("ProjectDetail subscription", () => {+ it("subscribes to every issue in the project and can unsubscribe again", async () => {+ const user = userEvent.setup();+ renderProjectDetail();++ await user.click(await screen.findByRole("button", { name: "Subscribe to all issues" }));+ expect(mocks.setProjectSubscription).toHaveBeenCalledWith("project-1", true);+ expect(mocks.toastSuccess).toHaveBeenCalled();++ await user.click(await screen.findByRole("button", { name: "Unsubscribe from project" }));+ expect(mocks.setProjectSubscription).toHaveBeenLastCalledWith("project-1", false);+ expect(await screen.findByRole("button", { name: "Subscribe to all issues" })).toBeInTheDocument();+ });++ it("keeps the current state and reports a failed update", async () => {+ mocks.setProjectSubscription.mockRejectedValueOnce(new Error("boom"));+ const user = userEvent.setup();+ renderProjectDetail();++ await user.click(await screen.findByRole("button", { name: "Subscribe to all issues" }));+ await waitFor(() => expect(mocks.toastError).toHaveBeenCalled());+ expect(screen.getByRole("button", { name: "Subscribe to all issues" })).toBeInTheDocument();+ });+});+describe("ProjectDetail project deletion", () => {it("allows cancelling an offline detail deletion without executing it on reconnect", async () => {onlineManager.setOnline(false);diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsxindex 03ac79227c..42f807681c 100644--- a/packages/views/projects/components/project-detail.tsx+++ b/packages/views/projects/components/project-detail.tsx@@ -3,7 +3,7 @@import { useMemo, useState, useCallback, useRef, useEffect } from "react";import { useRegisterCommandBarContext } from "../../search/register-context";import { useDefaultLayout, usePanelRef } from "react-resizable-panels";-import { Check, ChevronRight, FileQuestion, Link2, PanelRight, Pencil, Pin, PinOff, Trash2, UserMinus } from "@multica/ui/icons";+import { BellOff, BellRing, Check, ChevronRight, FileQuestion, Link2, PanelRight, Pencil, Pin, PinOff, Trash2, UserMinus } from "@multica/ui/icons";import { useQuery } from "@tanstack/react-query";import { cn } from "@multica/ui/lib/utils";import { copyText } from "@multica/ui/lib/clipboard";@@ -12,9 +12,9 @@ import type { Project, ProjectStatus, ProjectPriority } from "@multica/core/typeimport { useAuthStore } from "@multica/core/auth";import { canDeleteProject } from "@multica/core/projects/deletion-permissions";import { canChangeProjectLead } from "@multica/core/projects/access";-import { projectDetailOptions } from "@multica/core/projects/queries";+import { projectDetailOptions, projectSubscriptionOptions } from "@multica/core/projects/queries";import { Spinner } from "@multica/ui/components/ui/spinner";-import { useUpdateProject, useDeleteProject, ProjectDeletionOfflineError } from "@multica/core/projects/mutations";+import { useUpdateProject, useDeleteProject, useSetProjectSubscription, ProjectDeletionOfflineError } from "@multica/core/projects/mutations";import { pinListOptions } from "@multica/core/pins";import { useCreatePin, useDeletePin } from "@multica/core/pins";import { useModalStore } from "@multica/core/modals";@@ -165,6 +165,22 @@ export function ProjectDetail({ projectId }: { projectId: string }) {const canDelete = !!project && canDeleteProject(project, userId ?? null, role, agents);const createPin = useCreatePin();const deletePinMut = useDeletePin();+ const { data: isSubscribed = false } = useQuery({+ ...projectSubscriptionOptions(wsId, projectId),+ enabled: !!project,+ });+ const setSubscription = useSetProjectSubscription();+ const handleToggleSubscription = () => {+ setSubscription.mutate(+ { id: projectId, subscribed: !isSubscribed },+ {+ onSuccess: (subscribed) => {+ if (subscribed) toast.success(t(($) => $.detail.toast_subscribed));+ },+ onError: () => toast.error(t(($) => $.detail.toast_subscription_failed)),+ },+ );+ };const descEditorRef = useRef<ContentEditorRef>(null);const isMobile = useIsMobile();const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);@@ -573,6 +589,13 @@ export function ProjectDetail({ projectId }: { projectId: string }) {{isPinned ? <PinOff className="h-3.5 w-3.5" /> : <Pin className="h-3.5 w-3.5" />}{isPinned ? t(($) => $.detail.unpin_tooltip) : t(($) => $.detail.pin_tooltip)}</DropdownMenuItem>+ <DropdownMenuItem+ disabled={setSubscription.isPending}+ onClick={handleToggleSubscription}+ >+ {isSubscribed ? <BellOff className="h-3.5 w-3.5" /> : <BellRing className="h-3.5 w-3.5" />}+ {isSubscribed ? t(($) => $.detail.unsubscribe_action) : t(($) => $.detail.subscribe_action)}+ </DropdownMenuItem><ProjectWorkflowMenuItem project={project} onOpen={() => setWorkflowSheetOpen(true)} />{canDelete && (<>diff --git a/packages/views/settings/components/notifications-tab.tsx b/packages/views/settings/components/notifications-tab.tsxindex bab94ad457..3b5c847d02 100644--- a/packages/views/settings/components/notifications-tab.tsx+++ b/packages/views/settings/components/notifications-tab.tsx@@ -24,6 +24,7 @@ const INBOX_GROUP_KEYS = ["comments","mentions","updates",+ "new_issues","agent_activity",] as const;type InboxGroupKey = (typeof INBOX_GROUP_KEYS)[number];diff --git a/packages/views/settings/components/use-settings-search-index.ts b/packages/views/settings/components/use-settings-search-index.tsindex f5e25da4c1..1f956db3c0 100644--- a/packages/views/settings/components/use-settings-search-index.ts+++ b/packages/views/settings/components/use-settings-search-index.ts@@ -12,6 +12,7 @@ const NOTIFICATION_GROUPS = ["comments","mentions","updates",+ "new_issues","agent_activity",] as const;diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 6f4947e924..e2ff196eb6 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -140,6 +140,7 @@ var pgBigmOperatorClass = extensionOperatorClass{// they are still pending: a fresh self-hosted install, which is exactly where an// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{+ "648_project_subscriber_user_idx": "idx_project_subscriber_workspace_user","645_issue_member_creator_index": "idx_issue_workspace_member_creator","644_issue_requester_index": "idx_issue_workspace_requester","642_issue_environment_config_issue_idx": "idx_issue_environment_config_issue",diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.goindex e5fcccee68..7d11ffa660 100644--- a/server/cmd/server/notification_listeners.go+++ b/server/cmd/server/notification_listeners.go@@ -186,6 +186,7 @@ var notifTypeToGroup = map[string]string{"task_failed": "agent_activity","agent_blocked": "agent_activity","agent_completed": "agent_activity",+ "issue_created": "new_issues",}// isNotifMuted returns true if the given notification type is muted for a user@@ -312,13 +313,47 @@ func notifySubscribers(body string,details []byte,) {+ notified := notifyIssueAndParentSubscribers(ctx, queries, bus, issueID, issueStatus,+ workspaceID, e, exclude, notifType, severity, title, body, details)++ // Project watchers hear about every issue in the project, after the+ // issue-level fanout so nobody receives the same event twice.+ projectExclude := make(map[string]bool, len(exclude)+len(notified))+ for id := range exclude {+ projectExclude[id] = true+ }+ for id := range notified {+ projectExclude[id] = true+ }+ notifyProjectSubscribers(ctx, queries, bus, issueID, issueStatus, workspaceID, e,+ projectExclude, notifType, severity, title, body, details)+}++// notifyIssueAndParentSubscribers is the issue-level half of notifySubscribers:+// the issue's own subscribers, then — for bubbling types — its parent's.+// Returns every member it notified.+func notifyIssueAndParentSubscribers(+ ctx context.Context,+ queries *db.Queries,+ bus *events.Bus,+ issueID string,+ issueStatus string,+ workspaceID string,+ e events.Event,+ exclude map[string]bool,+ notifType string,+ severity string,+ title string,+ body string,+ details []byte,+) map[string]bool {notified, tierSuppressed := notifyIssueSubscribers(ctx, queries, bus,issueID, issueID, issueStatus, workspaceID, e, exclude,notifType, severity, title, body, details)// Only a small allowlist of event types bubbles to parent subscribers.if !parentBubbleNotifTypes[notifType] {- return+ return notified}// Also notify parent issue subscribers if this is a sub-issue.@@ -326,10 +361,10 @@ func notifySubscribers(if err != nil {slog.Error("failed to get issue for parent notification","issue_id", issueID, "error", err)- return+ return notified}if !issue.ParentIssueID.Valid {- return+ return notified}// Merge already-notified IDs into exclude set for parent subscribers.@@ -354,9 +389,113 @@ func notifySubscribers(// Query subscribers from the parent issue, but the inbox item still// points to the sub-issue so the user navigates to the actual change.parentID := util.UUIDToString(issue.ParentIssueID)- notifyIssueSubscribers(ctx, queries, bus,+ parentNotified, _ := notifyIssueSubscribers(ctx, queries, bus,parentID, issueID, issueStatus, workspaceID, e, parentExclude,notifType, severity, title, body, details)+ for id := range parentNotified {+ notified[id] = true+ }+ return notified+}++// notifyProjectSubscribers delivers an issue event to the members watching the+// issue's project. A project subscription is an explicit request to hear about+// every issue in it, so the delegated delivery tier does not narrow it; the+// actor, the exclude set, muted preference groups and per-issue opt-outs+// (ListProjectSubscribersForIssue) still apply.+func notifyProjectSubscribers(+ ctx context.Context,+ queries *db.Queries,+ bus *events.Bus,+ issueID string,+ issueStatus string,+ workspaceID string,+ e events.Event,+ exclude map[string]bool,+ notifType string,+ severity string,+ title string,+ body string,+ details []byte,+) {+ subscribers, err := queries.ListProjectSubscribersForIssue(ctx, parseUUID(issueID))+ if err != nil {+ slog.Error("failed to list project subscribers for notification",+ "issue_id", issueID, "error", err)+ return+ }+ if len(subscribers) == 0 {+ return+ }++ recipients := make([]string, 0, len(subscribers))+ for _, sub := range subscribers {+ subID := util.UUIDToString(sub.UserID)+ if subID == e.ActorID || exclude[subID] {+ continue+ }+ recipients = append(recipients, subID)+ }+ userPrefs := loadUserPrefs(ctx, queries, workspaceID, recipients)++ for _, subID := range recipients {+ if prefs, ok := userPrefs[subID]; ok && isNotifMuted(prefs, notifType) {+ continue+ }+ createMemberInboxItem(ctx, queries, bus, subID, workspaceID, e, issueID, issueStatus,+ notifType, severity, title, body, details)+ }+}++// createMemberInboxItem writes one member inbox row and announces it. Reports+// whether a row was actually inserted.+func createMemberInboxItem(+ ctx context.Context,+ queries *db.Queries,+ bus *events.Bus,+ recipientID string,+ workspaceID string,+ e events.Event,+ issueID string,+ issueStatus string,+ notifType string,+ severity string,+ title string,+ body string,+ details []byte,+) bool {+ item, inserted, err := inbox.CreateIfEligible(ctx, queries, db.CreateInboxItemParams{+ ID: dbid.NewV7(),+ WorkspaceID: parseUUID(workspaceID),+ RecipientType: "member",+ RecipientID: parseUUID(recipientID),+ Type: notifType,+ Severity: severity,+ IssueID: parseUUID(issueID),+ Title: title,+ Body: util.StrToText(body),+ ActorType: util.StrToText(e.ActorType),+ ActorID: optionalUUID(e.ActorID),+ Details: details,+ })+ if err != nil {+ slog.Error("member notification creation failed",+ "recipient_id", recipientID, "type", notifType, "error", err)+ return false+ }+ if !inserted {+ return false+ }+ resp := inboxItemToResponse(item)+ resp["issue_status"] = issueStatus+ bus.Publish(events.Event{+ Type: protocol.EventInboxNew,+ WorkspaceID: workspaceID,+ ActorType: e.ActorType,+ ActorID: e.ActorID,+ Payload: map[string]any{"item": resp},+ })+ return true}// notifyIssueSubscribers sends inbox notifications to subscribers of@@ -448,39 +587,10 @@ func notifyIssueSubscribers(continue}- item, inserted, err := inbox.CreateIfEligible(ctx, queries, db.CreateInboxItemParams{- ID: dbid.NewV7(),- WorkspaceID: parseUUID(workspaceID),- RecipientType: "member",- RecipientID: sub.UserID,- Type: notifType,- Severity: severity,- IssueID: parseUUID(targetIssueID),- Title: title,- Body: util.StrToText(body),- ActorType: util.StrToText(e.ActorType),- ActorID: optionalUUID(e.ActorID),- Details: details,- })- if err != nil {- slog.Error("subscriber notification creation failed",- "subscriber_id", subID, "type", notifType, "error", err)- continue+ if createMemberInboxItem(ctx, queries, bus, subID, workspaceID, e, targetIssueID, issueStatus,+ notifType, severity, title, body, details) {+ notified[subID] = true}- if !inserted {- continue- }-- notified[subID] = true- resp := inboxItemToResponse(item)- resp["issue_status"] = issueStatus- bus.Publish(events.Event{- Type: protocol.EventInboxNew,- WorkspaceID: workspaceID,- ActorType: e.ActorType,- ActorID: e.ActorID,- Payload: map[string]any{"item": resp},- })}return notified, tierSuppressed@@ -713,6 +823,14 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {notifyMentionedMembers(bus, queries, e, mentions, issue.ID, issue.Title, issue.Status,issue.Title, skip, emptyDetails)}++ // Members watching the project hear about every new issue in it.+ if issue.ProjectID != nil {+ notifyProjectSubscribers(ctx, queries, bus, issue.ID, issue.Status, issue.WorkspaceID, e,+ skip, "issue_created", "info",+ issue.Title, "",+ emptyDetails)+ }})// issue:updated — handle assignee changes, status changes, priority, due datediff --git a/server/cmd/server/notification_project_subscriber_test.go b/server/cmd/server/notification_project_subscriber_test.gonew file mode 100644index 0000000000..fd05663c46--- /dev/null+++ b/server/cmd/server/notification_project_subscriber_test.go@@ -0,0 +1,274 @@+package main++import (+ "context"+ "net/http"+ "slices"+ "testing"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/handler"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// createTestProject creates an empty project in the test workspace.+func createTestProject(t *testing.T) string {+ t.Helper()+ var projectID string+ if err := testPool.QueryRow(context.Background(), `+ INSERT INTO project (workspace_id, title) VALUES ($1, 'project subscriber test') RETURNING id+ `, testWorkspaceID).Scan(&projectID); err != nil {+ t.Fatalf("create project: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM project_subscriber WHERE project_id = $1`, projectID)+ testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID)+ })+ return projectID+}++// createProjectIssue files a fresh issue under projectID.+func createProjectIssue(t *testing.T, projectID string) string {+ t.Helper()+ issueID := createTestIssue(t, testWorkspaceID, testUserID)+ t.Cleanup(func() {+ cleanupInboxForIssue(t, issueID)+ cleanupTestIssue(t, issueID)+ })+ if _, err := testPool.Exec(context.Background(), `UPDATE issue SET project_id = $1 WHERE id = $2`, projectID, issueID); err != nil {+ t.Fatalf("move issue into project: %v", err)+ }+ return issueID+}++func addProjectSubscribers(t *testing.T, projectID string, userIDs ...string) {+ t.Helper()+ for _, id := range userIDs {+ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO project_subscriber (workspace_id, project_id, user_id) VALUES ($1, $2, $3)+ `, testWorkspaceID, projectID, id); err != nil {+ t.Fatalf("add project subscriber: %v", err)+ }+ }+}++// requestAs calls the real router as userID.+func requestAs(t *testing.T, userID, email, method, path string) {+ t.Helper()+ token, err := generateTestJWT(userID, email, "Project Watcher")+ if err != nil {+ t.Fatalf("generate token: %v", err)+ }+ req, err := http.NewRequest(method, testServer.URL+path, nil)+ if err != nil {+ t.Fatalf("new request: %v", err)+ }+ req.Header.Set("Authorization", "Bearer "+token)+ req.Header.Set("X-Workspace-ID", testWorkspaceID)+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatalf("%s %s: %v", method, path, err)+ }+ resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("%s %s: status %d, want 200", method, path, resp.StatusCode)+ }+}++func inboxTypes(t *testing.T, queries *db.Queries, recipientID string) []string {+ t.Helper()+ var types []string+ for _, item := range inboxItemsForRecipient(t, queries, recipientID) {+ types = append(types, item.Type)+ }+ return types+}++func inboxCountForIssue(t *testing.T, queries *db.Queries, recipientID, issueID string) int {+ t.Helper()+ n := 0+ for _, item := range inboxItemsForRecipient(t, queries, recipientID) {+ if item.IssueID.Valid && item.IssueID.String() == issueID {+ n+++ }+ }+ return n+}++func publishComment(bus *events.Bus, issueID, authorID string) {+ bus.Publish(events.Event{+ Type: protocol.EventCommentCreated,+ WorkspaceID: testWorkspaceID,+ ActorType: "member",+ ActorID: authorID,+ Payload: map[string]any{+ "comment": handler.CommentResponse{+ ID: "00000000-0000-0000-0000-000000000000",+ IssueID: issueID,+ AuthorType: "member",+ AuthorID: authorID,+ Content: "project subscriber comment",+ Type: "comment",+ },+ "issue_title": "project subscriber issue",+ "issue_status": "todo",+ },+ })+}++func TestNotification_ProjectSubscriber_IssueEvents(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)++ watcherEmail := "[email protected]"+ watcherID := createNotificationMember(t, watcherEmail)+ t.Cleanup(func() { cleanupTestUser(t, watcherEmail) })++ // Both an issue subscriber and a project watcher: notified once.+ bothEmail := "[email protected]"+ bothID := createNotificationMember(t, bothEmail)+ t.Cleanup(func() { cleanupTestUser(t, bothEmail) })++ projectID := createTestProject(t)+ issueID := createProjectIssue(t, projectID)+ addProjectSubscribers(t, projectID, watcherID, bothID, testUserID)+ addTestSubscriber(t, issueID, "member", bothID, "commenter")++ issue := handler.IssueResponse{+ ID: issueID,+ WorkspaceID: testWorkspaceID,+ Title: "project subscriber issue",+ Status: "todo",+ Priority: "medium",+ CreatorType: "member",+ CreatorID: testUserID,+ ProjectID: &projectID,+ }+ bus.Publish(events.Event{+ Type: protocol.EventIssueCreated,+ WorkspaceID: testWorkspaceID,+ ActorType: "member",+ ActorID: testUserID,+ Payload: map[string]any{"issue": issue},+ })++ issue.Status = "in_progress"+ bus.Publish(events.Event{+ Type: protocol.EventIssueUpdated,+ WorkspaceID: testWorkspaceID,+ ActorType: "member",+ ActorID: testUserID,+ Payload: map[string]any{+ "issue": issue,+ "status_changed": true,+ "prev_status": "todo",+ },+ })++ if got := inboxTypes(t, queries, watcherID); len(got) != 2 || !slices.Contains(got, "issue_created") || !slices.Contains(got, "status_changed") {+ t.Fatalf("watcher inbox = %v, want issue_created + status_changed", got)+ }+ if got := inboxTypes(t, queries, bothID); len(got) != 2 {+ t.Fatalf("issue+project subscriber inbox = %v, want each event once", got)+ }+ if got := inboxTypes(t, queries, testUserID); len(got) != 0 {+ t.Fatalf("actor inbox = %v, want empty", got)+ }+}++// A member who only watches the project leaves one issue through the issue+// endpoint. That opt-out must hold for that issue alone, survive a project+// re-subscribe, and yield to an explicit issue subscribe.+func TestNotification_ProjectSubscriber_LeaveOneIssue(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)++ watcherEmail := "[email protected]"+ watcherID := createNotificationMember(t, watcherEmail)+ t.Cleanup(func() { cleanupTestUser(t, watcherEmail) })++ commenterEmail := "[email protected]"+ commenterID := createNotificationMember(t, commenterEmail)+ t.Cleanup(func() { cleanupTestUser(t, commenterEmail) })++ projectID := createTestProject(t)+ leftIssueID := createProjectIssue(t, projectID)+ otherIssueID := createProjectIssue(t, projectID)++ requestAs(t, watcherID, watcherEmail, http.MethodPut, "/api/projects/"+projectID+"/subscription")+ requestAs(t, watcherID, watcherEmail, http.MethodPost, "/api/issues/"+leftIssueID+"/unsubscribe")++ publishComment(bus, leftIssueID, commenterID)+ publishComment(bus, otherIssueID, commenterID)+ if got := inboxCountForIssue(t, queries, watcherID, leftIssueID); got != 0 {+ t.Fatalf("left issue inbox items = %d, want 0", got)+ }+ if got := inboxCountForIssue(t, queries, watcherID, otherIssueID); got != 1 {+ t.Fatalf("other issue inbox items = %d, want 1", got)+ }++ // Re-subscribing to the project keeps the per-issue opt-out.+ requestAs(t, watcherID, watcherEmail, http.MethodDelete, "/api/projects/"+projectID+"/subscription")+ requestAs(t, watcherID, watcherEmail, http.MethodPut, "/api/projects/"+projectID+"/subscription")+ publishComment(bus, leftIssueID, commenterID)+ if got := inboxCountForIssue(t, queries, watcherID, leftIssueID); got != 0 {+ t.Fatalf("left issue inbox items after project re-subscribe = %d, want 0", got)+ }++ // An explicit subscribe brings the issue back as its own subscription,+ // which then outlives the project subscription.+ requestAs(t, watcherID, watcherEmail, http.MethodPost, "/api/issues/"+leftIssueID+"/subscribe")+ requestAs(t, watcherID, watcherEmail, http.MethodDelete, "/api/projects/"+projectID+"/subscription")+ publishComment(bus, leftIssueID, commenterID)+ publishComment(bus, otherIssueID, commenterID)+ if got := inboxCountForIssue(t, queries, watcherID, leftIssueID); got != 1 {+ t.Fatalf("left issue inbox items after explicit subscribe = %d, want 1", got)+ }+ if got := inboxCountForIssue(t, queries, watcherID, otherIssueID); got != 1 {+ t.Fatalf("other issue inbox items after project unsubscribe = %d, want still 1", got)+ }+}++func TestNotification_ProjectSubscriber_IssueCreatedRespectsMute(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)++ mutedEmail := "[email protected]"+ mutedID := createNotificationMember(t, mutedEmail)+ t.Cleanup(func() { cleanupTestUser(t, mutedEmail) })++ projectID := createTestProject(t)+ issueID := createProjectIssue(t, projectID)+ addProjectSubscribers(t, projectID, mutedID)+ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO notification_preference (workspace_id, user_id, preferences)+ VALUES ($1, $2, '{"new_issues":"muted"}'::jsonb)+ `, testWorkspaceID, mutedID); err != nil {+ t.Fatalf("seed muted notification preference: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM notification_preference WHERE user_id = $1`, mutedID)+ })++ bus.Publish(events.Event{+ Type: protocol.EventIssueCreated,+ WorkspaceID: testWorkspaceID,+ ActorType: "member",+ ActorID: testUserID,+ Payload: map[string]any{"issue": handler.IssueResponse{+ ID: issueID,+ WorkspaceID: testWorkspaceID,+ Title: "muted project issue",+ Status: "todo",+ Priority: "medium",+ CreatorType: "member",+ CreatorID: testUserID,+ ProjectID: &projectID,+ }},+ })++ if got := inboxTypes(t, queries, mutedID); len(got) != 0 {+ t.Fatalf("muted watcher inbox = %v, want empty", got)+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex a6bb6cd449..b5f33c4753 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2287,6 +2287,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/members", h.ListProjectMembers)r.Post("/members", h.AddProjectMembers)r.Delete("/members/{userId}", h.RemoveProjectMember)+ r.Get("/subscription", h.GetProjectSubscription)+ r.Put("/subscription", h.SubscribeToProject)+ r.Delete("/subscription", h.UnsubscribeFromProject)r.Get("/resources", h.ListProjectResources)r.Post("/resources", h.CreateProjectResource)r.Put("/resources/{resourceId}", h.UpdateProjectResource)diff --git a/server/internal/handler/notification_preference.go b/server/internal/handler/notification_preference.goindex afaed3d08a..9df49066dc 100644--- a/server/internal/handler/notification_preference.go+++ b/server/internal/handler/notification_preference.go@@ -24,6 +24,7 @@ var validNotifGroups = map[string]bool{"mentions": true,"updates": true,"agent_activity": true,+ "new_issues": true,"system_notifications": true,}diff --git a/server/internal/handler/project.go b/server/internal/handler/project.goindex 6ed7ef6d49..f036e721cd 100644--- a/server/internal/handler/project.go+++ b/server/internal/handler/project.go@@ -801,6 +801,13 @@ func (h *Handler) DeleteProject(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to delete project members")return}+ if err := qtx.DeleteProjectSubscribersByProject(r.Context(), db.DeleteProjectSubscribersByProjectParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete project subscribers")+ return+ }if err := qtx.DeleteProject(r.Context(), db.DeleteProjectParams{ID: project.ID,WorkspaceID: project.WorkspaceID,diff --git a/server/internal/handler/project_subscriber.go b/server/internal/handler/project_subscriber.gonew file mode 100644index 0000000000..505c128bfd--- /dev/null+++ b/server/internal/handler/project_subscriber.go@@ -0,0 +1,86 @@+package handler++import (+ "net/http"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type ProjectSubscriptionResponse struct {+ Subscribed bool `json:"subscribed"`+}++// loadProjectForSubscription resolves the visible project and the human+// caller. Project subscriptions belong to members: an agent already hears+// about its issues through assignment and mentions.+func (h *Handler) loadProjectForSubscription(w http.ResponseWriter, r *http.Request) (db.Project, string, bool) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return db.Project{}, "", false+ }+ project, ok := h.loadVisibleProject(w, r)+ if !ok {+ return db.Project{}, "", false+ }+ if actorType, _ := h.resolveActor(r, userID, uuidToString(project.WorkspaceID)); actorType == "agent" {+ writeError(w, http.StatusForbidden, "agents cannot subscribe to projects")+ return db.Project{}, "", false+ }+ return project, userID, true+}++func (h *Handler) writeProjectSubscription(w http.ResponseWriter, r *http.Request, project db.Project, userID string) {+ subscribed, err := h.Queries.IsProjectSubscriber(r.Context(), db.IsProjectSubscriberParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ UserID: parseUUID(userID),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load project subscription")+ return+ }+ writeJSON(w, http.StatusOK, ProjectSubscriptionResponse{Subscribed: subscribed})+}++// GetProjectSubscription — GET /api/projects/{id}/subscription+func (h *Handler) GetProjectSubscription(w http.ResponseWriter, r *http.Request) {+ project, userID, ok := h.loadProjectForSubscription(w, r)+ if !ok {+ return+ }+ h.writeProjectSubscription(w, r, project, userID)+}++// SubscribeToProject — PUT /api/projects/{id}/subscription+func (h *Handler) SubscribeToProject(w http.ResponseWriter, r *http.Request) {+ project, userID, ok := h.loadProjectForSubscription(w, r)+ if !ok {+ return+ }+ if err := h.Queries.AddProjectSubscriber(r.Context(), db.AddProjectSubscriberParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ UserID: parseUUID(userID),+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to subscribe to project")+ return+ }+ h.writeProjectSubscription(w, r, project, userID)+}++// UnsubscribeFromProject — DELETE /api/projects/{id}/subscription+func (h *Handler) UnsubscribeFromProject(w http.ResponseWriter, r *http.Request) {+ project, userID, ok := h.loadProjectForSubscription(w, r)+ if !ok {+ return+ }+ if err := h.Queries.RemoveProjectSubscriber(r.Context(), db.RemoveProjectSubscriberParams{+ ProjectID: project.ID,+ WorkspaceID: project.WorkspaceID,+ UserID: parseUUID(userID),+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to unsubscribe from project")+ return+ }+ writeJSON(w, http.StatusOK, ProjectSubscriptionResponse{Subscribed: false})+}diff --git a/server/internal/handler/project_subscriber_test.go b/server/internal/handler/project_subscriber_test.gonew file mode 100644index 0000000000..9a4ac9c4c1--- /dev/null+++ b/server/internal/handler/project_subscriber_test.go@@ -0,0 +1,140 @@+package handler++import (+ "context"+ "net/http"+ "testing"++ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestProjectSubscriptionAPI(t *testing.T) {+ f := newPrivateProjectFixture(t)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM project_subscriber WHERE project_id = $1`, f.projectID)+ })++ call := func(method, userID string) *testutil.Response {+ req := withURLParam(asUser(newRequest(method, "/api/projects/"+f.projectID+"/subscription", nil), userID), "id", f.projectID)+ switch method {+ case http.MethodPut:+ return testutil.Call(t, testHandler.SubscribeToProject, req)+ case http.MethodDelete:+ return testutil.Call(t, testHandler.UnsubscribeFromProject, req)+ default:+ return testutil.Call(t, testHandler.GetProjectSubscription, req)+ }+ }+ subscribed := func(method, userID string) bool {+ var resp ProjectSubscriptionResponse+ call(method, userID).Want(http.StatusOK).JSON(&resp)+ return resp.Subscribed+ }++ if subscribed(http.MethodGet, f.insider) {+ t.Fatal("new viewer should start unsubscribed")+ }+ if !subscribed(http.MethodPut, f.insider) {+ t.Fatal("PUT should subscribe")+ }+ // Idempotent.+ if !subscribed(http.MethodPut, f.insider) || !subscribed(http.MethodGet, f.insider) {+ t.Fatal("subscription should persist")+ }+ if subscribed(http.MethodDelete, f.insider) || subscribed(http.MethodGet, f.insider) {+ t.Fatal("DELETE should unsubscribe")+ }++ // A member who cannot see the private project cannot watch it either.+ call(http.MethodPut, f.outsider).Want(http.StatusNotFound)+ var count int+ if err := testPool.QueryRow(context.Background(),+ `SELECT count(*) FROM project_subscriber WHERE project_id = $1 AND user_id = $2`,+ f.projectID, f.outsider).Scan(&count); err != nil {+ t.Fatal(err)+ }+ if count != 0 {+ t.Fatalf("outsider subscription rows = %d, want 0", count)+ }+}++func TestIssueSubscribersIncludeProjectSubscribers(t *testing.T) {+ f := newPrivateProjectFixture(t)+ ctx := context.Background()+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM project_subscriber WHERE project_id = $1`, f.projectID)+ testPool.Exec(context.Background(), `DELETE FROM issue_subscriber WHERE issue_id = $1`, f.secretIssue)+ })+ // The outsider's row stands for a member who lost access after subscribing.+ for _, userID := range []string{f.insider, f.outsider, testUserID} {+ if _, err := testPool.Exec(ctx, `+ INSERT INTO project_subscriber (workspace_id, project_id, user_id) VALUES ($1, $2, $3)+ `, testWorkspaceID, f.projectID, userID); err != nil {+ t.Fatal(err)+ }+ }++ issuePath := "/api/issues/" + f.secretIssue+ reasons := func() map[string][]string {+ t.Helper()+ var resp []SubscriberResponse+ req := withURLParam(asUser(newRequest(http.MethodGet, issuePath+"/subscribers", nil), testUserID), "id", f.secretIssue)+ testutil.Call(t, testHandler.ListIssueSubscribers, req).Want(http.StatusOK).JSON(&resp)+ got := map[string][]string{}+ for _, s := range resp {+ got[s.UserID] = append(got[s.UserID], s.Reason)+ }+ return got+ }+ act := func(h http.HandlerFunc, path, userID string) {+ t.Helper()+ req := withURLParam(asUser(newRequest(http.MethodPost, path, nil), userID), "id", f.secretIssue)+ testutil.Call(t, h, req).Want(http.StatusOK)+ }+ optOutScope := func(userID string) string {+ t.Helper()+ var scope string+ if err := testPool.QueryRow(ctx, `+ SELECT opt_out_scope FROM issue_subscriber+ WHERE issue_id = $1 AND user_type = 'member' AND user_id = $2 AND unsubscribed_at IS NOT NULL+ `, f.secretIssue, userID).Scan(&scope); err != nil {+ t.Fatalf("opt-out for %s: %v", userID, err)+ }+ return scope+ }++ got := reasons()+ if r := got[f.insider]; len(r) != 1 || r[0] != "project" {+ t.Fatalf("insider reasons = %v, want [project]", r)+ }+ if r, ok := got[f.outsider]; ok {+ t.Fatalf("outsider listed with %v; they cannot see the project", r)+ }++ // Leaving the issue persists an opt-out although no row existed.+ act(testHandler.UnsubscribeFromIssue, issuePath+"/unsubscribe", f.insider)+ if r, ok := reasons()[f.insider]; ok {+ t.Fatalf("insider still listed with %v after leaving the issue", r)+ }+ if scope := optOutScope(f.insider); scope != "issue" {+ t.Fatalf("insider opt-out scope = %q, want issue", scope)+ }++ // An existing subtree opt-out is not narrowed by a second unsubscribe.+ if _, err := testPool.Exec(ctx, `+ INSERT INTO issue_subscriber (issue_id, user_type, user_id, reason, unsubscribed_at, opt_out_scope)+ VALUES ($1, 'member', $2, 'manual', now(), 'subtree')+ `, f.secretIssue, testUserID); err != nil {+ t.Fatal(err)+ }+ act(testHandler.UnsubscribeFromIssue, issuePath+"/unsubscribe", testUserID)+ if scope := optOutScope(testUserID); scope != "subtree" {+ t.Fatalf("owner opt-out scope = %q, want subtree", scope)+ }++ // Subscribing explicitly brings the member back once, as a direct row.+ act(testHandler.SubscribeToIssue, issuePath+"/subscribe", f.insider)+ if r := reasons()[f.insider]; len(r) != 1 || r[0] != "manual" {+ t.Fatalf("insider reasons after explicit subscribe = %v, want [manual]", r)+ }+}diff --git a/server/internal/handler/subscriber.go b/server/internal/handler/subscriber.goindex 7ae54d5f80..0cfcda6966 100644--- a/server/internal/handler/subscriber.go+++ b/server/internal/handler/subscriber.go@@ -46,14 +46,45 @@ func (h *Handler) ListIssueSubscribers(w http.ResponseWriter, r *http.Request) {return}- resp := make([]SubscriberResponse, len(subscribers))- for i, s := range subscribers {- resp[i] = subscriberToResponse(s)+ // Project subscribers have no row here but are notified all the same, so+ // they are part of the issue's effective list. A direct row wins: it+ // carries the reason the member is involved in this issue specifically.+ projectSubscribers, err := h.Queries.ListProjectSubscribersForIssue(r.Context(), issue.ID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list subscribers")+ return+ }++ resp := make([]SubscriberResponse, 0, len(subscribers)+len(projectSubscribers))+ direct := make(map[string]bool, len(subscribers))+ for _, s := range subscribers {+ resp = append(resp, subscriberToResponse(s))+ if s.UserType == "member" {+ direct[uuidToString(s.UserID)] = true+ }+ }+ for _, ps := range projectSubscribers {+ userID := uuidToString(ps.UserID)+ if direct[userID] {+ continue+ }+ resp = append(resp, SubscriberResponse{+ IssueID: uuidToString(issue.ID),+ UserType: "member",+ UserID: userID,+ Reason: subscriberReasonProject,+ CreatedAt: timestampToString(ps.CreatedAt),+ })}writeJSON(w, http.StatusOK, resp)}+// subscriberReasonProject marks a subscription inherited from the issue's+// project. It is never stored on issue_subscriber; leaving the issue writes an+// opt-out tombstone instead (RemoveIssueSubscriber).+const subscriberReasonProject = "project"+// 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.diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex eeda262989..abb4c440e1 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -118,6 +118,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"plugin_package_file": workspaceDelete,"project": workspaceDelete,"project_member": workspaceDelete,+ "project_subscriber": workspaceDelete,"project_resource": workspaceDelete,"quick_action": workspaceDelete,"runtime_profile": workspaceDelete,diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.goindex 206b15027d..4874c82fa2 100644--- a/server/internal/handler/workspace_revoke.go+++ b/server/internal/handler/workspace_revoke.go@@ -266,12 +266,17 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userID}// No FK cascade (repo rule): a departing member leaves every private- // project in the workspace.+ // project in the workspace and stops watching every project.if err := qtx.DeleteProjectMembersByUser(ctx, db.DeleteProjectMembersByUserParams{WorkspaceID: workspaceID, UserID: userID,}); err != nil {return empty, err}+ if err := qtx.DeleteProjectSubscribersByUser(ctx, db.DeleteProjectSubscribersByUserParams{+ WorkspaceID: workspaceID, UserID: userID,+ }); err != nil {+ return empty, err+ }if err := qtx.DeleteMember(ctx, memberID); err != nil {return empty, err}diff --git a/server/internal/integrations/wecom/strings.go b/server/internal/integrations/wecom/strings.goindex 59c6d08fb8..b3a05459e0 100644--- a/server/internal/integrations/wecom/strings.go+++ b/server/internal/integrations/wecom/strings.go@@ -463,6 +463,7 @@ var copyPacks = map[Locale]copyPack{"priority_changed": "优先级变更","due_date_changed": "截止日期变更","start_date_changed": "开始日期变更",+ "issue_created": "新任务",},InboxTypeFallback: "新消息",},@@ -541,6 +542,7 @@ var copyPacks = map[Locale]copyPack{"priority_changed": "Priority changed","due_date_changed": "Due date changed","start_date_changed": "Start date changed",+ "issue_created": "New issue",},InboxTypeFallback: "Notification",},diff --git a/server/migrations/647_project_subscriber.down.sql b/server/migrations/647_project_subscriber.down.sqlnew file mode 100644index 0000000000..05a0e09010--- /dev/null+++ b/server/migrations/647_project_subscriber.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS project_subscriber;diff --git a/server/migrations/647_project_subscriber.up.sql b/server/migrations/647_project_subscriber.up.sqlnew file mode 100644index 0000000000..03b83ebb55--- /dev/null+++ b/server/migrations/647_project_subscriber.up.sql@@ -0,0 +1,13 @@+-- Members who watch every issue in a project. Issue-level subscriptions stay+-- the source of per-issue intent; this row only adds the project's issues to+-- the member's notification fanout.+--+-- No foreign keys (repo rule): project deletion, member removal and workspace+-- teardown delete these rows in application code.+CREATE TABLE IF NOT EXISTS project_subscriber (+ workspace_id UUID NOT NULL,+ project_id UUID NOT NULL,+ user_id UUID NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (project_id, user_id)+);diff --git a/server/migrations/648_project_subscriber_user_idx.down.sql b/server/migrations/648_project_subscriber_user_idx.down.sqlnew file mode 100644index 0000000000..04f99e4918--- /dev/null+++ b/server/migrations/648_project_subscriber_user_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_project_subscriber_workspace_user;diff --git a/server/migrations/648_project_subscriber_user_idx.up.sql b/server/migrations/648_project_subscriber_user_idx.up.sqlnew file mode 100644index 0000000000..dbc234ca9f--- /dev/null+++ b/server/migrations/648_project_subscriber_user_idx.up.sql@@ -0,0 +1,3 @@+-- Serves the member-removal cleanup, keyed by (workspace, user).+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_project_subscriber_workspace_user+ ON project_subscriber (workspace_id, user_id);diff --git a/server/pkg/db/generated/inbox_archive.sql.go b/server/pkg/db/generated/inbox_archive.sql.goindex cb191aa94f..4fef26926d 100644--- a/server/pkg/db/generated/inbox_archive.sql.go+++ b/server/pkg/db/generated/inbox_archive.sql.go@@ -19,7 +19,7 @@ WITH base AS MATERIALIZED (WHEN i.type IN ('new_comment', 'reaction_added') THEN 'comment'WHEN i.type IN ('issue_assigned', 'unassigned', 'assignee_changed', 'issue_subscribed') THEN 'assign'WHEN i.type = 'review_requested' THEN 'review'- WHEN i.type IN ('status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'+ WHEN i.type IN ('issue_created', 'status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'WHEN i.type IN ('task_completed', 'task_failed', 'agent_blocked', 'agent_completed') THEN 'run'ELSE 'system'END AS type_group,@@ -214,7 +214,7 @@ WITH base AS MATERIALIZED (WHEN i.type IN ('new_comment', 'reaction_added') THEN 'comment'WHEN i.type IN ('issue_assigned', 'unassigned', 'assignee_changed', 'issue_subscribed') THEN 'assign'WHEN i.type = 'review_requested' THEN 'review'- WHEN i.type IN ('status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'+ WHEN i.type IN ('issue_created', 'status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'WHEN i.type IN ('task_completed', 'task_failed', 'agent_blocked', 'agent_completed') THEN 'run'ELSE 'system'END AS type_group,diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex e72cd87324..b14cc6fe77 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1548,6 +1548,13 @@ type ProjectResource struct {CreatedBy pgtype.UUID `json:"created_by"`}+type ProjectSubscriber struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ProjectID pgtype.UUID `json:"project_id"`+ UserID pgtype.UUID `json:"user_id"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}+type QuickAction struct {ID pgtype.UUID `json:"id"`WorkspaceID pgtype.UUID `json:"workspace_id"`diff --git a/server/pkg/db/generated/project_subscriber.sql.go b/server/pkg/db/generated/project_subscriber.sql.gonew file mode 100644index 0000000000..88ae26d0e2--- /dev/null+++ b/server/pkg/db/generated/project_subscriber.sql.go@@ -0,0 +1,166 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: project_subscriber.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const addProjectSubscriber = `-- name: AddProjectSubscriber :exec+INSERT INTO project_subscriber (workspace_id, project_id, user_id)+SELECT m.workspace_id, $1::uuid, m.user_id+FROM member m+WHERE m.workspace_id = $2 AND m.user_id = $3+ON CONFLICT (project_id, user_id) DO NOTHING+`++type AddProjectSubscriberParams struct {+ ProjectID pgtype.UUID `json:"project_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+}++// Only a current workspace member can watch a project.+func (q *Queries) AddProjectSubscriber(ctx context.Context, arg AddProjectSubscriberParams) error {+ _, err := q.db.Exec(ctx, addProjectSubscriber, arg.ProjectID, arg.WorkspaceID, arg.UserID)+ return err+}++const deleteProjectSubscribersByProject = `-- name: DeleteProjectSubscribersByProject :exec+DELETE FROM project_subscriber+WHERE project_id = $1 AND workspace_id = $2+`++type DeleteProjectSubscribersByProjectParams struct {+ ProjectID pgtype.UUID `json:"project_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) DeleteProjectSubscribersByProject(ctx context.Context, arg DeleteProjectSubscribersByProjectParams) error {+ _, err := q.db.Exec(ctx, deleteProjectSubscribersByProject, arg.ProjectID, arg.WorkspaceID)+ return err+}++const deleteProjectSubscribersByUser = `-- name: DeleteProjectSubscribersByUser :exec+DELETE FROM project_subscriber+WHERE workspace_id = $1 AND user_id = $2+`++type DeleteProjectSubscribersByUserParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+}++// A member leaving the workspace stops watching every project in it.+func (q *Queries) DeleteProjectSubscribersByUser(ctx context.Context, arg DeleteProjectSubscribersByUserParams) error {+ _, err := q.db.Exec(ctx, deleteProjectSubscribersByUser, arg.WorkspaceID, arg.UserID)+ return err+}++const isProjectSubscriber = `-- name: IsProjectSubscriber :one+SELECT EXISTS(+ SELECT 1 FROM project_subscriber+ WHERE project_id = $1+ AND workspace_id = $2+ AND user_id = $3+) AS subscribed+`++type IsProjectSubscriberParams struct {+ ProjectID pgtype.UUID `json:"project_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+}++func (q *Queries) IsProjectSubscriber(ctx context.Context, arg IsProjectSubscriberParams) (bool, error) {+ row := q.db.QueryRow(ctx, isProjectSubscriber, arg.ProjectID, arg.WorkspaceID, arg.UserID)+ var subscribed bool+ err := row.Scan(&subscribed)+ return subscribed, err+}++const listProjectSubscribersForIssue = `-- name: ListProjectSubscribersForIssue :many+WITH RECURSIVE ancestors(node_id, parent_id, depth) AS (+ SELECT root.id, root.parent_issue_id, 0 FROM issue root WHERE root.id = $1+ UNION ALL+ SELECT i.id, i.parent_issue_id, a.depth + 1 FROM issue i JOIN ancestors a ON i.id = a.parent_id+)+SELECT ps.user_id, ps.created_at+FROM issue target+JOIN project p ON p.id = target.project_id AND p.workspace_id = target.workspace_id+JOIN project_subscriber ps+ ON ps.project_id = p.id AND ps.workspace_id = p.workspace_id+JOIN member m ON m.workspace_id = ps.workspace_id AND m.user_id = ps.user_id+WHERE target.id = $1+ AND (+ p.visibility <> 'private'+ OR m.role IN ('owner', 'admin')+ OR EXISTS (+ SELECT 1 FROM project_member pm+ WHERE pm.project_id = p.id AND pm.user_id = ps.user_id+ )+ )+ AND NOT EXISTS (+ SELECT 1+ FROM issue_subscriber s+ JOIN ancestors a ON a.node_id = s.issue_id+ WHERE s.user_type = 'member' AND s.user_id = ps.user_id+ AND s.unsubscribed_at IS NOT NULL+ AND (a.depth = 0 OR s.opt_out_scope = 'subtree')+ )+ORDER BY ps.created_at, ps.user_id+`++type ListProjectSubscribersForIssueRow struct {+ UserID pgtype.UUID `json:"user_id"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}++// Members whose project subscription currently covers this issue: still in+// the workspace, able to see the project, and not opted out of this issue or+// of a tree containing it (the same rule as HasAncestorOptOut). Leaving an+// issue is the narrower, more recent intent, so the project never brings the+// member back. Both notification fanout and the issue's effective subscriber+// list read this, so the two cannot disagree.+func (q *Queries) ListProjectSubscribersForIssue(ctx context.Context, issueID pgtype.UUID) ([]ListProjectSubscribersForIssueRow, error) {+ rows, err := q.db.Query(ctx, listProjectSubscribersForIssue, issueID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListProjectSubscribersForIssueRow{}+ for rows.Next() {+ var i ListProjectSubscribersForIssueRow+ if err := rows.Scan(&i.UserID, &i.CreatedAt); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const removeProjectSubscriber = `-- name: RemoveProjectSubscriber :exec+DELETE FROM project_subscriber+WHERE project_id = $1+ AND workspace_id = $2+ AND user_id = $3+`++type RemoveProjectSubscriberParams struct {+ ProjectID pgtype.UUID `json:"project_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+}++func (q *Queries) RemoveProjectSubscriber(ctx context.Context, arg RemoveProjectSubscriberParams) error {+ _, err := q.db.Exec(ctx, removeProjectSubscriber, arg.ProjectID, arg.WorkspaceID, arg.UserID)+ return err+}diff --git a/server/pkg/db/generated/subscriber.sql.go b/server/pkg/db/generated/subscriber.sql.goindex dd6be0225b..b38a785e4d 100644--- a/server/pkg/db/generated/subscriber.sql.go+++ b/server/pkg/db/generated/subscriber.sql.go@@ -450,9 +450,25 @@ func (q *Queries) LockSubscriberWrites(ctx context.Context, arg LockSubscriberWr}const removeIssueSubscriber = `-- name: RemoveIssueSubscriber :exec-UPDATE issue_subscriber-SET unsubscribed_at = now(), opt_out_scope = 'issue'-WHERE issue_id = $1 AND user_type = $2 AND user_id = $3 AND unsubscribed_at IS NULL+WITH retired AS (+ UPDATE issue_subscriber+ SET unsubscribed_at = now(), opt_out_scope = 'issue'+ WHERE issue_subscriber.issue_id = $1+ AND issue_subscriber.user_type = $2+ AND issue_subscriber.user_id = $3+ AND issue_subscriber.unsubscribed_at IS NULL+ RETURNING issue_subscriber.issue_id+)+INSERT INTO issue_subscriber (issue_id, user_type, user_id, reason, unsubscribed_at, opt_out_scope)+SELECT i.id, 'member', ps.user_id, 'manual', now(), 'issue'+FROM issue i+JOIN project_subscriber ps+ ON ps.project_id = i.project_id AND ps.workspace_id = i.workspace_id+WHERE i.id = $1+ AND $2::text = 'member'+ AND ps.user_id = $3+ AND NOT EXISTS (SELECT 1 FROM retired)+ON CONFLICT (issue_id, user_type, user_id) DO NOTHING`type RemoveIssueSubscriberParams struct {@@ -465,6 +481,12 @@ type RemoveIssueSubscriberParams struct {// can tell "never subscribed" (no row) from "chose to leave" (row with// unsubscribed_at). scope='issue' keeps the opt-out from reaching descendants:// future children of this issue are still allowed to subscribe the user.+//+// A member watching the issue's project has no row to retire, yet still hears+// about the issue, so the opt-out is inserted for them. An existing tombstone+// is left as it is: a 'subtree' opt-out must not be narrowed to 'issue'.+// Members with neither a row nor a project subscription get nothing, so+// leaving an issue you never watched does not block later auto-subscribes.func (q *Queries) RemoveIssueSubscriber(ctx context.Context, arg RemoveIssueSubscriberParams) error {_, err := q.db.Exec(ctx, removeIssueSubscriber, arg.IssueID, arg.UserType, arg.UserID)return errdiff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex 2cc7e7a9c0..52e0b52993 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -644,6 +644,9 @@ deleted_profiles AS (),deleted_project_members AS (DELETE FROM project_member WHERE project_member.workspace_id = $1+),+deleted_project_subscribers AS (+ DELETE FROM project_subscriber WHERE project_subscriber.workspace_id = $1)DELETE FROM project WHERE project.workspace_id = $1`diff --git a/server/pkg/db/queries/inbox_archive.sql b/server/pkg/db/queries/inbox_archive.sqlindex 269fce10d7..e1f65ad715 100644--- a/server/pkg/db/queries/inbox_archive.sql+++ b/server/pkg/db/queries/inbox_archive.sql@@ -13,7 +13,7 @@ WITH base AS MATERIALIZED (WHEN i.type IN ('new_comment', 'reaction_added') THEN 'comment'WHEN i.type IN ('issue_assigned', 'unassigned', 'assignee_changed', 'issue_subscribed') THEN 'assign'WHEN i.type = 'review_requested' THEN 'review'- WHEN i.type IN ('status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'+ WHEN i.type IN ('issue_created', 'status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'WHEN i.type IN ('task_completed', 'task_failed', 'agent_blocked', 'agent_completed') THEN 'run'ELSE 'system'END AS type_group,@@ -126,7 +126,7 @@ WITH base AS MATERIALIZED (WHEN i.type IN ('new_comment', 'reaction_added') THEN 'comment'WHEN i.type IN ('issue_assigned', 'unassigned', 'assignee_changed', 'issue_subscribed') THEN 'assign'WHEN i.type = 'review_requested' THEN 'review'- WHEN i.type IN ('status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'+ WHEN i.type IN ('issue_created', 'status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'WHEN i.type IN ('task_completed', 'task_failed', 'agent_blocked', 'agent_completed') THEN 'run'ELSE 'system'END AS type_group,diff --git a/server/pkg/db/queries/project_subscriber.sql b/server/pkg/db/queries/project_subscriber.sqlnew file mode 100644index 0000000000..e7643b8f03--- /dev/null+++ b/server/pkg/db/queries/project_subscriber.sql@@ -0,0 +1,67 @@+-- name: AddProjectSubscriber :exec+-- Only a current workspace member can watch a project.+INSERT INTO project_subscriber (workspace_id, project_id, user_id)+SELECT m.workspace_id, sqlc.arg('project_id')::uuid, m.user_id+FROM member m+WHERE m.workspace_id = sqlc.arg('workspace_id') AND m.user_id = sqlc.arg('user_id')+ON CONFLICT (project_id, user_id) DO NOTHING;++-- name: RemoveProjectSubscriber :exec+DELETE FROM project_subscriber+WHERE project_id = sqlc.arg('project_id')+ AND workspace_id = sqlc.arg('workspace_id')+ AND user_id = sqlc.arg('user_id');++-- name: IsProjectSubscriber :one+SELECT EXISTS(+ SELECT 1 FROM project_subscriber+ WHERE project_id = sqlc.arg('project_id')+ AND workspace_id = sqlc.arg('workspace_id')+ AND user_id = sqlc.arg('user_id')+) AS subscribed;++-- name: ListProjectSubscribersForIssue :many+-- Members whose project subscription currently covers this issue: still in+-- the workspace, able to see the project, and not opted out of this issue or+-- of a tree containing it (the same rule as HasAncestorOptOut). Leaving an+-- issue is the narrower, more recent intent, so the project never brings the+-- member back. Both notification fanout and the issue's effective subscriber+-- list read this, so the two cannot disagree.+WITH RECURSIVE ancestors(node_id, parent_id, depth) AS (+ SELECT root.id, root.parent_issue_id, 0 FROM issue root WHERE root.id = sqlc.arg('issue_id')+ UNION ALL+ SELECT i.id, i.parent_issue_id, a.depth + 1 FROM issue i JOIN ancestors a ON i.id = a.parent_id+)+SELECT ps.user_id, ps.created_at+FROM issue target+JOIN project p ON p.id = target.project_id AND p.workspace_id = target.workspace_id+JOIN project_subscriber ps+ ON ps.project_id = p.id AND ps.workspace_id = p.workspace_id+JOIN member m ON m.workspace_id = ps.workspace_id AND m.user_id = ps.user_id+WHERE target.id = sqlc.arg('issue_id')+ AND (+ p.visibility <> 'private'+ OR m.role IN ('owner', 'admin')+ OR EXISTS (+ SELECT 1 FROM project_member pm+ WHERE pm.project_id = p.id AND pm.user_id = ps.user_id+ )+ )+ AND NOT EXISTS (+ SELECT 1+ FROM issue_subscriber s+ JOIN ancestors a ON a.node_id = s.issue_id+ WHERE s.user_type = 'member' AND s.user_id = ps.user_id+ AND s.unsubscribed_at IS NOT NULL+ AND (a.depth = 0 OR s.opt_out_scope = 'subtree')+ )+ORDER BY ps.created_at, ps.user_id;++-- name: DeleteProjectSubscribersByProject :exec+DELETE FROM project_subscriber+WHERE project_id = sqlc.arg('project_id') AND workspace_id = sqlc.arg('workspace_id');++-- name: DeleteProjectSubscribersByUser :exec+-- A member leaving the workspace stops watching every project in it.+DELETE FROM project_subscriber+WHERE workspace_id = sqlc.arg('workspace_id') AND user_id = sqlc.arg('user_id');diff --git a/server/pkg/db/queries/subscriber.sql b/server/pkg/db/queries/subscriber.sqlindex 85ccfd1e77..7ad4c122ea 100644--- a/server/pkg/db/queries/subscriber.sql+++ b/server/pkg/db/queries/subscriber.sql@@ -160,9 +160,31 @@ DO UPDATE SET unsubscribed_at = NULL, opt_out_scope = NULL, reason = EXCLUDED.re-- can tell "never subscribed" (no row) from "chose to leave" (row with-- unsubscribed_at). scope='issue' keeps the opt-out from reaching descendants:-- future children of this issue are still allowed to subscribe the user.-UPDATE issue_subscriber-SET unsubscribed_at = now(), opt_out_scope = 'issue'-WHERE issue_id = $1 AND user_type = $2 AND user_id = $3 AND unsubscribed_at IS NULL;+--+-- A member watching the issue's project has no row to retire, yet still hears+-- about the issue, so the opt-out is inserted for them. An existing tombstone+-- is left as it is: a 'subtree' opt-out must not be narrowed to 'issue'.+-- Members with neither a row nor a project subscription get nothing, so+-- leaving an issue you never watched does not block later auto-subscribes.+WITH retired AS (+ UPDATE issue_subscriber+ SET unsubscribed_at = now(), opt_out_scope = 'issue'+ WHERE issue_subscriber.issue_id = sqlc.arg(issue_id)+ AND issue_subscriber.user_type = sqlc.arg(user_type)+ AND issue_subscriber.user_id = sqlc.arg(user_id)+ AND issue_subscriber.unsubscribed_at IS NULL+ RETURNING issue_subscriber.issue_id+)+INSERT INTO issue_subscriber (issue_id, user_type, user_id, reason, unsubscribed_at, opt_out_scope)+SELECT i.id, 'member', ps.user_id, 'manual', now(), 'issue'+FROM issue i+JOIN project_subscriber ps+ ON ps.project_id = i.project_id AND ps.workspace_id = i.workspace_id+WHERE i.id = sqlc.arg(issue_id)+ AND sqlc.arg(user_type)::text = 'member'+ AND ps.user_id = sqlc.arg(user_id)+ AND NOT EXISTS (SELECT 1 FROM retired)+ON CONFLICT (issue_id, user_type, user_id) DO NOTHING;-- name: UnsubscribeFromIssueSubtree :many-- Leave an issue AND every descendant in one action. An agent-built tree isdiff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex e57a626a39..8eac4ad6ee 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -729,6 +729,9 @@ deleted_profiles AS (),deleted_project_members AS (DELETE FROM project_member WHERE project_member.workspace_id = $1+),+deleted_project_subscribers AS (+ DELETE FROM project_subscriber WHERE project_subscriber.workspace_id = $1)DELETE FROM project WHERE project.workspace_id = $1;