Skip to content

Commit 33e4a87

Browse files
committed
fix(web-ui): add removal actions to workspace history
1 parent ec72155 commit 33e4a87

10 files changed

Lines changed: 203 additions & 23 deletions

File tree

‎design-system/packages/ui/README.md‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -590,7 +590,7 @@ backing or fading parent cannot prevent it from sampling the content behind it.
590590
### Capsule actions
591591

592592
Wrap a pill-shaped `Button`, inline `Input`, or tag label in `Capsule`, matching
593-
its `size` to the child. Pass one `IconButton` (optionally inside `Tooltip`) to
593+
its `size` to the child. Pass an `IconButton` or an array of keyed `IconButton`s (optionally inside `Tooltip`) to
594594
`action`. The slot selects circular glass presentation and compact geometry;
595595
the consumer keeps the action's accessible label, tone, disabled/loading state,
596596
and callbacks. The action is a sibling of the primary control, never a nested
@@ -609,13 +609,14 @@ available. Its right inset equals the top and bottom clearance at every density.
609609
The default `actionPlacement="overlay"` floats over the intact label: do not clip,
610610
mask, hide, resize, or add action padding to its text when revealing the icon.
611611
Use `actionPlacement="reserved"` with a `Button` child for short selectable labels.
612-
The Button always reserves trailing padding for the action inside its pill surface,
613-
keeping the gaps between capsules compact. Its content is centered at rest, then
612+
The Button always reserves trailing padding for one action inside its pill surface,
613+
keeping the gaps between capsules compact. Additional actions overlay the content
614+
without adding padding. Its content is centered at rest, then
614615
shifts toward the leading edge as the icon fades in on pointer hover. Only the
615616
content transform and icon opacity change: hovering a row-end capsule cannot
616617
change its width or trigger wrapping. Keyboard focus reveals the action and moves
617-
the content immediately; touch keeps the action visible and the content clear of
618-
it. Reduced motion disables both transitions. Capsules without an action do not
618+
the content immediately; touch keeps the actions visible.
619+
Reduced motion disables both transitions. Capsules without an action do not
619620
reserve empty space.
620621
Normal constrained-width `OverflowText` behavior remains available.
621622
`TabGroupItem.endAction` uses a reserved slot as described above; removable

‎design-system/packages/ui/src/components/Capsule/Capsule.tsx‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { forwardRef, type HTMLAttributes, type ReactNode } from "react";
1+
import { Children, forwardRef, type HTMLAttributes, type ReactNode } from "react";
22
import { classNames } from "../../internal/classNames";
33
import { FloatingAction } from "../../internal/FloatingAction";
44
import actionStyles from "../../internal/FloatingAction.module.css";
@@ -9,9 +9,9 @@ export interface CapsuleProps extends HTMLAttributes<HTMLSpanElement> {
99
layout?: "inline" | "split";
1010
/** Fit both split controls and the capsule to their content, or use equal halves. */
1111
splitSizing?: "equal" | "content";
12-
/** One IconButton (optionally wrapped in Tooltip), rendered beside the content. */
12+
/** An IconButton or array of IconButtons (optionally wrapped in Tooltip). */
1313
action?: ReactNode;
14-
/** Reserve a fixed action slot inside a Button child's trailing padding. */
14+
/** Reserve one fixed action slot; additional actions overlay the content. */
1515
actionPlacement?: "overlay" | "reserved";
1616
/** Match the size of the child Button, Input, or label surface. */
1717
size?: "xs" | "sm" | "md" | "lg";
@@ -28,12 +28,13 @@ export const Capsule = forwardRef<HTMLSpanElement, CapsuleProps>(function Capsul
2828
splitSizing = "equal",
2929
...props
3030
}, ref) {
31+
const actionCount = Children.toArray(action).length;
3132
return (
3233
<span {...props} className={classNames(actionStyles.host, styles.root, className)}
3334
data-openbitfun-component="capsule" data-layout={layout} data-size={size} data-split-sizing={layout === "split" ? splitSizing : undefined}
34-
data-action-placement={action != null ? actionPlacement : undefined} data-overflow-trigger ref={ref}>
35+
data-action-placement={actionCount > 0 ? actionPlacement : undefined} data-overflow-trigger ref={ref}>
3536
{children}
36-
{action != null && <FloatingAction data-openbitfun-part="action"
37+
{actionCount > 0 && <FloatingAction data-openbitfun-part="action" group={actionCount > 1}
3738
className={actionPlacement === "reserved" ? styles.reservedAction : undefined}>{action}</FloatingAction>}
3839
</span>
3940
);

‎design-system/packages/ui/tests/capsule.test.mjs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,19 @@ test("capsules without actions preserve ordinary content and do not add a focus
3737
assert.doesNotMatch(markup, /tabindex|role=|data-openbitfun-part="action"|data-action-placement/);
3838
});
3939

40+
test("reserved capsules group multiple independent actions in a single reserved slot", () => {
41+
const markup = renderToStaticMarkup(h(Capsule, {
42+
size: "xs", actionPlacement: "reserved",
43+
action: [h(Tooltip, { key: "edit", content: "Edit host" }, action({ "aria-label": "Edit host" })),
44+
false, action({ key: "delete", "aria-label": "Delete host" })],
45+
}, h(Button, { size: "xs" }, "Build host")));
46+
assert.match(markup, /data-action-placement="reserved"/);
47+
assert.match(markup, /data-floating-action-group="true"/);
48+
assert.equal((markup.match(/<button\b/g) ?? []).length, 3);
49+
assert.match(markup, /aria-label="Edit host"/);
50+
assert.match(markup, /aria-label="Delete host"/);
51+
});
52+
4053
test("split capsules align filled edges with equal or compact content-sized widths", async () => {
4154
const markup = renderToStaticMarkup(h(Capsule, { layout: "split", splitSizing: "content", size: "sm", role: "group", "aria-label": "Provider" },
4255
h(Select, { size: "sm", variant: "pill", width: "content", "aria-label": "Region", options: [{ value: "international", label: "International" }] }),

‎src/web-ui/src/app/components/NewProjectDialog/NewProjectDialog.test.tsx‎

Lines changed: 91 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { activateSurface, resetDeviceSurfaceForTest, surfaceIdForDevice } from '
77
import { AssistantProjectFolderError, ProjectDirectoryUnavailableError } from '@/app/utils/projectDraft';
88
import { globalAPI, type WorkspaceInfo } from '@/infrastructure/api/service-api/GlobalAPI';
99
import type { WorkspaceSourceOption } from '@/features/ssh-remote/useWorkspaceSourceOptions';
10+
import { sshApi } from '@/features/ssh-remote/sshApi';
1011
import { PeerDeviceContext, type PeerDeviceContextValue } from '@/infrastructure/peer-device/peerDeviceContextState';
1112

1213
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
@@ -15,10 +16,10 @@ vi.mock('@/infrastructure/api/service-api/RemoteConnectAPI', async importOrigina
1516
remoteConnectAPI: { getDeviceInfo: async () => ({ device_id: 'local', device_name: 'Workstation', device_os: 'macOS' }) },
1617
}));
1718
const wslSupport = vi.hoisted(() => ({ supported: true }));
18-
vi.mock('@/features/ssh-remote/sshApi', () => ({ sshApi: { listWslDistributions: async () => ({ supported: wslSupport.supported, distributions: [] }) } }));
19-
const { pickDirectory, sourceOptions, optionsBySource } = vi.hoisted(() => ({ pickDirectory: vi.fn(), sourceOptions: [] as WorkspaceSourceOption[], optionsBySource: {} as Record<string, WorkspaceSourceOption[]> }));
19+
vi.mock('@/features/ssh-remote/sshApi', () => ({ sshApi: { deleteConnection: vi.fn(), listWslDistributions: async () => ({ supported: wslSupport.supported, distributions: [] }) } }));
20+
const { pickDirectory, sourceOptions, optionsBySource, refreshOptions } = vi.hoisted(() => ({ pickDirectory: vi.fn(), sourceOptions: [] as WorkspaceSourceOption[], optionsBySource: {} as Record<string, WorkspaceSourceOption[]>, refreshOptions: vi.fn() }));
2021
vi.mock('@/features/ssh-remote/useWorkspaceSourceOptions', () => ({
21-
useWorkspaceSourceOptions: (source: string) => ({ options: optionsBySource[source] || [], loading: false, error: '', refresh: vi.fn() }),
22+
useWorkspaceSourceOptions: (source: string) => ({ options: optionsBySource[source] || [], loading: false, error: '', refresh: () => refreshOptions(source) }),
2223
workspacePresetHost: (preset?: { kind: string; connection?: unknown }) => preset?.kind === 'saved' ? preset.connection : undefined,
2324
}));
2425
vi.mock('@/infrastructure/i18n', () => ({ useI18n: () => ({ t: (key: string, options?: { name?: string }) =>
@@ -61,11 +62,12 @@ describe('NewProjectDialog composition', () => {
6162
beforeEach(() => {
6263
vi.resetAllMocks();
6364
vi.spyOn(globalAPI, 'getRecentWorkspaces').mockResolvedValue([]);
65+
vi.spyOn(globalAPI, 'removeRecentWorkspace').mockResolvedValue(undefined);
6466
wslSupport.supported = true;
6567
sourceOptions.length = 0;
6668
for (const key of Object.keys(optionsBySource)) delete optionsBySource[key];
6769
for (const source of ['ssh', 'wsl', 'localDocker', 'remoteDocker']) {
68-
optionsBySource[source] = [{ id: `fixture-${source}`, label: source, preset: { kind: 'saved', connection: {
70+
optionsBySource[source] = [{ id: `fixture-${source}`, savedConnectionId: `fixture-${source}`, label: source, preset: { kind: 'saved', connection: {
6971
id: `fixture-${source}`, name: source, host: 'host.test', port: 22, username: 'dev', authType: { type: 'PrivateKey', keyPath: '/keys/dev' },
7072
} } }];
7173
}
@@ -219,12 +221,57 @@ describe('NewProjectDialog composition', () => {
219221
const pick = vi.fn();
220222
await render({ onPickRemoteFolder: pick, onSelectRemoteHost: selectHost });
221223
selectSource('ssh', false);
224+
expect(document.querySelector('button[aria-label="actions.delete · Build host"]')).toBeNull();
222225
await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="actions.edit · Build host"]')!.click());
223226
expect(selectHost).toHaveBeenCalledWith('ssh', { ...option.preset, edit: true });
224227
expect(document.querySelector('[data-workspace-choice="host"] button[aria-pressed]')?.getAttribute('aria-pressed')).toBe('false');
225228
expect(pick).not.toHaveBeenCalled();
226229
});
227230

231+
it('deletes a selected saved host without connecting and clears its project selection', async () => {
232+
let finish!: () => void;
233+
vi.mocked(sshApi.deleteConnection).mockReturnValue(new Promise(resolve => { finish = resolve; }));
234+
const selectHost = vi.fn();
235+
await render({ onPickRemoteFolder: vi.fn(), onSelectRemoteHost: selectHost });
236+
selectSource('ssh');
237+
enterName('Remote project');
238+
expect(button('newProject.create').disabled).toBe(false);
239+
const remove = document.querySelector<HTMLButtonElement>('button[aria-label="actions.delete · ssh"]')!;
240+
expect(remove.closest('button')?.parentElement?.closest('button')).toBeNull();
241+
await act(async () => remove.click());
242+
expect(sshApi.deleteConnection).toHaveBeenCalledExactlyOnceWith('fixture-ssh');
243+
expect(remove.disabled).toBe(true);
244+
expect(selectHost).not.toHaveBeenCalled();
245+
expect(refreshOptions).not.toHaveBeenCalled();
246+
await act(async () => finish());
247+
expect(refreshOptions).toHaveBeenCalledWith('ssh');
248+
expect(document.querySelector('[data-workspace-choice="fixture-ssh"] button[aria-pressed]')?.getAttribute('aria-pressed')).toBe('false');
249+
expect(button('newProject.create').disabled).toBe(true);
250+
});
251+
252+
it('retains the saved host and its selection when deletion fails', async () => {
253+
vi.mocked(sshApi.deleteConnection).mockRejectedValue(new Error('Host offline'));
254+
await render({ onPickRemoteFolder: vi.fn(), onSelectRemoteHost: vi.fn() });
255+
selectSource('ssh');
256+
await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="actions.delete · ssh"]')!.click());
257+
expect(document.querySelector('[role="alert"]')?.textContent).toContain('Host offline');
258+
expect(document.querySelector('[data-workspace-choice="fixture-ssh"] button[aria-pressed]')?.getAttribute('aria-pressed')).toBe('true');
259+
expect(refreshOptions).not.toHaveBeenCalled();
260+
});
261+
262+
it('ignores a completed deletion after switching device surfaces', async () => {
263+
let finish!: () => void;
264+
vi.mocked(sshApi.deleteConnection).mockReturnValue(new Promise(resolve => { finish = resolve; }));
265+
await render({ onPickRemoteFolder: vi.fn(), onSelectRemoteHost: vi.fn() });
266+
selectSource('ssh');
267+
await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="actions.delete · ssh"]')!.click());
268+
act(() => activateSurface(surfaceIdForDevice('peer')));
269+
await act(async () => finish());
270+
expect(refreshOptions).not.toHaveBeenCalled();
271+
expect(document.querySelector('[role="alert"]')).toBeNull();
272+
expect(sshApi.deleteConnection).toHaveBeenCalledTimes(1);
273+
});
274+
228275
const recentWorkspace = (id: string, extra: Partial<WorkspaceInfo> = {}): WorkspaceInfo => ({
229276
id, name: id, rootPath: `/work/${id}`, workspaceKind: 'normal', workspaceType: 'singleProject',
230277
languages: [], tags: [], openedAt: '2026-01-01', lastAccessed: '2026-01-01', ...extra,
@@ -260,6 +307,46 @@ describe('NewProjectDialog composition', () => {
260307
expect(document.querySelector('[data-workspace-choice="controller-private"]')).toBeNull();
261308
});
262309

310+
it('removes a recent workspace without selecting its folder or creating a project', async () => {
311+
vi.mocked(globalAPI.getRecentWorkspaces).mockResolvedValue([recentWorkspace('one'), recentWorkspace('two')]);
312+
let finish!: () => void;
313+
vi.mocked(globalAPI.removeRecentWorkspace).mockReturnValue(new Promise(resolve => { finish = resolve; }));
314+
await render({ onPickRemoteFolder: vi.fn() });
315+
const remove = document.querySelector<HTMLButtonElement>('button[aria-label="actions.delete · one"]')!;
316+
await act(async () => remove.click());
317+
expect(globalAPI.removeRecentWorkspace).toHaveBeenCalledExactlyOnceWith('one');
318+
expect(remove.disabled).toBe(true);
319+
expect(document.querySelector('[data-workspace-choice="one"]')).not.toBeNull();
320+
await act(async () => finish());
321+
expect(document.querySelector('[data-workspace-choice="one"]')).toBeNull();
322+
expect(document.querySelector('[data-workspace-choice="two"]')).not.toBeNull();
323+
expect(document.querySelectorAll('.new-project-dialog__folder li')).toHaveLength(0);
324+
expect(confirm).not.toHaveBeenCalled();
325+
expect(pickDirectory).not.toHaveBeenCalled();
326+
});
327+
328+
it('retains a recent workspace and reports a failed removal', async () => {
329+
vi.mocked(globalAPI.getRecentWorkspaces).mockResolvedValue([recentWorkspace('one')]);
330+
vi.mocked(globalAPI.removeRecentWorkspace).mockRejectedValue(new Error('Host offline'));
331+
await render({ onPickRemoteFolder: vi.fn() });
332+
await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="actions.delete · one"]')!.click());
333+
expect(document.querySelector('[data-workspace-choice="one"]')).not.toBeNull();
334+
expect(document.querySelector('[role="alert"]')?.textContent).toContain('Host offline');
335+
});
336+
337+
it('ignores a recent workspace removal response after switching devices', async () => {
338+
vi.mocked(globalAPI.getRecentWorkspaces).mockResolvedValue([recentWorkspace('one')]);
339+
let finish!: () => void;
340+
vi.mocked(globalAPI.removeRecentWorkspace).mockReturnValue(new Promise(resolve => { finish = resolve; }));
341+
await render({ onPickRemoteFolder: vi.fn() });
342+
await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="actions.delete · one"]')!.click());
343+
act(() => activateSurface(surfaceIdForDevice('peer')));
344+
await act(async () => finish());
345+
expect(globalAPI.removeRecentWorkspace).toHaveBeenCalledTimes(1);
346+
expect(document.querySelector('[data-workspace-choice="one"]')).not.toBeNull();
347+
expect(document.querySelector('[role="alert"]')).toBeNull();
348+
});
349+
263350
it('does not repeat the device name below the current-computer header', async () => {
264351
await render({ onPickRemoteFolder: vi.fn() });
265352
const row = document.querySelectorAll('[data-openbitfun-part="sourceField"]')[0];

‎src/web-ui/src/app/components/NewProjectDialog/NewProjectDialog.tsx‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { globalAPI, type WorkspaceInfo } from '@/infrastructure/api/service-api/
1111
import type { WorkspaceConnectionTarget } from '@/features/ssh-remote/types';
1212
import { WorkspaceSourceSelector } from '@/features/ssh-remote/WorkspaceSourceSelector';
1313
import { WorkspaceChoiceCapsules } from '@/features/ssh-remote/WorkspaceChoiceCapsules';
14+
import { sshApi } from '@/features/ssh-remote/sshApi';
1415
import { useWorkspaceSourceOptions, workspacePresetHost, type WorkspaceConnectionPreset, type WorkspaceSourceOption } from '@/features/ssh-remote/useWorkspaceSourceOptions';
1516
import { workspaceSourceCoordinates, type WorkspaceSource } from '@/features/ssh-remote/workspaceSource';
1617
import { AssistantProjectFolderError, DEFAULT_PROJECT_SUBDIRECTORY, ProjectDirectoryUnavailableError, projectFolderKey, projectFolderName, type ProjectDraft, type ProjectFolder } from '@/app/utils/projectDraft';
@@ -343,6 +344,43 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({
343344
} finally { setIsSelecting(false); }
344345
};
345346

347+
const handleDeleteHost = async (option: WorkspaceSourceOption) => {
348+
if (busy || hasFolders || !option.savedConnectionId) return;
349+
const scope = formSurface.current;
350+
setIsSelecting(true);
351+
setError('');
352+
try {
353+
scope.assertCurrent('delete project host');
354+
await sshApi.deleteConnection(option.savedConnectionId);
355+
scope.assertCurrent('accept deleted project host');
356+
if (selectedHostOption === option.id) {
357+
setSelectedHostOption(undefined);
358+
setSelectedOption(undefined);
359+
setConnectedRemote(undefined);
360+
}
361+
hostOptions.refresh();
362+
} catch (cause) {
363+
log.error('Failed to delete project host', cause);
364+
if (scope.isCurrent()) setError(cause instanceof Error ? cause.message : String(cause));
365+
} finally { setIsSelecting(false); }
366+
};
367+
368+
const handleRemoveRecentWorkspace = async (workspaceId: string) => {
369+
if (busy || hasFolders) return;
370+
const scope = formSurface.current;
371+
setIsSelecting(true);
372+
setRecentError('');
373+
try {
374+
scope.assertCurrent('remove recent project workspace');
375+
await globalAPI.removeRecentWorkspace(workspaceId);
376+
scope.assertCurrent('accept removed recent project workspace');
377+
setRecentWorkspaces(workspaces => workspaces.filter(workspace => workspace.id !== workspaceId));
378+
} catch (cause) {
379+
log.error('Failed to remove recent project workspace', cause);
380+
if (scope.isCurrent()) setRecentError(cause instanceof Error ? cause.message : String(cause));
381+
} finally { setIsSelecting(false); }
382+
};
383+
346384
const optionActions = (options: typeof sourceOptions, target: WorkspaceConnectionTarget) => <>
347385
{onSelectRemoteHost && <Tooltip content={t('ssh.remote.newConnection')}><IconButton variant="quiet" size="xs" disabled={busy || hasFolders || (target === 'remoteDocker' && !selectedHost)}
348386
icon={<Icon name="plus" size="xs" />} aria-label={t('ssh.remote.newConnection')}
@@ -359,7 +397,9 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({
359397
const option = options.options.find(item => item.id === id);
360398
if (option) void handleEditSource(option, target);
361399
} : undefined}
362-
choices={options.options} disabled={busy || hasFolders} onValueChange={value => {
400+
choices={options.options.map(option => ({ ...option,
401+
onDelete: target === 'ssh' && option.savedConnectionId ? () => void handleDeleteHost(option) : undefined,
402+
}))} disabled={busy || hasFolders} onValueChange={value => {
363403
onChange(value);
364404
if (value !== connectedRemote?.connectionId) setConnectedRemote(undefined);
365405
}} />}
@@ -486,7 +526,9 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({
486526
setSelectedHostOption(value); setSelectedOption(undefined);
487527
}) : source === 'host' ? <>
488528
{recentWorkspaces.length > 0 && <WorkspaceChoiceCapsules label={t('workspaceSource.availableOptions')}
489-
choices={recentWorkspaces.map(workspace => ({ id: workspace.id, label: workspace.name || projectFolderName(workspace.rootPath), description: workspace.rootPath }))}
529+
choices={recentWorkspaces.map(workspace => ({ id: workspace.id, label: workspace.name || projectFolderName(workspace.rootPath), description: workspace.rootPath,
530+
onDelete: () => void handleRemoveRecentWorkspace(workspace.id),
531+
}))}
490532
value={recentWorkspaces.find(workspace => folders.some(folder => projectFolderKey(folder) === projectFolderKey({ path: workspace.rootPath })))?.id}
491533
disabled={busy || hasFolders} onValueChange={id => {
492534
if (busy || hasFolders) return;

0 commit comments

Comments
 (0)