Skip to content

Commit b2d33ee

Browse files
authored
Merge pull request #3939 from bobleer/bob/promote-workspace-followup
fix(web-ui): show re-added workspace promotion immediately and keep it scoped
2 parents 8cd6f3f + b0f6003 commit b2d33ee

6 files changed

Lines changed: 267 additions & 56 deletions

File tree

‎src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSection.test.tsx‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,17 @@ const state = vi.hoisted(() => {
1919
workspaces: [assistant, project],
2020
defaultWorkspaces: [assistant, project],
2121
reorder: vi.fn<(...args: unknown[]) => Promise<void>>().mockResolvedValue(undefined),
22+
managerListeners: new Set<(event: { type: string; workspaceId?: string }) => void>(),
2223
};
2324
});
25+
vi.mock('@/infrastructure/services/business/workspaceManager', () => ({
26+
workspaceManager: {
27+
addEventListener: (listener: (event: { type: string; workspaceId?: string }) => void) => {
28+
state.managerListeners.add(listener);
29+
return () => { state.managerListeners.delete(listener); };
30+
},
31+
},
32+
}));
2433
vi.mock('@/infrastructure/i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) }));
2534
vi.mock('@/shared/notification-system', () => ({ notificationService: { error: vi.fn() } }));
2635
vi.mock('@/infrastructure/contexts/WorkspaceContext', () => ({
@@ -426,6 +435,40 @@ describe('assistant pinning', () => {
426435
});
427436
});
428437

438+
describe('re-added workspace promotion', () => {
439+
it('brings the promoted row into view once the new order renders', () => {
440+
state.grouping = 'grouped';
441+
const first = { id: 'first-project', name: 'First', workspaceKind: 'normal' };
442+
const second = { id: 'second-project', name: 'Second', workspaceKind: 'normal' };
443+
state.workspaces = [first, second];
444+
const scrolled: Array<string | null> = [];
445+
const scrollIntoView = vi.fn(function (this: HTMLElement) {
446+
scrolled.push(this.getAttribute('data-workspace-id'));
447+
});
448+
Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', { configurable: true, value: scrollIntoView });
449+
450+
const list = renderList();
451+
try {
452+
// An unrelated re-render does not scroll.
453+
list.render();
454+
expect(scrollIntoView).not.toHaveBeenCalled();
455+
456+
act(() => state.managerListeners.forEach(listener => listener({
457+
type: 'workspace:promoted', workspaceId: second.id,
458+
})));
459+
state.workspaces = [second, first];
460+
list.render();
461+
462+
expect(list.ownerRows()).toEqual([second.id, first.id]);
463+
expect(scrolled).toEqual([second.id]);
464+
expect(scrollIntoView).toHaveBeenCalledWith({ block: 'nearest' });
465+
} finally {
466+
list.unmount();
467+
delete (HTMLElement.prototype as { scrollIntoView?: unknown }).scrollIntoView;
468+
}
469+
});
470+
});
471+
429472
describe('project disclosure across view changes', () => {
430473
it('retains folded projects and reopened projects after Collapse All', () => {
431474
state.grouping = 'grouped';

‎src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceListSection.tsx‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
22
import { useI18n } from '@/infrastructure/i18n';
33
import { useWorkspaceContext } from '@/infrastructure/contexts/WorkspaceContext';
4+
import { workspaceManager } from '@/infrastructure/services/business/workspaceManager';
45
import { useSceneStore } from '@/app/stores/sceneStore';
56
import { useContentResourceStore } from '@/app/workbench/contentResourceStore';
67
import { getActiveSurfaceId, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface';
@@ -92,6 +93,7 @@ const WorkspaceListSection: React.FC<WorkspaceListSectionProps> = ({ variant, sc
9293
const pendingDragEndRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
9394
const workspaceRowRefs = useRef<Map<string, HTMLDivElement>>(new Map());
9495
const pendingDropRectsRef = useRef<Map<string, DOMRect> | null>(null);
96+
const pendingRevealWorkspaceIdRef = useRef<string | null>(null);
9597
const dropAnimationsRef = useRef<Map<string, Animation>>(new Map());
9698

9799
const sectionWorkspaces = variant === 'all'
@@ -165,8 +167,25 @@ const WorkspaceListSection: React.FC<WorkspaceListSectionProps> = ({ variant, sc
165167
useLayoutEffect(() => {
166168
resetDragState();
167169
pendingDropRectsRef.current = null;
170+
pendingRevealWorkspaceIdRef.current = null;
168171
}, [grouping, surfaceId, variant, resetDragState]);
169172

173+
const measureWorkspaceRows = useCallback(() => new Map(
174+
Array.from(workspaceRowRefs.current, ([id, element]) => (
175+
[id, element.getBoundingClientRect()] as const
176+
)),
177+
), []);
178+
179+
// Re-adding an opened workspace moves it to the top of this device's list.
180+
// The event arrives before the new order renders, so the rows can slide like
181+
// a drop, and the row is brought into view: a move the user cannot see reads
182+
// as the add doing nothing.
183+
useEffect(() => workspaceManager.addEventListener(event => {
184+
if (event.type !== 'workspace:promoted' || !workspaceRowRefs.current.has(event.workspaceId)) return;
185+
pendingDropRectsRef.current = measureWorkspaceRows();
186+
pendingRevealWorkspaceIdRef.current = event.workspaceId;
187+
}), [measureWorkspaceRows]);
188+
170189
useLayoutEffect(() => {
171190
if (draggedWorkspaceId && !canContinueDrag) {
172191
resetDragState();
@@ -222,6 +241,14 @@ const WorkspaceListSection: React.FC<WorkspaceListSectionProps> = ({ variant, sc
222241
}, []);
223242

224243
useLayoutEffect(() => {
244+
const revealWorkspaceId = pendingRevealWorkspaceIdRef.current;
245+
pendingRevealWorkspaceIdRef.current = null;
246+
if (revealWorkspaceId) {
247+
const row = workspaceRowRefs.current.get(revealWorkspaceId);
248+
const header = row?.querySelector<HTMLElement>('.openbitfun-nav-panel__workspace-item-card') ?? row;
249+
header?.scrollIntoView?.({ block: 'nearest' });
250+
}
251+
225252
const previousRects = pendingDropRectsRef.current;
226253
if (!previousRects) return;
227254
pendingDropRectsRef.current = null;
@@ -339,11 +366,7 @@ const WorkspaceListSection: React.FC<WorkspaceListSectionProps> = ({ variant, sc
339366
event.stopPropagation();
340367

341368
// Keep the slot measured by dragover, before the drop line changed layout.
342-
pendingDropRectsRef.current = new Map(
343-
Array.from(workspaceRowRefs.current, ([id, element]) => (
344-
[id, element.getBoundingClientRect()] as const
345-
)),
346-
);
369+
pendingDropRectsRef.current = measureWorkspaceRows();
347370

348371
try {
349372
await reorderOpenedWorkspacesInSection(reorderSection, payload.workspaceId, workspaceId, position);
@@ -354,7 +377,7 @@ const WorkspaceListSection: React.FC<WorkspaceListSectionProps> = ({ variant, sc
354377
{ duration: 4000 }
355378
);
356379
}
357-
}, [reorderOpenedWorkspacesInSection, reorderSection, resetDragState, t, variant]);
380+
}, [measureWorkspaceRows, reorderOpenedWorkspacesInSection, reorderSection, resetDragState, t, variant]);
358381

359382
/**
360383
* One session-group row. Pinned assistants and project workspaces share the

‎src/web-ui/src/features/ssh-remote/SSHRemoteProvider.test.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1485,7 +1485,8 @@ describe('SSHRemoteProvider remote workspace connection conflicts', () => {
14851485
await renderProvider();
14861486

14871487
expect(workspaceManagerMock.openRemoteWorkspace).toHaveBeenCalledTimes(1);
1488-
expect(workspaceManagerMock.openRemoteWorkspace.mock.calls[0]).toHaveLength(1);
1488+
// Never rebinds, and restore never moves the record in the sidebar.
1489+
expect(workspaceManagerMock.openRemoteWorkspace.mock.calls[0][1]).toEqual({ promoteIfOpened: false });
14891490
expect(confirmWarningMock).not.toHaveBeenCalled();
14901491
expect(notificationService.warning).toHaveBeenCalledWith(
14911492
'ssh.remote.connectionConflictRestoreDeferred {"path":"/srv/shared"}',

‎src/web-ui/src/features/ssh-remote/SSHRemoteProvider.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -424,8 +424,9 @@ export const SSHRemoteProvider: React.FC<SSHRemoteProviderProps> = ({ children }
424424
scope: SurfaceScope,
425425
): Promise<WorkspaceInfo | null> => {
426426
try {
427+
// Restoring is not an add: it must not move the record in the sidebar.
427428
return await runInSurfaceScope(scope, 'restore SSH workspace record', () =>
428-
workspaceManager.openRemoteWorkspace(workspace));
429+
workspaceManager.openRemoteWorkspace(workspace, { promoteIfOpened: false }));
429430
} catch (error) {
430431
scope.assertCurrent('restore SSH workspace record');
431432
if (!isRemoteWorkspaceConnectionConflictError(error)) {

‎src/web-ui/src/infrastructure/services/business/workspaceManager.test.ts‎

Lines changed: 98 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1259,8 +1259,31 @@ describe('WorkspaceManager openWorkspace promotion', () => {
12591259
.toEqual([workspaceB.id, workspaceC.id, workspaceA.id]);
12601260
});
12611261

1262+
it('shows the promoted order before the host finishes persisting it', async () => {
1263+
const manager = await getFreshWorkspaceManager();
1264+
await manager.initialize();
1265+
let finishReorder!: () => void;
1266+
globalStateMocks.reorderOpenedWorkspaces.mockReturnValueOnce(
1267+
new Promise<void>(resolve => { finishReorder = resolve; }),
1268+
);
1269+
globalStateMocks.openWorkspace.mockResolvedValue(workspaceB);
1270+
const events: string[] = [];
1271+
manager.addEventListener(event => { events.push(event.type); });
1272+
1273+
const opening = manager.openWorkspace(workspaceB.rootPath);
1274+
await flushAsyncWork();
1275+
1276+
expect(Array.from(manager.getState().openedWorkspaces.keys()))
1277+
.toEqual([workspaceB.id, workspaceA.id, workspaceC.id]);
1278+
expect(manager.getState().loading).toBe(false);
1279+
// Views measure the old layout on `promoted`, before the new order is published.
1280+
expect(events.indexOf('workspace:promoted')).toBeLessThan(events.indexOf('workspace:opened'));
1281+
finishReorder();
1282+
await expect(opening).resolves.toBe(workspaceB);
1283+
});
1284+
12621285
it.each(['local', 'remote'] as const)(
1263-
'does not apply a completed %s promotion after the device changes',
1286+
'keeps a %s promotion on its own device when the device changes during persistence',
12641287
async kind => {
12651288
const { manager, deviceSurface } = await getFreshWorkspaceHarness();
12661289
await manager.initialize();
@@ -1269,6 +1292,7 @@ describe('WorkspaceManager openWorkspace promotion', () => {
12691292
globalStateMocks.reorderOpenedWorkspaces.mockReturnValueOnce(reordered);
12701293
globalStateMocks.openWorkspace.mockResolvedValue(workspaceB);
12711294
globalStateMocks.openRemoteWorkspace.mockResolvedValue(workspaceC);
1295+
const promotedId = kind === 'local' ? workspaceB.id : workspaceC.id;
12721296

12731297
const opening = (kind === 'local'
12741298
? manager.openWorkspace(workspaceB.rootPath)
@@ -1278,18 +1302,88 @@ describe('WorkspaceManager openWorkspace promotion', () => {
12781302
await flushAsyncWork();
12791303
expect(globalStateMocks.reorderOpenedWorkspaces).toHaveBeenCalledTimes(1);
12801304

1281-
// The promotion's await resumes first; activation then precedes its caller's continuation.
1282-
const switched = reordered.then(() => deviceSurface.activateSurface('peer-b'));
1305+
deviceSurface.activateSurface('peer-b');
12831306
finishReorder();
1284-
await switched;
12851307

12861308
expect(isSurfaceChangedError(await opening)).toBe(true);
12871309
expect(manager.getState().openedWorkspaces.size).toBe(0);
12881310
expect(manager.getState().currentWorkspace).toBeNull();
12891311
expect(manager.getState().error).toBeNull();
1312+
expect(manager.getSurfaceOpenedWorkspaces(deviceSurface.LOCAL_SURFACE_ID)[0]?.id).toBe(promotedId);
12901313
},
12911314
);
12921315

1316+
it('does not promote a new workspace that a concurrent list refresh published first', async () => {
1317+
const manager = await getFreshWorkspaceManager();
1318+
await manager.initialize();
1319+
const added = { ...workspaceA, id: 'workspace-new', rootPath: '/repo/new' };
1320+
const hostOpened = [workspaceA, workspaceB, workspaceC, added];
1321+
1322+
// A switch whose background list refresh is still in flight.
1323+
let releaseRefresh!: (workspaces: typeof hostOpened) => void;
1324+
globalStateMocks.setActiveWorkspace.mockResolvedValue(workspaceB);
1325+
globalStateMocks.getOpenedWorkspaces.mockImplementationOnce(
1326+
() => new Promise(resolve => { releaseRefresh = resolve; }),
1327+
);
1328+
await manager.setActiveWorkspace(workspaceB.id);
1329+
1330+
globalStateMocks.getOpenedWorkspaces.mockResolvedValue(hostOpened);
1331+
globalStateMocks.openWorkspace.mockImplementation(async () => {
1332+
releaseRefresh(hostOpened);
1333+
await flushAsyncWork();
1334+
expect(manager.getState().openedWorkspaces.has(added.id)).toBe(true);
1335+
return added;
1336+
});
1337+
1338+
await manager.openWorkspace(added.rootPath);
1339+
1340+
expect(Array.from(manager.getState().openedWorkspaces.keys()))
1341+
.toEqual([workspaceA.id, workspaceB.id, workspaceC.id, added.id]);
1342+
expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled();
1343+
});
1344+
1345+
it('promotes within the project section and leaves the assistant slot alone', async () => {
1346+
const assistant = { ...workspaceA, id: 'assistant', rootPath: '/assistant', workspaceKind: 'assistant' };
1347+
const opened = [assistant, workspaceA, workspaceB];
1348+
globalStateMocks.initializeWorkspaceStartupState.mockResolvedValue({
1349+
cleanupRemovedCount: 0,
1350+
recentWorkspaces: opened,
1351+
openedWorkspaces: opened,
1352+
currentWorkspace: workspaceA,
1353+
legacyRemoteWorkspace: null,
1354+
});
1355+
globalStateMocks.getOpenedWorkspaces.mockResolvedValue(opened);
1356+
const manager = await getFreshWorkspaceManager();
1357+
await manager.initialize();
1358+
1359+
globalStateMocks.openWorkspace.mockResolvedValue(workspaceA);
1360+
await manager.openWorkspace(workspaceA.rootPath);
1361+
expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled();
1362+
1363+
globalStateMocks.openWorkspace.mockResolvedValue(workspaceB);
1364+
await manager.openWorkspace(workspaceB.rootPath);
1365+
expect(Array.from(manager.getState().openedWorkspaces.keys()))
1366+
.toEqual([assistant.id, workspaceB.id, workspaceA.id]);
1367+
expect(globalStateMocks.reorderOpenedWorkspaces)
1368+
.toHaveBeenCalledWith([assistant.id, workspaceB.id, workspaceA.id]);
1369+
});
1370+
1371+
it('does not move a remote record that a background restore reopens', async () => {
1372+
const manager = await getFreshWorkspaceManager();
1373+
await manager.initialize();
1374+
globalStateMocks.openRemoteWorkspace.mockResolvedValue(workspaceC);
1375+
1376+
await manager.openRemoteWorkspace({
1377+
connectionId: 'conn-1', connectionName: 'Remote', remotePath: workspaceC.rootPath,
1378+
}, { promoteIfOpened: false });
1379+
1380+
expect(Array.from(manager.getState().openedWorkspaces.keys()))
1381+
.toEqual([workspaceA.id, workspaceB.id, workspaceC.id]);
1382+
expect(globalStateMocks.reorderOpenedWorkspaces).not.toHaveBeenCalled();
1383+
// The manager-only flag never reaches the host.
1384+
expect(globalStateMocks.openRemoteWorkspace.mock.calls[0][4]).toEqual({});
1385+
});
1386+
12931387
it('does not persist a reorder when the workspace is already first', async () => {
12941388
const manager = await getFreshWorkspaceManager();
12951389
await manager.initialize();

0 commit comments

Comments
 (0)