zed: Add ability to restore last session w/ multiple windows (#14965)
This adds the ability for Zed to restore multiple windows after
restarting. It's now the default behavior.
Release Notes:
- Added ability to restore all windows that were open when Zed was quit.
Previously only the last used workspace was restored. This is now the
default behavior. To get back the old behavior, add the following to
your settings: `{"restore_on_startup": "last_workspace"}` (Part of
[#4985](https://github.com/zed-industries/zed/issues/4985) and
[#4683](https://github.com/zed-industries/zed/issues/4683))
Demo:
https://github.com/user-attachments/assets/57a375ec-0c6a-4724-97c4-3fea8f18bc2d
---------
Co-authored-by: Nathan <nathan@zed.dev>
This commit is contained in:
+57
-19
@@ -28,6 +28,7 @@ use assets::Assets;
|
||||
use node_runtime::RealNodeRuntime;
|
||||
use parking_lot::Mutex;
|
||||
use release_channel::{AppCommitSha, AppVersion};
|
||||
use session::Session;
|
||||
use settings::{handle_settings_file_changes, watch_config_file, Settings, SettingsStore};
|
||||
use simplelog::ConfigBuilder;
|
||||
use smol::process::Command;
|
||||
@@ -307,10 +308,15 @@ fn main() {
|
||||
.block(installation_id())
|
||||
.ok()
|
||||
.unzip();
|
||||
let session_id = Uuid::new_v4().to_string();
|
||||
|
||||
let session = app.background_executor().block(Session::new());
|
||||
|
||||
let app_version = AppVersion::init(env!("CARGO_PKG_VERSION"));
|
||||
reliability::init_panic_hook(installation_id.clone(), app_version, session_id.clone());
|
||||
reliability::init_panic_hook(
|
||||
installation_id.clone(),
|
||||
app_version,
|
||||
session.id().to_owned(),
|
||||
);
|
||||
|
||||
let (open_listener, mut open_rx) = OpenListener::new();
|
||||
|
||||
@@ -422,7 +428,7 @@ fn main() {
|
||||
client::init(&client, cx);
|
||||
language::init(cx);
|
||||
let telemetry = client.telemetry();
|
||||
telemetry.start(installation_id.clone(), session_id, cx);
|
||||
telemetry.start(installation_id.clone(), session.id().to_owned(), cx);
|
||||
telemetry.report_app_event(
|
||||
match existing_installation_id_found {
|
||||
Some(false) => "first open",
|
||||
@@ -438,6 +444,7 @@ fn main() {
|
||||
build_window_options,
|
||||
workspace_store,
|
||||
node_runtime: node_runtime.clone(),
|
||||
session,
|
||||
});
|
||||
AppState::set_global(Arc::downgrade(&app_state), cx);
|
||||
|
||||
@@ -657,23 +664,18 @@ async fn restore_or_create_workspace(
|
||||
app_state: Arc<AppState>,
|
||||
cx: &mut AsyncAppContext,
|
||||
) -> Result<()> {
|
||||
let restore_behaviour = cx.update(|cx| WorkspaceSettings::get(None, cx).restore_on_startup)?;
|
||||
let location = match restore_behaviour {
|
||||
workspace::RestoreOnStartupBehaviour::LastWorkspace => {
|
||||
workspace::last_opened_workspace_paths().await
|
||||
if let Some(locations) = restorable_workspace_locations(cx, &app_state).await {
|
||||
for location in locations {
|
||||
cx.update(|cx| {
|
||||
workspace::open_paths(
|
||||
location.paths().as_ref(),
|
||||
app_state.clone(),
|
||||
workspace::OpenOptions::default(),
|
||||
cx,
|
||||
)
|
||||
})?
|
||||
.await?;
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(location) = location {
|
||||
cx.update(|cx| {
|
||||
workspace::open_paths(
|
||||
location.paths().as_ref(),
|
||||
app_state,
|
||||
workspace::OpenOptions::default(),
|
||||
cx,
|
||||
)
|
||||
})?
|
||||
.await?;
|
||||
} else if matches!(KEY_VALUE_STORE.read_kvp(FIRST_OPEN), Ok(None)) {
|
||||
cx.update(|cx| show_welcome_view(app_state, cx))?.await?;
|
||||
} else {
|
||||
@@ -688,6 +690,42 @@ async fn restore_or_create_workspace(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn restorable_workspace_locations(
|
||||
cx: &mut AsyncAppContext,
|
||||
app_state: &Arc<AppState>,
|
||||
) -> Option<Vec<workspace::LocalPaths>> {
|
||||
let mut restore_behaviour = cx
|
||||
.update(|cx| WorkspaceSettings::get(None, cx).restore_on_startup)
|
||||
.ok()?;
|
||||
|
||||
let last_session_id = app_state.session.last_session_id();
|
||||
if last_session_id.is_none()
|
||||
&& matches!(
|
||||
restore_behaviour,
|
||||
workspace::RestoreOnStartupBehaviour::LastSession
|
||||
)
|
||||
{
|
||||
restore_behaviour = workspace::RestoreOnStartupBehaviour::LastWorkspace;
|
||||
}
|
||||
|
||||
match restore_behaviour {
|
||||
workspace::RestoreOnStartupBehaviour::LastWorkspace => {
|
||||
workspace::last_opened_workspace_paths()
|
||||
.await
|
||||
.map(|location| vec![location])
|
||||
}
|
||||
workspace::RestoreOnStartupBehaviour::LastSession => {
|
||||
if let Some(last_session_id) = last_session_id {
|
||||
workspace::last_session_workspace_locations(last_session_id)
|
||||
.filter(|locations| !locations.is_empty())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn init_paths() -> anyhow::Result<()> {
|
||||
for path in [
|
||||
paths::config_dir(),
|
||||
|
||||
@@ -5,6 +5,7 @@ pub(crate) mod linux_prompts;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub(crate) mod only_instance;
|
||||
mod open_listener;
|
||||
pub(crate) mod session;
|
||||
mod ssh_connection_modal;
|
||||
|
||||
pub use app_menus::*;
|
||||
@@ -3404,7 +3405,7 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
|
||||
pub(crate) fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
|
||||
init_test_with_state(cx, cx.update(|cx| AppState::test(cx)))
|
||||
}
|
||||
|
||||
|
||||
+352
-141
@@ -1,3 +1,4 @@
|
||||
use crate::restorable_workspace_locations;
|
||||
use crate::{
|
||||
handle_open_request, init_headless, init_ui, zed::ssh_connection_modal::SshConnectionModal,
|
||||
};
|
||||
@@ -528,149 +529,359 @@ pub async fn handle_cli_connection(
|
||||
return;
|
||||
}
|
||||
|
||||
let paths = if paths.is_empty() {
|
||||
if open_new_workspace == Some(true) {
|
||||
vec![]
|
||||
} else {
|
||||
workspace::last_opened_workspace_paths()
|
||||
.await
|
||||
.map(|location| {
|
||||
location
|
||||
.paths()
|
||||
.iter()
|
||||
.map(|path| PathLikeWithPosition {
|
||||
path_like: path.clone(),
|
||||
row: None,
|
||||
column: None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
} else {
|
||||
paths
|
||||
.into_iter()
|
||||
.map(|path_with_position_string| {
|
||||
PathLikeWithPosition::parse_str(
|
||||
&path_with_position_string,
|
||||
|_, path_str| {
|
||||
Ok::<_, std::convert::Infallible>(
|
||||
Path::new(path_str).to_path_buf(),
|
||||
)
|
||||
},
|
||||
)
|
||||
.expect("Infallible")
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let open_workspace_result = open_workspaces(
|
||||
paths,
|
||||
open_new_workspace,
|
||||
&responses,
|
||||
wait,
|
||||
app_state.clone(),
|
||||
&mut cx,
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut errored = false;
|
||||
|
||||
if !paths.is_empty() {
|
||||
match open_paths_with_positions(
|
||||
&paths,
|
||||
app_state,
|
||||
workspace::OpenOptions {
|
||||
open_new_workspace,
|
||||
..Default::default()
|
||||
},
|
||||
&mut cx,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((workspace, items)) => {
|
||||
let mut item_release_futures = Vec::new();
|
||||
|
||||
for (item, path) in items.into_iter().zip(&paths) {
|
||||
match item {
|
||||
Some(Ok(item)) => {
|
||||
cx.update(|cx| {
|
||||
let released = oneshot::channel();
|
||||
item.on_release(
|
||||
cx,
|
||||
Box::new(move |_| {
|
||||
let _ = released.0.send(());
|
||||
}),
|
||||
)
|
||||
.detach();
|
||||
item_release_futures.push(released.1);
|
||||
})
|
||||
.log_err();
|
||||
}
|
||||
Some(Err(err)) => {
|
||||
responses
|
||||
.send(CliResponse::Stderr {
|
||||
message: format!("error opening {path:?}: {err}"),
|
||||
})
|
||||
.log_err();
|
||||
errored = true;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
if wait {
|
||||
let background = cx.background_executor().clone();
|
||||
let wait = async move {
|
||||
if paths.is_empty() {
|
||||
let (done_tx, done_rx) = oneshot::channel();
|
||||
let _subscription = workspace.update(&mut cx, |_, cx| {
|
||||
cx.on_release(move |_, _, _| {
|
||||
let _ = done_tx.send(());
|
||||
})
|
||||
});
|
||||
let _ = done_rx.await;
|
||||
} else {
|
||||
let _ = futures::future::try_join_all(item_release_futures)
|
||||
.await;
|
||||
};
|
||||
}
|
||||
.fuse();
|
||||
futures::pin_mut!(wait);
|
||||
|
||||
loop {
|
||||
// Repeatedly check if CLI is still open to avoid wasting resources
|
||||
// waiting for files or workspaces to close.
|
||||
let mut timer = background.timer(Duration::from_secs(1)).fuse();
|
||||
futures::select_biased! {
|
||||
_ = wait => break,
|
||||
_ = timer => {
|
||||
if responses.send(CliResponse::Ping).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
errored = true;
|
||||
responses
|
||||
.send(CliResponse::Stderr {
|
||||
message: format!("error opening {paths:?}: {error}"),
|
||||
})
|
||||
.log_err();
|
||||
}
|
||||
}
|
||||
} else if matches!(KEY_VALUE_STORE.read_kvp(FIRST_OPEN), Ok(None)) {
|
||||
cx.update(|cx| show_welcome_view(app_state, cx).detach())
|
||||
.log_err();
|
||||
} else {
|
||||
cx.update(|cx| {
|
||||
workspace::open_new(app_state, cx, |workspace, cx| {
|
||||
Editor::new_file(workspace, &Default::default(), cx)
|
||||
})
|
||||
.detach();
|
||||
})
|
||||
.log_err();
|
||||
}
|
||||
|
||||
responses
|
||||
.send(CliResponse::Exit {
|
||||
status: i32::from(errored),
|
||||
})
|
||||
.log_err();
|
||||
let status = if open_workspace_result.is_err() { 1 } else { 0 };
|
||||
responses.send(CliResponse::Exit { status }).log_err();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn open_workspaces(
|
||||
paths: Vec<String>,
|
||||
open_new_workspace: Option<bool>,
|
||||
responses: &IpcSender<CliResponse>,
|
||||
wait: bool,
|
||||
app_state: Arc<AppState>,
|
||||
mut cx: &mut AsyncAppContext,
|
||||
) -> Result<()> {
|
||||
let grouped_paths = if paths.is_empty() {
|
||||
// If no paths are provided, restore from previous workspaces unless a new workspace is requested with -n
|
||||
if open_new_workspace == Some(true) {
|
||||
Vec::new()
|
||||
} else {
|
||||
let locations = restorable_workspace_locations(&mut cx, &app_state).await;
|
||||
locations
|
||||
.into_iter()
|
||||
.flat_map(|locations| {
|
||||
locations
|
||||
.into_iter()
|
||||
.map(|location| {
|
||||
location
|
||||
.paths()
|
||||
.iter()
|
||||
.map(|path| PathLikeWithPosition {
|
||||
path_like: path.clone(),
|
||||
row: None,
|
||||
column: None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
} else {
|
||||
// If paths are provided, parse them (they include positions)
|
||||
let paths_with_position = paths
|
||||
.into_iter()
|
||||
.map(|path_with_position_string| {
|
||||
PathLikeWithPosition::parse_str(&path_with_position_string, |_, path_str| {
|
||||
Ok::<_, std::convert::Infallible>(Path::new(path_str).to_path_buf())
|
||||
})
|
||||
.expect("Infallible")
|
||||
})
|
||||
.collect();
|
||||
vec![paths_with_position]
|
||||
};
|
||||
|
||||
if grouped_paths.is_empty() {
|
||||
// If we have no paths to open, show the welcome screen if this is the first launch
|
||||
if matches!(KEY_VALUE_STORE.read_kvp(FIRST_OPEN), Ok(None)) {
|
||||
cx.update(|cx| show_welcome_view(app_state, cx).detach())
|
||||
.log_err();
|
||||
}
|
||||
// If not the first launch, show an empty window with empty editor
|
||||
else {
|
||||
cx.update(|cx| {
|
||||
workspace::open_new(app_state, cx, |workspace, cx| {
|
||||
Editor::new_file(workspace, &Default::default(), cx)
|
||||
})
|
||||
.detach();
|
||||
})
|
||||
.log_err();
|
||||
}
|
||||
} else {
|
||||
// If there are paths to open, open a workspace for each grouping of paths
|
||||
let mut errored = false;
|
||||
|
||||
for workspace_paths in grouped_paths {
|
||||
let workspace_failed_to_open = open_workspace(
|
||||
workspace_paths,
|
||||
open_new_workspace,
|
||||
wait,
|
||||
responses,
|
||||
&app_state,
|
||||
&mut cx,
|
||||
)
|
||||
.await;
|
||||
|
||||
if workspace_failed_to_open {
|
||||
errored = true
|
||||
}
|
||||
}
|
||||
|
||||
if errored {
|
||||
return Err(anyhow!("failed to open a workspace"));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn open_workspace(
|
||||
workspace_paths: Vec<PathLikeWithPosition<PathBuf>>,
|
||||
open_new_workspace: Option<bool>,
|
||||
wait: bool,
|
||||
responses: &IpcSender<CliResponse>,
|
||||
app_state: &Arc<AppState>,
|
||||
cx: &mut AsyncAppContext,
|
||||
) -> bool {
|
||||
let mut errored = false;
|
||||
|
||||
match open_paths_with_positions(
|
||||
&workspace_paths,
|
||||
app_state.clone(),
|
||||
workspace::OpenOptions {
|
||||
open_new_workspace,
|
||||
..Default::default()
|
||||
},
|
||||
cx,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((workspace, items)) => {
|
||||
let mut item_release_futures = Vec::new();
|
||||
|
||||
for (item, path) in items.into_iter().zip(&workspace_paths) {
|
||||
match item {
|
||||
Some(Ok(item)) => {
|
||||
cx.update(|cx| {
|
||||
let released = oneshot::channel();
|
||||
item.on_release(
|
||||
cx,
|
||||
Box::new(move |_| {
|
||||
let _ = released.0.send(());
|
||||
}),
|
||||
)
|
||||
.detach();
|
||||
item_release_futures.push(released.1);
|
||||
})
|
||||
.log_err();
|
||||
}
|
||||
Some(Err(err)) => {
|
||||
responses
|
||||
.send(CliResponse::Stderr {
|
||||
message: format!("error opening {path:?}: {err}"),
|
||||
})
|
||||
.log_err();
|
||||
errored = true;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
if wait {
|
||||
let background = cx.background_executor().clone();
|
||||
let wait = async move {
|
||||
if workspace_paths.is_empty() {
|
||||
let (done_tx, done_rx) = oneshot::channel();
|
||||
let _subscription = workspace.update(cx, |_, cx| {
|
||||
cx.on_release(move |_, _, _| {
|
||||
let _ = done_tx.send(());
|
||||
})
|
||||
});
|
||||
let _ = done_rx.await;
|
||||
} else {
|
||||
let _ = futures::future::try_join_all(item_release_futures).await;
|
||||
};
|
||||
}
|
||||
.fuse();
|
||||
|
||||
futures::pin_mut!(wait);
|
||||
|
||||
loop {
|
||||
// Repeatedly check if CLI is still open to avoid wasting resources
|
||||
// waiting for files or workspaces to close.
|
||||
let mut timer = background.timer(Duration::from_secs(1)).fuse();
|
||||
futures::select_biased! {
|
||||
_ = wait => break,
|
||||
_ = timer => {
|
||||
if responses.send(CliResponse::Ping).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
errored = true;
|
||||
responses
|
||||
.send(CliResponse::Stderr {
|
||||
message: format!("error opening {workspace_paths:?}: {error}"),
|
||||
})
|
||||
.log_err();
|
||||
}
|
||||
}
|
||||
errored
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
|
||||
use cli::{
|
||||
ipc::{self},
|
||||
CliResponse,
|
||||
};
|
||||
use editor::Editor;
|
||||
use gpui::TestAppContext;
|
||||
use serde_json::json;
|
||||
use util::paths::PathLikeWithPosition;
|
||||
use workspace::{AppState, Workspace};
|
||||
|
||||
use crate::zed::{open_listener::open_workspace, tests::init_test};
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_open_workspace_with_directory(cx: &mut TestAppContext) {
|
||||
let app_state = init_test(cx);
|
||||
|
||||
app_state
|
||||
.fs
|
||||
.as_fake()
|
||||
.insert_tree(
|
||||
"/root",
|
||||
json!({
|
||||
"dir1": {
|
||||
"file1.txt": "content1",
|
||||
"file2.txt": "content2",
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(cx.windows().len(), 0);
|
||||
|
||||
// First open the workspace directory
|
||||
open_workspace_file("/root/dir1", None, app_state.clone(), cx).await;
|
||||
|
||||
assert_eq!(cx.windows().len(), 1);
|
||||
let workspace = cx.windows()[0].downcast::<Workspace>().unwrap();
|
||||
workspace
|
||||
.update(cx, |workspace, cx| {
|
||||
assert!(workspace.active_item_as::<Editor>(cx).is_none())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// Now open a file inside that workspace
|
||||
open_workspace_file("/root/dir1/file1.txt", None, app_state.clone(), cx).await;
|
||||
|
||||
assert_eq!(cx.windows().len(), 1);
|
||||
workspace
|
||||
.update(cx, |workspace, cx| {
|
||||
assert!(workspace.active_item_as::<Editor>(cx).is_some());
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// Now open a file inside that workspace, but tell Zed to open a new window
|
||||
open_workspace_file("/root/dir1/file1.txt", Some(true), app_state.clone(), cx).await;
|
||||
|
||||
assert_eq!(cx.windows().len(), 2);
|
||||
|
||||
let workspace_2 = cx.windows()[1].downcast::<Workspace>().unwrap();
|
||||
workspace_2
|
||||
.update(cx, |workspace, cx| {
|
||||
assert!(workspace.active_item_as::<Editor>(cx).is_some());
|
||||
let items = workspace.items(cx).collect::<Vec<_>>();
|
||||
assert_eq!(items.len(), 1, "Workspace should have two items");
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_open_workspace_with_nonexistent_files(cx: &mut TestAppContext) {
|
||||
let app_state = init_test(cx);
|
||||
|
||||
app_state.fs.as_fake().insert_tree("/root", json!({})).await;
|
||||
|
||||
assert_eq!(cx.windows().len(), 0);
|
||||
|
||||
// Test case 1: Open a single file that does not exist yet
|
||||
open_workspace_file("/root/file5.txt", None, app_state.clone(), cx).await;
|
||||
|
||||
assert_eq!(cx.windows().len(), 1);
|
||||
let workspace_1 = cx.windows()[0].downcast::<Workspace>().unwrap();
|
||||
workspace_1
|
||||
.update(cx, |workspace, cx| {
|
||||
assert!(workspace.active_item_as::<Editor>(cx).is_some())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// Test case 2: Open a single file that does not exist yet,
|
||||
// but tell Zed to add it to the current workspace
|
||||
open_workspace_file("/root/file6.txt", Some(false), app_state.clone(), cx).await;
|
||||
|
||||
assert_eq!(cx.windows().len(), 1);
|
||||
workspace_1
|
||||
.update(cx, |workspace, cx| {
|
||||
let items = workspace.items(cx).collect::<Vec<_>>();
|
||||
assert_eq!(items.len(), 2, "Workspace should have two items");
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// Test case 3: Open a single file that does not exist yet,
|
||||
// but tell Zed to NOT add it to the current workspace
|
||||
open_workspace_file("/root/file7.txt", Some(true), app_state.clone(), cx).await;
|
||||
|
||||
assert_eq!(cx.windows().len(), 2);
|
||||
let workspace_2 = cx.windows()[1].downcast::<Workspace>().unwrap();
|
||||
workspace_2
|
||||
.update(cx, |workspace, cx| {
|
||||
let items = workspace.items(cx).collect::<Vec<_>>();
|
||||
assert_eq!(items.len(), 1, "Workspace should have two items");
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn open_workspace_file(
|
||||
path: &str,
|
||||
open_new_workspace: Option<bool>,
|
||||
app_state: Arc<AppState>,
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let (response_tx, _) = ipc::channel::<CliResponse>().unwrap();
|
||||
|
||||
let path_like = PathBuf::from(path);
|
||||
let workspace_paths = vec![PathLikeWithPosition {
|
||||
path_like,
|
||||
row: None,
|
||||
column: None,
|
||||
}];
|
||||
|
||||
let errored = cx
|
||||
.spawn(|mut cx| async move {
|
||||
open_workspace(
|
||||
workspace_paths,
|
||||
open_new_workspace,
|
||||
false,
|
||||
&response_tx,
|
||||
&app_state,
|
||||
&mut cx,
|
||||
)
|
||||
.await
|
||||
})
|
||||
.await;
|
||||
|
||||
assert!(!errored);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
Reference in New Issue
Block a user