Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion coderd/apidoc/docs.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion coderd/apidoc/swagger.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions coderd/database/dump.sql

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP INDEX IF EXISTS idx_chat_diff_statuses_url_lower;
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- Index on LOWER(url) supports case-insensitive lookups when filtering
-- chats by their associated diff URL (e.g. a pull request URL).
CREATE INDEX idx_chat_diff_statuses_url_lower
ON chat_diff_statuses (LOWER(url))
WHERE url IS NOT NULL AND url <> '';
1 change: 1 addition & 0 deletions coderd/database/modelqueries.go
Original file line number Diff line number Diff line change
Expand Up @@ -764,6 +764,7 @@ func (q *sqlQuerier) GetAuthorizedChats(ctx context.Context, arg GetChatsParams,
arg.Archived,
arg.AfterID,
arg.LabelFilter,
arg.DiffURL,
arg.OffsetOpt,
arg.LimitOpt,
)
Expand Down
22 changes: 20 additions & 2 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions coderd/database/queries/chats.sql
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,22 @@ WHERE
WHEN sqlc.narg('label_filter')::jsonb IS NOT NULL THEN chats.labels @> sqlc.narg('label_filter')::jsonb
ELSE true
END
-- Match chats whose linked diff URL (e.g. a pull request URL)
-- equals the given value, case-insensitively. The URL may live on
-- a delegated sub-agent's diff status, so we surface the root chat
-- when any descendant matches.
AND CASE
WHEN sqlc.narg('diff_url')::text IS NOT NULL THEN EXISTS (
SELECT 1
FROM chat_diff_statuses cds
JOIN chats c2 ON c2.id = cds.chat_id
WHERE cds.url IS NOT NULL
AND cds.url <> ''
AND LOWER(cds.url) = LOWER(sqlc.narg('diff_url')::text)
AND (c2.id = chats.id OR c2.root_chat_id = chats.id)
)
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
Expand Down
1 change: 1 addition & 0 deletions coderd/database/sqlc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ sql:
api_version: APIVersion
avatar_url: AvatarURL
created_by_avatar_url: CreatedByAvatarURL
diff_url: DiffURL
dbcrypt_key: DBCryptKey
session_count_vscode: SessionCountVSCode
session_count_jetbrains: SessionCountJetBrains
Expand Down
3 changes: 2 additions & 1 deletion coderd/exp_chats.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ func (api *API) chatsByWorkspace(rw http.ResponseWriter, r *http.Request) {
// @Security CoderSessionToken
// @Tags Chats
// @Produce json
// @Param q query string false "Search query"
// @Param q query string false "Search query. Supports archived:bool and diff_url:<url> terms (quote URLs)."
// @Param label query string false "Filter by label as key:value. Repeat for multiple (AND logic)."
// @Success 200 {array} codersdk.Chat
// @Router /api/experimental/chats [get]
Expand Down Expand Up @@ -368,6 +368,7 @@ func (api *API) listChats(rw http.ResponseWriter, r *http.Request) {
Archived: searchParams.Archived,
AfterID: paginationParams.AfterID,
LabelFilter: labelFilter,
DiffURL: searchParams.DiffURL,
// #nosec G115 - Pagination offsets are small and fit in int32
OffsetOpt: int32(paginationParams.Offset),
// #nosec G115 - Pagination limits are small and fit in int32
Expand Down
130 changes: 130 additions & 0 deletions coderd/exp_chats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1409,6 +1409,136 @@ func TestListChats(t *testing.T) {
require.Len(t, c.Children, 2, "each root should embed its 2 children")
}
})

t.Run("DiffURLFilter", func(t *testing.T) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 [DEREM-2] No E2E test for archived + diff_url composition at the SQL layer. The parser test DiffURLWithArchived proves both fields populate GetChatsParams, but the SQL query has two independent AND CASE clauses whose interaction is never tested against the database. Every chat in the DiffURLFilter fixture is unarchived.

If one chat were archived with a matching diff URL, the default query (archived:false) should exclude it, and archived:true diff_url:"..." should surface it. Neither path is tested. Sketch: archive rootWithPR, then assert the filter excludes it by default and includes it when archived:true is explicit.

(Bisky)

🤖

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in c182a93. Added an archived fixture chat with its own diff URL plus two subtests: ArchivedFilteredOut confirms the default archived:false excludes it, and ArchivedTrueComposes confirms archived:true diff_url:"..." surfaces it.

t.Parallel()

ctx := testutil.Context(t, testutil.WaitLong)
client, db := newChatClientWithDatabase(t)
user := coderdtest.CreateFirstUser(t, client.Client)
modelConfig := createChatModelConfig(t, client)

// Helper that creates a chat (root or child) with a diff status URL.
create := func(title, url string, parentID uuid.NullUUID) database.Chat {
rootID := parentID
chat := dbgen.Chat(t, db, database.Chat{
OrganizationID: user.OrganizationID,
OwnerID: user.UserID,
LastModelConfigID: modelConfig.ID,
Title: title,
ParentChatID: parentID,
RootChatID: rootID,
})
if url != "" {
staleAt := time.Now().UTC().Add(time.Hour).Truncate(time.Second)
_, err := db.UpsertChatDiffStatusReference(
dbauthz.AsSystemRestricted(ctx),
database.UpsertChatDiffStatusReferenceParams{
ChatID: chat.ID,
Url: sql.NullString{String: url, Valid: true},
GitBranch: "feature/test",
GitRemoteOrigin: "git@github.com:coder/coder.git",
StaleAt: staleAt,
},
)
require.NoError(t, err)
}
return chat
}

// Root chat directly linked to the target PR.
rootWithPR := create("root with pr", "https://github.com/coder/coder/pull/1", uuid.NullUUID{})

// Root chat whose sub-agent owns the PR. The filter should still
// surface the parent because the URL lives on a descendant.
rootWithChildPR := create("root with child pr", "", uuid.NullUUID{})
_ = create(
"sub-agent with pr",
"https://github.com/coder/coder/pull/2",
uuid.NullUUID{UUID: rootWithChildPR.ID, Valid: true},
)

// Root chat with an unrelated PR; should not match either filter.
_ = create("unrelated pr", "https://github.com/coder/coder/pull/999", uuid.NullUUID{})

// Root chat with no diff status at all.
_ = create("no diff", "", uuid.NullUUID{})

// Archived root chat that points at the same URL as `rootWithPR`.
// Used to verify the archived filter and the diff_url filter
// compose at the SQL layer rather than ignoring each other.
archivedWithPR := create(
"archived with pr",
"https://github.com/coder/coder/pull/3",
uuid.NullUUID{},
)
require.NoError(t, client.UpdateChat(ctx, archivedWithPR.ID, codersdk.UpdateChatRequest{
Archived: ptr.Ref(true),
}))

t.Run("MatchesRoot", func(t *testing.T) {
chats, err := client.ListChats(ctx, &codersdk.ListChatsOptions{
Query: `diff_url:"https://github.com/coder/coder/pull/1"`,
})
require.NoError(t, err)
require.Len(t, chats, 1)
require.Equal(t, rootWithPR.ID, chats[0].ID)
})

t.Run("MatchesViaSubAgent", func(t *testing.T) {
chats, err := client.ListChats(ctx, &codersdk.ListChatsOptions{
Query: `diff_url:"https://github.com/coder/coder/pull/2"`,
})
require.NoError(t, err)
require.Len(t, chats, 1, "root chat should surface even when only a child has the PR")
require.Equal(t, rootWithChildPR.ID, chats[0].ID)
})

t.Run("CaseInsensitive", func(t *testing.T) {
chats, err := client.ListChats(ctx, &codersdk.ListChatsOptions{
Query: `diff_url:"HTTPS://GITHUB.COM/CODER/CODER/PULL/1"`,
})
require.NoError(t, err)
require.Len(t, chats, 1)
require.Equal(t, rootWithPR.ID, chats[0].ID)
})

t.Run("NoMatch", func(t *testing.T) {
chats, err := client.ListChats(ctx, &codersdk.ListChatsOptions{
Query: `diff_url:"https://github.com/coder/coder/pull/424242"`,
})
require.NoError(t, err)
require.Empty(t, chats)
})

t.Run("InvalidURL", func(t *testing.T) {
_, err := client.ListChats(ctx, &codersdk.ListChatsOptions{
Query: `diff_url:"ftp://example.com/x"`,
})
sdkErr := requireSDKError(t, err, http.StatusBadRequest)
require.NotEmpty(t, sdkErr.Validations, "expected validation error")
require.Equal(t, "diff_url", sdkErr.Validations[0].Field)
})

t.Run("ArchivedFilteredOut", func(t *testing.T) {
// Default archived filter is false, so an archived chat with
// a matching diff URL must not surface.
chats, err := client.ListChats(ctx, &codersdk.ListChatsOptions{
Query: `diff_url:"https://github.com/coder/coder/pull/3"`,
})
require.NoError(t, err)
require.Empty(t, chats, "archived chat must not match the default filter")
})

t.Run("ArchivedTrueComposes", func(t *testing.T) {
chats, err := client.ListChats(ctx, &codersdk.ListChatsOptions{
Query: `archived:true diff_url:"https://github.com/coder/coder/pull/3"`,
})
require.NoError(t, err)
require.Len(t, chats, 1)
require.Equal(t, archivedWithPR.ID, chats[0].ID)
})
})
}

func TestListChatModels(t *testing.T) {
Expand Down
36 changes: 34 additions & 2 deletions coderd/searchquery/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,9 @@ func Tasks(ctx context.Context, db database.Store, query string, actorID uuid.UU
//
// Supported query parameters:
// - archived: boolean (default: false, excludes archived chats unless explicitly set)
// - diff_url: string (matches chats whose linked diff URL equals the
// given value, case-insensitively; URLs typically contain ':' so
// they must be quoted, e.g. q=diff_url:"https://github.com/o/r/pull/1")
func Chats(query string) (database.GetChatsParams, []codersdk.ValidationError) {
filter := database.GetChatsParams{
// Default to hiding archived chats.
Expand All @@ -554,8 +557,10 @@ func Chats(query string) (database.GetChatsParams, []codersdk.ValidationError) {
return filter, nil
}

// Always lowercase for all searches.
query = strings.ToLower(query)
// Lowercase the keys so they match regardless of how the caller
// types them, but preserve value casing because some filters
// (e.g. diff_url) may include URL path segments where case is
// meaningful.
values, errors := searchTerms(query, func(term string, _ url.Values) error {
return xerrors.Errorf("unsupported search term: %q", term)
})
Expand All @@ -565,11 +570,38 @@ func Chats(query string) (database.GetChatsParams, []codersdk.ValidationError) {

parser := httpapi.NewQueryParamParser()
filter.Archived = parser.NullableBoolean(values, filter.Archived, "archived")
if diffURL := parser.String(values, "", "diff_url"); diffURL != "" {
if err := validateDiffURL(diffURL); err != nil {
parser.Errors = append(parser.Errors, codersdk.ValidationError{
Field: "diff_url",
Detail: err.Error(),
})
} else {
filter.DiffURL = sql.NullString{String: diffURL, Valid: true}
}
}

parser.ErrorExcessParams(values)
return filter, parser.Errors
}

// validateDiffURL checks that the value is a syntactically valid HTTP(S)
// URL. The check is intentionally forge-agnostic because the diff URL on
// a chat may point to a pull request, merge request, branch page, etc.
func validateDiffURL(raw string) error {
u, err := url.Parse(raw)
if err != nil {
return xerrors.Errorf("diff_url is not a valid URL: %w", err)
}
if u.Scheme != "http" && u.Scheme != "https" {
return xerrors.Errorf("diff_url must use http or https scheme, got %q", u.Scheme)
}
if u.Host == "" {
return xerrors.New("diff_url must include a host")
}
return nil
}

func searchTerms(query string, defaultKey func(term string, values url.Values) error) (url.Values, []codersdk.ValidationError) {
searchValues := make(url.Values)

Expand Down
Loading
Loading