diff --git a/coderd/apidoc/docs.go b/coderd/apidoc/docs.go index 74ac86c35a1..f7fd729222e 100644 --- a/coderd/apidoc/docs.go +++ b/coderd/apidoc/docs.go @@ -1537,7 +1537,7 @@ const docTemplate = `{ "parameters": [ { "type": "string", - "description": "Search query. Supports ` + "`" + `title:\u003csubstring\u003e` + "`" + ` (case-insensitive, quote multi-word values), ` + "`" + `archived:bool` + "`" + `, ` + "`" + `has_unread:bool` + "`" + `, ` + "`" + `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` + "`" + `, ` + "`" + `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" }, diff --git a/coderd/apidoc/swagger.json b/coderd/apidoc/swagger.json index cfc1fa15630..4eab58d18d8 100644 --- a/coderd/apidoc/swagger.json +++ b/coderd/apidoc/swagger.json @@ -1352,7 +1352,7 @@ "parameters": [ { "type": "string", - "description": "Search query. Supports `title:\u003csubstring\u003e` (case-insensitive, quote multi-word values), `archived:bool`, `has_unread:bool`, `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`, `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" }, diff --git a/coderd/database/modelqueries.go b/coderd/database/modelqueries.go index 93b022cca1f..e67f57a976e 100644 --- a/coderd/database/modelqueries.go +++ b/coderd/database/modelqueries.go @@ -850,6 +850,7 @@ func (q *sqlQuerier) GetAuthorizedChats(ctx context.Context, arg GetChatsParams, arg.DiffURL, arg.TitleQuery, arg.HasUnread, + pq.Array(arg.ChatStatuses), pq.Array(arg.PullRequestStatuses), arg.PrNumber, arg.RepoQuery, diff --git a/coderd/database/querier_test.go b/coderd/database/querier_test.go index aa6a34e5794..ea1b48d8e08 100644 --- a/coderd/database/querier_test.go +++ b/coderd/database/querier_test.go @@ -17576,6 +17576,27 @@ func TestGetChatsFilter(t *testing.T) { unreadNoPR := createRoot("unread no pr") makeUnread(unreadNoPR.ID) + setStatus := func(chat database.Chat, status database.ChatStatus) { + t.Helper() + _, err := store.UpdateChatStatus(ctx, database.UpdateChatStatusParams{ + ID: chat.ID, + Status: status, + }) + require.NoError(t, err) + } + + // Inbox status is computed from lifecycle status, then unread. + // A running chat with unread messages stays working. + workingUnread := createRoot("working unread chat") + makeUnread(workingUnread.ID) + setStatus(workingUnread, database.ChatStatusRunning) + needsAttention := createRoot("needs attention chat") + setStatus(needsAttention, database.ChatStatusRequiresAction) + failedChat := createRoot("failed chat") + setStatus(failedChat, database.ChatStatusError) + interruptingChat := createRoot("interrupting chat") + setStatus(interruptingChat, database.ChatStatusInterrupting) + // Read chat (message exists but marked read). readChat := createRoot("read chat") makeUnread(readChat.ID) @@ -17618,11 +17639,13 @@ func TestGetChatsFilter(t *testing.T) { draftPR.ID, openPR.ID, mergedPR.ID, closedPR.ID, unreadNoPR.ID, readChat.ID, childParent.ID, prNumberChat.ID, repoChat.ID, prTitleChat.ID, clearedPR.ID, + workingUnread.ID, needsAttention.ID, failedChat.ID, interruptingChat.ID, } noPRRootIDs := []uuid.UUID{ alphaProject.ID, betaProject.ID, gammaUnrelated.ID, percentComplete.ID, thousandOne.ID, underscoreConfig.ID, hyphenConfig.ID, unreadNoPR.ID, readChat.ID, childParent.ID, clearedPR.ID, + workingUnread.ID, needsAttention.ID, failedChat.ID, interruptingChat.ID, } noPROrOpenRootIDs := append(append([]uuid.UUID{}, noPRRootIDs...), openPR.ID, prNumberChat.ID, prTitleChat.ID) @@ -17656,9 +17679,18 @@ func TestGetChatsFilter(t *testing.T) { {"PRStatus/NoneAndOpen", database.GetChatsParams{PullRequestStatuses: []string{"none", "open"}}, noPROrOpenRootIDs}, // Unread filter. - {"Unread/MatchesUnread", database.GetChatsParams{HasUnread: sql.NullBool{Bool: true, Valid: true}}, []uuid.UUID{draftPR.ID, unreadNoPR.ID}}, + {"Unread/MatchesUnread", database.GetChatsParams{HasUnread: sql.NullBool{Bool: true, Valid: true}}, []uuid.UUID{draftPR.ID, unreadNoPR.ID, workingUnread.ID}}, // HasUnread=false returns chats without unread messages. - {"Unread/ExcludesRead", database.GetChatsParams{HasUnread: sql.NullBool{Bool: false, Valid: true}}, []uuid.UUID{alphaProject.ID, betaProject.ID, gammaUnrelated.ID, percentComplete.ID, thousandOne.ID, underscoreConfig.ID, hyphenConfig.ID, openPR.ID, mergedPR.ID, closedPR.ID, readChat.ID, childParent.ID, prNumberChat.ID, repoChat.ID, prTitleChat.ID, clearedPR.ID}}, + {"Unread/ExcludesRead", database.GetChatsParams{HasUnread: sql.NullBool{Bool: false, Valid: true}}, []uuid.UUID{alphaProject.ID, betaProject.ID, gammaUnrelated.ID, percentComplete.ID, thousandOne.ID, underscoreConfig.ID, hyphenConfig.ID, openPR.ID, mergedPR.ID, closedPR.ID, readChat.ID, childParent.ID, prNumberChat.ID, repoChat.ID, prTitleChat.ID, clearedPR.ID, needsAttention.ID, failedChat.ID, interruptingChat.ID}}, + + // chat_status enum, the same value the sidebar row icon uses. + {"Status/Running", database.GetChatsParams{ChatStatuses: []string{"running"}}, []uuid.UUID{workingUnread.ID}}, + {"Status/Interrupting", database.GetChatsParams{ChatStatuses: []string{"interrupting"}}, []uuid.UUID{interruptingChat.ID}}, + {"Status/RequiresAction", database.GetChatsParams{ChatStatuses: []string{"requires_action"}}, []uuid.UUID{needsAttention.ID}}, + {"Status/Error", database.GetChatsParams{ChatStatuses: []string{"error"}}, []uuid.UUID{failedChat.ID}}, + {"Status/Waiting", database.GetChatsParams{ChatStatuses: []string{"waiting"}}, []uuid.UUID{alphaProject.ID, betaProject.ID, gammaUnrelated.ID, percentComplete.ID, thousandOne.ID, underscoreConfig.ID, hyphenConfig.ID, openPR.ID, mergedPR.ID, closedPR.ID, draftPR.ID, unreadNoPR.ID, readChat.ID, childParent.ID, prNumberChat.ID, repoChat.ID, prTitleChat.ID, clearedPR.ID}}, + {"Status/RunningAndError", database.GetChatsParams{ChatStatuses: []string{"running", "error"}}, []uuid.UUID{workingUnread.ID, failedChat.ID}}, + {"Status/EmptyIsNoOp", database.GetChatsParams{ChatStatuses: nil}, allRootIDs}, // PR number filter. {"PRNumber/ExactMatch", database.GetChatsParams{PrNumber: 42}, []uuid.UUID{prNumberChat.ID}}, diff --git a/coderd/database/queries.sql.go b/coderd/database/queries.sql.go index 8e61a434b95..35d4e6fd363 100644 --- a/coderd/database/queries.sql.go +++ b/coderd/database/queries.sql.go @@ -10101,6 +10101,13 @@ WHERE ) = $11::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($12::text[], 1), 0) > 0 THEN + chats_expanded.status::text = ANY($12::text[]) + ELSE true + END -- Filter by pull request status. Unlike the diff_url filter above, -- this intentionally checks only the root chat's own diff status. -- Child chats share the same workspace and git branch as their @@ -10109,9 +10116,9 @@ WHERE -- "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($12::text[], 1), 0) > 0 THEN ( + WHEN COALESCE(array_length($13::text[], 1), 0) > 0 THEN ( ( - 'none' = ANY($12::text[]) + 'none' = ANY($13::text[]) AND NOT EXISTS ( SELECT 1 FROM chat_diff_statuses cds @@ -10129,56 +10136,56 @@ WHERE WHEN cds.pull_request_state = 'open' THEN 'open' ELSE cds.pull_request_state END - ) = ANY($12::text[]) + ) = ANY($13::text[]) ) ) ELSE true END -- Filter by PR number (exact match on chat's diff status). AND CASE - WHEN $13::int != 0 THEN EXISTS ( + WHEN $14::int != 0 THEN EXISTS ( SELECT 1 FROM chat_diff_statuses cds WHERE cds.chat_id = chats_expanded.id - AND cds.pr_number = $13 + AND cds.pr_number = $14 ) ELSE true END -- Filter by repository (substring match on remote origin or PR URL). AND CASE - WHEN $14::text != '' THEN EXISTS ( + WHEN $15::text != '' THEN EXISTS ( SELECT 1 FROM chat_diff_statuses cds WHERE cds.chat_id = chats_expanded.id AND ( - cds.git_remote_origin ILIKE '%' || $14 || '%' - OR cds.url ILIKE '%' || $14 || '%' + cds.git_remote_origin ILIKE '%' || $15 || '%' + OR cds.url ILIKE '%' || $15 || '%' ) ) ELSE true END -- Filter by pull request title (case-insensitive substring). AND CASE - WHEN $15::text != '' THEN EXISTS ( + WHEN $16::text != '' THEN EXISTS ( SELECT 1 FROM chat_diff_statuses cds WHERE cds.chat_id = chats_expanded.id - AND cds.pull_request_title ILIKE '%' || $15 || '%' + AND cds.pull_request_title ILIKE '%' || $16 || '%' ) ELSE true END -- websearch_to_tsquery accepts quoted phrases, OR, and -negation; -- the 'simple' config folds case and skips stemming. AND CASE - WHEN $16::text != '' THEN ( + WHEN $17::text != '' THEN ( -- Served by idx_chats_title_fts. - to_tsvector('simple', chats_expanded.title) @@ websearch_to_tsquery('simple', $16) + to_tsvector('simple', chats_expanded.title) @@ websearch_to_tsquery('simple', $17) -- 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', $16) + AND to_tsvector('simple', cds.pull_request_title) @@ websearch_to_tsquery('simple', $17) ) -- The WHERE clause must repeat the predicate of the partial index -- idx_chat_messages_search_tsv so the planner can use it. Additional @@ -10192,18 +10199,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', $16)) - OR (cm.search_tsv_config IS NULL AND cm.search_tsv @@ websearch_to_tsquery('simple', $16)) + (cm.search_tsv_config = 'english' AND cm.search_tsv @@ websearch_to_tsquery('english', $17)) + OR (cm.search_tsv_config IS NULL AND cm.search_tsv @@ websearch_to_tsquery('simple', $17)) ) ) -- Skip an explicit pr_number lookup unless the search is a valid bigint. OR CASE - WHEN $16 ~ '^[0-9]{1,18}$' THEN EXISTS ( + WHEN $17 ~ '^[0-9]{1,18}$' 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 = $16::bigint + AND cds.pr_number = $17::bigint ) ELSE false END @@ -10226,11 +10233,11 @@ ORDER BY -chats_expanded.pin_order DESC, chats_expanded.updated_at DESC, chats_expanded.id DESC -OFFSET $17 +OFFSET $18 LIMIT -- The chat list is unbounded and expected to grow large. -- Default to 50 to prevent accidental excessively large queries. - COALESCE(NULLIF($18 :: int, 0), 50) + COALESCE(NULLIF($19 :: int, 0), 50) ` type GetChatsParams struct { @@ -10245,6 +10252,7 @@ type GetChatsParams struct { 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"` @@ -10272,6 +10280,7 @@ func (q *sqlQuerier) GetChats(ctx context.Context, arg GetChatsParams) ([]GetCha arg.DiffURL, arg.TitleQuery, arg.HasUnread, + pq.Array(arg.ChatStatuses), pq.Array(arg.PullRequestStatuses), arg.PrNumber, arg.RepoQuery, diff --git a/coderd/database/queries/chats.sql b/coderd/database/queries/chats.sql index ca28b062d64..8d1f30641a2 100644 --- a/coderd/database/queries/chats.sql +++ b/coderd/database/queries/chats.sql @@ -644,6 +644,13 @@ WHERE ) = sqlc.narg('has_unread')::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(@chat_statuses::text[], 1), 0) > 0 THEN + chats_expanded.status::text = ANY(@chat_statuses::text[]) + ELSE true + END -- Filter by pull request status. Unlike the diff_url filter above, -- this intentionally checks only the root chat's own diff status. -- Child chats share the same workspace and git branch as their diff --git a/coderd/exp_chats.go b/coderd/exp_chats.go index 24328e952d4..66cf681e11d 100644 --- a/coderd/exp_chats.go +++ b/coderd/exp_chats.go @@ -413,7 +413,7 @@ 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`, `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`, `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" @@ -494,6 +494,7 @@ func (api *API) listChats(rw http.ResponseWriter, r *http.Request) { DiffURL: searchParams.DiffURL, TitleQuery: searchParams.TitleQuery, HasUnread: searchParams.HasUnread, + ChatStatuses: searchParams.ChatStatuses, PullRequestStatuses: searchParams.PullRequestStatuses, PrNumber: searchParams.PrNumber, RepoQuery: searchParams.RepoQuery, diff --git a/coderd/searchquery/search.go b/coderd/searchquery/search.go index 8fcf5882684..a762d390ded 100644 --- a/coderd/searchquery/search.go +++ b/coderd/searchquery/search.go @@ -502,6 +502,8 @@ func AIBridgeClients(query string, page codersdk.Pagination) (database.ListAIBri // - archived: boolean (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 // - pr_status: repeated or comma-separated list of draft, open, // merged, closed, or none (no pull request) // - diff_url: string (matches chats whose linked diff URL equals the @@ -541,6 +543,13 @@ func Chats(query string) (database.GetChatsParams, []codersdk.ValidationError) { parser := httpapi.NewQueryParamParser() 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))) + if !status.Valid() { + return "", xerrors.Errorf("%q is not a valid value", v) + } + return string(status), nil + }) filter.PullRequestStatuses = httpapi.ParseCustomList(parser, values, nil, "pr_status", func(v string) (string, error) { normalizedPRStatus := strings.ToLower(strings.TrimSpace(v)) switch normalizedPRStatus { diff --git a/coderd/searchquery/search_test.go b/coderd/searchquery/search_test.go index 2592631723d..996079688cc 100644 --- a/coderd/searchquery/search_test.go +++ b/coderd/searchquery/search_test.go @@ -1108,11 +1108,14 @@ func TestSearchChatsFrontendEmitted(t *testing.T) { {name: "HasUnread", query: "has_unread:true"}, {name: "Archived", query: "archived:true"}, {name: "PRStatuses", query: "pr_status:open,merged"}, + {name: "ChatStatuses", query: "status:error,running"}, {name: "PRStatusNone", query: "pr_status:none"}, {name: "DiffURL", query: `diff_url:"https://github.com/coder/coder/pull/1"`}, {name: "FilterAndSearch", query: `has_unread:true search:"fix auth"`}, {name: "SidebarDefault", query: "archived:false"}, {name: "SidebarUnread", query: "archived:false has_unread:true"}, + {name: "SidebarStatus", query: "archived:false status:requires_action,running,interrupting"}, + {name: "SidebarUnreadStatus", query: "archived:false has_unread:true status:requires_action,running,interrupting"}, { name: "SidebarFiltered", query: "archived:false pr_status:draft,closed source:created_by_me,shared_with_me", @@ -1128,7 +1131,7 @@ func TestSearchChatsFrontendEmitted(t *testing.T) { }) } - rejectedQueries := []string{"pr_status:banana", "has_unread:maybe"} + rejectedQueries := []string{"pr_status:banana", "has_unread:maybe", "status:working"} for _, query := range rejectedQueries { t.Run("Rejects"+query, func(t *testing.T) { t.Parallel() @@ -1208,6 +1211,29 @@ func TestSearchChats(t *testing.T) { Query: "has_unread:bogus", ExpectedErrorContains: "has_unread", }, + { + Name: "ChatStatusRunning", + Query: "status:running", + Expected: database.GetChatsParams{ + Archived: sql.NullBool{Bool: false, Valid: true}, + OwnedOnly: true, + ChatStatuses: []string{"running"}, + }, + }, + { + Name: "ChatStatusMultiple", + Query: "status:waiting,error", + Expected: database.GetChatsParams{ + Archived: sql.NullBool{Bool: false, Valid: true}, + OwnedOnly: true, + ChatStatuses: []string{"waiting", "error"}, + }, + }, + { + Name: "ChatStatusInvalid", + Query: "status:working", + ExpectedErrorContains: "status", + }, { Name: "PRStatusDraft", Query: "pr_status:draft", diff --git a/codersdk/toolsdk/chats.go b/codersdk/toolsdk/chats.go index 7d909836982..ecc04b3ff92 100644 --- a/codersdk/toolsdk/chats.go +++ b/codersdk/toolsdk/chats.go @@ -485,7 +485,7 @@ var ListChats = Tool[ListChatsArgs, ListChatsResponse]{ }, "query": map[string]any{ "type": "string", - "description": "Optional chat search query using fielded terms; bare text is rejected. Supported fields: search: (full-text, cannot combine with title, pr_title, or pr), title:, repo:, pr:, pr_title:, pr_status:, diff_url:, archived:, has_unread:, source:. Quote values containing spaces or colons (URLs always need quoting), e.g. search:\"failed deployment\" or diff_url:\"https://github.com/org/repo/pull/1\".", + "description": "Optional chat search query using fielded terms; bare text is rejected. Supported fields: search: (full-text, cannot combine with title, pr_title, or pr), title:, repo:, pr:, pr_title:, pr_status:, diff_url:, archived:, has_unread:, status:, source:. Quote values containing spaces or colons (URLs always need quoting), e.g. search:\"failed deployment\" or diff_url:\"https://github.com/org/repo/pull/1\".", }, "limit": map[string]any{ "type": "integer", diff --git a/docs/ai-coder/agents/chat-search-syntax.md b/docs/ai-coder/agents/chat-search-syntax.md index b10eac49fc5..c927ab5d47d 100644 --- a/docs/ai-coder/agents/chat-search-syntax.md +++ b/docs/ai-coder/agents/chat-search-syntax.md @@ -9,18 +9,19 @@ full-text search. ## Filters -| Key | Values | Description | -|--------------|---------------------------------------------|-----------------------------------------------------------------------------------------------------------------------| -| `title` | substring | Case-insensitive substring match. Quote multi-word values. | -| `archived` | `true`, `false` | Filter by archived state. Default: `false`. | -| `has_unread` | `true`, `false` | Conversations with unread assistant messages. | -| `pr_status` | `draft`, `open`, `merged`, `closed`, `none` | Linked pull request state. Comma-separated for OR. `none` matches conversations with no linked pull request. | -| `diff_url` | URL | Match by associated diff URL. Quote values containing colons. | -| `pr` | positive integer | Exact PR number match. | -| `repo` | substring | Case-insensitive substring match against git remote origin or URL. Quote values containing colons. | -| `pr_title` | substring | Case-insensitive PR title substring match. Quote multi-word values. | -| `source` | `created_by_me`, `shared_with_me` | Ownership scope. Default: `created_by_me`. Pass both values comma-separated to return owned and shared conversations. | -| `search` | text | Full-text search across chat titles, PR titles, PR numbers, and message content. Quote multi-word values. | +| Key | Values | Description | +|--------------|------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------| +| `title` | substring | Case-insensitive substring match. Quote multi-word values. | +| `archived` | `true`, `false` | Filter by archived state. Default: `false`. | +| `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_url` | URL | Match by associated diff URL. Quote values containing colons. | +| `pr` | positive integer | Exact PR number match. | +| `repo` | substring | Case-insensitive substring match against git remote origin or URL. Quote values containing colons. | +| `pr_title` | substring | Case-insensitive PR title substring match. Quote multi-word values. | +| `source` | `created_by_me`, `shared_with_me` | Ownership scope. Default: `created_by_me`. Pass both values comma-separated to return owned and shared conversations. | +| `search` | text | Full-text search across chat titles, PR titles, PR numbers, and message content. Quote multi-word values. | Multiple filters in one query combine with AND logic. `search:` cannot be combined with `title:`, `pr_title:`, or `pr:`. @@ -58,6 +59,12 @@ be combined with `title:`, `pr_title:`, or `pr:`. # Unread conversations ?q=has_unread:true +# Conversations that need you, or that failed +?q=status:requires_action,error + +# Conversations with a turn in progress +?q=status:running + # Conversations with open or draft PRs ?q=pr_status:open,draft @@ -91,6 +98,8 @@ be combined with `title:`, `pr_title:`, or `pr:`. ## Notes +- `status:waiting` is an idle conversation, `status:running` is a turn in progress, and `status:interrupting` is a turn being stopped. +- `status:requires_action` means the agent needs you before it can continue, and `status:error` means the turn failed. - `title:`, `repo:`, and `pr_title:` use ILIKE matching. `%` and `_` act as wildcards. - `pr_status:draft` means the PR is open **and** marked as a draft. `pr_status:open` means the PR is open and not a draft. diff --git a/docs/reference/api/chats.md b/docs/reference/api/chats.md index 641c6f34586..fcf09a103d9 100644 --- a/docs/reference/api/chats.md +++ b/docs/reference/api/chats.md @@ -52,13 +52,13 @@ 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`, `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 | +| 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 | ### Example responses diff --git a/site/src/api/queries/chats.test.ts b/site/src/api/queries/chats.test.ts index 2795965642d..7c3de2cdc2a 100644 --- a/site/src/api/queries/chats.test.ts +++ b/site/src/api/queries/chats.test.ts @@ -621,20 +621,53 @@ describe("invalidateChatListQueries", () => { ).not.toBe(true); }); - it("prepends new root chats to filtered list caches", () => { - const queryClient = createTestQueryClient(); - const activeChat = makeChat("active-created", { archived: false }); + it.each<{ status: TypesGen.ChatStatus; matchingFilters: string[] }>([ + { status: "waiting", matchingFilters: ["idle"] }, + { status: "running", matchingFilters: ["working"] }, + { status: "interrupting", matchingFilters: ["working"] }, + { status: "error", matchingFilters: ["error", "attention"] }, + { status: "requires_action", matchingFilters: ["action", "attention"] }, + ])( + "prepends $status root chats only to matching list caches", + ({ status, matchingFilters }) => { + const queryClient = createTestQueryClient(); + const chat = makeChat("active-created", { archived: false, status }); + const filters: { name: string; input: ChatListInput }[] = [ + { name: "unfiltered", input: {} }, + { name: "idle", input: { statuses: ["waiting"] } }, + { name: "working", input: { statuses: ["running"] } }, + { name: "error", input: { statuses: ["error"] } }, + { name: "action", input: { statuses: ["requires_action"] } }, + { + name: "attention", + input: { statuses: ["error", "requires_action"] }, + }, + { + name: "all", + input: { + statuses: ["requires_action", "error", "running", "waiting"], + }, + }, + { name: "archived", input: { archived: true, statuses: [status] } }, + ]; + for (const { input } of filters) { + seedInfiniteChats(queryClient, [], input); + } - seedInfiniteChats(queryClient, [makeChat("active-existing")], { - archived: false, - }); + prependToInfiniteChatsCache(queryClient, chat); + prependToInfiniteChatsCache(queryClient, chat); - prependToInfiniteChatsCache(queryClient, activeChat); - - expect(readInfiniteChats(queryClient, { archived: false })?.[0]).toEqual( - activeChat, - ); - }); + for (const { name, input } of filters) { + const matches = + name === "unfiltered" || + name === "all" || + matchingFilters.includes(name); + expect(readInfiniteChats(queryClient, input), name).toEqual( + matches ? [chat] : [], + ); + } + }, + ); }); describe("planModeFieldsForCreateMessage", () => { @@ -2144,6 +2177,7 @@ describe("chatListKey shape", () => { archived: true, prStatuses: [], status: "all", + statuses: [], sources: [], }); }); @@ -2170,6 +2204,36 @@ describe("getChatListQueryString", () => { expect( getChatListQueryString(toChatListParams({ prStatuses: ["none"] })), ).toBe("archived:false pr_status:none"); + expect( + getChatListQueryString( + toChatListParams({ + statuses: ["running", "requires_action"], + }), + ), + ).toBe("archived:false status:requires_action,running,interrupting"); + expect( + getChatListQueryString( + toChatListParams({ + chatStatus: "unread", + statuses: ["running", "requires_action"], + }), + ), + ).toBe( + "archived:false has_unread:true status:requires_action,running,interrupting", + ); + expect( + getChatListQueryString( + toChatListParams({ + statuses: [ + "requires_action", + "error", + "running", + "interrupting", + "waiting", + ], + }), + ), + ).toBe("archived:false"); }); }); diff --git a/site/src/api/queries/chats.ts b/site/src/api/queries/chats.ts index 653d08816be..90a9cb6d8a4 100644 --- a/site/src/api/queries/chats.ts +++ b/site/src/api/queries/chats.ts @@ -48,12 +48,42 @@ export type ChatListPRStatusFilter = | "merged" | "closed" | "none"; -export type ChatListStatusFilter = "read" | "unread"; +type ChatListStatusFilter = "read" | "unread"; +// Interrupting is a brief stop-in-progress state, so it is not its own +// filter. Selecting Working includes it. +export const CHAT_STATUS_FILTER_ORDER = [ + "requires_action", + "error", + "running", + "waiting", +] as const satisfies readonly Exclude[]; +export const CHAT_STATUS_GROUP_ORDER = [ + "requires_action", + "error", + "running", + "interrupting", + "waiting", +] as const satisfies readonly TypesGen.ChatStatus[]; +type _Assert = T; +type _ChatStatusFilterCovers = _Assert< + Exclude< + TypesGen.ChatStatus, + "interrupting" + > extends (typeof CHAT_STATUS_FILTER_ORDER)[number] + ? true + : false +>; +type _ChatStatusGroupCovers = _Assert< + TypesGen.ChatStatus extends (typeof CHAT_STATUS_GROUP_ORDER)[number] + ? true + : false +>; type ChatListParams = Readonly<{ archived: boolean; prStatuses: readonly ChatListPRStatusFilter[]; status: ChatListStatusFilter | "all"; + statuses: readonly TypesGen.ChatStatus[]; sources: readonly TypesGen.ChatListSource[]; }>; @@ -61,6 +91,7 @@ export type ChatListInput = Readonly<{ archived?: boolean; prStatuses?: readonly ChatListPRStatusFilter[]; chatStatus?: ChatListStatusFilter; + statuses?: readonly TypesGen.ChatStatus[]; sources?: readonly TypesGen.ChatListSource[]; }>; @@ -80,6 +111,9 @@ export const CHAT_LIST_PR_STATUS_ORDER = [ const chatListPRStatusSet = new Set( CHAT_LIST_PR_STATUS_ORDER, ); +const chatStatusFilterSet = new Set( + CHAT_STATUS_FILTER_ORDER, +); type InfiniteChatsCacheData = InfiniteData; @@ -100,6 +134,23 @@ export const canonicalizeChatListPRStatuses = ( return CHAT_LIST_PR_STATUS_ORDER.filter((status) => selected.has(status)); }; +/** Shared ordering keeps URL serialization stable. */ +const canonicalizeChatListStatuses = ( + statuses: Iterable, +): readonly TypesGen.ChatStatus[] => { + const selected = new Set(); + for (const status of statuses) { + if ( + typeof status === "string" && + chatStatusFilterSet.has(status as TypesGen.ChatStatus) + ) { + selected.add(status as TypesGen.ChatStatus); + } + } + + return CHAT_STATUS_FILTER_ORDER.filter((status) => selected.has(status)); +}; + const canonicalWorkspaceIds = ( workspaceIds: readonly string[], ): readonly string[] => { @@ -142,9 +193,8 @@ export const updateInfiniteChatsCache = ( * in the cache, but only if the chat doesn't already exist in any * page. This avoids the per-page duplication that would occur if * a prepend updater were passed to updateInfiniteChatsCache, which - * runs independently on each page. Lists whose archived filter - * conflicts with the chat's archive state are skipped, so an active - * chat is never inserted into an archived-only list. + * runs independently on each page. Lists whose archive or status + * filters exclude the chat are skipped. */ export const prependToInfiniteChatsCache = ( queryClient: QueryClient, @@ -158,6 +208,24 @@ export const prependToInfiniteChatsCache = ( if (archivedFilter !== undefined && archivedFilter !== chat.archived) { continue; } + const params = queryKey[chatListFamilyKey.length]; + const statuses = + queryKey.length === chatListFamilyKey.length + 1 && + params !== null && + typeof params === "object" && + "statuses" in params && + Array.isArray(params.statuses) + ? canonicalizeChatListStatuses(params.statuses) + : []; + if ( + statuses.length > 0 && + statuses.length < CHAT_STATUS_FILTER_ORDER.length && + !statuses.includes( + chat.status === "interrupting" ? "running" : chat.status, + ) + ) { + continue; + } queryClient.setQueryData(queryKey, (prev) => { if (!prev?.pages) return prev; // Check across ALL pages to avoid duplicates. @@ -1100,6 +1168,7 @@ export const toChatListParams = (input?: ChatListInput): ChatListParams => ({ archived: input?.archived ?? false, prStatuses: canonicalizeChatListPRStatuses(input?.prStatuses ?? []), status: input?.chatStatus ?? "all", + statuses: canonicalizeChatListStatuses(input?.statuses ?? []), sources: canonicalizeChatSources(input?.sources ?? []), }); @@ -1116,6 +1185,15 @@ export const getChatListQueryString = ( if (params.status !== "all") { qParts.push(`has_unread:${params.status === "unread"}`); } + if ( + params.statuses.length > 0 && + params.statuses.length < CHAT_STATUS_FILTER_ORDER.length + ) { + const statuses = params.statuses.flatMap((status) => + status === "running" ? (["running", "interrupting"] as const) : [status], + ); + qParts.push(`status:${statuses.join(",")}`); + } if (params.sources.length) { qParts.push(`source:${params.sources.join(",")}`); } diff --git a/site/src/pages/AgentsPage/AgentsPageLayout.tsx b/site/src/pages/AgentsPage/AgentsPageLayout.tsx index afed86008cd..6c9eda50e56 100644 --- a/site/src/pages/AgentsPage/AgentsPageLayout.tsx +++ b/site/src/pages/AgentsPage/AgentsPageLayout.tsx @@ -81,7 +81,10 @@ import { ResizableChatsSidebarFrame } from "./components/ChatsSidebar/ResizableC import { useAgentsPageKeybindings } from "./hooks/useAgentsPageKeybindings"; import { useAgentsPWA } from "./hooks/useAgentsPWA"; import { useOrganizationChatModels } from "./hooks/useOrganizationChatModels"; -import { getAgentSidebarFilters } from "./utils/agentSidebarFilters"; +import { + AGENT_CHAT_STATUS_ORDER, + getAgentSidebarFilters, +} from "./utils/agentSidebarFilters"; import { archiveChatAndDeleteWorkspace, notifyArchiveAndDeleteFailed, @@ -192,15 +195,16 @@ const AgentsPageLayout: React.FC = () => { }, []); const archivedFilter = sidebarFilters.archiveStatus === "archived"; - const chatStatusFilter = - sidebarFilters.chatStatuses.length === 1 - ? sidebarFilters.chatStatuses[0] - : undefined; + const statuses = + sidebarFilters.chatStatuses.length === AGENT_CHAT_STATUS_ORDER.length + ? undefined + : sidebarFilters.chatStatuses; const chatsQuery = useInfiniteQuery( infiniteChats({ archived: archivedFilter, prStatuses: sidebarFilters.prStatuses, - chatStatus: chatStatusFilter, + statuses, + chatStatus: sidebarFilters.unread ? "unread" : undefined, sources: sidebarFilters.sources, }), ); diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/ChatsSidebar.test.tsx b/site/src/pages/AgentsPage/components/ChatsSidebar/ChatsSidebar.test.tsx index eb4a2918692..3d095044cc4 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/ChatsSidebar.test.tsx +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/ChatsSidebar.test.tsx @@ -19,7 +19,10 @@ import { } from "#/testHelpers/entities"; import { createTestQueryClient } from "#/testHelpers/renderHelpers"; import themes, { DEFAULT_THEME } from "#/theme"; -import type { AgentSidebarFilters } from "../../utils/agentSidebarFilters"; +import { + AGENT_CHAT_STATUS_ORDER, + type AgentSidebarFilters, +} from "../../utils/agentSidebarFilters"; import { ChatsSidebar } from "./ChatsSidebar"; // ---- IntersectionObserver mock ---- @@ -104,7 +107,8 @@ const defaultSidebarFilters: AgentSidebarFilters = { archiveStatus: "active", groupBy: "date", prStatuses: [], - chatStatuses: ["unread", "read"], + chatStatuses: AGENT_CHAT_STATUS_ORDER, + unread: false, sources: ["created_by_me"], }; @@ -303,7 +307,7 @@ describe("ChatsSidebar filters", () => { archiveStatus: "archived", groupBy: "chat_status", prStatuses: ["draft"], - chatStatuses: ["unread"], + chatStatuses: ["running"], sources: ["shared_with_me"], }; @@ -330,7 +334,7 @@ describe("ChatsSidebar filters", () => { expect(onSidebarFiltersChange).toHaveBeenCalledWith({ ...sidebarFilters, prStatuses: [], - chatStatuses: ["unread", "read"], + chatStatuses: defaultSidebarFilters.chatStatuses, sources: ["created_by_me"], }); }); @@ -387,7 +391,7 @@ describe("ChatsSidebar filters", () => { {...defaultProps} sidebarFilters={{ ...defaultSidebarFilters, - chatStatuses: ["unread"], + chatStatuses: ["running"], sources: ["shared_with_me"], }} onSidebarFiltersChange={onSidebarFiltersChange} @@ -395,12 +399,37 @@ describe("ChatsSidebar filters", () => { , ); - await toggleSubmenuOption(user, /Chat status/, "Unread"); + await toggleSubmenuOption(user, "Status", "Working"); await toggleSubmenuOption(user, /Source/, "Shared with me"); expect(onSidebarFiltersChange).not.toHaveBeenCalled(); }); + it("applies the unread checkbox", async () => { + const user = userEvent.setup(); + const onSidebarFiltersChange = vi.fn(); + + render( + + + , + ); + + await user.click(screen.getByRole("button", { name: "Filter agents" })); + await user.click( + await screen.findByRole("menuitemcheckbox", { name: "Unread" }), + ); + + expect(onSidebarFiltersChange).toHaveBeenCalledWith({ + ...defaultSidebarFilters, + unread: true, + }); + }); + it("clears every sidebar filter from the menu", async () => { const user = userEvent.setup(); const onSidebarFiltersChange = vi.fn(); @@ -436,13 +465,29 @@ describe("ChatsSidebar filters", () => { {...defaultProps} chats={[ buildChat({ - id: "unread-chat", - title: "Unread chat", - has_unread: true, + id: "attention-chat", + title: "Needs action", + status: "requires_action", }), buildChat({ - id: "read-chat", - title: "Read chat", + id: "error-chat", + title: "Failed chat", + status: "error", + }), + buildChat({ + id: "working-chat", + title: "Working chat", + status: "running", + }), + buildChat({ + id: "interrupting-chat", + title: "Interrupting chat", + status: "interrupting", + }), + buildChat({ + id: "idle-chat", + title: "Idle chat", + status: "waiting", }), ]} sidebarFilters={{ @@ -453,26 +498,42 @@ describe("ChatsSidebar filters", () => { , ); - const unreadSection = screen.getByTestId("agents-section-toggle-Unread"); - const readSection = screen.getByTestId("agents-section-toggle-Read"); - const unreadNode = screen.getByTestId("agents-tree-node-unread-chat"); - const readNode = screen.getByTestId("agents-tree-node-read-chat"); + const attentionSection = screen.getByTestId( + "agents-section-toggle-Requires-action", + ); + const errorSection = screen.getByTestId("agents-section-toggle-Error"); + const workingSection = screen.getByTestId("agents-section-toggle-Working"); + const interruptingSection = screen.getByTestId( + "agents-section-toggle-Interrupting", + ); + const idleSection = screen.getByTestId("agents-section-toggle-Idle"); + const attentionNode = screen.getByTestId("agents-tree-node-attention-chat"); + const errorNode = screen.getByTestId("agents-tree-node-error-chat"); + const workingNode = screen.getByTestId("agents-tree-node-working-chat"); + const interruptingNode = screen.getByTestId( + "agents-tree-node-interrupting-chat", + ); + const idleNode = screen.getByTestId("agents-tree-node-idle-chat"); expect( screen.queryByTestId("agents-section-toggle-Today"), ).not.toBeInTheDocument(); - expect( - unreadSection.compareDocumentPosition(unreadNode) & - Node.DOCUMENT_POSITION_FOLLOWING, - ).toBeTruthy(); - expect( - unreadNode.compareDocumentPosition(readSection) & - Node.DOCUMENT_POSITION_FOLLOWING, - ).toBeTruthy(); - expect( - readSection.compareDocumentPosition(readNode) & - Node.DOCUMENT_POSITION_FOLLOWING, - ).toBeTruthy(); + for (const [before, after] of [ + [attentionSection, attentionNode], + [attentionNode, errorSection], + [errorSection, errorNode], + [errorNode, workingSection], + [workingSection, workingNode], + [workingNode, interruptingSection], + [interruptingSection, interruptingNode], + [interruptingNode, idleSection], + [idleSection, idleNode], + ] as const) { + expect( + before.compareDocumentPosition(after) & + Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + } }); }); diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/chats/ChatsPanel.tsx b/site/src/pages/AgentsPage/components/ChatsSidebar/chats/ChatsPanel.tsx index 33e71b21762..ff95ab86c1a 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/chats/ChatsPanel.tsx +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/chats/ChatsPanel.tsx @@ -37,6 +37,7 @@ import { } from "#/components/Tooltip/Tooltip"; import { getOSKey } from "#/utils/platform"; import { + AGENT_CHAT_STATUS_GROUP_ORDER, AGENT_CHAT_STATUS_ORDER, type AgentSidebarFilters, DEFAULT_AGENT_SIDEBAR_FILTERS, @@ -56,6 +57,7 @@ import { collectVisibleChatIDs, } from "../tree/chatTree"; import { SortableChatTreeNode } from "../tree/SortableChatTreeNode"; +import { getChatStatusDisplay } from "../tree/statusConfig"; import { ChatSectionHeader, getSectionToggleTestId, @@ -65,8 +67,6 @@ import { LoadMoreSentinel } from "./LoadMoreSentinel"; import { SectionSwitcher } from "./SectionSwitcher"; import { UserSidebarFooter } from "./UserSidebarFooter"; -const UNREAD_SECTION_KEY = "Unread"; -const READ_SECTION_KEY = "Read"; const SHARED_WITH_YOU_SECTION_KEY = "Shared with you"; type ChatsPanelProps = { @@ -174,6 +174,7 @@ export const ChatsPanel: React.FC = ({ const hasAppliedResultFilters = sidebarFilters.prStatuses.length > 0 || sidebarFilters.chatStatuses.length !== AGENT_CHAT_STATUS_ORDER.length || + sidebarFilters.unread || sidebarFilters.sources.length !== DEFAULT_AGENT_SIDEBAR_FILTERS.sources.length || sidebarFilters.sources.some( @@ -325,18 +326,14 @@ export const ChatsPanel: React.FC = ({ const chatSections = ( sidebarFilters.groupBy === "chat_status" - ? [ - { - key: UNREAD_SECTION_KEY, - label: UNREAD_SECTION_KEY, - chats: unpinnedOwnedChats.filter((chat) => chat.has_unread), - }, - { - key: READ_SECTION_KEY, - label: READ_SECTION_KEY, - chats: unpinnedOwnedChats.filter((chat) => !chat.has_unread), - }, - ] + ? AGENT_CHAT_STATUS_GROUP_ORDER.map((status) => { + const label = getChatStatusDisplay(status).label; + return { + key: label, + label, + chats: unpinnedOwnedChats.filter((chat) => chat.status === status), + }; + }) : TIME_GROUPS.map((group) => ({ key: group, label: group, @@ -358,6 +355,7 @@ export const ChatsPanel: React.FC = ({ ...sidebarFilters, prStatuses: [], chatStatuses: AGENT_CHAT_STATUS_ORDER, + unread: false, sources: DEFAULT_AGENT_SIDEBAR_FILTERS.sources, }); }; diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/ChatSearchDialog.stories.tsx b/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/ChatSearchDialog.stories.tsx index dd6751ffbb7..face4e77820 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/ChatSearchDialog.stories.tsx +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/ChatSearchDialog.stories.tsx @@ -568,6 +568,30 @@ export const ParameterizedFilterPillEnterCommit: Story = { }, }; +export const StatusFilterPill: Story = { + beforeEach: () => { + spyOn(API.experimental, "getChats").mockResolvedValue(mockChats); + }, + play: async () => { + const body = within(document.body); + const searchInput = body.getByRole("combobox", { name: "Search chats" }); + const toggleButton = body.getByRole("button", { name: "Toggle filters" }); + + await userEvent.click(toggleButton); + await userEvent.click(await body.findByText("Status")); + await userEvent.click(searchInput); + await userEvent.type(searchInput, "running"); + await userEvent.keyboard("{Enter}"); + + await waitFor(() => { + expect(API.experimental.getChats).toHaveBeenCalledWith({ + limit: CHAT_SEARCH_LIMIT, + q: "status:running", + }); + }); + }, +}; + export const BackspaceRemovesFilter: Story = { play: async () => { const body = within(document.body); diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/ChatSearchDialog.tsx b/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/ChatSearchDialog.tsx index efe9d7a5a9e..025ef897c47 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/ChatSearchDialog.tsx +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/ChatSearchDialog.tsx @@ -3,6 +3,7 @@ import { CircleDotIcon, FileTextIcon, LinkIcon, + MessagesSquareIcon, } from "lucide-react"; import { useId, useRef, useState } from "react"; import { keepPreviousData, useQuery } from "react-query"; @@ -19,6 +20,7 @@ import { CHAT_SEARCH_FILTER_KEYS, type ChatSearchFilterKey, extractTypedFilters, + isCommaSeparatedChatSearchFilter, isValidChatSearchFilterValue, normalizeChatSearchFilterValue, } from "./searchQuery"; @@ -49,6 +51,12 @@ const FILTER_DEFINITIONS_BY_KEY: Readonly< defaultValue: "true", validate: (value) => isValidChatSearchFilterValue("archived", value), }, + status: { + label: "Status", + icon: MessagesSquareIcon, + defaultValue: null, + validate: (value) => isValidChatSearchFilterValue("status", value), + }, pr_status: { label: "PR status", icon: FileTextIcon, @@ -221,10 +229,11 @@ const ChatSearchDialogContent: React.FC = ({ (def) => def.key === incompleteFilterKey, ); if (incompleteFilterKey && definition?.validate(value)) { - const committedValue = - incompleteFilterKey === "pr_status" - ? normalizeChatSearchFilterValue(incompleteFilterKey, value) - : value; + const committedValue = isCommaSeparatedChatSearchFilter( + incompleteFilterKey, + ) + ? normalizeChatSearchFilterValue(incompleteFilterKey, value) + : value; setFilters((previous) => [ ...previous.filter((filter) => filter.key !== incompleteFilterKey), { key: incompleteFilterKey, value: committedValue }, @@ -288,7 +297,7 @@ const ChatSearchDialogContent: React.FC = ({ freeText.trim() && !( event.key === " " && - incompleteFilterKey === "pr_status" && + isCommaSeparatedChatSearchFilter(incompleteFilterKey) && freeText.trimEnd().endsWith(",") ) ) { diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/searchQuery.test.ts b/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/searchQuery.test.ts index 3e8e03b7f9b..a55acef5742 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/searchQuery.test.ts +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/searchQuery.test.ts @@ -42,6 +42,9 @@ describe("buildChatSearchQuery", () => { expect( buildChatSearchQuery([{ key: "pr_status", value: ",, ," }], ""), ).toBe(undefined); + expect( + buildChatSearchQuery([{ key: "status", value: "error running" }], ""), + ).toBe("status:error,running"); expect( buildChatSearchQuery( [ @@ -78,6 +81,7 @@ describe("buildChatSearchQuery", () => { it("does not emit invalid structured filters", () => { for (const filter of [ { key: "pr_status", value: "banana" }, + { key: "status", value: "working" }, { key: "has_unread", value: "maybe" }, { key: "archived", value: "no" }, { key: "diff_url", value: "ftp://example.com/x" }, @@ -87,7 +91,7 @@ describe("buildChatSearchQuery", () => { }); it("skips filters whose sanitized value is empty", () => { - for (const key of ["pr_status", "diff_url"]) { + for (const key of ["pr_status", "status", "diff_url"]) { for (const value of ['"', '""']) { expect(buildChatSearchQuery([{ key, value }], "")).toBe(undefined); } @@ -151,6 +155,37 @@ describe("extractTypedFilters", () => { }); }); + it("extracts a chat status list", () => { + expect(extractTypedFilters("status:running", [])).toEqual({ + filters: [{ key: "status", value: "running" }], + remainingText: "", + consumed: true, + }); + expect(extractTypedFilters("status:error, running", [])).toEqual({ + filters: [{ key: "status", value: "error,running" }], + remainingText: "", + consumed: true, + }); + expect(extractTypedFilters("status:requires_action, error", [])).toEqual({ + filters: [{ key: "status", value: "requires_action,error" }], + remainingText: "", + consumed: true, + }); + }); + + it("leaves invalid chat status text unchanged", () => { + expect(extractTypedFilters("status:working", [])).toEqual({ + filters: [], + remainingText: "status:working", + consumed: false, + }); + expect(extractTypedFilters("status:error,", [])).toEqual({ + filters: [], + remainingText: "status:error,", + consumed: false, + }); + }); + it("accepts chats with no pull request", () => { expect(extractTypedFilters("pr_status:none", [])).toEqual({ filters: [{ key: "pr_status", value: "none" }], @@ -243,6 +278,7 @@ describe("extractTypedFilters", () => { "has_unread:maybe", "archived:no", "pr_status:banana", + "status:working", "pr_status:,,", 'diff_url:"ftp://example.com/x"', 'pr_status:""', diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/searchQuery.ts b/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/searchQuery.ts index c6a1448ce57..6c110d4bdf5 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/searchQuery.ts +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/searchQuery.ts @@ -1,9 +1,13 @@ -import { CHAT_LIST_PR_STATUS_ORDER } from "#/api/queries/chats"; +import { + CHAT_LIST_PR_STATUS_ORDER, + CHAT_STATUS_GROUP_ORDER, +} from "#/api/queries/chats"; import type { SearchFilter } from "./ChatSearchInput"; export const CHAT_SEARCH_FILTER_KEYS = [ "has_unread", "archived", + "status", "pr_status", "diff_url", ] as const; @@ -38,7 +42,7 @@ export const normalizeChatSearchFilterValue = ( if (key === "diff_url") { return addDefaultURLScheme(sanitizedValue); } - if (key === "pr_status") { + if (isCommaSeparatedChatSearchFilter(key)) { return sanitizedValue .split(/[\s,]+/) .filter(Boolean) @@ -48,6 +52,13 @@ export const normalizeChatSearchFilterValue = ( }; const validPRStatuses = new Set(CHAT_LIST_PR_STATUS_ORDER); +const validChatStatuses = new Set(CHAT_STATUS_GROUP_ORDER); + +// These values are lists, so a trailing comma means the user is still +// typing the next entry. +export const isCommaSeparatedChatSearchFilter = (key: string): boolean => { + return key === "pr_status" || key === "status"; +}; const validBooleans = new Set(["true", "false"]); @@ -72,6 +83,10 @@ const CHAT_SEARCH_FILTER_VALIDATORS: Readonly< value .split(",") .every((status) => validPRStatuses.has(status.toLowerCase())), + status: (value) => + value + .split(",") + .every((status) => validChatStatuses.has(status.toLowerCase())), diff_url: isValidDiffURL, }; @@ -210,7 +225,7 @@ export const extractTypedFilters = ( .trim(); const candidateTokens = [token.value]; let nextTokenIndex = tokenIndex + 1; - if (key === "pr_status" && value.endsWith(",")) { + if (isCommaSeparatedChatSearchFilter(key) && value.endsWith(",")) { while (value.endsWith(",") && nextTokenIndex < tokens.length) { const nextToken = tokens[nextTokenIndex]; value = `${value} ${nextToken.value}`; @@ -236,7 +251,7 @@ export const extractTypedFilters = ( } else { filtersByKey.set(key, { key, - value: key === "pr_status" ? normalizedValue : value, + value: isCommaSeparatedChatSearchFilter(key) ? normalizedValue : value, }); } tokenIndex = nextTokenIndex; diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/filters/FilterPopover.stories.tsx b/site/src/pages/AgentsPage/components/ChatsSidebar/filters/FilterPopover.stories.tsx index 80fff66eb37..504b16f4bad 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/filters/FilterPopover.stories.tsx +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/filters/FilterPopover.stories.tsx @@ -51,7 +51,8 @@ const activeFilters = { archiveStatus: "archived", groupBy: "chat_status", prStatuses: ["draft", "open"], - chatStatuses: ["unread"], + chatStatuses: ["running"], + unread: true, sources: ["shared_with_me"], } satisfies AgentSidebarFilters; @@ -64,6 +65,17 @@ export const ActiveFilters: Story = { }, }; +export const ChatStatusSubmenu: Story = { + play: async ({ canvasElement }) => { + const user = await openFilterMenu(canvasElement); + await user.click( + await within(canvasElement.ownerDocument.body).findByRole("menuitem", { + name: "Status", + }), + ); + }, +}; + export const PrStatusSubmenu: Story = { args: { filters: activeFilters, diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/filters/FilterPopover.tsx b/site/src/pages/AgentsPage/components/ChatsSidebar/filters/FilterPopover.tsx index db88b4f556a..86b86588b5e 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/filters/FilterPopover.tsx +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/filters/FilterPopover.tsx @@ -8,8 +8,6 @@ import { GitPullRequestDraftIcon, GitPullRequestIcon, type LucideIcon, - MailIcon, - MailOpenIcon, MessagesSquareIcon, UserIcon, UsersIcon, @@ -40,6 +38,7 @@ import { type AgentSourceFilter, DEFAULT_AGENT_SIDEBAR_FILTERS, } from "../../../utils/agentSidebarFilters"; +import { getChatStatusDisplay } from "../tree/statusConfig"; const PR_STATUS_LABELS: Record = { draft: "PR Draft", @@ -55,14 +54,9 @@ const GROUP_OPTIONS: readonly Readonly<{ icon: LucideIcon; }>[] = [ { value: "date", label: "Date", icon: CalendarIcon }, - { value: "chat_status", label: "Chat status", icon: MessagesSquareIcon }, + { value: "chat_status", label: "Status", icon: MessagesSquareIcon }, ]; -const CHAT_STATUS_LABELS: Record = { - unread: "Unread", - read: "Read", -}; - const SOURCE_LABELS: Record = { created_by_me: "Created by me", shared_with_me: "Shared with me", @@ -76,11 +70,6 @@ const PR_STATUS_ICONS: Record = { none: CircleOffIcon, }; -const CHAT_STATUS_ICONS: Record = { - unread: MailIcon, - read: MailOpenIcon, -}; - const SOURCE_ICONS: Record = { created_by_me: UserIcon, shared_with_me: UsersIcon, @@ -90,11 +79,14 @@ const CHAT_STATUS_OPTIONS: readonly Readonly<{ value: AgentChatStatusFilter; label: string; icon: LucideIcon; -}>[] = AGENT_CHAT_STATUS_ORDER.map((status) => ({ - value: status, - label: CHAT_STATUS_LABELS[status], - icon: CHAT_STATUS_ICONS[status], -})); +}>[] = AGENT_CHAT_STATUS_ORDER.map((status) => { + const display = getChatStatusDisplay(status); + return { + value: status, + label: display.label, + icon: display.icon, + }; +}); const SOURCE_OPTIONS: readonly Readonly<{ value: AgentSourceFilter; @@ -128,6 +120,7 @@ const hasActiveFilters = (filters: AgentSidebarFilters): boolean => { filters.chatStatuses, DEFAULT_AGENT_SIDEBAR_FILTERS.chatStatuses, ) || + filters.unread || !haveSameSelections(filters.sources, DEFAULT_AGENT_SIDEBAR_FILTERS.sources) ); }; @@ -305,7 +298,7 @@ export const FilterPopover: React.FC = ({ })} - + {CHAT_STATUS_OPTIONS.map((option) => { const Icon = option.icon; return ( @@ -343,6 +336,16 @@ export const FilterPopover: React.FC = ({ })} + + onFiltersChange({ ...filters, unread: checked === true }) + } + onSelect={keepMenuOpen} + className="[&>span]:right-3.5" + > + Unread + setArchived(checked === true)} diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/tree/statusConfig.ts b/site/src/pages/AgentsPage/components/ChatsSidebar/tree/statusConfig.ts index 4a2449e46ae..45e145fe061 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/tree/statusConfig.ts +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/tree/statusConfig.ts @@ -45,7 +45,7 @@ const statusConfig = { }, } as const satisfies Record; -const getStatusConfig = (status: ChatStatus): ChatIconConfig => { +export const getChatStatusDisplay = (status: ChatStatus): ChatIconConfig => { return statusConfig[status] ?? statusConfig.waiting; }; @@ -103,7 +103,7 @@ export const getChatDisplayConfig = ( diffStatus: ChatDiffStatus | undefined; } => { const diffStatus = getChatDiffStatus(chat); - const config = getStatusConfig(chat.status); + const config = getChatStatusDisplay(chat.status); return { icon: config.icon, className: config.className, diff --git a/site/src/pages/AgentsPage/utils/agentSidebarFilters.test.ts b/site/src/pages/AgentsPage/utils/agentSidebarFilters.test.ts index 0207d8da725..7bae93e216d 100644 --- a/site/src/pages/AgentsPage/utils/agentSidebarFilters.test.ts +++ b/site/src/pages/AgentsPage/utils/agentSidebarFilters.test.ts @@ -2,6 +2,7 @@ import { act, waitFor } from "@testing-library/react"; import { useSearchParams } from "react-router"; import { renderHookWithAuth } from "#/testHelpers/hooks"; import { + AGENT_CHAT_STATUS_ORDER, type AgentSidebarFilters, getAgentSidebarFilters, } from "./agentSidebarFilters"; @@ -10,7 +11,8 @@ const defaultFilters: AgentSidebarFilters = { archiveStatus: "active", groupBy: "date", prStatuses: [], - chatStatuses: ["unread", "read"], + chatStatuses: AGENT_CHAT_STATUS_ORDER, + unread: false, sources: ["created_by_me"], }; @@ -18,7 +20,8 @@ const archivedFilters: AgentSidebarFilters = { archiveStatus: "archived", groupBy: "chat_status", prStatuses: ["draft", "merged"], - chatStatuses: ["unread"], + chatStatuses: ["running"], + unread: false, sources: ["created_by_me", "shared_with_me"], }; @@ -48,12 +51,13 @@ describe(getAgentSidebarFilters.name, () => { { name: "parses archived, group_by, pr_status, chat_status, and source", route: - "/agents?archived=archived&group_by=chat_status&pr_status=open,draft,closed&chat_status=unread&source=shared_with_me", + "/agents?archived=archived&group_by=chat_status&pr_status=open,draft,closed&chat_status=running&source=shared_with_me", expected: { archiveStatus: "archived", groupBy: "chat_status", prStatuses: ["draft", "open", "closed"], - chatStatuses: ["unread"], + chatStatuses: ["running"], + unread: false, sources: ["shared_with_me"], }, }, @@ -80,7 +84,7 @@ describe(getAgentSidebarFilters.name, () => { it("omits default values when writing filters", async () => { const { result, getLocationSnapshot } = await renderFilters( - "/agents?archived=archived&group_by=chat_status&pr_status=draft&chat_status=unread", + "/agents?archived=archived&group_by=chat_status&pr_status=draft&chat_status=running", ); act(() => { @@ -129,7 +133,51 @@ describe(getAgentSidebarFilters.name, () => { expect(search.get("archived")).toBe("archived"); expect(search.get("group_by")).toBe("chat_status"); expect(search.get("pr_status")).toBe("draft,merged"); - expect(search.get("chat_status")).toBe("unread"); + expect(search.get("chat_status")).toBe("running"); expect(search.get("source")).toBe("created_by_me,shared_with_me"); }); + + it("writes a partial status selection in canonical order", async () => { + const { result, getLocationSnapshot } = await renderFilters(); + + act(() => { + result.current[1]({ + ...defaultFilters, + chatStatuses: ["running", "error"], + }); + }); + await waitFor(() => + expect(result.current[0].chatStatuses).toEqual(["error", "running"]), + ); + + expect(getLocationSnapshot().search.get("chat_status")).toBe( + "error,running", + ); + }); + + it("writes the unread filter without treating it as a chat status", async () => { + const { result, getLocationSnapshot } = await renderFilters(); + + act(() => { + result.current[1]({ ...defaultFilters, unread: true }); + }); + await waitFor(() => expect(result.current[0].unread).toBe(true)); + + const { search } = getLocationSnapshot(); + expect(search.get("unread")).toBe("true"); + expect(search.get("chat_status")).toBe(null); + }); + + it("reads the unread filter", async () => { + const { result } = await renderFilters("/agents?unread=true"); + expect(result.current[0].unread).toBe(true); + expect(result.current[0].chatStatuses).toEqual(AGENT_CHAT_STATUS_ORDER); + }); + + it("ignores interrupting and other values that are not filter options", async () => { + const { result } = await renderFilters( + "/agents?chat_status=working,interrupting,done", + ); + expect(result.current[0].chatStatuses).toEqual(AGENT_CHAT_STATUS_ORDER); + }); }); diff --git a/site/src/pages/AgentsPage/utils/agentSidebarFilters.ts b/site/src/pages/AgentsPage/utils/agentSidebarFilters.ts index 639639ff62a..3463731b0b9 100644 --- a/site/src/pages/AgentsPage/utils/agentSidebarFilters.ts +++ b/site/src/pages/AgentsPage/utils/agentSidebarFilters.ts @@ -2,21 +2,20 @@ import type { SetURLSearchParams } from "react-router"; import { CHAT_LIST_PR_STATUS_ORDER, CHAT_SOURCE_ORDER, + CHAT_STATUS_FILTER_ORDER, + CHAT_STATUS_GROUP_ORDER, type ChatListPRStatusFilter, - type ChatListStatusFilter, canonicalizeChatListPRStatuses, } from "#/api/queries/chats"; const AGENT_ARCHIVE_STATUS_ORDER = ["active", "archived"] as const; -export const AGENT_CHAT_STATUS_ORDER = [ - "unread", - "read", -] as const satisfies readonly ChatListStatusFilter[]; +export const AGENT_CHAT_STATUS_ORDER = CHAT_STATUS_FILTER_ORDER; +export const AGENT_CHAT_STATUS_GROUP_ORDER = CHAT_STATUS_GROUP_ORDER; export const AGENT_PR_STATUS_ORDER = CHAT_LIST_PR_STATUS_ORDER; export const AGENT_SOURCE_ORDER = CHAT_SOURCE_ORDER; type AgentArchiveStatusFilter = (typeof AGENT_ARCHIVE_STATUS_ORDER)[number]; -export type AgentChatStatusFilter = ChatListStatusFilter; +export type AgentChatStatusFilter = (typeof AGENT_CHAT_STATUS_ORDER)[number]; export type AgentPRStatusFilter = ChatListPRStatusFilter; export type AgentSidebarGroupBy = "date" | "chat_status"; export type AgentSourceFilter = (typeof AGENT_SOURCE_ORDER)[number]; @@ -26,6 +25,9 @@ export type AgentSidebarFilters = Readonly<{ groupBy: AgentSidebarGroupBy; prStatuses: readonly AgentPRStatusFilter[]; chatStatuses: readonly AgentChatStatusFilter[]; + // Unread is not a chat status. It narrows the selected statuses + // to conversations with an unread assistant message. + unread: boolean; sources: readonly AgentSourceFilter[]; }>; @@ -39,6 +41,7 @@ export const DEFAULT_AGENT_SIDEBAR_FILTERS: AgentSidebarFilters = { groupBy: "date", prStatuses: [], chatStatuses: AGENT_CHAT_STATUS_ORDER, + unread: false, sources: ["created_by_me"], }; @@ -47,6 +50,7 @@ const clearSidebarFilterParams = (searchParams: URLSearchParams) => { searchParams.delete("group_by"); searchParams.delete("pr_status"); searchParams.delete("chat_status"); + searchParams.delete("unread"); searchParams.delete("source"); }; @@ -68,8 +72,18 @@ const writeSidebarFilters = ( searchParams.set("pr_status", filters.prStatuses.join(",")); } - if (filters.chatStatuses.length === 1) { - searchParams.set("chat_status", filters.chatStatuses[0]); + const selectedChatStatuses = AGENT_CHAT_STATUS_ORDER.filter((status) => + filters.chatStatuses.includes(status), + ); + if ( + selectedChatStatuses.length > 0 && + selectedChatStatuses.length < AGENT_CHAT_STATUS_ORDER.length + ) { + searchParams.set("chat_status", selectedChatStatuses.join(",")); + } + + if (filters.unread) { + searchParams.set("unread", "true"); } if ( @@ -114,6 +128,7 @@ export const getAgentSidebarFilters = ( chatStatuses.length > 0 ? chatStatuses : DEFAULT_AGENT_SIDEBAR_FILTERS.chatStatuses, + unread: searchParams.get("unread") === "true", sources: sources.length > 0 ? sources : DEFAULT_AGENT_SIDEBAR_FILTERS.sources, };