fix(app): prevent queue bounce when reordering (#58074)

This commit is contained in:
usrnk1 2026-10-22 11:29:12 +02:00 • committed by GitHub
parent b7bf31b552
commit 6d273cf45f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 146 additions and 31 deletions

View file

@ -294,41 +294,125 @@ test("a steer into an idle session leaves the finished turn finished until deliv
await expect(finished).toHaveCount(1)
})
test("dragging reorders queued prompts", async ({ page }) => {
const mock = createQueueMock(["first queued prompt", "second queued prompt", "third queued prompt"])
mock.rows[0].payload.files = [
{ data: "aGk=", mime: "text/plain", source: { type: "uri", uri: "file:///repo/main.ts" }, name: "main.ts" },
]
const view = await openQueue(page, mock)
await expect(view.rows).toHaveCount(3)
for (const count of [2, 6]) {
test(`dragging reorders ${count} queued prompts without bouncing`, async ({ page }) => {
const order = Array.from({ length: count }, (_, index) => `queued prompt ${index + 1}`)
const mock = createQueueMock(order)
mock.rows[0].payload.files = [
{ data: "aGk=", mime: "text/plain", source: { type: "uri", uri: "file:///repo/main.ts" }, name: "main.ts" },
]
const view = await openQueue(page, mock)
await expect(view.rows).toHaveCount(count)
const texts = view.rows.locator('[data-action="session-queue-edit"]')
const panel = page.locator('[data-component="session-queue-panel"]')
const height = await panel.evaluate((el) => el.getBoundingClientRect().height)
const geometry = await panel.evaluateHandle((el) => {
const heights = [el.getBoundingClientRect().height]
const observer = new ResizeObserver(() => heights.push(el.getBoundingClientRect().height))
observer.observe(el)
return { heights, stop: () => observer.disconnect() }
})
const admission = await holdRoute(page, new RegExp(`/api/session/${sessionID}/prompt(\\?|$)`), { method: "POST" })
const cancellation = await holdRoute(page, new RegExp(`/api/session/${sessionID}/inbox/[^/?]+(\\?|$)`), {
method: "DELETE",
})
const first = view.rows.filter({ hasText: order[0] })
const targetIndex = Math.min(2, count - 1)
const destination = view.rows.filter({ hasText: order[targetIndex] })
await first.getByRole("button", { name: "Reorder queued prompt" }).hover()
await page.mouse.down()
const target = await destination.boundingBox()
if (!target) throw new Error("The target queue row is not visible")
await page.mouse.move(target.x + target.width / 2, target.y + target.height / 2, { steps: 10 })
await page.mouse.up()
const reordered = [...order.slice(1, targetIndex + 1), order[0], ...order.slice(targetIndex + 1)]
await admission.arrived
await expect(texts).toHaveText(reordered)
await expect(view.rows).toHaveCount(count)
admission.release()
// All replacements are admitted while the originals still exist. Neither copies nor extra height may leak out.
await cancellation.arrived
await expect(texts).toHaveText(reordered)
await expect(view.rows).toHaveCount(count)
const reconciliation = await holdRoute(page, new RegExp(`/api/session/${sessionID}/inbox(\\?|$)`), {
method: "GET",
})
cancellation.release()
await reconciliation.arrived
await expect(texts).toHaveText(reordered)
await expect(view.rows).toHaveCount(count)
reconciliation.release()
await expect(
view.rows.filter({ hasText: order[1] }).getByRole("button", { name: "Remove", exact: true }),
).toBeEnabled()
await expect(texts).toHaveText(reordered)
expect(
await geometry.evaluate((value) => {
value.stop()
return Math.max(...value.heights) - Math.min(...value.heights)
}),
).toBeLessThanOrEqual(1)
expect(await panel.evaluate((el) => el.getBoundingClientRect().height)).toBeCloseTo(height, 0)
await geometry.dispose()
expect(mock.prompts.map((prompt) => prompt.text)).toEqual(reordered)
// A re-admitted file keeps the URI it came from instead of becoming an inline snapshot.
expect(mock.prompts[targetIndex].files).toMatchObject([{ uri: "file:///repo/main.ts", name: "main.ts" }])
expect(mock.changes).toEqual(order.map((_, index) => ({ inboxID: `inb_seed_${index + 1}`, action: "cancel" })))
// The handoff must leave actions targeting the new inbox IDs, not the optimistic row keys.
await view.rows.getByText(order[0], { exact: true }).click()
await expect(view.input).toHaveText(order[0])
})
}
test("a partially cancelled reorder reconciles the server's queue instead of restoring stale rows", async ({
page,
}) => {
const mock = createQueueMock(["first queued prompt", "second queued prompt"])
const change = mock.onInboxChange
mock.onInboxChange = (input) => {
if (input.inboxID === "inb_seed_2") throw new Error("Cancellation failed")
change(input)
}
const view = await openQueue(page, mock)
await expect(view.rows).toHaveCount(2)
const admission = await holdRoute(page, new RegExp(`/api/session/${sessionID}/prompt(\\?|$)`), { method: "POST" })
const first = view.rows.filter({ hasText: "first queued prompt" })
const third = view.rows.filter({ hasText: "third queued prompt" })
const second = view.rows.filter({ hasText: "second queued prompt" })
await first.getByRole("button", { name: "Reorder queued prompt" }).hover()
await page.mouse.down()
const target = await third.boundingBox()
const target = await second.boundingBox()
if (!target) throw new Error("The target queue row is not visible")
await page.mouse.move(target.x + target.width / 2, target.y + target.height / 2, { steps: 10 })
await page.mouse.up()
await admission.arrived
await expect(view.rows.locator('[data-action="session-queue-edit"]')).toHaveText([
"second queued prompt",
"third queued prompt",
"first queued prompt",
])
expect(mock.prompts.map((prompt) => prompt.text)).toEqual([
admission.release()
// One original survived alongside the replacements: do not pretend the failed rewrite was rolled back.
await expect(view.rows.locator('[data-action="session-queue-edit"]')).toHaveText([
"second queued prompt",
"second queued prompt",
"third queued prompt",
"first queued prompt",
])
// A re-admitted file keeps the URI it came from instead of becoming an inline snapshot.
expect(mock.prompts[2].files).toMatchObject([{ uri: "file:///repo/main.ts", name: "main.ts" }])
expect(mock.changes).toEqual([
{ inboxID: "inb_seed_1", action: "cancel" },
{ inboxID: "inb_seed_2", action: "cancel" },
{ inboxID: "inb_seed_3", action: "cancel" },
])
await expect(first.getByRole("button", { name: "Remove", exact: true })).toBeEnabled()
await first.getByRole("button", { name: "Remove", exact: true }).click()
await expect.poll(() => mock.changes.at(-1)).toEqual({ inboxID: mock.prompts[1].id, action: "cancel" })
})
for (const change of ["reorder", "edit"] as const) {
@ -375,6 +459,9 @@ for (const change of ["reorder", "edit"] as const) {
)
await expect(view.rows.locator('[data-action="session-queue-edit"]')).toHaveText(order)
expect(mock.rows.map((row) => row.payload.text)).toEqual(order)
await expect(
view.rows.filter({ hasText: order[0] }).getByRole("button", { name: "Remove", exact: true }),
).toBeEnabled()
// A failed edit keeps its draft in the composer so nothing typed is lost.
if (change === "edit") await expect(view.input).toHaveText("second queued prompt, edited")
@ -1058,8 +1145,8 @@ for (const delivery of ["steer", "queue"] as const) {
})),
pending: await bubble.evaluate((element) => {
const probe = document.createElement("span")
probe.style.backgroundColor = "var(--v2-background-bg-layer-02)"
probe.style.color = "var(--v2-text-text-base)"
probe.style.backgroundColor = "var(--v2-background-bg-layer-01)"
probe.style.color = "var(--v2-text-text-muted)"
element.appendChild(probe)
const colors = {
@ -1080,9 +1167,7 @@ for (const delivery of ["steer", "queue"] as const) {
await expect(bubble).toHaveCSS("color", colors.pending.text)
await expect(bubble).toHaveCSS("transition-duration", "0s")
await expect(pending.locator('[data-slot="user-message-copy-wrapper"]')).toHaveCSS("opacity", "1")
await expect(pending.locator('[data-slot="user-message-meta"]')).toHaveText(
/^Pending\s*·\s*Build\s*·\s*Queue Model$/,
)
await expect(pending.locator('[data-slot="user-message-meta"]')).toHaveText(/^Pending\s*·\s*Queue Model$/)
await bubble.evaluate((element) => (element.dataset.deliveryMarker = "pending"))
}
@ -1164,7 +1249,7 @@ for (const delivery of ["steer", "queue"] as const) {
if (colors) {
await expect(bubble).toHaveAttribute("data-delivery-marker", "pending")
await expect(pending.locator('[data-slot="user-message-meta"]')).toHaveText(/^Build\s*·\s*Queue Model$/)
await expect(pending.locator('[data-slot="user-message-meta"]')).toHaveText("Queue Model")
await expect(bubble).toHaveCSS("background-color", colors.delivered.background)
await expect(bubble).toHaveCSS("color", colors.delivered.text)
// Only delivery animates the colour; reduced motion switches instantly.

View file

@ -57,6 +57,9 @@ export function createSessionQueue(input: {
const [state, setState] = createStore<{
editing?: { id: string; stash: EditStash }
sent: SentEdit[]
// Reordering re-admits prompts under new inbox IDs. Keep their existing row keys until the
// whole rewrite settles so admission and cancellation events cannot grow or shrink the strip.
reordering?: { rows: ReturnType<typeof queuedPromptRows>; moved: Record<string, string> }
// Prompts the server confirmed have left the queue. The pending list only drops them when the
// server's events arrive, which lag on a loaded server, so the strip hides them until then.
gone: string[]
@ -163,7 +166,12 @@ export function createSessionQueue(input: {
if (sent?.admitted) return
restoreEdit(change.prompt)
},
onSettled: () => data.session.pending.sync(input.sessionID).catch(() => undefined),
onSettled: async (_data, _error, change) => {
if (change.type === "reorder") data.session.pending.invalidate(input.sessionID)
await data.session.pending.sync(input.sessionID).catch(() => undefined)
if (change.type === "reorder") setState("reordering", undefined)
},
}))
const queued = createMemo(() =>
@ -172,7 +180,16 @@ export function createSessionQueue(input: {
.filter((item): item is QueuedPrompt => item.type === "user" && item.delivery === "queue"),
)
const rows = createMemo(() => queuedPromptRows(queued(), state.sent, state.gone))
const rows = createMemo(() => {
const current = queuedPromptRows(queued(), state.sent, state.gone)
const reordering = state.reordering
if (!reordering) return current
const hidden = new Set([...reordering.rows.map((row) => row.id), ...Object.values(reordering.moved)])
// Fresh prompts still appear while the reordered rows keep their optimistic positions.
return [...reordering.rows, ...current.filter((row) => !hidden.has(row.id))]
})
createEffect(() => {
const listed = new Set(queued().map((item) => item.id))
@ -236,6 +253,8 @@ export function createSessionQueue(input: {
if (replace) setState("sent", (edit) => edit.original === replace.original, "moved", moved)
if (!replace) setState("reordering", "moved", moved)
for (const item of ordered.slice(changed)) {
const admission =
item.id === replace?.original
@ -263,7 +282,12 @@ export function createSessionQueue(input: {
await data.session.prompt({ ...admission, id }).catch(async (error) => {
await Promise.all(
replacements.map((inboxID) =>
server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID }).catch(() => undefined),
server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID }).then(
() => {
if (!replace) hide([inboxID])
},
() => undefined,
),
),
)
throw error
@ -278,6 +302,8 @@ export function createSessionQueue(input: {
for (const item of replace ? replaced.reverse() : replaced) {
await server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID: item.id })
if (!replace) hide([item.id])
}
}
@ -342,12 +368,16 @@ export function createSessionQueue(input: {
}
const reorder = (inboxIDs: string[]) => {
if (mutation.isPending || refuseReverted()) return Promise.resolve()
if (state.reordering || mutation.isPending || refuseReverted()) return Promise.resolve()
const current = rows()
setState("reordering", { rows: inboxIDs.flatMap((id) => current.filter((row) => row.id === id)), moved: {} })
return mutation.mutateAsync({ type: "reorder", inboxIDs }).catch(() => undefined)
}
const sending = (id: string) => state.sent.some((edit) => id in edit.moved || Object.values(edit.moved).includes(id))
const sending = (id: string) =>
state.reordering?.rows.some((row) => row.id === id) ||
state.sent.some((edit) => id in edit.moved || Object.values(edit.moved).includes(id))
// Other rows stay editable while a change is in flight; the row it is changing ignores clicks
// and shows as pending until the server catches up.