From 7c50463629444addad68e2b4c115cdb0539da3f0 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 16 Nov 2026 19:32:57 +0800 Subject: [PATCH] fix(web-ui): polish promoted workspace reveal, persistence, and CLI peer reorder --- .../technical/tauri-command-map.json | 2 +- src/apps/cli/src/peer_host/args.rs | 24 ++ src/apps/cli/src/peer_host/commands/mod.rs | 2 + .../cli/src/peer_host/commands/workspace.rs | 17 +- .../generated/remote-surface-registry.json | 7 +- .../src/remote_surface/baseline.rs | 1 - .../src/remote_surface/table.rs | 2 +- .../NavPanel/MainNav.projectCreation.test.tsx | 11 + .../src/app/components/NavPanel/MainNav.tsx | 12 +- .../devices/DeviceWorkspaceSections.test.tsx | 15 + .../devices/DeviceWorkspaceSections.tsx | 7 + .../workspaces/WorkspaceListSection.test.tsx | 144 ++++++++- .../workspaces/WorkspaceListSection.tsx | 143 +++++++-- .../api/generated/remoteSurface.ts | 2 +- .../business/workspaceDisplayOrder.test.ts | 25 ++ .../business/workspaceDisplayOrder.ts | 105 ++++++- .../business/workspaceManager.test.ts | 151 ++++++++- .../services/business/workspaceManager.ts | 294 ++++++++++-------- 18 files changed, 757 insertions(+), 207 deletions(-) diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index 2ece102d80..32266d5623 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -7963,7 +7963,7 @@ "rustPath": "reorder_opened_workspaces", "sourceFile": "src/apps/desktop/src/api/commands.rs", "signature": "fn reorder_opened_workspaces( state: State<'_, AppState>, request: ReorderOpenedWorkspacesRequest, ) -> Result<(), String>", - "remoteWorkspacePolicy": "LegacyUnaudited" + "remoteWorkspacePolicy": "WorkspaceAgnostic" }, { "id": "replace_mode_skill_selection", diff --git a/src/apps/cli/src/peer_host/args.rs b/src/apps/cli/src/peer_host/args.rs index cf282ab428..b5111f631a 100644 --- a/src/apps/cli/src/peer_host/args.rs +++ b/src/apps/cli/src/peer_host/args.rs @@ -34,6 +34,21 @@ pub(crate) fn optional_bool(obj: &Value, camel: &str) -> Option { field(obj, camel, &snake).and_then(|v| v.as_bool()) } +pub(crate) fn get_string_vec(obj: &Value, camel: &str) -> Result, String> { + let snake = camel_to_snake(camel); + let items = field(obj, camel, &snake) + .and_then(|v| v.as_array()) + .ok_or_else(|| format!("Missing or invalid '{camel}' field"))?; + items + .iter() + .map(|item| { + item.as_str() + .map(str::to_string) + .ok_or_else(|| format!("Invalid string entry in '{camel}'")) + }) + .collect() +} + fn camel_to_snake(camel: &str) -> String { let mut out = String::with_capacity(camel.len() + 4); for (i, ch) in camel.chars().enumerate() { @@ -64,5 +79,14 @@ mod tests { optional_string(&camel, "workspacePath").as_deref(), Some("/a") ); + assert_eq!( + get_string_vec(&json!({ "workspaceIds": ["b", "a"] }), "workspaceIds").unwrap(), + vec!["b".to_string(), "a".to_string()] + ); + assert_eq!( + get_string_vec(&json!({ "workspace_ids": ["b", "a"] }), "workspaceIds").unwrap(), + vec!["b".to_string(), "a".to_string()] + ); + assert!(get_string_vec(&json!({ "workspaceIds": ["b", 1] }), "workspaceIds").is_err()); } } diff --git a/src/apps/cli/src/peer_host/commands/mod.rs b/src/apps/cli/src/peer_host/commands/mod.rs index da18e91c2d..3bc5c8b43f 100644 --- a/src/apps/cli/src/peer_host/commands/mod.rs +++ b/src/apps/cli/src/peer_host/commands/mod.rs @@ -63,6 +63,7 @@ pub(crate) fn dispatch<'a>( Box::pin(workspace::get_current_workspace(state)) } "set_active_workspace" => Box::pin(workspace::set_active_workspace(state, args)), + "reorder_opened_workspaces" => Box::pin(workspace::reorder_opened_workspaces(state, args)), "open_workspace" => Box::pin(workspace::open_workspace(state, args)), "ssh_list_saved_connections" => Box::pin(workspace::ssh_list_saved_connections()), "open_remote_workspace" => Box::pin(workspace::open_remote_workspace(state, args)), @@ -407,6 +408,7 @@ pub(crate) const HANDLED_COMMANDS: &[&str] = &[ "reload_config", "remove_project_permission_grant", "rename_session", + "reorder_opened_workspaces", "respond_permission", "respond_permission_batch", "restore_session", diff --git a/src/apps/cli/src/peer_host/commands/workspace.rs b/src/apps/cli/src/peer_host/commands/workspace.rs index f2dd397ce8..8fd9038339 100644 --- a/src/apps/cli/src/peer_host/commands/workspace.rs +++ b/src/apps/cli/src/peer_host/commands/workspace.rs @@ -8,7 +8,9 @@ use openbitfun_core::service::workspace::{ use openbitfun_runtime_ports::SessionStoragePathRequest; use serde_json::{json, Value}; -use crate::peer_host::args::{get_string, optional_bool, optional_string, request_value}; +use crate::peer_host::args::{ + get_string, get_string_vec, optional_bool, optional_string, request_value, +}; use crate::peer_host::state::PeerHostState; use crate::peer_host::workspace_dto::{workspace_info_to_json, workspace_list_to_json}; @@ -70,6 +72,19 @@ pub(crate) async fn set_active_workspace( Ok(workspace_info_to_json(&workspace)) } +pub(crate) async fn reorder_opened_workspaces( + state: &PeerHostState, + args: &Value, +) -> Result { + let workspace_ids = get_string_vec(request_value(args), "workspaceIds")?; + state + .workspace_service + .reorder_opened_workspaces(workspace_ids) + .await + .map_err(|error| format!("Failed to reorder opened workspaces: {error}"))?; + Ok(Value::Null) +} + pub(crate) async fn open_workspace(state: &PeerHostState, args: &Value) -> Result { let request = request_value(args); if let Some(id) = crate::peer_host::args::optional_string(request, "workspaceId") { diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index 6881f20be6..b392cd87ce 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:ab13282fb7012e10", + "digest": "fnv1a64:f165ae35a7d7a54c", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -6224,13 +6224,12 @@ { "id": "reorder_opened_workspaces", "surface": "tauri_command", - "remoteWorkspace": "LegacyUnaudited", + "remoteWorkspace": "WorkspaceAgnostic", "peer": { "kind": "proxied" }, "cliPeer": { - "kind": "unsupported", - "reason": "the CLI peer host has no handler for this command" + "kind": "handled" } }, { diff --git a/src/crates/contracts/product-domains/src/remote_surface/baseline.rs b/src/crates/contracts/product-domains/src/remote_surface/baseline.rs index 475b86b4ca..f9dc945f46 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/baseline.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/baseline.rs @@ -172,7 +172,6 @@ pub(super) const UNAUDITED_BASELINE: &[&str] = &[ "reload_config", "reload_custom_agents", "reload_subagents", - "reorder_opened_workspaces", "replace_mode_skill_selection", "report_ide_control_result", "reset_agent_profile_config", diff --git a/src/crates/contracts/product-domains/src/remote_surface/table.rs b/src/crates/contracts/product-domains/src/remote_surface/table.rs index d94497a57d..a7e2635427 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/table.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/table.rs @@ -611,7 +611,7 @@ pub(super) const OPERATIONS: &[OperationDefinition] = &[ op("remove_recent_workspace", Agnostic, Proxied, CLI_NOT_IMPLEMENTED), op("rename_file", Routed, Proxied, HANDLED), host_invoke_only("rename_session", Agnostic, Proxied, HANDLED), - op("reorder_opened_workspaces", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), + op("reorder_opened_workspaces", Agnostic, Proxied, HANDLED), op("replace_mode_skill_selection", Unaudited, Proxied, CLI_NOT_IMPLEMENTED), op("report_ide_control_result", Unaudited, ControllerLocal, REFUSED), op("report_miniapp_web_result", Agnostic, ControllerLocal, REFUSED), diff --git a/src/web-ui/src/app/components/NavPanel/MainNav.projectCreation.test.tsx b/src/web-ui/src/app/components/NavPanel/MainNav.projectCreation.test.tsx index fb1757b5cf..35f6c132ea 100644 --- a/src/web-ui/src/app/components/NavPanel/MainNav.projectCreation.test.tsx +++ b/src/web-ui/src/app/components/NavPanel/MainNav.projectCreation.test.tsx @@ -84,6 +84,7 @@ import MainNav from './MainNav'; import { useWorkspaceSessionViewStore } from './workspaceSessionView'; import { useMiniAppNavigationStore } from '@/app/scenes/miniapps/miniAppNavigationStore'; import { sidebarPreferences } from '@/app/navigation/sidebarPreferences'; +import { requestWorkspaceReveal, resetWorkspaceDisplayOrdersForTest } from '@/infrastructure/services/business/workspaceDisplayOrder'; describe('project creation entry points', () => { let root: Root; @@ -181,6 +182,16 @@ describe('project creation entry points', () => { expect(useWorkspaceSessionViewStore.getState().grouping).toBe(succeeded ? 'grouped' : 'all'); }); + it('switches flat session view to grouped when an explicit open requests revealing a project on the active device', () => { + resetWorkspaceDisplayOrdersForTest(); + useWorkspaceSessionViewStore.getState().setGrouping('all'); + act(() => { requestWorkspaceReveal('peer-b', 'ws-other', true); }); + expect(useWorkspaceSessionViewStore.getState().grouping).toBe('all'); + + act(() => { requestWorkspaceReveal('local', 'ws-local', true); }); + expect(useWorkspaceSessionViewStore.getState().grouping).toBe('grouped'); + }); + it.each(['sidebar', 'global'] as const)('%s opens the full source picker and adds a WSL folder', async entry => { if (entry === 'sidebar') { await act(async () => document.querySelector('[data-testid="nav-workspace-add-btn"]')!.click()); diff --git a/src/web-ui/src/app/components/NavPanel/MainNav.tsx b/src/web-ui/src/app/components/NavPanel/MainNav.tsx index f8290147a7..da5f3bfd90 100644 --- a/src/web-ui/src/app/components/NavPanel/MainNav.tsx +++ b/src/web-ui/src/app/components/NavPanel/MainNav.tsx @@ -51,7 +51,8 @@ import { useSidebarNavigation } from '@/app/navigation/useSidebarNavigation'; import PinnedNavigationItems from './components/PinnedNavigationItems'; import { createProject, type ProjectDraft, type ProjectFolder } from '@/app/services/createProject'; import { useWorkspaceSessionViewStore } from './workspaceSessionView'; -import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; +import { getActiveSurfaceId, getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; +import { subscribeWorkspaceReveal } from '@/infrastructure/services/business/workspaceDisplayOrder'; import { useNurseryStore } from '@/app/scenes/profile/nurseryStore'; import { RetainedMountBoundary } from '@/shared/presence'; import { lazyWithRecovery } from '@/shared/utils/lazyWithRecovery'; @@ -195,6 +196,15 @@ const MainNav: React.FC = () => { return () => window.removeEventListener('nav:new-project', onNewProject); }, []); + // Explicitly opening or re-adding a project workspace from any entry point + // switches out of the flat session list so the project header can be revealed. + useEffect(() => subscribeWorkspaceReveal(request => { + if (request.surfaceId !== getActiveSurfaceId()) return; + if (useWorkspaceSessionViewStore.getState().grouping === 'all') { + useWorkspaceSessionViewStore.getState().setGrouping('grouped'); + } + }), []); + const peerDevice = usePeerDeviceModeOptional(); const signedIn = useDeviceDirectory(state => state.localId !== null); const deviceSlots = useSidebarDevices(t('deviceOverview.thisDevice')); diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/DeviceWorkspaceSections.test.tsx b/src/web-ui/src/app/components/NavPanel/sections/devices/DeviceWorkspaceSections.test.tsx index 13a2f24303..5f61e5a79a 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/DeviceWorkspaceSections.test.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/DeviceWorkspaceSections.test.tsx @@ -28,6 +28,8 @@ import { beginDeviceOpen, endDeviceOpen } from '@/infrastructure/peer-device/dev import DeviceWorkspaceSections from './DeviceWorkspaceSections'; import { useDeviceVisibilityPreferences } from '@/app/navigation/deviceVisibilityPreferences'; import { activateSurface } from '@/infrastructure/peer-device/deviceSurface'; +import { requestWorkspaceReveal, resetWorkspaceDisplayOrdersForTest } from '@/infrastructure/services/business/workspaceDisplayOrder'; +import { useDeviceSectionDisclosure } from './useSidebarDevices'; globalThis.IS_REACT_ACT_ENVIRONMENT = true; @@ -152,4 +154,17 @@ describe('DeviceWorkspaceSections hand-over', () => { act(() => useDeviceVisibilityPreferences.getState().setVisible('local', false)); expect(host.children).toHaveLength(0); }); + + it('re-expands a collapsed current device section when a workspace open reveals a row on it', () => { + resetWorkspaceDisplayOrdersForTest(); + useDeviceSectionDisclosure.setState({ expanded: {} }); + slots.value = [slot('local', true), slot('peer-b', false)]; + render(); + + act(() => host.querySelector('[data-device-surface="local"] [data-testid="nav-device-section-toggle"]')!.click()); + expect(body('local')).toBeUndefined(); + + act(() => { requestWorkspaceReveal('local', 'ws-1', true); }); + expect(body('local')).toBe('live-list'); + }); }); diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/DeviceWorkspaceSections.tsx b/src/web-ui/src/app/components/NavPanel/sections/devices/DeviceWorkspaceSections.tsx index 658a8b6816..e6b54f0567 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/DeviceWorkspaceSections.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/DeviceWorkspaceSections.tsx @@ -20,6 +20,7 @@ import WorkspaceListSection from '../workspaces/WorkspaceListSection'; import DeviceCatalogSection from './DeviceCatalogSection'; import { useDeviceOpenIntent } from '@/infrastructure/peer-device/deviceOpenIntent'; import { useWorkspaceContext } from '@/infrastructure/contexts/WorkspaceContext'; +import { subscribeWorkspaceReveal } from '@/infrastructure/services/business/workspaceDisplayOrder'; import { workspaceManager } from '@/infrastructure/services/business/workspaceManager'; import { installBackgroundSurfaceSeeding } from '@/flow_chat/services/backgroundSurfaceSeeding'; import { useDeviceVisibilityPreferences } from '@/app/navigation/deviceVisibilityPreferences'; @@ -209,6 +210,12 @@ const DeviceWorkspaceSections: React.FC = ({ scrol setExpanded(activeSurfaceId, true); } }, [activeSurfaceId, setExpanded]); + useEffect(() => subscribeWorkspaceReveal(request => { + if (request.surfaceId !== getActiveSurfaceId()) return; + if (useDeviceSectionDisclosure.getState().expanded[request.surfaceId] === false) { + setExpanded(request.surfaceId, true); + } + }), [setExpanded]); const containerRef = useRef(null); useSwitchLayoutHold(containerRef, scrollRootRef); diff --git a/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSection.test.tsx b/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSection.test.tsx index 487b80dece..e177e7ac53 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSection.test.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSection.test.tsx @@ -19,17 +19,8 @@ const state = vi.hoisted(() => { workspaces: [assistant, project], defaultWorkspaces: [assistant, project], reorder: vi.fn<(...args: unknown[]) => Promise>().mockResolvedValue(undefined), - managerListeners: new Set<(event: { type: string; workspaceId?: string }) => void>(), }; }); -vi.mock('@/infrastructure/services/business/workspaceManager', () => ({ - workspaceManager: { - addEventListener: (listener: (event: { type: string; workspaceId?: string }) => void) => { - state.managerListeners.add(listener); - return () => { state.managerListeners.delete(listener); }; - }, - }, -})); vi.mock('@/infrastructure/i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) })); vi.mock('@/shared/notification-system', () => ({ notificationService: { error: vi.fn() } })); vi.mock('@/infrastructure/contexts/WorkspaceContext', () => ({ @@ -89,6 +80,11 @@ vi.mock('../sessions/SessionsSection', () => ({ import WorkspaceListSection from './WorkspaceListSection'; import { useSceneStore } from '@/app/stores/sceneStore'; +import { + prepareWorkspacePromotion, + requestWorkspaceReveal, + resetWorkspaceDisplayOrdersForTest, +} from '@/infrastructure/services/business/workspaceDisplayOrder'; function sessionTab(workspaceId: string, surfaceId = 'local'): SceneTab { const session = { surfaceId, workspaceKey: sessionSceneWorkspaceKey(workspaceId), sessionId: `chat-${workspaceId}` }; @@ -105,6 +101,7 @@ afterEach(() => { state.workspaces = [...state.defaultWorkspaces]; useSceneStore.setState({ activeTabId: null, openTabs: [] }); useContentResourceStore.setState({ resources: {} }); + resetWorkspaceDisplayOrdersForTest(); activateSurface('local'); }); @@ -436,7 +433,7 @@ describe('assistant pinning', () => { }); describe('re-added workspace promotion', () => { - it('brings the promoted row into view once the new order renders', () => { + it('brings the promoted row into view once the new order renders and reveals already-first rows too', () => { state.grouping = 'grouped'; const first = { id: 'first-project', name: 'First', workspaceKind: 'normal' }; const second = { id: 'second-project', name: 'Second', workspaceKind: 'normal' }; @@ -453,20 +450,141 @@ describe('re-added workspace promotion', () => { list.render(); expect(scrollIntoView).not.toHaveBeenCalled(); - act(() => state.managerListeners.forEach(listener => listener({ - type: 'workspace:promoted', workspaceId: second.id, - }))); + act(() => { requestWorkspaceReveal('local', second.id, true); }); state.workspaces = [second, first]; list.render(); expect(list.ownerRows()).toEqual([second.id, first.id]); expect(scrolled).toEqual([second.id]); expect(scrollIntoView).toHaveBeenCalledWith({ block: 'nearest' }); + + // Re-adding the row already at index 0 still scrolls it into view without changing order. + scrollIntoView.mockClear(); + scrolled.length = 0; + act(() => { requestWorkspaceReveal('local', second.id, false); }); + expect(scrolled).toEqual([second.id]); + } finally { + list.unmount(); + delete (HTMLElement.prototype as { scrollIntoView?: unknown }).scrollIntoView; + } + }); + + it('reveals the target row once flat view switches to grouped', () => { + state.grouping = 'all'; + const first = { id: 'first-project', name: 'First', workspaceKind: 'normal' }; + const second = { id: 'second-project', name: 'Second', workspaceKind: 'normal' }; + state.workspaces = [first, second]; + const scrolled: Array = []; + const scrollIntoView = vi.fn(function (this: HTMLElement) { + scrolled.push(this.getAttribute('data-workspace-id')); + }); + Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', { configurable: true, value: scrollIntoView }); + + const list = renderList(); + try { + act(() => { requestWorkspaceReveal('local', second.id, true); }); + state.workspaces = [second, first]; + list.render(); + expect(scrolled).toEqual([]); + + state.grouping = 'grouped'; + list.render(); + expect(scrolled).toEqual([second.id]); } finally { list.unmount(); delete (HTMLElement.prototype as { scrollIntoView?: unknown }).scrollIntoView; } }); + + it('clears the sticky section header when scrolling and subtracts scrollDelta from FLIP animations', () => { + state.grouping = 'grouped'; + const items = [ + { id: 'w-0', name: 'Zero', workspaceKind: 'normal' }, + { id: 'w-1', name: 'One', workspaceKind: 'normal' }, + { id: 'w-2', name: 'Two', workspaceKind: 'normal' }, + { id: 'w-3', name: 'Three', workspaceKind: 'normal' }, + ]; + state.workspaces = [...items]; + + const scrollRoot = document.createElement('div'); + scrollRoot.scrollTop = 1000; + const section = document.createElement('div'); + section.setAttribute('data-openbitfun-section', 'sessions'); + const stickyHeader = document.createElement('div'); + stickyHeader.setAttribute('data-openbitfun-part', 'stickySectionHeader'); + const content = document.createElement('div'); + section.append(stickyHeader, content); + scrollRoot.appendChild(section); + document.body.appendChild(scrollRoot); + + const scrollRootRef = { current: scrollRoot }; + const layoutOffsets = new Map([ + ['w-0', 82], + ['w-1', 122], + ['w-2', 1082], + ['w-3', 1482], + ]); + + vi.spyOn(scrollRoot, 'getBoundingClientRect').mockImplementation(() => new DOMRect(0, 60, 260, 400)); + vi.spyOn(stickyHeader, 'getBoundingClientRect').mockImplementation(() => new DOMRect(0, 60, 260, 22)); + + const animated = new Map(); + const animateMock = vi.fn(function (this: HTMLElement, keyframes: Keyframe[] | PropertyIndexedKeyframes | null) { + const id = this.getAttribute('data-workspace-id') ?? ''; + animated.set(id, (keyframes as Keyframe[]) ?? []); + return { cancel: vi.fn(), addEventListener: vi.fn() } as unknown as Animation; + }); + const originalAnimate = HTMLElement.prototype.animate; + HTMLElement.prototype.animate = animateMock; + + const root = createRoot(content); + const bindRowRects = () => { + for (const node of content.querySelectorAll('[data-workspace-id]')) { + const id = node.getAttribute('data-workspace-id')!; + node.getBoundingClientRect = () => new DOMRect(0, (layoutOffsets.get(id) ?? 0) - scrollRoot.scrollTop, 260, 34); + } + }; + + try { + act(() => root.render()); + bindRowRects(); + + // Promote w-2 from scrolled-down layoutY=1082 to index 0 (layoutY=82, right below stickyHeader.bottom=82). + act(() => { prepareWorkspacePromotion('local', 'w-2'); }); + state.workspaces = [items[2], items[0], items[1], items[3]]; + layoutOffsets.set('w-2', 82); + layoutOffsets.set('w-0', 122); + layoutOffsets.set('w-1', 162); + layoutOffsets.set('w-3', 1482); + // Bind rects as soon as React mounts/updates, so useLayoutEffect reads the new layout positions. + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) { + if (this === scrollRoot) return new DOMRect(0, 60, 260, 400); + if (this === stickyHeader) return new DOMRect(0, 60, 260, 22); + const id = this.getAttribute('data-workspace-id') + ?? this.closest('[data-workspace-id]')?.getAttribute('data-workspace-id'); + if (id && layoutOffsets.has(id)) { + return new DOMRect(0, (layoutOffsets.get(id) ?? 0) - scrollRoot.scrollTop, 260, 34); + } + return new DOMRect(0, 0, 0, 0); + }); + act(() => { + requestWorkspaceReveal('local', 'w-2', true); + root.render(); + }); + + // `scrollTop` aligns w-2's top (layoutY=82) to stickyHeader.bottom (82), not scrollRoot.top (60). + expect(scrollRoot.scrollTop).toBe(0); + // Neighbours w-0 and w-1 shifted by exactly 40px in layout, NOT -1040px! + expect(animated.get('w-0')?.[0]).toEqual({ transform: 'translateY(-40px)' }); + expect(animated.get('w-1')?.[0]).toEqual({ transform: 'translateY(-40px)' }); + // Off-screen unmoved w-3 (layoutY=1482) is skipped completely. + expect(animated.has('w-3')).toBe(false); + } finally { + act(() => root.unmount()); + scrollRoot.remove(); + HTMLElement.prototype.animate = originalAnimate; + } + }); }); describe('project disclosure across view changes', () => { diff --git a/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSection.tsx b/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSection.tsx index 86312d84d6..13a62b4017 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSection.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSection.tsx @@ -1,7 +1,13 @@ import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; import { useI18n } from '@/infrastructure/i18n'; import { useWorkspaceContext } from '@/infrastructure/contexts/WorkspaceContext'; -import { workspaceManager } from '@/infrastructure/services/business/workspaceManager'; +import { + consumeWorkspaceReveal, + getPendingWorkspaceReveal, + getWorkspaceRevealRevision, + subscribeWorkspacePromotionSnapshot, + subscribeWorkspaceRevealState, +} from '@/infrastructure/services/business/workspaceDisplayOrder'; import { useSceneStore } from '@/app/stores/sceneStore'; import { useContentResourceStore } from '@/app/workbench/contentResourceStore'; import { getActiveSurfaceId, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface'; @@ -35,9 +41,48 @@ interface WorkspaceDragPayload { variant: SessionNavigationScope; } +interface PendingDropSnapshot { + surfaceId: string; + scrollTop: number; + rects: Map; +} + const WORKSPACE_DRAG_MIME_TYPE = 'application/x-openbitfun-workspace'; const WORKSPACE_DROP_SETTLE_MS = 160; const WORKSPACE_DROP_EASING = 'cubic-bezier(0.22, 1, 0.36, 1)'; +const WORKSPACE_FLIP_VIEWPORT_MARGIN_PX = 40; +const WORKSPACE_FLIP_MAX_DELTA_PX = 240; + +/** + * Scroll `row`'s header card into the visible portion of `scrollRoot`, clearing + * any sticky section header (which also clips covered content via `clip-path`). + * Falls back to native `scrollIntoView` when no measured scroll container exists. + */ +function revealWorkspaceRow(row: HTMLElement, scrollRoot?: HTMLElement | null): void { + const header = row.querySelector('.openbitfun-nav-panel__workspace-item-card') ?? row; + if (scrollRoot) { + const scrollRect = scrollRoot.getBoundingClientRect(); + const stickyHeader = row.closest('[data-openbitfun-section="sessions"]') + ?.querySelector('[data-openbitfun-part="stickySectionHeader"]'); + const visibleTop = Math.max(scrollRect.top, stickyHeader?.getBoundingClientRect().bottom ?? scrollRect.top); + const visibleBottom = scrollRect.bottom; + if (visibleBottom > visibleTop) { + const rowRect = row.getBoundingClientRect(); + const headerRect = header.getBoundingClientRect(); + if (headerRect.top < visibleTop) { + scrollRoot.scrollTop = Math.max(0, scrollRoot.scrollTop + (rowRect.top - visibleTop)); + return; + } + if (headerRect.bottom > visibleBottom) { + const delta = Math.min(headerRect.bottom - visibleBottom, rowRect.top - visibleTop); + if (delta > 0) scrollRoot.scrollTop += delta; + return; + } + return; + } + } + header.scrollIntoView?.({ block: 'nearest' }); +} /** * WorkspaceListSection — the session section's group list. @@ -86,14 +131,18 @@ const WorkspaceListSection: React.FC = ({ variant, sc activeTab?.contentId ? state.resources[activeTab.contentId]?.scope : undefined )); const surfaceId = useSyncExternalStore(onSurfaceActivated, getActiveSurfaceId, getActiveSurfaceId); + const revealRevision = useSyncExternalStore( + subscribeWorkspaceRevealState, + getWorkspaceRevealRevision, + getWorkspaceRevealRevision, + ); // Refs for values that must be read inside event handlers without stale closures const draggedWorkspaceIdRef = useRef(null); const dropTargetRef = useRef<{ workspaceId: string; position: WorkspaceDragPosition } | null>(null); const pendingDragEndRef = useRef | undefined>(undefined); const workspaceRowRefs = useRef>(new Map()); - const pendingDropRectsRef = useRef | null>(null); - const pendingRevealWorkspaceIdRef = useRef(null); + const pendingDropSnapshotRef = useRef(null); const dropAnimationsRef = useRef>(new Map()); const sectionWorkspaces = variant === 'all' @@ -164,27 +213,30 @@ const WorkspaceListSection: React.FC = ({ variant, sc // A retained list can lose its native source without receiving dragend. // Device identity matters even when the new surface has identical workspace IDs. + // Pending reveal requests live in `workspaceDisplayOrder` so switching from + // flat (`all`) to grouped still reveals the row once it mounts. useLayoutEffect(() => { resetDragState(); - pendingDropRectsRef.current = null; - pendingRevealWorkspaceIdRef.current = null; + pendingDropSnapshotRef.current = null; }, [grouping, surfaceId, variant, resetDragState]); - const measureWorkspaceRows = useCallback(() => new Map( - Array.from(workspaceRowRefs.current, ([id, element]) => ( - [id, element.getBoundingClientRect()] as const - )), - ), []); + const captureWorkspaceRowsSnapshot = useCallback((): PendingDropSnapshot => ({ + surfaceId, + scrollTop: scrollRootRef?.current?.scrollTop ?? 0, + rects: new Map( + Array.from(workspaceRowRefs.current, ([id, element]) => ( + [id, element.getBoundingClientRect()] as const + )), + ), + }), [scrollRootRef, surfaceId]); // Re-adding an opened workspace moves it to the top of this device's list. - // The event arrives before the new order renders, so the rows can slide like - // a drop, and the row is brought into view: a move the user cannot see reads - // as the add doing nothing. - useEffect(() => workspaceManager.addEventListener(event => { - if (event.type !== 'workspace:promoted' || !workspaceRowRefs.current.has(event.workspaceId)) return; - pendingDropRectsRef.current = measureWorkspaceRows(); - pendingRevealWorkspaceIdRef.current = event.workspaceId; - }), [measureWorkspaceRows]); + // Snapshot pre-reorder geometry before the new order commits so rows can slide. + useEffect(() => subscribeWorkspacePromotionSnapshot((promotedSurfaceId, workspaceId) => { + if (promotedSurfaceId !== surfaceId) return; + if (!workspaceRowRefs.current.has(workspaceId)) return; + pendingDropSnapshotRef.current = captureWorkspaceRowsSnapshot(); + }), [captureWorkspaceRowsSnapshot, surfaceId]); useLayoutEffect(() => { if (draggedWorkspaceId && !canContinueDrag) { @@ -240,26 +292,49 @@ const WorkspaceListSection: React.FC = ({ variant, sc dropAnimationsRef.current.clear(); }, []); + const firstVisibleWorkspaceId = visibleReorderableGroups[0]?.workspace.id ?? null; + useLayoutEffect(() => { - const revealWorkspaceId = pendingRevealWorkspaceIdRef.current; - pendingRevealWorkspaceIdRef.current = null; - if (revealWorkspaceId) { - const row = workspaceRowRefs.current.get(revealWorkspaceId); - const header = row?.querySelector('.openbitfun-nav-panel__workspace-item-card') ?? row; - header?.scrollIntoView?.({ block: 'nearest' }); + const pendingReveal = getPendingWorkspaceReveal(surfaceId); + if (pendingReveal && (!pendingReveal.promoted || firstVisibleWorkspaceId === pendingReveal.workspaceId)) { + const row = workspaceRowRefs.current.get(pendingReveal.workspaceId); + if (row) { + consumeWorkspaceReveal(surfaceId, pendingReveal.token); + revealWorkspaceRow(row, scrollRootRef?.current); + } } - const previousRects = pendingDropRectsRef.current; - if (!previousRects) return; - pendingDropRectsRef.current = null; + const snapshot = pendingDropSnapshotRef.current; + if (!snapshot) return; + pendingDropSnapshotRef.current = null; + if (snapshot.surfaceId !== surfaceId) return; if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return; + const scrollRoot = scrollRootRef?.current; + const scrollDelta = (scrollRoot?.scrollTop ?? 0) - snapshot.scrollTop; + const scrollRect = scrollRoot?.getBoundingClientRect(); + const viewportHeight = scrollRect && scrollRect.height > 0 ? scrollRect.height : 0; + const maxDelta = viewportHeight > 0 + ? Math.max(96, Math.min(WORKSPACE_FLIP_MAX_DELTA_PX, viewportHeight * 0.65)) + : WORKSPACE_FLIP_MAX_DELTA_PX; + for (const [workspaceId, element] of workspaceRowRefs.current) { - const previousRect = previousRects.get(workspaceId); + const previousRect = snapshot.rects.get(workspaceId); if (!previousRect) continue; const currentRect = element.getBoundingClientRect(); - const deltaY = previousRect.top - currentRect.top; - if (Math.abs(deltaY) < 0.5) continue; + if ( + scrollRect + && viewportHeight > 0 + && ( + currentRect.bottom < scrollRect.top - WORKSPACE_FLIP_VIEWPORT_MARGIN_PX + || currentRect.top > scrollRect.bottom + WORKSPACE_FLIP_VIEWPORT_MARGIN_PX + ) + ) { + continue; + } + const rawDeltaY = (previousRect.top - currentRect.top) - scrollDelta; + if (Math.abs(rawDeltaY) < 0.5) continue; + const deltaY = Math.sign(rawDeltaY) * Math.min(Math.abs(rawDeltaY), maxDelta); dropAnimationsRef.current.get(workspaceId)?.cancel(); const animation = element.animate( @@ -276,7 +351,7 @@ const WorkspaceListSection: React.FC = ({ variant, sc } }, { once: true }); } - }, [workspaceSignature]); + }, [firstVisibleWorkspaceId, grouping, revealRevision, scrollRootRef, surfaceId, workspaceSignature]); const handleDragStart = useCallback((workspaceId: string) => (event: React.DragEvent) => { const payload: WorkspaceDragPayload = { workspaceId, variant }; @@ -366,18 +441,18 @@ const WorkspaceListSection: React.FC = ({ variant, sc event.stopPropagation(); // Keep the slot measured by dragover, before the drop line changed layout. - pendingDropRectsRef.current = measureWorkspaceRows(); + pendingDropSnapshotRef.current = captureWorkspaceRowsSnapshot(); try { await reorderOpenedWorkspacesInSection(reorderSection, payload.workspaceId, workspaceId, position); } catch (error) { - pendingDropRectsRef.current = null; + pendingDropSnapshotRef.current = null; notificationService.error( error instanceof Error ? error.message : t('nav.workspaces.reorderFailed'), { duration: 4000 } ); } - }, [measureWorkspaceRows, reorderOpenedWorkspacesInSection, reorderSection, resetDragState, t, variant]); + }, [captureWorkspaceRowsSnapshot, reorderOpenedWorkspacesInSection, reorderSection, resetDragState, t, variant]); /** * One session-group row. Pinned assistants and project workspaces share the diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index c0f6bd123a..8f60fac1c4 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:ab13282fb7012e10" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:f165ae35a7d7a54c" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller 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 26db57001e..7e03e0c985 100644 --- a/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.test.ts +++ b/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.test.ts @@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from 'vitest'; import { getWorkspaceDisplayOrderRevision, noteWorkspaceActivated, + noteWorkspaceOrderPersisted, orderWorkspacesForDisplay, resetWorkspaceDisplayOrdersForTest, setWorkspaceDisplayOrder, @@ -71,4 +72,28 @@ describe('stableWorkspaceOrder', () => { 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'); + + // 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']); + }); + + 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']); + + expect(ids(stableWorkspaceOrder('local', list('assistant', 'a', 'c', 'b')))) + .toEqual(['assistant', 'a', 'c', 'b']); + }); }); diff --git a/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.ts b/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.ts index 6176e4e493..e15b5a1d98 100644 --- a/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.ts +++ b/src/web-ui/src/infrastructure/services/business/workspaceDisplayOrder.ts @@ -25,9 +25,24 @@ 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; +export interface WorkspaceRevealRequest { + readonly surfaceId: string; + readonly workspaceId: string; + readonly promoted: boolean; + readonly token: number; +} + +const pendingReveals = new Map(); +const promotionSnapshotListeners = new Set<(surfaceId: string, workspaceId: string) => void>(); +const revealListeners = new Set<(request: WorkspaceRevealRequest) => void>(); +const revealStateListeners = new Set<() => void>(); +let revealRevision = 0; + const sameIds = (left: readonly string[], right: readonly string[]) => ( left.length === right.length && left.every((id, index) => id === right[index]) ); @@ -40,6 +55,13 @@ 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; @@ -50,10 +72,75 @@ export function subscribeWorkspaceDisplayOrder(listener: () => void): () => void return () => { listeners.delete(listener); }; } +/** + * Let mounted views snapshot pre-reorder row geometry before the promoted list + * is published, without triggering external-store renders against stale state. + */ +export function prepareWorkspacePromotion(surfaceId: string, workspaceId: string): void { + for (const listener of Array.from(promotionSnapshotListeners)) { + listener(surfaceId, workspaceId); + } +} + +export function subscribeWorkspacePromotionSnapshot( + listener: (surfaceId: string, workspaceId: string) => void, +): () => void { + promotionSnapshotListeners.add(listener); + return () => { promotionSnapshotListeners.delete(listener); }; +} + +/** + * Announce that an explicit user open should reveal `workspaceId` in the + * sidebar once the updated workspace state has been published. + */ +export function requestWorkspaceReveal( + surfaceId: string, + workspaceId: string, + promoted: boolean, +): WorkspaceRevealRequest { + revealRevision += 1; + const request: WorkspaceRevealRequest = { surfaceId, workspaceId, promoted, token: revealRevision }; + pendingReveals.set(surfaceId, request); + for (const listener of Array.from(revealListeners)) listener(request); + for (const listener of Array.from(revealStateListeners)) listener(); + return request; +} + +export function getPendingWorkspaceReveal(surfaceId: string): WorkspaceRevealRequest | undefined { + return pendingReveals.get(surfaceId); +} + +export function consumeWorkspaceReveal(surfaceId: string, token: number): void { + if (pendingReveals.get(surfaceId)?.token === token) { + pendingReveals.delete(surfaceId); + } +} + +export function clearPendingWorkspaceReveal(surfaceId: string): void { + if (pendingReveals.delete(surfaceId)) { + revealRevision += 1; + for (const listener of Array.from(revealStateListeners)) listener(); + } +} + +export function getWorkspaceRevealRevision(): number { + return revealRevision; +} + +export function subscribeWorkspaceReveal(listener: (request: WorkspaceRevealRequest) => void): () => void { + revealListeners.add(listener); + return () => { revealListeners.delete(listener); }; +} + +export function subscribeWorkspaceRevealState(listener: () => void): () => void { + revealStateListeners.add(listener); + return () => { revealStateListeners.delete(listener); }; +} + /** * 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 the shown order. + * still matches `lastSeenHostOrders`. */ export function noteWorkspaceActivated(surfaceId: string, workspaceId: string): void { const host = hostOrders.get(surfaceId); @@ -67,6 +154,7 @@ export function stableWorkspaceOrder(surfaceId: string if (!remembered) { setWorkspaceDisplayOrder(surfaceId, hostIds); hostOrders.set(surfaceId, hostIds); + lastSeenHostOrders.set(surfaceId, hostIds); return [...hostWorkspaces]; } // Both sides restricted to the workspaces they share. @@ -75,14 +163,23 @@ export function stableWorkspaceOrder(surfaceId: string ] as const; const [shown, listed] = common(remembered); const lastHost = hostOrders.get(surfaceId); - if (!isActivationReorder(shown, listed) && !(lastHost && isActivationReorder(...common(lastHost)))) { + 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); + 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; @@ -127,4 +224,6 @@ function isActivationReorder(shown: readonly string[], host: readonly string[]): 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 bfb4ec7008..210be36d7d 100644 --- a/src/web-ui/src/infrastructure/services/business/workspaceManager.test.ts +++ b/src/web-ui/src/infrastructure/services/business/workspaceManager.test.ts @@ -86,11 +86,14 @@ async function getFreshWorkspaceHarness() { vi.resetModules(); const deviceSurface = await import('@/infrastructure/peer-device/deviceSurface'); deviceSurface.resetDeviceSurfaceForTest(); + const displayOrder = await import('./workspaceDisplayOrder'); + displayOrder.resetWorkspaceDisplayOrdersForTest(); const { WorkspaceManager } = await import('./workspaceManager'); (WorkspaceManager as unknown as { instance: unknown }).instance = null; return { manager: WorkspaceManager.getInstance(), deviceSurface, + displayOrder, }; } @@ -1209,21 +1212,47 @@ describe('WorkspaceManager openWorkspace promotion', () => { ]); }); - it('keeps the promoted display order even if host reorder persistence fails', async () => { + 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 cli peer')); + 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, + ]); }); it('keeps local and peer display orders independent, including identical workspace IDs', async () => { @@ -1259,27 +1288,58 @@ describe('WorkspaceManager openWorkspace promotion', () => { .toEqual([workspaceB.id, workspaceC.id, workspaceA.id]); }); - it('shows the promoted order before the host finishes persisting it', async () => { - const manager = await getFreshWorkspaceManager(); + 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); + }); + const { manager, displayOrder } = await getFreshWorkspaceHarness(); await manager.initialize(); + let finishReorder!: () => void; globalStateMocks.reorderOpenedWorkspaces.mockReturnValueOnce( new Promise(resolve => { finishReorder = resolve; }), ); globalStateMocks.openWorkspace.mockResolvedValue(workspaceB); - const events: string[] = []; - manager.addEventListener(event => { events.push(event.type); }); - - const opening = manager.openWorkspace(workspaceB.rootPath); - await flushAsyncWork(); + const steps: string[] = []; + displayOrder.subscribeWorkspacePromotionSnapshot((_surfaceId, workspaceId) => { + steps.push(`snapshot:${workspaceId}`); + // At pre-promotion snapshot time, state still reflects the old layout. + expect(Array.from(manager.getState().openedWorkspaces.keys())) + .toEqual([workspaceA.id, workspaceB.id, workspaceC.id]); + }); + displayOrder.subscribeWorkspaceReveal(request => { + steps.push(`reveal:${request.workspaceId}:${request.promoted}`); + }); + 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())) .toEqual([workspaceB.id, workspaceA.id, workspaceC.id]); expect(manager.getState().loading).toBe(false); - // Views measure the old layout on `promoted`, before the new order is published. - expect(events.indexOf('workspace:promoted')).toBeLessThan(events.indexOf('workspace:opened')); + expect(steps).toEqual([ + 'workspace:loading', + `snapshot:${workspaceB.id}`, + '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 expect(opening).resolves.toBe(workspaceB); + await flushAsyncWork(); + expect(globalStateMocks.getOpenedWorkspaces).toHaveBeenCalledTimes(1); }); it.each(['local', 'remote'] as const)( @@ -1294,18 +1354,18 @@ describe('WorkspaceManager openWorkspace promotion', () => { globalStateMocks.openRemoteWorkspace.mockResolvedValue(workspaceC); const promotedId = kind === 'local' ? workspaceB.id : workspaceC.id; - const opening = (kind === 'local' + const opened = await (kind === 'local' ? manager.openWorkspace(workspaceB.rootPath) : manager.openRemoteWorkspace({ connectionId: 'conn-1', connectionName: 'Remote', remotePath: workspaceC.rootPath, - })).catch(error => error); - await flushAsyncWork(); + })); + expect(opened.id).toBe(promotedId); expect(globalStateMocks.reorderOpenedWorkspaces).toHaveBeenCalledTimes(1); deviceSurface.activateSurface('peer-b'); finishReorder(); + await flushAsyncWork(); - expect(isSurfaceChangedError(await opening)).toBe(true); expect(manager.getState().openedWorkspaces.size).toBe(0); expect(manager.getState().currentWorkspace).toBeNull(); expect(manager.getState().error).toBeNull(); @@ -1313,6 +1373,65 @@ describe('WorkspaceManager openWorkspace promotion', () => { }, ); + it('never sends reorder persistence to a new device switched inside a workspace:opened listener', async () => { + const { manager, deviceSurface } = await getFreshWorkspaceHarness(); + await manager.initialize(); + globalStateMocks.openWorkspace.mockResolvedValue(workspaceB); + + manager.addEventListener(event => { + if (event.type === 'workspace:opened') { + deviceSurface.activateSurface('peer-b'); + } + }); + + await manager.openWorkspace(workspaceB.rootPath); + await flushAsyncWork(); + + expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled(); + expect(manager.getSurfaceOpenedWorkspaces(deviceSurface.LOCAL_SURFACE_ID)[0]?.id).toBe(workspaceB.id); + expect(manager.getState().openedWorkspaces.size).toBe(0); + }); + + it('normalizes transport failures to SurfaceChangedError when the device changed mid-open', async () => { + const { manager, deviceSurface } = await getFreshWorkspaceHarness(); + await manager.initialize(); + globalStateMocks.openWorkspace.mockImplementation(async () => { + deviceSurface.activateSurface('peer-b'); + throw new Error('peer link closed'); + }); + + const error = await manager.openWorkspace(workspaceB.rootPath).catch(cause => cause); + expect(isSurfaceChangedError(error)).toBe(true); + expect(manager.getState().error).toBeNull(); + }); + + it('does not promote or persist a reorder 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]; + globalStateMocks.initializeWorkspaceStartupState.mockResolvedValue({ + cleanupRemovedCount: 0, + recentWorkspaces: opened, + openedWorkspaces: opened, + currentWorkspace: workspaceA, + legacyRemoteWorkspace: null, + }); + globalStateMocks.getOpenedWorkspaces.mockResolvedValue(opened); + + const { manager, displayOrder } = await getFreshWorkspaceHarness(); + await manager.initialize(); + const reveals: string[] = []; + displayOrder.subscribeWorkspaceReveal(request => { reveals.push(request.workspaceId); }); + + globalStateMocks.openWorkspace.mockResolvedValue(assistantB); + await manager.openWorkspace(assistantB.rootPath); + + expect(Array.from(manager.getState().openedWorkspaces.keys())) + .toEqual([assistantA.id, assistantB.id, workspaceA.id]); + expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled(); + 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(); diff --git a/src/web-ui/src/infrastructure/services/business/workspaceManager.ts b/src/web-ui/src/infrastructure/services/business/workspaceManager.ts index 52545b5da0..8323971f05 100644 --- a/src/web-ui/src/infrastructure/services/business/workspaceManager.ts +++ b/src/web-ui/src/infrastructure/services/business/workspaceManager.ts @@ -1,8 +1,12 @@ import { + clearPendingWorkspaceReveal, noteWorkspaceActivated, + noteWorkspaceOrderPersisted, orderWorkspacesForDisplay, + prepareWorkspacePromotion, + requestWorkspaceReveal, setWorkspaceDisplayOrder, stableWorkspaceOrder, } from './workspaceDisplayOrder'; @@ -77,12 +81,6 @@ interface WorkspaceIdentityChangedEvent { export type WorkspaceEvent = | { type: 'workspace:opened'; workspace: WorkspaceInfo } - /** - * An explicit add moved an already opened workspace to the front of its - * sidebar section. Emitted before the reordered state is published so views - * can measure the old layout and bring the row into view. - */ - | { type: 'workspace:promoted'; workspaceId: string } | { type: 'workspace:closed'; workspaceId: string } | { type: 'workspace:removed'; workspaceId: string } | { type: 'workspace:switched'; workspace: WorkspaceInfo } @@ -149,6 +147,8 @@ 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,6 +170,7 @@ function createWorkspaceSurfaceContainer(): WorkspaceSurfaceContainer { startupLegacyRemoteWorkspace: null, catalogResyncInFlight: false, catalogResyncPending: false, + catalogMutationDepth: 0, }; } @@ -400,22 +401,25 @@ class WorkspaceManager { * previous list instead let the two projections adopt each other's order on * every switch. */ - private preserveOpenedWorkspaceOrder(workspaces: WorkspaceInfo[]): WorkspaceInfo[] { - return stableWorkspaceOrder(getActiveSurfaceId(), workspaces); + private preserveOpenedWorkspaceOrder( + workspaces: WorkspaceInfo[], + surfaceId: DeviceSurfaceId = getActiveSurfaceId(), + ): WorkspaceInfo[] { + return stableWorkspaceOrder(surfaceId, workspaces); } private buildReorderedOpenedWorkspaceIds( section: WorkspaceSection, sourceWorkspaceId: string, targetWorkspaceId: string, - position: WorkspaceReorderPosition + position: WorkspaceReorderPosition, + openedWorkspaces: readonly WorkspaceInfo[] = this.getOpenedWorkspacesList(), ): string[] | null { if (sourceWorkspaceId === targetWorkspaceId) { return null; } - const openedWorkspaces = this.getOpenedWorkspacesList(); - const workspaceMap = this.buildOpenedWorkspaceMap(openedWorkspaces); + const workspaceMap = this.buildOpenedWorkspaceMap(Array.from(openedWorkspaces)); const sourceWorkspace = workspaceMap.get(sourceWorkspaceId); const targetWorkspace = workspaceMap.get(targetWorkspaceId); @@ -484,11 +488,13 @@ class WorkspaceManager { openedWorkspaces: WorkspaceInfo[], loading: boolean, error: string | null, - event?: WorkspaceEvent + event?: WorkspaceEvent, + options?: { surfaceId?: DeviceSurfaceId; preordered?: boolean }, ): void { + const surfaceId = options?.surfaceId ?? getActiveSurfaceId(); // Every list a host returns is shown in this surface's one display order. const openedWorkspaceMap = this.buildOpenedWorkspaceMap( - stableWorkspaceOrder(getActiveSurfaceId(), openedWorkspaces), + options?.preordered ? openedWorkspaces : stableWorkspaceOrder(surfaceId, openedWorkspaces), ); const resolvedCurrentWorkspace = currentWorkspace @@ -741,7 +747,12 @@ class WorkspaceManager { return; } const container = this.activeSurface; - if (!container.isInitialized || container.catalogResyncInFlight || container.state.loading) { + if ( + !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 // first re-reads once more (`updateState` drains the pending flag). @@ -758,6 +769,7 @@ class WorkspaceManager { && container.isInitialized && !container.catalogResyncInFlight && !container.state.loading + && container.catalogMutationDepth === 0 ) { void this.resyncWorkspaceCatalog(container); } @@ -1070,93 +1082,101 @@ class WorkspaceManager { /** Permanently release one detached peer's cached workspace projection. */ public discardDeviceSurface(surfaceId: DeviceSurfaceId): void { + clearPendingWorkspaceReveal(surfaceId); this.surfaceContainers.delete(surfaceId); } - /** - * The opened list with `workspaceId` first within its sidebar section - * (projects or assistants), or null when it is already first or not listed. - * The other section keeps its slots, like a drag reorder, so the pinned - * assistant's stored position is untouched. The list is one device's, so the - * device order never changes. - */ - private buildPromotedOpenedWorkspaces( - workspaceId: string, - orderedOpened: WorkspaceInfo[], - ): WorkspaceInfo[] | null { - const target = orderedOpened.find(item => item.id === workspaceId); - if (!target) { - return null; - } - const section: WorkspaceSection = this.isWorkspaceInSection(target, 'assistants') ? 'assistants' : 'projects'; - const sectionWorkspaces = orderedOpened.filter(item => this.isWorkspaceInSection(item, section)); - if (sectionWorkspaces[0]?.id === workspaceId) { - return null; - } - const promotedSection = [target, ...sectionWorkspaces.filter(item => item.id !== workspaceId)]; - let cursor = 0; - return orderedOpened.map(item => ( - this.isWorkspaceInSection(item, section) ? promotedSection[cursor++] : item - )); - } - /** * Publish a workspace the host just opened. When the user explicitly added a - * workspace this device already had open, it moves to the front of its - * section so the add has a visible effect; the order is shown first and - * persisted afterwards, and a host that cannot persist it keeps the shown - * order for this window. + * 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. */ - private async publishOpenedWorkspace( + private publishOpenedWorkspace( surface: SurfaceCapture, - action: string, + container: WorkspaceSurfaceContainer, workspace: WorkspaceInfo, recentWorkspaces: WorkspaceInfo[], openedWorkspaces: WorkspaceInfo[], promote: boolean, - ): Promise { - const promoted = promote - ? this.buildPromotedOpenedWorkspaces(workspace.id, this.preserveOpenedWorkspaceOrder(openedWorkspaces)) + 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; - const promotedIds = promoted?.map(item => item.id) ?? null; + + let finalOpened = orderedOpened; if (promotedIds) { - setWorkspaceDisplayOrder(surface.scope.surfaceId, promotedIds); - this.emit({ type: 'workspace:promoted', workspaceId: workspace.id }); + const byId = this.buildOpenedWorkspaceMap(orderedOpened); + finalOpened = promotedIds + .map(id => byId.get(id)) + .filter((item): item is WorkspaceInfo => Boolean(item)); + setWorkspaceDisplayOrder(surfaceId, promotedIds); + prepareWorkspacePromotion(surfaceId, workspace.id); + container.catalogMutationDepth += 1; } this.updateWorkspaceState( workspace, recentWorkspaces, - promoted ?? openedWorkspaces, + finalOpened, false, null, - { type: 'workspace:opened', workspace } + { type: 'workspace:opened', workspace }, + { surfaceId, preordered: true }, ); - if (!promotedIds) { - return; + 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)) { - throw 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(); } - log.warn('Failed to persist promoted workspace order', { - workspaceId: workspace.id, - error, - }); } - this.assertSurfaceUnchanged(surface, action); } - /** - * 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. - */ - public async openWorkspace(path: string): Promise { + private async runOpenWorkspaceFlow( + action: string, + options: { promoteIfOpened?: boolean }, + openOnHost: () => Promise, + handleSpecialError: (error: unknown) => boolean, + ): Promise { + 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()); @@ -1164,36 +1184,63 @@ class WorkspaceManager { this.setLoading(true); this.setError(null); - log.info('Opening workspace', { path }); + const workspace = await openOnHost(); + this.assertSurfaceUnchanged(surface, action); - const workspace = await globalStateAPI.openWorkspace(path); + // Catalog hints emitted before these reads are covered by them. + container.catalogResyncPending = false; const [recentWorkspaces, openedWorkspaces] = await Promise.all([ globalStateAPI.getRecentWorkspaces(), globalStateAPI.getOpenedWorkspaces(), ]); - this.assertSurfaceUnchanged(surface, 'open workspace'); + this.assertSurfaceUnchanged(surface, action); - await this.publishOpenedWorkspace( + this.publishOpenedWorkspace( surface, - 'open workspace', + container, workspace, recentWorkspaces, openedWorkspaces, - openedBefore.has(workspace.id), + promoteIfOpened && openedBefore.has(workspace.id), + promoteIfOpened, ); return workspace; } catch (error) { if (!this.isSurfaceUnchanged(surface)) { + throw isSurfaceChangedError(error) + ? error + : new SurfaceChangedError(surface.scope.surfaceId, surface.scope.epoch, action); + } + if (handleSpecialError(error)) { throw error; } - log.error('Failed to open workspace', { path, error }); const errorMessage = error instanceof Error ? error.message : String(error); this.updateState({ loading: false, error: errorMessage }, { type: 'workspace:error', error: errorMessage }); throw error; } } + /** + * 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. + */ + public async openWorkspace(path: string): Promise { + return this.runOpenWorkspaceFlow( + 'open workspace', + {}, + () => { + log.info('Opening workspace', { path }); + return globalStateAPI.openWorkspace(path); + }, + error => { + log.error('Failed to open workspace', { path, error }); + return false; + }, + ); + } + public async openRemoteWorkspace(remoteWorkspace: { connectionId: string; connectionName: string; @@ -1201,55 +1248,31 @@ class WorkspaceManager { sshHost?: string; }, options: OpenRemoteWorkspaceRequestOptions = {}): Promise { const { promoteIfOpened = true, ...hostOptions } = options; - const surface = this.captureSurface(); - const openedBefore = new Set(this.state.openedWorkspaces.keys()); - try { - this.setLoading(true); - this.setError(null); - - log.info('Opening remote workspace', remoteWorkspace); - - const remotePath = normalizeRemoteWorkspacePath(remoteWorkspace.remotePath); - - const workspace = await globalStateAPI.openRemoteWorkspace( - remotePath, - remoteWorkspace.connectionId, - remoteWorkspace.connectionName, - remoteWorkspace.sshHost, - hostOptions, - ); - - const [recentWorkspaces, openedWorkspaces] = await Promise.all([ - globalStateAPI.getRecentWorkspaces(), - globalStateAPI.getOpenedWorkspaces(), - ]); - this.assertSurfaceUnchanged(surface, 'open remote workspace'); - - await this.publishOpenedWorkspace( - surface, - 'open remote workspace', - workspace, - recentWorkspaces, - openedWorkspaces, - promoteIfOpened && openedBefore.has(workspace.id), - ); - - return workspace; - } catch (error) { - if (!this.isSurfaceUnchanged(surface)) { - throw error; - } - if (isRemoteWorkspaceConnectionConflictError(error)) { - // The caller owns the decision; the record is unchanged on the host. - log.warn('Remote workspace is bound to another SSH connection', { remoteWorkspace }); - this.setLoading(false); - throw error; - } - log.error('Failed to open remote workspace', { remoteWorkspace, error }); - const errorMessage = error instanceof Error ? error.message : String(error); - this.updateState({ loading: false, error: errorMessage }, { type: 'workspace:error', error: errorMessage }); - throw error; - } + return this.runOpenWorkspaceFlow( + 'open remote workspace', + { promoteIfOpened }, + () => { + log.info('Opening remote workspace', remoteWorkspace); + const remotePath = normalizeRemoteWorkspacePath(remoteWorkspace.remotePath); + return globalStateAPI.openRemoteWorkspace( + remotePath, + remoteWorkspace.connectionId, + remoteWorkspace.connectionName, + remoteWorkspace.sshHost, + hostOptions, + ); + }, + error => { + if (isRemoteWorkspaceConnectionConflictError(error)) { + // The caller owns the decision; the record is unchanged on the host. + log.warn('Remote workspace is bound to another SSH connection', { remoteWorkspace }); + this.setLoading(false); + return true; + } + log.error('Failed to open remote workspace', { remoteWorkspace, error }); + return false; + }, + ); } /** @@ -1379,6 +1402,7 @@ class WorkspaceManager { globalStateAPI.getOpenedWorkspaces(), ]); this.assertSurfaceUnchanged(surface, 'close workspace'); + clearPendingWorkspaceReveal(surface.scope.surfaceId); this.updateWorkspaceState( currentWorkspace, @@ -1561,6 +1585,7 @@ class WorkspaceManager { ? await globalStateAPI.openWorkspaceById(workspaceId) : 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); @@ -1650,24 +1675,30 @@ class WorkspaceManager { return; } - setWorkspaceDisplayOrder(getActiveSurfaceId(), reorderedOpenedWorkspaces.map(workspace => workspace.id)); + const surfaceId = surface.scope.surfaceId; + setWorkspaceDisplayOrder(surfaceId, reorderedOpenedWorkspaces.map(workspace => workspace.id)); this.updateWorkspaceState( previousCurrentWorkspace, previousRecentWorkspaces, reorderedOpenedWorkspaces, false, null, - { type: 'workspace:updated', workspace: reorderedEventWorkspace } + { type: 'workspace:updated', workspace: reorderedEventWorkspace }, + { surfaceId, preordered: true }, ); try { + this.assertSurfaceUnchanged(surface, 'reorder opened workspaces'); await globalStateAPI.reorderOpenedWorkspaces(reorderedOpenedWorkspaceIds); + noteWorkspaceOrderPersisted(surfaceId, reorderedOpenedWorkspaceIds); } catch (error) { if (!this.isSurfaceUnchanged(surface)) { - throw error; + throw isSurfaceChangedError(error) + ? error + : new SurfaceChangedError(surfaceId, surface.scope.epoch, 'reorder opened workspaces'); } const errorMessage = error instanceof Error ? error.message : String(error); - setWorkspaceDisplayOrder(getActiveSurfaceId(), previousOpenedWorkspaces.map(workspace => workspace.id)); + setWorkspaceDisplayOrder(surfaceId, previousOpenedWorkspaces.map(workspace => workspace.id)); const rollbackEventWorkspace = previousCurrentWorkspace ?? workspaceMap.get(sourceWorkspaceId) ?? previousOpenedWorkspaces[0] @@ -1678,7 +1709,8 @@ class WorkspaceManager { previousOpenedWorkspaces, false, errorMessage, - { type: 'workspace:updated', workspace: rollbackEventWorkspace } + { type: 'workspace:updated', workspace: rollbackEventWorkspace }, + { surfaceId, preordered: true }, ); this.emit({ type: 'workspace:error', error: errorMessage }); throw error;