fix(app): settle queued edits and make inbox edit experimental

User decisions:
- Apply the review fixes to queued prompt editing
- Keep tests minimal; don't add race tests
This commit is contained in:
James Long 2026-11-12 17:22:34 +00:00
parent 99272f3a2d
commit 9a0fd28430
20 changed files with 450 additions and 353 deletions

View file

@ -5,8 +5,9 @@ import { SessionInbox } from "@opencode/schema/session-inbox"
import { SessionMessage } from "@opencode/schema/session-message"
import { timelinePresets } from "@opencode/session-ui/timeline/detail"
import { Schema } from "effect"
import { ConflictError, InvalidRequestError } from "../../../protocol/src/errors"
import { holdRoute, provider, seed, SERVER } from "../utils/app"
import type { MockServerConfig } from "../utils/mock-server"
import type { MockAnswer, MockServerConfig } from "../utils/mock-server"
import { installSseTransport } from "../utils/sse-transport"
import { chooseUserMessageAction, openUserMessageMenu } from "../utils/timeline"
import { openSession } from "../utils/workspace"
@ -97,10 +98,10 @@ function createQueueMock(seed: string[], messages: SessionMessageInfo[] = []) {
shells,
emit,
events: () => events.splice(0),
onInboxEdit: (input: Parameters<NonNullable<MockServerConfig["onInboxEdit"]>>[0]) => {
onInboxEdit: (input: Parameters<NonNullable<MockServerConfig["onInboxEdit"]>>[0]): void | MockAnswer => {
const original = rows.find((item) => item.id === input.inboxID && item.delivery === "queue")
if (!original) throw new Error("Original delivered")
if (!original) return { status: 409, body: new ConflictError({ message: "Prompt is no longer queued" }) }
const body = decodePromptBody(input.body)
prompts.push(body)
original.payload = {
@ -110,7 +111,12 @@ function createQueueMock(seed: string[], messages: SessionMessageInfo[] = []) {
agents: body.agents?.map((agent) => ({ ...agent })),
}
original.delivery = body.delivery ?? "queue"
emit("session.inbox.edited", original)
emit("session.inbox.edited", {
sessionID,
inboxID: original.id,
payload: original.payload,
delivery: original.delivery,
})
},
onPrompt: (input: Parameters<NonNullable<MockServerConfig["onPrompt"]>>[0]) => {
const body = decodePromptBody(input.body)
@ -686,9 +692,10 @@ for (const change of ["reorder", "edit"] as const) {
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")
}
mock.onInboxEdit = () => ({
status: 400,
body: new InvalidRequestError({ message: "Cannot prepare attachment" }),
})
// The last prompt's re-admission fails after the server admitted it, so its response is lost.
mock.onPrompt = (input) => {
@ -724,11 +731,13 @@ for (const change of ["reorder", "edit"] as const) {
// The replacements admitted before the failure are withdrawn; the originals stay in place.
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,
)
if (change === "reorder") {
await expect.poll(() => mock.changes.length).toBe(order.length)
expect(mock.changes).toEqual(
expect.arrayContaining(mock.prompts.map((prompt) => ({ inboxID: prompt.id, action: "cancel" }))),
)
}
await expect(view.rows.locator('[data-action="session-queue-edit"]')).toHaveText(order)
expect(mock.rows.map((row) => row.payload.text)).toEqual(order)
await expect(
@ -740,8 +749,12 @@ for (const change of ["reorder", "edit"] as const) {
})
}
test("editing restores the existing draft and replaces only the original queue position", async ({ page }) => {
test("an applied edit keeps its position and restores the existing draft even if its response is lost", async ({
page,
}) => {
const mock = createQueueMock(["first queued prompt", "tighten the error copy", "third queued prompt"])
const edit = mock.onInboxEdit
mock.onInboxEdit = (input) => edit(input) ?? { status: 502, body: "Lost response" }
const view = await openQueue(page, mock)
const original = view.rows.getByText("tighten the error copy", { exact: true })
await expect(original).toBeVisible()
@ -767,10 +780,11 @@ test("editing restores the existing draft and replaces only the original queue p
"tighten the error copy and add a retry hint",
"third queued prompt",
])
await expect(view.input).toHaveText("my in-progress draft")
await expect
.poll(() => mock.prompts.map((prompt) => prompt.text))
.toEqual(["tighten the error copy and add a retry hint"])
await expect(view.rows.and(page.locator('[aria-busy="true"]'))).toHaveCount(0)
await expect(view.input).toHaveText("my in-progress draft")
expect(mock.rows.map((item) => item.id)).toEqual(["inb_seed_1", "inb_seed_2", "inb_seed_3"])
expect(mock.changes).toEqual([])
})
@ -785,7 +799,7 @@ test("an edit racing delivery keeps the edit draft and sends only the original",
// 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) => {
await page.route(`**/session/${sessionID}/inbox/*`, async (route) => {
if (["DELETE", "PUT"].includes(route.request().method()) && mock.rows[0]?.payload.text === "B") mock.rows.shift()
await route.fallback()
})
@ -878,7 +892,7 @@ for (const delivery of ["steer", "queue"] as const) {
]
const view = await openQueue(page, mock)
const edit = await holdRoute(page, new RegExp(`/api/session/${sessionID}/inbox/inb_seed_2(\\?|$)`), {
const edit = await holdRoute(page, new RegExp(`/api/experimental/session/${sessionID}/inbox/inb_seed_2(\\?|$)`), {
method: "PUT",
})

View file

@ -486,7 +486,7 @@ const Group = HttpApiGroup.make("mock")
}),
)
.add(
HttpApiEndpoint.put("sessionInboxEdit", "/api/session/:sessionID/inbox/:inboxID", {
HttpApiEndpoint.put("sessionInboxEdit", "/api/experimental/session/:sessionID/inbox/:inboxID", {
params: { ...SessionParams, inboxID: Schema.String },
payload: JsonPayload,
success: NoContent,

View file

@ -161,7 +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
onInboxEdit?: (input: { sessionID: string; inboxID: string; body: Schema.JsonObject }) => void | MockAnswer
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.
@ -1344,9 +1344,16 @@ function mockHandlers(
},
})),
sessionInboxEdit: (ctx) =>
Effect.sync(() =>
config.onInboxEdit?.({ ...ctx.params, body: Option.getOrElse(decodeJsonObject(ctx.payload), () => ({})) }),
).pipe(Effect.andThen(noContent)),
Effect.sync(() => {
const answer = config.onInboxEdit?.({
...ctx.params,
body: Option.getOrElse(decodeJsonObject(ctx.payload), () => ({})),
})
return answer
? HttpServerResponse.jsonUnsafe(answer.body, { status: answer.status })
: HttpApiSchema.NoContent.make()
}),
sessionInboxCancel: (ctx) =>
Effect.sync(() =>
config.onInboxChange?.({ sessionID: ctx.params.sessionID, inboxID: ctx.params.inboxID, action: "cancel" }),

View file

@ -221,6 +221,7 @@ describe("queue changes run one at a time", () => {
{ type: "edit.start", id: "inb_2", reverted: false, draft: draft("") },
{ 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: "inbox.synced", items: [item(one.id, "another client's edit"), two] },
{ type: "edit.confirm", delivery: "steer", reverted: false, prompt: prompt("inb_1 text") },
])

View file

@ -1,4 +1,5 @@
import { Option, Schema } from "effect"
import { unwrap } from "solid-js/store"
import type { PromptAttachment, SessionInboxInfo } from "@opencode/client/promise"
import type { ComposerDelivery } from "@/composer/adapter"
import type { ComposerStateTarget } from "@/composer/submission-state"
@ -150,7 +151,12 @@ export type QueueEvent =
readonly context: readonly ContextItem[]
}
// `hidden` lists the inbox IDs the failed operation already withdrew or cancelled.
| { readonly type: "mutation.failed"; readonly attempt: number; readonly hidden: readonly string[] }
| {
readonly type: "mutation.failed"
readonly attempt: number
readonly hidden: readonly string[]
readonly unconfirmed?: boolean
}
// `hidden` as for a failure: what the operation withdrew or cancelled before the bound ran out.
| {
readonly type: "mutation.timed-out"
@ -295,7 +301,9 @@ function settleDisposed(state: Extract<QueueState, { status: "disposed" }>, even
return changed(
{ status: "disposed" },
returning.type === "edit" ? [{ type: "draft.merge", prompt: returning.prompt, context: [], focus: false }] : [],
returning.type === "edit" && !event.unconfirmed
? [{ type: "draft.merge", prompt: returning.prompt, context: [], focus: false }]
: [],
)
}
@ -426,7 +434,14 @@ function startEdit(state: LiveQueueState, event: Extract<QueueEvent, { type: "ed
if (current?.id === event.id) return unchanged(state)
const text = queuedPromptText(item)
const attachments = queuedPromptAttachments(item)
const edit = { id: item.id, item, pin: state.seq + 1, stash: current?.stash ?? event.draft }
// Inbox refreshes can reconcile the Solid store row in place while its editor is open.
const edit = {
id: item.id,
item: structuredClone(unwrap(item)),
pin: state.seq + 1,
stash: current?.stash ?? event.draft,
}
// Pin the media for a draft that may outlive the queued item.
const effects: QueueEffect[] = [
@ -463,7 +478,7 @@ function confirmEdit(state: LiveQueueState, event: Extract<QueueEvent, { type: "
const attachments = event.prompt.filter(isAttachment)
if (!raw.trim() && !attachments.length) return changed(closed, [restored])
const item = state.items.find((entry) => entry.id === state.edit.id) ?? state.edit.item
const item = state.edit.item
const pristine = isPristine(item, event.prompt)
if (pristine && event.delivery === "queue") return changed(closed, [restored])
@ -590,7 +605,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"
const returned = active.type === "edit" && !event.unconfirmed
const restored =
returned && hidden.state.status === "editing-while-mutating"
@ -804,7 +819,7 @@ export function isPristine(item: QueuedPrompt, prompt: Prompt) {
const original = queuedPromptAttachments(item)
return (
promptText(prompt).trim() === queuedPromptText(item) &&
promptText(prompt).trim() === queuedPromptText(item).trim() &&
attachments.length === original.length &&
attachments.every((attachment, index) => attachment.id === original[index].id)
)

View file

@ -1,5 +1,11 @@
import { createEffect, createMemo, createSignal, onCleanup, untrack, type Accessor } from "solid-js"
import type { PromptAttachment } from "@opencode/client/promise"
import {
ClientError,
isMessageNotFoundError,
isSessionNotFoundError,
type PromptAttachment,
} from "@opencode/client/promise"
import { uuid } from "@opencode/util/uuid"
import { SessionMessage } from "@opencode/schema/session-message"
import type { ComposerDelivery, ComposerSession } from "@/composer/adapter"
import type { ComposerStateTarget } from "@/composer/submission-state"
@ -255,39 +261,89 @@ export function createSessionQueue(input: {
return
}
const settled = await (
operation.type === "reorder" ? rewrite(attempt, progress, operation.inboxIDs) : sendEdit(operation, progress)
).then(
if (operation.type === "edit") return sendEdit(operation, progress)
const settled = await rewrite(attempt, progress, operation.inboxIDs).then(
() => true,
() => false,
)
if (settled) progress.stage = "settled"
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)
await refresh().catch(() => undefined)
dispatch(
settled ? { type: "mutation.succeeded", attempt } : { type: "mutation.failed", attempt, hidden: progress.hidden },
)
}
const refresh = () => {
data.session.pending.invalidate(input.sessionID)
return data.session.pending.sync(input.sessionID)
}
const sendEdit = async (operation: EditOperation & { attempt: number }, progress: MutationProgress) => {
const signal = progress.controller.signal
const replacement = await editedPromptInput(
input.sessionID,
location().directory,
operation.item,
operation.prompt,
operation.raw,
)
signal.throwIfAborted()
const attempt = operation.attempt
const sessionID = input.sessionID
const inboxID = operation.original
// Preparation can normalize attachment bytes and expand skills. Identify this replacement even after delivery.
const editID = uuid()
const background = operation.delivery === "steer" ? input.background() : undefined
progress.stage = "committed"
await server.api.session.inbox.edit({ ...replacement, inboxID: operation.original, delivery: operation.delivery })
try {
const replacement = await editedPromptInput(
sessionID,
location().directory,
operation.item,
operation.prompt,
operation.raw,
)
progress.controller.signal.throwIfAborted()
progress.stage = "committed"
await server.api.experimental.session.inbox.edit({
...replacement,
inboxID,
delivery: operation.delivery,
metadata: { ...replacement.metadata, queueEditID: editID },
})
} catch (error) {
// The SDK throws declared HTTP rejections as Errors; transport and unreadable responses are ClientErrors.
if (progress.stage === "running" || !(error instanceof ClientError)) {
dispatch({ type: "mutation.failed", attempt, hidden: [] })
void refresh().catch(() => undefined)
return
}
const applied = await refresh()
.then(async () => {
const item = data.session.pending.list(sessionID).find((item) => item.id === inboxID)
if (item) return item.type === "user" && item.payload.metadata?.queueEditID === editID
const message = await server.api.session.message.get({ sessionID, messageID: inboxID })
return message.type === "user" && message.metadata?.queueEditID === editID
})
.catch((error) => (isMessageNotFoundError(error) || isSessionNotFoundError(error) ? false : undefined))
if (applied !== true)
return dispatch({
type: "mutation.failed",
attempt,
hidden: [],
unconfirmed: applied === undefined,
})
void background?.move()
return dispatch({ type: "mutation.succeeded", attempt })
}
progress.stage = "settled"
void background?.move()
await refresh().catch(() => undefined)
dispatch({ type: "mutation.succeeded", attempt })
}
const rewrite = async (attempt: number, progress: MutationProgress, inboxIDs: readonly string[]) => {

View file

@ -311,21 +311,6 @@ 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
@ -450,8 +435,10 @@ export interface SessionApi<E = never> {
readonly inbox: {
readonly list: SessionInboxListOperation<E>
readonly cancel: SessionInboxCancelOperation<E>
readonly edit: SessionInboxEditOperation<E>
readonly update: SessionInboxUpdateOperation<E>
/** @deprecated Use `client.experimental.session.inbox.edit`. Removed in the next minor. */
readonly edit: ExperimentalSessionInboxEditOperation<E>
}
readonly generate: SessionGenerateOperation<E>
readonly interrupt: SessionInterruptOperation<E>
@ -603,6 +590,21 @@ export type ExperimentalSessionWaitOperation<E = never> = (
input: ExperimentalSessionWaitInput,
) => Effect.Effect<ExperimentalSessionWaitOutput, E>
export type ExperimentalSessionInboxEditInput = {
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 ExperimentalSessionInboxEditOutput = void
export type ExperimentalSessionInboxEditOperation<E = never> = (
input: ExperimentalSessionInboxEditInput,
) => Effect.Effect<ExperimentalSessionInboxEditOutput, E>
export type ExperimentalSessionInstructionsEntryListInput = { readonly sessionID: Session.ID }
export type ExperimentalSessionInstructionsEntryListOutput = ReadonlyArray<InstructionEntry.Info>
export type ExperimentalSessionInstructionsEntryListOperation<E = never> = (
@ -835,10 +837,8 @@ export type ExperimentalSessionLogOutput =
| { readonly directory: AbsolutePath; readonly workspaceID?: Workspace.ID | undefined }
| undefined
readonly data: {
readonly id: SessionMessage.ID
readonly sessionID: Session.ID
readonly time: { readonly created: number }
readonly type: "user"
readonly inboxID: SessionMessage.ID
readonly payload: SessionInbox.UserPayload
readonly delivery: SessionInbox.Delivery
}
@ -1480,6 +1480,7 @@ export interface ExperimentalSessionApi<E = never> {
readonly export: ExperimentalSessionExportOperation<E>
readonly skill: ExperimentalSessionSkillOperation<E>
readonly wait: ExperimentalSessionWaitOperation<E>
readonly inbox: { readonly edit: ExperimentalSessionInboxEditOperation<E> }
readonly instructions: {
readonly entry: {
readonly list: ExperimentalSessionInstructionsEntryListOperation<E>
@ -2897,6 +2898,15 @@ export type SessionWaitOutput = ExperimentalSessionWaitOutput
/** @deprecated Use `ExperimentalSessionWaitOperation`. Removed in the next minor. */
export type SessionWaitOperation<E = never> = ExperimentalSessionWaitOperation<E>
/** @deprecated Use `ExperimentalSessionInboxEditInput`. Removed in the next minor. */
export type SessionInboxEditInput = ExperimentalSessionInboxEditInput
/** @deprecated Use `ExperimentalSessionInboxEditOutput`. Removed in the next minor. */
export type SessionInboxEditOutput = ExperimentalSessionInboxEditOutput
/** @deprecated Use `ExperimentalSessionInboxEditOperation`. Removed in the next minor. */
export type SessionInboxEditOperation<E = never> = ExperimentalSessionInboxEditOperation<E>
/** @deprecated Use `ExperimentalSessionInstructionsEntryListInput`. Removed in the next minor. */
export type SessionInstructionsEntryListInput = ExperimentalSessionInstructionsEntryListInput

View file

@ -67,8 +67,6 @@ import type {
SessionInboxListOutput,
SessionInboxCancelInput,
SessionInboxCancelOutput,
SessionInboxEditInput,
SessionInboxEditOutput,
SessionInboxUpdateInput,
SessionInboxUpdateOutput,
SessionGenerateInput,
@ -103,6 +101,8 @@ import type {
ExperimentalSessionSkillOutput,
ExperimentalSessionWaitInput,
ExperimentalSessionWaitOutput,
ExperimentalSessionInboxEditInput,
ExperimentalSessionInboxEditOutput,
ExperimentalSessionInstructionsEntryListInput,
ExperimentalSessionInstructionsEntryListOutput,
ExperimentalSessionInstructionsEntryPutInput,
@ -656,21 +656,6 @@ 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"]({
@ -791,7 +776,6 @@ const adaptGroupSession = (raw: RawClient["server.session"]) => ({
inbox: {
list: EndpointSessionInboxList(raw),
cancel: EndpointSessionInboxCancel(raw),
edit: EndpointSessionInboxEdit(raw),
update: EndpointSessionInboxUpdate(raw),
},
generate: EndpointSessionGenerate(raw),
@ -859,6 +843,22 @@ const EndpointExperimentalSessionWait = (raw: RawClient["server.session"]) => (i
raw["session.wait"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)),
)
const EndpointExperimentalSessionInboxEdit =
(raw: RawClient["server.session"]) => (input: ExperimentalSessionInboxEditInput) =>
preserveEffect<ExperimentalSessionInboxEditOutput>()(
raw["experimental.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 EndpointExperimentalSessionInstructionsEntryList =
(raw: RawClient["server.session"]) => (input: ExperimentalSessionInstructionsEntryListInput) =>
preserveEffect<ExperimentalSessionInstructionsEntryListOutput>()(
@ -904,6 +904,7 @@ const adaptGroupExperimentalSession = (raw: RawClient["server.session"]) => ({
export: EndpointExperimentalSessionExport(raw),
skill: EndpointExperimentalSessionSkill(raw),
wait: EndpointExperimentalSessionWait(raw),
inbox: { edit: EndpointExperimentalSessionInboxEdit(raw) },
instructions: {
entry: {
list: EndpointExperimentalSessionInstructionsEntryList(raw),
@ -2035,6 +2036,11 @@ const adaptClient = (raw: RawClient) => {
skill: client.experimental.session.skill,
/** @deprecated Use `client.experimental.session.wait`. Removed in the next minor. */
wait: client.experimental.session.wait,
inbox: {
...client.session.inbox,
/** @deprecated Use `client.experimental.session.inbox.edit`. Removed in the next minor. */
edit: client.experimental.session.inbox.edit,
},
/** @deprecated Use `client.experimental.session.instructions`. Removed in the next minor. */
instructions: {
/** @deprecated Use `client.experimental.session.instructions.entry`. Removed in the next minor. */

View file

@ -61,8 +61,6 @@ import type {
SessionInboxListOutput,
SessionInboxCancelInput,
SessionInboxCancelOutput,
SessionInboxEditInput,
SessionInboxEditOutput,
SessionInboxUpdateInput,
SessionInboxUpdateOutput,
SessionGenerateInput,
@ -97,6 +95,8 @@ import type {
ExperimentalSessionSkillOutput,
ExperimentalSessionWaitInput,
ExperimentalSessionWaitOutput,
ExperimentalSessionInboxEditInput,
ExperimentalSessionInboxEditOutput,
ExperimentalSessionInstructionsEntryListInput,
ExperimentalSessionInstructionsEntryListOutput,
ExperimentalSessionInstructionsEntryPutInput,
@ -908,25 +908,6 @@ 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>(
{
@ -1140,6 +1121,27 @@ export function make(options: ClientOptions) {
},
requestOptions,
),
inbox: {
edit: (input: ExperimentalSessionInboxEditInput, requestOptions?: RequestOptions) =>
request<ExperimentalSessionInboxEditOutput>(
{
method: "PUT",
path: `/api/experimental/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,
),
},
instructions: {
entry: {
list: (input: ExperimentalSessionInstructionsEntryListInput, requestOptions?: RequestOptions) =>
@ -2724,6 +2726,11 @@ export function make(options: ClientOptions) {
skill: client.experimental.session.skill,
/** @deprecated Use `client.experimental.session.wait`. Removed in the next minor. */
wait: client.experimental.session.wait,
inbox: {
...client.session.inbox,
/** @deprecated Use `client.experimental.session.inbox.edit`. Removed in the next minor. */
edit: client.experimental.session.inbox.edit,
},
/** @deprecated Use `client.experimental.session.instructions`. Removed in the next minor. */
instructions: {
/** @deprecated Use `client.experimental.session.instructions.entry`. Removed in the next minor. */

View file

@ -2639,10 +2639,8 @@ export type SessionInboxEdited = {
durable: { aggregateID: string; seq: EventSeq; version: 1 }
location?: LocationRef
data: {
id: SessionMessageID
sessionID: SessionID
time: { created: number }
type: "user"
inboxID: SessionMessageID
payload: SessionInboxUserPayload1
delivery: SessionInboxDelivery
}
@ -3574,37 +3572,6 @@ 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
@ -3963,6 +3930,37 @@ export type ExperimentalSessionWaitInput = { readonly sessionID: string }
export type ExperimentalSessionWaitOutput = void
export type ExperimentalSessionInboxEditInput = {
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 ExperimentalSessionInboxEditOutput = void
export type ExperimentalSessionInstructionsEntryListInput = { readonly sessionID: string }
export type ExperimentalSessionInstructionsEntryListOutput = { data: Array<InstructionEntryInfo> }["data"]
@ -4988,6 +4986,12 @@ export type SessionWaitInput = ExperimentalSessionWaitInput
/** @deprecated Use `ExperimentalSessionWaitOutput`. Removed in the next minor. */
export type SessionWaitOutput = ExperimentalSessionWaitOutput
/** @deprecated Use `ExperimentalSessionInboxEditInput`. Removed in the next minor. */
export type SessionInboxEditInput = ExperimentalSessionInboxEditInput
/** @deprecated Use `ExperimentalSessionInboxEditOutput`. Removed in the next minor. */
export type SessionInboxEditOutput = ExperimentalSessionInboxEditOutput
/** @deprecated Use `ExperimentalSessionInstructionsEntryListInput`. Removed in the next minor. */
export type SessionInstructionsEntryListInput = ExperimentalSessionInstructionsEntryListInput

View file

@ -322,7 +322,8 @@ export function createData(config: CreateDataInput) {
const stored = (message: SessionMessageInfo) => (config.omitToolFileData ? omitMessageFileData(message) : message)
const sync = createSync()
let activeUpdates: Map<string, DataSessionStatus | undefined> | undefined
const pendingUpdates = new Map<string, Map<string, SessionInboxInfo | SessionInbox.Delivery | undefined>>()
type PendingUpdate = (snapshot: Map<string, SessionInboxInfo>) => void
const pendingUpdates = new Map<string, PendingUpdate[]>()
function setSessionActive(sessionID: string, status: DataSessionStatus) {
activeUpdates?.set(sessionID, status)
@ -331,7 +332,7 @@ export function createData(config: CreateDataInput) {
function removePending(sessionID: string, inboxID?: string) {
if (!inboxID) return
pendingUpdates.get(sessionID)?.set(inboxID, undefined)
pendingUpdates.get(sessionID)?.push((snapshot) => snapshot.delete(inboxID))
if (store.session.pending[sessionID]?.some((item) => item.id === inboxID))
setStore(
"session",
@ -378,11 +379,23 @@ export function createData(config: CreateDataInput) {
})
}
function updatePending(sessionID: string, inboxID: string, delivery: SessionInbox.Delivery) {
function updatePending(
sessionID: string,
inboxID: string,
delivery: SessionInbox.Delivery,
payload?: Extract<SessionInboxInfo, { type: "user" }>["payload"],
) {
const update = (item: SessionInboxInfo): SessionInboxInfo =>
item.type === "user" && payload ? { ...item, delivery, payload } : { ...item, delivery }
const index = store.session.pending[sessionID]?.findIndex((item) => item.id === inboxID) ?? -1
const item = store.session.pending[sessionID]?.[index]
pendingUpdates.get(sessionID)?.set(inboxID, item ? { ...item, delivery } : delivery)
if (index < 0 || !item || item.delivery === delivery) return
pendingUpdates.get(sessionID)?.push((snapshot) => {
const existing = snapshot.get(inboxID) ?? item
if (existing) snapshot.set(inboxID, update(existing))
})
if (!item) return
if (payload) return admitLocal(update(item))
if (item.delivery === delivery) return
setStore("session", "pending", sessionID, index, { ...item, delivery })
}
@ -903,12 +916,9 @@ 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)
case "session.inbox.edited":
updatePending(event.data.sessionID, event.data.inboxID, event.data.delivery, event.data.payload)
return
}
case "session.inbox.enqueued": {
outbox.delete(event.data.inboxID)
const item = {
@ -917,7 +927,7 @@ export function createData(config: CreateDataInput) {
time: { created: event.created },
...event.data.item,
}
pendingUpdates.get(item.sessionID)?.set(item.id, item)
pendingUpdates.get(item.sessionID)?.push((snapshot) => snapshot.set(item.id, item))
admitLocal(item)
if (event.data.item.type === "compaction") {
const active = compacting.get(event.data.sessionID)
@ -1602,7 +1612,7 @@ export function createData(config: CreateDataInput) {
sync(sessionID: string) {
return sync.run(`session.pending:${sessionID}`, async () => {
const started = deletionEpoch
const updates = new Map<string, SessionInboxInfo | SessionInbox.Delivery | undefined>()
const updates: PendingUpdate[] = []
pendingUpdates.set(sessionID, updates)
try {
const snapshot = await api().session.inbox.list({ sessionID }).catch(evictMissing)
@ -1610,13 +1620,7 @@ export function createData(config: CreateDataInput) {
// Events can overtake this HTTP response on a remote connection.
// Reconcile them before an older snapshot can resurrect delivered input.
const current = new Map(snapshot.map((item) => [item.id, item]))
updates.forEach((item, id) => {
if (item === undefined) current.delete(id)
else if (typeof item === "string") {
const existing = current.get(id)
if (existing) current.set(id, { ...existing, delivery: item })
} else current.set(id, item)
})
updates.forEach((update) => update(current))
const pending = [...current.values()]
// A positive read acknowledges admission even when its SSE echo is delayed.
pending.forEach((item) => outbox.delete(item.id))

View file

@ -69,14 +69,6 @@ const encodeMove = Schema.encodeSync(MovePayload)
const inboxLocks = KeyedMutex.makeUnsafe<SessionSchema.ID>()
type PendingRef = { readonly id: SessionMessage.ID; readonly sessionID: SessionSchema.ID }
const queuedUser = (ref: PendingRef) =>
and(
eq(SessionInboxTable.id, ref.id),
eq(SessionInboxTable.session_id, ref.sessionID),
eq(SessionInboxTable.type, "user"),
eq(SessionInboxTable.delivery, "queue"),
)
export const serialized = <A, E, R>(sessionID: SessionSchema.ID, effect: Effect.Effect<A, E, R>) =>
inboxLocks.withLock(sessionID)(effect)
@ -270,19 +262,11 @@ 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* db
.select({ created: SessionInboxTable.time_created })
.from(SessionInboxTable)
.where(queuedUser(input))
.get()
.pipe(Effect.orDie)
if (!original) return yield* new LifecycleConflict({ id: input.id })
yield* bus.publish(SessionEvent.InboxEdited, {
...input,
...item,
time: original,
})
bus.publish(SessionEvent.InboxEdited, {
sessionID: input.sessionID,
inboxID: input.id,
payload: item.payload,
delivery: item.delivery,
}),
),
)
@ -412,12 +396,19 @@ export const projectEdited = Effect.fn("SessionInbox.projectEdited")(function* (
const updated = yield* db
.update(SessionInboxTable)
.set({ payload, delivery: item.delivery })
.where(queuedUser(item))
.where(
and(
eq(SessionInboxTable.id, item.inboxID),
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)
if (!updated) return yield* Effect.die(new LifecycleConflict({ id: item.inboxID }))
yield* SessionBlob.syncRefs(db, { sessionID: item.sessionID, messageID: item.inboxID, seq: updated.seq }, payload)
})
export const projectCancelled = Effect.fn("SessionInbox.projectCancelled")(function* (

View file

@ -3410,124 +3410,6 @@
"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",
@ -3616,6 +3498,126 @@
}
}
},
"/api/experimental/session/{sessionID}/inbox/{inboxID}": {
"put": {
"tags": ["session"],
"operationId": "experimental.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. Experimental: may change without compatibility guarantees.",
"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
}
}
},
"/api/experimental/session/{sessionID}/instructions/entries": {
"get": {
"tags": ["session"],
@ -28373,33 +28375,11 @@
"data": {
"type": "object",
"properties": {
"id": {
"$ref": "#/components/schemas/Session.Message.ID"
},
"sessionID": {
"$ref": "#/components/schemas/Session.ID"
},
"time": {
"type": "object",
"properties": {
"created": {
"anyOf": [
{
"type": "number"
},
{
"type": "string",
"enum": ["NaN", "Infinity", "-Infinity"]
}
]
}
},
"required": ["created"],
"additionalProperties": false
},
"type": {
"type": "string",
"enum": ["user"]
"inboxID": {
"$ref": "#/components/schemas/Session.Message.ID"
},
"payload": {
"$ref": "#/components/schemas/Session.Inbox.UserPayload"
@ -28408,7 +28388,7 @@
"$ref": "#/components/schemas/Session.Inbox.Delivery"
}
},
"required": ["id", "sessionID", "time", "type", "payload", "delivery"],
"required": ["sessionID", "inboxID", "payload", "delivery"],
"additionalProperties": false
}
},

View file

@ -566,7 +566,7 @@ export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S, FormI ext
),
)
.add(
HttpApiEndpoint.put("session.inbox.edit", "/api/session/:sessionID/inbox/:inboxID", {
HttpApiEndpoint.put("experimental.session.inbox.edit", "/api/experimental/session/:sessionID/inbox/:inboxID", {
params: { sessionID: Session.ID, inboxID: SessionMessage.ID },
payload: Schema.Struct({
...PromptInput.Prompt.fields,
@ -579,9 +579,10 @@ export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S, FormI ext
.middleware(sessionLocationMiddleware)
.annotateMerge(
OpenApi.annotations({
identifier: "session.inbox.edit",
identifier: "experimental.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.",
description:
"Replace a queued user prompt in place. Returns a conflict if it has already left the queue. Experimental: may change without compatibility guarantees.",
}),
),
)

View file

@ -230,7 +230,7 @@ export type InboxEnqueued = typeof InboxEnqueued.Type
export const InboxEdited = Event.durable({
type: "session.inbox.edited",
...options,
schema: { ...SessionInbox.User.fields, time: Schema.Struct({ created: Schema.Number }) },
schema: { ...InboxRef, payload: SessionInbox.UserPayload, delivery: SessionInbox.Delivery },
})
export type InboxEdited = typeof InboxEdited.Type

View file

@ -220,10 +220,16 @@ describe("public event manifest", () => {
expect(SessionEvent.Tool.Called.durable?.version).toBe(1)
})
test("keeps current session deletion minimal", () => {
test("keeps current session deletion and inbox edits minimal", () => {
const sessionID = SessionID.make("ses_test")
expect(SessionEvent.Deleted.data.make({ sessionID })).toEqual({ sessionID })
expect(SessionEvent.Deleted.durable?.version).toBe(2)
expect(Object.keys(SessionEvent.InboxEdited.data.fields).sort()).toEqual([
"delivery",
"inboxID",
"payload",
"sessionID",
])
})
})

View file

@ -547,7 +547,7 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
}),
)
.handle(
"session.inbox.edit",
"experimental.session.inbox.edit",
Effect.fn(function* (ctx) {
yield* session.editInbox({ ...ctx.params, ...ctx.payload }).pipe(
Effect.catchTag("Session.NotFoundError", missingSession),

View file

@ -213,7 +213,7 @@ it.live("serves stored media as refs only to clients that opt in while experimen
{ 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" }] })
await opted.experimental.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" }] } },
])
@ -221,7 +221,7 @@ it.live("serves stored media as refs only to clients that opt in while experimen
expect(
(
await handler(
new Request(`http://opencode.local/api/session/${sessionID}/inbox/${queued.id}`, {
new Request(`http://opencode.local/api/experimental/session/${sessionID}/inbox/${queued.id}`, {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ text: "Too late", delivery: "queue" }),

View file

@ -651,7 +651,7 @@ 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)
child.prompts.set(event.data.inboxID, event.data.payload)
return
}
if (event.type === "session.inbox.enqueued") {

View file

@ -8,6 +8,7 @@ import type {
SessionMessageInfo,
SessionMessageUser,
SessionInboxInfo,
SessionInboxItem,
} from "@opencode/client/promise"
import { ClientError } from "@opencode/client/promise"
import { Event } from "@opencode/schema/event"
@ -194,11 +195,11 @@ function errorMessage(error: { message?: string; _tag?: string }) {
return error.message || error._tag || "Session execution failed"
}
function pendingPrompt(item: SessionInboxInfo): PendingPrompt | undefined {
function pendingPrompt(id: string, item: SessionInboxItem): PendingPrompt | undefined {
if (item.type !== "user") return undefined
return {
messageID: item.id,
prompt: { messageID: item.id, ...messagePrompt(item.payload) },
messageID: id,
prompt: { messageID: id, ...messagePrompt(item.payload) },
files: item.payload.files,
delivery: item.delivery,
...(item.payload.skills?.length
@ -580,12 +581,12 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
)
}
let syncedPending: string[] | undefined
let syncedPending: PendingPrompt[] | undefined
const syncPending = () => {
const prompts = [...state.pending.values()]
const ids = prompts.map((item) => `${item.messageID}:${item.delivery}`)
if (syncedPending?.length === ids.length && syncedPending.every((id, index) => id === ids[index])) return
syncedPending = ids
if (syncedPending?.length === prompts.length && syncedPending.every((item, index) => item === prompts[index]))
return
syncedPending = prompts
input.trace?.write("ui.patch", { pending: prompts.length })
input.footer.event({ type: "queued.prompts", prompts })
}
@ -618,8 +619,8 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
])
}
const mergePending = (item: SessionInboxInfo) => {
const prompt = pendingPrompt(item)
const mergePending = (id: string, item: SessionInboxItem) => {
const prompt = pendingPrompt(id, item)
if (!prompt) return
if (state.promotedMessages.has(prompt.messageID)) {
renderUser(prompt.messageID, prompt.prompt.text, prompt.files, prompt.skills)
@ -989,7 +990,7 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
if (!current(attempt)) return
state.pending = new Map(
pending.flatMap((item) => {
const prompt = pendingPrompt(item)
const prompt = pendingPrompt(item.id, item)
return prompt ? [[prompt.messageID, prompt] as const] : []
}),
)
@ -1056,17 +1057,11 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
return
}
if (event.type === "session.inbox.edited") {
mergePending(event.data)
mergePending(event.data.inboxID, { type: "user", payload: event.data.payload, delivery: event.data.delivery })
return
}
if (event.type === "session.inbox.enqueued") {
if (event.data.item.type !== "user") return
mergePending({
id: event.data.inboxID,
sessionID: event.data.sessionID,
time: { created: event.created },
...event.data.item,
})
mergePending(event.data.inboxID, event.data.item)
return
}
if (event.type === "session.inbox.delivered") {
@ -1641,7 +1636,7 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
next.signal?.addEventListener("abort", interrupt, { once: true })
try {
const admitted = await send()
if (admitted) mergePending(admitted)
if (admitted) mergePending(admitted.id, admitted)
onAdmitted?.()
await settleSession(client)
if (active.terminalError && !active.failureRendered)
@ -1825,7 +1820,7 @@ export async function createSessionTransport(input: StreamInput): Promise<Sessio
await client.session.switchModel({ sessionID: input.sessionID, model: selected }, { signal: next.signal })
}
const admitted = await admitPrompt(next, client, delivery)
if (admitted) mergePending(admitted)
if (admitted) mergePending(admitted.id, admitted)
settlementClient = client
},
async waitForIdle() {