Visual Studio Code, rebuilt in Rust
Rust
feat(debug): launch extension development hosts from extensionHost launch
rokartur2e8c400ec310
diff --git a/native/crates/app/src/debug/session.rs b/native/crates/app/src/debug/session.rsindex a0bf1e0d96a..d61304768cf 100644--- a/native/crates/app/src/debug/session.rs+++ b/native/crates/app/src/debug/session.rs@@ -434,6 +434,11 @@ pub fn from_adapter_paths(message: &Value) -> Value {"breakpoint" => uri_to_path(&mut message["body"]["breakpoint"]["source"]),_ => {}},+ Some("request") if message["command"] == "launchVSCode" => {+ for arg in message["arguments"]["args"].as_array_mut().into_iter().flatten() {+ uri_to_path(arg);+ }+ }Some("response") if message["success"] == true => {let command = message["command"].as_str().unwrap_or_default().to_owned();let body = &mut message["body"];diff --git a/native/crates/app/src/main.rs b/native/crates/app/src/main.rsindex b1deffcd1db..52e730191ba 100644--- a/native/crates/app/src/main.rs+++ b/native/crates/app/src/main.rs@@ -138,7 +138,7 @@ use config::configuration::Overrides;use config::registry::Registry;use config::service::Settings;use config::workspace::Workspace;-use exthost::extension_development::ExtensionDevelopment;+use exthost::extension_development::{ExtensionDevelopment, ExtensionHostDebug};use exthost::extension_management::{UserExtensions, WindowExtensions, add_user_extensions};use exthost::main_thread_configuration::MainThreadConfiguration;use exthost::main_thread_files::MainThreadFiles;@@ -278,7 +278,7 @@ fn main() -> anyhow::Result<()> {}};let app = AppState { args: args.clone(), runtime, user_data, app_root, builtins, user_extensions_folder: extensions_folder, shared_storage };- let startup = (!positional.is_empty() || restored.is_empty()).then(|| WindowRequest { workspace, files, development, open_url, screenshot, screenshot_keys, screenshot_input, export_default_keybindings, profile: cli_profile, ..WindowRequest::default() });+ let startup = (!positional.is_empty() || restored.is_empty()).then(|| WindowRequest { workspace, files, development, host_debug: ExtensionHostDebug::from_args(&args), open_url, screenshot, screenshot_keys, screenshot_input, export_default_keybindings, profile: cli_profile, ..WindowRequest::default() });let application = application();// A click on the Dock icon without a window opens an empty one, as `app.on('activate')` does in app.ts.application.on_reopen(|cx| {@@ -354,7 +354,8 @@ impl gpui::Global for AppState {}pub(crate) struct WindowRequest {pub workspace: Option<Workspace>,pub files: workbench::command_line::FilesToOpen,- development: Option<ExtensionDevelopment>,+ pub development: Option<ExtensionDevelopment>,+ pub host_debug: ExtensionHostDebug,open_url: Option<String>,screenshot: Option<PathBuf>,screenshot_keys: Vec<Keystroke>,@@ -396,7 +397,7 @@ pub(crate) fn open_window_or_log(request: WindowRequest, cx: &mut App) {/// windowsMainService.ts `openInBrowserWindow`: a window with its own settings, storage, trust, extension host and/// workbench, as each reference window has.pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Result<gpui::WindowHandle<Workbench>> {- let WindowRequest { workspace, files, development, open_url, screenshot, screenshot_keys, screenshot_input, export_default_keybindings, backup_folder, ui, profile: cli_profile } = request;+ let WindowRequest { workspace, files, development, host_debug, open_url, screenshot, screenshot_keys, screenshot_input, export_default_keybindings, backup_folder, ui, profile: cli_profile } = request;let app = cx.global::<AppState>();let (args, runtime, user_data, app_root, builtins, shared_storage) = (app.args.clone(), app.runtime, app.user_data.clone(), app.app_root.clone(), app.builtins.clone(), app.shared_storage.clone());let flag_value = |flag: &str| args.iter().position(|arg| arg == flag).and_then(|i| args.get(i + 1)).cloned();@@ -549,6 +550,8 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resulworkbench.skip_dialogs = development.as_ref().is_some_and(|development| development.tests_path.is_some());workbench.refresh_keyboard_mapper();workbench.extension_development = development.is_some();+ workbench.development = development.clone();+ workbench.extension_host_debug = host_debug.clone();workbench.proposed_api = proposed_api.clone();workbench.cli_profile = cli_profile.clone();workbench.load_keybindings(keybindings::default_keybindings(&extensions), keybindings_file.clone());@@ -623,11 +626,12 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resul}let (session_ended, ended) = futures::channel::oneshot::channel::<()>();workbench.watch_session_end(session_closed.clone(), ended, cx);+ let start = workbench.extension_host_started(cx);std::thread::Builder::new().name("exthost-session".into()).spawn(move || {let runs_tests = development.as_ref().is_some_and(|development| development.tests_path.is_some());- if let Err(error) = run_extension_host(runtime, app_root, extensions, settings, storage, workspace_trusted, user_data, workspace, development, main_thread, request_sender, replies, &sender, &session_closed) {+ if let Err(error) = run_extension_host(runtime, app_root, extensions, settings, storage, workspace_trusted, user_data, workspace, development, host_debug, main_thread, request_sender, replies, &sender, &session_closed) {if runs_tests {eprintln!("extension host failed: {error:#}");std::process::exit(1);@@ -642,6 +646,9 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resulcx.spawn_in(window, async move |workbench, cx| {while let Some(line) = receiver.next().await {eprintln!("{line}");+ if line == EXITED_LINE {+ let _ = workbench.update_in(cx, |workbench, window, cx| workbench.extension_host_exited(start, window, cx));+ }if line.starts_with(HANDSHAKE_PREFIX) {let _ = workbench.update(cx, |workbench, _| {workbench.host.installed_extensions_registered = true;@@ -717,6 +724,7 @@ fn run_extension_host(user_data: PathBuf,workspace: Option<Workspace>,development: Option<ExtensionDevelopment>,+ host_debug: ExtensionHostDebug,main_thread: WorkbenchMainThread,workbench_requests: UnboundedSender<ForwardedRequest>,workbench_replies: Receiver<(u32, Result<serde_json::Value, serde_json::Value>)>,@@ -736,9 +744,13 @@ fn run_extension_host(if let Some(development) = &development {development.add_to_init_data(&mut init);}+ init["environment"]["isExtensionDevelopmentDebug"] = json!(host_debug.port.is_some());let entry = exthost_entry(&app_root);-- let host = ExtensionHost::start(HostOptions { runtime, entry: &entry, extra_env: vec![], extra_args: vec![] }, &init)?;+ let (runtime, extra_args) = match host_debug.port {+ Some(port) => (Runtime::Node, host_debug.node_args(port)),+ None => (runtime, Vec::new()),+ };+ let host = ExtensionHost::start(HostOptions { runtime, entry: &entry, extra_env: host_debug.env, extra_args }, &init)?;let _ = status.unbounded_send(format!("{HANDSHAKE_PREFIX}{}", host.child.id()));let mut session = Session::new(host);let folders: Vec<PathBuf> = workspace.iter().flat_map(|workspace| workspace.folders.iter().map(|folder| folder.path.clone())).collect();@@ -769,7 +781,8 @@ fn run_extension_host(perf::mark("code/willStartExtensionHost");session.start(&extensions, workspace.as_ref().map(|workspace| workspace_data(&init, workspace)))?;perf::mark("code/didStartExtensionHost");- let reply = session.call("ExtHostExtensionService", "$test_latency", vec![Arg::Json(json!(7))], Duration::from_secs(10))?;+ // No timeout: a host paused in a debugger answers once it runs on.+ let reply = session.request("ExtHostExtensionService", "$test_latency", vec![Arg::Json(json!(7))], None)?;let _ = status.unbounded_send(format!("main -> host: $test_latency(7) = {reply:?}"));let _ = status.unbounded_send(format!("host -> main: {} requests so far", session.log.host_calls.values().sum::<u32>()));let _ = status.unbounded_send(format!("{ACTIVATED_PREFIX}{}", session.log.activated.join(", ")));@@ -791,7 +804,7 @@ fn run_extension_host(drop(session);std::process::exit(code);}- let _ = status.unbounded_send("extension host exited".into());+ let _ = status.unbounded_send(EXITED_LINE.into());Ok(())}@@ -803,6 +816,7 @@ static VERSION: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| matchconst ACTIVATED_PREFIX: &str = "eager extensions activated: ";const HANDSHAKE_PREFIX: &str = "handshake done, pid ";+const EXITED_LINE: &str = "extension host exited";/// A step of `--screenshot-input`: `right X Y` (a right click), `move X Y` or `key KEYSTROKE`, in window points.fn screenshot_step(step: &str) -> anyhow::Result<gpui::PlatformInput> {diff --git a/native/crates/app/src/workbench.rs b/native/crates/app/src/workbench.rsindex ec66861d9e5..ed7bf3d95c5 100644--- a/native/crates/app/src/workbench.rs+++ b/native/crates/app/src/workbench.rs@@ -337,6 +337,12 @@ pub struct Workbench {wait_markers: Vec<PathBuf>,/// `IEnvironmentService.isExtensionDevelopment`.pub extension_development: bool,+ /// The window's `--extensionDevelopmentPath` and `--extensionTestsPath`, kept for a host restart and a reload.+ pub development: Option<exthost::extension_development::ExtensionDevelopment>,+ /// The window's `--inspect[-brk]-extensions`, `--debugId` and `--extensionEnvironment`.+ pub extension_host_debug: exthost::extension_development::ExtensionHostDebug,+ /// Extension hosts started in this window: the exit of one that a restart replaced is not the window's.+ pub extension_host_starts: u32,/// extensionsProposedApi.ts of this window, for the extensions a host restart scans again.pub proposed_api: exthost::proposed_api::ProposedApi,proxy_auth: proxy_auth::ProxyAuth,@@ -729,6 +735,9 @@ impl Workbench {wait_shown: Vec::new(),wait_markers: Vec::new(),extension_development: false,+ development: None,+ extension_host_debug: Default::default(),+ extension_host_starts: 0,proposed_api: exthost::proposed_api::ProposedApi::unbuilt(),proxy_auth: proxy_auth::ProxyAuth::default(),cli_profile: Default::default(),diff --git a/native/crates/app/src/workbench/debug_service.rs b/native/crates/app/src/workbench/debug_service.rsindex 9803628b4b6..cc2f8c5191f 100644--- a/native/crates/app/src/workbench/debug_service.rs+++ b/native/crates/app/src/workbench/debug_service.rs@@ -478,6 +478,10 @@ impl Workbench {let reply = self.start_debugging(folder, configuration, json!({ "parentSessionID": session_id }), DebugTasks::PreLaunch, window, cx);answer_with(reply, session_id.to_owned(), request.clone(), |started| if started == true { Ok(Value::Null) } else { Err("Failed to start debugging".into()) }, window, cx);}+ Some("launchVSCode") => {+ let opened = super::host::open_extension_development_host_window(&launch_vs_code_args(&arguments), cx);+ self.send_response(session_id, request, opened.map(|()| json!({})).map_err(|error| format!("{error:#}")));+ }_ => self.send_response(session_id, request, Err(format!("Unknown request '{}'", request["command"].as_str().unwrap_or_default()))),}}@@ -1155,6 +1159,18 @@ impl Workbench {receiver}+ /// debugUtils.ts `getExtensionHostDebugSession`: the session or its nearest parent that debugs an extension host.+ fn extension_host_debug_session(&self, session_id: &str) -> Option<&Session> {+ let mut session = self.debug.session(session_id)?;+ loop {+ let debug_type = session.configuration["type"].as_str()?;+ if debug_type.eq_ignore_ascii_case("extensionhost") || debug_type.eq_ignore_ascii_case("pwa-extensionhost") {+ return Some(session);+ }+ session = self.debug.session(session.parent.as_deref()?)?;+ }+ }+/// debugSession.ts `restart`: the request goes to the parent of a child whose lifecycle it manages.fn restart_request(&mut self, session_id: &str) -> Reply {let Some(session) = self.debug.session(session_id) else { return ready(Value::Null) };@@ -1165,6 +1181,43 @@ impl Workbench {self.dap_request(session_id, "restart", json!({ "arguments": arguments }))}+ /// debugService.ts `onAttachSession`: the extension host a session launched is up with its inspector on `port`, so+ /// the session, active or ended, attaches to it on a new adapter (debugSession.ts `initialize` shuts the old one down).+ pub(crate) fn attach_session(&mut self, session_id: &str, port: u16, window: &mut Window, cx: &mut Context<Self>) {+ let session = match self.debug.sessions.iter().position(|session| session.id == session_id) {+ Some(index) => {+ drop(self.dap_request(session_id, "disconnect", json!({})));+ let session = self.debug.sessions.remove(index);+ self.host.send("ExtHostDebugService", "$stopDASession", vec![json!(session.handle)]);+ session+ }+ None => {+ let Some(index) = self.debug.inactive_sessions.iter().position(|session| session.id == session_id) else { return };+ self.debug.inactive_sessions.remove(index)+ }+ };+ let mut configuration = session.configuration;+ configuration["request"] = json!("attach");+ configuration["port"] = json!(port);+ self.debug.next_handle += 1;+ let mut attaching = Session::new(session.id, self.debug.next_handle, configuration, session.unresolved_configuration, session.folder_uri, session.options);+ attaching.name = session.name;+ attaching.parent = session.parent;+ self.debug.sessions.push(attaching);+ let session_id = session_id.to_owned();+ cx.spawn_in(window, async move |this, cx| {+ let Err((message, show_user)) = launch_or_attach(&this, cx, &session_id).await else { return };+ let _ = on_workbench(&this, cx, |workbench, window, cx| {+ drop(workbench.disconnect_session(session_id, false, true, window, cx));+ if show_user {+ workbench.notify_error(message);+ }+ });+ })+ .detach();+ cx.notify();+ }+/// debugSession.ts `initialize` for a restart: a connection still open is shut down, then the ended session/// returns under its id with a new adapter handle.fn relaunch_session(&mut self, session_id: &str, window: &mut Window, cx: &mut Context<Self>) {@@ -1196,6 +1249,13 @@ impl Workbench {/// debugService.ts `onDidEndAdapter`: the session leaves the model, its requests fail, the focus moves on.pub(super) fn session_ended(&mut self, session_id: &str, window: &mut Window, cx: &mut Context<Self>) {let Some(index) = self.debug.sessions.iter().position(|session| session.id == session_id) else { return };+ // #3905: 'Run Without Debugging' ends the extension development host with its adapter.+ if let Some(extension_session) = self.extension_host_debug_session(session_id)+ && extension_session.initialized+ && extension_session.configuration["noDebug"] == true+ {+ super::host::run_in_extension_development_host(&extension_session.id, "workbench.action.closeWindow", cx);+ }let shown_repl = self.shown_repl_session();let mut session = self.debug.sessions.remove(index);session.exited = true;@@ -1303,6 +1363,24 @@ fn ready(value: Value) -> Reply {receiver}+/// rawDebugSession.ts `launchVsCode`: each argument's `prefix` and `path` joined, the environment as+/// `--extensionEnvironment`.+fn launch_vs_code_args(arguments: &Value) -> Vec<String> {+ let mut args = Vec::new();+ for arg in arguments["args"].as_array().into_iter().flatten() {+ let arg = format!("{}{}", arg["prefix"].as_str().unwrap_or_default(), arg["path"].as_str().unwrap_or_default());+ // js-debug turns a folder or file argument into `--folder-uri` or `--file-uri`; as paths they open the same.+ match arg.split_once('=') {+ Some(("--folder-uri" | "--file-uri", path)) => args.push(path.to_owned()),+ _ => args.push(arg),+ }+ }+ if arguments["env"].is_object() {+ args.push(format!("--extensionEnvironment={}", arguments["env"]));+ }+ args+}+/// The DAP `Source` of a breakpoint's resource: a file's path, else the URI string.fn source_of_uri(uri: &Value) -> Value {let path = match uri["scheme"].as_str() {@@ -1645,6 +1723,14 @@ async fn restart_flow(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext,}})?;let tasks = if restart_data.is_some() { DebugTasks::None } else { DebugTasks::Restart };+ // An extension host session reloads its development window instead.+ let extension_host = on_workbench(this, cx, |workbench, _, _| Some((workbench.extension_host_debug_session(session_id)?.id.clone(), workbench.debug.session(session_id)?.configuration.clone())))?;+ if let Some((extension_session_id, configuration)) = extension_host {+ if run_debug_tasks(this, cx, tasks, &configuration).await? {+ on_workbench(this, cx, |_, _, cx| super::host::run_in_extension_development_host(&extension_session_id, "workbench.action.reloadWindow", cx))?;+ }+ return Ok(());+ }let found = on_workbench(this, cx, |workbench, _, _| {let session = workbench.debug.session(session_id)?;Some((session.folder_uri.clone(), session.configuration.clone(), session.unresolved_configuration.clone(), session.capabilities["supportsRestartRequest"] == true))@@ -1761,6 +1847,8 @@ async fn launch_or_attach(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContsession.capabilities = if capabilities.is_object() { capabilities.clone() } else { json!({}) };session.initialized = true;let filters = session.capabilities["exceptionBreakpointFilters"].as_array().cloned().unwrap_or_default();+ // debugSession.ts `launchOrAttach`: js-debug passes the id to an extension host it launches as `--debugId`.+ session.configuration["__sessionId"] = json!(session_id);let (request, configuration) = (session.configuration["request"].as_str().unwrap_or("launch").to_owned(), session.configuration.clone());workbench.debug.model.set_exception_breakpoints_for_session(session_id, &filters);workbench.store_debug_model();@@ -1772,7 +1860,10 @@ async fn launch_or_attach(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContSome(launch)});let Ok(Some(launch)) = launch else { return Err(("Canceled".into(), false)) };- match launch.await.unwrap_or(Err(Value::Null)) {+ // debugSession.ts `shutdown` drops a connection without answering its requests: the launch an attach replaced+ // (`attach_session`) waits on, as upstream's does.+ let Ok(result) = launch.await else { return std::future::pending().await };+ match result {Ok(_) => Ok(()),Err(error) => Err((error_message(&error), error["showUser"] != false)),}diff --git a/native/crates/app/src/workbench/extension_host_restart.rs b/native/crates/app/src/workbench/extension_host_restart.rsindex 1f1b3332405..9ea9c2a2ae6 100644--- a/native/crates/app/src/workbench/extension_host_restart.rs+++ b/native/crates/app/src/workbench/extension_host_restart.rs@@ -15,7 +15,7 @@ use exthost::session::ForwardedRequest;use exthost::Runtime;use futures::StreamExt;use futures::channel::mpsc::{UnboundedReceiver, unbounded};-use gpui::{Context, Window};+use gpui::{App, Context, Window};use serde_json::{Value, json};use super::Workbench;@@ -74,7 +74,7 @@ impl Workbench {Ok(user) => add_user_extensions(&mut installed, user.unwrap_or_default()),Err(error) => eprintln!("[extensions] scanning the user extensions: {error:#}"),}- let development = development_without_tests();+ let development = self.development_without_tests();if let Some(development) = &development&& let Err(error) = development.add_extension(&mut installed){@@ -136,11 +136,13 @@ impl Workbench {let window_closed = Arc::new(AtomicBool::new(false));let (session_ended, ended) = futures::channel::oneshot::channel::<()>();self.watch_session_end(window_closed.clone(), ended, cx);+ let development = self.development_without_tests();+ let host_debug = self.extension_host_debug.clone();+ let start = self.extension_host_started(cx);std::thread::Builder::new().name("exthost-session".into()).spawn(move || {- let development = development_without_tests();- let started = crate::run_extension_host(runtime, app_root, extensions, settings, storage, trusted, user_data, workspace, development, main_thread, request_sender, replies, &status, &window_closed);+ let started = crate::run_extension_host(runtime, app_root, extensions, settings, storage, trusted, user_data, workspace, development, host_debug, main_thread, request_sender, replies, &status, &window_closed);if let Err(error) = started {let _ = status.unbounded_send(format!("extension host failed: {error:#}"));}@@ -152,6 +154,9 @@ impl Workbench {cx.spawn_in(window, async move |workbench, cx| {while let Some(line) = status_lines.next().await {eprintln!("{line}");+ if line == crate::EXITED_LINE {+ let _ = workbench.update_in(cx, |workbench, window, cx| workbench.extension_host_exited(start, window, cx));+ }if line.starts_with(crate::HANDSHAKE_PREFIX) {let _ = workbench.update(cx, |workbench, _| {workbench.host.installed_extensions_registered = true;@@ -164,11 +169,30 @@ impl Workbench {}}-/// The extension under development without its tests: a restarted host does not run them again.-fn development_without_tests() -> Option<ExtensionDevelopment> {- let args: Vec<String> = std::env::args().collect();- let development = ExtensionDevelopment::from_args(&args).ok().flatten()?;- Some(ExtensionDevelopment { tests_path: None, ..development })+impl Workbench {+ /// Counts a host this window starts, whose exit is reported with the returned number, and has a debug session+ /// attach to its inspector port.+ pub fn extension_host_started(&mut self, cx: &mut App) -> u32 {+ self.extension_host_starts += 1;+ super::host::attach_extension_host_session(&self.extension_host_debug, cx);+ self.extension_host_starts+ }++ /// abstractExtensionService.ts `_onExtensionHostCrashOrExit`: the exit of an extension development window's+ /// current host closes the window (nativeExtensionService.ts `_onExtensionHostExit`). A host a restart replaced+ /// does not count.+ pub fn extension_host_exited(&mut self, start: u32, window: &mut Window, cx: &mut Context<Self>) {+ if start != self.extension_host_starts || !self.extension_development {+ return;+ }+ _ = self.execute_command("workbench.action.closeWindow", vec![], window, cx);+ }++ /// The extension under development without its tests: a restarted host does not run them again.+ fn development_without_tests(&self) -> Option<ExtensionDevelopment> {+ let development = self.development.clone()?;+ Some(ExtensionDevelopment { tests_path: None, ..development })+ }}/// Answers the host requests the session forwards to the workbench, each on the window's thread.diff --git a/native/crates/app/src/workbench/host.rs b/native/crates/app/src/workbench/host.rsindex 25550b98c96..b79c07e1d36 100644--- a/native/crates/app/src/workbench/host.rs+++ b/native/crates/app/src/workbench/host.rs@@ -6,6 +6,7 @@ use std::path::PathBuf;use std::sync::Arc;use std::sync::atomic::{AtomicBool, Ordering};+use exthost::extension_development::{ExtensionDevelopment, ExtensionHostDebug};use futures::channel::oneshot;use gpui::{App, Context, Window, WindowHandle};#[cfg(target_os = "macos")]@@ -106,7 +107,12 @@ impl Workbench {(false, _) => Default::default(),};workbench.user_data_profiles.reloading = reason == ShutdownReason::Reload;- let request = WindowRequest { workspace: folder.map(config::workspace::Workspace::open), backup_folder, ui: Some(crate::windows_state::ui_state(window, cx)), profile, files, ..WindowRequest::default() };+ // windowImpl.ts `reload`: an extension development window stays one, with its debug flags.+ let (development, host_debug) = match reason == ShutdownReason::Reload {+ true => (workbench.development.clone(), workbench.extension_host_debug.clone()),+ false => Default::default(),+ };+ let request = WindowRequest { workspace: folder.map(config::workspace::Workspace::open), backup_folder, ui: Some(crate::windows_state::ui_state(window, cx)), profile, files, development, host_debug, ..WindowRequest::default() };workbench.lifecycle.window_closed = true;workbench.delete_wait_markers();workbench.remove_auxiliary_windows(cx);@@ -313,6 +319,57 @@ pub(super) fn open_command_line_window(path: Option<PathBuf>, mut files: FilesTo});}+/// extensionHostDebugIpc.ts and windowsMainService.ts `openExtensionDevelopmentHostWindow`: the window on the same+/// extension path reloads with the new debug flags, else a new window opens on the arguments' folder and files.+pub(super) fn open_extension_development_host_window(args: &[String], cx: &mut App) -> anyhow::Result<()> {+ let Some(development) = ExtensionDevelopment::from_args(args)? else { anyhow::bail!("no --extensionDevelopmentPath") };+ let host_debug = ExtensionHostDebug::from_args(args);+ let (parsed, _) = crate::argv::parse_and_validate(args).map_err(anyhow::Error::msg)?;+ let CommandLine { workspaces, files, .. } = CommandLine::from_args(&parsed, &std::env::current_dir()?);+ cx.defer(move |cx| {+ let mut windows = cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>());+ let existing = windows.find(|handle| handle.read(cx).is_ok_and(|workbench| workbench.development.as_ref().is_some_and(|open| open.extension_path == development.extension_path)));+ if let Some(handle) = existing {+ drop(handle.update(cx, |workbench, window, cx| {+ workbench.extension_host_debug = host_debug;+ let folder = workbench.workspace_location();+ workbench.relaunch(ShutdownReason::Reload, folder, FilesToOpen::default(), window, cx)+ }));+ return;+ }+ let request = WindowRequest { workspace: workspaces.into_iter().next().map(config::workspace::Workspace::open), files, development: Some(development), host_debug, ..WindowRequest::default() };+ #[cfg(not(test))]+ open_window_or_log(request, cx);+ #[cfg(test)]+ tests::open_request_window(request, cx);+ });+ Ok(())+}++/// extensionHostDebugService.ts `close` and `reload` as localProcessExtensionHost.ts hears them: the extension+/// development window whose `--debugId` is the session's runs `command`.+pub(super) fn run_in_extension_development_host(debug_id: &str, command: &'static str, cx: &mut App) {+ let debug_id = debug_id.to_owned();+ cx.defer(move |cx| {+ let mut windows = cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>());+ let found = windows.find(|handle| handle.read(cx).is_ok_and(|workbench| workbench.extension_development && workbench.extension_host_debug.debug_id.as_deref() == Some(debug_id.as_str())));+ let Some(handle) = found else { return };+ drop(handle.update(cx, |workbench, window, cx| workbench.execute_command(command, vec![], window, cx)));+ });+}++/// localProcessExtensionHost.ts `attachSession`: a host started with an inspector port in a window a debug session+/// launched has that session, in whichever window runs it, attach to the port.+pub(super) fn attach_extension_host_session(host_debug: &ExtensionHostDebug, cx: &mut App) {+ let (Some(debug_id), Some(port)) = (host_debug.debug_id.clone(), host_debug.port) else { return };+ cx.defer(move |cx| {+ let mut windows = cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>());+ let found = windows.find(|handle| handle.read(cx).is_ok_and(|workbench| workbench.debug.sessions_including_inactive().iter().any(|session| session.id == debug_id)));+ let Some(handle) = found else { return };+ drop(handle.update(cx, |workbench, window, cx| workbench.attach_session(&debug_id, port, window, cx)));+ });+}+/// Electron's `setAlwaysOnTop` on macOS: the floating window level.#[cfg(target_os = "macos")]pub(super) fn is_always_on_top(window: &Window) -> bool {diff --git a/native/crates/app/src/workbench/host/tests.rs b/native/crates/app/src/workbench/host/tests.rsindex a704e200e2f..5a5813554fa 100644--- a/native/crates/app/src/workbench/host/tests.rs+++ b/native/crates/app/src/workbench/host/tests.rs@@ -1,11 +1,15 @@-use std::path::Path;+use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex};use config::registry::Registry;use config::service::Settings;+use exthost::extension_development::{ExtensionDevelopment, ExtensionHostDebug};use exthost::scan::scan_extension;+use exthost::session::ForwardedRequest;use gpui::{AppContext, TestAppContext, VisualTestContext};+use serde_json::json;+use crate::debug::session::Session;use crate::host_sync::HostSync;use crate::languages::Languages;use crate::quick_input::Event;@@ -22,6 +26,101 @@ fn empty_window(cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, gpui::AnyW(workbench, vcx.update(|window, _| window.window_handle()))}+/// rawDebugSession.ts `launchVsCode`: js-debug's `launchVSCode` opens an extension development window with the+/// debug flags, and the adapter hears it opened.+#[gpui::test]+fn launch_vs_code_opens_an_extension_development_window_with_the_debug_flags(cx: &mut TestAppContext) {+ let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();+ let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();+ let (sender, host) = std::sync::mpsc::channel();+ let (workbench, vcx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root, None, Languages::new(&[]), crate::default_settings(), HostSync::new(sender), cx));+ let request = json!({ "type": "request", "seq": 3, "command": "launchVSCode", "arguments": {+ "args": [{ "prefix": "--debugId=s" }, { "prefix": "--inspect-brk-extensions=9229" }, { "prefix": "--extensionDevelopmentPath=", "path": { "$mid": 1, "scheme": "file", "path": "/tmp/ext" } }],+ "env": { "A": "1" },+ } });+ workbench.update_in(vcx, |workbench, window, cx| {+ workbench.debug.sessions.push(Session::new("s".into(), 1, json!({ "name": "Run Extension", "type": "pwa-extensionHost", "request": "launch" }), json!({}), None, json!({})));+ drop(workbench.handle_debug_request(ForwardedRequest { req: 1, proxy: "MainThreadDebugService", method: "$acceptDAMessage".into(), args: vec![json!(1), request] }, window, cx));+ });+ vcx.run_until_parked();+ let response = host.try_iter().find(|message| message.method == "$sendDAMessage").expect("the response").args[1].clone();+ assert_eq!((response["command"].clone(), response["success"].clone()), (json!("launchVSCode"), json!(true)));+ let opened: Vec<_> = vcx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()).filter_map(|handle| handle.read_with(vcx, |workbench, _| workbench.development.clone().map(|development| (development.extension_path, workbench.extension_host_debug.clone()))).ok().flatten()).collect();+ let env = [("A".to_owned(), "1".to_owned())].into_iter().collect();+ assert_eq!(opened, [(PathBuf::from("/tmp/ext"), ExtensionHostDebug { port: Some(9229), break_on_start: true, debug_id: Some("s".into()), env })]);+}++/// debugService.ts `onDidEndAdapter` (#3905): the end of a 'Run Without Debugging' extension host session closes its+/// development window, and only that one.+#[gpui::test]+fn the_end_of_a_run_without_debugging_session_closes_its_extension_development_window(cx: &mut TestAppContext) {+ let (workbench, window) = empty_window(cx);+ let development = |debug_id: &str| crate::WindowRequest { development: Some(ExtensionDevelopment { extension_path: "/tmp/ext".into(), tests_path: None }), host_debug: ExtensionHostDebug { debug_id: Some(debug_id.into()), ..Default::default() }, ..Default::default() };+ cx.update(|cx| {+ open_request_window(development("s"), cx);+ open_request_window(development("another"), cx);+ });+ let vcx = &mut VisualTestContext::from_window(window, cx);+ workbench.update_in(vcx, |workbench, window, cx| {+ let mut session = Session::new("s".into(), 1, json!({ "name": "Run Extension", "type": "extensionHost", "request": "launch", "noDebug": true }), json!({}), None, json!({}));+ session.initialized = true;+ workbench.debug.sessions.push(session);+ workbench.session_ended("s", window, cx);+ let mut debugged = Session::new("another".into(), 2, json!({ "name": "Run Extension", "type": "extensionHost", "request": "launch" }), json!({}), None, json!({}));+ debugged.initialized = true;+ workbench.debug.sessions.push(debugged);+ workbench.session_ended("another", window, cx);+ });+ vcx.run_until_parked();+ let debug_ids: Vec<_> = vcx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()).filter_map(|handle| handle.read_with(vcx, |workbench, _| workbench.extension_host_debug.debug_id.clone()).ok()).collect();+ assert_eq!(debug_ids, [None, Some("another".to_owned())], "the debugging window and the other session's window stay");+}++/// nativeExtensionService.ts `_onExtensionHostExit`: an extension development window closes with its host, but not for+/// the exit of a host a restart replaced.+#[gpui::test]+fn an_extension_development_window_closes_when_its_current_host_exits(cx: &mut TestAppContext) {+ let (workbench, window) = empty_window(cx);+ let vcx = &mut VisualTestContext::from_window(window, cx);+ let replaced = workbench.update(vcx, |workbench, cx| {+ workbench.extension_development = true;+ let replaced = workbench.extension_host_started(cx);+ workbench.extension_host_started(cx);+ replaced+ });+ workbench.update_in(vcx, |workbench, window, cx| workbench.extension_host_exited(replaced, window, cx));+ vcx.run_until_parked();+ assert_eq!(vcx.windows().len(), 1, "a replaced host's exit leaves the window open");+ workbench.update_in(vcx, |workbench, window, cx| workbench.extension_host_exited(replaced + 1, window, cx));+ vcx.run_until_parked();+ assert_eq!(vcx.windows().len(), 0);+}++/// localProcessExtensionHost.ts `attachSession` and debugService.ts `onAttachSession`: a debugged extension host's+/// start has the session that launched it attach to its inspector port on a new adapter.+#[gpui::test]+fn a_debugged_extension_host_start_attaches_its_session(cx: &mut TestAppContext) {+ let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();+ let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();+ let (sender, host) = std::sync::mpsc::channel();+ let (workbench, vcx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root, None, Languages::new(&[]), crate::default_settings(), HostSync::new(sender), cx));+ workbench.update(vcx, |workbench, cx| {+ workbench.debug.sessions.push(Session::new("s".into(), 7, json!({ "name": "Run Extension", "type": "pwa-extensionHost", "request": "launch" }), json!({}), None, json!({})));+ let host_debug = ExtensionHostDebug { port: Some(9229), break_on_start: true, debug_id: Some("s".into()), env: Default::default() };+ workbench.extension_host_debug = host_debug;+ workbench.extension_host_started(cx);+ });+ vcx.run_until_parked();+ let messages: Vec<_> = host.try_iter().filter(|message| message.method.ends_with("DASession")).map(|message| (message.method, message.args[0].clone())).collect();+ let (handle, configuration) = workbench.read_with(vcx, |workbench, _| {+ let session = workbench.debug.session("s").unwrap();+ (session.handle, session.configuration.clone())+ });+ assert_eq!(messages, [("$stopDASession", json!(7)), ("$startDASession", json!(handle))]);+ assert_ne!(handle, 7);+ assert_eq!((configuration["request"].clone(), configuration["port"].clone()), (json!("attach"), json!(9229)));+}+/// `open_window_or_log` for a test: an empty workbench window with the request's files.pub(crate) fn open_request_window(request: crate::WindowRequest, cx: &mut gpui::App) {let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();@@ -30,6 +129,9 @@ pub(crate) fn open_request_window(request: crate::WindowRequest, cx: &mut gpui::cx.new(|cx| {let mut workbench = Workbench::new(theme, app_root, request.workspace, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx);workbench.open_command_line_files(request.files, None, window, cx);+ workbench.extension_development = request.development.is_some();+ workbench.development = request.development;+ workbench.extension_host_debug = request.host_debug;workbench})});diff --git a/native/crates/exthost/src/extension_development.rs b/native/crates/exthost/src/extension_development.rsindex 6440cf4d0c6..f9acae4ea3d 100644--- a/native/crates/exthost/src/extension_development.rs+++ b/native/crates/exthost/src/extension_development.rs@@ -7,11 +7,42 @@ use serde_json::{Value, json};use crate::scan::{ScannedExtension, file_uri, scan_extension};+#[derive(Clone, Debug, PartialEq)]pub struct ExtensionDevelopment {pub extension_path: PathBuf,pub tests_path: Option<PathBuf>,}+/// environmentService.ts `debugExtensionHost` (`parseExtensionHostDebugPort`): `--inspect-extensions=<port>` or+/// `--inspect-brk-extensions=<port>`, `--debugId=<debug session>` and `--extensionEnvironment=<JSON object>`.+/// shortcut: no 5870 default port of a build from source, the checkout would always run Node.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct ExtensionHostDebug {+ pub port: Option<u16>,+ pub break_on_start: bool,+ pub debug_id: Option<String>,+ pub env: Vec<(String, String)>,+}++impl ExtensionHostDebug {+ pub fn from_args(args: &[String]) -> Self {+ let value = |flag: &str| args.iter().find_map(|arg| arg.strip_prefix(flag)?.strip_prefix('='));+ let brk_port = value("--inspect-brk-extensions").and_then(|port| port.parse::<u16>().ok()).filter(|port| *port != 0);+ let port = brk_port.or_else(|| value("--inspect-extensions").and_then(|port| port.parse::<u16>().ok()).filter(|port| *port != 0));+ // parseDebugParams ignores an environment that is not JSON; values that are not strings are left out.+ let env = value("--extensionEnvironment").and_then(|json| serde_json::from_str::<serde_json::Map<String, Value>>(json).ok()).unwrap_or_default();+ let env = env.into_iter().filter_map(|(key, value)| Some((key, value.as_str()?.to_owned()))).collect();+ ExtensionHostDebug { port, break_on_start: brk_port.is_some(), debug_id: value("--debugId").map(str::to_owned), env }+ }++ /// localProcessExtensionHost.ts `_start` execArgv: the inspector on the port, paused before the first line with+ /// `--inspect-brk-extensions`. Bun has no V8 inspector, so a debugged host runs on Node.+ pub fn node_args(&self, port: u16) -> Vec<String> {+ let inspect = if self.break_on_start { "--inspect-brk" } else { "--inspect" };+ vec!["--dns-result-order=ipv4first".into(), "--experimental-network-inspection".into(), "--nolazy".into(), format!("{inspect}=127.0.0.1:{port}")]+ }+}+impl ExtensionDevelopment {/// Reads `--extensionDevelopmentPath=<dir>` and `--extensionTestsPath=<path>` (the `=` form upstream's scripts pass)./// Paths are made absolute without resolving symlinks, as environmentService's `path.resolve` does.@@ -68,6 +99,17 @@ mod tests {assert!(ExtensionDevelopment::from_args(&args(&["code-gpui", &format!("--extensionTestsPath={}", dir.display())])).is_err());}+ #[test]+ fn reads_the_extension_host_debug_flags() {+ let args = |list: &[&str]| list.iter().map(|arg| arg.to_string()).collect::<Vec<_>>();+ let debug = ExtensionHostDebug::from_args(&args(&["code", "--debugId=abc", "--inspect-brk-extensions=9333", r#"--extensionEnvironment={"A":"1","B":null}"#]));+ assert_eq!(debug, ExtensionHostDebug { port: Some(9333), break_on_start: true, debug_id: Some("abc".into()), env: vec![("A".into(), "1".into())] });+ assert_eq!(debug.node_args(9333), ["--dns-result-order=ipv4first", "--experimental-network-inspection", "--nolazy", "--inspect-brk=127.0.0.1:9333"]);+ let debug = ExtensionHostDebug::from_args(&args(&["code", "--inspect-extensions=9334", "--extensionEnvironment=nope"]));+ assert_eq!((debug.port, debug.break_on_start, debug.env.len()), (Some(9334), false, 0));+ assert_eq!(ExtensionHostDebug::from_args(&args(&["code", "--inspect-extensions"])), ExtensionHostDebug::default());+ }+#[test]fn replaces_the_builtin_with_the_development_copy() {let dir = std::env::temp_dir().join(format!("extension-development-{}", std::process::id()));diff --git a/native/crates/exthost/src/session.rs b/native/crates/exthost/src/session.rsindex efb8e2c611b..bef4a50bfe8 100644--- a/native/crates/exthost/src/session.rs+++ b/native/crates/exthost/src/session.rs@@ -144,6 +144,7 @@ pub fn configuration_init_data(extensions: &[ScannedExtension]) -> Value {data}+#[derive(Debug)]pub enum CallResult {Ok(Reply),Err(Option<Value>),@@ -265,8 +266,11 @@ impl Session {let delta = json!({"versionId": 1, "toRemove": [], "toAdd": [], "addActivationEvents": {}, "myToRemove": [], "myToAdd": [],});- self.call("ExtHostExtensionService", "$startExtensionHost", vec![Arg::Json(delta)], Duration::from_secs(60))?;- Ok(())+ // No timeout, as upstream: a host paused at a breakpoint of an eager extension (`--inspect-brk-extensions`) answers once it runs on.+ match self.request("ExtHostExtensionService", "$startExtensionHost", vec![Arg::Json(delta)], None)? {+ CallResult::Ok(_) => Ok(()),+ CallResult::Err(error) => anyhow::bail!("ExtHostExtensionService.$startExtensionHost failed: {}", error.unwrap_or(Value::Null)),+ }}/// The part of a delta `_deltaExtensions` applies: `canRemoveExtension` drops ids that are unknown or whosediff --git a/port/fixtures/debug-extension/.vscode/launch.json b/port/fixtures/debug-extension/.vscode/launch.jsonnew file mode 100644index 00000000000..83aae78e6e5--- /dev/null+++ b/port/fixtures/debug-extension/.vscode/launch.json@@ -0,0 +1,11 @@+{+ "version": "0.2.0",+ "configurations": [+ {+ "type": "extensionHost",+ "request": "launch",+ "name": "Run Extension",+ "args": ["--extensionDevelopmentPath=${workspaceFolder}"]+ }+ ]+}diff --git a/port/fixtures/debug-extension/extension.js b/port/fixtures/debug-extension/extension.jsnew file mode 100644index 00000000000..d87d70ee51a--- /dev/null+++ b/port/fixtures/debug-extension/extension.js@@ -0,0 +1,8 @@+const vscode = require('vscode');++function activate() {+ const message = 'debug-extension activated';+ vscode.window.showInformationMessage(message);+}++module.exports = { activate };diff --git a/port/fixtures/debug-extension/package.json b/port/fixtures/debug-extension/package.jsonnew file mode 100644index 00000000000..58fb4eee8e8--- /dev/null+++ b/port/fixtures/debug-extension/package.json@@ -0,0 +1,12 @@+{+ "name": "debug-extension",+ "publisher": "vsrustium",+ "version": "0.0.1",+ "engines": {+ "vscode": "^1.100.0"+ },+ "main": "./extension.js",+ "activationEvents": [+ "onStartupFinished"+ ]+}diff --git a/port/fixtures/ui-pair/debug/extension-host.json b/port/fixtures/ui-pair/debug/extension-host.jsonnew file mode 100644index 00000000000..203aa0ecb24--- /dev/null+++ b/port/fixtures/ui-pair/debug/extension-host.json@@ -0,0 +1,69 @@+[+ {+ "wait": 25000+ },+ {+ "hotkey": [+ "cmd",+ "p"+ ],+ "foreground": true+ },+ {+ "wait": 1000+ },+ {+ "type": "extension.js"+ },+ {+ "wait": 1000+ },+ {+ "key": "return",+ "foreground": true+ },+ {+ "wait": 1000+ },+ {+ "hotkey": [+ "ctrl",+ "g"+ ],+ "foreground": true+ },+ {+ "wait": 500+ },+ {+ "type": "4"+ },+ {+ "key": "return",+ "foreground": true+ },+ {+ "wait": 500+ },+ {+ "key": "f9",+ "foreground": true+ },+ {+ "key": "f5",+ "foreground": true+ },+ {+ "wait": 60000+ },+ {+ "windows": "launched"+ },+ {+ "shot": "stopped"+ },+ {+ "window": "auxiliary",+ "shot": "host"+ }+]diff --git a/port/ledger.md b/port/ledger.mdindex fa8c0a98bf0..e55f3838654 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -475,7 +475,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| workbench/contrib/commands | workbench contribution | M9 | verified | | runCommands (commands.rs register_run_commands): cargo test -p app commands::, argument checks, spread args, order, stop at a failure; argument errors and the failure notify (cargo test -p app run_commands_argument_errors_notify) || workbench/contrib/comments | workbench contribution | M13 | verified | | Done: a reply and an edit form per thread and comment, open together (commentReply.ts per CommentThreadWidget): cargo test -p app two_threads_keep_their_reply_forms_open_together; a zone sized by the drawn comment bodies: cargo test -p app a_wrapped_comment_body_grows_its_zone; next/previous thread and Focus Comment on Current Line focus the thread's comments (`commentFocused`, Up/Down between comments, Escape collapses and selects the range): cargo test -p app the_reached_thread_takes_the_focus. Done in diff editors: glyphs, commenting ranges (asked for every side of every multi diff file), range highlights and zones on both sides of the diff editor and of each multi diff file, the other side aligned by a diagonal fill (workbench/editor_view/diff_editor_view.rs, multi_diff_editor_view.rs, diff_editor.rs `additional_heights`): cargo test -p app diff comment; ui-pair `portComments.openDiff` modified, original and multi. Floating widgets on a diff's original side and on both sides of each multi diff file (comment_thread_floating.rs `FloatingHost`, multi_diff_editor_view.rs `multi_diff_floating_hosts`), with `FloatingWidgetRoom` growing a file below its last line (commentThreadFloatingWidgetRoom.ts, `FileDiff.room`): cargo test -p app floating room multi_diff; ui-pair `portComments.openDiff` original and multi with the floating style. Range decorations (commentThreadRangeDecorator.ts and the floating empty-range line, workbench/comment_thread_widget.rs `comment_range_highlights`): cargo test -p app comment_thread_floating. The floating thread style (`comments.thread.experimental.style: floating`; workbench/comment_thread_floating_layout.rs with commentThreadFloatingWidget.test.ts ported, workbench/comment_thread_floating.rs: placement beside the code or its lines in code order, the outline and connector, title drag, edge resize, double-click reset, the layout kept per thread, wheel to the editor): cargo test -p app comment_thread_floating, ui-pair steps-comment-floating.json (port/results/language-features.md Floating comment threads). Done: the Comments panel (workbench/comments_view.rs: resources, threads with author, relative time, first line, range and replies, the unresolved badge, a markdown preview's images as "Image: {alt}" (cargo test -p app a_markdown_comment_previews_its_first_rendered_block), the filter box with Show Resolved/Unresolved and Sort By, its history in the memento's `filterHistory`, Escape and Cmd+Down while `commentsFilterFocus` (cargo test -p app the_filter_keeps_its_history_and_escape_clears_it; no match highlights, as commentsTreeViewer.ts's renderers ignore the filter data), Collapse/Expand All, row selection and keys; hideIfEmpty; a thread row's `commentsView/commentThread/context` inline actions and context menu with the built-in Reply, which reveals the thread with its zone expanded and reply open: cargo test -p app the_thread_menu_replies_to_the_thread), the gutter glyph that toggles the thread (workbench/editor_view/comment_glyph.rs) and the thread widget (workbench/comment_thread_widget.rs: zone, state colors, head with `comments/commentThread/title` actions and Collapse, markdown comments with `code` spans on no `textCodeBlock.background` (cargo test -p app a_comment_s_code_span_draws_no_code_block_background), reply form with `comments/commentThread/context` buttons and Cmd+Enter), each comment (workbench/comment_node.rs: `comments/comment/title` actions, edit mode with `comments/comment/context` buttons, reactions and their picker), commenting ranges with the add glyph, Add Comment and template threads (workbench/commenting_ranges.rs), the comment commands (workbench/comment_navigation.rs: Collapse/Expand All, Expand Unresolved, Toggle Editor Commenting, Focus Comment on Current Line, Dismiss Comment, next/previous thread, commented range and commenting range, reached at the provider's columns unless it holds the cursor: cargo test -p app a_commenting_range_is_reached_at_its_columns_unless_it_holds_the_cursor) and the comments accessibility help: cargo test -p app comment; ui-pair port/results/language-features.md (Comments, Comment editing and commands); Escape keeps a new template open as the reference does (ui-pair steps-comment-escape-typed.json, cargo test -p app dismissing_a_new_template_keeps_it_open). The reply and edit inputs are code editors (simpleCommentEditor.ts: a `comment`-scheme markdown model, word wrap, no glyph margin, line numbers or folding, `scrollBeyondLastLine` false, 5 to 25 lines by `calculateEditorHeight`) that take the focus with `commentEditorFocused`, Cmd+Enter submits and Escape hides; the host gets the input's document and no text editor (workbench/comment_thread_widget.rs `open_comment_editor`, workbench/editor.rs `comment_editor`): cargo test -p app an_expanded_thread_shows_a_zone_and_replies_run_the_form_actions a_comment_switched_to_editing_runs_the_edit_actions; ui-pair steps-comment-reply-editor.json (reply-empty, reply-lines, reply-grown). Comments panel rows: 4px pane inset, 4px radius and the tree's indent guides as the Problems tree (cargo test -p app rows_sit_in_the_pane_s_inset_with_the_tree_s_indent_and_guides; ui-pair steps-comments.json: chevron, name and thread line at the reference's x and y) || workbench/contrib/customEditor | workbench contribution | M17 | verified | | Each editor of a custom text editor's resource, the one opened in another group and a split's copy, has a webview of its own (customEditorInput.ts: cargo test -p app each_group_s_custom_text_editor_has_its_own_webview); Opening a custom text editor with `options.selection` reveals it in the panel and leaves the text model's cursor (cargo test -p app a_custom_text_editor_s_navigation_drives_the_outline); A custom document open in another group moves to the active one, or with `supportsMultipleEditorsPerDocument` gets a second editor there (editorResolverService.ts `moveExistingEditorForResource`: cargo test -p app a_custom_document_open_in_another_group_moves_to_the_active_one a_custom_document_with_multiple_editors_opens_one_more_in_the_active_group); `workbench.editorAssociations` merged as editorResolverService.ts `getAllUserAssociationsForSetting`: the workspace's globs before the default's and user's (cargo test -p app a_workspace_association_wins_over_a_user_one_of_the_same_length); Reopen Editor With puts a closed custom or notebook editor's replacement in its place, pinned (editorGroupView.ts `replaceEditors`: cargo test -p app a_reopened_preview_keeps_its_tab_position); Two default editors for one resource warn once and remember the choice per extension glob (editorResolverService.ts `doHandleConflictingDefaults`: cargo test -p app two_default_editors_for_a_resource_ask_once_which_to_keep); the memento's custom editors until the extensions register (cargo test -p app markdown_editor_files_offer); editor resolution by `workbench.editorAssociations` and contributed selectors (editorResolverService.ts ranks), Reopen Editor With picker (`reopenActiveEditorWith`, `workbench.action.reopenWithEditor`), `_workbench.open`, `_workbench.openWith`; `FIXTURE=custom-editor-tests port/tools/webview-check` 8/8; cargo test -p app custom_editors |-| workbench/contrib/debug | workbench contribution | M16 | ported | [3 M] disassembly_view.rs: the instruction table has no keyboard focus, selection or column sash (disassemblyView.ts WorkbenchTable) <br> [3 M] debug_view.rs: the Call Stack view has no context menu (DebugCallStackContext: the session and thread commands, Restart Frame, Copy Call Stack, Open Disassembly View) <br> [3 L] extensionHost launch type: not ported <br> [3 L] variable context menus: DebugVariablesContext, DebugWatchContext and DebugHoverContext (Copy Value, Copy as Expression, Add to Watch, Set Value, Break When Value Is Read/Changes/Is Accessed, View Binary Data) not ported <br> [3 L] debug visualizers: debugVisualizers.ts, `VisualizedExpression` rows in the Variables view and the hover not ported <br> [3 M] lazy variables: `presentationHint.lazy` rows and their reveal button (baseDebugView.ts `lazyButton`) not ported in the hover, Variables or Watch <br> [3 M] debug_hover.rs: Alt+click on an expandable hover row (abstractTree.ts `toggleCollapsed(location, recursive)`) expands one level, not the whole subtree <br> [3 M] debug_hover.rs: the hover tree has no find widget (abstractTree.ts `FindController`, `list.find`) | ui-pair port/fixtures/debug-node: gutter breakpoint, F5 stops at it, Variables (Local: main), Call Stack with folded deemphasized frames, Breakpoints, Debug Console REPL, toolbar, status bar entry; cargo test -p app debug; Breakpoints header `$(warning)` hint for the debugger's `strings.unverifiedBreakpoints` after breakpointsView.ts's 4s `hintDelayer`, restarted by every breakpoint change (cargo test -p app debug_view; ui-pair port/fixtures/ui-pair/debug/unverified-breakpoints.json with js-debug's unbound math.test.js breakpoint); preLaunchTask, postDebugTask, compound preLaunchTask and the restart tasks through debugTaskRunner.ts's runner with `debug.onTaskErrors`, the remembered task error choice and the slow task notification (cargo test -p app debug_task_runner); Run to Cursor's temporary breakpoint with debugService.ts `runTo`'s 2s verification wait, thread choice from the sessions that verified it, and removal at the next stop or session end (cargo test -p app debug_commands); Debug Console output styled by its SGR sequences with the theme's ANSI colors at contrast 4 (cargo test -p app debug_console debug::ansi); Debug Console filter box (replFilter.ts terms, "Showing N of M" badge, Cmd+F `repl.action.filter`, value and history in workspace storage) and session picker (consoles of the sessions with `hasSeparateRepl`, `mergeWithParent` children in the parent's, selection focuses the session or its stopped child), input history in workspace storage (`debug.repl.history`) (cargo test -p app debug_console); ended sessions stay inactive in the console picker with their output until Clear Console or a start of the same configuration (debugModel.ts `addSession`, repl.ts `sessionsToIgnore`; cargo test -p app an_ended_session_stays_in_the_picker_until_cleared_or_started_again); debugUtils.ts `saveAllBeforeDebugStart` before a start (not for a child session or with `suppressSaveBeforeStart`) and a restart, by `debug.saveBeforeStart` (cargo test -p app a_start_or_restart_saves_the_dirty_editors); triggered breakpoints: debugSession.ts `enableDependentBreakpoints` by `hitBreakpointIds` or the top frame's position sets `sessionsDidTrigger` and sends the files again, continue and the steps wait for it up to 1.5 s (`waitForTriggeredBreakpoints`), a restart clears it (cargo test -p app a_hit_breakpoint_enables_its_dependents); `debug.inlineValues` after the focused frame's lines: the `InlineValuesProvider`s' values (`$provideInlineValues`) or the most specific scopes' variables named on each line, their `formatHoverContent` hover, the 100ms removal on continue (cargo test -p app debug_inline_values); debugHover.ts in place of the editor hover while a frame is focused in the file: the `$provideEvaluatableExpression` range or the dotted path under the mouse, `hover` evaluation or the scopes' variable, Cmd+K Cmd+I focused, Alt for the editor hover, the tree's list keys and `layoutTree` height, the glyph margin's lockout release, the caret edge nearer the mouse (cargo test -p app debug_hover; ui-pair port/fixtures/debug-node `greeting` and `numbers` hovers); disassemblyView.ts: the `disassemble` requests around the focused frame's instruction pointer, the glyph click's instruction breakpoint (`setInstructionBreakpoints`), the Breakpoints view's instruction rows, `instruction` stepping granularity while the view is active (cargo test -p app disassembly a_step_in_the_disassembly_view debug::tests::instruction_breakpoints debug::tests::remove_instruction_breakpoints); shortcuts in port/notes.md |+| workbench/contrib/debug | workbench contribution | M16 | ported | [3 M] disassembly_view.rs: the instruction table has no keyboard focus, selection or column sash (disassemblyView.ts WorkbenchTable) <br> [3 M] debug_view.rs: the Call Stack view has no context menu (DebugCallStackContext: the session and thread commands, Restart Frame, Copy Call Stack, Open Disassembly View) <br> [3 L] variable context menus: DebugVariablesContext, DebugWatchContext and DebugHoverContext (Copy Value, Copy as Expression, Add to Watch, Set Value, Break When Value Is Read/Changes/Is Accessed, View Binary Data) not ported <br> [3 L] debug visualizers: debugVisualizers.ts, `VisualizedExpression` rows in the Variables view and the hover not ported <br> [3 M] lazy variables: `presentationHint.lazy` rows and their reveal button (baseDebugView.ts `lazyButton`) not ported in the hover, Variables or Watch <br> [3 M] debug_hover.rs: Alt+click on an expandable hover row (abstractTree.ts `toggleCollapsed(location, recursive)`) expands one level, not the whole subtree <br> [3 M] debug_hover.rs: the hover tree has no find widget (abstractTree.ts `FindController`, `list.find`) | ui-pair port/fixtures/debug-node: gutter breakpoint, F5 stops at it, Variables (Local: main), Call Stack with folded deemphasized frames, Breakpoints, Debug Console REPL, toolbar, status bar entry; cargo test -p app debug; Breakpoints header `$(warning)` hint for the debugger's `strings.unverifiedBreakpoints` after breakpointsView.ts's 4s `hintDelayer`, restarted by every breakpoint change (cargo test -p app debug_view; ui-pair port/fixtures/ui-pair/debug/unverified-breakpoints.json with js-debug's unbound math.test.js breakpoint); preLaunchTask, postDebugTask, compound preLaunchTask and the restart tasks through debugTaskRunner.ts's runner with `debug.onTaskErrors`, the remembered task error choice and the slow task notification (cargo test -p app debug_task_runner); Run to Cursor's temporary breakpoint with debugService.ts `runTo`'s 2s verification wait, thread choice from the sessions that verified it, and removal at the next stop or session end (cargo test -p app debug_commands); Debug Console output styled by its SGR sequences with the theme's ANSI colors at contrast 4 (cargo test -p app debug_console debug::ansi); Debug Console filter box (replFilter.ts terms, "Showing N of M" badge, Cmd+F `repl.action.filter`, value and history in workspace storage) and session picker (consoles of the sessions with `hasSeparateRepl`, `mergeWithParent` children in the parent's, selection focuses the session or its stopped child), input history in workspace storage (`debug.repl.history`) (cargo test -p app debug_console); ended sessions stay inactive in the console picker with their output until Clear Console or a start of the same configuration (debugModel.ts `addSession`, repl.ts `sessionsToIgnore`; cargo test -p app an_ended_session_stays_in_the_picker_until_cleared_or_started_again); debugUtils.ts `saveAllBeforeDebugStart` before a start (not for a child session or with `suppressSaveBeforeStart`) and a restart, by `debug.saveBeforeStart` (cargo test -p app a_start_or_restart_saves_the_dirty_editors); triggered breakpoints: debugSession.ts `enableDependentBreakpoints` by `hitBreakpointIds` or the top frame's position sets `sessionsDidTrigger` and sends the files again, continue and the steps wait for it up to 1.5 s (`waitForTriggeredBreakpoints`), a restart clears it (cargo test -p app a_hit_breakpoint_enables_its_dependents); `debug.inlineValues` after the focused frame's lines: the `InlineValuesProvider`s' values (`$provideInlineValues`) or the most specific scopes' variables named on each line, their `formatHoverContent` hover, the 100ms removal on continue (cargo test -p app debug_inline_values); debugHover.ts in place of the editor hover while a frame is focused in the file: the `$provideEvaluatableExpression` range or the dotted path under the mouse, `hover` evaluation or the scopes' variable, Cmd+K Cmd+I focused, Alt for the editor hover, the tree's list keys and `layoutTree` height, the glyph margin's lockout release, the caret edge nearer the mouse (cargo test -p app debug_hover; ui-pair port/fixtures/debug-node `greeting` and `numbers` hovers); disassemblyView.ts: the `disassemble` requests around the focused frame's instruction pointer, the glyph click's instruction breakpoint (`setInstructionBreakpoints`), the Breakpoints view's instruction rows, `instruction` stepping granularity while the view is active (cargo test -p app disassembly a_step_in_the_disassembly_view debug::tests::instruction_breakpoints debug::tests::remove_instruction_breakpoints); shortcuts in port/notes.md || workbench/contrib/dropOrPasteInto | workbench contribution | M13 | verified | | commands.ts `configurePreferredPasteAction`/`configurePreferredDropAction`: the widgets' menus and the Paste As pick open user settings JSON at `editor.pasteAs.preferences` or `editor.dropIntoEditor.preferences` (workbench/paste_edits.rs); the `editor.pasteAs.*` and `editor.dropIntoEditor.*` settings come from core-settings.json; ui-pair paste-menu (port/results/language-features.md) || workbench/contrib/editSessions | workbench contribution | | removed | | no sign-in/AI by decision (port/notes.md); not ported || workbench/contrib/editTelemetry | workbench contribution | | removed | | no AI or Microsoft services by decision (port/notes.md); API stays inert |diff --git a/port/notes.md b/port/notes.mdindex e337ca7ed6c..51f219a51fc 100644--- a/port/notes.md+++ b/port/notes.md@@ -937,6 +937,7 @@ Scope as in the M19 Work row of port/ledger.md.- Continuous run (`workbench/testing_continuous.rs`): the view title's dropdown of `getContinuousRunDropdown` runs plain actions upstream; the port's context menu runs commands, so each profile item is an internal `_testing.toggleContinuousRunProfile.<controller>.<profile>` command registered when the menu shows. testingExplorerView.ts re-sorts a parent when a continuous run changes, but `TreeSorter` has no continuous run criterion in 1.147.0, so the order does not change; the port draws rows from the run state each frame and needs no re-sort. The unattended restart participant `testing.continuousRun` waits on the unattended restart service (ledger row workbench/services/lifecycle).- Inline values (`workbench/debug_inline_values.rs`; debugEditorContribution.ts): `debug.inlineValues` `on` or `auto` with a provider shows the focused frame's values as `InjectionOwner::DebugInlineValue` text after the lines, `editor.inlineValuesForeground` on `editor.inlineValuesBackground`. Shortcuts: only the active editor shows them, where upstream decorates every editor on the frame's file; the scopes and variables are fetched again, not shared with the Variables view's cache; the text area width stands in for `layoutInfo.width` in the line length cut.- Debug hover (`workbench/debug_hover.rs`; debugHover.ts, debugEditorContribution.ts hover handling): while stopped, the expression at the mouse in the focused frame's file (the first `EvaluatableExpressionProvider` through `$provideEvaluatableExpression`, else `getExactExpressionStartAndEnd`) is evaluated with `context: "hover"` (or looked up in the cheap scopes without `supportsEvaluateForHovers`) after the doubled `editor.hover.delay`, the editor hover off meanwhile; Alt swaps it for the editor hover; Cmd+K Cmd+I shows it at the cursor. The focused tree takes listWidget.ts's and abstractTree.ts's keys through the `list.*` commands (Up, Down, Page Up, Page Down, Home, End, Left, Right, Space, Enter, type navigation by name), Escape clears a selection before it hides the widget; `layoutTree` sizes the tree to its rows plus 10px, at most max(266px, 55% of the editor) and the hovered line's top less 22px. The context menu and visualizers are ledger gaps of workbench/contrib/debug. The glyph margin lifts the editor hover lockout; the hovered position is the nearer edge of the character under the mouse, a tab's middle included. Lazy variables, the Alt+click recursive expand and the tree's find widget are ledger gaps of workbench/contrib/debug. ui-pair on `port/fixtures/debug-node` (Cmd+K Cmd+I on `numbers` and `greeting`) matches the reference's placement, tree indent and focus outline.+- Extension host debugging (`extensionHost` launch type; rawDebugSession.ts `launchVsCode`, localProcessExtensionHost.ts `attachSession`, debugService.ts `onAttachSession`): js-debug's `launchVSCode` opens the Extension Development Host window (or reloads the one on the same extension path) with `--debugId`, `--inspect-brk-extensions` and `--extensionEnvironment`; the host it starts has the session attach to the inspector port on a new adapter. Decision: a host with an inspector port runs on Node, since Bun has no V8 inspector; a host without one stays on Bun, and there is no 5870 default port (environmentService.ts gives one to a build from source, which would put every checkout run on Node). The window closes with its current host's exit and at the end of a 'Run Without Debugging' session; a restart reloads it. Check: `cargo test -p app workbench::host::`, ui-pair `debug/extension-host.json` with `FOLDER=port/fixtures/debug-extension` (stops at the breakpoint in `activate`).- Checks: `cargo test -p app debug` and `cargo test -p app testing::`; api-tests `MOCHA_GREP="vscode API - debug"`; `port/fixtures/debug-node` (app.js with launch.json, math.test.js) with `port/fixtures/extensions/tests-provider` through `port/tools/ui-pair`.## Milestone 11 windows: dialogs, lifecycle, hot exit, windows, title bar (in progress)