Skip to content

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

Go

feat(cli): add read-only inbox list with owner-triggered access (MUL-9382) (#10726)

Multica Eve0dfa8290ca77
diff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdx
index a5a2ac15ff..283b7884e9 100644
--- a/apps/docs/content/docs/cli.fr.mdx
+++ b/apps/docs/content/docs/cli.fr.mdx
@@ -371,6 +371,7 @@ multica autopilot trigger-update <autopilot-id> <trigger-id> --clear-event-filte
| --- | --- |
| `issue` | Créer, mettre à jour, assigner et rechercher des tâches ; gérer les commentaires, les abonnés, les étiquettes, les propriétés, les réveils, la chronologie et les exécutions |
| `project` | Gérer les projets et leurs ressources |
+| `inbox` | Lire vos notifications sans modifier leur état lu |
| `label`, `property` | Gérer les étiquettes et les propriétés personnalisées de l'espace de travail |
| `view` | Lire les vues enregistrées et lister les tâches qu'une vue affiche |
| `agent`, `skill`, `squad` | Gérer les agents, les skills et les squads |
@@ -500,6 +501,7 @@ Les tableaux ci-dessous couvrent toutes les commandes de premier niveau actuelle
| | `member list/add/set-role/remove` | Gérer les membres d'un squad | |
| | `activity <issue-id> <outcome>` | Enregistrer une évaluation du chef | |
| `chat` | `history`, `thread [id]` | Lire la session de messagerie externe qu'un agent traite actuellement | `--limit`, `--before` |
+| `inbox` | `list` | [Lire vos notifications actives](/inbox) sans les marquer comme lues | `--project`, `--type`, `--output` (`table` ou `json`) ; filtres locaux |
### Runtime
diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdx
index 9445f4c163..394a39ac44 100644
--- a/apps/docs/content/docs/cli.ja.mdx
+++ b/apps/docs/content/docs/cli.ja.mdx
@@ -371,6 +371,7 @@ multica autopilot trigger-update <autopilot-id> <trigger-id> --clear-event-filte
| --- | --- |
| `issue` | タスクの作成、更新、割り当て、検索。コメント、購読者、ラベル、プロパティ、ウェイクアップ、タイムライン、実行履歴の管理 |
| `project` | プロジェクトとそのリソースを管理 |
+| `inbox` | 既読状態を変えずに自分の通知を読み取る |
| `label`、`property` | ワークスペースのラベルとカスタムプロパティを管理 |
| `view` | 保存したビューを読み取り、ビューに表示されるタスクを一覧 |
| `agent`、`skill`、`squad` | エージェント、スキル、スクワッドを管理 |
@@ -492,6 +493,7 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで
| | `member list/add/set-role/remove` | スクワッドのメンバーを管理 | |
| | `activity <issue-id> <outcome>` | リーダーの評価を記録 | |
| `chat` | `history`、`thread [id]` | エージェントが現在処理している外部チャットセッションを読み取り | `--limit`、`--before` |
+| `inbox` | `list` | 既読にせずに[現在の通知を読み取る](/inbox) | `--project`、`--type`、`--output`(`table` または `json`);フィルターはローカルで適用 |
### Runtime
diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdx
index 3709e43b24..ce401b459c 100644
--- a/apps/docs/content/docs/cli.ko.mdx
+++ b/apps/docs/content/docs/cli.ko.mdx
@@ -371,6 +371,7 @@ multica autopilot trigger-update <autopilot-id> <trigger-id> --clear-event-filte
| --- | --- |
| `issue` | 태스크 생성, 업데이트, 할당, 검색. 댓글, 구독, 라벨, 속성, 깨우기, 타임라인, 실행 기록 관리 |
| `project` | 프로젝트와 프로젝트 리소스 관리 |
+| `inbox` | 읽음 상태를 바꾸지 않고 내 알림 읽기 |
| `label`, `property` | 워크스페이스 라벨과 사용자 지정 속성 관리 |
| `view` | 저장된 뷰를 읽고 뷰에 보이는 태스크 나열 |
| `agent`, `skill`, `squad` | 에이전트, 스킬, 스쿼드 관리 |
@@ -492,6 +493,7 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t
| | `member list/add/set-role/remove` | 스쿼드 멤버 관리 | |
| | `activity <issue-id> <outcome>` | 리더 평가 기록 | |
| `chat` | `history`, `thread [id]` | 에이전트가 현재 처리 중인 외부 채팅 대화 읽기 | `--limit`, `--before` |
+| `inbox` | `list` | 읽음으로 표시하지 않고 [현재 알림 읽기](/inbox) | `--project`, `--type`, `--output` (`table` 또는 `json`); 필터는 로컬에서 적용 |
### Runtime
diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdx
index c1bb2e17b5..581fa657b5 100644
--- a/apps/docs/content/docs/cli.mdx
+++ b/apps/docs/content/docs/cli.mdx
@@ -386,6 +386,7 @@ multica autopilot trigger-update <autopilot-id> <trigger-id> --clear-event-filte
| --- | --- |
| `issue` | Create, update, assign, and search issues; manage comments, subscribers, labels, properties, wakeups, the timeline, and runs |
| `project` | Manage projects, their resources, and the workflow they use |
+| `inbox` | Read your notifications without changing read status |
| `workflow` | Manage issue workflows: statuses and who handles each one |
| `issue-status` | Manage the workspace status catalog: statuses, their color, and their icon |
| `label`, `property` | Manage workspace labels and custom properties |
@@ -527,6 +528,7 @@ Migration from CSV parsing: replace `--attachment a,b` with `--attachment a --at
| | `member list/add/set-role/remove` | Manage squad members | |
| | `activity <issue-id> <outcome>` | Record a leader evaluation | |
| `chat` | `history`, `thread [id]` | Read the external chat session an agent is currently handling | `--limit`, `--before` |
+| `inbox` | `list` | [Read your active notifications](/inbox) without marking them read | `--project`, `--type`, `--output` (`table` or `json`); filters apply locally |
### Runtime
diff --git a/apps/docs/content/docs/cli.zh-Hant.mdx b/apps/docs/content/docs/cli.zh-Hant.mdx
index 2c988de31a..b76fde504e 100644
--- a/apps/docs/content/docs/cli.zh-Hant.mdx
+++ b/apps/docs/content/docs/cli.zh-Hant.mdx
@@ -368,6 +368,7 @@ multica autopilot trigger-update <autopilot-id> <trigger-id> --clear-event-filte
| --- | --- |
| `issue` | 建立、更新、分配和搜尋任務;管理評論、訂閱、標籤、屬性、喚醒、時間線與執行記錄 |
| `project` | 管理專案、專案資源和專案使用的工作流 |
+| `inbox` | 讀取自己的通知,不改變已讀狀態 |
| `workflow` | 管理工作流:狀態以及每個狀態交給誰處理 |
| `issue-status` | 管理工作區狀態目錄:狀態及其顏色和圖示 |
| `label`、`property` | 管理工作區標籤和自定義屬性 |
@@ -501,6 +502,7 @@ CLI 配置檔案包含可代表你訪問 Multica 的令牌。不要提交到倉
| | `member list/add/set-role/remove` | 管理小隊成員 | |
| | `activity <issue-id> <outcome>` | 記錄隊長評價 | |
| `chat` | `history`、`thread [id]` | 讀取 AI 代理當前正在處理的外部聊天會話 | `--limit`、`--before` |
+| `inbox` | `list` | [讀取目前通知](/inbox),不標為已讀 | `--project`、`--type`、`--output`(`table` 或 `json`);篩選在本機套用 |
### Runtime
diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdx
index f563c41edb..33e82451e6 100644
--- a/apps/docs/content/docs/cli.zh.mdx
+++ b/apps/docs/content/docs/cli.zh.mdx
@@ -371,6 +371,7 @@ multica autopilot trigger-update <autopilot-id> <trigger-id> --clear-event-filte
| --- | --- |
| `issue` | 创建、更新、分配和搜索任务;管理评论、订阅、标签、属性、唤醒、时间线与执行记录 |
| `project` | 管理项目、项目资源和项目使用的工作流 |
+| `inbox` | 读取自己的通知,不改变已读状态 |
| `workflow` | 管理工作流:状态以及每个状态交给谁处理 |
| `issue-status` | 管理工作区状态目录:状态及其颜色和图标 |
| `label`、`property` | 管理工作区标签和自定义属性 |
@@ -504,6 +505,7 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓
| | `member list/add/set-role/remove` | 管理小队成员 | |
| | `activity <issue-id> <outcome>` | 记录队长评价 | |
| `chat` | `history`、`thread [id]` | 读取智能体当前正在处理的外部聊天会话 | `--limit`、`--before` |
+| `inbox` | `list` | [读取当前通知](/inbox),不标为已读 | `--project`、`--type`、`--output`(`table` 或 `json`);筛选在本地应用 |
### Runtime
diff --git a/apps/docs/content/docs/concepts.fr.mdx b/apps/docs/content/docs/concepts.fr.mdx
index 94b36c2c12..fe421bc10c 100644
--- a/apps/docs/content/docs/concepts.fr.mdx
+++ b/apps/docs/content/docs/concepts.fr.mdx
@@ -51,7 +51,7 @@ Un moyen d'échanger qui n'est rattaché à aucune tâche — idéal pour les qu
### Boîte de réception
-Le centre de notifications d'un membre : l'activité sur les tâches auxquelles il est abonné, les mentions et les assignations y arrivent. Les agents n'utilisent pas la Boîte de réception. Voir [Boîte de réception et abonnements](/inbox).
+Le centre de notifications d'un membre : l'activité sur les tâches auxquelles il est abonné, les mentions et les assignations y arrivent. Les agents reçoivent directement des exécutions ; lire la liste des notifications actives du propriétaire du runtime exige une exécution déclenchée par ce propriétaire. Voir [Boîte de réception et abonnements](/inbox).
### Automatisation
diff --git a/apps/docs/content/docs/concepts.ja.mdx b/apps/docs/content/docs/concepts.ja.mdx
index e02d1fc220..5f8842cc6b 100644
--- a/apps/docs/content/docs/concepts.ja.mdx
+++ b/apps/docs/content/docs/concepts.ja.mdx
@@ -51,7 +51,7 @@ import { ConceptMapDemo } from "@/components/demos/concept-map-demo";
### インボックス
-メンバーの通知センターで、購読しているタスクの動き、メンション、割り当てがここに集まります。エージェントはインボックスを使いません。詳しくは[インボックスと購読](/inbox)を参照してください。
+メンバーの通知センターで、購読しているタスクの動き、メンション、割り当てがここに集まります。エージェントは実行を直接受け取り、ランタイム所有者のアクティブな通知一覧を読むには、その所有者本人が開始した実行が必要です。詳しくは[インボックスと購読](/inbox)を参照してください。
### オートパイロット
diff --git a/apps/docs/content/docs/concepts.ko.mdx b/apps/docs/content/docs/concepts.ko.mdx
index 297168e3a3..cb6cd1a01b 100644
--- a/apps/docs/content/docs/concepts.ko.mdx
+++ b/apps/docs/content/docs/concepts.ko.mdx
@@ -51,7 +51,7 @@ import { ConceptMapDemo } from "@/components/demos/concept-map-demo";
### 인박스
-멤버를 위한 알림 센터입니다. 구독한 태스크의 활동, 멘션, 할당 알림이 이곳에 모입니다. 에이전트는 인박스를 사용하지 않습니다. 자세한 내용은 [인박스와 구독](/inbox)을 참고하세요.
+멤버를 위한 알림 센터입니다. 구독한 태스크의 활동, 멘션, 할당 알림이 이곳에 모입니다. 에이전트는 실행을 직접 받으며, 런타임 소유자의 활성 알림 목록을 읽으려면 해당 소유자 본인이 시작한 실행이어야 합니다. 자세한 내용은 [인박스와 구독](/inbox)을 참고하세요.
### 오토파일럿
diff --git a/apps/docs/content/docs/concepts.mdx b/apps/docs/content/docs/concepts.mdx
index f372233934..1adbc133f0 100644
--- a/apps/docs/content/docs/concepts.mdx
+++ b/apps/docs/content/docs/concepts.mdx
@@ -51,7 +51,7 @@ A way to talk that is not attached to an issue — good for questions and quick
### Inbox
-A member's notification center: activity on subscribed issues, mentions, and assignments all land here. Agents do not use the inbox. See [Inbox and subscriptions](/inbox).
+A member's notification center: activity on subscribed issues, mentions, and assignments all land here. Agents receive runs directly; reading the runtime owner's active notification list requires a run triggered by that owner. See [Inbox and subscriptions](/inbox).
### Autopilot
diff --git a/apps/docs/content/docs/concepts.zh-Hant.mdx b/apps/docs/content/docs/concepts.zh-Hant.mdx
index f9f7f1cb79..ffa1e53e64 100644
--- a/apps/docs/content/docs/concepts.zh-Hant.mdx
+++ b/apps/docs/content/docs/concepts.zh-Hant.mdx
@@ -51,7 +51,7 @@ AI 代理的一次具體執行記錄。每次觸發產生一次執行,由某
### 收件箱
-成員的通知中心:訂閱的任務動態、提及和分配都匯聚在這裡。AI 代理不使用收件箱。詳見[收件箱與訂閱](/inbox)。
+成員的通知中心:訂閱的任務動態、提及和分配都匯聚在這裡。AI 代理直接接收執行;讀取執行環境擁有者的活躍通知列表,需要由該擁有者本人觸發。詳見[收件箱與訂閱](/inbox)。
### 自動化
diff --git a/apps/docs/content/docs/concepts.zh.mdx b/apps/docs/content/docs/concepts.zh.mdx
index 40195239e8..9324ee313d 100644
--- a/apps/docs/content/docs/concepts.zh.mdx
+++ b/apps/docs/content/docs/concepts.zh.mdx
@@ -51,7 +51,7 @@ import { ConceptMapDemo } from "@/components/demos/concept-map-demo";
### 收件箱
-成员的通知中心:订阅的任务动态、提及和分配都汇聚在这里。智能体不使用收件箱。详见[收件箱与订阅](/inbox)。
+成员的通知中心:订阅的任务动态、提及和分配都汇聚在这里。智能体直接接收运行;读取运行环境所有者的活跃通知列表,需要由该所有者本人触发。详见[收件箱与订阅](/inbox)。
### 自动化
diff --git a/apps/docs/content/docs/inbox.fr.mdx b/apps/docs/content/docs/inbox.fr.mdx
index d020795453..0d4bdfdba0 100644
--- a/apps/docs/content/docs/inbox.fr.mdx
+++ b/apps/docs/content/docs/inbox.fr.mdx
@@ -53,12 +53,24 @@ Sur une tâche assignée à quelqu'un d'autre ou à son agent, un abonnement obt
La page de la tâche signale un tel abonnement par **Mises à jour clés**. Son menu propose **Recevoir toute l'activité**, qui en fait un abonnement explicite à cette tâche ; il n'est ensuite plus possible de revenir aux mises à jour clés pour cette tâche, seulement de se désabonner. **Modifier la valeur par défaut** ouvre **Paramètres → Notifications**, où **Tâches des autres**, en tête de **Tâches que vous suivez**, fait passer toutes ces tâches à **Toute l'activité**.
-## Les agents n'utilisent pas la boîte de réception
+## Les agents et la boîte de réception
-La boîte de réception est réservée aux membres de l'espace de travail. Même lorsqu'un agent est l'assigné ou un abonné, il ne lit jamais les notifications de la boîte de réception.
+Les notifications appartiennent aux membres de l'espace de travail. Pour la liste des notifications actives utilisée par `multica inbox list`, un agent peut lire 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. 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, ne peuvent pas lire cette liste active. Cette garantie couvre uniquement la liste active ; les listes archivées et reportées, les compteurs de non-lus et les interfaces d'écriture conservent leurs permissions actuelles en attendant un traitement séparé.
@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.
+## Lire depuis le CLI
+
+Utilisez votre connexion CLI existante pour lister les notifications actives sans les marquer comme lues :
+
+```sh
+multica inbox list --project <project-id> --type mentioned --output json
+```
+
+`--project` accepte un UUID complet ou un préfixe d'ID unique, y compris l'ID court affiché par `multica project list`. Les préfixes sont résolus via la liste des projets avant de lire la boîte de réception ; un préfixe sans correspondance ou ambigu produit une erreur.
+
+Les deux filtres sont facultatifs et s'appliquent localement après récupération de la boîte de réception active. Le JSON contient les ID de notification, de tâche, de projet et, si disponible, de commentaire, ainsi que le type, le titre, l'état lu et la date de création. La sortie par défaut est un tableau. Une exécution d'agent autorisée utilise son identifiant d'exécution pour lire les notifications du propriétaire du runtime, sans revenir à la connexion d'une personne.
+
## Traiter les notifications
Cliquez sur une ligne pour ouvrir sa tâche au commentaire ou à la demande d'application dont parle la notification. La ligne reste en surbrillance tant que la tâche est ouverte, et un nouveau clic vous ramène à cet endroit. Ouvrir la tâche marque la notification comme lue, et la ligne reste dans la liste. Les notifications sans tâche, comme les mises en pause d'automatisation et les résultats de création rapide, s'ouvrent sur la page Boîte de réception.
diff --git a/apps/docs/content/docs/inbox.ja.mdx b/apps/docs/content/docs/inbox.ja.mdx
index a7956ac2a0..83caac5930 100644
--- a/apps/docs/content/docs/inbox.ja.mdx
+++ b/apps/docs/content/docs/inbox.ja.mdx
@@ -53,12 +53,24 @@ import { InboxDemo } from "@/components/demos/inbox-demo";
タスクのページでは、こうした購読に **重要な更新のみ** と表示されます。メニューの **すべてのアクティビティを受け取る** を選ぶと、このタスクの明示的な購読に変わります。その後このタスクを重要な更新のみに戻す方法はなく、購読解除だけが可能です。**デフォルトを変更** は **設定 → 通知** を開きます。**購読中のタスク** の先頭にある **他の人のタスク** を **すべてのアクティビティ** にすると、こうしたタスクすべてにアクティビティが届くようになります。
-## エージェントはインボックスを使わない
+## エージェントとインボックス
-インボックスはワークスペースメンバー専用です。エージェントが担当者や購読者であっても、インボックスの通知を読むことはありません。
+インボックスの通知はワークスペースメンバーに属します。`multica inbox list` が使うアクティブな通知一覧では、実行を開始した上流のユーザーがランタイム所有者本人であるとサーバーが確認できた場合だけ、エージェントがその所有者の通知を読み取れます。このユーザー情報はエージェントの委任チェーンで引き継がれます。他の人が開始した実行、開始した人を確認できない実行、タスクとの紐付けがないクラウドノードの認証情報では、このアクティブ一覧を読み取れません。この保証はアクティブ一覧のみが対象です。アーカイブ済み・スヌーズ中の一覧、未読件数、書き込み API は従来の権限を維持し、別途対応します。
コメントでの @メンション、タスクの割り当て、オートパイロットのトリガーは、直接実行を作成し、エージェントに通知は残しません。`@all` もメンバーにのみ通知します。
+## CLI から読み取る
+
+既存の CLI ログインを使い、通知を既読にせずに現在の通知を一覧表示できます。
+
+```sh
+multica inbox list --project <project-id> --type mentioned --output json
+```
+
+`--project` は完全な UUID または一意の ID プレフィックスを受け付けます。`multica project list` に表示される短い ID も使えます。プレフィックスはインボックスの読み取り前にプロジェクト一覧から解決され、一致なしや曖昧な場合はエラーになります。
+
+両方のフィルターは省略可能で、現在のインボックスの取得後にローカルで適用されます。JSON には通知、タスク、プロジェクト、および存在する場合はコメントの ID と、種類、タイトル、既読状態、作成日時が含まれます。既定の出力は表です。許可されたエージェント実行はタスクの認証情報でランタイム所有者の通知を読み取り、ユーザーのログイン情報にはフォールバックしません。
+
## 通知の処理
行をクリックすると、そのタスクが開き、通知の対象のコメントまたはアプリのリクエストの位置に移動します。タスクを開いている間、その行はハイライトされたままで、もう一度クリックするとその位置に戻ります。タスクを開くと通知は既読になりますが、行はリストに残ります。オートパイロットの一時停止やエージェント経由の作成結果など、タスクのない通知はインボックスページで開きます。
diff --git a/apps/docs/content/docs/inbox.ko.mdx b/apps/docs/content/docs/inbox.ko.mdx
index a1db174936..d092305265 100644
--- a/apps/docs/content/docs/inbox.ko.mdx
+++ b/apps/docs/content/docs/inbox.ko.mdx
@@ -53,12 +53,24 @@ import { InboxDemo } from "@/components/demos/inbox-demo";
태스크 페이지는 이런 구독에 **주요 업데이트만**이라고 표시합니다. 메뉴에서 **모든 활동 받기**를 고르면 이 태스크에 대한 직접 구독으로 바뀌며, 이후 이 태스크를 주요 업데이트만으로 되돌릴 방법은 없고 구독 취소만 할 수 있습니다. **기본값 변경**은 **설정 → 알림**을 열며, **구독 중인 태스크** 맨 위의 **다른 사람의 태스크**를 **모든 활동**으로 바꾸면 이런 태스크 전부가 모든 활동을 받습니다.
-## 에이전트는 인박스를 사용하지 않습니다
+## 에이전트와 인박스
-인박스는 워크스페이스 멤버만 사용합니다. 에이전트가 담당자나 구독자여도 인박스 알림을 읽지 않습니다.
+인박스 알림은 워크스페이스 멤버의 데이터입니다. `multica inbox list`가 사용하는 활성 알림 목록에서는 서버가 실행을 시작한 상위 사용자가 런타임 소유자 본인임을 확인한 경우에만 에이전트가 해당 소유자의 알림을 읽을 수 있습니다. 이 사용자 정보는 에이전트 위임 체인을 따라 상속됩니다. 다른 사람이 시작한 실행, 시작한 사람을 확인할 수 없는 실행, 태스크에 연결되지 않은 클라우드 노드 자격 증명으로는 이 활성 목록을 읽을 수 없습니다. 이 보장은 활성 목록에만 적용됩니다. 보관 및 다시 알림 목록, 읽지 않은 알림 수, 쓰기 API의 권한은 현재 상태를 유지하며 별도로 처리합니다.
댓글에서 에이전트를 @멘션하거나 태스크를 에이전트에게 할당하거나 자동화를 트리거하면 실행이 직접 생성되며, 에이전트에게 알림을 남기지 않습니다. `@all`도 멤버에게만 알립니다.
+## CLI에서 읽기
+
+기존 CLI 로그인으로 현재 알림을 읽음으로 표시하지 않고 조회할 수 있습니다.
+
+```sh
+multica inbox list --project <project-id> --type mentioned --output json
+```
+
+`--project`는 전체 UUID 또는 고유한 ID 접두사를 받으며 `multica project list`에 표시되는 짧은 ID도 사용할 수 있습니다. 인박스를 읽기 전에 프로젝트 목록에서 접두사를 확인하고, 일치하는 프로젝트가 없거나 여러 개이면 오류를 반환합니다.
+
+두 필터는 모두 선택 사항이며 현재 인박스를 가져온 후 로컬에서 적용됩니다. JSON에는 알림, 태스크, 프로젝트 및 가능한 경우 댓글 ID와 유형, 제목, 읽음 상태, 생성 시간이 포함됩니다. 기본 출력은 표입니다. 허용된 에이전트 실행은 태스크 자격 증명으로 런타임 소유자의 알림을 읽으며 사람의 로그인 정보로 대체하지 않습니다.
+
## 알림 처리
행을 클릭하면 해당 태스크가 열리고, 알림이 가리키는 댓글이나 앱 요청 위치로 이동합니다. 태스크가 열려 있는 동안 그 행은 강조된 채로 남고, 다시 클릭하면 그 위치로 돌아갑니다. 태스크를 열면 알림은 읽음으로 바뀌지만 행은 목록에 그대로 남습니다. 자동화 일시 중지나 빠른 생성 결과처럼 태스크가 없는 알림은 인박스 페이지에서 열립니다.
diff --git a/apps/docs/content/docs/inbox.mdx b/apps/docs/content/docs/inbox.mdx
index 99932562af..ef555b46a8 100644
--- a/apps/docs/content/docs/inbox.mdx
+++ b/apps/docs/content/docs/inbox.mdx
@@ -53,12 +53,24 @@ On an issue assigned to someone else or to their agent, a subscription you picke
The issue page marks such a subscription **Key updates only**. Its menu offers **Get all activity**, which turns it into an explicit subscription to this issue; there's no way back to key updates for that issue afterwards, only unsubscribing. **Change the default** opens **Settings → Notifications**, where **Other people's issues**, at the top of **Issues you subscribe to**, switches all such issues to **All activity**.
-## Agents don't use the inbox
+## Agents and the inbox
-The inbox is only for workspace members. Even when an agent is the assignee or a subscriber, it never reads inbox notifications.
+Inbox notifications belong to workspace members. For the active notification list used by `multica inbox list`, an agent may read 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. Runs triggered by another person or without a verifiable human, and cloud-node credentials without a task binding, cannot read that active list. This guarantee covers only the active list; archived and snoozed lists, unread counts and write endpoints retain their current permissions pending separate work.
@-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.
+## Read from the CLI
+
+Use your existing CLI login to list your active notifications without marking them read:
+
+```sh
+multica inbox list --project <project-id> --type mentioned --output json
+```
+
+`--project` accepts a full UUID or a unique ID prefix, including the short ID from `multica project list`. Prefixes are resolved through the project list before reading the inbox; no match or an ambiguous prefix produces an error.
+
+Both filters are optional and apply locally after fetching the active inbox. JSON includes notification, issue, project and optional comment IDs, plus the type, title, read status and creation time. The default output is a table. An authorized agent run reads the runtime owner's notifications using its task credential; it never falls back to a person's login.
+
## Handle notifications
Click a row to open its issue at the comment or app request the notification is about. The row stays lit while the issue is open, and clicking it again takes you back to that spot. Opening the issue marks the notification read, and the row stays in the list. Notifications without an issue, such as autopilot pauses and quick-create results, open on the Inbox page instead.
diff --git a/apps/docs/content/docs/inbox.zh-Hant.mdx b/apps/docs/content/docs/inbox.zh-Hant.mdx
index fa0864c3d5..9ac7ecf6db 100644
--- a/apps/docs/content/docs/inbox.zh-Hant.mdx
+++ b/apps/docs/content/docs/inbox.zh-Hant.mdx
@@ -53,12 +53,24 @@ import { InboxDemo } from "@/components/demos/inbox-demo";
任務頁面會把這類訂閱標為**僅關鍵更新**。點開後選**接收全部動態**,會把它變為對這個任務的手動訂閱;之後這個任務無法再退回僅關鍵更新,只能取消訂閱。**修改預設設定**會打開**設定 → 通知**,把**你訂閱的任務**分組頂部的**別人的任務**改為**全部動態**,所有這類任務都會推送全部動態。
-## AI 代理不使用收件箱
+## AI 代理與收件箱
-收件箱只面向工作區成員。即使 AI 代理是負責人或訂閱者,它也不會讀取收件箱通知。
+收件箱通知屬於工作區成員。對於 `multica inbox list` 使用的活躍通知列表,只有伺服器驗證執行的上游觸發人就是執行環境擁有者時,AI 代理才能讀取該擁有者的列表。這個身分會沿 AI 代理呼叫鏈繼承。由他人觸發、沒有可驗證觸發人的執行,以及沒有任務綁定的雲端節點憑證,都不能讀取該活躍列表。此保證只涵蓋活躍列表;封存、稍後提醒、未讀數和寫入介面沿用現有權限,另案處理。
在評論中 @ AI 代理、把任務分配給 AI 代理或觸發自動化,都會直接建立一次執行,不會給 AI 代理留通知。`@all` 也只通知成員。
+## 用 CLI 讀取
+
+沿用現有 CLI 登入,列出目前通知,不會將通知標為已讀:
+
+```sh
+multica inbox list --project <project-id> --type mentioned --output json
+```
+
+`--project` 接受完整 UUID 或唯一 ID 前綴,包括 `multica project list` 顯示的短 ID。前綴會先透過專案列表解析,再讀取收件箱;沒有符合項目或前綴有歧義時會顯示錯誤。
+
+兩個篩選條件都可省略,在取得目前收件箱後於本機套用。JSON 包含通知、任務、專案和可選的評論 ID,以及類型、標題、已讀狀態和建立時間。預設輸出為表格。獲授權的 AI 代理執行使用任務憑證讀取執行環境擁有者的通知,不會退回使用人的登入憑證。
+
## 處理通知
點選一列會開啟對應的任務,並定位到通知所指的評論或應用請求。任務開著時這一列保持高亮,再點一次會重新定位到那裡。開啟任務會把通知標為已讀,但這一列仍留在列表裡。沒有對應任務的通知,例如自動化暫停和快速建立結果,會在收件箱頁面中開啟。
diff --git a/apps/docs/content/docs/inbox.zh.mdx b/apps/docs/content/docs/inbox.zh.mdx
index 28c7f40bfe..e1b06a3d75 100644
--- a/apps/docs/content/docs/inbox.zh.mdx
+++ b/apps/docs/content/docs/inbox.zh.mdx
@@ -53,12 +53,24 @@ import { InboxDemo } from "@/components/demos/inbox-demo";
任务页面会把这类订阅标为**仅关键更新**。点开后选**接收全部动态**,会把它变为对这个任务的手动订阅;之后这个任务无法再退回仅关键更新,只能取消订阅。**修改默认设置**会打开**设置 → 通知**,把**你订阅的任务**分组顶部的**别人的任务**改为**全部动态**,所有这类任务都会推送全部动态。
-## 智能体不使用收件箱
+## 智能体与收件箱
-收件箱只面向工作区成员。即使智能体是负责人或订阅者,它也不会读取收件箱通知。
+收件箱通知属于工作区成员。对于 `multica inbox list` 使用的活跃通知列表,只有服务端验证运行的上游触发人就是运行环境所有者时,智能体才能读取该所有者的列表。这个身份会沿智能体调用链继承。由他人触发、没有可验证触发人的运行,以及没有任务绑定的云节点凭证,都不能读取该活跃列表。此保证只覆盖活跃列表;归档、稍后提醒、未读数和写接口沿用现有权限,另案处理。
在评论中 @智能体、把任务分配给智能体或触发自动化,都会直接创建一次运行,不会给智能体留通知。`@all` 也只通知成员。
+## 用 CLI 读取
+
+复用现有 CLI 登录,列出当前通知,不会将通知标为已读:
+
+```sh
+multica inbox list --project <project-id> --type mentioned --output json
+```
+
+`--project` 接受完整 UUID 或唯一 ID 前缀,包括 `multica project list` 显示的短 ID。前缀会先通过项目列表解析,再读取收件箱;无匹配或前缀有歧义时会报错。
+
+两个筛选条件都可省略,在拉取当前收件箱后于本地应用。JSON 包含通知、任务、项目和可选的评论 ID,以及类型、标题、已读状态和创建时间。默认输出为表格。获授权的智能体运行使用任务凭证读取运行环境所有者的通知,不会回退到人的登录凭证。
+
## 处理通知
点击一行会打开对应的任务,并定位到通知所指的评论或应用请求。任务开着时这一行保持高亮,再点一次会重新定位到那里。打开任务会把通知标为已读,但这一行仍留在列表里。没有对应任务的通知,例如自动化暂停和快速创建结果,会在收件箱页面中打开。
diff --git a/server/cmd/multica/cmd_inbox.go b/server/cmd/multica/cmd_inbox.go
new file mode 100644
index 0000000000..ba44967be2
--- /dev/null
+++ b/server/cmd/multica/cmd_inbox.go
@@ -0,0 +1,110 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+
+ "github.com/spf13/cobra"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+)
+
+var inboxCmd = &cobra.Command{
+ Use: "inbox",
+ Short: "Read your inbox notifications",
+}
+
+var inboxListCmd = &cobra.Command{
+ Use: "list",
+ Short: "List your active notifications without changing read status",
+ Long: "List your active notifications without changing read status. Filters apply locally. Agent tasks may read the runtime owner's inbox only when that owner is the task's verified upstream human originator; cloud-node credentials are refused.",
+ Args: exactArgs(0),
+ RunE: runInboxList,
+}
+
+func init() {
+ inboxCmd.AddCommand(inboxListCmd)
+ registerInboxListFlags(inboxListCmd)
+}
+
+func registerInboxListFlags(cmd *cobra.Command) {
+ cmd.Flags().String("project", "", "Filter by issue project ID or unique ID prefix")
+ cmd.Flags().String("type", "", "Filter by notification type (e.g. mentioned)")
+ cmd.Flags().String("output", "table", "Output format: table or json")
+}
+
+type inboxListItem struct {
+ ID string `json:"id"`
+ Type string `json:"type"`
+ Title string `json:"title"`
+ IssueID *string `json:"issue_id"`
+ CommentID *string `json:"comment_id,omitempty"`
+ IssueProjectID *string `json:"issue_project_id"`
+ Read bool `json:"read"`
+ CreatedAt string `json:"created_at"`
+}
+
+func runInboxList(cmd *cobra.Command, _ []string) error {
+ output, _ := cmd.Flags().GetString("output")
+ if output != "json" && output != "table" {
+ return fmt.Errorf("output must be table or json")
+ }
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(cmd.Context())
+ defer cancel()
+
+ projectID := ""
+ if v, _ := cmd.Flags().GetString("project"); v != "" {
+ project, err := resolveProjectID(ctx, client, v)
+ if err != nil {
+ return err
+ }
+ projectID = project.ID
+ }
+
+ var response []struct {
+ inboxListItem
+ Details json.RawMessage `json:"details"`
+ }
+ if err := client.GetJSON(ctx, "/api/inbox", &response); err != nil {
+ return fmt.Errorf("list inbox: %w", err)
+ }
+ notifType, _ := cmd.Flags().GetString("type")
+ items := make([]inboxListItem, 0, len(response))
+ for _, row := range response {
+ if projectID != "" && (row.IssueProjectID == nil || !strings.EqualFold(*row.IssueProjectID, projectID)) {
+ continue
+ }
+ if notifType != "" && row.Type != notifType {
+ continue
+ }
+ var details struct {
+ CommentID *string `json:"comment_id"`
+ }
+ if json.Unmarshal(row.Details, &details) == nil {
+ row.CommentID = details.CommentID
+ }
+ items = append(items, row.inboxListItem)
+ }
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, items)
+ }
+ rows := make([][]string, 0, len(items))
+ value := func(s *string) string {
+ if s == nil {
+ return ""
+ }
+ return *s
+ }
+ for _, item := range items {
+ rows = append(rows, []string{item.ID, item.Type, strings.Join(strings.Fields(item.Title), " "), value(item.IssueID), value(item.CommentID), value(item.IssueProjectID), strconv.FormatBool(item.Read), item.CreatedAt})
+ }
+ cli.PrintTable(os.Stdout, []string{"ID", "TYPE", "TITLE", "ISSUE", "COMMENT", "PROJECT", "READ", "CREATED"}, rows)
+ return nil
+}
diff --git a/server/cmd/multica/cmd_inbox_test.go b/server/cmd/multica/cmd_inbox_test.go
new file mode 100644
index 0000000000..e0d838ba21
--- /dev/null
+++ b/server/cmd/multica/cmd_inbox_test.go
@@ -0,0 +1,228 @@
+package main
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/spf13/cobra"
+)
+
+func runInboxListTest(t *testing.T, flags map[string]string) (string, error) {
+ t.Helper()
+ cmd := &cobra.Command{Use: "list"}
+ registerInboxListFlags(cmd)
+ for name, value := range flags {
+ if err := cmd.Flags().Set(name, value); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return captureStdout(t, func() error { return runInboxList(cmd, nil) })
+}
+
+func TestInboxListFiltersAndCommentAnchors(t *testing.T) {
+ requests := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ if r.Method != http.MethodGet || r.URL.RequestURI() != "/api/inbox" {
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL)
+ }
+ if r.Header.Get("X-Workspace-ID") != "ws-1" || r.Header.Get("Authorization") != "Bearer mat_inbox-test" {
+ t.Error("lost workspace or task credential")
+ }
+ _, _ = w.Write([]byte(`[
+ {"id":"n1","type":"mentioned","title":"Need input","issue_id":"i1","issue_project_id":"aaaaaaaa-1111-1111-1111-111111111111","read":false,"created_at":"2026-11-16T08:00:00Z","details":{"comment_id":"c1","original_prompt":"not a list field"}},
+ {"id":"n2","type":"mentioned","title":"Another project","issue_project_id":"bbbbbbbb-2222-2222-2222-222222222222","read":true},
+ {"id":"n3","type":"new_comment","issue_project_id":"aaaaaaaa-1111-1111-1111-111111111111","details":{}},
+ {"id":"n4","type":"system","issue_project_id":null,"details":null}
+ ]`))
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "mat_inbox-test")
+ t.Setenv("MULTICA_AGENT_ID", "agent-1")
+ t.Setenv("MULTICA_TASK_ID", "task-1")
+
+ for _, tc := range []struct {
+ name string
+ flags map[string]string
+ ids string
+ }{
+ {"all", map[string]string{}, "n1,n2,n3,n4"},
+ {"project", map[string]string{"project": "aaaaaaaa-1111-1111-1111-111111111111"}, "n1,n3"},
+ {"type", map[string]string{"type": "mentioned"}, "n1,n2"},
+ {"intersection", map[string]string{"project": "aaaaaaaa-1111-1111-1111-111111111111", "type": "mentioned"}, "n1"},
+ {"empty", map[string]string{"project": "cccccccc-3333-3333-3333-333333333333"}, ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tc.flags["output"] = "json"
+ out, err := runInboxListTest(t, tc.flags)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.TrimSpace(out) == "null" {
+ t.Fatal("empty list must be []")
+ }
+ var rows []map[string]any
+ if err := json.Unmarshal([]byte(out), &rows); err != nil {
+ t.Fatal(err)
+ }
+ ids := make([]string, 0, len(rows))
+ for _, row := range rows {
+ ids = append(ids, row["id"].(string))
+ if _, ok := row["details"]; ok {
+ t.Fatal("raw details leaked into list output")
+ }
+ if row["id"] == "n1" && (row["comment_id"] != "c1" || row["issue_id"] != "i1" || row["read"] != false || row["created_at"] != "2026-11-16T08:00:00Z") {
+ t.Fatalf("lost notification fields: %v", row)
+ }
+ if row["id"] != "n1" {
+ if _, ok := row["comment_id"]; ok {
+ t.Fatalf("invented comment anchor: %v", row)
+ }
+ }
+ }
+ if strings.Join(ids, ",") != tc.ids {
+ t.Fatalf("ids = %v, want %s", ids, tc.ids)
+ }
+ })
+ }
+ if requests != 5 {
+ t.Fatalf("requests = %d, want one GET per invocation", requests)
+ }
+}
+
+func TestInboxListTableAndDeniedRequest(t *testing.T) {
+ status := http.StatusOK
+ requests := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ if r.Method != http.MethodGet || r.URL.Path != "/api/inbox" {
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL)
+ }
+ w.WriteHeader(status)
+ if status == http.StatusForbidden {
+ _, _ = w.Write([]byte(`{"error":"inbox access denied"}`))
+ return
+ }
+ _, _ = w.Write([]byte(`[{"id":"n1","type":"mentioned","title":"Need input","issue_id":"i1","issue_project_id":"p1","read":true,"details":{"comment_id":"c1"}}]`))
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "mat_inbox-test")
+ out, err := runInboxListTest(t, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, value := range []string{"ID", "TYPE", "TITLE", "ISSUE", "COMMENT", "PROJECT", "READ", "CREATED", "n1", "c1", "true"} {
+ if !strings.Contains(out, value) {
+ t.Errorf("table missing %q: %s", value, out)
+ }
+ }
+ status = http.StatusForbidden
+ out, err = runInboxListTest(t, map[string]string{"output": "json"})
+ if err == nil || out != "" {
+ t.Fatalf("denied request: output=%q error=%v", out, err)
+ }
+ if requests != 2 {
+ t.Fatalf("denial retried or fell back to another credential: %d requests", requests)
+ }
+ _, err = runInboxListTest(t, map[string]string{"output": "yaml"})
+ if err == nil || requests != 2 {
+ t.Fatalf("invalid output made request or succeeded: %v", err)
+ }
+}
+
+func TestInboxListRegistered(t *testing.T) {
+ cmd, _, err := rootCmd.Find([]string{"inbox", "list"})
+ if err != nil || cmd.Name() != "list" || cmd.Parent().Name() != "inbox" {
+ t.Fatalf("inbox list not registered: %v", err)
+ }
+ if cmd.Flags().Lookup("user") != nil {
+ t.Fatal("inbox must not select another recipient")
+ }
+}
+
+func TestInboxListResolvesProjectID(t *testing.T) {
+ const projectA = "aaaaaaaa-1111-1111-1111-111111111111"
+ const projectB = "bbbbbbbb-2222-2222-2222-222222222222"
+ const collision = "aaaaaaaa-3333-3333-3333-333333333333"
+ for _, tc := range []struct {
+ name, input, wantID, wantError string
+ projectRequests, inboxRequests int
+ }{
+ {"full UUID", projectB, "n2", "", 0, 1},
+ {"uppercase full UUID", strings.ToUpper(projectB), "n2", "", 0, 1},
+ {"unique short ID", "bbbbbbbb", "n2", "", 1, 1},
+ {"longer prefix disambiguates", "aaaaaaaa-1111", "n1", "", 1, 1},
+ {"no match", "deadbeef", "", `no project found matching id prefix "deadbeef"`, 1, 0},
+ {"ambiguous prefix", "aaaaaaaa", "", `ambiguous project id prefix "aaaaaaaa"`, 1, 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ projectRequests, inboxRequests := 0, 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet || r.Header.Get("X-Workspace-ID") != "ws-1" ||
+ r.Header.Get("Authorization") != "Bearer mat_inbox-test" {
+ t.Errorf("unexpected method or execution credentials: %s %s", r.Method, r.URL)
+ }
+ switch r.URL.Path {
+ case "/api/projects":
+ projectRequests++
+ if r.URL.Query().Get("workspace_id") != "ws-1" || r.URL.Query().Get("include_archived") != "true" {
+ t.Errorf("project resolution lost existing catalog scope: %s", r.URL)
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"projects": []any{
+ map[string]any{"id": projectA, "title": "A"},
+ map[string]any{"id": projectB, "title": "B"},
+ map[string]any{"id": collision, "title": "No notifications, but still ambiguous"},
+ }})
+ case "/api/inbox":
+ inboxRequests++
+ _ = json.NewEncoder(w).Encode([]map[string]any{
+ {"id": "n1", "type": "mentioned", "issue_project_id": projectA},
+ {"id": "n2", "type": "mentioned", "issue_project_id": projectB},
+ {"id": "n3", "type": "new_comment", "issue_project_id": projectB},
+ })
+ default:
+ t.Errorf("unexpected path: %s", r.URL)
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "mat_inbox-test")
+ t.Setenv("MULTICA_AGENT_ID", "agent-1")
+ t.Setenv("MULTICA_TASK_ID", "task-1")
+ out, err := runInboxListTest(t, map[string]string{"project": tc.input, "type": "mentioned", "output": "json"})
+ if tc.wantError != "" {
+ if err == nil || !strings.Contains(err.Error(), tc.wantError) || out != "" {
+ t.Fatalf("output=%q error=%v, want %s without list output", out, err, tc.wantError)
+ }
+ if tc.name == "ambiguous prefix" && (!strings.Contains(err.Error(), projectA) || !strings.Contains(err.Error(), collision)) {
+ t.Fatalf("ambiguity error omitted matching project IDs: %v", err)
+ }
+ } else {
+ if err != nil {
+ t.Fatal(err)
+ }
+ var rows []struct {
+ ID string `json:"id"`
+ }
+ if err := json.Unmarshal([]byte(out), &rows); err != nil {
+ t.Fatal(err)
+ }
+ if len(rows) != 1 || rows[0].ID != tc.wantID {
+ t.Fatalf("filtered output=%s, want %s", out, tc.wantID)
+ }
+ }
+ if projectRequests != tc.projectRequests || inboxRequests != tc.inboxRequests {
+ t.Fatalf("project/inbox requests=%d/%d, want %d/%d", projectRequests, inboxRequests, tc.projectRequests, tc.inboxRequests)
+ }
+ })
+ }
+}
diff --git a/server/cmd/multica/main.go b/server/cmd/multica/main.go
index bd81a9fd04..6befee21aa 100644
--- a/server/cmd/multica/main.go
+++ b/server/cmd/multica/main.go
@@ -49,6 +49,7 @@ func init() {
// Core commands
issueCmd.GroupID = groupCore
+ inboxCmd.GroupID = groupCore
issueStatusCatalogCmd.GroupID = groupCore
projectCmd.GroupID = groupCore
workflowCmd.GroupID = groupCore
@@ -78,6 +79,7 @@ func init() {
versionCmd.GroupID = groupAdditional
rootCmd.AddCommand(issueCmd)
+ rootCmd.AddCommand(inboxCmd)
rootCmd.AddCommand(issueStatusCatalogCmd)
rootCmd.AddCommand(projectCmd)
rootCmd.AddCommand(workflowCmd)
diff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.go
index 98d2e30357..c725749615 100644
--- a/server/internal/handler/inbox.go
+++ b/server/internal/handler/inbox.go
@@ -3,12 +3,15 @@ package handler
import (
"context"
"encoding/json"
+ "errors"
"log/slog"
"net/http"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/logger"
+ "github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -205,6 +208,10 @@ func (h *Handler) ListInbox(w http.ResponseWriter, r *http.Request) {
return
}
+ if !h.requireInboxListAccess(w, r, userID, wsUUID) {
+ return
+ }
+
// Notifications about private-project issues are not written for
// outsiders (CreateInboxItem); this read filter also drops older rows once
// the reader loses access.
@@ -231,6 +238,55 @@ func (h *Handler) ListInbox(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
+// Task tokens identify the runtime owner, not necessarily the human who asked
+// the agent to act. Personal notifications require that same human upstream.
+// Auth strips client identity headers and stamps the task/agent from the token.
+func (h *Handler) requireInboxListAccess(w http.ResponseWriter, r *http.Request, userID string, workspaceID pgtype.UUID) bool {
+ source := r.Header.Get("X-Actor-Source")
+ if source == "" {
+ return true
+ }
+ deny := func() bool {
+ writeError(w, http.StatusForbidden, "inbox access requires the runtime owner's verified human trigger")
+ return false
+ }
+ queryFailure := func(err error) bool {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return deny()
+ }
+ slog.Warn("resolve inbox access failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to resolve inbox access")
+ return false
+ }
+ // A cloud-node PAT has no authenticated task binding or human trigger.
+ if source != "task_token" {
+ return deny()
+ }
+ taskID, err := util.ParseUUID(r.Header.Get("X-Task-ID"))
+ if err != nil {
+ return deny()
+ }
+ task, err := h.Queries.GetAgentTask(r.Context(), taskID)
+ if err != nil {
+ return queryFailure(err)
+ }
+ if isTerminalTaskStatus(task.Status) ||
+ !task.OriginatorUserID.Valid || uuidToString(task.OriginatorUserID) != userID ||
+ uuidToString(task.AgentID) != r.Header.Get("X-Agent-ID") {
+ return deny()
+ }
+ runtime, err := h.Queries.GetAgentRuntimeForWorkspace(r.Context(), db.GetAgentRuntimeForWorkspaceParams{
+ ID: task.RuntimeID, WorkspaceID: workspaceID,
+ })
+ if err != nil {
+ return queryFailure(err)
+ }
+ if !runtime.OwnerID.Valid || uuidToString(runtime.OwnerID) != userID {
+ return deny()
+ }
+ return true
+}
+
// ListArchivedInbox returns the recipient's archived notifications, backing the
// inbox's "Archived" sub-view. Kept as its own endpoint rather than a flag on
// ListInbox so installed clients keep their current contract, and so the
diff --git a/server/internal/handler/inbox_access_test.go b/server/internal/handler/inbox_access_test.go
new file mode 100644
index 0000000000..c75ec21944
--- /dev/null
+++ b/server/internal/handler/inbox_access_test.go
@@ -0,0 +1,301 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/golang-jwt/jwt/v5"
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/multica-ai/multica/server/internal/auth"
+ "github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func inboxTaskCredential(t *testing.T, taskID, agentID, workspaceID, userID string) string {
+ t.Helper()
+ token := "mat_" + uuid.NewString()
+ dbfx.Insert(t, "task_token", testutil.Cols{
+ "token_hash": auth.HashToken(token), "task_id": taskID, "agent_id": agentID,
+ "workspace_id": workspaceID, "user_id": userID, "expires_at": time.Now().Add(time.Hour),
+ })
+ return token
+}
+
+type inboxAccessFailureDB struct {
+ db.DBTX
+ query string
+ err error
+ failures, inboxReads int
+}
+
+func (d *inboxAccessFailureDB) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
+ if strings.HasPrefix(sql, "-- name: "+d.query+" :one\n") {
+ d.failures++
+ return &mockRow{err: d.err}
+ }
+ return d.DBTX.QueryRow(ctx, sql, args...)
+}
+
+func (d *inboxAccessFailureDB) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
+ if strings.HasPrefix(sql, "-- name: ListInboxItems :many\n") {
+ d.inboxReads++
+ }
+ return d.DBTX.Query(ctx, sql, args...)
+}
+
+func TestListInboxAccessLookupErrors(t *testing.T) {
+ runtimeID := dbfx.Runtime(t, "Inbox lookup runtime")
+ agentID := dbfx.Agent(t, "Inbox lookup agent", runtimeID)
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID, "status": "running",
+ "originator_user_id": testUserID, "accountable_user_id": testUserID,
+ })
+ token := inboxTaskCredential(t, taskID, agentID, testWorkspaceID, testUserID)
+ const privateDetails = "private-inbox-database-host-and-query"
+ for _, query := range []string{"GetAgentTask", "GetAgentRuntimeForWorkspace"} {
+ for _, tc := range []struct {
+ name string
+ err error
+ status int
+ }{
+ {"missing", pgx.ErrNoRows, http.StatusForbidden},
+ {"wrapped missing", fmt.Errorf("%s: %w", privateDetails, pgx.ErrNoRows), http.StatusForbidden},
+ {"deadline", fmt.Errorf("%s: %w", privateDetails, context.DeadlineExceeded), http.StatusInternalServerError},
+ {"statement timeout", &pgconn.PgError{Code: "57014", Message: privateDetails}, http.StatusInternalServerError},
+ {"connection failure", errors.New(privateDetails), http.StatusInternalServerError},
+ } {
+ t.Run(query+"/"+tc.name, func(t *testing.T) {
+ faults := &inboxAccessFailureDB{DBTX: testPool, query: query, err: tc.err}
+ h := *testHandler
+ h.Queries = db.New(faults)
+ handler := middleware.Auth(testHandler.Queries, nil, nil, nil)(
+ middleware.RequireWorkspaceMember(testHandler.Queries)(http.HandlerFunc(h.ListInbox)),
+ ).ServeHTTP
+ body := testutil.Call(t, handler, inboxCredentialRequest(token, testWorkspaceID)).Want(tc.status).Map()
+ if faults.failures != 1 || faults.inboxReads != 0 {
+ t.Fatalf("lookup failures=%d inbox reads=%d; want one failure and no Inbox read", faults.failures, faults.inboxReads)
+ }
+ publicError, ok := body["error"].(string)
+ if len(body) != 1 || !ok || publicError == "" || strings.Contains(fmt.Sprint(body), privateDetails) {
+ t.Fatalf("response must contain only a protected public error: %v", body)
+ }
+ if tc.status == http.StatusInternalServerError && body["error"] != "failed to resolve inbox access" {
+ t.Fatalf("service failure reported as an authorization error: %v", body)
+ }
+ })
+ }
+ }
+}
+
+func inboxAccessHandler(cloud *auth.CloudPATVerifier) http.HandlerFunc {
+ return middleware.Auth(testHandler.Queries, nil, cloud, nil)(
+ middleware.RequireWorkspaceMember(testHandler.Queries)(http.HandlerFunc(testHandler.ListInbox)),
+ ).ServeHTTP
+}
+
+func inboxCredentialRequest(token, workspaceID string) *http.Request {
+ return testutil.WithHeaders(testutil.JSONRequest(http.MethodGet, "/api/inbox", nil),
+ "Authorization", "Bearer "+token, "X-Workspace-ID", workspaceID)
+}
+
+func TestListInboxTaskCredentialAccess(t *testing.T) {
+ other := createPlainMember(t, "inbox-other-"+uuid.NewString()+"@example.test")
+ foreignWorkspace := dbfx.Workspace(t, "Foreign inbox", "inbox-foreign-"+uuid.NewString())
+ dbfx.Member(t, foreignWorkspace, testUserID, "owner")
+ for _, tc := range []struct {
+ name string
+ originator any
+ status string
+ change string
+ want int
+ }{
+ {"self-triggered", testUserID, "running", "", http.StatusOK},
+ {"another human", other, "running", "", http.StatusForbidden},
+ {"unattributed despite accountable owner", nil, "running", "", http.StatusForbidden},
+ {"completed task with lingering token", testUserID, "completed", "", http.StatusForbidden},
+ {"failed task with lingering token", testUserID, "failed", "", http.StatusForbidden},
+ {"cancelled task with lingering token", testUserID, "cancelled", "", http.StatusForbidden},
+ {"runtime ownership changed", testUserID, "running", "owner", http.StatusForbidden},
+ {"missing runtime owner", testUserID, "running", "no-owner", http.StatusForbidden},
+ {"runtime in another workspace", testUserID, "running", "workspace", http.StatusForbidden},
+ {"task agent differs from token", testUserID, "running", "agent", http.StatusForbidden},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ runtimeID := dbfx.Runtime(t, "Inbox runtime")
+ agentID := dbfx.Agent(t, "Inbox agent", runtimeID)
+ accountable := tc.originator
+ if accountable == nil {
+ accountable = testUserID
+ }
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID, "originator_user_id": tc.originator,
+ "accountable_user_id": accountable, "status": tc.status,
+ })
+ switch tc.change {
+ case "owner":
+ dbfx.Exec(t, `UPDATE agent_runtime SET owner_id=$2 WHERE id=$1`, runtimeID, other)
+ case "no-owner":
+ dbfx.Exec(t, `UPDATE agent_runtime SET owner_id=NULL WHERE id=$1`, runtimeID)
+ case "workspace":
+ dbfx.Exec(t, `UPDATE agent_runtime SET workspace_id=$2 WHERE id=$1`, runtimeID, foreignWorkspace)
+ case "agent":
+ agentID = dbfx.Agent(t, "Token agent", runtimeID)
+ }
+ token := inboxTaskCredential(t, taskID, agentID, testWorkspaceID, testUserID)
+ testutil.Call(t, inboxAccessHandler(nil), inboxCredentialRequest(token, testWorkspaceID)).Want(tc.want)
+ })
+ }
+}
+
+func TestListInboxRejectsForgedTaskIdentityAndWorkspace(t *testing.T) {
+ other := createPlainMember(t, "inbox-forger-"+uuid.NewString()+"@example.test")
+ runtimeID := dbfx.Runtime(t, "Inbox runtime")
+ agentID := dbfx.Agent(t, "Inbox agent", runtimeID)
+ allowedTask := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "running", "originator_user_id": testUserID, "accountable_user_id": testUserID})
+ deniedTask := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "running", "originator_user_id": other, "accountable_user_id": other})
+ token := inboxTaskCredential(t, deniedTask, agentID, testWorkspaceID, testUserID)
+ req := inboxCredentialRequest(token, testWorkspaceID)
+ req = testutil.WithHeaders(req, "X-Task-ID", allowedTask, "X-Agent-ID", agentID,
+ "X-Actor-Source", "member", "X-User-ID", other, "X-Originator-User-ID", testUserID)
+ req.URL.RawQuery = "originator_user_id=" + testUserID + "&recipient_id=" + other
+ testutil.Call(t, inboxAccessHandler(nil), req).Want(http.StatusForbidden)
+
+ foreignWorkspace := dbfx.Workspace(t, "Foreign inbox", "inbox-forged-ws-"+uuid.NewString())
+ dbfx.Member(t, foreignWorkspace, testUserID, "owner")
+ allowedToken := inboxTaskCredential(t, allowedTask, agentID, testWorkspaceID, testUserID)
+ testutil.Call(t, inboxAccessHandler(nil), inboxCredentialRequest(allowedToken, foreignWorkspace)).Want(http.StatusForbidden)
+}
+
+func TestListInboxCloudPATCannotBorrowTaskIdentity(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"valid": true, "owner_id": testUserID})
+ }))
+ defer srv.Close()
+ verifier := auth.NewCloudPATVerifier(auth.CloudPATVerifierConfig{FleetBaseURL: srv.URL})
+ runtimeID := dbfx.Runtime(t, "Cloud inbox runtime")
+ agentID := dbfx.Agent(t, "Cloud inbox agent", runtimeID)
+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "running", "originator_user_id": testUserID, "accountable_user_id": testUserID})
+ req := testutil.WithHeaders(inboxCredentialRequest("mcn_inbox-test", testWorkspaceID),
+ "X-Actor-Source", "task_token", "X-Task-ID", taskID, "X-Agent-ID", agentID)
+ testutil.Call(t, inboxAccessHandler(verifier), req).Want(http.StatusForbidden)
+}
+
+func TestListInboxHumanCredentialsAndReadOnlyIsolation(t *testing.T) {
+ other := createPlainMember(t, "inbox-recipient-"+uuid.NewString()+"@example.test")
+ foreignWorkspace := dbfx.Workspace(t, "Foreign inbox", "inbox-isolation-"+uuid.NewString())
+ dbfx.Member(t, foreignWorkspace, testUserID, "owner")
+ newItem := func(workspaceID, recipientID string) string {
+ return dbfx.Insert(t, "inbox_item", testutil.Cols{"workspace_id": workspaceID,
+ "recipient_type": "member", "recipient_id": recipientID, "type": "system", "severity": "info", "title": "Private personal notice"})
+ }
+ own := newItem(testWorkspaceID, testUserID)
+ otherItem := newItem(testWorkspaceID, other)
+ foreign := newItem(foreignWorkspace, testUserID)
+ pat := "mul_" + uuid.NewString()
+ dbfx.Insert(t, "personal_access_token", testutil.Cols{"user_id": testUserID, "name": "Inbox test", "token_hash": auth.HashToken(pat), "token_prefix": pat[:12]})
+ jwtToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{"sub": testUserID, "exp": time.Now().Add(time.Hour).Unix()}).SignedString(auth.JWTSecret())
+ if err != nil {
+ t.Fatal(err)
+ }
+ runtimeID := dbfx.Runtime(t, "Own inbox runtime")
+ agentID := dbfx.Agent(t, "Own inbox agent", runtimeID)
+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "running", "originator_user_id": testUserID, "accountable_user_id": testUserID})
+ taskToken := inboxTaskCredential(t, taskID, agentID, testWorkspaceID, testUserID)
+ for _, tc := range []struct {
+ name, token string
+ cookie bool
+ }{
+ {"personal PAT", pat, false}, {"login session", jwtToken, true}, {"self-triggered task", taskToken, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ req := inboxCredentialRequest(tc.token, testWorkspaceID)
+ if tc.cookie {
+ req.Header.Del("Authorization")
+ req.AddCookie(&http.Cookie{Name: auth.AuthCookieName, Value: tc.token})
+ }
+ req.Header.Set("X-User-ID", other)
+ req.URL.RawQuery = "recipient_id=" + other
+ var items []InboxItemResponse
+ testutil.Call(t, inboxAccessHandler(nil), req).Want(http.StatusOK).JSON(&items)
+ found := false
+ for _, item := range items {
+ if item.ID == otherItem || item.ID == foreign {
+ t.Fatalf("another recipient or workspace leaked: %s", item.ID)
+ }
+ if item.ID == own {
+ found = true
+ if item.Read || item.Archived {
+ t.Fatal("read changed notification state")
+ }
+ }
+ }
+ if !found {
+ t.Fatal("own personal notification missing")
+ }
+ if state := loadInboxItemState(t, own); state != (inboxItemState{}) {
+ t.Fatalf("GET mutated state: %+v", state)
+ }
+ })
+ }
+}
+
+func TestListInboxDelegatedOriginatorAndProjectVisibility(t *testing.T) {
+ var counterBefore int64
+ dbfx.QueryRow(t, `SELECT GREATEST(issue_counter,
+ (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id=$1))
+ FROM workspace WHERE id=$1`, testWorkspaceID).Scan(&counterBefore)
+ worker := seedAllowListedAgent(t, "Inbox delegated worker", testUserID, "public_to", testUserID)
+ chain := newCrossIssueChain(t, testUserID, testUserID)
+ agentComments(t, chain.CoordinatorID, chain.TaskA, chain.IssueY, mention(worker), "").Want(http.StatusCreated)
+ taskID, originator, ok := queuedTaskFor(t, chain.IssueY, worker)
+ if !ok || uuidToString(originator) != testUserID {
+ t.Fatal("delegation did not preserve the upstream human")
+ }
+ runTo(t, taskID)
+ // Delegation normally has a runtime selected when claimed.
+ dbfx.Exec(t, `UPDATE agent_task_queue SET runtime_id=$2 WHERE id=$1`, taskID, testRuntimeID)
+ token := inboxTaskCredential(t, taskID, worker, testWorkspaceID, testUserID)
+ // Allocate delegation issue numbers before introducing the fixture's random high numbers.
+ f := newPrivateProjectFixture(t)
+ secret := insertSecretInboxItem(t, f, testUserID)
+ list := func() map[string]bool {
+ var items []InboxItemResponse
+ testutil.Call(t, inboxAccessHandler(nil), inboxCredentialRequest(token, testWorkspaceID)).Want(http.StatusOK).JSON(&items)
+ ids := map[string]bool{}
+ for _, item := range items {
+ ids[item.ID] = true
+ }
+ return ids
+ }
+ if !list()[secret] {
+ t.Fatal("delegated own run cannot see permitted private notification")
+ }
+ removeProjectMemberRow(t, f.projectID, testUserID)
+ if list()[secret] {
+ t.Fatal("private notification survived membership revocation")
+ }
+ if state := loadInboxItemState(t, secret); state != (inboxItemState{}) {
+ t.Fatalf("GET mutated hidden notification: %+v", state)
+ }
+ // Loss of an upstream human must never borrow the accountable owner.
+ dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id=NULL,accountable_user_id=$2 WHERE id=$1`, taskID, testUserID)
+ testutil.Call(t, inboxAccessHandler(nil), inboxCredentialRequest(token, testWorkspaceID)).Want(http.StatusForbidden)
+
+ var counterAfter int64
+ dbfx.QueryRow(t, `SELECT issue_counter FROM workspace WHERE id=$1`, testWorkspaceID).Scan(&counterAfter)
+ if counterAfter != counterBefore+2 {
+ t.Fatalf("issue counter advanced from %d to %d; want %d for the two delegation issues without entering the private fixture's random range",
+ counterBefore, counterAfter, counterBefore+2)
+ }
+ t.Logf("delegation issue counter: %d -> %d", counterBefore, counterAfter)
+}