Visitar URL original
feat(app): queue a follow-up first with Alt+Enter by usrnk1 · Pull Request #63109 · anomalyco/opencode · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions packages/app/e2e/regression/session-queue.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,34 @@ test("follow-up preference controls Enter while Mod+Enter uses the alternate del
await expect(view.input).toHaveText("")
})

test("Alt+Enter queues a follow-up first without steering, regardless of the follow-up preference", async ({
page,
}) => {
const mock = createQueueMock(["Follow-up A", "Follow-up B"])

const view = await openQueue(page, mock, "steer")

await view.input.fill("Follow-up C")
await view.input.press("Alt+Enter")
await expect(view.rows.locator('[data-action="session-queue-edit"]')).toHaveText([
"Follow-up C",
"Follow-up A",
"Follow-up B",
])
await expect
.poll(() => mock.rows.map((row) => [row.payload.text, row.delivery]))
.toEqual([
["Follow-up C", "queue"],
["Follow-up A", "queue"],
["Follow-up B", "queue"],
])
await expect(view.input).toHaveText("")
expect(mock.changes.every((change) => change.action === "cancel")).toBe(true)
await view.input.fill("Another follow-up")
await view.composer.locator('[data-action="composer-alternate-delivery"]').hover()
await expect(page.getByRole("tooltip")).toContainText("Queue first")
})

test("a blank Enter leaves the running session alone while Stop still interrupts it, as in the TUI", async ({
page,
}) => {
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/composer/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ export type ComposerQueue = {
cancelEdit: () => void
// Loads the first queued prompt into the composer. Returns false when the queue is empty.
editFirst: () => boolean
// Moves an admitted follow-up ahead of the queued prompts, using the queue's serialized reorder.
first: (inboxID: string) => void
}

export type ComposerSession = {
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/composer/composer-touch.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ function TouchComposer(props: { state: State }) {
confirmEdit: (delivery: "steer" | "queue") => record(`Edited queued prompt, ${delivery}`),
cancelEdit: () => record("Cancelled the edit"),
editFirst: () => false,
first() {},
}

const editor = createComposerEditor({
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/composer/composer.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ function ComposerStory(props: {
undoing: () => false,
cancelEdit() {},
editFirst: () => false,
first() {},
}
: undefined,
onSubmit: () => {
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/composer/composer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ export function Composer(props: {
attachKeybind={command.keybindParts("file.attach")}
attachShortcut={command.keybind("file.attach")}
alternateKeybind={[formatKeybind("mod", language.t), "↵"]}
queueFirstKeybind={[formatKeybind("alt", language.t), "↵"]}
queueFirstLabel={language.t("session.queue.first")}
exitShellKeybind={[formatKeybind("esc", language.t)]}
suggestionBoundary={props.suggestionBoundary}
modelControl={
Expand Down
41 changes: 38 additions & 3 deletions packages/app/src/composer/editor/editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ export type ComposerEditorProps = {
attachKeybind?: string[]
attachShortcut?: string
alternateKeybind?: string[]
queueFirstKeybind?: string[]
queueFirstLabel?: string
exitShellKeybind?: string[]
suggestionBoundary?: () => HTMLElement | undefined
}
Expand Down Expand Up @@ -381,7 +383,13 @@ export function ComposerEditor(props: ComposerEditorProps) {

if (event.repeat) return
// On touch, Cmd+Return is the touch bar's primary action, since plain Return cannot send.
props.controller.submit(mod && !touch() ? { alternate: true } : undefined)
props.controller.submit(
!touch() && event.altKey && !mod
? { first: true }
: mod && !touch()
? { alternate: true }
: undefined,
)
}
}}
// The editor holds one flat run of text, mentions and <br>s. A touch keyboard's Return arrives as a
Expand Down Expand Up @@ -506,6 +514,8 @@ export function ComposerEditor(props: ComposerEditorProps) {
<ComposerEditorAlternateDelivery
controller={props.controller}
keybind={props.alternateKeybind ?? ["Mod", "Enter"]}
firstKeybind={props.queueFirstKeybind ?? ["Alt", "Enter"]}
firstLabel={props.queueFirstLabel}
/>
</Show>
<Show when={mode() === "shell"}>
Expand Down Expand Up @@ -1438,7 +1448,12 @@ function composerSuggestionMaxHeight(boundaryHeight: number, search: boolean, hi
// delivery opposite to what plain Enter does. Visible only while the queue
// exposes an alternate (turn running and composer holding a value), so it
// disappears on its own when the current turn ends.
function ComposerEditorAlternateDelivery(props: { controller: ComposerEditorModel; keybind: string[] }) {
function ComposerEditorAlternateDelivery(props: {
controller: ComposerEditorModel
keybind: string[]
firstKeybind: string[]
firstLabel?: string
}) {
const i18n = useI18n()
const view = props.controller.view

Expand All @@ -1456,7 +1471,27 @@ function ComposerEditorAlternateDelivery(props: { controller: ComposerEditorMode
return (
<Show when={action()} keyed>
{(delivery) => (
<Tooltip placement="top" inactive={delivery !== "steer"} value={i18n.t("ui.promptInput.steerHint")}>
<Tooltip
placement="top"
inactive={delivery !== "steer" && !view.submit.queue?.count()}
value={
<Show
when={view.submit.queue?.count() && !view.submit.queue?.editing() && props.firstLabel}
fallback={i18n.t("ui.promptInput.steerHint")}
>
<div class="flex flex-col gap-1">
<div class="flex items-center justify-between gap-4">
<span>{delivery === "steer" ? i18n.t("ui.promptInput.steer") : i18n.t("ui.promptInput.queue")}</span>
<Keybind keys={props.keybind} variant="neutral" />
</div>
<div class="flex items-center justify-between gap-4">
<span>{props.firstLabel}</span>
<Keybind keys={props.firstKeybind} variant="neutral" />
</div>
</div>
</Show>
}
>
<Button
data-action="composer-alternate-delivery"
type="button"
Expand Down
4 changes: 2 additions & 2 deletions packages/app/src/composer/editor/interaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export type ComposerEditorView = {
delivery: Accessor<ComposerDelivery | undefined>
onSubmit: (key: string, comment: string) => Promise<boolean>
}
onSubmit: (options?: { alternate?: boolean }) => void
onSubmit: (options?: { alternate?: boolean; first?: boolean }) => void
onStop: () => void
}
shell?: {
Expand Down Expand Up @@ -748,7 +748,7 @@ export function createComposerEditor(input: {
openShell() {
dispatch({ type: "mode.shell" })
},
submit(options?: { alternate?: boolean }) {
submit(options?: { alternate?: boolean; first?: boolean }) {
if (input.view.submit.available?.() === false) return

if (input.view.draftOnly) return
Expand Down
14 changes: 12 additions & 2 deletions packages/app/src/composer/machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type ComposerSubmission = {
images: ImageAttachmentPart[]
selection: ComposerSelection
delivery: ComposerDelivery
first?: boolean
}

type QuoteItem = Extract<ComposerSubmission["context"][number], { type: "quote" }>
Expand Down Expand Up @@ -88,6 +89,7 @@ export type SubmitSnapshot = {
text: string
mode: "normal" | "shell"
alternate: boolean
first?: boolean
delivery: ComposerDelivery
selection: ComposerSelection | undefined
loading: boolean
Expand Down Expand Up @@ -142,7 +144,7 @@ export type ComposerSubmitEffect =
| { type: "notify.missing-selection" }
| { type: "notify.unqueueable" }
| { type: "interrupt" }
| { type: "submit.retry"; alternate: boolean; done: SubmitDone }
| { type: "submit.retry"; alternate: boolean; first?: boolean; done: SubmitDone }
/** Shows a held prompt in its Session's timeline and clears the composer it came from. */
| { type: "hold.show"; attempt: number; session: ComposerSession; snapshot: SubmitSnapshot }
/** Removes a cancelled held prompt from the timeline and returns it to the composer it left. */
Expand Down Expand Up @@ -224,7 +226,14 @@ export function transitionComposerSubmit(
if (!state.shown)
return {
state: { type: "idle", attempt: state.attempt },
effects: [{ type: "submit.retry", alternate: state.snapshot.alternate, done: state.done }],
effects: [
{
type: "submit.retry",
alternate: state.snapshot.alternate,
first: state.snapshot.first,
done: state.done,
},
],
}

// The composer already cleared, so the send goes on from what was captured at Enter.
Expand Down Expand Up @@ -372,6 +381,7 @@ function prepare(
images: snapshot.draft.prompt.filter((part): part is ImageAttachmentPart => part.type === "image"),
selection,
delivery: snapshot.delivery,
first: snapshot.first,
}

// Only a prompt is admitted under its ID; shell commands and server commands always start fresh.
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/composer/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?

return (alternate ? queue.alternate() : queue.delivery()) ?? "steer"
},
queueFirst: (inboxID) => options?.queue?.first(inboxID),
notify: {
missingSelection: () =>
showToast({
Expand Down
20 changes: 15 additions & 5 deletions packages/app/src/composer/submit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ type ComposerSubmitInput = {
resetHistory: () => void
closePopover: () => void
delivery?: (alternate: boolean) => ComposerDelivery
queueFirst?: (inboxID: string) => void
clientCommand?: (text: string) => (() => void | Promise<void>) | undefined
notify: {
missingSelection: () => void
Expand Down Expand Up @@ -93,7 +94,7 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
}

if (effect.type === "submit.retry")
return dispatch({ type: "submit", snapshot: snapshot(input, effect.alternate), done: effect.done })
return dispatch({ type: "submit", snapshot: snapshot(input, effect.alternate, effect.first), done: effect.done })

if (effect.type === "hold.show") {
input.adapter.beforeSubmit?.()
Expand Down Expand Up @@ -257,11 +258,15 @@ export function createComposerSubmit(input: ComposerSubmitInput) {

return {
state,
submit(event: globalThis.Event, options?: { alternate?: boolean }) {
submit(event: globalThis.Event, options?: { alternate?: boolean; first?: boolean }) {
event.preventDefault()

return new Promise<void>((resolve) =>
dispatch({ type: "submit", snapshot: snapshot(input, options?.alternate ?? false), done: () => resolve() }),
dispatch({
type: "submit",
snapshot: snapshot(input, options?.alternate ?? false, options?.first),
done: () => resolve(),
}),
)
},
submitQuote(key: string, comment: string) {
Expand Down Expand Up @@ -294,12 +299,14 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
}
}

function snapshot(input: ComposerSubmitInput, alternate: boolean): SubmitSnapshot {
function snapshot(input: ComposerSubmitInput, alternate: boolean, first = false): SubmitSnapshot {
const target = input.adapter.state
const prompt = clonePrompt(target.current())
const text = submissionText(prompt)
const mode = input.mode()

const queueFirst = first && mode === "normal" && input.adapter.kind === "active-session" && input.adapter.working()

const context = target.context.items().map((item) => {
if (item.type === "note") return { ...item, live: item.live ? { ...item.live } : undefined }

Expand All @@ -325,7 +332,8 @@ function snapshot(input: ComposerSubmitInput, alternate: boolean): SubmitSnapsho
text,
mode,
alternate,
delivery: input.delivery?.(alternate) ?? "steer",
delivery: queueFirst ? "queue" : (input.delivery?.(alternate) ?? "steer"),
first: queueFirst,
selection: currentSelection(input),
loading: input.adapter.controls().model.loading,
retry: target.retry.current(),
Expand Down Expand Up @@ -568,6 +576,8 @@ function dispatchPrompt(input: ComposerSubmitInput, session: ComposerSession, va

if (!admitted) return false

if (value.first) input.queueFirst?.(value.id)

// Move blocking work only once the steer is admitted, so the next step can read it from the inbox.
void background?.move()

Expand Down
1 change: 1 addition & 0 deletions packages/app/src/runtime/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,7 @@ export const dict = {
"session.queue.count.one": "{{count}} queued",
"session.queue.count.other": "{{count}} queued",
"session.queue.steer": "Steer",
"session.queue.first": "Queue first",
"session.queue.send": "Send",
"session.queue.steerTooltip": "Send without interrupting",
"session.queue.remove": "Remove",
Expand Down
50 changes: 50 additions & 0 deletions packages/app/src/session/composer/queue-machine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,56 @@ const rowIDs = (state: QueueState) => selectQueueRows(state).map((row) => row.id

const [one, two, three] = ["inb_1", "inb_2", "inb_3"].map((id) => item(id))

describe("queue first shares the serialized reorder", () => {
test("a waiting request follows rewritten inbox IDs instead of resurrecting an original", () => {
const result = replay(createQueueState([one, two, three]), [
{ type: "reorder.requested", inboxIDs: [two.id, one.id, three.id], reverted: false },
{ type: "first.requested", id: three.id, reverted: false },
{ type: "mutation.moved", attempt: 1, moved: { [one.id]: "new_1", [two.id]: "new_2", [three.id]: "new_3" } },
{ type: "inbox.synced", items: [item("new_2"), item("new_1"), item("new_3")] },
{ type: "mutation.succeeded", attempt: 1 },
])

expect(runs(result.effects)).toMatchObject([
{ type: "reorder", inboxIDs: [two.id, one.id, three.id] },
{ type: "reorder", inboxIDs: ["new_3", "new_2", "new_1"] },
])
expect(rowIDs(result.state)).toEqual(["new_3", "new_2", "new_1"])

const stale = transitionQueue(result.state, { type: "mutation.failed", attempt: 1, hidden: [] })

expect(stale.state).toBe(result.state)
expect(stale.effects).toEqual([])
})

test.each([one.id, "delivered"])("%s needs no reorder", (id) => {
const state = createQueueState([one, two])

expect(transitionQueue(state, { type: "first.requested", id, reverted: false })).toEqual({ state, effects: [] })
})

test.each(["mutation.succeeded", "mutation.failed", "mutation.timed-out", "dispose"] as const)(
"%s settles a queue-first reorder through the existing lifecycle",
(type) => {
const started = transitionQueue(createQueueState([one, two]), {
type: "first.requested",
id: two.id,
reverted: false,
})

const result = transitionQueue(
started.state,
type === "dispose" ? { type } : { type, attempt: 1, hidden: [], stage: "running" },
)

expect(result.state.status).toBe(type === "dispose" ? "disposed" : "idle")
expect(
result.effects.some((effect) => effect.type === "mutation.timer.clear" || effect.type === "timer.clearAll"),
).toBe(true)
},
)
})

describe("an edit always returns the draft it replaced", () => {
test("when the server delivers the prompt being edited", () => {
const result = replay(createQueueState([one, two]), [
Expand Down
Loading
Loading