Skip to content

feat: support safely editing queued chat messages - #29182

Closed
mafredri wants to merge 11 commits into
mainfrom
mathias/codagt-971-support-safely-editing-queued-chat-messages
Closed

mafredri wants to merge 11 commits into
mainfrom
mathias/codagt-971-support-safely-editing-queued-chat-messages

Conversation

@mafredri

Copy link
Copy Markdown
Member

Queued chat messages can be edited again. Client-only editing was removed in #28265 because the backend could promote the row into history while the user was typing (CODAGT-230). This PR makes the edit safe on the server: the owner holds the row before editing, and a held row cannot be promoted by the passive queue drain.

Model

A hold splits the queue. The first held row and every row behind it are invisible to the state machine's classifier, so FinishTurn, FinishInterruption, and the errored-chat auto-promote stop at that row while rows ahead of it drain in order. When the held row reaches the head, the chat lands in waiting and the runner lets go of it; nothing spins. Blocked-ness of later rows is derived from queue order, never stored.

Explicit actions go around the hold: a direct send on an idle chat inserts into history as before, and "send now" clears the target's hold and promotes it. busy_behavior=interrupt is unchanged and waits behind a held head.

This works without new states because the classifier's queue dimension changes from "the table has rows" to "the head exists and is not held" (chatstate.LoadQueueState). The previous attempt (#28516) hit StateInvalid because waiting with a non-empty queue is invalid; a held head classifies as an empty queue, so waiting with a held head is a valid idle state.

API

PATCH /api/v2/chats/{chat}/queue/{queuedMessage} with content?, model_config_id?, reasoning_effort?, held?. The client sends held:true before editing, {content, held:false} to save, {held:false} to cancel. Releasing the hold on a waiting chat promotes the row in the same transaction and the response carries the inserted history rows. ChatQueuedMessage gains held_at so every client renders the held row and the paused tail from the regular queue_update snapshot.

Two contract changes fall out of admitting queue transitions from the "0" states: an empty queue is a 404 (row not found) instead of a 409 for delete and promote, and deleting a held head from waiting promotes the row behind it.

Deviations from the plan

  • GetStaleChats checks the head row's held_at rather than EXISTS (... held_at IS NULL); the plan's predicate flagged a waiting chat with a held head and unheld rows behind it.
  • DeleteQueuedMessage from a "0" state can land in the "1" sibling (and from W promotes), which the plan's matrix omitted.
  • The queue listing (GetChatQueuedMessages) now orders by position like the state machine. The plan filed this as a separate bug, but the paused-tail rendering depends on the order, so it is fixed here as an isolated commit (8adea28b6c) that can be dropped.
  • Frontend: saving a queued edit restores the pre-edit draft (the row stays in the conversation, unlike a history edit). Edit and Resume are hidden for read-only viewers, matching history edit.

coderd/x/chatd/ARCHITECTURE.md carries TODO markers at the affected sections per the repo rule; the prose is for the human author.

Closes https://linear.app/codercom/issue/CODAGT-971

Implementation plan

CODAGT-971: safely editing queued chat messages

Status: design approved by the operator (Mathias) on 2026-09-10 after discussion in chat and in the Coder Agents Slack thread. All decisions below are final; nothing is left open. Implement on branch mathias/codagt-971-support-safely-editing-queued-chat-messages. Commits use type(scope): message; scope must be a real path containing every changed file.

Requirement: let the chat owner edit a queued message so that neither the stale text nor any message queued behind it can be promoted into history while the edit is open, without reordering the queue.

Code facts below were read from main at d8e3f4fcf7. Re-verify line numbers; symbol names are the anchor.

1. Current system

Execution state is a pure function of (status, archived, queue non-empty) in chatstate.ClassifyExecutionState (coderd/x/chatd/chatstate/state.go). waiting with a non-empty queue matches no case and falls to StateInvalid; Tx.requireFromAllowed (machine.go) then refuses every transition except ReconcileInvalidState, which parks the chat in error. The test case WaitingWithQueue in state_internal_test.go pins this. This is the wall the previous attempt (#28516) hit.

Promotion of the queue head is fused into turn boundaries inside one transaction under the chat row lock (ChatMachine.Update -> LockChatAndBumpSnapshotVersion), all in chatstate/transitions.go:

  • FinishTurn from R1: GetChatQueuedMessageHead -> insert into history -> DeleteChatQueuedMessageReturningCount -> status running.
  • FinishInterruption from I1: same.
  • SendMessage from E1 (sendMessageE1): append tail, promote previous head.
  • PromoteQueuedMessage from E1/A1: promote target now (synthesizes tool cancellations, inserts, deletes, sets running, clears last_error); from R1/I1: ReorderChatQueuedMessageToHead, set interrupting.

Classification inputs are computed in two places, both via CountChatQueuedMessages: Tx.loadState (chatstate/machine.go) and chatWorker.acquireCandidate (coderd/x/chatd/worker.go).

chat_queued_messages columns: id, chat_id, content, created_at, model_config_id, position, created_by, reasoning_effort. Rows are hard-deleted. Trigger trigger_bump_chat_queue_version_on_queued_message_update is AFTER UPDATE OF content, model_config_id, position, created_by and sets chats.queue_version = snapshot_version. The stream loop (coderd/x/chatd/stream_loop.go) turns a queue_version advance into one queue_update event carrying the full queue from GetChatQueuedMessages; the frontend applies it via applyAuthoritativeQueuedMessages (site/src/pages/AgentsPage/components/ChatConversation/chatStore.ts).

Only ChatMachine.Update bumps snapshot_version and publishes chat:update. The stream loop and the poller reject anything with snapshot_version <= local, so a direct UPDATE chat_queued_messages outside a transition is invisible to open clients until an unrelated transition happens. Every write in this design therefore goes through a transition.

Queue endpoints today: DELETE /chats/{chat}/queue/{queuedMessage} and POST .../promote (coderd/chat_routes.go, handlers deleteChatQueuedMessage and promoteChatQueuedMessage in coderd/exp_chats.go, chatd methods Server.DeleteQueued and Server.PromoteQueued in coderd/x/chatd/chatd.go). Both are mounted under /api/v2 and /api/experimental. Neither has a codersdk client method.

GetStaleChats (queries/chats.sql) flags waiting + non-empty queue as stranded. It has no callers outside coderd/database.

EditMessage (history edit) calls clearQueue, discarding the whole queue including anything held. Unchanged.

Frontend: QueuedMessagesList (site/src/pages/AgentsPage/components/) renders Send now and Remove from queue with optimistic hide/restore. History editing lives in useConversationEditingState (site/src/pages/AgentsPage/hooks/): editingMessageId, draftBeforeHistoryEdit, editingFileBlocks, composer remount via remountKey, warning banner and "Save Edit" label in AgentChatInput, submit via PATCH /chats/{chat}/messages/{message} in AgentChatPage.handleSend (editedMessageID branch). Drafts persist in localStorage under agents.draft-input.<chatID>.

Prior art: #28265 removed the client-only edit (CODAGT-230: backend promoted mid-edit). #28516 tried PATCH /queue/{id} + an in-place update transition, then a hold, abandoned both on the StateInvalid wall, shipped frontend-only "dequeue into composer", closed unmerged. Its backend commits are unreachable in the repo.

2. Model (decided)

Holding a row splits the queue in two. The visible queue is the prefix before the first held row. That row and everything behind it are absent from the queue as far as the state machine is concerned, but remain in the table, in GET /messages queued_messages, and in queue_update events, so clients can show them.

Consequences:

  • The "1" queue sub-state means "the head exists and is not held". With 5 rows and row 3 held, rows 1 and 2 run to completion; after row 2's turn the chat lands in W and the runner abandons it like any idle chat. No spinning: the classifier sees an empty queue.
  • Rows 4, 5, and any later queued arrival wait behind row 3. Blocking is derived from position, never stored per row. Two independent holds need no bookkeeping: releasing 3 lets 3 and 4 flow; 5 still blocks.
  • Explicit "process now" actions go around the hold: a direct send on an idle chat (sendMessageDirect, unchanged) and Send now (PromoteQueuedMessage, which clears the target's hold). The held row lands after whatever went around it.
  • busy_behavior=interrupt is unchanged: interrupt, then append at the tail. With a held head there is no processable head, so the chat stops and the new message waits in the held half. message_agent documents this as "processed next, after any already-queued messages" (coderd/x/chatd/subagent.go, tool description), so tail semantics are the contract.
  • A hold has no expiry. It survives client disconnects and is visible and resumable from any client.

Rejected: chat-level pause flag (wrong grain; blocks rows ahead of the edit; one tab's resume unblocks another tab's edit), explicit H states (same design plus a state-space rewrite), "hold freezes the queue" (would still have to let Send now bypass; stalls message_agent to a held child, which goes through Server.SendMessage via sendSubagentMessage), dequeue into composer (loses order and attachments), edit without hold (CODAGT-230 again).

3. Acceptance criteria

  • Owner clicks Edit on a queued row. From the moment the hold commits, that row and every row behind it cannot be promoted by FinishTurn, FinishInterruption, or sendMessageE1.
  • Rows ahead of it still promote in order.
  • Save replaces the content and releases. If the chat is idle and the row is now the head, it is promoted in the same transaction. Cancel releases without changes.
  • If the row was promoted or deleted before the hold committed, the PATCH returns 404 and the client does not enter edit mode.
  • Held rows are visible to every client with a badge; rows at or behind the first held row render as paused; held rows offer Resume, Edit, Remove, Send now.

Out of scope: history editing, EditMessage's clearQueue, exposing position, the GET /messages queue ordering bug (listed by created_at, promoted by position; wrong after Send now; file separately), a hold TTL.

4. Detailed design

4.1 Schema and queries

Migration coderd/database/migrations/000592_chat_queued_messages_held_at.{up,down}.sql (check the latest number before creating; 000591 was latest at design time).

Up:

ALTER TABLE chat_queued_messages ADD COLUMN held_at timestamptz;
COMMENT ON COLUMN chat_queued_messages.held_at IS 'Set while the owner is editing the row. The state machine treats the first held row and everything behind it as absent from the queue.';
DROP TRIGGER trigger_bump_chat_queue_version_on_queued_message_update ON chat_queued_messages;
CREATE TRIGGER trigger_bump_chat_queue_version_on_queued_message_update
  AFTER UPDATE OF content, model_config_id, position, created_by, held_at
  ON chat_queued_messages FOR EACH ROW
  EXECUTE FUNCTION bump_chat_queue_version_on_queued_message_change();

Down: drop and recreate the trigger without held_at, then ALTER TABLE chat_queued_messages DROP COLUMN held_at.

Queries in coderd/database/queries/chats.sql, next to the other chat_queued_messages state-machine queries:

-- name: UpdateChatQueuedMessageHeld :one
-- Sets or clears held_at. Setting is idempotent: an already-held row keeps
-- its original held_at.
UPDATE chat_queued_messages
SET held_at = CASE WHEN @held::boolean THEN COALESCE(held_at, now()) ELSE NULL END
WHERE id = @id::bigint AND chat_id = @chat_id::uuid
RETURNING *;

-- name: UpdateChatQueuedMessageContent :one
UPDATE chat_queued_messages
SET content = @content::jsonb,
    model_config_id = sqlc.narg('model_config_id')::uuid,
    reasoning_effort = sqlc.narg('reasoning_effort')::chat_reasoning_effort
WHERE id = @id::bigint AND chat_id = @chat_id::uuid
RETURNING *;

GetStaleChats clause 3: add AND cqm.held_at IS NULL inside the EXISTS, so a held head is not reported as stranded.

GetChatQueuedMessages (listing) and GetChatQueuedMessagesByPosition return held rows too. CountChatQueuedMessages stays as the capacity check in requireQueueCapacity and counts held rows (a hold does not free capacity).

Wiring for each new query: make gen (sqlc, dbmetrics, dump.sql), then a hand-written dbauthz wrapper in coderd/database/dbauthz/dbauthz.go following DeleteChatQueuedMessageReturningCount (load chat by arg.ChatID, authorizeContext(ctx, policy.ActionUpdate, chat)), plus an s.Run("UpdateChatQueuedMessage...") case in coderd/database/dbauthz/dbauthz_test.go following the DeleteChatQueuedMessageReturningCount case. enterprise/audit/table.go does not list chat_queued_messages; no change unless make gen says otherwise.

4.2 chatstate: classifier

coderd/x/chatd/chatstate/state.go:

// QueueState is the queue input to ClassifyExecutionState.
type QueueState struct {
	// HasPromotableHead is true when the queue is non-empty and its head
	// row is not held. This, not the raw row count, is the "1" sub-state:
	// the first held row and everything behind it are absent from the
	// queue as far as the state machine is concerned.
	HasPromotableHead bool
}

// LoadQueueState reads the queue head in the caller's transaction.
// sql.ErrNoRows means an empty queue.
func LoadQueueState(ctx context.Context, store database.Store, chatID uuid.UUID) (QueueState, error) {
	head, err := store.GetChatQueuedMessageHead(ctx, chatID)
	if errors.Is(err, sql.ErrNoRows) { return QueueState{}, nil }
	if err != nil { return QueueState{}, xerrors.Errorf("get queue head: %w", err) }
	return QueueState{HasPromotableHead: !head.HeldAt.Valid}, nil
}

func ClassifyExecutionState(chat database.Chat, queue QueueState, exists bool) ExecutionState

Replace the two call sites (Tx.loadState, chatWorker.acquireCandidate) with LoadQueueState. After the change, rg CountChatQueuedMessages coderd/x/chatd must show only requireQueueCapacity and tests. Update the classifier doc comment (the "waiting with a non-empty queue" wording becomes "waiting with a promotable head"). In state_internal_test.go, split WaitingWithQueue into WaitingWithPromotableHead (Invalid) and WaitingWithHeldHead (W), and add RunningWithHeldHead (R0).

4.3 chatstate: transitions

Add TransitionEditQueuedMessage to transition.go and AllExecutionTransitions.

// EditQueuedMessageInput edits one queued row. Nil fields are left as is.
type EditQueuedMessageInput struct {
	QueuedMessageID int64
	// Content, when non-nil, replaces the row's content. ModelConfigID and
	// ReasoningEffort apply only together with Content and follow the same
	// override rules as EditMessageInput.
	Content         *pqtype.NullRawMessage
	ModelConfigID   uuid.NullUUID
	ReasoningEffort database.NullChatReasoningEffort
	// Held, when non-nil, sets or clears held_at.
	Held *bool
}

type EditQueuedMessageResult struct {
	QueuedMessage database.ChatQueuedMessage
	// PromotedMessage is set when releasing the hold from W promoted the
	// row into history in the same transaction.
	PromotedMessage      *database.ChatMessage
	CancellationMessages []database.ChatMessage
}

func (tx *Tx) EditQueuedMessage(input EditQueuedMessageInput) (EditQueuedMessageResult, error)

Behavior, in order, inside the transition:

  1. requireFromAllowed(TransitionEditQueuedMessage).
  2. GetChatQueuedMessageByID; sql.ErrNoRows -> ErrQueuedMessageNotFound.
  3. If Content != nil: UpdateChatQueuedMessageContent. Content is stored as-is; the caller (chatd) has already run it through the same input conversion as EditMessage.
  4. If Held != nil: UpdateChatQueuedMessageHeld. Setting on an already-held row is a no-op update (still bumps queue_version via the trigger, harmless). Clearing on an unheld row is likewise a no-op.
  5. If Held was set to false, status is waiting, and LoadQueueState now reports a promotable head: promote the head using the same steps as PromoteQueuedMessage's E1/A1 branch (synthesizePendingToolCancellations with reason "Tool execution interrupted by queued message promotion", messageFromQueuedRow, insertMessages, DeleteChatQueuedMessageReturningCount, applyExecutionState to running keeping WorkerID/RunnerID/LastError). Extract that branch into a helper shared by both transitions rather than duplicating it. From error do not promote: the chat lands in E1 and the existing "error must be cleared by a send or edit" rule applies. From R*/I*/A* nothing more happens; FinishTurn/FinishInterruption will promote in order.

PromoteQueuedMessage: before ReorderChatQueuedMessageToHead, call UpdateChatQueuedMessageHeld(false) on the target. Send now on a held row releases and promotes; on a row behind a held row it goes around the hold.

Matrix (transition.go), additions only:

From EditQueuedMessage DeleteQueuedMessage PromoteQueuedMessage
W W, R0, R1 W R0, R1
E0 E0, E1 E0 R0, R1
E1 E1, E0 (existing) (existing)
R0 R0, R1 R0 I1
R1 R1, R0 (existing) (existing)
I0 I0, I1 I0 I1
I1 I1, I0 (existing) (existing)
A0 A0, A1 A0 R0, R1
A1 A1, A0 (existing) (existing)

Archived states and Invalid: unchanged (no queue transitions). The "0" states admit queue transitions because a held row may exist there; a missing row returns ErrQueuedMessageNotFound, the existing convention.

Unchanged: FinishTurn, FinishInterruption, sendMessageDirect, sendMessageE1, sendMessageQueueAndSetStatus, PromoteQueuedMessage R1/I1 branch (apart from the hold clear). Their promotion branches run only when the classifier says "1", in which case GetChatQueuedMessageHead is the promotable head.

TestTransitionMatrix_AllCombinations (transitions_matrix_test.go) requires a positive case for every (from, transition, want) in the matrix and a disallowed case for every excluded pair. Add a heldHead queue shape to the seeding helpers (queue whose head has held_at set, optionally with an unheld row behind it for the R1/E1 outputs) and wire cases for every cell above.

4.4 chatd and HTTP

coderd/x/chatd/chatd.go:

type EditQueuedMessageOptions struct {
	ChatID          uuid.UUID
	QueuedMessageID int64
	Content         []codersdk.ChatMessagePart // nil: keep
	ModelConfigID   uuid.UUID                  // uuid.Nil: keep
	ReasoningEffort *string                    // nil: keep
	Held            *bool                      // nil: keep
}

type EditQueuedMessageResult struct {
	QueuedMessage    database.ChatQueuedMessage
	InsertedMessages []database.ChatMessage // cancellations + promoted row, when released from W
}

func (p *Server) EditQueuedMessage(ctx context.Context, opts EditQueuedMessageOptions) (EditQueuedMessageResult, error)

Mirror PromoteQueued: newChatMachine, machine.Update, load the locked chat, ErrChatArchived if archived, run tx.EditQueuedMessage, reload the chat inside the transaction, then publishChatPubsubEvent(refreshed, ChatWatchEventKindStatusChange, nil) after commit when a promotion happened. Content conversion reuses whatever EditMessage uses to turn []codersdk.ChatMessagePart into stored content (see Server.EditMessage).

Handler patchChatQueuedMessage in coderd/exp_chats.go, registered in coderd/chat_routes.go as r.Patch("/", api.patchChatQueuedMessage) inside the existing /queue/{queuedMessage} route:

PATCH /api/v2/chats/{chat}/queue/{queuedMessage}
Request  codersdk.EditChatQueuedMessageRequest {
  Content         []ChatInputPart `json:"content,omitempty"`          // omitted or null: keep; empty array: 400 "Content is required."
  ModelConfigID   *uuid.UUID      `json:"model_config_id,omitempty"`
  ReasoningEffort *string         `json:"reasoning_effort,omitempty"`
  Held            *bool           `json:"held,omitempty"`
}
Response 200 codersdk.EditChatQueuedMessageResponse {
  QueuedMessage *ChatQueuedMessage `json:"queued_message,omitempty"` // nil when the row was promoted by the release
  Messages      []ChatMessage      `json:"messages,omitempty"`       // user-visible rows inserted by a release-from-W promotion
}

Guards, copied from promoteChatQueuedMessage: requireChatDaemon, Authorize(ActionUpdate, chat.RBACObject()), owner-only (403 "Only the chat owner may edit queued messages."), archived -> 400, invalid id -> 400. Content, when present, goes through createChatInputFromParts exactly like patchChatMessage, and model_config_id/reasoning_effort through the same validators. A request with every field omitted is a 400. Error mapping: ErrQueuedMessageNotFound -> 404 "Queued message not found."; ErrChatNotFound -> ResourceNotFound; writeChatInvalidState; ErrTransitionNotAllowed -> 409; default 500. Swagger annotations like the sibling handlers (@Router /api/v2/chats/{chat}/queue/{queuedMessage} [patch]).

codersdk/chats.go: add HeldAt *time.Time \json:"held_at,omitempty" format:"date-time"`toChatQueuedMessage, the two types above, and Client.EditChatQueuedMessage(ctx, chatID, queuedMessageID, req). Update convertChatQueuedMessage (coderd/exp_chats.go) and db2sdk.ChatQueuedMessages (coderd/database/db2sdk/db2sdk.go) to populate HeldAt. make genregeneratessite/src/api/typesGenerated.tsanddocs/reference/api`.

4.5 Frontend

Files: site/src/api/api.ts, site/src/api/queries/chats.ts, site/src/pages/AgentsPage/components/QueuedMessagesList.tsx (+ .stories.tsx, .test.ts), site/src/pages/AgentsPage/hooks/useConversationEditingState.ts, site/src/pages/AgentsPage/components/AgentChatInput.tsx, site/src/pages/AgentsPage/AgentChatPage.tsx (+ .test.ts, .stories.tsx), AgentChatPageView.tsx, ChatPageContent.tsx for prop plumbing. Read site/AGENTS.md and .claude/docs/FRONTEND_PATTERNS.md first.

API: API.experimental.editChatQueuedMessage(chatId, id, req) -> PATCH. Mutation editChatQueuedMessage(queryClient, chatId) in queries/chats.ts; on success invalidate chat entity and messages like deleteChatQueuedMessage.

QueuedMessagesList:

  • Compute firstHeldIndex from the ordered messages. Rows with held_at show an "Editing" badge; every row at index >= firstHeldIndex renders with the paused style (reduced opacity plus a "Paused" hint in the tooltip). No stored state for this.
  • New optional props onEdit(id) and onResume(id). Held rows show Resume, Edit, Remove, Send now. Unheld rows show Edit, Send now, Remove. Edit and Resume are not optimistic (no hide); delete and promote keep the existing optimistic hide/restore.

useConversationEditingState:

  • Replace editingMessageId: number | null with editingTarget: { kind: "history"; id: number } | { kind: "queued"; id: number } | null. Keep every existing history behavior keyed on kind === "history".
  • handleEditQueuedMessage(id, text, fileBlocks): identical to handleEditUserMessage (save draftBeforeHistoryEdit, remount composer with the text, set editingFileBlocks) but sets kind: "queued".
  • Cancel (onCancelHistoryEdit, Escape): for queued, call onResumeQueuedMessage(id) then restore the pre-edit draft exactly as history cancel does.

AgentChatPage:

  • handleEditQueuedMessage(id): find the row in store.getSnapshot().queuedMessages. If it is not already held, await editChatQueuedMessage({ id, req: { held: true } }); on 404 toast "Queued message was already sent." and stop; on other errors toast and stop. Then getEditableContentPayload(row.content) (the shared helper from messageParsing.ts; add it if only getEditableUserMessagePayload exists) and editing.handleEditQueuedMessage(id, text, fileBlocks). Editing a row another tab already holds skips the PATCH and enters edit mode directly.
  • handleResumeQueuedMessage(id): PATCH { held: false }. On failure toast; the row stays held.
  • handleSend gains a queued branch beside the editedMessageID branch: build content the same way the history-edit branch does (text plus editingFileBlocks), send PATCH { content, model_config_id?, reasoning_effort?, held: false } using the same model/effort override rules as the history edit, and on success clear the composer and restore the pre-edit draft. If the response carries messages, upsert them into the message cache (a release from W promoted the row). On failure stay in edit mode and toast. Do not clear queuedMessages or set status optimistically; the queue_update and status events will arrive.
  • Banner text for kind === "queued" in AgentChatInput: "Editing a queued message. It and the messages behind it are paused until you save or cancel." Send button label stays "Save Edit".

Store: no change. held_at rides in queue_update; applyAuthoritativeQueuedMessages already replaces the list wholesale.

4.6 Data flow

Pencil -> (if not held) PATCH {held:true} -> Server.EditQueuedMessage -> machine.Update (row lock, snapshot bump) -> tx.EditQueuedMessage{Held:true} -> trigger bumps queue_version -> chat:update -> stream queue_update with held_at -> every client shows the badge; the originating client enters edit mode. Any concurrent FinishTurn either committed before the hold (PATCH returns 404, no edit mode) or runs after it and sees HasPromotableHead=false, landing in W.

Save -> PATCH {content, held:false} -> tx.EditQueuedMessage{Content, Held:false}. From W with the row now head: promoted into history, chat running, response carries the inserted messages. From R*/I*/A*: row stays queued and promotable; FinishTurn promotes it in order. From E0: chat becomes E1.

Cancel -> PATCH {held:false} with no content; same state outcomes.

4.7 Failure behavior

  • Hold races a promotion: serialized by the chat row lock; the PATCH either wins or returns 404. Client shows "already sent" and does not enter edit mode.
  • Client disconnects mid-edit: row stays held indefinitely, visible to all clients, resumable or deletable.
  • Two tabs: tab B resumes while tab A edits; tab A's save may 404 (row promoted) and toasts; nothing stale is sent because A's content never reached the server.
  • Rolling deploy: an old replica's FinishTurn ignores held_at and can promote a held head during the deploy window. Accepted.
  • Rollback: old code ignores the column; held rows become promotable. Down migration drops the column.
  • message_agent or API send to a chat whose owner holds the head: idle chat -> processed immediately (goes around); busy chat -> queued behind the held half, queued: true as today.

5. Tests

  • chatstate/state_internal_test.go: classifier cases listed in 4.2.
  • chatstate/transitions_matrix_test.go: every cell in the 4.3 table plus disallowed cases for archived and Invalid states (the suite fails until coverage is complete).
  • chatstate transition tests (DB-backed, DB=ci go test ./coderd/x/chatd/chatstate/ -run <Name>): FinishTurn R1 with held head -> W, row intact; FinishInterruption I1 likewise; SendMessage from W with held rows inserts directly and the held rows stay; EditQueuedMessage{Held:false} from W promotes and returns PromotedMessage; from E0 lands E1 without promoting; PromoteQueuedMessage on a held row clears held_at; five rows with row 3 held, two FinishTurns promote 1 and 2 then land W.
  • chatstate/trigger_test.go: held_at update advances queue_version (sibling of TestQueueDeleteUpdatesQueueVersion).
  • dbauthz_test.go: method cases for both new queries.
  • coderd/exp_chats_test.go (or the existing chat handler test file): PATCH hold then release; 404 on a promoted id; 403 non-owner; 400 archived; 400 empty request; 400 content: [].
  • Frontend: QueuedMessagesList.test.ts for held-row actions and paused rendering; AgentChatPage.test.ts for hold -> edit mode, 404 -> no edit mode, save -> PATCH with held:false and content, cancel -> PATCH with held:false; Storybook stories for a held row, a paused tail, and the queued-edit banner.

6. Steps

Each step compiles and passes existing tests on its own.

  1. Migration, queries, make gen, dbauthz wrappers and test cases (coderd/database/**). Verify: make gen leaves a clean tree, go test ./coderd/database/dbauthz/.... Mechanical.
  2. QueueState, LoadQueueState, classifier signature and both call sites, classifier tests (coderd/x/chatd/chatstate/state.go, machine.go, coderd/x/chatd/worker.go). Verify: go test ./coderd/x/chatd/.... Behavior-preserving until a row is held.
  3. EditQueuedMessage transition, shared promote helper, PromoteQueuedMessage hold clear, matrix rows, matrix cases, transition and trigger tests (coderd/x/chatd/chatstate/). Verify: DB=ci go test ./coderd/x/chatd/chatstate/. Substantive.
  4. Server.EditQueuedMessage, handler, route, codersdk types and client method, db2sdk/convertChatQueuedMessage, GetStaleChats tweak, Swagger, make gen (coderd/x/chatd/chatd.go, coderd/exp_chats.go, coderd/chat_routes.go, codersdk/chats.go, coderd/database/db2sdk/db2sdk.go). Verify: handler tests, make lint. Substantive.
  5. Frontend (files in 4.5). Verify: pnpm -C site check, pnpm -C site test for the touched test files, Storybook for the touched stories. Substantive.
  6. coderd/x/chatd/ARCHITECTURE.md: add TODO markers (not prose) at the execution-state table, the FinishTurn/FinishInterruption bullets, the queue-endpoint section, and the queue-version trigger listing. Repo rule: the human PR author writes the updates.

Steps 1 to 3 have no user-visible effect; 4 enables API clients; 5 enables the UI.

7. Decisions record

  • Per-row held_at, not a chat-level pause. Grain and multi-client reasons above.
  • Blocked successors are derived, never stored.
  • One transition, EditQueuedMessage, covering content, hold, and release.
  • Release from W promotes in the same transaction; release from E0 lands E1.
  • No hold expiry.
  • Send now on a held row releases and promotes.
  • Direct sends on an idle chat go around the hold. Interrupt-send is unchanged and waits in the held half when the head is held.
  • Queue listing order bug (created_at vs position) is filed separately, not fixed here.

🤖 This PR was created with the help of Coder Agents on behalf of @mafredri, and will be reviewed by a human. 🏂🏻

A queued message the owner is editing must not be promoted into history,
and neither may anything queued behind it. Store the hold as a nullable
held_at on the row; the state machine will derive "the first held row
and everything behind it is absent" from queue order.

The queue_version trigger now also fires on held_at so the hold reaches
open streams. GetStaleChats checks the head row's held_at instead of
queue non-emptiness: a waiting chat whose head is held is idle, not
stranded, even when unheld rows sit behind the held one.
The "1" queue sub-state used to mean "the table has rows". It now means
"the head row exists and is not held", read through
chatstate.LoadQueueState. A held head therefore classifies like an empty
queue, which is what lets FinishTurn land in W instead of promoting a
row the owner is editing, without adding states.

No behavior changes until a row is held; nothing sets held_at yet.
EditQueuedMessage rewrites a queued row's content and sets or clears its
hold in one transition. A hold splits the queue: the first held row and
everything behind it are invisible to the classifier, so FinishTurn,
FinishInterruption, and SendMessage from E1 stop promoting at that row
while rows ahead of it drain. Explicit actions go around it: a direct
send on an idle chat inserts into history as before, and
PromoteQueuedMessage now clears the target's hold before reordering.

The "0" states admit Delete, Promote, and Edit because a held head can
hide queued rows there. Releasing or deleting a held head while the chat
is waiting can expose a promotable head, which would classify as
Invalid; those transitions promote it in the same transaction instead
(promoteHeadIfWaiting). From error the chat lands in E1 and stays
parked, matching the existing rule that a send or edit clears errors.

An empty queue is therefore no longer a state conflict for Delete and
Promote; the missing row is a 404. The two handler tests that pinned the
409 are updated.
Exposes the queue hold to clients. The owner PATCHes held:true before
editing a queued message, then saves with the new content and
held:false, or cancels with held:false alone. Content goes through the
same input validation, user_prompt_submit hook, model and effort checks,
and file linking as a fresh send, so the stored row matches what a new
send would have queued. The response carries the promoted history rows
when releasing the hold on an idle chat processed the message
immediately.

ChatQueuedMessage gains held_at so every client can render the held row
and the paused tail behind it from the regular queue snapshot.

DeleteQueued now publishes a status change when deleting a held head
promoted the next row. The 409 messages on delete and promote no longer
claim the queue is empty; an empty queue is a 404 since the "0" states
admit those transitions.
Edit on a queued row holds it on the server before the composer loads
its text and attachments, so the row cannot be promoted underneath the
edit; that race is what removed client-only queued editing (CODAGT-230).
Save sends the new content and releases the hold in one PATCH; Cancel
and Escape release it. A held row shows an Editing badge and Resume, and
every row behind it renders paused. Blocked-ness is derived from queue
order on the client, never stored.

The editing state generalizes from a history message id to a target with
a kind, so the composer can tell a queued edit from a history edit while
reusing the same draft save and restore path. The model override rule
for edits moves into resolveEditModelConfigID so both edit kinds share
it. Enter on an empty composer no longer promotes a held head, since
that would silently release the hold.

Queue and status changes are not applied optimistically; they arrive
through the queue_update and status stream events.
The repo rule is that the human PR author writes the architecture prose,
so these are TODO markers at the execution-state table, the queue
transitions, the turn-boundary transitions, the queue endpoints, and
queue synchronization. The trigger listing is a code block, so it is
updated to match the migration.
The query has no callers and no database-backed test, so the held_at
predicate added in the migration commit was only checked by a mocked
dbauthz case. This runs it against Postgres for both shapes.
GetChatQueuedMessages ordered by created_at while promotion follows
position, so after "send now" on a row behind the head the client saw
the queue in the wrong order. Clients now derive the paused tail behind
a held row from this listing, which makes the mismatch user-visible: the
row the server will process next rendered as paused. Order by position
like the state machine does.
Every queue write path deduplicated snapshots by ID sequence, which was
a valid identity while queued rows never changed in place. Holding,
releasing, and editing now rewrite held_at and content on an existing
row, so those queue_update events were dropped and the Editing badge,
the paused tail, and the saved text never reached the list. Compare the
mutable fields too.
While the composer edits queued row X, another client can promote or
delete it, and Send now or Remove on X stay available in the list. Save
and Cancel then got a 404 and the composer stayed in Save Edit mode with
no way out. A 404 on save now keeps the edited text as a new draft and
leaves edit mode; a 404 on cancel restores the pre-edit draft.

Switching the composer to another row (queued or history) while a queued
edit is open releases the previous hold first, so an abandoned edit
cannot keep the queue paused.

The cancel handler and pre-edit draft state served both edit kinds under
history-specific names; they are renamed to match.
The field doc said "idle chat", but from error the release lands the row
back in the queue (E1) and the existing send-or-edit rule clears the
error. Say "waiting" so API clients do not expect a promotion there.
@linear-code

linear-code Bot commented Sep 10, 2026

Copy link
Copy Markdown

CODAGT-971

@github-actions

Copy link
Copy Markdown
Contributor

Docs preview

Check off each page once it's been reviewed. If a page changes in a later push, its checkbox clears automatically so it gets a fresh look. Pages not yet wired into the docs navigation aren't listed here.

@mafredri

Copy link
Copy Markdown
Member Author

Split into stacked PRs: backend #29215, frontend #29216 (based on the backend branch). Same commits, no code changes.

🤖 This comment was automatically generated with Coder Agents.

@mafredri mafredri closed this Sep 11, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 11, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant