Visual Studio Code, rebuilt in Rust
Rust
feat(lifecycle): port the terminal, testing, webview and notebook unattended restart participants
rokartur905789b48da4
diff --git a/native/crates/app/src/terminal.rs b/native/crates/app/src/terminal.rsindex 1341bad87b9..b00a4eb84ac 100644--- a/native/crates/app/src/terminal.rs+++ b/native/crates/app/src/terminal.rs@@ -547,6 +547,10 @@ impl TerminalInstance {changed}+ pub fn has_child_processes(&self) -> bool {+ self.pty.as_ref().is_some_and(Pty::has_child_processes)+ }+pub fn exited(&mut self, code: Option<i32>) {self.exit_code = Some(code);self.pty = None;diff --git a/native/crates/app/src/terminal/pty.rs b/native/crates/app/src/terminal/pty.rsindex 49a7cd701dc..e56e25997c1 100644--- a/native/crates/app/src/terminal/pty.rs+++ b/native/crates/app/src/terminal/pty.rs@@ -90,6 +90,13 @@ impl Pty {unsafe { libc::kill(self.pid, signal) };}+ /// childProcessMonitor.ts `hasChildProcesses`, as a process group other than the shell's in the foreground.+ /// shortcut: a background job (`cmd &`) does not count, upgrade to a child process walk when that matters.+ pub fn has_child_processes(&self) -> bool {+ let group = unsafe { libc::tcgetpgrp(self.master.as_raw_fd()) };+ group > 0 && group != self.pid+ }+/// node-pty `process` (pty.cc `pty_getproc` on Linux): the first argument of the foreground process group leader.#[cfg(target_os = "linux")]pub fn foreground_process(&self) -> Option<String> {diff --git a/native/crates/app/src/workbench/terminal_editor.rs b/native/crates/app/src/workbench/terminal_editor.rsindex d81e2387c46..97c5784c52b 100644--- a/native/crates/app/src/workbench/terminal_editor.rs+++ b/native/crates/app/src/workbench/terminal_editor.rs@@ -232,7 +232,7 @@ impl Workbench {/// terminalProcessManager.ts `shouldPersist`: a shell under `enablePersistentSessions`, not a task's or an/// extension's pty.- fn terminal_persists(&self, instance: &TerminalInstance) -> bool {+ pub(super) fn terminal_persists(&self, instance: &TerminalInstance) -> bool {self.setting("terminal.integrated.enablePersistentSessions") != false && !instance.launch.extension_pty && !instance.launch.is_feature_terminal}diff --git a/native/crates/app/src/workbench/unattended_restart.rs b/native/crates/app/src/workbench/unattended_restart.rsindex 23a1e59f5ef..7117905d76e 100644--- a/native/crates/app/src/workbench/unattended_restart.rs+++ b/native/crates/app/src/workbench/unattended_restart.rs@@ -7,6 +7,8 @@ use std::collections::{BTreeMap, BTreeSet};use std::time::Duration;use super::Workbench;+use crate::terminal::TerminalInstance;+use crate::terminal::prompt_input::PromptInputState;/// A participant's answer: the blocker id and, for the log only, what exactly blocks.type Blocker = (&'static str, Option<String>);@@ -34,6 +36,11 @@ impl Workbench {(!self.tasks.active.is_empty()).then_some(("tasks.running", None)),self.working_copy_restart_blocker().map(|id| (id, None)),(!self.wait_files.is_empty()).then_some(("cli.waitingForEditorClose", None)),+ self.terminal_restart_blocker().map(|id| (id, None)),+ self.testing.is_running().then_some(("testing.runInProgress", None)),+ self.testing.is_continuous().then_some(("testing.continuousRun", None)),+ self.webview_panels.panels.iter().any(|panel| panel.retain_context_when_hidden).then_some(("webview.retainedContext", None)),+ self.notebook_kernel_selected().then_some(("notebook.kernelSelected", None)),];let readiness = readiness(blockers.into_iter().flatten());if let Some(message) = changed_log(&mut self.unattended_restart_logged, &readiness) {@@ -77,6 +84,58 @@ impl Workbench {}}+/// terminalUnattendedRestart.ts `INTERACTIVE_SHELLS`, of the shell types the port detects.+const INTERACTIVE_SHELLS: [&str; 8] = ["bash", "csh", "fish", "ksh", "sh", "zsh", "nu", "pwsh"];++impl Workbench {+ /// notebookUnattendedRestart.ts `hasSelectedKernel`.+ fn notebook_kernel_selected(&self) -> bool {+ let notebooks = &self.host.notebooks;+ notebooks.models.iter().any(|model| notebooks.kernels.matching(&model.view_type, &model.uri_string()).1.is_some())+ }++ /// terminalUnattendedRestart.ts `TerminalUnattendedRestartParticipant._check`.+ fn terminal_restart_blocker(&self) -> Option<&'static str> {+ let view = &self.terminal_view;+ if view.instances.is_empty() {+ return None;+ }+ if let Some(blocker) = view.instances.iter().find_map(terminal_instance_blocker) {+ return Some(blocker);+ }+ let foreground = !view.editor_instances.is_empty() || view.groups.iter().any(|group| !group.instances.is_empty());+ if self.setting("terminal.integrated.confirmOnExit") == "always" && foreground {+ return Some("terminal.confirmOnExit");+ }+ let not_restorable = self.setting("terminal.integrated.persistentSessionReviveProcess") == "never" || !view.instances.iter().all(|instance| self.terminal_persists(instance));+ not_restorable.then_some("terminal.notRestorable")+ }+}++/// terminalUnattendedRestart.ts `getTerminalInstanceBlocker`.+fn terminal_instance_blocker(instance: &TerminalInstance) -> Option<&'static str> {+ let command_detection = instance.shell_integration.has_command_detection.then(|| {+ let prompt = &instance.prompt_input;+ (instance.shell_integration.executing(), prompt.state(), format!("{}{}", prompt.prefix(), prompt.suffix()))+ });+ instance_blocker(instance.has_child_processes(), instance.shell_type, command_detection)+}++fn instance_blocker(has_child_processes: bool, shell_type: Option<&str>, command_detection: Option<(bool, PromptInputState, String)>) -> Option<&'static str> {+ if has_child_processes || !shell_type.is_some_and(|shell| INTERACTIVE_SHELLS.contains(&shell)) {+ return Some("terminal.runningProcess");+ }+ let Some((executing, state, input)) = command_detection else { return Some("terminal.idleUnknown") };+ if executing {+ return Some("terminal.runningProcess");+ }+ if state != PromptInputState::Input {+ return Some("terminal.idleUnknown");+ }+ // Typed but not run: the revived shell starts with an empty prompt.+ (!input.trim().is_empty()).then_some("terminal.pendingInput")+}+/// The service's aggregation: ids deduplicated and sorted, details of one id joined with "; ".fn readiness(blockers: impl IntoIterator<Item = Blocker>) -> Readiness {let mut ids = BTreeSet::new();@@ -143,4 +202,33 @@ mod tests {let joined = super::readiness([("workbench.editorNotRestorable", Some("A [a]".to_owned())), ("workbench.editorNotRestorable", Some("B [b]".to_owned()))]);assert_eq!(describe_blockers(&joined), "workbench.editorNotRestorable (A [a]; B [b])");}++ /// testingUnattendedRestart.test.ts "blocks while tests run".+ #[test]+ fn testing_blocks_while_tests_run() {+ let mut testing = crate::workbench::testing_service::TestingService::default();+ assert!(!testing.is_running(), "noResults");+ let mut completed = crate::testing::TestResult::new("completed".into(), serde_json::Value::Null);+ completed.completed_at = Some(1);+ testing.results.push(completed);+ assert!(!testing.is_running(), "completed");+ testing.results.insert(0, crate::testing::TestResult::new("running".into(), serde_json::Value::Null));+ assert!(testing.is_running(), "running");+ }++ /// terminalUnattendedRestart.test.ts "only an interactive shell idle at an empty prompt can be restarted".+ #[test]+ fn only_an_idle_interactive_shell_can_be_restarted() {+ let idle = || Some((false, PromptInputState::Input, String::new()));+ let typed = |input: &str| Some((false, PromptInputState::Input, input.to_owned()));+ assert_eq!(instance_blocker(false, Some("bash"), idle()), None, "idleShell");+ assert_eq!(instance_blocker(true, Some("bash"), idle()), Some("terminal.runningProcess"), "childProcess");+ assert_eq!(instance_blocker(false, Some("python"), idle()), Some("terminal.runningProcess"), "replAsShell");+ assert_eq!(instance_blocker(false, None, idle()), Some("terminal.runningProcess"), "unknownShell");+ assert_eq!(instance_blocker(false, Some("bash"), None), Some("terminal.idleUnknown"), "noShellIntegration");+ assert_eq!(instance_blocker(false, Some("bash"), Some((true, PromptInputState::Execute, String::new()))), Some("terminal.runningProcess"), "builtinLoop");+ assert_eq!(instance_blocker(false, Some("bash"), Some((false, PromptInputState::Unknown, String::new()))), Some("terminal.idleUnknown"), "promptNotDetected");+ assert_eq!(instance_blocker(false, Some("bash"), typed("git push")), Some("terminal.pendingInput"), "typedCommand");+ assert_eq!(instance_blocker(false, Some("bash"), typed(" ")), None, "typedWhitespace");+ }}diff --git a/native/crates/app/src/workbench/webview_panels.rs b/native/crates/app/src/workbench/webview_panels.rsindex 08f4877a05a..ffd112bcb88 100644--- a/native/crates/app/src/workbench/webview_panels.rs+++ b/native/crates/app/src/workbench/webview_panels.rs@@ -59,7 +59,7 @@ pub(super) struct WebviewPanel {pub(super) html: String,/// `IWebviewContentOptions`.pub(super) content_options: Value,- retain_context_when_hidden: bool,+ pub(super) retain_context_when_hidden: bool,/// `do-update-state`: what `vscode.setState` stored, given back when a released webview loads again.pub(super) state: Value,/// `$setIconPath`: the light and the dark theme's icon file.diff --git a/port/ledger.md b/port/ledger.mdindex 26497d0a4f9..5e92f88ef7b 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -408,7 +408,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| workbench/services/languageDetection | workbench service | M13 | verified | | language_detection.rs (languageDetectionWebWorker.ts `detectLanguagesImpl`, `adjustLanguageConfidence`, the 10000 char sample) and workbench/language_detection.rs (`LanguageDetectionWorkerClient`: the file name guess first, then @vscode/vscode-languagedetection 1.0.23 with its model in a Bun worker from the app's node_modules, model ids mapped as `getLanguageId`; `autoDetectLanguage` of textEditorModel.ts for untitled models and extensionless plain text files, 600 ms throttle, skipped after an explicit language and with `workbench.editor.languageDetection` off): cargo test -p app language_detection (the worker test runs the real model). The history biases only feed the regexp model, which 1.147.0 does not ship (`vscode-regexp-languagedetection` is not a dependency), so neither side has it; no telemetry || workbench/services/languageStatus | workbench service | M13 | verified | | `$setLanguageStatus` / `$removeLanguageStatus`, statuses matched by selector, ordered by severity, source, id (workbench/language_status.rs): cargo test -p app language_status || workbench/services/layout | workbench service | M11 | ported | [3 L] editor_status.rs:606, content_hover.rs:498: no workbench-wide Tab order (the browser's DOM order): Tab stops at the content hover's ends, and Tab on the status bar in Tab Focus Mode keeps the focus (port/notes.md Toggle Tab Key Moves Focus) <br> [3 L] workbench.rs:591: the Workbench is one GPUI view, so every scroll frame of any list renders and lays out every part again, where upstream's DOM updates only the scrolled list; `scroll_frame_time` median / p95 at 42d10fe2347: Explorer 11.5 / 15.7 ms, Editor 18.0 / 19.2 to 42.0 ms, Settings 12.4 / 16.8 ms over the 8 ms gate (Extensions 2.8 / 3.0 meets it); per frame taffy lays out the whole workbench (6.6 ms of the Explorer frame), each `key_context` caller clones every `config.*` key (keyboard.rs:400), the menubar and the timeline toolbar are rebuilt; the next step is the part-entity split, side bar first (port/notes.md Scroll frame costs, cheap steps). GUI (Studio at load 33 to 57, 60 Hz display, 690 trackpad events in 7 s): main thread in `Window::draw` 86% scrolling the Explorer (800 files), 89% the Extensions @builtin list (port/notes.md Scroll frame costs) | layout.ts as a split-view tree (workbench/layout.rs): panel position (bottom, top, left, right) and alignment, primary side bar left or right, maximized panel with `panelMaximizationSupportedWhen`, hidden parts, persisted sizes and positions; zen mode (zen_mode.rs) with its settings and restore; centered layout (centered_layout.rs) with its sashes and stored margins; View > Appearance entries and the Panel Position and Align Panel submenus (cargo test -p app -- layout part_grid centered_layout zen_mode); layoutActions.ts Customize Layout quick pick (workbench/customize_layout.rs) with live items, Restore Defaults and Close, Toggle Activity Bar Visibility, Align Quick Input Top/Center (cargo test -p app -- customize_layout toggling_the_activity_bar; ui-pair m11/manage-menu.json, port/results/manage-menu.md; missing until then though the title bar showed its button); ui-pair layout-positions.json and layout-zen.json against the reference (port/results/layout.md). The pairs run with `zenMode.fullScreen` off. Maximize Secondary Side Bar (`workbench.action.maximizeAuxiliaryBar`, `restoreAuxiliaryBar`, `toggleMaximizedAuxiliaryBar`, the title's toggle) hides the other parts and restores them (workbench/panel.rs; cargo test -p app -- maximizing_the_secondary_side_bar_hides_the_other_parts_and_restore_brings_them_back). Zen mode enforces `zenMode.showTabs` on the main editor part until it ends (layout.ts `toggleZenMode` `enforcePartOptions`; workbench/zen_mode.rs `editor_show_tabs`; cargo test -p app -- show_tabs_picks_the_title_control_and_zen_mode_enforces_its_own); navigationActions.ts `workbench.action.focusNextPart`/`focusPreviousPart` (F6, Shift+F6) walk editor, panel, auxiliary bar, status bar, activity bar and side bar past the hidden ones with layout.ts `focusPart` (the pane container's first expanded view; workbench/part_navigation.rs; cargo test -p app f6_walks_the_visible_parts); in an editor window F6 goes between its editor and its own status bar, whose entry focus is kept per window (workbench/auxiliary_windows.rs `auxiliary_status_bar`, workbench/status_entries.rs; cargo test -p app f6_in_an_editor_window_reaches_its_own_status_bar) |-| workbench/services/lifecycle | workbench service | M11 | ported | [3 L] unattendedRestart.ts: the participants terminalUnattendedRestart.ts, testingUnattendedRestart.ts, webviewUnattendedRestart.ts, notebookUnattendedRestart.ts and testingContinuousRunService.ts `testing.continuousRun` are not ported (the port's terminal has no `hasChildProcesses`), the editor detail names the scheme where upstream names `typeId`, `workbench.floatingWindowNotRestorable` cannot occur (the port's auxiliary windows are all editor parts), and nothing calls `can_restart_unattended` yet: platform/update's `UnattendedRestartScheduler` (restart to update while the screen is locked, with `update.restartWhenIdle` on), `quitAndInstall` with `unattended` and windowsStateHandler.ts `setNextExactRestore` are not ported | workbench/lifecycle.rs: ShutdownReason, onBeforeShutdown vetoes on quit, close button, closeWindow, reload and load (`window.confirmBeforeClose`, backup tracker auto save, hot exit, showSaveConfirm); cargo test -p app lifecycle; no phases or onWillShutdown joiners; workbench/unattended_restart.rs: `canRestartUnattended` with its blocker aggregation and change log, and the participants `workbench.starting` (2.5 s after restore), dialog, quick input, transient workspace, modal editor, editors not restored or not restorable, `debug.sessionActive`, `tasks.running`, the backup tracker's `workingCopy.*` and `cli.waitingForEditorClose`: cargo test -p app unattended_restart (unattendedRestart.test.ts); verified: cargo test -p app backup_tracker lifecycle (workingCopyBackupTracker.test.ts); ui-pair hot-exit.json `dirty`, `restored` vs the reference (port/results/windows.md, milestone 11 verification) |+| workbench/services/lifecycle | workbench service | M11 | ported | [3 L] unattendedRestart.ts: the editor detail names the scheme where upstream names `typeId`, `workbench.floatingWindowNotRestorable` cannot occur (the port's auxiliary windows are all editor parts), and nothing calls `can_restart_unattended` yet: platform/update's `UnattendedRestartScheduler` (restart to update while the screen is locked, with `update.restartWhenIdle` on), `quitAndInstall` with `unattended` and windowsStateHandler.ts `setNextExactRestore` are not ported <br> [3 S] terminal/pty.rs:95: `hasChildProcesses` is a foreground process group other than the shell's, so a background job (`cmd &`) does not block the restart where upstream's childProcessMonitor.ts sees it | workbench/lifecycle.rs: ShutdownReason, onBeforeShutdown vetoes on quit, close button, closeWindow, reload and load (`window.confirmBeforeClose`, backup tracker auto save, hot exit, showSaveConfirm); cargo test -p app lifecycle; no phases or onWillShutdown joiners; workbench/unattended_restart.rs: `canRestartUnattended` with its blocker aggregation and change log, and the participants `workbench.starting` (2.5 s after restore), dialog, quick input, transient workspace, modal editor, editors not restored or not restorable, `debug.sessionActive`, `tasks.running`, the backup tracker's `workingCopy.*` and `cli.waitingForEditorClose`, terminalUnattendedRestart.ts, testingUnattendedRestart.ts, `testing.continuousRun`, webviewUnattendedRestart.ts and notebookUnattendedRestart.ts: cargo test -p app unattended_restart (unattendedRestart.test.ts, terminalUnattendedRestart.test.ts, testingUnattendedRestart.test.ts); verified: cargo test -p app backup_tracker lifecycle (workingCopyBackupTracker.test.ts); ui-pair hot-exit.json `dirty`, `restored` vs the reference (port/results/windows.md, milestone 11 verification) || workbench/services/localTranscription | workbench service | | removed | | no AI or Microsoft services by decision (port/notes.md); API stays inert || workbench/services/localization | workbench service | M18 | verified | | ui-pair port/fixtures/extensions/ui-display-language.json: picking Deutsch installs MS-CEINTL.vscode-language-pack-de with the "Installing Deutsch language support..." progress and asks "Restart VSRustium to switch to Deutsch?"; localeService.ts: argv.json `locale` written and cleared, restart dialog, install of an MS-CEINTL pack: cargo test -p app nls localization; Command Palette titles, categories and descriptions translate by the reference call's module and key (port/tools/ref-commands with ref-nls-clone.ts; cargo test -p app a_palette_title_two_modules), menu bar items, side bar titles and pane headers by the reference's `nlsKeys` per menu, view and container (cargo test -p app menu_bar_items_and_view_titles_resolve_per_scope); other surfaces stay English (port/notes.md) || workbench/services/log | workbench service | M6 | verified | | output/log_levels.rs: defaultLogLevels.ts argv.json `log-level` read and write, `getDefaultLogLevel`, `parseLogLevel`; logs_actions.rs `setDefaultLogLevel` (cargo test -p app set_default_log_level_writes_argv, reads_and_writes_argv_log_levels); the Window log as logConstants.ts `windowLogId`; electron-browser logService.ts in a test run: the host console reaches stdout/stderr through the session; output/log_levels.rs: defaultLogLevels.ts argv.json `log-level` read and write, `getDefaultLogLevel`, `parseLogLevel`; logs_actions.rs `setDefaultLogLevel` (cargo test -p app set_default_log_level_writes_argv, reads_and_writes_argv_log_levels); the Window log as logConstants.ts `windowLogId` |