diff --git a/src/web-ui/AGENTS-CN.md b/src/web-ui/AGENTS-CN.md index 5e8d84b893..efcd20064a 100644 --- a/src/web-ui/AGENTS-CN.md +++ b/src/web-ui/AGENTS-CN.md @@ -25,7 +25,9 @@ Peer Device Mode(同账号远程完整客户端)的边界见 `docs/architecture/peer-device-mode.md`。 前端不变量见 `src/infrastructure/peer-device/README.md`。不要重新引入内嵌会话/聊天壳; -应从设备列表(Remote Connect 的「我的 OpenBitFun」组)进入 peer mode。 +从侧边栏对应设备的分区打开工作区或会话。Remote Connect 的账号设备列表只管理 +显示状态、别名和移除设备,点击设备行不切换当前设备。拖动顺序只保存在控制端本机, +由账号列表、侧边栏分区和设备预览轮播共用;重命名、在线状态变化和远控切换不改变设备 ID。 Remote Connect 使用共享 OpenBitFun 账号(GitHub 或邮箱验证码登录)和官方版本化 Relay。账户控件复用 account-identity 服务,不再提供独立 Relay 账户、自定义服务器或自建部署入口。SSH 与 Docker 远程工作区 diff --git a/src/web-ui/AGENTS.md b/src/web-ui/AGENTS.md index 652091f242..7e85877ab3 100644 --- a/src/web-ui/AGENTS.md +++ b/src/web-ui/AGENTS.md @@ -26,8 +26,11 @@ Most changes start in: Peer Device Mode (same-account remote full client) is documented in `docs/architecture/peer-device-mode.md`. Frontend invariants: `src/infrastructure/peer-device/README.md`. Do not reintroduce nested -sessions/chat shells; enter peer mode from the device list (Remote Connect → -My OpenBitFun) instead. +sessions/chat shells; open a device’s workspace or session from its sidebar section. +Remote Connect’s account device list manages visibility, aliases, and removal; +its rows do not switch the rendered device. Device order is a controller-local +preference shared by this list, sidebar sections, and the device preview carousel; +keep device IDs stable through renames, presence changes, and Peer switches. Remote Connect uses the shared OpenBitFun account (GitHub or email-code sign-in) and the official versioned Relay. @@ -412,17 +415,27 @@ pnpm --dir src/web-ui run test:run src/app/components/panels/content-canvas/edit These local DOM/store fixtures do not establish native rendering or live remote behavior. -For device preview motion, linked sidebar visibility controls, and controller-owned theme selection: +For device preview motion, linked sidebar visibility and ordering, and controller-owned theme selection: ```bash -pnpm --dir src/web-ui run test:run src/app/components/NavPanel/components/DeviceStatusControl.test.tsx src/app/components/NavPanel/sections/devices/DeviceWorkspaceSections.test.tsx src/app/components/RemoteConnectDialog/AccountPanel.test.tsx src/app/navigation/deviceVisibilityPreferences.test.ts src/infrastructure/appearance/runtime/AppearanceService.test.ts +pnpm --dir src/web-ui run test:run src/app/components/NavPanel/components/DeviceStatusControl.test.tsx src/app/components/NavPanel/sections/devices/DeviceWorkspaceSections.test.tsx src/app/components/RemoteConnectDialog/AccountPanel.test.tsx src/app/navigation/deviceVisibilityPreferences.test.ts src/app/navigation/deviceOrderPreferences.test.ts src/app/components/NavPanel/sections/devices/useSidebarDevices.test.tsx src/infrastructure/appearance/runtime/AppearanceService.test.ts ``` These DOM/store and transport fixtures cover interrupted motion, reduced motion, -legacy preference loading, visibility across device activation, and local theme +legacy preference loading, drag ordering, visibility across device activation, and local theme reads/writes during simulated Peer switches. They do not establish native WebView frame rate or live SSH, Remote Control, Peer Device or Detached Dispatch behavior. +For cross-device session prewarm, native event routing and subscription handover: + +```bash +pnpm --dir src/web-ui run test:run src/flow_chat/services/RelaySessionHistory.test.ts src/flow_chat/services/RelaySessionHistory.routing.test.ts src/infrastructure/api/service-api/RemoteConnectAPI.test.ts src/infrastructure/api/adapters/tauri-adapter.test.ts src/infrastructure/peer-device/deviceSurfaceRouting.test.ts +``` + +These fixtures route tagged native events before and after a simulated Peer +activation, including same-ID sessions on other devices and cached replay. +They do not establish live Relay reconnect or remote-host performance. + For workspace icon editing, host capability gates, persistence requests and device-switch fences: ```bash diff --git a/src/web-ui/src/app/components/NavPanel/components/DeviceStatusControl.test.tsx b/src/web-ui/src/app/components/NavPanel/components/DeviceStatusControl.test.tsx index 7f5ccf71df..0c78f9ea79 100644 --- a/src/web-ui/src/app/components/NavPanel/components/DeviceStatusControl.test.tsx +++ b/src/web-ui/src/app/components/NavPanel/components/DeviceStatusControl.test.tsx @@ -10,6 +10,7 @@ import { } from '../deviceInterconnectionOverview'; import { getDeviceArtworkKind } from './deviceArtworkKind'; import DeviceStatusControl from './DeviceStatusControl'; +import { useDeviceOrderPreferences } from '@/app/navigation/deviceOrderPreferences'; import { useDeviceVisibilityPreferences } from '@/app/navigation/deviceVisibilityPreferences'; const state = vi.hoisted(() => ({ @@ -172,6 +173,7 @@ function installMotionPreference(initial = false) { } async function renderBrowseableDevices() { + useDeviceOrderPreferences.setState({ order: ['local', 'peer-1', 'peer-2', 'peer-3'] }); state.overview = overview({ peer: { deviceId: 'peer-1', deviceName: 'Current host' } }); state.identity = { status: 'signed-in', me: { user: { accountId: 'acct' } } }; state.getDeviceInfo.mockResolvedValue({ device_id: 'local', device_name: 'This computer' }); @@ -191,6 +193,7 @@ async function renderBrowseableDevices() { beforeEach(() => { vi.clearAllMocks(); useDeviceVisibilityPreferences.setState({ hidden: {} }); + useDeviceOrderPreferences.setState({ order: [] }); state.disconnectDevice.mockReset().mockResolvedValue(undefined); Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); state.identity = { status: 'signed-out', me: null }; @@ -397,6 +400,7 @@ describe('device status card', () => { }); it('opens on the current peer without sliding when the directory arrives, including after browsing and reopening', async () => { + useDeviceOrderPreferences.setState({ order: ['local', 'peer-1', 'peer-2'] }); state.overview = overview({ peer: { deviceId: 'peer-1', deviceName: 'Current host' } }); state.identity = { status: 'signed-in', me: { user: { accountId: 'acct' } } }; state.getDeviceInfo.mockResolvedValue({ device_id: 'local', device_name: 'This computer' }); @@ -985,3 +989,32 @@ describe('device status card', () => { expect(state.switchToDevice).not.toHaveBeenCalled(); }); }); + + +it('updates preview ordering immediately from the controller preference without switching the displayed host', async () => { + const { next } = await renderBrowseableDevices(); + expect(element('nav-device-status-name').textContent).toBe('Current host'); + act(() => useDeviceOrderPreferences.getState().move('peer-3', 'peer-1', 'after', ['local', 'peer-1', 'peer-2', 'peer-3'])); + expect(element('nav-device-status-name').textContent).toBe('Current host'); + await act(async () => next.click()); + expect(element('nav-device-status-name').textContent).toBe('Third host'); + expect(element('nav-device-status-pagination').textContent).toBe('3 / 4'); + expect(state.switchToDevice).not.toHaveBeenCalled(); + expect(state.switchToLocal).not.toHaveBeenCalled(); +}); + + +it('preserves a missing live peer in its saved position and removes it when the window leaves that peer', async () => { + useDeviceOrderPreferences.setState({ order: ['local', 'peer-1'] }); + state.overview = overview({ peer: { deviceId: 'peer-1', deviceName: 'Current host' } }); + state.identity = { status: 'signed-in', me: { user: { accountId: 'acct' } } }; + state.getDeviceInfo.mockResolvedValue({ device_id: 'local', device_name: 'This computer' }); + state.accountListDevices.mockResolvedValue([{ device_id: 'local', device_name: 'This computer', online: true }]); + await act(async () => { render(); }); + expect(element('nav-device-status-name').textContent).toBe('Current host'); + expect(element('nav-device-status-pagination').textContent).toBe('2 / 2'); + state.overview = overview(); + await act(async () => { render(); }); + expect(document.querySelector('[data-testid="nav-device-status-pagination"]')).toBeNull(); + expect(state.switchToDevice).not.toHaveBeenCalled(); +}); diff --git a/src/web-ui/src/app/components/NavPanel/components/DeviceStatusControl.tsx b/src/web-ui/src/app/components/NavPanel/components/DeviceStatusControl.tsx index 77c05caac6..0f8b5f4902 100644 --- a/src/web-ui/src/app/components/NavPanel/components/DeviceStatusControl.tsx +++ b/src/web-ui/src/app/components/NavPanel/components/DeviceStatusControl.tsx @@ -1,3 +1,4 @@ +import { applyDeviceOrder, sortAccountDevices, useDeviceOrderPreferences } from '@/app/navigation/deviceOrderPreferences'; import { useDeviceDirectory, resolveDeviceName, isDeviceControllable, deviceClientVersion, refreshDeviceDirectory } from '@/infrastructure/account/deviceDirectory'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { subscribeOverlayInteraction, createOverlayPortal, OverflowText, Button, Card, CardBody, CardHeader, Icon, IconButton, Input, ScrollArea, type IconSize } from '@openbitfun/ui'; @@ -103,6 +104,7 @@ const DeviceStatusControl: React.FC = ({ onManageDevices, }) => { useDeviceDirectory(); + const deviceOrder = useDeviceOrderPreferences(state => state.order); const { t, formatNumber } = useI18n('common'); const { warning, error: notifyError } = useNotification(); const peerContext = usePeerDeviceModeOptional(); @@ -148,11 +150,14 @@ const DeviceStatusControl: React.FC = ({ }, [accountId, open, warning]); const availableTargets = switchTargets?.accountId === accountId ? switchTargets : null; - const carouselDeviceIds = availableTargets?.devices.map(device => device.device_id) ?? []; - // Presence can lag behind a live control link; keep its disconnect entry reachable. - if (availableTargets && activePeerId && !carouselDeviceIds.includes(activePeerId)) { - carouselDeviceIds.unshift(activePeerId); - } + const carouselDeviceIds = useMemo(() => { + if (!availableTargets) return []; + const ids = sortAccountDevices(availableTargets.devices, availableTargets.localId, []).map(device => device.device_id); + // Presence can lag behind a live link. Retain that peer, in its saved + // position, only for as long as it remains the rendered device. + if (activePeerId && !ids.includes(activePeerId)) ids.unshift(activePeerId); + return applyDeviceOrder(ids, deviceOrder, id => id); + }, [availableTargets, activePeerId, deviceOrder]); const currentId = peerContext?.peerMode.active ? peerContext.peerMode.deviceId : availableTargets?.localId; const previewTarget = availableTargets?.devices.find(device => device.device_id === previewId); const platformHint = typeof navigator === 'undefined' diff --git a/src/web-ui/src/app/components/NavPanel/components/DeviceVisibilityButton.tsx b/src/web-ui/src/app/components/NavPanel/components/DeviceVisibilityButton.tsx index 1094947906..7e3d1f94c6 100644 --- a/src/web-ui/src/app/components/NavPanel/components/DeviceVisibilityButton.tsx +++ b/src/web-ui/src/app/components/NavPanel/components/DeviceVisibilityButton.tsx @@ -24,7 +24,6 @@ export function DeviceVisibilityButton({ surfaceId, name, compact = false, disab icon={} aria-label={label} aria-pressed={visible} - title={label} disabled={disabled} data-testid="device-sidebar-visibility" data-device-surface={surfaceId} diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/useSidebarDevices.test.tsx b/src/web-ui/src/app/components/NavPanel/sections/devices/useSidebarDevices.test.tsx new file mode 100644 index 0000000000..0645eae200 --- /dev/null +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/useSidebarDevices.test.tsx @@ -0,0 +1,43 @@ +// @vitest-environment jsdom +import React, { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { expect, it, vi } from 'vitest'; +import { useSidebarDevices } from './useSidebarDevices'; +import { useDeviceDirectory } from '@/infrastructure/account/deviceDirectory'; +import { useDeviceOrderPreferences } from '@/app/navigation/deviceOrderPreferences'; +import { activateSurface } from '@/infrastructure/peer-device/deviceSurface'; +import type { AccountDeviceInfo } from '@/infrastructure/api/service-api/RemoteConnectAPI'; + +vi.mock('@/infrastructure/api/service-api/ApiClient', () => ({ api: { listen: () => () => {} } })); +vi.mock('@/infrastructure/peer-device/peerDeviceContextState', () => ({ usePeerDeviceModeOptional: () => null })); + +it('uses saved device IDs for sidebar order across remote activation, offline recovery, and renames', () => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true; + useDeviceOrderPreferences.setState({ order: ['peer', 'local-id', 'offline'] }); + const devices = [ + { device_id: 'local-id', device_name: 'Local', online: true }, + { device_id: 'peer', device_name: 'Peer', online: true }, + { device_id: 'offline', device_name: 'Offline', online: false }, + ] as AccountDeviceInfo[]; + useDeviceDirectory.setState({ localId: 'local-id', devices, status: 'ready' }); + activateSurface('local'); + const host = document.createElement('div'); + const root = createRoot(host); + function Probe() { return <>{useSidebarDevices('This computer').map(slot => )}; } + const order = () => [...host.querySelectorAll('span')].map(node => node.dataset.id); + try { + act(() => root.render()); + expect(order()).toEqual(['peer', 'local-id']); + act(() => activateSurface('peer')); + expect(order()).toEqual(['peer', 'local-id']); + expect(host.querySelector('[data-rendered="true"]')?.getAttribute('data-id')).toBe('peer'); + act(() => useDeviceDirectory.setState({ devices: devices.map(device => ({ ...device, online: true, device_alias: 'Renamed' })) })); + expect(order()).toEqual(['peer', 'local-id', 'offline']); + act(() => useDeviceOrderPreferences.getState().move('offline', 'peer', 'before', ['peer', 'local-id', 'offline'])); + expect(order()).toEqual(['offline', 'peer', 'local-id']); + } finally { + act(() => root.unmount()); + activateSurface('local'); + useDeviceOrderPreferences.setState({ order: [] }); + } +}); diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/useSidebarDevices.ts b/src/web-ui/src/app/components/NavPanel/sections/devices/useSidebarDevices.ts index 83d2b863a1..7240a1f40b 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/useSidebarDevices.ts +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/useSidebarDevices.ts @@ -1,5 +1,6 @@ import { useMemo, useSyncExternalStore } from 'react'; import { create } from 'zustand'; +import { applyDeviceOrder, useDeviceOrderPreferences } from '@/app/navigation/deviceOrderPreferences'; import { createJSONStorage, persist } from 'zustand/middleware'; import { useDeviceDirectory, isDeviceControllable, resolveDeviceNameFrom } from '@/infrastructure/account/deviceDirectory'; import { getActiveSurfaceId, LOCAL_SURFACE_ID, onSurfaceActivated, surfaceIdForDevice, type DeviceSurfaceId } from '@/infrastructure/peer-device/deviceSurface'; @@ -37,8 +38,8 @@ export function devicePlatform(os: string | null | undefined): DevicePlatform | const CONTROLLER_KINDS = new Set(['mobile', 'watch']); /** - * The sidebar's device order: this machine first, then every online host of - * the account by name. The order never depends on which device is rendered, + * The controller's saved order, falling back to this machine then online hosts + * by name for devices the user has not arranged. The order never depends on which device is rendered, * so opening something on another device does not move any section. * * Returns a single slot when there is nothing else to show, so a signed-out or @@ -46,6 +47,7 @@ const CONTROLLER_KINDS = new Set(['mobile', 'watch']); */ export function useSidebarDevices(localLabel: string): SidebarDeviceSlot[] { const directory = useDeviceDirectory(); + const deviceOrder = useDeviceOrderPreferences(state => state.order); const peer = usePeerDeviceModeOptional(); const activeSurfaceId = useSyncExternalStore(onSurfaceActivated, getActiveSurfaceId, getActiveSurfaceId); const renderedPeer = peer?.peerMode.active ? peer.peerMode : null; @@ -95,8 +97,8 @@ export function useSidebarDevices(localLabel: string): SidebarDeviceSlot[] { }); } peers.sort((a, b) => a.name.localeCompare(b.name) || a.surfaceId.localeCompare(b.surfaceId)); - return [...slots, ...peers]; - }, [activeSurfaceId, attachments, directory.devices, directory.localId, localLabel, renderedPeer]); + return applyDeviceOrder([...slots, ...peers], deviceOrder, slot => slot.deviceId); + }, [deviceOrder, activeSurfaceId, attachments, directory.devices, directory.localId, localLabel, renderedPeer]); } interface DeviceSectionDisclosureState { diff --git a/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.scss b/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.scss index 0983f22b53..e4891d2f7b 100644 --- a/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.scss +++ b/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.scss @@ -144,34 +144,41 @@ align-items: center; gap: var(--openbitfun-space-2); padding: var(--openbitfun-space-3) surface.$row-inline; - transition: background-color var(--openbitfun-motion-duration-fast) var(--openbitfun-motion-easing-standard); // An offline device recedes; nothing else changes colour. &.offline .account-panel__device-glyph { color: var(--openbitfun-color-content-muted); } & + & { - @include surface.card-divider(calc(40px + #{surface.$row-gap})); + @include surface.card-divider; } - &.selectable:has(> .account-panel__device-select:hover) { - background: color-mix(in srgb, var(--openbitfun-color-content-primary) 4%, transparent); - } - - // Row actions stay quiet until the row is in hand. - // Row actions appear with the row in hand; at rest the list is just names. + // Visibility stays available; rename and remove appear on hover or focus. &:not(:hover, :focus-within) .account-panel__device-action:not(.account-panel__device-visibility) { opacity: 0; } + } - &.selectable:has(> .account-panel__device-select:active) { - background: var(--openbitfun-color-action-neutral-surface-pressed); - } + &__device-card[data-drop-position='before'] { box-shadow: inset 0 2px var(--openbitfun-color-accent-default); } + &__device-card[data-drop-position='after'] { box-shadow: inset 0 -2px var(--openbitfun-color-accent-default); } - &.selectable:has(> .account-panel__device-select:focus-visible) { - outline: var(--openbitfun-focus-width) solid var(--openbitfun-color-focus-ring); - outline-offset: calc(0px - var(--openbitfun-focus-width)); - } + &__device-drag-handle { + display: inline-flex; + flex-shrink: 0; + align-items: center; + justify-content: center; + width: 24px; + height: 32px; + padding: 0; + border: 0; + border-radius: var(--openbitfun-radius-sm); + background: transparent; + color: var(--openbitfun-color-content-muted); + cursor: grab; + + &:active { cursor: grabbing; } } - &__device-select { + &__device-card[draggable='false'] &__device-drag-handle { opacity: 0.4; cursor: default; } + + &__device-summary { display: flex; min-width: 0; flex: 1; @@ -183,26 +190,7 @@ color: var(--openbitfun-color-content-secondary); font: inherit; text-align: start; - cursor: default; - - &:is(button) { - cursor: pointer; - - // The whole row opens the device; row actions sit above this layer. - &::after { - position: absolute; - inset: 0; - content: ''; - } - } - - &:is(button):disabled { - cursor: default; - } - - &:focus-visible { - outline: 0; - } + cursor: grab; } &__device-glyph { @@ -291,13 +279,6 @@ gap: var(--openbitfun-space-1); } - &__device-chevron { - @include surface.chevron; - display: inline-flex; - inline-size: 16px; - justify-content: center; - } - &__device-alias-editor { position: relative; z-index: 1; @@ -393,10 +374,6 @@ } @media (prefers-reduced-motion: reduce) { - .account-panel__device-card { - transition: none; - } - .account-panel .spinning { animation: none; } diff --git a/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.test.tsx b/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.test.tsx index c15ca50b3c..a7dbd6bb5a 100644 --- a/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.test.tsx +++ b/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.test.tsx @@ -4,6 +4,7 @@ import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import { AccountPanel } from './AccountPanel'; import { useUpdateInstallStore } from '@/infrastructure/update/updateInstallStore'; +import { useDeviceOrderPreferences } from '@/app/navigation/deviceOrderPreferences'; import { useDeviceVisibilityPreferences } from '@/app/navigation/deviceVisibilityPreferences'; const mocks = vi.hoisted(() => ({ identity: { resolved: true, status: 'signed-in', me: { user: { githubId: 42, login: 'alice' } } } as { resolved: boolean; status: string; me: { user: { githubId: number; login: string } } | null }, @@ -56,6 +57,7 @@ beforeEach(() => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); vi.resetAllMocks(); useDeviceVisibilityPreferences.setState({ hidden: {} }); + useDeviceOrderPreferences.setState({ order: [] }); mocks.identity = { resolved: true, status: 'signed-in', me: { user: { githubId: 42, login: 'alice' } } }; mocks.peerMode = { active: false }; mocks.getDeviceInfo.mockResolvedValueOnce({ device_id: 'local', device_name: 'My computer' }) @@ -77,7 +79,7 @@ beforeEach(() => { }); afterEach(() => { act(() => root.unmount()); container.remove(); vi.unstubAllGlobals(); }); it('keeps initialization alive when the local device ID arrives', async () => { - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(mocks.accountStatus).toHaveBeenCalledTimes(1); expect(mocks.accountConnectDevices).toHaveBeenCalledTimes(1); expect(container.textContent).toContain('My computer'); @@ -92,7 +94,7 @@ it('shares sidebar visibility with the preview card, including offline devices, ]); // This is the same preference written by the preview card's eye button. useDeviceVisibilityPreferences.getState().setVisible('peer-a', false); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); const row = Array.from(container.querySelectorAll('.account-panel__device-card')) .find(element => element.textContent?.includes('Offline host'))!; const toggle = row.querySelector('[aria-label="nav.devices.showInSidebar"]')!; @@ -111,7 +113,7 @@ it('waits for local identity before saving a visibility choice under the canonic let resolveIdentity!: (device: { device_id: string; device_name: string }) => void; mocks.getDeviceInfo.mockReset().mockReturnValue(new Promise(resolve => { resolveIdentity = resolve; })); mocks.accountListDevices.mockResolvedValue([{ device_id: 'actual-local-id', device_name: 'My computer', online: true }]); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); const toggle = container.querySelector('[aria-label="nav.devices.hideInSidebar"]')!; expect(toggle.disabled).toBe(true); await act(async () => resolveIdentity({ device_id: 'actual-local-id', device_name: 'My computer' })); @@ -123,8 +125,8 @@ it('waits for local identity before saving a visibility choice under the canonic it('loads the device snapshot and retains it across a normal rerender', async () => { mocks.getDeviceInfo.mockResolvedValue({ device_id: 'local', device_name: 'My computer' }); mocks.accountListDevices.mockResolvedValue([{ device_id: 'local', device_name: 'My computer', online: true }]); - await act(async () => { root.render( {}} />); }); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); + await act(async () => { root.render(); }); expect(mocks.accountStatus).toHaveBeenCalledTimes(1); expect(mocks.accountListDevices).toHaveBeenCalledTimes(1); expect(container.textContent).toContain('My computer'); @@ -133,9 +135,9 @@ it('loads the device snapshot and retains it across a normal rerender', async () it('ignores a late device connection after shared identity signs out', async () => { let resolve!: (devices: Array<{ device_id: string; device_name: string }>) => void; mocks.accountConnectDevices.mockReturnValue(new Promise(res => { resolve = res; })); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); mocks.identity = { resolved: true, status: 'signed-out', me: null }; - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); await act(async () => { resolve([{ device_id: 'old', device_name: 'Old account device' }]); }); expect(container.textContent).not.toContain('Old account device'); expect(container.textContent).toContain('accountLogin.login'); @@ -145,19 +147,19 @@ it('ignores a late device connection after shared identity signs out', async () it('fences a late snapshot when switching accounts', async () => { let resolve!: (devices: Array<{ device_id: string; device_name: string; online: boolean }>) => void; mocks.accountListDevices.mockReturnValueOnce(new Promise(res => { resolve = res; })); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); mocks.identity = { resolved: true, status: 'signed-in', me: { user: { githubId: 7, login: 'bob' } } }; mocks.accountStatus.mockResolvedValue({ logged_in: true, user_id: '7' }); mocks.accountConnectDevices.mockResolvedValue([]); mocks.accountListDevices.mockResolvedValue([{ device_id: 'new', device_name: 'New account device', online: true }]); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); await act(async () => { resolve([{ device_id: 'old', device_name: 'Old account device', online: true }]); }); expect(container.textContent).toContain('New account device'); expect(container.textContent).not.toContain('Old account device'); }); it('shows a connection failure while retaining the signed-in account', async () => { mocks.accountStatus.mockReset().mockRejectedValue(new Error('network unavailable')); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.textContent).toContain('alice'); expect(container.textContent).toContain('accountLogin.retryConnect'); expect(container.textContent).not.toContain('accountLogin.loadingDevices'); @@ -169,7 +171,7 @@ it('explains a retired Relay version and offers an update instead of the raw err Object.assign(new Error('List devices failed: HTTP 410'), { status: 410 }), ); mocks.checkForUpdates.mockResolvedValue({ updateAvailable: true, currentVersion: '1.0.0', latestVersion: '2.0.0', releaseNotes: null, releaseDate: null }); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); // The actionable sentence replaces the raw transport detail and HTTP status. expect(container.textContent).toContain('accountLogin.relayFailureVersionRetired'); expect(container.textContent).not.toContain('List devices failed'); @@ -187,7 +189,7 @@ it('does not offer an update check in a runtime that cannot install updates', as mocks.accountStatus.mockReset().mockRejectedValue( Object.assign(new Error('List devices failed: HTTP 410'), { status: 410 }), ); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.textContent).toContain('accountLogin.relayFailureVersionRetired'); expect(container.textContent).not.toContain('update.checkForUpdates'); // Without a banner action the section heading still offers a way forward. @@ -200,7 +202,7 @@ it('offers a retry when the Relay is temporarily unavailable', async () => { mocks.accountStatus.mockReset().mockRejectedValue( Object.assign(new Error('List devices failed: HTTP 502'), { status: 502 }), ); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.textContent).toContain('accountLogin.relayFailureUnavailable'); expect(container.textContent).not.toContain('502'); const retryButtons = Array.from(container.querySelectorAll('button')) @@ -217,7 +219,7 @@ async function retryConnection() { it('retries a failed connection without asking for GitHub authorization again', async () => { mocks.accountStatus.mockResolvedValue({ logged_in: true, user_id: '42' }); mocks.accountConnectDevices.mockRejectedValueOnce(new Error('socket failure')); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); await retryConnection(); expect(container.textContent).toContain('My computer'); expect(container.textContent).not.toContain('accountLogin.loadingDevices'); @@ -228,14 +230,14 @@ it('allows the new account to retry while an old recovery is still pending', asy mocks.accountStatus.mockResolvedValue({ logged_in: true, user_id: '42' }); mocks.accountConnectDevices.mockRejectedValueOnce(new Error('socket failure')) .mockReturnValueOnce(new Promise(res => { finishOld = res; })); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); await retryConnection(); mocks.identity = { resolved: true, status: 'signed-in', me: { user: { githubId: 7, login: 'bob' } } }; mocks.accountStatus.mockResolvedValue({ logged_in: true, user_id: '7' }); mocks.accountConnectDevices.mockRejectedValueOnce(new Error('socket failure')) .mockResolvedValueOnce([{ device_id: 'new', device_name: 'New account device' }]); mocks.accountListDevices.mockResolvedValue([{ device_id: 'new', device_name: 'New account device', online: true }]); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); await retryConnection(); expect(container.textContent).toContain('New account device'); await act(async () => { finishOld([{ device_id: 'old', device_name: 'Old account device' }]); }); @@ -247,7 +249,7 @@ it('adopts the account-bound local device ID without reconnecting', async () => let finishInfo!: (info: { device_id: string }) => void; mocks.getDeviceInfo.mockReset().mockResolvedValueOnce({ device_id: 'before-auth' }) .mockReturnValueOnce(new Promise(resolve => { finishInfo = resolve; })); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.querySelector('[aria-label="accountLogin.thisDevice"]')).toBeNull(); await act(async () => { finishInfo({ device_id: 'local' }); }); expect(container.querySelector('[aria-label="accountLogin.thisDevice"]')).not.toBeNull(); @@ -258,7 +260,7 @@ it('adopts the account-bound local device ID without reconnecting', async () => it('finishes loading an empty device list', async () => { mocks.accountConnectDevices.mockResolvedValue([]); mocks.accountListDevices.mockResolvedValue([]); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.textContent).not.toContain('accountLogin.loadingDevices'); expect(mocks.accountListDevices).toHaveBeenCalledTimes(1); }); @@ -270,10 +272,10 @@ it('does not restart polling when a recovery snapshot finishes after logout', as mocks.accountStatus.mockResolvedValue({ logged_in: true, user_id: '42' }); mocks.accountConnectDevices.mockRejectedValueOnce(new Error('socket failure')); mocks.accountListDevices.mockReturnValueOnce(new Promise(resolve => { finishSnapshot = resolve; })); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); await retryConnection(); mocks.identity = { resolved: true, status: 'signed-out', me: null }; - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); await act(async () => { finishSnapshot([]); }); await act(async () => { await vi.advanceTimersByTimeAsync(60_000); }); expect(mocks.accountListDevices).toHaveBeenCalledTimes(1); @@ -288,7 +290,7 @@ it('ignores pre-auth device information that arrives after the adopted ID', asyn mocks.getDeviceInfo.mockReset() .mockReturnValueOnce(new Promise(resolve => { finishOldInfo = resolve; })) .mockResolvedValueOnce({ device_id: 'local' }); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.querySelector('[aria-label="accountLogin.thisDevice"]')).not.toBeNull(); await act(async () => { finishOldInfo({ device_id: 'before-auth' }); }); expect(container.querySelector('[aria-label="accountLogin.thisDevice"]')).not.toBeNull(); @@ -298,7 +300,7 @@ it('ignores pre-auth device information that arrives after the adopted ID', asyn it('lets a pending login reopen its external sign-in page', async () => { mocks.identity = { resolved: true, status: 'authorizing', me: null }; mocks.accountStatus.mockResolvedValue({ logged_in: false }); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); const reopen = [...container.querySelectorAll('button')].find(button => button.textContent === 'accountLogin.reopen'); expect(reopen).toBeDefined(); expect(reopen!.disabled).toBe(false); @@ -308,14 +310,14 @@ it('lets a pending login reopen its external sign-in page', async () => { it('shows explicit old Relay capability state before any mutation', async () => { mocks.accountRelayCapabilities.mockResolvedValue([]); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.textContent).toContain('accountLogin.deviceAliasUnsupported'); expect(mocks.accountUpdateDevice).not.toHaveBeenCalled(); }); it('accepts the negotiated alias capability and displays only alias plus metadata', async () => { mocks.accountRelayCapabilities.mockResolvedValue(['device_alias_v1']); mocks.accountListDevices.mockResolvedValue([{ device_id: 'local', device_name: 'technical', device_alias: 'Studio', device_model: 'Model', device_os: 'Linux', online: true }]); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.textContent).not.toContain('accountLogin.deviceAliasUnsupported'); expect(container.textContent).not.toContain('technical'); expect(container.textContent).toContain('Studio'); @@ -329,7 +331,7 @@ it('marks each row with the system it reported, a server for a CLI host, and the { device_id: 'srv', device_name: 'lwb_server', device_os: 'Linux', device_kind: 'cli', online: true }, { device_id: 'legacy', device_name: 'lwb_legacy', online: true }, ]); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); const rowFor = (name: string) => Array.from( container.querySelectorAll('[data-openbitfun-part="deviceCard"]'), @@ -348,7 +350,7 @@ it('keeps the unsupported notice hidden while the capability answer is pending', // An unanswered capability read used to render as an unsupported relay, which // flashed the notice on every panel entry while `/api/info` was in flight. mocks.accountRelayCapabilities.mockImplementation(() => new Promise(() => {})); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.textContent).toContain('My computer'); expect(container.textContent).not.toContain('accountLogin.deviceAliasUnsupported'); }); @@ -356,7 +358,7 @@ it('keeps the unsupported notice hidden when the capability read fails', async ( // Relay reachability owns its own banner; a transport error is not evidence // that the relay lacks the capability. mocks.accountRelayCapabilities.mockRejectedValue(new Error('network down')); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.textContent).not.toContain('accountLogin.deviceAliasUnsupported'); }); @@ -383,7 +385,7 @@ async function openAliasEditor() { it('replaces the device name in place instead of showing two names', async () => { mocks.accountRelayCapabilities.mockResolvedValue(['device_alias_v1']); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.querySelector('.account-panel__device-name')).not.toBeNull(); const input = await openAliasEditor(); // The editor occupies the name's slot; the technical name is not repeated. @@ -397,7 +399,7 @@ it('replaces the device name in place instead of showing two names', async () => it('saves an edited alias from the device row with Enter', async () => { mocks.accountRelayCapabilities.mockResolvedValue(['device_alias_v1']); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); const input = await openAliasEditor(); await act(async () => { setInputValue(input, ' Studio '); }); await act(async () => { input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); }); @@ -407,7 +409,7 @@ it('saves an edited alias from the device row with Enter', async () => { it('clears an alias when the row editor is saved empty', async () => { mocks.accountRelayCapabilities.mockResolvedValue(['device_alias_v1']); mocks.accountListDevices.mockResolvedValue([{ device_id: 'local', device_name: 'My computer', device_alias: 'Studio', online: true }]); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); const input = await openAliasEditor(); await act(async () => { setInputValue(input, ' '); }); await act(async () => { input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); }); @@ -416,7 +418,7 @@ it('clears an alias when the row editor is saved empty', async () => { it('closes the row editor on Escape without renaming', async () => { mocks.accountRelayCapabilities.mockResolvedValue(['device_alias_v1']); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); const input = await openAliasEditor(); await act(async () => { setInputValue(input, 'Studio'); }); await act(async () => { input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); }); @@ -431,7 +433,7 @@ it('never renders a device offline from an empty presence signal', async () => { mocks.accountListDevices.mockReset() .mockResolvedValueOnce([{ device_id: 'local', device_name: 'My computer', device_model: 'Model', online: true, last_seen_at: 1_700_000_000 }]) .mockImplementation(() => new Promise(() => {})); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.textContent).toContain('accountLogin.online'); await emitPresence([]); expect(container.textContent).toContain('accountLogin.online'); @@ -444,7 +446,7 @@ it('merges presence metadata without clearing fields an older relay omits', asyn mocks.accountListDevices.mockReset() .mockResolvedValueOnce([{ device_id: 'local', device_name: 'My computer', device_model: 'Model', device_os: 'Linux', online: true }]) .mockImplementation(() => new Promise(() => {})); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.textContent).not.toContain('Studio'); await emitPresence([{ device_id: 'local', device_name: 'My computer', device_alias: 'Studio' }]); expect(container.textContent).toContain('Studio'); @@ -461,7 +463,7 @@ it('keeps an incompatible device listed with a reason and never targets it', asy { device_id: 'local', device_name: 'My computer', online: true }, { device_id: 'peer', device_name: 'Old build', online: true, compatible: false, device_client_version: '0.9.0' }, ]); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); // The device stays visible; the reason mentions the peer version. expect(container.textContent).toContain('Old build'); expect(container.textContent).toContain('accountLogin.deviceClientIncompatibleWithVersion'); @@ -472,19 +474,34 @@ it('keeps an incompatible device listed with a reason and never targets it', asy expect(container.querySelectorAll('button[aria-label="accountLogin.editDeviceAlias"]').length).toBe(2); }); -it('still allows switching to a device whose compatibility flag is absent', async () => { +it.each([false, true])('keeps device rows non-interactive while peer mode is %s', async active => { + mocks.peerMode = { active }; mocks.accountConnectDevices.mockResolvedValue([]); mocks.getDeviceInfo.mockReset().mockResolvedValue({ device_id: 'local' }); - mocks.switchToDevice.mockResolvedValue('activated'); mocks.accountListDevices.mockResolvedValue([ { device_id: 'local', device_name: 'My computer', online: true }, { device_id: 'peer', device_name: 'Peer build', online: true }, + { device_id: 'offline', device_name: 'Offline host', online: false }, ]); - await act(async () => { root.render( {}} />); }); - const peer = container.querySelector('button[aria-label="accountLogin.openDevice"]'); - expect(peer).not.toBeNull(); - await act(async () => { peer!.click(); }); - expect(mocks.switchToDevice).toHaveBeenCalledWith('peer', 'Peer build'); + await act(async () => { root.render(); }); + const summaries = container.querySelectorAll('.account-panel__device-summary'); + expect(summaries).toHaveLength(3); + for (const summary of summaries) { + expect(summary.tagName).toBe('DIV'); + expect(summary.tabIndex).toBe(-1); + expect(summary.getAttribute('role')).toBeNull(); + await act(async () => { + summary.click(); + summary.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); + summary.dispatchEvent(new KeyboardEvent('keydown', { key: ' ', bubbles: true })); + }); + } + expect(container.querySelector('button[aria-label="accountLogin.openDevice"]')).toBeNull(); + expect(container.querySelector('.account-panel__device-chevron')).toBeNull(); + expect(mocks.switchToDevice).not.toHaveBeenCalled(); + expect(mocks.switchToLocal).not.toHaveBeenCalled(); + expect(useDeviceVisibilityPreferences.getState().hidden).toEqual({}); + expect(container.querySelectorAll('[aria-label="nav.devices.hideInSidebar"]')).toHaveLength(3); }); it('groups the account and its devices into titled sections with fixed row columns', async () => { @@ -494,7 +511,7 @@ it('groups the account and its devices into titled sections with fixed row colum { device_id: 'local', device_name: 'My computer', online: true }, { device_id: 'peer', device_name: 'Peer build', online: false }, ]); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); const titles = Array.from(container.querySelectorAll('.account-panel__section-title')).map(node => node.textContent); expect(titles).toEqual(['accountLogin.accountSectionTitle', 'accountLogin.linkedDevices']); const statuses = Array.from(container.querySelectorAll('.account-panel__device-status')) @@ -503,9 +520,9 @@ it('groups the account and its devices into titled sections with fixed row colum for (const row of container.querySelectorAll('[data-openbitfun-part="deviceCard"]')) { const children = Array.from(row.children).map(node => node.className); expect(children).toEqual([ - 'account-panel__device-select', + 'account-panel__device-drag-handle', + 'account-panel__device-summary', 'account-panel__device-actions', - 'account-panel__device-chevron', ]); } }); @@ -513,7 +530,51 @@ it('groups the account and its devices into titled sections with fixed row colum it('shows the sign-in action inside the account section when signed out', async () => { mocks.identity = { resolved: true, status: 'signed-out', me: null }; mocks.accountStatus.mockReset().mockResolvedValue({ logged_in: false }); - await act(async () => { root.render( {}} />); }); + await act(async () => { root.render(); }); expect(container.querySelector('.account-panel__section-title')?.textContent).toBe('accountLogin.accountSectionTitle'); expect(container.querySelector('[data-openbitfun-part="form"]')?.textContent).toContain('accountLogin.login'); }); + +function deviceOrderInPanel() { + return Array.from(container.querySelectorAll('[data-device-id]')).map(row => row.dataset.deviceId); +} + +function dispatchDeviceDrag(element: Element, type: string, clientY = 0) { + const event = new Event(type, { bubbles: true, cancelable: true }); + Object.defineProperties(event, { clientY: { value: clientY }, dataTransfer: { + value: { effectAllowed: '', dropEffect: '', setData: vi.fn() }, + } }); + element.dispatchEvent(event); +} + +it('commits a drag only on drop without row activation, key bindings or helper tooltips', async () => { + mocks.accountListDevices.mockResolvedValue([ + { device_id: 'local', device_name: 'My computer', online: true }, + { device_id: 'peer', device_name: 'Peer', online: true }, + { device_id: 'offline', device_name: 'Offline', online: false }, + ]); + await act(async () => { root.render(); }); + const row = (id: string) => container.querySelector(`[data-device-id="${id}"]`)!; + vi.spyOn(row('local'), 'getBoundingClientRect').mockReturnValue({ top: 20, height: 60 } as DOMRect); + act(() => dispatchDeviceDrag(row('offline'), 'dragstart')); + act(() => dispatchDeviceDrag(row('local'), 'dragover', 21)); + expect(row('local').dataset.dropPosition).toBe('before'); + expect(deviceOrderInPanel()).toEqual(['local', 'peer', 'offline']); + expect(useDeviceOrderPreferences.getState().order).toEqual([]); + act(() => dispatchDeviceDrag(row('local'), 'drop', 21)); + expect(deviceOrderInPanel()).toEqual(['offline', 'local', 'peer']); + expect(useDeviceOrderPreferences.getState().order).toEqual(['offline', 'local', 'peer']); + const handle = row('offline').querySelector('.account-panel__device-drag-handle')!; + expect(handle.tagName).toBe('SPAN'); + expect(handle.hasAttribute('title')).toBe(false); + act(() => handle.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }))); + expect(deviceOrderInPanel()).toEqual(['offline', 'local', 'peer']); + act(() => dispatchDeviceDrag(row('offline'), 'dragstart')); + act(() => dispatchDeviceDrag(row('peer'), 'dragover', 100)); + act(() => dispatchDeviceDrag(row('offline'), 'dragend')); + expect(deviceOrderInPanel()).toEqual(['offline', 'local', 'peer']); + expect(container.querySelector('[data-drop-position]')).toBeNull(); + expect(mocks.switchToDevice).not.toHaveBeenCalled(); + expect(mocks.switchToLocal).not.toHaveBeenCalled(); + expect(mocks.accountUpdateDevice).not.toHaveBeenCalled(); +}); diff --git a/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.tsx b/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.tsx index fe1cc2fa23..dc206a2696 100644 --- a/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.tsx +++ b/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.tsx @@ -1,5 +1,5 @@ import { refreshDeviceDirectory, isDeviceControllable, deviceClientVersion } from '@/infrastructure/account/deviceDirectory'; -/** Account login and authenticated device connections. */ +/** Account login and linked-device management. */ import { OverflowText, Alert, Avatar, Button, Icon, IconButton, Input, ScrollArea } from '@openbitfun/ui'; import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react'; @@ -7,10 +7,11 @@ import { useI18n } from '@/infrastructure/i18n'; import { confirmDanger, } from '@/infrastructure/confirm-dialog'; -import { LogOut, Pencil, Check, X, House } from 'lucide-react'; +import { LogOut, Pencil, Check, X, House, GripVertical } from 'lucide-react'; import { DeviceSystemGlyph } from '../NavPanel/components/DeviceSystemGlyph'; import { DeviceVisibilityButton } from '../NavPanel/components/DeviceVisibilityButton'; import { LOCAL_SURFACE_ID, surfaceIdForDevice } from '@/infrastructure/peer-device/deviceSurface'; +import { sortAccountDevices, useDeviceOrderPreferences } from '@/app/navigation/deviceOrderPreferences'; import { reportedHostKind } from '../NavPanel/deviceInterconnectionOverview'; import { remoteConnectAPI, deviceDisplayName, deviceMetadataLabel } from '@/infrastructure/api/service-api/RemoteConnectAPI'; import type { @@ -19,7 +20,6 @@ import type { } from '@/infrastructure/api/service-api/RemoteConnectAPI'; import { accountIdentityService, useAccountIdentity } from '@/infrastructure/account-identity'; import { api } from '@/infrastructure/api/service-api/ApiClient'; -import { usePeerDeviceMode } from '@/infrastructure/peer-device/peerDeviceContextState'; import { isAccountAuthFailure, isRelayUnreachable, @@ -102,11 +102,6 @@ async function connectDevicesWithRetry( throw lastError; } -interface AccountPanelProps { - /** Close the whole Remote Connect dialog (used when entering peer mode). */ - onCloseDialog: () => void; -} - /** * Merge one presence entry into a known device. Absent keys mean "this relay * cannot report the field", so they must never erase metadata that came from @@ -179,12 +174,9 @@ const FailureBanner: React.FC = ({ failure, t, busy, onClose ); }; -export const AccountPanel: React.FC = ({ - onCloseDialog, -}) => { +export const AccountPanel: React.FC = () => { const { t, formatRelativeTime } = useI18n('common'); const { success } = useNotification(); - const { peerMode, switchToDevice, switchToLocal } = usePeerDeviceMode(); const identity = useAccountIdentity(); const githubId = (identity.me?.user.accountId ?? identity.me?.user.githubId); const username = identity.me?.email ?? identity.me?.user.login ?? ''; @@ -254,13 +246,16 @@ export const AccountPanel: React.FC = ({ }).catch(error => { log.warn('getDeviceInfo failed', error); }); }, [isAccountEpochCurrent]); - const sortedDevices = useMemo(() => [...devices].sort((left, right) => { - const leftLocal = left.device_id === localDeviceId; - const rightLocal = right.device_id === localDeviceId; - if (leftLocal !== rightLocal) return leftLocal ? -1 : 1; - if (left.online !== right.online) return left.online ? -1 : 1; - return deviceDisplayName(left).localeCompare(deviceDisplayName(right)); - }), [devices, localDeviceId]); + const deviceOrder = useDeviceOrderPreferences(state => state.order); + const sortedDevices = useMemo(() => sortAccountDevices(devices, localDeviceId, deviceOrder), + [devices, localDeviceId, deviceOrder]); + const draggingDevice = useRef(null); + const [dropTarget, setDropTarget] = useState<{ id: string; placement: 'before' | 'after' } | null>(null); + const clearDeviceDrag = () => { draggingDevice.current = null; setDropTarget(null); }; + const moveDevice = (deviceId: string, targetId: string, placement: 'before' | 'after') => { + useDeviceOrderPreferences.getState().move(deviceId, targetId, placement, sortedDevices.map(device => device.device_id)); + }; + useEffect(() => { draggingDevice.current = null; setDropTarget(null); }, [activeAccountEpoch]); const resetState = useCallback(() => { setActiveAccountEpoch(null); @@ -763,46 +758,6 @@ export const AccountPanel: React.FC = ({ setEditingDeviceId(device.device_id); setAliasDraft(device.device_alias ?? ''); }, []); - const selectDevice = useCallback(async (device: AccountDeviceInfo) => { - if (!device.online) return; - // Picking this machine is a normal surface switch back, not a no-op: the - // window may currently be rendering a peer. - const isLocalDevice = Boolean(localDeviceId) && device.device_id === localDeviceId; - // A confirmed-incompatible peer is never a control target. Renaming stays a - // plain directory operation and is handled by its own row action. - if (!isLocalDevice && !isDeviceControllable(device)) return; - setLoading(true); - setError(null); - try { - let outcome: 'activated' | 'superseded'; - if (isLocalDevice) { - outcome = await switchToLocal(); - if (outcome === 'activated') { - success(t('accountLogin.deviceSwitcher.switchedLocal')); - } - } else { - outcome = await switchToDevice(device.device_id, deviceDisplayName(device)); - if (outcome === 'activated') { - success(t('accountLogin.enteredPeerMode', { name: deviceDisplayName(device) })); - } - } - if (outcome === 'activated') { - onCloseDialog(); - } - } catch (e: unknown) { - setError(reportAccountFailure('switch device failed', e)); - } finally { - setLoading(false); - } - }, [ - localDeviceId, - onCloseDialog, - reportAccountFailure, - success, - switchToDevice, - switchToLocal, - t, - ]); /** Run the next step a banner offers; sign-in keeps its existing flow. */ const runFailureAction = useCallback((action: RelayFailureAction) => { @@ -908,12 +863,6 @@ export const AccountPanel: React.FC = ({ )} {sortedDevices.map((d) => { const isLocal = localDeviceId === d.device_id; - // This machine is selectable while the window renders a peer, - // so the dialog can bring the UI back without disconnecting. - // A confirmed-incompatible peer stays listed but is never a - // control target; this machine is never gated by its own flag. - const deviceControllable = isLocal || isDeviceControllable(d); - const isSelectable = (isLocal ? peerMode.active : d.online) && deviceControllable; const incompatible = isLocal ? false : !isDeviceControllable(d); const incompatibleVersion = deviceClientVersion(d); const incompatibleNotice = incompatibleVersion @@ -936,23 +885,46 @@ export const AccountPanel: React.FC = ({ os: d.device_os, hostKind: reportedHostKind(d.device_kind), }; - const DeviceEntry = isSelectable && editingDeviceId !== d.device_id ? 'button' : 'div'; return (
- void selectDevice(d), - disabled: loading, - 'aria-label': t('accountLogin.openDevice', { name: displayName }), - } : {})} - > + data-device-id={d.device_id} + data-drop-position={dropTarget?.id === d.device_id ? dropTarget.placement : undefined} + draggable={editingDeviceId === null && sortedDevices.length > 1} + onDragStart={event => { + if ((event.target as HTMLElement).closest('button, input')) { + event.preventDefault(); return; + } + draggingDevice.current = d.device_id; + event.dataTransfer.effectAllowed = 'move'; + event.dataTransfer.setData('application/x-openbitfun-device-order', d.device_id); + }} + onDragOver={event => { + if (!draggingDevice.current || draggingDevice.current === d.device_id) return; + event.preventDefault(); + event.dataTransfer.dropEffect = 'move'; + const bounds = event.currentTarget.getBoundingClientRect(); + const placement = event.clientY < bounds.top + bounds.height / 2 ? 'before' : 'after'; + setDropTarget(previous => previous?.id === d.device_id && previous.placement === placement + ? previous : { id: d.device_id, placement }); + }} + onDrop={event => { + if (!draggingDevice.current) return; + event.preventDefault(); event.stopPropagation(); + const bounds = event.currentTarget.getBoundingClientRect(); + moveDevice(draggingDevice.current, d.device_id, + event.clientY < bounds.top + bounds.height / 2 ? 'before' : 'after'); + clearDeviceDrag(); + }} + onDragEnd={clearDeviceDrag} + className={`account-panel__device-card ${d.online ? '' : 'offline'} ${isLocal ? 'current' : ''}`}> + +
@@ -1026,7 +998,7 @@ export const AccountPanel: React.FC = ({ )} - +
{/* The open editor owns the row's actions; keeping rename and delete beside it rendered two competing icon clusters. */} {editingDeviceId !== d.device_id && ( @@ -1061,9 +1033,6 @@ export const AccountPanel: React.FC = ({ /> )} -
); })} diff --git a/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.contract.test.ts b/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.contract.test.ts index 2868d48b1d..8f878b3f61 100644 --- a/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.contract.test.ts +++ b/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.contract.test.ts @@ -151,18 +151,18 @@ describe('Remote Connect safety contracts', () => { expect(dialogSource).not.toContain('botConciseMode'); }); - it('keeps device-row actions in fixed columns with the open affordance last', () => { + it('keeps device management actions after a passive device summary', () => { const deviceRow = accountPanelSource.slice( - accountPanelSource.indexOf('const DeviceEntry'), + accountPanelSource.indexOf('sortedDevices.map'), accountPanelSource.indexOf('export default AccountPanel'), ); - expect(deviceRow.indexOf('account-panel__device-actions')).toBeLessThan( - deviceRow.indexOf('account-panel__device-chevron'), - ); - expect(deviceRow.indexOf('')).toBeLessThan( - deviceRow.indexOf(' { diff --git a/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.tsx b/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.tsx index aadaae3bdb..978cae25a5 100644 --- a/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.tsx +++ b/src/web-ui/src/app/components/RemoteConnectDialog/RemoteConnectDialog.tsx @@ -1641,7 +1641,7 @@ export const RemoteConnectDialog: React.FC = ({ role="region" aria-labelledby="remote-connect-view-title" > - + ) : activeView === 'network' ? ( { localStorage.clear(); preferences.setState({ order: [] }); }); + +it.each([undefined, {}, { order: null }, { order: 'local' }, { hidden: { local: true } }])( + 'loads absent or legacy preferences without requiring a migration: %j', async state => { + const saved = JSON.stringify({ state, version: 0 }); + localStorage.setItem(storageKey, saved); + await preferences.persist.rehydrate(); + expect(preferences.getState().order).toEqual([]); + expect(localStorage.getItem(storageKey)).toBe(saved); + }, +); + +it('round-trips order while preserving absent devices and ignoring invalid stored IDs', async () => { + localStorage.setItem(storageKey, JSON.stringify({ state: { order: ['offline', 'peer', 7, '', 'peer', 'local'] }, version: 0 })); + await preferences.persist.rehydrate(); + expect(preferences.getState().order).toEqual(['offline', 'peer', 'local']); + const visible = applyDeviceOrder(['local', 'peer'], preferences.getState().order, id => id); + expect(visible).toEqual(['peer', 'local']); + preferences.getState().move('local', 'peer', 'before', visible); + const saved = localStorage.getItem(storageKey)!; + preferences.setState({ order: [] }); + localStorage.setItem(storageKey, saved); + await preferences.persist.rehydrate(); + expect(preferences.getState().order).toEqual(['offline', 'local', 'peer']); + expect(applyDeviceOrder(['new', 'offline', 'peer', 'local'], preferences.getState().order, id => id)) + .toEqual(['offline', 'local', 'peer', 'new']); +}); + +it('keeps identity-based order through renames, presence changes, and invalid drops', () => { + preferences.getState().move('peer', 'local', 'before', ['local', 'peer', 'offline']); + const order = preferences.getState().order; + preferences.getState().move('unknown', 'peer', 'before', ['local', 'peer']); + preferences.getState().move('peer', 'peer', 'after', ['local', 'peer']); + expect(preferences.getState().order).toBe(order); + const devices = [ + { device_id: 'local', device_name: 'Z', online: true }, + { device_id: 'peer', device_name: 'Renamed', online: false }, + { device_id: 'offline', device_name: 'A', online: true }, + ] as AccountDeviceInfo[]; + expect(sortAccountDevices(devices, 'local', order).map(device => device.device_id)).toEqual(['peer', 'local', 'offline']); +}); diff --git a/src/web-ui/src/app/navigation/deviceOrderPreferences.ts b/src/web-ui/src/app/navigation/deviceOrderPreferences.ts new file mode 100644 index 0000000000..f1b3b5bcfa --- /dev/null +++ b/src/web-ui/src/app/navigation/deviceOrderPreferences.ts @@ -0,0 +1,53 @@ +import { create } from 'zustand'; +import { createJSONStorage, persist } from 'zustand/middleware'; +import { deviceDisplayName, type AccountDeviceInfo } from '@/infrastructure/api/service-api/RemoteConnectAPI'; + +/** Account device IDs, independent of the currently rendered device. */ +interface DeviceOrderPreferences { + order: string[]; + move: (deviceId: string, targetId: string, placement: 'before' | 'after', visibleIds: string[]) => void; +} + +function validIds(value: unknown): string[] { + return Array.isArray(value) + ? [...new Set(value.filter((id): id is string => typeof id === 'string' && id.trim().length > 0))] + : []; +} + +/** Unranked devices retain their normal order after explicitly arranged ones. */ +export function applyDeviceOrder(items: T[], order: string[], id: (item: T) => string | null): T[] { + const ranks = new Map(order.map((deviceId, index) => [deviceId, index])); + return [...items].sort((a, b) => + (ranks.get(id(a) ?? '') ?? order.length) - (ranks.get(id(b) ?? '') ?? order.length)); +} + +export function sortAccountDevices(devices: AccountDeviceInfo[], localId: string | null, order: string[]): AccountDeviceInfo[] { + const defaults = [...devices].sort((a, b) => { + if ((a.device_id === localId) !== (b.device_id === localId)) return a.device_id === localId ? -1 : 1; + if (a.online !== b.online) return a.online ? -1 : 1; + return deviceDisplayName(a).localeCompare(deviceDisplayName(b)) || a.device_id.localeCompare(b.device_id); + }); + return applyDeviceOrder(defaults, order, device => device.device_id); +} + +/** Presentation on this controller only: never saved to either host's config. */ +export const useDeviceOrderPreferences = create()(persist( + set => ({ + order: [], + move: (deviceId, targetId, placement, visibleIds) => set(state => { + if (deviceId === targetId || !visibleIds.includes(deviceId) || !visibleIds.includes(targetId)) return state; + const combined = validIds([...state.order, ...visibleIds]).filter(id => id !== deviceId); + combined.splice(combined.indexOf(targetId) + (placement === 'after' ? 1 : 0), 0, deviceId); + return { order: combined }; + }), + }), + { + name: 'openbitfun.device-order.v1', + storage: createJSONStorage(() => localStorage), + partialize: state => ({ order: state.order }), + merge: (persisted, current) => ({ + ...current, + order: validIds((persisted as Partial | null)?.order), + }), + }, +)); diff --git a/src/web-ui/src/flow_chat/services/RelaySessionHistory.routing.test.ts b/src/web-ui/src/flow_chat/services/RelaySessionHistory.routing.test.ts new file mode 100644 index 0000000000..0e1edb89be --- /dev/null +++ b/src/web-ui/src/flow_chat/services/RelaySessionHistory.routing.test.ts @@ -0,0 +1,75 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { activateSurface } from '@/infrastructure/peer-device/deviceSurface'; +import { setActiveSurfaceDeviceId } from '@/infrastructure/peer-device/deviceSurfaceRouting'; +import { TauriTransportAdapter } from '@/infrastructure/api/adapters/tauri-adapter'; +import { prewarmRelaySessionHistory, RelaySessionHistory } from './RelaySessionHistory'; + +const native = vi.hoisted(() => ({ + registrations: [] as string[], + handlers: new Map void>(), + subscribe: vi.fn(async (..._args: unknown[]) => 'warm-subscription'), unsubscribe: vi.fn(async () => {}), +})); +vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn(async (event: string, handler: (event: { payload: unknown }) => void) => { + native.registrations.push(event); + native.handlers.set(event, handler); + return () => native.handlers.delete(event); +}) })); +vi.mock('@/infrastructure/api/service-api/RemoteConnectAPI', async () => { + const { TauriTransportAdapter } = await import('@/infrastructure/api/adapters/tauri-adapter'); + const adapter = new TauriTransportAdapter(); + return { remoteConnectAPI: { + onSessionRecord: (callback: (value: unknown) => void) => adapter.listen('session-record', callback), + onSessionGap: (callback: (value: unknown) => void) => adapter.listen('relay://session-gap', callback), + onSessionReady: (callback: (value: unknown) => void) => adapter.listen('relay://session-ready', callback), + onSessionSyncError: (callback: (value: unknown) => void) => adapter.listen('account://session-sync-error', callback), + onSessionInteractionChanged: (callback: (value: unknown) => void) => adapter.listen('session-interaction-changed', callback), + subscribeSession: (...args: unknown[]) => native.subscribe(...args), + unsubscribeSession: native.unsubscribe, + loadOlderSession: vi.fn(), + } }; +}); + +beforeEach(() => { + vi.useFakeTimers(); + native.subscribe.mockClear(); native.unsubscribe.mockClear(); native.registrations.length = 0; + activateSurface('local'); setActiveSurfaceDeviceId(null); +}); +afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); activateSurface('local'); setActiveSurfaceDeviceId(null); }); + +it.each([true, false])('adopts only the target stream when records arrive before device commit: %s', async beforeCommit => { + const oldView = vi.fn(); + const nativeAdapter = new TauriTransportAdapter(); + const unlistenOld = nativeAdapter.listen('session-record', oldView); + prewarmRelaySessionHistory('peer', 'session'); + await Promise.resolve(); + const emit = (name: string, source: string, payload: Record) => { + native.handlers.get(name)?.({ payload: { ...payload, __openbitfunSourceDeviceId: source } }); + }; + if (!beforeCommit) { activateSurface('peer'); setActiveSurfaceDeviceId('peer'); } + emit('session-record', 'other-peer', { sessionId: 'session', id: 'wrong-device' }); + emit('relay://session-ready', 'other-peer', { sessionId: 'session', hasMore: true, cursor: 999, oldestSeq: 999 }); + emit('session-record', 'peer', { sessionId: 'other-session', id: 'wrong-session' }); + emit('session-record', 'peer', { sessionId: 'session', id: 'first-record' }); + emit('relay://session-ready', 'peer', { sessionId: 'session', hasMore: false, cursor: 1, oldestSeq: 1 }); + if (beforeCommit) { + expect(oldView).not.toHaveBeenCalled(); + activateSurface('peer'); setActiveSurfaceDeviceId('peer'); + } + unlistenOld(); + const apply = vi.fn(); const ready = vi.fn(); + const history = new RelaySessionHistory('session', apply, ready, vi.fn()); + let outcome: unknown; + const opening = history.open().then(() => { outcome = 'ready'; }, error => { outcome = error.name; }); + await vi.advanceTimersByTimeAsync(15_001); + await opening; + history.close(); + await nativeAdapter.disconnect(); + expect(outcome).toBe('ready'); + expect(apply.mock.calls).toEqual([[{ sessionId: 'session', id: 'first-record' }]]); + expect(ready).toHaveBeenCalledOnce(); + expect(ready.mock.calls[0][0].cursor).toBe(1); + expect(native.registrations.filter(name => name === 'session-record')).toHaveLength(1); + expect(native.registrations.filter(name => name === 'relay://session-ready')).toHaveLength(1); + expect(native.subscribe).toHaveBeenCalledOnce(); + expect(native.unsubscribe).toHaveBeenCalledWith('warm-subscription'); +}); diff --git a/src/web-ui/src/flow_chat/services/RelaySessionHistory.test.ts b/src/web-ui/src/flow_chat/services/RelaySessionHistory.test.ts index 592271683d..5e993ccf87 100644 --- a/src/web-ui/src/flow_chat/services/RelaySessionHistory.test.ts +++ b/src/web-ui/src/flow_chat/services/RelaySessionHistory.test.ts @@ -14,14 +14,15 @@ vi.mock('@/infrastructure/peer-device/deviceSurface', () => ({ assertCurrent: () => { if (!fixture.current) throw new Error('Surface changed'); } }), })); vi.mock('@/infrastructure/api/service-api/RemoteConnectAPI', () => ({ remoteConnectAPI: { - onSessionInteractionChanged: (listener: (event:any)=>void) => {fixture.interaction=listener;return()=>{fixture.interaction=null;};}, - onSessionRecord: (listener: (event: unknown) => void) => { fixture.record = listener; return () => { fixture.record = null; }; }, - onSessionReady: (listener: (event: any) => void) => { fixture.ready = listener; return () => { fixture.ready = null; }; }, - onSessionSyncError: (listener: (event: any) => void) => { fixture.error = listener; return () => { fixture.error = null; }; }, - onSessionGap: (listener: (event: any) => void) => { fixture.gap = listener; return () => { fixture.gap = null; }; }, + onSessionInteractionChanged: (listener: (event:any)=>void) => {fixture.interaction=listener;return()=>{if (fixture.interaction === listener) fixture.interaction=null;};}, + onSessionRecord: (listener: (event: unknown) => void) => { fixture.record = listener; return () => { if (fixture.record === listener) fixture.record = null; }; }, + onSessionReady: (listener: (event: any) => void) => { fixture.ready = listener; return () => { if (fixture.ready === listener) fixture.ready = null; }; }, + onSessionSyncError: (listener: (event: any) => void) => { fixture.error = listener; return () => { if (fixture.error === listener) fixture.error = null; }; }, + onSessionGap: (listener: (event: any) => void) => { fixture.gap = listener; return () => { if (fixture.gap === listener) fixture.gap = null; }; }, subscribeSession: fixture.subscribe, unsubscribeSession: fixture.unsubscribe, loadOlderSession: fixture.older, } })); +import { routeSurfaceEvent } from '@/infrastructure/peer-device/deviceSurfaceRouting'; import { prewarmRelaySessionHistory, RelaySessionHistory } from './RelaySessionHistory'; describe('RelaySessionHistory', () => { @@ -59,9 +60,9 @@ describe('RelaySessionHistory', () => { fixture.subscribe.mockImplementation(() => new Promise(resolve => { resolveSubscription = resolve; })); prewarmRelaySessionHistory('host', 'session'); // The host answers while the device switch is still running. - fixture.record?.({ sessionId: 'session', id: 'turn/turn' }); - fixture.record?.({ sessionId: 'other', id: 'turn/other' }); - fixture.ready?.({ sessionId: 'session', hasMore: false, oldestSeq: 1, cursor: 1 }); + routeSurfaceEvent('session-record', { __openbitfunSourceDeviceId: 'host', sessionId: 'session', id: 'turn/turn' }); + routeSurfaceEvent('session-record', { __openbitfunSourceDeviceId: 'host', sessionId: 'other', id: 'turn/other' }); + routeSurfaceEvent('relay://session-ready', { __openbitfunSourceDeviceId: 'host', sessionId: 'session', hasMore: false, oldestSeq: 1, cursor: 1 }); const apply = vi.fn(); const onReady = vi.fn(); const history = new RelaySessionHistory('session', apply, onReady, vi.fn()); diff --git a/src/web-ui/src/flow_chat/services/RelaySessionHistory.ts b/src/web-ui/src/flow_chat/services/RelaySessionHistory.ts index b571180013..6f4ea1b4b3 100644 --- a/src/web-ui/src/flow_chat/services/RelaySessionHistory.ts +++ b/src/web-ui/src/flow_chat/services/RelaySessionHistory.ts @@ -1,5 +1,6 @@ import { remoteConnectAPI } from '@/infrastructure/api/service-api/RemoteConnectAPI'; import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; +import { observeSurfaceEvents } from '@/infrastructure/peer-device/deviceSurfaceRouting'; import type { SessionRecord } from '../session-stream/SessionRecordReplica'; import { createLogger } from '@/shared/utils/logger'; import { resourceBudget } from '@/shared/utils/resourceBudget'; @@ -50,12 +51,26 @@ export function prewarmRelaySessionHistory(surfaceId: string, sessionId: string) if (warmStreams.has(key)) return; const events: WarmSessionStream['events'] = []; const forThisSession = (value: unknown) => (value as { sessionId?: unknown } | null)?.sessionId === sessionId; + // Warm reads belong to their target, which is not necessarily rendered yet. + // Observe before active-surface filtering; normal product listeners must stay + // fenced. Keep the native feeds registered with no-op consumers so the same + // event is buffered exactly once, both before and after the device commit. const disposers = [ - remoteConnectAPI.onSessionRecord(value => { if (forThisSession(value)) events.push({ kind: 'record', value }); }), - remoteConnectAPI.onSessionGap(value => { if (forThisSession(value)) events.push({ kind: 'gap', value }); }), - remoteConnectAPI.onSessionSyncError(value => { if (forThisSession(value)) events.push({ kind: 'syncError', value }); }), - remoteConnectAPI.onSessionReady(value => { if (forThisSession(value)) events.push({ kind: 'ready', value }); }), - remoteConnectAPI.onSessionInteractionChanged(value => { if (forThisSession(value)) events.push({ kind: 'interaction', value }); }), + observeSurfaceEvents((name, sourceDeviceId, value) => { + if (sourceDeviceId !== surfaceId || !forThisSession(value)) return; + const kind = name === 'session-record' ? 'record' + : name === 'relay://session-gap' ? 'gap' + : name === 'relay://session-ready' ? 'ready' : null; + if (kind) events.push({ kind, value }); + }), + remoteConnectAPI.onSessionRecord(() => undefined), + remoteConnectAPI.onSessionGap(() => undefined), + remoteConnectAPI.onSessionReady(() => undefined), + remoteConnectAPI.onSessionSyncError(value => { + if (value.targetDeviceId === surfaceId && forThisSession(value)) events.push({ kind: 'syncError', value }); + }), + // start() reads the interaction mailbox on adoption, including changes made + // while warming; no unscoped interaction event needs to be buffered here. ]; const subscription = remoteConnectAPI.subscribeSession(surfaceId, sessionId); const stream: WarmSessionStream = { @@ -86,7 +101,6 @@ function takeWarmStream(surfaceId: string, sessionId: string): WarmSessionStream if (!stream) return undefined; warmStreams.delete(key); clearTimeout(stream.timer); - stream.dispose(); return stream; } @@ -153,7 +167,8 @@ export class RelaySessionHistory { this.rejectReady(error); this.rejectPage?.(error); onError(error); }; this.resumeInteraction = onResumed; - // Taken before this owner listens, so no event is both buffered and live. + // Claim the stream first, but retain its native feeds until the new owner + // has registered. Unlisten/relisten would lose events during async setup. this.warm = takeWarmStream(this.scope.surfaceId, sessionId); // Register before asking Rust to replay its cache or fetch the first page. this.listeners.push(remoteConnectAPI.onSessionRecord(this.handlers.record = value => { @@ -208,6 +223,7 @@ export class RelaySessionHistory { if (!this.isCurrent() || event.sessionId !== this.sessionId || !onResumed) return; void onResumed().catch(error => log.warn('Session interaction mailbox refresh failed', {sessionId:this.sessionId,error})); })); + this.warm?.dispose(); // A closed subscription may never have had an open() caller. void this.firstPage.catch(() => {}); if (typeof document !== 'undefined') { diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.ts index f5cbc851f6..cab364b8c7 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/SessionModule.ts @@ -294,7 +294,7 @@ async function hydrateHistoricalSession( ? i18nService.t('flow-chat:externalHistory.unsupported') : sourceHistory?.sourceStatus === 'unavailable' && !sourceHistory.contentVersion ? i18nService.t('flow-chat:externalHistory.unavailableWithoutCache') - : 'Failed to load session history, showing empty session'; + : i18nService.t('flow-chat:historyState.failedTitle'); notificationService.warning(message, { duration: 3000 }); diff --git a/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.test.ts b/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.test.ts new file mode 100644 index 0000000000..8c8990f503 --- /dev/null +++ b/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.test.ts @@ -0,0 +1,26 @@ +import { beforeEach, expect, it, vi } from 'vitest'; +import { remoteConnectAPI } from './RemoteConnectAPI'; + +const fixture = vi.hoisted(() => ({ request: vi.fn(), wait: vi.fn() })); +vi.mock('../adapters', () => ({ getTransportAdapter: () => ({ request: fixture.request }) })); +vi.mock('./ApiClient', () => ({ api: { waitForListenerRegistrations: fixture.wait } })); +beforeEach(() => { vi.resetAllMocks(); fixture.request.mockResolvedValue('subscription'); }); + +it('waits for event registration before a subscription can replay cached history', async () => { + let registered!: () => void; + fixture.wait.mockReturnValue(new Promise(resolve => { registered = resolve; })); + const opening = remoteConnectAPI.subscribeSession('peer', 'session'); + await Promise.resolve(); + expect(fixture.request).not.toHaveBeenCalled(); + registered(); + await expect(opening).resolves.toBe('subscription'); + expect(fixture.request).toHaveBeenCalledWith('account_subscribe_session', { + request: { target_device_id: 'peer', session_id: 'session' }, + }); +}); + +it('does not allocate a subscription if listener registration fails', async () => { + fixture.wait.mockRejectedValue(new Error('Event listener unavailable')); + await expect(remoteConnectAPI.subscribeSession('peer', 'session')).rejects.toThrow('Event listener unavailable'); + expect(fixture.request).not.toHaveBeenCalled(); +}); diff --git a/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts b/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts index a19e5f65e7..dcc6736058 100644 --- a/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts +++ b/src/web-ui/src/infrastructure/api/service-api/RemoteConnectAPI.ts @@ -514,6 +514,9 @@ class RemoteConnectAPIService { } async subscribeSession(targetDeviceId: string, sessionId: string): Promise { + // Native listener registration is asynchronous; cached history may replay + // during the subscribe command, before its response reaches this window. + await api.waitForListenerRegistrations(); return this.adapter.request('account_subscribe_session', { request: { target_device_id: targetDeviceId, session_id: sessionId } }); } async unsubscribeSession(subscriptionId: string): Promise { diff --git a/src/web-ui/src/infrastructure/peer-device/README.md b/src/web-ui/src/infrastructure/peer-device/README.md index 95247b3572..f5aa2ea11e 100644 --- a/src/web-ui/src/infrastructure/peer-device/README.md +++ b/src/web-ui/src/infrastructure/peer-device/README.md @@ -130,7 +130,11 @@ notification metadata. 2. **Peer history has one owner.** `loadSessionHistory` uses `RelaySessionHistory`; it must not fall back to `restore_session_view`, cloud - imports, or a local transcript after a Relay failure. + imports, or a local transcript after a Relay failure. A prewarmed stream + buffers only its target device and session via the source-aware observer, + before active-surface filtering. Keep its native feeds alive until the + adopting owner has registered, and await event registration before requesting + replay; neither an early host reply nor handover may drop the first page. 3. **Failures stay explicit and recoverable.** Failed reads leave loading state, retain previously rendered records, and expose retry. An empty success is not