feat(app): add a touch dock to the mobile composer (#61773)

This commit is contained in:
Luke Parker
2026-11-04 14:37:38 -06:00
committed by GitHub
Unverified
parent ca545df43e
commit bbf71d6205
8 changed files with 666 additions and 66 deletions
@@ -892,6 +892,68 @@ test("keeps a line added at the end of a scrolling prompt clear of the bottom fa
.toBe(0)
})
test("Enter that confirms an IME candidate never sends, even after Safari's early compositionend", async ({ page }) => {
const prompts: Parameters<NonNullable<MockServerConfig["onPrompt"]>>[0]["body"][] = []
const view = await openSession(page, { name: "ComposerImeEnter", onPrompt: (input) => void prompts.push(input.body) })
const enter = (keyCode: number) =>
view.editor.evaluate(
(element, keyCode) =>
element.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", keyCode, bubbles: true, cancelable: true })),
keyCode,
)
await view.editor.fill("にほん")
// Safari delivers the confirming Enter after compositionend, so isComposing is false and only keyCode marks it.
await enter(229)
await expect(view.editor).toHaveText("にほん")
await enter(13)
await expect.poll(() => prompts.map((body) => body.text)).toEqual(["にほん"])
})
test.describe("touch keyboard", () => {
test.use({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true })
test("Return only adds a line, even over suggestions; the touch bar and Cmd+Return send", async ({ page }) => {
const prompts: Parameters<NonNullable<MockServerConfig["onPrompt"]>>[0]["body"][] = []
const view = await openSession(page, {
name: "ComposerTouchReturn",
onPrompt: (input) => void prompts.push(input.body),
})
const bar = page.locator('[data-slot="composer-touch-bar"]')
await expect(bar).toBeVisible()
await expect(page.locator('[data-action="composer-attach"]')).toHaveCount(0)
await expect(view.editor).toHaveAttribute("enterkeyhint", "enter")
await view.editor.fill("/model")
await expect(page.locator('[data-suggestion-id="model.choose"]')).toHaveAttribute("data-active", "")
await view.editor.press("Enter")
await expect(page.locator('[data-component="composer-suggestions"]')).toBeHidden()
await expect.poll(() => view.editor.innerText()).toMatch(/^\/model\n/)
await expect(page.getByRole("dialog", { name: "Select model", exact: true })).toBeHidden()
await view.editor.fill("first line")
await view.editor.press("Enter")
await view.editor.pressSequentially("second line")
await expect.poll(() => view.editor.innerText()).toBe("first line\nsecond line")
expect(prompts).toEqual([])
await bar.getByRole("button", { name: "Send", exact: true }).tap()
await expect.poll(() => prompts.map((body) => body.text)).toEqual(["first line\nsecond line"])
await expect(view.editor).toBeEmpty()
// A hardware keyboard, as on an iPad, still sends with Cmd+Return.
await view.editor.fill("from the iPad keyboard")
await view.editor.press("ControlOrMeta+Enter")
await expect
.poll(() => prompts.map((body) => body.text))
.toEqual(["first line\nsecond line", "from the iPad keyboard"])
})
})
test("a key-up never moves the caret back after later navigation", async ({ page }) => {
const input = await draft(page)
await input.pressSequentially("first line")
@@ -16,6 +16,9 @@ for (const { width, direction } of [
const editor = page.getByRole("textbox", { name: "Prompt", exact: true })
await expect(editor).toBeEditable()
// A narrow window with a mouse is not a phone: it keeps the desktop toolbar and Enter to send.
await expect(page.locator('[data-action="composer-attach"]')).toBeVisible()
await expect(page.locator('[data-slot="composer-touch-bar"]')).toHaveCount(0)
await editor.fill("Please check focus after sending.")
await expect(editor).toBeFocused()
@@ -49,6 +52,12 @@ test.describe("touch submission", () => {
await editor.fill("Please dismiss the keyboard after sending.")
await expect(editor).toBeFocused()
// With the titlebar at the bottom, the touch bar still sits on the bottom edge, where the keyboard opens.
const titlebar = (await page.locator('[data-slot="titlebar-v2"]').boundingBox())!
const bar = (await page.locator('[data-slot="composer-touch-bar"]').boundingBox())!
expect(bar.y).toBeGreaterThanOrEqual(titlebar.y + titlebar.height)
const admitted = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
@@ -732,7 +732,8 @@ for (const device of ["Pixel 7", "iPhone 13"]) {
timestamp: restingTimestamp(),
})
for (let step = 1; step <= 23; step++)
// Far enough that the delayed image above the anchor comes back into the mounted window.
for (let step = 1; step <= 25; step++)
await devtools.send("Input.dispatchTouchEvent", {
type: "touchMove",
touchPoints: [{ x: point.x, y: point.y + step * 30 }],
@@ -767,7 +768,7 @@ for (const device of ["Pixel 7", "iPhone 13"]) {
await expect(hidden).toHaveCount(1)
}
const anchor = page.getByText(detach === "scroll" ? "Part 48." : "Reading 20.", { exact: true })
const anchor = page.getByText(detach === "scroll" ? "Part 50." : "Reading 20.", { exact: true })
await expect(anchor).toBeInViewport()
const before = await anchor.evaluate((element) => element.getBoundingClientRect().top)
image.resolve()
@@ -260,6 +260,50 @@ test("a blank Enter leaves the running session alone while Stop still interrupts
expect(mock.prompts).toEqual([])
})
test.describe("touch keyboard", () => {
test.use({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true })
test("the touch bar stops, queues and steers a running session while Return only adds a line", async ({ page }) => {
const mock = createQueueMock([])
const view = await openQueue(page, mock, "steer")
const bar = page.locator('[data-slot="composer-touch-bar"]')
const stop = bar.getByRole("button", { name: "Stop", exact: true })
const interrupted = page.waitForRequest((request) =>
new URL(request.url()).pathname.endsWith(`/${sessionID}/interrupt`),
)
await stop.tap()
await interrupted
await view.input.fill("check the logs")
await expect(stop).toHaveCount(0)
await view.input.press("Enter")
await view.input.pressSequentially("then the tests")
expect(mock.prompts).toEqual([])
await bar.getByRole("button", { name: "Queue", exact: true }).tap()
await expect
.poll(() => mock.prompts.map((prompt) => [prompt.delivery, prompt.text]))
.toEqual([["queue", "check the logs\nthen the tests"]])
await view.input.fill("use the staging database")
await bar.getByRole("button", { name: "Steer", exact: true }).tap()
await expect
.poll(() => mock.prompts.map((prompt) => [prompt.delivery, prompt.text]))
.toEqual([
["queue", "check the logs\nthen the tests"],
["steer", "use the staging database"],
])
await expect(view.input).toBeEmpty()
// Editing a queued prompt: the primary action puts it back in the queue, the other steers it.
await view.rows.filter({ hasText: "check the logs" }).locator('[data-action="session-queue-edit"]').tap()
await expect(view.input).toHaveText(/check the logs/)
await expect(bar.locator('[data-action="composer-alternate-delivery"]')).toHaveText("Steer")
await expect(bar.locator('[data-action="composer-submit"]')).toHaveText("Queue")
})
})
test("a steer shows as pending in the timeline as the composer clears, before the server admits it", async ({
page,
}) => {
@@ -0,0 +1,283 @@
import { For, Show, createMemo, onCleanup, onMount } from "solid-js"
import { createStore } from "solid-js/store"
import type { ModelSelection } from "@/providers/models/selection"
import { STORY_MODEL } from "@opencode/session-ui/storybook"
import { Composer } from "./composer"
import type { ComposerModel } from "./model"
import { createComposerEditor, createComposerEditorState } from "./editor/interaction"
import type { ComposerPersistedState, ComposerSuggestion } from "./types"
import { promptLength } from "./prompt-parts"
// Every state of the real composer on a phone. On a touch device the composer shows its touch bar and Return only
// adds a line; anywhere else the same page shows the desktop toolbar, which is the point.
const states = [
{ id: "new-empty", name: "New session, empty" },
{ id: "new-draft", name: "New session, draft" },
{ id: "idle-draft", name: "Idle session, draft" },
{ id: "working", name: "Working, empty (Stop)" },
{ id: "steer", name: "Working + draft, steer first" },
{ id: "queue", name: "Working + draft, queue first" },
{ id: "editing", name: "Editing a queued prompt" },
{ id: "shell", name: "Shell command" },
{ id: "sending", name: "Sending" },
{ id: "suggestions", name: "Slash suggestions open" },
] as const
type State = (typeof states)[number]["id"]
const drafts: Record<State, string> = {
"new-empty": "",
"new-draft": "Add a touch bar to the composer",
"idle-draft": "Now run the focused tests",
working: "",
steer: "Also post the PR link in the thread",
queue: "After that, update the changelog",
editing: "Rename the flag before merging",
shell: "bun test composer",
sending: "Ship it",
suggestions: "",
}
const selectedModel = {
id: STORY_MODEL.id,
providerID: STORY_MODEL.providerID,
api: { id: STORY_MODEL.id, url: "https://opencode.ai", npm: "@ai-sdk/anthropic" },
name: "Claude Opus 5.5",
family: "claude-opus",
capabilities: {
temperature: true,
reasoning: true,
attachment: true,
toolcall: true,
input: { text: true, audio: false, image: true, video: false, pdf: true },
output: { text: true, audio: false, image: false, video: false, pdf: false },
interleaved: true,
},
cost: { input: 3, output: 15, cache: { read: 0.3, write: 3.75 } },
limit: { context: 200_000, output: 64_000 },
status: "active",
options: {},
headers: {},
release_date: "2026-05-22",
variants: { medium: {}, high: {} },
provider: { id: STORY_MODEL.providerID, name: "OpenCode", source: "custom", env: [], options: {}, models: {} },
latest: true,
} satisfies NonNullable<ReturnType<ModelSelection["current"]>>
const commands: ComposerSuggestion[] = [
{ id: "command.review", kind: "command", label: "/review", trigger: "review", title: "Review changes" },
{ id: "command.test", kind: "command", label: "/test", trigger: "test", title: "Run tests" },
{ id: "command.compact", kind: "command", label: "/compact", trigger: "compact", title: "Compact the session" },
]
const context: ComposerSuggestion[] = [
{
id: "file:src/composer/editor/editor.tsx",
kind: "file",
label: "src/composer/editor/editor.tsx",
path: "src/composer/editor/editor.tsx",
mention: {
type: "file",
path: "src/composer/editor/editor.tsx",
content: "@src/composer/editor/editor.tsx",
start: 0,
end: 0,
},
},
]
const text = (content: string): ComposerPersistedState["prompt"] => [
{ type: "text", content, start: 0, end: content.length },
]
function TouchComposer(props: { state: State }) {
const working = ["working", "steer", "queue", "editing"].includes(props.state)
const [session, setSession] = createStore<{ working: boolean; fresh: boolean; log: string[]; variant: string }>({
working,
fresh: props.state.startsWith("new"),
log: [],
variant: "high",
})
const prompt = text(drafts[props.state])
const [draft, setDraft] = createStore<ComposerPersistedState>({
prompt,
cursor: promptLength(prompt),
model: { providerID: STORY_MODEL.providerID, modelID: STORY_MODEL.id, variant: "high" },
context: { items: [] },
})
const blank = () => !draft.prompt.some((part) => "content" in part && part.content.trim())
const record = (entry: string) => setSession("log", (log) => [...log, entry])
const queue = {
count: () => (props.state === "editing" ? 1 : 0),
undoing: () => false,
delivery: () => (props.state === "queue" ? ("queue" as const) : ("steer" as const)),
alternate: () => (props.state === "queue" ? ("steer" as const) : ("queue" as const)),
editing: () => (props.state === "editing" ? "inb_story_editing" : undefined),
confirmEdit: (delivery: "steer" | "queue") => record(`Edited queued prompt, ${delivery}`),
cancelEdit: () => record("Cancelled the edit"),
editFirst: () => false,
}
const editor = createComposerEditor({
store: [draft, setDraft],
state: createComposerEditorState(props.state === "shell" ? "shell" : "normal"),
commands: () => commands,
context: () => context,
searchContextFiles: () => context,
view: {
placeholder: () =>
session.working
? "Add follow-up, / for commands, @ for context…"
: "Ask anything, / for commands, @ for context…",
variant: {
options: () => [
{ id: "default", label: "default" },
{ id: "medium", label: "Medium" },
{ id: "high", label: "High" },
],
current: () => session.variant,
onSelect: (variant) => setSession("variant", variant),
},
submit: {
stopping: () => session.working && blank(),
working: () => session.working,
busy: () => props.state === "sending",
get queue() {
return session.working ? queue : undefined
},
onSubmit: (options) => {
const value = draft.prompt.map((part) => ("content" in part ? part.content : "")).join("")
const delivery = session.working ? (options?.alternate ? queue.alternate() : queue.delivery()) : "send"
record(`${delivery}: ${value}`)
setDraft({ prompt: text(""), cursor: 0 })
setSession({ fresh: false, working: true })
},
onStop: () => {
record("Stop: interrupted the session")
setSession("working", false)
},
},
},
})
const selection = {
ready: Object.assign(() => true, { promise: undefined }),
key: () => ({ providerID: selectedModel.provider.id, modelID: selectedModel.id }),
current: () => selectedModel,
recent: () => [selectedModel],
favorite: { list: () => [], toggle() {} },
list: () => [selectedModel],
cycle() {},
set() {},
visible: () => true,
setVisibility() {},
variant: {
configured: () => "high",
selected: () => session.variant,
current: () => session.variant,
list: () => ["medium", "high"],
set: (variant: string | undefined) => setSession("variant", variant ?? "high"),
cycle() {},
},
} satisfies ModelSelection
const model = { ...editor, model: { selection, paid: true, loading: false } } satisfies ComposerModel
onMount(() => props.state === "suggestions" && editor.openCommands())
return (
<>
<div class="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-4 py-3" data-scrollable>
<Show
when={!session.fresh}
fallback={<p class="m-auto text-14-regular text-v2-text-text-faint">New session · opencode / dev</p>}
>
<p class="text-14-regular text-v2-text-text-base">
Recorded the session-layer split as deferred, so it won't come up again as an open question.
</p>
<div class="self-end max-w-[80%] rounded-2xl bg-v2-background-bg-layer-02 px-3.5 py-2.5 text-14-regular">
Keep that slack thread updated as PRs are merged
</div>
</Show>
<For each={session.log}>
{(entry) => (
<output class="self-end max-w-[80%] whitespace-pre-wrap rounded-2xl border border-v2-border-border-base px-3.5 py-2.5 text-13-regular text-v2-text-text-muted">
{entry}
</output>
)}
</For>
<Show when={session.working}>
<span class="text-13-regular text-v2-text-text-faint">Working…</span>
</Show>
</div>
<div class="shrink-0 px-2 pb-2">
<Composer model={model} borderUnderlay />
</div>
</>
)
}
function TouchStates(props: { state: State }) {
const [view, setView] = createStore({ state: props.state, generation: 0 })
const touch = matchMedia("(hover: none) and (pointer: coarse)")
const [device, setDevice] = createStore({ touch: touch.matches })
const sync = () => setDevice("touch", touch.matches)
touch.addEventListener("change", sync)
onCleanup(() => touch.removeEventListener("change", sync))
const key = createMemo(() => `${view.state}:${view.generation}`)
return (
<div
data-component="composer-touch-states"
class="flex h-dvh flex-col bg-v2-background-bg-deep text-v2-text-text-base"
style={{ "max-width": "430px", margin: "0 auto" }}
>
<header class="flex shrink-0 items-center gap-2 border-b border-v2-border-border-base px-3 py-2">
<select
aria-label="Composer state"
class="h-9 min-w-0 flex-1 rounded-md border border-v2-border-border-base bg-v2-background-bg-base px-2 text-14-regular"
value={view.state}
onChange={(event) => {
const next = states.find((state) => state.id === event.currentTarget.value)
if (next) setView({ state: next.id, generation: view.generation + 1 })
}}
>
<For each={states}>{(state) => <option value={state.id}>{state.name}</option>}</For>
</select>
<button
type="button"
class="h-9 rounded-md border border-v2-border-border-base px-3 text-14-regular"
onClick={() => setView("generation", view.generation + 1)}
>
Reset
</button>
<span data-slot="touch-device" class="font-mono text-12-regular text-v2-text-text-faint">
{device.touch ? "touch" : "mouse"}
</span>
</header>
<Show keyed when={key()}>
<TouchComposer state={view.state} />
</Show>
{/* Stands in for the shell's slot, so the touch bar docks to the bottom as it does in the app. */}
<div data-slot="composer-touch-bar-mount" class="shrink-0" />
</div>
)
}
export default {
title: "OpenCode/Composer/Touch",
parameters: { layout: "fullscreen" },
args: { state: "steer" },
argTypes: { state: { control: "select", options: states.map((state) => state.id) } },
render: (args: { state: State }) => <TouchStates state={args.state} />,
}
export const States = {}
+253 -60
View File
@@ -13,6 +13,7 @@ import {
type JSX,
} from "solid-js"
import { createStore } from "solid-js/store"
import { Portal } from "solid-js/web"
import { createResizeObserver } from "@solid-primitives/resize-observer"
import { createMediaQuery } from "@solid-primitives/media"
import { FileIcon } from "@opencode/ui/file-icon"
@@ -98,6 +99,12 @@ export function ComposerEditor(props: ComposerEditorProps) {
let controlsContent!: HTMLDivElement
const [overflow, setOverflow] = createStore({ start: false, end: false })
const [historyLayout, setHistoryLayout] = createStore<{ height?: number }>({})
// Phones and tablets, whatever their width: a narrow desktop window keeps the desktop composer.
const touch = createMediaQuery("(hover: none) and (pointer: coarse)")
// The shell's slot at the bottom of the screen; without one (a story), the touch bar stays under the composer.
const [dock, setDock] = createSignal<HTMLElement>()
onMount(() => setDock(document.querySelector<HTMLElement>('[data-slot="composer-touch-bar-mount"]') ?? undefined))
createEffect(() => {
if (state.popover.type !== "history") setHistoryLayout("height", undefined)
@@ -297,6 +304,7 @@ export function ComposerEditor(props: ComposerEditorProps) {
contenteditable={!props.disabled && !props.readOnly}
autocapitalize={state.mode === "normal" ? "sentences" : "off"}
autocorrect={state.mode === "normal" ? "on" : "off"}
enterkeyhint={touch() ? "enter" : undefined}
spellcheck={state.mode === "normal"}
// @ts-expect-error
autocomplete="off"
@@ -318,6 +326,12 @@ export function ComposerEditor(props: ComposerEditorProps) {
)
}}
onKeyDown={(event) => {
// A touch keyboard's Return only ever adds a line, even over suggestions; the touch bar sends. iOS
// also reports Shift on Return whenever autocapitalization arms it, which used to flip Return
// between sending and a newline. Only a hardware keyboard (an iPad's) has Cmd or Ctrl, and
// Cmd+Return sends there.
if (touch() && event.key === "Enter" && !event.metaKey && !event.ctrlKey) return
// Capture the opening footprint before the controller applies its first history preview.
const height =
state.popover.type === "closed" && event.shiftKey && event.key === "ArrowUp"
@@ -338,13 +352,25 @@ export function ComposerEditor(props: ComposerEditorProps) {
return
}
if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
// Safari delivers the Enter that confirms an IME candidate after compositionend, so only its
// keyCode 229 shows it belongs to the composition.
if (event.key === "Enter" && !event.shiftKey && !event.isComposing && event.keyCode !== 229) {
event.preventDefault()
if (event.repeat) return
props.controller.submit(mod ? { alternate: true } : undefined)
// On touch, Cmd+Return is the touch bar's primary action, since plain Return cannot send.
props.controller.submit(mod && !touch() ? { alternate: true } : undefined)
}
}}
// The editor holds one flat run of text, mentions and <br>s. A touch keyboard's Return arrives as a
// paragraph, which would wrap the next line in a <div> the parser joins without a newline; replace it
// with the line break Shift+Enter inserts. Only beforeinput is cancelled, so iOS still applies its
// autocorrection and capitalization around the Return.
onBeforeInput={(event) => {
if (event.inputType !== "insertParagraph") return
event.preventDefault()
document.execCommand("insertLineBreak")
}}
onKeyUp={updateCursor}
onPointerUp={updateCursor}
onPaste={(event) => {
@@ -385,34 +411,37 @@ export function ComposerEditor(props: ComposerEditorProps) {
</div>
</div>
<div class="flex h-11 shrink-0 items-center px-2">
<div
class="flex shrink-0 items-center"
aria-hidden={state.mode === "shell"}
inert={state.mode === "shell" ? true : undefined}
style={buttons()}
>
<ComposerEditorAddMenu
disabled={view.draftOnly || state.mode === "shell"}
title={i18n.t("ui.promptInput.add")}
keybind={props.attachKeybind ?? ["Mod", "U"]}
attachLabel={i18n.t("ui.promptInput.attachments")}
attachShortcut={props.attachShortcut ?? "Mod+U"}
commandsLabel={i18n.t("ui.promptInput.commands")}
contextLabel={i18n.t("ui.promptInput.context")}
shellLabel={i18n.t("ui.promptInput.shell")}
onAttach={props.controller.attach}
onCommands={props.controller.openCommands}
onContext={props.controller.openContext}
onShell={props.controller.openShell}
/>
</div>
<div class="flex h-11 shrink-0 items-center px-2" classList={{ hidden: touch() && state.mode === "shell" }}>
<Show when={!touch()}>
<div
class="flex shrink-0 items-center"
aria-hidden={state.mode === "shell"}
inert={state.mode === "shell" ? true : undefined}
style={buttons()}
>
<ComposerEditorAddMenu
disabled={view.draftOnly || state.mode === "shell"}
title={i18n.t("ui.promptInput.add")}
keybind={props.attachKeybind ?? ["Mod", "U"]}
attachLabel={i18n.t("ui.promptInput.attachments")}
attachShortcut={props.attachShortcut ?? "Mod+U"}
commandsLabel={i18n.t("ui.promptInput.commands")}
contextLabel={i18n.t("ui.promptInput.context")}
shellLabel={i18n.t("ui.promptInput.shell")}
onAttach={props.controller.attach}
onCommands={props.controller.openCommands}
onContext={props.controller.openContext}
onShell={props.controller.openShell}
/>
</div>
</Show>
<div
ref={controlsViewport}
data-slot="composer-controls"
data-overflow-start={overflow.start}
data-overflow-end={overflow.end}
class="ms-1 me-3 h-full min-w-0 flex-1 overflow-x-auto overscroll-x-contain no-scrollbar"
class="h-full min-w-0 flex-1 overflow-x-auto overscroll-x-contain no-scrollbar"
classList={{ "ms-1 me-3": !touch() }}
onScroll={updateOverflow}
// Chromium leaves a partly visible control where it is when it takes focus, cut off by the edge.
onFocusIn={() => document.activeElement?.scrollIntoView({ block: "nearest", inline: "nearest" })}
@@ -449,44 +478,55 @@ export function ComposerEditor(props: ComposerEditorProps) {
</Show>
</div>
</div>
<div data-slot="composer-actions" class="flex shrink-0 items-center">
<Show when={state.mode === "normal"}>
<ComposerEditorAlternateDelivery
controller={props.controller}
keybind={props.alternateKeybind ?? ["Mod", "Enter"]}
<Show when={!touch()}>
<div data-slot="composer-actions" class="flex shrink-0 items-center">
<Show when={state.mode === "normal"}>
<ComposerEditorAlternateDelivery
controller={props.controller}
keybind={props.alternateKeybind ?? ["Mod", "Enter"]}
/>
</Show>
<Show when={state.mode === "shell"}>
<Button
data-action="composer-exit-shell"
type="button"
variant="ghost-faint"
size="small"
class="me-3 gap-1.5 px-1.5"
onClick={() => {
props.controller.dispatch({ type: "mode.normal" })
props.controller.restoreFocus()
}}
>
{i18n.t("ui.promptInput.exitShell")}
<span class="hidden sm:block">
<Keybind keys={props.exitShellKeybind ?? ["ESC"]} variant="neutral" />
</span>
</Button>
</Show>
<ComposerEditorSubmitButton
mode={state.mode}
stopping={view.submit.stopping()}
busy={view.submit.busy?.() ?? false}
disabled={!props.controller.canSubmit()}
sendLabel={i18n.t("ui.promptInput.send")}
stopLabel={i18n.t("ui.promptInput.stop")}
onSubmit={() => props.controller.submit()}
onStop={props.controller.stop}
/>
</Show>
<Show when={state.mode === "shell"}>
<Button
data-action="composer-exit-shell"
type="button"
variant="ghost-faint"
size="small"
class="me-3 gap-1.5 px-1.5"
onClick={() => {
props.controller.dispatch({ type: "mode.normal" })
props.controller.restoreFocus()
}}
>
{i18n.t("ui.promptInput.exitShell")}
<span class="hidden sm:block">
<Keybind keys={props.exitShellKeybind ?? ["ESC"]} variant="neutral" />
</span>
</Button>
</Show>
<ComposerEditorSubmitButton
mode={state.mode}
stopping={view.submit.stopping()}
busy={view.submit.busy?.() ?? false}
disabled={!props.controller.canSubmit()}
sendLabel={i18n.t("ui.promptInput.send")}
stopLabel={i18n.t("ui.promptInput.stop")}
onSubmit={() => props.controller.submit()}
onStop={props.controller.stop}
/>
</div>
</div>
</Show>
</div>
</form>
<Show when={touch()}>
<Show when={dock()} fallback={<ComposerEditorTouchBar controller={props.controller} />}>
{(mount) => (
<Portal mount={mount()}>
<ComposerEditorTouchBar controller={props.controller} docked />
</Portal>
)}
</Show>
</Show>
</div>
)
}
@@ -1476,6 +1516,159 @@ function ComposerEditorSubmitButton(props: {
)
}
// The composer's actions on a touch device, where Return only adds a line: this bar is the one way to send, steer,
// queue or stop, and every target is at least 44px. Docked, it spans the bottom of the shell, which is the top of the
// keyboard while one is open. Buttons keep the editor focused so the keyboard stays open.
function ComposerEditorTouchBar(props: { controller: ComposerEditorModel; docked?: boolean }) {
const i18n = useI18n()
const state = props.controller.state
const view = props.controller.view
const keep = (event: MouseEvent) => event.preventDefault()
// Docked, the bar is the bottom edge and pads itself for the home indicator, so the shell's main area and a bottom
// titlebar stop doing so.
onMount(() => {
if (!props.docked) return
const root = document.documentElement
root.style.setProperty("--shell-safe-area-bottom", "0px")
onCleanup(() => root.style.removeProperty("--shell-safe-area-bottom"))
})
// The delivery the desktop toolbar offers on Mod+Enter.
const alternate = createMemo(() => {
const queue = view.submit.queue
if (state.mode !== "normal" || !queue || !props.controller.canSubmit()) return undefined
if (queue.editing()) return "steer" as const
return queue.alternate()
})
const label = () => {
const queue = view.submit.queue
if (state.mode !== "normal" || !queue) return i18n.t("ui.promptInput.send")
// A submit while editing puts the prompt back in the queue; the alternate steers it.
if (queue.editing()) return i18n.t("ui.promptInput.queue")
if (!queue.alternate()) return i18n.t("ui.promptInput.send")
return queue.delivery() === "queue" ? i18n.t("ui.promptInput.queue") : i18n.t("ui.promptInput.steer")
}
const busy = () => (view.submit.busy?.() ?? false) && !view.submit.stopping()
return (
<div
data-slot="composer-touch-bar"
class="flex shrink-0 items-center gap-1 bg-v2-background-bg-base"
classList={{
"mt-2 h-14 rounded-xl border border-v2-border-border-base px-1.5": !props.docked,
"box-content h-14 border-t border-v2-border-border-base px-2 pb-[var(--safe-area-inset-bottom,env(safe-area-inset-bottom,0px))]":
!!props.docked,
}}
>
<Show
when={state.mode === "normal"}
fallback={
<Button
data-action="composer-exit-shell"
variant="ghost-muted"
class="h-11 rounded-lg px-3 text-[15px] leading-5"
onMouseDown={keep}
onClick={() => {
props.controller.dispatch({ type: "mode.normal" })
props.controller.restoreFocus()
}}
>
{i18n.t("ui.promptInput.exitShell")}
</Button>
}
>
<IconButton
data-action="composer-attach-file"
variant="ghost-muted"
class="size-11 rounded-lg"
icon={<Icon name="plus" />}
aria-label={i18n.t("ui.promptInput.add")}
disabled={view.draftOnly}
onMouseDown={keep}
onClick={props.controller.attach}
/>
<For
each={
[
{ action: "composer-commands", glyph: "/", label: "ui.promptInput.commands", run: "openCommands" },
{ action: "composer-context", glyph: "@", label: "ui.promptInput.context", run: "openContext" },
{ action: "composer-shell", glyph: "!", label: "ui.promptInput.shell", run: "openShell" },
] as const
}
>
{(key) => (
<IconButton
data-action={key.action}
variant="ghost-muted"
class="size-11 rounded-lg"
icon={<span class="font-mono text-[17px] leading-5">{key.glyph}</span>}
aria-label={i18n.t(key.label)}
disabled={view.draftOnly}
onMouseDown={keep}
onClick={() => props.controller[key.run]()}
/>
)}
</For>
</Show>
<div class="flex-1" />
<Show
when={!view.submit.stopping()}
fallback={
<Button
data-action="composer-submit"
variant="neutral"
class="h-11 gap-2 rounded-xl px-4 text-[15px] leading-5"
onMouseDown={keep}
onClick={props.controller.stop}
>
<Icon name="stop" size="small" />
{i18n.t("ui.promptInput.stop")}
</Button>
}
>
<Show when={alternate()} keyed>
{(delivery) => (
<Button
data-action="composer-alternate-delivery"
variant="neutral"
class="h-11 rounded-xl px-4 text-[15px] leading-5"
onMouseDown={keep}
onClick={() => props.controller.submit({ alternate: true })}
>
{delivery === "steer" ? i18n.t("ui.promptInput.steer") : i18n.t("ui.promptInput.queue")}
</Button>
)}
</Show>
<Button
data-action="composer-submit"
variant="submit"
class="h-11 gap-1.5 rounded-xl px-4 text-[15px] leading-5"
disabled={!props.controller.canSubmit()}
aria-busy={busy()}
onMouseDown={keep}
onClick={() => props.controller.submit()}
>
{label()}
<Show when={busy()} fallback={<Icon name={state.mode === "shell" ? "arrow-undo-down" : "arrow-up"} />}>
<Loader class="size-4" />
</Show>
</Button>
</Show>
</div>
)
}
function ComposerSuggestionIcon(props: { item: ComposerSuggestion }) {
if (props.item.kind === "session") return <Icon name="speech-bubble" size="small" class="shrink-0" />
+5 -1
View File
@@ -300,10 +300,11 @@ export default function Layout(props: ParentProps) {
class="flex-1 min-h-0 min-w-0 overflow-x-hidden flex flex-col items-start contain-content"
style={{
"padding-top": bottomTitlebar() ? "env(safe-area-inset-top, 0px)" : "0px",
// A docked composer touch bar takes over the safe area.
"padding-bottom":
bottomTitlebar() || settings.active()
? "0px"
: "var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px))",
: "var(--shell-safe-area-bottom, var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px)))",
"--settings-bottom-inset": bottomTitlebar()
? "40px"
: "var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px))",
@@ -315,6 +316,9 @@ export default function Layout(props: ParentProps) {
</main>
<CollapsedSidebarToggle />
</div>
{/* On touch devices the active composer moves its actions here: the bottom edge, or the top of the keyboard.
Last in order, so it stays below a bottom titlebar (also order-last, but earlier in the DOM). */}
<div data-slot="composer-touch-bar-mount" class="order-last shrink-0" />
<PluginSlot at="window.bottom" input={{}} />
<ToastRegion />
<UploadToastHost />
+7 -3
View File
@@ -201,7 +201,7 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
height:
platform.platform === "web"
? bottom()
? "calc(28px + max(8px, var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px))))"
? "calc(28px + max(8px, var(--shell-safe-area-bottom, var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px)))))"
: mobileTop()
? `calc(28px + ${mobileTopClearance} + env(safe-area-inset-top, 0px))`
: "calc(28px + max(8px, env(safe-area-inset-top, 0px)))"
@@ -211,7 +211,10 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
: mobileTop()
? `calc(${mobileTopClearance} + env(safe-area-inset-top, 0px))`
: "env(safe-area-inset-top, 0px)",
"padding-bottom": bottom() ? "var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px))" : "0px",
// A docked composer touch bar below takes over the safe area.
"padding-bottom": bottom()
? "var(--shell-safe-area-bottom, var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px)))"
: "0px",
"min-height": minHeight(),
// Keep native macOS traffic lights clear even when the desktop window is narrow.
"padding-left": macTrafficLights() ? `${macTrafficLightsBaseWidth / zoom()}px` : 0,
@@ -678,7 +681,8 @@ export function Titlebar(props: { verticalTabs?: { mount?: HTMLElement } }) {
class="h-full flex-1 overflow-hidden flex flex-row items-center gap-1.5 px-2 md:pe-3"
classList={{
"pt-[max(0px,calc(8px-env(safe-area-inset-top,0px)))]": !bottom() && !windows() && !mobileTop(),
"pb-[max(0px,calc(8px-var(--safe-area-inset-bottom,env(safe-area-inset-bottom,0px))))]": bottom(),
"pb-[max(0px,calc(8px-var(--shell-safe-area-bottom,var(--safe-area-inset-bottom,env(safe-area-inset-bottom,0px)))))]":
bottom(),
"pl-2.5": macTrafficLights(),
// The menu glyph sits 2px further into its slot than the sidebar icons sit into their rows.
"ps-[calc(var(--sidebar-inset-start)-2px)]": windows() && !!props.verticalTabs,