Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(inbox): unsubscribe & archive on issues that are not yours (MUL-9343) (#10685)
Jiayuan Zhangf3a3040e5c13
diff --git a/apps/docs/content/docs/inbox.fr.mdx b/apps/docs/content/docs/inbox.fr.mdxindex 3efb652dab..652798f14e 100644--- a/apps/docs/content/docs/inbox.fr.mdx+++ b/apps/docs/content/docs/inbox.fr.mdx@@ -64,6 +64,7 @@ Une tâche ouverte depuis la boîte de réception affiche les actions de la boî- **Reporter** (`H`) retire la tâche de votre boîte de réception jusqu'à l'heure choisie et ouvre la suivante. Voir « Reporter une tâche » ci-dessous.- **Marquer comme terminé** passe la tâche en `done`, archive la notification et ouvre la suivante. La notification est archivée même si **Archiver les tâches que vous terminez** est désactivé. L'action est proposée tant que la tâche n'est ni terminée ni annulée.- **Archiver** (`E`) archive la notification et ouvre la suivante. L'archivage ne modifie ni ne supprime la tâche.+- **Se désabonner et archiver** (`⇧E`) est proposé sur les tâches qui ne sont pas les vôtres : assignées ni à vous, ni à un agent qui vous appartient. L'action vous désabonne de la tâche, archive la notification et ouvre la suivante. Les mises à jour ordinaires n'arrivent plus dans votre boîte de réception, mais les @mentions, si. Sur une tâche avec des sous-tâches, vous choisissez entre cette tâche seulement et cette tâche avec toutes ses sous-tâches. Pour cette tâche seulement, la confirmation propose **Annuler**, qui rétablit l'abonnement tel qu'il était. Le désabonnement des sous-tâches ne s'annule pas ici ; réabonnez-vous depuis la page de la tâche. La même action se trouve dans la carte au survol et dans le menu contextuel d'une ligne.La suivante est la ligne suivante que la section affiche avec ses filtres actuels : vous parcourez ainsi la boîte de réception sans revenir à la liste.diff --git a/apps/docs/content/docs/inbox.ja.mdx b/apps/docs/content/docs/inbox.ja.mdxindex a416d3bf42..1364c5309f 100644--- a/apps/docs/content/docs/inbox.ja.mdx+++ b/apps/docs/content/docs/inbox.ja.mdx@@ -64,6 +64,7 @@ import { InboxDemo } from "@/components/demos/inbox-demo";- **スヌーズ**(`H`)は、指定した時間までタスクをインボックスから外し、次の通知を開きます。詳しくは下の「タスクをスヌーズする」を参照してください。- **完了にする** は、タスクを `done` にし、通知をアーカイブして、次の通知を開きます。**自分が完了したタスクをアーカイブ** がオフでも、この通知はアーカイブされます。タスクがまだ完了またはキャンセルされていないときに表示されます。- **アーカイブ**(`E`)は、通知をアーカイブして次の通知を開きます。アーカイブしてもタスクは変更・削除されません。+- **購読解除してアーカイブ**(`⇧E`)は、自分のタスクではないとき(担当者が自分でも自分のエージェントでもない)に表示されます。タスクの購読を解除し、通知をアーカイブして次の通知を開きます。以降の通常の更新はインボックスに届きませんが、@メンションは引き続き通知されます。サブタスクがある場合は、このタスクのみか、すべてのサブタスクを含めるかを選べます。このタスクのみの場合は確認メッセージの **元に戻す** で購読を元どおりに戻せます。サブタスクごと解除した場合はここでは戻せないので、タスクのページで購読し直してください。ホバーカードと行の右クリックメニューにも同じ操作があります。次の通知とは、セクションが現在のフィルターで表示している次の行のことです。リストに戻らずにインボックスを順に片付けられます。diff --git a/apps/docs/content/docs/inbox.ko.mdx b/apps/docs/content/docs/inbox.ko.mdxindex f5e9b6a86c..2d5f79ab73 100644--- a/apps/docs/content/docs/inbox.ko.mdx+++ b/apps/docs/content/docs/inbox.ko.mdx@@ -64,6 +64,7 @@ import { InboxDemo } from "@/components/demos/inbox-demo";- **다시 알림**(`H`)은 지정한 시간까지 태스크를 인박스에서 빼고 다음 알림을 엽니다. 자세한 내용은 아래 '태스크 미루기'를 참고하세요.- **완료로 표시**는 태스크를 `done`으로 바꾸고, 알림을 보관한 뒤 다음 알림을 엽니다. **내가 완료한 태스크 보관**이 꺼져 있어도 이 알림은 보관됩니다. 태스크가 아직 완료되거나 취소되지 않았을 때만 표시됩니다.- **보관**(`E`)은 알림을 보관하고 다음 알림을 엽니다. 보관해도 태스크는 변경되거나 삭제되지 않습니다.+- **구독 해제 후 보관**(`⇧E`)은 내 태스크가 아닐 때(담당자가 나도, 내 에이전트도 아닐 때) 표시됩니다. 태스크 구독을 해제하고 알림을 보관한 뒤 다음 알림을 엽니다. 이후 일반 업데이트는 인박스에 오지 않지만 @멘션은 계속 알림을 받습니다. 하위 태스크가 있으면 이 태스크만 또는 모든 하위 태스크까지 해제할지 고를 수 있습니다. 이 태스크만 해제했다면 확인 메시지의 **실행 취소**로 구독을 원래대로 되돌릴 수 있습니다. 하위 태스크까지 해제한 경우에는 여기서 되돌릴 수 없으니 태스크 페이지에서 다시 구독하세요. 호버 카드와 행의 우클릭 메뉴에도 같은 동작이 있습니다.다음 알림은 섹션이 현재 필터로 보여 주는 다음 행입니다. 목록으로 돌아가지 않고 인박스를 차례로 처리할 수 있습니다.diff --git a/apps/docs/content/docs/inbox.mdx b/apps/docs/content/docs/inbox.mdxindex 9dc69340c4..f18ed84294 100644--- a/apps/docs/content/docs/inbox.mdx+++ b/apps/docs/content/docs/inbox.mdx@@ -64,6 +64,7 @@ An issue opened from the inbox carries the inbox's actions in its header:- **Snooze** (`H`) takes the issue out of your inbox until a time you pick, and opens the next one. See [Snooze an issue](#snooze-an-issue) below.- **Mark as done** sets the issue to `done`, archives the notification, and opens the next one. It archives the notification even when **Archive issues you complete** is off. It's offered while the issue isn't done or cancelled yet.- **Archive** (`E`) archives the notification and opens the next one. Archiving doesn't modify or delete the issue.+- **Unsubscribe & archive** (`⇧E`) is offered on issues that aren't yours: not assigned to you or to an agent you own. It unsubscribes you from the issue, archives the notification and opens the next one. Ordinary updates stop reaching your inbox, while @mentions still do. On an issue with sub-issues you choose between this issue only and this issue with all its sub-issues. For this issue only, the confirmation offers **Undo**, which restores the subscription as it was. Leaving the sub-issues as well can't be undone there; subscribe again on the issue page instead. The same action is on the hover card and in a row's right-click menu.The next one is the next row the section lists under its current filters, so you can work through the inbox without going back to the list.diff --git a/apps/docs/content/docs/inbox.zh-Hant.mdx b/apps/docs/content/docs/inbox.zh-Hant.mdxindex 20c5382a26..8df2c66430 100644--- a/apps/docs/content/docs/inbox.zh-Hant.mdx+++ b/apps/docs/content/docs/inbox.zh-Hant.mdx@@ -64,6 +64,7 @@ import { InboxDemo } from "@/components/demos/inbox-demo";- **延後**(`H`)把任務移出收件箱,到你選的時間再回來,並開啟下一條。詳見下方的「延後任務」。- **標記為已完成**會把任務設為 `done`,歸檔這條通知,並開啟下一條。即使關閉了**自動歸檔我完成的任務**,它也會歸檔這條通知。任務尚未完成或取消時才會出現。- **歸檔**(`E`)會歸檔這條通知並開啟下一條。歸檔不會修改或刪除任務。+- **取消訂閱並歸檔**(`⇧E`):任務不是你的(負責人不是你,也不是你擁有的 AI 代理)時出現。它取消你對這個任務的訂閱,歸檔這條通知並開啟下一條;之後一般動態不再進入收件箱,@你仍會通知。有子任務時可以選擇只退訂這個任務,或連同全部子任務一起退訂。只退訂這個任務時,提示裡可以**復原**,訂閱會按原來的方式恢復;連同子任務一起退訂無法在這裡復原,可以在任務頁面重新訂閱。懸停卡片和列的右鍵選單裡也有這個操作。"下一條"是分區在當前篩選下列出的下一列,因此不用回到列表,就能把收件箱一條條處理完。diff --git a/apps/docs/content/docs/inbox.zh.mdx b/apps/docs/content/docs/inbox.zh.mdxindex 2f56d784c6..adec6e5d9d 100644--- a/apps/docs/content/docs/inbox.zh.mdx+++ b/apps/docs/content/docs/inbox.zh.mdx@@ -64,6 +64,7 @@ import { InboxDemo } from "@/components/demos/inbox-demo";- **延后**(`H`)把任务移出收件箱,到你选的时间再回来,并打开下一条。详见下方的「延后任务」。- **标记为已完成**会把任务设为 `done`,归档这条通知,并打开下一条。即使关闭了**自动归档我完成的任务**,它也会归档这条通知。任务尚未完成或取消时才会出现。- **归档**(`E`)会归档这条通知并打开下一条。归档不会修改或删除任务。+- **取消订阅并归档**(`⇧E`):任务不是你的(负责人不是你,也不是你拥有的智能体)时出现。它取消你对这个任务的订阅,归档这条通知并打开下一条;之后普通动态不再进入收件箱,@你仍会通知。有子任务时可以选择只退订这个任务,或连同全部子任务一起退订。只退订这个任务时,提示里可以**撤销**,订阅会按原来的方式恢复;连同子任务一起退订无法在这里撤销,可以在任务页面重新订阅。悬停卡片和行的右键菜单里也有这个操作。"下一条"是分区在当前筛选下列出的下一行,因此不用回到列表,就能把收件箱一条条处理完。diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex b4740996bb..52492cc59b 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -2040,6 +2040,15 @@ export class ApiClient {});}+ /**+ * Reverses the caller's own issue-only unsubscribe, restoring the+ * subscription with its original reason (or the project subscription that+ * covered it). Not a subscribe: that would make it a manual subscription.+ */+ async undoUnsubscribeFromIssue(issueId: string): Promise<void> {+ await this.fetch(`/api/issues/${issueId}/unsubscribe/undo`, { method: "POST" });+ }+// Agentsasync listAgents(params?: { workspace_id?: string; include_archived?: boolean }): Promise<Agent[]> {const search = new URLSearchParams();diff --git a/packages/core/inbox/mutations.test.tsx b/packages/core/inbox/mutations.test.tsxindex 3ca0d260a3..82884f646f 100644--- a/packages/core/inbox/mutations.test.tsx+++ b/packages/core/inbox/mutations.test.tsx@@ -9,9 +9,18 @@ import type { ReactNode } from "react";import { setApiInstance } from "../api";import type { ApiClient } from "../api/client";import type { InboxItem, InboxWorkspaceUnread } from "../types";-import { useDeleteInbox, useMarkInboxRead, useMarkInboxUnread, useMarkIssueInboxRead, useUnarchiveInbox } from "./mutations";+import {+ useDeleteInbox,+ useMarkInboxRead,+ useMarkInboxUnread,+ useMarkIssueInboxRead,+ useUnarchiveInbox,+ undoUnsubscribeArchiveInbox,+ useUnsubscribeArchiveInbox,+} from "./mutations";import { inboxKeys, useInboxUnreadCount } from "./queries";import { onInboxSummaryInvalidate } from "./ws-updaters";+import { issueKeys } from "../issues/queries";import { createQueryClient } from "../query-client";vi.mock("../hooks", () => ({@@ -536,3 +545,98 @@ describe("unread summary is server-owned", () => {},);});++describe("useUnsubscribeArchiveInbox", () => {+ function setup(api: Partial<ApiClient>) {+ const qc = createQueryClient();+ setApiInstance({ listInbox: vi.fn(() => new Promise(() => {})), ...api } as unknown as ApiClient);+ qc.setQueryData(inboxKeys.list(WORKSPACE_ID), [+ item({ id: "a", archived: false }),+ item({ id: "b", archived: false }),+ item({ id: "c", issue_id: "issue-2", archived: false }),+ ]);+ const { result } = renderHook(() => useUnsubscribeArchiveInbox(), { wrapper: createWrapper(qc) });+ return { qc, result };+ }++ it("leaves the issue before archiving and takes its rows out at once", async () => {+ const calls: string[] = [];+ const { qc, result } = setup({+ unsubscribeFromIssue: vi.fn(async (id: string) => { calls.push(`unsubscribe:${id}`); }),+ archiveInbox: vi.fn(async (id: string) => { calls.push(`archive:${id}`); return {} as never; }),+ });+ act(() => result.current.mutate({ id: "a", issueId: "issue-1", scope: "issue" }));+ await waitFor(() =>+ expect(listCache(qc).map((i) => [i.id, i.archived])).toEqual([["a", true], ["b", true], ["c", false]]),+ );+ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(calls).toEqual(["unsubscribe:issue-1", "archive:a"]);+ });++ it("uses the subtree opt-out for scope subtree and refreshes subscriber lists", async () => {+ const unsubscribeFromIssueSubtree = vi.fn(async () => {});+ const { qc, result } = setup({ unsubscribeFromIssueSubtree, archiveInbox: vi.fn(async () => ({}) as never) });+ qc.setQueryData(issueKeys.subscribers("issue-1"), []);+ act(() => result.current.mutate({ id: "a", issueId: "issue-1", scope: "subtree" }));+ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(unsubscribeFromIssueSubtree).toHaveBeenCalledWith("issue-1");+ expect(qc.getQueryState(issueKeys.subscribers("issue-1"))?.isInvalidated).toBe(true);+ });++ it("reports the result through its own callbacks after the caller unmounts", async () => {+ for (const fail of [false, true]) {+ let settle!: () => void;+ let reject!: (e: Error) => void;+ const request = new Promise<void>((res, rej) => { settle = res; reject = rej; });+ const qc = createQueryClient();+ setApiInstance({+ listInbox: vi.fn(() => new Promise(() => {})),+ listSubscribedIssueIds: vi.fn(async () => []),+ unsubscribeFromIssue: vi.fn(() => request),+ archiveInbox: vi.fn(async () => ({}) as never),+ } as unknown as ApiClient);+ const onSuccess = vi.fn();+ const onError = vi.fn();+ const { result, unmount } = renderHook(+ () => useUnsubscribeArchiveInbox({ onSuccess, onError }),+ { wrapper: createWrapper(qc) },+ );+ act(() => result.current.mutate({ id: "a", issueId: "issue-1", scope: "issue" }));+ unmount();+ await act(async () => { if (fail) reject(new Error("nope")); else settle(); });+ await waitFor(() => expect((fail ? onError : onSuccess)).toHaveBeenCalledOnce());+ expect(fail ? onSuccess : onError).not.toHaveBeenCalled();+ qc.clear();+ }+ });++ it("does not archive when the unsubscribe fails, and puts the rows back", async () => {+ const archiveInbox = vi.fn(async () => ({}) as never);+ const { qc, result } = setup({+ unsubscribeFromIssue: vi.fn(async () => { throw new Error("nope"); }),+ archiveInbox,+ });+ act(() => result.current.mutate({ id: "a", issueId: "issue-1", scope: "issue" }));+ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(archiveInbox).not.toHaveBeenCalled();+ expect(listCache(qc).every((i) => !i.archived)).toBe(true);+ });+});++describe("undoUnsubscribeArchiveInbox", () => {+ it("restores the subscription as it was, never by subscribing again, then the item", async () => {+ const calls: string[] = [];+ const qc = createQueryClient();+ const subscribeToIssue = vi.fn(async () => {});+ setApiInstance({+ subscribeToIssue,+ undoUnsubscribeFromIssue: vi.fn(async (id: string) => { calls.push(`undo:${id}`); }),+ unarchiveInbox: vi.fn(async (id: string) => { calls.push(`unarchive:${id}`); return {} as never; }),+ listInbox: vi.fn(() => new Promise(() => {})),+ listSubscribedIssueIds: vi.fn(async () => []),+ } as unknown as ApiClient);+ await undoUnsubscribeArchiveInbox(qc, WORKSPACE_ID, { id: "a", issueId: "issue-1" });+ expect(calls).toEqual(["undo:issue-1", "unarchive:a"]);+ expect(subscribeToIssue).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/inbox/mutations.ts b/packages/core/inbox/mutations.tsindex c9756a16b4..e1724b6e69 100644--- a/packages/core/inbox/mutations.ts+++ b/packages/core/inbox/mutations.ts@@ -4,6 +4,8 @@ import { api } from "../api";import { inboxKeys, mapArchivedInboxCache, patchArchivedInboxCaches, type ArchivedInboxCache } from "./queries";import { onInboxInvalidate, onInboxSummaryInvalidate } from "./ws-updaters";import { useWorkspaceId } from "../hooks";+import { issueKeys } from "../issues/queries";+import { refreshSubscribedIssues } from "../issues/subscribed";import type { InboxItem, SnoozedInboxIssue } from "../types";/**@@ -220,6 +222,88 @@ export function useUnarchiveInbox() {});}+export type InboxUnsubscribeScope = "issue" | "subtree";++/** Subscription state changed for the viewer: re-read everything derived from it. */+function refreshAfterSubscriptionWrite(qc: QueryClient, wsId: string) {+ refreshInboxAfterWrite(qc, wsId);+ qc.invalidateQueries({ queryKey: issueKeys.subscribersAll() });+ void refreshSubscribedIssues(qc, wsId);+}++/**+ * Leave the issue an inbox item is about, then archive the item: the one-step+ * "stop telling me about this" for issues the viewer is only watching.+ *+ * Unsubscribes first so a failed unsubscribe never archives — an archived row+ * whose issue keeps notifying would read as the action having worked. The row+ * leaves the list optimistically, like a plain archive.+ */+export interface UnsubscribeArchiveVariables {+ id: string;+ issueId: string;+ scope: InboxUnsubscribeScope;+}++/**+ * The callbacks are the mutation's own, not `mutate`'s: the surfaces that fire+ * this move on to the next notification at once, and per-call callbacks die+ * with the component that made the call, taking the confirmation and its Undo+ * (or the error) with them.+ */+export interface UnsubscribeArchiveCallbacks {+ onSuccess?: (variables: UnsubscribeArchiveVariables) => void;+ onError?: (error: Error, variables: UnsubscribeArchiveVariables) => void;+}++export function useUnsubscribeArchiveInbox(callbacks: UnsubscribeArchiveCallbacks = {}) {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: async ({ id, issueId, scope }: UnsubscribeArchiveVariables) => {+ if (scope === "subtree") await api.unsubscribeFromIssueSubtree(issueId);+ else await api.unsubscribeFromIssue(issueId);+ await api.archiveInbox(id);+ },+ onMutate: async ({ issueId }) => {+ await qc.cancelQueries({ queryKey: inboxKeys.list(wsId) });+ const prev = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));+ qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), (old) =>+ old?.map((item) => (item.issue_id === issueId ? { ...item, archived: true } : item)),+ );+ return { prev };+ },+ onSuccess: (_data, vars) => callbacks.onSuccess?.(vars),+ onError: (err, vars, ctx) => {+ if (ctx?.prev) qc.setQueryData(inboxKeys.list(wsId), ctx.prev);+ callbacks.onError?.(err, vars);+ },+ onSettled: () => refreshAfterSubscriptionWrite(qc, wsId),+ });+}++/**+ * Undo for `useUnsubscribeArchiveInbox` with scope "issue": restore the+ * subscription as it was, then the item. A plain function rather than a hook,+ * because it runs from a toast that outlives the page that showed it.+ *+ * Restoring is not subscribing again: that would rewrite a commenter, delegated+ * or project-inherited subscription to manual, and the issue would start+ * delivering more than it did before the user left it.+ */+export async function undoUnsubscribeArchiveInbox(+ qc: QueryClient,+ wsId: string,+ { id, issueId }: { id: string; issueId: string },+): Promise<void> {+ try {+ await api.undoUnsubscribeFromIssue(issueId);+ await api.unarchiveInbox(id);+ } finally {+ refreshAfterSubscriptionWrite(qc, wsId);+ }+}+export function useMarkAllInboxRead() {const qc = useQueryClient();const wsId = useWorkspaceId();diff --git a/packages/core/issues/ownership.test.ts b/packages/core/issues/ownership.test.tsnew file mode 100644index 0000000000..fa393062c6--- /dev/null+++ b/packages/core/issues/ownership.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from "vitest";+import { isOwnIssue } from "./ownership";++const agents = [+ { id: "agent-mine", owner_id: "me" },+ { id: "agent-theirs", owner_id: "someone" },+];++describe("isOwnIssue", () => {+ it("is the viewer's when assigned to them or to an agent they own", () => {+ expect(isOwnIssue({ assignee_type: "member", assignee_id: "me" }, "me", agents)).toBe(true);+ expect(isOwnIssue({ assignee_type: "agent", assignee_id: "agent-mine" }, "me", agents)).toBe(true);+ });++ it("is someone else's when assigned elsewhere, to a squad, or to nobody", () => {+ expect(isOwnIssue({ assignee_type: "member", assignee_id: "someone" }, "me", agents)).toBe(false);+ expect(isOwnIssue({ assignee_type: "agent", assignee_id: "agent-theirs" }, "me", agents)).toBe(false);+ expect(isOwnIssue({ assignee_type: "squad", assignee_id: "squad-1" }, "me", agents)).toBe(false);+ expect(isOwnIssue({ assignee_type: null, assignee_id: null }, "me", agents)).toBe(false);+ });++ it("is never the viewer's without a viewer", () => {+ expect(isOwnIssue({ assignee_type: "member", assignee_id: "me" }, null, agents)).toBe(false);+ });+});diff --git a/packages/core/issues/ownership.ts b/packages/core/issues/ownership.tsnew file mode 100644index 0000000000..4e823b6a10--- /dev/null+++ b/packages/core/issues/ownership.ts@@ -0,0 +1,22 @@+import type { Agent, IssueAssigneeType } from "../types";++/**+ * Whether an issue is the viewer's own work: assigned to them, or to an agent+ * they own. Everything else they watch they are only a bystander on, which is+ * where the inbox offers "unsubscribe & archive".+ *+ * Squad assignments count as someone else's: a squad is shared, and the+ * viewer being in it does not make every issue it picks up theirs.+ */+export function isOwnIssue(+ issue: { assignee_type?: IssueAssigneeType | null; assignee_id?: string | null },+ userId: string | null | undefined,+ agents: readonly Pick<Agent, "id" | "owner_id">[],+): boolean {+ if (!userId || !issue.assignee_id) return false;+ if (issue.assignee_type === "member") return issue.assignee_id === userId;+ if (issue.assignee_type === "agent") {+ return agents.some((agent) => agent.id === issue.assignee_id && agent.owner_id === userId);+ }+ return false;+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex ac2ed1f0bd..1517941556 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -56,6 +56,7 @@"./issues/run-steering": "./issues/run-steering.ts","./issues/unread": "./issues/unread.ts","./issues/subscribed": "./issues/subscribed.ts",+ "./issues/ownership": "./issues/ownership.ts","./issues/date": "./issues/date.ts","./issues/ws-updaters": "./issues/ws-updaters.ts","./issues/sidebar-list": "./issues/sidebar-list.ts",diff --git a/packages/core/shortcuts/definitions.ts b/packages/core/shortcuts/definitions.tsindex cb43ba41c7..3d1ac7836c 100644--- a/packages/core/shortcuts/definitions.ts+++ b/packages/core/shortcuts/definitions.ts@@ -14,6 +14,7 @@ export type ShortcutActionId =| "newChat"| "findInIssue"| "archiveInboxItem"+ | "unsubscribeArchiveInboxItem"| "snoozeInboxItem"| "send"| "voiceInput"@@ -111,6 +112,13 @@ export const SHORTCUT_ACTIONS: readonly ShortcutActionDefinition[] = [defaultShortcut: createShortcutChord("E"),allowInEditable: false,},+ // Shift on archive: "archive, and stop telling me about this issue".+ {+ id: "unsubscribeArchiveInboxItem",+ category: "general",+ defaultShortcut: createShortcutChord("E", { shift: true }),+ allowInEditable: false,+ },{id: "snoozeInboxItem",category: "general",diff --git a/packages/views/inbox/components/inbox-context-menu.test.tsx b/packages/views/inbox/components/inbox-context-menu.test.tsxindex 06bada0442..ad618e65ce 100644--- a/packages/views/inbox/components/inbox-context-menu.test.tsx+++ b/packages/views/inbox/components/inbox-context-menu.test.tsx@@ -158,6 +158,39 @@ describe("inbox row context menu", () => {expect(onAction).toHaveBeenCalledWith("inbox-3");});+ it("offers unsubscribe & archive on rows the page accepts", async () => {+ const onUnsubscribeArchive = vi.fn();+ const { row } = renderRow({+ entry: item({ id: "inbox-4" }),+ actions: { onUnsubscribeArchive, canUnsubscribe: () => true },+ });++ fireEvent.contextMenu(row);+ fireEvent.click(await screen.findByText("Unsubscribe & archive"));++ expect(onUnsubscribeArchive).toHaveBeenCalledWith("inbox-4");+ });++ it("omits unsubscribe & archive on the viewer's own issues", async () => {+ const { row } = renderRow({+ actions: { onUnsubscribeArchive: vi.fn(), canUnsubscribe: () => false },+ });+ fireEvent.contextMenu(row);+ expect(await screen.findByText("Archive")).toBeInTheDocument();+ expect(screen.queryByText("Unsubscribe & archive")).toBeNull();+ });++ it("omits unsubscribe & archive in the archived view", async () => {+ const { row } = renderRow({+ entry: item({ archived: true }),+ view: "archived",+ actions: { onUnsubscribeArchive: vi.fn(), canUnsubscribe: () => true },+ });+ fireEvent.contextMenu(row);+ expect(await screen.findByText("Unarchive")).toBeInTheDocument();+ expect(screen.queryByText("Unsubscribe & archive")).toBeNull();+ });+it("drops the read toggle in the archived view and offers unarchive", async () => {// Archived rows deliberately render as read and the unread count excludes// them, so a read toggle there would report success and change nothing.diff --git a/packages/views/inbox/components/inbox-item-actions.tsx b/packages/views/inbox/components/inbox-item-actions.tsxindex 5f4dcf2400..52077f903a 100644--- a/packages/views/inbox/components/inbox-item-actions.tsx+++ b/packages/views/inbox/components/inbox-item-actions.tsx@@ -1,6 +1,6 @@"use client";-import { Archive, ArchiveRestore, Check, CircleDot, ExternalLink, Trash2 } from "@multica/ui/icons";+import { Archive, ArchiveRestore, BellOff, Check, CircleDot, ExternalLink, Trash2 } from "@multica/ui/icons";import { paths, useWorkspaceSlug } from "@multica/core/paths";import type { InboxItem } from "@multica/core/types";import type { RowActionItem } from "../../common/row-actions-menu";@@ -18,6 +18,12 @@ export interface InboxRowActions {*/onAction: (id: string) => void;onDelete: (id: string) => void;+ /**+ * Unsubscribe & archive, offered in the main list on rows `canUnsubscribe`+ * accepts (issues that are not the viewer's own).+ */+ onUnsubscribeArchive?: (id: string) => void;+ canUnsubscribe?: (item: InboxItem) => boolean;}/**@@ -99,6 +105,16 @@ export function useInboxItemActions(),onSelect: () => actions.onAction(item.id),},+ ...(!isArchivedView && actions.onUnsubscribeArchive && actions.canUnsubscribe?.(item)+ ? [+ {+ key: "unsubscribe-archive",+ label: t(($) => $.context_menu.unsubscribe_archive),+ icon: <BellOff className="h-4 w-4" />,+ onSelect: () => actions.onUnsubscribeArchive?.(item.id),+ },+ ]+ : []),]);groups.push([diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsxindex c8251d1070..9b639ee2e0 100644--- a/packages/views/inbox/components/inbox-page.test.tsx+++ b/packages/views/inbox/components/inbox-page.test.tsx@@ -109,6 +109,8 @@ vi.mock("@multica/core/inbox/mutations", () => {useArchiveAllInbox: mutation,useArchiveAllReadInbox: mutation,useArchiveCompletedInbox: mutation,+ useUnsubscribeArchiveInbox: mutation,+ undoUnsubscribeArchiveInbox: vi.fn(),useRetrySourceContextQuickCreate: () => ({mutateAsync: retrySourceContextMutateAsync,isPending: false,diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex 7a9184f47a..f294f644a1 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -41,6 +41,7 @@ import {useArchiveAllReadInbox,useArchiveCompletedInbox,useRetrySourceContextQuickCreate,+ type InboxUnsubscribeScope,} from "@multica/core/inbox/mutations";import {effectiveInboxFilters,@@ -105,6 +106,7 @@ import { InboxList } from "./inbox-list";import { InboxFilterMenu } from "./inbox-filter-menu";import { InboxFilterChipsBar } from "./inbox-filter-options";import { InboxContextMenuProvider } from "./inbox-context-menu";+import { useInboxUnsubscribable, useUnsubscribeArchive } from "./use-unsubscribe-archive";import { ARCHIVED_VIEW_PARAM, type InboxView } from "./inbox-view";import { useTypeLabels } from "./inbox-detail-label";import {@@ -589,6 +591,15 @@ export function InboxPage() {});};+ const unsubscribable = useInboxUnsubscribable(wsId);+ const unsubscribeArchive = useUnsubscribeArchive();+ const handleUnsubscribeArchive = (id: string, scope: InboxUnsubscribeScope = "issue") => {+ const item = listedItems.find((i) => i.id === id);+ if (!item?.issue_id) return;+ advanceSelectionPast(id, listedItems);+ unsubscribeArchive({ id, issueId: item.issue_id }, scope);+ };+// Keep the listener stable while using the latest selected-item action.const actionOnSelectedRef = useRef<(() => void) | null>(null);useEffect(() => {@@ -809,6 +820,8 @@ export function InboxPage() {onMarkUnread: handleMarkUnread,onAction: isArchivedView ? handleUnarchive : handleArchive,onDelete: (id) => setDeleteTarget(selectionItems.find((item) => item.id === id) ?? null),+ onUnsubscribeArchive: handleUnsubscribeArchive,+ canUnsubscribe: unsubscribable,}}><InboxList@@ -950,6 +963,9 @@ export function InboxPage() {onDone={() => {handleArchive(detailItem.id);}}+ onUnsubscribeArchive={+ isArchivedView ? undefined : (scope) => handleUnsubscribeArchive(detailItem.id, scope)+ }/></IssuePeekHost></ErrorBoundary>diff --git a/packages/views/inbox/components/unsubscribe-archive-button.test.tsx b/packages/views/inbox/components/unsubscribe-archive-button.test.tsxnew file mode 100644index 0000000000..fd10a3b399--- /dev/null+++ b/packages/views/inbox/components/unsubscribe-archive-button.test.tsx@@ -0,0 +1,88 @@+import { describe, expect, it, vi } from "vitest";+import { fireEvent, screen, waitFor } from "@testing-library/react";+import { QueryClientProvider } from "@tanstack/react-query";+import { setApiInstance } from "@multica/core/api";+import type { ApiClient } from "@multica/core/api/client";+import { createQueryClient } from "@multica/core/query-client";+import type { Agent, Issue, IssueSubscriber } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));++import { UnsubscribeArchiveButton } from "./unsubscribe-archive-button";++const ISSUE_ID = "issue-1";++function setup({+ assignee = { assignee_type: "member", assignee_id: "someone" } as Partial<Issue>,+ subscribed = true,+ children = [] as Partial<Issue>[],+} = {}) {+ const issue = { id: ISSUE_ID, workspace_id: "ws-1", ...assignee } as Issue;+ const subscribers: IssueSubscriber[] = subscribed+ ? [{ issue_id: ISSUE_ID, user_type: "member", user_id: "me", reason: "commenter", created_at: "" }]+ : [];+ const agents = [{ id: "agent-mine", owner_id: "me" }] as Agent[];+ setApiInstance({+ getIssue: vi.fn(async () => issue),+ listAgents: vi.fn(async () => agents),+ listIssueSubscribers: vi.fn(async () => subscribers),+ listChildIssues: vi.fn(async () => ({ issues: children })),+ } as unknown as ApiClient);+ const onConfirm = vi.fn();+ renderWithI18n(+ <QueryClientProvider client={createQueryClient()}>+ <UnsubscribeArchiveButton issueId={ISSUE_ID} userId="me" onConfirm={onConfirm} />+ </QueryClientProvider>,+ );+ return { onConfirm };+}++// Without sub-issues the button acts directly, once the child count is known;+// until then it is the scope menu's trigger.+async function directButton() {+ return waitFor(() => {+ const button = screen.getByRole("button", { name: "Unsubscribe & archive" });+ expect(button).not.toHaveAttribute("aria-haspopup");+ return button;+ });+}++describe("UnsubscribeArchiveButton", () => {+ it("leaves just this issue on an issue that is someone else's", async () => {+ const { onConfirm } = setup();+ fireEvent.click(await directButton());+ expect(onConfirm).toHaveBeenCalledWith("issue");+ });++ it("runs on Shift+E", async () => {+ const { onConfirm } = setup();+ await directButton();+ fireEvent.keyDown(document.body, { key: "E", code: "KeyE", shiftKey: true });+ expect(onConfirm).toHaveBeenCalledWith("issue");+ });++ it("asks for the scope when the issue has sub-issues", async () => {+ const { onConfirm } = setup({ children: [{ id: "c1" }, { id: "c2" }] });+ const trigger = await screen.findByRole("button", { name: "Unsubscribe & archive" });+ await waitFor(() => expect(trigger).toHaveAttribute("aria-haspopup"));+ fireEvent.click(trigger);+ fireEvent.click(await screen.findByText("This issue and its 2 sub-issues"));+ expect(onConfirm).toHaveBeenCalledWith("subtree");+ });++ it.each([+ ["assigned to the viewer", { assignee_type: "member", assignee_id: "me" }],+ ["assigned to the viewer's agent", { assignee_type: "agent", assignee_id: "agent-mine" }],+ ] as const)("is not offered on an issue %s", async (_, assignee) => {+ setup({ assignee });+ await new Promise((r) => setTimeout(r, 50));+ expect(screen.queryByRole("button", { name: "Unsubscribe & archive" })).toBeNull();+ });++ it("is not offered when the viewer is not subscribed", async () => {+ setup({ subscribed: false });+ await new Promise((r) => setTimeout(r, 50));+ expect(screen.queryByRole("button", { name: "Unsubscribe & archive" })).toBeNull();+ });+});diff --git a/packages/views/inbox/components/unsubscribe-archive-button.tsx b/packages/views/inbox/components/unsubscribe-archive-button.tsxnew file mode 100644index 0000000000..438bc3cc86--- /dev/null+++ b/packages/views/inbox/components/unsubscribe-archive-button.tsx@@ -0,0 +1,136 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { BellOff, ListTree } from "@multica/ui/icons";+import { IconButton } from "@multica/ui/components/common/icon-button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import { useWorkspaceId } from "@multica/core/hooks";+import { useModalStore } from "@multica/core/modals";+import type { InboxUnsubscribeScope } from "@multica/core/inbox/mutations";+import { childIssuesOptions, issueDetailOptions, issueSubscribersOptions } from "@multica/core/issues/queries";+import { isOwnIssue } from "@multica/core/issues/ownership";+import { agentListOptions } from "@multica/core/workspace/queries";+import {+ getShortcut,+ isEditableShortcutTarget,+ isPortalLayerShortcutTarget,+ shortcutMatchesEvent,+} from "@multica/core/shortcuts";+import { isImeComposing } from "@multica/core/utils";+import { ActionShortcutKeycaps } from "../../common/shortcut-keycaps";+import { useT } from "../../i18n";++/**+ * "Unsubscribe & archive" in the header of an issue opened from the Inbox.+ *+ * Offered only where it is a bystander's way out: the viewer is subscribed,+ * and the issue is not assigned to them or to an agent they own. Renders+ * nothing until all of that is known, so it never flashes on an issue where+ * it does not belong.+ *+ * With sub-issues it asks for the scope, reusing the issue-only and subtree+ * opt-outs the Activity section offers. While the child count is still+ * loading it asks too, rather than picking a scope for the user.+ */+export function UnsubscribeArchiveButton({+ issueId,+ userId,+ onConfirm,+}: {+ issueId: string;+ /** The viewer. */+ userId: string | undefined;+ onConfirm: (scope: InboxUnsubscribeScope) => void;+}) {+ const { t } = useT("inbox");+ const wsId = useWorkspaceId();+ const { data: issue } = useQuery(issueDetailOptions(wsId, issueId));+ const { data: agents, isSuccess: agentsKnown } = useQuery(agentListOptions(wsId));+ const { data: subscribers, isSuccess: subscribersKnown } = useQuery(issueSubscribersOptions(issueId));+ const { data: children = [], isSuccess: childrenLoaded, isFetching: childrenFetching } = useQuery({+ ...childIssuesOptions(wsId, issueId),+ enabled: !!issue,+ });+ const [menuOpen, setMenuOpen] = useState(false);++ const subscribed = !!subscribers?.some((s) => s.user_type === "member" && s.user_id === userId);+ const offered =+ !!issue && agentsKnown && subscribersKnown && subscribed && !isOwnIssue(issue, userId, agents ?? []);+ const childCountKnown = childrenLoaded && !childrenFetching;+ const asksScope = !childCountKnown || children.length > 0;++ const shortcutRef = useRef<(() => void) | null>(null);+ useEffect(() => {+ shortcutRef.current = offered ? (asksScope ? () => setMenuOpen(true) : () => onConfirm("issue")) : null;+ });+ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.defaultPrevented || event.repeat || isImeComposing(event)) return;+ if (isEditableShortcutTarget(event.target)) return;+ if (isPortalLayerShortcutTarget(event.target)) return;+ if (useModalStore.getState().modal) return;+ if (!shortcutMatchesEvent(getShortcut("unsubscribeArchiveInboxItem"), event)) return;+ const run = shortcutRef.current;+ if (!run) return;+ event.preventDefault();+ run();+ };+ document.addEventListener("keydown", onKeyDown);+ return () => document.removeEventListener("keydown", onKeyDown);+ }, []);++ if (!offered) return null;++ const label = t(($) => $.context_menu.unsubscribe_archive);+ const shortcut = <ActionShortcutKeycaps action="unsubscribeArchiveInboxItem" />;++ if (!asksScope) {+ return (+ <IconButton+ label={label}+ shortcut={shortcut}+ tooltipSide="bottom"+ className="text-muted-foreground"+ onClick={() => onConfirm("issue")}+ >+ <BellOff />+ </IconButton>+ );+ }++ return (+ <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>+ <DropdownMenuTrigger+ render={+ <IconButton label={label} shortcut={shortcut} tooltipSide="bottom" className="text-muted-foreground" />+ }+ >+ <BellOff />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-auto">+ <DropdownMenuGroup>+ <DropdownMenuLabel>{t(($) => $.unsubscribe.title)}</DropdownMenuLabel>+ {/* onClick, not onSelect: Base UI's Menu.Item has no onSelect. */}+ <DropdownMenuItem onClick={() => onConfirm("issue")}>+ <BellOff />+ {t(($) => $.unsubscribe.this_issue)}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => onConfirm("subtree")}>+ <ListTree />+ {childCountKnown+ ? t(($) => $.unsubscribe.subtree, { count: children.length })+ : t(($) => $.unsubscribe.subtree_unknown)}+ </DropdownMenuItem>+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/packages/views/inbox/components/use-unsubscribe-archive.test.tsx b/packages/views/inbox/components/use-unsubscribe-archive.test.tsxnew file mode 100644index 0000000000..32454d3957--- /dev/null+++ b/packages/views/inbox/components/use-unsubscribe-archive.test.tsx@@ -0,0 +1,75 @@+import { afterEach, expect, it, vi } from "vitest";+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import { QueryClientProvider } from "@tanstack/react-query";+import { createQueryClient } from "@multica/core/query-client";+import { setApiInstance } from "@multica/core/api";+import type { ApiClient } from "@multica/core/api/client";+import { I18nProvider } from "@multica/core/i18n/react";+import { toast } from "sonner";+import enInbox from "../../locales/en/inbox.json";+import { useUnsubscribeArchive } from "./use-unsubscribe-archive";++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-review" }));+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));+afterEach(() => { cleanup(); vi.clearAllMocks(); });++it.each([[false, false], [false, true], [true, false], [true, true]])("reports completion (navigation=%s, failure=%s)", async (navigate, fail) => {+ const qc = createQueryClient();+ let finish!: () => void;+ let reject!: (error: Error) => void;+ const request = new Promise<void>((resolve, rejectRequest) => { finish = resolve; reject = rejectRequest; });+ const unsubscribe = vi.fn(() => request);+ const archive = vi.fn(async () => ({}));+ setApiInstance({+ unsubscribeFromIssue: unsubscribe,+ archiveInbox: archive,+ listSubscribedIssueIds: vi.fn(async () => []),+ } as unknown as ApiClient);+ const { result, unmount } = renderHook(() => useUnsubscribeArchive(), {+ wrapper: ({ children }) => <QueryClientProvider client={qc}>+ <I18nProvider locale="en" resources={{ en: { inbox: enInbox } }}>{children}</I18nProvider>+ </QueryClientProvider>,+ });+ act(() => result.current({ id: "notification-review", issueId: "issue-review" }));+ await waitFor(() => expect(unsubscribe).toHaveBeenCalled());+ if (navigate) unmount(); // IssueDetailRoute keys the containing IssuePeekHost by canonicalId.+ await act(async () => { if (fail) reject(new Error("request failed")); else finish(); });+ await waitFor(() => expect(qc.getMutationCache().getAll()[0]?.state.status).toBe(fail ? "error" : "success"));+ if (fail) {+ expect(archive).not.toHaveBeenCalled();+ expect(toast.error).toHaveBeenCalledOnce();+ } else {+ expect(archive).toHaveBeenCalledOnce();+ expect(toast.success).toHaveBeenCalledWith("Unsubscribed and archived", expect.objectContaining({+ action: expect.objectContaining({ label: "Undo" }),+ }));+ }+});++it("undoes from the toast after the page is gone by restoring, not subscribing", async () => {+ const qc = createQueryClient();+ const subscribeToIssue = vi.fn(async () => {});+ const undoUnsubscribeFromIssue = vi.fn(async () => {});+ const unarchiveInbox = vi.fn(async () => ({}));+ setApiInstance({+ unsubscribeFromIssue: vi.fn(async () => {}),+ archiveInbox: vi.fn(async () => ({})),+ subscribeToIssue,+ undoUnsubscribeFromIssue,+ unarchiveInbox,+ listSubscribedIssueIds: vi.fn(async () => []),+ } as unknown as ApiClient);+ const { result, unmount } = renderHook(() => useUnsubscribeArchive(), {+ wrapper: ({ children }) => <QueryClientProvider client={qc}>+ <I18nProvider locale="en" resources={{ en: { inbox: enInbox } }}>{children}</I18nProvider>+ </QueryClientProvider>,+ });+ act(() => result.current({ id: "notification-review", issueId: "issue-review" }));+ unmount();+ await waitFor(() => expect(toast.success).toHaveBeenCalledOnce());+ const options = vi.mocked(toast.success).mock.calls[0]![1] as unknown as { action: { onClick: () => void } };+ await act(async () => options.action.onClick());+ await waitFor(() => expect(unarchiveInbox).toHaveBeenCalledWith("notification-review"));+ expect(undoUnsubscribeFromIssue).toHaveBeenCalledWith("issue-review");+ expect(subscribeToIssue).not.toHaveBeenCalled();+});diff --git a/packages/views/inbox/components/use-unsubscribe-archive.ts b/packages/views/inbox/components/use-unsubscribe-archive.tsnew file mode 100644index 0000000000..aaed5cf6f6--- /dev/null+++ b/packages/views/inbox/components/use-unsubscribe-archive.ts@@ -0,0 +1,90 @@+"use client";++import { useCallback } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { useWorkspaceId } from "@multica/core/hooks";+import { isOwnIssue } from "@multica/core/issues/ownership";+import type { InboxItem } from "@multica/core/types";+import { agentListOptions } from "@multica/core/workspace/queries";+import {+ undoUnsubscribeArchiveInbox,+ useUnsubscribeArchiveInbox,+ type InboxUnsubscribeScope,+} from "@multica/core/inbox/mutations";+import { useT } from "../../i18n";++/**+ * Whether a list row offers "unsubscribe & archive": it is about an issue+ * that is not the viewer's own (see `isOwnIssue`). Rows from a server that+ * predates the issue projection carry no assignee and are not offered, since+ * an own issue cannot be told apart there.+ */+export function useInboxUnsubscribable(wsId: string) {+ const { data: agents, isSuccess } = useQuery(agentListOptions(wsId));+ return useCallback(+ (item: InboxItem) =>+ !!item.issue_id &&+ isSuccess &&+ item.recipient_type === "member" &&+ item.issue_assignee_type !== undefined &&+ !isOwnIssue(+ { assignee_type: item.issue_assignee_type, assignee_id: item.issue_assignee_id },+ item.recipient_id,+ agents ?? [],+ ),+ [isSuccess, agents],+ );+}++export interface UnsubscribeArchiveTarget {+ /** The inbox item to archive. */+ id: string;+ /** The issue to leave. */+ issueId: string;+}++/**+ * "Unsubscribe & archive" with the confirmation every surface shares. Undo is+ * offered for a single issue only: a subtree opt-out tombstones every+ * descendant, and one issue's undo would not bring those back.+ *+ * The toasts hang off the mutation itself, not the `mutate` call: every+ * surface moves on to the next notification straight away, which unmounts the+ * caller before the request settles.+ */+export function useUnsubscribeArchive() {+ const { t } = useT("inbox");+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ const failed = (fallback: string) => (err: unknown) =>+ toast.error(err instanceof Error && err.message ? err.message : fallback);+ const { mutate } = useUnsubscribeArchiveInbox({+ onSuccess: ({ id, issueId, scope }) =>+ toast.success(+ scope === "subtree"+ ? t(($) => $.toasts.unsubscribed_archived_subtree)+ : t(($) => $.toasts.unsubscribed_archived),+ {+ description: t(($) => $.toasts.unsubscribed_hint),+ action:+ scope === "issue"+ ? {+ label: t(($) => $.toasts.undo),+ onClick: () => {+ undoUnsubscribeArchiveInbox(qc, wsId, { id, issueId }).catch(+ failed(t(($) => $.errors.undo_unsubscribe_failed)),+ );+ },+ }+ : undefined,+ },+ ),+ onError: failed(t(($) => $.errors.unsubscribe_archive_failed)),+ });+ return useCallback(+ (target: UnsubscribeArchiveTarget, scope: InboxUnsubscribeScope = "issue") =>+ mutate({ ...target, scope }),+ [mutate],+ );+}diff --git a/packages/views/issues/actions/__tests__/issue-inbox-actions.test.tsx b/packages/views/issues/actions/__tests__/issue-inbox-actions.test.tsxindex 8636d64512..d66d859f03 100644--- a/packages/views/issues/actions/__tests__/issue-inbox-actions.test.tsx+++ b/packages/views/issues/actions/__tests__/issue-inbox-actions.test.tsx@@ -8,13 +8,16 @@ import type { ApiClient } from "@multica/core/api/client";import { useInboxFilterStore } from "@multica/core/inbox/filter-store";import { inboxListOptions, snoozedInboxOptions } from "@multica/core/inbox/queries";import { useInboxSelectionStore } from "@multica/core/inbox/selection-store";-import type { InboxItem, SnoozedInboxIssue } from "@multica/core/types";+import { childIssuesOptions, issueDetailOptions, issueSubscribersOptions } from "@multica/core/issues/queries";+import { agentListOptions } from "@multica/core/workspace/queries";+import type { InboxItem, Issue, SnoozedInboxIssue } from "@multica/core/types";import { renderWithI18n } from "../../../test/i18n";import { NavigationProvider, type NavigationAdapter } from "../../../navigation";import { IssueInboxActions } from "../issue-inbox-actions";const state = vi.hoisted(() => ({archiveInbox: vi.fn(),+ unsubscribeArchive: vi.fn(),snooze: vi.fn(() => Promise.resolve()),unsnooze: vi.fn(() => Promise.resolve()),}));@@ -29,6 +32,8 @@ vi.mock("@multica/core/paths", async (importOriginal) => {// per-call callbacks when the next issue's page replaces the header.vi.mock("@multica/core/inbox/mutations", async (importOriginal) => ({...(await importOriginal<typeof import("@multica/core/inbox/mutations")>()),+ useUnsubscribeArchiveInbox: () => ({ mutate: state.unsubscribeArchive }),+ undoUnsubscribeArchiveInbox: vi.fn(),useSnoozeInbox: () => ({ mutateAsync: state.snooze }),useUnsnoozeInbox: () => ({ mutateAsync: state.unsnooze }),cachedInboxSnoozedUntil: () => null,@@ -68,11 +73,14 @@ function setup({issueId = "issue-1",onMarkDone,snoozed = [],+ theirs = false,}: {rows?: InboxItem[];issueId?: string;onMarkDone?: (onSaved: () => void) => void;snoozed?: SnoozedInboxIssue[];+ /** The viewer follows the issue, and someone else owns it. */+ theirs?: boolean;} = {}) {const nav: NavigationAdapter = {push: vi.fn(),@@ -89,6 +97,8 @@ function setup({listSnoozedInbox: async () => snoozed,getInboxUnreadSummary: async () => [],getAgentTaskSnapshot: async () => [],+ // The child list refetches on mount; the unsubscribe button acts directly once it is known.+ listChildIssues: async () => ({ issues: [] }),} as unknown as ApiClient);const qc = new QueryClient({defaultOptions: { queries: { retry: false, staleTime: Infinity }, mutations: { retry: false } },@@ -96,6 +106,18 @@ function setup({qc.setQueryData(inboxListOptions("ws").queryKey, rows);qc.setQueryData(snoozedInboxOptions("ws").queryKey, snoozed);qc.setQueryData(agentTaskSnapshotOptions("ws").queryKey, []);+ if (theirs) {+ qc.setQueryData(issueDetailOptions("ws", issueId).queryKey, {+ id: issueId,+ assignee_type: "member",+ assignee_id: "member-other",+ } as Issue);+ qc.setQueryData(agentListOptions("ws").queryKey, []);+ qc.setQueryData(issueSubscribersOptions(issueId).queryKey, [+ { issue_id: issueId, user_type: "member", user_id: "member-1", reason: "commenter", created_at: SNOOZED_AT },+ ]);+ qc.setQueryData(childIssuesOptions("ws", issueId).queryKey, []);+ }const page = (id: string | null) => (<QueryClientProvider client={qc}><NavigationProvider value={nav}>@@ -292,4 +314,42 @@ describe("IssueInboxActions", () => {fireEvent.keyDown(document, { key: "e", code: "KeyE" });await waitFor(() => expect(state.archiveInbox).toHaveBeenCalledWith("n-1"));});++ // Snooze, archive and unsubscribe share the header; each key does only its own.+ async function setupTheirs() {+ const nav = setup({ theirs: true });+ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Unsubscribe & archive" })).not.toHaveAttribute("aria-haspopup"),+ );+ return nav;+ }++ it("unsubscribes and moves on with Shift+E on someone else's issue", async () => {+ const nav = await setupTheirs();+ fireEvent.keyDown(document, { key: "E", code: "KeyE", shiftKey: true });+ expect(state.unsubscribeArchive).toHaveBeenCalledWith({ id: "n-1", issueId: "issue-1", scope: "issue" });+ await act(async () => {});+ expect(state.archiveInbox).not.toHaveBeenCalled();+ expect(nav.push).toHaveBeenCalledWith("/acme/issues/issue-2#comment-c-9");+ });++ it("still only archives with E there", async () => {+ await setupTheirs();+ fireEvent.keyDown(document, { key: "e", code: "KeyE" });+ await waitFor(() => expect(state.archiveInbox).toHaveBeenCalledWith("n-1"));+ expect(state.unsubscribeArchive).not.toHaveBeenCalled();+ });++ it("still only snoozes with H there", async () => {+ await setupTheirs();+ fireEvent.keyDown(document, { key: "h", code: "KeyH" });+ expect(await screen.findByRole("menuitem", { name: /^1 hour/ })).toBeInTheDocument();+ expect(state.unsubscribeArchive).not.toHaveBeenCalled();+ expect(state.archiveInbox).not.toHaveBeenCalled();+ });++ it("offers no unsubscribe on an issue the viewer does not follow as a bystander", () => {+ setup();+ expect(screen.queryByRole("button", { name: "Unsubscribe & archive" })).toBeNull();+ });});diff --git a/packages/views/issues/actions/issue-inbox-actions.tsx b/packages/views/issues/actions/issue-inbox-actions.tsxindex 8d6ed39db5..ce45e24b3e 100644--- a/packages/views/issues/actions/issue-inbox-actions.tsx+++ b/packages/views/issues/actions/issue-inbox-actions.tsx@@ -9,7 +9,7 @@ import { cn } from "@multica/ui/lib/utils";import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";import { useModalStore } from "@multica/core/modals";-import { useArchiveInbox } from "@multica/core/inbox/mutations";+import { useArchiveInbox, type InboxUnsubscribeScope } from "@multica/core/inbox/mutations";import { findSnoozedInboxIssue, snoozedInboxOptions } from "@multica/core/inbox/queries";import { useInboxSelectionStore } from "@multica/core/inbox/selection-store";import {@@ -26,14 +26,16 @@ import { formatSnoozeTime } from "../../inbox/components/inbox-snooze-time";import { useInboxSnooze } from "../../inbox/components/use-inbox-snooze";import { useFilteredInboxRows } from "../../inbox/components/use-filtered-inbox-rows";import { useSidebarInboxIssue } from "../../inbox/components/use-sidebar-inbox-issue";+import { UnsubscribeArchiveButton } from "../../inbox/components/unsubscribe-archive-button";+import { useUnsubscribeArchive } from "../../inbox/components/use-unsubscribe-archive";import { useNavigation } from "../../navigation";import { useLocale, useT } from "../../i18n";/*** The Inbox's actions in the header of an issue opened from the Work panel's* Inbox section, while the section still lists it. Marking it done,- * snoozing or archiving opens the next notification the section lists, so- * the Inbox can be worked through without leaving the page.+ * snoozing, archiving or unsubscribing opens the next notification the+ * section lists, so the Inbox can be worked through without leaving the page.** A snoozed issue shows when it comes back instead, wherever it is opened,* with the way to bring it back now or change the time.@@ -59,6 +61,7 @@ export function IssueInboxActions({const index = fromInbox ? rows.findIndex((row) => row.issue_id === issueId) : -1;const item = index >= 0 ? rows[index]! : null;const { mutateAsync: archiveAsync } = useArchiveInbox();+ const unsubscribeArchive = useUnsubscribeArchive();const { snooze, unsnooze } = useInboxSnooze();const { data: snoozedList } = useQuery(snoozedInboxOptions(wsId));const snoozed = item ? undefined : findSnoozedInboxIssue(snoozedList, issueId);@@ -86,6 +89,13 @@ export function IssueInboxActions({openNext(next);};+ const unsubscribeItem = (scope: InboxUnsubscribeScope) => {+ if (!item?.issue_id) return;+ const next = rows[index + 1] ?? rows[index - 1] ?? null;+ unsubscribeArchive({ id: item.id, issueId: item.issue_id }, scope);+ openNext(next);+ };+const snoozeItem = (until: Date) => {if (!item) return;const next = rows[index + 1] ?? rows[index - 1] ?? null;@@ -148,6 +158,7 @@ export function IssueInboxActions({return (<>+ <UnsubscribeArchiveButton issueId={issueId} userId={item.recipient_id} onConfirm={unsubscribeItem} />{onMarkDone && (<IconButtonlabel={tIssues(($) => $.detail.mark_done_tooltip)}diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex e266b59f15..6dae2b169a 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -76,6 +76,8 @@ import { ActorAvatar } from "../../common/actor-avatar";import { MemberProfileCard } from "../../members/member-profile-card";import { HoverCard, HoverCardTrigger, HoverCardContent } from "@multica/ui/components/ui/hover-card";import { ActionShortcutKeycaps } from "../../common/shortcut-keycaps";+import { UnsubscribeArchiveButton } from "../../inbox/components/unsubscribe-archive-button";+import type { InboxUnsubscribeScope } from "@multica/core/inbox/mutations";import { PropRow } from "../../common/prop-row";import { TimelineHandoff } from "../../workflows/timeline-handoff";import { PropertyIcon } from "../../common/property-icon";@@ -1221,6 +1223,11 @@ interface IssueDetailProps {onDelete?: () => void;/** Called after the issue is marked as done via the toolbar button. */onDone?: () => void;+ /**+ * The Inbox's "unsubscribe & archive", shown next to Done on issues that+ * are not the viewer's own. Only read alongside `onDone`.+ */+ onUnsubscribeArchive?: (scope: InboxUnsubscribeScope) => void;defaultSidebarOpen?: boolean;layoutId?: string;/** When set, the issue detail will auto-scroll to this comment and briefly highlight it. */@@ -1471,7 +1478,7 @@ export function IssueDetailSkeleton({// IssueDetail-export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = ISSUE_DETAIL_LAYOUT_ID, highlightCommentId: linkedCommentId, highlightRequestToken: linkedRequestToken, highlightAppRequestId, leadingAction, variant = "page", trailingActions, readsInbox = true, skipInitialRefetch = false, openDeliverable, onDeliverableLinkDone }: IssueDetailProps) {+export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, defaultSidebarOpen = true, layoutId = ISSUE_DETAIL_LAYOUT_ID, highlightCommentId: linkedCommentId, highlightRequestToken: linkedRequestToken, highlightAppRequestId, leadingAction, variant = "page", trailingActions, readsInbox = true, skipInitialRefetch = false, openDeliverable, onDeliverableLinkDone }: IssueDetailProps) {const isPeek = variant === "peek";const { t } = useT("issues");const { t: tCommon } = useT("common");@@ -3589,6 +3596,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr}/>)}+ {onDone && onUnsubscribeArchive && (+ <UnsubscribeArchiveButton issueId={id} userId={user?.id} onConfirm={onUnsubscribeArchive} />+ )}{onDone && !issueBehavesAsAny(issue, ["done", "closed"]) && (<IconButtonlabel={t(($) => $.detail.mark_done_tooltip)}diff --git a/packages/views/layout/panels/inbox-section.test.tsx b/packages/views/layout/panels/inbox-section.test.tsxindex bb70b7a64f..355e4a832c 100644--- a/packages/views/layout/panels/inbox-section.test.tsx+++ b/packages/views/layout/panels/inbox-section.test.tsx@@ -9,7 +9,8 @@ import {import { useInboxFilterStore } from "@multica/core/inbox/filter-store";import { useInboxSelectionStore } from "@multica/core/inbox/selection-store";import { agentTaskSnapshotOptions } from "@multica/core/agents";-import type { AgentTask, InboxItem, SnoozedInboxIssue } from "@multica/core/types";+import type { Agent, AgentTask, InboxItem, SnoozedInboxIssue } from "@multica/core/types";+import { agentListOptions } from "@multica/core/workspace/queries";import { snoozedInboxOptions } from "@multica/core/inbox/queries";import { renderWithI18n } from "../../test/i18n";import { NavigationProvider, type NavigationAdapter } from "../../navigation";@@ -19,6 +20,7 @@ const state = vi.hoisted(() => ({unread: 0,compact: false,archive: vi.fn(),+ unsubscribeArchive: vi.fn(),markAllRead: vi.fn(),archiveAll: vi.fn(),archiveAllRead: vi.fn(),@@ -45,6 +47,8 @@ vi.mock("@multica/core/inbox/mutations", () => ({useArchiveCompletedInbox: () => ({ mutate: state.archiveCompleted }),useMarkInboxRead: () => ({ mutate: state.markRead }),useMarkInboxUnread: () => ({ mutate: state.markUnread }),+ useUnsubscribeArchiveInbox: () => ({ mutate: state.unsubscribeArchive }),+ undoUnsubscribeArchiveInbox: vi.fn(),useSnoozeInbox: () => ({ mutateAsync: state.snooze }),useUnsnoozeInbox: () => ({ mutateAsync: state.unsnooze }),cachedInboxSnoozedUntil: () => null,@@ -114,10 +118,12 @@ function renderSection(url = "/acme/issues",tasks: Partial<AgentTask>[] = [],snoozed: SnoozedInboxIssue[] = [],+ agents: Pick<Agent, "id" | "owner_id">[] = [],) {const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });client.setQueryData(["inbox", "ws-1", "list"], items);client.setQueryData(snoozedInboxOptions("ws-1").queryKey, snoozed);+ client.setQueryData(agentListOptions("ws-1").queryKey, agents as Agent[]);client.setQueryData(agentTaskSnapshotOptions("ws-1").queryKey, tasks as AgentTask[]);const nav = adapter(url);// As the Work panel keys it: the issue opened from the section, or the Inbox page's notification.@@ -334,6 +340,31 @@ describe("InboxSection", () => {expect(state.archive).toHaveBeenCalledWith("n1");});+ it("offers unsubscribe & archive on the card only for issues that are not the viewer's", async () => {+ renderSection(+ [+ item({ id: "n1", issue_id: "issue-a", title: "Theirs", body: "Their comment", issue_assignee_type: "agent", issue_assignee_id: "agent-x" }),+ item({ id: "n2", issue_id: "issue-b", title: "Mine", body: "My comment", issue_assignee_type: "agent", issue_assignee_id: "agent-mine" }),+ ],+ null,+ "/acme/issues",+ [],+ [],+ [{ id: "agent-x", owner_id: "someone" }, { id: "agent-mine", owner_id: "member-1" }],+ );+ const label = "Unsubscribe & archive";++ fireEvent.mouseEnter(rows()[1]!.firstElementChild!);+ const mine = await screen.findByText("My comment", { selector: "[data-inbox-card] p" }, { timeout: 2000 });+ expect(within(mine.closest<HTMLElement>("[data-inbox-card]")!).queryByRole("button", { name: label })).toBeNull();+ fireEvent.mouseLeave(rows()[1]!.firstElementChild!);++ fireEvent.mouseEnter(rows()[0]!.firstElementChild!);+ const theirs = await screen.findByText("Their comment", { selector: "[data-inbox-card] p" }, { timeout: 2000 });+ fireEvent.click(within(theirs.closest<HTMLElement>("[data-inbox-card]")!).getByRole("button", { name: label }));+ expect(state.unsubscribeArchive).toHaveBeenCalledWith({ id: "n1", issueId: "issue-a", scope: "issue" });+ });+it("closes the card when the row is pressed, and keeps a pending hover from reopening it", async () => {renderSection([item({ id: "n1", issue_id: "issue-a", title: "Commented", body: "Ship it on Friday" })]);const trigger = rows()[0]!.firstElementChild!;diff --git a/packages/views/layout/panels/inbox-section.tsx b/packages/views/layout/panels/inbox-section.tsxindex cbe8131f2b..2bb34858fb 100644--- a/packages/views/layout/panels/inbox-section.tsx+++ b/packages/views/layout/panels/inbox-section.tsx@@ -3,7 +3,8 @@import { type ReactNode, useMemo, useState } from "react";import { useQuery } from "@tanstack/react-query";import { toast } from "sonner";-import { AlarmClock, Archive, BookCheck, CheckCheck, History, ListChecks, MoreHorizontal } from "@multica/ui/icons";+import { AlarmClock, Archive, BellOff, BookCheck, CheckCheck, History, ListChecks, MoreHorizontal } from "@multica/ui/icons";+import { IconButton } from "@multica/ui/components/common/icon-button";import { cn } from "@multica/ui/lib/utils";import { useIsCompact } from "@multica/ui/hooks/use-mobile";import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";@@ -51,6 +52,7 @@ import { useInboxSnooze } from "../../inbox/components/use-inbox-snooze";import { useBuiltinViewNavigation } from "../../issue-views/builtin-views";import { useFilteredInboxRows } from "../../inbox/components/use-filtered-inbox-rows";import { useTimeAgo } from "../../inbox/components/inbox-list-item";+import { useInboxUnsubscribable, useUnsubscribeArchive } from "../../inbox/components/use-unsubscribe-archive";import { StatusIcon } from "../../issues/components";import { useStatusLabel } from "../../issues/utils/status-label";import {@@ -146,6 +148,8 @@ export function InboxSection({const compact = useSidebarTreeStore((s) => s.inboxSettings.compact);const unread = useInboxUnreadCount(wsId);const archive = useArchiveInbox();+ const unsubscribable = useInboxUnsubscribable(wsId);+ const unsubscribeArchive = useUnsubscribeArchive();const { snooze } = useInboxSnooze();const { searchParams } = useNavigation();const isCompact = useIsCompact();@@ -203,6 +207,11 @@ export function InboxSection({compact={compact}updatesWhileSnoozed={item.issue_id ? (updatesWhileSnoozed.get(item.issue_id) ?? 0) : 0}onArchive={() => archive.mutate(item.id)}+ onUnsubscribe={+ item.issue_id && unsubscribable(item)+ ? () => unsubscribeArchive({ id: item.id, issueId: item.issue_id! })+ : undefined+ }onSnooze={(until) => snooze(item, until)}/>))}@@ -350,6 +359,7 @@ function InboxRow({compact,updatesWhileSnoozed,onArchive,+ onUnsubscribe,onSnooze,}: {item: InboxItem;@@ -360,6 +370,8 @@ function InboxRow({/** Notifications that arrived while the issue was snoozed. */updatesWhileSnoozed: number;onArchive: () => void;+ /** Unsubscribe & archive; only for issues that are not the viewer's own. */+ onUnsubscribe?: () => void;onSnooze: (until: Date) => void;}) {const { t } = useT("inbox");@@ -537,6 +549,7 @@ function InboxRow({land();}}onArchive={onArchive}+ onUnsubscribe={onUnsubscribe}onSnooze={item.issue_id? () => {@@ -649,6 +662,7 @@ function InboxRowCard({title,onOpen,onArchive,+ onUnsubscribe,onSnooze,}: {item: InboxItem;@@ -656,6 +670,7 @@ function InboxRowCard({title: string;onOpen: () => void;onArchive: () => void;+ onUnsubscribe?: () => void;/** Opens the row's snooze menu; issue rows only. */onSnooze?: () => void;}) {@@ -719,6 +734,15 @@ function InboxRowCard({<Button size="sm" variant="ghost" className="text-muted-foreground" onClick={onArchive}>{tInbox(($) => $.context_menu.archive)}</Button>+ {onUnsubscribe && (+ <IconButton+ label={tInbox(($) => $.context_menu.unsubscribe_archive)}+ className="ml-auto text-muted-foreground"+ onClick={onUnsubscribe}+ >+ <BellOff />+ </IconButton>+ )}</div></div>);diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.jsonindex 48d6ca2c2e..8b9c252412 100644--- a/packages/views/locales/en/inbox.json+++ b/packages/views/locales/en/inbox.json@@ -42,7 +42,8 @@"archive": "Archive","unarchive": "Unarchive","open_in_new_tab": "Open in new tab",- "delete": "Delete"+ "delete": "Delete",+ "unsubscribe_archive": "Unsubscribe & archive"},"list": {"loading_selection": "Loading notification…",@@ -125,7 +126,11 @@"source_context_retry_started": "Retry started with the original context","archived": "Notification archived","unarchived": "Notification restored",- "deleted": "Notification deleted"+ "deleted": "Notification deleted",+ "unsubscribed_archived": "Unsubscribed and archived",+ "unsubscribed_archived_subtree": "Unsubscribed from this issue and its sub-issues",+ "unsubscribed_hint": "Its updates won't reach your inbox. @mentions still will.",+ "undo": "Undo"},"errors": {"archived_lookup_failed": "Failed to load the linked notification",@@ -142,7 +147,9 @@"unarchive_failed": "Failed to unarchive","archived_load_failed": "Failed to load archived notifications","filters_load_failed": "Could not load filters",- "delete_failed": "Failed to delete notification. Try again."+ "delete_failed": "Failed to delete notification. Try again.",+ "unsubscribe_archive_failed": "Failed to unsubscribe",+ "undo_unsubscribe_failed": "Failed to undo"},"delete_dialog": {"title": "Delete notification?",@@ -151,6 +158,13 @@"cancel": "Cancel","active_issue_description": "This permanently deletes the active notifications for this issue. Previously archived notifications remain and will be visible again in Archived. The issue and its runs are kept."},+ "unsubscribe": {+ "title": "Unsubscribe and archive. Its updates stop reaching you; an @mention still does.",+ "this_issue": "This issue only",+ "subtree_one": "This issue and its {{count}} sub-issue",+ "subtree_other": "This issue and its {{count}} sub-issues",+ "subtree_unknown": "This issue and its sub-issues"+ },"snooze": {"action": "Snooze","menu_title": "Snooze until…",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex abc450ee5e..a34d81c241 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -432,6 +432,10 @@"label": "Archive notification","description": "Archive the open inbox notification, or restore it while reading the archive."},+ "unsubscribeArchiveInboxItem": {+ "label": "Unsubscribe & archive",+ "description": "Leave the open notification's issue and archive it. Offered on issues that are not yours or your agents'."+ },"snoozeInboxItem": {"label": "Snooze notification","description": "Snooze the open inbox issue, or bring it back now if it is snoozed."diff --git a/packages/views/locales/es/inbox.json b/packages/views/locales/es/inbox.jsonindex c41ec2b4ff..dfe7bbf985 100644--- a/packages/views/locales/es/inbox.json+++ b/packages/views/locales/es/inbox.json@@ -42,7 +42,8 @@"archive": "Archivar","unarchive": "Desarchivar","open_in_new_tab": "Abrir en una pestaña nueva",- "delete": "Eliminar"+ "delete": "Eliminar",+ "unsubscribe_archive": "Darse de baja y archivar"},"list": {"loading_selection": "Cargando notificación…",@@ -125,7 +126,11 @@"source_context_retry_started": "Reintento iniciado con el contexto original","archived": "Notificación archivada","unarchived": "Notificación restaurada",- "deleted": "Notificación eliminada"+ "deleted": "Notificación eliminada",+ "unsubscribed_archived": "Baja y archivo hechos",+ "unsubscribed_archived_subtree": "Te diste de baja de esta tarea y sus subtareas",+ "unsubscribed_hint": "Sus actualizaciones no llegarán a tu bandeja. Las @menciones sí.",+ "undo": "Deshacer"},"errors": {"archived_lookup_failed": "No se ha podido cargar la notificación enlazada",@@ -142,7 +147,9 @@"unarchive_failed": "No se ha podido desarchivar","archived_load_failed": "No se han podido cargar las notificaciones archivadas","filters_load_failed": "No se han podido cargar los filtros",- "delete_failed": "No se pudo eliminar la notificación. Inténtalo de nuevo."+ "delete_failed": "No se pudo eliminar la notificación. Inténtalo de nuevo.",+ "unsubscribe_archive_failed": "No se pudo dar de baja",+ "undo_unsubscribe_failed": "No se pudo deshacer"},"delete_dialog": {"title": "¿Eliminar notificación?",@@ -151,6 +158,13 @@"cancel": "Cancelar","active_issue_description": "Las notificaciones activas de esta tarea se eliminarán permanentemente. Las notificaciones archivadas anteriormente se conservarán y volverán a aparecer en Archivadas. La tarea y sus ejecuciones se conservarán."},+ "unsubscribe": {+ "title": "Darse de baja y archivar. Dejarás de recibir sus actualizaciones; las @menciones te seguirán llegando.",+ "this_issue": "Solo esta tarea",+ "subtree_one": "Esta tarea y su {{count}} subtarea",+ "subtree_other": "Esta tarea y sus {{count}} subtareas",+ "subtree_unknown": "Esta tarea y sus subtareas"+ },"snooze": {"action": "Posponer","menu_title": "Posponer hasta…",diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex 07b5473c7a..432651242b 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -432,6 +432,10 @@"label": "Archivar notificación","description": "Archiva la notificación de la bandeja abierta, o restaúrala mientras lees el archivo."},+ "unsubscribeArchiveInboxItem": {+ "label": "Darse de baja y archivar",+ "description": "Date de baja de la tarea de la notificación abierta y archívala. Disponible en tareas que no son tuyas ni de tus agentes."+ },"snoozeInboxItem": {"label": "Posponer notificación","description": "Pospone el issue abierto de la bandeja, o lo recupera ahora si ya está pospuesto."diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.jsonindex a8a99511e6..30f28648e9 100644--- a/packages/views/locales/fr/inbox.json+++ b/packages/views/locales/fr/inbox.json@@ -42,7 +42,8 @@"archive": "Archiver","unarchive": "Désarchiver","open_in_new_tab": "Ouvrir dans un nouvel onglet",- "delete": "Supprimer"+ "delete": "Supprimer",+ "unsubscribe_archive": "Se désabonner et archiver"},"list": {"loading_selection": "Chargement de la notification…",@@ -125,7 +126,11 @@"source_context_retry_started": "Nouvelle tentative démarrée avec le contexte d'origine","archived": "Notification archivée","unarchived": "Notification restaurée",- "deleted": "Notification supprimée"+ "deleted": "Notification supprimée",+ "unsubscribed_archived": "Désabonné et archivé",+ "unsubscribed_archived_subtree": "Désabonné de cette tâche et de ses sous-tâches",+ "unsubscribed_hint": "Ses mises à jour n'arriveront plus dans votre boîte de réception. Les @mentions, si.",+ "undo": "Annuler"},"errors": {"archived_lookup_failed": "Échec du chargement de la notification liée",@@ -142,7 +147,9 @@"unarchive_failed": "Échec du désarchivage","archived_load_failed": "Échec du chargement des notifications archivées","filters_load_failed": "Impossible de charger les filtres",- "delete_failed": "Impossible de supprimer la notification. Réessayez."+ "delete_failed": "Impossible de supprimer la notification. Réessayez.",+ "unsubscribe_archive_failed": "Échec du désabonnement",+ "undo_unsubscribe_failed": "Échec de l'annulation"},"delete_dialog": {"title": "Supprimer la notification ?",@@ -151,6 +158,13 @@"cancel": "Annuler","active_issue_description": "Les notifications actives de cette tâche seront supprimées définitivement. Les notifications précédemment archivées seront conservées et réapparaîtront dans les archives. La tâche et ses exécutions seront conservées."},+ "unsubscribe": {+ "title": "Se désabonner et archiver. Ses mises à jour ne vous parviendront plus ; les @mentions, si.",+ "this_issue": "Cette tâche uniquement",+ "subtree_one": "Cette tâche et sa {{count}} sous-tâche",+ "subtree_other": "Cette tâche et ses {{count}} sous-tâches",+ "subtree_unknown": "Cette tâche et ses sous-tâches"+ },"snooze": {"action": "Reporter","menu_title": "Reporter jusqu'à…",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex a448449cac..804ba775ff 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -432,6 +432,10 @@"label": "Archiver la notification","description": "Archiver la notification ouverte, ou la restaurer lors de la consultation des archives."},+ "unsubscribeArchiveInboxItem": {+ "label": "Se désabonner et archiver",+ "description": "Se désabonner de la tâche de la notification ouverte et l'archiver. Disponible sur les tâches qui ne sont ni à vous ni à vos agents."+ },"snoozeInboxItem": {"label": "Reporter la notification","description": "Reporte la tâche ouverte depuis la boîte de réception, ou la fait revenir si elle est reportée."diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.jsonindex 849a5a3447..5b61239e73 100644--- a/packages/views/locales/ja/inbox.json+++ b/packages/views/locales/ja/inbox.json@@ -40,7 +40,8 @@"archive": "アーカイブ","unarchive": "アーカイブ解除","open_in_new_tab": "新しいタブで開く",- "delete": "削除"+ "delete": "削除",+ "unsubscribe_archive": "購読解除してアーカイブ"},"list": {"loading_selection": "通知を読み込み中…",@@ -123,7 +124,11 @@"source_context_retry_started": "元のコンテキストで再試行を開始しました","archived": "通知をアーカイブしました","unarchived": "通知を元に戻しました",- "deleted": "通知を削除しました"+ "deleted": "通知を削除しました",+ "unsubscribed_archived": "購読を解除してアーカイブしました",+ "unsubscribed_archived_subtree": "このタスクとサブタスクの購読を解除しました",+ "unsubscribed_hint": "今後の更新はインボックスに届きません。@メンションは引き続き通知されます。",+ "undo": "元に戻す"},"errors": {"archived_lookup_failed": "リンク先の通知を読み込めませんでした",@@ -140,7 +145,9 @@"unarchive_failed": "アーカイブ解除に失敗しました","archived_load_failed": "アーカイブ済み通知を読み込めませんでした","filters_load_failed": "フィルターを読み込めませんでした",- "delete_failed": "通知を削除できませんでした。もう一度お試しください。"+ "delete_failed": "通知を削除できませんでした。もう一度お試しください。",+ "unsubscribe_archive_failed": "購読解除に失敗しました",+ "undo_unsubscribe_failed": "元に戻せませんでした"},"delete_dialog": {"title": "通知を削除しますか?",@@ -149,6 +156,12 @@"cancel": "キャンセル","active_issue_description": "このタスクの受信トレイ内の通知は完全に削除されます。以前アーカイブした通知は残り、アーカイブに再表示されます。タスクと実行記録は残ります。"},+ "unsubscribe": {+ "title": "購読を解除してアーカイブします。このタスクの更新は届かなくなりますが、@メンションは引き続き通知されます。",+ "this_issue": "このタスクのみ",+ "subtree_other": "このタスクと {{count}} 件のサブタスク",+ "subtree_unknown": "このタスクとサブタスク"+ },"snooze": {"action": "スヌーズ","menu_title": "スヌーズする時間…",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 70533fc9e3..ba8fdd9e78 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -426,6 +426,10 @@"label": "通知をアーカイブ","description": "開いているインボックス通知をアーカイブします。アーカイブ表示中はアーカイブを解除します。"},+ "unsubscribeArchiveInboxItem": {+ "label": "購読解除してアーカイブ",+ "description": "開いている通知のタスクの購読を解除し、アーカイブします。自分や自分のエージェントのタスク以外で使えます。"+ },"snoozeInboxItem": {"label": "通知をスヌーズ","description": "インボックスから開いたタスクをスヌーズします。スヌーズ中なら今すぐ戻します。"diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.jsonindex 8ccfcac2ec..54ee126c4a 100644--- a/packages/views/locales/ko/inbox.json+++ b/packages/views/locales/ko/inbox.json@@ -40,7 +40,8 @@"archive": "보관","unarchive": "보관 해제","open_in_new_tab": "새 탭에서 열기",- "delete": "삭제"+ "delete": "삭제",+ "unsubscribe_archive": "구독 해제 후 보관"},"list": {"loading_selection": "알림을 불러오는 중…",@@ -123,7 +124,11 @@"source_context_retry_started": "원본 컨텍스트로 재시도를 시작했습니다","archived": "알림을 보관했습니다","unarchived": "알림을 복원했습니다",- "deleted": "알림이 삭제되었습니다"+ "deleted": "알림이 삭제되었습니다",+ "unsubscribed_archived": "구독을 해제하고 보관했습니다",+ "unsubscribed_archived_subtree": "이 태스크와 하위 태스크의 구독을 해제했습니다",+ "unsubscribed_hint": "이후 업데이트는 인박스에 오지 않습니다. @멘션은 계속 알림을 받습니다.",+ "undo": "실행 취소"},"errors": {"archived_lookup_failed": "링크된 알림을 불러오지 못했습니다",@@ -140,7 +145,9 @@"unarchive_failed": "보관 해제에 실패했습니다","archived_load_failed": "보관된 알림을 불러오지 못했습니다","filters_load_failed": "필터를 불러올 수 없습니다",- "delete_failed": "알림을 삭제하지 못했습니다. 다시 시도해 주세요."+ "delete_failed": "알림을 삭제하지 못했습니다. 다시 시도해 주세요.",+ "unsubscribe_archive_failed": "구독 해제에 실패했습니다",+ "undo_unsubscribe_failed": "실행 취소에 실패했습니다"},"delete_dialog": {"title": "알림을 삭제할까요?",@@ -149,6 +156,12 @@"cancel": "취소","active_issue_description": "이 작업의 받은편지함 알림은 영구적으로 삭제됩니다. 이전에 보관한 알림은 유지되며 보관함에 다시 표시됩니다. 작업과 실행 기록은 유지됩니다."},+ "unsubscribe": {+ "title": "구독을 해제하고 보관합니다. 이 태스크의 업데이트 알림은 오지 않지만 @멘션은 계속 알림을 받습니다.",+ "this_issue": "이 태스크만",+ "subtree_other": "이 태스크와 하위 태스크 {{count}}개",+ "subtree_unknown": "이 태스크와 하위 태스크"+ },"snooze": {"action": "다시 알림","menu_title": "다시 알릴 시간…",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 6ce978078e..723be8f865 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -426,6 +426,10 @@"label": "알림 보관","description": "열린 인박스 알림을 보관합니다. 보관함을 보는 중에는 보관을 해제합니다."},+ "unsubscribeArchiveInboxItem": {+ "label": "구독 해제 후 보관",+ "description": "열린 알림의 태스크 구독을 해제하고 보관합니다. 나 또는 내 에이전트의 태스크가 아닐 때 사용할 수 있습니다."+ },"snoozeInboxItem": {"label": "알림 미루기","description": "인박스에서 연 태스크를 미룹니다. 이미 미뤘다면 지금 되돌립니다."diff --git a/packages/views/locales/ru/inbox.json b/packages/views/locales/ru/inbox.jsonindex 1ceb380d54..f74bec545d 100644--- a/packages/views/locales/ru/inbox.json+++ b/packages/views/locales/ru/inbox.json@@ -46,7 +46,8 @@"archive": "Архивировать","unarchive": "Восстановить из архива","open_in_new_tab": "Открыть в новой вкладке",- "delete": "Удалить"+ "delete": "Удалить",+ "unsubscribe_archive": "Отписаться и архивировать"},"list": {"loading_selection": "Загрузка уведомления…",@@ -129,7 +130,11 @@"source_context_retry_started": "Повтор запущен с исходным контекстом","archived": "Уведомление архивировано","unarchived": "Уведомление восстановлено",- "deleted": "Уведомление удалено"+ "deleted": "Уведомление удалено",+ "unsubscribed_archived": "Вы отписались, уведомление в архиве",+ "unsubscribed_archived_subtree": "Вы отписались от задачи и её подзадач",+ "unsubscribed_hint": "Обновления не попадут во входящие. @упоминания по-прежнему придут.",+ "undo": "Отменить"},"errors": {"archived_lookup_failed": "Не удалось загрузить связанное уведомление",@@ -146,7 +151,9 @@"unarchive_failed": "Не удалось восстановить из архива","archived_load_failed": "Не удалось загрузить архивные уведомления","filters_load_failed": "Не удалось загрузить фильтры",- "delete_failed": "Не удалось удалить уведомление. Попробуйте снова."+ "delete_failed": "Не удалось удалить уведомление. Попробуйте снова.",+ "unsubscribe_archive_failed": "Не удалось отписаться",+ "undo_unsubscribe_failed": "Не удалось отменить"},"delete_dialog": {"title": "Удалить уведомление?",@@ -155,6 +162,15 @@"cancel": "Отмена","active_issue_description": "Активные уведомления этой задачи будут удалены навсегда. Ранее архивированные уведомления сохранятся и снова появятся в архиве. Задача и её запуски сохранятся."},+ "unsubscribe": {+ "title": "Отписаться и отправить в архив. Обновления задачи больше не придут, но @упоминания по-прежнему будут.",+ "this_issue": "Только эта задача",+ "subtree_one": "Эта задача и {{count}} подзадача",+ "subtree_few": "Эта задача и {{count}} подзадачи",+ "subtree_many": "Эта задача и {{count}} подзадач",+ "subtree_other": "Эта задача и {{count}} подзадачи",+ "subtree_unknown": "Эта задача и её подзадачи"+ },"snooze": {"action": "Отложить","menu_title": "Отложить до…",diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex e80019633d..1769d388b0 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -443,6 +443,10 @@"label": "Архивировать уведомление","description": "Отправить в архив открытое уведомление во входящих или восстановить его при просмотре архива."},+ "unsubscribeArchiveInboxItem": {+ "label": "Отписаться и архивировать",+ "description": "Отписаться от задачи открытого уведомления и отправить его в архив. Доступно для задач, которые не ваши и не ваших агентов."+ },"snoozeInboxItem": {"label": "Отложить уведомление","description": "Откладывает открытое issue из входящих или возвращает его, если оно уже отложено."diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.jsonindex 3341c70833..1261b33069 100644--- a/packages/views/locales/zh-Hans/inbox.json+++ b/packages/views/locales/zh-Hans/inbox.json@@ -40,7 +40,8 @@"archive": "归档","unarchive": "取消归档","open_in_new_tab": "在新标签页打开",- "delete": "删除"+ "delete": "删除",+ "unsubscribe_archive": "取消订阅并归档"},"list": {"loading_selection": "正在加载通知…",@@ -123,7 +124,11 @@"source_context_retry_started": "已使用原始上下文开始重试","archived": "已归档通知","unarchived": "已恢复通知",- "deleted": "通知已删除"+ "deleted": "通知已删除",+ "unsubscribed_archived": "已取消订阅并归档",+ "unsubscribed_archived_subtree": "已取消订阅此任务及其子任务",+ "unsubscribed_hint": "之后的普通动态不会再进收件箱,@你时仍会通知",+ "undo": "撤销"},"errors": {"archived_lookup_failed": "无法加载链接指向的通知",@@ -140,7 +145,9 @@"unarchive_failed": "取消归档失败","archived_load_failed": "无法加载已归档通知","filters_load_failed": "无法加载筛选项",- "delete_failed": "无法删除通知,请重试。"+ "delete_failed": "无法删除通知,请重试。",+ "unsubscribe_archive_failed": "取消订阅失败",+ "undo_unsubscribe_failed": "撤销失败"},"delete_dialog": {"title": "删除通知?",@@ -149,6 +156,12 @@"cancel": "取消","active_issue_description": "此任务在收件箱中的通知将被永久删除。此前归档的通知会保留,并重新显示在归档视图中。任务和运行记录不受影响。"},+ "unsubscribe": {+ "title": "取消订阅并归档:不再收到它的订阅通知,@你时仍会通知",+ "this_issue": "仅此任务",+ "subtree_other": "此任务及其 {{count}} 个子任务",+ "subtree_unknown": "此任务及其子任务"+ },"snooze": {"action": "延后","menu_title": "延后到…",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 7f8240d297..d080c1bf47 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -426,6 +426,10 @@"label": "归档通知","description": "归档当前打开的收件箱通知;在归档列表中则取消归档。"},+ "unsubscribeArchiveInboxItem": {+ "label": "取消订阅并归档",+ "description": "退订当前通知所在的任务并归档它。仅在不属于你或你的智能体的任务上可用。"+ },"snoozeInboxItem": {"label": "延后通知","description": "延后从收件箱打开的任务;已延后时让它现在回来。"diff --git a/packages/views/locales/zh-Hant/inbox.json b/packages/views/locales/zh-Hant/inbox.jsonindex 8ed962bd1c..70ea6d3ff0 100644--- a/packages/views/locales/zh-Hant/inbox.json+++ b/packages/views/locales/zh-Hant/inbox.json@@ -40,7 +40,8 @@"archive": "歸檔","unarchive": "取消歸檔","open_in_new_tab": "在新標籤頁開啟",- "delete": "刪除"+ "delete": "刪除",+ "unsubscribe_archive": "取消訂閱並歸檔"},"list": {"loading_selection": "正在載入通知…",@@ -123,7 +124,11 @@"source_context_retry_started": "已使用原始上下文開始重試","archived": "已歸檔通知","unarchived": "已恢復通知",- "deleted": "通知已刪除"+ "deleted": "通知已刪除",+ "unsubscribed_archived": "已取消訂閱並歸檔",+ "unsubscribed_archived_subtree": "已取消訂閱此任務及其子任務",+ "unsubscribed_hint": "之後的一般動態不會再進收件匣,@你時仍會通知",+ "undo": "復原"},"errors": {"archived_lookup_failed": "無法載入連結指向的通知",@@ -140,7 +145,9 @@"unarchive_failed": "取消歸檔失敗","archived_load_failed": "無法載入已歸檔通知","filters_load_failed": "無法載入篩選項",- "delete_failed": "無法刪除通知,請重試。"+ "delete_failed": "無法刪除通知,請重試。",+ "unsubscribe_archive_failed": "取消訂閱失敗",+ "undo_unsubscribe_failed": "復原失敗"},"delete_dialog": {"title": "刪除通知?",@@ -149,6 +156,12 @@"cancel": "取消","active_issue_description": "此任務在收件箱中的通知將被永久刪除。先前歸檔的通知會保留,並重新顯示在已歸檔檢視中。任務和執行記錄不受影響。"},+ "unsubscribe": {+ "title": "取消訂閱並歸檔:不再收到它的訂閱通知,@你時仍會通知",+ "this_issue": "僅此任務",+ "subtree_other": "此任務及其 {{count}} 個子任務",+ "subtree_unknown": "此任務及其子任務"+ },"snooze": {"action": "延後","menu_title": "延後到…",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex d3550218a7..83a25557fb 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -426,6 +426,10 @@"label": "歸檔通知","description": "歸檔當前開啟的收件箱通知;在歸檔列表中則取消歸檔。"},+ "unsubscribeArchiveInboxItem": {+ "label": "取消訂閱並歸檔",+ "description": "退訂當前通知所在的任務並歸檔它。僅在不屬於你或你的智能體的任務上可用。"+ },"snoozeInboxItem": {"label": "延後通知","description": "延後從收件箱開啟的任務;已延後時讓它現在回來。"diff --git a/packages/views/settings/components/keyboard-shortcuts-tab.tsx b/packages/views/settings/components/keyboard-shortcuts-tab.tsxindex cf2613e490..c0544fa5bb 100644--- a/packages/views/settings/components/keyboard-shortcuts-tab.tsx+++ b/packages/views/settings/components/keyboard-shortcuts-tab.tsx@@ -273,7 +273,7 @@ function ShortcutRow({const { t } = useT("settings");const label = t(($) => $.shortcuts.actions[action.id].label);// Keep descriptions in the search index, but only show non-obvious behavior.- const description = ["openSearch", "toggleRightSidebar", "archiveInboxItem", "snoozeInboxItem", "send"].includes(action.id)+ const description = ["openSearch", "toggleRightSidebar", "archiveInboxItem", "unsubscribeArchiveInboxItem", "snoozeInboxItem", "send"].includes(action.id)? t(($) => $.shortcuts.actions[action.id].description): undefined;const errorText = error?.kind === "reserved"diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 80ce93a79f..5ba7d20b89 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2162,6 +2162,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/subscribe", h.SubscribeToIssue)r.Post("/unsubscribe", h.UnsubscribeFromIssue)r.Post("/unsubscribe/subtree", h.UnsubscribeFromIssueSubtree)+ r.Post("/unsubscribe/undo", h.UndoUnsubscribeFromIssue)r.Post("/read", h.MarkIssueRead)r.Post("/unread", h.MarkIssueUnread)r.Get("/wakeups", h.ListIssueWakeups)diff --git a/server/internal/handler/subscriber.go b/server/internal/handler/subscriber.goindex a36e92858d..010a82b46e 100644--- a/server/internal/handler/subscriber.go+++ b/server/internal/handler/subscriber.go@@ -282,6 +282,63 @@ func (h *Handler) unsubscribeFromIssue(w http.ResponseWriter, r *http.Request, swriteJSON(w, http.StatusOK, map[string]bool{"subscribed": false})}+// UndoUnsubscribeFromIssue reverses the caller's own issue-scope unsubscribe,+// restoring the subscription as it was (see UndoIssueUnsubscribe) rather than+// subscribing again: a member who left a commenter or delegated subscription+// gets that back, not a manual one that delivers every event. It acts on the+// caller only. A separate route, so an older server answers 404 instead of+// quietly doing something else (as UnsubscribeFromIssueSubtree explains).+// 409 when there is no opt-out to undo, e.g. it was already reversed.+func (h *Handler) UndoUnsubscribeFromIssue(w http.ResponseWriter, r *http.Request) {+ issueID := chi.URLParam(r, "id")+ issue, ok := h.loadIssueForUser(w, r, issueID)+ if !ok {+ return+ }+ workspaceID := uuidToString(issue.WorkspaceID)+ actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)+ actorID = uuidToString(parseUUID(actorID))++ row, err := h.Queries.UndoIssueUnsubscribe(r.Context(), db.UndoIssueUnsubscribeParams{+ IssueID: issue.ID,+ UserType: actorType,+ UserID: parseUUID(actorID),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to undo unsubscribe")+ return+ }++ reason := row.RevivedReason+ if row.DroppedOptOut && actorType == "member" {+ projectSubscribers, err := h.Queries.ListProjectSubscribersForIssue(r.Context(), issue.ID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to undo unsubscribe")+ return+ }+ for _, ps := range projectSubscribers {+ if uuidToString(ps.UserID) == actorID {+ reason = subscriberReasonProject+ break+ }+ }+ }+ if reason == "" && !row.DroppedOptOut {+ writeError(w, http.StatusConflict, "no unsubscribe to undo")+ return+ }++ if reason != "" {+ h.publish(protocol.EventSubscriberAdded, workspaceID, actorType, actorID, map[string]any{+ "issue_id": issueID,+ "user_type": actorType,+ "user_id": actorID,+ "reason": reason,+ })+ }+ writeJSON(w, http.StatusOK, map[string]any{"subscribed": reason != "", "reason": reason})+}+// errTargetNoLongerMember reports that the target left the workspace between// the handler's pre-check and the serialized write, so the caller can answer// 403 exactly as the pre-check would have.diff --git a/server/internal/handler/subscriber_undo_test.go b/server/internal/handler/subscriber_undo_test.gonew file mode 100644index 0000000000..4e7fb4b4d8--- /dev/null+++ b/server/internal/handler/subscriber_undo_test.go@@ -0,0 +1,120 @@+package handler++import (+ "context"+ "net/http"+ "testing"++ "github.com/multica-ai/multica/server/internal/testutil"+)++// Undo of an unsubscribe restores the subscription as it was. Subscribing+// again would rewrite every reason to manual: a commenter or delegated+// watcher would start getting every event, and a project watcher would pick+// up a direct row that outlives the project subscription (MUL-9343).+func TestUndoUnsubscribeRestoresTheSubscription(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)+ })+ issuePath := "/api/issues/" + f.secretIssue++ call := func(h http.HandlerFunc, path, userID string) *testutil.Response {+ t.Helper()+ req := withURLParam(asUser(newRequest(http.MethodPost, path, nil), userID), "id", f.secretIssue)+ return testutil.Call(t, h, req)+ }+ reasonOf := func(userID 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)+ for _, s := range resp {+ if s.UserType == "member" && s.UserID == userID {+ return s.Reason+ }+ }+ return ""+ }+ storedRows := func(userID string) int {+ t.Helper()+ var n int+ if err := testPool.QueryRow(ctx,+ `SELECT count(*) FROM issue_subscriber WHERE issue_id = $1 AND user_type = 'member' AND user_id = $2`,+ f.secretIssue, userID).Scan(&n); err != nil {+ t.Fatal(err)+ }+ return n+ }+ undo := func(userID string, want int) map[string]any {+ t.Helper()+ resp := call(testHandler.UndoUnsubscribeFromIssue, issuePath+"/unsubscribe/undo", userID).Want(want)+ var body map[string]any+ if want == http.StatusOK {+ resp.JSON(&body)+ }+ return body+ }++ for _, reason := range []string{"commenter", "delegated"} {+ t.Run(reason, func(t *testing.T) {+ testPool.Exec(ctx, `DELETE FROM issue_subscriber WHERE issue_id = $1 AND user_id = $2`, f.secretIssue, testUserID)+ if _, err := testPool.Exec(ctx, `+ INSERT INTO issue_subscriber (issue_id, user_type, user_id, reason, created_at)+ VALUES ($1, 'member', $2, $3, now() - interval '1 hour')+ `, f.secretIssue, testUserID, reason); err != nil {+ t.Fatal(err)+ }+ call(testHandler.UnsubscribeFromIssue, issuePath+"/unsubscribe", testUserID).Want(http.StatusOK)+ if got := reasonOf(testUserID); got != "" {+ t.Fatalf("still listed as %q after unsubscribing", got)+ }+ if body := undo(testUserID, http.StatusOK); body["reason"] != reason {+ t.Fatalf("undo answered %v, want reason %q", body, reason)+ }+ if got := reasonOf(testUserID); got != reason {+ t.Fatalf("reason after undo = %q, want %q", got, reason)+ }+ })+ }++ t.Run("project", func(t *testing.T) {+ 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)+ }+ call(testHandler.UnsubscribeFromIssue, issuePath+"/unsubscribe", f.insider).Want(http.StatusOK)+ if got := reasonOf(f.insider); got != "" {+ t.Fatalf("project watcher still listed as %q after unsubscribing", got)+ }+ if body := undo(f.insider, http.StatusOK); body["reason"] != "project" {+ t.Fatalf("undo answered %v, want reason project", body)+ }+ if got := reasonOf(f.insider); got != "project" {+ t.Fatalf("reason after undo = %q, want project", got)+ }+ if n := storedRows(f.insider); n != 0 {+ t.Fatalf("undo left %d issue_subscriber rows; the project subscription alone should cover the issue", n)+ }+ })++ t.Run("nothing to undo", func(t *testing.T) {+ undo(f.insider, http.StatusConflict)+ })++ t.Run("subtree opt-out stays", func(t *testing.T) {+ testPool.Exec(ctx, `DELETE FROM issue_subscriber WHERE issue_id = $1 AND user_id = $2`, f.secretIssue, testUserID)+ call(testHandler.UnsubscribeFromIssueSubtree, issuePath+"/unsubscribe/subtree", testUserID).Want(http.StatusOK)+ undo(testUserID, http.StatusConflict)+ 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, testUserID).Scan(&scope); err != nil || scope != "subtree" {+ t.Fatalf("subtree opt-out after undo: scope=%q err=%v", scope, err)+ }+ })+}diff --git a/server/pkg/db/generated/subscriber.sql.go b/server/pkg/db/generated/subscriber.sql.goindex c49aa6aa36..30c0601b19 100644--- a/server/pkg/db/generated/subscriber.sql.go+++ b/server/pkg/db/generated/subscriber.sql.go@@ -523,6 +523,68 @@ func (q *Queries) SubscribeToIssueExplicitly(ctx context.Context, arg SubscribeTreturn err}+const undoIssueUnsubscribe = `-- name: UndoIssueUnsubscribe :one+WITH target AS (+ SELECT s.issue_id, s.user_type, s.user_id, s.created_at = s.unsubscribed_at AS synthetic+ FROM issue_subscriber s+ WHERE s.issue_id = $1+ AND s.user_type = $2+ AND s.user_id = $3+ AND s.unsubscribed_at IS NOT NULL+ AND s.opt_out_scope = 'issue'+),+dropped AS (+ DELETE FROM issue_subscriber s+ USING target t+ WHERE t.synthetic+ AND s.issue_id = t.issue_id AND s.user_type = t.user_type AND s.user_id = t.user_id+ RETURNING s.issue_id+),+revived AS (+ UPDATE issue_subscriber s+ SET unsubscribed_at = NULL, opt_out_scope = NULL+ FROM target t+ WHERE NOT t.synthetic+ AND s.issue_id = t.issue_id AND s.user_type = t.user_type AND s.user_id = t.user_id+ RETURNING s.reason+)+SELECT+ COALESCE((SELECT reason FROM revived), '')::text AS revived_reason,+ EXISTS (SELECT 1 FROM dropped) AS dropped_opt_out+`++type UndoIssueUnsubscribeParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ UserType string `json:"user_type"`+ UserID pgtype.UUID `json:"user_id"`+}++type UndoIssueUnsubscribeRow struct {+ RevivedReason string `json:"revived_reason"`+ DroppedOptOut bool `json:"dropped_opt_out"`+}++// Reverse an issue-scope opt-out, putting the subscription back exactly as it+// was instead of subscribing again (which would rewrite the reason to manual+// and lift the member out of the delegated and bystander tiers):+//+// - a retired row keeps its reason (creator, commenter, delegated, ...), so+// it is reactivated as it stands;+// - a tombstone the opt-out itself inserted for a project watcher has no+// subscription behind it, so it is deleted and the project covers the+// issue again. RemoveIssueSubscriber writes such a row in one statement,+// which is why its created_at equals its unsubscribed_at; a retired row+// was created before it was retired.+//+// Subtree opt-outs are not undone here: they cover descendants and future+// children, which one issue's row cannot restore.+func (q *Queries) UndoIssueUnsubscribe(ctx context.Context, arg UndoIssueUnsubscribeParams) (UndoIssueUnsubscribeRow, error) {+ row := q.db.QueryRow(ctx, undoIssueUnsubscribe, arg.IssueID, arg.UserType, arg.UserID)+ var i UndoIssueUnsubscribeRow+ err := row.Scan(&i.RevivedReason, &i.DroppedOptOut)+ return i, err+}+const unsubscribeFromIssueSubtree = `-- name: UnsubscribeFromIssueSubtree :manyWITH RECURSIVE subtree(node_id) AS (SELECT root.id FROM issue root WHERE root.id = $1diff --git a/server/pkg/db/queries/subscriber.sql b/server/pkg/db/queries/subscriber.sqlindex 82300d2e9f..9165a0dda3 100644--- a/server/pkg/db/queries/subscriber.sql+++ b/server/pkg/db/queries/subscriber.sql@@ -186,6 +186,49 @@ WHERE i.id = sqlc.arg(issue_id)AND NOT EXISTS (SELECT 1 FROM retired)ON CONFLICT (issue_id, user_type, user_id) DO NOTHING;+-- name: UndoIssueUnsubscribe :one+-- Reverse an issue-scope opt-out, putting the subscription back exactly as it+-- was instead of subscribing again (which would rewrite the reason to manual+-- and lift the member out of the delegated and bystander tiers):+--+-- * a retired row keeps its reason (creator, commenter, delegated, ...), so+-- it is reactivated as it stands;+-- * a tombstone the opt-out itself inserted for a project watcher has no+-- subscription behind it, so it is deleted and the project covers the+-- issue again. RemoveIssueSubscriber writes such a row in one statement,+-- which is why its created_at equals its unsubscribed_at; a retired row+-- was created before it was retired.+--+-- Subtree opt-outs are not undone here: they cover descendants and future+-- children, which one issue's row cannot restore.+WITH target AS (+ SELECT s.issue_id, s.user_type, s.user_id, s.created_at = s.unsubscribed_at AS synthetic+ FROM issue_subscriber s+ WHERE s.issue_id = sqlc.arg(issue_id)+ AND s.user_type = sqlc.arg(user_type)+ AND s.user_id = sqlc.arg(user_id)+ AND s.unsubscribed_at IS NOT NULL+ AND s.opt_out_scope = 'issue'+),+dropped AS (+ DELETE FROM issue_subscriber s+ USING target t+ WHERE t.synthetic+ AND s.issue_id = t.issue_id AND s.user_type = t.user_type AND s.user_id = t.user_id+ RETURNING s.issue_id+),+revived AS (+ UPDATE issue_subscriber s+ SET unsubscribed_at = NULL, opt_out_scope = NULL+ FROM target t+ WHERE NOT t.synthetic+ AND s.issue_id = t.issue_id AND s.user_type = t.user_type AND s.user_id = t.user_id+ RETURNING s.reason+)+SELECT+ COALESCE((SELECT reason FROM revived), '')::text AS revived_reason,+ EXISTS (SELECT 1 FROM dropped) AS dropped_opt_out;+-- name: UnsubscribeFromIssueSubtree :many-- Leave an issue AND every descendant in one action. An agent-built tree is-- the unit a user actually wants to stop watching; leaving 30 sub-issues one