Repository navigation
Conversation
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.
Contributor
Docs previewCheck 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. |
Member
Author
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 inwaitingand 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=interruptis 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) hitStateInvalidbecausewaitingwith a non-empty queue is invalid; a held head classifies as an empty queue, sowaitingwith a held head is a valid idle state.API
PATCH /api/v2/chats/{chat}/queue/{queuedMessage}withcontent?,model_config_id?,reasoning_effort?,held?. The client sendsheld:truebefore 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.ChatQueuedMessagegainsheld_atso every client renders the held row and the paused tail from the regularqueue_updatesnapshot.Two contract changes fall out of admitting queue transitions from the "0" states: an empty queue is a
404(row not found) instead of a409for delete and promote, and deleting a held head fromwaitingpromotes the row behind it.Deviations from the plan
GetStaleChatschecks the head row'sheld_atrather thanEXISTS (... held_at IS NULL); the plan's predicate flagged a waiting chat with a held head and unheld rows behind it.DeleteQueuedMessagefrom a "0" state can land in the "1" sibling (and fromWpromotes), which the plan's matrix omitted.GetChatQueuedMessages) now orders bypositionlike 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.coderd/x/chatd/ARCHITECTURE.mdcarries 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 usetype(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
mainatd8e3f4fcf7. Re-verify line numbers; symbol names are the anchor.1. Current system
Execution state is a pure function of
(status, archived, queue non-empty)inchatstate.ClassifyExecutionState(coderd/x/chatd/chatstate/state.go).waitingwith a non-empty queue matches no case and falls toStateInvalid;Tx.requireFromAllowed(machine.go) then refuses every transition exceptReconcileInvalidState, which parks the chat inerror. The test caseWaitingWithQueueinstate_internal_test.gopins 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 inchatstate/transitions.go:FinishTurnfrom R1:GetChatQueuedMessageHead-> insert into history ->DeleteChatQueuedMessageReturningCount-> statusrunning.FinishInterruptionfrom I1: same.SendMessagefrom E1 (sendMessageE1): append tail, promote previous head.PromoteQueuedMessagefrom E1/A1: promote target now (synthesizes tool cancellations, inserts, deletes, sets running, clearslast_error); from R1/I1:ReorderChatQueuedMessageToHead, setinterrupting.Classification inputs are computed in two places, both via
CountChatQueuedMessages:Tx.loadState(chatstate/machine.go) andchatWorker.acquireCandidate(coderd/x/chatd/worker.go).chat_queued_messagescolumns:id, chat_id, content, created_at, model_config_id, position, created_by, reasoning_effort. Rows are hard-deleted. Triggertrigger_bump_chat_queue_version_on_queued_message_updateisAFTER UPDATE OF content, model_config_id, position, created_byand setschats.queue_version = snapshot_version. The stream loop (coderd/x/chatd/stream_loop.go) turns aqueue_versionadvance into onequeue_updateevent carrying the full queue fromGetChatQueuedMessages; the frontend applies it viaapplyAuthoritativeQueuedMessages(site/src/pages/AgentsPage/components/ChatConversation/chatStore.ts).Only
ChatMachine.Updatebumpssnapshot_versionand publisheschat:update. The stream loop and the poller reject anything withsnapshot_version <= local, so a directUPDATE chat_queued_messagesoutside 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}andPOST .../promote(coderd/chat_routes.go, handlersdeleteChatQueuedMessageandpromoteChatQueuedMessageincoderd/exp_chats.go, chatd methodsServer.DeleteQueuedandServer.PromoteQueuedincoderd/x/chatd/chatd.go). Both are mounted under/api/v2and/api/experimental. Neither has acodersdkclient method.GetStaleChats(queries/chats.sql) flagswaiting+ non-empty queue as stranded. It has no callers outsidecoderd/database.EditMessage(history edit) callsclearQueue, discarding the whole queue including anything held. Unchanged.Frontend:
QueuedMessagesList(site/src/pages/AgentsPage/components/) rendersSend nowandRemove from queuewith optimistic hide/restore. History editing lives inuseConversationEditingState(site/src/pages/AgentsPage/hooks/):editingMessageId,draftBeforeHistoryEdit,editingFileBlocks, composer remount viaremountKey, warning banner and "Save Edit" label inAgentChatInput, submit viaPATCH /chats/{chat}/messages/{message}inAgentChatPage.handleSend(editedMessageIDbranch). Drafts persist inlocalStorageunderagents.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 theStateInvalidwall, 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 /messagesqueued_messages, and inqueue_updateevents, so clients can show them.Consequences:
sendMessageDirect, unchanged) andSend now(PromoteQueuedMessage, which clears the target's hold). The held row lands after whatever went around it.busy_behavior=interruptis 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_agentdocuments this as "processed next, after any already-queued messages" (coderd/x/chatd/subagent.go, tool description), so tail semantics are the contract.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 nowbypass; stallsmessage_agentto a held child, which goes throughServer.SendMessageviasendSubagentMessage), dequeue into composer (loses order and attachments), edit without hold (CODAGT-230 again).3. Acceptance criteria
FinishTurn,FinishInterruption, orsendMessageE1.Out of scope: history editing,
EditMessage'sclearQueue, exposingposition, theGET /messagesqueue ordering bug (listed bycreated_at, promoted byposition; wrong afterSend 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:
Down: drop and recreate the trigger without
held_at, thenALTER TABLE chat_queued_messages DROP COLUMN held_at.Queries in
coderd/database/queries/chats.sql, next to the otherchat_queued_messagesstate-machine queries:GetStaleChatsclause 3: addAND cqm.held_at IS NULLinside theEXISTS, so a held head is not reported as stranded.GetChatQueuedMessages(listing) andGetChatQueuedMessagesByPositionreturn held rows too.CountChatQueuedMessagesstays as the capacity check inrequireQueueCapacityand counts held rows (a hold does not free capacity).Wiring for each new query:
make gen(sqlc,dbmetrics,dump.sql), then a hand-writtendbauthzwrapper incoderd/database/dbauthz/dbauthz.gofollowingDeleteChatQueuedMessageReturningCount(load chat byarg.ChatID,authorizeContext(ctx, policy.ActionUpdate, chat)), plus ans.Run("UpdateChatQueuedMessage...")case incoderd/database/dbauthz/dbauthz_test.gofollowing theDeleteChatQueuedMessageReturningCountcase.enterprise/audit/table.godoes not listchat_queued_messages; no change unlessmake gensays otherwise.4.2 chatstate: classifier
coderd/x/chatd/chatstate/state.go:Replace the two call sites (
Tx.loadState,chatWorker.acquireCandidate) withLoadQueueState. After the change,rg CountChatQueuedMessages coderd/x/chatdmust show onlyrequireQueueCapacityand tests. Update the classifier doc comment (the "waiting with a non-empty queue" wording becomes "waiting with a promotable head"). Instate_internal_test.go, splitWaitingWithQueueintoWaitingWithPromotableHead(Invalid) andWaitingWithHeldHead(W), and addRunningWithHeldHead(R0).4.3 chatstate: transitions
Add
TransitionEditQueuedMessagetotransition.goandAllExecutionTransitions.Behavior, in order, inside the transition:
requireFromAllowed(TransitionEditQueuedMessage).GetChatQueuedMessageByID;sql.ErrNoRows->ErrQueuedMessageNotFound.Content != nil:UpdateChatQueuedMessageContent. Content is stored as-is; the caller (chatd) has already run it through the same input conversion asEditMessage.Held != nil:UpdateChatQueuedMessageHeld. Setting on an already-held row is a no-op update (still bumpsqueue_versionvia the trigger, harmless). Clearing on an unheld row is likewise a no-op.Heldwas set to false, status iswaiting, andLoadQueueStatenow reports a promotable head: promote the head using the same steps asPromoteQueuedMessage's E1/A1 branch (synthesizePendingToolCancellationswith reason "Tool execution interrupted by queued message promotion",messageFromQueuedRow,insertMessages,DeleteChatQueuedMessageReturningCount,applyExecutionStatetorunningkeepingWorkerID/RunnerID/LastError). Extract that branch into a helper shared by both transitions rather than duplicating it. Fromerrordo 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/FinishInterruptionwill promote in order.PromoteQueuedMessage: beforeReorderChatQueuedMessageToHead, callUpdateChatQueuedMessageHeld(false)on the target.Send nowon a held row releases and promotes; on a row behind a held row it goes around the hold.Matrix (
transition.go), additions only: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,PromoteQueuedMessageR1/I1 branch (apart from the hold clear). Their promotion branches run only when the classifier says "1", in which caseGetChatQueuedMessageHeadis 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 aheldHeadqueue shape to the seeding helpers (queue whose head hasheld_atset, optionally with an unheld row behind it for theR1/E1outputs) and wire cases for every cell above.4.4 chatd and HTTP
coderd/x/chatd/chatd.go:Mirror
PromoteQueued:newChatMachine,machine.Update, load the locked chat,ErrChatArchivedif archived, runtx.EditQueuedMessage, reload the chat inside the transaction, thenpublishChatPubsubEvent(refreshed, ChatWatchEventKindStatusChange, nil)after commit when a promotion happened. Content conversion reuses whateverEditMessageuses to turn[]codersdk.ChatMessagePartinto stored content (seeServer.EditMessage).Handler
patchChatQueuedMessageincoderd/exp_chats.go, registered incoderd/chat_routes.goasr.Patch("/", api.patchChatQueuedMessage)inside the existing/queue/{queuedMessage}route: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 throughcreateChatInputFromPartsexactly likepatchChatMessage, andmodel_config_id/reasoning_effortthrough 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: addHeldAt *time.Time \json:"held_at,omitempty" format:"date-time"`toChatQueuedMessage, the two types above, andClient.EditChatQueuedMessage(ctx, chatID, queuedMessageID, req). UpdateconvertChatQueuedMessage(coderd/exp_chats.go) anddb2sdk.ChatQueuedMessages(coderd/database/db2sdk/db2sdk.go) to populateHeldAt.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.tsxfor prop plumbing. Readsite/AGENTS.mdand.claude/docs/FRONTEND_PATTERNS.mdfirst.API:
API.experimental.editChatQueuedMessage(chatId, id, req)->PATCH. MutationeditChatQueuedMessage(queryClient, chatId)inqueries/chats.ts; on success invalidate chat entity and messages likedeleteChatQueuedMessage.QueuedMessagesList:firstHeldIndexfrom the orderedmessages. Rows withheld_atshow an "Editing" badge; every row at index >=firstHeldIndexrenders with the paused style (reduced opacity plus a "Paused" hint in the tooltip). No stored state for this.onEdit(id)andonResume(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:editingMessageId: number | nullwitheditingTarget: { kind: "history"; id: number } | { kind: "queued"; id: number } | null. Keep every existing history behavior keyed onkind === "history".handleEditQueuedMessage(id, text, fileBlocks): identical tohandleEditUserMessage(savedraftBeforeHistoryEdit, remount composer with the text, seteditingFileBlocks) but setskind: "queued".onCancelHistoryEdit, Escape): forqueued, callonResumeQueuedMessage(id)then restore the pre-edit draft exactly as history cancel does.AgentChatPage:handleEditQueuedMessage(id): find the row instore.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. ThengetEditableContentPayload(row.content)(the shared helper frommessageParsing.ts; add it if onlygetEditableUserMessagePayloadexists) andediting.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.handleSendgains aqueuedbranch beside theeditedMessageIDbranch: build content the same way the history-edit branch does (text pluseditingFileBlocks), sendPATCH { 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 carriesmessages, upsert them into the message cache (a release from W promoted the row). On failure stay in edit mode and toast. Do not clearqueuedMessagesor set status optimistically; thequeue_updateand status events will arrive.kind === "queued"inAgentChatInput: "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_atrides inqueue_update;applyAuthoritativeQueuedMessagesalready 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 bumpsqueue_version->chat:update-> streamqueue_updatewithheld_at-> every client shows the badge; the originating client enters edit mode. Any concurrentFinishTurneither committed before the hold (PATCH returns 404, no edit mode) or runs after it and seesHasPromotableHead=false, landing in W.Save ->
PATCH {content, held:false}->tx.EditQueuedMessage{Content, Held:false}. From W with the row now head: promoted into history, chatrunning, response carries the inserted messages. From R*/I*/A*: row stays queued and promotable;FinishTurnpromotes it in order. From E0: chat becomes E1.Cancel ->
PATCH {held:false}with no content; same state outcomes.4.7 Failure behavior
FinishTurnignoresheld_atand can promote a held head during the deploy window. Accepted.message_agentor API send to a chat whose owner holds the head: idle chat -> processed immediately (goes around); busy chat -> queued behind the held half,queued: trueas 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).chatstatetransition tests (DB-backed,DB=ci go test ./coderd/x/chatd/chatstate/ -run <Name>):FinishTurnR1 with held head -> W, row intact;FinishInterruptionI1 likewise;SendMessagefrom W with held rows inserts directly and the held rows stay;EditQueuedMessage{Held:false}from W promotes and returnsPromotedMessage; from E0 lands E1 without promoting;PromoteQueuedMessageon a held row clearsheld_at; five rows with row 3 held, twoFinishTurns promote 1 and 2 then land W.chatstate/trigger_test.go:held_atupdate advancesqueue_version(sibling ofTestQueueDeleteUpdatesQueueVersion).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; 400content: [].QueuedMessagesList.test.tsfor held-row actions and paused rendering;AgentChatPage.test.tsfor hold -> edit mode, 404 -> no edit mode, save -> PATCH withheld:falseand content, cancel -> PATCH withheld: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.
make gen,dbauthzwrappers and test cases (coderd/database/**). Verify:make genleaves a clean tree,go test ./coderd/database/dbauthz/.... Mechanical.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.EditQueuedMessagetransition, shared promote helper,PromoteQueuedMessagehold clear, matrix rows, matrix cases, transition and trigger tests (coderd/x/chatd/chatstate/). Verify:DB=ci go test ./coderd/x/chatd/chatstate/. Substantive.Server.EditQueuedMessage, handler, route, codersdk types and client method,db2sdk/convertChatQueuedMessage,GetStaleChatstweak, 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.pnpm -C site check,pnpm -C site testfor the touched test files, Storybook for the touched stories. Substantive.coderd/x/chatd/ARCHITECTURE.md: add TODO markers (not prose) at the execution-state table, theFinishTurn/FinishInterruptionbullets, 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
held_at, not a chat-level pause. Grain and multi-client reasons above.EditQueuedMessage, covering content, hold, and release.Send nowon a held row releases and promotes.created_atvsposition) is filed separately, not fixed here.