diff --git a/coderd/apidoc/docs.go b/coderd/apidoc/docs.go index 50f005f9fec..c3bc37e83e2 100644 --- a/coderd/apidoc/docs.go +++ b/coderd/apidoc/docs.go @@ -213,6 +213,42 @@ const docTemplate = `{ } } }, + "/api/experimental/chats/projects/pins/order": { + "put": { + "consumes": [ + "application/json" + ], + "tags": [ + "Chats" + ], + "summary": "Reorder pinned chat projects", + "operationId": "reorder-chat-project-pins", + "parameters": [ + { + "description": "Reorder chat project pins request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/codersdk.ReorderChatProjectPinsRequest" + } + } + ], + "responses": { + "204": { + "description": "No Content" + } + }, + "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.", @@ -1242,6 +1278,84 @@ const docTemplate = `{ } } }, + "/api/experimental/organizations/{organization}/chats/projects/{project}/pin": { + "put": { + "tags": [ + "Chats" + ], + "summary": "Pin chat project", + "operationId": "pin-chat-project", + "parameters": [ + { + "type": "string", + "format": "uuid", + "description": "Organization ID", + "name": "organization", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "uuid", + "description": "Chat project ID", + "name": "project", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content" + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + }, + "delete": { + "tags": [ + "Chats" + ], + "summary": "Unpin chat project", + "operationId": "unpin-chat-project", + "parameters": [ + { + "type": "string", + "format": "uuid", + "description": "Organization ID", + "name": "organization", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "uuid", + "description": "Chat project ID", + "name": "project", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content" + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + } + }, "/api/experimental/organizations/{organization}/chats/projects/{project}/skills": { "get": { "produces": [ @@ -3394,6 +3508,12 @@ const docTemplate = `{ "description": "Only chats in this project.", "name": "project_id", "in": "query" + }, + { + "type": "boolean", + "description": "Leave out the caller's own unpinned chats in projects the caller can use. Project pins do not change the result.", + "name": "exclude_own_project_chats", + "in": "query" } ], "responses": { @@ -31591,6 +31711,19 @@ const docTemplate = `{ } } }, + "codersdk.ReorderChatProjectPinsRequest": { + "type": "object", + "properties": { + "project_ids": { + "description": "ProjectIDs are the pinned projects in their new order. Pins that are\nleft out follow the listed ones in their current order, and IDs the\ncaller has not pinned are ignored.", + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + } + } + }, "codersdk.Replica": { "type": "object", "properties": { diff --git a/coderd/apidoc/swagger.json b/coderd/apidoc/swagger.json index 606644689af..529512f6151 100644 --- a/coderd/apidoc/swagger.json +++ b/coderd/apidoc/swagger.json @@ -178,6 +178,38 @@ } } }, + "/api/experimental/chats/projects/pins/order": { + "put": { + "consumes": ["application/json"], + "tags": ["Chats"], + "summary": "Reorder pinned chat projects", + "operationId": "reorder-chat-project-pins", + "parameters": [ + { + "description": "Reorder chat project pins request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/codersdk.ReorderChatProjectPinsRequest" + } + } + ], + "responses": { + "204": { + "description": "No Content" + } + }, + "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.", @@ -1123,6 +1155,80 @@ } } }, + "/api/experimental/organizations/{organization}/chats/projects/{project}/pin": { + "put": { + "tags": ["Chats"], + "summary": "Pin chat project", + "operationId": "pin-chat-project", + "parameters": [ + { + "type": "string", + "format": "uuid", + "description": "Organization ID", + "name": "organization", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "uuid", + "description": "Chat project ID", + "name": "project", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content" + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + }, + "delete": { + "tags": ["Chats"], + "summary": "Unpin chat project", + "operationId": "unpin-chat-project", + "parameters": [ + { + "type": "string", + "format": "uuid", + "description": "Organization ID", + "name": "organization", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "uuid", + "description": "Chat project ID", + "name": "project", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "No Content" + } + }, + "security": [ + { + "CoderSessionToken": [] + } + ], + "x-apidocgen": { + "skip": true + } + } + }, "/api/experimental/organizations/{organization}/chats/projects/{project}/skills": { "get": { "produces": ["application/json"], @@ -3053,6 +3159,12 @@ "description": "Only chats in this project.", "name": "project_id", "in": "query" + }, + { + "type": "boolean", + "description": "Leave out the caller's own unpinned chats in projects the caller can use. Project pins do not change the result.", + "name": "exclude_own_project_chats", + "in": "query" } ], "responses": { @@ -29111,6 +29223,19 @@ } } }, + "codersdk.ReorderChatProjectPinsRequest": { + "type": "object", + "properties": { + "project_ids": { + "description": "ProjectIDs are the pinned projects in their new order. Pins that are\nleft out follow the listed ones in their current order, and IDs the\ncaller has not pinned are ignored.", + "type": "array", + "items": { + "type": "string", + "format": "uuid" + } + } + } + }, "codersdk.Replica": { "type": "object", "properties": { diff --git a/coderd/chat_project_pins.go b/coderd/chat_project_pins.go new file mode 100644 index 00000000000..8e3ab146060 --- /dev/null +++ b/coderd/chat_project_pins.go @@ -0,0 +1,173 @@ +package coderd + +import ( + "net/http" + + "github.com/google/uuid" + "golang.org/x/xerrors" + + "github.com/coder/coder/v2/coderd/database" + "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/x/chatd" + "github.com/coder/coder/v2/codersdk" +) + +// @Summary Pin chat project +// @ID pin-chat-project +// @Security CoderSessionToken +// @Tags Chats +// @Param organization path string true "Organization ID" format(uuid) +// @Param project path string true "Chat project ID" format(uuid) +// @Success 204 +// @Router /api/experimental/organizations/{organization}/chats/projects/{project}/pin [put] +// @x-apidocgen {"skip": true} +func (api *API) putChatProjectPin(rw http.ResponseWriter, r *http.Request) { + ctx := r.Context() + apiKey := httpmw.APIKey(r) + project := httpmw.ChatProjectParam(r) + if !api.authorizeChatProjectPin(rw, r, project) { + return + } + + err := api.Database.InTx(func(tx database.Store) error { + if err := tx.AcquireLock(ctx, chatProjectsOwnerLockID(apiKey.UserID)); err != nil { + return xerrors.Errorf("lock chat project pins: %w", err) + } + return tx.PinChatProject(ctx, database.PinChatProjectParams{ + UserID: apiKey.UserID, + ProjectID: project.ID, + }) + }, nil) + if err != nil { + httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ + Message: "Failed to pin chat project.", + Detail: err.Error(), + }) + return + } + rw.WriteHeader(http.StatusNoContent) +} + +// @Summary Reorder pinned chat projects +// @ID reorder-chat-project-pins +// @Security CoderSessionToken +// @Tags Chats +// @Accept json +// @Param request body codersdk.ReorderChatProjectPinsRequest true "Reorder chat project pins request" +// @Success 204 +// @Router /api/experimental/chats/projects/pins/order [put] +// @x-apidocgen {"skip": true} +func (api *API) putChatProjectPinOrder(rw http.ResponseWriter, r *http.Request) { + ctx := r.Context() + apiKey := httpmw.APIKey(r) + // The order is the caller's personal data, and the request names no + // project to authorize. dbauthz refuses the write for an API key scoped + // without user:update_personal, so answer 403 here instead of failing + // the transaction. + if !api.Authorize(r, policy.ActionUpdatePersonal, rbac.ResourceUserObject(apiKey.UserID)) { + httpapi.Forbidden(rw) + return + } + + var req codersdk.ReorderChatProjectPinsRequest + if !httpapi.Read(ctx, rw, r, &req) { + return + } + + err := api.Database.InTx(func(tx database.Store) error { + if err := tx.AcquireLock(ctx, chatProjectsOwnerLockID(apiKey.UserID)); err != nil { + return xerrors.Errorf("lock chat project pins: %w", err) + } + return tx.ReorderChatProjectPins(ctx, database.ReorderChatProjectPinsParams{ + UserID: apiKey.UserID, + ProjectIDs: req.ProjectIDs, + }) + }, nil) + if err != nil { + httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ + Message: "Failed to reorder chat project pins.", + Detail: err.Error(), + }) + return + } + rw.WriteHeader(http.StatusNoContent) +} + +// @Summary Unpin chat project +// @ID unpin-chat-project +// @Security CoderSessionToken +// @Tags Chats +// @Param organization path string true "Organization ID" format(uuid) +// @Param project path string true "Chat project ID" format(uuid) +// @Success 204 +// @Router /api/experimental/organizations/{organization}/chats/projects/{project}/pin [delete] +// @x-apidocgen {"skip": true} +func (api *API) deleteChatProjectPin(rw http.ResponseWriter, r *http.Request) { + ctx := r.Context() + apiKey := httpmw.APIKey(r) + project := httpmw.ChatProjectParam(r) + if !api.authorizeChatProjectPin(rw, r, project) { + return + } + + // Deleting one row cannot collide with another pin write, so unpinning + // takes no lock. + err := api.Database.UnpinChatProject(ctx, database.UnpinChatProjectParams{ + UserID: apiKey.UserID, + ProjectID: project.ID, + }) + if err != nil { + httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ + Message: "Failed to unpin chat project.", + Detail: err.Error(), + }) + return + } + rw.WriteHeader(http.StatusNoContent) +} + +// 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. +func (api *API) authorizeChatProjectPin(rw http.ResponseWriter, r *http.Request, project database.ChatProject) bool { + ctx := r.Context() + userID := httpmw.APIKey(r).UserID + // A pin is a personal preference, so the project only needs to be + // readable. + if !api.Authorize(r, policy.ActionRead, project.RBACObject()) { + httpapi.ResourceNotFound(rw) + return false + } + usable, err := chatd.ChatProjectUsableBy(ctx, api.Database, project, userID) + if err != nil { + httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ + Message: "Internal error checking chat project access.", + Detail: err.Error(), + }) + return false + } + if !usable { + httpapi.ResourceNotFound(rw) + return false + } + // The pin itself is the caller's personal data, which an API key scoped + // without user:update_personal may not change. dbauthz refuses that + // write, so answer 403 here instead of failing the transaction. + if !api.Authorize(r, policy.ActionUpdatePersonal, rbac.ResourceUserObject(userID)) { + httpapi.Forbidden(rw) + return false + } + return true +} + +// chatProjectsOwnerLockID serializes one user's project creates, pins and +// reorders. A new pin reads the last position and a reorder rewrites every +// position, so overlapping writes could otherwise share a position or +// deadlock. +func chatProjectsOwnerLockID(userID uuid.UUID) int64 { + return database.GenLockID("chat-projects-owner:" + userID.String()) +} diff --git a/coderd/chat_project_pins_test.go b/coderd/chat_project_pins_test.go new file mode 100644 index 00000000000..fcd08af4971 --- /dev/null +++ b/coderd/chat_project_pins_test.go @@ -0,0 +1,408 @@ +package coderd_test + +import ( + "cmp" + "context" + "database/sql" + "fmt" + "maps" + "net/http" + "slices" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/require" + "golang.org/x/sync/errgroup" + + "github.com/coder/coder/v2/coderd/coderdtest" + "github.com/coder/coder/v2/coderd/database" + "github.com/coder/coder/v2/coderd/database/dbgen" + "github.com/coder/coder/v2/coderd/database/dbtestutil" + "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/codersdk" + "github.com/coder/coder/v2/testutil" +) + +func TestChatProjectPins(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitLong) + client, sqlDB := newChatProjectPinsClient(t) + firstUser := coderdtest.CreateFirstUser(t, client.Client) + orgID, me := firstUser.OrganizationID, firstUser.UserID + reorder := func(client *codersdk.ExperimentalClient, projectIDs ...uuid.UUID) error { + return client.ReorderChatProjectPins(ctx, codersdk.ReorderChatProjectPinsRequest{ProjectIDs: projectIDs}) + } + + // New projects start pinned at the end of the creator's list. + 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) + + require.NoError(t, reorder(client, c.ID, a.ID, b.ID)) + requirePinnedProjects(ctx, t, sqlDB, me, 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) + + // 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) + // 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) + + // 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) + + // 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. + 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) + setRole := func(role codersdk.ChatProjectRole) { + require.NoError(t, client.UpdateChatProjectACL(ctx, orgID, a.ID, codersdk.UpdateChatProjectACL{ + UserRoles: map[string]codersdk.ChatProjectRole{otherUser.ID.String(): role}, + })) + } + setRole(codersdk.ChatProjectRoleUse) + requirePinnedProjects(ctx, t, sqlDB, otherUser.ID, otherOwn.ID) + require.NoError(t, other.PinChatProject(ctx, orgID, a.ID)) + requirePinnedProjects(ctx, t, sqlDB, otherUser.ID, otherOwn.ID, a.ID) + setRole(codersdk.ChatProjectRoleDeleted) + 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. + 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) +} + +// TestChatProjectPinsTokenScope checks that a pin, as the caller's personal +// data, cannot be written by an API key that lacks user:update_personal or +// cannot read the project. +func TestChatProjectPinsTokenScope(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitLong) + client, db := newChatProjectClient(t) + firstUser := coderdtest.CreateFirstUser(t, client.Client) + orgID := firstUser.OrganizationID + project := createChatProject(t, client, orgID, "Pin Scope") + + // Chat project scopes are not user-mintable, so seed scoped keys directly. + newScopedClient := func(scopes ...database.APIKeyScope) *codersdk.ExperimentalClient { + _, token := dbgen.APIKey(t, db, database.APIKey{ + UserID: firstUser.UserID, + Scopes: append(database.APIKeyScopes{"organization:read"}, scopes...), + }) + scoped := codersdk.New(client.URL) + scoped.SetSessionToken(token) + return codersdk.NewExperimentalClient(scoped) + } + + order := codersdk.ReorderChatProjectPinsRequest{ProjectIDs: []uuid.UUID{project.ID}} + readOnly := newScopedClient("chat_project:read") + requireSDKError(t, readOnly.PinChatProject(ctx, orgID, project.ID), http.StatusForbidden) + requireSDKError(t, readOnly.UnpinChatProject(ctx, orgID, project.ID), http.StatusForbidden) + requireSDKError(t, readOnly.ReorderChatProjectPins(ctx, order), http.StatusForbidden) + + // The same key with user:update_personal may change the pins, so that + // scope is the one the read-only key lacks. + personal := newScopedClient("chat_project:read", "user:update_personal") + require.NoError(t, personal.UnpinChatProject(ctx, orgID, project.ID)) + require.NoError(t, personal.PinChatProject(ctx, orgID, project.ID)) + require.NoError(t, personal.ReorderChatProjectPins(ctx, order)) + + // Creating a project pins it for its creator, so a key that may create + // projects also needs both of the pin's permissions. + createReq := codersdk.CreateChatProjectRequest{Name: "Scoped Create"} + _, err := newScopedClient("chat_project:create", "chat_project:read").CreateChatProject(ctx, orgID, createReq) + requireSDKError(t, err, http.StatusForbidden) + _, err = newScopedClient("chat_project:create", "user:update_personal").CreateChatProject(ctx, orgID, createReq) + requireSDKError(t, err, http.StatusForbidden) + _, err = newScopedClient("chat_project:create", "chat_project:read", "user:update_personal").CreateChatProject(ctx, orgID, createReq) + 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 + // Sixteen projects make overlapping writes collide reliably. + projectIDs := make([]uuid.UUID, 16) + want := make([]int32, len(projectIDs)) + for i := range projectIDs { + projectIDs[i] = createChatProject(t, client, orgID, fmt.Sprintf("Concurrent %d", i)).ID + want[i] = int32(i + 1) //nolint:gosec // Bounded by the number of projects. + } + // 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))) + } + + for round := range 10 { + // Overlapping reorders rewrite the same rows in different orders. + var reorders errgroup.Group + for i := range projectIDs { + reorders.Go(func() error { + order := append(slices.Clone(projectIDs[i:]), projectIDs[:i]...) + if (i+round)%2 == 0 { + slices.Reverse(order) + } + return client.ReorderChatProjectPins(ctx, codersdk.ReorderChatProjectPinsRequest{ProjectIDs: order}) + }) + } + require.NoError(t, reorders.Wait()) + requireDistinctPositions() + + // Overlapping pins each read the last position before taking the + // next one. + for _, projectID := range projectIDs { + require.NoError(t, client.UnpinChatProject(ctx, orgID, projectID)) + } + var pins errgroup.Group + for _, projectID := range projectIDs { + pins.Go(func() error { + return client.PinChatProject(ctx, orgID, projectID) + }) + } + require.NoError(t, pins.Wait()) + requireDistinctPositions() + } +} + +//nolint:paralleltest // Disabling chat sharing flips a process-wide RBAC switch. +func TestChatProjectsSharingDisabled(t *testing.T) { + previous := rbac.ChatACLDisabled() + t.Cleanup(func() { + rbac.ReloadBuiltinRoles(nil) + rbac.SetChatACLDisabled(previous) + }) + + ctx := testutil.Context(t, testutil.WaitLong) + db, ps := dbtestutil.NewDB(t) + client, _ := newChatProjectClientWithAPI(t, func(options *coderdtest.Options) { + options.Database, options.Pubsub = db, ps + options.DeploymentValues.DisableChatSharing = true + }) + firstUser := coderdtest.CreateFirstUser(t, client.Client) + orgID := firstUser.OrganizationID + model := createChatModel(t, client) + member, memberUser := newChatProjectMember(t, client, orgID) + project := createChatProject(t, client, orgID, "Members Disabled") + // Grants left from before sharing was disabled do not count. + require.NoError(t, db.UpdateChatProjectACLByID(ctx, database.UpdateChatProjectACLByIDParams{ + ID: project.ID, + UserACL: database.ChatACL{}, + GroupACL: database.ChatACL{orgID.String(): {Permissions: []policy.Action{policy.ActionRead}}}, + })) + + // The member cannot open the project, so no project list reaches their + // chat in it and the main list keeps it. + chat := dbgen.Chat(t, db, database.Chat{ + OrganizationID: orgID, OwnerID: memberUser.ID, LastModelConfigID: model.ID, + ProjectID: uuid.NullUUID{UUID: project.ID, Valid: true}, + }) + memberChats, err := member.ListChats(ctx, &codersdk.ListChatsOptions{ExcludeOwnProjectChats: true}) + require.NoError(t, err) + require.Contains(t, chatIDs(memberChats), chat.ID) + + // 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}}}, + GroupACL: database.ChatACL{}, + })) + requireSDKError(t, client.PinChatProject(ctx, orgID, memberProject.ID), http.StatusNotFound) + require.NoError(t, member.PinChatProject(ctx, orgID, memberProject.ID)) +} + +func TestListChatsExcludeOwnProjectChats(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitLong) + client, _ := newChatProjectClient(t) + firstUser := coderdtest.CreateFirstUser(t, client.Client) + orgID := firstUser.OrganizationID + _ = createChatModel(t, client) + pinned := createChatProject(t, client, orgID, "Sidebar Pinned") + unpinned := createChatProject(t, client, orgID, "Sidebar Unpinned") + require.NoError(t, client.UnpinChatProject(ctx, orgID, unpinned.ID)) + + unfiled := createChatInProject(t, client, orgID, nil) + // Project pins do not matter: chats in pinned and unpinned projects + // are both left out. + inPinned := createChatInProject(t, client, orgID, &pinned.ID) + pinnedChat := createChatInProject(t, client, orgID, &unpinned.ID) + require.NoError(t, client.UpdateChat(ctx, pinnedChat.ID, codersdk.UpdateChatRequest{PinOrder: ptr.Ref(int32(1))})) + // The newest chat is left out, so filtering after the query would + // return an empty second page. + inUnpinned := createChatInProject(t, client, orgID, &unpinned.ID) + + opts := &codersdk.ListChatsOptions{ExcludeOwnProjectChats: true, Pagination: codersdk.Pagination{Limit: 1}} + firstPage, err := client.ListChats(ctx, opts) + require.NoError(t, err) + require.Len(t, firstPage, 1) + require.Equal(t, pinnedChat.ID, firstPage[0].ID) + opts.AfterID = firstPage[0].ID + secondPage, err := client.ListChats(ctx, opts) + require.NoError(t, err) + require.Equal(t, []uuid.UUID{unfiled.ID}, chatIDs(secondPage)) + + // A chat in a project the viewer can no longer use stays listed, + // because no project list reaches it. + member, memberUser := newChatProjectMember(t, client, orgID) + setRole := func(role codersdk.ChatProjectRole) { + require.NoError(t, client.UpdateChatProjectACL(ctx, orgID, unpinned.ID, codersdk.UpdateChatProjectACL{ + UserRoles: map[string]codersdk.ChatProjectRole{memberUser.ID.String(): role}, + })) + } + setRole(codersdk.ChatProjectRoleUse) + revoked := createChatInProject(t, member, orgID, &unpinned.ID) + // Grants count: the member can use the project, so its chats are left + // out whether or not the member pinned it. + memberOpts := &codersdk.ListChatsOptions{ExcludeOwnProjectChats: true} + for _, pin := range []bool{false, true} { + if pin { + require.NoError(t, member.PinChatProject(ctx, orgID, unpinned.ID)) + } + memberChats, err := member.ListChats(ctx, memberOpts) + require.NoError(t, err) + require.NotContains(t, chatIDs(memberChats), revoked.ID) + } + setRole(codersdk.ChatProjectRoleDeleted) + memberChats, err := member.ListChats(ctx, memberOpts) + require.NoError(t, err) + require.Contains(t, chatIDs(memberChats), revoked.ID) + + // Without the option, every chat is listed. + all, err := client.ListChats(ctx, nil) + require.NoError(t, err) + require.Subset(t, chatIDs(all), []uuid.UUID{unfiled.ID, inPinned.ID, pinnedChat.ID, inUnpinned.ID}) +} + +// A chat pin belongs to the chat's owner, so pinning a shared chat must not +// change how the chat is listed for anyone it is shared with, and project +// pins never hide a shared chat. +func TestListChatsIgnoresOtherUsersChatPins(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitLong) + client, _ := newChatProjectClient(t) + firstUser := coderdtest.CreateFirstUser(t, client.Client) + orgID := firstUser.OrganizationID + _ = createChatModel(t, client) + member, memberUser := newChatProjectMember(t, client, orgID) + project := createChatProject(t, client, orgID, "Shared Project") + require.NoError(t, client.UpdateChatProjectACL(ctx, orgID, project.ID, codersdk.UpdateChatProjectACL{ + UserRoles: map[string]codersdk.ChatProjectRole{memberUser.ID.String(): codersdk.ChatProjectRoleUse}, + })) + + memberPinned := createChatInProject(t, member, orgID, nil) + require.NoError(t, member.UpdateChat(ctx, memberPinned.ID, codersdk.UpdateChatRequest{PinOrder: ptr.Ref(int32(1))})) + ownerPinned := createChatInProject(t, client, orgID, &project.ID) + newer := createChatInProject(t, client, orgID, nil) + // Shared in creation order so the newer chat stays the most recently + // updated even if sharing bumps updated_at. + for _, chat := range []codersdk.Chat{ownerPinned, newer} { + require.NoError(t, client.UpdateChatACL(ctx, chat.ID, codersdk.UpdateChatACL{ + UserRoles: map[string]codersdk.ChatRole{memberUser.ID.String(): codersdk.ChatRoleRead}, + })) + } + require.NoError(t, client.UpdateChat(ctx, ownerPinned.ID, codersdk.UpdateChatRequest{PinOrder: ptr.Ref(int32(1))})) + + // The sidebar lists owned and shared chats together. Only the member's + // own pin sorts first. Paging one chat at a time checks that the cursor + // uses the same order. + const ownedAndShared = "source:created_by_me,shared_with_me" + var listed []uuid.UUID + opts := &codersdk.ListChatsOptions{Query: ownedAndShared, Pagination: codersdk.Pagination{Limit: 1}} + for { + page, err := member.ListChats(ctx, opts) + require.NoError(t, err) + if len(page) == 0 { + break + } + listed = append(listed, chatIDs(page)...) + opts.AfterID = page[len(page)-1].ID + } + require.Equal(t, []uuid.UUID{memberPinned.ID, newer.ID, ownerPinned.ID}, listed) + + // The owner's own list keeps the pinned chat in the project. + ownerChats, err := client.ListChats(ctx, &codersdk.ListChatsOptions{ExcludeOwnProjectChats: true}) + require.NoError(t, err) + require.NotEmpty(t, ownerChats) + require.Equal(t, ownerPinned.ID, ownerChats[0].ID) + + // Chats shared with the member are listed whether or not anyone pinned + // the chat, although the member can use its project. + pinnedOpts := &codersdk.ListChatsOptions{Query: ownedAndShared, ExcludeOwnProjectChats: true} + want := []uuid.UUID{memberPinned.ID, newer.ID, ownerPinned.ID} + memberChats, err := member.ListChats(ctx, pinnedOpts) + require.NoError(t, err) + require.ElementsMatch(t, want, chatIDs(memberChats)) + require.NoError(t, client.UpdateChat(ctx, ownerPinned.ID, codersdk.UpdateChatRequest{PinOrder: ptr.Ref(int32(0))})) + memberChats, err = member.ListChats(ctx, pinnedOpts) + require.NoError(t, err) + 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) { + 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) + 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 + } + require.NoError(t, rows.Err()) + return pins +} + +// 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) { + 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) +} diff --git a/coderd/chat_projects.go b/coderd/chat_projects.go index e9a463ac7fa..58c47b8c00b 100644 --- a/coderd/chat_projects.go +++ b/coderd/chat_projects.go @@ -122,8 +122,9 @@ func (api *API) postChatProject(rw http.ResponseWriter, r *http.Request) { var project database.ChatProject err = api.Database.InTx(func(tx database.Store) error { // The lock serializes a user's creates so concurrent requests cannot - // both observe room under the cap. - if err := tx.AcquireLock(ctx, database.GenLockID("chat-projects-owner:"+apiKey.UserID.String())); err != nil { + // both observe room under the cap, and orders the creator's pin with + // their other pin writes. + if err := tx.AcquireLock(ctx, chatProjectsOwnerLockID(apiKey.UserID)); err != nil { return xerrors.Errorf("lock chat projects: %w", err) } // The count spans the user's projects in every organization, and the @@ -152,15 +153,21 @@ func (api *API) postChatProject(rw http.ResponseWriter, r *http.Request) { if err != nil { return err } - if len(req.TemplateIDs) == 0 { - return nil + if len(req.TemplateIDs) > 0 { + _, err = tx.InsertChatProjectTemplates(ctx, database.InsertChatProjectTemplatesParams{ + ProjectID: project.ID, + TemplateIDs: req.TemplateIDs, + CreatedBy: apiKey.UserID, + }) + if err != nil { + return err + } } - _, err = tx.InsertChatProjectTemplates(ctx, database.InsertChatProjectTemplatesParams{ - ProjectID: project.ID, - TemplateIDs: req.TemplateIDs, - CreatedBy: apiKey.UserID, + // New projects start pinned for their creator. + return tx.PinChatProject(ctx, database.PinChatProjectParams{ + UserID: apiKey.UserID, + ProjectID: project.ID, }) - return err }, nil) if errors.Is(err, errChatProjectLimit) { httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{ diff --git a/coderd/chat_projects_test.go b/coderd/chat_projects_test.go index 6636e806144..5faf181ca60 100644 --- a/coderd/chat_projects_test.go +++ b/coderd/chat_projects_test.go @@ -111,6 +111,8 @@ func TestChatProjectsCRUDListAndDeleteDetaches(t *testing.T) { require.NoError(t, err) require.Equal(t, duplicate.ID, fetched.ID) + // The creator's pin references the project, so the delete only + // succeeds because pins cascade with it. require.NoError(t, client.DeleteChatProject(ctx, firstUser.OrganizationID, project.ID)) storedChat, err := client.GetChat(ctx, chat.ID) require.NoError(t, err) diff --git a/coderd/chat_routes.go b/coderd/chat_routes.go index 853c97e1826..9c173593cf6 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.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 // with a 400. @@ -146,6 +147,8 @@ func (api *API) registerExperimentalOrganizationChatRoutes(r chi.Router) { r.Get("/", api.getChatProject) r.Patch("/", api.patchChatProject) r.Delete("/", api.deleteChatProject) + r.Put("/pin", api.putChatProjectPin) + r.Delete("/pin", api.deleteChatProjectPin) r.Route("/acl", func(r chi.Router) { r.Use(httpmw.RequireExperimentWithDevBypass(api.Experiments, codersdk.ExperimentChatProjectSharing)) r.Get("/", api.getChatProjectACL) diff --git a/coderd/database/check_constraint.go b/coderd/database/check_constraint.go index ca76905bb32..968ce914a21 100644 --- a/coderd/database/check_constraint.go +++ b/coderd/database/check_constraint.go @@ -38,6 +38,7 @@ const ( CheckChatProjectMemoriesBodyLength CheckConstraint = "chat_project_memories_body_length" // chat_project_memories CheckChatProjectMemoriesDescriptionLength CheckConstraint = "chat_project_memories_description_length" // chat_project_memories CheckChatProjectMemoriesNameFormat CheckConstraint = "chat_project_memories_name_format" // chat_project_memories + CheckChatProjectPinsPinOrderCheck CheckConstraint = "chat_project_pins_pin_order_check" // chat_project_pins CheckChatProjectsDefaultPresetOrParameters CheckConstraint = "chat_projects_default_preset_or_parameters" // chat_projects CheckChatProjectsDescriptionLength CheckConstraint = "chat_projects_description_length" // chat_projects CheckChatProjectsGroupAclIsObject CheckConstraint = "chat_projects_group_acl_is_object" // chat_projects diff --git a/coderd/database/dbauthz/dbauthz.go b/coderd/database/dbauthz/dbauthz.go index fc9f46ff666..843c2a554d8 100644 --- a/coderd/database/dbauthz/dbauthz.go +++ b/coderd/database/dbauthz/dbauthz.go @@ -1845,6 +1845,16 @@ func (q *querier) authorizeChatProjectConfig(ctx context.Context, action policy. return q.authorizeContext(ctx, action, project.RBACObject()) } +// authorizeChatProjectPin authorizes a change to a user's pin on a project. +// A pin is that user's personal preference, so the write is authorized on +// the user, and the project only needs to be readable. +func (q *querier) authorizeChatProjectPin(ctx context.Context, userID, projectID uuid.UUID) error { + if err := q.authorizeContext(ctx, policy.ActionUpdatePersonal, rbac.ResourceUserObject(userID)); err != nil { + return err + } + return q.authorizeChatProjectConfig(ctx, policy.ActionRead, projectID) +} + func (q *querier) authorizeChatProjectMemory(ctx context.Context, action policy.Action, memory database.ChatProjectMemory) error { project, err := q.db.GetChatProjectByID(ctx, memory.ProjectID) if err != nil { @@ -7698,6 +7708,13 @@ func (q *querier) PinChatByID(ctx context.Context, id uuid.UUID) error { return q.db.PinChatByID(ctx, id) } +func (q *querier) PinChatProject(ctx context.Context, arg database.PinChatProjectParams) error { + if err := q.authorizeChatProjectPin(ctx, arg.UserID, arg.ProjectID); err != nil { + return err + } + return q.db.PinChatProject(ctx, arg) +} + func (q *querier) ReduceWorkspaceAgentShareLevelToAuthenticatedByTemplate(ctx context.Context, templateID uuid.UUID) error { template, err := q.db.GetTemplateByID(ctx, templateID) if err != nil { @@ -7747,6 +7764,16 @@ func (q *querier) RenewChatHeartbeats(ctx context.Context, arg database.RenewCha return q.db.RenewChatHeartbeats(ctx, arg) } +// ReorderChatProjectPins changes only the order of the user's own pins and +// reveals nothing about the listed projects, so it is authorized on the user +// alone. +func (q *querier) ReorderChatProjectPins(ctx context.Context, arg database.ReorderChatProjectPinsParams) error { + if err := q.authorizeContext(ctx, policy.ActionUpdatePersonal, rbac.ResourceUserObject(arg.UserID)); err != nil { + return err + } + return q.db.ReorderChatProjectPins(ctx, arg) +} + func (q *querier) RevokeDBCryptKey(ctx context.Context, activeKeyDigest string) error { if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceSystem); err != nil { return err @@ -7887,6 +7914,13 @@ func (q *querier) UnpinChatByID(ctx context.Context, id uuid.UUID) error { return q.db.UnpinChatByID(ctx, id) } +func (q *querier) UnpinChatProject(ctx context.Context, arg database.UnpinChatProjectParams) error { + if err := q.authorizeChatProjectPin(ctx, arg.UserID, arg.ProjectID); err != nil { + return err + } + return q.db.UnpinChatProject(ctx, arg) +} + func (q *querier) UnsetDefaultChatModelConfigs(ctx context.Context, organizationID uuid.UUID) error { if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceChatModelConfig.InOrg(organizationID)); err != nil { return err diff --git a/coderd/database/dbauthz/dbauthz_test.go b/coderd/database/dbauthz/dbauthz_test.go index a60e7d8d912..21eb9e300bc 100644 --- a/coderd/database/dbauthz/dbauthz_test.go +++ b/coderd/database/dbauthz/dbauthz_test.go @@ -1394,6 +1394,25 @@ 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("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} + dbm.EXPECT().GetChatProjectByID(gomock.Any(), project.ID).Return(project, nil).AnyTimes() + dbm.EXPECT().PinChatProject(gomock.Any(), arg).Return(nil).AnyTimes() + check.Args(arg).Asserts(rbac.ResourceUserObject(arg.UserID), policy.ActionUpdatePersonal, project, policy.ActionRead) + })) + s.Run("ReorderChatProjectPins", s.Mocked(func(dbm *dbmock.MockStore, _ *gofakeit.Faker, check *expects) { + arg := database.ReorderChatProjectPinsParams{UserID: uuid.New(), ProjectIDs: []uuid.UUID{uuid.New()}} + dbm.EXPECT().ReorderChatProjectPins(gomock.Any(), arg).Return(nil).AnyTimes() + check.Args(arg).Asserts(rbac.ResourceUserObject(arg.UserID), policy.ActionUpdatePersonal) + })) + s.Run("UnpinChatProject", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) { + project := testutil.Fake(s.T(), faker, database.ChatProject{}) + arg := database.UnpinChatProjectParams{UserID: uuid.New(), ProjectID: project.ID} + dbm.EXPECT().GetChatProjectByID(gomock.Any(), project.ID).Return(project, nil).AnyTimes() + dbm.EXPECT().UnpinChatProject(gomock.Any(), arg).Return(nil).AnyTimes() + check.Args(arg).Asserts(rbac.ResourceUserObject(arg.UserID), policy.ActionUpdatePersonal, project, policy.ActionRead) + })) s.Run("IsChatProjectUsableByUserID", s.Mocked(func(dbm *dbmock.MockStore, _ *gofakeit.Faker, check *expects) { arg := database.IsChatProjectUsableByUserIDParams{ProjectID: uuid.New(), UserID: uuid.New()} dbm.EXPECT().IsChatProjectUsableByUserID(gomock.Any(), arg).Return(true, nil).AnyTimes() diff --git a/coderd/database/dbmetrics/querymetrics.go b/coderd/database/dbmetrics/querymetrics.go index 6efff5cedeb..63194f419a2 100644 --- a/coderd/database/dbmetrics/querymetrics.go +++ b/coderd/database/dbmetrics/querymetrics.go @@ -5448,6 +5448,14 @@ func (m queryMetricsStore) PinChatByID(ctx context.Context, id uuid.UUID) error return r0 } +func (m queryMetricsStore) PinChatProject(ctx context.Context, arg database.PinChatProjectParams) error { + start := time.Now() + r0 := m.s.PinChatProject(ctx, arg) + m.queryLatencies.WithLabelValues("PinChatProject").Observe(time.Since(start).Seconds()) + m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "PinChatProject").Inc() + return r0 +} + func (m queryMetricsStore) ReduceWorkspaceAgentShareLevelToAuthenticatedByTemplate(ctx context.Context, templateID uuid.UUID) error { start := time.Now() r0 := m.s.ReduceWorkspaceAgentShareLevelToAuthenticatedByTemplate(ctx, templateID) @@ -5496,6 +5504,14 @@ func (m queryMetricsStore) RenewChatHeartbeats(ctx context.Context, arg database return r0, r1 } +func (m queryMetricsStore) ReorderChatProjectPins(ctx context.Context, arg database.ReorderChatProjectPinsParams) error { + start := time.Now() + r0 := m.s.ReorderChatProjectPins(ctx, arg) + m.queryLatencies.WithLabelValues("ReorderChatProjectPins").Observe(time.Since(start).Seconds()) + m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "ReorderChatProjectPins").Inc() + return r0 +} + func (m queryMetricsStore) RevokeDBCryptKey(ctx context.Context, activeKeyDigest string) error { start := time.Now() r0 := m.s.RevokeDBCryptKey(ctx, activeKeyDigest) @@ -5616,6 +5632,14 @@ func (m queryMetricsStore) UnpinChatByID(ctx context.Context, id uuid.UUID) erro return r0 } +func (m queryMetricsStore) UnpinChatProject(ctx context.Context, arg database.UnpinChatProjectParams) error { + start := time.Now() + r0 := m.s.UnpinChatProject(ctx, arg) + m.queryLatencies.WithLabelValues("UnpinChatProject").Observe(time.Since(start).Seconds()) + m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "UnpinChatProject").Inc() + return r0 +} + func (m queryMetricsStore) UnsetDefaultChatModelConfigs(ctx context.Context, organizationID uuid.UUID) error { start := time.Now() r0 := m.s.UnsetDefaultChatModelConfigs(ctx, organizationID) diff --git a/coderd/database/dbmock/dbmock.go b/coderd/database/dbmock/dbmock.go index 7e266affa17..db87e62de0a 100644 --- a/coderd/database/dbmock/dbmock.go +++ b/coderd/database/dbmock/dbmock.go @@ -10340,6 +10340,20 @@ func (mr *MockStoreMockRecorder) PinChatByID(ctx, id any) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PinChatByID", reflect.TypeOf((*MockStore)(nil).PinChatByID), ctx, id) } +// PinChatProject mocks base method. +func (m *MockStore) PinChatProject(ctx context.Context, arg database.PinChatProjectParams) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PinChatProject", ctx, arg) + ret0, _ := ret[0].(error) + return ret0 +} + +// PinChatProject indicates an expected call of PinChatProject. +func (mr *MockStoreMockRecorder) PinChatProject(ctx, arg any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PinChatProject", reflect.TypeOf((*MockStore)(nil).PinChatProject), ctx, arg) +} + // Ping mocks base method. func (m *MockStore) Ping(ctx context.Context) (time.Duration, error) { m.ctrl.T.Helper() @@ -10443,6 +10457,20 @@ func (mr *MockStoreMockRecorder) RenewChatHeartbeats(ctx, arg any) *gomock.Call return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RenewChatHeartbeats", reflect.TypeOf((*MockStore)(nil).RenewChatHeartbeats), ctx, arg) } +// ReorderChatProjectPins mocks base method. +func (m *MockStore) ReorderChatProjectPins(ctx context.Context, arg database.ReorderChatProjectPinsParams) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ReorderChatProjectPins", ctx, arg) + ret0, _ := ret[0].(error) + return ret0 +} + +// ReorderChatProjectPins indicates an expected call of ReorderChatProjectPins. +func (mr *MockStoreMockRecorder) ReorderChatProjectPins(ctx, arg any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReorderChatProjectPins", reflect.TypeOf((*MockStore)(nil).ReorderChatProjectPins), ctx, arg) +} + // RevokeDBCryptKey mocks base method. func (m *MockStore) RevokeDBCryptKey(ctx context.Context, activeKeyDigest string) error { m.ctrl.T.Helper() @@ -10659,6 +10687,20 @@ func (mr *MockStoreMockRecorder) UnpinChatByID(ctx, id any) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnpinChatByID", reflect.TypeOf((*MockStore)(nil).UnpinChatByID), ctx, id) } +// UnpinChatProject mocks base method. +func (m *MockStore) UnpinChatProject(ctx context.Context, arg database.UnpinChatProjectParams) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UnpinChatProject", ctx, arg) + ret0, _ := ret[0].(error) + return ret0 +} + +// UnpinChatProject indicates an expected call of UnpinChatProject. +func (mr *MockStoreMockRecorder) UnpinChatProject(ctx, arg any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnpinChatProject", reflect.TypeOf((*MockStore)(nil).UnpinChatProject), ctx, arg) +} + // UnsetDefaultChatModelConfigs mocks base method. func (m *MockStore) UnsetDefaultChatModelConfigs(ctx context.Context, organizationID uuid.UUID) error { m.ctrl.T.Helper() diff --git a/coderd/database/dump.sql b/coderd/database/dump.sql index 3af3f75b025..187fcd407c1 100644 --- a/coderd/database/dump.sql +++ b/coderd/database/dump.sql @@ -927,6 +927,35 @@ $$; COMMENT ON FUNCTION chat_message_search_text(content jsonb) IS 'Extracts searchable content from chat_messages. Returns NULL for scalar JSON strings (content_version=0). Immutable as it is used in indexes.'; +CREATE FUNCTION chat_project_ids_for_user(viewer_id uuid, include_grants boolean) RETURNS TABLE(project_id uuid) + LANGUAGE sql STABLE + AS $$ +SELECT chat_projects.id +FROM chat_projects +WHERE chat_projects.owner_id = viewer_id + OR ( + include_grants + AND ( + chat_projects.user_acl ? viewer_id::text + OR chat_projects.group_acl ?| ARRAY( + SELECT group_members.group_id::text + FROM group_members + WHERE group_members.user_id = viewer_id + UNION ALL + SELECT organization_members.organization_id::text + FROM organization_members + WHERE organization_members.user_id = viewer_id + ) + ) + AND EXISTS ( + SELECT 1 + FROM organization_members + WHERE organization_members.user_id = viewer_id + AND organization_members.organization_id = chat_projects.organization_id + ) + ) +$$; + CREATE FUNCTION check_workspace_agent_name_unique() RETURNS trigger LANGUAGE plpgsql AS $$ @@ -2360,6 +2389,16 @@ CREATE TABLE chat_project_memories ( COMMENT ON TABLE chat_project_memories IS 'Organization-scoped durable memories for chat projects. Memories are immutable; changing one deletes it and creates its replacement.'; +CREATE TABLE chat_project_pins ( + user_id uuid NOT NULL, + project_id uuid NOT NULL, + pin_order integer NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT chat_project_pins_pin_order_check CHECK ((pin_order > 0)) +); + +COMMENT ON TABLE chat_project_pins IS 'Per-user pinned chat projects. Pins can outlive project access, so readers must check access.'; + CREATE TABLE chat_project_templates ( project_id uuid NOT NULL, template_id uuid NOT NULL, @@ -4750,6 +4789,9 @@ ALTER TABLE ONLY chat_project_instructions ALTER TABLE ONLY chat_project_memories ADD CONSTRAINT chat_project_memories_pkey PRIMARY KEY (id); +ALTER TABLE ONLY chat_project_pins + ADD CONSTRAINT chat_project_pins_pkey PRIMARY KEY (user_id, project_id); + ALTER TABLE ONLY chat_project_templates ADD CONSTRAINT chat_project_templates_pkey PRIMARY KEY (project_id, template_id); @@ -5258,6 +5300,8 @@ CREATE UNIQUE INDEX idx_chat_model_configs_single_default ON chat_model_configs CREATE UNIQUE INDEX idx_chat_project_memories_project_lower_name ON chat_project_memories USING btree (project_id, lower(name)); +CREATE INDEX idx_chat_project_pins_user_order ON chat_project_pins USING btree (user_id, pin_order); + CREATE INDEX idx_chat_projects_group_acl ON chat_projects USING gin (group_acl); CREATE INDEX idx_chat_projects_organization_id ON chat_projects USING btree (organization_id); @@ -5708,6 +5752,12 @@ ALTER TABLE ONLY chat_project_memories ALTER TABLE ONLY chat_project_memories ADD CONSTRAINT chat_project_memories_project_id_fkey FOREIGN KEY (project_id) REFERENCES chat_projects(id) ON DELETE CASCADE; +ALTER TABLE ONLY chat_project_pins + ADD CONSTRAINT chat_project_pins_project_id_fkey FOREIGN KEY (project_id) REFERENCES chat_projects(id) ON DELETE CASCADE; + +ALTER TABLE ONLY chat_project_pins + ADD CONSTRAINT chat_project_pins_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE; + ALTER TABLE ONLY chat_project_templates ADD CONSTRAINT chat_project_templates_created_by_fkey FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE CASCADE; diff --git a/coderd/database/foreign_key_constraint.go b/coderd/database/foreign_key_constraint.go index 0827094aefe..249311419b8 100644 --- a/coderd/database/foreign_key_constraint.go +++ b/coderd/database/foreign_key_constraint.go @@ -44,6 +44,8 @@ const ( ForeignKeyChatProjectMemoriesCreatedBy ForeignKeyConstraint = "chat_project_memories_created_by_fkey" // ALTER TABLE ONLY chat_project_memories ADD CONSTRAINT chat_project_memories_created_by_fkey FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE CASCADE; ForeignKeyChatProjectMemoriesOrganizationID ForeignKeyConstraint = "chat_project_memories_organization_id_fkey" // ALTER TABLE ONLY chat_project_memories ADD CONSTRAINT chat_project_memories_organization_id_fkey FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE CASCADE; ForeignKeyChatProjectMemoriesProjectID ForeignKeyConstraint = "chat_project_memories_project_id_fkey" // ALTER TABLE ONLY chat_project_memories ADD CONSTRAINT chat_project_memories_project_id_fkey FOREIGN KEY (project_id) REFERENCES chat_projects(id) ON DELETE CASCADE; + ForeignKeyChatProjectPinsProjectID ForeignKeyConstraint = "chat_project_pins_project_id_fkey" // ALTER TABLE ONLY chat_project_pins ADD CONSTRAINT chat_project_pins_project_id_fkey FOREIGN KEY (project_id) REFERENCES chat_projects(id) ON DELETE CASCADE; + ForeignKeyChatProjectPinsUserID ForeignKeyConstraint = "chat_project_pins_user_id_fkey" // ALTER TABLE ONLY chat_project_pins ADD CONSTRAINT chat_project_pins_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE; ForeignKeyChatProjectTemplatesCreatedBy ForeignKeyConstraint = "chat_project_templates_created_by_fkey" // ALTER TABLE ONLY chat_project_templates ADD CONSTRAINT chat_project_templates_created_by_fkey FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE CASCADE; ForeignKeyChatProjectTemplatesProjectID ForeignKeyConstraint = "chat_project_templates_project_id_fkey" // ALTER TABLE ONLY chat_project_templates ADD CONSTRAINT chat_project_templates_project_id_fkey FOREIGN KEY (project_id) REFERENCES chat_projects(id) ON DELETE CASCADE; ForeignKeyChatProjectTemplatesTemplateID ForeignKeyConstraint = "chat_project_templates_template_id_fkey" // ALTER TABLE ONLY chat_project_templates ADD CONSTRAINT chat_project_templates_template_id_fkey FOREIGN KEY (template_id) REFERENCES templates(id) ON DELETE CASCADE; diff --git a/coderd/database/migrations/000649_chat_project_pins.down.sql b/coderd/database/migrations/000649_chat_project_pins.down.sql new file mode 100644 index 00000000000..c4a123877a0 --- /dev/null +++ b/coderd/database/migrations/000649_chat_project_pins.down.sql @@ -0,0 +1,2 @@ +DROP FUNCTION chat_project_ids_for_user(uuid, boolean); +DROP TABLE chat_project_pins; diff --git a/coderd/database/migrations/000649_chat_project_pins.up.sql b/coderd/database/migrations/000649_chat_project_pins.up.sql new file mode 100644 index 00000000000..41762bddf3f --- /dev/null +++ b/coderd/database/migrations/000649_chat_project_pins.up.sql @@ -0,0 +1,58 @@ +CREATE TABLE chat_project_pins ( + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + project_id uuid NOT NULL REFERENCES chat_projects(id) ON DELETE CASCADE, + pin_order integer NOT NULL CONSTRAINT chat_project_pins_pin_order_check CHECK (pin_order > 0), + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, project_id) +); + +COMMENT ON TABLE chat_project_pins IS 'Per-user pinned chat projects. Pins can outlive project access, so readers must check access.'; + +CREATE INDEX idx_chat_project_pins_user_order ON chat_project_pins (user_id, pin_order); + +-- Pin every project its owner can already see in the sidebar, in the +-- sidebar's order, so nothing disappears on upgrade. Shared projects are +-- not pinned. +INSERT INTO chat_project_pins (user_id, project_id, pin_order) +SELECT + owner_id, + id, + ROW_NUMBER() OVER (PARTITION BY owner_id ORDER BY lower(name), id) +FROM chat_projects +ON CONFLICT DO NOTHING; + +-- Projects listed for a user: the ones they own and, when include_grants is +-- true, the ones whose user or group ACL names them or a group they belong +-- to (including the Everyone group) in an organization they belong to. +-- Grants match whatever actions they hold, so callers must still authorize +-- each project. The planner inlines this function, so the ACL indexes still +-- apply. +CREATE FUNCTION chat_project_ids_for_user(viewer_id uuid, include_grants boolean) +RETURNS TABLE (project_id uuid) +LANGUAGE sql STABLE +AS $$ +SELECT chat_projects.id +FROM chat_projects +WHERE chat_projects.owner_id = viewer_id + OR ( + include_grants + AND ( + chat_projects.user_acl ? viewer_id::text + OR chat_projects.group_acl ?| ARRAY( + SELECT group_members.group_id::text + FROM group_members + WHERE group_members.user_id = viewer_id + UNION ALL + SELECT organization_members.organization_id::text + FROM organization_members + WHERE organization_members.user_id = viewer_id + ) + ) + AND EXISTS ( + SELECT 1 + FROM organization_members + WHERE organization_members.user_id = viewer_id + AND organization_members.organization_id = chat_projects.organization_id + ) + ) +$$; diff --git a/coderd/database/migrations/LATEST b/coderd/database/migrations/LATEST index 0e40ff69820..092b5f8acc3 100644 --- a/coderd/database/migrations/LATEST +++ b/coderd/database/migrations/LATEST @@ -22,4 +22,4 @@ # # After a rebase finishes, run fix_migration_numbers.sh once and commit # the result. -000648_chat_diff_statuses_root_chats +000649_chat_project_pins diff --git a/coderd/database/migrations/migration000649_test.go b/coderd/database/migrations/migration000649_test.go new file mode 100644 index 00000000000..515487abe69 --- /dev/null +++ b/coderd/database/migrations/migration000649_test.go @@ -0,0 +1,58 @@ +package migrations_test + +import ( + "os" + "testing" + + "github.com/google/uuid" + "github.com/lib/pq" + "github.com/stretchr/testify/require" + + "github.com/coder/coder/v2/coderd/database" + "github.com/coder/coder/v2/coderd/database/dbgen" + "github.com/coder/coder/v2/testutil" +) + +// TestMigration000649PinsOwnedProjects checks that the upgrade pins each +// owner's projects in sidebar order and leaves shared projects unpinned. +func TestMigration000649PinsOwnedProjects(t *testing.T) { + t.Parallel() + + sqlDB := testSQLDB(t) + stepTo(t, sqlDB, 648) + ctx := testutil.Context(t, testutil.WaitLong) + + db := database.New(sqlDB) + orgID := insertMigrationTestOrganization(ctx, t, sqlDB, []string{}) + first := dbgen.User(t, db, database.User{}) + second := dbgen.User(t, db, database.User{}) + insertProject := func(ownerID, id uuid.UUID, name, userACL string) { + _, err := sqlDB.ExecContext(ctx, `INSERT INTO chat_projects (id, organization_id, owner_id, name, user_acl) VALUES ($1, $2, $3, $4, $5::jsonb)`, + id, orgID, ownerID, name, userACL) + require.NoError(t, err) + } + // The sidebar sorts by lower(name), then ID. Neither byte order + // ("Banana" < "apple") nor a collation that puts lowercase first + // ("banana" < "Banana") gives that order. + insertProject(first.ID, uuid.New(), "cherry", "{}") + insertProject(first.ID, uuid.New(), "apple", "{}") + insertProject(first.ID, uuid.MustParse("00000000-0000-4000-8000-000000000002"), "banana", "{}") + insertProject(first.ID, uuid.MustParse("00000000-0000-4000-8000-000000000001"), "Banana", "{}") + insertProject(second.ID, uuid.New(), "Shared", `{"`+first.ID.String()+`":{"permissions":["read"]}}`) + + up, err := os.ReadFile("000649_chat_project_pins.up.sql") + require.NoError(t, err) + _, err = sqlDB.ExecContext(ctx, string(up)) + require.NoError(t, err) + + pins := func(userID uuid.UUID) []string { + var got pq.StringArray + require.NoError(t, sqlDB.QueryRowContext(ctx, ` + SELECT array_agg(chat_projects.name || ':' || pin_order ORDER BY pin_order) + FROM chat_project_pins JOIN chat_projects ON chat_projects.id = chat_project_pins.project_id + WHERE user_id = $1`, userID).Scan(&got)) + return got + } + require.Equal(t, []string{"apple:1", "Banana:2", "banana:3", "cherry:4"}, pins(first.ID)) + require.Equal(t, []string{"Shared:1"}, pins(second.ID)) +} diff --git a/coderd/database/migrations/testdata/fixtures/000649_chat_project_pins.up.sql b/coderd/database/migrations/testdata/fixtures/000649_chat_project_pins.up.sql new file mode 100644 index 00000000000..2e1283db407 --- /dev/null +++ b/coderd/database/migrations/testdata/fixtures/000649_chat_project_pins.up.sql @@ -0,0 +1,2 @@ +INSERT INTO chat_project_pins (user_id, project_id, pin_order) +VALUES ('30095c71-380b-457a-8995-97b8ee6e5307', '59400000-0000-4000-8000-000000000001', 1); diff --git a/coderd/database/modelqueries.go b/coderd/database/modelqueries.go index 28d4ad0b061..de13e607d1c 100644 --- a/coderd/database/modelqueries.go +++ b/coderd/database/modelqueries.go @@ -856,6 +856,8 @@ func (q *sqlQuerier) GetAuthorizedChats(ctx context.Context, arg GetChatsParams, pq.Array(arg.SharedWithGroupIds), arg.Archived, arg.ProjectID, + arg.ExcludeOwnProjectChats, + arg.ACLEnabled, arg.AfterID, arg.LabelFilter, arg.DiffURL, diff --git a/coderd/database/models.go b/coderd/database/models.go index 726bd3e9fbc..e4d4105c664 100644 --- a/coderd/database/models.go +++ b/coderd/database/models.go @@ -5682,6 +5682,14 @@ type ChatProjectMemory struct { CreatedAt time.Time `db:"created_at" json:"created_at"` } +// Per-user pinned chat projects. Pins can outlive project access, so readers must check access. +type ChatProjectPin struct { + UserID uuid.UUID `db:"user_id" json:"user_id"` + ProjectID uuid.UUID `db:"project_id" json:"project_id"` + PinOrder int32 `db:"pin_order" json:"pin_order"` + CreatedAt time.Time `db:"created_at" json:"created_at"` +} + // Templates attached to chat projects. An attachment never grants access to its template; every reader is checked against the template itself. type ChatProjectTemplate struct { ProjectID uuid.UUID `db:"project_id" json:"project_id"` diff --git a/coderd/database/querier.go b/coderd/database/querier.go index 154523e0cfd..1d67b1c099b 100644 --- a/coderd/database/querier.go +++ b/coderd/database/querier.go @@ -1541,6 +1541,10 @@ type sqlcQuerier interface { // pin/unpin/reorder operation's ROW_NUMBER() self-heals the // sequence, so this is acceptable. PinChatByID(ctx context.Context, id uuid.UUID) error + // Pins a project at the end of the user's list. An existing pin keeps its + // place. Callers must hold the per-user pin lock, or two new pins could + // take the same position. + PinChatProject(ctx context.Context, arg PinChatProjectParams) error ReduceWorkspaceAgentShareLevelToAuthenticatedByTemplate(ctx context.Context, templateID uuid.UUID) error RegisterWorkspaceProxy(ctx context.Context, arg RegisterWorkspaceProxyParams) (WorkspaceProxy, error) ReindexStaleChatMessagesSearchTsv(ctx context.Context, batchSize int32) (int64, error) @@ -1555,6 +1559,12 @@ type sqlcQuerier interface { // granted, so a lease that a committed admission counted as stale cannot // be renewed afterwards. RenewChatHeartbeats(ctx context.Context, arg RenewChatHeartbeatsParams) ([]RenewChatHeartbeatsRow, error) + // Puts the user's pins on project_ids in that order, followed by the user's + // other pins in their current order. IDs the user has not pinned are + // ignored. The other pins include those on projects the user can no longer + // see, so no caller has to work out which pins are hidden. Callers must hold + // the per-user pin lock, or overlapping reorders could deadlock. + ReorderChatProjectPins(ctx context.Context, arg ReorderChatProjectPinsParams) error RevokeDBCryptKey(ctx context.Context, activeKeyDigest string) error // Note that this selects from the CTE, not the original table. The CTE is named // the same as the original table to trick sqlc into reusing the existing struct @@ -1610,6 +1620,10 @@ type sqlcQuerier interface { // re-authenticate under a new OIDC provider. UnlinkOIDCUsersByIssuerMismatch(ctx context.Context, expectedPrefix string) (int64, error) UnpinChatByID(ctx context.Context, id uuid.UUID) error + // Deletes a pin. Unpinning a project that is not pinned changes nothing. + // The remaining pins keep their order, with a gap in pin_order until the + // next reorder. + UnpinChatProject(ctx context.Context, arg UnpinChatProjectParams) error UnsetDefaultChatModelConfigs(ctx context.Context, organizationID uuid.UUID) error UpdateAIBridgeInterceptionEnded(ctx context.Context, arg UpdateAIBridgeInterceptionEndedParams) (AIBridgeInterception, error) // Records heartbeat liveness for an active Gateway DRPC session. The database sets the diff --git a/coderd/database/queries.sql.go b/coderd/database/queries.sql.go index 83a7c5bdb25..2d1cb6121f3 100644 --- a/coderd/database/queries.sql.go +++ b/coderd/database/queries.sql.go @@ -8485,6 +8485,74 @@ func (q *sqlQuerier) InsertChatProjectMemory(ctx context.Context, arg InsertChat return i, err } +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 +FROM chat_project_pins +WHERE user_id = $1::uuid +ON CONFLICT (user_id, project_id) DO NOTHING +` + +type PinChatProjectParams struct { + UserID uuid.UUID `db:"user_id" json:"user_id"` + ProjectID uuid.UUID `db:"project_id" json:"project_id"` +} + +// Pins a project at the end of the user's list. An existing pin keeps its +// place. Callers must hold the per-user pin lock, or two new pins could +// take the same position. +func (q *sqlQuerier) PinChatProject(ctx context.Context, arg PinChatProjectParams) error { + _, err := q.db.ExecContext(ctx, pinChatProject, arg.UserID, arg.ProjectID) + return err +} + +const reorderChatProjectPins = `-- name: ReorderChatProjectPins :exec +WITH ranked AS ( + SELECT p.project_id, ROW_NUMBER() OVER ( + ORDER BY array_position($2::uuid[], p.project_id) ASC NULLS LAST, p.pin_order ASC, p.project_id ASC + ) :: integer AS pin_order + FROM chat_project_pins p + WHERE p.user_id = $1::uuid +) +UPDATE chat_project_pins p +SET pin_order = ranked.pin_order +FROM ranked +WHERE p.user_id = $1::uuid AND p.project_id = ranked.project_id +` + +type ReorderChatProjectPinsParams struct { + UserID uuid.UUID `db:"user_id" json:"user_id"` + ProjectIDs []uuid.UUID `db:"project_ids" json:"project_ids"` +} + +// Puts the user's pins on project_ids in that order, followed by the user's +// other pins in their current order. IDs the user has not pinned are +// ignored. The other pins include those on projects the user can no longer +// see, so no caller has to work out which pins are hidden. Callers must hold +// the per-user pin lock, or overlapping reorders could deadlock. +func (q *sqlQuerier) ReorderChatProjectPins(ctx context.Context, arg ReorderChatProjectPinsParams) error { + _, err := q.db.ExecContext(ctx, reorderChatProjectPins, arg.UserID, pq.Array(arg.ProjectIDs)) + return err +} + +const unpinChatProject = `-- name: UnpinChatProject :exec +DELETE FROM chat_project_pins +WHERE user_id = $1::uuid AND project_id = $2::uuid +` + +type UnpinChatProjectParams struct { + UserID uuid.UUID `db:"user_id" json:"user_id"` + ProjectID uuid.UUID `db:"project_id" json:"project_id"` +} + +// Deletes a pin. Unpinning a project that is not pinned changes nothing. +// The remaining pins keep their order, with a gap in pin_order until the +// next reorder. +func (q *sqlQuerier) UnpinChatProject(ctx context.Context, arg UnpinChatProjectParams) error { + _, err := q.db.ExecContext(ctx, unpinChatProject, arg.UserID, arg.ProjectID) + return err +} + const countChatProjectsByOwnerID = `-- name: CountChatProjectsByOwnerID :one SELECT COUNT(*)::bigint FROM chat_projects @@ -8679,27 +8747,7 @@ func (q *sqlQuerier) GetChatProjectTemplatesByProjectIDs(ctx context.Context, pr const getChatProjectsOwnedOrSharedWithUserID = `-- name: GetChatProjectsOwnedOrSharedWithUserID :many SELECT chat_projects.id, chat_projects.organization_id, chat_projects.owner_id, chat_projects.name, chat_projects.description, chat_projects.icon, chat_projects.created_at, chat_projects.updated_at, chat_projects.user_acl, chat_projects.group_acl, chat_projects.limit_templates, chat_projects.default_template_id, chat_projects.default_template_version_preset_id, chat_projects.default_parameters FROM chat_projects -WHERE chat_projects.owner_id = $1::uuid - OR ( - ( - chat_projects.user_acl ? ($1::uuid)::text - OR chat_projects.group_acl ?| ARRAY( - SELECT group_members.group_id::text - FROM group_members - WHERE group_members.user_id = $1::uuid - UNION ALL - SELECT organization_members.organization_id::text - FROM organization_members - WHERE organization_members.user_id = $1::uuid - ) - ) - AND EXISTS ( - SELECT 1 - FROM organization_members - WHERE organization_members.user_id = $1::uuid - AND organization_members.organization_id = chat_projects.organization_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 ` @@ -11822,11 +11870,12 @@ func (q *sqlQuerier) GetChatWorkerAcquisitionCandidates(ctx context.Context, arg const getChats = `-- name: GetChats :many WITH cursor_chat AS ( SELECT + owner_id, pin_order, updated_at, id FROM chats - WHERE id = $8 + WHERE id = $10 ) SELECT chats_expanded.id, chats_expanded.owner_id, chats_expanded.workspace_id, chats_expanded.title, chats_expanded.status, chats_expanded.worker_id, chats_expanded.started_at, chats_expanded.heartbeat_at, chats_expanded.created_at, chats_expanded.updated_at, chats_expanded.parent_chat_id, chats_expanded.root_chat_id, chats_expanded.last_model_config_id, chats_expanded.last_reasoning_effort, chats_expanded.archived, chats_expanded.last_error, chats_expanded.mode, chats_expanded.mcp_server_ids, chats_expanded.labels, chats_expanded.build_id, chats_expanded.agent_id, chats_expanded.pin_order, chats_expanded.last_read_message_id, chats_expanded.dynamic_tools, chats_expanded.organization_id, chats_expanded.project_id, chats_expanded.plan_mode, chats_expanded.client_type, chats_expanded.last_turn_summary, chats_expanded.summary, chats_expanded.summary_generated_at, chats_expanded.snapshot_version, chats_expanded.history_version, chats_expanded.queue_version, chats_expanded.generation_attempt, chats_expanded.retry_state, chats_expanded.retry_state_version, chats_expanded.runner_id, chats_expanded.requires_action_deadline_at, chats_expanded.user_acl, chats_expanded.group_acl, chats_expanded.owner_username, chats_expanded.owner_name, chats_expanded.context_aggregate_hash, chats_expanded.context_dirty_since, chats_expanded.context_dirty_resources, chats_expanded.context_error, chats_expanded.compaction_requested_at, chats_expanded.title_source, chats_expanded.title_updated_at, @@ -11860,16 +11909,40 @@ WHERE WHEN $7::uuid IS NOT NULL THEN chats_expanded.project_id = $7::uuid ELSE true END + -- Leaves out the viewer's own unpinned chats in projects the viewer can + -- use, which clients list per project with project_id. Project pins do + -- not change the result. Filtering here, not after the query, keeps + -- cursor pages full. + AND CASE + WHEN $8::boolean THEN ( + chats_expanded.project_id IS NULL + OR chats_expanded.owner_id != $3::uuid + OR chats_expanded.pin_order > 0 + -- A chat in a project the viewer can no longer use stays + -- listed: the project is missing from the viewer's projects, so + -- no project list reaches the chat. + OR chats_expanded.project_id NOT IN ( + SELECT project_id FROM chat_project_ids_for_user($3::uuid, $9::boolean) + ) + ) + ELSE true + END AND CASE -- Cursor pagination: the last element on a page acts as the cursor. -- The 4-tuple matches the ORDER BY below. All columns sort DESC -- (pin_order is negated so lower values sort first in DESC order), - -- which lets us use a single tuple < comparison. - WHEN $8 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN ( - (CASE WHEN chats_expanded.pin_order > 0 THEN 1 ELSE 0 END, -chats_expanded.pin_order, chats_expanded.updated_at, chats_expanded.id) < ( + -- which lets us use a single tuple < comparison. Like the ORDER BY, + -- it counts a pin only on the viewer's own chats. + WHEN $10 :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN ( + ( + CASE WHEN chats_expanded.owner_id = $3::uuid AND chats_expanded.pin_order > 0 THEN 1 ELSE 0 END, + CASE WHEN chats_expanded.owner_id = $3::uuid THEN -chats_expanded.pin_order ELSE 0 END, + chats_expanded.updated_at, + chats_expanded.id + ) < ( SELECT - CASE WHEN cursor_chat.pin_order > 0 THEN 1 ELSE 0 END, - -cursor_chat.pin_order, + CASE WHEN cursor_chat.owner_id = $3::uuid AND cursor_chat.pin_order > 0 THEN 1 ELSE 0 END, + CASE WHEN cursor_chat.owner_id = $3::uuid THEN -cursor_chat.pin_order ELSE 0 END, cursor_chat.updated_at, cursor_chat.id FROM @@ -11879,20 +11952,20 @@ WHERE ELSE true END AND CASE - WHEN $9::jsonb IS NOT NULL THEN chats_expanded.labels @> $9::jsonb + WHEN $11::jsonb IS NOT NULL THEN chats_expanded.labels @> $11::jsonb ELSE true END -- Match linked diff URLs (e.g. pull request URLs) case-insensitively. -- Include rows on a chat's subagent chats because the schema does not -- enforce root-only diff-status ownership. AND CASE - WHEN $10::text IS NOT NULL THEN EXISTS ( + WHEN $12::text IS NOT NULL THEN EXISTS ( SELECT 1 FROM chat_diff_statuses cds JOIN chats c2 ON c2.id = cds.chat_id WHERE cds.url IS NOT NULL AND cds.url <> '' - AND LOWER(cds.url) = LOWER($10::text) + AND LOWER(cds.url) = LOWER($12::text) AND (c2.id = chats_expanded.id OR c2.root_chat_id = chats_expanded.id) ) ELSE true @@ -11900,11 +11973,11 @@ WHERE -- Filter by title substring (case-insensitive). Applied when the -- caller provides a non-empty title_query. AND CASE - WHEN $11 :: text != '' THEN chats_expanded.title ILIKE '%' || $11 || '%' + WHEN $13 :: text != '' THEN chats_expanded.title ILIKE '%' || $13 || '%' ELSE true END AND CASE - WHEN $12::boolean IS NOT NULL THEN ( + WHEN $14::boolean IS NOT NULL THEN ( EXISTS ( SELECT 1 FROM chat_messages cm WHERE cm.chat_id = chats_expanded.id @@ -11912,23 +11985,23 @@ WHERE AND cm.deleted = false AND cm.id > COALESCE(chats_expanded.last_read_message_id, 0) ) - ) = $12::boolean + ) = $14::boolean ELSE true END -- Filter by the stored chat_status enum, the same value the sidebar -- row icon uses. AND CASE - WHEN COALESCE(array_length($13::text[], 1), 0) > 0 THEN - chats_expanded.status::text = ANY($13::text[]) + WHEN COALESCE(array_length($15::text[], 1), 0) > 0 THEN + chats_expanded.status::text = ANY($15::text[]) ELSE true END -- Filter by pull request status stored on the root chat. -- "none" matches chats with no pull request: no diff-status row, or a -- row whose pull_request_state is null or empty. AND CASE - WHEN COALESCE(array_length($14::text[], 1), 0) > 0 THEN ( + WHEN COALESCE(array_length($16::text[], 1), 0) > 0 THEN ( ( - 'none' = ANY($14::text[]) + 'none' = ANY($16::text[]) AND NOT EXISTS ( SELECT 1 FROM chat_diff_statuses cds @@ -11946,56 +12019,56 @@ WHERE WHEN cds.pull_request_state = 'open' THEN 'open' ELSE cds.pull_request_state END - ) = ANY($14::text[]) + ) = ANY($16::text[]) ) ) ELSE true END -- Filter by PR number (exact match on chat's diff status). AND CASE - WHEN $15::int != 0 THEN EXISTS ( + WHEN $17::int != 0 THEN EXISTS ( SELECT 1 FROM chat_diff_statuses cds WHERE cds.chat_id = chats_expanded.id - AND cds.pr_number = $15 + AND cds.pr_number = $17 ) ELSE true END -- Filter by repository (substring match on remote origin or PR URL). AND CASE - WHEN $16::text != '' THEN EXISTS ( + WHEN $18::text != '' THEN EXISTS ( SELECT 1 FROM chat_diff_statuses cds WHERE cds.chat_id = chats_expanded.id AND ( - cds.git_remote_origin ILIKE '%' || $16 || '%' - OR cds.url ILIKE '%' || $16 || '%' + cds.git_remote_origin ILIKE '%' || $18 || '%' + OR cds.url ILIKE '%' || $18 || '%' ) ) ELSE true END -- Filter by pull request title (case-insensitive substring). AND CASE - WHEN $17::text != '' THEN EXISTS ( + WHEN $19::text != '' THEN EXISTS ( SELECT 1 FROM chat_diff_statuses cds WHERE cds.chat_id = chats_expanded.id - AND cds.pull_request_title ILIKE '%' || $17 || '%' + AND cds.pull_request_title ILIKE '%' || $19 || '%' ) ELSE true END -- websearch_to_tsquery accepts quoted phrases, OR, and -negation; -- the 'simple' config folds case and skips stemming. AND CASE - WHEN $18::text != '' THEN ( + WHEN $20::text != '' THEN ( -- Served by idx_chats_title_fts. - to_tsvector('simple', chats_expanded.title) @@ websearch_to_tsquery('simple', $18) + to_tsvector('simple', chats_expanded.title) @@ websearch_to_tsquery('simple', $20) -- Served by idx_chat_diff_statuses_pr_title_fts. OR EXISTS ( SELECT 1 FROM chat_diff_statuses cds WHERE cds.chat_id = chats_expanded.id - AND to_tsvector('simple', cds.pull_request_title) @@ websearch_to_tsquery('simple', $18) + AND to_tsvector('simple', cds.pull_request_title) @@ websearch_to_tsquery('simple', $20) ) -- The WHERE clause must repeat the predicate of the partial index -- idx_chat_messages_search_tsv so the planner can use it. Additional @@ -12009,18 +12082,18 @@ WHERE AND cm.visibility IN ('user', 'both') AND cm.role IN ('user', 'assistant') AND ( - (cm.search_tsv_config = 'english' AND cm.search_tsv @@ websearch_to_tsquery('english', $18)) - OR (cm.search_tsv_config IS NULL AND cm.search_tsv @@ websearch_to_tsquery('simple', $18)) + (cm.search_tsv_config = 'english' AND cm.search_tsv @@ websearch_to_tsquery('english', $20)) + OR (cm.search_tsv_config IS NULL AND cm.search_tsv @@ websearch_to_tsquery('simple', $20)) ) ) -- Digits only, so LIKE sees no metacharacters; a per-chat PK probe. OR CASE - WHEN $18 ~ '^[0-9]+$' THEN EXISTS ( + WHEN $20 ~ '^[0-9]+$' THEN EXISTS ( SELECT 1 FROM chat_diff_statuses cds WHERE cds.chat_id = chats_expanded.id AND cds.pr_number IS NOT NULL - AND cds.pr_number::text LIKE $18 || '%' + AND cds.pr_number::text LIKE $20 || '%' ) ELSE false END @@ -12038,39 +12111,42 @@ ORDER BY -- Pinned chats (pin_order > 0) sort before unpinned ones. Within -- pinned chats, lower pin_order values come first. The negation -- trick (-pin_order) keeps all sort columns DESC so the cursor - -- tuple < comparison works with uniform direction. - CASE WHEN chats_expanded.pin_order > 0 THEN 1 ELSE 0 END DESC, - -chats_expanded.pin_order DESC, + -- tuple < comparison works with uniform direction. A pin belongs to + -- the chat's owner, so another user's pinned chat sorts as unpinned. + CASE WHEN chats_expanded.owner_id = $3::uuid AND chats_expanded.pin_order > 0 THEN 1 ELSE 0 END DESC, + CASE WHEN chats_expanded.owner_id = $3::uuid THEN -chats_expanded.pin_order ELSE 0 END DESC, chats_expanded.updated_at DESC, chats_expanded.id DESC -OFFSET $19 +OFFSET $21 LIMIT -- The chat list is unbounded and expected to grow large. -- Default to 50 to prevent accidental excessively large queries. - COALESCE(NULLIF($20 :: int, 0), 50) + COALESCE(NULLIF($22 :: int, 0), 50) ` type GetChatsParams struct { - OwnedOnly bool `db:"owned_only" json:"owned_only"` - SharedOnly bool `db:"shared_only" json:"shared_only"` - ViewerID uuid.UUID `db:"viewer_id" json:"viewer_id"` - SharedWithUserID uuid.UUID `db:"shared_with_user_id" json:"shared_with_user_id"` - SharedWithGroupIds []string `db:"shared_with_group_ids" json:"shared_with_group_ids"` - Archived sql.NullBool `db:"archived" json:"archived"` - ProjectID uuid.NullUUID `db:"project_id" json:"project_id"` - AfterID uuid.UUID `db:"after_id" json:"after_id"` - LabelFilter pqtype.NullRawMessage `db:"label_filter" json:"label_filter"` - DiffURL sql.NullString `db:"diff_url" json:"diff_url"` - TitleQuery string `db:"title_query" json:"title_query"` - HasUnread sql.NullBool `db:"has_unread" json:"has_unread"` - ChatStatuses []string `db:"chat_statuses" json:"chat_statuses"` - PullRequestStatuses []string `db:"pull_request_statuses" json:"pull_request_statuses"` - PrNumber int32 `db:"pr_number" json:"pr_number"` - RepoQuery string `db:"repo_query" json:"repo_query"` - PrTitleQuery string `db:"pr_title_query" json:"pr_title_query"` - Search string `db:"search" json:"search"` - OffsetOpt int32 `db:"offset_opt" json:"offset_opt"` - LimitOpt int32 `db:"limit_opt" json:"limit_opt"` + OwnedOnly bool `db:"owned_only" json:"owned_only"` + SharedOnly bool `db:"shared_only" json:"shared_only"` + ViewerID uuid.UUID `db:"viewer_id" json:"viewer_id"` + SharedWithUserID uuid.UUID `db:"shared_with_user_id" json:"shared_with_user_id"` + SharedWithGroupIds []string `db:"shared_with_group_ids" json:"shared_with_group_ids"` + Archived sql.NullBool `db:"archived" json:"archived"` + ProjectID uuid.NullUUID `db:"project_id" json:"project_id"` + ExcludeOwnProjectChats sql.NullBool `db:"exclude_own_project_chats" json:"exclude_own_project_chats"` + ACLEnabled bool `db:"acl_enabled" json:"acl_enabled"` + AfterID uuid.UUID `db:"after_id" json:"after_id"` + LabelFilter pqtype.NullRawMessage `db:"label_filter" json:"label_filter"` + DiffURL sql.NullString `db:"diff_url" json:"diff_url"` + TitleQuery string `db:"title_query" json:"title_query"` + HasUnread sql.NullBool `db:"has_unread" json:"has_unread"` + ChatStatuses []string `db:"chat_statuses" json:"chat_statuses"` + PullRequestStatuses []string `db:"pull_request_statuses" json:"pull_request_statuses"` + PrNumber int32 `db:"pr_number" json:"pr_number"` + RepoQuery string `db:"repo_query" json:"repo_query"` + PrTitleQuery string `db:"pr_title_query" json:"pr_title_query"` + Search string `db:"search" json:"search"` + OffsetOpt int32 `db:"offset_opt" json:"offset_opt"` + LimitOpt int32 `db:"limit_opt" json:"limit_opt"` } type GetChatsRow struct { @@ -12087,6 +12163,8 @@ func (q *sqlQuerier) GetChats(ctx context.Context, arg GetChatsParams) ([]GetCha pq.Array(arg.SharedWithGroupIds), arg.Archived, arg.ProjectID, + arg.ExcludeOwnProjectChats, + arg.ACLEnabled, arg.AfterID, arg.LabelFilter, arg.DiffURL, diff --git a/coderd/database/queries/chatprojectpins.sql b/coderd/database/queries/chatprojectpins.sql new file mode 100644 index 00000000000..5cf97e2c89f --- /dev/null +++ b/coderd/database/queries/chatprojectpins.sql @@ -0,0 +1,34 @@ +-- name: PinChatProject :exec +-- Pins a project at the end of the user's list. An existing pin keeps its +-- place. Callers must hold the per-user pin lock, or two new pins could +-- take the same position. +INSERT INTO chat_project_pins (user_id, project_id, pin_order) +SELECT @user_id::uuid, @project_id::uuid, COALESCE(MAX(pin_order), 0) + 1 +FROM chat_project_pins +WHERE user_id = @user_id::uuid +ON CONFLICT (user_id, project_id) DO NOTHING; + +-- name: ReorderChatProjectPins :exec +-- Puts the user's pins on project_ids in that order, followed by the user's +-- other pins in their current order. IDs the user has not pinned are +-- ignored. The other pins include those on projects the user can no longer +-- see, so no caller has to work out which pins are hidden. Callers must hold +-- the per-user pin lock, or overlapping reorders could deadlock. +WITH ranked AS ( + SELECT p.project_id, ROW_NUMBER() OVER ( + ORDER BY array_position(@project_ids::uuid[], p.project_id) ASC NULLS LAST, p.pin_order ASC, p.project_id ASC + ) :: integer AS pin_order + FROM chat_project_pins p + WHERE p.user_id = @user_id::uuid +) +UPDATE chat_project_pins p +SET pin_order = ranked.pin_order +FROM ranked +WHERE p.user_id = @user_id::uuid AND p.project_id = ranked.project_id; + +-- name: UnpinChatProject :exec +-- Deletes a pin. Unpinning a project that is not pinned changes nothing. +-- The remaining pins keep their order, with a gap in pin_order until the +-- next reorder. +DELETE FROM chat_project_pins +WHERE user_id = @user_id::uuid AND project_id = @project_id::uuid; diff --git a/coderd/database/queries/chatprojects.sql b/coderd/database/queries/chatprojects.sql index 888bc553876..9617890aa9c 100644 --- a/coderd/database/queries/chatprojects.sql +++ b/coderd/database/queries/chatprojects.sql @@ -33,27 +33,7 @@ FOR UPDATE; -- authorize each row. SELECT chat_projects.* FROM chat_projects -WHERE chat_projects.owner_id = @user_id::uuid - OR ( - ( - chat_projects.user_acl ? (@user_id::uuid)::text - OR chat_projects.group_acl ?| ARRAY( - SELECT group_members.group_id::text - FROM group_members - WHERE group_members.user_id = @user_id::uuid - UNION ALL - SELECT organization_members.organization_id::text - FROM organization_members - WHERE organization_members.user_id = @user_id::uuid - ) - ) - AND EXISTS ( - SELECT 1 - FROM organization_members - WHERE organization_members.user_id = @user_id::uuid - AND organization_members.organization_id = chat_projects.organization_id - ) - ) +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; -- name: IsChatProjectUsableByUserID :one diff --git a/coderd/database/queries/chats.sql b/coderd/database/queries/chats.sql index a6b524d43c4..ba0367fb729 100644 --- a/coderd/database/queries/chats.sql +++ b/coderd/database/queries/chats.sql @@ -619,6 +619,7 @@ ORDER BY -- name: GetChats :many WITH cursor_chat AS ( SELECT + owner_id, pin_order, updated_at, id @@ -657,16 +658,40 @@ WHERE WHEN sqlc.narg('project_id')::uuid IS NOT NULL THEN chats_expanded.project_id = sqlc.narg('project_id')::uuid ELSE true END + -- Leaves out the viewer's own unpinned chats in projects the viewer can + -- use, which clients list per project with project_id. Project pins do + -- not change the result. Filtering here, not after the query, keeps + -- cursor pages full. + AND CASE + WHEN sqlc.narg('exclude_own_project_chats')::boolean THEN ( + chats_expanded.project_id IS NULL + OR chats_expanded.owner_id != @viewer_id::uuid + OR chats_expanded.pin_order > 0 + -- A chat in a project the viewer can no longer use stays + -- listed: the project is missing from the viewer's projects, so + -- no project list reaches the chat. + OR chats_expanded.project_id NOT IN ( + SELECT project_id FROM chat_project_ids_for_user(@viewer_id::uuid, @acl_enabled::boolean) + ) + ) + ELSE true + END AND CASE -- Cursor pagination: the last element on a page acts as the cursor. -- The 4-tuple matches the ORDER BY below. All columns sort DESC -- (pin_order is negated so lower values sort first in DESC order), - -- which lets us use a single tuple < comparison. + -- which lets us use a single tuple < comparison. Like the ORDER BY, + -- it counts a pin only on the viewer's own chats. WHEN @after_id :: uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN ( - (CASE WHEN chats_expanded.pin_order > 0 THEN 1 ELSE 0 END, -chats_expanded.pin_order, chats_expanded.updated_at, chats_expanded.id) < ( + ( + CASE WHEN chats_expanded.owner_id = @viewer_id::uuid AND chats_expanded.pin_order > 0 THEN 1 ELSE 0 END, + CASE WHEN chats_expanded.owner_id = @viewer_id::uuid THEN -chats_expanded.pin_order ELSE 0 END, + chats_expanded.updated_at, + chats_expanded.id + ) < ( SELECT - CASE WHEN cursor_chat.pin_order > 0 THEN 1 ELSE 0 END, - -cursor_chat.pin_order, + CASE WHEN cursor_chat.owner_id = @viewer_id::uuid AND cursor_chat.pin_order > 0 THEN 1 ELSE 0 END, + CASE WHEN cursor_chat.owner_id = @viewer_id::uuid THEN -cursor_chat.pin_order ELSE 0 END, cursor_chat.updated_at, cursor_chat.id FROM @@ -835,9 +860,10 @@ ORDER BY -- Pinned chats (pin_order > 0) sort before unpinned ones. Within -- pinned chats, lower pin_order values come first. The negation -- trick (-pin_order) keeps all sort columns DESC so the cursor - -- tuple < comparison works with uniform direction. - CASE WHEN chats_expanded.pin_order > 0 THEN 1 ELSE 0 END DESC, - -chats_expanded.pin_order DESC, + -- tuple < comparison works with uniform direction. A pin belongs to + -- the chat's owner, so another user's pinned chat sorts as unpinned. + CASE WHEN chats_expanded.owner_id = @viewer_id::uuid AND chats_expanded.pin_order > 0 THEN 1 ELSE 0 END DESC, + CASE WHEN chats_expanded.owner_id = @viewer_id::uuid THEN -chats_expanded.pin_order ELSE 0 END DESC, chats_expanded.updated_at DESC, chats_expanded.id DESC OFFSET @offset_opt diff --git a/coderd/database/sqlc.yaml b/coderd/database/sqlc.yaml index 2821a40c696..798f01ac9ad 100644 --- a/coderd/database/sqlc.yaml +++ b/coderd/database/sqlc.yaml @@ -265,6 +265,7 @@ sql: workspace_group_acl: WorkspaceGroupACL user_acl_display_info: UserACLDisplayInfo group_acl_display_info: GroupACLDisplayInfo + acl_enabled: ACLEnabled troubleshooting_url: TroubleshootingURL default_ttl: DefaultTTL motd_file: MOTDFile @@ -273,6 +274,7 @@ sql: time_til_dormant_autodelete: TimeTilDormantAutoDelete eof: EOF template_ids: TemplateIDs + project_ids: ProjectIDs active_user_ids: ActiveUserIDs display_app_ssh_helper: DisplayAppSSHHelper oauth2_provider_app: OAuth2ProviderApp diff --git a/coderd/database/unique_constraint.go b/coderd/database/unique_constraint.go index 6c51b101412..bfa11ed240c 100644 --- a/coderd/database/unique_constraint.go +++ b/coderd/database/unique_constraint.go @@ -41,6 +41,7 @@ const ( UniqueChatOrganizationSystemPromptsPkey UniqueConstraint = "chat_organization_system_prompts_pkey" // ALTER TABLE ONLY chat_organization_system_prompts ADD CONSTRAINT chat_organization_system_prompts_pkey PRIMARY KEY (organization_id); UniqueChatProjectInstructionsPkey UniqueConstraint = "chat_project_instructions_pkey" // ALTER TABLE ONLY chat_project_instructions ADD CONSTRAINT chat_project_instructions_pkey PRIMARY KEY (project_id); UniqueChatProjectMemoriesPkey UniqueConstraint = "chat_project_memories_pkey" // ALTER TABLE ONLY chat_project_memories ADD CONSTRAINT chat_project_memories_pkey PRIMARY KEY (id); + UniqueChatProjectPinsPkey UniqueConstraint = "chat_project_pins_pkey" // ALTER TABLE ONLY chat_project_pins ADD CONSTRAINT chat_project_pins_pkey PRIMARY KEY (user_id, project_id); UniqueChatProjectTemplatesPkey UniqueConstraint = "chat_project_templates_pkey" // ALTER TABLE ONLY chat_project_templates ADD CONSTRAINT chat_project_templates_pkey PRIMARY KEY (project_id, template_id); UniqueChatProjectsPkey UniqueConstraint = "chat_projects_pkey" // ALTER TABLE ONLY chat_projects ADD CONSTRAINT chat_projects_pkey PRIMARY KEY (id); UniqueChatQueuedMessagesPkey UniqueConstraint = "chat_queued_messages_pkey" // ALTER TABLE ONLY chat_queued_messages ADD CONSTRAINT chat_queued_messages_pkey PRIMARY KEY (id); diff --git a/coderd/exp_chats.go b/coderd/exp_chats.go index 696882b0aed..5e164897b04 100644 --- a/coderd/exp_chats.go +++ b/coderd/exp_chats.go @@ -461,6 +461,7 @@ func (api *API) chatsByWorkspace(rw http.ResponseWriter, r *http.Request) { // @Param limit query int false "Page limit" // @Param offset query int false "Page offset" // @Param project_id query string false "Only chats in this project." format(uuid) +// @Param exclude_own_project_chats query bool false "Leave out the caller's own unpinned chats in projects the caller can use. Project pins do not change the result." // @Success 200 {array} codersdk.Chat // @Router /api/v2/chats [get] func (api *API) listChats(rw http.ResponseWriter, r *http.Request) { @@ -535,6 +536,16 @@ func (api *API) listChats(rw http.ResponseWriter, r *http.Request) { projectID = uuid.NullUUID{UUID: parsedProjectID, Valid: true} } + parser := httpapi.NewQueryParamParser() + excludeOwnProjectChats := parser.Boolean(r.URL.Query(), false, "exclude_own_project_chats") + if len(parser.Errors) > 0 { + httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ + Message: "Invalid query parameters.", + Validations: parser.Errors, + }) + return + } + params := database.GetChatsParams{ OwnedOnly: searchParams.OwnedOnly, ViewerID: apiKey.UserID, @@ -554,6 +565,10 @@ func (api *API) listChats(rw http.ResponseWriter, r *http.Request) { PrTitleQuery: searchParams.PrTitleQuery, Search: searchParams.Search, ProjectID: projectID, + // ExcludeOwnProjectChats counts project grants only while RBAC + // honors them. + ACLEnabled: !api.chatSharingDisabled(), + ExcludeOwnProjectChats: sql.NullBool{Bool: excludeOwnProjectChats, Valid: excludeOwnProjectChats}, // #nosec G115 - Pagination offsets are small and fit in int32 OffsetOpt: int32(paginationParams.Offset), // #nosec G115 - Pagination limits are small and fit in int32 diff --git a/codersdk/chats.go b/codersdk/chats.go index 11c9aa28a75..efb2759ced0 100644 --- a/codersdk/chats.go +++ b/codersdk/chats.go @@ -285,6 +285,15 @@ type ChatProjectDefaultTemplate struct { Parameters map[string]string `json:"parameters,omitempty"` } +// ReorderChatProjectPinsRequest sets the order of the caller's pinned chat +// projects. +type ReorderChatProjectPinsRequest struct { + // ProjectIDs are the pinned projects in their new order. Pins that are + // left out follow the listed ones in their current order, and IDs the + // caller has not pinned are ignored. + ProjectIDs []uuid.UUID `json:"project_ids" format:"uuid"` +} + // CreateChatProjectRequest creates a chat project in the organization named // by the route. type CreateChatProjectRequest struct { @@ -2517,6 +2526,11 @@ type ListChatsOptions struct { Source ChatListSource Labels map[string]string ProjectID *uuid.UUID + // ExcludeOwnProjectChats leaves out the caller's own unpinned chats in + // projects the caller can use. List those with ProjectID. Chats shared + // with the caller and chats in projects the caller can no longer use are + // still included. + ExcludeOwnProjectChats bool Pagination } @@ -2574,6 +2588,13 @@ func (c *Client) ListChats(ctx context.Context, opts *ListChatsOptions) ([]Chat, r.URL.RawQuery = q.Encode() }) } + if opts.ExcludeOwnProjectChats { + reqOpts = append(reqOpts, func(r *http.Request) { + q := r.URL.Query() + q.Set("exclude_own_project_chats", "true") + r.URL.RawQuery = q.Encode() + }) + } if len(opts.Labels) > 0 { reqOpts = append(reqOpts, func(r *http.Request) { q := r.URL.Query() @@ -2672,6 +2693,22 @@ func (c *ExperimentalClient) DeleteChatProject(ctx context.Context, organization return 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 { + return requestNoContent(ctx, c.Client, http.MethodPut, chatProjectPath(organizationID, projectID)+"/pin", nil) +} + +// ReorderChatProjectPins sets the order of the caller's pinned chat projects. +func (c *ExperimentalClient) ReorderChatProjectPins(ctx context.Context, req ReorderChatProjectPinsRequest) error { + return requestNoContent(ctx, c.Client, http.MethodPut, "/api/experimental/chats/projects/pins/order", req) +} + +// UnpinChatProject unpins a chat project for the caller. +func (c *ExperimentalClient) UnpinChatProject(ctx context.Context, organizationID, projectID uuid.UUID) error { + return requestNoContent(ctx, c.Client, http.MethodDelete, chatProjectPath(organizationID, projectID)+"/pin", nil) +} + // ChatProjectACL returns who a chat project is shared with. func (c *ExperimentalClient) ChatProjectACL(ctx context.Context, organizationID, projectID uuid.UUID) (ChatProjectACL, error) { res, err := c.Request(ctx, http.MethodGet, chatProjectPath(organizationID, projectID)+"/acl", nil) diff --git a/docs/reference/api/chats.md b/docs/reference/api/chats.md index 71535f0aef2..35fa1c435c3 100644 --- a/docs/reference/api/chats.md +++ b/docs/reference/api/chats.md @@ -52,14 +52,15 @@ curl -X GET http://coder-server:8080/api/v2/chats \ ### Parameters -| Name | In | Type | Required | Description | -|--------------|-------|---------------|----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `q` | query | string | false | Search query. Supports `title:` (case-insensitive, quote multi-word values), `archived:bool`, `has_unread:bool`, `status:` (chat status, repeated or comma-separated), `pr_status:` (none matches chats with no pull request) as repeated or comma-separated values, `source:`, `diff_url:` (quote values containing colons), `pr:` (exact PR number match), `repo:` (case-insensitive substring match against git remote origin or URL), `pr_title:` (case-insensitive PR title substring), `search:` (full-text search across chat titles, PR titles, PR numbers, and message bodies; message bodies match English word stems, e.g. `refactor` matches `refactoring`, and ignore English stopwords; titles and PR titles match whole words case-insensitively without stemming; quote multi-word values; cannot be combined with title, pr_title, or pr; a value that tokenizes to no searchable words, e.g. punctuation only, returns an empty list). Bare terms are not supported; use `title:` or `search:`. | -| `label` | query | array[string] | false | Filter by label as key:value. Repeat for multiple (AND logic). | -| `after_id` | query | string(uuid) | false | After ID | -| `limit` | query | integer | false | Page limit | -| `offset` | query | integer | false | Page offset | -| `project_id` | query | string(uuid) | false | Only chats in this project. | +| Name | In | Type | Required | Description | +|-----------------------------|-------|---------------|----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `q` | query | string | false | Search query. Supports `title:` (case-insensitive, quote multi-word values), `archived:bool`, `has_unread:bool`, `status:` (chat status, repeated or comma-separated), `pr_status:` (none matches chats with no pull request) as repeated or comma-separated values, `source:`, `diff_url:` (quote values containing colons), `pr:` (exact PR number match), `repo:` (case-insensitive substring match against git remote origin or URL), `pr_title:` (case-insensitive PR title substring), `search:` (full-text search across chat titles, PR titles, PR numbers, and message bodies; message bodies match English word stems, e.g. `refactor` matches `refactoring`, and ignore English stopwords; titles and PR titles match whole words case-insensitively without stemming; quote multi-word values; cannot be combined with title, pr_title, or pr; a value that tokenizes to no searchable words, e.g. punctuation only, returns an empty list). Bare terms are not supported; use `title:` or `search:`. | +| `label` | query | array[string] | false | Filter by label as key:value. Repeat for multiple (AND logic). | +| `after_id` | query | string(uuid) | false | After ID | +| `limit` | query | integer | false | Page limit | +| `offset` | query | integer | false | Page offset | +| `project_id` | query | string(uuid) | false | Only chats in this project. | +| `exclude_own_project_chats` | query | boolean | false | Leave out the caller's own unpinned chats in projects the caller can use. Project pins do not change the result. | ### Example responses diff --git a/docs/reference/api/schemas.md b/docs/reference/api/schemas.md index 6387f485698..e2ab9c5d86d 100644 --- a/docs/reference/api/schemas.md +++ b/docs/reference/api/schemas.md @@ -15155,6 +15155,22 @@ Git clone makes use of this by parsing the URL from: 'Username for "https://gith |-----------|-------------------------------------------------------------|----------|--------------|-------------| | `regions` | array of [codersdk.WorkspaceProxy](#codersdkworkspaceproxy) | false | | | +## codersdk.ReorderChatProjectPinsRequest + +```json +{ + "project_ids": [ + "497f6eca-6276-4993-bfeb-53cbbbba6f08" + ] +} +``` + +### Properties + +| Name | Type | Required | Restrictions | Description | +|---------------|-----------------|----------|--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `project_ids` | array of string | false | | Project ids are the pinned projects in their new order. Pins that are left out follow the listed ones in their current order, and IDs the caller has not pinned are ignored. | + ## codersdk.Replica ```json diff --git a/site/src/api/typesGenerated.ts b/site/src/api/typesGenerated.ts index a52aa1935c5..fd44fbd8741 100644 --- a/site/src/api/typesGenerated.ts +++ b/site/src/api/typesGenerated.ts @@ -6960,6 +6960,13 @@ export interface ListChatsOptions extends Pagination { readonly Source: ChatListSource; readonly Labels: Record; readonly ProjectID: string | null; + /** + * ExcludeOwnProjectChats leaves out the caller's own unpinned chats in + * projects the caller can use. List those with ProjectID. Chats shared + * with the caller and chats in projects the caller can no longer use are + * still included. + */ + readonly ExcludeOwnProjectChats: boolean; } // From codersdk/inboxnotification.go @@ -9742,6 +9749,20 @@ export interface RegionsResponse { readonly regions: readonly R[]; } +// From codersdk/chats.go +/** + * ReorderChatProjectPinsRequest sets the order of the caller's pinned chat + * projects. + */ +export interface ReorderChatProjectPinsRequest { + /** + * ProjectIDs are the pinned projects in their new order. Pins that are + * left out follow the listed ones in their current order, and IDs the + * caller has not pinned are ignored. + */ + readonly project_ids: readonly string[]; +} + // From codersdk/replicas.go export interface Replica { /**