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
This commit is contained in:
1 parent
5138fa300f
commit
63e08e231e
24 files changed
+667
-673
No files matched your search
@@ -7669,18 +7669,6 @@ func (q *querier) ReorderChatQueuedMessageToFront(ctx context.Context, arg datab
|
||||
return q.db.ReorderChatQueuedMessageToFront(ctx, arg)
|
||||
}
|
||||
|
||||
func (q *querier) ReorderChatQueuedMessageToHead(ctx context.Context, arg database.ReorderChatQueuedMessageToHeadParams) (int64, error) {
|
||||
chat, err := q.db.GetChatByID(ctx, arg.ChatID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := q.authorizeContext(ctx, policy.ActionUpdate, chat); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
_ = chat
|
||||
return q.db.ReorderChatQueuedMessageToHead(ctx, arg)
|
||||
}
|
||||
|
||||
func (q *querier) RevokeDBCryptKey(ctx context.Context, activeKeyDigest string) error {
|
||||
if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceSystem); err != nil {
|
||||
return err
|
||||
@@ -7771,6 +7759,17 @@ func (q *querier) SoftDeleteWorkspaceAgentsByWorkspaceID(ctx context.Context, wo
|
||||
return q.db.SoftDeleteWorkspaceAgentsByWorkspaceID(ctx, workspaceID)
|
||||
}
|
||||
|
||||
func (q *querier) SteerChatQueuedMessage(ctx context.Context, arg database.SteerChatQueuedMessageParams) (int64, error) {
|
||||
chat, err := q.db.GetChatByID(ctx, arg.ChatID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := q.authorizeContext(ctx, policy.ActionUpdate, chat); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return q.db.SteerChatQueuedMessage(ctx, arg)
|
||||
}
|
||||
|
||||
func (q *querier) SyncAgentChatsContextLiveResources(ctx context.Context, agentID uuid.UUID) ([]uuid.UUID, error) {
|
||||
// The push can update multiple chats bound to the agent, so authorize the
|
||||
// chat resource class.
|
||||
|
||||
@@ -1775,11 +1775,11 @@ func (s *MethodTestSuite) TestChats() {
|
||||
dbm.EXPECT().DeleteAllChatQueuedMessagesReturningCount(gomock.Any(), chat.ID).Return(int64(1), nil).AnyTimes()
|
||||
check.Args(chat.ID).Asserts(chat, policy.ActionUpdate).Returns(int64(1))
|
||||
}))
|
||||
s.Run("ReorderChatQueuedMessageToHead", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) {
|
||||
s.Run("SteerChatQueuedMessage", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) {
|
||||
chat := testutil.Fake(s.T(), faker, database.Chat{})
|
||||
arg := database.ReorderChatQueuedMessageToHeadParams{ChatID: chat.ID, ID: 1}
|
||||
arg := database.SteerChatQueuedMessageParams{ChatID: chat.ID, ID: 1}
|
||||
dbm.EXPECT().GetChatByID(gomock.Any(), chat.ID).Return(chat, nil).AnyTimes()
|
||||
dbm.EXPECT().ReorderChatQueuedMessageToHead(gomock.Any(), arg).Return(int64(1), nil).AnyTimes()
|
||||
dbm.EXPECT().SteerChatQueuedMessage(gomock.Any(), arg).Return(int64(1), nil).AnyTimes()
|
||||
check.Args(arg).Asserts(chat, policy.ActionUpdate).Returns(int64(1))
|
||||
}))
|
||||
s.Run("UpdateChatQueuedMessageEditing", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) {
|
||||
|
||||
+8
-8
@@ -5456,14 +5456,6 @@ func (m queryMetricsStore) ReorderChatQueuedMessageToFront(ctx context.Context,
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
func (m queryMetricsStore) ReorderChatQueuedMessageToHead(ctx context.Context, arg database.ReorderChatQueuedMessageToHeadParams) (int64, error) {
|
||||
start := time.Now()
|
||||
r0, r1 := m.s.ReorderChatQueuedMessageToHead(ctx, arg)
|
||||
m.queryLatencies.WithLabelValues("ReorderChatQueuedMessageToHead").Observe(time.Since(start).Seconds())
|
||||
m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "ReorderChatQueuedMessageToHead").Inc()
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
func (m queryMetricsStore) RevokeDBCryptKey(ctx context.Context, activeKeyDigest string) error {
|
||||
start := time.Now()
|
||||
r0 := m.s.RevokeDBCryptKey(ctx, activeKeyDigest)
|
||||
@@ -5536,6 +5528,14 @@ func (m queryMetricsStore) SoftDeleteWorkspaceAgentsByWorkspaceID(ctx context.Co
|
||||
return r0
|
||||
}
|
||||
|
||||
func (m queryMetricsStore) SteerChatQueuedMessage(ctx context.Context, arg database.SteerChatQueuedMessageParams) (int64, error) {
|
||||
start := time.Now()
|
||||
r0, r1 := m.s.SteerChatQueuedMessage(ctx, arg)
|
||||
m.queryLatencies.WithLabelValues("SteerChatQueuedMessage").Observe(time.Since(start).Seconds())
|
||||
m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "SteerChatQueuedMessage").Inc()
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
func (m queryMetricsStore) SyncAgentChatsContextLiveResources(ctx context.Context, agentID uuid.UUID) ([]uuid.UUID, error) {
|
||||
start := time.Now()
|
||||
r0, r1 := m.s.SyncAgentChatsContextLiveResources(ctx, agentID)
|
||||
|
||||
Generated
+15
-15
@@ -10366,21 +10366,6 @@ func (mr *MockStoreMockRecorder) ReorderChatQueuedMessageToFront(ctx, arg any) *
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReorderChatQueuedMessageToFront", reflect.TypeOf((*MockStore)(nil).ReorderChatQueuedMessageToFront), ctx, arg)
|
||||
}
|
||||
|
||||
// ReorderChatQueuedMessageToHead mocks base method.
|
||||
func (m *MockStore) ReorderChatQueuedMessageToHead(ctx context.Context, arg database.ReorderChatQueuedMessageToHeadParams) (int64, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "ReorderChatQueuedMessageToHead", ctx, arg)
|
||||
ret0, _ := ret[0].(int64)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// ReorderChatQueuedMessageToHead indicates an expected call of ReorderChatQueuedMessageToHead.
|
||||
func (mr *MockStoreMockRecorder) ReorderChatQueuedMessageToHead(ctx, arg any) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReorderChatQueuedMessageToHead", reflect.TypeOf((*MockStore)(nil).ReorderChatQueuedMessageToHead), ctx, arg)
|
||||
}
|
||||
|
||||
// RevokeDBCryptKey mocks base method.
|
||||
func (m *MockStore) RevokeDBCryptKey(ctx context.Context, activeKeyDigest string) error {
|
||||
m.ctrl.T.Helper()
|
||||
@@ -10508,6 +10493,21 @@ func (mr *MockStoreMockRecorder) SoftDeleteWorkspaceAgentsByWorkspaceID(ctx, wor
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SoftDeleteWorkspaceAgentsByWorkspaceID", reflect.TypeOf((*MockStore)(nil).SoftDeleteWorkspaceAgentsByWorkspaceID), ctx, workspaceID)
|
||||
}
|
||||
|
||||
// SteerChatQueuedMessage mocks base method.
|
||||
func (m *MockStore) SteerChatQueuedMessage(ctx context.Context, arg database.SteerChatQueuedMessageParams) (int64, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "SteerChatQueuedMessage", ctx, arg)
|
||||
ret0, _ := ret[0].(int64)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// SteerChatQueuedMessage indicates an expected call of SteerChatQueuedMessage.
|
||||
func (mr *MockStoreMockRecorder) SteerChatQueuedMessage(ctx, arg any) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SteerChatQueuedMessage", reflect.TypeOf((*MockStore)(nil).SteerChatQueuedMessage), ctx, arg)
|
||||
}
|
||||
|
||||
// SyncAgentChatsContextLiveResources mocks base method.
|
||||
func (m *MockStore) SyncAgentChatsContextLiveResources(ctx context.Context, agentID uuid.UUID) ([]uuid.UUID, error) {
|
||||
m.ctrl.T.Helper()
|
||||
|
||||
Generated
+1
-3
@@ -1510,9 +1510,6 @@ type sqlcQuerier interface {
|
||||
// Mutates only created_at on the target row; ids are unchanged so
|
||||
// consumers can keep tracking queued messages by id.
|
||||
ReorderChatQueuedMessageToFront(ctx context.Context, arg ReorderChatQueuedMessageToFrontParams) (int64, error)
|
||||
// Sets the target queued message's position to one less than the
|
||||
// current minimum position for that chat, moving it to the head.
|
||||
ReorderChatQueuedMessageToHead(ctx context.Context, arg ReorderChatQueuedMessageToHeadParams) (int64, error)
|
||||
RevokeDBCryptKey(ctx context.Context, activeKeyDigest string) error
|
||||
// Note that this selects from the CTE, not the original table. The CTE is named
|
||||
// the same as the original table to trick sqlc into reusing the existing struct
|
||||
@@ -1551,6 +1548,7 @@ type sqlcQuerier interface {
|
||||
// Agent context rows are hard-deleted for the same reason as in
|
||||
// SoftDeletePriorWorkspaceAgents.
|
||||
SoftDeleteWorkspaceAgentsByWorkspaceID(ctx context.Context, workspaceID uuid.UUID) error
|
||||
SteerChatQueuedMessage(ctx context.Context, arg SteerChatQueuedMessageParams) (int64, error)
|
||||
// MCP and ACP resources bypass context drift and are live-synced on each push.
|
||||
// Changed chats are locked in ID order so concurrent clear-then-copy re-pins
|
||||
// cannot interleave with the replacement.
|
||||
|
||||
Generated
+21
-29
@@ -13375,35 +13375,6 @@ func (q *sqlQuerier) ReorderChatQueuedMessageToFront(ctx context.Context, arg Re
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const reorderChatQueuedMessageToHead = `-- name: ReorderChatQueuedMessageToHead :execrows
|
||||
UPDATE chat_queued_messages AS target
|
||||
SET position = COALESCE(
|
||||
(SELECT MIN(position) FROM chat_queued_messages WHERE chat_id = $1::uuid),
|
||||
0
|
||||
) - 1
|
||||
WHERE target.id = $2::bigint
|
||||
AND target.chat_id = $1::uuid
|
||||
AND target.position > COALESCE(
|
||||
(SELECT MIN(position) FROM chat_queued_messages WHERE chat_id = $1::uuid),
|
||||
target.position
|
||||
)
|
||||
`
|
||||
|
||||
type ReorderChatQueuedMessageToHeadParams struct {
|
||||
ChatID uuid.UUID `db:"chat_id" json:"chat_id"`
|
||||
ID int64 `db:"id" json:"id"`
|
||||
}
|
||||
|
||||
// Sets the target queued message's position to one less than the
|
||||
// current minimum position for that chat, moving it to the head.
|
||||
func (q *sqlQuerier) ReorderChatQueuedMessageToHead(ctx context.Context, arg ReorderChatQueuedMessageToHeadParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, reorderChatQueuedMessageToHead, arg.ChatID, arg.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const setChatContextSnapshot = `-- name: SetChatContextSnapshot :exec
|
||||
UPDATE chats
|
||||
SET
|
||||
@@ -13474,6 +13445,27 @@ func (q *sqlQuerier) SoftDeleteContextFileMessages(ctx context.Context, chatID u
|
||||
return err
|
||||
}
|
||||
|
||||
const steerChatQueuedMessage = `-- name: SteerChatQueuedMessage :execrows
|
||||
UPDATE chat_queued_messages
|
||||
SET position = nextval('chat_queued_messages_position_seq'),
|
||||
busy_behavior = 'steer'
|
||||
WHERE id = $1::bigint
|
||||
AND chat_id = $2::uuid
|
||||
`
|
||||
|
||||
type SteerChatQueuedMessageParams struct {
|
||||
ID int64 `db:"id" json:"id"`
|
||||
ChatID uuid.UUID `db:"chat_id" json:"chat_id"`
|
||||
}
|
||||
|
||||
func (q *sqlQuerier) SteerChatQueuedMessage(ctx context.Context, arg SteerChatQueuedMessageParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, steerChatQueuedMessage, arg.ID, arg.ChatID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const syncAgentChatsContextLiveResources = `-- name: SyncAgentChatsContextLiveResources :many
|
||||
WITH agent_live AS (
|
||||
SELECT source, body_kind, body, content_hash, size_bytes, status, error, source_path
|
||||
|
||||
@@ -3044,20 +3044,12 @@ SET content = @content::jsonb,
|
||||
WHERE id = @id::bigint AND chat_id = @chat_id::uuid
|
||||
RETURNING *;
|
||||
|
||||
-- name: ReorderChatQueuedMessageToHead :execrows
|
||||
-- Sets the target queued message's position to one less than the
|
||||
-- current minimum position for that chat, moving it to the head.
|
||||
UPDATE chat_queued_messages AS target
|
||||
SET position = COALESCE(
|
||||
(SELECT MIN(position) FROM chat_queued_messages WHERE chat_id = @chat_id::uuid),
|
||||
0
|
||||
) - 1
|
||||
WHERE target.id = @id::bigint
|
||||
AND target.chat_id = @chat_id::uuid
|
||||
AND target.position > COALESCE(
|
||||
(SELECT MIN(position) FROM chat_queued_messages WHERE chat_id = @chat_id::uuid),
|
||||
target.position
|
||||
);
|
||||
-- name: SteerChatQueuedMessage :execrows
|
||||
UPDATE chat_queued_messages
|
||||
SET position = nextval('chat_queued_messages_position_seq'),
|
||||
busy_behavior = 'steer'
|
||||
WHERE id = @id::bigint
|
||||
AND chat_id = @chat_id::uuid;
|
||||
|
||||
-- name: UpsertChatHeartbeat :exec
|
||||
-- Upserts a heartbeat row for the (chat_id, runner_id) lease. Uses
|
||||
|
||||
+13
-6
@@ -3608,6 +3608,10 @@ func (api *API) deleteChatQueuedMessage(rw http.ResponseWriter, r *http.Request)
|
||||
err = api.chatDaemon.DeleteQueued(ctx, chatID, queuedMessageID)
|
||||
if err != nil {
|
||||
switch {
|
||||
case xerrors.Is(err, chatd.ErrChatArchived):
|
||||
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
||||
Message: "Cannot delete queued messages in an archived chat.",
|
||||
})
|
||||
case xerrors.Is(err, chatstate.ErrQueuedMessageNotFound), xerrors.Is(err, sql.ErrNoRows):
|
||||
httpapi.Write(ctx, rw, http.StatusNotFound, codersdk.Response{
|
||||
Message: "Queued message not found.",
|
||||
@@ -3620,7 +3624,7 @@ func (api *API) deleteChatQueuedMessage(rw http.ResponseWriter, r *http.Request)
|
||||
// response already written
|
||||
case errors.Is(err, chatstate.ErrTransitionNotAllowed):
|
||||
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
|
||||
Message: "Chat has no queued messages to delete.",
|
||||
Message: "Cannot delete this queued message in the chat's current state.",
|
||||
Detail: err.Error(),
|
||||
})
|
||||
default:
|
||||
@@ -3687,7 +3691,7 @@ func (api *API) promoteChatQueuedMessage(rw http.ResponseWriter, r *http.Request
|
||||
return
|
||||
}
|
||||
|
||||
_, txErr := api.chatDaemon.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
||||
txErr := api.chatDaemon.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
||||
ChatID: chatID,
|
||||
QueuedMessageID: queuedMessageID,
|
||||
})
|
||||
@@ -3710,7 +3714,7 @@ func (api *API) promoteChatQueuedMessage(rw http.ResponseWriter, r *http.Request
|
||||
// response already written
|
||||
case errors.Is(txErr, chatstate.ErrTransitionNotAllowed):
|
||||
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
|
||||
Message: "Chat has no queued messages to promote.",
|
||||
Message: "Cannot promote this queued message in the chat's current state.",
|
||||
Detail: txErr.Error(),
|
||||
})
|
||||
default:
|
||||
@@ -3844,9 +3848,7 @@ func (api *API) patchChatQueuedMessage(rw http.ResponseWriter, r *http.Request)
|
||||
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
|
||||
Message: "Cannot edit queued messages in an archived chat.",
|
||||
})
|
||||
case errors.Is(err, chatstate.ErrQueuedMessageNotFound), errors.Is(err, chatstate.ErrTransitionNotAllowed):
|
||||
// Every unarchived, valid state that refuses EditQueuedMessage
|
||||
// has an empty queue, so the row no longer exists.
|
||||
case errors.Is(err, chatstate.ErrQueuedMessageNotFound):
|
||||
httpapi.Write(ctx, rw, http.StatusNotFound, codersdk.Response{
|
||||
Message: "Queued message not found.",
|
||||
})
|
||||
@@ -3860,6 +3862,11 @@ func (api *API) patchChatQueuedMessage(rw http.ResponseWriter, r *http.Request)
|
||||
httpapi.ResourceNotFound(rw)
|
||||
case writeChatInvalidState(ctx, rw, err):
|
||||
// response already written
|
||||
case errors.Is(err, chatstate.ErrTransitionNotAllowed):
|
||||
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
|
||||
Message: "Cannot edit this queued message in the chat's current state.",
|
||||
Detail: err.Error(),
|
||||
})
|
||||
case errors.Is(err, chatstate.ErrPausedQueuedHeadUnderEdit):
|
||||
httpapi.Write(ctx, rw, http.StatusConflict, codersdk.Response{
|
||||
Message: "The chat is paused at a queued message under edit. Finish editing, send, or remove it before editing another.",
|
||||
|
||||
@@ -264,9 +264,9 @@ func TestChatQueueEndpointErrors(t *testing.T) {
|
||||
wantStatus int
|
||||
}{
|
||||
{name: "DeleteMissingReturns404", method: http.MethodDelete, queueFirst: true, wantStatus: http.StatusNotFound},
|
||||
{name: "DeleteEmptyQueueReturnsConflict", method: http.MethodDelete, wantStatus: http.StatusConflict},
|
||||
{name: "DeleteEmptyQueueReturns404", method: http.MethodDelete, wantStatus: http.StatusNotFound},
|
||||
{name: "PromoteMissingReturns404", method: http.MethodPost, pathSuffix: "/promote", queueFirst: true, wantStatus: http.StatusNotFound},
|
||||
{name: "PromoteEmptyQueueReturnsConflict", method: http.MethodPost, pathSuffix: "/promote", wantStatus: http.StatusConflict},
|
||||
{name: "PromoteEmptyQueueReturns404", method: http.MethodPost, pathSuffix: "/promote", wantStatus: http.StatusNotFound},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
@@ -277,18 +277,28 @@ func TestChatQueueEndpointErrors(t *testing.T) {
|
||||
Content: []codersdk.ChatInputPart{{Type: codersdk.ChatInputPartTypeText, Text: "hello"}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
var queued *codersdk.ChatQueuedMessage
|
||||
if tc.queueFirst {
|
||||
_, err = client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
|
||||
sent, err := client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
|
||||
Content: []codersdk.ChatInputPart{{Type: codersdk.ChatInputPartTypeText, Text: "queued"}},
|
||||
BusyBehavior: codersdk.ChatBusyBehaviorQueue,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, sent.QueuedMessage)
|
||||
queued = sent.QueuedMessage
|
||||
}
|
||||
|
||||
res, err := client.Request(ctx, tc.method, fmt.Sprintf("/api/v2/chats/%s/queue/99999999%s", chat.ID, tc.pathSuffix), nil)
|
||||
require.NoError(t, err)
|
||||
defer res.Body.Close()
|
||||
require.Equal(t, tc.wantStatus, res.StatusCode)
|
||||
|
||||
if queued != nil {
|
||||
got, err := client.GetChatMessages(ctx, chat.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got.QueuedMessages, 1)
|
||||
require.Equal(t, queued.ID, got.QueuedMessages[0].ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+81
-34
@@ -12851,6 +12851,40 @@ func TestDeleteChatQueuedMessage(t *testing.T) {
|
||||
require.Equal(t, "Invalid queued message ID.", sdkErr.Message)
|
||||
require.Contains(t, sdkErr.Detail, "invalid syntax")
|
||||
})
|
||||
|
||||
t.Run("ArchivedChat", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, db := newChatClientWithDatabase(t)
|
||||
user := coderdtest.CreateFirstUser(t, client.Client)
|
||||
modelConfig := createChatModel(t, client)
|
||||
|
||||
chat := dbgen.Chat(t, db, database.Chat{
|
||||
OrganizationID: user.OrganizationID,
|
||||
OwnerID: user.UserID,
|
||||
LastModelConfigID: modelConfig.ID,
|
||||
Title: "delete queued archived",
|
||||
})
|
||||
queuedContent, err := json.Marshal([]codersdk.ChatMessagePart{
|
||||
codersdk.ChatMessageText("queued"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
queuedMessage := insertTestChatQueuedMessage(ctx, t, db, chat.ID, queuedContent, chat.LastModelConfigID)
|
||||
_, err = db.ArchiveChatByID(dbauthz.AsSystemRestricted(ctx), chat.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
res, err := client.Request(
|
||||
ctx,
|
||||
http.MethodDelete,
|
||||
fmt.Sprintf("/api/v2/chats/%s/queue/%d", chat.ID, queuedMessage.ID),
|
||||
nil,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
defer res.Body.Close()
|
||||
sdkErr := requireSDKError(t, codersdk.ReadBodyAsError(res), http.StatusBadRequest)
|
||||
require.Equal(t, "Cannot delete queued messages in an archived chat.", sdkErr.Message)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPromoteChatQueuedMessage(t *testing.T) {
|
||||
@@ -13153,7 +13187,7 @@ func TestPromoteChatQueuedMessage(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
client, db := newChatClientWithDatabase(t, withChatWorkerDisabled)
|
||||
client, db, api := newChatClientWithAPIAndDatabase(t)
|
||||
user := coderdtest.CreateFirstUser(t, client.Client)
|
||||
modelConfig := createChatModel(t, client)
|
||||
|
||||
@@ -13206,9 +13240,12 @@ func TestPromoteChatQueuedMessage(t *testing.T) {
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = db.UpdateChatStatus(dbauthz.AsSystemRestricted(ctx), database.UpdateChatStatusParams{
|
||||
ID: chat.ID,
|
||||
Status: database.ChatStatusRequiresAction,
|
||||
// The worker can take over an unowned requires_action chat. A
|
||||
// missing deadline makes it cancel the pending tool call at once.
|
||||
_, err = db.UpdateChatExecutionState(dbauthz.AsSystemRestricted(ctx), database.UpdateChatExecutionStateParams{
|
||||
ID: chat.ID,
|
||||
Status: database.ChatStatusRequiresAction,
|
||||
RequiresActionDeadlineAt: sql.NullTime{Time: dbtime.Now().Add(time.Hour), Valid: true},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -13233,25 +13270,37 @@ func TestPromoteChatQueuedMessage(t *testing.T) {
|
||||
require.NoError(t, json.NewDecoder(promoteRes.Body).Decode(&resp))
|
||||
require.NotEmpty(t, resp.Message)
|
||||
|
||||
after, err := db.GetChatByID(dbauthz.AsSystemRestricted(ctx), chat.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, database.ChatStatusRequiresAction, after.Status,
|
||||
"Send now does not cancel the pending tool call")
|
||||
queued, err := db.GetChatQueuedMessages(dbauthz.AsSystemRestricted(ctx), chat.ID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, queued, 1)
|
||||
require.Equal(t, queuedMessage.ID, queued[0].ID)
|
||||
require.Equal(t, database.ChatBusyBehaviorSteer, queued[0].BusyBehavior)
|
||||
|
||||
err = client.SubmitToolResults(ctx, chat.ID, codersdk.SubmitToolResultsRequest{
|
||||
Results: []codersdk.ToolResult{{ToolCallID: pendingToolCallID, Output: json.RawMessage(`"done"`)}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
coderdtest.WaitForChatSettled(ctx, t, api, chat.ID)
|
||||
|
||||
messages, err := db.GetChatMessagesByChatID(dbauthz.AsSystemRestricted(ctx), database.GetChatMessagesByChatIDParams{
|
||||
ChatID: chat.ID,
|
||||
AfterID: 0,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
var (
|
||||
syntheticID int64
|
||||
promotedID int64
|
||||
)
|
||||
var resultID, promotedID, replyID int64
|
||||
for _, msg := range messages {
|
||||
parts, parseErr := chatprompt.ParseContent(msg)
|
||||
require.NoError(t, parseErr)
|
||||
parts, err := chatprompt.ParseContent(msg)
|
||||
require.NoError(t, err)
|
||||
for _, part := range parts {
|
||||
if msg.Role == database.ChatMessageRoleTool &&
|
||||
part.Type == codersdk.ChatMessagePartTypeToolResult &&
|
||||
part.ToolCallID == pendingToolCallID &&
|
||||
part.IsError {
|
||||
syntheticID = msg.ID
|
||||
part.ToolCallID == pendingToolCallID {
|
||||
require.False(t, part.IsError, "the submitted result is the only result")
|
||||
resultID = msg.ID
|
||||
}
|
||||
if msg.Role == database.ChatMessageRoleUser &&
|
||||
part.Type == codersdk.ChatMessagePartTypeText &&
|
||||
@@ -13259,19 +13308,19 @@ func TestPromoteChatQueuedMessage(t *testing.T) {
|
||||
promotedID = msg.ID
|
||||
}
|
||||
}
|
||||
if msg.Role == database.ChatMessageRoleAssistant && promotedID != 0 && replyID == 0 {
|
||||
replyID = msg.ID
|
||||
}
|
||||
}
|
||||
require.NotZero(t, syntheticID,
|
||||
"expected a synthetic error tool result for the pending tool call")
|
||||
require.NotZero(t, promotedID,
|
||||
"expected the promoted user message in chat history")
|
||||
require.Less(t, syntheticID, promotedID,
|
||||
"synthetic tool result must precede the promoted user message")
|
||||
require.NotZero(t, resultID, "expected the submitted tool result")
|
||||
require.Less(t, resultID, promotedID,
|
||||
"the steered message goes in after the submitted tool result")
|
||||
require.NotZero(t, replyID,
|
||||
"expected an assistant reply after the steered message")
|
||||
|
||||
queuedRemaining, err := db.GetChatQueuedMessages(dbauthz.AsSystemRestricted(ctx), chat.ID)
|
||||
require.NoError(t, err)
|
||||
for _, qm := range queuedRemaining {
|
||||
require.NotEqual(t, queuedMessage.ID, qm.ID)
|
||||
}
|
||||
require.Empty(t, queuedRemaining)
|
||||
})
|
||||
|
||||
t.Run("WhileRunning", func(t *testing.T) {
|
||||
@@ -13292,15 +13341,12 @@ func TestPromoteChatQueuedMessage(t *testing.T) {
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Simulate an active worker by setting status to running.
|
||||
// We do not start a real worker; the running-case behavior
|
||||
// reorders the queue and moves the chat to interrupting. The
|
||||
// deferred auto-promote is exercised by chatd-package tests
|
||||
// where a real worker is involved.
|
||||
// No real worker runs here, so this test stops before delivery.
|
||||
workerID := uuid.New()
|
||||
_, err = db.UpdateChatStatus(dbauthz.AsSystemRestricted(ctx), database.UpdateChatStatusParams{
|
||||
ID: chat.ID,
|
||||
Status: database.ChatStatusRunning,
|
||||
WorkerID: uuid.NullUUID{UUID: uuid.New(), Valid: true},
|
||||
WorkerID: uuid.NullUUID{UUID: workerID, Valid: true},
|
||||
StartedAt: sql.NullTime{Time: dbtime.Now(), Valid: true},
|
||||
HeartbeatAt: sql.NullTime{Time: dbtime.Now(), Valid: true},
|
||||
})
|
||||
@@ -13328,16 +13374,17 @@ func TestPromoteChatQueuedMessage(t *testing.T) {
|
||||
|
||||
after, err := db.GetChatByID(dbauthz.AsSystemRestricted(ctx), chat.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, database.ChatStatusInterrupting, after.Status,
|
||||
"running-case promote must transition chat to interrupting")
|
||||
require.True(t, after.WorkerID.Valid,
|
||||
"running-case promote keeps current worker ownership")
|
||||
require.Equal(t, database.ChatStatusRunning, after.Status,
|
||||
"Send now does not interrupt a running chat")
|
||||
require.Equal(t, uuid.NullUUID{UUID: workerID, Valid: true}, after.WorkerID,
|
||||
"Send now keeps the worker")
|
||||
|
||||
queuedRemaining, err := db.GetChatQueuedMessages(dbauthz.AsSystemRestricted(ctx), chat.ID)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, queuedRemaining, 1)
|
||||
require.Equal(t, queuedMessage.ID, queuedRemaining[0].ID,
|
||||
"queued message ID must stay stable across reorder")
|
||||
"queued message ID must stay stable when it moves to the steer lane")
|
||||
require.Equal(t, database.ChatBusyBehaviorSteer, queuedRemaining[0].BusyBehavior)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -132,7 +132,8 @@ Queued messages wait in two lanes. These rules apply to every transition that qu
|
||||
|
||||
1. `busy_behavior` names the lane, `steer` or `queue`. Inside a lane, `position` gives the order.
|
||||
2. The whole `steer` lane goes first, in position order, then the `queue` lane. Every queue list shows this delivery order: the HTTP API, the `queue_update` stream event, and the `coder_get_chat_messages` MCP tool.
|
||||
3. Queued messages go into history only at delivery points. Before each assistant LLM API call, the whole `steer` lane goes in, and never a `queue` message. At `FinishTurn` and `FinishInterruption`, the whole `steer` lane goes in; if it is empty, the first `queue` message goes in. Delivery stops at a message under edit: it and every message behind it wait. In an errored or paused chat with queued messages, each `queue` or `steer` send is a delivery point with the same rule; a `steer` send delivers the `steer` lane with the new message at its end. From `E1` or `A1`, `PromoteQueuedMessage(qid)` delivers only `qid`. When one delivery inserts several messages, the chat takes the model and the reasoning effort of the last message that sets each (`InsertChatMessages`).
|
||||
3. Queued messages go into history only at delivery points. Before each assistant LLM API call, the whole `steer` lane goes in, and never a `queue` message. At `FinishTurn` and `FinishInterruption`, the whole `steer` lane goes in; if it is empty, the first `queue` message goes in. Delivery stops at a message under edit: it and every message behind it wait. In an errored or paused chat with queued messages, each `queue` or `steer` send, and each `SteerQueuedMessage`, is a delivery point with the same rule; a `steer` send delivers the `steer` lane with the new message at its end. When one delivery inserts several messages, the chat takes the model and the reasoning effort of the last message that sets each (`InsertChatMessages`).
|
||||
4. `SteerQueuedMessage` never interrupts.
|
||||
|
||||
### Transitions used by the HTTP endpoints
|
||||
|
||||
@@ -143,7 +144,7 @@ Queued messages wait in two lanes. These rules apply to every transition that qu
|
||||
- `SendMessage(m, busy_behavior)` inserts a user message directly when the chat is idle, or queues it when the chat is busy. `busy_behavior` must be `queue`, `steer` or `interrupt`. `queue` and `steer` name the lane (see [Queued message lanes](#queued-message-lanes)). Outside `E1`, a busy send with one of them stores `m` in its lane and keeps the status, except a `steer` send from `E1P` or `P`. From `E1`, `E1P`, and `P`, `busy_behavior=steer` inserts the queued `steer` messages and then `m` into history, and `queue` messages stay queued. From `E1`, `busy_behavior=queue` queues `m` as a `queue` message and promotes the next messages. With `busy_behavior=interrupt`, it also requests interruption, or cancels a pending dynamic-tool action and inserts the message directly. A queued interrupt message goes to the end of the `steer` lane. A `queue` send never runs before a message under edit; an interrupt send runs before it, unless the chat is running or interrupting and the message under edit is a `steer` message.
|
||||
- `EditMessage(k, replacement)` clears queued messages, cancels or obsoletes active work, marks the truncated active-history suffix as deleted, inserts the replacement turn followed by any caller-provided suffix messages, and lands in `running`.
|
||||
- `DeleteQueuedMessage(qid)` removes one queued message without changing the active history. From `P`, removing the head promotes the message behind it and reaches `running`, or reaches `waiting` when the head was the last queued message.
|
||||
- `PromoteQueuedMessage(qid)` makes a queued message the next message to process in its lane. It reorders the queue, interrupts active work, cancels pending dynamic-tool action, or promotes into history immediately as required by the input state. Promoting a message under edit ends its edit.
|
||||
- `SteerQueuedMessage(qid)` moves a queued message to the end of the `steer` lane. A `steer` message keeps its place. Steering a message under edit ends its edit. From `E1`, `E1P`, and `P`, it closes open tool calls with synthetic cancellation results, delivers the whole `steer` lane into history, and reaches `running`. When another `steer` message under edit is the head, nothing is delivered and the chat keeps its state. From the other states it keeps the chat status, and the `steer` lane waits for the next delivery point.
|
||||
- `EditQueuedMessage(qid, content?, editing?)` rewrites a queued message's content, begins or ends its edit, or both. Beginning an edit ends any other edit on the chat. From `P`, ending the head's edit promotes it and reaches `running`; beginning an edit on a different message is refused.
|
||||
- `Interrupt(reason)` requests cancellation of an active generation or closes pending dynamic-tool action. It preserves queued backlog. When the chat is `running` and no worker owns it, nothing is generating, so the same transaction also applies `FinishInterruption` after inserting synthetic cancellation results for any outstanding tool calls.
|
||||
- `CompleteRequiresAction(results)` inserts submitted tool-result messages followed by any caller-provided suffix messages, clears `requires_action_deadline_at`, and lands in `running`. It preserves queued messages.
|
||||
@@ -207,9 +208,9 @@ stateDiagram-v2
|
||||
E1 --> E0: DeleteQueuedMessage / removed last queued
|
||||
E1 --> E1: DeleteQueuedMessage / queue still non-empty
|
||||
E1 --> E1P: DeleteQueuedMessage / new head under edit
|
||||
E1 --> R0: PromoteQueuedMessage / promoted last queued
|
||||
E1 --> R1: PromoteQueuedMessage / queue still non-empty
|
||||
E1 --> R1P: PromoteQueuedMessage / new head under edit
|
||||
E1 --> R0: SteerQueuedMessage / promoted last queued
|
||||
E1 --> R1: SteerQueuedMessage / queue still non-empty
|
||||
E1 --> R1P: SteerQueuedMessage / new head under edit
|
||||
E1 --> E1: EditQueuedMessage / content edit or edit behind head
|
||||
E1 --> E1P: EditQueuedMessage / begin edit on head
|
||||
E1 --> XE1: SetArchived(true)
|
||||
@@ -223,9 +224,9 @@ stateDiagram-v2
|
||||
E1P --> E0: DeleteQueuedMessage / removed last queued
|
||||
E1P --> E1: DeleteQueuedMessage / new head ready
|
||||
E1P --> E1P: DeleteQueuedMessage / removed row behind head
|
||||
E1P --> R0: PromoteQueuedMessage / promoted last queued
|
||||
E1P --> R1: PromoteQueuedMessage / new head ready
|
||||
E1P --> R1P: PromoteQueuedMessage / new head under edit
|
||||
E1P --> R0: SteerQueuedMessage / promoted last queued
|
||||
E1P --> R1: SteerQueuedMessage / queue still non-empty
|
||||
E1P --> R1P: SteerQueuedMessage / steered row behind head
|
||||
E1P --> E1P: EditQueuedMessage / content edit
|
||||
E1P --> E1: EditQueuedMessage / end head edit or begin edit behind head
|
||||
E1P --> XE1P: SetArchived(true)
|
||||
@@ -258,7 +259,7 @@ stateDiagram-v2
|
||||
R1 --> R0: DeleteQueuedMessage / removed last queued
|
||||
R1 --> R1: DeleteQueuedMessage / queue still non-empty
|
||||
R1 --> R1P: DeleteQueuedMessage / new head under edit
|
||||
R1 --> I1: PromoteQueuedMessage
|
||||
R1 --> R1: SteerQueuedMessage
|
||||
R1 --> R1: EditQueuedMessage / content edit or edit behind head
|
||||
R1 --> R1P: EditQueuedMessage / begin edit on head
|
||||
R1 --> R0: FinishTurn / promoted last queued
|
||||
@@ -277,7 +278,7 @@ stateDiagram-v2
|
||||
R1P --> R0: DeleteQueuedMessage / removed last queued
|
||||
R1P --> R1: DeleteQueuedMessage / new head ready
|
||||
R1P --> R1P: DeleteQueuedMessage / removed row behind head
|
||||
R1P --> I1: PromoteQueuedMessage
|
||||
R1P --> R1: SteerQueuedMessage
|
||||
R1P --> R1P: EditQueuedMessage / content edit
|
||||
R1P --> R1: EditQueuedMessage / end head edit or begin edit behind head
|
||||
R1P --> P: FinishTurn
|
||||
@@ -291,7 +292,7 @@ stateDiagram-v2
|
||||
I1 --> I0: DeleteQueuedMessage / removed last queued
|
||||
I1 --> I1: DeleteQueuedMessage / queue still non-empty
|
||||
I1 --> I1P: DeleteQueuedMessage / new head under edit
|
||||
I1 --> I1: PromoteQueuedMessage
|
||||
I1 --> I1: SteerQueuedMessage
|
||||
I1 --> I1: EditQueuedMessage / content edit or edit behind head
|
||||
I1 --> I1P: EditQueuedMessage / begin edit on head
|
||||
I1 --> R0: FinishInterruption / promoted last queued
|
||||
@@ -303,7 +304,7 @@ stateDiagram-v2
|
||||
I1P --> I0: DeleteQueuedMessage / removed last queued
|
||||
I1P --> I1: DeleteQueuedMessage / new head ready
|
||||
I1P --> I1P: DeleteQueuedMessage / removed row behind head
|
||||
I1P --> I1: PromoteQueuedMessage
|
||||
I1P --> I1: SteerQueuedMessage
|
||||
I1P --> I1P: EditQueuedMessage / content edit
|
||||
I1P --> I1: EditQueuedMessage / end head edit or begin edit behind head
|
||||
I1P --> P: FinishInterruption
|
||||
@@ -326,9 +327,7 @@ stateDiagram-v2
|
||||
A1 --> A0: DeleteQueuedMessage / removed last queued
|
||||
A1 --> A1: DeleteQueuedMessage / queue still non-empty
|
||||
A1 --> A1P: DeleteQueuedMessage / new head under edit
|
||||
A1 --> R0: PromoteQueuedMessage / promoted last queued
|
||||
A1 --> R1: PromoteQueuedMessage / queue still non-empty
|
||||
A1 --> R1P: PromoteQueuedMessage / new head under edit
|
||||
A1 --> A1: SteerQueuedMessage
|
||||
A1 --> A1: EditQueuedMessage / content edit or edit behind head
|
||||
A1 --> A1P: EditQueuedMessage / begin edit on head
|
||||
|
||||
@@ -341,9 +340,7 @@ stateDiagram-v2
|
||||
A1P --> A0: DeleteQueuedMessage / removed last queued
|
||||
A1P --> A1: DeleteQueuedMessage / new head ready
|
||||
A1P --> A1P: DeleteQueuedMessage / removed row behind head
|
||||
A1P --> R0: PromoteQueuedMessage / promoted last queued
|
||||
A1P --> R1: PromoteQueuedMessage / new head ready
|
||||
A1P --> R1P: PromoteQueuedMessage / new head under edit
|
||||
A1P --> A1: SteerQueuedMessage
|
||||
A1P --> A1P: EditQueuedMessage / content edit
|
||||
A1P --> A1: EditQueuedMessage / end head edit or begin edit behind head
|
||||
|
||||
@@ -355,9 +352,9 @@ stateDiagram-v2
|
||||
P --> R0: DeleteQueuedMessage / removed head, promoted last queued
|
||||
P --> R1: DeleteQueuedMessage / removed head, queue still non-empty after promoting next
|
||||
P --> P: DeleteQueuedMessage / removed row behind head
|
||||
P --> R0: PromoteQueuedMessage / promoted last queued
|
||||
P --> R1: PromoteQueuedMessage / new head ready
|
||||
P --> R1P: PromoteQueuedMessage / new head under edit
|
||||
P --> R0: SteerQueuedMessage / promoted last queued
|
||||
P --> R1: SteerQueuedMessage / queue still non-empty
|
||||
P --> R1P: SteerQueuedMessage / steered row behind head
|
||||
P --> P: EditQueuedMessage / content edit
|
||||
P --> R0: EditQueuedMessage / end head edit, promoted last queued
|
||||
P --> R1: EditQueuedMessage / end head edit, queue still non-empty
|
||||
@@ -714,35 +711,29 @@ This endpoint uses `DeleteQueuedMessage(qid)`:
|
||||
|
||||
The endpoint is owner-only because removing the head from `P` promotes the message behind it, which runs LLM inference with the owner's delegated credentials.
|
||||
|
||||
No other input states are supported.
|
||||
No other input states are supported. In the other unarchived states the queue is empty, so the endpoint returns `404`, as it does for a missing `qid`. An archived chat returns `400`.
|
||||
|
||||
### `POST /api/v2/chats/{chat}/queue/{queuedMessage}/promote`
|
||||
|
||||
This endpoint uses `PromoteQueuedMessage(qid)`:
|
||||
This endpoint is "Send now". It applies `SteerQueuedMessage(qid)` and never interrupts:
|
||||
|
||||
- `E1 -> PromoteQueuedMessage(qid) -> R0` if promoting the last queued message
|
||||
- `E1 -> PromoteQueuedMessage(qid) -> R1` if the queue remains non-empty
|
||||
- `E1 -> PromoteQueuedMessage(qid) -> R1P` if a different message under edit becomes the head
|
||||
- `E1P -> PromoteQueuedMessage(qid) -> R0` if promoting the last queued message
|
||||
- `E1P -> PromoteQueuedMessage(qid) -> R1` if the queue remains non-empty
|
||||
- `E1P -> PromoteQueuedMessage(qid) -> R1P` if a different message under edit becomes the head
|
||||
- `R1 -> PromoteQueuedMessage(qid) -> I1`
|
||||
- `R1P -> PromoteQueuedMessage(qid) -> I1`
|
||||
- `I1 -> PromoteQueuedMessage(qid) -> I1`
|
||||
- `I1P -> PromoteQueuedMessage(qid) -> I1`
|
||||
- `A1 -> PromoteQueuedMessage(qid) -> R0` if promoting the last queued message
|
||||
- `A1 -> PromoteQueuedMessage(qid) -> R1` if the queue remains non-empty
|
||||
- `A1 -> PromoteQueuedMessage(qid) -> R1P` if a different message under edit becomes the head
|
||||
- `A1P -> PromoteQueuedMessage(qid) -> R0` if promoting the last queued message
|
||||
- `A1P -> PromoteQueuedMessage(qid) -> R1` if the queue remains non-empty
|
||||
- `A1P -> PromoteQueuedMessage(qid) -> R1P` if a different message under edit becomes the head
|
||||
- `P -> PromoteQueuedMessage(qid) -> R0 | R1 | R1P`: `R0` if promoting the last queued message, `R1` if the queue remains non-empty, `R1P` if a different message under edit becomes the head
|
||||
- `E1 -> SteerQueuedMessage(qid) -> R0 | R1 | R1P`
|
||||
- `E1P -> SteerQueuedMessage(qid) -> E1P | R0 | R1 | R1P`
|
||||
- `R1 -> SteerQueuedMessage(qid) -> R1`
|
||||
- `R1P -> SteerQueuedMessage(qid) -> R1 | R1P`
|
||||
- `I1 -> SteerQueuedMessage(qid) -> I1`
|
||||
- `I1P -> SteerQueuedMessage(qid) -> I1 | I1P`
|
||||
- `A1 -> SteerQueuedMessage(qid) -> A1`
|
||||
- `A1P -> SteerQueuedMessage(qid) -> A1 | A1P`
|
||||
- `P -> SteerQueuedMessage(qid) -> P | R0 | R1 | R1P`
|
||||
|
||||
`PromoteQueuedMessage` ends the target's edit and reorders `qid` to the head of its lane. From `E1`, `E1P`, `A1`, `A1P`, and `P`, it removes the queued message and inserts it into history immediately. From `R1`, `R1P`, `I1`, and `I1P`, it leaves the message queued at the head of its lane. After `FinishInterruption(partial?)` finalizes the interrupted suffix, it promotes every `steer` message, or `qid` if there are none. If `qid` is a `queue` message and `steer` messages are queued, `qid` stays queued at the head of the `queue` lane.
|
||||
`SteerQueuedMessage` moves `qid` to the end of the `steer` lane with a new, highest `position`. If `qid` is already a `steer` message, it keeps its place. From `E1`, `E1P`, and `P`, it closes open tool calls with synthetic cancellation results and delivers the whole `steer` lane into history: `R0` if no queued messages remain, or `R1` if `queue` messages remain (or `R1P` when the first of them is under edit). From the other states it keeps the chat status. The state keeps its `P` when `qid` waits behind a `steer` message under edit.
|
||||
|
||||
From `R1`, `R1P`, `I1`, `I1P`, `A1`, and `A1P`, the `steer` lane goes in at the next delivery point: `DeliverSteerMessages` before the next LLM API call, `FinishTurn`, or `FinishInterruption`.
|
||||
|
||||
When `qid` goes into history, the history message has `queued_message_id = qid`.
|
||||
|
||||
No other input states are supported.
|
||||
No other input states are supported. In the other unarchived states the queue is empty, so the endpoint returns `404`, as it does for a missing `qid`. An archived chat returns `400`.
|
||||
|
||||
### `PATCH /api/v2/chats/{chat}/queue/{queuedMessage}`
|
||||
|
||||
@@ -1037,7 +1028,7 @@ One `chat_turn` span covers one prompt, not one runner. A runner keeps ownership
|
||||
- Takeover: a runner that acquired its chat from an owner whose heartbeat went stale (`spawnRunnerRequest.TakenOver`) opens its first turn at now with no `acquisition` stage, so the previous owner's work is not reported as pickup delay. The flag is also set when the owner of a chat in `requires_action` died before the results arrived, so that turn records no `acquisition` either.
|
||||
- Newer prompt: if `Ensure` is called on the current turn with a trigger after that turn's trigger, it closes that turn and opens a new one for the newer prompt. The closed turn is `abandoned` unless the task that ran it records an outcome before releasing it (see Emission below). A trigger that lands while the previous turn is still running keeps its own trigger as the anchor.
|
||||
- Invalidate: `Invalidate` records an outcome and an error for the open turn. The first call is kept, and a call after `Complete` is ignored: the finishing transition has committed, so a later failure in the same step does not change the outcome. A step whose `FinishError` transition commits, including a step that fails closed, records `error` with the failure. Every other failed step records nothing. A failure the task runner retries keeps the same trigger, so the retry's `Ensure` continues the same turn. A step that exits with an expected, non-retryable error (a fence or history mismatch), or whose task context is done, leaves the turn open for the interrupt task, a newer prompt's `Ensure`, or runner exit to close. A step that commits after a stop has committed but before the runner cancels its task fails the fence check this way, and the interrupt task then closes its turn as `interrupted`.
|
||||
- Interrupt: the interrupt task confirms the chat is `interrupting`, then invalidates the open turn as `interrupted` before `FinishInterruption` commits, so a queued prompt the commit promotes cannot close it first. `OpenToken`, like `Ensure`, returns the zero token once the task's context is done, so a canceled interrupt task cannot mark a turn its successor opened. After the commit, including a commit whose `Update` call reported an error, it settles the turn and records the promoted prompt's `queue_wait`; settling closes the turn even when no generation task holds it, for example when the interrupt lands between two steps. `interrupted` therefore means an interrupt request stopped the turn: a user or API client stopping the chat or promoting a queued message on a running chat, or a parent agent calling `interrupt_agent` or `message_agent` with `interrupt: true`.
|
||||
- Interrupt: the interrupt task confirms the chat is `interrupting`, then invalidates the open turn as `interrupted` before `FinishInterruption` commits, so a queued prompt the commit promotes cannot close it first. `OpenToken`, like `Ensure`, returns the zero token once the task's context is done, so a canceled interrupt task cannot mark a turn its successor opened. After the commit, including a commit whose `Update` call reported an error, it settles the turn and records the promoted prompt's `queue_wait`; settling closes the turn even when no generation task holds it, for example when the interrupt lands between two steps. `interrupted` therefore means an interrupt request stopped the turn: a user or API client stopping the chat, or a parent agent calling `interrupt_agent` or `message_agent` with `interrupt: true`.
|
||||
- Complete: after the `FinishTurn` or `EnterRequiresAction` transition commits, the generation step calls `Complete`. This marks the turn finished but leaves the span open. A chat waiting in `requires_action` is therefore outside any turn; the generation resumed by its tool results opens a new one.
|
||||
- Settle: when the step returns to the generation loop, after the step's own `generation_step` stage has ended, the loop calls `Settle`, which closes a finished or invalidated turn. Closing in two steps ensures the finishing step is counted inside the turn.
|
||||
- Emission: closing a turn fixes its end time and stops `Ensure` from joining it, but its span is emitted only once every task that joined it has called `Release`. `runTask` calls `Release` after the task's function returns, so every stage the task started has ended by then. A closed turn that no task holds, such as one the interrupt task settles after its generation task exited, is emitted at once.
|
||||
@@ -1370,7 +1361,7 @@ Users can also request a compaction on demand via `POST /api/v2/chats/{chat}/com
|
||||
3. A forced compaction bypasses the automatic threshold gates (usage below threshold, unknown context window, and the threshold=100 disable) and stamps `source: "manual"` instead of `source: "automatic"` into the `chat_summarized` tool call arguments, tool result JSON, and streamed parts so clients can render manual compactions distinctly.
|
||||
4. The compaction `CommitStep` consumes the request by clearing `compaction_requested_at` in the same transaction that commits the summary triplet. The next decision pass finds the history complete and finishes the turn, so a chat with an empty queue returns to `waiting` with no assistant follow-up; a chat compacted from `E1` proceeds to its queued messages instead, and one compacted from `E1P` pauses. A `post_compact` hook effect is the one exception: because the decision reads user-visible history, an effect that commits a user-visible message leaves the history incomplete and the turn continues with an assistant response. A model-only effect such as `model_context` reaches the model without resuming generation.
|
||||
|
||||
The `compaction_requested_at` marker is one-shot: transitions that keep an active turn alive (`Acquire`, `Abandon`, `SetArchived`, queueing a message on a busy chat) carry it forward, while every other transition that rewrites the execution state (`FinishTurn`, `FinishError`, `Interrupt`, `EditMessage`, `PromoteQueuedMessage`, `CancelRequiresAction`, `ReconcileInvalidState`, and so on) clears it by construction, so a stale request can never replay on a later turn.
|
||||
The `compaction_requested_at` marker is one-shot: transitions that keep an active turn alive (`Acquire`, `Abandon`, `SetArchived`, queueing a message on a busy chat, `SteerQueuedMessage` on a busy chat) carry it forward, while every other transition that rewrites the execution state (`FinishTurn`, `FinishError`, `Interrupt`, `EditMessage`, `CancelRequiresAction`, `ReconcileInvalidState`, and so on) clears it by construction, so a stale request can never replay on a later turn.
|
||||
|
||||
# Lifecycle hooks
|
||||
|
||||
|
||||
@@ -573,8 +573,14 @@ func (p *Server) DeleteQueued(
|
||||
}
|
||||
|
||||
var deleted chatstate.DeleteQueuedMessageResult
|
||||
err := p.newChatMachine(chatID).Update(ctx, func(tx *chatstate.Tx, _ database.Store) error {
|
||||
var err error
|
||||
err := p.newChatMachine(chatID).Update(ctx, func(tx *chatstate.Tx, store database.Store) error {
|
||||
lockedChat, err := store.GetChatByID(ctx, chatID)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("load chat: %w", err)
|
||||
}
|
||||
if lockedChat.Archived {
|
||||
return ErrChatArchived
|
||||
}
|
||||
deleted, err = tx.DeleteQueuedMessage(chatstate.DeleteQueuedMessageInput{
|
||||
QueuedMessageID: queuedMessageID,
|
||||
})
|
||||
@@ -705,24 +711,19 @@ func (p *Server) EditQueuedMessage(
|
||||
return nil
|
||||
}
|
||||
|
||||
// PromoteQueued promotes a queued message through the chatstate state
|
||||
// machine. From running / interrupting states the state machine
|
||||
// transitions the chat to `interrupting` so the worker can finish the
|
||||
// in-flight generation before promoting; from idle / error / requires
|
||||
// action states it inserts the user message into history
|
||||
// synchronously.
|
||||
// PromoteQueued moves a queued message to the steer lane. From E1, E1P,
|
||||
// and P it delivers the steer lane in the same transaction. From other
|
||||
// states the steer lane waits for the next delivery point. It never
|
||||
// interrupts.
|
||||
func (p *Server) PromoteQueued(
|
||||
ctx context.Context,
|
||||
opts PromoteQueuedOptions,
|
||||
) (PromoteQueuedResult, error) {
|
||||
) error {
|
||||
if opts.ChatID == uuid.Nil {
|
||||
return PromoteQueuedResult{}, xerrors.New("chat_id is required")
|
||||
return xerrors.New("chat_id is required")
|
||||
}
|
||||
|
||||
var (
|
||||
result PromoteQueuedResult
|
||||
promotedQueuedAt time.Time
|
||||
)
|
||||
var promotedQueuedAt time.Time
|
||||
refreshed, err := p.updateChat(ctx, opts.ChatID, "promote", func(tx *chatstate.Tx, store database.Store, _ *database.Chat) error {
|
||||
lockedChat, err := store.GetChatByID(ctx, opts.ChatID)
|
||||
if err != nil {
|
||||
@@ -732,24 +733,21 @@ func (p *Server) PromoteQueued(
|
||||
return ErrChatArchived
|
||||
}
|
||||
|
||||
promoteResult, err := tx.PromoteQueuedMessage(chatstate.PromoteQueuedMessageInput{
|
||||
steered, err := tx.SteerQueuedMessage(chatstate.SteerQueuedMessageInput{
|
||||
QueuedMessageID: opts.QueuedMessageID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if promoteResult.InsertedMessage != nil {
|
||||
result.PromotedMessage = *promoteResult.InsertedMessage
|
||||
}
|
||||
promotedQueuedAt = promoteResult.PromotedQueuedAt
|
||||
promotedQueuedAt = steered.PromotedQueuedAt
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return PromoteQueuedResult{}, err
|
||||
return err
|
||||
}
|
||||
|
||||
p.recordQueueWait(ctx, refreshed, promotedQueuedAt)
|
||||
return result, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// SubmitToolResults dispatches hooks before completing the
|
||||
|
||||
@@ -521,14 +521,6 @@ type PromoteQueuedOptions struct {
|
||||
QueuedMessageID int64
|
||||
}
|
||||
|
||||
// PromoteQueuedResult contains post-promotion message metadata.
|
||||
type PromoteQueuedResult struct {
|
||||
// PromotedMessage is the inserted user message. For a chat that
|
||||
// was running at promote time, the insertion is deferred to the
|
||||
// worker's auto-promote and PromotedMessage is the zero value.
|
||||
PromotedMessage database.ChatMessage
|
||||
}
|
||||
|
||||
// forcedMCPServerConfigsForOwner filters enabled Force On configs
|
||||
// through the chat owner's ACL so availability cannot widen access.
|
||||
func forcedMCPServerConfigsForOwner(ctx context.Context, store database.Store, organizationID, ownerID uuid.UUID) ([]database.MCPServerConfig, error) {
|
||||
|
||||
@@ -1024,8 +1024,7 @@ func TestArchivedChatRejectsMutations(t *testing.T) {
|
||||
return err
|
||||
},
|
||||
"PromoteQueued": func(ctx context.Context) error {
|
||||
_, err := server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{ChatID: chat.ID, QueuedMessageID: 1})
|
||||
return err
|
||||
return server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{ChatID: chat.ID, QueuedMessageID: 1})
|
||||
},
|
||||
"SubmitToolResults": func(ctx context.Context) error {
|
||||
return server.SubmitToolResults(ctx, chatd.SubmitToolResultsOptions{ChatID: chat.ID, UserID: user.ID})
|
||||
@@ -13723,12 +13722,13 @@ func TestQueuedPromotionResolvesOrganizationModel(t *testing.T) {
|
||||
})
|
||||
queued := insertQueuedMessage(ctx, t, db, chat.ID, user.ID, foreignModel.ID, "queued")
|
||||
|
||||
result, err := server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
||||
err := server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
||||
ChatID: chat.ID,
|
||||
QueuedMessageID: queued.ID,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, localDefault.ID, result.PromotedMessage.ModelConfigID.UUID)
|
||||
delivered := requireDeliveredQueuedMessage(ctx, t, db, chat.ID, queued.ID)
|
||||
require.Equal(t, localDefault.ID, delivered.ModelConfigID.UUID)
|
||||
})
|
||||
|
||||
t.Run("ErrorStateSendPromotion", func(t *testing.T) {
|
||||
@@ -13778,7 +13778,7 @@ func TestQueuedPromotionResolvesOrganizationModel(t *testing.T) {
|
||||
})
|
||||
queued := insertQueuedMessage(ctx, t, db, chat.ID, user.ID, foreignModel.ID, "queued")
|
||||
|
||||
_, err := server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
||||
err := server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
||||
ChatID: chat.ID,
|
||||
QueuedMessageID: queued.ID,
|
||||
})
|
||||
@@ -13816,6 +13816,23 @@ func insertQueuedMessage(
|
||||
return queued
|
||||
}
|
||||
|
||||
func requireDeliveredQueuedMessage(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
db database.Store,
|
||||
chatID uuid.UUID,
|
||||
queuedID int64,
|
||||
) database.ChatMessage {
|
||||
t.Helper()
|
||||
for _, message := range chatMessages(ctx, t, db, chatID) {
|
||||
if message.QueuedMessageID.Valid && message.QueuedMessageID.Int64 == queuedID {
|
||||
return message
|
||||
}
|
||||
}
|
||||
require.FailNow(t, "queued message not delivered", "queued message %d", queuedID)
|
||||
return database.ChatMessage{}
|
||||
}
|
||||
|
||||
func TestPromoteQueuedPreservesReasoningEffort(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -13846,13 +13863,14 @@ func TestPromoteQueuedPreservesReasoningEffort(t *testing.T) {
|
||||
require.True(t, queued.ReasoningEffort.Valid)
|
||||
require.Equal(t, database.ChatReasoningEffortHigh, queued.ReasoningEffort.ChatReasoningEffort)
|
||||
|
||||
result, err := replica.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
||||
err = replica.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
||||
ChatID: chat.ID,
|
||||
QueuedMessageID: queued.ID,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, result.PromotedMessage.ReasoningEffort.Valid)
|
||||
require.Equal(t, database.ChatReasoningEffortHigh, result.PromotedMessage.ReasoningEffort.ChatReasoningEffort)
|
||||
delivered := requireDeliveredQueuedMessage(ctx, t, db, chat.ID, queued.ID)
|
||||
require.True(t, delivered.ReasoningEffort.Valid)
|
||||
require.Equal(t, database.ChatReasoningEffortHigh, delivered.ReasoningEffort.ChatReasoningEffort)
|
||||
|
||||
storedChat, err := db.GetChatByID(ctx, chat.ID)
|
||||
require.NoError(t, err)
|
||||
@@ -15034,13 +15052,12 @@ func TestActiveServer_TracesChatTurn(t *testing.T) {
|
||||
require.Equal(t, lastUserMessage(ctx, t, h.db, chat.ID).CreatedAt.UTC(), turns[1].StartTime().UTC())
|
||||
})
|
||||
|
||||
// The promotion and its queue_wait happen only after the interruption
|
||||
// finishes.
|
||||
// Send now moves the message to the steer lane without interrupting,
|
||||
// so the running turn completes and then delivers it.
|
||||
t.Run("PromoteQueuedWhileRunning", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
started, release := make(chan struct{}), make(chan struct{})
|
||||
defer close(release)
|
||||
h := newHarness(t, blockFirstStream(started, release, textResponse()))
|
||||
chat := createChatThroughServer(ctx, t, h.db, h.server, h.org.ID, h.user.ID, h.model.ID, "hello")
|
||||
testutil.TryReceive(ctx, t, started)
|
||||
@@ -15052,18 +15069,20 @@ func TestActiveServer_TracesChatTurn(t *testing.T) {
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, sent.Queued)
|
||||
_, err = h.server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
||||
err = h.server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
||||
ChatID: chat.ID,
|
||||
QueuedMessageID: sent.QueuedMessage.ID,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
close(release)
|
||||
waitForChatStatus(ctx, t, h.db, chat.ID, database.ChatStatusWaiting)
|
||||
index := waitForTurns(ctx, t, h.recorder, 2)
|
||||
|
||||
turns := index[string(chatloop.StageChatTurn)]
|
||||
requireStandaloneQueueWait(t, index, sent.QueuedMessage.CreatedAt)
|
||||
requireInterrupted(t, turns[0])
|
||||
require.Equal(t, string(chatloop.TurnOutcomeCompleted), chatd.SpanAttr(t, turns[1], chatloop.AttrTurnOutcome))
|
||||
for _, turn := range turns {
|
||||
require.Equal(t, string(chatloop.TurnOutcomeCompleted), chatd.SpanAttr(t, turn, chatloop.AttrTurnOutcome))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("EditAbandonsTurn", func(t *testing.T) {
|
||||
@@ -15133,7 +15152,7 @@ func TestActiveServer_TracesChatTurn(t *testing.T) {
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
h, chat, queued := failWithQueuedMessage(ctx, t)
|
||||
|
||||
_, err := h.server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
||||
err := h.server.PromoteQueued(ctx, chatd.PromoteQueuedOptions{
|
||||
ChatID: chat.ID,
|
||||
QueuedMessageID: queued.ID,
|
||||
})
|
||||
|
||||
@@ -92,7 +92,7 @@ var AllExecutionTransitions = []Transition{
|
||||
TransitionRequestCompaction,
|
||||
TransitionClearContext,
|
||||
TransitionDeleteQueuedMessage,
|
||||
TransitionPromoteQueuedMessage,
|
||||
TransitionSteerQueuedMessage,
|
||||
TransitionEditQueuedMessage,
|
||||
TransitionInterrupt,
|
||||
TransitionCompleteRequiresAction,
|
||||
|
||||
@@ -94,9 +94,6 @@ func queuedIDsByPosition(ctx context.Context, t *testing.T, f *testFixture, chat
|
||||
return ids
|
||||
}
|
||||
|
||||
// historyMessageIDs returns the chat history message IDs ordered by
|
||||
// row id. Used to assert that PromoteQueuedMessage from R1/I1 does NOT
|
||||
// insert any history rows.
|
||||
func historyMessageIDs(ctx context.Context, t *testing.T, f *testFixture, chatID uuid.UUID) []int64 {
|
||||
t.Helper()
|
||||
msgs, err := f.DB.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
||||
|
||||
@@ -27,15 +27,10 @@ func clientQueueIDs(t *testing.T, f *testFixture, chatID uuid.UUID) []int64 {
|
||||
return ids
|
||||
}
|
||||
|
||||
// TestClientQueueOrderMatchesPromotionOrder checks that clients receive the
|
||||
// queue in the order promotions take it (position, id), including when
|
||||
// position and created_at disagree.
|
||||
func TestClientQueueOrderMatchesPromotionOrder(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// An explicit promote on a running chat moves the target to the head
|
||||
// by position only; created_at keeps the old order.
|
||||
t.Run("PromoteWhileRunning", func(t *testing.T) {
|
||||
t.Run("SteerWhileRunning", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
f := newTestFixture(t)
|
||||
ctx := testutil.Context(t, testutil.WaitShort)
|
||||
@@ -47,17 +42,27 @@ func TestClientQueueOrderMatchesPromotionOrder(t *testing.T) {
|
||||
require.Equal(t, chatstate.StateR1, f.classify(ctx, t, created.Chat.ID))
|
||||
|
||||
require.NoError(t, m.Update(ctx, func(tx *chatstate.Tx, _ database.Store) error {
|
||||
_, err := tx.PromoteQueuedMessage(chatstate.PromoteQueuedMessageInput{
|
||||
_, err := tx.SteerQueuedMessage(chatstate.SteerQueuedMessageInput{
|
||||
QueuedMessageID: second.QueuedMessage.ID,
|
||||
})
|
||||
return err
|
||||
}))
|
||||
require.Equal(t, chatstate.StateI1, f.classify(ctx, t, created.Chat.ID))
|
||||
require.Equal(t, chatstate.StateR1, f.classify(ctx, t, created.Chat.ID))
|
||||
|
||||
promotionOrder := queuedIDsByPosition(ctx, t, f, created.Chat.ID)
|
||||
require.Equal(t, []int64{second.QueuedMessage.ID, first.QueuedMessage.ID}, promotionOrder)
|
||||
require.Equal(t, promotionOrder, clientQueueIDs(t, f, created.Chat.ID),
|
||||
"clients see the promoted message behind the message that will run after it")
|
||||
require.Equal(t, []int64{first.QueuedMessage.ID, second.QueuedMessage.ID}, queuedIDsByPosition(ctx, t, f, created.Chat.ID))
|
||||
clientOrder := clientQueueIDs(t, f, created.Chat.ID)
|
||||
require.Equal(t, []int64{second.QueuedMessage.ID, first.QueuedMessage.ID}, clientOrder,
|
||||
"clients see the steered message first")
|
||||
|
||||
var finish chatstate.FinishTurnResult
|
||||
require.NoError(t, m.Update(ctx, func(tx *chatstate.Tx, _ database.Store) error {
|
||||
var err error
|
||||
finish, err = tx.FinishTurn(chatstate.FinishTurnInput{})
|
||||
return err
|
||||
}))
|
||||
require.Len(t, finish.PromotedMessages, 1)
|
||||
require.Equal(t, clientOrder[0], finish.PromotedMessages[0].QueuedMessageID.Int64,
|
||||
"the first message clients see is promoted first")
|
||||
})
|
||||
|
||||
// Two senders: the first transaction starts (fixing now() and so
|
||||
|
||||
@@ -317,25 +317,8 @@ func testEditMessageSynthesizesToolCancellationsBeforeReplacement(t *testing.T)
|
||||
"edit replacements are not promoted from the queue")
|
||||
}
|
||||
|
||||
func TestSyntheticCancellation_PromoteQueuedMessage(t *testing.T) {
|
||||
func TestSyntheticCancellation_SteerQueuedMessage(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("error queued message", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
testPromoteQueuedMessageE1SynthesizesToolCancellations(t)
|
||||
})
|
||||
t.Run("requires action queued message", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
testPromoteQueuedMessageA1SynthesizesDynamicToolCancellations(t)
|
||||
})
|
||||
}
|
||||
|
||||
// testPromoteQueuedMessageE1SynthesizesToolCancellations verifies
|
||||
// that promoting a queued message from E1 inserts synthetic
|
||||
// tool-result rows for outstanding tool calls before the promoted
|
||||
// user message in history.
|
||||
func testPromoteQueuedMessageE1SynthesizesToolCancellations(t *testing.T) {
|
||||
t.Helper()
|
||||
f := newTestFixture(t)
|
||||
ctx := testutil.Context(t, testutil.WaitShort)
|
||||
created := createTestChat(t, f)
|
||||
@@ -362,70 +345,24 @@ func testPromoteQueuedMessageE1SynthesizesToolCancellations(t *testing.T) {
|
||||
}))
|
||||
require.Equal(t, chatstate.StateE1, f.classify(ctx, t, created.Chat.ID))
|
||||
|
||||
var promote chatstate.PromoteQueuedMessageResult
|
||||
var steer chatstate.SteerQueuedMessageResult
|
||||
require.NoError(t, m.Update(ctx, func(tx *chatstate.Tx, store database.Store) error {
|
||||
var err error
|
||||
promote, err = tx.PromoteQueuedMessage(chatstate.PromoteQueuedMessageInput{
|
||||
steer, err = tx.SteerQueuedMessage(chatstate.SteerQueuedMessageInput{
|
||||
QueuedMessageID: queued.QueuedMessage.ID,
|
||||
})
|
||||
return err
|
||||
}))
|
||||
|
||||
require.Len(t, promote.CancellationMessages, 1)
|
||||
assertToolResultForCall(t, promote.CancellationMessages[0], callID)
|
||||
require.NotNil(t, promote.InsertedMessage)
|
||||
require.Equal(t, database.ChatMessageRoleUser, promote.InsertedMessage.Role)
|
||||
require.Less(t, promote.CancellationMessages[0].ID, promote.InsertedMessage.ID,
|
||||
"cancel is inserted before the promoted user message")
|
||||
require.False(t, promote.CancellationMessages[0].QueuedMessageID.Valid,
|
||||
require.Len(t, steer.InsertedMessages, 2)
|
||||
cancel, delivered := steer.InsertedMessages[0], steer.InsertedMessages[1]
|
||||
assertToolResultForCall(t, cancel, callID)
|
||||
require.Equal(t, database.ChatMessageRoleUser, delivered.Role)
|
||||
require.Less(t, cancel.ID, delivered.ID,
|
||||
"cancel is inserted before the delivered user message")
|
||||
require.False(t, cancel.QueuedMessageID.Valid,
|
||||
"synthetic cancellations are not promoted from the queue")
|
||||
requireQueuedMessageLink(t, *promote.InsertedMessage, queued.QueuedMessage.ID)
|
||||
}
|
||||
|
||||
// testPromoteQueuedMessageA1SynthesizesDynamicToolCancellations
|
||||
// verifies that the dynamic outstanding tool call is canceled when
|
||||
// promoting from A1.
|
||||
func testPromoteQueuedMessageA1SynthesizesDynamicToolCancellations(t *testing.T) {
|
||||
t.Helper()
|
||||
f := newTestFixture(t)
|
||||
ctx := testutil.Context(t, testutil.WaitShort)
|
||||
|
||||
toolName := "dyn_promote_a1"
|
||||
created := createTestChatWithDynamicTools(t, f, toolName)
|
||||
m := chatstate.NewChatMachine(f.DB, f.Pub, created.Chat.ID)
|
||||
|
||||
dynCallID := "call_" + uuid.NewString()
|
||||
commitAssistantToolCall(t, f, m,
|
||||
assistantToolCallMessage(t, f.Model.ID, toolName, dynCallID))
|
||||
|
||||
// Land in A0.
|
||||
require.NoError(t, m.Update(ctx, func(tx *chatstate.Tx, store database.Store) error {
|
||||
_, err := tx.EnterRequiresAction(chatstate.EnterRequiresActionInput{})
|
||||
return err
|
||||
}))
|
||||
require.Equal(t, chatstate.StateA0, f.classify(ctx, t, created.Chat.ID))
|
||||
|
||||
// A0 -> A1 with one queued user message.
|
||||
queued := sendQueuedMessage(t, f, m, "queued-for-a1-promote")
|
||||
require.NotNil(t, queued.QueuedMessage)
|
||||
require.Equal(t, chatstate.StateA1, f.classify(ctx, t, created.Chat.ID))
|
||||
|
||||
var promote chatstate.PromoteQueuedMessageResult
|
||||
require.NoError(t, m.Update(ctx, func(tx *chatstate.Tx, store database.Store) error {
|
||||
var err error
|
||||
promote, err = tx.PromoteQueuedMessage(chatstate.PromoteQueuedMessageInput{
|
||||
QueuedMessageID: queued.QueuedMessage.ID,
|
||||
})
|
||||
return err
|
||||
}))
|
||||
|
||||
require.Len(t, promote.CancellationMessages, 1, "dynamic tool call canceled")
|
||||
assertToolResultForCall(t, promote.CancellationMessages[0], dynCallID)
|
||||
require.NotNil(t, promote.InsertedMessage)
|
||||
require.Equal(t, database.ChatMessageRoleUser, promote.InsertedMessage.Role)
|
||||
require.False(t, promote.CancellationMessages[0].QueuedMessageID.Valid,
|
||||
"synthetic cancellations are not promoted from the queue")
|
||||
requireQueuedMessageLink(t, *promote.InsertedMessage, queued.QueuedMessage.ID)
|
||||
requireQueuedMessageLink(t, delivered, queued.QueuedMessage.ID)
|
||||
}
|
||||
|
||||
func TestSyntheticCancellation_FinishTurn(t *testing.T) {
|
||||
|
||||
@@ -16,7 +16,7 @@ const (
|
||||
TransitionRequestCompaction Transition = "RequestCompaction"
|
||||
TransitionClearContext Transition = "ClearContext"
|
||||
TransitionDeleteQueuedMessage Transition = "DeleteQueuedMessage"
|
||||
TransitionPromoteQueuedMessage Transition = "PromoteQueuedMessage"
|
||||
TransitionSteerQueuedMessage Transition = "SteerQueuedMessage"
|
||||
TransitionEditQueuedMessage Transition = "EditQueuedMessage"
|
||||
TransitionInterrupt Transition = "Interrupt"
|
||||
TransitionCompleteRequiresAction Transition = "CompleteRequiresAction"
|
||||
@@ -74,24 +74,24 @@ var transitionMatrix = map[ExecutionState]map[Transition][]ExecutionState{
|
||||
TransitionClearContext: {StateW},
|
||||
},
|
||||
StateE1: {
|
||||
TransitionSetArchived: {StateXE1},
|
||||
TransitionSetProject: {StateE1},
|
||||
TransitionSendMessage: {StateR0, StateR1, StateR1P},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateE0, StateE1, StateE1P},
|
||||
TransitionPromoteQueuedMessage: {StateR0, StateR1, StateR1P},
|
||||
TransitionEditQueuedMessage: {StateE1, StateE1P},
|
||||
TransitionRequestCompaction: {StateR1},
|
||||
TransitionSetArchived: {StateXE1},
|
||||
TransitionSetProject: {StateE1},
|
||||
TransitionSendMessage: {StateR0, StateR1, StateR1P},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateE0, StateE1, StateE1P},
|
||||
TransitionSteerQueuedMessage: {StateR0, StateR1, StateR1P},
|
||||
TransitionEditQueuedMessage: {StateE1, StateE1P},
|
||||
TransitionRequestCompaction: {StateR1},
|
||||
},
|
||||
StateE1P: {
|
||||
TransitionSetArchived: {StateXE1P},
|
||||
TransitionSetProject: {StateE1P},
|
||||
TransitionSendMessage: {StateE1P, StateR1P},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateE0, StateE1, StateE1P},
|
||||
TransitionPromoteQueuedMessage: {StateR0, StateR1, StateR1P},
|
||||
TransitionEditQueuedMessage: {StateE1, StateE1P},
|
||||
TransitionRequestCompaction: {StateR1P},
|
||||
TransitionSetArchived: {StateXE1P},
|
||||
TransitionSetProject: {StateE1P},
|
||||
TransitionSendMessage: {StateE1P, StateR1P},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateE0, StateE1, StateE1P},
|
||||
TransitionSteerQueuedMessage: {StateE1P, StateR0, StateR1, StateR1P},
|
||||
TransitionEditQueuedMessage: {StateE1, StateE1P},
|
||||
TransitionRequestCompaction: {StateR1P},
|
||||
},
|
||||
StateR0: {
|
||||
TransitionSendMessage: {StateR1, StateI1},
|
||||
@@ -109,7 +109,7 @@ var transitionMatrix = map[ExecutionState]map[Transition][]ExecutionState{
|
||||
TransitionSendMessage: {StateR1, StateI1},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateR0, StateR1, StateR1P},
|
||||
TransitionPromoteQueuedMessage: {StateI1},
|
||||
TransitionSteerQueuedMessage: {StateR1},
|
||||
TransitionEditQueuedMessage: {StateR1, StateR1P},
|
||||
TransitionInterrupt: {StateI1},
|
||||
TransitionRecordGenerationAttempt: {StateR1},
|
||||
@@ -124,7 +124,7 @@ var transitionMatrix = map[ExecutionState]map[Transition][]ExecutionState{
|
||||
TransitionSendMessage: {StateR1, StateR1P, StateI1, StateI1P},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateR0, StateR1, StateR1P},
|
||||
TransitionPromoteQueuedMessage: {StateI1, StateI1P},
|
||||
TransitionSteerQueuedMessage: {StateR1, StateR1P},
|
||||
TransitionEditQueuedMessage: {StateR1, StateR1P},
|
||||
TransitionInterrupt: {StateI1P},
|
||||
TransitionRecordGenerationAttempt: {StateR1P},
|
||||
@@ -141,20 +141,20 @@ var transitionMatrix = map[ExecutionState]map[Transition][]ExecutionState{
|
||||
TransitionFinishInterruption: {StateW},
|
||||
},
|
||||
StateI1: {
|
||||
TransitionSendMessage: {StateI1},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateI0, StateI1, StateI1P},
|
||||
TransitionPromoteQueuedMessage: {StateI1},
|
||||
TransitionEditQueuedMessage: {StateI1, StateI1P},
|
||||
TransitionFinishInterruption: {StateR0, StateR1, StateR1P},
|
||||
TransitionSendMessage: {StateI1},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateI0, StateI1, StateI1P},
|
||||
TransitionSteerQueuedMessage: {StateI1},
|
||||
TransitionEditQueuedMessage: {StateI1, StateI1P},
|
||||
TransitionFinishInterruption: {StateR0, StateR1, StateR1P},
|
||||
},
|
||||
StateI1P: {
|
||||
TransitionSendMessage: {StateI1, StateI1P},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateI0, StateI1, StateI1P},
|
||||
TransitionPromoteQueuedMessage: {StateI1, StateI1P},
|
||||
TransitionEditQueuedMessage: {StateI1, StateI1P},
|
||||
TransitionFinishInterruption: {StateP},
|
||||
TransitionSendMessage: {StateI1, StateI1P},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateI0, StateI1, StateI1P},
|
||||
TransitionSteerQueuedMessage: {StateI1, StateI1P},
|
||||
TransitionEditQueuedMessage: {StateI1, StateI1P},
|
||||
TransitionFinishInterruption: {StateP},
|
||||
},
|
||||
StateA0: {
|
||||
TransitionSendMessage: {StateA1, StateR0},
|
||||
@@ -167,7 +167,7 @@ var transitionMatrix = map[ExecutionState]map[Transition][]ExecutionState{
|
||||
TransitionSendMessage: {StateA1, StateR1},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateA0, StateA1, StateA1P},
|
||||
TransitionPromoteQueuedMessage: {StateR0, StateR1, StateR1P},
|
||||
TransitionSteerQueuedMessage: {StateA1},
|
||||
TransitionEditQueuedMessage: {StateA1, StateA1P},
|
||||
TransitionInterrupt: {StateR1},
|
||||
TransitionCompleteRequiresAction: {StateR1},
|
||||
@@ -177,19 +177,19 @@ var transitionMatrix = map[ExecutionState]map[Transition][]ExecutionState{
|
||||
TransitionSendMessage: {StateA1, StateA1P, StateR1P},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateA0, StateA1, StateA1P},
|
||||
TransitionPromoteQueuedMessage: {StateR0, StateR1, StateR1P},
|
||||
TransitionSteerQueuedMessage: {StateA1, StateA1P},
|
||||
TransitionEditQueuedMessage: {StateA1, StateA1P},
|
||||
TransitionInterrupt: {StateR1P},
|
||||
TransitionCompleteRequiresAction: {StateR1P},
|
||||
TransitionCancelRequiresAction: {StateR1P},
|
||||
},
|
||||
StateP: {
|
||||
TransitionSetProject: {StateP},
|
||||
TransitionSendMessage: {StateP, StateR1P},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateP, StateW, StateR0, StateR1},
|
||||
TransitionPromoteQueuedMessage: {StateR0, StateR1, StateR1P},
|
||||
TransitionEditQueuedMessage: {StateP, StateR0, StateR1},
|
||||
TransitionSetProject: {StateP},
|
||||
TransitionSendMessage: {StateP, StateR1P},
|
||||
TransitionEditMessage: {StateR0},
|
||||
TransitionDeleteQueuedMessage: {StateP, StateW, StateR0, StateR1},
|
||||
TransitionSteerQueuedMessage: {StateP, StateR0, StateR1, StateR1P},
|
||||
TransitionEditQueuedMessage: {StateP, StateR0, StateR1},
|
||||
},
|
||||
StateXW: {
|
||||
TransitionSetArchived: {StateW},
|
||||
|
||||
@@ -1036,6 +1036,27 @@ func (tx *Tx) ClearContext(input ClearContextInput) (ClearContextResult, error)
|
||||
return ClearContextResult{Chat: updated, InsertedMessages: inserted}, nil
|
||||
}
|
||||
|
||||
// requireQueuedMessageTransition is requireFromAllowed for a transition
|
||||
// on one queued message. When t is refused and the message does not
|
||||
// exist, it returns ErrQueuedMessageNotFound.
|
||||
func (tx *Tx) requireQueuedMessageTransition(t Transition, id int64) (database.Chat, ExecutionState, error) {
|
||||
chat, from, err := tx.requireFromAllowed(t)
|
||||
if !errors.Is(err, ErrTransitionNotAllowed) {
|
||||
return chat, from, err
|
||||
}
|
||||
_, lookupErr := tx.store.GetChatQueuedMessageByID(tx.ctx, database.GetChatQueuedMessageByIDParams{
|
||||
ID: id,
|
||||
ChatID: tx.chatID,
|
||||
})
|
||||
if errors.Is(lookupErr, sql.ErrNoRows) {
|
||||
return chat, from, ErrQueuedMessageNotFound
|
||||
}
|
||||
if lookupErr != nil {
|
||||
return chat, from, xerrors.Errorf("get queued: %w", lookupErr)
|
||||
}
|
||||
return chat, from, err
|
||||
}
|
||||
|
||||
// DeleteQueuedMessageInput configures [Tx.DeleteQueuedMessage].
|
||||
type DeleteQueuedMessageInput struct {
|
||||
QueuedMessageID int64
|
||||
@@ -1054,7 +1075,7 @@ type DeleteQueuedMessageResult struct {
|
||||
// leaves paused once the head is ready or the queue is empty (see
|
||||
// leavePaused).
|
||||
func (tx *Tx) DeleteQueuedMessage(input DeleteQueuedMessageInput) (DeleteQueuedMessageResult, error) {
|
||||
chat, from, err := tx.requireFromAllowed(TransitionDeleteQueuedMessage)
|
||||
chat, from, err := tx.requireQueuedMessageTransition(TransitionDeleteQueuedMessage, input.QueuedMessageID)
|
||||
if err != nil {
|
||||
return DeleteQueuedMessageResult{}, err
|
||||
}
|
||||
@@ -1120,7 +1141,7 @@ type EditQueuedMessageResult struct {
|
||||
// leavePaused); beginning an edit on a different row is refused with
|
||||
// [ErrPausedQueuedHeadUnderEdit].
|
||||
func (tx *Tx) EditQueuedMessage(input EditQueuedMessageInput) (EditQueuedMessageResult, error) {
|
||||
chat, from, err := tx.requireFromAllowed(TransitionEditQueuedMessage)
|
||||
chat, from, err := tx.requireQueuedMessageTransition(TransitionEditQueuedMessage, input.QueuedMessageID)
|
||||
if err != nil {
|
||||
return EditQueuedMessageResult{}, err
|
||||
}
|
||||
@@ -1285,88 +1306,76 @@ func (tx *Tx) promoteQueuedRows(chat database.Chat, rows []database.ChatQueuedMe
|
||||
return updated, d, nil
|
||||
}
|
||||
|
||||
// PromoteQueuedMessageInput configures [Tx.PromoteQueuedMessage].
|
||||
type PromoteQueuedMessageInput struct {
|
||||
// SteerQueuedMessageInput configures [Tx.SteerQueuedMessage].
|
||||
type SteerQueuedMessageInput struct {
|
||||
QueuedMessageID int64
|
||||
}
|
||||
|
||||
// PromoteQueuedMessageResult is returned by [Tx.PromoteQueuedMessage].
|
||||
type PromoteQueuedMessageResult struct {
|
||||
QueuedMessage database.ChatQueuedMessage
|
||||
InsertedMessage *database.ChatMessage
|
||||
CancellationMessages []database.ChatMessage
|
||||
// PromotedQueuedAt is zero when the row only moved to the queue head.
|
||||
// SteerQueuedMessageResult is returned by [Tx.SteerQueuedMessage].
|
||||
type SteerQueuedMessageResult struct {
|
||||
// InsertedMessages holds the tool call cancellations and then the
|
||||
// delivered steer rows. Only E1, E1P, and P deliver; every other
|
||||
// state leaves it empty.
|
||||
InsertedMessages []database.ChatMessage
|
||||
// PromotedQueuedAt is zero when no queued message was delivered.
|
||||
PromotedQueuedAt time.Time
|
||||
}
|
||||
|
||||
// PromoteQueuedMessage moves the target queued message to the head of
|
||||
// its lane; from E1/E1P/A1/A1P/P it also pops it into active history.
|
||||
// The target's edit, if any, is ended first, so the target is always
|
||||
// ready.
|
||||
func (tx *Tx) PromoteQueuedMessage(input PromoteQueuedMessageInput) (PromoteQueuedMessageResult, error) {
|
||||
chat, from, err := tx.requireFromAllowed(TransitionPromoteQueuedMessage)
|
||||
// SteerQueuedMessage ends the target's edit, if any, then moves a queue
|
||||
// row behind existing steer rows, without reordering an existing steer
|
||||
// row. From E1, E1P, or P, a non-empty next delivery moves into history
|
||||
// and the chat runs with last_error cleared. Otherwise the chat keeps its
|
||||
// status.
|
||||
func (tx *Tx) SteerQueuedMessage(input SteerQueuedMessageInput) (SteerQueuedMessageResult, error) {
|
||||
chat, from, err := tx.requireQueuedMessageTransition(TransitionSteerQueuedMessage, input.QueuedMessageID)
|
||||
if err != nil {
|
||||
return PromoteQueuedMessageResult{}, err
|
||||
return SteerQueuedMessageResult{}, err
|
||||
}
|
||||
target, err := tx.store.GetChatQueuedMessageByID(tx.ctx, database.GetChatQueuedMessageByIDParams{
|
||||
ID: input.QueuedMessageID,
|
||||
ChatID: tx.chatID,
|
||||
})
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return PromoteQueuedMessageResult{}, ErrQueuedMessageNotFound
|
||||
return SteerQueuedMessageResult{}, ErrQueuedMessageNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return PromoteQueuedMessageResult{}, xerrors.Errorf("get queued: %w", err)
|
||||
return SteerQueuedMessageResult{}, xerrors.Errorf("get queued: %w", err)
|
||||
}
|
||||
if target.EditingSince.Valid {
|
||||
target, err = tx.store.UpdateChatQueuedMessageEditing(tx.ctx, database.UpdateChatQueuedMessageEditingParams{
|
||||
if _, err := tx.store.UpdateChatQueuedMessageEditing(tx.ctx, database.UpdateChatQueuedMessageEditingParams{
|
||||
ID: target.ID,
|
||||
ChatID: tx.chatID,
|
||||
Editing: false,
|
||||
})
|
||||
if err != nil {
|
||||
return PromoteQueuedMessageResult{}, xerrors.Errorf("end queued edit: %w", err)
|
||||
}
|
||||
}
|
||||
_, err = tx.store.ReorderChatQueuedMessageToHead(tx.ctx, database.ReorderChatQueuedMessageToHeadParams{
|
||||
ID: input.QueuedMessageID,
|
||||
ChatID: tx.chatID,
|
||||
})
|
||||
if err != nil {
|
||||
return PromoteQueuedMessageResult{}, xerrors.Errorf("reorder queue: %w", err)
|
||||
}
|
||||
|
||||
// R1/R1P/I1/I1P: leave the target at the head of its lane and
|
||||
// transition to status `interrupting` so the worker can finish the
|
||||
// in-flight generation before FinishInterruption delivers queued
|
||||
// messages. No history row is inserted here and no queue rows are
|
||||
// deleted.
|
||||
if from == StateR1 || from == StateR1P || from == StateI1 || from == StateI1P {
|
||||
if _, err := tx.applyExecutionState(executionStateUpdate{
|
||||
Status: database.ChatStatusInterrupting,
|
||||
Archived: false,
|
||||
WorkerID: chat.WorkerID,
|
||||
RunnerID: chat.RunnerID,
|
||||
LastError: chat.LastError,
|
||||
RequiresActionDeadlineAt: chat.RequiresActionDeadlineAt,
|
||||
}); err != nil {
|
||||
return PromoteQueuedMessageResult{}, xerrors.Errorf("set interrupting: %w", err)
|
||||
return SteerQueuedMessageResult{}, xerrors.Errorf("end queued edit: %w", err)
|
||||
}
|
||||
return PromoteQueuedMessageResult{
|
||||
QueuedMessage: target,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// E1/E1P/A1/A1P/P: pop the target into history and set running.
|
||||
_, d, err := tx.promoteQueuedRows(chat, []database.ChatQueuedMessage{target})
|
||||
if target.BusyBehavior == database.ChatBusyBehaviorQueue {
|
||||
if _, err := tx.store.SteerChatQueuedMessage(tx.ctx, database.SteerChatQueuedMessageParams{
|
||||
ID: target.ID,
|
||||
ChatID: tx.chatID,
|
||||
}); err != nil {
|
||||
return SteerQueuedMessageResult{}, xerrors.Errorf("steer queued: %w", err)
|
||||
}
|
||||
}
|
||||
if from != StateE1 && from != StateE1P && from != StateP {
|
||||
return SteerQueuedMessageResult{}, nil
|
||||
}
|
||||
queue, err := tx.store.GetChatQueuedMessages(tx.ctx, tx.chatID)
|
||||
if err != nil {
|
||||
return PromoteQueuedMessageResult{}, err
|
||||
return SteerQueuedMessageResult{}, xerrors.Errorf("get queued messages: %w", err)
|
||||
}
|
||||
return PromoteQueuedMessageResult{
|
||||
QueuedMessage: target,
|
||||
InsertedMessage: &d.delivered[0],
|
||||
CancellationMessages: d.inserted[:len(d.inserted)-len(d.delivered)],
|
||||
PromotedQueuedAt: target.CreatedAt,
|
||||
rows := nextDelivery(queue)
|
||||
if len(rows) == 0 {
|
||||
return SteerQueuedMessageResult{}, nil
|
||||
}
|
||||
_, d, err := tx.promoteQueuedRows(chat, rows)
|
||||
if err != nil {
|
||||
return SteerQueuedMessageResult{}, err
|
||||
}
|
||||
return SteerQueuedMessageResult{
|
||||
InsertedMessages: d.inserted,
|
||||
PromotedQueuedAt: d.queuedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -34,15 +34,13 @@ type seededChat struct {
|
||||
// the text body each queued message was seeded with. Cases that
|
||||
// promote queued messages into history use this to assert the
|
||||
// promoted message content matches what was originally queued.
|
||||
queuedMessageBodies []string
|
||||
queuedMessageCreatedBy []uuid.UUID
|
||||
queuedMessageBodies []string
|
||||
// editingQueuedID is the queued row seeded under edit, or zero when
|
||||
// no row is. Cases use it to assert the marker survives a
|
||||
// transition that must not touch it.
|
||||
editingQueuedID int64
|
||||
dynamicToolName string
|
||||
pendingToolCallID string
|
||||
pendingToolCallIDs []string
|
||||
editingQueuedID int64
|
||||
dynamicToolName string
|
||||
pendingToolCallID string
|
||||
}
|
||||
|
||||
// readyHeadOf maps each blocked-head state to the sibling state with
|
||||
@@ -506,9 +504,8 @@ func seedStateMultiQueued(t *testing.T, f *testFixture, state chatstate.Executio
|
||||
|
||||
// seedA1WithMixedOutstandingToolCalls seeds A1 with one queued message
|
||||
// and one assistant message carrying both a dynamic and non-dynamic
|
||||
// outstanding tool call. It is used by PromoteQueuedMessage(A1) to
|
||||
// prove all tool calls are closed before inserting the promoted user,
|
||||
// and by CancelRequiresAction(A1) to prove only the dynamic one is.
|
||||
// outstanding tool call. CancelRequiresAction(A1) uses it to prove only
|
||||
// the dynamic one is closed.
|
||||
func seedA1WithMixedOutstandingToolCalls(t *testing.T, f *testFixture, queuedExtras int, namePrefix string) seededChat {
|
||||
t.Helper()
|
||||
ctx := testutil.Context(t, testutil.WaitShort)
|
||||
@@ -533,9 +530,8 @@ func seedA1WithMixedOutstandingToolCalls(t *testing.T, f *testFixture, queuedExt
|
||||
return err
|
||||
}))
|
||||
var (
|
||||
queuedIDs []int64
|
||||
queuedBodies []string
|
||||
queuedCreatedBy []uuid.UUID
|
||||
queuedIDs []int64
|
||||
queuedBodies []string
|
||||
)
|
||||
for i := range queuedExtras {
|
||||
body := fmt.Sprintf("queued-%s-%d", namePrefix, i)
|
||||
@@ -550,7 +546,6 @@ func seedA1WithMixedOutstandingToolCalls(t *testing.T, f *testFixture, queuedExt
|
||||
require.NoError(t, err)
|
||||
queuedIDs = append(queuedIDs, queued.ID)
|
||||
queuedBodies = append(queuedBodies, body)
|
||||
queuedCreatedBy = append(queuedCreatedBy, createdBy)
|
||||
}
|
||||
return seededChat{
|
||||
chatID: created.Chat.ID,
|
||||
@@ -559,10 +554,8 @@ func seedA1WithMixedOutstandingToolCalls(t *testing.T, f *testFixture, queuedExt
|
||||
assistantToolCallMsgID: step.InsertedMessages[0].ID,
|
||||
queuedMessageIDs: queuedIDs,
|
||||
queuedMessageBodies: queuedBodies,
|
||||
queuedMessageCreatedBy: queuedCreatedBy,
|
||||
dynamicToolName: toolName,
|
||||
pendingToolCallID: dynCallID,
|
||||
pendingToolCallIDs: []string{dynCallID, nonDynCallID},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -713,7 +706,6 @@ func seedForEnterRequiresAction(t *testing.T, f *testFixture, state chatstate.Ex
|
||||
assistantToolCallMsgID: step.InsertedMessages[0].ID,
|
||||
dynamicToolName: toolName,
|
||||
pendingToolCallID: callID,
|
||||
pendingToolCallIDs: []string{callID},
|
||||
}
|
||||
case chatstate.StateR1, chatstate.StateR1P:
|
||||
toolName := "ra_tool_r1"
|
||||
@@ -743,7 +735,6 @@ func seedForEnterRequiresAction(t *testing.T, f *testFixture, state chatstate.Ex
|
||||
queuedMessageBodies: []string{queuedBody},
|
||||
dynamicToolName: toolName,
|
||||
pendingToolCallID: callID,
|
||||
pendingToolCallIDs: []string{callID},
|
||||
}
|
||||
if state == chatstate.StateR1P {
|
||||
beginQueuedMessageEdit(ctx, t, f, seeded.chatID, sm.QueuedMessage.ID)
|
||||
@@ -754,9 +745,6 @@ func seedForEnterRequiresAction(t *testing.T, f *testFixture, state chatstate.Ex
|
||||
return seedState(t, f, state)
|
||||
}
|
||||
|
||||
// activeHistoryIDs returns the ids of non-deleted history messages
|
||||
// for the chat in row-id order. Useful for verifying CommitStep,
|
||||
// EditMessage replacement, and PromoteQueuedMessage head insertion.
|
||||
func activeHistoryIDs(ctx context.Context, t *testing.T, f *testFixture, chatID uuid.UUID) []int64 {
|
||||
t.Helper()
|
||||
msgs, err := f.DB.GetChatMessagesByChatID(ctx, database.GetChatMessagesByChatIDParams{
|
||||
@@ -903,20 +891,6 @@ func assertQueuedMessageContent(t *testing.T, content json.RawMessage, want stri
|
||||
require.Equal(t, want, parts[0].Text, "unexpected queued message text")
|
||||
}
|
||||
|
||||
// assertQueueBodiesInOrder fetches the queued messages for the chat
|
||||
// in position order and asserts each row's text body matches the
|
||||
// supplied bodies. Used by matrix cases that need to verify the
|
||||
// remaining queue content after a promote / finish-turn /
|
||||
// finish-interruption.
|
||||
func assertQueueBodiesInOrder(ctx context.Context, t *testing.T, f *testFixture, chatID uuid.UUID, want []string) {
|
||||
t.Helper()
|
||||
rows := queuedRowsByPosition(ctx, t, f, chatID)
|
||||
require.Len(t, rows, len(want), "queue length must match expected bodies")
|
||||
for i, r := range rows {
|
||||
assertQueuedMessageContent(t, r.Content, want[i])
|
||||
}
|
||||
}
|
||||
|
||||
// snapshotBaseline records the chat's snapshot_version and the
|
||||
// publisher's recorded channel count immediately before a transition
|
||||
// runs. Tests use it to verify either a single snapshot bump and one
|
||||
|
||||
@@ -97,7 +97,12 @@ func seedBlockedHead(t *testing.T, f *testFixture, from chatstate.ExecutionState
|
||||
// after FinishTurn from R1P.
|
||||
func seedPaused(t *testing.T, f *testFixture, extra int) seededChat {
|
||||
t.Helper()
|
||||
seeded := seedBlockedHead(t, f, chatstate.StateR1, extra)
|
||||
return pauseSeeded(t, f, seedBlockedHead(t, f, chatstate.StateR1, extra))
|
||||
}
|
||||
|
||||
// pauseSeeded runs FinishTurn on a seeded R1P chat, which pauses it.
|
||||
func pauseSeeded(t *testing.T, f *testFixture, seeded seededChat) seededChat {
|
||||
t.Helper()
|
||||
m := chatstate.NewChatMachine(f.DB, f.Pub, seeded.chatID)
|
||||
require.NoError(t, m.Update(testutil.Context(t, testutil.WaitShort), func(tx *chatstate.Tx, _ database.Store) error {
|
||||
_, err := tx.FinishTurn(chatstate.FinishTurnInput{})
|
||||
@@ -132,11 +137,11 @@ func applySetEditing(idx int, editing bool) applierFn {
|
||||
}
|
||||
}
|
||||
|
||||
func applyPromoteQueuedMessageAt(idx int) applierFn {
|
||||
func applySteerQueuedMessageAt(idx int) applierFn {
|
||||
return func(t *testing.T, _ *testFixture, tx *chatstate.Tx, seeded seededChat, _ chatstate.ExecutionState, result *transitionCaseResult) error {
|
||||
t.Helper()
|
||||
var err error
|
||||
result.promoteQueuedMessage, err = tx.PromoteQueuedMessage(chatstate.PromoteQueuedMessageInput{
|
||||
result.steerQueuedMessage, err = tx.SteerQueuedMessage(chatstate.SteerQueuedMessageInput{
|
||||
QueuedMessageID: seeded.queuedMessageIDs[idx],
|
||||
})
|
||||
return err
|
||||
@@ -187,9 +192,9 @@ func withPromotedRow(spec transitionCaseSpec, idx int) transitionCaseSpec {
|
||||
spec.assert = func(ctx context.Context, t *testing.T, f *testFixture, seeded seededChat, base snapshotBaseline, result transitionCaseResult) {
|
||||
assertCase(ctx, t, f, seeded, base, result)
|
||||
promotedQueuedAt := map[chatstate.Transition]time.Time{
|
||||
chatstate.TransitionEditQueuedMessage: result.editQueuedMessage.PromotedQueuedAt,
|
||||
chatstate.TransitionDeleteQueuedMessage: result.deleteQueuedMessage.PromotedQueuedAt,
|
||||
chatstate.TransitionPromoteQueuedMessage: result.promoteQueuedMessage.PromotedQueuedAt,
|
||||
chatstate.TransitionEditQueuedMessage: result.editQueuedMessage.PromotedQueuedAt,
|
||||
chatstate.TransitionDeleteQueuedMessage: result.deleteQueuedMessage.PromotedQueuedAt,
|
||||
chatstate.TransitionSteerQueuedMessage: result.steerQueuedMessage.PromotedQueuedAt,
|
||||
}[spec.transition]
|
||||
require.False(t, promotedQueuedAt.IsZero(), "the result reports the promoted row's queued time")
|
||||
newIDs := newActiveMessageIDs(base, activeHistoryIDs(ctx, t, f, seeded.chatID))
|
||||
@@ -244,12 +249,16 @@ func editingQueueMatrixCases() []transitionCaseSpec {
|
||||
withPromotedRow(editingCase(chatstate.TransitionDeleteQueuedMessage, chatstate.StateP, chatstate.StateR1, "", seedP(2), applyDeleteQueuedMessage,
|
||||
func(s seededChat) []int64 { return append([]int64{}, s.queuedMessageIDs[2:]...) }, -1), 1),
|
||||
editingCase(chatstate.TransitionDeleteQueuedMessage, chatstate.StateP, chatstate.StateP, scenarioTargetBehindHead, seedP(1), applyDeleteQueuedMessageAt(1), headOnly, 0),
|
||||
// P: promoting the blocked head ends its edit and sends it; promoting
|
||||
// P: steering the blocked head ends its edit and sends it; steering
|
||||
// the row behind it sends that row and leaves the head blocked, so
|
||||
// the resumed turn runs as R1P.
|
||||
withPromotedRow(editingCase(chatstate.TransitionPromoteQueuedMessage, chatstate.StateP, chatstate.StateR0, "", seedP(0), applyPromoteQueuedMessage, noRows, -1), 0),
|
||||
withPromotedRow(editingCase(chatstate.TransitionPromoteQueuedMessage, chatstate.StateP, chatstate.StateR1, "", seedP(1), applyPromoteQueuedMessage, tailRows, -1), 0),
|
||||
withPromotedRow(editingCase(chatstate.TransitionPromoteQueuedMessage, chatstate.StateP, chatstate.StateR1P, scenarioTargetBehindHead, seedP(1), applyPromoteQueuedMessageAt(1), headOnly, 0), 1),
|
||||
// the resumed turn runs as R1P. A row steered behind a steer row
|
||||
// under edit waits for that edit.
|
||||
withPromotedRow(editingCase(chatstate.TransitionSteerQueuedMessage, chatstate.StateP, chatstate.StateR0, "", seedP(0), applySteerQueuedMessage, noRows, -1), 0),
|
||||
withPromotedRow(editingCase(chatstate.TransitionSteerQueuedMessage, chatstate.StateP, chatstate.StateR1, "", seedP(1), applySteerQueuedMessage, tailRows, -1), 0),
|
||||
withPromotedRow(editingCase(chatstate.TransitionSteerQueuedMessage, chatstate.StateP, chatstate.StateR1P, scenarioTargetBehindHead, seedP(1), applySteerQueuedMessageAt(1), headOnly, 0), 1),
|
||||
editingCase(chatstate.TransitionSteerQueuedMessage, chatstate.StateP, chatstate.StateP, scenarioEditSteerHead, func(t *testing.T, f *testFixture) seededChat {
|
||||
return pauseSeeded(t, f, seedSteerHeadUnderEdit(t, f, chatstate.StateR1P))
|
||||
}, applySteerQueuedMessageAt(1), allRows, 0),
|
||||
// P: a history edit clears the queue.
|
||||
editingCase(chatstate.TransitionEditMessage, chatstate.StateP, chatstate.StateR0, "", seedP(1), applyEditMessage, noRows, -1),
|
||||
}
|
||||
|
||||
@@ -49,15 +49,9 @@ const (
|
||||
// scenarioMulti marks cases seeded with multiple queued
|
||||
// messages so the post-mutation queue stays non-empty.
|
||||
scenarioMulti scenario = "multi"
|
||||
// scenarioHeadTarget marks multi-queued PromoteQueuedMessage
|
||||
// cases that target the queue head. From R1, R1P, I1, and I1P the
|
||||
// queue order is unchanged, and queue_version advances only when
|
||||
// the head's edit ends. From E1, E1P, A1, and A1P the head is
|
||||
// popped into history.
|
||||
|
||||
scenarioHeadTarget scenario = "head_target"
|
||||
// scenarioNonHead marks multi-queued PromoteQueuedMessage cases
|
||||
// that target a non-head queued message so the target moves to
|
||||
// the head and queue_version advances.
|
||||
|
||||
scenarioNonHead scenario = "non_head"
|
||||
// scenarioWithQueue marks ReconcileInvalidState cases seeded
|
||||
// with a non-empty queue.
|
||||
@@ -109,8 +103,11 @@ func transitionAllowed(tr chatstate.Transition, from chatstate.ExecutionState) b
|
||||
// returns when a transition is attempted from a state where the
|
||||
// matrix forbids it. N (missing chat) becomes ErrChatNotFound;
|
||||
// Invalid becomes ErrInvalidState (except for ReconcileInvalidState
|
||||
// which is allowed); everything else becomes ErrTransitionNotAllowed.
|
||||
func expectedErrorForDisallowed(tr chatstate.Transition, from chatstate.ExecutionState) error {
|
||||
// which is allowed); a transition on one queued message becomes
|
||||
// ErrQueuedMessageNotFound when the seed has no queued messages,
|
||||
// because its applier then targets ID 0; everything else becomes
|
||||
// ErrTransitionNotAllowed.
|
||||
func expectedErrorForDisallowed(tr chatstate.Transition, from chatstate.ExecutionState, seeded seededChat) error {
|
||||
switch from {
|
||||
case chatstate.StateN:
|
||||
if tr == chatstate.TransitionCreateChat {
|
||||
@@ -126,6 +123,14 @@ func expectedErrorForDisallowed(tr chatstate.Transition, from chatstate.Executio
|
||||
}
|
||||
return chatstate.ErrInvalidState
|
||||
}
|
||||
switch tr {
|
||||
case chatstate.TransitionDeleteQueuedMessage,
|
||||
chatstate.TransitionSteerQueuedMessage,
|
||||
chatstate.TransitionEditQueuedMessage:
|
||||
if len(seeded.queuedMessageIDs) == 0 {
|
||||
return chatstate.ErrQueuedMessageNotFound
|
||||
}
|
||||
}
|
||||
return chatstate.ErrTransitionNotAllowed
|
||||
}
|
||||
|
||||
@@ -224,14 +229,14 @@ func applyDeleteQueuedMessage(t *testing.T, _ *testFixture, tx *chatstate.Tx, se
|
||||
return err
|
||||
}
|
||||
|
||||
func applyPromoteQueuedMessage(t *testing.T, _ *testFixture, tx *chatstate.Tx, seeded seededChat, _ chatstate.ExecutionState, result *transitionCaseResult) error {
|
||||
func applySteerQueuedMessage(t *testing.T, _ *testFixture, tx *chatstate.Tx, seeded seededChat, _ chatstate.ExecutionState, result *transitionCaseResult) error {
|
||||
t.Helper()
|
||||
var targetQueueID int64
|
||||
if len(seeded.queuedMessageIDs) > 0 {
|
||||
targetQueueID = seeded.queuedMessageIDs[0]
|
||||
}
|
||||
var err error
|
||||
result.promoteQueuedMessage, err = tx.PromoteQueuedMessage(chatstate.PromoteQueuedMessageInput{
|
||||
result.steerQueuedMessage, err = tx.SteerQueuedMessage(chatstate.SteerQueuedMessageInput{
|
||||
QueuedMessageID: targetQueueID,
|
||||
})
|
||||
return err
|
||||
@@ -419,8 +424,8 @@ func defaultApplier(tr chatstate.Transition) applierFn {
|
||||
return applyClearContext
|
||||
case chatstate.TransitionDeleteQueuedMessage:
|
||||
return applyDeleteQueuedMessage
|
||||
case chatstate.TransitionPromoteQueuedMessage:
|
||||
return applyPromoteQueuedMessage
|
||||
case chatstate.TransitionSteerQueuedMessage:
|
||||
return applySteerQueuedMessage
|
||||
case chatstate.TransitionEditQueuedMessage:
|
||||
return applyEditQueuedMessage
|
||||
case chatstate.TransitionInterrupt:
|
||||
@@ -476,7 +481,7 @@ type transitionCaseResult struct {
|
||||
requestCompaction chatstate.RequestCompactionResult
|
||||
clearContext chatstate.ClearContextResult
|
||||
deleteQueuedMessage chatstate.DeleteQueuedMessageResult
|
||||
promoteQueuedMessage chatstate.PromoteQueuedMessageResult
|
||||
steerQueuedMessage chatstate.SteerQueuedMessageResult
|
||||
editQueuedMessage chatstate.EditQueuedMessageResult
|
||||
interrupt chatstate.InterruptResult
|
||||
completeRequiresAction chatstate.CompleteRequiresActionResult
|
||||
@@ -594,19 +599,6 @@ func remainingExcluding(ids []int64, exclude int) []int64 {
|
||||
return out
|
||||
}
|
||||
|
||||
// remainingBodiesExcluding returns bodies with the entry at exclude
|
||||
// removed. The order of the surviving entries is preserved.
|
||||
func remainingBodiesExcluding(bodies []string, exclude int) []string {
|
||||
out := make([]string, 0, len(bodies))
|
||||
for i, b := range bodies {
|
||||
if i == exclude {
|
||||
continue
|
||||
}
|
||||
out = append(out, b)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type queueSeed struct {
|
||||
scenario scenario
|
||||
behaviors []chatstate.BusyBehavior
|
||||
@@ -732,7 +724,7 @@ func runDisallowedCase(t *testing.T, f *testFixture, tr chatstate.Transition, fr
|
||||
return
|
||||
}
|
||||
|
||||
expectErr := expectedErrorForDisallowed(tr, from)
|
||||
expectErr := expectedErrorForDisallowed(tr, from, seeded)
|
||||
require.Error(t, err)
|
||||
require.ErrorIs(t, err, expectErr)
|
||||
assertNoMutationOrPublish(ctx, t, f, seeded.chatID, base)
|
||||
@@ -921,6 +913,9 @@ func TestTransitionMatrix_AllCombinations(t *testing.T) {
|
||||
|
||||
func matrixCases() []transitionCaseSpec {
|
||||
multiEditingBehind := withEditingRow(seedStateMultiQueued, 1)
|
||||
mixedLanes := func(t *testing.T, f *testFixture, from chatstate.ExecutionState) seededChat {
|
||||
return seedQueue(t, f, from, chatstate.BusyBehaviorQueue, chatstate.BusyBehaviorSteer, chatstate.BusyBehaviorQueue)
|
||||
}
|
||||
cases := []transitionCaseSpec{
|
||||
// SetArchived cases: each archived/unarchived pair flips the
|
||||
// archived flag, preserves status, history, last_error, and the
|
||||
@@ -1059,39 +1054,31 @@ func matrixCases() []transitionCaseSpec {
|
||||
deleteQueuedCase(chatstate.StateA1, chatstate.StateA0, queueShapeDefault),
|
||||
deleteQueuedCase(chatstate.StateA1, chatstate.StateA1, queueShapeMulti),
|
||||
|
||||
// PromoteQueuedMessage cases. E1/A1 pop the head into
|
||||
// history; R1/I1 only reorder the queue without
|
||||
// inserting history. R1/I1 has both a head-target
|
||||
// scenario (zero rows updated, queue_version unchanged)
|
||||
// and a non-head scenario (target moves to head,
|
||||
// queue_version advances). The target's edit ends, so the
|
||||
// new head is ready even from a blocked-head state; a
|
||||
// different blocked head stays blocked behind a promoted
|
||||
// non-head target.
|
||||
promoteQueuedCase(chatstate.StateE1, chatstate.StateR0, queueShapeDefault, 0),
|
||||
promoteQueuedCase(chatstate.StateE1, chatstate.StateR1, queueShapeMulti, 0),
|
||||
withSeed(promoteQueuedCase(chatstate.StateE1, chatstate.StateR1P, queueShapeDefault, 0), scenarioEditBehindHead, multiEditingBehind),
|
||||
promoteQueuedCase(chatstate.StateE1P, chatstate.StateR0, queueShapeDefault, 0),
|
||||
promoteQueuedCase(chatstate.StateE1P, chatstate.StateR1, queueShapeMulti, 0),
|
||||
promoteQueuedCase(chatstate.StateE1P, chatstate.StateR1P, queueShapeMulti, 1),
|
||||
promoteQueuedCase(chatstate.StateR1, chatstate.StateI1, queueShapeMulti, 0),
|
||||
promoteQueuedCase(chatstate.StateR1, chatstate.StateI1, queueShapeMulti, 1),
|
||||
promoteQueuedCase(chatstate.StateR1P, chatstate.StateI1, queueShapeMulti, 0),
|
||||
promoteQueuedCase(chatstate.StateR1P, chatstate.StateI1, queueShapeMulti, 1),
|
||||
withSeed(promoteQueuedCase(chatstate.StateR1P, chatstate.StateI1P, queueShapeMulti, 1), scenarioEditSteerHead, seedSteerHeadUnderEdit),
|
||||
promoteQueuedCase(chatstate.StateI1, chatstate.StateI1, queueShapeMulti, 1),
|
||||
promoteQueuedCase(chatstate.StateI1P, chatstate.StateI1, queueShapeMulti, 0),
|
||||
promoteQueuedCase(chatstate.StateI1P, chatstate.StateI1, queueShapeMulti, 1),
|
||||
withSeed(promoteQueuedCase(chatstate.StateI1P, chatstate.StateI1P, queueShapeMulti, 1), scenarioEditSteerHead, seedSteerHeadUnderEdit),
|
||||
promoteQueuedCase(chatstate.StateA1, chatstate.StateR0, queueShapeDefault, 0),
|
||||
promoteQueuedCase(chatstate.StateA1, chatstate.StateR1, queueShapeMulti, 0),
|
||||
withSeed(promoteQueuedCase(chatstate.StateA1, chatstate.StateR1P, queueShapeDefault, 0), scenarioEditBehindHead,
|
||||
withEditingRow(func(t *testing.T, f *testFixture, _ chatstate.ExecutionState) seededChat {
|
||||
return seedA1WithMixedOutstandingToolCalls(t, f, 2, "seed_tool_a1_promote_expose")
|
||||
}, 1)),
|
||||
promoteQueuedCase(chatstate.StateA1P, chatstate.StateR0, queueShapeDefault, 0),
|
||||
promoteQueuedCase(chatstate.StateA1P, chatstate.StateR1, queueShapeMulti, 0),
|
||||
promoteQueuedCase(chatstate.StateA1P, chatstate.StateR1P, queueShapeMulti, 1),
|
||||
steerQueuedCase(chatstate.StateE1, chatstate.StateR0, queueShapeDefault, 0),
|
||||
steerQueuedCase(chatstate.StateE1, chatstate.StateR1, queueShapeMulti, 0),
|
||||
steerQueuedCase(chatstate.StateE1, chatstate.StateR1, queueShapeMulti, 1),
|
||||
withSeed(steerQueuedCase(chatstate.StateE1, chatstate.StateR1, queueShapeDefault, 2), scenarioSteerJumps, mixedLanes),
|
||||
withSeed(steerQueuedCase(chatstate.StateE1, chatstate.StateR1P, queueShapeDefault, 0), scenarioEditBehindHead, multiEditingBehind),
|
||||
steerQueuedCase(chatstate.StateE1P, chatstate.StateR0, queueShapeDefault, 0),
|
||||
steerQueuedCase(chatstate.StateE1P, chatstate.StateR1, queueShapeMulti, 0),
|
||||
steerQueuedCase(chatstate.StateE1P, chatstate.StateR1P, queueShapeMulti, 1),
|
||||
withSeed(steerQueuedCase(chatstate.StateE1P, chatstate.StateE1P, queueShapeMulti, 1), scenarioEditSteerHead, seedSteerHeadUnderEdit),
|
||||
steerQueuedCase(chatstate.StateR1, chatstate.StateR1, queueShapeMulti, 0),
|
||||
steerQueuedCase(chatstate.StateR1, chatstate.StateR1, queueShapeMulti, 1),
|
||||
withSeed(steerQueuedCase(chatstate.StateR1, chatstate.StateR1, queueShapeDefault, 0), scenarioSteerJumps, mixedLanes),
|
||||
steerQueuedCase(chatstate.StateR1P, chatstate.StateR1, queueShapeMulti, 0),
|
||||
steerQueuedCase(chatstate.StateR1P, chatstate.StateR1, queueShapeMulti, 1),
|
||||
withSeed(steerQueuedCase(chatstate.StateR1P, chatstate.StateR1P, queueShapeMulti, 1), scenarioEditSteerHead, seedSteerHeadUnderEdit),
|
||||
steerQueuedCase(chatstate.StateI1, chatstate.StateI1, queueShapeMulti, 0),
|
||||
steerQueuedCase(chatstate.StateI1, chatstate.StateI1, queueShapeMulti, 1),
|
||||
steerQueuedCase(chatstate.StateI1P, chatstate.StateI1, queueShapeMulti, 0),
|
||||
steerQueuedCase(chatstate.StateI1P, chatstate.StateI1, queueShapeMulti, 1),
|
||||
withSeed(steerQueuedCase(chatstate.StateI1P, chatstate.StateI1P, queueShapeMulti, 1), scenarioEditSteerHead, seedSteerHeadUnderEdit),
|
||||
steerQueuedCase(chatstate.StateA1, chatstate.StateA1, queueShapeMulti, 0),
|
||||
steerQueuedCase(chatstate.StateA1, chatstate.StateA1, queueShapeMulti, 1),
|
||||
steerQueuedCase(chatstate.StateA1P, chatstate.StateA1, queueShapeMulti, 0),
|
||||
steerQueuedCase(chatstate.StateA1P, chatstate.StateA1, queueShapeMulti, 1),
|
||||
withSeed(steerQueuedCase(chatstate.StateA1P, chatstate.StateA1P, queueShapeMulti, 1), scenarioEditSteerHead, seedSteerHeadUnderEdit),
|
||||
|
||||
// Interrupt cases.
|
||||
interruptCase(chatstate.StateR0, chatstate.StateI0),
|
||||
@@ -1729,7 +1716,7 @@ func deleteQueuedCaseAt(from, want chatstate.ExecutionState, sc scenario, seed s
|
||||
}
|
||||
}
|
||||
|
||||
func promoteQueuedCase(from, want chatstate.ExecutionState, shape queueShape, targetIdx int) transitionCaseSpec {
|
||||
func steerQueuedCase(from, want chatstate.ExecutionState, shape queueShape, targetIdx int) transitionCaseSpec {
|
||||
var sc scenario
|
||||
if shape.isMulti() {
|
||||
switch targetIdx {
|
||||
@@ -1741,15 +1728,15 @@ func promoteQueuedCase(from, want chatstate.ExecutionState, shape queueShape, ta
|
||||
}
|
||||
apply := func(t *testing.T, _ *testFixture, tx *chatstate.Tx, seeded seededChat, _ chatstate.ExecutionState, result *transitionCaseResult) error {
|
||||
t.Helper()
|
||||
require.Less(t, targetIdx, len(seeded.queuedMessageIDs), "promote target index out of range")
|
||||
require.Less(t, targetIdx, len(seeded.queuedMessageIDs), "steer target index out of range")
|
||||
var err error
|
||||
result.promoteQueuedMessage, err = tx.PromoteQueuedMessage(chatstate.PromoteQueuedMessageInput{
|
||||
result.steerQueuedMessage, err = tx.SteerQueuedMessage(chatstate.SteerQueuedMessageInput{
|
||||
QueuedMessageID: seeded.queuedMessageIDs[targetIdx],
|
||||
})
|
||||
return err
|
||||
}
|
||||
spec := transitionCaseSpec{
|
||||
transition: chatstate.TransitionPromoteQueuedMessage,
|
||||
transition: chatstate.TransitionSteerQueuedMessage,
|
||||
from: from,
|
||||
want: want,
|
||||
scenario: sc,
|
||||
@@ -1757,160 +1744,87 @@ func promoteQueuedCase(from, want chatstate.ExecutionState, shape queueShape, ta
|
||||
assert: func(ctx context.Context, t *testing.T, f *testFixture, seeded seededChat, base snapshotBaseline, result transitionCaseResult) {
|
||||
after, err := f.DB.GetChatByID(ctx, seeded.chatID)
|
||||
require.NoError(t, err)
|
||||
afterHistory := activeHistoryIDs(ctx, t, f, seeded.chatID)
|
||||
afterQueueIDs := queuedIDsByPosition(ctx, t, f, seeded.chatID)
|
||||
afterQueue := int64(len(afterQueueIDs))
|
||||
require.Less(t, targetIdx, len(base.queueRows))
|
||||
target := base.queueRows[targetIdx]
|
||||
targetMoves := target.BusyBehavior == database.ChatBusyBehaviorQueue
|
||||
|
||||
require.NotEmpty(t, seeded.queuedMessageIDs)
|
||||
require.Less(t, targetIdx, len(seeded.queuedMessageIDs))
|
||||
targetID := seeded.queuedMessageIDs[targetIdx]
|
||||
require.Equal(t, targetID, result.promoteQueuedMessage.QueuedMessage.ID,
|
||||
"PromoteQueuedMessage returns the targeted queued message")
|
||||
var steerLane []int
|
||||
for i, row := range base.queueRows {
|
||||
if row.BusyBehavior == database.ChatBusyBehaviorSteer {
|
||||
steerLane = append(steerLane, i)
|
||||
}
|
||||
}
|
||||
if targetMoves {
|
||||
steerLane = append(steerLane, targetIdx)
|
||||
}
|
||||
// E1, E1P, and P deliver the steer lane up to the first row
|
||||
// still under edit. The target's own edit has ended.
|
||||
var delivered []int
|
||||
if from == chatstate.StateE1 || from == chatstate.StateE1P || from == chatstate.StateP {
|
||||
for _, i := range steerLane {
|
||||
if i != targetIdx && base.queueRows[i].EditingSince.Valid {
|
||||
break
|
||||
}
|
||||
delivered = append(delivered, i)
|
||||
}
|
||||
}
|
||||
wantQueue := []int64{}
|
||||
for i, id := range base.queueIDs {
|
||||
if slices.Contains(delivered, i) || (targetMoves && i == targetIdx) {
|
||||
continue
|
||||
}
|
||||
wantQueue = append(wantQueue, id)
|
||||
}
|
||||
targetQueued := !slices.Contains(delivered, targetIdx)
|
||||
if targetMoves && targetQueued {
|
||||
wantQueue = append(wantQueue, target.ID)
|
||||
}
|
||||
|
||||
switch from {
|
||||
case chatstate.StateE1, chatstate.StateE1P, chatstate.StateA1, chatstate.StateA1P:
|
||||
// Head is popped into history.
|
||||
require.Equal(t, base.queueCount-1, afterQueue,
|
||||
"E1/A1 promote pops the head into history")
|
||||
if len(delivered) > 0 {
|
||||
require.Equal(t, database.ChatStatusRunning, after.Status,
|
||||
"E1/A1 promote lands in running")
|
||||
"steer delivery lands in running")
|
||||
require.False(t, after.LastError.Valid,
|
||||
"E1/A1 promote clears last_error")
|
||||
require.False(t, after.RequiresActionDeadlineAt.Valid,
|
||||
"E1/A1 promote clears requires_action_deadline_at")
|
||||
require.NotNil(t, result.promoteQueuedMessage.InsertedMessage,
|
||||
"E1/A1 promote inserts a user history message")
|
||||
inserted := requireChatMessageByID(ctx, t, f, result.promoteQueuedMessage.InsertedMessage.ID)
|
||||
require.Equal(t, seeded.chatID, inserted.ChatID)
|
||||
require.Equal(t, database.ChatMessageRoleUser, inserted.Role)
|
||||
require.True(t, inserted.ModelConfigID.Valid)
|
||||
require.Equal(t, f.Model.ID, inserted.ModelConfigID.UUID)
|
||||
require.Equal(t, chatprompt.CurrentContentVersion, inserted.ContentVersion)
|
||||
require.True(t, inserted.CreatedBy.Valid)
|
||||
require.Equal(t, result.promoteQueuedMessage.QueuedMessage.CreatedBy, inserted.CreatedBy.UUID,
|
||||
"promoted history message preserves queued created_by")
|
||||
if len(seeded.queuedMessageCreatedBy) > targetIdx {
|
||||
require.Equal(t, seeded.queuedMessageCreatedBy[targetIdx], inserted.CreatedBy.UUID,
|
||||
"promoted history message preserves non-owner queued creator")
|
||||
}
|
||||
require.NotEmpty(t, seeded.queuedMessageBodies,
|
||||
"E1/A1 seed must record queued message bodies")
|
||||
assertChatMessageText(t, inserted, seeded.queuedMessageBodies[targetIdx])
|
||||
requireQueuedMessageLink(t, inserted, targetID)
|
||||
requireQueuedMessageDeleted(ctx, t, f, seeded.chatID, targetID)
|
||||
wantRemaining := remainingExcluding(base.queueIDs, targetIdx)
|
||||
require.Equal(t, wantRemaining, afterQueueIDs,
|
||||
"E1/A1 promote leaves the remaining queue order intact")
|
||||
assertQueueBodiesInOrder(ctx, t, f, seeded.chatID,
|
||||
remainingBodiesExcluding(seeded.queuedMessageBodies, targetIdx))
|
||||
// A different row under edit keeps its marker; the
|
||||
// target's edit ended when it was promoted.
|
||||
assertQueueEditMarkers(ctx, t, f, seeded.chatID, seeded.editingQueuedID)
|
||||
// New active history adds exactly the inserted
|
||||
// user message plus any synthetic cancellations.
|
||||
newIDs := newActiveMessageIDs(base, afterHistory)
|
||||
require.Contains(t, newIDs, inserted.ID,
|
||||
"newly-active history contains the promoted user message")
|
||||
if from == chatstate.StateA1 || from == chatstate.StateA1P {
|
||||
// A1: every outstanding tool call must be
|
||||
// canceled before the promoted user message.
|
||||
require.Len(t, result.promoteQueuedMessage.CancellationMessages, len(seeded.pendingToolCallIDs),
|
||||
"A1 promote synthesizes one tool-result cancellation per outstanding call")
|
||||
gotIDs := make(map[string]bool)
|
||||
for _, cancelMsg := range result.promoteQueuedMessage.CancellationMessages {
|
||||
cancel := requireChatMessageByID(ctx, t, f, cancelMsg.ID)
|
||||
require.Less(t, cancel.ID, inserted.ID,
|
||||
"A1 promote inserts cancellations before the promoted user message")
|
||||
parts, err := chatprompt.ParseContent(cancel)
|
||||
require.NoError(t, err)
|
||||
for _, part := range parts {
|
||||
if part.Type != codersdk.ChatMessagePartTypeToolResult {
|
||||
continue
|
||||
}
|
||||
require.True(t, part.IsError,
|
||||
"A1 promote synthetic cancellation is marked as an error")
|
||||
gotIDs[part.ToolCallID] = true
|
||||
}
|
||||
}
|
||||
for _, callID := range seeded.pendingToolCallIDs {
|
||||
require.True(t, gotIDs[callID],
|
||||
"A1 promote cancels outstanding tool call %s", callID)
|
||||
}
|
||||
} else {
|
||||
require.Empty(t, result.promoteQueuedMessage.CancellationMessages,
|
||||
"E1 promote has no synthetic cancellations")
|
||||
}
|
||||
case chatstate.StateR1, chatstate.StateR1P, chatstate.StateI1, chatstate.StateI1P:
|
||||
// Reorder-only: status flips to interrupting, no
|
||||
// history insert, queue cardinality unchanged.
|
||||
require.Equal(t, base.queueCount, afterQueue,
|
||||
"R1/I1 promote leaves queue cardinality unchanged")
|
||||
require.Equal(t, database.ChatStatusInterrupting, after.Status,
|
||||
"R1/I1 promote lands in interrupting")
|
||||
require.Nil(t, result.promoteQueuedMessage.InsertedMessage,
|
||||
"R1/I1 promote must not insert a history message")
|
||||
require.Empty(t, result.promoteQueuedMessage.CancellationMessages,
|
||||
"R1/I1 promote has no synthetic cancellations")
|
||||
require.Equal(t, base.historyIDs, afterHistory,
|
||||
"R1/I1 promote leaves history unchanged")
|
||||
// Target must still be present, now at the head, and
|
||||
// ready: its own edit is ended, another row's edit
|
||||
// stays.
|
||||
queued := requireQueuedMessageByID(ctx, t, f, seeded.chatID, targetID)
|
||||
require.Equal(t, targetID, queued.ID)
|
||||
require.False(t, queued.EditingSince.Valid,
|
||||
"R1/I1 promote ends the target's edit")
|
||||
wantEditing := seeded.editingQueuedID
|
||||
if wantEditing == targetID {
|
||||
wantEditing = 0
|
||||
}
|
||||
assertQueueEditMarkers(ctx, t, f, seeded.chatID, wantEditing)
|
||||
require.NotEmpty(t, afterQueueIDs)
|
||||
require.Equal(t, targetID, afterQueueIDs[0],
|
||||
"R1/I1 promote brings the target to the queue head")
|
||||
require.NotEmpty(t, seeded.queuedMessageBodies,
|
||||
"R1/I1 seed must record queued message bodies")
|
||||
if targetIdx == 0 {
|
||||
// See scenarioHeadTarget.
|
||||
require.Equal(t, base.queueIDs, afterQueueIDs,
|
||||
"head-target promote preserves queue order")
|
||||
if seeded.editingQueuedID == targetID {
|
||||
require.Greater(t, after.QueueVersion, base.queueVersion,
|
||||
"head-target promote of a blocked head advances queue_version by ending its edit")
|
||||
} else {
|
||||
require.Equal(t, base.queueVersion, after.QueueVersion,
|
||||
"head-target promote leaves queue_version unchanged")
|
||||
}
|
||||
assertQueueBodiesInOrder(ctx, t, f, seeded.chatID, seeded.queuedMessageBodies)
|
||||
} else {
|
||||
// Non-head: target moves to the head, the rest
|
||||
// of the original order is preserved.
|
||||
wantQueue := append([]int64{targetID}, remainingExcluding(base.queueIDs, targetIdx)...)
|
||||
require.Equal(t, wantQueue, afterQueueIDs,
|
||||
"non-head promote moves the target to the head and preserves the rest")
|
||||
require.Greater(t, after.QueueVersion, base.queueVersion,
|
||||
"non-head promote advances queue_version")
|
||||
wantBodies := append([]string{seeded.queuedMessageBodies[targetIdx]},
|
||||
remainingBodiesExcluding(seeded.queuedMessageBodies, targetIdx)...)
|
||||
assertQueueBodiesInOrder(ctx, t, f, seeded.chatID, wantBodies)
|
||||
"steer delivery clears last_error")
|
||||
inserted := result.steerQueuedMessage.InsertedMessages
|
||||
assertPromotedRows(ctx, t, f, seeded, base, inserted, delivered)
|
||||
insertedIDs := make([]int64, len(inserted))
|
||||
for i, msg := range inserted {
|
||||
insertedIDs[i] = msg.ID
|
||||
}
|
||||
require.Equal(t, insertedIDs, newActiveMessageIDs(base, activeHistoryIDs(ctx, t, f, seeded.chatID)),
|
||||
"steer delivers the steer lane in order")
|
||||
require.False(t, result.steerQueuedMessage.PromotedQueuedAt.IsZero(),
|
||||
"steer delivery reports the first delivered row's queued time")
|
||||
} else {
|
||||
require.Equal(t, base.chat.Status, after.Status,
|
||||
"steer without delivery keeps the status")
|
||||
require.Empty(t, result.steerQueuedMessage.InsertedMessages,
|
||||
"steer without delivery inserts nothing")
|
||||
require.Equal(t, base.historyIDs, activeHistoryIDs(ctx, t, f, seeded.chatID),
|
||||
"steer without delivery leaves history unchanged")
|
||||
}
|
||||
require.Equal(t, wantQueue, queuedIDsByPosition(ctx, t, f, seeded.chatID),
|
||||
"the target moves to the end of the queue and the other rows keep their order")
|
||||
wantEditing := seeded.editingQueuedID
|
||||
if wantEditing == target.ID {
|
||||
wantEditing = 0
|
||||
}
|
||||
assertQueueEditMarkers(ctx, t, f, seeded.chatID, wantEditing)
|
||||
if targetQueued {
|
||||
queued := requireQueuedMessageByID(ctx, t, f, seeded.chatID, target.ID)
|
||||
require.Equal(t, database.ChatBusyBehaviorSteer, queued.BusyBehavior,
|
||||
"the target is a steer row")
|
||||
}
|
||||
if targetMoves || target.EditingSince.Valid || len(delivered) > 0 {
|
||||
require.Greater(t, after.QueueVersion, base.queueVersion,
|
||||
"steer advances queue_version when the queue changes")
|
||||
} else {
|
||||
require.Equal(t, base.queueVersion, after.QueueVersion,
|
||||
"steering a steer row changes nothing in the queue")
|
||||
}
|
||||
},
|
||||
}
|
||||
switch {
|
||||
case from == chatstate.StateA1 || from == chatstate.StateA1P:
|
||||
seed := func(t *testing.T, f *testFixture, _ chatstate.ExecutionState) seededChat {
|
||||
queuedExtras := 1
|
||||
if shape.isMulti() {
|
||||
queuedExtras = 2
|
||||
}
|
||||
return seedA1WithMixedOutstandingToolCalls(t, f, queuedExtras, "seed_tool_a1_promote")
|
||||
}
|
||||
if from == chatstate.StateA1P {
|
||||
seed = withEditingRow(seed, 0)
|
||||
}
|
||||
spec.seed = seed
|
||||
case shape.isMulti():
|
||||
if shape.isMulti() {
|
||||
spec.seed = func(t *testing.T, f *testFixture, _ chatstate.ExecutionState) seededChat {
|
||||
return seedStateMultiQueued(t, f, from)
|
||||
}
|
||||
@@ -2317,7 +2231,6 @@ func finishInterruptionRejectsOutstandingToolCallCase() transitionCaseSpec {
|
||||
exists: true,
|
||||
initialUserMessageID: firstUserMessageID(ctx, t, f, created.Chat.ID),
|
||||
assistantToolCallMsgID: firstAssistantMessageID(ctx, t, f, created.Chat.ID),
|
||||
pendingToolCallIDs: []string{nonDynCallID},
|
||||
}
|
||||
},
|
||||
apply: applyFinishInterruption,
|
||||
|
||||
@@ -166,7 +166,7 @@ func TestCreateChat_AllowsNonFinalUserMessage(t *testing.T) {
|
||||
require.Len(t, res.InitialMessages, 2)
|
||||
}
|
||||
|
||||
func TestPromoteQueuedMessageResolvesOrganizationModel(t *testing.T) {
|
||||
func TestSteerQueuedMessageResolvesOrganizationModel(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("local model remains selected", func(t *testing.T) {
|
||||
@@ -175,7 +175,7 @@ func TestPromoteQueuedMessageResolvesOrganizationModel(t *testing.T) {
|
||||
localModel := dbgen.ChatModelConfig(t, f.DB, database.ChatModelConfig{
|
||||
OrganizationID: f.Org.ID,
|
||||
})
|
||||
promoted := promoteQueuedMessageWithModel(t, f, localModel.ID)
|
||||
promoted := steerQueuedMessageWithModel(t, f, localModel.ID)
|
||||
require.Equal(t, localModel.ID, promoted.ModelConfigID.UUID)
|
||||
})
|
||||
|
||||
@@ -187,14 +187,14 @@ func TestPromoteQueuedMessageResolvesOrganizationModel(t *testing.T) {
|
||||
OrganizationID: foreignOrg.ID,
|
||||
IsDefault: true,
|
||||
})
|
||||
promoted := promoteQueuedMessageWithModel(t, f, foreignModel.ID)
|
||||
promoted := steerQueuedMessageWithModel(t, f, foreignModel.ID)
|
||||
require.Equal(t, f.Model.ID, promoted.ModelConfigID.UUID)
|
||||
})
|
||||
|
||||
t.Run("missing model falls back to local default", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
f := newTestFixture(t)
|
||||
promoted := promoteQueuedMessageWithModel(t, f, uuid.New())
|
||||
promoted := steerQueuedMessageWithModel(t, f, uuid.New())
|
||||
require.Equal(t, f.Model.ID, promoted.ModelConfigID.UUID)
|
||||
})
|
||||
|
||||
@@ -205,7 +205,7 @@ func TestPromoteQueuedMessageResolvesOrganizationModel(t *testing.T) {
|
||||
OrganizationID: f.Org.ID,
|
||||
})
|
||||
setChatModelConfigEnabled(t, f.DB, disabled, false)
|
||||
promoted := promoteQueuedMessageWithModel(t, f, disabled.ID)
|
||||
promoted := steerQueuedMessageWithModel(t, f, disabled.ID)
|
||||
require.Equal(t, f.Model.ID, promoted.ModelConfigID.UUID)
|
||||
})
|
||||
|
||||
@@ -226,7 +226,7 @@ func TestPromoteQueuedMessageResolvesOrganizationModel(t *testing.T) {
|
||||
}))
|
||||
|
||||
err := machine.Update(ctx, func(tx *chatstate.Tx, _ database.Store) error {
|
||||
_, err := tx.PromoteQueuedMessage(chatstate.PromoteQueuedMessageInput{
|
||||
_, err := tx.SteerQueuedMessage(chatstate.SteerQueuedMessageInput{
|
||||
QueuedMessageID: queued.QueuedMessage.ID,
|
||||
})
|
||||
return err
|
||||
@@ -254,7 +254,7 @@ func TestPromoteQueuedMessageResolvesOrganizationModel(t *testing.T) {
|
||||
failingStore := &modelConfigErrorStore{Store: f.DB, err: queryErr}
|
||||
machine = chatstate.NewChatMachine(failingStore, f.Pub, created.Chat.ID)
|
||||
err := machine.Update(ctx, func(tx *chatstate.Tx, _ database.Store) error {
|
||||
_, err := tx.PromoteQueuedMessage(chatstate.PromoteQueuedMessageInput{
|
||||
_, err := tx.SteerQueuedMessage(chatstate.SteerQueuedMessageInput{
|
||||
QueuedMessageID: queued.QueuedMessage.ID,
|
||||
})
|
||||
return err
|
||||
@@ -264,6 +264,111 @@ func TestPromoteQueuedMessageResolvesOrganizationModel(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestSteerQueuedMessageLaneOrder(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
queue, steer := chatstate.BusyBehaviorQueue, chatstate.BusyBehaviorSteer
|
||||
cases := []struct {
|
||||
name string
|
||||
from chatstate.ExecutionState
|
||||
behaviors []chatstate.BusyBehavior
|
||||
|
||||
steered []int
|
||||
|
||||
finish bool
|
||||
wantHistory []int
|
||||
wantQueue []int
|
||||
}{
|
||||
{
|
||||
name: "steered queue rows follow the waiting steer row",
|
||||
from: chatstate.StateR1,
|
||||
behaviors: []chatstate.BusyBehavior{queue, queue, queue, steer},
|
||||
steered: []int{0, 2},
|
||||
finish: true,
|
||||
wantHistory: []int{3, 0, 2},
|
||||
wantQueue: []int{1},
|
||||
},
|
||||
{
|
||||
name: "steered steer row keeps its place",
|
||||
from: chatstate.StateR1,
|
||||
behaviors: []chatstate.BusyBehavior{steer, steer},
|
||||
steered: []int{0},
|
||||
finish: true,
|
||||
wantHistory: []int{0, 1},
|
||||
wantQueue: []int{},
|
||||
},
|
||||
{
|
||||
name: "owned interrupting chat delivers the whole steer lane",
|
||||
from: chatstate.StateI1,
|
||||
behaviors: []chatstate.BusyBehavior{queue, steer, queue},
|
||||
steered: []int{2},
|
||||
finish: true,
|
||||
wantHistory: []int{1, 2},
|
||||
wantQueue: []int{0},
|
||||
},
|
||||
{
|
||||
name: "errored chat delivers the steer lane at once",
|
||||
from: chatstate.StateE1,
|
||||
behaviors: []chatstate.BusyBehavior{queue, steer},
|
||||
steered: []int{0},
|
||||
wantHistory: []int{1, 0},
|
||||
wantQueue: []int{},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
f := newTestFixture(t)
|
||||
ctx := testutil.Context(t, testutil.WaitShort)
|
||||
seeded := seedQueue(t, f, tc.from, tc.behaviors...)
|
||||
m := chatstate.NewChatMachine(f.DB, f.Pub, seeded.chatID)
|
||||
historyBefore := activeHistoryIDs(ctx, t, f, seeded.chatID)
|
||||
|
||||
for _, idx := range tc.steered {
|
||||
require.NoError(t, m.Update(ctx, func(tx *chatstate.Tx, _ database.Store) error {
|
||||
_, err := tx.SteerQueuedMessage(chatstate.SteerQueuedMessageInput{
|
||||
QueuedMessageID: seeded.queuedMessageIDs[idx],
|
||||
})
|
||||
return err
|
||||
}))
|
||||
}
|
||||
if tc.finish {
|
||||
if tc.from == chatstate.StateR1 {
|
||||
require.NoError(t, m.Update(ctx, func(tx *chatstate.Tx, store database.Store) error {
|
||||
if err := ownChat(ctx, tx, store, seeded.chatID); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Interrupt(chatstate.InterruptInput{Reason: "test"})
|
||||
return err
|
||||
}))
|
||||
}
|
||||
require.NoError(t, m.Update(ctx, func(tx *chatstate.Tx, _ database.Store) error {
|
||||
_, err := tx.FinishInterruption(chatstate.FinishInterruptionInput{})
|
||||
return err
|
||||
}))
|
||||
}
|
||||
|
||||
var gotHistory []int64
|
||||
for _, id := range activeHistoryIDs(ctx, t, f, seeded.chatID)[len(historyBefore):] {
|
||||
msg := requireChatMessageByID(ctx, t, f, id)
|
||||
require.True(t, msg.QueuedMessageID.Valid, "history message %d is not a queued row", id)
|
||||
gotHistory = append(gotHistory, msg.QueuedMessageID.Int64)
|
||||
}
|
||||
wantHistory := make([]int64, len(tc.wantHistory))
|
||||
for i, idx := range tc.wantHistory {
|
||||
wantHistory[i] = seeded.queuedMessageIDs[idx]
|
||||
}
|
||||
require.Equal(t, wantHistory, gotHistory, "queued rows reach history in lane order")
|
||||
|
||||
wantQueue := make([]int64, len(tc.wantQueue))
|
||||
for i, idx := range tc.wantQueue {
|
||||
wantQueue[i] = seeded.queuedMessageIDs[idx]
|
||||
}
|
||||
require.Equal(t, wantQueue, queuedIDsByPosition(ctx, t, f, seeded.chatID), "queue rows stay queued")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type modelConfigErrorStore struct {
|
||||
database.Store
|
||||
err error
|
||||
@@ -282,7 +387,7 @@ func (s *modelConfigErrorStore) GetEnabledChatModelConfigByID(
|
||||
return database.ChatModelConfig{}, s.err
|
||||
}
|
||||
|
||||
func promoteQueuedMessageWithModel(
|
||||
func steerQueuedMessageWithModel(
|
||||
t *testing.T,
|
||||
f *testFixture,
|
||||
modelConfigID uuid.UUID,
|
||||
@@ -305,16 +410,16 @@ func promoteQueuedMessageWithModel(
|
||||
return err
|
||||
}))
|
||||
|
||||
var result chatstate.PromoteQueuedMessageResult
|
||||
var result chatstate.SteerQueuedMessageResult
|
||||
require.NoError(t, machine.Update(ctx, func(tx *chatstate.Tx, _ database.Store) error {
|
||||
var err error
|
||||
result, err = tx.PromoteQueuedMessage(chatstate.PromoteQueuedMessageInput{
|
||||
result, err = tx.SteerQueuedMessage(chatstate.SteerQueuedMessageInput{
|
||||
QueuedMessageID: queued.ID,
|
||||
})
|
||||
return err
|
||||
}))
|
||||
require.NotNil(t, result.InsertedMessage)
|
||||
promoted := requireChatMessageByID(ctx, t, f, result.InsertedMessage.ID)
|
||||
require.Len(t, result.InsertedMessages, 1)
|
||||
promoted := requireChatMessageByID(ctx, t, f, result.InsertedMessages[0].ID)
|
||||
require.True(t, promoted.ModelConfigID.Valid)
|
||||
return promoted
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user