Register terminal panel before restoring serialized terminals (#62712)

Closes https://github.com/zed-industries/zed/issues/62435
Part of https://github.com/zed-industries/zed/issues/60548

Before:


https://github.com/user-attachments/assets/6b5147da-44cb-40c7-9da5-c50145e2ab4e

After:


https://github.com/user-attachments/assets/c58423cc-ea99-40d9-ad18-23b31dfb8e5d


Previously, `TerminalPanel::load` awaited full deserialization of
serialized
terminals (each awaiting directory environment capture via a login
shell)
before the panel was registered in the dock. 

Until then, `terminal_panel::Toggle{Focus}` was a silent no-op: the
workspace finds no
panel in any dock, the keystroke is eaten, and nothing happens.

When it got eventually restored, it would close whatever panel in the
dock was open manually instead, wrecking the workflow.

Repro:
1. Add `case "$ZSH_EXECUTION_STRING" in *--printenv*) sleep 10;; esac`
to `~/.zshrc`.
2. Open a project, open at least one terminal in the panel, quit Zed
(Cmd+Q).
3. Relaunch via Dock/Spotlight (not the `zed` CLI, which skips env
capture via
   `cli_environment`).
4. Press the terminal shortcut within 10s: nothing happens; after ~10s
the
   panel appears and the shortcut works.

* `Register terminal panel before restoring serialized terminals` — the
panel
  is now created and registered immediately, and restoration runs in
  panel-owned tasks (cancelled on panel drop, nothing detached).
  Terminal-adding paths were initially queued behind restoration (later
  replaced by grafting, see below); the default shell spawns only if the
  panel ends up active and empty after restore.

* `Stop replaying serialized dock state over manual panel changes` —
fixes a
related race: `Dock::add_panel` replayed the serialized dock state
(active
panel, visibility, zoom) on every panel insertion, so a late-loading
panel
would re-activate the serialized panel over one the user had switched to
in
the meantime (e.g. the terminal panel yanking the dock away from the
agent
  panel), or re-open a dock the user had closed. Serialized state is now
applied at most once and is discarded as soon as the user changes the
dock
state manually. The new tests fail without this change and pass with it.

* `Show restoration progress in the terminal panel and allow spawning
terminals during it` — while terminals restore, the panel shows a
spinner
with "Restoring terminals…" instead of a blank pane, and logs the
restored
count and elapsed time. Supersedes the queuing from the first commit:
new
terminals spawn immediately, and any that land mid-restore are grafted
into
the restored layout instead of being lost. Serialization is paused
during
restoration, so quitting mid-restore can no longer persist a partial tab
  list and silently drop terminals.


Release Notes:

- Fixed the terminal panel not opening at all under certain
circumstances, made panels no longer switching back to the serialized
one when opened during startup.
This commit is contained in:
Kirill Bulatov authored and GitHub committed 2026-08-21 17:26:29 +00:00
1 parent f5187eac10
commit f7f3b90dca
6 files changed
+1223 -190

No files matched your search

+50 -13
View File
@@ -15,8 +15,8 @@ use db::{
sqlez_macros::sql,
};
use workspace::{
ItemHandle, ItemId, Member, Pane, PaneAxis, PaneGroup, SerializableItem as _, Workspace,
WorkspaceDb, WorkspaceId,
ItemHandle, ItemId, Member, Pane, PaneAxis, PaneGroup, SerializableItem as _, SplitDirection,
Workspace, WorkspaceDb, WorkspaceId,
};
use crate::{
@@ -92,14 +92,12 @@ pub(crate) fn deserialize_terminal_panel(
project: Entity<Project>,
database_id: WorkspaceId,
serialized_panel: SerializedTerminalPanel,
terminal_panel: WeakEntity<TerminalPanel>,
window: &mut Window,
cx: &mut App,
) -> Task<anyhow::Result<Entity<TerminalPanel>>> {
) -> Task<anyhow::Result<usize>> {
window.spawn(cx, async move |cx| {
let terminal_panel = workspace.update_in(cx, |workspace, window, cx| {
cx.new(|cx| TerminalPanel::new(workspace, window, cx))
})?;
match &serialized_panel.items {
let restored_items = match &serialized_panel.items {
SerializedItems::NoSplits(item_ids) => {
let items = deserialize_terminal_views(
database_id,
@@ -109,12 +107,14 @@ pub(crate) fn deserialize_terminal_panel(
cx,
)
.await;
let restored_items = items.len();
let active_item = serialized_panel.active_item_id;
terminal_panel.update_in(cx, |terminal_panel, window, cx| {
terminal_panel.active_pane.update(cx, |pane, cx| {
populate_pane_items(pane, items, active_item, window, cx);
});
})?;
restored_items
}
SerializedItems::WithSplits(serialized_pane_group) => {
let center_pane = deserialize_pane_group(
@@ -127,16 +127,48 @@ pub(crate) fn deserialize_terminal_panel(
)
.await;
if let Some((center_group, active_pane)) = center_pane {
terminal_panel.update(cx, |terminal_panel, _| {
terminal_panel.update_in(cx, |terminal_panel, window, cx| {
let interim_panes = terminal_panel
.center
.panes()
.into_iter()
.filter(|pane| pane.read(cx).items_len() > 0)
.cloned()
.collect::<Vec<_>>();
let focused_interim_pane = interim_panes
.iter()
.find(|pane| pane.read(cx).has_focus(window, cx))
.cloned();
terminal_panel.center = PaneGroup::with_root(center_group);
terminal_panel.active_pane =
active_pane.unwrap_or_else(|| terminal_panel.center.first_pane());
});
let restored_items = terminal_panel
.center
.panes()
.into_iter()
.map(|pane| pane.read(cx).items_len())
.sum::<usize>();
let restored_pane = terminal_panel.active_pane.clone();
for interim_pane in &interim_panes {
terminal_panel.center.split(
&restored_pane,
interim_pane,
SplitDirection::Right,
cx,
);
}
if let Some(focused_interim_pane) = focused_interim_pane {
terminal_panel.active_pane = focused_interim_pane;
}
restored_items
})?
} else {
0
}
}
}
};
Ok(terminal_panel)
Ok(restored_items)
})
}
@@ -147,6 +179,7 @@ fn populate_pane_items(
window: &mut Window,
cx: &mut Context<Pane>,
) {
let interim_active_item = (pane.items_len() > 0).then(|| pane.active_item()).flatten();
let mut active_item_index = None;
for (item_index, item) in (pane.items_len()..).zip(items) {
if Some(item.item_id().as_u64()) == active_item {
@@ -154,7 +187,11 @@ fn populate_pane_items(
}
pane.add_item(Box::new(item), false, false, None, window, cx);
}
if let Some(index) = active_item_index {
if let Some(interim_active_item) = interim_active_item {
if let Some(index) = pane.index_for_item(interim_active_item.as_ref()) {
pane.activate_item(index, false, false, window, cx);
}
} else if let Some(index) = active_item_index {
pane.activate_item(index, false, false, window, cx);
}
}
@@ -163,7 +200,7 @@ fn populate_pane_items(
async fn deserialize_pane_group(
workspace: WeakEntity<Workspace>,
project: Entity<Project>,
panel: Entity<TerminalPanel>,
panel: WeakEntity<TerminalPanel>,
workspace_id: WorkspaceId,
serialized: &SerializedPaneGroup,
cx: &mut AsyncWindowContext,
File diff suppressed because it is too large. Load diff
@@ -428,6 +428,11 @@ impl TerminalView {
}
}
pub(crate) fn mark_needs_serialize(&mut self, cx: &mut Context<Self>) {
self.needs_serialize = true;
cx.emit(ItemEvent::UpdateTab);
}
pub fn is_renaming(&self) -> bool {
self.rename_editor.is_some()
}
+106 -19
View File
@@ -288,12 +288,32 @@ pub struct Dock {
active_panel_index: Option<usize>,
focus_handle: FocusHandle,
focus_follows_mouse: FocusFollowsMouse,
pub(crate) serialized_dock: Option<DockData>,
restoration: DockRestoreState,
zoom_layer_open: bool,
modal_layer: Entity<ModalLayer>,
_subscriptions: [Subscription; 2],
}
enum DockRestoreState {
Restoring { pending: Option<DockData> },
Finished,
}
impl DockRestoreState {
fn pending(&self) -> Option<&DockData> {
match self {
Self::Restoring { pending } => pending.as_ref(),
Self::Finished => None,
}
}
fn discard_pending(&mut self) {
if let Self::Restoring { pending } = self {
*pending = None;
}
}
}
impl Focusable for Dock {
fn focus_handle(&self, _: &App) -> FocusHandle {
self.focus_handle.clone()
@@ -436,7 +456,7 @@ impl Dock {
focus_handle: focus_handle.clone(),
focus_follows_mouse: WorkspaceSettings::get_global(cx).focus_follows_mouse,
_subscriptions: [focus_subscription, zoom_subscription],
serialized_dock: None,
restoration: DockRestoreState::Restoring { pending: None },
zoom_layer_open: false,
modal_layer,
}
@@ -556,6 +576,13 @@ impl Dock {
}
pub fn set_open(&mut self, open: bool, window: &mut Window, cx: &mut Context<Self>) {
if open != self.is_open {
self.restoration.discard_pending();
}
self.set_open_internal(open, window, cx);
}
fn set_open_internal(&mut self, open: bool, window: &mut Window, cx: &mut Context<Self>) {
if open != self.is_open {
self.is_open = open;
if let Some(active_panel) = self.active_panel_entry() {
@@ -787,34 +814,82 @@ impl Dock {
},
);
self.restore_state(window, cx);
self.replay_pending_serialized_state(window, cx);
if panel.read(cx).starts_open(window, cx) {
self.activate_panel(index, window, cx);
self.set_open(true, window, cx);
self.activate_panel_internal(index, window, cx);
self.set_open_internal(true, window, cx);
}
cx.notify();
index
}
pub fn restore_state(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
if let Some(serialized) = self.serialized_dock.clone() {
if let Some(active_panel) = serialized.active_panel.filter(|_| serialized.visible)
&& let Some(idx) = self.panel_index_for_persistent_name(active_panel.as_str(), cx)
{
self.activate_panel(idx, window, cx);
pub(crate) fn restore_serialized_state(
&mut self,
serialized: DockData,
window: &mut Window,
cx: &mut Context<Self>,
) {
match &mut self.restoration {
DockRestoreState::Restoring { pending } => {
*pending = Some(serialized);
self.replay_pending_serialized_state(window, cx);
}
if serialized.zoom
&& let Some(panel) = self.active_panel()
{
panel.set_zoomed(true, window, cx)
DockRestoreState::Finished => {
let active_panel_missing = serialized
.active_panel
.as_deref()
.filter(|_| serialized.visible)
.is_some_and(|name| self.panel_index_for_persistent_name(name, cx).is_none());
if !active_panel_missing {
self.apply_serialized_state(&serialized, window, cx);
}
}
self.set_open(serialized.visible, window, cx);
return true;
}
false
}
fn replay_pending_serialized_state(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(serialized) = self.restoration.pending().cloned() else {
return;
};
let waiting_for_active_panel = serialized
.active_panel
.as_deref()
.filter(|_| serialized.visible)
.is_some_and(|name| self.panel_index_for_persistent_name(name, cx).is_none());
if waiting_for_active_panel {
self.set_open_internal(serialized.visible, window, cx);
} else {
self.apply_serialized_state(&serialized, window, cx);
self.restoration.discard_pending();
}
}
fn apply_serialized_state(
&mut self,
serialized: &DockData,
window: &mut Window,
cx: &mut Context<Self>,
) {
if let Some(active_panel) = serialized
.active_panel
.as_deref()
.filter(|_| serialized.visible)
&& let Some(idx) = self.panel_index_for_persistent_name(active_panel, cx)
{
self.activate_panel_internal(idx, window, cx);
}
if serialized.zoom
&& let Some(panel) = self.active_panel()
{
panel.set_zoomed(true, window, cx)
}
self.set_open_internal(serialized.visible, window, cx);
}
pub(crate) fn finish_restoration(&mut self) {
self.restoration = DockRestoreState::Finished;
}
pub fn remove_panel<T: Panel>(
@@ -861,6 +936,18 @@ impl Dock {
}
pub fn activate_panel(&mut self, panel_ix: usize, window: &mut Window, cx: &mut Context<Self>) {
if Some(panel_ix) != self.active_panel_index {
self.restoration.discard_pending();
}
self.activate_panel_internal(panel_ix, window, cx);
}
fn activate_panel_internal(
&mut self,
panel_ix: usize,
window: &mut Window,
cx: &mut Context<Self>,
) {
if Some(panel_ix) != self.active_panel_index {
if let Some(active_panel) = self.active_panel_entry() {
active_panel.panel.set_active(false, window, cx);
+358 -6
View File
@@ -2151,8 +2151,11 @@ impl Workspace {
(&workspace.bottom_dock, &default_docks.bottom),
] {
dock.update(cx, |dock, cx| {
dock.serialized_dock = Some(serialized_dock.clone());
dock.restore_state(window, cx);
dock.restore_serialized_state(
serialized_dock.clone(),
window,
cx,
);
});
}
cx.notify();
@@ -2289,8 +2292,15 @@ impl Workspace {
(&self.right_dock, docks.right),
] {
dock.update(cx, |dock, cx| {
dock.serialized_dock = Some(data);
dock.restore_state(window, cx);
dock.restore_serialized_state(data, window, cx);
});
}
}
pub fn finish_dock_restoration(&self, cx: &mut App) {
for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
dock.update(cx, |dock, _| {
dock.finish_restoration();
});
}
}
@@ -7477,8 +7487,7 @@ impl Workspace {
.iter_mut()
{
dock.update(cx, |dock, cx| {
dock.serialized_dock = Some(serialized_dock.clone());
dock.restore_state(window, cx);
dock.restore_serialized_state(serialized_dock.clone(), window, cx);
});
}
@@ -11763,6 +11772,7 @@ mod tests {
ItemBufferKind, ItemEvent,
test::{TestItem, TestProjectItem},
},
persistence::model::DockData,
};
use fs::FakeFs;
use gpui::{
@@ -18452,4 +18462,346 @@ mod tests {
});
assert_eq!(cx.opened_url(), Some("nonexistent.txt".to_string()));
}
#[gpui::test]
async fn test_serialized_dock_state_not_replayed_over_manual_panel_changes(
cx: &mut gpui::TestAppContext,
) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
let project = Project::test(fs, [], cx).await;
let (workspace, cx) =
cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
workspace.update_in(cx, |workspace, window, cx| {
workspace.bottom_dock().update(cx, |dock, cx| {
dock.restore_serialized_state(
DockData {
visible: true,
active_panel: Some(SecondTestPanel::persistent_name().to_string()),
zoom: false,
},
window,
cx,
);
});
});
let first_panel = workspace.update_in(cx, |workspace, window, cx| {
let panel = cx.new(|cx| TestPanel::new(DockPosition::Bottom, 100, cx));
workspace.add_panel(panel.clone(), window, cx);
panel
});
let second_panel = workspace.update_in(cx, |workspace, window, cx| {
let panel = cx.new(|cx| SecondTestPanel {
focus_handle: cx.focus_handle(),
zoomed: false,
});
workspace.add_panel(panel.clone(), window, cx);
panel
});
workspace.read_with(cx, |workspace, cx| {
let dock = workspace.bottom_dock().read(cx);
assert!(dock.is_open());
assert_eq!(
dock.active_panel().map(|panel| panel.panel_id()),
Some(second_panel.entity_id()),
);
});
workspace.update_in(cx, |workspace, window, cx| {
workspace.toggle_panel_focus::<TestPanel>(window, cx);
});
workspace.read_with(cx, |workspace, cx| {
assert_eq!(
workspace
.bottom_dock()
.read(cx)
.active_panel()
.map(|panel| panel.panel_id()),
Some(first_panel.entity_id()),
);
});
workspace.update_in(cx, |workspace, window, cx| {
let panel = cx.new(|cx| TestPanel::new(DockPosition::Bottom, 300, cx));
workspace.add_panel(panel, window, cx);
});
workspace.read_with(cx, |workspace, cx| {
let dock = workspace.bottom_dock().read(cx);
assert!(dock.is_open());
assert_eq!(
dock.active_panel().map(|panel| panel.panel_id()),
Some(first_panel.entity_id()),
);
});
}
#[gpui::test]
async fn test_closed_dock_not_reopened_by_late_serialized_panel(cx: &mut gpui::TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
let project = Project::test(fs, [], cx).await;
let (workspace, cx) =
cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
workspace.update_in(cx, |workspace, window, cx| {
workspace.bottom_dock().update(cx, |dock, cx| {
dock.restore_serialized_state(
DockData {
visible: true,
active_panel: Some(SecondTestPanel::persistent_name().to_string()),
zoom: false,
},
window,
cx,
);
});
});
workspace.read_with(cx, |workspace, cx| {
assert!(workspace.bottom_dock().read(cx).is_open());
});
workspace.update_in(cx, |workspace, window, cx| {
workspace
.bottom_dock()
.update(cx, |dock, cx| dock.set_open(false, window, cx));
});
workspace.update_in(cx, |workspace, window, cx| {
let panel = cx.new(|cx| SecondTestPanel {
focus_handle: cx.focus_handle(),
zoomed: false,
});
workspace.add_panel(panel, window, cx);
});
workspace.read_with(cx, |workspace, cx| {
assert!(!workspace.bottom_dock().read(cx).is_open());
});
}
#[gpui::test]
async fn test_stale_serialized_dock_state_discarded_when_panel_loading_finishes(
cx: &mut gpui::TestAppContext,
) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
let project = Project::test(fs, [], cx).await;
let (workspace, cx) =
cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
workspace.update_in(cx, |workspace, window, cx| {
workspace.bottom_dock().update(cx, |dock, cx| {
dock.restore_serialized_state(
DockData {
visible: true,
active_panel: Some(SecondTestPanel::persistent_name().to_string()),
zoom: false,
},
window,
cx,
);
});
});
workspace.update(cx, |workspace, cx| {
workspace.finish_dock_restoration(cx);
});
workspace.update_in(cx, |workspace, window, cx| {
let panel = cx.new(|cx| SecondTestPanel {
focus_handle: cx.focus_handle(),
zoomed: false,
});
workspace.add_panel(panel, window, cx);
});
workspace.read_with(cx, |workspace, cx| {
assert_eq!(
workspace
.bottom_dock()
.read(cx)
.active_panel()
.map(|panel| panel.panel_id()),
None,
"stale dock restoration state should not replay after panel loading finished",
);
});
}
#[gpui::test]
async fn test_serialized_state_for_missing_panel_dropped_after_restoration_finishes(
cx: &mut gpui::TestAppContext,
) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
let project = Project::test(fs, [], cx).await;
let (workspace, cx) =
cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
workspace.update(cx, |workspace, cx| {
workspace.finish_dock_restoration(cx);
});
workspace.update_in(cx, |workspace, window, cx| {
workspace.bottom_dock().update(cx, |dock, cx| {
dock.restore_serialized_state(
DockData {
visible: true,
active_panel: Some(SecondTestPanel::persistent_name().to_string()),
zoom: false,
},
window,
cx,
);
});
});
workspace.read_with(cx, |workspace, cx| {
let dock = workspace.bottom_dock().read(cx);
assert!(
!dock.is_open(),
"dock must not open for a panel that can no longer register",
);
});
workspace.update_in(cx, |workspace, window, cx| {
let panel = cx.new(|cx| SecondTestPanel {
focus_handle: cx.focus_handle(),
zoomed: false,
});
workspace.add_panel(panel, window, cx);
});
workspace.read_with(cx, |workspace, cx| {
assert!(
!workspace.bottom_dock().read(cx).is_open(),
"stale dock state must not replay when the panel registers much later",
);
});
}
#[gpui::test]
async fn test_serialized_zoom_not_applied_while_waiting_for_serialized_panel(
cx: &mut gpui::TestAppContext,
) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
let project = Project::test(fs, [], cx).await;
let (workspace, cx) =
cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
let first_panel = workspace.update_in(cx, |workspace, window, cx| {
let panel = cx.new(|cx| TestPanel::new(DockPosition::Bottom, 100, cx));
workspace.add_panel(panel.clone(), window, cx);
workspace.toggle_panel_focus::<TestPanel>(window, cx);
panel
});
workspace.update_in(cx, |workspace, window, cx| {
workspace.bottom_dock().update(cx, |dock, cx| {
dock.restore_serialized_state(
DockData {
visible: true,
active_panel: Some(SecondTestPanel::persistent_name().to_string()),
zoom: true,
},
window,
cx,
);
});
});
workspace.read_with(cx, |_, cx| {
assert!(
!first_panel.read(cx).zoomed,
"serialized zoom should not apply to another panel while the serialized active panel is loading",
);
});
let second_panel = workspace.update_in(cx, |workspace, window, cx| {
let panel = cx.new(|cx| SecondTestPanel {
focus_handle: cx.focus_handle(),
zoomed: false,
});
workspace.add_panel(panel.clone(), window, cx);
panel
});
workspace.read_with(cx, |workspace, cx| {
let dock = workspace.bottom_dock().read(cx);
assert!(dock.is_open());
assert_eq!(
dock.active_panel().map(|panel| panel.panel_id()),
Some(second_panel.entity_id()),
);
assert!(!first_panel.read(cx).zoomed);
assert!(second_panel.read(cx).zoomed);
});
}
struct SecondTestPanel {
focus_handle: FocusHandle,
zoomed: bool,
}
impl EventEmitter<PanelEvent> for SecondTestPanel {}
impl Focusable for SecondTestPanel {
fn focus_handle(&self, _cx: &App) -> FocusHandle {
self.focus_handle.clone()
}
}
impl Render for SecondTestPanel {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.id("second-test-panel")
.track_focus(&self.focus_handle(cx))
}
}
impl Panel for SecondTestPanel {
fn persistent_name() -> &'static str {
"SecondTestPanel"
}
fn panel_key() -> &'static str {
"SecondTestPanel"
}
fn position(&self, _: &Window, _: &App) -> DockPosition {
DockPosition::Bottom
}
fn position_is_valid(&self, _: DockPosition) -> bool {
true
}
fn set_position(&mut self, _: DockPosition, _: &mut Window, _: &mut Context<Self>) {}
fn default_size(&self, _: &Window, _: &App) -> Pixels {
px(300.)
}
fn icon(&self, _: &Window, _: &App) -> Option<ui::IconName> {
None
}
fn icon_tooltip(&self, _: &Window, _: &App) -> Option<&'static str> {
None
}
fn toggle_action(&self) -> Box<dyn Action> {
crate::dock::test::ToggleTestPanel.boxed_clone()
}
fn activation_priority(&self) -> u32 {
200
}
fn is_zoomed(&self, _: &Window, _: &App) -> bool {
self.zoomed
}
fn set_zoomed(&mut self, zoomed: bool, _: &mut Window, _: &mut Context<Self>) {
self.zoomed = zoomed;
}
}
}
+5 -1
View File
@@ -808,9 +808,13 @@ fn initialize_panels(window: &mut Window, cx: &mut Context<Workspace>) -> Task<a
add_panel_when_ready(git_panel, workspace_handle.clone(), cx.clone()),
add_panel_when_ready(channels_panel, workspace_handle.clone(), cx.clone()),
add_panel_when_ready(debug_panel, workspace_handle.clone(), cx.clone()),
initialize_agent_panel(workspace_handle, cx.clone()).map(|r| r.log_err()),
initialize_agent_panel(workspace_handle.clone(), cx.clone()).map(|r| r.log_err()),
);
workspace_handle.update(cx, |workspace, cx| {
workspace.finish_dock_restoration(cx);
})?;
anyhow::Ok(())
})
}