Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8992: fix(server): keep background runs and workspace-wide reads inside private projects (#10329)

pseudoyuc3a9d8fd1e46
diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.go
index 5bf71e4b3d..da71e49129 100644
--- a/server/cmd/server/listeners.go
+++ b/server/cmd/server/listeners.go
@@ -86,6 +86,9 @@ func isChatPrivateEvent(e events.Event) bool {
// MemberPrivateUserID is dropped instead of reaching the workspace.
var memberPrivateEvents = map[string]bool{
protocol.EventIssueViewPreferenceChanged: true,
+ protocol.EventPinCreated: true,
+ protocol.EventPinDeleted: true,
+ protocol.EventPinReordered: true,
}
// registerListeners wires up event bus listeners for WS broadcasting.
diff --git a/server/cmd/server/listeners_scope_test.go b/server/cmd/server/listeners_scope_test.go
index b751d71791..add8bf8d32 100644
--- a/server/cmd/server/listeners_scope_test.go
+++ b/server/cmd/server/listeners_scope_test.go
@@ -274,8 +274,35 @@ func TestRegisterListeners_ChatRoutingKeepsInProcessListeners(t *testing.T) {
}
}
+// A pin is one member's own in every workspace, with or without a private
+// project: one published without its member reaches nobody.
+func TestRegisterListeners_PinEventsWithoutMemberAreDropped(t *testing.T) {
+ for _, eventType := range []string{protocol.EventPinCreated, protocol.EventPinDeleted, protocol.EventPinReordered} {
+ t.Run(eventType, func(t *testing.T) {
+ bus := events.New()
+ fb := &fakeBroadcaster{}
+ registerListeners(bus, fb)
+
+ bus.Publish(events.Event{
+ Type: eventType, WorkspaceID: "ws-1", ActorType: "member", ActorID: "owner-1",
+ Payload: map[string]any{"item_type": "issue", "item_id": "issue-1"},
+ })
+
+ fb.mu.Lock()
+ defer fb.mu.Unlock()
+ if len(fb.workspaceCalls) != 0 || len(fb.scopeCalls) != 0 || len(fb.userCalls) != 0 || fb.broadcastCalled != 0 {
+ t.Fatalf("pin event was delivered: workspace=%+v scope=%+v user=%+v broadcast=%d",
+ fb.workspaceCalls, fb.scopeCalls, fb.userCalls, fb.broadcastCalled)
+ }
+ })
+ }
+}
+
func TestRegisterListeners_MemberPrivateEventsGoOnlyToThatMember(t *testing.T) {
- for _, eventType := range []string{protocol.EventIssueViewPreferenceChanged, protocol.EventIssueViewChanged} {
+ for _, eventType := range []string{
+ protocol.EventIssueViewPreferenceChanged, protocol.EventIssueViewChanged,
+ protocol.EventPinCreated, protocol.EventPinDeleted, protocol.EventPinReordered,
+ } {
t.Run(eventType, func(t *testing.T) {
bus := events.New()
fb := &fakeBroadcaster{}
diff --git a/server/cmd/server/private_project_aggregate_realtime_test.go b/server/cmd/server/private_project_aggregate_realtime_test.go
new file mode 100644
index 0000000000..b6d673e65a
--- /dev/null
+++ b/server/cmd/server/private_project_aggregate_realtime_test.go
@@ -0,0 +1,77 @@
+package main
+
+import (
+ "sort"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/realtime"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func publishPrivateAudience(e events.Event) *fakeBroadcaster {
+ bus := events.New()
+ fb := &fakeBroadcaster{}
+ registerListeners(bus, fb, newPrivateProjectAudience(fakeAudienceQuerier{}))
+ e.WorkspaceID = ppWorkspace
+ bus.Publish(e)
+ return fb
+}
+
+func memberScopes(userIDs ...string) []string {
+ out := make([]string, 0, len(userIDs))
+ for _, id := range userIDs {
+ out = append(out, realtime.WorkspaceMemberScopeID(ppWorkspace, id))
+ }
+ sort.Strings(out)
+ return out
+}
+
+func sameScopes(a, b []string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if a[i] != b[i] {
+ return false
+ }
+ }
+ return true
+}
+
+// Deleted private issues and pull requests linked to private issues
+// (MUL-8472) used to keep workspace fanout, handing their ids to members
+// outside the project.
+func TestRegisterListeners_PrivateProjectAggregateEvents(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ e events.Event
+ want []string
+ }{
+ {"deleted private issue", events.Event{Type: protocol.EventIssueDeleted,
+ Payload: map[string]any{"issue_id": "00000000-0000-0000-0000-00000000dead", "project_id": ppPrivate}}, memberScopes(ppMember, ppAdmin)},
+ {"pull request linked to a private and a public issue", events.Event{Type: protocol.EventPullRequestUpdated,
+ Payload: map[string]any{"pull_request": map[string]any{"id": "pr"}, "linked_issue_ids": []string{ppPublicIssue, ppSecretIssue}}}, memberScopes(ppMember, ppAdmin)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fb := publishPrivateAudience(tc.e)
+ if len(fb.workspaceCalls) != 0 {
+ t.Fatal("broadcast to the whole workspace")
+ }
+ if got := privateAudienceScopes(fb); !sameScopes(got, tc.want) {
+ t.Fatalf("delivered to %v, want %v", got, tc.want)
+ }
+ })
+ }
+
+ // Controls: nothing private involved keeps workspace fanout.
+ for _, e := range []events.Event{
+ {Type: protocol.EventIssueDeleted, Payload: map[string]any{"issue_id": "00000000-0000-0000-0000-00000000dead", "project_id": nil}},
+ {Type: protocol.EventPullRequestUpdated, Payload: map[string]any{"pull_request": map[string]any{"id": "pr"}, "linked_issue_ids": []string{ppPublicIssue}}},
+ {Type: protocol.EventPullRequestUpdated, Payload: map[string]any{"pull_request": map[string]any{"id": "pr"}, "linked_issue_ids": []string{}}},
+ } {
+ if fb := publishPrivateAudience(e); len(fb.workspaceCalls) != 1 {
+ t.Errorf("%s %v: workspace broadcasts = %d, want 1", e.Type, e.Payload, len(fb.workspaceCalls))
+ }
+ }
+}
diff --git a/server/cmd/server/private_project_realtime.go b/server/cmd/server/private_project_realtime.go
index eaf90123f0..1e1710b8fe 100644
--- a/server/cmd/server/private_project_realtime.go
+++ b/server/cmd/server/private_project_realtime.go
@@ -132,7 +132,8 @@ func (a *dbPrivateProjectAudience) Audience(ctx context.Context, e events.Event)
return nil, false, err
}
// A run can read more than one project (a quick-create into one project
- // under a parent in another); only members of every private one may see it.
+ // under a parent in another), and a pull request can be linked to issues in
+ // several; only members of every private one may see it.
var members []string
private := false
for _, projectID := range projectIDs {
@@ -218,7 +219,8 @@ func (a *dbPrivateProjectAudience) workspace(ctx context.Context, workspaceID st
// eventProjectIDs resolves the projects an event is about, or none. It reads
// the payload's own references first and only falls back to the database for
-// a bare issue, comment, autopilot or task id.
+// a bare issue, comment, autopilot or task id, or the issues a pull request is
+// linked to.
func (a *dbPrivateProjectAudience) eventProjectIDs(ctx context.Context, e events.Event) ([]string, error) {
refs := extractEventRefs(e.Type, e.Payload)
if refs.projectKnown {
@@ -244,6 +246,17 @@ func (a *dbPrivateProjectAudience) eventProjectIDs(ctx context.Context, e events
if refs.commentID != "" {
return lookup(refs.commentID, a.q.GetCommentIssueProjectID)
}
+ if len(refs.linkedIssueIDs) > 0 {
+ var out []string
+ for _, id := range refs.linkedIssueIDs {
+ projects, err := lookup(id, a.q.GetIssueProjectID)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, projects...)
+ }
+ return out, nil
+ }
if refs.autopilotID != "" {
return lookup(refs.autopilotID, func(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
ap, err := a.q.GetAutopilot(ctx, id)
@@ -322,6 +335,8 @@ type eventRefs struct {
issueID string
commentID string
autopilotID string
+ // linkedIssueIDs are the issues a pull_request:updated event names.
+ linkedIssueIDs []string
}
// extractEventRefs reads project / issue / comment references from an event
@@ -366,7 +381,8 @@ func extractEventRefs(eventType string, payload any) eventRefs {
}
}
}
- if id, ok := str(top, "project_id"); ok && id != "" && (isProjectEvent || eventType == protocol.EventProjectMembersChanged) {
+ // A deleted issue states its project, since its row is gone by now.
+ if id, ok := str(top, "project_id"); ok && id != "" && (isProjectEvent || eventType == protocol.EventProjectMembersChanged || eventType == protocol.EventIssueDeleted) {
return eventRefs{projectKnown: true, projectID: id}
}
// An autopilot bound to a private project carries its prompt and runs.
@@ -407,6 +423,11 @@ func extractEventRefs(eventType string, payload any) eventRefs {
refs.commentID = id
}
}
+ if refs.issueID == "" && refs.commentID == "" {
+ if v, ok := top["linked_issue_ids"]; ok {
+ _ = json.Unmarshal(v, &refs.linkedIssueIDs)
+ }
+ }
return refs
}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 0e7d94c3a1..f38212000d 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -30,6 +30,7 @@ import (
"github.com/multica-ai/multica/server/internal/logger"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/runtimeapps"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
@@ -95,6 +96,18 @@ func (h *Handler) requireDaemonWorkspaceAccess(w http.ResponseWriter, r *http.Re
return ok
}
+// daemonHiddenProjects is requestHiddenProjects for daemon routes (MUL-8472).
+// A daemon token sees every project: a shared runtime runs private-project
+// tasks its owner cannot see, holds their workdirs, and must keep reading
+// their lifecycle, or GC treats a live workdir as an orphan. A member's own
+// credential on these routes is bounded by the member, as on any other route.
+func (h *Handler) daemonHiddenProjects(w http.ResponseWriter, r *http.Request, workspaceID string) (projectaccess.Hidden, bool) {
+ if middleware.DaemonWorkspaceIDFromContext(r.Context()) != "" {
+ return projectaccess.Hidden{}, true
+ }
+ return h.requestHiddenProjects(w, r, workspaceID)
+}
+
// daemonRuntimeBindingAllowed is the runtime-level half of daemon
// authorization (MUL-8154). Workspace access alone is not enough: every
// member of a workspace can reach /api/daemon/* with their own PAT/JWT, and
@@ -3675,7 +3688,11 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
resp.ChatNoticeLocale = h.qoderChatNoticeLocale(r.Context(), runtime, *task, cs, resp.ChatChannelType, resp.ChatType)
// A web chat can opt into the same durable project context as an
// issue-bound task.
- projectCtx, projectErr := h.resolveClaimProjectContext(r.Context(), cs.ProjectID, cs.WorkspaceID)
+ chatProjectID, projectErr := h.chatRunProjectID(r.Context(), cs, *task, agent.OwnerID)
+ var projectCtx claimProjectContext
+ if projectErr == nil {
+ projectCtx, projectErr = h.resolveClaimProjectContext(r.Context(), chatProjectID, cs.WorkspaceID)
+ }
if projectErr != nil {
slog.Error("chat claim: load project context failed; preserving task for redelivery",
"task_id", uuidToString(task.ID),
@@ -6827,6 +6844,28 @@ func (h *Handler) BatchIssueGCCheck(w http.ResponseWriter, r *http.Request) {
rows[uuidToString(row.ID)] = row
}
}
+ if len(rows) > 0 {
+ hidden, ok := h.daemonHiddenProjects(w, r, workspaceID)
+ if !ok {
+ return
+ }
+ if !hidden.Empty() {
+ foundIDs := make([]pgtype.UUID, 0, len(rows))
+ for _, row := range rows {
+ foundIDs = append(foundIDs, row.ID)
+ }
+ projects, err := h.Queries.ListIssueProjectIDs(r.Context(), foundIDs)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to resolve project access")
+ return
+ }
+ for _, p := range projects {
+ if !hidden.CanSeeProject(p.ProjectID) {
+ delete(rows, uuidToString(p.ID))
+ }
+ }
+ }
+ }
// ONE resolver for the whole batch, not a point lookup per row. The
// package-level helpers issue a GetIssueStatusEntryByKey for every custom
@@ -6873,6 +6912,21 @@ func (h *Handler) GetIssueGCCheck(w http.ResponseWriter, r *http.Request) {
if !h.requireDaemonWorkspaceAccess(w, r, uuidToString(issue.WorkspaceID)) {
return
}
+ hidden, ok := h.daemonHiddenProjects(w, r, uuidToString(issue.WorkspaceID))
+ if !ok {
+ return
+ }
+ if !hidden.Empty() {
+ projectID, err := h.Queries.GetIssueProjectID(r.Context(), issueUUID)
+ if errors.Is(err, pgx.ErrNoRows) || (err == nil && !hidden.CanSeeProject(projectID)) {
+ writeError(w, http.StatusNotFound, "issue not found")
+ return
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to resolve project access")
+ return
+ }
+ }
// Same reasoning as BatchIssueGCCheck: normalize server-side so the
// daemon's terminal-status test stays correct. (MUL-6243)
status, category := issueGCWire(issue.Status,
diff --git a/server/internal/handler/dashboard.go b/server/internal/handler/dashboard.go
index d75f106dff..091bec1fef 100644
--- a/server/internal/handler/dashboard.go
+++ b/server/internal/handler/dashboard.go
@@ -41,7 +41,9 @@ import (
// failures/daily) carry no agent dimension and need workspace membership only —
// token spend / run time / failure volume are workspace-level operational
// metrics. The three per-AGENT rollups additionally apply per-agent visibility:
-// see foldRestrictedAgents.
+// see foldRestrictedAgents. Runs in private projects (MUL-8472) stay in all six
+// workspace totals, which never shrink for a viewer; only the project_id filter
+// refuses a project the viewer cannot see (dashboardProjectVisible).
// restrictedAgentsRowID is the synthetic agent_id that every row this response
// refuses to name is folded onto. Deliberately not a UUID, so it can never
@@ -145,6 +147,21 @@ func parseProjectIDParam(w http.ResponseWriter, r *http.Request) (pgtype.UUID, b
return u, true
}
+// dashboardProjectVisible guards the project_id filter: a private project
+// (MUL-8472) the request may not see is answered like one that does not exist,
+// with an empty rollup, and false.
+func (h *Handler) dashboardProjectVisible(w http.ResponseWriter, r *http.Request, workspaceID string, projectID pgtype.UUID) bool {
+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)
+ if !ok {
+ return false
+ }
+ if !hidden.CanSeeProject(projectID) {
+ writeJSON(w, http.StatusOK, []struct{}{})
+ return false
+ }
+ return true
+}
+
// DashboardUsageDailyResponse is one (date, provider, model) bucket. Cost-side
// math happens on the client from a per-model pricing table; provider + model
// stay on the wire so the client can disambiguate bare model ids that collide
@@ -182,6 +199,9 @@ func (h *Handler) GetDashboardUsageDaily(w http.ResponseWriter, r *http.Request)
if !ok {
return
}
+ if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {
+ return
+ }
tz := h.resolveViewingTZ(r)
since := parseSinceParamInTZ(r, 30, tz)
@@ -267,6 +287,9 @@ func (h *Handler) GetDashboardUsageByAgent(w http.ResponseWriter, r *http.Reques
if !ok {
return
}
+ if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {
+ return
+ }
restricted, ok := h.dashboardRestrictedAgents(w, r, workspaceID, member.Role)
if !ok {
return
@@ -389,6 +412,9 @@ func (h *Handler) GetDashboardAgentRunTime(w http.ResponseWriter, r *http.Reques
if !ok {
return
}
+ if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {
+ return
+ }
restricted, ok := h.dashboardRestrictedAgents(w, r, workspaceID, member.Role)
if !ok {
return
@@ -478,6 +504,9 @@ func (h *Handler) GetDashboardRunTimeDaily(w http.ResponseWriter, r *http.Reques
if !ok {
return
}
+ if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {
+ return
+ }
// Slice day buckets in the viewer's tz so the Time / Tasks charts cut
// their calendar day identically to the Cost / Tokens charts.
tz := h.resolveViewingTZ(r)
@@ -543,6 +572,9 @@ func (h *Handler) GetDashboardFailuresDaily(w http.ResponseWriter, r *http.Reque
if !ok {
return
}
+ if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {
+ return
+ }
// Same viewer-tz day boundary as every other daily series so the Errors
// tab lines up with Cost / Tokens / Time / Tasks.
tz := h.resolveViewingTZ(r)
@@ -591,6 +623,9 @@ func (h *Handler) GetDashboardFailuresByAgent(w http.ResponseWriter, r *http.Req
if !ok {
return
}
+ if !h.dashboardProjectVisible(w, r, workspaceID, projectID) {
+ return
+ }
restricted, ok := h.dashboardRestrictedAgents(w, r, workspaceID, member.Role)
if !ok {
return
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 51ca0d85de..7c4a1cf6c5 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -4633,7 +4633,9 @@ func (h *Handler) DeleteIssue(w http.ResponseWriter, r *http.Request) {
// identifier-style payload ("MUL-123") would leave stale entries on
// other clients after an identifier-path delete.
resolvedID := uuidToString(issue.ID)
- h.publish(protocol.EventIssueDeleted, uuidToString(issue.WorkspaceID), actorType, actorID, map[string]any{"issue_id": resolvedID})
+ // project_id lets the realtime audience narrow the event: the row is gone
+ // by the time it is resolved.
+ h.publish(protocol.EventIssueDeleted, uuidToString(issue.WorkspaceID), actorType, actorID, map[string]any{"issue_id": resolvedID, "project_id": uuidToPtr(issue.ProjectID)})
h.publishIssueSnapshots(r.Context(), deleteResult.DetachedChildren, actorType, actorID)
h.publishClearedDuplicates(r.Context(), deleteResult.ClearedDuplicates, actorType, actorID)
slog.Info("issue deleted", append(logger.RequestAttrs(r), "issue_id", resolvedID, "workspace_id", uuidToString(issue.WorkspaceID))...)
@@ -5249,7 +5251,7 @@ func (h *Handler) BatchDeleteIssues(w http.ResponseWriter, r *http.Request) {
h.deleteS3Objects(r.Context(), deleteResult.AttachmentURLs)
actorType, actorID := h.resolveActor(r, userID, workspaceID)
for _, issue := range issues {
- h.publish(protocol.EventIssueDeleted, workspaceID, actorType, actorID, map[string]any{"issue_id": uuidToString(issue.ID)})
+ h.publish(protocol.EventIssueDeleted, workspaceID, actorType, actorID, map[string]any{"issue_id": uuidToString(issue.ID), "project_id": uuidToPtr(issue.ProjectID)})
}
h.publishIssueSnapshots(r.Context(), deleteResult.DetachedChildren, actorType, actorID)
h.publishClearedDuplicates(r.Context(), deleteResult.ClearedDuplicates, actorType, actorID)
diff --git a/server/internal/handler/issue_workflow.go b/server/internal/handler/issue_workflow.go
index 561e4a0604..a507ac2950 100644
--- a/server/internal/handler/issue_workflow.go
+++ b/server/internal/handler/issue_workflow.go
@@ -18,6 +18,7 @@ import (
"github.com/multica-ai/multica/server/internal/issuestatus"
"github.com/multica-ai/multica/server/internal/issueworkflow"
"github.com/multica-ai/multica/server/internal/logger"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
"github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -151,7 +152,8 @@ func issueWorkflowToResponse(row db.IssueWorkflow, def issueworkflow.Definition,
// projectIDsByWorkflow groups the workspace's projects by the workflow row
// they use, so a list response can say where each workflow applies. Projects
// without a workflow, or pointing at a deleted one, count for Default.
-func (h *Handler) projectIDsByWorkflow(ctx context.Context, wsUUID pgtype.UUID, rows []db.IssueWorkflow) (map[string][]string, error) {
+// Projects the caller may not see (visible returns false) are left out.
+func (h *Handler) projectIDsByWorkflow(ctx context.Context, wsUUID pgtype.UUID, rows []db.IssueWorkflow, visible func(db.Project) bool) (map[string][]string, error) {
projects, err := h.Queries.ListProjects(ctx, db.ListProjectsParams{WorkspaceID: wsUUID})
if err != nil {
return nil, err
@@ -167,6 +169,9 @@ func (h *Handler) projectIDsByWorkflow(ctx context.Context, wsUUID pgtype.UUID,
}
out := map[string][]string{}
for _, p := range projects {
+ if !visible(p) {
+ continue
+ }
key := uuidToString(p.WorkflowID)
if !p.WorkflowID.Valid || !known[key] {
key = defaultID
@@ -224,7 +229,11 @@ func (h *Handler) ListIssueWorkflows(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to list workflows")
return
}
- byWorkflow, err := h.projectIDsByWorkflow(r.Context(), wsUUID, rows)
+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)
+ if !ok {
+ return
+ }
+ byWorkflow, err := h.projectIDsByWorkflow(r.Context(), wsUUID, rows, func(p db.Project) bool { return hidden.CanSeeProject(p.ID) })
if err != nil {
slog.Warn("ListIssueWorkflows projects failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to list workflows")
@@ -264,10 +273,16 @@ func (h *Handler) GetIssueWorkflow(w http.ResponseWriter, r *http.Request) {
}
func (h *Handler) writeIssueWorkflow(w http.ResponseWriter, r *http.Request, status int, row db.IssueWorkflow) {
- writeJSON(w, status, h.issueWorkflowResponse(r.Context(), row))
+ // Writes reach here after committing, so a failed access lookup lists no
+ // private project rather than failing the response.
+ visible := func(p db.Project) bool { return p.Visibility != projectaccess.VisibilityPrivate }
+ if hidden, err := h.hiddenProjects(r, uuidToString(row.WorkspaceID)); err == nil {
+ visible = func(p db.Project) bool { return hidden.CanSeeProject(p.ID) }
+ }
+ writeJSON(w, status, h.issueWorkflowResponse(r.Context(), row, visible))
}
-func (h *Handler) issueWorkflowResponse(ctx context.Context, row db.IssueWorkflow) IssueWorkflowResponse {
+func (h *Handler) issueWorkflowResponse(ctx context.Context, row db.IssueWorkflow, visible func(db.Project) bool) IssueWorkflowResponse {
def, err := issueworkflow.Decode(row)
if err != nil {
def = issueworkflow.Definition{}
@@ -276,7 +291,7 @@ func (h *Handler) issueWorkflowResponse(ctx context.Context, row db.IssueWorkflo
if err != nil {
rows = []db.IssueWorkflow{row}
}
- byWorkflow, err := h.projectIDsByWorkflow(ctx, row.WorkspaceID, rows)
+ byWorkflow, err := h.projectIDsByWorkflow(ctx, row.WorkspaceID, rows, visible)
if err != nil {
byWorkflow = map[string][]string{}
}
@@ -1296,7 +1311,12 @@ func (h *Handler) PreviewIssueWorkflowBrief(w http.ResponseWriter, r *http.Reque
projectName := ""
if req.ProjectID != "" {
if id, err := parseUUIDString(req.ProjectID); err == nil {
- if p, err := h.Queries.GetProjectInWorkspace(ctx, db.GetProjectInWorkspaceParams{ID: id, WorkspaceID: wsUUID}); err == nil {
+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)
+ if !ok {
+ return
+ }
+ // A project the caller may not see is previewed like an unknown one.
+ if p, err := h.Queries.GetProjectInWorkspace(ctx, db.GetProjectInWorkspaceParams{ID: id, WorkspaceID: wsUUID}); err == nil && hidden.CanSeeProject(p.ID) {
projectName = p.Title
}
}
diff --git a/server/internal/handler/pin.go b/server/internal/handler/pin.go
index 3c5cc5b9e8..0c9da7534a 100644
--- a/server/internal/handler/pin.go
+++ b/server/internal/handler/pin.go
@@ -9,6 +9,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
+ "github.com/multica-ai/multica/server/internal/events"
"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/protocol"
@@ -191,7 +192,7 @@ func (h *Handler) CreatePin(w http.ResponseWriter, r *http.Request) {
}
resp := pinnedItemToResponse(pin)
- h.publish(protocol.EventPinCreated, workspaceID, "member", userID, map[string]any{"pin": resp})
+ h.publishPin(protocol.EventPinCreated, workspaceID, userID, map[string]any{"pin": resp})
writeJSON(w, http.StatusCreated, resp)
}
@@ -224,7 +225,7 @@ func (h *Handler) DeletePin(w http.ResponseWriter, r *http.Request) {
return
}
- h.publish(protocol.EventPinDeleted, workspaceID, "member", userID, map[string]any{
+ h.publishPin(protocol.EventPinDeleted, workspaceID, userID, map[string]any{
"item_type": itemType,
"item_id": itemID,
})
@@ -268,7 +269,7 @@ func (h *Handler) ReorderPins(w http.ResponseWriter, r *http.Request) {
// Fan out so other sessions (web/desktop, or a second tab) refetch
// the pin list and pick up the new order. Without this, reorder is
// only consistent on the originating client until a hard refresh.
- h.publish(protocol.EventPinReordered, workspaceID, "member", userID, map[string]any{"items": req.Items})
+ h.publishPin(protocol.EventPinReordered, workspaceID, userID, map[string]any{"items": req.Items})
w.WriteHeader(http.StatusNoContent)
}
@@ -289,3 +290,16 @@ func (h *Handler) pinVisible(r *http.Request, hidden projectaccess.Hidden, pin d
return true
}
}
+
+// publishPin sends a pin event to its member's own sessions only: a pin is
+// that member's, and its item id may name a private project or issue.
+func (h *Handler) publishPin(eventType, workspaceID, userID string, payload any) {
+ h.Bus.Publish(events.Event{
+ Type: eventType,
+ WorkspaceID: workspaceID,
+ ActorType: "member",
+ ActorID: userID,
+ MemberPrivateUserID: userID,
+ Payload: payload,
+ })
+}
diff --git a/server/internal/handler/pin_realtime_test.go b/server/internal/handler/pin_realtime_test.go
new file mode 100644
index 0000000000..9451f4b610
--- /dev/null
+++ b/server/internal/handler/pin_realtime_test.go
@@ -0,0 +1,42 @@
+package handler
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Pins belong to one member, so every pin event is published private to them.
+func TestPinEventsArePrivateToTheirMember(t *testing.T) {
+ h := *testHandler
+ h.Bus = events.New()
+ var got []events.Event
+ for _, eventType := range []string{protocol.EventPinCreated, protocol.EventPinReordered, protocol.EventPinDeleted} {
+ h.Bus.Subscribe(eventType, func(e events.Event) { got = append(got, e) })
+ }
+ issueID := dbfx.Issue(t, "Pinned for one member")
+ dbfx.Cleanup(t, `DELETE FROM pinned_item WHERE item_id = $1`, issueID)
+
+ var pin PinnedItemResponse
+ testutil.Call(t, h.CreatePin, newRequest(http.MethodPost, "/api/pins", map[string]any{"item_type": "issue", "item_id": issueID})).
+ Want(http.StatusCreated).JSON(&pin)
+ testutil.Call(t, h.ReorderPins, newRequest(http.MethodPut, "/api/pins/reorder", map[string]any{
+ "items": []map[string]any{{"id": pin.ID, "position": 1}},
+ })).Want(http.StatusNoContent)
+ testutil.Call(t, h.DeletePin, withURLParams(newRequest(http.MethodDelete, "/api/pins/issue/"+issueID, nil), "itemType", "issue", "itemId", issueID)).
+ Want(http.StatusNoContent)
+
+ want := []string{protocol.EventPinCreated, protocol.EventPinReordered, protocol.EventPinDeleted}
+ if len(got) != len(want) {
+ t.Fatalf("published %d events, want %d: %+v", len(got), len(want), got)
+ }
+ for i, e := range got {
+ if e.Type != want[i] || e.WorkspaceID != testWorkspaceID || e.ActorID != testUserID || e.MemberPrivateUserID != testUserID {
+ t.Fatalf("event %d = type %q workspace %q actor %q private to %q, want %q private to %q",
+ i, e.Type, e.WorkspaceID, e.ActorID, e.MemberPrivateUserID, want[i], testUserID)
+ }
+ }
+}
diff --git a/server/internal/handler/private_project_aggregates_test.go b/server/internal/handler/private_project_aggregates_test.go
new file mode 100644
index 0000000000..1603042218
--- /dev/null
+++ b/server/internal/handler/private_project_aggregates_test.go
@@ -0,0 +1,187 @@
+package handler
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// Aggregates over many issues (MUL-8472) must count a private project only for
+// viewers who can see it, and must answer a hidden project_id exactly like a
+// project that does not exist. Dashboard totals are the exception: they are
+// the workspace's spend and failure volume, so they stay complete for every
+// member, as they do for restricted agents (foldRestrictedAgents), and only
+// the project_id filter refuses a hidden project.
+
+func TestPrivateProjectDashboardsKeepWorkspaceTotals(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ agentID := createHandlerTestAgent(t, f.marker+"-dash", []byte("[]"))
+ runtimeID := handlerTestRuntimeID(t)
+ for _, status := range []string{"completed", "failed"} {
+ dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID, "issue_id": f.secretIssue, "status": status,
+ "failure_reason": "agent_error.process_failure",
+ "started_at": testutil.Raw("now() - interval '2 minutes'"),
+ "completed_at": testutil.Raw("now() - interval '1 minute'"),
+ })
+ }
+ dbfx.InsertNoID(t, "task_usage_hourly", testutil.Cols{
+ "bucket_hour": testutil.Raw("date_trunc('hour', now())"), "workspace_id": testWorkspaceID,
+ "runtime_id": runtimeID, "agent_id": agentID, "project_id": f.projectID,
+ "provider": "anthropic", "model": f.marker, "input_tokens": 10, "task_count": 1,
+ }, "agent_id = $1", agentID)
+
+ get := func(h http.HandlerFunc, path, userID, query string) []map[string]any {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ h(rec, asUser(newRequest(http.MethodGet, path+"?days=7"+query, nil), userID))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("%s%s as %s = %d: %s", path, query, userID, rec.Code, rec.Body.String())
+ }
+ var rows []map[string]any
+ if err := json.Unmarshal(rec.Body.Bytes(), &rows); err != nil {
+ t.Fatalf("%s: %v", path, err)
+ }
+ return rows
+ }
+ sum := func(rows []map[string]any, key string) float64 {
+ var n float64
+ for _, row := range rows {
+ v, _ := row[key].(float64)
+ n += v
+ }
+ return n
+ }
+ hasAgent := func(rows []map[string]any) bool {
+ for _, row := range rows {
+ if row["agent_id"] == agentID {
+ return true
+ }
+ }
+ return false
+ }
+ missing := "&project_id=00000000-0000-0000-0000-0000000000ff"
+ secret := "&project_id=" + f.projectID
+ for _, ep := range []struct {
+ path string
+ h http.HandlerFunc
+ byAgent bool
+ count string
+ }{
+ {"/api/dashboard/usage/daily", testHandler.GetDashboardUsageDaily, false, "input_tokens"},
+ {"/api/dashboard/usage/by-agent", testHandler.GetDashboardUsageByAgent, true, "input_tokens"},
+ {"/api/dashboard/agent-runtime", testHandler.GetDashboardAgentRunTime, true, "task_count"},
+ {"/api/dashboard/runtime/daily", testHandler.GetDashboardRunTimeDaily, false, "task_count"},
+ {"/api/dashboard/failures/daily", testHandler.GetDashboardFailuresDaily, false, "task_count"},
+ {"/api/dashboard/failures/by-agent", testHandler.GetDashboardFailuresByAgent, true, "task_count"},
+ } {
+ t.Run(ep.path, func(t *testing.T) {
+ share := sum(get(ep.h, ep.path, f.insider, secret), ep.count)
+ if share == 0 {
+ t.Fatal("project member: the project rollup is empty")
+ }
+ if rows := get(ep.h, ep.path, f.outsider, secret); len(rows) != len(get(ep.h, ep.path, f.outsider, missing)) || len(rows) != 0 {
+ t.Fatalf("outsider: hidden project_id returned %d rows, want the missing-project answer (0)", len(rows))
+ }
+ outside := get(ep.h, ep.path, f.outsider, "")
+ for name, userID := range map[string]string{"project member": f.insider, "workspace owner": testUserID} {
+ if got, want := sum(outside, ep.count), sum(get(ep.h, ep.path, userID, ""), ep.count); got != want || got < share {
+ t.Fatalf("workspace %s: outsider = %v, %s = %v, want equal totals that include the private project's %v", ep.count, got, name, want, share)
+ }
+ }
+ if ep.byAgent && !hasAgent(outside) {
+ t.Fatal("outsider: the agent's row is missing from the workspace rollup")
+ }
+ })
+ }
+}
+
+func TestPrivateProjectWorkflowsHideProject(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ type workflowList struct {
+ Workflows []IssueWorkflowResponse `json:"workflows"`
+ }
+ list := func(userID string) workflowList {
+ var out workflowList
+ testutil.Call(t, testHandler.ListIssueWorkflows, asUser(workflowRequest(http.MethodGet, "/api/issue-workflows", nil), userID)).
+ Want(http.StatusOK).JSON(&out)
+ return out
+ }
+ names := func(wfs []IssueWorkflowResponse) bool {
+ for _, wf := range wfs {
+ for _, id := range wf.ProjectIDs {
+ if id == f.projectID {
+ return true
+ }
+ }
+ }
+ return false
+ }
+ insider, outsider := list(f.insider), list(f.outsider)
+ if !names(insider.Workflows) {
+ t.Fatal("project member: no workflow lists the private project")
+ }
+ if names(outsider.Workflows) {
+ t.Fatal("outsider: a workflow lists the private project")
+ }
+
+ var def IssueWorkflowResponse
+ for _, wf := range insider.Workflows {
+ if wf.IsDefault {
+ def = wf
+ }
+ }
+ if def.ID == "" || len(def.Steps) == 0 {
+ t.Fatalf("no Default workflow with steps: %+v", insider.Workflows)
+ }
+ var one IssueWorkflowResponse
+ testutil.Call(t, testHandler.GetIssueWorkflow, withURLParam(asUser(workflowRequest(http.MethodGet, "/api/issue-workflows/"+def.ID, nil), f.outsider), "id", def.ID)).
+ Want(http.StatusOK).JSON(&one)
+ if names([]IssueWorkflowResponse{one}) {
+ t.Fatal("outsider: GET workflow lists the private project")
+ }
+
+ brief := func(userID string) string {
+ var out struct {
+ Brief string `json:"brief"`
+ }
+ body := map[string]any{"status_key": def.Steps[0].StatusKey, "project_id": f.projectID}
+ req := withURLParam(asUser(workflowRequest(http.MethodPost, "/api/issue-workflows/"+def.ID+"/brief", body), userID), "id", def.ID)
+ testutil.Call(t, testHandler.PreviewIssueWorkflowBrief, req).Want(http.StatusOK).JSON(&out)
+ return out.Brief
+ }
+ if b := brief(f.insider); !strings.Contains(b, f.marker+" secret project") {
+ t.Fatalf("project member's brief lacks the project: %q", b)
+ }
+ if b := brief(f.outsider); strings.Contains(b, f.marker) {
+ t.Fatalf("outsider's brief names the private project: %q", b)
+ }
+}
+
+func TestPrivateProjectSearchIndexManifestLeavesOutHiddenRows(t *testing.T) {
+ f := newPrivateProjectFixture(t)
+ manifest := func(userID string) SearchIndexManifestResponse {
+ return testutil.Decode[SearchIndexManifestResponse](t, testHandler.GetSearchIndexManifest,
+ asUser(searchIndexRequest(http.MethodGet, "/api/search-index/manifest", testWorkspaceID, nil), userID), http.StatusOK)
+ }
+ inside, outside, owner := manifest(f.insider), manifest(f.outsider), manifest(testUserID)
+ if d := inside.IssueCount - outside.IssueCount; d != 1 {
+ t.Errorf("issue_count member - outsider = %d, want 1", d)
+ }
+ if d := inside.CommentCount - outside.CommentCount; d != 1 {
+ t.Errorf("comment_count member - outsider = %d, want 1", d)
+ }
+ if d := inside.ProjectCount - outside.ProjectCount; d != 1 {
+ t.Errorf("project_count member - outsider = %d, want 1", d)
+ }
+ if inside.TextBytes <= outside.TextBytes {
+ t.Errorf("text_bytes member %d <= outsider %d", inside.TextBytes, outside.TextBytes)
+ }
+ if owner.IssueCount != inside.IssueCount || owner.ProjectCount != inside.ProjectCount {
+ t.Errorf("owner counts %d/%d, want the member's %d/%d", owner.IssueCount, owner.ProjectCount, inside.IssueCount, inside.ProjectCount)
+ }
+}
diff --git a/server/internal/handler/private_project_chat_claim_test.go b/server/internal/handler/private_project_chat_claim_test.go
new file mode 100644
index 0000000000..0aa5235a0a
--- /dev/null
+++ b/server/internal/handler/private_project_chat_claim_test.go
@@ -0,0 +1,98 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/projectaccess"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// A chat bound to a private project (MUL-8472) hands the project's title,
+// description and resources to every run. A member removed from the project
+// keeps the chat, so the claim must stop carrying the project then.
+func TestPrivateProjectChatClaimDropsContextAfterRemoval(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ for _, tc := range []struct {
+ name string
+ removed bool
+ }{
+ {"project member", false},
+ {"removed from the project", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx := context.Background()
+ marker := fmt.Sprintf("ppchat%d", time.Now().UnixNano())
+ member := createPlainMember(t, marker+"@multica.test")
+ projectID := dbfx.Project(t, marker+" secret project", testutil.Cols{
+ "visibility": projectaccess.VisibilityPrivate,
+ "description": marker + " secret description",
+ })
+ addProjectMemberRow(t, projectID, member)
+
+ // The agent's owner is the workspace owner, who sees every
+ // project: only the chat's human can stop the context.
+ agentID := createHandlerTestAgent(t, "PrivateChatClaimAgent", []byte("[]"))
+ runtimeID := handlerTestRuntimeID(t)
+ sessionID := dbfx.ChatSession(t, agentID, testutil.Cols{"creator_id": member, "project_id": projectID})
+ dbfx.Exec(t, `INSERT INTO chat_message (chat_session_id, role, content) VALUES ($1, 'user', 'hello')`, sessionID)
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID, "priority": 1000, "chat_session_id": sessionID,
+ "originator_user_id": member, "accountable_user_id": member,
+ })
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM chat_message WHERE chat_session_id = $1`, sessionID)
+ })
+ if tc.removed {
+ if _, err := testPool.Exec(ctx, `DELETE FROM project_member WHERE project_id = $1 AND user_id = $2`, projectID, member); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // The shared TestMain runtime heartbeats only at suite start, and
+ // claims skip runtimes unseen for RuntimeClaimFreshnessSeconds
+ // (150s); a slow -race run reaches this test after that.
+ dbfx.Exec(t, `UPDATE agent_runtime SET status = 'online', last_seen_at = now() WHERE id = $1`, runtimeID)
+
+ w := httptest.NewRecorder()
+ req := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/claim", nil), "runtimeId", runtimeID)
+ testHandler.ClaimTaskByRuntime(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ClaimTaskByRuntime = %d: %s", w.Code, w.Body.String())
+ }
+ var resp struct {
+ Task *struct {
+ ID string `json:"id"`
+ ProjectID string `json:"project_id"`
+ ProjectTitle string `json:"project_title"`
+ ProjectDescription string `json:"project_description"`
+ } `json:"task"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatal(err)
+ }
+ if resp.Task == nil || resp.Task.ID != taskID {
+ t.Fatalf("claimed task = %+v, want %s", resp.Task, taskID)
+ }
+ if tc.removed {
+ if resp.Task.ProjectID != "" || resp.Task.ProjectTitle != "" || resp.Task.ProjectDescription != "" {
+ t.Fatalf("claim after removal carries the private project: %+v", resp.Task)
+ }
+ // The session keeps its binding; access coming back restores it.
+ if n := dbfx.Count(t, `SELECT count(*) FROM chat_session WHERE id = $1 AND project_id = $2`, sessionID, projectID); n != 1 {
+ t.Fatal("the claim cleared the session's project")
+ }
+ return
+ }
+ if resp.Task.ProjectID != projectID || resp.Task.ProjectTitle != marker+" secret project" {
+ t.Fatalf("project member's claim lacks the project: %+v", resp.Task)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/private_project_gc_test.go b/server/internal/handler/private_project_gc_test.go
new file mode 100644
index 0000000000..0bbec5ea68
--- /dev/null
+++ b/server/internal/handler/private_project_gc_test.go
@@ -0,0 +1,86 @@
+package handler
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// A member's credential on the daemon GC routes must not read the lifecycle
+// of an issue in a private project they cannot see (MUL-8472). A daemon token
+// keeps reading it: its runtime may run that project's tasks for others.
+func TestPrivateProjectDaemonIssueGCChecks(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ f := newPrivateProjectFixture(t)
+ missingID := "00000000-0000-0000-0000-000000000099"
+
+ for _, tc := range []struct {
+ name string
+ userID string
+ token bool
+ wantFound bool
+ }{
+ {"user outsider", f.outsider, false, false},
+ {"user project member", f.insider, false, true},
+ {"user workspace owner", testUserID, false, true},
+ {"daemon token of a runtime owner outside the project", f.outsider, true, true},
+ {"daemon token project member", f.insider, true, true},
+ {"workspace token", "", true, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ request := func(method, path string, body any) *http.Request {
+ r := asUser(newRequest(method, path, body), tc.userID)
+ if tc.token {
+ ctx := middleware.WithDaemonContext(r.Context(), testWorkspaceID, "gc-test-daemon")
+ ctx = middleware.WithDaemonTokenOwnerID(ctx, tc.userID)
+ r = r.WithContext(ctx)
+ }
+ return r
+ }
+ t.Run("single", func(t *testing.T) {
+ get := func(id string, want int) string {
+ r := withURLParam(request(http.MethodGet, "/api/daemon/issues/"+id+"/gc-check", nil), "issueId", id)
+ return testutil.Call(t, testHandler.GetIssueGCCheck, r).Want(want).Body.String()
+ }
+ want := http.StatusOK
+ if !tc.wantFound {
+ want = http.StatusNotFound
+ }
+ secret := get(f.secretIssue, want)
+ missing := get(missingID, http.StatusNotFound)
+ if !tc.wantFound && secret != missing {
+ t.Fatalf("hidden issue response %s differs from missing %s", secret, missing)
+ }
+ get(f.publicIssue, http.StatusOK)
+ })
+ t.Run("batch", func(t *testing.T) {
+ ids := []string{f.secretIssue, missingID, f.publicIssue, f.secretIssue}
+ r := withURLParam(request(http.MethodPost, "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check", map[string]any{"issue_ids": ids}), "workspaceId", testWorkspaceID)
+ var out struct {
+ Issues []batchIssueGCCheckItem `json:"issues"`
+ }
+ testutil.Call(t, testHandler.BatchIssueGCCheck, r).Want(http.StatusOK).JSON(&out)
+ if len(out.Issues) != len(ids) {
+ t.Fatalf("got %d results, want %d", len(out.Issues), len(ids))
+ }
+ for i, item := range out.Issues {
+ wantFound := i == 2 || (i != 1 && tc.wantFound)
+ if item.ID != ids[i] || item.Found != wantFound {
+ t.Errorf("result %d = %+v, want id %s, found %t", i, item, ids[i], wantFound)
+ }
+ if wantFound {
+ if item.Status == "" || item.Category == "" || item.UpdatedAt == nil {
+ t.Errorf("visible issue lacks lifecycle metadata: %+v", item)
+ }
+ } else if item.Status != "" || item.Category != "" || item.UpdatedAt != nil {
+ t.Errorf("hidden/missing issue exposes lifecycle metadata: %+v", item)
+ }
+ }
+ })
+ })
+ }
+}
diff --git a/server/internal/handler/project_access.go b/server/internal/handler/project_access.go
index 6a2528412a..51fc766b9c 100644
--- a/server/internal/handler/project_access.go
+++ b/server/internal/handler/project_access.go
@@ -341,6 +341,25 @@ func (h *Handler) requireChatProjectVisible(w http.ResponseWriter, r *http.Reque
return true
}
+// chatRunProjectID is the chat session project whose context a claimed chat
+// run may carry: none once the session's creator, the run's human or the
+// agent's owner can no longer see it. The session keeps its project_id, so
+// the context comes back if access does.
+func (h *Handler) chatRunProjectID(ctx context.Context, cs db.ChatSession, task db.AgentTaskQueue, agentOwnerID pgtype.UUID) (pgtype.UUID, error) {
+ if !cs.ProjectID.Valid {
+ return cs.ProjectID, nil
+ }
+ principals := append(projectaccess.RunPrincipals(task, agentOwnerID), cs.CreatorID)
+ hidden, err := projectaccess.ForPrincipals(ctx, h.Queries, cs.WorkspaceID, principals...)
+ if err != nil {
+ return pgtype.UUID{}, err
+ }
+ if !hidden.CanSeeProject(cs.ProjectID) {
+ return pgtype.UUID{}, nil
+ }
+ return cs.ProjectID, nil
+}
+
// hiddenProjectPredicate is the dynamic-SQL twin of the sqlc
// hidden_project_ids filter: rows outside any project always pass.
func hiddenProjectPredicate(column, param string) string {
diff --git a/server/internal/handler/search_index.go b/server/internal/handler/search_index.go
index d44a9c43fb..7204fe0f75 100644
--- a/server/internal/handler/search_index.go
+++ b/server/internal/handler/search_index.go
@@ -287,6 +287,10 @@ func (h *Handler) GetSearchIndexManifest(w http.ResponseWriter, r *http.Request)
if !ok {
return
}
+ hidden, ok := h.requestHiddenProjects(w, r, uuidToString(wsUUID))
+ if !ok {
+ return
+ }
release, ok := acquireSearchIndexBootstrapSlot(r.Context())
if !ok {
if writeRequestCancellation(w, r, r.Context().Err()) {
@@ -299,7 +303,10 @@ func (h *Handler) GetSearchIndexManifest(w http.ResponseWriter, r *http.Request)
var row db.GetSearchIndexManifestRow
err := h.runSearchIndexRead(r.Context(), func(q *db.Queries) error {
var err error
- row, err = q.GetSearchIndexManifest(r.Context(), wsUUID)
+ row, err = q.GetSearchIndexManifest(r.Context(), db.GetSearchIndexManifestParams{
+ WorkspaceID: wsUUID,
+ HiddenProjectIds: hidden.Param(),
+ })
return err
})
if err != nil {
diff --git a/server/internal/service/app_decision.go b/server/internal/service/app_decision.go
index 2a4f9c762f..628c4b0fe7 100644
--- a/server/internal/service/app_decision.go
+++ b/server/internal/service/app_decision.go
@@ -32,6 +32,9 @@ func (s *TaskService) EnqueueAppDecisionRun(ctx context.Context, issueID, agentI
if !agent.RuntimeID.Valid {
return ErrChatTaskAgentNoRuntime
}
+ if err := s.guardRunProjectAccess(ctx, issue, agent, actorID, actorID); err != nil {
+ return err
+ }
waiting, err := s.Queries.FindWaitingIssueRun(ctx, db.FindWaitingIssueRunParams{IssueID: issueID, AgentID: agentID, OriginatorUserID: actorID})
if err == nil {
folded, err := s.Queries.AppendQueuedTaskHandoffNote(ctx, db.AppendQueuedTaskHandoffNoteParams{ID: waiting, Note: note})
diff --git a/server/internal/service/issue_wakeup.go b/server/internal/service/issue_wakeup.go
index c552007ae2..3a9710f30a 100644
--- a/server/internal/service/issue_wakeup.go
+++ b/server/internal/service/issue_wakeup.go
@@ -643,6 +643,22 @@ func (s *IssueWakeupService) authorize(ctx context.Context, q *db.Queries, ws, m
return nil
}
+// authorizeRun is authorize plus the private-project rule every issue run
+// obeys (guardRunProjectAccess): the rule's creator and the agent's owner must
+// both still see the issue's project.
+func (s *IssueWakeupService) authorizeRun(ctx context.Context, q *db.Queries, issue db.Issue, member pgtype.UUID, a db.Agent) error {
+ if err := s.authorize(ctx, q, issue.WorkspaceID, member, a); err != nil {
+ return err
+ }
+ if err := s.Tasks.guardRunProjectAccess(ctx, issue, a, member, member); err != nil {
+ if errors.Is(err, ErrProjectAccessDenied) {
+ return ErrWakeupForbidden
+ }
+ return err
+ }
+ return nil
+}
+
// Tick uses the existing scheduler lease. Each config has a row lock as well,
// so a manual retry or a second server cannot dispatch the same receipt twice.
func (s *IssueWakeupService) Tick(ctx context.Context) error {
@@ -1019,7 +1035,7 @@ func (s *IssueWakeupService) dispatch(ctx context.Context, prev db.IssueWakeup)
if agent.ID.Valid && agent.RuntimeID != candidate.RuntimeID {
return tx.Commit(ctx)
}
- authErr := s.authorize(ctx, q, w.WorkspaceID, w.CreatedBy, agent)
+ authErr := s.authorizeRun(ctx, q, issue, w.CreatedBy, agent)
if w.DisabledAt.Valid || !active || authErr != nil {
if authErr != nil && !errors.Is(authErr, ErrWakeupForbidden) {
return authErr
@@ -1492,5 +1508,12 @@ func (s *IssueWakeupService) CheckClaim(ctx context.Context, task db.AgentTaskQu
if err != nil {
return err
}
- return s.authorize(ctx, s.Tasks.Queries, w.WorkspaceID, w.CreatedBy, agent)
+ issue, err := s.Tasks.Queries.GetIssue(ctx, w.IssueID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return ErrWakeupForbidden
+ }
+ if err != nil {
+ return err
+ }
+ return s.authorizeRun(ctx, s.Tasks.Queries, issue, w.CreatedBy, agent)
}
diff --git a/server/internal/service/issue_wakeup_system.go b/server/internal/service/issue_wakeup_system.go
index ccab4a4a4a..9e2bbe2e0d 100644
--- a/server/internal/service/issue_wakeup_system.go
+++ b/server/internal/service/issue_wakeup_system.go
@@ -11,6 +11,7 @@ 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"
@@ -630,6 +631,20 @@ func (s *IssueWakeupService) dispatchSystem(ctx context.Context, prev db.IssueWa
if err != nil {
return err
}
+ // Recorded without a run, like an assignee whose agent cannot run.
+ if err = s.Tasks.guardRunProjectAccess(ctx, issue, agent, attr.UserID, attr.AccountableUserID); err != nil {
+ if !errors.Is(err, ErrProjectAccessDenied) {
+ return err
+ }
+ facts["outcome"], facts["reason"] = "none", string(dispatch.ReasonProjectAccessBlocked)
+ if err = q.ConsumeWakeupReceipts(ctx, db.ConsumeWakeupReceiptsParams{Ids: ids}); err != nil {
+ return err
+ }
+ if err = note(wakeupActivityTriggered, facts); err != nil {
+ return err
+ }
+ return commit()
+ }
waiting, err := hasWaitingRun(ctx, q, issue.ID, agent.ID, attr.UserID)
if err != nil {
return err
diff --git a/server/internal/service/private_project_background_runs_test.go b/server/internal/service/private_project_background_runs_test.go
new file mode 100644
index 0000000000..b955807d72
--- /dev/null
+++ b/server/internal/service/private_project_background_runs_test.go
@@ -0,0 +1,256 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/dispatch"
+ "github.com/multica-ai/multica/server/internal/projectaccess"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/internal/util"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+)
+
+// Background runs (wakeups, the sub-issue rule, app decisions, delegated
+// failure recovery) start without a person clicking anything, so the private
+// project rule (MUL-8472) has to hold where they are created: the run's human
+// and the agent's owner must both see the issue's project.
+
+// privateRunFixture: a regular member who owns a private agent, and an issue
+// in a private project. inProject decides whether the member is a project
+// member; the workspace owner (f.UserID) is not a project member either way.
+type privateRunFixture struct {
+ principalFixture
+ member string
+ agent string
+ project string
+ issue pgtype.UUID
+}
+
+func newPrivateRunFixture(t *testing.T, inProject bool) privateRunFixture {
+ t.Helper()
+ f, _ := newPrincipalFixture(t)
+ if err := f.q.SeedIssueStatusEntries(context.Background(), parseTestUUID(t, f.WorkspaceID)); err != nil {
+ t.Fatal(err)
+ }
+ member := f.member(t, "pp-run")
+ project := f.Project(t, "pp-run secret project", testutil.Cols{"visibility": projectaccess.VisibilityPrivate})
+ if inProject {
+ f.InsertNoID(t, "project_member", testutil.Cols{
+ "workspace_id": f.WorkspaceID, "project_id": project, "user_id": member,
+ }, "project_id = $1 AND user_id = $2", project, member)
+ }
+ agent := f.privateAgentOwnedBy(t, member, "pp-run")
+ issue := f.Issue(t, "pp-run secret issue", testutil.Cols{"project_id": project, "creator_id": member})
+ f.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", issue)
+ f.Cleanup(t, "DELETE FROM issue_wakeup_receipt WHERE wakeup_id IN (SELECT id FROM issue_wakeup WHERE issue_id=$1)", issue)
+ f.Cleanup(t, "DELETE FROM agent_task_queue WHERE issue_id=$1", issue)
+ f.Cleanup(t, "DELETE FROM activity_log WHERE issue_id=$1", issue)
+ return privateRunFixture{principalFixture: f, member: member, agent: agent, project: project, issue: parseTestUUID(t, issue)}
+}
+
+func (f privateRunFixture) leaveProject(t *testing.T) {
+ t.Helper()
+ f.Exec(t, "DELETE FROM project_member WHERE project_id=$1 AND user_id=$2", f.project, f.member)
+}
+
+func (f privateRunFixture) issueRuns(t *testing.T) int {
+ t.Helper()
+ return f.Count(t, "SELECT count(*) FROM agent_task_queue WHERE issue_id=$1", f.issue)
+}
+
+func TestIssueWakeupPrivateProjectNeedsTheRulesCreator(t *testing.T) {
+ ctx := context.Background()
+ for _, tc := range []struct {
+ name string
+ removed bool
+ wantRuns int
+ }{
+ {"project member", false, 1},
+ {"removed from the project", true, 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f := newPrivateRunFixture(t, true)
+ s := &IssueWakeupService{Tasks: f.svc.TaskSvc}
+ w, err := s.Create(ctx, f.issue, parseTestUUID(t, f.member), pgtype.UUID{}, WakeupInput{
+ AgentID: f.agent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "Review",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tc.removed {
+ f.leaveProject(t)
+ }
+ f.Comment(t, util.UUIDToString(f.issue), "trigger")
+ wakeDispatch(t, s, w)
+ if n := wakeRuns(t, f.principalFixture, w.ID); n != tc.wantRuns {
+ t.Fatalf("wakeup runs = %d, want %d", n, tc.wantRuns)
+ }
+ got, err := f.q.LocklessWakeup(ctx, w.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tc.removed && (got.Enabled || !got.DisabledAt.Valid) {
+ t.Fatalf("rule of a creator outside the project stays on: enabled=%t disabled_at=%v", got.Enabled, got.DisabledAt.Valid)
+ }
+ // A once rule switches itself off after firing; only the
+ // platform sets disabled_at.
+ if !tc.removed && got.DisabledAt.Valid {
+ t.Fatalf("rule of a project member was disabled: %q", got.LastError.String)
+ }
+ })
+ }
+}
+
+// A wakeup run queued while its creator could see the project is refused at
+// claim once they cannot, like a creator who lost the agent.
+func TestIssueWakeupClaimRechecksPrivateProject(t *testing.T) {
+ ctx := context.Background()
+ f := newPrivateRunFixture(t, true)
+ s := &IssueWakeupService{Tasks: f.svc.TaskSvc}
+ w, err := s.Create(ctx, f.issue, parseTestUUID(t, f.member), pgtype.UUID{}, WakeupInput{
+ AgentID: f.agent, Kind: "event", Mode: "continuous", EventTypes: []string{"comment.created"}, Instruction: "Review",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.Comment(t, util.UUIDToString(f.issue), "trigger")
+ wakeDispatch(t, s, w)
+ got, err := f.q.LocklessWakeup(ctx, w.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ task, err := f.q.GetAgentTask(ctx, got.LastTaskID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := s.CheckClaim(ctx, task); err != nil {
+ t.Fatalf("project member's wakeup run refused at claim: %v", err)
+ }
+ f.leaveProject(t)
+ if err := s.CheckClaim(ctx, task); !errors.Is(err, ErrWakeupForbidden) {
+ t.Fatalf("claim after leaving the project = %v, want ErrWakeupForbidden", err)
+ }
+}
+
+// The workspace owner sees every private project without a project_member row.
+func TestIssueWakeupPrivateProjectWorkspaceOwner(t *testing.T) {
+ f := newPrivateRunFixture(t, false)
+ s := &IssueWakeupService{Tasks: f.svc.TaskSvc}
+ ownerAgent := f.privateAgentOwnedBy(t, f.UserID, "pp-run-owner")
+ w, err := s.Create(context.Background(), f.issue, parseTestUUID(t, f.UserID), pgtype.UUID{}, WakeupInput{
+ AgentID: ownerAgent, Kind: "event", EventTypes: []string{"comment.created"}, Instruction: "Review",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.Comment(t, util.UUIDToString(f.issue), "trigger")
+ wakeDispatch(t, s, w)
+ if n := wakeRuns(t, f.principalFixture, w.ID); n != 1 {
+ t.Fatalf("owner's wakeup runs = %d, want 1", n)
+ }
+}
+
+// The sub-issue rule wakes the parent's assignee as the issue's human; an
+// assignee whose owner is outside the project is recorded, not run.
+func TestChildDoneWakeupPrivateProjectNeedsTheAgentOwner(t *testing.T) {
+ ctx := context.Background()
+ for _, tc := range []struct {
+ name string
+ inProject bool
+ wantRuns int
+ }{
+ {"agent owner in the project", true, 1},
+ {"agent owner outside the project", false, 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f := newPrivateRunFixture(t, tc.inProject)
+ s := &IssueWakeupService{Tasks: f.svc.TaskSvc}
+ // The parent's creator is the workspace owner, so the agent's
+ // owner is the only principal the project can stop.
+ f.Exec(t, "UPDATE issue SET status='in_progress',assignee_type='agent',assignee_id=$2,creator_id=$3 WHERE id=$1", f.issue, f.agent, f.UserID)
+ child := f.Issue(t, "pp-run child", testutil.Cols{"parent_issue_id": f.issue, "project_id": f.project, "status": "in_progress"})
+ f.Cleanup(t, "DELETE FROM issue_child_event WHERE parent_id=$1", f.issue)
+ if err := s.ProcessChildEvents(ctx, f.issue); err != nil {
+ t.Fatal(err)
+ }
+ f.Exec(t, "UPDATE issue SET status='done' WHERE id=$1", child)
+ if err := s.ProcessChildEvents(ctx, f.issue); err != nil {
+ t.Fatal(err)
+ }
+ if n := f.issueRuns(t); n != tc.wantRuns {
+ t.Fatalf("runs on the parent = %d, want %d", n, tc.wantRuns)
+ }
+ if tc.wantRuns == 0 {
+ n := f.Count(t, `SELECT count(*) FROM activity_log WHERE issue_id=$1
+ AND details->>'outcome'='none' AND details->>'reason'=$2`, f.issue, string(dispatch.ReasonProjectAccessBlocked))
+ if n != 1 {
+ t.Fatalf("blocked timeline entries = %d, want 1", n)
+ }
+ }
+ })
+ }
+}
+
+func TestAppDecisionRunPrivateProjectNeedsTheDecider(t *testing.T) {
+ ctx := context.Background()
+ for _, tc := range []struct {
+ name string
+ removed bool
+ }{
+ {"project member", false},
+ {"removed from the project", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f := newPrivateRunFixture(t, true)
+ if tc.removed {
+ f.leaveProject(t)
+ }
+ err := f.svc.TaskSvc.EnqueueAppDecisionRun(ctx, f.issue, parseTestUUID(t, f.agent), parseTestUUID(t, f.member), dbid.NewV7(), "approved")
+ runs := f.issueRuns(t)
+ if tc.removed {
+ if !errors.Is(err, ErrProjectAccessDenied) || runs != 0 {
+ t.Fatalf("decision run outside the project: err=%v runs=%d, want ErrProjectAccessDenied and 0", err, runs)
+ }
+ return
+ }
+ if err != nil || runs != 1 {
+ t.Fatalf("decision run for a project member: err=%v runs=%d, want 1", err, runs)
+ }
+ })
+ }
+}
+
+// Recovery waits while the coordinator's human is outside the project and
+// resumes once they are back.
+func TestDelegatedFailureRecoveryPrivateProjectNeedsTheHuman(t *testing.T) {
+ f, svc := seedDelegatedFailureFixture(t)
+ ctx := context.Background()
+ fx := testutil.New(f.pool, f.workspaceID, f.userID)
+ fx.Exec(t, "UPDATE member SET role='member' WHERE workspace_id=$1 AND user_id=$2", f.workspaceID, f.userID)
+ project := fx.Project(t, "recovery secret project", testutil.Cols{"visibility": projectaccess.VisibilityPrivate})
+ fx.Exec(t, "UPDATE issue SET project_id=$2 WHERE id=$1", f.issueID, project)
+
+ failedID := f.insertWorkerTask(t, "running", "comment", 1, 2)
+ if _, err := svc.FailTask(ctx, failedID, "worker failed", "", "", "", "agent_error.process_failure", false, "", ""); err != nil {
+ t.Fatalf("FailTask: %v", err)
+ }
+ if n := f.recoveryTasks(t, failedID); n != 0 {
+ t.Fatalf("recovery runs outside the project = %d, want 0", n)
+ }
+ var signal pgtype.UUID
+ fx.QueryRow(t, `SELECT id FROM comment WHERE source_task_id=$1 AND type='progress_update'`, failedID).Scan(&signal)
+ if !f.pending(t, svc, signal) {
+ t.Fatal("refused recovery settled its signal")
+ }
+
+ fx.InsertNoID(t, "project_member", testutil.Cols{
+ "workspace_id": f.workspaceID, "project_id": project, "user_id": f.userID,
+ }, "project_id = $1 AND user_id = $2", project, f.userID)
+ sweepDelegatedFailureRecoveries(t, svc)
+ if n := f.recoveryTasks(t, failedID); n != 1 {
+ t.Fatalf("recovery runs once back in the project = %d, want 1", n)
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 31c725a989..6421063d25 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -6964,6 +6964,13 @@ func (s *TaskService) dispatchDelegatedFailureRecovery(ctx context.Context, targ
if !ruleVersionID.Valid {
ruleVersionID = target.source.RuleVersionID
}
+ // The signal stays pending, so a later sweep recovers once access is back.
+ if err := s.guardRunProjectAccess(ctx, target.issue, target.agent, originator, accountable); err != nil {
+ if errors.Is(err, ErrProjectAccessDenied) {
+ return delegatedFailureRecoveryCovered, nil
+ }
+ return delegatedFailureRecoveryCovered, err
+ }
overlay := s.buildRuntimeMCPOverlay(ctx, originator, target.agent)
task, err := s.Queries.CreateAgentTask(ctx, db.CreateAgentTaskParams{
ID: dbid.NewV7(),
diff --git a/server/pkg/db/generated/search_index.sql.go b/server/pkg/db/generated/search_index.sql.go
index 85651c8ba1..e4d2c34c18 100644
--- a/server/pkg/db/generated/search_index.sql.go
+++ b/server/pkg/db/generated/search_index.sql.go
@@ -33,21 +33,38 @@ func (q *Queries) GetSearchIndexCurrentSnapshot(ctx context.Context) (string, er
const getSearchIndexManifest = `-- name: GetSearchIndexManifest :one
-WITH ws AS (SELECT $1::uuid AS id)
+WITH ws AS (SELECT $1::uuid AS id, $2::uuid[] AS hidden),
+visible_issue AS (
+ SELECT i.id, i.title, i.description FROM issue i, ws
+ WHERE i.workspace_id = ws.id
+ AND (ws.hidden IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(ws.hidden)))
+),
+visible_comment AS (
+ SELECT c.content FROM comment c
+ JOIN visible_issue vi ON vi.id = c.issue_id, ws
+ WHERE c.workspace_id = ws.id AND c.deleted_at IS NULL
+),
+visible_project AS (
+ SELECT p.title, p.description FROM project p, ws
+ WHERE p.workspace_id = ws.id AND (ws.hidden IS NULL OR NOT (p.id = ANY(ws.hidden)))
+)
SELECT
pg_current_snapshot()::text AS snapshot,
- (SELECT count(*) FROM issue i, ws WHERE i.workspace_id = ws.id)::bigint AS issue_count,
- (SELECT COALESCE(sum(octet_length(i.title) + COALESCE(octet_length(i.description), 0)), 0)
- FROM issue i, ws WHERE i.workspace_id = ws.id)::bigint AS issue_bytes,
- (SELECT count(*) FROM comment c, ws
- WHERE c.workspace_id = ws.id AND c.deleted_at IS NULL)::bigint AS comment_count,
- (SELECT COALESCE(sum(octet_length(c.content)), 0) FROM comment c, ws
- WHERE c.workspace_id = ws.id AND c.deleted_at IS NULL)::bigint AS comment_bytes,
- (SELECT count(*) FROM project p, ws WHERE p.workspace_id = ws.id)::bigint AS project_count,
- (SELECT COALESCE(sum(octet_length(p.title) + COALESCE(octet_length(p.description), 0)), 0)
- FROM project p, ws WHERE p.workspace_id = ws.id)::bigint AS project_bytes
+ (SELECT count(*) FROM visible_issue)::bigint AS issue_count,
+ (SELECT COALESCE(sum(octet_length(title) + COALESCE(octet_length(description), 0)), 0)
+ FROM visible_issue)::bigint AS issue_bytes,
+ (SELECT count(*) FROM visible_comment)::bigint AS comment_count,
+ (SELECT COALESCE(sum(octet_length(content)), 0) FROM visible_comment)::bigint AS comment_bytes,
+ (SELECT count(*) FROM visible_project)::bigint AS project_count,
+ (SELECT COALESCE(sum(octet_length(title) + COALESCE(octet_length(description), 0)), 0)
+ FROM visible_project)::bigint AS project_bytes
`
+type GetSearchIndexManifestParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`
+}
+
type GetSearchIndexManifestRow struct {
Snapshot string `json:"snapshot"`
IssueCount int64 `json:"issue_count"`
@@ -65,9 +82,10 @@ type GetSearchIndexManifestRow struct {
// than this snapshot and reaches the client through the change log. The byte
// totals let the client reject a workspace too large for its memory budget
// before downloading it; octet_length reads the stored length, so TOASTed
-// bodies are not decompressed.
-func (q *Queries) GetSearchIndexManifest(ctx context.Context, workspaceID pgtype.UUID) (GetSearchIndexManifestRow, error) {
- row := q.db.QueryRow(ctx, getSearchIndexManifest, workspaceID)
+// bodies are not decompressed. Rows in hidden_project_ids are left out, as
+// the snapshot leaves them out.
+func (q *Queries) GetSearchIndexManifest(ctx context.Context, arg GetSearchIndexManifestParams) (GetSearchIndexManifestRow, error) {
+ row := q.db.QueryRow(ctx, getSearchIndexManifest, arg.WorkspaceID, arg.HiddenProjectIds)
var i GetSearchIndexManifestRow
err := row.Scan(
&i.Snapshot,
diff --git a/server/pkg/db/queries/search_index.sql b/server/pkg/db/queries/search_index.sql
index 8db9dfba63..aa5ca7baf4 100644
--- a/server/pkg/db/queries/search_index.sql
+++ b/server/pkg/db/queries/search_index.sql
@@ -7,20 +7,33 @@
-- than this snapshot and reaches the client through the change log. The byte
-- totals let the client reject a workspace too large for its memory budget
-- before downloading it; octet_length reads the stored length, so TOASTed
--- bodies are not decompressed.
-WITH ws AS (SELECT @workspace_id::uuid AS id)
+-- bodies are not decompressed. Rows in hidden_project_ids are left out, as
+-- the snapshot leaves them out.
+WITH ws AS (SELECT @workspace_id::uuid AS id, sqlc.narg('hidden_project_ids')::uuid[] AS hidden),
+visible_issue AS (
+ SELECT i.id, i.title, i.description FROM issue i, ws
+ WHERE i.workspace_id = ws.id
+ AND (ws.hidden IS NULL OR i.project_id IS NULL OR NOT (i.project_id = ANY(ws.hidden)))
+),
+visible_comment AS (
+ SELECT c.content FROM comment c
+ JOIN visible_issue vi ON vi.id = c.issue_id, ws
+ WHERE c.workspace_id = ws.id AND c.deleted_at IS NULL
+),
+visible_project AS (
+ SELECT p.title, p.description FROM project p, ws
+ WHERE p.workspace_id = ws.id AND (ws.hidden IS NULL OR NOT (p.id = ANY(ws.hidden)))
+)
SELECT
pg_current_snapshot()::text AS snapshot,
- (SELECT count(*) FROM issue i, ws WHERE i.workspace_id = ws.id)::bigint AS issue_count,
- (SELECT COALESCE(sum(octet_length(i.title) + COALESCE(octet_length(i.description), 0)), 0)
- FROM issue i, ws WHERE i.workspace_id = ws.id)::bigint AS issue_bytes,
- (SELECT count(*) FROM comment c, ws
- WHERE c.workspace_id = ws.id AND c.deleted_at IS NULL)::bigint AS comment_count,
- (SELECT COALESCE(sum(octet_length(c.content)), 0) FROM comment c, ws
- WHERE c.workspace_id = ws.id AND c.deleted_at IS NULL)::bigint AS comment_bytes,
- (SELECT count(*) FROM project p, ws WHERE p.workspace_id = ws.id)::bigint AS project_count,
- (SELECT COALESCE(sum(octet_length(p.title) + COALESCE(octet_length(p.description), 0)), 0)
- FROM project p, ws WHERE p.workspace_id = ws.id)::bigint AS project_bytes;
+ (SELECT count(*) FROM visible_issue)::bigint AS issue_count,
+ (SELECT COALESCE(sum(octet_length(title) + COALESCE(octet_length(description), 0)), 0)
+ FROM visible_issue)::bigint AS issue_bytes,
+ (SELECT count(*) FROM visible_comment)::bigint AS comment_count,
+ (SELECT COALESCE(sum(octet_length(content)), 0) FROM visible_comment)::bigint AS comment_bytes,
+ (SELECT count(*) FROM visible_project)::bigint AS project_count,
+ (SELECT COALESCE(sum(octet_length(title) + COALESCE(octet_length(description), 0)), 0)
+ FROM visible_project)::bigint AS project_bytes;
-- name: GetSearchIndexCurrentSnapshot :one
SELECT pg_current_snapshot()::text AS snapshot;