Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(inbox): deliver the report a squad finishes with when handoffs are muted (MUL-10054) (#11416)
Jiayuan Zhang33215cec572f
diff --git a/apps/docs/content/docs/inbox.fr.mdx b/apps/docs/content/docs/inbox.fr.mdxindex 276b357ba1..33c4da3b56 100644--- a/apps/docs/content/docs/inbox.fr.mdx+++ b/apps/docs/content/docs/inbox.fr.mdx@@ -171,7 +171,7 @@ En dessous, **Me notifier pour** active ou désactive chaque type de notificatio**Changements de statut** est désactivé par défaut ; tous les autres types sont activés. Un type désactivé ne crée aucune notification, et le réactiver ne fait pas revenir ce que vous avez manqué ; les changements restent enregistrés sur la tâche. Quelques types, comme les résultats de création rapide et les mises en pause d'automatisation, ne relèvent pas de ces 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.-Sous **Commentaires**, **Inclure les passations de squad** couvre les commentaires par lesquels le chef d'une squad et ses agents se transmettent le travail, sur une tâche assignée à la squad ou sur laquelle la squad a été @-mentionnée : le chef qui @-mentionne un agent ou une squad, et les agents qui lui rendent compte. Activé par défaut ; désactivez-le pour ne garder que les commentaires destinés à des personnes. Les commentaires qui vous @-mentionnent, vous ou quelqu'un d'autre, les réponses d'agent au commentaire d'une personne, les exécutions d'agent en échec et les statuts qui demandent votre attention arrivent toujours.+Sous **Commentaires**, **Inclure les passations de squad** couvre les commentaires par lesquels le chef d'une squad et ses agents se transmettent le travail, sur une tâche assignée à la squad ou sur laquelle la squad a été @-mentionnée : le chef qui @-mentionne un agent ou une squad, et les agents qui lui rendent compte. Activé par défaut ; désactivez-le pour ne garder que les commentaires destinés à des personnes. Les commentaires qui vous @-mentionnent, vous ou quelqu'un d'autre, les réponses d'agent au commentaire d'une personne, et les exécutions d'agent en échec arrivent toujours. Le compte rendu final de la squad arrive aussi : quand l'exécution du chef qui suit le compte rendu d'un agent se termine sans transmettre le travail ni écrire de commentaire, ce compte rendu est remis à ce moment-là. Les changements de statut suivent l'interrupteur **Changements de statut**.## Étapes suivantesdiff --git a/apps/docs/content/docs/inbox.ja.mdx b/apps/docs/content/docs/inbox.ja.mdxindex 190f5105d7..eb30f03172 100644--- a/apps/docs/content/docs/inbox.ja.mdx+++ b/apps/docs/content/docs/inbox.ja.mdx@@ -171,7 +171,7 @@ multica inbox snooze <id>... --until tomorrow # RFC 3339、30m、3h、1d、1w**ステータス変更** は既定でオフ、ほかの種類は既定でオンです。オフにした種類の通知は作られず、オンに戻しても見逃した分は戻りません。変更そのものはタスクに記録され続けます。エージェント経由の作成結果、オートパイロットの一時停止など一部のタイプはこれらのグループの対象外で、常に届きます。システム通知とブラウザ通知はデスクトップのバナーを制御するもので、インボックス自体は変わりません。-**コメント** の下の **スクワッド内の引き継ぎを含める** は、リーダーとエージェントが作業を受け渡すコメントが対象です。スクワッドに割り当てたタスクでも、コメントでスクワッドを @ メンションしたタスクでも同じです。リーダーがエージェントやスクワッドを @ メンションして依頼するコメントと、エージェントからの報告がこれに当たります。既定でオンで、オフにすると人に向けたコメントだけが届きます。あなたや他のメンバーを @ メンションしたコメント、人のコメントへのエージェントの返信、エージェント実行の失敗、対応が必要なステータスは引き続き届きます。+**コメント** の下の **スクワッド内の引き継ぎを含める** は、リーダーとエージェントが作業を受け渡すコメントが対象です。スクワッドに割り当てたタスクでも、コメントでスクワッドを @ メンションしたタスクでも同じです。リーダーがエージェントやスクワッドを @ メンションして依頼するコメントと、エージェントからの報告がこれに当たります。既定でオンで、オフにすると人に向けたコメントだけが届きます。あなたや他のメンバーを @ メンションしたコメント、人のコメントへのエージェントの返信、エージェント実行の失敗は引き続き届きます。スクワッドが作業を終えたときの最終報告も届きます。エージェントの報告のあと、リーダーの実行が作業を渡さずコメントも書かずに終わったら、その報告がそこで届きます。ステータス変更は **ステータス変更** のスイッチに従います。## 次のステップdiff --git a/apps/docs/content/docs/inbox.ko.mdx b/apps/docs/content/docs/inbox.ko.mdxindex 64e26b141c..7f2c57754d 100644--- a/apps/docs/content/docs/inbox.ko.mdx+++ b/apps/docs/content/docs/inbox.ko.mdx@@ -171,7 +171,7 @@ multica inbox snooze <id>... --until tomorrow # RFC 3339, 30m, 3h, 1d, 1w; uns**상태 변경**은 기본적으로 꺼져 있고 나머지 종류는 켜져 있습니다. 끈 종류의 알림은 만들어지지 않으며, 다시 켜도 놓친 알림은 돌아오지 않습니다. 변경 사항 자체는 태스크에 계속 기록됩니다. 빠른 생성 결과, 자동화 일시 중지 같은 일부 유형은 이 그룹들과 관계없이 항상 전달됩니다. 시스템 알림과 브라우저 알림 설정은 데스크톱 배너를 제어할 뿐 인박스 자체를 바꾸지 않습니다.-**댓글** 아래의 **스쿼드 내부 인계 포함**은 리더와 에이전트가 작업을 주고받는 댓글을 다룹니다. 스쿼드에 지정된 태스크든, 댓글에서 스쿼드를 @멘션한 태스크든 같습니다. 리더가 에이전트나 스쿼드를 @멘션해 일을 맡기는 댓글과 에이전트의 보고가 여기에 해당합니다. 기본적으로 켜져 있으며, 끄면 사람에게 향한 댓글만 받습니다. 나나 다른 멤버를 @멘션한 댓글, 사람의 댓글에 대한 에이전트 답글, 실패한 에이전트 실행, 확인이 필요한 상태는 계속 전달됩니다.+**댓글** 아래의 **스쿼드 내부 인계 포함**은 리더와 에이전트가 작업을 주고받는 댓글을 다룹니다. 스쿼드에 지정된 태스크든, 댓글에서 스쿼드를 @멘션한 태스크든 같습니다. 리더가 에이전트나 스쿼드를 @멘션해 일을 맡기는 댓글과 에이전트의 보고가 여기에 해당합니다. 기본적으로 켜져 있으며, 끄면 사람에게 향한 댓글만 받습니다. 나나 다른 멤버를 @멘션한 댓글, 사람의 댓글에 대한 에이전트 답글, 실패한 에이전트 실행은 계속 전달됩니다. 스쿼드가 작업을 마칠 때의 최종 보고도 전달됩니다. 에이전트가 보고한 뒤 리더의 실행이 작업을 넘기지도, 댓글을 쓰지도 않고 끝나면 그 보고가 그때 전달됩니다. 상태 변경은 **상태 변경** 스위치를 따릅니다.## 다음 단계diff --git a/apps/docs/content/docs/inbox.mdx b/apps/docs/content/docs/inbox.mdxindex 0b49065a01..3c07fcdb73 100644--- a/apps/docs/content/docs/inbox.mdx+++ b/apps/docs/content/docs/inbox.mdx@@ -171,7 +171,7 @@ Below them, **Notify me about** turns each kind of notification on or off. These**Status changes** starts off; every other kind starts on. A kind that's turned off creates no notification, and turning it back on doesn't bring back what you missed; the changes are still recorded on the issue. A few types, such as quick-create results and autopilot pauses, sit outside these groups and are always delivered. System and browser notifications control desktop banners and don't change the inbox itself.-Under **Comments**, **Include squad handoffs** covers the comments a squad's leader and agents pass work to each other with, on an issue assigned to the squad or one the squad was @-mentioned on: the leader @-mentioning an agent or squad, and the agents reporting back. It starts on; turn it off to keep only the comments meant for people. Comments that @-mention you or anyone else, agent replies to a person's comment, failed agent runs, and statuses that need attention still arrive.+Under **Comments**, **Include squad handoffs** covers the comments a squad's leader and agents pass work to each other with, on an issue assigned to the squad or one the squad was @-mentioned on: the leader @-mentioning an agent or squad, and the agents reporting back. It starts on; turn it off to keep only the comments meant for people. Comments that @-mention you or anyone else, agent replies to a person's comment, and failed agent runs still arrive. The report a squad finishes with arrives too: when the leader's run after an agent's report ends without passing the work on or writing a comment, that report is delivered then. Status changes follow the **Status changes** switch.## Next stepsdiff --git a/apps/docs/content/docs/inbox.zh-Hant.mdx b/apps/docs/content/docs/inbox.zh-Hant.mdxindex 56b23a10ba..92c51069b6 100644--- a/apps/docs/content/docs/inbox.zh-Hant.mdx+++ b/apps/docs/content/docs/inbox.zh-Hant.mdx@@ -171,7 +171,7 @@ multica inbox snooze <id>... --until tomorrow # RFC 3339、30m、3h、1d、1w**狀態變更**預設關閉,其餘類型預設開啟。關閉某一類後,不再建立這類通知,重新開啟也不會補回錯過的通知;相關變化仍然儲存在任務中。快速建立結果和自動化暫停等少數類型不受這些分組控制,始終投遞。系統通知和瀏覽器通知控制的是桌面橫幅,不會改變收件箱本身。-**評論**下的**包含小隊內部交接**針對隊長和 AI 代理之間傳遞工作的評論,無論任務是指派給小隊,還是在評論裡 @ 了小隊:隊長 @ AI 代理或小隊指派工作,以及 AI 代理向隊長回報。預設開啟;關閉後只保留寫給人的評論。@ 你或其他成員的評論、AI 代理對某人評論的回覆、AI 代理執行失敗和需要關注的狀態照常通知。+**評論**下的**包含小隊內部交接**針對隊長和 AI 代理之間傳遞工作的評論,無論任務是指派給小隊,還是在評論裡 @ 了小隊:隊長 @ AI 代理或小隊指派工作,以及 AI 代理向隊長回報。預設開啟;關閉後只保留寫給人的評論。@ 你或其他成員的評論、AI 代理對某人評論的回覆和 AI 代理執行失敗照常通知。小隊收尾時的最終回報也會送達:AI 代理回報後,隊長的執行如果既沒有繼續指派工作、也沒有發評論就結束了,那則回報會在這時送達。狀態變化依**狀態變更**開關通知。## 接下來diff --git a/apps/docs/content/docs/inbox.zh.mdx b/apps/docs/content/docs/inbox.zh.mdxindex 1d732aa18a..85b642d451 100644--- a/apps/docs/content/docs/inbox.zh.mdx+++ b/apps/docs/content/docs/inbox.zh.mdx@@ -171,7 +171,7 @@ multica inbox snooze <id>... --until tomorrow # RFC 3339、30m、3h、1d、1w**状态变更**默认关闭,其余类型默认打开。关闭某一类后,不再创建这类通知,重新打开也不会补回错过的通知;相关变化仍然保存在任务中。快速创建结果和自动化暂停等少数类型不受这些分组控制,始终投递。系统通知和浏览器通知控制的是桌面横幅,不会改变收件箱本身。-**评论**下的**包含小队内部交接**针对队长和智能体之间传递工作的评论,无论任务是指派给小队,还是在评论里 @ 了小队:队长 @ 智能体或小队派活,以及智能体向队长回报。默认打开;关闭后只保留写给人的评论。@ 你或其他成员的评论、智能体对某人评论的回复、智能体运行失败和需要关注的状态照常通知。+**评论**下的**包含小队内部交接**针对队长和智能体之间传递工作的评论,无论任务是指派给小队,还是在评论里 @ 了小队:队长 @ 智能体或小队派活,以及智能体向队长回报。默认打开;关闭后只保留写给人的评论。@ 你或其他成员的评论、智能体对某人评论的回复和智能体运行失败照常通知。小队收尾时的最终回报也会送达:智能体回报后,队长的运行如果既没有继续派活、也没有发评论就结束了,那条回报会在这时送达。状态变化按**状态变更**开关通知。## 接下来diff --git a/apps/mobile/locales/en/settings.json b/apps/mobile/locales/en/settings.jsonindex 45b619527a..5445e829ce 100644--- a/apps/mobile/locales/en/settings.json+++ b/apps/mobile/locales/en/settings.json@@ -72,7 +72,7 @@"comments": "Comments","comments_description": "New comments on issues you're subscribed to.","squad_handoffs": "Include squad handoffs",- "squad_handoffs_description": "Comments a squad's leader and agents pass work to each other with. @mentions of you, failed agent runs and statuses that need attention still arrive.",+ "squad_handoffs_description": "Comments a squad's leader and agents pass work to each other with. @mentions of you, failed agent runs and the report a squad finishes with still arrive.","mentions": "Mentions","mentions_description": "When someone @mentions you, including @all and @squad.","reactions": "Reactions",diff --git a/apps/mobile/locales/zh-Hans/settings.json b/apps/mobile/locales/zh-Hans/settings.jsonindex ad36eb7d08..a120e6d171 100644--- a/apps/mobile/locales/zh-Hans/settings.json+++ b/apps/mobile/locales/zh-Hans/settings.json@@ -72,7 +72,7 @@"comments": "评论","comments_description": "你订阅的任务有新评论时。","squad_handoffs": "包含小队内部交接",- "squad_handoffs_description": "小队队长给成员派活、成员向队长回报的评论。@你、智能体运行失败和需要人工关注的状态照常通知。",+ "squad_handoffs_description": "小队队长给成员派活、成员向队长回报的评论。@你、智能体运行失败和小队收尾时的最终回报照常通知。","mentions": "提及","mentions_description": "有人用 @ 提到你时,包括 @all 和 @squad。","reactions": "表情回应",diff --git a/apps/mobile/locales/zh-Hant/settings.json b/apps/mobile/locales/zh-Hant/settings.jsonindex 0b636a9a76..a5cccc1793 100644--- a/apps/mobile/locales/zh-Hant/settings.json+++ b/apps/mobile/locales/zh-Hant/settings.json@@ -72,7 +72,7 @@"comments": "評論","comments_description": "你訂閱的任務有新評論時。","squad_handoffs": "包含小隊內部交接",- "squad_handoffs_description": "小隊隊長指派工作給成員、成員向隊長回報的評論。@ 提及、AI 代理執行失敗和需要關注的狀態照常通知。",+ "squad_handoffs_description": "小隊隊長指派工作給成員、成員向隊長回報的評論。@ 提及、AI 代理執行失敗和小隊收尾時的最終回報照常通知。","mentions": "提及","mentions_description": "有人用 @ 提到你時,包括 @all 和 @squad。","reactions": "表情回應",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 818b511f8a..0dc436bd17 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -920,7 +920,7 @@},"squad_handoffs": {"label": "Include squad handoffs",- "description": "Comments a squad's leader and agents pass work to each other with. @mentions of you, failed agent runs and statuses that need attention still arrive."+ "description": "Comments a squad's leader and agents pass work to each other with. @mentions of you, failed agent runs and the report a squad finishes with still arrive."},"mentions": {"label": "Mentions",diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex 9c29db1ced..a11d746eb7 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -920,7 +920,7 @@},"squad_handoffs": {"label": "Incluir traspasos del squad",- "description": "Comentarios con los que el líder y los agentes de un squad se pasan el trabajo. Las @menciones, las ejecuciones de agente fallidas y los estados que requieren atención te siguen llegando."+ "description": "Comentarios con los que el líder y los agentes de un squad se pasan el trabajo. Las @menciones, las ejecuciones de agente fallidas y el informe final del squad te siguen llegando."},"mentions": {"label": "Menciones",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex b752c8ae90..55e68395ae 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -920,7 +920,7 @@},"squad_handoffs": {"label": "Inclure les passations de squad",- "description": "Commentaires par lesquels le chef et les agents d'un squad se transmettent le travail. Les @mentions, les exécutions d'agent échouées et les statuts qui nécessitent votre attention vous parviennent toujours."+ "description": "Commentaires par lesquels le chef et les agents d'un squad se transmettent le travail. Les @mentions, les exécutions d'agent échouées et le compte rendu final du squad vous parviennent toujours."},"mentions": {"label": "Mentions",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 05fca74ce1..0149f790a4 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -910,7 +910,7 @@},"squad_handoffs": {"label": "スクワッド内の引き継ぎを含める",- "description": "スクワッドのリーダーとエージェントが作業を受け渡すコメントです。@メンション、エージェントの実行失敗、確認が必要なステータスは引き続き通知されます。"+ "description": "スクワッドのリーダーとエージェントが作業を受け渡すコメントです。@メンション、エージェントの実行失敗、スクワッドが作業を終えたときの最終報告は引き続き通知されます。"},"mentions": {"label": "メンション",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex c4a45bec28..feaf2f41eb 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -910,7 +910,7 @@},"squad_handoffs": {"label": "스쿼드 내부 인계 포함",- "description": "스쿼드 리더와 에이전트가 서로 작업을 넘기는 댓글입니다. @멘션, 에이전트 실행 실패, 확인이 필요한 상태는 계속 알림이 옵니다."+ "description": "스쿼드 리더와 에이전트가 서로 작업을 넘기는 댓글입니다. @멘션, 에이전트 실행 실패, 스쿼드가 작업을 마칠 때의 최종 보고는 계속 알림이 옵니다."},"mentions": {"label": "멘션",diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex fa4c294137..3e77934026 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -952,7 +952,7 @@},"squad_handoffs": {"label": "Включать передачи внутри команды",- "description": "Комментарии, которыми лидер и агенты команды передают друг другу работу. @упоминания, ошибки запусков агентов и статусы, требующие внимания, по-прежнему приходят."+ "description": "Комментарии, которыми лидер и агенты команды передают друг другу работу. @упоминания, ошибки запусков агентов и итоговый отчёт, которым команда завершает работу, по-прежнему приходят."},"mentions": {"description": "Когда вас упоминают через @, в том числе через @all и @squad",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 7a712396cc..e42a4543a6 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -910,7 +910,7 @@},"squad_handoffs": {"label": "包含小队内部交接",- "description": "小队队长给成员派活、成员向队长回报的评论。@你、智能体运行失败和需要人工关注的状态照常通知。"+ "description": "小队队长给成员派活、成员向队长回报的评论。@你、智能体运行失败和小队收尾时的最终回报照常通知。"},"mentions": {"label": "提及",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex d857ed4f0b..eae5c6bcc6 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -910,7 +910,7 @@},"squad_handoffs": {"label": "包含小隊內部交接",- "description": "小隊隊長指派工作給成員、成員向隊長回報的評論。@ 提及、AI 代理執行失敗和需要關注的狀態照常通知。"+ "description": "小隊隊長指派工作給成員、成員向隊長回報的評論。@ 提及、AI 代理執行失敗和小隊收尾時的最終回報照常通知。"},"mentions": {"label": "提及",diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.goindex 465c65209a..f63a7c4125 100644--- a/server/cmd/server/notification_listeners.go+++ b/server/cmd/server/notification_listeners.go@@ -1283,7 +1283,11 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {)})- // task:completed — no inbox notification (completion is visible from status change)+ // task:completed — no notification of its own; a squad leader run that+ // ends its squad's chain delivers the handoff that woke it+ bus.Subscribe(protocol.EventTaskCompleted, func(e events.Event) {+ deliverSquadResult(ctx, queries, bus, e)+ })// task:failed — notify all subscribers except the agentbus.Subscribe(protocol.EventTaskFailed, func(e events.Event) {diff --git a/server/cmd/server/notification_squad_result.go b/server/cmd/server/notification_squad_result.gonew file mode 100644index 0000000000..48d53ddb13--- /dev/null+++ b/server/cmd/server/notification_squad_result.go@@ -0,0 +1,81 @@+package main++import (+ "context"+ "encoding/json"+ "log/slog"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/inbox"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// deliverSquadResult runs when an agent run completes. A squad leader run that+// a handoff woke, and that neither posted a comment, started another agent run+// nor left a wakeup waiting on its issue, is where the squad stopped passing+// the work on: the handoff that woke it is the squad's result (MUL-10054).+// Members who muted squad handoffs never received it, so it is delivered to+// them now as a new_comment row marked inbox.SquadResultDetail; Deliver keeps+// it from everyone else, who already have the handoff's own row.+//+// A leader that dispatched again or is waiting (for CI, say) keeps the chain+// going, and one that wrote to people has delivered its own comment, so none+// of them delivers the handoff.+func deliverSquadResult(ctx context.Context, queries *db.Queries, bus *events.Bus, e events.Event) {+ payload, ok := e.Payload.(map[string]any)+ if !ok {+ return+ }+ taskID, _ := payload["task_id"].(string)+ taskUUID, err := util.ParseUUID(taskID)+ if err != nil {+ return+ }+ task, err := queries.GetAgentTask(ctx, taskUUID)+ if err != nil || !task.IsLeaderTask || !task.SquadID.Valid || !task.IssueID.Valid || !task.TriggerCommentID.Valid {+ return+ }+ handoff, err := queries.GetCommentInWorkspace(ctx, db.GetCommentInWorkspaceParams{+ ID: task.TriggerCommentID,+ WorkspaceID: parseUUID(e.WorkspaceID),+ })+ if err != nil || handoff.DeletedAt.Valid || handoff.AuthorType != "agent" || handoff.AuthorID == task.AgentID || handoff.IssueID != task.IssueID {+ return+ }+ handoffID := util.UUIDToString(handoff.ID)+ if !isSquadHandoff(ctx, queries, e.WorkspaceID, handoffID, parseMentions(handoff.Content)) {+ return+ }++ // FAIL OPEN: a run whose follow-up cannot be read delivers the handoff.+ passedOn, err := queries.TaskPassedWorkOn(ctx, db.TaskPassedWorkOnParams{+ IssueID: task.IssueID,+ TaskID: task.ID,+ })+ if err != nil {+ slog.Warn("squad result: read leader run follow-up failed; delivering",+ "task_id", taskID, "error", err)+ } else if passedOn {+ return+ }++ issue, err := queries.GetIssue(ctx, task.IssueID)+ if err != nil {+ return+ }+ details, _ := json.Marshal(map[string]string{+ "comment_id": handoffID,+ inbox.SquadResultDetail: "true",+ })+ author := events.Event{+ Type: e.Type,+ WorkspaceID: e.WorkspaceID,+ ActorType: "agent",+ ActorID: util.UUIDToString(handoff.AuthorID),+ }+ notifySubscribers(ctx, queries, bus, util.UUIDToString(issue.ID), issue.Status, e.WorkspaceID, author,+ nil, "new_comment", "info",+ issue.Title, handoff.Content,+ details)+}diff --git a/server/cmd/server/notification_squad_result_test.go b/server/cmd/server/notification_squad_result_test.gonew file mode 100644index 0000000000..60ceb7a3db--- /dev/null+++ b/server/cmd/server/notification_squad_result_test.go@@ -0,0 +1,182 @@+package main++import (+ "context"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/handler"+ "github.com/multica-ai/multica/server/internal/inbox"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// TestNotification_SquadResult posts a handoff on a squad's issue, completes+// the leader run it woke, and checks that a member who muted squad handoffs+// gets the handoff only when that run passed nothing on (MUL-10054), while a+// member on the default keeps exactly the handoff's own row.+func TestNotification_SquadResult(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)+ fx := newSquadHandoffFixture(t)++ mutedEmail := "[email protected]"+ mutedID := createNotificationMember(t, mutedEmail)+ t.Cleanup(func() { cleanupTestUser(t, mutedEmail) })+ setNotificationPref(t, mutedID, inbox.SquadHandoffsPref, "muted")++ defaultEmail := "[email protected]"+ defaultID := createNotificationMember(t, defaultEmail)+ t.Cleanup(func() { cleanupTestUser(t, defaultEmail) })++ cases := []struct {+ name string+ // trigger is the comment that woke the leader run; nil posts the+ // worker's handoff.+ trigger func(t *testing.T, issueID string) string+ // followUp records what the leader run did after it was woken.+ followUp func(t *testing.T, issueID, leaderTask string)+ leader bool+ result bool+ }{+ {name: "leader ends the chain", leader: true, result: true},+ {name: "leader dispatches again", leader: true, result: false,+ followUp: func(t *testing.T, issueID, leaderTask string) {+ fx.f.Comment(t, issueID, agentMention(fx.workerID)+" one more pass", testutil.Cols{+ "author_type": "agent", "author_id": fx.leaderID, "source_task_id": leaderTask,+ })+ }},+ {name: "leader writes to people", leader: true, result: false,+ followUp: func(t *testing.T, issueID, leaderTask string) {+ fx.f.Comment(t, issueID, "Merged, all done.", testutil.Cols{+ "author_type": "agent", "author_id": fx.leaderID, "source_task_id": leaderTask,+ })+ }},+ {name: "leader starts another run without a comment", leader: true, result: false,+ followUp: func(t *testing.T, issueID, leaderTask string) {+ fx.f.Task(t, fx.outsideID, testutil.Cols{+ "runtime_id": fx.runtimeID, "issue_id": issueID, "delegated_from_task_id": leaderTask,+ })+ }},+ {name: "leader waits on a wakeup", leader: true, result: false,+ followUp: func(t *testing.T, issueID, leaderTask string) {+ leaderWakeup(t, fx, issueID, leaderTask, true)+ }},+ {name: "leader's wakeup already disabled", leader: true, result: true,+ followUp: func(t *testing.T, issueID, leaderTask string) {+ leaderWakeup(t, fx, issueID, leaderTask, false)+ }},+ {name: "leader woken by a person", leader: true, result: false,+ trigger: func(t *testing.T, issueID string) string {+ return fx.f.Comment(t, issueID, "status?")+ }},+ {name: "a worker run ends", leader: false, result: false},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ issueID := fx.f.Issue(t, "squad result: "+tc.name, testutil.Cols{+ "assignee_type": "squad", "assignee_id": fx.squadID,+ })+ t.Cleanup(func() { cleanupInboxForIssue(t, issueID) })+ addTestSubscriber(t, issueID, "member", mutedID, "manual")+ addTestSubscriber(t, issueID, "member", defaultID, "manual")++ var triggerID string+ if tc.trigger != nil {+ triggerID = tc.trigger(t, issueID)+ } else {+ const report = "Merged PR #1, branch deleted."+ triggerID = fx.f.Comment(t, issueID, report, testutil.Cols{+ "author_type": "agent", "author_id": fx.workerID,+ })+ publishAgentComment(bus, issueID, triggerID, fx.workerID, report)+ }++ runCols := testutil.Cols{+ "runtime_id": fx.runtimeID, "issue_id": issueID, "trigger_comment_id": triggerID,+ }+ runAgent := fx.workerID+ if tc.leader {+ runCols["is_leader_task"] = true+ runCols["squad_id"] = fx.squadID+ runAgent = fx.leaderID+ }+ run := fx.f.Task(t, runAgent, runCols)+ if tc.followUp != nil {+ tc.followUp(t, issueID, run)+ }+ bus.Publish(events.Event{+ Type: protocol.EventTaskCompleted,+ WorkspaceID: testWorkspaceID,+ ActorType: "system",+ Payload: map[string]any{"task_id": run, "agent_id": runAgent, "issue_id": issueID},+ })++ if got := squadResultRows(t, mutedID, issueID); got != boolCount(tc.result) {+ t.Fatalf("member who muted squad handoffs got %d result rows, want %d", got, boolCount(tc.result))+ }+ if got := squadResultRows(t, defaultID, issueID); got != 0 {+ t.Fatalf("member on the default got %d result rows, want 0", got)+ }+ if tc.trigger == nil && newCommentRow(t, defaultID, issueID) == nil {+ t.Fatalf("member on the default got no row for the handoff itself")+ }+ })+ }+}++// leaderWakeup records a one-time wakeup the leader run left on issueID, the+// way `multica issue wakeup create` does from inside that run.+func leaderWakeup(t *testing.T, fx squadHandoffFixture, issueID, leaderTask string, enabled bool) {+ t.Helper()+ fx.f.Insert(t, "issue_wakeup", testutil.Cols{+ "id": util.UUIDToString(dbid.NewV7()), "workspace_id": testWorkspaceID, "issue_id": issueID,+ "agent_id": fx.leaderID, "created_by": testUserID, "source_task_id": leaderTask,+ "instruction": "check CI", "kind": "at", "mode": "once",+ "next_fire_at": time.Now().Add(time.Hour), "enabled": enabled,+ })+}++func publishAgentComment(bus *events.Bus, issueID, commentID, authorID, content string) {+ bus.Publish(events.Event{+ Type: protocol.EventCommentCreated,+ WorkspaceID: testWorkspaceID,+ ActorType: "agent",+ ActorID: authorID,+ Payload: map[string]any{+ "comment": handler.CommentResponse{+ ID: commentID, IssueID: issueID, AuthorType: "agent",+ AuthorID: authorID, Content: content, Type: "comment",+ },+ "issue_title": "squad result",+ "issue_status": "in_progress",+ },+ })+}++// squadResultRows counts the recipient's new_comment rows on issueID marked+// as a squad result.+func squadResultRows(t *testing.T, recipientID, issueID string) int {+ t.Helper()+ var n int+ if err := testPool.QueryRow(context.Background(), `+ SELECT count(*) FROM inbox_item+ WHERE recipient_type = 'member' AND recipient_id = $1 AND issue_id = $2+ AND type = 'new_comment' AND details->>'squad_result' = 'true'+ `, recipientID, issueID).Scan(&n); err != nil {+ t.Fatalf("count squad result rows: %v", err)+ }+ return n+}++func boolCount(b bool) int {+ if b {+ return 1+ }+ return 0+}diff --git a/server/internal/inbox/registry.go b/server/internal/inbox/registry.goindex 44e9e68ccc..d54fc45e61 100644--- a/server/internal/inbox/registry.go+++ b/server/internal/inbox/registry.go@@ -130,17 +130,29 @@ const SquadHandoffsPref = "squad_handoffs"// a string map and reject the whole Inbox list otherwise.const SquadHandoffDetail = "squad_handoff"+// SquadResultDetail is the new_comment details key, set to "true", on the row+// that delivers the handoff a squad's chain ended with: its leader's run+// finished without passing the work on, so that report is the result+// (MUL-10054). Only members who muted squad handoffs receive it; everyone+// else already has the report's own row.+const SquadResultDetail = "squad_result"+// MutedSquadHandoff reports whether a member's parsed preferences drop this-// new_comment row as a squad handoff.+// new_comment row: a squad handoff for a member who muted them, or a squad+// result for one who did not.func MutedSquadHandoff(prefs map[string]string, notifType string, details []byte) bool {- if notifType != "new_comment" || prefs[SquadHandoffsPref] != "muted" || len(details) == 0 {+ if notifType != "new_comment" || len(details) == 0 {return false}var d map[string]anyif err := json.Unmarshal(details, &d); err != nil {return false}- return d[SquadHandoffDetail] == "true"+ muted := prefs[SquadHandoffsPref] == "muted"+ if d[SquadResultDetail] == "true" {+ return !muted+ }+ return muted && d[SquadHandoffDetail] == "true"}// Muted reports whether a member's parsed preferences mute notifType. nildiff --git a/server/internal/inbox/registry_test.go b/server/internal/inbox/registry_test.goindex d192f9d9c8..1767c9699c 100644--- a/server/internal/inbox/registry_test.go+++ b/server/internal/inbox/registry_test.go@@ -289,10 +289,12 @@ func frontendTypeMismatches(frontend []string) []string {}// TestMutedSquadHandoff pins that squad_handoffs only ever drops a marked-// new_comment row, and only for a member who muted it (MUL-10008).+// new_comment row, and only for a member who muted it (MUL-10008), and that a+// squad result reaches only those members (MUL-10054).func TestMutedSquadHandoff(t *testing.T) {marked := []byte(`{"comment_id":"c","squad_handoff":"true"}`)plain := []byte(`{"comment_id":"c"}`)+ result := []byte(`{"comment_id":"c","squad_result":"true"}`)muted := map[string]string{SquadHandoffsPref: "muted"}cases := []struct {name string@@ -307,6 +309,9 @@ func TestMutedSquadHandoff(t *testing.T) {{"default keeps a marked comment", map[string]string{}, "new_comment", marked, false},{"explicit all keeps a marked comment", map[string]string{SquadHandoffsPref: "all"}, "new_comment", marked, false},{"unreadable details are delivered", muted, "new_comment", []byte(`not json`), false},+ {"muted keeps a squad result", muted, "new_comment", result, false},+ {"default drops a squad result", map[string]string{}, "new_comment", result, true},+ {"explicit all drops a squad result", map[string]string{SquadHandoffsPref: "all"}, "new_comment", result, true},}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex a2b1f93ec6..d46fab0034 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -9255,6 +9255,36 @@ func (q *Queries) SettleDelegatedFailureRecoveryComment(ctx context.Context, comreturn result.RowsAffected(), nil}+const taskPassedWorkOn = `-- name: TaskPassedWorkOn :one+SELECT (+ EXISTS (+ SELECT 1 FROM comment c+ WHERE c.issue_id = $1::uuid AND c.source_task_id = $2::uuid+ ) OR EXISTS (+ SELECT 1 FROM agent_task_queue t+ WHERE t.issue_id = $1::uuid AND t.delegated_from_task_id = $2::uuid+ ) OR EXISTS (+ SELECT 1 FROM issue_wakeup w+ WHERE w.issue_id = $1::uuid AND w.source_task_id = $2::uuid AND w.enabled+ )+)::boolean AS passed_on+`++type TaskPassedWorkOnParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ TaskID pgtype.UUID `json:"task_id"`+}++// Whether a run posted a comment on its issue, started another agent run+// there, or left an enabled wakeup waiting on it: a squad leader run that did+// none of these ended its squad's chain of handoffs.+func (q *Queries) TaskPassedWorkOn(ctx context.Context, arg TaskPassedWorkOnParams) (bool, error) {+ row := q.db.QueryRow(ctx, taskPassedWorkOn, arg.IssueID, arg.TaskID)+ var passed_on bool+ err := row.Scan(&passed_on)+ return passed_on, err+}+const updateAgent = `-- name: UpdateAgent :oneUPDATE agent SETname = COALESCE($2, name),diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex c126475210..ebf2674e7b 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -2861,3 +2861,20 @@ RETURNING *;-- name: GetCommentThreadRootID :oneSELECT comment_thread_root_id(@comment_id::uuid)::uuid AS id;++-- name: TaskPassedWorkOn :one+-- Whether a run posted a comment on its issue, started another agent run+-- there, or left an enabled wakeup waiting on it: a squad leader run that did+-- none of these ended its squad's chain of handoffs.+SELECT (+ EXISTS (+ SELECT 1 FROM comment c+ WHERE c.issue_id = @issue_id::uuid AND c.source_task_id = @task_id::uuid+ ) OR EXISTS (+ SELECT 1 FROM agent_task_queue t+ WHERE t.issue_id = @issue_id::uuid AND t.delegated_from_task_id = @task_id::uuid+ ) OR EXISTS (+ SELECT 1 FROM issue_wakeup w+ WHERE w.issue_id = @issue_id::uuid AND w.source_task_id = @task_id::uuid AND w.enabled+ )+)::boolean AS passed_on;