From 34d3ce3c9cfc60f7685ea2f666a337b22dc6680d Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Tue, 17 Nov 2026 00:33:20 +0800 Subject: [PATCH] refactor(workspace): unify project open ordering in backend and drop display-order heuristics --- .../cli/src/peer_host/commands/workspace.rs | 14 +- src/apps/desktop/src/api/commands.rs | 32 +++ src/apps/server/src/rpc_dispatcher.rs | 47 +++- .../src/agentic/coordination/coordinator.rs | 7 +- .../src/service/workspace/legacy_compat.rs | 11 +- .../core/src/service/workspace/manager.rs | 151 +++++++++++- .../core/src/service/workspace/service.rs | 78 ++++++- .../api/service-api/GlobalAPI.ts | 7 + .../peer-device/deviceWorkspaceCatalog.ts | 7 +- .../business/workspaceDisplayOrder.test.ts | 119 ++++------ .../business/workspaceDisplayOrder.ts | 119 ++-------- .../business/workspaceManager.test.ts | 215 ++++-------------- .../services/business/workspaceManager.ts | 152 ++++--------- 13 files changed, 474 insertions(+), 485 deletions(-) diff --git a/src/apps/cli/src/peer_host/commands/workspace.rs b/src/apps/cli/src/peer_host/commands/workspace.rs index 8fd9038339..7e99ad6842 100644 --- a/src/apps/cli/src/peer_host/commands/workspace.rs +++ b/src/apps/cli/src/peer_host/commands/workspace.rs @@ -3,7 +3,7 @@ use std::path::PathBuf; use openbitfun_core::service::workspace::{ - remote_workspace_connection_conflict_message, RemoteConnectionRebind, + remote_workspace_connection_conflict_message, RemoteConnectionRebind, WorkspaceCreateOptions, }; use openbitfun_runtime_ports::SessionStoragePathRequest; use serde_json::{json, Value}; @@ -98,6 +98,8 @@ pub(crate) async fn open_workspace(state: &PeerHostState, args: &Value) -> Resul } // Explicit new-folder/old-protocol ingress. Existing-workspace selection uses ID. let path = get_string(request, "path")?; + let create_local = optional_bool(request, "createLocal").unwrap_or(false); + let promote_if_opened = optional_bool(request, "promoteIfOpened").unwrap_or(create_local); state .compatibility .ensure_workspace_runtime_ownership(&SessionStoragePathRequest { @@ -108,7 +110,13 @@ pub(crate) async fn open_workspace(state: &PeerHostState, args: &Value) -> Resul .map_err(|error| format!("Agent Runtime ownership is unavailable: {error}"))?; let info = state .workspace_service - .open_workspace(PathBuf::from(path)) + .open_workspace_with_options( + PathBuf::from(path), + WorkspaceCreateOptions { + promote_if_opened, + ..Default::default() + }, + ) .await .map_err(|e| format!("Failed to open workspace: {e}"))?; @@ -137,6 +145,7 @@ pub(crate) async fn open_remote_workspace( } else { RemoteConnectionRebind::Reject }; + let promote_if_opened = optional_bool(request, "promoteIfOpened").unwrap_or(true); let coordinator = openbitfun_core::agentic::coordination::get_global_coordinator() .ok_or("Conversation coordinator is unavailable")?; let info = coordinator @@ -146,6 +155,7 @@ pub(crate) async fn open_remote_workspace( &connection_id, host.as_deref(), rebind, + promote_if_opened, ) .await .map_err(|e| { diff --git a/src/apps/desktop/src/api/commands.rs b/src/apps/desktop/src/api/commands.rs index 4d2eee30ef..466215d730 100644 --- a/src/apps/desktop/src/api/commands.rs +++ b/src/apps/desktop/src/api/commands.rs @@ -381,6 +381,10 @@ pub struct OpenWorkspaceRequest { pub remote_connection_id: Option, } +fn default_promote_if_opened() -> bool { + true +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct OpenRemoteWorkspaceRequest { @@ -394,6 +398,11 @@ pub struct OpenRemoteWorkspaceRequest { /// connection to `connection_id`. #[serde(default)] pub rebind_connection: bool, + /// Move an already-opened record to the front of the project section. + /// Legacy callers omit this field and keep the explicit-open default (`true`); + /// background SSH restore sets `false` so reconnecting does not reorder rows. + #[serde(default = "default_promote_if_opened")] + pub promote_if_opened: bool, } #[derive(Debug, Deserialize, Default)] @@ -1492,6 +1501,7 @@ pub async fn open_remote_workspace( }, auto_set_current: true, add_to_recent: true, + promote_if_opened: request.promote_if_opened, workspace_kind: WorkspaceKind::Remote, assistant_id: None, display_name: Some(display_name), @@ -1874,6 +1884,28 @@ mod assistant_workspace_delete_tests { Ok(AssistantWorkspaceDirectoryPlan::RegistryEntryOnly) ); } + + #[test] + fn open_remote_workspace_request_defaults_promote_if_opened_for_legacy_payloads() { + let legacy: super::OpenRemoteWorkspaceRequest = serde_json::from_value(serde_json::json!({ + "remotePath": "/srv/app", + "connectionId": "ssh-prod", + "connectionName": "Prod", + })) + .expect("legacy payload should deserialize"); + assert!(legacy.promote_if_opened); + assert!(!legacy.rebind_connection); + + let background_restore: super::OpenRemoteWorkspaceRequest = + serde_json::from_value(serde_json::json!({ + "remotePath": "/srv/app", + "connectionId": "ssh-prod", + "connectionName": "Prod", + "promoteIfOpened": false, + })) + .expect("background restore payload should deserialize"); + assert!(!background_restore.promote_if_opened); + } } #[tauri::command] diff --git a/src/apps/server/src/rpc_dispatcher.rs b/src/apps/server/src/rpc_dispatcher.rs index a0954be1e4..497492a7e8 100644 --- a/src/apps/server/src/rpc_dispatcher.rs +++ b/src/apps/server/src/rpc_dispatcher.rs @@ -55,17 +55,42 @@ pub async fn dispatch( // ── Workspace ──────────────────────────────────────── "open_workspace" => { let request = extract_request(¶ms)?; - let path: String = serde_json::from_value( - request - .get("path") - .cloned() - .ok_or_else(|| anyhow!("Missing path"))?, - )?; - let info = state - .workspace_service - .open_workspace(path.into()) - .await - .map_err(|e| anyhow!("{}", e))?; + let create_local = request + .get("createLocal") + .and_then(|value| value.as_bool()) + .unwrap_or(false); + let info = if let Some(workspace_id) = request + .get("workspaceId") + .and_then(|value| value.as_str()) + .map(str::trim) + .filter(|value| !value.is_empty()) + { + state + .workspace_service + .open_workspace_by_id(workspace_id) + .await + .map_err(|e| anyhow!("{}", e))? + } else { + let path: String = serde_json::from_value( + request + .get("path") + .cloned() + .ok_or_else(|| anyhow!("Missing path"))?, + )?; + if create_local { + state + .workspace_service + .open_workspace(path.into()) + .await + .map_err(|e| anyhow!("{}", e))? + } else { + state + .workspace_service + .upgrade_legacy_workspace_open(path.into(), None, None) + .await + .map_err(|e| anyhow!("{}", e))? + } + }; *state.workspace_path.write().await = Some(info.root_path.clone()); Ok(serde_json::to_value(&info).unwrap_or_default()) } diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs index 25acfb1d0a..4db21d58cb 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs @@ -2640,6 +2640,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet connection_id: &str, ssh_host: Option<&str>, remote_connection_rebind: RemoteConnectionRebind, + promote_if_opened: bool, ) -> OpenBitFunResult { let workspace = workspace_service .prepare_remote_workspace(path, connection_id, ssh_host) @@ -2653,7 +2654,11 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet .and_then(|host| host.as_str()), )?; workspace_service - .open_known_remote_workspace_with_rebind(&workspace, remote_connection_rebind) + .open_known_remote_workspace_with_rebind( + &workspace, + remote_connection_rebind, + promote_if_opened, + ) .await } diff --git a/src/crates/assembly/core/src/service/workspace/legacy_compat.rs b/src/crates/assembly/core/src/service/workspace/legacy_compat.rs index 20d79c0d6b..203b37707a 100644 --- a/src/crates/assembly/core/src/service/workspace/legacy_compat.rs +++ b/src/crates/assembly/core/src/service/workspace/legacy_compat.rs @@ -167,7 +167,16 @@ impl WorkspaceService { self.open_workspace_by_id(&known.id).await }; } - match self.open_workspace(path).await { + match self + .open_workspace_with_options( + path, + super::service::WorkspaceCreateOptions { + promote_if_opened: false, + ..Default::default() + }, + ) + .await + { Ok(info) => Ok(info), Err(error) => { let message = error.to_string(); diff --git a/src/crates/assembly/core/src/service/workspace/manager.rs b/src/crates/assembly/core/src/service/workspace/manager.rs index 0337d66793..cbdf7215ac 100644 --- a/src/crates/assembly/core/src/service/workspace/manager.rs +++ b/src/crates/assembly/core/src/service/workspace/manager.rs @@ -191,6 +191,10 @@ pub struct WorkspaceOpenOptions { pub scan_options: ScanOptions, pub auto_set_current: bool, pub add_to_recent: bool, + /// When `true` (default for explicit folder opens), opening an already-open + /// project workspace promotes it to the first project slot. Selection by ID, + /// legacy upgrade paths, and background SSH restore pass `false`. + pub promote_if_opened: bool, pub workspace_kind: WorkspaceKind, pub assistant_id: Option, pub display_name: Option, @@ -212,6 +216,7 @@ impl Default for WorkspaceOpenOptions { scan_options: ScanOptions::default(), auto_set_current: true, add_to_recent: true, + promote_if_opened: true, workspace_kind: WorkspaceKind::Normal, assistant_id: None, display_name: None, @@ -1072,7 +1077,11 @@ impl WorkspaceManager { } } if keep_opened { - self.ensure_workspace_open(&workspace_id); + if options.promote_if_opened { + self.promote_workspace_open(&workspace_id); + } else { + self.ensure_workspace_open(&workspace_id); + } } if options.auto_set_current { self.set_current_workspace_with_recent_policy( @@ -1504,8 +1513,9 @@ impl WorkspaceManager { } /// Ensures a workspace is in the opened list. A newly opened workspace goes - /// first; an already opened one keeps its place, so activating a workspace - /// never reorders the list users arrange (recency lives in the recent list). + /// to the front of its section (projects skip leading assistants); an + /// already opened one keeps its place, so activating a workspace never + /// reorders the list users arrange (recency lives in the recent list). fn ensure_workspace_open(&mut self, workspace_id: &str) { if self .opened_workspace_ids @@ -1514,8 +1524,68 @@ impl WorkspaceManager { { return; } + let is_assistant = self + .workspaces + .get(workspace_id) + .is_some_and(|workspace| workspace.workspace_kind == WorkspaceKind::Assistant); + let insert_at = if is_assistant { + 0 + } else { + self.opened_workspace_ids + .iter() + .position(|id| { + self.workspaces.get(id).is_none_or(|workspace| { + workspace.workspace_kind != WorkspaceKind::Assistant + }) + }) + .unwrap_or(self.opened_workspace_ids.len()) + }; self.opened_workspace_ids - .insert(0, workspace_id.to_string()); + .insert(insert_at, workspace_id.to_string()); + } + + /// Ensures a workspace is open and, when it is a project workspace, places + /// it at the front of the project slots while leaving assistant slots in place. + fn promote_workspace_open(&mut self, workspace_id: &str) { + let is_assistant = self + .workspaces + .get(workspace_id) + .is_some_and(|workspace| workspace.workspace_kind == WorkspaceKind::Assistant); + if is_assistant + || !self + .opened_workspace_ids + .iter() + .any(|id| id == workspace_id) + { + self.ensure_workspace_open(workspace_id); + return; + } + + let workspaces = &self.workspaces; + let mut projects: Vec = self + .opened_workspace_ids + .iter() + .filter(|id| { + id.as_str() != workspace_id + && workspaces.get(*id).is_none_or(|workspace| { + workspace.workspace_kind != WorkspaceKind::Assistant + }) + }) + .cloned() + .collect(); + projects.insert(0, workspace_id.to_string()); + + let mut project_iter = projects.into_iter(); + for slot in &mut self.opened_workspace_ids { + let is_project_slot = workspaces + .get(slot.as_str()) + .is_none_or(|workspace| workspace.workspace_kind != WorkspaceKind::Assistant); + if is_project_slot { + if let Some(next) = project_iter.next() { + *slot = next; + } + } + } } /// Returns manager statistics. @@ -1949,4 +2019,77 @@ mod tests { vec!["avatar".to_string()] ); } + + #[tokio::test] + async fn opening_project_promotes_to_first_project_slot_without_moving_assistants() { + use super::{ + WorkspaceInfo, WorkspaceInfoRuntimeExt, WorkspaceKind, WorkspaceManager, + WorkspaceManagerConfig, WorkspaceOpenOptions, + }; + + let temp = tempfile::tempdir().expect("temp assistant dir"); + let mut manager = WorkspaceManager::new(WorkspaceManagerConfig::default()); + let assistant = WorkspaceInfo::new_without_worktree( + temp.path().to_path_buf(), + WorkspaceOpenOptions { + workspace_kind: WorkspaceKind::Assistant, + ..Default::default() + }, + ) + .await + .unwrap(); + manager + .workspaces + .insert(assistant.id.clone(), assistant.clone()); + manager.opened_workspace_ids = vec![assistant.id.clone()]; + + let remote = |promote_if_opened: bool| WorkspaceOpenOptions { + workspace_kind: WorkspaceKind::Remote, + remote_connection_id: Some("ssh-dev".into()), + remote_ssh_host: Some("dev.example".into()), + promote_if_opened, + ..Default::default() + }; + + let proj_a = manager + .open_workspace_with_options("/srv/proj-a".into(), remote(true)) + .await + .unwrap(); + let proj_b = manager + .open_workspace_with_options("/srv/proj-b".into(), remote(true)) + .await + .unwrap(); + assert_eq!( + manager.opened_workspace_ids, + vec![assistant.id.clone(), proj_b.id.clone(), proj_a.id.clone()] + ); + + // Background restore (`promote_if_opened: false`) preserves existing order. + manager + .open_workspace_with_options("/srv/proj-a".into(), remote(false)) + .await + .unwrap(); + assert_eq!( + manager.opened_workspace_ids, + vec![assistant.id.clone(), proj_b.id.clone(), proj_a.id.clone()] + ); + + // Explicit open (`promote_if_opened: true`) moves proj-a to the first project slot, + // keeping the leading assistant untouched. + manager + .open_workspace_with_options("/srv/proj-a".into(), remote(true)) + .await + .unwrap(); + assert_eq!( + manager.opened_workspace_ids, + vec![assistant.id.clone(), proj_a.id.clone(), proj_b.id.clone()] + ); + + // Ordinary activation keeps existing order. + manager.set_active_workspace(&proj_b.id).unwrap(); + assert_eq!( + manager.opened_workspace_ids, + vec![assistant.id.clone(), proj_a.id.clone(), proj_b.id.clone()] + ); + } } diff --git a/src/crates/assembly/core/src/service/workspace/service.rs b/src/crates/assembly/core/src/service/workspace/service.rs index e4d2243459..21ea7af00c 100644 --- a/src/crates/assembly/core/src/service/workspace/service.rs +++ b/src/crates/assembly/core/src/service/workspace/service.rs @@ -72,6 +72,8 @@ pub struct WorkspaceCreateOptions { pub scan_options: ScanOptions, pub auto_set_current: bool, pub add_to_recent: bool, + /// See [`crate::service::workspace::manager::WorkspaceOpenOptions::promote_if_opened`]. + pub promote_if_opened: bool, pub workspace_kind: WorkspaceKind, pub assistant_id: Option, pub display_name: Option, @@ -99,6 +101,7 @@ impl Default for WorkspaceCreateOptions { scan_options: ScanOptions::default(), auto_set_current: true, add_to_recent: true, + promote_if_opened: true, workspace_kind: WorkspaceKind::Normal, assistant_id: None, display_name: None, @@ -678,7 +681,7 @@ impl WorkspaceService { &self, known: &WorkspaceInfo, ) -> OpenBitFunResult { - self.open_known_remote_workspace_with_rebind(known, RemoteConnectionRebind::Reject) + self.open_known_remote_workspace_with_rebind(known, RemoteConnectionRebind::Reject, false) .await } @@ -686,6 +689,7 @@ impl WorkspaceService { &self, known: &WorkspaceInfo, remote_connection_rebind: RemoteConnectionRebind, + promote_if_opened: bool, ) -> OpenBitFunResult { let connection_id = known.remote_ssh_connection_id().ok_or_else(|| { OpenBitFunError::service(format!( @@ -708,6 +712,7 @@ impl WorkspaceService { let remote_path = normalize_remote_workspace_path(&known.root_path.to_string_lossy()); let options = WorkspaceCreateOptions { + promote_if_opened, workspace_kind: WorkspaceKind::Remote, display_name: Some(known.name.clone()), remote_connection_id: Some(connection_id.to_string()), @@ -1432,6 +1437,7 @@ impl WorkspaceService { scan_options: ScanOptions::default(), auto_set_current: existing_workspace.status == WorkspaceStatus::Active, add_to_recent: false, + promote_if_opened: false, workspace_kind: existing_workspace.workspace_kind.clone(), assistant_id: existing_workspace.assistant_id.clone(), display_name: Some(existing_workspace.name.clone()), @@ -2145,6 +2151,7 @@ impl WorkspaceService { scan_options: options.scan_options.clone(), auto_set_current: options.auto_set_current, add_to_recent: options.add_to_recent, + promote_if_opened: options.promote_if_opened, workspace_kind: options.workspace_kind.clone(), assistant_id: options.assistant_id.clone(), display_name: options.display_name.clone(), @@ -3962,6 +3969,75 @@ mod tests { "unrelated directories must be rejected" ); } + + #[tokio::test] + async fn explicit_folder_open_promotes_project_while_selection_and_legacy_upgrade_preserve_order( + ) { + let env = TestEnvironment::new(); + let service = build_test_workspace_service(env.path_manager.clone()).await; + service.ensure_assistant_workspaces().await.unwrap(); + let assistant_id = service.get_opened_workspaces().await[0].id.clone(); + + let project_a_dir = env.create_workspace_dir("project-a"); + let project_b_dir = env.create_workspace_dir("project-b"); + let project_a = service.open_workspace(project_a_dir.clone()).await.unwrap(); + let project_b = service.open_workspace(project_b_dir.clone()).await.unwrap(); + + let opened_ids = + |list: Vec| list.into_iter().map(|w| w.id).collect::>(); + assert_eq!( + opened_ids(service.get_opened_workspaces().await), + vec![ + assistant_id.clone(), + project_b.id.clone(), + project_a.id.clone() + ] + ); + + // Selecting by ID and legacy path-only upgrade must keep existing order. + service.open_workspace_by_id(&project_a.id).await.unwrap(); + assert_eq!( + opened_ids(service.get_opened_workspaces().await), + vec![ + assistant_id.clone(), + project_b.id.clone(), + project_a.id.clone() + ] + ); + service + .upgrade_legacy_workspace_open(project_a_dir.clone(), None, None) + .await + .unwrap(); + assert_eq!( + opened_ids(service.get_opened_workspaces().await), + vec![ + assistant_id.clone(), + project_b.id.clone(), + project_a.id.clone() + ] + ); + + // Explicit open promotes the project to the first project slot and persists it. + service.open_workspace(project_a_dir).await.unwrap(); + assert_eq!( + opened_ids(service.get_opened_workspaces().await), + vec![ + assistant_id.clone(), + project_a.id.clone(), + project_b.id.clone() + ] + ); + let saved: WorkspacePersistenceData = service + .persistence + .load_json("workspace_data") + .await + .unwrap() + .unwrap(); + assert_eq!( + saved.opened_workspace_ids, + vec![assistant_id, project_a.id, project_b.id] + ); + } } fn workspace_catalog_revision() -> &'static tokio::sync::watch::Sender { diff --git a/src/web-ui/src/infrastructure/api/service-api/GlobalAPI.ts b/src/web-ui/src/infrastructure/api/service-api/GlobalAPI.ts index 8c066aaa2e..cdb21356b7 100644 --- a/src/web-ui/src/infrastructure/api/service-api/GlobalAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/GlobalAPI.ts @@ -96,6 +96,12 @@ export interface OpenRemoteWorkspaceOptions { * connection to this connection. */ rebindConnection?: boolean; + /** + * Move a record this device already has open to the front of its section. + * Explicit selections keep the default (`true`); background restore passes + * `false` so reconnecting never rearranges the sidebar. + */ + promoteIfOpened?: boolean; } export interface UpdateAppStatusRequest { @@ -233,6 +239,7 @@ export class GlobalAPI { connectionName, ...(h ? { sshHost: h } : {}), ...(options.rebindConnection ? { rebindConnection: true } : {}), + ...(options.promoteIfOpened === false ? { promoteIfOpened: false } : {}), }, }); } catch (error) { diff --git a/src/web-ui/src/infrastructure/peer-device/deviceWorkspaceCatalog.ts b/src/web-ui/src/infrastructure/peer-device/deviceWorkspaceCatalog.ts index 6e17c61f2d..0559a860e9 100644 --- a/src/web-ui/src/infrastructure/peer-device/deviceWorkspaceCatalog.ts +++ b/src/web-ui/src/infrastructure/peer-device/deviceWorkspaceCatalog.ts @@ -38,7 +38,7 @@ import { } from './deviceSurface'; import { observeSurfaceEvents } from './deviceSurfaceRouting'; import { acknowledgeOnDevice, deviceCatalogLocalTransport, invokeOnDevice } from './deviceCatalogTransport'; -import { stableWorkspaceOrder } from '@/infrastructure/services/business/workspaceDisplayOrder'; +import { setWorkspaceDisplayOrder } from '@/infrastructure/services/business/workspaceDisplayOrder'; import { getDeviceOpenIntent, useDeviceOpenIntent } from './deviceOpenIntent'; const log = createLogger('DeviceWorkspaceCatalog'); @@ -499,9 +499,8 @@ export class DeviceWorkspaceCatalog { this.io.invoke(entry.deviceId, 'get_opened_workspaces', { request: {} }), ]); if (!this.isCurrent(entry)) return; - // The same display order the live list of this device uses. - const workspaces = stableWorkspaceOrder(entry.surfaceId, - upgradeLegacyWorktreeReferences(Array.isArray(raw) ? raw : []).map(mapWorkspaceInfo)); + const workspaces = upgradeLegacyWorktreeReferences(Array.isArray(raw) ? raw : []).map(mapWorkspaceInfo); + setWorkspaceDisplayOrder(entry.surfaceId, workspaces.map(workspace => workspace.id)); const opened = new Set(workspaces.map(workspace => workspace.id)); const sessions = Object.fromEntries(Object.entries(entry.snapshot.sessions) .filter(([workspaceId]) => opened.has(workspaceId))); diff --git a/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.test.ts b/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.test.ts index 7e03e0c985..05bf4277e6 100644 --- a/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.test.ts +++ b/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.test.ts @@ -1,99 +1,72 @@ import { afterEach, describe, expect, it } from 'vitest'; import { + clearPendingWorkspaceReveal, + consumeWorkspaceReveal, + getPendingWorkspaceReveal, getWorkspaceDisplayOrderRevision, - noteWorkspaceActivated, - noteWorkspaceOrderPersisted, orderWorkspacesForDisplay, + prepareWorkspacePromotion, + requestWorkspaceReveal, resetWorkspaceDisplayOrdersForTest, setWorkspaceDisplayOrder, - stableWorkspaceOrder, + subscribeWorkspacePromotionSnapshot, + subscribeWorkspaceReveal, } from './workspaceDisplayOrder'; const list = (...ids: string[]) => ids.map(id => ({ id })); const ids = (items: Array<{ id: string }>) => items.map(item => item.id); -describe('stableWorkspaceOrder', () => { +describe('workspaceDisplayOrder', () => { afterEach(resetWorkspaceDisplayOrdersForTest); - it('keeps the shown order when an older host moves the active workspace to the front', () => { - expect(ids(stableWorkspaceOrder('peer', list('openbitfun', 'repos')))).toEqual(['openbitfun', 'repos']); - // Activating repos on the host reordered its list. - expect(ids(stableWorkspaceOrder('peer', list('repos', 'openbitfun')))).toEqual(['openbitfun', 'repos']); - }); - - it('places a new workspace where the host put it and drops closed ones', () => { - stableWorkspaceOrder('peer', list('a', 'b', 'c')); - expect(ids(stableWorkspaceOrder('peer', list('new', 'c', 'a')))).toEqual(['new', 'a', 'c']); - }); - - it('keeps devices independent and lets an explicit reorder replace the order', () => { - stableWorkspaceOrder('local', list('a', 'b')); - stableWorkspaceOrder('peer', list('b', 'a')); - setWorkspaceDisplayOrder('local', ['b', 'a']); - expect(ids(stableWorkspaceOrder('local', list('a', 'b')))).toEqual(['b', 'a']); - expect(ids(stableWorkspaceOrder('peer', list('a', 'b')))).toEqual(['b', 'a']); - }); - - it('adopts an order the host was arranged into on purpose', () => { - stableWorkspaceOrder('peer', list('a', 'b', 'c', 'd')); - // Another controller reordered the host: more than a move to the front. - expect(ids(stableWorkspaceOrder('peer', list('b', 'a', 'd', 'c')))).toEqual(['b', 'a', 'd', 'c']); - expect(ids(stableWorkspaceOrder('peer', list('c', 'b', 'a', 'd')))).toEqual(['b', 'a', 'd', 'c']); - }); - - it('keeps the shown order through several activations an older host collected while the device was rendered', () => { - // Live list and catalog of one device, an older host that moves the - // active workspace to the front. - stableWorkspaceOrder('peer', list('assistant', 'herdr', 'openbitfun')); - // Rendered: the live list activates two workspaces and keeps showing its - // order; the catalog is not re-read meanwhile. - noteWorkspaceActivated('peer', 'openbitfun'); - expect(ids(stableWorkspaceOrder('peer', list('assistant', 'herdr', 'openbitfun')))).toEqual(['assistant', 'herdr', 'openbitfun']); - noteWorkspaceActivated('peer', 'herdr'); - // Left: the catalog reads the host's drifted list. - expect(ids(stableWorkspaceOrder('peer', list('herdr', 'openbitfun', 'assistant')))).toEqual(['assistant', 'herdr', 'openbitfun']); - // Rendered again: the live list's next read agrees, so nothing flips back. - expect(ids(stableWorkspaceOrder('peer', list('herdr', 'openbitfun', 'assistant')))).toEqual(['assistant', 'herdr', 'openbitfun']); - }); - - it('judges a read against the host order seen last, not only the shown one', () => { - stableWorkspaceOrder('peer', list('a', 'b', 'c')); - // Another controller activated c, then b. - expect(ids(stableWorkspaceOrder('peer', list('c', 'a', 'b')))).toEqual(['a', 'b', 'c']); - expect(ids(stableWorkspaceOrder('peer', list('b', 'c', 'a')))).toEqual(['a', 'b', 'c']); - }); - - it('orders an earlier list by the shown order without changing it', () => { - stableWorkspaceOrder('peer', list('a', 'b')); + it('orders cached lists by the latest recorded surface order without mutating state', () => { setWorkspaceDisplayOrder('peer', ['b', 'a']); const revision = getWorkspaceDisplayOrderRevision(); + expect(ids(orderWorkspacesForDisplay('peer', list('a', 'new', 'b')))).toEqual(['new', 'b', 'a']); expect(ids(orderWorkspacesForDisplay('other', list('a', 'b')))).toEqual(['a', 'b']); expect(getWorkspaceDisplayOrderRevision()).toBe(revision); - expect(ids(stableWorkspaceOrder('peer', list('a', 'b')))).toEqual(['b', 'a']); }); - it('preserves an unpersisted local promotion across activations on a static-order host', () => { - stableWorkspaceOrder('peer', list('assistant', 'a', 'b', 'c')); - // Promotion updated shown order, while persistence failed on the host. - setWorkspaceDisplayOrder('peer', ['assistant', 'b', 'a', 'c']); - noteWorkspaceActivated('peer', 'c'); - noteWorkspaceActivated('peer', 'a'); + it('keeps device surfaces independent and bumps revision only when the order changes', () => { + setWorkspaceDisplayOrder('local', ['a', 'b']); + setWorkspaceDisplayOrder('peer', ['b', 'a']); + const revision = getWorkspaceDisplayOrderRevision(); - // A static-order host still returns its original order on refresh. - expect(ids(stableWorkspaceOrder('peer', list('assistant', 'a', 'b', 'c')))) - .toEqual(['assistant', 'b', 'a', 'c']); - // Deliberate multi-row reorder on another controller is still adopted. - expect(ids(stableWorkspaceOrder('peer', list('assistant', 'c', 'b', 'a')))) - .toEqual(['assistant', 'c', 'b', 'a']); + setWorkspaceDisplayOrder('local', ['a', 'b']); + expect(getWorkspaceDisplayOrderRevision()).toBe(revision); + + setWorkspaceDisplayOrder('local', ['b', 'a']); + expect(getWorkspaceDisplayOrderRevision()).toBe(revision + 1); + expect(ids(orderWorkspacesForDisplay('local', list('a', 'b')))).toEqual(['b', 'a']); + expect(ids(orderWorkspacesForDisplay('peer', list('a', 'b')))).toEqual(['b', 'a']); }); - it('adopts a deliberate external reorder after persisting a local reorder', () => { - stableWorkspaceOrder('local', list('assistant', 'a', 'b', 'c')); - setWorkspaceDisplayOrder('local', ['assistant', 'b', 'a', 'c']); - noteWorkspaceOrderPersisted('local', ['assistant', 'b', 'a', 'c']); + it('tracks promotion snapshots and per-surface reveal requests', () => { + const events: string[] = []; + const unsubscribeSnapshot = subscribeWorkspacePromotionSnapshot((surfaceId, workspaceId) => { + events.push(`snapshot:${surfaceId}:${workspaceId}`); + }); + const unsubscribeReveal = subscribeWorkspaceReveal(request => { + events.push(`reveal:${request.surfaceId}:${request.workspaceId}:${request.promoted}`); + }); + + prepareWorkspacePromotion('local', 'proj-b'); + const request = requestWorkspaceReveal('local', 'proj-b', true); + expect(events).toEqual([ + 'snapshot:local:proj-b', + 'reveal:local:proj-b:true', + ]); + expect(getPendingWorkspaceReveal('local')).toEqual(request); + + consumeWorkspaceReveal('local', request.token); + expect(getPendingWorkspaceReveal('local')).toBeUndefined(); + + requestWorkspaceReveal('peer', 'proj-c', false); + clearPendingWorkspaceReveal('peer'); + expect(getPendingWorkspaceReveal('peer')).toBeUndefined(); - expect(ids(stableWorkspaceOrder('local', list('assistant', 'a', 'c', 'b')))) - .toEqual(['assistant', 'a', 'c', 'b']); + unsubscribeSnapshot(); + unsubscribeReveal(); }); }); diff --git a/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.ts b/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.ts index e15b5a1d98..b58dd165bb 100644 --- a/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.ts +++ b/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.ts @@ -1,32 +1,16 @@ /** - * One display order of opened workspaces per device surface. + * Shared display-order and sidebar-reveal coordination per device surface. * - * Hosts before this change move a workspace to the front of their opened list - * whenever it becomes active, so every re-read (a device switch, a catalog - * refresh, another controller's activation) could reorder the sidebar. The - * window keeps the order it last showed for each device and applies it to - * every host list, live or background, so both projections of a device agree - * and activation never moves a row. Workspaces new to the list keep the place - * the host gave them relative to their neighbours; an explicit reorder - * replaces the order. A host order that differs by more than one workspace - * moved to the front was arranged on purpose (a reorder on another - * controller), so the window adopts it. - * - * "One workspace moved to the front" is judged against the shown order and - * against the host's own last order. While a device is rendered its catalog is - * not re-read, so an older host can collect several activations between two - * reads; comparing only with the shown order took that drift for a deliberate - * arrangement, and the live list and the catalog then kept adopting each - * other's order on every switch. The host order is therefore remembered too, - * and activations this window asks for are applied to it the way an older - * host applies them (`noteWorkspaceActivated`). + * The backend `WorkspaceManager` owns workspace order: ordinary activation + * preserves positions, while explicit folder opens place projects at the front + * of the project section. On the frontend, the live rendered surface + * (`WorkspaceManager`) and background device sections (`DeviceWorkspaceCatalog`) + * read `get_opened_workspaces` at different times across device switches; + * recording the latest authoritative order per surface lets cached hand-overs + * render without moving rows. */ const orders = new Map(); -/** The host's own order as last seen, with this window's activations applied. */ -const hostOrders = new Map(); -/** The literal order last observed from the host, without speculative activation moves. */ -const lastSeenHostOrders = new Map(); const listeners = new Set<() => void>(); let revision = 0; @@ -55,13 +39,6 @@ export function setWorkspaceDisplayOrder(surfaceId: string, workspaceIds: readon for (const listener of Array.from(listeners)) listener(); } -/** Record an order the host just accepted and persisted. */ -export function noteWorkspaceOrderPersisted(surfaceId: string, workspaceIds: readonly string[]): void { - const snapshot = [...workspaceIds]; - hostOrders.set(surfaceId, snapshot); - lastSeenHostOrders.set(surfaceId, snapshot); -} - /** Changes whenever a surface's display order changes (for `useSyncExternalStore`). */ export function getWorkspaceDisplayOrderRevision(): number { return revision; @@ -138,92 +115,26 @@ export function subscribeWorkspaceRevealState(listener: () => void): () => void } /** - * This window activated `workspaceId` on the surface's host. An older host - * moves it to the front of its opened list; a newer one keeps its place, which - * still matches `lastSeenHostOrders`. - */ -export function noteWorkspaceActivated(surfaceId: string, workspaceId: string): void { - const host = hostOrders.get(surfaceId); - if (!host?.includes(workspaceId)) return; - hostOrders.set(surfaceId, [workspaceId, ...host.filter(id => id !== workspaceId)]); -} - -export function stableWorkspaceOrder(surfaceId: string, hostWorkspaces: readonly T[]): T[] { - const remembered = orders.get(surfaceId); - const hostIds = hostWorkspaces.map(workspace => workspace.id); - if (!remembered) { - setWorkspaceDisplayOrder(surfaceId, hostIds); - hostOrders.set(surfaceId, hostIds); - lastSeenHostOrders.set(surfaceId, hostIds); - return [...hostWorkspaces]; - } - // Both sides restricted to the workspaces they share. - const common = (previous: readonly string[]) => [ - previous.filter(id => hostIds.includes(id)), hostIds.filter(id => previous.includes(id)), - ] as const; - const [shown, listed] = common(remembered); - const lastHost = hostOrders.get(surfaceId); - const lastSeenHost = lastSeenHostOrders.get(surfaceId); - if ( - !isActivationReorder(shown, listed) - && !(lastHost && isActivationReorder(...common(lastHost))) - && !(lastSeenHost && isActivationReorder(...common(lastSeenHost))) - ) { - setWorkspaceDisplayOrder(surfaceId, hostIds); - hostOrders.set(surfaceId, hostIds); - lastSeenHostOrders.set(surfaceId, hostIds); - return [...hostWorkspaces]; - } - // A list already in the shown order says nothing about the host (the live - // list passes the order it shows on activation); keep the host order seen last. - if (!sameIds(shown, listed)) { - hostOrders.set(surfaceId, hostIds); - lastSeenHostOrders.set(surfaceId, hostIds); - } - const result = mergeIntoOrder(remembered, hostWorkspaces); - setWorkspaceDisplayOrder(surfaceId, result.map(workspace => workspace.id)); - return result; -} - -/** - * `workspaces` in the surface's remembered order, without changing it. For - * lists read earlier (a cached catalog, the last live list) that must look the - * same as the list now shown for the device. + * `workspaces` ordered by the surface's latest authoritative order, without + * mutating stored state. Used during live/background cached hand-overs. */ export function orderWorkspacesForDisplay(surfaceId: string, workspaces: readonly T[]): T[] { const remembered = orders.get(surfaceId); - return remembered ? mergeIntoOrder(remembered, workspaces) : [...workspaces]; -} - -/** `remembered` order of `hostWorkspaces`; new ones keep the host's place among their neighbours. */ -function mergeIntoOrder(remembered: readonly string[], hostWorkspaces: readonly T[]): T[] { - const byId = new Map(hostWorkspaces.map(workspace => [workspace.id, workspace])); + if (!remembered) return [...workspaces]; + const byId = new Map(workspaces.map(workspace => [workspace.id, workspace])); const result: T[] = remembered.flatMap(id => (byId.has(id) ? [byId.get(id)!] : [])); const placed = new Set(result.map(workspace => workspace.id)); - hostWorkspaces.forEach((workspace, hostIndex) => { + workspaces.forEach((workspace, index) => { if (placed.has(workspace.id)) return; - // Before every shown workspace the host lists after it, else at the end. - const after = new Set(hostWorkspaces.slice(hostIndex + 1).map(candidate => candidate.id)); + const after = new Set(workspaces.slice(index + 1).map(candidate => candidate.id)); const first = result.findIndex(candidate => after.has(candidate.id)); - const index = first === -1 ? result.length : first; - result.splice(index, 0, workspace); + result.splice(first === -1 ? result.length : first, 0, workspace); placed.add(workspace.id); }); return result; } -/** `host` equals `shown`, or is `shown` with one workspace moved to the front. */ -function isActivationReorder(shown: readonly string[], host: readonly string[]): boolean { - if (shown.length !== host.length) return false; - if (sameIds(shown, host)) return true; - const moved = host[0]; - const rest = shown.filter(id => id !== moved); - return rest.every((id, index) => id === host[index + 1]); -} - export function resetWorkspaceDisplayOrdersForTest(): void { orders.clear(); - hostOrders.clear(); - lastSeenHostOrders.clear(); pendingReveals.clear(); } diff --git a/src/web-ui/src/infrastructure/services/business/workspaceManager.test.ts b/src/web-ui/src/infrastructure/services/business/workspaceManager.test.ts index 210be36d7d..1395de3b4f 100644 --- a/src/web-ui/src/infrastructure/services/business/workspaceManager.test.ts +++ b/src/web-ui/src/infrastructure/services/business/workspaceManager.test.ts @@ -697,14 +697,14 @@ describe('WorkspaceManager device surface switching', () => { // While another device is rendered, this device's catalog reads a list // arranged on another controller. - expect(displayOrder.stableWorkspaceOrder(deviceSurface.LOCAL_SURFACE_ID, [c, b, a]).map(item => item.id)).toEqual(['c', 'b', 'a']); + displayOrder.setWorkspaceDisplayOrder(deviceSurface.LOCAL_SURFACE_ID, ['c', 'b', 'a']); // The background section's fallback and the live list returned to both // draw that order; the live list's next host read keeps it. expect(manager.getSurfaceOpenedWorkspaces(deviceSurface.LOCAL_SURFACE_ID).map(item => item.id)).toEqual(['c', 'b', 'a']); deviceSurface.activateSurface(deviceSurface.LOCAL_SURFACE_ID); expect([...manager.getState().openedWorkspaces.keys()]).toEqual(['c', 'b', 'a']); globalStateMocks.setActiveWorkspace.mockResolvedValue(b); - globalStateMocks.getOpenedWorkspaces.mockResolvedValue([b, c, a]); + globalStateMocks.getOpenedWorkspaces.mockResolvedValue([c, b, a]); await manager.setActiveWorkspace(b.id); await flushAsyncWork(); expect([...manager.getState().openedWorkspaces.keys()]).toEqual(['c', 'b', 'a']); @@ -1170,11 +1170,12 @@ describe('WorkspaceManager openWorkspace promotion', () => { globalStateMocks.reorderOpenedWorkspaces.mockResolvedValue(undefined); }); - it('moves an already-opened local workspace to the top of the current device list', async () => { + it('adopts the backend-promoted order for an already-opened local workspace without a second reorder RPC', async () => { const manager = await getFreshWorkspaceManager(); await manager.initialize(); globalStateMocks.openWorkspace.mockResolvedValue(workspaceB); + globalStateMocks.getOpenedWorkspaces.mockResolvedValue([workspaceB, workspaceA, workspaceC]); await manager.openWorkspace(workspaceB.rootPath); expect(Array.from(manager.getState().openedWorkspaces.keys())).toEqual([ @@ -1182,18 +1183,15 @@ describe('WorkspaceManager openWorkspace promotion', () => { workspaceA.id, workspaceC.id, ]); - expect(globalStateMocks.reorderOpenedWorkspaces).toHaveBeenCalledWith([ - workspaceB.id, - workspaceA.id, - workspaceC.id, - ]); + expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled(); }); - it('moves an already-opened remote workspace to the top of the current device list', async () => { + it('adopts the backend-promoted order for an already-opened remote workspace without a second reorder RPC', async () => { const manager = await getFreshWorkspaceManager(); await manager.initialize(); globalStateMocks.openRemoteWorkspace.mockResolvedValue(workspaceC); + globalStateMocks.getOpenedWorkspaces.mockResolvedValue([workspaceC, workspaceA, workspaceB]); await manager.openRemoteWorkspace({ connectionId: 'conn-1', connectionName: 'Remote', @@ -1205,54 +1203,7 @@ describe('WorkspaceManager openWorkspace promotion', () => { workspaceA.id, workspaceB.id, ]); - expect(globalStateMocks.reorderOpenedWorkspaces).toHaveBeenCalledWith([ - workspaceC.id, - workspaceA.id, - workspaceB.id, - ]); - }); - - it('keeps the promoted display order even if host reorder persistence fails and survives later switches', async () => { - const assistant = { ...workspaceA, id: 'assistant', rootPath: '/assistant', workspaceKind: 'assistant' }; - const hostList = [assistant, workspaceA, workspaceB, workspaceC]; - globalStateMocks.initializeWorkspaceStartupState.mockResolvedValue({ - cleanupRemovedCount: 0, - recentWorkspaces: hostList, - openedWorkspaces: hostList, - currentWorkspace: workspaceA, - legacyRemoteWorkspace: null, - }); - globalStateMocks.getOpenedWorkspaces.mockResolvedValue(hostList); - - const manager = await getFreshWorkspaceManager(); - await manager.initialize(); - - globalStateMocks.openWorkspace.mockResolvedValue(workspaceB); - globalStateMocks.reorderOpenedWorkspaces.mockRejectedValue(new Error('unsupported on older cli peer')); - - await manager.openWorkspace(workspaceB.rootPath); - await flushAsyncWork(); - - expect(Array.from(manager.getState().openedWorkspaces.keys())).toEqual([ - assistant.id, - workspaceB.id, - workspaceA.id, - workspaceC.id, - ]); - expect(manager.getState().error).toBeNull(); - - // Switching to another workspace refreshes against the unpersisted host list - // without reverting the promoted display order. - globalStateMocks.setActiveWorkspace.mockResolvedValue(workspaceC); - await manager.setActiveWorkspace(workspaceC.id); - await flushAsyncWork(); - - expect(Array.from(manager.getState().openedWorkspaces.keys())).toEqual([ - assistant.id, - workspaceB.id, - workspaceA.id, - workspaceC.id, - ]); + expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled(); }); it('keeps local and peer display orders independent, including identical workspace IDs', async () => { @@ -1268,9 +1219,9 @@ describe('WorkspaceManager openWorkspace promotion', () => { legacyRemoteWorkspace: null, }); await manager.initialize(); - globalStateMocks.getOpenedWorkspaces.mockResolvedValue([workspaceC, workspaceA, workspaceB]); globalStateMocks.openWorkspace.mockResolvedValue(workspaceB); + globalStateMocks.getOpenedWorkspaces.mockResolvedValue([workspaceB, workspaceC, workspaceA]); await manager.openWorkspace(workspaceB.rootPath); expect(Array.from(manager.getState().openedWorkspaces.keys())).toEqual([ @@ -1288,22 +1239,12 @@ describe('WorkspaceManager openWorkspace promotion', () => { .toEqual([workspaceB.id, workspaceC.id, workspaceA.id]); }); - it('resolves openWorkspace without blocking on reorder persistence and defers catalog resync until it settles', async () => { - let catalogHandler: ((event: { payload: Record }) => void) | null = null; - listenMock.mockImplementation((eventName, callback) => { - if (eventName === 'workspace-catalog-changed') { - catalogHandler = callback; - } - return Promise.resolve(() => undefined); - }); + it('snapshots pre-promotion geometry before state updates and emits reveal afterwards', async () => { const { manager, displayOrder } = await getFreshWorkspaceHarness(); await manager.initialize(); - let finishReorder!: () => void; - globalStateMocks.reorderOpenedWorkspaces.mockReturnValueOnce( - new Promise(resolve => { finishReorder = resolve; }), - ); globalStateMocks.openWorkspace.mockResolvedValue(workspaceB); + globalStateMocks.getOpenedWorkspaces.mockResolvedValue([workspaceB, workspaceA, workspaceC]); const steps: string[] = []; displayOrder.subscribeWorkspacePromotionSnapshot((_surfaceId, workspaceId) => { steps.push(`snapshot:${workspaceId}`); @@ -1316,7 +1257,6 @@ describe('WorkspaceManager openWorkspace promotion', () => { }); manager.addEventListener(event => { steps.push(event.type); }); - // Does not block on `reorderOpenedWorkspaces`. const opened = await manager.openWorkspace(workspaceB.rootPath); expect(opened).toBe(workspaceB); expect(Array.from(manager.getState().openedWorkspaces.keys())) @@ -1328,55 +1268,16 @@ describe('WorkspaceManager openWorkspace promotion', () => { 'workspace:opened', `reveal:${workspaceB.id}:true`, ]); - expect(globalStateMocks.reorderOpenedWorkspaces).toHaveBeenCalledTimes(1); - - // A catalog hint arriving mid-persistence does not race `reorderOpenedWorkspaces`. - globalStateMocks.getOpenedWorkspaces.mockClear(); - globalStateMocks.getOpenedWorkspaces.mockResolvedValue([workspaceB, workspaceA, workspaceC]); - catalogHandler?.({ payload: { revision: 2 } }); - await flushAsyncWork(); - expect(globalStateMocks.getOpenedWorkspaces).not.toHaveBeenCalled(); - - finishReorder(); - await flushAsyncWork(); - expect(globalStateMocks.getOpenedWorkspaces).toHaveBeenCalledTimes(1); + expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled(); }); - it.each(['local', 'remote'] as const)( - 'keeps a %s promotion on its own device when the device changes during persistence', - async kind => { - const { manager, deviceSurface } = await getFreshWorkspaceHarness(); - await manager.initialize(); - let finishReorder!: () => void; - const reordered = new Promise(resolve => { finishReorder = resolve; }); - globalStateMocks.reorderOpenedWorkspaces.mockReturnValueOnce(reordered); - globalStateMocks.openWorkspace.mockResolvedValue(workspaceB); - globalStateMocks.openRemoteWorkspace.mockResolvedValue(workspaceC); - const promotedId = kind === 'local' ? workspaceB.id : workspaceC.id; - - const opened = await (kind === 'local' - ? manager.openWorkspace(workspaceB.rootPath) - : manager.openRemoteWorkspace({ - connectionId: 'conn-1', connectionName: 'Remote', remotePath: workspaceC.rootPath, - })); - expect(opened.id).toBe(promotedId); - expect(globalStateMocks.reorderOpenedWorkspaces).toHaveBeenCalledTimes(1); - - deviceSurface.activateSurface('peer-b'); - finishReorder(); - await flushAsyncWork(); - - expect(manager.getState().openedWorkspaces.size).toBe(0); - expect(manager.getState().currentWorkspace).toBeNull(); - expect(manager.getState().error).toBeNull(); - expect(manager.getSurfaceOpenedWorkspaces(deviceSurface.LOCAL_SURFACE_ID)[0]?.id).toBe(promotedId); - }, - ); - - it('never sends reorder persistence to a new device switched inside a workspace:opened listener', async () => { - const { manager, deviceSurface } = await getFreshWorkspaceHarness(); + it('does not leak reveal requests onto a new device switched inside a workspace:opened listener', async () => { + const { manager, deviceSurface, displayOrder } = await getFreshWorkspaceHarness(); await manager.initialize(); globalStateMocks.openWorkspace.mockResolvedValue(workspaceB); + globalStateMocks.getOpenedWorkspaces.mockResolvedValue([workspaceB, workspaceA, workspaceC]); + const reveals: string[] = []; + displayOrder.subscribeWorkspaceReveal(request => { reveals.push(request.surfaceId); }); manager.addEventListener(event => { if (event.type === 'workspace:opened') { @@ -1387,7 +1288,7 @@ describe('WorkspaceManager openWorkspace promotion', () => { await manager.openWorkspace(workspaceB.rootPath); await flushAsyncWork(); - expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled(); + expect(reveals).toEqual([]); expect(manager.getSurfaceOpenedWorkspaces(deviceSurface.LOCAL_SURFACE_ID)[0]?.id).toBe(workspaceB.id); expect(manager.getState().openedWorkspaces.size).toBe(0); }); @@ -1405,7 +1306,7 @@ describe('WorkspaceManager openWorkspace promotion', () => { expect(manager.getState().error).toBeNull(); }); - it('does not promote or persist a reorder when opening an assistant directory', async () => { + it('does not snapshot promotion or emit reveal when opening an assistant directory', async () => { const assistantA = { ...workspaceA, id: 'assistant-a', rootPath: '/assistant/a', workspaceKind: 'assistant' }; const assistantB = { ...workspaceA, id: 'assistant-b', rootPath: '/assistant/b', workspaceKind: 'assistant' }; const opened = [assistantA, assistantB, workspaceA]; @@ -1432,36 +1333,7 @@ describe('WorkspaceManager openWorkspace promotion', () => { expect(reveals).toEqual([]); }); - it('does not promote a new workspace that a concurrent list refresh published first', async () => { - const manager = await getFreshWorkspaceManager(); - await manager.initialize(); - const added = { ...workspaceA, id: 'workspace-new', rootPath: '/repo/new' }; - const hostOpened = [workspaceA, workspaceB, workspaceC, added]; - - // A switch whose background list refresh is still in flight. - let releaseRefresh!: (workspaces: typeof hostOpened) => void; - globalStateMocks.setActiveWorkspace.mockResolvedValue(workspaceB); - globalStateMocks.getOpenedWorkspaces.mockImplementationOnce( - () => new Promise(resolve => { releaseRefresh = resolve; }), - ); - await manager.setActiveWorkspace(workspaceB.id); - - globalStateMocks.getOpenedWorkspaces.mockResolvedValue(hostOpened); - globalStateMocks.openWorkspace.mockImplementation(async () => { - releaseRefresh(hostOpened); - await flushAsyncWork(); - expect(manager.getState().openedWorkspaces.has(added.id)).toBe(true); - return added; - }); - - await manager.openWorkspace(added.rootPath); - - expect(Array.from(manager.getState().openedWorkspaces.keys())) - .toEqual([workspaceA.id, workspaceB.id, workspaceC.id, added.id]); - expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled(); - }); - - it('promotes within the project section and leaves the assistant slot alone', async () => { + it('detects promotion within the project section while leaving the assistant slot alone', async () => { const assistant = { ...workspaceA, id: 'assistant', rootPath: '/assistant', workspaceKind: 'assistant' }; const opened = [assistant, workspaceA, workspaceB]; globalStateMocks.initializeWorkspaceStartupState.mockResolvedValue({ @@ -1472,24 +1344,33 @@ describe('WorkspaceManager openWorkspace promotion', () => { legacyRemoteWorkspace: null, }); globalStateMocks.getOpenedWorkspaces.mockResolvedValue(opened); - const manager = await getFreshWorkspaceManager(); + const { manager, displayOrder } = await getFreshWorkspaceHarness(); await manager.initialize(); + const reveals: Array<{ id: string; promoted: boolean }> = []; + displayOrder.subscribeWorkspaceReveal(req => { + reveals.push({ id: req.workspaceId, promoted: req.promoted }); + }); globalStateMocks.openWorkspace.mockResolvedValue(workspaceA); await manager.openWorkspace(workspaceA.rootPath); - expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled(); globalStateMocks.openWorkspace.mockResolvedValue(workspaceB); + globalStateMocks.getOpenedWorkspaces.mockResolvedValue([assistant, workspaceB, workspaceA]); await manager.openWorkspace(workspaceB.rootPath); expect(Array.from(manager.getState().openedWorkspaces.keys())) .toEqual([assistant.id, workspaceB.id, workspaceA.id]); - expect(globalStateMocks.reorderOpenedWorkspaces) - .toHaveBeenCalledWith([assistant.id, workspaceB.id, workspaceA.id]); + expect(reveals).toEqual([ + { id: workspaceA.id, promoted: false }, + { id: workspaceB.id, promoted: true }, + ]); + expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled(); }); - it('does not move a remote record that a background restore reopens', async () => { - const manager = await getFreshWorkspaceManager(); + it('forwards promoteIfOpened: false on background remote restore and skips reveal', async () => { + const { manager, displayOrder } = await getFreshWorkspaceHarness(); await manager.initialize(); + const reveals: string[] = []; + displayOrder.subscribeWorkspaceReveal(req => { reveals.push(req.workspaceId); }); globalStateMocks.openRemoteWorkspace.mockResolvedValue(workspaceC); await manager.openRemoteWorkspace({ @@ -1498,27 +1379,18 @@ describe('WorkspaceManager openWorkspace promotion', () => { expect(Array.from(manager.getState().openedWorkspaces.keys())) .toEqual([workspaceA.id, workspaceB.id, workspaceC.id]); - expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled(); - // The manager-only flag never reaches the host. - expect(globalStateMocks.openRemoteWorkspace.mock.calls[0][4]).toEqual({}); - }); - - it('does not persist a reorder when the workspace is already first', async () => { - const manager = await getFreshWorkspaceManager(); - await manager.initialize(); - globalStateMocks.openWorkspace.mockResolvedValue(workspaceA); - - await manager.openWorkspace(workspaceA.rootPath); - - expect(Array.from(manager.getState().openedWorkspaces.keys())) - .toEqual([workspaceA.id, workspaceB.id, workspaceC.id]); - expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled(); + expect(reveals).toEqual([]); + expect(globalStateMocks.openRemoteWorkspace.mock.calls[0][4]).toEqual({ promoteIfOpened: false }); }); - it('keeps the host insertion order for a newly opened workspace', async () => { - const manager = await getFreshWorkspaceManager(); + it('reveals without promotion motion for a newly opened workspace', async () => { + const { manager, displayOrder } = await getFreshWorkspaceHarness(); await manager.initialize(); const added = { ...workspaceA, id: 'workspace-new', rootPath: '/repo/new' }; + const reveals: Array<{ id: string; promoted: boolean }> = []; + displayOrder.subscribeWorkspaceReveal(req => { + reveals.push({ id: req.workspaceId, promoted: req.promoted }); + }); globalStateMocks.openWorkspace.mockResolvedValue(added); globalStateMocks.getOpenedWorkspaces.mockResolvedValue([added, workspaceA, workspaceB, workspaceC]); @@ -1526,6 +1398,7 @@ describe('WorkspaceManager openWorkspace promotion', () => { expect(Array.from(manager.getState().openedWorkspaces.keys())) .toEqual([added.id, workspaceA.id, workspaceB.id, workspaceC.id]); + expect(reveals).toEqual([{ id: added.id, promoted: false }]); expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled(); }); }); diff --git a/src/web-ui/src/infrastructure/services/business/workspaceManager.ts b/src/web-ui/src/infrastructure/services/business/workspaceManager.ts index 8323971f05..ce72939e40 100644 --- a/src/web-ui/src/infrastructure/services/business/workspaceManager.ts +++ b/src/web-ui/src/infrastructure/services/business/workspaceManager.ts @@ -2,13 +2,10 @@ import { clearPendingWorkspaceReveal, - noteWorkspaceActivated, - noteWorkspaceOrderPersisted, orderWorkspacesForDisplay, prepareWorkspacePromotion, requestWorkspaceReveal, setWorkspaceDisplayOrder, - stableWorkspaceOrder, } from './workspaceDisplayOrder'; import type { RemoteWorkspaceSnapshot, @@ -108,14 +105,7 @@ export interface WorkspaceState { export type WorkspaceSection = 'all' | 'assistants' | 'projects'; -export interface OpenRemoteWorkspaceRequestOptions extends OpenRemoteWorkspaceOptions { - /** - * Move a record this device already has open to the front of its section. - * Explicit selections keep the default; background restore passes false so - * reconnecting never rearranges the sidebar. - */ - promoteIfOpened?: boolean; -} +export type OpenRemoteWorkspaceRequestOptions = OpenRemoteWorkspaceOptions; export type WorkspaceReorderPosition = 'before' | 'after'; @@ -147,8 +137,6 @@ interface WorkspaceSurfaceContainer { catalogResyncInFlight: boolean; /** A catalog hint arrived while a re-read (or the bootstrap) was running. */ catalogResyncPending: boolean; - /** Background catalog mutations (e.g. order persistence) still running for this surface. */ - catalogMutationDepth: number; } function createWorkspaceSurfaceContainer(): WorkspaceSurfaceContainer { @@ -170,7 +158,6 @@ function createWorkspaceSurfaceContainer(): WorkspaceSurfaceContainer { startupLegacyRemoteWorkspace: null, catalogResyncInFlight: false, catalogResyncPending: false, - catalogMutationDepth: 0, }; } @@ -394,20 +381,6 @@ class WorkspaceManager { : workspace.workspaceKind !== 'assistant'; } - /** - * A host list in this surface's display order. The same order the device - * catalog applies, so the live list and the device's background projection - * never disagree (see `workspaceDisplayOrder`). Ordering by this window's - * previous list instead let the two projections adopt each other's order on - * every switch. - */ - private preserveOpenedWorkspaceOrder( - workspaces: WorkspaceInfo[], - surfaceId: DeviceSurfaceId = getActiveSurfaceId(), - ): WorkspaceInfo[] { - return stableWorkspaceOrder(surfaceId, workspaces); - } - private buildReorderedOpenedWorkspaceIds( section: WorkspaceSection, sourceWorkspaceId: string, @@ -489,13 +462,14 @@ class WorkspaceManager { loading: boolean, error: string | null, event?: WorkspaceEvent, - options?: { surfaceId?: DeviceSurfaceId; preordered?: boolean }, + options?: { surfaceId?: DeviceSurfaceId }, ): void { const surfaceId = options?.surfaceId ?? getActiveSurfaceId(); - // Every list a host returns is shown in this surface's one display order. - const openedWorkspaceMap = this.buildOpenedWorkspaceMap( - options?.preordered ? openedWorkspaces : stableWorkspaceOrder(surfaceId, openedWorkspaces), + setWorkspaceDisplayOrder( + surfaceId, + openedWorkspaces.map(workspace => workspace.id), ); + const openedWorkspaceMap = this.buildOpenedWorkspaceMap(openedWorkspaces); const resolvedCurrentWorkspace = currentWorkspace ? openedWorkspaceMap.get(currentWorkspace.id) ?? currentWorkspace @@ -751,7 +725,6 @@ class WorkspaceManager { !container.isInitialized || container.catalogResyncInFlight || container.state.loading - || container.catalogMutationDepth > 0 ) { // The bootstrap, the running re-read, or this surface's own workspace // operation may have started before this change; whichever finishes @@ -769,7 +742,6 @@ class WorkspaceManager { && container.isInitialized && !container.catalogResyncInFlight && !container.state.loading - && container.catalogMutationDepth === 0 ) { void this.resyncWorkspaceCatalog(container); } @@ -821,8 +793,11 @@ class WorkspaceManager { openedWorkspaces: WorkspaceInfo[], ): void { const previousOpened = this.state.openedWorkspaces; - const orderedOpened = this.preserveOpenedWorkspaceOrder(openedWorkspaces); - const nextOpened = this.buildOpenedWorkspaceMap(orderedOpened); + setWorkspaceDisplayOrder( + getActiveSurfaceId(), + openedWorkspaces.map(workspace => workspace.id), + ); + const nextOpened = this.buildOpenedWorkspaceMap(openedWorkspaces); const previousActiveId = this.state.activeWorkspaceId; const keptActive = previousActiveId ? nextOpened.get(previousActiveId) ?? null : null; @@ -830,7 +805,7 @@ class WorkspaceManager { ?? (hostCurrentWorkspace ? nextOpened.get(hostCurrentWorkspace.id) ?? null : null); const activeChanged = (currentWorkspace?.id ?? null) !== previousActiveId; - const openedNow = orderedOpened.filter(workspace => !previousOpened.has(workspace.id)); + const openedNow = openedWorkspaces.filter(workspace => !previousOpened.has(workspace.id)); const closedNow = Array.from(previousOpened.keys()).filter(id => !nextOpened.has(id)); this.updateState({ @@ -1087,84 +1062,47 @@ class WorkspaceManager { } /** - * Publish a workspace the host just opened. When the user explicitly added a - * project workspace this device already had open, it moves to the front of - * the project section (leaving pinned assistants in place) so the add has a - * visible effect. The order is shown immediately and persisted in the - * background; a host that cannot persist it keeps the shown order for this - * window. + * Publish a workspace the host just opened. The backend owns workspace + * ordering (explicit project opens move to the front of the project slots, + * while background restores preserve positions); when an existing project row + * moved to slot 0, mounted views snapshot pre-commit rects for FLIP motion + * and scroll the row into view after state updates. */ private publishOpenedWorkspace( surface: SurfaceCapture, - container: WorkspaceSurfaceContainer, workspace: WorkspaceInfo, recentWorkspaces: WorkspaceInfo[], openedWorkspaces: WorkspaceInfo[], - promote: boolean, reveal: boolean, ): void { const surfaceId = surface.scope.surfaceId; - const orderedOpened = this.preserveOpenedWorkspaceOrder(openedWorkspaces, surfaceId); const isProject = this.isWorkspaceInSection(workspace, 'projects'); - const firstProject = orderedOpened.find(item => this.isWorkspaceInSection(item, 'projects')); - const promotedIds = promote && isProject && firstProject && firstProject.id !== workspace.id - ? this.buildReorderedOpenedWorkspaceIds('projects', workspace.id, firstProject.id, 'before', orderedOpened) - : null; - - let finalOpened = orderedOpened; - if (promotedIds) { - const byId = this.buildOpenedWorkspaceMap(orderedOpened); - finalOpened = promotedIds - .map(id => byId.get(id)) - .filter((item): item is WorkspaceInfo => Boolean(item)); - setWorkspaceDisplayOrder(surfaceId, promotedIds); + const previousProjects = this.getOpenedWorkspacesList() + .filter(item => this.isWorkspaceInSection(item, 'projects')); + const nextProjects = openedWorkspaces + .filter(item => this.isWorkspaceInSection(item, 'projects')); + const previousProjectIndex = previousProjects.findIndex(item => item.id === workspace.id); + const wasPromoted = reveal + && isProject + && previousProjectIndex > 0 + && nextProjects[0]?.id === workspace.id; + + if (wasPromoted) { prepareWorkspacePromotion(surfaceId, workspace.id); - container.catalogMutationDepth += 1; } this.updateWorkspaceState( workspace, recentWorkspaces, - finalOpened, + openedWorkspaces, false, null, { type: 'workspace:opened', workspace }, - { surfaceId, preordered: true }, + { surfaceId }, ); if (reveal && isProject && this.isSurfaceUnchanged(surface)) { - requestWorkspaceReveal(surfaceId, workspace.id, Boolean(promotedIds)); - } - - if (promotedIds) { - void this.persistPromotedWorkspaceOrder(surface, container, workspace.id, promotedIds); - } - } - - private async persistPromotedWorkspaceOrder( - surface: SurfaceCapture, - container: WorkspaceSurfaceContainer, - workspaceId: string, - promotedIds: string[], - ): Promise { - try { - if (!this.isSurfaceUnchanged(surface)) { - return; - } - await globalStateAPI.reorderOpenedWorkspaces(promotedIds); - noteWorkspaceOrderPersisted(surface.scope.surfaceId, promotedIds); - } catch (error) { - if (!isSurfaceChangedError(error) && this.isSurfaceUnchanged(surface)) { - log.warn('Failed to persist promoted workspace order', { - workspaceId, - error, - }); - } - } finally { - container.catalogMutationDepth = Math.max(0, container.catalogMutationDepth - 1); - if (this.isSurfaceUnchanged(surface)) { - this.drainPendingCatalogResync(); - } + requestWorkspaceReveal(surfaceId, workspace.id, wasPromoted); } } @@ -1177,9 +1115,6 @@ class WorkspaceManager { const { promoteIfOpened = true } = options; const surface = this.captureSurface(); const container = this.surfaceContainer(surface.scope.surfaceId); - // Read before the host call: a list refresh that lands meanwhile may - // already contain a workspace this call is adding for the first time. - const openedBefore = new Set(this.state.openedWorkspaces.keys()); try { this.setLoading(true); this.setError(null); @@ -1197,11 +1132,9 @@ class WorkspaceManager { this.publishOpenedWorkspace( surface, - container, workspace, recentWorkspaces, openedWorkspaces, - promoteIfOpened && openedBefore.has(workspace.id), promoteIfOpened, ); @@ -1222,9 +1155,8 @@ class WorkspaceManager { } /** - * Open a local folder as a workspace. Every caller is an explicit user open, - * so a workspace this device already has open moves to the front of its - * section instead of the add appearing to do nothing. + * Open a local folder as a workspace. The backend places newly opened and + * explicitly re-opened project workspaces at the front of the project slots. */ public async openWorkspace(path: string): Promise { return this.runOpenWorkspaceFlow( @@ -1247,7 +1179,7 @@ class WorkspaceManager { remotePath: string; sshHost?: string; }, options: OpenRemoteWorkspaceRequestOptions = {}): Promise { - const { promoteIfOpened = true, ...hostOptions } = options; + const { promoteIfOpened = true } = options; return this.runOpenWorkspaceFlow( 'open remote workspace', { promoteIfOpened }, @@ -1259,7 +1191,7 @@ class WorkspaceManager { remoteWorkspace.connectionId, remoteWorkspace.connectionName, remoteWorkspace.sshHost, - hostOptions, + options, ); }, error => { @@ -1586,9 +1518,6 @@ class WorkspaceManager { : await globalStateAPI.setActiveWorkspace(workspaceId); this.assertSurfaceUnchanged(surface, 'set active workspace'); clearPendingWorkspaceReveal(surface.scope.surfaceId); - // An older host moved it to the front of its opened list; that is not - // an arrangement the display order should adopt. - noteWorkspaceActivated(surface.scope.surfaceId, workspace.id); // The host has switched: show it now, from the lists this window holds. // The recent and opened lists are refreshed afterwards, off the path the // user waits on (opening a session in another workspace waits on this). @@ -1599,7 +1528,7 @@ class WorkspaceManager { this.updateWorkspaceState( workspace, this.state.recentWorkspaces, - this.preserveOpenedWorkspaceOrder(opened), + opened, false, null, { type: 'workspace:switched', workspace } @@ -1614,7 +1543,7 @@ class WorkspaceManager { this.updateWorkspaceState( this.state.currentWorkspace, recentWorkspaces, - this.preserveOpenedWorkspaceOrder(openedWorkspaces), + openedWorkspaces, false, null, { type: 'workspace:recent-updated' }, @@ -1676,7 +1605,6 @@ class WorkspaceManager { } const surfaceId = surface.scope.surfaceId; - setWorkspaceDisplayOrder(surfaceId, reorderedOpenedWorkspaces.map(workspace => workspace.id)); this.updateWorkspaceState( previousCurrentWorkspace, previousRecentWorkspaces, @@ -1684,13 +1612,12 @@ class WorkspaceManager { false, null, { type: 'workspace:updated', workspace: reorderedEventWorkspace }, - { surfaceId, preordered: true }, + { surfaceId }, ); try { this.assertSurfaceUnchanged(surface, 'reorder opened workspaces'); await globalStateAPI.reorderOpenedWorkspaces(reorderedOpenedWorkspaceIds); - noteWorkspaceOrderPersisted(surfaceId, reorderedOpenedWorkspaceIds); } catch (error) { if (!this.isSurfaceUnchanged(surface)) { throw isSurfaceChangedError(error) @@ -1698,7 +1625,6 @@ class WorkspaceManager { : new SurfaceChangedError(surfaceId, surface.scope.epoch, 'reorder opened workspaces'); } const errorMessage = error instanceof Error ? error.message : String(error); - setWorkspaceDisplayOrder(surfaceId, previousOpenedWorkspaces.map(workspace => workspace.id)); const rollbackEventWorkspace = previousCurrentWorkspace ?? workspaceMap.get(sourceWorkspaceId) ?? previousOpenedWorkspaces[0] @@ -1710,7 +1636,7 @@ class WorkspaceManager { false, errorMessage, { type: 'workspace:updated', workspace: rollbackEventWorkspace }, - { surfaceId, preordered: true }, + { surfaceId }, ); this.emit({ type: 'workspace:error', error: errorMessage }); throw error;