дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 10:07:11 +02:00
feat(run): debug Node.js on SSH, Docker and Compose run targets (#6919)
Debug on a Node.js configuration or a .js / .ts file run whose run target is SSH, Docker or Compose now debugs the program there, extending the Python flow. A js-debug configuration starts node with --inspect-brk on a free port (0.0.0.0 inside the container, published on this machine's loopback only; the host's loopback over the existing SSH forward). The run prints the project folder on the target as a system line, which the frontend reads to map sources before attaching js-debug. tsx is refused for now (it hangs once js-debug attaches); other programs get an error naming the fix. Closes #6901 Co-authored-by: wildcatDownstairs <[email protected]> Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
1 джерело
f5bb97babd
коміт
9b578c2fad
23 files changed
+476
-83
No files matched your search
@@ -454,7 +454,10 @@ async fn start_inner(
|
||||
if ide_run::is_python_kind(&config.kind) {
|
||||
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
|
||||
}
|
||||
let config = container::prepare(host, &project.root, target, config).await?;
|
||||
let (config, note) = container::prepare(host, &project.root, target, config).await?;
|
||||
if let Some(note) = note {
|
||||
on_output(OutputChunk::System { text: format!("{note}\n") });
|
||||
}
|
||||
let encoding = settings.console.encoding;
|
||||
let options = StartOptions {
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
|
||||
@@ -6,8 +6,8 @@ use ide_core::remote_settings::{RunTarget, RunTargetKind};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_docker::DockerEndpoint;
|
||||
use ide_remote::docker::{
|
||||
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, compose_container_root,
|
||||
compose_service, container_config, container_name, default_container_root,
|
||||
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, NODE_DEBUG_FOLDER,
|
||||
compose_container_root, compose_service, container_config, container_name, default_container_root, node_debug,
|
||||
};
|
||||
use ide_remote::target::DEBUG_PARAM;
|
||||
use ide_run::RunConfig;
|
||||
@@ -16,15 +16,21 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// `config` rewritten to run in a new container of `target`'s image or service.
|
||||
pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config: RunConfig) -> IdeResult<RunConfig> {
|
||||
/// `config` rewritten to run in a new container of `target`'s image or service, and for a
|
||||
/// Node.js debug run the line telling the debugger the project folder in the container.
|
||||
pub(super) async fn prepare(
|
||||
host: &Host,
|
||||
root: &Path,
|
||||
target: RunTarget,
|
||||
config: RunConfig,
|
||||
) -> IdeResult<(RunConfig, Option<String>)> {
|
||||
if config.kind == "dotnet" || config.kind == "dotnet-test" {
|
||||
return Err(IdeError::invalid(".NET Project requires the local machine"));
|
||||
}
|
||||
let debug = config.extras.params.get(DEBUG_PARAM).is_some_and(|v| v == "true");
|
||||
if debug && config.debug_adapter.as_deref() != Some("debugpy") {
|
||||
if debug && config.debug_adapter.as_deref() != Some("debugpy") && !node_debug(&config) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"'{}' can't be debugged in a container: only Python run configurations can",
|
||||
"'{}' can't be debugged in a container: only Python and Node.js run configurations can",
|
||||
config.name
|
||||
)));
|
||||
}
|
||||
@@ -41,7 +47,8 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
let (service_env, service_ports) = server_context(&data_dir, &root, &target, &config);
|
||||
let name = container_name(&config.id, &unique());
|
||||
let debugging = if debug { Some(Debugging::prepare(&data_dir)?) } else { None };
|
||||
container_config(
|
||||
let note = (debug && node_debug(&config)).then(|| format!("{NODE_DEBUG_FOLDER}{container_root}"));
|
||||
let config = container_config(
|
||||
&config,
|
||||
&ContainerRun {
|
||||
target: &target,
|
||||
@@ -60,7 +67,8 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
debugpy: d.debugpy.as_deref(),
|
||||
}),
|
||||
},
|
||||
)
|
||||
)?;
|
||||
Ok((config, note))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -33,12 +33,13 @@ pub struct ContainerRun<'a> {
|
||||
pub name: &'a str,
|
||||
/// `--user uid:gid`; `None` keeps the image's user.
|
||||
pub user: Option<(u32, u32)>,
|
||||
/// Runs the Python program under debugpy, for the debugger to attach.
|
||||
/// Runs the program for the debugger to attach: Python under debugpy, Node.js (a `js-debug`
|
||||
/// configuration) with its inspector waiting.
|
||||
pub debug: Option<ContainerDebug<'a>>,
|
||||
}
|
||||
|
||||
/// A debug run: the program starts under [`DEBUG_BOOTSTRAP`], which waits for the
|
||||
/// debugger on `port` (published on this machine's loopback interface only).
|
||||
/// A debug run: the program starts under [`DEBUG_BOOTSTRAP`] (Node.js: with `--inspect-brk`),
|
||||
/// which waits for the debugger on `port` (published on this machine's loopback interface only).
|
||||
pub struct ContainerDebug<'a> {
|
||||
pub port: u16,
|
||||
/// Folder on this machine holding [`DEBUG_BOOTSTRAP`] as [`DEBUG_BOOTSTRAP_NAME`].
|
||||
@@ -57,6 +58,14 @@ const DEBUG_DIR: &str = "/opt/openidea/debug";
|
||||
const DEBUGPY_DIR: &str = "/opt/openidea/debugpy-lib";
|
||||
/// Start of the line the bootstrap prints when the debugger can attach.
|
||||
pub const DEBUG_READY: &str = "debugpy is waiting for the debugger on port ";
|
||||
/// Start of the line printed before a Node.js program starts for debugging on a run target,
|
||||
/// followed by the project folder there. Node prints `Debugger listening on ws://…` itself.
|
||||
pub const NODE_DEBUG_FOLDER: &str = "Starting Node.js for the debugger, project folder ";
|
||||
|
||||
/// Whether a debug run of `config` starts Node.js with its inspector rather than debugpy.
|
||||
pub fn node_debug(config: &RunConfig) -> bool {
|
||||
config.debug_adapter.as_deref() == Some("js-debug")
|
||||
}
|
||||
|
||||
/// The container folder of the project when a Docker target sets none.
|
||||
pub fn default_container_root(root: &Path) -> String {
|
||||
@@ -243,9 +252,12 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
|
||||
if let Some((uid, gid)) = run.user {
|
||||
args.extend(["--user".into(), format!("{uid}:{gid}")]);
|
||||
}
|
||||
let node = node_debug(config);
|
||||
if let Some(debug) = &run.debug {
|
||||
let port = debug.port;
|
||||
args.extend(["--publish".into(), format!("127.0.0.1:{port}:{port}")]);
|
||||
}
|
||||
if let Some(debug) = run.debug.as_ref().filter(|_| !node) {
|
||||
args.extend(["--volume".into(), format!("{}:{DEBUG_DIR}:ro", debug.bootstrap_dir.to_string_lossy())]);
|
||||
if let Some(lib) = debug.debugpy {
|
||||
args.extend(["--volume".into(), format!("{}:{DEBUGPY_DIR}:ro", lib.to_string_lossy())]);
|
||||
@@ -262,11 +274,15 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
|
||||
match (command.shell_line, &run.debug) {
|
||||
(Some(_), Some(_)) => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"'{}' is a shell command line: only a Python script, module or console script can be debugged in a container. Set Command to the Python executable and put the script or -m module in Arguments",
|
||||
"'{}' is a shell command line: only a Python or Node.js program can be debugged in a container. Set Command to the Python or Node.js executable and put the script in Arguments",
|
||||
config.name
|
||||
)));
|
||||
}
|
||||
(Some(line), None) => args.extend(["sh".into(), "-c".into(), line]),
|
||||
// Inside the container the inspector listens on every interface, for the published port.
|
||||
(None, Some(debug)) if node => {
|
||||
args.extend(node_debug_command(&command.program, &command.args, "0.0.0.0", debug.port)?)
|
||||
}
|
||||
(None, Some(debug)) => {
|
||||
let bootstrap = format!("{DEBUG_DIR}/{DEBUG_BOOTSTRAP_NAME}");
|
||||
args.extend(debug_command(
|
||||
@@ -347,6 +363,43 @@ fn is_python(program: &str) -> bool {
|
||||
name == "python" || name == "python2" || name.starts_with("python3")
|
||||
}
|
||||
|
||||
/// Why tsx can't be debugged on a run target yet: js-debug's attach never lets the program start
|
||||
/// past tsx's loader worker.
|
||||
const TSX_UNSUPPORTED: &str = "tsx can't be debugged on a run target yet: the program does not start once the debugger attaches. For TypeScript, set the Node interpreter to node and add --experimental-strip-types to the Node options";
|
||||
|
||||
/// `program args` (a Node.js command on a run target) with the inspector waiting for the debugger
|
||||
/// on `host:port`: `--inspect-brk` goes right after `node`, so the configuration's Node options keep
|
||||
/// applying.
|
||||
pub(crate) fn node_debug_command(program: &str, args: &[String], host: &str, port: u16) -> IdeResult<Vec<String>> {
|
||||
let name = |s: &str| s.rsplit(['/', '\\']).next().unwrap_or(s).trim_end_matches(".exe").to_owned();
|
||||
// `node --import tsx` registers the same loader worker (`--loader tsx` fails on its own).
|
||||
let tsx_import = |value: &str| value == "tsx" || value.starts_with("tsx/") || value.contains("/tsx/");
|
||||
let mut imports_tsx = false;
|
||||
let mut i = 0;
|
||||
while let Some(a) = args.get(i).filter(|a| a.starts_with('-')) {
|
||||
if a == "--import" {
|
||||
imports_tsx |= args.get(i + 1).is_some_and(|v| tsx_import(v));
|
||||
i += 1;
|
||||
}
|
||||
imports_tsx |= a.strip_prefix("--import=").is_some_and(tsx_import);
|
||||
i += 1;
|
||||
}
|
||||
match name(program).as_str() {
|
||||
"node" if imports_tsx => return Err(IdeError::invalid(TSX_UNSUPPORTED)),
|
||||
"node" => {}
|
||||
"tsx" => return Err(IdeError::invalid(TSX_UNSUPPORTED)),
|
||||
"npx" if args.first().is_some_and(|a| a == "tsx") => return Err(IdeError::invalid(TSX_UNSUPPORTED)),
|
||||
_ => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"`{program}` can't be debugged on a run target: set the Node interpreter to node"
|
||||
)));
|
||||
}
|
||||
}
|
||||
let mut line = vec![program.to_owned(), format!("--inspect-brk={host}:{port}")];
|
||||
line.extend(args.iter().cloned());
|
||||
Ok(line)
|
||||
}
|
||||
|
||||
/// The command line that runs `program args` under [`DEBUG_BOOTSTRAP`] (at `bootstrap` in the
|
||||
/// container or on the SSH host): `python [options] <bootstrap> <port> <folder> (script | -m module | -c code) args`.
|
||||
/// A console script (`pytest`) runs as a module of the interpreter next to it, or of the
|
||||
@@ -741,6 +794,52 @@ mod tests {
|
||||
assert!(args.contains("openidea/debug:ro python:3.12") && !args.contains("debugpy-lib"), "{args}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn debug_starts_node_with_the_inspector_on_the_published_port() {
|
||||
let target = RunTarget { kind: RunTargetKind::Docker, image: "node:22".into(), ..Default::default() };
|
||||
let line = |command: &str, args: &[&str]| {
|
||||
let c = RunConfig { debug_adapter: Some("js-debug".into()), ..config(command, args) };
|
||||
let args = debugged(&target, &c).unwrap().join(" ");
|
||||
assert!(args.contains("--publish 127.0.0.1:41234:41234 node:22"), "{args}");
|
||||
assert!(!args.contains("openidea/debug"), "no bootstrap for Node.js: {args}");
|
||||
args.split_once("node:22 ").unwrap().1.to_owned()
|
||||
};
|
||||
let inspect = "--inspect-brk=0.0.0.0:41234";
|
||||
assert_eq!(
|
||||
line("/usr/local/bin/node", &["--env-file=.env", "/work/proj/main.js", "a"]),
|
||||
format!("node {inspect} --env-file=.env /workspaces/proj/main.js a"),
|
||||
"the configuration's Node options stay"
|
||||
);
|
||||
assert_eq!(
|
||||
line("node", &["--import", "./setup.mjs", "main.js", "--import", "tsx"]),
|
||||
format!("node {inspect} --import ./setup.mjs main.js --import tsx"),
|
||||
"other imports, and the program's own arguments, don't count"
|
||||
);
|
||||
assert_eq!(
|
||||
line("node", &["--experimental-strip-types", "main.ts"]),
|
||||
format!("node {inspect} --experimental-strip-types main.ts")
|
||||
);
|
||||
// tsx hangs once js-debug attaches: refused, pointing to type stripping.
|
||||
for (command, args, error) in [
|
||||
("/work/proj/node_modules/.bin/tsx", &["main.ts"][..], "--experimental-strip-types"),
|
||||
("npx", &["tsx", "main.ts"][..], "tsx can't be debugged"),
|
||||
("node", &["--import", "tsx", "main.ts"][..], "tsx can't be debugged"),
|
||||
("node", &["--import=tsx/esm", "main.ts"][..], "tsx can't be debugged"),
|
||||
(
|
||||
"node",
|
||||
&["--env-file=.env", "--import", "/opt/lib/node_modules/tsx/dist/loader.mjs", "main.ts"][..],
|
||||
"tsx",
|
||||
),
|
||||
("npm", &["run", "dev"][..], "set the Node interpreter to node"),
|
||||
("node main.js", &[][..], "shell command line"),
|
||||
] {
|
||||
let c = RunConfig { debug_adapter: Some("js-debug".into()), ..config(command, args) };
|
||||
let err = debugged(&target, &c).unwrap_err();
|
||||
assert!(err.message.contains(error), "{command}: {}", err.message);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_files_printed_in_the_container_through_the_longest_mount() {
|
||||
let root = Path::new("project");
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::deploy::{Deployment, FileStamp, SyncEntry, SyncStatus, SyncStep, Tran
|
||||
use crate::mapping::{Excludes, Mappings, ResolvedMapping, posix};
|
||||
use crate::target::{
|
||||
DEBUG_PARAM, PROBE_NO_FOLDER, RemoteDebug, RemoteRuns, RemoteStart, SyncFn, debug_interpreter, debugpy_probe,
|
||||
remote_command, rewrite_external_classpath, ssh_debug_command,
|
||||
remote_command, rewrite_external_classpath, ssh_debug_command, ssh_node_debug_command,
|
||||
};
|
||||
use ide_core::remote_settings::{AutoUpload, DeploymentServer, DeploymentType, RunTarget};
|
||||
use ide_core::settings::Settings;
|
||||
@@ -605,14 +605,21 @@ async fn prepare_debug(
|
||||
remote_root: &str,
|
||||
debugpy_lib: Option<&Path>,
|
||||
) -> IdeResult<(RemoteDebug, Option<SyncFn>)> {
|
||||
if config.debug_adapter.as_deref() != Some("debugpy") {
|
||||
let node = crate::docker::node_debug(config);
|
||||
if config.debug_adapter.as_deref() != Some("debugpy") && !node {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"'{}' can't be debugged on an SSH run target: only Python run configurations can",
|
||||
"'{}' can't be debugged on an SSH run target: only Python and Node.js run configurations can",
|
||||
config.name
|
||||
)));
|
||||
}
|
||||
let dir = join(&fs.home().await?, DEBUG_FOLDER);
|
||||
let port = std::net::TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port();
|
||||
if node {
|
||||
let command = ssh_node_debug_command(&remote_command(config, target, root, remote_root), port)?;
|
||||
let tunnel = forward(session, port).await?;
|
||||
let note = Some(format!("{}{remote_root}", crate::docker::NODE_DEBUG_FOLDER));
|
||||
return Ok((RemoteDebug { command, tunnel, note }, None));
|
||||
}
|
||||
let dir = join(&fs.home().await?, DEBUG_FOLDER);
|
||||
// Unique among this machine's debug runs; other machines' runs use other temporary names too.
|
||||
let temp = |path: &str| format!("{path}.{}-{port}.tmp", std::process::id());
|
||||
// Named after its content and never rewritten: a concurrent run may be reading it.
|
||||
@@ -671,13 +678,19 @@ async fn prepare_debug(
|
||||
}));
|
||||
}
|
||||
}
|
||||
let tunnel = forward(session, port).await?;
|
||||
Ok((RemoteDebug { command, tunnel, note: None }, upload))
|
||||
}
|
||||
|
||||
/// Forwards local `port` to the same port on the host's loopback interface.
|
||||
async fn forward(session: &Arc<ide_ssh::Session>, port: u16) -> IdeResult<ide_ssh::Tunnel> {
|
||||
let tunnel = ide_ssh::Tunnel::listen_on(session.clone(), Some(port), "127.0.0.1", port).await?;
|
||||
if tunnel.port() != port {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"local port {port} for the debugger was taken meanwhile; try again"
|
||||
)));
|
||||
}
|
||||
Ok((RemoteDebug { command, tunnel }, upload))
|
||||
Ok(tunnel)
|
||||
}
|
||||
|
||||
/// Uploads outside-root classpath entries to their mirrored remote copies,
|
||||
|
||||
@@ -153,6 +153,18 @@ pub fn ssh_debug_command(
|
||||
})
|
||||
}
|
||||
|
||||
/// `command` (an SSH target's Node.js command) with the inspector waiting on the host's loopback
|
||||
/// `port`, which the IDE reaches through an SSH forward.
|
||||
pub fn ssh_node_debug_command(command: &RemoteCommand, port: u16) -> IdeResult<RemoteCommand> {
|
||||
if command.shell_line.is_some() {
|
||||
return Err(IdeError::invalid(
|
||||
"a shell command line can't be debugged on a run target: set the Node interpreter to node and the JavaScript file to the script",
|
||||
));
|
||||
}
|
||||
let line = crate::docker::node_debug_command(&command.program, &command.args, "127.0.0.1", port)?;
|
||||
Ok(RemoteCommand { program: line[0].clone(), args: line[1..].to_vec(), shell_line: None, ..command.clone() })
|
||||
}
|
||||
|
||||
/// The interpreter of an [`ssh_debug_command`] (with its options, or behind `uv run`).
|
||||
pub fn debug_interpreter(debug: &RemoteCommand, bootstrap: &str) -> RemoteCommand {
|
||||
let end = debug.args.iter().position(|a| a == bootstrap).unwrap_or(debug.args.len());
|
||||
@@ -358,6 +370,8 @@ pub struct RemoteStart {
|
||||
pub struct RemoteDebug {
|
||||
pub command: RemoteCommand,
|
||||
pub tunnel: ide_ssh::Tunnel,
|
||||
/// Printed right before the program starts (`docker::NODE_DEBUG_FOLDER`).
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
impl RemoteRuns {
|
||||
@@ -485,6 +499,9 @@ async fn run_remote(
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
on_output(OutputChunk::System { text: format!("{}\n", command.display()) });
|
||||
if let Some(note) = start.debug.as_ref().and_then(|d| d.note.as_ref()) {
|
||||
on_output(OutputChunk::System { text: format!("{note}\n") });
|
||||
}
|
||||
let out = on_output.clone();
|
||||
let process = start
|
||||
.session
|
||||
@@ -556,6 +573,26 @@ mod tests {
|
||||
assert_eq!(c.program, "make");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn debugs_node_on_an_ssh_host_through_its_loopback_port() {
|
||||
let target = RunTarget { node: "/opt/node/bin/node".into(), ..Default::default() };
|
||||
let plain = remote_command(
|
||||
&config("/usr/local/bin/node", &["--enable-source-maps", "/work/proj/src/main.js"], None),
|
||||
&target,
|
||||
Path::new("/work/proj"),
|
||||
"/home/me/proj",
|
||||
);
|
||||
let debug = ssh_node_debug_command(&plain, 50123).unwrap();
|
||||
assert_eq!(debug.program, "/opt/node/bin/node");
|
||||
assert_eq!(debug.args, ["--inspect-brk=127.0.0.1:50123", "--enable-source-maps", "/home/me/proj/src/main.js"]);
|
||||
assert_eq!((debug.cwd.as_str(), &debug.env), (plain.cwd.as_str(), &plain.env));
|
||||
let tsx = RemoteCommand { program: "tsx".into(), ..plain.clone() };
|
||||
assert!(ssh_node_debug_command(&tsx, 50123).unwrap_err().message.contains("--experimental-strip-types"));
|
||||
let shell = RemoteCommand { shell_line: Some("node main.js".into()), ..plain };
|
||||
assert!(ssh_node_debug_command(&shell, 50123).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn debugs_python_on_an_ssh_host_through_its_loopback_port() {
|
||||
|
||||
@@ -115,7 +115,7 @@ The debugger adds attach-only types such as **Remote JVM Debug**, **Go Remote**,
|
||||
|
||||
### Common fields
|
||||
|
||||
- **Run on**: the local machine, or an SSH host defined in **Settings › Build, Execution, Deployment › Run Targets**. Only Python configurations can be debugged on a run target; see [Python debugging](/en/languages/python#debugging). See [SSH](/en/guide/remote/ssh).
|
||||
- **Run on**: the local machine, or an SSH host defined in **Settings › Build, Execution, Deployment › Run Targets**. Python and Node.js configurations can be debugged on a run target (Node.js run with tsx not yet); see [Python debugging](/en/languages/python#debugging) and [JavaScript debugging](/en/languages/javascript#debugging). See [SSH](/en/guide/remote/ssh).
|
||||
- **Working directory**: relative to the project root; empty means the project root. It may use the path macros `$PROJECT_DIR$`, `$ContentRoot$`, `$MODULE_DIR$`, `$MODULE_WORKING_DIR$` and `$USER_HOME$`, expanded when the configuration starts, so a shared configuration works on every machine.
|
||||
- **Environment variables**: `VAR=value` pairs separated by `;`. The list button opens the **Environment Variables** dialog, where **Include system environment variables** can be turned off.
|
||||
- **Debug adapter**: which debugger **Debug** uses for this configuration (for example `debugpy`, `js-debug`, `codelldb`, `delve`).
|
||||
|
||||
@@ -121,6 +121,7 @@ Cypress runs report through Cypress's built-in `teamcity` reporter unless the co
|
||||
Debugging uses the JavaScript Debugger (vscode-js-debug); if it is missing, the first debug session offers to install it.
|
||||
|
||||
- **Debug** works for npm script configurations, Node.js files and `deno run` / `deno test`. Child processes are attached automatically.
|
||||
- A Node.js configuration or a `.js` / `.ts` file run on an SSH, Docker or Compose run target is debugged there: Node starts with `--inspect-brk` on a free port (published from the container on this machine's loopback interface, or forwarded through the SSH connection) and the debugger attaches as **Attach to Node.js** does, with the project folder mapped onto the target's. The interpreter must be `node`, and the configuration's Node options are kept. For TypeScript, add `--experimental-strip-types` to the Node options: tsx (`tsx`, `npx tsx`, `node --import tsx`) can't be debugged on a run target yet, because the program does not start once the debugger attaches. npm script configurations can only be run on a target.
|
||||
- **Attach to Node.js** is a run configuration type for a process started with `--inspect` on this or another machine (default port 9229), with local and remote root mapping. With **Reconnect automatically** on, the session waits while the process restarts (nodemon, `node --watch`, `tsx watch`) and attaches to it again with the same breakpoints.
|
||||
- **Attach to Process…** in the Run menu lists running Node.js processes.
|
||||
- **JavaScript Debug** is a run configuration type that opens a URL in Chrome or Edge and debugs the page's JavaScript and TypeScript through source maps. Start the page's server first (for example with the `dev` npm script); **Web root** is the folder the URL serves, the project root by default.
|
||||
|
||||
@@ -111,7 +111,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码,
|
||||
|
||||
### 通用字段
|
||||
|
||||
- **运行于**:本地计算机,或在 **设置 › 构建、执行、部署 › 运行目标** 中添加的 SSH 主机。运行目标上只能调试 Python 配置,见 [Python 调试](/zh/languages/python#调试)。参见 [SSH](/zh/guide/remote/ssh)。
|
||||
- **运行于**:本地计算机,或在 **设置 › 构建、执行、部署 › 运行目标** 中添加的 SSH 主机。运行目标上可以调试 Python 和 Node.js 配置(用 tsx 运行的 Node.js 暂不支持),见 [Python 调试](/zh/languages/python#调试) 与 [JavaScript 调试](/zh/languages/javascript#调试)。参见 [SSH](/zh/guide/remote/ssh)。
|
||||
- **工作目录**:相对于项目根目录,留空即项目根目录。可以使用路径宏 `$PROJECT_DIR$`、`$ContentRoot$`、`$MODULE_DIR$`、`$MODULE_WORKING_DIR$` 和 `$USER_HOME$`,在配置启动时展开,因此共享的配置在每台机器上都能用。
|
||||
- **环境变量**:`VAR=value` 形式,用 `;` 分隔。点旁边的列表按钮打开“环境变量”对话框,可以关闭 **包括系统环境变量**。
|
||||
- **调试适配器**:按“调试”时这个配置使用哪个调试器(如 `debugpy`、`js-debug`、`codelldb`、`delve`)。
|
||||
|
||||
@@ -122,6 +122,7 @@ Cypress 运行时使用 Cypress 内置的 `teamcity` 报告器(配置里指定
|
||||
调试使用 JavaScript 调试器(vscode-js-debug);未安装时,第一次调试会提示安装。
|
||||
|
||||
- **调试** 适用于 npm 脚本配置、Node.js 文件以及 `deno run` / `deno test`,子进程会自动附加。
|
||||
- 在 SSH、Docker 或 Compose 运行目标上运行的 Node.js 配置或 `.js` / `.ts` 文件,会在目标上调试:Node 以 `--inspect-brk` 在空闲端口上启动(容器中的端口发布到本机回环地址,SSH 主机上的端口经 SSH 连接转发),调试器像 **附加到 Node.js** 一样附加,并把项目文件夹映射到目标上的项目文件夹。解释器须为 `node`,配置中的 Node 选项保持不变。TypeScript 请在 Node 选项中加上 `--experimental-strip-types`:tsx(`tsx`、`npx tsx`、`node --import tsx`)暂时不能在运行目标上调试,因为调试器附加后程序不会开始运行。npm 脚本配置在运行目标上只能运行。
|
||||
- **附加到 Node.js** 是一种运行配置类型,用于附加到本机或其他机器上以 `--inspect` 启动的进程(默认端口 9229),可设置本地与远程根目录映射。勾选 **自动重新连接** 后,进程重启时(nodemon、`node --watch`、`tsx watch`)会话会等待,并以相同的断点重新附加。
|
||||
- 运行菜单中的 **附加到进程…** 会列出正在运行的 Node.js 进程。
|
||||
- **JavaScript 调试** 是一种运行配置类型:在 Chrome 或 Edge 中打开一个 URL,通过 source map 调试页面中的 JavaScript 和 TypeScript。先启动页面的服务(例如 `dev` npm 脚本);**Web 根目录** 是该 URL 对应的文件夹,默认为项目根目录。
|
||||
|
||||
@@ -34,8 +34,8 @@ const {
|
||||
phpRemoteType,
|
||||
jdwpAgentArgs,
|
||||
xdebugCommand,
|
||||
isPythonAttachTarget,
|
||||
pythonAttachConfig,
|
||||
isTargetAttach,
|
||||
targetAttachConfig,
|
||||
remoteAttachConfig,
|
||||
remoteJvmTarget,
|
||||
remoteWaitingNote,
|
||||
@@ -135,9 +135,9 @@ describe("remote attach requests", () => {
|
||||
|
||||
it("a Python program in a container: the project root maps onto its folder there", () => {
|
||||
const target = { name: "app", adapter: "debugpy" as const, hostName: "127.0.0.1", port: 41234, remoteRoot: "/app" };
|
||||
expect(isPythonAttachTarget({ ...target, process: 3 })).toBe(true);
|
||||
expect(isPythonAttachTarget({ name: "app", module: "", hostName: "h", port: 5005 })).toBe(false);
|
||||
const l = pythonAttachConfig(target, "/p");
|
||||
expect(isTargetAttach({ ...target, process: 3 })).toBe(true);
|
||||
expect(isTargetAttach({ name: "app", module: "", hostName: "h", port: 5005 })).toBe(false);
|
||||
const l = targetAttachConfig(target, "/p");
|
||||
expect(l).toMatchObject({ name: "app", adapter: "debugpy", request: "attach", cwd: "/p" });
|
||||
expect(JSON.parse(l.extraJson!)).toMatchObject({
|
||||
debugServer: "127.0.0.1:41234",
|
||||
@@ -145,6 +145,27 @@ describe("remote attach requests", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("a Node.js program on a run target: js-debug attaches to its inspector like Attach to Node.js", () => {
|
||||
const target = {
|
||||
name: "app",
|
||||
adapter: "js-debug" as const,
|
||||
hostName: "127.0.0.1",
|
||||
port: 41234,
|
||||
remoteRoot: "/app",
|
||||
};
|
||||
expect(isTargetAttach(target)).toBe(true);
|
||||
const l = targetAttachConfig(target, "/p");
|
||||
expect(l).toMatchObject({ name: "app", adapter: "js-debug", request: "attach", cwd: "/p" });
|
||||
expect(JSON.parse(l.extraJson!)).toMatchObject({
|
||||
type: "pwa-node",
|
||||
address: "127.0.0.1",
|
||||
port: 41234,
|
||||
localRoot: "/p",
|
||||
remoteRoot: "/app",
|
||||
continueOnAttach: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("Python remote connects to debugpy --listen with pathMappings", () => {
|
||||
const l = remoteAttachConfig(
|
||||
configOf(pythonRemoteType, { host: "::1", localRoot: "svc", remoteRoot: "/app" }),
|
||||
|
||||
@@ -73,9 +73,9 @@ import { DEVTOOLS_WINDOWS, devToolsUrl, refreshDevTools, WIDGET_PREVIEW_WINDOW }
|
||||
import { debugUnsupportedReason, launchConfigFor, withEnvFiles } from "./launch";
|
||||
import { attachConfig } from "./attach";
|
||||
import {
|
||||
isPythonAttachTarget,
|
||||
isTargetAttach,
|
||||
isRemoteConfig,
|
||||
pythonAttachConfig,
|
||||
targetAttachConfig,
|
||||
REMOTE_JVM,
|
||||
remoteAttachConfig,
|
||||
remoteJvmTarget,
|
||||
@@ -724,8 +724,8 @@ export function registerDebugActions(): () => void {
|
||||
title: "Attach Debugger",
|
||||
category: "Debug",
|
||||
hidden: true,
|
||||
// Also debugpy to a Python program in a run target's container
|
||||
// (arg: { name, adapter: "debugpy", hostName, port, remoteRoot, process }).
|
||||
// Also debugpy or js-debug to a Python or Node.js program on a run target
|
||||
// (arg: { name, adapter: "debugpy" | "js-debug", hostName, port, remoteRoot, process }).
|
||||
// Also a process from Attach to Process (arg: { attachable, process, runConfig }).
|
||||
description:
|
||||
"Attach the Java debugger to a JVM listening for JDWP (arg: { name, module, hostName, port, process })",
|
||||
@@ -737,7 +737,7 @@ export function registerDebugActions(): () => void {
|
||||
if (!root) return;
|
||||
let launch: LaunchConfig;
|
||||
if (isAttachableTarget(arg)) launch = await attachConfig(arg.attachable, root);
|
||||
else if (isPythonAttachTarget(arg)) launch = pythonAttachConfig(arg, root);
|
||||
else if (isTargetAttach(arg)) launch = targetAttachConfig(arg, root);
|
||||
else if (isJavaAttachTarget(arg)) launch = await javaAttachConfig(arg, root);
|
||||
else return;
|
||||
const process = (arg.process ?? null) as RunId | null;
|
||||
|
||||
@@ -430,27 +430,37 @@ function debugpyAttach(
|
||||
});
|
||||
}
|
||||
|
||||
/** A Python program debugged on a run target (SSH host or container), waiting for the debugger (Run's `debugOnTarget`). */
|
||||
export interface PythonAttachTarget {
|
||||
/**
|
||||
* A Python or Node.js program debugged on a run target (SSH host or container), waiting for the
|
||||
* debugger (Run's `debugOnTarget`): debugpy, or Node's inspector for js-debug.
|
||||
*/
|
||||
export interface TargetAttach {
|
||||
name: string;
|
||||
adapter: "debugpy";
|
||||
adapter: "debugpy" | "js-debug";
|
||||
hostName: string;
|
||||
port: number;
|
||||
/** The project folder in the container. */
|
||||
/** The project folder on the target. */
|
||||
remoteRoot: string;
|
||||
}
|
||||
|
||||
export function isPythonAttachTarget(
|
||||
arg: unknown,
|
||||
): arg is PythonAttachTarget & { process?: number | null; runConfig?: RunConfig } {
|
||||
export function isTargetAttach(arg: unknown): arg is TargetAttach & { process?: number | null; runConfig?: RunConfig } {
|
||||
if (!arg || typeof arg !== "object") return false;
|
||||
const a = arg as Partial<PythonAttachTarget>;
|
||||
return a.adapter === "debugpy" && typeof a.port === "number" && typeof a.remoteRoot === "string";
|
||||
const a = arg as Partial<TargetAttach>;
|
||||
return (
|
||||
(a.adapter === "debugpy" || a.adapter === "js-debug") &&
|
||||
typeof a.port === "number" &&
|
||||
typeof a.remoteRoot === "string"
|
||||
);
|
||||
}
|
||||
|
||||
/** Attach request of a `PythonAttachTarget`: the project root maps onto the container's folder. */
|
||||
export function pythonAttachConfig(target: PythonAttachTarget, root: string): LaunchConfig {
|
||||
return debugpyAttach(target.name, root, target.hostName, target.port, { local: root, remote: target.remoteRoot });
|
||||
/** Attach request of a `TargetAttach`: the project root maps onto the target's folder, as in Attach to Node.js. */
|
||||
export function targetAttachConfig(target: TargetAttach, root: string): LaunchConfig {
|
||||
if (target.adapter === "debugpy")
|
||||
return debugpyAttach(target.name, root, target.hostName, target.port, { local: root, remote: target.remoteRoot });
|
||||
const params = { host: target.hostName, port: String(target.port), remoteRoot: target.remoteRoot };
|
||||
const launch = remoteAttachConfig({ name: target.name, kind: NODE_REMOTE, params } as unknown as RunConfig, root)!;
|
||||
// The program waits at its first line (`--inspect-brk`) only until the breakpoints are set.
|
||||
return { ...launch, extraJson: JSON.stringify({ ...JSON.parse(launch.extraJson!), continueOnAttach: true }) };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -213,7 +213,10 @@ describe("remote debugging", () => {
|
||||
await executeAction("run.debugConfig", remote.id);
|
||||
expect(startConfig).not.toHaveBeenCalled();
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Only Python can be debugged on SSH run targets", level: "warning" }),
|
||||
expect.objectContaining({
|
||||
title: "Only Python and Node.js can be debugged on SSH run targets",
|
||||
level: "warning",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -251,6 +254,38 @@ describe("remote debugging", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("debugs Node.js on an SSH host through the forwarded port, waiting as long as the upload takes", async () => {
|
||||
const attach = vi.fn();
|
||||
const off = registerActions([{ id: "debug.attach", title: "Attach", run: ({ arg }) => attach(arg) }]);
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const node = cfg("app", {
|
||||
target: "box",
|
||||
kind: "node",
|
||||
command: "node",
|
||||
args: ["--experimental-strip-types", "main.ts"],
|
||||
debugAdapter: "js-debug",
|
||||
});
|
||||
useRun.setState({ configs: [node], loaded: true });
|
||||
ipc.runStart.mockResolvedValueOnce(ok);
|
||||
await executeAction("run.debugConfig", node.id);
|
||||
await vi.advanceTimersByTimeAsync(300_000);
|
||||
expect(ipc.runStop).not.toHaveBeenCalled();
|
||||
const channel = ipc.runStart.mock.calls.at(-1)![1] as { onmessage: (m: unknown) => void };
|
||||
channel.onmessage({ kind: "system", text: "Starting Node.js for the debugger, project folder /home/me/app\n" });
|
||||
channel.onmessage({ kind: "stderr", text: "Debugger listening on ws://127.0.0.1:50123/0a1b\n" });
|
||||
await vi.waitFor(() =>
|
||||
expect(attach).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ adapter: "js-debug", port: 50123, remoteRoot: "/home/me/app" }),
|
||||
),
|
||||
);
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
off();
|
||||
}
|
||||
});
|
||||
|
||||
it("stops an SSH debug run whose program never announces debugpy", async () => {
|
||||
const off = registerActions([{ id: "debug.attach", title: "Attach", run: () => undefined }]);
|
||||
vi.useFakeTimers();
|
||||
@@ -400,13 +435,116 @@ describe("remote debugging", () => {
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("starts Node.js with its inspector and attaches js-debug with the project folder mapped", async () => {
|
||||
const node = cfg("app", {
|
||||
target: "py",
|
||||
kind: "node",
|
||||
command: "node",
|
||||
args: ["main.js"],
|
||||
debugAdapter: "js-debug",
|
||||
});
|
||||
useRun.setState({ configs: [node], loaded: true });
|
||||
ipc.runStart.mockResolvedValueOnce(ok);
|
||||
await executeAction("run.debugConfig", node.id);
|
||||
expect(startConfig).not.toHaveBeenCalled();
|
||||
expect(ipc.runStart).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: "app", params: { targetDebug: "true" } }),
|
||||
expect.anything(),
|
||||
expect.any(Number),
|
||||
);
|
||||
const channel = ipc.runStart.mock.calls.at(-1)![1] as { onmessage: (m: unknown) => void };
|
||||
// Node's line alone, before the IDE's line naming the folder, is not enough.
|
||||
channel.onmessage({ kind: "stderr", text: "Debugger listening on ws://0.0.0.0:41234/0a1b\n" });
|
||||
channel.onmessage({ kind: "system", text: "Starting Node.js for the debugger, project folder /app\n" });
|
||||
expect(attach).not.toHaveBeenCalled();
|
||||
channel.onmessage({ kind: "stderr", text: "Debugger listening on ws://0.0.0.0:41234/0a1b\n" });
|
||||
await vi.waitFor(() =>
|
||||
expect(attach).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({
|
||||
adapter: "js-debug",
|
||||
hostName: "127.0.0.1",
|
||||
port: 41234,
|
||||
remoteRoot: "/app",
|
||||
process: 3,
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stops a Node.js container that never opens its inspector", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const node = cfg("app", {
|
||||
target: "py",
|
||||
kind: "node",
|
||||
command: "node",
|
||||
args: ["main.js"],
|
||||
debugAdapter: "js-debug",
|
||||
});
|
||||
useRun.setState({ configs: [node], loaded: true });
|
||||
ipc.runStart.mockResolvedValueOnce(ok);
|
||||
await executeAction("run.debugConfig", node.id);
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
expect(ipc.runStop).toHaveBeenCalledWith(3);
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
title: "Cannot start container debugging",
|
||||
body: "The Node.js inspector did not become ready within 120 seconds. Check the Run console.",
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("reports a Node.js container that exits before its inspector is ready", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const node = cfg("app", {
|
||||
target: "py",
|
||||
kind: "node",
|
||||
command: "node",
|
||||
args: ["main.js"],
|
||||
debugAdapter: "js-debug",
|
||||
});
|
||||
useRun.setState({ configs: [node], loaded: true });
|
||||
ipc.runStart.mockResolvedValueOnce(ok);
|
||||
await executeAction("run.debugConfig", node.id);
|
||||
onRunExited(3, 1);
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
expect(attach).not.toHaveBeenCalled();
|
||||
expect(notify).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({ body: expect.stringContaining("exited before the Node.js inspector") }),
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps npm scripts blocked", async () => {
|
||||
const npm = cfg("app", {
|
||||
target: "py",
|
||||
kind: "npm",
|
||||
command: "npm",
|
||||
args: ["run", "dev"],
|
||||
debugAdapter: "js-debug",
|
||||
});
|
||||
useRun.setState({ configs: [npm], loaded: true });
|
||||
await executeAction("run.debugConfig", npm.id);
|
||||
expect(ipc.runStart).not.toHaveBeenCalled();
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Only Python and Node.js can be debugged in containers" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("refuses other debuggers", async () => {
|
||||
const go = cfg("app", { target: "py", debugAdapter: "delve" });
|
||||
useRun.setState({ configs: [go], loaded: true });
|
||||
await executeAction("run.debugConfig", go.id);
|
||||
expect(ipc.runStart).not.toHaveBeenCalled();
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: "Only Python can be debugged in containers", level: "warning" }),
|
||||
expect.objectContaining({ title: "Only Python and Node.js can be debugged in containers", level: "warning" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -78,14 +78,19 @@ export function containerTarget(
|
||||
return target && inContainer(target) ? target.id : null;
|
||||
}
|
||||
|
||||
/** A Python configuration on an SSH, Docker or Compose target: debugged there (`debugOnTarget`). */
|
||||
/**
|
||||
* A Python configuration, or a Node.js one (a Node.js configuration or a `.js` / `.ts` file run; not
|
||||
* npm scripts, whose child processes would need js-debug's auto attach there), on an SSH, Docker
|
||||
* or Compose target: debugged there (`debugOnTarget`).
|
||||
*/
|
||||
export function targetDebuggable(config: RunConfig, targets: readonly RuntimeRunTarget[] = allRunTargets()): boolean {
|
||||
const target = targetOf(config, targets);
|
||||
return !!target && (target.kind === "ssh" || inContainer(target)) && config.debugAdapter === "debugpy";
|
||||
const supported = config.debugAdapter === "debugpy" || (config.debugAdapter === "js-debug" && config.kind === "node");
|
||||
return !!target && (target.kind === "ssh" || inContainer(target)) && supported;
|
||||
}
|
||||
|
||||
/**
|
||||
* Debugging on run targets is supported for Python on SSH and container targets: tells
|
||||
* Debugging on run targets is supported for Python and Node.js on SSH and container targets: tells
|
||||
* so (offering Run) and returns true when `config` can't be debugged where it runs.
|
||||
*/
|
||||
export function remoteDebugBlocked(config: RunConfig, targets: readonly RuntimeRunTarget[] = allRunTargets()): boolean {
|
||||
@@ -99,9 +104,9 @@ export function remoteDebugBlocked(config: RunConfig, targets: readonly RuntimeR
|
||||
key: "run.remoteDebug",
|
||||
title:
|
||||
where && inContainer(where)
|
||||
? "Only Python can be debugged in containers"
|
||||
? "Only Python and Node.js can be debugged in containers"
|
||||
: where?.kind === "ssh"
|
||||
? "Only Python can be debugged on SSH run targets"
|
||||
? "Only Python and Node.js can be debugged on SSH run targets"
|
||||
: "Debugging on run targets is not supported",
|
||||
body: txTemplate(
|
||||
`'${config.name}' runs on ${target}. Run it, or choose “Local machine” under “Run on” to debug it.`,
|
||||
|
||||
@@ -144,6 +144,8 @@ interface SessionRuntime {
|
||||
generation: number;
|
||||
/** Called with every complete output line (e.g. waiting for a JDWP agent). */
|
||||
lineListeners: Array<(text: string) => void>;
|
||||
/** Called with every line the IDE printed itself (`OutputChunk::System`). */
|
||||
systemListeners: Array<(text: string) => void>;
|
||||
/** Called with output as shown (the Debug console of a debugger attached to this process). */
|
||||
outputListeners: Set<OutputListener>;
|
||||
/** Called once the process exited (run executors: collect a coverage report…). */
|
||||
@@ -840,6 +842,7 @@ function newRuntime(config: RunConfig): SessionRuntime {
|
||||
if (pluginTests && kind !== "system") pluginTests.feed(text);
|
||||
if (parser && tests && kind !== "system" && !(kind === "stdout" && stdout)) applyTests(parser.feed(text));
|
||||
if (kind !== "system") for (const l of runtime.lineListeners) l(text);
|
||||
else for (const l of runtime.systemListeners) l(text);
|
||||
if (kind !== "system") runtime.dotnetReports?.feed(text);
|
||||
if (kind !== "system") runtime.xcodeReports?.feed(text);
|
||||
},
|
||||
@@ -849,6 +852,7 @@ function newRuntime(config: RunConfig): SessionRuntime {
|
||||
flushedAt: -Infinity,
|
||||
generation: 0,
|
||||
lineListeners: [],
|
||||
systemListeners: [],
|
||||
outputListeners: new Set(),
|
||||
input: "",
|
||||
terminal: null,
|
||||
@@ -931,6 +935,8 @@ interface StartRunOptions {
|
||||
launch?: RunConfig;
|
||||
/** Every output line of this run. */
|
||||
onLine?: (text: string) => void;
|
||||
/** Every line the IDE printed in this run's console (the command line, a debug run's notes). */
|
||||
onSystemLine?: (text: string) => void;
|
||||
/** The process exited. */
|
||||
onExit?: (exitCode: number | null, stopped: boolean) => void;
|
||||
/** Before launch tasks already ran (or must not run). */
|
||||
@@ -1101,6 +1107,7 @@ async function startRunIn(
|
||||
check?.own(sessionId);
|
||||
check?.signal.throwIfAborted();
|
||||
if (options.onLine) rt.lineListeners.push(options.onLine);
|
||||
if (options.onSystemLine) rt.systemListeners.push(options.onSystemLine);
|
||||
let browserOpened = false;
|
||||
rt.lineListeners.push((line) => {
|
||||
if (config.kind === "tomcat" && /Server startup in/.test(line)) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { debugpyReady, targetDebugLaunch } from "./targetDebug";
|
||||
import { debugpyReady, inspectorPort, nodeDebugFolder, targetDebugLaunch } from "./targetDebug";
|
||||
|
||||
describe("debugging on run targets", () => {
|
||||
it("reads the port and the project folder from the bootstrap's line", () => {
|
||||
@@ -13,6 +13,16 @@ describe("debugging on run targets", () => {
|
||||
expect(debugpyReady("waiting for the debugger on port 41234")).toBeNull();
|
||||
});
|
||||
|
||||
it("reads the project folder from the IDE's line and the port from Node's", () => {
|
||||
expect(nodeDebugFolder("Starting Node.js for the debugger, project folder /workspaces/my app\r")).toBe(
|
||||
"/workspaces/my app",
|
||||
);
|
||||
expect(nodeDebugFolder("debugpy is starting")).toBeNull();
|
||||
expect(inspectorPort("Debugger listening on ws://0.0.0.0:41234/9f1c2e3a-0000\r")).toBe(41234);
|
||||
expect(inspectorPort("Debugger listening on ws://[::1]:9229/abc")).toBe(9229);
|
||||
expect(inspectorPort("For help, see: https://nodejs.org/en/docs/inspector")).toBeNull();
|
||||
});
|
||||
|
||||
it("asks the backend for a debug run, keeping the configuration's parameters", () => {
|
||||
const config = { id: "a", params: { module: "app" } } as unknown as RunConfig;
|
||||
expect(targetDebugLaunch(config).params).toEqual({ module: "app", targetDebug: "true" });
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/**
|
||||
* Debugging Python on run targets: the run starts the program under debugpy (the bootstrap
|
||||
* of `ide_remote::docker`) in a new container, or on the SSH host with an SSH forward of
|
||||
* the port, and the bootstrap prints the port once debugpy listens; the debugger then
|
||||
* attaches like a Python Remote Debug configuration, with the project folder mapped.
|
||||
* Output stays in the Run tab; stopping the debugger stops the program.
|
||||
* Debugging Python and Node.js on run targets: the run starts the program under debugpy (the
|
||||
* bootstrap of `ide_remote::docker`), or Node.js with `--inspect-brk`, in a new container, or on
|
||||
* the SSH host with an SSH forward of the port. Once debugpy listens the bootstrap prints the
|
||||
* port; Node prints its own `Debugger listening` line, after the IDE's line naming the project
|
||||
* folder there. The debugger then attaches like Python Remote Debug or Attach to Node.js, with
|
||||
* the project folder mapped. Output stays in the Run tab; stopping the debugger stops the program.
|
||||
*/
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
@@ -19,6 +20,12 @@ const STARTING = "debugpy is starting";
|
||||
/** The bootstrap's line (`ide_remote::docker::DEBUG_READY`). */
|
||||
const READY = /^debugpy is waiting for the debugger on port (\d+), project folder (.+)$/;
|
||||
|
||||
/** The IDE's line before a Node.js debug run starts (`ide_remote::docker::NODE_DEBUG_FOLDER`). */
|
||||
const NODE_FOLDER = "Starting Node.js for the debugger, project folder ";
|
||||
|
||||
/** Node's line once the inspector listens (`Debugger listening on ws://0.0.0.0:9229/<id>`). */
|
||||
const INSPECTOR = /^Debugger listening on ws:\/\/(?:\[[^\]]*\]|[^/:]+):(\d+)\//;
|
||||
|
||||
interface Ready {
|
||||
port: number;
|
||||
remoteRoot: string;
|
||||
@@ -30,17 +37,31 @@ export function debugpyReady(line: string): Ready | null {
|
||||
return m ? { port: Number(m[1]), remoteRoot: m[2]! } : null;
|
||||
}
|
||||
|
||||
/** `config` as the backend runs it for debugging: under debugpy, waiting for the debugger. */
|
||||
/** The project folder on the target, from the IDE's line before a Node.js debug run. */
|
||||
export function nodeDebugFolder(line: string): string | null {
|
||||
const text = line.trim();
|
||||
return text.startsWith(NODE_FOLDER) ? text.slice(NODE_FOLDER.length) : null;
|
||||
}
|
||||
|
||||
/** The inspector's port, from Node's line once it listens. */
|
||||
export function inspectorPort(line: string): number | null {
|
||||
const m = INSPECTOR.exec(line.trim());
|
||||
return m ? Number(m[1]) : null;
|
||||
}
|
||||
|
||||
/** `config` as the backend runs it for debugging: under debugpy or with Node's inspector, waiting for the debugger. */
|
||||
export function targetDebugLaunch(config: RunConfig): RunConfig {
|
||||
return { ...config, params: { ...config.params, targetDebug: "true" } };
|
||||
}
|
||||
|
||||
/** Runs `config` on its run target under debugpy and attaches the debugger. */
|
||||
/** Runs `config` on its run target under debugpy (Node.js: with its inspector) and attaches the debugger. */
|
||||
export async function debugOnTarget(config: RunConfig): Promise<void> {
|
||||
const target = targetOf(config);
|
||||
const container = !target || inContainer(target);
|
||||
const node = config.debugAdapter === "js-debug";
|
||||
let sessionId: string | null = null;
|
||||
let ready: Ready | null = null;
|
||||
let nodeFolder: string | null = null;
|
||||
let done = false;
|
||||
const pending: { timer?: ReturnType<typeof setTimeout>; unsubscribe?: () => void } = {};
|
||||
const finish = () => {
|
||||
@@ -63,7 +84,7 @@ export async function debugOnTarget(config: RunConfig): Promise<void> {
|
||||
const runId = useRun.getState().sessions.find((s) => s.id === sessionId)?.runId ?? null;
|
||||
void executeAction("debug.attach", {
|
||||
name: config.name,
|
||||
adapter: "debugpy",
|
||||
adapter: node ? "js-debug" : "debugpy",
|
||||
hostName: "127.0.0.1",
|
||||
port,
|
||||
remoteRoot,
|
||||
@@ -75,13 +96,15 @@ export async function debugOnTarget(config: RunConfig): Promise<void> {
|
||||
if (done || pending.timer) return;
|
||||
pending.timer = setTimeout(() => {
|
||||
fail(
|
||||
container
|
||||
? tx(
|
||||
"debugpy did not become ready within 120 seconds. Check the Run console and the container's Python interpreter.",
|
||||
)
|
||||
: tx(
|
||||
"debugpy did not become ready within 120 seconds. Check the Run console and the SSH host's Python interpreter.",
|
||||
),
|
||||
node
|
||||
? tx("The Node.js inspector did not become ready within 120 seconds. Check the Run console.")
|
||||
: container
|
||||
? tx(
|
||||
"debugpy did not become ready within 120 seconds. Check the Run console and the container's Python interpreter.",
|
||||
)
|
||||
: tx(
|
||||
"debugpy did not become ready within 120 seconds. Check the Run console and the SSH host's Python interpreter.",
|
||||
),
|
||||
);
|
||||
if (sessionId) void stopSession(sessionId);
|
||||
}, 120_000);
|
||||
@@ -92,12 +115,19 @@ export async function debugOnTarget(config: RunConfig): Promise<void> {
|
||||
if (done) return;
|
||||
// Over SSH the project and debugpy may be uploaded first, for as long as the link needs:
|
||||
// the wait starts with the program.
|
||||
if (line.trim() === STARTING) startTimer();
|
||||
const parsed = debugpyReady(line);
|
||||
if (!node && line.trim() === STARTING) startTimer();
|
||||
const port = node && nodeFolder !== null ? inspectorPort(line) : null;
|
||||
const parsed = node ? (port === null ? null : { port, remoteRoot: nodeFolder! }) : debugpyReady(line);
|
||||
if (!parsed) return;
|
||||
ready = parsed;
|
||||
if (sessionId) attach(ready);
|
||||
},
|
||||
onSystemLine: (line) => {
|
||||
const folder = node && !done ? nodeDebugFolder(line) : null;
|
||||
if (folder === null) return;
|
||||
nodeFolder = folder;
|
||||
startTimer();
|
||||
},
|
||||
});
|
||||
if (!session) return;
|
||||
sessionId = session.id;
|
||||
@@ -106,9 +136,13 @@ export async function debugOnTarget(config: RunConfig): Promise<void> {
|
||||
if (!current || current.stopped || current.status === "failed") finish();
|
||||
else if (!isLive(current))
|
||||
fail(
|
||||
container
|
||||
? tx("The container exited before debugpy was ready. Check the Run console for errors.")
|
||||
: tx("The program exited before debugpy was ready. Check the Run console for errors."),
|
||||
node
|
||||
? container
|
||||
? tx("The container exited before the Node.js inspector was ready. Check the Run console for errors.")
|
||||
: tx("The program exited before the Node.js inspector was ready. Check the Run console for errors.")
|
||||
: container
|
||||
? tx("The container exited before debugpy was ready. Check the Run console for errors.")
|
||||
: tx("The program exited before debugpy was ready. Check the Run console for errors."),
|
||||
);
|
||||
};
|
||||
pending.unsubscribe = useRun.subscribe(check);
|
||||
|
||||
@@ -571,7 +571,7 @@ export function RunTargetsEditor() {
|
||||
</T>{" "}
|
||||
<T>
|
||||
{
|
||||
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine."
|
||||
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine."
|
||||
}
|
||||
</T>
|
||||
</div>
|
||||
|
||||
@@ -1455,12 +1455,15 @@
|
||||
"Cannot start debugging on the SSH host": "Cannot start debugging on the SSH host",
|
||||
"debugpy did not become ready within 120 seconds. Check the Run console and the SSH host's Python interpreter.": "debugpy did not become ready within 120 seconds. Check the Run console and the SSH host's Python interpreter.",
|
||||
"The program exited before debugpy was ready. Check the Run console for errors.": "The program exited before debugpy was ready. Check the Run console for errors.",
|
||||
"Only Python can be debugged on SSH run targets": "Only Python can be debugged on SSH run targets",
|
||||
"Only Python and Node.js can be debugged on SSH run targets": "Only Python and Node.js can be debugged on SSH run targets",
|
||||
"Install debugpy": "Install debugpy",
|
||||
"The container exited before debugpy was ready. Check the Run console for errors.": "The container exited before debugpy was ready. Check the Run console for errors.",
|
||||
"The Node.js inspector did not become ready within 120 seconds. Check the Run console.": "The Node.js inspector did not become ready within 120 seconds. Check the Run console.",
|
||||
"The container exited before the Node.js inspector was ready. Check the Run console for errors.": "The container exited before the Node.js inspector was ready. Check the Run console for errors.",
|
||||
"The program exited before the Node.js inspector was ready. Check the Run console for errors.": "The program exited before the Node.js inspector was ready. Check the Run console for errors.",
|
||||
"debugpy did not become ready within 120 seconds. Check the Run console and the container's Python interpreter.": "debugpy did not become ready within 120 seconds. Check the Run console and the container's Python interpreter.",
|
||||
"Only Python can be debugged in containers": "Only Python can be debugged in containers",
|
||||
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.": "Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.",
|
||||
"Only Python and Node.js can be debugged in containers": "Only Python and Node.js can be debugged in containers",
|
||||
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine.": "Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine.",
|
||||
"Use Project JDK": "Use Project JDK",
|
||||
"JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence.": "JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence.",
|
||||
"Application server": "Application server",
|
||||
|
||||
@@ -7763,8 +7763,8 @@
|
||||
"The project is mounted here; paths and the working directory are mapped into it.": "Проект монтируется сюда; пути и рабочий каталог сопоставляются с этой папкой.",
|
||||
"Published ports": "Опубликованные порты",
|
||||
"Run as the image's user, not the project folder's owner (Linux)": "Запускать от имени пользователя образа, а не владельца папки проекта (Linux)",
|
||||
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.": "Подключения Docker берутся из окна инструментов «Сервисы». При каждом запуске создаётся новый контейнер, который удаляется после завершения. Там можно отлаживать конфигурации Python; покрытие кода и профилирование остаются на этом компьютере.",
|
||||
"Only Python can be debugged in containers": "В контейнерах можно отлаживать только Python",
|
||||
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine.": "Подключения Docker берутся из окна инструментов «Сервисы». При каждом запуске создаётся новый контейнер, который удаляется после завершения. Там можно отлаживать конфигурации Python и Node.js; покрытие кода и профилирование остаются на этом компьютере.",
|
||||
"Only Python and Node.js can be debugged in containers": "В контейнерах можно отлаживать только Python и Node.js",
|
||||
"Service name, e.g. ORCLPDB1": "Имя сервиса, например ORCLPDB1",
|
||||
"Current schema:": "Текущая схема:",
|
||||
"HR (ALTER SESSION SET CURRENT_SCHEMA)": "HR (ALTER SESSION SET CURRENT_SCHEMA)",
|
||||
|
||||
@@ -793,8 +793,8 @@
|
||||
"Cannot start container debugging": "Kapsayıcı hata ayıklaması başlatılamıyor",
|
||||
"The container exited before debugpy was ready. Check the Run console for errors.": "debugpy hazır olmadan kapsayıcı sonlandı. Hatalar için Çalıştır konsolunu kontrol edin.",
|
||||
"debugpy did not become ready within 120 seconds. Check the Run console and the container's Python interpreter.": "debugpy 120 saniye içinde hazır olmadı. Çalıştır konsolunu ve kapsayıcının Python yorumlayıcısını kontrol edin.",
|
||||
"Only Python can be debugged in containers": "Kapsayıcılarda yalnızca Python hata ayıklaması yapılabilir",
|
||||
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.": "Docker bağlantıları Hizmetler araç penceresinden alınır. Her çalıştırma için yeni bir kapsayıcı oluşturulur ve tamamlandığında kaldırılır. Python yapılandırmalarında kapsayıcı içinde hata ayıklanabilir; kapsam ve profilleme işlemleri bu bilgisayarda kalır.",
|
||||
"Only Python and Node.js can be debugged in containers": "Kapsayıcılarda yalnızca Python ve Node.js hata ayıklaması yapılabilir",
|
||||
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine.": "Docker bağlantıları Hizmetler araç penceresinden alınır. Her çalıştırma için yeni bir kapsayıcı oluşturulur ve tamamlandığında kaldırılır. Python ve Node.js yapılandırmalarında kapsayıcı içinde hata ayıklanabilir; kapsam ve profilleme işlemleri bu bilgisayarda kalır.",
|
||||
"Use Project JDK": "Proje JDK'sını Kullan",
|
||||
"JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence.": "Maven eşitlemesi, derlemeler, hedefler ve testlerde kullanılan JDK. Çalıştırma yapılandırmasında açıkça belirtilen JAVA_HOME önceliklidir.",
|
||||
"Application server": "Uygulama sunucusu",
|
||||
|
||||
@@ -7283,8 +7283,8 @@
|
||||
"The project is mounted here; paths and the working directory are mapped into it.": "專案掛載在此處;路徑和工作目錄會對映到其中。",
|
||||
"Published ports": "釋出的埠",
|
||||
"Run as the image's user, not the project folder's owner (Linux)": "以映像的使用者執行,而不是專案資料夾的所有者(Linux)",
|
||||
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.": "Docker 連線來自「服務」工具視窗。每次執行都會使用一個新容器,執行結束後刪除。Python 組態可以在容器中偵錯;覆蓋率和效能分析仍在本機進行。",
|
||||
"Only Python can be debugged in containers": "容器中只能偵錯 Python",
|
||||
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine.": "Docker 連線來自「服務」工具視窗。每次執行都會使用一個新容器,執行結束後刪除。Python 和 Node.js 組態可以在容器中偵錯;覆蓋率和效能分析仍在本機進行。",
|
||||
"Only Python and Node.js can be debugged in containers": "容器中只能偵錯 Python 和 Node.js",
|
||||
"Service name, e.g. ORCLPDB1": "服務名,例如 ORCLPDB1",
|
||||
"Current schema:": "目前模式:",
|
||||
"HR (ALTER SESSION SET CURRENT_SCHEMA)": "HR(ALTER SESSION SET CURRENT_SCHEMA)",
|
||||
|
||||
@@ -8178,8 +8178,8 @@
|
||||
"The project is mounted here; paths and the working directory are mapped into it.": "项目挂载在此处;路径和工作目录会映射到其中。",
|
||||
"Published ports": "发布的端口",
|
||||
"Run as the image's user, not the project folder's owner (Linux)": "以镜像的用户运行,而不是项目文件夹的所有者(Linux)",
|
||||
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.": "Docker 连接来自“服务”工具窗口。每次运行都会使用一个新容器,运行结束后删除。Python 配置可以在容器中调试;覆盖率和性能分析仍在本机进行。",
|
||||
"Only Python can be debugged in containers": "容器中只能调试 Python",
|
||||
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine.": "Docker 连接来自“服务”工具窗口。每次运行都会使用一个新容器,运行结束后删除。Python 和 Node.js 配置可以在容器中调试;覆盖率和性能分析仍在本机进行。",
|
||||
"Only Python and Node.js can be debugged in containers": "容器中只能调试 Python 和 Node.js",
|
||||
"Service name, e.g. ORCLPDB1": "服务名,例如 ORCLPDB1",
|
||||
"Current schema:": "当前模式:",
|
||||
"HR (ALTER SESSION SET CURRENT_SCHEMA)": "HR(ALTER SESSION SET CURRENT_SCHEMA)",
|
||||
@@ -8297,9 +8297,12 @@
|
||||
"Cannot start debugging on the SSH host": "无法在 SSH 主机上启动调试",
|
||||
"debugpy did not become ready within 120 seconds. Check the Run console and the SSH host's Python interpreter.": "debugpy 在 120 秒内未就绪。请检查运行控制台和 SSH 主机上的 Python 解释器。",
|
||||
"The program exited before debugpy was ready. Check the Run console for errors.": "程序在 debugpy 就绪前已退出。请检查运行控制台中的错误。",
|
||||
"Only Python can be debugged on SSH run targets": "SSH 运行目标上只能调试 Python",
|
||||
"Only Python and Node.js can be debugged on SSH run targets": "SSH 运行目标上只能调试 Python 和 Node.js",
|
||||
"Install debugpy": "安装 debugpy",
|
||||
"The container exited before debugpy was ready. Check the Run console for errors.": "容器在 debugpy 就绪前已退出。请检查运行控制台中的错误。",
|
||||
"The Node.js inspector did not become ready within 120 seconds. Check the Run console.": "Node.js 检查器在 120 秒内未就绪。请检查运行控制台。",
|
||||
"The container exited before the Node.js inspector was ready. Check the Run console for errors.": "容器在 Node.js 检查器就绪前已退出。请检查运行控制台中的错误。",
|
||||
"The program exited before the Node.js inspector was ready. Check the Run console for errors.": "程序在 Node.js 检查器就绪前已退出。请检查运行控制台中的错误。",
|
||||
"debugpy did not become ready within 120 seconds. Check the Run console and the container's Python interpreter.": "debugpy 未在 120 秒内就绪。请检查运行控制台和容器的 Python 解释器。",
|
||||
"Use Project JDK": "使用项目 SDK",
|
||||
"JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence.": "用于 Maven 同步、构建、目标和测试的 JDK。运行配置中显式设置的 JAVA_HOME 优先。",
|
||||
|
||||
Reference in new issue
Заблокувати користувача