дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
Thread.print lists only platform threads, so Dump Threads never showed virtual threads or deadlocks between them. On Java 21+ it now also takes the JSON thread dump (Thread.dump_to_file -format=json into an owner-only directory under the heap snapshot root, read with a size cap and always removed) and lists the virtual threads in a Virtual threads (n) group by container. On Java 25 the JSON carries lock owners, so monitor deadlocks between virtual threads show in the deadlock banner; on 21-24 the viewer says lock owners need Java 25. The JSON request is skipped while a debugger holds the JVM suspended, since it would hang the attach listener until resume. Part of #5593. Co-authored-by: ntbang0901 <[email protected]>
225 рядки
7.5 KiB
TypeScript
225 рядки
7.5 KiB
TypeScript
/**
|
||
* Code › Analyze Stack Trace or Thread Dump…: paste a trace (prefilled from
|
||
* the clipboard) and browse it in a console whose frames link to the sources,
|
||
* using the run console's link parser and navigation. Like IDEA, each trace
|
||
* is a tab of the Run tool window, next to the run sessions.
|
||
*/
|
||
import { useState } from "react";
|
||
import { create } from "zustand";
|
||
import { registerActions } from "@/platform/actions";
|
||
import { fontWeightOf } from "@/platform/editorSettings";
|
||
import { resolveMonoFont } from "@/platform/fonts";
|
||
import { useProject } from "@/platform/project";
|
||
import { registerOverlay, toolWindowService } from "@/workbench/contributions";
|
||
import { Dialog, T } from "@/ui";
|
||
import { ConsoleModel } from "./console";
|
||
import { ConsoleView } from "./ConsoleView";
|
||
import { findOutputLinks } from "./links";
|
||
import { useRun } from "./store";
|
||
import styles from "./StackTrace.module.css";
|
||
import { tx } from "@/platform/i18n";
|
||
import { readClipboardPlainText } from "@/platform/clipboard";
|
||
import { isThreadDump, parseThreadDump, type ThreadDump } from "./threadDump/parse";
|
||
import { threadDumpTab, type ThreadDumpSource, type ThreadDumpTab, type VirtualSource } from "./threadDump/store";
|
||
|
||
export interface TraceTab {
|
||
kind: "trace";
|
||
id: string;
|
||
title: string;
|
||
model: ConsoleModel;
|
||
}
|
||
|
||
/** A tab of the Run tool window that is not a run session: a stack trace or a thread dump. */
|
||
export type StackTraceTab = TraceTab | ThreadDumpTab;
|
||
|
||
interface StackTraceState {
|
||
tabs: StackTraceTab[];
|
||
/** Text of the open "Analyze Stack Trace" dialog, or null when closed. */
|
||
dialog: string | null;
|
||
}
|
||
|
||
export const useStackTraces = create<StackTraceState>(() => ({ tabs: [], dialog: null }));
|
||
|
||
let seq = 0;
|
||
|
||
/** Normalises pasted text: line endings, trailing blanks, surrounding empty lines. */
|
||
export function normalizeTrace(text: string): string {
|
||
return text
|
||
.replace(/\r\n?/g, "\n")
|
||
.split("\n")
|
||
.map((l) => l.replace(/\s+$/, ""))
|
||
.join("\n")
|
||
.replace(/^\n+|\n+$/g, "");
|
||
}
|
||
|
||
/** Tab title: the exception (or first) line, shortened. */
|
||
export function traceTitle(text: string): string {
|
||
const lines = text
|
||
.split("\n")
|
||
.map((l) => l.trim())
|
||
.filter(Boolean);
|
||
const head =
|
||
lines.find((l) => /(Exception|Error|panicked|Traceback|^Full thread dump)/.test(l) && !/^at\s/.test(l)) ??
|
||
lines[0] ??
|
||
"Stack trace";
|
||
// `java.lang.IllegalStateException: boom` → `IllegalStateException`
|
||
const m = /^(?:Exception in thread "[^"]*"\s+)?(?:[\w$]+\.)*([\w$]+(?:Exception|Error))\b/.exec(head);
|
||
const title = m ? m[1]! : head;
|
||
return title.length > 40 ? `${title.slice(0, 39)}…` : title;
|
||
}
|
||
|
||
/** Number of lines in `text` with a clickable source location. */
|
||
export function countFrames(text: string): number {
|
||
return text.split("\n").filter((l) => findOutputLinks(l).some((k) => k.kind === "file")).length;
|
||
}
|
||
|
||
function openTab(tab: StackTraceTab): string {
|
||
useStackTraces.setState((s) => ({ tabs: [...s.tabs, tab] }));
|
||
useRun.setState({ activeSession: tab.id });
|
||
return tab.id;
|
||
}
|
||
|
||
function addTrace(text: string, title: string): string {
|
||
const model = new ConsoleModel();
|
||
model.append({ kind: "stdout", text });
|
||
model.flush();
|
||
return openTab({ kind: "trace", id: `trace-${++seq}`, title, model });
|
||
}
|
||
|
||
function addThreads(
|
||
text: string,
|
||
title: string,
|
||
source: ThreadDumpSource | null,
|
||
dump: ThreadDump,
|
||
virtual: VirtualSource | null,
|
||
): string {
|
||
return openTab(threadDumpTab(`trace-${++seq}`, title, text, source, dump, virtual));
|
||
}
|
||
|
||
/** Opens a pasted trace, or a pasted thread dump in the thread viewer. */
|
||
export function addStackTrace(raw: string): string | null {
|
||
const text = normalizeTrace(raw);
|
||
if (!text) return null;
|
||
const dump = isThreadDump(text) ? parseThreadDump(text) : null;
|
||
return dump ? addThreads(text, tx("Thread dump"), null, dump, null) : addTrace(text, traceTitle(text));
|
||
}
|
||
|
||
/** Opens a dump in the thread viewer; text that holds no thread opens as a plain trace. */
|
||
export function addThreadDump(
|
||
raw: string,
|
||
meta: { title: string; source: ThreadDumpSource | null; virtual?: VirtualSource },
|
||
): string {
|
||
const text = normalizeTrace(raw);
|
||
const dump = parseThreadDump(text);
|
||
return dump ? addThreads(text, meta.title, meta.source, dump, meta.virtual ?? null) : addTrace(text, meta.title);
|
||
}
|
||
|
||
/** Replaces a thread dump tab, e.g. with its next dump or the user's selection. */
|
||
export function updateThreadDump(id: string, update: (tab: ThreadDumpTab) => ThreadDumpTab) {
|
||
useStackTraces.setState((s) => ({
|
||
tabs: s.tabs.map((t) => (t.id === id && t.kind === "threads" ? update(t) : t)),
|
||
}));
|
||
}
|
||
|
||
export function closeStackTrace(id: string) {
|
||
useStackTraces.setState((s) => ({ tabs: s.tabs.filter((t) => t.id !== id) }));
|
||
}
|
||
|
||
async function openDialog() {
|
||
let clip = "";
|
||
try {
|
||
clip = await readClipboardPlainText();
|
||
} catch {
|
||
// clipboard unavailable or denied: start empty
|
||
}
|
||
useStackTraces.setState({ dialog: countFrames(normalizeTrace(clip)) > 0 ? clip : "" });
|
||
}
|
||
|
||
function StackTraceDialogOverlay() {
|
||
const initial = useStackTraces((s) => s.dialog);
|
||
if (initial === null) return null;
|
||
return <StackTraceDialog initial={initial} />;
|
||
}
|
||
|
||
function StackTraceDialog({ initial }: { initial: string }) {
|
||
const [text, setText] = useState(initial);
|
||
const editor = useProject((s) => s.settings?.editor);
|
||
const { family, size } = resolveMonoFont(undefined, editor);
|
||
const close = () => useStackTraces.setState({ dialog: null });
|
||
const ok = () => {
|
||
if (!addStackTrace(text)) return;
|
||
close();
|
||
toolWindowService().show("run", true);
|
||
};
|
||
return (
|
||
<Dialog
|
||
open
|
||
title="Analyze Stack Trace"
|
||
onClose={close}
|
||
width={634}
|
||
minWidth={340}
|
||
minHeight={220}
|
||
resizable="both"
|
||
className={styles.dialog}
|
||
buttons={[
|
||
{ label: "Analyze", role: "default", disabled: !text.trim(), onClick: ok },
|
||
{ label: "Cancel", role: "cancel" },
|
||
]}
|
||
>
|
||
<div className={styles.form}>
|
||
<label className={styles.label} htmlFor="stacktrace-text">
|
||
<T>Put a stack trace or a complete thread dump here:</T>
|
||
</label>
|
||
<textarea
|
||
id="stacktrace-text"
|
||
className={styles.text}
|
||
spellCheck={false}
|
||
style={{
|
||
fontFamily: family,
|
||
fontSize: size,
|
||
fontWeight: fontWeightOf(editor?.fontWeight, 400),
|
||
lineHeight: editor?.lineHeight ? `${editor.lineHeight}px` : undefined,
|
||
tabSize: editor?.tabSize || 4,
|
||
}}
|
||
value={text}
|
||
onChange={(e) => setText(e.target.value)}
|
||
data-autofocus=""
|
||
/>
|
||
</div>
|
||
</Dialog>
|
||
);
|
||
}
|
||
|
||
/** A trace tab's console in the Run tool window. */
|
||
export function StackTracePanel({ tab }: { tab: TraceTab }) {
|
||
const root = useProject((s) => s.project?.root ?? "/");
|
||
return (
|
||
<ConsoleView
|
||
model={tab.model}
|
||
version={tab.model.size}
|
||
softWrap={false}
|
||
follow={false}
|
||
onFollowChange={() => {}}
|
||
cwd={root}
|
||
aria-label={tx`Stack trace ${tab.title}`}
|
||
/>
|
||
);
|
||
}
|
||
|
||
export function activateStackTrace(): () => void {
|
||
const disposers = [
|
||
registerOverlay({ id: "run.stackTraceDialog", component: StackTraceDialogOverlay }),
|
||
registerActions([
|
||
{
|
||
id: "analyze.stackTrace",
|
||
title: "Analyze Stack Trace or Thread Dump…",
|
||
category: "Code",
|
||
when: "projectOpen",
|
||
keywords: ["stacktrace", "exception", "thread dump", "unscramble"],
|
||
run: () => void openDialog(),
|
||
},
|
||
]),
|
||
];
|
||
return () => disposers.reverse().forEach((d) => d());
|
||
}
|