From 4aef0f6fdd1b26e66724ea6b253d55c191bfde2b Mon Sep 17 00:00:00 2001 From: Jaayden Halko Date: Wed, 2 Dec 2026 15:49:09 +0800 Subject: [PATCH] feat: add chat project summaries (#32026) Adds project summaries and share counts on top of #32025. The sidebar's pinned projects read the summaries; the Projects page reads the summaries and the counts. - **`GET /api/experimental/chats/projects/summaries`** returns one `ChatProjectSummary` for every project in the existing project list (the same set): `project_id`, `pinned`, `pin_order`, `own_chat_count`, `own_unread_count`, `own_running`, `own_needs_attention` (`requires_action`, `error` or `paused`) and `last_activity_at` (newest `updated_at` among the caller's counted chats). Counts use only the caller's own top-level, non-archived chats; unread uses the same rule as `has_unread`. `pin_order` is the stored order from #32025: it sorts the pinned projects, lowest first, and can have gaps. A summary does not repeat the project: clients pair it with `GET /chats/projects` by ID. - **Share counts on `ChatProject`:** every project response now carries `member_count` (the owner plus the users the project is shared with directly), `group_count` (shared groups, including Everyone) and `shared_with_everyone`. They count exactly the users and groups `GET .../projects/{project}/acl` lists: users outside the project's organization and deleted groups are left out, through the same helper the ACL endpoint uses. Group members are not expanded, so a list costs two extra queries (memberships and groups) for any number of projects. While chat sharing is disabled or the `chat-project-sharing` experiment is off, every project reports 1 member, 0 groups. - **Same numbers on both pages:** the project page heading already showed "N members, M groups" from the ACL. It now uses a shared formatter, `formatProjectMembers`, which the Projects page card (#32083) also uses, and names the Everyone group first instead of counting it: "Everyone, 2 members, 1 group". - **Why summaries are separate:** the pin and the caller's chat counts change with every chat event, and clients refetch them often, so they do not come with the project, its templates and permissions. - **Authorization:** summaries return only projects the caller can read. They also carry the caller's pins, so they ask RBAC for `read_personal` on the caller: an API key scoped without `user:read_personal` gets a 403. The summaries authorize each project with a full evaluation while the caller has fewer than 200, because the partial evaluation `rbac.Filter` prepares by default costs an organization member about 6 ms per request and a full evaluation about 0.03 ms per project.
Verification `make gen/db` and the API docs and TypeScript types regenerate cleanly; Go lint on the changed packages, the summaries, share counts, pin, chat list, ACL and dbauthz tests pass; `pnpm lint` and the project page tests pass. `TestChatProjectShareCounts` fails if either ACL filter (organization membership, existing groups) is removed. The summaries timings (1.6 ms at 10 projects, 4.6 ms at 50) are medians of 40 runs against a local Postgres 13, measured before the share counts change. Dogfood UAT with a premium license ran on an earlier response shape, which carried the project and a people count inside each summary. It was not repeated for this shape; the Go and Vitest tests cover it.
> [!NOTE] > Most of this PR was written by AI agents (Xum, with UAT run through Coder Agents). The verification above is from those runs. --- coderd/apidoc/docs.go | 77 +++++++ coderd/apidoc/swagger.json | 73 +++++++ coderd/chat_project_acl.go | 96 ++++++++- coderd/chat_project_acl_test.go | 55 +++++ coderd/chat_project_pins.go | 36 +++- coderd/chat_project_pins_test.go | 204 +++++++++++++----- coderd/chat_projects.go | 17 +- coderd/chat_routes.go | 1 + coderd/database/db2sdk/db2sdk.go | 14 ++ coderd/database/dbauthz/dbauthz.go | 27 +++ coderd/database/dbauthz/dbauthz_test.go | 10 + coderd/database/dbgen/dbgen.go | 11 + coderd/database/dbmetrics/querymetrics.go | 8 + coderd/database/dbmock/dbmock.go | 15 ++ coderd/database/modelmethods.go | 12 ++ coderd/database/querier.go | 10 + coderd/database/queries.sql.go | 101 +++++++++ coderd/database/queries/chatprojectpins.sql | 49 +++++ codersdk/chats.go | 40 +++- docs/reference/api/schemas.md | 64 ++++-- site/src/api/typesGenerated.ts | 43 ++++ .../ProjectDetailsPanelView.stories.tsx | 5 +- .../ProjectPage/ProjectDetailsPanelView.tsx | 10 +- .../ProjectPage/projectAccess.test.ts | 31 ++- .../components/ProjectPage/projectAccess.ts | 43 +++- site/src/testHelpers/entities.ts | 3 + 26 files changed, 945 insertions(+), 110 deletions(-) diff --git a/coderd/apidoc/docs.go b/coderd/apidoc/docs.go index c3bc37e83e2..6a2709cb7d9 100644 --- a/coderd/apidoc/docs.go +++ b/coderd/apidoc/docs.go @@ -249,6 +249,37 @@ const docTemplate = `{ } } }, + "/api/experimental/chats/projects/summaries": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "Chats" + ], + "summary": "List chat project summaries", + "operationId": "list-chat-project-summaries", + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/codersdk.ChatProjectSummary" + } + } + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + } + }, "/api/experimental/chats/{chat}/stream/desktop": { "get": { "description": "Raw binary WebSocket stream of the chat workspace desktop.\nExperimental: this endpoint is subject to change.", @@ -24155,6 +24186,10 @@ const docTemplate = `{ "description": { "type": "string" }, + "group_count": { + "description": "GroupCount is how many groups the project is shared with, as\nChatProjectACL lists them, including the Everyone group. It is 0 while\nchat sharing is unavailable.", + "type": "integer" + }, "hidden_template_count": { "description": "HiddenTemplateCount is the number of attached templates the caller\ncannot access. Nothing else about them is returned.", "type": "integer" @@ -24171,6 +24206,10 @@ const docTemplate = `{ "description": "LimitTemplates restricts the project's chats to its attached\ntemplates, and to none when nothing is attached. When false, the chats\ncan use every template their owner can use.", "type": "boolean" }, + "member_count": { + "description": "MemberCount is the owner plus the users the project is shared with\ndirectly, as ChatProjectACL lists them. Members of shared groups are\nnot counted. It is 1 while chat sharing is unavailable.", + "type": "integer" + }, "name": { "description": "Name is a display label and is not unique; ID identifies the project.", "type": "string" @@ -24186,6 +24225,10 @@ const docTemplate = `{ "permissions": { "$ref": "#/definitions/codersdk.ChatProjectPermissions" }, + "shared_with_everyone": { + "description": "SharedWithEveryone reports whether one of those groups is the Everyone\ngroup of the project's organization.", + "type": "boolean" + }, "templates": { "description": "Templates are the attached templates the caller can access. Deprecated\ntemplates and templates that do not allow agents are left out.", "type": "array", @@ -24389,6 +24432,40 @@ const docTemplate = `{ "ChatProjectRoleDeleted" ] }, + "codersdk.ChatProjectSummary": { + "type": "object", + "properties": { + "last_activity_at": { + "description": "LastActivityAt is the latest update to one of the caller's chats.", + "type": "string", + "format": "date-time" + }, + "own_chat_count": { + "type": "integer" + }, + "own_needs_attention": { + "description": "OwnNeedsAttention reports a chat that requires action, failed, or is paused.", + "type": "boolean" + }, + "own_running": { + "type": "boolean" + }, + "own_unread_count": { + "type": "integer" + }, + "pin_order": { + "description": "PinOrder sorts pinned projects, lowest first, with gaps. 0 means not pinned.", + "type": "integer" + }, + "pinned": { + "type": "boolean" + }, + "project_id": { + "type": "string", + "format": "uuid" + } + } + }, "codersdk.ChatProjectTemplate": { "type": "object", "properties": { diff --git a/coderd/apidoc/swagger.json b/coderd/apidoc/swagger.json index 529512f6151..b95610c7d84 100644 --- a/coderd/apidoc/swagger.json +++ b/coderd/apidoc/swagger.json @@ -210,6 +210,33 @@ } } }, + "/api/experimental/chats/projects/summaries": { + "get": { + "produces": ["application/json"], + "tags": ["Chats"], + "summary": "List chat project summaries", + "operationId": "list-chat-project-summaries", + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/codersdk.ChatProjectSummary" + } + } + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + } + }, "/api/experimental/chats/{chat}/stream/desktop": { "get": { "description": "Raw binary WebSocket stream of the chat workspace desktop.\nExperimental: this endpoint is subject to change.", @@ -21917,6 +21944,10 @@ "description": { "type": "string" }, + "group_count": { + "description": "GroupCount is how many groups the project is shared with, as\nChatProjectACL lists them, including the Everyone group. It is 0 while\nchat sharing is unavailable.", + "type": "integer" + }, "hidden_template_count": { "description": "HiddenTemplateCount is the number of attached templates the caller\ncannot access. Nothing else about them is returned.", "type": "integer" @@ -21933,6 +21964,10 @@ "description": "LimitTemplates restricts the project's chats to its attached\ntemplates, and to none when nothing is attached. When false, the chats\ncan use every template their owner can use.", "type": "boolean" }, + "member_count": { + "description": "MemberCount is the owner plus the users the project is shared with\ndirectly, as ChatProjectACL lists them. Members of shared groups are\nnot counted. It is 1 while chat sharing is unavailable.", + "type": "integer" + }, "name": { "description": "Name is a display label and is not unique; ID identifies the project.", "type": "string" @@ -21948,6 +21983,10 @@ "permissions": { "$ref": "#/definitions/codersdk.ChatProjectPermissions" }, + "shared_with_everyone": { + "description": "SharedWithEveryone reports whether one of those groups is the Everyone\ngroup of the project's organization.", + "type": "boolean" + }, "templates": { "description": "Templates are the attached templates the caller can access. Deprecated\ntemplates and templates that do not allow agents are left out.", "type": "array", @@ -22144,6 +22183,40 @@ "ChatProjectRoleDeleted" ] }, + "codersdk.ChatProjectSummary": { + "type": "object", + "properties": { + "last_activity_at": { + "description": "LastActivityAt is the latest update to one of the caller's chats.", + "type": "string", + "format": "date-time" + }, + "own_chat_count": { + "type": "integer" + }, + "own_needs_attention": { + "description": "OwnNeedsAttention reports a chat that requires action, failed, or is paused.", + "type": "boolean" + }, + "own_running": { + "type": "boolean" + }, + "own_unread_count": { + "type": "integer" + }, + "pin_order": { + "description": "PinOrder sorts pinned projects, lowest first, with gaps. 0 means not pinned.", + "type": "integer" + }, + "pinned": { + "type": "boolean" + }, + "project_id": { + "type": "string", + "format": "uuid" + } + } + }, "codersdk.ChatProjectTemplate": { "type": "object", "properties": { diff --git a/coderd/chat_project_acl.go b/coderd/chat_project_acl.go index b692b585930..67d11f69655 100644 --- a/coderd/chat_project_acl.go +++ b/coderd/chat_project_acl.go @@ -11,6 +11,7 @@ import ( "github.com/google/uuid" "golang.org/x/xerrors" + "github.com/coder/coder/v2/buildinfo" "github.com/coder/coder/v2/coderd/audit" "github.com/coder/coder/v2/coderd/database" "github.com/coder/coder/v2/coderd/database/db2sdk" @@ -322,25 +323,100 @@ func grantedChatProjectIDs(roles map[uuid.UUID]codersdk.ChatProjectRole) []uuid. } func (api *API) chatProjectACLUsers(ctx context.Context, project database.ChatProject) ([]codersdk.ChatProjectUser, error) { - // Entries for users outside the organization grant nothing, because access - // requires membership, so hide them. The 000629 trigger and the membership - // lock in patchChatProjectACL keep such entries from being written. //nolint:gocritic // Project readers see who it is shared with without user read permission. memberships, err := api.Database.GetOrganizationIDsByMemberIDs(dbauthz.AsSystemRestricted(ctx), parseACLIDs(project.UserACL)) if err != nil && !xerrors.Is(err, sql.ErrNoRows) { return nil, xerrors.Errorf("get organization memberships: %w", err) } - members := make(database.ChatACL, len(memberships)) - for _, membership := range memberships { - if slices.Contains(membership.OrganizationIDs, project.OrganizationID) { - members[membership.UserID.String()] = project.UserACL[membership.UserID.String()] - } - } - return resolveACLUsers(ctx, api.Database, members, func(user codersdk.MinimalUser, entry database.ChatACLEntry) codersdk.ChatProjectUser { + return resolveACLUsers(ctx, api.Database, chatProjectACLMembers(project, memberships), func(user codersdk.MinimalUser, entry database.ChatACLEntry) codersdk.ChatProjectUser { return codersdk.ChatProjectUser{MinimalUser: user, Role: convertToChatProjectRole(entry.Permissions)} }) } +// chatProjectACLMembers keeps the project's user entries for members of its +// organization. Entries for other users grant nothing, because access +// requires membership, so the ACL hides them. The 000629 trigger and the +// membership lock in patchChatProjectACL keep such entries from being +// written. memberships may cover users of other projects. +func chatProjectACLMembers(project database.ChatProject, memberships []database.GetOrganizationIDsByMemberIDsRow) database.ChatACL { + members := make(database.ChatACL, len(project.UserACL)) + for _, membership := range memberships { + key := membership.UserID.String() + entry, ok := project.UserACL[key] + if ok && slices.Contains(membership.OrganizationIDs, project.OrganizationID) { + members[key] = entry + } + } + return members +} + +// chatProjectSharingAvailable reports whether projects report the users and +// groups they are shared with. It matches the gate on the project ACL +// routes. Which projects are listed does not depend on it: grant keys +// select candidates and RBAC decides. +func (api *API) chatProjectSharingAvailable() bool { + return !api.chatSharingDisabled() && (buildinfo.IsDev() || api.Experiments.Enabled(codersdk.ExperimentChatProjectSharing)) +} + +// chatProjectShareCounts holds how many users and groups a project's ACL +// lists. +type chatProjectShareCounts struct { + users, groups int + everyone bool +} + +// chatProjectsShareCounts counts the users and groups getChatProjectACL +// lists for each project, without the owner. Group members are not +// expanded, so this takes two queries for any number of projects. While +// chat sharing is unavailable, every project counts nothing. +func (api *API) chatProjectsShareCounts(ctx context.Context, projects []database.ChatProject) (map[uuid.UUID]chatProjectShareCounts, error) { + counts := make(map[uuid.UUID]chatProjectShareCounts, len(projects)) + if !api.chatProjectSharingAvailable() { + return counts, nil + } + var userIDs, groupIDs []uuid.UUID + for _, project := range projects { + userIDs = append(userIDs, parseACLIDs(project.UserACL)...) + groupIDs = append(groupIDs, parseACLIDs(project.GroupACL)...) + } + //nolint:gocritic // Project readers see who it is shared with without user read permission. + sysCtx := dbauthz.AsSystemRestricted(ctx) + var memberships []database.GetOrganizationIDsByMemberIDsRow + if len(userIDs) > 0 { + var err error + memberships, err = api.Database.GetOrganizationIDsByMemberIDs(sysCtx, slice.Unique(userIDs)) + if err != nil && !xerrors.Is(err, sql.ErrNoRows) { + return nil, xerrors.Errorf("get organization memberships: %w", err) + } + } + // As in resolveACLGroups, entries for groups that no longer exist are + // not listed. + groupExists := make(map[string]bool, len(groupIDs)) + if len(groupIDs) > 0 { + groups, err := api.Database.GetGroups(sysCtx, database.GetGroupsParams{GroupIds: slice.Unique(groupIDs)}) + if err != nil { + return nil, xerrors.Errorf("get ACL groups: %w", err) + } + for _, group := range groups { + groupExists[group.Group.ID.String()] = true + } + } + for _, project := range projects { + count := chatProjectShareCounts{users: len(chatProjectACLMembers(project, memberships))} + for key := range project.GroupACL { + if groupExists[key] { + count.groups++ + } + } + // The Everyone group's ID is the organization ID. + everyone := project.OrganizationID.String() + _, shared := project.GroupACL[everyone] + count.everyone = shared && groupExists[everyone] + counts[project.ID] = count + } + return counts, nil +} + type ChatProjectACLUpdateValidator codersdk.UpdateChatProjectACL var _ acl.UpdateValidator[codersdk.ChatProjectRole] = ChatProjectACLUpdateValidator{} diff --git a/coderd/chat_project_acl_test.go b/coderd/chat_project_acl_test.go index 171c033bef8..de0fe70656d 100644 --- a/coderd/chat_project_acl_test.go +++ b/coderd/chat_project_acl_test.go @@ -486,6 +486,61 @@ WHERE datname = current_database() AND pid <> pg_backend_pid() AND wait_event_ty requireSDKError(t, err, http.StatusNotFound) } +// TestChatProjectShareCounts checks that a project counts the users and +// groups its ACL lists, so the Projects page and the project page agree. +func TestChatProjectShareCounts(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitLong) + db, ps := dbtestutil.NewDB(t) + client, _ := newChatProjectClientWithAPI(t, func(options *coderdtest.Options) { + options.Database, options.Pubsub = db, ps + }) + firstUser := coderdtest.CreateFirstUser(t, client.Client) + orgID := firstUser.OrganizationID + _, alice := newChatProjectMember(t, client, orgID) + group := dbgen.Group(t, db, database.Group{OrganizationID: orgID}) + otherOrg := dbgen.Organization(t, db, database.Organization{}) + outsider := dbgen.User(t, db, database.User{}) + dbgen.OrganizationMember(t, db, database.OrganizationMember{UserID: outsider.ID, OrganizationID: otherOrg.ID}) + foreignGroup := dbgen.Group(t, db, database.Group{OrganizationID: otherOrg.ID}) + + shared := createChatProject(t, client, orgID, "Counts Shared") + read := database.ChatACLEntry{Permissions: []policy.Action{policy.ActionRead}} + // The ACL lists alice, the group, the Everyone group (its ID is the + // organization ID) and the stored group from another organization. It + // hides the user outside the organization and the deleted group. + require.NoError(t, db.UpdateChatProjectACLByID(ctx, database.UpdateChatProjectACLByIDParams{ + ID: shared.ID, + UserACL: database.ChatACL{alice.ID.String(): read, outsider.ID.String(): read}, + GroupACL: database.ChatACL{ + group.ID.String(): read, + orgID.String(): read, + foreignGroup.ID.String(): read, + uuid.NewString(): read, + }, + })) + private := createChatProject(t, client, orgID, "Counts Private") + + projects, err := client.ListChatProjects(ctx) + require.NoError(t, err) + type counts struct { + members, groups int + everyone bool + } + got := make(map[uuid.UUID]counts, len(projects)) + for _, project := range projects { + got[project.ID] = counts{project.MemberCount, project.GroupCount, project.SharedWithEveryone} + } + require.Equal(t, counts{2, 3, true}, got[shared.ID]) + require.Equal(t, counts{1, 0, false}, got[private.ID]) + + acl, err := client.ChatProjectACL(ctx, orgID, shared.ID) + require.NoError(t, err) + require.Len(t, acl.Users, got[shared.ID].members-1) + require.Len(t, acl.Groups, got[shared.ID].groups) +} + func newChatProjectMember(t testing.TB, client *codersdk.ExperimentalClient, organizationID uuid.UUID) (*codersdk.ExperimentalClient, codersdk.User) { t.Helper() raw, user := coderdtest.CreateAnotherUser(t, client.Client, organizationID) diff --git a/coderd/chat_project_pins.go b/coderd/chat_project_pins.go index 8e3ab146060..c0d9f7e5c2f 100644 --- a/coderd/chat_project_pins.go +++ b/coderd/chat_project_pins.go @@ -7,14 +7,46 @@ import ( "golang.org/x/xerrors" "github.com/coder/coder/v2/coderd/database" + "github.com/coder/coder/v2/coderd/database/db2sdk" "github.com/coder/coder/v2/coderd/httpapi" "github.com/coder/coder/v2/coderd/httpmw" "github.com/coder/coder/v2/coderd/rbac" "github.com/coder/coder/v2/coderd/rbac/policy" + "github.com/coder/coder/v2/coderd/util/slice" "github.com/coder/coder/v2/coderd/x/chatd" "github.com/coder/coder/v2/codersdk" ) +// @Summary List chat project summaries +// @ID list-chat-project-summaries +// @Security CoderSessionToken +// @Tags Chats +// @Produce json +// @Success 200 {array} codersdk.ChatProjectSummary +// @Router /api/experimental/chats/projects/summaries [get] +// @x-apidocgen {"skip": true} +func (api *API) listChatProjectSummaries(rw http.ResponseWriter, r *http.Request) { + ctx := r.Context() + apiKey := httpmw.APIKey(r) + // Summaries carry the caller's pins, which are personal data. dbauthz + // refuses the read for an API key scoped without user:read_personal, + // so answer 403 here instead of failing the query. + if !api.Authorize(r, policy.ActionReadPersonal, rbac.ResourceUserObject(apiKey.UserID)) { + httpapi.Forbidden(rw) + return + } + + rows, err := api.Database.GetChatProjectSummariesByUserID(ctx, apiKey.UserID) + if err != nil { + httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ + Message: "Failed to list chat project summaries.", + Detail: err.Error(), + }) + return + } + httpapi.Write(ctx, rw, http.StatusOK, slice.List(rows, db2sdk.ChatProjectSummary)) +} + // @Summary Pin chat project // @ID pin-chat-project // @Security CoderSessionToken @@ -131,8 +163,8 @@ func (api *API) deleteChatProjectPin(rw http.ResponseWriter, r *http.Request) { // authorizeChatProjectPin writes a 404 and returns false unless the caller // owns the project or holds a grant on it that RBAC honors. -// The project list shows only those projects, so role-based read access -// alone would leave the pin invisible. +// Summaries list only those projects, so role-based read access alone would +// leave the pin invisible. func (api *API) authorizeChatProjectPin(rw http.ResponseWriter, r *http.Request, project database.ChatProject) bool { ctx := r.Context() userID := httpmw.APIKey(r).UserID diff --git a/coderd/chat_project_pins_test.go b/coderd/chat_project_pins_test.go index fcd08af4971..05be4bf565c 100644 --- a/coderd/chat_project_pins_test.go +++ b/coderd/chat_project_pins_test.go @@ -3,12 +3,12 @@ package coderd_test import ( "cmp" "context" - "database/sql" "fmt" "maps" "net/http" "slices" "testing" + "time" "github.com/google/uuid" "github.com/stretchr/testify/require" @@ -21,6 +21,7 @@ import ( "github.com/coder/coder/v2/coderd/rbac" "github.com/coder/coder/v2/coderd/rbac/policy" "github.com/coder/coder/v2/coderd/util/ptr" + "github.com/coder/coder/v2/coderd/util/slice" "github.com/coder/coder/v2/codersdk" "github.com/coder/coder/v2/testutil" ) @@ -29,9 +30,9 @@ func TestChatProjectPins(t *testing.T) { t.Parallel() ctx := testutil.Context(t, testutil.WaitLong) - client, sqlDB := newChatProjectPinsClient(t) + client, _ := newChatProjectClient(t) firstUser := coderdtest.CreateFirstUser(t, client.Client) - orgID, me := firstUser.OrganizationID, firstUser.UserID + orgID := firstUser.OrganizationID reorder := func(client *codersdk.ExperimentalClient, projectIDs ...uuid.UUID) error { return client.ReorderChatProjectPins(ctx, codersdk.ReorderChatProjectPinsRequest{ProjectIDs: projectIDs}) } @@ -40,36 +41,36 @@ func TestChatProjectPins(t *testing.T) { a := createChatProject(t, client, orgID, "Pin A") b := createChatProject(t, client, orgID, "Pin B") c := createChatProject(t, client, orgID, "Pin C") - requirePinnedProjects(ctx, t, sqlDB, me, a.ID, b.ID, c.ID) + requirePinnedProjects(ctx, t, client, a.ID, b.ID, c.ID) require.NoError(t, reorder(client, c.ID, a.ID, b.ID)) - requirePinnedProjects(ctx, t, sqlDB, me, c.ID, a.ID, b.ID) + requirePinnedProjects(ctx, t, client, c.ID, a.ID, b.ID) // Pins left out of the list follow the listed ones in their order. require.NoError(t, reorder(client, b.ID)) - requirePinnedProjects(ctx, t, sqlDB, me, b.ID, c.ID, a.ID) + requirePinnedProjects(ctx, t, client, b.ID, c.ID, a.ID) // Unpinning keeps the other pins in order, and repeating it changes // nothing. require.NoError(t, client.UnpinChatProject(ctx, orgID, c.ID)) require.NoError(t, client.UnpinChatProject(ctx, orgID, c.ID)) - requirePinnedProjects(ctx, t, sqlDB, me, b.ID, a.ID) + requirePinnedProjects(ctx, t, client, b.ID, a.ID) // A reorder skips a project that is not pinned, such as one another // tab just unpinned, and does not pin it. require.NoError(t, reorder(client, c.ID, a.ID, b.ID)) - requirePinnedProjects(ctx, t, sqlDB, me, a.ID, b.ID) + requirePinnedProjects(ctx, t, client, a.ID, b.ID) // A re-pinned project goes to the end and an existing pin keeps its // place. require.NoError(t, client.PinChatProject(ctx, orgID, c.ID)) require.NoError(t, client.PinChatProject(ctx, orgID, a.ID)) - requirePinnedProjects(ctx, t, sqlDB, me, a.ID, b.ID, c.ID) + requirePinnedProjects(ctx, t, client, a.ID, b.ID, c.ID) // Pins need read access. Sharing does not pin, and a pin that outlives // access stays hidden. other, otherUser := newChatProjectMember(t, client, orgID) requireSDKError(t, other.PinChatProject(ctx, orgID, a.ID), http.StatusNotFound) - // Role-based read access is not enough: the project is missing from the - // site owner's project list. + // Role-based read access is not enough: the project would be missing + // from the site owner's summaries. otherOwn := createChatProject(t, other, orgID, "Pin Other") requireSDKError(t, client.PinChatProject(ctx, orgID, otherOwn.ID), http.StatusNotFound) requireSDKError(t, client.UnpinChatProject(ctx, orgID, otherOwn.ID), http.StatusNotFound) @@ -79,16 +80,19 @@ func TestChatProjectPins(t *testing.T) { })) } setRole(codersdk.ChatProjectRoleUse) - requirePinnedProjects(ctx, t, sqlDB, otherUser.ID, otherOwn.ID) + requirePinnedProjects(ctx, t, other, otherOwn.ID) require.NoError(t, other.PinChatProject(ctx, orgID, a.ID)) - requirePinnedProjects(ctx, t, sqlDB, otherUser.ID, otherOwn.ID, a.ID) + requirePinnedProjects(ctx, t, other, otherOwn.ID, a.ID) setRole(codersdk.ChatProjectRoleDeleted) + require.NotContains(t, chatProjectSummariesByID(ctx, t, other), a.ID) requireSDKError(t, other.UnpinChatProject(ctx, orgID, a.ID), http.StatusNotFound) // The caller cannot list a pin they no longer see, so a reorder keeps - // it after the listed pins. + // it after the listed pins, where it shows again with the access. otherNew := createChatProject(t, other, orgID, "Pin Other New") require.NoError(t, reorder(other, otherNew.ID, otherOwn.ID)) - requirePinnedProjects(ctx, t, sqlDB, otherUser.ID, otherNew.ID, otherOwn.ID, a.ID) + requirePinnedProjects(ctx, t, other, otherNew.ID, otherOwn.ID) + setRole(codersdk.ChatProjectRoleUse) + requirePinnedProjects(ctx, t, other, otherNew.ID, otherOwn.ID, a.ID) } // TestChatProjectPinsTokenScope checks that a pin, as the caller's personal @@ -136,15 +140,21 @@ func TestChatProjectPinsTokenScope(t *testing.T) { requireSDKError(t, err, http.StatusForbidden) _, err = newScopedClient("chat_project:create", "chat_project:read", "user:update_personal").CreateChatProject(ctx, orgID, createReq) require.NoError(t, err) + + // Summaries carry the caller's pins, so listing them needs + // user:read_personal. + _, err = readOnly.ListChatProjectSummaries(ctx) + requireSDKError(t, err, http.StatusForbidden) + _, err = newScopedClient("chat_project:read", "user:read_personal").ListChatProjectSummaries(ctx) + require.NoError(t, err) } func TestChatProjectPinsConcurrentWrites(t *testing.T) { t.Parallel() ctx := testutil.Context(t, testutil.WaitLong) - client, sqlDB := newChatProjectPinsClient(t) - firstUser := coderdtest.CreateFirstUser(t, client.Client) - orgID := firstUser.OrganizationID + client, _ := newChatProjectClient(t) + orgID := coderdtest.CreateFirstUser(t, client.Client).OrganizationID // Sixteen projects make overlapping writes collide reliably. projectIDs := make([]uuid.UUID, 16) want := make([]int32, len(projectIDs)) @@ -155,8 +165,11 @@ func TestChatProjectPinsConcurrentWrites(t *testing.T) { // Every pin holds its own position, with none skipped. requireDistinctPositions := func() { t.Helper() - pins := chatProjectPinOrders(ctx, t, sqlDB, firstUser.UserID) - require.ElementsMatch(t, want, slices.Collect(maps.Values(pins))) + summaries, err := client.ListChatProjectSummaries(ctx) + require.NoError(t, err) + require.ElementsMatch(t, want, slice.List(summaries, func(summary codersdk.ChatProjectSummary) int32 { + return summary.PinOrder + })) } for round := range 10 { @@ -190,6 +203,88 @@ func TestChatProjectPinsConcurrentWrites(t *testing.T) { } } +func TestChatProjectSummaries(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitLong) + db, ps := dbtestutil.NewDB(t) + client, api := newChatProjectClientWithAPI(t, func(options *coderdtest.Options) { + options.Database, options.Pubsub = db, ps + }) + firstUser := coderdtest.CreateFirstUser(t, client.Client) + orgID, me := firstUser.OrganizationID, firstUser.UserID + model := createChatModel(t, client) + aliceClient, alice := newChatProjectMember(t, client, orgID) + _, carol := newChatProjectMember(t, client, orgID) + newChat := func(project codersdk.ChatProject, owner uuid.UUID, status database.ChatStatus, reply bool, parent uuid.NullUUID) database.Chat { + chat := dbgen.Chat(t, api.Database, database.Chat{ + OrganizationID: orgID, OwnerID: owner, ProjectID: uuid.NullUUID{UUID: project.ID, Valid: true}, + LastModelConfigID: model.ID, Status: status, ParentChatID: parent, RootChatID: parent, + }) + if reply { + dbgen.ChatMessage(t, api.Database, database.ChatMessage{ChatID: chat.ID, Role: database.ChatMessageRoleAssistant}) + } + return chat + } + share := func(name string, users ...uuid.UUID) codersdk.ChatProject { + project := createChatProject(t, client, orgID, name) + acl := codersdk.UpdateChatProjectACL{UserRoles: map[string]codersdk.ChatProjectRole{}} + for _, id := range users { + acl.UserRoles[id.String()] = codersdk.ChatProjectRoleUse + } + require.NoError(t, client.UpdateChatProjectACL(ctx, orgID, project.ID, acl)) + return project + } + none := uuid.NullUUID{} + + busy := share("Summary Busy", alice.ID) + unread := newChat(busy, me, database.ChatStatusWaiting, true, none) + running := newChat(busy, me, database.ChatStatusRunning, false, none) + paused := newChat(busy, me, database.ChatStatusPaused, false, none) + // Child chats, archived chats and other users' chats are not counted. + quiet := share("Summary Quiet", carol.ID) + read := newChat(quiet, me, database.ChatStatusWaiting, false, none) + newChat(quiet, me, database.ChatStatusError, false, uuid.NullUUID{UUID: read.ID, Valid: true}) + archived := newChat(quiet, me, database.ChatStatusError, true, none) + require.NoError(t, client.UpdateChat(ctx, archived.ID, codersdk.UpdateChatRequest{Archived: ptr.Ref(true)})) + newChat(quiet, carol.ID, database.ChatStatusRunning, true, none) + // A chat that is being stopped still counts as running. + stopping := share("Summary Stopping") + interrupting := newChat(stopping, me, database.ChatStatusInterrupting, false, none) + idle := share("Summary Idle") + + type summary struct { + chats, unread int64 + running, attention bool + lastActivity time.Time + } + latestUpdate := func(chats ...database.Chat) time.Time { + var latest time.Time + for _, chat := range chats { + fetched, err := client.GetChat(ctx, chat.ID) + require.NoError(t, err) + if fetched.UpdatedAt.After(latest) { + latest = fetched.UpdatedAt.UTC() + } + } + return latest + } + summaries := chatProjectSummariesByID(ctx, t, client) + for project, want := range map[uuid.UUID]summary{ + busy.ID: {3, 1, true, true, latestUpdate(unread, running, paused)}, + quiet.ID: {1, 0, false, false, latestUpdate(read)}, + stopping.ID: {1, 0, true, false, latestUpdate(interrupting)}, + idle.ID: {0, 0, false, false, time.Time{}}, + } { + got := summaries[project] + require.True(t, got.Pinned) + lastActivity := ptr.NilToDefault(got.LastActivityAt, time.Time{}).UTC() + gotSummary := summary{got.OwnChatCount, got.OwnUnreadCount, got.OwnRunning, got.OwnNeedsAttention, lastActivity} + require.Equal(t, want, gotSummary, project) + } + requireSummariesMatchList(ctx, t, aliceClient) +} + //nolint:paralleltest // Disabling chat sharing flips a process-wide RBAC switch. func TestChatProjectsSharingDisabled(t *testing.T) { previous := rbac.ChatACLDisabled() @@ -215,6 +310,11 @@ func TestChatProjectsSharingDisabled(t *testing.T) { UserACL: database.ChatACL{}, GroupACL: database.ChatACL{orgID.String(): {Permissions: []policy.Action{policy.ActionRead}}}, })) + listed, err := client.GetChatProject(ctx, orgID, project.ID) + require.NoError(t, err) + require.Equal(t, 1, listed.MemberCount) + require.Zero(t, listed.GroupCount) + require.False(t, listed.SharedWithEveryone) // The member cannot open the project, so no project list reaches their // chat in it and the main list keeps it. @@ -226,9 +326,12 @@ func TestChatProjectsSharingDisabled(t *testing.T) { require.NoError(t, err) require.Contains(t, chatIDs(memberChats), chat.ID) + memberProject := createChatProject(t, member, orgID, "Member Project") + require.NotContains(t, chatProjectSummariesByID(ctx, t, member), project.ID) + requireSummariesMatchList(ctx, t, member) + // Only the owner can pin a project, even when a role reads it and a // grant from before sharing was disabled names the caller. - memberProject := createChatProject(t, member, orgID, "Member Project") require.NoError(t, db.UpdateChatProjectACLByID(ctx, database.UpdateChatProjectACLByIDParams{ ID: memberProject.ID, UserACL: database.ChatACL{firstUser.UserID.String(): {Permissions: []policy.Action{policy.ActionRead}}}, @@ -236,6 +339,10 @@ func TestChatProjectsSharingDisabled(t *testing.T) { })) requireSDKError(t, client.PinChatProject(ctx, orgID, memberProject.ID), http.StatusNotFound) require.NoError(t, member.PinChatProject(ctx, orgID, memberProject.ID)) + // The owner role still reads such a project, so the summaries list it, + // as the project list does. + require.Contains(t, chatProjectSummariesByID(ctx, t, client), memberProject.ID) + requireSummariesMatchList(ctx, t, client) } func TestListChatsExcludeOwnProjectChats(t *testing.T) { @@ -368,41 +475,34 @@ func TestListChatsIgnoresOtherUsersChatPins(t *testing.T) { require.ElementsMatch(t, want, chatIDs(memberChats)) } -// newChatProjectPinsClient returns a client and a connection to its -// database for reading pin rows. -func newChatProjectPinsClient(t testing.TB) (*codersdk.ExperimentalClient, *sql.DB) { +func chatProjectSummariesByID(ctx context.Context, t testing.TB, client *codersdk.ExperimentalClient) map[uuid.UUID]codersdk.ChatProjectSummary { t.Helper() - db, ps, sqlDB := dbtestutil.NewDBWithSQLDB(t) - client, _ := newChatProjectClient(t, func(options *coderdtest.Options) { - options.Database, options.Pubsub = db, ps - }) - return client, sqlDB -} - -// chatProjectPinOrders reads the stored order of each of the user's pins. -func chatProjectPinOrders(ctx context.Context, t testing.TB, sqlDB *sql.DB, userID uuid.UUID) map[uuid.UUID]int32 { - t.Helper() - rows, err := sqlDB.QueryContext(ctx, `SELECT project_id, pin_order FROM chat_project_pins WHERE user_id = $1`, userID) + summaries, err := client.ListChatProjectSummaries(ctx) require.NoError(t, err) - defer rows.Close() - pins := map[uuid.UUID]int32{} - for rows.Next() { - var projectID uuid.UUID - var order int32 - require.NoError(t, rows.Scan(&projectID, &order)) - pins[projectID] = order + byID := make(map[uuid.UUID]codersdk.ChatProjectSummary, len(summaries)) + for _, summary := range summaries { + byID[summary.ProjectID] = summary } - require.NoError(t, rows.Err()) - return pins + return byID } -// requirePinnedProjects checks which projects the user has pinned, in pin -// order. Pins on projects the user can no longer see count too. -func requirePinnedProjects(ctx context.Context, t testing.TB, sqlDB *sql.DB, userID uuid.UUID, want ...uuid.UUID) { +// requireSummariesMatchList checks that the summaries, which clients join to +// the project list by ID, cover exactly its projects. +func requireSummariesMatchList(ctx context.Context, t testing.TB, client *codersdk.ExperimentalClient) { t.Helper() - pins := chatProjectPinOrders(ctx, t, sqlDB, userID) - got := slices.SortedFunc(maps.Keys(pins), func(a, b uuid.UUID) int { - return cmp.Compare(pins[a], pins[b]) - }) - require.Equal(t, want, got) + projects, err := client.ListChatProjects(ctx) + require.NoError(t, err) + projectIDs := slice.List(projects, func(project codersdk.ChatProject) uuid.UUID { return project.ID }) + require.ElementsMatch(t, projectIDs, slices.Collect(maps.Keys(chatProjectSummariesByID(ctx, t, client)))) +} + +// requirePinnedProjects checks which projects the summaries report as +// pinned for the caller, in pin order. +func requirePinnedProjects(ctx context.Context, t testing.TB, client *codersdk.ExperimentalClient, want ...uuid.UUID) { + t.Helper() + summaries, err := client.ListChatProjectSummaries(ctx) + require.NoError(t, err) + pinned := slice.Filter(summaries, func(summary codersdk.ChatProjectSummary) bool { return summary.Pinned }) + slices.SortFunc(pinned, func(a, b codersdk.ChatProjectSummary) int { return cmp.Compare(a.PinOrder, b.PinOrder) }) + require.Equal(t, want, slice.List(pinned, func(summary codersdk.ChatProjectSummary) uuid.UUID { return summary.ProjectID })) } diff --git a/coderd/chat_projects.go b/coderd/chat_projects.go index 58c47b8c00b..6c105ffe7e7 100644 --- a/coderd/chat_projects.go +++ b/coderd/chat_projects.go @@ -372,7 +372,7 @@ func (api *API) writeChatProject(rw http.ResponseWriter, r *http.Request, status converted, err := api.convertChatProjects(r, []database.ChatProject{project}) if err != nil { httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ - Message: "Failed to load chat project templates.", + Message: "Failed to load chat project.", Detail: err.Error(), }) return @@ -381,13 +381,18 @@ func (api *API) writeChatProject(rw http.ResponseWriter, r *http.Request, status } // convertChatProjects converts projects with the caller's permissions on -// them and the attached templates the caller can access. +// them, the attached templates the caller can access and how many users and +// groups they are shared with. func (api *API) convertChatProjects(r *http.Request, projects []database.ChatProject) ([]codersdk.ChatProject, error) { ctx := r.Context() templates, err := chattool.LoadProjectsTemplates(ctx, api.Database, projects) if err != nil { return nil, err } + shareCounts, err := api.chatProjectsShareCounts(ctx, projects) + if err != nil { + return nil, err + } subject := httpmw.UserAuthorization(ctx) return slice.List(projects, func(project database.ChatProject) codersdk.ChatProject { obj := project.RBACObject() @@ -396,11 +401,17 @@ func (api *API) convertChatProjects(r *http.Request, projects []database.ChatPro can := func(action policy.Action) bool { return api.HTTPAuth.Authorizer.Authorize(ctx, subject, action, obj) == nil } - return db2sdk.ChatProject(project, codersdk.ChatProjectPermissions{ + converted := db2sdk.ChatProject(project, codersdk.ChatProjectPermissions{ Update: can(policy.ActionUpdate), Delete: can(policy.ActionDelete), Share: can(policy.ActionShare), }, templates[project.ID]) + counts := shareCounts[project.ID] + // The owner is always a member. + converted.MemberCount = 1 + counts.users + converted.GroupCount = counts.groups + converted.SharedWithEveryone = counts.everyone + return converted }), nil } diff --git a/coderd/chat_routes.go b/coderd/chat_routes.go index 9c173593cf6..83d283b45d7 100644 --- a/coderd/chat_routes.go +++ b/coderd/chat_routes.go @@ -116,6 +116,7 @@ func (api *API) registerExperimentalChatRoutes(r chi.Router, apiKeyMiddleware fu r.Route("/chats", func(r chi.Router) { r.Use(apiKeyMiddleware) r.Get("/projects", api.listChatProjects) + r.Get("/projects/summaries", api.listChatProjectSummaries) r.Put("/projects/pins/order", api.putChatProjectPinOrder) // Reserve the promoted /config segment so it returns 404 instead // of falling into the {chat} wildcard and failing UUID parsing diff --git a/coderd/database/db2sdk/db2sdk.go b/coderd/database/db2sdk/db2sdk.go index caaa963f5ef..82fc9852a63 100644 --- a/coderd/database/db2sdk/db2sdk.go +++ b/coderd/database/db2sdk/db2sdk.go @@ -2155,6 +2155,20 @@ func ChatProject(project database.ChatProject, permissions codersdk.ChatProjectP return converted } +// ChatProjectSummary converts a project summary row. +func ChatProjectSummary(row database.GetChatProjectSummariesByUserIDRow) codersdk.ChatProjectSummary { + return codersdk.ChatProjectSummary{ + ProjectID: row.ProjectID, + Pinned: row.Pinned, + PinOrder: row.PinOrder, + OwnChatCount: row.OwnChatCount, + OwnUnreadCount: row.OwnUnreadCount, + OwnRunning: row.OwnRunning, + OwnNeedsAttention: row.OwnNeedsAttention, + LastActivityAt: nullTimePtr(row.LastActivityAt), + } +} + // ChatProjectInstructions converts a project's stored instructions. func ChatProjectInstructions(row database.GetChatProjectInstructionsByProjectIDRow) codersdk.ChatProjectInstructions { updatedAt := row.ChatProjectInstruction.UpdatedAt diff --git a/coderd/database/dbauthz/dbauthz.go b/coderd/database/dbauthz/dbauthz.go index 843c2a554d8..1b06bdd4b80 100644 --- a/coderd/database/dbauthz/dbauthz.go +++ b/coderd/database/dbauthz/dbauthz.go @@ -3885,6 +3885,33 @@ func (q *querier) GetChatProjectMemoryByName(ctx context.Context, arg database.G return row, nil } +// GetChatProjectSummariesByUserID returns a user's pins and chat counts, +// which are that user's personal data, so the read is authorized on the +// user as well as on each project. +func (q *querier) GetChatProjectSummariesByUserID(ctx context.Context, userID uuid.UUID) ([]database.GetChatProjectSummariesByUserIDRow, error) { + // The row count at or above which rows are authorized with one partial + // evaluation instead of a full evaluation each. Clients refetch + // summaries on chat watch events, and for an organization member a + // partial evaluation measured about 6 ms against about 0.03 ms per row, + // so rbac.DefaultFilterThreshold would make nearly every refetch pay + // for a partial evaluation that only a list of about 200 projects + // recovers. + const filterThreshold = 200 + + if err := q.authorizeContext(ctx, policy.ActionReadPersonal, rbac.ResourceUserObject(userID)); err != nil { + return nil, err + } + act, ok := ActorFromContext(ctx) + if !ok { + return nil, ErrNoActor + } + rows, err := q.db.GetChatProjectSummariesByUserID(ctx, userID) + if err != nil { + return nil, xerrors.Errorf("fetch object: %w", err) + } + return rbac.Filter(ctx, q.auth, act, policy.ActionRead, rows, filterThreshold) +} + // GetChatProjectTemplatesByProjectIDs authorizes each attachment through its // project. It does not check the attached templates, so callers must not // expose a template the actor cannot read. diff --git a/coderd/database/dbauthz/dbauthz_test.go b/coderd/database/dbauthz/dbauthz_test.go index 21eb9e300bc..9f9e9b837e2 100644 --- a/coderd/database/dbauthz/dbauthz_test.go +++ b/coderd/database/dbauthz/dbauthz_test.go @@ -1394,6 +1394,16 @@ func (s *MethodTestSuite) TestChats() { dbm.EXPECT().GetChatProjectsOwnedOrSharedWithUserID(gomock.Any(), userID).Return(rows, nil).AnyTimes() check.Args(userID).Asserts(project, policy.ActionRead).Returns(rows) })) + s.Run("GetChatProjectSummariesByUserID", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) { + userID := uuid.New() + project := testutil.Fake(s.T(), faker, database.ChatProject{OwnerID: userID}) + rows := []database.GetChatProjectSummariesByUserIDRow{{ + ProjectID: project.ID, OrganizationID: project.OrganizationID, OwnerID: project.OwnerID, + UserACL: project.UserACL, GroupACL: project.GroupACL, Pinned: true, PinOrder: 1, + }} + dbm.EXPECT().GetChatProjectSummariesByUserID(gomock.Any(), userID).Return(rows, nil).AnyTimes() + check.Args(userID).Asserts(rbac.ResourceUserObject(userID), policy.ActionReadPersonal, project, policy.ActionRead).Returns(rows) + })) s.Run("PinChatProject", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) { project := testutil.Fake(s.T(), faker, database.ChatProject{}) arg := database.PinChatProjectParams{UserID: uuid.New(), ProjectID: project.ID} diff --git a/coderd/database/dbgen/dbgen.go b/coderd/database/dbgen/dbgen.go index 93fede16a10..a00e7cbd2d3 100644 --- a/coderd/database/dbgen/dbgen.go +++ b/coderd/database/dbgen/dbgen.go @@ -101,6 +101,17 @@ func ChatProject(t testing.TB, db database.Store, seed database.ChatProject) dat return project } +// ChatProjectPin pins a project for a user at the end of their list. +func ChatProjectPin(t testing.TB, db database.Store, seed database.ChatProjectPin) { + t.Helper() + + err := db.PinChatProject(genCtx, database.PinChatProjectParams{ + UserID: seed.UserID, + ProjectID: seed.ProjectID, + }) + require.NoError(t, err, "pin chat project") +} + // ChatProjectTemplate attaches a template to a chat project. func ChatProjectTemplate(t testing.TB, db database.Store, seed database.ChatProjectTemplate) database.ChatProjectTemplate { t.Helper() diff --git a/coderd/database/dbmetrics/querymetrics.go b/coderd/database/dbmetrics/querymetrics.go index 63194f419a2..b3bf2c6b955 100644 --- a/coderd/database/dbmetrics/querymetrics.go +++ b/coderd/database/dbmetrics/querymetrics.go @@ -1928,6 +1928,14 @@ func (m queryMetricsStore) GetChatProjectMemoryByName(ctx context.Context, arg d return r0, r1 } +func (m queryMetricsStore) GetChatProjectSummariesByUserID(ctx context.Context, arg uuid.UUID) ([]database.GetChatProjectSummariesByUserIDRow, error) { + start := time.Now() + r0, r1 := m.s.GetChatProjectSummariesByUserID(ctx, arg) + m.queryLatencies.WithLabelValues("GetChatProjectSummariesByUserID").Observe(time.Since(start).Seconds()) + m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "GetChatProjectSummariesByUserID").Inc() + return r0, r1 +} + func (m queryMetricsStore) GetChatProjectTemplatesByProjectIDs(ctx context.Context, projectIds []uuid.UUID) ([]database.GetChatProjectTemplatesByProjectIDsRow, error) { start := time.Now() r0, r1 := m.s.GetChatProjectTemplatesByProjectIDs(ctx, projectIds) diff --git a/coderd/database/dbmock/dbmock.go b/coderd/database/dbmock/dbmock.go index db87e62de0a..f450d18a68f 100644 --- a/coderd/database/dbmock/dbmock.go +++ b/coderd/database/dbmock/dbmock.go @@ -3625,6 +3625,21 @@ func (mr *MockStoreMockRecorder) GetChatProjectMemoryByName(ctx, arg any) *gomoc return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetChatProjectMemoryByName", reflect.TypeOf((*MockStore)(nil).GetChatProjectMemoryByName), ctx, arg) } +// GetChatProjectSummariesByUserID mocks base method. +func (m *MockStore) GetChatProjectSummariesByUserID(ctx context.Context, userID uuid.UUID) ([]database.GetChatProjectSummariesByUserIDRow, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetChatProjectSummariesByUserID", ctx, userID) + ret0, _ := ret[0].([]database.GetChatProjectSummariesByUserIDRow) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetChatProjectSummariesByUserID indicates an expected call of GetChatProjectSummariesByUserID. +func (mr *MockStoreMockRecorder) GetChatProjectSummariesByUserID(ctx, userID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetChatProjectSummariesByUserID", reflect.TypeOf((*MockStore)(nil).GetChatProjectSummariesByUserID), ctx, userID) +} + // GetChatProjectTemplatesByProjectIDs mocks base method. func (m *MockStore) GetChatProjectTemplatesByProjectIDs(ctx context.Context, projectIds []uuid.UUID) ([]database.GetChatProjectTemplatesByProjectIDsRow, error) { m.ctrl.T.Helper() diff --git a/coderd/database/modelmethods.go b/coderd/database/modelmethods.go index 0df77fdb2fd..5a9fdc11254 100644 --- a/coderd/database/modelmethods.go +++ b/coderd/database/modelmethods.go @@ -221,6 +221,18 @@ func (p ChatProject) RBACObject() rbac.Object { WithGroupACL(p.GroupACL.RBACACL()) } +// RBACObject authorizes a summary through its project, which the row +// carries only the authorization columns of. +func (r GetChatProjectSummariesByUserIDRow) RBACObject() rbac.Object { + return ChatProject{ + ID: r.ProjectID, + OrganizationID: r.OrganizationID, + OwnerID: r.OwnerID, + UserACL: r.UserACL, + GroupACL: r.GroupACL, + }.RBACObject() +} + // RBACObject authorizes an attachment through its project. Access to the // attached template is a separate check, because an attachment never grants // access to its template. diff --git a/coderd/database/querier.go b/coderd/database/querier.go index 1d67b1c099b..7d6255a187a 100644 --- a/coderd/database/querier.go +++ b/coderd/database/querier.go @@ -563,6 +563,16 @@ type sqlcQuerier interface { GetChatProjectMemoriesByProjectID(ctx context.Context, projectID uuid.UUID) ([]GetChatProjectMemoriesByProjectIDRow, error) GetChatProjectMemoryByID(ctx context.Context, id uuid.UUID) (GetChatProjectMemoryByIDRow, error) GetChatProjectMemoryByName(ctx context.Context, arg GetChatProjectMemoryByNameParams) (GetChatProjectMemoryByNameRow, error) + // Returns the user's pin and aggregates over the user's own top-level, + // non-archived chats for each project from + // GetChatProjectsOwnedOrSharedWithUserID. The project columns only serve + // authorization: entries match regardless of the actions they grant, so + // callers must authorize each row. Pins on projects the user can no longer + // see are never returned. + // Grant keys select candidates even while chat sharing is disabled, as in + // GetChatProjectsOwnedOrSharedWithUserID: a role can still let the caller + // read the project. + GetChatProjectSummariesByUserID(ctx context.Context, userID uuid.UUID) ([]GetChatProjectSummariesByUserIDRow, error) // Lists the templates attached to the given projects, oldest attachment // first. Deleted, deprecated, and agent-disabled templates are left out // because no chat can use them, whoever asks. The rows are not filtered by diff --git a/coderd/database/queries.sql.go b/coderd/database/queries.sql.go index 2d1cb6121f3..489e821f321 100644 --- a/coderd/database/queries.sql.go +++ b/coderd/database/queries.sql.go @@ -8485,6 +8485,107 @@ func (q *sqlQuerier) InsertChatProjectMemory(ctx context.Context, arg InsertChat return i, err } +const getChatProjectSummariesByUserID = `-- name: GetChatProjectSummariesByUserID :many +WITH own_chats AS ( + -- Read through idx_chats_owner. + SELECT + c.project_id, + COUNT(*) AS chat_count, + -- Same rule as has_unread in GetChats. + COUNT(*) FILTER (WHERE EXISTS ( + SELECT 1 FROM chat_messages cm + WHERE cm.chat_id = c.id AND cm.role = 'assistant' AND cm.deleted = false + AND cm.id > COALESCE(c.last_read_message_id, 0) + )) AS unread_count, + bool_or(c.status IN ('running', 'interrupting')) AS running, + bool_or(c.status IN ('requires_action', 'error', 'paused')) AS needs_attention, + MAX(c.updated_at)::timestamptz AS last_activity_at + FROM chats c + WHERE c.owner_id = $1::uuid AND c.project_id IS NOT NULL AND c.parent_chat_id IS NULL AND c.archived = false + GROUP BY c.project_id +) +SELECT + chat_projects.id AS project_id, + chat_projects.organization_id, + chat_projects.owner_id, + chat_projects.user_acl, + chat_projects.group_acl, + (pins.project_id IS NOT NULL)::boolean AS pinned, + -- The stored order: it sorts the pins, and its values can have gaps. + COALESCE(pins.pin_order, 0)::integer AS pin_order, + COALESCE(own_chats.chat_count, 0)::bigint AS own_chat_count, + COALESCE(own_chats.unread_count, 0)::bigint AS own_unread_count, + COALESCE(own_chats.running, false)::boolean AS own_running, + COALESCE(own_chats.needs_attention, false)::boolean AS own_needs_attention, + own_chats.last_activity_at +FROM chat_projects +LEFT JOIN chat_project_pins pins + ON pins.user_id = $1::uuid AND pins.project_id = chat_projects.id +LEFT JOIN own_chats ON own_chats.project_id = chat_projects.id +WHERE chat_projects.id IN (SELECT project_id FROM chat_project_ids_for_user($1::uuid, true)) +ORDER BY lower(chat_projects.name), chat_projects.id +` + +type GetChatProjectSummariesByUserIDRow struct { + ProjectID uuid.UUID `db:"project_id" json:"project_id"` + OrganizationID uuid.UUID `db:"organization_id" json:"organization_id"` + OwnerID uuid.UUID `db:"owner_id" json:"owner_id"` + UserACL ChatACL `db:"user_acl" json:"user_acl"` + GroupACL ChatACL `db:"group_acl" json:"group_acl"` + Pinned bool `db:"pinned" json:"pinned"` + PinOrder int32 `db:"pin_order" json:"pin_order"` + OwnChatCount int64 `db:"own_chat_count" json:"own_chat_count"` + OwnUnreadCount int64 `db:"own_unread_count" json:"own_unread_count"` + OwnRunning bool `db:"own_running" json:"own_running"` + OwnNeedsAttention bool `db:"own_needs_attention" json:"own_needs_attention"` + LastActivityAt sql.NullTime `db:"last_activity_at" json:"last_activity_at"` +} + +// Returns the user's pin and aggregates over the user's own top-level, +// non-archived chats for each project from +// GetChatProjectsOwnedOrSharedWithUserID. The project columns only serve +// authorization: entries match regardless of the actions they grant, so +// callers must authorize each row. Pins on projects the user can no longer +// see are never returned. +// Grant keys select candidates even while chat sharing is disabled, as in +// GetChatProjectsOwnedOrSharedWithUserID: a role can still let the caller +// read the project. +func (q *sqlQuerier) GetChatProjectSummariesByUserID(ctx context.Context, userID uuid.UUID) ([]GetChatProjectSummariesByUserIDRow, error) { + rows, err := q.db.QueryContext(ctx, getChatProjectSummariesByUserID, userID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []GetChatProjectSummariesByUserIDRow + for rows.Next() { + var i GetChatProjectSummariesByUserIDRow + if err := rows.Scan( + &i.ProjectID, + &i.OrganizationID, + &i.OwnerID, + &i.UserACL, + &i.GroupACL, + &i.Pinned, + &i.PinOrder, + &i.OwnChatCount, + &i.OwnUnreadCount, + &i.OwnRunning, + &i.OwnNeedsAttention, + &i.LastActivityAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const pinChatProject = `-- name: PinChatProject :exec INSERT INTO chat_project_pins (user_id, project_id, pin_order) SELECT $1::uuid, $2::uuid, COALESCE(MAX(pin_order), 0) + 1 diff --git a/coderd/database/queries/chatprojectpins.sql b/coderd/database/queries/chatprojectpins.sql index 5cf97e2c89f..e404324a67f 100644 --- a/coderd/database/queries/chatprojectpins.sql +++ b/coderd/database/queries/chatprojectpins.sql @@ -32,3 +32,52 @@ WHERE p.user_id = @user_id::uuid AND p.project_id = ranked.project_id; -- next reorder. DELETE FROM chat_project_pins WHERE user_id = @user_id::uuid AND project_id = @project_id::uuid; + +-- name: GetChatProjectSummariesByUserID :many +-- Returns the user's pin and aggregates over the user's own top-level, +-- non-archived chats for each project from +-- GetChatProjectsOwnedOrSharedWithUserID. The project columns only serve +-- authorization: entries match regardless of the actions they grant, so +-- callers must authorize each row. Pins on projects the user can no longer +-- see are never returned. +WITH own_chats AS ( + -- Read through idx_chats_owner. + SELECT + c.project_id, + COUNT(*) AS chat_count, + -- Same rule as has_unread in GetChats. + COUNT(*) FILTER (WHERE EXISTS ( + SELECT 1 FROM chat_messages cm + WHERE cm.chat_id = c.id AND cm.role = 'assistant' AND cm.deleted = false + AND cm.id > COALESCE(c.last_read_message_id, 0) + )) AS unread_count, + bool_or(c.status IN ('running', 'interrupting')) AS running, + bool_or(c.status IN ('requires_action', 'error', 'paused')) AS needs_attention, + MAX(c.updated_at)::timestamptz AS last_activity_at + FROM chats c + WHERE c.owner_id = @user_id::uuid AND c.project_id IS NOT NULL AND c.parent_chat_id IS NULL AND c.archived = false + GROUP BY c.project_id +) +SELECT + chat_projects.id AS project_id, + chat_projects.organization_id, + chat_projects.owner_id, + chat_projects.user_acl, + chat_projects.group_acl, + (pins.project_id IS NOT NULL)::boolean AS pinned, + -- The stored order: it sorts the pins, and its values can have gaps. + COALESCE(pins.pin_order, 0)::integer AS pin_order, + COALESCE(own_chats.chat_count, 0)::bigint AS own_chat_count, + COALESCE(own_chats.unread_count, 0)::bigint AS own_unread_count, + COALESCE(own_chats.running, false)::boolean AS own_running, + COALESCE(own_chats.needs_attention, false)::boolean AS own_needs_attention, + own_chats.last_activity_at +FROM chat_projects +LEFT JOIN chat_project_pins pins + ON pins.user_id = @user_id::uuid AND pins.project_id = chat_projects.id +LEFT JOIN own_chats ON own_chats.project_id = chat_projects.id +-- Grant keys select candidates even while chat sharing is disabled, as in +-- GetChatProjectsOwnedOrSharedWithUserID: a role can still let the caller +-- read the project. +WHERE chat_projects.id IN (SELECT project_id FROM chat_project_ids_for_user(@user_id::uuid, true)) +ORDER BY lower(chat_projects.name), chat_projects.id; diff --git a/codersdk/chats.go b/codersdk/chats.go index efb2759ced0..fa545cf67d2 100644 --- a/codersdk/chats.go +++ b/codersdk/chats.go @@ -249,9 +249,20 @@ type ChatProject struct { // DefaultTemplate is omitted when the project has none or the caller // cannot access it. DefaultTemplate *ChatProjectDefaultTemplate `json:"default_template,omitempty"` - CreatedAt time.Time `json:"created_at" format:"date-time"` - UpdatedAt time.Time `json:"updated_at" format:"date-time"` - Permissions ChatProjectPermissions `json:"permissions"` + // MemberCount is the owner plus the users the project is shared with + // directly, as ChatProjectACL lists them. Members of shared groups are + // not counted. It is 1 while chat sharing is unavailable. + MemberCount int `json:"member_count"` + // GroupCount is how many groups the project is shared with, as + // ChatProjectACL lists them, including the Everyone group. It is 0 while + // chat sharing is unavailable. + GroupCount int `json:"group_count"` + // SharedWithEveryone reports whether one of those groups is the Everyone + // group of the project's organization. + SharedWithEveryone bool `json:"shared_with_everyone"` + CreatedAt time.Time `json:"created_at" format:"date-time"` + UpdatedAt time.Time `json:"updated_at" format:"date-time"` + Permissions ChatProjectPermissions `json:"permissions"` } // ChatProjectPermissions are the actions the caller may take on a project. @@ -285,6 +296,23 @@ type ChatProjectDefaultTemplate struct { Parameters map[string]string `json:"parameters,omitempty"` } +// ChatProjectSummary is the caller's pin on a project and aggregates over +// the caller's own top-level, non-archived chats in it. The project itself +// comes from ListChatProjects. +type ChatProjectSummary struct { + ProjectID uuid.UUID `json:"project_id" format:"uuid"` + Pinned bool `json:"pinned"` + // PinOrder sorts pinned projects, lowest first, with gaps. 0 means not pinned. + PinOrder int32 `json:"pin_order"` + OwnChatCount int64 `json:"own_chat_count"` + OwnUnreadCount int64 `json:"own_unread_count"` + OwnRunning bool `json:"own_running"` + // OwnNeedsAttention reports a chat that requires action, failed, or is paused. + OwnNeedsAttention bool `json:"own_needs_attention"` + // LastActivityAt is the latest update to one of the caller's chats. + LastActivityAt *time.Time `json:"last_activity_at,omitempty" format:"date-time"` +} + // ReorderChatProjectPinsRequest sets the order of the caller's pinned chat // projects. type ReorderChatProjectPinsRequest struct { @@ -2693,6 +2721,12 @@ func (c *ExperimentalClient) DeleteChatProject(ctx context.Context, organization return nil } +// ListChatProjectSummaries lists the caller's pin and chat aggregates for +// each project from ListChatProjects. +func (c *ExperimentalClient) ListChatProjectSummaries(ctx context.Context) ([]ChatProjectSummary, error) { + return requestJSON[[]ChatProjectSummary](ctx, c.Client, http.MethodGet, "/api/experimental/chats/projects/summaries", http.StatusOK, nil) +} + // PinChatProject pins a chat project at the end of the caller's pins. A // project that is already pinned keeps its place. func (c *ExperimentalClient) PinChatProject(ctx context.Context, organizationID, projectID uuid.UUID) error { diff --git a/docs/reference/api/schemas.md b/docs/reference/api/schemas.md index e2ab9c5d86d..e5a230af00e 100644 --- a/docs/reference/api/schemas.md +++ b/docs/reference/api/schemas.md @@ -5177,10 +5177,12 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in "template_id": "c6d67e98-83ea-49f0-8812-e4abae2b68bc" }, "description": "string", + "group_count": 0, "hidden_template_count": 0, "icon": "string", "id": "497f6eca-6276-4993-bfeb-53cbbbba6f08", "limit_templates": true, + "member_count": 0, "name": "string", "organization_id": "7c60d51f-b44e-4682-87d6-449835ea4de6", "owner_id": "8826ee2e-7933-4665-aef2-2393f84a0d05", @@ -5189,6 +5191,7 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in "share": true, "update": true }, + "shared_with_everyone": true, "templates": [ { "display_name": "string", @@ -5203,21 +5206,24 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in ### Properties -| Name | Type | Required | Restrictions | Description | -|-------------------------|----------------------------------------------------------------------------|----------|--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `created_at` | string | false | | | -| `default_template` | [codersdk.ChatProjectDefaultTemplate](#codersdkchatprojectdefaulttemplate) | false | | Default template is omitted when the project has none or the caller cannot access it. | -| `description` | string | false | | | -| `hidden_template_count` | integer | false | | Hidden template count is the number of attached templates the caller cannot access. Nothing else about them is returned. | -| `icon` | string | false | | Icon is a URL, typically an emoji image under /emojis, or empty for the default folder glyph. | -| `id` | string | false | | | -| `limit_templates` | boolean | false | | Limit templates restricts the project's chats to its attached templates, and to none when nothing is attached. When false, the chats can use every template their owner can use. | -| `name` | string | false | | Name is a display label and is not unique; ID identifies the project. | -| `organization_id` | string | false | | | -| `owner_id` | string | false | | | -| `permissions` | [codersdk.ChatProjectPermissions](#codersdkchatprojectpermissions) | false | | | -| `templates` | array of [codersdk.ChatProjectTemplate](#codersdkchatprojecttemplate) | false | | Templates are the attached templates the caller can access. Deprecated templates and templates that do not allow agents are left out. | -| `updated_at` | string | false | | | +| Name | Type | Required | Restrictions | Description | +|-------------------------|----------------------------------------------------------------------------|----------|--------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `created_at` | string | false | | | +| `default_template` | [codersdk.ChatProjectDefaultTemplate](#codersdkchatprojectdefaulttemplate) | false | | Default template is omitted when the project has none or the caller cannot access it. | +| `description` | string | false | | | +| `group_count` | integer | false | | Group count is how many groups the project is shared with, as ChatProjectACL lists them, including the Everyone group. It is 0 while chat sharing is unavailable. | +| `hidden_template_count` | integer | false | | Hidden template count is the number of attached templates the caller cannot access. Nothing else about them is returned. | +| `icon` | string | false | | Icon is a URL, typically an emoji image under /emojis, or empty for the default folder glyph. | +| `id` | string | false | | | +| `limit_templates` | boolean | false | | Limit templates restricts the project's chats to its attached templates, and to none when nothing is attached. When false, the chats can use every template their owner can use. | +| `member_count` | integer | false | | Member count is the owner plus the users the project is shared with directly, as ChatProjectACL lists them. Members of shared groups are not counted. It is 1 while chat sharing is unavailable. | +| `name` | string | false | | Name is a display label and is not unique; ID identifies the project. | +| `organization_id` | string | false | | | +| `owner_id` | string | false | | | +| `permissions` | [codersdk.ChatProjectPermissions](#codersdkchatprojectpermissions) | false | | | +| `shared_with_everyone` | boolean | false | | Shared with everyone reports whether one of those groups is the Everyone group of the project's organization. | +| `templates` | array of [codersdk.ChatProjectTemplate](#codersdkchatprojecttemplate) | false | | Templates are the attached templates the caller can access. Deprecated templates and templates that do not allow agents are left out. | +| `updated_at` | string | false | | | ## codersdk.ChatProjectACL @@ -5446,6 +5452,34 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in |--------------------| | ``, `admin`, `use` | +## codersdk.ChatProjectSummary + +```json +{ + "last_activity_at": "2019-08-24T14:15:22Z", + "own_chat_count": 0, + "own_needs_attention": true, + "own_running": true, + "own_unread_count": 0, + "pin_order": 0, + "pinned": true, + "project_id": "405d8375-3514-403b-8c43-83ae74cfe0e9" +} +``` + +### Properties + +| Name | Type | Required | Restrictions | Description | +|-----------------------|---------|----------|--------------|--------------------------------------------------------------------------------| +| `last_activity_at` | string | false | | Last activity at is the latest update to one of the caller's chats. | +| `own_chat_count` | integer | false | | | +| `own_needs_attention` | boolean | false | | Own needs attention reports a chat that requires action, failed, or is paused. | +| `own_running` | boolean | false | | | +| `own_unread_count` | integer | false | | | +| `pin_order` | integer | false | | Pin order sorts pinned projects, lowest first, with gaps. 0 means not pinned. | +| `pinned` | boolean | false | | | +| `project_id` | string | false | | | + ## codersdk.ChatProjectTemplate ```json diff --git a/site/src/api/typesGenerated.ts b/site/src/api/typesGenerated.ts index fd44fbd8741..d8e699449c8 100644 --- a/site/src/api/typesGenerated.ts +++ b/site/src/api/typesGenerated.ts @@ -3672,6 +3672,23 @@ export interface ChatProject { * cannot access it. */ readonly default_template?: ChatProjectDefaultTemplate; + /** + * MemberCount is the owner plus the users the project is shared with + * directly, as ChatProjectACL lists them. Members of shared groups are + * not counted. It is 1 while chat sharing is unavailable. + */ + readonly member_count: number; + /** + * GroupCount is how many groups the project is shared with, as + * ChatProjectACL lists them, including the Everyone group. It is 0 while + * chat sharing is unavailable. + */ + readonly group_count: number; + /** + * SharedWithEveryone reports whether one of those groups is the Everyone + * group of the project's organization. + */ + readonly shared_with_everyone: boolean; readonly created_at: string; readonly updated_at: string; readonly permissions: ChatProjectPermissions; @@ -3767,6 +3784,32 @@ export type ChatProjectRole = "admin" | "" | "use"; export const ChatProjectRoles: ChatProjectRole[] = ["admin", "", "use"]; +// From codersdk/chats.go +/** + * ChatProjectSummary is the caller's pin on a project and aggregates over + * the caller's own top-level, non-archived chats in it. The project itself + * comes from ListChatProjects. + */ +export interface ChatProjectSummary { + readonly project_id: string; + readonly pinned: boolean; + /** + * PinOrder sorts pinned projects, lowest first, with gaps. 0 means not pinned. + */ + readonly pin_order: number; + readonly own_chat_count: number; + readonly own_unread_count: number; + readonly own_running: boolean; + /** + * OwnNeedsAttention reports a chat that requires action, failed, or is paused. + */ + readonly own_needs_attention: boolean; + /** + * LastActivityAt is the latest update to one of the caller's chats. + */ + readonly last_activity_at?: string; +} + // From codersdk/chats.go /** * ChatProjectTemplate is a workspace template attached to a chat project. diff --git a/site/src/pages/AgentsPage/components/ProjectPage/ProjectDetailsPanelView.stories.tsx b/site/src/pages/AgentsPage/components/ProjectPage/ProjectDetailsPanelView.stories.tsx index 0cf9fa5169a..c8e51d4bb28 100644 --- a/site/src/pages/AgentsPage/components/ProjectPage/ProjectDetailsPanelView.stories.tsx +++ b/site/src/pages/AgentsPage/components/ProjectPage/ProjectDetailsPanelView.stories.tsx @@ -348,7 +348,10 @@ export const MembersFullRow: Story = { }, }; -/** Groups follow users and count separately in the heading. */ +/** + * Groups follow users. The heading names the Everyone group first and counts + * the other groups. + */ export const MembersWithGroups: Story = { args: { members: { diff --git a/site/src/pages/AgentsPage/components/ProjectPage/ProjectDetailsPanelView.tsx b/site/src/pages/AgentsPage/components/ProjectPage/ProjectDetailsPanelView.tsx index 1fff85b2c21..90d9c4d90d5 100644 --- a/site/src/pages/AgentsPage/components/ProjectPage/ProjectDetailsPanelView.tsx +++ b/site/src/pages/AgentsPage/components/ProjectPage/ProjectDetailsPanelView.tsx @@ -13,7 +13,7 @@ import { TooltipTrigger, } from "#/components/Tooltip/Tooltip"; import { DATE_FORMAT, formatDateTime } from "#/utils/time"; -import { formatMembersHeading, type ProjectAccessEntry } from "./projectAccess"; +import { formatProjectMembers, type ProjectAccessEntry } from "./projectAccess"; /** The most avatar tiles the members row shows, including the "+K" tile. */ const MAX_MEMBER_TILES = 8; @@ -268,8 +268,12 @@ const MembersSection: React.FC = ({ }; let heading = "Members"; if (entries) { - const groupCount = entries.filter((entry) => entry.kind === "group").length; - heading = formatMembersHeading(entries.length - groupCount, groupCount); + const groups = entries.filter((entry) => entry.kind === "group"); + heading = formatProjectMembers({ + member_count: entries.length - groups.length, + group_count: groups.length, + shared_with_everyone: groups.some((group) => group.isEveryone), + }); } const maxTiles = rowWidth ? Math.min(MAX_MEMBER_TILES, Math.max(1, Math.floor((rowWidth + 4) / 28))) diff --git a/site/src/pages/AgentsPage/components/ProjectPage/projectAccess.test.ts b/site/src/pages/AgentsPage/components/ProjectPage/projectAccess.test.ts index be84e2f3568..fbf74cd503f 100644 --- a/site/src/pages/AgentsPage/components/ProjectPage/projectAccess.test.ts +++ b/site/src/pages/AgentsPage/components/ProjectPage/projectAccess.test.ts @@ -6,17 +6,28 @@ import { MockUserMember, MockUserOwner, } from "#/testHelpers/entities"; -import { buildAccessEntries, formatMembersHeading } from "./projectAccess"; +import { buildAccessEntries, formatProjectMembers } from "./projectAccess"; -describe("formatMembersHeading", () => { - it.each([ - [1, 0, "1 member"], - [3, 0, "3 members"], - [1, 1, "1 member, 1 group"], - [2, 3, "2 members, 3 groups"], - ])("formats %i members and %i groups as %s", (members, groups, expected) => { - expect(formatMembersHeading(members, groups)).toBe(expected); - }); +describe("formatProjectMembers", () => { + it.each<[string, number, number, boolean]>([ + ["1 member", 1, 0, false], + ["3 members", 3, 0, false], + ["1 member, 1 group", 1, 1, false], + ["2 members, 3 groups", 2, 3, false], + ["Everyone, 1 member", 1, 1, true], + ["Everyone, 2 members, 2 groups", 2, 3, true], + ])( + "returns %s", + (expected, member_count, group_count, shared_with_everyone) => { + expect( + formatProjectMembers({ + member_count, + group_count, + shared_with_everyone, + }), + ).toBe(expected); + }, + ); }); describe("buildAccessEntries", () => { diff --git a/site/src/pages/AgentsPage/components/ProjectPage/projectAccess.ts b/site/src/pages/AgentsPage/components/ProjectPage/projectAccess.ts index 320791e8600..fdfe2c1c057 100644 --- a/site/src/pages/AgentsPage/components/ProjectPage/projectAccess.ts +++ b/site/src/pages/AgentsPage/components/ProjectPage/projectAccess.ts @@ -1,9 +1,10 @@ import type { + ChatProject, ChatProjectACL, ChatProjectRole, MinimalUser, } from "#/api/typesGenerated"; -import { getGroupSubtitle } from "#/modules/groups"; +import { getGroupSubtitle, isEveryoneGroup } from "#/modules/groups"; type ProjectAccessEntryBase = { readonly id: string; @@ -19,8 +20,14 @@ type ProjectAccessEntryBase = { export type ProjectAccessEntry = | (ProjectAccessEntryBase & { readonly kind: "owner" }) | (ProjectAccessEntryBase & { - readonly kind: "user" | "group"; + readonly kind: "user"; readonly role: ChatProjectRole; + }) + | (ProjectAccessEntryBase & { + readonly kind: "group"; + readonly role: ChatProjectRole; + /** The organization's Everyone group, which reaches every member. */ + readonly isEveryone: boolean; }); /** A user or group that can be granted a project role. */ @@ -35,16 +42,29 @@ export type AccessChangeCallbacks = { readonly onSettled?: () => void; }; -/** `memberCount` includes the owner; groups are counted separately. */ -export const formatMembersHeading = ( - memberCount: number, - groupCount: number, -): string => { - const members = memberCount === 1 ? "1 member" : `${memberCount} members`; - if (groupCount === 0) { - return members; +/** + * Describes who a project is shared with, such as "2 members, 1 group", from + * the counts its ACL entries give: members include the owner, and groups + * include the Everyone group. The Everyone group is named first instead of + * counted, because it reaches the whole organization. + */ +export const formatProjectMembers = ({ + member_count, + group_count, + shared_with_everyone, +}: Pick< + ChatProject, + "member_count" | "group_count" | "shared_with_everyone" +>): string => { + const parts = [member_count === 1 ? "1 member" : `${member_count} members`]; + if (shared_with_everyone) { + parts.unshift("Everyone"); } - return `${members}, ${groupCount === 1 ? "1 group" : `${groupCount} groups`}`; + const otherGroups = shared_with_everyone ? group_count - 1 : group_count; + if (otherGroups > 0) { + parts.push(otherGroups === 1 ? "1 group" : `${otherGroups} groups`); + } + return parts.join(", "); }; const userSubtitle = (user: MinimalUser) => @@ -93,6 +113,7 @@ export const buildAccessEntries = ( subtitle: getGroupSubtitle(group), avatarUrl: group.avatar_url, role: group.role, + isEveryone: isEveryoneGroup(group), }), ) .sort(compareEntries), diff --git a/site/src/testHelpers/entities.ts b/site/src/testHelpers/entities.ts index d8012d373be..a68025dec78 100644 --- a/site/src/testHelpers/entities.ts +++ b/site/src/testHelpers/entities.ts @@ -575,6 +575,9 @@ export const MockChatProject: TypesGen.ChatProject = { limit_templates: false, templates: [], hidden_template_count: 0, + member_count: 1, + group_count: 0, + shared_with_everyone: false, created_at: "2026-09-01T12:00:00Z", updated_at: "2026-09-02T12:00:00Z", permissions: { update: true, delete: true, share: true },