Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9549: feat(cli): manage the inbox from the CLI with owner-gated writes (#10861)
Jiayuan Zhang63cebc194804
diff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdxindex 7d138fbe61..e54d8e26cc 100644--- a/apps/docs/content/docs/cli.fr.mdx+++ b/apps/docs/content/docs/cli.fr.mdx@@ -404,7 +404,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 |+| `inbox` | Lire et gérer vos notifications : lister, marquer comme lues, archiver, reporter || `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 |@@ -535,7 +535,14 @@ Les tableaux ci-dessous couvrent toutes les commandes de premier niveau actuelle| | `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` || | `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` | [Lire vos notifications actives](/inbox) sans les marquer comme lues | `--project`, `--type`, `--output` (`table` ou `json`) ; filtres locaux |+| `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` |+| | `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`) |+| | `unarchive <id>...` | Restaurer des notifications archivées | |+| | `snooze <id>...` | Retirer la tâche de chaque notification de la boîte de réception jusqu'à une date | `--until` (RFC 3339, `30m`, `3h`, `1d`, `1w`, `tomorrow`) |+| | `unsnooze <id>...` | Faire revenir maintenant des tâches reportées | |### Runtimediff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex 500088cbc4..406fd60a31 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -404,7 +404,7 @@ multica autopilot trigger-update <autopilot-id> <trigger-id> --clear-event-filte| --- | --- || `issue` | タスクの作成、更新、割り当て、検索。コメント、購読者、ラベル、プロパティ、ウェイクアップ、タイムライン、実行履歴の管理 || `project` | プロジェクトとそのリソースを管理 |-| `inbox` | 既読状態を変えずに自分の通知を読み取る |+| `inbox` | 自分の通知を読み取り、管理する:一覧、既読、アーカイブ、スヌーズ || `label`、`property` | ワークスペースのラベルとカスタムプロパティを管理 || `view` | 保存したビューを読み取り、ビューに表示されるタスクを一覧 || `agent`、`skill`、`squad` | エージェント、スキル、スクワッドを管理 |@@ -527,7 +527,14 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで| | `activity <issue-id> <outcome>` | リーダーの評価を記録 | || `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) | `--project`、`--type`、`--output`(`table` または `json`);フィルターはローカルで適用 |+| `inbox` | `list` | 既読にせずに[通知を一覧表示](/inbox)。`--archived` または `--snoozed` ではそれらを一覧表示 | `--unread`、`--issue`、`--since`、`--project`、`--type`、`--output`(`table` または `json`);`--archived` は全ページを読む |+| | `count` | このワークスペースと所属する各ワークスペースの未読件数 | `--output` |+| | `read [<id>...]` | 通知を既読にする(各通知のタスク全体に適用)。または 1 つのタスクのすべての通知、またはすべて | `--issue`、`--all`(`--yes` が必要) |+| | `unread <id>...` | 通知を未読に戻す | |+| | `archive [<id>...]` | 通知をアーカイブする(各通知のタスク全体に適用)。または一括で | `--all`、`--read`、`--completed`(いずれも `--yes` が必要) |+| | `unarchive <id>...` | アーカイブした通知を復元する | |+| | `snooze <id>...` | 通知のタスクを指定時刻までインボックスから外す | `--until`(RFC 3339、`30m`、`3h`、`1d`、`1w`、`tomorrow`) |+| | `unsnooze <id>...` | スヌーズ中のタスクをすぐに戻す | |### Runtimediff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex b97946bcce..f968eb0bf9 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -404,7 +404,7 @@ multica autopilot trigger-update <autopilot-id> <trigger-id> --clear-event-filte| --- | --- || `issue` | 태스크 생성, 업데이트, 할당, 검색. 댓글, 구독, 라벨, 속성, 깨우기, 타임라인, 실행 기록 관리 || `project` | 프로젝트와 프로젝트 리소스 관리 |-| `inbox` | 읽음 상태를 바꾸지 않고 내 알림 읽기 |+| `inbox` | 내 알림 읽기와 관리: 목록, 읽음 표시, 보관, 다시 알림 || `label`, `property` | 워크스페이스 라벨과 사용자 지정 속성 관리 || `view` | 저장된 뷰를 읽고 뷰에 보이는 태스크 나열 || `agent`, `skill`, `squad` | 에이전트, 스킬, 스쿼드 관리 |@@ -527,7 +527,14 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t| | `activity <issue-id> <outcome>` | 리더 평가 기록 | || `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) | `--project`, `--type`, `--output` (`table` 또는 `json`); 필터는 로컬에서 적용 |+| `inbox` | `list` | 읽음으로 표시하지 않고 [알림 목록 보기](/inbox). `--archived` 또는 `--snoozed`는 해당 목록을 보여 줌 | `--unread`, `--issue`, `--since`, `--project`, `--type`, `--output` (`table` 또는 `json`); `--archived`는 모든 페이지를 읽음 |+| | `count` | 이 워크스페이스와 소속된 각 워크스페이스의 읽지 않은 알림 수 | `--output` |+| | `read [<id>...]` | 알림을 읽음으로 표시(각 알림의 태스크 전체에 적용). 또는 한 태스크의 모든 알림, 또는 전체 | `--issue`, `--all` (`--yes` 필요) |+| | `unread <id>...` | 알림을 읽지 않음으로 표시 | |+| | `archive [<id>...]` | 알림 보관(각 알림의 태스크 전체에 적용). 또는 일괄 보관 | `--all`, `--read`, `--completed` (모두 `--yes` 필요) |+| | `unarchive <id>...` | 보관한 알림 복원 | |+| | `snooze <id>...` | 알림의 태스크를 지정한 시간까지 인박스에서 빼기 | `--until` (RFC 3339, `30m`, `3h`, `1d`, `1w`, `tomorrow`) |+| | `unsnooze <id>...` | 다시 알림 중인 태스크를 지금 되돌리기 | |### Runtimediff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex 796e799200..aff7d6e0a5 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -419,7 +419,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 |+| `inbox` | Read and manage your notifications: list, mark read, archive, snooze || `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 |@@ -562,7 +562,14 @@ Migration from CSV parsing: replace `--attachment a,b` with `--attachment a --at| | `activity <issue-id> <outcome>` | Record a leader evaluation | || `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` | [Read your active notifications](/inbox) without marking them read | `--project`, `--type`, `--output` (`table` or `json`); filters apply locally |+| `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` |+| | `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`) |+| | `unarchive <id>...` | Restore archived notifications | |+| | `snooze <id>...` | Take each notification's issue out of the inbox until a time | `--until` (RFC 3339, `30m`, `3h`, `1d`, `1w`, `tomorrow`) |+| | `unsnooze <id>...` | Bring snoozed issues back now | |### Runtimediff --git a/apps/docs/content/docs/cli.zh-Hant.mdx b/apps/docs/content/docs/cli.zh-Hant.mdxindex dba919dfbd..6763c6fa9c 100644--- a/apps/docs/content/docs/cli.zh-Hant.mdx+++ b/apps/docs/content/docs/cli.zh-Hant.mdx@@ -401,7 +401,7 @@ multica autopilot trigger-update <autopilot-id> <trigger-id> --clear-event-filte| --- | --- || `issue` | 建立、更新、分配和搜尋任務;管理評論、訂閱、標籤、屬性、喚醒、時間線與執行記錄 || `project` | 管理專案、專案資源和專案使用的工作流 |-| `inbox` | 讀取自己的通知,不改變已讀狀態 |+| `inbox` | 讀取和管理自己的通知:列出、標為已讀、封存、稍後提醒 || `workflow` | 管理工作流:狀態以及每個狀態交給誰處理 || `issue-status` | 管理工作區狀態目錄:狀態及其顏色和圖示 || `label`、`property` | 管理工作區標籤和自定義屬性 |@@ -536,7 +536,14 @@ CLI 配置檔案包含可代表你訪問 Multica 的令牌。不要提交到倉| | `activity <issue-id> <outcome>` | 記錄隊長評價 | || `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),不標為已讀 | `--project`、`--type`、`--output`(`table` 或 `json`);篩選在本機套用 |+| `inbox` | `list` | [列出通知](/inbox),不標為已讀;`--archived` 或 `--snoozed` 改為列出封存或稍後提醒的內容 | `--unread`、`--issue`、`--since`、`--project`、`--type`、`--output`(`table` 或 `json`);`--archived` 讀取全部分頁 |+| | `count` | 目前工作區及你所在各工作區的未讀數 | `--output` |+| | `read [<id>...]` | 將通知標為已讀(作用於所在任務的全部通知);或一個任務上的全部通知,或全部 | `--issue`、`--all`(需要 `--yes`) |+| | `unread <id>...` | 將通知標為未讀 | |+| | `archive [<id>...]` | 封存通知(作用於所在任務的全部通知);或批次封存 | `--all`、`--read`、`--completed`(皆需 `--yes`) |+| | `unarchive <id>...` | 還原已封存的通知 | |+| | `snooze <id>...` | 讓通知所在任務暫時離開收件箱,直到指定時間 | `--until`(RFC 3339、`30m`、`3h`、`1d`、`1w`、`tomorrow`) |+| | `unsnooze <id>...` | 讓稍後提醒的任務立即回到收件箱 | |### Runtimediff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex 21470582ed..3e7e2cbc43 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -404,7 +404,7 @@ multica autopilot trigger-update <autopilot-id> <trigger-id> --clear-event-filte| --- | --- || `issue` | 创建、更新、分配和搜索任务;管理评论、订阅、标签、属性、唤醒、时间线与执行记录 || `project` | 管理项目、项目资源和项目使用的工作流 |-| `inbox` | 读取自己的通知,不改变已读状态 |+| `inbox` | 读取和管理自己的通知:列出、标为已读、归档、稍后提醒 || `workflow` | 管理工作流:状态以及每个状态交给谁处理 || `issue-status` | 管理工作区状态目录:状态及其颜色和图标 || `label`、`property` | 管理工作区标签和自定义属性 |@@ -539,7 +539,14 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| | `activity <issue-id> <outcome>` | 记录队长评价 | || `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),不标为已读 | `--project`、`--type`、`--output`(`table` 或 `json`);筛选在本地应用 |+| `inbox` | `list` | [列出通知](/inbox),不标为已读;`--archived` 或 `--snoozed` 改为列出归档或稍后提醒的内容 | `--unread`、`--issue`、`--since`、`--project`、`--type`、`--output`(`table` 或 `json`);`--archived` 读取全部分页 |+| | `count` | 当前工作区及你所在各工作区的未读数 | `--output` |+| | `read [<id>...]` | 将通知标为已读(作用于所在任务的全部通知);或一个任务上的全部通知,或全部 | `--issue`、`--all`(需要 `--yes`) |+| | `unread <id>...` | 将通知标为未读 | |+| | `archive [<id>...]` | 归档通知(作用于所在任务的全部通知);或批量归档 | `--all`、`--read`、`--completed`(均需 `--yes`) |+| | `unarchive <id>...` | 恢复已归档的通知 | |+| | `snooze <id>...` | 让通知所在任务暂时离开收件箱,直到指定时间 | `--until`(RFC 3339、`30m`、`3h`、`1d`、`1w`、`tomorrow`) |+| | `unsnooze <id>...` | 让稍后提醒的任务立即回到收件箱 | |### Runtimediff --git a/apps/docs/content/docs/inbox.fr.mdx b/apps/docs/content/docs/inbox.fr.mdxindex e1722e5931..9aed285ba8 100644--- a/apps/docs/content/docs/inbox.fr.mdx+++ b/apps/docs/content/docs/inbox.fr.mdx@@ -56,21 +56,37 @@ 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. Pour la liste des notifications actives utilisée par `multica inbox list` et pour les notifications archivées, 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 les lire. Cette garantie couvre uniquement la liste active et les archives ; la liste reportée, les compteurs de non-lus et les interfaces d'écriture conservent leurs permissions actuelles en attendant un traitement séparé.+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.@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+## Gérer depuis le CLI-Utilisez votre connexion CLI existante pour lister les notifications actives sans les marquer comme lues :+Utilisez votre connexion CLI existante pour lire et traiter vos notifications. Lister ne marque rien comme lu :```sh-multica inbox list --project <project-id> --type mentioned --output json+multica inbox count+multica inbox list --unread --since 1d --output json+multica inbox list --issue MUL-123+multica inbox list --archived # ou --snoozed```-`--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.+Chaque ligne indique l'ID de la notification, la clé de la tâche, le type, son auteur, le titre et un court résumé du commentaire ou du changement. `--unread`, `--issue` (une clé de tâche ou un UUID), `--since` (une date RFC 3339 ou une durée comme `2h`, `1d`, `1w`), `--project` et `--type` filtrent la liste. `--archived` lit toute l'archive page par page : une tâche archivée il y a longtemps reste trouvable et restaurable. `--project` accepte un UUID complet ou un préfixe d'ID unique, y compris l'ID court affiché par `multica project list` ; un préfixe sans correspondance ou ambigu produit une erreur. Le tableau garde aussi les ID de tâche, de commentaire et de projet, et abrège le résumé ; `--output json` donne le résumé complet.-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.+Traitez les notifications avec les ID affichés par la liste :++```sh+multica inbox read <id>... # unread <id>... annule+multica inbox read --issue MUL-123 # toutes les notifications d'une tâche+multica inbox archive <id>... # unarchive <id>... restaure+multica inbox snooze <id>... --until tomorrow # RFC 3339, 30m, 3h, 1d, 1w ; unsnooze <id>... y met fin+```++Comme dans l'application, marquer comme lue, archiver ou reporter une notification de tâche s'applique à toute la tâche, tandis que marquer une notification comme non lue ne change qu'elle. L'échec d'un ID n'arrête pas les autres ; la commande indique lesquels ont échoué et se termine avec un code non nul.++Les actions groupées correspondent au menu de la boîte de réception : `multica inbox read --all`, et `multica inbox archive` avec `--all`, `--read` (tâches dont la notification la plus récente est lue) ou `--completed` (tâches dans un statut `done` ou `closed`). Elles exigent `--yes`, ou une confirmation saisie lors d'une exécution manuelle, et laissent de côté les tâches reportées, sauf `--completed` : comme dans l'application, il archive aussi une tâche terminée ou fermée même reportée, ce qui met fin au report. Chaque modification affiche le nombre de notifications réellement modifiées, tâches entières comprises ; une notification déjà dans cet état compte pour 0. `--output json` renvoie ce même nombre, avec le résultat de chaque ID. Le CLI ne permet pas de supprimer des notifications.++Une exécution d'agent autorisée utilise son identifiant d'exécution pour tout cela, sans revenir à la connexion d'une personne.## Traiter les notificationsdiff --git a/apps/docs/content/docs/inbox.ja.mdx b/apps/docs/content/docs/inbox.ja.mdxindex 8037f878c7..5e089a19ca 100644--- a/apps/docs/content/docs/inbox.ja.mdx+++ b/apps/docs/content/docs/inbox.ja.mdx@@ -56,21 +56,37 @@ import { InboxDemo } from "@/components/demos/inbox-demo";## エージェントとインボックス-インボックスの通知はワークスペースメンバーに属します。`multica inbox list` が使うアクティブな通知一覧とアーカイブ済みの通知では、実行を開始した上流のユーザーがランタイム所有者本人であるとサーバーが確認できた場合だけ、エージェントがその所有者の通知を読み取れます。このユーザー情報はエージェントの委任チェーンで引き継がれます。他の人が開始した実行、開始した人を確認できない実行、タスクとの紐付けがないクラウドノードの認証情報では、これらを読み取れません。この保証はアクティブ一覧とアーカイブのみが対象です。スヌーズ中の一覧、未読件数、書き込み API は従来の権限を維持し、別途対応します。+インボックスの通知はワークスペースメンバーに属します。実行を開始した上流のユーザーがランタイム所有者本人であるとサーバーが確認できた場合だけ、エージェントはその所有者の通知を読み取り、処理できます。このユーザー情報はエージェントの委任チェーンで引き継がれます。この規則はインボックスのすべての操作に適用されます。アクティブ一覧、アーカイブ、スヌーズ中の一覧、未読件数、そしてすべての変更です。他の人が開始した実行、開始した人を確認できない実行、タスクとの紐付けがないクラウドノードの認証情報は拒否されます。通知を削除できるのは人だけです。エージェントによる変更は、どのエージェントがどの実行で誰の代わりに行ったかとともにサーバーに記録されます。コメントでの @メンション、タスクの割り当て、オートパイロットのトリガーは、直接実行を作成し、エージェントに通知は残しません。`@all` もメンバーにのみ通知します。-## CLI から読み取る+## CLI から管理する-既存の CLI ログインを使い、通知を既読にせずに現在の通知を一覧表示できます。+既存の CLI ログインで通知を読み取り、処理できます。一覧表示で既読になることはありません。```sh-multica inbox list --project <project-id> --type mentioned --output json+multica inbox count+multica inbox list --unread --since 1d --output json+multica inbox list --issue MUL-123+multica inbox list --archived # または --snoozed```-`--project` は完全な UUID または一意の ID プレフィックスを受け付けます。`multica project list` に表示される短い ID も使えます。プレフィックスはインボックスの読み取り前にプロジェクト一覧から解決され、一致なしや曖昧な場合はエラーになります。+各行には通知 ID、タスクキー、種類、送信元、タイトル、コメントや変更の短い要約が表示されます。`--unread`、`--issue`(タスクキーまたは UUID)、`--since`(RFC 3339 の時刻、または `2h`、`1d`、`1w` のような期間)、`--project`、`--type` で一覧を絞り込めます。`--archived` はアーカイブ全体をページごとに読むので、ずっと前にアーカイブしたタスクも見つけて復元できます。`--project` は完全な UUID または一意の ID プレフィックスを受け付け、`multica project list` に表示される短い ID も使えます。一致なしや曖昧な場合はエラーになります。表にはタスク、コメント、プロジェクトの ID も残り、要約は短く切られます。`--output json` には要約の全文が含まれます。-両方のフィルターは省略可能で、現在のインボックスの取得後にローカルで適用されます。JSON には通知、タスク、プロジェクト、および存在する場合はコメントの ID と、種類、タイトル、既読状態、作成日時が含まれます。既定の出力は表です。許可されたエージェント実行はタスクの認証情報でランタイム所有者の通知を読み取り、ユーザーのログイン情報にはフォールバックしません。+一覧に表示される ID で通知を処理します。++```sh+multica inbox read <id>... # unread <id>... で元に戻す+multica inbox read --issue MUL-123 # 1 つのタスクのすべての通知+multica inbox archive <id>... # unarchive <id>... で復元+multica inbox snooze <id>... --until tomorrow # RFC 3339、30m、3h、1d、1w。unsnooze <id>... で終了+```++アプリと同様に、タスクの通知を既読、アーカイブ、スヌーズにするとタスク全体に適用され、未読に戻すとその通知だけが変わります。1 つの ID が失敗しても残りは処理され、失敗した ID を報告してゼロ以外の終了コードで終わります。++一括操作はインボックスのメニューと同じです。`multica inbox read --all` と、`--all`、`--read`(最新の通知が既読のタスク)、`--completed`(`done` または `closed` カテゴリのステータスのタスク)を付けた `multica inbox archive` です。`--yes` が必要で、手動で実行する場合は確認を入力することもできます。スヌーズ中のタスクは対象外ですが、`--completed` は例外です。アプリと同じく、完了またはクローズ済みのタスクはスヌーズ中でもアーカイブし、スヌーズを終了します。どの変更も、タスク全体を含めて実際に変更した通知の件数を出力します。すでにその状態だったものは 0 件です。`--output json` では同じ件数と ID ごとの結果を返します。CLI から通知は削除できません。++許可されたエージェント実行はこれらすべてにタスクの認証情報を使い、ユーザーのログイン情報にはフォールバックしません。## 通知の処理diff --git a/apps/docs/content/docs/inbox.ko.mdx b/apps/docs/content/docs/inbox.ko.mdxindex 04d6fae42e..39942c5063 100644--- a/apps/docs/content/docs/inbox.ko.mdx+++ b/apps/docs/content/docs/inbox.ko.mdx@@ -56,21 +56,37 @@ import { InboxDemo } from "@/components/demos/inbox-demo";## 에이전트와 인박스-인박스 알림은 워크스페이스 멤버의 데이터입니다. `multica inbox list`가 사용하는 활성 알림 목록과 보관된 알림에서는 서버가 실행을 시작한 상위 사용자가 런타임 소유자 본인임을 확인한 경우에만 에이전트가 해당 소유자의 알림을 읽을 수 있습니다. 이 사용자 정보는 에이전트 위임 체인을 따라 상속됩니다. 다른 사람이 시작한 실행, 시작한 사람을 확인할 수 없는 실행, 태스크에 연결되지 않은 클라우드 노드 자격 증명으로는 이를 읽을 수 없습니다. 이 보장은 활성 목록과 보관함에만 적용됩니다. 다시 알림 목록, 읽지 않은 알림 수, 쓰기 API의 권한은 현재 상태를 유지하며 별도로 처리합니다.+인박스 알림은 워크스페이스 멤버의 데이터입니다. 서버가 실행을 시작한 상위 사용자가 런타임 소유자 본인임을 확인한 경우에만 에이전트가 해당 소유자의 알림을 읽고 처리할 수 있습니다. 이 사용자 정보는 에이전트 위임 체인을 따라 상속됩니다. 이 규칙은 활성 목록, 보관함, 다시 알림 목록, 읽지 않은 알림 수, 모든 변경 등 인박스의 모든 작업에 적용됩니다. 다른 사람이 시작한 실행, 시작한 사람을 확인할 수 없는 실행, 태스크에 연결되지 않은 클라우드 노드 자격 증명은 거부됩니다. 알림은 사람만 삭제할 수 있습니다. 에이전트가 변경할 때마다 서버는 어떤 에이전트가 어떤 실행에서 누구를 대신해 변경했는지 기록합니다.댓글에서 에이전트를 @멘션하거나 태스크를 에이전트에게 할당하거나 자동화를 트리거하면 실행이 직접 생성되며, 에이전트에게 알림을 남기지 않습니다. `@all`도 멤버에게만 알립니다.-## CLI에서 읽기+## CLI에서 관리하기-기존 CLI 로그인으로 현재 알림을 읽음으로 표시하지 않고 조회할 수 있습니다.+기존 CLI 로그인으로 알림을 읽고 처리할 수 있습니다. 목록 조회는 알림을 읽음으로 표시하지 않습니다.```sh-multica inbox list --project <project-id> --type mentioned --output json+multica inbox count+multica inbox list --unread --since 1d --output json+multica inbox list --issue MUL-123+multica inbox list --archived # 또는 --snoozed```-`--project`는 전체 UUID 또는 고유한 ID 접두사를 받으며 `multica project list`에 표시되는 짧은 ID도 사용할 수 있습니다. 인박스를 읽기 전에 프로젝트 목록에서 접두사를 확인하고, 일치하는 프로젝트가 없거나 여러 개이면 오류를 반환합니다.+각 행에는 알림 ID, 태스크 키, 유형, 보낸 사람, 제목, 댓글이나 변경 사항의 짧은 요약이 표시됩니다. `--unread`, `--issue`(태스크 키 또는 UUID), `--since`(RFC 3339 시간 또는 `2h`, `1d`, `1w` 같은 기간), `--project`, `--type`으로 목록을 거를 수 있습니다. `--archived`는 보관함 전체를 페이지별로 읽으므로 오래전에 보관한 태스크도 찾아서 복원할 수 있습니다. `--project`는 전체 UUID 또는 고유한 ID 접두사를 받으며 `multica project list`에 표시되는 짧은 ID도 사용할 수 있고, 일치하는 프로젝트가 없거나 여러 개이면 오류를 반환합니다. 표에는 태스크, 댓글, 프로젝트 ID도 남고 요약은 짧게 잘립니다. `--output json`에는 요약 전체가 들어갑니다.-두 필터는 모두 선택 사항이며 현재 인박스를 가져온 후 로컬에서 적용됩니다. JSON에는 알림, 태스크, 프로젝트 및 가능한 경우 댓글 ID와 유형, 제목, 읽음 상태, 생성 시간이 포함됩니다. 기본 출력은 표입니다. 허용된 에이전트 실행은 태스크 자격 증명으로 런타임 소유자의 알림을 읽으며 사람의 로그인 정보로 대체하지 않습니다.+목록에 표시된 ID로 알림을 처리합니다.++```sh+multica inbox read <id>... # unread <id>...로 되돌리기+multica inbox read --issue MUL-123 # 한 태스크의 모든 알림+multica inbox archive <id>... # unarchive <id>...로 복원+multica inbox snooze <id>... --until tomorrow # RFC 3339, 30m, 3h, 1d, 1w; unsnooze <id>...로 종료+```++앱과 마찬가지로 태스크 알림을 읽음, 보관, 다시 알림으로 처리하면 태스크 전체에 적용되고, 읽지 않음으로 표시하면 그 알림만 바뀝니다. 한 ID가 실패해도 나머지는 계속 처리되며, 실패한 ID를 알려 주고 0이 아닌 코드로 종료합니다.++일괄 작업은 인박스 메뉴와 같습니다. `multica inbox read --all`, 그리고 `--all`, `--read`(최신 알림을 읽은 태스크), `--completed`(`done` 또는 `closed` 카테고리 상태의 태스크)를 붙인 `multica inbox archive`입니다. `--yes`가 필요하며 직접 실행할 때는 확인을 입력할 수도 있습니다. 다시 알림 중인 태스크는 건드리지 않지만 `--completed`는 예외입니다. 앱과 마찬가지로 완료되거나 닫힌 태스크는 다시 알림 중이어도 보관하고 다시 알림을 끝냅니다. 모든 변경은 태스크 전체를 포함해 실제로 바뀐 알림 수를 출력하며, 이미 그 상태였던 알림은 0으로 셉니다. `--output json`은 같은 개수와 ID별 결과를 반환합니다. CLI에서는 알림을 삭제할 수 없습니다.++허용된 에이전트 실행은 이 모든 작업에 태스크 자격 증명을 사용하며 사람의 로그인 정보로 대체하지 않습니다.## 알림 처리diff --git a/apps/docs/content/docs/inbox.mdx b/apps/docs/content/docs/inbox.mdxindex 48235f3921..c4da76b650 100644--- a/apps/docs/content/docs/inbox.mdx+++ b/apps/docs/content/docs/inbox.mdx@@ -56,21 +56,37 @@ The issue page marks such a subscription **Key updates only**. Its menu offers *## Agents and the inbox-Inbox notifications belong to workspace members. For the active notification list used by `multica inbox list` and for archived notifications, 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 them. This guarantee covers only the active and archived lists; the snoozed list, unread counts and write endpoints retain their current permissions pending separate work.+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.@-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+## Manage from the CLI-Use your existing CLI login to list your active notifications without marking them read:+Use your existing CLI login to read and handle your notifications. Listing never marks anything read:```sh-multica inbox list --project <project-id> --type mentioned --output json+multica inbox count+multica inbox list --unread --since 1d --output json+multica inbox list --issue MUL-123+multica inbox list --archived # or --snoozed```-`--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.+Each row shows the notification ID, the issue key, the type, who it is from, the title and a short summary of the comment or change. `--unread`, `--issue` (an issue key or UUID), `--since` (an RFC 3339 time or a duration such as `2h`, `1d`, `1w`), `--project` and `--type` filter the list. `--archived` reads the whole archive page by page, so an issue archived long ago can still be found and restored. `--project` accepts a full UUID or a unique ID prefix, including the short ID from `multica project list`; no match or an ambiguous prefix produces an error. The table also keeps the issue, comment and project IDs and cuts the summary short; `--output json` has the full summary.-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 by the IDs the list shows:++```sh+multica inbox read <id>... # unread <id>... reverses it+multica inbox read --issue MUL-123 # every notification on one issue+multica inbox archive <id>... # unarchive <id>... restores+multica inbox snooze <id>... --until tomorrow # RFC 3339, 30m, 3h, 1d, 1w; unsnooze <id>... ends it+```++As in the app, reading, archiving or snoozing a notification on an issue applies to the whole issue, while marking one unread changes only that notification. A failure on one ID doesn't stop the others; the command reports which failed and exits non-zero.++The bulk actions match the inbox menu: `multica inbox read --all`, and `multica inbox archive` with `--all`, `--read` (issues whose newest notification is read) or `--completed` (issues in a `done` or `closed` status). They need `--yes`, or a typed confirmation when run by hand, and leave snoozed issues alone, except `--completed`: as in the app, it also archives a done or closed issue while it's snoozed, ending the snooze. Every change reports how many notifications it actually changed, whole issues included; one already in that state counts 0. `--output json` returns the same count, with the result for each ID. Notifications can't be deleted from the CLI.++An authorized agent run uses its task credential for all of this; it never falls back to a person's login.## Handle notificationsdiff --git a/apps/docs/content/docs/inbox.zh-Hant.mdx b/apps/docs/content/docs/inbox.zh-Hant.mdxindex 43c6c2c793..c9a7ea2072 100644--- a/apps/docs/content/docs/inbox.zh-Hant.mdx+++ b/apps/docs/content/docs/inbox.zh-Hant.mdx@@ -56,21 +56,37 @@ import { InboxDemo } from "@/components/demos/inbox-demo";## AI 代理與收件箱-收件箱通知屬於工作區成員。對於 `multica inbox list` 使用的活躍通知列表和封存通知,只有伺服器驗證執行的上游觸發人就是執行環境擁有者時,AI 代理才能讀取該擁有者的列表。這個身分會沿 AI 代理呼叫鏈繼承。由他人觸發、沒有可驗證觸發人的執行,以及沒有任務綁定的雲端節點憑證,都不能讀取。此保證只涵蓋活躍列表和封存;稍後提醒、未讀數和寫入介面沿用現有權限,另案處理。+收件箱通知屬於工作區成員。只有伺服器驗證執行的上游觸發人就是執行環境擁有者時,AI 代理才能讀取和處理該擁有者的通知。這個身分會沿 AI 代理呼叫鏈繼承。這條規則涵蓋收件箱的所有操作:活躍列表、封存、稍後提醒列表、未讀數,以及所有修改。由他人觸發、沒有可驗證觸發人的執行,以及沒有任務綁定的雲端節點憑證,都會被拒絕。只有人可以刪除通知。AI 代理做的每次修改都會在伺服器留下紀錄,寫明是哪個 AI 代理、哪次執行、代哪個人操作。在評論中 @ AI 代理、把任務分配給 AI 代理或觸發自動化,都會直接建立一次執行,不會給 AI 代理留通知。`@all` 也只通知成員。-## 用 CLI 讀取+## 用 CLI 管理-沿用現有 CLI 登入,列出目前通知,不會將通知標為已讀:+沿用現有 CLI 登入讀取和處理通知。列出通知不會將其標為已讀:```sh-multica inbox list --project <project-id> --type mentioned --output json+multica inbox count+multica inbox list --unread --since 1d --output json+multica inbox list --issue MUL-123+multica inbox list --archived # 或 --snoozed```-`--project` 接受完整 UUID 或唯一 ID 前綴,包括 `multica project list` 顯示的短 ID。前綴會先透過專案列表解析,再讀取收件箱;沒有符合項目或前綴有歧義時會顯示錯誤。+每列顯示通知 ID、任務編號、類型、來自誰、標題,以及評論或變更的簡短摘要。`--unread`、`--issue`(任務編號或 UUID)、`--since`(RFC 3339 時間,或 `2h`、`1d`、`1w` 這樣的時長)、`--project` 和 `--type` 用於篩選列表。`--archived` 會逐頁讀取整個封存,早已封存的任務也能找到並還原。`--project` 接受完整 UUID 或唯一 ID 前綴,包括 `multica project list` 顯示的短 ID;沒有符合項目或前綴有歧義時會顯示錯誤。表格還保留任務、評論和專案 ID,摘要會截短;`--output json` 帶完整摘要。-兩個篩選條件都可省略,在取得目前收件箱後於本機套用。JSON 包含通知、任務、專案和可選的評論 ID,以及類型、標題、已讀狀態和建立時間。預設輸出為表格。獲授權的 AI 代理執行使用任務憑證讀取執行環境擁有者的通知,不會退回使用人的登入憑證。+用列表裡的 ID 處理通知:++```sh+multica inbox read <id>... # unread <id>... 復原+multica inbox read --issue MUL-123 # 一個任務上的全部通知+multica inbox archive <id>... # unarchive <id>... 還原+multica inbox snooze <id>... --until tomorrow # RFC 3339、30m、3h、1d、1w;unsnooze <id>... 結束+```++與應用程式裡一樣,標為已讀、封存或稍後提醒一則任務通知,會作用於整個任務;標為未讀只改變這一則。某個 ID 失敗不會中斷其餘 ID,指令會列出失敗的項目並以非零狀態結束。++批次操作與收件箱選單一致:`multica inbox read --all`,以及帶 `--all`、`--read`(最新通知已讀的任務)或 `--completed`(處於 `done` 或 `closed` 類狀態的任務)的 `multica inbox archive`。它們需要 `--yes`,手動執行時也可以輸入確認;除 `--completed` 外,稍後提醒中的任務不受影響:與應用程式一致,`--completed` 也會封存稍後提醒中已完成或已關閉的任務,並結束稍後提醒。每次修改都會輸出實際改動的通知則數,包括整個任務上的通知;原本就是該狀態的記為 0。`--output json` 回傳同一計數,以及每個 ID 的結果。CLI 不能刪除通知。++獲授權的 AI 代理執行在這些操作中都使用任務憑證,不會退回使用人的登入憑證。## 處理通知diff --git a/apps/docs/content/docs/inbox.zh.mdx b/apps/docs/content/docs/inbox.zh.mdxindex fa81e08da0..5d4d2084e7 100644--- a/apps/docs/content/docs/inbox.zh.mdx+++ b/apps/docs/content/docs/inbox.zh.mdx@@ -56,21 +56,37 @@ import { InboxDemo } from "@/components/demos/inbox-demo";## 智能体与收件箱-收件箱通知属于工作区成员。对于 `multica inbox list` 使用的活跃通知列表和归档通知,只有服务端验证运行的上游触发人就是运行环境所有者时,智能体才能读取该所有者的列表。这个身份会沿智能体调用链继承。由他人触发、没有可验证触发人的运行,以及没有任务绑定的云节点凭证,都不能读取。此保证只覆盖活跃列表和归档;稍后提醒、未读数和写接口沿用现有权限,另案处理。+收件箱通知属于工作区成员。只有服务端验证运行的上游触发人就是运行环境所有者时,智能体才能读取和处理该所有者的通知。这个身份会沿智能体调用链继承。这条规则覆盖收件箱的所有操作:活跃列表、归档、稍后提醒列表、未读数,以及所有修改。由他人触发、没有可验证触发人的运行,以及没有任务绑定的云节点凭证,都会被拒绝。只有人可以删除通知。智能体做的每次修改都会在服务端留下记录,写明是哪个智能体、哪次运行、代哪个人操作。在评论中 @智能体、把任务分配给智能体或触发自动化,都会直接创建一次运行,不会给智能体留通知。`@all` 也只通知成员。-## 用 CLI 读取+## 用 CLI 管理-复用现有 CLI 登录,列出当前通知,不会将通知标为已读:+复用现有 CLI 登录读取和处理通知。列出通知不会将其标为已读:```sh-multica inbox list --project <project-id> --type mentioned --output json+multica inbox count+multica inbox list --unread --since 1d --output json+multica inbox list --issue MUL-123+multica inbox list --archived # 或 --snoozed```-`--project` 接受完整 UUID 或唯一 ID 前缀,包括 `multica project list` 显示的短 ID。前缀会先通过项目列表解析,再读取收件箱;无匹配或前缀有歧义时会报错。+每行显示通知 ID、任务编号、类型、来自谁、标题,以及评论或变更的简短摘要。`--unread`、`--issue`(任务编号或 UUID)、`--since`(RFC 3339 时间,或 `2h`、`1d`、`1w` 这样的时长)、`--project` 和 `--type` 用于筛选列表。`--archived` 会逐页读取整个归档,早已归档的任务也能找到并恢复。`--project` 接受完整 UUID 或唯一 ID 前缀,包括 `multica project list` 显示的短 ID;无匹配或前缀有歧义时会报错。表格还保留任务、评论和项目 ID,摘要会截短;`--output json` 带完整摘要。-两个筛选条件都可省略,在拉取当前收件箱后于本地应用。JSON 包含通知、任务、项目和可选的评论 ID,以及类型、标题、已读状态和创建时间。默认输出为表格。获授权的智能体运行使用任务凭证读取运行环境所有者的通知,不会回退到人的登录凭证。+用列表里的 ID 处理通知:++```sh+multica inbox read <id>... # unread <id>... 撤销+multica inbox read --issue MUL-123 # 一个任务上的全部通知+multica inbox archive <id>... # unarchive <id>... 恢复+multica inbox snooze <id>... --until tomorrow # RFC 3339、30m、3h、1d、1w;unsnooze <id>... 结束+```++与应用里一样,标为已读、归档或稍后提醒一条任务通知,会作用于整个任务;标为未读只改变这一条。某个 ID 失败不会中断其余 ID,命令会列出失败的条目并以非零状态退出。++批量操作与收件箱菜单一致:`multica inbox read --all`,以及带 `--all`、`--read`(最新通知已读的任务)或 `--completed`(处于 `done` 或 `closed` 类状态的任务)的 `multica inbox archive`。它们需要 `--yes`,手动运行时也可以输入确认;除 `--completed` 外,稍后提醒中的任务不受影响:与应用一致,`--completed` 也会归档稍后提醒中已完成或已关闭的任务,并结束稍后提醒。每次修改都会输出实际改动的通知条数,包括整个任务上的通知;本来就是该状态的记为 0。`--output json` 返回同一计数,以及每个 ID 的结果。CLI 不能删除通知。++获授权的智能体运行在这些操作中都使用任务凭证,不会回退到人的登录凭证。## 处理通知diff --git a/server/cmd/multica/cmd_inbox.go b/server/cmd/multica/cmd_inbox.goindex ba44967be2..cbbfd5dc33 100644--- a/server/cmd/multica/cmd_inbox.go+++ b/server/cmd/multica/cmd_inbox.go@@ -1,57 +1,208 @@package mainimport (+ "bufio"+ "context""encoding/json""fmt"+ "net/url""os"+ "regexp""strconv""strings"+ "time"+ "unicode/utf8""github.com/spf13/cobra""github.com/multica-ai/multica/server/internal/cli")+const inboxAccessNote = "Agent tasks may read and change the runtime owner's inbox only when that owner is the task's verified upstream human originator; cloud-node credentials are refused."+var inboxCmd = &cobra.Command{Use: "inbox",- Short: "Read your inbox notifications",+ Short: "Read and manage your inbox notifications",+ Long: "Read and manage your inbox notifications: list them, mark them read or unread, archive, and snooze.\n\n" ++ "Reading or archiving a notification on an issue applies to every notification on that issue, as in the app. " ++ "Notifications cannot be deleted from the CLI.\n\n" + inboxAccessNote,}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.",+ Short: "List your notifications without changing read status",+ Long: "List your active notifications without changing read status. --archived lists archived notifications and --snoozed the issues you snoozed instead.\n\n" ++ "With --archived every page of the archive is read, so --issue finds old issues too. Each row carries its issue key (e.g. MUL-123), who it is from, and a short summary of the comment or change; the table cuts the summary short, JSON has all of it. Issue keys and names are looked up in extra requests and stay empty when that lookup fails.\n\n" ++ inboxAccessNote,+ Args: exactArgs(0),+ RunE: runInboxList,+}++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,Args: exactArgs(0),- RunE: runInboxList,+ RunE: runInboxCount,+}++var inboxReadCmd = &cobra.Command{+ Use: "read [<id>...]",+ Short: "Mark notifications read",+ Long: "Mark notifications read: the given notification ids, every notification on one issue with --issue, or the whole inbox with --all --yes.\n\n" ++ "Reading a notification on an issue reads every unread notification on that issue, as opening it in the app does. Snoozed issues are left unread by --issue and --all.\n\n" ++ inboxAccessNote,+ RunE: runInboxRead,+}++var inboxUnreadCmd = &cobra.Command{+ Use: "unread <id>...",+ Short: "Mark notifications unread",+ Long: "Mark notifications unread, to come back to them later. Only the given notification changes, not the rest of its issue.\n\n" + inboxAccessNote,+ Args: minimumArgs(1),+ RunE: runInboxUnread,+}++var inboxArchiveCmd = &cobra.Command{+ Use: "archive [<id>...]",+ Short: "Archive notifications",+ Long: "Archive notifications: the given notification ids, or in bulk with --all, --read (issues whose newest notification is read) or --completed (issues in a done or closed status). Bulk archiving needs --yes. --all and --read leave snoozed issues alone; --completed also archives snoozed issues that are done or closed, ending the snooze, as in the app.\n\n" ++ "Archiving a notification on an issue archives every notification on that issue. Archiving does not change the issue itself; `multica inbox unarchive` brings notifications back.\n\n" ++ inboxAccessNote,+ RunE: runInboxArchive,+}++var inboxUnarchiveCmd = &cobra.Command{+ Use: "unarchive <id>...",+ Short: "Restore archived notifications",+ Long: "Restore archived notifications to the inbox, with every notification on the same issue, in the read state they were archived in.\n\n" + inboxAccessNote,+ Args: minimumArgs(1),+ RunE: runInboxUnarchive,+}++var inboxSnoozeCmd = &cobra.Command{+ Use: "snooze <id>... --until <time>",+ Short: "Snooze the issues of notifications until a time",+ Long: "Take the issue each notification is on out of the inbox until a time, as Snooze does in the app. Snoozing a snoozed issue changes its time.\n\n" ++ "--until takes an RFC 3339 time, a duration from now (30m, 3h, 1d, 1w), or \"tomorrow\" (9:00 local time). Like the app, a snooze of a day or more made between 22:00 and 6:00 comes back at 9:00. The time must be within a year.\n\n" ++ inboxAccessNote,+ Args: minimumArgs(1),+ RunE: runInboxSnooze,+}++var inboxUnsnoozeCmd = &cobra.Command{+ Use: "unsnooze <id>...",+ Short: "End the snooze on the issues of notifications",+ Long: "Bring the issue each notification is on back into the inbox now, unread.\n\n" + inboxAccessNote,+ Args: minimumArgs(1),+ RunE: runInboxUnsnooze,}func init() {- inboxCmd.AddCommand(inboxListCmd)+ inboxCmd.AddCommand(inboxListCmd, inboxCountCmd, inboxReadCmd, inboxUnreadCmd, inboxArchiveCmd, inboxUnarchiveCmd, inboxSnoozeCmd, inboxUnsnoozeCmd)registerInboxListFlags(inboxListCmd)+ registerInboxReadFlags(inboxReadCmd)+ registerInboxArchiveFlags(inboxArchiveCmd)+ registerInboxSnoozeFlags(inboxSnoozeCmd)+ for _, cmd := range []*cobra.Command{inboxCountCmd, inboxUnreadCmd, inboxUnarchiveCmd, inboxUnsnoozeCmd} {+ registerInboxOutputFlag(cmd)+ }+}++func registerInboxReadFlags(cmd *cobra.Command) {+ cmd.Flags().String("issue", "", "Mark every notification on this issue read (issue key or UUID)")+ cmd.Flags().Bool("all", false, "Mark the whole inbox read (needs --yes)")+ cmd.Flags().BoolP("yes", "y", false, "Confirm a bulk change without a prompt")+ registerInboxOutputFlag(cmd)+}++func registerInboxArchiveFlags(cmd *cobra.Command) {+ cmd.Flags().Bool("all", false, "Archive the whole inbox (needs --yes)")+ cmd.Flags().Bool("read", false, "Archive every issue whose newest notification is read (needs --yes)")+ cmd.Flags().Bool("completed", false, "Archive every issue in a done or closed status (needs --yes)")+ cmd.Flags().BoolP("yes", "y", false, "Confirm a bulk change without a prompt")+ registerInboxOutputFlag(cmd)+}++func registerInboxSnoozeFlags(cmd *cobra.Command) {+ cmd.Flags().String("until", "", "When the issue comes back: RFC 3339 time, 30m, 3h, 1d, 1w, or tomorrow")+ registerInboxOutputFlag(cmd)}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().Bool("unread", false, "Only unread notifications")+ cmd.Flags().String("issue", "", "Only notifications on this issue (issue key or UUID)")+ cmd.Flags().String("since", "", "Only notifications received since a time: RFC 3339, or a duration back from now (2h, 1d, 1w)")+ cmd.Flags().Bool("archived", false, "List archived notifications instead of active ones")+ cmd.Flags().Bool("snoozed", false, "List snoozed issues instead of active notifications")+ registerInboxOutputFlag(cmd)+}++func registerInboxOutputFlag(cmd *cobra.Command) {cmd.Flags().String("output", "table", "Output format: table or json")}+func inboxOutput(cmd *cobra.Command) (string, error) {+ output, _ := cmd.Flags().GetString("output")+ if output != "json" && output != "table" {+ return "", fmt.Errorf("output must be table or json")+ }+ return output, nil+}+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"`+ ID string `json:"id"`+ Type string `json:"type"`+ Title string `json:"title"`+ IssueID *string `json:"issue_id"`+ IssueIdentifier string `json:"issue_identifier,omitempty"`+ CommentID *string `json:"comment_id,omitempty"`+ IssueProjectID *string `json:"issue_project_id"`+ ActorType *string `json:"actor_type,omitempty"`+ ActorID *string `json:"actor_id,omitempty"`+ Actor string `json:"actor,omitempty"`+ Summary string `json:"summary,omitempty"`+ Read bool `json:"read"`+ CreatedAt string `json:"created_at"`+}++type inboxSnoozedItem struct {+ ID string `json:"id"`+ IssueID string `json:"issue_id"`+ IssueIdentifier string `json:"issue_identifier,omitempty"`+ Title string `json:"title,omitempty"`+ SnoozedUntil string `json:"snoozed_until"`+ SnoozedAt string `json:"snoozed_at"`+ Updates int64 `json:"updates"`}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")+ output, err := inboxOutput(cmd)+ if err != nil {+ return err}+ archived, _ := cmd.Flags().GetBool("archived")+ snoozed, _ := cmd.Flags().GetBool("snoozed")+ if archived && snoozed {+ return fmt.Errorf("--archived and --snoozed cannot be combined")+ }+ if snoozed {+ for _, name := range []string{"project", "type", "unread", "since"} {+ if cmd.Flags().Changed(name) {+ return fmt.Errorf("--%s does not apply to --snoozed", name)+ }+ }+ }+ var since time.Time+ if v, _ := cmd.Flags().GetString("since"); v != "" {+ since, err = parseInboxTime(v, time.Now(), true)+ if err != nil {+ return fmt.Errorf("--since: %w", err)+ }+ }+client, err := newAPIClient(cmd)if err != nil {return err@@ -67,15 +218,48 @@ func runInboxList(cmd *cobra.Command, _ []string) error {}projectID = project.ID}+ issueID := ""+ if v, _ := cmd.Flags().GetString("issue"); v != "" {+ issue, err := resolveIssueRef(ctx, client, v)+ if err != nil {+ return err+ }+ issueID = issue.ID+ }- var response []struct {- inboxListItem- Details json.RawMessage `json:"details"`+ if snoozed {+ return listSnoozedInbox(ctx, cmd.Context(), client, issueID, output)+ }++ unreadOnly, _ := cmd.Flags().GetBool("unread")+ notifType, _ := cmd.Flags().GetString("type")+ var response []inboxListRow+ if archived {+ // The archive lists one notification per issue, so the type has to+ // be matched before that one is picked, not after.+ filters := url.Values{}+ if notifType != "" {+ filters.Set("notification_types", notifType)+ }+ if issueID != "" {+ filters.Set("group_id", issueID)+ }+ if projectID != "" {+ filters.Set("projects", projectID)+ }+ if unreadOnly {+ filters.Set("unread_only", "true")+ }+ if !since.IsZero() {+ filters.Set("received_after", since.UTC().Format(time.RFC3339Nano))+ }+ response, err = listArchivedInbox(cmd.Context(), client, filters)+ } else {+ err = client.GetJSON(ctx, "/api/inbox", &response)}- if err := client.GetJSON(ctx, "/api/inbox", &response); err != nil {+ if 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)) {@@ -84,14 +268,49 @@ func runInboxList(cmd *cobra.Command, _ []string) error {if notifType != "" && row.Type != notifType {continue}+ if unreadOnly && row.Read {+ continue+ }+ if issueID != "" && (row.IssueID == nil || !strings.EqualFold(*row.IssueID, issueID)) {+ continue+ }+ if !since.IsZero() {+ created, err := time.Parse(time.RFC3339Nano, row.CreatedAt)+ if err != nil || created.Before(since) {+ continue+ }+ }var details struct {CommentID *string `json:"comment_id"`}if json.Unmarshal(row.Details, &details) == nil {row.CommentID = details.CommentID}+ if row.Body != nil {+ row.Summary = strings.Join(strings.Fields(*row.Body), " ")+ }items = append(items, row.inboxListItem)}++ issueIDs := make([]string, 0, len(items))+ for _, item := range items {+ if item.IssueID != nil {+ issueIDs = append(issueIDs, *item.IssueID)+ }+ }+ issues := lookupInboxIssues(cmd.Context(), client, issueIDs)+ actorCtx, actorCancel := cli.APIContext(cmd.Context())+ defer actorCancel()+ actors := loadActorDisplayLookup(actorCtx, client)+ for i := range items {+ if items[i].IssueID != nil {+ items[i].IssueIdentifier = issues[strings.ToLower(*items[i].IssueID)].Identifier+ }+ if items[i].ActorType != nil && items[i].ActorID != nil {+ items[i].Actor = actors.actor(*items[i].ActorType, *items[i].ActorID)+ }+ }+if output == "json" {return cli.PrintJSON(os.Stdout, items)}@@ -103,8 +322,558 @@ func runInboxList(cmd *cobra.Command, _ []string) error {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})+ rows = append(rows, []string{item.ID, item.Type, oneLine(item.Title, 0), value(item.IssueID), value(item.CommentID), value(item.IssueProjectID), strconv.FormatBool(item.Read), item.CreatedAt,+ item.IssueIdentifier, item.Actor, oneLine(item.Summary, 80)})+ }+ // New columns go after the original ones so their positions stay put.+ cli.PrintTable(os.Stdout, []string{"ID", "TYPE", "TITLE", "ISSUE", "COMMENT", "PROJECT", "READ", "CREATED", "KEY", "FROM", "SUMMARY"}, rows)+ return nil+}++type inboxListRow struct {+ inboxListItem+ Body *string `json:"body"`+ Details json.RawMessage `json:"details"`+}++// listArchivedInbox reads every page of the archive with the given filters,+// each page under its own deadline.+func listArchivedInbox(parent context.Context, client *cli.APIClient, filters url.Values) ([]inboxListRow, error) {+ rows := []inboxListRow{}+ cursor := ""+ for {+ params := url.Values{"limit": {"100"}}+ for key, values := range filters {+ params[key] = values+ }+ if cursor != "" {+ params.Set("cursor", cursor)+ }+ var page struct {+ Items []inboxListRow `json:"items"`+ NextCursor *string `json:"next_cursor"`+ HasMore bool `json:"has_more"`+ }+ ctx, cancel := cli.APIContext(parent)+ err := client.GetJSON(ctx, "/api/inbox/archived/page?"+params.Encode(), &page)+ cancel()+ if err != nil {+ return nil, err+ }+ rows = append(rows, page.Items...)+ if !page.HasMore || page.NextCursor == nil || *page.NextCursor == "" {+ return rows, nil+ }+ cursor = *page.NextCursor+ }+}++func listSnoozedInbox(ctx, parent context.Context, client *cli.APIClient, issueID, output string) error {+ var response []struct {+ inboxSnoozedItem+ // The server calls the notification id item_id here; the CLI calls it+ // id everywhere, so the column feeds straight into unsnooze.+ ItemID string `json:"item_id"`+ }+ if err := client.GetJSON(ctx, "/api/inbox/snoozed", &response); err != nil {+ return fmt.Errorf("list snoozed inbox: %w", err)+ }+ items := make([]inboxSnoozedItem, 0, len(response))+ ids := make([]string, 0, len(response))+ for _, row := range response {+ if issueID != "" && !strings.EqualFold(row.IssueID, issueID) {+ continue+ }+ row.ID = row.ItemID+ items = append(items, row.inboxSnoozedItem)+ ids = append(ids, row.IssueID)+ }+ issues := lookupInboxIssues(parent, client, ids)+ for i := range items {+ issue := issues[strings.ToLower(items[i].IssueID)]+ items[i].IssueIdentifier, items[i].Title = issue.Identifier, issue.Title+ }+ if output == "json" {+ return cli.PrintJSON(os.Stdout, items)+ }+ rows := make([][]string, 0, len(items))+ for _, item := range items {+ issue := item.IssueIdentifier+ if issue == "" {+ issue = item.IssueID+ }+ rows = append(rows, []string{item.ID, issue, oneLine(item.Title, 0), item.SnoozedUntil, strconv.FormatInt(item.Updates, 10)})+ }+ cli.PrintTable(os.Stdout, []string{"ID", "ISSUE", "TITLE", "UNTIL", "UPDATES"}, rows)+ return nil+}++type inboxIssue struct {+ Identifier string+ Title string+}++// lookupInboxIssues fetches the key and title of each issue in one request per+// hundred ids, each under its own deadline. It is best effort: notifications+// still list without their issue key when the lookup fails.+func lookupInboxIssues(parent context.Context, client *cli.APIClient, ids []string) map[string]inboxIssue {+ const chunk = 100+ issues := map[string]inboxIssue{}+ unique := make([]string, 0, len(ids))+ seen := map[string]bool{}+ for _, id := range ids {+ id = strings.ToLower(id)+ if !seen[id] && uuidRegexp.MatchString(id) {+ seen[id] = true+ unique = append(unique, id)+ }+ }+ for start := 0; start < len(unique); start += chunk {+ end := min(start+chunk, len(unique))+ params := url.Values{"ids": {strings.Join(unique[start:end], ",")}, "limit": {strconv.Itoa(chunk)}}+ var resp struct {+ Issues []struct {+ ID string `json:"id"`+ Identifier string `json:"identifier"`+ Title string `json:"title"`+ } `json:"issues"`+ }+ ctx, cancel := cli.APIContext(parent)+ err := client.GetJSON(ctx, "/api/issues?"+params.Encode(), &resp)+ cancel()+ if err != nil {+ fmt.Fprintf(os.Stderr, "warning: could not look up issue keys: %v\n", err)+ return issues+ }+ for _, issue := range resp.Issues {+ issues[strings.ToLower(issue.ID)] = inboxIssue{Identifier: issue.Identifier, Title: issue.Title}+ }+ }+ return issues+}++// oneLine collapses whitespace and, when limit is positive, cuts to limit runes.+func oneLine(s string, limit int) string {+ s = strings.Join(strings.Fields(s), " ")+ if limit <= 0 || utf8.RuneCountInString(s) <= limit {+ return s+ }+ runes := []rune(s)+ return string(runes[:limit-1]) + "…"+}++func runInboxCount(cmd *cobra.Command, _ []string) error {+ output, err := inboxOutput(cmd)+ if err != nil {+ return err+ }+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(cmd.Context())+ defer cancel()++ var count struct {+ Count int64 `json:"count"`+ }+ if err := client.GetJSON(ctx, "/api/inbox/unread-count", &count); err != nil {+ return fmt.Errorf("count unread inbox: %w", err)+ }+ var workspaces []struct {+ WorkspaceID string `json:"workspace_id"`+ Count int64 `json:"count"`+ }+ if err := client.GetJSON(ctx, "/api/inbox/unread-summary", &workspaces); err != nil {+ return fmt.Errorf("summarize unread inbox: %w", err)+ }+ if workspaces == nil {+ workspaces = []struct {+ WorkspaceID string `json:"workspace_id"`+ Count int64 `json:"count"`+ }{}+ }+ if output == "json" {+ return cli.PrintJSON(os.Stdout, map[string]any{+ "workspace_id": client.WorkspaceID,+ "unread": count.Count,+ "workspaces": workspaces,+ })+ }+ fmt.Fprintf(os.Stdout, "Unread in this workspace: %d\n", count.Count)+ if len(workspaces) > 0 {+ rows := make([][]string, 0, len(workspaces))+ for _, ws := range workspaces {+ rows = append(rows, []string{ws.WorkspaceID, strconv.FormatInt(ws.Count, 10)})+ }+ fmt.Fprintln(os.Stdout)+ cli.PrintTable(os.Stdout, []string{"WORKSPACE", "UNREAD"}, rows)}- cli.PrintTable(os.Stdout, []string{"ID", "TYPE", "TITLE", "ISSUE", "COMMENT", "PROJECT", "READ", "CREATED"}, rows)return nil}++// inboxWriteResult is what every write prints. Count is the number of+// notifications the server actually changed, issue groups included; an id+// whose change was already in place counts 0.+type inboxWriteResult struct {+ Action string `json:"action"`+ Count int64 `json:"count"`+ Items []inboxWriteItem `json:"items,omitempty"`+ Failed []inboxWriteFailure `json:"failed,omitempty"`+ IssueID string `json:"issue_id,omitempty"`+ SnoozedUntil string `json:"snoozed_until,omitempty"`+}++type inboxWriteItem struct {+ ID string `json:"id"`+ IssueID *string `json:"issue_id"`+ Count int64 `json:"count"`+}++type inboxWriteFailure struct {+ ID string `json:"id"`+ Error string `json:"error"`+}++// inboxItemCall changes one notification and reports what changed.+type inboxItemCall func(ctx context.Context, client *cli.APIClient, id string) (inboxWriteItem, error)++func inboxItemIDs(args []string) ([]string, error) {+ ids := make([]string, 0, len(args))+ seen := map[string]bool{}+ for _, arg := range args {+ id := strings.ToLower(strings.TrimSpace(arg))+ if !uuidRegexp.MatchString(id) {+ return nil, fmt.Errorf("notification id %q is not a full UUID; copy it from `multica inbox list --output json`", arg)+ }+ if !seen[id] {+ seen[id] = true+ ids = append(ids, id)+ }+ }+ return ids, nil+}++// runInboxItemWrites applies one change to each notification in turn. Every+// id is validated before the first request, and a failure on one id does not+// stop the rest; the command exits non-zero when any failed.+func runInboxItemWrites(cmd *cobra.Command, args []string, result inboxWriteResult, past string, call inboxItemCall) error {+ output, err := inboxOutput(cmd)+ if err != nil {+ return err+ }+ ids, err := inboxItemIDs(args)+ if err != nil {+ return err+ }+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ for _, id := range ids {+ ctx, cancel := cli.APIContext(cmd.Context())+ item, err := call(ctx, client, id)+ cancel()+ if err != nil {+ msg := cli.ServerMessage(err)+ if msg == "" {+ msg = err.Error()+ }+ result.Failed = append(result.Failed, inboxWriteFailure{ID: id, Error: msg})+ continue+ }+ item.ID = id+ result.Items = append(result.Items, item)+ result.Count += item.Count+ }+ if output == "json" {+ if err := cli.PrintJSON(os.Stdout, result); err != nil {+ return err+ }+ } else {+ for _, item := range result.Items {+ fmt.Fprintf(os.Stdout, "%s: %s\n", item.ID, inboxCountText(item.Count))+ }+ for _, failure := range result.Failed {+ fmt.Fprintf(os.Stderr, "Failed %s: %s\n", failure.ID, failure.Error)+ }+ if err := printInboxCount(output, result, past); err != nil {+ return err+ }+ }+ if len(result.Failed) > 0 {+ return fmt.Errorf("%d of %d notifications could not be %s", len(result.Failed), len(ids), past)+ }+ return nil+}++func capitalize(s string) string {+ if s == "" {+ return s+ }+ return strings.ToUpper(s[:1]) + s[1:]+}++// postInboxItem posts to one notification's action endpoint and returns the+// issue and change count the response names.+func postInboxItem(action string, body any) inboxItemCall {+ return func(ctx context.Context, client *cli.APIClient, id string) (inboxWriteItem, error) {+ var resp struct {+ IssueID *string `json:"issue_id"`+ Count *int64 `json:"count"`+ }+ if err := client.PostJSON(ctx, "/api/inbox/"+url.PathEscape(id)+"/"+action, body, &resp); err != nil {+ return inboxWriteItem{}, err+ }+ // Older servers leave count out of read, unread, archive and unarchive;+ // the notification itself is the one change their answer confirms.+ count := int64(1)+ if resp.Count != nil {+ count = *resp.Count+ }+ return inboxWriteItem{IssueID: resp.IssueID, Count: count}, nil+ }+}++func inboxCountText(count int64) string {+ switch count {+ case 0:+ return "no change"+ case 1:+ return "1 notification"+ }+ return fmt.Sprintf("%d notifications", count)+}++// runInboxBatch runs one server-side bulk change after confirmation and+// prints the server's count.+func runInboxBatch(cmd *cobra.Command, action, path, prompt, past string) error {+ output, err := inboxOutput(cmd)+ if err != nil {+ return err+ }+ if confirmed, err := confirmInboxBatch(cmd, prompt); !confirmed {+ return err+ }+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(cmd.Context())+ defer cancel()+ var resp struct {+ Count int64 `json:"count"`+ }+ if err := client.PostJSON(ctx, path, nil, &resp); err != nil {+ return fmt.Errorf("%s: %w", strings.ReplaceAll(action, "_", " "), err)+ }+ return printInboxCount(output, inboxWriteResult{Action: action, Count: resp.Count}, past)+}++func printInboxCount(output string, result inboxWriteResult, past string) error {+ if output == "json" {+ return cli.PrintJSON(os.Stdout, result)+ }+ noun := "notifications"+ if result.Count == 1 {+ noun = "notification"+ }+ fmt.Fprintf(os.Stdout, "%s %d %s\n", capitalize(past), result.Count, noun)+ return nil+}++// confirmInboxBatch guards the bulk changes: --yes, or a "y" typed at the+// prompt. A run that cannot answer the prompt fails without changing anything.+func confirmInboxBatch(cmd *cobra.Command, prompt string) (bool, error) {+ if yes, _ := cmd.Flags().GetBool("yes"); yes {+ return true, nil+ }+ fmt.Fprint(os.Stderr, prompt+" [y/N] ")+ answer, readErr := bufio.NewReader(os.Stdin).ReadString('\n')+ answer = strings.TrimSpace(strings.ToLower(answer))+ if answer == "y" || answer == "yes" {+ return true, nil+ }+ if answer == "" && readErr != nil {+ return false, fmt.Errorf("no confirmation received (stdin is not interactive); re-run with --yes to confirm the bulk change")+ }+ fmt.Fprintln(os.Stderr, "Aborted.")+ return false, nil+}++// inboxMode returns the one mode the flags select, refusing a mix of ids and+// mode flags or of two mode flags.+func inboxMode(cmd *cobra.Command, args []string, flags ...string) (string, error) {+ mode := ""+ if len(args) > 0 {+ mode = "ids"+ }+ for _, name := range flags {+ if !cmd.Flags().Changed(name) {+ continue+ }+ if f := cmd.Flags().Lookup(name); f.Value.Type() == "bool" && f.Value.String() != "true" {+ continue+ }+ if mode != "" {+ return "", fmt.Errorf("pass notification ids or exactly one of --%s", strings.Join(flags, ", --"))+ }+ mode = name+ }+ if mode == "" {+ return "", fmt.Errorf("pass notification ids or one of --%s", strings.Join(flags, ", --"))+ }+ return mode, nil+}++func runInboxRead(cmd *cobra.Command, args []string) error {+ mode, err := inboxMode(cmd, args, "issue", "all")+ if err != nil {+ return err+ }+ switch mode {+ case "all":+ return runInboxBatch(cmd, "mark_all_read", "/api/inbox/mark-all-read", "Mark every notification in your inbox read?", "marked read")+ case "issue":+ output, err := inboxOutput(cmd)+ if err != nil {+ return err+ }+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(cmd.Context())+ defer cancel()+ ref, _ := cmd.Flags().GetString("issue")+ issue, err := resolveIssueRef(ctx, client, ref)+ if err != nil {+ return err+ }+ var resp struct {+ Count int64 `json:"count"`+ }+ if err := client.PostJSON(ctx, "/api/inbox/issues/"+url.PathEscape(issue.ID)+"/read", nil, &resp); err != nil {+ return fmt.Errorf("mark issue %s read: %w", issue.Display, err)+ }+ return printInboxCount(output, inboxWriteResult{Action: "read", Count: resp.Count, IssueID: issue.ID}, "marked read")+ }+ return runInboxItemWrites(cmd, args, inboxWriteResult{Action: "read"}, "marked read", postInboxItem("read", nil))+}++func runInboxUnread(cmd *cobra.Command, args []string) error {+ return runInboxItemWrites(cmd, args, inboxWriteResult{Action: "unread"}, "marked unread", postInboxItem("unread", nil))+}++func runInboxArchive(cmd *cobra.Command, args []string) error {+ mode, err := inboxMode(cmd, args, "all", "read", "completed")+ if err != nil {+ return err+ }+ switch mode {+ case "all":+ return runInboxBatch(cmd, "archive_all", "/api/inbox/archive-all", "Archive every notification in your inbox?", "archived")+ case "read":+ return runInboxBatch(cmd, "archive_read", "/api/inbox/archive-all-read", "Archive every issue in your inbox whose newest notification is read?", "archived")+ case "completed":+ return runInboxBatch(cmd, "archive_completed", "/api/inbox/archive-completed", "Archive every issue in your inbox that is done or closed?", "archived")+ }+ return runInboxItemWrites(cmd, args, inboxWriteResult{Action: "archive"}, "archived", postInboxItem("archive", nil))+}++func runInboxUnarchive(cmd *cobra.Command, args []string) error {+ return runInboxItemWrites(cmd, args, inboxWriteResult{Action: "unarchive"}, "unarchived", postInboxItem("unarchive", nil))+}++func runInboxSnooze(cmd *cobra.Command, args []string) error {+ value, _ := cmd.Flags().GetString("until")+ if value == "" {+ return fmt.Errorf("--until is required")+ }+ until, err := parseInboxTime(value, time.Now(), false)+ if err != nil {+ return fmt.Errorf("--until: %w", err)+ }+ if !until.After(time.Now()) {+ return fmt.Errorf("--until must be in the future")+ }+ formatted := until.UTC().Format(time.RFC3339)+ snooze := postInboxItem("snooze", map[string]string{"until": formatted})+ snoozedIssues := map[string]bool{}+ // Every id on an issue snoozes the whole issue to the same time, so only+ // the first one on each issue changes anything.+ call := func(ctx context.Context, client *cli.APIClient, id string) (inboxWriteItem, error) {+ item, err := snooze(ctx, client, id)+ if err == nil && item.IssueID != nil {+ key := strings.ToLower(*item.IssueID)+ if snoozedIssues[key] {+ item.Count = 0+ }+ snoozedIssues[key] = true+ }+ return item, err+ }+ return runInboxItemWrites(cmd, args, inboxWriteResult{Action: "snooze", SnoozedUntil: formatted}, "snoozed", call)+}++func runInboxUnsnooze(cmd *cobra.Command, args []string) error {+ return runInboxItemWrites(cmd, args, inboxWriteResult{Action: "unsnooze"}, "unsnoozed", postInboxItem("unsnooze", nil))+}++var inboxRelativeTime = regexp.MustCompile(`^(\d+)\s*([mhdw])$`)++// Mirrors the app's snooze presets (packages/core/inbox/snooze.ts): a day or+// more keeps the clock time, except at night, when it lands in the morning.+const (+ inboxMorningHour = 9+ inboxNightStartHour = 22+ inboxNightEndHour = 6+)++// parseInboxTime reads an RFC 3339 time, "tomorrow" (9:00 local), or a+// duration such as 30m, 3h, 1d or 1w. Durations count forward from now, or+// backward when back is set.+func parseInboxTime(value string, now time.Time, back bool) (time.Time, error) {+ value = strings.ToLower(strings.TrimSpace(value))+ if t, err := time.Parse(time.RFC3339, strings.ToUpper(value)); err == nil {+ return t, nil+ }+ if value == "tomorrow" && !back {+ y, m, d := now.AddDate(0, 0, 1).Date()+ return time.Date(y, m, d, inboxMorningHour, 0, 0, 0, now.Location()), nil+ }+ match := inboxRelativeTime.FindStringSubmatch(value)+ if match == nil {+ if d, err := time.ParseDuration(value); err == nil && d > 0 {+ if back {+ return now.Add(-d), nil+ }+ return now.Add(d), nil+ }+ return time.Time{}, fmt.Errorf("%q is not an RFC 3339 time, a duration such as 30m, 3h, 1d or 1w, or tomorrow", value)+ }+ n, err := strconv.Atoi(match[1])+ if err != nil || n <= 0 {+ return time.Time{}, fmt.Errorf("%q must be a positive duration", value)+ }+ sign := 1+ if back {+ sign = -1+ }+ switch match[2] {+ case "m":+ return now.Add(time.Duration(sign*n) * time.Minute), nil+ case "h":+ return now.Add(time.Duration(sign*n) * time.Hour), nil+ }+ days := n+ if match[2] == "w" {+ days = n * 7+ }+ t := now.AddDate(0, 0, sign*days)+ if hour := now.Hour(); !back && (hour >= inboxNightStartHour || hour < inboxNightEndHour) {+ y, m, d := t.Date()+ t = time.Date(y, m, d, inboxMorningHour, 0, 0, 0, now.Location())+ }+ return t, nil+}diff --git a/server/cmd/multica/cmd_inbox_manage_test.go b/server/cmd/multica/cmd_inbox_manage_test.gonew file mode 100644index 0000000000..7a9c91a001--- /dev/null+++ b/server/cmd/multica/cmd_inbox_manage_test.go@@ -0,0 +1,526 @@+package main++import (+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "net/url"+ "os"+ "strconv"+ "strings"+ "testing"+ "time"++ "github.com/spf13/cobra"+)++const (+ inboxItemA = "aaaaaaaa-0000-0000-0000-00000000000a"+ inboxItemB = "bbbbbbbb-0000-0000-0000-00000000000b"+ inboxItemC = "cccccccc-0000-0000-0000-00000000000c"+ inboxIssue1 = "11111111-0000-0000-0000-000000000001"+ inboxIssue2 = "22222222-0000-0000-0000-000000000002"+ inboxMember = "33333333-0000-0000-0000-000000000003"+ inboxAgent = "44444444-0000-0000-0000-000000000004"+ inboxProject = "55555555-0000-0000-0000-000000000005"+)++type inboxRequest struct {+ method, uri, body string+}++// fakeInboxServer answers each "METHOD path" from routes and records every+// request in order.+func fakeInboxServer(t *testing.T, routes map[string]func(w http.ResponseWriter, r *http.Request)) *[]inboxRequest {+ t.Helper()+ requests := &[]inboxRequest{}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body, _ := io.ReadAll(r.Body)+ *requests = append(*requests, inboxRequest{r.Method, r.URL.RequestURI(), string(body)})+ if r.Header.Get("Authorization") != "Bearer mat_inbox-test" || r.Header.Get("X-Workspace-ID") != "ws-1" {+ t.Errorf("lost workspace or task credential on %s %s", r.Method, r.URL)+ }+ if handler, ok := routes[r.Method+" "+r.URL.Path]; ok {+ handler(w, r)+ return+ }+ t.Errorf("unexpected request: %s %s", r.Method, r.URL)+ http.NotFound(w, r)+ }))+ t.Cleanup(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")+ return requests+}++func reply(body string) func(http.ResponseWriter, *http.Request) {+ return func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(body)) }+}++func runInboxCommand(t *testing.T, register func(*cobra.Command), run func(*cobra.Command, []string) error, args []string, flags map[string]string) (string, error) {+ t.Helper()+ cmd := &cobra.Command{Use: "test"}+ register(cmd)+ for name, value := range flags {+ if err := cmd.Flags().Set(name, value); err != nil {+ t.Fatal(err)+ }+ }+ return captureStdout(t, func() error { return run(cmd, args) })+}++// withEmptyStdin stands in for an agent run, which cannot answer a prompt.+func withEmptyStdin(t *testing.T) {+ t.Helper()+ devNull, err := os.Open(os.DevNull)+ if err != nil {+ t.Fatal(err)+ }+ old := os.Stdin+ os.Stdin = devNull+ t.Cleanup(func() { os.Stdin = old; devNull.Close() })+}++func TestInboxListFiltersAndEnrichesRows(t *testing.T) {+ recent := time.Now().Add(-time.Hour).UTC().Format(time.RFC3339)+ old := time.Now().Add(-72 * time.Hour).UTC().Format(time.RFC3339)+ requests := fakeInboxServer(t, map[string]func(http.ResponseWriter, *http.Request){+ "GET /api/inbox": reply(`[+ {"id":"` + inboxItemA + `","type":"new_comment","title":"Comment on X","issue_id":"` + inboxIssue1 + `","read":false,"created_at":"` + recent + `",+ "actor_type":"member","actor_id":"` + inboxMember + `","body":"Looks good,\n ship it","details":{"comment_id":"c1"}},+ {"id":"` + inboxItemB + `","type":"mentioned","title":"Mention on Y","issue_id":"` + inboxIssue2 + `","read":true,"created_at":"` + recent + `",+ "actor_type":"agent","actor_id":"` + inboxAgent + `"},+ {"id":"old","type":"new_comment","title":"Old","issue_id":"` + inboxIssue1 + `","read":false,"created_at":"` + old + `"}+ ]`),+ "GET /api/issues": func(w http.ResponseWriter, r *http.Request) {+ if ids := r.URL.Query().Get("ids"); ids != inboxIssue1 {+ t.Errorf("issue lookup ids = %q, want only the listed issue", ids)+ }+ _, _ = w.Write([]byte(`{"issues":[{"id":"` + inboxIssue1 + `","identifier":"MUL-1","title":"X"}]}`))+ },+ "GET /api/workspaces/ws-1/members": reply(`[{"user_id":"` + inboxMember + `","name":"Jiayuan"}]`),+ })+ out, err := runInboxCommand(t, registerInboxListFlags, func(cmd *cobra.Command, _ []string) error { return runInboxList(cmd, nil) }, nil,+ map[string]string{"unread": "true", "since": "1d", "issue": inboxIssue1, "output": "json"})+ if err != nil {+ t.Fatal(err)+ }+ var rows []map[string]any+ if err := json.Unmarshal([]byte(out), &rows); err != nil {+ t.Fatal(err)+ }+ if len(rows) != 1 || rows[0]["id"] != inboxItemA {+ t.Fatalf("filters kept %v, want only the recent unread row on the issue", rows)+ }+ row := rows[0]+ if row["issue_identifier"] != "MUL-1" || row["actor"] != "member:Jiayuan" || row["summary"] != "Looks good, ship it" || row["comment_id"] != "c1" {+ t.Fatalf("row not enriched: %v", row)+ }+ if _, ok := row["body"]; ok {+ t.Fatal("raw body leaked into list output")+ }+ if len(*requests) != 3 {+ t.Fatalf("requests = %v; want inbox, one issue lookup and one member lookup", *requests)+ }+}++// The archive used to come from a list capped at 200 issue groups, so an older+// archived issue could not be found to restore it.+func TestInboxListArchivedReadsEveryPage(t *testing.T) {+ const groups = 250+ var pages []url.Values+ fakeInboxServer(t, map[string]func(http.ResponseWriter, *http.Request){+ "GET /api/inbox/archived/page": func(w http.ResponseWriter, r *http.Request) {+ q := r.URL.Query()+ pages = append(pages, q)+ start := 0+ if cursor := q.Get("cursor"); cursor != "" {+ start, _ = strconv.Atoi(cursor)+ }+ limit, _ := strconv.Atoi(q.Get("limit"))+ end := min(start+limit, groups)+ items := make([]string, 0, end-start)+ for i := start; i < end; i++ {+ items = append(items, fmt.Sprintf(`{"id":"%08d-0000-0000-0000-000000000000","type":"system","title":"Notice %d","read":true,"created_at":"2026-11-01T00:00:00Z"}`, i, i))+ }+ next := "null"+ if end < groups {+ next = fmt.Sprintf(`"%d"`, end)+ }+ fmt.Fprintf(w, `{"items":[%s],"next_cursor":%s,"has_more":%t}`, strings.Join(items, ","), next, end < groups)+ },+ })+ out, err := runInboxCommand(t, registerInboxListFlags, func(cmd *cobra.Command, _ []string) error { return runInboxList(cmd, nil) }, nil,+ map[string]string{"archived": "true", "output": "json"})+ if err != nil {+ t.Fatal(err)+ }+ var rows []map[string]any+ if err := json.Unmarshal([]byte(out), &rows); err != nil {+ t.Fatal(err)+ }+ if len(rows) != groups || rows[groups-1]["title"] != fmt.Sprintf("Notice %d", groups-1) {+ t.Fatalf("listed %d archived groups, want all %d", len(rows), groups)+ }+ if len(pages) != 3 || pages[0].Get("cursor") != "" || pages[1].Get("cursor") != "100" || pages[2].Get("cursor") != "200" {+ t.Fatalf("pages = %v", pages)+ }+}++func TestInboxListArchivedSendsFiltersToServer(t *testing.T) {+ var query url.Values+ fakeInboxServer(t, map[string]func(http.ResponseWriter, *http.Request){+ "GET /api/projects/" + inboxProject: reply(`{"id":"` + inboxProject + `"}`),+ "GET /api/inbox/archived/page": func(w http.ResponseWriter, r *http.Request) {+ query = r.URL.Query()+ _, _ = w.Write([]byte(`{"items":[{"id":"` + inboxItemA + `","type":"new_comment","title":"Old","issue_id":"` + inboxIssue1 + `","issue_project_id":"` + inboxProject + `","read":false,"created_at":"` + time.Now().UTC().Format(time.RFC3339) + `"}],"next_cursor":null,"has_more":false}`))+ },+ "GET /api/issues": reply(`{"issues":[{"id":"` + inboxIssue1 + `","identifier":"MUL-1","title":"X"}]}`),+ })+ out, err := runInboxCommand(t, registerInboxListFlags, func(cmd *cobra.Command, _ []string) error { return runInboxList(cmd, nil) }, nil,+ map[string]string{"archived": "true", "issue": inboxIssue1, "project": inboxProject, "unread": "true", "since": "1d", "type": "new_comment", "output": "json"})+ if err != nil || !strings.Contains(out, inboxItemA) {+ t.Fatalf("archived: %s %v", out, err)+ }+ since, err := time.Parse(time.RFC3339Nano, query.Get("received_after"))+ if query.Get("group_id") != inboxIssue1 || query.Get("projects") != inboxProject || query.Get("unread_only") != "true" || query.Get("notification_types") != "new_comment" ||+ err != nil || time.Since(since) < 23*time.Hour || time.Since(since) > 25*time.Hour {+ t.Fatalf("archive page query = %v", query)+ }+}++// The archive lists each issue under one notification, so a mention under a+// later status change is only found when the type reaches the server.+func TestInboxListArchivedTypeFindsOlderNotification(t *testing.T) {+ fakeInboxServer(t, map[string]func(http.ResponseWriter, *http.Request){+ "GET /api/inbox/archived/page": func(w http.ResponseWriter, r *http.Request) {+ id, kind := inboxItemB, "status_changed"+ if r.URL.Query().Get("notification_types") == "mentioned" {+ id, kind = inboxItemA, "mentioned"+ }+ fmt.Fprintf(w, `{"items":[{"id":"%s","type":"%s","title":"T","issue_id":"%s","read":true,"created_at":"2026-11-01T00:00:00Z"}],"next_cursor":null,"has_more":false}`, id, kind, inboxIssue1)+ },+ "GET /api/issues": reply(`{"issues":[{"id":"` + inboxIssue1 + `","identifier":"MUL-1","title":"X"}]}`),+ })+ out, err := runInboxCommand(t, registerInboxListFlags, func(cmd *cobra.Command, _ []string) error { return runInboxList(cmd, nil) }, nil,+ map[string]string{"archived": "true", "type": "mentioned", "issue": inboxIssue1, "output": "json"})+ if err != nil {+ t.Fatal(err)+ }+ var rows []map[string]any+ if err := json.Unmarshal([]byte(out), &rows); err != nil {+ t.Fatal(err)+ }+ if len(rows) != 1 || rows[0]["id"] != inboxItemA || rows[0]["type"] != "mentioned" {+ t.Fatalf("archived --type mentioned = %v, want the older mention", rows)+ }+}++func TestInboxListSnoozed(t *testing.T) {+ requests := fakeInboxServer(t, map[string]func(http.ResponseWriter, *http.Request){+ "GET /api/inbox/snoozed": reply(`[{"issue_id":"` + inboxIssue1 + `","item_id":"` + inboxItemB + `","snoozed_until":"2026-12-01T09:00:00Z","snoozed_at":"2026-11-18T00:00:00Z","updates":2}]`),+ "GET /api/issues": reply(`{"issues":[{"id":"` + inboxIssue1 + `","identifier":"MUL-1","title":"X"}]}`),+ })+ list := func(cmd *cobra.Command, _ []string) error { return runInboxList(cmd, nil) }++ out, err := runInboxCommand(t, registerInboxListFlags, list, nil, map[string]string{"snoozed": "true", "output": "json"})+ if err != nil {+ t.Fatal(err)+ }+ var snoozed []map[string]any+ if err := json.Unmarshal([]byte(out), &snoozed); err != nil {+ t.Fatal(err)+ }+ if len(snoozed) != 1 || snoozed[0]["id"] != inboxItemB || snoozed[0]["issue_identifier"] != "MUL-1" || snoozed[0]["title"] != "X" || snoozed[0]["updates"] != float64(2) {+ t.Fatalf("snoozed row = %v", snoozed)+ }++ before := len(*requests)+ for _, flags := range []map[string]string{+ {"archived": "true", "snoozed": "true"},+ {"snoozed": "true", "unread": "true"},+ {"since": "next tuesday"},+ } {+ if _, err := runInboxCommand(t, registerInboxListFlags, list, nil, flags); err == nil {+ t.Errorf("flags %v accepted", flags)+ }+ }+ if len(*requests) != before {+ t.Fatal("invalid flags reached the server")+ }+}++func TestInboxItemWritesReportCountAndFailures(t *testing.T) {+ requests := fakeInboxServer(t, map[string]func(http.ResponseWriter, *http.Request){+ // A reads its whole issue; C, on the same issue, has nothing left to read.+ "POST /api/inbox/" + inboxItemA + "/read": reply(`{"id":"` + inboxItemA + `","issue_id":"` + inboxIssue1 + `","count":3}`),+ "POST /api/inbox/" + inboxItemC + "/read": reply(`{"id":"` + inboxItemC + `","issue_id":"` + inboxIssue1 + `","count":0}`),+ "POST /api/inbox/" + inboxItemB + "/read": func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusForbidden)+ _, _ = w.Write([]byte(`{"error":"inbox access requires the runtime owner's verified human trigger"}`))+ },+ })+ out, err := runInboxCommand(t, registerInboxReadFlags, runInboxRead, []string{inboxItemA, strings.ToUpper(inboxItemA), inboxItemB, inboxItemC}, map[string]string{"output": "json"})+ if err == nil || !strings.Contains(err.Error(), "1 of 3") {+ t.Fatalf("partial failure error = %v", err)+ }+ var result inboxWriteResult+ if err := json.Unmarshal([]byte(out), &result); err != nil {+ t.Fatal(err)+ }+ if result.Action != "read" || result.Count != 3 || len(result.Items) != 2 ||+ result.Items[0].ID != inboxItemA || result.Items[0].Count != 3 || *result.Items[0].IssueID != inboxIssue1 ||+ result.Items[1].ID != inboxItemC || result.Items[1].Count != 0 ||+ len(result.Failed) != 1 || result.Failed[0].ID != inboxItemB || !strings.Contains(result.Failed[0].Error, "verified human trigger") {+ t.Fatalf("result = %+v", result)+ }+ if len(*requests) != 3 {+ t.Fatalf("duplicate id not collapsed or failure stopped the batch: %v", *requests)+ }++ *requests = nil+ out, err = runInboxCommand(t, registerInboxReadFlags, runInboxRead, []string{inboxItemA, inboxItemC}, nil)+ if err != nil {+ t.Fatal(err)+ }+ for _, line := range []string{inboxItemA + ": 3 notifications", inboxItemC + ": no change", "Marked read 3 notifications"} {+ if !strings.Contains(out, line) {+ t.Errorf("table output missing %q: %s", line, out)+ }+ }++ *requests = nil+ if _, err := runInboxCommand(t, registerInboxReadFlags, runInboxRead, []string{inboxItemA, "aaaa"}, nil); err == nil || !strings.Contains(err.Error(), "not a full UUID") {+ t.Fatalf("short id error = %v", err)+ }+ if len(*requests) != 0 {+ t.Fatal("an invalid id must stop the command before any write")+ }+}++func TestInboxArchiveUnarchiveUnreadUnsnoozeHitTheirEndpoints(t *testing.T) {+ for _, tc := range []struct {+ name string+ register func(*cobra.Command)+ run func(*cobra.Command, []string) error+ action string+ }{+ {"unread", registerInboxOutputFlag, runInboxUnread, "unread"},+ {"archive", registerInboxArchiveFlags, runInboxArchive, "archive"},+ {"unarchive", registerInboxOutputFlag, runInboxUnarchive, "unarchive"},+ {"unsnooze", registerInboxOutputFlag, runInboxUnsnooze, "unsnooze"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ // An older server answers without a count; the notification itself still counts.+ for body, want := range map[string]int64{`{"issue_id":"` + inboxIssue1 + `","count":4}`: 4, `{"issue_id":"` + inboxIssue1 + `"}`: 1} {+ requests := fakeInboxServer(t, map[string]func(http.ResponseWriter, *http.Request){+ "POST /api/inbox/" + inboxItemA + "/" + tc.action: reply(body),+ })+ out, err := runInboxCommand(t, tc.register, tc.run, []string{inboxItemA}, map[string]string{"output": "json"})+ if err != nil {+ t.Fatal(err)+ }+ var result inboxWriteResult+ if err := json.Unmarshal([]byte(out), &result); err != nil || result.Action != tc.action || result.Count != want {+ t.Fatalf("answer %s: result = %s (%v), want count %d", body, out, err, want)+ }+ if len(*requests) != 1 {+ t.Fatalf("requests = %v", *requests)+ }+ }+ })+ }+}++func TestInboxSnoozeSendsUntil(t *testing.T) {+ requests := fakeInboxServer(t, map[string]func(http.ResponseWriter, *http.Request){+ "POST /api/inbox/" + inboxItemA + "/snooze": reply(`{"issue_id":"` + inboxIssue1 + `","count":3}`),+ "POST /api/inbox/" + inboxItemC + "/snooze": reply(`{"issue_id":"` + inboxIssue1 + `","count":3}`),+ "POST /api/inbox/" + inboxItemB + "/snooze": reply(`{"issue_id":"` + inboxIssue2 + `","count":2}`),+ })+ until := time.Now().Add(48 * time.Hour).UTC().Truncate(time.Second).Format(time.RFC3339)+ out, err := runInboxCommand(t, registerInboxSnoozeFlags, runInboxSnooze, []string{inboxItemA, inboxItemC, inboxItemB}, map[string]string{"until": until, "output": "json"})+ if err != nil {+ t.Fatal(err)+ }+ if len(*requests) != 3 || (*requests)[0].body != `{"until":"`+until+`"}` {+ t.Fatalf("requests = %v", *requests)+ }+ var result inboxWriteResult+ if err := json.Unmarshal([]byte(out), &result); err != nil {+ t.Fatal(err)+ }+ // C re-snoozes A's issue to the same time, which changes nothing.+ if result.SnoozedUntil != until || result.Count != 5 || len(result.Items) != 3 || result.Items[1].Count != 0 {+ t.Fatalf("result = %+v", result)+ }++ *requests = nil+ for _, flags := range []map[string]string{{}, {"until": "2020-01-01T00:00:00Z"}, {"until": "someday"}} {+ if _, err := runInboxCommand(t, registerInboxSnoozeFlags, runInboxSnooze, []string{inboxItemA}, flags); err == nil {+ t.Errorf("--until %v accepted", flags)+ }+ }+ if len(*requests) != 0 {+ t.Fatal("an invalid --until reached the server")+ }+}++func TestInboxReadIssueAndBulkModes(t *testing.T) {+ requests := fakeInboxServer(t, map[string]func(http.ResponseWriter, *http.Request){+ "GET /api/issues/MUL-1": reply(`{"id":"` + inboxIssue1 + `","identifier":"MUL-1"}`),+ "POST /api/inbox/issues/" + inboxIssue1 + "/read": reply(`{"count":4}`),+ "POST /api/inbox/mark-all-read": reply(`{"count":35}`),+ "POST /api/inbox/archive-all": reply(`{"count":7}`),+ "POST /api/inbox/archive-all-read": reply(`{"count":5}`),+ "POST /api/inbox/archive-completed": reply(`{"count":2}`),+ })+ count := func(out string) int64 {+ t.Helper()+ var result inboxWriteResult+ if err := json.Unmarshal([]byte(out), &result); err != nil {+ t.Fatalf("%s: %v", out, err)+ }+ return result.Count+ }++ out, err := runInboxCommand(t, registerInboxReadFlags, runInboxRead, nil, map[string]string{"issue": "MUL-1", "output": "json"})+ if err != nil || count(out) != 4 {+ t.Fatalf("read --issue: %s %v", out, err)+ }++ withEmptyStdin(t)+ *requests = nil+ for _, tc := range []struct {+ register func(*cobra.Command)+ run func(*cobra.Command, []string) error+ flag string+ }{+ {registerInboxReadFlags, runInboxRead, "all"},+ {registerInboxArchiveFlags, runInboxArchive, "all"},+ {registerInboxArchiveFlags, runInboxArchive, "read"},+ {registerInboxArchiveFlags, runInboxArchive, "completed"},+ } {+ if _, err := runInboxCommand(t, tc.register, tc.run, nil, map[string]string{tc.flag: "true"}); err == nil || !strings.Contains(err.Error(), "--yes") {+ t.Fatalf("--%s without --yes: %v", tc.flag, err)+ }+ }+ if len(*requests) != 0 {+ t.Fatalf("an unconfirmed bulk change reached the server: %v", *requests)+ }++ for _, tc := range []struct {+ register func(*cobra.Command)+ run func(*cobra.Command, []string) error+ flag string+ want int64+ }{+ {registerInboxReadFlags, runInboxRead, "all", 35},+ {registerInboxArchiveFlags, runInboxArchive, "all", 7},+ {registerInboxArchiveFlags, runInboxArchive, "read", 5},+ {registerInboxArchiveFlags, runInboxArchive, "completed", 2},+ } {+ out, err := runInboxCommand(t, tc.register, tc.run, nil, map[string]string{tc.flag: "true", "yes": "true", "output": "json"})+ if err != nil || count(out) != tc.want {+ t.Fatalf("--%s --yes: %s %v", tc.flag, out, err)+ }+ }++ *requests = nil+ for _, tc := range []struct {+ register func(*cobra.Command)+ run func(*cobra.Command, []string) error+ args []string+ flags map[string]string+ }{+ {registerInboxReadFlags, runInboxRead, nil, nil},+ {registerInboxReadFlags, runInboxRead, []string{inboxItemA}, map[string]string{"all": "true", "yes": "true"}},+ {registerInboxReadFlags, runInboxRead, nil, map[string]string{"issue": "MUL-1", "all": "true"}},+ {registerInboxArchiveFlags, runInboxArchive, nil, map[string]string{"read": "true", "completed": "true", "yes": "true"}},+ } {+ if _, err := runInboxCommand(t, tc.register, tc.run, tc.args, tc.flags); err == nil {+ t.Errorf("ambiguous selection accepted: args=%v flags=%v", tc.args, tc.flags)+ }+ }+ if len(*requests) != 0 {+ t.Fatalf("an ambiguous selection reached the server: %v", *requests)+ }+}++func TestInboxCount(t *testing.T) {+ fakeInboxServer(t, map[string]func(http.ResponseWriter, *http.Request){+ "GET /api/inbox/unread-count": reply(`{"count":36}`),+ "GET /api/inbox/unread-summary": reply(`[{"workspace_id":"ws-1","count":36},{"workspace_id":"ws-2","count":1}]`),+ })+ out, err := runInboxCommand(t, registerInboxOutputFlag, runInboxCount, nil, map[string]string{"output": "json"})+ if err != nil {+ t.Fatal(err)+ }+ var result struct {+ WorkspaceID string `json:"workspace_id"`+ Unread int64 `json:"unread"`+ Workspaces []struct {+ WorkspaceID string `json:"workspace_id"`+ Count int64 `json:"count"`+ } `json:"workspaces"`+ }+ if err := json.Unmarshal([]byte(out), &result); err != nil || result.WorkspaceID != "ws-1" || result.Unread != 36 || len(result.Workspaces) != 2 {+ t.Fatalf("count = %s (%v)", out, err)+ }+}++func TestInboxCommandsRegisteredWithoutDelete(t *testing.T) {+ for _, name := range []string{"list", "count", "read", "unread", "archive", "unarchive", "snooze", "unsnooze"} {+ cmd, _, err := rootCmd.Find([]string{"inbox", name})+ if err != nil || cmd.Name() != name || cmd.Parent().Name() != "inbox" {+ t.Errorf("inbox %s not registered: %v", name, err)+ }+ }+ for _, cmd := range inboxCmd.Commands() {+ if cmd.Name() == "delete" || cmd.HasAlias("delete") || cmd.HasAlias("rm") {+ t.Fatal("notifications must not be deletable from the CLI")+ }+ }+}++func TestParseInboxTime(t *testing.T) {+ loc := time.FixedZone("UTC+8", 8*3600)+ afternoon := time.Date(2026, 11, 18, 15, 30, 0, 0, loc)+ night := time.Date(2026, 11, 18, 23, 10, 0, 0, loc)+ for _, tc := range []struct {+ value string+ now time.Time+ back bool+ want time.Time+ }{+ {"2026-12-01T09:00:00Z", afternoon, false, time.Date(2026, 12, 1, 9, 0, 0, 0, time.UTC)},+ {"30m", afternoon, false, afternoon.Add(30 * time.Minute)},+ {"3h", afternoon, false, afternoon.Add(3 * time.Hour)},+ {"1h30m", afternoon, false, afternoon.Add(90 * time.Minute)},+ {"1d", afternoon, false, time.Date(2026, 11, 19, 15, 30, 0, 0, loc)},+ {"1w", afternoon, false, time.Date(2026, 11, 25, 15, 30, 0, 0, loc)},+ {"1d", night, false, time.Date(2026, 11, 19, 9, 0, 0, 0, loc)},+ {"3h", night, false, night.Add(3 * time.Hour)},+ {"Tomorrow", afternoon, false, time.Date(2026, 11, 19, 9, 0, 0, 0, loc)},+ {"2d", night, true, time.Date(2026, 11, 16, 23, 10, 0, 0, loc)},+ {"24h", afternoon, true, afternoon.Add(-24 * time.Hour)},+ } {+ got, err := parseInboxTime(tc.value, tc.now, tc.back)+ if err != nil || !got.Equal(tc.want) {+ t.Errorf("parseInboxTime(%q, back=%v) = %v, %v; want %v", tc.value, tc.back, got, err, tc.want)+ }+ }+ for _, value := range []string{"", "soon", "0d", "-1h", "tomorrow-ish"} {+ if _, err := parseInboxTime(value, afternoon, false); err == nil {+ t.Errorf("parseInboxTime(%q) accepted", value)+ }+ }+ if _, err := parseInboxTime("tomorrow", afternoon, true); err == nil {+ t.Error("--since tomorrow accepted")+ }+}diff --git a/server/cmd/multica/cmd_inbox_test.go b/server/cmd/multica/cmd_inbox_test.goindex e0d838ba21..6f1da71785 100644--- a/server/cmd/multica/cmd_inbox_test.go+++ b/server/cmd/multica/cmd_inbox_test.go@@ -96,6 +96,7 @@ func TestInboxListFiltersAndCommentAnchors(t *testing.T) {}func TestInboxListTableAndDeniedRequest(t *testing.T) {+ const longTitle = "Need input on the archive pagination rewrite before the Friday release goes out"status := http.StatusOKrequests := 0srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -108,7 +109,7 @@ func TestInboxListTableAndDeniedRequest(t *testing.T) {_, _ = 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"}}]`))+ _, _ = w.Write([]byte(`[{"id":"n1","type":"mentioned","title":"` + longTitle + `","issue_id":"i1","issue_project_id":"p1","read":true,"details":{"comment_id":"c1"}}]`))}))defer srv.Close()t.Setenv("MULTICA_SERVER_URL", srv.URL)@@ -118,7 +119,11 @@ func TestInboxListTableAndDeniedRequest(t *testing.T) {if err != nil {t.Fatal(err)}- for _, value := range []string{"ID", "TYPE", "TITLE", "ISSUE", "COMMENT", "PROJECT", "READ", "CREATED", "n1", "c1", "true"} {+ header := strings.Fields(strings.SplitN(out, "\n", 2)[0])+ if want := []string{"ID", "TYPE", "TITLE", "ISSUE", "COMMENT", "PROJECT", "READ", "CREATED", "KEY", "FROM", "SUMMARY"}; strings.Join(header, " ") != strings.Join(want, " ") {+ t.Errorf("header = %v, want the original columns first, then %v", header, want[8:])+ }+ for _, value := range []string{"n1", longTitle, "i1", "c1", "p1", "true"} {if !strings.Contains(out, value) {t.Errorf("table missing %q: %s", value, out)}diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex b82d6a23ac..2a82aa1652 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -751,7 +751,7 @@ const platformSkillName = "multica-platform"// description, repeated in the brief's recall hint for agents that never read// the skill listing. TestPlatformSkillDomainsMatchDescription keeps it equal to// the description, so a new reference cannot ship without reaching the brief.-const platformSkillDomains = "issue and PR contracts, sub-issues, batch changes, saved views, charts and files in comments, mentions, agents, squads, autopilots, projects, runtimes, local environments, skill import, themes"+const platformSkillDomains = "issue and PR contracts, sub-issues, batch changes, saved views, comment charts and files, mentions, inbox, agents, squads, autopilots, projects, runtimes, local environments, skill import, themes"// subIssueContractsSkill returns how the brief should refer to the skill// carrying the sub-issue contracts, and whether any such skill is installed.diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 8814c1c137..f4639c81fb 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -1300,6 +1300,9 @@ func (h *Handler) loadInboxItemForUser(w http.ResponseWriter, r *http.Request, iif !ok {return db.InboxItem{}, false}+ if !h.requireInboxOwnerAccess(w, r, userID, wsUUID) {+ return db.InboxItem{}, false+ }item, err := h.Queries.GetInboxItemInWorkspace(r.Context(), db.GetInboxItemInWorkspaceParams{ID: itemUUID,diff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.goindex 658669156a..7de00bd3f6 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -263,9 +263,9 @@ func (h *Handler) ListInbox(w http.ResponseWriter, r *http.Request) {}// Task tokens identify the runtime owner, not necessarily the human who asked-// the agent to act. Reading the owner's notifications (active list and the-// archive) requires that same human upstream. Auth strips client identity-// headers and stamps the task/agent from the token.+// the agent to act. Reading or changing the owner's notifications requires+// that same human upstream; every inbox endpoint goes through this gate. Auth+// strips client identity headers and stamps the task/agent from the token.func (h *Handler) requireInboxOwnerAccess(w http.ResponseWriter, r *http.Request, userID string, workspaceID pgtype.UUID) bool {source := r.Header.Get("X-Actor-Source")if source == "" {@@ -312,6 +312,17 @@ func (h *Handler) requireInboxOwnerAccess(w http.ResponseWriter, r *http.Requestreturn true}+// logAgentInboxWrite records which agent changed which human's inbox, so a+// change made on the owner's behalf can be traced to the run that made it.+// Human writes need no extra record.+func logAgentInboxWrite(r *http.Request, action string, attrs ...any) {+ if r.Header.Get("X-Actor-Source") != "task_token" {+ return+ }+ attrs = append([]any{"action", action, "agent_id", r.Header.Get("X-Agent-ID"), "task_id", r.Header.Get("X-Task-ID")}, attrs...)+ slog.Info("inbox: agent write", append(logger.RequestAttrs(r), attrs...)...)+}+// 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@@ -373,12 +384,15 @@ func (h *Handler) MarkInboxRead(w http.ResponseWriter, r *http.Request) {if !ok {return}- item, err := h.Queries.MarkInboxRead(r.Context(), prev.ID)+ row, err := h.Queries.MarkInboxRead(r.Context(), prev.ID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to mark read")return}+ item := row.InboxItem+ count := row.SiblingsRead + changedCount(!prev.Read)+ logAgentInboxWrite(r, "read", "item_id", uuidToString(item.ID), "count", count)userID := requestUserID(r)workspaceID := uuidToString(item.WorkspaceID)h.publish(protocol.EventInboxRead, workspaceID, "member", userID, map[string]any{@@ -387,7 +401,21 @@ func (h *Handler) MarkInboxRead(w http.ResponseWriter, r *http.Request) {})resp := h.enrichInboxResponse(r.Context(), inboxToResponse(item), item.IssueID)- writeJSON(w, http.StatusOK, resp)+ writeJSON(w, http.StatusOK, inboxWriteResponse{resp, count})+}++// inboxWriteResponse is the changed item plus how many notifications the change+// actually modified, its issue group included; repeating a change counts 0.+type inboxWriteResponse struct {+ InboxItemResponse+ Count int64 `json:"count"`+}++func changedCount(changed bool) int64 {+ if changed {+ return 1+ }+ return 0}// MarkInboxUnread flips a notification back to unread, the inverse of@@ -409,6 +437,8 @@ func (h *Handler) MarkInboxUnread(w http.ResponseWriter, r *http.Request) {return}+ count := changedCount(prev.Read)+ logAgentInboxWrite(r, "unread", "item_id", uuidToString(item.ID), "count", count)userID := requestUserID(r)workspaceID := uuidToString(item.WorkspaceID)h.publish(protocol.EventInboxUnread, workspaceID, "member", userID, map[string]any{@@ -417,10 +447,16 @@ func (h *Handler) MarkInboxUnread(w http.ResponseWriter, r *http.Request) {})resp := h.enrichInboxResponse(r.Context(), inboxToResponse(item), item.IssueID)- writeJSON(w, http.StatusOK, resp)+ writeJSON(w, http.StatusOK, inboxWriteResponse{resp, count})}+// DeleteInboxItem is human-only: deletion cannot be undone, unlike every other+// inbox change, so agents acting for the owner may archive but not delete.func (h *Handler) DeleteInboxItem(w http.ResponseWriter, r *http.Request) {+ if isMachineCredentialActor(r) {+ writeError(w, http.StatusForbidden, "deleting notifications is only available to human actors")+ return+ }item, ok := h.loadInboxItemForUser(w, r, chi.URLParam(r, "id"))if !ok {return@@ -457,16 +493,19 @@ func (h *Handler) ArchiveInboxItem(w http.ResponseWriter, r *http.Request) {return}+ count := changedCount(!prev.Archived)// Archive all sibling inbox items for the same issue (issue-level archive)if item.IssueID.Valid {- h.Queries.ArchiveInboxByIssue(r.Context(), db.ArchiveInboxByIssueParams{+ siblings, _ := h.Queries.ArchiveInboxByIssue(r.Context(), db.ArchiveInboxByIssueParams{WorkspaceID: item.WorkspaceID,RecipientType: item.RecipientType,RecipientID: item.RecipientID,IssueID: item.IssueID,})+ count += siblings}+ logAgentInboxWrite(r, "archive", "item_id", uuidToString(item.ID), "issue_id", uuidToPtr(item.IssueID), "count", count)userID := requestUserID(r)workspaceID := uuidToString(item.WorkspaceID)h.publish(protocol.EventInboxArchived, workspaceID, "member", userID, map[string]any{@@ -476,7 +515,7 @@ func (h *Handler) ArchiveInboxItem(w http.ResponseWriter, r *http.Request) {})resp := h.enrichInboxResponse(r.Context(), inboxToResponse(item), item.IssueID)- writeJSON(w, http.StatusOK, resp)+ writeJSON(w, http.StatusOK, inboxWriteResponse{resp, count})}// UnarchiveInboxItem restores an archived notification to the main inbox. It is@@ -499,16 +538,19 @@ func (h *Handler) UnarchiveInboxItem(w http.ResponseWriter, r *http.Request) {return}+ count := changedCount(prev.Archived)// Restore all sibling inbox items for the same issue (issue-level restore).if item.IssueID.Valid {- h.Queries.UnarchiveInboxByIssue(r.Context(), db.UnarchiveInboxByIssueParams{+ siblings, _ := h.Queries.UnarchiveInboxByIssue(r.Context(), db.UnarchiveInboxByIssueParams{WorkspaceID: item.WorkspaceID,RecipientType: item.RecipientType,RecipientID: item.RecipientID,IssueID: item.IssueID,})+ count += siblings}+ logAgentInboxWrite(r, "unarchive", "item_id", uuidToString(item.ID), "issue_id", uuidToPtr(item.IssueID), "count", count)userID := requestUserID(r)workspaceID := uuidToString(item.WorkspaceID)h.publish(protocol.EventInboxUnarchived, workspaceID, "member", userID, map[string]any{@@ -518,7 +560,7 @@ func (h *Handler) UnarchiveInboxItem(w http.ResponseWriter, r *http.Request) {})resp := h.enrichInboxResponse(r.Context(), inboxToResponse(item), item.IssueID)- writeJSON(w, http.StatusOK, resp)+ writeJSON(w, http.StatusOK, inboxWriteResponse{resp, count})}func (h *Handler) CountUnreadInbox(w http.ResponseWriter, r *http.Request) {@@ -533,6 +575,9 @@ func (h *Handler) CountUnreadInbox(w http.ResponseWriter, r *http.Request) {if !ok {return}+ if !h.requireInboxOwnerAccess(w, r, userID, wsUUID) {+ return+ }hidden, ok := h.requestInboxHiddenProjects(w, r, workspaceID)if !ok {@@ -574,6 +619,14 @@ 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.+ if r.Header.Get("X-Actor-Source") != "" {+ wsUUID, ok := parseUUIDOrBadRequest(w, ctxWorkspaceID(r.Context()), "workspace id")+ if !ok || !h.requireInboxOwnerAccess(w, r, userID, wsUUID) {+ return+ }+ }value, err := h.inboxReadGuard().Summary(r.Context(), userID, func(ctx context.Context) (any, error) {return runInboxRead(ctx, h, "summary", func(ctx context.Context, q *db.Queries) ([]db.CountUnreadInboxByWorkspaceRow, error) {@@ -607,6 +660,9 @@ func (h *Handler) MarkAllInboxRead(w http.ResponseWriter, r *http.Request) {if !ok {return}+ if !h.requireInboxOwnerAccess(w, r, userID, wsUUID) {+ return+ }count, err := h.Queries.MarkAllInboxRead(r.Context(), db.MarkAllInboxReadParams{WorkspaceID: wsUUID,@@ -618,6 +674,7 @@ func (h *Handler) MarkAllInboxRead(w http.ResponseWriter, r *http.Request) {}slog.Info("inbox: mark all read", append(logger.RequestAttrs(r), "user_id", userID, "count", count)...)+ logAgentInboxWrite(r, "mark_all_read", "count", count)h.publish(protocol.EventInboxBatchRead, workspaceID, "member", userID, map[string]any{"recipient_id": userID,"count": count,@@ -646,6 +703,9 @@ func (h *Handler) MarkIssueInboxRead(w http.ResponseWriter, r *http.Request) {if !ok {return}+ if !h.requireInboxOwnerAccess(w, r, userID, wsUUID) {+ return+ }count, err := h.Queries.MarkInboxReadByIssue(r.Context(), db.MarkInboxReadByIssueParams{WorkspaceID: wsUUID,@@ -656,6 +716,7 @@ func (h *Handler) MarkIssueInboxRead(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to mark issue inbox read")return}+ logAgentInboxWrite(r, "read_issue", "issue_id", uuidToString(issueUUID), "count", count)// Opening an issue with nothing unread is the common case. It changes no// row, so it must not make every open client refetch its inbox.@@ -680,6 +741,9 @@ func (h *Handler) ArchiveAllInbox(w http.ResponseWriter, r *http.Request) {if !ok {return}+ if !h.requireInboxOwnerAccess(w, r, userID, wsUUID) {+ return+ }count, err := h.Queries.ArchiveAllInbox(r.Context(), db.ArchiveAllInboxParams{WorkspaceID: wsUUID,@@ -691,6 +755,7 @@ func (h *Handler) ArchiveAllInbox(w http.ResponseWriter, r *http.Request) {}slog.Info("inbox: archive all", append(logger.RequestAttrs(r), "user_id", userID, "count", count)...)+ logAgentInboxWrite(r, "archive_all", "count", count)h.publish(protocol.EventInboxBatchArchived, workspaceID, "member", userID, map[string]any{"recipient_id": userID,"count": count,@@ -709,6 +774,9 @@ func (h *Handler) ArchiveAllReadInbox(w http.ResponseWriter, r *http.Request) {if !ok {return}+ if !h.requireInboxOwnerAccess(w, r, userID, wsUUID) {+ return+ }count, err := h.Queries.ArchiveAllReadInbox(r.Context(), db.ArchiveAllReadInboxParams{WorkspaceID: wsUUID,@@ -720,6 +788,7 @@ func (h *Handler) ArchiveAllReadInbox(w http.ResponseWriter, r *http.Request) {}slog.Info("inbox: archive all read", append(logger.RequestAttrs(r), "user_id", userID, "count", count)...)+ logAgentInboxWrite(r, "archive_all_read", "count", count)h.publish(protocol.EventInboxBatchArchived, workspaceID, "member", userID, map[string]any{"recipient_id": userID,"count": count,@@ -738,6 +807,9 @@ func (h *Handler) ArchiveCompletedInbox(w http.ResponseWriter, r *http.Request)if !ok {return}+ if !h.requireInboxOwnerAccess(w, r, userID, wsUUID) {+ return+ }terminalStatusKeys, err := h.terminalIssueStatusKeys(r.Context(), wsUUID)if err != nil {@@ -755,6 +827,7 @@ func (h *Handler) ArchiveCompletedInbox(w http.ResponseWriter, r *http.Request)}slog.Info("inbox: archive completed", append(logger.RequestAttrs(r), "user_id", userID, "count", count)...)+ logAgentInboxWrite(r, "archive_completed", "count", count)h.publish(protocol.EventInboxBatchArchived, workspaceID, "member", userID, map[string]any{"recipient_id": userID,"count": count,diff --git a/server/internal/handler/inbox_archive.go b/server/internal/handler/inbox_archive.goindex 392180f919..147864458e 100644--- a/server/internal/handler/inbox_archive.go+++ b/server/internal/handler/inbox_archive.go@@ -132,14 +132,40 @@ func (h *Handler) parseArchivedInboxFilters(w http.ResponseWriter, r *http.Reque// A cursor is tied to the recipient and filters, so it cannot accidentally// continue a different archive or a changed filter selection.-func archivedInboxScope(p db.ArchivedInboxFacetsParams, groupID pgtype.UUID) string {+func archivedInboxScope(p db.ArchivedInboxFacetsParams, groupID pgtype.UUID, notificationTypes []string) string {encoded, _ := json.Marshal(struct {- Filters db.ArchivedInboxFacetsParams- Group pgtype.UUID- }{p, groupID})+ Filters db.ArchivedInboxFacetsParams+ Group pgtype.UUID+ NotificationTypes []string `json:",omitempty"`+ }{p, groupID, notificationTypes})return fmt.Sprintf("%x", sha256.Sum256(encoded))}+// archivedInboxNotificationTypes reads the exact-type filter, which the CLI+// sends because it filters on one type rather than a type group.+func archivedInboxNotificationTypes(w http.ResponseWriter, r *http.Request) ([]string, bool) {+ types := []string{}+ raw := r.URL.Query().Get("notification_types")+ if raw == "" {+ return types, true+ }+ if len(raw) > 8192 {+ writeError(w, http.StatusBadRequest, "filter is too long")+ return nil, false+ }+ types = strings.Split(raw, ",")+ if len(types) > 100 {+ writeError(w, http.StatusBadRequest, "too many filter values")+ return nil, false+ }+ if slices.Contains(types, "") {+ writeError(w, http.StatusBadRequest, "empty filter value")+ return nil, false+ }+ slices.Sort(types)+ return slices.Compact(types), true+}+func (h *Handler) ListArchivedInboxPage(w http.ResponseWriter, r *http.Request) {r, cancel := h.inboxReadRequest(r)defer cancel()@@ -154,6 +180,10 @@ func (h *Handler) ListArchivedInboxPage(w http.ResponseWriter, r *http.Request)Assignees: filters.Assignees, Labels: filters.Labels, DueDates: filters.DueDates, Today: filters.Today,UnreadOnly: filters.UnreadOnly,}+ p.NotificationTypes, ok = archivedInboxNotificationTypes(w, r)+ if !ok {+ return+ }limit := 50if raw := r.URL.Query().Get("limit"); raw != "" {var err error@@ -169,7 +199,7 @@ func (h *Handler) ListArchivedInboxPage(w http.ResponseWriter, r *http.Request)return}}- scope := archivedInboxScope(filters, p.GroupID)+ scope := archivedInboxScope(filters, p.GroupID, p.NotificationTypes)if raw := r.URL.Query().Get("cursor"); raw != "" {if len(raw) > 2048 {writeError(w, http.StatusBadRequest, "invalid archive cursor")diff --git a/server/internal/handler/inbox_archive_test.go b/server/internal/handler/inbox_archive_test.goindex 88ee4115bb..5761a01e54 100644--- a/server/internal/handler/inbox_archive_test.go+++ b/server/internal/handler/inbox_archive_test.go@@ -99,6 +99,59 @@ func TestArchivedInboxMatchedNotificationKeepsItsCommentAnchor(t *testing.T) {}}+// An exact type, as the CLI filters, picks the group's newest notification of+// that type, even under a newer one of another type or of the same type group.+func TestArchivedInboxExactTypeMatchesBeforeGrouping(t *testing.T) {+ ws := dbfx.Workspace(t, "Archive exact types", "archive-exact-type-"+uuid.NewString())+ dbfx.Member(t, ws, testUserID, "owner")+ old := time.Now().UTC().Add(-time.Hour)+ insert := func(issue, kind string, created time.Time) string {+ return dbfx.Insert(t, "inbox_item", testutil.Cols{+ "workspace_id": ws, "recipient_type": "member", "recipient_id": testUserID,+ "type": kind, "severity": "info", "title": "Typed", "issue_id": issue,+ "archived": true, "created_at": created,+ })+ }+ mentioned := dbfx.Issue(t, "Mentioned, then changed", testutil.Cols{"workspace_id": ws})+ mention := insert(mentioned, "mentioned", old)+ insert(mentioned, "status_changed", old.Add(time.Minute))+ commented := dbfx.Issue(t, "Commented, then reacted", testutil.Cols{"workspace_id": ws})+ comment := insert(commented, "new_comment", old)+ insert(commented, "reaction_added", old.Add(time.Minute))+ get := func(query string) []string {+ var page archivedInboxPageResponse+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListArchivedInboxPage), inboxRequest(http.MethodGet, "/api/inbox/archived/page?"+query, ws)).Want(http.StatusOK).JSON(&page)+ ids := []string{}+ for _, item := range page.Items {+ ids = append(ids, item.ID)+ }+ return ids+ }+ for query, want := range map[string][]string{+ "notification_types=mentioned": {mention},+ "notification_types=mentioned&group_id=" + mentioned: {mention},+ "notification_types=new_comment": {comment},+ "notification_types=new_comment&group_id=" + commented: {comment},+ "notification_types=new_comment,mentioned": {comment, mention},+ "notification_types=issue_assigned": {},+ } {+ got := get(query)+ slices.Sort(got)+ slices.Sort(want)+ if !slices.Equal(got, want) {+ t.Errorf("%s = %v, want %v", query, got, want)+ }+ }+ var page archivedInboxPageResponse+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListArchivedInboxPage), inboxRequest(http.MethodGet, "/api/inbox/archived/page?limit=1", ws)).Want(http.StatusOK).JSON(&page)+ if page.NextCursor == nil {+ t.Fatal("two groups at limit=1 left no cursor")+ }+ for _, query := range []string{"notification_types=a,,b", "notification_types=mentioned&limit=1&cursor=" + url.QueryEscape(*page.NextCursor)} {+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListArchivedInboxPage), inboxRequest(http.MethodGet, "/api/inbox/archived/page?"+query, ws)).Want(http.StatusBadRequest)+ }+}+func TestArchivedInboxFiltersAndLookupUseLatestGroup(t *testing.T) {ws := dbfx.Workspace(t, "Archive filters", "archive-filter-"+uuid.NewString())dbfx.Member(t, ws, testUserID, "owner")diff --git a/server/internal/handler/inbox_snooze.go b/server/internal/handler/inbox_snooze.goindex 971e40b836..970df1f63d 100644--- a/server/internal/handler/inbox_snooze.go+++ b/server/internal/handler/inbox_snooze.go@@ -38,6 +38,9 @@ func (h *Handler) ListSnoozedInbox(w http.ResponseWriter, r *http.Request) {if !ok {return}+ if !h.requireInboxOwnerAccess(w, r, userID, wsUUID) {+ return+ }hidden, ok := h.requestInboxHiddenProjects(w, r, workspaceID)if !ok {return@@ -115,6 +118,7 @@ func (h *Handler) SnoozeInboxItem(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to snooze")return}+ logAgentInboxWrite(r, "snooze", "item_id", uuidToString(prev.ID), "issue_id", uuidToPtr(prev.IssueID), "snoozed_until", until.UTC().Format(time.RFC3339), "count", len(rows))h.publish(protocol.EventInboxSnoozed, uuidToString(prev.WorkspaceID), "member", requestUserID(r), map[string]any{"item_id": uuidToString(prev.ID),@@ -171,6 +175,7 @@ func (h *Handler) UnsnoozeInboxItem(w http.ResponseWriter, r *http.Request) {return}}+ logAgentInboxWrite(r, "unsnooze", "item_id", uuidToString(prev.ID), "issue_id", uuidToPtr(prev.IssueID), "count", len(rows))h.publish(protocol.EventInboxUnsnoozed, uuidToString(prev.WorkspaceID), "member", requestUserID(r), map[string]any{"item_id": uuidToString(prev.ID),diff --git a/server/internal/handler/inbox_write_access_test.go b/server/internal/handler/inbox_write_access_test.gonew file mode 100644index 0000000000..884cefc0c2--- /dev/null+++ b/server/internal/handler/inbox_write_access_test.go@@ -0,0 +1,222 @@+package handler++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/auth"+ "github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// Every inbox endpoint beyond the list reads, writes included, shares the+// list's owner gate: an agent acts on the runtime owner's inbox only when that+// owner triggered the task, and cloud-node credentials never do.+type inboxOwnerEndpoint struct {+ name, method string+ // path receives the inbox item and its issue; param names the chi URL+ // parameter the handler reads, if any.+ path func(item, issue string) string+ param string+ body map[string]any+ handler func(*Handler, http.ResponseWriter, *http.Request)+ // changes reports whether a successful call leaves the item read or archived.+ changes bool+}++var inboxOwnerEndpoints = []inboxOwnerEndpoint{+ {name: "read", method: http.MethodPost, path: func(item, _ string) string { return "/api/inbox/" + item + "/read" }, param: "id", handler: (*Handler).MarkInboxRead, changes: true},+ {name: "unread", method: http.MethodPost, path: func(item, _ string) string { return "/api/inbox/" + item + "/unread" }, param: "id", handler: (*Handler).MarkInboxUnread},+ {name: "archive", method: http.MethodPost, path: func(item, _ string) string { return "/api/inbox/" + item + "/archive" }, param: "id", handler: (*Handler).ArchiveInboxItem, changes: true},+ {name: "unarchive", method: http.MethodPost, path: func(item, _ string) string { return "/api/inbox/" + item + "/unarchive" }, param: "id", handler: (*Handler).UnarchiveInboxItem},+ {name: "snooze", method: http.MethodPost, path: func(item, _ string) string { return "/api/inbox/" + item + "/snooze" }, param: "id",+ body: map[string]any{"until": time.Now().Add(time.Hour).UTC().Format(time.RFC3339)}, handler: (*Handler).SnoozeInboxItem},+ {name: "unsnooze", method: http.MethodPost, path: func(item, _ string) string { return "/api/inbox/" + item + "/unsnooze" }, param: "id", handler: (*Handler).UnsnoozeInboxItem},+ {name: "read issue", method: http.MethodPost, path: func(_, issue string) string { return "/api/inbox/issues/" + issue + "/read" }, param: "issueId", handler: (*Handler).MarkIssueInboxRead, changes: true},+ {name: "mark all read", method: http.MethodPost, path: func(_, _ string) string { return "/api/inbox/mark-all-read" }, handler: (*Handler).MarkAllInboxRead, changes: true},+ {name: "archive all", method: http.MethodPost, path: func(_, _ string) string { return "/api/inbox/archive-all" }, handler: (*Handler).ArchiveAllInbox, changes: true},+ {name: "archive all read", method: http.MethodPost, path: func(_, _ string) string { return "/api/inbox/archive-all-read" }, handler: (*Handler).ArchiveAllReadInbox},+ {name: "archive completed", method: http.MethodPost, path: func(_, _ string) string { return "/api/inbox/archive-completed" }, handler: (*Handler).ArchiveCompletedInbox},+ {name: "unread count", method: http.MethodGet, path: func(_, _ string) string { return "/api/inbox/unread-count" }, handler: (*Handler).CountUnreadInbox},+ {name: "unread summary", method: http.MethodGet, path: func(_, _ string) string { return "/api/inbox/unread-summary" }, handler: (*Handler).UnreadInboxSummary},+ {name: "snoozed", method: http.MethodGet, path: func(_, _ string) string { return "/api/inbox/snoozed" }, handler: (*Handler).ListSnoozedInbox},+}++type inboxWriteFixture struct {+ workspaceID, issueID, runtimeID, agentID string+}++func newInboxWriteFixture(t *testing.T) inboxWriteFixture {+ t.Helper()+ workspaceID := dbfx.Workspace(t, "Inbox writes", "inbox-writes-"+uuid.NewString())+ dbfx.Member(t, workspaceID, testUserID, "owner")+ dbfx.Cleanup(t, `DELETE FROM inbox_item WHERE workspace_id = $1`, workspaceID)+ runtimeID := dbfx.Runtime(t, "Inbox write runtime", testutil.Cols{"workspace_id": workspaceID})+ return inboxWriteFixture{+ workspaceID: workspaceID,+ issueID: dbfx.Issue(t, "Inbox write issue", testutil.Cols{"workspace_id": workspaceID}),+ runtimeID: runtimeID,+ agentID: dbfx.Agent(t, "Inbox write agent", runtimeID, testutil.Cols{"workspace_id": workspaceID}),+ }+}++func (f inboxWriteFixture) item(t *testing.T) string {+ t.Helper()+ return dbfx.Insert(t, "inbox_item", testutil.Cols{"workspace_id": f.workspaceID, "issue_id": f.issueID,+ "recipient_type": "member", "recipient_id": testUserID, "type": "new_comment", "severity": "info", "title": "Owner notice"})+}++func (f inboxWriteFixture) taskToken(t *testing.T, originator any) string {+ t.Helper()+ accountable := originator+ if accountable == nil {+ accountable = testUserID+ }+ taskID := dbfx.Task(t, f.agentID, testutil.Cols{"runtime_id": f.runtimeID, "status": "running",+ "originator_user_id": originator, "accountable_user_id": accountable})+ return inboxTaskCredential(t, taskID, f.agentID, f.workspaceID, testUserID)+}++func serveInboxEndpoint(handler func(*Handler, http.ResponseWriter, *http.Request), cloud *auth.CloudPATVerifier) http.HandlerFunc {+ return middleware.Auth(testHandler.Queries, nil, cloud, nil)(+ middleware.RequireWorkspaceMember(testHandler.Queries)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler(testHandler, w, r)+ })),+ ).ServeHTTP+}++func (e inboxOwnerEndpoint) request(f inboxWriteFixture, item, token string, headers ...string) *http.Request {+ var body any+ if e.body != nil {+ body = e.body+ }+ req := testutil.WithHeaders(testutil.JSONRequest(e.method, e.path(item, f.issueID), body),+ append([]string{"Authorization", "Bearer " + token, "X-Workspace-ID", f.workspaceID}, headers...)...)+ switch e.param {+ case "id":+ req = withURLParam(req, "id", item)+ case "issueId":+ req = withURLParam(req, "issueId", f.issueID)+ }+ return req+}++func requireInboxItemUntouched(t *testing.T, item string) {+ t.Helper()+ if state := loadInboxItemState(t, item); state != (inboxItemState{}) {+ t.Fatalf("denied call changed the owner's notification: %+v", state)+ }+ var snoozed bool+ dbfx.QueryRow(t, `SELECT snoozed_until IS NOT NULL FROM inbox_item WHERE id = $1`, item).Scan(&snoozed)+ if snoozed {+ t.Fatal("denied call snoozed the owner's notification")+ }+}++func TestInboxEndpointsShareOwnerGate(t *testing.T) {+ f := newInboxWriteFixture(t)+ other := createPlainMember(t, "inbox-write-other-"+uuid.NewString()+"@example.test")+ allowed := f.taskToken(t, testUserID)+ foreignTriggered := f.taskToken(t, other)+ unattributed := f.taskToken(t, nil)+ for _, e := range inboxOwnerEndpoints {+ t.Run(e.name, func(t *testing.T) {+ for name, token := range map[string]string{"another human": foreignTriggered, "unattributed": unattributed} {+ t.Run(name, func(t *testing.T) {+ item := f.item(t)+ testutil.Call(t, serveInboxEndpoint(e.handler, nil), e.request(f, item, token)).Want(http.StatusForbidden)+ requireInboxItemUntouched(t, item)+ })+ }++ item := f.item(t)+ testutil.Call(t, serveInboxEndpoint(e.handler, nil), e.request(f, item, allowed)).Want(http.StatusOK)+ if changed := loadInboxItemState(t, item) != (inboxItemState{}); changed != e.changes {+ t.Fatalf("self-triggered call changed=%v, want %v", changed, e.changes)+ }+ })+ }+}++func TestInboxEndpointsRejectCloudPAT(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})+ f := newInboxWriteFixture(t)+ taskID := dbfx.Task(t, f.agentID, testutil.Cols{"runtime_id": f.runtimeID, "status": "running",+ "originator_user_id": testUserID, "accountable_user_id": testUserID})+ for _, e := range inboxOwnerEndpoints {+ t.Run(e.name, func(t *testing.T) {+ item := f.item(t)+ req := e.request(f, item, "mcn_inbox-write-test", "X-Actor-Source", "task_token", "X-Task-ID", taskID, "X-Agent-ID", f.agentID)+ testutil.Call(t, serveInboxEndpoint(e.handler, verifier), req).Want(http.StatusForbidden)+ requireInboxItemUntouched(t, item)+ })+ }+}++// Per-item writes report how many notifications they actually changed, the+// issue group included, so repeating one reports 0.+func TestInboxItemWritesReportChangedCount(t *testing.T) {+ f := newInboxWriteFixture(t)+ token := f.taskToken(t, testUserID)+ endpoint := func(name string) inboxOwnerEndpoint {+ for _, e := range inboxOwnerEndpoints {+ if e.name == name {+ return e+ }+ }+ t.Fatalf("no endpoint %q", name)+ return inboxOwnerEndpoint{}+ }+ items := []string{f.item(t), f.item(t), f.item(t)}+ dbfx.Exec(t, `UPDATE inbox_item SET read = true WHERE id = $1`, items[2])+ for _, step := range []struct {+ action string+ item string+ want int64+ }{+ {"read", items[0], 2},+ {"read", items[1], 0},+ {"unread", items[0], 1},+ {"unread", items[0], 0},+ {"archive", items[1], 3},+ {"archive", items[0], 0},+ {"unarchive", items[2], 3},+ {"unarchive", items[2], 0},+ } {+ e := endpoint(step.action)+ var resp struct {+ ID string `json:"id"`+ Count *int64 `json:"count"`+ }+ testutil.Call(t, serveInboxEndpoint(e.handler, nil), e.request(f, step.item, token)).Want(http.StatusOK).JSON(&resp)+ if resp.ID != step.item || resp.Count == nil || *resp.Count != step.want {+ t.Fatalf("%s %s: id=%s count=%v, want %d", step.action, step.item, resp.ID, resp.Count, step.want)+ }+ }+}++func TestDeleteInboxItemIsHumanOnly(t *testing.T) {+ f := newInboxWriteFixture(t)+ endpoint := inboxOwnerEndpoint{method: http.MethodDelete, path: func(item, _ string) string { return "/api/inbox/" + item }, param: "id"}++ item := f.item(t)+ testutil.Call(t, serveInboxEndpoint((*Handler).DeleteInboxItem, nil), endpoint.request(f, item, f.taskToken(t, testUserID))).Want(http.StatusForbidden)+ requireInboxItemUntouched(t, item)++ pat := "mul_" + uuid.NewString()+ dbfx.Insert(t, "personal_access_token", testutil.Cols{"user_id": testUserID, "name": "Inbox delete test", "token_hash": auth.HashToken(pat), "token_prefix": pat[:12]})+ testutil.Call(t, serveInboxEndpoint((*Handler).DeleteInboxItem, nil), endpoint.request(f, item, pat)).Want(http.StatusOK)+ var remaining int+ dbfx.QueryRow(t, `SELECT count(*) FROM inbox_item WHERE id = $1`, item).Scan(&remaining)+ if remaining != 0 {+ t.Fatal("human delete left the notification in place")+ }+}diff --git a/server/internal/service/builtin_skills/multica-platform/SKILL.md b/server/internal/service/builtin_skills/multica-platform/SKILL.mdindex 912afe4288..d922d300bf 100644--- a/server/internal/service/builtin_skills/multica-platform/SKILL.md+++ b/server/internal/service/builtin_skills/multica-platform/SKILL.md@@ -1,6 +1,6 @@---name: multica-platform-description: "Use for Multica actions the runtime brief does not fully cover: issue and PR contracts, sub-issues, batch changes, saved views, charts and files in comments, mentions, agents, squads, autopilots, projects, runtimes, local environments, skill import, themes. Not for product code you are working on."+description: "Use for Multica actions the runtime brief does not fully cover: issue and PR contracts, sub-issues, batch changes, saved views, comment charts and files, mentions, inbox, agents, squads, autopilots, projects, runtimes, local environments, skill import, themes. Not for product code you are editing."user-invocable: falseallowed-tools: Bash(multica *), Bash(git *), Bash(gh *)---@@ -31,13 +31,14 @@ Read the invariants below, then open the reference(s) your task actually needs| `references/environments.md` | Local environments in the issue sidebar: writing `.multica/environments.toml`, `multica env start` / `stop` / `list`, detected servers || `references/skill-import.md` | Importing a skill into this workspace from a URL or a local archive || `references/themes.md` | Building or changing a Multica app theme: the format, the checker, delivering to Desktop's themes folder or as a `.zip` |+| `references/inbox.md` | Going through the runtime owner's inbox for them: listing unread notifications, marking read or unread, archiving, snoozing, bulk clean-up (`multica inbox`) |Open what the task needs. A single-domain task usually needs one; a task thatcrosses domains needs each domain it touches — creating a squad, assigning it anissue, then writing a mention needs `squads.md`, `issues.md` and `mentions.md`,and skipping one of those means acting on a contract you have not read.-What is never right is reading all eleven because you are not sure. Each+What is never right is reading all of them because you are not sure. Eachreference states its own contracts in full and none depends on another, sopick by domain and skip the rest.diff --git a/server/internal/service/builtin_skills/multica-platform/references/inbox.md b/server/internal/service/builtin_skills/multica-platform/references/inbox.mdnew file mode 100644index 0000000000..4747e56abb--- /dev/null+++ b/server/internal/service/builtin_skills/multica-platform/references/inbox.md@@ -0,0 +1,96 @@+# Inbox++The inbox holds a workspace member's notifications: assignments, mentions,+comments, status changes, failed runs. `multica inbox` reads and changes the+same inbox the app shows, so every change appears in the member's open+windows right away.++## Whose inbox, and when++A task acts on the **runtime owner's** inbox, never anyone else's; no flag+selects another person. The server allows it only while the task is running+and its verified upstream human, the person who triggered it directly or+through a delegation chain, is that owner. A run someone else triggered, a+run without a verifiable human, and cloud-node credentials are refused with+`403` on every inbox command, reads included. That refusal is final for this+run: do not retry with another credential. Tell the person the inbox is only+available in runs they start themselves.++Notifications cannot be deleted from the CLI, and the server refuses deletion+from agent credentials. Archive instead; it is reversible.++## Read first++```bash+multica inbox count --output json # unread here and per workspace+multica inbox list --unread --output json # active notifications+multica inbox list --since 1d --issue MUL-123 --output json+multica inbox list --archived --output json # archived instead+multica inbox list --snoozed --output json # snoozed issues instead+```++Each row has the notification `id` (the handle every write takes), `type`,+`title`, `issue_id`, `issue_identifier` (MUL-123), `actor` (`member:Name` or+`agent:Name`), `summary` (the comment or change, shortened), `comment_id`+when it points at a comment, `read` and `created_at`. Listing never changes+read state. `issue_identifier` and `actor` stay empty when their lookup fails;+the row is still valid.++The active list has one row per notification, while the app shows one row per+issue, so several rows can share an issue. The archived list has one row per+issue and is read page by page to the end, so an issue archived long ago is+still found by `--issue`.++## Change++```bash+multica inbox read <id>... # and the rest of each issue+multica inbox read --issue MUL-123 # every notification on one issue+multica inbox unread <id>... # only that notification+multica inbox archive <id>... # and the rest of each issue+multica inbox unarchive <id>...+multica inbox snooze <id>... --until 3h # RFC 3339, 30m, 3h, 1d, 1w, tomorrow+multica inbox unsnooze <id>...+```++Ids must be full UUIDs from `list --output json`. Every id is checked before+the first request; after that, a failure on one id does not stop the others.+The JSON result lists `items` that succeeded, each with its own `count`, and+`failed` with each server error; the command exits non-zero when any failed.+Reading or archiving one notification also reads or archives every other+notification on its issue, as opening or archiving it in the app does. So+`count` is the number of notifications actually changed, whole issues+included: a second id on an issue already handled, or a change already in+place, counts 0.++Snoozing takes the whole issue out of the inbox until the time. It comes back+early when someone mentions the owner by name, assigns it to them, a run+fails, an app asks for their action, or all its sub-issues finish. A day or more chosen between 22:00 and+6:00 comes back at 9:00, as in the app.++## Bulk changes++```bash+multica inbox read --all --yes # mark everything read+multica inbox archive --read --yes # issues whose newest notification is read+multica inbox archive --completed --yes # issues in a done or closed status+multica inbox archive --all --yes # everything+```++Without `--yes` they ask for confirmation, and a run, which cannot answer,+fails without changing anything. `count` is the number of notifications the+server changed. `read --all`, `archive --all` and `archive --read` leave+snoozed issues alone; `archive --completed` also archives a done or closed+issue while it is snoozed and ends that snooze, as in the app.++Only run a bulk change when the person asked for that sweep. To clear what+you judged handled, pass those ids; `--all` also takes notifications that+arrived after you listed.++## Going through the inbox for someone++1. `inbox list --unread --output json`, then read the issues that matter.+2. Decide per notification, and say what you decided: handled (`read` or+ `archive`), later (`snooze` or `unread`), needs them (leave it).+3. Apply with the ids, then `inbox list --unread` again to confirm.+4. Report counts and what you left for them, by issue key.diff --git a/server/internal/service/builtin_skills_test.go b/server/internal/service/builtin_skills_test.goindex 234e684c1b..525d999381 100644--- a/server/internal/service/builtin_skills_test.go+++ b/server/internal/service/builtin_skills_test.go@@ -364,6 +364,7 @@ func TestPlatformSkillDescriptionNamesEveryDomain(t *testing.T) {"references/environments.md": "local environment","references/skill-import.md": "skill import","references/themes.md": "theme",+ "references/inbox.md": "inbox",}skill, ok := findSkill(t, PlatformSkillName)@@ -439,6 +440,7 @@ func TestPlatformSkillCoversPlatformContracts(t *testing.T) {"references/environments.md","references/skill-import.md","references/themes.md",+ "references/inbox.md",// Invariants deduplicated out of the eight merged bodies. Each// was repeated in most of them; the router is now their only// home, so losing one here loses it everywhere.@@ -735,6 +737,21 @@ func TestPlatformSkillCoversPlatformContracts(t *testing.T) {"multica attachment upload <path>",},},+ {+ // MUL-9549: an agent manages only its triggering owner's inbox,+ // cannot delete, and bulk sweeps need explicit confirmation.+ file: "references/inbox.md",+ want: []string{+ "**runtime owner's** inbox",+ "do not retry with another credential",+ "Notifications cannot be deleted from the CLI",+ "multica inbox list --unread --output json",+ "multica inbox read --issue MUL-123",+ "multica inbox snooze <id>... --until 3h",+ "multica inbox read --all --yes",+ "Only run a bulk change when the person asked for that sweep",+ },+ },{file: "references/skill-import.md",want: []string{diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.goindex 9500f90c49..e1eda87dac 100644--- a/server/pkg/db/generated/inbox.sql.go+++ b/server/pkg/db/generated/inbox.sql.go@@ -871,12 +871,18 @@ WITH target AS (AND s.issue_id = target.issue_idAND s.archived = false AND s.read = falseAND s.id <> $1+ RETURNING s.id)UPDATE inbox_item AS item SET read = trueWHERE item.id = $1-RETURNING item.id, item.workspace_id, item.recipient_type, item.recipient_id, item.type, item.severity, item.issue_id, item.title, item.body, item.read, item.archived, item.created_at, item.actor_type, item.actor_id, item.details, item.section, item.snoozed_until, item.snoozed_at+RETURNING item.id, item.workspace_id, item.recipient_type, item.recipient_id, item.type, item.severity, item.issue_id, item.title, item.body, item.read, item.archived, item.created_at, item.actor_type, item.actor_id, item.details, item.section, item.snoozed_until, item.snoozed_at, (SELECT count(*) FROM siblings)::bigint AS siblings_read`+type MarkInboxReadRow struct {+ InboxItem InboxItem `json:"inbox_item"`+ SiblingsRead int64 `json:"siblings_read"`+}+// Opening a row in the inbox opens its issue, so it reads every active unread// row on that issue, not just the one shown (MUL-8618). The inbox renders one// row per issue carrying its newest item; reading only that item left older@@ -885,29 +891,30 @@ RETURNING item.id, item.workspace_id, item.recipient_type, item.recipient_id, it// opened outside the inbox. The item itself is read whether or not it is// archived; its siblings only while active, as in MarkInboxReadByIssue, which// keeps the probe on the partial index idx_inbox_active_by_issue. Items without-// an issue are their own group.-func (q *Queries) MarkInboxRead(ctx context.Context, id pgtype.UUID) (InboxItem, error) {+// an issue are their own group. siblings_read is how many other rows it read.+func (q *Queries) MarkInboxRead(ctx context.Context, id pgtype.UUID) (MarkInboxReadRow, error) {row := q.db.QueryRow(ctx, markInboxRead, id)- var i InboxItem+ var i MarkInboxReadRowerr := row.Scan(- &i.ID,- &i.WorkspaceID,- &i.RecipientType,- &i.RecipientID,- &i.Type,- &i.Severity,- &i.IssueID,- &i.Title,- &i.Body,- &i.Read,- &i.Archived,- &i.CreatedAt,- &i.ActorType,- &i.ActorID,- &i.Details,- &i.Section,- &i.SnoozedUntil,- &i.SnoozedAt,+ &i.InboxItem.ID,+ &i.InboxItem.WorkspaceID,+ &i.InboxItem.RecipientType,+ &i.InboxItem.RecipientID,+ &i.InboxItem.Type,+ &i.InboxItem.Severity,+ &i.InboxItem.IssueID,+ &i.InboxItem.Title,+ &i.InboxItem.Body,+ &i.InboxItem.Read,+ &i.InboxItem.Archived,+ &i.InboxItem.CreatedAt,+ &i.InboxItem.ActorType,+ &i.InboxItem.ActorID,+ &i.InboxItem.Details,+ &i.InboxItem.Section,+ &i.InboxItem.SnoozedUntil,+ &i.InboxItem.SnoozedAt,+ &i.SiblingsRead,)return i, err}diff --git a/server/pkg/db/generated/inbox_archive.sql.go b/server/pkg/db/generated/inbox_archive.sql.goindex c81fa2596f..228cbaabbb 100644--- a/server/pkg/db/generated/inbox_archive.sql.go+++ b/server/pkg/db/generated/inbox_archive.sql.go@@ -208,7 +208,7 @@ func (q *Queries) ArchivedInboxFacets(ctx context.Context, arg ArchivedInboxFaceconst listArchivedInboxPage = `-- name: ListArchivedInboxPage :manyWITH base AS MATERIALIZED (- SELECT i.id, i.issue_id, COALESCE(i.issue_id, i.id) AS group_id, i.created_at, i.read,+ SELECT i.id, i.issue_id, COALESCE(i.issue_id, i.id) AS group_id, i.created_at, i.read, i.type,CASEWHEN i.type = 'mentioned' THEN 'mention'WHEN i.type IN ('new_comment', 'reaction_added') THEN 'comment'@@ -241,13 +241,14 @@ WITH base AS MATERIALIZED (AND active.issue_id = i.issue_id AND active.archived = false))), newest AS (- SELECT DISTINCT ON (group_id) base.id, base.issue_id, base.group_id, base.created_at, base.read, base.type_group, base.actor+ SELECT DISTINCT ON (group_id) base.id, base.issue_id, base.group_id, base.created_at, base.read, base.type, base.type_group, base.actorFROM baseWHERE (cardinality($5::text[]) = 0OR (type_group = ANY($5::text[])) <> ('type' = ANY($6::text[])))- AND (cardinality($7::text[]) = 0- OR COALESCE(actor = ANY($7::text[]), false) <> ('actor' = ANY($6::text[])))- AND ($8::timestamptz IS NULL OR created_at >= $8::timestamptz)+ AND (cardinality($7::text[]) = 0 OR type = ANY($7::text[]))+ AND (cardinality($8::text[]) = 0+ OR COALESCE(actor = ANY($8::text[]), false) <> ('actor' = ANY($6::text[])))+ AND ($9::timestamptz IS NULL OR created_at >= $9::timestamptz)ORDER BY group_id, created_at DESC, id DESC), projected AS (SELECT newest.id, newest.created_at, newest.read,@@ -264,31 +265,31 @@ WITH base AS MATERIALIZED (), selected AS (SELECT projected.id, projected.created_at, projected.issue_status, projected.issue_priorityFROM projected- WHERE (cardinality($9::text[]) = 0 OR (issue_ref IS NOT NULL- AND (issue_status = ANY($9::text[])) <> ('status' = ANY($6::text[]))))- AND (cardinality($10::text[]) = 0 OR (issue_ref IS NOT NULL- AND (issue_priority = ANY($10::text[])) <> ('priority' = ANY($6::text[]))))+ WHERE (cardinality($10::text[]) = 0 OR (issue_ref IS NOT NULL+ AND (issue_status = ANY($10::text[])) <> ('status' = ANY($6::text[]))))AND (cardinality($11::text[]) = 0 OR (issue_ref IS NOT NULL- AND (project_key = ANY($11::text[])) <> ('project' = ANY($6::text[]))))+ AND (issue_priority = ANY($11::text[])) <> ('priority' = ANY($6::text[]))))AND (cardinality($12::text[]) = 0 OR (issue_ref IS NOT NULL- AND (assignee_key = ANY($12::text[])) <> ('assignee' = ANY($6::text[]))))+ AND (project_key = ANY($12::text[])) <> ('project' = ANY($6::text[]))))AND (cardinality($13::text[]) = 0 OR (issue_ref IS NOT NULL- AND (label_ids && $13::text[]) <> ('label' = ANY($6::text[]))))- AND (cardinality($14::text[]) = 0 OR (issue_ref IS NOT NULL AND COALESCE(- ('overdue' = ANY($14::text[]) AND due_date < $15::date)- OR ('today' = ANY($14::text[]) AND due_date = $15::date)- OR ('this_week' = ANY($14::text[])- AND due_date >= $15::date - (EXTRACT(ISODOW FROM $15::date)::int - 1)- AND due_date < $15::date - (EXTRACT(ISODOW FROM $15::date)::int - 1) + 7)- OR ('next_7_days' = ANY($14::text[])- AND due_date >= $15::date AND due_date < $15::date + 7)- OR ('none' = ANY($14::text[]) AND due_date IS NULL), false)+ AND (assignee_key = ANY($13::text[])) <> ('assignee' = ANY($6::text[]))))+ AND (cardinality($14::text[]) = 0 OR (issue_ref IS NOT NULL+ AND (label_ids && $14::text[]) <> ('label' = ANY($6::text[]))))+ AND (cardinality($15::text[]) = 0 OR (issue_ref IS NOT NULL AND COALESCE(+ ('overdue' = ANY($15::text[]) AND due_date < $16::date)+ OR ('today' = ANY($15::text[]) AND due_date = $16::date)+ OR ('this_week' = ANY($15::text[])+ AND due_date >= $16::date - (EXTRACT(ISODOW FROM $16::date)::int - 1)+ AND due_date < $16::date - (EXTRACT(ISODOW FROM $16::date)::int - 1) + 7)+ OR ('next_7_days' = ANY($15::text[])+ AND due_date >= $16::date AND due_date < $16::date + 7)+ OR ('none' = ANY($15::text[]) AND due_date IS NULL), false)<> ('dueDate' = ANY($6::text[]))))- AND (NOT $16::boolean OR NOT read)- AND ($17::timestamptz IS NULL OR- (created_at, id) < ($17::timestamptz, $18::uuid))+ AND (NOT $17::boolean OR NOT read)+ AND ($18::timestamptz IS NULL OR+ (created_at, id) < ($18::timestamptz, $19::uuid))ORDER BY created_at DESC, id DESC- LIMIT $19::int+ LIMIT $20::int)SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section, i.snoozed_until, i.snoozed_at, selected.issue_status, selected.issue_priority,iss.number AS issue_number,@@ -319,25 +320,26 @@ ORDER BY i.created_at DESC, i.id DESC`type ListArchivedInboxPageParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- RecipientID pgtype.UUID `json:"recipient_id"`- HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`- GroupID pgtype.UUID `json:"group_id"`- Types []string `json:"types"`- Negated []string `json:"negated"`- Actors []string `json:"actors"`- ReceivedAfter pgtype.Timestamptz `json:"received_after"`- Statuses []string `json:"statuses"`- Priorities []string `json:"priorities"`- Projects []string `json:"projects"`- Assignees []string `json:"assignees"`- Labels []string `json:"labels"`- DueDates []string `json:"due_dates"`- Today pgtype.Date `json:"today"`- UnreadOnly bool `json:"unread_only"`- BeforeTime pgtype.Timestamptz `json:"before_time"`- BeforeID pgtype.UUID `json:"before_id"`- PageLimit int32 `json:"page_limit"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`+ GroupID pgtype.UUID `json:"group_id"`+ Types []string `json:"types"`+ Negated []string `json:"negated"`+ NotificationTypes []string `json:"notification_types"`+ Actors []string `json:"actors"`+ ReceivedAfter pgtype.Timestamptz `json:"received_after"`+ Statuses []string `json:"statuses"`+ Priorities []string `json:"priorities"`+ Projects []string `json:"projects"`+ Assignees []string `json:"assignees"`+ Labels []string `json:"labels"`+ DueDates []string `json:"due_dates"`+ Today pgtype.Date `json:"today"`+ UnreadOnly bool `json:"unread_only"`+ BeforeTime pgtype.Timestamptz `json:"before_time"`+ BeforeID pgtype.UUID `json:"before_id"`+ PageLimit int32 `json:"page_limit"`}type ListArchivedInboxPageRow struct {@@ -361,6 +363,8 @@ type ListArchivedInboxPageRow struct {// review_requested, task_completed, agent_blocked and agent_completed are no// longer written, but archived rows from older servers still carry them.// Select narrow group representatives before loading bodies or comment anchors.+// notification_types matches exact types, for callers such as the CLI that+// filter by one type rather than a type group.func (q *Queries) ListArchivedInboxPage(ctx context.Context, arg ListArchivedInboxPageParams) ([]ListArchivedInboxPageRow, error) {rows, err := q.db.Query(ctx, listArchivedInboxPage,arg.WorkspaceID,@@ -369,6 +373,7 @@ func (q *Queries) ListArchivedInboxPage(ctx context.Context, arg ListArchivedInbarg.GroupID,arg.Types,arg.Negated,+ arg.NotificationTypes,arg.Actors,arg.ReceivedAfter,arg.Statuses,diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sqlindex 0c57ee3f71..5abdecbabc 100644--- a/server/pkg/db/queries/inbox.sql+++ b/server/pkg/db/queries/inbox.sql@@ -168,7 +168,7 @@ RETURNING *;-- opened outside the inbox. The item itself is read whether or not it is-- archived; its siblings only while active, as in MarkInboxReadByIssue, which-- keeps the probe on the partial index idx_inbox_active_by_issue. Items without--- an issue are their own group.+-- an issue are their own group. siblings_read is how many other rows it read.WITH target AS (SELECT t.workspace_id, t.recipient_type, t.recipient_id, t.issue_idFROM inbox_item t@@ -182,10 +182,11 @@ WITH target AS (AND s.issue_id = target.issue_idAND s.archived = false AND s.read = falseAND s.id <> $1+ RETURNING s.id)UPDATE inbox_item AS item SET read = trueWHERE item.id = $1-RETURNING item.*;+RETURNING sqlc.embed(item), (SELECT count(*) FROM siblings)::bigint AS siblings_read;-- name: MarkInboxUnread :one-- Item-level, unlike MarkInboxRead: the inbox renders one row per issuediff --git a/server/pkg/db/queries/inbox_archive.sql b/server/pkg/db/queries/inbox_archive.sqlindex 6d91c05625..cbfd6bc9a8 100644--- a/server/pkg/db/queries/inbox_archive.sql+++ b/server/pkg/db/queries/inbox_archive.sql@@ -8,8 +8,10 @@-- name: ListArchivedInboxPage :many-- Select narrow group representatives before loading bodies or comment anchors.+-- notification_types matches exact types, for callers such as the CLI that+-- filter by one type rather than a type group.WITH base AS MATERIALIZED (- SELECT i.id, i.issue_id, COALESCE(i.issue_id, i.id) AS group_id, i.created_at, i.read,+ SELECT i.id, i.issue_id, COALESCE(i.issue_id, i.id) AS group_id, i.created_at, i.read, i.type,CASEWHEN i.type = 'mentioned' THEN 'mention'WHEN i.type IN ('new_comment', 'reaction_added') THEN 'comment'@@ -46,6 +48,7 @@ WITH base AS MATERIALIZED (FROM baseWHERE (cardinality(sqlc.arg(types)::text[]) = 0OR (type_group = ANY(sqlc.arg(types)::text[])) <> ('type' = ANY(sqlc.arg(negated)::text[])))+ AND (cardinality(sqlc.arg(notification_types)::text[]) = 0 OR type = ANY(sqlc.arg(notification_types)::text[]))AND (cardinality(sqlc.arg(actors)::text[]) = 0OR COALESCE(actor = ANY(sqlc.arg(actors)::text[]), false) <> ('actor' = ANY(sqlc.arg(negated)::text[])))AND (sqlc.narg(received_after)::timestamptz IS NULL OR created_at >= sqlc.narg(received_after)::timestamptz)