Skip to content

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

Go

feat(notifications): key updates only for other people's issues (MUL-9343) (#10688)

Jiayuan Zhang7f9321031888
diff --git a/apps/docs/content/docs/inbox.fr.mdx b/apps/docs/content/docs/inbox.fr.mdx
index 652798f14e..65c1e64a46 100644
--- a/apps/docs/content/docs/inbox.fr.mdx
+++ b/apps/docs/content/docs/inbox.fr.mdx
@@ -21,7 +21,7 @@ Sur téléphone, le panneau Travail se trouve dans le tiroir. Sa section Boîte
Les notifications courantes incluent :
- une tâche vous est assignée, ou vous est retirée ;
-- une tâche à laquelle vous êtes abonné reçoit un nouveau commentaire, ou son assigné, son statut, sa priorité ou ses dates changent ;
+- une tâche à laquelle vous êtes abonné reçoit un nouveau commentaire, ou son assigné, son statut, sa priorité ou ses dates changent (sur les tâches des autres, seulement les mises à jour clés par défaut ; voir plus bas) ;
- quelqu'un vous @mentionne dans la description ou un commentaire d'une tâche ;
- une tâche ou un commentaire que vous avez créé reçoit une réaction ;
- une exécution d'agent échoue sur une tâche à laquelle vous êtes abonné ;
@@ -47,6 +47,12 @@ Changer l'assigné ne supprime pas les abonnements existants. Abonnez-vous ou d
Lorsque le statut d'une sous-tâche change, les abonnés de la tâche parente sont également notifiés. Les commentaires, la priorité et les changements de dates d'une sous-tâche ne remontent pas à la tâche parente.
</Callout>
+## Tâches des autres
+
+Sur une tâche assignée à quelqu'un d'autre ou à son agent, un abonnement obtenu parce que vous l'avez créée, commentée ou y avez été mentionné n'apporte par défaut que les mises à jour clés : les @mentions, les réponses dans les fils auxquels vous avez participé et les statuts qui demandent une personne, comme `in_review`, `blocked` ou `done`. Les commentaires courants et les autres changements restent sur la tâche. Les tâches auxquelles vous vous êtes abonné vous-même, celles que vous suivez par leur projet et celles assignées à vous ou à vos agents apportent toujours toute l'activité.
+
+La page de la tâche signale un tel abonnement par **Mises à jour clés**. Son menu propose **Recevoir toute l'activité**, qui en fait un abonnement explicite à cette tâche ; il n'est ensuite plus possible de revenir aux mises à jour clés pour cette tâche, seulement de se désabonner. **Modifier la valeur par défaut** ouvre **Paramètres → Notifications**, où **Tâches des autres**, en tête de **Tâches que vous suivez**, fait passer toutes ces tâches à **Toute l'activité**.
+
## Les agents n'utilisent pas la boîte de réception
La boîte de réception est réservée aux membres de l'espace de travail. Même lorsqu'un agent est l'assigné ou un abonné, il ne lit jamais les notifications de la boîte de réception.
diff --git a/apps/docs/content/docs/inbox.ja.mdx b/apps/docs/content/docs/inbox.ja.mdx
index 1364c5309f..4dccc97abd 100644
--- a/apps/docs/content/docs/inbox.ja.mdx
+++ b/apps/docs/content/docs/inbox.ja.mdx
@@ -21,7 +21,7 @@ import { InboxDemo } from "@/components/demos/inbox-demo";
主な通知は次のとおりです。
- タスクがあなたに割り当てられた、またはあなたから外された
-- 購読中のタスクに新しいコメントが付いた、または担当者・ステータス・優先度・日付が変わった
+- 購読中のタスクに新しいコメントが付いた、または担当者・ステータス・優先度・日付が変わった(他の人のタスクは既定で重要な更新のみ。後述)
- タスクの説明やコメントで誰かがあなたを @メンションした
- あなたが作成したタスクやコメントにリアクションが付いた
- 購読中のタスクでエージェントの実行が失敗した
@@ -47,6 +47,12 @@ import { InboxDemo } from "@/components/demos/inbox-demo";
サブタスクのステータスが変わると、親タスクの購読者にも通知されます。サブタスクのコメント、優先度、日付の変更は親タスクには伝わりません。
</Callout>
+## 他の人のタスク
+
+他の人やその人のエージェントに割り当てられたタスクでは、作成・コメント・メンションによって自動的に購読した場合、既定で重要な更新だけが届きます。あなたへの @メンション、参加したスレッドへの返信、そして `in_review`・`blocked`・`done` など人の確認が必要なステータスです。通常のコメントやその他の変更はタスクに残ります。自分で購読したタスク、プロジェクト経由で購読しているタスク、あなたやあなたのエージェントに割り当てられたタスクには、引き続きすべてのアクティビティが届きます。
+
+タスクのページでは、こうした購読に **重要な更新のみ** と表示されます。メニューの **すべてのアクティビティを受け取る** を選ぶと、このタスクの明示的な購読に変わります。その後このタスクを重要な更新のみに戻す方法はなく、購読解除だけが可能です。**デフォルトを変更** は **設定 → 通知** を開きます。**購読中のタスク** の先頭にある **他の人のタスク** を **すべてのアクティビティ** にすると、こうしたタスクすべてにアクティビティが届くようになります。
+
## エージェントはインボックスを使わない
インボックスはワークスペースメンバー専用です。エージェントが担当者や購読者であっても、インボックスの通知を読むことはありません。
diff --git a/apps/docs/content/docs/inbox.ko.mdx b/apps/docs/content/docs/inbox.ko.mdx
index 2d5f79ab73..fff44712a5 100644
--- a/apps/docs/content/docs/inbox.ko.mdx
+++ b/apps/docs/content/docs/inbox.ko.mdx
@@ -21,7 +21,7 @@ import { InboxDemo } from "@/components/demos/inbox-demo";
일반적인 알림은 다음과 같습니다.
- 태스크가 나에게 할당되거나 내 할당에서 해제됨
-- 구독한 태스크에 새 댓글이 달리거나 담당자, 상태, 우선순위, 날짜가 변경됨
+- 구독한 태스크에 새 댓글이 달리거나 담당자, 상태, 우선순위, 날짜가 변경됨(다른 사람의 태스크는 기본적으로 주요 업데이트만, 아래 참고)
- 누군가 태스크 설명이나 댓글에서 나를 @멘션함
- 내가 만든 태스크나 댓글에 이모지 반응이 추가됨
- 구독한 태스크에서 에이전트의 실행이 실패함
@@ -47,6 +47,12 @@ import { InboxDemo } from "@/components/demos/inbox-demo";
하위 태스크의 상태가 변경되면 상위 태스크 구독자에게도 알림이 갑니다. 하위 태스크의 댓글, 우선순위, 날짜 변경은 상위 태스크로 전달되지 않습니다.
</Callout>
+## 다른 사람의 태스크
+
+다른 사람이나 그 사람의 에이전트에게 배정된 태스크에서, 만들거나 댓글을 달거나 멘션되어 자동으로 생긴 구독은 기본적으로 주요 업데이트만 전달합니다. 나를 향한 @멘션, 참여한 스레드의 답글, 그리고 `in_review`, `blocked`, `done`처럼 사람이 봐야 하는 상태입니다. 일반 댓글과 그 밖의 변경은 태스크에 남습니다. 직접 구독한 태스크, 프로젝트를 통해 구독한 태스크, 나 또는 내 에이전트에게 배정된 태스크는 계속 모든 활동을 받습니다.
+
+태스크 페이지는 이런 구독에 **주요 업데이트만**이라고 표시합니다. 메뉴에서 **모든 활동 받기**를 고르면 이 태스크에 대한 직접 구독으로 바뀌며, 이후 이 태스크를 주요 업데이트만으로 되돌릴 방법은 없고 구독 취소만 할 수 있습니다. **기본값 변경**은 **설정 → 알림**을 열며, **구독 중인 태스크** 맨 위의 **다른 사람의 태스크**를 **모든 활동**으로 바꾸면 이런 태스크 전부가 모든 활동을 받습니다.
+
## 에이전트는 인박스를 사용하지 않습니다
인박스는 워크스페이스 멤버만 사용합니다. 에이전트가 담당자나 구독자여도 인박스 알림을 읽지 않습니다.
diff --git a/apps/docs/content/docs/inbox.mdx b/apps/docs/content/docs/inbox.mdx
index f18ed84294..a0daf04c07 100644
--- a/apps/docs/content/docs/inbox.mdx
+++ b/apps/docs/content/docs/inbox.mdx
@@ -21,7 +21,7 @@ On a phone, the Work panel sits in the drawer. Its Inbox section ends with **All
Common notifications include:
- an issue is assigned to you, or moved away from you;
-- an issue you subscribe to gets a new comment, or its assignee, status, priority, or dates change;
+- an issue you subscribe to gets a new comment, or its assignee, status, priority, or dates change (on other people's issues, only key updates by default; see below);
- someone @-mentions you in an issue description or comment;
- an issue or comment you created gets a reaction;
- an agent run fails on an issue you subscribe to;
@@ -47,6 +47,12 @@ Changing the assignee does not remove existing subscriptions. Subscribe or unsub
When a sub-issue's status changes, subscribers of the parent issue are notified as well. Sub-issue comments, priority, and date changes do not bubble up to the parent.
</Callout>
+## Other people's issues
+
+On an issue assigned to someone else or to their agent, a subscription you picked up by creating, commenting on, or being mentioned in it brings only key updates by default: @-mentions, replies in threads you took part in, and statuses that need a person, such as `in_review`, `blocked`, or `done`. Routine comments and other changes stay on the issue. Issues you subscribed to yourself, issues you follow through their project, and issues assigned to you or your agents still bring all activity.
+
+The issue page marks such a subscription **Key updates only**. Its menu offers **Get all activity**, which turns it into an explicit subscription to this issue; there's no way back to key updates for that issue afterwards, only unsubscribing. **Change the default** opens **Settings → Notifications**, where **Other people's issues**, at the top of **Issues you subscribe to**, switches all such issues to **All activity**.
+
## Agents don't use the inbox
The inbox is only for workspace members. Even when an agent is the assignee or a subscriber, it never reads inbox notifications.
diff --git a/apps/docs/content/docs/inbox.zh-Hant.mdx b/apps/docs/content/docs/inbox.zh-Hant.mdx
index 8df2c66430..9878c06f20 100644
--- a/apps/docs/content/docs/inbox.zh-Hant.mdx
+++ b/apps/docs/content/docs/inbox.zh-Hant.mdx
@@ -21,7 +21,7 @@ import { InboxDemo } from "@/components/demos/inbox-demo";
常見通知包括:
- 任務分配給你,或從你名下移走;
-- 你訂閱的任務出現新評論,或負責人、狀態、優先順序和日期發生變化;
+- 你訂閱的任務出現新評論,或負責人、狀態、優先順序和日期發生變化(別人的任務預設只推送關鍵更新,見下文);
- 有人在任務描述或評論中 @你;
- 你建立的任務或評論收到表情回應;
- 你訂閱的任務中,AI 代理執行失敗;
@@ -47,6 +47,12 @@ import { InboxDemo } from "@/components/demos/inbox-demo";
子任務的狀態發生變化時,也會通知父任務的訂閱者。子任務的評論、優先順序和日期變化不會向父任務冒泡。
</Callout>
+## 別人的任務
+
+任務指派給別人或別人的 AI 代理時,你因為建立、評論或被 @ 而自動產生的訂閱,預設只推送關鍵更新:@你、回覆你參與的討論,以及 `in_review`、`blocked`、`done` 等需要人來看的狀態。日常評論和其他變化留在任務裡。你手動訂閱的任務、透過專案訂閱的任務,以及指派給你或你的 AI 代理的任務,仍會收到全部動態。
+
+任務頁面會把這類訂閱標為**僅關鍵更新**。點開後選**接收全部動態**,會把它變為對這個任務的手動訂閱;之後這個任務無法再退回僅關鍵更新,只能取消訂閱。**修改預設設定**會打開**設定 → 通知**,把**你訂閱的任務**分組頂部的**別人的任務**改為**全部動態**,所有這類任務都會推送全部動態。
+
## AI 代理不使用收件箱
收件箱只面向工作區成員。即使 AI 代理是負責人或訂閱者,它也不會讀取收件箱通知。
diff --git a/apps/docs/content/docs/inbox.zh.mdx b/apps/docs/content/docs/inbox.zh.mdx
index adec6e5d9d..790dcd5b6b 100644
--- a/apps/docs/content/docs/inbox.zh.mdx
+++ b/apps/docs/content/docs/inbox.zh.mdx
@@ -21,7 +21,7 @@ import { InboxDemo } from "@/components/demos/inbox-demo";
常见通知包括:
- 任务分配给你,或从你名下移走;
-- 你订阅的任务出现新评论,或负责人、状态、优先级和日期发生变化;
+- 你订阅的任务出现新评论,或负责人、状态、优先级和日期发生变化(别人的任务默认只推送关键更新,见下文);
- 有人在任务描述或评论中 @你;
- 你创建的任务或评论收到表情回应;
- 你订阅的任务中,智能体运行失败;
@@ -47,6 +47,12 @@ import { InboxDemo } from "@/components/demos/inbox-demo";
子任务的状态发生变化时,也会通知父任务的订阅者。子任务的评论、优先级和日期变化不会向父任务冒泡。
</Callout>
+## 别人的任务
+
+任务分配给别人或别人的智能体时,你因为创建、评论或被 @ 而自动产生的订阅,默认只推送关键更新:@你、回复你参与的讨论,以及 `in_review`、`blocked`、`done` 等需要人来看的状态。日常评论和其他变化留在任务里。你手动订阅的任务、通过项目订阅的任务,以及分配给你或你的智能体的任务,仍会收到全部动态。
+
+任务页面会把这类订阅标为**仅关键更新**。点开后选**接收全部动态**,会把它变为对这个任务的手动订阅;之后这个任务无法再退回仅关键更新,只能取消订阅。**修改默认设置**会打开**设置 → 通知**,把**你订阅的任务**分组顶部的**别人的任务**改为**全部动态**,所有这类任务都会推送全部动态。
+
## 智能体不使用收件箱
收件箱只面向工作区成员。即使智能体是负责人或订阅者,它也不会读取收件箱通知。
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index e893639566..f66ab456d5 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -1221,12 +1221,18 @@ export function useToggleIssueSubscriber(issueId: string) {
qc.setQueryData<IssueSubscriber[]>(
issueKeys.subscribers(issueId),
(old) => {
+ // An explicit subscribe rewrites an existing row's reason to
+ // manual, which lifts it out of the delegated and bystander tiers.
if (
old?.some(
(s) => s.user_id === userId && s.user_type === userType,
)
)
- return old;
+ return old.map((s) =>
+ s.user_id === userId && s.user_type === userType
+ ? { ...s, reason: "manual" as const }
+ : s,
+ );
return [...(old ?? []), temp];
},
);
diff --git a/packages/core/notification-preferences/bystander.test.ts b/packages/core/notification-preferences/bystander.test.ts
new file mode 100644
index 0000000000..083d5a67e5
--- /dev/null
+++ b/packages/core/notification-preferences/bystander.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+import { receivesKeyUpdatesOnly } from "./bystander";
+
+const me = "user-me";
+const agents = [
+ { id: "agent-mine", owner_id: me },
+ { id: "agent-theirs", owner_id: "user-other" },
+];
+
+function check(
+ reason: Parameters<typeof receivesKeyUpdatesOnly>[0]["reason"],
+ issue: Parameters<typeof receivesKeyUpdatesOnly>[0]["issue"],
+ preferences = {},
+) {
+ return receivesKeyUpdatesOnly({ reason, issue, userId: me, agents, preferences });
+}
+
+describe("receivesKeyUpdatesOnly", () => {
+ it("narrows a passive subscription to someone else's issue", () => {
+ expect(check("commenter", { assignee_type: "member", assignee_id: "user-other" })).toBe(true);
+ expect(check("creator", { assignee_type: "agent", assignee_id: "agent-theirs" })).toBe(true);
+ expect(check("mentioned", { assignee_type: "squad", assignee_id: "squad-1" })).toBe(true);
+ });
+
+ it("keeps full delivery on the member's own issue or an unassigned one", () => {
+ expect(check("commenter", { assignee_type: "member", assignee_id: me })).toBe(false);
+ expect(check("creator", { assignee_type: "agent", assignee_id: "agent-mine" })).toBe(false);
+ expect(check("creator", { assignee_type: null, assignee_id: null })).toBe(false);
+ });
+
+ it("keeps full delivery for explicit subscriptions and the all preference", () => {
+ const theirs = { assignee_type: "member", assignee_id: "user-other" } as const;
+ expect(check("manual", theirs)).toBe(false);
+ expect(check("autopilot", theirs)).toBe(false);
+ expect(check("delegated", theirs)).toBe(false);
+ expect(check("project", theirs)).toBe(false);
+ expect(check("commenter", theirs, { others_issues: "all" })).toBe(false);
+ });
+
+ it("keeps full delivery when the member also watches the project", () => {
+ expect(
+ receivesKeyUpdatesOnly({
+ reason: "commenter",
+ projectCovered: true,
+ issue: { assignee_type: "member", assignee_id: "user-other" },
+ userId: me,
+ agents,
+ preferences: {},
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/core/notification-preferences/bystander.ts b/packages/core/notification-preferences/bystander.ts
new file mode 100644
index 0000000000..9e7f605ad1
--- /dev/null
+++ b/packages/core/notification-preferences/bystander.ts
@@ -0,0 +1,54 @@
+import type {
+ Agent,
+ IssueAssigneeType,
+ IssueSubscriber,
+ NotificationPreferences,
+} from "../types";
+import { notificationPreferenceValue } from "./patch";
+
+/**
+ * Subscriptions picked up as a side effect of acting on an issue. manual and
+ * autopilot are explicit and keep every event; delegated has its own tier.
+ */
+const BYSTANDER_REASONS: ReadonlySet<IssueSubscriber["reason"]> = new Set([
+ "creator",
+ "assignee",
+ "commenter",
+ "mentioned",
+]);
+
+/**
+ * Whether the server delivers only key updates of this issue to this member:
+ * a passive subscription, on an issue assigned to someone other than them or
+ * an agent they own, with "Other people's issues" left at key updates, and
+ * no subscription to the issue's project (that path delivers every event).
+ * Mirrors deliverToBystander in server/cmd/server/notification_listeners.go.
+ */
+export function receivesKeyUpdatesOnly({
+ reason,
+ projectCovered = false,
+ issue,
+ userId,
+ agents,
+ preferences,
+}: {
+ reason: IssueSubscriber["reason"] | undefined;
+ projectCovered?: boolean;
+ issue: { assignee_type?: IssueAssigneeType | null; assignee_id?: string | null };
+ userId: string | null | undefined;
+ agents: readonly Pick<Agent, "id" | "owner_id">[];
+ preferences: NotificationPreferences;
+}): boolean {
+ if (!userId || !reason || !BYSTANDER_REASONS.has(reason)) return false;
+ if (projectCovered) return false;
+ if (notificationPreferenceValue(preferences, "others_issues") === "all") return false;
+ if (!issue.assignee_id) return false;
+ switch (issue.assignee_type) {
+ case "member":
+ return issue.assignee_id !== userId;
+ case "agent":
+ return !agents.some((a) => a.id === issue.assignee_id && a.owner_id === userId);
+ default:
+ return true;
+ }
+}
diff --git a/packages/core/notification-preferences/index.ts b/packages/core/notification-preferences/index.ts
index 4b3efba544..87686c0bd9 100644
--- a/packages/core/notification-preferences/index.ts
+++ b/packages/core/notification-preferences/index.ts
@@ -1,3 +1,4 @@
export * from "./queries";
export * from "./mutations";
export * from "./patch";
+export * from "./bystander";
diff --git a/packages/core/notification-preferences/patch.test.ts b/packages/core/notification-preferences/patch.test.ts
index e1916cc19b..9d8ef4c614 100644
--- a/packages/core/notification-preferences/patch.test.ts
+++ b/packages/core/notification-preferences/patch.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
applyNotificationPreferencePatch,
deriveNotificationPreferencePatch,
+ notificationPreferenceValue,
rollbackNotificationPreferencePatch,
} from "./patch";
@@ -66,6 +67,25 @@ describe("notification preference patches", () => {
).toEqual({ comments: "muted", mentions: "muted" });
});
+ it("treats a missing others_issues as key updates, not all", () => {
+ expect(notificationPreferenceValue({}, "others_issues")).toBe("key_updates");
+ expect(
+ deriveNotificationPreferencePatch({}, { others_issues: "all" }),
+ ).toEqual({ others_issues: "all" });
+ expect(
+ deriveNotificationPreferencePatch({ others_issues: "all" }, {}),
+ ).toEqual({ others_issues: "key_updates" });
+ expect(
+ applyNotificationPreferencePatch({ comments: "muted" }, { others_issues: "all" }),
+ ).toEqual({ comments: "muted", others_issues: "all" });
+ expect(
+ applyNotificationPreferencePatch({ others_issues: "all" }, { others_issues: "key_updates" }),
+ ).toEqual({});
+ expect(
+ rollbackNotificationPreferencePatch({ others_issues: "all" }, { others_issues: "all" }, {}),
+ ).toEqual({});
+ });
+
it("does not roll back a key that a later mutation already changed", () => {
expect(
rollbackNotificationPreferencePatch(
diff --git a/packages/core/notification-preferences/patch.ts b/packages/core/notification-preferences/patch.ts
index e8698afc7a..40d0b2a683 100644
--- a/packages/core/notification-preferences/patch.ts
+++ b/packages/core/notification-preferences/patch.ts
@@ -1,64 +1,84 @@
-import type {
- NotificationGroupKey,
- NotificationGroupValue,
- NotificationPreferences,
-} from "../types";
+import type { NotificationPreferences } from "../types";
-const NOTIFICATION_GROUP_KEYS: readonly NotificationGroupKey[] = [
- "assignments",
- "status_changes",
- "comments",
- "chat_replies",
- "mentions",
- "reactions",
- "updates",
- "new_issues",
- "agent_activity",
- "system_notifications",
- "auto_archive_completed",
-];
+type PreferenceKey = keyof NotificationPreferences;
+type PreferenceValues = Record<PreferenceKey, string | undefined>;
-function preferenceValue(
+/**
+ * The value each key means when it is missing. Every key the settings UI can
+ * write must be listed, or its change is silently never sent.
+ */
+const PREFERENCE_DEFAULTS: { [K in PreferenceKey]-?: NonNullable<NotificationPreferences[K]> } = {
+ assignments: "all",
+ status_changes: "all",
+ comments: "all",
+ chat_replies: "all",
+ mentions: "all",
+ reactions: "all",
+ updates: "all",
+ new_issues: "all",
+ agent_activity: "all",
+ system_notifications: "all",
+ auto_archive_completed: "all",
+ others_issues: "key_updates",
+};
+
+const PREFERENCE_KEYS = Object.keys(PREFERENCE_DEFAULTS) as PreferenceKey[];
+
+/** The effective value of a preference, filling in its default. */
+export function notificationPreferenceValue<K extends PreferenceKey>(
preferences: NotificationPreferences,
- key: NotificationGroupKey,
-): NotificationGroupValue {
- return preferences[key] ?? "all";
+ key: K,
+): NonNullable<NotificationPreferences[K]> {
+ return (preferences[key] ?? PREFERENCE_DEFAULTS[key]) as NonNullable<NotificationPreferences[K]>;
+}
+
+/** Set a value on a copy, dropping the key when it is the default. */
+function withValue(
+ preferences: NotificationPreferences,
+ key: PreferenceKey,
+ value: string,
+): NotificationPreferences {
+ const next = { ...preferences } as PreferenceValues;
+ if (value === PREFERENCE_DEFAULTS[key]) {
+ delete next[key];
+ } else {
+ next[key] = value;
+ }
+ return next as NotificationPreferences;
}
/**
* Convert the full preference object produced by the settings UI into the
- * smallest atomic patch. Missing keys mean the default value ("all").
+ * smallest atomic patch. Missing keys mean their default value.
*/
export function deriveNotificationPreferencePatch(
previous: NotificationPreferences,
next: NotificationPreferences,
): NotificationPreferences {
- const patch: NotificationPreferences = {};
+ const patch = {} as PreferenceValues;
- for (const key of NOTIFICATION_GROUP_KEYS) {
- const previousValue = preferenceValue(previous, key);
- const nextValue = preferenceValue(next, key);
+ for (const key of PREFERENCE_KEYS) {
+ const previousValue = notificationPreferenceValue(previous, key);
+ const nextValue = notificationPreferenceValue(next, key);
if (previousValue !== nextValue) {
patch[key] = nextValue;
}
}
- return patch;
+ return patch as NotificationPreferences;
}
-/** Apply a preference patch while keeping default "all" values sparse. */
+/** Apply a preference patch while keeping default values sparse. */
export function applyNotificationPreferencePatch(
current: NotificationPreferences,
patch: NotificationPreferences,
): NotificationPreferences {
- const next = { ...current };
+ let next = { ...current };
- for (const key of NOTIFICATION_GROUP_KEYS) {
+ for (const key of PREFERENCE_KEYS) {
const value = patch[key];
- if (value === "muted") {
- next[key] = value;
- } else if (value === "all") {
- delete next[key];
+ if (value !== undefined) {
+ next = withValue(next, key, value);
}
}
@@ -74,23 +94,17 @@ export function rollbackNotificationPreferencePatch(
patch: NotificationPreferences,
previous: NotificationPreferences,
): NotificationPreferences {
- const next = { ...current };
+ let next = { ...current };
- for (const key of NOTIFICATION_GROUP_KEYS) {
+ for (const key of PREFERENCE_KEYS) {
const patchedValue = patch[key];
if (
patchedValue === undefined ||
- preferenceValue(current, key) !== patchedValue
+ notificationPreferenceValue(current, key) !== patchedValue
) {
continue;
}
-
- const previousValue = preferenceValue(previous, key);
- if (previousValue === "all") {
- delete next[key];
- } else {
- next[key] = previousValue;
- }
+ next = withValue(next, key, notificationPreferenceValue(previous, key));
}
return next;
diff --git a/packages/core/package.json b/packages/core/package.json
index 1517941556..ea6711d5b8 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -81,6 +81,7 @@
"./notification-preferences/queries": "./notification-preferences/queries.ts",
"./notification-preferences/mutations": "./notification-preferences/mutations.ts",
"./notification-preferences/patch": "./notification-preferences/patch.ts",
+ "./notification-preferences/bystander": "./notification-preferences/bystander.ts",
"./chat": "./chat/index.ts",
"./chat/queries": "./chat/queries.ts",
"./chat/mutations": "./chat/mutations.ts",
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index f011eb983d..d74c8d589b 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -143,7 +143,7 @@ export type {
PluginTokenIssue,
} from "./plugin";
export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread, ArchivedInboxPage, ArchivedInboxFacets, SnoozedInboxIssue } from "./inbox";
-export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";
+export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse, OthersIssuesValue } from "./notification-preference";
export type { Comment, CommentType, CommentAuthorType, CommentSupplementReceipt, CommentSupplementStatus, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, CommentTriggerOutcome, CommentTriggerStatus, Reaction } from "./comment";
export type { Label, LabelResourceType, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse, ResourceLabelsResponse } from "./label";
export type { IssueProperty, IssuePropertyType, ScalarIssuePropertyType, ListIssuePropertyType, IssuePropertyOption, IssuePropertyConfig, IssuePropertyValue, IssuePropertyValues, CreatePropertyRequest, UpdatePropertyRequest, ListPropertiesResponse, IssuePropertiesResponse, IssuePropertyActorKind, IssuePropertyActorRef, PropertyFilterOp, PropertyOperatorFilter, PropertyFilterValue } from "./property";
diff --git a/packages/core/types/notification-preference.ts b/packages/core/types/notification-preference.ts
index 3e2e4866df..c5a5a79ed6 100644
--- a/packages/core/types/notification-preference.ts
+++ b/packages/core/types/notification-preference.ts
@@ -13,7 +13,16 @@ export type NotificationGroupKey =
export type NotificationGroupValue = "all" | "muted";
-export type NotificationPreferences = Partial<Record<NotificationGroupKey, NotificationGroupValue>>;
+/**
+ * How much of someone else's issue reaches you when you are only passively
+ * subscribed (you filed it, commented, or were mentioned). Missing means
+ * "key_updates": mentions, replies in your threads and handoffs.
+ */
+export type OthersIssuesValue = "all" | "key_updates";
+
+export type NotificationPreferences = Partial<Record<NotificationGroupKey, NotificationGroupValue>> & {
+ others_issues?: OthersIssuesValue;
+};
export interface NotificationPreferenceResponse {
workspace_id: string;
diff --git a/packages/core/types/subscriber.ts b/packages/core/types/subscriber.ts
index 35c9927d58..2907963c82 100644
--- a/packages/core/types/subscriber.ts
+++ b/packages/core/types/subscriber.ts
@@ -28,4 +28,10 @@ export interface IssueSubscriber {
user_id: string;
reason: IssueSubscriberReason;
created_at: string;
+ /**
+ * A direct row whose member also subscribes to the issue's project. The
+ * project delivers every event, so the direct reason does not narrow what
+ * reaches them.
+ */
+ project_covered?: boolean;
}
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 6dae2b169a..b4fc22d609 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -69,6 +69,7 @@ import {
DropdownMenuItem,
} from "@multica/ui/components/ui/dropdown-menu";
import { Popover, PopoverTrigger, PopoverContent } from "@multica/ui/components/ui/popover";
+import { KeyUpdatesSubscriptionBadge } from "./key-updates-subscription-badge";
import { Checkbox } from "@multica/ui/components/ui/checkbox";
import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } from "@multica/ui/components/ui/command";
import { AvatarGroup, AvatarGroupCount } from "@multica/ui/components/ui/avatar";
@@ -2421,9 +2422,9 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
} = useIssueReactions(id, user?.id);
const {
- subscribers, isSubscribed, subscriptionReason, subscriptionKnown,
+ subscribers, isSubscribed, subscriptionReason, subscriptionProjectCovered, subscriptionKnown,
togglePending, subtreePending,
- toggleSubscribe: handleToggleSubscribe, toggleSubscriber,
+ toggleSubscribe: handleToggleSubscribe, toggleSubscriber, followAllActivity,
unsubscribeFromSubtree: handleUnsubscribeSubtree,
} = useIssueSubscribers(id, user?.id);
@@ -4096,6 +4097,16 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
</TooltipContent>
</Tooltip>
)}
+ {isSubscribed && (
+ <KeyUpdatesSubscriptionBadge
+ issue={issue}
+ userId={user?.id}
+ reason={subscriptionReason}
+ projectCovered={subscriptionProjectCovered}
+ pending={togglePending}
+ onFollowAll={followAllActivity}
+ />
+ )}
{/* Inherited from the project: say so, and that leaving
here only covers this issue, so Unsubscribe is not read as
leaving the whole project. */}
diff --git a/packages/views/issues/components/key-updates-subscription-badge.test.tsx b/packages/views/issues/components/key-updates-subscription-badge.test.tsx
new file mode 100644
index 0000000000..1b4bf2be3c
--- /dev/null
+++ b/packages/views/issues/components/key-updates-subscription-badge.test.tsx
@@ -0,0 +1,108 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { I18nProvider } from "@multica/core/i18n/react";
+import { notificationPreferenceKeys } from "@multica/core/notification-preferences/queries";
+import { agentListOptions } from "@multica/core/workspace/queries";
+import type { Agent } from "@multica/core/types";
+import enIssues from "../../locales/en/issues.json";
+import { KeyUpdatesSubscriptionBadge } from "./key-updates-subscription-badge";
+
+const push = vi.fn();
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-a" }));
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({ settings: () => "/acme/settings" }),
+}));
+vi.mock("../../navigation", () => ({ useNavigation: () => ({ push }) }));
+
+afterEach(() => {
+ cleanup();
+ push.mockReset();
+});
+
+const me = "user-me";
+
+function renderBadge({
+ assignee,
+ reason = "commenter",
+ projectCovered = false,
+ preferences = {},
+ onFollowAll = vi.fn(),
+}: {
+ assignee: { assignee_type: "member" | "agent" | null; assignee_id: string | null };
+ reason?: "commenter" | "manual" | "creator";
+ projectCovered?: boolean;
+ preferences?: Record<string, string>;
+ onFollowAll?: () => void;
+}) {
+ const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } });
+ qc.setQueryData(notificationPreferenceKeys.all("ws-a"), { workspace_id: "ws-a", preferences });
+ qc.setQueryData(agentListOptions("ws-a").queryKey, [{ id: "agent-mine", owner_id: me } as Agent]);
+ render(
+ <QueryClientProvider client={qc}>
+ <I18nProvider locale="en" resources={{ en: { issues: enIssues } }}>
+ <KeyUpdatesSubscriptionBadge
+ issue={assignee}
+ userId={me}
+ reason={reason}
+ projectCovered={projectCovered}
+ pending={false}
+ onFollowAll={onFollowAll}
+ />
+ </I18nProvider>
+ </QueryClientProvider>,
+ );
+}
+
+describe("KeyUpdatesSubscriptionBadge", () => {
+ it("offers all activity on someone else's issue", async () => {
+ const onFollowAll = vi.fn();
+ renderBadge({ assignee: { assignee_type: "member", assignee_id: "user-other" }, onFollowAll });
+ fireEvent.click(screen.getByRole("button", { name: "Key updates only" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Get all activity" }));
+ expect(onFollowAll).toHaveBeenCalledOnce();
+ });
+
+ it("links to the default in settings", async () => {
+ renderBadge({ assignee: { assignee_type: "member", assignee_id: "user-other" } });
+ fireEvent.click(screen.getByRole("button", { name: "Key updates only" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Change the default" }));
+ expect(push).toHaveBeenCalledWith("/acme/settings?tab=notifications&section=others_issues");
+ });
+
+ it.each([
+ { name: "own issue", assignee: { assignee_type: "member" as const, assignee_id: me } },
+ { name: "own agent", assignee: { assignee_type: "agent" as const, assignee_id: "agent-mine" } },
+ { name: "unassigned", assignee: { assignee_type: null, assignee_id: null } },
+ ])("stays hidden on the $name", ({ assignee }) => {
+ renderBadge({ assignee });
+ expect(screen.queryByRole("button", { name: "Key updates only" })).toBeNull();
+ });
+
+ it("stays hidden for an explicit subscription or the all preference", () => {
+ const theirs = { assignee_type: "member" as const, assignee_id: "user-other" };
+ renderBadge({ assignee: theirs, reason: "manual" });
+ expect(screen.queryByRole("button", { name: "Key updates only" })).toBeNull();
+ cleanup();
+ renderBadge({ assignee: theirs, preferences: { others_issues: "all" } });
+ expect(screen.queryByRole("button", { name: "Key updates only" })).toBeNull();
+ });
+
+ // Commenting on someone else's issue in a project the member watches leaves
+ // a commenter row, but the project still delivers every event (MUL-9343).
+ it("stays hidden when the project already delivers everything", () => {
+ renderBadge({
+ assignee: { assignee_type: "member", assignee_id: "user-other" },
+ projectCovered: true,
+ });
+ expect(screen.queryByRole("button", { name: "Key updates only" })).toBeNull();
+ });
+
+ // Clickable chips use rounded-md (packages/ui/docs/button.md).
+ it("uses the clickable chip radius", () => {
+ renderBadge({ assignee: { assignee_type: "member", assignee_id: "user-other" } });
+ const trigger = screen.getByRole("button", { name: "Key updates only" });
+ expect(trigger.className).toContain("rounded-md");
+ expect(trigger.className).not.toContain("rounded-full");
+ });
+});
diff --git a/packages/views/issues/components/key-updates-subscription-badge.tsx b/packages/views/issues/components/key-updates-subscription-badge.tsx
new file mode 100644
index 0000000000..5f5b5b0235
--- /dev/null
+++ b/packages/views/issues/components/key-updates-subscription-badge.tsx
@@ -0,0 +1,98 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import { Bell, Settings2 } from "@multica/ui/icons";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { receivesKeyUpdatesOnly } from "@multica/core/notification-preferences/bystander";
+import { notificationPreferenceOptions } from "@multica/core/notification-preferences/queries";
+import { agentListOptions } from "@multica/core/workspace/queries";
+import type { IssueAssigneeType, IssueSubscriber } from "@multica/core/types";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { useT } from "../../i18n";
+import { useNavigation } from "../../navigation";
+
+/**
+ * Says that this issue reaches the viewer as key updates only — someone
+ * else's issue they follow passively (MUL-9343) — and offers the way back to
+ * every event for this one issue. Renders nothing until the preference and the
+ * agent list resolve, so it never flashes on the viewer's own issue.
+ */
+export function KeyUpdatesSubscriptionBadge({
+ issue,
+ userId,
+ reason,
+ projectCovered,
+ pending,
+ onFollowAll,
+}: {
+ issue: { assignee_type?: IssueAssigneeType | null; assignee_id?: string | null };
+ userId: string | undefined;
+ reason: IssueSubscriber["reason"] | undefined;
+ projectCovered: boolean;
+ pending: boolean;
+ onFollowAll: () => void;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const { push } = useNavigation();
+ const { data: preferences, isSuccess: preferencesKnown } = useQuery(
+ notificationPreferenceOptions(wsId),
+ );
+ const { data: agents, isSuccess: agentsKnown } = useQuery(agentListOptions(wsId));
+
+ if (
+ !preferencesKnown ||
+ !agentsKnown ||
+ !receivesKeyUpdatesOnly({
+ reason,
+ projectCovered,
+ issue,
+ userId,
+ agents: agents ?? [],
+ preferences: preferences?.preferences ?? {},
+ })
+ ) {
+ return null;
+ }
+
+ return (
+ <DropdownMenu>
+ {/* Same quiet surface as the delegated badge: it explains a state; the
+ menu holds the one action that changes it. */}
+ <DropdownMenuTrigger
+ disabled={pending}
+ className="cursor-pointer rounded-md bg-muted px-2 py-0.5 text-caption text-muted-foreground transition-colors hover:text-foreground"
+ >
+ {t(($) => $.detail.key_updates_subscription_badge)}
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-72">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="whitespace-normal font-normal leading-snug">
+ {t(($) => $.detail.key_updates_subscription_hint)}
+ </DropdownMenuLabel>
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={onFollowAll} disabled={pending}>
+ <Bell />
+ {t(($) => $.detail.key_updates_follow_all)}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => push(`${paths.settings()}?tab=notifications&section=others_issues`)}
+ >
+ <Settings2 />
+ {t(($) => $.detail.key_updates_settings)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/packages/views/issues/hooks/use-issue-subscribers.test.tsx b/packages/views/issues/hooks/use-issue-subscribers.test.tsx
index f62ad41903..b831db740f 100644
--- a/packages/views/issues/hooks/use-issue-subscribers.test.tsx
+++ b/packages/views/issues/hooks/use-issue-subscribers.test.tsx
@@ -2,7 +2,7 @@
* @vitest-environment jsdom
*/
import { afterEach, describe, expect, it, vi } from "vitest";
-import { cleanup, renderHook, waitFor } from "@testing-library/react";
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";
import { setApiInstance } from "@multica/core/api";
@@ -39,8 +39,11 @@ vi.mock("../../i18n", () => ({
}),
}));
+const wsHandlers = new Map<string, (payload: unknown) => void>();
vi.mock("@multica/core/realtime", () => ({
- useWSEvent: () => undefined,
+ useWSEvent: (event: string, handler: (payload: unknown) => void) => {
+ wsHandlers.set(event, handler);
+ },
useWSReconnect: () => undefined,
}));
@@ -278,3 +281,75 @@ describe("useIssueSubscribers subscriptionKnown", () => {
expect(result.current.subscriptionKnown).toBe(false);
});
});
+
+/**
+ * A project watcher who comments gets a direct commenter row. The project
+ * still delivers every event to them, so the hook must keep saying so, or the
+ * issue page claims "key updates only" for a subscription that is not narrowed
+ * (MUL-9343).
+ */
+describe("useIssueSubscribers project coverage", () => {
+ afterEach(() => {
+ cleanup();
+ wsHandlers.clear();
+ });
+
+ const row = (reason: string, extra: Record<string, unknown> = {}) => ({
+ issue_id: "issue-1",
+ user_type: "member",
+ user_id: "user-1",
+ reason,
+ created_at: "2026-01-01T00:00:00Z",
+ ...extra,
+ });
+
+ it("reads project_covered from the server", async () => {
+ setApiInstance({
+ listIssueSubscribers: async () => [row("commenter", { project_covered: true })],
+ } as unknown as ApiClient);
+
+ const { result } = renderSubscribers();
+ await waitFor(() => expect(result.current.subscriptionKnown).toBe(true));
+ await waitFor(() => expect(result.current.subscriptionReason).toBe("commenter"));
+ expect(result.current.subscriptionProjectCovered).toBe(true);
+ });
+
+ it("keeps the coverage when a project row turns into a direct one", async () => {
+ setApiInstance({
+ listIssueSubscribers: async () => [row("project")],
+ } as unknown as ApiClient);
+
+ const { result } = renderSubscribers();
+ await waitFor(() => expect(result.current.subscriptionReason).toBe("project"));
+ act(() => {
+ wsHandlers.get("subscriber:added")?.({
+ issue_id: "issue-1",
+ user_type: "member",
+ user_id: "user-1",
+ reason: "commenter",
+ });
+ });
+
+ await waitFor(() => expect(result.current.subscriptionReason).toBe("commenter"));
+ expect(result.current.subscriptionProjectCovered).toBe(true);
+ });
+
+ it("is false for a plain direct subscription", async () => {
+ setApiInstance({
+ listIssueSubscribers: async () => [row("manual")],
+ } as unknown as ApiClient);
+
+ const { result } = renderSubscribers();
+ await waitFor(() => expect(result.current.subscriptionKnown).toBe(true));
+ act(() => {
+ wsHandlers.get("subscriber:added")?.({
+ issue_id: "issue-1",
+ user_type: "member",
+ user_id: "user-1",
+ reason: "commenter",
+ });
+ });
+ await waitFor(() => expect(result.current.subscriptionReason).toBe("commenter"));
+ expect(result.current.subscriptionProjectCovered).toBe(false);
+ });
+});
diff --git a/packages/views/issues/hooks/use-issue-subscribers.ts b/packages/views/issues/hooks/use-issue-subscribers.ts
index 17c3070ef0..87c1d754f1 100644
--- a/packages/views/issues/hooks/use-issue-subscribers.ts
+++ b/packages/views/issues/hooks/use-issue-subscribers.ts
@@ -75,9 +75,17 @@ export function useIssueSubscribers(issueId: string, userId?: string) {
// delegation that no longer applies (MUL-5483).
if (existing) {
if (existing.reason === p.reason) return old;
+ // A project watcher who now has a direct row (they commented,
+ // say) still receives everything through the project.
+ const projectCovered =
+ existing.project_covered || existing.reason === "project";
return old.map((s) =>
s.user_id === p.user_id && s.user_type === p.user_type
- ? { ...s, reason: p.reason as IssueSubscriber["reason"] }
+ ? {
+ ...s,
+ reason: p.reason as IssueSubscriber["reason"],
+ ...(projectCovered ? { project_covered: true } : {}),
+ }
: s,
);
}
@@ -136,6 +144,7 @@ export function useIssueSubscribers(issueId: string, userId?: string) {
// your behalf" explanation — a subscription nobody remembers opting into
// reads as the product being creepy unless it says why (MUL-5483).
const subscriptionReason = ownSubscription?.reason;
+ const subscriptionProjectCovered = !!ownSubscription?.project_covered;
// Serializes direct toggles. Disabling the button covers the ordinary case,
// but React Query flushes `isPending` in a microtask, so two clicks in the
@@ -180,6 +189,25 @@ export function useIssueSubscribers(issueId: string, userId?: string) {
if (userId) toggleSubscriber(userId, "member", isSubscribed);
}, [userId, isSubscribed, toggleSubscriber]);
+ // An explicit subscribe while already subscribed: the server rewrites the
+ // reason to manual, which delivers every event on someone else's issue.
+ const followAllActivity = useCallback(() => {
+ if (!userId || toggleInFlight.current) return;
+ toggleInFlight.current = true;
+ toggleMutation.mutate(
+ { userId, userType: "member", subscribed: false },
+ {
+ onSuccess: () =>
+ toast.success(t(($) => $.detail.key_updates_follow_all_done)),
+ onError: () =>
+ toast.error(t(($) => $.detail.subscription_update_failed)),
+ onSettled: () => {
+ toggleInFlight.current = false;
+ },
+ },
+ );
+ }, [userId, toggleMutation, t]);
+
// Subscription state is server-owned and the row simply does not change on
// failure, so nothing on screen moves. Without an explicit message the user
// reads a failed unsubscribe as a no-op button and tries again forever.
@@ -210,6 +238,7 @@ export function useIssueSubscribers(issueId: string, userId?: string) {
subscriptionKnown,
isSubscribed,
subscriptionReason,
+ subscriptionProjectCovered,
// Serializing the UI on these is what keeps the whole-list optimistic
// snapshot in useToggleIssueSubscriber safe: concurrent toggles would each
// snapshot the other's in-flight patch and roll back to the wrong list.
@@ -217,6 +246,7 @@ export function useIssueSubscribers(issueId: string, userId?: string) {
subtreePending: subtreeMutation.isPending,
toggleSubscribe,
toggleSubscriber,
+ followAllActivity,
unsubscribeFromSubtree,
};
}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 88282e367a..1224f4bd43 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -559,6 +559,11 @@
"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.",
+ "key_updates_subscription_badge": "Key updates only",
+ "key_updates_subscription_hint": "This issue is someone else's, and you follow it because you created, commented on or were mentioned in it. You'll hear about @mentions, replies in your threads, and when it needs review, gets stuck or finishes.",
+ "key_updates_follow_all": "Get all activity",
+ "key_updates_follow_all_done": "You'll get all activity on this issue",
+ "key_updates_settings": "Change the default",
"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",
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index a34d81c241..dae410a245 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -848,6 +848,12 @@
"projects": "Projects you subscribe to",
"agents": "Agents"
},
+ "others_issues": {
+ "label": "Other people's issues",
+ "description": "Issues assigned to someone else or their agent, that you only follow because you created, commented on or were mentioned in them. Key updates are @mentions, replies in threads you joined, and statuses that need a person, like in review, blocked or done.",
+ "key_updates": "Key updates only",
+ "all": "All activity"
+ },
"leaving": {
"title": "Leaving the Inbox",
"description": "Reading a notification doesn't take it out of the Inbox.",
diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.json
index c19b9fd169..9405785e30 100644
--- a/packages/views/locales/es/issues.json
+++ b/packages/views/locales/es/issues.json
@@ -528,6 +528,11 @@
"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.",
+ "key_updates_subscription_badge": "Solo actualizaciones clave",
+ "key_updates_subscription_hint": "Esta tarea es de otra persona y la sigues porque la creaste, la comentaste o te mencionaron. Recibirás las @menciones, las respuestas en tus hilos y los avisos cuando necesite revisión, se bloquee o termine.",
+ "key_updates_follow_all": "Recibir toda la actividad",
+ "key_updates_follow_all_done": "Recibirás toda la actividad de esta tarea",
+ "key_updates_settings": "Cambiar el valor predeterminado",
"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",
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index 432651242b..e19c7a51fb 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -848,6 +848,12 @@
"projects": "Proyectos a los que te suscribes",
"agents": "Agentes"
},
+ "others_issues": {
+ "label": "Tareas de otras personas",
+ "description": "Tareas asignadas a otra persona o a su agente, que sigues solo porque las creaste, comentaste o te mencionaron. Las actualizaciones clave son las @menciones, las respuestas en hilos en los que participaste y los estados que necesitan a una persona, como en revisión, bloqueada o terminada.",
+ "key_updates": "Solo actualizaciones clave",
+ "all": "Toda la actividad"
+ },
"leaving": {
"title": "Salir de la bandeja de entrada",
"description": "Leer una notificación no la saca de la bandeja de entrada.",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 58cf72a2d8..a7e6b9fbd6 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -559,6 +559,11 @@
"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.",
+ "key_updates_subscription_badge": "Mises à jour clés",
+ "key_updates_subscription_hint": "Cette tâche est celle de quelqu'un d'autre, et vous la suivez parce que vous l'avez créée, commentée ou y avez été mentionné. Vous recevrez les @mentions, les réponses dans vos fils, et les alertes quand elle demande une relecture, se bloque ou se termine.",
+ "key_updates_follow_all": "Recevoir toute l'activité",
+ "key_updates_follow_all_done": "Vous recevrez toute l'activité de cette tâche",
+ "key_updates_settings": "Modifier la valeur par défaut",
"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",
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 804ba775ff..2cd2d98c26 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -848,6 +848,12 @@
"projects": "Projets que vous suivez",
"agents": "Agents"
},
+ "others_issues": {
+ "label": "Tâches des autres",
+ "description": "Tâches assignées à quelqu'un d'autre ou à son agent, que vous suivez seulement parce que vous les avez créées, commentées ou y avez été mentionné. Les mises à jour clés sont les @mentions, les réponses dans les fils auxquels vous avez participé et les statuts qui demandent une personne, comme en relecture, bloquée ou terminée.",
+ "key_updates": "Mises à jour clés",
+ "all": "Toute l'activité"
+ },
"leaving": {
"title": "Sortir de la boîte de réception",
"description": "Lire une notification ne la retire pas de la boîte de réception.",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 63a01a75a8..0e01e05cb8 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -551,6 +551,11 @@
"unsubscribe": "購読解除",
"delegated_subscription_badge": "エージェント経由で購読中",
"delegated_subscription_hint": "エージェントがあなたに代わってこのタスクを作成したため、購読しています。レビュー待ち・完了・ブロック時に通知されます。",
+ "key_updates_subscription_badge": "重要な更新のみ",
+ "key_updates_subscription_hint": "他の人が担当するタスクで、作成・コメント・メンションによって購読しています。あなたへの @メンション、参加したスレッドへの返信、レビュー待ち・ブロック・完了のときだけ通知されます。",
+ "key_updates_follow_all": "すべてのアクティビティを受け取る",
+ "key_updates_follow_all_done": "このタスクのすべてのアクティビティを受け取ります",
+ "key_updates_settings": "デフォルトを変更",
"project_subscription_badge": "プロジェクト経由で購読中",
"project_subscription_hint": "このプロジェクトのすべてのタスクを購読しています。ここで購読解除すると、このタスクの通知だけが止まります。",
"unsubscribe_this": "このタスクの購読を解除",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index ba8fdd9e78..e1e3e19659 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -839,6 +839,12 @@
"projects": "購読中のプロジェクト",
"agents": "エージェント"
},
+ "others_issues": {
+ "label": "他の人のタスク",
+ "description": "他の人やその人のエージェントに割り当てられたタスクで、作成・コメント・メンションによって自動的に購読しているもの。重要な更新とは、あなたへの @メンション、参加したスレッドへの返信、レビュー待ち・ブロック・完了など人の確認が必要なステータスです。",
+ "key_updates": "重要な更新のみ",
+ "all": "すべてのアクティビティ"
+ },
"leaving": {
"title": "インボックスから外れるとき",
"description": "既読にしてもインボックスからは消えません。",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index e336a97bca..f861b57816 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -551,6 +551,11 @@
"unsubscribe": "구독 해제",
"delegated_subscription_badge": "에이전트를 통해 구독 중",
"delegated_subscription_hint": "에이전트가 회원님을 대신해 이 태스크를 만들었기 때문에 구독 중입니다. 검토 필요, 완료, 차단 시 알림을 받습니다.",
+ "key_updates_subscription_badge": "주요 업데이트만",
+ "key_updates_subscription_hint": "다른 사람이 맡은 태스크이며, 만들거나 댓글을 달거나 멘션되어 구독 중입니다. 나를 향한 @멘션, 참여한 스레드의 답글, 그리고 검토 필요·차단·완료 시에만 알림을 받습니다.",
+ "key_updates_follow_all": "모든 활동 받기",
+ "key_updates_follow_all_done": "이 태스크의 모든 활동을 받습니다",
+ "key_updates_settings": "기본값 변경",
"project_subscription_badge": "프로젝트를 통해 구독 중",
"project_subscription_hint": "이 프로젝트의 모든 태스크를 구독 중입니다. 여기서 구독을 해제하면 이 태스크의 알림만 중지됩니다.",
"unsubscribe_this": "이 태스크 구독 해제",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 723be8f865..1673e242d7 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -839,6 +839,12 @@
"projects": "구독 중인 프로젝트",
"agents": "에이전트"
},
+ "others_issues": {
+ "label": "다른 사람의 태스크",
+ "description": "다른 사람이나 그 사람의 에이전트에게 배정된 태스크 중, 만들거나 댓글을 달거나 멘션되어 자동으로 구독한 것. 주요 업데이트는 나를 향한 @멘션, 참여한 스레드의 답글, 그리고 검토 필요·차단·완료처럼 사람이 봐야 하는 상태입니다.",
+ "key_updates": "주요 업데이트만",
+ "all": "모든 활동"
+ },
"leaving": {
"title": "인박스에서 빠지는 경우",
"description": "읽어도 인박스에서 사라지지 않습니다.",
diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.json
index 5ece793cf5..a055caa19a 100644
--- a/packages/views/locales/ru/issues.json
+++ b/packages/views/locales/ru/issues.json
@@ -569,6 +569,11 @@
"unsubscribe": "Отписаться",
"delegated_subscription_badge": "Отслеживается через агента",
"delegated_subscription_hint": "Ваш агент создал эту задачу от вашего имени, поэтому вы на неё подписаны. Вы получите уведомление, когда потребуется проверка, работа завершится или возникнет затруднение.",
+ "key_updates_subscription_badge": "Только ключевые",
+ "key_updates_subscription_hint": "Это чужая задача, и вы подписаны на неё, потому что создали её, комментировали или были упомянуты. Вы получите @упоминания, ответы в ваших обсуждениях и уведомления, когда потребуется проверка, возникнет затруднение или работа завершится.",
+ "key_updates_follow_all": "Получать все события",
+ "key_updates_follow_all_done": "Вы будете получать все события этой задачи",
+ "key_updates_settings": "Изменить по умолчанию",
"project_subscription_badge": "Подписка через проект",
"project_subscription_hint": "Вы подписаны на все задачи этого проекта. Отписка здесь остановит уведомления только по этой задаче.",
"unsubscribe_this": "Отписаться от этой задачи",
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index 1769d388b0..868d39bd68 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -865,6 +865,12 @@
"projects": "Проекты, на которые вы подписаны",
"agents": "Агенты"
},
+ "others_issues": {
+ "label": "Чужие задачи",
+ "description": "Задачи, назначенные другому человеку или его агенту, на которые вы подписаны только потому, что создали их, комментировали или были упомянуты. Ключевые обновления — это @упоминания, ответы в обсуждениях с вашим участием и статусы, которым нужен человек: на проверке, заблокирована, готово.",
+ "key_updates": "Только ключевые",
+ "all": "Все события"
+ },
"leaving": {
"title": "Когда уведомление уходит из «Входящих»",
"description": "Прочитанное уведомление остаётся во «Входящих».",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 133afd1498..a18c7ba6b0 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -551,6 +551,11 @@
"unsubscribe": "取消订阅",
"delegated_subscription_badge": "由智能体代你关注",
"delegated_subscription_hint": "你的智能体代你创建了这个任务,因此你在关注它。待评审、完成或受阻时会通知你。",
+ "key_updates_subscription_badge": "仅关键更新",
+ "key_updates_subscription_hint": "这是别人负责的任务,你是因为创建、评论或被 @ 才订阅的。只有 @你、回复你参与的讨论,以及待评审、受阻、完成时会通知你。",
+ "key_updates_follow_all": "接收全部动态",
+ "key_updates_follow_all_done": "之后会收到这个任务的全部动态",
+ "key_updates_settings": "修改默认设置",
"project_subscription_badge": "通过项目订阅",
"project_subscription_hint": "你订阅了这个项目的全部任务。在这里取消订阅只会停止这个任务的通知。",
"unsubscribe_this": "取消订阅此任务",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index d080c1bf47..b467070254 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -839,6 +839,12 @@
"projects": "你订阅的项目",
"agents": "智能体"
},
+ "others_issues": {
+ "label": "别人的任务",
+ "description": "任务分配给别人或别人的智能体,而你只是因为创建、评论或被 @ 自动订阅了它。关键更新指 @你、回复你参与的讨论,以及待评审、受阻、完成等需要人来看的状态。",
+ "key_updates": "仅关键更新",
+ "all": "全部动态"
+ },
"leaving": {
"title": "移出收件箱",
"description": "通知不会因为已读而离开收件箱。",
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index 9a6feab512..28c022bec6 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -551,6 +551,11 @@
"unsubscribe": "取消訂閱",
"delegated_subscription_badge": "由 AI 代理代你關注",
"delegated_subscription_hint": "你的 AI 代理代你建立了這個任務,因此你在關注它。待評審、完成或受阻時會通知你。",
+ "key_updates_subscription_badge": "僅關鍵更新",
+ "key_updates_subscription_hint": "這是別人負責的任務,你是因為建立、留言或被 @ 才訂閱的。只有 @你、回覆你參與的討論,以及待評審、受阻、完成時會通知你。",
+ "key_updates_follow_all": "接收全部動態",
+ "key_updates_follow_all_done": "之後會收到這個任務的全部動態",
+ "key_updates_settings": "修改預設設定",
"project_subscription_badge": "透過專案訂閱",
"project_subscription_hint": "你訂閱了這個專案的全部任務。在這裡取消訂閱只會停止這個任務的通知。",
"unsubscribe_this": "取消訂閱此任務",
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index 83a25557fb..ac49d92a2a 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -839,6 +839,12 @@
"projects": "你訂閱的專案",
"agents": "AI 代理"
},
+ "others_issues": {
+ "label": "別人的任務",
+ "description": "任務指派給別人或別人的 AI 代理,而你只是因為建立、留言或被 @ 自動訂閱了它。關鍵更新指 @你、回覆你參與的討論,以及待評審、受阻、完成等需要人來看的狀態。",
+ "key_updates": "僅關鍵更新",
+ "all": "全部動態"
+ },
"leaving": {
"title": "移出收件箱",
"description": "通知不會因為已讀而離開收件箱。",
diff --git a/packages/views/settings/components/notifications-tab.test.tsx b/packages/views/settings/components/notifications-tab.test.tsx
index 01b81fc719..23fcdd8f41 100644
--- a/packages/views/settings/components/notifications-tab.test.tsx
+++ b/packages/views/settings/components/notifications-tab.test.tsx
@@ -53,6 +53,7 @@ describe("Inbox notification settings", () => {
"Mentions",
"Reactions",
"Issues you subscribe to",
+ "Other people's issues",
"Status changes",
"Comments",
"Priority & Due date",
@@ -65,6 +66,16 @@ describe("Inbox notification settings", () => {
expect(within(inbox).getByRole("switch", { name: "Comments" })).toBeChecked();
});
+ it.each<{ preferences: Record<string, string>; shown: string }>([
+ { preferences: {}, shown: "Key updates only" },
+ { preferences: { others_issues: "key_updates" }, shown: "Key updates only" },
+ { preferences: { others_issues: "all" }, shown: "All activity" },
+ ])("shows how much of other people's issues reaches you: %j", ({ preferences, shown }) => {
+ renderTab(preferences);
+ const inbox = screen.getByRole("region", { name: "Inbox" });
+ expect(within(inbox).getByRole("combobox", { name: "Other people's issues" })).toHaveTextContent(shown);
+ });
+
it("explains how notifications leave the Inbox, with a way to the archived ones", () => {
renderTab();
const leaving = screen.getByRole("region", { name: "Leaving the Inbox" });
diff --git a/packages/views/settings/components/notifications-tab.tsx b/packages/views/settings/components/notifications-tab.tsx
index 5c8eb280b1..278edc4dae 100644
--- a/packages/views/settings/components/notifications-tab.tsx
+++ b/packages/views/settings/components/notifications-tab.tsx
@@ -6,8 +6,20 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { notificationPreferenceOptions } from "@multica/core/notification-preferences/queries";
import { useUpdateNotificationPreferences } from "@multica/core/notification-preferences/mutations";
-import type { NotificationGroupKey, NotificationPreferences } from "@multica/core/types";
+import { notificationPreferenceValue } from "@multica/core/notification-preferences/patch";
+import type {
+ NotificationGroupKey,
+ NotificationPreferences,
+ OthersIssuesValue,
+} from "@multica/core/types";
import { buttonVariants } from "@multica/ui/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
import { Switch } from "@multica/ui/components/ui/switch";
import { cn } from "@multica/ui/lib/utils";
import { toast } from "sonner";
@@ -40,6 +52,17 @@ export function NotificationsTab() {
const preferences = data?.preferences ?? {};
+ const save = (updated: NotificationPreferences) => {
+ mutation.mutate(updated, {
+ onError: (err) =>
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.notifications.toast_failed),
+ ),
+ });
+ };
+
const handleToggle = (key: NotificationGroupKey, enabled: boolean) => {
const updated: NotificationPreferences = {
...preferences,
@@ -49,16 +72,20 @@ export function NotificationsTab() {
if (enabled) {
delete updated[key];
}
- mutation.mutate(updated, {
- onError: (err) =>
- toast.error(
- err instanceof Error && err.message
- ? err.message
- : t(($) => $.notifications.toast_failed),
- ),
- });
+ save(updated);
};
+ const handleOthersIssues = (value: OthersIssuesValue) => {
+ const updated: NotificationPreferences = { ...preferences, others_issues: value };
+ if (value === "key_updates") delete updated.others_issues;
+ save(updated);
+ };
+
+ const othersIssuesItems: { value: OthersIssuesValue; label: string }[] = [
+ { value: "key_updates", label: t(($) => $.notifications.others_issues.key_updates) },
+ { value: "all", label: t(($) => $.notifications.others_issues.all) },
+ ];
+
const systemEnabled = preferences.system_notifications !== "muted";
return (
@@ -79,6 +106,34 @@ export function NotificationsTab() {
>
{t(($) => $.notifications.categories[category.key])}
</div>
+ {category.key === "issues" && (
+ <SettingsRow
+ anchor="others_issues"
+ label={t(($) => $.notifications.others_issues.label)}
+ description={t(($) => $.notifications.others_issues.description)}
+ >
+ <Select
+ items={othersIssuesItems}
+ value={notificationPreferenceValue(preferences, "others_issues")}
+ onValueChange={(next) => next && handleOthersIssues(next as OthersIssuesValue)}
+ >
+ <SelectTrigger
+ size="sm"
+ className="w-40"
+ aria-label={t(($) => $.notifications.others_issues.label)}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end">
+ {othersIssuesItems.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+ )}
{category.groups.map((key) => (
<SettingsRow
key={key}
diff --git a/packages/views/settings/components/use-settings-search-index.ts b/packages/views/settings/components/use-settings-search-index.ts
index de155aae43..4329a27922 100644
--- a/packages/views/settings/components/use-settings-search-index.ts
+++ b/packages/views/settings/components/use-settings-search-index.ts
@@ -182,6 +182,12 @@ export function useSettingsSearchIndex(
title: t(($) => $.notifications.groups[group].label),
description: t(($) => $.notifications.groups[group].description),
})),
+ {
+ tab: "notifications",
+ anchor: "others_issues",
+ title: t(($) => $.notifications.others_issues.label),
+ description: t(($) => $.notifications.others_issues.description),
+ },
{
tab: "notifications",
anchor: "auto_archive_completed",
diff --git a/server/cmd/server/bystander_tier_test.go b/server/cmd/server/bystander_tier_test.go
new file mode 100644
index 0000000000..dc4a37f992
--- /dev/null
+++ b/server/cmd/server/bystander_tier_test.go
@@ -0,0 +1,248 @@
+package main
+
+import (
+ "context"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func TestDeliverToBystander(t *testing.T) {
+ cases := []struct {
+ notifType string
+ handoff bool
+ threadParticipant bool
+ want bool
+ }{
+ {"mentioned", false, false, true},
+ {"status_changed", true, false, true},
+ {"status_changed", false, false, false},
+ {"new_comment", false, true, true},
+ {"new_comment", false, false, false},
+ {"task_failed", true, true, false},
+ {"assignee_changed", true, true, false},
+ {"priority_changed", true, true, false},
+ {"reaction_added", true, true, false},
+ }
+ for _, c := range cases {
+ if got := deliverToBystander(c.notifType, c.handoff, c.threadParticipant); got != c.want {
+ t.Errorf("deliverToBystander(%q, handoff=%v, thread=%v) = %v, want %v",
+ c.notifType, c.handoff, c.threadParticipant, got, c.want)
+ }
+ }
+}
+
+func setOthersIssuesPref(t *testing.T, userID, value string) {
+ t.Helper()
+ workspaceFixture(t).Exec(t, `
+ INSERT INTO notification_preference (workspace_id, user_id, preferences)
+ VALUES ($1, $2, jsonb_build_object('others_issues', $3::text))
+ ON CONFLICT (workspace_id, user_id) DO UPDATE SET preferences = EXCLUDED.preferences
+ `, testWorkspaceID, userID, value)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM notification_preference WHERE workspace_id = $1 AND user_id = $2`,
+ testWorkspaceID, userID)
+ })
+}
+
+func inboxCount(t *testing.T, queries *db.Queries, recipientID string) int {
+ t.Helper()
+ return len(inboxItemsForRecipient(t, queries, recipientID))
+}
+
+// On an issue assigned to someone else, a passive subscription hears only the
+// handoff; the owner, an explicit follower and a member who chose "all" hear
+// the routine move too.
+func TestBystanderTier_StatusChange(t *testing.T) {
+ queries := db.New(testPool)
+ bus := newNotificationBus(t, queries)
+
+ owner := createNotificationMember(t, "[email protected]")
+ t.Cleanup(func() { cleanupTestUser(t, "[email protected]") })
+ watcher := createNotificationMember(t, "[email protected]")
+ t.Cleanup(func() { cleanupTestUser(t, "[email protected]") })
+ follower := createNotificationMember(t, "[email protected]")
+ t.Cleanup(func() { cleanupTestUser(t, "[email protected]") })
+ optedIn := createNotificationMember(t, "[email protected]")
+ t.Cleanup(func() { cleanupTestUser(t, "[email protected]") })
+ setOthersIssuesPref(t, optedIn, "all")
+
+ issueID := workspaceFixture(t).Issue(t, "bystander tier issue", testutil.Cols{
+ "assignee_type": "member",
+ "assignee_id": owner,
+ })
+ t.Cleanup(func() { cleanupInboxForIssue(t, issueID) })
+
+ addTestSubscriber(t, issueID, "member", owner, "assignee")
+ addTestSubscriber(t, issueID, "member", watcher, "commenter")
+ addTestSubscriber(t, issueID, "member", follower, "manual")
+ addTestSubscriber(t, issueID, "member", optedIn, "creator")
+
+ publishStatusChange(bus, issueID, "in_progress", "todo")
+
+ for name, c := range map[string]struct {
+ id string
+ want int
+ }{
+ "owner": {owner, 1},
+ "watcher": {watcher, 0},
+ "follower": {follower, 1},
+ "opted in": {optedIn, 1},
+ } {
+ if got := inboxCount(t, queries, c.id); got != c.want {
+ t.Errorf("%s after in_progress: %d inbox items, want %d", name, got, c.want)
+ }
+ }
+
+ publishStatusChange(bus, issueID, "in_review", "in_progress")
+ if got := inboxCount(t, queries, watcher); got != 1 {
+ t.Errorf("watcher after in_review: %d inbox items, want 1", got)
+ }
+}
+
+// An issue assigned to an agent the subscriber owns is their own issue.
+func TestBystanderTier_OwnAgentIsOwnIssue(t *testing.T) {
+ queries := db.New(testPool)
+ bus := newNotificationBus(t, queries)
+
+ owner := createNotificationMember(t, "[email protected]")
+ t.Cleanup(func() { cleanupTestUser(t, "[email protected]") })
+ other := createNotificationMember(t, "[email protected]")
+ t.Cleanup(func() { cleanupTestUser(t, "[email protected]") })
+
+ f := workspaceFixture(t)
+ runtimeID := f.Runtime(t, "bystander-runtime", testutil.Cols{"owner_id": owner})
+ agentID := f.Agent(t, "bystander-agent", runtimeID, testutil.Cols{"owner_id": owner})
+ issueID := f.Issue(t, "bystander tier issue", testutil.Cols{
+ "assignee_type": "agent",
+ "assignee_id": agentID,
+ })
+ t.Cleanup(func() { cleanupInboxForIssue(t, issueID) })
+
+ addTestSubscriber(t, issueID, "member", owner, "creator")
+ addTestSubscriber(t, issueID, "member", other, "creator")
+
+ publishStatusChange(bus, issueID, "in_progress", "todo")
+
+ if got := inboxCount(t, queries, owner); got != 1 {
+ t.Errorf("agent owner: %d inbox items, want 1", got)
+ }
+ if got := inboxCount(t, queries, other); got != 0 {
+ t.Errorf("other member: %d inbox items, want 0", got)
+ }
+}
+
+// A bystander still hears a reply in a thread they took part in, and nothing
+// from a thread they did not.
+func TestBystanderTier_ThreadReply(t *testing.T) {
+ queries := db.New(testPool)
+ bus := newNotificationBus(t, queries)
+
+ owner := createNotificationMember(t, "[email protected]")
+ t.Cleanup(func() { cleanupTestUser(t, "[email protected]") })
+ watcher := createNotificationMember(t, "[email protected]")
+ t.Cleanup(func() { cleanupTestUser(t, "[email protected]") })
+
+ f := workspaceFixture(t)
+ issueID := f.Issue(t, "bystander tier issue", testutil.Cols{
+ "assignee_type": "member",
+ "assignee_id": owner,
+ })
+ t.Cleanup(func() { cleanupInboxForIssue(t, issueID) })
+ addTestSubscriber(t, issueID, "member", watcher, "commenter")
+
+ rootID := f.Comment(t, issueID, "a question from the watcher", testutil.Cols{"author_id": watcher})
+ publishComment := func(content string, parentID *string) {
+ commentID := f.Comment(t, issueID, content, testutil.Cols{"author_id": owner, "parent_id": parentID})
+ bus.Publish(events.Event{
+ Type: protocol.EventCommentCreated,
+ WorkspaceID: testWorkspaceID,
+ ActorType: "member",
+ ActorID: owner,
+ Payload: map[string]any{
+ "comment": handler.CommentResponse{
+ ID: commentID,
+ IssueID: issueID,
+ AuthorType: "member",
+ AuthorID: owner,
+ Content: content,
+ Type: "comment",
+ ParentID: parentID,
+ },
+ "issue_title": "bystander tier issue",
+ "issue_status": "in_progress",
+ },
+ })
+ }
+
+ publishComment("an unrelated update", nil)
+ if got := inboxCount(t, queries, watcher); got != 0 {
+ t.Fatalf("watcher after an unrelated comment: %d inbox items, want 0", got)
+ }
+
+ publishComment("an answer", &rootID)
+ items := inboxItemsForRecipient(t, queries, watcher)
+ if len(items) != 1 || items[0].Type != "new_comment" {
+ t.Fatalf("watcher after a reply in their thread: %+v, want one new_comment", items)
+ }
+}
+
+// A member who watches the project and commented on someone else's issue in it
+// has a commenter row, but the project path still delivers every event — once.
+func TestBystanderTier_ProjectWatcherKeepsEveryEvent(t *testing.T) {
+ queries := db.New(testPool)
+ bus := newNotificationBus(t, queries)
+
+ owner := createNotificationMember(t, "[email protected]")
+ t.Cleanup(func() { cleanupTestUser(t, "[email protected]") })
+ watcher := createNotificationMember(t, "[email protected]")
+ t.Cleanup(func() { cleanupTestUser(t, "[email protected]") })
+ bystander := createNotificationMember(t, "[email protected]")
+ t.Cleanup(func() { cleanupTestUser(t, "[email protected]") })
+
+ projectID := createTestProject(t)
+ f := workspaceFixture(t)
+ issueID := f.Issue(t, "bystander tier issue", testutil.Cols{
+ "assignee_type": "member",
+ "assignee_id": owner,
+ "project_id": projectID,
+ })
+ t.Cleanup(func() { cleanupInboxForIssue(t, issueID) })
+ addProjectSubscribers(t, projectID, watcher)
+ addTestSubscriber(t, issueID, "member", watcher, "commenter")
+ addTestSubscriber(t, issueID, "member", bystander, "commenter")
+
+ content := "a routine update"
+ commentID := f.Comment(t, issueID, content, testutil.Cols{"author_id": owner})
+ bus.Publish(events.Event{
+ Type: protocol.EventCommentCreated,
+ WorkspaceID: testWorkspaceID,
+ ActorType: "member",
+ ActorID: owner,
+ Payload: map[string]any{
+ "comment": handler.CommentResponse{
+ ID: commentID,
+ IssueID: issueID,
+ AuthorType: "member",
+ AuthorID: owner,
+ Content: content,
+ Type: "comment",
+ },
+ "issue_title": "bystander tier issue",
+ "issue_status": "in_progress",
+ },
+ })
+ publishStatusChange(bus, issueID, "in_progress", "todo")
+
+ if got := inboxTypes(t, queries, watcher); len(got) != 2 {
+ t.Errorf("project watcher: inbox %v, want the comment and the status change once each", got)
+ }
+ if got := inboxCount(t, queries, bystander); got != 0 {
+ t.Errorf("plain bystander: %d inbox items, want 0", got)
+ }
+}
diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.go
index 575cf1f5c6..28e9716b0b 100644
--- a/server/cmd/server/notification_listeners.go
+++ b/server/cmd/server/notification_listeners.go
@@ -117,9 +117,10 @@ func issueStatusIsHandoff(
// deliverToSubscriber reports whether a subscriber row should receive this
// notification type. Direct subscriptions (creator / assignee / commenter /
-// mentioned / manual / autopilot) are unchanged — they opted in to this issue,
-// explicitly or by acting on it. Only the delegated tier is narrowed, and only
-// to drop churn.
+// mentioned / manual / autopilot) pass — they opted in to this issue,
+// explicitly or by acting on it; the passive ones are narrowed separately on
+// someone else's issue (deliverToBystander). Only the delegated tier is
+// narrowed here, and only to drop churn.
//
// A child finishing is NOT churn: "sub-issue X is ready for review" is exactly
// the signal a delegated watcher needs, and there is one per piece of real work.
@@ -146,6 +147,155 @@ func deliverToSubscriber(reason, notifType string, statusIsHandoff bool) bool {
return statusIsHandoff
}
+// othersIssuesPref is the preference key for how much of SOMEONE ELSE'S issue
+// reaches a member who is only passively subscribed to it. Absent or
+// "key_updates" applies the bystander tier; "all" turns it off (MUL-9343).
+const othersIssuesPref = "others_issues"
+
+// bystanderReasons are the subscription reasons a member picks up as a side
+// effect of acting on an issue — filing it, once being its assignee,
+// commenting, being mentioned. On an issue assigned to someone else these
+// narrow to the bystander tier. manual and autopilot are explicit requests to
+// follow the issue and keep every event; delegated has its own tier.
+var bystanderReasons = map[string]bool{
+ "creator": true,
+ "assignee": true,
+ "commenter": true,
+ "mentioned": true,
+}
+
+// deliverToBystander reports whether a bystander — a passive subscriber of an
+// issue assigned to someone else — receives this notification type. They hear
+// what is addressed at them or needs them: a mention, a reply in a comment
+// thread they took part in, and a status that hands the issue back to a human
+// (statusIsHandoff, as in deliverToSubscriber). The rest of the issue's
+// back-and-forth stays on the issue page.
+func deliverToBystander(notifType string, statusIsHandoff, threadParticipant bool) bool {
+ switch notifType {
+ case "mentioned":
+ return true
+ case "status_changed":
+ return statusIsHandoff
+ case "new_comment":
+ return threadParticipant
+ default:
+ return false
+ }
+}
+
+// issueOwner is who an issue is assigned to, resolved to the human behind it:
+// the assigned member, or the owner of the assigned agent. A squad assignee
+// has no single owner, so a squad's issue is nobody's own.
+type issueOwner struct {
+ assigned bool
+ ownerID string
+}
+
+// isSomeoneElses reports whether the issue is assigned, and not to userID or
+// an agent userID owns. An unassigned issue is nobody else's: its creator is
+// the closest thing it has to an owner, and nothing about it is routine yet.
+func (o issueOwner) isSomeoneElses(userID string) bool {
+ return o.assigned && o.ownerID != userID
+}
+
+func loadIssueOwner(ctx context.Context, queries *db.Queries, issueID string) (issueOwner, error) {
+ issue, err := queries.GetIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ return issueOwner{}, err
+ }
+ if !issue.AssigneeID.Valid {
+ return issueOwner{}, nil
+ }
+ switch issue.AssigneeType.String {
+ case "member":
+ return issueOwner{assigned: true, ownerID: util.UUIDToString(issue.AssigneeID)}, nil
+ case "agent":
+ agent, err := queries.GetAgent(ctx, issue.AssigneeID)
+ if err != nil {
+ return issueOwner{}, err
+ }
+ owner := ""
+ if agent.OwnerID.Valid {
+ owner = util.UUIDToString(agent.OwnerID)
+ }
+ return issueOwner{assigned: true, ownerID: owner}, nil
+ default:
+ return issueOwner{assigned: true}, nil
+ }
+}
+
+// loadThreadParticipants returns the members who wrote another comment in the
+// thread the notified comment belongs to, read from the new_comment details.
+func loadThreadParticipants(ctx context.Context, queries *db.Queries, workspaceID string, details []byte) (map[string]bool, error) {
+ var d struct {
+ CommentID string `json:"comment_id"`
+ }
+ if err := json.Unmarshal(details, &d); err != nil || d.CommentID == "" {
+ return map[string]bool{}, nil
+ }
+ authors, err := queries.ListThreadMemberAuthors(ctx, db.ListThreadMemberAuthorsParams{
+ CommentID: parseUUID(d.CommentID),
+ WorkspaceID: parseUUID(workspaceID),
+ })
+ if err != nil {
+ return nil, err
+ }
+ participants := make(map[string]bool, len(authors))
+ for _, id := range authors {
+ participants[util.UUIDToString(id)] = true
+ }
+ return participants, nil
+}
+
+// bystanderTier applies deliverToBystander across one subscriber list. It
+// reads the issue's owner, and for a comment its thread, at most once and only
+// when a passive subscriber reaches it.
+//
+// FAIL OPEN, for the reason notifyIssueSubscribers resolves handoffs that way:
+// a spare inbox row costs a dismissal, a dropped one can strand a reply.
+type bystanderTier struct {
+ ctx context.Context
+ queries *db.Queries
+ workspaceID string
+ issueID string
+ details []byte
+
+ ownerLoaded bool
+ owner issueOwner
+ ownerErr error
+ threadLoaded bool
+ thread map[string]bool
+ threadErr error
+}
+
+func (b *bystanderTier) deliver(userID, notifType string, statusIsHandoff bool) bool {
+ if !b.ownerLoaded {
+ b.ownerLoaded = true
+ b.owner, b.ownerErr = loadIssueOwner(b.ctx, b.queries, b.issueID)
+ if b.ownerErr != nil {
+ slog.Warn("resolve issue owner for bystander delivery; delivering",
+ "issue_id", b.issueID, "error", b.ownerErr)
+ }
+ }
+ if b.ownerErr != nil || !b.owner.isSomeoneElses(userID) {
+ return true
+ }
+
+ participant := false
+ if notifType == "new_comment" {
+ if !b.threadLoaded {
+ b.threadLoaded = true
+ b.thread, b.threadErr = loadThreadParticipants(b.ctx, b.queries, b.workspaceID, b.details)
+ if b.threadErr != nil {
+ slog.Warn("resolve comment thread for bystander delivery; delivering",
+ "issue_id", b.issueID, "error", b.threadErr)
+ }
+ }
+ participant = b.threadErr != nil || b.thread[userID]
+ }
+ return deliverToBystander(notifType, statusIsHandoff, participant)
+}
+
// loadUserPrefs loads the notification preferences of a fanout's recipients
// in one query.
func loadUserPrefs(
@@ -584,6 +734,10 @@ func notifyIssueSubscribers(
}
}
userPrefs := loadUserPrefs(ctx, queries, workspaceID, memberIDs)
+ bystander := &bystanderTier{
+ ctx: ctx, queries: queries, workspaceID: workspaceID,
+ issueID: subscriberIssueID, details: details,
+ }
for _, sub := range subs {
// Only notify member-type subscribers (not agents)
@@ -610,6 +764,15 @@ func notifyIssueSubscribers(
continue
}
+ // A passive subscription to someone else's issue delivers the
+ // bystander tier unless the member asked for everything. This is not
+ // added to tierSuppressed: the parent bubble judges the parent's own
+ // subscription, and the parent may well be this member's issue.
+ if bystanderReasons[sub.Reason] && userPrefs[subID][othersIssuesPref] != "all" &&
+ !bystander.deliver(subID, notifType, statusIsHandoff) {
+ continue
+ }
+
if createMemberInboxItem(ctx, queries, bus, subID, workspaceID, e, targetIssueID, issueStatus,
notifType, severity, title, body, details, userPrefs) {
notified[subID] = true
diff --git a/server/internal/handler/notification_preference.go b/server/internal/handler/notification_preference.go
index bbcd101fc2..9a06df75b3 100644
--- a/server/internal/handler/notification_preference.go
+++ b/server/internal/handler/notification_preference.go
@@ -30,14 +30,31 @@ var validNotifGroups = map[string]bool{
"new_issues": true,
"system_notifications": true,
"auto_archive_completed": true,
+ "others_issues": true,
}
-// validNotifValues is the set of allowed preference values per group.
+// validNotifValues is the set of allowed preference values for a group not
+// listed in notifValuesByGroup.
var validNotifValues = map[string]bool{
"all": true,
"muted": true,
}
+// notifValuesByGroup lists the groups whose values are not on/off.
+// `others_issues` is how much of someone else's issue a passive subscriber
+// receives: absent or "key_updates" for mentions, thread replies and handoffs,
+// "all" for every event. Muting it would only hide what still needs you.
+var notifValuesByGroup = map[string]map[string]bool{
+ "others_issues": {"all": true, "key_updates": true},
+}
+
+func validNotifValue(group, value string) bool {
+ if values, ok := notifValuesByGroup[group]; ok {
+ return values[value]
+ }
+ return validNotifValues[value]
+}
+
func (h *Handler) GetNotificationPreferences(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
@@ -94,7 +111,7 @@ func decodeNotificationPreferenceRequest(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusBadRequest, "invalid preference group: "+k)
return nil, false
}
- if !validNotifValues[v] {
+ if !validNotifValue(k, v) {
writeError(w, http.StatusBadRequest, "invalid preference value: "+v)
return nil, false
}
diff --git a/server/internal/handler/notification_preference_test.go b/server/internal/handler/notification_preference_test.go
index d5b8b34d6f..c38f611521 100644
--- a/server/internal/handler/notification_preference_test.go
+++ b/server/internal/handler/notification_preference_test.go
@@ -196,3 +196,45 @@ func TestPatchNotificationPreferencesRejectsUnknownGroups(t *testing.T) {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
}
+
+func TestPatchNotificationPreferencesValidatesOthersIssuesValues(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `
+ DELETE FROM notification_preference
+ WHERE workspace_id = $1 AND user_id = $2
+ `, testWorkspaceID, testUserID)
+ })
+
+ for value, want := range map[string]int{
+ "all": http.StatusOK,
+ "key_updates": http.StatusOK,
+ "muted": http.StatusBadRequest,
+ } {
+ recorder := httptest.NewRecorder()
+ testHandler.PatchNotificationPreferences(
+ recorder,
+ notificationPreferenceRequest(t, http.MethodPatch, map[string]string{
+ "others_issues": value,
+ }),
+ )
+ if recorder.Code != want {
+ t.Errorf("others_issues=%q: status=%d want %d body=%s",
+ value, recorder.Code, want, recorder.Body.String())
+ }
+ }
+
+ // key_updates stays exclusive to others_issues.
+ recorder := httptest.NewRecorder()
+ testHandler.PatchNotificationPreferences(
+ recorder,
+ notificationPreferenceRequest(t, http.MethodPatch, map[string]string{
+ "comments": "key_updates",
+ }),
+ )
+ if recorder.Code != http.StatusBadRequest {
+ t.Fatalf("comments=key_updates: status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+}
diff --git a/server/internal/handler/subscriber.go b/server/internal/handler/subscriber.go
index 010a82b46e..944d8aeb8d 100644
--- a/server/internal/handler/subscriber.go
+++ b/server/internal/handler/subscriber.go
@@ -20,6 +20,10 @@ type SubscriberResponse struct {
UserID string `json:"user_id"`
Reason string `json:"reason"`
CreatedAt string `json:"created_at"`
+ // ProjectCovered marks a direct row whose member also subscribes to the
+ // issue's project. The project path delivers every event regardless of the
+ // direct reason, so clients must not read that reason as a reduced tier.
+ ProjectCovered bool `json:"project_covered,omitempty"`
}
func subscriberToResponse(s db.IssueSubscriber) SubscriberResponse {
@@ -55,13 +59,20 @@ func (h *Handler) ListIssueSubscribers(w http.ResponseWriter, r *http.Request) {
return
}
+ projectCovered := make(map[string]bool, len(projectSubscribers))
+ for _, ps := range projectSubscribers {
+ projectCovered[uuidToString(ps.UserID)] = true
+ }
+
resp := make([]SubscriberResponse, 0, len(subscribers)+len(projectSubscribers))
direct := make(map[string]bool, len(subscribers))
for _, s := range subscribers {
- resp = append(resp, subscriberToResponse(s))
+ row := subscriberToResponse(s)
if s.UserType == "member" {
- direct[uuidToString(s.UserID)] = true
+ direct[row.UserID] = true
+ row.ProjectCovered = projectCovered[row.UserID]
}
+ resp = append(resp, row)
}
for _, ps := range projectSubscribers {
userID := uuidToString(ps.UserID)
diff --git a/server/internal/handler/subscriber_project_covered_test.go b/server/internal/handler/subscriber_project_covered_test.go
new file mode 100644
index 0000000000..dc6042e7a5
--- /dev/null
+++ b/server/internal/handler/subscriber_project_covered_test.go
@@ -0,0 +1,47 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// A direct row of a member who also watches the project says so: the project
+// delivers every event, so the direct reason does not describe a reduced tier.
+func TestIssueSubscribersMarkProjectCoveredRows(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)
+ })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO project_subscriber (workspace_id, project_id, user_id) VALUES ($1, $2, $3)
+ `, testWorkspaceID, f.projectID, f.insider); err != nil {
+ t.Fatal(err)
+ }
+ for _, userID := range []string{f.insider, testUserID} {
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO issue_subscriber (issue_id, user_type, user_id, reason) VALUES ($1, 'member', $2, 'commenter')
+ `, f.secretIssue, userID); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ var resp []SubscriberResponse
+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/issues/"+f.secretIssue+"/subscribers", nil), testUserID), "id", f.secretIssue)
+ testutil.Call(t, testHandler.ListIssueSubscribers, req).Want(http.StatusOK).JSON(&resp)
+
+ got := map[string][]SubscriberResponse{}
+ for _, s := range resp {
+ got[s.UserID] = append(got[s.UserID], s)
+ }
+ if rows := got[f.insider]; len(rows) != 1 || rows[0].Reason != "commenter" || !rows[0].ProjectCovered {
+ t.Fatalf("project watcher rows = %+v, want one commenter row marked project_covered", rows)
+ }
+ if rows := got[testUserID]; len(rows) != 1 || rows[0].ProjectCovered {
+ t.Fatalf("plain commenter rows = %+v, want one row without project_covered", rows)
+ }
+}
diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.go
index 1196a957f8..fa3583d3da 100644
--- a/server/pkg/db/generated/comment.sql.go
+++ b/server/pkg/db/generated/comment.sql.go
@@ -1976,6 +1976,62 @@ func (q *Queries) ListThreadCommentsForIssuePaged(ctx context.Context, arg ListT
return items, nil
}
+const listThreadMemberAuthors = `-- name: ListThreadMemberAuthors :many
+WITH RECURSIVE root_of AS (
+ SELECT c.id, c.parent_id
+ FROM comment c
+ WHERE c.id = $1 AND c.workspace_id = $2
+ UNION ALL
+ SELECT p.id, p.parent_id
+ FROM comment p
+ JOIN root_of r ON p.id = r.parent_id
+),
+thread AS (
+ SELECT c.id
+ FROM comment c
+ WHERE c.id = (SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1)
+ UNION ALL
+ SELECT c.id
+ FROM comment c
+ JOIN thread t ON c.parent_id = t.id
+)
+SELECT DISTINCT c.author_id
+FROM comment c
+JOIN thread t ON t.id = c.id
+WHERE c.id <> $1
+ AND c.author_type = 'member'
+ AND c.deleted_at IS NULL
+`
+
+type ListThreadMemberAuthorsParams struct {
+ CommentID pgtype.UUID `json:"comment_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// The members who wrote any other comment in the thread @comment_id belongs
+// to: its root and every reply under that root, at any depth. Used by the
+// bystander delivery tier, so a reply in a thread you took part in still
+// reaches you on an issue you are only watching (MUL-9343).
+func (q *Queries) ListThreadMemberAuthors(ctx context.Context, arg ListThreadMemberAuthorsParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listThreadMemberAuthors, arg.CommentID, arg.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var author_id pgtype.UUID
+ if err := rows.Scan(&author_id); err != nil {
+ return nil, err
+ }
+ items = append(items, author_id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const lockCommentAncestorPath = `-- name: LockCommentAncestorPath :many
WITH RECURSIVE ancestor_ids AS (
SELECT c.id, c.parent_id, 1::integer AS depth, ARRAY[c.id]::uuid[] AS visited_ids
diff --git a/server/pkg/db/queries/comment.sql b/server/pkg/db/queries/comment.sql
index 021a78e3f5..6fce3b17af 100644
--- a/server/pkg/db/queries/comment.sql
+++ b/server/pkg/db/queries/comment.sql
@@ -927,3 +927,33 @@ FROM comment c
JOIN ancestor_ids path ON path.id = c.id
ORDER BY c.id
FOR UPDATE OF c;
+
+-- name: ListThreadMemberAuthors :many
+-- The members who wrote any other comment in the thread @comment_id belongs
+-- to: its root and every reply under that root, at any depth. Used by the
+-- bystander delivery tier, so a reply in a thread you took part in still
+-- reaches you on an issue you are only watching (MUL-9343).
+WITH RECURSIVE root_of AS (
+ SELECT c.id, c.parent_id
+ FROM comment c
+ WHERE c.id = @comment_id AND c.workspace_id = @workspace_id
+ UNION ALL
+ SELECT p.id, p.parent_id
+ FROM comment p
+ JOIN root_of r ON p.id = r.parent_id
+),
+thread AS (
+ SELECT c.id
+ FROM comment c
+ WHERE c.id = (SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1)
+ UNION ALL
+ SELECT c.id
+ FROM comment c
+ JOIN thread t ON c.parent_id = t.id
+)
+SELECT DISTINCT c.author_id
+FROM comment c
+JOIN thread t ON t.id = c.id
+WHERE c.id <> @comment_id
+ AND c.author_type = 'member'
+ AND c.deleted_at IS NULL;