feat(app): send quotes directly from the comment popup (#60640)

This commit is contained in:
usrnk1
2026-10-30 20:37:36 +01:00
committed by GitHub
Unverified
parent 2e29481d5c
commit ad71144054
10 changed files with 553 additions and 68 deletions
@@ -3,6 +3,7 @@ import type { SessionMessageAssistant, SessionMessageInfo, ShellInfo } from "@op
import { timelinePresets } from "@opencode/session-ui/timeline/detail"
import { createTwoFilesPatch } from "diff"
import { readSessionDraftText } from "../utils/drafts"
import { holdRoute } from "../utils/app"
import {
assistantID,
assistantMessage,
@@ -2005,6 +2006,7 @@ test("quotes plain timeline text into the composer, with or without a comment",
const user = '[data-slot="user-message-text"]'
const answer = `[data-timeline-part-id="${renderedPartID("prt_quote_answer")}"] [data-slot="text-part-body"]`
await expect(page.locator(answer).getByText("bundle", { exact: true })).toBeVisible()
await expect(page.locator('[data-component="composer-editor"]')).toBeFocused()
const select = (from: string, to: string) =>
page.evaluate(
@@ -2050,7 +2052,7 @@ test("quotes plain timeline text into the composer, with or without a comment",
await comment.fill("Why three?")
await expect(popover.getByRole("button")).toHaveCount(1)
await expect(popover.getByRole("button", { name: "Add comment", exact: true })).toBeVisible()
await popover.getByRole("button", { name: "Add comment", exact: true }).click()
await comment.press("Alt+Enter")
await expect(comment).toHaveCount(0)
await expect(chips.nth(1)).toContainText("Why three?")
await chips.nth(1).click()
@@ -2110,6 +2112,151 @@ test("quotes plain timeline text into the composer, with or without a comment",
await expect(chips).toHaveCount(0)
})
test("quote popup sends independently without consuming the draft or other quotes", async ({ page }) => {
const sent: string[] = []
await setupTimeline(page, {
messages: [userMessage(), assistantMessage([textPart("prt_direct_quote", "Keep this quoted passage.")])],
onPrompt: (input) => void sent.push(String(input.body.delivery)),
})
const answer = page.locator(
`[data-timeline-part-id="${renderedPartID("prt_direct_quote")}"] [data-slot="text-part-body"]`,
)
const editor = page.locator('[data-component="composer-editor"]')
const quote = page
.getByRole("toolbar", { name: "Quote selection" })
.getByRole("button", { name: "Quote", exact: true })
await expect(answer).toHaveText("Keep this quoted passage.")
await editor.fill("Keep my separate draft")
await selectQuoteText(answer)
await quote.click({ modifiers: ["Alt"] })
await expect(editor).toBeFocused()
await selectQuoteText(answer)
await quote.click()
const popup = page.locator('[data-component="composer-quote-comment"]')
const comment = popup.locator("textarea")
const action = popup.getByRole("button")
const modifier = await page.evaluate(() => (/(Mac|iPod|iPhone|iPad)/.test(navigator.platform) ? "Meta" : "Control"))
await expect(comment).toBeFocused()
await comment.fill("Explain this please")
await action.focus()
await page.keyboard.down(modifier)
await expect(action).toHaveAccessibleName("Send quote")
await page.keyboard.press("Enter")
await page.keyboard.up(modifier)
await expect(popup).toHaveCount(0)
await expect.poll(() => sent).toEqual(["steer"])
await expect(editor).toHaveText("Keep my separate draft")
const remaining = page.locator('[data-component="composer-attachments"] [data-component="attachment-card"]')
await expect(remaining).toHaveCount(1)
await expect(remaining).toContainText("Keep this quoted passage.")
await expect(remaining).not.toContainText("Explain this please")
})
test("a pending quote send hides mentions and keeps the comment read-only", async ({ page }) => {
const sent: string[] = []
await setupTimeline(page, {
settings: { followUpBehavior: "steer" },
sessionStatus: { [sessionID]: { type: "busy" } },
messages: [userMessage(), assistantMessage([textPart("prt_quote_mentions", "Keep this quoted passage.")])],
findFiles: () => ["src/api.ts"],
onPrompt: (input) => void sent.push(String(input.body.delivery)),
})
const answer = page.locator(
`[data-timeline-part-id="${renderedPartID("prt_quote_mentions")}"] [data-slot="text-part-body"]`,
)
await expect(answer).toHaveText("Keep this quoted passage.")
await expect(page.locator('[data-component="composer-editor"]')).toBeFocused()
await selectQuoteText(answer)
await page
.getByRole("toolbar", { name: "Quote selection" })
.getByRole("button", { name: "Quote", exact: true })
.click()
const popup = page.locator('[data-component="composer-quote-comment"]')
const comment = popup.locator("textarea")
const modifier = await page.evaluate(() => (/(Mac|iPod|iPhone|iPad)/.test(navigator.platform) ? "Meta" : "Control"))
await comment.fill("Explain @src/a")
await expect(popup.locator('[data-slot="line-comment-v2-mention-item"]')).toHaveCount(1)
const admission = await holdRoute(page, new RegExp(`/api/session/${sessionID}/prompt(\\?|$)`), { method: "POST" })
await popup.locator('[data-slot="line-comment-v2-submit"]').click({ modifiers: [modifier] })
await admission.arrived
await expect(popup.getByRole("button")).toBeDisabled()
await expect(comment).toHaveAttribute("readonly", "")
await expect(popup.locator('[data-component="loader-v2"]')).toBeVisible()
await expect(popup.locator('[data-slot="line-comment-v2-mention-item"]')).toHaveCount(0)
await comment.press("Tab")
await expect(comment).toHaveValue("Explain @src/a")
expect(admission.requests).toHaveLength(1)
admission.release()
await expect(popup).toHaveCount(0)
await expect.poll(() => sent).toEqual(["queue"])
})
function selectQuoteText(target: Locator) {
return target.evaluate((element) => {
const range = document.createRange()
range.selectNodeContents(element)
window.getSelection()?.removeAllRanges()
window.getSelection()?.addRange(range)
})
}
test("a failed direct quote send keeps the popup and comment for retry", async ({ page }) => {
let reject = true
await setupTimeline(page, {
messages: [userMessage(), assistantMessage([textPart("prt_direct_quote_failure", "Keep this quoted passage.")])],
onPrompt: () => {
if (reject) throw new Error("Quote send failed")
},
})
const answer = page.locator(
`[data-timeline-part-id="${renderedPartID("prt_direct_quote_failure")}"] [data-slot="text-part-body"]`,
)
await expect(answer).toHaveText("Keep this quoted passage.")
await selectQuoteText(answer)
await page
.getByRole("toolbar", { name: "Quote selection" })
.getByRole("button", { name: "Quote", exact: true })
.click()
const popup = page.locator('[data-component="composer-quote-comment"]')
const comment = popup.locator("textarea")
const modifier = await page.evaluate(() => (/(Mac|iPod|iPhone|iPad)/.test(navigator.platform) ? "Meta" : "Control"))
await comment.fill("Keep my latest comment")
await comment.press(`${modifier}+Enter`)
await expect(popup.getByRole("alert")).toHaveText("Couldn’t send. Your comment is still here. Try again.")
await expect(comment).toHaveValue("Keep my latest comment")
await expect(comment).toBeEditable()
reject = false
await popup.getByRole("button").click({ modifiers: [modifier] })
await expect(popup).toHaveCount(0)
await expect(page.locator('[data-component="composer-attachments"] [data-component="attachment-card"]')).toHaveCount(
0,
)
})
test("highlights the exact duplicate passage whenever its quote comment is open", async ({ page }) => {
let reject = true
await setupTimeline(page, {
@@ -2230,6 +2377,7 @@ test("highlights the exact duplicate passage whenever its quote comment is open"
await comment.press("Enter")
await expect(comment).toHaveCount(0)
await expect.poll(highlights).toEqual([[]])
await expect(editor).toBeFocused()
await select(second, 23)
await toolbar.getByRole("button", { name: "Quote", exact: true }).click({ modifiers: ["Alt"] })
@@ -270,6 +270,7 @@ export function ComposerEditor(props: ComposerEditorProps) {
onQuoteFocus={props.controller.focusQuotePrompt}
onEditQuote={props.controller.editQuote}
onQuoteComment={(quote, comment) => props.controller.commentQuote(quote.key, comment)}
quoteSubmit={view.submit.quote}
searchPaths={props.controller.searchPaths}
/>
</Show>
@@ -686,6 +687,7 @@ function ComposerAttachments(props: {
onQuoteFocus?: () => void
onEditQuote?: (key?: string) => void
onQuoteComment?: (quote: Extract<ComposerComment, { type: "quote" }>, comment: string) => void
quoteSubmit?: ComposerEditorModel["view"]["submit"]["quote"]
searchPaths?: (query: string) => Promise<string[]>
}) {
const i18n = useI18n()
@@ -882,6 +884,13 @@ function ComposerAttachments(props: {
text={current.text}
comment={current.comment ?? ""}
mention={(query) => props.searchPaths?.(query) ?? Promise.resolve([])}
send={
props.quoteSubmit && {
available: props.quoteSubmit.available(),
delivery: props.quoteSubmit.delivery(),
onSubmit: (comment) => props.quoteSubmit!.onSubmit(current.key, comment),
}
}
onSubmit={(comment) => {
props.onQuoteComment?.(current, comment)
props.onEditQuote?.()
@@ -23,7 +23,7 @@ import {
type ComposerInteractionEvent,
} from "../suggestions/machine"
import { clonePrompt, isAttachment, promptLength } from "../prompt-parts"
import type { ComposerQueue } from "../adapter"
import type { ComposerDelivery, ComposerQueue } from "../adapter"
import { isCommentItem } from "../state"
import type { ComposerQuoteAnchor } from "@opencode/plugin/gui"
@@ -49,6 +49,11 @@ export type ComposerEditorView = {
held?: Accessor<boolean>
working?: Accessor<boolean>
queue?: ComposerQueue
quote?: {
available: Accessor<boolean>
delivery: Accessor<ComposerDelivery | undefined>
onSubmit: (key: string, comment: string) => Promise<boolean>
}
onSubmit: (options?: { alternate?: boolean }) => void
onStop: () => void
}
@@ -1,4 +1,4 @@
import { createMemo, onCleanup } from "solid-js"
import { createMemo, onCleanup, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { Portal } from "solid-js/web"
import { makeEventListener } from "@solid-primitives/event-listener"
@@ -6,6 +6,15 @@ import { createResizeObserver } from "@solid-primitives/resize-observer"
import { LineCommentEditor } from "@opencode/ui/line-comment"
import { useLanguage } from "@/runtime/i18n/language"
import type { ComposerQuoteAnchor } from "@opencode/plugin/gui"
import type { ComposerDelivery } from "../adapter"
const IS_MAC = /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
const sendLabels = {
queue: "session.quote.queue",
steer: "session.quote.steer",
send: "session.quote.send",
} as const
const GAP = 8
@@ -19,6 +28,11 @@ export function QuoteCommentEditor(props: {
mention: (query: string) => Promise<string[]>
onSubmit: (comment: string) => void
onClose: (focus?: boolean) => void
send?: {
available: boolean
delivery: ComposerDelivery | undefined
onSubmit: (comment: string) => Promise<boolean>
}
}) {
const language = useLanguage()
@@ -30,6 +44,8 @@ export function QuoteCommentEditor(props: {
revision: 0,
height: 0,
openingHeight: 0,
sending: false,
failed: false,
})
const width = () => Math.min(WIDTH, state.viewport - GAP * 2)
@@ -47,6 +63,8 @@ export function QuoteCommentEditor(props: {
let frame: number | undefined
let mounted = true
const schedule = () => {
if (frame !== undefined) return
frame = requestAnimationFrame(() => {
@@ -61,6 +79,8 @@ export function QuoteCommentEditor(props: {
}
onCleanup(() => {
mounted = false
if (frame !== undefined) cancelAnimationFrame(frame)
})
@@ -72,7 +92,7 @@ export function QuoteCommentEditor(props: {
if (target instanceof Node && (element?.contains(target) || props.anchor.contains(target))) return
if (state.draft.trim() === props.comment.trim()) props.onClose()
if (!state.sending && state.draft.trim() === props.comment.trim()) props.onClose()
})
const left = () => Math.min(Math.max(source()?.left ?? state.rect.left, GAP), state.viewport - width() - GAP)
@@ -88,6 +108,28 @@ export function QuoteCommentEditor(props: {
const availableHeight = () => Math.max(0, bottom() - GAP)
const top = () => Math.max(GAP, bottom() - state.height)
const alternateSubmit = createMemo(() => {
const send = props.send
if (!send) return
return {
label: language.t(sendLabels[send.delivery ?? "send"]),
keys: [IS_MAC ? "⌘" : language.t("common.key.ctrl"), "⏎"],
disabled: !send.available,
onSubmit: async (comment: string) => {
setState({ sending: true, failed: false })
const sent = await send.onSubmit(comment)
if (!mounted) return
setState({ sending: false, failed: !sent })
if (sent) props.onClose()
},
}
})
return (
<Portal>
<div
@@ -125,6 +167,8 @@ export function QuoteCommentEditor(props: {
onInput={(value) => setState("draft", value)}
onCancel={() => props.onClose(true)}
onSubmit={props.onSubmit}
submitting={state.sending}
alternateSubmit={alternateSubmit()}
placeholder={language.t("session.quote.optionalCommentPlaceholder")}
submitLabel={language.t(
props.comment.trim()
@@ -137,6 +181,14 @@ export function QuoteCommentEditor(props: {
mention={{ items: props.mention }}
selection={<span dir="auto">{props.text}</span>}
/>
<Show when={state.failed}>
<p
role="alert"
class="rounded-b-[8px] bg-v2-background-bg-layer-01 px-3 pb-3 text-[12px] leading-[var(--line-height-compact)] text-v2-text-text-base"
>
{language.t("session.quote.sendFailed")}
</p>
</Show>
</div>
</div>
</Portal>
+9
View File
@@ -536,6 +536,15 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
held: submission.held,
working: adapter.working,
queue: options?.queue,
quote:
adapter.kind === "active-session"
? {
available: () =>
available() && !adapter.controls().model.loading && !submission.held() && !options?.queue?.undoing(),
delivery: () => (adapter.working() ? (options?.queue?.alternate() ?? "steer") : undefined),
onSubmit: submission.submitQuote,
}
: undefined,
onSubmit: (submitOptions) => {
if (!available()) return
const queue = options?.queue
+8 -6
View File
@@ -185,17 +185,19 @@ function createComposerStateValue(store: ComposerStore, setStore: SetStoreFuncti
},
/** Edits the file comment, note, or quote with this commentID; only file comments carry a preview. */
updateComment(commentID: string, next: { readonly comment?: string; readonly preview?: string }) {
setStore("context", "items", (items) =>
items.map((item) => {
if (item.commentID !== commentID) return item
if (item.type === "quote") return { ...item, comment: next.comment }
setStore(
"context",
"items",
(item) => item.commentID === commentID,
(item) => {
// Preserve quote identity so an open comment editor does not remount.
if (item.type === "quote") return { comment: next.comment }
const value =
item.type === "file" ? { ...item, ...next } : { ...item, comment: next.comment ?? item.comment }
return { ...value, key: contextItemKey(value) }
}),
},
)
clearRetry()
},
+114 -6
View File
@@ -84,14 +84,14 @@ function submitInput(
commands: () => readonly { name: string }[] | undefined = () => [],
history: string[] = [],
clientCommand?: (text: string) => (() => void | Promise<void>) | undefined,
delivery: ComposerDelivery = "steer",
delivery: (alternate: boolean) => ComposerDelivery = () => "steer",
) {
return createComposerSubmit({
adapter,
mode: () => mode,
commands,
clientCommand,
delivery: () => delivery,
delivery,
editor: () => undefined,
queueScroll() {},
addToHistory: (prompt) =>
@@ -176,6 +176,108 @@ function session(input: {
}
describe("Composer submission", () => {
test.each(["steer", "queue"] as const)(
"sends only the selected quote as a %s, including its comment mentions, without clearing the draft",
async (delivery) => {
const state = createMemoryComposerState({ prompt: "/review keep this draft" }).capture()
const image = {
type: "image" as const,
id: "unrelated-image",
filename: "draft.png",
mime: "image/png",
blob: { id: "unrelated-image", url: "data:image/png;base64,YQ==" },
}
state.set([...state.current(), image], 5)
state.mode.set("shell")
state.context.add({ type: "quote", text: "Selected passage", commentID: "selected", comment: "Old comment" })
state.context.add({ type: "quote", text: "Unrelated passage", commentID: "other" })
state.context.add({ type: "file", path: "unrelated.ts" })
const before = state.current()
const requests: Parameters<ComposerSession["data"]["session"]["prompt"]>[0][] = []
const submission = submitInput(
active(state, session({ calls: [], prompt: async (value) => void requests.push(value) })),
undefined,
"shell",
undefined,
undefined,
undefined,
(alternate) => {
expect(alternate).toBe(true)
return delivery
},
)
expect(await submission.submitQuote("quote:c=selected", "Compare @src/api.ts")).toBe(true)
expect(requests).toHaveLength(1)
expect(requests[0]?.text).toBe(
"The user quoted the following from earlier in the conversation:\n> Selected passage\n\nThe user made the following comment regarding this quote: Compare @src/api.ts",
)
expect(requests[0]).toMatchObject({
delivery,
files: [{ uri: "file:///C:/repo/src/api.ts", name: "api.ts" }],
agents: [],
skills: [],
metadata: {
displayText: "",
comments: [{ type: "quote", text: "Selected passage", comment: "Compare @src/api.ts" }],
attachments: [],
},
})
expect(state.current()).toBe(before)
expect(state.cursor()).toBe(5)
expect(state.mode.current()).toBe("shell")
expect(state.context.items().map((item) => item.key)).toEqual([
"quote:c=other",
"file:unrelated.ts:undefined:undefined",
])
},
)
test("a failed quote send retains its latest comment and prevents duplicate submissions while pending", async () => {
const state = createMemoryComposerState({ prompt: "Keep this draft" }).capture()
state.context.add({ type: "quote", text: "Selected passage", commentID: "selected" })
const failed = Promise.withResolvers<void>()
const started = Promise.withResolvers<void>()
const errors: string[] = []
const calls: string[] = []
const submission = submitInput(
active(
state,
session({
calls,
prompt: async () => {
started.resolve()
await failed.promise
},
}),
),
{ missingSelection() {}, unqueueable() {}, failed: (_kind, error) => void errors.push(String(error)) },
)
const pending = submission.submitQuote("quote:c=selected", "Latest comment")
await started.promise
expect(await submission.submitQuote("quote:c=selected", "Duplicate")).toBe(false)
failed.reject(new Error("Could not send"))
expect(await pending).toBe(false)
expect(errors).toHaveLength(1)
expect(state.current()).toEqual([{ type: "text", content: "Keep this draft", start: 0, end: 15 }])
expect(state.context.items()).toMatchObject([
{ key: "quote:c=selected", text: "Selected passage", comment: "Latest comment" },
])
expect(calls.filter((call) => call === "send")).toHaveLength(2)
})
test("applies the selection and runs a client argument command without admitting it to the session", async () => {
const state = createMemoryComposerState().capture()
@@ -319,9 +421,15 @@ describe("Composer submission", () => {
switchModel: async () => committed.promise,
})
await submitInput(active(state, target), undefined, "normal", undefined, undefined, undefined, delivery).submit(
new Event("submit"),
)
await submitInput(
active(state, target),
undefined,
"normal",
undefined,
undefined,
undefined,
() => delivery,
).submit(new Event("submit"))
expect(state.current()).toEqual([{ type: "text", content: "", start: 0, end: 0 }])
expect(statuses).toEqual(["running"])
@@ -630,7 +738,7 @@ describe("Composer submission", () => {
() => [],
[],
undefined,
delivery,
() => delivery,
).submit(new Event("submit"))
// The send settles after submit returns; let it and the move that follows it finish.
await new Promise((resolve) => setTimeout(resolve, 0))
+100 -37
View File
@@ -165,36 +165,7 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
const restore = () => restoreSubmission(input, submission, value, comments)
if (value.mode === "normal" && !command) {
// The timeline shows a steer, and any switches it makes, as the composer clears; a queued prompt shows in
// the queue once admitted.
if (value.delivery === "steer")
session.handoff.set({
message: handoffMessage(value),
selection: {
agent: value.selection.agent,
model: {
id: value.selection.model.modelID,
providerID: value.selection.model.providerID,
variant: value.selection.variant,
},
},
})
const optimisticBusy = !input.adapter.working()
// Like iOS, a steer moves the run's blocking shells and subagents to the background. The move follows
// admission: the steer already waits in the inbox when the moved work ends the step, so that step reads it.
const background = value.delivery === "steer" && !optimisticBusy ? session.background?.() : undefined
if (optimisticBusy) session.data.session.setStatus(session.id, "running")
const sending = sendPrompt(session, value, input.adapter.controls().model.selection.trackSessionCommit).then(
() => {
void background?.move()
return { ok: true as const }
},
(error) => ({ ok: false as const, error }),
)
const dispatch = dispatchPrompt(input, session, value)
await started.cleanupReady
await started.complete?.()
@@ -203,12 +174,7 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
submission.context.forEach((item) => submission.target().context.remove(item.key))
input.comments.clear()
clearSubmission(input, submission)
void sending.then((result) => {
if (!result.ok)
failSubmission(input, session, "prompt", result.error, restore, value.id, () => {
if (optimisticBusy) session.data.session.setStatus(session.id, "idle")
})
})
void dispatch.sending.then((result) => dispatch.settle(result, restore))
return
}
@@ -239,6 +205,56 @@ export function createComposerSubmit(input: ComposerSubmitInput) {
return {
submit,
async submitQuote(key: string, comment: string) {
if (input.adapter.kind !== "active-session" || held() || submitting.has(input.adapter.state)) return false
const target = input.adapter.state
const quote = target.context.items().find((item) => item.key === key)
if (quote?.type !== "quote") return false
const selection = currentSelection(input)
if (!selection) {
input.notify.missingSelection()
return false
}
const session = input.adapter.session()
const value: ComposerSubmission = {
id: SessionMessage.ID.create(),
mode: "normal",
prompt: [],
context: [{ ...quote, comment, source: quote.source ? { ...quote.source } : undefined }],
text: "",
images: [],
selection,
delivery: input.delivery?.(true) ?? "steer",
}
submitting.add(input.adapter.state)
try {
const dispatch = dispatchPrompt(input, session, value)
const sent = dispatch.settle(await dispatch.sending, () => {
target.context.updateComment(quote.commentID, { comment })
return true
})
if (!sent) return false
target.context.remove(key)
if (target.quoteComment.key() === key) target.quoteComment.set()
input.adapter.submitted()
return true
} finally {
submitting.delete(input.adapter.state)
}
},
held,
stop: () => {
// Stopping a held send cancels it and leaves the prompt in the composer.
@@ -395,6 +411,51 @@ function currentSelection(input: ComposerSubmitInput): ComposerSelection | undef
}
}
function dispatchPrompt(input: ComposerSubmitInput, session: ComposerSession, value: ComposerSubmission) {
// A steer appears in the timeline before the composer clears; queued prompts appear in the queue on admission.
if (value.delivery === "steer")
session.handoff.set({
message: handoffMessage(value),
selection: {
agent: value.selection.agent,
model: {
id: value.selection.model.modelID,
providerID: value.selection.model.providerID,
variant: value.selection.variant,
},
},
})
const optimisticBusy = !input.adapter.working()
const background = value.delivery === "steer" && !optimisticBusy ? session.background?.() : undefined
if (optimisticBusy) session.data.session.setStatus(session.id, "running")
const sending = sendPrompt(session, value, input.adapter.controls().model.selection.trackSessionCommit).then(
() => ({ ok: true as const }),
(error) => ({ ok: false as const, error }),
)
return {
sending,
// The composer settles after clearing its captured draft; a quote settles before removing only its context.
settle(result: Awaited<typeof sending>, restore: () => boolean) {
const admitted =
result.ok ||
failSubmission(input, session, "prompt", result.error, restore, value.id, () => {
if (optimisticBusy) session.data.session.setStatus(session.id, "idle")
})
if (!admitted) return false
// Move blocking work only once the steer is admitted, so the next step can read it from the inbox.
void background?.move()
return true
},
}
}
function clearSubmission(input: ComposerSubmitInput, submission: ReturnType<typeof createComposerSubmission>) {
submission.clear()
submission.target().mode.set("normal")
@@ -654,10 +715,12 @@ function failSubmission(
messageID?: string,
rollback?: () => void,
) {
if (messageID && session.admitted(messageID)) return
if (messageID && session.admitted(messageID)) return true
if (messageID) session.handoff.clear(messageID)
rollback?.()
restore()
input.notify.failed(kind, error)
return false
}
+4
View File
@@ -697,6 +697,10 @@ export const dict = {
"session.quote.optionalCommentPlaceholder": "Add an optional comment...",
"session.quote.done": "Done",
"session.quote.addComment": "Add comment",
"session.quote.send": "Send quote",
"session.quote.queue": "Queue quote",
"session.quote.steer": "Steer with quote",
"session.quote.sendFailed": "Couldn’t send. Your comment is still here. Try again.",
"session.quote.commentPlaceholder": "Add a comment about this quote",
"session.quote.tooLong": "Selection too long",
"session.header.open.finder": "Finder",
@@ -18,6 +18,8 @@ import { Icon } from "@opencode/ui/icon"
import { IconButton } from "@opencode/ui/icon-button"
import { Keybind } from "@opencode/ui/keybind"
import { Tooltip } from "@opencode/ui/tooltip"
import { Loader } from "@opencode/ui/loader"
import { makeEventListener } from "@solid-primitives/event-listener"
import check from "./quote-check.svg"
import "./line-comment.css"
@@ -100,6 +102,15 @@ export interface LineCommentEditorProps extends Omit<ComponentProps<"div">, "chi
/** Submit an empty value too, such as to clear a comment that exists (default: false). Compact empty actions otherwise cancel. */
allowEmpty?: boolean
mention?: LineCommentEditorMention
/** Compact editor action on Mod+Enter or modifier-click. */
alternateSubmit?: {
label: string
keys: string[]
disabled?: boolean
onSubmit: (value: string) => void
}
/** Keep the draft read-only and prevent duplicate actions while its submission settles. */
submitting?: boolean
}
function pathFilename(path: string) {
@@ -119,6 +130,8 @@ export function LineCommentEditor(props: LineCommentEditorProps) {
let textareaRef: HTMLTextAreaElement | undefined
const [mentionOpen, setMentionOpen] = createSignal(false)
const [alternate, setAlternate] = createSignal(false)
const [local, rest] = splitProps(props, [
"label",
"value",
@@ -134,6 +147,8 @@ export function LineCommentEditor(props: LineCommentEditorProps) {
"autofocus",
"allowEmpty",
"mention",
"alternateSubmit",
"submitting",
"class",
"classList",
])
@@ -141,10 +156,25 @@ export function LineCommentEditor(props: LineCommentEditorProps) {
const canSubmit = () => !!local.allowEmpty || local.value.trim().length > 0
const compactCancel = () => !canSubmit()
const alternateActive = () => !!local.alternateSubmit && alternate()
const compactLabel = () =>
compactCancel()
? (local.cancelLabel ?? i18n.t("ui.lineComment.cancel"))
: (local.submitLabel ?? i18n.t("ui.lineComment.submit"))
alternateActive()
? local.alternateSubmit!.label
: compactCancel()
? (local.cancelLabel ?? i18n.t("ui.lineComment.cancel"))
: (local.submitLabel ?? i18n.t("ui.lineComment.submit"))
createEffect(() => {
if (local.variant !== "compact" || !local.alternateSubmit) return
const update = (event: KeyboardEvent) => setAlternate(modified(event))
// Capture modifier releases; the textarea stops key propagation.
makeEventListener(document, "keydown", update, { capture: true })
makeEventListener(document, "keyup", update, { capture: true })
makeEventListener(window, "blur", () => setAlternate(false))
})
const closeMention = () => {
setMentionOpen(false)
@@ -228,10 +258,18 @@ export function LineCommentEditor(props: LineCommentEditorProps) {
selectMention(items.find((item) => item.path === active) ?? items[0])
}
const submit = () => {
const submit = (alternate = false) => {
if (local.submitting) return
const v = local.value.trim()
if (!v && !local.allowEmpty) return
if (alternate && local.alternateSubmit) {
if (!local.alternateSubmit.disabled) local.alternateSubmit.onSubmit(v)
return
}
local.onSubmit(v)
}
@@ -278,6 +316,7 @@ export function LineCommentEditor(props: LineCommentEditorProps) {
data-component="line-comment-v2"
data-variant="editor"
data-layout={local.variant ?? "default"}
aria-busy={local.submitting || undefined}
classList={{
...local.classList,
[local.class ?? ""]: !!local.class,
@@ -300,6 +339,7 @@ export function LineCommentEditor(props: LineCommentEditorProps) {
rows={local.rows ?? (local.variant === "compact" ? 1 : 4)}
placeholder={local.placeholder ?? i18n.t("ui.lineComment.contextPlaceholder")}
value={local.value}
readOnly={local.submitting}
style={{ "unicode-bidi": "plaintext", "text-align": "start" }}
onInput={(e) => {
local.onInput(e.currentTarget.value)
@@ -312,7 +352,7 @@ export function LineCommentEditor(props: LineCommentEditorProps) {
if (e.isComposing || e.keyCode === 229) return
if (mentionOpen()) {
if (mentionOpen() && !local.submitting) {
if (e.key === "Escape") {
e.preventDefault()
closeMention()
@@ -343,6 +383,8 @@ export function LineCommentEditor(props: LineCommentEditorProps) {
if (e.key === "Escape") {
e.preventDefault()
if (local.submitting) return
e.currentTarget.blur()
local.onCancel()
@@ -351,11 +393,13 @@ export function LineCommentEditor(props: LineCommentEditorProps) {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault()
submit()
if (e.repeat) return
submit(modified(e))
}
}}
/>
<Show when={mentionOpen() && mention.flat().length > 0}>
<Show when={!local.submitting && mentionOpen() && mention.flat().length > 0}>
<div data-slot="line-comment-v2-mention-list">
<For each={mention.flat().slice(0, 10)}>
{(item) => {
@@ -388,9 +432,21 @@ export function LineCommentEditor(props: LineCommentEditorProps) {
<Show when={local.variant === "compact"}>
<Tooltip
value={
<>
{compactLabel()} <Keybind keys={[compactCancel() ? "Esc" : "⏎"]} variant="neutral" />
</>
<div class="flex flex-col gap-1.5">
<div class="flex items-center gap-1.5">
{compactLabel()}
<Keybind
keys={alternateActive() ? local.alternateSubmit!.keys : [compactCancel() ? "Esc" : "⏎"]}
variant="neutral"
/>
</div>
<Show when={local.alternateSubmit && !alternateActive()}>
<div class="flex items-center gap-1.5">
{local.alternateSubmit!.label}
<Keybind keys={local.alternateSubmit!.keys} variant="neutral" />
</div>
</Show>
</div>
}
placement="top"
>
@@ -398,9 +454,16 @@ export function LineCommentEditor(props: LineCommentEditorProps) {
data-slot="line-comment-v2-submit"
type="button"
size="small"
variant={local.value.trim() ? "neutral" : "ghost-muted"}
variant={
alternateActive() || local.submitting ? "submit" : local.value.trim() ? "neutral" : "ghost-muted"
}
disabled={local.submitting || (alternateActive() && local.alternateSubmit?.disabled)}
icon={
compactCancel() ? (
local.submitting ? (
<Loader />
) : alternateActive() ? (
<Icon name="arrow-up" />
) : compactCancel() ? (
<Icon name="close" />
) : (
<span
@@ -411,12 +474,30 @@ export function LineCommentEditor(props: LineCommentEditorProps) {
)
}
aria-label={compactLabel()}
onClick={() => (compactCancel() ? local.onCancel() : submit())}
onPointerEnter={(event) => {
if (modified(event)) setAlternate(true)
}}
onClick={(event) => {
if (compactCancel() && !alternateActive()) return local.onCancel()
submit(alternateActive() || modified(event))
}}
onKeyDown={(event) => {
if (event.key !== "Escape" || event.isComposing) return
if (event.isComposing) return
if (event.key === "Enter" && modified(event) && local.alternateSubmit) {
event.preventDefault()
event.stopPropagation()
if (!event.repeat) submit(true)
return
}
if (event.key !== "Escape") return
event.preventDefault()
event.stopPropagation()
local.onCancel()
if (!local.submitting) local.onCancel()
}}
/>
</Tooltip>
@@ -441,3 +522,7 @@ export function LineCommentEditor(props: LineCommentEditorProps) {
</div>
)
}
function modified(event: Pick<KeyboardEvent, "metaKey" | "ctrlKey" | "altKey" | "shiftKey">) {
return (event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey
}