Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9215: feat(inbox): list issues by whose turn it is, with snooze (#10573)
Jiayuan Zhang0a89348c8ee5
diff --git a/apps/docs/content/docs/inbox.fr.mdx b/apps/docs/content/docs/inbox.fr.mdxindex 90b450015a..9f6b4c1dd1 100644--- a/apps/docs/content/docs/inbox.fr.mdx+++ b/apps/docs/content/docs/inbox.fr.mdx@@ -44,37 +44,59 @@ La boîte de réception est réservée aux membres de l'espace de travail. Même@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.+## Sections++La boîte de réception affiche chaque tâche une seule fois, selon la personne dont c'est le tour :++- **À traiter** — la tâche vous attend. Vous avez été @mentionné ou assigné, une exécution d'agent que vous avez lancée s'est terminée, a échoué ou a été annulée, ou il s'est passé quelque chose sur une tâche que vous avez créée ou qui vous est assignée : un nouveau commentaire, une exécution en échec, ou un statut qui attend une personne, comme `in_review` ou `blocked`. Chaque ligne en donne la raison, par exemple **À valider**, **Attend votre réponse** ou **Exécution en échec**.+- **En cours** — un agent travaille sur la tâche à votre demande : vous l'avez assignée, commentée ou relancée. La ligne indique l'agent et la durée de l'exécution, ou **En file d'attente**. Les exécutions que vous n'avez pas lancées vous-même, par exemple celles d'une automatisation ou d'un autre membre, n'y figurent pas.+- **Mises à jour** — tout le reste : l'activité des tâches auxquelles vous êtes abonné et qui n'attend rien de vous. Seules les mises à jour non lues y figurent ; une fois lue, une mise à jour passe dans **Archivées**.+- **Reportées** — les tâches que vous avez mises de côté jusqu'à plus tard.++Une tâche qui correspond à plusieurs sections apparaît dans la première, dans l'ordre ci-dessus. **Mises à jour** et **Reportées** restent repliées tant que vous ne les ouvrez pas ; chaque en-tête indique le nombre de tâches qu'elle contient.++Le badge de la boîte de réception compte les tâches de la section **À traiter**. Lire une tâche ne la retire pas du compteur : elle y reste jusqu'à ce que vous la confiiez à un agent, la reportiez ou l'archiviez.++Quand votre commentaire ou votre assignation lance une exécution d'agent, la tâche quitte **À traiter** et s'affiche dans **En cours**. Quand l'exécution se termine, échoue ou est annulée, elle revient dans **À traiter**, sauf si la tâche est déjà clôturée.++Une exécution annulée revient avec la mention **Exécution annulée**. Si vous l'avez arrêtée vous-même, la ligne est déjà lue et indique **Vous avez arrêté cette exécution** ; si quelqu'un d'autre l'a arrêtée, elle est non lue et nomme cette personne. Elle ne revient pas tant qu'une autre exécution que vous avez lancée est active sur la tâche, par exemple après une relance : la tâche reste dans **En cours**.+## Traiter les notifications-Sélectionner une notification la marque comme lue. Archivez-la quand vous avez terminé ; l'archivage ne modifie ni ne supprime la tâche correspondante.+Sélectionner une notification la marque comme lue. Dans **À traiter**, lire n'est pas traiter : la ligne reste jusqu'à ce que vous agissiez sur la tâche. Archivez-la quand vous avez terminé, avec **Archiver** dans l'en-tête de la tâche ouverte ou avec `E` ; l'archivage ne modifie ni ne supprime la tâche correspondante.<InboxDemo />Dès qu'une tâche atteint un statut qui la rend à une personne, ses notifications « Exécution en échec » sont archivées automatiquement. Ces statuts sont `in_review`, les statuts personnalisés de la catégorie `started` et tous les statuts des catégories `done` et `closed`. `blocked` fait exception : il rend aussi la tâche, mais le travail reste bloqué, donc les échecs précédents méritent encore d'être lus.-Faites un clic droit sur une notification pour **Marquer comme lu** / **Marquer comme non lu** et **Archiver** (**Désarchiver** dans la vue Archivées). Marquer comme non lu est l'action « j'ai regardé, mais je n'en ai pas fini » : la notification redevient non lue et fait remonter le compteur de non-lus, et elle reste non lue même tant que vous la gardez ouverte ; la rouvrir plus tard la marque comme lue, comme d'habitude. Les notifications archivées conservent leur état de lecture : en restaurer une la rétablit exactement comme vous l'aviez laissée.+Une tâche qui passe à un statut des catégories `done` ou `closed` quitte la boîte de réception de tout le monde ; il n'en reste qu'une entrée dans **Mises à jour** indiquant qu'elle est clôturée.-Depuis le menu de la boîte de réception, vous pouvez aussi :+Faites un clic droit sur une notification pour **Marquer comme lu** / **Marquer comme non lu**, le report et **Archiver** (**Désarchiver** dans la vue Archivées). Marquer comme non lu est l'action « j'ai regardé, mais je n'en ai pas fini » : la notification redevient non lue, et elle reste non lue même tant que vous la gardez ouverte ; la rouvrir plus tard la marque comme lue, comme d'habitude. Les notifications archivées conservent leur état de lecture : en restaurer une la rétablit exactement comme vous l'aviez laissée. Une mise à jour fait exception : elle revient non lue, car une mise à jour lue repartirait aussitôt. **Supprimer** retire définitivement une notification et n'est proposé que dans la vue Archivées.-- tout marquer comme lu ;-- tout archiver, ou archiver tout ce qui est lu ;-- archiver les notifications des tâches en `done` ou `cancelled` ;-- ouvrir Archivées et restaurer une notification.+Dans **Mises à jour**, lire, c'est traiter : ouvrez-en une, et elle passe dans **Archivées** dès que vous passez à autre chose. **Effacer**, sur l'en-tête de la section, archive toutes les mises à jour affichées, lues ou non. Rien ne quitte **À traiter** en bloc : une tâche en sort quand vous la traitez, l'archivez ou la reportez.-Ouvrez **Archivées** en bas de la boîte de réception pour parcourir les notifications plus anciennes. D'autres éléments se chargent au fil du défilement. Les filtres s'appliquent à l'ensemble des archives, y compris aux éléments pas encore chargés.+Ouvrez **Archivées** depuis le menu du titre de la boîte de réception pour parcourir les notifications plus anciennes et en restaurer une. D'autres éléments se chargent au fil du défilement.++### Filtrer++La boîte de réception se filtre selon la tâche : statut, priorité, projet, responsable, étiquette et date d'échéance. Un filtre s'applique à toutes les sections, **En cours** comprise. **Archivées** se filtre aussi selon la notification elle-même : état de lecture, type, expéditeur et date de réception. Ses filtres s'appliquent à l'ensemble des archives, y compris aux éléments pas encore chargés.++### Reporter++Reportez une tâche pour la mettre de côté jusqu'au moment de votre choix. Ouvrez-la et utilisez **Reporter** dans l'en-tête (ou appuyez sur `H`), ou faites un clic droit dessus dans la liste. Les choix sont **Dans 1 heure**, **Plus tard aujourd'hui**, **Demain** et **Lundi prochain** ; le menu de l'en-tête propose aussi **Choisir une date...** pour n'importe quel moment dans l'année à venir.++Une tâche reportée passe dans **Reportées** et n'est plus comptée par le badge. Le moment venu, elle revient dans sa section d'origine, non lue. Elle revient plus tôt si un nouvel élément demande votre attention sur cette tâche, comme une mention ou une exécution en échec ; l'activité qui ne relève que des **Mises à jour** ne la fait pas revenir. Pour la faire revenir vous-même, utilisez **Annuler le report** dans les mêmes menus.## Régler les types de notification-Ouvrez **Paramètres → Notifications** pour activer ou désactiver chaque groupe séparément :+Ouvrez **Paramètres → Notifications**. La page suit les sections de la boîte de réception :++- **À traiter** — les mentions, les assignations, les exécutions que vous avez lancées et l'activité des tâches que vous avez créées ou qui vous sont assignées. Elles sont toujours envoyées. Le seul réglage est **@all et @squad** : désactivé, les mentions de groupe sont classées dans **Mises à jour** au lieu d'**À traiter**.+- **Mises à jour** — les commentaires, changements de statut, changements d'assignation, priorité et date d'échéance, nouvelles tâches et exécutions d'agent sur les tâches que vous suivez. Chaque type peut être désactivé.-- Assignations ;-- Changements de statut ;-- Commentaires ;-- Mentions ;-- Priorité et date d'échéance ;-- Activité des agents.+Désactiver un type n'empêche pas l'enregistrement des changements sur la tâche — cela arrête seulement les notifications dans la boîte de réception. Quelques types, comme les réactions, les résultats de création rapide et les mises en pause d'automatisation, n'ont pas de réglage et sont toujours envoyés.-Désactiver un groupe n'empêche pas l'enregistrement des changements sur la tâche — cela arrête seulement les notifications dans la boîte de réception. Quelques types, comme les réactions, les résultats de création rapide et les mises en pause d'automatisation, ne relèvent pas de ces six groupes et sont toujours envoyés. Les notifications système et du navigateur contrôlent les bannières sur le bureau et ne modifient pas la boîte de réception elle-même.+Les notifications système et du navigateur contrôlent les bannières sur le bureau et ne modifient pas la boîte de réception elle-même. Dans la boîte de réception, seule une notification non lue de la section **À traiter** affiche une bannière ; les mises à jour, jamais.## Étapes suivantesdiff --git a/apps/docs/content/docs/inbox.ja.mdx b/apps/docs/content/docs/inbox.ja.mdxindex 056dae5588..cfc682e7c5 100644--- a/apps/docs/content/docs/inbox.ja.mdx+++ b/apps/docs/content/docs/inbox.ja.mdx@@ -44,37 +44,59 @@ import { InboxDemo } from "@/components/demos/inbox-demo";コメントでの @メンション、タスクの割り当て、オートパイロットのトリガーは、直接実行を作成し、エージェントに通知は残しません。`@all` もメンバーにのみ通知します。+## セクション++インボックスでは、各タスクは 1 回だけ、いま誰の番かに応じたセクションに表示されます。++- **対応待ち** — タスクがあなたを待っています。@メンションされた、割り当てられた、あなたが開始したエージェントの実行が完了・失敗した、またはキャンセルされた、あるいはあなたが作成した・担当しているタスクに動きがあった場合です(新しいコメント、実行の失敗、`in_review` や `blocked` のように人の対応を待つステータス)。各行には**確認待ち**、**回答待ち**、**実行失敗**などの理由が表示されます。+- **実行中** — あなたの依頼でエージェントがタスクに取り組んでいます(割り当て、コメント、再実行)。行にはエージェントと実行の経過時間、または**待機中**が表示されます。オートパイロットや他のメンバーが開始した実行など、あなた自身が開始していないものは表示されません。+- **アップデート** — それ以外の通知です。購読中のタスクの動きのうち、あなたの対応を待っていないものが入ります。表示されるのは未読のものだけで、読んだアップデートは**アーカイブ済み**に移ります。+- **スヌーズ中** — あとで戻ってくるように、いったん脇に置いたタスクです。++複数のセクションに当てはまるタスクは、上の順で最初のセクションに表示されます。**アップデート**と**スヌーズ中**は開くまで折りたたまれています。見出しにはそれぞれのタスク数が表示されます。++インボックスのバッジは**対応待ち**のタスク数を表します。読んだだけでは数は減りません。エージェントに渡す、スヌーズする、アーカイブするまで残ります。++あなたのコメントや割り当てでエージェントの実行が始まると、タスクは**対応待ち**から外れて**実行中**に表示されます。実行が完了・失敗するか、キャンセルされると**対応待ち**に戻ります。ただし、タスクがすでにクローズされている場合は戻りません。++キャンセルされた実行は**実行キャンセル**として戻ります。自分で停止した場合、行は既読で**あなたがこの実行を停止しました**と表示されます。ほかの人が停止した場合、行は未読で、停止した人の名前が表示されます。再実行したときのように、あなたが開始した別の実行がそのタスクで動いている間は戻らず、タスクは**実行中**に残ります。+## 通知の処理-通知を選択すると既読になります。対応が済んだらアーカイブできます。アーカイブしても対応するタスクは変更・削除されません。+通知を選択すると既読になります。**対応待ち**では、読むだけでは対応したことになりません。タスクに対して何かするまで、行は残ります。対応が済んだら、開いているタスクのヘッダーの**アーカイブ**か `E` でアーカイブできます。アーカイブしても対応するタスクは変更・削除されません。<InboxDemo />タスクが人に引き継がれるステータスになると、その「実行失敗」の通知は自動的にアーカイブされます。対象は `in_review`、`started` カテゴリのカスタムステータス、`done`・`closed` カテゴリのすべてのステータスです。`blocked` は例外です。人に引き継がれはしますが作業は止まったままなので、それまでの失敗の記録はまだ確認する必要があります。-通知を右クリックすると、**既読にする** / **未読にする**と**アーカイブ**(「アーカイブ済み」ビューでは**アーカイブ解除**)を使えます。未読にするは「目は通したが、まだ終わっていない」ための操作です。通知は未読に戻り、未読数も戻ります。開いたままでも未読のままで、あとでもう一度開けば通常どおり既読になります。アーカイブ済みの通知は既読状態を保持するため、復元すると元のまま戻ります。+タスクが `done` または `closed` カテゴリのステータスになると、全員のインボックスから外れ、**アップデート**にクローズを知らせる通知が 1 件だけ残ります。-インボックスのメニューからは次の操作もできます。+通知を右クリックすると、**既読にする** / **未読にする**、スヌーズ、**アーカイブ**(「アーカイブ済み」ビューでは**アーカイブ解除**)を使えます。未読にするは「目は通したが、まだ終わっていない」ための操作です。通知は未読に戻ります。開いたままでも未読のままで、あとでもう一度開けば通常どおり既読になります。アーカイブ済みの通知は既読状態を保持するため、復元すると元のまま戻ります。アップデートは例外で、未読として戻ります。既読のアップデートはまたすぐに外れてしまうためです。**削除**は通知を完全に取り除く操作で、「アーカイブ済み」ビューでのみ使えます。-- すべて既読にする-- すべてアーカイブする、または既読の項目をすべてアーカイブする-- `done` または `cancelled` のタスクの通知をアーカイブする-- 「アーカイブ済み」を開いて通知を復元する+**アップデート**では、読むことが対応です。開いたアップデートは、ほかの項目に移ると**アーカイブ済み**に移ります。セクション見出しの**クリア**は、表示されているアップデートを既読・未読にかかわらずすべてアーカイブします。**対応待ち**のタスクをまとめて外す操作はありません。対応する、アーカイブする、スヌーズするのいずれかで、1 件ずつ外れます。-インボックス下部の**アーカイブ済み**を開くと、スクロールに合わせて過去の通知が読み込まれます。フィルターは、まだ読み込まれていない通知も含め、アーカイブ全体に適用されます。+インボックスのタイトルのメニューから**アーカイブ済み**を開くと、過去の通知を確認して復元できます。スクロールに合わせて続きが読み込まれます。++### フィルター++インボックスはタスクの属性で絞り込みます。ステータス、優先度、プロジェクト、担当者、ラベル、期限です。フィルターは**実行中**を含むすべてのセクションに適用されます。**アーカイブ済み**は通知そのものでも絞り込めます。既読状態、通知の種類、送信者、受信日時です。こちらのフィルターは、まだ読み込まれていない通知も含め、アーカイブ全体に適用されます。++### スヌーズ++タスクをスヌーズすると、選んだ時刻までインボックスから外しておけます。タスクを開いてヘッダーの**スヌーズ**を使う(または `H` を押す)か、一覧で右クリックします。選べるのは**1 時間後**、**今日このあと**、**明日**、**次の月曜日**です。ヘッダーのメニューには**日時を選択...**もあり、1 年以内の任意の日時を指定できます。++スヌーズしたタスクは**スヌーズ中**に移り、バッジには数えられません。時刻になると、未読の状態で元のセクションに戻ります。メンションや実行の失敗など、そのタスクで新しく対応が必要になったときは早めに戻ります。**アップデート**に入るだけの動きでは戻りません。自分で戻すには、同じメニューの**スヌーズを解除**を使います。## 通知タイプの調整-**設定 → 通知**では、次のグループを個別にオン・オフできます。+**設定 → 通知**を開きます。ページはインボックスのセクションに沿って分かれています。++- **対応待ち** — メンション、担当の割り当て、あなたが開始した実行、あなたが作成または担当するタスクの動きです。これらは常に届きます。スイッチは **@all と @squad** の 1 つだけで、オフにするとグループ宛てのメンションは**対応待ち**ではなく**アップデート**に入ります。+- **アップデート** — フォロー中のタスクのコメント、ステータス変更、担当の変更、優先度と期限、新しいタスク、エージェントの実行です。種類ごとにオフにできます。-- 担当の割り当て-- ステータス変更-- コメント-- メンション-- 優先度と期限-- エージェントのアクティビティ+種類をオフにしても、関連する変更はタスクに記録され続けます。インボックス通知が作られなくなるだけです。リアクション、エージェント経由の作成結果、オートパイロットの一時停止など一部のタイプにはスイッチがなく、常に届きます。-グループをオフにしても、関連する変更はタスクに記録され続けます。インボックス通知が作られなくなるだけです。リアクション、エージェント経由の作成結果、オートパイロットの一時停止など一部のタイプはこの 6 グループの対象外で、常に届きます。システム通知とブラウザ通知はデスクトップのバナーを制御するもので、インボックス自体は変わりません。+システム通知とブラウザ通知はデスクトップのバナーを制御するもので、インボックス自体は変わりません。インボックスからバナーが出るのは**対応待ち**の未読の通知だけで、アップデートでは出ません。## 次のステップdiff --git a/apps/docs/content/docs/inbox.ko.mdx b/apps/docs/content/docs/inbox.ko.mdxindex f9831e3208..724a15f046 100644--- a/apps/docs/content/docs/inbox.ko.mdx+++ b/apps/docs/content/docs/inbox.ko.mdx@@ -44,37 +44,59 @@ import { InboxDemo } from "@/components/demos/inbox-demo";댓글에서 에이전트를 @멘션하거나 태스크를 에이전트에게 할당하거나 자동화를 트리거하면 실행이 직접 생성되며, 에이전트에게 알림을 남기지 않습니다. `@all`도 멤버에게만 알립니다.+## 섹션++인박스는 태스크마다 한 번씩, 지금 누구 차례인지에 따라 나누어 보여 줍니다.++- **처리 필요** — 태스크가 나를 기다리고 있습니다. 내가 @멘션되거나 할당받았을 때, 내가 시작한 에이전트 실행이 완료되거나 실패하거나 취소됐을 때, 내가 만들었거나 담당하는 태스크에 새 댓글, 실행 실패, `in_review`·`blocked`처럼 사람을 기다리는 상태 같은 변화가 생겼을 때입니다. 각 행에는 **검토 대기**, **답변 대기**, **실행 실패** 같은 이유가 표시됩니다.+- **실행 중** — 내가 요청해서 에이전트가 태스크를 처리하는 중입니다. 할당하거나 댓글을 달거나 다시 실행한 경우입니다. 행에는 에이전트와 실행 경과 시간, 또는 **대기 중**이 표시됩니다. 자동화나 다른 멤버가 시작한 실행처럼 내가 직접 시작하지 않은 실행은 표시되지 않습니다.+- **업데이트** — 그 밖의 알림입니다. 구독한 태스크의 활동 중 내가 처리할 필요가 없는 것이 들어옵니다. 읽지 않은 것만 표시되며, 읽은 업데이트는 **보관됨**으로 옮겨집니다.+- **미룬 항목** — 나중에 다시 보려고 미뤄 둔 태스크입니다.++여러 섹션에 해당하는 태스크는 위 순서에서 가장 앞선 섹션에 표시됩니다. **업데이트**와 **미룬 항목**은 열기 전까지 접혀 있으며, 제목에 각각의 태스크 수가 표시됩니다.++인박스 배지는 **처리 필요**에 있는 태스크 수를 셉니다. 읽기만 해서는 숫자가 줄지 않으며, 에이전트에게 넘기거나 미루거나 보관할 때까지 남아 있습니다.++내 댓글이나 할당으로 에이전트 실행이 시작되면 태스크는 **처리 필요**에서 빠지고 **실행 중**에 표시됩니다. 실행이 완료되거나 실패하거나 취소되면 **처리 필요**로 돌아옵니다. 단, 태스크가 이미 닫혔다면 돌아오지 않습니다.++취소된 실행은 **실행 취소됨**으로 돌아옵니다. 내가 직접 중지했다면 행은 읽은 상태이고 **내가 이 실행을 중지했습니다**라고 표시됩니다. 다른 사람이 중지했다면 읽지 않은 상태이고 누가 중지했는지 표시됩니다. 다시 실행한 경우처럼 내가 시작한 다른 실행이 그 태스크를 처리하고 있으면 돌아오지 않고, 태스크는 **실행 중**에 남습니다.+## 알림 처리-알림을 선택하면 읽음으로 표시됩니다. 처리한 뒤 보관할 수 있으며, 보관해도 해당 태스크가 변경되거나 삭제되지 않습니다.+알림을 선택하면 읽음으로 표시됩니다. **처리 필요**에서는 읽는 것만으로 처리한 것이 되지 않으며, 태스크에 조치를 취할 때까지 행이 남아 있습니다. 처리한 뒤에는 열어 둔 태스크 헤더의 **보관**이나 `E`로 보관할 수 있으며, 보관해도 해당 태스크가 변경되거나 삭제되지 않습니다.<InboxDemo />태스크가 사람에게 넘어가는 상태가 되면 그 태스크의 "실행 실패함" 알림은 자동으로 보관됩니다. 해당 상태는 `in_review`, `started` 카테고리의 사용자 지정 상태, `done`·`closed` 카테고리의 모든 상태입니다. `blocked`는 예외입니다. 사람에게 넘어가기는 하지만 작업이 여전히 막혀 있으므로 지난 실패 기록을 계속 확인해야 합니다.-알림을 오른쪽 클릭하면 **읽음으로 표시** / **읽지 않음으로 표시**와 **보관**("보관됨" 뷰에서는 **보관 해제**)을 쓸 수 있습니다. 읽지 않음으로 표시는 "보긴 했지만 아직 끝내지 않았다"는 뜻입니다. 알림이 다시 읽지 않음이 되고 읽지 않은 개수도 다시 올라가며, 열어둔 상태에서도 읽지 않음으로 유지됩니다. 나중에 다시 열면 평소대로 읽음으로 바뀝니다. 보관된 알림은 읽음 상태를 유지하므로 복원하면 그대로 돌아옵니다.+태스크가 `done` 또는 `closed` 카테고리의 상태가 되면 모든 사람의 인박스에서 빠지고, 닫혔다는 알림 하나만 **업데이트**에 남습니다.-인박스 메뉴에서는 다음 작업도 할 수 있습니다.+알림을 오른쪽 클릭하면 **읽음으로 표시** / **읽지 않음으로 표시**, 미루기, **보관**("보관됨" 뷰에서는 **보관 해제**)을 쓸 수 있습니다. 읽지 않음으로 표시는 "보긴 했지만 아직 끝내지 않았다"는 뜻입니다. 알림이 다시 읽지 않음이 되며, 열어둔 상태에서도 읽지 않음으로 유지됩니다. 나중에 다시 열면 평소대로 읽음으로 바뀝니다. 보관된 알림은 읽음 상태를 유지하므로 복원하면 그대로 돌아옵니다. 업데이트는 예외로, 읽지 않은 상태로 돌아옵니다. 읽은 업데이트는 다시 빠져나가기 때문입니다. **삭제**는 알림을 완전히 없애며 "보관됨" 뷰에서만 쓸 수 있습니다.-- 모두 읽음으로 표시-- 전체 또는 읽은 알림 모두 보관-- 상태가 `done` 또는 `cancelled`인 태스크 알림 보관-- "보관됨"을 열고 특정 알림 복원+**업데이트**에서는 읽는 것이 곧 처리입니다. 하나를 열었다가 다른 항목으로 넘어가면 **보관됨**으로 옮겨집니다. 섹션 제목의 **비우기**는 표시된 업데이트를 읽었든 아니든 모두 보관합니다. **처리 필요**의 태스크는 한꺼번에 치울 수 없으며, 처리하거나 보관하거나 미룰 때 하나씩 빠집니다.-인박스 하단의 **보관됨**을 열고 아래로 스크롤하면 이전 알림이 계속 불러와집니다. 필터는 아직 불러오지 않은 알림을 포함한 전체 보관 기록에 적용됩니다.+인박스 제목의 메뉴에서 **보관됨**을 열면 이전 알림을 보고 복원할 수 있습니다. 아래로 스크롤하면 계속 불러옵니다.++### 필터++인박스는 태스크 기준으로 필터링합니다. 상태, 우선순위, 프로젝트, 담당자, 레이블, 마감일입니다. 필터는 **실행 중**을 포함한 모든 섹션에 적용됩니다. **보관됨**은 알림 자체로도 필터링할 수 있습니다. 읽음 상태, 알림 유형, 보낸 사람, 받은 시간입니다. 이 필터는 아직 불러오지 않은 알림을 포함한 전체 보관 기록에 적용됩니다.++### 미루기++태스크를 미루면 내가 고른 시간까지 인박스에서 치워 둘 수 있습니다. 태스크를 열고 헤더의 **미루기**를 쓰거나(`H` 키) 목록에서 오른쪽 클릭합니다. **1시간 후**, **오늘 늦게**, **내일**, **다음 월요일** 중에서 고를 수 있고, 헤더 메뉴에는 1년 이내의 원하는 시간을 정하는 **시간 선택...**도 있습니다.++미룬 태스크는 **미룬 항목**으로 옮겨지고 배지에 포함되지 않습니다. 시간이 되면 읽지 않은 상태로 원래 섹션에 돌아옵니다. 멘션이나 실행 실패처럼 그 태스크에서 새로 처리할 일이 생기면 더 일찍 돌아오며, **업데이트**에만 들어오는 활동으로는 돌아오지 않습니다. 직접 되돌리려면 같은 메뉴에서 **미루기 취소**를 선택합니다.## 알림 유형 조정-**설정 → 알림**을 열면 다음 유형을 각각 켜거나 끌 수 있습니다.+**설정 → 알림**을 엽니다. 페이지는 인박스의 섹션을 따라 나뉩니다.++- **처리 필요** — 멘션, 할당, 내가 시작한 실행, 내가 만들었거나 담당하는 태스크의 활동입니다. 항상 전달됩니다. 스위치는 **@all 및 @squad** 하나뿐이며, 끄면 그룹 멘션이 **처리 필요** 대신 **업데이트**로 들어갑니다.+- **업데이트** — 팔로우 중인 태스크의 댓글, 상태 변경, 할당 변경, 우선순위 및 마감일, 새 태스크, 에이전트 실행입니다. 유형별로 끌 수 있습니다.-- 할당-- 상태 변경-- 댓글-- 멘션-- 우선순위와 날짜-- 에이전트 활동+특정 유형을 꺼도 관련 변경 사항은 태스크에 계속 저장되며 인박스 알림만 생성되지 않습니다. 이모지 반응, 빠른 생성 결과, 자동화 일시 중지 같은 일부 유형은 스위치가 없고 항상 전달됩니다.-특정 유형을 꺼도 관련 변경 사항은 태스크에 계속 저장되며 인박스 알림만 생성되지 않습니다. 이모지 반응, 빠른 생성 결과, 자동화 일시 중지 같은 일부 유형은 이 여섯 그룹의 설정과 관계없이 항상 전달됩니다. 시스템 알림과 브라우저 알림 설정은 데스크톱 배너를 제어할 뿐 인박스 자체를 바꾸지 않습니다.+시스템 알림과 브라우저 알림 설정은 데스크톱 배너를 제어할 뿐 인박스 자체를 바꾸지 않습니다. 인박스에서는 **처리 필요**의 읽지 않은 알림만 배너를 띄우며, 업데이트는 띄우지 않습니다.## 다음 단계diff --git a/apps/docs/content/docs/inbox.mdx b/apps/docs/content/docs/inbox.mdxindex 7bdacd23b5..61dd8ef206 100644--- a/apps/docs/content/docs/inbox.mdx+++ b/apps/docs/content/docs/inbox.mdx@@ -44,37 +44,59 @@ The inbox is only for workspace members. Even when an agent is the assignee or a@-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.+## Sections++The inbox lists each issue once, under whose turn it is:++- **Needs you** — the issue is waiting on you. You were @-mentioned or assigned, an agent run you started finished, failed, or was cancelled, or something happened on an issue you created or are assigned to: a new comment, a failed run, or a status that waits on a person, such as `in_review` or `blocked`. Each row says why, for example **Ready for review**, **Waiting for your answer**, or **Run failed**.+- **Working** — an agent is working on the issue because you asked: you assigned it, commented, or reran it. The row shows the agent and how long the run has been going, or **Queued**. Runs you didn't start yourself, such as an autopilot's or another member's, aren't listed.+- **Updates** — everything else: activity on issues you subscribe to that doesn't wait on you. Only unread ones are listed; an update moves to **Archived** once you've read it.+- **Snoozed** — issues you put away until a later time.++An issue that fits more than one section appears in the first of them, in the order above. **Updates** and **Snoozed** stay folded until you open them; each header shows how many issues it holds.++The inbox badge counts the issues under **Needs you**. Reading one doesn't take it off the count: it stays until you hand it to an agent, snooze it, or archive it.++When your comment or assignment starts an agent run, the issue leaves **Needs you** and shows under **Working**. When the run finishes, fails, or is cancelled, it comes back to **Needs you**, unless the issue is already closed.++A cancelled run comes back as **Run cancelled**. If you stopped it yourself, the row is already read and says **You stopped this run**; if someone else did, it is unread and names them. It doesn't come back while another run you started is active on the issue, as when you rerun it: the issue stays under **Working**.+## Handle notifications-Selecting a notification marks it as read. Archive it when you're done; archiving doesn't modify or delete the corresponding issue.+Selecting a notification marks it as read. Under **Needs you**, reading isn't handling: the row stays until you act on the issue. Archive it when you're done, with **Archive** in the header of the open issue or `E`; archiving doesn't modify or delete the corresponding issue.<InboxDemo />Once an issue reaches a status that hands it back to a person, its **Run failed** notifications archive automatically. Those statuses are `in_review`, custom statuses in the `started` category, and any status in the `done` or `closed` category. `blocked` is the exception: it hands the issue over too, but the work is still stuck, so the earlier failures are still worth reading.-Right-click a notification for **Mark as read** / **Mark as unread** and **Archive** (**Unarchive** in the Archived view). Mark as unread is the "I looked, but I'm not done with this" action: the notification goes back to unread and raises the unread count again, and it stays unread even while you keep it open; opening it again later marks it read as usual. Archived notifications keep their read state, so restoring one brings it back exactly as you left it.+An issue moved to a status in the `done` or `closed` category leaves everyone's inbox; what remains is one entry under **Updates** saying it closed.-From the inbox menu you can also:+Right-click a notification for **Mark as read** / **Mark as unread**, snoozing, and **Archive** (**Unarchive** in the Archived view). Mark as unread is the "I looked, but I'm not done with this" action: the notification goes back to unread, and it stays unread even while you keep it open; opening it again later marks it read as usual. Archived notifications keep their read state, so restoring one brings it back exactly as you left it. An update is the exception: it comes back unread, because a read update would leave again. **Delete** removes a notification for good, and is offered in the Archived view only.-- mark all as read;-- archive all, or archive all read;-- archive notifications for issues in `done` or `cancelled`;-- open Archived and restore a notification.+Under **Updates**, reading is handling: open one and it moves to **Archived** when you move on to something else. **Clear** on the section header archives every update listed, read or not. Nothing leaves **Needs you** in bulk: an issue goes when you handle it, archive it, or snooze it.-Open **Archived** at the bottom of the inbox to browse older notifications. More records load as you scroll. Filters apply to the entire archive, including records that have not loaded yet.+Open **Archived** from the menu on the inbox title to browse older notifications and restore one. More records load as you scroll.++### Filter++The inbox filters by the issue: status, priority, project, assignee, label, and due date. A filter applies to every section, **Working** included. **Archived** can also be filtered by the notification itself: read state, type, sender, and when it was received. Its filters apply to the entire archive, including records that have not loaded yet.++### Snooze++Snooze an issue to put it away until a time you choose. Open it and use **Snooze** in the header (or press `H`), or right-click it in the list. The choices are **In 1 hour**, **Later today**, **Tomorrow**, and **Next Monday**; the header menu also has **Pick a time...** for any time within the next year.++A snoozed issue moves to **Snoozed** and stops counting on the badge. When the time comes, it returns to the section it was in, as unread. It comes back early if something new needs you on that issue, such as a mention or a failed run; activity that only lands under **Updates** doesn't bring it back. To bring it back yourself, use **Unsnooze** in the same menus.## Tune notification types-Open **Settings → Notifications** to toggle each group separately:+Open **Settings → Notifications**. The page follows the inbox's sections:++- **Needs you** — mentions, assignments, runs you started, and activity on issues you created or are assigned to. These are always delivered. The one switch is **@all and @squad**: turn it off and group mentions are filed under **Updates** instead of **Needs you**.+- **Updates** — comments, status changes, assignment changes, priority and due date, new issues, and agent runs on issues you follow. Each can be turned off.-- assignments;-- status changes;-- comments;-- mentions;-- priority and dates;-- agent activity.+Turning a kind off doesn't stop the changes from being recorded on the issue — it only stops the inbox notifications. A few types, such as reactions, quick-create results, and autopilot pauses, have no switch and are always delivered.-Turning a group off doesn't stop the changes from being recorded on the issue — it only stops the inbox notifications. A few types, such as reactions, quick-create results, and autopilot pauses, sit outside these six groups and are always delivered. System and browser notifications control desktop banners and don't change the inbox itself.+System and browser notifications control desktop banners and don't change the inbox itself. From the inbox, only an unread notification under **Needs you** raises a banner; updates never do.## Next stepsdiff --git a/apps/docs/content/docs/inbox.zh-Hant.mdx b/apps/docs/content/docs/inbox.zh-Hant.mdxindex d1fb151dbd..aca0eff41d 100644--- a/apps/docs/content/docs/inbox.zh-Hant.mdx+++ b/apps/docs/content/docs/inbox.zh-Hant.mdx@@ -44,37 +44,59 @@ import { InboxDemo } from "@/components/demos/inbox-demo";在評論中 @ AI 代理、把任務分配給 AI 代理或觸發自動化,都會直接建立一次執行,不會給 AI 代理留通知。`@all` 也只通知成員。+## 分區++收件箱裡每個任務只出現一次,按"現在該誰處理"分區:++- **需要你處理** — 任務在等你。有人 @你 或把任務分配給你,你發起的 AI 代理執行完成、失敗或被取消,或者你建立、負責的任務有了新情況:新評論、執行失敗,或進入等人處理的狀態(如 `in_review`、`blocked`)。每一行都會寫明原因,例如**等你驗收**、**等你回答**、**執行失敗**。+- **執行中** — AI 代理正在按你的要求處理這個任務:你分配了任務、發了評論或重新執行。這一行顯示 AI 代理和已執行的時長,或顯示**排隊中**。不是你親自發起的執行(例如自動化或其他成員發起的)不會列在這裡。+- **動態** — 其餘的通知:你訂閱的任務上不需要你處理的活動。這裡只列未讀的;讀過的動態會移到**已歸檔**。+- **已延後** — 你暫時放到一邊、到時間再回來的任務。++一個任務同時符合多個分區時,按上面的順序出現在最靠前的那個分區。**動態**和**已延後**預設摺疊;標題上顯示各自的任務數。++收件箱的角標統計的是**需要你處理**裡的任務數。讀過並不會讓它從計數裡消失:直到你把它交給 AI 代理、延後或歸檔,它才會離開。++你的評論或分配觸發 AI 代理執行後,任務會離開**需要你處理**,出現在**執行中**。執行完成、失敗或被取消後,它會回到**需要你處理**;如果任務已經關閉,則不會再回來。++被取消的執行會以**執行已取消**回來。如果是你自己停的,這一行是已讀的,並寫著**你停止了這次執行**;如果是別人停的,這一行是未讀的,並寫明是誰。如果你發起的另一次執行還在處理這個任務(例如你重新執行了),它不會回來,任務留在**執行中**。+## 處理通知-選擇一條通知會把它標為已讀。處理完後可以歸檔,歸檔不會修改或刪除對應的任務。+選擇一條通知會把它標為已讀。在**需要你處理**裡,讀過不等於處理完:這一行會一直留著,直到你對任務採取行動。處理完後可以歸檔:點選任務標題列裡的**歸檔**,或按 `E`。歸檔不會修改或刪除對應的任務。<InboxDemo />任務進入交回給人的狀態後,它的"執行失敗"通知會自動歸檔。這類狀態包括 `in_review`、`started` 分類下的自定義狀態,以及 `done`、`closed` 分類下的任一狀態。`blocked` 例外:它同樣交回給人,但工作還卡著,之前的失敗記錄還要看。-右鍵點選一條通知,可以使用**標為已讀** / **標為未讀**和**歸檔**(在"已歸檔"檢視中是**取消歸檔**)。標為未讀表達的是"我看過了,但還沒處理完":該通知重新變為未讀,未讀數也會回升;即使它還開著也保持未讀,之後再開啟一次才會照常標為已讀。已歸檔的通知會保留已讀狀態,因此恢復時會原樣回來。+任務進入 `done` 或 `closed` 分類下的狀態後,會從所有人的收件箱裡移走,只在**動態**裡留下一條說明它已關閉的通知。-收件箱選單還可以:+右鍵點選一條通知,可以使用**標為已讀** / **標為未讀**、延後選項和**歸檔**(在"已歸檔"檢視中是**取消歸檔**)。標為未讀表達的是"我看過了,但還沒處理完":該通知重新變為未讀;即使它還開著也保持未讀,之後再開啟一次才會照常標為已讀。已歸檔的通知會保留已讀狀態,因此恢復時會原樣回來。動態例外:恢復後是未讀的,因為讀過的動態會再次離開。**刪除**會永久移除通知,只在"已歸檔"檢視中提供。-- 全部標為已讀;-- 歸檔全部或全部已讀;-- 歸檔狀態為 `done` 或 `cancelled` 的任務通知;-- 開啟"已歸檔"並恢復某條通知。+在**動態**裡,讀過就是處理完:開啟一條,等你轉去看別的,它就移到**已歸檔**。分區標題上的**清空**會把列出的動態全部歸檔,不論已讀未讀。**需要你處理**裡的任務不能批次移走:只有你處理、歸檔或延後它,它才會離開。-從收件箱底部開啟**已歸檔**,向下捲動可繼續載入更早的通知。篩選覆蓋全部歸檔記錄,包括尚未載入的記錄。+從收件箱標題的選單開啟**已歸檔**,可以瀏覽更早的通知並恢復某一條。向下捲動可繼續載入。++### 篩選++收件箱按任務篩選:狀態、優先順序、專案、負責人、標籤和截止日期。篩選對每個分區都生效,包括**執行中**。**已歸檔**還可以按通知本身篩選:閱讀狀態、通知類型、來自和收到時間。它的篩選覆蓋全部歸檔記錄,包括尚未載入的記錄。++### 延後++把任務延後,可以讓它暫時離開收件箱,到你選的時間再回來。開啟任務後點選標題列裡的**延後**(或按 `H`),也可以在列表裡右鍵點選它。可選的時間有 **1 小時後**、**今天稍晚**、**明天**和**下週一**;標題列的選單裡還有**選擇時間...**,可以選一年內的任意時間。++延後的任務會移到**已延後**,不再計入角標。時間一到,它會以未讀狀態回到原來的分區。如果這個任務上有新的事需要你處理(例如有人 @你,或執行失敗),它會提前回來;只進入**動態**的活動不會讓它提前回來。想自己提前取回,可以在同樣的選單裡選擇**取消延後**。## 調整通知型別-開啟**設定 → 通知**,可以分別開關:+開啟**設定 → 通知**。頁面按收件箱的分區組織:++- **需要你處理** — 提及、分配、你發起的執行,以及你建立或負責的任務上的活動。這些一律投遞。唯一的開關是 **@all 和 @squad**:關閉後,群組提及改進**動態**,不再進**需要你處理**。+- **動態** — 你訂閱的任務上的評論、狀態變更、分配變更、優先順序與截止日期、新任務和 AI 代理執行。每一類都可以關閉。-- 分配;-- 狀態變更;-- 評論;-- 提及;-- 優先順序與日期;-- AI 代理活動。+關閉某一類後,相關變化仍然儲存在任務中,只是不再建立收件箱通知。表情回應、快速建立結果和自動化暫停等少數型別沒有開關,始終投遞。-關閉某一類後,相關變化仍然儲存在任務中,只是不再建立收件箱通知。表情回應、快速建立結果和自動化暫停等少數型別不受這六組控制,始終投遞。系統通知和瀏覽器通知控制的是桌面橫幅,不會改變收件箱本身。+系統通知和瀏覽器通知控制的是桌面橫幅,不會改變收件箱本身。收件箱裡只有**需要你處理**下的未讀通知會跳出橫幅,動態不會。## 接下來diff --git a/apps/docs/content/docs/inbox.zh.mdx b/apps/docs/content/docs/inbox.zh.mdxindex 643d140b07..2d00e1c032 100644--- a/apps/docs/content/docs/inbox.zh.mdx+++ b/apps/docs/content/docs/inbox.zh.mdx@@ -44,37 +44,59 @@ import { InboxDemo } from "@/components/demos/inbox-demo";在评论中 @智能体、把任务分配给智能体或触发自动化,都会直接创建一次运行,不会给智能体留通知。`@all` 也只通知成员。+## 分区++收件箱里每个任务只出现一次,按"现在该谁处理"分区:++- **要你处理** — 任务在等你。有人 @你 或把任务分配给你,你发起的智能体运行完成、失败或被取消,或者你创建、负责的任务有了新情况:新评论、运行失败,或进入等人处理的状态(如 `in_review`、`blocked`)。每一行都会写明原因,例如**等你验收**、**等你回答**、**运行失败**。+- **运行中** — 智能体正在按你的要求处理这个任务:你分配了任务、发了评论或重新运行。这一行显示智能体和已运行的时长,或显示**排队中**。不是你亲自发起的运行(例如自动化或其他成员发起的)不会列在这里。+- **动态** — 其余的通知:你订阅的任务上不需要你处理的活动。这里只列未读的;读过的动态会移到**已归档**。+- **已推迟** — 你暂时放到一边、到时间再回来的任务。++一个任务同时符合多个分区时,按上面的顺序出现在最靠前的那个分区。**动态**和**已推迟**默认折叠;标题上显示各自的任务数。++收件箱的角标统计的是**要你处理**里的任务数。读过并不会让它从计数里消失:直到你把它交给智能体、推迟或归档,它才会离开。++你的评论或分配触发智能体运行后,任务会离开**要你处理**,出现在**运行中**。运行完成、失败或被取消后,它会回到**要你处理**;如果任务已经关闭,则不会再回来。++被取消的运行会以**运行已取消**回来。如果是你自己停的,这一行是已读的,并写着**你停止了这次运行**;如果是别人停的,这一行是未读的,并写明是谁。如果你发起的另一次运行还在处理这个任务(例如你重新运行了),它不会回来,任务留在**运行中**。+## 处理通知-选择一条通知会把它标为已读。处理完后可以归档,归档不会修改或删除对应的任务。+选择一条通知会把它标为已读。在**要你处理**里,读过不等于处理完:这一行会一直留着,直到你对任务采取行动。处理完后可以归档:点击任务标题栏里的**归档**,或按 `E`。归档不会修改或删除对应的任务。<InboxDemo />任务进入交回给人的状态后,它的"运行失败"通知会自动归档。这类状态包括 `in_review`、`started` 分类下的自定义状态,以及 `done`、`closed` 分类下的任一状态。`blocked` 例外:它同样交回给人,但工作还卡着,之前的失败记录还要看。-右键点击一条通知,可以使用**标为已读** / **标为未读**和**归档**(在"已归档"视图中是**取消归档**)。标为未读表达的是"我看过了,但还没处理完":该通知重新变为未读,未读数也会回升;即使它还开着也保持未读,之后再打开一次才会照常标为已读。已归档的通知会保留已读状态,因此恢复时会原样回来。+任务进入 `done` 或 `closed` 分类下的状态后,会从所有人的收件箱里移走,只在**动态**里留下一条说明它已关闭的通知。-收件箱菜单还可以:+右键点击一条通知,可以使用**标为已读** / **标为未读**、推迟选项和**归档**(在"已归档"视图中是**取消归档**)。标为未读表达的是"我看过了,但还没处理完":该通知重新变为未读;即使它还开着也保持未读,之后再打开一次才会照常标为已读。已归档的通知会保留已读状态,因此恢复时会原样回来。动态例外:恢复后是未读的,因为读过的动态会再次离开。**删除**会永久移除通知,只在"已归档"视图中提供。-- 全部标为已读;-- 归档全部或全部已读;-- 归档状态为 `done` 或 `cancelled` 的任务通知;-- 打开"已归档"并恢复某条通知。+在**动态**里,读过就是处理完:打开一条,等你转去看别的,它就移到**已归档**。分区标题上的**清空**会把列出的动态全部归档,不论已读未读。**要你处理**里的任务不能批量移走:只有你处理、归档或推迟它,它才会离开。-从收件箱底部打开**已归档**,向下滚动可继续加载更早的通知。筛选覆盖全部归档记录,包括尚未加载的记录。+从收件箱标题的菜单打开**已归档**,可以浏览更早的通知并恢复某一条。向下滚动可继续加载。++### 筛选++收件箱按任务筛选:状态、优先级、项目、负责人、标签和截止日期。筛选对每个分区都生效,包括**运行中**。**已归档**还可以按通知本身筛选:阅读状态、通知类型、来自和收到时间。它的筛选覆盖全部归档记录,包括尚未加载的记录。++### 推迟++把任务推迟,可以让它暂时离开收件箱,到你选的时间再回来。打开任务后点击标题栏里的**推迟**(或按 `H`),也可以在列表里右键点击它。可选的时间有 **1 小时后**、**今天晚些时候**、**明天**和**下周一**;标题栏的菜单里还有**选择时间...**,可以选一年内的任意时间。++推迟的任务会移到**已推迟**,不再计入角标。时间一到,它会以未读状态回到原来的分区。如果这个任务上有新的事需要你处理(比如有人 @你,或运行失败),它会提前回来;只进入**动态**的活动不会让它提前回来。想自己提前取回,可以在同样的菜单里选择**取消推迟**。## 调整通知类型-打开**设置 → 通知**,可以分别开关:+打开**设置 → 通知**。页面按收件箱的分区组织:++- **要你处理** — 提及、分配、你发起的运行,以及你创建或负责的任务上的活动。这些始终投递。唯一的开关是 **@all 和 @squad**:关闭后,群体提及改进**动态**,不再进**要你处理**。+- **动态** — 你订阅的任务上的评论、状态变更、分配变化、优先级与截止日期、新任务和智能体运行。每一类都可以关闭。-- 分配;-- 状态变更;-- 评论;-- 提及;-- 优先级与日期;-- 智能体活动。+关闭某一类后,相关变化仍然保存在任务中,只是不再创建收件箱通知。表情回应、快速创建结果和自动化暂停等少数类型没有开关,始终投递。-关闭某一类后,相关变化仍然保存在任务中,只是不再创建收件箱通知。表情回应、快速创建结果和自动化暂停等少数类型不受这六组控制,始终投递。系统通知和浏览器通知控制的是桌面横幅,不会改变收件箱本身。+系统通知和浏览器通知控制的是桌面横幅,不会改变收件箱本身。收件箱里只有**要你处理**下的未读通知会弹出横幅,动态不会。## 接下来diff --git a/apps/docs/content/docs/shortcuts.fr.mdx b/apps/docs/content/docs/shortcuts.fr.mdxindex c7e7b8c0bb..437fa7b219 100644--- a/apps/docs/content/docs/shortcuts.fr.mdx+++ b/apps/docs/content/docs/shortcuts.fr.mdx@@ -36,11 +36,12 @@ Choisir un résultat l'ouvre. Maintenez `⌘` (`Ctrl` sous Windows et Linux) en| Demander à Multica | `⇧⌘J` | `Ctrl+Maj+J` | Démarre une nouvelle discussion dans la fenêtre flottante. || Rechercher dans la tâche | `⌘F` | `Ctrl+F` | Voir plus bas. || Archiver la notification | `E` | `E` | Archive la notification ouverte dans la boîte de réception, ou la restaure quand vous consultez les archives. |+| Reporter la notification | `H` | `H` | Ouvre le menu de report de la notification ouverte dans la boîte de réception. || Envoyer | `⌘↵` | `Ctrl+Enter` | Envoie commentaires et messages de discussion, et sert aussi à créer des tâches. || Revenir en arrière | `⌘[` | `Ctrl+[` | || Avancer | `⌘]` | `Ctrl+]` | |-Les raccourcis à une seule touche (`C`, `E`) et Revenir en arrière / Avancer ne réagissent pas pendant que vous tapez dans un champ.+Les raccourcis à une seule touche (`C`, `E`, `H`) et Revenir en arrière / Avancer ne réagissent pas pendant que vous tapez dans un champ.Le groupe **Navigation** propose aussi d'aller à la boîte de réception, aux discussions, à Mes tâches, aux tâches, aux projets, aux automatisations, aux agents, aux squads, aux statistiques, aux runtimes, aux skills et aux paramètres. Aucune de ces actions n'a de touche par défaut : attribuez-en à celles que vous utilisez.diff --git a/apps/docs/content/docs/shortcuts.ja.mdx b/apps/docs/content/docs/shortcuts.ja.mdxindex 5b8a2c152e..c7a33390f7 100644--- a/apps/docs/content/docs/shortcuts.ja.mdx+++ b/apps/docs/content/docs/shortcuts.ja.mdx@@ -36,11 +36,12 @@ import { Step, Steps } from "fumadocs-ui/components/steps";| Multica に質問 | `⇧⌘J` | `Ctrl+Shift+J` | フローティングチャットで新しいチャットを始めます。 || タスク内を検索 | `⌘F` | `Ctrl+F` | 後述。 || 通知をアーカイブ | `E` | `E` | インボックスで開いている通知をアーカイブします。アーカイブ表示中はアーカイブを解除します。 |+| 通知をスヌーズ | `H` | `H` | インボックスで開いている通知のスヌーズメニューを開きます。 || 送信 | `⌘↵` | `Ctrl+Enter` | コメントやチャットのメッセージを送信します。新しいタスクの作成にも使います。 || 戻る | `⌘[` | `Ctrl+[` | || 進む | `⌘]` | `Ctrl+]` | |-1 キーだけのショートカット(`C`、`E`)と「戻る」「進む」は、入力欄で文字を打っている間は反応しません。+1 キーだけのショートカット(`C`、`E`、`H`)と「戻る」「進む」は、入力欄で文字を打っている間は反応しません。**ナビゲーション**には、インボックス、チャット、自分のタスク、タスク、プロジェクト、自動化、エージェント、Squads、使用量、ランタイム、Skills、設定へ移動する操作もあります。どれも既定ではキーが割り当てられていないので、よく使うものに設定してください。diff --git a/apps/docs/content/docs/shortcuts.ko.mdx b/apps/docs/content/docs/shortcuts.ko.mdxindex 4c460e6d31..af94d5767c 100644--- a/apps/docs/content/docs/shortcuts.ko.mdx+++ b/apps/docs/content/docs/shortcuts.ko.mdx@@ -36,11 +36,12 @@ import { Step, Steps } from "fumadocs-ui/components/steps";| Multica에 묻기 | `⇧⌘J` | `Ctrl+Shift+J` | 플로팅 채팅 창에서 새 채팅을 시작합니다. || 태스크에서 찾기 | `⌘F` | `Ctrl+F` | 아래 설명 참고. || 알림 보관 | `E` | `E` | 인박스에서 열어 둔 알림을 보관합니다. 보관함을 보는 중에는 보관을 해제합니다. |+| 알림 미루기 | `H` | `H` | 인박스에서 열어 둔 알림의 미루기 메뉴를 엽니다. || 보내기 | `⌘↵` | `Ctrl+Enter` | 댓글과 채팅 메시지를 보내고, 새 태스크를 만들 때도 씁니다. || 뒤로 가기 | `⌘[` | `Ctrl+[` | || 앞으로 가기 | `⌘]` | `Ctrl+]` | |-키 하나짜리 단축키(`C`, `E`)와 뒤로 가기·앞으로 가기는 입력란에서 글을 쓰는 동안에는 동작하지 않습니다.+키 하나짜리 단축키(`C`, `E`, `H`)와 뒤로 가기·앞으로 가기는 입력란에서 글을 쓰는 동안에는 동작하지 않습니다.**탐색** 그룹에는 인박스, 채팅, 내 태스크, 태스크, 프로젝트, 자동화, 에이전트, 스쿼드, 사용량, 런타임, Skills, 설정으로 이동하는 동작도 있습니다. 모두 기본 키가 없으니 자주 쓰는 것에 직접 지정하세요.diff --git a/apps/docs/content/docs/shortcuts.mdx b/apps/docs/content/docs/shortcuts.mdxindex 1f56882fb7..35cf5afabe 100644--- a/apps/docs/content/docs/shortcuts.mdx+++ b/apps/docs/content/docs/shortcuts.mdx@@ -36,11 +36,12 @@ Selecting a result opens it. Hold `⌘` (`Ctrl` on Windows and Linux) while clic| Ask Multica | `⇧⌘J` | `Ctrl+Shift+J` | Starts a new chat in the floating window. || Find in issue | `⌘F` | `Ctrl+F` | See below. || Archive notification | `E` | `E` | Archives the open inbox notification, or restores it while you're reading the archive. |+| Snooze notification | `H` | `H` | Opens the snooze menu for the open inbox notification. || Send | `⌘↵` | `Ctrl+Enter` | Sends comments and chat messages, and also submits new issues. || Go back | `⌘[` | `Ctrl+[` | || Go forward | `⌘]` | `Ctrl+]` | |-Single-key shortcuts (`C`, `E`) and Go back / Go forward don't fire while you're typing in an input.+Single-key shortcuts (`C`, `E`, `H`) and Go back / Go forward don't fire while you're typing in an input.The **Navigation** group also has Go to Inbox, Chat, My Issues, Issues, Projects, Autopilot, Agents, Squads, Usage, Runtimes, Skills, and Settings. None of them has a key by default; bind the ones you use.diff --git a/apps/docs/content/docs/shortcuts.zh-Hant.mdx b/apps/docs/content/docs/shortcuts.zh-Hant.mdxindex 0762b506dc..a5d0d36d0a 100644--- a/apps/docs/content/docs/shortcuts.zh-Hant.mdx+++ b/apps/docs/content/docs/shortcuts.zh-Hant.mdx@@ -36,11 +36,12 @@ import { Step, Steps } from "fumadocs-ui/components/steps";| 問 Multica | `⇧⌘J` | `Ctrl+Shift+J` | 在懸浮聊天窗裡開始新對話。 || 在任務中查詢 | `⌘F` | `Ctrl+F` | 見下文。 || 歸檔通知 | `E` | `E` | 歸檔收件箱裡當前開啟的通知;檢視已歸檔時則取消歸檔。 |+| 延後通知 | `H` | `H` | 開啟收件箱裡當前通知的延後選單。 || 傳送 | `⌘↵` | `Ctrl+Enter` | 傳送評論和聊天訊息,也用於提交新任務。 || 後退 | `⌘[` | `Ctrl+[` | || 前進 | `⌘]` | `Ctrl+]` | |-單鍵快捷鍵(`C`、`E`)和後退、前進在輸入框裡不起作用,避免打字時誤觸。+單鍵快捷鍵(`C`、`E`、`H`)和後退、前進在輸入框裡不起作用,避免打字時誤觸。**導航**類操作還有前往收件箱、聊天、我的任務、任務、專案、自動化、AI 代理、小隊、統計、執行時、Skills 和設定,預設都沒有設定按鍵,需要時自己繫結。diff --git a/apps/docs/content/docs/shortcuts.zh.mdx b/apps/docs/content/docs/shortcuts.zh.mdxindex 5e6e6ead40..245d0f81bf 100644--- a/apps/docs/content/docs/shortcuts.zh.mdx+++ b/apps/docs/content/docs/shortcuts.zh.mdx@@ -36,11 +36,12 @@ import { Step, Steps } from "fumadocs-ui/components/steps";| 问 Multica | `⇧⌘J` | `Ctrl+Shift+J` | 在悬浮聊天窗里开始新对话。 || 在任务中查找 | `⌘F` | `Ctrl+F` | 见下文。 || 归档通知 | `E` | `E` | 归档收件箱里当前打开的通知;查看已归档时则取消归档。 |+| 推迟通知 | `H` | `H` | 打开收件箱里当前通知的推迟菜单。 || 发送 | `⌘↵` | `Ctrl+Enter` | 发送评论和聊天消息,也用于提交新任务。 || 后退 | `⌘[` | `Ctrl+[` | || 前进 | `⌘]` | `Ctrl+]` | |-单键快捷键(`C`、`E`)和后退、前进在输入框里不起作用,避免打字时误触。+单键快捷键(`C`、`E`、`H`)和后退、前进在输入框里不起作用,避免打字时误触。**导航**类操作还有前往收件箱、聊天、我的任务、任务、项目、自动化、智能体、小队、统计、运行时、Skills 和设置,默认都没有设置按键,需要时自己绑定。diff --git a/apps/mobile/components/inbox/detail-label.tsx b/apps/mobile/components/inbox/detail-label.tsxindex a989cb0875..2e766982c2 100644--- a/apps/mobile/components/inbox/detail-label.tsx+++ b/apps/mobile/components/inbox/detail-label.tsx@@ -49,6 +49,7 @@ const TYPE_KEY: Record<InboxItemType, string> = {review_requested: "type.review_requested",task_completed: "type.task_completed",task_failed: "type.task_failed",+ task_cancelled: "type.task_cancelled",agent_blocked: "type.agent_blocked",agent_completed: "type.agent_completed",reaction_added: "type.reaction_added",diff --git a/apps/mobile/locales/en/inbox.json b/apps/mobile/locales/en/inbox.jsonindex 91b6cea631..cc7aa87ec5 100644--- a/apps/mobile/locales/en/inbox.json+++ b/apps/mobile/locales/en/inbox.json@@ -58,6 +58,7 @@"review_requested": "Review requested","task_completed": "Task completed","task_failed": "Task failed",+ "task_cancelled": "Run cancelled","agent_blocked": "Agent blocked","agent_completed": "Agent completed","reaction_added": "Reaction added",diff --git a/apps/mobile/locales/zh-Hans/inbox.json b/apps/mobile/locales/zh-Hans/inbox.jsonindex b7e993ff10..813e346a10 100644--- a/apps/mobile/locales/zh-Hans/inbox.json+++ b/apps/mobile/locales/zh-Hans/inbox.json@@ -58,6 +58,7 @@"review_requested": "请求审查","task_completed": "运行完成","task_failed": "运行失败",+ "task_cancelled": "运行已取消","agent_blocked": "智能体受阻","agent_completed": "智能体已完成","reaction_added": "添加了表情",diff --git a/apps/mobile/locales/zh-Hant/inbox.json b/apps/mobile/locales/zh-Hant/inbox.jsonindex de4277e17d..fd7ff17e4b 100644--- a/apps/mobile/locales/zh-Hant/inbox.json+++ b/apps/mobile/locales/zh-Hant/inbox.json@@ -58,6 +58,7 @@"review_requested": "請求審查","task_completed": "執行完成","task_failed": "執行失敗",+ "task_cancelled": "執行已取消","agent_blocked": "AI 代理受阻","agent_completed": "AI 代理已完成","reaction_added": "新增了表情",diff --git a/packages/core/api/archived-inbox.test.ts b/packages/core/api/archived-inbox.test.tsindex 23ae833b16..33e8cc8182 100644--- a/packages/core/api/archived-inbox.test.ts+++ b/packages/core/api/archived-inbox.test.ts@@ -15,11 +15,9 @@ describe("archived inbox API", () => {it("sends cursor, lookup and every archive filter dimension and maps the page", async () => {const fetch = respond({ items: [], next_cursor: null, has_more: false });const api = new ApiClient("https://api.example.test");- // The archive has no agent dimension; a selection carried in from the- // active inbox must not reach the server.const filters: InboxFilters = {...EMPTY_INBOX_FILTERS,- statuses: ["in_review"], priorities: ["high"], actors: ["system"], unreadOnly: true, agent: "idle",+ statuses: ["in_review"], priorities: ["high"], actors: ["system"], unreadOnly: true,labels: ["label-1"], negated: ["label"],};await expect(api.listArchivedInboxPage(filters, { cursor: "cursor-value", groupId: "group" })).resolves.toEqual({ items: [], nextCursor: null, hasMore: false });diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex a7e750e6a8..8a6f8a03c5 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -838,6 +838,9 @@ function dingTalkGroupSearch(params: ListDingTalkGroupsParams): string {// (server/internal/middleware/auth.go). Matched rather than inferred from the// status, because 403 also covers real authorization failures that must not// be retried.+/** The most groups `POST /api/inbox/archive-updates` takes in one request. */+const INBOX_ARCHIVE_UPDATES_MAX_GROUPS = 500;+const CSRF_REJECTED_ERROR = "CSRF validation failed";// One header, two possible values — see ApiClient.readCsrfValue.@@ -3129,8 +3132,11 @@ export class ApiClient {}// Inbox+ // `include_snoozed` asks for the rows the Snoozed section shows. The server+ // leaves them out for a client that does not ask, which would otherwise list+ // a snoozed issue as plainly unread.async listInbox(): Promise<InboxItem[]> {- const raw = await this.fetch<unknown>("/api/inbox");+ const raw = await this.fetch<unknown>("/api/inbox?include_snoozed=true");return parseWithFallback(raw, InboxItemListSchema, EMPTY_INBOX_ITEMS, {endpoint: "GET /api/inbox",});@@ -3197,6 +3203,21 @@ export class ApiClient {return this.fetch(`/api/inbox/${id}/unarchive`, { method: "POST" });}+ /**+ * Snooze the item's issue until `until` (an ISO time). Issue-level, like+ * archive: every active row on the issue goes with it.+ */+ async snoozeInbox(id: string, until: string): Promise<void> {+ await this.fetch(`/api/inbox/${id}/snooze`, {+ method: "POST",+ body: JSON.stringify({ until }),+ });+ }++ async unsnoozeInbox(id: string): Promise<void> {+ await this.fetch(`/api/inbox/${id}/unsnooze`, { method: "POST" });+ }+// Raw unread ROW count — not the number any badge shows. The inbox renders// one row per issue, so a single issue with three unread notifications// counts once there and three times here. `getInboxUnreadSummary` is the@@ -3207,10 +3228,10 @@ export class ApiClient {return this.fetch("/api/inbox/unread-count");}- // Cross-workspace unread summary: one entry per workspace the user belongs- // to that has unread inbox items. Backs the workspace-switcher dot for- // OTHER workspaces. Schema-guarded so a contract drift hides the dot rather- // than crashing the sidebar.+ // Cross-workspace inbox summary: one entry per workspace the user belongs+ // to that has unread items or issues waiting on them. Backs the Inbox badge+ // and the workspace-switcher dot for OTHER workspaces. Schema-guarded so a+ // contract drift hides them rather than crashing the sidebar.async getInboxUnreadSummary(): Promise<InboxWorkspaceUnread[]> {const raw = await this.fetch<unknown>("/api/inbox/unread-summary");return parseWithFallback(raw, InboxUnreadSummarySchema, EMPTY_INBOX_UNREAD_SUMMARY, {@@ -3218,10 +3239,6 @@ export class ApiClient {});}- async markAllInboxRead(): Promise<{ count: number }> {- return this.fetch("/api/inbox/mark-all-read", { method: "POST" });- }-/*** Reads every unread notification the caller has on one issue. `count` is* how many rows the server read, or `null` when the response did not say:@@ -3235,16 +3252,22 @@ export class ApiClient {});}- async archiveAllInbox(): Promise<{ count: number }> {- return this.fetch("/api/inbox/archive-all", { method: "POST" });- }-- async archiveAllReadInbox(): Promise<{ count: number }> {- return this.fetch("/api/inbox/archive-all-read", { method: "POST" });- }-- async archiveCompletedInbox(): Promise<{ count: number }> {- return this.fetch("/api/inbox/archive-completed", { method: "POST" });+ /**+ * Archive issues that only carry updates. `groups` are list keys+ * (`issue_id ?? id`). The server re-checks each one and leaves it when it+ * has since gained something addressed to the user or was snoozed; with+ * `readOnly`, also when its newest update is unread.+ */+ async archiveInboxUpdates(groups: readonly string[], readOnly: boolean): Promise<void> {+ for (let start = 0; start < groups.length; start += INBOX_ARCHIVE_UPDATES_MAX_GROUPS) {+ await this.fetch("/api/inbox/archive-updates", {+ method: "POST",+ body: JSON.stringify({+ groups: groups.slice(start, start + INBOX_ARCHIVE_UPDATES_MAX_GROUPS),+ read_only: readOnly,+ }),+ });+ }}// Notification preferencesdiff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 5b0e658c51..cff9eb6075 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -1489,6 +1489,23 @@ describe("InboxUnreadSummarySchema", () => {]);});+ it("carries the needs-you count, and reads a malformed one as absent", () => {+ const parsed = parseWithFallback(+ [+ { workspace_id: "ws-1", count: 2, needs_you: 5 },+ { workspace_id: "ws-2", count: 1, needs_you: "many" },+ { workspace_id: "ws-3", count: 4 },+ ],+ InboxUnreadSummarySchema,+ EMPTY_INBOX_UNREAD_SUMMARY,+ ENDPOINT,+ );+ // An absent count is what an older server sends: the badge then falls+ // back to `count`, so one bad value must not blank every workspace.+ expect(parsed.map((entry) => entry.needs_you)).toEqual([5, undefined, undefined]);+ expect(parsed.map((entry) => entry.count)).toEqual([2, 1, 4]);+ });+it("returns the empty fallback (dot hidden) for a non-array body", () => {expect(parseWithFallback({ rows: [] }, InboxUnreadSummarySchema, EMPTY_INBOX_UNREAD_SUMMARY, ENDPOINT),@@ -1562,6 +1579,29 @@ describe("InboxItemListSchema", () => {expect(parsed).toHaveLength(1);});+ it("carries the section and snooze time, and reads malformed ones as unset", () => {+ const parsed = parseWithFallback(+ [+ row({ id: "a", section: "needs_you", snoozed_until: "2026-06-16T09:00:00Z" }),+ row({ id: "b", section: "updates", snoozed_until: null }),+ row({ id: "c", section: "some_future_section", snoozed_until: 12 }),+ row({ id: "d" }),+ ],+ InboxItemListSchema,+ EMPTY_INBOX_ITEMS,+ ENDPOINT,+ );+ // A section this client does not know must not blank the whole inbox.+ expect(parsed).toHaveLength(4);+ expect(parsed.map((item) => item.section)).toEqual(["needs_you", "updates", undefined, undefined]);+ expect(parsed.map((item) => item.snoozed_until)).toEqual([+ "2026-06-16T09:00:00Z",+ null,+ undefined,+ undefined,+ ]);+ });+it("accepts rows that omit the nullable optional fields", () => {const { body, issue_id, ...withoutOptionals } = row();void body;diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 81ce8287fe..769951d64b 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -3075,6 +3075,11 @@ export const InboxUnreadSummarySchema = z.array(.object({workspace_id: z.string(),count: z.number(),+ // Absent from a server that predates the sectioned Inbox. A value that+ // is not a number is dropped the same way, so the badge falls back to+ // `count` instead of the whole summary failing.+ needs_you: z.number().optional().catch(undefined),+ next_wake_at: z.string().optional().catch(undefined),}).loose(),);@@ -3178,6 +3183,10 @@ export const InboxItemListSchema = z.array(read: z.boolean(),archived: z.boolean(),created_at: z.string(),+ // Absent from a server that predates the sectioned Inbox. Neither may+ // fail the row: an unknown section or a malformed time reads as unset.+ section: z.enum(["needs_you", "updates"]).nullish().catch(undefined),+ snoozed_until: z.string().nullish().catch(undefined),}).loose(),);diff --git a/packages/core/command-bar/context-store.ts b/packages/core/command-bar/context-store.tsindex 6ffdc6e2ca..a132d23bd5 100644--- a/packages/core/command-bar/context-store.ts+++ b/packages/core/command-bar/context-store.ts@@ -33,8 +33,6 @@ export type CommandBarContext =item: InboxItem | null;archive: (id: string) => void;markUnread: (id: string) => void;- markAllRead: () => void;- archiveAllRead: () => void;}| {kind: "chat";diff --git a/packages/core/inbox/filter-store.test.ts b/packages/core/inbox/filter-store.test.tsindex 2dec0acc7c..81bfe30dcc 100644--- a/packages/core/inbox/filter-store.test.ts+++ b/packages/core/inbox/filter-store.test.ts@@ -1,9 +1,10 @@// @vitest-environment nodeimport { beforeEach, describe, expect, it } from "vitest";-import type { InboxItem } from "../types";+import type { InboxItem, Label } from "../types";import {EMPTY_INBOX_FILTERS,+ activeInboxFilterSupport,archivedInboxQuery,effectiveInboxFilters,filterInboxItems,@@ -12,6 +13,8 @@ import {inboxFiltersForPrioritySupport,inboxFilterCount,inboxIssueFieldsSupport,+ inboxIssueMatches,+ inboxIssueProjection,inboxPriorityFilterSupport,inboxReceivedAfter,inboxTypeGroup,@@ -201,11 +204,24 @@ describe("issue dimensions", () => {expect(run({ dueDates: ["overdue", "none"] })).toEqual(["bare"]);});- it("keeps or drops issues by whether an agent is on them", () => {- const filters = (agent: InboxFilters["agent"]) => ({ ...EMPTY_INBOX_FILTERS, agent });- const activeIssueIds = new Set(["issue-tracked"]);- expect(ids(filterInboxItems(rows, filters("running"), { activeIssueIds }))).toEqual(["tracked"]);- expect(ids(filterInboxItems(rows, filters("idle"), { activeIssueIds }))).toEqual(["bare"]);+ it("asks an issue that has no notification the same questions", () => {+ // A "Working" row is an issue, not a notification: it is filtered by the+ // issue fields alone, read off the issue itself.+ const issue = inboxIssueProjection({+ id: "issue-working", status: "in_progress", priority: "high", project_id: "project-1",+ assignee_type: "agent", assignee_id: "agent-1", due_date: "2026-08-24",+ labels: [{ id: "bug" } as Label],+ });+ const matches = (filters: Partial<InboxFilters>) =>+ inboxIssueMatches(issue, { ...EMPTY_INBOX_FILTERS, ...filters }, new Date(2026, 7, 24, 12));++ expect(matches({})).toBe(true);+ expect(matches({ statuses: ["in_progress"], projects: ["project-1"], labels: ["bug"], dueDates: ["today"] })).toBe(true);+ expect(matches({ assignees: ["agent:agent-1"] })).toBe(true);+ expect(matches({ statuses: ["done"] })).toBe(false);+ expect(matches({ labels: ["bug"], negated: ["label"] })).toBe(false);+ // The notification dimensions have nothing to ask an issue.+ expect(matches({ types: ["mention"], actors: ["system"], received: "today", unreadOnly: true })).toBe(true);});});@@ -248,45 +264,6 @@ describe("unread filtering", () => {});});-describe("pinned row with agent filtering", () => {- it("keeps the open notification after an agent starts on its issue", () => {- const filters = { ...EMPTY_INBOX_FILTERS, agent: "idle" as const };- const opened = item("opened", "todo", "high", { issue_id: "issue-opened" });- const other = item("other", "todo", "high", { issue_id: "issue-other" });- const activeIssueIds = new Set(["issue-opened", "issue-other"]);-- expect(- ids(filterInboxItems([opened, other], filters, {- activeIssueIds,- pinnedAgentKey: "issue-opened",- })),- ).toEqual(["opened"]);-- // Each pin crosses only its own dimension.- expect(- filterInboxItems([opened], filters, {- activeIssueIds,- pinnedUnreadKey: "issue-opened",- }),- ).toEqual([]);- expect(- filterInboxItems(- [{ ...opened, read: true }],- { ...filters, agent: null, unreadOnly: true },- { pinnedAgentKey: "issue-opened" },- ),- ).toEqual([]);-- // The pin still never crosses an explicit issue filter.- expect(- filterInboxItems([opened], { ...filters, statuses: ["done"] }, {- activeIssueIds,- pinnedAgentKey: "issue-opened",- }),- ).toEqual([]);- });-});-describe("inboxFacetCounts", () => {it("counts each value as if it alone were selected", () => {const rows = [@@ -323,20 +300,28 @@ describe("backend capability", () => {expect(inboxIssueFieldsSupport([item("legacy", "todo", "high", { issue_label_ids: undefined })])).toBe("unsupported");});+ it("holds the main list's selection with no notification, for the Working rows left", () => {+ expect(activeInboxFilterSupport([])).toEqual({ priority: "supported", issueFields: "supported" });+ expect(activeInboxFilterSupport([item("legacy", "todo", undefined, { issue_label_ids: undefined })])).toEqual({+ priority: "unsupported",+ issueFields: "unsupported",+ });+ });+it("keeps unproven dimensions dormant, and on the archive everything an old server would ignore", () => {const filters: InboxFilters = {...EMPTY_INBOX_FILTERS,- types: ["mention"], statuses: ["done"], projects: ["p"], agent: "idle",+ types: ["mention"], statuses: ["done"], projects: ["p"],negated: ["status"], received: "today",};expect(effectiveInboxFilters(filters, { priority: "supported", issueFields: "unknown" })).toEqual({- ...filters, projects: [],+ ...filters, projects: [], types: [], received: null,});expect(effectiveInboxFilters(filters, { priority: "supported", issueFields: "unsupported", archived: true })).toEqual({...EMPTY_INBOX_FILTERS,});expect(effectiveInboxFilters(filters, { priority: "supported", issueFields: "supported", archived: true })).toEqual({- ...filters, agent: null,+ ...filters,});});});@@ -428,16 +413,14 @@ describe("useInboxFilterStore", () => {expect(sanitizeInboxFilters(filters).negated).toEqual([]);});- it("selects a single received window and agent state, toggling off on reselect", () => {+ it("selects a single received window, toggling off on reselect", () => {const store = useInboxFilterStore.getState();store.setReceived("ws-1", "today");store.setReceived("ws-1", "last_7_days");- store.setAgent("ws-1", "running");expect(useInboxFilterStore.getState().filtersByWorkspace["ws-1"]).toMatchObject({- received: "last_7_days", agent: "running",+ received: "last_7_days",});useInboxFilterStore.getState().setReceived("ws-1", "last_7_days");- useInboxFilterStore.getState().clearFilter("ws-1", "agent");expect(useInboxFilterStore.getState().filtersByWorkspace["ws-1"]).toBeUndefined();});@@ -453,13 +436,13 @@ describe("useInboxFilterStore", () => {});describe("sanitizeInboxFilters", () => {- it("rebuilds a stored entry, dropping unknown values and carrying the old idle toggle over", () => {+ it("rebuilds a stored entry, dropping unknown values and dimensions that no longer exist", () => {expect(sanitizeInboxFilters({- statuses: ["todo", 3], types: ["mention", "bogus"], idleOnly: true,+ statuses: ["todo", 3], types: ["mention", "bogus"], agent: "idle",negated: ["status", "label", "creator"], received: "yesterday",})).toEqual({...EMPTY_INBOX_FILTERS,- statuses: ["todo"], types: ["mention"], agent: "idle", negated: ["status"],+ statuses: ["todo"], types: ["mention"], negated: ["status"],});expect(sanitizeInboxFilters(null)).toEqual(EMPTY_INBOX_FILTERS);});diff --git a/packages/core/inbox/filter-store.ts b/packages/core/inbox/filter-store.tsindex 9393e924f7..b2c0b55951 100644--- a/packages/core/inbox/filter-store.ts+++ b/packages/core/inbox/filter-store.ts@@ -10,7 +10,6 @@ import {sanitizeInboxFilters,toggleInboxFilterValue,withoutInboxFilter,- type InboxAgentFilter,type InboxFilterKey,type InboxFilters,type InboxListDimension,@@ -30,7 +29,6 @@ interface InboxFilterState {toggleUnreadOnly: (wsId: string) => void;/** Selecting the current value again clears the dimension. */setReceived: (wsId: string, received: InboxReceivedFilter) => void;- setAgent: (wsId: string, agent: InboxAgentFilter) => void;clearFilter: (wsId: string, key: InboxFilterKey) => void;clearPriorityFilters: (wsId: string) => void;clearIssueFieldFilters: (wsId: string) => void;@@ -96,13 +94,6 @@ export const useInboxFilterStore = create<InboxFilterState>()(received: current.received === received ? null : received,})),),- setAgent: (wsId, agent) =>- set((state) =>- update(state, wsId, (current) => ({- ...current,- agent: current.agent === agent ? null : agent,- })),- ),clearFilter: (wsId, key) =>set((state) => update(state, wsId, (current) => withoutInboxFilter(current, key))),clearPriorityFilters: (wsId) =>diff --git a/packages/core/inbox/filters.ts b/packages/core/inbox/filters.tsindex 12492348dd..4f92bb0e91 100644--- a/packages/core/inbox/filters.ts+++ b/packages/core/inbox/filters.ts@@ -5,7 +5,7 @@ import {dueDateMatches,type DueDateFilter,} from "../issues/stores/filter-tree";-import type { InboxItem, InboxItemType, IssuePriority, IssueStatus } from "../types";+import type { InboxItem, InboxItemType, Issue, IssuePriority, IssueStatus } from "../types";import { groupInboxRows, sortInboxNewestFirst, withCommentAnchor } from "./group";/**@@ -49,6 +49,7 @@ const TYPE_GROUP: Partial<Record<InboxItemType, InboxTypeGroup>> = {children_done: "change",task_completed: "run",task_failed: "run",+ task_cancelled: "run",agent_blocked: "run",agent_completed: "run",};@@ -70,10 +71,6 @@ const RECEIVED_DAYS: Record<InboxReceivedFilter, number> = {last_30_days: 30,};-/** Whether an agent is running or queued on the issue. Active inbox only. */-export type InboxAgentFilter = "running" | "idle";-export const INBOX_AGENT_FILTERS: readonly InboxAgentFilter[] = ["running", "idle"];-/** Multi-value dimensions; each one can be flipped to "is not". */export type InboxListDimension =| "type"@@ -119,7 +116,6 @@ export interface InboxFilters {readonly assignees: readonly string[];readonly labels: readonly string[];readonly dueDates: readonly DueDateFilter[];- readonly agent: InboxAgentFilter | null;/** Dimensions whose values are excluded rather than required. */readonly negated: readonly InboxListDimension[];}@@ -138,17 +134,21 @@ export const INBOX_DIMENSION_FIELD: Record<InboxListDimension, ListField> = {};/** One chip / one "active" row: a list dimension or a single-choice one. */-export type InboxFilterKey = InboxListDimension | "received" | "unread" | "agent";+export type InboxFilterKey = InboxListDimension | "received" | "unread";++/**+ * What the main Inbox can be narrowed by: the issue. Its sections already say+ * what kind of notification a row is and whether it is read, so the dimensions+ * about the notification belong to the archive, which is one flat list.+ */+export const INBOX_NOTIFICATION_FILTER_KEYS: readonly InboxFilterKey[] = ["unread", "type", "actor", "received"];export function inboxFilterValues(filters: InboxFilters, dimension: InboxListDimension): readonly string[] {return filters[INBOX_DIMENSION_FIELD[dimension]];}-/**- * The server-filtered archive has no agent dimension, so `agent` never- * reaches its endpoints or query keys.- */-export type ArchivedInboxFilters = Omit<InboxFilters, "agent">;+/** The filters the server-filtered archive is asked with. */+export type ArchivedInboxFilters = InboxFilters;/*** Stable identity for "who this notification came from", used as the value of@@ -193,7 +193,6 @@ export const EMPTY_INBOX_FILTERS: InboxFilters = Object.freeze({assignees: Object.freeze([]),labels: Object.freeze([]),dueDates: Object.freeze([]),- agent: null,negated: Object.freeze([]),});@@ -206,7 +205,6 @@ export function activeInboxFilterKeys(filters: InboxFilters): InboxFilterKey[] {if (filters.received) keys.push("received");if (filters.statuses.length > 0) keys.push("status");if (filters.priorities.length > 0) keys.push("priority");- if (filters.agent) keys.push("agent");if (filters.projects.length > 0) keys.push("project");if (filters.assignees.length > 0) keys.push("assignee");if (filters.labels.length > 0) keys.push("label");@@ -237,8 +235,6 @@ export function withoutInboxFilter(filters: InboxFilters, key: InboxFilterKey):return { ...filters, unreadOnly: false };case "received":return { ...filters, received: null };- case "agent":- return { ...filters, agent: null };default:return {...filters,@@ -249,7 +245,6 @@ export function withoutInboxFilter(filters: InboxFilters, key: InboxFilterKey):}const RECEIVED_SET = new Set<string>(INBOX_RECEIVED_FILTERS);-const AGENT_SET = new Set<string>(INBOX_AGENT_FILTERS);const TYPE_SET = new Set<string>(INBOX_TYPE_GROUPS);const DUE_SET = new Set<string>(DUE_DATE_FILTERS);const DIMENSION_SET = new Set<string>(INBOX_LIST_DIMENSIONS);@@ -280,11 +275,6 @@ export function sanitizeInboxFilters(raw: unknown): InboxFilters {assignees: stringList(value.assignees),labels: stringList(value.labels),dueDates: stringList(value.dueDates, DUE_SET) as DueDateFilter[],- agent: typeof value.agent === "string" && AGENT_SET.has(value.agent)- ? (value.agent as InboxAgentFilter)- : value.idleOnly === true- ? "idle"- : null,negated: stringList(value.negated, DIMENSION_SET) as InboxListDimension[],};return {@@ -325,6 +315,20 @@ export function inboxIssueFieldsSupport(: "unsupported";}+/**+ * Capability of the main Inbox list, for the page, its preview and the filter+ * menu alike. With no notification there is nothing to probe, but nothing for+ * the server to answer either: every row left is a run in "Working", matched+ * against its issue on the client. The selection holds for those rows, and an+ * older server is still caught by the first notification that arrives.+ */+export function activeInboxFilterSupport(+ items: readonly InboxItem[],+): { priority: InboxPriorityFilterSupport; issueFields: InboxFilterSupport } {+ if (items.length === 0) return { priority: "supported", issueFields: "supported" };+ return { priority: inboxPriorityFilterSupport(items), issueFields: inboxIssueFieldsSupport(items) };+}+/** Ignore a stale priority selection until the backend capability is proven. */export function inboxFiltersForPrioritySupport(filters: InboxFilters,@@ -341,8 +345,11 @@ export function inboxFiltersForPrioritySupport(* than hiding every row: priority and the issue fields until the server is* known to send them, and on the archive also everything only that newer* server understands — type, received, and "is not" — since an older one- * would ignore them and answer a different question. The archive has no- * agent dimension at all.+ * would ignore them and answer a different question.+ *+ * The two views share one stored selection. The main Inbox only reads its+ * issue dimensions (INBOX_NOTIFICATION_FILTER_KEYS), so a notification+ * dimension picked in the archive is dormant there rather than lost.*/export function effectiveInboxFilters(filters: InboxFilters,@@ -359,15 +366,10 @@ export function effectiveInboxFilters(: [...INBOX_ISSUE_FIELD_DIMENSIONS];next = dormant.reduce(withoutInboxFilter, next);}- if (archived && next.agent) next = withoutInboxFilter(next, "agent");+ if (!archived) next = INBOX_NOTIFICATION_FILTER_KEYS.reduce(withoutInboxFilter, next);return next;}-/** @deprecated Use `effectiveInboxFilters` with `archived: true`. */-export function inboxFiltersForArchive(filters: InboxFilters): InboxFilters {- return filters.agent ? withoutInboxFilter(filters, "agent") : filters;-}-/** Start of the received window, at a local midnight so it holds all day. */export function inboxReceivedAfter(received: InboxReceivedFilter, now: Date = new Date()): Date {const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());@@ -405,68 +407,95 @@ export function archivedInboxQuery(return params;}-const EMPTY_ISSUE_IDS: ReadonlySet<string> = new Set();-/** Page state `filterInboxItems` needs beyond the selected filters. */export interface InboxFilterContext {- /** Issues an agent is running or queued on. Read only by `agent`. */- readonly activeIssueIds?: ReadonlySet<string>;/*** Group key (`issue_id ?? id`) of the open notification, pinned against the* unread dimension only. Set by the page after opening marks the row read.*/readonly pinnedUnreadKey?: string | null;- /**- * Group key of the open notification, pinned against the agent dimension- * only. Set by the page once the row was opened while it matched.- */- readonly pinnedAgentKey?: string | null;/** Clock for the received and due-date dimensions. */readonly now?: Date;}+/** The issue fields an inbox row carries, which the issue dimensions read. */+export type InboxIssueProjection = Pick<+ InboxItem,+ | "issue_id"+ | "issue_status"+ | "issue_priority"+ | "issue_project_id"+ | "issue_assignee_type"+ | "issue_assignee_id"+ | "issue_due_date"+ | "issue_label_ids"+>;+type RowTest = (item: InboxItem) => boolean;+type IssueTest = (issue: InboxIssueProjection) => boolean;-/** Values a row has in a dimension; null when it has no issue to ask. */-function dimensionValues(item: InboxItem, dimension: InboxListDimension, today: string): readonly string[] | null {- switch (dimension) {- case "type":- return [inboxTypeGroup(item.type)];- case "actor": {- const key = inboxActorKey(item);- return key ? [key] : [];- }- default:- break;- }- if (item.issue_id == null) return null;+type NotificationDimension = "type" | "actor";+type IssueDimension = Exclude<InboxListDimension, NotificationDimension>;++const NOTIFICATION_DIMENSIONS: readonly NotificationDimension[] = ["type", "actor"];+const ISSUE_DIMENSIONS: readonly IssueDimension[] = [+ "status",+ "priority",+ "project",+ "assignee",+ "label",+ "dueDate",+];++function isNotificationDimension(dimension: InboxListDimension): dimension is NotificationDimension {+ return dimension === "type" || dimension === "actor";+}++/** Values a notification has in a dimension about itself. */+function notificationValues(item: InboxItem, dimension: NotificationDimension): readonly string[] {+ if (dimension === "type") return [inboxTypeGroup(item.type)];+ const key = inboxActorKey(item);+ return key ? [key] : [];+}++/** Values an issue has in a dimension; null when there is no issue to ask. */+function issueValues(issue: InboxIssueProjection, dimension: IssueDimension, today: string): readonly string[] | null {+ if (issue.issue_id == null) return null;switch (dimension) {case "status":- return item.issue_status == null ? null : [item.issue_status];+ return issue.issue_status == null ? null : [issue.issue_status];case "priority":- return item.issue_priority == null ? null : [item.issue_priority];+ return issue.issue_priority == null ? null : [issue.issue_priority];case "project":- return [item.issue_project_id ?? FILTER_NONE_VALUE];+ return [issue.issue_project_id ?? FILTER_NONE_VALUE];case "assignee":return [- item.issue_assignee_type && item.issue_assignee_id- ? `${item.issue_assignee_type}:${item.issue_assignee_id}`+ issue.issue_assignee_type && issue.issue_assignee_id+ ? `${issue.issue_assignee_type}:${issue.issue_assignee_id}`: FILTER_NONE_VALUE,];case "label":- return item.issue_label_ids ?? [];+ return issue.issue_label_ids ?? [];case "dueDate":- return DUE_DATE_FILTERS.filter((bucket) => dueDateMatches(item.issue_due_date, bucket, today));+ return DUE_DATE_FILTERS.filter((bucket) => dueDateMatches(issue.issue_due_date, bucket, today));}}-function dimensionTest(filters: InboxFilters, dimension: InboxListDimension, today: string): RowTest | null {+function dimensionValues(item: InboxItem, dimension: InboxListDimension, today: string): readonly string[] | null {+ return isNotificationDimension(dimension) ? notificationValues(item, dimension) : issueValues(item, dimension, today);+}++function dimensionTest<Row>(+ filters: InboxFilters,+ dimension: InboxListDimension,+ valuesOf: (row: Row) => readonly string[] | null,+): ((row: Row) => boolean) | null {const selected = inboxFilterValues(filters, dimension);if (selected.length === 0) return null;const set = new Set(selected);const negated = filters.negated.includes(dimension);- return (item) => {- const values = dimensionValues(item, dimension, today);+ return (row) => {+ const values = valuesOf(row);// A notification without an issue answers no issue question, "is not"// included.if (values === null) return false;@@ -474,44 +503,34 @@ function dimensionTest(filters: InboxFilters, dimension: InboxListDimension, tod};}-const NOTIFICATION_DIMENSIONS: readonly InboxListDimension[] = ["type", "actor"];-const ISSUE_DIMENSIONS: readonly InboxListDimension[] = [- "status",- "priority",- "project",- "assignee",- "label",- "dueDate",-];-interface CompiledInboxFilters {/** Per-notification tests, keyed so a facet can leave its own out. */notification: Map<InboxListDimension | "received", RowTest>;- issue: Map<InboxListDimension, RowTest>;+ issue: Map<InboxListDimension, IssueTest>;}function compile(filters: InboxFilters, now: Date): CompiledInboxFilters {const today = toDateOnly(now);const notification = new Map<InboxListDimension | "received", RowTest>();for (const dimension of NOTIFICATION_DIMENSIONS) {- const test = dimensionTest(filters, dimension, today);+ const test = dimensionTest(filters, dimension, (item: InboxItem) => notificationValues(item, dimension));if (test) notification.set(dimension, test);}if (filters.received) {const after = inboxReceivedAfter(filters.received, now).getTime();notification.set("received", (item) => new Date(item.created_at).getTime() >= after);}- const issue = new Map<InboxListDimension, RowTest>();+ const issue = new Map<InboxListDimension, IssueTest>();for (const dimension of ISSUE_DIMENSIONS) {- const test = dimensionTest(filters, dimension, today);+ const test = dimensionTest(filters, dimension, (row: InboxIssueProjection) => issueValues(row, dimension, today));if (test) issue.set(dimension, test);}return { notification, issue };}-function passes(- tests: Map<string, RowTest>,- item: InboxItem,+function passes<Row>(+ tests: Map<string, (row: Row) => boolean>,+ item: Row,skip?: string,): boolean {for (const [key, test] of tests) {@@ -520,14 +539,32 @@ function passes(return true;}-function agentMatches(- item: InboxItem,- agent: InboxAgentFilter | null,- activeIssueIds: ReadonlySet<string>,+/** The issue fields of an issue, shaped like an inbox row carries them. */+export function inboxIssueProjection(+ issue: Pick<Issue, "id" | "status" | "priority" | "project_id" | "assignee_type" | "assignee_id" | "due_date" | "labels">,+): InboxIssueProjection {+ return {+ issue_id: issue.id,+ issue_status: issue.status,+ issue_priority: issue.priority,+ issue_project_id: issue.project_id,+ issue_assignee_type: issue.assignee_type,+ issue_assignee_id: issue.assignee_id,+ issue_due_date: issue.due_date,+ issue_label_ids: (issue.labels ?? []).map((label) => label.id),+ };+}++/**+ * Whether an issue passes the issue dimensions: the test for a row that has+ * no notification to ask, such as an issue an agent is working on.+ */+export function inboxIssueMatches(+ issue: InboxIssueProjection,+ filters: InboxFilters,+ now: Date = new Date(),): boolean {- if (!agent) return true;- if (item.issue_id == null) return false;- return activeIssueIds.has(item.issue_id) === (agent === "running");+ return passes(compile(filters, now).issue, issue);}/**@@ -542,30 +579,23 @@ function agentMatches(* notification filter that is simply the newest row, as deduplication shows.** The issue dimensions — status, priority, project, assignee, label, due- * date, agent — ask about the issue, so a notification without one never- * matches them, "is not" included. `unreadOnly` reads the rendered row. The+ * date — ask about the issue, so a notification without one never matches+ * them, "is not" included. `unreadOnly` reads the rendered row. The* unread badge (`useInboxUnreadCount`) counts the same newest-per-issue rows* from the server's summary endpoint, so "only unread" and the number next to* Inbox still cannot disagree when no other filter is set.*- * `pinnedUnreadKey` / `pinnedAgentKey` name the notification whose detail is- * open. Opening an unread notification marks it read, and replying from the- * detail can start or finish an agent on its issue; either would otherwise- * remove the row the user is working in from under the detail pane. The- * pinned row therefore survives the unread and agent dimensions only, and- * each pin only crosses its own dimension. Every other dimension always- * applies, because changing one is an explicit request to filter the- * notification itself out.+ * `pinnedUnreadKey` names the notification whose detail is open. Opening an+ * unread notification marks it read, which would otherwise remove the row the+ * user is reading from under the detail pane. The pinned row therefore+ * survives the unread dimension only. Every other dimension always applies,+ * because changing one is an explicit request to filter the notification+ * itself out.*/export function filterInboxItems(items: readonly InboxItem[],filters: InboxFilters,- {- activeIssueIds = EMPTY_ISSUE_IDS,- pinnedUnreadKey = null,- pinnedAgentKey = null,- now = new Date(),- }: InboxFilterContext = {},+ { pinnedUnreadKey = null, now = new Date() }: InboxFilterContext = {},): InboxItem[] {const tests = compile(filters, now);const out: InboxItem[] = [];@@ -577,10 +607,7 @@ export function filterInboxItems(!filters.unreadOnly ||row.read !== true ||(pinnedUnreadKey != null && key === pinnedUnreadKey);- const matchesAgent =- agentMatches(row, filters.agent, activeIssueIds) ||- (pinnedAgentKey != null && key === pinnedAgentKey);- if (matchesUnread && matchesAgent) out.push(withCommentAnchor(row, group));+ if (matchesUnread) out.push(withCommentAnchor(row, group));}return sortInboxNewestFirst(out);}@@ -610,10 +637,7 @@ function bump(counts: Map<string, number>, key: string) {export function inboxFacetCounts(items: readonly InboxItem[],filters: InboxFilters,- {- activeIssueIds = EMPTY_ISSUE_IDS,- now = new Date(),- }: Pick<InboxFilterContext, "activeIssueIds" | "now"> = {},+ { now = new Date() }: Pick<InboxFilterContext, "now"> = {},): InboxFacetCounts {const tests = compile(filters, now);const today = toDateOnly(now);@@ -637,7 +661,7 @@ export function inboxFacetCounts(const readMatches = (item: InboxItem) => !filters.unreadOnly || item.read !== true;for (const group of groupInboxRows(items)) {const head = group[0];- if (!head || !agentMatches(head, filters.agent, activeIssueIds)) continue;+ if (!head) continue;const issueOk = passes(tests.issue, head);const row = group.find((item) => passes(tests.notification, item));diff --git a/packages/core/inbox/index.ts b/packages/core/inbox/index.tsindex 870d3e34b7..a113ddca6c 100644--- a/packages/core/inbox/index.ts+++ b/packages/core/inbox/index.ts@@ -1,3 +1,5 @@export * from "./queries";export * from "./mutations";export * from "./ws-updaters";+export * from "./sections";+export * from "./snooze";diff --git a/packages/core/inbox/mutations.test.tsx b/packages/core/inbox/mutations.test.tsxindex 3ca0d260a3..aed3045c5e 100644--- a/packages/core/inbox/mutations.test.tsx+++ b/packages/core/inbox/mutations.test.tsx@@ -9,7 +9,7 @@ import type { ReactNode } from "react";import { setApiInstance } from "../api";import type { ApiClient } from "../api/client";import type { InboxItem, InboxWorkspaceUnread } from "../types";-import { useDeleteInbox, useMarkInboxRead, useMarkInboxUnread, useMarkIssueInboxRead, useUnarchiveInbox } from "./mutations";+import { useArchiveInboxUpdates, useDeleteInbox, useMarkInboxRead, useMarkInboxUnread, useMarkIssueInboxRead, useSnoozeInbox, useUnarchiveInbox, useUnsnoozeInbox } from "./mutations";import { inboxKeys, useInboxUnreadCount } from "./queries";import { onInboxSummaryInvalidate } from "./ws-updaters";import { createQueryClient } from "../query-client";@@ -398,6 +398,157 @@ describe("useUnarchiveInbox", () => {* (MUL-6967). These pin the property that replaces the old local recompute:* whatever races, the badge converges on the server's value.*/+describe("useSnoozeInbox", () => {+ const UNTIL = "2026-06-18T01:00:00.000Z";+ let queryClient: QueryClient;+ let snoozeInbox: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ snoozeInbox = vi.fn(async () => undefined);+ setApiInstance({ snoozeInbox } as unknown as ApiClient);+ queryClient.setQueryData(inboxKeys.list(WORKSPACE_ID), [+ item({ id: "inbox-1", issue_id: "issue-1", archived: false, read: true }),+ item({ id: "inbox-2", issue_id: "issue-1", archived: false, read: true }),+ item({ id: "inbox-3", issue_id: "issue-1", archived: true, read: true }),+ item({ id: "inbox-4", issue_id: "issue-2", archived: false, read: true }),+ ]);+ queryClient.setQueryData(inboxKeys.unreadSummary(), [{ workspace_id: WORKSPACE_ID, count: 1 }]);+ });++ it("puts every active notification of the issue away at once, and makes the row unread", async () => {+ let finish!: () => void;+ snoozeInbox.mockImplementation(() => new Promise<void>((resolve) => { finish = resolve; }));+ const { result } = renderHook(() => useSnoozeInbox(), { wrapper: createWrapper(queryClient) });++ act(() => result.current.mutate({ id: "inbox-1", until: UNTIL }));+ await waitFor(() => expect(snoozeInbox).toHaveBeenCalledWith("inbox-1", UNTIL));++ expect(listCache(queryClient).map((row) => [row.id, row.snoozed_until ?? null, row.read])).toEqual([+ ["inbox-1", UNTIL, false],+ ["inbox-2", UNTIL, true],+ // Archived, and another issue's: neither is touched.+ ["inbox-3", null, true],+ ["inbox-4", null, true],+ ]);++ await act(async () => finish());+ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ // The badge is the server's to count: a snoozed issue leaves it.+ await waitFor(() => {+ expect(queryClient.getQueryState(inboxKeys.list(WORKSPACE_ID))?.isInvalidated).toBe(true);+ expect(queryClient.getQueryState(inboxKeys.unreadSummary())?.isInvalidated).toBe(true);+ });+ });++ it("puts the issue back when the request fails", async () => {+ snoozeInbox.mockRejectedValue(new Error("offline"));+ const { result } = renderHook(() => useSnoozeInbox(), { wrapper: createWrapper(queryClient) });++ act(() => result.current.mutate({ id: "inbox-1", until: UNTIL }));+ await waitFor(() => expect(result.current.isError).toBe(true));++ expect(listCache(queryClient).every((row) => row.snoozed_until == null && row.read)).toBe(true);+ });+});++describe("useArchiveInboxUpdates", () => {+ let queryClient: QueryClient;+ let archiveInboxUpdates: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ archiveInboxUpdates = vi.fn(async () => undefined);+ setApiInstance({ archiveInboxUpdates } as unknown as ApiClient);+ queryClient.setQueryData(inboxKeys.list(WORKSPACE_ID), [+ item({ id: "inbox-1", issue_id: "issue-1", archived: false, read: true }),+ item({ id: "inbox-2", issue_id: "issue-1", archived: false, read: true }),+ item({ id: "inbox-3", issue_id: "issue-2", archived: false }),+ item({ id: "inbox-4", issue_id: null, archived: false, read: true }),+ ]);+ });++ it("takes the named issues out of the list at once, a notification without an issue by its own id", async () => {+ let finish!: () => void;+ archiveInboxUpdates.mockImplementation(() => new Promise<void>((resolve) => { finish = resolve; }));+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");+ const { result } = renderHook(() => useArchiveInboxUpdates(), { wrapper: createWrapper(queryClient) });++ act(() => result.current.mutate({ groups: ["issue-1", "inbox-4"], readOnly: true }));+ await waitFor(() => expect(archiveInboxUpdates).toHaveBeenCalledWith(["issue-1", "inbox-4"], true));++ expect(listCache(queryClient).map((row) => [row.id, row.archived])).toEqual([+ ["inbox-1", true],+ ["inbox-2", true],+ ["inbox-3", false],+ ["inbox-4", true],+ ]);++ // The server decides what really left, so the list is read back.+ await act(async () => finish());+ await waitFor(() =>+ expect(invalidate).toHaveBeenCalledWith(expect.objectContaining({ queryKey: inboxKeys.all(WORKSPACE_ID) })),+ );+ });++ it("puts the rows back when the request fails", async () => {+ archiveInboxUpdates.mockRejectedValue(new Error("offline"));+ const { result } = renderHook(() => useArchiveInboxUpdates(), { wrapper: createWrapper(queryClient) });++ act(() => result.current.mutate({ groups: ["issue-1"], readOnly: false }));+ await waitFor(() => expect(result.current.isError).toBe(true));++ expect(listCache(queryClient).every((row) => !row.archived)).toBe(true);+ });+});++describe("useUnsnoozeInbox", () => {+ const UNTIL = "2026-06-18T01:00:00.000Z";+ let queryClient: QueryClient;+ let unsnoozeInbox: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ unsnoozeInbox = vi.fn(async () => undefined);+ setApiInstance({ unsnoozeInbox } as unknown as ApiClient);+ queryClient.setQueryData(inboxKeys.list(WORKSPACE_ID), [+ item({ id: "inbox-1", issue_id: "issue-1", archived: false, snoozed_until: UNTIL }),+ item({ id: "inbox-2", issue_id: "issue-1", archived: false, snoozed_until: UNTIL }),+ item({ id: "inbox-4", issue_id: "issue-2", archived: false, snoozed_until: UNTIL }),+ ]);+ });++ it("brings the whole issue back now and leaves other snoozes alone", async () => {+ const { result } = renderHook(() => useUnsnoozeInbox(), { wrapper: createWrapper(queryClient) });++ act(() => result.current.mutate("inbox-2"));+ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ expect(unsnoozeInbox).toHaveBeenCalledWith("inbox-2");+ expect(listCache(queryClient).map((row) => [row.id, row.snoozed_until ?? null])).toEqual([+ ["inbox-1", null],+ ["inbox-2", null],+ ["inbox-4", UNTIL],+ ]);+ });++ it("keeps the issue snoozed when the request fails", async () => {+ unsnoozeInbox.mockRejectedValue(new Error("offline"));+ const { result } = renderHook(() => useUnsnoozeInbox(), { wrapper: createWrapper(queryClient) });++ act(() => result.current.mutate("inbox-2"));+ await waitFor(() => expect(result.current.isError).toBe(true));++ expect(listCache(queryClient).every((row) => row.snoozed_until === UNTIL)).toBe(true);+ });+});+describe("unread summary is server-owned", () => {let queryClient: QueryClient;diff --git a/packages/core/inbox/mutations.ts b/packages/core/inbox/mutations.tsindex 72d3d3160e..7538c2bb81 100644--- a/packages/core/inbox/mutations.ts+++ b/packages/core/inbox/mutations.ts@@ -170,6 +170,67 @@ export function useArchiveInbox() {});}+/**+ * Snooze an issue until a time. Issue-level, like archive: every active+ * notification on the issue is put away with it, and the one snoozed from is+ * unread again so it reads as new when it comes back.+ */+export function useSnoozeInbox() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: ({ id, until }: { id: string; until: string }) => api.snoozeInbox(id, until),+ onMutate: async ({ id, until }) => {+ await qc.cancelQueries({ queryKey: inboxKeys.list(wsId) });+ const prev = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));+ const issueId = prev?.find((item) => item.id === id)?.issue_id;+ qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), (old) =>+ old?.map((item) => {+ if (item.archived) return item;+ if (item.id === id) return { ...item, snoozed_until: until, read: false };+ return issueId && item.issue_id === issueId ? { ...item, snoozed_until: until } : item;+ }),+ );+ return { prev };+ },+ onError: (_err, _vars, ctx) => {+ if (ctx?.prev) qc.setQueryData(inboxKeys.list(wsId), ctx.prev);+ },+ onSettled: () => {+ // A snoozed issue leaves the badge until it comes back.+ refreshInboxAfterWrite(qc, wsId);+ },+ });+}++/** Bring a snoozed issue back now. */+export function useUnsnoozeInbox() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: (id: string) => api.unsnoozeInbox(id),+ onMutate: async (id) => {+ await qc.cancelQueries({ queryKey: inboxKeys.list(wsId) });+ const prev = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));+ const issueId = prev?.find((item) => item.id === id)?.issue_id;+ qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), (old) =>+ old?.map((item) =>+ !item.archived && (item.id === id || (issueId && item.issue_id === issueId))+ ? { ...item, snoozed_until: null }+ : item,+ ),+ );+ return { prev };+ },+ onError: (_err, _id, ctx) => {+ if (ctx?.prev) qc.setQueryData(inboxKeys.list(wsId), ctx.prev);+ },+ onSettled: () => {+ refreshInboxAfterWrite(qc, wsId);+ },+ });+}+export function useDeleteInbox() {const qc = useQueryClient();const wsId = useWorkspaceId();@@ -220,17 +281,28 @@ export function useUnarchiveInbox() {});}-export function useMarkAllInboxRead() {+/**+ * Move issues that only carry updates to the archive: what reading an update+ * comes to (`readOnly`), and what clearing the section does to the rest.+ * `groups` are list keys (`issue_id ?? id`).+ *+ * The rows leave at once. Which of them the server really archived is its+ * call — an issue that gained something addressed to the user in the meantime+ * stays — so the list is refreshed on settle rather than trusted.+ */+export function useArchiveInboxUpdates() {const qc = useQueryClient();const wsId = useWorkspaceId();return useMutation({- mutationFn: () => api.markAllInboxRead(),- onMutate: async () => {+ mutationFn: ({ groups, readOnly }: { groups: readonly string[]; readOnly: boolean }) =>+ api.archiveInboxUpdates(groups, readOnly),+ onMutate: async ({ groups }) => {await qc.cancelQueries({ queryKey: inboxKeys.list(wsId) });const prev = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));+ const keys = new Set(groups);qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), (old) =>old?.map((item) =>- !item.archived ? { ...item, read: true } : item,+ !item.archived && keys.has(item.issue_id ?? item.id) ? { ...item, archived: true } : item,),);return { prev };@@ -243,39 +315,3 @@ export function useMarkAllInboxRead() {},});}--// The three batch-archive mutations below all move items into the archive, so-// each invalidates BOTH lists on settle — plus the unread summary, since an-// archived unread group leaves the badge.-export function useArchiveAllInbox() {- const qc = useQueryClient();- const wsId = useWorkspaceId();- return useMutation({- mutationFn: () => api.archiveAllInbox(),- onSettled: () => {- refreshInboxAfterWrite(qc, wsId);- },- });-}--export function useArchiveAllReadInbox() {- const qc = useQueryClient();- const wsId = useWorkspaceId();- return useMutation({- mutationFn: () => api.archiveAllReadInbox(),- onSettled: () => {- refreshInboxAfterWrite(qc, wsId);- },- });-}--export function useArchiveCompletedInbox() {- const qc = useQueryClient();- const wsId = useWorkspaceId();- return useMutation({- mutationFn: () => api.archiveCompletedInbox(),- onSettled: () => {- refreshInboxAfterWrite(qc, wsId);- },- });-}diff --git a/packages/core/inbox/queries.test.ts b/packages/core/inbox/queries.test.tsindex 146a6b5d89..368037ff9e 100644--- a/packages/core/inbox/queries.test.ts+++ b/packages/core/inbox/queries.test.ts@@ -141,17 +141,6 @@ describe("deduplicateArchivedInboxItems", () => {});describe("archived inbox options", () => {- it("keeps an agent selection out of archive query keys", () => {- const idle: InboxFilters = { ...EMPTY_INBOX_FILTERS, agent: "idle" };-- expect(archivedInboxPagesOptions("ws", idle).queryKey).toEqual(- archivedInboxPagesOptions("ws", EMPTY_INBOX_FILTERS).queryKey,- );- expect(archivedInboxFacetsOptions("ws", idle).queryKey).toEqual(- archivedInboxFacetsOptions("ws", EMPTY_INBOX_FILTERS).queryKey,- );- });-it("carries the previous result across a filter change but never across workspaces", () => {const todo: InboxFilters = { ...EMPTY_INBOX_FILTERS, statuses: ["todo"] };for (const options of [archivedInboxPagesOptions, archivedInboxFacetsOptions]) {@@ -275,3 +264,31 @@ describe("unreadCountForWorkspace", () => {expect(unreadCountForWorkspace([], "ws-1")).toBe(0);});});++describe("the badge on a server that counts what needs the user", () => {+ // `needs_you` is the issues waiting on the user, read or not; `count` is+ // the unread ones. The badge and the workspace dots follow the first.+ const summary: InboxWorkspaceUnread[] = [+ { workspace_id: "read-but-waiting", count: 0, needs_you: 2 },+ { workspace_id: "only-updates", count: 5, needs_you: 0 },+ { workspace_id: "older-server", count: 3 },+ ];++ it("counts issues that wait on the user even when they are read", () => {+ expect(unreadCountForWorkspace(summary, "read-but-waiting")).toBe(2);+ });++ it("does not count unread updates", () => {+ expect(unreadCountForWorkspace(summary, "only-updates")).toBe(0);+ });++ it("keeps counting unread issues when the server sends no needs-you count", () => {+ expect(unreadCountForWorkspace(summary, "older-server")).toBe(3);+ });++ it("lights the workspace dots by the same number", () => {+ expect([...unreadWorkspaceIds(summary)].sort()).toEqual(["older-server", "read-but-waiting"]);+ expect(hasOtherWorkspaceUnread(summary.slice(0, 2), "read-but-waiting")).toBe(false);+ expect(hasOtherWorkspaceUnread(summary.slice(0, 2), "only-updates")).toBe(true);+ });+});diff --git a/packages/core/inbox/queries.ts b/packages/core/inbox/queries.tsindex d78138c06b..cdb2d8452f 100644--- a/packages/core/inbox/queries.ts+++ b/packages/core/inbox/queries.ts@@ -15,7 +15,7 @@ export const inboxKeys = {lookup: (wsId: string) => [...inboxKeys.archived(wsId), "lookup"] as const,facets: (wsId: string) => [...inboxKeys.all(wsId), "archived-facets"] as const,// Account-level (not workspace-scoped): a single shared cache entry that- // holds unread counts for every workspace the user belongs to.+ // holds the inbox counts for every workspace the user belongs to.unreadSummary: () => ["inbox", "unread-summary"] as const,};@@ -108,6 +108,21 @@ export function patchArchivedInboxCaches(qc: QueryClient, wsId: string, patch: (return snapshot;}+// The longest delay a timer takes; a wake further out is re-checked then.+const MAX_TIMER_MS = 2_147_000_000;+// Read a little after the wake, so the server's clock has passed it too.+const WAKE_SLACK_MS = 1_000;++/** The earliest time a snoozed issue comes back in any workspace, in ms. */+export function nextInboxSummaryWake(summary: readonly InboxWorkspaceUnread[] | undefined): number | null {+ let next: number | null = null;+ for (const entry of summary ?? []) {+ const at = entry.next_wake_at ? Date.parse(entry.next_wake_at) : Number.NaN;+ if (Number.isFinite(at) && (next == null || at < next)) next = at;+ }+ return next;+}+/*** Cross-workspace unread inbox summary. One cache entry shared across all* workspaces — the data is account-level, so switching workspaces does not@@ -115,9 +130,14 @@ export function patchArchivedInboxCaches(qc: QueryClient, wsId: string, patch: (** Visibility gating is the default, including for direct observers such as* the search palette. `refetchOnWindowFocus` re-reads an invalidated summary- * once when the page is shown again; with `staleTime: Infinity` a page that- * missed no event is not stale and makes no request. The dock badge overrides- * `enabled` through `inboxUnreadSummaryEnabled` to stay live while hidden.+ * once when the page is shown again; a page that missed no event is not stale+ * and makes no request. The dock badge overrides `enabled` through+ * `inboxUnreadSummaryEnabled` to stay live while hidden.+ *+ * The one change no event reports is a snooze running out (MUL-9215). The+ * summary says when the next one does: the query is re-read then while on+ * screen, and counts as stale from then on, so a page shown again after it+ * re-reads on focus.*/export function inboxUnreadSummaryOptions() {return queryOptions({@@ -125,6 +145,14 @@ export function inboxUnreadSummaryOptions() {queryFn: () => api.getInboxUnreadSummary(),enabled: () => focusManager.isFocused(),refetchOnWindowFocus: true,+ staleTime: (query) => {+ const wake = nextInboxSummaryWake(query.state.data);+ return wake == null ? Infinity : Math.min(Math.max(wake - query.state.dataUpdatedAt, 0), MAX_TIMER_MS);+ },+ refetchInterval: (query) => {+ const wake = nextInboxSummaryWake(query.state.data);+ return wake == null ? false : Math.min(Math.max(wake - Date.now(), 0) + WAKE_SLACK_MS, MAX_TIMER_MS);+ },});}@@ -147,44 +175,56 @@ export function inboxUnreadSummaryEnabled(}/**- * Whether any workspace OTHER than `currentWsId` has unread inbox items.- * Drives the workspace-switcher dot: the active workspace's own unread is- * already surfaced by the Inbox nav count, so it is excluded here to avoid a+ * The number a workspace's Inbox badge shows: the issues waiting on the user,+ * read or not (MUL-9215). Reading a row no longer clears it; handling the+ * issue does. A server that predates the sectioned Inbox sends no `needs_you`,+ * and the badge keeps counting unread issues as it did.+ */+export function inboxBadgeCount(entry: InboxWorkspaceUnread): number {+ return entry.needs_you ?? entry.count;+}++/**+ * Whether any workspace OTHER than `currentWsId` has issues waiting on the+ * user. Drives the workspace-switcher dot: the active workspace's own count+ * is already on the Inbox nav badge, so it is excluded here to avoid a* duplicate signal.*/export function hasOtherWorkspaceUnread(summary: InboxWorkspaceUnread[],currentWsId: string | null | undefined,): boolean {- return summary.some((s) => s.workspace_id !== currentWsId && s.count > 0);+ return summary.some((s) => s.workspace_id !== currentWsId && inboxBadgeCount(s) > 0);}/**- * Set of workspace ids that have unread inbox items. Lets the workspace- * switcher dropdown mark WHICH workspace a pending message lives in (the+ * Set of workspace ids that have issues waiting on the user. Lets the+ * workspace switcher dropdown mark WHICH workspace they live in (the* aggregate switcher dot only says "somewhere else"). Workspaces with a zero* count are excluded.*/export function unreadWorkspaceIds(summary: InboxWorkspaceUnread[]): Set<string> {- return new Set(summary.filter((s) => s.count > 0).map((s) => s.workspace_id));+ return new Set(summary.filter((s) => inboxBadgeCount(s) > 0).map((s) => s.workspace_id));}/**- * Unread inbox count for one workspace within the cross-workspace summary.- * A workspace with nothing unread is absent from the response entirely, so a- * missing entry means zero rather than "not loaded yet".+ * Inbox badge count for one workspace within the cross-workspace summary.+ * A workspace with nothing to report is absent from the response entirely, so+ * a missing entry means zero rather than "not loaded yet".*/export function unreadCountForWorkspace(summary: InboxWorkspaceUnread[],wsId: string | null | undefined,): number {if (!wsId) return 0;- return summary.find((s) => s.workspace_id === wsId)?.count ?? 0;+ const entry = summary.find((s) => s.workspace_id === wsId);+ return entry ? inboxBadgeCount(entry) : 0;}/**- * Unread inbox count for the given workspace — the number the sidebar nav- * badge and the desktop dock badge render.+ * Inbox badge count for the given workspace — the number the sidebar nav+ * badge and the desktop dock badge render. See {@link inboxBadgeCount} for+ * what it counts.** Read from the cross-workspace summary, NOT from the inbox list. The summary* is one small server-computed row per workspace and the sidebar already@@ -194,8 +234,8 @@ export function unreadCountForWorkspace(** `GET /api/inbox/unread-count` is deliberately not the source: it counts raw* notification rows, while the inbox renders one row per issue. The summary- * endpoint applies the same newest-per-issue rule `deduplicateInboxItems`- * applies client-side, so this number matches the list the user sees.+ * endpoint counts issues, so this number matches the "Needs you" section the+ * user sees.*/export function useInboxUnreadCount(wsId: string | null | undefined,@@ -204,6 +244,7 @@ export function useInboxUnreadCount(const { data } = useQuery({...inboxUnreadSummaryOptions(),enabled: inboxUnreadSummaryEnabled(wsId, options),+ refetchIntervalInBackground: options?.whileHidden ?? false,select: (summary: InboxWorkspaceUnread[]) =>unreadCountForWorkspace(summary, wsId),});diff --git a/packages/core/inbox/section-store.ts b/packages/core/inbox/section-store.tsnew file mode 100644index 0000000000..fad03e5143--- /dev/null+++ b/packages/core/inbox/section-store.ts@@ -0,0 +1,46 @@+"use client";++import { create } from "zustand";+import { createJSONStorage, persist } from "zustand/middleware";+import { defaultStorage } from "../platform/storage";++/** The Inbox sections that fold. "Needs you" and "Working" are always open. */+export type InboxFoldingSection = "updates" | "snoozed";++interface InboxSectionState {+ open: Record<InboxFoldingSection, boolean>;+ toggle: (section: InboxFoldingSection) => void;+}++const CLOSED: Record<InboxFoldingSection, boolean> = { updates: false, snoozed: false };++/**+ * Which folding sections the user has opened. Both start closed: they are+ * what the user does not have to look at. A view preference, so it is kept+ * across workspaces and restarts.+ */+export const useInboxSectionStore = create<InboxSectionState>()(+ persist(+ (set) => ({+ open: CLOSED,+ toggle: (section) =>+ set((state) => ({ open: { ...state.open, [section]: !state.open[section] } })),+ }),+ {+ name: "multica_inbox_sections",+ version: 1,+ storage: createJSONStorage(() => defaultStorage),+ partialize: (state) => ({ open: state.open }),+ merge: (persisted, current) => {+ const stored = (persisted as { open?: Record<string, unknown> } | undefined)?.open;+ return {+ ...current,+ open: {+ updates: stored?.updates === true,+ snoozed: stored?.snoozed === true,+ },+ };+ },+ },+ ),+);diff --git a/packages/core/inbox/sections.test.ts b/packages/core/inbox/sections.test.tsnew file mode 100644index 0000000000..263eb23956--- /dev/null+++ b/packages/core/inbox/sections.test.ts@@ -0,0 +1,354 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import type { AgentTask, InboxItem } from "../types";+import {+ buildInboxSections,+ inboxReasonKind,+ inboxWorkingRows,+ nextInboxWake,+ placeInboxGroup,+} from "./sections";++const NOW = new Date("2026-06-15T12:00:00Z").getTime();+const LATER = "2026-06-15T18:00:00Z";+const EARLIER = "2026-06-15T09:00:00Z";++function item(overrides: Partial<InboxItem>): InboxItem {+ return {+ id: "inbox-1",+ workspace_id: "workspace-1",+ recipient_type: "member",+ recipient_id: "member-1",+ actor_type: "agent",+ actor_id: "agent-1",+ type: "new_comment",+ severity: "info",+ issue_id: "issue-1",+ title: "Issue title",+ body: null,+ issue_status: null,+ read: false,+ archived: false,+ created_at: "2026-06-15T08:00:00Z",+ details: null,+ section: "needs_you",+ ...overrides,+ };+}++function task(overrides: Partial<AgentTask>): AgentTask {+ return {+ id: "task-1",+ agent_id: "agent-1",+ runtime_id: "runtime-1",+ issue_id: "issue-1",+ status: "running",+ priority: 0,+ dispatched_at: null,+ started_at: "2026-06-15T11:00:00Z",+ completed_at: null,+ result: null,+ error: null,+ created_at: "2026-06-15T10:59:00Z",+ attribution: { source: "direct_human", precise: true, originator: { id: "me" } },+ ...overrides,+ } as AgentTask;+}++describe("placeInboxGroup", () => {+ it("keeps an issue under needs you after it has been read", () => {+ const mention = item({ type: "mentioned", read: true });+ expect(placeInboxGroup([mention], NOW)).toMatchObject({ section: "needs_you", reason: mention });+ });++ it("explains the row by the newest notification addressed to the user", () => {+ const update = item({ id: "update", section: "updates", created_at: "2026-06-15T11:00:00Z" });+ const mention = item({ id: "mention", type: "mentioned", created_at: "2026-06-15T10:00:00Z" });+ const assigned = item({ id: "assigned", type: "issue_assigned", created_at: "2026-06-15T09:00:00Z" });+ expect(placeInboxGroup([update, mention, assigned], NOW).reason).toBe(mention);+ });++ it("previews the newest notification that says something", () => {+ const handBack = item({ id: "done", type: "agent_completed", created_at: "2026-06-15T11:00:00Z" });+ const comment = item({ id: "comment", body: "PR is up", created_at: "2026-06-15T10:00:00Z" });+ const older = item({ id: "older", body: "Starting", created_at: "2026-06-15T09:00:00Z" });+ expect(placeInboxGroup([handBack, comment, older], NOW)).toMatchObject({+ reason: handBack,+ preview: comment,+ });+ });++ it("files an issue the user only follows under updates", () => {+ expect(placeInboxGroup([item({ section: "updates" })], NOW)).toMatchObject({+ section: "updates",+ reason: null,+ });+ });++ it("treats a row without a section as addressed to the user", () => {+ // A server that predates sections: its one list is what needs the user.+ const legacy = item({ section: undefined });+ expect(placeInboxGroup([legacy], NOW).section).toBe("needs_you");+ });++ it("puts a snoozed issue away until its time", () => {+ const snoozed = item({ snoozed_until: LATER });+ expect(placeInboxGroup([snoozed], NOW)).toMatchObject({+ section: "snoozed",+ reason: null,+ snoozedUntil: LATER,+ });+ });++ it("brings a snoozed issue back once its time has passed", () => {+ const woken = item({ snoozed_until: EARLIER });+ expect(placeInboxGroup([woken], NOW)).toMatchObject({+ section: "needs_you",+ reason: woken,+ wokeAt: new Date(EARLIER).getTime(),+ });+ });++ it("brings a snoozed issue back early when something new is addressed to the user", () => {+ const snoozed = item({ id: "old", snoozed_until: LATER });+ const question = item({ id: "new", type: "mentioned", created_at: "2026-06-15T11:30:00Z" });+ expect(placeInboxGroup([question, snoozed], NOW)).toMatchObject({+ section: "needs_you",+ reason: question,+ });+ });++ it("leaves a snoozed issue away when only activity arrives", () => {+ const snoozed = item({ id: "old", snoozed_until: LATER });+ const activity = item({ id: "new", section: "updates", created_at: "2026-06-15T11:30:00Z" });+ expect(placeInboxGroup([activity, snoozed], NOW).section).toBe("snoozed");+ });+});++describe("buildInboxSections", () => {+ it("lists each issue once, in the section its notifications put it", () => {+ const needs = item({ id: "a", issue_id: "issue-a", type: "mentioned" });+ const update = item({ id: "b", issue_id: "issue-b", section: "updates" });+ const snoozed = item({ id: "c", issue_id: "issue-c", snoozed_until: LATER });+ const all = [needs, update, snoozed];++ const sections = buildInboxSections(all, all, NOW);++ expect(sections.needsYou.map((row) => row.item.id)).toEqual(["a"]);+ expect(sections.updates.map((row) => row.item.id)).toEqual(["b"]);+ expect(sections.snoozed.map((row) => row.item.id)).toEqual(["c"]);+ expect(sections.snoozed[0]?.snoozedUntil).toBe(LATER);+ expect(sections.working).toEqual([]);+ });++ it("places a row by all of the issue's notifications, not the one a filter kept", () => {+ const mention = item({ id: "mention", type: "mentioned", created_at: "2026-06-15T09:00:00Z" });+ const update = item({ id: "update", section: "updates", created_at: "2026-06-15T10:00:00Z" });++ const sections = buildInboxSections([update], [mention, update], NOW);++ expect(sections.needsYou).toHaveLength(1);+ expect(sections.needsYou[0]).toMatchObject({ item: update, reason: mention });+ expect(sections.updates).toEqual([]);+ });++ it("puts an issue that just came back from a snooze first", () => {+ const fresh = item({ id: "fresh", issue_id: "issue-a", created_at: "2026-06-15T10:00:00Z" });+ const woken = item({+ id: "woken",+ issue_id: "issue-b",+ created_at: "2026-06-10T10:00:00Z",+ snoozed_until: "2026-06-15T11:00:00Z",+ });+ const all = [fresh, woken];++ expect(buildInboxSections(all, all, NOW).needsYou.map((row) => row.item.id)).toEqual([+ "woken",+ "fresh",+ ]);+ });++ it("orders snoozed issues by when they come back", () => {+ const tomorrow = item({ id: "tomorrow", issue_id: "issue-a", snoozed_until: "2026-06-16T09:00:00Z" });+ const tonight = item({ id: "tonight", issue_id: "issue-b", snoozed_until: LATER });+ const all = [tomorrow, tonight];++ expect(buildInboxSections(all, all, NOW).snoozed.map((row) => row.item.id)).toEqual([+ "tonight",+ "tomorrow",+ ]);+ });++ it("lists an issue the user's agent is working on under working, not updates", () => {+ const update = item({ id: "update", section: "updates" });+ const sections = buildInboxSections([update], [update], NOW, { working: { tasks: [task({})], userId: "me" } });++ expect(sections.working.map((row) => row.issueId)).toEqual(["issue-1"]);+ expect(sections.updates).toEqual([]);+ });++ it("keeps an issue that needs the user out of working", () => {+ const mention = item({ type: "mentioned" });+ const sections = buildInboxSections([mention], [mention], NOW, { working: { tasks: [task({})], userId: "me" } });++ expect(sections.needsYou).toHaveLength(1);+ expect(sections.working).toEqual([]);+ });++ it("keeps a snoozed issue out of working", () => {+ const snoozed = item({ section: "updates", snoozed_until: LATER });+ const sections = buildInboxSections([snoozed], [snoozed], NOW, { working: { tasks: [task({})], userId: "me" } });++ expect(sections.snoozed).toHaveLength(1);+ expect(sections.working).toEqual([]);+ });++ it("leaves a read update out and names it for the archive", () => {+ const unread = item({ id: "unread", issue_id: "issue-a", section: "updates" });+ const read = item({ id: "read", issue_id: "issue-b", section: "updates", read: true });+ const all = [unread, read];++ const sections = buildInboxSections(all, all, NOW);++ expect(sections.updates.map((row) => row.item.id)).toEqual(["unread"]);+ expect(sections.readUpdates).toEqual(["issue-b"]);+ });++ it("goes by the newest update, so a later unread one keeps the issue listed", () => {+ const older = item({ id: "older", section: "updates", read: true, created_at: "2026-06-15T09:00:00Z" });+ const newer = item({ id: "newer", section: "updates", created_at: "2026-06-15T10:00:00Z" });++ const sections = buildInboxSections([newer], [newer, older], NOW);++ expect(sections.updates.map((row) => row.item.id)).toEqual(["newer"]);+ expect(sections.readUpdates).toEqual([]);+ });++ it("keeps the update that is open until the user moves on", () => {+ const open = item({ id: "open", issue_id: "issue-a", section: "updates", read: true });+ const all = [open];++ expect(buildInboxSections(all, all, NOW, { openKey: "issue-a" })).toMatchObject({+ updates: [{ item: open }],+ readUpdates: [],+ });+ expect(buildInboxSections(all, all, NOW, { openKey: "issue-b" })).toMatchObject({+ updates: [],+ readUpdates: ["issue-a"],+ });+ });++ it("names a read update a filter left out, and never one that is read but needs the user", () => {+ const readUpdate = item({ id: "update", issue_id: "issue-a", section: "updates", read: true });+ const readMention = item({ id: "mention", issue_id: "issue-b", type: "mentioned", read: true });+ const snoozed = item({ id: "snoozed", issue_id: "issue-c", section: "updates", read: true, snoozed_until: LATER });++ const sections = buildInboxSections([readMention], [readUpdate, readMention, snoozed], NOW);++ expect(sections.needsYou.map((row) => row.item.id)).toEqual(["mention"]);+ expect(sections.readUpdates).toEqual(["issue-a"]);+ });+});++describe("inboxWorkingRows", () => {+ it("lists a run the user started, queued or running", () => {+ const rows = inboxWorkingRows(+ [+ task({ id: "running", issue_id: "issue-a" }),+ task({ id: "queued", issue_id: "issue-b", status: "queued", started_at: null }),+ ],+ "me",+ );+ expect(rows).toEqual([+ { issueId: "issue-a", taskId: "running", agentId: "agent-1", queued: false, since: "2026-06-15T11:00:00Z" },+ { issueId: "issue-b", taskId: "queued", agentId: "agent-1", queued: true, since: "2026-06-15T10:59:00Z" },+ ]);+ });++ it("leaves out runs someone or something else started", () => {+ const rows = inboxWorkingRows(+ [+ task({ id: "other", attribution: { source: "direct_human", precise: true, originator: { id: "someone" } } }),+ task({ id: "autopilot", attribution: { source: "rule_owner", precise: true, initiator: { id: "me" } } }),+ task({ id: "delegated", attribution: { source: "delegation", precise: true, originator: { id: "me" } } }),+ task({ id: "legacy", attribution: undefined }),+ ],+ "me",+ );+ expect(rows).toEqual([]);+ });++ it("leaves out finished runs and runs without an issue", () => {+ const rows = inboxWorkingRows(+ [+ task({ id: "done", status: "completed" }),+ task({ id: "failed", status: "failed" }),+ task({ id: "cancelled", status: "cancelled" }),+ task({ id: "chat", issue_id: "" }),+ task({ id: "parked", status: "deferred" }),+ ],+ "me",+ );+ expect(rows).toEqual([]);+ });++ it("shows one row per issue, the running run over a queued one", () => {+ const rows = inboxWorkingRows(+ [+ task({ id: "queued", status: "queued", started_at: null }),+ task({ id: "running" }),+ ],+ "me",+ );+ expect(rows.map((row) => row.taskId)).toEqual(["running"]);+ });++ it("lists nothing before the user is known", () => {+ expect(inboxWorkingRows([task({})], undefined)).toEqual([]);+ });+});++describe("nextInboxWake", () => {+ it("is the soonest snooze still running", () => {+ const items = [+ item({ id: "a", snoozed_until: "2026-06-16T09:00:00Z" }),+ item({ id: "b", snoozed_until: LATER }),+ item({ id: "c", snoozed_until: EARLIER }),+ item({ id: "d" }),+ item({ id: "e", archived: true, snoozed_until: "2026-06-15T12:30:00Z" }),+ ];+ expect(nextInboxWake(items, NOW)).toBe(new Date(LATER).getTime());+ });++ it("is null when nothing is snoozed", () => {+ expect(nextInboxWake([item({})], NOW)).toBeNull();+ });+});++describe("inboxReasonKind", () => {+ it("keeps the reason a notification names itself", () => {+ expect(inboxReasonKind(item({ type: "mentioned", issue_status: "in_review" }))).toBe("mention");+ expect(inboxReasonKind(item({ type: "issue_assigned" }))).toBe("assigned");+ expect(inboxReasonKind(item({ type: "task_failed", issue_status: "in_review" }))).toBe("failed");+ expect(inboxReasonKind(item({ type: "task_cancelled", issue_status: "in_progress" }))).toBe("cancelled");+ expect(inboxReasonKind(item({ type: "agent_blocked" }))).toBe("question");+ expect(inboxReasonKind(item({ type: "review_requested" }))).toBe("review");+ });++ it("reads a hand-over through the issue's status", () => {+ expect(inboxReasonKind(item({ type: "agent_completed", issue_status: "in_review" }))).toBe("review");+ expect(inboxReasonKind(item({ type: "agent_completed", issue_status: "blocked" }))).toBe("question");+ expect(inboxReasonKind(item({ type: "new_comment", issue_status: "in_review" }))).toBe("review");+ expect(inboxReasonKind(item({ type: "status_changed", issue_status: "blocked" }))).toBe("question");+ });++ it("falls back to what happened when the status asks for nothing", () => {+ expect(inboxReasonKind(item({ type: "agent_completed", issue_status: "in_progress" }))).toBe("finished");+ expect(inboxReasonKind(item({ type: "new_comment", issue_status: "todo" }))).toBe("comment");+ });++ it("leaves the rest to the notification's own label", () => {+ expect(inboxReasonKind(item({ type: "status_changed", issue_status: "todo" }))).toBeNull();+ expect(inboxReasonKind(item({ type: "app_action_requested" }))).toBeNull();+ });+});diff --git a/packages/core/inbox/sections.ts b/packages/core/inbox/sections.tsnew file mode 100644index 0000000000..d2f6a7cf74--- /dev/null+++ b/packages/core/inbox/sections.ts@@ -0,0 +1,321 @@+import type { AgentTask, InboxItem } from "../types";+import { groupInboxRows } from "./group";++/**+ * The Inbox lists every issue once, under whose turn it is (MUL-9215):+ *+ * - "Needs you": a notification addressed to the user is waiting on the issue.+ * It stays there after it is read, until the user hands the issue on,+ * archives it or snoozes it.+ * - "Working": an agent run the user started is active on the issue.+ * - "Snoozed": the user put it away until a time.+ * - "Updates": the user only follows the issue. Reading one is all there is+ * to do with it, so a read update leaves for the archive.+ *+ * An issue that qualifies for several is listed in the first of that order.+ */+export type InboxItemSection = "needs_you" | "updates" | "snoozed";++/** Where one issue's notifications put it. */+export interface InboxPlacement {+ section: InboxItemSection;+ /**+ * The notification that explains a "Needs you" row: the newest one addressed+ * to the user that is not snoozed. Null in the other sections.+ */+ reason: InboxItem | null;+ /** When a snoozed issue comes back. Null unless `section` is "snoozed". */+ snoozedUntil: string | null;+ /** When a snooze that ran out brought the issue back, so it sorts as new. */+ wokeAt: number | null;+ /** The newest notification that carries text, for the row's latest line. */+ preview: InboxItem | null;+ /** Whether the issue's newest notification is read. */+ read: boolean;+}++/** One issue's row in a section. */+export interface InboxSectionRow {+ /** The notification the row opens and acts on. */+ item: InboxItem;+ reason: InboxItem | null;+ snoozedUntil: string | null;+ preview: InboxItem | null;+}++/** An issue an agent is working on for the user. It has no notification. */+export interface InboxWorkingRow {+ issueId: string;+ taskId: string;+ agentId: string;+ /** Waiting for a runtime rather than running. */+ queued: boolean;+ /** When the run started, or was queued while it has not. */+ since: string;+}++export interface InboxSections {+ needsYou: InboxSectionRow[];+ working: InboxWorkingRow[];+ updates: InboxSectionRow[];+ snoozed: InboxSectionRow[];+ /**+ * Keys (`issue_id ?? id`) of the issues whose updates the user has read.+ * They are not listed, and are due to move to the archive.+ */+ readUpdates: string[];+}++export interface InboxSectionOptions {+ /** Where "Working" is read from. Left out, the section is empty. */+ working?: InboxWorkingSource;+ /**+ * Key of the row that is open. Opening an update reads it, and it stays+ * listed until the user moves on.+ */+ openKey?: string | null;+}++/** The runs "Working" is read from, and whose they have to be. */+export interface InboxWorkingSource {+ tasks: readonly AgentTask[];+ userId: string | null | undefined;+}++function time(value: string | null | undefined): number {+ if (!value) return Number.NaN;+ return new Date(value).getTime();+}++function isSnoozed(item: InboxItem, now: number): boolean {+ return time(item.snoozed_until) > now;+}++/**+ * Whether a notification is addressed to the user rather than an update on+ * something they follow.+ *+ * A row from a server that predates sections carries none. Its Inbox was one+ * list of everything addressed to the user, which is what "Needs you" is.+ */+export function inboxItemNeedsUser(item: Pick<InboxItem, "section">): boolean {+ return (item.section ?? "needs_you") === "needs_you";+}++/**+ * Place one issue's notifications, newest first.+ *+ * Snoozing is issue-level and ends early by itself: a notification addressed+ * to the user that arrives later carries no snooze, so the issue is back in+ * "Needs you" the moment it lands. One that only reports activity does not+ * bring it back. This is the rule the server counts the badge by.+ */+export function placeInboxGroup(group: readonly InboxItem[], now: number): InboxPlacement {+ let wokeAt: number | null = null;+ let snoozedUntil: string | null = null;+ for (const item of group) {+ const until = time(item.snoozed_until);+ if (Number.isNaN(until)) continue;+ if (until > now) {+ if (snoozedUntil == null || until > time(snoozedUntil)) snoozedUntil = item.snoozed_until ?? null;+ } else if (wokeAt == null || until > wokeAt) {+ wokeAt = until;+ }+ }+ const preview = group.find((item) => !!item.body?.trim()) ?? null;+ const read = group[0]?.read === true;+ const reason = group.find((item) => inboxItemNeedsUser(item) && !isSnoozed(item, now)) ?? null;+ if (reason) return { section: "needs_you", reason, snoozedUntil: null, wokeAt, preview, read };+ if (snoozedUntil) return { section: "snoozed", reason: null, snoozedUntil, wokeAt: null, preview, read };+ return { section: "updates", reason: null, snoozedUntil: null, wokeAt, preview, read };+}++/** Placement of every issue in `items`, keyed like the list (`issue_id ?? id`). */+export function inboxPlacements(+ items: readonly InboxItem[],+ now: number,+): Map<string, InboxPlacement> {+ const placements = new Map<string, InboxPlacement>();+ for (const group of groupInboxRows(items)) {+ const first = group[0];+ if (first) placements.set(first.issue_id ?? first.id, placeInboxGroup(group, now));+ }+ return placements;+}++/**+ * Split the list's rows into sections.+ *+ * `rows` is the list as filtered: one notification per issue. `items` is every+ * active notification, which is what decides the section — a filter picks+ * which issues are listed, never where an issue belongs.+ *+ * Read updates are left out whether or not they pass the filter, and named+ * in `readUpdates`: reading an update is what clears it.+ */+export function buildInboxSections(+ rows: readonly InboxItem[],+ items: readonly InboxItem[],+ now: number,+ { working, openKey = null }: InboxSectionOptions = {},+): InboxSections {+ const placements = inboxPlacements(items, now);+ // Issues listed above "Working", which they would otherwise repeat.+ const ahead = new Set<string>();+ const readUpdates = new Set<string>();+ for (const [key, placement] of placements) {+ if (placement.section !== "updates") ahead.add(key);+ else if (placement.read && key !== openKey) readUpdates.add(key);+ }+ const workingRows = working ? inboxWorkingRows(working.tasks, working.userId, ahead) : [];+ const workingIssueIds = new Set(workingRows.map((row) => row.issueId));++ const sections: InboxSections = {+ needsYou: [],+ working: workingRows,+ updates: [],+ snoozed: [],+ readUpdates: [...readUpdates],+ };+ const sortAt = new Map<InboxSectionRow, number>();+ for (const item of rows) {+ const key = item.issue_id ?? item.id;+ if (readUpdates.has(key)) continue;+ const placement = placements.get(key) ?? placeInboxGroup([item], now);+ const row: InboxSectionRow = {+ item,+ reason: placement.reason,+ snoozedUntil: placement.snoozedUntil,+ preview: placement.preview,+ };+ if (placement.section === "needs_you") {+ sortAt.set(row, Math.max(time(item.created_at), placement.wokeAt ?? 0));+ sections.needsYou.push(row);+ } else if (placement.section === "snoozed") {+ sortAt.set(row, time(placement.snoozedUntil));+ sections.snoozed.push(row);+ } else if (!(item.issue_id && workingIssueIds.has(item.issue_id))) {+ sortAt.set(row, time(item.created_at));+ sections.updates.push(row);+ }+ }+ const at = (row: InboxSectionRow) => sortAt.get(row) ?? 0;+ sections.needsYou.sort((a, b) => at(b) - at(a));+ sections.updates.sort((a, b) => at(b) - at(a));+ // The one that comes back first leads.+ sections.snoozed.sort((a, b) => at(a) - at(b));+ return sections;+}++/**+ * The next moment a snooze runs out, or null. The list re-places its rows+ * then: nothing arrives from the server when a snooze simply elapses.+ */+export function nextInboxWake(items: readonly InboxItem[], now: number): number | null {+ let next: number | null = null;+ for (const item of items) {+ if (item.archived) continue;+ const until = time(item.snoozed_until);+ if (until > now && (next == null || until < next)) next = until;+ }+ return next;+}++function isQueued(task: AgentTask): boolean {+ return (+ task.status === "queued" ||+ task.status === "dispatched" ||+ task.status === "waiting_local_directory" ||+ (task.status === "deferred" && !!task.wakeup_id)+ );+}++/**+ * The issues an agent is working on because the user asked: a run the user+ * started themselves, by assigning, commenting or rerunning. Runs that+ * autopilots, other members or other agents started are not the user's+ * hand-over, and neither are chat runs, which have no issue.+ *+ * One row per issue, a running run before a queued one. Issues in `exclude`+ * are listed elsewhere: they need the user, or the user snoozed them.+ */+export function inboxWorkingRows(+ tasks: readonly AgentTask[],+ userId: string | null | undefined,+ exclude: ReadonlySet<string> = new Set(),+): InboxWorkingRow[] {+ if (!userId) return [];+ const byIssue = new Map<string, InboxWorkingRow>();+ for (const task of tasks) {+ if (!task.issue_id || exclude.has(task.issue_id)) continue;+ const running = task.status === "running";+ if (!running && !isQueued(task)) continue;+ if (task.attribution?.source !== "direct_human") continue;+ if (task.attribution.originator?.id !== userId) continue;+ const row: InboxWorkingRow = {+ issueId: task.issue_id,+ taskId: task.id,+ agentId: task.agent_id,+ queued: !running,+ since: (running ? task.started_at : null) ?? task.created_at,+ };+ const current = byIssue.get(task.issue_id);+ if (+ !current ||+ (current.queued && !row.queued) ||+ (current.queued === row.queued && time(row.since) < time(current.since))+ ) {+ byIssue.set(task.issue_id, row);+ }+ }+ return [...byIssue.values()].sort((a, b) =>+ a.queued === b.queued ? time(b.since) - time(a.since) : a.queued ? 1 : -1,+ );+}++/** Why an issue waits on the user, for the words a "Needs you" row leads with. */+export type InboxReasonKind =+ | "review"+ | "question"+ | "mention"+ | "failed"+ | "cancelled"+ | "assigned"+ | "comment"+ | "finished";++/**+ * What a "Needs you" row is waiting for, from the notification that put it+ * there. A notification that names its own reason keeps it; one that only+ * reports the agent handed over (a finished run, a status change, a comment)+ * is read through the issue's status, which says what the hand-over asks for:+ * `in_review` asks for a check, `blocked` for an answer. Null when neither+ * says, and the row falls back to the notification's own label.+ */+export function inboxReasonKind(reason: InboxItem): InboxReasonKind | null {+ switch (reason.type) {+ case "task_failed":+ case "quick_create_failed":+ return "failed";+ case "task_cancelled":+ return "cancelled";+ case "agent_blocked":+ return "question";+ case "mentioned":+ return "mention";+ case "issue_assigned":+ return "assigned";+ case "review_requested":+ return "review";+ case "agent_completed":+ case "task_completed":+ case "status_changed":+ case "new_comment":+ if (reason.issue_status === "in_review") return "review";+ if (reason.issue_status === "blocked") return "question";+ if (reason.type === "new_comment") return "comment";+ return reason.type === "status_changed" ? null : "finished";+ default:+ return null;+ }+}diff --git a/packages/core/inbox/snooze.test.ts b/packages/core/inbox/snooze.test.tsnew file mode 100644index 0000000000..acc1d0e5a4--- /dev/null+++ b/packages/core/inbox/snooze.test.ts@@ -0,0 +1,54 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { inboxSnoozeOptions, parseInboxSnoozeInput } from "./snooze";++// Local-time constructors on purpose: the choices are in the viewer's zone.+const at = (y: number, m: number, d: number, h: number, min = 0) => new Date(y, m - 1, d, h, min);++describe("inboxSnoozeOptions", () => {+ it("offers an hour, this evening, tomorrow morning and Monday morning", () => {+ // A Wednesday.+ const options = inboxSnoozeOptions(at(2026, 6, 17, 14, 20));+ expect(options).toEqual([+ { preset: "in_one_hour", until: at(2026, 6, 17, 15, 20) },+ { preset: "later_today", until: at(2026, 6, 17, 18) },+ { preset: "tomorrow", until: at(2026, 6, 18, 9) },+ { preset: "next_week", until: at(2026, 6, 22, 9) },+ ]);+ });++ it("drops this evening once it is less than an hour away", () => {+ const presets = inboxSnoozeOptions(at(2026, 6, 17, 17, 30)).map((option) => option.preset);+ expect(presets).toEqual(["in_one_hour", "tomorrow", "next_week"]);+ });++ it("drops Monday on a Sunday, when it is tomorrow", () => {+ const options = inboxSnoozeOptions(at(2026, 6, 21, 10));+ expect(options.map((option) => option.preset)).toEqual(["in_one_hour", "later_today", "tomorrow"]);+ expect(options[2]?.until).toEqual(at(2026, 6, 22, 9));+ });++ it("means the following Monday on a Monday", () => {+ const options = inboxSnoozeOptions(at(2026, 6, 22, 10));+ expect(options.find((option) => option.preset === "next_week")?.until).toEqual(at(2026, 6, 29, 9));+ });+});++describe("parseInboxSnoozeInput", () => {+ const now = at(2026, 6, 17, 14);++ it("reads a local date and time", () => {+ expect(parseInboxSnoozeInput("2026-06-18T09:30", now)).toEqual(at(2026, 6, 18, 9, 30));+ });++ it("refuses a time that is not in the future", () => {+ expect(parseInboxSnoozeInput("2026-06-17T13:00", now)).toBeNull();+ expect(parseInboxSnoozeInput("2026-06-17T14:00", now)).toBeNull();+ });++ it("refuses a time past the server's limit, and anything unreadable", () => {+ expect(parseInboxSnoozeInput("2028-01-01T09:00", now)).toBeNull();+ expect(parseInboxSnoozeInput("", now)).toBeNull();+ expect(parseInboxSnoozeInput("soon", now)).toBeNull();+ });+});diff --git a/packages/core/inbox/snooze.ts b/packages/core/inbox/snooze.tsnew file mode 100644index 0000000000..45b680d4aa--- /dev/null+++ b/packages/core/inbox/snooze.ts@@ -0,0 +1,56 @@+/** The times the Inbox offers to snooze an issue until. */+export type InboxSnoozePreset = "in_one_hour" | "later_today" | "tomorrow" | "next_week";++export interface InboxSnoozeOption {+ preset: InboxSnoozePreset;+ until: Date;+}++/** The server refuses a snooze further out than this. */+export const INBOX_SNOOZE_MAX_DAYS = 366;++const MORNING_HOUR = 9;+const EVENING_HOUR = 18;+const HOUR_MS = 60 * 60 * 1000;++function localDay(now: Date, addDays: number, hour: number): Date {+ return new Date(now.getFullYear(), now.getMonth(), now.getDate() + addDays, hour, 0, 0, 0);+}++/**+ * Snooze choices for `now`, in the viewer's own time zone, soonest first.+ *+ * "Later today" is the evening, and is offered only while the evening is more+ * than an hour away: after that it would repeat "in one hour" or name a time+ * that has passed. "Next week" is Monday morning, and is left out on a Sunday,+ * when it is the same morning as "tomorrow".+ */+export function inboxSnoozeOptions(now: Date): InboxSnoozeOption[] {+ const options: InboxSnoozeOption[] = [+ { preset: "in_one_hour", until: new Date(now.getTime() + HOUR_MS) },+ ];+ const evening = localDay(now, 0, EVENING_HOUR);+ if (evening.getTime() - now.getTime() > HOUR_MS) {+ options.push({ preset: "later_today", until: evening });+ }+ options.push({ preset: "tomorrow", until: localDay(now, 1, MORNING_HOUR) });+ // Sunday is 0, so Monday is one day away then and seven on a Monday.+ const daysToMonday = ((8 - now.getDay()) % 7) || 7;+ if (daysToMonday > 1) {+ options.push({ preset: "next_week", until: localDay(now, daysToMonday, MORNING_HOUR) });+ }+ return options;+}++/**+ * A time the user typed into a `datetime-local` field, or null when it cannot+ * be snoozed until: unparseable, not in the future, or past the server's limit.+ */+export function parseInboxSnoozeInput(value: string, now: Date): Date | null {+ if (!value) return null;+ const until = new Date(value);+ const at = until.getTime();+ if (Number.isNaN(at) || at <= now.getTime()) return null;+ if (at > now.getTime() + INBOX_SNOOZE_MAX_DAYS * 24 * HOUR_MS) return null;+ return until;+}diff --git a/packages/core/inbox/unread-summary-wake.test.tsx b/packages/core/inbox/unread-summary-wake.test.tsxnew file mode 100644index 0000000000..5ea3561d3b--- /dev/null+++ b/packages/core/inbox/unread-summary-wake.test.tsx@@ -0,0 +1,107 @@+/** @vitest-environment jsdom */+import { act, cleanup, renderHook } from "@testing-library/react";+import { QueryClientProvider, focusManager } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { setApiInstance } from "../api";+import type { ApiClient } from "../api/client";+import { createQueryClient } from "../query-client";+import type { InboxWorkspaceUnread } from "../types";+import { inboxKeys, nextInboxSummaryWake, useInboxUnreadCount } from "./queries";++/**+ * Nothing is sent when a snooze runs out (MUL-9215). The summary says when the+ * next one does, so the badge comes back on its own, wherever the user is.+ */++const WS = "ws-1";+const START = Date.parse("2026-11-14T12:00:00Z");+const WAKE = START + 60_000;+const getInboxUnreadSummary = vi.fn<() => Promise<InboxWorkspaceUnread[]>>();++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(START);+ getInboxUnreadSummary.mockReset();+ getInboxUnreadSummary.mockResolvedValue([{ workspace_id: WS, count: 1, needs_you: 1 }]);+ setApiInstance({ getInboxUnreadSummary } as unknown as ApiClient);+});++afterEach(() => {+ cleanup();+ focusManager.setFocused(undefined);+ vi.useRealTimers();+});++function setup(options?: { whileHidden?: boolean }) {+ const qc = createQueryClient();+ qc.setQueryData<InboxWorkspaceUnread[]>(inboxKeys.unreadSummary(), [+ { workspace_id: WS, count: 0, needs_you: 0, next_wake_at: new Date(WAKE).toISOString() },+ ]);+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>+ );+ return renderHook(() => useInboxUnreadCount(WS, options), { wrapper });+}++async function advance(ms: number) {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(ms);+ });+}++it("re-reads the summary when a snoozed issue comes back, with no Inbox open", async () => {+ const view = setup();+ expect(view.result.current).toBe(0);++ await advance(WAKE - START - 1);+ expect(getInboxUnreadSummary).not.toHaveBeenCalled();++ await advance(2_000);+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1);+ expect(view.result.current).toBe(1);++ // Nothing else is snoozed, so nothing else is asked.+ await advance(24 * 3_600_000);+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1);+});++it("a page hidden when the snooze runs out re-reads the summary once shown", async () => {+ const view = setup();+ await act(async () => {+ focusManager.setFocused(false);+ });++ await advance(WAKE - START + 2_000);+ expect(getInboxUnreadSummary).not.toHaveBeenCalled();++ await act(async () => {+ focusManager.setFocused(true);+ });+ await advance(0);+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1);+ expect(view.result.current).toBe(1);+});++it("the dock badge re-reads the summary at the wake while the page is hidden", async () => {+ const view = setup({ whileHidden: true });+ await act(async () => {+ focusManager.setFocused(false);+ });++ await advance(WAKE - START + 2_000);+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1);+ expect(view.result.current).toBe(1);+});++it("takes the earliest wake across workspaces and ignores what it cannot read", () => {+ expect(nextInboxSummaryWake(undefined)).toBeNull();+ expect(nextInboxSummaryWake([{ workspace_id: "a", count: 0 }])).toBeNull();+ expect(+ nextInboxSummaryWake([+ { workspace_id: "a", count: 0, next_wake_at: "2026-11-15T00:00:00Z" },+ { workspace_id: "b", count: 0, next_wake_at: "not a time" },+ { workspace_id: "c", count: 0, next_wake_at: "2026-11-14T13:00:00Z" },+ ]),+ ).toBe(Date.parse("2026-11-14T13:00:00Z"));+});diff --git a/packages/core/issue-views/sidebar-views.test.ts b/packages/core/issue-views/sidebar-views.test.tsindex 25cd60ef40..9957cdd13a 100644--- a/packages/core/issue-views/sidebar-views.test.ts+++ b/packages/core/issue-views/sidebar-views.test.ts@@ -20,11 +20,10 @@ const view = (id: string, owner_id: string): IssueView => ({});describe("defaultSidebarViewOrder", () => {- it("lists built-ins except Unread, own views, then previously pinned views once", () => {+ it("lists built-ins, own views, then previously pinned views once", () => {const views = [view("a", "me"), view("b", "other"), view("c", "other")];expect(defaultSidebarViewOrder(views, "me", ["c", "a"])).toEqual(["builtin:my_issues",- "builtin:my_agents","builtin:all_issues","view:a","view:c",@@ -42,10 +41,12 @@ describe("resolveSidebarViewItems", () => {expect(items[1]).toMatchObject({ kind: "builtin", key: "all_issues" });});- it("resolves a starred Unread like any other built-in", () => {- const items = resolveSidebarViewItems(["builtin:all_issues", "view:a", "builtin:unread"], [view("a", "me")]);- expect(items.map((item) => item.id)).toEqual(["builtin:all_issues", "view:a", "builtin:unread"]);- expect(items[2]).toMatchObject({ kind: "builtin", key: "unread" });+ it("drops the built-ins the Inbox replaced from an order saved before", () => {+ const items = resolveSidebarViewItems(+ ["builtin:my_agents", "builtin:all_issues", "view:a", "builtin:unread"],+ [view("a", "me")],+ );+ expect(items.map((item) => item.id)).toEqual(["builtin:all_issues", "view:a"]);});});diff --git a/packages/core/issue-views/sidebar-views.ts b/packages/core/issue-views/sidebar-views.tsindex a4185fc52e..fc57f30efa 100644--- a/packages/core/issue-views/sidebar-views.ts+++ b/packages/core/issue-views/sidebar-views.ts@@ -8,15 +8,18 @@ import type { PinnedItem } from "../types";import { issueViewEverywhereOptions } from "./queries";import { issueViewPreferenceOptions, useUpdateIssueViewPreference } from "./preferences";-/** The views every workspace has without saving anything. */-export type BuiltinViewKey = "my_issues" | "my_agents" | "all_issues" | "unread";-export const BUILTIN_VIEW_KEYS: readonly BuiltinViewKey[] = ["my_issues", "my_agents", "all_issues", "unread"];-/**- * The built-ins starred before the user arranges the list. Unread is opt-in- * while it overlaps with Inbox.+ * The views every workspace has without saving anything.+ *+ * "My agents' work" and "Unread" used to be here. The Inbox answers both now+ * (what agents are doing for you, and what came back), so a stored order that+ * still names them resolves without them.*/-const DEFAULT_STARRED_BUILTINS: readonly BuiltinViewKey[] = ["my_issues", "my_agents", "all_issues"];+export type BuiltinViewKey = "my_issues" | "all_issues";+export const BUILTIN_VIEW_KEYS: readonly BuiltinViewKey[] = ["my_issues", "all_issues"];++/** The built-ins starred before the user arranges the list. */+const DEFAULT_STARRED_BUILTINS: readonly BuiltinViewKey[] = BUILTIN_VIEW_KEYS;export const builtinViewItemId = (key: BuiltinViewKey) => `builtin:${key}`;export const savedViewItemId = (viewId: string) => `view:${viewId}`;diff --git a/packages/core/issues/sidebar-list.test.ts b/packages/core/issues/sidebar-list.test.tsindex 4d1b7bd68e..6e1e94e30c 100644--- a/packages/core/issues/sidebar-list.test.ts+++ b/packages/core/issues/sidebar-list.test.ts@@ -156,13 +156,12 @@ describe("builtinSidebarRequest", () => {});expect(request("my_issues", "created")?.scope).toEqual({ kind: "my", relation: "created" });expect(request("my_issues", "all")?.scope).toEqual({ kind: "my", relation: "any" });- expect(request("my_agents", "assigned")?.scope).toEqual({ kind: "my", relation: "involved" });});it("ignores the project-only assignee setting and lists nothing when every status is hidden", () => {for (const assignee of ["me", "my_agents", "me_and_my_agents"] as const) {const settings = { ...DEFAULT_SIDEBAR_ISSUE_SETTINGS, hiddenStatuses: [], assignee };- expect(builtinSidebarRequest("my_agents", "assigned", settings, STATUSES)?.table.filters).toEqual({+ expect(builtinSidebarRequest("my_issues", "assigned", settings, STATUSES)?.table.filters).toEqual({include_sub_issues: true,});}diff --git a/packages/core/issues/sidebar-list.ts b/packages/core/issues/sidebar-list.tsindex f0ecf4c03f..6ea3a111fc 100644--- a/packages/core/issues/sidebar-list.ts+++ b/packages/core/issues/sidebar-list.ts@@ -190,14 +190,14 @@ export function viewSidebarRequest(* issues a built-in lists. `null` when the settings leave nothing to list.*/export function builtinSidebarRequest(- builtin: Exclude<BuiltinViewKey, "unread">,+ builtin: BuiltinViewKey,myRelation: MyIssuesRelation,settings: SidebarIssueSettings,statuses: readonly StatusRef[],): SidebarIssuesRequest | null {const shown = shownSidebarStatuses(settings, statuses);if (shown.length === 0) return null;- const relation = builtin === "my_agents" ? "involved" : myRelation === "all" ? "any" : myRelation;+ const relation = myRelation === "all" ? "any" : myRelation;return {table: {scope: builtin === "all_issues" ? { kind: "workspace" } : { kind: "my", relation },diff --git a/packages/core/package.json b/packages/core/package.jsonindex e853d1b918..7140444b10 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -72,6 +72,9 @@"./inbox/mutations": "./inbox/mutations.ts","./inbox/filter-store": "./inbox/filter-store.ts","./inbox/selection-store": "./inbox/selection-store.ts",+ "./inbox/section-store": "./inbox/section-store.ts",+ "./inbox/sections": "./inbox/sections.ts",+ "./inbox/snooze": "./inbox/snooze.ts","./inbox/ws-updaters": "./inbox/ws-updaters.ts","./notification-preferences": "./notification-preferences/index.ts","./notification-preferences/queries": "./notification-preferences/queries.ts",diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.tsindex 965021a85d..f98a50e267 100644--- a/packages/core/realtime/use-realtime-sync.test.ts+++ b/packages/core/realtime/use-realtime-sync.test.ts@@ -854,6 +854,34 @@ describe("handleInboxNew", () => {expect(showNotification).not.toHaveBeenCalled();});+ it("shows a banner only for what is addressed to the user and unread", async () => {+ const qc = createQueryClient();+ qc.setQueryData<Workspace[]>(workspaceKeys.list(), [workspace()]);+ qc.setQueryData(notificationPreferenceKeys.all("ws-a"), {+ preferences: { system_notifications: "all" },+ });+ const invalidate = vi.spyOn(qc, "invalidateQueries");+ const showNotification = stubDesktopAPI();++ // An update on something the user only follows.+ await handleInboxNew(qc, inboxItem({ id: "update", section: "updates" }));+ // A run the user stopped themselves comes back already read.+ await handleInboxNew(qc, inboxItem({ id: "stopped", type: "task_cancelled", section: "needs_you", read: true }));++ expect(showNotification).not.toHaveBeenCalled();+ // The list still learns about both. Its refresh is not awaited by the+ // handler, which has nothing left to wait for once the banner is skipped.+ await vi.waitFor(() =>+ expect(invalidate).toHaveBeenCalledWith({ queryKey: inboxKeys.all("ws-a") }),+ );++ await handleInboxNew(qc, inboxItem({ id: "mention", section: "needs_you" }));+ // A server that predates sections sends none: everything was addressed to the user.+ await handleInboxNew(qc, inboxItem({ id: "legacy" }));++ expect(showNotification.mock.calls.map(([payload]) => payload.itemId)).toEqual(["mention", "legacy"]);+ });+// The tests below exercise the COLD-cache mute path (source preference not// yet cached), where the request — not just the query key — must be scoped// to the source workspace (#3766 follow-up). They install a fake API so thediff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex a83a5c1a99..7abcea8329 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -61,6 +61,7 @@ import {invalidateUpdatedAtSortedIssueLists,} from "../issues/cache-coordinator";import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged, onInboxIssueDeleted, onInboxSummaryInvalidate } from "../inbox/ws-updaters";+import { inboxItemNeedsUser } from "../inbox/sections";import {notificationPreferenceOptions,notificationPreferenceKeys,@@ -589,6 +590,10 @@ export async function handleInboxNew(// A new item in ANY workspace can light the workspace-switcher dot, so// refresh the cross-workspace summary regardless of the active workspace.void onInboxSummaryInvalidate(qc);+ // A banner interrupts, so it is kept for what is addressed to the user and+ // still unread. An update reports activity on something they only follow,+ // and a run they stopped themselves comes back already read.+ if (!inboxItemNeedsUser(item) || item.read) return;// Fire a native OS notification only when the app isn't focused. When// the user is already looking at Multica, the inbox sidebar's unread// styling is enough — no need to interrupt with a banner. `desktopAPI`diff --git a/packages/core/shortcuts/definitions.ts b/packages/core/shortcuts/definitions.tsindex 2f042d1f8d..cb43ba41c7 100644--- a/packages/core/shortcuts/definitions.ts+++ b/packages/core/shortcuts/definitions.ts@@ -14,6 +14,7 @@ export type ShortcutActionId =| "newChat"| "findInIssue"| "archiveInboxItem"+ | "snoozeInboxItem"| "send"| "voiceInput"| "goBack"@@ -110,6 +111,12 @@ export const SHORTCUT_ACTIONS: readonly ShortcutActionDefinition[] = [defaultShortcut: createShortcutChord("E"),allowInEditable: false,},+ {+ id: "snoozeInboxItem",+ category: "general",+ defaultShortcut: createShortcutChord("H"),+ allowInEditable: false,+ },{ id: "send", category: "general", defaultShortcut: primary("Enter"), allowInEditable: true },// Voice input works where the caret is, so it must fire inside editors. It// is matched on keydown AND keyup (holding it is push-to-talk), so the voicediff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex 56661d82dc..b8a2c661e7 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -39,6 +39,8 @@ export type WSEventType =| "inbox:unread"| "inbox:archived"| "inbox:unarchived"+ | "inbox:snoozed"+ | "inbox:unsnoozed"| "inbox:deleted"| "inbox:batch-read"| "inbox:batch-archived"@@ -245,6 +247,20 @@ export interface InboxUnarchivedPayload {recipient_id: string;}+/** Personal: the recipient snoozed an issue's notifications until a time. */+export interface InboxSnoozedPayload {+ item_id: string;+ issue_id: string | null;+ recipient_id: string;+ snoozed_until: string;+}++export interface InboxUnsnoozedPayload {+ item_id: string;+ issue_id: string | null;+ recipient_id: string;+}+/** Personal: the recipient's unread mark on an issue changed. Workspace-tagged* because personal events reach every connection the user has. */export interface IssueUnreadChangedPayload {@@ -682,6 +698,8 @@ export interface WSEventPayloadMap {"inbox:unread": InboxUnreadPayload;"inbox:archived": InboxArchivedPayload;"inbox:unarchived": InboxUnarchivedPayload;+ "inbox:snoozed": InboxSnoozedPayload;+ "inbox:unsnoozed": InboxUnsnoozedPayload;"inbox:deleted": { item_id: string; recipient_id: string; count: number };"inbox:batch-read": InboxBatchReadPayload;"inbox:batch-archived": InboxBatchArchivedPayload;diff --git a/packages/core/types/inbox.ts b/packages/core/types/inbox.tsindex e4587e29d1..4afa4e8958 100644--- a/packages/core/types/inbox.ts+++ b/packages/core/types/inbox.ts@@ -18,6 +18,9 @@ export type InboxItemType =| "review_requested"| "task_completed"| "task_failed"+ // A run the recipient started was cancelled. `details` names who by+ // (`cancelled_by_type`, `cancelled_by_id`, `cancelled_by_name`).+ | "task_cancelled"| "agent_blocked"| "agent_completed"| "reaction_added"@@ -42,14 +45,33 @@ export type InboxItemType =| "app_action_result";/**- * One workspace's unread inbox count in the cross-workspace summary- * (`GET /api/inbox/unread-summary`). The sidebar uses this to light a dot on- * the workspace switcher when a workspace OTHER than the active one has- * unread items.+ * The Inbox section a notification was filed under when it was written.+ * `needs_you`: it is addressed to the recipient, so the issue waits on them.+ * `updates`: they only follow the issue.+ */+export type InboxSection = "needs_you" | "updates";++/**+ * One workspace's inbox counts in the cross-workspace summary+ * (`GET /api/inbox/unread-summary`). The rail badge and the workspace+ * switcher dot read it.*/export interface InboxWorkspaceUnread {workspace_id: string;+ /** Unread issues. */count: number;+ /**+ * Issues waiting on the user, read or not: the rows of the Inbox's "Needs+ * you" section, and what the badge shows. Absent from a server that+ * predates the sectioned Inbox, where the badge falls back to `count`.+ */+ needs_you?: number;+ /**+ * When the workspace's next snoozed issue comes back. The counts leave it+ * out until then and nothing arrives when the time passes, so the summary+ * is read again at this time. Absent when nothing is snoozed.+ */+ next_wake_at?: string;}export interface InboxItem {@@ -85,6 +107,17 @@ export interface InboxItem {archived: boolean;created_at: string;details: Record<string, string> | null;+ /**+ * Absent from a server that predates the sectioned Inbox; every row then+ * belongs to the one list it had.+ */+ section?: InboxSection | null;+ /**+ * When a snoozed row comes back. A time in the past means it already has.+ * Snoozing is issue-level, so every row the issue had at the time carries+ * the same value.+ */+ snoozed_until?: string | null;}diff --git a/packages/views/inbox/components/inbox-context-menu.test.tsx b/packages/views/inbox/components/inbox-context-menu.test.tsxindex 06bada0442..1d00a3e135 100644--- a/packages/views/inbox/components/inbox-context-menu.test.tsx+++ b/packages/views/inbox/components/inbox-context-menu.test.tsx@@ -117,13 +117,19 @@ function renderRow({}describe("inbox row context menu", () => {- it.each(["inbox", "archived"] as const)("offers deletion in the %s view", async (view) => {+ it("offers deletion in the archive", async () => {const onDelete = vi.fn();- const { row } = renderRow({ view, actions: { onDelete } });+ const { row } = renderRow({ view: "archived", actions: { onDelete } });fireEvent.contextMenu(row);fireEvent.click(await screen.findByText("Delete"));expect(onDelete).toHaveBeenCalledWith("inbox-1");});+ it("keeps deletion out of the main view, where archiving is the way out", async () => {+ const { row } = renderRow();+ fireEvent.contextMenu(row);+ await screen.findByText("Archive");+ expect(screen.queryByText("Delete")).toBeNull();+ });it("offers mark-as-unread on a read row and reports the item id", async () => {const onMarkUnread = vi.fn();const { row } = renderRow({@@ -173,6 +179,70 @@ describe("inbox row context menu", () => {expect(screen.queryByText("Mark as read")).toBeNull();});+ describe("snooze", () => {+ // A Wednesday afternoon, with the evening still more than an hour away.+ const now = new Date(2026, 5, 17, 14, 20);+ const frozen = (run: () => Promise<void>) => async () => {+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(now);+ try {+ await run();+ } finally {+ vi.useRealTimers();+ }+ };++ it("puts the issue away until the time picked", frozen(async () => {+ const onSnooze = vi.fn();+ const { row } = renderRow({ entry: item({ id: "inbox-4" }), actions: { onSnooze } });++ fireEvent.contextMenu(row);+ expect(await screen.findByText("Snooze for 1 hour")).toBeInTheDocument();+ expect(screen.getByText("Snooze until later today")).toBeInTheDocument();+ expect(screen.getByText("Snooze until next Monday")).toBeInTheDocument();+ fireEvent.click(screen.getByText("Snooze until tomorrow"));++ expect(onSnooze).toHaveBeenCalledWith("inbox-4", new Date(2026, 5, 18, 9));+ }));++ it("offers only the way back on an issue that is snoozed", frozen(async () => {+ const onUnsnooze = vi.fn();+ const { row } = renderRow({+ entry: item({ id: "inbox-5", snoozed_until: new Date(2026, 5, 18, 9).toISOString() }),+ actions: { onSnooze: vi.fn(), onUnsnooze },+ });++ fireEvent.contextMenu(row);+ fireEvent.click(await screen.findByText("Unsnooze"));++ expect(onUnsnooze).toHaveBeenCalledWith("inbox-5");+ expect(screen.queryByText("Snooze until tomorrow")).toBeNull();+ }));++ it("offers to snooze again once the time has passed", frozen(async () => {+ const { row } = renderRow({+ entry: item({ snoozed_until: new Date(2026, 5, 17, 9).toISOString() }),+ actions: { onSnooze: vi.fn(), onUnsnooze: vi.fn() },+ });++ fireEvent.contextMenu(row);++ expect(await screen.findByText("Snooze until tomorrow")).toBeInTheDocument();+ expect(screen.queryByText("Unsnooze")).toBeNull();+ }));++ it("is not offered in the archive, or where the list cannot snooze", async () => {+ const archived = renderRow({+ entry: item({ archived: true }),+ view: "archived",+ actions: { onSnooze: vi.fn() },+ });+ fireEvent.contextMenu(archived.row);+ expect(await screen.findByText("Unarchive")).toBeInTheDocument();+ expect(screen.queryByText("Snooze until tomorrow")).toBeNull();+ });+ });+it("suppresses the browser's native menu so ours is the only one", async () => {const { row } = renderRow();@@ -208,9 +278,9 @@ describe("inbox row context menu", () => {// A touch pointer has neither hover nor right-click, so the row's compact menu// is the only way in. It must therefore offer what right-click offers.describe("inbox row compact menu", () => {- it("offers deletion without selecting the row", async () => {+ it("offers deletion in the archive without selecting the row", async () => {const onDelete = vi.fn();- renderRow({ actions: { onDelete } });+ renderRow({ view: "archived", actions: { onDelete } });fireEvent.click(screen.getByRole("button", { name: "Notification actions" }));fireEvent.click(await screen.findByText("Delete"));expect(onDelete).toHaveBeenCalledWith("inbox-1");diff --git a/packages/views/inbox/components/inbox-delete-dialog.test.tsx b/packages/views/inbox/components/inbox-delete-dialog.test.tsxindex d6bc787c51..4cef31c94a 100644--- a/packages/views/inbox/components/inbox-delete-dialog.test.tsx+++ b/packages/views/inbox/components/inbox-delete-dialog.test.tsx@@ -7,12 +7,11 @@ import type { ApiClient } from "@multica/core/api/client";import type { InboxItem } from "@multica/core/types";import enInbox from "../../locales/en/inbox.json";import { InboxDeleteDialog } from "./inbox-delete-dialog";-import type { InboxView } from "./inbox-view";vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));const entry = { id: "notification-1", title: "Create with agent failed", issue_id: null } as InboxItem;-function setup(remove = vi.fn(async () => ({ count: 1 })), issueId: string | null = null, view: InboxView = "inbox") {+function setup(remove = vi.fn(async () => ({ count: 1 })), issueId: string | null = null) {setApiInstance({ deleteInbox: remove } as unknown as ApiClient);const onClose = vi.fn();const onDeleted = vi.fn();@@ -20,7 +19,7 @@ function setup(remove = vi.fn(async () => ({ count: 1 })), issueId: string | nulrender(<QueryClientProvider client={qc}><I18nProvider locale="en" resources={{ en: { inbox: enInbox } }}>- <InboxDeleteDialog item={{ ...entry, issue_id: issueId }} view={view} onClose={onClose} onDeleted={onDeleted} />+ <InboxDeleteDialog item={{ ...entry, issue_id: issueId }} onClose={onClose} onDeleted={onDeleted} /></I18nProvider></QueryClientProvider>,);@@ -64,20 +63,13 @@ describe("inbox deletion confirmation", () => {expect(remove).toHaveBeenCalledTimes(2);});- it("explains that deleting active issue notifications makes old archived history visible again", () => {- setup(undefined, "issue-1", "inbox");- expect(screen.getByRole("alertdialog")).toHaveTextContent("Previously archived notifications remain and will be visible again in Archived.");- });-- it("explains the archived group scope without promising to retain the deleted history", () => {- setup(undefined, "issue-1", "archived");+ it("explains that an issue's archived notifications go together", () => {+ setup(undefined, "issue-1");expect(screen.getByText(enInbox.delete_dialog.issue_description)).toBeInTheDocument();- expect(screen.getByRole("alertdialog")).not.toHaveTextContent("Previously archived notifications");});- it("does not mention archived history for an issue-less active notification", () => {+ it("describes a single notification when it has no issue", () => {setup();expect(screen.getByText(enInbox.delete_dialog.description)).toBeInTheDocument();- expect(screen.getByRole("alertdialog")).not.toHaveTextContent("Previously archived notifications");});});diff --git a/packages/views/inbox/components/inbox-delete-dialog.tsx b/packages/views/inbox/components/inbox-delete-dialog.tsxindex 592c80f103..ac188e3ecb 100644--- a/packages/views/inbox/components/inbox-delete-dialog.tsx+++ b/packages/views/inbox/components/inbox-delete-dialog.tsx@@ -14,16 +14,14 @@ import {} from "@multica/ui/components/ui/alert-dialog";import { Button } from "@multica/ui/components/ui/button";import { useT } from "../../i18n";-import type { InboxView } from "./inbox-view";+/** Confirms deleting an archived notification, or an issue's archived ones. */export function InboxDeleteDialog({item,- view,onClose,onDeleted,}: {item: InboxItem;- view: InboxView;onClose: () => void;onDeleted: (id: string) => void;}) {@@ -54,9 +52,7 @@ export function InboxDeleteDialog({<AlertDialogTitle>{t(($) => $.delete_dialog.title)}</AlertDialogTitle><AlertDialogDescription>{item.issue_id- ? view === "inbox"- ? t(($) => $.delete_dialog.active_issue_description)- : t(($) => $.delete_dialog.issue_description)+ ? t(($) => $.delete_dialog.issue_description): t(($) => $.delete_dialog.description)}</AlertDialogDescription></AlertDialogHeader>diff --git a/packages/views/inbox/components/inbox-detail-actions.tsx b/packages/views/inbox/components/inbox-detail-actions.tsxnew file mode 100644index 0000000000..e915a51fea--- /dev/null+++ b/packages/views/inbox/components/inbox-detail-actions.tsx@@ -0,0 +1,91 @@+"use client";++import { Archive, Clock } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import { IconButton } from "@multica/ui/components/common/icon-button";+import { ActionShortcutKeycaps } from "../../common/shortcut-keycaps";+import { useT } from "../../i18n";+import { InboxSnoozeMenu } from "./inbox-snooze-menu";++/**+ * Snooze and archive for the notification the inbox has open, in the detail+ * header. These are the two ways to say "not now" and "done with it" without+ * replying, so they sit where the reader's eye already is, with their keys.+ *+ * `compact` drops the words: a phone header has no room for them.+ */+export function InboxDetailActions({+ compact,+ snoozed,+ snoozeOpen,+ onSnoozeOpenChange,+ onSnooze,+ onUnsnooze,+ onArchive,+}: {+ compact: boolean;+ snoozed: boolean;+ snoozeOpen: boolean;+ onSnoozeOpenChange: (open: boolean) => void;+ onSnooze: (until: Date) => void;+ onUnsnooze: () => void;+ onArchive: () => void;+}) {+ const { t } = useT("inbox");+ const snoozeLabel = t(($) => $.snooze.action);+ const archiveLabel = t(($) => $.detail.archive);++ return (+ <>+ <InboxSnoozeMenu+ open={snoozeOpen}+ onOpenChange={onSnoozeOpenChange}+ snoozed={snoozed}+ onSnooze={onSnooze}+ onUnsnooze={onUnsnooze}+ trigger={+ compact ? (+ <IconButton+ label={snoozeLabel}+ shortcut={<ActionShortcutKeycaps action="snoozeInboxItem" />}+ tooltipSide="bottom"+ className="text-muted-foreground"+ >+ <Clock />+ </IconButton>+ ) : (+ <Button variant="ghost" size="sm" className="shrink-0 gap-1.5 text-muted-foreground">+ <Clock />+ {snoozeLabel}+ <ActionShortcutKeycaps action="snoozeInboxItem" />+ </Button>+ )+ }+ />+ {compact ? (+ <IconButton+ label={archiveLabel}+ shortcut={<ActionShortcutKeycaps action="archiveInboxItem" />}+ tooltipSide="bottom"+ className="text-muted-foreground"+ onClick={onArchive}+ >+ <Archive />+ </IconButton>+ ) : (+ <Button+ variant="ghost"+ size="sm"+ className="shrink-0 gap-1.5 text-muted-foreground"+ onClick={onArchive}+ >+ <Archive />+ {archiveLabel}+ <ActionShortcutKeycaps action="archiveInboxItem" />+ </Button>+ )}+ {/* Sets the notification's two actions apart from the issue's own. */}+ {!compact && <span aria-hidden className="mx-1 h-4 w-px shrink-0 bg-border" />}+ </>+ );+}diff --git a/packages/views/inbox/components/inbox-detail-label.tsx b/packages/views/inbox/components/inbox-detail-label.tsxindex 85b359096f..f5741798e5 100644--- a/packages/views/inbox/components/inbox-detail-label.tsx+++ b/packages/views/inbox/components/inbox-detail-label.tsx@@ -30,6 +30,7 @@ export function useTypeLabels(): Record<InboxItemType, string> {review_requested: t(($) => $.types.review_requested),task_completed: t(($) => $.types.task_completed),task_failed: t(($) => $.types.task_failed),+ task_cancelled: t(($) => $.types.task_cancelled),agent_blocked: t(($) => $.types.agent_blocked),agent_completed: t(($) => $.types.agent_completed),reaction_added: t(($) => $.types.reaction_added),diff --git a/packages/views/inbox/components/inbox-filter-menu.test.tsx b/packages/views/inbox/components/inbox-filter-menu.test.tsxindex 20ba145096..008fbc291d 100644--- a/packages/views/inbox/components/inbox-filter-menu.test.tsx+++ b/packages/views/inbox/components/inbox-filter-menu.test.tsx@@ -91,7 +91,6 @@ function renderMenu({priorityFilterSupport = "supported",issueFieldsSupport = "supported",archived = false,- activeIssueIds,getArchivedInboxFacets = vi.fn(async () => ({ statuses: {}, priorities: {}, actors: {}, unreadCount: 0 })),statusEntries = BUILT_IN_STATUS_ORDER.map(statusEntry),}: {@@ -99,7 +98,6 @@ function renderMenu({priorityFilterSupport?: InboxFilterSupport;issueFieldsSupport?: InboxFilterSupport;archived?: boolean;- activeIssueIds?: ReadonlySet<string>;getArchivedInboxFacets?: ReturnType<typeof vi.fn>;statusEntries?: IssueStatusEntry[];} = {}) {@@ -127,7 +125,6 @@ function renderMenu({items={items}priorityFilterSupport={priorityFilterSupport}issueFieldsSupport={issueFieldsSupport}- activeIssueIds={activeIssueIds}archived={archived}/></QueryClientProvider>,@@ -159,16 +156,53 @@ afterEach(() => {});describe("InboxFilterMenu", () => {- it("groups the fields into notification and issue sections", async () => {+ it("narrows the main inbox by the issue only", async () => {renderMenu({items: [item("from-alice", "todo", "high", { actor_type: "member", actor_id: "alice" })],});openMenu();+ for (const name of ["Status", "Priority", "Project", "Assignee", "Label", "Due date"]) {+ expect(await screen.findByRole("menuitem", { name: new RegExp(`^${name}`) })).toBeTruthy();+ }+ // The sections already say what kind of notification a row is.+ for (const name of ["Read state", "Type", "From", "Received", "Agent status"]) {+ expect(screen.queryByRole("menuitem", { name: new RegExp(`^${name}`) })).toBeNull();+ }+ // One group of fields needs no heading to tell it from another.+ expect(screen.queryByText("Notification")).toBeNull();+ expect(screen.queryByText("Issue")).toBeNull();++ fireEvent.change(screen.getByRole("textbox", { name: "Filter by field or value…" }), {+ target: { value: "last 7" },+ });+ expect(await screen.findByText("No results")).toBeTruthy();+ });++ it("leaves a notification filter picked in the archive dormant in the main inbox", async () => {+ const store = useInboxFilterStore.getState();+ store.toggleFilterValue("ws-1", "type", "mention");+ store.toggleUnreadOnly("ws-1");+ renderMenu();++ // Not counted on the trigger, not pinned in the menu, and still stored.+ openMenu();+ await screen.findByRole("menuitem", { name: /^Status/ });+ expect(screen.queryByText("Active")).toBeNull();+ expect(storedFilters()).toMatchObject({ types: ["mention"], unreadOnly: true });+ });++ it("groups the archive's fields into notification and issue sections", async () => {+ renderMenu({+ archived: true,+ getArchivedInboxFacets: vi.fn(async () => ({ statuses: {}, priorities: {}, actors: { "member:alice": 1 }, unreadCount: 0 })),+ });+ openMenu();+const notification = await screen.findByText("Notification");const issue = screen.getByText("Issue");- for (const name of ["Read state", "Type", "From", "Received", "Status", "Priority", "Agent status", "Project", "Assignee", "Label", "Due date"]) {- expect(screen.getByRole("menuitem", { name: new RegExp(`^${name}`) })).toBeTruthy();+ for (const name of ["Read state", "Type", "From", "Received", "Status", "Priority", "Project", "Assignee", "Label", "Due date"]) {+ expect(await screen.findByRole("menuitem", { name: new RegExp(`^${name}`) })).toBeTruthy();}expect(notification.compareDocumentPosition(issue) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();expect(screen.queryByText("Active")).toBeNull();@@ -178,7 +212,7 @@ describe("InboxFilterMenu", () => {const store = useInboxFilterStore.getState();store.toggleFilterValue("ws-1", "type", "mention");store.setFilterNegated("ws-1", "type", true);- renderMenu();+ renderMenu({ archived: true });openMenu("1 active filter");expect(await screen.findByText("Active")).toBeTruthy();@@ -191,10 +225,8 @@ describe("InboxFilterMenu", () => {it("selects a notification type and switches it to is not", async () => {renderMenu({- items: [- item("mention", "todo", "high"),- item("comment", "todo", "high", { type: "new_comment" }),- ],+ archived: true,+ getArchivedInboxFacets: vi.fn(async () => ({ statuses: {}, priorities: {}, actors: {}, types: { mention: 1, comment: 1 }, unreadCount: 0 })),});await openSubmenu("Type");fireEvent.click(await screen.findByRole("menuitemcheckbox", { name: /Comments & reactions.*1 notification/ }));@@ -205,7 +237,7 @@ describe("InboxFilterMenu", () => {});it("keeps is not when it is chosen before the first type", async () => {- renderMenu({ items: [item("mention", "todo", "high")] });+ renderMenu({ archived: true });await openSubmenu("Type");fireEvent.click(await screen.findByRole("menuitemradio", { name: "is not" }));fireEvent.click(screen.getByRole("menuitemcheckbox", { name: /^Agent runs/ }));@@ -215,7 +247,7 @@ describe("InboxFilterMenu", () => {});it("finds a value by search and adds it in one click", async () => {- renderMenu();+ renderMenu({ archived: true });openMenu();fireEvent.change(await screen.findByRole("textbox", { name: "Filter by field or value…" }), {target: { value: "last 7" },@@ -322,36 +354,18 @@ describe("InboxFilterMenu", () => {expect(storedFilters()).toBeUndefined();});- it("offers only the actors the view's notifications carry", async () => {- renderMenu({- items: [- item("from-alice", "todo", "high", { actor_type: "member", actor_id: "alice" }),- item("from-bob", "done", "low", { actor_type: "agent", actor_id: "bob" }),- ],- });-- await openSubmenu("From");- const alice = await screen.findByRole("menuitemcheckbox", { name: /Alice.*1 notification/ });- expect(screen.getByRole("menuitemcheckbox", { name: /Bob.*1 notification/ })).toBeTruthy();-- fireEvent.click(alice);- expect(storedFilters()?.actors).toEqual(["member:alice"]);- });-- it("hides From when no notification carries an actor", async () => {- renderMenu();+ it("hides From when the archive has no notification with an actor", async () => {+ renderMenu({ archived: true });openMenu();await screen.findByRole("menuitem", { name: /^Status/ });expect(screen.queryByRole("menuitem", { name: /^From/ })).toBeNull();});- it("filters to unread and counts the unread issues behind it", async () => {+ it("filters the archive to unread and counts the unread issues behind it", async () => {renderMenu({- items: [- item("unread", "todo", "high"),- item("read", "done", "low", { read: true }),- ],+ archived: true,+ getArchivedInboxFacets: vi.fn(async () => ({ statuses: {}, priorities: {}, actors: {}, unreadCount: 1 })),});await openSubmenu("Read state");@@ -363,25 +377,6 @@ describe("InboxFilterMenu", () => {);});- it("filters by agent status without a count beside it", async () => {- renderMenu({ activeIssueIds: new Set(["issue-todo-high"]) });-- await openSubmenu("Agent status");- fireEvent.click(await screen.findByRole("menuitemcheckbox", { name: /^Idle$/ }));-- expect(storedFilters()?.agent).toBe("idle");- });-- it("hides agent status in the archive and ignores a carried-over selection", async () => {- useInboxFilterStore.getState().setAgent("ws-1", "idle");- renderMenu({ archived: true });-- // Not counted on the trigger, and not offered in the menu.- openMenu();- await screen.findByRole("menuitem", { name: /^Status/ });- expect(screen.queryByRole("menuitem", { name: /^Agent status/ })).toBeNull();- });-it("hides priority and clears its filter for a legacy response", async () => {useInboxFilterStore.getState().togglePriorityFilter("ws-1", "high");renderMenu({diff --git a/packages/views/inbox/components/inbox-filter-menu.tsx b/packages/views/inbox/components/inbox-filter-menu.tsxindex b9fb1b0dab..56b5c35e18 100644--- a/packages/views/inbox/components/inbox-filter-menu.tsx+++ b/packages/views/inbox/components/inbox-filter-menu.tsx@@ -5,7 +5,7 @@ import { Filter, RotateCcw, Search } from "@multica/ui/icons";import { PRIORITY_DISPLAY_ORDER } from "@multica/core/issues/config";import { DUE_DATE_FILTERS, FILTER_NONE_VALUE } from "@multica/core/issues/stores/filter-tree";import {- INBOX_AGENT_FILTERS,+ INBOX_NOTIFICATION_FILTER_KEYS,INBOX_RECEIVED_FILTERS,INBOX_TYPE_GROUPS,activeInboxFilterKeys,@@ -57,21 +57,18 @@ import {import { useStatusOptions } from "../../issues/utils/status-options";import { useT } from "../../i18n";import {- INBOX_AGENT_ICONS,INBOX_FILTER_ICONS,INBOX_TYPE_ICONS,useInboxFilterChips,useInboxFilterLabels,} from "./inbox-filter-options";-const EMPTY_ISSUE_IDS: ReadonlySet<string> = new Set();const NO_COUNTS = new Map<string, number>();-const NOTIFICATION_KEYS: readonly InboxFilterKey[] = ["unread", "type", "actor", "received"];+const NOTIFICATION_KEYS = INBOX_NOTIFICATION_FILTER_KEYS;const ISSUE_KEYS: readonly InboxFilterKey[] = ["status","priority",- "agent","project","assignee","label",@@ -113,8 +110,12 @@ function ValueItem({/*** The inbox filter, shaped like the issue filter: search, the dimensions in- * use pinned on top, then notification and issue fields, "is" / "is not" per- * field, and each field's current value on its row.+ * use pinned on top, "is" / "is not" per field, and each field's current+ * value on its row.+ *+ * The main Inbox is narrowed by the issue only: its sections already say what+ * kind of notification a row is and whether it is read. The archive is one+ * flat list, so it also offers the notification fields.** `items` are the view's notifications, every one rather than one per issue:* the notification fields match any notification of an issue.@@ -124,15 +125,12 @@ export function InboxFilterMenu({items,priorityFilterSupport,issueFieldsSupport = "supported",- activeIssueIds = EMPTY_ISSUE_IDS,archived = false,}: {wsId: string;items: InboxItem[];priorityFilterSupport: InboxFilterSupport;issueFieldsSupport?: InboxFilterSupport;- /** Issues an agent is running or queued on. */- activeIssueIds?: ReadonlySet<string>;archived?: boolean;}) {const { t } = useT("inbox");@@ -167,10 +165,10 @@ export function InboxFilterMenu({switch (key) {case "priority":return priorityFilterSupport === "supported";- case "agent":- return !archived;+ case "unread":+ return archived;case "actor":- return actorOptions.length > 0;+ return archived && actorOptions.length > 0;case "project":case "assignee":case "label":@@ -178,7 +176,7 @@ export function InboxFilterMenu({return issueFieldsSupported;case "type":case "received":- return serverOnlySupported;+ return archived && serverOnlySupported;default:return true;}@@ -199,8 +197,8 @@ export function InboxFilterMenu({// Counts are faceted: each respects every other active dimension while// ignoring its own, so it says how many rows selecting that value shows.const localCounts = useMemo(- () => (archived || !open ? null : inboxFacetCounts(items, effectiveFilters, { activeIssueIds })),- [archived, open, items, effectiveFilters, activeIssueIds],+ () => (archived || !open ? null : inboxFacetCounts(items, effectiveFilters)),+ [archived, open, items, effectiveFilters],);const counts = {types: archived ? toMap(facets?.types) : localCounts?.types ?? NO_COUNTS,@@ -362,19 +360,6 @@ export function InboxFilterMenu({))}</>);- case "agent":- return INBOX_AGENT_FILTERS.map((agent) => {- const Icon = INBOX_AGENT_ICONS[agent];- return (- <ValueItem- key={agent}- checked={effectiveFilters.agent === agent}- onToggle={() => store.setAgent(wsId, agent)}- icon={<Icon className="size-3.5 text-muted-foreground" />}- label={labels.agent[agent]}- />- );- });case "project":return (<>@@ -463,12 +448,12 @@ export function InboxFilterMenu({// The dimensions in use when the menu opened go first; membership is// taken at open, so a row never jumps out from under the pointer.const activeKeys = activeAtOpen ?? new Set(activeInboxFilterKeys(effectiveFilters));- const group = (title: string, keys: readonly InboxFilterKey[]) => {+ const group = (title: string | null, keys: readonly InboxFilterKey[]) => {const shown = keys.filter((key) => available(key) && !activeKeys.has(key));if (shown.length === 0) return null;return (<DropdownMenuGroup>- <DropdownMenuLabel>{title}</DropdownMenuLabel>+ {title && <DropdownMenuLabel>{title}</DropdownMenuLabel>}{shown.map(section)}</DropdownMenuGroup>);@@ -496,7 +481,9 @@ export function InboxFilterMenu({valueHits.push(listHit("type", type, labels.type[type], <Icon className="size-3.5 text-muted-foreground" />));}}- for (const option of actorOptions) valueHits.push(listHit("actor", option.key, option.name, actorAvatar(option)));+ if (available("actor")) {+ for (const option of actorOptions) valueHits.push(listHit("actor", option.key, option.name, actorAvatar(option)));+ }if (available("received")) {for (const received of INBOX_RECEIVED_FILTERS) {valueHits.push({@@ -509,14 +496,6 @@ export function InboxFilterMenu({if (available("priority")) {for (const option of valueCatalog("priority")) valueHits.push(listHit("priority", option.value, option.label, option.icon));}- if (available("agent")) {- for (const agent of INBOX_AGENT_FILTERS) {- valueHits.push({- key: "agent", value: agent, label: labels.agent[agent], icon: null,- checked: effectiveFilters.agent === agent, onToggle: () => store.setAgent(wsId, agent),- });- }- }for (const dimension of ["project", "assignee", "label", "dueDate"] as const) {if (!available(dimension)) continue;for (const option of valueCatalog(dimension)) valueHits.push(listHit(dimension, option.value, option.label, option.icon));@@ -574,7 +553,8 @@ export function InboxFilterMenu({</>)}{group(t(($) => $.filters.section_notification), NOTIFICATION_KEYS)}- {group(t(($) => $.filters.section_issue), ISSUE_KEYS)}+ {/* With no notification fields the heading has nothing to tell apart. */}+ {group(archived ? t(($) => $.filters.section_issue) : null, ISSUE_KEYS)}{activeCount > 0 && (<><DropdownMenuSeparator />diff --git a/packages/views/inbox/components/inbox-filter-options.tsx b/packages/views/inbox/components/inbox-filter-options.tsxindex 77637a9e31..fcd3e0dceb 100644--- a/packages/views/inbox/components/inbox-filter-options.tsx+++ b/packages/views/inbox/components/inbox-filter-options.tsx@@ -2,11 +2,9 @@import { useQuery } from "@tanstack/react-query";import {- Activity,AtSign,Bell,Bot,- BotOff,CalendarClock,CircleDot,Clock,@@ -29,7 +27,6 @@ import {activeInboxFilterKeys,inboxActorKeyParts,useInboxFilterStore,- type InboxAgentFilter,type InboxFilterKey,type InboxFilters,type InboxReceivedFilter,@@ -50,7 +47,6 @@ export const INBOX_FILTER_ICONS: Record<InboxFilterKey, IconComponent> = {received: Clock,status: CircleDot,priority: SignalHigh,- agent: Bot,project: FolderKanban,assignee: User,label: Tag,@@ -67,11 +63,6 @@ export const INBOX_TYPE_ICONS: Record<InboxTypeGroup, IconComponent> = {system: Settings,};-export const INBOX_AGENT_ICONS: Record<InboxAgentFilter, IconComponent> = {- running: Activity,- idle: BotOff,-};-/** Display names for every dimension and the values that have no directory. */export function useInboxFilterLabels() {const { t } = useT("inbox");@@ -83,7 +74,6 @@ export function useInboxFilterLabels() {received: t(($) => $.filters.received),status: tIssues(($) => $.filters.section_status),priority: tIssues(($) => $.filters.section_priority),- agent: tIssues(($) => $.filters.section_agent_status),project: tIssues(($) => $.filters.section_project),assignee: tIssues(($) => $.filters.section_assignee),label: tIssues(($) => $.filters.section_label),@@ -103,15 +93,10 @@ export function useInboxFilterLabels() {last_7_days: t(($) => $.filters.received_last_7_days),last_30_days: t(($) => $.filters.received_last_30_days),};- const agent: Record<InboxAgentFilter, string> = {- running: tIssues(($) => $.filters.agent_status_running),- idle: t(($) => $.filters.agent_idle),- };return {dimension,type,received,- agent,unread: tIssues(($) => $.filters.read_state_unread),noProject: tIssues(($) => $.filters.no_project),noAssignee: tIssues(($) => $.filters.no_assignee),@@ -153,8 +138,6 @@ export function useInboxFilterChips(wsId: string, filters: InboxFilters): Filter);case "priority":return filters.priorities.map((priority) => tIssues(($) => $.priority[priority]));- case "agent":- return filters.agent ? [labels.agent[filters.agent]] : [];case "project":return filters.projects.map((id) =>id === FILTER_NONE_VALUE ? labels.noProject : projects.find((p) => p.id === id)?.title ?? "",diff --git a/packages/views/inbox/components/inbox-item-actions.tsx b/packages/views/inbox/components/inbox-item-actions.tsxindex 5f4dcf2400..cfb327c6e4 100644--- a/packages/views/inbox/components/inbox-item-actions.tsx+++ b/packages/views/inbox/components/inbox-item-actions.tsx@@ -1,6 +1,7 @@"use client";-import { Archive, ArchiveRestore, Check, CircleDot, ExternalLink, Trash2 } from "@multica/ui/icons";+import { Archive, ArchiveRestore, Check, CircleDot, Clock, ExternalLink, Trash2, Undo2 } from "@multica/ui/icons";+import { inboxSnoozeOptions, type InboxSnoozePreset } from "@multica/core/inbox/snooze";import { paths, useWorkspaceSlug } from "@multica/core/paths";import type { InboxItem } from "@multica/core/types";import type { RowActionItem } from "../../common/row-actions-menu";@@ -17,7 +18,12 @@ export interface InboxRowActions {* reversal-of-the-current-view the row's inline button performs.*/onAction: (id: string) => void;+ /** Delete for good. Offered in the archive only. */onDelete: (id: string) => void;+ /** Put the row's issue away until a time. Absent where snoozing is not offered. */+ onSnooze?: (id: string, until: Date) => void;+ /** Bring a snoozed issue back now. */+ onUnsnooze?: (id: string) => void;}/**@@ -47,6 +53,12 @@ export function useInboxItemActions(? paths.workspace(slug).issueDetail(item.issue_id): null;const isArchivedView = view === "archived";+ const snoozeLabel: Record<InboxSnoozePreset, string> = {+ in_one_hour: t(($) => $.context_menu.snooze_in_one_hour),+ later_today: t(($) => $.context_menu.snooze_later_today),+ tomorrow: t(($) => $.context_menu.snooze_tomorrow),+ next_week: t(($) => $.context_menu.snooze_next_week),+ };const groups: RowActionItem[][] = [];@@ -86,6 +98,35 @@ export function useInboxItemActions(]);}+ // Snoozing is for the main list: an archived row is already put away. The+ // menus have no room for a time field, so they offer the fixed choices and+ // the detail header's menu covers any other time.+ if (!isArchivedView) {+ const { onSnooze, onUnsnooze } = actions;+ const now = new Date();+ const snoozed =+ item.snoozed_until != null && new Date(item.snoozed_until).getTime() > now.getTime();+ if (snoozed && onUnsnooze) {+ groups.push([+ {+ key: "unsnooze",+ label: t(($) => $.context_menu.unsnooze),+ icon: <Undo2 className="h-4 w-4" />,+ onSelect: () => onUnsnooze(item.id),+ },+ ]);+ } else if (!snoozed && onSnooze) {+ groups.push(+ inboxSnoozeOptions(now).map((option) => ({+ key: `snooze-${option.preset}`,+ label: snoozeLabel[option.preset],+ icon: <Clock className="h-4 w-4" />,+ onSelect: () => onSnooze(item.id, option.until),+ })),+ );+ }+ }+groups.push([{key: "archive-toggle",@@ -101,15 +142,19 @@ export function useInboxItemActions(},]);- groups.push([- {- key: "delete",- label: t(($) => $.context_menu.delete),- icon: <Trash2 className="h-4 w-4" />,- danger: true,- onSelect: () => actions.onDelete(item.id),- },- ]);+ // Deleting is for the archive. In the main list a row leaves by being+ // handled, archived or snoozed, all of which can be undone.+ if (isArchivedView) {+ groups.push([+ {+ key: "delete",+ label: t(($) => $.context_menu.delete),+ icon: <Trash2 className="h-4 w-4" />,+ danger: true,+ onSelect: () => actions.onDelete(item.id),+ },+ ]);+ }return groups;}diff --git a/packages/views/inbox/components/inbox-list-item.test.tsx b/packages/views/inbox/components/inbox-list-item.test.tsxindex deb3ff7959..98cfe29fc5 100644--- a/packages/views/inbox/components/inbox-list-item.test.tsx+++ b/packages/views/inbox/components/inbox-list-item.test.tsx@@ -2,10 +2,11 @@ import { fireEvent, render, screen } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";import { WorkspaceSlugProvider } from "@multica/core/paths";import { buildIssueStatusCatalog } from "@multica/core/issue-statuses";+import type { InboxSectionRow } from "@multica/core/inbox/sections";import type { InboxItem, IssueStatusEntry } from "@multica/core/types";import { NavigationProvider } from "../../navigation";import type { NavigationAdapter } from "../../navigation";-import { InboxListItem } from "./inbox-list-item";+import { InboxListItem, type InboxRowSection } from "./inbox-list-item";// The catalog is server state; these suites render leaves without a// QueryClientProvider, so it is stubbed like the other data hooks. The real@@ -77,7 +78,15 @@ vi.mock("./inbox-detail-label", () => ({autopilot_quota_exceeded: "Autopilot run limit reached",}),}));-vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "label" }) }));+vi.mock("./inbox-reason-label", () => ({+ InboxReasonLabel: ({ reason, preview }: { reason: InboxItem; preview?: InboxItem | null }) => (+ <span data-testid="reason" data-reason-id={reason.id} data-preview-id={preview?.id ?? ""} />+ ),+}));+vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getActorName: (type: string, id: string) => `${type}:${id}` }),+}));+vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "label" }), useLocale: () => "en-GB" }));function item(overrides: Partial<InboxItem> = {}): InboxItem {return {@@ -121,6 +130,8 @@ function renderRow(props: {view: "inbox" | "archived";adapter?: NavigationAdapter;onClick?: () => void;+ section?: InboxRowSection;+ row?: Partial<InboxSectionRow>;isSelected?: boolean;}) {return render(@@ -132,6 +143,12 @@ function renderRow(props: {isSelected={props.isSelected ?? false}onClick={props.onClick ?? vi.fn()}onAction={vi.fn()}+ section={props.section}+ row={+ props.section+ ? { item: props.item, reason: null, snoozedUntil: null, preview: null, ...props.row }+ : undefined+ }/></NavigationProvider></WorkspaceSlugProvider>,@@ -169,6 +186,108 @@ describe("InboxListItem unread affordance", () => {});});+describe("InboxListItem under Needs you", () => {+ it("keeps a read row at full strength: it is read, not handled", () => {+ const { container } = renderRow({ item: item({ read: true }), view: "inbox", section: "needs_you" });++ expect(unreadDot(container)).toBeNull();+ expect(title(container)?.className).not.toContain("font-medium");+ expect(title(container)?.className).not.toContain("text-muted-foreground");+ });++ it("still marks an unread row", () => {+ const { container } = renderRow({ item: item({ read: false }), view: "inbox", section: "needs_you" });++ expect(unreadDot(container)).not.toBeNull();+ expect(title(container)?.className).toContain("font-medium");+ });++ it("leads with why the issue waits, and shows who is waiting", () => {+ const reason = item({ id: "inbox-ask", type: "agent_blocked", actor_id: "agent-asking" });+ const preview = item({ id: "inbox-said", body: "Which region?" });+ const { getByTestId } = renderRow({+ item: item({ id: "inbox-latest", type: "status_changed", actor_type: "member", actor_id: "member-9" }),+ view: "inbox",+ section: "needs_you",+ row: { reason, preview },+ });++ expect(getByTestId("reason").getAttribute("data-reason-id")).toBe("inbox-ask");+ expect(getByTestId("reason").getAttribute("data-preview-id")).toBe("inbox-said");+ expect(getByTestId("actor-avatar").getAttribute("data-actor-id")).toBe("agent-asking");+ });++ it("keeps the status glyph and the agent badge beside the time", () => {+ const { getByTestId } = renderRow({+ item: item({ issue_status: "in_review" }),+ view: "inbox",+ section: "needs_you",+ });++ expect(getByTestId("status-icon").getAttribute("data-status")).toBe("in_review");+ expect(getByTestId("issue-agent-activity")).toBeInTheDocument();+ });+});++describe("InboxListItem under Updates", () => {+ it("is a quieter row: who did it, and no status or agent badge", () => {+ const { container, queryByTestId, getByText } = renderRow({+ item: item({ read: true, issue_status: "in_review", actor_type: "member", actor_id: "member-9" }),+ view: "inbox",+ section: "updates",+ });++ expect(title(container)?.className).toContain("text-muted-foreground");+ expect(getByText("member:member-9")).toBeInTheDocument();+ expect(queryByTestId("status-icon")).toBeNull();+ expect(queryByTestId("issue-agent-activity")).toBeNull();+ expect(queryByTestId("reason")).toBeNull();+ });++ it("still marks an unread update", () => {+ const { container } = renderRow({ item: item({ read: false }), view: "inbox", section: "updates" });++ expect(unreadDot(container)).not.toBeNull();+ });+});++describe("InboxListItem under Snoozed", () => {+ it("is one line: the title and when it comes back", () => {+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(new Date(2026, 5, 17, 14, 20));+ try {+ const { container, queryByTestId, getByText } = renderRow({+ item: item({ read: true, issue_status: "todo" }),+ view: "inbox",+ section: "snoozed",+ row: { snoozedUntil: new Date(2026, 5, 17, 18, 0).toISOString() },+ });++ expect(getByText("18:00")).toBeInTheDocument();+ expect(title(container)?.className).toContain("text-muted-foreground");+ expect(queryByTestId("actor-avatar")).toBeNull();+ expect(queryByTestId("status-icon")).toBeNull();+ expect(container.querySelector("p")).toBeNull();+ } finally {+ vi.useRealTimers();+ }+ });+});++describe("InboxListItem under Snoozed, while unread", () => {+ it("shows no unread mark: snoozing made it unread so it returns as new", () => {+ const { container } = renderRow({+ item: item({ read: false }),+ view: "inbox",+ section: "snoozed",+ row: { snoozedUntil: new Date(Date.now() + 3_600_000).toISOString() },+ });++ expect(unreadDot(container)).toBeNull();+ expect(title(container)?.className).not.toContain("font-medium");+ });+});+describe("InboxListItem theme hooks", () => {it("marks the row open in the detail pane as selected", () => {const anchor = (container: HTMLElement) => container.querySelector('[data-mc="inbox-item"]');diff --git a/packages/views/inbox/components/inbox-list-item.tsx b/packages/views/inbox/components/inbox-list-item.tsxindex 3f0252c879..7126421914 100644--- a/packages/views/inbox/components/inbox-list-item.tsx+++ b/packages/views/inbox/components/inbox-list-item.tsx@@ -7,10 +7,14 @@ import {} from "../../issues/components/issue-agent-activity-indicator";import { ActorAvatar } from "../../common/actor-avatar";import { DeferredTooltip } from "../../common/deferred-tooltip";-import { Archive, ArchiveRestore } from "@multica/ui/icons";+import { Archive, ArchiveRestore, Clock } from "@multica/ui/icons";+import type { InboxSectionRow } from "@multica/core/inbox/sections";import type { InboxItem } from "@multica/core/types";+import { useActorName } from "@multica/core/workspace/hooks";import type { InboxView } from "./inbox-view";import { InboxDetailLabel, useTypeLabels } from "./inbox-detail-label";+import { InboxReasonLabel } from "./inbox-reason-label";+import { formatSnoozeTime } from "./inbox-snooze-time";import {getInboxDisplayTitle,isAutopilotQuotaNotice,@@ -19,7 +23,7 @@ import { useInboxContextMenu } from "./inbox-context-menu";import { useStatusLabel } from "../../issues/utils/status-label";import { InboxRowMenu } from "./inbox-row-menu";import { handleRowActivationKey } from "../../common/row-actions-menu";-import { useT } from "../../i18n";+import { useLocale, useT } from "../../i18n";import { paths, useWorkspaceSlug } from "@multica/core/paths";import { resolveClickIntent, useIntentNavigate } from "../../navigation";@@ -40,12 +44,34 @@ export function useTimeAgo() {};}+// The two below are components so that only the rows that show them+// subscribe to what they read: the workspace's people, and the locale.++function InboxActorName({ actorType, actorId }: { actorType: string; actorId: string }) {+ const { getActorName } = useActorName();+ return <span className="shrink-0">{getActorName(actorType, actorId)}</span>;+}++function InboxSnoozeTime({ until }: { until: string }) {+ const locale = useLocale();+ return (+ <span className="text-caption text-muted-foreground">+ {formatSnoozeTime(new Date(until), new Date(), locale)}+ </span>+ );+}++/** The section a row is listed under, which decides how much of it shows. */+export type InboxRowSection = "needs_you" | "updates" | "snoozed";+export function InboxListItem({item,view,isSelected,onClick,onAction,+ section,+ row,}: {item: InboxItem;view: InboxView;@@ -54,6 +80,14 @@ export function InboxListItem({// Archive in the main list, unarchive in the archived one — the row action is// always the reversal of the current view, so the two lists share this row.onAction: () => void;+ /**+ * Set by the sectioned main list. "Needs you" rows are the full two lines+ * and lead with why the issue waits; "Updates" and "Snoozed" rows are+ * smaller and quieter, because nothing in them is waiting. Absent in the+ * archive, whose rows are as they always were.+ */+ section?: InboxRowSection;+ row?: InboxSectionRow;}) {const { t } = useT("inbox");const timeAgo = useTimeAgo();@@ -80,12 +114,19 @@ export function InboxListItem({// Archiving deliberately leaves `read` untouched so unarchiving restores the// real unread state, so archived rows would otherwise keep an unread marker// the user cannot clear from this view. Suppress the affordance here only.- const showUnread = item.read !== true && !isArchivedView;+ // A snoozed row is unread on purpose, so the issue comes back as new when+ // its time passes; until then it is put away and shows nothing to do.+ const showUnread = item.read !== true && !isArchivedView && section !== "snoozed";const ActionIcon = isArchivedView ? ArchiveRestore : Archive;const actionLabel = isArchivedView? t(($) => $.list.unarchive_tooltip): t(($) => $.list.archive_tooltip);- const actorType = item.actor_type ?? item.recipient_type;+ // A "Needs you" row shows who is waiting, which is whoever sent the+ // notification that put it there, not whoever touched the issue last.+ const actor = (section === "needs_you" ? row?.reason : null) ?? item;+ const actorType = actor.actor_type ?? actor.recipient_type;+ const actorId = actor.actor_id ?? actor.recipient_id;+ const compact = section === "updates" || section === "snoozed";// The glyph is per CATEGORY, so it alone cannot tell "In Review" from a// custom "Human Review" — moving between two statuses of the same category// left this row pixel-identical and read as "the inbox never updated"@@ -129,18 +170,28 @@ export function InboxListItem({onContextMenu={openContextMenu ? (e) => openContextMenu(item, e) : undefined}- className={`group flex w-full cursor-default select-none items-center gap-2.5 rounded-md px-2 py-2.5 text-left outline-none transition-colors focus-visible:ring-1 focus-visible:ring-ring ${+ data-section={section}+ className={`group flex w-full cursor-default select-none items-center rounded-md px-2 text-left outline-none transition-colors focus-visible:ring-1 focus-visible:ring-ring ${+ compact ? "gap-2 py-1.5" : "gap-2.5 py-2.5"+ } ${isSelected? "bg-accent": "hover:bg-accent/50 data-[popup-open]:bg-accent/50"}`}>- <ActorAvatar- actorType={actorType}- actorId={item.actor_id ?? item.recipient_id}- size="lg"- enableHoverCard- />+ {section === "snoozed" ? (+ // The row's width matches the small avatar the rows above it carry.+ <span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground">+ <Clock className="h-3.5 w-3.5" />+ </span>+ ) : (+ <ActorAvatar+ actorType={actorType}+ actorId={actorId}+ size={compact ? "sm" : "lg"}+ enableHoverCard+ />+ )}<div className="min-w-0 flex-1"><div className="flex items-center justify-between gap-2"><div className="flex min-w-0 items-center gap-1.5">@@ -148,7 +199,15 @@ export function InboxListItem({<span data-mc="unread-dot" className="h-1.5 w-1.5 shrink-0 rounded-full bg-brand" />)}<span- className={`truncate text-body ${showUnread ? "font-medium" : "text-muted-foreground"}`}+ className={`truncate text-body ${+ showUnread+ ? "font-medium"+ : // Read is not handled: a "Needs you" row keeps its colour+ // until the issue leaves the section.+ section === "needs_you"+ ? ""+ : "text-muted-foreground"+ }`}>{displayTitle}</span>@@ -175,12 +234,37 @@ export function InboxListItem({}/><InboxRowMenu item={item} view={view} />+ {section === "snoozed" && row?.snoozedUntil && (+ <InboxSnoozeTime until={row.snoozedUntil} />+ )}</div></div>+ {section !== "snoozed" && (<div className="mt-0.5 flex items-center justify-between gap-2">- <p className={`min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-caption ${showUnread ? "text-muted-foreground" : "text-muted-foreground"}`}>- <InboxDetailLabel item={item} />+ <p className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-caption text-muted-foreground">+ {section === "needs_you" && row?.reason ? (+ <InboxReasonLabel reason={row.reason} latest={item} preview={row.preview} />+ ) : section === "updates" ? (+ // Who did what: the avatar is too small here to carry the name.+ <span className="flex min-w-0 items-center gap-1">+ {item.actor_id && (+ <InboxActorName actorType={item.actor_type ?? "member"} actorId={item.actor_id} />+ )}+ <span className="min-w-0 truncate">+ <InboxDetailLabel item={item} />+ </span>+ </span>+ ) : (+ <InboxDetailLabel item={item} />+ )}</p>+ {section === "updates" ? (+ // Only when: nothing here waits on the user, so the row carries+ // neither the issue's status nor the agent badge.+ <span className="shrink-0 text-caption text-muted-foreground">+ {timeAgo(item.created_at)}+ </span>+ ) : (<div className="flex shrink-0 items-center gap-1.5">{/* Badge only, no hover card (MUL-5189). "An agent is on this"is worth showing while triaging; the card behind it adds only@@ -212,11 +296,13 @@ export function InboxListItem({/></span>)}- <span className={`text-caption ${showUnread ? "text-muted-foreground" : "text-muted-foreground"}`}>+ <span className="text-caption text-muted-foreground">{timeAgo(item.created_at)}</span></div>+ )}</div>+ )}</div></div>);diff --git a/packages/views/inbox/components/inbox-page-query.test.tsx b/packages/views/inbox/components/inbox-page-query.test.tsxindex 04c9f7f8c6..6af155196f 100644--- a/packages/views/inbox/components/inbox-page-query.test.tsx+++ b/packages/views/inbox/components/inbox-page-query.test.tsx@@ -8,6 +8,7 @@ import { EMPTY_INBOX_FILTERS, filterInboxItems, useInboxFilterStore, type InboxFimport { archivedInboxLookupOptions, inboxKeys } from "@multica/core/inbox/queries";import { useInboxSelectionStore } from "@multica/core/inbox/selection-store";import { onInboxIssueDeleted, patchInboxIssueProjection } from "@multica/core/inbox/ws-updaters";+import type { InboxSections } from "@multica/core/inbox/sections";import type { ArchivedInboxPage } from "@multica/core/types/inbox";import type { InboxItem } from "@multica/core/types";import { InboxPage } from "./inbox-page";@@ -47,6 +48,17 @@ vi.mock("./inbox-list", () => ({))}</div>),}));+vi.mock("./inbox-sectioned-list", () => ({+ InboxSectionedList: ({ sections, onSelect }: { sections: InboxSections; onSelect: (item: InboxItem) => void }) => (+ <div>{[...sections.needsYou, ...sections.updates, ...sections.snoozed].map(({ item: row }) => (+ <button key={row.id} data-read={row.read} onClick={() => onSelect(row)}>{row.id}</button>+ ))}</div>+ ),+}));+vi.mock("@multica/core/auth", () => ({+ useAuthStore: (selector: (state: { user: { id: string } }) => unknown) =>+ selector({ user: { id: "member-1" } }),+}));const filterMenuUnmounted = vi.hoisted(() => vi.fn());vi.mock("./inbox-filter-menu", () => ({InboxFilterMenu: () => {@@ -65,7 +77,7 @@ vi.mock("./inbox-context-menu", () => ({vi.mock("./inbox-detail-label", () => ({ useTypeLabels: () => ({}) }));vi.mock("../../i18n", () => {const t = () => "Inbox";- return { useT: () => ({ t }) };+ return { useT: () => ({ t }), useLocale: () => "en" };});function item(overrides: Partial<InboxItem> = {}): InboxItem {@@ -273,26 +285,6 @@ async function openArchived(fixture: ReturnType<typeof archivedFixture>, viaUrlreturn detail;}-it("keeps the active read selection until moving to another notification", async () => {- let rows = [item(), item({ id: "inbox-b", issue_id: "issue-b" })];- const listInbox = vi.fn(async () => rows);- const markInboxRead = vi.fn(async (id: string) => {- rows = rows.map((row) => row.id === id ? { ...row, read: true } : row);- return rows.find((row) => row.id === id)!;- });- setApiInstance({ listInbox, markInboxRead, getInboxUnreadSummary: async () => [] } as unknown as ApiClient);- renderPage();- fireEvent.click(await screen.findByText("inbox-a"));- await waitFor(() => expect(listInbox).toHaveBeenCalledTimes(2));- expect(screen.getByText("inbox-a")).toHaveAttribute("data-read", "true");- expect(screen.getByTestId("detail")).toHaveTextContent("issue-a");- fireEvent.click(screen.getByText("inbox-b"));- await waitFor(() => expect(listInbox).toHaveBeenCalledTimes(3));- expect(screen.getByTestId("detail")).toHaveTextContent("issue-b");- expect(screen.queryByText("inbox-a")).not.toBeInTheDocument();- expect(screen.getByText("inbox-b")).toHaveAttribute("data-read", "true");-});-it.each(["click", "url"])("keeps the archived row and detail mounted through refetch and slow lookup after %s selection, then releases the pin", async (selection) => {const fixture = archivedFixture();const detail = await openArchived(fixture, selection === "url");diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsxindex a27897741f..91c0e1caaa 100644--- a/packages/views/inbox/components/inbox-page.test.tsx+++ b/packages/views/inbox/components/inbox-page.test.tsx@@ -2,7 +2,8 @@ import { act, fireEvent, render, screen } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";import { toast } from "sonner";import { ApiError } from "@multica/core/api";-import type { AgentTask, InboxItem } from "@multica/core/types";+import type { InboxSections } from "@multica/core/inbox/sections";+import type { AgentTask, InboxItem, Issue } from "@multica/core/types";import { useInboxFilterStore } from "@multica/core/inbox/filter-store";import { useInboxSelectionStore } from "@multica/core/inbox/selection-store";import { InboxPage } from "./inbox-page";@@ -15,10 +16,20 @@ vi.mock("sonner", () => ({// The page runs two queries — the active list and the archived one. They are// told apart by the queryKey their options carry, so each test can stock the// two lists independently.-const listData: { active: InboxItem[]; archived: InboxItem[]; lookup?: InboxItem[]; tasks: AgentTask[] } = {+const listData: {+ active: InboxItem[];+ archived: InboxItem[];+ lookup?: InboxItem[];+ tasks: AgentTask[];+ tasksPending: boolean;+ /** Issue details already in the cache, by id. One that is absent is loading. */+ issues: Record<string, Partial<Issue>>;+} = {active: [],archived: [],tasks: [],+ tasksPending: false,+ issues: {},};const queryCalls: Array<{ queryKey: readonly unknown[]; enabled?: boolean }> = [];@@ -37,7 +48,22 @@ vi.mock("@tanstack/react-query", () => ({isError: false,refetch: vi.fn(),...(options.queryKey.includes("lookup") ? lookupState : {}),+ ...(options.queryKey.includes("agent-task-snapshot") ? { isPending: listData.tasksPending } : {}),}); },+ // "Working" rows are tested against their issue under a filter.+ useQueries: ({+ queries,+ combine,+ }: {+ queries: Array<{ queryKey: readonly unknown[] }>;+ combine: (results: Array<{ data: unknown; isPending: boolean }>) => unknown;+ }) =>+ combine(+ queries.map((query) => {+ const issue = listData.issues[String(query.queryKey.at(-1))];+ return { data: issue, isPending: !issue };+ }),+ ),useInfiniteQuery: (options: { queryKey: readonly unknown[]; enabled?: boolean }) => {queryCalls.push(options);return ({@@ -86,6 +112,9 @@ const markReadMutate = vi.fn();const markUnreadMutate = vi.fn();const archiveMutate = vi.fn();const unarchiveMutate = vi.fn();+const snoozeMutate = vi.fn();+const unsnoozeMutate = vi.fn();+const archiveUpdatesMutate = vi.fn();const retrySourceContextMutateAsync = vi.fn();const showIssueLimitUpgradePrompt = vi.hoisted(() => vi.fn());const showAutopilotQuotaRecoveryPrompt = vi.hoisted(() => vi.fn());@@ -98,16 +127,14 @@ vi.mock("../../modals/use-issue-limit-upgrade-prompt", () => ({}));vi.mock("@multica/core/inbox/mutations", () => {- const mutation = () => ({ mutate: vi.fn() });return {useMarkInboxRead: () => ({ mutate: markReadMutate }),useMarkInboxUnread: () => ({ mutate: markUnreadMutate }),useArchiveInbox: () => ({ mutate: archiveMutate }),useUnarchiveInbox: () => ({ mutate: unarchiveMutate }),- useMarkAllInboxRead: mutation,- useArchiveAllInbox: mutation,- useArchiveAllReadInbox: mutation,- useArchiveCompletedInbox: mutation,+ useSnoozeInbox: () => ({ mutate: snoozeMutate }),+ useUnsnoozeInbox: () => ({ mutate: unsnoozeMutate }),+ useArchiveInboxUpdates: () => ({ mutate: archiveUpdatesMutate }),useRetrySourceContextQuickCreate: () => ({mutateAsync: retrySourceContextMutateAsync,isPending: false,@@ -124,11 +151,37 @@ const issueDetailProps = vi.hoisted(vi.mock("../../issues/components/issue-detail", () => ({IssueDetail: (props: Record<string, unknown>) => {issueDetailProps.push(props);- return null;+ // The header slot the inbox fills with its own actions.+ return <>{props.hostActions as React.ReactNode}</>;},issueHighlightMementoKey: (issueId: string) => `highlight:${issueId}`,}));+// The header actions as bare controls, so a test can drive what the page+// wired into them and read back the state it passed down.+const SNOOZE_UNTIL = new Date("2026-06-18T01:00:00Z");+vi.mock("./inbox-detail-actions", () => ({+ InboxDetailActions: ({+ snoozed,+ snoozeOpen,+ onSnooze,+ onUnsnooze,+ onArchive,+ }: {+ snoozed: boolean;+ snoozeOpen: boolean;+ onSnooze: (until: Date) => void;+ onUnsnooze: () => void;+ onArchive: () => void;+ }) => (+ <div data-testid="detail-actions" data-snoozed={String(snoozed)} data-snooze-open={String(snoozeOpen)}>+ <button type="button" data-testid="detail-snooze" onClick={() => onSnooze(SNOOZE_UNTIL)} />+ <button type="button" data-testid="detail-unsnooze" onClick={onUnsnooze} />+ <button type="button" data-testid="detail-archive" onClick={onArchive} />+ </div>+ ),+}));+const replace = vi.fn();let searchParams = new URLSearchParams();@@ -180,13 +233,73 @@ vi.mock("./inbox-list", () => ({</div>),}));+// The main view's list, flattened in section order. Rows keep the `row` test+// id whichever section they are in, so a test that only cares that a row is+// listed does not have to know where; `data-section` is there for the ones+// that do. "Working" rows are issues, not notifications, and get their own id.+vi.mock("./inbox-sectioned-list", () => ({+ InboxSectionedList: ({+ sections,+ onSelect,+ onSelectIssue,+ onClearUpdates,+ emptyLabel,+ emptyAction,+ }: {+ sections: InboxSections;+ onSelect: (item: InboxItem) => void;+ onSelectIssue: (issueId: string) => void;+ onClearUpdates?: () => void;+ emptyLabel?: string;+ emptyAction?: React.ReactNode;+ }) => {+ const groups = [+ ["needs_you", sections.needsYou],+ ["updates", sections.updates],+ ["snoozed", sections.snoozed],+ ] as const;+ const empty = groups.every(([, rows]) => rows.length === 0) && sections.working.length === 0;+ return (+ <div data-testid="list" data-view="inbox">+ {groups.slice(0, 1).map(([section, rows]) =>+ rows.map((row) => (+ <button key={row.item.id} data-testid="row" data-section={section} onClick={() => onSelect(row.item)}>+ {row.item.id}+ </button>+ )),+ )}+ {sections.working.map((row) => (+ <button key={row.issueId} data-testid="working-row" onClick={() => onSelectIssue(row.issueId)}>+ {row.issueId}+ </button>+ ))}+ {groups.slice(1).map(([section, rows]) =>+ rows.map((row) => (+ <button key={row.item.id} data-testid="row" data-section={section} onClick={() => onSelect(row.item)}>+ {row.item.id}+ </button>+ )),+ )}+ {sections.updates.length > 0 && (+ <button type="button" data-testid="clear-updates" onClick={onClearUpdates} />+ )}+ {empty && emptyLabel && <p>{emptyLabel}</p>}+ {empty && emptyAction}+ </div>+ );+ },+}));+vi.mock("@multica/core/auth", () => ({+ useAuthStore: (selector: (state: { user: { id: string } }) => unknown) =>+ selector({ user: { id: "member-1" } }),+}));vi.mock("./inbox-filter-menu", () => ({InboxFilterMenu: () => <button type="button">Filter inbox</button>,}));vi.mock("./inbox-list-item", () => ({ useTimeAgo: () => vi.fn() }));vi.mock("./inbox-filter-options", () => ({- InboxFilterChipsBar: ({ filters }: { filters: { types: string[]; agent: string | null } }) => (- <div data-testid="filter-chips" data-types={filters.types.join(",")} data-agent={filters.agent ?? ""} />+ InboxFilterChipsBar: ({ filters }: { filters: { types: string[] } }) => (+ <div data-testid="filter-chips" data-types={filters.types.join(",")} />),}));@@ -196,6 +309,8 @@ let rowActions: {onMarkRead: (id: string) => void;onMarkUnread: (id: string) => void;onAction: (id: string) => void;+ onSnooze: (id: string, until: Date) => void;+ onUnsnooze: (id: string) => void;} | null = null;vi.mock("./inbox-context-menu", () => ({InboxContextMenuProvider: ({@@ -225,7 +340,7 @@ vi.mock("./autopilot-quota-notice", () => ({</button>),}));-vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "Inbox" }) }));+vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "Inbox" }), useLocale: () => "en" }));function item(overrides: Partial<InboxItem> = {}): InboxItem {return {@@ -256,6 +371,8 @@ function reset() {listData.archived = [];listData.lookup = undefined;listData.tasks = [];+ listData.tasksPending = false;+ listData.issues = {};lookupState.isLoading = false;lookupState.isError = false;lookupState.refetch.mockClear();@@ -266,6 +383,9 @@ function reset() {markUnreadMutate.mockClear();archiveMutate.mockClear();unarchiveMutate.mockClear();+ snoozeMutate.mockClear();+ unsnoozeMutate.mockClear();+ archiveUpdatesMutate.mockClear();retrySourceContextMutateAsync.mockReset();retrySourceContextMutateAsync.mockResolvedValue({});showIssueLimitUpgradePrompt.mockClear();@@ -280,55 +400,6 @@ function reset() {}describe("InboxPage", () => {- it.each([false, true])("enabling idle hides an already busy row with unread pin=%s", (unreadOnly) => {- reset();- layout.width = DESKTOP;- listData.active = [item({ id: "busy-row", issue_id: "busy-issue", read: !unreadOnly })];- listData.tasks = [{ id: "task-a", agent_id: "agent-1", issue_id: "busy-issue", status: "running" }] as AgentTask[];- if (unreadOnly) useInboxFilterStore.getState().toggleUnreadOnly("workspace-1");- markReadMutate.mockImplementation(() => {- listData.active = listData.active.map((current) => ({ ...current, read: true }));- });- const { rerender } = render(<InboxPage />);- fireEvent.click(screen.getByTestId("row"));- rerender(<InboxPage />);- expect(screen.getByTestId("row")).toHaveTextContent("busy-row");-- act(() => useInboxFilterStore.getState().setAgent("workspace-1", "idle"));-- expect(screen.queryByTestId("row")).toBeNull();- });-- it("enabling unread hides a read row pinned by idle", () => {- reset();- layout.width = DESKTOP;- listData.active = [item({ id: "read-row", issue_id: "idle-issue", read: true })];- useInboxFilterStore.getState().setAgent("workspace-1", "idle");- render(<InboxPage />);- fireEvent.click(screen.getByTestId("row"));-- act(() => useInboxFilterStore.getState().toggleUnreadOnly("workspace-1"));-- expect(screen.queryByTestId("row")).toBeNull();- });-- it("re-enabling idle evaluates current activity after disabling it", () => {- reset();- layout.width = DESKTOP;- listData.active = [item({ id: "was-idle", issue_id: "issue-a", read: true })];- useInboxFilterStore.getState().setAgent("workspace-1", "idle");- const { rerender } = render(<InboxPage />);- fireEvent.click(screen.getByTestId("row"));- act(() => useInboxFilterStore.getState().setAgent("workspace-1", "idle"));- listData.tasks = [{ id: "task-a", agent_id: "agent-1", issue_id: "issue-a", status: "running" }] as AgentTask[];- rerender(<InboxPage />);- expect(screen.getByTestId("row")).toHaveTextContent("was-idle");-- act(() => useInboxFilterStore.getState().setAgent("workspace-1", "idle"));-- expect(screen.queryByTestId("row")).toBeNull();- });-// Inbox rows need more room than the nav's labels, so the list is sized by// the list width rather than the space panel's.it("sizes the desktop list with the list column width", () => {@@ -342,15 +413,11 @@ describe("InboxPage", () => {);});- it("keeps the title unread count static", () => {+ it("leaves the count to the section it counts, not the title", () => {reset();const { container } = render(<InboxPage />);- const titleCount = container.querySelector("h1")?.parentElement?.querySelector(- "number-flow-react",- ) as (HTMLElement & { animated?: boolean }) | null;- expect(titleCount?.getAttribute("aria-label")).toBe("2");- expect(titleCount?.animated).toBe(false);+ expect(container.querySelector("h1")?.parentElement?.querySelector("number-flow-react")).toBeNull();});it("shows the active list by default", () => {@@ -391,87 +458,41 @@ describe("InboxPage", () => {expect(screen.getByTestId("row")).toHaveTextContent("done-low");});- it("hides read notifications while the unread filter is on", () => {- reset();- listData.active = [- item({ id: "unread-row", issue_id: "issue-1", read: false }),- item({ id: "read-row", issue_id: "issue-2", read: true }),- ];- useInboxFilterStore.getState().toggleUnreadOnly("workspace-1");-- render(<InboxPage />);-- expect(screen.getAllByTestId("row")).toHaveLength(1);- expect(screen.getByTestId("row")).toHaveTextContent("unread-row");- });-- it("filters by the actor the row carries", () => {+ it("leaves the filters that describe a notification to the archive", () => {+ // Read state, type, sender and age are what the sections already sort by.+ // A choice made in the archive is kept for it, and does nothing here.reset();listData.active = [- item({ id: "from-alice", issue_id: "issue-1", actor_type: "member", actor_id: "alice" }),- item({ id: "from-bob", issue_id: "issue-2", actor_type: "agent", actor_id: "bob" }),- ];- useInboxFilterStore.getState().toggleActorFilter("workspace-1", "member:alice");-- render(<InboxPage />);-- expect(screen.getAllByTestId("row")).toHaveLength(1);- expect(screen.getByTestId("row")).toHaveTextContent("from-alice");- });-- it("matches a type on any notification of an issue and shows the newest match", () => {- reset();- listData.active = [- item({ id: "newest-comment", issue_id: "issue-1", type: "new_comment", created_at: "2026-06-15T09:00:00Z" }),- item({ id: "older-mention", issue_id: "issue-1", type: "mentioned", created_at: "2026-06-15T08:00:00Z" }),- item({ id: "other-comment", issue_id: "issue-2", type: "new_comment" }),- ];- useInboxFilterStore.getState().toggleFilterValue("workspace-1", "type", "mention");-- render(<InboxPage />);-- expect(screen.getAllByTestId("row")).toHaveLength(1);- expect(screen.getByTestId("row")).toHaveTextContent("older-mention");- expect(screen.getByTestId("filter-chips").dataset.types).toBe("mention");- });-- it("keeps a type filtered out with is not", () => {- reset();- listData.active = [- item({ id: "mention", issue_id: "issue-1", type: "mentioned" }),- item({ id: "comment", issue_id: "issue-2", type: "new_comment" }),+ item({ id: "unread-mention", issue_id: "issue-1", type: "mentioned", read: false, actor_type: "member", actor_id: "alice" }),+ item({ id: "read-comment", issue_id: "issue-2", type: "new_comment", read: true, actor_type: "agent", actor_id: "bob" }),];const filters = useInboxFilterStore.getState();+ filters.toggleUnreadOnly("workspace-1");+ filters.toggleActorFilter("workspace-1", "member:alice");filters.toggleFilterValue("workspace-1", "type", "mention");- filters.setFilterNegated("workspace-1", "type", true);+ filters.setReceived("workspace-1", "today");render(<InboxPage />);- expect(screen.getAllByTestId("row")).toHaveLength(1);- expect(screen.getByTestId("row")).toHaveTextContent("comment");+ expect(screen.getAllByTestId("row").map((row) => row.textContent)).toEqual(["unread-mention", "read-comment"]);+ expect(screen.getByTestId("filter-chips").dataset.types).toBe("");+ expect(useInboxFilterStore.getState().filtersByWorkspace["workspace-1"]).toMatchObject({+ unreadOnly: true,+ types: ["mention"],+ });});- it("hides issues an agent is running or queued on while the idle filter is on", () => {+ it("keeps a notification filter in force in the archive", () => {reset();- listData.active = [- item({ id: "running", issue_id: "issue-1" }),- item({ id: "queued", issue_id: "issue-2" }),- item({ id: "finished", issue_id: "issue-3" }),- item({ id: "untouched", issue_id: "issue-4" }),+ searchParams = new URLSearchParams("view=archived");+ listData.archived = [+ item({ id: "mention", issue_id: "issue-1", type: "mentioned", archived: true, issue_label_ids: [] }),];- listData.tasks = [- { id: "task-1", agent_id: "agent-1", issue_id: "issue-1", status: "running" },- { id: "task-2", agent_id: "agent-1", issue_id: "issue-2", status: "queued" },- { id: "task-3", agent_id: "agent-1", issue_id: "issue-3", status: "completed" },- ] as AgentTask[];- useInboxFilterStore.getState().setAgent("workspace-1", "idle");+ useInboxFilterStore.getState().toggleFilterValue("workspace-1", "type", "mention");render(<InboxPage />);- expect(screen.getAllByTestId("row").map((row) => row.textContent)).toEqual([- "finished",- "untouched",- ]);+ expect(screen.getByTestId("filter-chips").dataset.types).toBe("mention");});it("offers to clear filters when they hide every notification", () => {@@ -490,7 +511,7 @@ describe("InboxPage", () => {render(<InboxPage />);expect(screen.queryByTestId("row")).toBeNull();- // The test's `useT` names every control "Inbox"; the header's batch menu+ // The test's `useT` names every control "Inbox"; the title's view switch// shares the name, so skip the menu trigger.const clearFilters = screen.getAllByRole("button", { name: "Inbox" })@@ -621,33 +642,13 @@ describe("InboxPage", () => {expect(screen.getByTestId("list").dataset.view).toBe("archived");});- it("hides the batch-actions menu in the archived view", () => {- // Every batch action archives from the MAIN inbox; offering them over the- // archived list would read as "archive all of these" and do the opposite.+ it("has no batch menu: nothing leaves Needs you in bulk", () => {reset();- listData.archived = [item({ id: "archived-1", archived: true })];- const batchMenu = ':not(h1) > [aria-haspopup="menu"]';- const { container: mainView } = render(<InboxPage />);- expect(mainView.querySelector(batchMenu)).not.toBeNull();-- searchParams = new URLSearchParams("view=archived");- const { container: archivedView } = render(<InboxPage />);- expect(archivedView.querySelector(batchMenu)).toBeNull();- });-- it("ignores a carried-over idle selection in the archive", () => {- reset();- searchParams = new URLSearchParams("view=archived");- listData.archived = [item({ id: "archived-busy", issue_id: "issue-1", archived: true })];- listData.tasks = [- { id: "task-1", agent_id: "agent-1", issue_id: "issue-1", status: "running" },- ] as AgentTask[];- useInboxFilterStore.getState().setAgent("workspace-1", "idle");-- render(<InboxPage />);+ listData.active = [item({ id: "active-1" })];+ const { container } = render(<InboxPage />);- expect(screen.getByTestId("row")).toHaveTextContent("archived-busy");- expect(screen.getByTestId("filter-chips").dataset.agent).toBe("");+ // The title's view switch is the only menu the header opens.+ expect(container.querySelector(':not(h1) > [aria-haspopup="menu"]')).toBeNull();});it("keeps the archive open when it is empty", () => {@@ -828,18 +829,19 @@ describe("InboxPage", () => {expect(markReadMutate).toHaveBeenCalledWith("inbox-a", expect.anything());});- it("keeps an unread-filtered notification open after it is marked read", () => {+ it("keeps an unread-filtered archived notification open after it is marked read", () => {// Opening a row marks it read. With the unread filter on, that would drop// the row before its detail renders and clear the selection, so the click// looked like it only made the notification disappear.reset();layout.width = DESKTOP;- listData.active = [- item({ id: "inbox-a", issue_id: "issue-a", read: false }),+ searchParams = new URLSearchParams("view=archived");+ listData.archived = [+ item({ id: "inbox-a", issue_id: "issue-a", read: false, archived: true }),];useInboxFilterStore.getState().toggleUnreadOnly("workspace-1");markReadMutate.mockImplementation((id: string) => {- listData.active = listData.active.map((current) =>+ listData.archived = listData.archived.map((current) =>current.id === id ? { ...current, read: true } : current,);});@@ -848,35 +850,9 @@ describe("InboxPage", () => {fireEvent.click(screen.getByTestId("row"));rerender(<InboxPage />);+ expect(markReadMutate).toHaveBeenCalledWith("inbox-a", expect.anything());expect(screen.getByTestId("row")).toHaveTextContent("inbox-a");- expect(replace).not.toHaveBeenCalledWith("/acme/inbox");- });-- it("keeps an idle-filtered notification open after an agent starts on it", () => {- // Replying from the detail can start an agent on the open issue. With the- // idle filter on, that would drop the row the user is working in.- reset();- layout.width = DESKTOP;- listData.active = [- item({ id: "inbox-a", issue_id: "issue-a", read: true }),- item({ id: "inbox-b", issue_id: "issue-b", read: true }),- ];- useInboxFilterStore.getState().setAgent("workspace-1", "idle");-- const { rerender } = render(<InboxPage />);- fireEvent.click(screen.getAllByTestId("row")[0]!);- rerender(<InboxPage />);- listData.tasks = [- { id: "task-a", agent_id: "agent-1", issue_id: "issue-a", status: "queued" },- { id: "task-b", agent_id: "agent-1", issue_id: "issue-b", status: "running" },- ] as AgentTask[];- rerender(<InboxPage />);-- // The open row stays; another row that turned busy is still filtered.- expect(screen.getAllByTestId("row").map((row) => row.textContent)).toEqual([- "inbox-a",- ]);- expect(replace).not.toHaveBeenCalledWith("/acme/inbox");+ expect(replace).not.toHaveBeenCalledWith("/acme/inbox?view=archived");});it("keeps an explicitly unread row unread while it stays open", () => {@@ -1153,6 +1129,447 @@ describe("InboxPage", () => {});});+ // A run the viewer started themselves: the only kind "Working" lists.+ function ownRun(issueId: string, startedBy = "member-1"): AgentTask {+ return {+ id: `task-${issueId}`,+ agent_id: "agent-1",+ issue_id: issueId,+ status: "running",+ created_at: "2026-06-15T08:00:00Z",+ started_at: "2026-06-15T08:01:00Z",+ attribution: { source: "direct_human", precise: true, originator: { id: startedBy } },+ } as AgentTask;+ }++ const listed = () =>+ screen.getAllByTestId("row").map((row) => `${row.dataset.section}:${row.textContent}`);++ describe("sections", () => {+ it("files each issue under the section its notifications put it in", () => {+ reset();+ layout.width = DESKTOP;+ listData.active = [+ item({ id: "update", issue_id: "issue-u", section: "updates", read: false }),+ item({ id: "needs", issue_id: "issue-n", section: "needs_you" }),+ item({+ id: "snoozed",+ issue_id: "issue-s",+ section: "needs_you",+ snoozed_until: new Date(Date.now() + 3_600_000).toISOString(),+ }),+ ];++ render(<InboxPage />);++ expect(listed()).toEqual(["needs_you:needs", "updates:update", "snoozed:snoozed"]);+ });++ it("lists the issues the viewer handed to an agent, which have no notification", () => {+ reset();+ layout.width = DESKTOP;+ listData.tasks = [ownRun("issue-w"), ownRun("issue-other", "member-2")];++ render(<InboxPage />);++ expect(screen.getAllByTestId("working-row").map((row) => row.textContent)).toEqual(["issue-w"]);+ });++ it("narrows Working by the issue itself, once the issue has loaded", () => {+ reset();+ layout.width = DESKTOP;+ listData.active = [item({ id: "inbox-a", issue_id: "issue-a", issue_priority: "high" })];+ listData.tasks = [ownRun("issue-high"), ownRun("issue-low"), ownRun("issue-loading")];+ listData.issues = {+ "issue-high": { id: "issue-high", status: "in_progress", priority: "high", labels: [] },+ "issue-low": { id: "issue-low", status: "in_progress", priority: "low", labels: [] },+ };+ useInboxFilterStore.getState().togglePriorityFilter("workspace-1", "high");++ render(<InboxPage />);++ expect(listed()).toEqual(["needs_you:inbox-a"]);+ expect(screen.getAllByTestId("working-row").map((row) => row.textContent)).toEqual(["issue-high"]);+ });++ it("keeps narrowing Working once no notification is left", () => {+ reset();+ layout.width = DESKTOP;+ listData.tasks = [ownRun("issue-a"), ownRun("issue-b")];+ listData.issues = {+ "issue-a": { id: "issue-a", status: "in_progress", project_id: "project-a", labels: [] },+ "issue-b": { id: "issue-b", status: "in_progress", project_id: "project-b", labels: [] },+ };+ useInboxFilterStore.getState().toggleFilterValue("workspace-1", "project", "project-a");++ render(<InboxPage />);++ expect(screen.getAllByTestId("working-row").map((row) => row.textContent)).toEqual(["issue-a"]);+ });++ it("does not call a link to a Working issue broken while its issue loads under a filter", () => {+ reset();+ layout.width = DESKTOP;+ searchParams = new URLSearchParams("issue=issue-w");+ listData.tasks = [ownRun("issue-w")];+ useInboxFilterStore.getState().togglePriorityFilter("workspace-1", "high");++ const { rerender } = render(<InboxPage />);+ expect(replace).not.toHaveBeenCalled();++ listData.issues = { "issue-w": { id: "issue-w", status: "in_progress", priority: "high", labels: [] } };+ rerender(<InboxPage />);+ expect(issueDetailProps.at(-1)).toMatchObject({ issueId: "issue-w" });+ expect(replace).not.toHaveBeenCalled();+ });+ });++ describe("updates", () => {+ const update = (id: string, overrides: Partial<InboxItem> = {}) =>+ item({ id, issue_id: `issue-${id}`, section: "updates", read: false, ...overrides });++ it("lists the unread ones and sends the read ones to the archive", () => {+ reset();+ layout.width = DESKTOP;+ listData.active = [+ update("new"),+ update("seen", { read: true }),+ item({ id: "needs", issue_id: "issue-n", section: "needs_you", read: true }),+ ];++ const { rerender } = render(<InboxPage />);++ expect(listed()).toEqual(["needs_you:needs", "updates:new"]);+ expect(archiveUpdatesMutate).toHaveBeenCalledTimes(1);+ expect(archiveUpdatesMutate).toHaveBeenCalledWith({ groups: ["issue-seen"], readOnly: true });++ // The same set is asked for once, however often the page renders.+ rerender(<InboxPage />);+ expect(archiveUpdatesMutate).toHaveBeenCalledTimes(1);+ });++ it("keeps an update listed while it is open, and lets it go when the user moves on", () => {+ reset();+ layout.width = DESKTOP;+ listData.active = [update("a"), update("b")];+ markReadMutate.mockImplementation((id: string) => {+ listData.active = listData.active.map((current) =>+ current.id === id ? { ...current, read: true } : current,+ );+ });++ const { rerender } = render(<InboxPage />);+ fireEvent.click(screen.getByText("a"));+ rerender(<InboxPage />);++ expect(listed()).toEqual(["updates:a", "updates:b"]);+ expect(archiveUpdatesMutate).not.toHaveBeenCalled();++ fireEvent.click(screen.getByText("b"));+ rerender(<InboxPage />);++ expect(listed()).toEqual(["updates:b"]);+ expect(archiveUpdatesMutate).toHaveBeenCalledWith({ groups: ["issue-a"], readOnly: true });+ });++ it("leaves the archive alone while the archive is what is open", () => {+ reset();+ searchParams = new URLSearchParams("view=archived");+ listData.active = [update("seen", { read: true })];++ render(<InboxPage />);++ expect(archiveUpdatesMutate).not.toHaveBeenCalled();+ });++ it("clears the listed updates, read or not, and closes the one that was open", () => {+ reset();+ layout.width = DESKTOP;+ listData.active = [+ update("a"),+ update("b"),+ item({ id: "needs", issue_id: "issue-n", section: "needs_you" }),+ ];+ render(<InboxPage />);+ fireEvent.click(screen.getByText("a"));+ replace.mockClear();++ fireEvent.click(screen.getByTestId("clear-updates"));++ expect(archiveUpdatesMutate).toHaveBeenLastCalledWith(+ { groups: ["issue-a", "issue-b"], readOnly: false },+ expect.anything(),+ );+ expect(replace).toHaveBeenCalledWith("/acme/inbox");+ expect(archiveMutate).not.toHaveBeenCalled();+ });++ it("clears only what a filter shows", () => {+ reset();+ layout.width = DESKTOP;+ listData.active = [+ update("high", { issue_priority: "high" }),+ update("low", { issue_priority: "low" }),+ ];+ useInboxFilterStore.getState().togglePriorityFilter("workspace-1", "high");+ render(<InboxPage />);++ fireEvent.click(screen.getByTestId("clear-updates"));++ expect(archiveUpdatesMutate).toHaveBeenLastCalledWith(+ { groups: ["issue-high"], readOnly: false },+ expect.anything(),+ );+ });++ it("reports a failed clear", () => {+ reset();+ listData.active = [update("a")];+ render(<InboxPage />);+ fireEvent.click(screen.getByTestId("clear-updates"));++ const options = archiveUpdatesMutate.mock.calls.at(-1)?.[1] as { onError: (err: unknown) => void };+ act(() => options.onError(new Error("boom")));++ expect(toast.error).toHaveBeenCalledWith("boom");+ });+ });++ describe("an issue open without a notification", () => {+ it("opens a Working row in the detail pane, with nothing to snooze or archive", () => {+ reset();+ layout.width = DESKTOP;+ listData.tasks = [ownRun("issue-w")];++ render(<InboxPage />);+ fireEvent.click(screen.getByTestId("working-row"));++ expect(replace).toHaveBeenCalledWith("/acme/inbox?issue=issue-w");+ expect(issueDetailProps.at(-1)).toMatchObject({ issueId: "issue-w", readsInbox: false });+ expect(issueDetailProps.at(-1)?.onDone).toBeUndefined();+ expect(screen.queryByTestId("detail-actions")).toBeNull();+ expect(markReadMutate).not.toHaveBeenCalled();+ expect(replace).not.toHaveBeenCalledWith("/acme/issues/issue-w");+ });++ it("opens a link to a Working issue instead of leaving for its page", () => {+ reset();+ layout.width = DESKTOP;+ searchParams = new URLSearchParams("issue=issue-w");+ listData.tasks = [ownRun("issue-w")];++ render(<InboxPage />);++ expect(issueDetailProps.at(-1)).toMatchObject({ issueId: "issue-w" });+ expect(replace).not.toHaveBeenCalled();+ });++ it("waits for the runs to load before calling such a link broken", () => {+ reset();+ layout.width = DESKTOP;+ searchParams = new URLSearchParams("issue=issue-w");+ listData.tasksPending = true;++ const { rerender } = render(<InboxPage />);+ expect(replace).not.toHaveBeenCalled();++ listData.tasksPending = false;+ rerender(<InboxPage />);+ expect(replace).toHaveBeenCalledWith("/acme/issues/issue-w");+ });++ it("keeps the issue open when replying hands it to an agent and its notification goes", () => {+ reset();+ layout.width = DESKTOP;+ listData.active = [item({ id: "inbox-a", issue_id: "issue-a" })];++ const { rerender } = render(<InboxPage />);+ fireEvent.click(screen.getByTestId("row"));+ expect(screen.getByTestId("detail-actions")).toBeInTheDocument();+ replace.mockClear();+ issueDetailProps.length = 0;++ // The server archives the viewer's notifications as the run starts.+ listData.active = [];+ listData.tasks = [ownRun("issue-a")];+ rerender(<InboxPage />);++ expect(issueDetailProps.at(-1)).toMatchObject({ issueId: "issue-a" });+ expect(screen.queryByTestId("detail-actions")).toBeNull();+ expect(replace).not.toHaveBeenCalled();+ });++ it("keeps it open even when no run shows up for it", () => {+ reset();+ layout.width = DESKTOP;+ listData.active = [item({ id: "inbox-a", issue_id: "issue-a" })];++ const { rerender } = render(<InboxPage />);+ fireEvent.click(screen.getByTestId("row"));+ replace.mockClear();+ issueDetailProps.length = 0;+ listData.active = [];+ rerender(<InboxPage />);++ expect(issueDetailProps.at(-1)).toMatchObject({ issueId: "issue-a" });+ expect(replace).not.toHaveBeenCalled();+ });++ it("lets go once the selection moves on", () => {+ reset();+ layout.width = DESKTOP;+ listData.active = [+ item({ id: "inbox-a", issue_id: "issue-a" }),+ item({ id: "inbox-b", issue_id: "issue-b" }),+ ];++ const { rerender } = render(<InboxPage />);+ fireEvent.click(screen.getAllByTestId("row")[0]!);+ listData.active = [item({ id: "inbox-b", issue_id: "issue-b" })];+ rerender(<InboxPage />);+ fireEvent.click(screen.getByTestId("row"));+ expect(issueDetailProps.at(-1)).toMatchObject({ issueId: "issue-b" });+ replace.mockClear();++ // Back on the first issue by URL: it is a plain unknown link again.+ searchParams = new URLSearchParams("issue=issue-a");+ rerender(<InboxPage />);++ expect(replace).toHaveBeenCalledWith("/acme/issues/issue-a");+ });+ });++ describe("snooze", () => {+ type MutateOptions = { onSuccess?: () => void; onError?: (err: unknown) => void };+ const until = new Date("2026-06-18T01:00:00Z");++ function renderTwoWaiting() {+ reset();+ layout.width = DESKTOP;+ listData.active = [+ item({ id: "inbox-a", issue_id: "issue-a", section: "needs_you" }),+ item({ id: "inbox-b", issue_id: "issue-b", section: "needs_you" }),+ item({ id: "inbox-u", issue_id: "issue-u", section: "updates", read: false }),+ ];+ const view = render(<InboxPage />);+ fireEvent.click(screen.getAllByTestId("row")[0]!);+ replace.mockClear();+ return view;+ }++ it("snoozes from the row menu and moves on to the next issue that waits", () => {+ renderTwoWaiting();+ act(() => rowActions?.onSnooze("inbox-a", until));++ expect(snoozeMutate).toHaveBeenCalledWith(+ { id: "inbox-a", until: "2026-06-18T01:00:00.000Z" },+ expect.anything(),+ );+ expect(replace).toHaveBeenCalledWith("/acme/inbox?issue=issue-b");+ });++ it("stays in the section it finished rather than dropping into the updates below", () => {+ renderTwoWaiting();+ fireEvent.click(screen.getAllByTestId("row")[1]!);+ replace.mockClear();+ act(() => rowActions?.onAction("inbox-b"));++ expect(replace).toHaveBeenCalledWith("/acme/inbox?issue=issue-a");+ expect(replace).not.toHaveBeenCalledWith("/acme/inbox?issue=issue-u");+ });++ it("says when the issue comes back, since its row has left the screen", () => {+ renderTwoWaiting();+ act(() => rowActions?.onSnooze("inbox-a", until));+ act(() => (snoozeMutate.mock.calls.at(-1)?.[1] as MutateOptions).onSuccess?.());++ expect(toast.success).toHaveBeenCalledTimes(1);+ });++ it("reports a failed snooze as a failure only", () => {+ renderTwoWaiting();+ act(() => rowActions?.onSnooze("inbox-a", until));+ act(() => (snoozeMutate.mock.calls.at(-1)?.[1] as MutateOptions).onError?.(new Error("boom")));++ expect(toast.error).toHaveBeenCalledWith("boom");+ expect(toast.success).not.toHaveBeenCalled();+ });++ it("snoozes and archives the open notification from the detail header", () => {+ renderTwoWaiting();++ fireEvent.click(screen.getByTestId("detail-snooze"));+ expect(snoozeMutate).toHaveBeenCalledWith(+ { id: "inbox-a", until: SNOOZE_UNTIL.toISOString() },+ expect.anything(),+ );++ fireEvent.click(screen.getByTestId("detail-archive"));+ expect(archiveMutate).toHaveBeenCalledWith("inbox-b", expect.anything());+ });++ it("offers the way back on an issue that is snoozed, and takes it", () => {+ reset();+ layout.width = DESKTOP;+ listData.active = [+ item({+ id: "inbox-s",+ issue_id: "issue-s",+ section: "needs_you",+ snoozed_until: new Date(Date.now() + 3_600_000).toISOString(),+ }),+ ];++ render(<InboxPage />);+ fireEvent.click(screen.getByTestId("row"));+ expect(screen.getByTestId("detail-actions")).toHaveAttribute("data-snoozed", "true");++ fireEvent.click(screen.getByTestId("detail-unsnooze"));+ expect(unsnoozeMutate).toHaveBeenCalledWith("inbox-s", expect.anything());+ // Unsnoozing brings the issue back; it does not move the selection off it.+ expect(replace).not.toHaveBeenCalledWith("/acme/inbox");+ });++ it("opens the snooze menu for the open notification on its shortcut", () => {+ renderTwoWaiting();+ expect(screen.getByTestId("detail-actions")).toHaveAttribute("data-snooze-open", "false");++ fireEvent.keyDown(document, { key: "h" });++ expect(screen.getByTestId("detail-actions")).toHaveAttribute("data-snooze-open", "true");+ expect(snoozeMutate).not.toHaveBeenCalled();+ });++ it("closes the menu with the selection it was opened for", () => {+ renderTwoWaiting();+ fireEvent.keyDown(document, { key: "h" });++ fireEvent.click(screen.getAllByTestId("row")[1]!);++ expect(screen.getByTestId("detail-actions")).toHaveAttribute("data-snooze-open", "false");+ });++ it("has nothing to snooze in the archive or on a Working issue", () => {+ reset();+ layout.width = DESKTOP;+ searchParams = new URLSearchParams("view=archived");+ listData.archived = [item({ id: "archived-1", issue_id: "issue-9", archived: true })];+ const archive = render(<InboxPage />);+ fireEvent.click(screen.getByTestId("row"));+ fireEvent.keyDown(document, { key: "h" });+ expect(screen.queryByTestId("detail-actions")).toBeNull();+ archive.unmount();++ reset();+ layout.width = DESKTOP;+ listData.tasks = [ownRun("issue-w")];+ render(<InboxPage />);+ fireEvent.click(screen.getByTestId("working-row"));+ fireEvent.keyDown(document, { key: "h" });+ expect(screen.queryByTestId("detail-actions")).toBeNull();+ });+ });+it("does not swallow a deep link to an issue that is not in the archive", () => {// ?view=archived&issue=X with an empty archive: the drain effect and the// unresolved-selection fallback both want to navigate. The fallback mustdiff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex 20e4f735db..fbd2e90cc8 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -36,21 +36,19 @@ import {useMarkInboxUnread,useArchiveInbox,useUnarchiveInbox,- useMarkAllInboxRead,- useArchiveAllInbox,- useArchiveAllReadInbox,- useArchiveCompletedInbox,+ useSnoozeInbox,+ useUnsnoozeInbox,+ useArchiveInboxUpdates,useRetrySourceContextQuickCreate,} from "@multica/core/inbox/mutations";import {+ activeInboxFilterSupport,effectiveInboxFilters,filterInboxItems,inboxFilterCount,inboxIssueFieldsSupport,- inboxPriorityFilterSupport,useInboxFilters,useInboxFilterStore,- type InboxAgentFilter,type InboxFilterSupport,} from "@multica/core/inbox/filter-store";@@ -58,40 +56,32 @@ import { IssueDetail, issueHighlightMementoKey } from "../../issues/components/iimport { ActionShortcutKeycaps } from "../../common/shortcut-keycaps";import { useRegisterCommandBarContext } from "../../search/register-context";import { IssuePeekHost } from "../../issues/components/issue-peek";-import { useIssueSurfaceActivity } from "../../issues/surface/activity";import { useViewStateWriter } from "../../platform";import { ErrorBoundary } from "@multica/ui/components/common/error-boundary";import { useNavigation, useReportNavigating } from "../../navigation";import { toast } from "sonner";import {- MoreHorizontal,Inbox,- CheckCheck,Archive,ArchiveRestore,- BookCheck,ChevronDown,- ListChecks,+ Clock,ArrowLeft,} from "@multica/ui/icons";import type { InboxItem } from "@multica/core/types";import { Button } from "@multica/ui/components/ui/button";-import { IconButton } from "@multica/ui/components/common/icon-button";import {Tooltip,TooltipContent,TooltipTrigger,} from "@multica/ui/components/ui/tooltip";import { Skeleton } from "@multica/ui/components/ui/skeleton";-import { NumberFlow } from "@multica/ui/components/ui/number-flow";import {DropdownMenu,DropdownMenuTrigger,DropdownMenuContent,- DropdownMenuItem,DropdownMenuRadioGroup,DropdownMenuRadioItem,- DropdownMenuSeparator,} from "@multica/ui/components/ui/dropdown-menu";import { useIsCompact } from "@multica/ui/hooks/use-mobile";import { cn } from "@multica/ui/lib/utils";@@ -102,6 +92,11 @@ import { InboxDeleteDialog } from "./inbox-delete-dialog";import { ListColumn } from "../../layout/list-column";import { useTimeAgo } from "./inbox-list-item";import { InboxList } from "./inbox-list";+import { InboxSectionedList } from "./inbox-sectioned-list";+import { InboxDetailActions } from "./inbox-detail-actions";+import { InboxSnoozeMenu } from "./inbox-snooze-menu";+import { formatSnoozeTime } from "./inbox-snooze-time";+import { useInboxSections } from "./use-inbox-sections";import { InboxFilterMenu } from "./inbox-filter-menu";import { InboxFilterChipsBar } from "./inbox-filter-options";import { InboxContextMenuProvider } from "./inbox-context-menu";@@ -115,14 +110,16 @@ import {} from "./inbox-display";import { AutopilotQuotaNotice } from "./autopilot-quota-notice";import { InboxAppRequest } from "../../common/app-requests";-import { useT } from "../../i18n";+import { useLocale, useT } from "../../i18n";import { useIssueLimitUpgradePrompt } from "../../modals/use-issue-limit-upgrade-prompt";+const NO_ITEMS: InboxItem[] = [];+export function InboxPage() {const queryClient = useQueryClient();const { t } = useT("inbox");- const { t: tCommon } = useT("common");+ const locale = useLocale();const showIssueLimitUpgradePrompt = useIssueLimitUpgradePrompt();const showAutopilotQuotaRecoveryPrompt = useIssueLimitUpgradePrompt("autopilot_quota",@@ -139,12 +136,6 @@ export function InboxPage() {// so the filter would otherwise drop the row before the detail finishes// mounting. Scoped to the selection: moving away releases it.const pinnedUnreadKeyRef = useRef<string | null>(null);- // The row the user opened under the agent filter. Replying from the detail- // can start or finish an agent on its issue, which would otherwise drop the- // row the user is working in. Set once the open row has passed the agent- // filter, so turning the filter on over a non-matching row still filters- // it out; it only holds for the agent state it was pinned under.- const pinnedAgentRef = useRef<{ key: string; agent: InboxAgentFilter } | null>(null);// Sync from URL when searchParams change (e.g. navigation)useEffect(() => {@@ -190,37 +181,21 @@ export function InboxPage() {const viewItems = isArchivedView ? archivedItems : items;// The paginated endpoint guarantees the priority projection, including on// empty pages.- const priorityFilterSupport = isArchivedView ? "supported" : inboxPriorityFilterSupport(rawItems);- const issueFieldsSupport = isArchivedView ? archiveIssueFields : inboxIssueFieldsSupport(rawItems);+ const activeSupport = activeInboxFilterSupport(rawItems);+ const priorityFilterSupport = isArchivedView ? "supported" : activeSupport.priority;+ const issueFieldsSupport = isArchivedView ? archiveIssueFields : activeSupport.issueFields;const activeFilters = useMemo(() => effectiveInboxFilters(filters, { priority: priorityFilterSupport, issueFields: issueFieldsSupport }),[filters, priorityFilterSupport, issueFieldsSupport],);const effectiveFilters = isArchivedView ? archiveFilters : activeFilters;- // "Active" is the same running-or-queued rule the row's activity badge uses.- const { activityByIssueId } = useIssueSurfaceActivity();- const activeIssueIds = useMemo(() => new Set(activityByIssueId.keys()), [activityByIssueId]);- // Only an agent selection reads the snapshot, so task churn leaves the- // list alone while it is off.- const agentFilterIssueIds = effectiveFilters.agent ? activeIssueIds : undefined;- // The open row survives the unread and agent dimensions while it stays- // selected; see the pin refs above. Each pin is passed separately so it- // only crosses its own dimension.- const pinnedUnreadKey =+ // The open row survives the unread dimension while it stays selected; see+ // the pin ref above.+ const pinnedKey =effectiveFilters.unreadOnly && pinnedUnreadKeyRef.current === selectedKey? selectedKey: null;- const pinnedAgentKey =- effectiveFilters.agent &&- pinnedAgentRef.current?.key === selectedKey &&- pinnedAgentRef.current.agent === effectiveFilters.agent- ? selectedKey- : null;- const pinnedKey = pinnedUnreadKey ?? pinnedAgentKey;- const filterContext = useMemo(- () => ({ activeIssueIds: agentFilterIssueIds, pinnedUnreadKey, pinnedAgentKey }),- [agentFilterIssueIds, pinnedUnreadKey, pinnedAgentKey],- );+ const filterContext = useMemo(() => ({ pinnedUnreadKey: pinnedKey }), [pinnedKey]);const filterRows = isArchivedView ? archivedItems : activeRows;const filteredItems = useMemo(() => filterInboxItems(filterRows, effectiveFilters, filterContext),@@ -259,10 +234,25 @@ export function InboxPage() {}, [isArchivedView, selectedOnPage, filteredItems, lookupItems, effectiveFilters, filterContext]);const visibleItems = isArchivedView && pinnedKey ? selectionItems : filteredItems;- // Inbox zero: the bleeding m rises once, at the moment the last notification- // leaves; opening an already-empty inbox shows it at rest. Archived and- // filtered views are not inbox zero, so they never arm it.- const inboxZeroCount = isArchivedView || hasActiveFilters ? -1 : visibleItems.length;+ // The main list, by whose turn it is. Every active notification decides the+ // section; the filtered rows decide what is listed in it.+ const sections = useInboxSections(wsId, isArchivedView ? NO_ITEMS : visibleItems, activeRows, {+ filters: activeFilters,+ openKey: selectedKey,+ });+ const workingIssueIds = useMemo(+ () => new Set(sections.working.map((row) => row.issueId)),+ [sections.working],+ );+ const { workingPending } = sections;+ const hasRows = isArchivedView+ ? visibleItems.length > 0+ : sections.needsYou.length + sections.working.length + sections.updates.length + sections.snoozed.length > 0;++ // Inbox zero: the bleeding m rises once, at the moment the last issue that+ // needs the user leaves; opening an inbox with none shows it at rest.+ // Archived and filtered views are not inbox zero, so they never arm it.+ const inboxZeroCount = isArchivedView || hasActiveFilters ? -1 : sections.needsYou.length;const [prevInboxZeroCount, setPrevInboxZeroCount] = useState(inboxZeroCount);const [inboxZeroRises, setInboxZeroRises] = useState(false);if (inboxZeroCount !== prevInboxZeroCount) {@@ -275,6 +265,22 @@ export function InboxPage() {: null);const selectionFilteredOut = !!selectedKey && !!selectedInView && !selected;+ // An issue can be open without a notification of its own: a "Working" row+ // has none, and neither does the issue the user just handed to an agent+ // from here, whose notifications the server archives as the run starts.+ // `heldKey` keeps that second one open: it is the issue that was resolved+ // while it has stayed selected, so replying never closes the detail under+ // the reply. Moving the selection releases it.+ const [heldKey, setHeldKey] = useState<string | null>(null);+ const selectedIssueResolved =+ !isArchivedView && !!selectedKey && (selected?.issue_id === selectedKey || workingIssueIds.has(selectedKey));+ useEffect(() => {+ setHeldKey((held) => (selectedIssueResolved || held === selectedKey ? selectedKey : null));+ }, [selectedIssueResolved, selectedKey]);+ const isIssueOnlyKey = (key: string) =>+ !isArchivedView && !!key && (workingIssueIds.has(key) || heldKey === key);+ const selectedIssueOnly = !selected && !selectionFilteredOut && isIssueOnlyKey(selectedKey);+// What the DETAIL pane shows, one React transition behind the click.//// Mounting `IssueDetail` is the expensive half of switching rows, and driven@@ -287,6 +293,18 @@ export function InboxPage() {const detailKey = useDeferredValue(selectedKey);const detailSwapping = detailKey !== selectedKey;const detailItem = resolveDetailItem(selectionItems, selectedKey, detailKey);+ // The issue the pane shows: the open notification's, or an issue open+ // without one. The deferred key is held like a row is, and falls forward to+ // the live selection once it no longer resolves.+ const detailIssueId =+ detailItem?.issue_id ??+ (detailItem+ ? null+ : isIssueOnlyKey(detailKey)+ ? detailKey+ : selectedIssueOnly+ ? selectedKey+ : null);// The gap above is invisible to the navigation adapter — the inbox stays on// the same route and only rewrites `?issue=` — so report it explicitly and@@ -297,8 +315,10 @@ export function InboxPage() {// selection that disappears stays in Inbox; an unknown shared link still// falls back to the issue page.useEffect(() => {- if (selected) useInboxSelectionStore.getState().rememberResolvedKey(wsId, selectedKey);- }, [wsId, selected, selectedKey]);+ if (selected || selectedIssueOnly) {+ useInboxSelectionStore.getState().rememberResolvedKey(wsId, selectedKey);+ }+ }, [wsId, selected, selectedIssueOnly, selectedKey]);// Both the view and the selection live in the URL, so every write has to// carry the other one — a bare `?issue=` would silently drop the user out of@@ -353,8 +373,9 @@ export function InboxPage() {useEffect(() => {if (viewLoading || viewError || lookupLoading || lookupError) return;if (!selectedKey) return;- if (selected) return;+ if (selected || selectedIssueOnly) return;if (selectionFilteredOut) return;+ if (!isArchivedView && workingPending) return;if (useInboxSelectionStore.getState().lastResolvedKeyByWorkspace[wsId] === selectedKey) {setSelectedKey("");return;@@ -367,7 +388,10 @@ export function InboxPage() {lookupError,selectedKey,selected,+ selectedIssueOnly,selectionFilteredOut,+ isArchivedView,+ workingPending,replace,wsPaths,wsId,@@ -383,10 +407,9 @@ export function InboxPage() {const markUnreadMutation = useMarkInboxUnread();const archiveMutation = useArchiveInbox();const unarchiveMutation = useUnarchiveInbox();- const markAllReadMutation = useMarkAllInboxRead();- const archiveAllMutation = useArchiveAllInbox();- const archiveAllReadMutation = useArchiveAllReadInbox();- const archiveCompletedMutation = useArchiveCompletedInbox();+ const snoozeMutation = useSnoozeInbox();+ const unsnoozeMutation = useUnsnoozeInbox();+ const archiveUpdatesMutation = useArchiveInboxUpdates();const retrySourceContextMutation = useRetrySourceContextQuickCreate();const timeAgo = useTimeAgo();const typeLabels = useTypeLabels();@@ -407,6 +430,7 @@ export function InboxPage() {const markReadMutate = markReadMutation.mutate;const selectedId = selected?.id;const selectedRead = selected?.read;+ const unreadOnlyActive = effectiveFilters.unreadOnly;useEffect(() => {if (!selectedId) {openedItemIdRef.current = null;@@ -416,7 +440,7 @@ export function InboxPage() {openedItemIdRef.current = selectedId;if (!justOpened && selectedRead) return;if (manualUnreadIdRef.current === selectedId) return;- if (filters.unreadOnly) {+ if (unreadOnlyActive) {pinnedUnreadKeyRef.current = selectedKey;if (isArchivedView && selected) {// The unread page drops this group on refetch. Seed its lookup before@@ -434,7 +458,7 @@ export function InboxPage() {: t(($) => $.errors.mark_read_failed),),});- }, [selectedId, selectedRead, selectedKey, selected, filters.unreadOnly, isArchivedView, queryClient, wsId, lookupFilters, markReadMutate, t]);+ }, [selectedId, selectedRead, selectedKey, selected, unreadOnlyActive, isArchivedView, queryClient, wsId, lookupFilters, markReadMutate, t]);// Release the guards as soon as the selection moves off their row.useEffect(() => {@@ -444,31 +468,29 @@ export function InboxPage() {if (pinnedUnreadKeyRef.current && pinnedUnreadKeyRef.current !== selectedKey) {pinnedUnreadKeyRef.current = null;}- if (pinnedAgentRef.current && pinnedAgentRef.current.key !== selectedKey) {- pinnedAgentRef.current = null;- }}, [selectedId, selectedKey]);- // `selected` only exists once the open row passed every filter, so under- // the agent filter this pins a row that matched when the user opened it.- const agentFilter = effectiveFilters.agent;- const unreadOnlyActive = effectiveFilters.unreadOnly;- const hasSelected = selected != null;- useEffect(() => {- if (agentFilter && hasSelected && selectedKey) {- pinnedAgentRef.current = { key: selectedKey, agent: agentFilter };- }- }, [agentFilter, hasSelected, selectedKey]);-- // Turning a filter off releases its pin, so turning it back on judges the+ // Turning the filter off releases its pin, so turning it back on judges the// open row by its current state instead of an exemption from earlier.- useEffect(() => {- if (!agentFilter) pinnedAgentRef.current = null;- }, [agentFilter]);useEffect(() => {if (!unreadOnlyActive) pinnedUnreadKeyRef.current = null;}, [unreadOnlyActive]);+ // Reading an update is all there is to do with it, so the read ones move to+ // the archive: when the page opens, and as the user moves on from one they+ // had open. The server checks each issue again. One set is asked for once,+ // so a request that fails is not repeated until the set changes.+ const archiveUpdates = archiveUpdatesMutation.mutate;+ const readUpdates = sections.readUpdates;+ const sweptUpdatesRef = useRef("");+ useEffect(() => {+ if (isArchivedView || readUpdates.length === 0) return;+ const signature = [...readUpdates].sort().join(",");+ if (sweptUpdatesRef.current === signature) return;+ sweptUpdatesRef.current = signature;+ archiveUpdates({ groups: readUpdates, readOnly: true });+ }, [isArchivedView, readUpdates, archiveUpdates]);+const writeViewState = useViewStateWriter();// Bumped when the already-open notification row is re-clicked; threaded to// IssueDetail so it replays the comment-highlight landing without a@@ -492,6 +514,9 @@ export function InboxPage() {setSelectedKey(nextKey);};+ /** Open an issue that has no notification: a "Working" row. */+ const handleSelectIssue = (issueId: string) => setSelectedKey(issueId);+const handleMarkRead = (id: string) => {// Reading it back explicitly cancels an earlier park on the same row.if (manualUnreadIdRef.current === id) manualUnreadIdRef.current = null;@@ -520,18 +545,24 @@ export function InboxPage() {});};- // Both archive and unarchive remove the row from the list it was actioned- // from, so both have to move the selection off it first. `list` is whichever- // list the row came from — the main one for archive, the archived one for- // unarchive.+ // Archive, unarchive and snooze all remove the row from where it was+ // actioned, so each has to move the selection off it first. `list` is+ // whichever list the row came from: the archived one for unarchive, and in+ // the main view the row's own section, so finishing "Needs you" leaves the+ // selection there instead of dropping into the updates below it.const advanceSelectionPast = (id: string, list: InboxItem[]) => {+ if (!isArchivedView) {+ const sectionRows = [sections.needsYou, sections.updates, sections.snoozed].find((rows) =>+ rows.some((row) => row.item.id === id),+ );+ if (sectionRows) list = sectionRows.map((row) => row.item);+ }const idx = list.findIndex((i) => i.id === id);const target = idx >= 0 ? list[idx] : null;const wasSelected = !!target && (target.issue_id ?? target.id) === selectedKey;if (!wasSelected) return;- // List is sorted newest-first; prefer the next (older) item, fall back- // to the previous (newer) one when actioning at the bottom, and only- // clear the selection when nothing else is left.+ // Prefer the next row down, fall back to the one above when actioning at+ // the bottom, and only clear the selection when nothing else is left.const next = list[idx + 1] ?? list[idx - 1] ?? null;setSelectedKey(next ? (next.issue_id ?? next.id) : "");};@@ -563,12 +594,54 @@ export function InboxPage() {});};+ // Snoozing puts the whole issue away until a time, so like archive it moves+ // the selection on first. The toast names the time: the row has gone into a+ // folded section and nothing else on screen says when it returns.+ const handleSnooze = (id: string, until: Date) => {+ advanceSelectionPast(id, selectionItems);+ snoozeMutation.mutate(+ { id, until: until.toISOString() },+ {+ onSuccess: () =>+ toast.success(+ t(($) => $.toasts.snoozed, { time: formatSnoozeTime(until, new Date(), locale) }),+ ),+ onError: (err) =>+ toast.error(+ err instanceof Error && err.message+ ? err.message+ : t(($) => $.errors.snooze_failed),+ ),+ },+ );+ };++ const handleUnsnooze = (id: string) => {+ unsnoozeMutation.mutate(id, {+ onError: (err) =>+ toast.error(+ err instanceof Error && err.message+ ? err.message+ : t(($) => $.errors.unsnooze_failed),+ ),+ });+ };++ // The snooze menu hangs off the detail header's button; the shortcut opens+ // it for the row that is open. It belongs to that row, so it closes when the+ // selection moves.+ const [snoozeMenuKey, setSnoozeMenuKey] = useState<string | null>(null);+ const snoozeMenuOpen = !!selectedKey && snoozeMenuKey === selectedKey;+// Keep the listener stable while using the latest selected-item action.const actionOnSelectedRef = useRef<(() => void) | null>(null);+ const snoozeSelectedRef = useRef<(() => void) | null>(null);useEffect(() => {actionOnSelectedRef.current = selected? () => (isArchivedView ? handleUnarchive(selected.id) : handleArchive(selected.id)): null;+ snoozeSelectedRef.current =+ selected && !isArchivedView ? () => setSnoozeMenuKey(selectedKey) : null;});useEffect(() => {@@ -577,8 +650,11 @@ export function InboxPage() {if (isEditableShortcutTarget(event.target)) return;if (isPortalLayerShortcutTarget(event.target)) return;if (useModalStore.getState().modal) return;- if (!shortcutMatchesEvent(getShortcut("archiveInboxItem"), event)) return;- const run = actionOnSelectedRef.current;+ const run = shortcutMatchesEvent(getShortcut("archiveInboxItem"), event)+ ? actionOnSelectedRef.current+ : shortcutMatchesEvent(getShortcut("snoozeInboxItem"), event)+ ? snoozeSelectedRef.current+ : null;if (!run) return;event.preventDefault();run();@@ -587,58 +663,30 @@ export function InboxPage() {return () => document.removeEventListener("keydown", onKeyDown);}, []);- // Batch operations- const handleMarkAllRead = () => {- markAllReadMutation.mutate(undefined, {- onError: (err) =>- toast.error(- err instanceof Error && err.message- ? err.message- : t(($) => $.errors.mark_all_read_failed),- ),- });- };-- const handleArchiveAll = () => {- setSelectedKey("");- archiveAllMutation.mutate(undefined, {- onError: (err) =>- toast.error(- err instanceof Error && err.message- ? err.message- : t(($) => $.errors.archive_all_failed),- ),- });- };-- const handleArchiveAllRead = () => {- const readKeys = items.filter((i) => i.read).map((i) => i.issue_id ?? i.id);- if (readKeys.includes(selectedKey)) setSelectedKey("");- archiveAllReadMutation.mutate(undefined, {- onError: (err) =>- toast.error(- err instanceof Error && err.message- ? err.message- : t(($) => $.errors.archive_all_read_failed),- ),- });+ // "Clear" archives every update listed, read or not. Under a filter that is+ // the ones the filter shows.+ const handleClearUpdates = () => {+ const groups = sections.updates.map((row) => row.item.issue_id ?? row.item.id);+ if (groups.length === 0) return;+ if (groups.includes(selectedKey)) setSelectedKey("");+ archiveUpdatesMutation.mutate(+ { groups, readOnly: false },+ {+ onError: (err) =>+ toast.error(+ err instanceof Error && err.message+ ? err.message+ : t(($) => $.errors.archive_failed),+ ),+ },+ );};// The command bar calls the page's own handlers, so archiving from it moves// the selection and toasts exactly like the row actions do.- const commandBarHandlersRef = useRef({- handleArchive,- handleMarkUnread,- handleMarkAllRead,- handleArchiveAllRead,- });+ const commandBarHandlersRef = useRef({ handleArchive, handleMarkUnread });useEffect(() => {- commandBarHandlersRef.current = {- handleArchive,- handleMarkUnread,- handleMarkAllRead,- handleArchiveAllRead,- };+ commandBarHandlersRef.current = { handleArchive, handleMarkUnread };});const commandBarItem = isArchivedView ? null : selected;useRegisterCommandBarContext(@@ -648,25 +696,11 @@ export function InboxPage() {item: commandBarItem,archive: (id: string) => commandBarHandlersRef.current.handleArchive(id),markUnread: (id: string) => commandBarHandlersRef.current.handleMarkUnread(id),- markAllRead: () => commandBarHandlersRef.current.handleMarkAllRead(),- archiveAllRead: () => commandBarHandlersRef.current.handleArchiveAllRead(),}),[commandBarItem],),);- const handleArchiveCompleted = () => {- setSelectedKey("");- archiveCompletedMutation.mutate(undefined, {- onError: (err) =>- toast.error(- err instanceof Error && err.message- ? err.message- : t(($) => $.errors.archive_completed_failed),- ),- });- };-// -- Shared sub-components --------------------------------------------------const listHeader = (@@ -705,66 +739,26 @@ export function InboxPage() {</DropdownMenu>}leading={<CollapsedNavTrigger />}- meta={- !isArchivedView && unreadCount > 0 && (- <NumberFlow- value={unreadCount}- animated={false}- format={{ maximumFractionDigits: 0 }}- aria-label={String(unreadCount)}- className="text-caption text-muted-foreground"- />- )- }><InboxFilterMenuwsId={wsId}items={filterRows}priorityFilterSupport={priorityFilterSupport}issueFieldsSupport={issueFieldsSupport}- activeIssueIds={activeIssueIds}archived={isArchivedView}/>- {/* Batch actions are main-view only. Every entry archives from the MAIN- inbox, so offering them while the archived list is on screen reads as- "archive all of these" and does the opposite of what it looks like. */}- {!isArchivedView && (- <DropdownMenu>- <DropdownMenuTrigger- render={- <IconButton- label={tCommon(($) => $.more_actions)}- tooltipSide="bottom"- className="text-muted-foreground"- />- }- >- <MoreHorizontal className="h-4 w-4" />- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="w-auto">- <DropdownMenuItem onClick={handleMarkAllRead}>- <CheckCheck className="h-4 w-4" />- {t(($) => $.menu.mark_all_read)}- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem onClick={handleArchiveAll}>- <Archive className="h-4 w-4" />- {t(($) => $.menu.archive_all)}- </DropdownMenuItem>- <DropdownMenuItem onClick={handleArchiveAllRead}>- <BookCheck className="h-4 w-4" />- {t(($) => $.menu.archive_all_read)}- </DropdownMenuItem>- <DropdownMenuItem onClick={handleArchiveCompleted}>- <ListChecks className="h-4 w-4" />- {t(($) => $.menu.archive_completed)}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )}</PanelHeader>);+ const filterEmptyLabel =+ hasActiveFilters && !hasRows ? t(($) => $.filters.empty) : undefined;+ const filterEmptyAction =+ hasActiveFilters && !hasRows ? (+ <Button variant="outline" size="sm" onClick={() => clearFilters(wsId)}>+ {t(($) => $.filters.clear)}+ </Button>+ ) : undefined;+const list = isArchivedView && archivedError ? (<div className="flex-1 min-h-0 overflow-y-auto"><div className="flex flex-col items-center justify-center py-16 text-muted-foreground">@@ -783,39 +777,40 @@ export function InboxPage() {onMarkUnread: handleMarkUnread,onAction: isArchivedView ? handleUnarchive : handleArchive,onDelete: (id) => setDeleteTarget(selectionItems.find((item) => item.id === id) ?? null),+ onSnooze: handleSnooze,+ onUnsnooze: handleUnsnooze,}}>- <InboxList- items={visibleItems}- view={view}- selectedKey={selectedKey}- onLoadMore={isArchivedView && archiveQuery.hasNextPage ? loadNextArchivedPage : undefined}- loadingMore={archiveQuery.isFetchingNextPage}- loadMoreError={archiveQuery.isFetchNextPageError}- onSelect={handleSelect}- onAction={isArchivedView ? handleUnarchive : handleArchive}- emptyLabel={- hasActiveFilters && visibleItems.length === 0- ? t(($) => $.filters.empty)- : undefined- }- emptyAction={- hasActiveFilters && visibleItems.length === 0 ? (- <Button- variant="outline"- size="sm"- onClick={() => clearFilters(wsId)}- >- {t(($) => $.filters.clear)}- </Button>- ) : undefined- }- />+ {isArchivedView ? (+ <InboxList+ items={visibleItems}+ view={view}+ selectedKey={selectedKey}+ onLoadMore={archiveQuery.hasNextPage ? loadNextArchivedPage : undefined}+ loadingMore={archiveQuery.isFetchingNextPage}+ loadMoreError={archiveQuery.isFetchNextPageError}+ onSelect={handleSelect}+ onAction={handleUnarchive}+ emptyLabel={filterEmptyLabel}+ emptyAction={filterEmptyAction}+ />+ ) : (+ <InboxSectionedList+ sections={sections}+ selectedKey={selectedKey}+ filtered={hasActiveFilters}+ onSelect={handleSelect}+ onSelectIssue={handleSelectIssue}+ onAction={handleArchive}+ onClearUpdates={handleClearUpdates}+ emptyLabel={filterEmptyLabel}+ emptyAction={filterEmptyAction}+ />+ )}{deleteTarget && (<InboxDeleteDialogkey={deleteTarget.id}item={deleteTarget}- view={view}onClose={() => setDeleteTarget(null)}onDeleted={(id) => {advanceSelectionPast(id, selectionItems);@@ -876,13 +871,33 @@ export function InboxPage() {</div>) : null;- const detailContent = detailItem?.issue_id ? (+ // Snooze and archive act on the open notification, so an issue open without+ // one (a "Working" row) has neither, and the archive keeps its own actions.+ const detailSnoozed =+ !!detailItem &&+ sections.snoozed.some((row) => row.item.id === detailItem.id);+ const detailHostActions =+ detailItem && !isArchivedView ? (+ <InboxDetailActions+ compact={isCompact}+ snoozed={detailSnoozed}+ snoozeOpen={snoozeMenuOpen}+ onSnoozeOpenChange={(open) => setSnoozeMenuKey(open ? selectedKey : null)}+ onSnooze={(until) => handleSnooze(detailItem.id, until)}+ onUnsnooze={() => handleUnsnooze(detailItem.id)}+ onArchive={() => handleArchive(detailItem.id)}+ />+ ) : undefined;++ const detailContent = detailIssueId ? (// Key by issue_id (not inbox-item id): a new comment/reaction generates a// new inbox notification for the same issue, and the dedup helper picks the// newest one — keying on its id would remount IssueDetail on every event,- // wiping the comment composer draft and resetting scroll position.+ // wiping the comment composer draft and resetting scroll position. It is+ // also what keeps the detail mounted while the issue's notification comes+ // and goes under it.<ErrorBoundary- resetKeys={[detailItem.issue_id]}+ resetKeys={[detailIssueId]}// The default fallback is a bare message card. On a phone it would be the// only thing on screen, so it has to carry the way back too — the bar is// the point here, the message is whatever the boundary caught.@@ -896,16 +911,16 @@ export function InboxPage() {) : undefined}>{/* Shift+Click on an issue mention peeks it over the detail pane. */}- <IssuePeekHost key={detailItem.issue_id}>+ <IssuePeekHost key={detailIssueId}><IssueDetail- key={detailItem.issue_id}- issueId={detailItem.issue_id}+ key={detailIssueId}+ issueId={detailIssueId}defaultSidebarOpen={false}layoutId="multica_inbox_issue_detail_layout"- highlightCommentId={detailItem.details?.comment_id ?? undefined}+ highlightCommentId={detailItem?.details?.comment_id ?? undefined}highlightRequestToken={highlightRequestToken}highlightAppRequestId={- detailItem.type.startsWith("app_") ? (detailItem.details?.request_id ?? undefined) : undefined+ detailItem?.type.startsWith("app_") ? (detailItem.details?.request_id ?? undefined) : undefined}// The inbox reads the row it selected itself (see the auto-read// effect above), and must keep a row marked unread while it is open.@@ -921,9 +936,8 @@ export function InboxPage() {// longer exists.setSelectedKey("");}}- onDone={() => {- handleArchive(detailItem.id);- }}+ hostActions={detailHostActions}+ onDone={detailItem ? () => handleArchive(detailItem.id) : undefined}/></IssuePeekHost></ErrorBoundary>@@ -1015,6 +1029,22 @@ export function InboxPage() {{t(($) => $.detail.edit_advanced)}</Button>)}+ {!isArchivedView && (+ <InboxSnoozeMenu+ open={snoozeMenuOpen}+ onOpenChange={(open) => setSnoozeMenuKey(open ? selectedKey : null)}+ snoozed={detailSnoozed}+ onSnooze={(until) => handleSnooze(detailItem.id, until)}+ onUnsnooze={() => handleUnsnooze(detailItem.id)}+ trigger={+ <Button variant="outline" size="sm">+ <Clock className="mr-1.5 h-3.5 w-3.5" />+ {t(($) => $.snooze.action)}+ <ActionShortcutKeycaps action="snoozeInboxItem" />+ </Button>+ }+ />+ )}{/* Mirrors the row action: the button always reverses the view theitem is being read in. */}<Tooltip>@@ -1078,7 +1108,7 @@ export function InboxPage() {// of selection get their chrome from different places, so they render// differently — `InboxItem.issue_id` is nullable and a null one is a plain// notification (a failed quick-create, say), not an issue.- if (detailItem?.issue_id) {+ if (detailIssueId) {// No scroll container and no back bar of our own: `IssueDetail` owns// both, and takes the way back through `leadingAction`. Wrapping it in// an `overflow-y-auto` used to collapse its inner scroller to content@@ -1156,12 +1186,19 @@ export function InboxPage() {<Inbox className="mb-3 h-10 w-10 text-faint-foreground" />)}<p className="relative text-body">- {visibleItems.length > 0- ? t(($) => $.detail.select_prompt)- : isArchivedView- ? t(($) => $.list.archived_empty)- : t(($) => $.detail.empty)}+ {inboxZeroCount === 0+ ? t(($) => $.detail.nothing_needs_you)+ : hasRows+ ? t(($) => $.detail.select_prompt)+ : isArchivedView+ ? t(($) => $.list.archived_empty)+ : t(($) => $.filters.empty)}</p>+ {inboxZeroCount === 0 && (+ <p className="relative mt-1 max-w-xs text-center text-caption">+ {t(($) => $.detail.nothing_needs_you_hint)}+ </p>+ )}</div></>)}diff --git a/packages/views/inbox/components/inbox-reason-label.test.tsx b/packages/views/inbox/components/inbox-reason-label.test.tsxnew file mode 100644index 0000000000..e77f267b86--- /dev/null+++ b/packages/views/inbox/components/inbox-reason-label.test.tsx@@ -0,0 +1,172 @@+import { screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import type { InboxItem } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { InboxReasonLabel } from "./inbox-reason-label";++// The change label reads the status catalog and the workspace's people. This+// file only cares whether it is shown, and for which notification.+vi.mock("./inbox-detail-label", () => ({+ InboxDetailLabel: ({ item }: { item: InboxItem }) => <span data-testid="change">{item.id}</span>,+ useTypeLabels: () => ({ app_request: "App request" }),+}));++function item(overrides: Partial<InboxItem> = {}): InboxItem {+ return {+ id: "inbox-1",+ workspace_id: "workspace-1",+ recipient_type: "member",+ recipient_id: "member-1",+ actor_type: "agent",+ actor_id: "agent-1",+ type: "new_comment",+ severity: "info",+ issue_id: "issue-1",+ title: "Issue title",+ body: null,+ issue_status: null,+ read: false,+ archived: false,+ created_at: "2026-06-15T08:00:00Z",+ details: null,+ ...overrides,+ };+}++const reasonEl = (container: HTMLElement) => container.querySelector("[data-reason]") as HTMLElement;++describe("InboxReasonLabel", () => {+ it.each([+ [{ type: "agent_completed", issue_status: "in_review" }, "review", "Ready for review"],+ [{ type: "agent_completed", issue_status: "blocked" }, "question", "Waiting for your answer"],+ [{ type: "agent_blocked" }, "question", "Waiting for your answer"],+ [{ type: "mentioned" }, "mention", "Mentioned you"],+ [{ type: "task_failed" }, "failed", "Run failed"],+ [{ type: "task_cancelled" }, "cancelled", "Run cancelled"],+ [{ type: "issue_assigned" }, "assigned", "Assigned to you"],+ [{ type: "new_comment" }, "comment", "New comment"],+ [{ type: "agent_completed", issue_status: "in_progress" }, "finished", "Run finished"],+ ] as const)("names why %o waits", (overrides, kind, label) => {+ const reason = item(overrides as Partial<InboxItem>);+ const { container } = renderWithI18n(<InboxReasonLabel reason={reason} latest={reason} />);++ expect(reasonEl(container)).toHaveAttribute("data-reason", kind);+ expect(reasonEl(container)).toHaveTextContent(label);+ });++ it("colours only the two that ask for something to be answered or fixed", () => {+ const tone = (overrides: Partial<InboxItem>) => {+ const reason = item(overrides);+ const { container, unmount } = renderWithI18n(<InboxReasonLabel reason={reason} latest={reason} />);+ const className = reasonEl(container).className;+ unmount();+ return className;+ };++ expect(tone({ type: "agent_blocked" })).toContain("text-warning");+ expect(tone({ type: "task_failed" })).toContain("text-destructive");+ expect(tone({ type: "mentioned" })).toContain("text-foreground");+ expect(tone({ type: "agent_completed", issue_status: "in_review" })).toContain("text-foreground");+ });++ it("falls back to the notification's own label for a type it has no reason for", () => {+ const reason = item({ type: "app_request" as InboxItem["type"] });+ const { container } = renderWithI18n(<InboxReasonLabel reason={reason} latest={reason} />);++ expect(reasonEl(container)).toHaveTextContent("App request");+ });++ it("follows the reason with the latest thing said on the issue", () => {+ const reason = item({ type: "agent_blocked" });+ renderWithI18n(+ <InboxReasonLabel+ reason={reason}+ latest={reason}+ preview={item({ id: "inbox-said", body: " Which region should it deploy to? " })}+ />,+ );++ expect(screen.getByText("Which region should it deploy to?")).toBeInTheDocument();+ expect(screen.queryByTestId("change")).toBeNull();+ });++ it("shows a mention in what was said as its name, not its link", () => {+ const reason = item({ type: "mentioned" });+ renderWithI18n(+ <InboxReasonLabel+ reason={reason}+ latest={reason}+ preview={item({+ id: "inbox-said",+ type: "new_comment",+ body: "[@Ada](mention://member/user-1) can you decide on [MUL-12](mention://issue/issue-12)?",+ })}+ />,+ );++ expect(screen.getByText("@Ada can you decide on MUL-12?")).toBeInTheDocument();+ });++ it("does not repeat the issue title as what was said", () => {+ const reason = item({ type: "issue_assigned", body: "Issue title" });+ const { container } = renderWithI18n(+ <InboxReasonLabel reason={reason} latest={reason} preview={reason} />,+ );++ expect(container).toHaveTextContent(/^Assigned to you$/);+ });++ it("shows what changed last when nothing on the issue carries text", () => {+ const reason = item({ type: "mentioned" });+ renderWithI18n(+ <InboxReasonLabel reason={reason} latest={item({ id: "inbox-moved", type: "status_changed" })} />,+ );++ expect(screen.getByTestId("change")).toHaveTextContent("inbox-moved");+ });++ it.each([+ [{ cancelled_by_type: "member", cancelled_by_id: "member-1", cancelled_by_name: "Me" }, "You stopped this run"],+ [{ cancelled_by_type: "member", cancelled_by_id: "member-2", cancelled_by_name: "Ada" }, "Ada stopped this run"],+ [{ cancelled_by_type: "agent", cancelled_by_id: "agent-2", cancelled_by_name: "Lambda" }, "Lambda stopped this run"],+ [{ cancelled_by_type: "system" }, "Stopped by the system"],+ ])("says who stopped a cancelled run: %o", (details, text) => {+ const reason = item({ type: "task_cancelled", details: { task_id: "task-1", ...details } });+ renderWithI18n(<InboxReasonLabel reason={reason} latest={reason} />);++ expect(screen.getByText(text)).toBeInTheDocument();+ });++ it("shows a cancelled run alone when nothing says who stopped it", () => {+ const reason = item({ type: "task_cancelled", details: { task_id: "task-1" } });+ const { container } = renderWithI18n(<InboxReasonLabel reason={reason} latest={reason} />);++ expect(container).toHaveTextContent(/^Run cancelled$/);+ });++ it("keeps who stopped the run until something is said after it", () => {+ const reason = item({+ type: "task_cancelled",+ created_at: "2026-06-15T10:00:00Z",+ details: { cancelled_by_type: "member", cancelled_by_id: "member-1" },+ });+ const earlier = item({ id: "inbox-earlier", body: "Started on the migration", created_at: "2026-06-15T09:00:00Z" });+ const later = item({ id: "inbox-later", body: "Can you pick this back up?", created_at: "2026-06-15T11:00:00Z" });++ const { unmount } = renderWithI18n(<InboxReasonLabel reason={reason} latest={reason} preview={earlier} />);+ expect(screen.getByText("You stopped this run")).toBeInTheDocument();+ expect(screen.queryByText("Started on the migration")).toBeNull();+ unmount();++ renderWithI18n(<InboxReasonLabel reason={reason} latest={later} preview={later} />);+ expect(screen.getByText("Can you pick this back up?")).toBeInTheDocument();+ expect(screen.queryByText("You stopped this run")).toBeNull();+ });++ it("shows the reason alone when it is also the latest notification", () => {+ const reason = item({ type: "status_changed", issue_status: "in_review" });+ renderWithI18n(<InboxReasonLabel reason={reason} latest={reason} />);++ expect(screen.queryByTestId("change")).toBeNull();+ });+});diff --git a/packages/views/inbox/components/inbox-reason-label.tsx b/packages/views/inbox/components/inbox-reason-label.tsxnew file mode 100644index 0000000000..a408bfcf75--- /dev/null+++ b/packages/views/inbox/components/inbox-reason-label.tsx@@ -0,0 +1,134 @@+"use client";++import { inboxReasonKind, type InboxReasonKind } from "@multica/core/inbox/sections";+import type { InboxItem } from "@multica/core/types";+import {+ AtSign,+ CheckCheck,+ CircleCheck,+ CircleHelp,+ CircleSlash,+ MessageSquare,+ TriangleAlert,+ UserRound,+ type IconComponent,+} from "@multica/ui/icons";+import { cn } from "@multica/ui/lib/utils";+import { useT } from "../../i18n";+import { stripMentionMarkdown } from "../../issues/utils/strip-mention-markdown";+import { InboxDetailLabel, useTypeLabels } from "./inbox-detail-label";++const REASON_ICON: Record<InboxReasonKind, IconComponent> = {+ review: CheckCheck,+ question: CircleHelp,+ mention: AtSign,+ failed: TriangleAlert,+ cancelled: CircleSlash,+ assigned: UserRound,+ comment: MessageSquare,+ finished: CircleCheck,+};++// Only the two that ask for something to be fixed or answered take a colour;+// the rest stay the text colour so a full section does not read as an alarm.+const REASON_TONE: Partial<Record<InboxReasonKind, string>> = {+ question: "text-warning",+ failed: "text-destructive",+};++// Notifications whose own label says what changed, which is worth showing+// after the reason when no notification on the issue carries any text.+const CHANGE_TYPES: ReadonlySet<InboxItem["type"]> = new Set([+ "status_changed",+ "priority_changed",+ "assignee_changed",+ "unassigned",+ "start_date_changed",+ "due_date_changed",+ "reaction_added",+ "children_done",+]);++/**+ * Who stopped a cancelled run, in the words the row follows its reason with.+ * The notification goes to the member who started the run, so one they+ * cancelled names its own recipient. Anyone else is named as the server+ * recorded them with the cancellation. Null when it does not say.+ */+function useStoppedBy(reason: InboxItem): string | null {+ const { t } = useT("inbox");+ if (reason.type !== "task_cancelled") return null;+ const { cancelled_by_type: type, cancelled_by_id: id, cancelled_by_name: name } = reason.details ?? {};+ if (type === "member" && id === reason.recipient_id) return t(($) => $.reasons.stopped_by_you);+ if (type === "system") return t(($) => $.reasons.stopped_by_system);+ return name ? t(($) => $.reasons.stopped_by, { name }) : null;+}++/**+ * Second line of a "Needs you" row: why the issue waits on the user, then the+ * latest thing said on it. A cancelled run says who stopped it instead, until+ * something is said after it.+ *+ * `reason` is the notification that put the issue in the section; `latest` is+ * the row's newest notification and `preview` the newest that carries text.+ */+export function InboxReasonLabel({+ reason,+ latest,+ preview,+}: {+ reason: InboxItem;+ latest: InboxItem;+ preview?: InboxItem | null;+}) {+ const { t } = useT("inbox");+ const typeLabels = useTypeLabels();+ const kind = inboxReasonKind(reason);+ const Icon = kind ? REASON_ICON[kind] : null;+ const label = kind+ ? {+ review: t(($) => $.reasons.review),+ question: t(($) => $.reasons.question),+ mention: t(($) => $.reasons.mention),+ failed: t(($) => $.reasons.failed),+ cancelled: t(($) => $.reasons.cancelled),+ assigned: t(($) => $.reasons.assigned),+ comment: t(($) => $.reasons.comment),+ finished: t(($) => $.reasons.finished),+ }[kind]+ : (typeLabels[reason.type] ?? reason.type);+ // The body is the comment as written. A comment that mentions someone opens+ // with the mention's link, which would fill the line before any of its words.+ // An issue title repeated as the body adds nothing under the title.+ const text = preview?.body ? stripMentionMarkdown(preview.body).trim() : "";+ const stoppedBy = useStoppedBy(reason);+ const saidSince =+ !stoppedBy ||+ (preview != null && new Date(preview.created_at).getTime() > new Date(reason.created_at).getTime());+ const said = text && text !== latest.title.trim() && saidSince ? text : stoppedBy;++ return (+ <span className="flex min-w-0 items-center gap-1">+ <span+ data-reason={kind ?? reason.type}+ className={cn("inline-flex shrink-0 items-center gap-1", (kind && REASON_TONE[kind]) ?? "text-foreground")}+ >+ {Icon && <Icon className="h-3 w-3" />}+ {label}+ </span>+ {said ? (+ <>+ <span aria-hidden>·</span>+ <span className="min-w-0 truncate">{said}</span>+ </>+ ) : CHANGE_TYPES.has(latest.type) && latest.id !== reason.id ? (+ <>+ <span aria-hidden>·</span>+ <span className="min-w-0 truncate">+ <InboxDetailLabel item={latest} />+ </span>+ </>+ ) : null}+ </span>+ );+}diff --git a/packages/views/inbox/components/inbox-sectioned-list.test.tsx b/packages/views/inbox/components/inbox-sectioned-list.test.tsxnew file mode 100644index 0000000000..620a46c19c--- /dev/null+++ b/packages/views/inbox/components/inbox-sectioned-list.test.tsx@@ -0,0 +1,313 @@+import { forwardRef, useImperativeHandle } from "react";+import { fireEvent, screen, within } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useInboxSectionStore } from "@multica/core/inbox/section-store";+import type {+ InboxSectionRow,+ InboxSections,+ InboxWorkingRow,+} from "@multica/core/inbox/sections";+import type { InboxItem } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { InboxSectionedList } from "./inbox-sectioned-list";++// jsdom has no layout, so the real Virtuoso measures a 0-height viewport and+// renders nothing. The mock renders every entry inline and exposes the handle+// method the list drives, so the keyboard behaviour is observable.+const scrollIntoView = vi.hoisted(() => vi.fn());++vi.mock("react-virtuoso", () => ({+ Virtuoso: forwardRef(function MockVirtuoso(+ {+ data,+ itemContent,+ computeItemKey,+ }: {+ data: unknown[];+ itemContent: (index: number, entry: unknown) => React.ReactNode;+ computeItemKey: (index: number, entry: unknown) => string;+ },+ ref: React.Ref<unknown>,+ ) {+ useImperativeHandle(ref, () => ({ scrollIntoView }));+ return (+ <div>+ {data.map((entry, index) => (+ <div key={computeItemKey(index, entry)} data-entry={computeItemKey(index, entry)}>+ {itemContent(index, entry)}+ </div>+ ))}+ </div>+ );+ }),+}));++// The rows render avatars, hover cards and queries of their own, none of which+// this file is about. Each is a bare button carrying what the list hands it.+vi.mock("./inbox-list-item", () => ({+ InboxListItem: ({+ item,+ section,+ isSelected,+ onClick,+ }: {+ item: InboxItem;+ section: string;+ isSelected: boolean;+ onClick: () => void;+ }) => (+ <button type="button" data-row={section} data-selected={isSelected} onClick={onClick}>+ {item.id}+ </button>+ ),+}));+vi.mock("./inbox-working-item", () => ({+ InboxWorkingItem: ({+ row,+ isSelected,+ onClick,+ }: {+ row: InboxWorkingRow;+ isSelected: boolean;+ onClick: () => void;+ }) => (+ <button type="button" data-row="working" data-selected={isSelected} onClick={onClick}>+ {row.issueId}+ </button>+ ),+}));++function row(id: string, overrides: Partial<InboxItem> = {}): InboxSectionRow {+ const item: InboxItem = {+ id,+ workspace_id: "workspace-1",+ recipient_type: "member",+ recipient_id: "member-1",+ actor_type: "agent",+ actor_id: "agent-1",+ type: "new_comment",+ severity: "info",+ issue_id: `issue-${id}`,+ title: "Issue title",+ body: null,+ issue_status: null,+ read: true,+ archived: false,+ created_at: "2026-06-15T08:00:00Z",+ details: null,+ ...overrides,+ };+ return { item, reason: null, snoozedUntil: null, preview: null };+}++const working = (issueId: string, agentId = "agent-1"): InboxWorkingRow => ({+ issueId,+ taskId: `task-${issueId}`,+ agentId,+ queued: false,+ since: "2026-06-15T08:00:00Z",+});++const EMPTY: InboxSections = { needsYou: [], working: [], updates: [], snoozed: [], readUpdates: [] };++const FULL: InboxSections = {+ needsYou: [row("a"), row("b")],+ working: [working("issue-w")],+ updates: [row("u", { read: false })],+ snoozed: [row("s")],+ readUpdates: [],+};++function renderList(+ sections: InboxSections,+ props: Partial<React.ComponentProps<typeof InboxSectionedList>> = {},+) {+ const onSelect = vi.fn();+ const onSelectIssue = vi.fn();+ const utils = renderWithI18n(+ <InboxSectionedList+ sections={sections}+ selectedKey=""+ onSelect={onSelect}+ onSelectIssue={onSelectIssue}+ onAction={vi.fn()}+ {...props}+ />,+ );+ const scroller = utils.container.querySelector(".overflow-y-auto") as HTMLElement;+ return { ...utils, scroller, onSelect, onSelectIssue };+}++const header = (section: string) =>+ document.querySelector(`[data-section-header="${section}"]`) as HTMLElement | null;+const rows = () =>+ Array.from(document.querySelectorAll("[data-row]")).map(+ (el) => `${el.getAttribute("data-row")}:${el.textContent}`,+ );++beforeEach(() => {+ scrollIntoView.mockClear();+ useInboxSectionStore.setState({ open: { updates: false, snoozed: false } });+});++describe("InboxSectionedList sections", () => {+ it("lists what needs the user, then what agents are working on, and folds the rest", () => {+ renderList(FULL);++ expect(+ Array.from(document.querySelectorAll("[data-section-header]")).map((el) =>+ el.getAttribute("data-section-header"),+ ),+ ).toEqual(["needs_you", "working", "updates", "snoozed"]);+ expect(rows()).toEqual(["needs_you:a", "needs_you:b", "working:issue-w"]);+ expect(header("needs_you")).toHaveTextContent(/^Needs you2$/);+ expect(header("working")).toHaveTextContent(/^Working1$/);+ expect(header("updates")).toHaveTextContent(/^Updates1$/);+ expect(header("snoozed")).toHaveTextContent(/^Snoozed1$/);+ });++ it("clears the updates from the header once they are in view", () => {+ const onClearUpdates = vi.fn();+ renderList(FULL, { onClearUpdates });+ // Folded, nothing is listed to clear.+ expect(screen.queryByRole("button", { name: "Clear" })).toBeNull();++ fireEvent.click(within(header("updates")!).getByRole("button", { name: /Updates/ }));+ fireEvent.click(within(header("updates")!).getByRole("button", { name: "Clear" }));++ expect(onClearUpdates).toHaveBeenCalledOnce();+ // Clearing is not folding.+ expect(useInboxSectionStore.getState().open.updates).toBe(true);+ expect(within(header("snoozed")!).queryByRole("button", { name: "Clear" })).toBeNull();+ });++ it("offers no Clear where the list is only a preview", () => {+ useInboxSectionStore.setState({ open: { updates: true, snoozed: false } });+ renderList(FULL);++ expect(screen.queryByRole("button", { name: "Clear" })).toBeNull();+ });++ it("opens a folded section from its header and remembers it", () => {+ renderList(FULL);+ const toggle = within(header("updates")!).getByRole("button");+ expect(toggle).toHaveAttribute("aria-expanded", "false");++ fireEvent.click(toggle);++ expect(rows()).toEqual(["needs_you:a", "needs_you:b", "working:issue-w", "updates:u"]);+ expect(within(header("updates")!).getByRole("button")).toHaveAttribute("aria-expanded", "true");+ expect(useInboxSectionStore.getState().open).toEqual({ updates: true, snoozed: false });+ });++ it("never folds what needs the user or what is being worked on", () => {+ renderList(FULL);++ expect(within(header("needs_you")!).queryByRole("button")).toBeNull();+ expect(within(header("working")!).queryByRole("button")).toBeNull();+ });++ it("leaves out a section with nothing in it, except the one that leads", () => {+ renderList({ ...EMPTY, updates: [row("u")] });++ expect(header("needs_you")).not.toBeNull();+ expect(header("working")).toBeNull();+ expect(header("snoozed")).toBeNull();+ });+});++describe("InboxSectionedList with nothing waiting", () => {+ it("says so, and counts the agents still at work", () => {+ renderList({+ ...EMPTY,+ working: [working("issue-1", "agent-1"), working("issue-2", "agent-1"), working("issue-3", "agent-2")],+ });++ expect(screen.getByText("All caught up")).toBeInTheDocument();+ expect(+ screen.getByText("2 agents are still working. Results come back here."),+ ).toBeInTheDocument();+ // The section has nothing to count.+ expect(header("needs_you")).toHaveTextContent(/^Needs you$/);+ });++ it("says nothing about agents when none is working", () => {+ renderList(EMPTY);++ expect(screen.getByText("All caught up")).toBeInTheDocument();+ expect(screen.queryByText(/still working/)).toBeNull();+ });+});++describe("InboxSectionedList under a filter", () => {+ it("lists the matches: folded sections open, empty ones gone", () => {+ renderList({ ...EMPTY, updates: [row("u")], snoozed: [row("s")] }, { filtered: true });++ expect(header("needs_you")).toBeNull();+ expect(screen.queryByText("All caught up")).toBeNull();+ expect(rows()).toEqual(["updates:u", "snoozed:s"]);+ // Nothing to fold while the list is the answer to a filter.+ expect(within(header("updates")!).queryByRole("button")).toBeNull();+ });++ it("shows the empty label and its action when nothing matches", () => {+ renderList(EMPTY, {+ filtered: true,+ emptyLabel: "No notifications match these filters",+ emptyAction: <button type="button">Clear filters</button>,+ });++ expect(screen.getByText("No notifications match these filters")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Clear filters" })).toBeInTheDocument();+ });+});++describe("InboxSectionedList selection", () => {+ it("selects a notification by its issue and a working row by its own", () => {+ const { onSelect, onSelectIssue } = renderList(FULL, { selectedKey: "issue-w" });++ expect(screen.getByText("issue-w")).toHaveAttribute("data-selected", "true");+ expect(screen.getByText("a")).toHaveAttribute("data-selected", "false");++ fireEvent.click(screen.getByText("b"));+ expect(onSelect).toHaveBeenCalledWith(FULL.needsYou[1]!.item);+ fireEvent.click(screen.getByText("issue-w"));+ expect(onSelectIssue).toHaveBeenCalledWith("issue-w");+ });++ it("walks the arrow keys across sections, past their headers", () => {+ const { scroller, onSelectIssue } = renderList(FULL, { selectedKey: "issue-b" });++ const claimed = !fireEvent.keyDown(scroller, { key: "ArrowDown" });++ expect(claimed).toBe(true);+ expect(onSelectIssue).toHaveBeenCalledWith("issue-w");+ // Entries: header, a, b, header, the working row.+ expect(scrollIntoView).toHaveBeenCalledWith({ index: 4 });+ });++ it("stops at the last row that is showing, not inside a folded section", () => {+ const { scroller, onSelect, onSelectIssue } = renderList(FULL, { selectedKey: "issue-w" });++ fireEvent.keyDown(scroller, { key: "ArrowDown" });++ expect(onSelect).not.toHaveBeenCalled();+ expect(onSelectIssue).not.toHaveBeenCalled();+ });++ it("reaches an opened section's rows", () => {+ useInboxSectionStore.setState({ open: { updates: true, snoozed: false } });+ const { scroller, onSelect } = renderList(FULL, { selectedKey: "issue-w" });++ fireEvent.keyDown(scroller, { key: "ArrowDown" });++ expect(onSelect).toHaveBeenCalledWith(FULL.updates[0]!.item);+ });++ it("leaves modified arrows and arrows typed into a field alone", () => {+ const { scroller, onSelect } = renderList(FULL, { selectedKey: "issue-a" });++ expect(fireEvent.keyDown(scroller, { key: "ArrowDown", metaKey: true })).toBe(true);+ expect(onSelect).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/inbox/components/inbox-sectioned-list.tsx b/packages/views/inbox/components/inbox-sectioned-list.tsxnew file mode 100644index 0000000000..14a0f73f8c--- /dev/null+++ b/packages/views/inbox/components/inbox-sectioned-list.tsx@@ -0,0 +1,335 @@+"use client";++import {+ useCallback,+ useMemo,+ useRef,+ useState,+ type KeyboardEvent,+ type ReactNode,+} from "react";+import { Virtuoso, type VirtuosoHandle } from "react-virtuoso";+import {+ useInboxSectionStore,+ type InboxFoldingSection,+} from "@multica/core/inbox/section-store";+import type {+ InboxSectionRow,+ InboxSections,+ InboxWorkingRow,+} from "@multica/core/inbox/sections";+import { isEditableShortcutTarget } from "@multica/core/shortcuts";+import type { InboxItem } from "@multica/core/types";+import { isImeComposing } from "@multica/core/utils";+import { CheckCheck, ChevronRight } from "@multica/ui/icons";+import { cn } from "@multica/ui/lib/utils";+import { VirtuosoSeed, VIRTUOSO_SEED_COUNT } from "../../common/virtuoso-seed";+import { useT } from "../../i18n";+import { useRestoredScrollOffset, useRestoredScrollRef } from "../../platform";+import { InboxListItem, type InboxRowSection } from "./inbox-list-item";+import { InboxWorkingItem } from "./inbox-working-item";++// Sizing only, shared by the seed's spacer and Virtuoso's default: a+// "Needs you" row is two text lines plus py-2.5; the other rows are shorter+// and get measured once mounted.+const INBOX_ROW_ESTIMATED_HEIGHT = 58;++type SectionKey = "needs_you" | "working" | InboxFoldingSection;++type Entry =+ | { kind: "header"; section: SectionKey; count: number | null; folding: boolean; open: boolean }+ | { kind: "item"; section: InboxRowSection; row: InboxSectionRow }+ | { kind: "working"; row: InboxWorkingRow }+ | { kind: "caught-up"; agents: number };++/** The key the page selects a row by. */+function entryKey(entry: Entry): string | null {+ if (entry.kind === "item") return entry.row.item.issue_id ?? entry.row.item.id;+ if (entry.kind === "working") return entry.row.issueId;+ return null;+}++/**+ * The main Inbox list: one column, sectioned by whose turn it is.+ *+ * "Needs you" leads and is always there, so an empty one says so instead of+ * leaving the column to look broken. "Working" follows, then "Updates" and+ * "Snoozed", which start folded: nothing in them is waiting.+ *+ * "Updates" holds what has not been read yet. Opening one reads it and it+ * leaves for the archive; "Clear" sends the rest there unread.+ *+ * The sections are one virtualized list rather than four, so the column has a+ * single scroller and the arrow keys walk straight through. Under a filter+ * the list is the matches: folded sections open and empty ones are left out.+ */+export function InboxSectionedList({+ sections,+ selectedKey,+ filtered = false,+ onSelect,+ onSelectIssue,+ onAction,+ onClearUpdates,+ emptyLabel,+ emptyAction,+ scrollRestoration = true,+}: {+ sections: InboxSections;+ selectedKey: string;+ /** A filter is on: show matches only, and never the caught-up state. */+ filtered?: boolean;+ onSelect: (item: InboxItem) => void;+ /** Open an issue that has no notification: a "Working" row. */+ onSelectIssue: (issueId: string) => void;+ onAction: (id: string) => void;+ /** Archive every update listed. Absent where the list is only a preview. */+ onClearUpdates?: () => void;+ emptyLabel?: string;+ emptyAction?: ReactNode;+ /**+ * Off for a preview rendered over another route, which must neither read+ * nor be captured as that route's `list` scroll offset.+ */+ scrollRestoration?: boolean;+}) {+ const { t } = useT("inbox");+ const stored = useInboxSectionStore((s) => s.open);+ const toggle = useInboxSectionStore((s) => s.toggle);+ const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null);+ const savedScrollTop = useRestoredScrollOffset("list");+ const restoreScrollRef = useRestoredScrollRef("list");+ const restoredScrollTop = scrollRestoration ? savedScrollTop : undefined;+ const attachScrollEl = useCallback(+ (el: HTMLDivElement | null) => {+ setScrollEl(el);+ if (scrollRestoration) restoreScrollRef(el);+ },+ [restoreScrollRef, scrollRestoration],+ );+ const virtuosoRef = useRef<VirtuosoHandle>(null);++ const entries = useMemo(() => {+ const out: Entry[] = [];+ const { needsYou, working, updates, snoozed } = sections;+ const header = (section: SectionKey, count: number | null, open = true) =>+ out.push({ kind: "header", section, count, folding: !filtered && section !== "needs_you" && section !== "working", open });++ if (needsYou.length > 0 || !filtered) {+ header("needs_you", needsYou.length > 0 ? needsYou.length : null);+ for (const row of needsYou) out.push({ kind: "item", section: "needs_you", row });+ if (needsYou.length === 0) {+ out.push({ kind: "caught-up", agents: new Set(working.map((row) => row.agentId)).size });+ }+ }+ if (working.length > 0) {+ header("working", working.length);+ for (const row of working) out.push({ kind: "working", row });+ }+ if (updates.length > 0) {+ const open = filtered || stored.updates;+ header("updates", updates.length, open);+ if (open) for (const row of updates) out.push({ kind: "item", section: "updates", row });+ }+ if (snoozed.length > 0) {+ const open = filtered || stored.snoozed;+ header("snoozed", snoozed.length, open);+ if (open) for (const row of snoozed) out.push({ kind: "item", section: "snoozed", row });+ }+ return out;+ }, [sections, filtered, stored]);++ // Keyboard focus lives on the scroll container, not on a row: a virtualized+ // row unmounts as it scrolls out and would take the focus with it.+ const focusList = useCallback(() => {+ scrollEl?.focus({ preventScroll: true });+ }, [scrollEl]);++ const selectEntry = useCallback(+ (entry: Entry) => {+ focusList();+ if (entry.kind === "item") onSelect(entry.row.item);+ else if (entry.kind === "working") onSelectIssue(entry.row.issueId);+ },+ [focusList, onSelect, onSelectIssue],+ );++ // Arrow keys move the selection through every section's rows, skipping the+ // headers. Bound to the container so they only act while focus is in the+ // list, and never swap the row out from under someone reading the detail.+ const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;+ if (event.defaultPrevented || isImeComposing(event)) return;+ if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;+ if (isEditableShortcutTarget(event.target)) return;++ event.preventDefault();+ focusList();++ const rows: number[] = [];+ entries.forEach((entry, index) => {+ if (entryKey(entry) != null) rows.push(index);+ });+ if (rows.length === 0) return;+ const current = rows.findIndex((index) => entryKey(entries[index]!) === selectedKey);+ const step = event.key === "ArrowDown" ? 1 : -1;+ const next =+ current < 0+ ? step === 1+ ? 0+ : rows.length - 1+ : Math.min(Math.max(current + step, 0), rows.length - 1);+ if (next === current) return;+ const index = rows[next]!;+ virtuosoRef.current?.scrollIntoView({ index });+ selectEntry(entries[index]!);+ };++ const sectionLabel: Record<SectionKey, string> = {+ needs_you: t(($) => $.sections.needs_you),+ working: t(($) => $.sections.working),+ updates: t(($) => $.sections.updates),+ snoozed: t(($) => $.sections.snoozed),+ };++ if (entries.length === 0) {+ return (+ <div className="flex-1 min-h-0 overflow-y-auto">+ <div className="px-5 pt-2.5 pb-1.5 text-caption text-muted-foreground">+ <p>{emptyLabel ?? t(($) => $.list.empty)}</p>+ {emptyAction && <div className="mt-3">{emptyAction}</div>}+ </div>+ </div>+ );+ }++ const computeItemKey = (_index: number, entry: Entry) =>+ entry.kind === "header"+ ? `header:${entry.section}`+ : entry.kind === "caught-up"+ ? "caught-up"+ : `${entry.kind}:${entryKey(entry)}`;++ const itemContent = (index: number, entry: Entry) => {+ if (entry.kind === "header") {+ const label = (+ <>+ <span className="text-foreground">{sectionLabel[entry.section]}</span>+ {entry.count != null && <span className="tabular-nums">{entry.count}</span>}+ </>+ );+ const className =+ "flex min-w-0 flex-1 items-center gap-1.5 py-1 text-caption font-medium text-muted-foreground";+ // A button cannot hold another, so "Clear" sits beside the fold toggle+ // rather than inside it.+ const clear = entry.section === "updates" && entry.open && onClearUpdates && (+ <button+ type="button"+ onClick={onClearUpdates}+ className="shrink-0 rounded-md px-1.5 py-0.5 text-caption text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring"+ >+ {t(($) => $.sections.clear_updates)}+ </button>+ );+ return (+ <div+ role="heading"+ aria-level={2}+ data-section-header={entry.section}+ className={cn("flex items-center gap-1 px-2", index === 0 ? "pt-0.5" : "pt-2")}+ >+ {entry.folding ? (+ <>+ <button+ type="button"+ aria-expanded={entry.open}+ onClick={() => toggle(entry.section as InboxFoldingSection)}+ className={cn(className, "rounded-md text-left outline-none focus-visible:ring-1 focus-visible:ring-ring")}+ >+ {label}+ </button>+ {clear}+ <ChevronRight+ aria-hidden+ onClick={() => toggle(entry.section as InboxFoldingSection)}+ className={cn("h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform", entry.open && "rotate-90")}+ />+ </>+ ) : (+ <>+ <div className={className}>{label}</div>+ {clear}+ </>+ )}+ </div>+ );+ }+ if (entry.kind === "caught-up") {+ return (+ <div className="flex flex-col items-center px-4 pt-5 pb-4 text-center">+ <CheckCheck className="h-4 w-4 text-muted-foreground" />+ <p className="mt-2 text-body font-medium">{t(($) => $.sections.caught_up)}</p>+ {entry.agents > 0 && (+ <p className="mt-1 text-caption text-muted-foreground">+ {t(($) => $.sections.still_working, { count: entry.agents })}+ </p>+ )}+ </div>+ );+ }+ if (entry.kind === "working") {+ return (+ <InboxWorkingItem+ row={entry.row}+ isSelected={entry.row.issueId === selectedKey}+ onClick={() => selectEntry(entry)}+ />+ );+ }+ const { item } = entry.row;+ return (+ <InboxListItem+ item={item}+ view="inbox"+ section={entry.section}+ row={entry.row}+ isSelected={(item.issue_id ?? item.id) === selectedKey}+ onClick={() => selectEntry(entry)}+ onAction={() => onAction(item.id)}+ />+ );+ };++ return (+ <div+ ref={attachScrollEl}+ data-tab-scroll-root={scrollRestoration ? "list" : undefined}+ tabIndex={-1}+ onKeyDown={handleKeyDown}+ className="flex-1 min-h-0 overflow-y-auto outline-none"+ >+ <div className="px-2 py-1">+ {scrollEl ? (+ <Virtuoso+ ref={virtuosoRef}+ customScrollParent={scrollEl}+ data={entries}+ computeItemKey={computeItemKey}+ initialScrollTop={restoredScrollTop}+ initialItemCount={Math.min(entries.length, VIRTUOSO_SEED_COUNT)}+ defaultItemHeight={INBOX_ROW_ESTIMATED_HEIGHT}+ increaseViewportBy={{ top: 400, bottom: 400 }}+ itemContent={itemContent}+ />+ ) : (+ <VirtuosoSeed+ data={entries}+ itemContent={itemContent}+ computeItemKey={computeItemKey}+ estimatedItemHeight={INBOX_ROW_ESTIMATED_HEIGHT}+ />+ )}+ </div>+ </div>+ );+}diff --git a/packages/views/inbox/components/inbox-snooze-menu.test.tsx b/packages/views/inbox/components/inbox-snooze-menu.test.tsxnew file mode 100644index 0000000000..f377d35e52--- /dev/null+++ b/packages/views/inbox/components/inbox-snooze-menu.test.tsx@@ -0,0 +1,140 @@+import { useState } from "react";+import { fireEvent, screen, within } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { renderWithI18n } from "../../test/i18n";+import { InboxSnoozeMenu } from "./inbox-snooze-menu";+import { formatSnoozeTime } from "./inbox-snooze-time";++const at = (y: number, m: number, d: number, h: number, min = 0) => new Date(y, m - 1, d, h, min);+// A Wednesday afternoon, with the evening still more than an hour away.+const NOW = at(2026, 6, 17, 14, 20);+// The times are written the way the locale writes them, which is the+// formatter's business and has its own tests.+const time = (until: Date, now = NOW) => formatSnoozeTime(until, now, "en");++function Harness({+ onSnooze,+ onUnsnooze,+ snoozed,+ initialOpen = true,+}: {+ onSnooze: (until: Date) => void;+ onUnsnooze?: () => void;+ snoozed?: boolean;+ initialOpen?: boolean;+}) {+ const [open, setOpen] = useState(initialOpen);+ return (+ <InboxSnoozeMenu+ open={open}+ onOpenChange={setOpen}+ snoozed={snoozed}+ onSnooze={onSnooze}+ onUnsnooze={onUnsnooze}+ trigger={<button type="button">Snooze</button>}+ />+ );+}++beforeEach(() => {+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(NOW);+});+afterEach(() => {+ vi.useRealTimers();+});++describe("InboxSnoozeMenu", () => {+ it("offers a few times worth one click, each with the time it means", async () => {+ renderWithI18n(<Harness onSnooze={vi.fn()} />);++ const items = await screen.findAllByRole("menuitem");+ expect(items.map((item) => item.textContent)).toEqual([+ `In 1 hour${time(at(2026, 6, 17, 15, 20))}`,+ `Later today${time(at(2026, 6, 17, 18))}`,+ `Tomorrow${time(at(2026, 6, 18, 9))}`,+ `Next Monday${time(at(2026, 6, 22, 9))}`,+ "Pick a time...",+ ]);+ expect(+ screen.getByText("Comes back early if something new needs you, such as a mention or a failed run."),+ ).toBeInTheDocument();+ });++ it("snoozes until the time picked", async () => {+ const onSnooze = vi.fn();+ renderWithI18n(<Harness onSnooze={onSnooze} />);++ fireEvent.click(await screen.findByRole("menuitem", { name: /^Later today/ }));++ expect(onSnooze).toHaveBeenCalledWith(at(2026, 6, 17, 18));+ });++ it("offers the way back only for an issue that is already snoozed", async () => {+ const onUnsnooze = vi.fn();+ const { unmount } = renderWithI18n(<Harness onSnooze={vi.fn()} onUnsnooze={onUnsnooze} />);+ await screen.findByRole("menuitem", { name: /^In 1 hour/ });+ expect(screen.queryByRole("menuitem", { name: "Unsnooze" })).toBeNull();+ unmount();++ renderWithI18n(<Harness onSnooze={vi.fn()} onUnsnooze={onUnsnooze} snoozed />);+ fireEvent.click(await screen.findByRole("menuitem", { name: "Unsnooze" }));++ expect(onUnsnooze).toHaveBeenCalledTimes(1);+ });++ it("reads the clock again each time it opens", async () => {+ renderWithI18n(<Harness onSnooze={vi.fn()} initialOpen={false} />);+ const later = at(2026, 6, 17, 15, 0);+ vi.setSystemTime(later);++ fireEvent.click(screen.getByRole("button", { name: "Snooze" }));++ expect(await screen.findByRole("menuitem", { name: /^In 1 hour/ })).toHaveTextContent(+ time(at(2026, 6, 17, 16, 0), later),+ );+ });+});++describe("InboxSnoozeMenu custom time", () => {+ async function openDialog(onSnooze = vi.fn()) {+ renderWithI18n(<Harness onSnooze={onSnooze} />);+ fireEvent.click(await screen.findByRole("menuitem", { name: "Pick a time..." }));+ const dialog = await screen.findByRole("dialog");+ const field = dialog.querySelector('input[type="datetime-local"]') as HTMLInputElement;+ return { dialog, field, onSnooze };+ }++ it("starts from tomorrow morning", async () => {+ const { dialog, field } = await openDialog();++ expect(within(dialog).getByRole("heading", { name: "Snooze until" })).toBeInTheDocument();+ expect(field.value).toBe("2026-06-18T09:00");+ });++ it("snoozes until the time typed, in the viewer's own time zone", async () => {+ const { dialog, field, onSnooze } = await openDialog();++ fireEvent.change(field, { target: { value: "2026-07-03T08:30" } });+ fireEvent.click(within(dialog).getByRole("button", { name: "Snooze" }));++ expect(onSnooze).toHaveBeenCalledWith(at(2026, 7, 3, 8, 30));+ expect(screen.queryByRole("dialog")).toBeNull();+ });++ it("refuses a time that has passed and says what it takes", async () => {+ const { dialog, field, onSnooze } = await openDialog();++ fireEvent.change(field, { target: { value: "2026-06-17T09:00" } });+ fireEvent.click(within(dialog).getByRole("button", { name: "Snooze" }));++ expect(onSnooze).not.toHaveBeenCalled();+ expect(within(dialog).getByRole("alert")).toHaveTextContent(+ "Choose a time in the future, within a year.",+ );+ expect(field).toHaveAttribute("aria-invalid", "true");++ fireEvent.change(field, { target: { value: "2026-06-19T09:00" } });+ expect(within(dialog).queryByRole("alert")).toBeNull();+ });+});diff --git a/packages/views/inbox/components/inbox-snooze-menu.tsx b/packages/views/inbox/components/inbox-snooze-menu.tsxnew file mode 100644index 0000000000..796000fd13--- /dev/null+++ b/packages/views/inbox/components/inbox-snooze-menu.tsx@@ -0,0 +1,205 @@+"use client";++import { useId, useState, type ReactElement } from "react";+import {+ inboxSnoozeOptions,+ parseInboxSnoozeInput,+ type InboxSnoozePreset,+} from "@multica/core/inbox/snooze";+import { CalendarClock, Clock, Undo2 } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuShortcut,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import { Input } from "@multica/ui/components/ui/input";+import { useLocale, useT } from "../../i18n";+import { formatSnoozeTime } from "./inbox-snooze-time";++function useSnoozePresetLabel(): (preset: InboxSnoozePreset) => string {+ const { t } = useT("inbox");+ return (preset) =>+ preset === "in_one_hour"+ ? t(($) => $.snooze.in_one_hour)+ : preset === "later_today"+ ? t(($) => $.snooze.later_today)+ : preset === "tomorrow"+ ? t(($) => $.snooze.tomorrow)+ : t(($) => $.snooze.next_week);+}++/**+ * The snooze choices behind a trigger: a few times worth one click, and a+ * dialog for any other.+ *+ * Controlled, so the page's shortcut can open it for the row that is open.+ * `snoozed` adds the way back for an issue that is already put away.+ */+export function InboxSnoozeMenu({+ open,+ onOpenChange,+ trigger,+ snoozed = false,+ onSnooze,+ onUnsnooze,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ trigger: ReactElement;+ snoozed?: boolean;+ onSnooze: (until: Date) => void;+ onUnsnooze?: () => void;+}) {+ const { t } = useT("inbox");+ const locale = useLocale();+ const presetLabel = useSnoozePresetLabel();+ const [picking, setPicking] = useState(false);+ // Read when the menu opens, so the times it lists are the ones it snoozes to.+ const [now, setNow] = useState(() => new Date());++ return (+ <>+ <DropdownMenu+ open={open}+ onOpenChange={(next) => {+ if (next) setNow(new Date());+ onOpenChange(next);+ }}+ >+ <DropdownMenuTrigger render={trigger} />+ <DropdownMenuContent align="end" className="w-64">+ {snoozed && onUnsnooze && (+ <>+ <DropdownMenuItem onClick={onUnsnooze}>+ <Undo2 className="h-4 w-4" />+ {t(($) => $.snooze.unsnooze)}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>+ )}+ {inboxSnoozeOptions(now).map((option) => (+ <DropdownMenuItem key={option.preset} onClick={() => onSnooze(option.until)}>+ <Clock className="h-4 w-4" />+ {presetLabel(option.preset)}+ <DropdownMenuShortcut className="tracking-normal tabular-nums">+ {formatSnoozeTime(option.until, now, locale)}+ </DropdownMenuShortcut>+ </DropdownMenuItem>+ ))}+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => setPicking(true)}>+ <CalendarClock className="h-4 w-4" />+ {t(($) => $.snooze.pick_time)}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <p className="px-2 py-1 text-caption text-muted-foreground">{t(($) => $.snooze.hint)}</p>+ </DropdownMenuContent>+ </DropdownMenu>+ {picking && (+ <SnoozeTimeDialog+ onClose={() => setPicking(false)}+ onSnooze={(until) => {+ setPicking(false);+ onSnooze(until);+ }}+ />+ )}+ </>+ );+}++function pad(value: number): string {+ return String(value).padStart(2, "0");+}++/** A `datetime-local` value for a local time. */+function toLocalInput(date: Date): string {+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;+}++function SnoozeTimeDialog({+ onClose,+ onSnooze,+}: {+ onClose: () => void;+ onSnooze: (until: Date) => void;+}) {+ const { t } = useT("inbox");+ const { t: tIssues } = useT("issues");+ const { t: tCommon } = useT("common");+ const errorId = useId();+ // Tomorrow morning: the choice the field most often ends up near.+ const [value, setValue] = useState(() => {+ const tomorrow = inboxSnoozeOptions(new Date()).find((option) => option.preset === "tomorrow");+ return tomorrow ? toLocalInput(tomorrow.until) : "";+ });+ const [invalid, setInvalid] = useState(false);++ const submit = () => {+ const until = parseInboxSnoozeInput(value, new Date());+ if (!until) {+ setInvalid(true);+ return;+ }+ onSnooze(until);+ };++ return (+ <Dialog+ open+ onOpenChange={(next) => {+ if (!next) onClose();+ }}+ >+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>{t(($) => $.snooze.custom_title)}</DialogTitle>+ </DialogHeader>+ <form+ onSubmit={(event) => {+ event.preventDefault();+ submit();+ }}+ >+ <Input+ type="datetime-local"+ autoFocus+ aria-label={tIssues(($) => $.wakeups.local_time, {+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,+ })}+ aria-invalid={invalid}+ aria-describedby={invalid ? errorId : undefined}+ value={value}+ onChange={(event) => {+ setValue(event.target.value);+ setInvalid(false);+ }}+ />+ {invalid && (+ <p id={errorId} role="alert" className="mt-2 text-caption text-destructive">+ {t(($) => $.snooze.custom_invalid)}+ </p>+ )}+ <DialogFooter className="mt-4">+ <DialogClose render={<Button type="button" variant="outline" />}>+ {tCommon(($) => $.cancel)}+ </DialogClose>+ <Button type="submit">{t(($) => $.snooze.action)}</Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/inbox/components/inbox-snooze-time.test.ts b/packages/views/inbox/components/inbox-snooze-time.test.tsnew file mode 100644index 0000000000..5825b9217f--- /dev/null+++ b/packages/views/inbox/components/inbox-snooze-time.test.ts@@ -0,0 +1,27 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { formatSnoozeTime } from "./inbox-snooze-time";++const at = (y: number, m: number, d: number, h: number, min = 0) => new Date(y, m - 1, d, h, min);+// A Wednesday afternoon.+const now = at(2026, 6, 17, 14, 20);++describe("formatSnoozeTime", () => {+ it("shows the time alone for later today", () => {+ expect(formatSnoozeTime(at(2026, 6, 17, 18), now, "en-GB")).toBe("18:00");+ });++ it("names tomorrow", () => {+ expect(formatSnoozeTime(at(2026, 6, 18, 9), now, "en-GB")).toMatch(/^tomorrow 0?9:00$/);+ expect(formatSnoozeTime(at(2026, 6, 18, 9), now, "zh-Hans")).toMatch(/^明天 /);+ });++ it("names the weekday within the week", () => {+ expect(formatSnoozeTime(at(2026, 6, 22, 9), now, "en-GB")).toMatch(/^Mon 0?9:00$/);+ });++ it("shows the date further out, and the year once it differs", () => {+ expect(formatSnoozeTime(at(2026, 7, 3, 9), now, "en-GB")).toMatch(/^3 Jul,? 0?9:00$/);+ expect(formatSnoozeTime(at(2027, 1, 4, 9), now, "en-GB")).toMatch(/^4 Jan 2027,? 0?9:00$/);+ });+});diff --git a/packages/views/inbox/components/inbox-snooze-time.ts b/packages/views/inbox/components/inbox-snooze-time.tsnew file mode 100644index 0000000000..d9772c70be--- /dev/null+++ b/packages/views/inbox/components/inbox-snooze-time.ts@@ -0,0 +1,31 @@+const DAY_MS = 24 * 60 * 60 * 1000;++function startOfDay(date: Date): number {+ return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();+}++/**+ * When a snooze ends, as short as the distance allows: the time alone today,+ * "tomorrow" and the time, a weekday within the week, a date after that. In+ * the viewer's own time zone, which is the one they picked the time in.+ */+export function formatSnoozeTime(until: Date, now: Date, locale: string): string {+ const time = new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "2-digit" }).format(until);+ const days = Math.round((startOfDay(until) - startOfDay(now)) / DAY_MS);+ if (days <= 0) return time;+ if (days === 1) {+ const tomorrow = new Intl.RelativeTimeFormat(locale, { numeric: "auto" }).format(1, "day");+ return `${tomorrow} ${time}`;+ }+ if (days < 7) {+ const weekday = new Intl.DateTimeFormat(locale, { weekday: "short" }).format(until);+ return `${weekday} ${time}`;+ }+ return new Intl.DateTimeFormat(locale, {+ month: "short",+ day: "numeric",+ hour: "numeric",+ minute: "2-digit",+ ...(until.getFullYear() === now.getFullYear() ? {} : { year: "numeric" as const }),+ }).format(until);+}diff --git a/packages/views/inbox/components/inbox-working-item.test.tsx b/packages/views/inbox/components/inbox-working-item.test.tsxnew file mode 100644index 0000000000..ab4fc86b12--- /dev/null+++ b/packages/views/inbox/components/inbox-working-item.test.tsx@@ -0,0 +1,122 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { fireEvent, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { setApiInstance } from "@multica/core/api";+import type { ApiClient } from "@multica/core/api/client";+import type { InboxWorkingRow } from "@multica/core/inbox/sections";+import { issueDetailOptions } from "@multica/core/issues/queries";+import { WorkspaceSlugProvider } from "@multica/core/paths";+import type { Issue } from "@multica/core/types";+import { NavigationProvider, type NavigationAdapter } from "../../navigation";+import { renderWithI18n } from "../../test/i18n";+import { InboxWorkingItem } from "./inbox-working-item";++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({ getActorName: (_type: string, id: string) => `Agent ${id}` }),+}));+vi.mock("../../common/actor-avatar", () => ({+ ActorAvatar: ({ actorType, actorId }: { actorType: string; actorId: string }) => (+ <span data-testid="avatar" data-actor={`${actorType}:${actorId}`} />+ ),+}));++const ROW: InboxWorkingRow = {+ issueId: "issue-1",+ taskId: "task-1",+ agentId: "agent-1",+ queued: false,+ since: "2026-06-17T14:16:00Z",+};++function renderRow({+ row = ROW,+ issue,+ getIssue,+ adapter = {},+}: {+ row?: InboxWorkingRow;+ issue?: Partial<Issue>;+ getIssue?: () => Promise<Issue>;+ adapter?: Partial<NavigationAdapter>;+} = {}) {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });+ if (issue) qc.setQueryData(issueDetailOptions("ws-1", row.issueId).queryKey, issue as Issue);+ setApiInstance({ getIssue: getIssue ?? (() => new Promise<Issue>(() => {})) } as unknown as ApiClient);+ const onClick = vi.fn();+ const navigation: NavigationAdapter = {+ push: vi.fn(),+ replace: vi.fn(),+ back: vi.fn(),+ pathname: "/acme/inbox",+ searchParams: new URLSearchParams(),+ hash: "",+ getShareableUrl: (path) => path,+ ...adapter,+ };+ const utils = renderWithI18n(+ <QueryClientProvider client={qc}>+ <WorkspaceSlugProvider slug="acme">+ <NavigationProvider value={navigation}>+ <InboxWorkingItem row={row} isSelected={false} onClick={onClick} />+ </NavigationProvider>+ </WorkspaceSlugProvider>+ </QueryClientProvider>,+ );+ return { ...utils, onClick };+}++beforeEach(() => {+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(new Date("2026-06-17T14:20:00Z"));+});+afterEach(() => {+ vi.useRealTimers();+});++describe("InboxWorkingItem", () => {+ it("names the issue the agent is on, and how long it has been running", () => {+ renderRow({ issue: { id: "issue-1", title: "Search the work panel" } });++ const row = screen.getByRole("button");+ expect(row).toHaveTextContent("Search the work panel");+ expect(row).toHaveTextContent("4m");+ expect(screen.getByTestId("avatar")).toHaveAttribute("data-actor", "agent:agent-1");+ expect(row.querySelector(".bg-success")).not.toBeNull();+ });++ it("says a run that has not started is queued, without the live dot", () => {+ renderRow({ row: { ...ROW, queued: true }, issue: { id: "issue-1", title: "Search the work panel" } });++ const row = screen.getByRole("button");+ expect(row).toHaveTextContent("Queued");+ expect(row.querySelector(".bg-success")).toBeNull();+ });++ it("falls back to the agent's name when the issue cannot be read", async () => {+ renderRow({ getIssue: () => Promise.reject(new Error("forbidden")) });++ expect(await screen.findByText("Agent agent-1")).toBeInTheDocument();+ });++ it("opens the issue in the detail pane on a plain click", () => {+ const { onClick } = renderRow({ issue: { id: "issue-1", title: "Search the work panel" } });++ fireEvent.click(screen.getByRole("button"));++ expect(onClick).toHaveBeenCalledTimes(1);+ });++ it("opens the issue as its own tab on a modifier click", () => {+ const openInNewTab = vi.fn();+ const { onClick } = renderRow({+ issue: { id: "issue-1", title: "Search the work panel" },+ adapter: { openInNewTab },+ });++ fireEvent.click(screen.getByRole("button"), { metaKey: true });++ expect(onClick).not.toHaveBeenCalled();+ expect(openInNewTab).toHaveBeenCalledWith("/acme/issues/issue-1", undefined);+ });+});diff --git a/packages/views/inbox/components/inbox-working-item.tsx b/packages/views/inbox/components/inbox-working-item.tsxnew file mode 100644index 0000000000..6b51ce4516--- /dev/null+++ b/packages/views/inbox/components/inbox-working-item.tsx@@ -0,0 +1,89 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import type { InboxWorkingRow } from "@multica/core/inbox/sections";+import { issueDetailOptions } from "@multica/core/issues/queries";+import { useWorkspaceId } from "@multica/core/hooks";+import { paths, useWorkspaceSlug } from "@multica/core/paths";+import { useActorName } from "@multica/core/workspace/hooks";+import { Skeleton } from "@multica/ui/components/ui/skeleton";+import { ActorAvatar } from "../../common/actor-avatar";+import { handleRowActivationKey } from "../../common/row-actions-menu";+import { useT } from "../../i18n";+import { resolveClickIntent, useIntentNavigate } from "../../navigation";+import { useTimeAgo } from "./inbox-list-item";++/**+ * An issue an agent is working on for the user. One quiet line: nothing here+ * is waiting on them, it only shows the hand-over is still in flight.+ *+ * The run carries no issue title, so the row reads the issue itself. That is+ * the same cache entry the detail pane fills when the row is opened.+ */+export function InboxWorkingItem({+ row,+ isSelected,+ onClick,+}: {+ row: InboxWorkingRow;+ isSelected: boolean;+ onClick: () => void;+}) {+ const { t } = useT("inbox");+ const wsId = useWorkspaceId();+ const slug = useWorkspaceSlug();+ const timeAgo = useTimeAgo();+ const { getActorName } = useActorName();+ const intentNavigate = useIntentNavigate();+ const issue = useQuery(issueDetailOptions(wsId, row.issueId));+ const issueHref = slug ? paths.workspace(slug).issueDetail(row.issueId) : null;++ return (+ <div+ role="button"+ tabIndex={0}+ onClick={(e) => {+ if (issueHref) {+ const intent = resolveClickIntent(e);+ if (intent !== "push") {+ intentNavigate(issueHref, intent);+ return;+ }+ }+ onClick();+ }}+ onKeyDown={(e) => handleRowActivationKey(e, onClick)}+ onAuxClick={(e) => {+ if (e.defaultPrevented || e.button !== 1 || !issueHref) return;+ e.preventDefault();+ intentNavigate(issueHref, "background-tab");+ }}+ className={`flex w-full cursor-default select-none items-center gap-2 rounded-md px-2 py-2 text-left outline-none transition-colors focus-visible:ring-1 focus-visible:ring-ring ${+ isSelected ? "bg-accent" : "hover:bg-accent/50"+ }`}+ >+ <ActorAvatar actorType="agent" actorId={row.agentId} size="sm" enableHoverCard />+ <span className="min-w-0 flex-1 truncate text-body text-muted-foreground">+ {issue.data ? (+ issue.data.title+ ) : issue.isPending ? (+ <Skeleton className="h-3.5 w-2/3" />+ ) : (+ // The issue cannot be read (deleted, or out of the viewer's reach):+ // the agent's name still says what the row is.+ getActorName("agent", row.agentId)+ )}+ </span>+ {row.queued ? (+ <span className="shrink-0 text-caption text-muted-foreground">+ {t(($) => $.sections.queued)}+ </span>+ ) : (+ <span className="flex shrink-0 items-center gap-1.5 text-caption text-muted-foreground">+ <span aria-hidden className="size-1.5 rounded-full bg-success" />+ {timeAgo(row.since)}+ </span>+ )}+ </div>+ );+}diff --git a/packages/views/inbox/components/use-inbox-sections.test.tsx b/packages/views/inbox/components/use-inbox-sections.test.tsxnew file mode 100644index 0000000000..2fae553f17--- /dev/null+++ b/packages/views/inbox/components/use-inbox-sections.test.tsx@@ -0,0 +1,96 @@+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import { QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { createQueryClient } from "@multica/core/query-client";+import { inboxKeys, useInboxUnreadCount } from "@multica/core/inbox/queries";+import { EMPTY_INBOX_FILTERS, activeInboxFilterSupport, effectiveInboxFilters } from "@multica/core/inbox/filter-store";+import type { AgentTask, InboxItem } from "@multica/core/types";+import { useInboxSections } from "./use-inbox-sections";++const mocks = vi.hoisted(() => ({ tasks: [] as unknown[], summary: vi.fn() }));+vi.mock("@multica/core/auth", () => ({+ useAuthStore: (selector: (state: unknown) => unknown) => selector({ user: { id: "me" } }),+}));+vi.mock("@multica/core/agents", () => ({+ agentTaskSnapshotOptions: () => ({ queryKey: ["test-tasks"], queryFn: async () => mocks.tasks }),+}));+vi.mock("@multica/core/issues/queries", () => ({+ issueDetailOptions: (_ws: string, id: string) => ({+ queryKey: ["test-issue", id],+ queryFn: async () => ({ id, project_id: "project-b", labels: [] }),+ }),+}));+vi.mock("@multica/core/api", () => ({ api: { getInboxUnreadSummary: mocks.summary } }));++afterEach(() => {+ cleanup();+ vi.useRealTimers();+ mocks.tasks = [];+});++describe("useInboxSections", () => {+ it("re-reads the badge when a snoozed issue comes back, with no other event", async () => {+ vi.useFakeTimers();+ const start = Date.parse("2026-11-14T12:00:00Z");+ vi.setSystemTime(start);+ const row = {+ id: "n",+ issue_id: "i",+ section: "needs_you",+ archived: false,+ read: false,+ created_at: new Date(start).toISOString(),+ snoozed_until: new Date(start + 1000).toISOString(),+ } as InboxItem;+ const qc = createQueryClient();+ qc.setQueryData(["test-tasks"], []);+ qc.setQueryData(inboxKeys.unreadSummary(), [{ workspace_id: "ws", count: 0, needs_you: 0 }]);+ mocks.summary.mockResolvedValue([{ workspace_id: "ws", count: 1, needs_you: 1 }]);+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>+ );+ const { result } = renderHook(+ () => ({+ sections: useInboxSections("ws", [row], [row], { filters: EMPTY_INBOX_FILTERS }),+ badge: useInboxUnreadCount("ws"),+ }),+ { wrapper },+ );+ expect(result.current.sections.snoozed).toHaveLength(1);++ await act(async () => {+ await vi.advanceTimersByTimeAsync(1100);+ });++ expect(result.current.sections.needsYou).toHaveLength(1);+ expect(result.current.badge).toBe(1);+ });++ it("keeps narrowing Working when no notification is left", async () => {+ mocks.tasks = [+ {+ id: "t",+ issue_id: "i",+ agent_id: "a",+ status: "running",+ started_at: "2026-11-14T12:00:00Z",+ created_at: "2026-11-14T12:00:00Z",+ attribution: { source: "direct_human", originator: { id: "me" } },+ } as AgentTask,+ ];+ const rawItems: InboxItem[] = [];+ const filters = effectiveInboxFilters(+ { ...EMPTY_INBOX_FILTERS, projects: ["project-a"] },+ activeInboxFilterSupport(rawItems),+ );+ const qc = createQueryClient();+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>+ );+ const { result } = renderHook(() => useInboxSections("ws", rawItems, rawItems, { filters }), { wrapper });++ await waitFor(() => expect(result.current.workingPending).toBe(false));+ expect(result.current.working).toHaveLength(0);+ });+});diff --git a/packages/views/inbox/components/use-inbox-sections.ts b/packages/views/inbox/components/use-inbox-sections.tsnew file mode 100644index 0000000000..1b39e52512--- /dev/null+++ b/packages/views/inbox/components/use-inbox-sections.ts@@ -0,0 +1,103 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import { useQueries, useQuery, useQueryClient, type UseQueryResult } from "@tanstack/react-query";+import { agentTaskSnapshotOptions } from "@multica/core/agents";+import { useAuthStore } from "@multica/core/auth";+import {+ inboxFilterCount,+ inboxIssueMatches,+ inboxIssueProjection,+ type InboxFilters,+} from "@multica/core/inbox/filter-store";+import { inboxKeys } from "@multica/core/inbox/queries";+import {+ buildInboxSections,+ nextInboxWake,+ type InboxSections,+} from "@multica/core/inbox/sections";+import { issueDetailOptions } from "@multica/core/issues/queries";+import type { AgentTask, InboxItem, Issue } from "@multica/core/types";++const EMPTY_TASKS: AgentTask[] = [];+const issuesOf = (results: UseQueryResult<Issue>[]) => ({+ issues: results.map((result) => result.data),+ pending: results.some((result) => result.isPending),+});++export interface InboxSectionsState extends InboxSections {+ /**+ * "Working" is not settled: the task snapshot has not answered, or under a+ * filter an issue a row is tested against has not loaded. Until then a link+ * to an issue that is only listed there cannot be told from a broken one.+ */+ workingPending: boolean;+}+// The longest delay a timer takes; a snooze further out re-arms when it fires.+const MAX_TIMER_MS = 2_147_000_000;++/**+ * The current time, moved forward when the next snooze in `items` runs out.+ * Nothing arrives from the server when a snooze simply elapses, so the list+ * has to notice by itself that an issue is back, and the badge is re-read+ * with it so the two agree.+ */+function useInboxClock(items: readonly InboxItem[]): number {+ const qc = useQueryClient();+ const [now, setNow] = useState(() => Date.now());+ const nextWake = useMemo(() => nextInboxWake(items, now), [items, now]);+ useEffect(() => {+ if (nextWake == null) return;+ const delay = Math.min(Math.max(nextWake - Date.now(), 0) + 50, MAX_TIMER_MS);+ const timer = setTimeout(() => {+ setNow(Date.now());+ if (Date.now() >= nextWake) void qc.invalidateQueries({ queryKey: inboxKeys.unreadSummary() });+ }, delay);+ return () => clearTimeout(timer);+ }, [nextWake, qc]);+ return now;+}++/**+ * The Inbox list split into its sections.+ *+ * `rows` is the list as filtered, one notification per issue; `items` is every+ * active notification. "Working" is read from the workspace's task snapshot,+ * which realtime already keeps fresh.+ *+ * `filters` narrows "Working" like every other section. A run carries none of+ * its issue's fields, so the row is tested against the issue itself, the same+ * cache entry the row shows its title from, and is left out until that has+ * loaded.+ */+export function useInboxSections(+ wsId: string,+ rows: readonly InboxItem[],+ items: readonly InboxItem[],+ { filters, openKey = null }: { filters: InboxFilters; openKey?: string | null },+): InboxSectionsState {+ const userId = useAuthStore((s) => s.user?.id);+ const { data: tasks = EMPTY_TASKS, isPending: tasksPending } = useQuery(agentTaskSnapshotOptions(wsId));+ const now = useInboxClock(items);+ const sections = useMemo(+ () => buildInboxSections(rows, items, now, { working: { tasks, userId }, openKey }),+ [rows, items, now, tasks, userId, openKey],+ );+ const filtered = inboxFilterCount(filters) > 0;+ const workingIssues = useQueries({+ queries: filtered ? sections.working.map((row) => issueDetailOptions(wsId, row.issueId)) : [],+ combine: issuesOf,+ });+ return useMemo(() => {+ if (!filtered) return { ...sections, workingPending: tasksPending };+ const at = new Date(now);+ return {+ ...sections,+ working: sections.working.filter((_row, index) => {+ const issue = workingIssues.issues[index];+ return !!issue && inboxIssueMatches(inboxIssueProjection(issue), filters, at);+ }),+ workingPending: tasksPending || workingIssues.pending,+ };+ }, [sections, filtered, workingIssues, filters, now, tasksPending]);+}diff --git a/packages/views/issue-views/all-views-page.test.tsx b/packages/views/issue-views/all-views-page.test.tsxindex 134cf9d426..4bf2b0fd88 100644--- a/packages/views/issue-views/all-views-page.test.tsx+++ b/packages/views/issue-views/all-views-page.test.tsx@@ -128,8 +128,8 @@ describe("AllViewsPage", () => {expect(screen.getByRole("heading", { level: 1, name: "All views" })).toBeInTheDocument();await user.click(screen.getByRole("button", { name: "All views" }));- expect(await screen.findByRole("menuitemradio", { name: /^All views/ })).toHaveTextContent("6");- expect(screen.getByRole("menuitemradio", { name: /^Built-in/ })).toHaveTextContent("4");+ expect(await screen.findByRole("menuitemradio", { name: /^All views/ })).toHaveTextContent("4");+ expect(screen.getByRole("menuitemradio", { name: /^Built-in/ })).toHaveTextContent("2");expect(screen.getByRole("menuitemradio", { name: /^Created by me/ })).toHaveTextContent("1");await user.click(screen.getByRole("menuitemradio", { name: /^Shared/ }));@@ -172,17 +172,12 @@ describe("AllViewsPage", () => {expect(useActiveIssueViewStore.getState().active[WORKSPACE_KEY]).toBe("v2");});- it("lists Unread as a built-in that is starred on demand and opens its view", async () => {- const user = userEvent.setup();- const { push } = renderPage();-- await user.click(screen.getByRole("button", { name: "Add Unread to sidebar" }));- expect(mocks.star).toHaveBeenCalledWith("builtin:unread");- expect(push).not.toHaveBeenCalled();+ it("no longer lists the two built-ins the Inbox replaced", () => {+ renderPage();- await user.click(screen.getByText("Unread"));- expect(push).toHaveBeenCalledWith("/acme/issues?view=unread");- expect(useActiveIssueViewStore.getState().active[WORKSPACE_KEY]).toBe("unread");+ expect(screen.queryByText("Unread")).not.toBeInTheDocument();+ expect(screen.queryByText("My agents' work")).not.toBeInTheDocument();+ expect(screen.getAllByRole("button", { name: /^(Add .+ to|Remove .+ from) sidebar$/ })).toHaveLength(4);});it("opens a view in place for a shift-click, which rows never hand to the browser", async () => {@@ -214,23 +209,18 @@ describe("AllViewsPage", () => {expect(useActiveIssueViewStore.getState().active[WORKSPACE_KEY]).toBe("v-open");});- it("gives My Issues and My agents' work their own URLs", async () => {+ it("opens My Issues at its own URL", async () => {const user = userEvent.setup();const openInNewTab = vi.fn();const { push } = renderPage({ openInNewTab });- const row = (name: string) =>- screen- .getByRole("button", { name: new RegExp(`^(Add ${name} to|Remove ${name} from) sidebar$`) })- .closest('[role="row"]')!;+ const row = screen.getByRole("button", { name: "Remove My Issues from sidebar" }).closest('[role="row"]')!;await user.keyboard("{Meta>}");- await user.click(row("My Issues"));- await user.click(row("My agents' work"));+ await user.click(row);await user.keyboard("{/Meta}");expect(openInNewTab).toHaveBeenCalledWith("/acme/my-issues", "My Issues");- expect(openInNewTab).toHaveBeenCalledWith("/acme/my-issues?scope=agents", "My agents' work");- await user.click(row("My agents' work"));- expect(push).toHaveBeenCalledWith("/acme/my-issues?scope=agents");+ await user.click(row);+ expect(push).toHaveBeenCalledWith("/acme/my-issues");});});diff --git a/packages/views/issue-views/all-views-page.tsx b/packages/views/issue-views/all-views-page.tsxindex 3c35a61430..e9d0568840 100644--- a/packages/views/issue-views/all-views-page.tsx+++ b/packages/views/issue-views/all-views-page.tsx@@ -3,7 +3,6 @@import { useMemo, useState } from "react";import { useQuery } from "@tanstack/react-query";import {- Bot,CircleUser,Copy,Layers,@@ -54,7 +53,6 @@ import {import { useT } from "../i18n";import { useBuiltinViewNavigation } from "./builtin-views";import { DeleteViewDialog } from "./delete-view-dialog";-import { UnreadViewIcon } from "./unread-view-icon";import { useIssueViewActions } from "./use-view-actions";type DirectoryScope = "all" | "builtin" | "mine" | "shared";@@ -69,9 +67,7 @@ type DirectoryRow =const BUILTIN_ICON: Record<BuiltinViewKey, React.ReactNode> = {my_issues: <CircleUser className="size-4 shrink-0 text-muted-foreground" />,- my_agents: <Bot className="size-4 shrink-0 text-muted-foreground" />,all_issues: <ListTodo className="size-4 shrink-0 text-muted-foreground" />,- unread: <UnreadViewIcon />,};/** Every view the user can open, and the switch that puts it in the sidebar. */diff --git a/packages/views/issue-views/builtin-views.ts b/packages/views/issue-views/builtin-views.tsindex d067bae72d..ac5813725e 100644--- a/packages/views/issue-views/builtin-views.ts+++ b/packages/views/issue-views/builtin-views.ts@@ -5,8 +5,6 @@ import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";import { issueViewContainerKey, useActiveIssueViewStore } from "@multica/core/issue-views/active-view-store";import type { BuiltinViewKey } from "@multica/core/issue-views/sidebar-views";-import { UNREAD_VIEW, UNREAD_VIEW_ID } from "@multica/core/issue-views/unread-view";-import { issueViewTarget } from "@multica/core/issue-views/view-target";const WORKSPACE_SCOPE = { scope_type: "workspace" } as const;const MY_SCOPE = { scope_type: "my" } as const;@@ -21,24 +19,13 @@ export function useBuiltinViewNavigation() {const setActive = useActiveIssueViewStore((s) => s.setActive);const hrefFor = useCallback(- (key: BuiltinViewKey) =>- key === "unread"- ? issueViewTarget(wsId, UNREAD_VIEW, p).href- : key === "all_issues"- ? p.issues()- : key === "my_agents"- ? p.myAgents()- : p.myIssues(),- [p, wsId],+ (key: BuiltinViewKey) => (key === "all_issues" ? p.issues() : p.myIssues()),+ [p],);const prepare = useCallback((key: BuiltinViewKey) => {- if (key === "unread" || key === "all_issues") {- setActive(issueViewContainerKey(wsId, WORKSPACE_SCOPE), key === "unread" ? UNREAD_VIEW_ID : null);- return;- }- setActive(issueViewContainerKey(wsId, MY_SCOPE), null);+ setActive(issueViewContainerKey(wsId, key === "all_issues" ? WORKSPACE_SCOPE : MY_SCOPE), null);},[setActive, wsId],);diff --git a/packages/views/issue-views/view-header.tsx b/packages/views/issue-views/view-header.tsxindex 160b75ccda..eaf8e0ffd7 100644--- a/packages/views/issue-views/view-header.tsx+++ b/packages/views/issue-views/view-header.tsx@@ -168,16 +168,21 @@ export function IssueViewHeader({const agentRunningFilter = useViewStore((s) => s.agentRunningFilter);const toggleAgentRunningFilter = useViewStore((s) => s.toggleAgentRunningFilter);+ // My agents' work is still a page (old links and open tabs land on it), but+ // no longer a built-in view: it has a name and no star.+ const myAgents = base.kind === "my" && myScope === "agents";const builtinKey: BuiltinViewKey | null =- base.kind === "workspace" ? "all_issues" : base.kind === "my" ? (myScope === "agents" ? "my_agents" : "my_issues") : null;+ base.kind === "workspace" ? "all_issues" : base.kind === "my" && !myAgents ? "my_issues" : null;const baseName =base.kind === "project"? base.project.title- : t(($) => $.views.builtin[builtinKey!]);+ : myAgents+ ? t(($) => $.views.builtin.my_agents)+ : t(($) => $.views.builtin[builtinKey!]);const baseIcon =base.kind === "project" ? (<ProjectIcon project={base.project} size="sm" />- ) : builtinKey === "my_agents" ? (+ ) : myAgents ? (<Bot className="size-4" />) : builtinKey === "my_issues" ? (<CircleUser className="size-4" />@@ -206,7 +211,7 @@ export function IssueViewHeader({const unreadView = isUnreadView(activeView);const activeViewName = unreadView ? t(($) => $.views.builtin.unread) : activeView?.name;const starId = unreadView- ? builtinViewItemId("unread")+ ? null: activeView? savedViewItemId(activeView.id): builtinKey@@ -471,7 +476,7 @@ export function IssueViewHeader({<DropdownMenuItemonClick={() =>actions.copyLink(- builtinKey === "my_agents"+ myAgents? paths.myAgents(): base.kind === "my"? paths.myIssues()diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 80de2819e9..e1da3ec9f7 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -1253,6 +1253,13 @@ interface IssueDetailProps {variant?: "page" | "peek";/** Peek only: host controls at the end of the header (open full page, close). */trailingActions?: ReactNode;+ /**+ * The host's own actions on what it has open, ahead of the issue's in the+ * header. The inbox puts snooze and archive here: they act on the+ * notification, which only the inbox knows. A host that passes them owns+ * archiving, so the header's own archive button for a done issue is left out.+ */+ hostActions?: ReactNode;/*** Read the viewer's inbox notifications on this issue while it is on screen* (MUL-8588). The inbox turns this off for the issue it has open: it reads@@ -1472,7 +1479,7 @@ export function IssueDetailSkeleton({// IssueDetail-export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = ISSUE_DETAIL_LAYOUT_ID, highlightCommentId: linkedCommentId, highlightRequestToken: linkedRequestToken, highlightAppRequestId, leadingAction, variant = "page", trailingActions, readsInbox = true, skipInitialRefetch = false, openDeliverable, onDeliverableLinkDone }: IssueDetailProps) {+export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = ISSUE_DETAIL_LAYOUT_ID, highlightCommentId: linkedCommentId, highlightRequestToken: linkedRequestToken, highlightAppRequestId, leadingAction, variant = "page", trailingActions, hostActions, readsInbox = true, skipInitialRefetch = false, openDeliverable, onDeliverableLinkDone }: IssueDetailProps) {const isPeek = variant === "peek";const { t } = useT("issues");const { t: tCommon } = useT("common");@@ -3539,6 +3546,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trIt self-hides when no agent is active. */}<IssueAgentHeaderChip issueId={id} onJumpToRun={jumpToRun} /><IssueWakeupHeaderChip issueId={id} onOpen={openWakeups} />+ {hostActions}{onDone && !issueBehavesAsAny(issue, ["done", "closed"]) && (<IconButtonlabel={t(($) => $.detail.mark_done_tooltip)}@@ -3549,7 +3557,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr<CircleCheck /></IconButton>)}- {onDone && issueBehavesAs(issue, "done") && (+ {onDone && !hostActions && issueBehavesAs(issue, "done") && (<IconButtonlabel={t(($) => $.detail.archive_tooltip)}tooltipSide="bottom"diff --git a/packages/views/layout/app-rail.tsx b/packages/views/layout/app-rail.tsxindex 90d5b1c7fa..85f745e5b8 100644--- a/packages/views/layout/app-rail.tsx+++ b/packages/views/layout/app-rail.tsx@@ -13,7 +13,7 @@ import {import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";import { SortableContext, arrayMove, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";-import { CheckCheck, ExternalLink, Link2, RotateCcw, Settings, Users, type IconComponent } from "@multica/ui/icons";+import { ExternalLink, Link2, RotateCcw, Settings, Users, type IconComponent } from "@multica/ui/icons";import { toast } from "sonner";import { useChatStore } from "@multica/core/chat";import { chatSessionsOptions } from "@multica/core/chat/queries";@@ -23,7 +23,6 @@ import {inboxListOptions,useInboxUnreadCount,} from "@multica/core/inbox/queries";-import { useMarkAllInboxRead } from "@multica/core/inbox/mutations";import { resolveRailOrder, useRailOrderStore } from "@multica/core/navigation";import {RAIL_SPACES,@@ -211,7 +210,7 @@ function RailSpaceLink({// bubble through it; a press inside the menu must not start a drag.const menu = rowMenu.menu.point && (<span className="contents" onPointerDown={(event) => event.stopPropagation()}>- <RailSpaceMenu space={space} href={href} title={fullLabel} unread={badge?.kind === "count" ? badge.value : 0} state={rowMenu} />+ <RailSpaceMenu href={href} title={fullLabel} state={rowMenu} /></span>);// A label the same as the full name still needs the tooltip whenever a@@ -238,16 +237,12 @@ function RailSpaceLink({/** A rail space's right-click menu. */function RailSpaceMenu({- space,href,title,- unread,state,}: {- space: RailSpaceId;href: string;title: string;- unread: number;state: ReturnType<typeof useRowMenu>;}) {const { t } = useT("layout");@@ -257,7 +252,6 @@ function RailSpaceMenu({const copyLink = async () => {if (await copyText(getShareableUrl(href))) toast.success(t(($) => $.rail.link_copied));};- const markAllRead = useMarkAllInboxRead();const customOrder = useRailOrderStore((s) => s.order !== null);const setOrder = useRailOrderStore((s) => s.setOrder);return (@@ -271,21 +265,6 @@ function RailSpaceMenu({<Link2 />{t(($) => $.rail.copy_link)}</DropdownMenuItem>- {space === "inbox" && unread > 0 && (- <>- <DropdownMenuSeparator />- <DropdownMenuItem- onClick={() =>- markAllRead.mutate(undefined, {- onError: () => toast.error(t(($) => $.rail.mark_all_read_failed)),- })- }- >- <CheckCheck />- {t(($) => $.rail.mark_all_read)}- </DropdownMenuItem>- </>- )}<DropdownMenuSeparator /><DropdownMenuItem disabled={!customOrder} onClick={() => setOrder(RAIL_SPACES)}><RotateCcw />diff --git a/packages/views/layout/panels/list-space-peeks.test.tsx b/packages/views/layout/panels/list-space-peeks.test.tsxnew file mode 100644index 0000000000..a3d6617653--- /dev/null+++ b/packages/views/layout/panels/list-space-peeks.test.tsx@@ -0,0 +1,220 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { fireEvent, screen, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { agentTaskSnapshotOptions } from "@multica/core/agents";+import { setApiInstance } from "@multica/core/api";+import type { ApiClient } from "@multica/core/api/client";+import { useInboxFilterStore } from "@multica/core/inbox/filter-store";+import { inboxKeys } from "@multica/core/inbox/queries";+import type { InboxSections } from "@multica/core/inbox/sections";+import type { AgentTask, InboxItem } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { InboxPeek } from "./list-space-peeks";++const push = vi.hoisted(() => vi.fn());+const archive = vi.hoisted(() => vi.fn());++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/auth", () => ({+ useAuthStore: (selector: (state: { user: { id: string } }) => unknown) =>+ selector({ user: { id: "member-1" } }),+}));+vi.mock("@multica/core/paths", () => ({+ useWorkspacePaths: () => ({ inbox: () => "/acme/inbox", chat: () => "/acme/chat" }),+}));+vi.mock("@multica/core/inbox/queries", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/inbox/queries")>()),+ useInboxUnreadCount: () => 1,+}));+vi.mock("@multica/core/inbox/mutations", () => ({ useArchiveInbox: () => ({ mutate: archive }) }));+vi.mock("../../navigation", () => ({ useNavigation: () => ({ push }) }));+vi.mock("../../chat/components/chat-thread-list", () => ({ ChatThreadList: () => null }));++// The list itself has its own tests. Here it is the sections it was handed+// and the callbacks the peek wired into it.+vi.mock("../../inbox/components/inbox-sectioned-list", () => ({+ InboxSectionedList: ({+ sections,+ filtered,+ scrollRestoration,+ onSelect,+ onSelectIssue,+ onAction,+ }: {+ sections: InboxSections;+ filtered: boolean;+ scrollRestoration: boolean;+ onSelect: (item: InboxItem) => void;+ onSelectIssue: (issueId: string) => void;+ onAction: (id: string) => void;+ }) => (+ <div data-testid="list" data-filtered={String(filtered)} data-scroll-restoration={String(scrollRestoration)}>+ {(["needsYou", "updates", "snoozed"] as const).flatMap((section) =>+ sections[section].map((row) => (+ <span key={row.item.id}>+ <button type="button" data-row={section} onClick={() => onSelect(row.item)}>+ {row.item.id}+ </button>+ <button type="button" onClick={() => onAction(row.item.id)}>+ archive {row.item.id}+ </button>+ </span>+ )),+ )}+ {sections.working.map((row) => (+ <button key={row.issueId} type="button" data-row="working" onClick={() => onSelectIssue(row.issueId)}>+ {row.issueId}+ </button>+ ))}+ </div>+ ),+}));++function item(id: string, overrides: Partial<InboxItem> = {}): InboxItem {+ return {+ id,+ workspace_id: "ws-1",+ recipient_type: "member",+ recipient_id: "member-1",+ actor_type: "agent",+ actor_id: "agent-1",+ type: "new_comment",+ severity: "info",+ issue_id: `issue-${id}`,+ title: "Issue title",+ body: null,+ issue_status: null,+ read: true,+ archived: false,+ created_at: "2026-06-15T08:00:00Z",+ details: null,+ ...overrides,+ };+}++function renderPeek(items: InboxItem[], tasks: AgentTask[] = []) {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });+ qc.setQueryData(inboxKeys.list("ws-1"), items);+ qc.setQueryData(agentTaskSnapshotOptions("ws-1").queryKey, tasks);+ return renderWithI18n(+ <QueryClientProvider client={qc}>+ <InboxPeek />+ </QueryClientProvider>,+ );+}++const rows = () =>+ Array.from(document.querySelectorAll("[data-row]")).map(+ (el) => `${el.getAttribute("data-row")}:${el.textContent}`,+ );++beforeEach(() => {+ push.mockClear();+ archive.mockClear();+ useInboxFilterStore.setState({ filtersByWorkspace: {} });+});++describe("InboxPeek", () => {+ it("shows the Inbox in its sections, without the archived or the snoozed mixed in", () => {+ renderPeek(+ [+ item("needs", { section: "needs_you" }),+ item("update", { section: "updates", read: false }),+ // Read, so on its way to the archive.+ item("seen", { section: "updates" }),+ item("later", { section: "needs_you", snoozed_until: new Date(Date.now() + 3_600_000).toISOString() }),+ item("gone", { section: "needs_you", archived: true }),+ ],+ [+ {+ id: "task-1",+ agent_id: "agent-1",+ issue_id: "issue-w",+ status: "running",+ created_at: "2026-06-15T08:00:00Z",+ started_at: "2026-06-15T08:01:00Z",+ attribution: { source: "direct_human", precise: true, originator: { id: "member-1" } },+ } as AgentTask,+ ],+ );++ expect(rows()).toEqual(["needsYou:needs", "updates:update", "snoozed:later", "working:issue-w"]);+ // A preview over another route must not take that route's scroll offset.+ expect(screen.getByTestId("list")).toHaveAttribute("data-scroll-restoration", "false");+ });++ it("lands on the row in the Inbox, whether it is a notification or a Working issue", () => {+ renderPeek([item("needs", { section: "needs_you" })], [+ {+ id: "task-1",+ agent_id: "agent-1",+ issue_id: "issue-w",+ status: "queued",+ created_at: "2026-06-15T08:00:00Z",+ attribution: { source: "direct_human", precise: true, originator: { id: "member-1" } },+ } as AgentTask,+ ]);++ fireEvent.click(screen.getByText("needs"));+ expect(push).toHaveBeenLastCalledWith("/acme/inbox?issue=issue-needs");+ fireEvent.click(screen.getByText("issue-w"));+ expect(push).toHaveBeenLastCalledWith("/acme/inbox?issue=issue-w");+ });++ it("archives from the row", () => {+ renderPeek([item("needs", { section: "needs_you" })]);++ fireEvent.click(screen.getByText("archive needs"));++ expect(archive).toHaveBeenCalledWith("needs");+ });++ it("follows the Inbox's saved filters, Working included", async () => {+ setApiInstance({+ getIssue: async (id: string) => ({ id, status: "todo", priority: id === "issue-w" ? "high" : "low", labels: [] }),+ } as unknown as ApiClient);+ const filters = useInboxFilterStore.getState();+ filters.togglePriorityFilter("ws-1", "high");+ // A filter for the archive, which the Inbox leaves alone.+ filters.toggleUnreadOnly("ws-1");+ const run = (issueId: string) =>+ ({+ id: `task-${issueId}`,+ agent_id: "agent-1",+ issue_id: issueId,+ status: "running",+ created_at: "2026-06-15T08:00:00Z",+ attribution: { source: "direct_human", precise: true, originator: { id: "member-1" } },+ }) as AgentTask;+ renderPeek(+ [+ item("high", { section: "needs_you", issue_priority: "high" }),+ item("low", { section: "needs_you", issue_priority: "low", read: false }),+ ],+ [run("issue-w"), run("issue-other")],+ );++ await waitFor(() => expect(rows()).toEqual(["needsYou:high", "working:issue-w"]));+ expect(screen.getByTestId("list")).toHaveAttribute("data-filtered", "true");+ });++ it("keeps narrowing Working once no notification is left", async () => {+ setApiInstance({+ getIssue: async (id: string) => ({ id, status: "todo", project_id: id === "issue-a" ? "project-a" : "project-b", labels: [] }),+ } as unknown as ApiClient);+ useInboxFilterStore.getState().toggleFilterValue("ws-1", "project", "project-a");+ const run = (issueId: string) =>+ ({+ id: `task-${issueId}`,+ agent_id: "agent-1",+ issue_id: issueId,+ status: "running",+ created_at: "2026-06-15T08:00:00Z",+ attribution: { source: "direct_human", precise: true, originator: { id: "member-1" } },+ }) as AgentTask;+ renderPeek([], [run("issue-a"), run("issue-b")]);++ await waitFor(() => expect(rows()).toEqual(["working:issue-a"]));+ expect(screen.getByTestId("list")).toHaveAttribute("data-filtered", "true");+ });+});diff --git a/packages/views/layout/panels/list-space-peeks.tsx b/packages/views/layout/panels/list-space-peeks.tsxindex 65834a37d1..c1a34d13fb 100644--- a/packages/views/layout/panels/list-space-peeks.tsx+++ b/packages/views/layout/panels/list-space-peeks.tsx@@ -7,10 +7,10 @@ import { useSetChatSessionArchived } from "@multica/core/chat/mutations";import { chatSessionsOptions } from "@multica/core/chat/queries";import { useWorkspaceId } from "@multica/core/hooks";import {+ activeInboxFilterSupport,effectiveInboxFilters,filterInboxItems,- inboxIssueFieldsSupport,- inboxPriorityFilterSupport,+ inboxFilterCount,useInboxFilters,} from "@multica/core/inbox/filter-store";import { useArchiveInbox } from "@multica/core/inbox/mutations";@@ -23,8 +23,8 @@ import type { Agent, ChatSession, InboxItem } from "@multica/core/types";import { agentListOptions } from "@multica/core/workspace/queries";import { ChatThreadList } from "../../chat/components/chat-thread-list";import { useT } from "../../i18n";-import { InboxList } from "../../inbox/components/inbox-list";-import { useIssueSurfaceActivity } from "../../issues/surface/activity";+import { InboxSectionedList } from "../../inbox/components/inbox-sectioned-list";+import { useInboxSections } from "../../inbox/components/use-inbox-sections";import { useNavigation } from "../../navigation";import { PanelCount, PanelHeader } from "../panel-nav";@@ -33,8 +33,9 @@ const EMPTY_SESSIONS: ChatSession[] = [];const EMPTY_AGENTS: Agent[] = [];/**- * Inbox previewed from another space: the list the Inbox page shows, under- * the same saved filters. Opening a row lands on it in the Inbox.+ * Inbox previewed from another space: the list the Inbox page shows, in the+ * same sections and under the same saved filters. Opening a row lands on it+ * in the Inbox.*/export function InboxPeek() {const { t } = useT("inbox");@@ -43,19 +44,17 @@ export function InboxPeek() {const { push } = useNavigation();const { data: rawItems = EMPTY_INBOX } = useQuery(inboxListOptions(wsId));const filters = useInboxFilters(wsId);- const { activityByIssueId } = useIssueSurfaceActivity();const unreadCount = useInboxUnreadCount(wsId);const archive = useArchiveInbox();- const items = useMemo(() => {- const effective = effectiveInboxFilters(filters, {- priority: inboxPriorityFilterSupport(rawItems),- issueFields: inboxIssueFieldsSupport(rawItems),- });- return filterInboxItems(rawItems.filter((item) => !item.archived), effective, {- activeIssueIds: effective.agent ? new Set(activityByIssueId.keys()) : undefined,- });- }, [rawItems, filters, activityByIssueId]);+ const activeRows = useMemo(() => rawItems.filter((item) => !item.archived), [rawItems]);+ const effective = useMemo(+ () => effectiveInboxFilters(filters, activeInboxFilterSupport(rawItems)),+ [rawItems, filters],+ );+ const rows = useMemo(() => filterInboxItems(activeRows, effective), [activeRows, effective]);+ const filtered = inboxFilterCount(effective) > 0;+ const sections = useInboxSections(wsId, rows, activeRows, { filters: effective });const open = (params: Record<string, string>) =>push(`${p.inbox()}?${new URLSearchParams(params).toString()}`);@@ -66,13 +65,15 @@ export function InboxPeek() {title={t(($) => $.page.title)}meta={<PanelCount value={unreadCount} className="text-muted-foreground" />}/>- <InboxList- items={items}- view="inbox"+ <InboxSectionedList+ sections={sections}selectedKey=""+ filtered={filtered}scrollRestoration={false}onSelect={(item) => open({ issue: item.issue_id ?? item.id })}+ onSelectIssue={(issueId) => open({ issue: issueId })}onAction={(id) => archive.mutate(id)}+ emptyLabel={filtered ? t(($) => $.filters.empty) : undefined}/></>);diff --git a/packages/views/layout/panels/views-section.tsx b/packages/views/layout/panels/views-section.tsxindex 326ff0d9b2..46de33c4da 100644--- a/packages/views/layout/panels/views-section.tsx+++ b/packages/views/layout/panels/views-section.tsx@@ -7,7 +7,7 @@ import { DndContext, PointerSensor, closestCenter, useSensor, useSensors, type Dimport { SortableContext, arrayMove, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";import { CSS } from "@dnd-kit/utilities";-import { Bot, CircleUser, Copy, EyeOff, Filter, Layers, Link2, ListTodo, MoreHorizontal, Pencil, Plus, Trash2 } from "@multica/ui/icons";+import { CircleUser, Copy, EyeOff, Filter, Layers, Link2, ListTodo, MoreHorizontal, Pencil, Plus, Trash2 } from "@multica/ui/icons";import { cn } from "@multica/ui/lib/utils";import { IconButton } from "@multica/ui/components/common/icon-button";import {@@ -54,11 +54,9 @@ import {type SidebarViewItem,} from "@multica/core/issue-views/sidebar-views";import { issueViewTarget } from "@multica/core/issue-views/view-target";-import { UNREAD_VIEW, UNREAD_VIEW_ID } from "@multica/core/issue-views/unread-view";import type { IssueViewActions } from "../../issue-views/use-view-actions";import { DeleteViewDialog } from "../../issue-views/delete-view-dialog";import { ViewNameInput } from "../../issue-views/view-name-input";-import { UnreadViewIcon } from "../../issue-views/unread-view-icon";import { useBuiltinViewNavigation } from "../../issue-views/builtin-views";import { useNavigation } from "../../navigation";import { shouldOpenRowMenu, useRowMenu } from "../../common/point-menu";@@ -92,7 +90,7 @@ interface ViewsSectionProps {/** The sidebar source of a starred view's issue list. */export function sidebarViewItemSource(item: SidebarViewItem): string {if (item.kind === "view") return viewSidebarSource(item.view.id);- return item.key === "unread" ? viewSidebarSource(UNREAD_VIEW_ID) : builtinSidebarSource(item.key);+ return builtinSidebarSource(item.key);}/**@@ -181,15 +179,6 @@ export function ViewsSection({onDelete={setDeleteTarget}drag={drag}/>- ) : item.key === "unread" ? (- <UnreadViewRow- wsId={wsId}- pathname={pathname}- plainRowsLit={plainRowsLit}- activeIssueId={litSource === sidebarViewItemSource(item) ? activeIssueId : null}- actions={actions}- drag={drag}- />) : (<BuiltinViewRowwsId={wsId}@@ -296,11 +285,8 @@ function RowMenu({);}-type ScopeBuiltinViewKey = Exclude<BuiltinViewKey, "unread">;--const BUILTIN_ICON: Record<ScopeBuiltinViewKey, React.ReactNode> = {+const BUILTIN_ICON: Record<BuiltinViewKey, React.ReactNode> = {my_issues: <CircleUser className="size-4 shrink-0" />,- my_agents: <Bot className="size-4 shrink-0" />,all_issues: <ListTodo className="size-4 shrink-0" />,};@@ -315,7 +301,7 @@ function BuiltinViewRow({drag,}: {wsId: string;- builtin: ScopeBuiltinViewKey;+ builtin: BuiltinViewKey;pathname: string;plainRowsLit: boolean;issueInAllIssues: boolean;@@ -339,18 +325,14 @@ function BuiltinViewRow({const onMyIssues = pathname === p.myIssues();const href = builtinNav.hrefFor(builtin);const label =- builtin === "my_issues"- ? t(($) => $.nav.my_issues)- : builtin === "my_agents"- ? t(($) => $.panels.work.my_agents)- : t(($) => $.panels.work.all_issues);+ builtin === "my_issues" ? t(($) => $.nav.my_issues) : t(($) => $.panels.work.all_issues);const active =plainRowsLit &&(builtin === "all_issues"? pathname === p.issues()? activeWorkspaceView === null: issueInAllIssues && isPathWithin(pathname, p.issues())- : onMyIssues && activeMyView === null && (builtin === "my_agents") === isMyAgentsSearch(searchParams));+ : onMyIssues && activeMyView === null && !isMyAgentsSearch(searchParams));const source = builtinSidebarSource(builtin);const expanded = useSidebarTreeStore((s) => s.expanded.includes(source));@@ -419,106 +401,6 @@ function BuiltinViewRow({* The built-in Unread view, once the user stars it. The row stays when* nothing is unread; only the count goes.*/-function UnreadViewRow({- wsId,- pathname,- plainRowsLit,- activeIssueId,- actions,- drag,-}: {- wsId: string;- pathname: string;- plainRowsLit: boolean;- activeIssueId: string | null;- actions: IssueViewActions;- drag: DragBindings;-}) {- const { t } = useT("layout");- const p = useWorkspacePaths();- const listId = useId();- const linkRef = useRef<HTMLAnchorElement>(null);- const rowMenu = useRowMenu();- const target = issueViewTarget(wsId, UNREAD_VIEW, p);- const open = useActiveIssueViewStore(- (s) => pathname === target.path && s.active[target.containerKey] === UNREAD_VIEW_ID,- );- const setActive = useActiveIssueViewStore((s) => s.setActive);- const source = viewSidebarSource(UNREAD_VIEW_ID);- const expanded = useSidebarTreeStore((s) => s.expanded.includes(source));- const setExpanded = useSidebarTreeStore((s) => s.setExpanded);- const unread = useIssueUnreadIds(wsId);- const unreadDependency = filterDependencyState(true, [unread]);- const count = unread.data?.length ?? 0;- const request = unreadDependency.unresolved- ? undefined- : viewSidebarRequest(UNREAD_VIEW, todayDateOnly(), unread.data);- const prefetch = usePrefetch(wsId, source, request);- const label = t(($) => $.panels.work.unread);-- return (- <>- <TreeRow- ref={linkRef}- rowRef={drag.rowRef}- {...drag.listeners}- href={target.href}- label={label}- icon={<UnreadViewIcon />}- active={plainRowsLit && open}- expanded={expanded}- onExpandedChange={(next) => setExpanded(source, next)}- listId={listId}- toggleLabel={t(($) => $.panels.work.project_issues, { name: label })}- onPrefetch={prefetch}- onContextMenu={(event) => {- if (shouldOpenRowMenu(event)) rowMenu.openAtPointer(event);- }}- onNavigateInPlace={() => setActive(target.containerKey, UNREAD_VIEW_ID)}- trailing={- // The menu button takes the count's place, so the row never reflows.- <span className="relative flex h-5 min-w-5 items-center justify-end">- <PanelCount- value={count}- className="font-medium text-brand transition-opacity group-focus-within/row:opacity-0 group-hover/row:opacity-0 group-has-[[data-popup-open]]/row:opacity-0 [@media(pointer:coarse)]:opacity-0"- />- <RowMenu- label={t(($) => $.panels.work.view_actions, { name: label })}- state={rowMenu}- className="absolute right-0"- >- <DropdownMenuItem onClick={() => actions.copyLink(target.href)}>- <Link2 className="size-3.5" />- {t(($) => $.panels.work.view_copy_link)}- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem onClick={() => actions.sidebar.unstar(builtinViewItemId("unread"))}>- <EyeOff className="size-3.5" />- {t(($) => $.panels.work.view_remove)}- </DropdownMenuItem>- </RowMenu>- </span>- }- />- {expanded && (- <SidebarIssueList- id={listId}- wsId={wsId}- source={source}- params={request}- paramsError={unreadDependency.error}- onRetry={unreadDependency.retry}- activeIssueId={activeIssueId}- onCollapse={() => {- setExpanded(source, false);- linkRef.current?.focus();- }}- />- )}- </>- );-}-function SavedViewRow({wsId,item,diff --git a/packages/views/layout/panels/views-section.unread.test.tsx b/packages/views/layout/panels/views-section.unread.test.tsxindex f7a11414d7..b1e690f54d 100644--- a/packages/views/layout/panels/views-section.unread.test.tsx+++ b/packages/views/layout/panels/views-section.unread.test.tsx@@ -6,8 +6,7 @@ import { setApiInstance } from "@multica/core/api";import type { ApiClient } from "@multica/core/api/client";import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-store";import { builtinSidebarSource, viewSidebarSource } from "@multica/core/issues/sidebar-list";-import { issueUnreadOptions } from "@multica/core/issues/unread";-import { issueViewContainerKey, useActiveIssueViewStore } from "@multica/core/issue-views/active-view-store";+import { useActiveIssueViewStore } from "@multica/core/issue-views/active-view-store";import { UNREAD_VIEW_ID } from "@multica/core/issue-views/unread-view";import { renderWithI18n } from "../../test/i18n";import { NavigationProvider, type NavigationAdapter } from "../../navigation";@@ -188,7 +187,7 @@ const mark = (issueId: string) => ({created_at: "2026-01-01T00:00:00Z",});-describe("ViewsSection built-in Unread view", () => {+describe("ViewsSection without a built-in Unread view", () => {beforeEach(() => {actions.sidebar.items = [{ id: "builtin:all_issues", kind: "builtin", key: "all_issues" },@@ -197,61 +196,13 @@ describe("ViewsSection built-in Unread view", () => {useSidebarTreeStore.setState({ viewsCollapsed: false, expanded: [] });});- it("is not in the sidebar until starred, even with unread issues", async () => {+ it("has no Unread row of its own, even with unread issues", async () => {listIssueUnread.mockResolvedValue([mark("a"), mark("b")]);renderSection();await waitFor(() => expect(listIssueUnread).toHaveBeenCalled());await screen.findByRole("link", { name: "All issues" });expect(screen.queryByRole("link", { name: /^Unread/ })).toBeNull();});-- describe("once starred", () => {- beforeEach(() => {- actions.sidebar.items = [...actions.sidebar.items, { id: "builtin:unread", kind: "builtin", key: "unread" }];- });-- it("sits where it was starred, with the unread count", async () => {- listIssueUnread.mockResolvedValue([mark("a"), mark("b")]);- renderSection();- const link = await screen.findByRole("link", { name: /^Unread/ });- expect(link).toHaveAttribute("href", "/acme/issues?view=unread");- await waitFor(() => expect(link.closest("li")).toHaveTextContent(/^Unread2/));- const names = screen.getAllByRole("link").map((l) => l.textContent);- expect(names.slice(0, 3)).toEqual(["All issues", "Mine unread", "Unread"]);- });-- it("stays when the count reaches 0", async () => {- listIssueUnread.mockResolvedValue([mark("a")]);- const { qc } = renderSection({ activeIssueId: "a" });- const link = await screen.findByRole("link", { name: /^Unread/ });- await waitFor(() => expect(link.closest("li")).toHaveTextContent(/^Unread1/));-- qc.setQueryData(issueUnreadOptions("ws-1").queryKey, []);- await waitFor(() => expect(link.closest("li")).toHaveTextContent(/^Unread$/));- expect(screen.getByRole("link", { name: /^Unread/ })).toBe(link);- });-- it("lights while its page is open", async () => {- listIssueUnread.mockResolvedValue([]);- useActiveIssueViewStore- .getState()- .setActive(issueViewContainerKey("ws-1", { scope_type: "workspace" }), UNREAD_VIEW_ID);- renderSection();- const link = await screen.findByRole("link", { name: /^Unread/ });- expect(link).toHaveAttribute("aria-current", "page");- expect(screen.getByRole("link", { name: /^All issues/ })).not.toHaveAttribute("aria-current");- });-- it("is removed from the sidebar from its row menu", async () => {- listIssueUnread.mockResolvedValue([]);- renderSection();- const link = await screen.findByRole("link", { name: /^Unread/ });-- fireEvent.contextMenu(link);- fireEvent.click(await screen.findByRole("menuitem", { name: "Remove from sidebar" }));- expect(actions.sidebar.unstar).toHaveBeenCalledWith("builtin:unread");- });- });});describe("ViewsSection built-in All issues view", () => {diff --git a/packages/views/layout/panels/work-panel.test.tsx b/packages/views/layout/panels/work-panel.test.tsxindex 0e034e6ffc..02b0d4df61 100644--- a/packages/views/layout/panels/work-panel.test.tsx+++ b/packages/views/layout/panels/work-panel.test.tsx@@ -491,58 +491,3 @@ describe("WorkPanel and the open issue's project", () => {await waitFor(() => expect(useSidebarTreeStore.getState().locate).toBeNull());});});--describe("WorkPanel starred Unread view after its last issue is read", () => {- const unreadRow = (scope: Pick<typeof screen, "queryByRole"> = screen) =>- scope.queryByRole("link", { name: /^Unread/ });- const defaultItems = actions.sidebar.items;-- beforeEach(() => {- actions.sidebar.items = [...defaultItems, { id: "builtin:unread", kind: "builtin", key: "unread" }];- return () => {- actions.sidebar.items = defaultItems;- };- });-- async function openAndReadLastUnread() {- useSidebarTreeStore.setState({ expanded: ["view:unread"] });- apiMock.listIssueTableRows.mockResolvedValue({ rows: [{ issue: ISSUE }], total: 1, next_cursor: null });- const qc = renderPanel("/acme/my-issues", [], [], [ISSUE.id]);- // The unread dot's label is part of the link's name until it is read.- fireEvent.click(await screen.findByRole("link", { name: new RegExp(`^${ISSUE.title}`) }));- apiMock.listIssueTableRows.mockResolvedValue({ rows: [], total: 0, next_cursor: null });- await act(async () => {- qc.setQueryData(issueDetailOptions("ws-1", ISSUE.id).queryKey, ISSUE);- qc.setQueryData(issueUnreadOptions("ws-1").queryKey, []);- });- await waitFor(() => expect(unreadRow()?.closest("li")).toHaveTextContent(/^Unread/));- expect(unreadRow()?.closest("li")).not.toHaveTextContent("Unread1");- expect(issueRow()).toHaveAttribute("aria-current", "page");- return qc;- }-- it("keeps the row and the open issue in the hover peek", async () => {- await openAndReadLastUnread();- fireEvent.click(screen.getByRole("button", { name: "Open peek" }));- const peek = within(screen.getByTestId("peek"));- expect(unreadRow(peek)).not.toBeNull();- expect(peek.getByRole("link", { name: ISSUE.title })).toHaveAttribute("aria-current", "page");- });-- it("keeps the row and the open issue when the compact sheet reopens", async () => {- await openAndReadLastUnread();- fireEvent.click(screen.getByRole("button", { name: "Toggle sheet" }));- fireEvent.click(screen.getByRole("button", { name: "Toggle sheet" }));- expect(unreadRow()).not.toBeNull();- expect(issueRow()).toHaveAttribute("aria-current", "page");- });-- it("keeps the row but drops the read issue once it is no longer the page", async () => {- await openAndReadLastUnread();- fireEvent.click(screen.getByRole("button", { name: "Visit inbox" }));- fireEvent.click(screen.getByRole("button", { name: "Return to issue" }));- await screen.findByRole("link", { name: "All issues" });- expect(unreadRow()).not.toBeNull();- await waitFor(() => expect(screen.queryByRole("link", { name: ISSUE.title })).toBeNull());- });-});diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.jsonindex f39e51e7e6..288272e5fd 100644--- a/packages/views/locales/en/inbox.json+++ b/packages/views/locales/en/inbox.json@@ -3,12 +3,6 @@"title": "Inbox","back": "Inbox"},- "menu": {- "mark_all_read": "Mark all as read",- "archive_all": "Archive all",- "archive_all_read": "Archive all read",- "archive_completed": "Archive completed"- },"filters": {"tooltip": "Filter inbox","active_count_one": "{{count}} active filter",@@ -33,8 +27,7 @@"type_system": "System","received_today": "Today","received_last_7_days": "Last 7 days",- "received_last_30_days": "Last 30 days",- "agent_idle": "Idle"+ "received_last_30_days": "Last 30 days"},"context_menu": {"mark_read": "Mark as read",@@ -42,7 +35,12 @@"archive": "Archive","unarchive": "Unarchive","open_in_new_tab": "Open in new tab",- "delete": "Delete"+ "delete": "Delete",+ "snooze_in_one_hour": "Snooze for 1 hour",+ "snooze_later_today": "Snooze until later today",+ "snooze_tomorrow": "Snooze until tomorrow",+ "snooze_next_week": "Snooze until next Monday",+ "unsnooze": "Unsnooze"},"list": {"loading_selection": "Loading notification…",@@ -65,14 +63,15 @@},"detail": {"select_prompt": "Select a notification to view details",- "empty": "Your inbox is empty","original_input": "Original input","retry_with_context": "Retry with context","edit_advanced": "Edit as advanced form","autopilot_quota_exceeded_body": "This workspace has reached its limit of {{limit}} autopilot runs for the current period. Further autopilot runs will not start until the allowance resets {{resetAt}}.","autopilot_quota_upgrade": "View upgrade options","archive": "Archive",- "unarchive": "Unarchive"+ "unarchive": "Unarchive",+ "nothing_needs_you": "Nothing needs you",+ "nothing_needs_you_hint": "Issues appear on the left when an agent hands back a result or someone mentions you."},"types": {"issue_assigned": "Assigned",@@ -89,6 +88,7 @@"review_requested": "Review requested","task_completed": "Run completed","task_failed": "Run failed",+ "task_cancelled": "Run cancelled","agent_blocked": "Agent blocked","agent_completed": "Agent completed","reaction_added": "Reacted",@@ -122,7 +122,8 @@"source_context_retry_started": "Retry started with the original context","archived": "Notification archived","unarchived": "Notification restored",- "deleted": "Notification deleted"+ "deleted": "Notification deleted",+ "snoozed": "Snoozed until {{time}}"},"errors": {"archived_lookup_failed": "Failed to load the linked notification",@@ -132,20 +133,53 @@"mark_unread_failed": "Failed to mark as unread","archive_failed": "Failed to archive","mark_done_failed": "Failed to mark as done",- "mark_all_read_failed": "Failed to mark all as read",- "archive_all_failed": "Failed to archive all",- "archive_all_read_failed": "Failed to archive read items",- "archive_completed_failed": "Failed to archive completed","unarchive_failed": "Failed to unarchive","archived_load_failed": "Failed to load archived notifications","filters_load_failed": "Could not load filters",- "delete_failed": "Failed to delete notification. Try again."+ "delete_failed": "Failed to delete notification. Try again.",+ "snooze_failed": "Failed to snooze",+ "unsnooze_failed": "Failed to unsnooze"},"delete_dialog": {"title": "Delete notification?","description": "This permanently deletes this notification. Related issues and runs are kept.","issue_description": "This permanently deletes the notifications for this issue in this view. The issue and its runs are kept.",- "cancel": "Cancel",- "active_issue_description": "This permanently deletes the active notifications for this issue. Previously archived notifications remain and will be visible again in Archived. The issue and its runs are kept."+ "cancel": "Cancel"+ },+ "sections": {+ "needs_you": "Needs you",+ "working": "Working",+ "updates": "Updates",+ "snoozed": "Snoozed",+ "clear_updates": "Clear",+ "queued": "Queued",+ "caught_up": "All caught up",+ "still_working_one": "{{count}} agent is still working. Results come back here.",+ "still_working_other": "{{count}} agents are still working. Results come back here."+ },+ "reasons": {+ "review": "Ready for review",+ "question": "Waiting for your answer",+ "mention": "Mentioned you",+ "failed": "Run failed",+ "cancelled": "Run cancelled",+ "assigned": "Assigned to you",+ "comment": "New comment",+ "finished": "Run finished",+ "stopped_by_you": "You stopped this run",+ "stopped_by": "{{name}} stopped this run",+ "stopped_by_system": "Stopped by the system"+ },+ "snooze": {+ "action": "Snooze",+ "unsnooze": "Unsnooze",+ "in_one_hour": "In 1 hour",+ "later_today": "Later today",+ "tomorrow": "Tomorrow",+ "next_week": "Next Monday",+ "pick_time": "Pick a time...",+ "hint": "Comes back early if something new needs you, such as a mention or a failed run.",+ "custom_title": "Snooze until",+ "custom_invalid": "Choose a time in the future, within a year."}}diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.jsonindex 71b98a0705..78d2edb9d7 100644--- a/packages/views/locales/en/layout.json+++ b/packages/views/locales/en/layout.json@@ -108,8 +108,6 @@"copy_link": "Copy link","link_copied": "Link copied","workspace_settings": "Workspace settings",- "mark_all_read": "Mark all as read",- "mark_all_read_failed": "Couldn't mark all as read","reset_order": "Reset to default order","copy_workspace_link": "Copy workspace link","workspace_meta_one": "{{slug}} · {{count}} member",@@ -122,9 +120,7 @@},"panels": {"work": {- "my_agents": "My agents' work","all_issues": "All issues",- "unread": "Unread","views": "Views","new_project": "New project","new_issue_in_project": "New issue in {{name}}",diff --git a/packages/views/locales/en/search.json b/packages/views/locales/en/search.jsonindex 7f37331a67..f581ffcd21 100644--- a/packages/views/locales/en/search.json+++ b/packages/views/locales/en/search.json@@ -88,9 +88,7 @@},"inbox": {"archive": "Archive",- "mark_unread": "Mark as unread",- "mark_all_read": "Mark all inbox items as read",- "archive_all_read": "Archive all read inbox items"+ "mark_unread": "Mark as unread"},"chat": {"link_project": "Link to project...",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 1d3ffeaf95..92c207d86f 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -432,6 +432,10 @@"label": "Archive notification","description": "Archive the open inbox notification, or restore it while reading the archive."},+ "snoozeInboxItem": {+ "label": "Snooze notification",+ "description": "Choose when the open inbox notification comes back."+ },"send": {"label": "Send","description": "Also submits new issues."@@ -831,25 +835,48 @@"toast_profile_failed": "Failed to update profile"},"notifications": {- "title": "Inbox Notifications",- "description": "Muted events remain visible on the issue.","toast_failed": "Failed to update notification settings",- "groups": {+ "needs_you": {+ "title": "Needs you",+ "description": "Anything addressed to you stays under Needs you in the Inbox until you handle or archive it. These can't be turned off.",+ "always_on": "Always on",+ "mentions": {+ "label": "Mentions",+ "description": "When someone @mentions you"+ },"assignments": {"label": "Assignments",- "description": "When you are assigned or unassigned from an issue"+ "description": "When an issue is assigned to you"},- "status_changes": {- "label": "Status changes",- "description": "When an issue you follow changes status (e.g. todo, in progress, done)"+ "runs": {+ "label": "Runs you started",+ "description": "When the agent finishes, fails, asks you something, or the run is cancelled"+ },+ "your_issues": {+ "label": "Issues you created or are assigned",+ "description": "New comments, or a status that waits on you"+ }+ },+ "updates": {+ "title": "Updates",+ "description": "Activity on issues you follow. Not counted in the badge, and gone from the Inbox once read. What you turn off stays visible on the issue."+ },+ "groups": {+ "mentions": {+ "label": "@all and @squad",+ "description": "Group mentions also go to Needs you. When off, they go to Updates."},"comments": {"label": "Comments","description": "New comments on issues you follow"},- "mentions": {- "label": "Mentions",- "description": "When someone @mentions you, including @all and @squad"+ "status_changes": {+ "label": "Status changes",+ "description": "When an issue you follow changes status (e.g. todo, in progress, done)"+ },+ "assignments": {+ "label": "Assignment changes",+ "description": "When you are unassigned, or an issue you follow is reassigned"},"updates": {"label": "Priority & Due date",@@ -860,8 +887,8 @@"description": "When an issue is created in a project you subscribe to"},"agent_activity": {- "label": "Agent activity",- "description": "When an agent run fails"+ "label": "Agent runs",+ "description": "When an agent run fails or gets blocked on an issue you follow"},"chat_replies": {"label": "Include chat replies"@@ -869,7 +896,8 @@},"system": {"title": "System Notifications",- "label": "Show system notifications when Multica is in the background"+ "label": "Show system notifications when Multica is in the background",+ "description": "From the Inbox, only Needs you shows a banner. Updates never do."},"browser": {"label": "Browser notifications",diff --git a/packages/views/locales/es/inbox.json b/packages/views/locales/es/inbox.jsonindex 08772f113f..178d53c4bb 100644--- a/packages/views/locales/es/inbox.json+++ b/packages/views/locales/es/inbox.json@@ -3,12 +3,6 @@"title": "Bandeja de entrada","back": "Bandeja de entrada"},- "menu": {- "mark_all_read": "Marcar todo como leído",- "archive_all": "Archivar todo",- "archive_all_read": "Archivar todo lo leído",- "archive_completed": "Archivar lo completado"- },"filters": {"tooltip": "Filtrar bandeja","active_count_one": "{{count}} filtro activo",@@ -33,8 +27,7 @@"type_system": "Sistema","received_today": "Hoy","received_last_7_days": "Últimos 7 días",- "received_last_30_days": "Últimos 30 días",- "agent_idle": "Inactivo"+ "received_last_30_days": "Últimos 30 días"},"context_menu": {"mark_read": "Marcar como leído",@@ -42,7 +35,12 @@"archive": "Archivar","unarchive": "Desarchivar","open_in_new_tab": "Abrir en una pestaña nueva",- "delete": "Eliminar"+ "delete": "Eliminar",+ "snooze_in_one_hour": "Posponer 1 hora",+ "snooze_later_today": "Posponer hasta más tarde hoy",+ "snooze_tomorrow": "Posponer hasta mañana",+ "snooze_next_week": "Posponer hasta el próximo lunes",+ "unsnooze": "Cancelar posposición"},"list": {"loading_selection": "Cargando notificación…",@@ -65,14 +63,15 @@},"detail": {"select_prompt": "Selecciona una notificación para ver los detalles",- "empty": "Tu bandeja de entrada está vacía","original_input": "Entrada original","retry_with_context": "Reintentar con contexto","edit_advanced": "Editar como formulario avanzado","autopilot_quota_exceeded_body": "Este espacio de trabajo ha alcanzado su límite de {{limit}} ejecuciones de automatizaciones para el periodo actual. No se iniciarán más ejecuciones de automatizaciones hasta que se reinicie la cuota {{resetAt}}.","autopilot_quota_upgrade": "Ver opciones de mejora del plan","archive": "Archivar",- "unarchive": "Desarchivar"+ "unarchive": "Desarchivar",+ "nothing_needs_you": "Nada pendiente de ti",+ "nothing_needs_you_hint": "Las tareas aparecen a la izquierda cuando un agente entrega un resultado o alguien te menciona."},"types": {"issue_assigned": "Asignada",@@ -89,6 +88,7 @@"review_requested": "Revisión solicitada","task_completed": "Ejecución completada","task_failed": "Ejecución fallida",+ "task_cancelled": "Ejecución cancelada","agent_blocked": "Agente bloqueado","agent_completed": "Agente completado","reaction_added": "Reaccionó",@@ -122,7 +122,8 @@"source_context_retry_started": "Reintento iniciado con el contexto original","archived": "Notificación archivada","unarchived": "Notificación restaurada",- "deleted": "Notificación eliminada"+ "deleted": "Notificación eliminada",+ "snoozed": "Pospuesta hasta {{time}}"},"errors": {"archived_lookup_failed": "No se ha podido cargar la notificación enlazada",@@ -132,20 +133,53 @@"mark_unread_failed": "No se ha podido marcar como no leído","archive_failed": "No se ha podido archivar","mark_done_failed": "No se ha podido marcar como hecho",- "mark_all_read_failed": "No se ha podido marcar todo como leído",- "archive_all_failed": "No se ha podido archivar todo",- "archive_all_read_failed": "No se ha podido archivar los elementos leídos",- "archive_completed_failed": "No se ha podido archivar lo completado","unarchive_failed": "No se ha podido desarchivar","archived_load_failed": "No se han podido cargar las notificaciones archivadas","filters_load_failed": "No se han podido cargar los filtros",- "delete_failed": "No se pudo eliminar la notificación. Inténtalo de nuevo."+ "delete_failed": "No se pudo eliminar la notificación. Inténtalo de nuevo.",+ "snooze_failed": "No se pudo posponer",+ "unsnooze_failed": "No se pudo cancelar la posposición"},"delete_dialog": {"title": "¿Eliminar notificación?","description": "Esta notificación se eliminará permanentemente. Las tareas y ejecuciones relacionadas se conservarán.","issue_description": "Las notificaciones de esta tarea en esta vista se eliminarán permanentemente. La tarea y sus ejecuciones se conservarán.",- "cancel": "Cancelar",- "active_issue_description": "Las notificaciones activas de esta tarea se eliminarán permanentemente. Las notificaciones archivadas anteriormente se conservarán y volverán a aparecer en Archivadas. La tarea y sus ejecuciones se conservarán."+ "cancel": "Cancelar"+ },+ "sections": {+ "needs_you": "Pendientes de ti",+ "working": "En curso",+ "updates": "Novedades",+ "snoozed": "Pospuestas",+ "clear_updates": "Vaciar",+ "queued": "En cola",+ "caught_up": "Todo al día",+ "still_working_one": "{{count}} agente sigue trabajando. Los resultados volverán aquí.",+ "still_working_other": "{{count}} agentes siguen trabajando. Los resultados volverán aquí."+ },+ "reasons": {+ "review": "Lista para revisar",+ "question": "Espera tu respuesta",+ "mention": "Te mencionó",+ "failed": "Ejecución fallida",+ "cancelled": "Ejecución cancelada",+ "assigned": "Asignada a ti",+ "comment": "Nuevo comentario",+ "finished": "Ejecución terminada",+ "stopped_by_you": "Detuviste esta ejecución",+ "stopped_by": "{{name}} detuvo esta ejecución",+ "stopped_by_system": "Detenida por el sistema"+ },+ "snooze": {+ "action": "Posponer",+ "unsnooze": "Cancelar posposición",+ "in_one_hour": "En 1 hora",+ "later_today": "Más tarde hoy",+ "tomorrow": "Mañana",+ "next_week": "El próximo lunes",+ "pick_time": "Elegir fecha y hora...",+ "hint": "Vuelve antes si algo nuevo requiere tu atención, como una mención o una ejecución fallida.",+ "custom_title": "Posponer hasta",+ "custom_invalid": "Elige una fecha futura, dentro de un año."}}diff --git a/packages/views/locales/es/layout.json b/packages/views/locales/es/layout.jsonindex ff3ffb46af..d2e9fb058f 100644--- a/packages/views/locales/es/layout.json+++ b/packages/views/locales/es/layout.json@@ -108,8 +108,6 @@"copy_link": "Copiar enlace","link_copied": "Enlace copiado","workspace_settings": "Ajustes del espacio de trabajo",- "mark_all_read": "Marcar todo como leído",- "mark_all_read_failed": "No se pudo marcar todo como leído","reset_order": "Restablecer el orden predeterminado","copy_workspace_link": "Copiar enlace del espacio de trabajo","workspace_meta_one": "{{slug}} · {{count}} miembro",@@ -122,9 +120,7 @@},"panels": {"work": {- "my_agents": "Trabajo de mis agentes","all_issues": "Todas las tareas",- "unread": "Sin leer","views": "Vistas","new_project": "Nuevo proyecto","new_issue_in_project": "Nueva tarea en {{name}}",diff --git a/packages/views/locales/es/search.json b/packages/views/locales/es/search.jsonindex 99245ccc20..118bec420a 100644--- a/packages/views/locales/es/search.json+++ b/packages/views/locales/es/search.json@@ -110,9 +110,7 @@},"inbox": {"archive": "Archivar",- "mark_unread": "Marcar como no leído",- "mark_all_read": "Marcar toda la bandeja de entrada como leída",- "archive_all_read": "Archivar todos los elementos leídos de la bandeja de entrada"+ "mark_unread": "Marcar como no leído"},"chat": {"link_project": "Vincular a proyecto...",diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex 6ae857143f..bac8590c10 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -432,6 +432,10 @@"label": "Archivar notificación","description": "Archiva la notificación de la bandeja abierta, o restaúrala mientras lees el archivo."},+ "snoozeInboxItem": {+ "label": "Posponer notificación",+ "description": "Elige cuándo vuelve la notificación abierta de la bandeja de entrada."+ },"send": {"label": "Enviar","description": "También envía nuevas tareas."@@ -831,25 +835,48 @@"toast_profile_failed": "Error al actualizar el perfil"},"notifications": {- "title": "Notificaciones de la bandeja",- "description": "Los eventos silenciados siguen visibles en la tarea.","toast_failed": "Error al actualizar la configuración de notificaciones",- "groups": {+ "needs_you": {+ "title": "Pendientes de ti",+ "description": "Lo que va dirigido a ti permanece en «Pendientes de ti» de la bandeja de entrada hasta que lo atiendas o lo archives. No se puede desactivar.",+ "always_on": "Siempre activado",+ "mentions": {+ "label": "Menciones",+ "description": "Cuando alguien te @menciona"+ },"assignments": {"label": "Asignaciones",- "description": "Cuando te asignan o te quitan de una tarea"+ "description": "Cuando te asignan una tarea"},- "status_changes": {- "label": "Cambios de estado",- "description": "Cuando una tarea que sigues cambia de estado (p. ej. pendiente, en curso, completado)"+ "runs": {+ "label": "Ejecuciones que iniciaste",+ "description": "Cuando el agente termina, falla, te pregunta algo o se cancela la ejecución"+ },+ "your_issues": {+ "label": "Tareas que creaste o tienes asignadas",+ "description": "Comentarios nuevos, o un estado que espera tu acción"+ }+ },+ "updates": {+ "title": "Novedades",+ "description": "Actividad en las tareas que sigues. No cuenta en la insignia y desaparece de la bandeja de entrada al leerla. Lo que desactives sigue visible en la tarea."+ },+ "groups": {+ "mentions": {+ "label": "@all y @squad",+ "description": "Las menciones de grupo también van a «Pendientes de ti». Si se desactiva, van a «Novedades»."},"comments": {"label": "Comentarios","description": "Comentarios nuevos en tareas que sigues"},- "mentions": {- "label": "Menciones",- "description": "Cuando alguien te @menciona, incluidos @all y @squad"+ "status_changes": {+ "label": "Cambios de estado",+ "description": "Cuando una tarea que sigues cambia de estado (p. ej. pendiente, en curso, completado)"+ },+ "assignments": {+ "label": "Cambios de asignación",+ "description": "Cuando te quitan de una tarea, o una tarea que sigues cambia de responsable"},"updates": {"label": "Prioridad y fecha de entrega",@@ -860,8 +887,8 @@"description": "Cuando se crea una tarea en un proyecto al que estás suscrito"},"agent_activity": {- "label": "Actividad de agentes",- "description": "Cuando falla una ejecución de agente"+ "label": "Ejecuciones de agentes",+ "description": "Cuando la ejecución de un agente falla o se bloquea en una tarea que sigues"},"chat_replies": {"label": "Incluir respuestas del chat"@@ -869,7 +896,8 @@},"system": {"title": "Notificaciones del sistema",- "label": "Mostrar notificaciones del sistema"+ "label": "Mostrar notificaciones del sistema",+ "description": "De la bandeja de entrada, solo «Pendientes de ti» muestra un aviso. Las novedades, nunca."},"browser": {"label": "Notificaciones del navegador",diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.jsonindex 9b888fe750..019154453e 100644--- a/packages/views/locales/fr/inbox.json+++ b/packages/views/locales/fr/inbox.json@@ -3,12 +3,6 @@"title": "Boîte de réception","back": "Boîte de réception"},- "menu": {- "mark_all_read": "Tout marquer comme lu",- "archive_all": "Tout archiver",- "archive_all_read": "Archiver tout ce qui est lu",- "archive_completed": "Archiver les éléments terminés"- },"filters": {"tooltip": "Filtrer la boîte de réception","active_count_one": "{{count}} filtre actif",@@ -33,8 +27,7 @@"type_system": "Système","received_today": "Aujourd'hui","received_last_7_days": "7 derniers jours",- "received_last_30_days": "30 derniers jours",- "agent_idle": "Inactif"+ "received_last_30_days": "30 derniers jours"},"context_menu": {"mark_read": "Marquer comme lu",@@ -42,7 +35,12 @@"archive": "Archiver","unarchive": "Désarchiver","open_in_new_tab": "Ouvrir dans un nouvel onglet",- "delete": "Supprimer"+ "delete": "Supprimer",+ "snooze_in_one_hour": "Reporter d'1 heure",+ "snooze_later_today": "Reporter à plus tard aujourd'hui",+ "snooze_tomorrow": "Reporter à demain",+ "snooze_next_week": "Reporter à lundi prochain",+ "unsnooze": "Annuler le report"},"list": {"loading_selection": "Chargement de la notification…",@@ -65,14 +63,15 @@},"detail": {"select_prompt": "Sélectionnez une notification pour afficher les détails",- "empty": "Votre boîte de réception est vide","original_input": "Saisie d'origine","retry_with_context": "Réessayer avec le contexte","edit_advanced": "Modifier en mode avancé","autopilot_quota_exceeded_body": "Cet espace de travail a atteint sa limite de {{limit}} exécutions d'automatisation pour la période actuelle. Les prochaines exécutions d'automatisation ne démarreront qu'après la réinitialisation du quota {{resetAt}}.","autopilot_quota_upgrade": "Voir les options de mise à niveau","archive": "Archiver",- "unarchive": "Désarchiver"+ "unarchive": "Désarchiver",+ "nothing_needs_you": "Rien à traiter",+ "nothing_needs_you_hint": "Les tâches apparaissent à gauche lorsqu'un agent rend un résultat ou que quelqu'un vous mentionne."},"types": {"issue_assigned": "Assigné",@@ -89,6 +88,7 @@"review_requested": "Relecture demandée","task_completed": "Exécution terminée","task_failed": "Exécution en échec",+ "task_cancelled": "Exécution annulée","agent_blocked": "Agent bloqué","agent_completed": "Agent terminé","reaction_added": "Réaction",@@ -122,7 +122,8 @@"source_context_retry_started": "Nouvelle tentative démarrée avec le contexte d'origine","archived": "Notification archivée","unarchived": "Notification restaurée",- "deleted": "Notification supprimée"+ "deleted": "Notification supprimée",+ "snoozed": "Reportée jusqu'à {{time}}"},"errors": {"archived_lookup_failed": "Échec du chargement de la notification liée",@@ -132,20 +133,53 @@"mark_unread_failed": "Échec du marquage comme non lu","archive_failed": "Échec de l'archivage","mark_done_failed": "Échec du marquage comme traité",- "mark_all_read_failed": "Échec du marquage global comme lu",- "archive_all_failed": "Échec de l'archivage global",- "archive_all_read_failed": "Échec de l'archivage des éléments lus",- "archive_completed_failed": "Échec de l'archivage des éléments terminés","unarchive_failed": "Échec du désarchivage","archived_load_failed": "Échec du chargement des notifications archivées","filters_load_failed": "Impossible de charger les filtres",- "delete_failed": "Impossible de supprimer la notification. Réessayez."+ "delete_failed": "Impossible de supprimer la notification. Réessayez.",+ "snooze_failed": "Impossible de reporter",+ "unsnooze_failed": "Impossible d'annuler le report"},"delete_dialog": {"title": "Supprimer la notification ?","description": "Cette notification sera supprimée définitivement. Les tâches et exécutions associées seront conservées.","issue_description": "Les notifications de cette tâche dans cette vue seront supprimées définitivement. La tâche et ses exécutions seront conservées.",- "cancel": "Annuler",- "active_issue_description": "Les notifications actives de cette tâche seront supprimées définitivement. Les notifications précédemment archivées seront conservées et réapparaîtront dans les archives. La tâche et ses exécutions seront conservées."+ "cancel": "Annuler"+ },+ "sections": {+ "needs_you": "À traiter",+ "working": "En cours",+ "updates": "Mises à jour",+ "snoozed": "Reportées",+ "clear_updates": "Effacer",+ "queued": "En file d'attente",+ "caught_up": "Tout est traité",+ "still_working_one": "{{count}} agent travaille encore. Les résultats reviendront ici.",+ "still_working_other": "{{count}} agents travaillent encore. Les résultats reviendront ici."+ },+ "reasons": {+ "review": "À valider",+ "question": "Attend votre réponse",+ "mention": "Vous mentionne",+ "failed": "Exécution en échec",+ "cancelled": "Exécution annulée",+ "assigned": "Assignée à vous",+ "comment": "Nouveau commentaire",+ "finished": "Exécution terminée",+ "stopped_by_you": "Vous avez arrêté cette exécution",+ "stopped_by": "{{name}} a arrêté cette exécution",+ "stopped_by_system": "Arrêtée par le système"+ },+ "snooze": {+ "action": "Reporter",+ "unsnooze": "Annuler le report",+ "in_one_hour": "Dans 1 heure",+ "later_today": "Plus tard aujourd'hui",+ "tomorrow": "Demain",+ "next_week": "Lundi prochain",+ "pick_time": "Choisir une date...",+ "hint": "Revient plus tôt si un nouvel élément demande votre attention, comme une mention ou une exécution en échec.",+ "custom_title": "Reporter jusqu'à",+ "custom_invalid": "Choisissez une date future, à moins d'un an."}}diff --git a/packages/views/locales/fr/layout.json b/packages/views/locales/fr/layout.jsonindex 5c1f64ce56..a101f6a8d9 100644--- a/packages/views/locales/fr/layout.json+++ b/packages/views/locales/fr/layout.json@@ -108,8 +108,6 @@"copy_link": "Copier le lien","link_copied": "Lien copié","workspace_settings": "Paramètres de l’espace de travail",- "mark_all_read": "Tout marquer comme lu",- "mark_all_read_failed": "Impossible de tout marquer comme lu","reset_order": "Rétablir l’ordre par défaut","copy_workspace_link": "Copier le lien de l’espace de travail","workspace_meta_one": "{{slug}} · {{count}} membre",@@ -122,9 +120,7 @@},"panels": {"work": {- "my_agents": "Travail de mes agents","all_issues": "Toutes les tâches",- "unread": "Non lues","views": "Vues","new_project": "Nouveau projet","new_issue_in_project": "Nouvelle tâche dans {{name}}",diff --git a/packages/views/locales/fr/search.json b/packages/views/locales/fr/search.jsonindex 43cd5ce54b..caa3035f1f 100644--- a/packages/views/locales/fr/search.json+++ b/packages/views/locales/fr/search.json@@ -88,9 +88,7 @@},"inbox": {"archive": "Archiver",- "mark_unread": "Marquer comme non lu",- "mark_all_read": "Tout marquer comme lu dans la boîte de réception",- "archive_all_read": "Archiver tous les éléments lus"+ "mark_unread": "Marquer comme non lu"},"chat": {"link_project": "Associer à un projet...",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex b9c6a95a4e..11ad64b1eb 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -432,6 +432,10 @@"label": "Archiver la notification","description": "Archiver la notification ouverte, ou la restaurer lors de la consultation des archives."},+ "snoozeInboxItem": {+ "label": "Reporter la notification",+ "description": "Choisissez quand la notification ouverte revient dans la boîte de réception."+ },"send": {"label": "Envoyer","description": "Permet aussi de créer des tâches."@@ -831,25 +835,48 @@"toast_profile_failed": "Échec de la mise à jour du profil"},"notifications": {- "title": "Notifications de la boîte de réception",- "description": "Les événements désactivés restent visibles dans la tâche.","toast_failed": "Échec de la mise à jour des réglages de notification",- "groups": {+ "needs_you": {+ "title": "À traiter",+ "description": "Ce qui vous est adressé reste dans « À traiter » de la boîte de réception jusqu'à ce que vous le traitiez ou l'archiviez. Impossible à désactiver.",+ "always_on": "Toujours activé",+ "mentions": {+ "label": "Mentions",+ "description": "Quand quelqu'un vous @mentionne"+ },"assignments": {"label": "Assignations",- "description": "Quand une tâche vous est assignée ou retirée"+ "description": "Quand une tâche vous est assignée"},- "status_changes": {- "label": "Changements de statut",- "description": "Quand une tâche que vous suivez change de statut (à faire, en cours, terminé…)"+ "runs": {+ "label": "Exécutions que vous avez lancées",+ "description": "Quand l'agent termine, échoue, vous pose une question, ou que l'exécution est annulée"+ },+ "your_issues": {+ "label": "Tâches que vous avez créées ou qui vous sont assignées",+ "description": "Nouveaux commentaires, ou statut en attente de votre action"+ }+ },+ "updates": {+ "title": "Mises à jour",+ "description": "L'activité des tâches que vous suivez. Non comptée dans le badge, et retirée de la boîte de réception une fois lue. Ce que vous désactivez reste visible sur la tâche."+ },+ "groups": {+ "mentions": {+ "label": "@all et @squad",+ "description": "Les mentions de groupe vont aussi dans « À traiter ». Désactivé, elles vont dans « Mises à jour »."},"comments": {"label": "Commentaires","description": "Nouveaux commentaires sur les tâches que vous suivez"},- "mentions": {- "label": "Mentions",- "description": "Quand quelqu'un vous @mentionne, y compris via @all et @squad"+ "status_changes": {+ "label": "Changements de statut",+ "description": "Quand une tâche que vous suivez change de statut (à faire, en cours, terminé…)"+ },+ "assignments": {+ "label": "Changements d'assignation",+ "description": "Quand une tâche ne vous est plus assignée, ou qu'une tâche que vous suivez change de responsable"},"updates": {"label": "Priorité et date d'échéance",@@ -860,8 +887,8 @@"description": "Quand une tâche est créée dans un projet auquel vous êtes abonné"},"agent_activity": {- "label": "Activité des agents",- "description": "Lorsqu'une exécution d'agent échoue"+ "label": "Exécutions d'agent",+ "description": "Quand l'exécution d'un agent échoue ou se bloque sur une tâche que vous suivez"},"chat_replies": {"label": "Inclure les réponses du chat"@@ -869,7 +896,8 @@},"system": {"title": "Notifications système",- "label": "Afficher les notifications système lorsque Multica est en arrière-plan"+ "label": "Afficher les notifications système lorsque Multica est en arrière-plan",+ "description": "Dans la boîte de réception, seul « À traiter » affiche une bannière. Les mises à jour, jamais."},"browser": {"label": "Notifications du navigateur",diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.jsonindex e2751b2d95..7dc3230924 100644--- a/packages/views/locales/ja/inbox.json+++ b/packages/views/locales/ja/inbox.json@@ -3,12 +3,6 @@"title": "インボックス","back": "インボックス"},- "menu": {- "mark_all_read": "すべて既読にする",- "archive_all": "すべてアーカイブ",- "archive_all_read": "既読の項目をすべてアーカイブ",- "archive_completed": "完了した項目をアーカイブ"- },"filters": {"tooltip": "インボックスを絞り込む","active_count_other": "{{count}} 件のフィルター",@@ -31,8 +25,7 @@"type_system": "システム","received_today": "今日","received_last_7_days": "過去 7 日間",- "received_last_30_days": "過去 30 日間",- "agent_idle": "待機中"+ "received_last_30_days": "過去 30 日間"},"context_menu": {"mark_read": "既読にする",@@ -40,7 +33,12 @@"archive": "アーカイブ","unarchive": "アーカイブ解除","open_in_new_tab": "新しいタブで開く",- "delete": "削除"+ "delete": "削除",+ "snooze_in_one_hour": "1 時間スヌーズ",+ "snooze_later_today": "今日このあとまでスヌーズ",+ "snooze_tomorrow": "明日までスヌーズ",+ "snooze_next_week": "次の月曜日までスヌーズ",+ "unsnooze": "スヌーズを解除"},"list": {"loading_selection": "通知を読み込み中…",@@ -63,14 +61,15 @@},"detail": {"select_prompt": "詳細を表示する通知を選択してください",- "empty": "インボックスは空です","original_input": "元の入力","retry_with_context": "コンテキストを保持して再試行","edit_advanced": "詳細フォームで編集","autopilot_quota_exceeded_body": "このワークスペースは現在の期間の自動化実行上限 {{limit}} 回に達しました。実行枠が {{resetAt}} にリセットされるまで、以降の自動化は開始されません。","autopilot_quota_upgrade": "アップグレード方法を見る","archive": "アーカイブ",- "unarchive": "アーカイブ解除"+ "unarchive": "アーカイブ解除",+ "nothing_needs_you": "対応が必要なタスクはありません",+ "nothing_needs_you_hint": "エージェントが結果を返したとき、またはメンションされたときに、左側に表示されます。"},"types": {"issue_assigned": "割り当て済み",@@ -87,6 +86,7 @@"review_requested": "レビューを依頼","task_completed": "実行完了","task_failed": "実行失敗",+ "task_cancelled": "実行キャンセル","agent_blocked": "エージェントがブロック","agent_completed": "エージェントが完了","reaction_added": "リアクションあり",@@ -120,7 +120,8 @@"source_context_retry_started": "元のコンテキストで再試行を開始しました","archived": "通知をアーカイブしました","unarchived": "通知を元に戻しました",- "deleted": "通知を削除しました"+ "deleted": "通知を削除しました",+ "snoozed": "{{time}} までスヌーズしました"},"errors": {"archived_lookup_failed": "リンク先の通知を読み込めませんでした",@@ -130,20 +131,52 @@"mark_unread_failed": "未読にできませんでした","archive_failed": "アーカイブできませんでした","mark_done_failed": "完了にできませんでした",- "mark_all_read_failed": "すべて既読にできませんでした",- "archive_all_failed": "すべてアーカイブできませんでした",- "archive_all_read_failed": "既読の項目をアーカイブできませんでした",- "archive_completed_failed": "完了した項目をアーカイブできませんでした","unarchive_failed": "アーカイブ解除に失敗しました","archived_load_failed": "アーカイブ済み通知を読み込めませんでした","filters_load_failed": "フィルターを読み込めませんでした",- "delete_failed": "通知を削除できませんでした。もう一度お試しください。"+ "delete_failed": "通知を削除できませんでした。もう一度お試しください。",+ "snooze_failed": "スヌーズできませんでした",+ "unsnooze_failed": "スヌーズを解除できませんでした"},"delete_dialog": {"title": "通知を削除しますか?","description": "この通知は完全に削除されます。関連するタスクと実行記録は残ります。","issue_description": "このビューにあるこのタスクの通知は完全に削除されます。タスクと実行記録は残ります。",- "cancel": "キャンセル",- "active_issue_description": "このタスクの受信トレイ内の通知は完全に削除されます。以前アーカイブした通知は残り、アーカイブに再表示されます。タスクと実行記録は残ります。"+ "cancel": "キャンセル"+ },+ "sections": {+ "needs_you": "対応待ち",+ "working": "実行中",+ "updates": "アップデート",+ "snoozed": "スヌーズ中",+ "clear_updates": "クリア",+ "queued": "待機中",+ "caught_up": "すべて対応済みです",+ "still_working_other": "{{count}} 件のエージェントが実行中です。結果はここに戻ります。"+ },+ "reasons": {+ "review": "確認待ち",+ "question": "回答待ち",+ "mention": "メンション",+ "failed": "実行失敗",+ "cancelled": "実行キャンセル",+ "assigned": "あなたに割り当て",+ "comment": "新しいコメント",+ "finished": "実行完了",+ "stopped_by_you": "あなたがこの実行を停止しました",+ "stopped_by": "{{name}} がこの実行を停止しました",+ "stopped_by_system": "システムがこの実行を停止しました"+ },+ "snooze": {+ "action": "スヌーズ",+ "unsnooze": "スヌーズを解除",+ "in_one_hour": "1 時間後",+ "later_today": "今日このあと",+ "tomorrow": "明日",+ "next_week": "次の月曜日",+ "pick_time": "日時を選択...",+ "hint": "メンションや実行の失敗など、新しく対応が必要になったときは早めに戻ります。",+ "custom_title": "スヌーズの期限",+ "custom_invalid": "1 年以内の未来の日時を選択してください。"}}diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.jsonindex 401879f42f..4b4b06fb88 100644--- a/packages/views/locales/ja/layout.json+++ b/packages/views/locales/ja/layout.json@@ -107,8 +107,6 @@"copy_link": "リンクをコピー","link_copied": "リンクをコピーしました","workspace_settings": "ワークスペース設定",- "mark_all_read": "すべて既読にする",- "mark_all_read_failed": "すべて既読にできませんでした","reset_order": "デフォルトの順序に戻す","copy_workspace_link": "ワークスペースのリンクをコピー","workspace_meta_other": "{{slug}} · メンバー {{count}} 人"@@ -119,9 +117,7 @@},"panels": {"work": {- "my_agents": "マイエージェントの作業","all_issues": "すべてのタスク",- "unread": "未読","views": "ビュー","new_project": "新規プロジェクト","new_issue_in_project": "{{name}} に新規タスク",diff --git a/packages/views/locales/ja/search.json b/packages/views/locales/ja/search.jsonindex 7ceb3b3490..b3fdb43d15 100644--- a/packages/views/locales/ja/search.json+++ b/packages/views/locales/ja/search.json@@ -85,9 +85,7 @@},"inbox": {"archive": "アーカイブ",- "mark_unread": "未読にする",- "mark_all_read": "インボックスをすべて既読にする",- "archive_all_read": "既読のインボックス項目をすべてアーカイブ"+ "mark_unread": "未読にする"},"chat": {"link_project": "プロジェクトに関連付け...",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex dfa92ec9ae..60a00d62b7 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -426,6 +426,10 @@"label": "通知をアーカイブ","description": "開いているインボックス通知をアーカイブします。アーカイブ表示中はアーカイブを解除します。"},+ "snoozeInboxItem": {+ "label": "通知をスヌーズ",+ "description": "開いているインボックスの通知が戻る日時を選びます。"+ },"send": {"label": "送信","description": "新しいタスクの作成にも使えます。"@@ -822,25 +826,48 @@"toast_profile_failed": "プロフィールを更新できませんでした"},"notifications": {- "title": "インボックス通知",- "description": "通知をオフにしても、タスク上で履歴を確認できます。","toast_failed": "通知設定を更新できませんでした",- "groups": {+ "needs_you": {+ "title": "対応待ち",+ "description": "あなた宛ての通知は、対応するかアーカイブするまでインボックスの「対応待ち」に残ります。オフにはできません。",+ "always_on": "常にオン",+ "mentions": {+ "label": "メンション",+ "description": "誰かがあなたを @メンションしたとき"+ },"assignments": {"label": "担当の割り当て",- "description": "タスクの担当者に割り当てられたとき、または解除されたとき"+ "description": "タスクの担当者に割り当てられたとき"},- "status_changes": {- "label": "ステータス変更",- "description": "フォロー中のタスクのステータスが変わったとき(例: todo、in progress、done)"+ "runs": {+ "label": "あなたが開始した実行",+ "description": "エージェントが完了・失敗したとき、質問したとき、または実行がキャンセルされたとき"+ },+ "your_issues": {+ "label": "あなたが作成または担当するタスク",+ "description": "新しいコメントが付いたとき、またはステータスがあなたの対応待ちになったとき"+ }+ },+ "updates": {+ "title": "アップデート",+ "description": "フォロー中のタスクのアクティビティです。バッジには数えられず、読むとインボックスから消えます。オフにしてもタスク上では確認できます。"+ },+ "groups": {+ "mentions": {+ "label": "@all と @squad",+ "description": "グループ宛てのメンションも「対応待ち」に入ります。オフにすると「アップデート」に入ります。"},"comments": {"label": "コメント","description": "フォロー中のタスクに新しいコメントが付いたとき"},- "mentions": {- "label": "メンション",- "description": "誰かがあなたを @メンションしたとき(@all と @squad を含む)"+ "status_changes": {+ "label": "ステータス変更",+ "description": "フォロー中のタスクのステータスが変わったとき(例: todo、in progress、done)"+ },+ "assignments": {+ "label": "担当の変更",+ "description": "担当を解除されたとき、またはフォロー中のタスクの担当者が変わったとき"},"updates": {"label": "優先度と期限",@@ -851,8 +878,8 @@"description": "購読中のプロジェクトでタスクが作成されたとき"},"agent_activity": {- "label": "エージェントのアクティビティ",- "description": "エージェントの実行が失敗したとき"+ "label": "エージェントの実行",+ "description": "フォロー中のタスクでエージェントの実行が失敗またはブロックされたとき"},"chat_replies": {"label": "チャットの返信を含める"@@ -860,7 +887,8 @@},"system": {"title": "システム通知",- "label": "Multica がバックグラウンドにあるときにシステム通知を表示"+ "label": "Multica がバックグラウンドにあるときにシステム通知を表示",+ "description": "インボックスでは「対応待ち」のみバナーを表示します。「アップデート」では表示しません。"},"browser": {"label": "ブラウザ通知",diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.jsonindex 91865f7b4a..45d211509e 100644--- a/packages/views/locales/ko/inbox.json+++ b/packages/views/locales/ko/inbox.json@@ -3,12 +3,6 @@"title": "인박스","back": "인박스"},- "menu": {- "mark_all_read": "모두 읽음으로 표시",- "archive_all": "모두 보관",- "archive_all_read": "읽은 항목 모두 보관",- "archive_completed": "완료된 항목 보관"- },"filters": {"tooltip": "인박스 필터","active_count_other": "필터 {{count}}개 적용됨",@@ -31,8 +25,7 @@"type_system": "시스템","received_today": "오늘","received_last_7_days": "최근 7일",- "received_last_30_days": "최근 30일",- "agent_idle": "유휴"+ "received_last_30_days": "최근 30일"},"context_menu": {"mark_read": "읽음으로 표시",@@ -40,7 +33,12 @@"archive": "보관","unarchive": "보관 해제","open_in_new_tab": "새 탭에서 열기",- "delete": "삭제"+ "delete": "삭제",+ "snooze_in_one_hour": "1시간 미루기",+ "snooze_later_today": "오늘 늦게까지 미루기",+ "snooze_tomorrow": "내일까지 미루기",+ "snooze_next_week": "다음 월요일까지 미루기",+ "unsnooze": "미루기 취소"},"list": {"loading_selection": "알림을 불러오는 중…",@@ -63,14 +61,15 @@},"detail": {"select_prompt": "자세히 볼 알림을 선택하세요",- "empty": "인박스가 비어 있습니다","original_input": "원본 입력","retry_with_context": "컨텍스트를 유지하여 재시도","edit_advanced": "고급 양식으로 수정","autopilot_quota_exceeded_body": "이 워크스페이스는 현재 기간의 자동화 실행 한도 {{limit}}회에 도달했습니다. 한도가 {{resetAt}}에 초기화될 때까지 이후 자동화 실행은 시작되지 않습니다.","autopilot_quota_upgrade": "업그레이드 옵션 보기","archive": "보관",- "unarchive": "보관 해제"+ "unarchive": "보관 해제",+ "nothing_needs_you": "처리할 태스크가 없습니다",+ "nothing_needs_you_hint": "에이전트가 결과를 넘기거나 누군가 멘션하면 왼쪽에 표시됩니다."},"types": {"issue_assigned": "할당됨",@@ -87,6 +86,7 @@"review_requested": "리뷰 요청됨","task_completed": "실행 완료됨","task_failed": "실행 실패함",+ "task_cancelled": "실행 취소됨","agent_blocked": "에이전트 막힘","agent_completed": "에이전트 완료됨","reaction_added": "반응 추가됨",@@ -120,7 +120,8 @@"source_context_retry_started": "원본 컨텍스트로 재시도를 시작했습니다","archived": "알림을 보관했습니다","unarchived": "알림을 복원했습니다",- "deleted": "알림이 삭제되었습니다"+ "deleted": "알림이 삭제되었습니다",+ "snoozed": "{{time}}까지 미뤘습니다"},"errors": {"archived_lookup_failed": "링크된 알림을 불러오지 못했습니다",@@ -130,20 +131,52 @@"mark_unread_failed": "읽지 않음 표시를 하지 못했습니다","archive_failed": "보관하지 못했습니다","mark_done_failed": "완료 표시를 하지 못했습니다",- "mark_all_read_failed": "모두 읽음으로 표시하지 못했습니다",- "archive_all_failed": "모두 보관하지 못했습니다",- "archive_all_read_failed": "읽은 항목을 보관하지 못했습니다",- "archive_completed_failed": "완료된 항목을 보관하지 못했습니다","unarchive_failed": "보관 해제에 실패했습니다","archived_load_failed": "보관된 알림을 불러오지 못했습니다","filters_load_failed": "필터를 불러올 수 없습니다",- "delete_failed": "알림을 삭제하지 못했습니다. 다시 시도해 주세요."+ "delete_failed": "알림을 삭제하지 못했습니다. 다시 시도해 주세요.",+ "snooze_failed": "미루지 못했습니다",+ "unsnooze_failed": "미루기를 취소하지 못했습니다"},"delete_dialog": {"title": "알림을 삭제할까요?","description": "이 알림은 영구적으로 삭제됩니다. 관련 작업과 실행 기록은 유지됩니다.","issue_description": "이 보기에서 해당 작업의 알림이 영구적으로 삭제됩니다. 작업과 실행 기록은 유지됩니다.",- "cancel": "취소",- "active_issue_description": "이 작업의 받은편지함 알림은 영구적으로 삭제됩니다. 이전에 보관한 알림은 유지되며 보관함에 다시 표시됩니다. 작업과 실행 기록은 유지됩니다."+ "cancel": "취소"+ },+ "sections": {+ "needs_you": "처리 필요",+ "working": "실행 중",+ "updates": "업데이트",+ "snoozed": "미룬 항목",+ "clear_updates": "비우기",+ "queued": "대기 중",+ "caught_up": "모두 처리했습니다",+ "still_working_other": "에이전트 {{count}}개가 아직 실행 중입니다. 결과는 여기로 돌아옵니다."+ },+ "reasons": {+ "review": "검토 대기",+ "question": "답변 대기",+ "mention": "멘션",+ "failed": "실행 실패",+ "cancelled": "실행 취소됨",+ "assigned": "나에게 할당됨",+ "comment": "새 댓글",+ "finished": "실행 완료",+ "stopped_by_you": "내가 이 실행을 중지했습니다",+ "stopped_by": "{{name}} 님이 이 실행을 중지했습니다",+ "stopped_by_system": "시스템이 이 실행을 중지했습니다"+ },+ "snooze": {+ "action": "미루기",+ "unsnooze": "미루기 취소",+ "in_one_hour": "1시간 후",+ "later_today": "오늘 늦게",+ "tomorrow": "내일",+ "next_week": "다음 월요일",+ "pick_time": "시간 선택...",+ "hint": "멘션이나 실행 실패처럼 새로 처리할 일이 생기면 더 일찍 돌아옵니다.",+ "custom_title": "미룰 시간",+ "custom_invalid": "1년 이내의 미래 시간을 선택하세요."}}diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.jsonindex 816d1b99e9..7f423f7ac7 100644--- a/packages/views/locales/ko/layout.json+++ b/packages/views/locales/ko/layout.json@@ -107,8 +107,6 @@"copy_link": "링크 복사","link_copied": "링크를 복사했습니다","workspace_settings": "작업 공간 설정",- "mark_all_read": "모두 읽음으로 표시",- "mark_all_read_failed": "모두 읽음으로 표시하지 못했습니다","reset_order": "기본 순서로 재설정","copy_workspace_link": "작업 공간 링크 복사","workspace_meta_other": "{{slug}} · 멤버 {{count}}명"@@ -119,9 +117,7 @@},"panels": {"work": {- "my_agents": "내 에이전트의 작업","all_issues": "전체 태스크",- "unread": "읽지 않음","views": "뷰","new_project": "새 프로젝트","new_issue_in_project": "{{name}}에 새 태스크",diff --git a/packages/views/locales/ko/search.json b/packages/views/locales/ko/search.jsonindex cdce8db951..71df9bc90c 100644--- a/packages/views/locales/ko/search.json+++ b/packages/views/locales/ko/search.json@@ -85,9 +85,7 @@},"inbox": {"archive": "보관",- "mark_unread": "읽지 않음으로 표시",- "mark_all_read": "인박스 모두 읽음으로 표시",- "archive_all_read": "읽은 인박스 항목 모두 보관"+ "mark_unread": "읽지 않음으로 표시"},"chat": {"link_project": "프로젝트에 연결...",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 258b75c8dd..e2efdea354 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -426,6 +426,10 @@"label": "알림 보관","description": "열린 인박스 알림을 보관합니다. 보관함을 보는 중에는 보관을 해제합니다."},+ "snoozeInboxItem": {+ "label": "알림 미루기",+ "description": "열려 있는 인박스 알림이 돌아올 시간을 선택합니다."+ },"send": {"label": "보내기","description": "새 태스크 생성에도 사용됩니다."@@ -822,25 +826,48 @@"toast_profile_failed": "프로필을 업데이트하지 못했습니다"},"notifications": {- "title": "인박스 알림",- "description": "알림을 꺼도 태스크에서 관련 활동을 볼 수 있습니다.","toast_failed": "알림 설정을 업데이트하지 못했습니다",- "groups": {+ "needs_you": {+ "title": "처리 필요",+ "description": "나에게 온 알림은 처리하거나 보관할 때까지 인박스의 '처리 필요'에 남습니다. 끌 수 없습니다.",+ "always_on": "항상 켜짐",+ "mentions": {+ "label": "멘션",+ "description": "누군가 나를 @멘션할 때"+ },"assignments": {"label": "할당",- "description": "태스크에 할당되거나 할당 해제될 때"+ "description": "태스크가 나에게 할당될 때"},- "status_changes": {- "label": "상태 변경",- "description": "팔로우 중인 태스크의 상태가 바뀔 때(예: 할 일, 진행 중, 완료)"+ "runs": {+ "label": "내가 시작한 실행",+ "description": "에이전트가 완료하거나 실패할 때, 질문할 때, 또는 실행이 취소될 때"+ },+ "your_issues": {+ "label": "내가 만들었거나 담당하는 태스크",+ "description": "새 댓글이 달리거나 상태가 내 처리를 기다리게 될 때"+ }+ },+ "updates": {+ "title": "업데이트",+ "description": "팔로우 중인 태스크의 활동입니다. 배지에 포함되지 않으며 읽으면 인박스에서 사라집니다. 꺼도 태스크에서는 볼 수 있습니다."+ },+ "groups": {+ "mentions": {+ "label": "@all 및 @squad",+ "description": "그룹 멘션도 '처리 필요'에 들어갑니다. 끄면 '업데이트'로 들어갑니다."},"comments": {"label": "댓글","description": "팔로우 중인 태스크에 새 댓글이 달릴 때"},- "mentions": {- "label": "멘션",- "description": "누군가 나를 @멘션할 때(@all, @squad 포함)"+ "status_changes": {+ "label": "상태 변경",+ "description": "팔로우 중인 태스크의 상태가 바뀔 때(예: 할 일, 진행 중, 완료)"+ },+ "assignments": {+ "label": "할당 변경",+ "description": "내 할당이 해제되거나 팔로우 중인 태스크의 담당자가 바뀔 때"},"updates": {"label": "우선순위 및 마감일",@@ -851,8 +878,8 @@"description": "구독 중인 프로젝트에 태스크가 생성될 때"},"agent_activity": {- "label": "에이전트 활동",- "description": "에이전트 실행이 실패할 때"+ "label": "에이전트 실행",+ "description": "팔로우 중인 태스크에서 에이전트 실행이 실패하거나 막혔을 때"},"chat_replies": {"label": "채팅 답변 포함"@@ -860,7 +887,8 @@},"system": {"title": "시스템 알림",- "label": "Multica가 백그라운드에 있을 때 시스템 알림 표시"+ "label": "Multica가 백그라운드에 있을 때 시스템 알림 표시",+ "description": "인박스에서는 '처리 필요'만 배너를 띄웁니다. '업데이트'는 띄우지 않습니다."},"browser": {"label": "브라우저 알림",diff --git a/packages/views/locales/ru/inbox.json b/packages/views/locales/ru/inbox.jsonindex d71f252454..0422eec38f 100644--- a/packages/views/locales/ru/inbox.json+++ b/packages/views/locales/ru/inbox.json@@ -3,12 +3,6 @@"title": "Входящие","back": "Входящие"},- "menu": {- "mark_all_read": "Отметить всё как прочитанное",- "archive_all": "Архивировать всё",- "archive_all_read": "Архивировать всё прочитанное",- "archive_completed": "Архивировать завершённые"- },"filters": {"tooltip": "Фильтр входящих","active_count_one": "{{count}} активный фильтр",@@ -37,8 +31,7 @@"type_system": "Система","received_today": "Сегодня","received_last_7_days": "Последние 7 дней",- "received_last_30_days": "Последние 30 дней",- "agent_idle": "Простаивает"+ "received_last_30_days": "Последние 30 дней"},"context_menu": {"mark_read": "Отметить как прочитанное",@@ -46,7 +39,12 @@"archive": "Архивировать","unarchive": "Восстановить из архива","open_in_new_tab": "Открыть в новой вкладке",- "delete": "Удалить"+ "delete": "Удалить",+ "snooze_in_one_hour": "Отложить на 1 час",+ "snooze_later_today": "Отложить до вечера",+ "snooze_tomorrow": "Отложить до завтра",+ "snooze_next_week": "Отложить до следующего понедельника",+ "unsnooze": "Вернуть сейчас"},"list": {"loading_selection": "Загрузка уведомления…",@@ -69,14 +67,15 @@},"detail": {"select_prompt": "Выберите уведомление, чтобы посмотреть детали",- "empty": "Ваши входящие пусты","original_input": "Исходный ввод","retry_with_context": "Повторить с контекстом","edit_advanced": "Редактировать как расширенную форму","autopilot_quota_exceeded_body": "Это рабочее пространство достигло лимита в {{limit}} запусков Автопилота за текущий период. Новые запуски Автопилота не начнутся, пока лимит не будет сброшен {{resetAt}}.","autopilot_quota_upgrade": "Посмотреть варианты обновления","archive": "Архивировать",- "unarchive": "Восстановить из архива"+ "unarchive": "Восстановить из архива",+ "nothing_needs_you": "Вас ничего не ждёт",+ "nothing_needs_you_hint": "Задачи появятся слева, когда агент вернёт результат или вас упомянут."},"types": {"issue_assigned": "Назначено",@@ -93,6 +92,7 @@"review_requested": "Запрошено ревью","task_completed": "Запуск завершён","task_failed": "Запуск завершился ошибкой",+ "task_cancelled": "Запуск отменён","agent_blocked": "Агент заблокирован","agent_completed": "Агент завершил работу","reaction_added": "Реакция",@@ -126,7 +126,8 @@"source_context_retry_started": "Повтор запущен с исходным контекстом","archived": "Уведомление архивировано","unarchived": "Уведомление восстановлено",- "deleted": "Уведомление удалено"+ "deleted": "Уведомление удалено",+ "snoozed": "Отложено до {{time}}"},"errors": {"archived_lookup_failed": "Не удалось загрузить связанное уведомление",@@ -136,20 +137,55 @@"mark_unread_failed": "Не удалось отметить как непрочитанное","archive_failed": "Не удалось архивировать","mark_done_failed": "Не удалось отметить как выполненное",- "mark_all_read_failed": "Не удалось отметить всё как прочитанное",- "archive_all_failed": "Не удалось архивировать всё",- "archive_all_read_failed": "Не удалось архивировать прочитанные элементы",- "archive_completed_failed": "Не удалось архивировать завершённые","unarchive_failed": "Не удалось восстановить из архива","archived_load_failed": "Не удалось загрузить архивные уведомления","filters_load_failed": "Не удалось загрузить фильтры",- "delete_failed": "Не удалось удалить уведомление. Попробуйте снова."+ "delete_failed": "Не удалось удалить уведомление. Попробуйте снова.",+ "snooze_failed": "Не удалось отложить",+ "unsnooze_failed": "Не удалось вернуть"},"delete_dialog": {"title": "Удалить уведомление?","description": "Уведомление будет удалено навсегда. Связанные задачи и запуски сохранятся.","issue_description": "Уведомления этой задачи в текущем представлении будут удалены навсегда. Задача и её запуски сохранятся.",- "cancel": "Отмена",- "active_issue_description": "Активные уведомления этой задачи будут удалены навсегда. Ранее архивированные уведомления сохранятся и снова появятся в архиве. Задача и её запуски сохранятся."+ "cancel": "Отмена"+ },+ "sections": {+ "needs_you": "Ждут вас",+ "working": "В работе",+ "updates": "Обновления",+ "snoozed": "Отложено",+ "clear_updates": "Очистить",+ "queued": "В очереди",+ "caught_up": "Всё разобрано",+ "still_working_one": "{{count}} агент ещё работает. Результаты появятся здесь.",+ "still_working_few": "{{count}} агента ещё работают. Результаты появятся здесь.",+ "still_working_many": "{{count}} агентов ещё работают. Результаты появятся здесь.",+ "still_working_other": "{{count}} агента ещё работают. Результаты появятся здесь."+ },+ "reasons": {+ "review": "Ждёт проверки",+ "question": "Ждёт ответа",+ "mention": "Вас упомянули",+ "failed": "Запуск не удался",+ "cancelled": "Запуск отменён",+ "assigned": "Назначено вам",+ "comment": "Новый комментарий",+ "finished": "Запуск завершён",+ "stopped_by_you": "Вы остановили этот запуск",+ "stopped_by": "Запуск остановлен: {{name}}",+ "stopped_by_system": "Запуск остановлен системой"+ },+ "snooze": {+ "action": "Отложить",+ "unsnooze": "Вернуть сейчас",+ "in_one_hour": "Через 1 час",+ "later_today": "Сегодня позже",+ "tomorrow": "Завтра",+ "next_week": "В следующий понедельник",+ "pick_time": "Выбрать время...",+ "hint": "Вернётся раньше, если появится что-то, что требует вашего участия, например упоминание или сбой запуска.",+ "custom_title": "Отложить до",+ "custom_invalid": "Выберите время в будущем, не позже чем через год."}}diff --git a/packages/views/locales/ru/layout.json b/packages/views/locales/ru/layout.jsonindex cdb6e03946..f04fe2cf54 100644--- a/packages/views/locales/ru/layout.json+++ b/packages/views/locales/ru/layout.json@@ -84,8 +84,6 @@"copy_link": "Копировать ссылку","link_copied": "Ссылка скопирована","workspace_settings": "Настройки рабочего пространства",- "mark_all_read": "Отметить все как прочитанные",- "mark_all_read_failed": "Не удалось отметить все как прочитанные","reset_order": "Вернуть порядок по умолчанию","copy_workspace_link": "Копировать ссылку на рабочее пространство","workspace_meta_one": "{{slug}} · {{count}} участник",@@ -102,7 +100,6 @@},"panels": {"work": {- "my_agents": "Работа моих агентов","all_issues": "Все задачи","views": "Представления","new_project": "Новый проект",@@ -144,7 +141,6 @@"all_projects_few": "Всего {{count}} проекта","all_projects_many": "Всего {{count}} проектов","project_issues_retry": "Повторить",- "unread": "Непрочитанные","new_issue_here": "Новая задача в этом проекте"},"team": {diff --git a/packages/views/locales/ru/search.json b/packages/views/locales/ru/search.jsonindex 117614d91d..5e583b81c5 100644--- a/packages/views/locales/ru/search.json+++ b/packages/views/locales/ru/search.json@@ -94,9 +94,7 @@},"inbox": {"archive": "В архив",- "mark_unread": "Отметить как непрочитанное",- "mark_all_read": "Отметить все входящие как прочитанные",- "archive_all_read": "Переместить все прочитанные входящие в архив"+ "mark_unread": "Отметить как непрочитанное"},"chat": {"link_project": "Связать с проектом...",diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex d0551a58fb..9944a731dc 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -443,6 +443,10 @@"label": "Архивировать уведомление","description": "Отправить в архив открытое уведомление во входящих или восстановить его при просмотре архива."},+ "snoozeInboxItem": {+ "label": "Отложить уведомление",+ "description": "Выберите, когда открытое уведомление вернётся во входящие."+ },"send": {"label": "Отправить","description": "Также отправляет новые задачи."@@ -848,42 +852,49 @@"toast_profile_failed": "Не удалось обновить профиль"},"notifications": {- "title": "Уведомления во входящих",- "description": "Отключённые события остаются видимыми в задаче.","toast_failed": "Не удалось обновить настройки уведомлений",- "system": {- "title": "Системные уведомления",- "label": "Показывать системные уведомления, когда Multica работает в фоне"+ "needs_you": {+ "title": "Ждут вас",+ "description": "Всё, что адресовано вам, остаётся во входящих в разделе «Ждут вас», пока вы не разберёте или не заархивируете это. Отключить нельзя.",+ "always_on": "Всегда включено",+ "mentions": {+ "label": "Упоминания",+ "description": "Когда вас упоминают через @"+ },+ "assignments": {+ "label": "Назначения",+ "description": "Когда вас назначают исполнителем задачи"+ },+ "runs": {+ "label": "Запуски, начатые вами",+ "description": "Когда агент завершает работу, терпит неудачу, задаёт вопрос или запуск отменяют"+ },+ "your_issues": {+ "label": "Задачи, которые вы создали или ведёте",+ "description": "Новые комментарии или статус, который ждёт вашего действия"+ }},- "browser": {- "label": "Уведомления браузера",- "hint": "Разрешите этому браузеру показывать баннеры для уведомлений входящих и ответов в чате.",- "enable": "Включить",- "granted": "Этот браузер может показывать баннеры уведомлений.",- "denied": "Заблокировано вашим браузером. Включите уведомления для этого сайта в настройках браузера.",- "enabled_badge": "Включено"+ "updates": {+ "title": "Обновления",+ "description": "Активность в задачах, на которые вы подписаны. Не учитывается в счётчике и исчезает из входящих после прочтения. Отключённое остаётся видно в самой задаче."},"groups": {- "agent_activity": {- "description": "Когда запуск агента завершается с ошибкой",- "label": "Активность агентов"- },- "assignments": {- "description": "Когда вас назначают исполнителем задачи или снимают назначение",- "label": "Назначения"+ "mentions": {+ "label": "@all и @squad",+ "description": "Групповые упоминания тоже попадают в «Ждут вас». Если выключить, они попадают в «Обновления»."},"comments": {"description": "Новые комментарии к задачам, на которые вы подписаны","label": "Комментарии"},- "mentions": {- "description": "Когда вас упоминают через @, в том числе через @all и @squad",- "label": "Упоминания"- },"status_changes": {"description": "Когда у задачи, на которую вы подписаны, меняется статус (например, «К выполнению», «В работе», «Готово»)","label": "Изменения статуса"},+ "assignments": {+ "label": "Смена исполнителя",+ "description": "Когда с вас снимают назначение или у задачи, на которую вы подписаны, меняется исполнитель"+ },"updates": {"description": "Когда у задач, на которые вы подписаны, меняется приоритет или срок","label": "Приоритет и срок"@@ -892,9 +903,26 @@"label": "Новые задачи","description": "Когда в проекте, на который вы подписаны, создаётся задача"},+ "agent_activity": {+ "label": "Запуски агентов",+ "description": "Когда запуск агента завершается с ошибкой или блокируется в задаче, на которую вы подписаны"+ },"chat_replies": {"label": "Включать ответы в чате"}+ },+ "system": {+ "title": "Системные уведомления",+ "label": "Показывать системные уведомления, когда Multica работает в фоне",+ "description": "Из входящих баннер показывает только раздел «Ждут вас». Обновления — никогда."+ },+ "browser": {+ "label": "Уведомления браузера",+ "hint": "Разрешите этому браузеру показывать баннеры для уведомлений входящих и ответов в чате.",+ "enable": "Включить",+ "granted": "Этот браузер может показывать баннеры уведомлений.",+ "denied": "Заблокировано вашим браузером. Включите уведомления для этого сайта в настройках браузера.",+ "enabled_badge": "Включено"}},"tokens": {diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.jsonindex b80d37e7b7..a170630c34 100644--- a/packages/views/locales/zh-Hans/inbox.json+++ b/packages/views/locales/zh-Hans/inbox.json@@ -3,12 +3,6 @@"title": "收件箱","back": "收件箱"},- "menu": {- "mark_all_read": "全部标为已读",- "archive_all": "归档全部",- "archive_all_read": "归档全部已读",- "archive_completed": "归档已完成"- },"filters": {"tooltip": "筛选收件箱","active_count_other": "{{count}} 个筛选条件",@@ -31,8 +25,7 @@"type_system": "系统","received_today": "今天","received_last_7_days": "最近 7 天",- "received_last_30_days": "最近 30 天",- "agent_idle": "空闲"+ "received_last_30_days": "最近 30 天"},"context_menu": {"mark_read": "标为已读",@@ -40,7 +33,12 @@"archive": "归档","unarchive": "取消归档","open_in_new_tab": "在新标签页打开",- "delete": "删除"+ "delete": "删除",+ "snooze_in_one_hour": "推迟 1 小时",+ "snooze_later_today": "推迟到今天晚些时候",+ "snooze_tomorrow": "推迟到明天",+ "snooze_next_week": "推迟到下周一",+ "unsnooze": "取消推迟"},"list": {"loading_selection": "正在加载通知…",@@ -63,14 +61,15 @@},"detail": {"select_prompt": "选择一条通知查看详情",- "empty": "收件箱为空","original_input": "原始输入","retry_with_context": "保留上下文重试","edit_advanced": "在完整表单中编辑","autopilot_quota_exceeded_body": "当前周期的 {{limit}} 次自动化执行额度已用完。在 {{resetAt}} 重置前,后续自动化执行将不会启动。","autopilot_quota_upgrade": "查看升级方案","archive": "归档",- "unarchive": "取消归档"+ "unarchive": "取消归档",+ "nothing_needs_you": "没有需要你处理的任务",+ "nothing_needs_you_hint": "智能体交回结果、有人 @ 你时,会出现在左侧。"},"types": {"issue_assigned": "已分配",@@ -87,6 +86,7 @@"review_requested": "请求审查","task_completed": "运行已完成","task_failed": "运行失败",+ "task_cancelled": "运行已取消","agent_blocked": "智能体被阻塞","agent_completed": "智能体已完成","reaction_added": "添加了表情反应",@@ -120,7 +120,8 @@"source_context_retry_started": "已使用原始上下文开始重试","archived": "已归档通知","unarchived": "已恢复通知",- "deleted": "通知已删除"+ "deleted": "通知已删除",+ "snoozed": "已推迟到 {{time}}"},"errors": {"archived_lookup_failed": "无法加载链接指向的通知",@@ -130,20 +131,52 @@"mark_unread_failed": "标为未读失败","archive_failed": "归档失败","mark_done_failed": "标为已完成失败",- "mark_all_read_failed": "全部标为已读失败",- "archive_all_failed": "归档全部失败",- "archive_all_read_failed": "归档已读失败",- "archive_completed_failed": "归档已完成失败","unarchive_failed": "取消归档失败","archived_load_failed": "无法加载已归档通知","filters_load_failed": "无法加载筛选项",- "delete_failed": "无法删除通知,请重试。"+ "delete_failed": "无法删除通知,请重试。",+ "snooze_failed": "无法推迟",+ "unsnooze_failed": "无法取消推迟"},"delete_dialog": {"title": "删除通知?","description": "此通知将被永久删除,关联任务和运行记录不受影响。","issue_description": "当前视图中此任务的通知将被永久删除,任务和运行记录不受影响。",- "cancel": "取消",- "active_issue_description": "此任务在收件箱中的通知将被永久删除。此前归档的通知会保留,并重新显示在归档视图中。任务和运行记录不受影响。"+ "cancel": "取消"+ },+ "sections": {+ "needs_you": "要你处理",+ "working": "运行中",+ "updates": "动态",+ "snoozed": "已推迟",+ "clear_updates": "清空",+ "queued": "排队中",+ "caught_up": "都处理完了",+ "still_working_other": "{{count}} 个智能体还在运行,有结果会回到这里。"+ },+ "reasons": {+ "review": "等你验收",+ "question": "等你回答",+ "mention": "提到你",+ "failed": "运行失败",+ "cancelled": "运行已取消",+ "assigned": "分配给你",+ "comment": "新评论",+ "finished": "运行完成",+ "stopped_by_you": "你停止了这次运行",+ "stopped_by": "{{name}} 停止了这次运行",+ "stopped_by_system": "系统停止了这次运行"+ },+ "snooze": {+ "action": "推迟",+ "unsnooze": "取消推迟",+ "in_one_hour": "1 小时后",+ "later_today": "今天晚些时候",+ "tomorrow": "明天",+ "next_week": "下周一",+ "pick_time": "选择时间...",+ "hint": "有新的事需要你处理时会提前回来,比如有人 @ 你,或智能体运行失败。",+ "custom_title": "推迟到",+ "custom_invalid": "请选择一年内的未来时间。"}}diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.jsonindex 87e753a412..a800fc5cbe 100644--- a/packages/views/locales/zh-Hans/layout.json+++ b/packages/views/locales/zh-Hans/layout.json@@ -107,8 +107,6 @@"copy_link": "复制链接","link_copied": "链接已复制","workspace_settings": "工作区设置",- "mark_all_read": "全部标为已读",- "mark_all_read_failed": "全部标为已读失败","reset_order": "恢复默认顺序","copy_workspace_link": "复制工作区链接","workspace_meta_other": "{{slug}} · {{count}} 位成员"@@ -119,9 +117,7 @@},"panels": {"work": {- "my_agents": "我的智能体在做","all_issues": "全部任务",- "unread": "未读","views": "视图","new_project": "新建项目","new_issue_in_project": "在 {{name}} 中新建任务",diff --git a/packages/views/locales/zh-Hans/search.json b/packages/views/locales/zh-Hans/search.jsonindex d8312dc59f..54ee4a560e 100644--- a/packages/views/locales/zh-Hans/search.json+++ b/packages/views/locales/zh-Hans/search.json@@ -85,9 +85,7 @@},"inbox": {"archive": "归档",- "mark_unread": "标为未读",- "mark_all_read": "收件箱全部标为已读",- "archive_all_read": "归档收件箱全部已读"+ "mark_unread": "标为未读"},"chat": {"link_project": "关联到项目...",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 533e9a1350..7870d7b962 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -426,6 +426,10 @@"label": "归档通知","description": "归档当前打开的收件箱通知;在归档列表中则取消归档。"},+ "snoozeInboxItem": {+ "label": "推迟通知",+ "description": "选择当前打开的收件箱通知何时回来。"+ },"send": {"label": "发送","description": "也用于提交新任务。"@@ -822,25 +826,48 @@"toast_profile_failed": "更新资料失败"},"notifications": {- "title": "收件箱通知",- "description": "关闭通知后,仍可在任务中查看相关动态。","toast_failed": "更新通知设置失败",- "groups": {+ "needs_you": {+ "title": "要你处理",+ "description": "写给你的事会留在收件箱的「要你处理」里,直到你处理或归档。这些不能关闭。",+ "always_on": "始终开启",+ "mentions": {+ "label": "提及",+ "description": "有人 @ 你时"+ },"assignments": {"label": "分配",- "description": "你被分配或取消分配某个任务时"+ "description": "任务分配给你时"},- "status_changes": {- "label": "状态变更",- "description": "你订阅的任务状态变化时(例如 todo、in_progress、done)"+ "runs": {+ "label": "你发起的运行",+ "description": "智能体跑完、失败、向你提问,或运行被取消时"+ },+ "your_issues": {+ "label": "你创建或负责的任务",+ "description": "有新评论,或状态变成等你处理时"+ }+ },+ "updates": {+ "title": "动态",+ "description": "你订阅的任务上发生的事。不计入徽标,看过就离开收件箱。关闭后仍可在任务中查看。"+ },+ "groups": {+ "mentions": {+ "label": "@all 和 @squad",+ "description": "群体提及也进「要你处理」。关闭后改进「动态」。"},"comments": {"label": "评论","description": "你订阅的任务有新评论时"},- "mentions": {- "label": "提及",- "description": "有人 @ 你时,包括 @all 和 @squad"+ "status_changes": {+ "label": "状态变更",+ "description": "你订阅的任务状态变化时(例如 todo、in_progress、done)"+ },+ "assignments": {+ "label": "分配变化",+ "description": "你被取消分配,或你订阅的任务换了负责人时"},"updates": {"label": "优先级与截止日期",@@ -851,8 +878,8 @@"description": "你订阅的项目中有新任务创建时"},"agent_activity": {- "label": "智能体活动",- "description": "智能体运行失败时"+ "label": "智能体运行",+ "description": "你订阅的任务上智能体运行失败或卡住时"},"chat_replies": {"label": "包含聊天回复"@@ -860,7 +887,8 @@},"system": {"title": "系统通知",- "label": "Multica 在后台时显示系统通知"+ "label": "Multica 在后台时显示系统通知",+ "description": "收件箱里只有「要你处理」的事会弹出,动态不弹。"},"browser": {"label": "浏览器通知",diff --git a/packages/views/locales/zh-Hant/inbox.json b/packages/views/locales/zh-Hant/inbox.jsonindex 6c5bd9b2fa..163da9e351 100644--- a/packages/views/locales/zh-Hant/inbox.json+++ b/packages/views/locales/zh-Hant/inbox.json@@ -3,12 +3,6 @@"title": "收件箱","back": "收件箱"},- "menu": {- "mark_all_read": "全部標為已讀",- "archive_all": "歸檔全部",- "archive_all_read": "歸檔全部已讀",- "archive_completed": "歸檔已完成"- },"filters": {"tooltip": "篩選收件箱","active_count_other": "{{count}} 個篩選條件",@@ -31,8 +25,7 @@"type_system": "系統","received_today": "今天","received_last_7_days": "最近 7 天",- "received_last_30_days": "最近 30 天",- "agent_idle": "閒置"+ "received_last_30_days": "最近 30 天"},"context_menu": {"mark_read": "標為已讀",@@ -40,7 +33,12 @@"archive": "歸檔","unarchive": "取消歸檔","open_in_new_tab": "在新標籤頁開啟",- "delete": "刪除"+ "delete": "刪除",+ "snooze_in_one_hour": "延後 1 小時",+ "snooze_later_today": "延後到今天稍晚",+ "snooze_tomorrow": "延後到明天",+ "snooze_next_week": "延後到下週一",+ "unsnooze": "取消延後"},"list": {"loading_selection": "正在載入通知…",@@ -63,14 +61,15 @@},"detail": {"select_prompt": "選擇一條通知檢視詳情",- "empty": "收件箱為空","original_input": "原始輸入","retry_with_context": "保留上下文重試","edit_advanced": "在完整表單中編輯","autopilot_quota_exceeded_body": "當前週期的 {{limit}} 次自動化執行額度已用完。在 {{resetAt}} 重置前,後續自動化執行將不會啟動。","autopilot_quota_upgrade": "檢視升級方案","archive": "歸檔",- "unarchive": "取消歸檔"+ "unarchive": "取消歸檔",+ "nothing_needs_you": "沒有需要你處理的任務",+ "nothing_needs_you_hint": "AI 代理交回結果、有人 @ 你時,會出現在左側。"},"types": {"issue_assigned": "已分配",@@ -87,6 +86,7 @@"review_requested": "請求審查","task_completed": "執行已完成","task_failed": "執行失敗",+ "task_cancelled": "執行已取消","agent_blocked": "AI 代理被阻塞","agent_completed": "AI 代理已完成","reaction_added": "新增了表情反應",@@ -120,7 +120,8 @@"source_context_retry_started": "已使用原始上下文開始重試","archived": "已歸檔通知","unarchived": "已恢復通知",- "deleted": "通知已刪除"+ "deleted": "通知已刪除",+ "snoozed": "已延後到 {{time}}"},"errors": {"archived_lookup_failed": "無法載入連結指向的通知",@@ -130,20 +131,52 @@"mark_unread_failed": "標為未讀失敗","archive_failed": "歸檔失敗","mark_done_failed": "標為已完成失敗",- "mark_all_read_failed": "全部標為已讀失敗",- "archive_all_failed": "歸檔全部失敗",- "archive_all_read_failed": "歸檔已讀失敗",- "archive_completed_failed": "歸檔已完成失敗","unarchive_failed": "取消歸檔失敗","archived_load_failed": "無法載入已歸檔通知","filters_load_failed": "無法載入篩選項",- "delete_failed": "無法刪除通知,請重試。"+ "delete_failed": "無法刪除通知,請重試。",+ "snooze_failed": "無法延後",+ "unsnooze_failed": "無法取消延後"},"delete_dialog": {"title": "刪除通知?","description": "此通知將被永久刪除,相關任務和執行記錄不受影響。","issue_description": "目前檢視中此任務的通知將被永久刪除,任務和執行記錄不受影響。",- "cancel": "取消",- "active_issue_description": "此任務在收件箱中的通知將被永久刪除。先前歸檔的通知會保留,並重新顯示在已歸檔檢視中。任務和執行記錄不受影響。"+ "cancel": "取消"+ },+ "sections": {+ "needs_you": "需要你處理",+ "working": "執行中",+ "updates": "動態",+ "snoozed": "已延後",+ "clear_updates": "清空",+ "queued": "排隊中",+ "caught_up": "都處理完了",+ "still_working_other": "{{count}} 個 AI 代理還在執行,有結果會回到這裡。"+ },+ "reasons": {+ "review": "等你驗收",+ "question": "等你回答",+ "mention": "提到你",+ "failed": "執行失敗",+ "cancelled": "執行已取消",+ "assigned": "分配給你",+ "comment": "新評論",+ "finished": "執行完成",+ "stopped_by_you": "你停止了這次執行",+ "stopped_by": "{{name}} 停止了這次執行",+ "stopped_by_system": "系統停止了這次執行"+ },+ "snooze": {+ "action": "延後",+ "unsnooze": "取消延後",+ "in_one_hour": "1 小時後",+ "later_today": "今天稍晚",+ "tomorrow": "明天",+ "next_week": "下週一",+ "pick_time": "選擇時間...",+ "hint": "有新的事需要你處理時會提前回來,例如有人 @ 你,或 AI 代理執行失敗。",+ "custom_title": "延後到",+ "custom_invalid": "請選擇一年內的未來時間。"}}diff --git a/packages/views/locales/zh-Hant/layout.json b/packages/views/locales/zh-Hant/layout.jsonindex e45ebda8a4..1315de2b60 100644--- a/packages/views/locales/zh-Hant/layout.json+++ b/packages/views/locales/zh-Hant/layout.json@@ -107,8 +107,6 @@"copy_link": "複製連結","link_copied": "已複製連結","workspace_settings": "工作區設定",- "mark_all_read": "全部標為已讀",- "mark_all_read_failed": "全部標為已讀失敗","reset_order": "恢復預設順序","copy_workspace_link": "複製工作區連結","workspace_meta_other": "{{slug}} · {{count}} 位成員"@@ -119,9 +117,7 @@},"panels": {"work": {- "my_agents": "我的 AI 代理在做","all_issues": "全部任務",- "unread": "未讀","views": "檢視","new_project": "新建專案","new_issue_in_project": "在 {{name}} 中新建任務",diff --git a/packages/views/locales/zh-Hant/search.json b/packages/views/locales/zh-Hant/search.jsonindex 503b8ddb03..d8d4c8360c 100644--- a/packages/views/locales/zh-Hant/search.json+++ b/packages/views/locales/zh-Hant/search.json@@ -85,9 +85,7 @@},"inbox": {"archive": "封存",- "mark_unread": "標為未讀",- "mark_all_read": "收件箱全部標為已讀",- "archive_all_read": "封存收件箱全部已讀"+ "mark_unread": "標為未讀"},"chat": {"link_project": "關聯到專案...",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex d02eaeb5e4..cd428ea706 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -426,6 +426,10 @@"label": "歸檔通知","description": "歸檔當前開啟的收件箱通知;在歸檔列表中則取消歸檔。"},+ "snoozeInboxItem": {+ "label": "延後通知",+ "description": "選擇目前開啟的收件箱通知何時回來。"+ },"send": {"label": "傳送","description": "也用於提交新任務。"@@ -822,25 +826,48 @@"toast_profile_failed": "更新資料失敗"},"notifications": {- "title": "收件箱通知",- "description": "關閉通知後,仍可在任務中檢視相關動態。","toast_failed": "更新通知設定失敗",- "groups": {+ "needs_you": {+ "title": "需要你處理",+ "description": "寫給你的事會留在收件箱的「需要你處理」裡,直到你處理或歸檔。這些無法關閉。",+ "always_on": "一律開啟",+ "mentions": {+ "label": "提及",+ "description": "有人 @ 你時"+ },"assignments": {"label": "分配",- "description": "你被分配或取消分配某個任務時"+ "description": "任務分配給你時"},- "status_changes": {- "label": "狀態變更",- "description": "你訂閱的任務狀態變化時(例如 todo、in_progress、done)"+ "runs": {+ "label": "你發起的執行",+ "description": "AI 代理執行完成、失敗、向你提問,或執行被取消時"+ },+ "your_issues": {+ "label": "你建立或負責的任務",+ "description": "有新評論,或狀態變成等你處理時"+ }+ },+ "updates": {+ "title": "動態",+ "description": "你訂閱的任務上發生的事。不計入徽章,看過就離開收件箱。關閉後仍可在任務中查看。"+ },+ "groups": {+ "mentions": {+ "label": "@all 和 @squad",+ "description": "群組提及也進「需要你處理」。關閉後改進「動態」。"},"comments": {"label": "評論","description": "你訂閱的任務有新評論時"},- "mentions": {- "label": "提及",- "description": "有人 @ 你時,包括 @all 和 @squad"+ "status_changes": {+ "label": "狀態變更",+ "description": "你訂閱的任務狀態變化時(例如 todo、in_progress、done)"+ },+ "assignments": {+ "label": "分配變更",+ "description": "你被取消分配,或你訂閱的任務換了負責人時"},"updates": {"label": "優先順序與截止日期",@@ -851,8 +878,8 @@"description": "你訂閱的專案中有新任務建立時"},"agent_activity": {- "label": "AI 代理活動",- "description": "AI 代理執行失敗時"+ "label": "AI 代理執行",+ "description": "你訂閱的任務上 AI 代理執行失敗或卡住時"},"chat_replies": {"label": "包含聊天回覆"@@ -860,7 +887,8 @@},"system": {"title": "系統通知",- "label": "Multica 在背景時顯示系統通知"+ "label": "Multica 在背景時顯示系統通知",+ "description": "收件箱裡只有「需要你處理」的事會跳出,動態不會。"},"browser": {"label": "瀏覽器通知",diff --git a/packages/views/search/commands/global-commands.tsx b/packages/views/search/commands/global-commands.tsxindex 72dd55d9a2..9871f7b061 100644--- a/packages/views/search/commands/global-commands.tsx+++ b/packages/views/search/commands/global-commands.tsx@@ -1,10 +1,7 @@"use client";import { useMemo } from "react";-import { toast } from "sonner";import {- Archive,- CheckCheck,FolderPlus,MessageCircleQuestion,MessageSquare,@@ -14,7 +11,6 @@ import {} from "@multica/ui/icons";import { useChatStore } from "@multica/core/chat";import type { CommandBarContext } from "@multica/core/command-bar";-import { useArchiveAllReadInbox, useMarkAllInboxRead } from "@multica/core/inbox/mutations";import { openCreateIssueWithPreference } from "@multica/core/issues/stores";import { useModalStore } from "@multica/core/modals";import { useWorkspacePaths } from "@multica/core/paths";@@ -31,19 +27,14 @@ import type { PaletteCommand } from "../types";*/export function useGlobalCommands(contexts: readonly CommandBarContext[]): PaletteCommand[] {const { t } = useT("search");- const { t: tInbox } = useT("inbox");const palette = usePalette();const p = useWorkspacePaths();const navigation = useNavigation();const createIssueShortcut = useShortcut("createIssue");const toggleChatShortcut = useShortcut("toggleChat");- const markAllRead = useMarkAllInboxRead();- const archiveAllRead = useArchiveAllReadInbox();const projectContext = contexts.find((c) => c.kind === "project");const projectId = projectContext?.kind === "project" ? projectContext.project.id : null;- const inboxContext = contexts.find((c) => c.kind === "inbox");- const inbox = inboxContext?.kind === "inbox" ? inboxContext : null;const { pathname } = navigation;return useMemo<PaletteCommand[]>(() => {@@ -90,44 +81,6 @@ export function useGlobalCommands(contexts: readonly CommandBarContext[]): Paletkeywords: ["new", "autopilot", "automation", "schedule", "create", "新建", "自动化"],run: () => palette.openHostDialog({ type: "new-autopilot" }),},- {- id: "inbox-mark-all-read",- label: t(($) => $.inbox.mark_all_read),- icon: CheckCheck,- keywords: ["inbox", "read", "all", "收件箱", "已读"],- run: () => {- if (inbox) {- inbox.markAllRead();- return;- }- markAllRead.mutateAsync(undefined).catch((err: unknown) =>- toast.error(- err instanceof Error && err.message- ? err.message- : tInbox(($) => $.errors.mark_all_read_failed),- ),- );- },- },- {- id: "inbox-archive-all-read",- label: t(($) => $.inbox.archive_all_read),- icon: Archive,- keywords: ["inbox", "archive", "read", "收件箱", "归档"],- run: () => {- if (inbox) {- inbox.archiveAllRead();- return;- }- archiveAllRead.mutateAsync(undefined).catch((err: unknown) =>- toast.error(- err instanceof Error && err.message- ? err.message- : tInbox(($) => $.errors.archive_all_read_failed),- ),- );- },- },{id: "theme",label: t(($) => $.commands.change_theme),@@ -144,17 +97,13 @@ export function useGlobalCommands(contexts: readonly CommandBarContext[]): Palet},];}, [- archiveAllRead,createIssueShortcut,- inbox,- markAllRead,navigation,p,palette,pathname,projectId,t,- tInbox,toggleChatShortcut,]);}diff --git a/packages/views/settings/components/notifications-tab.test.tsx b/packages/views/settings/components/notifications-tab.test.tsxindex e6ac43e699..c22f91a6a8 100644--- a/packages/views/settings/components/notifications-tab.test.tsx+++ b/packages/views/settings/components/notifications-tab.test.tsx@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { cleanup, render, screen, within } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { I18nProvider } from "@multica/core/i18n/react";import { notificationPreferenceKeys } from "@multica/core/notification-preferences/queries";@@ -8,12 +8,69 @@ import { NotificationsTab } from "./notifications-tab";vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-a" }));vi.mock("@multica/core/paths", () => ({ useCurrentWorkspace: () => ({ id: "ws-a", name: "Acme" }) }));+const mutate = vi.hoisted(() => vi.fn());vi.mock("@multica/core/notification-preferences/mutations", () => ({- useUpdateNotificationPreferences: () => ({ mutate: vi.fn() }),+ useUpdateNotificationPreferences: () => ({ mutate }),}));vi.mock("./browser-notification-setting", () => ({ BrowserNotificationSetting: () => null }));-afterEach(cleanup);+afterEach(() => {+ cleanup();+ mutate.mockClear();+});++function renderTab(preferences: Record<string, string> = {}) {+ const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } });+ qc.setQueryData(notificationPreferenceKeys.all("ws-a"), { workspace_id: "ws-a", preferences });+ render(+ <QueryClientProvider client={qc}>+ <I18nProvider locale="en" resources={{ en: { settings: enSettings } }}>+ <NotificationsTab />+ </I18nProvider>+ </QueryClientProvider>,+ );+}++describe("inbox notification settings", () => {+ it("offers no way to turn off what is addressed to the user", () => {+ renderTab();+ const needsYou = screen.getByRole("region", { name: "Needs you" });++ for (const label of ["Mentions", "Assignments", "Runs you started", "Issues you created or are assigned"]) {+ expect(within(needsYou).getByText(label)).toBeInTheDocument();+ }+ expect(within(needsYou).getAllByText("Always on")).toHaveLength(4);+ // The one choice: whether a mention of a group counts as the user's.+ expect(within(needsYou).getAllByRole("switch")).toHaveLength(1);+ expect(within(needsYou).getByRole("switch", { name: "@all and @squad" })).toBeChecked();+ });++ it("sends group mentions to Updates when their switch is off", () => {+ renderTab({ comments: "muted" });++ fireEvent.click(screen.getByRole("switch", { name: "@all and @squad" }));++ expect(mutate).toHaveBeenCalledWith({ comments: "muted", mentions: "muted" }, expect.anything());+ });++ it("lets each kind of update be turned off", () => {+ renderTab({ status_changes: "muted" });+ const updates = screen.getByRole("region", { name: "Updates" });++ expect(within(updates).getAllByRole("switch").map((el) => el.getAttribute("aria-label"))).toEqual([+ "Comments",+ "Status changes",+ "Assignment changes",+ "Priority & Due date",+ "New issues",+ "Agent runs",+ ]);+ expect(within(updates).getByRole("switch", { name: "Status changes" })).not.toBeChecked();++ fireEvent.click(within(updates).getByRole("switch", { name: "Status changes" }));+ expect(mutate).toHaveBeenCalledWith({}, expect.anything());+ });+});describe("notification setting hierarchy", () => {it.each([diff --git a/packages/views/settings/components/notifications-tab.tsx b/packages/views/settings/components/notifications-tab.tsxindex 1b9b9e4e38..1e2bce4904 100644--- a/packages/views/settings/components/notifications-tab.tsx+++ b/packages/views/settings/components/notifications-tab.tsx@@ -16,18 +16,22 @@ import {SettingsTab,} from "./settings-layout";-// Inbox event groups rendered in the per-event toggle list. `system_notifications`-// is a sibling preference key but lives in its own section below.-const INBOX_GROUP_KEYS = [- "assignments",- "status_changes",+// What is addressed to the user: always delivered, so these rows have no+// switch. The Inbox files them under "Needs you" (MUL-9215).+const ALWAYS_ON_KEYS = ["mentions", "assignments", "runs", "your_issues"] as const;++// Activity on what the user only follows, filed under "Updates". Each kind can+// be switched off. `system_notifications` is a sibling preference key but+// lives in its own section below.+const UPDATE_GROUP_KEYS = ["comments",- "mentions",+ "status_changes",+ "assignments","updates","new_issues","agent_activity",] as const;-type InboxGroupKey = (typeof INBOX_GROUP_KEYS)[number];+type SwitchGroupKey = (typeof UPDATE_GROUP_KEYS)[number] | "mentions";export function NotificationsTab() {const { t } = useT("settings");@@ -56,36 +60,55 @@ export function NotificationsTab() {});};+ const groupSwitch = (key: SwitchGroupKey) => (+ <SettingsRow+ key={key}+ anchor={key}+ label={t(($) => $.notifications.groups[key].label)}+ description={t(($) => $.notifications.groups[key].description)}+ >+ <Switch+ checked={preferences[key] !== "muted"}+ aria-label={t(($) => $.notifications.groups[key].label)}+ onCheckedChange={(checked) => handleToggle(key, checked)}+ />+ </SettingsRow>+ );+const systemEnabled = preferences.system_notifications !== "muted";return (<SettingsTab title={t(($) => $.page.tabs.notifications)} scope="workspace-only"><SettingsSection- title={t(($) => $.notifications.title)}- description={t(($) => $.notifications.description)}+ title={t(($) => $.notifications.needs_you.title)}+ description={t(($) => $.notifications.needs_you.description)}anchor="inbox"><SettingsCard>- {INBOX_GROUP_KEYS.map((key: InboxGroupKey) => {- const enabled = preferences[key] !== "muted";- return (- <SettingsRow- key={key}- anchor={key}- label={t(($) => $.notifications.groups[key].label)}- description={t(($) => $.notifications.groups[key].description)}- >- <Switch- checked={enabled}- aria-label={t(($) => $.notifications.groups[key].label)}- onCheckedChange={(checked) => handleToggle(key, checked)}- />- </SettingsRow>- );- })}+ {ALWAYS_ON_KEYS.map((key) => (+ <SettingsRow+ key={key}+ label={t(($) => $.notifications.needs_you[key].label)}+ description={t(($) => $.notifications.needs_you[key].description)}+ >+ <span className="shrink-0 text-caption text-muted-foreground">+ {t(($) => $.notifications.needs_you.always_on)}+ </span>+ </SettingsRow>+ ))}+ {/* The one choice here: a mention of a group is addressed to everyone+ in it, so the user decides whether that counts as theirs. */}+ {groupSwitch("mentions")}</SettingsCard></SettingsSection>+ <SettingsSection+ title={t(($) => $.notifications.updates.title)}+ description={t(($) => $.notifications.updates.description)}+ >+ <SettingsCard>{UPDATE_GROUP_KEYS.map(groupSwitch)}</SettingsCard>+ </SettingsSection>+<SettingsSectiontitle={t(($) => $.notifications.system.title)}anchor={systemEnabled ? undefined : "chat_replies"}@@ -94,6 +117,7 @@ export function NotificationsTab() {<SettingsRowanchor="system"label={t(($) => $.notifications.system.label)}+ description={t(($) => $.notifications.system.description)}><Switchchecked={systemEnabled}diff --git a/packages/views/settings/components/use-settings-search-index.ts b/packages/views/settings/components/use-settings-search-index.tsindex f5269e8d57..17d4b85d90 100644--- a/packages/views/settings/components/use-settings-search-index.ts+++ b/packages/views/settings/components/use-settings-search-index.ts@@ -6,11 +6,12 @@ import type { SettingsSearchEntry } from "./settings-search";import { CHANNEL_INTEGRATIONS } from "./settings-navigation";import { browserNotificationSettingAvailable } from "./browser-notification-setting";+// The notification kinds that have a switch, in the order the page lists them.const NOTIFICATION_GROUPS = [- "assignments",- "status_changes",- "comments","mentions",+ "comments",+ "status_changes",+ "assignments","updates","new_issues","agent_activity",@@ -190,6 +191,7 @@ export function useSettingsSearchIndex(tab: "notifications",anchor: "system",title: t(($) => $.notifications.system.label),+ description: t(($) => $.notifications.system.description),},// Web-only row: absent on desktop and without the Notification API....(browserNotificationSettingAvailable()diff --git a/server/cmd/server/inbox_sections_test.go b/server/cmd/server/inbox_sections_test.gonew file mode 100644index 0000000000..4e362ff1cd--- /dev/null+++ b/server/cmd/server/inbox_sections_test.go@@ -0,0 +1,712 @@+package main++import (+ "context"+ "testing"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/handler"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// The Inbox files each notification by who the recipient is to the issue+// (MUL-9215). These tests drive the listeners and read what was stored.++type storedInboxRow struct {+ notifType string+ section string+ archived bool+ taskID string+}++// inboxRowsOnIssue lists a member's rows on one issue, oldest first.+func inboxRowsOnIssue(t *testing.T, recipientID, issueID string) []storedInboxRow {+ t.Helper()+ rows, err := testPool.Query(context.Background(), `+ SELECT type, coalesce(section, ''), archived, coalesce(details->>'task_id', '')+ FROM inbox_item+ WHERE recipient_type = 'member' AND recipient_id = $1 AND issue_id = $2+ ORDER BY created_at, id+ `, recipientID, issueID)+ if err != nil {+ t.Fatalf("inboxRowsOnIssue: %v", err)+ }+ defer rows.Close()+ var out []storedInboxRow+ for rows.Next() {+ var row storedInboxRow+ if err := rows.Scan(&row.notifType, &row.section, &row.archived, &row.taskID); err != nil {+ t.Fatalf("inboxRowsOnIssue scan: %v", err)+ }+ out = append(out, row)+ }+ return out+}++// activeInboxRows keeps the rows still in the Inbox.+func activeInboxRows(rows []storedInboxRow) []storedInboxRow {+ var out []storedInboxRow+ for _, row := range rows {+ if !row.archived {+ out = append(out, row)+ }+ }+ return out+}++// seedInboxTask records a run and who started it. source is the attribution+// waterfall level; retryOf, when set, makes it the retry of an earlier run.+func seedInboxTask(t *testing.T, issueID, originatorID, source, status, retryOf string) string {+ t.Helper()+ agentID := getAgentID(t)+ var taskID string+ if err := testPool.QueryRow(context.Background(), `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority,+ originator_user_id, accountable_user_id, originator_source, retry_of_task_id)+ SELECT id, runtime_id, $2, $5, 0, $3, $3, $4, NULLIF($6, '')::uuid FROM agent WHERE id = $1+ RETURNING id+ `, agentID, issueID, originatorID, source, status, retryOf).Scan(&taskID); err != nil {+ t.Fatalf("seed task: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)+ })+ return taskID+}++func publishTaskEvent(bus *events.Bus, eventType, issueID, taskID string, extra map[string]any) {+ payload := map[string]any{+ "task_id": taskID,+ "agent_id": "00000000-0000-0000-0000-aaaaaaaaaaaa",+ "issue_id": issueID,+ }+ for key, value := range extra {+ payload[key] = value+ }+ bus.Publish(events.Event{+ Type: eventType,+ WorkspaceID: testWorkspaceID,+ ActorType: "system",+ Payload: payload,+ })+}++func publishSectionsComment(bus *events.Bus, issueID, authorID, issueStatus string) {+ bus.Publish(events.Event{+ Type: protocol.EventCommentCreated,+ WorkspaceID: testWorkspaceID,+ ActorType: "member",+ ActorID: authorID,+ Payload: map[string]any{+ "comment": handler.CommentResponse{+ ID: "00000000-0000-0000-0000-000000000000",+ IssueID: issueID,+ AuthorType: "member",+ AuthorID: authorID,+ Content: "a reply",+ Type: "comment",+ },+ "issue_title": "sections test issue",+ "issue_status": issueStatus,+ },+ })+}++// inboxSectionsIssue is an issue the test user created, with a second member+// who answers for it by assignment and a third who only follows it.+type inboxSectionsIssue struct {+ issueID string+ assigneeID string+ followerID string+ authorID string+}++func newInboxSectionsIssue(t *testing.T, tag string) inboxSectionsIssue {+ t.Helper()+ member := func(role string) string {+ email := "inbox-sections-" + tag + "-" + role + "@multica.ai"+ id := createNotificationMember(t, email)+ t.Cleanup(func() { cleanupTestUser(t, email) })+ return id+ }+ f := inboxSectionsIssue{+ assigneeID: member("assignee"),+ followerID: member("follower"),+ authorID: member("author"),+ }+ f.issueID = createTestIssue(t, testWorkspaceID, testUserID)+ t.Cleanup(func() {+ cleanupInboxForIssue(t, f.issueID)+ cleanupTestIssue(t, f.issueID)+ })+ if _, err := testPool.Exec(context.Background(),+ `UPDATE issue SET assignee_type = 'member', assignee_id = $2 WHERE id = $1`, f.issueID, f.assigneeID); err != nil {+ t.Fatalf("assign issue: %v", err)+ }+ addTestSubscriber(t, f.issueID, "member", testUserID, "creator")+ addTestSubscriber(t, f.issueID, "member", f.assigneeID, "assignee")+ addTestSubscriber(t, f.issueID, "member", f.followerID, "commenter")+ return f+}++func wantSingleRow(t *testing.T, who string, rows []storedInboxRow, notifType, section string) {+ t.Helper()+ active := activeInboxRows(rows)+ if len(active) != 1 {+ t.Fatalf("%s: %d active rows, want 1: %+v", who, len(active), rows)+ }+ if active[0].notifType != notifType || active[0].section != section {+ t.Fatalf("%s: row = %s in %q, want %s in %q", who, active[0].notifType, active[0].section, notifType, section)+ }+}++// The same comment needs the people who answer for the issue and is an update+// for someone who only follows it.+func TestInboxSection_CommentIsFiledByTheRecipientsRelation(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)+ f := newInboxSectionsIssue(t, "comment")++ var announced []string+ bus.Subscribe(protocol.EventInboxNew, func(e events.Event) {+ payload, _ := e.Payload.(map[string]any)+ item, _ := payload["item"].(map[string]any)+ if item["issue_id"] == nil {+ return+ }+ if id, _ := item["issue_id"].(*string); id != nil && *id == f.issueID {+ section, _ := item["section"].(string)+ announced = append(announced, section)+ }+ })++ publishSectionsComment(bus, f.issueID, f.authorID, "todo")++ wantSingleRow(t, "creator", inboxRowsOnIssue(t, testUserID, f.issueID), "new_comment", "needs_you")+ wantSingleRow(t, "assignee", inboxRowsOnIssue(t, f.assigneeID, f.issueID), "new_comment", "needs_you")+ wantSingleRow(t, "follower", inboxRowsOnIssue(t, f.followerID, f.issueID), "new_comment", "updates")++ needsYou, updates := 0, 0+ for _, section := range announced {+ switch section {+ case "needs_you":+ needsYou+++ case "updates":+ updates+++ }+ }+ if needsYou != 2 || updates != 1 {+ t.Fatalf("inbox:new carried sections %v, want two needs_you and one updates", announced)+ }+}++// A mention is addressed to its target whatever their relation to the issue.+func TestInboxSection_MentionNeedsItsTarget(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)+ f := newInboxSectionsIssue(t, "mention")++ bus.Publish(events.Event{+ Type: protocol.EventCommentCreated,+ WorkspaceID: testWorkspaceID,+ ActorType: "member",+ ActorID: f.authorID,+ Payload: map[string]any{+ "comment": handler.CommentResponse{+ ID: "00000000-0000-0000-0000-000000000000",+ IssueID: f.issueID,+ AuthorType: "member",+ AuthorID: f.authorID,+ Content: "[@Follower](mention://member/" + f.followerID + ") can you look?",+ Type: "comment",+ },+ "issue_title": "sections test issue",+ "issue_status": "todo",+ },+ })++ var mention *storedInboxRow+ for _, row := range inboxRowsOnIssue(t, f.followerID, f.issueID) {+ if row.notifType == "mentioned" {+ mention = &row+ }+ }+ if mention == nil || mention.section != "needs_you" {+ t.Fatalf("follower's mention = %+v, want a mentioned row in needs_you", mention)+ }+}++// A status change needs the people who answer for the issue only when the new+// status waits on a person.+func TestInboxSection_StatusChangeNeedsTheOwnerOnlyWhenItWaits(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)++ for _, tc := range []struct {+ status string+ ownerSection string+ }{+ {"in_review", "needs_you"},+ {"blocked", "needs_you"},+ {"in_progress", "updates"},+ {"todo", "updates"},+ } {+ t.Run(tc.status, func(t *testing.T) {+ f := newInboxSectionsIssue(t, "status-"+tc.status)+ // publishStatusChange acts as the test user, so the assignee is the+ // owner who hears about it.+ publishStatusChange(bus, f.issueID, tc.status, "backlog")+ wantSingleRow(t, "assignee", inboxRowsOnIssue(t, f.assigneeID, f.issueID), "status_changed", tc.ownerSection)+ wantSingleRow(t, "follower", inboxRowsOnIssue(t, f.followerID, f.issueID), "status_changed", "updates")+ })+ }+}++// A done or cancelled issue leaves every Inbox. What remains is the one update+// saying it closed.+func TestInbox_ClosedIssueLeavesEveryInbox(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)++ for _, status := range []string{"done", "cancelled"} {+ t.Run(status, func(t *testing.T) {+ f := newInboxSectionsIssue(t, "closed-"+status)+ publishSectionsComment(bus, f.issueID, f.authorID, "in_review")++ var archived []map[string]any+ bus.Subscribe(protocol.EventInboxBatchArchived, func(e events.Event) {+ payload, _ := e.Payload.(map[string]any)+ if payload["issue_id"] == f.issueID {+ archived = append(archived, payload)+ }+ })++ publishStatusChange(bus, f.issueID, status, "in_review")++ for who, id := range map[string]string{"assignee": f.assigneeID, "follower": f.followerID} {+ rows := inboxRowsOnIssue(t, id, f.issueID)+ if len(rows) != 2 || !rows[0].archived {+ t.Fatalf("%s: rows = %+v, want the comment archived", who, rows)+ }+ wantSingleRow(t, who, rows, "status_changed", "updates")+ }+ // The test user closed it, so they get no update, and nothing waits.+ if active := activeInboxRows(inboxRowsOnIssue(t, testUserID, f.issueID)); len(active) != 0 {+ t.Fatalf("closer: active rows = %+v, want none", active)+ }+ if len(archived) != 3 {+ t.Fatalf("inbox:batch-archived events = %d, want one per recipient", len(archived))+ }+ for _, payload := range archived {+ if payload["reason"] != "issue_closed" {+ t.Fatalf("batch-archived reason = %v, want issue_closed", payload["reason"])+ }+ }+ })+ }+}++// A member's own action starting a run hands the issue to the agent: their+// rows leave "Needs you", and nobody else's do.+func TestInbox_RunStartedByMemberArchivesTheirRows(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)+ f := newInboxSectionsIssue(t, "run-start")+ publishSectionsComment(bus, f.issueID, f.authorID, "todo")++ var archived []map[string]any+ bus.Subscribe(protocol.EventInboxBatchArchived, func(e events.Event) {+ payload, _ := e.Payload.(map[string]any)+ if payload["issue_id"] == f.issueID {+ archived = append(archived, payload)+ }+ })++ // A run an agent started on the member's behalf, and the retry of an+ // earlier attempt, are not the member handing anything over. The listener+ // reads who started the run, not its status, so the rows are seeded+ // finished: one agent may have a single pending run per issue.+ delegated := seedInboxTask(t, f.issueID, testUserID, "delegation", "completed", "")+ publishTaskEvent(bus, protocol.EventTaskQueued, f.issueID, delegated, nil)+ first := seedInboxTask(t, f.issueID, testUserID, "direct_human", "failed", "")+ retry := seedInboxTask(t, f.issueID, testUserID, "direct_human", "completed", first)+ publishTaskEvent(bus, protocol.EventTaskQueued, f.issueID, retry, nil)+ if active := activeInboxRows(inboxRowsOnIssue(t, testUserID, f.issueID)); len(active) != 1 {+ t.Fatalf("after a delegated run and a retry: active rows = %+v, want the comment kept", active)+ }++ direct := seedInboxTask(t, f.issueID, testUserID, "direct_human", "completed", "")+ publishTaskEvent(bus, protocol.EventTaskQueued, f.issueID, direct, nil)++ if active := activeInboxRows(inboxRowsOnIssue(t, testUserID, f.issueID)); len(active) != 0 {+ t.Fatalf("starter: active rows = %+v, want none", active)+ }+ if active := activeInboxRows(inboxRowsOnIssue(t, f.assigneeID, f.issueID)); len(active) != 1 {+ t.Fatalf("assignee: active rows = %+v, want theirs untouched", active)+ }+ if len(archived) != 1 || archived[0]["recipient_id"] != testUserID || archived[0]["reason"] != "handed_to_agent" {+ t.Fatalf("inbox:batch-archived = %+v, want one handed_to_agent event for the starter", archived)+ }+}++// When the run a member started completes, the issue comes back to them in+// "Needs you", whether or not the agent mentioned them.+func TestInbox_RunCompletedHandsBackToTheMemberWhoStartedIt(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)+ f := newInboxSectionsIssue(t, "run-done")++ direct := seedInboxTask(t, f.issueID, f.followerID, "direct_human", "completed", "")+ publishTaskEvent(bus, protocol.EventTaskCompleted, f.issueID, direct, nil)+ // A run an agent started on someone's behalf hands nothing back.+ delegated := seedInboxTask(t, f.issueID, f.authorID, "delegation", "completed", "")+ publishTaskEvent(bus, protocol.EventTaskCompleted, f.issueID, delegated, nil)++ rows := inboxRowsOnIssue(t, f.followerID, f.issueID)+ wantSingleRow(t, "starter", rows, "agent_completed", "needs_you")+ if rows[0].taskID != direct {+ t.Fatalf("starter: row names run %q, want %q", rows[0].taskID, direct)+ }+ for who, id := range map[string]string{"delegating member": f.authorID, "creator": testUserID, "assignee": f.assigneeID} {+ if rows := inboxRowsOnIssue(t, id, f.issueID); len(rows) != 0 {+ t.Fatalf("%s: rows = %+v, want none", who, rows)+ }+ }+}++// A run that closed the issue has nothing to hand back.+func TestInbox_RunCompletedOnClosedIssueHandsNothingBack(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)+ f := newInboxSectionsIssue(t, "run-done-closed")+ if _, err := testPool.Exec(context.Background(), `UPDATE issue SET status = 'done' WHERE id = $1`, f.issueID); err != nil {+ t.Fatalf("close issue: %v", err)+ }++ task := seedInboxTask(t, f.issueID, f.followerID, "direct_human", "completed", "")+ publishTaskEvent(bus, protocol.EventTaskCompleted, f.issueID, task, nil)++ if rows := inboxRowsOnIssue(t, f.followerID, f.issueID); len(rows) != 0 {+ t.Fatalf("starter: rows = %+v, want none on a closed issue", rows)+ }+}++// A failed run comes back to whoever started it and to the people who answer+// for the issue; a follower gets an update. An attempt with a retry pending+// has not ended the run and reaches no one.+func TestInbox_RunFailedIsFiledByRelationOnceFinal(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)+ f := newInboxSectionsIssue(t, "run-failed")+ starterEmail := "[email protected]"+ starterID := createNotificationMember(t, starterEmail)+ t.Cleanup(func() { cleanupTestUser(t, starterEmail) })++ task := seedInboxTask(t, f.issueID, starterID, "direct_human", "failed", "")++ publishTaskEvent(bus, protocol.EventTaskFailed, f.issueID, task, map[string]any{"retry_pending": true})+ for who, id := range map[string]string{"starter": starterID, "creator": testUserID, "follower": f.followerID} {+ if rows := inboxRowsOnIssue(t, id, f.issueID); len(rows) != 0 {+ t.Fatalf("%s: rows = %+v after an attempt that will be retried, want none", who, rows)+ }+ }++ publishTaskEvent(bus, protocol.EventTaskFailed, f.issueID, task, map[string]any{"retry_pending": false})++ // The starter does not subscribe to the issue and still hears.+ starterRows := inboxRowsOnIssue(t, starterID, f.issueID)+ wantSingleRow(t, "starter", starterRows, "task_failed", "needs_you")+ if starterRows[0].taskID != task {+ t.Fatalf("starter: row names run %q, want %q", starterRows[0].taskID, task)+ }+ wantSingleRow(t, "creator", inboxRowsOnIssue(t, testUserID, f.issueID), "task_failed", "needs_you")+ wantSingleRow(t, "assignee", inboxRowsOnIssue(t, f.assigneeID, f.issueID), "task_failed", "needs_you")+ wantSingleRow(t, "follower", inboxRowsOnIssue(t, f.followerID, f.issueID), "task_failed", "updates")+}++// A member an agent filed the issue for answers for it like its creator.+func TestInboxSection_DelegatedSubscriberAnswersForTheIssue(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)+ f := newInboxSectionsIssue(t, "delegated")+ delegatedEmail := "[email protected]"+ delegatedID := createNotificationMember(t, delegatedEmail)+ t.Cleanup(func() { cleanupTestUser(t, delegatedEmail) })+ addTestSubscriber(t, f.issueID, "member", delegatedID, "delegated")++ publishStatusChange(bus, f.issueID, "in_review", "in_progress")++ wantSingleRow(t, "delegated owner", inboxRowsOnIssue(t, delegatedID, f.issueID), "status_changed", "needs_you")+}++// cancelInboxTask records who cancelled a run. An empty byType leaves the+// columns unset, as a cancel without an actor does.+func cancelInboxTask(t *testing.T, taskID, byType, byID, byName string) {+ t.Helper()+ if _, err := testPool.Exec(context.Background(), `+ UPDATE agent_task_queue+ SET status = 'cancelled', completed_at = now(),+ cancelled_by_type = NULLIF($2, ''), cancelled_by_id = NULLIF($3, '')::uuid,+ cancelled_by_name = NULLIF($4, '')+ WHERE id = $1+ `, taskID, byType, byID, byName); err != nil {+ t.Fatalf("cancel task: %v", err)+ }+}++type cancelledInboxRow struct {+ section string+ read bool+ archived bool+ taskID string+ byType string+ byID string+ byName string+}++func cancelledInboxRows(t *testing.T, recipientID, issueID string) []cancelledInboxRow {+ t.Helper()+ rows, err := testPool.Query(context.Background(), `+ SELECT coalesce(section, ''), read, archived,+ coalesce(details->>'task_id', ''), coalesce(details->>'cancelled_by_type', ''),+ coalesce(details->>'cancelled_by_id', ''), coalesce(details->>'cancelled_by_name', '')+ FROM inbox_item+ WHERE recipient_type = 'member' AND recipient_id = $1 AND issue_id = $2 AND type = 'task_cancelled'+ ORDER BY created_at, id+ `, recipientID, issueID)+ if err != nil {+ t.Fatalf("cancelledInboxRows: %v", err)+ }+ defer rows.Close()+ var out []cancelledInboxRow+ for rows.Next() {+ var row cancelledInboxRow+ if err := rows.Scan(&row.section, &row.read, &row.archived, &row.taskID, &row.byType, &row.byID, &row.byName); err != nil {+ t.Fatalf("cancelledInboxRows scan: %v", err)+ }+ out = append(out, row)+ }+ return out+}++// A cancelled run comes back to the member who started it. They have read it+// already when they stopped it themselves, and not when someone else did.+func TestInbox_RunCancelledHandsBackToTheMemberWhoStartedIt(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)++ for _, tc := range []struct {+ name string+ byType string+ byMember string // "starter", "other" or ""+ byName string+ wantRead bool+ }{+ {"stopped by the starter", "member", "starter", "Starter", true},+ {"stopped by another member", "member", "other", "Someone Else", false},+ {"stopped by the system", "system", "", "", false},+ {"no actor recorded", "", "", "", false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ f := newInboxSectionsIssue(t, "run-cancelled-"+tc.byType+"-"+tc.byMember)+ starterID := f.followerID+ byID := map[string]string{"starter": starterID, "other": f.authorID, "": ""}[tc.byMember]++ var announced []map[string]any+ bus.Subscribe(protocol.EventInboxNew, func(e events.Event) {+ payload, _ := e.Payload.(map[string]any)+ item, _ := payload["item"].(map[string]any)+ if item["recipient_id"] == starterID && item["type"] == "task_cancelled" {+ announced = append(announced, item)+ }+ })++ task := seedInboxTask(t, f.issueID, starterID, "direct_human", "running", "")+ cancelInboxTask(t, task, tc.byType, byID, tc.byName)+ publishTaskEvent(bus, protocol.EventTaskCancelled, f.issueID, task, nil)++ rows := cancelledInboxRows(t, starterID, f.issueID)+ if len(rows) != 1 {+ t.Fatalf("starter: %d cancelled rows, want 1: %+v", len(rows), rows)+ }+ row := rows[0]+ if row.section != "needs_you" || row.archived || row.read != tc.wantRead {+ t.Fatalf("starter: row = %+v, want an active needs_you row with read=%v", row, tc.wantRead)+ }+ if row.taskID != task || row.byType != tc.byType || row.byID != byID || row.byName != tc.byName {+ t.Fatalf("starter: row = %+v, want it to name run %s cancelled by %s %s %q", row, task, tc.byType, byID, tc.byName)+ }+ if len(announced) != 1 || announced[0]["read"] != tc.wantRead || announced[0]["section"] != "needs_you" {+ t.Fatalf("inbox:new = %+v, want one needs_you item with read=%v", announced, tc.wantRead)+ }+ // Nobody else hears about a cancelled run.+ for who, id := range map[string]string{"creator": testUserID, "assignee": f.assigneeID, "author": f.authorID} {+ if rows := cancelledInboxRows(t, id, f.issueID); len(rows) != 0 {+ t.Fatalf("%s: rows = %+v, want none", who, rows)+ }+ }++ // The same cancellation announced again hands nothing more back.+ publishTaskEvent(bus, protocol.EventTaskCancelled, f.issueID, task, map[string]any{"replay": true})+ if rows := cancelledInboxRows(t, starterID, f.issueID); len(rows) != 1 {+ t.Fatalf("after a replay: %d cancelled rows, want still 1", len(rows))+ }+ })+ }+}++// A cancelled run hands nothing back when the issue is not coming back to the+// member who started it.+func TestInbox_RunCancelledHandsNothingBack(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)++ t.Run("a run nobody started by hand", func(t *testing.T) {+ f := newInboxSectionsIssue(t, "cancel-delegated")+ task := seedInboxTask(t, f.issueID, f.followerID, "delegation", "running", "")+ cancelInboxTask(t, task, "system", "", "")+ publishTaskEvent(bus, protocol.EventTaskCancelled, f.issueID, task, nil)+ if rows := cancelledInboxRows(t, f.followerID, f.issueID); len(rows) != 0 {+ t.Fatalf("rows = %+v, want none", rows)+ }+ })++ t.Run("the issue is being deleted", func(t *testing.T) {+ f := newInboxSectionsIssue(t, "cancel-deleted")+ task := seedInboxTask(t, f.issueID, f.followerID, "direct_human", "running", "")+ cancelInboxTask(t, task, "system", "", "")+ publishTaskEvent(bus, protocol.EventTaskCancelled, f.issueID, task, map[string]any{"issue_deleted": true})+ if rows := cancelledInboxRows(t, f.followerID, f.issueID); len(rows) != 0 {+ t.Fatalf("rows = %+v, want none", rows)+ }+ })++ t.Run("the issue is closed", func(t *testing.T) {+ f := newInboxSectionsIssue(t, "cancel-closed")+ if _, err := testPool.Exec(context.Background(), `UPDATE issue SET status = 'cancelled' WHERE id = $1`, f.issueID); err != nil {+ t.Fatalf("close issue: %v", err)+ }+ task := seedInboxTask(t, f.issueID, f.followerID, "direct_human", "running", "")+ cancelInboxTask(t, task, "member", f.followerID, "Starter")+ publishTaskEvent(bus, protocol.EventTaskCancelled, f.issueID, task, nil)+ if rows := cancelledInboxRows(t, f.followerID, f.issueID); len(rows) != 0 {+ t.Fatalf("rows = %+v, want none", rows)+ }+ })++ t.Run("another run the member started is still active", func(t *testing.T) {+ f := newInboxSectionsIssue(t, "cancel-still-working")+ seedInboxTask(t, f.issueID, f.followerID, "direct_human", "running", "")+ cancelled := seedInboxTask(t, f.issueID, f.followerID, "direct_human", "running", "")+ cancelInboxTask(t, cancelled, "member", f.followerID, "Starter")+ publishTaskEvent(bus, protocol.EventTaskCancelled, f.issueID, cancelled, nil)+ if rows := cancelledInboxRows(t, f.followerID, f.issueID); len(rows) != 0 {+ t.Fatalf("rows = %+v, want none while the other run is active", rows)+ }++ // That run is the follower's. For another member the issue is not+ // with the agent, so their cancelled run comes back.+ other := seedInboxTask(t, f.issueID, f.authorID, "direct_human", "running", "")+ cancelInboxTask(t, other, "system", "", "")+ publishTaskEvent(bus, protocol.EventTaskCancelled, f.issueID, other, nil)+ if rows := cancelledInboxRows(t, f.authorID, f.issueID); len(rows) != 1 {+ t.Fatalf("author: rows = %+v, want their cancelled run handed back", rows)+ }+ })+}++// A rerun or an edited comment cancels the pending run before queueing its+// replacement. The replacement's start takes the cancelled row out again, so+// the issue ends up under "Working" and not under "Needs you".+func TestInbox_RunCancelledThenRestartedLeavesNothing(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)+ f := newInboxSectionsIssue(t, "cancel-rerun")++ pending := seedInboxTask(t, f.issueID, f.followerID, "direct_human", "queued", "")+ cancelInboxTask(t, pending, "system", "", "")+ publishTaskEvent(bus, protocol.EventTaskCancelled, f.issueID, pending, nil)+ replacement := seedInboxTask(t, f.issueID, f.followerID, "direct_human", "queued", "")+ publishTaskEvent(bus, protocol.EventTaskQueued, f.issueID, replacement, nil)++ rows := cancelledInboxRows(t, f.followerID, f.issueID)+ if len(rows) != 1 || !rows[0].archived {+ t.Fatalf("rows = %+v, want the cancelled row archived by the new run", rows)+ }+}++func muteNotifications(t *testing.T, userID, preferences string) {+ t.Helper()+ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO notification_preference (workspace_id, user_id, preferences)+ VALUES ($1, $2, $3::jsonb)+ `, testWorkspaceID, userID, preferences); err != nil {+ t.Fatalf("seed notification preference: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM notification_preference WHERE user_id = $1`, userID)+ })+}++// A switched-off kind stops reaching the people who only follow the issue. The+// people who answer for it still get it: it is waiting on them.+func TestInbox_MutingSilencesUpdatesOnly(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)++ t.Run("comments", func(t *testing.T) {+ f := newInboxSectionsIssue(t, "mute-comments")+ muteNotifications(t, f.assigneeID, `{"comments":"muted"}`)+ muteNotifications(t, f.followerID, `{"comments":"muted"}`)++ publishSectionsComment(bus, f.issueID, f.authorID, "todo")++ wantSingleRow(t, "assignee", inboxRowsOnIssue(t, f.assigneeID, f.issueID), "new_comment", "needs_you")+ if rows := inboxRowsOnIssue(t, f.followerID, f.issueID); len(rows) != 0 {+ t.Fatalf("follower: rows = %+v, want none", rows)+ }+ })++ t.Run("status changes", func(t *testing.T) {+ f := newInboxSectionsIssue(t, "mute-status")+ muteNotifications(t, f.assigneeID, `{"status_changes":"muted"}`)+ muteNotifications(t, f.followerID, `{"status_changes":"muted"}`)++ // in_progress waits on nobody, so it is an update for the assignee too.+ publishStatusChange(bus, f.issueID, "in_progress", "todo")+ for who, id := range map[string]string{"assignee": f.assigneeID, "follower": f.followerID} {+ if rows := inboxRowsOnIssue(t, id, f.issueID); len(rows) != 0 {+ t.Fatalf("%s: rows = %+v after a status nobody waits on, want none", who, rows)+ }+ }++ publishStatusChange(bus, f.issueID, "in_review", "in_progress")+ wantSingleRow(t, "assignee", inboxRowsOnIssue(t, f.assigneeID, f.issueID), "status_changed", "needs_you")+ if rows := inboxRowsOnIssue(t, f.followerID, f.issueID); len(rows) != 0 {+ t.Fatalf("follower: rows = %+v, want none", rows)+ }+ })++ t.Run("agent activity", func(t *testing.T) {+ f := newInboxSectionsIssue(t, "mute-agent")+ muteNotifications(t, f.assigneeID, `{"agent_activity":"muted"}`)+ muteNotifications(t, f.followerID, `{"agent_activity":"muted"}`)+ muteNotifications(t, f.authorID, `{"agent_activity":"muted"}`)++ // The author started the run, so both its outcomes are theirs.+ failed := seedInboxTask(t, f.issueID, f.authorID, "direct_human", "failed", "")+ publishTaskEvent(bus, protocol.EventTaskFailed, f.issueID, failed, map[string]any{"retry_pending": false})+ wantSingleRow(t, "starter", inboxRowsOnIssue(t, f.authorID, f.issueID), "task_failed", "needs_you")+ wantSingleRow(t, "assignee", inboxRowsOnIssue(t, f.assigneeID, f.issueID), "task_failed", "needs_you")+ if rows := inboxRowsOnIssue(t, f.followerID, f.issueID); len(rows) != 0 {+ t.Fatalf("follower: rows = %+v, want none", rows)+ }++ completed := seedInboxTask(t, f.issueID, f.authorID, "direct_human", "completed", "")+ publishTaskEvent(bus, protocol.EventTaskCompleted, f.issueID, completed, nil)+ if active := activeInboxRows(inboxRowsOnIssue(t, f.authorID, f.issueID)); len(active) != 2 || active[1].notifType != "agent_completed" {+ t.Fatalf("starter: active rows = %+v, want the finished run handed back too", active)+ }+ })+}diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.goindex da71e49129..5d33f4ee0f 100644--- a/server/cmd/server/listeners.go+++ b/server/cmd/server/listeners.go@@ -120,6 +120,8 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster, audience ...privprotocol.EventInboxDeleted: true,protocol.EventInboxBatchRead: true,protocol.EventInboxBatchArchived: true,+ protocol.EventInboxSnoozed: true,+ protocol.EventInboxUnsnoozed: true,protocol.EventInvitationCreated: true,protocol.EventInvitationRevoked: true,protocol.EventIssueUnreadChanged: true,@@ -153,12 +155,13 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster, audience ...priv})// inbox:read, inbox:archived, inbox:unarchived, inbox:batch-read,- // inbox:batch-archived, issue_unread:changed — extract recipient from- // top-level payload+ // inbox:batch-archived, inbox:snoozed, inbox:unsnoozed,+ // issue_unread:changed — extract recipient from top-level payloadfor _, eventType := range []string{protocol.EventInboxRead, protocol.EventInboxArchived, protocol.EventInboxUnarchived,protocol.EventInboxDeleted,protocol.EventInboxBatchRead, protocol.EventInboxBatchArchived,+ protocol.EventInboxSnoozed, protocol.EventInboxUnsnoozed,protocol.EventIssueUnreadChanged,} {bus.Subscribe(eventType, func(e events.Event) {diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.goindex 0663abf04b..953cc91ee5 100644--- a/server/cmd/server/notification_listeners.go+++ b/server/cmd/server/notification_listeners.go@@ -3,9 +3,12 @@ package mainimport ("context""encoding/json"+ "errors""log/slog"+ "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/attribution""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/handler""github.com/multica-ai/multica/server/internal/inbox"@@ -91,17 +94,33 @@ func issueStatusIsHandoff(workspaceID pgtype.UUID,status string,) (bool, error) {+ handoff, _, err := issueStatusHandoff(ctx, queries, workspaceID, status)+ return handoff, err+}++// issueStatusHandoff answers issueStatusIsHandoff and, with the same catalog+// read, whether the status WAITS on a person: a started status other than+// in_progress (in review, blocked, a custom gate). done / closed are a handoff+// that waits on no one, which is what separates the two answers. The Inbox+// files a status change under "Needs you" only when it waits (MUL-9215).+func issueStatusHandoff(+ ctx context.Context,+ queries *db.Queries,+ workspaceID pgtype.UUID,+ status string,+) (handoff, waitsOnHuman bool, err error) {category, err := issuestatus.CategoryWithError(ctx, queries, workspaceID, status)if err != nil {- return false, err+ return false, false, err}switch category {case issuestatus.CategoryDone, issuestatus.CategoryClosed:- return true, nil+ return true, false, nilcase issuestatus.CategoryStarted:- return status != issuestatus.InProgress, nil+ waits := status != issuestatus.InProgress+ return waits, waits, nildefault:- return false, nil+ return false, false, nil}}@@ -136,15 +155,18 @@ func deliverToSubscriber(reason, notifType string, statusIsHandoff bool) bool {return statusIsHandoff}-// notifTypeToGroup maps each InboxItemType to a user-configurable preference-// group. Types not in this map are always delivered (not configurable).+// notifTypeToGroup maps each InboxItemType to the preference group that can+// switch it off. Types not in this map are always delivered (not configurable).+//+// A group only ever silences updates: see isNotifMuted. Mentions are not here,+// since their one choice is where a group mention is filed+// (groupMentionsAreUpdates).var notifTypeToGroup = map[string]string{"issue_assigned": "assignments","unassigned": "assignments","assignee_changed": "assignments","status_changed": "status_changes","new_comment": "comments",- "mentioned": "mentions","priority_changed": "updates","start_date_changed": "updates","due_date_changed": "updates",@@ -155,9 +177,17 @@ var notifTypeToGroup = map[string]string{"issue_created": "new_issues",}-// isNotifMuted returns true if the given notification type is muted for a user-// based on their parsed preferences map.-func isNotifMuted(prefs map[string]string, notifType string) bool {+// isNotifMuted returns true if the user switched this notification off, based+// on their parsed preferences map.+//+// Only an update can be switched off (MUL-9215). A row filed under "Needs you"+// is addressed to the user: a mention, an assignment, a run they started, or+// activity on an issue they created or are assigned. Dropping one would leave+// the issue waiting on them with nothing in their Inbox to say so.+func isNotifMuted(prefs map[string]string, notifType, section string) bool {+ if section != inbox.SectionUpdates {+ return false+ }group, ok := notifTypeToGroup[notifType]if !ok {return false // unconfigurable types are always delivered@@ -165,6 +195,17 @@ func isNotifMuted(prefs map[string]string, notifType string) bool {return prefs[group] == "muted"}+// groupMentionsAreUpdates reports whether the user asked for @all and @squad+// mentions to be filed as updates instead of under "Needs you". A mention by+// name is always addressed to them.+//+// The choice is stored under the `mentions` key, which used to switch every+// mention off. Whoever muted it keeps the quieter Inbox they asked for, and+// gets the mentions by name back.+func groupMentionsAreUpdates(prefs map[string]string) bool {+ return prefs["mentions"] == "muted"+}+// loadUserPrefs loads notification preferences for a set of user IDs in a// workspace. Returns a map from user_id string to parsed preferences.func loadUserPrefs(@@ -258,6 +299,308 @@ func archiveStaleTaskFailedInbox("row_count", len(rows), "recipient_count", len(counts))}+// publishInboxArchived tells each member whose rows were just archived, so+// connected clients drop the issue without a reload.+func publishInboxArchived(bus *events.Bus, workspaceID, issueID, reason string, counts map[string]int64) {+ for recipientID, count := range counts {+ bus.Publish(events.Event{+ Type: protocol.EventInboxBatchArchived,+ WorkspaceID: workspaceID,+ Payload: map[string]any{+ "recipient_id": recipientID,+ "count": count,+ "issue_id": issueID,+ "reason": reason,+ },+ })+ }+}++// memberStartedRun reports the member whose own action started this run, the+// one the Inbox lists it under "Working" for. Runs nobody started by hand+// (delegation, a reaction to an agent's comment, an autopilot) have none.+func memberStartedRun(task db.AgentTaskQueue) (string, bool) {+ if !task.OriginatorUserID.Valid || task.OriginatorSource.String != string(attribution.SourceDirectHuman) {+ return "", false+ }+ return util.UUIDToString(task.OriginatorUserID), true+}++// archiveInboxOnRunStart takes an issue out of a member's "Needs you" when+// their own action starts an agent run on it: the issue is with the agent now.+// The Inbox lists it under "Working" from the run itself, and it comes back+// through notifyRunEnded or the task:failed listener when the run ends. Runs+// the member did not start themselves leave the Inbox alone, and so does the+// retry of an earlier attempt, which is the same hand-over continuing.+func archiveInboxOnRunStart(ctx context.Context, queries *db.Queries, bus *events.Bus, e events.Event) {+ payload, ok := e.Payload.(map[string]any)+ if !ok {+ return+ }+ issueID, _ := payload["issue_id"].(string)+ taskID, _ := payload["task_id"].(string)+ issueUUID, err := util.ParseUUID(issueID)+ if err != nil {+ return+ }+ taskUUID, err := util.ParseUUID(taskID)+ if err != nil {+ return+ }+ task, err := queries.GetAgentTask(ctx, taskUUID)+ if err != nil {+ slog.Error("archive handed-over inbox: failed to get task", "task_id", taskID, "error", err)+ return+ }+ originator, ok := memberStartedRun(task)+ if !ok || task.RetryOfTaskID.Valid {+ return+ }+ count, err := queries.ArchiveInboxByIssue(ctx, db.ArchiveInboxByIssueParams{+ WorkspaceID: parseUUID(e.WorkspaceID),+ RecipientType: "member",+ RecipientID: task.OriginatorUserID,+ IssueID: issueUUID,+ })+ if err != nil {+ slog.Error("archive handed-over inbox: query failed",+ "workspace_id", e.WorkspaceID, "issue_id", issueID, "member_id", originator, "error", err)+ return+ }+ if count == 0 {+ return+ }+ publishInboxArchived(bus, e.WorkspaceID, issueID, "handed_to_agent", map[string]int64{originator: count})+}++// archiveInboxForClosedIssue takes an issue out of every Inbox once it reaches+// a done or cancelled status, whoever moved it there: nothing on it waits on+// anyone. The caller records the status change after this, so followers still+// get the one update saying the issue closed.+//+// FAIL CLOSED: an unresolved custom status keeps the rows, since hiding what+// waits on someone is worse than leaving it listed.+func archiveInboxForClosedIssue(ctx context.Context, queries *db.Queries, bus *events.Bus, workspaceID, issueID, status string) {+ category, err := issuestatus.CategoryWithError(ctx, queries, parseUUID(workspaceID), status)+ if err != nil {+ slog.Warn("resolve issue status category for inbox archive; keeping rows",+ "issue_id", issueID, "status", status, "error", err)+ return+ }+ if category != issuestatus.CategoryDone && category != issuestatus.CategoryClosed {+ return+ }+ rows, err := queries.ArchiveInboxByIssueForAll(ctx, db.ArchiveInboxByIssueForAllParams{+ WorkspaceID: parseUUID(workspaceID),+ IssueID: parseUUID(issueID),+ })+ if err != nil {+ slog.Error("archive closed-issue inbox: query failed",+ "workspace_id", workspaceID, "issue_id", issueID, "error", err)+ return+ }+ counts := map[string]int64{}+ for _, row := range rows {+ if row.RecipientType != "member" {+ continue+ }+ counts[util.UUIDToString(row.RecipientID)]+++ }+ publishInboxArchived(bus, workspaceID, issueID, "issue_closed", counts)+}++// runDetails names the run an inbox row reports.+func runDetails(taskID string) []byte {+ if taskID == "" {+ return emptyDetails+ }+ details, _ := json.Marshal(map[string]string{"task_id": taskID})+ return details+}++// notifyRunEnded hands an issue back to the member whose own action started+// the run, when the run completes: the row lands in their "Needs you" whether+// or not the agent mentioned them. Runs nobody started by hand leave people+// alone; whoever answers for the issue hears through the agent's comment or+// the status it sets.+func notifyRunEnded(ctx context.Context, queries *db.Queries, bus *events.Bus, e events.Event) {+ payload, ok := e.Payload.(map[string]any)+ if !ok {+ return+ }+ issueID, _ := payload["issue_id"].(string)+ taskID, _ := payload["task_id"].(string)+ agentID, _ := payload["agent_id"].(string)+ issueUUID, err := util.ParseUUID(issueID)+ if err != nil {+ return+ }+ taskUUID, err := util.ParseUUID(taskID)+ if err != nil {+ return+ }+ task, err := queries.GetAgentTask(ctx, taskUUID)+ if err != nil {+ slog.Error("run ended notification: failed to get task", "task_id", taskID, "error", err)+ return+ }+ originator, ok := memberStartedRun(task)+ if !ok {+ return+ }+ issue, err := queries.GetIssue(ctx, issueUUID)+ if err != nil {+ slog.Error("run ended notification: failed to get issue", "issue_id", issueID, "error", err)+ return+ }+ // A run that closed the issue has nothing to hand back: the status change+ // already told everyone. An unresolved custom status still hands back,+ // since a spare row costs one archive and a missing one strands the issue.+ if category, err := issuestatus.CategoryWithError(ctx, queries, issue.WorkspaceID, issue.Status); err == nil &&+ (category == issuestatus.CategoryDone || category == issuestatus.CategoryClosed) {+ return+ }+ notifyDirect(ctx, queries, bus,+ "member", originator,+ e.WorkspaceID,+ events.Event{Type: e.Type, WorkspaceID: e.WorkspaceID, ActorType: "agent", ActorID: agentID},+ issueID, issue.Status,+ "agent_completed", "action_required",+ issue.Title, "",+ runDetails(taskID),+ )+}++// notifyRunCancelled hands an issue back to the member whose own action+// started a run that was then cancelled. Without it the issue leaves "Working"+// and appears nowhere: the run's start archived what the member had on it, and+// a cancelled run reports nothing else.+//+// The row is read when the member stopped the run themselves, since it tells+// them nothing new, and unread when someone else or the system did. It names+// who in its details.+//+// Nothing is handed back when the issue is not coming back to the member: it+// is being deleted, it is closed, or another run they started on it is still+// active. A rerun or an edited comment cancels the pending run before queueing+// its replacement, so the row is written and the replacement's task:queued+// archives it again (archiveInboxOnRunStart).+func notifyRunCancelled(ctx context.Context, queries *db.Queries, bus *events.Bus, e events.Event) {+ payload, ok := e.Payload.(map[string]any)+ if !ok {+ return+ }+ // A replay re-announces a run that was already handed back, and a deleted+ // issue takes its Inbox rows with it.+ if replay, _ := payload["replay"].(bool); replay {+ return+ }+ if deleted, _ := payload["issue_deleted"].(bool); deleted {+ return+ }+ issueID, _ := payload["issue_id"].(string)+ taskID, _ := payload["task_id"].(string)+ issueUUID, err := util.ParseUUID(issueID)+ if err != nil {+ return+ }+ taskUUID, err := util.ParseUUID(taskID)+ if err != nil {+ return+ }+ task, err := queries.GetAgentTask(ctx, taskUUID)+ if err != nil {+ slog.Error("run cancelled notification: failed to get task", "task_id", taskID, "error", err)+ return+ }+ originator, ok := memberStartedRun(task)+ if !ok {+ return+ }+ issue, err := queries.GetIssue(ctx, issueUUID)+ if err != nil {+ if !errors.Is(err, pgx.ErrNoRows) {+ slog.Error("run cancelled notification: failed to get issue", "issue_id", issueID, "error", err)+ }+ return+ }+ // Same rule as notifyRunEnded: an unresolved custom status still hands back.+ if category, err := issuestatus.CategoryWithError(ctx, queries, issue.WorkspaceID, issue.Status); err == nil &&+ (category == issuestatus.CategoryDone || category == issuestatus.CategoryClosed) {+ return+ }+ stillWorking, err := queries.HasOtherActiveRunStartedByMember(ctx, db.HasOtherActiveRunStartedByMemberParams{+ IssueID: issueUUID,+ TaskID: taskUUID,+ OriginatorUserID: task.OriginatorUserID,+ })+ if err != nil {+ slog.Error("run cancelled notification: failed to check active runs", "issue_id", issueID, "error", err)+ return+ }+ if stillWorking {+ return+ }++ details := map[string]string{"task_id": taskID}+ cancelledByID := ""+ if task.CancelledByType.Valid {+ details["cancelled_by_type"] = task.CancelledByType.String+ }+ if task.CancelledByID.Valid {+ cancelledByID = util.UUIDToString(task.CancelledByID)+ details["cancelled_by_id"] = cancelledByID+ }+ if task.CancelledByName.Valid {+ details["cancelled_by_name"] = task.CancelledByName.String+ }+ detailsJSON, _ := json.Marshal(details)+ stoppedByMember := task.CancelledByType.String == "member" && cancelledByID == originator++ agentID := util.UUIDToString(task.AgentID)+ item, inserted, err := inbox.CreateIfEligible(ctx, queries, db.CreateInboxItemParams{+ ID: dbid.NewV7(),+ WorkspaceID: parseUUID(e.WorkspaceID),+ RecipientType: "member",+ RecipientID: task.OriginatorUserID,+ Type: "task_cancelled",+ Severity: "info",+ IssueID: issueUUID,+ Title: issue.Title,+ ActorType: util.StrToText("agent"),+ ActorID: optionalUUID(agentID),+ Details: detailsJSON,+ Read: pgtype.Bool{Bool: stoppedByMember, Valid: true},+ })+ if err != nil {+ slog.Error("run cancelled notification: creation failed",+ "issue_id", issueID, "recipient_id", originator, "error", err)+ return+ }+ if !inserted {+ return+ }+ resp := inboxItemToResponse(item)+ resp["issue_status"] = issue.Status+ bus.Publish(events.Event{+ Type: protocol.EventInboxNew,+ WorkspaceID: e.WorkspaceID,+ ActorType: "agent",+ ActorID: agentID,+ Payload: map[string]any{"item": resp},+ })+}++// memberAnswersForIssue reports whether the member created the issue or has it+// assigned: the two relations that make what happens on it theirs to handle.+func memberAnswersForIssue(issue db.Issue, memberID string) bool {+ if issue.CreatorType == "member" && util.UUIDToString(issue.CreatorID) == memberID {+ return true+ }+ return issue.AssigneeType.String == "member" && issue.AssigneeID.Valid &&+ util.UUIDToString(issue.AssigneeID) == memberID+}+// notifySubscribers queries the subscriber table for an issue, excludes the// actor and any extra IDs, and creates inbox items for each remaining member// subscriber. Publishes an inbox:new event for each notification.@@ -405,11 +748,13 @@ func notifyProjectSubscribers(userPrefs := loadUserPrefs(ctx, queries, workspaceID, recipients)for _, subID := range recipients {- if prefs, ok := userPrefs[subID]; ok && isNotifMuted(prefs, notifType) {+ if prefs, ok := userPrefs[subID]; ok && isNotifMuted(prefs, notifType, inbox.SectionUpdates) {continue}+ // Watching a project is following it: whoever answers for the issue+ // was reached through its own subscribers first and is excluded here.createMemberInboxItem(ctx, queries, bus, subID, workspaceID, e, issueID, issueStatus,- notifType, severity, title, body, details)+ notifType, severity, title, body, details, inbox.SectionUpdates)}}@@ -429,6 +774,7 @@ func createMemberInboxItem(title string,body string,details []byte,+ section string,) bool {item, inserted, err := inbox.CreateIfEligible(ctx, queries, db.CreateInboxItemParams{ID: dbid.NewV7(),@@ -443,6 +789,7 @@ func createMemberInboxItem(ActorType: util.StrToText(e.ActorType),ActorID: optionalUUID(e.ActorID),Details: details,+ Section: util.StrToText(section),})if err != nil {slog.Error("member notification creation failed",@@ -500,11 +847,24 @@ func notifyIssueSubscribers(// outcomes are not symmetric: a spare inbox row costs one dismissal, while// a dropped one silently strands the issue on a status whose whole purpose// is to be waited on, with no other signal to the delegated subscriber.- statusIsHandoff, err := issueStatusIsHandoff(ctx, queries, parseUUID(workspaceID), issueStatus)+ //+ // The same direction decides the section: on a failed read the status is+ // taken to wait on a person, so the row lands in "Needs you".+ statusIsHandoff, statusWaitsOnHuman, err := issueStatusHandoff(ctx, queries, parseUUID(workspaceID), issueStatus)if err != nil {slog.Warn("resolve issue status handoff for delegated delivery; delivering","issue_id", subscriberIssueID, "status", issueStatus, "error", err)statusIsHandoff = true+ statusWaitsOnHuman = true+ }++ // Who answers for the issue the notification points at decides its Inbox+ // section. FAIL OPEN again: without the issue, every recipient is treated+ // as answering for it.+ targetIssue, targetIssueErr := queries.GetIssue(ctx, parseUUID(targetIssueID))+ if targetIssueErr != nil {+ slog.Warn("load issue for inbox section; filing under needs you",+ "issue_id", targetIssueID, "error", targetIssueErr)}subs, err := queries.ListIssueSubscribers(ctx, parseUUID(subscriberIssueID))@@ -541,8 +901,14 @@ func notifyIssueSubscribers(continue}- // Skip if this notification type is muted by the user- if prefs, ok := userPrefs[subID]; ok && isNotifMuted(prefs, notifType) {+ // A delegated subscription means an agent filed the issue on this+ // member's behalf, so it is theirs as much as one they created.+ addressed := sub.Reason == "delegated" || targetIssueErr != nil ||+ memberAnswersForIssue(targetIssue, subID)+ section := inbox.SubscriberSection(notifType, addressed, statusWaitsOnHuman)++ // Skip if the user switched this kind of update off+ if prefs, ok := userPrefs[subID]; ok && isNotifMuted(prefs, notifType, section) {continue}@@ -554,7 +920,7 @@ func notifyIssueSubscribers(}if createMemberInboxItem(ctx, queries, bus, subID, workspaceID, e, targetIssueID, issueStatus,- notifType, severity, title, body, details) {+ notifType, severity, title, body, details, section) {notified[subID] = true}}@@ -585,10 +951,11 @@ func notifyDirect(return}- // Check notification preferences for member recipients.- if recipientType == "member" {+ // Check notification preferences for member recipients. The row is filed+ // by its type (inbox.CreateIfEligible), and only an update can be muted.+ if section := inbox.DefaultSection(notifType); recipientType == "member" && section == inbox.SectionUpdates {prefs := loadUserPrefs(ctx, queries, workspaceID, []string{recipientID})- if p, ok := prefs[recipientID]; ok && isNotifMuted(p, notifType) {+ if p, ok := prefs[recipientID]; ok && isNotifMuted(p, notifType, section) {return}}@@ -642,7 +1009,8 @@ func notifyMentionedMembers(skip map[string]bool,details []byte,) {- // Collect the set of member IDs to notify.+ // Collect the set of member IDs to notify. The value records whether the+ // member was mentioned by name, rather than only through @all or a squad.recipientIDs := map[string]bool{}hasAll := false@@ -677,8 +1045,8 @@ func notifyMentionedMembers(continue}for _, sm := range members {- if sm.MemberType == "member" {- recipientIDs[util.UUIDToString(sm.MemberID)] = true+ if id := util.UUIDToString(sm.MemberID); sm.MemberType == "member" && !recipientIDs[id] {+ recipientIDs[id] = false}}}@@ -690,7 +1058,9 @@ func notifyMentionedMembers(slog.Error("failed to list members for @all mention", "workspace_id", e.WorkspaceID, "error", err)} else {for _, m := range members {- recipientIDs[util.UUIDToString(m.UserID)] = true+ if id := util.UUIDToString(m.UserID); !recipientIDs[id] {+ recipientIDs[id] = false+ }}}}@@ -704,15 +1074,16 @@ func notifyMentionedMembers(}mentionPrefs := loadUserPrefs(context.Background(), queries, e.WorkspaceID, mentionUserIDs)- for id := range recipientIDs {+ for id, byName := range recipientIDs {if id == e.ActorID || skip[id] {continue}- // Skip if mentions are muted by this user. This is deliberately a- // different group from `comments`: muting comment volume must not- // silence someone asking for you by name.- if p, ok := mentionPrefs[id]; ok && isNotifMuted(p, "mentioned") {- continue+ // A mention is never dropped. One that reached the member only through+ // @all or a squad is an update when they asked for that; everything+ // else is addressed to them.+ section := inbox.SectionNeedsYou+ if p, ok := mentionPrefs[id]; ok && !byName && groupMentionsAreUpdates(p) {+ section = inbox.SectionUpdates}item, inserted, err := inbox.CreateIfEligible(context.Background(), queries, db.CreateInboxItemParams{ID: dbid.NewV7(),@@ -726,6 +1097,7 @@ func notifyMentionedMembers(ActorType: util.StrToText(e.ActorType),ActorID: optionalUUID(e.ActorID),Details: details,+ Section: util.StrToText(section),})if err != nil {slog.Error("mention inbox creation failed", "mentioned_id", id, "error", err)@@ -888,6 +1260,9 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {"from": prevStatus,"to": issue.Status,})+ // A done or cancelled issue leaves every Inbox before the change is+ // recorded, so what remains is the one update saying it closed.+ archiveInboxForClosedIssue(ctx, queries, bus, e.WorkspaceID, issue.ID, issue.Status)notifySubscribers(ctx, queries, bus, issue.ID, issue.Status, e.WorkspaceID, e,nil, "status_changed", "info",issue.Title, "",@@ -1126,16 +1501,34 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {)})- // task:completed — no inbox notification (completion is visible from status change)+ // task:queued — the member who started the run has handed the issue over+ bus.Subscribe(protocol.EventTaskQueued, func(e events.Event) {+ archiveInboxOnRunStart(ctx, queries, bus, e)+ })++ // task:completed — hand the issue back to the member who started the run+ bus.Subscribe(protocol.EventTaskCompleted, func(e events.Event) {+ notifyRunEnded(ctx, queries, bus, e)+ })++ // task:cancelled — hand the issue back to the member who started the run+ bus.Subscribe(protocol.EventTaskCancelled, func(e events.Event) {+ notifyRunCancelled(ctx, queries, bus, e)+ })- // task:failed — notify all subscribers except the agent+ // task:failed — notify all subscribers except the agent, once the failure+ // is final: an attempt with a retry pending has not ended the run.bus.Subscribe(protocol.EventTaskFailed, func(e events.Event) {payload, ok := e.Payload.(map[string]any)if !ok {return}+ if retryPending, _ := payload["retry_pending"].(bool); retryPending {+ return+ }agentID, _ := payload["agent_id"].(string)issueID, _ := payload["issue_id"].(string)+ taskID, _ := payload["task_id"].(string)if issueID == "" {return}@@ -1150,17 +1543,37 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {if agentID != "" {exclude[agentID] = true}+ agentEvent := events.Event{+ Type: e.Type,+ WorkspaceID: e.WorkspaceID,+ ActorType: "agent",+ ActorID: agentID,+ }+ details := runDetails(taskID)++ // The member who started the run gets it back in "Needs you" whatever+ // their relation to the issue. Everyone else is filed by that relation+ // in the subscriber fan-out.+ if taskUUID, err := util.ParseUUID(taskID); err == nil {+ if task, err := queries.GetAgentTask(ctx, taskUUID); err != nil {+ slog.Error("task:failed notification: failed to get task", "task_id", taskID, "error", err)+ } else if originator, ok := memberStartedRun(task); ok {+ notifyDirect(ctx, queries, bus,+ "member", originator,+ e.WorkspaceID, agentEvent, issueID, issue.Status,+ "task_failed", "action_required",+ issue.Title, "",+ details,+ )+ exclude[originator] = true+ }+ }notifySubscribers(ctx, queries, bus, issueID, issue.Status, e.WorkspaceID,- events.Event{- Type: e.Type,- WorkspaceID: e.WorkspaceID,- ActorType: "agent",- ActorID: agentID,- },+ agentEvent,exclude, "task_failed", "action_required",issue.Title, "",- emptyDetails)+ details)})}@@ -1183,5 +1596,7 @@ func inboxItemToResponse(item db.InboxItem) map[string]any {"actor_type": util.TextToPtr(item.ActorType),"actor_id": util.UUIDToPtr(item.ActorID),"details": json.RawMessage(item.Details),+ "section": inbox.EffectiveSection(item.Section, item.Type, item.Read),+ "snoozed_until": util.TimestampToPtr(item.SnoozedUntil),}}diff --git a/server/cmd/server/notification_listeners_test.go b/server/cmd/server/notification_listeners_test.goindex 465048c12b..2579f42da6 100644--- a/server/cmd/server/notification_listeners_test.go+++ b/server/cmd/server/notification_listeners_test.go@@ -656,8 +656,11 @@ func TestNotification_AssigneeChanged(t *testing.T) {}}-// TestNotification_TaskCompleted verifies that task:completed events do NOT-// create inbox notifications (completion is visible from the status change).+// TestNotification_TaskCompleted verifies that a task:completed event for a+// run no member started by hand does NOT create inbox notifications: whoever+// answers for the issue hears through the agent's comment or the status it+// sets. The hand-back to a member who did start the run is covered in+// inbox_sections_test.go.func TestNotification_TaskCompleted(t *testing.T) {queries := db.New(testPool)bus := newNotificationBus(t, queries)@@ -688,7 +691,7 @@ func TestNotification_TaskCompleted(t *testing.T) {},})- // No inbox notification should be created for task:completed+ // No inbox notification should be created for this task:completedcreatorItems := inboxItemsForRecipient(t, queries, testUserID)if len(creatorItems) != 0 {t.Fatalf("expected 0 inbox items for creator on task:completed, got %d", len(creatorItems))diff --git a/server/cmd/server/notification_mentions_test.go b/server/cmd/server/notification_mentions_test.goindex d20961f6a2..2b7b5fb079 100644--- a/server/cmd/server/notification_mentions_test.go+++ b/server/cmd/server/notification_mentions_test.go@@ -82,19 +82,44 @@ func TestNotification_MalformedMemberMentionPreservesValidRecipients(t *testing.if items[0].Type != "mentioned" || util.UUIDToString(items[0].IssueID) != issueID {t.Fatalf("unexpected mention inbox item: %+v", items[0])}+ if items[0].Section.String != "needs_you" {+ t.Fatalf("mention section = %q, want needs_you", items[0].Section.String)+ }var details map[string]stringif err := json.Unmarshal(items[0].Details, &details); err != nil || details["comment_id"] != commentID {t.Fatalf("mention details = %s, error = %v; want comment_id %s", items[0].Details, err, commentID)}- if count := fx.Count(t, `SELECT count(*) FROM inbox_item WHERE issue_id = $1`, issueID); count != 1 {- t.Fatalf("issue has %d inbox items, want only the valid, unmuted recipient", count)+ // A mention is never dropped (MUL-9215). The member who asked for+ // group mentions to be updates gets one by name under "Needs you"+ // like anyone else, and one through @all as an update.+ mutedItems := inboxItemsForRecipient(t, queries, mutedID)+ wantMutedSection := "needs_you"+ if tc.mentionAll {+ wantMutedSection = "updates"+ }+ if len(mutedItems) != 1 || mutedItems[0].Type != "mentioned" || mutedItems[0].Section.String != wantMutedSection {+ t.Fatalf("muted recipient's items = %+v, want one mention in %s", mutedItems, wantMutedSection)+ }+ if count := fx.Count(t, `SELECT count(*) FROM inbox_item WHERE issue_id = $1`, issueID); count != 2 {+ t.Fatalf("issue has %d inbox items, want one per valid recipient", count)}- if len(inboxEvents) != 1 {- t.Fatalf("got %d inbox:new events, want 1", len(inboxEvents))+ if len(inboxEvents) != 2 {+ t.Fatalf("got %d inbox:new events, want 2", len(inboxEvents))}- item := inboxEvents[0].Payload.(map[string]any)["item"].(map[string]any)- if item["recipient_id"] != recipientID || item["type"] != "mentioned" || item["issue_status"] != "todo" {- t.Fatalf("unexpected inbox:new item: %+v", item)+ for _, e := range inboxEvents {+ item := e.Payload.(map[string]any)["item"].(map[string]any)+ if item["type"] != "mentioned" || item["issue_status"] != "todo" {+ t.Fatalf("unexpected inbox:new item: %+v", item)+ }+ wantSection := "needs_you"+ if item["recipient_id"] == mutedID {+ wantSection = wantMutedSection+ } else if item["recipient_id"] != recipientID {+ t.Fatalf("inbox:new for an unexpected recipient: %+v", item)+ }+ if item["section"] != wantSection {+ t.Fatalf("inbox:new section = %v, want %s: %+v", item["section"], wantSection, item)+ }}})}diff --git a/server/cmd/server/notification_mute_group_test.go b/server/cmd/server/notification_mute_group_test.goindex d50a6673fb..92d8aee5d6 100644--- a/server/cmd/server/notification_mute_group_test.go+++ b/server/cmd/server/notification_mute_group_test.go@@ -1,47 +1,69 @@package main-import "testing"--// TestIsNotifMutedGroupSplit pins the contract the `mentions` group exists for:-// muting comment VOLUME must never silence someone asking for you BY NAME.-// `new_comment` and `mentioned` shared the `comments` group until #6468, so a-// user who muted comment churn also lost every mention — and a muted item is-// never created, so it was unrecoverable rather than merely delayed.-func TestIsNotifMutedGroupSplit(t *testing.T) {+import (+ "testing"++ "github.com/multica-ai/multica/server/internal/inbox"+)++// TestIsNotifMuted pins what a preference group can switch off: an update, and+// never a row addressed to the member (MUL-9215). A muted row is never created,+// so muting one that waits on the member would strand the issue with nothing in+// their Inbox to say so.+func TestIsNotifMuted(t *testing.T) {cases := []struct {name stringprefs map[string]stringnotifType string+ section stringwant bool}{- // The regression this split fixes.- {"muted comments still delivers mentions", map[string]string{"comments": "muted"}, "mentioned", false},- {"muted comments drops new_comment", map[string]string{"comments": "muted"}, "new_comment", true},- {"muted mentions drops mentioned", map[string]string{"mentions": "muted"}, "mentioned", true},- {"muted mentions still delivers new_comment", map[string]string{"mentions": "muted"}, "new_comment", false},- {"both muted drops both", map[string]string{"comments": "muted", "mentions": "muted"}, "mentioned", true},-- // Absent key means the default "all" — preferences are stored sparse,- // which is why existing `{"comments":"muted"}` rows need no migration.- {"empty prefs delivers mentions", map[string]string{}, "mentioned", false},- {"empty prefs delivers comments", map[string]string{}, "new_comment", false},- {"explicit all delivers", map[string]string{"comments": "all"}, "new_comment", false},-- // Other groups are unaffected by the split.- {"assignments group intact", map[string]string{"assignments": "muted"}, "issue_assigned", true},- {"status group intact", map[string]string{"status_changes": "muted"}, "status_changed", true},- {"muting comments leaves assignments alone", map[string]string{"comments": "muted"}, "issue_assigned", false},+ {"muted comments drops a comment on a followed issue", map[string]string{"comments": "muted"}, "new_comment", inbox.SectionUpdates, true},+ {"muted comments keeps a comment on the member's own issue", map[string]string{"comments": "muted"}, "new_comment", inbox.SectionNeedsYou, false},+ {"muted status drops a status change on a followed issue", map[string]string{"status_changes": "muted"}, "status_changed", inbox.SectionUpdates, true},+ {"muted status keeps a status that waits on the member", map[string]string{"status_changes": "muted"}, "status_changed", inbox.SectionNeedsYou, false},+ {"muted assignments drops a reassignment", map[string]string{"assignments": "muted"}, "assignee_changed", inbox.SectionUpdates, true},+ {"muted assignments keeps an assignment to the member", map[string]string{"assignments": "muted"}, "issue_assigned", inbox.SectionNeedsYou, false},+ {"muted agent activity drops a failed run on a followed issue", map[string]string{"agent_activity": "muted"}, "task_failed", inbox.SectionUpdates, true},+ {"muted agent activity keeps the member's own failed run", map[string]string{"agent_activity": "muted"}, "task_failed", inbox.SectionNeedsYou, false},++ // Groups stay separate: muting comment volume leaves the rest alone.+ {"muted comments leaves status changes alone", map[string]string{"comments": "muted"}, "status_changed", inbox.SectionUpdates, false},++ // A mention is never dropped; `mentions` only says where a group+ // mention is filed (groupMentionsAreUpdates).+ {"mentions is not a mute group", map[string]string{"mentions": "muted"}, "mentioned", inbox.SectionUpdates, false},++ // Absent key means the default "all" — preferences are stored sparse.+ {"empty prefs delivers", map[string]string{}, "new_comment", inbox.SectionUpdates, false},+ {"explicit all delivers", map[string]string{"comments": "all"}, "new_comment", inbox.SectionUpdates, false},// Types outside the map are always delivered.- {"unconfigurable type always delivered", map[string]string{"comments": "muted"}, "reaction_added", false},+ {"unconfigurable type always delivered", map[string]string{"comments": "muted"}, "reaction_added", inbox.SectionUpdates, false},}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {- if got := isNotifMuted(tc.prefs, tc.notifType); got != tc.want {- t.Fatalf("isNotifMuted(%v, %q) = %v, want %v",- tc.prefs, tc.notifType, got, tc.want)+ if got := isNotifMuted(tc.prefs, tc.notifType, tc.section); got != tc.want {+ t.Fatalf("isNotifMuted(%v, %q, %q) = %v, want %v",+ tc.prefs, tc.notifType, tc.section, got, tc.want)}})}}++func TestGroupMentionsAreUpdates(t *testing.T) {+ for _, tc := range []struct {+ prefs map[string]string+ want bool+ }{+ {map[string]string{}, false},+ {map[string]string{"mentions": "all"}, false},+ {map[string]string{"mentions": "muted"}, true},+ {map[string]string{"comments": "muted"}, false},+ } {+ if got := groupMentionsAreUpdates(tc.prefs); got != tc.want {+ t.Fatalf("groupMentionsAreUpdates(%v) = %v, want %v", tc.prefs, got, tc.want)+ }+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 330a7265b2..7ef9b99551 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2657,6 +2657,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/archive-all", h.ArchiveAllInbox)r.Post("/archive-all-read", h.ArchiveAllReadInbox)r.Post("/archive-completed", h.ArchiveCompletedInbox)+ // The updates the member read or cleared (MUL-9215).+ r.Post("/archive-updates", h.ArchiveInboxUpdates)// Every unread notification on one issue, for reading the issue// outside the inbox (MUL-8588).r.Post("/issues/{issueId}/read", h.MarkIssueInboxRead)@@ -2664,6 +2666,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/{id}/unread", h.MarkInboxUnread)r.Post("/{id}/archive", h.ArchiveInboxItem)r.Post("/{id}/unarchive", h.UnarchiveInboxItem)+ r.Post("/{id}/snooze", h.SnoozeInboxItem)+ r.Post("/{id}/unsnooze", h.UnsnoozeInboxItem)r.Delete("/{id}", h.DeleteInboxItem)})diff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.goindex 9ad39f3557..16a8fa84df 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -5,9 +5,12 @@ import ("encoding/json""log/slog""net/http"+ "sort"+ "time""github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/inbox""github.com/multica-ai/multica/server/internal/logger"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -39,6 +42,13 @@ type InboxItemResponse struct {ActorType *string `json:"actor_type"`ActorID *string `json:"actor_id"`Details json.RawMessage `json:"details"`+ // Section is the Inbox section the row belongs to: "needs_you" when it is+ // addressed to the recipient, "updates" when they only follow the issue+ // (inbox.EffectiveSection).+ Section string `json:"section"`+ // SnoozedUntil is when a snoozed row comes back. A time in the past means+ // it already has.+ SnoozedUntil *string `json:"snoozed_until"`}func inboxToResponse(i db.InboxItem) InboxItemResponse {@@ -58,6 +68,8 @@ func inboxToResponse(i db.InboxItem) InboxItemResponse {ActorType: textToPtr(i.ActorType),ActorID: uuidToPtr(i.ActorID),Details: json.RawMessage(i.Details),+ Section: inbox.EffectiveSection(i.Section, i.Type, i.Read),+ SnoozedUntil: timestampToPtr(i.SnoozedUntil),}}@@ -141,6 +153,8 @@ func inboxRowToResponse(r db.ListInboxItemsRow) InboxItemResponse {ActorType: textToPtr(r.ActorType),ActorID: uuidToPtr(r.ActorID),Details: json.RawMessage(r.Details),+ Section: inbox.EffectiveSection(r.Section, r.Type, r.Read),+ SnoozedUntil: timestampToPtr(r.SnoozedUntil),}}@@ -213,9 +227,18 @@ func (h *Handler) ListInbox(w http.ResponseWriter, r *http.Request) {return}- resp := make([]InboxItemResponse, len(items))- for i, item := range items {- resp[i] = inboxRowToResponse(item)+ // A snoozed row is out of the Inbox until its time passes. A client that+ // shows the Snoozed section asks for those rows; one that predates it gets+ // the list without them, so a snoozed issue is hidden there too instead of+ // sitting in its inbox as unread.+ includeSnoozed := r.URL.Query().Get("include_snoozed") == "true"+ now := time.Now()+ resp := make([]InboxItemResponse, 0, len(items))+ for _, item := range items {+ if !includeSnoozed && item.SnoozedUntil.Valid && item.SnoozedUntil.Time.After(now) {+ continue+ }+ resp = append(resp, inboxRowToResponse(item))}writeJSON(w, http.StatusOK, resp)@@ -384,9 +407,11 @@ func (h *Handler) ArchiveInboxItem(w http.ResponseWriter, r *http.Request) {// one item archives every sibling for the same issue, so restoring brings the// whole group back.//-// `read` is untouched on purpose. An item archived while unread comes back-// unread, which raises the unread badge again — the badge only ever counted-// non-archived items, so restoring one is a real addition, not a bug.+// `read` is untouched on purpose for an issue that needs the member. An item+// archived while unread comes back unread, which raises the unread badge again+// — the badge only ever counted non-archived items, so restoring one is a real+// addition, not a bug. An update comes back unread whatever it was: see+// MarkRestoredInboxUpdateUnread.func (h *Handler) UnarchiveInboxItem(w http.ResponseWriter, r *http.Request) {id := chi.URLParam(r, "id")prev, ok := h.loadInboxItemForUser(w, r, id)@@ -409,6 +434,17 @@ func (h *Handler) UnarchiveInboxItem(w http.ResponseWriter, r *http.Request) {})}+ if flipped, err := h.Queries.MarkRestoredInboxUpdateUnread(r.Context(), db.MarkRestoredInboxUpdateUnreadParams{+ ID: item.ID,+ NeedsYouTypes: inbox.NeedsYouTypes,+ }); err != nil {+ slog.Warn("inbox: mark restored update unread failed", append(logger.RequestAttrs(r), "item_id", id, "error", err)...)+ } else if flipped > 0 {+ if fresh, err := h.Queries.GetInboxItem(r.Context(), item.ID); err == nil {+ item = fresh+ }+ }+userID := requestUserID(r)workspaceID := uuidToString(item.WorkspaceID)h.publish(protocol.EventInboxUnarchived, workspaceID, "member", userID, map[string]any{@@ -450,42 +486,169 @@ func (h *Handler) CountUnreadInbox(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, map[string]int64{"count": count})}-// InboxWorkspaceUnreadResponse is one workspace's unread inbox count in the+// InboxWorkspaceUnreadResponse is one workspace's inbox counts in the// cross-workspace summary.type InboxWorkspaceUnreadResponse struct {WorkspaceID string `json:"workspace_id"`- Count int64 `json:"count"`+ // Count is the number of unread issues. Clients that predate the sectioned+ // Inbox show it as their badge, so its meaning does not change.+ Count int64 `json:"count"`+ // NeedsYou is the number of issues waiting on the user, read or not: the+ // rows of the Inbox's "Needs you" section, and the badge of a client that+ // shows it (MUL-9215).+ NeedsYou int64 `json:"needs_you"`+ // NextWakeAt is when the workspace's next snoozed issue comes back, RFC+ // 3339, or absent with none. The counts leave snoozed issues out and+ // nothing is sent when a snooze runs out, so a client re-reads the+ // summary then.+ NextWakeAt *string `json:"next_wake_at,omitempty"`}-// UnreadInboxSummary returns per-workspace unread inbox counts across every-// workspace the user belongs to. The sidebar uses it to light a dot on the-// workspace switcher when a workspace OTHER than the active one has unread-// items, without fetching each workspace's full inbox list. It is-// account-level by nature: it ignores the active workspace and keys only on-// the authenticated user.+// UnreadInboxSummary returns per-workspace inbox counts across every workspace+// the user belongs to. The rail badge and the workspace switcher dot read it+// without fetching each workspace's full inbox list. It is account-level by+// nature: it ignores the active workspace and keys only on the authenticated+// user. A workspace appears when either count is above zero or it has a+// snoozed issue still to come back.func (h *Handler) UnreadInboxSummary(w http.ResponseWriter, r *http.Request) {userID, ok := requireUserID(w, r)if !ok {return}- rows, err := h.Queries.CountUnreadInboxByWorkspace(r.Context(), parseUUID(userID))+ unread, err := h.Queries.CountUnreadInboxByWorkspace(r.Context(), parseUUID(userID))if err != nil {writeError(w, http.StatusInternalServerError, "failed to summarize unread inbox")return}+ needsYou, err := h.Queries.CountNeedsYouInboxByWorkspace(r.Context(), db.CountNeedsYouInboxByWorkspaceParams{+ RecipientID: parseUUID(userID),+ NeedsYouTypes: inbox.NeedsYouTypes,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to summarize inbox")+ return+ }+ wakes, err := h.Queries.NextInboxWakeByWorkspace(r.Context(), parseUUID(userID))+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to summarize inbox")+ return+ }- resp := make([]InboxWorkspaceUnreadResponse, len(rows))- for i, row := range rows {- resp[i] = InboxWorkspaceUnreadResponse{- WorkspaceID: uuidToString(row.WorkspaceID),- Count: row.Count,+ byWorkspace := make(map[string]*InboxWorkspaceUnreadResponse, len(unread)+len(needsYou))+ entry := func(workspaceID pgtype.UUID) *InboxWorkspaceUnreadResponse {+ id := uuidToString(workspaceID)+ if byWorkspace[id] == nil {+ byWorkspace[id] = &InboxWorkspaceUnreadResponse{WorkspaceID: id}}+ return byWorkspace[id]+ }+ for _, row := range unread {+ entry(row.WorkspaceID).Count = row.Count+ }+ for _, row := range needsYou {+ entry(row.WorkspaceID).NeedsYou = row.Count+ }+ for _, row := range wakes {+ entry(row.WorkspaceID).NextWakeAt = timestampToPtr(row.NextWakeAt)+ }++ resp := make([]InboxWorkspaceUnreadResponse, 0, len(byWorkspace))+ for _, summary := range byWorkspace {+ resp = append(resp, *summary)}+ sort.Slice(resp, func(i, j int) bool { return resp[i].WorkspaceID < resp[j].WorkspaceID })writeJSON(w, http.StatusOK, resp)}+// inboxSnoozeMaxDuration bounds how far ahead an issue can be snoozed. The+// picker offers hours to days; a year is far past any of it and keeps a typo+// or a clock gone wrong from parking an issue for good.+const inboxSnoozeMaxDuration = 366 * 24 * time.Hour++type SnoozeInboxRequest struct {+ // Until is when the issue comes back, RFC 3339.+ Until string `json:"until"`+}++// SnoozeInboxItem takes an issue out of the Inbox until a time the member+// picks. It is issue-level, like archiving: every active row the member has on+// the item's issue is snoozed with it. The issue comes back when the time+// passes, or earlier when something new is addressed to the member: a row+// written after the snooze carries no wake time.+func (h *Handler) SnoozeInboxItem(w http.ResponseWriter, r *http.Request) {+ item, ok := h.loadInboxItemForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ var req SnoozeInboxRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ until, err := time.Parse(time.RFC3339, req.Until)+ if err != nil {+ writeError(w, http.StatusBadRequest, "until must be an RFC 3339 time")+ return+ }+ now := time.Now()+ if !until.After(now) {+ writeError(w, http.StatusBadRequest, "until must be in the future")+ return+ }+ if until.After(now.Add(inboxSnoozeMaxDuration)) {+ writeError(w, http.StatusBadRequest, "until is too far in the future")+ return+ }+ if item.Archived {+ writeError(w, http.StatusConflict, "an archived notification cannot be snoozed")+ return+ }++ count, err := h.Queries.SnoozeInboxGroup(r.Context(), db.SnoozeInboxGroupParams{+ ID: item.ID,+ SnoozedUntil: pgtype.Timestamptz{Time: until, Valid: true},+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to snooze")+ return+ }++ snoozedUntil := until.UTC().Format(time.RFC3339)+ h.publish(protocol.EventInboxSnoozed, uuidToString(item.WorkspaceID), "member", requestUserID(r), map[string]any{+ "item_id": uuidToString(item.ID),+ "issue_id": uuidToPtr(item.IssueID),+ "recipient_id": uuidToString(item.RecipientID),+ "snoozed_until": snoozedUntil,+ })+ writeJSON(w, http.StatusOK, map[string]any{"count": count, "snoozed_until": snoozedUntil})+}++// UnsnoozeInboxItem brings a snoozed issue back now. Issue-level, mirroring+// SnoozeInboxItem.+func (h *Handler) UnsnoozeInboxItem(w http.ResponseWriter, r *http.Request) {+ item, ok := h.loadInboxItemForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ count, err := h.Queries.UnsnoozeInboxGroup(r.Context(), item.ID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to unsnooze")+ return+ }+ // Bringing back an issue that was not snoozed changes no row, so it must+ // not make every open client refetch its inbox.+ if count > 0 {+ h.publish(protocol.EventInboxUnsnoozed, uuidToString(item.WorkspaceID), "member", requestUserID(r), map[string]any{+ "item_id": uuidToString(item.ID),+ "issue_id": uuidToPtr(item.IssueID),+ "recipient_id": uuidToString(item.RecipientID),+ })+ }+ writeJSON(w, http.StatusOK, map[string]any{"count": count})+}+func (h *Handler) MarkAllInboxRead(w http.ResponseWriter, r *http.Request) {userID, ok := requireUserID(w, r)if !ok {@@ -617,6 +780,82 @@ func (h *Handler) ArchiveAllReadInbox(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, map[string]any{"count": count})}+// inboxArchiveUpdatesMaxGroups bounds one archive-updates request. A client+// with more groups to put away sends them in several requests.+const inboxArchiveUpdatesMaxGroups = 500++type ArchiveInboxUpdatesRequest struct {+ // The issues to archive, by issue id. A notification without an issue is+ // named by its own id, which is how the Inbox keys its rows.+ Groups []string `json:"groups"`+ // Archive only the groups that have been read.+ ReadOnly bool `json:"read_only"`+}++// ArchiveInboxUpdates archives the listed issues as long as they are still+// only updates for the caller (see ArchiveInboxUpdateGroups). The Inbox calls+// it with read_only for the updates the member has read, which leave the list+// once read, and without it when the member clears the "Updates" section.+//+// A listed issue that needs the caller, is snoozed, or (with read_only) has+// become unread again is left alone, so the count can be lower than the+// number of groups sent.+func (h *Handler) ArchiveInboxUpdates(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ workspaceID := ctxWorkspaceID(r.Context())+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }+ var req ArchiveInboxUpdatesRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if len(req.Groups) > inboxArchiveUpdatesMaxGroups {+ writeError(w, http.StatusBadRequest, "too many groups")+ return+ }+ groupIDs := make([]pgtype.UUID, 0, len(req.Groups))+ for _, group := range req.Groups {+ groupID, ok := parseUUIDOrBadRequest(w, group, "group id")+ if !ok {+ return+ }+ groupIDs = append(groupIDs, groupID)+ }+ if len(groupIDs) == 0 {+ writeJSON(w, http.StatusOK, map[string]any{"count": 0})+ return+ }++ count, err := h.Queries.ArchiveInboxUpdateGroups(r.Context(), db.ArchiveInboxUpdateGroupsParams{+ WorkspaceID: wsUUID,+ RecipientID: parseUUID(userID),+ GroupIds: groupIDs,+ NeedsYouTypes: inbox.NeedsYouTypes,+ ReadOnly: req.ReadOnly,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to archive inbox updates")+ return+ }++ // Nothing archived changes no row, so it must not make every open client+ // refetch its inbox.+ if count > 0 {+ h.publish(protocol.EventInboxBatchArchived, workspaceID, "member", userID, map[string]any{+ "recipient_id": userID,+ "count": count,+ })+ }++ writeJSON(w, http.StatusOK, map[string]any{"count": count})+}+func (h *Handler) ArchiveCompletedInbox(w http.ResponseWriter, r *http.Request) {userID, ok := requireUserID(w, r)if !ok {diff --git a/server/internal/handler/inbox_sections_test.go b/server/internal/handler/inbox_sections_test.gonew file mode 100644index 0000000000..72e71890bd--- /dev/null+++ b/server/internal/handler/inbox_sections_test.go@@ -0,0 +1,621 @@+package handler++import (+ "net/http"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// inboxSectionsFixture is one workspace whose inbox rows the caller owns.+type inboxSectionsFixture struct {+ t *testing.T+ workspaceID string+}++func newInboxSectionsFixture(t *testing.T, name string) inboxSectionsFixture {+ t.Helper()+ workspaceID := dbfx.Workspace(t, name, "inbox-sections-"+uuid.NewString())+ dbfx.Member(t, workspaceID, testUserID, "owner")+ dbfx.Cleanup(t, `DELETE FROM inbox_item WHERE workspace_id = $1`, workspaceID)+ return inboxSectionsFixture{t: t, workspaceID: workspaceID}+}++func (f inboxSectionsFixture) issue(title string) string {+ f.t.Helper()+ return dbfx.Issue(f.t, title, testutil.Cols{"workspace_id": f.workspaceID})+}++// row inserts one of the caller's inbox rows. A nil issue makes it issue-less.+func (f inboxSectionsFixture) row(issueID any, notifType string, over testutil.Cols) string {+ f.t.Helper()+ cols := testutil.Cols{+ "workspace_id": f.workspaceID,+ "recipient_type": "member",+ "recipient_id": testUserID,+ "type": notifType,+ "severity": "info",+ "title": notifType,+ }+ if issueID != nil {+ cols["issue_id"] = issueID+ }+ for k, v := range over {+ cols[k] = v+ }+ return dbfx.Insert(f.t, "inbox_item", cols)+}++func (f inboxSectionsFixture) summary() InboxWorkspaceUnreadResponse {+ f.t.Helper()+ var summary []InboxWorkspaceUnreadResponse+ testutil.Call(f.t, inboxWorkspaceHandler(testHandler.UnreadInboxSummary),+ inboxRequest(http.MethodGet, "/api/inbox/unread-summary", f.workspaceID)).+ Want(http.StatusOK).+ JSON(&summary)+ for _, s := range summary {+ if s.WorkspaceID == f.workspaceID {+ return s+ }+ }+ return InboxWorkspaceUnreadResponse{WorkspaceID: f.workspaceID}+}++func (f inboxSectionsFixture) list(query string) []InboxItemResponse {+ f.t.Helper()+ var items []InboxItemResponse+ testutil.Call(f.t, inboxWorkspaceHandler(testHandler.ListInbox),+ inboxRequest(http.MethodGet, "/api/inbox"+query, f.workspaceID)).+ Want(http.StatusOK).+ JSON(&items)+ return items+}++func (f inboxSectionsFixture) snooze(id string, body any) *testutil.Response {+ f.t.Helper()+ req := testutil.WithHeaders(+ testutil.JSONRequest(http.MethodPost, "/api/inbox/"+id+"/snooze", body),+ "X-User-ID", testUserID,+ "X-Workspace-ID", f.workspaceID,+ )+ return testutil.Call(f.t, inboxWorkspaceHandler(testHandler.SnoozeInboxItem), withURLParam(req, "id", id))+}++func (f inboxSectionsFixture) unsnooze(id string) int64 {+ f.t.Helper()+ var resp struct {+ Count int64 `json:"count"`+ }+ testutil.Call(f.t, inboxWorkspaceHandler(testHandler.UnsnoozeInboxItem),+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/"+id+"/unsnooze", f.workspaceID), "id", id)).+ Want(http.StatusOK).+ JSON(&resp)+ return resp.Count+}++// The badge counts the issues that wait on the member, read or not, and+// nothing they only follow (MUL-9215).+func TestInboxSummaryCountsIssuesThatNeedTheMember(t *testing.T) {+ f := newInboxSectionsFixture(t, "Inbox needs-you count")+ future := time.Now().Add(2 * time.Hour)+ past := time.Now().Add(-2 * time.Hour)++ // Counted: opening an issue is not handling it, and two rows are one issue.+ opened := f.issue("Opened but not handled")+ f.row(opened, "new_comment", testutil.Cols{"section": "needs_you", "read": true})+ f.row(opened, "agent_completed", testutil.Cols{"section": "needs_you", "read": true})++ // Not counted: the member only follows this one.+ f.row(f.issue("Followed"), "new_comment", testutil.Cols{"section": "updates"})++ // Rows from before sections were stored: an unread one addressed to the+ // member counts, a read one was handled when it was read, and a comment+ // has no recorded relation.+ f.row(f.issue("Legacy unread mention"), "mentioned", nil)+ f.row(f.issue("Legacy read mention"), "mentioned", testutil.Cols{"read": true})+ f.row(f.issue("Legacy comment"), "new_comment", nil)+ // The retired routing wrote other values; they follow the legacy rule.+ f.row(f.issue("Retired routing"), "issue_assigned", testutil.Cols{"section": "action"})++ // Snoozed: out until the time passes, back once it has.+ f.row(f.issue("Snoozed"), "mentioned", testutil.Cols{"section": "needs_you", "snoozed_until": future})+ f.row(f.issue("Snooze over"), "mentioned", testutil.Cols{"section": "needs_you", "snoozed_until": past})++ // Something new addressed to the member brings a snoozed issue back early;+ // an update on it does not.+ wokenEarly := f.issue("Woken early")+ f.row(wokenEarly, "new_comment", testutil.Cols{"section": "needs_you", "snoozed_until": future, "read": true})+ f.row(wokenEarly, "mentioned", testutil.Cols{"section": "needs_you"})+ stillSnoozed := f.issue("Still snoozed")+ f.row(stillSnoozed, "mentioned", testutil.Cols{"section": "needs_you", "snoozed_until": future, "read": true})+ f.row(stillSnoozed, "priority_changed", testutil.Cols{"section": "updates"})++ // Archived rows are gone, and an issue-less notice counts on its own.+ f.row(f.issue("Archived"), "mentioned", testutil.Cols{"section": "needs_you", "archived": true})+ f.row(nil, "autopilot_paused", testutil.Cols{"section": "needs_you"})++ got := f.summary()+ // opened, legacy unread mention, retired routing, snooze over, woken+ // early, issue-less notice.+ if got.NeedsYou != 6 {+ t.Errorf("needs_you = %d, want 6", got.NeedsYou)+ }+}++// Clients that predate the sectioned Inbox show `count` as their badge, so it+// stays the number of unread issues. Only a snooze takes an issue out of it.+func TestInboxSummaryKeepsTheUnreadCount(t *testing.T) {+ f := newInboxSectionsFixture(t, "Inbox unread count")++ f.row(f.issue("Unread update"), "new_comment", testutil.Cols{"section": "updates"})+ f.row(f.issue("Read and waiting"), "mentioned", testutil.Cols{"section": "needs_you", "read": true})+ f.row(f.issue("Snoozed"), "mentioned", testutil.Cols{"section": "needs_you", "snoozed_until": time.Now().Add(time.Hour)})++ got := f.summary()+ if got.Count != 1 {+ t.Errorf("count = %d, want 1: the unread update", got.Count)+ }+ if got.NeedsYou != 1 {+ t.Errorf("needs_you = %d, want 1: the read row still waiting", got.NeedsYou)+ }++ var unread struct {+ Count int64 `json:"count"`+ }+ testutil.Call(t, inboxWorkspaceHandler(testHandler.CountUnreadInbox),+ inboxRequest(http.MethodGet, "/api/inbox/unread-count", f.workspaceID)).+ Want(http.StatusOK).+ JSON(&unread)+ if unread.Count != 1 {+ t.Errorf("unread-count = %d, want 1: a snoozed row is not unread", unread.Count)+ }+}++// A workspace with nothing unread still appears once something waits there.+func TestInboxSummaryListsAWorkspaceWithOnlyReadRowsWaiting(t *testing.T) {+ f := newInboxSectionsFixture(t, "Inbox read but waiting")+ f.row(f.issue("Read and waiting"), "issue_assigned", testutil.Cols{"section": "needs_you", "read": true})++ got := f.summary()+ if got.Count != 0 || got.NeedsYou != 1 {+ t.Errorf("summary = %+v, want count 0 and needs_you 1", got)+ }+}++func TestListInboxReportsSectionAndHidesSnoozedRowsUnlessAsked(t *testing.T) {+ f := newInboxSectionsFixture(t, "Inbox list sections")+ until := time.Now().Add(3 * time.Hour).UTC().Truncate(time.Second)++ waiting := f.row(f.issue("Waiting"), "new_comment", testutil.Cols{"section": "needs_you", "read": true})+ followed := f.row(f.issue("Followed"), "new_comment", testutil.Cols{"section": "updates"})+ legacy := f.row(f.issue("Legacy"), "mentioned", nil)+ snoozed := f.row(f.issue("Snoozed"), "mentioned", testutil.Cols{"section": "needs_you", "snoozed_until": until})+ back := f.row(f.issue("Back"), "mentioned", testutil.Cols{"section": "needs_you", "snoozed_until": time.Now().Add(-time.Hour)})++ byID := func(items []InboxItemResponse) map[string]InboxItemResponse {+ out := make(map[string]InboxItemResponse, len(items))+ for _, item := range items {+ out[item.ID] = item+ }+ return out+ }++ // A client that predates the Snoozed section does not ask for those rows+ // and must not get them: it would show a snoozed issue as plainly unread.+ plain := byID(f.list(""))+ if _, ok := plain[snoozed]; ok {+ t.Errorf("a snoozed row was listed without include_snoozed")+ }+ if _, ok := plain[back]; !ok {+ t.Errorf("a row whose snooze is over was not listed")+ }+ for id, want := range map[string]string{waiting: "needs_you", followed: "updates", legacy: "needs_you"} {+ if got := plain[id].Section; got != want {+ t.Errorf("section of %s = %q, want %q", id, got, want)+ }+ }++ all := byID(f.list("?include_snoozed=true"))+ got, ok := all[snoozed]+ if !ok {+ t.Fatalf("include_snoozed=true did not list the snoozed row")+ }+ if got.SnoozedUntil == nil {+ t.Fatalf("snoozed_until missing on the snoozed row")+ }+ if parsed, err := time.Parse(time.RFC3339, *got.SnoozedUntil); err != nil || !parsed.Equal(until) {+ t.Errorf("snoozed_until = %q, want %s", *got.SnoozedUntil, until.Format(time.RFC3339))+ }+ if all[waiting].SnoozedUntil != nil {+ t.Errorf("snoozed_until = %q on a row that was never snoozed", *all[waiting].SnoozedUntil)+ }+}++func TestSnoozeInboxItemSnoozesTheWholeIssue(t *testing.T) {+ f := newInboxSectionsFixture(t, "Inbox snooze")+ issueID := f.issue("Snoozed issue")+ older := f.row(issueID, "issue_assigned", testutil.Cols{"section": "needs_you", "read": true})+ newest := f.row(issueID, "new_comment", testutil.Cols{"section": "needs_you", "read": true})+ archived := f.row(issueID, "new_comment", testutil.Cols{"section": "needs_you", "archived": true})+ other := f.row(f.issue("Another issue"), "mentioned", testutil.Cols{"section": "needs_you"})++ published := make(chan map[string]any, 4)+ for _, eventType := range []string{protocol.EventInboxSnoozed, protocol.EventInboxUnsnoozed} {+ testHandler.Bus.Subscribe(eventType, func(e events.Event) {+ payload, ok := e.Payload.(map[string]any)+ if !ok || payload["item_id"] != newest {+ return+ }+ select {+ case published <- map[string]any{"type": e.Type, "recipient_id": payload["recipient_id"]}:+ default:+ }+ })+ }++ until := time.Now().Add(24 * time.Hour).UTC().Truncate(time.Second)+ var resp struct {+ Count int64 `json:"count"`+ SnoozedUntil string `json:"snoozed_until"`+ }+ f.snooze(newest, map[string]string{"until": until.Format(time.RFC3339)}).Want(http.StatusOK).JSON(&resp)+ if resp.Count != 2 {+ t.Fatalf("count = %d, want the issue's two active rows", resp.Count)+ }+ if resp.SnoozedUntil != until.Format(time.RFC3339) {+ t.Errorf("snoozed_until = %q, want %q", resp.SnoozedUntil, until.Format(time.RFC3339))+ }++ snoozedUntil := func(id string) *time.Time {+ t.Helper()+ var at *time.Time+ dbfx.QueryRow(t, `SELECT snoozed_until FROM inbox_item WHERE id = $1`, id).Scan(&at)+ return at+ }+ isRead := func(id string) bool {+ t.Helper()+ var read bool+ dbfx.QueryRow(t, `SELECT read FROM inbox_item WHERE id = $1`, id).Scan(&read)+ return read+ }+ for _, id := range []string{older, newest} {+ if at := snoozedUntil(id); at == nil || !at.Equal(until) {+ t.Errorf("snoozed_until of %s = %v, want %s", id, at, until)+ }+ }+ for _, id := range []string{archived, other} {+ if at := snoozedUntil(id); at != nil {+ t.Errorf("snoozed_until of %s = %v, want it untouched", id, at)+ }+ }+ // The row the Inbox shows comes back as new; its sibling keeps its state.+ if isRead(newest) {+ t.Errorf("the snoozed row stayed read; it should come back unread")+ }+ if !isRead(older) {+ t.Errorf("an older sibling became unread")+ }+ select {+ case got := <-published:+ if got["type"] != protocol.EventInboxSnoozed || got["recipient_id"] != testUserID {+ t.Errorf("published %+v, want inbox:snoozed for the caller", got)+ }+ default:+ t.Errorf("snoozing published no inbox:snoozed event")+ }++ if f.summary().NeedsYou != 1 {+ t.Errorf("needs_you = %d, want 1: only the other issue", f.summary().NeedsYou)+ }++ if got := f.unsnooze(newest); got != 2 {+ t.Fatalf("unsnooze count = %d, want the issue's two rows", got)+ }+ for _, id := range []string{older, newest} {+ if at := snoozedUntil(id); at != nil {+ t.Errorf("snoozed_until of %s = %v after unsnooze, want none", id, at)+ }+ }+ select {+ case got := <-published:+ if got["type"] != protocol.EventInboxUnsnoozed {+ t.Errorf("published %+v, want inbox:unsnoozed", got)+ }+ default:+ t.Errorf("unsnoozing published no inbox:unsnoozed event")+ }+ if got := f.unsnooze(older); got != 0 {+ t.Errorf("unsnoozing an issue that is not snoozed changed %d rows", got)+ }+ if f.summary().NeedsYou != 2 {+ t.Errorf("needs_you = %d after unsnooze, want 2", f.summary().NeedsYou)+ }+}++// Nothing is written when a snooze runs out, so the summary says when the+// next one does and the badge re-reads it then.+func TestInboxSummaryReportsTheNextSnoozeToRunOut(t *testing.T) {+ f := newInboxSectionsFixture(t, "Inbox next wake")+ if got := f.summary().NextWakeAt; got != nil {+ t.Fatalf("next_wake_at = %q with nothing snoozed, want none", *got)+ }++ soon := time.Now().Add(time.Hour).UTC().Truncate(time.Second)+ later := soon.Add(24 * time.Hour)+ f.row(f.issue("Back later"), "mentioned", testutil.Cols{"section": "needs_you", "snoozed_until": later})+ // Only followed, but its row is still out of the counts until then.+ f.row(f.issue("Back soon"), "new_comment", testutil.Cols{"section": "updates", "snoozed_until": soon})+ // Not coming back: already back, or archived.+ f.row(f.issue("Already back"), "mentioned", testutil.Cols{"section": "needs_you", "snoozed_until": time.Now().Add(-time.Hour)})+ f.row(f.issue("Archived"), "mentioned", testutil.Cols{"section": "needs_you", "archived": true, "snoozed_until": soon.Add(-time.Minute)})++ got := f.summary()+ if got.NextWakeAt == nil {+ t.Fatalf("next_wake_at missing, want %s", soon)+ }+ at, err := time.Parse(time.RFC3339, *got.NextWakeAt)+ if err != nil || !at.Equal(soon) {+ t.Errorf("next_wake_at = %q, want %s", *got.NextWakeAt, soon.Format(time.RFC3339))+ }+ if got.NeedsYou != 1 {+ t.Errorf("needs_you = %d, want only the issue already back", got.NeedsYou)+ }+}++func TestSnoozeInboxItemRejectsATimeItCannotUse(t *testing.T) {+ f := newInboxSectionsFixture(t, "Inbox snooze validation")+ id := f.row(f.issue("Issue"), "mentioned", testutil.Cols{"section": "needs_you"})+ archived := f.row(f.issue("Archived issue"), "mentioned", testutil.Cols{"section": "needs_you", "archived": true})++ for name, body := range map[string]any{+ "missing": map[string]string{},+ "not a time": map[string]string{"until": "tomorrow"},+ "in the past": map[string]string{"until": time.Now().Add(-time.Minute).Format(time.RFC3339)},+ "years from now": map[string]string{"until": time.Now().AddDate(3, 0, 0).Format(time.RFC3339)},+ } {+ f.snooze(id, body).Want(http.StatusBadRequest)+ if got := dbfx.Count(t, `SELECT count(*) FROM inbox_item WHERE id = $1 AND snoozed_until IS NOT NULL`, id); got != 0 {+ t.Errorf("%s: the row was snoozed", name)+ }+ }+ f.snooze(archived, map[string]string{"until": time.Now().Add(time.Hour).Format(time.RFC3339)}).+ Want(http.StatusConflict)+ f.snooze(uuid.NewString(), map[string]string{"until": time.Now().Add(time.Hour).Format(time.RFC3339)}).+ Want(http.StatusNotFound)+}++// Restoring an archived issue is asking to see it now, so a snooze set before+// the archive does not hide it again.+func TestUnarchiveInboxItemDropsASnooze(t *testing.T) {+ f := newInboxSectionsFixture(t, "Inbox unarchive snooze")+ issueID := f.issue("Archived while snoozed")+ future := time.Now().Add(6 * time.Hour)+ first := f.row(issueID, "mentioned", testutil.Cols{"section": "needs_you", "archived": true, "snoozed_until": future})+ second := f.row(issueID, "new_comment", testutil.Cols{"section": "needs_you", "archived": true, "snoozed_until": future})++ testutil.Call(t, inboxWorkspaceHandler(testHandler.UnarchiveInboxItem),+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/"+first+"/unarchive", f.workspaceID), "id", first)).+ Want(http.StatusOK)++ if got := dbfx.Count(t,+ `SELECT count(*) FROM inbox_item WHERE id = ANY($1::uuid[]) AND archived = false AND snoozed_until IS NULL`,+ []string{first, second}); got != 2 {+ t.Errorf("restored rows without a snooze = %d, want 2", got)+ }+ if f.summary().NeedsYou != 1 {+ t.Errorf("needs_you = %d, want the restored issue", f.summary().NeedsYou)+ }+}++func (f inboxSectionsFixture) archiveUpdates(body any) *testutil.Response {+ f.t.Helper()+ req := testutil.WithHeaders(+ testutil.JSONRequest(http.MethodPost, "/api/inbox/archive-updates", body),+ "X-User-ID", testUserID,+ "X-Workspace-ID", f.workspaceID,+ )+ return testutil.Call(f.t, inboxWorkspaceHandler(testHandler.ArchiveInboxUpdates), req)+}++func (f inboxSectionsFixture) archivedRows(ids ...string) int {+ f.t.Helper()+ return dbfx.Count(f.t, `SELECT count(*) FROM inbox_item WHERE id = ANY($1::uuid[]) AND archived = true`, ids)+}++// The Inbox drops an update once it has been read (MUL-9215). Only what is+// still a read update goes: an issue that needs the member, one they snoozed,+// and one that became unread again all stay.+func TestArchiveInboxUpdatesArchivesReadUpdates(t *testing.T) {+ f := newInboxSectionsFixture(t, "Inbox archive read updates")+ older := time.Now().Add(-time.Hour)++ read := f.issue("Read update")+ readRows := []string{+ f.row(read, "new_comment", testutil.Cols{"section": "updates", "read": true, "created_at": older}),+ f.row(read, "status_changed", testutil.Cols{"section": "updates", "read": true}),+ }+ // The Inbox shows an issue as read by its newest row, so an older unread+ // sibling does not keep it.+ readByNewest := f.issue("Read by its newest row")+ readByNewestRows := []string{+ f.row(readByNewest, "new_comment", testutil.Cols{"section": "updates", "created_at": older}),+ f.row(readByNewest, "priority_changed", testutil.Cols{"section": "updates", "read": true}),+ }+ // A row from before sections were stored is an update once it is read.+ legacyRead := f.row(f.issue("Legacy read"), "mentioned", testutil.Cols{"read": true})+ issueless := f.row(nil, "quick_create_done", testutil.Cols{"section": "updates", "read": true})++ unread := f.issue("Unread again")+ unreadRows := []string{+ f.row(unread, "new_comment", testutil.Cols{"section": "updates", "read": true, "created_at": older}),+ f.row(unread, "new_comment", testutil.Cols{"section": "updates"}),+ }+ waiting := f.issue("Waiting on the member")+ waitingRows := []string{+ f.row(waiting, "mentioned", testutil.Cols{"section": "needs_you", "read": true, "created_at": older}),+ f.row(waiting, "status_changed", testutil.Cols{"section": "updates", "read": true}),+ }+ legacyUnread := f.row(f.issue("Legacy unread mention"), "mentioned", nil)+ snoozedIssue := f.issue("Snoozed update")+ snoozed := f.row(snoozedIssue, "new_comment", testutil.Cols{+ "section": "updates", "read": true, "snoozed_until": time.Now().Add(time.Hour),+ })+ notListed := f.row(f.issue("Not listed"), "new_comment", testutil.Cols{"section": "updates", "read": true})+ // Someone else's row on a listed issue is not the caller's to archive.+ otherID := dbfx.User(t, "Other reader", "inbox-archive-updates-"+uuid.NewString()+"@multica.ai")+ dbfx.Member(t, f.workspaceID, otherID, "member")+ othersRow := f.row(read, "new_comment", testutil.Cols{"section": "updates", "read": true, "recipient_id": otherID})++ var published []map[string]any+ testHandler.Bus.Subscribe(protocol.EventInboxBatchArchived, func(e events.Event) {+ if e.WorkspaceID != f.workspaceID {+ return+ }+ if payload, ok := e.Payload.(map[string]any); ok {+ published = append(published, payload)+ }+ })++ var resp struct {+ Count int64 `json:"count"`+ }+ f.archiveUpdates(map[string]any{+ "read_only": true,+ "groups": []string{+ read, readByNewest, inboxRowIssue(t, legacyRead), issueless,+ unread, waiting, inboxRowIssue(t, legacyUnread), snoozedIssue,+ },+ }).Want(http.StatusOK).JSON(&resp)++ if resp.Count != 6 {+ t.Errorf("count = %d, want the six rows of the four read updates", resp.Count)+ }+ archived := append(append([]string{legacyRead, issueless}, readRows...), readByNewestRows...)+ if got := f.archivedRows(archived...); got != len(archived) {+ t.Errorf("archived read updates = %d, want %d", got, len(archived))+ }+ kept := append(append([]string{legacyUnread, snoozed, notListed, othersRow}, unreadRows...), waitingRows...)+ if got := f.archivedRows(kept...); got != 0 {+ t.Errorf("archived %d rows that are not the caller's read updates, want 0", got)+ }+ if len(published) != 1 || published[0]["recipient_id"] != testUserID || published[0]["count"] != int64(6) {+ t.Errorf("published %+v, want one inbox:batch-archived for the caller's six rows", published)+ }++ // Nothing left to archive changes no row and announces nothing.+ f.archiveUpdates(map[string]any{"read_only": true, "groups": []string{read, unread, waiting}}).+ Want(http.StatusOK).JSON(&resp)+ if resp.Count != 0 || len(published) != 1 {+ t.Errorf("second call: count = %d with %d events, want 0 and no new event", resp.Count, len(published))+ }+}++// inboxRowIssue is the issue a seeded row belongs to: the key the Inbox+// names its group by.+func inboxRowIssue(t *testing.T, itemID string) string {+ t.Helper()+ var issueID string+ dbfx.QueryRow(t, `SELECT issue_id FROM inbox_item WHERE id = $1`, itemID).Scan(&issueID)+ return issueID+}++// Clearing "Updates" archives the unread ones too, and still nothing that+// needs the member.+func TestArchiveInboxUpdatesClearsUnreadUpdates(t *testing.T) {+ f := newInboxSectionsFixture(t, "Inbox clear updates")+ unreadIssue := f.issue("Unread update")+ unread := f.row(unreadIssue, "new_comment", testutil.Cols{"section": "updates"})+ waitingIssue := f.issue("Waiting on the member")+ waiting := f.row(waitingIssue, "new_comment", testutil.Cols{"section": "needs_you"})+ groupMentionIssue := f.issue("Group mention filed as an update")+ groupMention := f.row(groupMentionIssue, "mentioned", testutil.Cols{"section": "updates"})++ var resp struct {+ Count int64 `json:"count"`+ }+ f.archiveUpdates(map[string]any{"groups": []string{unreadIssue, waitingIssue, groupMentionIssue}}).+ Want(http.StatusOK).JSON(&resp)+ if resp.Count != 2 {+ t.Errorf("count = %d, want the two updates", resp.Count)+ }+ if got := f.archivedRows(unread, groupMention); got != 2 {+ t.Errorf("archived updates = %d, want 2", got)+ }+ if got := f.archivedRows(waiting); got != 0 {+ t.Errorf("the issue that needs the member was archived")+ }+ if f.summary().NeedsYou != 1 {+ t.Errorf("needs_you = %d, want the waiting issue still counted", f.summary().NeedsYou)+ }+}++func TestArchiveInboxUpdatesRejectsBadInput(t *testing.T) {+ f := newInboxSectionsFixture(t, "Inbox archive updates input")++ var resp struct {+ Count int64 `json:"count"`+ }+ f.archiveUpdates(map[string]any{"groups": []string{}}).Want(http.StatusOK).JSON(&resp)+ if resp.Count != 0 {+ t.Errorf("count = %d for no groups, want 0", resp.Count)+ }+ f.archiveUpdates(map[string]any{"groups": []string{"not-a-uuid"}}).Want(http.StatusBadRequest)+ tooMany := make([]string, inboxArchiveUpdatesMaxGroups+1)+ for i := range tooMany {+ tooMany[i] = uuid.NewString()+ }+ f.archiveUpdates(map[string]any{"groups": tooMany}).Want(http.StatusBadRequest)+}++// A restored update comes back unread, or the Inbox would drop it again as a+// read update. An issue that needs the member keeps the state it had.+func TestUnarchiveInboxItemRestoresAnUpdateAsUnread(t *testing.T) {+ f := newInboxSectionsFixture(t, "Inbox unarchive update")+ older := time.Now().Add(-time.Hour)+ unarchive := func(id string) InboxItemResponse {+ t.Helper()+ var item InboxItemResponse+ testutil.Call(t, inboxWorkspaceHandler(testHandler.UnarchiveInboxItem),+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/"+id+"/unarchive", f.workspaceID), "id", id)).+ Want(http.StatusOK).+ JSON(&item)+ return item+ }+ isRead := func(id string) bool {+ t.Helper()+ var read bool+ dbfx.QueryRow(t, `SELECT read FROM inbox_item WHERE id = $1`, id).Scan(&read)+ return read+ }++ update := f.issue("Archived update")+ updateOlder := f.row(update, "new_comment", testutil.Cols{"section": "updates", "read": true, "archived": true, "created_at": older})+ updateNewest := f.row(update, "status_changed", testutil.Cols{"section": "updates", "read": true, "archived": true})+ // Restored from the older row: the one the Inbox renders is still the newest.+ if got := unarchive(updateOlder); got.Archived {+ t.Fatalf("the restored row is still archived: %+v", got)+ }+ if isRead(updateNewest) {+ t.Errorf("the restored update's newest row stayed read")+ }+ if !isRead(updateOlder) {+ t.Errorf("an older row of the restored update became unread")+ }+ var resp struct {+ Count int64 `json:"count"`+ }+ f.archiveUpdates(map[string]any{"read_only": true, "groups": []string{update}}).Want(http.StatusOK).JSON(&resp)+ if resp.Count != 0 {+ t.Errorf("the restored update was archived again as read")+ }++ waiting := f.issue("Archived while waiting")+ waitingRow := f.row(waiting, "mentioned", testutil.Cols{"section": "needs_you", "read": true, "archived": true})+ if got := unarchive(waitingRow); !got.Read {+ t.Errorf("an issue that needs the member came back unread: %+v", got)+ }+}diff --git a/server/internal/inbox/create.go b/server/internal/inbox/create.goindex 1fb9d23369..d5718c707f 100644--- a/server/internal/inbox/create.go+++ b/server/internal/inbox/create.go@@ -5,13 +5,21 @@ import ("errors""github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"db "github.com/multica-ai/multica/server/pkg/db/generated")// CreateIfEligible returns inserted=false without an error when the recipient// does not belong to the workspace. Other database errors remain failures.// Eligibility is checked by the insert's snapshot, without additional locks.+//+// Every row is written with its Inbox section. A caller that fans an event out+// to subscribers sets it per recipient (SubscriberSection); one that writes+// straight to the person concerned leaves it unset and gets DefaultSection.func CreateIfEligible(ctx context.Context, queries *db.Queries, params db.CreateInboxItemParams) (item db.InboxItem, inserted bool, err error) {+ if !params.Section.Valid {+ params.Section = pgtype.Text{String: DefaultSection(params.Type), Valid: true}+ }item, err = queries.CreateInboxItem(ctx, params)if errors.Is(err, pgx.ErrNoRows) {return db.InboxItem{}, false, nildiff --git a/server/internal/inbox/section.go b/server/internal/inbox/section.gonew file mode 100644index 0000000000..f5302828e0--- /dev/null+++ b/server/internal/inbox/section.go@@ -0,0 +1,108 @@+package inbox++import "github.com/jackc/pgx/v5/pgtype"++// The Inbox lists issues by whose turn it is (MUL-9215). A notification is+// written into one of two sections:+//+// - SectionNeedsYou: it is addressed to the recipient, so the issue waits on+// them until they act on it or archive it. These are the rows the Inbox+// badge counts, read or not.+// - SectionUpdates: the recipient only follows the issue. Nothing waits on+// them, the rows are not counted, and reading is all there is to do.+//+// The section is decided when the row is written, from who the recipient is to+// the issue, and stored in inbox_item.section. It is deliberately not decided+// by notification type alone: an agent's reply on an issue the recipient owns+// and the same reply on an issue they merely follow are the same type.+const (+ SectionNeedsYou = "needs_you"+ SectionUpdates = "updates"+)++// NeedsYouTypes are the types only ever written to the person they are for: a+// mention, an assignment, a run handed back, an app call waiting on an answer,+// a paused autopilot. They need no relation check.+//+// The list also classifies rows written before sections were stored (see+// EffectiveSection) and is passed to the SQL that counts them, so both read+// one definition.+var NeedsYouTypes = []string{+ "mentioned",+ "issue_assigned",+ "review_requested",+ "agent_completed",+ "agent_blocked",+ "task_failed",+ "task_cancelled",+ "children_done",+ "app_action_requested",+ "app_action_reminder",+ "app_connect_requested",+ "autopilot_paused",+ "autopilot_quota_exceeded",+ "quick_create_failed",+ "quick_create_unconfirmed",+}++var needsYouTypeSet = func() map[string]bool {+ set := make(map[string]bool, len(NeedsYouTypes))+ for _, t := range NeedsYouTypes {+ set[t] = true+ }+ return set+}()++// DefaultSection is the section of a row written straight to its recipient.+func DefaultSection(notifType string) string {+ if needsYouTypeSet[notifType] {+ return SectionNeedsYou+ }+ return SectionUpdates+}++// SubscriberSection is the section of a row fanned out to an issue's+// subscribers, where the same event reaches people with different stakes.+//+// addressed reports whether the recipient answers for the issue: they created+// it, it is assigned to them, an agent filed it on their behalf, or they+// started the run the event is about. waitsOnHuman reports whether the issue's+// status hands it to a person (in review, blocked, a custom started status).+//+// A comment, a failed run or a blocked agent needs the people who answer for+// the issue and is an update for everyone else. A status change needs them only+// when the new status waits on a person. Field edits are updates for everyone.+func SubscriberSection(notifType string, addressed, waitsOnHuman bool) string {+ switch notifType {+ case "new_comment", "task_failed", "agent_blocked":+ if addressed {+ return SectionNeedsYou+ }+ case "status_changed":+ if addressed && waitsOnHuman {+ return SectionNeedsYou+ }+ }+ return SectionUpdates+}++// EffectiveSection is the section a stored row belongs to.+//+// Rows written before sections were stored have none. Reading was handling+// then, so such a row needs the recipient only while it is unread and of a type+// addressed to them; everything else they already saw is an update. The SQL+// that counts the badge (CountNeedsYouInboxByWorkspace) applies the same rule.+func EffectiveSection(stored pgtype.Text, notifType string, read bool) string {+ if stored.Valid {+ if stored.String == SectionNeedsYou {+ return SectionNeedsYou+ }+ if stored.String == SectionUpdates {+ return SectionUpdates+ }+ }+ if !read && needsYouTypeSet[notifType] {+ return SectionNeedsYou+ }+ return SectionUpdates+}diff --git a/server/internal/inbox/section_test.go b/server/internal/inbox/section_test.gonew file mode 100644index 0000000000..1878d2016c--- /dev/null+++ b/server/internal/inbox/section_test.go@@ -0,0 +1,86 @@+package inbox++import (+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+)++func TestDefaultSection(t *testing.T) {+ for notifType, want := range map[string]string{+ "mentioned": SectionNeedsYou,+ "issue_assigned": SectionNeedsYou,+ "agent_completed": SectionNeedsYou,+ "task_failed": SectionNeedsYou,+ "app_action_requested": SectionNeedsYou,+ "autopilot_paused": SectionNeedsYou,+ "autopilot_quota_exceeded": SectionNeedsYou,+ "quick_create_failed": SectionNeedsYou,+ // Results and courtesies ask nothing of the recipient.+ "issue_subscribed": SectionUpdates,+ "quick_create_done": SectionUpdates,+ "app_action_result": SectionUpdates,+ "reaction_added": SectionUpdates,+ "unassigned": SectionUpdates,+ "a_type_added_later": SectionUpdates,+ } {+ if got := DefaultSection(notifType); got != want {+ t.Errorf("DefaultSection(%q) = %q, want %q", notifType, got, want)+ }+ }+}++func TestSubscriberSection(t *testing.T) {+ for _, tc := range []struct {+ notifType string+ addressed bool+ waitsOnHuman bool+ want string+ }{+ // The same comment needs whoever answers for the issue and is an update+ // for someone who only follows it.+ {"new_comment", true, false, SectionNeedsYou},+ {"new_comment", false, false, SectionUpdates},+ {"task_failed", true, false, SectionNeedsYou},+ {"task_failed", false, false, SectionUpdates},+ {"agent_blocked", true, false, SectionNeedsYou},+ {"agent_blocked", false, false, SectionUpdates},+ // A status change needs them only when the new status waits on a person.+ {"status_changed", true, true, SectionNeedsYou},+ {"status_changed", true, false, SectionUpdates},+ {"status_changed", false, true, SectionUpdates},+ // Field edits are updates for everyone.+ {"priority_changed", true, true, SectionUpdates},+ {"assignee_changed", true, true, SectionUpdates},+ {"due_date_changed", true, true, SectionUpdates},+ {"issue_created", true, true, SectionUpdates},+ } {+ if got := SubscriberSection(tc.notifType, tc.addressed, tc.waitsOnHuman); got != tc.want {+ t.Errorf("SubscriberSection(%q, addressed=%v, waits=%v) = %q, want %q",+ tc.notifType, tc.addressed, tc.waitsOnHuman, got, tc.want)+ }+ }+}++func TestEffectiveSection(t *testing.T) {+ stored := func(s string) pgtype.Text { return pgtype.Text{String: s, Valid: true} }+ for _, tc := range []struct {+ name string+ stored pgtype.Text+ notifType string+ read bool+ want string+ }{+ {"a stored section wins over the type", stored(SectionUpdates), "mentioned", false, SectionUpdates},+ {"a stored section survives being read", stored(SectionNeedsYou), "new_comment", true, SectionNeedsYou},+ {"an unread legacy mention still needs the recipient", pgtype.Text{}, "mentioned", false, SectionNeedsYou},+ {"a read legacy mention was handled when it was read", pgtype.Text{}, "mentioned", true, SectionUpdates},+ {"a legacy comment has no recorded relation", pgtype.Text{}, "new_comment", false, SectionUpdates},+ {"a value from the retired routing is treated as legacy", stored("action"), "issue_assigned", false, SectionNeedsYou},+ {"a retired value on a read row is an update", stored("activity"), "issue_assigned", true, SectionUpdates},+ } {+ if got := EffectiveSection(tc.stored, tc.notifType, tc.read); got != tc.want {+ t.Errorf("%s: EffectiveSection = %q, want %q", tc.name, got, tc.want)+ }+ }+}diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.goindex 78e8356011..3df52c0a48 100644--- a/server/internal/integrations/wecom/outbound.go+++ b/server/internal/integrations/wecom/outbound.go@@ -850,6 +850,11 @@ func (o *Outbound) handleInboxNew(e events.Event) {if rt, _ := item["recipient_type"].(string); rt != "member" {return}+ // A row written as read reports the member's own action (a run they+ // stopped themselves), so there is nothing to tell them.+ if read, _ := item["read"].(bool); read {+ return+ }recipientIDStr, _ := item["recipient_id"].(string)workspaceIDStr, _ := item["workspace_id"].(string)if recipientIDStr == "" || workspaceIDStr == "" {diff --git a/server/internal/integrations/wecom/strings.go b/server/internal/integrations/wecom/strings.goindex b3a05459e0..f4130b779a 100644--- a/server/internal/integrations/wecom/strings.go+++ b/server/internal/integrations/wecom/strings.go@@ -458,6 +458,8 @@ var copyPacks = map[Locale]copyPack{"new_comment": "新评论","reaction_added": "表情反应","task_failed": "task 失败",+ "agent_completed": "运行完成",+ "task_cancelled": "运行已取消","unassigned": "取消指派","assignee_changed": "指派人变更","priority_changed": "优先级变更",@@ -537,6 +539,8 @@ var copyPacks = map[Locale]copyPack{"new_comment": "New comment","reaction_added": "Reaction","task_failed": "Run failed",+ "agent_completed": "Run finished",+ "task_cancelled": "Run cancelled","unassigned": "Unassigned","assignee_changed": "Assignee changed","priority_changed": "Priority changed",diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex f7f28722d0..1422513294 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -2749,7 +2749,9 @@ func (s *TaskService) CancelTasksForIssue(ctx context.Context, issueID pgtype.UU}for _, t := range cancelled {s.captureTaskCancelled(ctx, t)- s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)+ // The issue is about to be deleted, so the cancelled run has nowhere to+ // be handed back to (notifyRunCancelled).+ s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t, map[string]any{"issue_deleted": true})}// Reconcile once per distinct agent instead of once per cancelled row:// cancelling an issue often stops several tasks owned by the same agent,@@ -3442,6 +3444,8 @@ func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.// cancel time, BEFORE the daemon's ack — clients may have refetched a row// without the delivery and will not refetch again on their own. Consumers// treat task:cancelled as idempotent cache invalidation, so a replay is safe.+// The event says it is a replay for the one consumer that acts once per+// cancellation: the Inbox hand-back (notifyRunCancelled).func (s *TaskService) RebroadcastCancelledTask(ctx context.Context, taskID pgtype.UUID) {task, err := s.Queries.GetAgentTask(ctx, taskID)if err != nil {@@ -3454,7 +3458,7 @@ func (s *TaskService) RebroadcastCancelledTask(ctx context.Context, taskID pgtyp// carrying the row's final fields; nothing stale to refresh.return}- s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, task)+ s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, task, map[string]any{"replay": true})}// RetireCancelledTaskSession records, on a CANCELLED task, a session the daemondiff --git a/server/migrations/657_inbox_item_snoozed_until.down.sql b/server/migrations/657_inbox_item_snoozed_until.down.sqlnew file mode 100644index 0000000000..9cef356d07--- /dev/null+++ b/server/migrations/657_inbox_item_snoozed_until.down.sql@@ -0,0 +1 @@+ALTER TABLE inbox_item DROP COLUMN IF EXISTS snoozed_until;diff --git a/server/migrations/657_inbox_item_snoozed_until.up.sql b/server/migrations/657_inbox_item_snoozed_until.up.sqlnew file mode 100644index 0000000000..d0bb03234a--- /dev/null+++ b/server/migrations/657_inbox_item_snoozed_until.up.sql@@ -0,0 +1,6 @@+-- MUL-9215: when a member snoozes an issue in the Inbox, every active row they+-- have on it carries the time it comes back. NULL means not snoozed, so+-- existing rows need no backfill and older servers keep writing valid rows.+-- The column is nullable with no default, which keeps the ALTER a catalog-only+-- change with no table scan.+ALTER TABLE inbox_item ADD COLUMN IF NOT EXISTS snoozed_until TIMESTAMPTZ;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 136356c16a..f294d08a0f 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -4725,6 +4725,33 @@ func (q *Queries) HasActiveTaskForIssueAndAgentInThread(ctx context.Context, argreturn has_active, err}+const hasOtherActiveRunStartedByMember = `-- name: HasOtherActiveRunStartedByMember :one+SELECT EXISTS (+ SELECT 1 FROM agent_task_queue+ WHERE issue_id = $1+ AND id <> $2+ AND originator_user_id = $3+ AND originator_source = 'direct_human'+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+) AS has_other+`++type HasOtherActiveRunStartedByMemberParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ TaskID pgtype.UUID `json:"task_id"`+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`+}++// Whether the member has another run of their own still active on the issue,+// besides the given task. The Inbox keeps the issue under "Working" while one+// is (MUL-9215), so a cancelled sibling does not hand the issue back.+func (q *Queries) HasOtherActiveRunStartedByMember(ctx context.Context, arg HasOtherActiveRunStartedByMemberParams) (bool, error) {+ row := q.db.QueryRow(ctx, hasOtherActiveRunStartedByMember, arg.IssueID, arg.TaskID, arg.OriginatorUserID)+ var has_other bool+ err := row.Scan(&has_other)+ return has_other, err+}+const hasPendingTaskForIssue = `-- name: HasPendingTaskForIssue :oneSELECT count(*) > 0 AS has_pending FROM agent_task_queueWHERE context->>'wakeup_id' IS NULL AND issue_id = $1 AND status IN ('queued', 'dispatched')diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.goindex 16d3841611..f4ba9480d1 100644--- a/server/pkg/db/generated/inbox.sql.go+++ b/server/pkg/db/generated/inbox.sql.go@@ -158,10 +158,48 @@ func (q *Queries) ArchiveInboxByIssueAndType(ctx context.Context, arg ArchiveInbreturn items, nil}+const archiveInboxByIssueForAll = `-- name: ArchiveInboxByIssueForAll :many+UPDATE inbox_item SET archived = true+WHERE workspace_id = $1 AND issue_id = $2 AND archived = false+RETURNING recipient_type, recipient_id+`++type ArchiveInboxByIssueForAllParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++type ArchiveInboxByIssueForAllRow struct {+ RecipientType string `json:"recipient_type"`+ RecipientID pgtype.UUID `json:"recipient_id"`+}++// An issue that reached a done or cancelled status waits on no one, so it+// leaves every recipient's Inbox at once (MUL-9215).+func (q *Queries) ArchiveInboxByIssueForAll(ctx context.Context, arg ArchiveInboxByIssueForAllParams) ([]ArchiveInboxByIssueForAllRow, error) {+ rows, err := q.db.Query(ctx, archiveInboxByIssueForAll, arg.WorkspaceID, arg.IssueID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ArchiveInboxByIssueForAllRow{}+ for rows.Next() {+ var i ArchiveInboxByIssueForAllRow+ if err := rows.Scan(&i.RecipientType, &i.RecipientID); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const archiveInboxItem = `-- name: ArchiveInboxItem :oneUPDATE inbox_item SET archived = trueWHERE id = $1-RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section+RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until`func (q *Queries) ArchiveInboxItem(ctx context.Context, id pgtype.UUID) (InboxItem, error) {@@ -184,10 +222,155 @@ func (q *Queries) ArchiveInboxItem(ctx context.Context, id pgtype.UUID) (InboxIt&i.ActorID,&i.Details,&i.Section,+ &i.SnoozedUntil,)return i, err}+const archiveInboxUpdateGroups = `-- name: ArchiveInboxUpdateGroups :execrows+WITH candidates AS (+ SELECT i.id, COALESCE(i.issue_id, i.id) AS group_id, i.read, i.created_at,+ i.snoozed_until, i.section, i.type+ FROM inbox_item i+ WHERE i.workspace_id = $1+ AND i.recipient_type = 'member'+ AND i.recipient_id = $2+ AND i.archived = false+ AND (i.issue_id = ANY($3::uuid[])+ OR (i.issue_id IS NULL AND i.id = ANY($3::uuid[])))+), update_groups AS (+ SELECT c.group_id+ FROM candidates c+ GROUP BY c.group_id+ -- COALESCE: a row from before sections were stored has none, and a NULL+ -- comparison would leave the whole test NULL.+ HAVING NOT bool_or(+ COALESCE(c.section, '') = 'needs_you'+ OR (COALESCE(c.section, '') NOT IN ('needs_you', 'updates')+ AND c.read = false+ AND c.type = ANY($4::text[])))+ AND NOT bool_or(c.snoozed_until IS NOT NULL AND c.snoozed_until > now())+ AND (NOT $5::boolean+ OR (array_agg(c.read ORDER BY c.created_at DESC, c.id DESC))[1])+)+UPDATE inbox_item i SET archived = true+FROM candidates c+JOIN update_groups g ON g.group_id = c.group_id+WHERE i.id = c.id+`++type ArchiveInboxUpdateGroupsParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ GroupIds []pgtype.UUID `json:"group_ids"`+ NeedsYouTypes []string `json:"needs_you_types"`+ ReadOnly bool `json:"read_only"`+}++// Archives the listed issue groups (items without an issue group on their own+// id) as long as they are still only updates: nothing in the group is addressed+// to the member, and the group is not snoozed. With read_only, a group also has+// to be read, which is the state of its newest active row, the one the Inbox+// renders.+//+// The Inbox drops an update once it has been read and clears the section on+// request (MUL-9215). Both name the groups the member was looking at, and the+// conditions are checked again here, so a mention or a new unread update that+// arrived in between keeps its group in the Inbox.+//+// "Addressed to the member" follows inbox.EffectiveSection, as+// CountNeedsYouInboxByWorkspace does. Keep the three in step.+func (q *Queries) ArchiveInboxUpdateGroups(ctx context.Context, arg ArchiveInboxUpdateGroupsParams) (int64, error) {+ result, err := q.db.Exec(ctx, archiveInboxUpdateGroups,+ arg.WorkspaceID,+ arg.RecipientID,+ arg.GroupIds,+ arg.NeedsYouTypes,+ arg.ReadOnly,+ )+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const countNeedsYouInboxByWorkspace = `-- name: CountNeedsYouInboxByWorkspace :many+SELECT i.workspace_id, count(DISTINCT COALESCE(i.issue_id, i.id)) AS count+FROM inbox_item i+JOIN member m ON m.workspace_id = i.workspace_id AND m.user_id = i.recipient_id+WHERE i.recipient_type = 'member'+ AND i.recipient_id = $1+ AND i.archived = false+ AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())+ AND (+ i.section = 'needs_you'+ OR (COALESCE(i.section, '') NOT IN ('needs_you', 'updates')+ AND i.read = false+ AND i.type = ANY($2::text[]))+ )+ -- MUL-8472: issues in private projects the recipient is outside of+ -- (neither a project member nor a workspace owner/admin) do not count.+ AND NOT (m.role NOT IN ('owner', 'admin') AND EXISTS (+ SELECT 1 FROM issue private_issue+ JOIN project private_project ON private_project.id = private_issue.project_id+ WHERE private_issue.id = i.issue_id+ AND private_project.visibility = 'private'+ AND NOT EXISTS (+ SELECT 1 FROM project_member pm+ WHERE pm.project_id = private_project.id AND pm.user_id = i.recipient_id+ )+ ))+GROUP BY i.workspace_id+`++type CountNeedsYouInboxByWorkspaceParams struct {+ RecipientID pgtype.UUID `json:"recipient_id"`+ NeedsYouTypes []string `json:"needs_you_types"`+}++type CountNeedsYouInboxByWorkspaceRow struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Count int64 `json:"count"`+}++// Per-workspace count of issues waiting on a recipient member: the rows of the+// Inbox's "Needs you" section, which is what the Inbox badge shows (MUL-9215).+// One per issue (items without an issue count on their own id) that has an+// active row addressed to the member (inbox.SectionNeedsYou) which is not+// snoozed right now. Read state does not matter: opening an issue is not+// handling it, so it counts until the member acts on it or archives it.+//+// A snoozed issue has that wake time on every row it had when it was snoozed,+// so a row without one is something addressed to the member since, and it+// brings the issue back early. That is why the snooze test is per row.+//+// Rows written before sections were stored follow inbox.EffectiveSection:+// unread and of a type addressed to the member (needs_you_types). Keep the two+// in step.+//+// The member join keeps counts scoped to workspaces the user still belongs to,+// so a stale item left behind in a workspace the user has since left cannot+// light the badge.+func (q *Queries) CountNeedsYouInboxByWorkspace(ctx context.Context, arg CountNeedsYouInboxByWorkspaceParams) ([]CountNeedsYouInboxByWorkspaceRow, error) {+ rows, err := q.db.Query(ctx, countNeedsYouInboxByWorkspace, arg.RecipientID, arg.NeedsYouTypes)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []CountNeedsYouInboxByWorkspaceRow{}+ for rows.Next() {+ var i CountNeedsYouInboxByWorkspaceRow+ if err := rows.Scan(&i.WorkspaceID, &i.Count); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const countUnreadInbox = `-- name: CountUnreadInbox :oneSELECT count(*) FROM inbox_item iWHERE i.workspace_id = $1@@ -195,6 +378,8 @@ WHERE i.workspace_id = $1AND i.recipient_id = $3AND i.read = falseAND i.archived = false+ -- A snoozed row is out of the Inbox until its time passes.+ AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())-- MUL-8472: private projects the caller cannot see.AND ($4::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (SELECT 1 FROM issue hidden_issue@@ -232,6 +417,8 @@ FROM (WHERE i.recipient_type = 'member'AND i.recipient_id = $1AND i.archived = false+ -- A snoozed row is out of the Inbox until its time passes.+ AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())-- MUL-8472: issues in private projects the recipient is outside of-- (neither a project member nor a workspace owner/admin) do not count.AND NOT (m.role NOT IN ('owner', 'admin') AND EXISTS (@@ -290,9 +477,9 @@ const createInboxItem = `-- name: CreateInboxItem :oneINSERT INTO inbox_item (workspace_id, recipient_type, recipient_id,type, severity, issue_id, title, body,- actor_type, actor_id, details, id+ actor_type, actor_id, details, id, section, read)-SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE($12::uuid, gen_random_uuid())+SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE($12::uuid, gen_random_uuid()), $13::text, COALESCE($14::boolean, false)WHERE (($2::text = 'member' AND EXISTS (SELECT 1 FROM member WHERE workspace_id = $1 AND user_id = $3)) OR ($2::text = 'agent' AND EXISTS (@@ -313,7 +500,7 @@ AND NOT ($2::text = 'member' AND EXISTS (AND manager.role IN ('owner', 'admin'))))-RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section+RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until`type CreateInboxItemParams struct {@@ -329,10 +516,16 @@ type CreateInboxItemParams struct {ActorID pgtype.UUID `json:"actor_id"`Details []byte `json:"details"`ID pgtype.UUID `json:"id"`+ Section pgtype.Text `json:"section"`+ Read pgtype.Bool `json:"read"`}// A missing recipient is a quiet skip (pgx.ErrNoRows), not a delivery failure.// Check the insertion snapshot without adding recipient row locks.+//+// `read` is set only for a row that reports the recipient's own action (a run+// they stopped themselves): it belongs in their Inbox, and there is nothing in+// it they have not seen.// MUL-8472: a member outside a private project gets no notification about its// issues. Owners/admins and project members do.func (q *Queries) CreateInboxItem(ctx context.Context, arg CreateInboxItemParams) (InboxItem, error) {@@ -349,6 +542,8 @@ func (q *Queries) CreateInboxItem(ctx context.Context, arg CreateInboxItemParamsarg.ActorID,arg.Details,arg.ID,+ arg.Section,+ arg.Read,)var i InboxItemerr := row.Scan(@@ -368,13 +563,14 @@ func (q *Queries) CreateInboxItem(ctx context.Context, arg CreateInboxItemParams&i.ActorID,&i.Details,&i.Section,+ &i.SnoozedUntil,)return i, err}const deleteInboxGroup = `-- name: DeleteInboxGroup :execrowsWITH target AS (- SELECT selected.id, selected.workspace_id, selected.recipient_type, selected.recipient_id, selected.type, selected.severity, selected.issue_id, selected.title, selected.body, selected.read, selected.archived, selected.created_at, selected.actor_type, selected.actor_id, selected.details, selected.section FROM inbox_item selected+ SELECT selected.id, selected.workspace_id, selected.recipient_type, selected.recipient_id, selected.type, selected.severity, selected.issue_id, selected.title, selected.body, selected.read, selected.archived, selected.created_at, selected.actor_type, selected.actor_id, selected.details, selected.section, selected.snoozed_until FROM inbox_item selectedWHERE selected.id = $1 AND selected.workspace_id = $2AND selected.recipient_type = 'member' AND selected.recipient_id = $3)@@ -404,7 +600,7 @@ func (q *Queries) DeleteInboxGroup(ctx context.Context, arg DeleteInboxGroupPara}const getInboxItem = `-- name: GetInboxItem :one-SELECT id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section FROM inbox_item+SELECT id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until FROM inbox_itemWHERE id = $1`@@ -428,12 +624,13 @@ func (q *Queries) GetInboxItem(ctx context.Context, id pgtype.UUID) (InboxItem,&i.ActorID,&i.Details,&i.Section,+ &i.SnoozedUntil,)return i, err}const getInboxItemInWorkspace = `-- name: GetInboxItemInWorkspace :one-SELECT id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section FROM inbox_item+SELECT id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until FROM inbox_itemWHERE id = $1 AND workspace_id = $2`@@ -462,6 +659,7 @@ func (q *Queries) GetInboxItemInWorkspace(ctx context.Context, arg GetInboxItemI&i.ActorID,&i.Details,&i.Section,+ &i.SnoozedUntil,)return i, err}@@ -517,7 +715,7 @@ WITH eligible_archived AS MATERIALIZED (UNIONSELECT id FROM comment_anchors)-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,+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,iss.status AS issue_status,iss.priority AS issue_priority,iss.project_id AS issue_project_id,@@ -557,6 +755,7 @@ type ListArchivedInboxItemsRow struct {ActorID pgtype.UUID `json:"actor_id"`Details []byte `json:"details"`Section pgtype.Text `json:"section"`+ SnoozedUntil pgtype.Timestamptz `json:"snoozed_until"`IssueStatus pgtype.Text `json:"issue_status"`IssuePriority pgtype.Text `json:"issue_priority"`IssueProjectID pgtype.UUID `json:"issue_project_id"`@@ -618,6 +817,7 @@ func (q *Queries) ListArchivedInboxItems(ctx context.Context, arg ListArchivedIn&i.ActorID,&i.Details,&i.Section,+ &i.SnoozedUntil,&i.IssueStatus,&i.IssuePriority,&i.IssueProjectID,@@ -637,7 +837,7 @@ func (q *Queries) ListArchivedInboxItems(ctx context.Context, arg ListArchivedIn}const listInboxItems = `-- name: ListInboxItems :many-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,+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,iss.status AS issue_status,iss.priority AS issue_priority,iss.project_id AS issue_project_id,@@ -678,6 +878,7 @@ type ListInboxItemsRow struct {ActorID pgtype.UUID `json:"actor_id"`Details []byte `json:"details"`Section pgtype.Text `json:"section"`+ SnoozedUntil pgtype.Timestamptz `json:"snoozed_until"`IssueStatus pgtype.Text `json:"issue_status"`IssuePriority pgtype.Text `json:"issue_priority"`IssueProjectID pgtype.UUID `json:"issue_project_id"`@@ -721,6 +922,7 @@ func (q *Queries) ListInboxItems(ctx context.Context, arg ListInboxItemsParams)&i.ActorID,&i.Details,&i.Section,+ &i.SnoozedUntil,&i.IssueStatus,&i.IssuePriority,&i.IssueProjectID,@@ -774,7 +976,7 @@ WITH target AS ()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+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`// Opening a row in the inbox opens its issue, so it reads every active unread@@ -806,6 +1008,7 @@ func (q *Queries) MarkInboxRead(ctx context.Context, id pgtype.UUID) (InboxItem,&i.ActorID,&i.Details,&i.Section,+ &i.SnoozedUntil,)return i, err}@@ -842,7 +1045,7 @@ func (q *Queries) MarkInboxReadByIssue(ctx context.Context, arg MarkInboxReadByIconst markInboxUnread = `-- name: MarkInboxUnread :oneUPDATE inbox_item SET read = falseWHERE id = $1-RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section+RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until`// Item-level, unlike MarkInboxRead: the inbox renders one row per issue@@ -871,12 +1074,136 @@ func (q *Queries) MarkInboxUnread(ctx context.Context, id pgtype.UUID) (InboxIte&i.ActorID,&i.Details,&i.Section,+ &i.SnoozedUntil,)return i, err}+const markRestoredInboxUpdateUnread = `-- name: MarkRestoredInboxUpdateUnread :execrows+WITH target AS (+ SELECT t.id, t.workspace_id, t.recipient_type, t.recipient_id, t.issue_id+ FROM inbox_item t+ WHERE t.id = $1+), restored AS (+ SELECT i.id, i.created_at,+ (COALESCE(i.section, '') = 'needs_you'+ OR (COALESCE(i.section, '') NOT IN ('needs_you', 'updates')+ AND i.read = false+ AND i.type = ANY($2::text[]))) AS needs_you+ FROM inbox_item i+ JOIN target+ ON i.workspace_id = target.workspace_id+ AND i.recipient_type = target.recipient_type+ AND i.recipient_id = target.recipient_id+ WHERE i.archived = false+ AND (i.id = target.id OR i.issue_id = target.issue_id)+)+UPDATE inbox_item u SET read = false+WHERE u.id = (SELECT r.id FROM restored r ORDER BY r.created_at DESC, r.id DESC LIMIT 1)+ AND u.read = true+ AND NOT EXISTS (SELECT 1 FROM restored r WHERE r.needs_you)+`++type MarkRestoredInboxUpdateUnreadParams struct {+ ID pgtype.UUID `json:"id"`+ NeedsYouTypes []string `json:"needs_you_types"`+}++// A restored update comes back unread. The Inbox drops an update once it is+// read (MUL-9215), so one restored as read would leave again at once.+//+// Flips the newest active row on the item's issue, the one the Inbox renders,+// and only while the group is an update: nothing in it is addressed to the+// member (same test as ArchiveInboxUpdateGroups). An issue that needs the+// member stays listed whatever its read state, so it keeps the state it was+// archived in (UnarchiveInboxItem).+func (q *Queries) MarkRestoredInboxUpdateUnread(ctx context.Context, arg MarkRestoredInboxUpdateUnreadParams) (int64, error) {+ result, err := q.db.Exec(ctx, markRestoredInboxUpdateUnread, arg.ID, arg.NeedsYouTypes)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const nextInboxWakeByWorkspace = `-- name: NextInboxWakeByWorkspace :many+SELECT i.workspace_id, min(i.snoozed_until)::timestamptz AS next_wake_at+FROM inbox_item i+JOIN member m ON m.workspace_id = i.workspace_id AND m.user_id = i.recipient_id+WHERE i.recipient_type = 'member'+ AND i.recipient_id = $1+ AND i.archived = false+ AND i.snoozed_until > now()+GROUP BY i.workspace_id+`++type NextInboxWakeByWorkspaceRow struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ NextWakeAt pgtype.Timestamptz `json:"next_wake_at"`+}++// Per-workspace time the next snoozed row of a recipient member comes back.+// Both counts above leave snoozed rows out, and nothing is written when a+// snooze runs out, so a client re-reads the summary at this time instead of+// showing the old counts until some unrelated event (MUL-9215).+func (q *Queries) NextInboxWakeByWorkspace(ctx context.Context, recipientID pgtype.UUID) ([]NextInboxWakeByWorkspaceRow, error) {+ rows, err := q.db.Query(ctx, nextInboxWakeByWorkspace, recipientID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []NextInboxWakeByWorkspaceRow{}+ for rows.Next() {+ var i NextInboxWakeByWorkspaceRow+ if err := rows.Scan(&i.WorkspaceID, &i.NextWakeAt); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const snoozeInboxGroup = `-- name: SnoozeInboxGroup :execrows+WITH target AS (+ SELECT t.id, t.workspace_id, t.recipient_type, t.recipient_id, t.issue_id+ FROM inbox_item t+ WHERE t.id = $2+)+UPDATE inbox_item i+SET snoozed_until = $1::timestamptz,+ read = CASE WHEN i.id = target.id THEN false ELSE i.read END+FROM target+WHERE i.workspace_id = target.workspace_id+ AND i.recipient_type = target.recipient_type+ AND i.recipient_id = target.recipient_id+ AND i.archived = false+ AND (i.id = target.id OR i.issue_id = target.issue_id)+`++type SnoozeInboxGroupParams struct {+ SnoozedUntil pgtype.Timestamptz `json:"snoozed_until"`+ ID pgtype.UUID `json:"id"`+}++// Snoozing is issue-level, like archiving: every active row the recipient has+// on the item's issue carries the same wake time. Items without an issue are+// their own group.+//+// The item itself, the one the Inbox row shows, becomes unread so the issue+// comes back as new when the time passes. Its siblings keep their read state,+// for the reason MarkInboxUnread gives.+func (q *Queries) SnoozeInboxGroup(ctx context.Context, arg SnoozeInboxGroupParams) (int64, error) {+ result, err := q.db.Exec(ctx, snoozeInboxGroup, arg.SnoozedUntil, arg.ID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const unarchiveInboxByIssue = `-- name: UnarchiveInboxByIssue :execrows-UPDATE inbox_item SET archived = false+UPDATE inbox_item SET archived = false, snoozed_until = NULLWHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_id = $4 AND archived = true`@@ -904,14 +1231,16 @@ func (q *Queries) UnarchiveInboxByIssue(ctx context.Context, arg UnarchiveInboxB}const unarchiveInboxItem = `-- name: UnarchiveInboxItem :one-UPDATE inbox_item SET archived = false+UPDATE inbox_item SET archived = false, snoozed_until = NULLWHERE id = $1-RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section+RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until`// Deliberately does not touch `read`: unarchiving restores an item to the main// inbox in the exact read/unread state it was archived in, so restoring an-// unread item legitimately raises the unread badge again (MUL-3736).+// unread item legitimately raises the unread badge again (MUL-3736). A snooze+// set before the archive is dropped: a restored item is one the member asked to+// see now.func (q *Queries) UnarchiveInboxItem(ctx context.Context, id pgtype.UUID) (InboxItem, error) {row := q.db.QueryRow(ctx, unarchiveInboxItem, id)var i InboxItem@@ -932,6 +1261,33 @@ func (q *Queries) UnarchiveInboxItem(ctx context.Context, id pgtype.UUID) (Inbox&i.ActorID,&i.Details,&i.Section,+ &i.SnoozedUntil,)return i, err}++const unsnoozeInboxGroup = `-- name: UnsnoozeInboxGroup :execrows+WITH target AS (+ SELECT t.id, t.workspace_id, t.recipient_type, t.recipient_id, t.issue_id+ FROM inbox_item t+ WHERE t.id = $1+)+UPDATE inbox_item i SET snoozed_until = NULL+FROM target+WHERE i.workspace_id = target.workspace_id+ AND i.recipient_type = target.recipient_type+ AND i.recipient_id = target.recipient_id+ AND i.archived = false+ AND i.snoozed_until IS NOT NULL+ AND (i.id = target.id OR i.issue_id = target.issue_id)+`++// Brings a snoozed issue back now. `read` is left alone: SnoozeInboxGroup+// already made the row unread.+func (q *Queries) UnsnoozeInboxGroup(ctx context.Context, id pgtype.UUID) (int64, error) {+ result, err := q.db.Exec(ctx, unsnoozeInboxGroup, id)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}diff --git a/server/pkg/db/generated/inbox_archive.sql.go b/server/pkg/db/generated/inbox_archive.sql.goindex 4fef26926d..c0f3578bc4 100644--- a/server/pkg/db/generated/inbox_archive.sql.go+++ b/server/pkg/db/generated/inbox_archive.sql.go@@ -20,7 +20,7 @@ WITH base AS MATERIALIZED (WHEN i.type IN ('issue_assigned', 'unassigned', 'assignee_changed', 'issue_subscribed') THEN 'assign'WHEN i.type = 'review_requested' THEN 'review'WHEN i.type IN ('issue_created', 'status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'- WHEN i.type IN ('task_completed', 'task_failed', 'agent_blocked', 'agent_completed') THEN 'run'+ WHEN i.type IN ('task_completed', 'task_failed', 'task_cancelled', 'agent_blocked', 'agent_completed') THEN 'run'ELSE 'system'END AS type_group,CASE WHEN i.actor_type = 'system' THEN 'system'@@ -215,7 +215,7 @@ WITH base AS MATERIALIZED (WHEN i.type IN ('issue_assigned', 'unassigned', 'assignee_changed', 'issue_subscribed') THEN 'assign'WHEN i.type = 'review_requested' THEN 'review'WHEN i.type IN ('issue_created', 'status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'- WHEN i.type IN ('task_completed', 'task_failed', 'agent_blocked', 'agent_completed') THEN 'run'+ WHEN i.type IN ('task_completed', 'task_failed', 'task_cancelled', 'agent_blocked', 'agent_completed') THEN 'run'ELSE 'system'END AS type_group,CASE WHEN i.actor_type = 'system' THEN 'system'@@ -290,7 +290,7 @@ WITH base AS MATERIALIZED (ORDER BY created_at DESC, id DESCLIMIT $19::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, selected.issue_status, selected.issue_priority,+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, selected.issue_status, selected.issue_priority,iss.project_id AS issue_project_id,iss.assignee_type AS issue_assignee_type,iss.assignee_id AS issue_assignee_id,@@ -403,6 +403,7 @@ func (q *Queries) ListArchivedInboxPage(ctx context.Context, arg ListArchivedInb&i.InboxItem.ActorID,&i.InboxItem.Details,&i.InboxItem.Section,+ &i.InboxItem.SnoozedUntil,&i.IssueStatus,&i.IssuePriority,&i.IssueProjectID,diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex b2f72a0816..5068fa58da 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -915,6 +915,7 @@ type InboxItem struct {ActorID pgtype.UUID `json:"actor_id"`Details []byte `json:"details"`Section pgtype.Text `json:"section"`+ SnoozedUntil pgtype.Timestamptz `json:"snoozed_until"`}type InstanceTelemetryState struct {diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex a2c3cc0ffa..02cc86d93a 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -1693,6 +1693,19 @@ SELECT EXISTS (SELECT 1 FROM agent_task_queue WHERE issue_id = $1);SELECT count(*) > 0 AS has_active FROM agent_task_queueWHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory');+-- name: HasOtherActiveRunStartedByMember :one+-- Whether the member has another run of their own still active on the issue,+-- besides the given task. The Inbox keeps the issue under "Working" while one+-- is (MUL-9215), so a cancelled sibling does not hand the issue back.+SELECT EXISTS (+ SELECT 1 FROM agent_task_queue+ WHERE issue_id = sqlc.arg(issue_id)+ AND id <> sqlc.arg(task_id)+ AND originator_user_id = sqlc.arg(originator_user_id)+ AND originator_source = 'direct_human'+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+) AS has_other;+-- name: HasPendingTaskForIssue :one-- Returns true if there is a queued or dispatched (but not yet running) task for the issue.-- Used by the coalescing queue: allow enqueue when a task is running (sodiff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sqlindex 50b4f1e415..c7313ed07e 100644--- a/server/pkg/db/queries/inbox.sql+++ b/server/pkg/db/queries/inbox.sql@@ -116,12 +116,16 @@ WHERE id = $1 AND workspace_id = $2;-- name: CreateInboxItem :one-- A missing recipient is a quiet skip (pgx.ErrNoRows), not a delivery failure.-- Check the insertion snapshot without adding recipient row locks.+--+-- `read` is set only for a row that reports the recipient's own action (a run+-- they stopped themselves): it belongs in their Inbox, and there is nothing in+-- it they have not seen.INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id,type, severity, issue_id, title, body,- actor_type, actor_id, details, id+ actor_type, actor_id, details, id, section, read)-SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())+SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE(sqlc.narg('id')::uuid, gen_random_uuid()), sqlc.narg('section')::text, COALESCE(sqlc.narg('read')::boolean, false)WHERE (($2::text = 'member' AND EXISTS (SELECT 1 FROM member WHERE workspace_id = $1 AND user_id = $3)) OR ($2::text = 'agent' AND EXISTS (@@ -213,8 +217,10 @@ WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_-- name: UnarchiveInboxItem :one-- Deliberately does not touch `read`: unarchiving restores an item to the main-- inbox in the exact read/unread state it was archived in, so restoring an--- unread item legitimately raises the unread badge again (MUL-3736).-UPDATE inbox_item SET archived = false+-- unread item legitimately raises the unread badge again (MUL-3736). A snooze+-- set before the archive is dropped: a restored item is one the member asked to+-- see now.+UPDATE inbox_item SET archived = false, snoozed_until = NULLWHERE id = $1RETURNING *;@@ -222,7 +228,7 @@ RETURNING *;-- Issue-level restore, mirroring ArchiveInboxByIssue: archiving one item-- archives every sibling for the same issue, so unarchiving must bring the-- whole group back. Leaves `read` untouched for the same reason as above.-UPDATE inbox_item SET archived = false+UPDATE inbox_item SET archived = false, snoozed_until = NULLWHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_id = $4 AND archived = true;-- name: ArchiveInboxByIssueAndType :many@@ -230,6 +236,53 @@ UPDATE inbox_item SET archived = trueWHERE workspace_id = $1 AND issue_id = $2 AND type = $3 AND archived = falseRETURNING recipient_type, recipient_id;+-- name: ArchiveInboxByIssueForAll :many+-- An issue that reached a done or cancelled status waits on no one, so it+-- leaves every recipient's Inbox at once (MUL-9215).+UPDATE inbox_item SET archived = true+WHERE workspace_id = $1 AND issue_id = $2 AND archived = false+RETURNING recipient_type, recipient_id;++-- name: SnoozeInboxGroup :execrows+-- Snoozing is issue-level, like archiving: every active row the recipient has+-- on the item's issue carries the same wake time. Items without an issue are+-- their own group.+--+-- The item itself, the one the Inbox row shows, becomes unread so the issue+-- comes back as new when the time passes. Its siblings keep their read state,+-- for the reason MarkInboxUnread gives.+WITH target AS (+ SELECT t.id, t.workspace_id, t.recipient_type, t.recipient_id, t.issue_id+ FROM inbox_item t+ WHERE t.id = sqlc.arg(id)+)+UPDATE inbox_item i+SET snoozed_until = sqlc.arg(snoozed_until)::timestamptz,+ read = CASE WHEN i.id = target.id THEN false ELSE i.read END+FROM target+WHERE i.workspace_id = target.workspace_id+ AND i.recipient_type = target.recipient_type+ AND i.recipient_id = target.recipient_id+ AND i.archived = false+ AND (i.id = target.id OR i.issue_id = target.issue_id);++-- name: UnsnoozeInboxGroup :execrows+-- Brings a snoozed issue back now. `read` is left alone: SnoozeInboxGroup+-- already made the row unread.+WITH target AS (+ SELECT t.id, t.workspace_id, t.recipient_type, t.recipient_id, t.issue_id+ FROM inbox_item t+ WHERE t.id = sqlc.arg(id)+)+UPDATE inbox_item i SET snoozed_until = NULL+FROM target+WHERE i.workspace_id = target.workspace_id+ AND i.recipient_type = target.recipient_type+ AND i.recipient_id = target.recipient_id+ AND i.archived = false+ AND i.snoozed_until IS NOT NULL+ AND (i.id = target.id OR i.issue_id = target.issue_id);+-- name: CountUnreadInbox :oneSELECT count(*) FROM inbox_item iWHERE i.workspace_id = sqlc.arg('workspace_id')@@ -237,6 +290,8 @@ WHERE i.workspace_id = sqlc.arg('workspace_id')AND i.recipient_id = sqlc.arg('recipient_id')AND i.read = falseAND i.archived = false+ -- A snoozed row is out of the Inbox until its time passes.+ AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())-- MUL-8472: private projects the caller cannot see.AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR i.issue_id IS NULL OR NOT EXISTS (SELECT 1 FROM issue hidden_issue@@ -265,6 +320,8 @@ FROM (WHERE i.recipient_type = 'member'AND i.recipient_id = $1AND i.archived = false+ -- A snoozed row is out of the Inbox until its time passes.+ AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())-- MUL-8472: issues in private projects the recipient is outside of-- (neither a project member nor a workspace owner/admin) do not count.AND NOT (m.role NOT IN ('owner', 'admin') AND EXISTS (@@ -282,6 +339,66 @@ FROM (WHERE newest.read = falseGROUP BY newest.workspace_id;+-- name: CountNeedsYouInboxByWorkspace :many+-- Per-workspace count of issues waiting on a recipient member: the rows of the+-- Inbox's "Needs you" section, which is what the Inbox badge shows (MUL-9215).+-- One per issue (items without an issue count on their own id) that has an+-- active row addressed to the member (inbox.SectionNeedsYou) which is not+-- snoozed right now. Read state does not matter: opening an issue is not+-- handling it, so it counts until the member acts on it or archives it.+--+-- A snoozed issue has that wake time on every row it had when it was snoozed,+-- so a row without one is something addressed to the member since, and it+-- brings the issue back early. That is why the snooze test is per row.+--+-- Rows written before sections were stored follow inbox.EffectiveSection:+-- unread and of a type addressed to the member (needs_you_types). Keep the two+-- in step.+--+-- The member join keeps counts scoped to workspaces the user still belongs to,+-- so a stale item left behind in a workspace the user has since left cannot+-- light the badge.+SELECT i.workspace_id, count(DISTINCT COALESCE(i.issue_id, i.id)) AS count+FROM inbox_item i+JOIN member m ON m.workspace_id = i.workspace_id AND m.user_id = i.recipient_id+WHERE i.recipient_type = 'member'+ AND i.recipient_id = sqlc.arg(recipient_id)+ AND i.archived = false+ AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())+ AND (+ i.section = 'needs_you'+ OR (COALESCE(i.section, '') NOT IN ('needs_you', 'updates')+ AND i.read = false+ AND i.type = ANY(sqlc.arg(needs_you_types)::text[]))+ )+ -- MUL-8472: issues in private projects the recipient is outside of+ -- (neither a project member nor a workspace owner/admin) do not count.+ AND NOT (m.role NOT IN ('owner', 'admin') AND EXISTS (+ SELECT 1 FROM issue private_issue+ JOIN project private_project ON private_project.id = private_issue.project_id+ WHERE private_issue.id = i.issue_id+ AND private_project.visibility = 'private'+ AND NOT EXISTS (+ SELECT 1 FROM project_member pm+ WHERE pm.project_id = private_project.id AND pm.user_id = i.recipient_id+ )+ ))+GROUP BY i.workspace_id;++-- name: NextInboxWakeByWorkspace :many+-- Per-workspace time the next snoozed row of a recipient member comes back.+-- Both counts above leave snoozed rows out, and nothing is written when a+-- snooze runs out, so a client re-reads the summary at this time instead of+-- showing the old counts until some unrelated event (MUL-9215).+SELECT i.workspace_id, min(i.snoozed_until)::timestamptz AS next_wake_at+FROM inbox_item i+JOIN member m ON m.workspace_id = i.workspace_id AND m.user_id = i.recipient_id+WHERE i.recipient_type = 'member'+ AND i.recipient_id = sqlc.arg(recipient_id)+ AND i.archived = false+ AND i.snoozed_until > now()+GROUP BY i.workspace_id;+-- name: MarkAllInboxRead :execrowsUPDATE inbox_item SET read = trueWHERE workspace_id = $1 AND recipient_type = 'member' AND recipient_id = $2 AND archived = false AND read = false;@@ -333,6 +450,82 @@ WHERE i.workspace_id = $1AND i.archived = falseAND COALESCE(i.issue_id, i.id) = selected.group_id;+-- name: ArchiveInboxUpdateGroups :execrows+-- Archives the listed issue groups (items without an issue group on their own+-- id) as long as they are still only updates: nothing in the group is addressed+-- to the member, and the group is not snoozed. With read_only, a group also has+-- to be read, which is the state of its newest active row, the one the Inbox+-- renders.+--+-- The Inbox drops an update once it has been read and clears the section on+-- request (MUL-9215). Both name the groups the member was looking at, and the+-- conditions are checked again here, so a mention or a new unread update that+-- arrived in between keeps its group in the Inbox.+--+-- "Addressed to the member" follows inbox.EffectiveSection, as+-- CountNeedsYouInboxByWorkspace does. Keep the three in step.+WITH candidates AS (+ SELECT i.id, COALESCE(i.issue_id, i.id) AS group_id, i.read, i.created_at,+ i.snoozed_until, i.section, i.type+ FROM inbox_item i+ WHERE i.workspace_id = sqlc.arg(workspace_id)+ AND i.recipient_type = 'member'+ AND i.recipient_id = sqlc.arg(recipient_id)+ AND i.archived = false+ AND (i.issue_id = ANY(sqlc.arg(group_ids)::uuid[])+ OR (i.issue_id IS NULL AND i.id = ANY(sqlc.arg(group_ids)::uuid[])))+), update_groups AS (+ SELECT c.group_id+ FROM candidates c+ GROUP BY c.group_id+ -- COALESCE: a row from before sections were stored has none, and a NULL+ -- comparison would leave the whole test NULL.+ HAVING NOT bool_or(+ COALESCE(c.section, '') = 'needs_you'+ OR (COALESCE(c.section, '') NOT IN ('needs_you', 'updates')+ AND c.read = false+ AND c.type = ANY(sqlc.arg(needs_you_types)::text[])))+ AND NOT bool_or(c.snoozed_until IS NOT NULL AND c.snoozed_until > now())+ AND (NOT sqlc.arg(read_only)::boolean+ OR (array_agg(c.read ORDER BY c.created_at DESC, c.id DESC))[1])+)+UPDATE inbox_item i SET archived = true+FROM candidates c+JOIN update_groups g ON g.group_id = c.group_id+WHERE i.id = c.id;++-- name: MarkRestoredInboxUpdateUnread :execrows+-- A restored update comes back unread. The Inbox drops an update once it is+-- read (MUL-9215), so one restored as read would leave again at once.+--+-- Flips the newest active row on the item's issue, the one the Inbox renders,+-- and only while the group is an update: nothing in it is addressed to the+-- member (same test as ArchiveInboxUpdateGroups). An issue that needs the+-- member stays listed whatever its read state, so it keeps the state it was+-- archived in (UnarchiveInboxItem).+WITH target AS (+ SELECT t.id, t.workspace_id, t.recipient_type, t.recipient_id, t.issue_id+ FROM inbox_item t+ WHERE t.id = sqlc.arg(id)+), restored AS (+ SELECT i.id, i.created_at,+ (COALESCE(i.section, '') = 'needs_you'+ OR (COALESCE(i.section, '') NOT IN ('needs_you', 'updates')+ AND i.read = false+ AND i.type = ANY(sqlc.arg(needs_you_types)::text[]))) AS needs_you+ FROM inbox_item i+ JOIN target+ ON i.workspace_id = target.workspace_id+ AND i.recipient_type = target.recipient_type+ AND i.recipient_id = target.recipient_id+ WHERE i.archived = false+ AND (i.id = target.id OR i.issue_id = target.issue_id)+)+UPDATE inbox_item u SET read = false+WHERE u.id = (SELECT r.id FROM restored r ORDER BY r.created_at DESC, r.id DESC LIMIT 1)+ AND u.read = true+ AND NOT EXISTS (SELECT 1 FROM restored r WHERE r.needs_you);+-- name: ArchiveCompletedInbox :execrowsUPDATE inbox_item i SET archived = trueWHERE i.workspace_id = $1 AND i.recipient_type = 'member' AND i.recipient_id = $2 AND i.archived = falsediff --git a/server/pkg/db/queries/inbox_archive.sql b/server/pkg/db/queries/inbox_archive.sqlindex e1f65ad715..cfc80b82b3 100644--- a/server/pkg/db/queries/inbox_archive.sql+++ b/server/pkg/db/queries/inbox_archive.sql@@ -14,7 +14,7 @@ WITH base AS MATERIALIZED (WHEN i.type IN ('issue_assigned', 'unassigned', 'assignee_changed', 'issue_subscribed') THEN 'assign'WHEN i.type = 'review_requested' THEN 'review'WHEN i.type IN ('issue_created', 'status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'- WHEN i.type IN ('task_completed', 'task_failed', 'agent_blocked', 'agent_completed') THEN 'run'+ WHEN i.type IN ('task_completed', 'task_failed', 'task_cancelled', 'agent_blocked', 'agent_completed') THEN 'run'ELSE 'system'END AS type_group,CASE WHEN i.actor_type = 'system' THEN 'system'@@ -127,7 +127,7 @@ WITH base AS MATERIALIZED (WHEN i.type IN ('issue_assigned', 'unassigned', 'assignee_changed', 'issue_subscribed') THEN 'assign'WHEN i.type = 'review_requested' THEN 'review'WHEN i.type IN ('issue_created', 'status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'- WHEN i.type IN ('task_completed', 'task_failed', 'agent_blocked', 'agent_completed') THEN 'run'+ WHEN i.type IN ('task_completed', 'task_failed', 'task_cancelled', 'agent_blocked', 'agent_completed') THEN 'run'ELSE 'system'END AS type_group,CASE WHEN i.actor_type = 'system' THEN 'system'diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 36047d5e71..dea9230ea3 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -54,6 +54,8 @@ const (EventInboxDeleted = "inbox:deleted"EventInboxBatchRead = "inbox:batch-read"EventInboxBatchArchived = "inbox:batch-archived"+ EventInboxSnoozed = "inbox:snoozed"+ EventInboxUnsnoozed = "inbox:unsnoozed"// Workspace eventsEventWorkspaceUpdated = "workspace:updated"