diff --git a/packages/app/e2e/regression/new-session.spec.ts b/packages/app/e2e/regression/new-session.spec.ts index 3d2a8cc820f..9d105439411 100644 --- a/packages/app/e2e/regression/new-session.spec.ts +++ b/packages/app/e2e/regression/new-session.spec.ts @@ -790,6 +790,45 @@ test("the title and message stay stable through worktree creation", async ({ pag await expect.poll(() => mock.calls).toEqual(["worktree", "session", "prompt"]) }) +test("the created session's composer keeps focus and a caret placed mid-draft", async ({ page }) => { + const mock = await openWorktreeDraft(page, pendingDraft) + const pending = await submitPending(page, mock) + await draftFollowUp(page) + // The start of the second line: not where focusing the editor alone would put the caret. + await editor(page).press("ControlOrMeta+End") + await editor(page).press("Home") + mock.worktree.resolve({ status: 200, json: { directory: workspace } }) + + await expect(page.locator("[data-session-title]").getByRole("heading", { level: 1 })).toHaveText( + "Created workspace session", + ) + await expect(pending.shimmer).toHaveCount(0) + await expect(editor(page)).toHaveText(followUp) + await expect(editor(page)).toBeFocused() + // Types into whatever holds focus, without focusing the editor again. + await page.keyboard.type("Also: ") + await expect(editor(page)).toHaveText(followUp.replace("\n", "\nAlso: ")) +}) + +test("a user who leaves the pending composer keeps focus there once the session is created", async ({ page }) => { + const mock = await openWorktreeDraft(page, pendingDraft) + const pending = await submitPending(page, mock) + await draftFollowUp(page) + await pending.shimmer.click() + await expect(editor(page)).not.toBeFocused() + mock.worktree.resolve({ status: 200, json: { directory: workspace } }) + + await expect(page.locator("[data-session-title]").getByRole("heading", { level: 1 })).toHaveText( + "Created workspace session", + ) + await expect(pending.shimmer).toHaveCount(0) + await expect(editor(page)).toHaveText(followUp) + await expect(submit(page)).toBeEnabled() + await expect(editor(page)).not.toBeFocused() + await expect.poll(() => mock.calls).toEqual(["worktree", "session", "prompt"]) + await expect(editor(page)).not.toBeFocused() +}) + for (const row of [ { failure: "worktree", followUp: true, calls: ["worktree"] }, { failure: "session", followUp: true, calls: ["worktree", "session"] }, diff --git a/packages/app/src/composer/editor/dom.test.ts b/packages/app/src/composer/editor/dom.test.ts index 2665526621d..d58601491cc 100644 --- a/packages/app/src/composer/editor/dom.test.ts +++ b/packages/app/src/composer/editor/dom.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test" -import { setCursorPosition } from "./dom" +import { getCursorPosition, setCursorPosition } from "./dom" const br = () => document.createElement("br") @@ -51,7 +51,41 @@ test.each<{ name: string; nodes: () => Node[]; caret: [number, number | null, nu const selection = window.getSelection() expect(selection?.anchorNode).toBe(child === null ? container : container.childNodes[child]!) expect(selection?.anchorOffset).toBe(offset) + expect(getCursorPosition(container)).toBe(position) }) container.remove() }) + +test("reads a caret on or inside a mention as before or after it", () => { + const container = document.createElement("div") + const mention = pill() + container.append(text("ab"), mention, br(), text("cd")) + document.body.appendChild(container) + const selection = window.getSelection()! + + selection.collapse(mention.firstChild, 0) + expect(getCursorPosition(container)).toBe(2) + selection.collapse(mention.firstChild, 3) + expect(getCursorPosition(container)).toBe(7) + selection.collapse(container.childNodes[2]!, 0) + expect(getCursorPosition(container)).toBe(7) + + container.remove() +}) + +test("reads no caret for a range or a selection outside the editor", () => { + const container = document.createElement("div") + container.append(text("abcd")) + const outside = text("outside") + document.body.append(container, outside) + const selection = window.getSelection()! + + selection.setBaseAndExtent(container.firstChild!, 1, container.firstChild!, 3) + expect(getCursorPosition(container)).toBeUndefined() + selection.collapse(outside, 2) + expect(getCursorPosition(container)).toBeUndefined() + + container.remove() + outside.remove() +}) diff --git a/packages/app/src/composer/editor/dom.ts b/packages/app/src/composer/editor/dom.ts index 7ff5e15c2e9..f293c922184 100644 --- a/packages/app/src/composer/editor/dom.ts +++ b/packages/app/src/composer/editor/dom.ts @@ -1,7 +1,52 @@ function getNodeLength(node: Node): number { - if (node.nodeType === Node.ELEMENT_NODE && (node as HTMLElement).tagName === "BR") return 1 + if (node instanceof Element && node.tagName === "BR") return 1 - return (node.textContent ?? "").replace(/\u200B/g, "").length + return textLength(node) +} + +// The node's text without zero-width spaces, like `textContent` but without building the string. +function textLength(node: Node): number { + if (node instanceof Text) return countText(node.data, node.length) + let length = 0 + + for (let child = node.firstChild; child; child = child.nextSibling) length += textLength(child) + + return length +} + +/** + * The collapsed caret's position in `parent`, counted the way `setCursorPosition` places it, or `undefined` when + * the selection is a range or lies outside `parent`. Runs on every `selectionchange`, so it allocates nothing. + */ +export function getCursorPosition(parent: HTMLElement) { + const selection = window.getSelection() + const anchor = selection?.anchorNode + + if (!selection?.isCollapsed || !anchor || !parent.contains(anchor)) return + const offset = selection.anchorOffset + let position = 0 + let index = 0 + + for (let node = parent.firstChild; node; node = node.nextSibling) { + if (anchor === parent && index === offset) return position + + if (node === anchor && node instanceof Text) return position + countText(node.data, offset) + + // Mentions and breaks are atomic: a caret on or inside one sits before or after it. + if (node.contains(anchor)) return offset === 0 ? position : position + getNodeLength(node) + position += getNodeLength(node) + index++ + } + + return position +} + +function countText(text: string, end: number) { + let count = 0 + + for (let index = 0; index < end; index++) if (text.charCodeAt(index) !== 0x200b) count++ + + return count } export function setCursorPosition(parent: HTMLElement, position: number) { @@ -11,8 +56,8 @@ export function setCursorPosition(parent: HTMLElement, position: number) { while (node) { const length = getNodeLength(node) const isText = node.nodeType === Node.TEXT_NODE - const isPill = node.nodeType === Node.ELEMENT_NODE && !!(node as HTMLElement).dataset.mention - const isBreak = node.nodeType === Node.ELEMENT_NODE && (node as HTMLElement).tagName === "BR" + const isPill = node instanceof HTMLElement && !!node.dataset.mention + const isBreak = node instanceof Element && node.tagName === "BR" if (isText && remaining <= length) { const range = document.createRange() diff --git a/packages/app/src/session/composer/controller.ts b/packages/app/src/session/composer/controller.ts index 6af67ebcfb7..85582106fe0 100644 --- a/packages/app/src/session/composer/controller.ts +++ b/packages/app/src/session/composer/controller.ts @@ -1,4 +1,4 @@ -import { createEffect, createMemo, on, onCleanup, type Accessor } from "solid-js" +import { createEffect, createMemo, createSignal, on, onMount, untrack, type Accessor } from "solid-js" import { useDialog } from "@opencode/ui/context/dialog" import type { ComposerControls } from "@/composer/adapter" import { setCursorPosition } from "@/composer/editor/dom" @@ -6,6 +6,8 @@ import { promptLength } from "@/composer/prompt-parts" import { createComposerModel } from "@/composer/model" import { useSettings } from "@/settings/model" import { createActiveComposerAdapter } from "./adapter" +import { useComposerFocus } from "./focus" +import { needsRealComposerFocus } from "./focus-machine" import { createSessionQueue } from "./queue" import { createSessionComposerRegionController } from "./session-composer-region-controller" @@ -17,8 +19,9 @@ export function createSessionComposerController(input: { }) { const settings = useSettings() const dialog = useDialog() + const focus = useComposerFocus(input.sessionID) const region = createSessionComposerRegionController(input.dock) - let editor: HTMLDivElement | undefined + const [editor, setEditor] = createSignal() const background = () => input.dock.state.background.steer(input.sessionID) @@ -29,7 +32,7 @@ export function createSessionComposerController(input: { submitted: region.onResponseSubmit, background, setEditor: (element) => { - editor = element + setEditor(element) region.setPromptRef(element) }, }) @@ -41,7 +44,7 @@ export function createSessionComposerController(input: { behavior: settings.general.followUpBehavior, background, restoreFocus: (cursor) => { - const target = editor + const target = editor() if (!target) return requestAnimationFrame(() => { @@ -52,33 +55,18 @@ export function createSessionComposerController(input: { }) const composer = createComposerModel(adapter, { queue }) - // This controller is recreated when a session becomes active. Wait for its draft and - // the editor's DOM commit, without reacting to subsequent cursor or message updates. - createEffect( - on(adapter.ready, (ready) => { - if (!ready) return - - const frame = requestAnimationFrame(() => { - if (!editor?.isConnected || !region.showComposer() || region.child() || dialog.active) return - const active = document.activeElement - - // A control chosen while the session was loading owns focus now. The tab link that opened the session - // passes focus on, unless it sits in a dialog, such as the mobile tabs drawer reopened before the composer. - if ( - active && - active !== document.body && - active !== editor && - (!active.matches("[data-titlebar-tab-link]") || active.closest('[role="dialog"]')) - ) - return - editor.focus({ preventScroll: true }) - setCursorPosition(editor, adapter.state.cursor() ?? promptLength(adapter.state.current())) - }) - - onCleanup(() => cancelAnimationFrame(frame)) - }), - ) const editable = createMemo(() => region.showComposer() && !region.child()) + // This controller is recreated when a session becomes active, which is when its composer takes focus + // (focus-machine.ts). It waits for the draft, the editor and any request dock or dialog to clear. + focus.bindReal({ target: () => input.sessionID, element: editor, editable }) + onMount(() => focus.dispatch({ type: "real.mounted", target: input.sessionID })) + createEffect(() => { + if (!needsRealComposerFocus(focus.state(), input.sessionID)) return + + if (!adapter.ready() || !editor() || !editable() || dialog.active) return + const cursor = untrack(() => adapter.state.cursor() ?? promptLength(adapter.state.current())) + focus.dispatch({ type: "real.ready", target: input.sessionID, cursor }) + }) // Requests hide the view without disposing its draft or queue edit. createEffect(on(editable, () => composer.clearDrag())) diff --git a/packages/app/src/session/composer/focus-machine.test.ts b/packages/app/src/session/composer/focus-machine.test.ts new file mode 100644 index 00000000000..359c7e7f6e5 --- /dev/null +++ b/packages/app/src/session/composer/focus-machine.test.ts @@ -0,0 +1,285 @@ +import { expect, test } from "bun:test" +import { + createComposerFocusState, + FOCUS_HANDOFF_TIMEOUT_MS, + needsRealComposerFocus, + REAL_FOCUS_RETRY_LIMIT, + transitionComposerFocus, + type ComposerFocusEffect, + type ComposerFocusEvent, + type ComposerFocusState, +} from "./focus-machine" + +const A = "ses_a" + +const B = "ses_b" + +// A frame or timer result answers the state it was started from, the way the driver fences them by attempt. +type Answer = { readonly answer: (state: ComposerFocusState) => ComposerFocusEvent } + +type Step = ComposerFocusEvent | Answer + +type Replay = { + readonly state: ComposerFocusState + readonly effects: readonly ComposerFocusEffect[] + readonly log: readonly ComposerFocusEffect[] +} + +function replay(steps: Step[], initial = createComposerFocusState()) { + const start: Replay = { state: initial, effects: [], log: [] } + + return steps.reduce((current, step) => { + const result = transitionComposerFocus(current.state, "answer" in step ? step.answer(current.state) : step) + + return { state: result.state, effects: result.effects, log: [...current.log, ...result.effects] } + }, start) +} + +const attempt = (state: ComposerFocusState) => (state.status === "disposed" ? -1 : state.attempt) + +const preparingFrame = (outcome: "focused" | "blocked"): Answer => ({ + answer: (state) => ({ type: "preparing.frame", attempt: attempt(state), outcome }), +}) + +const realFrame = (outcome: "focused" | "claimed" | "blocked"): Answer => ({ + answer: (state) => ({ type: "real.frame", attempt: attempt(state), outcome }), +}) + +const timeout: Answer = { answer: (state) => ({ type: "timeout", attempt: attempt(state) }) } + +// The user typed in the pending session's composer, which took focus on its first frame. +const typing: Step[] = [ + { type: "target.changed", target: A }, + { type: "preparing.mounted", target: A, cursor: 0 }, + preparingFrame("focused"), +] + +test("a session composer that mounts frames after the pending composer left takes its focus and caret", () => { + const handoff = replay([...typing, { type: "preparing.unmounted", target: A, cursor: 32 }]) + expect(handoff.state).toMatchObject({ status: "handoff", target: A, cursor: 32 }) + expect(handoff.effects).toEqual([]) + + // The route resolves the session and the request dock clears before the composer can take focus. + const mounted = replay([{ type: "real.mounted", target: A }], handoff.state) + expect(mounted.state).toMatchObject({ status: "pending-real", cursor: 32, retries: 0 }) + expect(mounted.effects).toEqual([ + { type: "timer.start", attempt: attempt(mounted.state), delayMs: FOCUS_HANDOFF_TIMEOUT_MS }, + ]) + expect(needsRealComposerFocus(mounted.state, A)).toBe(true) + + // The caret read from the pending editor wins over the stored cursor, which can lag behind it. + const ready = replay([{ type: "real.ready", target: A, cursor: 31 }], mounted.state) + expect(ready.effects).toEqual([ + { type: "timer.clear" }, + { type: "frame.real", target: A, attempt: attempt(ready.state), cursor: 32 }, + ]) + + const done = replay([realFrame("focused")], ready.state) + expect(done.state).toMatchObject({ status: "idle", target: A }) + expect(needsRealComposerFocus(done.state, A)).toBe(false) +}) + +test("a session created before the pending composer's first frame still hands focus over", () => { + const claiming = replay([ + { type: "target.changed", target: A }, + { type: "preparing.mounted", target: A, cursor: 4 }, + ]) + + expect(claiming.effects).toEqual([{ type: "frame.preparing", target: A, attempt: attempt(claiming.state), cursor: 4 }]) + const late = preparingFrame("focused").answer(claiming.state) + + const handoff = replay([{ type: "preparing.unmounted", target: A, cursor: 4 }], claiming.state) + expect(handoff.state).toMatchObject({ status: "handoff", cursor: 4 }) + expect(handoff.effects).toEqual([{ type: "frame.cancel" }]) + expect(transitionComposerFocus(handoff.state, late).state).toBe(handoff.state) +}) + +test("a user who left the pending composer keeps focus when the session composer replaces it", () => { + const declined = replay([ + ...typing, + { type: "preparing.blurred", target: A }, + { type: "preparing.unmounted", target: A, cursor: 4 }, + ]) + + expect(declined.state).toMatchObject({ status: "declined", target: A }) + + const mounted = replay([{ type: "real.mounted", target: A }], declined.state) + expect(mounted.state).toMatchObject({ status: "idle", target: A }) + expect(mounted.effects).toEqual([]) + expect(needsRealComposerFocus(mounted.state, A)).toBe(false) + expect(transitionComposerFocus(mounted.state, { type: "real.ready", target: A, cursor: 4 }).state).toBe(mounted.state) + + // Coming back to the session later opens it as usual. + const revisit = replay( + [ + { type: "target.changed", target: B }, + { type: "target.changed", target: A }, + { type: "real.mounted", target: A }, + ], + mounted.state, + ) + + expect(revisit.state).toMatchObject({ status: "pending-real", target: A, cursor: undefined }) +}) + +test("a control or dialog that holds focus on the pending composer's first frame counts as leaving it", () => { + const blocked = replay([ + { type: "target.changed", target: A }, + { type: "preparing.mounted", target: A, cursor: 0 }, + preparingFrame("blocked"), + { type: "preparing.unmounted", target: A, cursor: 0 }, + ]) + + expect(blocked.state).toMatchObject({ status: "declined" }) +}) + +test("returning to the pending composer before the session is created hands focus over again", () => { + const result = replay([ + ...typing, + { type: "preparing.blurred", target: A }, + { type: "preparing.focused", target: A }, + { type: "preparing.unmounted", target: A, cursor: 7 }, + ]) + + expect(result.state).toMatchObject({ status: "handoff", cursor: 7 }) +}) + +test("focusing the pending composer before its first frame cancels the frame", () => { + const result = replay([ + { type: "target.changed", target: A }, + { type: "preparing.mounted", target: A, cursor: 0 }, + { type: "preparing.focused", target: A }, + ]) + + expect(result.state).toMatchObject({ status: "preparing", focus: "focused" }) + expect(result.effects).toEqual([{ type: "frame.cancel" }]) +}) + +test("opening a session focuses its composer at the stored caret", () => { + const result = replay([ + { type: "target.changed", target: A }, + { type: "real.mounted", target: A }, + { type: "real.ready", target: A, cursor: 5 }, + ]) + + expect(result.effects).toEqual([ + { type: "timer.clear" }, + { type: "frame.real", target: A, attempt: attempt(result.state), cursor: 5 }, + ]) + + const claimed = replay([realFrame("claimed")], result.state) + expect(claimed.state).toMatchObject({ status: "idle", target: A }) + + // A remounted composer, such as after the mobile changes view, focuses again. + const remounted = replay([{ type: "real.mounted", target: A }], claimed.state) + expect(remounted.state).toMatchObject({ status: "pending-real", target: A }) +}) + +test("a composer hidden again before its frame waits again, up to the retry limit", () => { + const ready: Step[] = [{ type: "real.ready", target: A, cursor: 3 }] + + const opened = replay([ + { type: "target.changed", target: A }, + { type: "real.mounted", target: A }, + ...ready, + ]) + + const retried = Array.from({ length: REAL_FOCUS_RETRY_LIMIT }).reduce((state, _, index) => { + const result = replay([realFrame("blocked")], state) + expect(result.state).toMatchObject({ status: "pending-real", cursor: 3, retries: index + 1 }) + expect(result.effects).toEqual([ + { type: "timer.start", attempt: attempt(result.state), delayMs: FOCUS_HANDOFF_TIMEOUT_MS }, + ]) + + return replay(ready, result.state).state + }, opened.state) + + const result = replay([realFrame("blocked")], retried) + expect(result.state).toMatchObject({ status: "idle", target: A }) + expect(result.effects).toEqual([]) +}) + +test("a composer that never becomes focusable gives up at the timeout, ignoring stale timers", () => { + const waiting = replay([ + { type: "target.changed", target: A }, + { type: "real.mounted", target: A }, + ]) + + const stale = transitionComposerFocus(waiting.state, { type: "timeout", attempt: attempt(waiting.state) - 1 }) + expect(stale.state).toBe(waiting.state) + + const result = replay([timeout], waiting.state) + expect(result.state).toMatchObject({ status: "idle", target: A }) + expect(transitionComposerFocus(result.state, { type: "real.ready", target: A, cursor: 0 }).state).toBe(result.state) +}) + +test("stale frames from an earlier phase are ignored", () => { + const opened = replay([ + { type: "target.changed", target: A }, + { type: "real.mounted", target: A }, + { type: "real.ready", target: A, cursor: 0 }, + ]) + + const late = realFrame("focused").answer(opened.state) + const again = replay([realFrame("blocked"), { type: "real.ready", target: A, cursor: 0 }], opened.state) + expect(again.state).toMatchObject({ status: "focusing-real" }) + expect(transitionComposerFocus(again.state, late).state).toBe(again.state) +}) + +test("switching sessions cancels the previous session's frame and timer and ignores its late events", () => { + const claiming = replay([ + { type: "target.changed", target: A }, + { type: "preparing.mounted", target: A, cursor: 0 }, + ]) + + const late = preparingFrame("focused").answer(claiming.state) + + const switched = replay([{ type: "target.changed", target: B }], claiming.state) + expect(switched.state).toMatchObject({ status: "idle", target: B }) + expect(switched.effects).toEqual([{ type: "frame.cancel" }]) + const after = replay([late, { type: "preparing.unmounted", target: A, cursor: 0 }], switched.state) + expect(after.state).toBe(switched.state) + + const waiting = replay([{ type: "real.mounted", target: B }], switched.state) + expect(replay([{ type: "target.changed", target: A }], waiting.state).effects).toEqual([{ type: "timer.clear" }]) + + // The pending composer may unmount before or after the route reports the new session. + const unmountedFirst = replay( + [ + { type: "preparing.unmounted", target: A, cursor: 0 }, + { type: "target.changed", target: B }, + { type: "real.mounted", target: B }, + ], + claiming.state, + ) + + expect(unmountedFirst.state).toMatchObject({ status: "pending-real", target: B, cursor: undefined }) +}) + +test("disposal cancels pending work and ignores every later event", () => { + const waiting = replay([ + { type: "target.changed", target: A }, + { type: "real.mounted", target: A }, + ]) + + expect(replay([{ type: "disposed" }], waiting.state).effects).toEqual([{ type: "timer.clear" }]) + + const focusing = replay([{ type: "real.ready", target: A, cursor: 0 }], waiting.state) + const disposed = replay([{ type: "disposed" }], focusing.state) + expect(disposed.effects).toEqual([{ type: "frame.cancel" }]) + + const later = replay( + [ + { type: "target.changed", target: B }, + { type: "real.mounted", target: B }, + ], + disposed.state, + ) + + expect(later.state).toBe(disposed.state) + expect(later.log).toEqual([]) +}) + +test("each machine starts from its own state", () => { + expect(createComposerFocusState()).not.toBe(createComposerFocusState()) +}) diff --git a/packages/app/src/session/composer/focus-machine.ts b/packages/app/src/session/composer/focus-machine.ts new file mode 100644 index 00000000000..1d6284b152c --- /dev/null +++ b/packages/app/src/session/composer/focus-machine.ts @@ -0,0 +1,212 @@ +// How long a mounted session composer may wait to become focusable (draft loaded, no request dock or dialog) +// before it stops trying to take focus. +export const FOCUS_HANDOFF_TIMEOUT_MS = 10_000 + +// Frames that found the composer gone or hidden after it looked ready, before the attempt gives up. +export const REAL_FOCUS_RETRY_LIMIT = 3 + +export type PreparingFocus = "claiming" | "focused" | "blurred" + +// Focus for the routed session, across the pending session's composer and the session composer that replaces it. +// `target` is the routed session ID; the machine lives under one server, so the ID alone names the session. +// `attempt` advances on every phase change, so a late frame or timer from an earlier phase is ignored. +// +// - `idle`: nothing to do until a session composer mounts, which then takes focus (opening a session). +// - `preparing`: the pending session's composer is shown. `claiming` is its first focus frame in flight. +// - `handoff`: the pending composer unmounted while it held focus; the session composer takes focus and `cursor` when it mounts. +// - `declined`: the user had left the pending composer; the session composer that replaces it leaves focus alone. +// - `pending-real`: the session composer is mounted and waits until it can take focus. +// - `focusing-real`: its focus frame is in flight. +export type ComposerFocusState = + | { readonly status: "idle"; readonly target: string | undefined; readonly attempt: number } + | { readonly status: "preparing"; readonly target: string; readonly attempt: number; readonly focus: PreparingFocus } + | { readonly status: "handoff"; readonly target: string; readonly attempt: number; readonly cursor: number } + | { readonly status: "declined"; readonly target: string; readonly attempt: number } + | { + readonly status: "pending-real" + readonly target: string + readonly attempt: number + readonly cursor: number | undefined + readonly retries: number + } + | { + readonly status: "focusing-real" + readonly target: string + readonly attempt: number + readonly cursor: number + readonly retries: number + } + | { readonly status: "disposed" } + +export type ComposerFocusEvent = + | { readonly type: "target.changed"; readonly target: string } + | { readonly type: "preparing.mounted"; readonly target: string; readonly cursor: number } + | { readonly type: "preparing.frame"; readonly attempt: number; readonly outcome: "focused" | "blocked" } + | { readonly type: "preparing.focused"; readonly target: string } + | { readonly type: "preparing.blurred"; readonly target: string } + | { readonly type: "preparing.unmounted"; readonly target: string; readonly cursor: number } + | { readonly type: "real.mounted"; readonly target: string } + | { readonly type: "real.ready"; readonly target: string; readonly cursor: number } + | { readonly type: "real.frame"; readonly attempt: number; readonly outcome: "focused" | "claimed" | "blocked" } + | { readonly type: "timeout"; readonly attempt: number } + | { readonly type: "disposed" } + +export type ComposerFocusEffect = + | { readonly type: "frame.preparing"; readonly target: string; readonly attempt: number; readonly cursor: number } + | { readonly type: "frame.real"; readonly target: string; readonly attempt: number; readonly cursor: number } + | { readonly type: "frame.cancel" } + | { readonly type: "timer.start"; readonly attempt: number; readonly delayMs: number } + | { readonly type: "timer.clear" } + +export type ComposerFocusTransition = { + readonly state: ComposerFocusState + readonly effects: readonly ComposerFocusEffect[] +} + +type Active = Exclude + +const NO_EFFECTS: readonly ComposerFocusEffect[] = [] + +export function createComposerFocusState(): ComposerFocusState { + return { status: "idle", target: undefined, attempt: 0 } +} + +export function transitionComposerFocus(state: ComposerFocusState, event: ComposerFocusEvent): ComposerFocusTransition { + if (state.status === "disposed") return unchanged(state) + + if (event.type === "disposed") return { state: { status: "disposed" }, effects: cleanup(state) } + + if (event.type === "target.changed") { + if (event.target === state.target) return unchanged(state) + + return { state: { status: "idle", target: event.target, attempt: state.attempt + 1 }, effects: cleanup(state) } + } + + if (event.type === "preparing.frame") return preparingFrame(state, event) + + if (event.type === "real.frame") return realFrame(state, event) + + if (event.type === "timeout") { + if (state.status !== "pending-real" || state.attempt !== event.attempt) return unchanged(state) + + return changed({ status: "idle", target: state.target, attempt: state.attempt }) + } + + if (event.target !== state.target) return unchanged(state) + const target = event.target + const attempt = state.attempt + 1 + + if (event.type === "preparing.mounted") { + return changed({ status: "preparing", target, attempt, focus: "claiming" }, [ + ...cleanup(state), + { type: "frame.preparing", target, attempt, cursor: event.cursor }, + ]) + } + + if (event.type === "real.mounted") return realMounted(state, target) + + if (event.type === "real.ready") { + if (state.status !== "pending-real") return unchanged(state) + const cursor = state.cursor ?? event.cursor + + return changed({ status: "focusing-real", target, attempt, cursor, retries: state.retries }, [ + { type: "timer.clear" }, + { type: "frame.real", target, attempt, cursor }, + ]) + } + + if (state.status !== "preparing") return unchanged(state) + + if (event.type === "preparing.unmounted") { + // A user who left the composer while the session was created keeps focus where they put it. + if (state.focus === "blurred") return changed({ status: "declined", target, attempt }, cleanup(state)) + + // Claiming counts as focused: a session created before the first frame still hands focus over. + return changed({ status: "handoff", target, attempt, cursor: event.cursor }, cleanup(state)) + } + + const focus = event.type === "preparing.focused" ? "focused" : "blurred" + + if (state.focus === focus) return unchanged(state) + + return changed({ ...state, focus }, cleanup(state)) +} + +/** Whether the session composer for `target` is waiting to take focus. */ +export function needsRealComposerFocus(state: ComposerFocusState, target: string) { + return state.status === "pending-real" && state.target === target +} + +function preparingFrame( + state: Active, + event: Extract, +): ComposerFocusTransition { + if (state.status !== "preparing" || state.focus !== "claiming" || state.attempt !== event.attempt) { + return unchanged(state) + } + + // Another control or a dialog held focus, so the user is elsewhere. + return changed({ ...state, focus: event.outcome === "focused" ? "focused" : "blurred" }) +} + +function realFrame( + state: Active, + event: Extract, +): ComposerFocusTransition { + if (state.status !== "focusing-real" || state.attempt !== event.attempt) return unchanged(state) + + // The composer became ready, then disappeared or a dialog opened before the frame: wait for it again. + if (event.outcome === "blocked" && state.retries < REAL_FOCUS_RETRY_LIMIT) { + const attempt = state.attempt + 1 + + return changed( + { + status: "pending-real", + target: state.target, + attempt, + cursor: state.cursor, + retries: state.retries + 1, + }, + [{ type: "timer.start", attempt, delayMs: FOCUS_HANDOFF_TIMEOUT_MS }], + ) + } + + return changed({ status: "idle", target: state.target, attempt: state.attempt }) +} + +function realMounted(state: Active, target: string): ComposerFocusTransition { + const attempt = state.attempt + 1 + + if (state.status === "declined") return changed({ status: "idle", target, attempt }) + + if (state.status !== "idle" && state.status !== "handoff") return unchanged(state) + + return changed( + { + status: "pending-real", + target, + attempt, + cursor: state.status === "handoff" ? state.cursor : undefined, + retries: 0, + }, + [{ type: "timer.start", attempt, delayMs: FOCUS_HANDOFF_TIMEOUT_MS }], + ) +} + +function cleanup(state: Active): readonly ComposerFocusEffect[] { + if ((state.status === "preparing" && state.focus === "claiming") || state.status === "focusing-real") { + return [{ type: "frame.cancel" }] + } + + if (state.status === "pending-real") return [{ type: "timer.clear" }] + + return NO_EFFECTS +} + +function changed(state: ComposerFocusState, effects = NO_EFFECTS): ComposerFocusTransition { + return { state, effects } +} + +function unchanged(state: ComposerFocusState): ComposerFocusTransition { + return { state, effects: NO_EFFECTS } +} diff --git a/packages/app/src/session/composer/focus.tsx b/packages/app/src/session/composer/focus.tsx new file mode 100644 index 00000000000..c59a609628a --- /dev/null +++ b/packages/app/src/session/composer/focus.tsx @@ -0,0 +1,156 @@ +import { + createComputed, + createContext, + createSignal, + onCleanup, + untrack, + useContext, + type Accessor, + type ParentProps, +} from "solid-js" +import { useDialog } from "@opencode/ui/context/dialog" +import { setCursorPosition } from "@/composer/editor/dom" +import { + createComposerFocusState, + transitionComposerFocus, + type ComposerFocusEffect, + type ComposerFocusEvent, +} from "./focus-machine" + +// A composer that can take focus for one session: the pending session's composer or the session composer. +type ComposerSurface = { + target: Accessor + element: Accessor + editable?: Accessor +} + +export type ComposerFocus = ReturnType + +const ComposerFocusContext = createContext() + +// One machine for the session route, so focus outlives the pending composer until the session composer mounts. +export function ComposerFocusProvider(props: ParentProps<{ sessionID: string }>) { + const focus = createComposerFocus() + + // A computation, not an effect: the target changes before the new session's composers mount and report to it. + createComputed(() => focus.dispatch({ type: "target.changed", target: props.sessionID })) + + return {props.children} +} + +// Outside the session route (stories), a session composer focuses itself as it does when a session opens. +export function useComposerFocus(sessionID: string) { + const routed = useContext(ComposerFocusContext) + + if (routed) return routed + const focus = createComposerFocus() + focus.dispatch({ type: "target.changed", target: sessionID }) + + return focus +} + +// The tab link that opened the session passes focus on, unless it sits in a dialog, such as the mobile tabs drawer +// reopened before the composer. +export function isTitlebarTabLink(element: Element) { + return element.matches("[data-titlebar-tab-link]") && !element.closest('[role="dialog"]') +} + +function createComposerFocus() { + const dialog = useDialog() + const [state, setState] = createSignal(createComposerFocusState()) + let frame: number | undefined + let timer: ReturnType | undefined + let preparing: ComposerSurface | undefined + let real: ComposerSurface | undefined + + const dispatch = (event: ComposerFocusEvent) => { + const previous = untrack(state) + const result = transitionComposerFocus(previous, event) + + if (result.state === previous) return + setState(result.state) + result.effects.forEach(run) + } + + const run = (effect: ComposerFocusEffect) => { + if (effect.type === "frame.cancel") return cancelFrame() + + if (effect.type === "timer.clear") return clearTimer() + + if (effect.type === "timer.start") { + clearTimer() + timer = setTimeout(() => { + timer = undefined + dispatch({ type: "timeout", attempt: effect.attempt }) + }, effect.delayMs) + + return + } + + cancelFrame() + // One frame after mounting, so the editor's content and the outgoing composer's DOM have settled. + frame = requestAnimationFrame(() => { + frame = undefined + + if (effect.type === "frame.real") { + dispatch({ type: "real.frame", attempt: effect.attempt, outcome: focusSurface(real, effect) }) + + return + } + + const outcome = focusSurface(preparing, effect) === "focused" ? "focused" : "blocked" + dispatch({ type: "preparing.frame", attempt: effect.attempt, outcome }) + }) + } + + const focusSurface = ( + surface: ComposerSurface | undefined, + effect: { target: string; cursor: number }, + ): "focused" | "claimed" | "blocked" => { + const element = surface?.target() === effect.target ? surface.element() : undefined + + if (!element?.isConnected || surface?.editable?.() === false || dialog.active) return "blocked" + const active = document.activeElement + + // The user already put the caret in this composer. + if (active && element.contains(active)) return "focused" + + // A control chosen while the session was loading owns focus now. + if (active && active !== document.body && !isTitlebarTabLink(active)) return "claimed" + element.focus({ preventScroll: true }) + setCursorPosition(element, effect.cursor) + + return "focused" + } + + const cancelFrame = () => { + if (frame === undefined) return + cancelAnimationFrame(frame) + frame = undefined + } + + const clearTimer = () => { + if (timer === undefined) return + clearTimeout(timer) + timer = undefined + } + + onCleanup(() => dispatch({ type: "disposed" })) + + return { + state, + dispatch, + bindPreparing(surface: ComposerSurface) { + preparing = surface + onCleanup(() => { + if (preparing === surface) preparing = undefined + }) + }, + bindReal(surface: ComposerSurface) { + real = surface + onCleanup(() => { + if (real === surface) real = undefined + }) + }, + } +} diff --git a/packages/app/src/session/preparing-composer.tsx b/packages/app/src/session/preparing-composer.tsx index 26cc148f0d8..70329f33f5f 100644 --- a/packages/app/src/session/preparing-composer.tsx +++ b/packages/app/src/session/preparing-composer.tsx @@ -1,45 +1,62 @@ -import { createEffect, on, onCleanup } from "solid-js" -import { useLocation } from "@solidjs/router" +import { createEffect, createSignal, on, onCleanup } from "solid-js" +import { makeEventListener } from "@solid-primitives/event-listener" import { ComposerEditor } from "@/composer/editor/editor" -import { setCursorPosition } from "@/composer/editor/dom" +import { getCursorPosition } from "@/composer/editor/dom" import { createComposerEditor } from "@/composer/editor/interaction" +import { promptLength } from "@/composer/prompt-parts" import type { PendingSession } from "@/shell/tabs/tabs" +import { isTitlebarTabLink, useComposerFocus } from "./composer/focus" -export function PreparingComposer(props: { pending: PendingSession }) { - const location = useLocation() - let element: HTMLElement | undefined +export function PreparingComposer(props: { sessionID: string; pending: PendingSession }) { + const focus = useComposerFocus(props.sessionID) + const [element, setElement] = createSignal() const editor = createComposerEditor({ store: () => props.pending.composer.store, commands: () => [], context: () => [], searchContextFiles: () => [], - onEditor: (value) => { - element = value - }, + onEditor: setElement, view: { draftOnly: true, submit: { stopping: () => false, onSubmit() {}, onStop() {} }, }, }) + focus.bindPreparing({ target: () => props.sessionID, element }) + + createEffect(() => { + const el = element() + + if (!el) return + makeEventListener(el, "focusin", () => focus.dispatch({ type: "preparing.focused", target: props.sessionID })) + makeEventListener(el, "focusout", (event) => { + // Removing the editor, or the window losing focus, is not the user leaving it. + if (!el.isConnected || !document.hasFocus() || document.activeElement === el) return + + if (event.relatedTarget instanceof Element && isTitlebarTabLink(event.relatedTarget)) return + focus.dispatch({ type: "preparing.blurred", target: props.sessionID }) + }) + // The editor stores the caret only on input, key up and pointer up. Keep it current while a key is held, so + // the draft that moves into the created session carries the caret. + makeEventListener(document, "selectionchange", () => { + if (document.activeElement !== el) return + const cursor = getCursorPosition(el) + + if (cursor !== undefined && cursor !== props.pending.composer.cursor()) editor.onCursor(cursor) + }) + }) + createEffect( on( () => props.pending, (pending) => { - const pathname = location.pathname - editor.restoreFocus(pending.composer.cursor()) + const target = props.sessionID + const cursor = () => pending.composer.cursor() ?? promptLength(pending.composer.current()) + focus.dispatch({ type: "preparing.mounted", target, cursor: cursor() }) onCleanup(() => { - if (document.activeElement !== element) return - const cursor = pending.composer.cursor() - requestAnimationFrame(() => { - if (location.pathname !== pathname) return - const next = document.querySelector('[data-component="composer-editor"]') - - if (!next || next === element) return - next.focus() - setCursorPosition(next, cursor ?? 0) - }) + const el = element() + focus.dispatch({ type: "preparing.unmounted", target, cursor: (el && getCursorPosition(el)) ?? cursor() }) }) }, ), diff --git a/packages/app/src/session/route.tsx b/packages/app/src/session/route.tsx index bf48519da88..d4d64f1f010 100644 --- a/packages/app/src/session/route.tsx +++ b/packages/app/src/session/route.tsx @@ -33,6 +33,7 @@ import { sessionRouteView } from "./resolution-machine" import { createSessionResolution } from "./session-resolution" import { SessionScreenView } from "./screen" import { PreparingComposer } from "./preparing-composer" +import { ComposerFocusProvider } from "./composer/focus" export function TargetSessionRouteContent() { const params = useParams<{ serverKey: string; id: string }>() @@ -48,9 +49,11 @@ export function TargetSessionRouteContent() { - }> - {(pending) => } - + + }> + {(pending) => } + + @@ -96,7 +99,7 @@ function PreparingSession(props: { sessionID: string; pending: PendingSession }) - + )