Repository navigation
feat: support editing queued chat messages - #29215
Conversation
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. |
28604ca to
c188dec
Compare
|
A few design decisions worth pointing out that effect edge cases:
|
Documentation CheckUpdates Needed
Automated review via Coder Agents |
|
|
||
| The shorthands in the table below use the convention that the first 1 or 2 letters indicate the status, and then `1` or `0` indicate the presence or absence of queued messages. | ||
|
|
||
| TODO: document the paused execution state `P`: `chats.status = paused`, not archived, non-empty queue for which a pause condition holds (`chatstate.StateP`, classified from `chatstate.QueueState{HasRows, Paused}` read by `chatstate.LoadQueueState`; `Paused` is `chatstate.queuePaused(head)`, the single place pause mechanisms register their condition; today: the head has `editing_since`). `paused` is a first-class status (in the `chat_status` enum since 000596) so every reader of `status` distinguishes it from idle without the queue. At most one queued message per chat carries `editing_since` (set while its owner edits it; beginning an edit on another ends the first). An edit changes no other state: busy states classify by row count. `waiting` with rows and `paused` without a pause condition are invalid. `P` is not runnable; a send to `P` queues at the tail. Status consumers that treat `paused` like `waiting`: the runner (abandon task), `interruptSubagent` (no turn to interrupt), and the end-of-turn label, summary, and push (`turnFinished`). SQL: `paused` is in the active-status lists of `MarkChatsContextDirtyByAgent` and `GetActiveChatsByAgentID` and excluded from both auto-archive queries; `GetStaleChats` never returns it. |
There was a problem hiding this comment.
please address those TODOs
| AND c.created_at < @archive_cutoff::timestamptz | ||
| -- New active statuses must be added here to prevent archiving. | ||
| AND c.status NOT IN ('running', 'requires_action') | ||
| AND c.status NOT IN ('running', 'requires_action', 'paused') |
There was a problem hiding this comment.
I think this should also have interrupting
There was a problem hiding this comment.
Added interrupting, and paused for this PR. The query has no production caller (auto-archive uses GetAutoArchiveInactiveChatCandidates and SetFamilyArchived); deleting it is a separate change.
🤖 Reply by Coder Agents on behalf of @mafredri.
|
|
||
| ALTER TABLE chat_queued_messages ADD COLUMN editing_since timestamptz; | ||
|
|
||
| COMMENT ON COLUMN chat_queued_messages.editing_since IS 'Set while the owner edits the row. The state machine does not promote a row under edit.'; |
There was a problem hiding this comment.
It's not the state machine promoting rows, it's the chat runner.
There was a problem hiding this comment.
Fixed: "Set while the owner edits the row. A row under edit is not promoted into history until the edit ends."
🤖 Reply by Coder Agents on behalf of @mafredri.
| // last queued message, or stays in E1 otherwise), which is why several | ||
| // entries list more than one output. | ||
| // | ||
| // A paused queue head (see queuePaused) is not promoted by FinishTurn |
There was a problem hiding this comment.
this comment seems out of place here
There was a problem hiding this comment.
Removed. The matrix comment says only that each 1P state admits the transitions of its 1 sibling; the cells list the outputs.
🤖 Reply by Coder Agents on behalf of @mafredri.
| seedP := func(extra int) func(*testing.T, *testFixture) seededChat { | ||
| return func(t *testing.T, f *testFixture) seededChat { return seedPaused(t, f, extra) } | ||
| } | ||
| cases := []transitionCaseSpec{ |
There was a problem hiding this comment.
I'm wondering if we should have new R1P, I1P, A1P, E1P, XE1P states to represent that the queue head is being edited. Right now transitions behave differently based on whether the next message in the queue is being edited.
There was a problem hiding this comment.
Done. R1P, I1P, A1P, E1P and XE1P are explicit states, and the coverage test needs a case for every matrix cell, so one table shows how an edited head changes each transition.
🤖 Reply by Coder Agents on behalf of @mafredri.
| type QueueState struct { | ||
| // HasRows is the "1" queue sub-state. | ||
| HasRows bool | ||
| // Paused is [queuePaused] of the head. Only P requires it. |
There was a problem hiding this comment.
why? isn't the fact that the status is paused sufficient to determine that we're in P?
There was a problem hiding this comment.
Status alone would classify it, but checking the head catches a paused chat whose head is not under edit. P is not runnable, so that chat would never advance; it classifies Invalid and reconciles to error, like waiting with rows. The classifier reads the head anyway, so this costs no extra query.
🤖 Reply by Coder Agents on behalf of @mafredri.
| {name: "XE1", status: database.ChatStatusError, archived: true, queueNonEmpty: true, exists: true, want: StateXE1}, | ||
| {name: "P", status: database.ChatStatusPaused, queueNonEmpty: true, paused: true, exists: true, want: StateP}, | ||
| // A head under edit changes nothing outside paused. | ||
| {name: "R1Paused", status: database.ChatStatusRunning, queueNonEmpty: true, paused: true, exists: true, want: StateR1}, |
There was a problem hiding this comment.
regarding our discussion, looks like the new states could come in handy
There was a problem hiding this comment.
Agreed. The test enumerates each 1P state.
🤖 Reply by Coder Agents on behalf of @mafredri.
738bfa2 to
b1c103e
Compare
#29507) On viewports below 640 px, Enter inserts a newline, so once a turn was streaming the footer offered only Stop and there was no way to queue a follow-up message from touch. The rightmost footer slot now follows one rule while a turn streams: Stop while the draft is empty, and the send button labelled Queue once the draft has sendable text, an active upload, or a live voice recording. Editing a history message while streaming keeps Stop. When not streaming, nothing changes. Exactly one of Stop or the send button renders in the slot at any time. Two fixes from the UAT report are included: - Below 640 px, the send button omits `aria-keyshortcuts` and the tooltip shortcut suffix, and the queued list hides its Enter hint (`hidden sm:flex`), since Enter does not send there. - Voice input is available while a turn streams. The mic renders whenever speech recognition is supported, so a recording can start mid-stream; Accept holds the primary slot while recording, then Queue once the transcript lands, and Cancel with an empty draft returns to Stop. Accept and Cancel refocus the editor on non-mobile viewports. UAT report: https://github.com/coder/scott-misc/blob/main/uat/mobile-queue-send-uat/README.md **Merge point with #29216:** that PR changes the label to `isEditingMessage ? "Save Edit" : isChatPaused ? "Queue" : "Send"` and renames `isEditingHistoryMessage` to `isEditingMessage`. Whichever lands second should resolve the label to `isEditingMessage ? "Save Edit" : isStreaming || isChatPaused ? "Queue" : "Send"`. <details> <summary>UAT findings disposition</summary> | # | Finding | Disposition | |---|---------|-------------| | 1 | Stop unreachable while a draft exists; live Stop returns under thumb after Queue | Accepted as designed (single-slot rule) | | 2 | Queue tooltip and `aria-keyshortcuts` say Enter below 640 px; queued-list hint mismatches | Fixed here | | 3 | Focus lands on `body` after Queue on phone | Deferred until #29216 lands (rewrites the same button block) | | 4 | Interrupt with queued messages promotes the queue instead of stopping | Skipped; pre-existing chatd behavior, needs design atop #29215 hold semantics | | 5 | Voice recording loses Accept and Cancel when a turn starts | Fixed here, extended: the mic is available throughout a stream, not only for a recording already in progress | | 6 | 384 px attachment-error toast covers the footer on a 390 px phone | Skipped; global `Toaster` width, needs design sign-off | </details> <details> <summary>Implementation plan</summary> Repository: /home/coder/coder, branch `scott/mobile-queue-send` off `origin/main`. **Confirmed reading** - `AgentChatInput.tsx`: `handleSubmit` does not check `isStreaming`; the editor's `onEnter={handleSubmit}` therefore queues a message while a turn streams, and the page's send path handles `response.queued`. Footer right group: voice input hidden while streaming, context usage visible, Stop under `isStreaming && onInterrupt`, send button only under `!isStreaming`. `sendButtonLabel` is `"Save Edit" | "Send"`; open PR #29216 changes it to `isEditingMessage ? "Save Edit" : isChatPaused ? "Queue" : "Send"`. - Gap: on touch/narrow viewports Enter inserts a newline, so there is no way to queue. **Decisions and constraints** - Do not add a Queue button beside Stop. Render one primary footer button whose role depends on the composer draft while a turn streams: draft empty shows Stop; draft non-empty shows the send button labelled "Queue", submitting through the existing `handleSubmit` path. Not streaming: unchanged. The button stays in the rightmost footer slot. - "Draft non-empty" is `draftOccupiesSlot = hasSendableContent || hasActiveUploads`: an attachment still uploading shows a transiently disabled Queue, an errored-only attachment keeps Stop. Stop is also kept while a history message is being edited during a stream; Enter still saves the edit. - While streaming with an empty draft and no `onInterrupt`, nothing renders in the slot (same as `main`). - Smallest change, Vitest for behaviour, setup-only stories with a narrow-viewport streaming story. **Scope** Single component change plus test and story. No page wiring, no server change. **Changes** 1. `AgentChatInput.tsx`: label `isEditingHistoryMessage ? "Save Edit" : isStreaming ? "Queue" : "Send"`; footer slot shows Stop when `isStreaming && onInterrupt && !draftOccupiesSlot`, the send button when `!isStreaming || draftOccupiesSlot`; spinner only when `isLoading && !isInterruptPending`; tooltip `Queue: <shortcut>` follows from the label. 2. `AgentChatInput.test.tsx`: Stop -> Queue -> Stop after draft clear, with callback assertions; interrupt-pending with a draft renders a disabled Queue that does not call `onSend`. 3. `AgentChatInput.stories.tsx`: narrow-viewport streaming story with a draft so the 390 px footer with Queue in the Stop slot is captured. 4. `ChatPageContent.stories.tsx` `InterruptingShowsBusyComposer`: the absent-send-button assertion queries the streaming label "Queue". **UAT follow-up (this PR)** - Item 2: `mobileViewportMediaQuery` constant in `utils/mobile.ts`; `useMediaQuery` in `AgentChatInput` drops `aria-keyshortcuts` and the tooltip suffix below 640 px; queued-list hint `hidden sm:flex`. - Item 5: mic cluster rendered whenever `speech.isSupported`; `speech.isRecording` added to `draftOccupiesSlot`; a live recording takes precedence over history editing in the slot. </details> --- This PR was generated by Coder Agents on behalf of @jscottmiller.
This comment has been minimized.
This comment has been minimized.
|
Chat: Review in progress (19/19 reviewers complete) | View chat deep-review v0.13.0 | Round 1 | Status: Panel review (17 reviewers) About deep-reviewCRF = Coder Review Finding (P0-P4, Nit, Note)
|
There was a problem hiding this comment.
This PR adds editing of queued chat messages (PATCH /queue/{id}, editing_since, the paused status, and five 1P execution states). Findings: 1 P1, 2 P2, 19 P3, 18 P4, 6 Nit.
The GetChatQueuedMessages ordering fix does not depend on the rest of the PR; landing it as its own PR would let it merge without waiting on the state machine review.
Out of scope (needs a ticket or explicit acceptance by a human):
coderd/database/queries/chats.sql:1879:GetStaleChatshas no production caller, so the strandedwaiting-with-rows chats its comment says it recovers are recovered only when a client calls the reconcile endpoint.coderd/database/queries/chats.sql:2923:AutoArchiveInactiveChatshas no production caller and archives with a directUPDATE, so any future caller would bypass the state machine.coderd/exp_chats.go:3038:DELETEandPOST .../promoteon a missing queued row return 409 when the queue is empty and 404 otherwise, because the matrix check runs before the row lookup; clients cannot rely on 404 meaning "already gone".coderd/x/chatd/subagent.go:1054: thelist_agentsstatus description omitsrequires_action, so the model gets no meaning for that value.
Notes:
PATCHreturns 204 with no body, so a client learns the resulting row and chat status only fromqueue_updateandstatusstream events.- No test drives the worker through
Pand a resume end to end;TestPatchChatQueuedMessagedisables the worker and setspauseddirectly.
coderd/x/chatd/chatstate/machine.go:56
P3 [CRF-5] machine.go:56 and chatstate/doc.go:25 still say classification reads the "queue cardinality". (Netero)
loadState now calls LoadQueueState, which reads the head and its edit marker, and the 1P states depend on that. A reader of the package docs will assume classification depends only on whether the queue is empty. Change both to "queue state".
🤖
coderd/x/chatd/subagent.go:1643
P2 [CRF-7] checkSubagentCompletion treats a paused child as finished, so wait_agent returns the child's previous report as the reply to a message the child has not processed. (Mafuuu)
Child chats share the parent's owner, so the owner can pause a child by editing its queued head, and message_agent then queues behind that head (P + SendMessage -> P). Only running and interrupting count as not done; a scratch test with the TestAwaitSubagentCompletion fixtures returned status=paused report="previous turn report" after 1.5ms. Treat paused as not done, or return a paused result without a report.
🤖
coderd/x/chatd/subagent.go:1055
P4 [CRF-23] The list_agents and interrupt_agent tool descriptions tell the model what each status means, and neither covers paused. (Mafuuu, Melody)
list_agents defines running, interrupting, waiting, and error; interrupt_agent says the child moves to waiting or running, but I1P + FinishInterruption now reaches paused. A model that reads paused cannot tell that the child stays stopped until the user ends the edit. Add "paused = stopped until the user finishes editing a queued message" to both.
🤖
codersdk/toolsdk/chats.go:301
P4 [CRF-24] The AwaitChat description lists the statuses that end the wait and omits paused, which also ends it. (Mafuuu)
chatStatusBusy returns false for paused, so the wait returns while the description names only waiting, error, and requires_action. Add paused to the list.
🤖
🤖 This review was automatically generated with Coder Agents.
| } | ||
|
|
||
| contentParts := opts.Content | ||
| if len(contentParts) > 0 && p.hooks.Enabled() { |
There was a problem hiding this comment.
P3 [CRF-3] The user_prompt_submit admission sequence now exists in SendMessage, EditMessage, and EditQueuedMessage. (Netero)
Loading the chat, the archived check, model config validation, UserPromptMessage, hooks.Trigger, dispatch error handling, and ComposeUserPromptContent are repeated in each, so a change to hook admission (such as the dispatch-error fix at line 2230) has to be made three times. Extract a helper that takes the chat ID and content parts and returns the composed parts.
🤖
There was a problem hiding this comment.
The three sites share three calls, but their pre-checks differ, and after the CRF-2 fix their dispatch-error policies differ too: a queued edit fails only the edit, while SendMessage and EditMessage can park an idle chat. A helper that includes the error handling would bring CRF-2 back, so this PR keeps them separate.
🤖 Posted using
/amend-reviewskill via Coder Agents.
| // changes outside a transition leaves a paused chat that classifies | ||
| // invalid. | ||
| func queuePaused(head database.ChatQueuedMessage) bool { | ||
| return head.EditingSince.Valid |
There was a problem hiding this comment.
P2 [CRF-6] Nothing on the server ends an edit, so a client that sends {"editing": true} and never sends the end leaves the chat paused indefinitely. (Pariston, Killua, Luffy, Melody, Ryosuke, Takumi, Pen Botter, Leorio, Knuckle, Mafuuu, Razor, Nami)
editing_since is only read as .Valid, and only owner requests clear it (PATCH editing: false, promote, delete). After a closed tab, crash, or network loss, the running turn reaches R1P + FinishTurn -> P; from P, new messages (including busy_behavior: interrupt) queue behind the head until MaxQueueSize, Interrupt and SetArchived are refused, and both auto-archive queries skip paused, so the chat is never archived or purged. queuePaused forbids a condition that changes outside a transition, so the fix is a transition that ends stale edits (for example, a sweep that ends edits older than a lease and resumes the chat) with the editing client renewing the lease; the COALESCE in UpdateChatQueuedMessageEditing keeps the first timestamp, so renewal needs its own update.
🤖
There was a problem hiding this comment.
Intended. An edit does not expire: it stays open until the owner ends it, or the message is promoted or deleted.
🤖 Posted using
/amend-reviewskill via Coder Agents.
b1c103e to
e39136c
Compare
|
In reply to CRF-5 (P3, Fixed in 65642a0: In reply to CRF-7 (P2, Fixed in the stacked #29292: In reply to CRF-23 (P4,
In reply to CRF-24 (P4, Fixed in a6b23b3: the
|
1ba2bd6 to
cfdf0a0
Compare
The down test only covered a transaction that locks the chat row first, and a down migration that locks just chats passes it. The new case reads the queue, then queues a message and updates the chat. The insert locks chats through its foreign key check and trigger. A migration that holds chats while it waits for the queue deadlocks with it. Locking both tables in one attempt does not. The up test caught a stalled reader only because the harness's 5s lock_timeout ended the migration. The reader now has to finish within 1s while the application transaction is open, so the test checks the stall itself.
Reconcile the rebased stack with main: port the moved chatd mutations and turn preparation, renumber the migration to 000631, and apply the interrupt-send, SetProject, and paused-label rules to the paused states.
Move the editing migration to 000633 after main's 000631 and 000632, restore main's architecture text that the replay dropped, and resolve skill invocations in queued-message content edits as sends and history edits do.
…hers TestGetChatQueuedMessages_OrdersByPosition repeats the PromoteWhileRunning case of TestClientQueueOrderMatchesPromotionOrder, and the content-edit override test repeats OverridesApplyWithContent in the queued-edit API tests. Five of the interrupt-ahead-of-an-edited-head subtests repeat transition matrix cells; the unowned running case has no cell, so it stays as its own test. A coverage profile of the package shows one block left uncovered here, the reasoning effort override in EditQueuedMessage, which the API test still covers.
FinishTurn, FinishInterruption, and leaving P all pick the next state from the queue head: an empty queue waits, a blocked head pauses, and a ready head is promoted. advanceQueue does that once, so the per-state branches in FinishTurn and FinishInterruption go away. promoteQueuedRow now takes the last_error to store. advanceQueue passes the chat's own, as main does for FinishTurn and FinishInterruption, while promotions out of error and requires-action still clear it. This also restores main's FinishTurn from R1, which this branch had changed to clear last_error. TestQueueAdvanceKeepsLastError pins both paths.
DeleteQueuedMessage and EditQueuedMessage now return the updated chat when the transition left P, and nil otherwise. chatd publishes the status change from that row instead of reloading the chat and comparing statuses, the same way CompactChat and ClearChat hand the result's chat to updateChat instead of reloading it.
Leaving P with a ready head went through advanceQueue with the chat's own last_error, while PromoteQueuedMessage from P clears it. advanceQueue now takes the last_error for a promoted head, and leavePaused passes null, so every promotion out of P clears it again. last_error by transition: - FinishTurn (R0 to W, R1 to R*, R1P to P) and FinishInterruption (I0 to W, I1 to R*, I1P to P) keep it, as on main. - DeleteQueuedMessage from P to W keeps it. - DeleteQueuedMessage and ending the head's edit from P to R* clear it, as PromoteQueuedMessage from P does. - A Delete or edit end that stays in P does not write the chat row. TestQueueAdvanceKeepsLastError now covers every FinishTurn and FinishInterruption outcome, and TestEditing_LeavingPaused covers each P path: the stored last_error, that staying in P leaves updated_at alone and returns no chat, and that leaving P returns the updated chat.
Move the editing migration to 000634 after main's 000633, and keep the paused archive refusal message in main's shared chat update path.
The paused resume delete guard and the paused auto-archive candidate test repeat checks that TestQueuedMessagePromotionRequiresSingleDelete and TestAutoArchiveCandidateQueriesAgree already make through the same code. TestQueueAdvanceKeepsLastError and the last_error column of TestEditing_LeavingPaused seed last_error by a direct row write onto R, I, and P chats. No transition stores last_error outside error: every exit from E0, E1, and E1P clears it, so those inputs never occur. The matrix already covers their state outcomes and queue links.
Main added migration 000634_aibridge_interception_organization, so the queued-message editing_since migration and its test move to 000635. Regenerate the chat API docs for main's project_id parameter change.
A queued content edit links its files, but dropping that LinkFiles call failed no test.
Only FinishError and ReconcileInvalidState store a last_error, both in error, and every transition out of E0, E1, and E1P clears it. The chats that advanceQueue sees (R, I, P) therefore never carry one, so promoteQueuedRow can clear it for all callers and the last_error parameters on promoteQueuedRow and advanceQueue go away.
Editing a row that was already sent or removed returned 404 while other rows were queued, but 409 with the internal transition error in Detail once the queue was empty, because the state check runs before the row lookup. Every unarchived, valid state that refuses the edit has an empty queue, so the row is gone in that case too.
queue_wait runs from the queued row's created_at to its promotion, and editing a queued row does not change created_at, so a row's time under edit counts toward queue_wait.
Renumber the editing_since migration to 000638 after main's 000637 and regenerate the database wrappers.
7954fdb to
5eb7389
Compare
Backend for CODAGT-971. The frontend is stacked as #29553, #29554, #29555.
The owner can edit a queued message, and
editing_sincemarks the row under edit. chatd never sends a row under edit: rows ahead of it still send in order, and a turn that ends at it puts the chat in the newpausedstatus. In a paused chat, ending the head's edit sends it, and deleting or promoting a queued row continues the chat. Stop behind a head under edit pauses the chat. An interrupting send runs ahead of the queue in every paused state, as on main (#30729), and the chat pauses again afterwards. When no worker owns the chat, Stop or an interrupting send finishes the interruption in the same request.SetProjectis allowed from paused states.API
PATCH /api/v2/chats/{chat}/queue/{queuedMessage}takescontent(optionally withmodel_config_idandreasoning_effort) andediting, and returns 204. In a paused chat, beginning an edit on a row other than the head returns 409. This endpoint andDELETEon queue rows are owner-only, because ending the edit of a paused chat's head, or deleting the head, sends the next message with the owner's credentials.ChatQueuedMessagegainsediting_sinceandreasoning_effort.ChatStatusgainspaused, so clients can tell it fromwaitingwithout reading the queue; thestatus:chat filter accepts it. A chat whose family has a paused member cannot be archived, and auto-archive skips that family.Review-worthy decisions
Explicit
1Pstates.ClassifyExecutionStatetakesQueueState{HasRows, Paused}and classifies a non-empty queue by its head:1when ready,1Pwhen under edit.R1P,I1P,A1P,E1PandXE1Pbehave like their1sibling except where the sibling would promote the head:E1P + SendMessagestaysE1P, andR1P + FinishTurnandI1P + FinishInterruptionreachP. This puts every path topausedin the transition matrix and its coverage test, at the cost of 5 states and 34 matrix cells, most of them copies of the1sibling. A future pause condition extendsqueuePausedinchatstate/state.go.pausedrequires a head under edit.Pis not runnable, so a paused chat with a ready head or an empty queue would never advance. It classifiesInvalidand reconciles toerror, likewaitingwith rows. A pause condition may therefore change only inside a state machine transition. Details are incoderd/x/chatd/ARCHITECTURE.md.Compatibility
The frontend on
mainkeeps working:editing_sinceis optional and main's UI never sets it. This PR addspausedto the sidebar status table, the sidebar Status filter, and the status group lists, which main type-checks. Until the frontend stack lands, a chat paused by another API client shows the Paused status, but the chat page shows no edit marker and plays no completion chime for it.Part of https://linear.app/codercom/issue/CODAGT-971
Implements https://linear.app/codercom/issue/CODAGT-1028