Skip to content

Commit 63e08e2

Browse files
feat(coderd): steer queued messages on Send now (#31156)
"Send now" on a queued message (`POST /api/v2/chats/{chat}/queue/{queuedMessage}/promote`) now just moves it to the end of the steer lane. It never interrupts the chat, so it can't cancel the step that would have answered it. The endpoint's request doesn't change. Before, it moved the message to the head of the queue with `MIN(position) - 1`, so if you pressed "Send now" on two messages, the second one went first. With a queue of `Q1 Q2 Q3 S4`, "Send now" on `Q1` then `Q3` now delivers `S4 Q1 Q3`, and `Q2` keeps waiting. If the chat has errored or is paused, the steer lane goes in straight away, like a send. Otherwise it goes in at the next delivery point: before the next model call, when the turn ends, or when an interrupt finishes. Stop is the only thing that interrupts. "Send now" and "Remove" on a message that's already been delivered now return a 404 instead of a 409, the same as editing one, and "Remove" on an archived chat returns a 400. In chatstate, `SteerQueuedMessage` replaces `PromoteQueuedMessage`. It moves the message to the end of the steer lane, and on an errored or paused chat it also delivers the steer lane and resumes the chat, like a send does. The `SteerChatQueuedMessage` query sets `position = nextval(...)` and replaces `ReorderChatQueuedMessageToHead`. Most of the diff is tests. #31174 then makes `steer` the API default and removes `interrupt` as a busy behaviour, #31175 makes `message_agent` always steer, and #31173 updates the site. Part of CODAGT-1140
1 parent 5138fa3 commit 63e08e2

24 files changed

Lines changed: 667 additions & 673 deletions

‎coderd/database/dbauthz/dbauthz.go‎

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7669,18 +7669,6 @@ func (q *querier) ReorderChatQueuedMessageToFront(ctx context.Context, arg datab
76697669
return q.db.ReorderChatQueuedMessageToFront(ctx, arg)
76707670
}
76717671

7672-
func (q *querier) ReorderChatQueuedMessageToHead(ctx context.Context, arg database.ReorderChatQueuedMessageToHeadParams) (int64, error) {
7673-
chat, err := q.db.GetChatByID(ctx, arg.ChatID)
7674-
if err != nil {
7675-
return 0, err
7676-
}
7677-
if err := q.authorizeContext(ctx, policy.ActionUpdate, chat); err != nil {
7678-
return 0, err
7679-
}
7680-
_ = chat
7681-
return q.db.ReorderChatQueuedMessageToHead(ctx, arg)
7682-
}
7683-
76847672
func (q *querier) RevokeDBCryptKey(ctx context.Context, activeKeyDigest string) error {
76857673
if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceSystem); err != nil {
76867674
return err
@@ -7771,6 +7759,17 @@ func (q *querier) SoftDeleteWorkspaceAgentsByWorkspaceID(ctx context.Context, wo
77717759
return q.db.SoftDeleteWorkspaceAgentsByWorkspaceID(ctx, workspaceID)
77727760
}
77737761

7762+
func (q *querier) SteerChatQueuedMessage(ctx context.Context, arg database.SteerChatQueuedMessageParams) (int64, error) {
7763+
chat, err := q.db.GetChatByID(ctx, arg.ChatID)
7764+
if err != nil {
7765+
return 0, err
7766+
}
7767+
if err := q.authorizeContext(ctx, policy.ActionUpdate, chat); err != nil {
7768+
return 0, err
7769+
}
7770+
return q.db.SteerChatQueuedMessage(ctx, arg)
7771+
}
7772+
77747773
func (q *querier) SyncAgentChatsContextLiveResources(ctx context.Context, agentID uuid.UUID) ([]uuid.UUID, error) {
77757774
// The push can update multiple chats bound to the agent, so authorize the
77767775
// chat resource class.

‎coderd/database/dbauthz/dbauthz_test.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1775,11 +1775,11 @@ func (s *MethodTestSuite) TestChats() {
17751775
dbm.EXPECT().DeleteAllChatQueuedMessagesReturningCount(gomock.Any(), chat.ID).Return(int64(1), nil).AnyTimes()
17761776
check.Args(chat.ID).Asserts(chat, policy.ActionUpdate).Returns(int64(1))
17771777
}))
1778-
s.Run("ReorderChatQueuedMessageToHead", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) {
1778+
s.Run("SteerChatQueuedMessage", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) {
17791779
chat := testutil.Fake(s.T(), faker, database.Chat{})
1780-
arg := database.ReorderChatQueuedMessageToHeadParams{ChatID: chat.ID, ID: 1}
1780+
arg := database.SteerChatQueuedMessageParams{ChatID: chat.ID, ID: 1}
17811781
dbm.EXPECT().GetChatByID(gomock.Any(), chat.ID).Return(chat, nil).AnyTimes()
1782-
dbm.EXPECT().ReorderChatQueuedMessageToHead(gomock.Any(), arg).Return(int64(1), nil).AnyTimes()
1782+
dbm.EXPECT().SteerChatQueuedMessage(gomock.Any(), arg).Return(int64(1), nil).AnyTimes()
17831783
check.Args(arg).Asserts(chat, policy.ActionUpdate).Returns(int64(1))
17841784
}))
17851785
s.Run("UpdateChatQueuedMessageEditing", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) {

‎coderd/database/dbmetrics/querymetrics.go‎

Lines changed: 8 additions & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎coderd/database/dbmock/dbmock.go‎

Lines changed: 15 additions & 15 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎coderd/database/querier.go‎

Lines changed: 1 addition & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎coderd/database/queries.sql.go‎

Lines changed: 21 additions & 29 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎coderd/database/queries/chats.sql‎

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3044,20 +3044,12 @@ SET content = @content::jsonb,
30443044
WHERE id = @id::bigint AND chat_id = @chat_id::uuid
30453045
RETURNING *;
30463046

3047-
-- name: ReorderChatQueuedMessageToHead :execrows
3048-
-- Sets the target queued message's position to one less than the
3049-
-- current minimum position for that chat, moving it to the head.
3050-
UPDATE chat_queued_messages AS target
3051-
SET position = COALESCE(
3052-
(SELECT MIN(position) FROM chat_queued_messages WHERE chat_id = @chat_id::uuid),
3053-
0
3054-
) - 1
3055-
WHERE target.id = @id::bigint
3056-
AND target.chat_id = @chat_id::uuid
3057-
AND target.position > COALESCE(
3058-
(SELECT MIN(position) FROM chat_queued_messages WHERE chat_id = @chat_id::uuid),
3059-
target.position
3060-
);
3047+
-- name: SteerChatQueuedMessage :execrows
3048+
UPDATE chat_queued_messages
3049+
SET position = nextval('chat_queued_messages_position_seq'),
3050+
busy_behavior = 'steer'
3051+
WHERE id = @id::bigint
3052+
AND chat_id = @chat_id::uuid;
30613053

30623054
-- name: UpsertChatHeartbeat :exec
30633055
-- Upserts a heartbeat row for the (chat_id, runner_id) lease. Uses

‎coderd/exp_chats.go‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3608,6 +3608,10 @@ func (api *API) deleteChatQueuedMessage(rw http.ResponseWriter, r *http.Request)
36083608
err = api.chatDaemon.DeleteQueued(ctx, chatID, queuedMessageID)
36093609
if err != nil {
36103610
switch {
3611+
case xerrors.Is(err, chatd.ErrChatArchived):
3612+
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
3613+
Message: "Cannot delete queued messages in an archived chat.",
3614+
})
36113615
case xerrors.Is(err, chatstate.ErrQueuedMessageNotFound), xerrors.Is(err, sql.ErrNoRows):
36123616
httpapi.Write(ctx, rw, http.StatusNotFound, codersdk.Response{
36133617
Message: "Queued message not found.",
@@ -3620,7 +3624,7 @@ func (api *API) deleteChatQueuedMessage(rw http.ResponseWriter, r *http.Request)
36203624
// response already written
36213625
case errors.Is(err, chatstate.ErrTransitionNotAllowed):
36223626
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
3623-
Message: "Chat has no queued messages to delete.",
3627+
Message: "Cannot delete this queued message in the chat's current state.",
36243628
Detail: err.Error(),
36253629
})
36263630
default:
@@ -3687,7 +3691,7 @@ func (api *API) promoteChatQueuedMessage(rw http.ResponseWriter, r *http.Request
36873691
return
36883692
}
36893693

3690-
_, txErr := api.chatDaemon.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
3694+
txErr := api.chatDaemon.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
36913695
ChatID: chatID,
36923696
QueuedMessageID: queuedMessageID,
36933697
})
@@ -3710,7 +3714,7 @@ func (api *API) promoteChatQueuedMessage(rw http.ResponseWriter, r *http.Request
37103714
// response already written
37113715
case errors.Is(txErr, chatstate.ErrTransitionNotAllowed):
37123716
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
3713-
Message: "Chat has no queued messages to promote.",
3717+
Message: "Cannot promote this queued message in the chat's current state.",
37143718
Detail: txErr.Error(),
37153719
})
37163720
default:
@@ -3844,9 +3848,7 @@ func (api *API) patchChatQueuedMessage(rw http.ResponseWriter, r *http.Request)
38443848
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
38453849
Message: "Cannot edit queued messages in an archived chat.",
38463850
})
3847-
case errors.Is(err, chatstate.ErrQueuedMessageNotFound), errors.Is(err, chatstate.ErrTransitionNotAllowed):
3848-
// Every unarchived, valid state that refuses EditQueuedMessage
3849-
// has an empty queue, so the row no longer exists.
3851+
case errors.Is(err, chatstate.ErrQueuedMessageNotFound):
38503852
httpapi.Write(ctx, rw, http.StatusNotFound, codersdk.Response{
38513853
Message: "Queued message not found.",
38523854
})
@@ -3860,6 +3862,11 @@ func (api *API) patchChatQueuedMessage(rw http.ResponseWriter, r *http.Request)
38603862
httpapi.ResourceNotFound(rw)
38613863
case writeChatInvalidState(ctx, rw, err):
38623864
// response already written
3865+
case errors.Is(err, chatstate.ErrTransitionNotAllowed):
3866+
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
3867+
Message: "Cannot edit this queued message in the chat's current state.",
3868+
Detail: err.Error(),
3869+
})
38633870
case errors.Is(err, chatstate.ErrPausedQueuedHeadUnderEdit):
38643871
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
38653872
Message: "The chat is paused at a queued message under edit. Finish editing, send, or remove it before editing another.",

‎coderd/exp_chats_chatstate_test.go‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -264,9 +264,9 @@ func TestChatQueueEndpointErrors(t *testing.T) {
264264
wantStatus int
265265
}{
266266
{name: "DeleteMissingReturns404", method: http.MethodDelete, queueFirst: true, wantStatus: http.StatusNotFound},
267-
{name: "DeleteEmptyQueueReturnsConflict", method: http.MethodDelete, wantStatus: http.StatusConflict},
267+
{name: "DeleteEmptyQueueReturns404", method: http.MethodDelete, wantStatus: http.StatusNotFound},
268268
{name: "PromoteMissingReturns404", method: http.MethodPost, pathSuffix: "/promote", queueFirst: true, wantStatus: http.StatusNotFound},
269-
{name: "PromoteEmptyQueueReturnsConflict", method: http.MethodPost, pathSuffix: "/promote", wantStatus: http.StatusConflict},
269+
{name: "PromoteEmptyQueueReturns404", method: http.MethodPost, pathSuffix: "/promote", wantStatus: http.StatusNotFound},
270270
} {
271271
t.Run(tc.name, func(t *testing.T) {
272272
t.Parallel()
@@ -277,18 +277,28 @@ func TestChatQueueEndpointErrors(t *testing.T) {
277277
Content: []codersdk.ChatInputPart{{Type: codersdk.ChatInputPartTypeText, Text: "hello"}},
278278
})
279279
require.NoError(t, err)
280+
var queued *codersdk.ChatQueuedMessage
280281
if tc.queueFirst {
281-
_, err = client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
282+
sent, err := client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
282283
Content: []codersdk.ChatInputPart{{Type: codersdk.ChatInputPartTypeText, Text: "queued"}},
283284
BusyBehavior: codersdk.ChatBusyBehaviorQueue,
284285
})
285286
require.NoError(t, err)
287+
require.NotNil(t, sent.QueuedMessage)
288+
queued = sent.QueuedMessage
286289
}
287290

288291
res, err := client.Request(ctx, tc.method, fmt.Sprintf("/api/v2/chats/%s/queue/99999999%s", chat.ID, tc.pathSuffix), nil)
289292
require.NoError(t, err)
290293
defer res.Body.Close()
291294
require.Equal(t, tc.wantStatus, res.StatusCode)
295+
296+
if queued != nil {
297+
got, err := client.GetChatMessages(ctx, chat.ID, nil)
298+
require.NoError(t, err)
299+
require.Len(t, got.QueuedMessages, 1)
300+
require.Equal(t, queued.ID, got.QueuedMessages[0].ID)
301+
}
292302
})
293303
}
294304
}

0 commit comments

Comments
 (0)