Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5632: fix(engine): broadcast the full issue payload for chat-created issues (#6278)
Xichang(Seacen) Zhaocb04226fd484
diff --git a/server/cmd/server/subscriber_listeners.go b/server/cmd/server/subscriber_listeners.goindex f50e9314f1..c898a10839 100644--- a/server/cmd/server/subscriber_listeners.go+++ b/server/cmd/server/subscriber_listeners.go@@ -29,7 +29,7 @@ func registerSubscriberListeners(bus *events.Bus, pool *pgxpool.Pool) {return}// Issues created via handler use IssueResponse; autopilot-created issues- // use map[string]any (see service/autopilot.go → issueToMap).+ // use map[string]any (see service/autopilot.go → IssueToMap).issue, ok := extractIssueFields(payload["issue"])if !ok {returndiff --git a/server/internal/handler/issue_metadata.go b/server/internal/handler/issue_metadata.goindex 2ff0fec698..e723567cb2 100644--- a/server/internal/handler/issue_metadata.go+++ b/server/internal/handler/issue_metadata.go@@ -11,6 +11,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5""github.com/multica-ai/multica/server/internal/logger"+ "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")@@ -75,16 +76,11 @@ func validateIssueMetadataValue(raw json.RawMessage) error {// parseIssueMetadata decodes the JSONB bytes from db.Issue.Metadata into a// Go map suitable for response serialization. Empty or unparseable blobs// degrade to an empty map — the DB CHECK guarantees object shape, so this-// path is only hit on rows somehow predating the migration.+// path is only hit on rows somehow predating the migration. Shared with the+// service-layer broadcast rendering (service.IssueToMap) so both ways of+// describing an issue agree on what an unset bag looks like on the wire.func parseIssueMetadata(raw []byte) map[string]any {- if len(raw) == 0 {- return map[string]any{}- }- var out map[string]any- if err := json.Unmarshal(raw, &out); err != nil || out == nil {- return map[string]any{}- }- return out+ return util.JSONObjectOrEmpty(raw)}// parseMetadataFilterParam reads the `metadata` query parameter (a JSONdiff --git a/server/internal/handler/issue_payload_shape_test.go b/server/internal/handler/issue_payload_shape_test.gonew file mode 100644index 0000000000..c33d1d9083--- /dev/null+++ b/server/internal/handler/issue_payload_shape_test.go@@ -0,0 +1,182 @@+package handler++import (+ "encoding/json"+ "sort"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// An issue reaches clients rendered two different ways: the HTTP handler+// marshals IssueResponse, while events published outside it (autopilot and the+// channel engine's /issue command on issue:created, the background stuck-issue+// status reset on issue:updated) marshal service.IssueToMap.+// Clients type both as a complete Issue and insert the+// object straight into the list cache without runtime validation, so a key+// present in one rendering and absent from the other is a field that reads+// back undefined depending on which entry point created the issue — a project+// that never lands in its project view, a custom-property column that shows+// empty until the next refetch.+//+// Adding a field to IssueResponse without adding it to IssueToMap must fail+// here rather than in the UI.+func TestIssueToMap_KeysMatchIssueResponse(t *testing.T) {+ const prefix = "MUL"+ issue := fullyPopulatedIssue(t)++ responseKeys := jsonKeys(t, issueToResponse(issue, prefix))+ mapKeys := jsonKeys(t, service.IssueToMap(issue, prefix))++ for _, k := range responseKeys {+ if !hasKey(mapKeys, k) {+ t.Errorf("service.IssueToMap is missing %q, which handler.IssueResponse emits; "++ "clients treat both as a complete Issue", k)+ }+ }+ for _, k := range mapKeys {+ if !hasKey(responseKeys, k) {+ t.Errorf("service.IssueToMap emits %q, which handler.IssueResponse does not; "++ "the two renderings must describe the same issue", k)+ }+ }+}++// The two renderings must also agree on values and JSON types, not just on+// which keys exist — a number sent as a string, or a date formatted+// differently, breaks clients just as quietly as a missing field.+func TestIssueToMap_ValuesMatchIssueResponse(t *testing.T) {+ const prefix = "MUL"+ issue := fullyPopulatedIssue(t)++ response, err := json.Marshal(issueToResponse(issue, prefix))+ if err != nil {+ t.Fatalf("marshal IssueResponse: %v", err)+ }+ fromMap, err := json.Marshal(service.IssueToMap(issue, prefix))+ if err != nil {+ t.Fatalf("marshal IssueToMap: %v", err)+ }++ var want, got map[string]any+ if err := json.Unmarshal(response, &want); err != nil {+ t.Fatalf("unmarshal IssueResponse: %v", err)+ }+ if err := json.Unmarshal(fromMap, &got); err != nil {+ t.Fatalf("unmarshal IssueToMap: %v", err)+ }++ for k, wantValue := range want {+ gotValue, ok := got[k]+ if !ok {+ continue // reported by the key test+ }+ wantJSON, _ := json.Marshal(wantValue)+ gotJSON, _ := json.Marshal(gotValue)+ if string(wantJSON) != string(gotJSON) {+ t.Errorf("issue[%q]: IssueToMap has %s, IssueResponse has %s", k, gotJSON, wantJSON)+ }+ }+}++// metadata and properties are documented as always present so clients can+// index them without a nil guard. A row that never had either bag written+// must still broadcast {}, never null.+func TestIssueToMap_UnsetJSONBagsAreEmptyObjects(t *testing.T) {+ issue := db.Issue{Number: 42}++ raw, err := json.Marshal(service.IssueToMap(issue, "MUL"))+ if err != nil {+ t.Fatalf("marshal IssueToMap: %v", err)+ }+ var payload map[string]json.RawMessage+ if err := json.Unmarshal(raw, &payload); err != nil {+ t.Fatalf("unmarshal IssueToMap: %v", err)+ }++ for _, key := range []string{"metadata", "properties"} {+ if got := string(payload[key]); got != "{}" {+ t.Errorf("issue[%q] = %s; want {} so clients can index it without a nil guard", key, got)+ }+ }+}++// A workspace lookup can fail on the chat path, which degrades the prefix to+// "". The identifier is then rendered from the number alone rather than as a+// stray "-42", and the chat reply and the broadcast payload must not disagree+// about it (both call service.IssueIdentifier).+func TestIssueIdentifier_DegradesWithoutPrefix(t *testing.T) {+ if got := service.IssueIdentifier("MUL", 42); got != "MUL-42" {+ t.Errorf("IssueIdentifier(\"MUL\", 42) = %q; want MUL-42", got)+ }+ if got := service.IssueIdentifier("", 42); got != "#42" {+ t.Errorf("IssueIdentifier(\"\", 42) = %q; want #42", got)+ }+}++// fullyPopulatedIssue returns a row with every nullable column set, so a+// rendering that drops a field cannot pass by coincidentally emitting the+// zero value both ways.+func fullyPopulatedIssue(t *testing.T) db.Issue {+ t.Helper()+ utcDate := func(y int, m time.Month, d int) time.Time {+ return time.Date(y, m, d, 0, 0, 0, 0, time.UTC)+ }+ return db.Issue{+ ID: parseUUID("11111111-1111-1111-1111-111111111111"),+ WorkspaceID: parseUUID("22222222-2222-2222-2222-222222222222"),+ Number: 42,+ Title: "Fix login",+ Description: pgtype.Text{String: "details", Valid: true},+ Status: "todo",+ Priority: "high",+ AssigneeType: pgtype.Text{String: "agent", Valid: true},+ AssigneeID: parseUUID("33333333-3333-3333-3333-333333333333"),+ CreatorType: "member",+ CreatorID: parseUUID("44444444-4444-4444-4444-444444444444"),+ ParentIssueID: parseUUID("55555555-5555-5555-5555-555555555555"),+ ProjectID: parseUUID("66666666-6666-6666-6666-666666666666"),+ Position: 1024.5,+ Stage: pgtype.Int4{Int32: 2, Valid: true},+ StartDate: pgtype.Date{Time: utcDate(2026, time.January, 1), Valid: true},+ DueDate: pgtype.Date{Time: utcDate(2026, time.February, 1), Valid: true},+ CreatedAt: pgtype.Timestamptz{Time: utcDate(2026, time.January, 1), Valid: true},+ UpdatedAt: pgtype.Timestamptz{Time: utcDate(2026, time.January, 2), Valid: true},+ Metadata: []byte(`{"pr_url":"https://example.test/pr/1"}`),+ Properties: []byte(`{"77777777-7777-7777-7777-777777777777":"done"}`),+ }+}++// jsonKeys marshals a value and returns its top-level JSON keys. Fields tagged+// omitempty (reactions, attachments, labels) are absent from both renderings+// here by construction: they are optional decorations the client already+// nil-guards, not part of the core issue shape this test pins.+func jsonKeys(t *testing.T, v any) []string {+ t.Helper()+ raw, err := json.Marshal(v)+ if err != nil {+ t.Fatalf("marshal %T: %v", v, err)+ }+ var fields map[string]json.RawMessage+ if err := json.Unmarshal(raw, &fields); err != nil {+ t.Fatalf("unmarshal %T: %v", v, err)+ }+ keys := make([]string, 0, len(fields))+ for k := range fields {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ return keys+}++func hasKey(keys []string, key string) bool {+ for _, k := range keys {+ if k == key {+ return true+ }+ }+ return false+}diff --git a/server/internal/handler/property.go b/server/internal/handler/property.goindex c1240a8f65..52d26f2d79 100644--- a/server/internal/handler/property.go+++ b/server/internal/handler/property.go@@ -434,14 +434,7 @@ func describeOptionsInUse(existingConfig []byte, rows []db.CountIssuesUsingPrope// parseIssueProperties mirrors parseIssueMetadata for the properties bag.func parseIssueProperties(raw []byte) map[string]any {- if len(raw) == 0 {- return map[string]any{}- }- var out map[string]any- if err := json.Unmarshal(raw, &out); err != nil || out == nil {- return map[string]any{}- }- return out+ return util.JSONObjectOrEmpty(raw)}// ---------------------------------------------------------------------------diff --git a/server/internal/integrations/channel/engine/issue_broadcast_test.go b/server/internal/integrations/channel/engine/issue_broadcast_test.gonew file mode 100644index 0000000000..6b2f48a601--- /dev/null+++ b/server/internal/integrations/channel/engine/issue_broadcast_test.go@@ -0,0 +1,90 @@+package engine++import (+ "context"+ "testing"++ "github.com/multica-ai/multica/server/internal/service"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// A chat-created issue must broadcast the same full issue payload the HTTP+// path does. cmd/server's extractIssueFields drops any issue:created event+// whose payload lacks id or creator_id, and dropping it means the creator is+// never auto-subscribed to the issue they just opened from chat.+func TestRouter_IssueCommand_BroadcastPayloadCarriesIdentityFields(t *testing.T) {+ h := newHarness(t)+ h.binder.appendResult = AppendResult{+ DedupMarked: true,+ IssueCommand: &IssueCommand{Title: "Fix login", Description: "details"},+ }++ issueID := uuidFromString(t, "77777777-7777-7777-7777-777777777777")+ creatorID := h.ident.id.UserID+ workspaceID := h.inst.inst.WorkspaceID+ created := db.Issue{+ ID: issueID,+ WorkspaceID: workspaceID,+ Number: 42,+ Title: "Fix login",+ CreatorType: "member",+ CreatorID: creatorID,+ }+ h.issues.result = service.IssueCreateResult{Issue: created}++ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !h.issues.called {+ t.Fatal("expected issue create")+ }++ build := h.issues.opts.BroadcastPayload+ if build == nil {+ t.Fatal("engine passed no BroadcastPayload, so the service emits its " ++ "{\"issue_id\": ...} stub; extractIssueFields finds no \"issue\" key " ++ "and short-circuits, leaving the creator unsubscribed")+ }++ payload := build(created, nil, nil)+ raw, ok := payload["issue"]+ if !ok {+ t.Fatalf("payload has no \"issue\" key; got keys %v", keysOf(payload))+ }+ issue, ok := raw.(map[string]any)+ if !ok {+ t.Fatalf("payload[\"issue\"] is %T; want map[string]any", raw)+ }++ // The three fields extractIssueFields reads before it decides whether to+ // keep the event.+ for _, tc := range []struct {+ field string+ want string+ }{+ {"id", "77777777-7777-7777-7777-777777777777"},+ {"creator_id", "44444444-4444-4444-4444-444444444444"},+ {"workspace_id", "22222222-2222-2222-2222-222222222222"},+ } {+ got, _ := issue[tc.field].(string)+ if got != tc.want {+ t.Errorf("issue[%q] = %q; want %q", tc.field, got, tc.want)+ }+ }+ if got, _ := issue["creator_type"].(string); got != "member" {+ t.Errorf("issue[\"creator_type\"] = %q; want member", got)+ }+ // The workspace issue prefix must come from the workspace row, matching the+ // identifier the chat reply already shows.+ if got, _ := issue["identifier"].(string); got != "MUL-42" {+ t.Errorf("issue[\"identifier\"] = %q; want MUL-42", got)+ }+}++func keysOf(m map[string]any) []string {+ out := make([]string, 0, len(m))+ for k := range m {+ out = append(out, k)+ }+ return out+}diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.goindex 919e7b08fb..f452e08026 100644--- a/server/internal/integrations/channel/engine/router.go+++ b/server/internal/integrations/channel/engine/router.go@@ -12,6 +12,8 @@ import ("github.com/multica-ai/multica/server/internal/integrations/channel""github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated")// Router is the channel-agnostic inbound pipeline — the generalization of the@@ -369,18 +371,19 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe// 7. /issue command, if present. chat_message is already durable; all// error returns from here signal finalizeNone (or the defensive Mark).if appendRes.IssueCommand != nil {- issueRes, err := r.createIssue(ctx, inst, set.OriginType, identity.UserID, sessionID, *appendRes.IssueCommand)+ // One lookup feeds both the broadcast payload's identifier and the+ // chat reply's.+ prefix := r.issuePrefix(ctx, inst.WorkspaceID)+ issueRes, err := r.createIssue(ctx, inst, set.OriginType, identity.UserID, sessionID, *appendRes.IssueCommand, prefix)if err != nil {return Result{}, postAppendFinalize, fmt.Errorf("create issue from command: %w", err)}res.IssueID = issueRes.Issue.IDres.IssueNumber = issueRes.Issue.Numberres.IssueTitle = issueRes.Issue.Title- if ws, werr := r.reader.GetWorkspace(ctx, inst.WorkspaceID); werr == nil && ws.IssuePrefix != "" {- res.IssueIdentifier = fmt.Sprintf("%s-%d", ws.IssuePrefix, issueRes.Issue.Number)- } else {- res.IssueIdentifier = fmt.Sprintf("#%d", issueRes.Issue.Number)- }+ // Same renderer the broadcast payload uses, so a degraded prefix can't+ // show the chat "#42" while the realtime list shows "-42".+ res.IssueIdentifier = service.IssueIdentifier(prefix, issueRes.Issue.Number)}// 8. Debounce the run trigger. The synchronous outcome is OutcomeIngested@@ -655,7 +658,7 @@ func (r *Router) drop(ctx context.Context, set ResolverSet, msg channel.InboundMreturn Result{Outcome: OutcomeDropped, DropReason: reason, InstallationID: instID}}-func (r *Router) createIssue(ctx context.Context, inst ResolvedInstallation, originType string, creatorUserID, sessionID pgtype.UUID, cmd IssueCommand) (service.IssueCreateResult, error) {+func (r *Router) createIssue(ctx context.Context, inst ResolvedInstallation, originType string, creatorUserID, sessionID pgtype.UUID, cmd IssueCommand, issuePrefix string) (service.IssueCreateResult, error) {if cmd.Title == "" {return service.IssueCreateResult{}, ErrEmptyIssueTitle}@@ -672,7 +675,33 @@ func (r *Router) createIssue(ctx context.Context, inst ResolvedInstallation, oriOriginType: pgtype.Text{String: originType, Valid: originType != ""},OriginID: sessionID,}- return r.issues.Create(ctx, params, service.IssueCreateOpts{})+ // Without a BroadcastPayload the service emits its minimal+ // {"issue_id": ...} stub, and every issue:created consumer that reads the+ // "issue" key drops the event — most visibly the subscriber listener, which+ // needs id + creator_id and so never subscribed the person who typed+ // /issue to their own issue. IssueToMap is the shared renderer for events+ // published outside the HTTP handler; it stays key-compatible with the+ // IssueResponse that handler path broadcasts, so clients see one issue+ // shape regardless of which entry point created the issue.+ opts := service.IssueCreateOpts{+ BroadcastPayload: func(issue db.Issue, _ []db.Attachment, _ []db.IssueLabel) map[string]any {+ return map[string]any{"issue": service.IssueToMap(issue, issuePrefix)}+ },+ }+ return r.issues.Create(ctx, params, opts)+}++// issuePrefix reads the workspace's issue key (the "MUL" in MUL-42). A read+// failure is not worth failing issue creation over, so it degrades to empty+// and only the rendered identifier suffers.+func (r *Router) issuePrefix(ctx context.Context, workspaceID pgtype.UUID) string {+ ws, err := r.reader.GetWorkspace(ctx, workspaceID)+ if err != nil {+ r.logger.Warn("channel engine: workspace lookup for issue prefix failed",+ "workspace_id", util.UUIDToString(workspaceID), "error", err)+ return ""+ }+ return ws.IssuePrefix}// ErrEmptyIssueTitle is returned by createIssue when /issue has no title anddiff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.goindex 9a24f32287..931dcd6e89 100644--- a/server/internal/integrations/channel/engine/router_test.go+++ b/server/internal/integrations/channel/engine/router_test.go@@ -236,13 +236,15 @@ func (f *fakeMedia) calls() int {type fakeIssues struct {called boolparams service.IssueCreateParams+ opts service.IssueCreateOptsresult service.IssueCreateResulterr error}-func (f *fakeIssues) Create(_ context.Context, p service.IssueCreateParams, _ service.IssueCreateOpts) (service.IssueCreateResult, error) {+func (f *fakeIssues) Create(_ context.Context, p service.IssueCreateParams, o service.IssueCreateOpts) (service.IssueCreateResult, error) {f.called = truef.params = p+ f.opts = oreturn f.result, f.err}diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex b081416834..874923025f 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -691,7 +691,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.AutopiActorType: "agent",ActorID: util.UUIDToString(leader.ID),Payload: map[string]any{- "issue": issueToMap(issue, prefix),+ "issue": IssueToMap(issue, prefix),},})s.captureIssueCreatedFromAutopilot(ap, run, issue, leader.ID)diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex d7ed240650..bd97ee0274 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -4494,7 +4494,7 @@ func (s *TaskService) broadcastChatDone(ctx context.Context, task db.AgentTaskQu// issue's status before the write so the client can gate that reconcile on// status_changed.//-// The `issue` payload is a map (issueToMap), which the workspace WS fanout+// The `issue` payload is a map (IssueToMap), which the workspace WS fanout// (listeners.go SubscribeAll) marshals and broadcasts as-is — that is what// drives the UI reconcile. Note this does NOT cover the full HTTP UpdateIssue// side effects: the activity-log and inbox listeners type-assert `issue` to a@@ -4510,7 +4510,7 @@ func (s *TaskService) broadcastIssueUpdated(issue db.Issue, prevStatus string) {ActorType: "system",ActorID: "",Payload: map[string]any{- "issue": issueToMap(issue, prefix),+ "issue": IssueToMap(issue, prefix),"status_changed": prevStatus != issue.Status,"prev_status": prevStatus,},@@ -4623,12 +4623,27 @@ func (s *TaskService) AutoUnresolveThreadOnReply(ctx context.Context, parent *db})}-func issueToMap(issue db.Issue, issuePrefix string) map[string]any {+// IssueToMap renders an issue row as the map shape the issue:created /+// issue:updated broadcast payloads carry under their "issue" key. It is the+// single source of truth for that shape wherever the event is published from+// outside the HTTP handler — autopilot and the channel engine's /issue command+// on issue:created, the background stuck-issue status reset on issue:updated.+// The workspace WS fanout marshals it as-is for the UI, and cmd/server's+// extractIssueFields reads id / creator_id / workspace_id off it to decide who+// to auto-subscribe.+//+// The map must stay key-compatible with handler.IssueResponse, the other+// rendering of the same event. Clients type both as a complete Issue and+// insert it straight into the list cache without runtime validation, so a+// field missing here is a field that reads back undefined until the next+// refetch — see TestIssueToMap_KeysMatchIssueResponse, which fails if the two+// renderings drift apart.+func IssueToMap(issue db.Issue, issuePrefix string) map[string]any {return map[string]any{"id": util.UUIDToString(issue.ID),"workspace_id": util.UUIDToString(issue.WorkspaceID),"number": issue.Number,- "identifier": issuePrefix + "-" + strconv.Itoa(int(issue.Number)),+ "identifier": IssueIdentifier(issuePrefix, issue.Number),"title": issue.Title,"description": util.TextToPtr(issue.Description),"status": issue.Status,@@ -4638,12 +4653,28 @@ func issueToMap(issue db.Issue, issuePrefix string) map[string]any {"creator_type": issue.CreatorType,"creator_id": util.UUIDToString(issue.CreatorID),"parent_issue_id": util.UUIDToPtr(issue.ParentIssueID),+ "project_id": util.UUIDToPtr(issue.ProjectID),"position": issue.Position,+ "stage": util.Int4ToPtr(issue.Stage),"start_date": util.DateToPtr(issue.StartDate),"due_date": util.DateToPtr(issue.DueDate),"created_at": util.TimestampToString(issue.CreatedAt),"updated_at": util.TimestampToString(issue.UpdatedAt),+ "metadata": util.JSONObjectOrEmpty(issue.Metadata),+ "properties": util.JSONObjectOrEmpty(issue.Properties),+ }+}++// IssueIdentifier renders the human-facing issue key ("MUL-42"). Callers that+// resolve the workspace prefix defensively may pass "": a failed workspace+// lookup should not surface as a stray "-42", so the number stands alone as+// "#42". The HTTP layer never passes "" — handler.getIssuePrefix derives a+// prefix from the workspace name before rendering anything.+func IssueIdentifier(issuePrefix string, number int32) string {+ if issuePrefix == "" {+ return "#" + strconv.Itoa(int(number))}+ return issuePrefix + "-" + strconv.Itoa(int(number))}// parseQuickCreateContext returns the quick-create payload if the task'sdiff --git a/server/internal/util/json.go b/server/internal/util/json.gonew file mode 100644index 0000000000..6e799c6d04--- /dev/null+++ b/server/internal/util/json.go@@ -0,0 +1,19 @@+package util++import "encoding/json"++// JSONObjectOrEmpty decodes a JSONB column whose API contract promises an+// object is always present (issue metadata, issue custom properties) into a+// Go map. Empty, null, or unparseable blobs degrade to an empty map rather+// than nil: nil marshals to `null`, and "always present" is precisely what+// lets clients index the field without a nil guard.+func JSONObjectOrEmpty(raw []byte) map[string]any {+ if len(raw) == 0 {+ return map[string]any{}+ }+ var out map[string]any+ if err := json.Unmarshal(raw, &out); err != nil || out == nil {+ return map[string]any{}+ }+ return out+}