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 dccf49bbdc..487b80dece 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,8 +19,17 @@ 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', () => ({ @@ -426,6 +435,40 @@ describe('assistant pinning', () => { }); }); +describe('re-added workspace promotion', () => { + it('brings the promoted row into view once the new order renders', () => { + state.grouping = 'grouped'; + 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 { + // An unrelated re-render does not scroll. + list.render(); + expect(scrollIntoView).not.toHaveBeenCalled(); + + act(() => state.managerListeners.forEach(listener => listener({ + type: 'workspace:promoted', workspaceId: second.id, + }))); + state.workspaces = [second, first]; + list.render(); + + expect(list.ownerRows()).toEqual([second.id, first.id]); + expect(scrolled).toEqual([second.id]); + expect(scrollIntoView).toHaveBeenCalledWith({ block: 'nearest' }); + } finally { + list.unmount(); + delete (HTMLElement.prototype as { scrollIntoView?: unknown }).scrollIntoView; + } + }); +}); + describe('project disclosure across view changes', () => { it('retains folded projects and reopened projects after Collapse All', () => { state.grouping = 'grouped'; 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 8ce7921d45..86312d84d6 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,6 +1,7 @@ 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 { useSceneStore } from '@/app/stores/sceneStore'; import { useContentResourceStore } from '@/app/workbench/contentResourceStore'; import { getActiveSurfaceId, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface'; @@ -92,6 +93,7 @@ const WorkspaceListSection: React.FC = ({ variant, sc const pendingDragEndRef = useRef | undefined>(undefined); const workspaceRowRefs = useRef>(new Map()); const pendingDropRectsRef = useRef | null>(null); + const pendingRevealWorkspaceIdRef = useRef(null); const dropAnimationsRef = useRef>(new Map()); const sectionWorkspaces = variant === 'all' @@ -165,8 +167,25 @@ const WorkspaceListSection: React.FC = ({ variant, sc useLayoutEffect(() => { resetDragState(); pendingDropRectsRef.current = null; + pendingRevealWorkspaceIdRef.current = null; }, [grouping, surfaceId, variant, resetDragState]); + const measureWorkspaceRows = useCallback(() => new Map( + Array.from(workspaceRowRefs.current, ([id, element]) => ( + [id, element.getBoundingClientRect()] as const + )), + ), []); + + // 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]); + useLayoutEffect(() => { if (draggedWorkspaceId && !canContinueDrag) { resetDragState(); @@ -222,6 +241,14 @@ const WorkspaceListSection: React.FC = ({ variant, sc }, []); 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 previousRects = pendingDropRectsRef.current; if (!previousRects) return; pendingDropRectsRef.current = null; @@ -339,11 +366,7 @@ const WorkspaceListSection: React.FC = ({ variant, sc event.stopPropagation(); // Keep the slot measured by dragover, before the drop line changed layout. - pendingDropRectsRef.current = new Map( - Array.from(workspaceRowRefs.current, ([id, element]) => ( - [id, element.getBoundingClientRect()] as const - )), - ); + pendingDropRectsRef.current = measureWorkspaceRows(); try { await reorderOpenedWorkspacesInSection(reorderSection, payload.workspaceId, workspaceId, position); @@ -354,7 +377,7 @@ const WorkspaceListSection: React.FC = ({ variant, sc { duration: 4000 } ); } - }, [reorderOpenedWorkspacesInSection, reorderSection, resetDragState, t, variant]); + }, [measureWorkspaceRows, reorderOpenedWorkspacesInSection, reorderSection, resetDragState, t, variant]); /** * One session-group row. Pinned assistants and project workspaces share the diff --git a/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.test.tsx b/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.test.tsx index 233b7e0f65..98eb4b5ad4 100644 --- a/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.test.tsx +++ b/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.test.tsx @@ -1485,7 +1485,8 @@ describe('SSHRemoteProvider remote workspace connection conflicts', () => { await renderProvider(); expect(workspaceManagerMock.openRemoteWorkspace).toHaveBeenCalledTimes(1); - expect(workspaceManagerMock.openRemoteWorkspace.mock.calls[0]).toHaveLength(1); + // Never rebinds, and restore never moves the record in the sidebar. + expect(workspaceManagerMock.openRemoteWorkspace.mock.calls[0][1]).toEqual({ promoteIfOpened: false }); expect(confirmWarningMock).not.toHaveBeenCalled(); expect(notificationService.warning).toHaveBeenCalledWith( 'ssh.remote.connectionConflictRestoreDeferred {"path":"/srv/shared"}', diff --git a/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.tsx b/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.tsx index e81d8b875c..c383e53e95 100644 --- a/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.tsx +++ b/src/web-ui/src/features/ssh-remote/SSHRemoteProvider.tsx @@ -424,8 +424,9 @@ export const SSHRemoteProvider: React.FC = ({ children } scope: SurfaceScope, ): Promise => { try { + // Restoring is not an add: it must not move the record in the sidebar. return await runInSurfaceScope(scope, 'restore SSH workspace record', () => - workspaceManager.openRemoteWorkspace(workspace)); + workspaceManager.openRemoteWorkspace(workspace, { promoteIfOpened: false })); } catch (error) { scope.assertCurrent('restore SSH workspace record'); if (!isRemoteWorkspaceConnectionConflictError(error)) { 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 8159d41d62..bfb4ec7008 100644 --- a/src/web-ui/src/infrastructure/services/business/workspaceManager.test.ts +++ b/src/web-ui/src/infrastructure/services/business/workspaceManager.test.ts @@ -1259,8 +1259,31 @@ 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(); + 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(); + + 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')); + finishReorder(); + await expect(opening).resolves.toBe(workspaceB); + }); + it.each(['local', 'remote'] as const)( - 'does not apply a completed %s promotion after the device changes', + 'keeps a %s promotion on its own device when the device changes during persistence', async kind => { const { manager, deviceSurface } = await getFreshWorkspaceHarness(); await manager.initialize(); @@ -1269,6 +1292,7 @@ describe('WorkspaceManager openWorkspace promotion', () => { globalStateMocks.reorderOpenedWorkspaces.mockReturnValueOnce(reordered); globalStateMocks.openWorkspace.mockResolvedValue(workspaceB); globalStateMocks.openRemoteWorkspace.mockResolvedValue(workspaceC); + const promotedId = kind === 'local' ? workspaceB.id : workspaceC.id; const opening = (kind === 'local' ? manager.openWorkspace(workspaceB.rootPath) @@ -1278,18 +1302,88 @@ describe('WorkspaceManager openWorkspace promotion', () => { await flushAsyncWork(); expect(globalStateMocks.reorderOpenedWorkspaces).toHaveBeenCalledTimes(1); - // The promotion's await resumes first; activation then precedes its caller's continuation. - const switched = reordered.then(() => deviceSurface.activateSurface('peer-b')); + deviceSurface.activateSurface('peer-b'); finishReorder(); - await switched; expect(isSurfaceChangedError(await opening)).toBe(true); 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('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 () => { + const assistant = { ...workspaceA, id: 'assistant', rootPath: '/assistant', workspaceKind: 'assistant' }; + const opened = [assistant, workspaceA, workspaceB]; + globalStateMocks.initializeWorkspaceStartupState.mockResolvedValue({ + cleanupRemovedCount: 0, + recentWorkspaces: opened, + openedWorkspaces: opened, + currentWorkspace: workspaceA, + legacyRemoteWorkspace: null, + }); + globalStateMocks.getOpenedWorkspaces.mockResolvedValue(opened); + const manager = await getFreshWorkspaceManager(); + await manager.initialize(); + + globalStateMocks.openWorkspace.mockResolvedValue(workspaceA); + await manager.openWorkspace(workspaceA.rootPath); + expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled(); + + globalStateMocks.openWorkspace.mockResolvedValue(workspaceB); + 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]); + }); + + it('does not move a remote record that a background restore reopens', async () => { + const manager = await getFreshWorkspaceManager(); + await manager.initialize(); + globalStateMocks.openRemoteWorkspace.mockResolvedValue(workspaceC); + + await manager.openRemoteWorkspace({ + connectionId: 'conn-1', connectionName: 'Remote', remotePath: workspaceC.rootPath, + }, { promoteIfOpened: false }); + + 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(); diff --git a/src/web-ui/src/infrastructure/services/business/workspaceManager.ts b/src/web-ui/src/infrastructure/services/business/workspaceManager.ts index e9cf624a60..52545b5da0 100644 --- a/src/web-ui/src/infrastructure/services/business/workspaceManager.ts +++ b/src/web-ui/src/infrastructure/services/business/workspaceManager.ts @@ -77,6 +77,12 @@ 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 } @@ -103,6 +109,16 @@ 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 WorkspaceReorderPosition = 'before' | 'after'; /** @@ -1058,30 +1074,72 @@ class WorkspaceManager { } /** - * Move an already-opened workspace to the front of this device's opened list - * when the user explicitly adds/opens it again, without changing device order. + * 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. */ - private async promoteExistingOpenedWorkspace( + private async publishOpenedWorkspace( surface: SurfaceCapture, + action: string, workspace: WorkspaceInfo, + recentWorkspaces: WorkspaceInfo[], openedWorkspaces: WorkspaceInfo[], - wasAlreadyOpened: boolean, - ): Promise { - const orderedOpened = this.preserveOpenedWorkspaceOrder(openedWorkspaces); - if (!wasAlreadyOpened || orderedOpened.length <= 1 || orderedOpened[0]?.id === workspace.id) { - return orderedOpened; + promote: boolean, + ): Promise { + const promoted = promote + ? this.buildPromotedOpenedWorkspaces(workspace.id, this.preserveOpenedWorkspaceOrder(openedWorkspaces)) + : null; + const promotedIds = promoted?.map(item => item.id) ?? null; + if (promotedIds) { + setWorkspaceDisplayOrder(surface.scope.surfaceId, promotedIds); + this.emit({ type: 'workspace:promoted', workspaceId: workspace.id }); } - const target = orderedOpened.find(item => item.id === workspace.id) ?? workspace; - const promoted = [target, ...orderedOpened.filter(item => item.id !== workspace.id)]; - const promotedIds = promoted.map(item => item.id); - setWorkspaceDisplayOrder(surface.scope.surfaceId, promotedIds); + this.updateWorkspaceState( + workspace, + recentWorkspaces, + promoted ?? openedWorkspaces, + false, + null, + { type: 'workspace:opened', workspace } + ); + if (!promotedIds) { + return; + } try { await globalStateAPI.reorderOpenedWorkspaces(promotedIds); - this.assertSurfaceUnchanged(surface, 'promote opened workspace'); } catch (error) { - if (!this.isSurfaceUnchanged(surface)) { + if (isSurfaceChangedError(error) || !this.isSurfaceUnchanged(surface)) { throw error; } log.warn('Failed to persist promoted workspace order', { @@ -1089,12 +1147,19 @@ class WorkspaceManager { error, }); } - - return promoted; + 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 { const surface = this.captureSurface(); + // 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); @@ -1108,22 +1173,13 @@ class WorkspaceManager { ]); this.assertSurfaceUnchanged(surface, 'open workspace'); - const wasAlreadyOpened = this.state.openedWorkspaces.has(workspace.id); - const orderedOpened = await this.promoteExistingOpenedWorkspace( + await this.publishOpenedWorkspace( surface, - workspace, - openedWorkspaces, - wasAlreadyOpened, - ); - this.assertSurfaceUnchanged(surface, 'open workspace'); - - this.updateWorkspaceState( + 'open workspace', workspace, recentWorkspaces, - orderedOpened, - false, - null, - { type: 'workspace:opened', workspace } + openedWorkspaces, + openedBefore.has(workspace.id), ); return workspace; @@ -1143,8 +1199,10 @@ class WorkspaceManager { connectionName: string; remotePath: string; sshHost?: string; - }, options: OpenRemoteWorkspaceOptions = {}): Promise { + }, 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); @@ -1158,7 +1216,7 @@ class WorkspaceManager { remoteWorkspace.connectionId, remoteWorkspace.connectionName, remoteWorkspace.sshHost, - options, + hostOptions, ); const [recentWorkspaces, openedWorkspaces] = await Promise.all([ @@ -1167,22 +1225,13 @@ class WorkspaceManager { ]); this.assertSurfaceUnchanged(surface, 'open remote workspace'); - const wasAlreadyOpened = this.state.openedWorkspaces.has(workspace.id); - const orderedOpened = await this.promoteExistingOpenedWorkspace( + await this.publishOpenedWorkspace( surface, - workspace, - openedWorkspaces, - wasAlreadyOpened, - ); - this.assertSurfaceUnchanged(surface, 'open remote workspace'); - - this.updateWorkspaceState( + 'open remote workspace', workspace, recentWorkspaces, - orderedOpened, - false, - null, - { type: 'workspace:opened', workspace } + openedWorkspaces, + promoteIfOpened && openedBefore.has(workspace.id), ); return workspace;