Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,17 @@ const state = vi.hoisted(() => {
workspaces: [assistant, project],
defaultWorkspaces: [assistant, project],
reorder: vi.fn<(...args: unknown[]) => Promise<void>>().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', () => ({
Expand Down Expand Up @@ -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<string | null> = [];
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';
Expand Down
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -92,6 +93,7 @@ const WorkspaceListSection: React.FC<WorkspaceListSectionProps> = ({ variant, sc
const pendingDragEndRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const workspaceRowRefs = useRef<Map<string, HTMLDivElement>>(new Map());
const pendingDropRectsRef = useRef<Map<string, DOMRect> | null>(null);
const pendingRevealWorkspaceIdRef = useRef<string | null>(null);
const dropAnimationsRef = useRef<Map<string, Animation>>(new Map());

const sectionWorkspaces = variant === 'all'
Expand Down Expand Up @@ -165,8 +167,25 @@ const WorkspaceListSection: React.FC<WorkspaceListSectionProps> = ({ 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();
Expand Down Expand Up @@ -222,6 +241,14 @@ const WorkspaceListSection: React.FC<WorkspaceListSectionProps> = ({ variant, sc
}, []);

useLayoutEffect(() => {
const revealWorkspaceId = pendingRevealWorkspaceIdRef.current;
pendingRevealWorkspaceIdRef.current = null;
if (revealWorkspaceId) {
const row = workspaceRowRefs.current.get(revealWorkspaceId);
const header = row?.querySelector<HTMLElement>('.openbitfun-nav-panel__workspace-item-card') ?? row;
header?.scrollIntoView?.({ block: 'nearest' });
}

const previousRects = pendingDropRectsRef.current;
if (!previousRects) return;
pendingDropRectsRef.current = null;
Expand Down Expand Up @@ -339,11 +366,7 @@ const WorkspaceListSection: React.FC<WorkspaceListSectionProps> = ({ 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);
Expand All @@ -354,7 +377,7 @@ const WorkspaceListSection: React.FC<WorkspaceListSectionProps> = ({ 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"}',
Expand Down
3 changes: 2 additions & 1 deletion src/web-ui/src/features/ssh-remote/SSHRemoteProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -424,8 +424,9 @@ export const SSHRemoteProvider: React.FC<SSHRemoteProviderProps> = ({ children }
scope: SurfaceScope,
): Promise<WorkspaceInfo | null> => {
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)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>(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();
Expand All @@ -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)
Expand All @@ -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();
Expand Down
Loading
Loading