Files
multica/server/internal/handler/inbox.go
b566b5fd4e perf(inbox): ship a 200-character preview of comment notifications in the lists (#8294)
A comment notification stores the full comment it was raised for, and both
inbox lists returned it verbatim. A several-thousand-character agent reply
travelled over the wire, through JSON parsing and into the client cache for
every subscriber, only to be rendered as a single truncated line.

The main and archived list responses now cap the body of a `new_comment`
notification on an issue at 200 characters, the ellipsis included. The
database keeps the full text, and `details.comment_id` is untouched.

The scope is exactly the rows whose full body no client reads from the list.
Opening an issue-backed notification renders the issue itself and lands on the
comment through `comment_id`; everywhere else, web, desktop and mobile show
that body as one line. That holds for builds already installed, so none has to
change: the field, its type and the endpoints are the same. Other types keep
their full body — issue-less notifications render it in the detail pane from
the list cache, and Quick Create failures refill the composer from `details`.
Single-item responses are unchanged.

Truncation walks code points and stops at the limit, so a multi-byte character
is never split and the work per row is bounded by the preview, not by the
comment's length.

Sampled on 264 comments from this workspace's recent issues: half exceed 200
characters (median 203, p90 3,277, max 12,251), and capping cuts their text by
86%. A list of comment notifications built from them shrinks 64% raw and 69%
gzipped; an inbox's overall saving depends on its share of comment rows.

Refs MUL-6967.

Co-authored-by: J <[email protected]>
Co-authored-by: multica-agent <[email protected]>
2026-09-11 14:12:02 +08:00

532 lines
18 KiB
Go

package handler
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/logger"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
type InboxItemResponse struct {
ID string `json:"id"`
WorkspaceID string `json:"workspace_id"`
RecipientType string `json:"recipient_type"`
RecipientID string `json:"recipient_id"`
Type string `json:"type"`
Severity string `json:"severity"`
IssueID *string `json:"issue_id"`
Title string `json:"title"`
Body *string `json:"body"`
Read bool `json:"read"`
Archived bool `json:"archived"`
CreatedAt string `json:"created_at"`
IssueStatus *string `json:"issue_status"`
IssuePriority *string `json:"issue_priority"`
ActorType *string `json:"actor_type"`
ActorID *string `json:"actor_id"`
Details json.RawMessage `json:"details"`
}
func inboxToResponse(i db.InboxItem) InboxItemResponse {
return InboxItemResponse{
ID: uuidToString(i.ID),
WorkspaceID: uuidToString(i.WorkspaceID),
RecipientType: i.RecipientType,
RecipientID: uuidToString(i.RecipientID),
Type: i.Type,
Severity: i.Severity,
IssueID: uuidToPtr(i.IssueID),
Title: i.Title,
Body: textToPtr(i.Body),
Read: i.Read,
Archived: i.Archived,
CreatedAt: timestampToString(i.CreatedAt),
ActorType: textToPtr(i.ActorType),
ActorID: uuidToPtr(i.ActorID),
Details: json.RawMessage(i.Details),
}
}
// inboxListBodyPreviewLimit caps, in characters, the body a comment
// notification carries in the inbox LIST responses. The ellipsis counts
// toward it.
//
// A comment notification stores the full comment it was raised for, and the
// list shipped that verbatim — a several-thousand-character agent reply went
// over the wire, through JSON parsing and into the client cache, only for
// every client to render it as a single truncated line. 200 leaves ample room
// for that one line at any width or script, while bounding what each row can
// cost.
const inboxListBodyPreviewLimit = 200
// inboxListBody returns the body a notification carries in the inbox list:
// comment notifications on an issue get a bounded preview, everything else is
// returned as stored. The database keeps the full text.
//
// Scoped to exactly the rows whose full body no client ever reads from the
// list. Opening an issue-backed notification renders the issue itself, and the
// comment it points at is found through `details.comment_id`, which is left
// intact — on every client already installed, so none needs to change. Other
// notification types are NOT shortened: issue-less notifications render their
// body in the detail pane straight from the list cache, and Quick Create
// failures refill the composer from `details` — cutting those would lose
// content, not just bytes.
//
// Truncation is by code point, so a multi-byte character is never split into
// invalid UTF-8. A grapheme cluster (an emoji sequence, a letter with a
// combining mark) can still be cut at the boundary; that lands ~200 characters
// in, far past the single line any client shows.
//
// One pass that stops at the limit, rather than counting or converting the
// whole string: the work per row stays bounded by the preview, not by however
// long the comment happens to be.
func inboxListBody(notifType string, issueID pgtype.UUID, body pgtype.Text) *string {
full := textToPtr(body)
if full == nil || notifType != "new_comment" || !issueID.Valid {
return full
}
// `range` yields the byte offset where each character starts. `cut` ends
// up where the ellipsis goes: after limit-1 characters.
cut, seen := 0, 0
for offset := range *full {
if seen == inboxListBodyPreviewLimit-1 {
cut = offset
}
if seen++; seen > inboxListBodyPreviewLimit {
preview := (*full)[:cut] + "…"
return &preview
}
}
return full
}
// inboxRowToResponse maps a LIST row — the main inbox and, through
// archivedInboxRowToResponse, the archived view. Single-item responses go
// through inboxToResponse and keep the full body.
func inboxRowToResponse(r db.ListInboxItemsRow) InboxItemResponse {
return InboxItemResponse{
ID: uuidToString(r.ID),
WorkspaceID: uuidToString(r.WorkspaceID),
RecipientType: r.RecipientType,
RecipientID: uuidToString(r.RecipientID),
Type: r.Type,
Severity: r.Severity,
IssueID: uuidToPtr(r.IssueID),
Title: r.Title,
Body: inboxListBody(r.Type, r.IssueID, r.Body),
Read: r.Read,
Archived: r.Archived,
CreatedAt: timestampToString(r.CreatedAt),
IssueStatus: textToPtr(r.IssueStatus),
IssuePriority: textToPtr(r.IssuePriority),
ActorType: textToPtr(r.ActorType),
ActorID: uuidToPtr(r.ActorID),
Details: json.RawMessage(r.Details),
}
}
// ListArchivedInboxItemsRow carries the same columns as ListInboxItemsRow (both
// queries select `inbox_item.*` plus the joined issue projections), so the archived
// row converts to the active one and reuses its mapper. If either query's
// column list drifts, this conversion stops compiling — which is the point.
func archivedInboxRowToResponse(r db.ListArchivedInboxItemsRow) InboxItemResponse {
return inboxRowToResponse(db.ListInboxItemsRow(r))
}
func (h *Handler) enrichInboxResponse(ctx context.Context, resp InboxItemResponse, issueID pgtype.UUID) InboxItemResponse {
if !issueID.Valid {
return resp
}
issue, err := h.Queries.GetIssue(ctx, issueID)
if err == nil {
s := issue.Status
resp.IssueStatus = &s
p := issue.Priority
resp.IssuePriority = &p
}
return resp
}
func (h *Handler) ListInbox(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
return
}
workspaceID := ctxWorkspaceID(r.Context())
wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
return
}
items, err := h.Queries.ListInboxItems(r.Context(), db.ListInboxItemsParams{
WorkspaceID: wsUUID,
RecipientType: "member",
RecipientID: parseUUID(userID),
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list inbox")
return
}
resp := make([]InboxItemResponse, len(items))
for i, item := range items {
resp[i] = inboxRowToResponse(item)
}
writeJSON(w, http.StatusOK, resp)
}
// ListArchivedInbox returns the recipient's archived notifications, backing the
// inbox's "Archived" sub-view. Kept as its own endpoint rather than a flag on
// ListInbox so installed clients keep their current contract, and so the
// unbounded archive never rides along with the main list.
//
// The query drops any issue that also has an active row, keeping this list and
// the main inbox mutually exclusive per issue group. It selects at most 200
// groups and returns only each group's newest row plus its optional comment
// anchor — see the query comment for both the bound and the grouping contract.
func (h *Handler) ListArchivedInbox(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
return
}
workspaceID := ctxWorkspaceID(r.Context())
wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
return
}
items, err := h.Queries.ListArchivedInboxItems(r.Context(), db.ListArchivedInboxItemsParams{
WorkspaceID: wsUUID,
RecipientType: "member",
RecipientID: parseUUID(userID),
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list archived inbox")
return
}
resp := make([]InboxItemResponse, len(items))
for i, item := range items {
resp[i] = archivedInboxRowToResponse(item)
}
writeJSON(w, http.StatusOK, resp)
}
func (h *Handler) MarkInboxRead(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
prev, ok := h.loadInboxItemForUser(w, r, id)
if !ok {
return
}
item, err := h.Queries.MarkInboxRead(r.Context(), prev.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to mark read")
return
}
userID := requestUserID(r)
workspaceID := uuidToString(item.WorkspaceID)
h.publish(protocol.EventInboxRead, workspaceID, "member", userID, map[string]any{
"item_id": uuidToString(item.ID),
"recipient_id": uuidToString(item.RecipientID),
})
resp := h.enrichInboxResponse(r.Context(), inboxToResponse(item), item.IssueID)
writeJSON(w, http.StatusOK, resp)
}
// MarkInboxUnread flips a notification back to unread, the inverse of
// MarkInboxRead. It exists so a user can park something they opened but did not
// act on: the inbox auto-marks an item read the moment it is selected, which
// otherwise makes "opened" and "handled" the same signal.
//
// Scope is the single item, matching MarkInboxRead — see the query comment.
func (h *Handler) MarkInboxUnread(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
prev, ok := h.loadInboxItemForUser(w, r, id)
if !ok {
return
}
item, err := h.Queries.MarkInboxUnread(r.Context(), prev.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to mark unread")
return
}
userID := requestUserID(r)
workspaceID := uuidToString(item.WorkspaceID)
h.publish(protocol.EventInboxUnread, workspaceID, "member", userID, map[string]any{
"item_id": uuidToString(item.ID),
"recipient_id": uuidToString(item.RecipientID),
})
resp := h.enrichInboxResponse(r.Context(), inboxToResponse(item), item.IssueID)
writeJSON(w, http.StatusOK, resp)
}
func (h *Handler) ArchiveInboxItem(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
prev, ok := h.loadInboxItemForUser(w, r, id)
if !ok {
return
}
item, err := h.Queries.ArchiveInboxItem(r.Context(), prev.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to archive")
return
}
// Archive all sibling inbox items for the same issue (issue-level archive)
if item.IssueID.Valid {
h.Queries.ArchiveInboxByIssue(r.Context(), db.ArchiveInboxByIssueParams{
WorkspaceID: item.WorkspaceID,
RecipientType: item.RecipientType,
RecipientID: item.RecipientID,
IssueID: item.IssueID,
})
}
userID := requestUserID(r)
workspaceID := uuidToString(item.WorkspaceID)
h.publish(protocol.EventInboxArchived, workspaceID, "member", userID, map[string]any{
"item_id": uuidToString(item.ID),
"issue_id": uuidToPtr(item.IssueID),
"recipient_id": uuidToString(item.RecipientID),
})
resp := h.enrichInboxResponse(r.Context(), inboxToResponse(item), item.IssueID)
writeJSON(w, http.StatusOK, resp)
}
// UnarchiveInboxItem restores an archived notification to the main inbox. It is
// the inverse of ArchiveInboxItem and mirrors its issue-level scope: archiving
// one item archives every sibling for the same issue, so restoring brings the
// whole group back.
//
// `read` is untouched on purpose. An item archived while unread comes back
// unread, which raises the unread badge again — the badge only ever counted
// non-archived items, so restoring one is a real addition, not a bug.
func (h *Handler) UnarchiveInboxItem(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
prev, ok := h.loadInboxItemForUser(w, r, id)
if !ok {
return
}
item, err := h.Queries.UnarchiveInboxItem(r.Context(), prev.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to unarchive")
return
}
// Restore all sibling inbox items for the same issue (issue-level restore).
if item.IssueID.Valid {
h.Queries.UnarchiveInboxByIssue(r.Context(), db.UnarchiveInboxByIssueParams{
WorkspaceID: item.WorkspaceID,
RecipientType: item.RecipientType,
RecipientID: item.RecipientID,
IssueID: item.IssueID,
})
}
userID := requestUserID(r)
workspaceID := uuidToString(item.WorkspaceID)
h.publish(protocol.EventInboxUnarchived, workspaceID, "member", userID, map[string]any{
"item_id": uuidToString(item.ID),
"issue_id": uuidToPtr(item.IssueID),
"recipient_id": uuidToString(item.RecipientID),
})
resp := h.enrichInboxResponse(r.Context(), inboxToResponse(item), item.IssueID)
writeJSON(w, http.StatusOK, resp)
}
func (h *Handler) CountUnreadInbox(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
return
}
workspaceID := ctxWorkspaceID(r.Context())
wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
return
}
count, err := h.Queries.CountUnreadInbox(r.Context(), db.CountUnreadInboxParams{
WorkspaceID: wsUUID,
RecipientType: "member",
RecipientID: parseUUID(userID),
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to count unread inbox")
return
}
writeJSON(w, http.StatusOK, map[string]int64{"count": count})
}
// InboxWorkspaceUnreadResponse is one workspace's unread inbox count in the
// cross-workspace summary.
type InboxWorkspaceUnreadResponse struct {
WorkspaceID string `json:"workspace_id"`
Count int64 `json:"count"`
}
// UnreadInboxSummary returns per-workspace unread inbox counts across every
// workspace the user belongs to. The sidebar uses it to light a dot on the
// workspace switcher when a workspace OTHER than the active one has unread
// items, without fetching each workspace's full inbox list. It is
// account-level by nature: it ignores the active workspace and keys only on
// the authenticated user.
func (h *Handler) UnreadInboxSummary(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
return
}
rows, err := h.Queries.CountUnreadInboxByWorkspace(r.Context(), parseUUID(userID))
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to summarize unread inbox")
return
}
resp := make([]InboxWorkspaceUnreadResponse, len(rows))
for i, row := range rows {
resp[i] = InboxWorkspaceUnreadResponse{
WorkspaceID: uuidToString(row.WorkspaceID),
Count: row.Count,
}
}
writeJSON(w, http.StatusOK, resp)
}
func (h *Handler) MarkAllInboxRead(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
return
}
workspaceID := ctxWorkspaceID(r.Context())
wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
return
}
count, err := h.Queries.MarkAllInboxRead(r.Context(), db.MarkAllInboxReadParams{
WorkspaceID: wsUUID,
RecipientID: parseUUID(userID),
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to mark all inbox read")
return
}
slog.Info("inbox: mark all read", append(logger.RequestAttrs(r), "user_id", userID, "count", count)...)
h.publish(protocol.EventInboxBatchRead, workspaceID, "member", userID, map[string]any{
"recipient_id": userID,
"count": count,
})
writeJSON(w, http.StatusOK, map[string]any{"count": count})
}
func (h *Handler) ArchiveAllInbox(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
return
}
workspaceID := ctxWorkspaceID(r.Context())
wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
return
}
count, err := h.Queries.ArchiveAllInbox(r.Context(), db.ArchiveAllInboxParams{
WorkspaceID: wsUUID,
RecipientID: parseUUID(userID),
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to archive all inbox")
return
}
slog.Info("inbox: archive all", append(logger.RequestAttrs(r), "user_id", userID, "count", count)...)
h.publish(protocol.EventInboxBatchArchived, workspaceID, "member", userID, map[string]any{
"recipient_id": userID,
"count": count,
})
writeJSON(w, http.StatusOK, map[string]any{"count": count})
}
func (h *Handler) ArchiveAllReadInbox(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
return
}
workspaceID := ctxWorkspaceID(r.Context())
wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
return
}
count, err := h.Queries.ArchiveAllReadInbox(r.Context(), db.ArchiveAllReadInboxParams{
WorkspaceID: wsUUID,
RecipientID: parseUUID(userID),
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to archive all read inbox")
return
}
slog.Info("inbox: archive all read", append(logger.RequestAttrs(r), "user_id", userID, "count", count)...)
h.publish(protocol.EventInboxBatchArchived, workspaceID, "member", userID, map[string]any{
"recipient_id": userID,
"count": count,
})
writeJSON(w, http.StatusOK, map[string]any{"count": count})
}
func (h *Handler) ArchiveCompletedInbox(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
return
}
workspaceID := ctxWorkspaceID(r.Context())
wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
return
}
terminalStatusKeys, err := h.terminalIssueStatusKeys(r.Context(), wsUUID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to resolve status categories")
return
}
count, err := h.Queries.ArchiveCompletedInbox(r.Context(), db.ArchiveCompletedInboxParams{
WorkspaceID: wsUUID,
RecipientID: parseUUID(userID),
TerminalStatusKeys: terminalStatusKeys,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to archive completed inbox")
return
}
slog.Info("inbox: archive completed", append(logger.RequestAttrs(r), "user_id", userID, "count", count)...)
h.publish(protocol.EventInboxBatchArchived, workspaceID, "member", userID, map[string]any{
"recipient_id": userID,
"count": count,
})
writeJSON(w, http.StatusOK, map[string]any{"count": count})
}