Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
refactor(inbox): route every inbox write through inbox.Deliver (MUL-9335) (#10670)
Jiayuan Zhangf485c0b2bd68
diff --git a/.github/ci-paths.json b/.github/ci-paths.jsonindex 43b2088483..3ffc2b4f63 100644--- a/.github/ci-paths.json+++ b/.github/ci-paths.json@@ -31,6 +31,7 @@"backend": ["server/**","packages/core/runtimes/cli-version.ts",+ "packages/core/types/inbox.ts",".multica/environments.toml","examples/plugins/**",".env.example",diff --git a/scripts/ci-scope.test.mjs b/scripts/ci-scope.test.mjsindex 4fabd2583c..a1ac5de4c1 100644--- a/scripts/ci-scope.test.mjs+++ b/scripts/ci-scope.test.mjs@@ -51,6 +51,7 @@ for (const [name, files, selected] of [["brand generator", ["scripts/brand/sync.mjs"], ["quality"]],["PR evidence uploader", ["scripts/pr-shots"], ["quality"]],["cross-module runtime contract", ["packages/core/runtimes/cli-version.ts"], ["frontend", "backend", "runtime", "quality"]],+ ["inbox type contract", ["packages/core/types/inbox.ts"], ["frontend", "backend", "quality"]],["shared quick action body contract", ["server/internal/handler/testdata/quick_action_bodies.json"], ["frontend", "backend", "runtime"]],["lockfile", ["pnpm-lock.yaml"], ["frontend", "quality", "docs"]],["workspace catalog", ["pnpm-workspace.yaml"], ["frontend", "quality", "docs"]],diff --git a/server/cmd/server/autopilot_failure_monitor.go b/server/cmd/server/autopilot_failure_monitor.goindex 158b3d1ad8..e6c7e0b2a9 100644--- a/server/cmd/server/autopilot_failure_monitor.go+++ b/server/cmd/server/autopilot_failure_monitor.go@@ -235,7 +235,6 @@ func emitAutopilotPausedNotifications("reason": "auto_paused_high_failure_rate",})- workspaceID := util.UUIDToString(autopilot.WorkspaceID)autopilotIDStr := util.UUIDToString(autopilot.ID)emitted := make(map[string]bool, len(recipients))@@ -246,7 +245,7 @@ func emitAutopilotPausedNotifications(}emitted[key] = true- item, inserted, err := inbox.CreateIfEligible(ctx, queries, db.CreateInboxItemParams{+ _, _, err := inbox.Deliver(ctx, queries, bus, inbox.Notification{Params: db.CreateInboxItemParams{ID: dbid.NewV7(),WorkspaceID: autopilot.WorkspaceID,RecipientType: r.Type,@@ -259,7 +258,7 @@ func emitAutopilotPausedNotifications(ActorType: util.StrToText("system"),ActorID: pgtype.UUID{},Details: details,- })+ }})if err != nil {slog.Warn("autopilot failure monitor: inbox write failed","autopilot_id", autopilotIDStr,@@ -267,20 +266,7 @@ func emitAutopilotPausedNotifications("recipient_id", util.UUIDToString(r.ID),"error", err,)- continue- }-- if !inserted {- continue}-- bus.Publish(events.Event{- Type: protocol.EventInboxNew,- WorkspaceID: workspaceID,- ActorType: "system",- ActorID: "",- Payload: map[string]any{"item": inboxItemToResponse(item)},- })}}diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.goindex d14830a8ac..575cf1f5c6 100644--- a/server/cmd/server/notification_listeners.go+++ b/server/cmd/server/notification_listeners.go@@ -146,70 +146,57 @@ func deliverToSubscriber(reason, notifType string, statusIsHandoff bool) bool {return statusIsHandoff}-// notifTypeToGroup maps each inbox type the issue listeners write to a-// user-configurable preference group. Types not in this map are always-// delivered (not configurable). app_action_result also belongs to-// agent_activity; connectedapps checks that group itself.-var notifTypeToGroup = map[string]string{- "issue_assigned": "assignments",- "unassigned": "assignments",- "assignee_changed": "assignments",- "status_changed": "status_changes",- "new_comment": "comments",- "mentioned": "mentions",- "reaction_added": "reactions",- "priority_changed": "updates",- "start_date_changed": "updates",- "due_date_changed": "updates",- "task_failed": "agent_activity",- "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 {- group, ok := notifTypeToGroup[notifType]- if !ok {- return false // unconfigurable types are always delivered- }- return prefs[group] == "muted"-}--// loadUserPrefs loads notification preferences for a set of user IDs in a-// workspace. Returns a map from user_id string to parsed preferences.+// loadUserPrefs loads the notification preferences of a fanout's recipients+// in one query.func loadUserPrefs(ctx context.Context,queries *db.Queries,workspaceID string,userIDs []string,-) map[string]map[string]string {+) inbox.Preferences {if len(userIDs) == 0 {- return nil+ return inbox.Preferences{}}-uuids := make([]pgtype.UUID, len(userIDs))for i, id := range userIDs {uuids[i] = parseUUID(id)}+ return inbox.LoadPreferences(ctx, queries, parseUUID(workspaceID), uuids)+}- rows, err := queries.ListNotificationPreferencesByUsers(ctx, db.ListNotificationPreferencesByUsersParams{- WorkspaceID: parseUUID(workspaceID),- UserIds: uuids,- })- if err != nil {- slog.Error("failed to load notification preferences", "error", err)- return nil- }-- result := make(map[string]map[string]string, len(rows))- for _, row := range rows {- var prefs map[string]string- if err := json.Unmarshal(row.Preferences, &prefs); err != nil {- continue- }- result[util.UUIDToString(row.UserID)] = prefs+// issueNotification is the inbox row an issue event writes for one recipient.+func issueNotification(+ e events.Event,+ recipientType string,+ recipientID string,+ workspaceID string,+ issueID string,+ issueStatus string,+ notifType string,+ severity string,+ title string,+ body string,+ details []byte,+ prefs inbox.Preferences,+) inbox.Notification {+ return inbox.Notification{+ Params: db.CreateInboxItemParams{+ ID: dbid.NewV7(),+ WorkspaceID: parseUUID(workspaceID),+ RecipientType: recipientType,+ RecipientID: parseUUID(recipientID),+ Type: notifType,+ Severity: severity,+ IssueID: parseUUID(issueID),+ Title: title,+ Body: util.StrToText(body),+ ActorType: util.StrToText(e.ActorType),+ ActorID: optionalUUID(e.ActorID),+ Details: details,+ },+ IssueStatus: &issueStatus,+ Preferences: prefs,}- return result}// archiveStaleTaskFailedInbox archives all task_failed inbox rows for the@@ -506,16 +493,13 @@ func notifyProjectSubscribers(userPrefs := loadUserPrefs(ctx, queries, workspaceID, recipients)for _, subID := range recipients {- if prefs, ok := userPrefs[subID]; ok && isNotifMuted(prefs, notifType) {- continue- }createMemberInboxItem(ctx, queries, bus, subID, workspaceID, e, issueID, issueStatus,- notifType, severity, title, body, details)+ notifType, severity, title, body, details, userPrefs)}}-// createMemberInboxItem writes one member inbox row and announces it. Reports-// whether a row was actually inserted.+// createMemberInboxItem delivers one member inbox row. Reports whether a row+// was actually inserted.func createMemberInboxItem(ctx context.Context,queries *db.Queries,@@ -530,39 +514,16 @@ func createMemberInboxItem(title string,body string,details []byte,+ prefs inbox.Preferences,) bool {- item, inserted, err := inbox.CreateIfEligible(ctx, queries, db.CreateInboxItemParams{- ID: dbid.NewV7(),- WorkspaceID: parseUUID(workspaceID),- RecipientType: "member",- RecipientID: parseUUID(recipientID),- Type: notifType,- Severity: severity,- IssueID: parseUUID(issueID),- Title: title,- Body: util.StrToText(body),- ActorType: util.StrToText(e.ActorType),- ActorID: optionalUUID(e.ActorID),- Details: details,- })+ _, inserted, err := inbox.Deliver(ctx, queries, bus, issueNotification(e, "member", recipientID,+ workspaceID, issueID, issueStatus, notifType, severity, title, body, details, prefs))if err != nil {slog.Error("member notification creation failed","recipient_id", recipientID, "type", notifType, "error", err)return false}- if !inserted {- return false- }- resp := inboxItemToResponse(item)- resp["issue_status"] = issueStatus- bus.Publish(events.Event{- Type: inbox.NewItemEventType(item),- WorkspaceID: workspaceID,- ActorType: e.ActorType,- ActorID: e.ActorID,- Payload: map[string]any{"item": resp},- })- return true+ return inserted}// notifyIssueSubscribers sends inbox notifications to subscribers of@@ -642,11 +603,6 @@ func notifyIssueSubscribers(continue}- // Skip if this notification type is muted by the user- if prefs, ok := userPrefs[subID]; ok && isNotifMuted(prefs, notifType) {- continue- }-// Delegated subscriptions deliver a narrower event set than direct// ones — see deliverToSubscriber.if !deliverToSubscriber(sub.Reason, notifType, statusIsHandoff) {@@ -655,7 +611,7 @@ func notifyIssueSubscribers(}if createMemberInboxItem(ctx, queries, bus, subID, workspaceID, e, targetIssueID, issueStatus,- notifType, severity, title, body, details) {+ notifType, severity, title, body, details, userPrefs) {notified[subID] = true}}@@ -663,8 +619,8 @@ func notifyIssueSubscribers(return notified, tierSuppressed}-// notifyDirect creates an inbox item for a specific recipient. Skips if the-// recipient is the actor. Publishes an inbox:new event on success.+// notifyDirect delivers an inbox item to a specific recipient. Skips if the+// recipient is the actor.func notifyDirect(ctx context.Context,queries *db.Queries,@@ -686,46 +642,11 @@ func notifyDirect(return}- // Check notification preferences for member recipients.- if recipientType == "member" {- prefs := loadUserPrefs(ctx, queries, workspaceID, []string{recipientID})- if p, ok := prefs[recipientID]; ok && isNotifMuted(p, notifType) {- return- }- }-- item, inserted, err := inbox.CreateIfEligible(ctx, queries, db.CreateInboxItemParams{- ID: dbid.NewV7(),- WorkspaceID: parseUUID(workspaceID),- RecipientType: recipientType,- RecipientID: parseUUID(recipientID),- Type: notifType,- Severity: severity,- IssueID: parseUUID(issueID),- Title: title,- Body: util.StrToText(body),- ActorType: util.StrToText(e.ActorType),- ActorID: optionalUUID(e.ActorID),- Details: details,- })- if err != nil {+ if _, _, err := inbox.Deliver(ctx, queries, bus, issueNotification(e, recipientType, recipientID,+ workspaceID, issueID, issueStatus, notifType, severity, title, body, details, nil)); err != nil {slog.Error("direct notification creation failed","issue_id", issueID, "recipient_id", recipientID, "type", notifType, "error", err)- return- }- if !inserted {- return}-- resp := inboxItemToResponse(item)- resp["issue_status"] = issueStatus- bus.Publish(events.Event{- Type: inbox.NewItemEventType(item),- WorkspaceID: workspaceID,- ActorType: e.ActorType,- ActorID: e.ActorID,- Payload: map[string]any{"item": resp},- })}// notifyDelegatedIssueCreated tells the human behind an agent-created issue@@ -874,43 +795,16 @@ func notifyMentionedMembers(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- }- item, inserted, err := inbox.CreateIfEligible(context.Background(), queries, db.CreateInboxItemParams{- ID: dbid.NewV7(),- WorkspaceID: parseUUID(e.WorkspaceID),- RecipientType: "member",- RecipientID: parseUUID(id),- Type: "mentioned",- Severity: "info",- IssueID: parseUUID(issueID),- Title: title,- Body: util.StrToText(body),- ActorType: util.StrToText(e.ActorType),- ActorID: optionalUUID(e.ActorID),- Details: withDetail(details, "mention_via", via[id]),- })+ _, inserted, err := inbox.Deliver(context.Background(), queries, bus, issueNotification(e, "member", id,+ e.WorkspaceID, issueID, issueStatus, "mentioned", "info", title, body,+ withDetail(details, "mention_via", via[id]), mentionPrefs))if err != nil {slog.Error("mention inbox creation failed", "mentioned_id", id, "error", err)continue}- if !inserted {- continue+ if inserted {+ notified[id] = true}- notified[id] = true- resp := inboxItemToResponse(item)- resp["issue_status"] = issueStatus- bus.Publish(events.Event{- Type: inbox.NewItemEventType(item),- WorkspaceID: e.WorkspaceID,- ActorType: e.ActorType,- ActorID: e.ActorID,- Payload: map[string]any{"item": resp},- })}return notified}@@ -1356,28 +1250,6 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {})}-// inboxItemToResponse converts a db.InboxItem into a map suitable for-// JSON-serializable event payloads (mirrors handler.inboxToResponse fields).-func inboxItemToResponse(item db.InboxItem) map[string]any {- return map[string]any{- "id": util.UUIDToString(item.ID),- "workspace_id": util.UUIDToString(item.WorkspaceID),- "recipient_type": item.RecipientType,- "recipient_id": util.UUIDToString(item.RecipientID),- "type": item.Type,- "severity": item.Severity,- "issue_id": util.UUIDToPtr(item.IssueID),- "title": item.Title,- "body": util.TextToPtr(item.Body),- "read": item.Read,- "archived": item.Archived,- "created_at": util.TimestampToString(item.CreatedAt),- "actor_type": util.TextToPtr(item.ActorType),- "actor_id": util.UUIDToPtr(item.ActorID),- "details": json.RawMessage(item.Details),- }-}-// withDetail returns details with one more string field. Details that are not// a JSON object are returned as they are.func withDetail(details []byte, key, value string) []byte {diff --git a/server/cmd/server/notification_mute_group_test.go b/server/cmd/server/notification_mute_group_test.godeleted file mode 100644index cfe7493436..0000000000--- a/server/cmd/server/notification_mute_group_test.go+++ /dev/null@@ -1,51 +0,0 @@-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) {- cases := []struct {- name string- prefs map[string]string- notifType string- want 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},-- // Reactions have their own group, apart from comments.- {"muted reactions drops reaction_added", map[string]string{"reactions": "muted"}, "reaction_added", true},- {"muted comments still delivers reactions", map[string]string{"comments": "muted"}, "reaction_added", false},-- // Types outside the map are always delivered.- {"unconfigurable type always delivered", map[string]string{"comments": "muted"}, "children_done", 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)- }- })- }-}diff --git a/server/internal/connectedapps/requests.go b/server/internal/connectedapps/requests.goindex 982111b0ea..4307958d4b 100644--- a/server/internal/connectedapps/requests.go+++ b/server/internal/connectedapps/requests.go@@ -407,11 +407,9 @@ func appLabel(slug string) string {// notify writes the approver's inbox item. Confirmation and connection// requests are always delivered: the agent is stopped until the person-// answers. Results follow the recipient's agent-activity preference.+// answers. Results follow the recipient's agent-activity preference; the+// inbox type registry owns both rules.func (s *Service) notify(ctx context.Context, req db.AppActionRequest, notifType string) {- if notifType == NotifActionResult && s.mutedAgentActivity(ctx, req) {- return- }actorType := pgtype.Text{String: "agent", Valid: true}agentName := "Agent"if agent, err := s.q.GetAgent(ctx, req.AgentID); err == nil {@@ -460,52 +458,26 @@ func (s *Service) notify(ctx context.Context, req db.AppActionRequest, notifType"summary": req.Summary,"expires_at": util.TimestampToString(req.ExpiresAt),})- item, inserted, err := inbox.CreateIfEligible(ctx, s.q, db.CreateInboxItemParams{- ID: dbid.NewV7(),- WorkspaceID: req.WorkspaceID,- RecipientType: "member",- RecipientID: req.ApproverUserID,- Type: notifType,- Severity: severity,- IssueID: req.IssueID,- Title: title,- Body: pgtype.Text{String: body, Valid: true},- ActorType: actorType,- ActorID: req.AgentID,- Details: details,+ _, _, err := inbox.Deliver(ctx, s.q, s.bus, inbox.Notification{+ Params: db.CreateInboxItemParams{+ ID: dbid.NewV7(),+ WorkspaceID: req.WorkspaceID,+ RecipientType: "member",+ RecipientID: req.ApproverUserID,+ Type: notifType,+ Severity: severity,+ IssueID: req.IssueID,+ Title: title,+ Body: pgtype.Text{String: body, Valid: true},+ ActorType: actorType,+ ActorID: req.AgentID,+ Details: details,+ },+ IssueStatus: &issueStatus,})if err != nil {slog.Warn("connectedapps: create inbox item failed", "request_id", util.UUIDToString(req.ID), "error", err)- return- }- if !inserted || s.bus == nil {- return- }- s.bus.Publish(events.Event{- Type: inbox.NewItemEventType(item), WorkspaceID: util.UUIDToString(item.WorkspaceID), ActorType: "agent", ActorID: util.UUIDToString(req.AgentID),- Payload: map[string]any{"item": map[string]any{- "id": util.UUIDToString(item.ID), "workspace_id": util.UUIDToString(item.WorkspaceID),- "recipient_type": item.RecipientType, "recipient_id": util.UUIDToString(item.RecipientID),- "type": item.Type, "severity": item.Severity, "issue_id": util.UUIDToPtr(item.IssueID),- "title": item.Title, "body": util.TextToPtr(item.Body), "read": item.Read, "archived": item.Archived,- "created_at": util.TimestampToString(item.CreatedAt), "actor_type": util.TextToPtr(item.ActorType),- "actor_id": util.UUIDToPtr(item.ActorID), "details": json.RawMessage(item.Details), "issue_status": issueStatus,- }},- })-}--// mutedAgentActivity reports whether the recipient muted the agent-activity-// group, which app results belong to.-func (s *Service) mutedAgentActivity(ctx context.Context, req db.AppActionRequest) bool {- pref, err := s.q.GetNotificationPreference(ctx, db.GetNotificationPreferenceParams{- WorkspaceID: req.WorkspaceID, UserID: req.ApproverUserID,- })- if err != nil {- return false}- prefs := map[string]string{}- _ = json.Unmarshal(pref.Preferences, &prefs)- return prefs["agent_activity"] == "muted"}// RunSweeper runs Sweep every minute until ctx ends. Safe on every replica:diff --git a/server/internal/handler/inbox_snooze_test.go b/server/internal/handler/inbox_snooze_test.goindex 4d47929a63..989ce64f9f 100644--- a/server/internal/handler/inbox_snooze_test.go+++ b/server/internal/handler/inbox_snooze_test.go@@ -175,7 +175,7 @@ func TestInboxRowsWrittenIntoASnoozeJoinItUnlessTheyWakeIt(t *testing.T) {create := func(notifType string, details string) db.InboxItem {t.Helper()- row, inserted, err := inbox.CreateIfEligible(context.Background(), testHandler.Queries, db.CreateInboxItemParams{+ row, inserted, err := inbox.Deliver(context.Background(), testHandler.Queries, nil, inbox.Notification{Params: db.CreateInboxItemParams{WorkspaceID: parseUUID(f.workspaceID),RecipientType: "member",RecipientID: parseUUID(testUserID),@@ -184,7 +184,7 @@ func TestInboxRowsWrittenIntoASnoozeJoinItUnlessTheyWakeIt(t *testing.T) {IssueID: parseUUID(f.issueID),Title: "Snoozed issue",Details: []byte(details),- })+ }})if err != nil || !inserted {t.Fatalf("create %s: inserted=%v err=%v", notifType, inserted, err)}@@ -297,7 +297,7 @@ func TestSnoozeInboxRefreshesClientsThatPredateIt(t *testing.T) {// A row written into the snooze is announced as snoozed only: never as new,// and without the refresh, since the list does not change.*seen = nil- row, inserted, err := inbox.CreateIfEligible(context.Background(), testHandler.Queries, db.CreateInboxItemParams{+ row, inserted, err := inbox.Deliver(context.Background(), testHandler.Queries, nil, inbox.Notification{Params: db.CreateInboxItemParams{WorkspaceID: parseUUID(f.workspaceID),RecipientType: "member",RecipientID: parseUUID(testUserID),@@ -306,7 +306,7 @@ func TestSnoozeInboxRefreshesClientsThatPredateIt(t *testing.T) {IssueID: parseUUID(f.issueID),Title: "Snoozed issue",Details: []byte(`{}`),- })+ }})if err != nil || !inserted {t.Fatalf("create: inserted=%v err=%v", inserted, err)}diff --git a/server/internal/handler/project_owner_recovery.go b/server/internal/handler/project_owner_recovery.goindex 208da2046b..1b33e7878a 100644--- a/server/internal/handler/project_owner_recovery.go+++ b/server/internal/handler/project_owner_recovery.go@@ -14,7 +14,6 @@ import ("github.com/multica-ai/multica/server/internal/projectaccess"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")// Owner recovery for private projects (MUL-9284).@@ -214,12 +213,11 @@ func (h *Handler) notifyProjectOwnerJoined(ctx context.Context, project db.Proje"joined_by": name,})body := name + " is a workspace owner and added themselves to this private project. They can now see its issues."- workspaceID := uuidToString(project.WorkspaceID)for _, recipient := range recipients {if recipient == ownerID {continue}- item, created, err := inbox.CreateIfEligible(ctx, h.Queries, db.CreateInboxItemParams{+ _, _, err := inbox.Deliver(ctx, h.Queries, h.Bus, inbox.Notification{Params: db.CreateInboxItemParams{ID: dbid.NewV7(),WorkspaceID: project.WorkspaceID,RecipientType: "member",@@ -232,42 +230,13 @@ func (h *Handler) notifyProjectOwnerJoined(ctx context.Context, project db.ProjeActorType: pgtype.Text{String: "member", Valid: true},ActorID: ownerID,Details: details,- })+ }})if err != nil {slog.Warn("project owner-joined notice failed","project_id", uuidToString(project.ID),"recipient_id", uuidToString(recipient),"error", err,)- continue- }- if !created {- continue}- h.publish(protocol.EventInboxNew, workspaceID, "member", uuidToString(ownerID), map[string]any{- "item": inboxEventPayload(item),- })- }-}--// inboxEventPayload is the inbox item as the inbox:new listener reads it: a-// plain map, because it routes on the nested recipient_id.-func inboxEventPayload(item db.InboxItem) map[string]any {- return map[string]any{- "id": uuidToString(item.ID),- "workspace_id": uuidToString(item.WorkspaceID),- "recipient_type": item.RecipientType,- "recipient_id": uuidToString(item.RecipientID),- "type": item.Type,- "severity": item.Severity,- "issue_id": uuidToPtr(item.IssueID),- "title": item.Title,- "body": textToPtr(item.Body),- "read": item.Read,- "archived": item.Archived,- "created_at": timestampToString(item.CreatedAt),- "actor_type": textToPtr(item.ActorType),- "actor_id": uuidToPtr(item.ActorID),- "details": json.RawMessage(item.Details),}}diff --git a/server/internal/inbox/create.go b/server/internal/inbox/create.goindex 3559677f0f..a1c80f67a1 100644--- a/server/internal/inbox/create.go+++ b/server/internal/inbox/create.go@@ -10,7 +10,7 @@ import (db "github.com/multica-ai/multica/server/pkg/db/generated")-// CreateIfEligible returns inserted=false without an error when the recipient+// 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.//@@ -18,7 +18,7 @@ import (// CreateInboxItem). When the row is one that needs the recipient// (WakesSnooze), the snooze ends instead and the issue is back in the inbox// with this row on top. Announce the returned row with NewItemEventType.-func CreateIfEligible(ctx context.Context, queries *db.Queries, params db.CreateInboxItemParams) (item db.InboxItem, inserted bool, err error) {+func createIfEligible(ctx context.Context, queries *db.Queries, params db.CreateInboxItemParams) (item db.InboxItem, inserted bool, err error) {item, err = queries.CreateInboxItem(ctx, params)if errors.Is(err, pgx.ErrNoRows) {return db.InboxItem{}, false, nildiff --git a/server/internal/inbox/deliver.go b/server/internal/inbox/deliver.gonew file mode 100644index 0000000000..740afb8c3f--- /dev/null+++ b/server/internal/inbox/deliver.go@@ -0,0 +1,128 @@+package inbox++import (+ "context"+ "encoding/json"+ "fmt"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Publisher receives the event announcing each delivered row: the event bus,+// or a Deferred when the row is written inside a transaction.+type Publisher interface {+ Publish(events.Event)+}++// Notification is one inbox row to deliver.+type Notification struct {+ Params db.CreateInboxItemParams+ // IssueStatus, when set, rides on the announced item as issue_status.+ IssueStatus *string+ // Preferences are the recipients' preferences a fanout loaded once with+ // LoadPreferences. Nil makes Deliver read this recipient's own.+ Preferences Preferences+ // IgnorePreferences delivers a mutable type even when the recipient+ // muted its group.+ IgnorePreferences bool+}++// Deliver is the one way an inbox row is written. It refuses an unregistered+// type, drops a member notification whose group the member muted, inserts the+// row only when the recipient is eligible to see it, and announces the new row+// on pub: inbox:new, or inbox:snoozed when it joined a snooze on its issue.+// A row that needs the recipient ends that snooze instead (see+// createIfEligible). inserted is false, without an error, for a+// muted or ineligible recipient.+//+// Inside a transaction, pass a Deferred and Flush it after commit, so no+// client hears about a row that may roll back.+func Deliver(ctx context.Context, queries *db.Queries, pub Publisher, n Notification) (item db.InboxItem, inserted bool, err error) {+ group, ok := typeGroups[n.Params.Type]+ if !ok {+ return db.InboxItem{}, false, fmt.Errorf("inbox: unregistered notification type %q", n.Params.Type)+ }+ if group != "" && !n.IgnorePreferences && n.Params.RecipientType == "member" {+ prefs := n.Preferences+ if prefs == nil {+ prefs = LoadPreferences(ctx, queries, n.Params.WorkspaceID, []pgtype.UUID{n.Params.RecipientID})+ }+ if p, ok := prefs[util.UUIDToString(n.Params.RecipientID)]; ok && Muted(p, n.Params.Type) {+ return db.InboxItem{}, false, nil+ }+ }+ item, inserted, err = createIfEligible(ctx, queries, n.Params)+ if err != nil || !inserted {+ return item, inserted, err+ }+ publish(pub, newEvent(item, n.IssueStatus))+ return item, true, nil+}++// Deferred holds announcing events until the transaction that wrote their rows+// commits. The zero value is ready to use.+type Deferred struct {+ events []events.Event+}++// Publish holds e for Flush.+func (d *Deferred) Publish(e events.Event) {+ d.events = append(d.events, e)+}++// Flush publishes the held events in delivery order and empties d.+func (d *Deferred) Flush(pub Publisher) {+ held := d.events+ d.events = nil+ for _, e := range held {+ publish(pub, e)+ }+}++func publish(pub Publisher, e events.Event) {+ // A service built without a bus holds a nil *events.Bus, which arrives+ // here as a non-nil interface.+ if pub == nil {+ return+ }+ if bus, ok := pub.(*events.Bus); ok && bus == nil {+ return+ }+ pub.Publish(e)+}++// newEvent builds the event that announces a written row: inbox:new, or+// inbox:snoozed for a row that joined a snooze. Its actor is the row's actor;+// listeners route it on the nested item's recipient_id.+func newEvent(item db.InboxItem, issueStatus *string) events.Event {+ payload := map[string]any{+ "id": util.UUIDToString(item.ID),+ "workspace_id": util.UUIDToString(item.WorkspaceID),+ "recipient_type": item.RecipientType,+ "recipient_id": util.UUIDToString(item.RecipientID),+ "type": item.Type,+ "severity": item.Severity,+ "issue_id": util.UUIDToPtr(item.IssueID),+ "title": item.Title,+ "body": util.TextToPtr(item.Body),+ "read": item.Read,+ "archived": item.Archived,+ "created_at": util.TimestampToString(item.CreatedAt),+ "actor_type": util.TextToPtr(item.ActorType),+ "actor_id": util.UUIDToPtr(item.ActorID),+ "details": json.RawMessage(item.Details),+ }+ if issueStatus != nil {+ payload["issue_status"] = *issueStatus+ }+ return events.Event{+ Type: NewItemEventType(item),+ WorkspaceID: util.UUIDToString(item.WorkspaceID),+ ActorType: item.ActorType.String,+ ActorID: util.UUIDToString(item.ActorID),+ Payload: map[string]any{"item": payload},+ }+}diff --git a/server/internal/inbox/deliver_test.go b/server/internal/inbox/deliver_test.gonew file mode 100644index 0000000000..a842e7410c--- /dev/null+++ b/server/internal/inbox/deliver_test.go@@ -0,0 +1,121 @@+package inbox++import (+ "context"+ "strings"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestDeliverRefusesUnregisteredType(t *testing.T) {+ _, inserted, err := Deliver(context.Background(), nil, nil, Notification{+ Params: db.CreateInboxItemParams{RecipientType: "member", Type: "not_a_type"},+ })+ if err == nil || !strings.Contains(err.Error(), "not_a_type") {+ t.Fatalf("Deliver error = %v, want unregistered type error", err)+ }+ if inserted {+ t.Fatal("Deliver inserted an unregistered type")+ }+}++// A muted member is dropped before anything is written, from the preferences+// a fanout loaded.+func TestDeliverDropsMutedMember(t *testing.T) {+ recipient := util.MustParseUUID("11111111-1111-1111-1111-111111111111")+ prefs := Preferences{util.UUIDToString(recipient): {GroupComments: "muted"}}+ bus := events.New()+ published := 0+ bus.Subscribe(protocol.EventInboxNew, func(events.Event) { published++ })++ _, inserted, err := Deliver(context.Background(), nil, bus, Notification{+ Params: db.CreateInboxItemParams{RecipientType: "member", RecipientID: recipient, Type: "new_comment"},+ Preferences: prefs,+ })+ if err != nil || inserted || published != 0 {+ t.Fatalf("Deliver = inserted %v, err %v, published %d; want a silent drop", inserted, err, published)+ }+}++func TestDeferredPublishesOnlyOnFlush(t *testing.T) {+ bus := events.New()+ var got []string+ bus.Subscribe(protocol.EventInboxNew, func(e events.Event) { got = append(got, e.ActorID) })++ var pending Deferred+ pending.Publish(events.Event{Type: protocol.EventInboxNew, ActorID: "a"})+ pending.Publish(events.Event{Type: protocol.EventInboxNew, ActorID: "b"})+ if len(got) != 0 {+ t.Fatalf("published before Flush: %v", got)+ }+ pending.Flush(bus)+ if strings.Join(got, ",") != "a,b" {+ t.Fatalf("Flush published %v, want [a b] in order", got)+ }+ pending.Flush(bus)+ if len(got) != 2 {+ t.Fatalf("second Flush republished: %v", got)+ }+}++func TestFlushWithoutBus(t *testing.T) {+ var nilBus *events.Bus+ for _, pub := range []Publisher{nil, nilBus} {+ var pending Deferred+ pending.Publish(events.Event{Type: protocol.EventInboxNew})+ pending.Flush(pub)+ }+}++func TestNewEventShape(t *testing.T) {+ agentID := util.MustParseUUID("22222222-2222-2222-2222-222222222222")+ workspaceID := util.MustParseUUID("33333333-3333-3333-3333-333333333333")+ item := db.InboxItem{+ ID: util.MustParseUUID("44444444-4444-4444-4444-444444444444"),+ WorkspaceID: workspaceID,+ RecipientType: "member",+ RecipientID: util.MustParseUUID("55555555-5555-5555-5555-555555555555"),+ Type: "quick_create_done",+ ActorType: pgtype.Text{String: "agent", Valid: true},+ ActorID: agentID,+ Details: []byte("{}"),+ }++ status := "todo"+ e := newEvent(item, &status)+ if e.Type != protocol.EventInboxNew || e.WorkspaceID != util.UUIDToString(workspaceID) {+ t.Fatalf("event = %s in %s", e.Type, e.WorkspaceID)+ }+ if e.ActorType != "agent" || e.ActorID != util.UUIDToString(agentID) {+ t.Fatalf("event actor = %s/%s, want the row's actor", e.ActorType, e.ActorID)+ }+ payload := e.Payload.(map[string]any)["item"].(map[string]any)+ if payload["recipient_id"] != "55555555-5555-5555-5555-555555555555" {+ t.Fatalf("recipient_id = %v", payload["recipient_id"])+ }+ if payload["issue_status"] != "todo" {+ t.Fatalf("issue_status = %v, want todo", payload["issue_status"])+ }++ system := newEvent(db.InboxItem{ActorType: pgtype.Text{String: "system", Valid: true}}, nil)+ if _, ok := system.Payload.(map[string]any)["item"].(map[string]any)["issue_status"]; ok {+ t.Fatal("issue_status present without an issue status")+ }+ if system.ActorType != "system" || system.ActorID != "" {+ t.Fatalf("system event actor = %s/%q", system.ActorType, system.ActorID)+ }+}++// A row that joined a snooze must not banner or push.+func TestNewEventAnnouncesSnoozedRowAsSnoozed(t *testing.T) {+ item := db.InboxItem{SnoozedUntil: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true}}+ if got := newEvent(item, nil).Type; got != protocol.EventInboxSnoozed {+ t.Fatalf("snoozed row announced as %s, want %s", got, protocol.EventInboxSnoozed)+ }+}diff --git a/server/internal/inbox/registry.go b/server/internal/inbox/registry.gonew file mode 100644index 0000000000..170c05f5a7--- /dev/null+++ b/server/internal/inbox/registry.go@@ -0,0 +1,131 @@+package inbox++import (+ "context"+ "encoding/json"+ "log/slog"+ "sort"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Preference groups a member can mute. The keys are stored in+// notification_preference.preferences and validated by the preferences API.+const (+ GroupAssignments = "assignments"+ GroupStatusChanges = "status_changes"+ GroupComments = "comments"+ GroupMentions = "mentions"+ GroupReactions = "reactions"+ GroupUpdates = "updates"+ GroupAgentActivity = "agent_activity"+ GroupNewIssues = "new_issues"+)++// typeGroups is every inbox type the server writes, mapped to the preference+// group that can mute it. An empty group means the type is always delivered.+// Deliver refuses a type missing here. TestRegistryMatchesFrontendTypes keeps+// InboxItemType in packages/core/types/inbox.ts equal to these types plus+// legacyTypes.+//+// `mentioned` is deliberately apart from `comments`: muting comment volume+// must not silence someone asking for you by name.+var typeGroups = map[string]string{+ "issue_assigned": GroupAssignments,+ "unassigned": GroupAssignments,+ "assignee_changed": GroupAssignments,+ "status_changed": GroupStatusChanges,+ "new_comment": GroupComments,+ "mentioned": GroupMentions,+ "reaction_added": GroupReactions,+ "priority_changed": GroupUpdates,+ "start_date_changed": GroupUpdates,+ "due_date_changed": GroupUpdates,+ "task_failed": GroupAgentActivity,+ "app_action_result": GroupAgentActivity,+ "issue_created": GroupNewIssues,++ "issue_subscribed": "",+ "quick_create_done": "",+ "quick_create_failed": "",+ "quick_create_unconfirmed": "",+ "autopilot_paused": "",+ "autopilot_quota_exceeded": "",+ "children_done": "",+ "project_owner_joined": "",+ // The agent is stopped until the person answers these.+ "app_action_requested": "",+ "app_action_reminder": "",+ "app_connect_requested": "",+}++// legacyTypes are types earlier releases wrote and this server no longer+// does. Their rows remain, so clients keep labels and filter groups for them,+// but Deliver refuses them. Retiring a type moves it here rather than+// deleting it.+var legacyTypes = []string{+ "review_requested",+ "task_completed",+ "agent_blocked",+ "agent_completed",+}++// Types returns every inbox type the server delivers, sorted.+func Types() []string {+ types := make([]string, 0, len(typeGroups))+ for t := range typeGroups {+ types = append(types, t)+ }+ sort.Strings(types)+ return types+}++// Group returns the preference group that can mute notifType; "" means it is+// always delivered. ok is false for an unregistered type.+func Group(notifType string) (group string, ok bool) {+ group, ok = typeGroups[notifType]+ return group, ok+}++// Muted reports whether a member's parsed preferences mute notifType. A+// missing key means the default "all": preferences are stored sparse.+func Muted(prefs map[string]string, notifType string) bool {+ group := typeGroups[notifType]+ if group == "" {+ return false+ }+ return prefs[group] == "muted"+}++// Preferences holds the parsed notification preferences of a set of members+// in one workspace, keyed by user ID. A member without a row is absent.+type Preferences map[string]map[string]string++// LoadPreferences reads the preferences of userIDs in one query, for a fanout+// that delivers to many members. A read failure is logged and yields no+// preferences, so the fanout delivers rather than drops. The result is never+// nil, which is how Deliver tells "loaded" from "not loaded".+func LoadPreferences(ctx context.Context, queries *db.Queries, workspaceID pgtype.UUID, userIDs []pgtype.UUID) Preferences {+ result := Preferences{}+ if len(userIDs) == 0 {+ return result+ }+ rows, err := queries.ListNotificationPreferencesByUsers(ctx, db.ListNotificationPreferencesByUsersParams{+ WorkspaceID: workspaceID,+ UserIds: userIDs,+ })+ if err != nil {+ slog.Error("failed to load notification preferences", "error", err)+ return result+ }+ for _, row := range rows {+ var prefs map[string]string+ if err := json.Unmarshal(row.Preferences, &prefs); err != nil {+ continue+ }+ result[util.UUIDToString(row.UserID)] = prefs+ }+ return result+}diff --git a/server/internal/inbox/registry_test.go b/server/internal/inbox/registry_test.gonew file mode 100644index 0000000000..35b64838c0--- /dev/null+++ b/server/internal/inbox/registry_test.go@@ -0,0 +1,232 @@+package inbox++import (+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "testing"+)++// TestMutedGroupSplit 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 TestMutedGroupSplit(t *testing.T) {+ cases := []struct {+ name string+ prefs map[string]string+ notifType string+ want 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},++ // Reactions have their own group, apart from comments.+ {"muted reactions drops reaction_added", map[string]string{"reactions": "muted"}, "reaction_added", true},+ {"muted comments still delivers reactions", map[string]string{"comments": "muted"}, "reaction_added", false},++ // Types outside the map are always delivered.+ {"unconfigurable type always delivered", map[string]string{"comments": "muted"}, "children_done", false},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := Muted(tc.prefs, tc.notifType); got != tc.want {+ t.Fatalf("Muted(%v, %q) = %v, want %v",+ tc.prefs, tc.notifType, got, tc.want)+ }+ })+ }+}++// App results follow the agent-activity group; the requests that stop an+// agent until the person answers can never be muted.+func TestConnectedAppTypeGroups(t *testing.T) {+ muted := map[string]string{GroupAgentActivity: "muted"}+ if !Muted(muted, "app_action_result") {+ t.Error("app_action_result must follow the agent_activity mute")+ }+ for _, notifType := range []string{"app_action_requested", "app_action_reminder", "app_connect_requested"} {+ if Muted(muted, notifType) {+ t.Errorf("%s must always be delivered", notifType)+ }+ }+}++// The web, desktop and mobile clients switch on InboxItemType. It must list+// exactly the types the server delivers plus the legacy types older releases+// wrote: a delivered type missing there is a row no client can render, a+// legacy type missing there is history that loses its label and filter, and a+// type the server knows neither way is a client branch for a row that is+// never written. This file is why packages/core/types/inbox.ts belongs in+// CI's backend path filter.+func TestRegistryMatchesFrontendTypes(t *testing.T) {+ path := filepath.Join("..", "..", "..", "packages", "core", "types", "inbox.ts")+ src, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ frontend, err := parseInboxItemType(string(src))+ if err != nil {+ t.Fatalf("%s: %v", path, err)+ }+ for _, problem := range frontendTypeMismatches(frontend) {+ t.Error(problem)+ }+}++func TestLegacyTypesAreNotDelivered(t *testing.T) {+ for _, legacy := range legacyTypes {+ if _, ok := Group(legacy); ok {+ t.Errorf("%q is both delivered and legacy", legacy)+ }+ }+}++// The union's comments may contain semicolons, as the legacy note in+// inbox.ts does; the declaration ends only at one outside a comment.+func TestParseInboxItemTypeSkipsComments(t *testing.T) {+ src := `export type InboxSeverity = "info";++export type InboxItemType =+ | "issue_assigned"+ // No longer written, but older servers wrote them and those rows remain;+ // keep their labels and filter groups so history still reads and filters.+ | "review_requested"+ /* a block; with "quotes" */+ | "quick_create_done";++export interface InboxItem { type: "not_a_member" }+`+ got, err := parseInboxItemType(src)+ if err != nil {+ t.Fatal(err)+ }+ want := []string{"issue_assigned", "quick_create_done", "review_requested"}+ if strings.Join(got, ",") != strings.Join(want, ",") {+ t.Fatalf("parsed %v, want %v", got, want)+ }+}++func TestFrontendTypeMismatches(t *testing.T) {+ complete := append(Types(), legacyTypes...)+ without := func(drop string) []string {+ var out []string+ for _, v := range complete {+ if v != drop {+ out = append(out, v)+ }+ }+ return out+ }+ cases := []struct {+ name string+ frontend []string+ want string+ }{+ {"delivered plus legacy matches", complete, ""},+ {"dropping a delivered type fails", without("children_done"), `"children_done"`},+ {"dropping a legacy type fails", without("agent_blocked"), `"agent_blocked"`},+ {"an unknown type fails", append(append([]string(nil), complete...), "brand_new"), `"brand_new"`},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ problems := strings.Join(frontendTypeMismatches(tc.frontend), "\n")+ if tc.want == "" && problems != "" {+ t.Fatalf("unexpected mismatches:\n%s", problems)+ }+ if !strings.Contains(problems, tc.want) {+ t.Fatalf("mismatches %q do not name %s", problems, tc.want)+ }+ })+ }+}++// parseInboxItemType returns the string literals of the InboxItemType union,+// sorted. It skips // and /* */ comments, so a semicolon or quote inside one+// neither ends the declaration nor adds a member.+func parseInboxItemType(src string) ([]string, error) {+ const decl = "export type InboxItemType"+ start := strings.Index(src, decl)+ if start < 0 {+ return nil, errors.New("InboxItemType not found")+ }+ var types []string+ for i := start + len(decl); i < len(src); i++ {+ switch {+ case strings.HasPrefix(src[i:], "//"):+ end := strings.IndexByte(src[i:], '\n')+ if end < 0 {+ return nil, errors.New("InboxItemType is not terminated")+ }+ i += end+ case strings.HasPrefix(src[i:], "/*"):+ end := strings.Index(src[i+2:], "*/")+ if end < 0 {+ return nil, errors.New("unterminated block comment in InboxItemType")+ }+ i += end + 3+ case src[i] == '"':+ end := strings.IndexByte(src[i+1:], '"')+ if end < 0 {+ return nil, errors.New("unterminated string in InboxItemType")+ }+ types = append(types, src[i+1:i+1+end])+ i += end + 1+ case src[i] == ';':+ sort.Strings(types)+ return types, nil+ }+ }+ return nil, errors.New("InboxItemType is not terminated")+}++// frontendTypeMismatches compares the client's InboxItemType with the+// delivered and legacy types and describes every difference.+func frontendTypeMismatches(frontend []string) []string {+ listed := map[string]bool{}+ for _, v := range frontend {+ listed[v] = true+ }+ var problems []string+ for _, v := range Types() {+ if !listed[v] {+ problems = append(problems, fmt.Sprintf("server delivers %q but InboxItemType does not list it", v))+ }+ delete(listed, v)+ }+ for _, v := range legacyTypes {+ if !listed[v] {+ problems = append(problems, fmt.Sprintf("legacy type %q left InboxItemType; older rows would lose their label and filter", v))+ }+ delete(listed, v)+ }+ var unknown []string+ for v := range listed {+ unknown = append(unknown, v)+ }+ sort.Strings(unknown)+ for _, v := range unknown {+ problems = append(problems, fmt.Sprintf("InboxItemType lists %q but the server neither delivers it nor lists it as legacy", v))+ }+ return problems+}diff --git a/server/internal/inbox/snooze.go b/server/internal/inbox/snooze.goindex f02794151b..dac664faed 100644--- a/server/internal/inbox/snooze.go+++ b/server/internal/inbox/snooze.go@@ -54,8 +54,7 @@ func IsSnoozed(item db.InboxItem, now time.Time) bool {return item.SnoozedUntil.Valid && item.SnoozedUntil.Time.After(now)}-// NewItemEventType names the event that announces a row CreateIfEligible-// wrote. A row that joined a snooze is announced as inbox:snoozed, so no+// NewItemEventType names the event that announces a row Deliver wrote. A row that joined a snooze is announced as inbox:snoozed, so no// client raises a banner and no channel pushes it.func NewItemEventType(item db.InboxItem) string {if IsSnoozed(item, time.Now()) {diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.goindex 78e8356011..3f2ededac0 100644--- a/server/internal/integrations/wecom/outbound.go+++ b/server/internal/integrations/wecom/outbound.go@@ -1090,7 +1090,7 @@ func (o *Outbound) memberBindingFor(ctx context.Context, item map[string]any, wo}// inboxActorAgent reads the agent an inbox notification names as its actor,-// when it names one. The payload is the map inboxItemToResponse builds, whose+// when it names one. The payload is the map inbox.Deliver builds, whose// actor fields are pointers (util.TextToPtr / util.UUIDToPtr) and nil for a// notification a member authored. Both spellings are accepted, the same// defensive shape itemIDOf uses, so a payload that was re-encoded on its waydiff --git a/server/internal/integrations/wecom/outbound_test.go b/server/internal/integrations/wecom/outbound_test.goindex f279e0df8d..5249b7f7ef 100644--- a/server/internal/integrations/wecom/outbound_test.go+++ b/server/internal/integrations/wecom/outbound_test.go@@ -952,7 +952,7 @@ func TestInboxActorAgent(t *testing.T) {// agentInboxItem is one issue-comment notification as the listeners publish// it: a member recipient, and the agent whose comment it is as the actor —-// behind pointers, which is how inboxItemToResponse builds the map.+// behind pointers, which is how inbox.Deliver builds the map.func agentInboxItem(notifType, agentID string) map[string]any {return map[string]any{"recipient_type": "member",diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 1cb8dc1436..9ea5eeabaf 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -932,11 +932,9 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopireturn nil}-// notifyAutopilotSubscribersOnCreate writes an inbox_item for each template-// subscriber of an autopilot-created issue and broadcasts an inbox:new event-// so the recipient's inbox updates in real time. Mirrors the inbox payload-// shape from notification_listeners.go so the WS consumer sees the same fields-// the listener-driven path produces. Failures are logged, not propagated:+// notifyAutopilotSubscribersOnCreate delivers an inbox_item to each template+// subscriber of an autopilot-created issue, so the recipient's inbox updates+// in real time. Failures are logged, not propagated:// the issue and its subscriber rows are already committed, and an inbox-write// hiccup must not bubble up as a dispatch failure.func (s *AutopilotService) notifyAutopilotSubscribersOnCreate(@@ -960,19 +958,22 @@ func (s *AutopilotService) notifyAutopilotSubscribersOnCreate(if sub.UserType != "member" {continue}- item, inserted, err := inbox.CreateIfEligible(ctx, s.Queries, db.CreateInboxItemParams{- ID: dbid.NewV7(),- WorkspaceID: ap.WorkspaceID,- RecipientType: "member",- RecipientID: sub.UserID,- Type: "issue_subscribed",- Severity: "info",- IssueID: issue.ID,- Title: issue.Title,- Body: pgtype.Text{},- ActorType: pgtype.Text{String: "agent", Valid: true},- ActorID: leaderID,- Details: details,+ _, _, err := inbox.Deliver(ctx, s.Queries, s.Bus, inbox.Notification{+ Params: db.CreateInboxItemParams{+ ID: dbid.NewV7(),+ WorkspaceID: ap.WorkspaceID,+ RecipientType: "member",+ RecipientID: sub.UserID,+ Type: "issue_subscribed",+ Severity: "info",+ IssueID: issue.ID,+ Title: issue.Title,+ Body: pgtype.Text{},+ ActorType: pgtype.Text{String: "agent", Valid: true},+ ActorID: leaderID,+ Details: details,+ },+ IssueStatus: &issue.Status,})if err != nil {slog.Error("autopilot subscriber inbox write failed",@@ -981,37 +982,7 @@ func (s *AutopilotService) notifyAutopilotSubscribersOnCreate("recipient_id", util.UUIDToString(sub.UserID),"error", err,)- continue- }- if !inserted {- continue}- s.Bus.Publish(events.Event{- Type: protocol.EventInboxNew,- WorkspaceID: util.UUIDToString(ap.WorkspaceID),- ActorType: "agent",- ActorID: util.UUIDToString(leaderID),- Payload: map[string]any{- "item": map[string]any{- "id": util.UUIDToString(item.ID),- "workspace_id": util.UUIDToString(item.WorkspaceID),- "recipient_type": item.RecipientType,- "recipient_id": util.UUIDToString(item.RecipientID),- "type": item.Type,- "severity": item.Severity,- "issue_id": util.UUIDToPtr(item.IssueID),- "issue_status": issue.Status,- "title": item.Title,- "body": util.TextToPtr(item.Body),- "read": item.Read,- "archived": item.Archived,- "created_at": util.TimestampToString(item.CreatedAt),- "actor_type": util.TextToPtr(item.ActorType),- "actor_id": util.UUIDToPtr(item.ActorID),- "details": json.RawMessage(item.Details),- },- },- })}}diff --git a/server/internal/service/autopilot_quota_notifications.go b/server/internal/service/autopilot_quota_notifications.goindex ea69f8d254..8aaba6ef5c 100644--- a/server/internal/service/autopilot_quota_notifications.go+++ b/server/internal/service/autopilot_quota_notifications.go@@ -12,12 +12,10 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/entitlement"- "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""github.com/multica-ai/multica/server/pkg/dbid"- "github.com/multica-ai/multica/server/pkg/protocol")const autopilotQuotaFirstRejectionNoticeKey = "rejection_first"@@ -44,19 +42,18 @@ func (s *AutopilotService) deliverAutopilotQuotaRejectionNotice(policy.notifications.OnRejection != entitlement.NotificationFirstRejectionPerPeriod {return}- items, err := s.createAutopilotQuotaRejectionNotice(ctx, policy, workspaceID, source, params)- if err != nil {+ if _, err := s.createAutopilotQuotaRejectionNotice(ctx, policy, workspaceID, source, params); err != nil {slog.Warn("autopilot quota rejection notice delivery failed; quota rejection remains committed","workspace_id", util.UUIDToString(workspaceID),"autopilot_id", util.UUIDToString(params.AutopilotID),"source", source,"error", err,)- return}- s.publishAutopilotQuotaInboxItems(items)}+// createAutopilotQuotaRejectionNotice writes the period's first rejection+// notice and, once that commits, announces each row.func (s *AutopilotService) createAutopilotQuotaRejectionNotice(ctx context.Context,policy autopilotQuotaPolicy,@@ -85,7 +82,8 @@ func (s *AutopilotService) createAutopilotQuotaRejectionNotice(return nil, nil}- items, err := s.createAutopilotQuotaInboxItems(ctx, q, autopilotQuotaNoticeFacts{+ var pending inbox.Deferred+ items, err := s.createAutopilotQuotaInboxItems(ctx, q, &pending, autopilotQuotaNoticeFacts{WorkspaceID: period.WorkspaceID,AutopilotID: params.AutopilotID,Source: source,@@ -116,12 +114,14 @@ func (s *AutopilotService) createAutopilotQuotaRejectionNotice(if err := tx.Commit(ctx); err != nil {return nil, fmt.Errorf("commit quota rejection notice: %w", err)}+ pending.Flush(s.Bus)return items, nil}func (s *AutopilotService) createAutopilotQuotaInboxItems(ctx context.Context,q *db.Queries,+ pending *inbox.Deferred,facts autopilotQuotaNoticeFacts,) ([]db.InboxItem, error) {autopilotTitle := ""@@ -159,14 +159,14 @@ func (s *AutopilotService) createAutopilotQuotaInboxItems(items := make([]db.InboxItem, 0, len(recipients))for _, recipient := range recipients {- item, inserted, err := inbox.CreateIfEligible(ctx, q, db.CreateInboxItemParams{+ item, inserted, err := inbox.Deliver(ctx, q, pending, inbox.Notification{Params: db.CreateInboxItemParams{ID: dbid.NewV7(), WorkspaceID: facts.WorkspaceID,RecipientType: recipient.Type, RecipientID: recipient.ID,Type: "autopilot_quota_exceeded", Severity: "attention", IssueID: pgtype.UUID{},Title: "Autopilot run limit reached", Body: pgtype.Text{String: body, Valid: true},ActorType: pgtype.Text{String: "system", Valid: true}, ActorID: pgtype.UUID{},Details: details,- })+ }})if err != nil {return nil, fmt.Errorf("create autopilot quota inbox item: %w", err)}@@ -177,25 +177,3 @@ func (s *AutopilotService) createAutopilotQuotaInboxItems(}return items, nil}--func (s *AutopilotService) publishAutopilotQuotaInboxItems(items []db.InboxItem) {- if s.Bus == nil {- return- }- for _, item := range items {- s.Bus.Publish(events.Event{- Type: protocol.EventInboxNew, WorkspaceID: util.UUIDToString(item.WorkspaceID),- ActorType: "system",- Payload: map[string]any{"item": map[string]any{- "id": util.UUIDToString(item.ID), "workspace_id": util.UUIDToString(item.WorkspaceID),- "recipient_type": item.RecipientType, "recipient_id": util.UUIDToString(item.RecipientID),- "type": item.Type, "severity": item.Severity, "issue_id": nil,- "issue_status": nil, "issue_priority": nil,- "title": item.Title, "body": util.TextToPtr(item.Body), "read": item.Read,- "archived": item.Archived, "created_at": util.TimestampToString(item.CreatedAt),- "actor_type": util.TextToPtr(item.ActorType), "actor_id": nil,- "details": json.RawMessage(item.Details),- }},- })- }-}diff --git a/server/internal/service/issue_wakeup_system.go b/server/internal/service/issue_wakeup_system.goindex 00a3b9b2d5..26852df0b2 100644--- a/server/internal/service/issue_wakeup_system.go+++ b/server/internal/service/issue_wakeup_system.go@@ -12,7 +12,6 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/dispatch"- "github.com/multica-ai/multica/server/internal/events"inboxwriter "github.com/multica-ai/multica/server/internal/inbox""github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/util"@@ -502,7 +501,7 @@ func (s *IssueWakeupService) dispatchSystem(ctx context.Context, prev db.IssueWareturn err}var activities []wakeupActivity- var inbox []db.InboxItem+ var pendingInbox inboxwriter.Deferrednote := func(action string, details map[string]any) error {a, err := recordWakeupActivity(ctx, q, w, action, "system", pgtype.UUID{}, details)if err == nil {@@ -515,8 +514,8 @@ func (s *IssueWakeupService) dispatchSystem(ctx context.Context, prev db.IssueWareturn err}s.publishWakeupActivities(activities...)- for _, item := range inbox {- s.publishSystemInbox(item, issue.Status)+ if s.Tasks != nil {+ pendingInbox.Flush(s.Tasks.Bus)}return nil}@@ -561,17 +560,18 @@ func (s *IssueWakeupService) dispatchSystem(ctx context.Context, prev db.IssueWaif current.Type == "member" {facts["outcome"] = "notified"details, _ := json.Marshal(facts)- item, inserted, err := inboxwriter.CreateIfEligible(ctx, q, db.CreateInboxItemParams{- ID: dbid.NewV7(), WorkspaceID: issue.WorkspaceID, RecipientType: "member", RecipientID: current.ID,- Type: "children_done", Severity: "info", IssueID: issue.ID, Title: issue.Title,- ActorType: pgtype.Text{String: "system", Valid: true}, Details: details,+ _, inserted, err := inboxwriter.Deliver(ctx, q, &pendingInbox, inboxwriter.Notification{+ Params: db.CreateInboxItemParams{+ ID: dbid.NewV7(), WorkspaceID: issue.WorkspaceID, RecipientType: "member", RecipientID: current.ID,+ Type: "children_done", Severity: "info", IssueID: issue.ID, Title: issue.Title,+ ActorType: pgtype.Text{String: "system", Valid: true}, Details: details,+ },+ IssueStatus: &issue.Status,})if err != nil {return err}- if inserted {- inbox = append(inbox, item)- } else {+ if !inserted {facts["outcome"] = "none"}}@@ -706,23 +706,6 @@ func (s *IssueWakeupService) dispatchSystem(ctx context.Context, prev db.IssueWareturn nil}-func (s *IssueWakeupService) publishSystemInbox(item db.InboxItem, issueStatus string) {- if s.Tasks == nil || s.Tasks.Bus == nil {- return- }- s.Tasks.Bus.Publish(events.Event{- Type: inboxwriter.NewItemEventType(item), WorkspaceID: util.UUIDToString(item.WorkspaceID), ActorType: "system",- Payload: map[string]any{"item": map[string]any{- "id": util.UUIDToString(item.ID), "workspace_id": util.UUIDToString(item.WorkspaceID),- "recipient_type": item.RecipientType, "recipient_id": util.UUIDToString(item.RecipientID),- "type": item.Type, "severity": item.Severity, "issue_id": util.UUIDToPtr(item.IssueID),- "title": item.Title, "body": util.TextToPtr(item.Body), "read": item.Read, "archived": item.Archived,- "created_at": util.TimestampToString(item.CreatedAt), "actor_type": util.TextToPtr(item.ActorType),- "actor_id": util.UUIDToPtr(item.ActorID), "details": json.RawMessage(item.Details), "issue_status": issueStatus,- }},- })-}-// SystemWakeupInput is a person's change to a system rule on one issue.// Omitted fields keep their value.type SystemWakeupInput struct {diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex b0015f318d..c07ae4964e 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -6777,9 +6777,8 @@ func delegatedFailureRecoveryAttribution(target *delegatedFailureRecoveryTarget)// by the first and does not report another exhaustion.func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, target *delegatedFailureRecoveryTarget) (bool, error) {var exhaustedComment db.Comment- var exhaustedInbox db.InboxItem+ var pendingInbox inbox.Deferredcreated := false- inboxCreated := falseif err := s.runInTx(ctx, func(qtx *db.Queries) error {if _, err := qtx.AcknowledgeExhaustedDelegatedFailureRecovery(ctx, db.AcknowledgeExhaustedDelegatedFailureRecoveryParams{CommentID: target.comment.ID,@@ -6854,19 +6853,25 @@ func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, targeif err != nil {return fmt.Errorf("encode delegated failure exhaustion details: %w", err)}- exhaustedInbox, inboxCreated, err = inbox.CreateIfEligible(ctx, qtx, db.CreateInboxItemParams{- ID: dbid.NewV7(),- WorkspaceID: target.issue.WorkspaceID,- RecipientType: "member",- RecipientID: recipient,- Type: "task_failed",- Severity: "action_required",- IssueID: target.issue.ID,- Title: target.issue.Title,- Body: pgtype.Text{String: exhaustedComment.Content, Valid: true},- ActorType: pgtype.Text{String: "system", Valid: true},- ActorID: pgtype.UUID{},- Details: details,+ _, _, err = inbox.Deliver(ctx, qtx, &pendingInbox, inbox.Notification{+ Params: db.CreateInboxItemParams{+ ID: dbid.NewV7(),+ WorkspaceID: target.issue.WorkspaceID,+ RecipientType: "member",+ RecipientID: recipient,+ Type: "task_failed",+ Severity: "action_required",+ IssueID: target.issue.ID,+ Title: target.issue.Title,+ Body: pgtype.Text{String: exhaustedComment.Content, Valid: true},+ ActorType: pgtype.Text{String: "system", Valid: true},+ ActorID: pgtype.UUID{},+ Details: details,+ },+ IssueStatus: &target.issue.Status,+ // The one notice that automatic recovery gave up; it has+ // never followed the agent_activity mute.+ IgnorePreferences: true,})if err != nil {return fmt.Errorf("create delegated failure exhaustion inbox item: %w", err)@@ -6890,32 +6895,7 @@ func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, targe},})}- if inboxCreated && s.Bus != nil {- s.Bus.Publish(events.Event{- Type: inbox.NewItemEventType(exhaustedInbox),- WorkspaceID: util.UUIDToString(target.issue.WorkspaceID),- ActorType: "system",- ActorID: "",- Payload: map[string]any{"item": map[string]any{- "id": util.UUIDToString(exhaustedInbox.ID),- "workspace_id": util.UUIDToString(exhaustedInbox.WorkspaceID),- "recipient_type": exhaustedInbox.RecipientType,- "recipient_id": util.UUIDToString(exhaustedInbox.RecipientID),- "type": exhaustedInbox.Type,- "severity": exhaustedInbox.Severity,- "issue_id": util.UUIDToPtr(exhaustedInbox.IssueID),- "title": exhaustedInbox.Title,- "body": util.TextToPtr(exhaustedInbox.Body),- "read": exhaustedInbox.Read,- "archived": exhaustedInbox.Archived,- "created_at": util.TimestampToString(exhaustedInbox.CreatedAt),- "actor_type": util.TextToPtr(exhaustedInbox.ActorType),- "actor_id": util.UUIDToPtr(exhaustedInbox.ActorID),- "details": json.RawMessage(exhaustedInbox.Details),- "issue_status": target.issue.Status,- }},- })- }+ pendingInbox.Flush(s.Bus)return created, nil}@@ -8322,28 +8302,25 @@ func (s *TaskService) notifyQuickCreateCompleted(ctx context.Context, task db.Ag"identifier": identifier,"original_prompt": qc.Prompt,})- item, inserted, err := inbox.CreateIfEligible(ctx, s.Queries, db.CreateInboxItemParams{- ID: dbid.NewV7(),- WorkspaceID: workspaceID,- RecipientType: "member",- RecipientID: requesterID,- Type: "quick_create_done",- Severity: "info",- IssueID: issue.ID,- Title: issue.Title,- Body: pgtype.Text{},- ActorType: pgtype.Text{String: "agent", Valid: true},- ActorID: task.AgentID,- Details: details,- })- if err != nil {+ if _, _, err := inbox.Deliver(ctx, s.Queries, s.Bus, inbox.Notification{+ Params: db.CreateInboxItemParams{+ ID: dbid.NewV7(),+ WorkspaceID: workspaceID,+ RecipientType: "member",+ RecipientID: requesterID,+ Type: "quick_create_done",+ Severity: "info",+ IssueID: issue.ID,+ Title: issue.Title,+ Body: pgtype.Text{},+ ActorType: pgtype.Text{String: "agent", Valid: true},+ ActorID: task.AgentID,+ Details: details,+ },+ IssueStatus: &issue.Status,+ }); err != nil {slog.Error("quick-create completion: inbox write failed", "task_id", util.UUIDToString(task.ID), "error", err)- return- }- if !inserted {- return}- s.publishQuickCreateInbox(item, qc.WorkspaceID, util.UUIDToString(task.AgentID), issue.Status)}// Inbox types for the two non-success quick-create outcomes. They are distinct@@ -8426,59 +8403,26 @@ func (s *TaskService) writeQuickCreateOutcomeInbox(ctx context.Context, task db."error": redact.Text(errMsg),"source_context_id": qc.SourceContextID,})- item, inserted, err := inbox.CreateIfEligible(ctx, s.Queries, db.CreateInboxItemParams{- ID: dbid.NewV7(),- WorkspaceID: workspaceID,- RecipientType: "member",- RecipientID: requesterID,- Type: inboxType,- Severity: "action_required",- IssueID: pgtype.UUID{},- Title: title,- Body: pgtype.Text{String: redact.Text(errMsg), Valid: true},- ActorType: pgtype.Text{String: "agent", Valid: true},- ActorID: task.AgentID,- Details: details,- })- if err != nil {+ noIssueStatus := ""+ if _, _, err := inbox.Deliver(ctx, s.Queries, s.Bus, inbox.Notification{+ Params: db.CreateInboxItemParams{+ ID: dbid.NewV7(),+ WorkspaceID: workspaceID,+ RecipientType: "member",+ RecipientID: requesterID,+ Type: inboxType,+ Severity: "action_required",+ IssueID: pgtype.UUID{},+ Title: title,+ Body: pgtype.Text{String: redact.Text(errMsg), Valid: true},+ ActorType: pgtype.Text{String: "agent", Valid: true},+ ActorID: task.AgentID,+ Details: details,+ },+ IssueStatus: &noIssueStatus,+ }); err != nil {slog.Error("quick-create failure: inbox write failed", "task_id", util.UUIDToString(task.ID), "error", err)- return}- if !inserted {- return- }- s.publishQuickCreateInbox(item, qc.WorkspaceID, util.UUIDToString(task.AgentID), "")-}--// publishQuickCreateInbox emits the WS event so the requester's inbox list-// updates immediately. Mirrors the payload shape used by the other inbox-// listeners (notification_listeners.go).-func (s *TaskService) publishQuickCreateInbox(item db.InboxItem, workspaceID, agentID, issueStatus string) {- resp := map[string]any{- "id": util.UUIDToString(item.ID),- "workspace_id": util.UUIDToString(item.WorkspaceID),- "recipient_type": item.RecipientType,- "recipient_id": util.UUIDToString(item.RecipientID),- "type": item.Type,- "severity": item.Severity,- "issue_id": util.UUIDToPtr(item.IssueID),- "title": item.Title,- "body": util.TextToPtr(item.Body),- "read": item.Read,- "archived": item.Archived,- "created_at": util.TimestampToString(item.CreatedAt),- "actor_type": util.TextToPtr(item.ActorType),- "actor_id": util.UUIDToPtr(item.ActorID),- "details": json.RawMessage(item.Details),- "issue_status": issueStatus,- }- s.Bus.Publish(events.Event{- Type: inbox.NewItemEventType(item),- WorkspaceID: workspaceID,- ActorType: "agent",- ActorID: agentID,- Payload: map[string]any{"item": resp},- })}// agentToMap builds a simple map for broadcasting agent status updates.diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.goindex 494ff84319..a8b2f9df8b 100644--- a/server/pkg/db/generated/inbox.sql.go+++ b/server/pkg/db/generated/inbox.sql.go@@ -352,7 +352,7 @@ type CreateInboxItemParams struct {//// MUL-9333: a row written on an issue the recipient has snoozed joins the// snooze, so it stays out of the inbox with the rest of the issue.-// inbox.CreateIfEligible ends the snooze instead when the row is one that+// inbox.Deliver ends the snooze instead when the row is one that// wakes it.// MUL-8472: a member outside a private project gets no notification about its// issues, whatever their workspace role. Only project members do.diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sqlindex 4048874b25..e1219f7cb7 100644--- a/server/pkg/db/queries/inbox.sql+++ b/server/pkg/db/queries/inbox.sql@@ -119,7 +119,7 @@ WHERE id = $1 AND workspace_id = $2;---- MUL-9333: a row written on an issue the recipient has snoozed joins the-- snooze, so it stays out of the inbox with the rest of the issue.--- inbox.CreateIfEligible ends the snooze instead when the row is one that+-- inbox.Deliver ends the snooze instead when the row is one that-- wakes it.INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id,