Файли
openidea/src/features/plugins/corePoints.tsx
T
l0ng-ai 79f6476d52 fix: unique menu row keys, backend-only plugin points, Debug Server host hint (#6623)
Menu rows of one action repeated with object args (Run with Coverage, Profile... via run.withExecutor) shared a React key; repeated keys now get a suffix. The client defines the backend-only runConfigurations and locales plugin points so plugins contributing them no longer log 'has no client projection'. The Python Debug Server host hint now says loopback hosts listen on loopback only, matching how the listener binds.
2026-11-28 10:55:14 +08:00

303 рядки
11 KiB
TypeScript

/**
* Editor-free first-party plugin UI points (commands, themes, icon themes,
* secrets, endpoints), shared by the workbench and the Settings window without
* pulling in CodeMirror-backed plugin editors.
*/
import { registerEndpointProvider, registerSearchCategory, type EndpointEntry } from "@/workbench/contributions";
import type { PluginInfo, ThemeDef } from "@/bindings";
import { pluginIconName } from "./pluginIcon";
import { registerAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { addContributedTheme, pluginThemeRef } from "@/platform/themes";
import { currentThemeChoice, setTheme, useThemeOverride } from "@/workbench/theme";
import { useProject } from "@/platform/project";
import { Button, Kbd, T } from "@/ui";
import { addIconTheme, iconThemeKey, selectIconTheme, useSelectedIconTheme } from "./iconThemes";
import { defineUiPoint, type UiItem } from "./projection";
import { SecretsDetails, type SecretDecl } from "./secrets";
import { pluginSettingsPageId } from "./settings";
import { pluginsBackend } from "./backend";
import { isLive, runPluginCommand, usePlugins } from "./store";
import { focusedViewItem } from "./views/PluginView";
import styles from "./PluginsPage.module.css";
/** Unpacks an action argument: a bare path, or a menu's `{ path, paths }`. */
export function commandArgs(arg: unknown): [string | null, string[]] {
if (typeof arg === "string") return [arg, []];
const { path, paths, line, column } = (arg ?? {}) as {
path?: unknown;
paths?: unknown;
line?: unknown;
column?: unknown;
};
if (typeof path !== "string" || !Array.isArray(paths)) return [null, []];
if (typeof line === "number" && typeof column === "number")
return [JSON.stringify({ path, line, column }), paths.filter((p): p is string => typeof p === "string")];
return [path, paths.filter((p): p is string => typeof p === "string")];
}
export const pluginActionId = (pluginId: string, commandId: string) => `plugin.${pluginId}.${commandId}`;
interface CommandDecl {
id: string;
title: string;
icon?: string | null;
category?: string | null;
when?: string | null;
}
function CommandsDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<CommandDecl>[] }) {
const runnable = plugin.status === "active" || plugin.status === "inactive";
return (
<ul className={styles.items}>
{items.map(({ decl: c }) => {
const actionId = pluginActionId(plugin.id, c.id);
return (
<li key={c.id} className={styles.item}>
<span className={styles.itemMain}>{c.title}</span>
<Kbd action={actionId} />
<span className={styles.mono} title={tx("Action id (bind it in Keymap)")}>
{actionId}
</span>
<Button
size="small"
variant="ghost"
icon="run"
disabled={!runnable}
onClick={() => void runPluginCommand(plugin.id, c.id)}
aria-label={tx`Run ${c.title}`}
>
<T>Run</T>
</Button>
</li>
);
})}
</ul>
);
}
function ThemesDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<ThemeDef>[] }) {
// The selection is the Appearance setting; these buttons write it as the theme pickers do.
useProject((s) => s.settings?.appearance);
useThemeOverride((s) => s.theme);
const selected = currentThemeChoice();
const live = isLive(plugin.status);
return (
<ul className={styles.items}>
{items.map(({ decl: t }) => {
const isActive = selected === pluginThemeRef(plugin.id, t.id);
return (
<li key={t.id} className={styles.item}>
<span className={styles.itemMain}>{t.name}</span>
<span className={styles.muted}>{t.kind === "dark" ? tx("Dark") : tx("Light")}</span>
{isActive ? (
<Button
size="small"
variant="secondary"
onClick={() => void setTheme(t.kind === "light" ? "light" : "dark")}
>
<T>Use Default Theme</T>
</Button>
) : (
<Button
size="small"
variant="ghost"
disabled={!live}
onClick={() => void setTheme(pluginThemeRef(plugin.id, t.id))}
aria-label={tx`Apply theme ${t.name}`}
>
<T>Apply</T>
</Button>
)}
</li>
);
})}
</ul>
);
}
interface IconThemeDecl {
id: string;
label: string;
icons: number;
}
function IconThemesDetails({ plugin, items }: { plugin: PluginInfo; items: UiItem<IconThemeDecl>[] }) {
const selected = useSelectedIconTheme();
return (
<ul className={styles.items}>
{items.map(({ decl: t }) => {
const key = iconThemeKey(plugin.id, t.id);
return (
<li key={t.id} className={styles.item}>
<span className={styles.itemMain}>{t.label}</span>
<span className={styles.muted}>{tx`${t.icons} icons`}</span>
{selected === key ? (
<Button size="small" variant="secondary" onClick={() => void selectIconTheme(null)}>
<T>Use Default Icons</T>
</Button>
) : (
<Button
size="small"
variant="ghost"
onClick={() => void selectIconTheme(key)}
aria-label={tx`Apply icon theme ${t.label}`}
>
<T>Apply</T>
</Button>
)}
</li>
);
})}
</ul>
);
}
const endpointPlugins = new Map<string, { declarations: number; dispose: () => void }>();
/** One endpoint provider per plugin, however many `[[contributes.endpoints]]` it declares. */
function providePluginEndpoints(pluginId: string): () => void {
let entry = endpointPlugins.get(pluginId);
if (!entry) {
const dispose = registerEndpointProvider({
id: `plugin:${pluginId}`,
endpoints: async (root): Promise<EndpointEntry[]> =>
(await pluginsBackend().endpoints(pluginId)).map((e) => ({
method: e.method ?? "*",
url: e.path,
framework: e.framework,
handler: e.handler ?? undefined,
controller: e.framework,
methodName: e.handler ?? "",
pluginId,
path: e.location.path,
rel: e.location.path.startsWith(`${root}/`) ? e.location.path.slice(root.length + 1) : e.location.path,
line: e.location.range.start.line,
col: e.location.range.start.col,
})),
});
entry = { declarations: 0, dispose };
endpointPlugins.set(pluginId, entry);
}
const held = entry;
held.declarations++;
return () => {
if (--held.declarations > 0) return;
held.dispose();
endpointPlugins.delete(pluginId);
};
}
/** Registers the editor-free UI points (commands, themes, icon themes, secrets, endpoints, search categories). */
export function defineCoreUiPoints(): () => void {
const disposers = [
// Read by the backend (or straight from the store) only: defined so their items aren't reported as unknown.
defineUiPoint("mcpTools", {}),
defineUiPoint("serverCommands", {}),
defineUiPoint("runConfigurations", {}),
defineUiPoint("locales", {}),
defineUiPoint<{ id: string; title: string }>("searchCategories", {
project: ({ pluginId, decl }) => {
let active = true;
const command = (id: string) =>
usePlugins.getState().ui.find((c) => c.pluginId === pluginId && c.point === "commands" && c.key === id)
?.decl as CommandDecl | undefined;
const dispose = registerSearchCategory({
id: `plugin:${pluginId}:${decl.id}`,
title: decl.title,
search: (request, query, limit) => pluginsBackend().search(pluginId, decl.id, query, limit, request),
command: (id) => {
const c = command(id);
if (!active || !c) return undefined;
return {
id: pluginActionId(pluginId, id),
title: c.title,
when: c.when ?? undefined,
run: async ({ arg }) => {
if (active && command(id))
await runPluginCommand(pluginId, id, typeof arg === "string" ? arg : null, []);
},
};
},
});
return () => {
active = false;
dispose();
};
},
}),
defineUiPoint("endpoints", { project: ({ pluginId }) => providePluginEndpoints(pluginId) }),
defineUiPoint<CommandDecl>("commands", {
title: "Commands",
project: ({ pluginId, decl }, { plugin }) => {
let disposed = false;
const action = {
id: pluginActionId(pluginId, decl.id),
title: decl.title,
category: decl.category ?? plugin.name,
icon:
decl.icon && !decl.icon.endsWith(".svg")
? decl.icon
: plugin.icon
? pluginIconName(pluginId, plugin.icon)
: "package",
when: decl.when ?? undefined,
verbatim: true,
// A command can call a model or a server; its toolbar button must show the click was taken.
indicatesRunning: true,
keywords: ["plugin", plugin.name, pluginId],
description: tx`From plugin ${plugin.name}`,
run: async ({ arg }: { arg?: unknown }) => {
// A shortcut passes nothing: the plugin's focused view supplies its selected item.
const [path, paths] = commandArgs(arg ?? focusedViewItem(pluginId, action.id));
await runPluginCommand(pluginId, decl.id, path, paths);
},
};
let off = registerAction(action);
if (decl.icon?.endsWith(".svg"))
void pluginsBackend()
.assets(pluginId, `commandIcon/${decl.id}`)
.then((assets) => {
const svg = assets.find(([id]) => id === `commandIcon/${decl.id}`)?.[1];
if (!svg || disposed) return;
off();
off = registerAction({ ...action, icon: pluginIconName(pluginId, { light: svg, dark: null }) });
})
.catch(console.warn);
return () => {
disposed = true;
off();
};
},
Details: CommandsDetails,
}),
// Offered by every theme picker while the plugin is live; `followThemeSetting` applies the selected one.
defineUiPoint<ThemeDef>("themes", {
title: "Themes",
project: ({ pluginId, decl }, { plugin }) =>
addContributedTheme({
id: pluginThemeRef(pluginId, decl.id),
label: decl.name,
kind: decl.kind === "light" ? "light" : "dark",
origin: plugin.name,
}),
Details: ThemesDetails,
}),
defineUiPoint<IconThemeDecl>("iconThemes", {
title: "File Icon Themes",
project: ({ pluginId, decl }, { plugin }) =>
addIconTheme({
pluginId,
id: decl.id,
label: decl.label,
origin: plugin.name,
settingsPage: `${pluginSettingsPageId(pluginId)}.${decl.id.replace(/\./g, "-")}`,
}),
Details: IconThemesDetails,
}),
// Stored by the backend; listed here with a field per secret.
defineUiPoint<SecretDecl>("secrets", { title: "Secrets", Details: SecretsDetails }),
];
return () => disposers.reverse().forEach((d) => d());
}