fix(app): keep composer comment focus and editor caret through explicit state machines (#61969)

This commit is contained in:
Luke Parker
2026-11-05 00:43:39 -06:00
committed by GitHub
Unverified
parent ae828d7b74
commit 3b1ab8d789
12 changed files with 720 additions and 82 deletions
@@ -1149,6 +1149,33 @@ test("shows the dropzone and attaches a dropped file", async ({ page }) => {
await expect(page.locator('[data-component="composer-attachments"]')).toContainText("dropzone.txt")
})
test("an attachment pasted mid-sentence leaves the text and the caret where they were", async ({ page }) => {
const { editor } = await openDraft(page, {
name: "ComposerDraft",
provider: NO_PROVIDER,
onFileWrite: () => undefined,
})
await editor.click()
await page.keyboard.type("Hello world")
await editor.press("Home")
for (let count = 0; count < "Hello".length; count++) await editor.press("ArrowRight")
const text = await editor.evaluateHandle((element) => element.firstChild)
await editor.evaluate((element) => {
const data = new DataTransfer()
data.items.add(new File(["Attachment fixture"], "notes.txt", { type: "text/plain" }))
element.dispatchEvent(new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }))
})
await expect(page.locator('[data-component="composer-attachments"]')).toContainText("notes.txt")
// A rewrite of the editor would replace this node, even when it put the caret back in the same place.
expect(await editor.evaluate((element, node) => element.firstChild === node, text)).toBe(true)
await page.keyboard.type(",")
await expect(editor).toHaveText("Hello, world")
})
test("keeps one dropzone while a file drag crosses the composer, and none for a text drag", async ({ page }) => {
const editor = await draft(page)
await page.keyboard.type("worktree off the latest dev")
@@ -0,0 +1,112 @@
import { describe, expect, test } from "bun:test"
import {
commentActiveTarget,
commentFocusTarget,
INITIAL_COMMENT_FOCUS_STATE,
transitionCommentFocus,
type CommentFocusEffect,
type CommentFocusEvent,
type CommentFocusState,
} from "./comment-focus-machine"
const a = { file: "a.ts", id: "c1" }
const b = { file: "b.ts", id: "c2" }
function run(events: CommentFocusEvent[], state: CommentFocusState = INITIAL_COMMENT_FOCUS_STATE) {
return events.reduce<{ state: CommentFocusState; effects: CommentFocusEffect[] }>(
(current, event) => {
const step = transitionCommentFocus(current.state, event)
return { state: step.state, effects: [...current.effects, ...step.effects] }
},
{ state, effects: [] },
)
}
describe("comment focus handoff", () => {
test("a request waits for its view however late it mounts, and one acknowledgement settles it", () => {
const opened = transitionCommentFocus(INITIAL_COMMENT_FOCUS_STATE, { type: "comment.opened", target: a })
expect(opened.state).toEqual({ status: "pending", attempt: 1, target: a, active: a })
expect(opened.effects).toEqual([{ type: "timer.start", attempt: 1 }])
const acknowledged = transitionCommentFocus(opened.state, { type: "focus.set", target: null })
expect(acknowledged.state).toEqual({ status: "idle", attempt: 1, active: a })
expect(acknowledged.effects).toEqual([{ type: "timer.clear" }])
expect(commentFocusTarget(acknowledged.state)).toBeNull()
expect(commentActiveTarget(acknowledged.state)).toEqual(a)
// The old retry loop requested the same comment again after the view had revealed it.
const repeated = transitionCommentFocus(acknowledged.state, { type: "focus.set", target: null })
expect(repeated.state).toBe(acknowledged.state)
})
test("a newer request wins over the older one's timeout", () => {
const step = run([
{ type: "comment.opened", target: a },
{ type: "comment.opened", target: b },
{ type: "focus.timed-out", attempt: 1 },
])
expect(step.state).toEqual({ status: "pending", attempt: 2, target: b, active: b })
const timedOut = transitionCommentFocus(step.state, { type: "focus.timed-out", attempt: 2 })
expect(timedOut.state).toEqual({ status: "idle", attempt: 2, active: b })
expect(timedOut.effects).toEqual([{ type: "timer.clear" }])
})
test("a request for the comment already pending keeps its attempt and timer", () => {
const pending = run([{ type: "comment.opened", target: a }]).state
for (const event of [
{ type: "comment.opened", target: { ...a } },
{ type: "focus.set", target: { ...a } },
{ type: "active.set", target: { ...a } },
] satisfies CommentFocusEvent[]) {
const step = transitionCommentFocus(pending, event)
expect(step.state).toBe(pending)
expect(step.effects).toEqual([])
}
})
test("a new comment asks for focus without changing the active comment", () => {
const step = run([
{ type: "active.set", target: a },
{ type: "focus.set", target: b },
])
expect(step.state).toEqual({ status: "pending", attempt: 1, target: b, active: a })
})
test("removing the pending comment settles it; removing another comment does not", () => {
const pending = run([{ type: "comment.opened", target: a }]).state
expect(transitionCommentFocus(pending, { type: "comment.removed", target: b }).state).toBe(pending)
const removed = transitionCommentFocus(pending, { type: "comment.removed", target: { ...a } })
expect(removed.state).toEqual({ status: "idle", attempt: 1, active: a })
expect(removed.effects).toEqual([{ type: "timer.clear" }])
})
test("a reset clears the request and the active comment", () => {
const step = run([{ type: "comment.opened", target: a }, { type: "comments.reset" }])
expect(step.state).toEqual({ status: "idle", attempt: 1, active: null })
expect(step.effects).toEqual([{ type: "timer.start", attempt: 1 }, { type: "timer.clear" }])
expect(transitionCommentFocus(step.state, { type: "comments.reset" }).state).toBe(step.state)
})
test("disposal cancels the timer and ignores everything after it", () => {
const disposed = run([{ type: "comment.opened", target: a }, { type: "disposed" }])
expect(disposed.state).toEqual({ status: "disposed" })
expect(disposed.effects.at(-1)).toEqual({ type: "timer.clear" })
expect(commentFocusTarget(disposed.state)).toBeNull()
expect(commentActiveTarget(disposed.state)).toBeNull()
for (const event of [
{ type: "focus.set", target: b },
{ type: "focus.timed-out", attempt: 1 },
{ type: "comment.opened", target: b },
] satisfies CommentFocusEvent[])
expect(transitionCommentFocus(disposed.state, event).state).toBe(disposed.state)
})
})
@@ -0,0 +1,141 @@
// An unanswered request stops waiting for its view, so a panel opened minutes later does not jump to an old comment.
export const COMMENT_FOCUS_TIMEOUT_MS = 5_000
export type CommentTarget = {
readonly file: string
readonly id: string
}
/**
* A session's comment focus handoff and its active comment.
* - `idle`: no view has a comment to reveal; `active` still marks the last opened comment.
* - `pending`: the view that shows `target` (the review diff or a file tab) reveals it and acknowledges with
* `focus.set(null)`, or the request times out.
* - `disposed`: the session's comment state was evicted; late acknowledgements and timers are ignored.
*/
export type CommentFocusState =
| { readonly status: "idle"; readonly attempt: number; readonly active: CommentTarget | null }
| {
readonly status: "pending"
readonly attempt: number
readonly target: CommentTarget
readonly active: CommentTarget | null
}
| { readonly status: "disposed" }
export type CommentFocusEvent =
/** A view or a new comment asks for `target` to be revealed; `null` is a view's acknowledgement. */
| { readonly type: "focus.set"; readonly target: CommentTarget | null }
/** The user opened a comment from its composer chip: reveal it and mark it active. */
| { readonly type: "comment.opened"; readonly target: CommentTarget }
| { readonly type: "active.set"; readonly target: CommentTarget | null }
| { readonly type: "comment.removed"; readonly target: CommentTarget }
| { readonly type: "comments.reset" }
| { readonly type: "focus.timed-out"; readonly attempt: number }
| { readonly type: "disposed" }
export type CommentFocusEffect =
| { readonly type: "timer.start"; readonly attempt: number }
| { readonly type: "timer.clear" }
export type CommentFocusTransition = {
readonly state: CommentFocusState
readonly effects: readonly CommentFocusEffect[]
}
export const INITIAL_COMMENT_FOCUS_STATE: CommentFocusState = Object.freeze({
status: "idle",
attempt: 0,
active: null,
})
const NO_EFFECTS: readonly CommentFocusEffect[] = Object.freeze([])
const CLEAR_TIMER: readonly CommentFocusEffect[] = Object.freeze([{ type: "timer.clear" }])
export function transitionCommentFocus(state: CommentFocusState, event: CommentFocusEvent): CommentFocusTransition {
if (state.status === "disposed") return stay(state)
switch (event.type) {
case "disposed":
return { state: { status: "disposed" }, effects: state.status === "pending" ? CLEAR_TIMER : NO_EFFECTS }
case "focus.set":
if (!event.target) return settle(state, state.active)
if (state.status === "pending" && sameTarget(state.target, event.target)) return stay(state)
return request(state, event.target, state.active)
case "comment.opened":
if (state.status === "pending" && sameTarget(state.target, event.target)) {
if (sameTarget(state.active, event.target)) return stay(state)
return { state: { ...state, active: state.target }, effects: NO_EFFECTS }
}
return request(state, event.target, copy(event.target))
case "active.set":
if (sameTarget(state.active, event.target)) return stay(state)
return { state: { ...state, active: event.target && copy(event.target) }, effects: NO_EFFECTS }
case "comment.removed":
if (state.status !== "pending" || !sameTarget(state.target, event.target)) return stay(state)
return settle(state, state.active)
case "comments.reset":
if (state.status === "idle" && !state.active) return stay(state)
return settle(state, null)
case "focus.timed-out":
if (state.status !== "pending" || state.attempt !== event.attempt) return stay(state)
return settle(state, state.active)
}
}
/** The comment a view should reveal now, or `null`. */
export function commentFocusTarget(state: CommentFocusState) {
return state.status === "pending" ? state.target : null
}
/** The comment the composer marks as opened, or `null`. */
export function commentActiveTarget(state: CommentFocusState) {
return state.status === "disposed" ? null : state.active
}
function request(
state: Exclude<CommentFocusState, { status: "disposed" }>,
target: CommentTarget,
active: CommentTarget | null,
): CommentFocusTransition {
const attempt = state.attempt + 1
return {
state: { status: "pending", attempt, target: copy(target), active },
effects: [{ type: "timer.start", attempt }],
}
}
function settle(
state: Exclude<CommentFocusState, { status: "disposed" }>,
active: CommentTarget | null,
): CommentFocusTransition {
if (state.status === "idle" && state.active === active) return stay(state)
return {
state: { status: "idle", attempt: state.attempt, active },
effects: state.status === "pending" ? CLEAR_TIMER : NO_EFFECTS,
}
}
function stay(state: CommentFocusState): CommentFocusTransition {
return { state, effects: NO_EFFECTS }
}
function sameTarget(a: CommentTarget | null, b: CommentTarget | null) {
return a?.file === b?.file && a?.id === b?.id
}
// Callers pass objects they keep; the state holds its own copy.
function copy(target: CommentTarget): CommentTarget {
return { file: target.file, id: target.id }
}
+23 -1
View File
@@ -1,5 +1,6 @@
import { describe, expect, test } from "bun:test"
import { describe, expect, jest, test } from "bun:test"
import { createRoot } from "solid-js"
import { COMMENT_FOCUS_TIMEOUT_MS } from "./comment-focus-machine"
import { createCommentSessionForTest, type LineComment } from "./comments"
function line(file: string, id: string, time: number): LineComment {
@@ -63,6 +64,27 @@ describe("comments session indexing", () => {
})
})
test("an unanswered focus request expires", () => {
jest.useFakeTimers()
try {
createRoot((dispose) => {
const comments = createCommentSessionForTest({ "a.ts": [line("a.ts", "a1", 10)] })
comments.open({ file: "a.ts", id: "a1" })
jest.advanceTimersByTime(COMMENT_FOCUS_TIMEOUT_MS - 1)
expect(comments.focus()).toEqual({ file: "a.ts", id: "a1" })
jest.advanceTimersByTime(1)
expect(comments.focus()).toBeNull()
expect(comments.active()).toEqual({ file: "a.ts", id: "a1" })
dispose()
})
} finally {
jest.useRealTimers()
}
})
test.each(["replace", "clear"] as const)("%s resets comment state and focus", (action) => {
createRoot((dispose) => {
const comments = createCommentSessionForTest({
+46 -35
View File
@@ -1,4 +1,4 @@
import { batch, createMemo, createRoot, onCleanup } from "solid-js"
import { batch, createMemo, createRoot, createSignal, onCleanup, untrack } from "solid-js"
import { createStore, reconcile, type SetStoreFunction, type Store } from "solid-js/store"
import { createSimpleContext } from "@opencode/ui/context"
import { useParams } from "@solidjs/router"
@@ -10,12 +10,19 @@ import { createScopedCache } from "@/runtime/server/scoped-cache"
import { uuid } from "@opencode/util/uuid"
import type { SelectedLineRange } from "@/workspaces/files/model"
import { useWorkspaceLocation } from "@/workspaces/location"
import {
COMMENT_FOCUS_TIMEOUT_MS,
commentActiveTarget,
commentFocusTarget,
INITIAL_COMMENT_FOCUS_STATE,
transitionCommentFocus,
type CommentFocusEvent,
type CommentTarget,
} from "./comment-focus-machine"
import { CommentStore, type LineComment } from "./schema"
export type { LineComment } from "./schema"
type CommentFocus = { file: string; id: string }
const WORKSPACE_KEY = "__workspace__"
const MAX_COMMENT_SESSIONS = 20
@@ -80,13 +87,25 @@ function group(comments: LineComment[]) {
}
function createCommentSessionState(store: Store<CommentStore>, setStore: SetStoreFunction<CommentStore>) {
const [state, setState] = createStore<{
focus: CommentFocus | null
active: CommentFocus | null
}>({
focus: null,
active: null,
})
const [focusState, setFocusState] = createSignal(INITIAL_COMMENT_FOCUS_STATE)
let focusTimer: ReturnType<typeof setTimeout> | undefined
const dispatchFocus = (event: CommentFocusEvent) => {
const step = transitionCommentFocus(untrack(focusState), event)
setFocusState(step.state)
step.effects.forEach((effect) => {
clearTimeout(focusTimer)
focusTimer = undefined
if (effect.type !== "timer.start") return
focusTimer = setTimeout(
() => dispatchFocus({ type: "focus.timed-out", attempt: effect.attempt }),
COMMENT_FOCUS_TIMEOUT_MS,
)
})
}
onCleanup(() => dispatchFocus({ type: "disposed" }))
// Reuse the previous array when contents are unchanged so consumers keep a stable
// identity; a fresh array per call cascaded into diff annotation re-renders.
@@ -101,17 +120,6 @@ function createCommentSessionState(store: Store<CommentStore>, setStore: SetStor
return next
}
const setRef = (
key: "focus" | "active",
value: CommentFocus | null | ((value: CommentFocus | null) => CommentFocus | null),
) => setState(key, value)
const setFocus = (value: CommentFocus | null | ((value: CommentFocus | null) => CommentFocus | null)) =>
setRef("focus", value)
const setActive = (value: CommentFocus | null | ((value: CommentFocus | null) => CommentFocus | null)) =>
setRef("active", value)
const list = (file: string) => store.comments[file] ?? []
const add = (input: Omit<LineComment, "id" | "time">) => {
@@ -124,7 +132,7 @@ function createCommentSessionState(store: Store<CommentStore>, setStore: SetStor
batch(() => {
setStore("comments", input.file, (items) => [...(items ?? []), next])
setFocus({ file: input.file, id: next.id })
dispatchFocus({ type: "focus.set", target: { file: input.file, id: next.id } })
})
return next
@@ -133,7 +141,7 @@ function createCommentSessionState(store: Store<CommentStore>, setStore: SetStor
const remove = (file: string, id: string) => {
batch(() => {
setStore("comments", file, (items) => (items ?? []).filter((item) => item.id !== id))
setFocus((current) => (current?.file === file && current.id === id ? null : current))
dispatchFocus({ type: "comment.removed", target: { file, id } })
})
}
@@ -150,16 +158,14 @@ function createCommentSessionState(store: Store<CommentStore>, setStore: SetStor
const replace = (comments: LineComment[]) => {
batch(() => {
setStore("comments", reconcile(group(comments)))
setFocus(null)
setActive(null)
dispatchFocus({ type: "comments.reset" })
})
}
const clear = () => {
batch(() => {
setStore("comments", reconcile({}))
setFocus(null)
setActive(null)
dispatchFocus({ type: "comments.reset" })
})
}
@@ -171,12 +177,14 @@ function createCommentSessionState(store: Store<CommentStore>, setStore: SetStor
update,
replace,
clear,
focus: () => state.focus,
setFocus,
clearFocus: () => setRef("focus", null),
active: () => state.active,
setActive,
clearActive: () => setRef("active", null),
/** Marks `target` active and asks the view that shows it to reveal it. */
open: (target: CommentTarget) => dispatchFocus({ type: "comment.opened", target }),
focus: () => commentFocusTarget(focusState()),
setFocus: (target: CommentTarget | null) => dispatchFocus({ type: "focus.set", target }),
clearFocus: () => dispatchFocus({ type: "focus.set", target: null }),
active: () => commentActiveTarget(focusState()),
setActive: (target: CommentTarget | null) => dispatchFocus({ type: "active.set", target }),
clearActive: () => dispatchFocus({ type: "active.set", target: null }),
}
}
@@ -202,6 +210,7 @@ function createCommentSession(scope: ServerScope, dir: string, id: string | unde
update: session.update,
replace: session.replace,
clear: session.clear,
open: session.open,
focus: session.focus,
setFocus: session.setFocus,
clearFocus: session.clearFocus,
@@ -257,11 +266,13 @@ export const { use: useComments, provider: CommentsProvider } = createSimpleCont
update: (file: string, id: string, comment: string) => session().update(file, id, comment),
replace: (comments: LineComment[]) => session().replace(comments),
clear: () => session().clear(),
// Resolved at the call, so a request always lands on the session the user opened it in.
open: (target: CommentTarget) => session().open(target),
focus: () => session().focus(),
setFocus: (focus: CommentFocus | null) => session().setFocus(focus),
setFocus: (focus: CommentTarget | null) => session().setFocus(focus),
clearFocus: () => session().clearFocus(),
active: () => session().active(),
setActive: (active: CommentFocus | null) => session().setActive(active),
setActive: (active: CommentTarget | null) => session().setActive(active),
clearActive: () => session().clearActive(),
}
},
+78 -1
View File
@@ -1,5 +1,6 @@
import { expect, test } from "bun:test"
import { getCursorPosition, setCursorPosition } from "./dom"
import type { ComposerPrompt } from "../types"
import { editorMatchesPrompt, getCursorPosition, isEditorDomBlank, isPromptInlineBlank, setCursorPosition } from "./dom"
const br = () => document.createElement("br")
@@ -74,6 +75,82 @@ test("reads a caret on or inside a mention as before or after it", () => {
container.remove()
})
const part = (content: string) => ({ type: "text" as const, content, start: 0, end: 0 })
const filePart = { type: "file" as const, path: "src/a.ts", content: "@file", start: 0, end: 0 }
const attachment = { type: "path" as const, id: "att", filename: "a.png", mime: "image/png", path: "/tmp/a.png" }
const fileMention = () => {
const element = pill()
element.dataset.path = "src/a.ts"
return element
}
const editor = (...nodes: Node[]) => {
const element = document.createElement("div")
element.append(...nodes)
return element
}
const prompt = (...parts: ComposerPrompt): ComposerPrompt => parts
test.each<{ name: string; dom: () => HTMLElement; prompt: ComposerPrompt; matches: boolean }>([
{ name: "one text node", dom: () => editor(text("hello")), prompt: prompt(part("hello")), matches: true },
{
name: "split runs and breaks",
dom: () => editor(text("ab"), br(), text("cd")),
prompt: prompt(part("ab\ncd")),
matches: true,
},
{
name: "adjacent text parts",
dom: () => editor(text("abcd")),
prompt: prompt(part("ab"), part("cd")),
matches: true,
},
{
name: "a mention between text, with an attachment",
dom: () => editor(text("see "), fileMention(), text(" now")),
prompt: prompt(attachment, part("see "), filePart, part(" now")),
matches: true,
},
{
name: "an empty editor and an empty prompt",
dom: () => editor(),
prompt: prompt(part(""), attachment),
matches: true,
},
{ name: "the store cleared the text", dom: () => editor(text("!")), prompt: prompt(part("")), matches: false },
{ name: "different text", dom: () => editor(text("hello")), prompt: prompt(part("help!")), matches: false },
{
name: "a missing trailing part",
dom: () => editor(text("ab")),
prompt: prompt(part("ab"), filePart),
matches: false,
},
{
name: "a mention with another target",
dom: () => editor(fileMention()),
prompt: prompt({ ...filePart, path: "src/b.ts" }),
matches: false,
},
{ name: "a break where the prompt has text", dom: () => editor(br()), prompt: prompt(part("a")), matches: false },
])("matches the editor against the prompt: $name", (row) => {
expect(editorMatchesPrompt(row.dom(), row.prompt)).toBe(row.matches)
})
test("classifies blank editors and prompts the way the parser normalizes them", () => {
expect(isEditorDomBlank(editor(br(), text("\u200B\n")))).toBe(true)
expect(isEditorDomBlank(editor(text("a")))).toBe(false)
expect(isEditorDomBlank(editor(pill()))).toBe(false)
expect(isPromptInlineBlank(prompt(part(""), attachment))).toBe(true)
expect(isPromptInlineBlank(prompt(part(" ")))).toBe(false)
expect(isPromptInlineBlank(prompt(filePart))).toBe(false)
})
test("reads no caret for a range or a selection outside the editor", () => {
const container = document.createElement("div")
container.append(text("abcd"))
+150
View File
@@ -1,3 +1,153 @@
import { isAttachment } from "../prompt-parts"
import type { ComposerPrompt } from "../types"
// Where `editorMatchesPrompt` is in the prompt: the part and the characters of it already matched. Module state so
// the per-keystroke walk allocates nothing; the walk is synchronous, so calls never interleave.
let matchPart = 0
let matchOffset = 0
/**
* Whether the editor shows `prompt`'s inline parts, read the way `parseComposerEditor` reads the DOM: text runs
* (split or not), `<br>` as a line break, mention pills by kind, label and target, and other elements by their
* content. Attachments and empty text parts are ignored. Reads every part when it matches, so a caller in an effect
* tracks in-place store updates. Runs on every keystroke, so it allocates nothing.
*/
export function editorMatchesPrompt(editor: HTMLElement, prompt: ComposerPrompt) {
matchPart = 0
matchOffset = 0
for (let node = editor.firstChild; node; node = node.nextSibling) {
if (!matchNode(node, prompt)) return false
// The parser joins block children with a line break.
if (node.nextSibling && node instanceof HTMLElement && (node.tagName === "DIV" || node.tagName === "P"))
if (!matchText("\n", prompt)) return false
}
for (; matchPart < prompt.length; matchPart++, matchOffset = 0) {
const part = prompt[matchPart]!
if (!isAttachment(part) && part.content.length > matchOffset) return false
}
return true
}
/** Whether the editor holds nothing but line breaks and zero-width spaces, which the parser reads as empty. */
export function isEditorDomBlank(node: Node): boolean {
for (let child = node.firstChild; child; child = child.nextSibling) {
if (child instanceof Text) {
for (let index = 0; index < child.length; index++) {
const code = child.data.charCodeAt(index)
if (code !== 0x0a && code !== 0x200b) return false
}
continue
}
if (!(child instanceof HTMLElement)) continue
if (child.dataset.mention || (child.tagName !== "BR" && !isEditorDomBlank(child))) return false
}
return true
}
/** Whether `prompt` has no inline content: attachments only, or empty text. */
export function isPromptInlineBlank(prompt: ComposerPrompt) {
for (let index = 0; index < prompt.length; index++) {
const part = prompt[index]!
if (!isAttachment(part) && (part.type !== "text" || part.content.length > 0)) return false
}
return true
}
function matchNode(node: Node, prompt: ComposerPrompt): boolean {
if (node instanceof Text) return matchText(node.data, prompt)
if (!(node instanceof HTMLElement)) return true
if (node.dataset.mention) return matchMention(node, prompt)
if (node.tagName === "BR") return matchText("\n", prompt)
for (let child = node.firstChild; child; child = child.nextSibling) if (!matchNode(child, prompt)) return false
return true
}
function matchText(text: string, prompt: ComposerPrompt) {
let index = 0
while (index < text.length) {
const part = nextPart(prompt)
if (part?.type !== "text") return false
const length = Math.min(text.length - index, part.content.length - matchOffset)
// One native comparison covers a text node that lies inside one part, even a long draft.
const same =
index === 0 && length === text.length
? part.content.startsWith(text, matchOffset)
: sameChars(text, index, part.content, matchOffset, length)
if (!same) return false
index += length
matchOffset += length
}
return true
}
function matchMention(element: HTMLElement, prompt: ComposerPrompt) {
const part = nextPart(prompt)
if (!part || part.type === "text" || isAttachment(part) || matchOffset !== 0) return false
const kind = part.type === "file" && part.mime === "application/x-directory" ? "reference" : part.type
const label = element.firstChild instanceof Text && !element.firstChild.nextSibling ? element.firstChild.data : null
if (element.dataset.mention !== kind || (label ?? element.textContent) !== part.content) return false
if (part.type === "session" && element.title !== part.id) return false
if (part.type === "agent" && element.dataset.name !== part.name) return false
if (part.type === "skill" && (element.dataset.id !== part.id || element.dataset.name !== part.name)) return false
if (
part.type === "file" &&
(element.dataset.path !== part.path ||
element.dataset.mime !== (part.mime || undefined) ||
element.dataset.filename !== (part.filename || undefined))
)
return false
matchPart++
return true
}
function sameChars(a: string, aStart: number, b: string, bStart: number, length: number) {
for (let offset = 0; offset < length; offset++)
if (a.charCodeAt(aStart + offset) !== b.charCodeAt(bStart + offset)) return false
return true
}
// The part the next character belongs to, past attachments and fully matched text.
function nextPart(prompt: ComposerPrompt) {
for (; matchPart < prompt.length; matchPart++, matchOffset = 0) {
const part = prompt[matchPart]!
if (isAttachment(part)) continue
if (part.type !== "text" || part.content.length > matchOffset) return part
}
}
function getNodeLength(node: Node): number {
if (node instanceof Element && node.tagName === "BR") return 1
+26 -24
View File
@@ -45,7 +45,15 @@ import type {
ComposerSuggestion,
} from "../types"
import type { ComposerEditorModel, ComposerSelectControl } from "./interaction"
import { isAttachment } from "../prompt-parts"
import { isAttachment, promptLength } from "../prompt-parts"
import { editorMatchesPrompt, getCursorPosition, isEditorDomBlank, isPromptInlineBlank } from "./dom"
import {
INITIAL_EDITOR_SYNC_STATE,
INPUT_PARSED,
INPUT_PARSED_BLANK,
storeChanged,
transitionEditorSync,
} from "./machine"
import { QuoteCommentEditor } from "./quote-comment"
import "../attachments/attachments.css"
import "./editor.css"
@@ -158,11 +166,12 @@ export function ComposerEditor(props: ComposerEditorProps) {
scrollObserver.disconnect()
})
})
let localInput = false
let sync = INITIAL_EDITOR_SYNC_STATE
const updateCursor = () => {
if (!editor || !window.getSelection()?.isCollapsed) return
props.controller.onCursor(composerCursor(editor))
const cursor = editor && getCursorPosition(editor)
if (cursor !== undefined) props.controller.onCursor(cursor)
}
const mode = createMemo(() => state.mode)
@@ -177,14 +186,15 @@ export function ComposerEditor(props: ComposerEditorProps) {
const parts = props.controller.parts()
if (!editor) return
// The DOM already shows the user's own input and any update that leaves the text alone (an attachment), so
// neither rewrites it, which would move the caret and drop native undo. Each check reads every part, so an
// in-place store update runs this again.
const matches = editorMatchesPrompt(editor, parts)
const blank = !matches && isPromptInlineBlank(parts) && isEditorDomBlank(editor)
const step = transitionEditorSync(sync, storeChanged(matches, blank))
sync = step.state
if (localInput) {
localInput = false
return
}
renderComposerEditor(editor, parts)
if (step.render) renderComposerEditor(editor, parts)
})
// Kept out of JSX: an inline ternary prop compiles to a memo created on every read, and the popover reads
@@ -315,10 +325,13 @@ export function ComposerEditor(props: ComposerEditorProps) {
"text-align": "start",
}}
onInput={(event) => {
const cursor = composerCursor(event.currentTarget)
const prompt = parseComposerEditor(event.currentTarget)
const cursor = getCursorPosition(event.currentTarget) ?? promptLength(prompt)
const attachments = props.controller.parts().filter(isAttachment)
localInput = true
sync = transitionEditorSync(
sync,
event.currentTarget.firstChild && isPromptInlineBlank(prompt) ? INPUT_PARSED_BLANK : INPUT_PARSED,
).state
props.controller.onInput(
prompt.map((part) => part.content).join(""),
[...prompt, ...attachments],
@@ -696,17 +709,6 @@ function parseComposerEditor(editor: HTMLDivElement) {
return [{ type: "text" as const, content: "", start: 0, end: 0 }]
}
function composerCursor(editor: HTMLDivElement) {
const selection = window.getSelection()
if (!selection?.rangeCount || !editor.contains(selection.anchorNode)) return editor.textContent?.length ?? 0
const range = selection.getRangeAt(0).cloneRange()
range.selectNodeContents(editor)
range.setEnd(selection.anchorNode!, selection.anchorOffset)
return range.toString().length
}
function ComposerAttachments(props: {
attachments: ComposerAttachment[]
uploads?: Upload[]
@@ -0,0 +1,47 @@
import { expect, test } from "bun:test"
import {
INITIAL_EDITOR_SYNC_STATE,
INPUT_PARSED,
INPUT_PARSED_BLANK,
storeChanged,
transitionEditorSync,
type EditorSyncEvent,
type EditorSyncTransition,
} from "./machine"
function run(events: EditorSyncEvent[]) {
return events.reduce<EditorSyncTransition>((step, event) => transitionEditorSync(step.state, event), {
state: INITIAL_EDITOR_SYNC_STATE,
render: false,
})
}
test("typing `!` renders the shell-mode clear that arrives in the same flush as the keystroke", () => {
// The DOM shows `!` while the store holds the cleared prompt.
expect(run([INPUT_PARSED, storeChanged(false, false)]).render).toBe(true)
})
test("an input the store never echoed does not swallow the next external update", () => {
const typed = run([INPUT_PARSED])
expect(typed.render).toBe(false)
expect(transitionEditorSync(typed.state, storeChanged(false, false)).render).toBe(true)
})
test("the echo of a keystroke and an attachment edit leave the DOM alone", () => {
const echoed = run([INPUT_PARSED, storeChanged(true, false)])
expect(echoed).toEqual({ state: INITIAL_EDITOR_SYNC_STATE, render: false })
expect(transitionEditorSync(echoed.state, storeChanged(true, false))).toBe(echoed)
})
test("a blank echo keeps the user's line breaks once, and a later blank update renders", () => {
const blank = run([INPUT_PARSED_BLANK])
expect(blank.state.status).toBe("local-blank")
const echoed = transitionEditorSync(blank.state, storeChanged(false, true))
expect(echoed).toEqual({ state: INITIAL_EDITOR_SYNC_STATE, render: false })
expect(transitionEditorSync(echoed.state, storeChanged(false, true)).render).toBe(true)
})
test("typing text after a blank input returns to rendering every difference", () => {
expect(run([INPUT_PARSED_BLANK, INPUT_PARSED, storeChanged(false, true)]).render).toBe(true)
})
@@ -0,0 +1,63 @@
/**
* Whether a store change must render the prompt into the editable DOM. Runs on every keystroke, so states, events
* and results are frozen singletons.
* - `synced`: a store change renders whenever its inline parts differ from what the DOM shows.
* - `local-blank`: the user's input left only line breaks or zero-width spaces, which the parser reads as an empty
* prompt. The store's empty echo of that input keeps them, so Shift+Enter on an empty prompt and deleting its last
* character keep their line and native undo; any later empty update renders.
*/
export type EditorSyncState = { readonly status: "synced" } | { readonly status: "local-blank" }
export type EditorSyncEvent =
/** The user edited the DOM; `blank` when the parser normalized what is left to an empty prompt. */
| { readonly type: "input.parsed"; readonly blank: boolean }
/**
* The store's prompt changed. `matches` when the DOM already shows its inline parts; `blank` when both the DOM and
* the prompt are empty apart from line breaks and zero-width spaces.
*/
| { readonly type: "store.changed"; readonly matches: boolean; readonly blank: boolean }
export type EditorSyncTransition = {
readonly state: EditorSyncState
readonly render: boolean
}
const SYNCED: EditorSyncState = Object.freeze({ status: "synced" })
const LOCAL_BLANK: EditorSyncState = Object.freeze({ status: "local-blank" })
export const INITIAL_EDITOR_SYNC_STATE: EditorSyncState = SYNCED
export const INPUT_PARSED = Object.freeze({ type: "input.parsed", blank: false }) satisfies EditorSyncEvent
export const INPUT_PARSED_BLANK = Object.freeze({ type: "input.parsed", blank: true }) satisfies EditorSyncEvent
const STORE_MATCHES = Object.freeze({ type: "store.changed", matches: true, blank: false }) satisfies EditorSyncEvent
const STORE_BLANK = Object.freeze({ type: "store.changed", matches: false, blank: true }) satisfies EditorSyncEvent
const STORE_DIFFERS = Object.freeze({ type: "store.changed", matches: false, blank: false }) satisfies EditorSyncEvent
const STAY_SYNCED: EditorSyncTransition = Object.freeze({ state: SYNCED, render: false })
const STAY_LOCAL_BLANK: EditorSyncTransition = Object.freeze({ state: LOCAL_BLANK, render: false })
const RENDER: EditorSyncTransition = Object.freeze({ state: SYNCED, render: true })
/** The reused `store.changed` event for one comparison of the store's prompt with the DOM. */
export function storeChanged(matches: boolean, blank: boolean): EditorSyncEvent {
if (matches) return STORE_MATCHES
return blank ? STORE_BLANK : STORE_DIFFERS
}
export function transitionEditorSync(state: EditorSyncState, event: EditorSyncEvent): EditorSyncTransition {
if (event.type === "input.parsed") return event.blank ? STAY_LOCAL_BLANK : STAY_SYNCED
if (event.matches) return STAY_SYNCED
// The blank echo of the user's own input, consumed once.
if (state.status === "local-blank" && event.blank) return STAY_SYNCED
return RENDER
}
+3 -21
View File
@@ -483,7 +483,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue?
return
}
if (item?.type === "file") openComment(item, links, plugins.current(), files, comments)
if (item?.type === "file") openComment(item, links, plugins.current(), comments)
},
onEditor(element) {
// SAFETY: the editor's only `setEditor` call passes its editable root, a `<div>` (`editor/editor.tsx`).
@@ -655,31 +655,13 @@ function openComment(
item: { path: string; commentID?: string; commentOrigin?: "review" | "file" },
links: Links,
session: MountedSession | undefined,
files: ReturnType<typeof useFile>,
comments: ReturnType<typeof useComments>,
) {
if (!item.commentID) return
const focus = { file: item.path, id: item.commentID }
comments.setActive(focus)
const queueFocus = (attempts = 6) => {
requestAnimationFrame(() => {
comments.setFocus({ ...focus })
if (attempts <= 0) return
requestAnimationFrame(() => {
const current = comments.focus()
if (current?.file === focus.file && current.id === focus.id) queueFocus(attempts - 1)
})
})
}
// The plugin that owns the comment's origin reveals it (the review diff or a file tab), keeping the conversation.
// It opens first, so a preview it replaces unmounts before the request, which then waits for the view to answer.
links.open({ href: item.path, origin: item.commentOrigin, exact: true, background: true, session })
if (item.commentOrigin === "review") return queueFocus()
void Promise.resolve(files.load(item.path)).finally(() => queueFocus())
comments.open({ file: item.path, id: item.commentID })
}
function firstWord(query: string) {
@@ -26,6 +26,10 @@ export function useComments() {
setFocus(null)
setActive(null)
},
open(target: { file: string; id: string }) {
setActive(target)
setFocus(target)
},
focus,
setFocus,
active,