Visual Studio Code, rebuilt in Rust
Rust
feat(lifecycle): wire the unattended restart scheduler and restore the windows exactly after it
rokarturebbb4bf9593f
diff --git a/native/crates/app/src/main.rs b/native/crates/app/src/main.rsindex 1099c62f01f..c4469b660d2 100644--- a/native/crates/app/src/main.rs+++ b/native/crates/app/src/main.rs@@ -281,10 +281,15 @@ fn main() -> anyhow::Result<()> {// startup window's place and open from the task, as effects deferred from this callback never run.let launch_urls: Vec<Vec<String>> = std::iter::from_fn(|| urls.try_recv().ok()).collect();let opens_documents = no_cli_paths && launch_urls.iter().flatten().any(|url| url.starts_with("file:"));- let restored = match restores {+ let exact_restore = windows_state::take_exact_restore(&app.user_data);+ let mut restored = match restores {true => last_session_windows(&app.user_data, !no_cli_paths, opens_documents),false => Vec::new(),};+ // windowsMainService.ts `openInBrowserWindow`: a window comes back minimized only in an exact restore.+ for ui in restored.iter_mut().filter_map(|window| window.ui.as_mut()) {+ ui.minimized &= exact_restore.is_some();+ }let opens_startup = !opens_documents && (!no_cli_paths || restored.is_empty());cx.spawn(async move |cx| {let mut opened_urls = futures::StreamExt::chain(futures::stream::iter(launch_urls), urls);@@ -314,7 +319,12 @@ fn main() -> anyhow::Result<()> {if let Some(launches) = launches {launch::handle_launches(launches, cx);}- cx.activate(true);+ // windowsMainService.ts `open`: an exact restore of a hidden app hides it again.+ if exact_restore.is_some_and(|exact| exact.hide_application) {+ cx.hide();+ } else {+ cx.activate(true);+ }});Ok(())}@@ -486,6 +496,8 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resulbackup_path: backup_folder.clone(),ui: None,};+ // Only a restored window of an exact restore asks for it; it must not take focus (windowImpl.ts `applyState`).+ let minimized = ui.is_some_and(|ui| ui.minimized);let ui = ui.or_else(|| windows_state::stored_ui_state(&user_data, &location, open_windows.is_empty(), cx).filter(|_| !extension_tests));// windowsStateHandler.ts `doGetNewWindowState` for a window without a stored state: `window.newWindowDimensions`.let last_active = cx.window_stack().unwrap_or_else(|| cx.windows()).into_iter().find_map(|handle| handle.downcast::<Workbench>());@@ -503,7 +515,7 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resullet (display_id, window_bounds) = ui.and_then(|ui| windows_state::window_bounds(ui, cx)).map_or((None, default_bounds), |(display, bounds)| (Some(display), bounds));// window.ts `WindowMinimumSize`.let window_min_size = Some(size(px(400.), px(270.)));- let options = WindowOptions { window_bounds: Some(window_bounds), display_id, titlebar: Some(titlebar), app_owns_titlebar_drag: true, window_min_size, app_id: crate::product::linux_desktop_name(), ..Default::default() };+ let options = WindowOptions { window_bounds: Some(window_bounds), display_id, titlebar: Some(titlebar), app_owns_titlebar_drag: true, window_min_size, app_id: crate::product::linux_desktop_name(), focus: !minimized, ..Default::default() };perf::mark("code/willOpenNewWindow");perf::mark("code/willCreateCodeWindow");let window = {@@ -685,6 +697,9 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resul})})?};+ if minimized {+ window.update(cx, |_, window, _| window.minimize_window())?;+ }perf::mark("code/didCreateCodeWindow");Ok(window)}@@ -900,7 +915,7 @@ fn a_finder_launch_restores_the_last_session_only_with_preserve() {std::fs::create_dir_all(user_data.join("User/globalStorage")).unwrap();std::fs::create_dir_all(user_data.join("folder")).unwrap();let folder = windows_state::WindowState { folder: Some(user_data.join("folder")), ..Default::default() };- windows_state::save(&user_data, Some(&folder), &[]);+ windows_state::save(&user_data, Some(&folder), &[], None);let restored_with = |setting: &str| {std::fs::write(user_data.join("User/settings.json"), format!(r#"{{ "window.restoreWindows": "{setting}" }}"#)).unwrap();last_session_windows(&user_data, false, true)diff --git a/native/crates/app/src/power.rs b/native/crates/app/src/power.rsindex c205f9e2646..b82f7dfb60e 100644--- a/native/crates/app/src/power.rs+++ b/native/crates/app/src/power.rs@@ -66,7 +66,7 @@ impl PowerSaveBlockers {}}-static BLOCKERS: LazyLock<Mutex<PowerSaveBlockers>> = LazyLock::new(Default::default);+pub(crate) static BLOCKERS: LazyLock<Mutex<PowerSaveBlockers>> = LazyLock::new(Default::default);/// mainThreadPower.ts: the answer to one `MainThreadPower` request.pub fn request(method: &str, args: &[Value]) -> Result<Value, String> {diff --git a/native/crates/app/src/power/macos.rs b/native/crates/app/src/power/macos.rsindex 7be827670d3..0478b6874ea 100644--- a/native/crates/app/src/power/macos.rs+++ b/native/crates/app/src/power/macos.rs@@ -2,7 +2,7 @@//! NSWorkspace and NSProcessInfo notifications.use std::ptr::NonNull;-use std::sync::{Mutex, OnceLock};+use std::sync::{Mutex, Once};use block2::RcBlock;use core_foundation::base::{CFType, TCFType};@@ -109,20 +109,22 @@ pub(super) fn release_assertion(assertion: u32) {unsafe { IOPMAssertionRelease(assertion) };}-static EVENTS: OnceLock<UnboundedSender<PowerEvent>> = OnceLock::new();+static EVENTS: Mutex<Vec<UnboundedSender<PowerEvent>>> = Mutex::new(Vec::new());+static OBSERVING: Once = Once::new();static ON_BATTERY: Mutex<Option<bool>> = Mutex::new(None);-/// powerMonitor's events as ExtHostPower methods, delivered on the main thread: suspend and resume, shutdown,-/// screen lock, thermal state, battery and speed limit changes. Call once; the observers live as long as the app.+fn send(event: PowerEvent) {+ EVENTS.lock().unwrap().retain(|events| events.unbounded_send(event.clone()).is_ok());+}++/// powerMonitor's events as ExtHostPower methods, delivered on the main thread to every receiver: suspend and resume,+/// shutdown, screen lock, thermal state, battery and speed limit changes. The observers live as long as the app.pub fn watch(events: UnboundedSender<PowerEvent>) {- if EVENTS.set(events).is_err() {- return;- }- let send = |event: PowerEvent| {- if let Some(events) = EVENTS.get() {- let _ = events.unbounded_send(event);- }- };+ EVENTS.lock().unwrap().push(events);+ OBSERVING.call_once(observe_power_events);+}++fn observe_power_events() {let queue = NSOperationQueue::mainQueue();let observe = |center: &NSNotificationCenter, name: &NSString, event: fn() -> PowerEvent| {let block = RcBlock::new(move |_: NonNull<NSNotification>| send(event()));@@ -166,7 +168,5 @@ extern "C" fn power_sources_changed(_: *mut std::ffi::c_void) {return;}*last = Some(on_battery);- if let Some(events) = EVENTS.get() {- let _ = events.unbounded_send(("$onDidChangeOnBatteryPower", vec![json!(on_battery)]));- }+ send(("$onDidChangeOnBatteryPower", vec![json!(on_battery)]));}diff --git a/native/crates/app/src/update.rs b/native/crates/app/src/update.rsindex 681d7619f64..b429599aaf9 100644--- a/native/crates/app/src/update.rs+++ b/native/crates/app/src/update.rs@@ -438,6 +438,11 @@ impl UpdateService {true}+ #[cfg(test)]+ pub(crate) fn set_state_for_tests(&mut self, state: State, cx: &mut Context<Self>) {+ self.set_state(state, cx);+ }+pub fn cancel_restart(&mut self, cx: &mut Context<Self>) {if let State::Restarting { update, app } = &self.state {let state = State::Ready { update: update.clone(), app: app.clone() };diff --git a/native/crates/app/src/update/unattended_restart.rs b/native/crates/app/src/update/unattended_restart.rsindex cc5b4cc9b17..8c0915d8fa1 100644--- a/native/crates/app/src/update/unattended_restart.rs+++ b/native/crates/app/src/update/unattended_restart.rs@@ -4,8 +4,6 @@//! `keep_awake_until` is ahead. No telemetry is sent (port/notes.md Privacy), so with `update.restartWhenIdle` off//! nothing runs, as upstream's does at telemetry level NONE, and the outcomes upstream reports are not kept.-#![cfg_attr(not(test), expect(dead_code, reason = "the next step of the lifecycle row's unattendedRestart gap wires the scheduler to the power events and the update service"))]-use std::time::{Duration, Instant};use crate::workbench::unattended_restart::{Readiness, describe_blockers};@@ -174,6 +172,11 @@ impl Scheduler {self.keep_awake_since.map(|since| since + KEEP_AWAKE_LIMIT)}+ /// `keepAwakeLimit`: the caller's timer at `keep_awake_until`.+ pub fn keep_awake_limit_reached(&mut self) {+ self.allow_sleep("the restart did not happen in time");+ }+/// `getBlockers` past the windows' answers, which the caller already put in `readiness`.fn blockers(&self, is_due: bool, update: &str, checks: Checks) -> Readiness {let mut readiness = checks.readiness;diff --git a/native/crates/app/src/windows_state.rs b/native/crates/app/src/windows_state.rsindex 9bb364ee6d5..938aac4f29c 100644--- a/native/crates/app/src/windows_state.rs+++ b/native/crates/app/src/windows_state.rs@@ -10,6 +10,7 @@ use storage::state::FileStorage;use crate::uri::Uri;const WINDOWS_STATE_KEY: &str = "windowsState";+const EXACT_RESTORE_KEY: &str = "windowsExactRestore";/// `WindowMode`.pub const MAXIMIZED: u64 = 0;@@ -34,8 +35,24 @@ pub struct UiState {pub y: f64,pub width: f64,pub height: f64,+ /// Only recorded and restored when the app restores the windows exactly.+ pub minimized: bool,}+/// `IExactRestoreState`: the next start restores the windows exactly as they were, minimized ones minimized, after+/// the app restarted while the user was away.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct ExactRestore {+ /// macOS: hide the app again after showing its windows.+ pub hide_application: bool,+}++/// windowsStateHandler.ts `nextExactRestore`, written as the app quits without a veto (`setNextExactRestore`).+#[derive(Default)]+pub struct NextExactRestore(pub Option<ExactRestore>);++impl gpui::Global for NextExactRestore {}+/// windowsStateHandler.ts `lastClosedState`: the last window closed, the last active one of a quit without windows;/// forgotten once another window opens.pub struct LastClosedWindow(pub Option<WindowState>);@@ -74,14 +91,40 @@ pub fn load(user_data: &Path) -> (Option<WindowState>, Vec<WindowState>) {(state.get("lastActiveWindow").filter(|window| window.is_object()).map(parse), opened)}-/// `getWindowsStateStoreData` written as the app quits.-pub fn save(user_data: &Path, last_active: Option<&WindowState>, opened: &[WindowState]) {+/// `getWindowsStateStoreData` written as the app quits, with `nextExactRestore` (`onWillShutdown`).+pub fn save(user_data: &Path, last_active: Option<&WindowState>, opened: &[WindowState], exact: Option<ExactRestore>) {let mut storage = FileStorage::open(&storage_file(user_data));let mut state = json!({ "openedWindows": opened.iter().map(serialize).collect::<Vec<_>>() });if let Some(last_active) = last_active {state["lastActiveWindow"] = serialize(last_active);}storage.set_item(WINDOWS_STATE_KEY, Some(state));+ if let Some(exact) = exact {+ storage.set_item(EXACT_RESTORE_KEY, Some(json!({ "hideApplication": exact.hide_application })));+ }+}++/// windowsMainService.ts `restoreExactlyOnNextStartup`: the app hidden now is hidden again then.+pub fn restore_exactly_on_next_startup(restore: bool, cx: &mut App) {+ let next = restore.then(|| ExactRestore { hide_application: app_hidden() });+ cx.set_global(NextExactRestore(next));+}++/// `app.isHidden()`; tests run off the main thread, without an NSApplication.+fn app_hidden() -> bool {+ #[cfg(target_os = "macos")]+ return objc2::MainThreadMarker::new().is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isHidden());+ #[cfg(not(target_os = "macos"))]+ false+}++/// `takeExactRestore`: the exact restore the last quit asked for, which applies to this start only.+pub fn take_exact_restore(user_data: &Path) -> Option<ExactRestore> {+ let mut storage = FileStorage::open(&storage_file(user_data));+ let hide_application = storage.get_item(EXACT_RESTORE_KEY)?["hideApplication"].as_bool();+ storage.set_item(EXACT_RESTORE_KEY, None);+ eprintln!("[WindowsStateHandler] restoring windows exactly");+ Some(ExactRestore { hide_application: hide_application? })}/// `doGetPathsFromLastSession`: `none` nothing, `one` the last active window, `folders` the opened windows and the@@ -120,7 +163,15 @@ pub fn ui_state(window: &Window, cx: &App) -> UiState {};let display = window.display(cx).map(|display| u64::from(display.id()));let points = |pixels: Pixels| f64::from(f32::from(pixels));- UiState { mode, display, x: points(bounds.origin.x), y: points(bounds.origin.y), width: points(bounds.size.width), height: points(bounds.size.height) }+ UiState { mode, display, x: points(bounds.origin.x), y: points(bounds.origin.y), width: points(bounds.size.width), height: points(bounds.size.height), minimized: false }+}++/// `isMinimized`; none on GPUI's test platform.+pub fn is_minimized(window: &Window) -> bool {+ #[cfg(target_os = "macos")]+ return crate::dialog::app_kit_window(window).is_some_and(|window| window.isMiniaturized());+ #[cfg(not(target_os = "macos"))]+ false}/// `validateWindowState`: the display and bounds to open a restored window with, none when its display is gone or@@ -148,7 +199,7 @@ fn parse(window: &Value) -> WindowState {let ui = &window["uiState"];let number = |key: &str| ui[key].as_f64();let ui = match (number("x"), number("y"), number("width"), number("height")) {- (Some(x), Some(y), Some(width), Some(height)) => Some(UiState { mode: ui["mode"].as_u64().unwrap_or(NORMAL), display: ui["display"].as_u64(), x, y, width, height }),+ (Some(x), Some(y), Some(width), Some(height)) => Some(UiState { mode: ui["mode"].as_u64().unwrap_or(NORMAL), display: ui["display"].as_u64(), x, y, width, height, minimized: ui["minimized"] == true }),_ => None,};WindowState { workspace: path(&window["workspaceIdentifier"]["configURIPath"]), folder: path(&window["folder"]), backup_path: window["backupPath"].as_str().map(PathBuf::from), ui }@@ -169,6 +220,9 @@ fn serialize(window: &WindowState) -> Value {}if let Some(ui) = window.ui {state["uiState"] = json!({ "mode": ui.mode, "display": ui.display, "x": ui.x, "y": ui.y, "width": ui.width, "height": ui.height });+ if ui.minimized {+ state["uiState"]["minimized"] = json!(true);+ }}state}@@ -188,14 +242,25 @@ mod tests {#[test]fn the_state_round_trips_through_storage_json() {let dir = scratch("save");- let ui = Some(UiState { mode: NORMAL, display: Some(1), x: 10., y: 20., width: 1024., height: 768. });+ let ui = Some(UiState { mode: NORMAL, display: Some(1), x: 10., y: 20., width: 1024., height: 768., minimized: true });let folder = WindowState { folder: Some(dir.join("folder")), backup_path: Some(dir.join("Backups/abc")), ui, ..WindowState::default() };let empty = WindowState { backup_path: Some(dir.join("Backups/123")), ..WindowState::default() };- save(&dir, Some(&folder), &[empty.clone(), folder.clone()]);+ save(&dir, Some(&folder), &[empty.clone(), folder.clone()], None);assert_eq!(load(&dir), (Some(folder), vec![empty, WindowState { folder: Some(dir.join("folder")), backup_path: Some(dir.join("Backups/abc")), ui, ..WindowState::default() }]));std::fs::remove_dir_all(&dir).unwrap();}+ #[test]+ fn an_exact_restore_applies_to_the_next_start_only() {+ let dir = scratch("exact");+ save(&dir, None, &[], None);+ assert_eq!(take_exact_restore(&dir), None);+ save(&dir, None, &[], Some(ExactRestore { hide_application: true }));+ assert_eq!(take_exact_restore(&dir), Some(ExactRestore { hide_application: true }));+ assert_eq!(take_exact_restore(&dir), None);+ std::fs::remove_dir_all(&dir).unwrap();+ }+#[test]fn a_new_window_cascades_off_the_open_ones() {let at = |x: f32, y: f32| Bounds::new(point(px(x), px(y)), size(px(1024.), px(768.)));diff --git a/native/crates/app/src/workbench.rs b/native/crates/app/src/workbench.rsindex 1267c5f5f5e..ba5aabf568e 100644--- a/native/crates/app/src/workbench.rs+++ b/native/crates/app/src/workbench.rs@@ -338,7 +338,6 @@ pub struct Workbench {/// When the window finished restoring (`LifecyclePhase.Restored`).pub restored_at: Option<std::time::Instant>,/// The blockers `can_restart_unattended` logged last.- #[expect(dead_code, reason = "the unattended restart scheduler, the next step of the lifecycle row's unattendedRestart gap, calls it")]unattended_restart_logged: String,/// The group and path of each editor `release_closed_wait_files` saw last, to tell a close from a move.wait_shown: Vec<(u32, PathBuf)>,diff --git a/native/crates/app/src/workbench/backup_tracker.rs b/native/crates/app/src/workbench/backup_tracker.rsindex 5e588737804..e371374b1e8 100644--- a/native/crates/app/src/workbench/backup_tracker.rs+++ b/native/crates/app/src/workbench/backup_tracker.rs@@ -383,7 +383,6 @@ impl Workbench {/// workingCopyBackupTracker.ts `getUnattendedRestartBlocker`: a modified working copy that a shutdown would ask/// about, save, or lose.- #[expect(dead_code, reason = "the unattended restart scheduler, the next step of the lifecycle row's unattendedRestart gap, calls it")]pub(super) fn working_copy_restart_blocker(&self) -> Option<&'static str> {let models: Vec<&OpenEditor> = self.editors.editors.iter().chain(&self.editors.models).filter(|model| tracked(model) && model.is_dirty()).collect();let custom = self.dirty_documents(DocumentKind::Custom);diff --git a/native/crates/app/src/workbench/lifecycle.rs b/native/crates/app/src/workbench/lifecycle.rsindex 5f7b077a555..612d6fabf8c 100644--- a/native/crates/app/src/workbench/lifecycle.rs+++ b/native/crates/app/src/workbench/lifecycle.rs@@ -10,7 +10,7 @@ use super::Workbench;use super::actions::{file_names_message, save_confirm_text};use crate::commands::Outcome;use crate::dialog;-use crate::windows_state::{self, LastClosedWindow, WindowState};+use crate::windows_state::{self, LastClosedWindow, NextExactRestore, WindowState};/// `ShutdownReason`.#[derive(Clone, Copy, Debug, PartialEq)]@@ -210,6 +210,7 @@ pub(super) async fn quit_all_windows(cx: &mut AsyncWindowContext) -> bool {/// windows when there are two or more.fn save_windows_state(cx: &mut App) {let mut last_active = cx.try_global::<LastClosedWindow>().and_then(|closed| closed.0.clone());+ let exact = cx.try_global::<NextExactRestore>().and_then(|next| next.0);let mut active = None;let mut opened = Vec::new();for handle in cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()) {@@ -217,7 +218,10 @@ fn save_windows_state(cx: &mut App) {if workbench.extension_development {return;}- let state = workbench.window_state(window, cx);+ let mut state = workbench.window_state(window, cx);+ if let Some(ui) = &mut state.ui {+ ui.minimized = exact.is_some() && windows_state::is_minimized(window);+ }if window.is_window_active() {active = Some(state.clone());}@@ -229,7 +233,7 @@ fn save_windows_state(cx: &mut App) {opened.clear();}let user_data = cx.global::<crate::AppState>().user_data.clone();- windows_state::save(&user_data, last_active.as_ref(), &opened);+ windows_state::save(&user_data, last_active.as_ref(), &opened, exact);}/// The `onBeforeShutdown` participants in order; true when one vetoes.diff --git a/native/crates/app/src/workbench/unattended_restart.rs b/native/crates/app/src/workbench/unattended_restart.rsindex 7117905d76e..ec9b58a6799 100644--- a/native/crates/app/src/workbench/unattended_restart.rs+++ b/native/crates/app/src/workbench/unattended_restart.rs@@ -1,12 +1,18 @@//! `UnattendedRestartService` (workbench/services/lifecycle/common/unattendedRestart.ts) with its participants//! (contrib/update/browser/unattendedRestartParticipants.ts and the ones other areas register), called directly.-#![expect(dead_code, reason = "the unattended restart scheduler, the next step of the lifecycle row's unattendedRestart gap, calls it")]-use std::collections::{BTreeMap, BTreeSet};-use std::time::Duration;+use std::time::{Duration, Instant};++use futures::StreamExt;+use futures::channel::mpsc::unbounded;+use gpui::{AppContext, Context, Entity, Global, Task, Window, WindowHandle};+use serde_json::Value;use super::Workbench;+use crate::update::State;+use crate::update::unattended_restart::{Checks, Scheduler, Step};+use crate::windows_state;use crate::terminal::TerminalInstance;use crate::terminal::prompt_input::PromptInputState;@@ -173,10 +179,197 @@ fn changed_log(last_logged: &mut String, readiness: &Readiness) -> Option<StringSome(message)}+/// unattendedRestartScheduler.ts's host, one for the app: the power events, the windows' blur and the update service's+/// state go to the scheduler; it runs the evaluations the scheduler asks for and keeps the machine awake meanwhile.+struct UnattendedRestart {+ scheduler: Scheduler,+ evaluation: Task<()>,+ /// The `prevent-app-suspension` blocker and the timer of `KEEP_AWAKE_LIMIT`.+ keep_awake: Option<(i64, Task<()>)>,+}++struct GlobalUnattendedRestart(Entity<UnattendedRestart>);++impl Global for GlobalUnattendedRestart {}++impl Workbench {+ /// Starts the scheduler with the first window, on macOS only (`isUnattendedRestartSupported`).+ pub(super) fn start_unattended_restart(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ cx.observe_window_activation(window, |_, window, cx| {+ if !window.is_window_active()+ && let Some(global) = cx.try_global::<GlobalUnattendedRestart>()+ {+ global.0.clone().update(cx, |this, _| this.scheduler.window_blurred(Instant::now()));+ }+ })+ .detach();+ if !cfg!(target_os = "macos") || cx.has_global::<GlobalUnattendedRestart>() {+ return;+ }+ let service = crate::update::service(cx);+ let entity = cx.new(|cx: &mut Context<UnattendedRestart>| {+ let (sender, mut events) = unbounded();+ crate::power::watch(sender);+ cx.spawn(async move |this, cx| {+ while let Some((method, args)) = events.next().await {+ if this.update(cx, |this, cx| this.power_event(method, &args, cx)).is_err() {+ return;+ }+ }+ })+ .detach();+ cx.subscribe(&service, |this, _, state, cx| {+ let step = this.scheduler.update_state_changed(Instant::now(), matches!(state, State::Ready { .. }), matches!(state, State::Restarting { .. }));+ this.follow(step, cx);+ })+ .detach();+ UnattendedRestart { scheduler: Scheduler::new(None), evaluation: Task::ready(()), keep_awake: None }+ });+ cx.set_global(GlobalUnattendedRestart(entity));+ }+}++impl UnattendedRestart {+ fn power_event(&mut self, method: &str, args: &[Value], cx: &mut Context<Self>) {+ let now = Instant::now();+ let step = match method {+ "$onDidLockScreen" => self.scheduler.screen_locked(now, cx.active_window().is_some()),+ "$onDidUnlockScreen" => {+ self.evaluation = Task::ready(());+ self.scheduler.screen_unlocked();+ Step::Nothing+ }+ "$onDidSuspend" => {+ self.evaluation = Task::ready(());+ self.scheduler.suspended();+ Step::Nothing+ }+ "$onDidResume" => self.scheduler.resumed(now),+ "$onDidChangeOnBatteryPower" if args.first() == Some(&Value::Bool(true)) => {+ self.scheduler.power_changed(true, crate::power::thermal_state());+ Step::Nothing+ }+ "$onDidChangeThermalState" => {+ self.scheduler.power_changed(false, args.first().and_then(Value::as_str).unwrap_or_default());+ Step::Nothing+ }+ _ => return,+ };+ self.follow(step, cx);+ }++ fn follow(&mut self, step: Step, cx: &mut Context<Self>) {+ match step {+ Step::Nothing => {}+ Step::EvaluateAt(at) => {+ self.evaluation = cx.spawn(async move |this, cx| {+ cx.background_executor().timer(at.saturating_duration_since(Instant::now())).await;+ let _ = this.update(cx, |this, cx| this.evaluate(cx));+ });+ }+ Step::Restart { .. } => self.restart(cx),+ }+ // `cancelRestart`: no pending restart, no exact restore.+ if self.scheduler.pending.is_none() {+ windows_state::restore_exactly_on_next_startup(false, cx);+ }+ self.sync_keep_awake(cx);+ }++ /// `getBlockers`' window part: every window's readiness, and `update.restartWhenIdle` on in all of them.+ fn evaluate(&mut self, cx: &mut Context<Self>) {+ let windows: Vec<WindowHandle<Workbench>> = cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()).collect();+ let mut blockers = Vec::new();+ let mut enabled = !windows.is_empty();+ for handle in windows {+ let _ = handle.update(cx, |workbench, _, _| {+ let mut window = workbench.can_restart_unattended();+ blockers.extend(window.blockers.into_iter().map(|id| (id, window.details.remove(id))));+ enabled &= workbench.setting("update.restartWhenIdle") == true;+ });+ }+ let update = match crate::update::service(cx).read(cx).state() {+ State::Ready { update, .. } => Some(update.version.clone()),+ _ => None,+ };+ let checks = Checks { readiness: readiness(blockers), idle_state: crate::power::system_idle_state(60), on_battery: crate::power::on_battery_power(), thermal_state: crate::power::thermal_state() };+ let step = self.scheduler.evaluate(Instant::now(), update.as_deref(), enabled, checks);+ self.follow(step, cx);+ }++ /// `restoreExactlyOnNextStartup(true)`, then `quitAndInstall` from a window; the shutdown is under way when the+ /// update service is Restarting. `unattended` and `token` only matter to the overwrite check, which the port does+ /// not reach (port/notes.md Update service); relaunchInBackground is not passed on, as updateService.darwin.ts does not.+ fn restart(&mut self, cx: &mut Context<Self>) {+ windows_state::restore_exactly_on_next_startup(true, cx);+ let first = cx.windows().into_iter().find_map(|handle| handle.downcast::<Workbench>());+ if let Some(handle) = first {+ let _ = handle.update(cx, |_, window, cx| super::update::quit_and_install(window, cx));+ }+ let restarting = matches!(crate::update::service(cx).read(cx).state(), State::Restarting { .. });+ self.scheduler.restart_returned(restarting);+ }++ fn sync_keep_awake(&mut self, cx: &mut Context<Self>) {+ match (self.scheduler.keep_awake_until(), &self.keep_awake) {+ (Some(until), None) => {+ let id = crate::power::BLOCKERS.lock().unwrap().start("prevent-app-suspension");+ let limit = cx.spawn(async move |this, cx| {+ cx.background_executor().timer(until.saturating_duration_since(Instant::now())).await;+ let _ = this.update(cx, |this, cx| {+ this.scheduler.keep_awake_limit_reached();+ this.sync_keep_awake(cx);+ });+ });+ self.keep_awake = Some((id, limit));+ }+ (None, Some(_)) => {+ let (id, _) = self.keep_awake.take().expect("matched above");+ crate::power::BLOCKERS.lock().unwrap().stop(id);+ }+ _ => {}+ }+ }+}+#[cfg(test)]mod tests {use super::*;+ fn workbench(cx: &mut gpui::TestAppContext) -> (Entity<Workbench>, &mut gpui::VisualTestContext) {+ let app_root = std::path::Path::new(env!("VSCODE_SRC")).to_path_buf();+ let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();+ let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();+ let dir = std::env::temp_dir().join(format!("vsrustium-unattended-restart-{}", std::process::id()));+ std::fs::create_dir_all(dir.join("User")).unwrap();+ let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));+ let host = crate::host_sync::HostSync::new(std::sync::mpsc::channel().0);+ let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), settings, host, cx));+ cx.run_until_parked();+ (workbench, cx)+ }++ /// The host feeds the lock to the scheduler and runs its first evaluation, which keeps the machine awake while+ /// every window could be restored; the unlock lets it sleep again.+ #[gpui::test]+ fn a_locked_screen_keeps_the_machine_awake_until_it_is_unlocked(cx: &mut gpui::TestAppContext) {+ let (workbench, cx) = workbench(cx);+ let update = crate::update::Update { version: "bbbb".into(), product_version: "1.148.0".into(), timestamp: 2, url: "https://example.com/a.zip".into(), sha256hash: "ab".repeat(32) };+ workbench.update_in(cx, |workbench, window, cx| {+ workbench.restored_at = Some(Instant::now() - 2 * EVENTUALLY);+ workbench.settings.lock().unwrap().update_value("update.restartWhenIdle", Some(&serde_json::json!(true)), config::service::Target::User, None, &[]).unwrap();+ workbench.register_update_actions(window, cx);+ crate::update::service(cx).update(cx, |service, cx| service.set_state_for_tests(State::Ready { update, app: "/tmp/VSRustium.app".into() }, cx));+ });+ let host = cx.update(|_, cx| cx.global::<GlobalUnattendedRestart>().0.clone());+ let keeps_awake = |cx: &mut gpui::VisualTestContext| host.read_with(cx, |host, _| host.keep_awake.is_some());+ host.update(cx, |host, cx| host.power_event("$onDidLockScreen", &[], cx));+ cx.run_until_parked();+ assert!(keeps_awake(cx));+ host.update(cx, |host, cx| host.power_event("$onDidUnlockScreen", &[], cx));+ assert!(!keeps_awake(cx));+ }+/// unattendedRestart.test.ts "aggregates blockers, treats failures as blockers and forgets disposed participants",/// without the failing participant: the port's checks are calls that cannot fail or time out.#[test]diff --git a/native/crates/app/src/workbench/update.rs b/native/crates/app/src/workbench/update.rsindex 2b450545727..3d42f21f555 100644--- a/native/crates/app/src/workbench/update.rs+++ b/native/crates/app/src/workbench/update.rs@@ -18,6 +18,7 @@ impl Workbench {self.update_state = service.read(cx).state().clone();self.update_title_bar_state_changed(window, cx);cx.subscribe_in(&service, window, |workbench, _, state, window, cx| workbench.update_state_changed(state, window, cx)).detach();+ self.start_unattended_restart(window, cx);for id in ["update.check", "update.checkForUpdate"] {self.commands.register(id, |_, _, _, cx| {crate::update::service(cx).update(cx, |service, cx| service.check_for_updates(true, cx));@@ -134,7 +135,7 @@ impl Workbench {/// `quitAndInstall`: Restarting, then every window's shutdown; a veto puts Ready back. The helper starts when the/// app quits (`UpdateService::install_on_quit`).-fn quit_and_install(window: &mut Window, cx: &mut Context<Workbench>) {+pub(super) fn quit_and_install(window: &mut Window, cx: &mut Context<Workbench>) {let service = crate::update::service(cx);if !service.update(cx, |service, cx| service.begin_restart(cx)) {return;diff --git a/port/ledger.md b/port/ledger.mdindex b2cdb488a34..6d439d2605b 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 | ported | [3 S] workbench/language_detection.rs: 4 s after typing a Python snippet into a new untitled editor (Cmd+N in a ui-pair run, hc) the port's language entry shows Python, the reference's still Plain Text, also after 12 s; not yet known whether the reference build lacks the detection model or the port detects where upstream does not | 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 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` or update/unattended_restart.rs yet: the scheduler is not wired to the power events, its timers, the keep-awake `powerSaveBlocker`, the update service's state and the windows' readiness, and `getWindowBlockers`, `hasArgumentsLostOnRelaunch`, the remembered failed update (`update.unattendedRestartFailedUpdate`), `quitAndInstall` with `unattended`, `relaunchInBackground` and its cancellation token, 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); update/unattended_restart.rs: unattendedRestartScheduler.ts's decisions (keep awake from the lock, restart once locked a minute, retry every minute, veto, a newer update postponing, battery and thermal pressure, resume restarting the clock, the update not installed last time) over injected time: cargo test -p app update::unattended_restart (13 of unattendedRestartScheduler.test.ts's cases, without the telemetry outcomes the port does not send); 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 the scheduler's app-level blockers are not ported: `getWindowBlockers` (`window.none` aside), `hasArgumentsLostOnRelaunch`, `app.dialogOpen`, `app.launchedFromCli`, and the remembered pending restart and failed update (`update.unattendedRestart`, `update.unattendedRestartFailedUpdate`) <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); update/unattended_restart.rs: unattendedRestartScheduler.ts's decisions (keep awake from the lock, restart once locked a minute, retry every minute, veto, a newer update postponing, battery and thermal pressure, resume restarting the clock, the update not installed last time) over injected time: cargo test -p app update::unattended_restart (13 of unattendedRestartScheduler.test.ts's cases, without the telemetry outcomes the port does not send); workbench/unattended_restart.rs `UnattendedRestart`: the scheduler's host on macOS (power events, window blur, update state, timers, the `prevent-app-suspension` blocker, `quitAndInstall` from a window): cargo test -p app a_locked_screen_keeps_the_machine_awake; windows_state.rs `setNextExactRestore`/`takeExactRestore` (minimized windows, hidden app): cargo test -p app windows_state; 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` |