Файли
openidea/src/features/debugger/state.ts
T
Bert Verhelstтаbertyhell ad685ea19e feat(debugger): Disassembly view and instruction stepping for native debugging (#6694)
Native debug sessions whose adapter supports disassemble get a Disassembly tab showing the selected frame's instructions with the program counter highlighted, following stepping and frame selection, including frames without source. Show Disassembly is on the Frames list; Step Over Instruction and Step Into Instruction send steps with instruction granularity and are disabled with a reason when the adapter lacks it. Frames keep instructionPointerReference; when the PC is not where the requested window expects it, the view reads again from the PC.

lldb-dap sends instruction bytes already spaced and pads mnemonics unevenly; the view strips the spacing before grouping the bytes and pads mnemonics to one width.

Part of #5922

Co-authored-by: bertyhell <[email protected]>
2026-11-29 15:54:29 +08:00

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

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
/**
* Debug sessions as the UI sees them, fed by `IdeEvent::Debug` and by pulls
* (threads, frames, locals) after each stop.
*/
import { tx } from "@/platform/i18n";
import { logError } from "@/platform/errorLog";
import { workflowSettings } from "@/platform/workflowSettings";
import { executeAction, getAction } from "@/platform/actions";
import { create } from "zustand";
import { AnsiStream, appendSpans, type Span } from "@/ui/ansi";
import { setContext } from "@/platform/context";
import {
call,
commands,
isTauri,
isCancelled,
type DebugCapabilities,
type DebugEvent,
type DebugSessionId,
type JvmBackendState,
type LaunchConfig,
type RunId,
type RunConfig,
type Scope,
type StackFrame,
type ThreadInfo,
type Variable,
} from "@/platform/ipc";
import { confirmTerminate } from "@/workbench/confirmTerminate";
import {
maybeEditorService,
notifications,
runOutput,
SERVICES_WINDOW,
toolWindowService,
useDebugRunSessions,
} from "@/workbench/contributions";
import { startedPort } from "@/platform/serverPort";
import { breakpointsOf, consumeTemporary, flushBreakpoints, refreshStates, resetStatuses } from "./breakpoints/store";
import { interpolateLog, logParts, suspends } from "./breakpoints/model";
import { syncSpecial, useSpecialBreakpoints } from "./breakpoints/special";
import { refreshExceptionFilters } from "./breakpoints/exceptions";
import { flashTaskbarForBreakpoint, stopTaskbarFlash } from "./taskbarFlash";
import { useProject } from "@/platform/project";
import { isRemoteWindow } from "@/platform/remote";
import { queueNetworkEvent } from "./js/network";
import { setRefused } from "./js/refusals";
import {
browserLaunch,
installedDebugBrowser,
isBrowserLaunch,
isNodeLaunch,
launchedBrowser,
launchedUrl,
loopbackUrls,
} from "./browser";
import { missingAdapter } from "./missingAdapter";
import { startFailureMessage } from "./startFailure";
import { evaluateWithImports, forgetImports } from "./classImports";
import { JAVA_ADAPTER } from "./java";
import { listensAgain, reconnects, remoteWaitingNote } from "./remote";
import { isTracing, markTraceStop } from "./streams/streamStore";
export type SessionStatus = "starting" | "running" | "paused" | "stopping" | "terminated";
export interface DebugSession {
id: DebugSessionId;
name: string;
/** Originating configuration, retained for toolbar targeting and prepared debug reruns. */
runConfig?: RunConfig;
startedAt?: number;
/** When it terminated. */
endedAt?: number;
adapter: string;
parent: DebugSessionId | null;
/** Launch configuration (root sessions), used by Rerun. */
launch: LaunchConfig | null;
/** The program runs in a terminal the IDE gave it: the console types into it while it runs. */
programInput?: boolean;
/** Process the session is attached to (a Run tab's build tool); stopped with the session. */
process: RunId | null;
/** Stable Debug-tab slot; a restarted session inherits it even though its backend id changes. */
tabOrder?: number;
/** Pinned tab (root sessions): once finished, a later session opens a new tab instead of taking its place. */
pinned?: boolean;
/** Started in place from the Services tool window (root sessions): its stops show it there, not in the Debug window. */
inPlace?: boolean;
status: SessionStatus;
stoppedThread: number | null;
stopReason: string | null;
stopDescription: string | null;
/**
* Threads stopped alone (a `stopped` event without `allThreadsStopped`), oldest first. Adapters
* such as java-debug keep them suspended while another thread runs.
*/
suspendedThreads?: SuspendedThread[];
/** The last stop suspended every thread. */
allThreadsStopped?: boolean;
threads: ThreadInfo[];
selectedThread: number | null;
frames: StackFrame[];
/** Why the selected thread's frames could not be loaded (Threads & Variables offers a retry). */
framesError?: string | null;
selectedFrame: number | null;
/** Breakpoint hits in this session. */
hits: number;
/** `stopped` events of this session; unlike the global `stopSeq`, no other session or value edit moves it. */
stops: number;
exitCode: number | null;
/** What the adapter supports (fetched after start). */
caps: DebugCapabilities | null;
/** State of the backend that reads a JVM's objects; absent until the backend reports one. */
jvmBackend?: JvmBackendState;
/** Flutter: the app's VM Service, which DevTools connects to. */
vmServiceUri?: string;
/** Flutter: the device the app runs on. */
flutterDevice?: string | null;
/** A cancelled JDT build may have lost class-file deltas needed by this session. */
hotSwapNeedsRestart?: boolean;
/** `flutter debug_adapter` reported the app as started: it can take a hot reload. */
flutterAppStarted?: boolean;
}
export interface SuspendedThread {
id: number;
reason: string;
description: string | null;
}
export interface ConsoleLine {
id: number;
category: string;
/** Plain text without escape sequences. */
text: string;
/** `text` styled by its ANSI colours. */
spans: Span[];
/** A carriage return ended the output so far: the next text replaces the line. */
cr?: boolean;
}
interface DebugState {
sessions: Record<number, DebugSession>;
/** Session shown in the Debug tool window / title bar. */
active: DebugSessionId | null;
console: Record<number, ConsoleLine[]>;
/** Lines of a session's console dropped from the front, as the Run console counts them. */
consoleDropped: Record<number, number>;
watches: string[];
/** Incremented on every stop; views re-pull data when it changes. */
stopSeq: number;
/**
* Incremented when the adapter says it has new values for the suspended frame (`invalidated`).
* Separate from `stopSeq`: no stop happened, so nothing may count as changed and the Memory view stays put.
*/
variablesEpoch: number;
}
export const useDebug = create<DebugState>(() => ({
sessions: {},
active: null,
console: {},
consoleDropped: {},
watches: [],
stopSeq: 0,
variablesEpoch: 0,
}));
let tabOrderSeq = 0;
/** Allocates a Debug-tab slot that is independent of the backend's session ids. */
function allocateTabOrder() {
return ++tabOrderSeq;
}
/** Visible order key; test fixtures without a slot retain their former id order. */
export function tabOrderOf(s: Pick<DebugSession, "id" | "tabOrder">): number {
return s.tabOrder ?? s.id;
}
/** Sessions as their Debug tabs show: by their root's slot, so children stay next to their parent. */
export function inTabOrder<T extends Pick<DebugSession, "id" | "parent" | "tabOrder">>(sessions: readonly T[]): T[] {
const byId = new Map(sessions.map((s) => [s.id, s]));
const root = (s: T) => {
let cur = s;
for (let p = byId.get(cur.parent!); cur.parent != null && p; p = byId.get(cur.parent!)) cur = p;
return cur;
};
return [...sessions].sort(
(a, b) => tabOrderOf(root(a)) - tabOrderOf(root(b)) || tabOrderOf(a) - tabOrderOf(b) || a.id - b.id,
);
}
function sessionsInTabOrder(sessions: Record<number, DebugSession>): DebugSession[] {
return inTabOrder(Object.values(sessions));
}
/** Execution point of the selected frame, plus the frame's locals for inline values. */
interface ExecutionPoint {
path: string | null;
line: number;
/** The selected frame is the top frame (current position, not a caller). */
top: boolean;
values: Record<string, string>;
/** Full variables behind `values`, for the click-to-show popup. */
variables?: Record<string, Variable>;
}
export const useExecutionPoint = create<ExecutionPoint>(() => ({
path: null,
line: 0,
top: true,
values: {},
variables: {},
}));
/** Console buffer: at most this many physical lines per session. */
const MAX_CONSOLE_LINES = 50_000;
/** Longer lines are broken up, as in the Run console, so one blob can't stall rendering. */
export const MAX_LINE_LENGTH = 8_000;
/**
* Output of one session waiting for the next frame, in characters. A program printing faster
* than the console parses keeps only the newest output (the rest would be trimmed anyway), so
* the backlog and each frame's work stay bounded instead of growing with the flood.
*/
const MAX_PENDING_CHARS = 4 * 1024 * 1024;
let lineSeq = 0;
/** ANSI state per session and output category (a colour can span several output events). */
const ansiStreams = new Map<DebugSessionId, Map<string, AnsiStream>>();
/** Streamed output buffered until the next animation frame (one setState per frame). */
interface PendingOutput {
session: DebugSessionId;
category: string;
raw: string;
}
const pendingOutput: PendingOutput[] = [];
let outputFlushHandle: { raf: number; timeout: number } | null = null;
/** When the console last showed queued output (`performance.now()`). */
let lastOutputFlush = -Infinity;
function cancelOutputFlush() {
if (!outputFlushHandle) return;
cancelAnimationFrame(outputFlushHandle.raf);
clearTimeout(outputFlushHandle.timeout);
outputFlushHandle = null;
}
function ansiStream(session: DebugSessionId, category: string): AnsiStream {
let streams = ansiStreams.get(session);
if (!streams) ansiStreams.set(session, (streams = new Map()));
let stream = streams.get(category);
if (!stream) streams.set(category, (stream = new AnsiStream()));
return stream;
}
/** Styled output, keeping a carriage return (and erase-line) for the console to overwrite its line. */
function outputSpans(session: DebugSessionId, category: string, raw: string): Span[] {
const stream = ansiStream(session, category);
return stream.spans(stream.clean(raw).replace(/\r\n/g, "\n"));
}
// --- accessors ---------------------------------------------------------------
export function activeSession(): DebugSession | null {
const { active, sessions } = useDebug.getState();
return active != null ? (sessions[active] ?? null) : null;
}
export function isLive(s: DebugSession | null | undefined): boolean {
return !!s && s.status !== "terminated";
}
/** The session the Debug tool window's Stop acts on: the selected one while it runs (any live one when none is selected). */
export function stopTarget(): DebugSession | null {
const s = activeSession();
if (s) return isLive(s) ? s : null;
return Object.values(useDebug.getState().sessions).find(isLive) ?? null;
}
/** Whether the session with this id is still there and running, as of now. */
export const isLiveSession = (id: DebugSessionId) => isLive(useDebug.getState().sessions[id]);
/** Root (user-started) session of `s`. */
export function rootOf(s: DebugSession): DebugSession {
const { sessions } = useDebug.getState();
let cur = s;
while (cur.parent != null && sessions[cur.parent]) cur = sessions[cur.parent]!;
return cur;
}
function patch(id: DebugSessionId, p: Partial<DebugSession>) {
useDebug.setState((s) => {
const cur = s.sessions[id];
if (!cur) return s;
return { sessions: { ...s.sessions, [id]: { ...cur, ...p } } };
});
publishContext();
}
function blank(id: DebugSessionId, { tabOrder = allocateTabOrder(), ...p }: Partial<DebugSession> = {}): DebugSession {
return {
id,
name: "Debug",
startedAt: Date.now(),
adapter: "",
parent: null,
launch: null,
process: null,
tabOrder,
status: "starting",
stoppedThread: null,
stopReason: null,
stopDescription: null,
threads: [],
selectedThread: null,
frames: [],
selectedFrame: null,
hits: 0,
stops: 0,
exitCode: null,
caps: null,
...p,
};
}
// Sessions this window owns. The backend sends a session's events only to the window
// that started it; as a second line of defence, events of other sessions are dropped.
/** `debugStart` calls in flight: their root session's id is not known yet. */
let pendingStarts = 0;
/** Sessions adopted while a start was in flight, not yet confirmed by its result. */
const provisional = new Set<DebugSessionId>();
/** Every session id this window has owned (late events of dropped sessions are ignored). */
const owned = new Set<DebugSessionId>();
/** Registers a session as owned by this window (idempotent). */
export function adoptSession(id: DebugSessionId, p: Partial<DebugSession> = {}): DebugSession {
const existing = useDebug.getState().sessions[id];
if (existing) return existing;
owned.add(id);
const s = blank(id, { status: "running", ...p });
void loadCapabilities(id);
useDebug.setState((st) => ({
sessions: { ...st.sessions, [id]: s },
active: st.active == null || !isLive(st.sessions[st.active]) ? id : st.active,
}));
publishContext();
return s;
}
/**
* The session an event belongs to, adopting it when it is this window's: a child
* (announced by `started` with a parent) of one of its sessions, or the root
* session of a start still in flight here (its build output and `started` arrive
* before `debugStart` returns the id). Anything else is not ours.
*/
function ownSession(id: DebugSessionId, event: DebugEvent): DebugSession | null {
const st = useDebug.getState();
const existing = st.sessions[id];
if (existing) return existing;
// `started` is a session's first event, sent once when the backend creates it: never a late event
// of a forgotten session, though its id may be one (another backend numbers from 1 again).
if (owned.has(id) && event.kind !== "started") return null;
if (event.kind === "started" && event.parent != null) {
const parent = st.sessions[event.parent];
if (!parent) return null;
const child = adoptSession(id, { name: event.name, adapter: event.adapter, parent: event.parent });
// A process attached again after its restart takes the finished one's place (one tab, its output kept).
if (reconnects(rootOf(parent).runConfig))
for (const s of Object.values(st.sessions)) {
if (s.parent !== event.parent || isLive(s)) continue;
flushConsoleOutput();
useDebug.setState((cur) => ({
console: { ...cur.console, [id]: [...(cur.console[s.id] ?? []), ...(cur.console[id] ?? [])] },
}));
removeSession(s.id);
}
return child;
}
if (pendingStarts === 0) return null;
provisional.add(id);
// The new root session takes the tab it replaces now, not once `debugStart` returns.
const replaced = pendingReplacements[0];
// A Python Debug Server's `debugStart` returns once a program connects: until then it is starting.
// The start this session belongs to (by name): a server still waiting must not lend its configuration.
const at = event.kind === "started" ? pendingConfigs.findIndex((c) => c.name === event.name) : -1;
const rc = at >= 0 ? pendingConfigs.splice(at, 1)[0]!.runConfig : undefined;
const waiting = listensAgain(rc) ? { runConfig: rc, status: "starting" as const } : {};
const slot = { ...waiting, ...(replaced ? { tabOrder: replaced.tabOrder, pinned: replaced.pinned } : {}) };
const s =
event.kind === "started"
? adoptSession(id, { name: event.name, adapter: event.adapter, ...slot })
: adoptSession(id, slot);
if (replaced) {
// Listening again for the next program keeps the output of the previous ones.
const previous = replaced.session;
if (waiting.runConfig && previous != null)
useDebug.setState((cur) => ({
console: { ...cur.console, [id]: [...(cur.console[previous] ?? []), ...(cur.console[id] ?? [])] },
}));
takeReplacement(replaced);
useDebug.setState({ active: id });
publishContext();
}
if (waiting.runConfig) appendConsole(id, "system", `${remoteWaitingNote(rc, false, true)}\n`);
return s;
}
/**
* A start finished (`id` on success): sessions no start claimed are failed starts' leftovers,
* kept as terminated or, with `discard`, removed.
*/
function settleStart(id: DebugSessionId | null, discard = false) {
pendingStarts = Math.max(0, pendingStarts - 1);
if (id != null) provisional.delete(id);
if (pendingStarts > 0) return;
const leftovers = [...provisional];
provisional.clear();
if (discard) {
useDebug.setState((st) => {
const sessions = { ...st.sessions };
const console = { ...st.console };
for (const s of leftovers) {
delete sessions[s];
delete console[s];
ansiStreams.delete(s);
}
return { sessions, console, active: st.active != null && sessions[st.active] ? st.active : null };
});
publishContext();
return;
}
for (const s of leftovers) if (isLive(useDebug.getState().sessions[s])) markTerminated(s);
}
/** The session being rerun: its tab is the one the new session takes, pinned or not. */
let rerunOf: DebugSessionId | null = null;
/** Sessions whose Rerun is in progress: their tab stays selected when they terminate. */
const rerunning = new Set<DebugSessionId>();
interface ReplacedTab {
pinned?: boolean;
tabOrder?: number;
/** The finished tab, kept until the new session takes its place (`defer`). */
session?: DebugSessionId;
}
/** Finished tabs whose starting replacements have no session yet, oldest start first. */
const pendingReplacements: ReplacedTab[] = [];
/** The run configurations of starts in flight, oldest first. */
const pendingConfigs: { name: string; runConfig?: RunConfig }[] = [];
/** The new session is shown: the finished tab it replaces gives way. */
function takeReplacement(r: ReplacedTab | undefined) {
if (!r) return;
const i = pendingReplacements.indexOf(r);
if (i >= 0) pendingReplacements.splice(i, 1);
if (r.session != null && useDebug.getState().sessions[r.session]) removeSession(r.session);
r.session = undefined;
}
/**
* As IDEA reuses run content: a new session takes the place of one finished tab (with its
* children) that isn't pinned, preferring the same configuration id, then its display name,
* then the selected one; other finished tabs stay. The returned slot lets the new backend
* session keep the tab where the replaced one was.
*/
function replaceFinished(name: string, configId?: string, defer = false): ReplacedTab {
const { sessions, active } = useDebug.getState();
const own = rerunOf != null ? sessions[rerunOf] : undefined;
rerunOf = null;
// Rerun's Stop waits for the adapter, even if this window has not handled its terminated event yet.
if (own) {
const tabOrder = tabOrderOf(own);
if (defer) return { pinned: own.pinned, tabOrder, session: own.id };
removeSession(own.id);
return { pinned: own.pinned, tabOrder };
}
const finished = sessionsInTabOrder(sessions).filter(
(s) => s.parent == null && !isLive(s) && !s.pinned && !pendingReplacements.some((r) => r.session === s.id),
);
const selected = active != null ? sessions[active] : undefined;
const ordered =
selected && finished.includes(selected) ? [selected, ...finished.filter((s) => s !== selected)] : finished;
const reused =
(configId == null ? undefined : ordered.find((s) => s.runConfig?.id === configId)) ??
ordered.find((s) => s.name === name) ??
ordered[0];
const pinned = workflowSettings().run.pinTabs || undefined;
if (!reused) return { pinned };
const tabOrder = tabOrderOf(reused);
if (defer) return { pinned, tabOrder, session: reused.id };
removeSession(reused.id);
return { pinned, tabOrder };
}
/**
* A JDWP agent in server mode listens again, on a new port, when its debugger detaches; a
* debugger that detaches as the JVM exits leaves an announcement of a JVM about to be gone.
* An attach to `process` this soon after a session on it ended may be to such a JVM.
*/
const RELISTEN_MS = 3000;
export function justDetached(process: RunId | null | undefined): boolean {
if (process == null) return false;
const now = Date.now();
return Object.values(useDebug.getState().sessions).some(
(s) => s.process === process && s.status === "terminated" && s.endedAt != null && now - s.endedAt < RELISTEN_MS,
);
}
export function publishContext() {
const s = activeSession();
const retained = sessionsInTabOrder(useDebug.getState().sessions);
useDebugRunSessions.setState({
serviceSessions: retained.flatMap((session) => {
if (session.parent != null || !session.runConfig) return [];
const paused =
isLive(session) && retained.some((child) => child.status === "paused" && rootOf(child).id === session.id);
return [
{
id: session.id,
config: session.runConfig,
startedAt: session.startedAt ?? 0,
status: paused ? ("paused" as const) : session.status,
processId: session.process,
httpPort: sessionHttpPort(session.id),
rerun: session.runConfig || session.launch ? () => void rerunSession(session.id) : null,
rerunInPlace:
session.runConfig || session.launch ? () => void rerunSession(session.id, { show: false }) : null,
stop: (options?: { stopProcess?: boolean }) => stopSession(session.id, options),
show: () => {
if (!useDebug.getState().sessions[session.id]) return;
selectSession(session.id);
toolWindowService().show("debug", true);
},
},
];
}),
sessions: retained
.filter((session) => session.parent == null && isLive(session))
.map((session) => {
const paused = Object.values(useDebug.getState().sessions).find(
(child) => child.status === "paused" && rootOf(child).id === session.id,
);
return {
id: session.id,
configId: session.runConfig?.id ?? null,
name: session.runConfig?.name ?? session.name,
startedAt: session.startedAt ?? 0,
status: session.status,
paused: !!paused,
rerun: session.runConfig || session.launch ? () => void rerunSession(session.id) : null,
stop: () => void stopSession(session.id),
resume: () => {
selectSession(paused?.id ?? session.id);
void executeAction("debug.resume");
},
};
}),
});
const anyLive = Object.values(useDebug.getState().sessions).some(isLive);
setContext("debugSessionActive", anyLive);
// Stop acts on the selected session tab, so a finished one doesn't stop another session.
setContext("debugCanStop", !!stopTarget());
setContext("debugSessionRunning", s?.status === "running");
setContext("debugSessionPaused", s?.status === "paused");
// Dart and Flutter sessions: Hot Reload / Hot Restart.
setContext("debugSessionDart", !!s && rootOf(s).adapter === "dart");
setContext("debugCanRerun", !!s && !!(rootOf(s).runConfig || rootOf(s).launch));
setContext(
"debugCanHotSwap",
Object.values(useDebug.getState().sessions).some((x) => isLive(x) && !!x.caps?.hotCodeReplace),
);
setContext("debugHasVmService", !!s && isLive(s) && !!rootOf(s).vmServiceUri);
// Refresh Memory View acts on the selected session only.
setContext("debugHasJvmMemory", !!s && isLive(s) && sessionSupports("jvmMemory", s));
setContext("debugHasJsPage", !!s && isLive(s) && sessionSupports("jsPage", s));
setContext("debugStreamTracing", !!s && isTracing(s.id));
setContext(
"debugAnyStreamTracing",
Object.values(useDebug.getState().sessions).some((x) => isTracing(x.id)),
);
setContext("debugCanTraceStream", canTraceStream(s));
}
// --- console -----------------------------------------------------------------
/**
* The HTTP port the session's application announced on its console ("Tomcat started on
* port 8080"), the same embedded web server line the Run console is parsed for. Kept per
* session, so the Services node keeps the port after the line scrolls out of the buffer.
*/
const announcedPorts = new Map<DebugSessionId, number>();
export function sessionHttpPort(id: DebugSessionId): number | undefined {
let port: number | undefined;
for (const line of useDebug.getState().console[id] ?? []) {
const found = startedPort(line.text);
if (found !== null) port = found;
}
if (port !== undefined) announcedPorts.set(id, port);
else port = announcedPorts.get(id);
return port;
}
/** Republishes Services metadata only when a console announced a port it had not shown yet. */
function republishForPorts() {
const published = useDebugRunSessions.getState().serviceSessions;
if (published.some((d) => d.httpPort !== sessionHttpPort(d.id))) publishContext();
}
/** Sessions attached to a process Run started: their Console follows its output. */
const processOutput = new Map<DebugSessionId, () => void>();
/** Shows the output of the Run process `process` in the Console of `session`, as a launched program's. */
function followProcessOutput(session: DebugSessionId, process: RunId) {
processOutput.get(session)?.();
const unsubscribe = runOutput()?.subscribe(process, (kind, text) => appendConsoleQueued(session, kind, text));
if (unsubscribe) processOutput.set(session, unsubscribe);
}
function unfollowProcessOutput(session: DebugSessionId) {
processOutput.get(session)?.();
processOutput.delete(session);
}
export function appendConsole(session: DebugSessionId, category: string, raw: string) {
if (!raw) return;
flushConsoleOutput();
const spans = outputSpans(session, category, raw);
const text = spans.map((sp) => sp.text).join("");
if (!text) return;
useDebug.setState((s) => {
const prev = s.console[session] ?? [];
const next = [...prev];
appendConsoleLines(next, category, spans);
const trimmed = trimConsole(next);
return {
console: { ...s.console, [session]: next },
...(trimmed
? { consoleDropped: { ...s.consoleDropped, [session]: (s.consoleDropped[session] ?? 0) + trimmed } }
: {}),
};
});
republishForPorts();
}
/**
* Queues streamed debuggee output: ANSI parsing and the console store update happen
* once per animation frame (or timer while unfocused), with pending chunks merged per
* (session, category), so a flood of `output` events can't saturate React.
*/
export function appendConsoleQueued(session: DebugSessionId, category: string, raw: string) {
if (!raw) return;
const last = pendingOutput[pendingOutput.length - 1];
if (last && last.session === session && last.category === category) {
last.raw += raw;
} else {
pendingOutput.push({ session, category, raw });
}
capPendingOutput(session);
if (outputFlushHandle === null) {
// Next frame, or later when Settings › Tools › Terminal › Max FPS asks for fewer frames (#5897).
const fps = Number(workflowSettings().terminal.maxFps);
const since = performance.now() - lastOutputFlush;
const wait = fps > 0 && since >= 0 ? Math.round(1000 / fps) - since : 0;
outputFlushHandle =
wait > 16
? { raf: 0, timeout: window.setTimeout(flushConsoleOutput, wait) }
: { raf: requestAnimationFrame(flushConsoleOutput), timeout: window.setTimeout(flushConsoleOutput, 100) };
}
}
/** Lines dropped from the front of the pending output, per session, until the next flush. */
const pendingDropped = new Map<DebugSessionId, number>();
/** Drops the oldest pending output of `session` past [MAX_PENDING_CHARS], whole lines at a time. */
function capPendingOutput(session: DebugSessionId) {
let total = 0;
for (const chunk of pendingOutput) if (chunk.session === session) total += chunk.raw.length;
let excess = total - MAX_PENDING_CHARS;
while (excess > 0) {
const at = pendingOutput.findIndex((chunk) => chunk.session === session);
const chunk = pendingOutput[at]!;
// Up to the end of the line that holds the excess; a chunk without a later newline goes whole.
const end = chunk.raw.indexOf("\n", Math.min(excess, chunk.raw.length) - 1);
const cut = end < 0 ? chunk.raw.length : end + 1;
let lines = 0;
for (let i = chunk.raw.indexOf("\n"); i >= 0 && i < cut; i = chunk.raw.indexOf("\n", i + 1)) lines++;
pendingDropped.set(session, (pendingDropped.get(session) ?? 0) + lines);
if (cut >= chunk.raw.length) pendingOutput.splice(at, 1);
else chunk.raw = chunk.raw.slice(cut);
excess -= cut;
}
}
function flushConsoleOutput() {
cancelOutputFlush();
if (pendingOutput.length === 0) return;
lastOutputFlush = performance.now();
const chunks = pendingOutput.splice(0);
const dropped = new Map(pendingDropped);
pendingDropped.clear();
const printed: Array<[DebugSessionId, string]> = [];
useDebug.setState((s) => {
const consoleBySession = { ...s.console };
const droppedBySession = { ...s.consoleDropped };
for (const [session, count] of dropped)
if (s.sessions[session]) droppedBySession[session] = (droppedBySession[session] ?? 0) + count;
for (const { session, category, raw } of chunks) {
if (!s.sessions[session]) continue;
const spans = outputSpans(session, category, raw);
const text = spans.map((sp) => sp.text).join("");
if (!text) continue;
printed.push([session, text]);
const prev = consoleBySession[session] ?? [];
const next = [...prev];
appendConsoleLines(next, category, spans);
const trimmed = trimConsole(next);
if (trimmed) droppedBySession[session] = (droppedBySession[session] ?? 0) + trimmed;
consoleBySession[session] = next;
}
return { console: consoleBySession, consoleDropped: droppedBySession };
});
republishForPorts();
for (const [session, text] of printed) debugServerPage(session, text);
}
/**
* A browser launch shows as its page (`sessionTabs`), so a selected launch passes the selection
* to its page. Either may exist first: the page's `started` event can precede the launch's result.
*/
function selectBrowserPage(launch: DebugSessionId) {
const st = useDebug.getState();
if (st.active !== launch || !isBrowserLaunch(st.sessions[launch]?.launch ?? null)) return;
const page = Object.values(st.sessions).find((s) => s.parent === launch);
if (!page) return;
useDebug.setState({ active: page.id });
publishContext();
}
/** `url` as `location.href` spells it (`http://localhost:5173` → `http://localhost:5173/`). */
function canonicalUrl(url: string): string {
try {
return new URL(url).href;
} catch {
return url;
}
}
/**
* Debugs the page `launch` opens. A project has one browser of a kind under the debugger (a
* second one can't share its profile), so when it is already running its page goes to the URL
* instead and becomes the selected session.
*/
export async function startBrowserSession(
launch: LaunchConfig,
options: Parameters<typeof startSession>[1] = {},
): Promise<DebugSessionId | null> {
const { sessions } = useDebug.getState();
const browser = launchedBrowser(launch);
const running = Object.values(sessions).find(
(s) => s.parent == null && isLive(s) && s.launch?.cwd === launch.cwd && launchedBrowser(s.launch) === browser,
);
if (!running) return startSession(launch, options);
const page = Object.values(sessions).find((s) => s.parent === running.id && isLive(s));
if (!page) return running.id;
selectSession(page.id);
const url = launchedUrl(launch);
if (url) {
// The page may have moved on since the browser started (an earlier launch, a link): it
// compares its own address, so a page already there isn't reloaded. The address is made
// canonical here, the page's own `URL` may be anything.
const target = JSON.stringify(canonicalUrl(url));
const go = `location.href !== ${target} && location.assign(${target})`;
await call(commands.debugEvaluateIn(page.id, null, go, "repl")).catch(() => undefined);
}
return running.id;
}
/**
* What a debugged Node.js program has shown about its page: the URLs already asked, and the
* browser session on the one that answered (null while it starts, undefined until one does).
*/
interface ServerPage {
asked: Set<string>;
page: DebugSessionId | null | undefined;
}
const serverPages = new Map<DebugSessionId, ServerPage>();
/** URLs asked per run: a program that keeps logging addresses isn't probed without end. */
const SERVER_URLS_ASKED = 5;
/**
* Debugging a program that serves a page (a dev server behind an npm script, an app with
* server-side rendering) also debugs the page: each address of this machine it prints is
* asked whether it answers with an HTML document, and a browser session opens on the first
* that does. An API never gets one. The session ends with the server (`markTerminated`);
* closing the browser leaves the server running.
*/
function debugServerPage(id: DebugSessionId, output: string) {
if (!workflowSettings().debugger.debugServerPage || isRemoteWindow()) return;
const s = useDebug.getState().sessions[id];
const root = s && rootOf(s);
if (!root || !isLive(root) || !isNodeLaunch(root.launch)) return;
const known = serverPages.get(root.id) ?? { asked: new Set<string>(), page: undefined };
if (known.page !== undefined) return;
for (const url of loopbackUrls(output)) {
if (known.asked.has(url) || known.asked.size >= SERVER_URLS_ASKED) continue;
known.asked.add(url);
serverPages.set(root.id, known);
void openServerPage(root, known, url);
}
}
async function openServerPage(server: DebugSession, known: ServerPage, url: string) {
const isPage = await call(commands.webServesPage(url)).catch(() => false);
// Another address may have answered first, or the server stopped meanwhile.
if (!isPage || known.page !== undefined || serverPages.get(server.id) !== known) return;
known.page = null;
const root = useProject.getState().project?.root ?? server.launch?.cwd ?? "";
// The server's directory holds the page's sources; the session itself is the project's.
const launch = {
...browserLaunch(new URL(url).host, url, await installedDebugBrowser(), server.launch?.cwd ?? root),
cwd: root,
};
const before = useDebug.getState().sessions;
const page = await startBrowserSession(launch, { show: false }).catch(() => null);
// A browser the user was already debugging in is theirs to stop.
if (page == null || before[page]) return;
if (serverPages.get(server.id) === known) known.page = page;
else void stopSession(page);
}
/**
* Split styled output at real line breaks, retaining partial lines across events. As in the
* Run console, a carriage return makes the next text replace the line (progress bars).
*/
function appendConsoleLines(lines: ConsoleLine[], category: string, spans: Span[]) {
const last = lines.at(-1);
let line =
last && last.category === category && !last.text.endsWith("\n") ? { ...last, spans: [...last.spans] } : undefined;
if (line) lines[lines.length - 1] = line;
for (const span of spans) {
for (const piece of span.text.split(/(\r|\n)/)) {
if (piece === "\r") {
if (line) line.cr = true;
continue;
}
if (!piece) continue;
if (!line) {
line = { id: ++lineSeq, category, text: "", spans: [] };
lines.push(line);
}
if (line.cr) {
line.cr = undefined;
if (piece !== "\n") {
line.text = "";
line.spans = [];
}
}
let rest = piece;
while (rest) {
if (!line) {
line = { id: ++lineSeq, category, text: "", spans: [] };
lines.push(line);
}
const room = piece === "\n" ? 1 : MAX_LINE_LENGTH - line.text.length;
const part = rest.slice(0, Math.max(room, 0));
rest = rest.slice(part.length);
if (part) {
line.text += part;
line.spans = appendSpans(line.spans, [{ ...span, text: part }]);
}
// A full line continues on the next one.
if (rest || piece === "\n") line = undefined;
}
}
}
}
/** Drops the oldest lines once past the line or configured character cap; returns how many. */
function trimConsole(lines: ConsoleLine[]): number {
let drop = 0;
if (lines.length > MAX_CONSOLE_LINES) {
drop = lines.length - MAX_CONSOLE_LINES + Math.ceil(MAX_CONSOLE_LINES / 10);
}
const c = workflowSettings().console;
if (c.overrideBuffer) {
const limit = c.bufferKb * 1024;
let chars = 0;
for (let i = lines.length - 1; i >= 0; i--) {
chars += lines[i]!.text.length + 1;
if (chars > limit) {
drop = Math.max(drop, i + 1);
break;
}
}
}
if (drop > 0) lines.splice(0, drop);
return drop;
}
export function clearConsole(session: DebugSessionId) {
flushConsoleOutput();
ansiStreams.delete(session);
pendingDropped.delete(session);
useDebug.setState((s) => ({
console: { ...s.console, [session]: [] },
consoleDropped: { ...s.consoleDropped, [session]: 0 },
}));
}
// --- lifecycle ---------------------------------------------------------------
let preparationSeq = 0;
const preparations = new Map<DebugSessionId, AbortController>();
/** A visible session owns preparation, including its console and Stop, before DAP has an id. */
export async function startPreparedSession(
config: RunConfig,
prepare: (signal: AbortSignal, report: (text: string, kind?: "system" | "stderr") => void) => Promise<LaunchConfig>,
options: { show?: boolean } = {},
): Promise<DebugSessionId | null> {
const id = --preparationSeq as DebugSessionId;
const controller = new AbortController();
preparations.set(id, controller);
// The new tab takes the place of a finished one while its build runs, not once the adapter starts.
const reused = replaceFinished(config.name, config.id);
useDebug.setState((s) => ({
sessions: {
...s.sessions,
[id]: blank(id, {
name: config.name,
adapter: config.debugAdapter ?? "",
runConfig: config,
pinned: reused.pinned,
...(reused.tabOrder == null ? {} : { tabOrder: reused.tabOrder }),
inPlace: options.show === false,
}),
},
console: { ...s.console, [id]: [] },
consoleDropped: { ...s.consoleDropped, [id]: 0 },
active: id,
}));
publishContext();
try {
if (options.show !== false && workflowSettings().run.showOnStart) toolWindowService().show("debug");
} catch {
/* no workbench (tests) */
}
const report = (text: string, kind = "system") => {
if (!controller.signal.aborted && useDebug.getState().sessions[id]) appendConsole(id, kind, text);
};
try {
report(tx`Starting debugger for ${config.name}…` + "\n");
const launch = await prepare(controller.signal, report);
controller.signal.throwIfAborted();
return await startSession(launch, {
runConfig: config,
preparation: { id, signal: controller.signal },
show: options.show,
});
} catch (e) {
if (controller.signal.aborted || isCancelled(e)) return null;
report((e instanceof Error ? e.message : String(e)) + "\n", "stderr");
throw e;
} finally {
preparations.delete(id);
if (useDebug.getState().sessions[id]) markTerminated(id);
}
}
export async function startSession(
launch: LaunchConfig,
options: {
runConfig?: RunConfig;
preparation?: { id: DebugSessionId; signal: AbortSignal };
/** A process started for this session (e.g. Maven with a JDWP agent): Stop ends it too. */
process?: RunId | null;
/** Rerun repeats the launch (false for attaching to a process that is gone afterwards). */
rerunnable?: boolean;
/** `false`: keep the current tool window (the Services panel starts debuggers in place). */
show?: boolean;
/** Starts the backend session instead of `debugStart` (a notebook kernel's debugger). */
start?: () => Promise<DebugSessionId>;
} = {},
): Promise<DebugSessionId | null> {
if (!isTauri()) {
notifications().notify({ group: "run", level: "warning", title: "Debugging needs the desktop app" });
return null;
}
// Attaching to a JVM that may be gone: the finished session stays until the attach succeeds.
const afterDetach = justDetached(options.process);
const previousActive = useDebug.getState().active;
// The finished tab stays in place until the new session appears there.
let replaced =
!afterDetach && !options.preparation ? replaceFinished(launch.name, options.runConfig?.id, true) : undefined;
if (replaced?.session != null) pendingReplacements.push(replaced);
try {
if (options.show !== false && workflowSettings().run.showOnStart) toolWindowService().show("debug");
} catch {
// Workbench not ready (tests).
}
const startedAt = Date.now();
pendingStarts++;
try {
await flushBreakpoints();
options.preparation?.signal.throwIfAborted();
const adapterStarted = performance.now();
const pending = { name: launch.name, runConfig: options.runConfig };
pendingConfigs.push(pending);
const id = await (options.start?.() ?? call(commands.debugStart(launch))).finally(() => {
// Its session took the entry when it was announced, unless it never was.
const at = pendingConfigs.indexOf(pending);
if (at >= 0) pendingConfigs.splice(at, 1);
});
console.info("Debug adapter started", { name: launch.name, ms: performance.now() - adapterStarted });
owned.add(id);
if (afterDetach && !options.preparation) replaced = replaceFinished(launch.name, options.runConfig?.id);
if (options.preparation?.signal.aborted) {
await call(commands.debugStop(id)).catch(() => undefined);
settleStart(id);
if (useDebug.getState().sessions[id]) markTerminated(id);
return null;
}
flushConsoleOutput();
takeReplacement(replaced);
const preparation = options.preparation && useDebug.getState().sessions[options.preparation.id];
useDebug.setState((s) => {
const cur = s.sessions[id] ?? blank(id, { status: "running" });
const sessions = { ...s.sessions };
const console = { ...s.console };
if (preparation) {
console[id] = [...(console[preparation.id] ?? []), ...(console[id] ?? [])];
delete console[preparation.id];
delete sessions[preparation.id];
ansiStreams.delete(preparation.id);
}
return {
console,
sessions: {
...sessions,
[id]: {
...cur,
name: launch.name,
runConfig: options.runConfig,
startedAt: preparation?.startedAt ?? startedAt,
// The backend may start another adapter than the one asked for; `launch` keeps the request for Rerun.
adapter: cur.adapter || launch.adapter,
launch: options.rerunnable === false ? null : launch,
process: options.process ?? null,
pinned: preparation ? preparation.pinned : replaced?.pinned,
tabOrder: preparation?.tabOrder ?? replaced?.tabOrder ?? cur.tabOrder ?? allocateTabOrder(),
inPlace: options.show === false,
status: cur.status === "starting" ? "running" : cur.status,
},
},
active: id,
};
});
settleStart(id);
if (options.process != null) followProcessOutput(id, options.process);
selectBrowserPage(id);
publishContext();
void refreshExceptionFilters();
void loadCapabilities(id);
// Method breakpoints / watchpoints went out during configuration: pull their states.
void syncSpecial();
return id;
} catch (e) {
takeReplacement(replaced);
settleStart(null, afterDetach);
if (afterDetach) {
// The JVM that announced the port ended as its previous debugger detached.
console.info("Debugger not attached: the JVM is gone", { name: launch.name, error: e });
const { sessions, active } = useDebug.getState();
if (active == null && previousActive != null && sessions[previousActive])
useDebug.setState({ active: previousActive });
publishContext();
return null;
}
if (options.preparation?.signal.aborted || isCancelled(e)) return null;
if (options.preparation)
appendConsole(options.preparation.id, "stderr", (e instanceof Error ? e.message : String(e)) + "\n");
const missing = missingAdapter(launch.adapter, e);
if (missing) {
notifications().notify({
group: "run",
level: "warning",
title: missing.title,
body: missing.body,
key: "debug.start",
sticky: true,
actions: [
{
label: missing.action ?? "Install and Debug",
run: () => void executeAction("tools.install", missing.tool).then(() => startSession(launch, options)),
},
],
});
return null;
}
notifications().notify({
group: "run",
level: "error",
title: `Cannot start debugger for ${launch.name}`,
body: startFailureMessage(e),
key: "debug.start",
});
return null;
}
}
/** Stops an associated Run process through its owner, which records the user's stop intent. */
export async function stopAssociatedProcess(process: RunId): Promise<void> {
if (getAction("run.stopProcess")) await executeAction("run.stopProcess", process);
else await call(commands.runStop(process)).catch(() => undefined);
}
export async function stopSession(id: DebugSessionId, options: { stopProcess?: boolean } = {}) {
const s = useDebug.getState().sessions[id];
if (!s) return;
const root = rootOf(s);
const preparation = preparations.get(root.id);
if (preparation) {
preparation.abort();
appendConsole(root.id, "system", tx("Launch cancelled.") + "\n");
markTerminated(root.id);
return;
}
// Between the Stop press and the adapter's terminated event the session is shutting down:
// keep it live (Run stays disabled) and let the toolbar show the spinner.
for (const sid of new Set([root.id, s.id])) {
const target = useDebug.getState().sessions[sid];
if (target && isLive(target)) patch(sid, { status: "stopping" });
}
const stoppingProcess =
options.stopProcess !== false && root.process != null ? stopAssociatedProcess(root.process) : null;
try {
await call(commands.debugStop(root.id));
} catch (e) {
// Already gone: mark it finished locally.
console.warn("debugStop failed", e);
markTerminated(root.id);
}
await stoppingProcess;
}
/**
* Closes a session's tab: a live session is stopped first once the user agrees (the Run
* tab's question), then the window forgets it — and its children.
*/
export async function closeSessionTab(id: DebugSessionId): Promise<boolean> {
const s = useDebug.getState().sessions[id];
if (!s) return false;
if (isLive(s)) {
if (workflowSettings().run.confirmTerminate && !(await confirmTerminate(s.name))) return false;
await stopSession(s.id);
}
removeSession(s.id);
// As in IDEA, the tool window and its stripe button go away with its last tab.
if (!Object.keys(useDebug.getState().sessions).length) {
try {
toolWindowService().hide("debug", { removeFromStripe: true });
} catch {
// Workbench not ready (tests).
}
}
return true;
}
/** Pins or unpins a session's tab. */
export function pinSession(id: DebugSessionId, pinned: boolean) {
patch(id, { pinned });
}
/**
* Forgets a session and its descendants (Node's `pnpm` → `pnpm.cjs` → `rspack.js`); a selected
* one passes the selection to the tab on its left.
*/
export function removeSession(id: DebugSessionId) {
const st = useDebug.getState();
const gone = new Set<DebugSessionId>([id]);
for (let added = true; added;) {
added = false;
for (const s of sessionsInTabOrder(st.sessions))
if (s.parent != null && gone.has(s.parent) && !gone.has(s.id)) {
gone.add(s.id);
added = true;
}
}
const order = sessionsInTabOrder(st.sessions).map((s) => s.id);
const sessions: Record<number, DebugSession> = {};
for (const s of sessionsInTabOrder(st.sessions)) if (!gone.has(s.id)) sessions[s.id] = s;
const console = { ...st.console };
for (const goneId of gone) delete console[goneId];
const at = order.indexOf(id);
const neighbour =
order
.slice(0, at)
.reverse()
.find((n) => sessions[n]) ??
order.slice(at + 1).find((n) => sessions[n]) ??
null;
useDebug.setState({
sessions,
active: st.active != null && sessions[st.active] ? st.active : neighbour,
console,
});
for (const goneId of gone) {
owned.delete(goneId);
ansiStreams.delete(goneId);
unfollowProcessOutput(goneId);
}
updateExecutionPoint();
publishContext();
}
export async function rerunSession(id: DebugSessionId, options: { show?: boolean } = {}) {
const s = useDebug.getState().sessions[id];
if (!s) return;
const root = rootOf(s);
const launch = root.launch;
if (!root.runConfig && !launch) return;
rerunning.add(root.id);
try {
if (isLive(root)) await stopSession(root.id);
rerunOf = root.id;
// A session debugged in place from Services reruns there too.
const show = options.show ?? (root.inPlace ? false : undefined);
if (root.runConfig)
await executeAction("run.debugConfig", show === false ? { config: root.runConfig, show: false } : root.runConfig);
else await startSession(launch!, { show });
} finally {
rerunOf = null;
rerunning.delete(root.id);
}
}
async function loadCapabilities(id: DebugSessionId) {
try {
const caps = await call(commands.debugCapabilities(id));
if (useDebug.getState().sessions[id]) patch(id, { caps });
} catch {
// Session already gone.
}
}
/** Whether the active session's adapter supports `cap` (false while unknown). */
export function sessionSupports(cap: keyof DebugCapabilities, s: DebugSession | null = activeSession()): boolean {
return !!s?.caps?.[cap];
}
export function canTraceStream(s: DebugSession | null): boolean {
return !!s && s.status === "paused" && sessionSupports("streamTrace", s) && !isTracing(s.id);
}
/** The thread a paused session's actions act on. */
export function pausedThread(s: DebugSession): number | null {
return s.selectedThread ?? s.stoppedThread ?? s.threads[0]?.id ?? null;
}
export function isThreadSuspended(s: DebugSession, threadId: number): boolean {
if (s.status !== "paused") return false;
return !!s.allThreadsStopped || s.stoppedThread === threadId || !!s.suspendedThreads?.some((t) => t.id === threadId);
}
/** The selected frame of the paused session (top frame when none is selected). */
export function selectedFrame(s: DebugSession): StackFrame | null {
return s.frames.find((f) => f.id === s.selectedFrame) ?? s.frames[0] ?? null;
}
/** The frame a stop selects: the first with source. */
export function topFrame(frames: StackFrame[]): StackFrame | null {
return frames.find((f) => f.path && f.presentationHint !== "label") ?? frames[0] ?? null;
}
/** Sessions whose next stop ends an instruction step: it selects the frame that holds the program counter. */
const instructionSteps = new Set<DebugSessionId>();
/** The step about to be sent moves by one instruction (`false`: it was not sent after all). */
export function markInstructionStep(id: DebugSessionId, on: boolean) {
if (on) instructionSteps.add(id);
else instructionSteps.delete(id);
}
function markTerminated(id: DebugSessionId) {
stopTaskbarFlash();
instructionSteps.delete(id);
forgetImports(id);
const page = serverPages.get(id)?.page;
if (serverPages.delete(id) && page != null) void stopSession(page);
patch(id, { status: "terminated", endedAt: Date.now(), frames: [], selectedFrame: null, stoppedThread: null });
const st = useDebug.getState();
if (st.active === id && !rerunning.has(id)) {
// Prefer another live session (e.g. the parent of a finished child).
const other = sessionsInTabOrder(st.sessions).find(isLive);
if (other) useDebug.setState({ active: other.id });
}
if (!Object.values(useDebug.getState().sessions).some(isLive)) {
resetStatuses();
useSpecialBreakpoints.setState({ status: {} });
if (workflowSettings().debugger.hideOnTermination) {
try {
toolWindowService().hide("debug");
} catch {
// Workbench not ready (tests).
}
}
}
updateExecutionPoint();
publishContext();
}
// --- selection / pulls -------------------------------------------------------
export function selectSession(id: DebugSessionId) {
useDebug.setState({ active: id });
publishContext();
updateExecutionPoint();
}
export async function selectThread(id: DebugSessionId, threadId: number) {
patch(id, { selectedThread: threadId, frames: [], selectedFrame: null });
updateExecutionPoint();
await loadFrames(id, threadId, true);
}
export function selectFrame(id: DebugSessionId, frameId: number, reveal = true) {
patch(id, { selectedFrame: frameId });
updateExecutionPoint();
const s = useDebug.getState().sessions[id];
const frame = s?.frames.find((f) => f.id === frameId);
if (reveal && useDebug.getState().active === id && frame?.path) {
void maybeEditorService()?.openFile(frame.path, {
selection: { line: frame.line, col: frame.column },
focus: false,
});
}
void loadLocals(id, frameId);
}
/**
* `newStop`: false when returning to an earlier stop, whose breakpoint hit was handled when it happened.
* `exact`: select the innermost frame even without source (after an instruction step into a library).
*/
async function loadFrames(id: DebugSessionId, threadId: number, reveal: boolean, newStop = true, exact = false) {
if (useDebug.getState().sessions[id]?.framesError) patch(id, { framesError: null });
const before = useDebug.getState().sessions[id];
let frames: StackFrame[] = [];
let framesError: string | null = null;
try {
frames = await call(commands.debugStackTrace(id, threadId));
} catch (e) {
logError("Debugger stack trace", e);
framesError = e instanceof Error ? e.message : String(e);
}
const s = useDebug.getState().sessions[id];
if (!s || s.status !== "paused" || s.selectedThread !== threadId || s.frames !== before?.frames) return;
patch(id, { frames, framesError });
const top = exact ? (frames[0] ?? null) : topFrame(frames);
if (newStop && top?.path && (s.stopReason === "breakpoint" || s.stopReason === "function breakpoint")) {
void logSuspendingHit(id, top);
consumeTemporary(top.path, top.line);
}
if (top) selectFrame(id, top.id, reveal);
else updateExecutionPoint();
}
/**
* A suspending breakpoint that also logs: DAP logpoints never suspend, so the
* message is evaluated in the stopped frame and printed here instead.
*/
async function logSuspendingHit(id: DebugSessionId, frame: StackFrame) {
const bp = breakpointsOf(frame.path!).find((b) => b.line === frame.line && b.enabled);
if (!bp || !suspends(bp)) return;
for (const part of logParts(bp, frame.path!)) {
// oxlint-disable-next-line no-await-in-loop -- console lines must be appended in log-part order
const text = await interpolateLog(part, async (expr) => {
const v = await call(commands.debugEvaluateIn(id, frame.id, expr, "repl"));
return v.value;
});
appendConsole(id, "console", `${text}\n`);
}
}
async function loadThreads(id: DebugSessionId) {
try {
const threads = await call(commands.debugThreads(id));
patch(id, { threads });
} catch (e) {
console.warn("threads failed", e);
}
}
export interface FrameLocals {
scopes: Scope[];
/** Variables of the first non-expensive scope. */
locals: Variable[];
}
let frameLocalsMemo: { key: string; frames: readonly StackFrame[] | undefined; value: Promise<FrameLocals> } | null =
null;
/**
* Scopes and first-scope variables of `frameId` at the current stop. Inline values and the Variables view
* ask for the same frame on every stop; they share one request, since an adapter may take seconds to
* format a large local (#6170).
*/
export function frameLocals(id: DebugSessionId, frameId: number): Promise<FrameLocals> {
const { stopSeq, variablesEpoch, sessions } = useDebug.getState();
const key = `${id}:${frameId}:${stopSeq}:${variablesEpoch}`;
// Every stop loads a new stack: a stop counter that starts over cannot hand out an old answer.
const frames = sessions[id]?.frames;
if (frameLocalsMemo?.key !== key || frameLocalsMemo.frames !== frames) {
const value = (async () => {
const scopes = await call(commands.debugScopes(id, frameId));
const scope = scopes.find((sc) => !sc.expensive);
const locals = scope ? await call(commands.debugVariables(id, scope.variablesReference)) : [];
return { scopes, locals };
})();
frameLocalsMemo = { key, frames, value };
}
return frameLocalsMemo.value;
}
/** Locals of `frameId` (first non-expensive scope) for inline values. */
async function loadLocals(id: DebugSessionId, frameId: number) {
const frames = useDebug.getState().sessions[id]?.frames;
const values: Record<string, string> = Object.create(null);
const variables: Record<string, Variable> = Object.create(null);
try {
for (const v of (await frameLocals(id, frameId)).locals)
if (v.name && !Object.hasOwn(values, v.name)) {
values[v.name] = v.value;
variables[v.name] = v;
}
} catch {
// No inline values.
}
const s = useDebug.getState().sessions[id];
if (useDebug.getState().active !== id || s?.status !== "paused" || s.selectedFrame !== frameId || s.frames !== frames)
return;
useExecutionPoint.setState({ values, variables });
}
/** Show Execution Point (⌥F10): back to the suspended thread's top frame, revealed and focused. */
export async function showExecutionPoint(id: DebugSessionId) {
const s = useDebug.getState().sessions[id];
if (!s || s.status !== "paused" || s.stoppedThread == null) return;
if (s.selectedThread !== s.stoppedThread) {
patch(id, { selectedThread: s.stoppedThread, frames: [], selectedFrame: null });
updateExecutionPoint();
await loadFrames(id, s.stoppedThread, false);
}
const cur = useDebug.getState().sessions[id];
const top = cur?.frames.find((f) => f.path && f.presentationHint !== "label");
if (!cur || !top) return;
selectFrame(id, top.id, false);
await revealFrame(top, true);
}
/** Opens a frame's source at its line (Jump to Source, F4). */
export async function revealFrame(frame: StackFrame, focus: boolean) {
if (!frame.path) return;
await maybeEditorService()?.openFile(frame.path, { selection: { line: frame.line, col: frame.column }, focus });
}
export function updateExecutionPoint() {
const s = activeSession();
const frame = s && s.status === "paused" ? s.frames.find((f) => f.id === s.selectedFrame) : undefined;
if (!s || !frame || !frame.path) {
if (useExecutionPoint.getState().path !== null)
useExecutionPoint.setState({ path: null, values: {}, variables: {} });
return;
}
const top = s.frames.find((f) => f.path && f.presentationHint !== "label")?.id === frame.id;
const cur = useExecutionPoint.getState();
if (cur.path === frame.path && cur.line === frame.line && cur.top === top) return;
useExecutionPoint.setState({ path: frame.path, line: frame.line, top, values: {}, variables: {} });
}
/** Invalidate suspended data before sending a command that resumes execution. */
export async function resumeExecution(id: DebugSessionId, request: () => Promise<unknown>) {
const before = useDebug.getState().sessions[id];
if (!before || before.status !== "paused") return;
const frames: StackFrame[] = [];
patch(id, { status: "running", frames, selectedFrame: null, stoppedThread: null });
updateExecutionPoint();
try {
await request();
} catch (e) {
const current = useDebug.getState().sessions[id];
// A stop/continue/termination received during the request owns the newer state.
if (current?.status === "running" && current.frames === frames) {
patch(id, {
status: before.status,
frames: before.frames,
selectedFrame: before.selectedFrame,
stoppedThread: before.stoppedThread,
});
updateExecutionPoint();
if (before.selectedFrame != null) void loadLocals(id, before.selectedFrame);
}
throw e;
}
}
// --- watches -------------------------------------------------------------------
export function addWatch(expression: string) {
const e = expression.trim();
if (!e) return;
useDebug.setState((s) => (s.watches.includes(e) ? s : { watches: [...s.watches, e] }));
persistWatches();
}
export function removeWatch(expression: string) {
useDebug.setState((s) => ({ watches: s.watches.filter((w) => w !== expression) }));
persistWatches();
}
export function removeAllWatches() {
useDebug.setState({ watches: [] });
persistWatches();
}
/** Watches used to be one list for every project; it is only read now, as a project's first list. */
const SHARED_WATCH_KEY = "openidea.debugger.watches";
const watchKey = (root: string) => `${SHARED_WATCH_KEY}:${root}`;
/** The project whose watches are loaded; without one they aren't stored. */
let watchRoot: string | null = null;
function persistWatches() {
if (watchRoot == null) return;
try {
localStorage.setItem(watchKey(watchRoot), JSON.stringify(useDebug.getState().watches));
} catch {
// ignore
}
}
function storedWatches(key: string): string[] | null {
try {
const stored = localStorage.getItem(key);
const raw = stored == null ? null : (JSON.parse(stored) as unknown);
return Array.isArray(raw) ? raw.filter((w): w is string => typeof w === "string") : null;
} catch {
return null;
}
}
/** The watches of the project at `root`. */
export function loadWatches(root: string | null) {
watchRoot = root;
const own = root == null ? [] : storedWatches(watchKey(root));
useDebug.setState({ watches: own ?? storedWatches(SHARED_WATCH_KEY) ?? [] });
if (own == null) persistWatches();
}
/**
* "Set Value" (F2 in the variables tree): `setVariable` in `container`, or
* `setExpression` on the evaluate name. Refreshes variables, watches and inline values.
*/
export async function setVariableValue(
target: { container: number; name: string; evaluateName: string | null },
value: string,
session: DebugSession | null = activeSession(),
): Promise<Variable> {
if (!session || session.status !== "paused") throw new Error("The debugger is not suspended");
const result = await call(
commands.debugSetVariable(
session.id,
target.container,
target.name,
target.evaluateName,
session.selectedFrame,
value,
),
);
useDebug.setState((st) => ({ stopSeq: st.stopSeq + 1 }));
if (session.selectedFrame != null) void loadLocals(session.id, session.selectedFrame);
return result;
}
/** Whether the console types into the session's program (it runs, in a terminal the IDE gave it). */
export function readsProgramInput(s: DebugSession): boolean {
return !!s.programInput && s.status === "running";
}
/** Types `text` into the session's program; its terminal echoes it to the console. */
export async function sendProgramInput(session: DebugSession, text: string): Promise<void> {
await call(commands.debugSendInput(session.id, text));
}
export async function evaluate(
expression: string,
context: "repl" | "watch" | "hover" | "clipboard",
session: DebugSession | null = activeSession(),
): Promise<Variable> {
if (!session || !isLive(session)) throw new Error("No active debug session");
const run = (expr: string) => call(commands.debugEvaluateIn(session.id, session.selectedFrame, expr, context));
return session.adapter === JAVA_ADAPTER ? evaluateWithImports(session.id, expression, run) : run(expression);
}
/** Settings › Debugger › Focus application on breakpoint. */
function focusAppWindow() {
if (!isTauri()) return;
void import("@tauri-apps/api/window")
.then(async ({ getCurrentWindow }) => {
const w = getCurrentWindow();
if (await w.isMinimized()) await w.unminimize();
await w.setFocus();
})
.catch(() => undefined);
}
// --- events ----------------------------------------------------------------------
export function handleDebugEvent(id: DebugSessionId, event: DebugEvent) {
const s = ownSession(id, event);
if (!s) return;
switch (event.kind) {
case "started": {
if (!s.launch) patch(id, { name: event.name, adapter: event.adapter, parent: event.parent });
if (event.parent != null) selectBrowserPage(event.parent);
break;
}
case "initialized":
if (s.status === "starting") patch(id, { status: "running" });
break;
case "flutterAppStarted":
patch(id, { flutterAppStarted: true });
break;
case "stopped": {
const isBp = event.reason === "breakpoint" || event.reason === "function breakpoint";
const alone = (s.suspendedThreads ?? []).filter((t) => t.id !== event.threadId);
if (!event.allThreadsStopped)
alone.push({ id: event.threadId, reason: event.reason, description: event.description });
patch(id, {
status: "paused",
suspendedThreads: event.allThreadsStopped ? [] : alone,
allThreadsStopped: event.allThreadsStopped,
stoppedThread: event.threadId,
selectedThread: event.threadId,
stopReason: event.reason,
stopDescription: event.description,
frames: [],
selectedFrame: null,
hits: s.hits + (isBp ? 1 : 0),
stops: s.stops + 1,
});
useDebug.setState((st) => ({ active: id, stopSeq: st.stopSeq + 1 }));
publishContext();
updateExecutionPoint();
void loadThreads(id);
// The stop a stream trace ends in would bring the source tab over the trace tab that shows its result.
void loadFrames(
id,
event.threadId,
!markTraceStop(id, event.threadId, s.stops + 1),
true,
instructionSteps.delete(id),
);
const dbg = workflowSettings().debugger;
try {
// A session debugged in place from Services shows its debugger there (#4773).
if (dbg.showOnBreakpoint) toolWindowService().show(rootOf(s).inPlace ? SERVICES_WINDOW : "debug");
} catch {
// ignore
}
// Attention for a background window: focusing the app and flashing the taskbar are
// alternatives (IDEA), so a window configured to grab focus does not also flash.
if (dbg.focusAppOnBreakpoint) focusAppWindow();
else if (isBp) flashTaskbarForBreakpoint();
break;
}
case "continued": {
const cur = useDebug.getState().sessions[id]!;
if (cur.status === "terminated") break;
const rest = event.allThreadsContinued ? [] : (cur.suspendedThreads ?? []).filter((t) => t.id !== event.threadId);
if (!event.allThreadsContinued && event.threadId !== (cur.selectedThread ?? cur.stoppedThread)) {
patch(id, { suspendedThreads: rest });
break;
}
stopTaskbarFlash();
const next = rest.at(-1);
if (next) {
// Like IDEA, the session stays suspended on a thread its own breakpoint still holds.
patch(id, {
status: "paused",
suspendedThreads: rest,
stoppedThread: next.id,
selectedThread: next.id,
stopReason: next.reason,
stopDescription: next.description,
frames: [],
selectedFrame: null,
});
useDebug.setState((st) => ({ stopSeq: st.stopSeq + 1 }));
publishContext();
updateExecutionPoint();
void loadThreads(id);
void loadFrames(id, next.id, true, false);
break;
}
patch(id, {
status: "running",
frames: [],
selectedFrame: null,
stoppedThread: null,
suspendedThreads: [],
allThreadsStopped: false,
});
updateExecutionPoint();
break;
}
case "output":
appendConsoleQueued(id, event.category, event.output);
break;
case "thread":
if (s.status === "paused") void loadThreads(id);
break;
case "programInput":
patch(id, { programInput: true });
break;
case "breakpointsChanged":
void refreshStates(event.path);
break;
case "exited":
patch(id, { exitCode: event.code });
appendConsole(id, "system", `\nProcess finished with exit code ${event.code}\n`);
break;
case "terminated": {
// The connected program ended by itself (not Stop, not a wait cancelled or failed):
// a Python Debug Server waits for the next one.
const connected = s.status === "running" || s.status === "paused";
const again = s.parent == null && connected && listensAgain(s.runConfig) && !rerunning.has(id);
markTerminated(id);
if (again) void rerunSession(id);
break;
}
case "capabilities":
void loadCapabilities(id);
break;
case "jvmBackend":
patch(id, { jvmBackend: event.state });
break;
case "jsNetwork":
queueNetworkEvent(id, event.event);
break;
case "flutterVmService":
patch(id, { vmServiceUri: event.uri, flutterDevice: event.device });
break;
case "flutterNavigate":
// Focus stays in the inspector, where the next widget gets picked.
void maybeEditorService()?.openFile(event.path, {
selection: { line: event.line, col: event.column },
preview: true,
focus: false,
});
break;
case "jsNetworkUnavailable":
setRefused(id, "network", "");
break;
case "invalidated":
if (s.status !== "paused") break;
if (event.areas.length && !event.areas.some((a) => a === "variables" || a === "all")) break;
useDebug.setState((st) => ({ variablesEpoch: st.variablesEpoch + 1 }));
if (s.selectedFrame != null) void loadLocals(id, s.selectedFrame);
break;
}
}
/** The window switched projects: stops its sessions and forgets them (late events stay ignored via `owned`). */
export function resetSessions() {
const { sessions } = useDebug.getState();
for (const s of Object.values(sessions)) if (s.parent == null && isLive(s)) void stopSession(s.id);
for (const id of [...processOutput.keys()]) unfollowProcessOutput(id);
pendingOutput.length = 0;
cancelOutputFlush();
ansiStreams.clear();
announcedPorts.clear();
serverPages.clear();
pendingDropped.clear();
useDebug.setState({ sessions: {}, active: null, console: {}, consoleDropped: {}, stopSeq: 0, variablesEpoch: 0 });
useExecutionPoint.setState({ path: null, line: 0, top: true, values: {}, variables: {} });
publishContext();
}
/** Breakpoint ↔ session glue: unverified look only makes sense while debugging. */
export function sessionsRunning(): boolean {
return Object.values(useDebug.getState().sessions).some(isLive);
}