Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,6 @@
"@ai-sdk/google@3.0.73": "patches/@ai-sdk%2Fgoogle@3.0.73.patch",
"@tanstack/virtual-core@3.17.8": "patches/@tanstack%2Fvirtual-core@3.17.8.patch",
"@ff-labs/fff-bun@0.10.5": "patches/@ff-labs%2Ffff-bun@0.10.5.patch",
"ghostty-web@github:anomalyco/ghostty-web#83c0a07": "patches/ghostty-web@0.3.0.patch",
"vite@8.2.2": "patches/vite@8.2.2.patch",
"@modelcontextprotocol/client@2.0.0": "patches/@modelcontextprotocol%2Fclient@2.0.0.patch",
"@corvu/drawer@0.2.4": "patches/@corvu%2Fdrawer@0.2.4.patch",
Expand Down
39 changes: 39 additions & 0 deletions packages/app/component-tests/terminal-focus.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import type { Page } from "@playwright/test"
import { expect, sourceURL, story } from "../../storybook/playwright/story"

const fixture = sourceURL(new URL("../../gui-extensions/src/terminal/terminal.fixture.tsx", import.meta.url))

const mountTerminal = async (page: Page, autoFocus: boolean) => {
await page.evaluate(
async (input) => {
const { mountTerminalFocus } = await import(input.fixture)
mountTerminalFocus({ autoFocus: input.autoFocus })
},
{ fixture, autoFocus },
)
const root = page.getByTestId("terminal-focus-fixture")
await expect(root.locator('[data-component="terminal"] textarea')).toBeAttached()
// The terminal's deferred focus and restore run on timers queued when it opened; let them run first.
await page.evaluate(
() => new Promise<void>((resolve) => setTimeout(() => setTimeout(() => requestAnimationFrame(() => resolve()), 0), 0)),
)

return root
}

story.beforeEach(async ({ mount }) => {
// Any story loads the app styles; the fixture mounts the real terminal beside it.
await mount("ui-line-comment--editor")
})

story("a terminal opened with a focus request keeps focus after the request is consumed", async ({ page }) => {
const root = await mountTerminal(page, true)

await expect(root.locator('[data-component="terminal"] textarea')).toBeFocused()
})

story("a terminal opened without a focus request leaves focus in the composer", async ({ page }) => {
const root = await mountTerminal(page, false)

await expect(root.getByRole("textbox", { name: "Composer", exact: true })).toBeFocused()
})
2 changes: 1 addition & 1 deletion packages/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"@types/node": "catalog:",
"@typescript/native": "catalog:",
"diff": "catalog:",
"ghostty-web": "github:anomalyco/ghostty-web#83c0a07b8628b748aed073b232cb4b52a6ca11c1",
"ghostty-web": "github:anomalyco/ghostty-web#e91e38a9ceb13c566ddfa15185a9393849f712a9",
"happy-dom": "20.11.1",
"tw-animate-css": "1.4.0",
"vite": "8.2.2",
Expand Down
2 changes: 1 addition & 1 deletion packages/gui-extensions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"@tanstack/solid-virtual": "catalog:",
"effect": "catalog:",
"fuzzysort": "catalog:",
"ghostty-web": "github:anomalyco/ghostty-web#83c0a07b8628b748aed073b232cb4b52a6ca11c1",
"ghostty-web": "github:anomalyco/ghostty-web#e91e38a9ceb13c566ddfa15185a9393849f712a9",
"remeda": "catalog:",
"solid-js": "catalog:",
"solid-presence": "0.2.0",
Expand Down
60 changes: 60 additions & 0 deletions packages/gui-extensions/src/terminal/model.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { afterEach, describe, expect, test } from "bun:test"
import { createRoot } from "solid-js"
import type { ServerRef, Sessions, Storage } from "../sdk"
import { createTerminalModel } from "./model"

// SAFETY: the workspace model reads only these members when it loads and handles focus.
const storage = {
memory: (_key: string, options: { initial: unknown }) => [options.initial],
store: () => ({ value: { all: [] }, ready: () => true }),
} as unknown as Storage

// SAFETY: load reads only sessions.list and server.id.
const sessions = { list: () => [] } as unknown as Sessions

// SAFETY: load reads only sessions.list and server.id.
const server = { id: "server" } as unknown as ServerRef

const cleanups: VoidFunction[] = []

afterEach(() => {
cleanups.splice(0).forEach((cleanup) => cleanup())
document.body.replaceChildren()
})

const workspace = () =>
createRoot((dispose) => {
cleanups.push(dispose)

return createTerminalModel({ storage, sessions }).load({ server, directory: "/workspace" })
})

const field = (parent: HTMLElement) => {
const input = document.createElement("input")
parent.append(input)

return input
}

describe("terminal focus requests", () => {
test("survive the side region focusing its selected tab while switching terminals", () => {
const side = document.createElement("div")
side.id = "review-panel"
document.body.append(side)
const terminal = workspace()

terminal.requestFocus("pty_2")
field(side).focus()

expect(terminal.focusRequested("pty_2")).toBe(true)
})

test("are cancelled when focus leaves the side region", () => {
const terminal = workspace()

terminal.requestFocus("pty_2")
field(document.body).focus()

expect(terminal.focusRequested("pty_2")).toBe(false)
})
})
3 changes: 2 additions & 1 deletion packages/gui-extensions/src/terminal/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,8 @@ function createWorkspace(input: { storage: Storage; server: ServerRef; directory

if (!(event.target instanceof Element)) return

if (event.target.closest("#terminal-panel")) return
// The side region focuses its selected tab trigger or root while switching tabs; only focus leaving it cancels.
if (event.target.closest("#terminal-panel, #review-panel")) return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This exempts focus anywhere in the side region, not just the tab trigger or root that the tab switch focuses. Any request that hasn't been used yet now outlives the user moving to other side-panel content. Two examples:

  • Ctrl+Alt+T, then clicking into the file tree or review diff before pty.create resolves. The pending request survives, and the new terminal takes focus when it mounts.
  • ⌘2 to a terminal, then ⌘3 to a non-terminal tab before the request is used. The request stays open and later takes focus when that terminal becomes active again.

Could this only ignore the elements the switch itself focuses (the #review-panel root and its tab triggers, e.g. event.target.id === "review-panel" || event.target.closest('#review-panel [role="tab"]'))? Also, this would no longer tie the terminal extension to all of the host's panel DOM.


cancelFocus()
}
Expand Down
69 changes: 69 additions & 0 deletions packages/gui-extensions/src/terminal/terminal.fixture.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { ThemeProvider } from "@opencode/ui/theme/context"
import { createSignal } from "solid-js"
import { render } from "solid-js/web"
import { ExtensionContext, type Context, type ServerRef } from "../sdk"
import { Terminal } from "./terminal"

/**
* Mounts the real terminal beside a focused composer field, as the side panel does when the user opens a terminal while
* typing. The PTY connection never resolves, so only the mount and focus lifecycle runs.
*/
export function mountTerminalFocus(input: { autoFocus: boolean }) {
const host = document.createElement("div")
host.dataset.testid = "terminal-focus-fixture"
host.style.cssText = "display:flex;flex-direction:column;gap:8px;width:640px;height:360px"
document.body.append(host)

const composer = document.createElement("textarea")
composer.setAttribute("aria-label", "Composer")
host.append(composer)
composer.focus()

const surface = document.createElement("div")
surface.style.cssText = "position:relative;flex:1"
host.append(surface)

// As the panel's focus request does, consuming the request turns autoFocus off.
const [requested, setRequested] = createSignal(input.autoFocus)

// SAFETY: the terminal reads only these extension members while it mounts and focuses.
const extension = {
t: (key: string) => key,
appearance: { font: () => "monospace" },
keybinds: { matches: () => false },
system: { openExternal() {} },
} as unknown as Context

// SAFETY: the terminal reads only these server members; the PTY token never resolves, so it never connects.
const server = {
id: "fixture",
name: "fixture",
url: "http://127.0.0.1:1",
client: { pty: { connect: { token: () => new Promise(() => {}) } } },
} as unknown as ServerRef

const dispose = render(
() => (
<ThemeProvider>
<ExtensionContext.Provider value={extension}>
<Terminal
pty={{ id: "pty_fixture", title: "Terminal", titleNumber: 1 }}
server={server}
directory="/fixture"
ghostty={() =>
import("ghostty-web").then(async (mod) => ({ mod, ghostty: await mod.Ghostty.load() }))
}
autoFocus={requested()}
onAutoFocus={() => setRequested(false)}
/>
</ExtensionContext.Provider>
</ThemeProvider>
),
surface,
)

return () => {
dispose()
host.remove()
}
}
7 changes: 5 additions & 2 deletions packages/gui-extensions/src/terminal/terminal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -507,12 +507,15 @@ export const Terminal = (props: TerminalProps) => {
handleLinkClick,
})

if (local.autoFocus === true) {
// onAutoFocus consumes the request, which flips autoFocus, so read it once.
const autoFocus = local.autoFocus === true

if (autoFocus) {
focusTerminal()
local.onAutoFocus?.()
}

if (local.autoFocus !== true) {
if (!autoFocus) {
const restoreFocus = () => {
const current = document.activeElement

Expand Down
Loading
Loading