mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
fix(app): edit queued prompts in place
User decisions: - Reproduce the queued edit through a normal caller on current v2 before fixing it. - Keep the fix minimal and verify a regression test fails before and passes after. - Publish the topic branch as a draft PR for review.
This commit is contained in:
parent
28f74f8591
commit
cb1ac3a3d1
26 changed files with 649 additions and 300 deletions
|
|
@ -97,6 +97,20 @@ function createQueueMock(seed: string[], messages: SessionMessageInfo[] = []) {
|
|||
shells,
|
||||
emit,
|
||||
events: () => events.splice(0),
|
||||
onInboxEdit: (input: Parameters<NonNullable<MockServerConfig["onInboxEdit"]>>[0]) => {
|
||||
const original = rows.find((item) => item.id === input.inboxID && item.delivery === "queue")
|
||||
if (!original) throw new Error("Original delivered")
|
||||
const body = decodePromptBody(input.body)
|
||||
prompts.push(body)
|
||||
original.payload = {
|
||||
text: body.text,
|
||||
metadata: body.metadata,
|
||||
files: body.files?.map(storedFile),
|
||||
agents: body.agents?.map((agent) => ({ ...agent })),
|
||||
}
|
||||
original.delivery = body.delivery ?? "queue"
|
||||
emit("session.inbox.edited", original)
|
||||
},
|
||||
onPrompt: (input: Parameters<NonNullable<MockServerConfig["onPrompt"]>>[0]) => {
|
||||
const body = decodePromptBody(input.body)
|
||||
prompts.push(body)
|
||||
|
|
@ -188,6 +202,7 @@ async function openQueue(
|
|||
sessionStatus: () => ({ [sessionID]: { type: status } }),
|
||||
inbox: () => [...mock.rows.map((row) => ({ ...row, payload: { ...row.payload } })), ...mock.compactions],
|
||||
onPrompt: mock.onPrompt,
|
||||
onInboxEdit: mock.onInboxEdit,
|
||||
onCompact: mock.onCompact,
|
||||
onInboxChange: mock.onInboxChange,
|
||||
onBackground: mock.onBackground,
|
||||
|
|
@ -666,10 +681,13 @@ test("a partially cancelled reorder reconciles the server's queue instead of res
|
|||
})
|
||||
|
||||
for (const change of ["reorder", "edit"] as const) {
|
||||
test(`a ${change} that cannot re-admit a prompt leaves the queue unchanged`, async ({ page }) => {
|
||||
test(`a ${change} that the server rejects leaves the queue unchanged`, async ({ page }) => {
|
||||
const order = ["first queued prompt", "second queued prompt", "third queued prompt"]
|
||||
const mock = createQueueMock(order)
|
||||
const admit = mock.onPrompt
|
||||
mock.onInboxEdit = () => {
|
||||
throw new Error("Cannot prepare attachment")
|
||||
}
|
||||
// The last prompt's re-admission fails after the server admitted it, so its response is lost.
|
||||
mock.onPrompt = (input) => {
|
||||
admit(input)
|
||||
|
|
@ -702,7 +720,8 @@ for (const change of ["reorder", "edit"] as const) {
|
|||
}
|
||||
|
||||
// The replacements admitted before the failure are withdrawn; the originals stay in place.
|
||||
await expect.poll(() => mock.log.includes(`cancel:${mock.prompts.at(-1)?.id}`)).toBe(true)
|
||||
if (change === "edit") await expect(page.getByText("Request failed")).toBeVisible()
|
||||
if (change === "reorder") await expect.poll(() => mock.log.includes(`cancel:${mock.prompts.at(-1)?.id}`)).toBe(true)
|
||||
await expect.poll(() => mock.changes.length).toBe(mock.prompts.length)
|
||||
expect(mock.changes.every((entry) => entry.action === "cancel" && !entry.inboxID.startsWith("inb_seed_"))).toBe(
|
||||
true,
|
||||
|
|
@ -746,19 +765,31 @@ test("editing restores the existing draft and replaces only the original queue p
|
|||
"third queued prompt",
|
||||
])
|
||||
await expect(view.input).toHaveText("my in-progress draft")
|
||||
// The strip shows the edit before the server confirms it; wait for the rewrite to finish.
|
||||
await expect.poll(() => mock.changes.length).toBe(2)
|
||||
// One rewrite from the edited position: the replacement, then the prompts after it.
|
||||
expect(mock.prompts.map((prompt) => prompt.text)).toEqual([
|
||||
"tighten the error copy and add a retry hint",
|
||||
"third queued prompt",
|
||||
])
|
||||
expect(mock.prompts.every((prompt) => prompt.delivery === "queue" && prompt.resume === false)).toBe(true)
|
||||
expect(mock.changes).toEqual([
|
||||
{ inboxID: "inb_seed_3", action: "cancel" },
|
||||
{ inboxID: "inb_seed_2", action: "cancel" },
|
||||
])
|
||||
expect(mock.log[0]).toBe("prompt:queue")
|
||||
await expect
|
||||
.poll(() => mock.prompts.map((prompt) => prompt.text))
|
||||
.toEqual(["tighten the error copy and add a retry hint"])
|
||||
expect(mock.rows.map((item) => item.id)).toEqual(["inb_seed_1", "inb_seed_2", "inb_seed_3"])
|
||||
expect(mock.changes).toEqual([])
|
||||
})
|
||||
|
||||
test("an edit racing delivery keeps the edit draft and sends only the original", async ({ page }) => {
|
||||
const mock = createQueueMock(["B"])
|
||||
const view = await openQueue(page, mock, "queue")
|
||||
await view.rows.getByText("B", { exact: true }).click()
|
||||
await expect(view.input).toBeFocused()
|
||||
await view.input.press("End")
|
||||
await view.input.pressSequentially("2")
|
||||
|
||||
// Let the runner take B just before the write that would change or remove B.
|
||||
// In the admit/cancel implementation the replacement is already queued at this point.
|
||||
await page.route(`**/api/session/${sessionID}/**`, async (route) => {
|
||||
if (["DELETE", "PUT"].includes(route.request().method()) && mock.rows[0]?.payload.text === "B") mock.rows.shift()
|
||||
await route.fallback()
|
||||
})
|
||||
await view.input.press("Enter")
|
||||
await expect(page.getByText("Request failed")).toBeVisible()
|
||||
await expect(view.input).toHaveText("B2")
|
||||
expect(mock.rows.map((row) => row.payload.text)).toEqual([])
|
||||
})
|
||||
|
||||
test("a queued prompt the server delivers mid-edit returns the draft typed before the edit", async ({ page }) => {
|
||||
|
|
@ -801,7 +832,7 @@ for (const delivery of ["queue", "steer"] as const) {
|
|||
}
|
||||
|
||||
for (const change of ["reorder", "edit"] as const) {
|
||||
test(`a staged revert refuses a queue ${change}, whose admission would commit it`, async ({ page }) => {
|
||||
test(`a staged revert refuses a queue ${change}`, async ({ page }) => {
|
||||
const order = ["first queued prompt", "second queued prompt"]
|
||||
|
||||
const mock = createQueueMock(order, [
|
||||
|
|
@ -843,11 +874,9 @@ for (const delivery of ["steer", "queue"] as const) {
|
|||
},
|
||||
]
|
||||
const view = await openQueue(page, mock)
|
||||
// A loaded server answers admissions and cancellations late; hold both until the strip is checked.
|
||||
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 edit = await holdRoute(page, new RegExp(`/api/session/${sessionID}/inbox/inb_seed_2(\\?|$)`), {
|
||||
method: "PUT",
|
||||
})
|
||||
|
||||
const texts = view.rows.locator('[data-action="session-queue-edit"]')
|
||||
|
|
@ -859,7 +888,7 @@ for (const delivery of ["steer", "queue"] as const) {
|
|||
await view.input.press("End")
|
||||
await view.input.pressSequentially(", edited")
|
||||
await view.input.press(delivery === "queue" ? "Enter" : "ControlOrMeta+Enter")
|
||||
await admission.arrived
|
||||
await edit.arrived
|
||||
|
||||
// The composer is free at once and the strip shows the edit, pending, in the original's place.
|
||||
const edited = view.rows.filter({ hasText: "second queued prompt, edited" })
|
||||
|
|
@ -885,13 +914,12 @@ for (const delivery of ["steer", "queue"] as const) {
|
|||
? ["first queued prompt, edited too", "second queued prompt, edited"]
|
||||
: ["first queued prompt, edited too"]
|
||||
|
||||
admission.release()
|
||||
await cancellation.arrived
|
||||
cancellation.release()
|
||||
edit.release()
|
||||
|
||||
await expect(texts).toHaveText(final)
|
||||
await expect(view.rows.and(page.locator('[aria-busy="true"]'))).toHaveCount(0)
|
||||
// The steered or queued edit was admitted once, with its attachment, and no original is left.
|
||||
// The same two items survive the edits with their IDs and attachment intact.
|
||||
expect(mock.rows.map((row) => row.id)).toEqual(["inb_seed_1", "inb_seed_2"])
|
||||
expect(mock.prompts[0]).toMatchObject({ text: "second queued prompt, edited", delivery })
|
||||
expect(mock.prompts[0].files?.map((file) => file.uri.startsWith("data:image/png;"))).toEqual([true])
|
||||
await expect
|
||||
|
|
|
|||
|
|
@ -485,6 +485,13 @@ const Group = HttpApiGroup.make("mock")
|
|||
success: NoContent,
|
||||
}),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.put("sessionInboxEdit", "/api/session/:sessionID/inbox/:inboxID", {
|
||||
params: { ...SessionParams, inboxID: Schema.String },
|
||||
payload: JsonPayload,
|
||||
success: NoContent,
|
||||
}),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.patch("sessionInboxUpdate", "/api/session/:sessionID/inbox/:inboxID", {
|
||||
params: { ...SessionParams, inboxID: Schema.String },
|
||||
|
|
|
|||
|
|
@ -161,6 +161,7 @@ export interface MockServerConfig {
|
|||
sessionStatus?: Resolvable<Record<string, { type: string }>>
|
||||
inbox?: unknown[] | (() => unknown[])
|
||||
onPrompt?: (input: { sessionID: string; body: Schema.JsonObject }) => void
|
||||
onInboxEdit?: (input: { sessionID: string; inboxID: string; body: Schema.JsonObject }) => void
|
||||
onCompact?: (input: { sessionID: string; body: Schema.JsonObject }) => void
|
||||
// POST /api/session/:id/fork creates `<id>_fork` in the same directory. The hook may hold the request, or return an
|
||||
// answer to replace the response.
|
||||
|
|
@ -1342,6 +1343,10 @@ function mockHandlers(
|
|||
text: "Side-question answer",
|
||||
},
|
||||
})),
|
||||
sessionInboxEdit: (ctx) =>
|
||||
Effect.sync(() =>
|
||||
config.onInboxEdit?.({ ...ctx.params, body: Option.getOrElse(decodeJsonObject(ctx.payload), () => ({})) }),
|
||||
).pipe(Effect.andThen(noContent)),
|
||||
sessionInboxCancel: (ctx) =>
|
||||
Effect.sync(() =>
|
||||
config.onInboxChange?.({ sessionID: ctx.params.sessionID, inboxID: ctx.params.inboxID, action: "cancel" }),
|
||||
|
|
|
|||
|
|
@ -31,8 +31,6 @@ const draft = (content: string): EditStash => ({
|
|||
retry: undefined,
|
||||
})
|
||||
|
||||
const ids = ["new_1", "new_2", "new_3", "new_4"]
|
||||
|
||||
// Replays events through the pure transition, collecting every effect in order.
|
||||
function replay(state: QueueState, events: QueueEvent[]) {
|
||||
const effects: QueueEffect[] = []
|
||||
|
|
@ -140,7 +138,7 @@ describe("an edit always returns the draft it replaced", () => {
|
|||
test("when the server delivers it while another row's edit is in flight", () => {
|
||||
const result = replay(createQueueState([one, two]), [
|
||||
{ type: "edit.start", id: "inb_2", reverted: false, draft: draft("") },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_2 edited"), ids },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_2 edited") },
|
||||
{ type: "edit.start", id: "inb_1", reverted: false, draft: draft("my unsent draft") },
|
||||
])
|
||||
|
||||
|
|
@ -167,7 +165,7 @@ describe("an edit always returns the draft it replaced", () => {
|
|||
test("a failed edit that never reached the server returns to the composer", () => {
|
||||
const sent = replay(createQueueState([one, two]), [
|
||||
{ type: "edit.start", id: "inb_1", reverted: false, draft: draft("") },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_1 edited"), ids },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_1 edited") },
|
||||
])
|
||||
|
||||
const attempt = runs(sent.effects)[0].attempt
|
||||
|
|
@ -176,12 +174,6 @@ describe("an edit always returns the draft it replaced", () => {
|
|||
expect(failed.state.status).toBe("idle")
|
||||
expect(failed.effects).toContainEqual({ type: "draft.merge", prompt: prompt("inb_1 edited"), context: [] })
|
||||
expect(rowIDs(failed.state)).toEqual(["inb_1", "inb_2"])
|
||||
|
||||
// Once every replacement is admitted, a failure leaves the edit with the server.
|
||||
const admitted = transitionQueue(sent.state, { type: "mutation.admitted", attempt })
|
||||
const late = transitionQueue(admitted.state, { type: "mutation.failed", attempt, hidden: [] })
|
||||
|
||||
expect(late.effects.some((effect) => effect.type === "draft.merge")).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
|
|
@ -227,9 +219,9 @@ describe("queue changes run one at a time", () => {
|
|||
test("confirming an unchanged edit as a steer waits behind the edit in flight", () => {
|
||||
const result = replay(createQueueState([one, two]), [
|
||||
{ type: "edit.start", id: "inb_2", reverted: false, draft: draft("") },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_2 edited"), ids },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_2 edited") },
|
||||
{ type: "edit.start", id: "inb_1", reverted: false, draft: draft("my draft") },
|
||||
{ type: "edit.confirm", delivery: "steer", reverted: false, prompt: prompt("inb_1 text"), ids },
|
||||
{ type: "edit.confirm", delivery: "steer", reverted: false, prompt: prompt("inb_1 text") },
|
||||
])
|
||||
|
||||
expect(result.state).toMatchObject({ status: "mutating", pending: [{ type: "steer", id: "inb_1" }] })
|
||||
|
|
@ -241,33 +233,26 @@ describe("queue changes run one at a time", () => {
|
|||
describe("replaced inbox IDs", () => {
|
||||
const moved = (state: QueueState) => viewQueue(state, { working: true, behavior: "queue" }).moved
|
||||
|
||||
// Edits `id` as a queued prompt; its replacement and the prompts after it take `next`.
|
||||
function edit(state: QueueState, id: string, next: string[]) {
|
||||
const confirmed = replay(state, [
|
||||
{ type: "edit.start", id, reverted: false, draft: draft("") },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt(`${id} edited`), ids: next },
|
||||
])
|
||||
function reorder(state: QueueState, first: string, second: string, moved: Record<string, string>) {
|
||||
const requested = transitionQueue(state, { type: "reorder.requested", inboxIDs: [second, first], reverted: false })
|
||||
const attempt = runs(requested.effects)[0].attempt
|
||||
|
||||
return { state: confirmed.state, attempt: runs(confirmed.effects)[0].attempt }
|
||||
return { state: transitionQueue(requested.state, { type: "mutation.moved", moved, attempt }).state, attempt }
|
||||
}
|
||||
|
||||
test("an edit's replacements chain across later edits until their prompts leave the queue", () => {
|
||||
const first = edit(createQueueState([one]), "inb_1", ["msg_1"])
|
||||
// In flight, the panel already sees the replacement it may swap in.
|
||||
expect(moved(first.state)).toEqual({ inb_1: "msg_1" })
|
||||
test("a reorder's replacements chain across later reorders until their prompts leave the queue", () => {
|
||||
const first = reorder(createQueueState([one, two]), one.id, two.id, { inb_1: "msg_1", inb_2: "other_1" })
|
||||
expect(moved(first.state)).toEqual({ inb_1: "msg_1", inb_2: "other_1" })
|
||||
|
||||
const settled = replay(first.state, [
|
||||
{ type: "inbox.synced", items: [item("msg_1")] },
|
||||
{ type: "inbox.synced", items: [item("other_1"), item("msg_1")] },
|
||||
{ type: "mutation.succeeded", attempt: first.attempt },
|
||||
]).state
|
||||
|
||||
expect(settled.status).toBe("idle")
|
||||
expect(moved(settled)).toEqual({ inb_1: "msg_1" })
|
||||
|
||||
const second = edit(settled, "msg_1", ["msg_2"])
|
||||
const second = reorder(settled, "other_1", "msg_1", { msg_1: "msg_2", other_1: "other_2" })
|
||||
|
||||
const chained = replay(second.state, [
|
||||
{ type: "inbox.synced", items: [item("msg_2")] },
|
||||
{ type: "inbox.synced", items: [item("msg_2"), item("other_2")] },
|
||||
{ type: "mutation.succeeded", attempt: second.attempt },
|
||||
]).state
|
||||
|
||||
|
|
@ -277,14 +262,6 @@ describe("replaced inbox IDs", () => {
|
|||
// Once the last replacement is delivered, nothing it maps is queued.
|
||||
expect(moved(transitionQueue(chained, { type: "inbox.synced", items: [] }).state)).toEqual({})
|
||||
})
|
||||
|
||||
test("a failed edit leaves no replacement behind", () => {
|
||||
const sent = edit(createQueueState([one, two]), "inb_1", ["msg_1", "msg_2"])
|
||||
expect(moved(sent.state)).toEqual({ inb_1: "msg_1", inb_2: "msg_2" })
|
||||
|
||||
const failed = transitionQueue(sent.state, { type: "mutation.failed", attempt: sent.attempt, hidden: [] })
|
||||
expect(moved(failed.state)).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe("optimistic rows", () => {
|
||||
|
|
@ -320,12 +297,12 @@ describe("optimistic rows", () => {
|
|||
test("an edit in flight shows on its row as pending", () => {
|
||||
const result = replay(createQueueState([one, two]), [
|
||||
{ type: "edit.start", id: "inb_1", reverted: false, draft: draft("") },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_1 edited"), ids },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_1 edited") },
|
||||
])
|
||||
|
||||
expect(selectQueueRows(result.state)).toEqual([
|
||||
{ id: "inb_1", text: "inb_1 edited", attachments: 0, pending: true },
|
||||
{ id: "inb_2", text: "inb_2 text", attachments: 0, pending: true },
|
||||
{ id: "inb_2", text: "inb_2 text", attachments: 0, pending: undefined },
|
||||
])
|
||||
// A pending row cannot be opened again.
|
||||
expect(
|
||||
|
|
@ -385,7 +362,7 @@ describe("stale results", () => {
|
|||
test("an edit the server never admitted before dispose returns to the saved draft if it then fails", () => {
|
||||
const sent = replay(createQueueState([one]), [
|
||||
{ type: "edit.start", id: "inb_1", reverted: false, draft: draft("") },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_1 edited"), ids },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_1 edited") },
|
||||
{ type: "dispose" },
|
||||
])
|
||||
|
||||
|
|
@ -395,7 +372,7 @@ describe("stale results", () => {
|
|||
{ type: "draft.merge", prompt: prompt("inb_1 edited"), context: [], focus: false },
|
||||
])
|
||||
|
||||
const admitted = transitionQueue(sent.state, { type: "mutation.admitted", attempt }).state
|
||||
const admitted = transitionQueue(sent.state, { type: "mutation.succeeded", attempt }).state
|
||||
|
||||
expect(transitionQueue(admitted, { type: "mutation.failed", attempt, hidden: [] }).effects).toEqual([])
|
||||
})
|
||||
|
|
@ -441,7 +418,7 @@ describe("an operation past its bound", () => {
|
|||
test("a steered edit whose admission is in flight keeps the edit until the server answers", () => {
|
||||
const sent = replay(createQueueState([one, two]), [
|
||||
{ type: "edit.start", id: "inb_1", reverted: false, draft: draft("") },
|
||||
{ type: "edit.confirm", delivery: "steer", reverted: false, prompt: prompt("inb_1 edited"), ids },
|
||||
{ type: "edit.confirm", delivery: "steer", reverted: false, prompt: prompt("inb_1 edited") },
|
||||
])
|
||||
|
||||
const attempt = runs(sent.effects)[0].attempt
|
||||
|
|
@ -451,14 +428,7 @@ describe("an operation past its bound", () => {
|
|||
expect(waiting.state).toBe(sent.state)
|
||||
expect(waiting.effects).toEqual([])
|
||||
|
||||
// Delivered, a later failure of the original's cancel leaves the edit with the server.
|
||||
const admitted = transitionQueue(waiting.state, { type: "mutation.admitted", attempt }).state
|
||||
|
||||
expect(
|
||||
transitionQueue(admitted, { type: "mutation.failed", attempt, hidden: [] }).effects.some(
|
||||
(effect) => effect.type === "draft.merge",
|
||||
),
|
||||
).toBe(false)
|
||||
expect(transitionQueue(waiting.state, { type: "mutation.succeeded", attempt }).state.status).toBe("idle")
|
||||
|
||||
// Refused, it really did not go out, so it returns to the composer.
|
||||
expect(transitionQueue(waiting.state, { type: "mutation.failed", attempt, hidden: [] }).effects).toContainEqual({
|
||||
|
|
@ -505,7 +475,7 @@ describe("an operation past its bound", () => {
|
|||
test("an edit the server holds whose queue re-read stalled counts as done", () => {
|
||||
const sent = replay(createQueueState([one]), [
|
||||
{ type: "edit.start", id: "inb_1", reverted: false, draft: draft("") },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_1 edited"), ids },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt("inb_1 edited") },
|
||||
])
|
||||
|
||||
const attempt = runs(sent.effects)[0].attempt
|
||||
|
|
|
|||
|
|
@ -32,8 +32,7 @@ export type QueueRow = {
|
|||
readonly pending?: boolean
|
||||
}
|
||||
|
||||
// An edit confirmed from the composer. `moved` maps each inbox ID the edit replaces to the ID admitted in its place:
|
||||
// the original's replacement and, for a queued edit, the prompts after it, re-admitted to keep their order.
|
||||
// An edit confirmed from the composer keeps its inbox ID.
|
||||
export type EditOperation = {
|
||||
readonly type: "edit"
|
||||
readonly original: string
|
||||
|
|
@ -43,7 +42,6 @@ export type EditOperation = {
|
|||
readonly raw: string
|
||||
readonly text: string
|
||||
readonly attachments: number
|
||||
readonly moved: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
export type QueuedOperation =
|
||||
|
|
@ -52,10 +50,9 @@ export type QueuedOperation =
|
|||
| { readonly type: "remove"; readonly id: string }
|
||||
| { readonly type: "first"; readonly id: string }
|
||||
|
||||
// Operations that leave the composer free, so a row can be edited while one runs. `cancelling` means the server
|
||||
// admitted every replacement, so a later failure must not hand the edit back to the composer.
|
||||
// Operations that leave the composer free, so a row can be edited while one runs.
|
||||
export type ConcurrentOperation =
|
||||
| (EditOperation & { readonly attempt: number; readonly phase: "admitting" | "cancelling" })
|
||||
| (EditOperation & { readonly attempt: number })
|
||||
| { readonly type: "steer"; readonly attempt: number; readonly id: string }
|
||||
| { readonly type: "remove"; readonly attempt: number; readonly id: string }
|
||||
|
||||
|
|
@ -81,7 +78,7 @@ type QueueBase = {
|
|||
readonly seq: number
|
||||
readonly items: readonly QueuedPrompt[]
|
||||
readonly gone: readonly GoneEntry[]
|
||||
// Each inbox ID a finished edit or reorder replaced, mapped to the ID admitted in its place, so the strip can swap
|
||||
// Each inbox ID a finished reorder replaced, mapped to the ID admitted in its place, so the strip can swap
|
||||
// the row in place. An entry is dropped once no ID along its chain is queued.
|
||||
readonly moved: Readonly<Record<string, string>>
|
||||
}
|
||||
|
|
@ -96,8 +93,8 @@ const NO_MOVES: Readonly<Record<string, string>> = Object.freeze({})
|
|||
export const QUEUE_MUTATION_TIMEOUT_MS = 60_000
|
||||
|
||||
/**
|
||||
* How far a timed-out operation got. `committed`: a step it cannot take back is in flight (an undo's cancel, a steered
|
||||
* edit's admission, or the cancels of a rewrite's originals once every copy is in), so the operation waits for its
|
||||
* How far a timed-out operation got. `committed`: a step it cannot take back is in flight (an undo's cancel, a queued
|
||||
* edit's write, or the cancels of a rewrite's originals once every copy is in), so the operation waits for its
|
||||
* result. `settled`: the server holds the whole change and only re-reading its queue stalled.
|
||||
*/
|
||||
export type QueueMutationStage = "running" | "committed" | "settled"
|
||||
|
|
@ -137,8 +134,6 @@ export type QueueEvent =
|
|||
readonly delivery: ComposerDelivery
|
||||
readonly reverted: boolean
|
||||
readonly prompt: Prompt
|
||||
// Fresh inbox IDs, one per queued prompt, for the replacements an edit admits.
|
||||
readonly ids: readonly string[]
|
||||
}
|
||||
| { readonly type: "reorder.requested"; readonly inboxIDs: readonly string[]; readonly reverted: boolean }
|
||||
| { readonly type: "first.requested"; readonly id: string; readonly reverted: boolean }
|
||||
|
|
@ -147,7 +142,6 @@ export type QueueEvent =
|
|||
| { readonly type: "remove.requested"; readonly id: string }
|
||||
| { readonly type: "undo.requested"; readonly id: string; readonly mode: "normal" | "shell" }
|
||||
| { readonly type: "mutation.moved"; readonly attempt: number; readonly moved: Readonly<Record<string, string>> }
|
||||
| { readonly type: "mutation.admitted"; readonly attempt: number }
|
||||
| { readonly type: "mutation.succeeded"; readonly attempt: number }
|
||||
| {
|
||||
readonly type: "mutation.undone"
|
||||
|
|
@ -205,7 +199,7 @@ export type QueueView = {
|
|||
readonly undoing: boolean
|
||||
readonly delivery: ComposerDelivery
|
||||
readonly alternate: ComposerDelivery | undefined
|
||||
/** Inbox IDs replaced by an edit or reorder, finished or in flight, mapped to their replacements. */
|
||||
/** Inbox IDs replaced by a reorder, finished or in flight, mapped to their replacements. */
|
||||
readonly moved: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
|
|
@ -269,14 +263,9 @@ export function transitionQueue(state: QueueState, event: QueueEvent): QueueTran
|
|||
const edit = editOf(state)
|
||||
const active = state.status === "mutating" || state.status === "editing-while-mutating" ? state.active : undefined
|
||||
|
||||
const returning: DisposedReturn | undefined =
|
||||
active?.type === "edit" && active.phase === "admitting"
|
||||
? { type: "edit", attempt: active.attempt, prompt: active.prompt }
|
||||
: active?.type === "undo"
|
||||
? { type: "undo", attempt: active.attempt }
|
||||
: undefined
|
||||
const returning = active?.type === "edit" || active?.type === "undo" ? active : undefined
|
||||
|
||||
// Operations in flight still finish, since the server may already hold half of an edit, but waiting ones never
|
||||
// Operations in flight still finish, since the server may already have applied an edit, but waiting ones never
|
||||
// start. An undo stops before its cancel if it can: nothing would show the restored prompt.
|
||||
return changed(returning ? { status: "disposed", returning } : { status: "disposed" }, [
|
||||
...(edit ? [restore(edit, false)] : []),
|
||||
|
|
@ -295,7 +284,7 @@ function settleDisposed(state: Extract<QueueState, { status: "disposed" }>, even
|
|||
|
||||
if (!returning || !("attempt" in event) || event.attempt !== returning.attempt) return unchanged(state)
|
||||
|
||||
if (event.type === "mutation.admitted" || event.type === "mutation.succeeded") return changed({ status: "disposed" })
|
||||
if (event.type === "mutation.succeeded") return changed({ status: "disposed" })
|
||||
|
||||
if (event.type === "mutation.undone")
|
||||
return changed({ status: "disposed" }, [
|
||||
|
|
@ -338,21 +327,7 @@ export function selectQueueRows(state: QueueState): QueueRow[] {
|
|||
),
|
||||
]
|
||||
|
||||
const edits = operations.flatMap((operation): SentEdit[] =>
|
||||
operation.type === "edit"
|
||||
? [
|
||||
{
|
||||
original: operation.original,
|
||||
delivery: operation.delivery,
|
||||
text: operation.text,
|
||||
attachments: operation.attachments,
|
||||
moved: operation.moved,
|
||||
admitted: "phase" in operation && operation.phase === "cancelling",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
)
|
||||
|
||||
const edits = operations.filter((operation) => operation.type === "edit")
|
||||
const rows = queuedPromptRows(state.items, edits, hidden)
|
||||
const active = operations[0]
|
||||
|
||||
|
|
@ -386,7 +361,7 @@ export function selectQueueMoved(state: QueueState) {
|
|||
if (state.status === "disposed") return NO_MOVES
|
||||
const active = state.status === "mutating" || state.status === "editing-while-mutating" ? state.active : undefined
|
||||
|
||||
if ((active?.type !== "edit" && active?.type !== "reorder") || !Object.keys(active.moved).length) return state.moved
|
||||
if (active?.type !== "reorder" || !Object.keys(active.moved).length) return state.moved
|
||||
|
||||
return { ...state.moved, ...active.moved }
|
||||
}
|
||||
|
|
@ -444,7 +419,7 @@ function startEdit(state: LiveQueueState, event: Extract<QueueEvent, { type: "ed
|
|||
|
||||
if (!row || row.pending || !item) return unchanged(state)
|
||||
|
||||
// Re-admitting a queued prompt commits a staged revert, which drops every prompt queued after its boundary.
|
||||
// Keep queue edits closed during a staged revert, as for reordering.
|
||||
if (event.reverted) return changed(state, [{ type: "toast", key: "session.queue.reverted" }])
|
||||
const current = editOf(state)
|
||||
|
||||
|
|
@ -453,8 +428,7 @@ function startEdit(state: LiveQueueState, event: Extract<QueueEvent, { type: "ed
|
|||
const attachments = queuedPromptAttachments(item)
|
||||
const edit = { id: item.id, item, pin: state.seq + 1, stash: current?.stash ?? event.draft }
|
||||
|
||||
// The edit cancels the original once its replacement is admitted, so the draft takes local copies of the queued
|
||||
// media as soon as they load.
|
||||
// Pin the media for a draft that may outlive the queued item.
|
||||
const effects: QueueEffect[] = [
|
||||
{
|
||||
type: "draft.load",
|
||||
|
|
@ -489,16 +463,13 @@ function confirmEdit(state: LiveQueueState, event: Extract<QueueEvent, { type: "
|
|||
const attachments = event.prompt.filter(isAttachment)
|
||||
|
||||
if (!raw.trim() && !attachments.length) return changed(closed, [restored])
|
||||
const position = state.items.findIndex((entry) => entry.id === state.edit.id)
|
||||
const item = state.items[position] ?? state.edit.item
|
||||
const item = state.items.find((entry) => entry.id === state.edit.id) ?? state.edit.item
|
||||
const pristine = isPristine(item, event.prompt)
|
||||
|
||||
if (pristine && event.delivery === "queue") return changed(closed, [restored])
|
||||
|
||||
// An unchanged prompt steers in place instead of being replaced.
|
||||
// An unchanged prompt only needs its delivery mode updated.
|
||||
if (pristine) return enqueue(closed, { type: "steer", id: item.id }, [restored])
|
||||
// A queued edit re-admits the prompts after it, so they are pending too; their IDs are minted now.
|
||||
const after = event.delivery === "queue" && position >= 0 ? state.items.slice(position + 1) : []
|
||||
|
||||
return enqueue(
|
||||
closed,
|
||||
|
|
@ -511,7 +482,6 @@ function confirmEdit(state: LiveQueueState, event: Extract<QueueEvent, { type: "
|
|||
raw,
|
||||
text: raw.trim(),
|
||||
attachments: attachments.length,
|
||||
moved: Object.fromEntries([item, ...after].map((entry, index) => [entry.id, event.ids[index]])),
|
||||
},
|
||||
[restored],
|
||||
)
|
||||
|
|
@ -579,10 +549,7 @@ function undo(state: LiveQueueState, event: Extract<QueueEvent, { type: "undo.re
|
|||
|
||||
function settle(
|
||||
state: LiveQueueState,
|
||||
event: Extract<
|
||||
QueueEvent,
|
||||
{ type: "mutation.moved" | "mutation.admitted" | "mutation.succeeded" | "mutation.undone" | "mutation.failed" }
|
||||
>,
|
||||
event: Extract<QueueEvent, { type: "mutation.moved" | "mutation.succeeded" | "mutation.undone" | "mutation.failed" }>,
|
||||
): QueueTransition {
|
||||
// A result for an operation that is no longer in flight is stale, for example one that settles after unmount.
|
||||
if (state.status !== "mutating" && state.status !== "editing-while-mutating") return unchanged(state)
|
||||
|
|
@ -591,17 +558,11 @@ function settle(
|
|||
if (active.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
if (event.type === "mutation.moved") {
|
||||
if (active.type !== "edit" && active.type !== "reorder") return unchanged(state)
|
||||
if (active.type !== "reorder") return unchanged(state)
|
||||
|
||||
return changed(withActive(state, { ...active, moved: event.moved }))
|
||||
}
|
||||
|
||||
if (event.type === "mutation.admitted") {
|
||||
if (active.type !== "edit") return unchanged(state)
|
||||
|
||||
return changed(withActive(state, { ...active, phase: "cancelling" }))
|
||||
}
|
||||
|
||||
if (event.type === "mutation.undone") {
|
||||
if (active.type !== "undo") return unchanged(state)
|
||||
const hidden = hide(state, [active.item.id])
|
||||
|
|
@ -615,15 +576,8 @@ function settle(
|
|||
}
|
||||
|
||||
if (event.type === "mutation.succeeded") {
|
||||
const confirmed =
|
||||
active.type === "steer" || active.type === "remove"
|
||||
? [active.id]
|
||||
: active.type === "undo"
|
||||
? [active.item.id]
|
||||
: Object.keys(active.moved)
|
||||
|
||||
const hidden = hide(state, confirmed)
|
||||
const moved = active.type === "edit" || active.type === "reorder" ? active.moved : NO_MOVES
|
||||
const hidden = hide(state, removedBy(active))
|
||||
const moved = active.type === "reorder" ? active.moved : NO_MOVES
|
||||
|
||||
const next = advance(
|
||||
moved === NO_MOVES ? hidden.state : { ...hidden.state, moved: { ...hidden.state.moved, ...moved } },
|
||||
|
|
@ -636,7 +590,7 @@ function settle(
|
|||
const hidden = hide(state, event.hidden)
|
||||
// Nothing typed is lost: an edit that never reached the server returns to the composer, merged into what it holds
|
||||
// now, or into the draft an open edit stashed.
|
||||
const returned = active.type === "edit" && active.phase === "admitting"
|
||||
const returned = active.type === "edit"
|
||||
|
||||
const restored =
|
||||
returned && hidden.state.status === "editing-while-mutating"
|
||||
|
|
@ -665,6 +619,16 @@ type Mutating = Extract<QueueState, { status: "mutating" | "editing-while-mutati
|
|||
|
||||
type MutatingTransition = { readonly state: Mutating; readonly effects: readonly QueueEffect[] }
|
||||
|
||||
function removedBy(operation: ActiveOperation) {
|
||||
if (operation.type === "undo") return [operation.item.id]
|
||||
|
||||
if (operation.type === "reorder") return Object.keys(operation.moved)
|
||||
|
||||
if (operation.type === "edit") return operation.delivery === "steer" ? [operation.original] : []
|
||||
|
||||
return [operation.id]
|
||||
}
|
||||
|
||||
function hide(state: Mutating, ids: readonly string[]): MutatingTransition {
|
||||
const listed = ids.filter((id) => state.items.some((item) => item.id === id))
|
||||
|
||||
|
|
@ -685,11 +649,7 @@ function advance(state: Mutating, moved: Readonly<Record<string, string>>): Queu
|
|||
const [head, ...rest] = state.pending.map(
|
||||
(operation): QueuedOperation =>
|
||||
operation.type === "edit"
|
||||
? {
|
||||
...operation,
|
||||
original: remap(operation.original),
|
||||
moved: Object.fromEntries(Object.entries(operation.moved).map(([id, next]) => [remap(id), next])),
|
||||
}
|
||||
? { ...operation, original: remap(operation.original) }
|
||||
: { ...operation, id: remap(operation.id) },
|
||||
)
|
||||
|
||||
|
|
@ -765,8 +725,6 @@ function activate(operation: QueuedOperation, attempt: number, state: LiveQueueS
|
|||
return { type: "reorder", attempt, inboxIDs: rows.map((row) => row.id), rows, moved: {} }
|
||||
}
|
||||
|
||||
if (operation.type === "edit") return { ...operation, attempt, phase: "admitting" }
|
||||
|
||||
return { ...operation, attempt }
|
||||
}
|
||||
|
||||
|
|
@ -813,52 +771,30 @@ function unchanged(state: QueueState): QueueTransition {
|
|||
}
|
||||
|
||||
// An edit in flight, as the strip shows it.
|
||||
export type SentEdit = {
|
||||
readonly original: string
|
||||
readonly delivery: ComposerDelivery
|
||||
readonly text: string
|
||||
readonly attachments: number
|
||||
readonly moved: Readonly<Record<string, string>>
|
||||
// The server admitted every replacement.
|
||||
readonly admitted: boolean
|
||||
}
|
||||
export type SentEdit = Pick<EditOperation, "original" | "text" | "attachments">
|
||||
|
||||
// An edit in flight shows its edited text on the original row, and every row it rewrites shows as
|
||||
// pending. A re-admitted copy stays hidden while the row it replaces is listed, so the strip keeps
|
||||
// its order; a steered edit leaves the strip once the server admits it. Hidden rows (confirmed gone
|
||||
// or optimistically steered or removed) stay out.
|
||||
export function queuedPromptRows(
|
||||
items: readonly QueuedPrompt[],
|
||||
sent: readonly SentEdit[] = [],
|
||||
hidden: readonly string[] = [],
|
||||
) {
|
||||
const queued = items.filter((item) => !hidden.includes(item.id))
|
||||
const listed = new Set(queued.map((item) => item.id))
|
||||
const moves = sent.flatMap((edit) => Object.entries(edit.moved))
|
||||
|
||||
return queued.flatMap((item): { id: string; text: string; attachments: number; pending?: boolean }[] => {
|
||||
// The latest edit of this prompt, on its original row or, once that is gone, on its replacement.
|
||||
const edit = sent.findLast((entry) => entry.original === item.id || entry.moved[entry.original] === item.id)
|
||||
|
||||
if (moves.some(([old, next]) => next === item.id && listed.has(old))) return []
|
||||
|
||||
if (sent.some((entry) => entry.original === item.id && entry.admitted && entry.delivery === "steer")) return []
|
||||
|
||||
return queued.map((item): QueueRow => {
|
||||
const edit = sent.find((entry) => entry.original === item.id)
|
||||
const presentation = readPromptPresentation(item.payload.metadata)
|
||||
// Text-only edits preserve the original context suffix. A context-only edit currently loads that suffix as text.
|
||||
const comments = !edit || presentation?.displayText.trim() ? (presentation?.comments ?? []) : []
|
||||
|
||||
return [
|
||||
{
|
||||
id: item.id,
|
||||
text: edit ? edit.text : (presentation?.displayText.trim() ?? queuedPromptText(item)),
|
||||
attachments:
|
||||
(edit ? edit.attachments : (item.payload.files?.length ?? 0) + (presentation?.attachments.length ?? 0)) +
|
||||
// File comments already contribute their context file; quotes and plugin notes have no file.
|
||||
comments.filter((comment) => comment.type === "quote" || comment.type === "note").length,
|
||||
pending: moves.some(([old, next]) => old === item.id || next === item.id) ? true : undefined,
|
||||
},
|
||||
]
|
||||
return {
|
||||
id: item.id,
|
||||
text: edit ? edit.text : (presentation?.displayText.trim() ?? queuedPromptText(item)),
|
||||
attachments:
|
||||
(edit ? edit.attachments : (item.payload.files?.length ?? 0) + (presentation?.attachments.length ?? 0)) +
|
||||
// File comments already contribute their context file; quotes and plugin notes have no file.
|
||||
comments.filter((comment) => comment.type === "quote" || comment.type === "note").length,
|
||||
pending: edit ? true : undefined,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -28,15 +28,10 @@ const other = { ...queued[0], id: "msg_other", payload: { text: "other" } }
|
|||
|
||||
const later = { ...queued[0], id: "msg_later", payload: { text: "later" } }
|
||||
|
||||
const laterCopy = { ...later, id: "msg_later_copy" }
|
||||
|
||||
const sent = (change: Partial<SentEdit> = {}): SentEdit => ({
|
||||
original: "msg_original",
|
||||
delivery: "queue",
|
||||
text: "edited",
|
||||
attachments: 1,
|
||||
moved: { msg_original: "msg_replacement", msg_later: "msg_later_copy" },
|
||||
admitted: false,
|
||||
...change,
|
||||
})
|
||||
|
||||
|
|
@ -49,8 +44,6 @@ const row = (item: (typeof queued)[number], pending?: boolean) => ({
|
|||
|
||||
const edited = (id: string) => ({ id, text: "edited", attachments: 1, pending: true })
|
||||
|
||||
// One edit's life in the strip: sent from the composer, re-admitted by the server, its originals
|
||||
// cancelled last first, then settled once the server's queue reflects it, or rolled back on failure.
|
||||
describe("queuedPromptRows", () => {
|
||||
const quote = { type: "quote" as const, text: "Earlier answer" }
|
||||
|
||||
|
|
@ -136,34 +129,10 @@ describe("queuedPromptRows", () => {
|
|||
|
||||
test.each([
|
||||
[
|
||||
"shows a sent edit on the original row and marks the rows it rewrites as pending",
|
||||
"shows a pending edit on its original row and leaves the rest of the queue available",
|
||||
[other, queued[0], later],
|
||||
[sent()],
|
||||
[row(other), edited("msg_original"), row(later, true)],
|
||||
],
|
||||
[
|
||||
"hides re-admitted copies while their originals are listed",
|
||||
[other, queued[0], later, queued[1], laterCopy],
|
||||
[sent()],
|
||||
[row(other), edited("msg_original"), row(later, true)],
|
||||
],
|
||||
[
|
||||
"keeps the order as the originals are cancelled last first",
|
||||
[other, queued[0], queued[1], laterCopy],
|
||||
[sent({ admitted: true })],
|
||||
[row(other), edited("msg_original"), row(laterCopy, true)],
|
||||
],
|
||||
[
|
||||
"shows the edit on its replacement once the original is gone",
|
||||
[other, queued[1], laterCopy],
|
||||
[sent({ admitted: true })],
|
||||
[row(other), edited("msg_replacement"), row(laterCopy, true)],
|
||||
],
|
||||
[
|
||||
"drops the original row once a steered edit is admitted",
|
||||
[queued[0], other],
|
||||
[sent({ delivery: "steer", moved: { msg_original: "msg_replacement" }, admitted: true })],
|
||||
[row(other)],
|
||||
[row(other), edited("msg_original"), row(later)],
|
||||
],
|
||||
["shows the server's queue once the edit settles", [other, queued[1]], [], [row(other), row(queued[1])]],
|
||||
["restores the original row when a failed edit settles", [queued[0], other], [], [row(queued[0]), row(other)]],
|
||||
|
|
@ -172,12 +141,12 @@ describe("queuedPromptRows", () => {
|
|||
})
|
||||
|
||||
test("shows each of several edits in flight on its own row", () => {
|
||||
const second = sent({ original: "msg_other", text: "other edited", moved: { msg_other: "msg_other_copy" } })
|
||||
const second = sent({ original: "msg_other", text: "other edited" })
|
||||
|
||||
expect(queuedPromptRows([queued[0], other, later], [sent(), second])).toEqual([
|
||||
edited("msg_original"),
|
||||
{ id: "msg_other", text: "other edited", attachments: 1, pending: true },
|
||||
row(later, true),
|
||||
row(later),
|
||||
])
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -256,7 +256,7 @@ export function createSessionQueue(input: {
|
|||
}
|
||||
|
||||
const settled = await (
|
||||
operation.type === "reorder" ? rewrite(attempt, progress, [...operation.inboxIDs]) : sendEdit(operation, progress)
|
||||
operation.type === "reorder" ? rewrite(attempt, progress, operation.inboxIDs) : sendEdit(operation, progress)
|
||||
).then(
|
||||
() => true,
|
||||
() => false,
|
||||
|
|
@ -264,7 +264,7 @@ export function createSessionQueue(input: {
|
|||
|
||||
if (settled) progress.stage = "settled"
|
||||
|
||||
if (operation.type === "reorder") data.session.pending.invalidate(input.sessionID)
|
||||
data.session.pending.invalidate(input.sessionID)
|
||||
// The rows keep their optimistic state until the server's queue has caught up.
|
||||
await data.session.pending.sync(input.sessionID).catch(() => undefined)
|
||||
dispatch(
|
||||
|
|
@ -283,48 +283,14 @@ export function createSessionQueue(input: {
|
|||
operation.raw,
|
||||
)
|
||||
|
||||
// Admit before cancelling so a failed replacement never discards the original. A queued edit rebuilds its position
|
||||
// in one rewrite, which leaves the queue unchanged if any admission fails.
|
||||
const admission = { ...replacement, id: operation.moved[operation.original], delivery: operation.delivery }
|
||||
|
||||
if (operation.delivery === "queue")
|
||||
return rewrite(operation.attempt, progress, undefined, {
|
||||
original: operation.original,
|
||||
admission: { ...admission, resume: false },
|
||||
moved: operation.moved,
|
||||
})
|
||||
|
||||
signal.throwIfAborted()
|
||||
// Like a queued edit, an original the server delivered meanwhile keeps the edit draft instead of sending twice.
|
||||
const pending = await server.api.session.inbox.list({ sessionID: input.sessionID })
|
||||
|
||||
if (!pending.some((item) => item.id === operation.original && item.type === "user" && item.delivery === "queue"))
|
||||
throw new Error("Queued prompt was delivered before the edit")
|
||||
signal.throwIfAborted()
|
||||
const background = input.background()
|
||||
// A steered replacement can be delivered before a withdrawal reaches it, so the bound waits for the admission and
|
||||
// the edit returns to the composer only if it really did not go out.
|
||||
const background = operation.delivery === "steer" ? input.background() : undefined
|
||||
progress.stage = "committed"
|
||||
await data.session.prompt(admission)
|
||||
await server.api.session.inbox.edit({ ...replacement, inboxID: operation.original, delivery: operation.delivery })
|
||||
void background?.move()
|
||||
dispatch({ type: "mutation.admitted", attempt: operation.attempt })
|
||||
// Cancelling is a no-op once the original is gone, so one retry is safe.
|
||||
const cancel = () => server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID: operation.original })
|
||||
await cancel().catch(cancel)
|
||||
}
|
||||
|
||||
// `replace` substitutes an edited prompt for the original at its position in the same rewrite.
|
||||
// Without `inboxIDs` the server's current order is kept.
|
||||
const rewrite = async (
|
||||
attempt: number,
|
||||
progress: MutationProgress,
|
||||
inboxIDs: string[] | undefined,
|
||||
replace?: {
|
||||
original: string
|
||||
admission: Parameters<typeof data.session.prompt>[0]
|
||||
moved: Readonly<Record<string, string>>
|
||||
},
|
||||
) => {
|
||||
const rewrite = async (attempt: number, progress: MutationProgress, inboxIDs: readonly string[]) => {
|
||||
const signal = progress.controller.signal
|
||||
signal.throwIfAborted()
|
||||
const pending = await server.api.session.inbox.list({ sessionID: input.sessionID })
|
||||
|
|
@ -333,12 +299,10 @@ export function createSessionQueue(input: {
|
|||
if (pending.some((item) => item.delivery === "queue" && item.type !== "user"))
|
||||
throw new Error("Queued control items block reordering")
|
||||
const current = pending.filter((item): item is QueuedPrompt => item.type === "user" && item.delivery === "queue")
|
||||
const ordered = inboxIDs ? inboxIDs.flatMap((id) => current.filter((item) => item.id === id)) : current
|
||||
const ordered = inboxIDs.flatMap((id) => current.filter((item) => item.id === id))
|
||||
|
||||
// An edited prompt delivered meanwhile is no longer queued; fail so the edit draft stays.
|
||||
if (ordered.length !== current.length || (replace && !current.some((item) => item.id === replace.original)))
|
||||
throw new Error("Queued prompts changed before reordering")
|
||||
const changed = ordered.findIndex((item, index) => item.id !== current[index]?.id || item.id === replace?.original)
|
||||
if (ordered.length !== current.length) throw new Error("Queued prompts changed before reordering")
|
||||
const changed = ordered.findIndex((item, index) => item.id !== current[index]?.id)
|
||||
|
||||
if (changed < 0) return
|
||||
|
||||
|
|
@ -364,39 +328,31 @@ export function createSessionQueue(input: {
|
|||
signal.throwIfAborted()
|
||||
}
|
||||
|
||||
// An edit's pending rows follow the queue as the server has it now, keeping the IDs minted at confirm.
|
||||
const moved = Object.fromEntries(
|
||||
ordered.slice(changed).map((item) => [item.id, replace?.moved[item.id] ?? SessionMessage.ID.create()]),
|
||||
)
|
||||
const moved = Object.fromEntries(ordered.slice(changed).map((item) => [item.id, SessionMessage.ID.create()]))
|
||||
|
||||
dispatch({ type: "mutation.moved", attempt, moved })
|
||||
|
||||
for (const item of ordered.slice(changed)) {
|
||||
const admission =
|
||||
item.id === replace?.original
|
||||
? replace.admission
|
||||
: {
|
||||
id: moved[item.id],
|
||||
sessionID: input.sessionID,
|
||||
text: item.payload.text,
|
||||
files: item.payload.files?.map((file) => ({
|
||||
uri: storedFileUri(file),
|
||||
name: file.name,
|
||||
description: file.description,
|
||||
mention: file.mention,
|
||||
})),
|
||||
agents: item.payload.agents,
|
||||
skills: item.payload.skills,
|
||||
metadata: item.payload.metadata,
|
||||
delivery: "queue" as const,
|
||||
resume: false,
|
||||
}
|
||||
|
||||
const id = admission.id ?? SessionMessage.ID.create()
|
||||
const admission = {
|
||||
id: moved[item.id],
|
||||
sessionID: input.sessionID,
|
||||
text: item.payload.text,
|
||||
files: item.payload.files?.map((file) => ({
|
||||
uri: storedFileUri(file),
|
||||
name: file.name,
|
||||
description: file.description,
|
||||
mention: file.mention,
|
||||
})),
|
||||
agents: item.payload.agents,
|
||||
skills: item.payload.skills,
|
||||
metadata: item.payload.metadata,
|
||||
delivery: "queue" as const,
|
||||
resume: false,
|
||||
}
|
||||
|
||||
await stopped()
|
||||
replacements.push(id)
|
||||
await data.session.prompt({ ...admission, id }).catch(async (error) => {
|
||||
replacements.push(admission.id)
|
||||
await data.session.prompt(admission).catch(async (error) => {
|
||||
await withdraw()
|
||||
throw error
|
||||
})
|
||||
|
|
@ -406,13 +362,7 @@ export function createSessionQueue(input: {
|
|||
// Every copy is in, so the originals must go, however long that takes, or the queue holds both.
|
||||
progress.stage = "committed"
|
||||
|
||||
if (replace) dispatch({ type: "mutation.admitted", attempt })
|
||||
|
||||
// An edit cancels last first: the strip shows each original until it goes, so its copies never
|
||||
// show out of order.
|
||||
const replaced = current.slice(changed)
|
||||
|
||||
for (const item of replace ? replaced.reverse() : replaced) {
|
||||
for (const item of current.slice(changed)) {
|
||||
await server.api.session.inbox.cancel({ sessionID: input.sessionID, inboxID: item.id })
|
||||
progress.hidden.push(item.id)
|
||||
}
|
||||
|
|
@ -456,7 +406,6 @@ export function createSessionQueue(input: {
|
|||
delivery,
|
||||
reverted: reverted(),
|
||||
prompt: clonePrompt(input.draft.current()),
|
||||
ids: queued().map(() => SessionMessage.ID.create()),
|
||||
}),
|
||||
cancelEdit: () => dispatch({ type: "edit.cancel" }),
|
||||
editFirst: () => {
|
||||
|
|
|
|||
35
packages/client/src/effect/api/api.ts
generated
35
packages/client/src/effect/api/api.ts
generated
|
|
@ -311,6 +311,21 @@ export type SessionInboxCancelOperation<E = never> = (
|
|||
input: SessionInboxCancelInput,
|
||||
) => Effect.Effect<SessionInboxCancelOutput, E>
|
||||
|
||||
export type SessionInboxEditInput = {
|
||||
readonly sessionID: Session.ID
|
||||
readonly inboxID: SessionMessage.ID
|
||||
readonly text: string
|
||||
readonly files?: ReadonlyArray<PromptInput.FileAttachment> | undefined
|
||||
readonly agents?: ReadonlyArray<AgentAttachment> | undefined
|
||||
readonly skills?: ReadonlyArray<PromptInput.SkillAttachment> | undefined
|
||||
readonly metadata?: { readonly [x: string]: unknown } | undefined
|
||||
readonly delivery: SessionInbox.Delivery
|
||||
}
|
||||
export type SessionInboxEditOutput = void
|
||||
export type SessionInboxEditOperation<E = never> = (
|
||||
input: SessionInboxEditInput,
|
||||
) => Effect.Effect<SessionInboxEditOutput, E>
|
||||
|
||||
export type SessionInboxUpdateInput = {
|
||||
readonly sessionID: Session.ID
|
||||
readonly inboxID: SessionMessage.ID
|
||||
|
|
@ -435,6 +450,7 @@ export interface SessionApi<E = never> {
|
|||
readonly inbox: {
|
||||
readonly list: SessionInboxListOperation<E>
|
||||
readonly cancel: SessionInboxCancelOperation<E>
|
||||
readonly edit: SessionInboxEditOperation<E>
|
||||
readonly update: SessionInboxUpdateOperation<E>
|
||||
}
|
||||
readonly generate: SessionGenerateOperation<E>
|
||||
|
|
@ -809,6 +825,24 @@ export type ExperimentalSessionLogOutput =
|
|||
readonly item: SessionInbox.Item
|
||||
}
|
||||
}
|
||||
| {
|
||||
readonly id: Event.ID
|
||||
readonly created: number
|
||||
readonly metadata?: { readonly [x: string]: unknown } | undefined
|
||||
readonly type: "session.inbox.edited"
|
||||
readonly durable: { readonly aggregateID: string; readonly seq: Event.Seq; readonly version: Event.Version }
|
||||
readonly location?:
|
||||
| { readonly directory: AbsolutePath; readonly workspaceID?: Workspace.ID | undefined }
|
||||
| undefined
|
||||
readonly data: {
|
||||
readonly id: SessionMessage.ID
|
||||
readonly sessionID: Session.ID
|
||||
readonly time: { readonly created: DateTime.Utc }
|
||||
readonly type: "user"
|
||||
readonly payload: SessionInbox.UserPayload
|
||||
readonly delivery: SessionInbox.Delivery
|
||||
}
|
||||
}
|
||||
| {
|
||||
readonly id: Event.ID
|
||||
readonly created: number
|
||||
|
|
@ -2091,6 +2125,7 @@ export type EventSubscribeInput = {
|
|||
| "session.forked"
|
||||
| "session.inbox.delivered"
|
||||
| "session.inbox.enqueued"
|
||||
| "session.inbox.edited"
|
||||
| "session.inbox.cancelled"
|
||||
| "session.inbox.delivery.changed"
|
||||
| "session.execution.started"
|
||||
|
|
|
|||
18
packages/client/src/effect/generated/client.ts
generated
18
packages/client/src/effect/generated/client.ts
generated
|
|
@ -67,6 +67,8 @@ import type {
|
|||
SessionInboxListOutput,
|
||||
SessionInboxCancelInput,
|
||||
SessionInboxCancelOutput,
|
||||
SessionInboxEditInput,
|
||||
SessionInboxEditOutput,
|
||||
SessionInboxUpdateInput,
|
||||
SessionInboxUpdateOutput,
|
||||
SessionGenerateInput,
|
||||
|
|
@ -654,6 +656,21 @@ const EndpointSessionInboxCancel = (raw: RawClient["server.session"]) => (input:
|
|||
),
|
||||
)
|
||||
|
||||
const EndpointSessionInboxEdit = (raw: RawClient["server.session"]) => (input: SessionInboxEditInput) =>
|
||||
preserveEffect<SessionInboxEditOutput>()(
|
||||
raw["session.inbox.edit"]({
|
||||
params: { sessionID: input["sessionID"], inboxID: input["inboxID"] },
|
||||
payload: {
|
||||
text: input["text"],
|
||||
files: input["files"],
|
||||
agents: input["agents"],
|
||||
skills: input["skills"],
|
||||
metadata: input["metadata"],
|
||||
delivery: input["delivery"],
|
||||
},
|
||||
}).pipe(Effect.mapError(mapClientError)),
|
||||
)
|
||||
|
||||
const EndpointSessionInboxUpdate = (raw: RawClient["server.session"]) => (input: SessionInboxUpdateInput) =>
|
||||
preserveEffect<SessionInboxUpdateOutput>()(
|
||||
raw["session.inbox.update"]({
|
||||
|
|
@ -774,6 +791,7 @@ const adaptGroupSession = (raw: RawClient["server.session"]) => ({
|
|||
inbox: {
|
||||
list: EndpointSessionInboxList(raw),
|
||||
cancel: EndpointSessionInboxCancel(raw),
|
||||
edit: EndpointSessionInboxEdit(raw),
|
||||
update: EndpointSessionInboxUpdate(raw),
|
||||
},
|
||||
generate: EndpointSessionGenerate(raw),
|
||||
|
|
|
|||
21
packages/client/src/promise/generated/client.ts
generated
21
packages/client/src/promise/generated/client.ts
generated
|
|
@ -61,6 +61,8 @@ import type {
|
|||
SessionInboxListOutput,
|
||||
SessionInboxCancelInput,
|
||||
SessionInboxCancelOutput,
|
||||
SessionInboxEditInput,
|
||||
SessionInboxEditOutput,
|
||||
SessionInboxUpdateInput,
|
||||
SessionInboxUpdateOutput,
|
||||
SessionGenerateInput,
|
||||
|
|
@ -906,6 +908,25 @@ export function make(options: ClientOptions) {
|
|||
},
|
||||
requestOptions,
|
||||
),
|
||||
edit: (input: SessionInboxEditInput, requestOptions?: RequestOptions) =>
|
||||
request<SessionInboxEditOutput>(
|
||||
{
|
||||
method: "PUT",
|
||||
path: `/api/session/${encodeURIComponent(input.sessionID)}/inbox/${encodeURIComponent(input.inboxID)}`,
|
||||
body: {
|
||||
text: input["text"],
|
||||
files: input["files"],
|
||||
agents: input["agents"],
|
||||
skills: input["skills"],
|
||||
metadata: input["metadata"],
|
||||
delivery: input["delivery"],
|
||||
},
|
||||
successStatus: 204,
|
||||
declaredStatuses: [400, 401, 404, 409],
|
||||
empty: true,
|
||||
},
|
||||
requestOptions,
|
||||
),
|
||||
update: (input: SessionInboxUpdateInput, requestOptions?: RequestOptions) =>
|
||||
request<SessionInboxUpdateOutput>(
|
||||
{
|
||||
|
|
|
|||
51
packages/client/src/promise/generated/types.ts
generated
51
packages/client/src/promise/generated/types.ts
generated
|
|
@ -2631,6 +2631,23 @@ export type SessionInboxUser = {
|
|||
delivery: SessionInboxDelivery
|
||||
}
|
||||
|
||||
export type SessionInboxEdited = {
|
||||
id: EventID
|
||||
created: number
|
||||
metadata?: { [x: string]: any }
|
||||
type: "session.inbox.edited"
|
||||
durable: { aggregateID: string; seq: EventSeq; version: 1 }
|
||||
location?: LocationRef
|
||||
data: {
|
||||
id: SessionMessageID
|
||||
sessionID: SessionID
|
||||
time: { created: number }
|
||||
type: "user"
|
||||
payload: SessionInboxUserPayload1
|
||||
delivery: SessionInboxDelivery
|
||||
}
|
||||
}
|
||||
|
||||
export type SessionMessageAssistantTool = {
|
||||
type: "tool"
|
||||
id: string
|
||||
|
|
@ -2848,6 +2865,7 @@ export type SessionEventDurable =
|
|||
| SessionForked
|
||||
| SessionInboxDelivered
|
||||
| SessionInboxEnqueued
|
||||
| SessionInboxEdited
|
||||
| SessionInboxCancelled
|
||||
| SessionInboxDeliveryChanged
|
||||
| SessionExecutionStarted
|
||||
|
|
@ -2907,6 +2925,7 @@ export type V2Event =
|
|||
| SessionForked
|
||||
| SessionInboxDelivered
|
||||
| SessionInboxEnqueued
|
||||
| SessionInboxEdited
|
||||
| SessionInboxCancelled
|
||||
| SessionInboxDeliveryChanged
|
||||
| SessionExecutionStarted
|
||||
|
|
@ -3555,6 +3574,37 @@ export type SessionInboxCancelInput = { readonly sessionID: string; readonly inb
|
|||
|
||||
export type SessionInboxCancelOutput = void
|
||||
|
||||
export type SessionInboxEditInput = {
|
||||
readonly sessionID: string
|
||||
readonly inboxID: string
|
||||
readonly text: string
|
||||
readonly files?:
|
||||
| ReadonlyArray<{
|
||||
readonly uri: string
|
||||
readonly source?: { readonly type: "inline" } | { readonly type: "uri"; readonly uri: string }
|
||||
readonly name?: string
|
||||
readonly description?: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
| undefined
|
||||
readonly agents?:
|
||||
| ReadonlyArray<{
|
||||
readonly name: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
| undefined
|
||||
readonly skills?:
|
||||
| ReadonlyArray<{
|
||||
readonly id: string
|
||||
readonly mention?: { readonly start: number; readonly end: number; readonly text: string }
|
||||
}>
|
||||
| undefined
|
||||
readonly metadata?: { readonly [x: string]: JsonValue } | undefined
|
||||
readonly delivery: "steer" | "queue"
|
||||
}
|
||||
|
||||
export type SessionInboxEditOutput = void
|
||||
|
||||
export type SessionInboxUpdateInput = {
|
||||
readonly sessionID: string
|
||||
readonly inboxID: string
|
||||
|
|
@ -4406,6 +4456,7 @@ export type EventSubscribeInput = {
|
|||
| "session.forked"
|
||||
| "session.inbox.delivered"
|
||||
| "session.inbox.enqueued"
|
||||
| "session.inbox.edited"
|
||||
| "session.inbox.cancelled"
|
||||
| "session.inbox.delivery.changed"
|
||||
| "session.execution.started"
|
||||
|
|
|
|||
|
|
@ -903,6 +903,12 @@ export function createData(config: CreateDataInput) {
|
|||
compacting.get(event.data.sessionID)?.observed.add(event.data.inboxID)
|
||||
return
|
||||
}
|
||||
case "session.inbox.edited": {
|
||||
const item = event.data
|
||||
pendingUpdates.get(item.sessionID)?.set(item.id, item)
|
||||
admitLocal(item)
|
||||
return
|
||||
}
|
||||
case "session.inbox.enqueued": {
|
||||
outbox.delete(event.data.inboxID)
|
||||
const item = {
|
||||
|
|
|
|||
|
|
@ -181,6 +181,9 @@ export interface Interface {
|
|||
/** Experimental: {@link Interface.inbox} with files stored in `blob` left as `media:` refs when the session's location enables `experimental.media_blob`. */
|
||||
readonly inboxWithRefs: (sessionID: SessionSchema.ID) => Effect.Effect<SessionInbox.MediaInfo[], NotFoundError>
|
||||
readonly cancelInbox: (input: InboxItemRef) => Effect.Effect<void, NotFoundError | InboxConflictError>
|
||||
readonly editInbox: (
|
||||
input: InboxItemRef & Parameters<Session.Handle["editInbox"]>[0],
|
||||
) => ReturnType<Session.Handle["editInbox"]>
|
||||
readonly steerInbox: (input: InboxItemRef) => Effect.Effect<void, NotFoundError | InboxConflictError>
|
||||
readonly queueInbox: (input: InboxItemRef) => Effect.Effect<void, NotFoundError | InboxConflictError>
|
||||
/**
|
||||
|
|
@ -479,6 +482,7 @@ const layer = Layer.effect(
|
|||
return yield* SessionInbox.listWithRefs(db, sessionID)
|
||||
}),
|
||||
cancelInbox: (input) => sessions.forSession(input.sessionID).cancelInbox(input.inboxID),
|
||||
editInbox: (input) => sessions.forSession(input.sessionID).editInbox(input),
|
||||
steerInbox: (input) => sessions.forSession(input.sessionID).steerInbox(input.inboxID),
|
||||
queueInbox: (input) => sessions.forSession(input.sessionID).queueInbox(input.inboxID),
|
||||
log: (input) =>
|
||||
|
|
|
|||
|
|
@ -259,6 +259,18 @@ export const make = Effect.fn("SessionInbox.make")(function* () {
|
|||
),
|
||||
)
|
||||
|
||||
const edit = Effect.fn("SessionInbox.edit")((input: PendingRef, item: Extract<Item, { type: "user" }>) =>
|
||||
publishMutation(
|
||||
input,
|
||||
Effect.gen(function* () {
|
||||
const original = yield* find(db, input.id)
|
||||
if (original?.type !== "user" || original.sessionID !== input.sessionID || original.delivery !== "queue")
|
||||
return yield* new LifecycleConflict({ id: input.id })
|
||||
yield* bus.publish(SessionEvent.InboxEdited, { ...original, ...item })
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
const steer = Effect.fn("SessionInbox.steer")((input: PendingRef) =>
|
||||
publishMutation(
|
||||
input,
|
||||
|
|
@ -286,6 +298,7 @@ export const make = Effect.fn("SessionInbox.make")(function* () {
|
|||
reconcile,
|
||||
admit,
|
||||
admitCompaction,
|
||||
edit,
|
||||
cancel,
|
||||
steer,
|
||||
queue,
|
||||
|
|
@ -375,6 +388,26 @@ const delivered = (row: typeof SessionInboxTable.$inferSelect): Delivered => {
|
|||
return { id: row.id, type: row.type }
|
||||
}
|
||||
|
||||
export const projectEdited = Effect.fn("SessionInbox.projectEdited")(function* (db: DatabaseService, item: User) {
|
||||
const payload = encodeStoredUser(yield* SessionBlob.externalizePayload(db, item.payload))
|
||||
const updated = yield* db
|
||||
.update(SessionInboxTable)
|
||||
.set({ payload, delivery: item.delivery })
|
||||
.where(
|
||||
and(
|
||||
eq(SessionInboxTable.id, item.id),
|
||||
eq(SessionInboxTable.session_id, item.sessionID),
|
||||
eq(SessionInboxTable.type, "user"),
|
||||
eq(SessionInboxTable.delivery, "queue"),
|
||||
),
|
||||
)
|
||||
.returning({ seq: SessionInboxTable.enqueued_seq })
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
if (!updated) return yield* Effect.die(new LifecycleConflict({ id: item.id }))
|
||||
yield* SessionBlob.syncRefs(db, { sessionID: item.sessionID, messageID: item.id, seq: updated.seq }, payload)
|
||||
})
|
||||
|
||||
export const projectCancelled = Effect.fn("SessionInbox.projectCancelled")(function* (
|
||||
db: DatabaseService,
|
||||
input: PendingRef,
|
||||
|
|
|
|||
|
|
@ -143,6 +143,7 @@ export function update(adapter: Adapter, event: SessionEvent.DurableEvent) {
|
|||
"session.forked": () => Effect.void,
|
||||
"session.inbox.delivered": () => Effect.void,
|
||||
"session.inbox.enqueued": () => Effect.void,
|
||||
"session.inbox.edited": () => Effect.void,
|
||||
"session.inbox.cancelled": () => Effect.void,
|
||||
"session.inbox.delivery.changed": () => Effect.void,
|
||||
"session.execution.started": () => Effect.void,
|
||||
|
|
|
|||
|
|
@ -1046,6 +1046,7 @@ const layer = Layer.effectDiscard(
|
|||
yield* touch(db, event)
|
||||
}),
|
||||
)
|
||||
yield* bus.project(SessionEvent.InboxEdited, (event) => SessionInbox.projectEdited(db, event.data))
|
||||
yield* bus.project(SessionEvent.InboxCancelled, (event) =>
|
||||
SessionInbox.projectCancelled(db, {
|
||||
id: event.data.inboxID,
|
||||
|
|
|
|||
|
|
@ -152,6 +152,23 @@ export const make = Effect.fn("Session.make")(function* () {
|
|||
(sessionID: SessionSchema.ID, inboxID: SessionMessage.ID) => mutatePending(sessionID, inboxID, admission.queue),
|
||||
Effect.uninterruptible,
|
||||
)
|
||||
const editInbox = Effect.fn("Session.editInbox")(function* (
|
||||
sessionID: SessionSchema.ID,
|
||||
input: SessionPrompt.Input & { inboxID: SessionMessage.ID },
|
||||
) {
|
||||
const session = yield* get(sessionID)
|
||||
yield* Effect.uninterruptibleMask((restore) =>
|
||||
Effect.gen(function* () {
|
||||
const item = yield* restore(SessionPrompt.prepare({ session, messageID: input.inboxID, input }))
|
||||
yield* mutatePending(sessionID, input.inboxID, (ref) => admission.edit(ref, item))
|
||||
if (item.delivery === "steer") yield* execution.wake(sessionID)
|
||||
}),
|
||||
).pipe(
|
||||
instances.provide(session),
|
||||
Effect.provideService(Database.Service, database),
|
||||
Effect.provideService(FSUtil.Service, fs),
|
||||
)
|
||||
})
|
||||
const prompt = Effect.fn("Session.prompt")((sessionID: SessionSchema.ID, input: PromptRequest) =>
|
||||
Effect.uninterruptibleMask((restore) =>
|
||||
Effect.gen(function* () {
|
||||
|
|
@ -377,6 +394,7 @@ export const make = Effect.fn("Session.make")(function* () {
|
|||
resume,
|
||||
interrupt,
|
||||
cancelInbox,
|
||||
editInbox,
|
||||
steerInbox,
|
||||
queueInbox,
|
||||
revert,
|
||||
|
|
@ -403,6 +421,7 @@ export const make = Effect.fn("Session.make")(function* () {
|
|||
const resume = operations.resume.bind(undefined, sessionID)
|
||||
const interrupt = operations.interrupt.bind(undefined, sessionID)
|
||||
const cancelInbox = operations.cancelInbox.bind(undefined, sessionID)
|
||||
const editInbox = operations.editInbox.bind(undefined, sessionID)
|
||||
const steerInbox = operations.steerInbox.bind(undefined, sessionID)
|
||||
const queueInbox = operations.queueInbox.bind(undefined, sessionID)
|
||||
const stage = operations.revert.stage.bind(undefined, sessionID)
|
||||
|
|
@ -432,6 +451,7 @@ export const make = Effect.fn("Session.make")(function* () {
|
|||
resume,
|
||||
interrupt,
|
||||
cancelInbox,
|
||||
editInbox,
|
||||
steerInbox,
|
||||
queueInbox,
|
||||
revert,
|
||||
|
|
|
|||
|
|
@ -285,6 +285,29 @@ const forkInlineParent = Effect.fnUntraced(function* (id: string, directory: str
|
|||
})
|
||||
|
||||
describe("Session.prompt", () => {
|
||||
it.effect("edits a queued prompt in place and rejects an edit after delivery", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* setup
|
||||
const session = yield* Session.Service
|
||||
const bus = yield* Bus.Service
|
||||
const { db } = yield* Database.Service
|
||||
const original = yield* session.prompt({ sessionID, text: "B", delivery: "queue", resume: false })
|
||||
const next = yield* session.prompt({ sessionID, text: "C", delivery: "queue", resume: false })
|
||||
const edit = { sessionID, inboxID: original.id, delivery: "queue" as const }
|
||||
yield* session.editInbox({ ...edit, text: "B2" })
|
||||
expect(yield* session.inbox(sessionID)).toEqual([
|
||||
{ ...original, payload: { ...original.payload, text: "B2" } },
|
||||
next,
|
||||
])
|
||||
yield* SessionInbox.promote(db, bus, sessionID, "input")
|
||||
expect(yield* session.editInbox({ ...edit, text: "too late" }).pipe(Effect.flip)).toMatchObject({
|
||||
_tag: "Session.InboxConflictError",
|
||||
})
|
||||
expect(yield* session.inbox(sessionID)).toEqual([next])
|
||||
expect(yield* session.message({ sessionID, messageID: original.id })).toMatchObject({ text: "B2" })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("exposes the execution registry", () =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* Session.Service
|
||||
|
|
|
|||
198
packages/protocol/openapi.json
generated
198
packages/protocol/openapi.json
generated
|
|
@ -3410,6 +3410,124 @@
|
|||
"description": "Cancel an inbox item that has not yet been delivered. Unavailable items are a no-op.",
|
||||
"summary": "Cancel inbox input"
|
||||
},
|
||||
"put": {
|
||||
"tags": ["session"],
|
||||
"operationId": "session.inbox.edit",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "sessionID",
|
||||
"in": "path",
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Session.ID"
|
||||
},
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "inboxID",
|
||||
"in": "path",
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Session.Message.ID"
|
||||
},
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"security": [],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "<No Content>"
|
||||
},
|
||||
"400": {
|
||||
"description": "InvalidRequestError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/InvalidRequestErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "UnauthorizedError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UnauthorizedErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "SessionNotFoundError | LocationNotFoundError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/SessionNotFoundErrorEncoded"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/LocationNotFoundErrorEncoded"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "ConflictError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ConflictErrorEncoded"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Replace a queued user prompt in place. Returns a conflict if it has already left the queue.",
|
||||
"summary": "Edit queued prompt",
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"text": {
|
||||
"type": "string"
|
||||
},
|
||||
"files": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/PromptInput.FileAttachment"
|
||||
}
|
||||
},
|
||||
"agents": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/Prompt.AgentAttachment"
|
||||
}
|
||||
},
|
||||
"skills": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/PromptInput.SkillAttachment"
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object"
|
||||
},
|
||||
"delivery": {
|
||||
"$ref": "#/components/schemas/Session.Inbox.Delivery"
|
||||
}
|
||||
},
|
||||
"required": ["text", "delivery"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": true
|
||||
}
|
||||
},
|
||||
"patch": {
|
||||
"tags": ["session"],
|
||||
"operationId": "session.inbox.update",
|
||||
|
|
@ -10106,6 +10224,7 @@
|
|||
"session.forked",
|
||||
"session.inbox.delivered",
|
||||
"session.inbox.enqueued",
|
||||
"session.inbox.edited",
|
||||
"session.inbox.cancelled",
|
||||
"session.inbox.delivery.changed",
|
||||
"session.execution.started",
|
||||
|
|
@ -10217,6 +10336,7 @@
|
|||
"session.forked",
|
||||
"session.inbox.delivered",
|
||||
"session.inbox.enqueued",
|
||||
"session.inbox.edited",
|
||||
"session.inbox.cancelled",
|
||||
"session.inbox.delivery.changed",
|
||||
"session.execution.started",
|
||||
|
|
@ -22894,6 +23014,9 @@
|
|||
{
|
||||
"$ref": "#/components/schemas/session.inbox.enqueued"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.inbox.edited"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.inbox.cancelled"
|
||||
},
|
||||
|
|
@ -25410,6 +25533,9 @@
|
|||
{
|
||||
"$ref": "#/components/schemas/session.inbox.enqueued"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.inbox.edited"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.inbox.cancelled"
|
||||
},
|
||||
|
|
@ -28209,6 +28335,78 @@
|
|||
"required": ["id", "created", "type", "durable", "data"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"session.inbox.edited": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"$ref": "#/components/schemas/Event.ID"
|
||||
},
|
||||
"created": {
|
||||
"type": "number"
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object"
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": ["session.inbox.edited"]
|
||||
},
|
||||
"durable": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"aggregateID": {
|
||||
"type": "string"
|
||||
},
|
||||
"seq": {
|
||||
"$ref": "#/components/schemas/Event.Seq"
|
||||
},
|
||||
"version": {
|
||||
"$ref": "#/components/schemas/Event.VersionEncoded_c77c5abcb68d"
|
||||
}
|
||||
},
|
||||
"required": ["aggregateID", "seq", "version"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"location": {
|
||||
"$ref": "#/components/schemas/Location.Ref"
|
||||
},
|
||||
"data": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"$ref": "#/components/schemas/Session.Message.ID"
|
||||
},
|
||||
"sessionID": {
|
||||
"$ref": "#/components/schemas/Session.ID"
|
||||
},
|
||||
"time": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"created": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"required": ["created"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": ["user"]
|
||||
},
|
||||
"payload": {
|
||||
"$ref": "#/components/schemas/Session.Inbox.UserPayload"
|
||||
},
|
||||
"delivery": {
|
||||
"$ref": "#/components/schemas/Session.Inbox.Delivery"
|
||||
}
|
||||
},
|
||||
"required": ["id", "sessionID", "time", "type", "payload", "delivery"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["id", "created", "type", "durable", "data"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"session.inbox.enqueued": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
|
|
|||
|
|
@ -565,6 +565,26 @@ export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S, FormI ext
|
|||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.put("session.inbox.edit", "/api/session/:sessionID/inbox/:inboxID", {
|
||||
params: { sessionID: Session.ID, inboxID: SessionMessage.ID },
|
||||
payload: Schema.Struct({
|
||||
...PromptInput.Prompt.fields,
|
||||
metadata: SessionInbox.UserPayload.fields.metadata,
|
||||
delivery: SessionInbox.Delivery,
|
||||
}),
|
||||
success: HttpApiSchema.NoContent,
|
||||
error: [ConflictError, InvalidRequestError, SessionNotFoundError],
|
||||
})
|
||||
.middleware(sessionLocationMiddleware)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "session.inbox.edit",
|
||||
summary: "Edit queued prompt",
|
||||
description: "Replace a queued user prompt in place. Returns a conflict if it has already left the queue.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.patch("session.inbox.update", "/api/session/:sessionID/inbox/:inboxID", {
|
||||
params: { sessionID: Session.ID, inboxID: SessionMessage.ID },
|
||||
|
|
|
|||
|
|
@ -227,6 +227,13 @@ export const InboxEnqueued = Event.durable({
|
|||
})
|
||||
export type InboxEnqueued = typeof InboxEnqueued.Type
|
||||
|
||||
export const InboxEdited = Event.durable({
|
||||
type: "session.inbox.edited",
|
||||
...options,
|
||||
schema: SessionInbox.User.fields,
|
||||
})
|
||||
export type InboxEdited = typeof InboxEdited.Type
|
||||
|
||||
export const InboxCancelled = Event.durable({
|
||||
type: "session.inbox.cancelled",
|
||||
...options,
|
||||
|
|
@ -678,6 +685,7 @@ export const Definitions = Event.inventory(
|
|||
Forked,
|
||||
InboxDelivered,
|
||||
InboxEnqueued,
|
||||
InboxEdited,
|
||||
InboxCancelled,
|
||||
InboxDeliveryChanged,
|
||||
Execution.Started,
|
||||
|
|
|
|||
|
|
@ -130,6 +130,7 @@ describe("public event manifest", () => {
|
|||
"session.forked.2",
|
||||
"session.inbox.delivered.1",
|
||||
"session.inbox.enqueued.1",
|
||||
"session.inbox.edited.1",
|
||||
"session.inbox.cancelled.1",
|
||||
"session.inbox.delivery.changed.1",
|
||||
"session.execution.started.1",
|
||||
|
|
|
|||
|
|
@ -546,6 +546,28 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
|
|||
return HttpApiSchema.NoContent.make()
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"session.inbox.edit",
|
||||
Effect.fn(function* (ctx) {
|
||||
yield* session.editInbox({ ...ctx.params, ...ctx.payload }).pipe(
|
||||
Effect.catchTag("Session.NotFoundError", missingSession),
|
||||
Effect.catchTag(
|
||||
"Session.InboxConflictError",
|
||||
(error) => new ConflictError({ resource: error.inboxID, message: "Prompt is no longer queued" }),
|
||||
),
|
||||
Effect.catchTag(
|
||||
"Session.AttachmentError",
|
||||
(error) => new InvalidRequestError({ message: error.message, field: "files" }),
|
||||
),
|
||||
Effect.catchTag(
|
||||
"Session.SkillNotFoundError",
|
||||
(error) => new InvalidRequestError({ message: `Skill not found: ${error.skill}`, field: "skills" }),
|
||||
),
|
||||
locationErrors,
|
||||
)
|
||||
return HttpApiSchema.NoContent.make()
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"session.inbox.update",
|
||||
Effect.fn(function* (ctx) {
|
||||
|
|
|
|||
|
|
@ -212,7 +212,23 @@ it.live("serves stored media as refs only to clients that opt in while experimen
|
|||
expect(await plain.session.inbox.list({ sessionID })).toMatchObject([
|
||||
{ id: queued.id, payload: { files: [{ data: png, mime: "image/png", name: "again.png" }] } },
|
||||
])
|
||||
const edit = { sessionID, inboxID: queued.id, text: "Updated", delivery: "queue" as const }
|
||||
await opted.session.inbox.edit({ ...edit, files: [{ uri: media(text), name: "edited.txt" }] })
|
||||
expect(await opted.session.inbox.list({ sessionID })).toMatchObject([
|
||||
{ id: queued.id, payload: { text: "Updated", files: [{ uri: media(text), name: "edited.txt" }] } },
|
||||
])
|
||||
await opted.session.inbox.cancel({ sessionID, inboxID: queued.id })
|
||||
expect(
|
||||
(
|
||||
await handler(
|
||||
new Request(`http://opencode.local/api/session/${sessionID}/inbox/${queued.id}`, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ text: "Too late", delivery: "queue" }),
|
||||
}),
|
||||
)
|
||||
).status,
|
||||
).toBe(409)
|
||||
|
||||
// A ref whose blob is gone reaches opted-in clients as the same placeholder inline readers get.
|
||||
const gone = "e".repeat(64)
|
||||
|
|
|
|||
|
|
@ -650,6 +650,10 @@ export function createSubagentTracker(input: SubagentTrackerInput): SubagentTrac
|
|||
}
|
||||
|
||||
const reduce = (child: ChildState, event: V2Event) => {
|
||||
if (event.type === "session.inbox.edited") {
|
||||
child.prompts.set(event.data.id, event.data.payload)
|
||||
return
|
||||
}
|
||||
if (event.type === "session.inbox.enqueued") {
|
||||
if (event.data.item.type === "user") child.prompts.set(event.data.inboxID, event.data.item.payload)
|
||||
return
|
||||
|
|
|
|||
|
|
@ -1026,8 +1026,7 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
|
|||
if (!current(attempt)) return
|
||||
const client = attempt.client
|
||||
if (catalogEvents.has(event.type)) {
|
||||
if (input.location && event.location && event.location.directory !== input.location.directory)
|
||||
return
|
||||
if (input.location && event.location && event.location.directory !== input.location.directory) return
|
||||
void refreshCatalog(attempt)
|
||||
return
|
||||
}
|
||||
|
|
@ -1056,6 +1055,10 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
|
|||
input.onSessionTitle?.(event.data.title)
|
||||
return
|
||||
}
|
||||
if (event.type === "session.inbox.edited") {
|
||||
mergePending(event.data)
|
||||
return
|
||||
}
|
||||
if (event.type === "session.inbox.enqueued") {
|
||||
if (event.data.item.type !== "user") return
|
||||
mergePending({
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue