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
22 changes: 22 additions & 0 deletions src/web-ui/src/features/dispatch/DispatchTargetPicker.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ vi.mock('@/infrastructure/i18n', () => ({
const pickerState = vi.hoisted(() => ({
loggedIn: false,
targets: [] as Array<Record<string, unknown>>,
executionDevice: null as string | null,
}));

vi.mock('@/infrastructure/peer-device/useExecutionDeviceName', () => ({
useExecutionDeviceName: () => pickerState.executionDevice,
}));

vi.mock('@/infrastructure/account/useAccountLoginState', () => ({
Expand Down Expand Up @@ -68,6 +73,7 @@ describe('DispatchTargetPicker overlay', () => {
beforeEach(() => {
pickerState.loggedIn = false;
pickerState.targets = [];
pickerState.executionDevice = null;
Object.defineProperty(window, 'innerWidth', { configurable: true, value: 800 });
Object.defineProperty(window, 'innerHeight', { configurable: true, value: 800 });
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function () {
Expand Down Expand Up @@ -115,6 +121,22 @@ describe('DispatchTargetPicker overlay', () => {
expect(menu?.style.top).toBe('293px');
});

it('names the device that runs a local-target task instead of "this computer"', async () => {
pickerState.executionDevice = 'Ubuntu';
await act(async () => {
root.render(
<DispatchTargetPicker target={{ kind: 'local' }} locked={false} onSelectTarget={vi.fn()} />,
);
});
const trigger = container.querySelector<HTMLButtonElement>(
'[data-testid="chat-input-dispatch-trigger"]',
);
expect(trigger?.textContent).toBe('Ubuntu');
await act(async () => trigger?.click());
expect(document.querySelector('[data-testid="dispatch-target-local-option"]')?.textContent)
.toContain('Ubuntu');
});

it('offers New Worktree inside the local target and reflects the selected local mode', async () => {
const onSelectLocal = vi.fn();
const onWorktreeChange = vi.fn();
Expand Down
8 changes: 6 additions & 2 deletions src/web-ui/src/features/dispatch/DispatchTargetPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { subscribeOverlayInteraction, createOverlayPortal, OverflowText, Icon, M
import { SSHConnectionDialog } from '@/features/ssh-remote/SSHConnectionDialog';
import { getAppearanceOverlayHost } from '@/infrastructure/appearance/runtime/AppearanceOverlayHost';
import { useI18n } from '@/infrastructure/i18n';
import { useExecutionDeviceName } from '@/infrastructure/peer-device/useExecutionDeviceName';
import { useAnchoredPopoverPosition } from '@/shared/utils/useAnchoredPopoverPosition';
import { DispatchTargetDialog } from './DispatchTargetDialog';
import { DispatchTransportStatus } from './DispatchTransportStatus';
Expand Down Expand Up @@ -77,9 +78,12 @@ export const DispatchTargetPicker: React.FC<DispatchTargetPickerProps> = ({
layoutRevision: `${targets.length}:${loading}:${error ?? ''}`,
});

// Name the device that actually runs the task: this machine locally, the
// controlled device on a peer surface. "This computer" would be misleading.
const localDeviceLabel = useExecutionDeviceName() ?? t('chatInput.dispatch.local');
const localDisplayLabel = localWorktreeControl?.enabled
? localWorktreeControl.label
: t('chatInput.dispatch.local');
: localDeviceLabel;
const displayLabel = target.kind === 'local'
? localDisplayLabel
: target.kind === 'device' ? resolveDeviceName(target.deviceId, target.displayName) : target.displayName;
Expand Down Expand Up @@ -167,7 +171,7 @@ export const DispatchTargetPicker: React.FC<DispatchTargetPickerProps> = ({
onClick={() => selectLocalMode(false)}
>
<span className="dispatch-target-picker__option-copy">
<strong><OverflowText>{t('chatInput.dispatch.local')}</OverflowText></strong>
<strong><OverflowText>{localDeviceLabel}</OverflowText></strong>
</span>
</MenuItem>
</Tooltip>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// @vitest-environment jsdom

import React, { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

globalThis.IS_REACT_ACT_ENVIRONMENT = true;

const state = vi.hoisted(() => ({
peerMode: { active: false } as { active: boolean; deviceId?: string; deviceName?: string },
getDeviceInfo: vi.fn(),
}));

vi.mock('@/infrastructure/api/service-api/RemoteConnectAPI', () => ({
remoteConnectAPI: { getDeviceInfo: state.getDeviceInfo },
deviceDisplayName: (device: { device_id: string; device_name?: string; device_alias?: string }) =>
device.device_alias ?? device.device_name ?? device.device_id,
}));
vi.mock('@/infrastructure/api/service-api/ApiClient', () => ({ api: { listen: vi.fn() } }));
vi.mock('./peerDeviceContextState', () => ({
usePeerDeviceModeOptional: () => ({ peerMode: state.peerMode }),
}));

import { useDeviceDirectory } from '@/infrastructure/account/deviceDirectory';
import { activateSurface } from './deviceSurface';
import { resetExecutionDeviceNameForTest, useExecutionDeviceName } from './useExecutionDeviceName';

function Probe() {
return <span data-testid="name">{useExecutionDeviceName() ?? 'none'}</span>;
}

describe('useExecutionDeviceName', () => {
let container: HTMLDivElement;
let root: Root;
const rendered = () => container.querySelector('[data-testid="name"]')?.textContent;

beforeEach(() => {
resetExecutionDeviceNameForTest();
state.peerMode = { active: false };
state.getDeviceInfo.mockReset();
state.getDeviceInfo.mockResolvedValue({ device_id: 'mac-1', device_name: 'MacBook', mac_address: '' });
useDeviceDirectory.setState({ devices: [], localId: null, status: 'idle' });
activateSurface('local');
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
});

afterEach(() => {
act(() => root.unmount());
container.remove();
activateSurface('local');
});

it('names this machine on the local surface, signed out included', async () => {
await act(async () => root.render(<Probe />));
expect(rendered()).toBe('MacBook');
expect(state.getDeviceInfo).toHaveBeenCalledOnce();
});

it('prefers the account alias for this machine', async () => {
useDeviceDirectory.setState({
devices: [{ device_id: 'mac-1', device_name: 'MacBook', device_alias: 'Work Mac', online: true, last_seen_at: null }],
localId: 'mac-1',
status: 'ready',
});
await act(async () => root.render(<Probe />));
expect(rendered()).toBe('Work Mac');
});

it('names the controlled device on a peer surface', async () => {
state.peerMode = { active: true, deviceId: 'ubuntu-1', deviceName: 'Ubuntu' };
activateSurface('ubuntu-1');
await act(async () => root.render(<Probe />));
expect(rendered()).toBe('Ubuntu');
expect(state.getDeviceInfo).not.toHaveBeenCalled();
});

it('keeps the generic label until a name is known', async () => {
state.getDeviceInfo.mockRejectedValueOnce(new Error('unavailable'));
await act(async () => root.render(<Probe />));
expect(rendered()).toBe('none');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { useEffect, useState, useSyncExternalStore } from 'react';
import { resolveDeviceNameFrom, useDeviceDirectory } from '@/infrastructure/account/deviceDirectory';
import { remoteConnectAPI } from '@/infrastructure/api/service-api/RemoteConnectAPI';
import { getActiveSurfaceScope, isLocalSurface, onSurfaceActivated } from './deviceSurface';
import { usePeerDeviceModeOptional } from './peerDeviceContextState';

/**
* This machine's own name. `remote_connect_get_device_info` stays on the
* controller, works signed out, and does not change while the app runs, so
* one read is shared. A failed read is retried by the next consumer.
*/
let localDeviceName: Promise<string | null> | null = null;

function loadLocalDeviceName(): Promise<string | null> {
localDeviceName ??= remoteConnectAPI.getDeviceInfo()
.then(info => info.device_name?.trim() || null)
.catch(() => {
localDeviceName = null;
return null;
});
return localDeviceName;
}

/**
* Name of the device that runs the rendered surface's sessions: this machine
* on the local surface, the controlled device on a peer surface. Account
* aliases win over host names. `null` until a name is known, so callers keep
* a generic label instead of showing an id.
*/
export function useExecutionDeviceName(): string | null {
const scope = useSyncExternalStore(onSurfaceActivated, getActiveSurfaceScope, getActiveSurfaceScope);
const directory = useDeviceDirectory();
const peerMode = usePeerDeviceModeOptional()?.peerMode;
const [hostName, setHostName] = useState<string | null>(null);
const local = isLocalSurface(scope.surfaceId);

useEffect(() => {
if (!local) return;
let cancelled = false;
void loadLocalDeviceName().then(name => { if (!cancelled) setHostName(name); });
return () => { cancelled = true; };
}, [local]);

if (local) {
return directory.localId
? resolveDeviceNameFrom(directory.devices, directory.localId, hostName ?? '') || hostName
: hostName;
}
const announced = peerMode?.active && peerMode.deviceId === scope.surfaceId ? peerMode.deviceName : '';
return resolveDeviceNameFrom(directory.devices, scope.surfaceId, announced) || null;
}

export function resetExecutionDeviceNameForTest(): void {
localDeviceName = null;
}
4 changes: 2 additions & 2 deletions src/web-ui/src/locales/en-US/flow-chat.json
Original file line number Diff line number Diff line change
Expand Up @@ -924,8 +924,8 @@
"current": "Run this task on {{target}}",
"menuLabel": "Where this task runs",
"sessionScope": "This task only",
"localSection": "Local",
"localDescription": "Run in this OpenBitFun app",
"localSection": "Current device",
"localDescription": "Run in OpenBitFun on the current device",
"sshSection": "SSH",
"loading": "Loading targets…",
"noSshTargets": "No saved SSH targets",
Expand Down
4 changes: 2 additions & 2 deletions src/web-ui/src/locales/zh-CN/flow-chat.json
Original file line number Diff line number Diff line change
Expand Up @@ -924,8 +924,8 @@
"current": "将此任务运行在 {{target}}",
"menuLabel": "这个任务在哪运行",
"sessionScope": "仅当前任务",
"localSection": "本机",
"localDescription": "在当前 OpenBitFun 应用中运行",
"localSection": "当前设备",
"localDescription": "在当前设备的 OpenBitFun 中运行",
"sshSection": "SSH",
"loading": "正在加载目标…",
"noSshTargets": "没有已保存的 SSH 目标",
Expand Down
4 changes: 2 additions & 2 deletions src/web-ui/src/locales/zh-TW/flow-chat.json
Original file line number Diff line number Diff line change
Expand Up @@ -924,8 +924,8 @@
"current": "將此任務執行於 {{target}}",
"menuLabel": "這個任務在哪裡執行",
"sessionScope": "僅目前任務",
"localSection": "本機",
"localDescription": "在目前 OpenBitFun 應用程式中執行",
"localSection": "目前裝置",
"localDescription": "在目前裝置的 OpenBitFun 中執行",
"sshSection": "SSH",
"loading": "正在載入目標…",
"noSshTargets": "沒有已儲存的 SSH 目標",
Expand Down