feat(app): add session location menu actions (#59607)

This commit is contained in:
usrnk1
2026-10-27 15:44:13 +01:00
committed by GitHub
Unverified
parent 115113931c
commit 4ba064f653
11 changed files with 256 additions and 27 deletions
@@ -2,6 +2,7 @@ import type { SessionMessageInfo } from "@opencode/client/promise"
import { expect, test, type Page } from "@playwright/test"
import { REMOTE_SERVER, seed, sessionHref } from "../utils/app"
import { fixture, mockStressTimeline } from "../utils/session-fixture"
import { reviewTabs } from "../utils/side-panel"
import { expectSessionTitle } from "../utils/waits"
import { mockRemoteServer, mockWorkspace, openSession } from "../utils/workspace"
@@ -333,7 +334,7 @@ test.describe("location", () => {
test("names the project and worktree, and the card copies the full path", async ({ page, context }) => {
await context.grantPermissions(["clipboard-read", "clipboard-write"])
await openSession(page, workspace)
await openSession(page, { ...workspace, vcs: { current: "", default: "main" } })
await expect(trigger(page).locator('[data-slot="session-location-project"]')).toHaveText("Location")
await expect(trigger(page).locator('[data-slot="session-location-worktree"]')).toHaveText("quiet-falcon")
await expect(trigger(page)).not.toContainText("/")
@@ -341,6 +342,8 @@ test.describe("location", () => {
await trigger(page).click()
const card = page.locator('[data-slot="session-location-card"]')
const path = card.getByRole("menuitem", { name: worktree, exact: true })
await expect(card.getByText("No branch", { exact: true })).toBeVisible()
await expect(card.getByRole("menuitem", { name: "No branch", exact: true })).toHaveCount(0)
await expect(path).toHaveText(worktree)
await expect(card.getByRole("menuitem", { name: "Copy path", exact: true })).toHaveCount(0)
// Select actual text on the first line, not the empty half of a wrapped path's bounding box.
@@ -379,6 +382,98 @@ test.describe("location", () => {
await expect(page.locator('[data-slot="session-location-card"]').getByText("apollo", { exact: true })).toBeVisible()
})
test("copies the branch name and opens its worktree in the right-panel terminal", async ({ page, context }) => {
await context.grantPermissions(["clipboard-read", "clipboard-write"])
await page.setViewportSize({ width: 1440, height: 900 })
const { pty } = await openSession(page, {
...workspace,
vcs: (directory) => ({ current: directory === worktree ? "feature/branch-menu" : "main", default: "main" }),
pty: {},
})
await expect(page.getByRole("button", { name: "More options", exact: true })).toBeVisible()
await trigger(page).click()
const card = page.locator('[data-slot="session-location-card"]')
const branch = card.getByRole("menuitem", { name: "feature/branch-menu", exact: true })
await page.screenshot({ path: test.info().outputPath("branch-card.png"), animations: "disabled" })
await branch.press("Enter")
const actions = page.getByRole("menu", { name: "feature/branch-menu", exact: true })
await expect(actions.getByRole("menuitem")).toHaveText(["Copy branch name", "Open in terminal"])
await page.screenshot({ path: test.info().outputPath("branch-actions.png"), animations: "disabled" })
await actions.getByRole("menuitem", { name: "Copy branch name", exact: true }).click()
await expect(card).toBeHidden()
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("feature/branch-menu")
await trigger(page).click()
await branch.click()
await actions.getByRole("menuitem", { name: "Open in terminal", exact: true }).click()
await expect(card).toBeHidden()
await expect.poll(() => pty.created.map((item) => item.cwd)).toEqual([worktree])
await expect.poll(() => pty.sockets.length).toBe(1)
pty.send("$ pwd\r\n" + worktree + "\r\n")
const terminal = page.locator('[data-component="terminal"]')
await expect(terminal).toHaveCSS("opacity", "1")
await expect(terminal.locator("textarea")).toBeFocused()
await expect
.poll(async () => {
const box = await terminal.boundingBox()
const header = await page.locator("[data-session-title]").boundingBox()
return !!box && !!header && box.x >= header.x + header.width
})
.toBe(true)
await page.screenshot({ path: test.info().outputPath("branch-terminal.png"), animations: "disabled" })
})
for (const app of [
{ id: "vscode", label: "VS Code" },
{ id: "finder", label: "Finder" },
]) {
test(`uses the selected ${app.label} app in the path submenu`, async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 })
const mock = await mockWorkspace(page, {
...workspace,
seed: {
storage: {
...reviewTabs(worktree, "ses_location"),
"opencode.global.dat:plugin.file.app": { app: app.id },
},
},
})
await page.goto(
`/e2e/utils/windows-menu.html?${new URLSearchParams({
server: mock.server,
path: sessionHref("ses_location", "sidecar"),
os: "macos",
openApps: "1",
})}`,
)
await expectSessionTitle(page, "Location session")
await page.getByRole("button", { name: "Toggle review", exact: true }).click()
// Opening review hands focus to the panel after its motion; let that finish before opening another menu.
await expect(page.getByRole("complementary", { name: "Review and files", exact: true })).toBeFocused()
await expect(page.getByRole("button", { name: `Open in ${app.label}`, exact: true })).toBeVisible()
await trigger(page).click()
await page.getByRole("menuitem", { name: worktree, exact: true }).click()
const actions = page.getByRole("menu", { name: worktree, exact: true })
if (app.id === "finder") {
await expect(actions.getByRole("menuitem")).toHaveText(["Copy path", "Reveal in Finder"])
return
}
await page.screenshot({ path: test.info().outputPath("path-open-app.png"), animations: "disabled" })
await actions.getByRole("menuitem", { name: "Open in VS Code", exact: true }).click()
await expect(page.getByLabel("Opened paths")).toHaveText(
JSON.stringify([{ path: worktree, app: "Visual Studio Code" }]),
)
})
}
test.describe("touch", () => {
test.use({ hasTouch: true })
@@ -7,7 +7,7 @@ import { PlatformProvider, type Platform } from "../../src/runtime/platform/plat
// The app on a Windows desktop platform, so the titlebar shows the app menu. Menu actions are listed in an output.
// `path` opens a route other than Home.
export function mount(input: { server: string; path?: string }) {
export function mount(input: { server: string; path?: string; os?: "macos"; openApps?: boolean }) {
const root = document.getElementById("root")
if (!root) throw new Error("Missing fixture root")
@@ -15,7 +15,10 @@ export function mount(input: { server: string; path?: string }) {
if (input.path) history.set({ value: input.path, replace: true })
render(() => {
const [store, setStore] = createStore<{ actions: string[] }>({ actions: [] })
const [store, setStore] = createStore<{ actions: string[]; opened: { path: string; app?: string }[] }>({
actions: [],
opened: [],
})
const unused = async () => {
throw new Error("Unexpected fixture action")
@@ -42,7 +45,7 @@ export function mount(input: { server: string; path?: string }) {
const platform: Platform = {
platform: "desktop",
os: "windows",
os: input.os ?? "windows",
windowID: "windows-menu-test",
openExternal: () => undefined,
openDirectoryPickerDialog: async () => null,
@@ -52,10 +55,19 @@ export function mount(input: { server: string; path?: string }) {
runDesktopMenuAction: (action) => setStore("actions", (actions) => [...actions, action]),
}
if (input.openApps) {
platform.checkAppExists = async (app) => app === "Visual Studio Code" || app === "code"
platform.openPath = async (path, app) => void setStore("opened", (opened) => [...opened, { path, app }])
platform.revealPath = async () => true
}
return (
<PlatformProvider value={platform}>
<AppBaseProviders locale="en">
<output aria-label="Desktop menu actions">{store.actions.join(",")}</output>
<output aria-label="Opened paths" class="sr-only">
{JSON.stringify(store.opened)}
</output>
<AppInterface
servers={[{ type: "sidecar", variant: "base", displayName: "Local Server", http: { url: input.server } }]}
router={(props) => <MemoryRouter {...props} history={history} />}
+6 -1
View File
@@ -8,7 +8,12 @@
<script type="module">
import { mount } from "./windows-menu.fixture.tsx"
const params = new URLSearchParams(location.search)
mount({ server: params.get("server"), path: params.get("path") ?? undefined })
mount({
server: params.get("server"),
path: params.get("path") ?? undefined,
os: params.get("os") === "macos" ? "macos" : undefined,
openApps: params.get("openApps") === "1",
})
</script>
</body>
</html>
+1
View File
@@ -670,6 +670,7 @@ export const dict = {
"session.header.reveal.fileExplorer": "Reveal in File Explorer",
"session.header.reveal.containingFolder": "Open containing folder",
"session.location.copyPath": "Copy path",
"session.location.copyBranch": "Copy branch name",
"session.location.noBranch": "No branch",
"settings.tab.servers": "Servers",
@@ -147,18 +147,14 @@ export function SessionLocation(props: {
void server.ctx.data.location.vcs.sync({ directory: props.project.worktree }).catch(() => undefined)
}
const copyPath = async () => {
const directory = props.directory
if (!directory) return
const copyText = async (text: string) => {
try {
await (platform.writeClipboardText?.(directory) ?? navigator.clipboard.writeText(directory))
await (platform.writeClipboardText?.(text) ?? navigator.clipboard.writeText(text))
showToast({
variant: "success",
icon: "circle-check",
title: language.t("common.copied"),
description: directory,
description: text,
})
} catch (cause) {
showToast({
@@ -291,10 +287,10 @@ export function SessionLocation(props: {
</Show>
</Show>
<Show when={git()}>
<SessionLocationDetail icon="branch">
<Show
when={branch()}
fallback={
<Show
when={branch()}
fallback={
<SessionLocationDetail icon="branch">
<span class="flex min-w-0 items-center gap-1.5">
<span class="shrink-0 whitespace-nowrap">{language.t("session.location.noBranch")}</span>
<Show when={baseBranch()}>
@@ -308,11 +304,46 @@ export function SessionLocation(props: {
)}
</Show>
</span>
}
>
{branch()}
</Show>
</SessionLocationDetail>
</SessionLocationDetail>
}
>
{(name) => (
<Menu.Sub gutter={4} overflowPadding={16} overlap>
<Menu.SubTrigger class="[&_[data-slot=menu-v2-item-chevron]]:text-v2-icon-icon-muted">
<Icon name="branch" class="shrink-0 text-v2-icon-icon-muted" />
<bdi dir="auto" class="min-w-0 truncate">
{name()}
</bdi>
</Menu.SubTrigger>
<Menu.Portal>
<Menu.SubContent class="w-max max-w-[calc(100vw-32px)]" aria-label={name()}>
<Menu.Item onSelect={() => void copyText(name())}>
<Icon name="outline-copy" class="text-v2-icon-icon-muted" />
{language.t("session.location.copyBranch")}
</Menu.Item>
<Show when={props.context}>
{(context) => (
<PluginSlot
at="session.location.branch.menu"
input={{
get session() {
return context().session
},
get screen() {
return context().screen
},
get shown() {
return store.open
},
}}
/>
)}
</Show>
</Menu.SubContent>
</Menu.Portal>
</Menu.Sub>
)}
</Show>
</Show>
<Show when={props.context}>
{(context) => (
@@ -353,7 +384,7 @@ export function SessionLocation(props: {
</Menu.SubTrigger>
<Menu.Portal>
<Menu.SubContent class="w-max max-w-[calc(100vw-32px)]" aria-label={directory()}>
<Menu.Item onSelect={() => void copyPath()}>
<Menu.Item onSelect={() => void copyText(directory())}>
<Icon name="outline-copy" class="text-v2-icon-icon-muted" />
{language.t("session.location.copyPath")}
</Menu.Item>
@@ -363,6 +394,24 @@ export function SessionLocation(props: {
{language.t(fileManagerApp(platform.os ?? "unknown").actionLabel)}
</Menu.Item>
</Show>
<Show when={props.context}>
{(context) => (
<PluginSlot
at="session.location.path.menu"
input={{
get session() {
return context().session
},
get screen() {
return context().screen
},
get shown() {
return store.open
},
}}
/>
)}
</Show>
</Menu.SubContent>
</Menu.Portal>
</Menu.Sub>
+11 -1
View File
@@ -224,7 +224,7 @@ SDK icon fields take an `IconName` from `@opencode/plugin/gui`: the names of the
| [`LinkHandler`](../plugin/src/gui/registries.ts) | window | Opens local links, such as file paths in messages, and says whether their target exists |
| [`TitlebarItem`](../plugin/src/gui/registries.ts) | window | A pill in the titlebar or the tabs footer |
| [`ComposerPill`](../plugin/src/gui/registries.ts) | window | A pill in the row above a session's composer, optionally opening a menu of rows |
| [`Slot`](../plugin/src/gui/registries.ts) | window | Content for `window.bottom`, `session.header`, `session.location.menu`, `session.panel.end`; built-ins also fill `session.location.workspace` through `BuiltinSlot` |
| [`Slot`](../plugin/src/gui/registries.ts) | window | Content for `window.bottom`, `session.header`, `session.location.menu`, `session.panel.end`; built-ins also fill `session.location.workspace`, `session.location.branch.menu` and `session.location.path.menu` through `BuiltinSlot` |
| [`Style`](../plugin/src/gui/registries.ts) | window | CSS imported with `?inline` |
| [`MenubarItem`](../plugin/src/gui/main.ts) | main | An item of the native app menu |
@@ -232,6 +232,16 @@ SDK icon fields take an `IconName` from `@opencode/plugin/gui`: the names of the
the live `session`, and `shown`; keep data subscriptions active only while `shown` is true. Loading headers without an
owning screen show the host's location details without this slot.
`session.location.branch.menu` (built-ins only, through `BuiltinSlot`) contributes items after Copy branch name in
the branch submenu, with the same `screen`, live `session`, and project-menu `shown` context. It renders only when a
branch name and owning screen are available. Use it for actions on the branch's working directory, such as opening
an integrated terminal.
`session.location.path.menu` (built-ins only, through `BuiltinSlot`) contributes items after the host's copy and
reveal actions in the session directory's path submenu. It receives the same session context and renders only with
an owning screen. Use it for external-app actions on `session.directory` without duplicating the host's file-manager
action.
`session.location.workspace` (built-ins only, through `BuiltinSlot`) replaces the current location row with the same
session context plus its `label` and `icon`; one contribution owns it. Without a contribution, the host keeps its
static location row. Use it to attach location actions directly
@@ -193,6 +193,27 @@ export function useOpenInApp(input: { session: MountedSession; path: () => strin
type OpenInAppState = ReturnType<typeof useOpenInApp>
export function OpenInAppMenuItem(props: { session: MountedSession }) {
const ctx = usePlugin()
const state = useOpenInApp({
get session() {
return props.session
},
path: () => props.session.directory,
request: useShared().request,
})
return (
<Show when={state.canOpen() && state.current().id !== "finder"}>
<Menu.Item disabled={state.opening()} onSelect={() => state.openPath(state.current().id)}>
<AppIcon id={state.current().icon} class="size-3.5 shrink-0" />
{ctx.t("open.ariaLabel", { app: state.current().label })}
</Menu.Item>
</Show>
)
}
export default function OpenInAppButton(props: { session: MountedSession; screen: SessionScreen }) {
const ctx = usePlugin()
const directory = () => props.screen.file.root
+21 -2
View File
@@ -46,7 +46,7 @@ import type File from "./index"
import { FileVisual } from "./label"
import { fileTabId, fileTabPath, isFileTab, workspaceFileUrl } from "./path"
import tabStyles from "./tabs.css?inline"
import { onIdle, BuiltinPanel, type BuiltinPanelTab } from "@opencode/plugin/gui/builtin"
import { onIdle, BuiltinPanel, BuiltinSlot, type BuiltinPanelTab } from "@opencode/plugin/gui/builtin"
import { Browser } from "@opencode/plugin/gui/browser"
import { Changes } from "@opencode/plugin/gui/review"
@@ -414,6 +414,10 @@ const setup: Plugin.Setup<typeof File> = (ctx) => {
const OpenInAppButton = lazy(() => import("./open-in-app"))
const OpenInAppMenuItem = lazy(() =>
import("./open-in-app").then((module) => ({ default: module.OpenInAppMenuItem })),
)
// How many "Open in" buttons each screen's panel headers show; the tab strip shows its own only while none do.
const headers = new WeakMap<SessionScreen, Signal<number>>()
@@ -430,7 +434,22 @@ const setup: Plugin.Setup<typeof File> = (ctx) => {
}
if (desktop) {
onCleanup(onIdle(() => void OpenInAppButton.preload()))
onCleanup(
onIdle(() => {
void OpenInAppButton.preload()
void OpenInAppMenuItem.preload()
}),
)
ctx.add(BuiltinSlot, {
at: "session.location.path.menu",
render: (input) => (
<FileProvider>
<Suspense>
<OpenInAppMenuItem session={input.session} />
</Suspense>
</FileProvider>
),
})
ctx.add(Slot, {
at: "session.panel.end",
render: (input) => (
@@ -3,6 +3,7 @@ export default {
"command.toggle": "Toggle terminal",
"command.new": "New terminal",
"command.new.description": "Create a new terminal tab",
"location.open": "Open in terminal",
loading: "Loading terminal…",
"title.numbered": "Terminal {{number}}",
close: "Close terminal",
+14 -2
View File
@@ -1,4 +1,6 @@
import { createMemo, lazy, on, onCleanup, Suspense } from "solid-js"
import { Icon } from "@opencode/ui/icon"
import { Menu } from "@opencode/ui/menu"
import {
Command,
createKeyed,
@@ -16,7 +18,7 @@ import { terminalTab, type LocalPTY } from "./state"
import { terminalTabLabel } from "./title"
import { TerminalTabLabel } from "./label"
import quoteStyles from "./quote.css?inline"
import { onIdle, BuiltinCommand } from "@opencode/plugin/gui/builtin"
import { onIdle, BuiltinCommand, BuiltinSlot } from "@opencode/plugin/gui/builtin"
const setup: Plugin.Setup<typeof Terminal> = (ctx) => {
const sessions = ctx.sessions
@@ -66,7 +68,7 @@ const setup: Plugin.Setup<typeof Terminal> = (ctx) => {
void terminal.new().then((id) => {
const pty = id ? terminal.all().find((item) => item.id === id) : undefined
if (pty) show(session, terminal, pty)
if (pty && !ctx.signal.aborted) show(session, terminal, pty)
})
// Closes the tab, which closes its terminal; the narrow-screen view lists terminals without storing their tabs.
@@ -78,6 +80,16 @@ const setup: Plugin.Setup<typeof Terminal> = (ctx) => {
const active = (terminal: TerminalWorkspace) => terminal.all().find((pty) => pty.id === terminal.active())
ctx.add(BuiltinSlot, {
at: "session.location.branch.menu",
render: (input) => (
<Menu.Item onSelect={() => create(input.session, model.load(input.session))}>
<Icon name="outline-console" class="text-v2-icon-icon-muted" />
{ctx.t("location.open")}
</Menu.Item>
),
})
ctx.add(
Command,
(): Command => ({
+4
View File
@@ -98,6 +98,10 @@ export const BuiltinPanel = Registry.define<BuiltinPanel>("panel")
/** The slots of `SlotMap`, and those only built-ins fill. */
export interface BuiltinSlotMap extends SlotMap {
/** Items after Copy branch name in the branch submenu. Only rendered for a named branch with an owning screen. */
readonly "session.location.branch.menu": SlotMap["session.location.menu"]
/** Items after the host's copy and reveal actions in the session directory's path submenu. Requires an owning screen. */
readonly "session.location.path.menu": SlotMap["session.location.menu"]
/**
* Replaces the project menu's current location row; one contribution owns it. Without one the host shows a static
* row.