diff --git a/coderd/apidoc/docs.go b/coderd/apidoc/docs.go index f77d5341eb0..c3af88743ff 100644 --- a/coderd/apidoc/docs.go +++ b/coderd/apidoc/docs.go @@ -2340,7 +2340,7 @@ const docTemplate = `{ "parameters": [ { "type": "string", - "description": "Search query. Supports ` + "`" + `title:\u003csubstring\u003e` + "`" + ` (case-insensitive, quote multi-word values), ` + "`" + `archived:bool` + "`" + `, ` + "`" + `has_unread:bool` + "`" + `, ` + "`" + `status:\u003cwaiting\\|running\\|error\\|requires_action\\|interrupting\u003e` + "`" + ` (chat status, repeated or comma-separated), ` + "`" + `pr_status:\u003cdraft\\|open\\|merged\\|closed\\|none\u003e` + "`" + ` (none matches chats with no pull request) as repeated or comma-separated values, ` + "`" + `source:\u003ccreated_by_me\\|shared_with_me\u003e` + "`" + `, ` + "`" + `diff_url:\u003curl\u003e` + "`" + ` (quote values containing colons), ` + "`" + `pr:\u003cnumber\u003e` + "`" + ` (exact PR number match), ` + "`" + `repo:\u003cowner/repo\u003e` + "`" + ` (case-insensitive substring match against git remote origin or URL), ` + "`" + `pr_title:\u003ctext\u003e` + "`" + ` (case-insensitive PR title substring), ` + "`" + `search:\u003ctext\u003e` + "`" + ` (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:\u003cvalue\u003e` + "`" + ` or ` + "`" + `search:\u003cvalue\u003e` + "`" + `.", + "description": "Search query. Supports ` + "`" + `title:\u003csubstring\u003e` + "`" + ` (case-insensitive, quote multi-word values), ` + "`" + `archived:bool` + "`" + ` (` + "`" + `archived:any` + "`" + ` matches archived and active chats), ` + "`" + `has_unread:bool` + "`" + `, ` + "`" + `status:\u003cwaiting\\|running\\|error\\|requires_action\\|interrupting\u003e` + "`" + ` (chat status, repeated or comma-separated), ` + "`" + `pr_status:\u003cdraft\\|open\\|merged\\|closed\\|none\u003e` + "`" + ` (none matches chats with no pull request) as repeated or comma-separated values, ` + "`" + `source:\u003ccreated_by_me\\|shared_with_me\u003e` + "`" + `, ` + "`" + `diff_url:\u003curl\u003e` + "`" + ` (quote values containing colons), ` + "`" + `pr:\u003cnumber\u003e` + "`" + ` (exact PR number match), ` + "`" + `repo:\u003cowner/repo\u003e` + "`" + ` (case-insensitive substring match against git remote origin or URL), ` + "`" + `pr_title:\u003ctext\u003e` + "`" + ` (case-insensitive PR title substring), ` + "`" + `search:\u003ctext\u003e` + "`" + ` (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:\u003cvalue\u003e` + "`" + ` or ` + "`" + `search:\u003cvalue\u003e` + "`" + `.", "name": "q", "in": "query" }, @@ -2373,6 +2373,13 @@ const docTemplate = `{ "name": "offset", "in": "query" }, + { + "type": "string", + "format": "uuid", + "description": "Filter to chats the automation created or sent messages to. Ignored unless the chat-automations experiment is enabled for the caller.", + "name": "automation_id", + "in": "query" + }, { "type": "string", "format": "uuid", diff --git a/coderd/apidoc/swagger.json b/coderd/apidoc/swagger.json index 075593e2568..dc21bb77a58 100644 --- a/coderd/apidoc/swagger.json +++ b/coderd/apidoc/swagger.json @@ -2081,7 +2081,7 @@ "parameters": [ { "type": "string", - "description": "Search query. Supports `title:\u003csubstring\u003e` (case-insensitive, quote multi-word values), `archived:bool`, `has_unread:bool`, `status:\u003cwaiting\\|running\\|error\\|requires_action\\|interrupting\u003e` (chat status, repeated or comma-separated), `pr_status:\u003cdraft\\|open\\|merged\\|closed\\|none\u003e` (none matches chats with no pull request) as repeated or comma-separated values, `source:\u003ccreated_by_me\\|shared_with_me\u003e`, `diff_url:\u003curl\u003e` (quote values containing colons), `pr:\u003cnumber\u003e` (exact PR number match), `repo:\u003cowner/repo\u003e` (case-insensitive substring match against git remote origin or URL), `pr_title:\u003ctext\u003e` (case-insensitive PR title substring), `search:\u003ctext\u003e` (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:\u003cvalue\u003e` or `search:\u003cvalue\u003e`.", + "description": "Search query. Supports `title:\u003csubstring\u003e` (case-insensitive, quote multi-word values), `archived:bool` (`archived:any` matches archived and active chats), `has_unread:bool`, `status:\u003cwaiting\\|running\\|error\\|requires_action\\|interrupting\u003e` (chat status, repeated or comma-separated), `pr_status:\u003cdraft\\|open\\|merged\\|closed\\|none\u003e` (none matches chats with no pull request) as repeated or comma-separated values, `source:\u003ccreated_by_me\\|shared_with_me\u003e`, `diff_url:\u003curl\u003e` (quote values containing colons), `pr:\u003cnumber\u003e` (exact PR number match), `repo:\u003cowner/repo\u003e` (case-insensitive substring match against git remote origin or URL), `pr_title:\u003ctext\u003e` (case-insensitive PR title substring), `search:\u003ctext\u003e` (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:\u003cvalue\u003e` or `search:\u003cvalue\u003e`.", "name": "q", "in": "query" }, @@ -2114,6 +2114,13 @@ "name": "offset", "in": "query" }, + { + "type": "string", + "format": "uuid", + "description": "Filter to chats the automation created or sent messages to. Ignored unless the chat-automations experiment is enabled for the caller.", + "name": "automation_id", + "in": "query" + }, { "type": "string", "format": "uuid", diff --git a/coderd/database/modelqueries.go b/coderd/database/modelqueries.go index 5b80fb1f9c4..a22d22f33fe 100644 --- a/coderd/database/modelqueries.go +++ b/coderd/database/modelqueries.go @@ -857,6 +857,7 @@ func (q *sqlQuerier) GetAuthorizedChats(ctx context.Context, arg GetChatsParams, arg.RepoQuery, arg.PrTitleQuery, arg.Search, + arg.AutomationID, arg.OffsetOpt, arg.LimitOpt, ) diff --git a/coderd/database/queries.sql.go b/coderd/database/queries.sql.go index 157479cd41e..a0a24d3b379 100644 --- a/coderd/database/queries.sql.go +++ b/coderd/database/queries.sql.go @@ -11331,6 +11331,21 @@ WHERE ) ELSE true END + -- Filter to chats an automation created or sent messages to. Served + -- by chats_automation_idx and chat_messages_automation_idx. + AND CASE + WHEN $19::uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN ( + chats_expanded.automation_id = $19::uuid + OR EXISTS ( + SELECT 1 + FROM chat_messages cm + WHERE cm.chat_id = chats_expanded.id + AND cm.automation_id = $19::uuid + AND cm.deleted = false + ) + ) + ELSE true + END -- Paginate over root chats only. Children are fetched -- separately via GetChildChatsByParentIDs and embedded under -- each parent. Other callers that need the full set should @@ -11347,11 +11362,11 @@ ORDER BY -chats_expanded.pin_order DESC, chats_expanded.updated_at DESC, chats_expanded.id DESC -OFFSET $19 +OFFSET $20 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($21 :: int, 0), 50) ` type GetChatsParams struct { @@ -11373,6 +11388,7 @@ type GetChatsParams struct { RepoQuery string `db:"repo_query" json:"repo_query"` PrTitleQuery string `db:"pr_title_query" json:"pr_title_query"` Search string `db:"search" json:"search"` + AutomationID uuid.UUID `db:"automation_id" json:"automation_id"` OffsetOpt int32 `db:"offset_opt" json:"offset_opt"` LimitOpt int32 `db:"limit_opt" json:"limit_opt"` } @@ -11402,6 +11418,7 @@ func (q *sqlQuerier) GetChats(ctx context.Context, arg GetChatsParams) ([]GetCha arg.RepoQuery, arg.PrTitleQuery, arg.Search, + arg.AutomationID, arg.OffsetOpt, arg.LimitOpt, ) diff --git a/coderd/database/queries/chats.sql b/coderd/database/queries/chats.sql index ab17d49b1a6..5ddcc4edf43 100644 --- a/coderd/database/queries/chats.sql +++ b/coderd/database/queries/chats.sql @@ -772,6 +772,21 @@ WHERE ) ELSE true END + -- Filter to chats an automation created or sent messages to. Served + -- by chats_automation_idx and chat_messages_automation_idx. + AND CASE + WHEN @automation_id::uuid != '00000000-0000-0000-0000-000000000000'::uuid THEN ( + chats_expanded.automation_id = @automation_id::uuid + OR EXISTS ( + SELECT 1 + FROM chat_messages cm + WHERE cm.chat_id = chats_expanded.id + AND cm.automation_id = @automation_id::uuid + AND cm.deleted = false + ) + ) + ELSE true + END -- Paginate over root chats only. Children are fetched -- separately via GetChildChatsByParentIDs and embedded under -- each parent. Other callers that need the full set should diff --git a/coderd/exp_chats.go b/coderd/exp_chats.go index b924ee4a2bc..29d65da954a 100644 --- a/coderd/exp_chats.go +++ b/coderd/exp_chats.go @@ -413,11 +413,12 @@ func (api *API) chatsByWorkspace(rw http.ResponseWriter, r *http.Request) { // @Security CoderSessionToken // @Tags Chats // @Produce json -// @Param 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:`." +// @Param q query string false "Search query. Supports `title:` (case-insensitive, quote multi-word values), `archived:bool` (`archived:any` matches archived and active chats), `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:`." // @Param label query []string false "Filter by label as key:value. Repeat for multiple (AND logic)." collectionFormat(multi) // @Param after_id query string false "After ID" format(uuid) // @Param limit query int false "Page limit" // @Param offset query int false "Page offset" +// @Param automation_id query string false "Filter to chats the automation created or sent messages to. Ignored unless the chat-automations experiment is enabled for the caller." format(uuid) // @Param project_id query string false "Only chats in this project. Requires the chat-projects experiment." format(uuid) // @Success 200 {array} codersdk.Chat // @Router /api/v2/chats [get] @@ -467,6 +468,30 @@ func (api *API) listChats(rw http.ResponseWriter, r *http.Request) { } } + // The chat list is not experiment-gated, so the automation filter is + // ignored, not rejected, when the experiment is off for the caller. + // The evaluator reads the database, so it runs only when the filter + // is requested. + automationID := uuid.Nil + if r.URL.Query().Has("automation_id") && chatd.AutomationsEnabled(ctx, api.ExperimentEvaluator, apiKey.UserID) { + parser := httpapi.NewQueryParamParser() + automationID = parser.UUID(r.URL.Query(), uuid.Nil, "automation_id") + // The query treats the nil UUID as "no filter". + if len(parser.Errors) == 0 && automationID == uuid.Nil { + parser.Errors = append(parser.Errors, codersdk.ValidationError{ + Field: "automation_id", + Detail: "Query param \"automation_id\" must not be the nil UUID.", + }) + } + if len(parser.Errors) > 0 { + httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ + Message: "Query parameters have invalid values.", + Validations: parser.Errors, + }) + return + } + } + var sharedWithGroupIDs []string if searchParams.SharedOnly { groups, err := api.Database.GetGroups(ctx, database.GetGroupsParams{HasMemberID: apiKey.UserID}) @@ -517,6 +542,7 @@ func (api *API) listChats(rw http.ResponseWriter, r *http.Request) { RepoQuery: searchParams.RepoQuery, PrTitleQuery: searchParams.PrTitleQuery, Search: searchParams.Search, + AutomationID: automationID, ProjectID: projectID, // #nosec G115 - Pagination offsets are small and fit in int32 OffsetOpt: int32(paginationParams.Offset), diff --git a/coderd/exp_chats_test.go b/coderd/exp_chats_test.go index 31c220955ad..9bed490ac71 100644 --- a/coderd/exp_chats_test.go +++ b/coderd/exp_chats_test.go @@ -3025,6 +3025,95 @@ func TestListChats(t *testing.T) { require.Equal(t, archivedWithPR.ID, chats[0].ID) }) }) + + t.Run("AutomationFilter", func(t *testing.T) { + t.Parallel() + + env := newChatAutomationTestEnv(t, nil, nil) + ctx := testutil.Context(t, testutil.WaitLong) + automationID := uuid.New() + markCreatedBy := func(chat database.Chat) { + t.Helper() + rows, err := env.db.UpdateChatAutomationIDByID(dbauthz.AsSystemRestricted(ctx), database.UpdateChatAutomationIDByIDParams{ + ID: chat.ID, + AutomationID: automationID, + }) + require.NoError(t, err) + require.EqualValues(t, 1, rows) + } + newMemberChat := func() database.Chat { + return dbgen.Chat(t, env.db, database.Chat{ + OrganizationID: env.orgID, + OwnerID: env.memberID, + LastModelConfigID: env.modelConfig.ID, + }) + } + + created := newMemberChat() + markCreatedBy(created) + // Archived chats stay in the automation's history when the + // caller asks for archived:any. + archivedCreated := newMemberChat() + markCreatedBy(archivedCreated) + require.NoError(t, env.member.UpdateChat(ctx, archivedCreated.ID, codersdk.UpdateChatRequest{Archived: ptr.Ref(true)})) + // The automation only sent a message to this existing chat. + writtenTo := env.memberChat + dbgen.ChatMessage(t, env.db, database.ChatMessage{ + ChatID: writtenTo.ID, + AutomationID: uuid.NullUUID{UUID: automationID, Valid: true}, + }) + unrelated := newMemberChat() + // A deleted automation message no longer counts as writing to + // the chat. + deletedMessageChat := newMemberChat() + deletedMessage := dbgen.ChatMessage(t, env.db, database.ChatMessage{ + ChatID: deletedMessageChat.ID, + AutomationID: uuid.NullUUID{UUID: automationID, Valid: true}, + }) + require.NoError(t, env.db.SoftDeleteChatMessageByID(dbauthz.AsSystemRestricted(ctx), deletedMessage.ID)) + // Another user's chat that the member may not read. + owner, err := env.owner.User(ctx, codersdk.Me) + require.NoError(t, err) + markCreatedBy(dbgen.Chat(t, env.db, database.Chat{ + OrganizationID: env.orgID, + OwnerID: owner.ID, + LastModelConfigID: env.modelConfig.ID, + })) + + chatIDs := func(opts *codersdk.ListChatsOptions) []uuid.UUID { + t.Helper() + chats, err := env.member.ListChats(ctx, opts) + require.NoError(t, err) + ids := make([]uuid.UUID, 0, len(chats)) + for _, chat := range chats { + ids = append(ids, chat.ID) + } + return ids + } + + require.ElementsMatch(t, []uuid.UUID{created.ID, writtenTo.ID}, chatIDs(&codersdk.ListChatsOptions{AutomationID: automationID})) + require.ElementsMatch(t, []uuid.UUID{created.ID, archivedCreated.ID, writtenTo.ID}, chatIDs(&codersdk.ListChatsOptions{AutomationID: automationID, Query: "archived:any"})) + require.Equal(t, []uuid.UUID{archivedCreated.ID}, chatIDs(&codersdk.ListChatsOptions{AutomationID: automationID, Query: "archived:true"})) + require.Empty(t, chatIDs(&codersdk.ListChatsOptions{AutomationID: uuid.New()})) + + for _, value := range []string{"not-a-uuid", uuid.Nil.String()} { + status, body := rawGet(t, env.member, "/api/v2/chats?automation_id="+value) + require.Equal(t, http.StatusBadRequest, status, body) + require.Contains(t, body, "automation_id") + } + + // With the experiment off for the member, the filter is ignored. + member, err := env.member.User(ctx, codersdk.Me) + require.NoError(t, err) + _, err = env.owner.PutExperimentRule(ctx, codersdk.ExperimentChatAutomations, codersdk.PutExperimentRuleRequest{ + Mode: codersdk.ExperimentRuleModeCondition, + Condition: fmt.Sprintf("user.username != %q", member.Username), + }) + require.NoError(t, err) + require.ElementsMatch(t, []uuid.UUID{created.ID, writtenTo.ID, unrelated.ID, deletedMessageChat.ID}, chatIDs(&codersdk.ListChatsOptions{AutomationID: automationID})) + status, body := rawGet(t, env.member, "/api/v2/chats?automation_id=not-a-uuid") + require.Equal(t, http.StatusOK, status, body) + }) } func TestListChatModels(t *testing.T) { diff --git a/coderd/searchquery/search.go b/coderd/searchquery/search.go index a762d390ded..251faa9b1ca 100644 --- a/coderd/searchquery/search.go +++ b/coderd/searchquery/search.go @@ -499,8 +499,8 @@ func AIBridgeClients(query string, page codersdk.Pagination) (database.ListAIBri // Supported query parameters: // - title: case-insensitive title substring match via ILIKE (bare terms // are rejected; use title: for title filtering) -// - archived: boolean (default: false, excludes archived chats unless -// explicitly set) +// - archived: boolean, or any to include archived and active chats +// (default: false, excludes archived chats unless explicitly set) // - has_unread: nullable boolean (filter by unread message status) // - status: repeated or comma-separated chat_status enum value: // waiting, running, error, requires_action, or interrupting @@ -541,7 +541,14 @@ func Chats(query string) (database.GetChatsParams, []codersdk.ValidationError) { } parser := httpapi.NewQueryParamParser() - filter.Archived = parser.NullableBoolean(values, filter.Archived, "archived") + if archived := values["archived"]; len(archived) == 1 && strings.EqualFold(archived[0], "any") { + // A null filter matches archived and active chats. Deleting the + // term keeps ErrorExcessParams from rejecting it as unparsed. + filter.Archived = sql.NullBool{} + values.Del("archived") + } else { + filter.Archived = parser.NullableBoolean(values, filter.Archived, "archived") + } filter.HasUnread = parser.NullableBoolean(values, filter.HasUnread, "has_unread") filter.ChatStatuses = httpapi.ParseCustomList(parser, values, nil, "status", func(v string) (string, error) { status := database.ChatStatus(strings.ToLower(strings.TrimSpace(v))) diff --git a/coderd/searchquery/search_test.go b/coderd/searchquery/search_test.go index 996079688cc..9f090371c84 100644 --- a/coderd/searchquery/search_test.go +++ b/coderd/searchquery/search_test.go @@ -1091,8 +1091,8 @@ func TestSearchChatsFrontendEmitted(t *testing.T) { t.Parallel() // These query shapes must match the emitters in - // site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/searchQuery.ts - // and site/src/api/queries/chats.ts. + // site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/searchQuery.ts, + // site/src/api/queries/chats.ts and site/src/api/queries/chatAutomations.ts. testCases := []struct { name string query string @@ -1107,6 +1107,7 @@ func TestSearchChatsFrontendEmitted(t *testing.T) { {name: "SearchOperatorWord", query: `search:"or"`}, {name: "HasUnread", query: "has_unread:true"}, {name: "Archived", query: "archived:true"}, + {name: "AutomationHistory", query: "archived:any"}, {name: "PRStatuses", query: "pr_status:open,merged"}, {name: "ChatStatuses", query: "status:error,running"}, {name: "PRStatusNone", query: "pr_status:none"}, @@ -1188,6 +1189,25 @@ func TestSearchChats(t *testing.T) { OwnedOnly: true, }, }, + { + Name: "ArchivedAny", + Query: "archived:any", + Expected: database.GetChatsParams{ + OwnedOnly: true, + }, + }, + { + Name: "ArchivedAnyUpperCase", + Query: "archived:ANY", + Expected: database.GetChatsParams{ + OwnedOnly: true, + }, + }, + { + Name: "ArchivedAnyRepeated", + Query: "archived:any archived:true", + ExpectedErrorContains: "archived", + }, { Name: "HasUnreadTrue", Query: "has_unread:true", diff --git a/codersdk/chats.go b/codersdk/chats.go index 504320f7d8a..cb6d6b77183 100644 --- a/codersdk/chats.go +++ b/codersdk/chats.go @@ -2198,6 +2198,10 @@ type ListChatsOptions struct { Source ChatListSource Labels map[string]string ProjectID *uuid.UUID + // AutomationID filters to chats the automation created or sent + // messages to. The server ignores it unless the chat-automations + // experiment is enabled for the caller. + AutomationID uuid.UUID Pagination } @@ -2236,6 +2240,13 @@ func (c *Client) ListChats(ctx context.Context, opts *ListChatsOptions) ([]Chat, r.URL.RawQuery = q.Encode() }) } + if opts.AutomationID != uuid.Nil { + reqOpts = append(reqOpts, func(r *http.Request) { + q := r.URL.Query() + q.Set("automation_id", opts.AutomationID.String()) + r.URL.RawQuery = q.Encode() + }) + } } res, err := c.Request(ctx, http.MethodGet, "/api/v2/chats", nil, reqOpts...) if err != nil { diff --git a/docs/ai-coder/agents/chat-search-syntax.md b/docs/ai-coder/agents/chat-search-syntax.md index 027c964123b..b4d781d436a 100644 --- a/docs/ai-coder/agents/chat-search-syntax.md +++ b/docs/ai-coder/agents/chat-search-syntax.md @@ -12,7 +12,7 @@ full-text search. | Key | Values | Description | |--------------|------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------| | `title` | substring | Case-insensitive substring match. Quote multi-word values. | -| `archived` | `true`, `false` | Filter by archived state. Default: `false`. | +| `archived` | `true`, `false`, `any` | Filter by archived state. `any` matches archived and active conversations. Default: `false` hides archived ones. | | `has_unread` | `true`, `false` | Conversations with unread assistant messages. | | `status` | `waiting`, `running`, `error`, `requires_action`, `interrupting` | Conversation state. Comma-separated or repeated values match any of them. | | `pr_status` | `draft`, `open`, `merged`, `closed`, `none` | Linked pull request state. Comma-separated for OR. `none` matches conversations with no linked pull request. | diff --git a/docs/reference/api/chats.md b/docs/reference/api/chats.md index 3ab15fa90b4..1b133a43eed 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. Requires the chat-projects experiment. | +| Name | In | Type | Required | Description | +|-----------------|-------|---------------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `q` | query | string | false | Search query. Supports `title:` (case-insensitive, quote multi-word values), `archived:bool` (`archived:any` matches archived and active chats), `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 | +| `automation_id` | query | string(uuid) | false | Filter to chats the automation created or sent messages to. Ignored unless the chat-automations experiment is enabled for the caller. | +| `project_id` | query | string(uuid) | false | Only chats in this project. Requires the chat-projects experiment. | ### Example responses diff --git a/site/src/api/api.ts b/site/src/api/api.ts index ada68734d41..8d8d2a1b98e 100644 --- a/site/src/api/api.ts +++ b/site/src/api/api.ts @@ -3287,6 +3287,7 @@ class ExperimentalApiMethods { limit?: number; offset?: number; q?: string; + automation_id?: string; }, signal?: AbortSignal, ): Promise => { @@ -3893,6 +3894,28 @@ class ExperimentalApiMethods { return response.data; }; + updateChatAutomation = async ( + organizationId: string, + automationId: string, + req: TypesGen.UpdateChatAutomationRequest, + ): Promise => { + const response = await this.axios.patch( + `/api/experimental/organizations/${encodeURIComponent(organizationId)}/chat-automations/${encodeURIComponent(automationId)}`, + req, + ); + return response.data; + }; + + runChatAutomation = async ( + organizationId: string, + automationId: string, + ): Promise => { + const response = await this.axios.post( + `/api/experimental/organizations/${encodeURIComponent(organizationId)}/chat-automations/${encodeURIComponent(automationId)}/runs`, + ); + return response.data; + }; + createChatModel = async ( organizationId: string, req: TypesGen.CreateChatModelRequest, diff --git a/site/src/api/queries/chatAutomations.ts b/site/src/api/queries/chatAutomations.ts index 07826f4b867..764d01fe764 100644 --- a/site/src/api/queries/chatAutomations.ts +++ b/site/src/api/queries/chatAutomations.ts @@ -1,13 +1,23 @@ -import type { QueryClient, UseQueryOptions } from "react-query"; +import { + infiniteQueryOptions, + type QueryClient, + type UseQueryOptions, +} from "react-query"; import { API } from "#/api/api"; -import type { ChatAutomation } from "#/api/typesGenerated"; +import { invalidateChatListQueries } from "#/api/queries/chats"; +import type { + Chat, + ChatAutomation, + ChatAutomationRunResponse, + UpdateChatAutomationRequest, +} from "#/api/typesGenerated"; const chatAutomationsFamilyKey = ["chat-automations"] as const; export const chatAutomationsKey = (organizationId: string) => [...chatAutomationsFamilyKey, organizationId] as const; -const chatAutomations = (organizationId: string) => ({ +export const chatAutomations = (organizationId: string) => ({ queryKey: chatAutomationsKey(organizationId), queryFn: (): Promise => API.experimental.getChatAutomations(organizationId), @@ -38,3 +48,67 @@ export const chatAutomationNameMap = ( /** Refetches automation names, for example after new automation input. */ export const invalidateChatAutomations = (queryClient: QueryClient) => queryClient.invalidateQueries({ queryKey: chatAutomationsFamilyKey }); + +export const updateChatAutomation = ( + queryClient: QueryClient, + organizationId: string, +) => ({ + mutationFn: ({ + automationId, + req, + }: { + automationId: string; + req: UpdateChatAutomationRequest; + }) => + API.experimental.updateChatAutomation(organizationId, automationId, req), + onSettled: () => + queryClient.invalidateQueries({ + queryKey: chatAutomationsKey(organizationId), + }), +}); + +const automationChatsKey = (automationId: string) => + ["chat-automation-chats", automationId] as const; + +const automationChatsPageSize = 25; + +export const automationChats = (automationId: string) => + infiniteQueryOptions({ + queryKey: automationChatsKey(automationId), + initialPageParam: 0, + getNextPageParam: (lastPage: Chat[], pages: Chat[][]) => + lastPage.length < automationChatsPageSize + ? undefined + : pages.length * automationChatsPageSize, + queryFn: ({ pageParam, signal }) => + API.experimental.getChats( + { + automation_id: automationId, + // The history includes chats archived after the automation + // created or wrote to them. + q: "archived:any", + limit: automationChatsPageSize, + offset: pageParam, + }, + signal, + ), + }); + +export const runChatAutomation = ( + queryClient: QueryClient, + organizationId: string, +) => ({ + mutationFn: (automationId: string): Promise => + API.experimental.runChatAutomation(organizationId, automationId), + onSuccess: async (_: ChatAutomationRunResponse, automationId: string) => { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: chatAutomationsKey(organizationId), + }), + queryClient.invalidateQueries({ + queryKey: automationChatsKey(automationId), + }), + invalidateChatListQueries(queryClient), + ]); + }, +}); diff --git a/site/src/api/typesGenerated.ts b/site/src/api/typesGenerated.ts index 760abf81c16..3e2d8423849 100644 --- a/site/src/api/typesGenerated.ts +++ b/site/src/api/typesGenerated.ts @@ -6536,6 +6536,12 @@ export interface ListChatsOptions extends Pagination { readonly Source: ChatListSource; readonly Labels: Record; readonly ProjectID: string | null; + /** + * AutomationID filters to chats the automation created or sent + * messages to. The server ignores it unless the chat-automations + * experiment is enabled for the caller. + */ + readonly AutomationID: string; } // From codersdk/inboxnotification.go diff --git a/site/src/pages/AgentsPage/AgentAutomationsPage.test.tsx b/site/src/pages/AgentsPage/AgentAutomationsPage.test.tsx new file mode 100644 index 00000000000..a2c9a600421 --- /dev/null +++ b/site/src/pages/AgentsPage/AgentAutomationsPage.test.tsx @@ -0,0 +1,331 @@ +import { screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { HttpResponse, http } from "msw"; +import { toast } from "sonner"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { ChatAutomation } from "#/api/typesGenerated"; +import { MockChat, MockChatAutomation } from "#/testHelpers/chatEntities"; +import { + MockDefaultOrganization, + MockOrganization2, +} from "#/testHelpers/entities"; +import { renderWithAuth } from "#/testHelpers/renderHelpers"; +import { server } from "#/testHelpers/server"; +import AgentAutomationsPage from "./AgentAutomationsPage"; +import { selectedOrganizationIdStorageKey } from "./components/AgentCreateForm"; + +// AgentPageHeader needs the layout's outlet context. +vi.mock("./components/AgentPageHeader", () => ({ + AgentPageHeader: () => null, +})); + +const mockAutomation: ChatAutomation = { + ...MockChatAutomation, + organization_id: MockDefaultOrganization.id, + target_chat_id: MockChat.id, +}; + +const automationsPath = (organizationId: string) => + `/api/experimental/organizations/${organizationId}/chat-automations`; + +const setup = ({ + experiments = ["chat-automations"], + automations = [mockAutomation], +}: { + experiments?: string[]; + automations?: ChatAutomation[]; +} = {}) => { + const requests: Request[] = []; + server.use( + http.get("/api/v2/experiments", () => HttpResponse.json(experiments)), + http.get("/api/v2/organizations", () => + HttpResponse.json([MockDefaultOrganization, MockOrganization2]), + ), + http.get("/api/v2/chats/:chatId", () => HttpResponse.json(MockChat)), + http.get("/api/v2/chats", ({ request }) => { + requests.push(request); + return HttpResponse.json([MockChat]); + }), + http.all( + "/api/experimental/organizations/:organizationId/chat-automations*", + ({ request }) => { + requests.push(request); + return undefined; + }, + ), + http.get(automationsPath(":organizationId"), () => + HttpResponse.json(automations), + ), + ); + renderWithAuth(); + return requests; +}; + +const requestPaths = (requests: readonly Request[]) => + requests.map((request) => { + const url = new URL(request.url); + return `${request.method} ${url.pathname}${url.search}`; + }); + +afterEach(() => { + localStorage.clear(); + vi.restoreAllMocks(); +}); + +describe("AgentAutomationsPage", () => { + it("lists the automations of the organization the Agents picker selected", async () => { + const user = userEvent.setup(); + localStorage.setItem( + selectedOrganizationIdStorageKey, + MockOrganization2.id, + ); + const requests = setup(); + + await waitFor(() => { + expect(requestPaths(requests)).toContain( + `GET ${automationsPath(MockOrganization2.id)}`, + ); + }); + expect(requestPaths(requests)).not.toContain( + `GET ${automationsPath(MockDefaultOrganization.id)}`, + ); + + await user.click( + await screen.findByRole("button", { + name: `Organization: ${MockOrganization2.display_name}`, + }), + ); + await user.click( + await screen.findByRole("option", { + name: MockDefaultOrganization.display_name, + }), + ); + await waitFor(() => { + expect(requestPaths(requests)).toContain( + `GET ${automationsPath(MockDefaultOrganization.id)}`, + ); + }); + expect(localStorage.getItem(selectedOrganizationIdStorageKey)).toBe( + MockDefaultOrganization.id, + ); + }); + + it("does not request automations when the experiment is off", async () => { + const requests = setup({ experiments: [] }); + + await screen.findByText("This page could not be found."); + expect(requests).toEqual([]); + }); + + it("disables an automation with the enabled switch", async () => { + const user = userEvent.setup(); + let body: unknown; + setup(); + server.use( + http.patch( + `${automationsPath(MockDefaultOrganization.id)}/${mockAutomation.id}`, + async ({ request }) => { + body = await request.json(); + return HttpResponse.json({ ...mockAutomation, enabled: false }); + }, + ), + ); + + await user.click( + await screen.findByRole("switch", { + name: `Enable ${mockAutomation.name}`, + }), + ); + + await waitFor(() => { + expect(body).toEqual({ enabled: false }); + }); + }); + + it("does not update a used single-use webhook from its switch", async () => { + const user = userEvent.setup(); + const mockUsedWebhook: ChatAutomation = { + ...mockAutomation, + kind: "webhook", + webhook_use: "single", + webhook_consumed_at: "2026-09-29T10:00:00Z", + enabled: true, + }; + const mockSecondAutomation: ChatAutomation = { + ...mockAutomation, + id: "second-automation", + name: "Second automation", + }; + setup({ automations: [mockUsedWebhook, mockSecondAutomation] }); + const updatedIds: string[] = []; + server.use( + http.patch<{ automationId: string }>( + `${automationsPath(MockDefaultOrganization.id)}/:automationId`, + ({ params }) => { + updatedIds.push(params.automationId); + return HttpResponse.json({ ...mockSecondAutomation, enabled: false }); + }, + ), + ); + + await user.click( + await screen.findByRole("switch", { + name: `Enable ${mockUsedWebhook.name}`, + }), + ); + // The second row's update is sent after the used webhook's click, so + // once it arrives any update from the first click would have too. + await user.click( + await screen.findByRole("switch", { + name: `Enable ${mockSecondAutomation.name}`, + }), + ); + await waitFor(() => { + expect(updatedIds).toContain(mockSecondAutomation.id); + }); + expect(updatedIds).toEqual([mockSecondAutomation.id]); + }); + + it("shows the error of a failed toggle after another row was toggled", async () => { + const user = userEvent.setup(); + const toastError = vi.spyOn(toast, "error"); + const secondAutomation: ChatAutomation = { + ...mockAutomation, + id: "second-automation", + name: "Second automation", + }; + setup({ automations: [mockAutomation, secondAutomation] }); + let failFirstUpdate = () => {}; + const firstUpdateFailed = new Promise((resolve) => { + failFirstUpdate = resolve; + }); + server.use( + http.patch( + `${automationsPath(MockDefaultOrganization.id)}/${mockAutomation.id}`, + async () => { + await firstUpdateFailed; + return HttpResponse.json( + { message: "The first update failed." }, + { status: 400 }, + ); + }, + ), + http.patch( + `${automationsPath(MockDefaultOrganization.id)}/${secondAutomation.id}`, + () => HttpResponse.json({ ...secondAutomation, enabled: false }), + ), + ); + + await user.click( + await screen.findByRole("switch", { + name: `Enable ${mockAutomation.name}`, + }), + ); + await user.click( + await screen.findByRole("switch", { + name: `Enable ${secondAutomation.name}`, + }), + ); + failFirstUpdate(); + + await waitFor(() => { + expect(toastError).toHaveBeenCalledWith( + "The first update failed.", + expect.anything(), + ); + }); + }); + + it("sends the Run now request", async () => { + const user = userEvent.setup(); + const requests = setup(); + const runPath = `${automationsPath(MockDefaultOrganization.id)}/${mockAutomation.id}/runs`; + server.use( + http.post(runPath, ({ request }) => { + requests.push(request); + return HttpResponse.json( + { message: "The target chat is busy." }, + { status: 409 }, + ); + }), + ); + + await user.click( + await screen.findByRole("button", { + name: `Run now ${mockAutomation.name}`, + }), + ); + + await waitFor(() => { + expect(requestPaths(requests)).toContain(`POST ${runPath}`); + }); + }); + + it("requests an automation's archived and active chats", async () => { + const user = userEvent.setup(); + const requests = setup(); + + await user.click( + await screen.findByRole("button", { + name: `View chats ${mockAutomation.name}`, + }), + ); + + await waitFor(() => { + expect(requestPaths(requests)).toContain( + `GET /api/v2/chats?automation_id=${mockAutomation.id}&q=archived%3Aany&limit=25&offset=0`, + ); + }); + }); + + it("returns focus to View chats when the chats dialog closes", async () => { + const user = userEvent.setup(); + setup(); + + const viewChats = await screen.findByRole("button", { + name: `View chats ${mockAutomation.name}`, + }); + viewChats.focus(); + await user.keyboard("{Enter}"); + await screen.findByRole("dialog", { + name: `Chats for ${mockAutomation.name}`, + }); + await user.keyboard("{Escape}"); + + await waitFor(() => { + expect(viewChats).toHaveFocus(); + }); + }); + + it("loads more of an automation's chats", async () => { + const user = userEvent.setup(); + const requests = setup(); + const mockChatPage = Array.from({ length: 25 }, (_, index) => ({ + ...MockChat, + id: `chat-${index}`, + })); + server.use( + http.get("/api/v2/chats", ({ request }) => { + requests.push(request); + return HttpResponse.json( + new URL(request.url).searchParams.get("offset") === "0" + ? mockChatPage + : [MockChat], + ); + }), + ); + + await user.click( + await screen.findByRole("button", { + name: `View chats ${mockAutomation.name}`, + }), + ); + await user.click(await screen.findByRole("button", { name: "Load more" })); + + await waitFor(() => { + expect(requestPaths(requests)).toContain( + `GET /api/v2/chats?automation_id=${mockAutomation.id}&q=archived%3Aany&limit=25&offset=25`, + ); + }); + }); +}); diff --git a/site/src/pages/AgentsPage/AgentAutomationsPage.tsx b/site/src/pages/AgentsPage/AgentAutomationsPage.tsx new file mode 100644 index 00000000000..e02c2407281 --- /dev/null +++ b/site/src/pages/AgentsPage/AgentAutomationsPage.tsx @@ -0,0 +1,149 @@ +import { useState } from "react"; +import { + useInfiniteQuery, + useMutation, + useQuery, + useQueryClient, +} from "react-query"; +import { toast } from "sonner"; +import { getErrorDetail, getErrorMessage } from "#/api/errors"; +import { + automationChats, + chatAutomations, + runChatAutomation, + updateChatAutomation, +} from "#/api/queries/chatAutomations"; +import type { ChatAutomation, Organization } from "#/api/typesGenerated"; +import { useAuthenticated } from "#/hooks/useAuthenticated"; +import { useDashboard } from "#/modules/dashboard/useDashboard"; +import NotFoundPage from "#/pages/NotFoundPage/NotFoundPage"; +import { + AgentAutomationsPageView, + type AutomationRunError, +} from "./AgentAutomationsPageView"; +import { selectedOrganizationIdStorageKey } from "./components/AgentCreateForm"; +import { AgentPageHeader } from "./components/AgentPageHeader"; +import { useAutomationsEnabled } from "./components/Automations/automationsFlag"; +import { CompactOrgSelector } from "./components/ChatElements/CompactOrgSelector"; + +const AgentAutomationsPage: React.FC = () => { + return useAutomationsEnabled() ? : ; +}; + +const AutomationsList: React.FC = () => { + const { organizations, showOrganizations } = useDashboard(); + const queryClient = useQueryClient(); + const { user } = useAuthenticated(); + const [selectedOrgId, setSelectedOrgId] = useState(() => + localStorage.getItem(selectedOrganizationIdStorageKey), + ); + const selectedOrg = + organizations.find((org) => org.id === selectedOrgId) ?? + organizations.find((org) => org.is_default) ?? + organizations[0]; + const organizationId = selectedOrg?.id ?? ""; + + const [runError, setRunError] = useState(); + const [chatsAutomation, setChatsAutomation] = useState(); + + const automationsQuery = useQuery({ + ...chatAutomations(organizationId), + enabled: Boolean(organizationId), + // Keeps the server-computed next run current while the page is open. + refetchInterval: 60_000, + }); + const chatsQuery = useInfiniteQuery({ + ...automationChats(chatsAutomation?.id ?? ""), + enabled: Boolean(chatsAutomation), + }); + const updateMutation = useMutation( + updateChatAutomation(queryClient, organizationId), + ); + const runMutation = useMutation( + runChatAutomation(queryClient, organizationId), + ); + + const handleOrganizationChange = (organization: Organization) => { + setSelectedOrgId(organization.id); + localStorage.setItem(selectedOrganizationIdStorageKey, organization.id); + setRunError(undefined); + }; + + const handleToggleEnabled = ( + automation: ChatAutomation, + enabled: boolean, + ) => { + // mutate's per-call callbacks run only for the latest call, so a later + // toggle on another row would swallow this row's error toast. + updateMutation + .mutateAsync({ automationId: automation.id, req: { enabled } }) + .catch((error) => { + toast.error( + getErrorMessage(error, `Could not update ${automation.name}.`), + { description: getErrorDetail(error) }, + ); + }); + }; + + const handleRunNow = (automation: ChatAutomation) => { + setRunError(undefined); + runMutation.mutate(automation.id, { + onSuccess: () => { + toast.success(`${automation.name} accepted the run.`); + }, + onError: (error) => { + setRunError({ automation, error }); + }, + }); + }; + + return ( + + } + currentUserId={user.id} + organizationName={selectedOrg?.display_name || selectedOrg?.name} + organizationSelector={ + showOrganizations && ( + + ) + } + automations={automationsQuery.data} + isLoading={automationsQuery.isLoading} + error={automationsQuery.error} + updatingAutomationId={ + updateMutation.isPending + ? updateMutation.variables?.automationId + : undefined + } + runningAutomationId={ + runMutation.isPending ? runMutation.variables : undefined + } + runError={runError} + onDismissRunError={() => setRunError(undefined)} + onToggleEnabled={handleToggleEnabled} + onRunNow={handleRunNow} + onViewChats={setChatsAutomation} + chatsDialog={ + chatsAutomation && { + automation: chatsAutomation, + chats: chatsQuery.data?.pages.flat(), + isLoading: chatsQuery.isLoading, + error: chatsQuery.error, + hasNextPage: chatsQuery.hasNextPage, + isFetchingNextPage: chatsQuery.isFetchingNextPage, + onLoadMore: () => void chatsQuery.fetchNextPage(), + onClose: () => setChatsAutomation(undefined), + } + } + /> + ); +}; + +export default AgentAutomationsPage; diff --git a/site/src/pages/AgentsPage/AgentAutomationsPageView.stories.tsx b/site/src/pages/AgentsPage/AgentAutomationsPageView.stories.tsx new file mode 100644 index 00000000000..649a46633f5 --- /dev/null +++ b/site/src/pages/AgentsPage/AgentAutomationsPageView.stories.tsx @@ -0,0 +1,175 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { fn } from "storybook/test"; +import { chatEntityKey } from "#/api/queries/chats"; +import type { Chat, ChatAutomation } from "#/api/typesGenerated"; +import { MockChat, MockChatAutomation } from "#/testHelpers/chatEntities"; +import { MockUserOwner, mockApiError } from "#/testHelpers/entities"; +import { AgentAutomationsPageView } from "./AgentAutomationsPageView"; + +const mockTargetChat: Chat = { + ...MockChat, + id: "chat-target", + title: "Nightly build triage", +}; +const mockCreatingChat: Chat = { + ...MockChat, + id: "chat-creator", + title: "Set up CI monitoring", +}; +const mockArchivedChat: Chat = { + ...MockChat, + id: "chat-archived", + title: "Old release thread", + archived: true, +}; + +const mockScheduleAutomation: ChatAutomation = { + ...MockChatAutomation, + id: "automation-schedule", + name: "Nightly build check", + target_chat_id: mockTargetChat.id, + schedule_cron: "0 9 * * 1-5", + schedule_time_zone: "Europe/Berlin", + next_run_times: ["2026-10-01T07:00:00Z"], +}; +const mockHeartbeatAutomation: ChatAutomation = { + ...MockChatAutomation, + id: "automation-heartbeat", + name: "CI heartbeat", + created_by_chat_id: mockCreatingChat.id, + target_chat_id: mockCreatingChat.id, + schedule_cron: "*/5 * * * *", + schedule_time_zone: "UTC", + next_run_times: ["2026-09-30T12:05:00Z"], +}; +const mockWebhookAutomation: ChatAutomation = { + ...MockChatAutomation, + id: "automation-webhook", + name: "Deploy finished", + kind: "webhook", + enabled: false, + target_mode: "new_chat", + target_chat_id: undefined, + when_busy: undefined, + webhook_use: "single", + webhook_consumed_at: "2026-09-29T10:00:00Z", + schedule_cron: undefined, + schedule_time_zone: undefined, +}; + +const meta: Meta = { + title: "pages/AgentsPage/AgentAutomationsPageView", + component: AgentAutomationsPageView, + args: { + currentUserId: MockUserOwner.id, + organizationName: "Coder", + automations: [ + mockScheduleAutomation, + mockHeartbeatAutomation, + mockWebhookAutomation, + ], + isLoading: false, + error: undefined, + onDismissRunError: fn(), + onToggleEnabled: fn(), + onRunNow: fn(), + onViewChats: fn(), + }, + parameters: { + queries: [ + { key: chatEntityKey(mockTargetChat.id), data: mockTargetChat }, + { key: chatEntityKey(mockCreatingChat.id), data: mockCreatingChat }, + { key: chatEntityKey(mockArchivedChat.id), data: mockArchivedChat }, + ], + }, +}; + +export default meta; +type Story = StoryObj; + +export const WithAutomations: Story = {}; + +export const OtherOwner: Story = { + args: { currentUserId: "another-user-id" }, +}; + +export const Empty: Story = { + args: { automations: [] }, +}; + +export const MissingTarget: Story = { + args: { + automations: [ + { + ...mockScheduleAutomation, + id: "automation-no-target", + name: "Deleted target", + target_chat_id: undefined, + }, + { + ...mockScheduleAutomation, + id: "automation-archived-target", + name: "Archived target", + target_chat_id: mockArchivedChat.id, + }, + ], + }, +}; + +export const RunNowError: Story = { + args: { + runError: { + automation: mockScheduleAutomation, + error: mockApiError({ + message: "The target chat is busy and the automation skips busy runs.", + }), + }, + }, +}; + +export const ChatsDialog: Story = { + args: { + chatsDialog: { + automation: mockScheduleAutomation, + chats: [mockTargetChat, mockCreatingChat], + isLoading: false, + error: undefined, + hasNextPage: true, + isFetchingNextPage: false, + onLoadMore: fn(), + onClose: fn(), + }, + }, +}; + +export const ChatsDialogLoadMoreError: Story = { + args: { + chatsDialog: { + automation: mockScheduleAutomation, + chats: [mockTargetChat, mockCreatingChat], + isLoading: false, + error: mockApiError({ message: "Failed to load more chats." }), + hasNextPage: true, + isFetchingNextPage: false, + onLoadMore: fn(), + onClose: fn(), + }, + }, +}; + +export const Loading: Story = { + args: { automations: undefined, isLoading: true }, +}; + +export const RefetchError: Story = { + args: { + error: mockApiError({ message: "Failed to refresh chat automations." }), + }, +}; + +export const ListError: Story = { + args: { + automations: undefined, + error: mockApiError({ message: "Failed to list chat automations." }), + }, +}; diff --git a/site/src/pages/AgentsPage/AgentAutomationsPageView.tsx b/site/src/pages/AgentsPage/AgentAutomationsPageView.tsx new file mode 100644 index 00000000000..837fc74bbf3 --- /dev/null +++ b/site/src/pages/AgentsPage/AgentAutomationsPageView.tsx @@ -0,0 +1,247 @@ +import { useState } from "react"; +import { getErrorDetail, getErrorMessage } from "#/api/errors"; +import type { Chat, ChatAutomation } from "#/api/typesGenerated"; +import { Alert, AlertDescription, AlertTitle } from "#/components/Alert/Alert"; +import { ErrorAlert } from "#/components/Alert/ErrorAlert"; +import { Button } from "#/components/Button/Button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "#/components/Dialog/Dialog"; +import { Loader } from "#/components/Loader/Loader"; +import { ScrollArea } from "#/components/ScrollArea/ScrollArea"; +import { Spinner } from "#/components/Spinner/Spinner"; +import { + Table, + TableBody, + TableHead, + TableHeader, + TableRow, +} from "#/components/Table/Table"; +import { TableEmpty } from "#/components/TableEmpty/TableEmpty"; +import { TableLoader } from "#/components/TableLoader/TableLoader"; +import { + AutomationRow, + ChatTitleLink, +} from "./components/Automations/AutomationRow"; +import { SectionHeader } from "./components/SectionHeader"; + +export type AutomationRunError = { + automation: ChatAutomation; + error: unknown; +}; + +type AutomationChatsDialogState = { + automation: ChatAutomation; + chats: readonly Chat[] | undefined; + isLoading: boolean; + error: unknown; + hasNextPage: boolean; + isFetchingNextPage: boolean; + onLoadMore: () => void; + onClose: () => void; +}; + +type AgentAutomationsPageViewProps = { + header?: React.ReactNode; + currentUserId: string; + organizationName: string | undefined; + organizationSelector?: React.ReactNode; + automations: readonly ChatAutomation[] | undefined; + isLoading: boolean; + error: unknown; + updatingAutomationId?: string; + runningAutomationId?: string; + runError?: AutomationRunError; + onDismissRunError: () => void; + onToggleEnabled: (automation: ChatAutomation, enabled: boolean) => void; + onRunNow: (automation: ChatAutomation) => void; + onViewChats: (automation: ChatAutomation) => void; + chatsDialog?: AutomationChatsDialogState; +}; + +type AutomationChatsDialogProps = { + state: AutomationChatsDialogState; +}; + +const AutomationChatsDialog: React.FC = ({ + state, +}) => { + // The dialog opens from a row button rather than a DialogTrigger, so Radix + // has no trigger to return focus to on close. It mounts right after the + // View chats button is activated, so the focused element is the opener. + const [opener] = useState(() => document.activeElement); + let body: React.ReactNode; + if (state.isLoading) { + body = ; + } else if (state.error && !state.chats) { + body = ; + } else if (!state.chats || state.chats.length === 0) { + body = ( +

+ No chats that you can open were created by or received messages from + this automation. +

+ ); + } else { + body = ( +
    + {state.chats.map((chat) => ( +
  • + +
  • + ))} + {Boolean(state.error) && ( +
  • + +
  • + )} + {state.hasNextPage && ( +
  • + +
  • + )} +
+ ); + } + return ( + { + if (!open) { + state.onClose(); + } + }} + > + { + if (opener instanceof HTMLElement && opener.isConnected) { + event.preventDefault(); + opener.focus(); + } + }} + > + + Chats for {state.automation.name} + + Chats this automation created or sent messages to. + + + {body} + + + ); +}; + +export const AgentAutomationsPageView: React.FC< + AgentAutomationsPageViewProps +> = ({ + header, + currentUserId, + organizationName, + organizationSelector, + automations, + isLoading, + error, + updatingAutomationId, + runningAutomationId, + runError, + onDismissRunError, + onToggleEnabled, + onRunNow, + onViewChats, + chatsDialog, +}) => { + let rows: React.ReactNode; + if (isLoading) { + rows = ; + } else if (!automations || automations.length === 0) { + rows = ( + + ); + } else { + rows = automations.map((automation) => ( + + )); + } + + return ( + + {header} +
+
+ + {runError && ( + + Could not run {runError.automation.name} + + {getErrorMessage(runError.error, "The run did not start.")} + {getErrorDetail(runError.error) && ( + + {getErrorDetail(runError.error)} + + )} + + + )} + {Boolean(error) && } + {(!error || automations) && ( + + + + Name + Trigger + Target + Next run + Enabled + + Actions + + + + {rows} +
+ )} +
+
+ {chatsDialog && } +
+ ); +}; diff --git a/site/src/pages/AgentsPage/AgentsPageLayout.tsx b/site/src/pages/AgentsPage/AgentsPageLayout.tsx index 54972e005ae..09a8a1fd784 100644 --- a/site/src/pages/AgentsPage/AgentsPageLayout.tsx +++ b/site/src/pages/AgentsPage/AgentsPageLayout.tsx @@ -66,6 +66,7 @@ import { canAccessCoderAgentsSettings } from "#/modules/permissions"; import { pageTitle } from "#/utils/page"; import { createReconnectingWebSocket } from "#/utils/reconnectingWebSocket"; import { emptyInputStorageKey } from "./components/AgentCreateForm"; +import { AUTOMATIONS_PATH } from "./components/Automations/automationsFlag"; import { type ChatDetailError, chatDetailErrorsEqual, @@ -728,6 +729,10 @@ const AgentsPageLayout: React.FC = () => { const isSettingsDetail = isSettingsPanel && Boolean(sidebarView.section); const isBoardRoute = useChatBoardEnabled() && location.pathname.startsWith(CHAT_BOARD_PATH); + // On mobile the automations page replaces the sidebar, like a settings + // detail page. + const isFullPageRoute = + isSettingsDetail || location.pathname.startsWith(AUTOMATIONS_PATH); // The sidebar expects plain string error messages, but the outlet // context carries structured ChatDetailError objects. @@ -775,7 +780,7 @@ const AgentsPageLayout: React.FC = () => { "sm:h-full sm:min-h-0 sm:border-b-0", agentId ? "hidden sm:block shrink-0 h-[42dvh] min-h-[240px] border-b border-border-default" - : isSettingsDetail + : isFullPageRoute ? "hidden sm:block shrink-0" : "order-2 sm:order-0 flex-1 min-h-0 border-b border-border-default sm:flex-none sm:border-t-0 sm:border-b-0", isSidebarCollapsed && "sm:hidden", @@ -830,7 +835,7 @@ const AgentsPageLayout: React.FC = () => { "min-h-0 min-w-0 flex-1 flex-col bg-surface-primary", isSettingsIndex ? "hidden sm:flex" : "flex", !agentId && - !isSettingsDetail && + !isFullPageRoute && sidebarView.panel === "chats" && "contents sm:flex sm:flex-1 sm:flex-col", )} diff --git a/site/src/pages/AgentsPage/components/Automations/AutomationRow.tsx b/site/src/pages/AgentsPage/components/Automations/AutomationRow.tsx new file mode 100644 index 00000000000..a1a6ec39f17 --- /dev/null +++ b/site/src/pages/AgentsPage/components/Automations/AutomationRow.tsx @@ -0,0 +1,269 @@ +import { memo } from "react"; +import { useQuery } from "react-query"; +import { Link as RouterLink } from "react-router"; +import { getErrorMessage, getErrorStatus } from "#/api/errors"; +import { chat } from "#/api/queries/chats"; +import type { Chat, ChatAutomation } from "#/api/typesGenerated"; +import { Badge } from "#/components/Badge/Badge"; +import { Button } from "#/components/Button/Button"; +import { Link, type LinkProps } from "#/components/Link/Link"; +import { Skeleton } from "#/components/Skeleton/Skeleton"; +import { Spinner } from "#/components/Spinner/Spinner"; +import { Switch } from "#/components/Switch/Switch"; +import { TableCell, TableRow } from "#/components/Table/Table"; +import { formatDate } from "#/utils/time"; + +type AutomationRowProps = { + automation: ChatAutomation; + isOwner: boolean; + isUpdating: boolean; + isRunning: boolean; + /** One run request at a time, so a pending run disables every row. */ + isAnyRunPending: boolean; + onToggleEnabled: (automation: ChatAutomation, enabled: boolean) => void; + onRunNow: (automation: ChatAutomation) => void; + onViewChats: (automation: ChatAutomation) => void; +}; + +const formatNextRun = (automation: ChatAutomation): string => { + const next = automation.next_run_times[0]; + if (automation.kind !== "schedule" || !next) { + return "Not scheduled"; + } + const date = new Date(next); + if (!Number.isFinite(date.getTime())) { + return "Not scheduled"; + } + return formatDate(date, { + locale: "en-US", + timeZone: automation.schedule_time_zone || "UTC", + timeZoneName: "short", + month: "short", + day: "numeric", + year: undefined, + hour: "numeric", + minute: "2-digit", + second: undefined, + }); +}; + +type ChatTitleLinkProps = { + chatId: string; + title: string | undefined; + size?: LinkProps["size"]; +}; + +/** Links to a chat by its title, falling back to "Untitled". */ +export const ChatTitleLink: React.FC = ({ + chatId, + title, + size = "lg", +}) => { + return ( + + {title || "Untitled"} + + ); +}; + +type ChatTitleProps = { + chat: Chat | undefined; + chatId: string; + isLoading: boolean; + error: unknown; + size?: LinkProps["size"]; +}; + +const ChatTitle: React.FC = ({ + chat, + chatId, + isLoading, + error, + size, +}) => { + if (isLoading) { + return ; + } + if (error) { + return ( + + {getErrorMessage(error, "Chat unavailable")} + + ); + } + return ; +}; + +type CreatingChatProps = { + chatId: string; +}; + +const CreatingChat: React.FC = ({ chatId }) => { + const chatQuery = useQuery(chat(chatId)); + return ( + + Created by agent in + {getErrorStatus(chatQuery.error) === 404 ? ( + " a deleted chat" + ) : ( + + )} + + ); +}; + +type TriggerCellProps = { + automation: ChatAutomation; +}; + +const TriggerCell: React.FC = ({ automation }) => { + if (automation.kind === "schedule") { + return ( +
+ + {automation.schedule_cron} + + + {automation.schedule_time_zone} + +
+ ); + } + return ( +
+ + {automation.webhook_use === "single" + ? "Webhook, single-use" + : "Webhook, multi-use"} + + {automation.webhook_consumed_at && ( + Used + )} +
+ ); +}; + +// memo() is allowed for list items under the React Compiler; it keeps +// other rows from re-rendering while one row's mutation is pending. +export const AutomationRow = memo( + ({ + automation, + isOwner, + isUpdating, + isRunning, + isAnyRunPending, + onToggleEnabled, + onRunNow, + onViewChats, + }) => { + const isConsumed = Boolean(automation.webhook_consumed_at); + const targetChatId = + automation.target_mode === "existing_chat" + ? automation.target_chat_id + : undefined; + // Chat titles are looked up only for the viewer's own automations: + // the per-owner cap bounds the requests, and other owners' chats are + // usually unreadable, which would look like a missing target. + const targetQuery = useQuery({ + ...chat(targetChatId ?? ""), + enabled: isOwner && Boolean(targetChatId), + }); + // A deleted target clears target_chat_id; an archived one refuses runs. + const isTargetMissing = + automation.target_mode === "existing_chat" && + (!targetChatId || + getErrorStatus(targetQuery.error) === 404 || + Boolean(targetQuery.data?.archived)); + + return ( + + +
+ + {automation.name} + + {automation.created_by_chat_id && + (isOwner ? ( + + ) : ( + + Created by agent + + ))} +
+
+ + + + + {automation.target_mode === "new_chat" ? ( + New chat each run + ) : isTargetMissing || !targetChatId ? ( + + Missing target + + ) : !isOwner ? ( + Existing chat + ) : ( + + )} + + + {formatNextRun(automation)} + + + onToggleEnabled(automation, enabled)} + /> + + +
+ {automation.kind === "schedule" && isOwner && ( + + )} + {isOwner && ( + + )} +
+
+
+ ); + }, +); diff --git a/site/src/pages/AgentsPage/components/Automations/AutomationsNavItem.tsx b/site/src/pages/AgentsPage/components/Automations/AutomationsNavItem.tsx new file mode 100644 index 00000000000..6720685abda --- /dev/null +++ b/site/src/pages/AgentsPage/components/Automations/AutomationsNavItem.tsx @@ -0,0 +1,41 @@ +import { ZapIcon } from "lucide-react"; +import { Link, useLocation } from "react-router"; +import { Button } from "#/components/Button/Button"; +import { SettingsNavItem } from "../ChatsSidebar/settings/SettingsNavItem"; +import { AUTOMATIONS_PATH, useAutomationsEnabled } from "./automationsFlag"; + +type AutomationsNavItemProps = { + /** Normalized query string the sidebar appends to its own links. */ + readonly locationSearch: string; +}; + +export const AutomationsNavItem: React.FC = ({ + locationSearch, +}) => { + const location = useLocation(); + return useAutomationsEnabled() ? ( + + ) : null; +}; + +/** The mobile header's link to the page; the sidebar nav is hidden there. */ +export const AutomationsMobileLink: React.FC = () => { + return useAutomationsEnabled() ? ( + + ) : null; +}; diff --git a/site/src/pages/AgentsPage/components/Automations/automationsFlag.ts b/site/src/pages/AgentsPage/components/Automations/automationsFlag.ts new file mode 100644 index 00000000000..7391da46c13 --- /dev/null +++ b/site/src/pages/AgentsPage/components/Automations/automationsFlag.ts @@ -0,0 +1,11 @@ +/** + * The automations page route and the chat-automations experiment flag that + * gates the page and its entry points. + */ +import { useDashboard } from "#/modules/dashboard/useDashboard"; + +export const AUTOMATIONS_PATH = "/agents/automations"; + +/** Whether the chat-automations experiment is on for the viewer. */ +export const useAutomationsEnabled = (): boolean => + useDashboard().experiments.includes("chat-automations"); diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/ChatsSidebar.stories.tsx b/site/src/pages/AgentsPage/components/ChatsSidebar/ChatsSidebar.stories.tsx index 37ea57948c4..771574c841a 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/ChatsSidebar.stories.tsx +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/ChatsSidebar.stories.tsx @@ -2511,3 +2511,37 @@ export const PreservesArchivedFilterOnSettingsNavigation: Story = { }); }, }; + +export const MobileWithAutomations: Story = { + args: { + chats: sectionHeaderChats, + }, + parameters: { + experiments: ["chat-automations"], + viewport: { defaultViewport: "mobile1" }, + reactRouter: reactRouterParameters({ + location: { path: "/agents" }, + routing: agentsRouting, + }), + }, + decorators: [ + (Story) => ( +
+ +
+ ), + ], +}; + +export const AutomationsActive: Story = { + args: { + chats: sectionHeaderChats, + }, + parameters: { + experiments: ["chat-automations"], + reactRouter: reactRouterParameters({ + location: { path: "/agents/automations" }, + routing: agentsRouting, + }), + }, +}; diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/ChatsSidebar.tsx b/site/src/pages/AgentsPage/components/ChatsSidebar/ChatsSidebar.tsx index b187d80f411..46c86cc4168 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/ChatsSidebar.tsx +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/ChatsSidebar.tsx @@ -4,6 +4,7 @@ import { useLocation, useParams } from "react-router"; import { userChatProviderConfigs } from "#/api/queries/chats"; import type { Chat, ChatModel } from "#/api/typesGenerated"; import type { AgentSidebarFilters } from "../../utils/agentSidebarFilters"; +import { AUTOMATIONS_PATH } from "../Automations/automationsFlag"; import { ChatsPanel } from "./chats/ChatsPanel"; import { ChatSearchDialog } from "./dialogs/ChatSearchDialog"; import { RenameChatDialog } from "./dialogs/RenameChatDialog"; @@ -161,7 +162,11 @@ export const ChatsSidebar: React.FC = (props) => { onCollapse={onCollapse} activeChatId={activeChatId} isSettingsPanel={isSettingsPanel} - isChatsActive={!activeChatId && sidebarView.panel === "chats"} + isChatsActive={ + !activeChatId && + sidebarView.panel === "chats" && + !location.pathname.startsWith(AUTOMATIONS_PATH) + } location={location} currentUserId={currentUserId} /> diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/chats/ChatsPanel.tsx b/site/src/pages/AgentsPage/components/ChatsSidebar/chats/ChatsPanel.tsx index 425784dd73f..e329914d64c 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/chats/ChatsPanel.tsx +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/chats/ChatsPanel.tsx @@ -50,6 +50,10 @@ import { DEFAULT_AGENT_SIDEBAR_FILTERS, } from "../../../utils/agentSidebarFilters"; import { getTimeGroup, TIME_GROUPS } from "../../../utils/timeGroups"; +import { + AutomationsMobileLink, + AutomationsNavItem, +} from "../../Automations/AutomationsNavItem"; import { canManageChat } from "../../ChatActionsMenuItems"; import { FilterPopover } from "../filters/FilterPopover"; import { normalizeLocationSearch } from "../locationSearch"; @@ -468,6 +472,7 @@ export const ChatsPanel: React.FC = ({ /> )} +
@@ -487,6 +492,7 @@ export const ChatsPanel: React.FC = ({ )} + import("./pages/AgentsPage/AgentChatPage")); const ChatBoardPage = lazy( () => import("./pages/AgentsPage/exp/chatBoard/ChatBoardRoute"), ); +const AgentAutomationsPage = lazy( + () => import("./pages/AgentsPage/AgentAutomationsPage"), +); const AgentEmbedPage = lazy(() => import("./pages/AgentsPage/AgentEmbedPage")); const DesktopPopoutPage = lazy( () => import("./pages/AgentsPage/DesktopPopoutPage"), @@ -901,6 +904,14 @@ export const router = createBrowserRouter( } /> + }> + + + } + />