Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(chat): preserve visible queue-head ordering (MUL-5751) (#6431)

Multica Eve521a63671c85
diff --git a/server/internal/handler/chat_input_ownership_test.go b/server/internal/handler/chat_input_ownership_test.go
index 4884019b57..86ad691f68 100644
--- a/server/internal/handler/chat_input_ownership_test.go
+++ b/server/internal/handler/chat_input_ownership_test.go
@@ -60,6 +60,16 @@ func markTaskRunning(t *testing.T, ctx context.Context, taskID string) {
}
}
+func insertTaskTranscriptRow(t *testing.T, ctx context.Context, taskID string) {
+ t.Helper()
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_message (task_id, seq, type, content)
+ VALUES ($1, 1, 'text', 'partial output')
+ `, taskID); err != nil {
+ t.Fatalf("insert task transcript row: %v", err)
+ }
+}
+
func completeResult(t *testing.T, output string) []byte {
t.Helper()
b, err := json.Marshal(TaskCompleteRequest{Output: output})
@@ -120,11 +130,12 @@ func TestDirectChat_TaskOwnsItsOwnInputBatch(t *testing.T) {
}
// TestDirectChat_ClaimKeepsQueuedTurnsPairedWithReplies covers the follow-up
-// transcript regression from MUL-5751. The queued user rows are persisted
-// before the first assistant reply, but each row must enter the transcript
-// only when its own task is claimed, after the preceding reply. The same
-// server-authoritative order must drive both the legacy full list and every
-// cursor page.
+// transcript regression from MUL-5751. The idle positional head is visible
+// before claim, while later queued user rows remain hidden. When a predecessor
+// settles, its reply and the newly-visible follow-up must become atomically
+// ordered during the completion-to-claim window; claiming that already-visible
+// head must not move it again. The same server-authoritative order must drive
+// both the legacy full list and every cursor page.
func TestDirectChat_ClaimKeepsQueuedTurnsPairedWithReplies(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
@@ -136,16 +147,42 @@ func TestDirectChat_ClaimKeepsQueuedTurnsPairedWithReplies(t *testing.T) {
t2 := sendDirectChat(t, ctx, agentID, sessionID, "user B")
t3 := sendDirectChat(t, ctx, agentID, sessionID, "user C")
+ inputABeforeClaim, err := testHandler.Queries.ListChatInputMessages(ctx, parseUUID(t1))
+ if err != nil || len(inputABeforeClaim) != 1 {
+ t.Fatalf("load A input before claim: messages=%+v err=%v", inputABeforeClaim, err)
+ }
+ transcript, err := testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("list transcript before claiming A: %v", err)
+ }
+ assertChatTranscriptContents(t, transcript, []string{"user A"})
+
claimTaskForRuntimeGuard(t, runtimeID, daemonID)
+ inputAAfterClaim, err := testHandler.Queries.ListChatInputMessages(ctx, parseUUID(t1))
+ if err != nil || len(inputAAfterClaim) != 1 {
+ t.Fatalf("load A input after claim: messages=%+v err=%v", inputAAfterClaim, err)
+ }
+ if !inputAAfterClaim[0].CreatedAt.Time.Equal(inputABeforeClaim[0].CreatedAt.Time) {
+ t.Fatalf("claim moved already-visible A from %s to %s", inputABeforeClaim[0].CreatedAt.Time, inputAAfterClaim[0].CreatedAt.Time)
+ }
markTaskRunning(t, ctx, t1)
if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "assistant A"), "", "", false, ""); err != nil {
t.Fatalf("complete turn A: %v", err)
}
+ transcript, err = testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("list transcript before claiming B: %v", err)
+ }
+ assertChatTranscriptContents(t, transcript, []string{"user A", "assistant A", "user B"})
queuedBeforeClaim, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(t2))
if err != nil {
t.Fatalf("load queued turn B: %v", err)
}
+ inputBBeforeClaim, err := testHandler.Queries.ListChatInputMessages(ctx, parseUUID(t2))
+ if err != nil || len(inputBBeforeClaim) != 1 {
+ t.Fatalf("load B input before claim: messages=%+v err=%v", inputBBeforeClaim, err)
+ }
claimTaskForRuntimeGuard(t, runtimeID, daemonID)
claimedAfter, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(t2))
if err != nil {
@@ -154,8 +191,15 @@ func TestDirectChat_ClaimKeepsQueuedTurnsPairedWithReplies(t *testing.T) {
if !claimedAfter.CreatedAt.Time.Equal(queuedBeforeClaim.CreatedAt.Time) {
t.Fatalf("claim changed task queue created_at from %s to %s", queuedBeforeClaim.CreatedAt.Time, claimedAfter.CreatedAt.Time)
}
+ inputBAfterClaim, err := testHandler.Queries.ListChatInputMessages(ctx, parseUUID(t2))
+ if err != nil || len(inputBAfterClaim) != 1 {
+ t.Fatalf("load B input after claim: messages=%+v err=%v", inputBAfterClaim, err)
+ }
+ if !inputBAfterClaim[0].CreatedAt.Time.Equal(inputBBeforeClaim[0].CreatedAt.Time) {
+ t.Fatalf("claim moved already-visible B from %s to %s", inputBBeforeClaim[0].CreatedAt.Time, inputBAfterClaim[0].CreatedAt.Time)
+ }
- transcript, err := testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
+ transcript, err = testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
if err != nil {
t.Fatalf("list transcript after claiming B: %v", err)
}
@@ -198,6 +242,12 @@ func TestDirectChat_ClaimKeepsQueuedTurnsPairedWithReplies(t *testing.T) {
if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t2), completeResult(t, "assistant B"), "", "", false, ""); err != nil {
t.Fatalf("complete turn B: %v", err)
}
+ transcript, err = testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("list transcript before claiming C: %v", err)
+ }
+ assertChatTranscriptContents(t, transcript, []string{"user A", "assistant A", "user B", "assistant B", "user C"})
+
claimTaskForRuntimeGuard(t, runtimeID, daemonID)
transcript, err = testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
if err != nil {
@@ -470,6 +520,91 @@ func TestFailTask_ChatRetryInheritsInputOwnerAndPriority(t *testing.T) {
}
}
+// A non-retried failure is an assistant outcome just like a normal completion.
+// The failure row and the next queued head must commit in transcript order so
+// the successor cannot be claimed or rendered before the failure it follows.
+func TestFailTask_ChatFailureKeepsNextTurnAfterOutcome(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "failed turn order")
+ t1 := sendDirectChat(t, ctx, agentID, sessionID, "user A")
+ sendDirectChat(t, ctx, agentID, sessionID, "user B")
+ markTaskRunning(t, ctx, t1)
+
+ if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(t1), "assistant failure", "", "", "agent_error.unknown", false, ""); err != nil {
+ t.Fatalf("fail turn A: %v", err)
+ }
+ transcript, err := testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("list failed-turn transcript: %v", err)
+ }
+ assertChatTranscriptContents(t, transcript, []string{"user A", "assistant failure", "user B"})
+}
+
+// Cancellation finalization intentionally happens after the cancellation
+// transaction (#5219), so this test pins the eventual transcript order rather
+// than claiming cursor stability during that post-commit window. When output
+// is already durable, finalization is synchronous and the visible result must
+// still pair the cancelled turn with Stopped. before exposing its successor.
+func TestCancelTask_ChatStoppedKeepsNextTurnAfterOutcome(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "cancelled turn order")
+ t1 := sendDirectChat(t, ctx, agentID, sessionID, "user A")
+ sendDirectChat(t, ctx, agentID, sessionID, "user B")
+ markTaskRunning(t, ctx, t1)
+ insertTaskTranscriptRow(t, ctx, t1)
+
+ if _, err := testHandler.TaskService.CancelTaskWithResult(ctx, parseUUID(t1), service.CancelTaskOptions{ClientSupportsDraftRestore: true}); err != nil {
+ t.Fatalf("cancel turn A: %v", err)
+ }
+ transcript, err := testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("list synchronously cancelled transcript: %v", err)
+ }
+ assertChatTranscriptContents(t, transcript, []string{"user A", "Stopped.", "user B"})
+}
+
+// A started task with no durable output defers its empty/non-empty judgment
+// until the daemon ack or sweeper. During that intentional transient, the next
+// queued turn can be visible at its enqueue position. Once late output lands,
+// deferred finalization must produce the same stable final order as the
+// synchronous path.
+func TestCancelTask_DeferredStoppedKeepsNextTurnAfterOutcome(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "deferred cancelled turn order")
+ t1 := sendDirectChat(t, ctx, agentID, sessionID, "user A")
+ sendDirectChat(t, ctx, agentID, sessionID, "user B")
+ markTaskRunning(t, ctx, t1)
+
+ if _, err := testHandler.TaskService.CancelTaskWithResult(ctx, parseUUID(t1), service.CancelTaskOptions{ClientSupportsDraftRestore: true}); err != nil {
+ t.Fatalf("cancel turn A: %v", err)
+ }
+ transcript, err := testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("list deferred cancellation transient: %v", err)
+ }
+ assertChatTranscriptContents(t, transcript, []string{"user A", "user B"})
+
+ // Simulate output flushed after the cancellation commit, then settle the
+ // deferred marker as the daemon acknowledgement or sweeper would.
+ insertTaskTranscriptRow(t, ctx, t1)
+ testHandler.TaskService.FinalizeDeferredCancelledChat(ctx, parseUUID(t1))
+
+ transcript, err = testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("list deferred cancelled transcript: %v", err)
+ }
+ assertChatTranscriptContents(t, transcript, []string{"user A", "Stopped.", "user B"})
+}
+
// ---- helpers ----
func msgContents(msgs []db.ChatMessage) []string {
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 5f682dc28e..fa27f40904 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2173,6 +2173,32 @@ func chatInputOwnerID(task db.AgentTaskQueue) pgtype.UUID {
return task.ID
}
+// createAssistantChatMessage writes an assistant outcome and reanchors the
+// newly-visible queued direct head in the caller's transaction. Keeping the two
+// statements together is the transcript-order boundary: readers must not see
+// the reply commit while the next head still carries its older enqueue time.
+// The caller MUST observe the settling task outside the visible-head status set
+// before invoking this helper; completion and failure settle it earlier in the
+// same transaction, while cancellation commits that status in its prior
+// transaction (#5219). Otherwise the head query still selects the settling task
+// and reanchoring its successor is a no-op.
+func createAssistantChatMessage(ctx context.Context, qtx *db.Queries, params db.CreateChatMessageParams) (db.ChatMessage, error) {
+ if params.Role != "assistant" {
+ return db.ChatMessage{}, fmt.Errorf("create assistant chat message: invalid role %q", params.Role)
+ }
+ row, err := qtx.CreateChatMessage(ctx, params)
+ if err != nil {
+ return db.ChatMessage{}, err
+ }
+ if err := qtx.ReanchorNextQueuedDirectChatInput(ctx, db.ReanchorNextQueuedDirectChatInputParams{
+ AssistantCreatedAt: row.CreatedAt,
+ ChatSessionID: row.ChatSessionID,
+ }); err != nil {
+ return db.ChatMessage{}, fmt.Errorf("reanchor next queued direct chat input: %w", err)
+ }
+ return row, nil
+}
+
func (s *TaskService) settleQueuedChatInput(
ctx context.Context,
qtx *db.Queries,
@@ -2188,7 +2214,7 @@ func (s *TaskService) settleQueuedChatInput(
return nil, fmt.Errorf("check queued chat channel provenance: %w", err)
}
if channelIngested {
- if _, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ if _, err := createAssistantChatMessage(ctx, qtx, db.CreateChatMessageParams{
ChatSessionID: task.ChatSessionID,
Role: "assistant",
Content: "Stopped.",
@@ -2320,7 +2346,7 @@ func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.
}
return nil
}
- if _, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ if _, err := createAssistantChatMessage(ctx, qtx, db.CreateChatMessageParams{
ChatSessionID: task.ChatSessionID,
Role: "assistant",
Content: "Stopped.",
@@ -2454,7 +2480,7 @@ func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID
payload.MessageID = util.UUIDToString(deleted.ID)
return nil
}
- row, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ row, err := createAssistantChatMessage(ctx, qtx, db.CreateChatMessageParams{
ChatSessionID: claimed.ChatSessionID,
Role: "assistant",
Content: "Stopped.",
@@ -2507,13 +2533,11 @@ func (s *TaskService) broadcastChatCancelFinalized(ctx context.Context, task db.
// respecting max_concurrent_tasks.
func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.AgentTaskQueue, error) {
start := time.Now()
- var (
- outcome = "unknown"
- getAgentMs, countRunningMs, claimAgentMs, updateStatusMs, dispatchMs int64
- claimed *db.AgentTaskQueue
- )
+ outcome := "unknown"
+ var getAgentMs, countRunningMs, claimAgentMs, reanchorMs, updateStatusMs, dispatchMs int64
+ var claimed *db.AgentTaskQueue
defer func() {
- s.maybeLogClaimSlow(agentID, outcome, start, getAgentMs, countRunningMs, claimAgentMs, updateStatusMs, dispatchMs)
+ s.maybeLogClaimSlow(agentID, outcome, start, getAgentMs, countRunningMs, claimAgentMs, reanchorMs, updateStatusMs, dispatchMs)
}()
err := s.runInTx(ctx, func(qtx *db.Queries) error {
@@ -2554,21 +2578,25 @@ func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.A
return fmt.Errorf("claim task: %w", err)
}
- // A task-owned direct-chat user row is written when the user enqueues
- // it, but stays hidden until this queued -> dispatched transition. Move
- // its transcript timestamp inside the same transaction as the claim so
- // every full-list and cursor reader observes either hidden+queued or
- // visible+reanchored, never an intermediate state. Retry children keep
- // the root input owner and stale-dispatch reclaim uses a separate query,
- // so neither path can move an already-visible user turn again.
- if task.ChatSessionID.Valid && task.ChatInputTaskID == task.ID {
+ // An idle task-owned direct-chat row may already be visible as the
+ // positional queue head. Normal completion reanchors a successor beside
+ // the assistant outcome before commit; this claim-time query is the
+ // compatibility fallback for an older or otherwise out-of-order row.
+ // It only moves that row inside the claim transaction, so full-list and
+ // cursor readers see the corrected boundary once it is dispatched. Retry
+ // children keep the root input owner and stale-dispatch reclaim uses a
+ // separate query, so neither path moves an already-visible turn again.
+ if task.ChatSessionID.Valid && task.ChatInputTaskID.Valid && task.ChatInputTaskID == task.ID {
+ t0 = time.Now()
if err := qtx.ReanchorClaimedDirectChatInput(ctx, db.ReanchorClaimedDirectChatInputParams{
DispatchedAt: task.DispatchedAt,
TaskID: task.ID,
}); err != nil {
+ reanchorMs = time.Since(t0).Milliseconds()
outcome = "error_reanchor_chat_input"
return fmt.Errorf("reanchor claimed direct chat input: %w", err)
}
+ reanchorMs = time.Since(t0).Milliseconds()
}
claimedTask := task
@@ -2993,7 +3021,7 @@ func (s *TaskService) PromoteDueDeferredTasksForRuntime(ctx context.Context, run
// logs at normal poll rates. Called via defer so it captures the full path
// including post-claim updateAgentStatus / broadcastTaskDispatch (both of
// which can hit the DB) and any error exit.
-func (s *TaskService) maybeLogClaimSlow(agentID pgtype.UUID, outcome string, start time.Time, getAgentMs, countRunningMs, claimAgentMs, updateStatusMs, dispatchMs int64) {
+func (s *TaskService) maybeLogClaimSlow(agentID pgtype.UUID, outcome string, start time.Time, getAgentMs, countRunningMs, claimAgentMs, reanchorMs, updateStatusMs, dispatchMs int64) {
totalMs := time.Since(start).Milliseconds()
if totalMs < 300 {
return
@@ -3005,6 +3033,7 @@ func (s *TaskService) maybeLogClaimSlow(agentID pgtype.UUID, outcome string, sta
"get_agent_ms", getAgentMs,
"count_running_ms", countRunningMs,
"claim_agent_ms", claimAgentMs,
+ "reanchor_chat_input_ms", reanchorMs,
"update_status_ms", updateStatusMs,
"dispatch_ms", dispatchMs,
)
@@ -3423,7 +3452,7 @@ func (s *TaskService) writeChatCompletionOutcome(ctx context.Context, qtx *db.Qu
params.Content = chatNoResponseFallback
params.MessageKind = pgtype.Text{String: protocol.ChatMessageKindNoResponse, Valid: true}
}
- row, err := qtx.CreateChatMessage(ctx, params)
+ row, err := createAssistantChatMessage(ctx, qtx, params)
if err != nil {
return nil, err
}
@@ -3659,6 +3688,24 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
}
retried = &child
}
+
+ // A terminal non-retried chat failure is a visible assistant outcome.
+ // Persist it while the session lock and failure transaction are still
+ // held, then reanchor the next direct head. Otherwise the successor could
+ // be claimed between the status flip and this row, placing its user input
+ // before the failure it follows.
+ if t.ChatSessionID.Valid && retried == nil {
+ if _, err := createAssistantChatMessage(ctx, qtx, db.CreateChatMessageParams{
+ ChatSessionID: t.ChatSessionID,
+ Role: "assistant",
+ Content: redact.Text(errMsg),
+ TaskID: t.ID,
+ FailureReason: pgtype.Text{String: failureReason, Valid: failureReason != ""},
+ ElapsedMs: computeChatElapsedMs(t),
+ }); err != nil {
+ return fmt.Errorf("write chat failure outcome: %w", err)
+ }
+ }
return nil
}); err != nil {
if existing, lookupErr := s.Queries.GetAgentTask(ctx, taskID); lookupErr == nil {
@@ -3719,27 +3766,6 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
s.createAgentComment(ctx, task.IssueID, task.AgentID, redact.Text(errMsg), "system", task.TriggerCommentID, task.ID)
}
- // Mirror the issue fallback for chat tasks: write an assistant
- // chat_message tagged with the daemon-reported failure_reason so the
- // conversation history shows what happened. Skip when auto-retry is
- // pending (the new attempt will write its own outcome) — same guard as
- // the issue path above.
- if task.ChatSessionID.Valid && retried == nil {
- if _, err := s.Queries.CreateChatMessage(ctx, db.CreateChatMessageParams{
- ChatSessionID: task.ChatSessionID,
- Role: "assistant",
- Content: redact.Text(errMsg),
- TaskID: pgtype.UUID{Bytes: task.ID.Bytes, Valid: true},
- FailureReason: pgtype.Text{String: failureReason, Valid: failureReason != ""},
- ElapsedMs: computeChatElapsedMs(task),
- }); err != nil {
- slog.Error("failed to save failure chat message",
- "task_id", util.UUIDToString(task.ID),
- "chat_session_id", util.UUIDToString(task.ChatSessionID),
- "error", err)
- }
- }
-
// Quick-create tasks: push a failure inbox notification to the
// requester so they can either retry or fall back to the advanced form
// without losing their original prompt. Skipped when an auto-retry is
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index ac67c2ab6e..b447b869d2 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -1379,6 +1379,7 @@ ORDER BY message.created_at ASC, message.id ASC
// IMPORTANT: the visible-head selector below is also used by
// ListChatMessagesForLegacyTask, ListChatMessagesPage,
+// ReanchorClaimedDirectChatInput, ReanchorNextQueuedDirectChatInput,
// ListPendingChatTasksForSession, and CancelQueuedAgentTasksForSession in
// agent.sql. Keep the eligible statuses and ordering identical: a claimed task
// is current, a deferred retry precedes still-queued work, and queued peers use
@@ -2174,11 +2175,14 @@ func (q *Queries) PromoteChannelChatTasksIfMediaReady(ctx context.Context, chatS
}
const reanchorClaimedDirectChatInput = `-- name: ReanchorClaimedDirectChatInput :exec
-UPDATE chat_message AS claimed_input
-SET created_at = GREATEST(
- $1::timestamptz,
- COALESCE((
- SELECT prior.created_at + interval '1 microsecond'
+WITH latest_visible AS (
+ SELECT
+ claimed_input.id AS claimed_input_id,
+ claimed_input.created_at AS input_created_at,
+ prior.created_at AS prior_created_at
+ FROM chat_message AS claimed_input
+ CROSS JOIN LATERAL (
+ SELECT prior.created_at
FROM chat_message AS prior
WHERE prior.chat_session_id = claimed_input.chat_session_id
AND prior.id != claimed_input.id
@@ -2190,15 +2194,40 @@ SET created_at = GREATEST(
WHERE queued_task.chat_session_id = prior.chat_session_id
AND queued_task.status = 'queued'
AND queued_task.id = prior.task_id
+ AND queued_task.id <> (
+ SELECT head.id
+ FROM agent_task_queue AS head
+ WHERE head.chat_session_id = claimed_input.chat_session_id
+ AND head.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+ AND head.regenerate_quick_actions_for IS NULL
+ ORDER BY
+ CASE
+ WHEN head.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0
+ WHEN head.status = 'deferred' THEN 1
+ ELSE 2
+ END,
+ head.priority DESC,
+ head.created_at ASC,
+ head.id ASC
+ LIMIT 1
+ )
)
)
ORDER BY prior.created_at DESC, prior.id DESC
LIMIT 1
- ), $1::timestamptz)
+ ) AS prior
+ WHERE claimed_input.task_id = $2
+ AND claimed_input.role = 'user'
+ AND NOT claimed_input.channel_ingested
+)
+UPDATE chat_message AS claimed_input
+SET created_at = GREATEST(
+ $1::timestamptz,
+ latest_visible.prior_created_at + interval '1 microsecond'
)
-WHERE claimed_input.task_id = $2
- AND claimed_input.role = 'user'
- AND NOT claimed_input.channel_ingested
+FROM latest_visible
+WHERE claimed_input.id = latest_visible.claimed_input_id
+ AND latest_visible.prior_created_at >= latest_visible.input_created_at
`
type ReanchorClaimedDirectChatInputParams struct {
@@ -2206,10 +2235,12 @@ type ReanchorClaimedDirectChatInputParams struct {
TaskID pgtype.UUID `json:"task_id"`
}
-// A direct follow-up is persisted at enqueue time but hidden from the settled
-// transcript while its task remains queued. When that task is claimed, move
-// the user row to the claim boundary so it becomes visible after the previous
-// assistant outcome instead of jumping back to its original enqueue time.
+// An idle direct send is visible while it is the positional queue head. A
+// older/pre-deploy follow-up whose enqueue timestamp puts it before a newer
+// settled reply can still reach claim; this is the fallback that moves only
+// that out-of-order user row to the new turn boundary. In-order visible heads
+// keep their original timestamp, so an idle send already returned to a cursor
+// client never moves merely because a daemon claimed it.
//
// The task's own created_at remains immutable and continues to drive queue
// FIFO, wait duration, and elapsed time. Only the message timestamp changes,
@@ -2218,15 +2249,75 @@ type ReanchorClaimedDirectChatInputParams struct {
// ordering can never put the new user turn before the previous assistant row.
//
// channel_ingested excludes sealed Slack/Lark batches, which can own multiple
-// user rows and must preserve their original provider order. Retry children
-// are excluded by the caller because their chat_input_task_id names the root
-// task rather than themselves. Stale dispatched reclaim bypasses this query,
-// so re-delivery does not move an already-visible turn.
+// user rows and must preserve their original provider order. A direct send
+// owns exactly one non-channel user row today; if direct batching is added,
+// this query must assign a stable per-row offset instead of one timestamp.
+// Retry children are excluded by the caller because their chat_input_task_id
+// names the root task rather than themselves. Stale dispatched reclaim bypasses
+// this query, so re-delivery does not move an already-visible turn.
+//
+// Lock order is task row first (ClaimAgentTask), then this non-FK message-only
+// update. The visibility subqueries take no row locks, avoiding an inverse
+// message -> task lock edge with send/completion transactions.
func (q *Queries) ReanchorClaimedDirectChatInput(ctx context.Context, arg ReanchorClaimedDirectChatInputParams) error {
_, err := q.db.Exec(ctx, reanchorClaimedDirectChatInput, arg.DispatchedAt, arg.TaskID)
return err
}
+const reanchorNextQueuedDirectChatInput = `-- name: ReanchorNextQueuedDirectChatInput :exec
+UPDATE chat_message AS queued_input
+SET created_at = $2::timestamptz + interval '1 microsecond'
+WHERE queued_input.chat_session_id = $1
+ AND queued_input.role = 'user'
+ AND NOT queued_input.channel_ingested
+ AND queued_input.created_at <= $2::timestamptz
+ AND EXISTS (
+ SELECT 1
+ FROM agent_task_queue AS queued_task
+ WHERE queued_task.id = queued_input.task_id
+ AND queued_task.chat_session_id = queued_input.chat_session_id
+ AND queued_task.status = 'queued'
+ AND queued_task.chat_input_task_id = queued_task.id
+ AND queued_task.regenerate_quick_actions_for IS NULL
+ AND queued_task.id = (
+ SELECT head.id
+ FROM agent_task_queue AS head
+ WHERE head.chat_session_id = queued_input.chat_session_id
+ AND head.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+ AND head.regenerate_quick_actions_for IS NULL
+ ORDER BY
+ CASE
+ WHEN head.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0
+ WHEN head.status = 'deferred' THEN 1
+ ELSE 2
+ END,
+ head.priority DESC,
+ head.created_at ASC,
+ head.id ASC
+ LIMIT 1
+ )
+ )
+`
+
+type ReanchorNextQueuedDirectChatInputParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ AssistantCreatedAt pgtype.Timestamptz `json:"assistant_created_at"`
+}
+
+// An assistant outcome can make the next queued direct task the positional
+// head before a daemon claims it (MUL-5750). Its user row was persisted before
+// this reply, so move that still-hidden single-row input just after the reply.
+// Callers run this immediately after CreateChatMessage in the same transaction:
+// readers see either the old active head without the reply, or the settled
+// reply followed by the newly-visible head — never user B before assistant A.
+// Channel batches are excluded because their immutable provider ordering may
+// contain multiple user rows. Direct chat currently owns exactly one row; if
+// direct batching is added, assign stable per-row offsets here.
+func (q *Queries) ReanchorNextQueuedDirectChatInput(ctx context.Context, arg ReanchorNextQueuedDirectChatInputParams) error {
+ _, err := q.db.Exec(ctx, reanchorNextQueuedDirectChatInput, arg.ChatSessionID, arg.AssistantCreatedAt)
+ return err
+}
+
const setChatMessageQuickActionsByTask = `-- name: SetChatMessageQuickActionsByTask :one
UPDATE chat_message
SET quick_actions = $2
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index b68ba0a99f..bf06b2c491 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -451,6 +451,7 @@ RETURNING *;
-- name: ListChatMessages :many
-- IMPORTANT: the visible-head selector below is also used by
-- ListChatMessagesForLegacyTask, ListChatMessagesPage,
+-- ReanchorClaimedDirectChatInput, ReanchorNextQueuedDirectChatInput,
-- ListPendingChatTasksForSession, and CancelQueuedAgentTasksForSession in
-- agent.sql. Keep the eligible statuses and ordering identical: a claimed task
-- is current, a deferred retry precedes still-queued work, and queued peers use
@@ -538,10 +539,12 @@ WHERE task_id = $1 AND role = 'user'
ORDER BY created_at ASC, id ASC;
-- name: ReanchorClaimedDirectChatInput :exec
--- A direct follow-up is persisted at enqueue time but hidden from the settled
--- transcript while its task remains queued. When that task is claimed, move
--- the user row to the claim boundary so it becomes visible after the previous
--- assistant outcome instead of jumping back to its original enqueue time.
+-- An idle direct send is visible while it is the positional queue head. A
+-- older/pre-deploy follow-up whose enqueue timestamp puts it before a newer
+-- settled reply can still reach claim; this is the fallback that moves only
+-- that out-of-order user row to the new turn boundary. In-order visible heads
+-- keep their original timestamp, so an idle send already returned to a cursor
+-- client never moves merely because a daemon claimed it.
--
-- The task's own created_at remains immutable and continues to drive queue
-- FIFO, wait duration, and elapsed time. Only the message timestamp changes,
@@ -550,15 +553,24 @@ ORDER BY created_at ASC, id ASC;
-- ordering can never put the new user turn before the previous assistant row.
--
-- channel_ingested excludes sealed Slack/Lark batches, which can own multiple
--- user rows and must preserve their original provider order. Retry children
--- are excluded by the caller because their chat_input_task_id names the root
--- task rather than themselves. Stale dispatched reclaim bypasses this query,
--- so re-delivery does not move an already-visible turn.
-UPDATE chat_message AS claimed_input
-SET created_at = GREATEST(
- @dispatched_at::timestamptz,
- COALESCE((
- SELECT prior.created_at + interval '1 microsecond'
+-- user rows and must preserve their original provider order. A direct send
+-- owns exactly one non-channel user row today; if direct batching is added,
+-- this query must assign a stable per-row offset instead of one timestamp.
+-- Retry children are excluded by the caller because their chat_input_task_id
+-- names the root task rather than themselves. Stale dispatched reclaim bypasses
+-- this query, so re-delivery does not move an already-visible turn.
+--
+-- Lock order is task row first (ClaimAgentTask), then this non-FK message-only
+-- update. The visibility subqueries take no row locks, avoiding an inverse
+-- message -> task lock edge with send/completion transactions.
+WITH latest_visible AS (
+ SELECT
+ claimed_input.id AS claimed_input_id,
+ claimed_input.created_at AS input_created_at,
+ prior.created_at AS prior_created_at
+ FROM chat_message AS claimed_input
+ CROSS JOIN LATERAL (
+ SELECT prior.created_at
FROM chat_message AS prior
WHERE prior.chat_session_id = claimed_input.chat_session_id
AND prior.id != claimed_input.id
@@ -570,15 +582,83 @@ SET created_at = GREATEST(
WHERE queued_task.chat_session_id = prior.chat_session_id
AND queued_task.status = 'queued'
AND queued_task.id = prior.task_id
+ AND queued_task.id <> (
+ SELECT head.id
+ FROM agent_task_queue AS head
+ WHERE head.chat_session_id = claimed_input.chat_session_id
+ AND head.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+ AND head.regenerate_quick_actions_for IS NULL
+ ORDER BY
+ CASE
+ WHEN head.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0
+ WHEN head.status = 'deferred' THEN 1
+ ELSE 2
+ END,
+ head.priority DESC,
+ head.created_at ASC,
+ head.id ASC
+ LIMIT 1
+ )
)
)
ORDER BY prior.created_at DESC, prior.id DESC
LIMIT 1
- ), @dispatched_at::timestamptz)
+ ) AS prior
+ WHERE claimed_input.task_id = @task_id
+ AND claimed_input.role = 'user'
+ AND NOT claimed_input.channel_ingested
)
-WHERE claimed_input.task_id = @task_id
- AND claimed_input.role = 'user'
- AND NOT claimed_input.channel_ingested;
+UPDATE chat_message AS claimed_input
+SET created_at = GREATEST(
+ @dispatched_at::timestamptz,
+ latest_visible.prior_created_at + interval '1 microsecond'
+)
+FROM latest_visible
+WHERE claimed_input.id = latest_visible.claimed_input_id
+ AND latest_visible.prior_created_at >= latest_visible.input_created_at;
+
+-- name: ReanchorNextQueuedDirectChatInput :exec
+-- An assistant outcome can make the next queued direct task the positional
+-- head before a daemon claims it (MUL-5750). Its user row was persisted before
+-- this reply, so move that still-hidden single-row input just after the reply.
+-- Callers run this immediately after CreateChatMessage in the same transaction:
+-- readers see either the old active head without the reply, or the settled
+-- reply followed by the newly-visible head — never user B before assistant A.
+-- Channel batches are excluded because their immutable provider ordering may
+-- contain multiple user rows. Direct chat currently owns exactly one row; if
+-- direct batching is added, assign stable per-row offsets here.
+UPDATE chat_message AS queued_input
+SET created_at = sqlc.arg('assistant_created_at')::timestamptz + interval '1 microsecond'
+WHERE queued_input.chat_session_id = $1
+ AND queued_input.role = 'user'
+ AND NOT queued_input.channel_ingested
+ AND queued_input.created_at <= sqlc.arg('assistant_created_at')::timestamptz
+ AND EXISTS (
+ SELECT 1
+ FROM agent_task_queue AS queued_task
+ WHERE queued_task.id = queued_input.task_id
+ AND queued_task.chat_session_id = queued_input.chat_session_id
+ AND queued_task.status = 'queued'
+ AND queued_task.chat_input_task_id = queued_task.id
+ AND queued_task.regenerate_quick_actions_for IS NULL
+ AND queued_task.id = (
+ SELECT head.id
+ FROM agent_task_queue AS head
+ WHERE head.chat_session_id = queued_input.chat_session_id
+ AND head.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+ AND head.regenerate_quick_actions_for IS NULL
+ ORDER BY
+ CASE
+ WHEN head.status IN ('dispatched', 'running', 'waiting_local_directory') THEN 0
+ WHEN head.status = 'deferred' THEN 1
+ ELSE 2
+ END,
+ head.priority DESC,
+ head.created_at ASC,
+ head.id ASC
+ LIMIT 1
+ )
+ );
-- name: ListChatMessagesPage :many
SELECT message.* FROM chat_message AS message