Skip to content

Visual Studio Code, rebuilt in Rust

Rust
24.5 KB
Raw Blame
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};

use config::registry::Registry;
use config::service::Settings;
use exthost::scan::scan_extension;
use gpui::{TestAppContext, VisualTestContext};

use super::*;
use crate::host_sync::{HostMessage, HostSync};
use crate::languages::Languages;
use crate::theme::load_theme;

fn item(action: Value) -> CodeActionItem {
    CodeActionItem { action, handle: 1 }
}

#[test]
fn kinds_contain_their_children_and_the_empty_kind_contains_all() {
    assert!(contains("refactor", "refactor.extract"));
    assert!(contains("refactor", "refactor"));
    assert!(!contains("refactor", "refactorx"));
    assert!(contains("", "quickfix"));
    assert!(!contains(NONE_KIND, "quickfix"));
}

#[test]
fn filters_drop_source_actions_unless_asked_and_keep_preferred_only_when_asked() {
    let fix = json!({ "title": "a", "kind": "quickfix" });
    let organize = json!({ "title": "b", "kind": "source.organizeImports" });
    let plain = json!({ "title": "c" });
    assert!(filters_action(&Filter::default(), &fix));
    assert!(!filters_action(&Filter::default(), &organize));
    assert!(filters_action(&Filter { include_source_actions: true, ..Default::default() }, &organize));
    // An include drops actions without a kind, even the empty kind of `editor.action.codeAction`.
    assert!(!filters_action(&Filter { include: Some(String::new()), ..Default::default() }, &plain));
    assert!(!filters_action(&Filter { only_preferred: true, ..Default::default() }, &fix));
    assert!(!may_include_kind(&Filter { include: Some("refactor".into()), ..Default::default() }, "quickfix"));
    assert!(may_include_kind(&Filter { include: Some("refactor.extract".into()), ..Default::default() }, "refactor"));
    assert!(!may_include_kind(&Filter { excludes: vec!["notebook".into()], ..Default::default() }, "notebook.format"));
}

#[test]
fn sets_put_diagnostic_fixes_first_then_preferred_and_ai_last() {
    let set = CodeActionSet::new(
        vec![
            item(json!({ "title": "ai", "isAI": true, "diagnostics": [{}] })),
            item(json!({ "title": "plain" })),
            item(json!({ "title": "preferred", "isPreferred": true })),
            item(json!({ "title": "fix", "kind": "quickfix", "diagnostics": [{}] })),
            item(json!({ "title": "off", "disabled": "no" })),
        ],
        Vec::new(),
        Vec::new(),
    );
    let titles: Vec<&str> = set.all.iter().map(|item| item.action["title"].as_str().unwrap()).collect();
    assert_eq!(titles, ["fix", "preferred", "plain", "off", "ai"]);
    assert_eq!(set.valid.len(), 4);
    assert!(!set.has_auto_fix);
    assert!(set.has_ai_fix);
    assert!(!set.all_ai_fixes);
}

#[test]
fn command_args_read_kind_apply_and_preferred() {
    let (kind, apply, preferred) = command_args(Some(&json!({ "kind": "refactor.extract", "apply": "First", "preferred": true })), "", AutoApply::IfSingle);
    assert_eq!(kind, "refactor.extract");
    assert!(apply == AutoApply::First);
    assert!(preferred);
    assert_eq!(none_message(Some(&json!({ "kind": "refactor.extract" })), false, "refactorings"), "No refactorings for 'refactor.extract' available");
    assert_eq!(none_message(None, true, "code actions"), "No preferred code actions available");
}

#[test]
fn indent_levels_and_keybindings_of_kinds() {
    assert_eq!(compute_indent_level("\t  x", 4), 6);
    assert_eq!(compute_indent_level("   ", 4), -1);
    let bindings = vec![("source".to_owned(), false, "A".to_owned()), ("source.organizeImports".to_owned(), false, "B".to_owned())];
    assert_eq!(keybinding_for_action(&bindings, &json!({ "kind": "source.organizeImports" })).as_deref(), Some("B"));
    assert_eq!(keybinding_for_action(&bindings, &json!({ "kind": "source.fixAll" })).as_deref(), Some("A"));
    assert_eq!(keybinding_for_action(&bindings, &json!({ "kind": "quickfix" })), None);
}

/// The test's own folder: tests run in parallel threads named after them, and share no files.
fn test_dir() -> PathBuf {
    let test = std::thread::current().name().unwrap_or("main").replace("::", "-");
    std::env::temp_dir().join(format!("code-gpui-code-actions-{}-{test}", std::process::id()))
}

/// A folder with `a.ts` holding `text`, open with the cursor at its start, with one code action provider.
fn open<'a>(text: &str, cx: &'a mut TestAppContext) -> (gpui::Entity<Workbench>, &'a mut VisualTestContext, Receiver<HostMessage>) {
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let themes = scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
    let theme = load_theme(&[themes], "Dark Modern").unwrap();
    let dir = test_dir();
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("a.ts"), text).unwrap();
    let workspace = config::workspace::Workspace::folder(dir.clone());
    let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("User"), Some(workspace.clone()))));
    let (sender, receiver) = std::sync::mpsc::channel();
    let (workbench, cx) = cx.add_window_view(|window, cx| {
        let mut workbench = Workbench::new(theme, app_root.clone(), Some(workspace), Languages::new(&[]), settings, HostSync::new(sender), cx);
        workbench.watch_editor_focus(window, cx);
        workbench.language_features.register(REGISTER, vec![json!(7), json!("*"), json!({}), json!("test"), json!("test.ext"), json!(false)]);
        workbench.open_file(dir.join("a.ts"), true, window, cx);
        window.focus(&workbench.editor_focus, cx);
        workbench
    });
    cx.run_until_parked();
    (workbench, cx, receiver)
}

/// Answers the code action requests sent since the last answer; returns their contexts.
fn answer(receiver: &Receiver<HostMessage>, actions: Value, cx: &mut VisualTestContext) -> Vec<Value> {
    let mut contexts = Vec::new();
    for message in receiver.try_iter().filter(|message| message.method == "$provideCodeActions") {
        contexts.push(message.args[3].clone());
        let _ = message.reply.expect("a call").send(Ok(json!({ "cacheId": contexts.len(), "actions": actions })));
    }
    cx.run_until_parked();
    contexts
}

fn edit_action(title: &str, text: &str) -> Value {
    let path = test_dir().join("a.ts");
    let resource = json!({ "scheme": "file", "path": path.to_string_lossy() });
    json!({ "title": title, "kind": "quickfix", "edit": { "edits": [{ "resource": resource, "textEdit": { "range": { "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 1 }, "text": text } }] } })
}

#[gpui::test]
fn an_automatic_request_shows_the_light_bulb_and_cmd_period_applies_from_the_menu(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open("let x\n", cx);
    let contexts = answer(&receiver, json!([edit_action("Add a", "a"), edit_action("Add b", "b")]), cx);
    assert_eq!(contexts, [json!({ "only": null, "trigger": AUTO })]);
    workbench.read_with(cx, |workbench, _| {
        let lightbulb = workbench.code_actions.lightbulb.as_ref().expect("two actions show the light bulb");
        // `let x` has no indentation to hold it, the empty line below does.
        assert_eq!((lightbulb.line, lightbulb.column), (1, Some(0)));
    });
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.quickFix", vec![], window, cx));
    cx.run_until_parked();
    let contexts = answer(&receiver, json!([edit_action("Add a", "a"), edit_action("Add b", "b")]), cx);
    assert_eq!(contexts, [json!({ "only": null, "trigger": INVOKE })]);
    workbench.update_in(cx, |workbench, window, cx| {
        assert!(workbench.action_widget_visible());
        assert_eq!(workbench.action_widget_labels(), ["Quick Fix", "Add a", "Add b"]);
        _ = workbench.execute_command("selectNextCodeAction", vec![], window, cx);
        _ = workbench.execute_command("acceptSelectedCodeAction", vec![], window, cx);
    });
    cx.run_until_parked();
    workbench.read_with(cx, |workbench, _| {
        assert!(!workbench.action_widget_visible());
        assert_eq!(workbench.editors.active().unwrap().document().lines[0], "blet x");
    });
    let released: Vec<Value> = receiver.try_iter().filter(|message| message.method == "$releaseCodeActions").map(|message| message.args[1].clone()).collect();
    assert!(released.contains(&json!(1)), "the replaced automatic list is released: {released:?}");
}

/// lightBulbWidget.ts `update`: line 1 without room puts the light bulb in the glyph margin, unless another glyph
/// (`hasDecoration`) is there; then it sits inline at the line's start.
#[gpui::test]
fn a_glyph_on_line_1_keeps_the_light_bulb_inline(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open("let x\nlet y", cx);
    workbench.update(cx, |workbench, _| {
        let uri = workbench.editors.active().unwrap().document().uri();
        workbench.debug.model.add_breakpoints(&uri, vec![crate::debug::BreakpointData::at(1)]);
    });
    answer(&receiver, json!([edit_action("Add a", "a")]), cx);
    workbench.read_with(cx, |workbench, _| {
        let lightbulb = workbench.code_actions.lightbulb.as_ref().expect("an action shows the light bulb");
        assert_eq!((lightbulb.line, lightbulb.column), (0, Some(0)));
    });
}

/// actionWidget.ts: the list takes the focus, so typed keys navigate it (listWidget.ts `TypeNavigationController`)
/// rather than edit the text, and the widget hides when the focus leaves it.
#[gpui::test]
fn the_action_widget_takes_the_keys_and_hides_on_blur(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open("let x\n", cx);
    cx.update(|window, _| window.activate_window());
    answer(&receiver, json!([]), cx);
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), app_root.join("keybindings-unused.json"));
        _ = workbench.execute_command("editor.action.quickFix", vec![], window, cx);
    });
    cx.run_until_parked();
    answer(&receiver, json!([edit_action("Add a", "a"), edit_action("Remove b", "b")]), cx);
    assert!(workbench.read_with(cx, |workbench, _| workbench.scrollable_drawn("action-widget-list")), "action-widget-list sits in a ScrollableElement");
    cx.simulate_keystrokes("r");
    workbench.update_in(cx, |workbench, window, _| {
        assert!(workbench.action_widget_visible());
        assert_eq!(workbench.action_widget_focused_action().map(|action| action["title"].clone()), Some(json!("Remove b")));
        assert_eq!(workbench.editors.active().unwrap().document().lines[0], "let x", "the key does not reach the text");
        let context = workbench.key_context(window);
        assert_eq!((&context["editorFocus"], &context["editorTextFocus"]), (&json!(true), &json!(false)));
    });
    cx.simulate_keystrokes("escape");
    workbench.update_in(cx, |workbench, window, cx| {
        assert!(!workbench.action_widget_visible());
        assert!(workbench.editor_focus.is_focused(window), "escape gives the focus back to the editor");
        _ = workbench.execute_command("editor.action.quickFix", vec![], window, cx);
    });
    cx.run_until_parked();
    answer(&receiver, json!([edit_action("Add a", "a"), edit_action("Remove b", "b")]), cx);
    workbench.update_in(cx, |workbench, window, cx| {
        assert!(workbench.action_widget_visible());
        window.focus(&workbench.explorer.focus.clone(), cx);
    });
    cx.run_until_parked();
    workbench.read_with(cx, |workbench, _| assert!(!workbench.action_widget_visible(), "the widget hides on blur"));
}

#[gpui::test]
fn preview_selected_code_action_waits_in_the_refactor_preview(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open("let x\n", cx);
    answer(&receiver, json!([]), cx);
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.quickFix", vec![], window, cx));
    cx.run_until_parked();
    answer(&receiver, json!([edit_action("Add a", "a"), edit_action("Add b", "b")]), cx);
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("previewSelectedCodeAction", vec![], window, cx));
    cx.run_until_parked();
    let first_line = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().document().lines[0].clone());
    assert_eq!(first_line(cx), "let x", "the edit waits in the preview");
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("refactorPreview.apply", vec![], window, cx));
    cx.run_until_parked();
    assert_eq!(first_line(cx), "alet x");
}

#[gpui::test]
fn a_code_action_applies_its_file_edits(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open("let x\n", cx);
    answer(&receiver, json!([]), cx);
    let created = test_dir().join("created.ts");
    let _ = std::fs::remove_file(&created);
    let mut action = edit_action("Add a and create a file", "a");
    action["edit"]["edits"].as_array_mut().unwrap().push(json!({ "newResource": { "scheme": "file", "path": created.to_string_lossy() } }));
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.quickFix", vec![], window, cx));
    cx.run_until_parked();
    answer(&receiver, json!([action, edit_action("Add b", "b")]), cx);
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("acceptSelectedCodeAction", vec![], window, cx));
    cx.run_until_parked();
    for message in receiver.try_iter() {
        if let Some(work) = message.files {
            work.run(&mut files::disk::Disk);
        }
    }
    cx.run_until_parked();
    assert!(created.exists(), "the file edit applies with the text edit");
    workbench.read_with(cx, |workbench, _| assert_eq!(workbench.editors.active().unwrap().document().lines[0], "alet x"));
}

#[gpui::test]
fn the_marker_hover_asks_for_the_markers_quick_fixes(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open("let x\n", cx);
    answer(&receiver, json!([]), cx);
    let path = test_dir().join("a.ts");
    let uri = json!({ "scheme": "file", "path": path.to_string_lossy() });
    let marker = json!({ "severity": 8, "message": "bad", "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 4 });
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.change_many_markers("test", &json!([[uri, [marker]]]), cx);
        _ = workbench.execute_command("editor.action.showHover", vec![], window, cx);
    });
    cx.run_until_parked();
    let contexts = answer(&receiver, json!([edit_action("Fix", "f")]), cx);
    assert!(contexts.contains(&json!({ "only": "quickfix", "trigger": INVOKE })), "{contexts:?}");
    workbench.update_in(cx, |workbench, _, cx| {
        let marker = workbench.code_actions.marker_fixes.marker.clone().expect("the hover shows the marker");
        assert!(matches!(workbench.marker_quick_fix_status(&marker), QuickFixStatus::QuickFix));
        workbench.show_marker_quick_fixes(cx);
        assert_eq!(workbench.action_widget_labels(), ["Quick Fix", "Fix"]);
    });
}

/// markersTreeViewer.ts `getModel(waitForModel)`: a Problems row of a file without a model gets its fixes once the
/// file opens.
#[gpui::test]
fn a_problems_marker_gets_its_quick_fixes_once_its_file_opens(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open("let x\n", cx);
    answer(&receiver, json!([]), cx);
    let path = test_dir().join("b.ts");
    std::fs::write(&path, "let y\n").unwrap();
    let uri = json!({ "scheme": "file", "path": path.to_string_lossy() });
    let marker = json!({ "severity": 8, "message": "bad", "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 4 });
    let marker = workbench.update_in(cx, |workbench, _, cx| {
        workbench.change_many_markers("test", &json!([[uri, [marker]]]), cx);
        let marker = workbench.diagnostics.service.read(crate::markers::ReadOptions::default()).into_iter().find(|marker| marker.resource.ends_with("b.ts")).unwrap();
        workbench.problems_marker_hovered(&marker, cx);
        marker
    });
    cx.executor().advance_clock(std::time::Duration::from_millis(300));
    cx.run_until_parked();
    assert!(answer(&receiver, json!([]), cx).is_empty(), "no model, no request");
    workbench.update_in(cx, |workbench, window, cx| workbench.open_file(path.clone(), true, window, cx));
    cx.run_until_parked();
    let contexts = answer(&receiver, json!([edit_action("Fix", "f")]), cx);
    assert!(contexts.contains(&json!({ "only": "quickfix", "trigger": INVOKE })), "{contexts:?}");
    workbench.read_with(cx, |workbench, _| assert_eq!(workbench.problems_quick_fix_icon(&marker), Some("lightbulb")));
}

/// markersTreeViewer.ts `MarkerViewModel`: each marker keeps the fixes it got, asked once, until its resource's markers
/// change.
#[gpui::test]
fn each_problems_marker_keeps_its_quick_fixes(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open("let x = y\n", cx);
    answer(&receiver, json!([]), cx);
    let path = test_dir().join("a.ts");
    let uri = json!({ "scheme": "file", "path": path.to_string_lossy() });
    let first = json!({ "severity": 8, "message": "bad x", "startLineNumber": 1, "startColumn": 5, "endLineNumber": 1, "endColumn": 6 });
    let second = json!({ "severity": 8, "message": "bad y", "startLineNumber": 1, "startColumn": 9, "endLineNumber": 1, "endColumn": 10 });
    let markers = workbench.update_in(cx, |workbench, _, cx| {
        workbench.change_many_markers("test", &json!([[uri, [first, second]]]), cx);
        workbench.diagnostics.service.read(crate::markers::ReadOptions::default())
    });
    let (first, second) = (markers[0].clone(), markers[1].clone());
    for marker in [&first, &second] {
        workbench.update_in(cx, |workbench, _, cx| workbench.problems_marker_hovered(marker, cx));
        cx.executor().advance_clock(std::time::Duration::from_millis(300));
        cx.run_until_parked();
        answer(&receiver, json!([edit_action("Fix", "f")]), cx);
    }
    workbench.read_with(cx, |workbench, _| {
        assert_eq!(workbench.problems_quick_fix_icon(&first), Some("lightbulb"), "the first marker keeps its fixes");
        assert_eq!(workbench.problems_quick_fix_icon(&second), Some("lightbulb"));
    });
    workbench.update_in(cx, |workbench, _, cx| workbench.problems_marker_hovered(&first, cx));
    cx.executor().advance_clock(std::time::Duration::from_millis(300));
    cx.run_until_parked();
    assert!(answer(&receiver, json!([]), cx).is_empty(), "asked once");
    workbench.update_in(cx, |workbench, _, cx| workbench.change_many_markers("test", &json!([[uri, [json!({ "severity": 8, "message": "bad x", "startLineNumber": 1, "startColumn": 5, "endLineNumber": 1, "endColumn": 6 })]]]), cx));
    workbench.read_with(cx, |workbench, _| assert_eq!(workbench.problems_quick_fix_icon(&first), None, "a changed resource's markers are new ones"));
}

/// markersTreeViewer.ts `MarkerViewModel` asks `modelService.getModel(resource)`, whichever group shows it: a Problems
/// row of a file open only in another group gets its fixes at once.
#[gpui::test]
fn a_problems_marker_of_a_file_in_another_group_gets_its_quick_fixes(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open("let x = y\n", cx);
    answer(&receiver, json!([]), cx);
    crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);
    answer(&receiver, json!([]), cx);
    let uri = json!({ "scheme": "file", "path": test_dir().join("a.ts").to_string_lossy() });
    let marker = json!({ "severity": 8, "message": "bad x", "startLineNumber": 1, "startColumn": 5, "endLineNumber": 1, "endColumn": 6 });
    let marker = workbench.update_in(cx, |workbench, _, cx| {
        workbench.change_many_markers("test", &json!([[uri, [marker]]]), cx);
        let marker = workbench.diagnostics.service.read(crate::markers::ReadOptions::default()).remove(0);
        workbench.problems_marker_hovered(&marker, cx);
        marker
    });
    cx.executor().advance_clock(std::time::Duration::from_millis(300));
    cx.run_until_parked();
    answer(&receiver, json!([edit_action("Fix", "f")]), cx);
    workbench.read_with(cx, |workbench, _| assert_eq!(workbench.problems_quick_fix_icon(&marker), Some("lightbulb")));
}

#[gpui::test]
fn a_kind_command_applies_a_single_action_and_reports_none(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open("let x\n", cx);
    answer(&receiver, json!([]), cx);
    let organize = json!({ "kind": "source.organizeImports" });
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.codeAction", vec![organize], window, cx));
    cx.run_until_parked();
    let contexts = answer(&receiver, json!([{ "title": "Organize", "kind": "source.organizeImports", "edit": edit_action("", "o")["edit"] }]), cx);
    assert_eq!(contexts, [json!({ "only": "source.organizeImports", "trigger": INVOKE })]);
    workbench.read_with(cx, |workbench, _| {
        assert!(!workbench.action_widget_visible());
        assert_eq!(workbench.editors.active().unwrap().document().lines[0], "olet x");
    });
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("editor.action.fixAll", vec![], window, cx));
    cx.run_until_parked();
    answer(&receiver, json!([]), cx);
    workbench.read_with(cx, |workbench, _| assert!(workbench.editor_message_visible()));
}

/// saveParticipants.ts `CodeActionOnSaveParticipant`: an explicit save asks for the setting's kinds over the whole
/// file and writes the text the actions left.
#[gpui::test]
fn an_explicit_save_applies_the_code_actions_on_save(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open("let x\n", cx);
    workbench.update(cx, |workbench, _| {
        let value = json!({ "source.organizeImports": "explicit" });
        workbench.settings.lock().unwrap().update_value("editor.codeActionsOnSave", Some(&value), config::service::Target::User, None, &[]).unwrap();
    });
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("type", vec![json!({ "text": "y" })], window, cx));
    cx.run_until_parked();
    answer(&receiver, json!([]), cx);
    workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("workbench.action.files.save", vec![], window, cx));
    cx.run_until_parked();
    let mut action = edit_action("Organize Imports", "import a;");
    action["kind"] = json!("source.organizeImports");
    let contexts = answer(&receiver, json!([action]), cx);
    assert_eq!(contexts, [json!({ "only": "source.organizeImports", "trigger": AUTO })]);
    workbench.read_with(cx, |workbench, _| {
        let editor = workbench.editors.active().unwrap();
        assert_eq!((editor.document().lines[0].as_str(), editor.is_dirty()), ("import a;ylet x", false));
    });
}

/// saveParticipants.ts `triggerCodeActionsCommand`: a window focus change runs the `always` source kinds once
/// `editor.codeActions.triggerOnFocusChange` is on and `files.autoSave` is `afterDelay`.
#[gpui::test]
fn a_window_focus_change_runs_the_always_code_actions_on_save(cx: &mut TestAppContext) {
    let (workbench, cx, receiver) = open("let x\n", cx);
    answer(&receiver, json!([]), cx);
    let set = |workbench: &mut Workbench, key: &str, value: Value| {
        workbench.settings.lock().unwrap().update_value(key, Some(&value), config::service::Target::User, None, &[]).unwrap();
    };
    workbench.update(cx, |workbench, _| {
        set(workbench, "editor.codeActionsOnSave", json!({ "source.organizeImports": "always", "source.fixAll": "explicit", "quickfix": "always" }));
        set(workbench, "files.autoSave", json!("afterDelay"));
    });
    cx.deactivate_window();
    cx.run_until_parked();
    assert!(answer(&receiver, json!([]), cx).is_empty(), "off without editor.codeActions.triggerOnFocusChange");
    workbench.update(cx, |workbench, _| set(workbench, "editor.codeActions.triggerOnFocusChange", json!(true)));
    cx.update(|window, _| window.activate_window());
    cx.run_until_parked();
    let mut action = edit_action("Organize Imports", "import a;");
    action["kind"] = json!("source.organizeImports");
    let contexts = answer(&receiver, json!([action]), cx);
    assert_eq!(contexts, [json!({ "only": "source.organizeImports", "trigger": AUTO })]);
    workbench.read_with(cx, |workbench, _| assert_eq!(workbench.editors.active().unwrap().document().lines[0], "import a;let x"));
    let other = test_dir().join("b.ts");
    std::fs::write(&other, "").unwrap();
    workbench.update_in(cx, |workbench, window, cx| workbench.open_file(other, true, window, cx));
    cx.run_until_parked();
    let contexts = answer(&receiver, json!([]), cx);
    assert!(contexts.contains(&json!({ "only": "source.organizeImports", "trigger": AUTO })), "an active editor change runs them too: {contexts:?}");
}