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
11 changes: 6 additions & 5 deletions design-system/packages/ui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ backing or fading parent cannot prevent it from sampling the content behind it.
### Capsule actions

Wrap a pill-shaped `Button`, inline `Input`, or tag label in `Capsule`, matching
its `size` to the child. Pass one `IconButton` (optionally inside `Tooltip`) to
its `size` to the child. Pass an `IconButton` or an array of keyed `IconButton`s (optionally inside `Tooltip`) to
`action`. The slot selects circular glass presentation and compact geometry;
the consumer keeps the action's accessible label, tone, disabled/loading state,
and callbacks. The action is a sibling of the primary control, never a nested
Expand All @@ -609,13 +609,14 @@ available. Its right inset equals the top and bottom clearance at every density.
The default `actionPlacement="overlay"` floats over the intact label: do not clip,
mask, hide, resize, or add action padding to its text when revealing the icon.
Use `actionPlacement="reserved"` with a `Button` child for short selectable labels.
The Button always reserves trailing padding for the action inside its pill surface,
keeping the gaps between capsules compact. Its content is centered at rest, then
The Button always reserves trailing padding for one action inside its pill surface,
keeping the gaps between capsules compact. Additional actions overlay the content
without adding padding. Its content is centered at rest, then
shifts toward the leading edge as the icon fades in on pointer hover. Only the
content transform and icon opacity change: hovering a row-end capsule cannot
change its width or trigger wrapping. Keyboard focus reveals the action and moves
the content immediately; touch keeps the action visible and the content clear of
it. Reduced motion disables both transitions. Capsules without an action do not
the content immediately; touch keeps the actions visible.
Reduced motion disables both transitions. Capsules without an action do not
reserve empty space.
Normal constrained-width `OverflowText` behavior remains available.
`TabGroupItem.endAction` uses a reserved slot as described above; removable
Expand Down
11 changes: 6 additions & 5 deletions design-system/packages/ui/src/components/Capsule/Capsule.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { forwardRef, type HTMLAttributes, type ReactNode } from "react";
import { Children, forwardRef, type HTMLAttributes, type ReactNode } from "react";
import { classNames } from "../../internal/classNames";
import { FloatingAction } from "../../internal/FloatingAction";
import actionStyles from "../../internal/FloatingAction.module.css";
Expand All @@ -9,9 +9,9 @@ export interface CapsuleProps extends HTMLAttributes<HTMLSpanElement> {
layout?: "inline" | "split";
/** Fit both split controls and the capsule to their content, or use equal halves. */
splitSizing?: "equal" | "content";
/** One IconButton (optionally wrapped in Tooltip), rendered beside the content. */
/** An IconButton or array of IconButtons (optionally wrapped in Tooltip). */
action?: ReactNode;
/** Reserve a fixed action slot inside a Button child's trailing padding. */
/** Reserve one fixed action slot; additional actions overlay the content. */
actionPlacement?: "overlay" | "reserved";
/** Match the size of the child Button, Input, or label surface. */
size?: "xs" | "sm" | "md" | "lg";
Expand All @@ -28,12 +28,13 @@ export const Capsule = forwardRef<HTMLSpanElement, CapsuleProps>(function Capsul
splitSizing = "equal",
...props
}, ref) {
const actionCount = Children.toArray(action).length;
return (
<span {...props} className={classNames(actionStyles.host, styles.root, className)}
data-openbitfun-component="capsule" data-layout={layout} data-size={size} data-split-sizing={layout === "split" ? splitSizing : undefined}
data-action-placement={action != null ? actionPlacement : undefined} data-overflow-trigger ref={ref}>
data-action-placement={actionCount > 0 ? actionPlacement : undefined} data-overflow-trigger ref={ref}>
{children}
{action != null && <FloatingAction data-openbitfun-part="action"
{actionCount > 0 && <FloatingAction data-openbitfun-part="action" group={actionCount > 1}
className={actionPlacement === "reserved" ? styles.reservedAction : undefined}>{action}</FloatingAction>}
</span>
);
Expand Down
13 changes: 13 additions & 0 deletions design-system/packages/ui/tests/capsule.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,19 @@ test("capsules without actions preserve ordinary content and do not add a focus
assert.doesNotMatch(markup, /tabindex|role=|data-openbitfun-part="action"|data-action-placement/);
});

test("reserved capsules group multiple independent actions in a single reserved slot", () => {
const markup = renderToStaticMarkup(h(Capsule, {
size: "xs", actionPlacement: "reserved",
action: [h(Tooltip, { key: "edit", content: "Edit host" }, action({ "aria-label": "Edit host" })),
false, action({ key: "delete", "aria-label": "Delete host" })],
}, h(Button, { size: "xs" }, "Build host")));
assert.match(markup, /data-action-placement="reserved"/);
assert.match(markup, /data-floating-action-group="true"/);
assert.equal((markup.match(/<button\b/g) ?? []).length, 3);
assert.match(markup, /aria-label="Edit host"/);
assert.match(markup, /aria-label="Delete host"/);
});

test("split capsules align filled edges with equal or compact content-sized widths", async () => {
const markup = renderToStaticMarkup(h(Capsule, { layout: "split", splitSizing: "content", size: "sm", role: "group", "aria-label": "Provider" },
h(Select, { size: "sm", variant: "pill", width: "content", "aria-label": "Region", options: [{ value: "international", label: "International" }] }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { activateSurface, resetDeviceSurfaceForTest, surfaceIdForDevice } from '
import { AssistantProjectFolderError, ProjectDirectoryUnavailableError } from '@/app/utils/projectDraft';
import { globalAPI, type WorkspaceInfo } from '@/infrastructure/api/service-api/GlobalAPI';
import type { WorkspaceSourceOption } from '@/features/ssh-remote/useWorkspaceSourceOptions';
import { sshApi } from '@/features/ssh-remote/sshApi';
import { PeerDeviceContext, type PeerDeviceContextValue } from '@/infrastructure/peer-device/peerDeviceContextState';

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

it('deletes a selected saved host without connecting and clears its project selection', async () => {
let finish!: () => void;
vi.mocked(sshApi.deleteConnection).mockReturnValue(new Promise(resolve => { finish = resolve; }));
const selectHost = vi.fn();
await render({ onPickRemoteFolder: vi.fn(), onSelectRemoteHost: selectHost });
selectSource('ssh');
enterName('Remote project');
expect(button('newProject.create').disabled).toBe(false);
const remove = document.querySelector<HTMLButtonElement>('button[aria-label="actions.delete · ssh"]')!;
expect(remove.closest('button')?.parentElement?.closest('button')).toBeNull();
await act(async () => remove.click());
expect(sshApi.deleteConnection).toHaveBeenCalledExactlyOnceWith('fixture-ssh');
expect(remove.disabled).toBe(true);
expect(selectHost).not.toHaveBeenCalled();
expect(refreshOptions).not.toHaveBeenCalled();
await act(async () => finish());
expect(refreshOptions).toHaveBeenCalledWith('ssh');
expect(document.querySelector('[data-workspace-choice="fixture-ssh"] button[aria-pressed]')?.getAttribute('aria-pressed')).toBe('false');
expect(button('newProject.create').disabled).toBe(true);
});

it('retains the saved host and its selection when deletion fails', async () => {
vi.mocked(sshApi.deleteConnection).mockRejectedValue(new Error('Host offline'));
await render({ onPickRemoteFolder: vi.fn(), onSelectRemoteHost: vi.fn() });
selectSource('ssh');
await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="actions.delete · ssh"]')!.click());
expect(document.querySelector('[role="alert"]')?.textContent).toContain('Host offline');
expect(document.querySelector('[data-workspace-choice="fixture-ssh"] button[aria-pressed]')?.getAttribute('aria-pressed')).toBe('true');
expect(refreshOptions).not.toHaveBeenCalled();
});

it('ignores a completed deletion after switching device surfaces', async () => {
let finish!: () => void;
vi.mocked(sshApi.deleteConnection).mockReturnValue(new Promise(resolve => { finish = resolve; }));
await render({ onPickRemoteFolder: vi.fn(), onSelectRemoteHost: vi.fn() });
selectSource('ssh');
await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="actions.delete · ssh"]')!.click());
act(() => activateSurface(surfaceIdForDevice('peer')));
await act(async () => finish());
expect(refreshOptions).not.toHaveBeenCalled();
expect(document.querySelector('[role="alert"]')).toBeNull();
expect(sshApi.deleteConnection).toHaveBeenCalledTimes(1);
});

const recentWorkspace = (id: string, extra: Partial<WorkspaceInfo> = {}): WorkspaceInfo => ({
id, name: id, rootPath: `/work/${id}`, workspaceKind: 'normal', workspaceType: 'singleProject',
languages: [], tags: [], openedAt: '2026-01-01', lastAccessed: '2026-01-01', ...extra,
Expand Down Expand Up @@ -260,6 +307,46 @@ describe('NewProjectDialog composition', () => {
expect(document.querySelector('[data-workspace-choice="controller-private"]')).toBeNull();
});

it('removes a recent workspace without selecting its folder or creating a project', async () => {
vi.mocked(globalAPI.getRecentWorkspaces).mockResolvedValue([recentWorkspace('one'), recentWorkspace('two')]);
let finish!: () => void;
vi.mocked(globalAPI.removeRecentWorkspace).mockReturnValue(new Promise(resolve => { finish = resolve; }));
await render({ onPickRemoteFolder: vi.fn() });
const remove = document.querySelector<HTMLButtonElement>('button[aria-label="actions.delete · one"]')!;
await act(async () => remove.click());
expect(globalAPI.removeRecentWorkspace).toHaveBeenCalledExactlyOnceWith('one');
expect(remove.disabled).toBe(true);
expect(document.querySelector('[data-workspace-choice="one"]')).not.toBeNull();
await act(async () => finish());
expect(document.querySelector('[data-workspace-choice="one"]')).toBeNull();
expect(document.querySelector('[data-workspace-choice="two"]')).not.toBeNull();
expect(document.querySelectorAll('.new-project-dialog__folder li')).toHaveLength(0);
expect(confirm).not.toHaveBeenCalled();
expect(pickDirectory).not.toHaveBeenCalled();
});

it('retains a recent workspace and reports a failed removal', async () => {
vi.mocked(globalAPI.getRecentWorkspaces).mockResolvedValue([recentWorkspace('one')]);
vi.mocked(globalAPI.removeRecentWorkspace).mockRejectedValue(new Error('Host offline'));
await render({ onPickRemoteFolder: vi.fn() });
await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="actions.delete · one"]')!.click());
expect(document.querySelector('[data-workspace-choice="one"]')).not.toBeNull();
expect(document.querySelector('[role="alert"]')?.textContent).toContain('Host offline');
});

it('ignores a recent workspace removal response after switching devices', async () => {
vi.mocked(globalAPI.getRecentWorkspaces).mockResolvedValue([recentWorkspace('one')]);
let finish!: () => void;
vi.mocked(globalAPI.removeRecentWorkspace).mockReturnValue(new Promise(resolve => { finish = resolve; }));
await render({ onPickRemoteFolder: vi.fn() });
await act(async () => document.querySelector<HTMLButtonElement>('button[aria-label="actions.delete · one"]')!.click());
act(() => activateSurface(surfaceIdForDevice('peer')));
await act(async () => finish());
expect(globalAPI.removeRecentWorkspace).toHaveBeenCalledTimes(1);
expect(document.querySelector('[data-workspace-choice="one"]')).not.toBeNull();
expect(document.querySelector('[role="alert"]')).toBeNull();
});

it('does not repeat the device name below the current-computer header', async () => {
await render({ onPickRemoteFolder: vi.fn() });
const row = document.querySelectorAll('[data-openbitfun-part="sourceField"]')[0];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { globalAPI, type WorkspaceInfo } from '@/infrastructure/api/service-api/
import type { WorkspaceConnectionTarget } from '@/features/ssh-remote/types';
import { WorkspaceSourceSelector } from '@/features/ssh-remote/WorkspaceSourceSelector';
import { WorkspaceChoiceCapsules } from '@/features/ssh-remote/WorkspaceChoiceCapsules';
import { sshApi } from '@/features/ssh-remote/sshApi';
import { useWorkspaceSourceOptions, workspacePresetHost, type WorkspaceConnectionPreset, type WorkspaceSourceOption } from '@/features/ssh-remote/useWorkspaceSourceOptions';
import { workspaceSourceCoordinates, type WorkspaceSource } from '@/features/ssh-remote/workspaceSource';
import { AssistantProjectFolderError, DEFAULT_PROJECT_SUBDIRECTORY, ProjectDirectoryUnavailableError, projectFolderKey, projectFolderName, type ProjectDraft, type ProjectFolder } from '@/app/utils/projectDraft';
Expand Down Expand Up @@ -343,6 +344,43 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({
} finally { setIsSelecting(false); }
};

const handleDeleteHost = async (option: WorkspaceSourceOption) => {
if (busy || hasFolders || !option.savedConnectionId) return;
const scope = formSurface.current;
setIsSelecting(true);
setError('');
try {
scope.assertCurrent('delete project host');
await sshApi.deleteConnection(option.savedConnectionId);
scope.assertCurrent('accept deleted project host');
if (selectedHostOption === option.id) {
setSelectedHostOption(undefined);
setSelectedOption(undefined);
setConnectedRemote(undefined);
}
hostOptions.refresh();
} catch (cause) {
log.error('Failed to delete project host', cause);
if (scope.isCurrent()) setError(cause instanceof Error ? cause.message : String(cause));
} finally { setIsSelecting(false); }
};

const handleRemoveRecentWorkspace = async (workspaceId: string) => {
if (busy || hasFolders) return;
const scope = formSurface.current;
setIsSelecting(true);
setRecentError('');
try {
scope.assertCurrent('remove recent project workspace');
await globalAPI.removeRecentWorkspace(workspaceId);
scope.assertCurrent('accept removed recent project workspace');
setRecentWorkspaces(workspaces => workspaces.filter(workspace => workspace.id !== workspaceId));
} catch (cause) {
log.error('Failed to remove recent project workspace', cause);
if (scope.isCurrent()) setRecentError(cause instanceof Error ? cause.message : String(cause));
} finally { setIsSelecting(false); }
};

const optionActions = (options: typeof sourceOptions, target: WorkspaceConnectionTarget) => <>
{onSelectRemoteHost && <Tooltip content={t('ssh.remote.newConnection')}><IconButton variant="quiet" size="xs" disabled={busy || hasFolders || (target === 'remoteDocker' && !selectedHost)}
icon={<Icon name="plus" size="xs" />} aria-label={t('ssh.remote.newConnection')}
Expand All @@ -359,7 +397,9 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({
const option = options.options.find(item => item.id === id);
if (option) void handleEditSource(option, target);
} : undefined}
choices={options.options} disabled={busy || hasFolders} onValueChange={value => {
choices={options.options.map(option => ({ ...option,
onDelete: target === 'ssh' && option.savedConnectionId ? () => void handleDeleteHost(option) : undefined,
}))} disabled={busy || hasFolders} onValueChange={value => {
onChange(value);
if (value !== connectedRemote?.connectionId) setConnectedRemote(undefined);
}} />}
Expand Down Expand Up @@ -486,7 +526,9 @@ export const NewProjectDialog: React.FC<NewProjectDialogProps> = ({
setSelectedHostOption(value); setSelectedOption(undefined);
}) : source === 'host' ? <>
{recentWorkspaces.length > 0 && <WorkspaceChoiceCapsules label={t('workspaceSource.availableOptions')}
choices={recentWorkspaces.map(workspace => ({ id: workspace.id, label: workspace.name || projectFolderName(workspace.rootPath), description: workspace.rootPath }))}
choices={recentWorkspaces.map(workspace => ({ id: workspace.id, label: workspace.name || projectFolderName(workspace.rootPath), description: workspace.rootPath,
onDelete: () => void handleRemoveRecentWorkspace(workspace.id),
}))}
value={recentWorkspaces.find(workspace => folders.some(folder => projectFolderKey(folder) === projectFolderKey({ path: workspace.rootPath })))?.id}
disabled={busy || hasFolders} onValueChange={id => {
if (busy || hasFolders) return;
Expand Down
Loading
Loading