Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6680: fix autopilot list subscribers + make CLI triggers discoverable (#7552)
Bohan Jiang6cbb50378f02
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex daaf075562..8d448e81fb 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -835,6 +835,11 @@ multica autopilot get <id>multica autopilot get <id> --output json # includes triggers```+In JSON output `triggers` is a **top-level key alongside `autopilot`**, not nested+inside it — the payload is `{"autopilot": {...}, "triggers": [...], "collaborators": [...]}`.+Read trigger ids with `jq '.triggers[].id'`, or use `autopilot trigger-list` below.+The table output shows only the autopilot's own fields, not its triggers.+### Create / Update / Delete```bash@@ -871,12 +876,22 @@ multica autopilot runs <id> --limit 50 --output json### Schedule Triggers```bash+multica autopilot trigger-list <autopilot-id> # ids, kind, schedule, next run+multica autopilot trigger-list <autopilot-id> --full-id # canonical UUIDsmultica autopilot trigger-add <autopilot-id> --cron "0 9 * * 1-5" --timezone "America/New_York"multica autopilot trigger-update <autopilot-id> <trigger-id> --enabled=falsemultica autopilot trigger-delete <autopilot-id> <trigger-id>```-Only cron-based `schedule` triggers are currently exposed via the CLI. The data model also defines `webhook` and `api` kinds, but there is no server endpoint that fires them yet, so they're not surfaced here.+`trigger-list` is the way to obtain the `<trigger-id>` that `trigger-update`,+`trigger-delete` and `trigger-rotate-url` require. Like autopilot ids, trigger ids+may be passed as a short prefix as long as it is unique within that autopilot; use+`--full-id` to print canonical UUIDs. Webhook credentials are redacted in this+output — use `autopilot get <id> --output json --show-secrets` to reveal them.++The CLI exposes cron-based `schedule` triggers via `trigger-add`, and `webhook`+triggers via `trigger-add --kind webhook` plus `trigger-rotate-url`. The data model+also defines an `api` kind, which is not surfaced here.## Other Commandsdiff --git a/server/cmd/multica/cmd_autopilot.go b/server/cmd/multica/cmd_autopilot.goindex 32c5ed59ff..58ac6148bf 100644--- a/server/cmd/multica/cmd_autopilot.go+++ b/server/cmd/multica/cmd_autopilot.go@@ -74,6 +74,13 @@ var autopilotTriggerAddCmd = &cobra.Command{RunE: runAutopilotTriggerAdd,}+var autopilotTriggerListCmd = &cobra.Command{+ Use: "trigger-list <autopilot-id>",+ Short: "List an autopilot's triggers (ids for trigger-update/-delete/-rotate-url)",+ Args: exactArgs(1),+ RunE: runAutopilotTriggerList,+}+var autopilotTriggerUpdateCmd = &cobra.Command{Use: "trigger-update <autopilot-id> <trigger-id>",Short: "Update an existing trigger",@@ -104,6 +111,7 @@ func init() {autopilotCmd.AddCommand(autopilotTriggerCmd)autopilotCmd.AddCommand(autopilotRunsCmd)autopilotCmd.AddCommand(autopilotTriggerAddCmd)+ autopilotCmd.AddCommand(autopilotTriggerListCmd)autopilotCmd.AddCommand(autopilotTriggerUpdateCmd)autopilotCmd.AddCommand(autopilotTriggerDeleteCmd)autopilotCmd.AddCommand(autopilotTriggerRotateURLCmd)@@ -159,6 +167,10 @@ func init() {autopilotTriggerAddCmd.Flags().String("label", "", "Optional human-readable label")autopilotTriggerAddCmd.Flags().String("output", "json", "Output format: table or json")+ // trigger-list+ autopilotTriggerListCmd.Flags().String("output", "table", "Output format: table or json")+ autopilotTriggerListCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")+// trigger-rotate-url — webhook onlyautopilotTriggerRotateURLCmd.Flags().String("output", "json", "Output format: table or json")autopilotTriggerRotateURLCmd.Flags().BoolP("yes", "y", false, "Skip the interactive confirmation prompt")@@ -207,7 +219,10 @@ func runAutopilotList(cmd *cobra.Command, _ []string) error {fullID, _ := cmd.Flags().GetBool("full-id")actors := loadActorDisplayLookup(ctx, client)- headers := []string{"ID", "TITLE", "STATUS", "MODE", "ASSIGNEE", "LAST_RUN"}+ // NEXT_RUN is what distinguishes a scheduled autopilot from one with no+ // trigger at all. The list payload has carried next_run_at all along, but+ // the table dropped it, leaving the two indistinguishable here (MUL-6680).+ headers := []string{"ID", "TITLE", "STATUS", "MODE", "ASSIGNEE", "NEXT_RUN", "LAST_RUN"}rows := make([][]string, 0, len(resp.Autopilots))for _, a := range resp.Autopilots {rows = append(rows, []string{@@ -216,7 +231,8 @@ func runAutopilotList(cmd *cobra.Command, _ []string) error {strVal(a, "status"),strVal(a, "execution_mode"),actors.agent(strVal(a, "assignee_id")),- strVal(a, "last_run_at"),+ relativeTimestamp(strVal(a, "next_run_at")),+ relativeTimestamp(strVal(a, "last_run_at")),})}cli.PrintTable(os.Stdout, headers, rows)@@ -309,6 +325,51 @@ func redactAutopilotWebhookCredentials(resp map[string]any) {}}+// relativeTimestamp renders an RFC3339 timestamp as a short, fixed-width-ish+// relative string ("in 2h", "3d ago", "—" when absent or unparseable). Table+// columns use this instead of the raw timestamp so NEXT_RUN fits alongside the+// existing columns on a narrow terminal, and so "never scheduled" reads as a+// visibly different value rather than an empty cell (MUL-6680).+func relativeTimestamp(ts string) string {+ return relativeTimestampAt(ts, time.Now())+}++func relativeTimestampAt(ts string, now time.Time) string {+ trimmed := strings.TrimSpace(ts)+ if trimmed == "" {+ return "—"+ }+ t, err := time.Parse(time.RFC3339, trimmed)+ if err != nil {+ return "—"+ }++ d := t.Sub(now)+ suffix := " ago"+ if d >= 0 {+ suffix = ""+ } else {+ d = -d+ }++ var magnitude string+ switch {+ case d < time.Minute:+ magnitude = fmt.Sprintf("%ds", int(d.Seconds()))+ case d < time.Hour:+ magnitude = fmt.Sprintf("%dm", int(d.Minutes()))+ case d < 24*time.Hour:+ magnitude = fmt.Sprintf("%dh", int(d.Hours()))+ default:+ magnitude = fmt.Sprintf("%dd", int(d.Hours()/24))+ }++ if suffix == "" {+ return "in " + magnitude+ }+ return magnitude + suffix+}+func webhookTokenHint(token string) string {if len(token) < 4 {return ""@@ -590,6 +651,68 @@ func runAutopilotRuns(cmd *cobra.Command, args []string) error {return nil}+func runAutopilotTriggerList(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ autopilotRef, err := resolveAutopilotID(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve autopilot: %w", err)+ }++ // The detail endpoint already returns triggers as a top-level sibling of+ // "autopilot"; this command exists so the ids that trigger-update /+ // trigger-delete / trigger-rotate-url require are discoverable without+ // knowing that envelope shape (MUL-6680).+ var resp map[string]any+ if err := client.GetJSON(ctx, "/api/autopilots/"+autopilotRef.ID, &resp); err != nil {+ return fmt.Errorf("get autopilot: %w", err)+ }+ redactAutopilotWebhookCredentials(resp)++ triggersRaw, _ := resp["triggers"].([]any)+ triggers := make([]map[string]any, 0, len(triggersRaw))+ for _, raw := range triggersRaw {+ if t, ok := raw.(map[string]any); ok {+ triggers = append(triggers, t)+ }+ }++ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(os.Stdout, map[string]any{"triggers": triggers, "total": len(triggers)})+ }++ fullID, _ := cmd.Flags().GetBool("full-id")+ headers := []string{"ID", "KIND", "ENABLED", "SCHEDULE", "NEXT_RUN", "LABEL"}+ rows := make([][]string, 0, len(triggers))+ for _, t := range triggers {+ enabled := "no"+ if b, ok := t["enabled"].(bool); ok && b {+ enabled = "yes"+ }+ schedule := strVal(t, "cron_expression")+ if tz := strVal(t, "timezone"); schedule != "" && tz != "" {+ schedule += " (" + tz + ")"+ }+ rows = append(rows, []string{+ displayID(strVal(t, "id"), fullID),+ strVal(t, "kind"),+ enabled,+ schedule,+ relativeTimestamp(strVal(t, "next_run_at")),+ strVal(t, "label"),+ })+ }+ cli.PrintTable(os.Stdout, headers, rows)+ return nil+}+func runAutopilotTriggerAdd(cmd *cobra.Command, args []string) error {client, err := newAPIClient(cmd)if err != nil {diff --git a/server/cmd/multica/cmd_autopilot_test.go b/server/cmd/multica/cmd_autopilot_test.goindex e5a84efbea..593e10f18a 100644--- a/server/cmd/multica/cmd_autopilot_test.go+++ b/server/cmd/multica/cmd_autopilot_test.go@@ -7,6 +7,7 @@ import ("net/http/httptest""strings""testing"+ "time""github.com/spf13/cobra"@@ -729,3 +730,159 @@ func TestUUIDRegexp(t *testing.T) {}}}++func newAutopilotTriggerListTestCmd(output string) *cobra.Command {+ cmd := &cobra.Command{Use: "trigger-list"}+ cmd.Flags().String("output", output, "")+ cmd.Flags().Bool("full-id", false, "")+ return cmd+}++// TestRunAutopilotTriggerListSurfacesIDs covers MUL-6680: the trigger ids that+// trigger-update / trigger-delete / trigger-rotate-url require must be readable+// from a command of their own, not only by knowing that `get --output json`+// returns "triggers" as a sibling of "autopilot".+func TestRunAutopilotTriggerListSurfacesIDs(t *testing.T) {+ const (+ autopilotID = "11111111-1111-1111-1111-111111111111"+ triggerID = "22222222-2222-2222-2222-222222222222"+ )++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/autopilots/"+autopilotID {+ http.NotFound(w, r)+ return+ }+ _ = json.NewEncoder(w).Encode(map[string]any{+ "autopilot": map[string]any{"id": autopilotID, "title": "Deploy"},+ "triggers": []map[string]any{+ {+ "id": triggerID,+ "kind": "schedule",+ "enabled": true,+ "cron_expression": "0 9 * * 1-5",+ "timezone": "America/New_York",+ "label": "weekday morning",+ },+ },+ })+ }))+ defer srv.Close()++ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ // A task-scoped mat_ token so the test also passes inside an agent workdir,+ // where a daemon task marker makes newAPIClient reject a plain token.+ t.Setenv("MULTICA_TOKEN", "mat_test-token")++ out, err := captureStdout(t, func() error {+ return runAutopilotTriggerList(newAutopilotTriggerListTestCmd("table"), []string{autopilotID})+ })+ if err != nil {+ t.Fatalf("runAutopilotTriggerList: %v", err)+ }+ // The short id prefix is what trigger-update accepts, so it must be visible.+ for _, want := range []string{triggerID[:8], "schedule", "0 9 * * 1-5", "weekday morning"} {+ if !strings.Contains(out, want) {+ t.Errorf("table output missing %q:\n%s", want, out)+ }+ }++ out, err = captureStdout(t, func() error {+ return runAutopilotTriggerList(newAutopilotTriggerListTestCmd("json"), []string{autopilotID})+ })+ if err != nil {+ t.Fatalf("runAutopilotTriggerList (json): %v", err)+ }+ var got struct {+ Triggers []map[string]any `json:"triggers"`+ Total int `json:"total"`+ }+ if err := json.Unmarshal([]byte(out), &got); err != nil {+ t.Fatalf("json output is not valid JSON: %v\n%s", err, out)+ }+ if got.Total != 1 || len(got.Triggers) != 1 {+ t.Fatalf("expected exactly one trigger, got total=%d triggers=%v", got.Total, got.Triggers)+ }+ if got.Triggers[0]["id"] != triggerID {+ t.Errorf("id = %#v, want %q", got.Triggers[0]["id"], triggerID)+ }+}++// Webhook triggers carry a URL that grants the ability to fire the autopilot,+// so trigger-list must redact it the same way `get` does.+func TestRunAutopilotTriggerListRedactsWebhookCredentials(t *testing.T) {+ const (+ autopilotID = "11111111-1111-1111-1111-111111111111"+ webhookToken = "awt_super-secret-7890"+ )++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/autopilots/"+autopilotID {+ http.NotFound(w, r)+ return+ }+ _ = json.NewEncoder(w).Encode(map[string]any{+ "autopilot": map[string]any{"id": autopilotID},+ "triggers": []map[string]any{+ {+ "id": "22222222-2222-2222-2222-222222222222",+ "kind": "webhook",+ "enabled": true,+ "webhook_token": webhookToken,+ "webhook_path": "/api/webhooks/autopilots/" + webhookToken,+ "webhook_url": "https://hooks.example.com/api/webhooks/autopilots/" + webhookToken,+ },+ },+ })+ }))+ defer srv.Close()++ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ // A task-scoped mat_ token so the test also passes inside an agent workdir,+ // where a daemon task marker makes newAPIClient reject a plain token.+ t.Setenv("MULTICA_TOKEN", "mat_test-token")++ out, err := captureStdout(t, func() error {+ return runAutopilotTriggerList(newAutopilotTriggerListTestCmd("json"), []string{autopilotID})+ })+ if err != nil {+ t.Fatalf("runAutopilotTriggerList: %v", err)+ }+ if strings.Contains(out, webhookToken) {+ t.Fatalf("trigger-list leaked webhook credential:\n%s", out)+ }+}++func TestRelativeTimestampAt(t *testing.T) {+ now := time.Date(2026, 8, 25, 12, 0, 0, 0, time.UTC)+ at := func(d time.Duration) string {+ return now.Add(d).Format(time.RFC3339)+ }++ cases := []struct {+ name string+ in string+ want string+ }{+ // An autopilot with no schedule must read as visibly different from+ // one that is scheduled — that ambiguity is the MUL-6680 misdiagnosis.+ {"empty", "", "—"},+ {"unparseable", "not-a-timestamp", "—"},+ {"seconds ahead", at(30 * time.Second), "in 30s"},+ {"minutes ahead", at(45 * time.Minute), "in 45m"},+ {"hours ahead", at(2 * time.Hour), "in 2h"},+ {"days ahead", at(72 * time.Hour), "in 3d"},+ {"minutes past", at(-45 * time.Minute), "45m ago"},+ {"hours past", at(-2 * time.Hour), "2h ago"},+ {"days past", at(-72 * time.Hour), "3d ago"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := relativeTimestampAt(tc.in, now); got != tc.want {+ t.Errorf("relativeTimestampAt(%q) = %q, want %q", tc.in, got, tc.want)+ }+ })+ }+}diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex 7d6de02f65..de25909287 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -432,11 +432,40 @@ func (h *Handler) ListAutopilots(w http.ResponseWriter, r *http.Request) {}}+ // Subscribers are fetched for the whole page in one batched query. An+ // earlier version passed nil here to dodge an N+1, but the response type+ // serializes a nil slice as [] rather than omitting it, so every listed+ // autopilot claimed to have no subscribers while the detail endpoint+ // reported the real ones — a silently wrong value is worse than a missing+ // one (MUL-6680). The batch keys off the primary key's leading column, so+ // this costs one indexed query per page, not one per row.+ subsByAutopilot := map[string][]db.AutopilotSubscriber{}+ autopilotIDs := make([]pgtype.UUID, 0, len(autopilots))+ for _, row := range autopilots {+ autopilotIDs = append(autopilotIDs, row.Autopilot.ID)+ }+ if len(autopilotIDs) > 0 {+ subs, err := h.Queries.ListAutopilotSubscribersForAutopilots(r.Context(), autopilotIDs)+ if err != nil {+ // Fail closed. Degrading to an empty set here would reintroduce+ // exactly the bug this endpoint was fixed for: subscribers is a+ // non-omitempty field documented as authoritative, so an empty+ // value on a failed read is indistinguishable from "none+ // configured" — and a caller acting on it can overwrite a real+ // subscriber list. An error the caller can see and retry is the+ // only honest answer.+ writeError(w, http.StatusInternalServerError, "failed to list autopilot subscribers")+ return+ }+ for _, s := range subs {+ id := uuidToString(s.AutopilotID)+ subsByAutopilot[id] = append(subsByAutopilot[id], s)+ }+ }+resp := make([]AutopilotResponse, len(autopilots))for i, row := range autopilots {- // Omit subscribers to avoid an N+1; GET /api/autopilots/{id} is- // the source of truth for the populated template.- r := autopilotToResponse(row.Autopilot, nil)+ r := autopilotToResponse(row.Autopilot, subsByAutopilot[uuidToString(row.Autopilot.ID)])r.TriggerKinds = row.TriggerKindsif row.NextRunAt.Valid {r.NextRunAt = timestampToPtr(row.NextRunAt)@@ -466,8 +495,11 @@ func (h *Handler) GetAutopilot(w http.ResponseWriter, r *http.Request) {subs, err := h.Queries.ListAutopilotSubscribers(r.Context(), autopilot.ID)if err != nil {- // Don't 500 the detail fetch over template metadata.- subs = nil+ // Fail closed for the same reason the list endpoint does: an empty+ // subscribers array is a claim, not an absence, and this response is+ // what clients round-trip back into a full-replace PATCH.+ writeError(w, http.StatusInternalServerError, "failed to list autopilot subscribers")+ return}resp := autopilotToResponse(autopilot, subs)diff --git a/server/internal/handler/autopilot_list_test.go b/server/internal/handler/autopilot_list_test.goindex c8bb6b9e0d..7d1ec3c4f7 100644--- a/server/internal/handler/autopilot_list_test.go+++ b/server/internal/handler/autopilot_list_test.go@@ -4,6 +4,7 @@ import ("context""encoding/json""net/http/httptest"+ "strings""testing")@@ -164,3 +165,149 @@ func TestListAutopilots_DefaultExcludesArchived(t *testing.T) {t.Fatalf("archived autopilot %s missing from status=archived list", archived)}}++// TestListAutopilots_SubscribersMatchDetail is the regression guard for+// MUL-6680: GET /api/autopilots used to hard-code an empty subscriber slice to+// avoid an N+1, which serialized as "subscribers": [] on every row. The key was+// present and looked authoritative, so callers could not tell "no subscribers"+// from "not fetched" — and the detail endpoint reported something different for+// the very same autopilot. The two projections must now agree.+func TestListAutopilots_SubscribersMatchDetail(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ agentID := createHandlerTestAgent(t, "autopilot-list-subs-agent", []byte(`[]`))+ withSubs := insertListTestAutopilot(t, agentID, "list-subs-populated")+ withoutSubs := insertListTestAutopilot(t, agentID, "list-subs-empty")++ if _, err := testPool.Exec(ctx, `+ INSERT INTO autopilot_subscriber (autopilot_id, user_type, user_id)+ VALUES ($1, 'member', $2)+ `, withSubs, testUserID); err != nil {+ t.Fatalf("insert subscriber fixture: %v", err)+ }++ // list+ w := httptest.NewRecorder()+ testHandler.ListAutopilots(w, newRequest("GET", "/api/autopilots", nil))+ if w.Code != 200 {+ t.Fatalf("ListAutopilots: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var listBody struct {+ Autopilots []map[string]any `json:"autopilots"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &listBody); err != nil {+ t.Fatalf("failed to decode list body: %v", err)+ }+ listRows := make(map[string]map[string]any)+ for _, row := range listBody.Autopilots {+ listRows[row["id"].(string)] = row+ }++ // detail, for the same autopilot at the same moment+ w = httptest.NewRecorder()+ testHandler.GetAutopilot(w, withURLParam(+ newRequest("GET", "/api/autopilots/"+withSubs+"?workspace_id="+testWorkspaceID, nil), "id", withSubs))+ if w.Code != 200 {+ t.Fatalf("GetAutopilot: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var detailBody struct {+ Autopilot map[string]any `json:"autopilot"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &detailBody); err != nil {+ t.Fatalf("failed to decode detail body: %v", err)+ }++ fromList, _ := listRows[withSubs]["subscribers"].([]any)+ fromDetail, _ := detailBody.Autopilot["subscribers"].([]any)+ if len(fromDetail) != 1 {+ t.Fatalf("detail subscribers: expected the seeded member, got %v", detailBody.Autopilot["subscribers"])+ }+ if len(fromList) != len(fromDetail) {+ t.Errorf("list/detail disagree on subscribers: list=%v detail=%v", fromList, fromDetail)+ }+ if len(fromList) == 1 {+ got, _ := fromList[0].(map[string]any)+ if got["user_id"] != testUserID {+ t.Errorf("list subscriber user_id: expected %s, got %v", testUserID, got["user_id"])+ }+ }++ // An autopilot with genuinely no subscribers must still serialize the key+ // as [] rather than omitting it — the field's documented contract, which+ // only becomes trustworthy now that it is populated.+ empty, ok := listRows[withoutSubs]["subscribers"]+ if !ok {+ t.Errorf("subscribers key must be present even when empty")+ } else if entries, _ := empty.([]any); len(entries) != 0 {+ t.Errorf("expected empty subscribers for %s, got %v", withoutSubs, empty)+ }+}++// hideAutopilotSubscriberTable makes reads of autopilot_subscriber fail for the+// duration of one test, so the subscriber query's error branch can be exercised+// while the autopilot query itself still succeeds. A rename isolates the+// failure to exactly that one query; t.Cleanup restores it. Safe to run+// alongside the rest of the suite because non-parallel tests in a package run+// sequentially, and no parallel test in this package touches this table.+func hideAutopilotSubscriberTable(t *testing.T) {+ t.Helper()+ ctx := context.Background()+ if _, err := testPool.Exec(ctx, `ALTER TABLE autopilot_subscriber RENAME TO autopilot_subscriber_hidden`); err != nil {+ t.Fatalf("hide autopilot_subscriber: %v", err)+ }+ t.Cleanup(func() {+ if _, err := testPool.Exec(ctx, `ALTER TABLE autopilot_subscriber_hidden RENAME TO autopilot_subscriber`); err != nil {+ t.Fatalf("restore autopilot_subscriber: %v", err)+ }+ })+}++// TestAutopilotSubscriberReadFailureFailsClosed guards the error path of the+// MUL-6680 fix. "subscribers" has no omitempty and is documented as+// authoritative, so degrading a failed read to an empty array would recreate+// the very defect this change removes: the caller cannot tell "none+// configured" from "read failed", and a client that round-trips the response+// into a full-replace PATCH would silently wipe a real subscriber list. Both+// projections must surface the error instead.+func TestAutopilotSubscriberReadFailureFailsClosed(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ agentID := createHandlerTestAgent(t, "autopilot-subs-failclosed-agent", []byte(`[]`))+ apID := insertListTestAutopilot(t, agentID, "list-subs-fail-closed")+ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO autopilot_subscriber (autopilot_id, user_type, user_id)+ VALUES ($1, 'member', $2)+ `, apID, testUserID); err != nil {+ t.Fatalf("insert subscriber fixture: %v", err)+ }++ hideAutopilotSubscriberTable(t)++ t.Run("list", func(t *testing.T) {+ w := httptest.NewRecorder()+ testHandler.ListAutopilots(w, newRequest("GET", "/api/autopilots", nil))+ if w.Code != 500 {+ t.Fatalf("expected 500 when the subscriber read fails, got %d: %s", w.Code, w.Body.String())+ }+ if strings.Contains(w.Body.String(), `"subscribers":[]`) {+ t.Errorf("response must not carry an authoritative empty subscriber list: %s", w.Body.String())+ }+ })++ t.Run("detail", func(t *testing.T) {+ w := httptest.NewRecorder()+ testHandler.GetAutopilot(w, withURLParam(+ newRequest("GET", "/api/autopilots/"+apID+"?workspace_id="+testWorkspaceID, nil), "id", apID))+ if w.Code != 500 {+ t.Fatalf("expected 500 when the subscriber read fails, got %d: %s", w.Code, w.Body.String())+ }+ if strings.Contains(w.Body.String(), `"subscribers":[]`) {+ t.Errorf("response must not carry an authoritative empty subscriber list: %s", w.Body.String())+ }+ })+}diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 3cc7eb491d..74ba595a52 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -1264,6 +1264,48 @@ func (q *Queries) ListAutopilotSubscribers(ctx context.Context, autopilotID pgtyreturn items, nil}+const listAutopilotSubscribersForAutopilots = `-- name: ListAutopilotSubscribersForAutopilots :many+SELECT s.autopilot_id, s.user_type, s.user_id, s.created_at FROM autopilot_subscriber AS s+JOIN autopilot AS a ON a.id = s.autopilot_id+JOIN member AS m+ ON m.workspace_id = a.workspace_id+ AND m.user_id = s.user_id+WHERE s.autopilot_id = ANY($1::uuid[])+ AND s.user_type = 'member'+ORDER BY s.autopilot_id ASC, s.created_at ASC, s.user_id ASC+`++// Batch form of ListAutopilotSubscribers for the list endpoint, which must not+// issue one query per row. The autopilot_subscriber primary key leads with+// autopilot_id, so ANY($1) is index-supported and no extra index is needed.+// The member join and ordering are identical to the single-autopilot query on+// purpose: list and detail have to agree on who counts as a subscriber, or the+// two projections disagree again (MUL-6680).+func (q *Queries) ListAutopilotSubscribersForAutopilots(ctx context.Context, dollar_1 []pgtype.UUID) ([]AutopilotSubscriber, error) {+ rows, err := q.db.Query(ctx, listAutopilotSubscribersForAutopilots, dollar_1)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AutopilotSubscriber{}+ for rows.Next() {+ var i AutopilotSubscriber+ if err := rows.Scan(+ &i.AutopilotID,+ &i.UserType,+ &i.UserID,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listAutopilotTriggers = `-- name: ListAutopilotTriggers :manySELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret, event_filters, published_by_type, published_by_id FROM autopilot_triggerdiff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex 29b715bc70..3086a544ae 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -712,6 +712,22 @@ WHERE s.autopilot_id = $1AND s.user_type = 'member'ORDER BY s.created_at ASC, s.user_id ASC;+-- name: ListAutopilotSubscribersForAutopilots :many+-- Batch form of ListAutopilotSubscribers for the list endpoint, which must not+-- issue one query per row. The autopilot_subscriber primary key leads with+-- autopilot_id, so ANY($1) is index-supported and no extra index is needed.+-- The member join and ordering are identical to the single-autopilot query on+-- purpose: list and detail have to agree on who counts as a subscriber, or the+-- two projections disagree again (MUL-6680).+SELECT s.* FROM autopilot_subscriber AS s+JOIN autopilot AS a ON a.id = s.autopilot_id+JOIN member AS m+ ON m.workspace_id = a.workspace_id+ AND m.user_id = s.user_id+WHERE s.autopilot_id = ANY($1::uuid[])+ AND s.user_type = 'member'+ORDER BY s.autopilot_id ASC, s.created_at ASC, s.user_id ASC;+-- name: AddAutopilotSubscriber :execINSERT INTO autopilot_subscriber (autopilot_id, user_type, user_id)VALUES ($1, $2, $3)