Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9651 fix(inbox): scope unread summary to a task's bound workspace (#10974)
Multica Evee1fe10d66948
diff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdxindex e54d8e26cc..1dd11fd50a 100644--- a/apps/docs/content/docs/cli.fr.mdx+++ b/apps/docs/content/docs/cli.fr.mdx@@ -536,7 +536,7 @@ Les tableaux ci-dessous couvrent toutes les commandes de premier niveau actuelle| `chat` | `history`, `thread [id]` | Lire la session de messagerie externe qu'un agent traite actuellement | `--limit`, `--before` || | `wakeup create/list/get/update/cancel/finish/checkin` | Gérer le suivi dans l’exécution de chat en cours ; voir [Réveils de chat](#chat-wakeups) | `--title`, `--instruction` / `--instruction-file`, `--until-*`, `--at` / `--after`, `--every`, `--expires-in` / `--expires-at`; `checkin`: `--note` || `inbox` | `list` | [Lister vos notifications](/inbox) sans les marquer comme lues ; `--archived` ou `--snoozed` liste celles-ci à la place | `--unread`, `--issue`, `--since`, `--project`, `--type`, `--output` (`table` ou `json`) ; `--archived` lit toutes les pages |-| | `count` | Nombre de non-lus dans cet espace de travail et dans chacun de vos espaces | `--output` |+| | `count` | Nombre de non-lus dans cet espace de travail et dans chacun de vos espaces ; une exécution d'agent ne voit que son propre espace | `--output` || | `read [<id>...]` | Marquer des notifications comme lues, toute la tâche pour chacune ; ou toutes celles d'une tâche, ou toutes | `--issue`, `--all` (exige `--yes`) || | `unread <id>...` | Marquer des notifications comme non lues | || | `archive [<id>...]` | Archiver des notifications, toute la tâche pour chacune ; ou en lot | `--all`, `--read`, `--completed` (chacun exige `--yes`) |diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex 406fd60a31..32ed4a4411 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -528,7 +528,7 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで| `chat` | `history`、`thread [id]` | エージェントが現在処理している外部チャットセッションを読み取り | `--limit`、`--before` || | `wakeup create/list/get/update/cancel/finish/checkin` | 現在のチャット実行の予定を管理。[チャットのウェイクアップ](#chat-wakeups)を参照 | `--title`, `--instruction` / `--instruction-file`, `--until-*`, `--at` / `--after`, `--every`, `--expires-in` / `--expires-at`; `checkin`: `--note` || `inbox` | `list` | 既読にせずに[通知を一覧表示](/inbox)。`--archived` または `--snoozed` ではそれらを一覧表示 | `--unread`、`--issue`、`--since`、`--project`、`--type`、`--output`(`table` または `json`);`--archived` は全ページを読む |-| | `count` | このワークスペースと所属する各ワークスペースの未読件数 | `--output` |+| | `count` | このワークスペースと所属する各ワークスペースの未読件数。エージェントの実行では自身のワークスペースのみ | `--output` || | `read [<id>...]` | 通知を既読にする(各通知のタスク全体に適用)。または 1 つのタスクのすべての通知、またはすべて | `--issue`、`--all`(`--yes` が必要) || | `unread <id>...` | 通知を未読に戻す | || | `archive [<id>...]` | 通知をアーカイブする(各通知のタスク全体に適用)。または一括で | `--all`、`--read`、`--completed`(いずれも `--yes` が必要) |diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex f968eb0bf9..f2eabea70b 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -528,7 +528,7 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t| `chat` | `history`, `thread [id]` | 에이전트가 현재 처리 중인 외부 채팅 대화 읽기 | `--limit`, `--before` || | `wakeup create/list/get/update/cancel/finish/checkin` | 현재 채팅 실행의 후속 작업 관리. [채팅 웨이크업](#chat-wakeups) 참고 | `--title`, `--instruction` / `--instruction-file`, `--until-*`, `--at` / `--after`, `--every`, `--expires-in` / `--expires-at`; `checkin`: `--note` || `inbox` | `list` | 읽음으로 표시하지 않고 [알림 목록 보기](/inbox). `--archived` 또는 `--snoozed`는 해당 목록을 보여 줌 | `--unread`, `--issue`, `--since`, `--project`, `--type`, `--output` (`table` 또는 `json`); `--archived`는 모든 페이지를 읽음 |-| | `count` | 이 워크스페이스와 소속된 각 워크스페이스의 읽지 않은 알림 수 | `--output` |+| | `count` | 이 워크스페이스와 소속된 각 워크스페이스의 읽지 않은 알림 수. 에이전트 실행에서는 해당 워크스페이스만 | `--output` || | `read [<id>...]` | 알림을 읽음으로 표시(각 알림의 태스크 전체에 적용). 또는 한 태스크의 모든 알림, 또는 전체 | `--issue`, `--all` (`--yes` 필요) || | `unread <id>...` | 알림을 읽지 않음으로 표시 | || | `archive [<id>...]` | 알림 보관(각 알림의 태스크 전체에 적용). 또는 일괄 보관 | `--all`, `--read`, `--completed` (모두 `--yes` 필요) |diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex aff7d6e0a5..aff56652af 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -563,7 +563,7 @@ Migration from CSV parsing: replace `--attachment a,b` with `--attachment a --at| `chat` | `history`, `thread [id]` | Read the external chat session an agent is currently handling | `--limit`, `--before` || | `wakeup create/list/get/update/cancel/finish/checkin` | Manage follow-ups in the current chat run; see [Chat wakeups](#chat-wakeups) | `--title`, `--instruction` / `--instruction-file`, `--until-*`, `--at` / `--after`, `--every`, `--expires-in` / `--expires-at`; `checkin`: `--note` || `inbox` | `list` | [List your notifications](/inbox) without marking them read; `--archived` or `--snoozed` lists those instead | `--unread`, `--issue`, `--since`, `--project`, `--type`, `--output` (`table` or `json`); `--archived` reads every page |-| | `count` | Unread count in this workspace and in each of your workspaces | `--output` |+| | `count` | Unread count in this workspace and in each of your workspaces; an agent run sees only its own workspace | `--output` || | `read [<id>...]` | Mark notifications read, the whole issue for each; or every notification on one issue, or all | `--issue`, `--all` (needs `--yes`) || | `unread <id>...` | Mark notifications unread | || | `archive [<id>...]` | Archive notifications, the whole issue for each; or in bulk | `--all`, `--read`, `--completed` (each needs `--yes`) |diff --git a/apps/docs/content/docs/cli.zh-Hant.mdx b/apps/docs/content/docs/cli.zh-Hant.mdxindex 6763c6fa9c..26c202bed2 100644--- a/apps/docs/content/docs/cli.zh-Hant.mdx+++ b/apps/docs/content/docs/cli.zh-Hant.mdx@@ -537,7 +537,7 @@ CLI 配置檔案包含可代表你訪問 Multica 的令牌。不要提交到倉| `chat` | `history`、`thread [id]` | 讀取 AI 代理當前正在處理的外部聊天會話 | `--limit`、`--before` || | `wakeup create/list/get/update/cancel/finish/checkin` | 管理目前聊天執行的跟進;見[聊天喚醒](#chat-wakeups) | `--title`, `--instruction` / `--instruction-file`, `--until-*`, `--at` / `--after`, `--every`, `--expires-in` / `--expires-at`; `checkin`: `--note` || `inbox` | `list` | [列出通知](/inbox),不標為已讀;`--archived` 或 `--snoozed` 改為列出封存或稍後提醒的內容 | `--unread`、`--issue`、`--since`、`--project`、`--type`、`--output`(`table` 或 `json`);`--archived` 讀取全部分頁 |-| | `count` | 目前工作區及你所在各工作區的未讀數 | `--output` |+| | `count` | 目前工作區及你所在各工作區的未讀數;AI 代理執行時只回傳所在工作區 | `--output` || | `read [<id>...]` | 將通知標為已讀(作用於所在任務的全部通知);或一個任務上的全部通知,或全部 | `--issue`、`--all`(需要 `--yes`) || | `unread <id>...` | 將通知標為未讀 | || | `archive [<id>...]` | 封存通知(作用於所在任務的全部通知);或批次封存 | `--all`、`--read`、`--completed`(皆需 `--yes`) |diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex 3e7e2cbc43..7bcf8fb26c 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -540,7 +540,7 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| `chat` | `history`、`thread [id]` | 读取智能体当前正在处理的外部聊天会话 | `--limit`、`--before` || | `wakeup create/list/get/update/cancel/finish/checkin` | 管理当前聊天运行的跟进;见[聊天唤醒](#chat-wakeups) | `--title`, `--instruction` / `--instruction-file`, `--until-*`, `--at` / `--after`, `--every`, `--expires-in` / `--expires-at`; `checkin`: `--note` || `inbox` | `list` | [列出通知](/inbox),不标为已读;`--archived` 或 `--snoozed` 改为列出归档或稍后提醒的内容 | `--unread`、`--issue`、`--since`、`--project`、`--type`、`--output`(`table` 或 `json`);`--archived` 读取全部分页 |-| | `count` | 当前工作区及你所在各工作区的未读数 | `--output` |+| | `count` | 当前工作区及你所在各工作区的未读数;智能体运行时只返回所在工作区 | `--output` || | `read [<id>...]` | 将通知标为已读(作用于所在任务的全部通知);或一个任务上的全部通知,或全部 | `--issue`、`--all`(需要 `--yes`) || | `unread <id>...` | 将通知标为未读 | || | `archive [<id>...]` | 归档通知(作用于所在任务的全部通知);或批量归档 | `--all`、`--read`、`--completed`(均需 `--yes`) |diff --git a/apps/docs/content/docs/inbox.fr.mdx b/apps/docs/content/docs/inbox.fr.mdxindex 73479f98c3..3204c68b02 100644--- a/apps/docs/content/docs/inbox.fr.mdx+++ b/apps/docs/content/docs/inbox.fr.mdx@@ -56,7 +56,7 @@ La page de la tâche signale un tel abonnement par **Mises à jour clés**. Son## Les agents et la boîte de réception-Les notifications appartiennent aux membres de l'espace de travail. Un agent peut lire et traiter les notifications du propriétaire du runtime uniquement si le serveur vérifie que ce propriétaire est la personne à l'origine de l'exécution. Cette identité est transmise dans les chaînes de délégation entre agents. La règle couvre toutes les actions de la boîte de réception : la liste active, les archives, la liste reportée, les compteurs de non-lus et toutes les modifications. Les exécutions déclenchées par une autre personne ou sans personne vérifiable, ainsi que les identifiants de nœud cloud sans liaison à une exécution, sont refusés. Seules les personnes peuvent supprimer des notifications. Le serveur journalise chaque modification faite par un agent, avec l'agent, l'exécution et la personne pour qui il agissait.+Les notifications appartiennent aux membres de l'espace de travail. Un agent peut lire et traiter les notifications du propriétaire du runtime uniquement si le serveur vérifie que ce propriétaire est la personne à l'origine de l'exécution. Cette identité est transmise dans les chaînes de délégation entre agents. La règle couvre toutes les actions de la boîte de réception : la liste active, les archives, la liste reportée, les compteurs de non-lus et toutes les modifications. Les exécutions déclenchées par une autre personne ou sans personne vérifiable, ainsi que les identifiants de nœud cloud sans liaison à une exécution, sont refusés. Les compteurs de non-lus lus par un agent ne couvrent que l'espace de travail de son exécution, jamais les autres espaces du propriétaire. Seules les personnes peuvent supprimer des notifications. Le serveur journalise chaque modification faite par un agent, avec l'agent, l'exécution et la personne pour qui il agissait.@mentionner un agent dans un commentaire, lui assigner une tâche ou déclencher une automatisation crée directement une exécution ; aucune notification n'est laissée à l'agent. `@all` ne notifie que les membres.diff --git a/apps/docs/content/docs/inbox.ja.mdx b/apps/docs/content/docs/inbox.ja.mdxindex 05be00d534..4b70301c24 100644--- a/apps/docs/content/docs/inbox.ja.mdx+++ b/apps/docs/content/docs/inbox.ja.mdx@@ -56,7 +56,7 @@ import { InboxDemo } from "@/components/demos/inbox-demo";## エージェントとインボックス-インボックスの通知はワークスペースメンバーに属します。実行を開始した上流のユーザーがランタイム所有者本人であるとサーバーが確認できた場合だけ、エージェントはその所有者の通知を読み取り、処理できます。このユーザー情報はエージェントの委任チェーンで引き継がれます。この規則はインボックスのすべての操作に適用されます。アクティブ一覧、アーカイブ、スヌーズ中の一覧、未読件数、そしてすべての変更です。他の人が開始した実行、開始した人を確認できない実行、タスクとの紐付けがないクラウドノードの認証情報は拒否されます。通知を削除できるのは人だけです。エージェントによる変更は、どのエージェントがどの実行で誰の代わりに行ったかとともにサーバーに記録されます。+インボックスの通知はワークスペースメンバーに属します。実行を開始した上流のユーザーがランタイム所有者本人であるとサーバーが確認できた場合だけ、エージェントはその所有者の通知を読み取り、処理できます。このユーザー情報はエージェントの委任チェーンで引き継がれます。この規則はインボックスのすべての操作に適用されます。アクティブ一覧、アーカイブ、スヌーズ中の一覧、未読件数、そしてすべての変更です。他の人が開始した実行、開始した人を確認できない実行、タスクとの紐付けがないクラウドノードの認証情報は拒否されます。エージェントが読み取る未読件数は実行中のワークスペースのものだけで、所有者の他のワークスペースは含みません。通知を削除できるのは人だけです。エージェントによる変更は、どのエージェントがどの実行で誰の代わりに行ったかとともにサーバーに記録されます。コメントでの @メンション、タスクの割り当て、オートパイロットのトリガーは、直接実行を作成し、エージェントに通知は残しません。`@all` もメンバーにのみ通知します。diff --git a/apps/docs/content/docs/inbox.ko.mdx b/apps/docs/content/docs/inbox.ko.mdxindex 08e0920ae8..f95ba1f503 100644--- a/apps/docs/content/docs/inbox.ko.mdx+++ b/apps/docs/content/docs/inbox.ko.mdx@@ -56,7 +56,7 @@ import { InboxDemo } from "@/components/demos/inbox-demo";## 에이전트와 인박스-인박스 알림은 워크스페이스 멤버의 데이터입니다. 서버가 실행을 시작한 상위 사용자가 런타임 소유자 본인임을 확인한 경우에만 에이전트가 해당 소유자의 알림을 읽고 처리할 수 있습니다. 이 사용자 정보는 에이전트 위임 체인을 따라 상속됩니다. 이 규칙은 활성 목록, 보관함, 다시 알림 목록, 읽지 않은 알림 수, 모든 변경 등 인박스의 모든 작업에 적용됩니다. 다른 사람이 시작한 실행, 시작한 사람을 확인할 수 없는 실행, 태스크에 연결되지 않은 클라우드 노드 자격 증명은 거부됩니다. 알림은 사람만 삭제할 수 있습니다. 에이전트가 변경할 때마다 서버는 어떤 에이전트가 어떤 실행에서 누구를 대신해 변경했는지 기록합니다.+인박스 알림은 워크스페이스 멤버의 데이터입니다. 서버가 실행을 시작한 상위 사용자가 런타임 소유자 본인임을 확인한 경우에만 에이전트가 해당 소유자의 알림을 읽고 처리할 수 있습니다. 이 사용자 정보는 에이전트 위임 체인을 따라 상속됩니다. 이 규칙은 활성 목록, 보관함, 다시 알림 목록, 읽지 않은 알림 수, 모든 변경 등 인박스의 모든 작업에 적용됩니다. 다른 사람이 시작한 실행, 시작한 사람을 확인할 수 없는 실행, 태스크에 연결되지 않은 클라우드 노드 자격 증명은 거부됩니다. 에이전트가 읽는 읽지 않은 알림 수는 실행 중인 워크스페이스만 포함하며 소유자의 다른 워크스페이스는 포함하지 않습니다. 알림은 사람만 삭제할 수 있습니다. 에이전트가 변경할 때마다 서버는 어떤 에이전트가 어떤 실행에서 누구를 대신해 변경했는지 기록합니다.댓글에서 에이전트를 @멘션하거나 태스크를 에이전트에게 할당하거나 자동화를 트리거하면 실행이 직접 생성되며, 에이전트에게 알림을 남기지 않습니다. `@all`도 멤버에게만 알립니다.diff --git a/apps/docs/content/docs/inbox.mdx b/apps/docs/content/docs/inbox.mdxindex 698d48a3fa..9cb75afa04 100644--- a/apps/docs/content/docs/inbox.mdx+++ b/apps/docs/content/docs/inbox.mdx@@ -56,7 +56,7 @@ The issue page marks such a subscription **Key updates only**. Its menu offers *## Agents and the inbox-Inbox notifications belong to workspace members. An agent may read and change the runtime owner's notifications only when the server verifies that the owner is the upstream human who triggered the run. This identity follows agent delegation chains. The rule covers every inbox action: the active, archived and snoozed lists, unread counts, and every change. Runs triggered by another person or without a verifiable human, and cloud-node credentials without a task binding, are refused. Only people can delete notifications. The server logs each change an agent makes, with the agent, the run and the person it acted for.+Inbox notifications belong to workspace members. An agent may read and change the runtime owner's notifications only when the server verifies that the owner is the upstream human who triggered the run. This identity follows agent delegation chains. The rule covers every inbox action: the active, archived and snoozed lists, unread counts, and every change. Runs triggered by another person or without a verifiable human, and cloud-node credentials without a task binding, are refused. An agent's unread counts cover only the workspace its run belongs to, never the owner's other workspaces. Only people can delete notifications. The server logs each change an agent makes, with the agent, the run and the person it acted for.@-mentioning an agent in a comment, assigning an issue to it, or triggering an autopilot creates a run directly; no notification is left for the agent. `@all` notifies members only.diff --git a/apps/docs/content/docs/inbox.zh-Hant.mdx b/apps/docs/content/docs/inbox.zh-Hant.mdxindex 09795a4012..f47b80108c 100644--- a/apps/docs/content/docs/inbox.zh-Hant.mdx+++ b/apps/docs/content/docs/inbox.zh-Hant.mdx@@ -56,7 +56,7 @@ import { InboxDemo } from "@/components/demos/inbox-demo";## AI 代理與收件箱-收件箱通知屬於工作區成員。只有伺服器驗證執行的上游觸發人就是執行環境擁有者時,AI 代理才能讀取和處理該擁有者的通知。這個身分會沿 AI 代理呼叫鏈繼承。這條規則涵蓋收件箱的所有操作:活躍列表、封存、稍後提醒列表、未讀數,以及所有修改。由他人觸發、沒有可驗證觸發人的執行,以及沒有任務綁定的雲端節點憑證,都會被拒絕。只有人可以刪除通知。AI 代理做的每次修改都會在伺服器留下紀錄,寫明是哪個 AI 代理、哪次執行、代哪個人操作。+收件箱通知屬於工作區成員。只有伺服器驗證執行的上游觸發人就是執行環境擁有者時,AI 代理才能讀取和處理該擁有者的通知。這個身分會沿 AI 代理呼叫鏈繼承。這條規則涵蓋收件箱的所有操作:活躍列表、封存、稍後提醒列表、未讀數,以及所有修改。由他人觸發、沒有可驗證觸發人的執行,以及沒有任務綁定的雲端節點憑證,都會被拒絕。AI 代理讀取的未讀數只包含執行所在的工作區,不包含擁有者的其他工作區。只有人可以刪除通知。AI 代理做的每次修改都會在伺服器留下紀錄,寫明是哪個 AI 代理、哪次執行、代哪個人操作。在評論中 @ AI 代理、把任務分配給 AI 代理或觸發自動化,都會直接建立一次執行,不會給 AI 代理留通知。`@all` 也只通知成員。diff --git a/apps/docs/content/docs/inbox.zh.mdx b/apps/docs/content/docs/inbox.zh.mdxindex 3158cc2dd1..fc73dcf4b8 100644--- a/apps/docs/content/docs/inbox.zh.mdx+++ b/apps/docs/content/docs/inbox.zh.mdx@@ -56,7 +56,7 @@ import { InboxDemo } from "@/components/demos/inbox-demo";## 智能体与收件箱-收件箱通知属于工作区成员。只有服务端验证运行的上游触发人就是运行环境所有者时,智能体才能读取和处理该所有者的通知。这个身份会沿智能体调用链继承。这条规则覆盖收件箱的所有操作:活跃列表、归档、稍后提醒列表、未读数,以及所有修改。由他人触发、没有可验证触发人的运行,以及没有任务绑定的云节点凭证,都会被拒绝。只有人可以删除通知。智能体做的每次修改都会在服务端留下记录,写明是哪个智能体、哪次运行、代哪个人操作。+收件箱通知属于工作区成员。只有服务端验证运行的上游触发人就是运行环境所有者时,智能体才能读取和处理该所有者的通知。这个身份会沿智能体调用链继承。这条规则覆盖收件箱的所有操作:活跃列表、归档、稍后提醒列表、未读数,以及所有修改。由他人触发、没有可验证触发人的运行,以及没有任务绑定的云节点凭证,都会被拒绝。智能体读取的未读数只包含运行所在的工作区,不包含所有者的其他工作区。只有人可以删除通知。智能体做的每次修改都会在服务端留下记录,写明是哪个智能体、哪次运行、代哪个人操作。在评论中 @智能体、把任务分配给智能体或触发自动化,都会直接创建一次运行,不会给智能体留通知。`@all` 也只通知成员。diff --git a/server/cmd/multica/cmd_inbox.go b/server/cmd/multica/cmd_inbox.goindex cbbfd5dc33..2c85d8f69b 100644--- a/server/cmd/multica/cmd_inbox.go+++ b/server/cmd/multica/cmd_inbox.go@@ -41,7 +41,7 @@ var inboxListCmd = &cobra.Command{var inboxCountCmd = &cobra.Command{Use: "count",Short: "Show your unread notification count",- Long: "Show the unread notification count in the current workspace and in every workspace you belong to. Snoozed issues are not counted.\n\n" + inboxAccessNote,+ Long: "Show the unread notification count in the current workspace and in every workspace you belong to. Snoozed issues are not counted. In an agent run, only the workspace the run belongs to is listed; the owner's other workspaces are left out.\n\n" + inboxAccessNote,Args: exactArgs(0),RunE: runInboxCount,}diff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.goindex 193794b6a3..e8be1cc461 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -616,9 +616,14 @@ type InboxWorkspaceUnreadResponse struct {// UnreadInboxSummary returns per-workspace unread inbox counts across every// workspace the user belongs to. The sidebar uses it to light a dot on the// workspace switcher when a workspace OTHER than the active one has unread-// items, without fetching each workspace's full inbox list. It is-// account-level by nature: it ignores the active workspace and keys only on-// the authenticated user.+// items, without fetching each workspace's full inbox list. For a human+// credential it is account-level by nature: it ignores the active workspace+// and keys only on the authenticated user.+//+// A task credential is bound to one workspace. Its access is verified there,+// and the response is limited to that workspace's row, so an agent the owner+// triggered in one workspace never learns the owner's other workspace IDs or+// their unread counts.func (h *Handler) UnreadInboxSummary(w http.ResponseWriter, r *http.Request) {r, cancel := h.inboxReadRequest(r)defer cancel()@@ -626,13 +631,13 @@ func (h *Handler) UnreadInboxSummary(w http.ResponseWriter, r *http.Request) {if !ok {return}- // The summary ignores the active workspace, but an agent's access is- // verified against the workspace its task runs in.+ var boundWorkspace pgtype.UUIDif r.Header.Get("X-Actor-Source") != "" {wsUUID, ok := parseUUIDOrBadRequest(w, ctxWorkspaceID(r.Context()), "workspace id")if !ok || !h.requireInboxOwnerAccess(w, r, userID, wsUUID) {return}+ boundWorkspace = wsUUID}value, err := h.inboxReadGuard().Summary(r.Context(), userID, func(ctx context.Context) (any, error) {@@ -645,13 +650,22 @@ func (h *Handler) UnreadInboxSummary(w http.ResponseWriter, r *http.Request) {return}+ // The guard coalesces concurrent summary requests per user, so the value+ // here may come from a query another caller started: the owner's own+ // client or a task bound to a different workspace. It is always the+ // account-wide summary; a task credential takes only its bound+ // workspace's row from it, into a new slice, so the shared value stays+ // whole for every other caller of the same coalesced query.rows := value.([]db.CountUnreadInboxByWorkspaceRow)- resp := make([]InboxWorkspaceUnreadResponse, len(rows))- for i, row := range rows {- resp[i] = InboxWorkspaceUnreadResponse{+ resp := make([]InboxWorkspaceUnreadResponse, 0, len(rows))+ for _, row := range rows {+ if boundWorkspace.Valid && row.WorkspaceID != boundWorkspace {+ continue+ }+ resp = append(resp, InboxWorkspaceUnreadResponse{WorkspaceID: uuidToString(row.WorkspaceID),Count: row.Count,- }+ })}writeJSON(w, http.StatusOK, resp)diff --git a/server/internal/handler/inbox_write_access_test.go b/server/internal/handler/inbox_write_access_test.goindex d85bb90015..aa999895af 100644--- a/server/internal/handler/inbox_write_access_test.go+++ b/server/internal/handler/inbox_write_access_test.go@@ -1,12 +1,20 @@package handlerimport (+ "context"+ "encoding/json"+ "fmt""net/http"+ "net/http/httptest"+ "sync"+ "sync/atomic""testing""time""github.com/google/uuid"+ "github.com/jackc/pgx/v5""github.com/multica-ai/multica/server/internal/auth"+ "github.com/multica-ai/multica/server/internal/inboxread""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/testutil")@@ -202,3 +210,145 @@ func TestDeleteInboxItemIsHumanOnly(t *testing.T) {t.Fatal("human delete left the notification in place")}}++// A task credential is bound to one workspace. When the owner triggered it+// and belongs to other workspaces too, the cross-workspace summary must not+// carry those workspaces' IDs or unread counts back to the agent, while the+// owner's own credential still sees every workspace. The inbox read guard+// coalesces concurrent summary requests per user, so the agent and the owner+// are lined up to share one query, in both arrival orders: whichever of them+// starts the shared query, each gets only what its credential allows.+func TestUnreadInboxSummaryTaskCredentialStaysInBoundWorkspace(t *testing.T) {+ f := newInboxWriteFixture(t)+ other := newInboxWriteFixture(t)+ f.item(t)+ other.item(t)+ token := f.taskToken(t, testUserID)++ for _, agentFirst := range []bool{true, false} {+ t.Run(fmt.Sprintf("agent first=%v", agentFirst), func(t *testing.T) {+ gate := make(chan struct{})+ starter := &gatedSummaryStarter{inner: testPool, gate: gate, blocked: make(chan struct{})}+ h := *testHandler+ h.InboxReads = inboxread.New(inboxread.Config{Concurrency: 2})+ h.TxStarter = starter+ asAgent := middleware.Auth(h.Queries, nil, nil, nil)(+ middleware.RequireWorkspaceMember(h.Queries)(http.HandlerFunc(h.UnreadInboxSummary)))+ asOwner := middleware.RequireWorkspaceMember(h.Queries)(http.HandlerFunc(h.UnreadInboxSummary))+ agentRequest := func() *http.Request {+ return testutil.WithHeaders(testutil.JSONRequest(http.MethodGet, "/api/inbox/unread-summary", nil),+ "Authorization", "Bearer "+token, "X-Workspace-ID", f.workspaceID)+ }+ ownerRequest := func() *http.Request {+ return inboxRequest(http.MethodGet, "/api/inbox/unread-summary", f.workspaceID)+ }+ serve := func(handler http.Handler, req *http.Request) <-chan *httptest.ResponseRecorder {+ done := make(chan *httptest.ResponseRecorder, 1)+ go func() {+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, req)+ done <- rec+ }()+ return done+ }+ // joined waits until n callers are inside the pending follow-up+ // generation, counted under the guard's admission lock.+ joined := func(n int) {+ t.Helper()+ deadline := time.Now().Add(2 * time.Second)+ for h.InboxReads.PendingSummaryCallers(testUserID) != n {+ if time.Now().After(deadline) {+ t.Fatalf("pending summary callers = %d, want %d", h.InboxReads.PendingSummaryCallers(testUserID), n)+ }+ time.Sleep(time.Millisecond)+ }+ }++ // An owner request occupies the running query, so the next two+ // requests queue into one shared follow-up query.+ warmUp := serve(asOwner, ownerRequest())+ select {+ case <-starter.blocked:+ case rec := <-warmUp:+ t.Fatalf("warm-up summary finished before its query was held: %d %s", rec.Code, rec.Body.String())+ case <-time.After(5 * time.Second):+ t.Fatal("warm-up summary query never started")+ }+ var agentDone, ownerDone <-chan *httptest.ResponseRecorder+ if agentFirst {+ agentDone = serve(asAgent, agentRequest())+ joined(1)+ ownerDone = serve(asOwner, ownerRequest())+ } else {+ ownerDone = serve(asOwner, ownerRequest())+ joined(1)+ agentDone = serve(asAgent, agentRequest())+ }+ joined(2)+ close(gate)++ summaryOf := func(name string, done <-chan *httptest.ResponseRecorder) map[string]int64 {+ t.Helper()+ rec := <-done+ if rec.Code != http.StatusOK {+ t.Fatalf("%s summary status = %d: %s", name, rec.Code, rec.Body.String())+ }+ var rows []InboxWorkspaceUnreadResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &rows); err != nil {+ t.Fatalf("%s summary: %v", name, err)+ }+ counts := make(map[string]int64, len(rows))+ for _, row := range rows {+ counts[row.WorkspaceID] = row.Count+ }+ return counts+ }+ agentView := summaryOf("agent", agentDone)+ if len(agentView) != 1 || agentView[f.workspaceID] != 1 {+ t.Fatalf("task credential summary = %v; want only bound workspace %s with 1 unread", agentView, f.workspaceID)+ }+ for name, done := range map[string]<-chan *httptest.ResponseRecorder{"owner": ownerDone, "warm-up owner": warmUp} {+ if view := summaryOf(name, done); view[f.workspaceID] != 1 || view[other.workspaceID] != 1 {+ t.Fatalf("%s summary = %v; want both workspaces", name, view)+ }+ }+ if queries := starter.queries.Load(); queries != 2 {+ t.Fatalf("summary queries = %d; want 2, the agent and owner sharing one", queries)+ }+ })+ }+}++// gatedSummaryStarter holds every inbox read query until gate closes, and+// counts them. Begin itself is not held: it runs under a short setup budget.+type gatedSummaryStarter struct {+ inner txStarter+ gate <-chan struct{}+ blocked chan struct{}+ once sync.Once+ queries atomic.Int32+}++func (s *gatedSummaryStarter) Begin(ctx context.Context) (pgx.Tx, error) {+ tx, err := s.inner.Begin(ctx)+ if err != nil {+ return nil, err+ }+ return gatedSummaryTx{Tx: tx, starter: s}, nil+}++type gatedSummaryTx struct {+ pgx.Tx+ starter *gatedSummaryStarter+}++func (tx gatedSummaryTx) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {+ tx.starter.queries.Add(1)+ tx.starter.once.Do(func() { close(tx.starter.blocked) })+ select {+ case <-tx.starter.gate:+ case <-ctx.Done():+ return nil, ctx.Err()+ }+ return tx.Tx.Query(ctx, sql, args...)+}diff --git a/server/internal/inboxread/guard.go b/server/internal/inboxread/guard.goindex ca54e31e8a..1ff89e82f7 100644--- a/server/internal/inboxread/guard.go+++ b/server/internal/inboxread/guard.go@@ -79,6 +79,7 @@ type summaryGeneration struct {ctx context.Contextquery func(context.Context) (any, error)started bool // protected by summaryMu+ callers int // callers joined to this generation; protected by summaryMudone chan struct{}value anyerr error@@ -247,6 +248,7 @@ func (g *Guard) Summary(ctx context.Context, userID string, query func(context.C}generation = queue.next}+ generation.callers++g.summaryMu.Unlock()select {case <-generation.done:@@ -258,6 +260,25 @@ func (g *Guard) Summary(ctx context.Context, userID string, query func(context.C}}+// PendingSummaryCallers reports how many callers have joined the user's+// generation that has not started yet, all of which will share its one query.+// It reads under the same lock that admits callers, so a count of n means n+// callers are already in that generation, not merely admitted to Summary.+func (g *Guard) PendingSummaryCallers(userID string) int {+ g.summaryMu.Lock()+ defer g.summaryMu.Unlock()+ queue := g.summaryCalls[userID]+ switch {+ case queue == nil:+ return 0+ case !queue.current.started:+ return queue.current.callers+ case queue.next != nil:+ return queue.next.callers+ }+ return 0+}+func newSummaryGeneration(ctx context.Context, query func(context.Context) (any, error)) *summaryGeneration {return &summaryGeneration{ctx: context.WithoutCancel(ctx), query: query, done: make(chan struct{})}}diff --git a/server/internal/inboxread/guard_test.go b/server/internal/inboxread/guard_test.goindex e4978cabd6..41583feeb1 100644--- a/server/internal/inboxread/guard_test.go+++ b/server/internal/inboxread/guard_test.go@@ -316,3 +316,47 @@ func TestSummarySlowReadReturnsEachGenerationWithItsOwnBudget(t *testing.T) {t.Fatalf("SQL executions = %d, want 2", runs.Load())}}++// PendingSummaryCallers counts only callers already inside the generation that+// will run next, so a test can wait until callers share one query.+func TestPendingSummaryCallersCountsJoinedGeneration(t *testing.T) {+ g := New(Config{Concurrency: 2})+ started, finish := make(chan struct{}), make(chan struct{})+ var calls atomic.Int32+ query := func(context.Context) (any, error) {+ if calls.Add(1) == 1 {+ close(started)+ <-finish+ }+ return nil, nil+ }+ if n := g.PendingSummaryCallers("user"); n != 0 {+ t.Fatalf("idle pending = %d", n)+ }+ done := make(chan error, 3)+ read := func() { _, err := g.Summary(context.Background(), "user", query); done <- err }+ go read()+ <-started+ if n := g.PendingSummaryCallers("user"); n != 0 {+ t.Fatalf("running generation counted as pending: %d", n)+ }+ go read()+ eventually(t, func() bool { return g.PendingSummaryCallers("user") == 1 })+ go read()+ eventually(t, func() bool { return g.PendingSummaryCallers("user") == 2 })+ if n := g.PendingSummaryCallers("other"); n != 0 {+ t.Fatalf("other user pending = %d", n)+ }+ close(finish)+ for range 3 {+ if err := <-done; err != nil {+ t.Fatal(err)+ }+ }+ if calls.Load() != 2 {+ t.Fatalf("pending callers did not share one query: %d", calls.Load())+ }+ if n := g.PendingSummaryCallers("user"); n != 0 {+ t.Fatalf("finished pending = %d", n)+ }+}