Файли
openidea/src/features/run/services.tsx
T
l0ng-aiтаClaude Opus 5.5 f665beb17e fix(run): rerun with the configuration as edited, and drop deleted ones from Services (#1579)
Rerunning a run tab launched the configuration snapshot taken when the tab first ran, so edits from Edit Configurations were ignored until the tab was closed. Every rerun path (Run tool window, Services, the exit notification, Debug from a run tab, Rerun Failed Tests / selected tests, Update Application's restart) now uses the saved configuration with the same id, falling back to the snapshot when it was deleted or never saved. Services also drops a configuration deleted after it ran once its run has ended; ad-hoc runs (build tasks, external tools) still show.

Fixes #1497

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 23:12:13 +08:00

591 рядки
20 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
/**
* Run configurations in the Services tool window (IDEA's Run Dashboard): Spring
* Boot by default, the configuration types added there ("Add Service › Run
* Configuration Type"), the types of this window's run sessions and the
* configurations that ran before (kept per project across restarts), one group
* each, with run / debug / stop / rerun per configuration. A configuration that
* ran shows its console in the detail pane, a running web application its HTTP port.
*/
import { useEffect, useMemo } from "react";
import { create } from "zustand";
import { executeAction } from "@/platform/actions";
import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { projectLocation, useRemote } from "@/platform/remote";
import { tx, useT, useTxTemplate } from "@/platform/i18n";
import { Button, EmptyState, T } from "@/ui";
import type { MenuItem } from "@/ui";
import {
toolWindowService,
notifications,
useRunConfigTypes,
useDebugRunSessions,
type DebugServiceSession,
type ServiceItemAction,
type ServiceProviderContribution,
type ServiceTreeItem,
} from "@/workbench/contributions";
import { commandLine, configIcon, KIND_OPTIONS, kindLabel } from "./configs";
import { SessionPanel } from "./RunView";
import { showApplicationUpdate } from "./applicationUpdate";
import { isUpdatable } from "./updatePolicies";
import {
configRemoved,
loadConfigs,
persistTemporary,
rerunConfig,
startRun,
stopSession,
useRun,
type RunSession,
} from "./store";
import {
currentServiceSession,
currentServiceSessions,
liveServiceSession,
serviceDebugger,
serviceSessions,
stopServiceSessions,
type ServiceSession,
} from "./serviceSessions";
import { isDebugOnly } from "./types";
import {
currentServiceOrder,
moveServiceOrder,
orderServices,
saveServiceOrder,
useServiceOrder,
type ServiceOrder,
} from "./serviceOrder";
import styles from "./RunServices.module.css";
export const RUN_PROVIDER = "runConfigurations";
const TYPE_PREFIX = "run:type:";
const CONFIG_PREFIX = "run:config:";
const STORAGE_KEY = "openidea.services.runTypes:";
const RAN_KEY = "openidea.services.ran:";
/** Types shown in Services until the user changes the list. */
export const DEFAULT_TYPES: readonly string[] = ["spring-boot"];
// ---------------------------------------------------------------------------
// Types added to Services, per project
const useAddedTypes = create<{ root: string | null; types: string[] }>(() => ({ root: null, types: [] }));
/** The project's types; Spring Boot until the user changes the list. */
export function readTypes(root: string): string[] {
try {
const raw = localStorage.getItem(STORAGE_KEY + root);
if (raw === null) return [...DEFAULT_TYPES];
const v: unknown = JSON.parse(raw);
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
} catch {
return [...DEFAULT_TYPES];
}
}
function addedTypes(root: string | null): string[] {
const s = useAddedTypes.getState();
return s.root === root ? s.types : root ? readTypes(root) : [];
}
function setAddedTypes(types: string[]) {
const root = useProject.getState().project?.root ?? null;
useAddedTypes.setState({ root, types });
if (!root) return;
try {
localStorage.setItem(STORAGE_KEY + root, JSON.stringify(types));
} catch {
/* storage unavailable */
}
}
const currentTypes = () => addedTypes(useProject.getState().project?.root ?? null);
export function addType(kind: string) {
const types = currentTypes();
if (!types.includes(kind)) setAddedTypes([...types, kind]);
}
export function removeType(kind: string) {
setAddedTypes(currentTypes().filter((t) => t !== kind));
}
// ---------------------------------------------------------------------------
// Configurations that ran, per project (shown again after a restart)
const useRanConfigs = create<{ root: string | null; ids: string[] }>(() => ({ root: null, ids: [] }));
/** The project's previously run configuration ids, most recent last. */
export function readRan(root: string): string[] {
try {
const raw = localStorage.getItem(RAN_KEY + root);
if (raw === null) return [];
const v: unknown = JSON.parse(raw);
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
} catch {
return [];
}
}
function ranIds(root: string | null): string[] {
const s = useRanConfigs.getState();
return s.root === root ? s.ids : root ? readRan(root) : [];
}
/** Records a run, so its configuration is back in Services after a restart. */
export function recordRun(configId: string) {
const root = useProject.getState().project?.root ?? null;
const ids = [...ranIds(root).filter((id) => id !== configId), configId];
useRanConfigs.setState({ root, ids });
if (!root) return;
try {
localStorage.setItem(RAN_KEY + root, JSON.stringify(ids));
} catch {
/* storage unavailable */
}
}
// ---------------------------------------------------------------------------
// Project removal: a workspace member's data leaves with it
/** Whether `path` is inside the directory `root` (a removed member, not a sibling with a shared prefix). */
function insideRoot(path: string, root: string): boolean {
return path === root || path.startsWith(`${root}/`);
}
/**
* Drops a removed workspace member's data from Services: stops and forgets its
* sessions (a finished one still groups the tree), removes its temporary
* configurations, reloads (the backend no longer lists the member) and clears
* the added types and remembered runs that would otherwise render empty groups.
*/
export async function cleanupRemovedProject(removedRoot: string): Promise<void> {
const { configs, sessions, temporary } = useRun.getState();
const ofRemoved = (c: RunConfig) => !!c.cwd && insideRoot(c.cwd, removedRoot);
const removedIds = new Set(configs.filter(ofRemoved).map((c) => c.id));
const removedSessions = sessions.filter((s) => removedIds.has(s.config.id));
for (const s of removedSessions) if (busy(s)) await stopSession(s.id);
if (removedSessions.length) {
const ids = new Set(removedSessions.map((s) => s.id));
useRun.setState((s) => ({ sessions: s.sessions.filter((x) => !ids.has(x.id)) }));
}
if (temporary.some((id) => removedIds.has(id))) {
const temporaryLeft = temporary.filter((id) => !removedIds.has(id));
useRun.setState({
configs: useRun.getState().configs.filter((c) => !removedIds.has(c.id)),
temporary: temporaryLeft,
});
persistTemporary();
}
// The kinds the member had configurations of; after the reload those that are
// left without any (and without a session) are removed from the added types.
const kinds = new Set(configs.filter(ofRemoved).map((c) => c.kind));
await loadConfigs();
const { configs: fresh, sessions: liveSessions } = useRun.getState();
const liveKinds = new Set([...fresh.map((c) => c.kind), ...liveSessions.map((s) => s.config.kind)]);
for (const kind of kinds) if (!liveKinds.has(kind)) removeType(kind);
const root = useProject.getState().project?.root ?? null;
if (root) {
const freshIds = new Set(fresh.map((c) => c.id));
const ids = ranIds(root).filter((id) => freshIds.has(id));
if (ids.length !== ranIds(root).length) {
useRanConfigs.setState({ root, ids });
try {
localStorage.setItem(RAN_KEY + root, JSON.stringify(ids));
} catch {
/* storage unavailable */
}
}
}
}
// ---------------------------------------------------------------------------
// Tree
const busy = (s: RunSession) => s.status === "running" || s.status === "starting";
export function sessionStatus(s: RunSession | undefined): string | undefined {
if (!s) return undefined;
if (busy(s)) return s.status === "starting" ? "Starting" : "Running";
if (s.stopped) return "Stopped";
if (s.status === "failed") return s.exitCode === null ? "Failed" : `Failed (exit ${s.exitCode})`;
return "Finished";
}
/** A node's grey text: the HTTP port of a running web application, else the state. */
export function sessionDetail(s: RunSession | undefined): string | undefined {
return s && busy(s) && s.httpPort ? `:${s.httpPort}` : sessionStatus(s);
}
function executionDetail(s: ServiceSession | undefined): string | undefined {
if (!s) return undefined;
const debug = serviceDebugger(s);
if (debug?.status === "paused") return "Suspended";
if (debug)
return s.run && busy(s.run) && s.run.httpPort
? `:${s.run.httpPort}`
: debug.status === "starting"
? "Starting"
: "Debugging";
return s.run ? sessionDetail(s.run) : "Finished";
}
/**
* Groups by configuration type: added types list all their configurations, other
* types only those that ran. A default type (Spring Boot) without configurations is hidden.
* A configuration deleted since it ran (`removed`) stays only while its run is live.
*/
export function runServiceItems(
configs: readonly RunConfig[],
sessions: readonly RunSession[],
added: readonly string[],
ran: readonly string[] = [],
order: ServiceOrder = {},
debug: readonly DebugServiceSession[] = [],
removed: (id: string) => boolean = () => false,
): ServiceTreeItem[] {
const executions = serviceSessions(sessions, debug);
const latest = currentServiceSessions(executions);
const kinds = [...added];
const shown = (s: ServiceSession) => liveServiceSession(s) || !removed(s.config.id);
for (const s of executions) if (shown(s) && !kinds.includes(s.config.kind)) kinds.push(s.config.kind);
for (const id of ran) {
const kind = configs.find((c) => c.id === id)?.kind;
if (kind && !kinds.includes(kind)) kinds.push(kind);
}
return kinds.flatMap((kind) => {
const entries: RunConfig[] = added.includes(kind)
? configs.filter((c) => c.kind === kind)
: ran.map((id) => configs.find((c) => c.id === id)).filter((c): c is RunConfig => !!c && c.kind === kind);
for (const s of latest.values())
if (s.config.kind === kind && shown(s) && !entries.some((c) => c.id === s.config.id)) entries.push(s.config);
if (!entries.length && DEFAULT_TYPES.includes(kind)) return [];
const children = orderServices(entries, order[kind]).map((c): ServiceTreeItem => {
const s = latest.get(c.id);
return {
key: CONFIG_PREFIX + c.id,
label: c.name,
icon: serviceDebugger(s) ? "debug" : s && liveServiceSession(s) ? "run" : configIcon(c),
detail: executionDetail(s),
dim: !s || !liveServiceSession(s),
};
});
const running = entries.filter((c) => {
const s = latest.get(c.id);
return !!s && liveServiceSession(s);
}).length;
return [
{
key: TYPE_PREFIX + kind,
label: kindLabel(kind),
icon: configIcon({ kind, isTest: false }),
detail: running ? tx`${running} running` : undefined,
expanded: true,
children,
},
];
});
}
function useRoots(): ServiceTreeItem[] {
const root = useProject((s) => s.project?.root ?? null);
useRemote((s) => s.session);
const order = useServiceOrder(projectLocation(root));
const configs = useRun((s) => s.configs);
const sessions = useRun((s) => s.sessions);
const debug = useDebugRunSessions((s) => s.serviceSessions);
const types = useAddedTypes((s) => s.types);
const typesRoot = useAddedTypes((s) => s.root);
const ran = useRanConfigs((s) => s.ids);
const ranRoot = useRanConfigs((s) => s.root);
useEffect(() => {
if (typesRoot !== root) useAddedTypes.setState({ root, types: root ? readTypes(root) : [] });
if (ranRoot !== root) useRanConfigs.setState({ root, ids: root ? readRan(root) : [] });
}, [root, typesRoot, ranRoot]);
return useMemo(
() =>
runServiceItems(
configs,
sessions,
typesRoot === root ? types : [],
ranRoot === root ? ran : [],
order,
debug,
configRemoved,
),
[configs, sessions, types, typesRoot, ran, ranRoot, root, order, debug],
);
}
interface Resolved {
kind: string | null;
config: RunConfig | null;
session: ServiceSession | undefined;
/** Sessions of a group's configurations. */
sessions: ServiceSession[];
}
function resolve(item: ServiceTreeItem): Resolved {
const { configs, sessions } = useRun.getState();
const executions = serviceSessions(sessions, useDebugRunSessions.getState().serviceSessions);
if (item.key.startsWith(TYPE_PREFIX)) {
const kind = item.key.slice(TYPE_PREFIX.length);
return { kind, config: null, session: undefined, sessions: executions.filter((s) => s.config.kind === kind) };
}
const id = item.key.slice(CONFIG_PREFIX.length);
const session = currentServiceSession(id, executions);
const config = configs.find((c) => c.id === id) ?? session?.config ?? null;
return { kind: config?.kind ?? null, config, session, sessions: session ? [session] : [] };
}
function showOutput(s: RunSession) {
useRun.setState({ activeSession: s.id });
toolWindowService().show("run", true);
}
/** Runs (or reruns, in its tab) a configuration; the output stays in Services instead of opening Run. */
function run(r: Resolved) {
const debug = serviceDebugger(r.session);
if (debug) debug.rerun?.();
else if (r.session?.run) {
const s = r.session.run;
void startRun(rerunConfig(s), s.id, s.baseConfig, { show: false });
} else if (r.config) void startRun(r.config, undefined, undefined, { show: false });
}
function debug(r: Resolved) {
const session = serviceDebugger(r.session);
if (session) session.rerun?.();
else if (r.config) void executeAction("run.debugConfig", r.config);
}
function actions(item: ServiceTreeItem): ServiceItemAction[] {
const r = resolve(item);
const running = r.sessions.filter(liveServiceSession);
const stop = {
id: "stop",
title: "Stop",
icon: "stop",
disabled: !running.length,
run: () => void stopServiceSessions(running),
};
if (!r.config) return [stop];
const live = !!r.session && liveServiceSession(r.session);
const debugging = serviceDebugger(r.session);
return [
{
id: "run",
title: live ? "Rerun" : "Run",
icon: live ? "rerun" : "run",
disabled: debugging ? !debugging.rerun : isDebugOnly(r.config),
run: () => run(r),
},
{ id: "debug", title: "Debug", icon: "debug", disabled: !!debugging && !debugging.rerun, run: () => debug(r) },
stop,
...(isUpdatable(r.config)
? [
{
id: "update",
title: "Update Application",
icon: "refresh",
disabled: !live,
run: () => showApplicationUpdate(r.session?.run?.id ?? (debugging ? `debug:${debugging.id}` : undefined)),
},
]
: []),
];
}
function menu(item: ServiceTreeItem): MenuItem[] {
const items: MenuItem[] = actions(item).map((a) => ({
id: a.id,
label: a.title,
icon: a.icon,
disabled: a.disabled,
run: a.run,
}));
const r = resolve(item);
if (!r.config && r.kind && currentTypes().includes(r.kind)) {
const kind = r.kind;
items.push({ kind: "separator" }, { label: "Remove from Services", icon: "close", run: () => removeType(kind) });
}
if (r.config) {
const config = r.config;
const session = r.session?.run;
const debuggerSession = serviceDebugger(r.session) ?? r.session?.debug.at(-1);
items.push(
{ kind: "separator" },
{
label: "Show in Run Tool Window",
icon: "toolwindow-run",
disabled: !session,
run: () => session && showOutput(session),
},
{
label: "Show in Debug Tool Window",
icon: "toolwindow-debug",
disabled: !debuggerSession,
run: () => debuggerSession?.show(),
},
{ label: "Edit Configuration…", icon: "edit", run: () => void executeAction("run.editConfigs", config.id) },
);
}
return items;
}
function RunDetail({ item }: { item: ServiceTreeItem }) {
// Re-render on session changes.
useRun((s) => s.sessions);
const debugViews = useDebugRunSessions();
const Console = debugViews.Console;
const t = useT();
const txTemplate = useTxTemplate();
const r = resolve(item);
if (!r.config)
return (
<EmptyState title={kindLabel(r.kind ?? "")}>
<div>
{item.children?.length
? t("run.services.configurationCount", { count: item.children.length })
: txTemplate("No configurations of this type")}
</div>
</EmptyState>
);
// The configuration ran: its console, as in the Run tool window.
if (r.session?.run) {
const execution = r.session;
const d = serviceDebugger(execution);
return (
<SessionPanel
key={execution.run!.id}
session={execution.run!}
onRerun={d ? d.rerun : undefined}
onDebug={d ? d.rerun : undefined}
onStop={d ? () => void stopServiceSessions([execution]) : undefined}
/>
);
}
const d = r.session?.debug[0];
if (d && Console)
return (
<div className={styles.debugConsole}>
<Console key={d.id} sessionId={d.id} />
</div>
);
return (
<div className={styles.detail}>
<dl className={styles.facts}>
<dt>
<T>Configuration</T>
</dt>
<dd>{r.config.name}</dd>
<dt>
<T>Type</T>
</dt>
<dd>
<T>{kindLabel(r.config.kind)}</T>
</dd>
<dt>
<T>Command</T>
</dt>
<dd className={styles.mono}>{commandLine(r.config)}</dd>
<dt>
<T>Status</T>
</dt>
<dd>
<T>Not started</T>
</dd>
</dl>
<div className={styles.actions}>
<Button icon="run" disabled={isDebugOnly(r.config)} onClick={() => run(r)}>
Run
</Button>
<Button icon="debug" onClick={() => debug(r)}>
Debug
</Button>
</div>
</div>
);
}
/** "Add Service › Run Configuration Type": the project's types first, then the rest. */
function addMenu(): MenuItem[] {
const added = currentTypes();
const used = [...new Set(useRun.getState().configs.map((c) => c.kind))];
const known = [...KIND_OPTIONS.map((o) => o.value), ...useRunConfigTypes.getState().types.keys()];
const kinds = [...new Set([...used, ...known])].filter((k) => k !== "compound" && !added.includes(k));
const item = (kind: string): MenuItem => ({
label: kindLabel(kind),
icon: configIcon({ kind, isTest: false }),
run: () => addType(kind),
});
const submenu: MenuItem[] = [
...kinds.filter((k) => used.includes(k)).map(item),
...(used.some((k) => kinds.includes(k)) ? [{ kind: "separator" } as MenuItem] : []),
...kinds
.filter((k) => !used.includes(k))
.sort((a, b) => kindLabel(a).localeCompare(kindLabel(b)))
.map(item),
];
return [{ label: "Run Configuration Type", icon: "toolwindow-run", disabled: !submenu.length, submenu }];
}
export const runServiceProvider: ServiceProviderContribution = {
id: RUN_PROVIDER,
order: 0,
useRoots,
actions,
menu,
activate: (item) => {
const r = resolve(item);
if (r.config && !(r.session && liveServiceSession(r.session)) && !isDebugOnly(r.config)) run(r);
},
detail: RunDetail,
addMenu,
reorder: {
canMove: (source, target) => {
if (!source.key.startsWith(CONFIG_PREFIX) || !target.key.startsWith(CONFIG_PREFIX) || source.key === target.key)
return false;
const from = resolve(source),
to = resolve(target);
return !!from.config && !!to.config && from.kind === to.kind;
},
move: (source, target, position) => {
if (!runServiceProvider.reorder!.canMove(source, target)) return;
const location = projectLocation(useProject.getState().project?.root);
const kind = resolve(source).kind;
if (!location || !kind) return;
const { configs, sessions } = useRun.getState();
const order = currentServiceOrder(location);
const group = runServiceItems(
configs,
sessions,
currentTypes(),
ranIds(useProject.getState().project?.root ?? null),
order,
useDebugRunSessions.getState().serviceSessions,
).find((g) => g.key === TYPE_PREFIX + kind);
const ids = group?.children?.map((c) => c.key.slice(CONFIG_PREFIX.length)) ?? [];
const from = source.key.slice(CONFIG_PREFIX.length),
to = target.key.slice(CONFIG_PREFIX.length);
if (!ids.includes(from) || !ids.includes(to)) return;
if (
!saveServiceOrder(location, { ...order, [kind]: moveServiceOrder(order[kind] ?? [], ids, from, to, position) })
) {
notifications().notify({
group: "run",
level: "warning",
title: "Cannot save service order",
body: "The order will be kept for this session only.",
});
}
},
},
};