Skip to content

feat: support editing queued chat messages - #29215

Merged
mafredri merged 73 commits into
mainfrom
mathias/codagt-971-queue-hold-backend
Oct 30, 2026
Merged

mafredri merged 73 commits into
mainfrom
mathias/codagt-971-queue-hold-backend

Conversation

@mafredri

@mafredri mafredri commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Backend for CODAGT-971. The frontend is stacked as #29553, #29554, #29555.

The owner can edit a queued message, and editing_since marks 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 new paused status. 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. SetProject is allowed from paused states.

API

PATCH /api/v2/chats/{chat}/queue/{queuedMessage} takes content (optionally with model_config_id and reasoning_effort) and editing, and returns 204. In a paused chat, beginning an edit on a row other than the head returns 409. This endpoint and DELETE on 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.

ChatQueuedMessage gains editing_since and reasoning_effort. ChatStatus gains paused, so clients can tell it from waiting without reading the queue; the status: 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 1P states. ClassifyExecutionState takes QueueState{HasRows, Paused} and classifies a non-empty queue by its head: 1 when ready, 1P when under edit. R1P, I1P, A1P, E1P and XE1P behave like their 1 sibling except where the sibling would promote the head: E1P + SendMessage stays E1P, and R1P + FinishTurn and I1P + FinishInterruption reach P. This puts every path to paused in the transition matrix and its coverage test, at the cost of 5 states and 34 matrix cells, most of them copies of the 1 sibling. A future pause condition extends queuePaused in chatstate/state.go.

paused requires a head under edit. P is not runnable, so a paused chat with a ready head or an empty queue would never advance. It classifies Invalid and reconciles to error, like waiting with rows. A pause condition may therefore change only inside a state machine transition. Details are in coderd/x/chatd/ARCHITECTURE.md.

Compatibility

The frontend on main keeps working: editing_since is optional and main's UI never sets it. This PR adds paused to 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

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

@linear-code

linear-code Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

CODAGT-971

CODAGT-1028

@github-actions

github-actions Bot commented Sep 11, 2026 •

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 mafredri changed the title feat(coderd): hold queued chat messages for safe editing feat: hold queued chat messages for safe editing Sep 11, 2026
@mafredri
mafredri added this pull request to stack #29294 September 14, 2026 16:23
@mafredri mafredri changed the title feat: hold queued chat messages for safe editing feat: support editing queued chat messages Sep 16, 2026
@mafredri
mafredri force-pushed the mathias/codagt-971-queue-hold-backend branch from 28604ca to c188dec Compare September 17, 2026 15:19
@mafredri

Copy link
Copy Markdown
Member Author

A few design decisions worth pointing out that effect edge cases:

  1. If a chat is paused (due to a message under edit), you can't interrupt it to "idle", it errors/remains "paused"; the reason being that canceling the edit would reveal the message in the queue and thus resume the chat. Interrupts could in theory cancel an edit though, but the user started the edit so they should control when to exit it; could go either way.
  2. When editing a message on a paused chat, you can't switch to editing another message, but you can delete it, save it, or cancel the edit; I preferred this vs allowing "multiple edit" as it becomes complex to reason about. On a busy chat, switching is allowed: starting an edit on another message ends the previous one in the same request.
  3. You can always send a queued message immediately, bypassing the message under edit and leaving it in edit mode. This is because canceling the edit to send a message would create a race where the message in edit may be delivered before the message we wanted to promote.

@mafredri
mafredri requested a review from hugodutka September 17, 2026 17:53
@mafredri
mafredri marked this pull request as ready for review September 17, 2026 17:53
@coderagents

coderagents Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Documentation Check

Updates Needed

  • docs/ai-coder/agents/tasks-to-chats-migration.md - The status mapping table in "5. Update status handling" lists every Chats API status, but this PR adds paused to ChatStatus. The row mapping the Tasks API paused to "n/a" ("The Chats API equivalent is interrupt plus separate workspace lifecycle") is now misleading, and the table is missing a n/a / paused row explaining that the chat pauses while the owner edits its queued head message.
  • docs/ai-coder/agents/tasks-to-chats-migration.md - The "Features available only in the Chats API" table enumerates PATCH /chats/{chat}/messages/{message} under "Message editing" and automatic queuing under "Message queuing". This PR adds a new user-facing endpoint, PATCH /api/v2/chats/{chat}/queue/{queuedMessage}, for editing queued messages (including holding one under edit, which pauses the chat when it is the queue head). A row for editing queued messages belongs in that table.

Automated review via Coder Agents

Comment thread coderd/x/chatd/ARCHITECTURE.md Outdated

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please address those TODOs

@mafredri mafredri Sep 18, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. The document also covers interrupts that run ahead of the queue (#30729), SetProject from paused states (#30893), and skill resolution in queued edits (#30861).

🤖 Reply by Coder Agents on behalf of @mafredri.

Comment thread coderd/database/queries/chats.sql Resolved
Comment thread coderd/database/queries/chats.sql Outdated
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')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should also have interrupting

@mafredri mafredri Sep 18, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.';

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not the state machine promoting rows, it's the chat runner.

@mafredri mafredri Sep 18, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread coderd/x/chatd/chatstate/transition.go Outdated
// 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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this comment seems out of place here

@mafredri mafredri Sep 18, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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{

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@mafredri mafredri Sep 18, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread coderd/x/chatd/chatstate/state.go Outdated
type QueueState struct {
// HasRows is the "1" queue sub-state.
HasRows bool
// Paused is [queuePaused] of the head. Only P requires it.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why? isn't the fact that the status is paused sufficient to determine that we're in P?

@mafredri mafredri Sep 18, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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},

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

regarding our discussion, looks like the new states could come in handy

@mafredri mafredri Sep 18, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. The test enumerates each 1P state.

🤖 Reply by Coder Agents on behalf of @mafredri.

@mafredri
mafredri force-pushed the mathias/codagt-971-queue-hold-backend branch from 738bfa2 to b1c103e Compare September 22, 2026 13:45
jscottmiller pushed a commit that referenced this pull request Sep 22, 2026
#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.
@mafredri

This comment has been minimized.

@coder-agents-review

coder-agents-review Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Chat: Review in progress (19/19 reviewers complete) | View chat
Requested: 2026-09-24 16:27 UTC by @mafredri

deep-review v0.13.0 | Round 1 | d532b40..b1c103e

Status: Panel review (17 reviewers)

About deep-review

CRF = Coder Review Finding (P0-P4, Nit, Note)

Reviewer Focus
Bisky tests
Chopper ops/errors
Churn-guard change verification
Ging language modernization
Gon naming
Hisoka edge cases
Killua perf
Kite change integrity
Knov contracts
Knuckle SQL
Komugi flake/determinism
Kurapika security
Law decomposition
Leorio docs
Luffy product
Mafu-san process
Mafuuu contracts
Melody dispatch/pairing
Meruem structural
Nami frontend
Netero mechanical checks
Pariston premise testing
Pen-botter product gaps
Razor verification
Robin duplication
Ryosuke Go arch
Takumi concurrency
Zoro shape

🤖 Managed by Coder Agents.

@coder-agents-review coder-agents-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: GetStaleChats has no production caller, so the stranded waiting-with-rows chats its comment says it recovers are recovered only when a client calls the reconcile endpoint.
  • coderd/database/queries/chats.sql:2923: AutoArchiveInactiveChats has no production caller and archives with a direct UPDATE, so any future caller would bypass the state machine.
  • coderd/exp_chats.go:3038: DELETE and POST .../promote on 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: the list_agents status description omits requires_action, so the model gets no meaning for that value.

Notes:

  • PATCH returns 204 with no body, so a client learns the resulting row and chat status only from queue_update and status stream events.
  • No test drives the worker through P and a resume end to end; TestPatchChatQueuedMessage disables the worker and sets paused directly.

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.

Comment thread coderd/x/chatd/chatd.go Resolved
Comment thread coderd/x/chatd/chatd.go Outdated
}

contentParts := opts.Content
if len(contentParts) > 0 && p.hooks.Enabled() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

🤖

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-review skill via Coder Agents.

Comment thread coderd/exp_chats.go Resolved
// changes outside a transition leaves a paused chat that classifies
// invalid.
func queuePaused(head database.ChatQueuedMessage) bool {
return head.EditingSince.Valid

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

🤖

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Intended. An edit does not expire: it stays open until the owner ends it, or the message is promoted or deleted.

🤖 Posted using /amend-review skill via Coder Agents.

Comment thread coderd/x/chatd/chatstate/transitions.go Resolved
Comment thread coderd/exp_chats_queue_edit_test.go Resolved
@mafredri
mafredri force-pushed the mathias/codagt-971-queue-hold-backend branch from b1c103e to e39136c Compare September 28, 2026 19:36
@mafredri
mafredri requested a review from a team as a code owner September 28, 2026 19:36
@mafredri

Copy link
Copy Markdown
Member Author

In reply to CRF-5 (P3, coderd/x/chatd/chatstate/machine.go:56): #29215 (review)

Fixed in 65642a0: chatstate/doc.go and machine.go say queue state.


In reply to CRF-7 (P2, coderd/x/chatd/subagent.go:1643): #29215 (review)

Fixed in the stacked #29292: checkSubagentCompletion counts a paused child as not done, so wait_agent keeps waiting, and a timeout on a paused child says why.


In reply to CRF-23 (P4, coderd/x/chatd/subagent.go:1055): #29215 (review)

list_agents is covered in the stacked #29292, and 5534e79 there adds the paused outcome to the interrupt_agent description.


In reply to CRF-24 (P4, codersdk/toolsdk/chats.go:301): #29215 (review)

Fixed in a6b23b3: the AwaitChat description lists paused among the statuses that end the wait, which is what chatStatusBusy does today.

🤖 Posted using /amend-review skill via Coder Agents.

@mafredri
mafredri force-pushed the mathias/codagt-971-queue-hold-backend branch 2 times, most recently from 1ba2bd6 to cfdf0a0 Compare October 2, 2026 14:44
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.
@mafredri
mafredri force-pushed the mathias/codagt-971-queue-hold-backend branch from 7954fdb to 5eb7389 Compare October 30, 2026 13:10
@mafredri
mafredri merged commit c0f7663 into main Oct 30, 2026
49 of 51 checks passed
@mafredri
mafredri deleted the mathias/codagt-971-queue-hold-backend branch October 30, 2026 13:52
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 30, 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.

4 participants