Visual Studio Code, rebuilt in Rust
Rust
feat(debug): show the focused frame's inline values after its lines
rokartur32851c292676
diff --git a/native/crates/app/src/editor/injected_text.rs b/native/crates/app/src/editor/injected_text.rsindex 9fbbda2f209..09de9b4cc5a 100644--- a/native/crates/app/src/editor/injected_text.rs+++ b/native/crates/app/src/editor/injected_text.rs@@ -18,6 +18,8 @@ pub enum InjectionOwner {DecorationContent,/// The room of the inline progress widget, which draws itself.InlineProgress,+ /// A debug inline value after its line (debugEditorContribution.ts `createInlineValueDecoration`).+ DebugInlineValue,}/// One injected text before the char at `position` (after the line's last char at its length).diff --git a/native/crates/app/src/snippets.rs b/native/crates/app/src/snippets.rsindex 3799a7e058d..7c334ef7363 100644--- a/native/crates/app/src/snippets.rs+++ b/native/crates/app/src/snippets.rs@@ -439,7 +439,7 @@ pub fn resolve_snippet_completion(snippet: &Snippet) -> Value {}/// `appendEscapedMarkdownCodeBlockFence`: a fence longer than any backtick run starting a line of `code`.-fn escaped_code_block_fence(code: &str, language: &str) -> String {+pub(crate) fn escaped_code_block_fence(code: &str, language: &str) -> String {let longest = code.split(['\n', '\r']).filter_map(|line| {diff --git a/native/crates/app/src/theme/debug_colors.rs b/native/crates/app/src/theme/debug_colors.rsindex 874b594665e..b3269417ead 100644--- a/native/crates/app/src/theme/debug_colors.rs+++ b/native/crates/app/src/theme/debug_colors.rs@@ -1,5 +1,5 @@//! Registry defaults of the debug keys: debugColors.ts, breakpointEditorContribution.ts,-//! callStackEditorContribution.ts, statusbarColorProvider.ts and testing/browser/theme.ts, as `registry_default` columns: dark, light,+//! callStackEditorContribution.ts, debugEditorContribution.ts, statusbarColorProvider.ts and testing/browser/theme.ts, as `registry_default` columns: dark, light,//! high contrast, high contrast light.use super::ColorValue::{self, *};@@ -34,6 +34,8 @@ pub(super) fn debug_default(key: &str) -> Option<[ColorValue; 4]> {"debugIcon.breakpointStackframeForeground" => [Hex("#89D185"), Hex("#89D185"), Hex("#89D185"), Hex("#89D185")],"editor.stackFrameHighlightBackground" => [Hex("#ffff0033"), Hex("#ffff6673"), Hex("#ffff0033"), Hex("#ffff6673")],"editor.focusedStackFrameHighlightBackground" => [Hex("#7abd7a4d"), Hex("#cee7ce73"), Hex("#7abd7a4d"), Hex("#cee7ce73")],+ "editor.inlineValuesForeground" => [Hex("#ffffff80"), Hex("#00000080"), Hex("#ffffff80"), Hex("#00000080")],+ "editor.inlineValuesBackground" => [Hex("#ffc80033"), Hex("#ffc80033"), Hex("#ffc80033"), Hex("#ffc80033")],"statusBar.debuggingBackground" => [Hex("#CC6633"), Hex("#CC6633"), Hex("#BA592C"), Hex("#B5200D")],"statusBar.debuggingForeground" => [Key("statusBar.foreground"), Key("statusBar.foreground"), Key("statusBar.foreground"), Hex("#FFFFFF")],"testing.iconFailed" | "testing.iconErrored" => [Key("list.errorForeground"), Key("list.errorForeground"), Key("list.errorForeground"), Key("list.errorForeground")],diff --git a/native/crates/app/src/workbench.rs b/native/crates/app/src/workbench.rsindex 706eb1fe59c..6cd7e12fc4e 100644--- a/native/crates/app/src/workbench.rs+++ b/native/crates/app/src/workbench.rs@@ -207,6 +207,7 @@ mod comments_view;mod color_picker;mod standalone_color_picker;mod inlay_hints;+mod debug_inline_values;mod rename;mod links;mod selection_ranges;@@ -407,6 +408,7 @@ pub struct Workbench {paste_edits: paste_edits::PasteEdits,code_lenses: code_lens::CodeLenses,inlay_hints: inlay_hints::InlayHints,+ debug_inline_values: debug_inline_values::DebugInlineValues,color_detector: color_detector::ColorDetector,inline_completions: inline_completions::InlineCompletions,language_detection: language_detection::LanguageDetection,@@ -782,6 +784,7 @@ impl Workbench {paste_edits: Default::default(),code_lenses: Default::default(),inlay_hints: Default::default(),+ debug_inline_values: Default::default(),color_detector: Default::default(),inline_completions: Default::default(),language_detection: Default::default(),@@ -1191,6 +1194,7 @@ impl Workbench {self.sync_comment_widgets();self.refresh_commenting_ranges(false, cx);self.inlay_hints_model_changed(cx);+ self.update_debug_inline_values(cx);self.color_detector_model_changed(cx);self.inline_completions_model_changed(cx);self.language_detection_model_changed(cx);diff --git a/native/crates/app/src/workbench/content_hover.rs b/native/crates/app/src/workbench/content_hover.rsindex 90a7579dd82..53f3ab59e6a 100644--- a/native/crates/app/src/workbench/content_hover.rs+++ b/native/crates/app/src/workbench/content_hover.rs@@ -892,6 +892,7 @@ impl Workbench {parts.extend(self.link_hover_parts(editor, anchor));parts.extend(self.definition_link_hover_parts(editor, anchor));parts.extend(self.keybinding_mark_hover_parts(editor, anchor));+ parts.extend(self.debug_inline_value_hover_parts(editor, anchor));parts}None => Vec::new(),diff --git a/native/crates/app/src/workbench/debug_commands.rs b/native/crates/app/src/workbench/debug_commands.rsindex edf9e1bda2e..7f1704e3b86 100644--- a/native/crates/app/src/workbench/debug_commands.rs+++ b/native/crates/app/src/workbench/debug_commands.rs@@ -244,6 +244,7 @@ impl Workbench {self.debug.focus.frame = None;self.debug.scopes.clear();self.debug.children.clear();+ self.update_debug_inline_values(cx);cx.notify();Outcome::Pending(reply)}diff --git a/native/crates/app/src/workbench/debug_inline_values.rs b/native/crates/app/src/workbench/debug_inline_values.rsnew file mode 100644index 00000000000..cc6bd1c6719--- /dev/null+++ b/native/crates/app/src/workbench/debug_inline_values.rs@@ -0,0 +1,479 @@+//! debugEditorContribution.ts inline values: with `debug.inlineValues` on, the focused stack frame's values after the+//! lines of its file in the active editor, from the `InlineValuesProvider`s, else from the variables of the frame's+//! most specific scopes found as words of the lines (`createInlineValueDecoration`, its hover `formatHoverContent`).+// shortcut: only the active editor shows the values, where upstream decorates every editor on the frame's file; needs the state per editor.++use std::collections::{HashMap, HashSet};+use std::time::Duration;++use gpui::{AnyElement, AsyncApp, Context, Task, WeakEntity, div, prelude::*, px};+use serde_json::{Value, json};++use super::Workbench;+use super::content_hover::{Anchor, Part, PartContent, Participant};+use crate::debug::session::{StackFrame, Variable};+use crate::editor::in_place_replace::DEFAULT_WORD_REGEXP;+use crate::editor::injected_text::{InjectedText, InjectionOwner};+use crate::editor::{OpenEditor, Position, TextDocument, char_column};+use crate::language_feature_debounce::FeatureDebounce;+use crate::language_features::Candidate;++#[cfg(test)]+mod tests;++const REGISTER: &str = "$registerInlineValuesProvider";+const MAX_NUM_INLINE_VALUES: usize = 100;+const MAX_TOKENIZATION_LINE_LEN: usize = 500;+/// `removeInlineValuesScheduler`.+const REMOVE_DELAY: Duration = Duration::from_millis(100);+const SPACER: char = '\u{a0}';++/// A 1-based (line, column) of `IRange`.+type At = (u64, u64);++#[derive(Default)]+pub(super) struct DebugInlineValues {+ /// The text of each shown value by its injection id, uncut, for its hover.+ texts: Vec<String>,+ /// `updateInlineValuesScheduler`.+ scheduled: Option<Task<()>>,+ /// The update in flight; dropping it cancels it (`displayedStore`).+ running: Option<Task<()>>,+ removing: Option<Task<()>>,+ /// `debounceInfo`: `{ min: 200 }`, so `max` is 200 ** 2.+ debounce: FeatureDebounce<200, 40000>,+}++impl Workbench {+ /// `updateInlineValuesScheduler.schedule()`: an edit, or a scroll with providers to ask about the new lines.+ pub(super) fn schedule_debug_inline_values(&mut self, cx: &mut Context<Self>) {+ let delay = match self.editors.active() {+ Some(editor) => {+ let key = self.inline_values_debounce_key(editor);+ self.debug_inline_values.debounce.get(&key)+ }+ None => Duration::from_millis(200),+ };+ self.debug_inline_values.scheduled = Some(cx.spawn(async move |workbench, cx| {+ cx.background_executor().timer(delay).await;+ let _ = workbench.update(cx, |workbench, cx| workbench.update_debug_inline_values(cx));+ }));+ }++ /// `onDidScrollChange`: only the providers' values depend on the visible lines.+ pub(super) fn debug_inline_values_scrolled(&mut self, cx: &mut Context<Self>) {+ if self.editors.active().is_some_and(|editor| !self.inline_values_handles(editor).is_empty()) {+ self.schedule_debug_inline_values(cx);+ }+ }++ /// `updateInlineValueDecorations` for the focused frame: off, or with the frame in another file, the values+ /// go 100ms later.+ pub(super) fn update_debug_inline_values(&mut self, cx: &mut Context<Self>) {+ self.debug_inline_values.scheduled = None;+ let Some((model_id, frame, handles)) = self.inline_values_target() else {+ if self.debug_inline_values.removing.is_none() {+ self.debug_inline_values.removing = Some(cx.spawn(async move |workbench, cx| {+ cx.background_executor().timer(REMOVE_DELAY).await;+ let _ = workbench.update(cx, |workbench, cx| {+ workbench.debug_inline_values.removing = None;+ workbench.debug_inline_values.running = None;+ workbench.clear_debug_inline_values();+ cx.notify();+ });+ }));+ }+ return;+ };+ self.debug_inline_values.removing = None;+ let Some(session_id) = self.debug.focus.session.clone() else { return };+ let editor = self.editors.active().expect("found by the target");+ let lines = &editor.document().lines;+ let view_ranges: Vec<(At, At)> = super::semantic_tokens::visible_ranges_plus_viewport_above_below(editor, self.editors.viewport)+ .into_iter()+ .map(|(start, end)| ((start as u64 + 1, 1), (end as u64 + 1, lines[end].encode_utf16().count() as u64 + 1)))+ .collect();+ let uri = editor.document().uri();+ let debounce_key = self.inline_values_debounce_key(editor);+ self.debug_inline_values.running = Some(cx.spawn(async move |workbench, cx| {+ let values = match handles.is_empty() {+ true => scope_values(&workbench, cx, &session_id, &frame, model_id, &view_ranges).await,+ false => {+ let started = cx.background_executor().now();+ let values = provider_values(&workbench, cx, &session_id, &frame, model_id, uri, &handles, &view_ranges).await;+ let elapsed = cx.background_executor().now() - started;+ let _ = workbench.update(cx, |workbench, _| workbench.debug_inline_values.debounce.update(&debounce_key, elapsed));+ values+ }+ };+ let _ = workbench.update(cx, |workbench, cx| workbench.show_debug_inline_values(model_id, values, cx));+ }));+ }++ /// The active editor's model, the focused frame and the editor's inline values providers when+ /// `debug.inlineValues` is `on` (or `auto` with a provider) and the frame is in the editor's file.+ fn inline_values_target(&self) -> Option<(u32, StackFrame, Vec<u64>)> {+ let editor = self.editors.active()?;+ let frame = self.debug.focused_frame()?;+ let handles = self.inline_values_handles(editor);+ let setting = self.setting("debug.inlineValues");+ let on = setting == true || setting == "on" || (setting == "auto" && !handles.is_empty());+ let document = editor.document();+ let same_file = document.scheme == "file" && frame.path() == Some(&*document.path.to_string_lossy());+ (on && same_file).then(|| (editor.model_id, frame.clone(), handles))+ }++ /// `inlineValuesProvider.ordered(model)`, best first.+ fn inline_values_handles(&self, editor: &OpenEditor) -> Vec<u64> {+ let uri = editor.document().uri();+ let language = editor.document().language_id.clone();+ let candidate = Candidate { uri: &uri, language: &language };+ self.language_features.ordered(REGISTER, &candidate).iter().map(|registration| registration.handle).collect()+ }++ fn inline_values_debounce_key(&self, editor: &OpenEditor) -> String {+ format!("{}{:?}", editor.document().uri(), self.inline_values_handles(editor))+ }++ /// `oldDecorations.set`: with word wrap the values can wrap lines, so the cursor keeps its top when visible.+ fn show_debug_inline_values(&mut self, model_id: u32, values: Vec<(usize, String)>, cx: &mut Context<Self>) {+ self.debug_inline_values.running = None;+ self.clear_debug_inline_values();+ let viewport = self.editors.viewport;+ // shortcut: the text area's width stands for `layoutInfo.width`, a left minimap's width short; needs the editor's width kept.+ let max_columns = ((self.text_area_bounds.get().size.width - 50.) / viewport.char_width).floor().max(0.) as usize;+ let Some(editor) = self.editors.editors.iter_mut().find(|editor| editor.model_id == model_id) else { return };+ let cursor_line = editor.head_view_line(0);+ let kept_top = (editor.wraps() && editor.visible_lines(viewport).contains(&cursor_line)).then(|| editor.line_top(cursor_line, viewport));+ let mut injections = Vec::new();+ let mut texts = Vec::new();+ for (line, text) in values {+ let content = inline_value_content(&text, max_columns);+ let position = Position::new(line, editor.document().lines[line].chars().count());+ injections.push(InjectedText { position, columns: content.chars().count() as f32, content, owner: InjectionOwner::DebugInlineValue, id: texts.len(), at_range_start: false });+ texts.push(text);+ }+ editor.set_injected_text(InjectionOwner::DebugInlineValue, injections);+ if let Some(top) = kept_top {+ let cursor_line = editor.head_view_line(0);+ editor.scroll.top = (editor.scroll.top - (top - editor.line_top(cursor_line, viewport))).max(0.);+ }+ self.debug_inline_values.texts = texts;+ cx.notify();+ }++ fn clear_debug_inline_values(&mut self) {+ for editor in self.editors.editors.iter_mut().chain(&mut self.editors.models) {+ if editor.injected_text.iter().any(|injection| injection.owner == InjectionOwner::DebugInlineValue) {+ editor.set_injected_text(InjectionOwner::DebugInlineValue, Vec::new());+ }+ }+ self.debug_inline_values.texts.clear();+ }++ /// `.debug-inline-value` after its no-break space spacer.+ pub(super) fn debug_inline_value_element(&self, content: &str, left: f32, line_height: f32) -> AnyElement {+ let value = content.strip_prefix(SPACER).expect("made with the spacer").to_owned();+ let value = div().bg(self.color("editor.inlineValuesBackground")).text_color(self.color("editor.inlineValuesForeground")).child(value);+ div().absolute().top_0().left(px(left)).h(px(line_height)).flex().items_center().whitespace_nowrap().child(SPACER.to_string()).child(value).into_any_element()+ }++ /// markdownHoverParticipant.ts `computeSync`: the `hoverMessage` of a value whose line end the anchor touches.+ pub(super) fn debug_inline_value_hover_parts(&self, editor: &OpenEditor, anchor: Anchor) -> Vec<Part> {+ let mut parts = Vec::new();+ for injection in editor.injected_text_on(anchor.line).iter().filter(|injection| injection.owner == InjectionOwner::DebugInlineValue) {+ let column = injection.position.column;+ if column > anchor.start + 1 || anchor.end > column + 1 {+ continue;+ }+ let content = PartContent::Markdown(vec![json!({ "value": format_hover_content(&self.debug_inline_values.texts[injection.id]) })]);+ parts.push(Part { participant: Participant::Markdown, ordinal: parts.len(), start: injection.position, end: injection.position, content, source: None });+ }+ parts+ }+}++/// The providers' values, each value's line its segments by column joined with `, `.+#[allow(clippy::too_many_arguments)]+async fn provider_values(workbench: &WeakEntity<Workbench>, cx: &mut AsyncApp, session_id: &str, frame: &StackFrame, model_id: u32, uri: Value, handles: &[u64], view_ranges: &[(At, At)]) -> Vec<(usize, String)> {+ let range = |(start, end): (At, At)| json!({ "startLineNumber": start.0, "startColumn": start.1, "endLineNumber": end.0, "endColumn": end.1 });+ let stopped = range(((frame.line as u64, frame.column as u64 + 1), (frame.end_line as u64, frame.end_column as u64 + 1)));+ let context = json!({ "frameId": frame.id, "stoppedLocation": stopped });+ let Ok(calls) = workbench.update(cx, |workbench, _| {+ let mut calls = Vec::new();+ for &handle in handles.iter().rev() {+ for &view_range in view_ranges {+ calls.push(workbench.host.call_cancellable("ExtHostLanguageFeatures", "$provideInlineValues", vec![json!(handle), uri.clone(), range(view_range), context.clone()]));+ }+ }+ calls+ }) else {+ return Vec::new();+ };+ let mut segments: Vec<(usize, Vec<(u64, String)>)> = Vec::new();+ let mut scope_variables: Option<Vec<Variable>> = None;+ for call in calls {+ let Ok(Ok(values)) = call.await else { continue };+ for value in values.as_array().into_iter().flatten() {+ let start: At = (value["range"]["startLineNumber"].as_u64().unwrap_or(1), value["range"]["startColumn"].as_u64().unwrap_or(1));+ let end_column = value["range"]["endColumn"].as_u64().unwrap_or(1);+ let source_text = |cx: &mut AsyncApp| workbench.update(cx, |workbench, _| range_text(workbench, model_id, start, end_column)).unwrap_or_default();+ let text = match value["type"].as_str() {+ Some("text") => value["text"].as_str().map(str::to_owned),+ Some("variable") => {+ let name = value["variableName"].as_str().map(str::to_owned).unwrap_or_else(|| source_text(cx));+ if scope_variables.is_none() {+ scope_variables = Some(most_specific_scope_variables(workbench, cx, session_id, frame).await.into_iter().flat_map(|(_, variables)| variables).collect());+ }+ let case_sensitive = value["caseSensitiveLookup"] == true;+ let found = scope_variables.iter().flatten().find(|variable| if case_sensitive { variable.name == name } else { variable.name.to_lowercase() == name.to_lowercase() });+ found.filter(|variable| !variable.value.is_empty()).map(|variable| format!("{name} = {}", variable.value))+ }+ Some("expression") => {+ let expression = value["expression"].as_str().map(str::to_owned).unwrap_or_else(|| source_text(cx));+ match expression.is_empty() {+ true => None,+ false => evaluate(workbench, cx, session_id, frame.id, &expression).await.map(|result| format!("{expression} = {result}")),+ }+ }+ _ => None,+ };+ let Some(text) = text.filter(|text| !text.is_empty()) else { continue };+ let line = start.0.max(1) as usize - 1;+ let index = match segments.iter().position(|(shown, _)| *shown == line) {+ Some(index) => index,+ None => {+ segments.push((line, Vec::new()));+ segments.len() - 1+ }+ };+ if !segments[index].1.iter().any(|(_, shown)| *shown == text) {+ segments[index].1.push((start.1, text));+ }+ }+ }+ let mut values = Vec::new();+ for (line, mut line_segments) in segments {+ line_segments.sort_by_key(|(column, _)| *column);+ values.push((line, line_segments.into_iter().map(|(_, text)| text).collect::<Vec<_>>().join(", ")));+ }+ values+}++/// The old "one-size-fits-all" strategy: the scopes' values on the lines that name them.+async fn scope_values(workbench: &WeakEntity<Workbench>, cx: &mut AsyncApp, session_id: &str, frame: &StackFrame, model_id: u32, view_ranges: &[(At, At)]) -> Vec<(usize, String)> {+ let scopes = most_specific_scope_variables(workbench, cx, session_id, frame).await;+ let frame_start = (frame.line as u64, frame.column as u64);+ workbench+ .update(cx, |workbench, _| {+ let Some(editor) = workbench.editors.editors.iter().find(|editor| editor.model_id == model_id) else { return Vec::new() };+ words_inline_values(&editor.document(), &scopes, frame_start, view_ranges)+ })+ .unwrap_or_default()+}++/// The (start, end) of a scope's DAP range, when it has one.+type ScopeRange = Option<(At, At)>;++/// `getMostSpecificScopes(stackFrame.range)` and each scope's `getChildren`.+// shortcut: each update asks for the scopes and variables again, where upstream's frame caches them for the Variables view too; needs a shared cache.+async fn most_specific_scope_variables(workbench: &WeakEntity<Workbench>, cx: &mut AsyncApp, session_id: &str, frame: &StackFrame) -> Vec<(ScopeRange, Vec<Variable>)> {+ let Ok(reply) = workbench.update(cx, |workbench, _| workbench.dap_request(session_id, "scopes", json!({ "frameId": frame.id }))) else { return Vec::new() };+ let Ok(Ok(body)) = reply.await else { return Vec::new() };+ let scopes = most_specific_scopes(body["scopes"].as_array().map_or(&[], Vec::as_slice), frame);+ let mut result = Vec::new();+ for (range, reference) in scopes {+ let Ok(reply) = workbench.update(cx, |workbench, _| workbench.dap_request(session_id, "variables", json!({ "variablesReference": reference }))) else { break };+ let variables = match reply.await {+ Ok(Ok(body)) => body["variables"].as_array().into_iter().flatten().map(Variable::from_dap).collect(),+ _ => Vec::new(),+ };+ result.push((range, variables));+ }+ result+}++/// debugModel.ts `getMostSpecificScopes`: the scopes that are not expensive; with ranges, those around the frame's+/// range, narrowest first, unless none is. Each with its range and `variablesReference`.+fn most_specific_scopes(scopes: &[Value], frame: &StackFrame) -> Vec<(ScopeRange, i64)> {+ let cheap: Vec<(ScopeRange, i64)> = scopes.iter().filter(|scope| scope["expensive"] != true).map(|scope| (scope_range(scope), scope["variablesReference"].as_i64().unwrap_or(0))).collect();+ if cheap.iter().all(|(range, _)| range.is_none()) {+ return cheap;+ }+ let frame_range = ((frame.line as u64, frame.column as u64), (frame.end_line as u64, frame.end_column as u64));+ let mut around: Vec<(ScopeRange, i64)> = cheap.iter().copied().filter(|(range, _)| range.is_some_and(|(start, end)| start <= frame_range.0 && frame_range.1 <= end)).collect();+ around.sort_by_key(|(range, _)| range.map(|(start, end)| end.0 - start.0));+ if around.is_empty() { cheap } else { around }+}++/// debugModel.ts `new Scope(...)`: a range only with all four of `line`, `column`, `endLine` and `endColumn`.+fn scope_range(scope: &Value) -> ScopeRange {+ let number = |key: &str| scope[key].as_u64().filter(|value| *value != 0);+ Some(((number("line")?, number("column")?), (number("endLine")?, number("endColumn")?)))+}++/// The scopes from the narrowest out: in its part of the view ranges up to the frame's position, each line that has+/// a variable's name as a word shows it, a name keeping the value of its narrowest scope (#129770, #217326).+fn words_inline_values(document: &TextDocument, scopes: &[(ScopeRange, Vec<Variable>)], frame_start: At, view_ranges: &[(At, At)]) -> Vec<(usize, String)> {+ let mut words: HashMap<String, Vec<u64>> = HashMap::new();+ let mut parsed = HashSet::new();+ let mut values_per_line: Vec<(u64, Vec<(String, String)>)> = Vec::new();+ for (range, variables) in scopes {+ let scope_start = range.map_or((0, 0), |(start, _)| start);+ let own_ranges: Vec<(At, At)> = view_ranges.iter().map(|&(start, end)| (start.max(scope_start), end.min(frame_start))).filter(|(start, end)| start <= end).collect();+ for &(start, end) in &own_ranges {+ for line in start.0..=end.0 {+ if parsed.insert(line) {+ line_words(document, line, &mut words);+ }+ }+ }+ for (line, names) in names_per_line(document, variables, &own_ranges, &words) {+ let index = match values_per_line.iter().position(|(shown, _)| *shown == line) {+ Some(index) => index,+ None => {+ values_per_line.push((line, Vec::new()));+ values_per_line.len() - 1+ }+ };+ let values = &mut values_per_line[index].1;+ for (name, value) in names {+ if !values.iter().any(|(shown, _)| *shown == name) {+ values.push((name, value));+ }+ }+ }+ }+ let joined = |values: Vec<(String, String)>| values.into_iter().map(|(name, value)| format!("{name} = {value}")).collect::<Vec<_>>().join(", ");+ values_per_line.into_iter().map(|(line, values)| (line as usize - 1, joined(values))).collect()+}++/// `createInlineValueDecorationsInsideRange`: the first 100 names' values, on each line in `ranges` that has the+/// name as a word, in the order the line has them.+fn names_per_line(document: &TextDocument, variables: &[Variable], ranges: &[(At, At)], words: &HashMap<String, Vec<u64>>) -> Vec<(u64, Vec<(String, String)>)> {+ let mut name_values: Vec<(&str, &str)> = Vec::new();+ for variable in variables {+ match name_values.iter_mut().find(|(name, _)| *name == variable.name) {+ Some(entry) => entry.1 = &variable.value,+ None => name_values.push((&variable.name, &variable.value)),+ }+ if name_values.len() >= MAX_NUM_INLINE_VALUES {+ break;+ }+ }+ let mut line_names: Vec<(u64, Vec<&str>)> = Vec::new();+ for &(name, _) in &name_values {+ for &line in words.get(name).into_iter().flatten() {+ if !ranges.iter().any(|(start, end)| line >= start.0 && line <= end.0) {+ continue;+ }+ match line_names.iter_mut().find(|(shown, _)| *shown == line) {+ Some((_, names)) if names.contains(&name) => {}+ Some((_, names)) => names.push(name),+ None => line_names.push((line, vec![name])),+ }+ }+ }+ let mut result = Vec::new();+ for (line, mut names) in line_names {+ let text = &document.lines[line as usize - 1];+ names.sort_by_key(|name| text.find(name));+ let value = |name: &str| name_values.iter().find(|(shown, _)| *shown == name).expect("named above").1.to_owned();+ result.push((line, names.into_iter().map(|name| (name.to_owned(), value(name))).collect()));+ }+ result+}++/// `getWordToLineNumbersMap`: the first word of each `Other` token of the 1-based `line`; a line over 500 chars+/// is skipped.+fn line_words(document: &TextDocument, line: u64, words: &mut HashMap<String, Vec<u64>>) {+ let index = line as usize - 1;+ let text = &document.lines[index];+ if text.encode_utf16().count() > MAX_TOKENIZATION_LINE_LEN {+ return;+ }+ let mut start = 0;+ for (end, token_type, _) in document.tokens.line_tokens(&document.lines, index) {+ let token = &text[start..end];+ if token_type == textmate::StandardTokenType::Other+ && let Some((word_start, word_end)) = DEFAULT_WORD_REGEXP.find(token)+ {+ words.entry(token[word_start..word_end].to_owned()).or_default().push(line);+ }+ start = end;+ }+}++/// The model text of a value's range on its line, by UTF-16 columns.+fn range_text(workbench: &Workbench, model_id: u32, start: At, end_column: u64) -> String {+ let Some(editor) = workbench.editors.editors.iter().find(|editor| editor.model_id == model_id) else { return String::new() };+ let document = editor.document();+ let Some(text) = document.lines.get(start.0.max(1) as usize - 1) else { return String::new() };+ let (from, to) = (char_column(text, start.1.max(1) as usize - 1), char_column(text, end_column.max(1) as usize - 1));+ text.chars().skip(from).take(to.saturating_sub(from)).collect()+}++/// `Expression.evaluate(session, frame, 'watch')`: the result when the adapter answered with a body.+async fn evaluate(workbench: &WeakEntity<Workbench>, cx: &mut AsyncApp, session_id: &str, frame_id: i64, expression: &str) -> Option<String> {+ let reply = workbench.update(cx, |workbench, _| workbench.dap_request(session_id, "evaluate", json!({ "expression": expression, "frameId": frame_id, "context": "watch" }))).ok()?;+ let body = reply.await.ok()?.ok().filter(|body| !body.is_null())?;+ Some(body["result"].as_str().unwrap_or_default().to_owned())+}++/// `createInlineValueDecoration`: the spacer, then the text cut at `max_columns` UTF-16 units with `...`, its+/// spaces, tabs and newlines as no-break spaces.+fn inline_value_content(text: &str, max_columns: usize) -> String {+ let units: Vec<u16> = text.encode_utf16().collect();+ let shown = match units.len() > max_columns {+ true => String::from_utf16_lossy(&units[..max_columns]) + "...",+ false => text.to_owned(),+ };+ format!("{SPACER}{}", shown.replace([' ', '\t', '\n'], &SPACER.to_string()))+}++/// `formatHoverContent`: a code block of the text; `name = value` pairs split at the comma before each `=` after+/// the first, one per line, a pair's later lines indented past its `=`.+pub(super) fn format_hover_content(text: &str) -> String {+ let code = match text.contains(',') && text.contains('=') {+ true => hover_pairs(text).iter().map(|pair| indent_pair(pair)).collect::<Vec<_>>().join(",\n"),+ false => text.to_owned(),+ };+ format!("\n{}\n", crate::snippets::escaped_code_block_fence(&code, ""))+}++fn hover_pairs(text: &str) -> Vec<String> {+ let mut splits = Vec::new();+ let mut equals_found = 0;+ let mut start = 0;+ for (index, c) in text.char_indices() {+ if c != '=' {+ continue;+ }+ if equals_found > 0+ && let Some(comma) = text[..=index].rfind(',').filter(|comma| *comma >= start)+ {+ splits.push(comma);+ start = comma + 1;+ }+ equals_found += 1;+ }+ let mut pairs = Vec::new();+ let mut from = 0;+ for split in splits {+ pairs.push(text[from..split].trim().to_owned());+ from = split + 1;+ }+ if from < text.len() {+ pairs.push(text[from..].trim().to_owned());+ }+ pairs+}++fn indent_pair(pair: &str) -> String {+ let Some(equals) = pair.find('=') else { return pair.to_owned() };+ let indent = " ".repeat(pair[..equals].encode_utf16().count() + 2);+ let pair = pair.replace("\r\n", "\n");+ let mut lines = pair.split('\n');+ let first = lines.next().unwrap_or_default().to_owned();+ lines.fold(first, |text, line| format!("{text}\n{indent}{line}"))+}diff --git a/native/crates/app/src/workbench/debug_inline_values/tests.rs b/native/crates/app/src/workbench/debug_inline_values/tests.rsnew file mode 100644index 00000000000..054e2bf7418--- /dev/null+++ b/native/crates/app/src/workbench/debug_inline_values/tests.rs@@ -0,0 +1,156 @@+use std::path::Path;+use std::sync::{Arc, Mutex};+use std::sync::mpsc::Receiver;++use exthost::session::ForwardedRequest;+use gpui::{TestAppContext, VisualTestContext};+use serde_json::{Value, json};++use super::*;+use crate::host_sync::{HostMessage, HostSync};+use crate::languages::Languages;+use crate::workbench::debug_service::DebugFocus;++#[test]+fn hover_content_puts_each_pair_on_its_line_indented_past_its_equals() {+ assert_eq!(format_hover_content("plain"), "\n```\nplain\n```\n");+ assert_eq!(format_hover_content("a = f(1, 2), b = 3"), "\n```\na = f(1, 2),\nb = 3\n```\n");+ assert_eq!(format_hover_content("x = {\r\n y: 1\n}, z = 2"), "\n```\nx = {\n y: 1\n },\nz = 2\n```\n");+}++#[test]+fn a_long_value_is_cut_and_its_spaces_do_not_break() {+ assert_eq!(inline_value_content("a = 1", 150), "\u{a0}a\u{a0}=\u{a0}1");+ assert_eq!(inline_value_content("abcdef", 3), "\u{a0}abc...");+}++#[test]+fn the_most_specific_scopes_are_the_cheap_ones_around_the_frame_narrowest_first() {+ let frame = StackFrame { line: 5, column: 3, end_line: 5, end_column: 3, ..Default::default() };+ let scope = |reference: i64, range: Option<(u64, u64)>, expensive: bool| {+ let mut scope = json!({ "variablesReference": reference, "expensive": expensive });+ if let Some((start, end)) = range {+ scope.as_object_mut().unwrap().extend([("line".into(), json!(start)), ("column".into(), json!(1)), ("endLine".into(), json!(end)), ("endColumn".into(), json!(1))]);+ }+ scope+ };+ let references = |scopes: &[Value]| most_specific_scopes(scopes, &frame).into_iter().map(|(_, reference)| reference).collect::<Vec<_>>();+ assert_eq!(references(&[scope(1, None, false), scope(2, None, true), scope(3, None, false)]), [1, 3]);+ assert_eq!(references(&[scope(1, Some((1, 20)), false), scope(2, Some((4, 6)), false), scope(3, Some((6, 9)), false), scope(4, None, false)]), [2, 1]);+ assert_eq!(references(&[scope(1, Some((7, 9)), false), scope(2, None, false)]), [1, 2], "no scope around the frame keeps them all");+}++fn workbench<'a>(cx: &'a mut TestAppContext, file: &Path) -> (gpui::Entity<Workbench>, Receiver<HostMessage>, &'a mut VisualTestContext) {+ let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();+ let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();+ let javascript = exthost::scan::scan_extension(&app_root.join("extensions/javascript"), true).unwrap();+ let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();+ let (sender, host) = std::sync::mpsc::channel();+ let file = file.to_path_buf();+ let user = file.parent().unwrap().join("User");+ let (workbench, cx) = cx.add_window_view(|window, cx| {+ let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[javascript]), Arc::new(Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), user, None))), HostSync::new(sender), cx);+ workbench.open_file(file.clone(), true, window, cx);+ let mut session = crate::debug::session::Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));+ session.set_threads(&[json!({ "id": 1, "name": "main" })]);+ let frame = StackFrame { id: 9, name: "f".into(), source: json!({ "path": file.to_string_lossy() }), line: 3, column: 3, end_line: 3, end_column: 3, ..Default::default() };+ session.thread_mut(1).unwrap().frames = vec![frame];+ workbench.debug.sessions.push(session);+ workbench+ });+ cx.run_until_parked();+ (workbench, host, cx)+}++/// Answers the adapter requests sent so far by their command; the rest stay unanswered.+fn respond(workbench: &gpui::Entity<Workbench>, host: &Receiver<HostMessage>, bodies: &[(&str, Value)], cx: &mut VisualTestContext) {+ let requests: Vec<Value> = host.try_iter().filter(|message| message.method == "$sendDAMessage").map(|message| message.args[1].clone()).collect();+ for request in requests {+ let Some((_, body)) = bodies.iter().find(|(command, _)| request["command"] == *command) else { continue };+ let response = json!({ "type": "response", "seq": 0, "request_seq": request["seq"], "success": true, "command": request["command"], "body": body });+ let accept = ForwardedRequest { req: 1, proxy: "MainThreadDebugService", method: "$acceptDAMessage".into(), args: vec![json!(1), response] };+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(accept, window, cx)));+ cx.run_until_parked();+ }+}++fn shown(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Vec<(usize, String)> {+ workbench.read_with(cx, |workbench, _| {+ let editor = workbench.editors.active().unwrap();+ editor.injected_text.iter().filter(|injection| injection.owner == InjectionOwner::DebugInlineValue).map(|injection| (injection.position.line, injection.content.replace('\u{a0}', " "))).collect()+ })+}++/// debugEditorContribution.ts old strategy: with `debug.inlineValues` on, each line up to the stop shows the scope's+/// variables it names, in the order it names them; a continue takes them away 100ms later.+#[gpui::test]+fn the_focused_frame_shows_its_variables_after_the_lines_naming_them(cx: &mut TestAppContext) {+ let dir = std::env::temp_dir().join(format!("vsrustium-inline-values-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let file = dir.join("a.js");+ std::fs::write(&file, "function f(a) {\n let b = a + 1;\n return b;\n}\n").unwrap();+ let (workbench, host, cx) = workbench(cx, &file);+ workbench.update(cx, |workbench, _| drop(workbench.settings.lock().unwrap().update_value("debug.inlineValues", Some(&json!("on")), config::service::Target::User, None, &[]).unwrap()));+ let focus = DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) };+ workbench.update_in(cx, |workbench, window, cx| workbench.set_debug_focus(focus, false, window, cx));+ cx.run_until_parked();+ respond(&workbench, &host, &[("scopes", json!({ "scopes": [{ "name": "Local", "variablesReference": 4, "expensive": false }] }))], cx);+ let variables = json!({ "variables": [{ "name": "a", "value": "1", "variablesReference": 0 }, { "name": "b", "value": "2", "variablesReference": 0 }] });+ respond(&workbench, &host, &[("variables", variables)], cx);+ assert_eq!(shown(&workbench, cx), [(0, " a = 1".into()), (1, " b = 2, a = 1".into()), (2, " b = 2".into())]);++ let hover = workbench.read_with(cx, |workbench, _| {+ let editor = workbench.editors.active().unwrap();+ let anchor = Anchor { model_id: editor.model_id, line: 1, start: 16, end: 16 };+ workbench.debug_inline_value_hover_parts(editor, anchor).into_iter().map(|part| part.content).collect::<Vec<_>>()+ });+ assert!(matches!(&hover[..], [PartContent::Markdown(contents)] if contents[0]["value"] == "\n```\nb = 2,\na = 1\n```\n"), "{hover:?}");++ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.debug.continue", Vec::new(), window, cx)));+ cx.run_until_parked();+ assert_eq!(shown(&workbench, cx).len(), 3, "the values stay 100ms");+ cx.executor().advance_clock(REMOVE_DELAY);+ cx.run_until_parked();+ assert!(shown(&workbench, cx).is_empty());+ std::fs::remove_dir_all(dir).unwrap();+}++/// `debug.inlineValues: auto` asks the providers only; a variable lookup takes the value from the scopes.+#[gpui::test]+fn auto_shows_the_providers_values_in_column_order(cx: &mut TestAppContext) {+ let dir = std::env::temp_dir().join(format!("vsrustium-inline-providers-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let file = dir.join("a.js");+ std::fs::write(&file, "function f(a) {\n let b = a + 1;\n return b;\n}\n").unwrap();+ let (workbench, host, cx) = workbench(cx, &file);+ let focus = DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) };+ workbench.update_in(cx, |workbench, window, cx| workbench.set_debug_focus(focus.clone(), false, window, cx));+ cx.run_until_parked();+ assert!(host.try_iter().all(|message| message.method != "$provideInlineValues"), "auto without a provider shows nothing");+ workbench.update_in(cx, |workbench, window, cx| {+ workbench.language_features.register(REGISTER, vec![json!(3), json!("*")]);+ workbench.set_debug_focus(focus, false, window, cx);+ });+ cx.run_until_parked();+ let range = |line: u64, start: u64, end: u64| json!({ "startLineNumber": line, "startColumn": start, "endLineNumber": line, "endColumn": end });+ let values = json!([+ { "type": "variable", "range": range(2, 11, 12) },+ { "type": "text", "range": range(2, 3, 4), "text": "first" },+ { "type": "variable", "range": range(2, 7, 8), "variableName": "B", "caseSensitiveLookup": false },+ { "type": "text", "range": range(2, 9, 9), "text": "first" },+ ]);+ let mut provided = 0;+ for mut message in host.try_iter().collect::<Vec<_>>() {+ if message.method == "$provideInlineValues" {+ provided += 1;+ assert_eq!(message.args[3], json!({ "frameId": 9, "stoppedLocation": range(3, 4, 4) }));+ drop(message.reply.take().unwrap().send(Ok(values.clone())));+ }+ }+ assert_eq!(provided, 1);+ cx.run_until_parked();+ respond(&workbench, &host, &[("scopes", json!({ "scopes": [{ "name": "Local", "variablesReference": 4 }] }))], cx);+ respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "a", "value": "1" }, { "name": "b", "value": "2" }] }))], cx);+ assert_eq!(shown(&workbench, cx), [(1, " first, B = 2, a = 1".into())]);+ std::fs::remove_dir_all(dir).unwrap();+}diff --git a/native/crates/app/src/workbench/debug_service.rs b/native/crates/app/src/workbench/debug_service.rsindex e9347a6a7ee..d5b2a1b7fb0 100644--- a/native/crates/app/src/workbench/debug_service.rs+++ b/native/crates/app/src/workbench/debug_service.rs@@ -856,6 +856,7 @@ impl Workbench {self.debug.scopes.clear();self.debug.children.clear();self.send_stack_frame_focus();+ self.update_debug_inline_values(cx);}cx.notify();}@@ -878,6 +879,7 @@ impl Workbench {self.reveal_stack_frame(&frame, window, cx);}self.toggle_exception_widget(cx);+ self.update_debug_inline_values(cx);self.refresh_focus(window, cx);}@@ -1177,6 +1179,7 @@ impl Workbench {let dto = self.debug.focused_session().map(|session| self.debug.session_dto(session));self.host.send("ExtHostDebugService", "$acceptDebugSessionActiveChanged", vec![dto.unwrap_or(Value::Null)]);self.send_stack_frame_focus();+ self.update_debug_inline_values(cx);// repl.ts `onDidFocusSession(undefined)` keeps the console's session in the tree.self.debug_console.selected_session = if self.debug.focus.session.is_some() { None } else { shown_repl };}diff --git a/native/crates/app/src/workbench/editor_view.rs b/native/crates/app/src/workbench/editor_view.rsindex 830a2db2799..cef0366ec5c 100644--- a/native/crates/app/src/workbench/editor_view.rs+++ b/native/crates/app/src/workbench/editor_view.rs@@ -1504,6 +1504,7 @@ impl Workbench {self.minimap_scrolled(cx);self.code_lens_scrolled(cx);self.inlay_hints_scrolled(cx);+ self.debug_inline_values_scrolled(cx);cx.notify();}diff --git a/native/crates/app/src/workbench/editor_view/injected_text_view.rs b/native/crates/app/src/workbench/editor_view/injected_text_view.rsindex eaff5313f12..3da25137a01 100644--- a/native/crates/app/src/workbench/editor_view/injected_text_view.rs+++ b/native/crates/app/src/workbench/editor_view/injected_text_view.rs@@ -65,6 +65,7 @@ impl Workbench {InjectionOwner::GhostText => self.ghost_text_element(injection.id, left, metrics.line_height),InjectionOwner::DecorationContent => self.decoration_content_element(editor, injection.id, left, metrics.line_height),InjectionOwner::InlineProgress => None,+ InjectionOwner::DebugInlineValue => Some(self.debug_inline_value_element(&injection.content, left, metrics.line_height)),};elements.extend(element);}diff --git a/native/crates/app/src/workbench/text_input.rs b/native/crates/app/src/workbench/text_input.rsindex a6b84a04f58..f818cecdd00 100644--- a/native/crates/app/src/workbench/text_input.rs+++ b/native/crates/app/src/workbench/text_input.rs@@ -69,6 +69,7 @@ impl Workbench {drop(document);self.search_model_changed(&scheme, &path);self.language_detection_content_changed(&scheme, &path, cx);+ self.schedule_debug_inline_values(cx);if change.is_some() {self.cell_status_bar_content_changed(&scheme, &path, cx);}diff --git a/port/ledger.md b/port/ledger.mdindex a1b8ab12451..882d76db5d0 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 | ported | [3 M] comment_thread_widget.rs:5, :29, comments_view.rs:4, comment_navigation.rs:3: several forms; body line height; thread menus, filter highlights and history, a markdown preview's image shows its alt text, not "Image: {alt}"; focus and whole-line ranges | 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, the filter box with Show Resolved/Unresolved and Sort By, Collapse/Expand All, row selection and keys; hideIfEmpty), 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, 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) 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 | ported | [3 M] custom_editors.rs:637: a custom text editor's resource in two groups shares one 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 L] Disassembly view: not ported <br> [3 L] extensionHost launch type: not ported <br> [3 L] debug hover, inline values: debugHover.ts (`$provideEvaluatableExpression`, evaluate on hover) and the `debug.inlineValues` decorations (`$provideInlineValues`) | 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); shortcuts in port/notes.md |+| workbench/contrib/debug | workbench contribution | M16 | ported | [3 L] Disassembly view: not ported <br> [3 L] extensionHost launch type: not ported <br> [3 L] debug hover: debugHover.ts (`$provideEvaluatableExpression`, evaluate on hover) | 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); 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 7c2d54c9e74..65b9eecdf50 100644--- a/port/notes.md+++ b/port/notes.md@@ -933,6 +933,7 @@ Scope as in the M19 Work row of port/ledger.md.- js-debug: `ms-vscode.js-debug` 1.140.1, `js-debug-companion` 1.1.3 and `vscode-js-profile-table` 1.0.11 (product.json `builtInExtensions`) are MIT and on Open VSX at those versions. Decision: ship them as upstream's dev build does, from `.build/builtInExtensions`, which `port/tools/fetch-builtin-extensions` fills from Open VSX; `exthost::scan::scan_dev_system_extensions` adds them to the built-ins. No marketplace or Microsoft service is contacted.- Testing (`testing.rs`, `workbench/testing_service.rs`, `testing_view.rs`): MainThreadTesting with the test collection diffs, run profiles, live results (`$runControllerTests`, `$startedExtensionTestRun`, `$applyTestRunUpdates`, `$publishTestResults`), the Testing view (shows once a controller registers), run glyphs in the editor gutter and the Test Results editor. VSBuffer arguments of forwarded requests now reach the workbench as byte arrays (`exthost::session::arg_value`).- 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.- 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)