Skip to content
Open
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
5 changes: 5 additions & 0 deletions docs/plugin-authoring-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ Each line is the main call. Read the types for every field.
| `ui` (optional) | The host's own controls | `Button`, `Input`, `Field`, `Switch`, `Dialog`. Fall back to plain elements when missing. |
| `host` | Commands, HTTPS, processes, files | Needs `manifest.host`, below |

In a mounted panel, `ctx.panels.useTabTitle?.(label, icon, actions)` sets the
tab's live title and optional icon. Pass an optional stable array of
`{ label, run }` entries to add actions to that tab's context menu. Older hosts
that support the title hook may ignore the actions argument.

Agent tool names match `/^[a-z][a-z0-9_]{0,63}$/` and are unique across plugins; prefix them with your plugin. Changing a tool's name, description or schema restarts some agent sessions. `addInstructions` text is sent on every turn, so keep it short.

In a Solo region, check `ui.headerMenuActions === true` before passing
Expand Down
107 changes: 91 additions & 16 deletions src/features/panels/PanelWorkspace.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { StrictMode, useRef, useState } from "react";
import { StrictMode, useCallback, useMemo, useRef, useState } from "react";
import {
act,
cleanup,
Expand Down Expand Up @@ -104,38 +104,113 @@ function Fixture({
const tabs = () => screen.getByRole("tablist", { name: "Panel tabs" });
const tab = (name: string) => within(tabs()).getByRole("tab", { name });

test("a plugin panel names its tab with panels.useTabTitle, and renders without one outside a tab", () => {
test("a mounted plugin panel supplies its tab title and context-menu actions", async () => {
const user = userEvent.setup();
const ctx = new Context();
ctx.provide("pluginStatus", {
isActive: () => true,
subscribe: () => () => {},
});
const { useTabTitle } = new PanelsService(ctx);
function Build({ id }: { id: string }) {
useTabTitle?.(`#${id}`);
return <p>Build {id}</p>;
const [showLogs, setShowLogs] = useState(false);
const actions = useMemo(
() => [{ label: "Show logs", run: () => setShowLogs(true) }],
[],
);
useTabTitle?.(`#${id}`, undefined, actions);
return <p>{showLogs ? `Logs for build ${id}` : `Build ${id}`}</p>;
}
const { rerender } = render(
const workspace = (id?: string) => (
<PanelWorkspace
value="ci"
select={() => {}}
items={[{ id: "ci", label: "CI", content: <Build id="1" /> }]}
/>,
items={[
{
id: "ci",
label: "CI",
actions: [{ label: "Open in browser", run() {} }],
content: id ? <Build id={id} /> : <p>No build selected</p>,
},
]}
/>
);
const { rerender } = render(workspace("1"));
expect(tab("#1")).toBeInTheDocument();
rerender(
<PanelWorkspace
value="ci"
select={() => {}}
items={[{ id: "ci", label: "CI", content: <Build id="2" /> }]}
/>,
);
expect(tab("#2")).toBeInTheDocument();
expect(within(tabs()).queryByRole("tab", { name: "CI" })).toBeNull();
rerender(workspace("2"));

await user.pointer({ keys: "[MouseRight]", target: tab("#2") });
expect(
await screen.findByRole("menuitem", { name: "Open in browser" }),
).toBeVisible();
await user.click(screen.getByRole("menuitem", { name: "Show logs" }));
expect(await screen.findByText("Logs for build 2")).toBeVisible();

rerender(workspace());
await user.pointer({ keys: "[MouseRight]", target: tab("CI") });
expect(
await screen.findByRole("menuitem", { name: "Open in browser" }),
).toBeVisible();
expect(screen.queryByRole("menuitem", { name: "Show logs" })).toBeNull();
cleanup();
render(<Build id="3" />);
expect(screen.getByText("Build 3")).toBeInTheDocument();
});

test("a plugin-only tab menu preserves focus and closes when its action is withdrawn", async () => {
const user = userEvent.setup();
function BuildTitle({ showLogs }: { showLogs: () => void }) {
const actions = useMemo(
() => [{ label: "Show logs", run: showLogs }],
[showLogs],
);
usePanelTabTitle("Build", undefined, actions);
return null;
}
function Workspace({ hasBuild }: { hasBuild: boolean }) {
const [showLogs, setShowLogs] = useState(false);
const openLogs = useCallback(() => setShowLogs(true), []);
return (
<PanelWorkspace
value="build"
select={() => {}}
items={[
{
id: "build",
label: "Build",
content: (
<>
{hasBuild && <BuildTitle showLogs={openLogs} />}
<p>{showLogs ? "Build logs" : "Build summary"}</p>
</>
),
},
]}
/>
);
}

const { rerender } = render(<Workspace hasBuild={false} />);
tab("Build").focus();
rerender(<Workspace hasBuild />);
expect(tab("Build")).toHaveFocus();
await user.keyboard("{Shift>}{F10}{/Shift}");
await screen.findByRole("menuitem", { name: "Show logs" });
await vi.waitFor(() => expect(screen.getByRole("menu")).toHaveFocus());

rerender(<Workspace hasBuild={false} />);
await vi.waitFor(() => expect(tab("Build")).toHaveFocus());
await user.keyboard("{Shift>}{F10}{/Shift}");
expect(screen.queryByRole("menu")).toBeNull();

rerender(<Workspace hasBuild />);
expect(tab("Build")).toHaveFocus();
expect(screen.queryByRole("menu")).toBeNull();
await user.keyboard("{Shift>}{F10}{/Shift}");
await user.click(await screen.findByRole("menuitem", { name: "Show logs" }));
expect(await screen.findByText("Build logs")).toBeVisible();
});

test("switches retained panels, associates their tabs, and closes inactive or active tabs with focus recovery", async () => {
const user = userEvent.setup();
render(
Expand Down
42 changes: 28 additions & 14 deletions src/features/panels/PanelWorkspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,11 @@ export type PanelWorkspaceItem = {
/** Header icon actions for this tab's content, shown while it is selected. */
toolbar?: ReactNode;
};
type Identity = { label: string; icon?: ReactNode };
type Identity = {
label: string;
icon?: ReactNode;
actions?: readonly TabAction[] | undefined;
};
/** `keepOwner`: the owner stays open; only its detail tabs are cleared. */
type Close = (options?: { keepOwner?: boolean }) => void;
type Local = { id: string; label: string; owner: string; close: Close };
Expand All @@ -60,15 +64,19 @@ export function usePanelTabHost() {
return useContext(TabHost);
}

export function usePanelTabTitle(label: string, icon?: ReactNode) {
export function usePanelTabTitle(
label: string,
icon?: ReactNode,
actions?: readonly TabAction[],
) {
const host = usePanelTabHost();
const title = host?.title;
const owner = host?.owner;
useLayoutEffect(() => {
if (!title || !owner) return;
title(owner, { label, icon });
title(owner, { label, icon, actions });
return () => title(owner, undefined);
}, [title, owner, label, icon]);
}, [title, owner, label, icon, actions]);
}

// Keyboard opens and reduced motion skip the push. Deciding here, rather than
Expand Down Expand Up @@ -214,16 +222,22 @@ export function PanelWorkspace({
(tab) => tab.id === localSelection && tab.owner === value,
);
const selected = selectedLocal?.id ?? value;
const tabs = items.flatMap((item) => [
{
...item,
...titles[item.id],
icon: titles[item.id]?.icon ?? item.icon ?? <BrowserIcon size="1rem" />,
},
...owned
.filter((tab) => tab.owner === item.id)
.map((tab) => ({ ...tab, icon: <TerminalWindowIcon size="1rem" /> })),
]);
const tabs = items.flatMap((item) => {
const title = titles[item.id];
return [
{
...item,
...title,
icon: title?.icon ?? item.icon ?? <BrowserIcon size="1rem" />,
actions: title?.actions
? [...title.actions, ...(item.actions ?? [])]
Comment thread
tellaho marked this conversation as resolved.
Resolved
: item.actions,

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.

🤖 [P3] Preserve keyboard focus when a highlighted dynamic action disappears

With a host action and a plugin action present, open the tab menu with Shift+F10, use ArrowDown to focus the plugin item, then withdraw that contribution. In the actual application under Playwright WebKit, focus moves to body while the mixed menu remains open, and ArrowDown stops navigating (4/4 repeats). Escape recovers; Chromium instead focuses the host action. This also reproduces on the earlier feature head 6245640, so it is a gap in the new dynamic-action path rather than a regression specific to the final fix commit. Native WKWebView was not tested.

When removal takes away the focused item, move focus to a remaining item/popup or close the menu and return focus to the tab. Add a WebKit regression for this mixed-menu case.

},
...owned
.filter((tab) => tab.owner === item.id)
.map((tab) => ({ ...tab, icon: <TerminalWindowIcon size="1rem" /> })),
];
});
const active = tabs.find((tab) => tab.id === selected);
const choose = (id: string) => {
const local = owned.find((tab) => tab.id === id);
Expand Down
8 changes: 4 additions & 4 deletions src/features/panels/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,10 @@ export type Panels = {
handleOpenRequests(
handler: (request: PanelOpenRequest) => boolean,
): () => void;
/** React hook for a panel component: names its tab, in place of the static
* `title`, while mounted, with an optional icon. Also works in a host workspace.
* Does nothing outside a tab. Absent on hosts
* that predate it, so feature-detect before calling. */
/** React hook for a panel component: sets its tab title, optional icon and
* context-menu actions while mounted. Keep the actions array stable between
* renders. Also works in a host workspace and does nothing outside a tab.
* Feature-detect the hook on older hosts. */
useTabTitle?: typeof usePanelTabTitle;
};
declare module "@deepseek-ai/cordis" {
Expand Down
24 changes: 17 additions & 7 deletions src/shared/design-system/ui/Tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -373,13 +373,19 @@ export function TabMenu({
closeOthers: (() => boolean) | undefined;
children: ReactNode;
}) {
const hasMenu = !!(actions?.length || onRename || closeAll || closeOthers);
const [open, setOpen] = useState(false);
const trigger = useRef<HTMLElement>(null);
const [anchor, setAnchor] = useState<HTMLElement>();
const closingAll = useRef(false);
// A host action runs once the menu has closed, from its tab, so a
// destination it opens can take focus from there.
const afterClose = useRef<() => void>(undefined);
useLayoutEffect(() => {
if (hasMenu) return;
afterClose.current = undefined;
setOpen(false);
}, [hasMenu]);
// Middle-click closes a closable tab, without the browser's own default.
const item = {
className: "buzz-tabs-item",
Expand All @@ -393,20 +399,23 @@ export function TabMenu({
onClose();
},
};
if (!actions?.length && !onRename && !closeAll)
return <span {...item}>{children}</span>;
return (
<ContextMenuRoot
open={open}
onOpenChange={(next) => {
disabled={!hasMenu}
open={hasMenu && open}
onOpenChange={(next, details) => {
if (next && !hasMenu) {
details.cancel();
return;
}
if (next) closingAll.current = false;
setOpen(next);
}}
onOpenChangeComplete={(next) => {
if (next) return;
const action = afterClose.current;
afterClose.current = undefined;
if (!action) return;
if (!hasMenu || !action) 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.

🤖 [P3] Cancel a withdrawn queued action even when host menu items remain

Select a plugin action, then withdraw its contribution before the exit animation finishes. With plugin-only actions the queued callback is cleared, but when a host action or closeAll remains, hasMenu stays true and the retired callback still runs. An actual-app probe reproduced this in Chromium and WebKit 4/4 each, withdrawing 80–110 ms before close completion and observing the callback run after its contributor unmounted. A component probe independently gives runs=0 without host actions and runs=1 with them.

The earlier finding #4267 (comment) is fixed for whole-menu withdrawal; the mixed-menu case exposes the remaining limitation of this fix. Apply one cancellation rule based on whether the selected contribution remains current, rather than global menu availability.

Add a committed regression covering selected-action withdrawal both with and without host actions. Removing both cancellation guards still leaves all 242 panel/design-system tests passing; the new component probe detects the plugin-only regression as well as the mixed-menu defect.

trigger.current
?.querySelector<HTMLElement>('[role="tab"], button')
?.focus();
Expand All @@ -422,8 +431,9 @@ export function TabMenu({
onTouchStart={() => setAnchor(undefined)}
onKeyDown={(event) => {
if (
event.key === "ContextMenu" ||
(event.shiftKey && event.key === "F10")
hasMenu &&
(event.key === "ContextMenu" ||
(event.shiftKey && event.key === "F10"))
) {
event.preventDefault();
closingAll.current = false;
Expand Down
Loading