Restore the last session when Zed is started by opening a path (#65463)

Closes #4848
Closes #57305

## Summary

On Windows and Linux, starting Zed by opening a file or folder (Explorer
"Open with Zed", a file manager, `zed <path>`) skipped session
restoration.
The new session then replaced the old one, so its windows, tabs and
unsaved buffers were lost.
macOS does not have that bug: there the request arrives after the
restore has started.

Now such a start first restores the local windows of the last session,
for at most 5 seconds, then handles the request with the same code as
before.
The request's window is created last, so it ends up in front.

- **A file opened without a CLI environment** (Explorer, a file manager,
the desktop entry) becomes a tab in its project's window, or in the
front window, as when Zed is already running.
  A file that has a saved window of its own reopens that window instead.
- **Any other path request** (a file from a terminal, a folder, `-n`,
`-a`, `-r`, `--diff`, `--dev-container`) opens in its own window, as
before.
A saved window with the same folders (a folder inside another one is
folded into it), or of the same repository, is left to the request and
kept out of the sidebar of the other restored windows.
- Remote requests, `zed://` links, channel links and `--wait` requests
are handled as before, without restoring.

Two changes in `workspace` come with it:

- A window restored by such a start can still be loading its tabs while
the user works in it or quits.
Until it has finished, saving it writes the layout it is restoring plus
a pane with what was opened in it meanwhile, and tabs opened in it are
kept when the saved tabs arrive.
  Every other restore takes the same code path as before.
- `Workspace::open_paths` returned the opened items sorted by path, not
in the order the paths were given, so several file links with positions
opened into one existing window could each get another file's line.
  Such a start now reaches that code, so it is fixed here.

Known limits:

- The requested path appears after the session's windows, at most 5
seconds later, and requests that arrive during startup wait for it.
- A saved window that has not opened within the 5 seconds is not
restored by this start; a bare `zed` in the same run restores it.
- A path start does not restore remote windows.
- A window still loading after the 5 seconds finishes behind the
request's window.
Until then its saved state wins over what is done in it: a saved unsaved
draft replaces newer text of the same file (typed, or saved to disk), a
bookmark or breakpoint removed from a saved row comes back, dock changes
are not saved, and `--wait` on a file among its saved tabs returns when
the saved tab takes its place.
A new tab whose id equals a saved tab's id replaces that tab in the
saved layout.

## Testing

50 new tests.
The startup tests run each kind of request against a saved session:
files joining a restored window (also file links with positions), files
and folders getting their own window with the CLI environment, `-n` and
`-r`, saved windows and sidebar projects left to the request (also
through a symlink, with a nested folder, and for a linked worktree),
remote windows, bare CLI, link and `--wait` requests, and the 5-second
limit ending in each phase.
The restore tests cover a window that is still loading: quitting keeps
its saved tabs, docks, bookmarks and breakpoints together with what was
added meanwhile; a tab opened in it survives, a file among the saved
tabs gets one tab, pinned tabs stay in place, the tab in use stays
selected; an ordinary start is unchanged.

Manual check:

1. Set `"restore_on_startup": "last_session"`.
2. Open a folder with two tabs and an untitled buffer with text, then
quit.
3. With Zed closed, open a file inside that folder from the file
manager: the folder window comes back with its tabs and the untitled
text, and the file is a new tab.
4. Quit and run `zed /another/folder` in a terminal: that folder is in
front and the first window is restored behind it.

## Self-review

- [ ] I've reviewed my diff for quality, security, reliability, and
performance.
- [x] UI changes follow the
[checklist](https://zed.dev/docs/development/ui-checklist). (No UI
changes.)
- [x] Tests cover the new or changed behavior.

Release Notes:

- Fixed opening a file or folder while Zed is closed not restoring the
last session on Windows and Linux, which caused previously open windows,
tabs and unsaved buffers to be lost.

Co-authored-by: Kirill Bulatov <kirill@zed.dev>
This commit is contained in:
Verlaire
2026-11-12 00:02:18 +00:00
committed by GitHub
parent b6ff193ba6
commit f99c53f4f6
7 changed files with 3234 additions and 190 deletions
+5
View File
@@ -66,6 +66,11 @@ impl ProjectEnvironment {
}
}
#[cfg(any(test, feature = "test-support"))]
pub fn inherited_cli_environment(&self) -> Option<&HashMap<String, String>> {
self.cli_environment.as_ref()
}
/// Returns the inherited CLI environment, if this project was opened from the Zed CLI.
pub(crate) fn get_cli_environment(&self) -> Option<HashMap<String, String>> {
if cfg!(any(test, feature = "test-support")) {
+381 -3
View File
@@ -1157,6 +1157,10 @@ impl WorkspaceDb {
self.workspace_for_roots_internal(worktree_roots, None)
}
pub fn has_workspace_for_roots<P: AsRef<Path>>(&self, worktree_roots: &[P]) -> bool {
self.workspace_for_roots(worktree_roots).is_some()
}
pub(crate) fn remote_workspace_for_roots<P: AsRef<Path>>(
&self,
worktree_roots: &[P],
@@ -3017,10 +3021,11 @@ mod tests {
use crate::ProjectGroupKey;
use crate::RemovalIntent;
use crate::{
item::test::TestItem,
multi_workspace::MultiWorkspace,
persistence::{
model::{
SerializedItem, SerializedPane, SerializedPaneGroup, SerializedWorkspace,
DockData, SerializedItem, SerializedPane, SerializedPaneGroup, SerializedWorkspace,
SessionWorkspace,
},
read_multi_workspace_state,
@@ -3029,11 +3034,16 @@ mod tests {
use gpui::TaskExt;
use gpui::AppContext as _;
use language::Point;
use pretty_assertions::assert_eq;
use project::Project;
use project::{
Project,
debugger::breakpoint_store::{self, BreakpointEditAction, BreakpointWithPosition},
};
use remote::SshConnectionOptions;
use serde_json::json;
use std::{thread, time::Duration};
use std::{cell::RefCell, rc::Rc, thread, time::Duration};
use util::path;
/// Creates a unique directory in a FakeFs, returning the path.
/// Uses a UUID suffix to avoid collisions with other tests sharing the global DB.
@@ -5476,6 +5486,374 @@ mod tests {
);
}
#[gpui::test]
async fn test_restoring_workspace_saves_what_it_restores_and_what_was_added(
cx: &mut gpui::TestAppContext,
) {
crate::tests::init_test(cx);
cx.update(crate::register_serializable_item::<TestItem>);
let fs = fs::FakeFs::new(cx.executor());
fs.insert_tree(
path!("/project"),
json!({ "saved.rs": "one\ntwo\n", "added.rs": "one\ntwo\n" }),
)
.await;
let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
let (multi_workspace, cx) =
cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
let workspace =
multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone());
let db = cx.update(|_, cx| WorkspaceDb::global(cx));
let workspace_id = db.next_id().await.unwrap();
workspace.update(cx, |workspace, _| workspace.set_database_id(workspace_id));
let added_item = cx.new(TestItem::new);
let added_item_id = added_item.entity_id().as_u64();
workspace.update_in(cx, |workspace, window, cx| {
workspace.add_item_to_active_pane(Box::new(added_item.clone()), None, true, window, cx);
});
let buffer = project
.update(cx, |project, cx| {
project.open_local_buffer(path!("/project/added.rs"), cx)
})
.await
.unwrap();
project.update(cx, |project, cx| {
let position = buffer.read(cx).anchor_before(Point::new(1, 0));
project.bookmark_store().update(cx, |bookmark_store, cx| {
bookmark_store.toggle_bookmark(buffer.clone(), position, String::new(), cx);
});
project
.breakpoint_store()
.update(cx, |breakpoint_store, cx| {
breakpoint_store.toggle_breakpoint(
buffer.clone(),
BreakpointWithPosition {
position,
bp: breakpoint_store::Breakpoint::new_standard(),
},
BreakpointEditAction::Toggle,
cx,
);
});
});
let saved_path = Arc::<Path>::from(Path::new(path!("/project/saved.rs")));
let added_path = Arc::<Path>::from(Path::new(path!("/project/added.rs")));
let bookmark = |row| SerializedBookmark {
row,
label: String::new(),
};
let breakpoint = |row, path: &Arc<Path>| SourceBreakpoint {
row,
path: path.clone(),
message: None,
condition: None,
hit_condition: None,
state: BreakpointState::Enabled,
};
let saved_docks = DockStructure {
left: DockData {
visible: true,
active_panel: Some("SavedPanel".to_owned()),
zoom: false,
},
..Default::default()
};
let restoring_from = SerializedWorkspace {
id: workspace_id,
paths: PathList::new(&[path!("/project")]),
identity_paths: None,
location: SerializedWorkspaceLocation::Local,
center_group: SerializedPaneGroup::Pane(SerializedPane::new(
vec![
SerializedItem::new("Terminal", added_item_id, true, false),
SerializedItem::new("TestItem", added_item_id + 1, false, false),
],
true,
1,
)),
window_bounds: Default::default(),
display: Default::default(),
docks: saved_docks.clone(),
centered_layout: false,
bookmarks: BTreeMap::from_iter([(saved_path.clone(), vec![bookmark(0)])]),
breakpoints: BTreeMap::from_iter([(
saved_path.clone(),
vec![breakpoint(0, &saved_path)],
)]),
session_id: None,
window_id: None,
user_toolchains: Default::default(),
recent_navigation_history: Default::default(),
path_style: PathStyle::local(),
};
workspace.update(cx, |workspace, _| {
workspace.restoring_workspace.set(true);
workspace.restoring_from.replace(Some(restoring_from));
});
multi_workspace
.update_in(cx, |multi_workspace, window, cx| {
multi_workspace.workspace().update(cx, |workspace, cx| {
workspace.flush_serialization(window, cx)
})
})
.await;
let both_breakpoints = BTreeMap::from_iter([
(added_path.clone(), vec![breakpoint(1, &added_path)]),
(saved_path.clone(), vec![breakpoint(0, &saved_path)]),
]);
let saved = db.workspace_for_id(workspace_id).unwrap();
assert_eq!(
(
saved.center_group,
saved.docks,
saved.bookmarks,
saved.breakpoints
),
(
SerializedPaneGroup::Group {
axis: SerializedAxis(Axis::Horizontal),
children: vec![
SerializedPaneGroup::Pane(SerializedPane::new(
vec![SerializedItem::new(
"TestItem",
added_item_id + 1,
false,
false
)],
false,
0,
)),
SerializedPaneGroup::Pane(SerializedPane::new(
vec![SerializedItem::new("TestItem", added_item_id, true, false)],
true,
0,
)),
],
flexes: None,
},
saved_docks,
BTreeMap::from_iter([
(added_path.clone(), vec![bookmark(1)]),
(saved_path.clone(), vec![bookmark(0)]),
]),
both_breakpoints.clone(),
)
);
workspace.update(cx, |workspace, _| workspace.restoring_workspace.set(false));
multi_workspace
.update_in(cx, |multi_workspace, window, cx| {
multi_workspace.workspace().update(cx, |workspace, cx| {
workspace.flush_serialization(window, cx)
})
})
.await;
let saved = db.workspace_for_id(workspace_id).unwrap();
assert_eq!(
(
saved.center_group,
saved.docks,
saved.bookmarks,
saved.breakpoints
),
(
SerializedPaneGroup::Pane(SerializedPane::new(
vec![SerializedItem::new("TestItem", added_item_id, true, false)],
true,
0,
)),
DockStructure::default(),
BTreeMap::from_iter([(added_path.clone(), vec![bookmark(1)])]),
both_breakpoints,
)
);
}
#[test]
fn test_saved_layout_is_unchanged_when_nothing_was_opened_while_restoring() {
let saved = SerializedPaneGroup::Pane(SerializedPane::new(
vec![SerializedItem::new("Terminal", 5, true, false)],
true,
1,
));
let nothing_opened = SerializedPaneGroup::Pane(SerializedPane::new(Vec::new(), true, 0));
assert_eq!(
saved
.clone()
.with_panes_opened_while_restoring(nothing_opened),
saved
);
}
#[gpui::test]
async fn test_restoring_workspace_keeps_its_saved_breakpoints_until_they_are_loaded(
cx: &mut gpui::TestAppContext,
) {
crate::tests::init_test(cx);
let fs = fs::FakeFs::new(cx.executor());
fs.insert_tree(path!("/project"), json!({ "saved.rs": "one\ntwo\n" }))
.await;
let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await;
let (multi_workspace, cx) =
cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
let workspace =
multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone());
let db = cx.update(|_, cx| WorkspaceDb::global(cx));
let workspace_id = db.next_id().await.unwrap();
workspace.update(cx, |workspace, _| workspace.set_database_id(workspace_id));
let saved_path = Arc::<Path>::from(Path::new(path!("/project/saved.rs")));
let saved_breakpoints = BTreeMap::from_iter([(
saved_path.clone(),
vec![SourceBreakpoint {
row: 1,
path: saved_path.clone(),
message: None,
condition: None,
hit_condition: None,
state: BreakpointState::Enabled,
}],
)]);
let restoring_from = SerializedWorkspace {
id: workspace_id,
paths: PathList::new(&[path!("/project")]),
identity_paths: None,
location: SerializedWorkspaceLocation::Local,
center_group: Default::default(),
window_bounds: Default::default(),
display: Default::default(),
docks: Default::default(),
centered_layout: false,
bookmarks: Default::default(),
breakpoints: saved_breakpoints.clone(),
session_id: None,
window_id: None,
user_toolchains: Default::default(),
recent_navigation_history: Default::default(),
path_style: PathStyle::local(),
};
let breakpoints_when_the_tabs_were_in_place = Rc::new(RefCell::new(None));
let _tabs_in_place = cx.update(|_, cx| {
cx.observe(&workspace, {
let breakpoints_when_the_tabs_were_in_place =
breakpoints_when_the_tabs_were_in_place.clone();
move |workspace, cx| {
let workspace = workspace.read(cx);
if !workspace.is_restoring()
&& breakpoints_when_the_tabs_were_in_place.borrow().is_none()
{
let restoring_from = workspace.restoring_from.borrow();
breakpoints_when_the_tabs_were_in_place.replace(Some(
restoring_from
.as_ref()
.map(|restoring_from| restoring_from.breakpoints.clone()),
));
}
}
})
});
workspace.update(cx, |workspace, _| {
workspace.restoring_workspace.set(true);
workspace
.restoring_from
.replace(Some(restoring_from.clone()));
});
workspace
.update_in(cx, |_, window, cx| {
crate::Workspace::load_workspace(restoring_from, Vec::new(), window, cx)
})
.await
.unwrap();
let loaded_breakpoints = project.read_with(cx, |project, cx| {
project
.breakpoint_store()
.read(cx)
.all_source_breakpoints(cx)
});
let still_restoring_from = workspace.read_with(cx, |workspace, _| {
workspace.restoring_from.borrow().is_some()
});
assert_eq!(
(
breakpoints_when_the_tabs_were_in_place.take(),
loaded_breakpoints,
still_restoring_from,
),
(
Some(Some(saved_breakpoints.clone())),
saved_breakpoints,
false
)
);
}
#[gpui::test]
async fn test_workspace_whose_restore_is_cancelled_is_no_longer_restoring(
cx: &mut gpui::TestAppContext,
) {
crate::tests::init_test(cx);
let fs = fs::FakeFs::new(cx.executor());
let project = Project::test(fs.clone(), [], cx).await;
let (multi_workspace, cx) =
cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
let workspace =
multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone());
let db = cx.update(|_, cx| WorkspaceDb::global(cx));
let workspace_id = db.next_id().await.unwrap();
workspace.update(cx, |workspace, _| {
workspace.set_database_id(workspace_id);
workspace.keeps_saved_state_while_restoring = true;
});
let restoring_from = SerializedWorkspace {
id: workspace_id,
paths: PathList::default(),
identity_paths: None,
location: SerializedWorkspaceLocation::Local,
center_group: Default::default(),
window_bounds: Default::default(),
display: Default::default(),
docks: Default::default(),
centered_layout: false,
bookmarks: Default::default(),
breakpoints: Default::default(),
session_id: None,
window_id: None,
user_toolchains: Default::default(),
recent_navigation_history: Default::default(),
path_style: PathStyle::local(),
};
let restoring_state = |cx: &mut gpui::VisualTestContext| {
workspace.read_with(cx, |workspace, _| {
(
workspace.is_restoring(),
workspace.restoring_from.borrow().is_some(),
)
})
};
let restore = workspace.update_in(cx, |workspace, window, cx| {
crate::open_items(workspace, Some(restoring_from), Vec::new(), window, cx)
});
let while_restoring = restoring_state(cx);
drop(restore);
cx.run_until_parked();
assert_eq!(
(while_restoring, restoring_state(cx)),
((true, true), (false, false))
);
}
#[gpui::test]
async fn test_pending_serialization_flushed_on_shutdown(cx: &mut gpui::TestAppContext) {
crate::tests::init_test(cx);
+59 -2
View File
@@ -5,12 +5,12 @@ use crate::{
};
use anyhow::{Context, Result};
use async_recursion::async_recursion;
use collections::IndexSet;
use collections::{HashSet, IndexSet};
use db::sqlez::{
bindable::{Bind, Column, StaticColumnCount},
statement::Statement,
};
use gpui::{AsyncWindowContext, Entity, WeakEntity, WindowId};
use gpui::{AsyncWindowContext, Axis, Entity, WeakEntity, WindowId};
use language::{Toolchain, ToolchainScope};
use project::{
@@ -242,6 +242,63 @@ pub(crate) enum SerializedPaneGroup {
Pane(SerializedPane),
}
impl SerializedPaneGroup {
pub(crate) fn with_panes_opened_while_restoring(mut self, mut opened: Self) -> Self {
let mut opened_item_ids = HashSet::default();
let mut opened_pane_is_active = false;
opened.for_each_pane(&mut |pane| {
opened_item_ids.extend(pane.children.iter().map(|item| item.item_id));
opened_pane_is_active |= pane.active;
});
if opened_item_ids.is_empty() {
return self;
}
self.for_each_pane(&mut |pane| {
let replaced_pinned_items = pane
.children
.iter()
.take(pane.pinned_count)
.filter(|item| opened_item_ids.contains(&item.item_id))
.count();
pane.children
.retain(|item| !opened_item_ids.contains(&item.item_id));
pane.pinned_count -= replaced_pinned_items;
pane.active &= !opened_pane_is_active;
});
Self::Group {
axis: SerializedAxis(Axis::Horizontal),
children: vec![self, opened],
flexes: None,
}
}
fn for_each_pane(&mut self, update: &mut impl FnMut(&mut SerializedPane)) {
match self {
Self::Pane(pane) => update(pane),
Self::Group { children, .. } => {
for child in children {
child.for_each_pane(update);
}
}
}
}
}
pub(crate) fn add_saved_rows<T>(
rows: &mut BTreeMap<Arc<Path>, Vec<T>>,
saved_rows: BTreeMap<Arc<Path>, Vec<T>>,
row: impl Fn(&T) -> u32,
) {
for (path, saved_rows) in saved_rows {
let rows = rows.entry(path).or_default();
for saved_row in saved_rows {
if !rows.iter().any(|existing| row(existing) == row(&saved_row)) {
rows.push(saved_row);
}
}
}
}
#[cfg(test)]
impl Default for SerializedPaneGroup {
fn default() -> Self {
+202 -41
View File
@@ -168,7 +168,7 @@ use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::Notificat
use crate::{
persistence::{
SerializedAxis,
model::{SerializedItem, SerializedPane, SerializedPaneGroup},
model::{SerializedItem, SerializedPane, SerializedPaneGroup, add_saved_rows},
},
security_modal::SecurityModal,
};
@@ -1730,7 +1730,9 @@ pub struct Workspace {
deferred_save_items: Vec<Box<dyn WeakItemHandle>>,
persisted_recent_navigation_history: Vec<PathBuf>,
last_active_project_path: Option<ProjectPath>,
restoring_workspace: bool,
restoring_workspace: Rc<Cell<bool>>,
restoring_from: Rc<RefCell<Option<SerializedWorkspace>>>,
keeps_saved_state_while_restoring: bool,
}
impl EventEmitter<Event> for Workspace {}
@@ -2235,7 +2237,9 @@ impl Workspace {
deferred_save_items: Vec::new(),
persisted_recent_navigation_history: Vec::new(),
last_active_project_path: None,
restoring_workspace: false,
restoring_workspace: Rc::new(Cell::new(false)),
restoring_from: Rc::default(),
keeps_saved_state_while_restoring: false,
}
}
@@ -2463,8 +2467,8 @@ impl Workspace {
let all_paths_resolved = project_paths.iter().all(|(_, path)| path.is_some());
let opened_items = window
.update(cx, |_, window, cx| {
workspace.update(cx, |_workspace: &mut Workspace, cx| {
open_items(serialized_workspace, project_paths, window, cx)
workspace.update(cx, |workspace: &mut Workspace, cx| {
open_items(workspace, serialized_workspace, project_paths, window, cx)
})
})?
.await
@@ -3006,12 +3010,12 @@ impl Workspace {
}
pub fn is_restoring(&self) -> bool {
self.restoring_workspace
self.restoring_workspace.get()
}
#[cfg(any(test, feature = "test-support"))]
pub fn set_restoring_workspace(&mut self, restoring: bool) {
self.restoring_workspace = restoring;
self.restoring_workspace.set(restoring);
}
pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
@@ -3302,7 +3306,7 @@ impl Workspace {
}
fn remember_navigation_history_path(&mut self, project_path: &ProjectPath, cx: &App) -> bool {
if self.restoring_workspace {
if self.restoring_workspace.get() {
return false;
}
let Some(absolute_path) = self.project.read(cx).absolute_path(project_path, cx) else {
@@ -4250,6 +4254,8 @@ impl Workspace {
let fs = self.app_state.fs.clone();
let caller_ordered_abs_paths = abs_paths.clone();
let mut caller_indices = (0..abs_paths.len()).collect::<Vec<_>>();
caller_indices.sort_by(|left, right| abs_paths.get(*left).cmp(&abs_paths.get(*right)));
// Sort the paths to ensure we add worktrees for parents before their children.
abs_paths.sort_unstable();
@@ -4418,7 +4424,14 @@ impl Workspace {
}
}
results
let mut results_in_caller_order = (0..results.len()).map(|_| None).collect::<Vec<_>>();
for (caller_index, result) in caller_indices.into_iter().zip(results) {
if let Some(result_in_caller_order) = results_in_caller_order.get_mut(caller_index)
{
*result_in_caller_order = result;
}
}
results_in_caller_order
})
}
@@ -8043,7 +8056,6 @@ impl Workspace {
let Some(database_id) = self.database_id() else {
return Task::ready(());
};
fn build_serialized_pane_group(
pane_group: &Member,
window: &mut Window,
@@ -8079,14 +8091,14 @@ impl Workspace {
match self.workspace_location(cx) {
WorkspaceLocation::Location(location, paths) => {
let bookmarks = self.project.update(cx, |project, cx| {
let mut bookmarks = self.project.update(cx, |project, cx| {
project
.bookmark_store()
.read(cx)
.all_serialized_bookmarks(cx)
});
let breakpoints = self.project.update(cx, |project, cx| {
let mut breakpoints = self.project.update(cx, |project, cx| {
project
.breakpoint_store()
.read(cx)
@@ -8098,8 +8110,22 @@ impl Workspace {
.user_toolchains(cx)
.unwrap_or_default();
let center_group = build_serialized_pane_group(&self.center.root, window, cx);
let docks = build_serialized_docks(self, window, cx);
let mut center_group = build_serialized_pane_group(&self.center.root, window, cx);
let mut docks = build_serialized_docks(self, window, cx);
if let Some(restoring_from) = self.restoring_from.borrow().clone() {
if self.restoring_workspace.get() {
center_group = restoring_from
.center_group
.with_panes_opened_while_restoring(center_group);
docks = restoring_from.docks;
add_saved_rows(&mut bookmarks, restoring_from.bookmarks, |bookmark| {
bookmark.row
});
}
add_saved_rows(&mut breakpoints, restoring_from.breakpoints, |breakpoint| {
breakpoint.row
});
}
let default_docks = (paths.is_empty()
&& location == SerializedWorkspaceLocation::Local)
.then(|| docks.clone());
@@ -8233,7 +8259,7 @@ impl Workspace {
let recent_navigation_history = serialized_workspace.recent_navigation_history.clone();
workspace.update(cx, |workspace, _| {
workspace.persisted_recent_navigation_history = recent_navigation_history;
workspace.restoring_workspace = true;
workspace.restoring_workspace.set(true);
})?;
let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
@@ -8280,6 +8306,32 @@ impl Workspace {
// Remove old panes from workspace panes list
workspace.update_in(cx, |workspace, window, cx| {
if let Some((center_group, active_pane)) = center_group {
let item_in_use = workspace.active_item(cx);
let panes_used_while_restoring = if workspace.restoring_from.borrow().is_some()
{
workspace
.center
.panes()
.into_iter()
.cloned()
.collect::<Vec<_>>()
} else {
Vec::new()
};
let mut items_opened_while_restoring = Vec::new();
for pane in panes_used_while_restoring {
let items = pane
.read(cx)
.items()
.map(|item| item.boxed_clone())
.collect::<Vec<_>>();
pane.update(cx, |pane, cx| {
for item in &items {
pane.remove_item(item.item_id(), false, false, window, cx);
}
});
items_opened_while_restoring.extend(items);
}
workspace.remove_panes(workspace.center.root.clone(), window, cx);
// Swap workspace center group
@@ -8293,6 +8345,50 @@ impl Workspace {
} else {
workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
}
let restored_pane = workspace.active_pane.clone();
let mut kept_item_in_use = None;
for item in items_opened_while_restoring {
let was_in_use = item_in_use
.as_ref()
.is_some_and(|item_in_use| item_in_use.item_id() == item.item_id());
let restored_item = item.project_path(cx).and_then(|project_path| {
workspace.panes.iter().find_map(|pane| {
pane.read(cx).item_for_path(project_path.clone(), cx)
})
});
let kept_item = match restored_item {
Some(restored_item) => restored_item,
None => {
if let Some(serializable_item) =
item.to_serializable_item_handle(cx)
&& let Some(item_ids) = item_ids_by_kind
.get_mut(&serializable_item.serialized_item_kind())
{
item_ids.push(item.item_id().as_u64() as ItemId);
}
restored_pane.update(cx, |pane, cx| {
let end = pane.items_len();
pane.add_item_inner(
item.boxed_clone(),
false,
false,
false,
Some(end),
window,
cx,
);
});
item
}
};
if was_in_use {
kept_item_in_use = Some(kept_item);
}
}
if let Some(item) = kept_item_in_use {
workspace.activate_item(item.as_ref(), true, true, window, cx);
}
}
let docks = serialized_workspace.docks;
@@ -8309,7 +8405,7 @@ impl Workspace {
});
}
workspace.restoring_workspace = false;
workspace.restoring_workspace.set(false);
cx.notify();
})?;
@@ -8332,6 +8428,9 @@ impl Workspace {
})
})
.await;
workspace.update(cx, |workspace, _| {
workspace.restoring_from.borrow_mut().take();
})?;
// Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
// after loading the items, we might have different items and in order to avoid
@@ -9732,12 +9831,38 @@ fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
})
}
struct StopRestoringOnDrop {
restoring_workspace: Rc<Cell<bool>>,
restoring_from: Rc<RefCell<Option<SerializedWorkspace>>>,
}
impl Drop for StopRestoringOnDrop {
fn drop(&mut self) {
self.restoring_workspace.set(false);
self.restoring_from.borrow_mut().take();
}
}
fn open_items(
workspace: &mut Workspace,
serialized_workspace: Option<SerializedWorkspace>,
mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
window: &mut Window,
cx: &mut Context<Workspace>,
) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
let restoring = serialized_workspace
.as_ref()
.filter(|_| workspace.keeps_saved_state_while_restoring)
.map(|serialized_workspace| {
workspace.restoring_workspace.set(true);
workspace
.restoring_from
.replace(Some(serialized_workspace.clone()));
StopRestoringOnDrop {
restoring_workspace: workspace.restoring_workspace.clone(),
restoring_from: workspace.restoring_from.clone(),
}
});
let restored_items = serialized_workspace.map(|serialized_workspace| {
Workspace::load_workspace(
serialized_workspace,
@@ -9752,6 +9877,7 @@ fn open_items(
});
cx.spawn_in(window, async move |workspace, cx| {
let _restoring = restoring;
let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
if let Some(restored_items) = restored_items {
@@ -10729,26 +10855,9 @@ pub async fn restore_multiworkspace(
state,
} = multi_workspace;
let workspace_result = if active_workspace.paths.is_empty() {
cx.update(|cx| {
open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
})
.await
} else {
cx.update(|cx| {
Workspace::new_local(
active_workspace.paths.paths().to_vec(),
app_state.clone(),
None,
None,
None,
OpenMode::Add,
cx,
)
})
.await
.map(|result| result.window)
};
let workspace_result = cx
.update(|cx| open_saved_workspace(&active_workspace, app_state.clone(), false, cx))
.await;
let window_handle = match workspace_result {
Ok(handle) => {
@@ -10806,6 +10915,44 @@ pub async fn restore_multiworkspace(
Ok(window_handle)
}
pub fn open_saved_workspace(
saved: &SessionWorkspace,
app_state: Arc<AppState>,
keeps_saved_state_while_restoring: bool,
cx: &mut App,
) -> impl Future<Output = anyhow::Result<WindowHandle<MultiWorkspace>>> + use<> {
if saved.paths.is_empty() {
open_workspace_by_id(
saved.workspace_id,
app_state,
None,
keeps_saved_state_while_restoring,
cx,
)
.left_future()
} else {
let init = keeps_saved_state_while_restoring.then(|| {
Box::new(
|workspace: &mut Workspace, _: &mut Window, _: &mut Context<Workspace>| {
workspace.keeps_saved_state_while_restoring = true;
},
)
as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>
});
Workspace::new_local(
saved.paths.paths().to_vec(),
app_state,
None,
None,
init,
OpenMode::Add,
cx,
)
.map(|result| result.map(|result| result.window))
.right_future()
}
}
pub async fn apply_restored_multiworkspace_state(
window_handle: WindowHandle<MultiWorkspace>,
state: &MultiWorkspaceState,
@@ -10878,7 +11025,7 @@ pub async fn apply_restored_multiworkspace_state(
}
}
fn restore_native_window_state(
pub fn restore_native_window_state(
window_handle: WindowHandle<MultiWorkspace>,
workspace_id: WorkspaceId,
cx: &mut AsyncApp,
@@ -11584,6 +11731,7 @@ pub fn open_workspace_by_id(
workspace_id: WorkspaceId,
app_state: Arc<AppState>,
requesting_window: Option<WindowHandle<MultiWorkspace>>,
keeps_saved_state_while_restoring: bool,
cx: &mut App,
) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
let project_handle = Project::local(
@@ -11678,8 +11826,15 @@ pub fn open_workspace_by_id(
// Restore items from the serialized workspace
window
.update(cx, |_, window, cx| {
workspace.update(cx, |_workspace, cx| {
open_items(Some(serialized_workspace), Vec::new(), window, cx)
workspace.update(cx, |workspace, cx| {
workspace.keeps_saved_state_while_restoring = keeps_saved_state_while_restoring;
open_items(
workspace,
Some(serialized_workspace),
Vec::new(),
window,
cx,
)
})
})?
.await?;
@@ -12116,8 +12271,14 @@ async fn open_remote_project_inner(
let items = window
.update(cx, |_, window, cx| {
window.activate_window();
workspace.update(cx, |_workspace, cx| {
open_items(serialized_workspace, project_paths_to_open, window, cx)
workspace.update(cx, |workspace, cx| {
open_items(
workspace,
serialized_workspace,
project_paths_to_open,
window,
cx,
)
})
})?
.await?;
+507 -40
View File
@@ -27,11 +27,16 @@ use db::kvp::{GlobalKeyValueStore, KeyValueStore};
use editor::Editor;
use extension::ExtensionHostProxy;
use fs::{Fs, RealFs};
use futures::{FutureExt, StreamExt, channel::oneshot, future};
use futures::{
FutureExt, StreamExt,
channel::{mpsc, oneshot},
future::{self, FusedFuture},
};
use git::GitHostingProviderRegistry;
use git_ui::clone::clone_and_open;
use gpui::{
App, AppContext, Application, AsyncApp, QuitMode, Task, TaskExt, UpdateGlobal as _, block_on,
App, AppContext, Application, AsyncApp, EntityId, QuitMode, Task, TaskExt, UpdateGlobal as _,
WindowHandle, block_on,
};
use gpui_platform;
@@ -46,28 +51,31 @@ use reqwest_client::ReqwestClient;
use assets::Assets;
use node_runtime::{NodeBinaryOptions, NodeRuntime};
use parking_lot::Mutex;
use project::{project_settings::ProjectSettings, trusted_worktrees};
use project::{Project, ProjectGroupKey, project_settings::ProjectSettings, trusted_worktrees};
use recent_projects::{RemoteSettings, open_remote_project};
use release_channel::{AppCommitSha, AppVersion, ReleaseChannel};
use session::{AppSession, Session};
use settings::{BaseKeymap, Settings, SettingsStore, watch_config_file};
use smol::future::poll_once;
use std::{
cell::RefCell,
cell::{Cell, RefCell},
env,
io::{self, IsTerminal},
path::{Path, PathBuf},
process,
rc::Rc,
sync::{Arc, LazyLock, OnceLock},
time::Instant,
time::{Duration, Instant},
};
use theme::{ActiveTheme, GlobalTheme, ThemeRegistry};
use theme_settings::load_user_theme;
use util::{ResultExt, maybe};
use util::{
ResultExt, maybe,
paths::{PathStyle, SanitizedPath},
};
use uuid::Uuid;
use workspace::{
AppState, MultiWorkspace, SerializedWorkspaceLocation, SessionWorkspace, Toast,
AppState, MultiWorkspace, PathList, SerializedWorkspaceLocation, SessionWorkspace, Toast,
WorkspaceSettings, WorkspaceStore,
notifications::{NotificationId, NotifyResultExt},
restore_multiworkspace,
@@ -75,7 +83,8 @@ use workspace::{
use zed::{
OpenListener, OpenRequest, RawOpenRequest, app_menus, build_window_options,
derive_paths_with_position, edit_prediction_registry, handle_cli_connection,
handle_keymap_file_changes, initialize_workspace, open_paths_with_positions,
handle_cli_request, handle_keymap_file_changes, initialize_workspace,
open_paths_with_positions,
};
use crate::zed::{CrashHandler, OpenRequestKind, eager_load_active_theme_and_icon_theme};
@@ -926,11 +935,14 @@ fn main() {
)
};
let restore_task = match open_rx
let initial_request = open_rx
.try_recv()
.ok()
.and_then(|request| OpenRequest::parse(request, cx).log_err())
{
.and_then(|request| OpenRequest::parse(request, cx).log_err());
let runs_full_restore = initial_request
.as_ref()
.is_none_or(|request| request.is_focus_app_only());
let restore_task = match initial_request {
Some(request) if request.is_focus_app_only() => cx.spawn({
let app_state = app_state.clone();
async move |cx| {
@@ -940,8 +952,8 @@ fn main() {
}
}),
Some(request) => {
handle_open_request(request, app_state.clone(), cx);
Task::ready(())
let restore_wait = cx.background_executor().timer(STARTUP_RESTORE_WAIT);
open_startup_request(request, app_state.clone(), restore_wait, cx)
}
None => cx.spawn({
let app_state = app_state.clone();
@@ -956,7 +968,7 @@ fn main() {
let (first_window_tx, first_window_rx) = oneshot::channel::<()>();
let first_window_tx = Rc::new(RefCell::new(Some(first_window_tx)));
let _first_window_subscription = cx.observe_new::<MultiWorkspace>(move |_, _, _| {
if let Some(tx) = first_window_tx.borrow_mut().take() {
if runs_full_restore && let Some(tx) = first_window_tx.borrow_mut().take() {
tx.send(()).ok();
}
});
@@ -1005,6 +1017,485 @@ fn main() {
});
}
const STARTUP_RESTORE_WAIT: Duration = Duration::from_secs(5);
pub(crate) fn open_startup_request(
request: OpenRequest,
app_state: Arc<AppState>,
restore_wait: impl Future<Output = ()> + 'static,
cx: &mut App,
) -> Task<()> {
let is_cli_connection = matches!(request.kind, Some(OpenRequestKind::CliConnection(_)));
if !is_cli_connection && RequestedPaths::of_request(&request).is_none() {
handle_open_request(request, app_state, cx);
return Task::ready(());
}
cx.spawn(async move |cx| {
let restore_wait = restore_wait.fuse();
futures::pin_mut!(restore_wait);
let Some(mut request) =
StartupRequest::read(request, &mut restore_wait, &app_state, cx).await
else {
return;
};
let Some(requested) = cx.update(|cx| request.requested_paths(cx)) else {
request.open(app_state, cx);
return;
};
let mut requested = cx
.spawn({
let fs = app_state.fs.clone();
let db = cx.update(|cx| workspace::WorkspaceDb::global(cx));
async move |_| RequestedProject::new(fs.as_ref(), &db, &requested).await
})
.fuse();
let requested = futures::select_biased! {
requested = requested => Some(requested),
() = restore_wait => None,
};
let Some(requested) = requested else {
request.open(app_state, cx);
return;
};
let joins_restored_windows = requested.joins_restored_windows;
let restored_in_time =
restore_local_windows(&app_state, requested, &mut restore_wait, cx).await;
if !joins_restored_windows || !restored_in_time {
request.open_in_new_window();
}
request.open(app_state, cx);
})
}
enum StartupRequest {
Cli {
request: cli::CliRequest,
requests: mpsc::UnboundedReceiver<cli::CliRequest>,
responses: Box<dyn cli::CliResponseSink>,
},
Other(OpenRequest),
}
impl StartupRequest {
async fn read(
request: OpenRequest,
mut restore_wait: &mut (impl FusedFuture<Output = ()> + Unpin),
app_state: &Arc<AppState>,
cx: &mut AsyncApp,
) -> Option<Self> {
match request.kind {
Some(OpenRequestKind::CliConnection((mut requests, responses))) => {
let request = futures::select_biased! {
request = requests.next() => Some(request),
() = restore_wait => None,
};
let Some(request) = request else {
cx.spawn({
let app_state = app_state.clone();
async move |cx| {
handle_cli_connection((requests, responses), app_state, cx).await
}
})
.detach();
return None;
};
Some(Self::Cli {
request: request?,
requests,
responses,
})
}
_ => Some(Self::Other(request)),
}
}
fn requested_paths(&self, cx: &App) -> Option<RequestedPaths> {
match self {
Self::Cli { request, .. } => RequestedPaths::of_cli_request(request, cx),
Self::Other(request) => RequestedPaths::of_request(request),
}
}
fn open_in_new_window(&mut self) {
match self {
Self::Cli {
request: cli::CliRequest::Open { open_behavior, .. },
..
} => *open_behavior = cli::OpenBehavior::AlwaysNew,
Self::Cli { .. } => {}
Self::Other(request) => request.open_behavior = Some(cli::OpenBehavior::AlwaysNew),
}
}
fn open(self, app_state: Arc<AppState>, cx: &mut AsyncApp) {
match self {
Self::Cli {
request,
requests,
responses,
} => cx
.spawn(async move |cx| {
handle_cli_request(request, requests, responses, app_state, cx).await
})
.detach(),
Self::Other(request) => cx.update(|cx| handle_open_request(request, app_state, cx)),
}
}
}
struct RequestedPaths {
paths: Vec<String>,
reuses_windows: bool,
}
impl RequestedPaths {
fn of_request(request: &OpenRequest) -> Option<Self> {
let opens_local_paths = request.kind.is_none()
&& request.remote_connection.is_none()
&& request.open_channel_notes.is_empty()
&& request.join_channel.is_none()
&& (!request.open_paths.is_empty() || !request.diff_paths.is_empty());
opens_local_paths.then(|| Self {
paths: request.open_paths.clone(),
reuses_windows: !request.open_paths.is_empty()
&& request.diff_paths.is_empty()
&& !request.dev_container
&& matches!(
request.open_behavior,
None | Some(cli::OpenBehavior::Default | cli::OpenBehavior::ExistingWindow)
),
})
}
fn of_cli_request(request: &cli::CliRequest, cx: &App) -> Option<Self> {
let cli::CliRequest::Open {
urls,
paths,
diff_paths,
diff_all,
wait,
wsl,
open_behavior,
dev_container,
env,
cwd,
..
} = request
else {
return None;
};
if *wait {
return None;
}
if !urls.is_empty() {
let request = OpenRequest::parse(
RawOpenRequest {
urls: urls.clone(),
diff_paths: diff_paths.clone(),
diff_all: *diff_all,
dev_container: *dev_container,
wsl: wsl.clone(),
open_behavior: Some(*open_behavior),
},
cx,
)
.ok()?;
return Self::of_request(&request);
}
if paths.is_empty()
&& diff_paths.is_empty()
&& *open_behavior != cli::OpenBehavior::AlwaysNew
{
return None;
}
let mut requested = paths.clone();
if paths.is_empty()
&& !diff_paths.is_empty()
&& let Some(cwd) = cwd
{
requested.push(cwd.to_string_lossy().into_owned());
}
Some(Self {
paths: requested,
reuses_windows: !paths.is_empty()
&& diff_paths.is_empty()
&& !dev_container
&& env.is_none()
&& matches!(
open_behavior,
cli::OpenBehavior::Default | cli::OpenBehavior::ExistingWindow
),
})
}
}
struct RequestedProject {
paths: Vec<PathBuf>,
roots: Vec<PathBuf>,
repositories: PathList,
joins_restored_windows: bool,
}
impl RequestedProject {
async fn new(fs: &dyn Fs, db: &workspace::WorkspaceDb, requested: &RequestedPaths) -> Self {
let paths = derive_paths_with_position(fs, &requested.paths)
.await
.into_iter()
.map(|path| path.path)
.collect::<Vec<_>>();
let mut joins_restored_windows =
requested.reuses_windows && !db.has_workspace_for_roots(&paths);
for path in &paths {
if fs.is_dir(path).await {
joins_restored_windows = false;
}
}
let paths = resolved_paths(fs, &paths).await;
let roots = outermost_paths(&paths);
let repositories = PathList::new(&repository_paths(fs, &roots).await);
Self {
paths,
roots,
repositories,
joins_restored_windows,
}
}
async fn opens(&self, fs: &dyn Fs, roots: &[PathBuf]) -> bool {
if roots.is_empty() {
return false;
}
let roots = resolved_paths(fs, roots).await;
let outermost_roots = outermost_paths(&roots);
if outermost_roots.iter().all(|root| self.paths.contains(root))
&& self.roots.iter().all(|path| outermost_roots.contains(path))
{
return true;
}
PathList::new(&repository_paths(fs, &roots).await) == self.repositories
}
async fn window_to_restore(
&self,
fs: &dyn Fs,
mut multi_workspace: workspace::SerializedMultiWorkspace,
) -> Option<workspace::SerializedMultiWorkspace> {
let saved = &multi_workspace.active_workspace;
if saved.location != SerializedWorkspaceLocation::Local {
return None;
}
if self.opens(fs, saved.paths.paths()).await {
return None;
}
let mut project_groups = Vec::new();
for group in std::mem::take(&mut multi_workspace.state.project_groups) {
let key = ProjectGroupKey::from(group.clone());
if key.host().is_some() || !self.opens(fs, key.path_list().paths()).await {
project_groups.push(group);
}
}
multi_workspace.state.project_groups = project_groups;
Some(multi_workspace)
}
}
async fn restore_local_windows(
app_state: &Arc<AppState>,
requested: RequestedProject,
mut restore_wait: &mut (impl FusedFuture<Output = ()> + Unpin),
cx: &mut AsyncApp,
) -> bool {
let fs = app_state.fs.clone();
let mut windows_to_restore = cx
.spawn({
let app_state = app_state.clone();
let fs = fs.clone();
async move |cx| {
let mut multi_workspaces = restorable_workspaces(cx, &app_state).await?;
if requested.joins_restored_windows {
multi_workspaces.sort_by_key(|multi_workspace| {
let roots = multi_workspace.active_workspace.paths.paths();
requested
.paths
.iter()
.any(|path| roots.iter().any(|root| path.starts_with(root)))
});
}
let mut windows_to_restore = Vec::new();
for multi_workspace in multi_workspaces {
windows_to_restore.extend(
requested
.window_to_restore(fs.as_ref(), multi_workspace)
.await,
);
}
Some(windows_to_restore)
}
})
.fuse();
let windows_to_restore = futures::select_biased! {
windows_to_restore = windows_to_restore => windows_to_restore,
() = restore_wait => return false,
};
let mut error_count = 0;
let mut restored_in_time = true;
for multi_workspace in windows_to_restore.into_iter().flatten() {
let saved = multi_workspace.active_workspace;
let state = multi_workspace.state;
let restored_project = Rc::new(Cell::new(None));
let project_created = cx.update(|cx| {
cx.observe_new::<Project>({
let restored_project = restored_project.clone();
move |_, _, cx| {
if restored_project.get().is_none() {
restored_project.set(Some(cx.entity_id()));
}
}
})
});
let restoring =
cx.update(|cx| workspace::open_saved_workspace(&saved, app_state.clone(), true, cx));
drop(project_created);
let mut restoring = restoring
.then({
let mut cx = cx.clone();
let fs = fs.clone();
let workspace_id = saved.workspace_id;
async move |window| {
let window = window?;
workspace::restore_native_window_state(window, workspace_id, &mut cx);
workspace::apply_restored_multiworkspace_state(window, &state, fs, &mut cx)
.await;
anyhow::Ok(window)
}
})
.boxed_local()
.fuse();
let restored = futures::select_biased! {
restored = restoring => Some(restored),
() = restore_wait => None,
};
match restored {
Some(Ok(window)) => {
window
.update(cx, |_, window, _| window.activate_window())
.log_err();
}
Some(Err(error)) => {
log::error!("Failed to restore workspace: {error:#}");
error_count += 1;
}
None => {
let window = restored_project
.get()
.and_then(|project| cx.update(|cx| window_of_project(project, cx)));
if let Some(window) = window {
window
.update(cx, |_, window, _| window.activate_window())
.log_err();
cx.spawn(async move |_| {
restoring.await.log_err();
})
.detach();
}
restored_in_time = false;
break;
}
}
}
if error_count > 0 {
let message = restore_errors_message(error_count);
cx.update(|cx| show_toast_in_active_workspace(&message, cx));
}
restored_in_time
}
fn window_of_project(project: EntityId, cx: &App) -> Option<WindowHandle<MultiWorkspace>> {
cx.windows()
.into_iter()
.filter_map(|window| window.downcast::<MultiWorkspace>())
.find(|window| {
window.read(cx).is_ok_and(|multi_workspace| {
multi_workspace
.workspaces()
.any(|workspace| workspace.read(cx).project().entity_id() == project)
})
})
}
async fn resolved_paths(fs: &dyn Fs, paths: &[PathBuf]) -> Vec<PathBuf> {
let mut resolved = Vec::with_capacity(paths.len());
for path in paths {
let path = fs.canonicalize(path).await.unwrap_or_else(|_| path.clone());
resolved.push(
SanitizedPath::from_arc(Arc::from(path.as_path()))
.as_path()
.to_path_buf(),
);
}
resolved
}
fn outermost_paths(paths: &[PathBuf]) -> Vec<PathBuf> {
paths
.iter()
.filter(|path| {
!paths
.iter()
.any(|other| other != *path && path.starts_with(other))
})
.cloned()
.collect()
}
async fn repository_paths(fs: &dyn Fs, paths: &[PathBuf]) -> Vec<PathBuf> {
let mut repositories = Vec::with_capacity(paths.len());
for path in paths {
repositories.push(
match project::discover_root_repo_common_dir(path, fs).await {
Some(common_dir) if !project::is_submodule_git_dir(&common_dir) => {
project::repo_identity_path(&common_dir, PathStyle::local()).to_path_buf()
}
_ => path.clone(),
},
);
}
repositories
}
fn restore_errors_message(error_count: usize) -> String {
if error_count == 1 {
"Failed to restore 1 workspace. Check logs for details.".to_string()
} else {
format!(
"Failed to restore {} workspaces. Check logs for details.",
error_count
)
}
}
fn show_toast_in_active_workspace(message: &str, cx: &mut App) -> bool {
if let Some(window) = cx.active_window()
&& let Some(multi_workspace) = window.downcast::<MultiWorkspace>()
{
multi_workspace
.update(cx, |multi_workspace, _, cx| {
multi_workspace.workspace().update(cx, |workspace, cx| {
workspace.show_toast(
Toast::new(NotificationId::unique::<()>(), message.to_string()),
cx,
)
});
})
.ok();
return true;
}
false
}
fn handle_open_request(request: OpenRequest, app_state: Arc<AppState>, cx: &mut App) {
if let Some(kind) = request.kind {
match kind {
@@ -1485,34 +1976,10 @@ pub(crate) async fn restore_or_create_workspace(
}
if error_count > 0 {
let message = if error_count == 1 {
"Failed to restore 1 workspace. Check logs for details.".to_string()
} else {
format!(
"Failed to restore {} workspaces. Check logs for details.",
error_count
)
};
let message = restore_errors_message(error_count);
// Try to find an active workspace to show the toast
let toast_shown = cx.update(|cx| {
if let Some(window) = cx.active_window()
&& let Some(multi_workspace) = window.downcast::<MultiWorkspace>()
{
multi_workspace
.update(cx, |multi_workspace, _, cx| {
multi_workspace.workspace().update(cx, |workspace, cx| {
workspace.show_toast(
Toast::new(NotificationId::unique::<()>(), message.clone()),
cx,
)
});
})
.ok();
return true;
}
false
});
let toast_shown = cx.update(|cx| show_toast_in_active_workspace(&message, cx));
// If we couldn't show a toast (no windows opened successfully),
// open a fallback empty workspace and show the error there
File diff suppressed because it is too large Load Diff
+114 -104
View File
@@ -601,117 +601,127 @@ pub async fn handle_cli_connection(
cx: &mut AsyncApp,
) {
if let Some(request) = requests.next().await {
match request {
CliRequest::Open {
urls,
handle_cli_request(request, requests, responses, app_state, cx).await;
}
}
pub async fn handle_cli_request(
request: CliRequest,
mut requests: mpsc::UnboundedReceiver<CliRequest>,
responses: Box<dyn CliResponseSink>,
app_state: Arc<AppState>,
cx: &mut AsyncApp,
) {
match request {
CliRequest::Open {
urls,
paths,
diff_paths,
diff_all,
wait,
wsl,
mut open_behavior,
env,
user_data_dir: _,
dev_container,
cwd,
} => {
if !urls.is_empty() {
cx.update(|cx| {
match OpenRequest::parse(
RawOpenRequest {
urls,
diff_paths,
diff_all,
dev_container,
wsl,
open_behavior: Some(open_behavior),
},
cx,
) {
Ok(open_request) => {
cx.activate(true);
handle_open_request(open_request, app_state.clone(), cx);
responses.send(CliResponse::Exit { status: 0 }).log_err();
}
Err(e) => {
responses
.send(CliResponse::Stderr {
message: format!("{e}"),
})
.log_err();
responses.send(CliResponse::Exit { status: 1 }).log_err();
}
};
});
return;
}
if open_behavior == cli::OpenBehavior::Default {
match resolve_open_behavior(
&paths,
&app_state,
responses.as_ref(),
&mut requests,
cx,
)
.await
{
Some(settings::CliDefaultOpenBehavior::ExistingWindow) => {
open_behavior = cli::OpenBehavior::ExistingWindow;
}
Some(settings::CliDefaultOpenBehavior::NewWindow) => {
open_behavior = cli::OpenBehavior::PreferNewWindow;
}
None => {}
}
}
if open_behavior == cli::OpenBehavior::Default {
open_behavior = cx.update(|cx| open_behavior_for_default_setting(cx));
}
cx.update(|cx| cx.activate(true));
let open_workspace_result = open_workspaces(
paths,
diff_paths,
diff_all,
open_behavior,
responses.as_ref(),
wait,
wsl,
mut open_behavior,
env,
user_data_dir: _,
dev_container,
app_state.clone(),
env,
cwd,
} => {
if !urls.is_empty() {
cx.update(|cx| {
match OpenRequest::parse(
RawOpenRequest {
urls,
diff_paths,
diff_all,
dev_container,
wsl,
open_behavior: Some(open_behavior),
},
cx,
) {
Ok(open_request) => {
cx.activate(true);
handle_open_request(open_request, app_state.clone(), cx);
responses.send(CliResponse::Exit { status: 0 }).log_err();
}
Err(e) => {
responses
.send(CliResponse::Stderr {
message: format!("{e}"),
})
.log_err();
responses.send(CliResponse::Exit { status: 1 }).log_err();
}
};
});
return;
}
cx,
)
.await;
if open_behavior == cli::OpenBehavior::Default {
match resolve_open_behavior(
&paths,
&app_state,
responses.as_ref(),
&mut requests,
cx,
)
.await
{
Some(settings::CliDefaultOpenBehavior::ExistingWindow) => {
open_behavior = cli::OpenBehavior::ExistingWindow;
}
Some(settings::CliDefaultOpenBehavior::NewWindow) => {
open_behavior = cli::OpenBehavior::PreferNewWindow;
}
None => {}
}
}
if open_behavior == cli::OpenBehavior::Default {
open_behavior = cx.update(|cx| open_behavior_for_default_setting(cx));
}
cx.update(|cx| cx.activate(true));
let open_workspace_result = open_workspaces(
paths,
diff_paths,
diff_all,
open_behavior,
responses.as_ref(),
wait,
dev_container,
app_state.clone(),
env,
cwd,
cx,
)
.await;
let status = if open_workspace_result.is_err() { 1 } else { 0 };
responses.send(CliResponse::Exit { status }).log_err();
}
CliRequest::SetOpenBehavior { .. } => {
// We handle this case in a situation-specific way in
// resolve_open_behavior
debug_panic!("unexpected SetOpenBehavior message");
}
CliRequest::DebugState => {
// Deliberately does not activate the app: activation redraws
// windows and would disturb the state being inspected.
let state = cx.update(|cx| cx.debug_state());
let response = match serde_json::to_string_pretty(&state) {
Ok(message) => CliResponse::Stdout { message },
Err(error) => CliResponse::Stderr {
message: format!("failed to serialize debug state: {error}"),
},
};
let status = match response {
CliResponse::Stdout { .. } => 0,
_ => 1,
};
responses.send(response).log_err();
responses.send(CliResponse::Exit { status }).log_err();
}
let status = if open_workspace_result.is_err() { 1 } else { 0 };
responses.send(CliResponse::Exit { status }).log_err();
}
CliRequest::SetOpenBehavior { .. } => {
// We handle this case in a situation-specific way in
// resolve_open_behavior
debug_panic!("unexpected SetOpenBehavior message");
}
CliRequest::DebugState => {
// Deliberately does not activate the app: activation redraws
// windows and would disturb the state being inspected.
let state = cx.update(|cx| cx.debug_state());
let response = match serde_json::to_string_pretty(&state) {
Ok(message) => CliResponse::Stdout { message },
Err(error) => CliResponse::Stderr {
message: format!("failed to serialize debug state: {error}"),
},
};
let status = match response {
CliResponse::Stdout { .. } => 0,
_ => 1,
};
responses.send(response).log_err();
responses.send(CliResponse::Exit { status }).log_err();
}
}
}