diff --git a/.oxlintrc.json b/.oxlintrc.json index 474a249b06..332da9aa05 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -422,7 +422,6 @@ "packages/app/src/components/headers/back-header.tsx", "packages/app/src/components/headers/screen-header.tsx", "packages/app/src/components/host-status-dot.tsx", - "packages/app/src/components/hosts/host-picker.tsx", "packages/app/src/components/icons/paseo-logo.tsx", "packages/app/src/components/left-sidebar.tsx", "packages/app/src/components/plan-card.tsx", @@ -554,7 +553,6 @@ "packages/app/src/components/headers/back-header.tsx", "packages/app/src/components/highlighted-code-block.tsx", "packages/app/src/components/hosts/host-filter.tsx", - "packages/app/src/components/hosts/host-picker.tsx", "packages/app/src/components/import-session-sheet.tsx", "packages/app/src/components/left-sidebar.tsx", "packages/app/src/components/markdown/fence/mermaid/host.native.tsx", diff --git a/packages/app/e2e/browser/host-appearance.spec.ts b/packages/app/e2e/browser/host-appearance.spec.ts index cb6695c439..26321fa37c 100644 --- a/packages/app/e2e/browser/host-appearance.spec.ts +++ b/packages/app/e2e/browser/host-appearance.spec.ts @@ -4,6 +4,7 @@ import { addConnectedHostAndReload, chooseHostBadgeDisplay, chooseHostColor, + chooseHostIcon, expectHostAppearancePreview, expectHostBadgeIconOnly, expectHostBadgeName, @@ -115,12 +116,21 @@ test("customizes a host badge and preserves its appearance after reload", async expect(widths.content).toBeLessThanOrEqual(widths.client); }); - await test.step("preview a color and apply it to the sidebar badge", async () => { + await test.step("preview a color and icon and apply them to the sidebar badge and host popover", async () => { await openHostAppearanceSettings(page, badge.serverId); await chooseHostColor(page, "Teal"); + await chooseHostIcon(page, "Laptop"); await expectHostAppearancePreview(page, { serverId: badge.serverId, hostName, color: "teal" }); await leaveHostAppearanceSettings(page); await expectHostBadgeTinted(page, { ...badge, hostName, color: "teal" }); + + await page.getByTestId("sidebar-hosts-trigger").click(); + const hostRow = page.getByTestId(`sidebar-host-row-${badge.serverId}`); + await expect(hostRow).toBeVisible(); + await expect(hostRow).toContainText("Direct"); + await expect(hostRow).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/); + await expect(hostRow).not.toContainText(/agents?/i); + await page.keyboard.press("Escape"); }); await test.step("keep the icon-only preference through reload", async () => { @@ -145,3 +155,30 @@ test("customizes a host badge and preserves its appearance after reload", async }); }); }); + +base( + "activates Add host from the sidebar host picker via focus+Enter and Arrow+Enter", + async ({ page }) => { + await gotoAppShell(page); + const trigger = page.getByTestId("sidebar-hosts-trigger"); + await expect(trigger).toBeVisible(); + + // Focus + Enter on Add host must open the Add connection dialog rather than selecting the active host. + const addConnectionDialog = page.getByRole("dialog").filter({ hasText: "Add connection" }); + await trigger.click(); + const addHostButton = page.getByRole("button", { name: "Add host", exact: true }); + await expect(addHostButton).toBeVisible(); + await addHostButton.focus(); + await page.keyboard.press("Enter"); + await expect(addConnectionDialog).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(addConnectionDialog).toBeHidden(); + + // ArrowDown + Enter must also reach Add host from the host list. + await trigger.click(); + await expect(addHostButton).toBeVisible(); + await page.keyboard.press("ArrowDown"); + await page.keyboard.press("Enter"); + await expect(addConnectionDialog).toBeVisible(); + }, +); diff --git a/packages/app/e2e/browser/settings-navigation.spec.ts b/packages/app/e2e/browser/settings-navigation.spec.ts index 1e9805bef0..3f4d59e983 100644 --- a/packages/app/e2e/browser/settings-navigation.spec.ts +++ b/packages/app/e2e/browser/settings-navigation.spec.ts @@ -65,8 +65,7 @@ import { openSettingsHostSection, removeCurrentHostFromSettings, openSidebarHostPicker, - sidebarHostSettingsButton, - expectStandaloneSidebarHostSettingsButton, + sidebarHostRowButton, activateSidebarHostSettingsWithKeyboard, bindCommandCenterToEnter, } from "../support/helpers/settings"; @@ -192,17 +191,16 @@ test.describe("Settings sidebar scroll position", () => { }); test.describe("Settings sidebar navigation", () => { - test("the sidebar host gear opens Overview in one click", async ({ page, withWorkspace }) => { + test("the sidebar host row opens Overview in one click", async ({ page, withWorkspace }) => { const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" }); await openWorkspace(page, workspace); await openSidebarHostPicker(page); - await expectStandaloneSidebarHostSettingsButton(page); - await sidebarHostSettingsButton(page).click(); + await sidebarHostRowButton(page).click(); await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host")); }); - test("Enter opens the focused sidebar host gear", async ({ page, withWorkspace }) => { + test("Enter opens the active sidebar host row", async ({ page, withWorkspace }) => { await bindCommandCenterToEnter(page); const workspace = await withWorkspace({ prefix: "keyboard-host-settings-" }); await openWorkspace(page, workspace); @@ -566,7 +564,7 @@ test.describe("Settings — compact master-detail", () => { await openWorkspace(page, workspace); await page.getByRole("button", { name: "Open menu", exact: true }).click(); await page.getByTestId("sidebar-hosts-trigger").click(); - await page.getByRole("button", { name: /Open .* settings/ }).click(); + await sidebarHostRowButton(page).click(); await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host")); await expect(page.getByText("Overview", { exact: true })).toBeVisible(); diff --git a/packages/app/e2e/support/helpers/hosts.ts b/packages/app/e2e/support/helpers/hosts.ts index 0e0a9f56fe..0f3d8783cc 100644 --- a/packages/app/e2e/support/helpers/hosts.ts +++ b/packages/app/e2e/support/helpers/hosts.ts @@ -132,7 +132,10 @@ export async function waitForConnectedHost( ): Promise { await page.getByTestId("sidebar-hosts-trigger").click(); const host = page.getByTestId(`sidebar-host-row-${input.serverId}`); - await expect(host).toContainText(input.endpoint, { timeout: 30_000 }); + const escapedEndpoint = input.endpoint.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + // Local daemons render "Local" without repeating localhost:; remote hosts render the endpoint. + await expect(host).toContainText(new RegExp(`${escapedEndpoint}|Local`), { timeout: 30_000 }); + await expect(host).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/, { timeout: 30_000 }); await page.keyboard.press("Escape"); await expect(host).not.toBeVisible(); } @@ -195,6 +198,12 @@ export async function chooseHostColor(page: Page, colorName: string): Promise { + await page.getByTestId("host-appearance-icon").click(); + await page.getByRole("menuitem", { name: iconName, exact: true }).click(); + await expect(page.getByRole("button", { name: `Icon, ${iconName}` })).toBeVisible(); +} + export async function chooseHostBadgeDisplay( page: Page, option: "Name" | "Icon only" | "Hidden", diff --git a/packages/app/e2e/support/helpers/settings.ts b/packages/app/e2e/support/helpers/settings.ts index 96e4a5b284..bd6664f067 100644 --- a/packages/app/e2e/support/helpers/settings.ts +++ b/packages/app/e2e/support/helpers/settings.ts @@ -16,8 +16,8 @@ export async function openSidebarHostPicker(page: Page) { await page.getByRole("button", { name: "Hosts", exact: true }).click(); } -export function sidebarHostSettingsButton(page: Page) { - return page.getByRole("button", { name: `Open ${TEST_HOST_LABEL} settings`, exact: true }); +export function sidebarHostRowButton(page: Page) { + return page.getByTestId(`sidebar-host-row-${getServerId()}`); } export async function bindCommandCenterToEnter(page: Page) { @@ -32,20 +32,10 @@ export async function bindCommandCenterToEnter(page: Page) { }); } -export async function expectStandaloneSidebarHostSettingsButton(page: Page) { - const gear = sidebarHostSettingsButton(page); - await expect(gear).toBeVisible(); - expect(await gear.evaluate((button) => button.parentElement?.closest("button") === null)).toBe( - true, - ); -} - export async function activateSidebarHostSettingsWithKeyboard(page: Page) { - const host = page.getByRole("button", { name: TEST_HOST_LABEL, exact: true }); + const host = sidebarHostRowButton(page); + await expect(host).toBeVisible(); await expect(host).toBeFocused(); - await page.keyboard.press("ArrowDown"); - await page.keyboard.press("Tab"); - await expect(sidebarHostSettingsButton(page)).toBeFocused(); await page.keyboard.press("Enter"); } diff --git a/packages/app/src/components/hosts/host-picker.tsx b/packages/app/src/components/hosts/host-picker.tsx index c8a7c0060c..4051896640 100644 --- a/packages/app/src/components/hosts/host-picker.tsx +++ b/packages/app/src/components/hosts/host-picker.tsx @@ -1,11 +1,28 @@ -import { useCallback, useMemo, type ReactElement, type ReactNode } from "react"; -import { Pressable, View } from "react-native"; -import { Plus, Server, Settings } from "lucide-react-native"; -import { StyleSheet, useUnistyles } from "react-native-unistyles"; +import { + useCallback, + useEffect, + useMemo, + useState, + type ReactElement, + type ReactNode, +} from "react"; +import { useTranslation } from "react-i18next"; +import { Text, View } from "react-native"; +import { Check, Plus, Server } from "lucide-react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { HostStatusDot } from "@/components/host-status-dot"; -import { Combobox, ComboboxItem, type ComboboxProps } from "@/components/ui/combobox"; +import { Combobox, type ComboboxProps } from "@/components/ui/combobox"; +import { PressHighlight } from "@/components/ui/press-highlight"; import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon"; -import { useHostRuntimeSnapshot, type ActiveConnection } from "@/runtime/host-runtime"; +import { defaultHostAppearance, resolveHostIcon, type HostAppearance } from "@/hosts/appearance"; +import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon"; +import { + getHostRuntimeStore, + useHostRuntimeConnectionStatus, + useHosts, +} from "@/runtime/host-runtime"; +import { useSessionStore } from "@/stores/session-store"; +import { ICON_SIZE, type Theme } from "@/styles/theme"; import { orderHostsLocalFirst } from "@/types/host-connection"; import { ADD_HOST_OPTION_ID, @@ -22,7 +39,16 @@ export { }; const SEARCHABLE_THRESHOLD = 10; +const DEFAULT_DESKTOP_MIN_WIDTH = 328; +const LEADING_RAIL_SIZE = 16; +const HOST_ROW_ICON_SIZE = 14; type RenderHostOption = NonNullable; + +const ThemedCheck = withUnistyles(Check); +const ThemedPlus = withUnistyles(Plus); +const ThemedServer = withUnistyles(Server); +const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); + export interface HostPickerHost { serverId: string; label: string; @@ -36,122 +62,166 @@ export function HostStatusDotSlot({ serverId }: { serverId: string }): ReactElem ); } -// Standard secure/plain web ports carry no information in the host display, so -// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept. -function formatConnectionEndpoint(endpoint: string): string { - return endpoint.replace(/:(?:443|80)$/, ""); -} - -// Socket/pipe transports have no host:port — their endpoint is a filesystem -// path, so they read as "Local". TCP and relay show the address being used. -function formatActiveConnectionLabel(connection: ActiveConnection): string { - if (connection.type === "directSocket" || connection.type === "directPipe") { - return "Local"; - } - return formatConnectionEndpoint(connection.endpoint); -} - export interface HostPickerOptionProps { serverId: string; label: string; - showActiveConnection: boolean; + appearance: HostAppearance; selected?: boolean; active: boolean; onPress: () => void; - onOpenHostSettings?: (serverId: string) => void; testID?: string; } export function HostPickerOption({ serverId, label, - showActiveConnection, + appearance, selected, active, onPress, - onOpenHostSettings, testID, }: HostPickerOptionProps): ReactElement { - const { theme } = useUnistyles(); - const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null; - const connectionLabel = - showActiveConnection && activeConnection - ? formatActiveConnectionLabel(activeConnection) - : undefined; - const leadingSlot = useMemo(() => , [serverId]); - const handleSettingsPress = useCallback(() => { - onOpenHostSettings?.(serverId); - }, [onOpenHostSettings, serverId]); - const trailingAction = useMemo(() => { - if (!onOpenHostSettings) return undefined; - return ( - - - - ); - }, [ - handleSettingsPress, - label, - onOpenHostSettings, - theme.colors.foregroundMuted, - theme.iconSize.sm, - ]); + const status = useHostRuntimeConnectionStatus(serverId); + const detectedMachineKind = useSessionStore( + (state) => state.sessions[serverId]?.serverInfo?.machineKind ?? null, + ); + const resolvedIcon = resolveHostIcon({ appearance, detectedMachineKind }); + const [hovered, setHovered] = useState(false); + const handlePointerEnter = useCallback(() => setHovered(true), []); + const handlePointerLeave = useCallback(() => setHovered(false), []); + const isOffline = status === "offline" || status === "error"; return ( - + + + + + + + + + + {label} + + + + + + + {selected ? : null} + + + ); } -const SYSTEM_HOST_PICKER_OPTION_LABELS: Record<"add" | "all" | "enableBuiltInDaemon", string> = { - add: "Add host", - all: "All hosts", - enableBuiltInDaemon: "Enable built-in daemon", -}; - -function SystemHostPickerOption({ +function AllHostsOption({ active, selected, onPress, - kind, testID, }: { active: boolean; selected?: boolean; onPress: () => void; - kind: "add" | "all" | "enableBuiltInDaemon"; testID?: string; }): ReactElement { - const { theme } = useUnistyles(); - const Icon = kind === "add" ? Plus : Server; - const label = SYSTEM_HOST_PICKER_OPTION_LABELS[kind]; - const leadingSlot = useMemo( - () => , - [Icon, theme.colors.foregroundMuted, theme.iconSize.sm], - ); + const { t } = useTranslation(); + const [hovered, setHovered] = useState(false); + const handlePointerEnter = useCallback(() => setHovered(true), []); + const handlePointerLeave = useCallback(() => setHovered(false), []); + const label = t("sidebar.display.hostFilter.all"); return ( - + + + + + + + {label} + + {selected ? : null} + + + ); +} + +function ActionOptionRow({ + kind, + active, + showDivider, + onPress, + testID, +}: { + kind: "add" | "enableBuiltInDaemon"; + active: boolean; + showDivider: boolean; + onPress: () => void; + testID?: string; +}): ReactElement { + const { t } = useTranslation(); + const [hovered, setHovered] = useState(false); + const handlePointerEnter = useCallback(() => setHovered(true), []); + const handlePointerLeave = useCallback(() => setHovered(false), []); + const label = kind === "add" ? t("settings.addHost") : t("settings.enableBuiltInDaemon"); + + return ( + + {showDivider ? : null} + + + + {kind === "add" ? ( + + ) : ( + + )} + + + {label} + + + + ); } @@ -168,7 +238,6 @@ export interface HostPickerProps { includeEnableBuiltInDaemon?: boolean; onEnableBuiltInDaemon?: () => void; showActiveConnection?: boolean; - onOpenHostSettings?: (serverId: string) => void; searchable?: boolean; title?: string; desktopPlacement?: ComboboxProps["desktopPlacement"]; @@ -190,74 +259,85 @@ export function HostPicker({ onAddHost, includeEnableBuiltInDaemon, onEnableBuiltInDaemon, - showActiveConnection, - onOpenHostSettings, searchable, title, desktopPlacement = "bottom-start", - desktopMinWidth, + desktopMinWidth = DEFAULT_DESKTOP_MIN_WIDTH, addHostTestID, hostOptionTestID, children, }: HostPickerProps): ReactElement { + const { t } = useTranslation(); const localServerId = useLocalDaemonServerId(); + const allHostProfiles = useHosts(); const orderedHosts = useMemo( () => orderHostsLocalFirst(hosts, localServerId), [hosts, localServerId], ); + const appearanceByServerId = useMemo(() => { + const map = new Map(); + for (const profile of allHostProfiles) { + map.set(profile.serverId, profile.appearance); + } + return map; + }, [allHostProfiles]); + + useEffect(() => { + if (!open) return; + getHostRuntimeStore().refreshActiveLatencies(orderedHosts.map((host) => host.serverId)); + }, [open, orderedHosts]); + const options = useMemo(() => { const hostOptions = orderedHosts.map((host) => ({ id: host.serverId, label: host.label })); - if (includeAllHost) hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: "All hosts" }); - if (includeAddHost) hostOptions.push({ id: ADD_HOST_OPTION_ID, label: "Add host" }); - if (includeEnableBuiltInDaemon) + if (includeAllHost) { + hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: t("sidebar.display.hostFilter.all") }); + } + if (includeAddHost) { + hostOptions.push({ id: ADD_HOST_OPTION_ID, label: t("settings.addHost") }); + } + if (includeEnableBuiltInDaemon) { hostOptions.push({ id: ENABLE_BUILT_IN_DAEMON_OPTION_ID, - label: "Enable built-in daemon", + label: t("settings.enableBuiltInDaemon"), }); + } return hostOptions; - }, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon]); + }, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon, t]); + + let firstActionOptionId: string | null = null; + if (includeAddHost) { + firstActionOptionId = ADD_HOST_OPTION_ID; + } else if (includeEnableBuiltInDaemon) { + firstActionOptionId = ENABLE_BUILT_IN_DAEMON_OPTION_ID; + } const isSearchable = searchable === true && orderedHosts.length > SEARCHABLE_THRESHOLD; + const resolvedTitle = title ?? t("sidebar.actions.hosts"); const handleSelect = useCallback( (id: string) => { if (id === ADD_HOST_OPTION_ID) { + onOpenChange(false); onAddHost?.(); - } else if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) { - onEnableBuiltInDaemon?.(); - } else { - onSelect(id); + return; } + if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) { + onOpenChange(false); + onEnableBuiltInDaemon?.(); + return; + } + onSelect(id); onOpenChange(false); }, [onAddHost, onEnableBuiltInDaemon, onOpenChange, onSelect], ); - const handleOpenHostSettings = useCallback( - (serverId: string) => { - onOpenHostSettings?.(serverId); - onOpenChange(false); - }, - [onOpenHostSettings, onOpenChange], - ); - const renderOption = useCallback( ({ option, selected, active, onPress }) => { - if (option.id === ADD_HOST_OPTION_ID) { - return ( - - ); - } if (option.id === ALL_HOSTS_OPTION_ID) { return ( - ); } - if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) { + if (option.id === ADD_HOST_OPTION_ID) { return ( - + 0} + onPress={onPress} + testID={addHostTestID} + /> ); } + if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) { + return ( + 0 + } + onPress={onPress} + /> + ); + } + const appearance = appearanceByServerId.get(option.id) ?? defaultHostAppearance(); return ( ); }, [ addHostTestID, + appearanceByServerId, + firstActionOptionId, hostOptionTestID, - onOpenHostSettings, - showActiveConnection, - handleOpenHostSettings, + orderedHosts.length, ], ); @@ -301,8 +399,8 @@ export function HostPicker({ onSelect={handleSelect} renderOption={renderOption} searchable={isSearchable} - searchPlaceholder="Search hosts" - title={title ?? "Host"} + searchPlaceholder={t("sidebar.host.searchPlaceholder")} + title={resolvedTitle} open={open} onOpenChange={onOpenChange} anchorRef={anchorRef} @@ -314,16 +412,86 @@ export function HostPicker({ } const styles = StyleSheet.create((theme) => ({ - settingsAction: { - flex: 1, - justifyContent: "center", - paddingLeft: theme.spacing[1], - paddingRight: theme.spacing[3], - }, statusDotSlot: { width: theme.iconSize.sm, height: theme.iconSize.sm, alignItems: "center", justifyContent: "center", }, + rowEnvelope: { + position: "relative", + }, + // Shared leading rail: the status dot on host rows and the '+' / All hosts glyph share one + // centered 16px column aligned to the first line's 18px line-height. + leadingRailSlot: { + width: LEADING_RAIL_SIZE, + height: 18, + alignItems: "center", + justifyContent: "center", + flexShrink: 0, + }, + hostRow: { + flexDirection: "row", + alignItems: "flex-start", + gap: theme.spacing[2], + marginHorizontal: theme.spacing[1], + paddingHorizontal: theme.spacing[2], + paddingVertical: theme.spacing[2], + borderRadius: theme.borderRadius.md, + }, + rowHighlighted: { + backgroundColor: theme.colors.surface1, + }, + hostBody: { + flex: 1, + minWidth: 0, + gap: 2, + }, + hostHeaderRow: { + flexDirection: "row", + alignItems: "center", + gap: 6, + minWidth: 0, + }, + hostGlyph: { + flexShrink: 0, + }, + hostName: { + flex: 1, + minWidth: 0, + fontSize: theme.fontSize.base, + lineHeight: 18, + color: theme.colors.foreground, + }, + hostNameMuted: { + color: theme.colors.foregroundMuted, + }, + hostTrailing: { + flexDirection: "row", + alignItems: "center", + height: 18, + gap: theme.spacing[2], + flexShrink: 0, + }, + actionSectionDivider: { + height: theme.borderWidth[1], + backgroundColor: theme.colors.border, + marginVertical: theme.spacing[1], + }, + actionRow: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + marginHorizontal: theme.spacing[1], + paddingHorizontal: theme.spacing[2], + paddingVertical: theme.spacing[2], + borderRadius: theme.borderRadius.md, + }, + actionLabel: { + flex: 1, + minWidth: 0, + fontSize: theme.fontSize.base, + lineHeight: 18, + color: theme.colors.foreground, + }, })); diff --git a/packages/app/src/components/icons/tailscale-icon.tsx b/packages/app/src/components/icons/tailscale-icon.tsx new file mode 100644 index 0000000000..ad54f79c9d --- /dev/null +++ b/packages/app/src/components/icons/tailscale-icon.tsx @@ -0,0 +1,32 @@ +import Svg, { Circle } from "react-native-svg"; + +const TAILSCALE_DOTS = [3, 12, 21].flatMap((cy, row) => + [3, 12, 21].map((cx, column) => ({ + cx, + cy, + // The Tailscale mark is a 3x3 dot grid with a solid T (middle row + bottom center). + solid: row === 1 || (row === 2 && column === 1), + })), +); + +export interface TailscaleIconProps { + size?: number; + color?: string; +} + +export function TailscaleIcon({ size = 12, color = "currentColor" }: TailscaleIconProps) { + return ( + + {TAILSCALE_DOTS.map((dot) => ( + + ))} + + ); +} diff --git a/packages/app/src/components/left-sidebar.tsx b/packages/app/src/components/left-sidebar.tsx index 55874b0fb1..bd6d22a88a 100644 --- a/packages/app/src/components/left-sidebar.tsx +++ b/packages/app/src/components/left-sidebar.tsx @@ -388,10 +388,10 @@ function SidebarHostPicker({ includeAddHost onAddHost={onAddHost} showActiveConnection - onOpenHostSettings={onOpenHostSettings} searchable + title={label} desktopPlacement="top-start" - desktopMinWidth={240} + desktopMinWidth={328} addHostTestID="sidebar-host-add" hostOptionTestID={sidebarHostOptionTestID} > diff --git a/packages/app/src/components/ui/combobox.tsx b/packages/app/src/components/ui/combobox.tsx index c6c60b2c46..8d7c024b67 100644 --- a/packages/app/src/components/ui/combobox.tsx +++ b/packages/app/src/components/ui/combobox.tsx @@ -73,6 +73,9 @@ export { buildDesktopFrameStyle } from "./combobox-frame-style"; const IS_WEB = isWeb; const TRAILING_ACTION_DATASET = { comboboxTrailingAction: true }; +const FOOTER_DATASET = { comboboxFooter: true }; +const FOCUSED_COMBOBOX_ACTION_SELECTOR = + '[data-combobox-trailing-action] button, [data-combobox-trailing-action] [role="button"], [data-combobox-footer] button, [data-combobox-footer] [role="button"]'; export type ComboboxOption = ComboboxOptionModel; export type ComboboxDesktopPlacement = "top-start" | "bottom-start"; @@ -402,6 +405,7 @@ export function ComboboxEmpty({ children }: { children: ReactNode }): ReactEleme type RenderOptionFn = NonNullable; interface OptionRowProps { + index: number; option: ComboboxOption; selected: boolean; active: boolean; @@ -409,20 +413,27 @@ interface OptionRowProps { renderOption: RenderOptionFn | undefined; } -function OptionRow({ option, selected, active, onSelect, renderOption }: OptionRowProps) { +function OptionRow({ index, option, selected, active, onSelect, renderOption }: OptionRowProps) { const handlePress = useCallback(() => onSelect(option.id), [onSelect, option.id]); + const optionDataset = useMemo(() => ({ comboboxOptionIndex: String(index) }), [index]); if (renderOption) { - return {renderOption({ option, selected, active, onPress: handlePress })}; + return ( + + {renderOption({ option, selected, active, onPress: handlePress })} + + ); } return ( - + + + ); } @@ -451,6 +462,7 @@ function OptionsList({ {options.map((opt, index) => ( (footer ? {footer} : undefined), + () => + footer ? ( + + {footer} + + ) : undefined, [footer, footerStyle], ); return ( @@ -1341,7 +1359,11 @@ function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null { renderOption={props.renderOption} /> )} - {props.footer ? {props.footer} : null} + {props.footer ? ( + + {props.footer} + + ) : null} @@ -1597,6 +1619,30 @@ export function Combobox({ setActiveIndex, ); + // Keep activeIndex aligned when a keyboard user Tabs onto a specific option button on web. + useEffect(() => { + if (!IS_WEB || !isOpen || isMobile) return; + const handleFocusIn = (event: FocusEvent) => { + const target = event.target; + if (!(target instanceof Element)) return; + const optionEl = target.closest("[data-combobox-option-index]"); + if (!optionEl) return; + const nextIndex = Number.parseInt( + optionEl.getAttribute("data-combobox-option-index") ?? "", + 10, + ); + if ( + Number.isInteger(nextIndex) && + nextIndex >= 0 && + nextIndex < orderedVisibleOptions.length + ) { + setActiveIndex(nextIndex); + } + }; + document.addEventListener("focusin", handleFocusIn); + return () => document.removeEventListener("focusin", handleFocusIn); + }, [isMobile, isOpen, orderedVisibleOptions.length]); + const handleSelect = useCallback( (id: string) => { onSelect(id); diff --git a/packages/app/src/hosts/appearance.test.ts b/packages/app/src/hosts/appearance.test.ts index da7d47e1f7..b8d1141b35 100644 --- a/packages/app/src/hosts/appearance.test.ts +++ b/packages/app/src/hosts/appearance.test.ts @@ -4,6 +4,7 @@ import { defaultHostAppearance, normalizeStoredHostAppearance, resolveHostBadgeDisplay, + resolveHostIcon, selectHostBadges, } from "@/hosts/appearance"; @@ -16,7 +17,7 @@ function host( } describe("normalizeStoredHostAppearance", () => { - it("defaults when the stored registry predates the field or holds junk", () => { + it("defaults without writing an icon field so untouched records stay downgrade-safe", () => { const expected = { color: "none", badgeDisplay: null }; expect(normalizeStoredHostAppearance(undefined)).toEqual(expected); expect(normalizeStoredHostAppearance(null)).toEqual(expected); @@ -24,13 +25,79 @@ describe("normalizeStoredHostAppearance", () => { expect(normalizeStoredHostAppearance({})).toEqual(expected); expect(normalizeStoredHostAppearance({ color: "chartreuse" })).toEqual(expected); expect(normalizeStoredHostAppearance({ badgeDisplay: "loud" })).toEqual(expected); + expect("icon" in defaultHostAppearance()).toBe(false); }); - it("round-trips a value the user actually chose", () => { - expect(normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" })).toEqual({ + it("preserves an unknown stored icon on disk while falling back at render time", () => { + const normalized = normalizeStoredHostAppearance({ + color: "teal", + icon: "spaceship", + badgeDisplay: "icon", + }); + expect(normalized).toEqual({ + color: "teal", + icon: "spaceship", + badgeDisplay: "icon", + }); + expect(resolveHostIcon({ appearance: normalized })).toBe("server"); + expect(resolveHostIcon({ appearance: normalized, detectedMachineKind: "laptop" })).toBe( + "laptop", + ); + }); + + it("keeps icon absent on stored entries that predate host icons", () => { + const normalized = normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" }); + expect(normalized).toEqual({ color: "teal", badgeDisplay: "icon", }); + expect("icon" in normalized).toBe(false); + }); + + it("round-trips a value the user actually chose", () => { + expect( + normalizeStoredHostAppearance({ color: "teal", icon: "laptop", badgeDisplay: "icon" }), + ).toEqual({ + color: "teal", + icon: "laptop", + badgeDisplay: "icon", + }); + }); +}); + +describe("resolveHostIcon", () => { + it("prefers an explicit user icon over daemon auto-detection", () => { + expect( + resolveHostIcon({ + appearance: { color: "none", icon: "workstation", badgeDisplay: null }, + detectedMachineKind: "laptop", + }), + ).toBe("workstation"); + }); + + it("uses the daemon-detected machine kind while the user icon is auto (null)", () => { + expect( + resolveHostIcon({ + appearance: defaultHostAppearance(), + detectedMachineKind: "laptop", + }), + ).toBe("laptop"); + expect( + resolveHostIcon({ + appearance: defaultHostAppearance(), + detectedMachineKind: "container", + }), + ).toBe("container"); + }); + + it("falls back to server when the detected machine kind is absent or unknown", () => { + expect(resolveHostIcon({ appearance: defaultHostAppearance() })).toBe("server"); + expect( + resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: null }), + ).toBe("server"); + expect( + resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: "future-kind" }), + ).toBe("server"); }); }); @@ -50,13 +117,13 @@ describe("resolveHostBadgeDisplay", () => { it("prefers an explicit choice over either default", () => { expect( resolveHostBadgeDisplay({ - appearance: { color: "none", badgeDisplay: "icon" }, + appearance: { color: "none", icon: "server", badgeDisplay: "icon" }, isLocalHost: true, }), ).toBe("icon"); expect( resolveHostBadgeDisplay({ - appearance: { color: "none", badgeDisplay: "hidden" }, + appearance: { color: "none", icon: "server", badgeDisplay: "hidden" }, isLocalHost: false, }), ).toBe("hidden"); @@ -72,7 +139,7 @@ describe("resolveHostBadgeDisplay", () => { ).toBeNull(); expect( resolveHostBadgeDisplay({ - appearance: { color: "none", badgeDisplay: "icon" }, + appearance: { color: "none", icon: "server", badgeDisplay: "icon" }, isLocalHost: false, localHostResolutionPending: true, }), @@ -93,7 +160,7 @@ describe("selectHostBadges", () => { it("omits a host the user hid and keeps its sibling", () => { const badges = selectHostBadges({ hosts: [ - host("alpha", "Alpha", { color: "none", badgeDisplay: "hidden" }), + host("alpha", "Alpha", { color: "none", icon: "server", badgeDisplay: "hidden" }), host("beta", "Beta"), ], localServerId: null, @@ -104,13 +171,14 @@ describe("selectHostBadges", () => { serverId: "beta", label: "Beta", color: "none", + icon: "server", showLabel: true, }); }); it("keeps an icon-only host in the map without its label", () => { const badges = selectHostBadges({ - hosts: [host("alpha", "Alpha", { color: "teal", badgeDisplay: "icon" })], + hosts: [host("alpha", "Alpha", { color: "teal", icon: "mini", badgeDisplay: "icon" })], localServerId: null, enabled: true, }); @@ -118,6 +186,7 @@ describe("selectHostBadges", () => { serverId: "alpha", label: "Alpha", color: "teal", + icon: "mini", showLabel: false, }); }); @@ -150,4 +219,21 @@ describe("selectHostBadges", () => { }); expect(badges.size).toBe(0); }); + + it("applies daemon-detected machine kind for auto icons while respecting explicit overrides", () => { + const badges = selectHostBadges({ + hosts: [ + host("alpha", "Alpha"), + host("beta", "Beta", { color: "sky", icon: "workstation", badgeDisplay: "name" }), + ], + localServerId: null, + detectedMachineKindByServerId: new Map([ + ["alpha", "laptop"], + ["beta", "cloud"], + ]), + enabled: true, + }); + expect(badges.get("alpha")?.icon).toBe("laptop"); + expect(badges.get("beta")?.icon).toBe("workstation"); + }); }); diff --git a/packages/app/src/hosts/appearance.ts b/packages/app/src/hosts/appearance.ts index e51f4410dc..75bdc42a43 100644 --- a/packages/app/src/hosts/appearance.ts +++ b/packages/app/src/hosts/appearance.ts @@ -6,25 +6,69 @@ export type HostColor = "none" | IdentityColorName; export const HOST_COLORS: readonly HostColor[] = ["none", ...IDENTITY_COLOR_NAMES]; +export const HOST_ICONS = [ + "server", + "laptop", + "desktop", + "mini", + "workstation", + "cloud", + "container", + "board", + "terminal", +] as const; + +export type HostIcon = (typeof HOST_ICONS)[number]; + +export const DEFAULT_HOST_ICON: HostIcon = "server"; + +const HOST_ICON_SET = new Set(HOST_ICONS); + +export function normalizeDetectedHostIcon(value: string | null | undefined): HostIcon | null { + const trimmed = value?.trim(); + if (trimmed && HOST_ICON_SET.has(trimmed)) { + return trimmed as HostIcon; + } + return null; +} + export type HostBadgeDisplay = "name" | "icon" | "hidden"; export const HOST_BADGE_DISPLAYS: readonly HostBadgeDisplay[] = ["name", "icon", "hidden"]; /** - * Per-device host presentation. `badgeDisplay` is null while the user has not chosen, - * because the default differs by host (local hides, remote shows) and local-ness is only - * knowable from a desktop-only async query — never at parse time. + * Per-device host presentation. + * - `icon` is omitted while untouched ("Auto") so existing records stay byte-for-byte compatible + * with older builds whose stored appearance schema is strict. An unknown icon string written by + * a newer build is preserved on disk and falls back at render time via `resolveHostIcon`. + * - `badgeDisplay` is null while untouched so runtime defaults apply (hidden for local / name for + * remote) without baking runtime facts at parse time. */ export interface HostAppearance { color: HostColor; + icon?: string; badgeDisplay: HostBadgeDisplay | null; } -export const HostAppearanceSchema: z.ZodType = z.strictObject({ +const StoredHostAppearanceSchema = z.strictObject({ color: z.enum(["none", ...IDENTITY_COLOR_NAMES]), + // Optional loose string on disk so untouched hosts stay readable after a downgrade and an icon + // added by a newer build survives read/write instead of being dropped or overwritten. + icon: z.string().nullable().optional(), badgeDisplay: z.enum(["name", "icon", "hidden"]).nullable(), }); +export const HostAppearanceSchema = StoredHostAppearanceSchema.transform( + (value): HostAppearance => { + const icon = value.icon?.trim(); + return { + color: value.color, + ...(icon ? { icon } : {}), + badgeDisplay: value.badgeDisplay, + }; + }, +); + export function defaultHostAppearance(): HostAppearance { return { color: "none", badgeDisplay: null }; } @@ -34,6 +78,17 @@ export function normalizeStoredHostAppearance(value: unknown): HostAppearance { return result.success ? result.data : defaultHostAppearance(); } +export function resolveHostIcon(input: { + appearance: HostAppearance; + detectedMachineKind?: string | null; +}): HostIcon { + return ( + normalizeDetectedHostIcon(input.appearance.icon) ?? + normalizeDetectedHostIcon(input.detectedMachineKind) ?? + DEFAULT_HOST_ICON + ); +} + export function resolveHostBadgeDisplay(input: { appearance: HostAppearance; isLocalHost: boolean; @@ -52,6 +107,7 @@ export interface HostBadgeModel { serverId: string; label: string; color: HostColor; + icon: HostIcon; showLabel: boolean; } @@ -66,6 +122,7 @@ export function selectHostBadges(input: { hosts: readonly HostAppearanceSource[]; localServerId: string | null; localHostResolutionPending?: boolean; + detectedMachineKindByServerId?: ReadonlyMap; enabled: boolean; }): ReadonlyMap { const badges = new Map(); @@ -85,6 +142,10 @@ export function selectHostBadges(input: { serverId: host.serverId, label: host.label.trim() || host.serverId, color: host.appearance.color, + icon: resolveHostIcon({ + appearance: host.appearance, + detectedMachineKind: input.detectedMachineKindByServerId?.get(host.serverId) ?? null, + }), showLabel: display === "name", }); } diff --git a/packages/app/src/hosts/connection-display.test.ts b/packages/app/src/hosts/connection-display.test.ts new file mode 100644 index 0000000000..410b169afd --- /dev/null +++ b/packages/app/src/hosts/connection-display.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, it } from "vitest"; +import { + describeActiveConnection, + describeHostConnection, + formatConnectionEndpoint, + isTailscaleEndpoint, +} from "./connection-display"; + +describe("isTailscaleEndpoint", () => { + it("recognizes MagicDNS .ts.net hostnames with or without ports", () => { + expect(isTailscaleEndpoint("mac-mini.tail123.ts.net:6767")).toBe(true); + expect(isTailscaleEndpoint("Mac-Mini.Tail123.TS.NET:443")).toBe(true); + expect(isTailscaleEndpoint("devbox.tailnet.ts.net")).toBe(true); + expect(isTailscaleEndpoint(".ts.net")).toBe(false); + }); + + it("recognizes Tailscale IPv4 CGNAT (100.64.0.0/10) and IPv6 ULA addresses", () => { + expect(isTailscaleEndpoint("100.64.0.1:6767")).toBe(true); + expect(isTailscaleEndpoint("100.100.42.9:6767")).toBe(true); + expect(isTailscaleEndpoint("100.127.255.254:6767")).toBe(true); + expect(isTailscaleEndpoint("100.63.255.255:6767")).toBe(false); + expect(isTailscaleEndpoint("100.128.0.1:6767")).toBe(false); + expect(isTailscaleEndpoint("[fd7a:115c:a1e0::1]:6767")).toBe(true); + }); + + it("does not misclassify LAN, localhost, or ordinary domains", () => { + expect(isTailscaleEndpoint("localhost:6767")).toBe(false); + expect(isTailscaleEndpoint("127.0.0.1:6767")).toBe(false); + expect(isTailscaleEndpoint("192.168.1.25:6767")).toBe(false); + expect(isTailscaleEndpoint("relay.paseo.sh:443")).toBe(false); + expect(isTailscaleEndpoint("not-ts.net.example.com:6767")).toBe(false); + }); +}); + +describe("describeActiveConnection", () => { + it("describes local socket and pipe connections without exposing paths", () => { + expect( + describeActiveConnection({ + type: "directSocket", + endpoint: "/tmp/paseo.sock", + display: "socket", + }), + ).toEqual({ kind: "local" }); + expect( + describeActiveConnection({ + type: "directPipe", + endpoint: "\\\\.\\pipe\\paseo", + display: "pipe", + }), + ).toEqual({ kind: "local" }); + }); + + it("describes loopback TCP on the local host as local, and remote loopback as direct", () => { + const loopback = { + type: "directTcp", + endpoint: "localhost:6767", + display: "localhost:6767", + } as const; + expect(describeActiveConnection(loopback, { isLocalHost: true })).toEqual({ kind: "local" }); + expect(describeActiveConnection(loopback, { isLocalHost: false })).toEqual({ + kind: "direct", + endpoint: "localhost:6767", + }); + }); + + it("strips standard web ports on relay, tailscale, and direct connections", () => { + expect( + describeActiveConnection({ type: "relay", endpoint: "relay.paseo.sh:443", display: "relay" }), + ).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" }); + expect( + describeActiveConnection({ + type: "directTcp", + endpoint: "mac-mini.tail123.ts.net:6767", + display: "mac-mini.tail123.ts.net:6767", + }), + ).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" }); + expect( + describeActiveConnection({ + type: "directTcp", + endpoint: "devbox.example.com:443", + display: "devbox.example.com:443", + }), + ).toEqual({ kind: "direct", endpoint: "devbox.example.com" }); + }); + + it("preserves SSH and routed targets", () => { + expect( + describeActiveConnection({ + type: "remoteSsh", + endpoint: "mo@workstation", + display: "mo@workstation", + }), + ).toEqual({ kind: "ssh", endpoint: "mo@workstation" }); + expect( + describeActiveConnection({ + type: "routed", + endpoint: "srv_origin", + display: "via srv_origin", + }), + ).toEqual({ kind: "routed", endpoint: "srv_origin" }); + }); + + it("strips default HTTP/HTTPS ports only", () => { + expect(formatConnectionEndpoint("relay.paseo.sh:443")).toBe("relay.paseo.sh"); + expect(formatConnectionEndpoint("example.com:80")).toBe("example.com"); + expect(formatConnectionEndpoint("127.0.0.1:6767")).toBe("127.0.0.1:6767"); + }); + + it("describes configured host connections before an active connection is online", () => { + expect( + describeHostConnection({ + id: "direct:mac-mini.tail123.ts.net:6767", + type: "directTcp", + endpoint: "mac-mini.tail123.ts.net:6767", + }), + ).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" }); + expect( + describeHostConnection({ + id: "relay:wss:relay.paseo.sh:443", + type: "relay", + relayEndpoint: "relay.paseo.sh:443", + useTls: true, + daemonPublicKeyB64: "key", + }), + ).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" }); + expect( + describeHostConnection({ + id: "ssh:mo%40workstation::", + type: "remoteSsh", + host: "mo@workstation", + }), + ).toEqual({ kind: "ssh", endpoint: "mo@workstation" }); + }); +}); diff --git a/packages/app/src/hosts/connection-display.ts b/packages/app/src/hosts/connection-display.ts new file mode 100644 index 0000000000..bdbae87b3a --- /dev/null +++ b/packages/app/src/hosts/connection-display.ts @@ -0,0 +1,120 @@ +import type { ActiveConnection } from "@/runtime/host-runtime"; +import type { HostConnection } from "@/types/host-connection"; + +export type HostConnectionKind = "local" | "relay" | "tailscale" | "ssh" | "direct" | "routed"; + +export interface HostConnectionDisplay { + kind: HostConnectionKind; + /** Address shown beside the connection kind. Omitted for local transports. */ + endpoint?: string; +} + +// Standard secure/plain web ports carry no information in the host display, so +// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept. +export function formatConnectionEndpoint(endpoint: string): string { + return endpoint.replace(/:(?:443|80)$/, ""); +} + +function extractEndpointHost(endpoint: string): string { + const trimmed = endpoint.trim().toLowerCase(); + if (!trimmed) return ""; + + const withoutScheme = trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\//, ""); + const authority = withoutScheme.split("/")[0] ?? ""; + const hostPort = authority.includes("@") + ? authority.slice(authority.lastIndexOf("@") + 1) + : authority; + + if (hostPort.startsWith("[")) { + const closeBracket = hostPort.indexOf("]"); + return closeBracket > 1 ? hostPort.slice(1, closeBracket) : hostPort; + } + + const firstColon = hostPort.indexOf(":"); + const lastColon = hostPort.lastIndexOf(":"); + if (firstColon !== -1 && firstColon === lastColon) { + return hostPort.slice(0, firstColon); + } + return hostPort; +} + +function isTailscaleIpv4(host: string): boolean { + const parts = host.split("."); + if (parts.length !== 4) return false; + const octets = parts.map((part) => (/^\d+$/.test(part) ? Number(part) : Number.NaN)); + if (octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) { + return false; + } + // Tailscale assigns addresses from the RFC 6598 CGNAT range 100.64.0.0/10. + return octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127; +} + +function isTailscaleIpv6(host: string): boolean { + return host.startsWith("fd7a:115c:a1e0:"); +} + +export function isTailscaleEndpoint(endpoint: string): boolean { + const host = extractEndpointHost(endpoint); + if (!host) return false; + if (host.endsWith(".ts.net") && host.length > ".ts.net".length) { + return true; + } + return isTailscaleIpv4(host) || isTailscaleIpv6(host); +} + +export function isLoopbackEndpoint(endpoint: string): boolean { + const host = extractEndpointHost(endpoint); + return host === "localhost" || host === "127.0.0.1" || host === "::1"; +} + +export function describeActiveConnection( + connection: ActiveConnection, + options?: { isLocalHost?: boolean }, +): HostConnectionDisplay { + switch (connection.type) { + case "directSocket": + case "directPipe": + return { kind: "local" }; + case "relay": + return { kind: "relay", endpoint: formatConnectionEndpoint(connection.endpoint) }; + case "remoteSsh": + return { kind: "ssh", endpoint: connection.endpoint }; + case "routed": + return { kind: "routed", endpoint: connection.endpoint }; + case "directTcp": { + if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) { + return { kind: "local" }; + } + if (isTailscaleEndpoint(connection.endpoint)) { + return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) }; + } + return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) }; + } + } +} + +export function describeHostConnection( + connection: HostConnection, + options?: { isLocalHost?: boolean }, +): HostConnectionDisplay { + switch (connection.type) { + case "directSocket": + case "directPipe": + return { kind: "local" }; + case "relay": + return { kind: "relay", endpoint: formatConnectionEndpoint(connection.relayEndpoint) }; + case "remoteSsh": + return { kind: "ssh", endpoint: connection.host }; + case "routed": + return { kind: "routed", endpoint: connection.originServerId }; + case "directTcp": { + if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) { + return { kind: "local" }; + } + if (isTailscaleEndpoint(connection.endpoint)) { + return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) }; + } + return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) }; + } + } +} diff --git a/packages/app/src/hosts/host-badge.tsx b/packages/app/src/hosts/host-badge.tsx index d35a4324f5..9b253b39ad 100644 --- a/packages/app/src/hosts/host-badge.tsx +++ b/packages/app/src/hosts/host-badge.tsx @@ -1,9 +1,8 @@ import { Text, View } from "react-native"; -import { StyleSheet, withUnistyles } from "react-native-unistyles"; -import { Server } from "lucide-react-native"; -import { HOST_COLORS, type HostBadgeModel, type HostColor } from "@/hosts/appearance"; +import { StyleSheet } from "react-native-unistyles"; +import { type HostBadgeModel, type HostColor } from "@/hosts/appearance"; +import { HostIconGlyph } from "@/hosts/host-icon-glyph"; import { identityForeground } from "@/styles/identity-colors"; -import type { Theme } from "@/styles/theme"; /** * The glyph size the badge draws at. Rows that place the badge alongside their own glyphs @@ -11,30 +10,9 @@ import type { Theme } from "@/styles/theme"; */ export const HOST_BADGE_ICON_SIZE = 12; -const ThemedServer = withUnistyles(Server); - -const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); - -// One stable mapping per host color for the life of the module — a fresh `uniProps` identity -// on every render makes withUnistyles re-subscribe each pass. The scheme is read inside the -// mapping rather than baked in, so a theme change repaints the glyph without a React render. -// -// Glyph and label share one color, so a badge reads as one object rather than a colored icon -// with an unrelated grey word beside it. -const HOST_ICON_MAPPINGS: Record { color: string }> = (() => { - const byColor = {} as Record { color: string }>; - for (const color of HOST_COLORS) { - byColor[color] = - color === "none" - ? mutedMapping - : (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) }); - } - return byColor; -})(); - /** - * Which machine something lives on, drawn the same way everywhere it appears: a server glyph - * and, when the host is configured to show one, its name — both in the host's identity color. + * Which machine something lives on, drawn the same way everywhere it appears: the host's device + * glyph and, when the host is configured to show one, its name — both in the host's identity color. * * A hostname is the least interesting thing on any line that carries it and the only one whose * length nobody chose, so the badge yields space before its neighbours rather than alongside @@ -47,10 +25,11 @@ export function HostBadge({ badge }: { badge: HostBadgeModel }) { testID={`host-badge-${badge.serverId}`} accessibilityLabel={badge.label} > - {badge.showLabel ? ( diff --git a/packages/app/src/hosts/host-chooser.tsx b/packages/app/src/hosts/host-chooser.tsx index eb6fdea5a0..8315d0f5fe 100644 --- a/packages/app/src/hosts/host-chooser.tsx +++ b/packages/app/src/hosts/host-chooser.tsx @@ -7,14 +7,16 @@ import { EditingTextInput as TextInput, type EditingTextInputHandle, } from "@/components/ui/text-input"; -import { Server } from "lucide-react-native"; import { create } from "zustand"; import { StyleSheet, useUnistyles } from "react-native-unistyles"; -import { HostStatusDotSlot } from "@/components/hosts/host-picker"; +import { HostStatusDot } from "@/components/host-status-dot"; import { isWeb } from "@/constants/platform"; import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon"; +import { resolveHostIcon } from "@/hosts/appearance"; +import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon"; import { OverlayLayerProvider, useGlobalOverlayLayer } from "@/lib/overlay-root"; -import { useHosts } from "@/runtime/host-runtime"; +import { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime"; +import { useSessionStore } from "@/stores/session-store"; import { orderHostsLocalFirst, type HostProfile } from "@/types/host-connection"; type HostFilter = (host: HostProfile) => boolean; @@ -101,36 +103,52 @@ function HostChooserRow({ active: boolean; onChooseHost: (serverId: string) => void; }) { - const { theme } = useUnistyles(); + const detectedMachineKind = useSessionStore( + (state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null, + ); + const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind }); + const [hovered, setHovered] = useState(false); + const handlePointerEnter = useCallback(() => setHovered(true), []); + const handlePointerLeave = useCallback(() => setHovered(false), []); const handlePress = useCallback(() => onChooseHost(host.serverId), [host.serverId, onChooseHost]); const rowStyle = useCallback( - ({ hovered = false, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [ + ({ pressed }: PressableStateCallbackType) => [ styles.row, (active || hovered || pressed) && styles.rowActive, ], - [active], + [active, hovered], ); return ( - - - - - - - {host.label} - - - {host.serverId} - - - - + + + + + + + + + + {host.label} + + + + + + + + + ); } @@ -161,6 +179,7 @@ export function HostChooserModal() { useEffect(() => { if (!request) return; + getHostRuntimeStore().refreshActiveLatencies(request.serverIds); inputRef.current?.replaceText(""); setQuery(""); setActiveIndex(0); @@ -328,7 +347,7 @@ const styles = StyleSheet.create((theme) => ({ }, row: { flexDirection: "row", - alignItems: "center", + alignItems: "flex-start", gap: theme.spacing[3], minHeight: 56, paddingHorizontal: theme.spacing[4], @@ -337,19 +356,39 @@ const styles = StyleSheet.create((theme) => ({ rowActive: { backgroundColor: theme.colors.surface1, }, + rowTrailing: { + flexDirection: "row", + alignItems: "center", + height: 20, + flexShrink: 0, + }, rowIconSlot: { - width: 18, + width: 16, + height: 20, alignItems: "center", justifyContent: "center", + flexShrink: 0, }, rowText: { flex: 1, minWidth: 0, gap: theme.spacing[1], }, + rowHeader: { + flexDirection: "row", + alignItems: "center", + gap: 6, + minWidth: 0, + }, + rowGlyph: { + flexShrink: 0, + }, rowTitle: { + flex: 1, + minWidth: 0, color: theme.colors.foreground, fontSize: theme.fontSize.base, + lineHeight: 20, }, rowSubtitle: { color: theme.colors.foregroundMuted, diff --git a/packages/app/src/hosts/host-icon-glyph.tsx b/packages/app/src/hosts/host-icon-glyph.tsx new file mode 100644 index 0000000000..fa5a2f1458 --- /dev/null +++ b/packages/app/src/hosts/host-icon-glyph.tsx @@ -0,0 +1,77 @@ +import type { ReactElement } from "react"; +import type { StyleProp, ViewStyle } from "react-native"; +import { + Cloud, + Computer, + Container, + Cpu, + Laptop, + Monitor, + PcCase, + Server, + Terminal, +} from "lucide-react-native"; +import { withUnistyles } from "react-native-unistyles"; +import { DEFAULT_HOST_ICON, HOST_COLORS, type HostColor, type HostIcon } from "@/hosts/appearance"; +import { identityForeground } from "@/styles/identity-colors"; +import type { Theme } from "@/styles/theme"; + +const ThemedServer = withUnistyles(Server); +const ThemedLaptop = withUnistyles(Laptop); +const ThemedMonitor = withUnistyles(Monitor); +const ThemedComputer = withUnistyles(Computer); +const ThemedPcCase = withUnistyles(PcCase); +const ThemedCloud = withUnistyles(Cloud); +const ThemedContainer = withUnistyles(Container); +const ThemedCpu = withUnistyles(Cpu); +const ThemedTerminal = withUnistyles(Terminal); + +const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); + +// One stable uniProps mapping per host color for the life of the module — a fresh identity on +// every render makes withUnistyles re-subscribe each pass. Reading `theme.colorScheme` inside the +// mapping keeps theme switches off React's render path. +const HOST_ICON_MAPPINGS: Record { color: string }> = (() => { + const byColor = {} as Record { color: string }>; + for (const color of HOST_COLORS) { + byColor[color] = + color === "none" + ? mutedMapping + : (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) }); + } + return byColor; +})(); + +export function HostIconGlyph({ + icon = DEFAULT_HOST_ICON, + color = "none", + size = 16, + style, +}: { + icon?: HostIcon; + color?: HostColor; + size?: number; + style?: StyleProp; +}): ReactElement { + const uniProps = HOST_ICON_MAPPINGS[color]; + switch (icon) { + case "laptop": + return ; + case "desktop": + return ; + case "mini": + return ; + case "workstation": + return ; + case "cloud": + return ; + case "container": + return ; + case "board": + return ; + case "terminal": + return ; + case "server": + return ; + } +} diff --git a/packages/app/src/hosts/host-icon.tsx b/packages/app/src/hosts/host-icon.tsx new file mode 100644 index 0000000000..d335e7adf1 --- /dev/null +++ b/packages/app/src/hosts/host-icon.tsx @@ -0,0 +1,215 @@ +import { useMemo, type ReactElement } from "react"; +import { useTranslation } from "react-i18next"; +import { Text, View } from "react-native"; +import { Globe, Monitor, Network, Terminal, Waypoints } from "lucide-react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { TailscaleIcon } from "@/components/icons/tailscale-icon"; +import { + describeActiveConnection, + describeHostConnection, + type HostConnectionKind, +} from "@/hosts/connection-display"; +import { HostIconGlyph } from "@/hosts/host-icon-glyph"; +import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon"; +import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime"; +import type { Theme } from "@/styles/theme"; +import type { HostProfile } from "@/types/host-connection"; +import { formatLatency } from "@/utils/latency"; + +export { HostIconGlyph }; + +const CONNECTION_GLYPH_SIZE = 11; + +const ThemedMonitor = withUnistyles(Monitor); +const ThemedTerminal = withUnistyles(Terminal); +const ThemedGlobe = withUnistyles(Globe); +const ThemedNetwork = withUnistyles(Network); +const ThemedWaypoints = withUnistyles(Waypoints); +const ThemedTailscale = withUnistyles(TailscaleIcon); + +const extraMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundExtraMuted }); + +function ConnectionKindGlyph({ kind }: { kind: HostConnectionKind }): ReactElement { + switch (kind) { + case "local": + return ( + + ); + case "relay": + return ( + + ); + case "tailscale": + return ; + case "ssh": + return ( + + ); + case "routed": + return ( + + ); + case "direct": + return ( + + ); + } +} + +function resolvePreferredConnection(host: HostProfile | undefined) { + if (!host || host.connections.length === 0) return null; + if (host.preferredConnectionId) { + const preferred = host.connections.find( + (connection) => connection.id === host.preferredConnectionId, + ); + if (preferred) return preferred; + } + return host.connections[0] ?? null; +} + +export function HostConnectionLine({ serverId }: { serverId: string }): ReactElement | null { + const { t } = useTranslation(); + const snapshot = useHostRuntimeSnapshot(serverId); + const localServerId = useLocalDaemonServerId(); + const hosts = useHosts(); + const activeConnection = snapshot?.activeConnection ?? null; + const hostProfile = useMemo( + () => hosts.find((candidate) => candidate.serverId === serverId), + [hosts, serverId], + ); + const fallbackConnection = useMemo( + () => (activeConnection ? null : resolvePreferredConnection(hostProfile)), + [activeConnection, hostProfile], + ); + + const described = useMemo(() => { + const options = { isLocalHost: serverId === localServerId }; + if (activeConnection) { + return describeActiveConnection(activeConnection, options); + } + if (fallbackConnection) { + return describeHostConnection(fallbackConnection, options); + } + return null; + }, [activeConnection, fallbackConnection, localServerId, serverId]); + + if (!described) { + return null; + } + + const endpoint = + described.kind === "routed" && described.endpoint + ? (hosts.find((host) => host.serverId === described.endpoint)?.label ?? described.endpoint) + : described.endpoint; + + return ( + + + + + + {t(`settings.host.connectionKinds.${described.kind}`)} + + {endpoint ? ( + + {endpoint} + + ) : null} + + ); +} + +export function HostLatencyLabel({ serverId }: { serverId: string }): ReactElement | null { + const { t } = useTranslation(); + const snapshot = useHostRuntimeSnapshot(serverId); + const status = snapshot?.connectionStatus; + const activeConnectionId = snapshot?.activeConnectionId; + const activeProbe = activeConnectionId + ? snapshot?.probeByConnectionId.get(activeConnectionId) + : undefined; + const latencyMs = + status === "online" && activeProbe?.status === "available" ? activeProbe.latencyMs : null; + + if (latencyMs !== null) { + return ( + + {formatLatency(latencyMs)} + + ); + } + + if (status === "offline" || status === "error") { + return ( + + {t("common.connectionStatus.offline")} + + ); + } + + return null; +} + +const styles = StyleSheet.create((theme) => ({ + connectionRow: { + flexDirection: "row", + alignItems: "center", + gap: 6, + minWidth: 0, + }, + // Matches the 14px host icon width on the row above so connection text aligns on the same rail. + linkIconSlot: { + width: 14, + alignItems: "center", + justifyContent: "center", + flexShrink: 0, + }, + linkIcon: { + flexShrink: 0, + }, + connectionKind: { + fontSize: theme.fontSize.sm, + lineHeight: 16, + color: theme.colors.foregroundMuted, + flexShrink: 0, + }, + connectionEndpoint: { + fontSize: theme.fontSize.sm, + lineHeight: 16, + color: theme.colors.foregroundExtraMuted, + flexShrink: 1, + minWidth: 0, + }, + latency: { + fontSize: theme.fontSize.sm, + lineHeight: 16, + color: theme.colors.foregroundMuted, + fontVariant: ["tabular-nums"], + flexShrink: 0, + }, + statusText: { + fontSize: theme.fontSize.sm, + lineHeight: 16, + color: theme.colors.foregroundExtraMuted, + flexShrink: 0, + }, +})); diff --git a/packages/app/src/hosts/use-host-badges.ts b/packages/app/src/hosts/use-host-badges.ts index d401d3eef9..80d672e815 100644 --- a/packages/app/src/hosts/use-host-badges.ts +++ b/packages/app/src/hosts/use-host-badges.ts @@ -1,11 +1,13 @@ import { useMemo } from "react"; +import { useShallow } from "zustand/react/shallow"; import { useHosts } from "@/runtime/host-runtime"; import { useLocalDaemonServerId, useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon"; import { selectHostBadges, type HostBadgeModel } from "@/hosts/appearance"; +import { useSessionStore } from "@/stores/session-store"; /** - * Every host's badge, resolved from the three things that decide one: the host registry, which - * host is local, and each host's own appearance. `enabled` is the caller's own "off" — a surface + * Every host's badge, resolved from the host registry, local-host detection, daemon-reported + * machine kind, and each host's own appearance. `enabled` is the caller's own "off" — a surface * that has its own reason to hide badges passes false rather than filtering the result, so the * per-host setting stays the only thing that decides name vs icon vs hidden. */ @@ -17,14 +19,25 @@ export function useHostBadges({ const hosts = useHosts(); const localServerId = useLocalDaemonServerId(); const localDaemon = useLocalDaemonServerIdState(); - return useMemo( - () => - selectHostBadges({ - hosts, - localServerId, - localHostResolutionPending: localDaemon.status !== "resolved", - enabled, - }), - [hosts, localDaemon.status, localServerId, enabled], + const detectedMachineKinds = useSessionStore( + useShallow((state) => { + const result: Record = {}; + for (const host of hosts) { + result[host.serverId] = state.sessions[host.serverId]?.serverInfo?.machineKind ?? null; + } + return result; + }), ); + return useMemo(() => { + const detectedMachineKindByServerId = new Map( + Object.entries(detectedMachineKinds), + ); + return selectHostBadges({ + hosts, + localServerId, + localHostResolutionPending: localDaemon.status !== "resolved", + detectedMachineKindByServerId, + enabled, + }); + }, [hosts, localDaemon.status, localServerId, detectedMachineKinds, enabled]); } diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index cf35f82939..0ef64842e6 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2841,6 +2841,23 @@ export const ar: TranslationResources = { name: { label: "الاسم", }, + icon: { + label: "الأيقونة", + accessibilityLabel: "الأيقونة، {{value}}", + auto: "تلقائي", + autoDetected: "تلقائي ({{icon}})", + options: { + server: "خادم", + laptop: "حاسوب محمول", + desktop: "حاسوب مكتبي", + mini: "حاسوب مصغّر", + workstation: "محطة عمل", + cloud: "سحابي", + container: "حاوية", + board: "حاسوب أحادي اللوحة", + terminal: "طرفية", + }, + }, color: { label: "اللون", accessibilityLabel: "اللون، {{value}}", @@ -2877,6 +2894,14 @@ export const ar: TranslationResources = { local: "محلي", remoteSsh: "SSH عن بُعد", }, + connectionKinds: { + local: "محلي", + relay: "تتابع", + tailscale: "Tailscale", + ssh: "SSH", + direct: "مباشر", + routed: "عبر", + }, connections: { title: "اتصالات", removeTitle: "إزالة الاتصال", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index eee3ac578a..4b89156f1b 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2936,6 +2936,23 @@ export const en = { name: { label: "Name", }, + icon: { + label: "Icon", + accessibilityLabel: "Icon, {{value}}", + auto: "Auto", + autoDetected: "Auto ({{icon}})", + options: { + server: "Server", + laptop: "Laptop", + desktop: "Desktop", + mini: "Mini", + workstation: "Workstation", + cloud: "Cloud", + container: "Container", + board: "Single-board PC", + terminal: "Terminal", + }, + }, color: { label: "Color", accessibilityLabel: "Color, {{value}}", @@ -2972,6 +2989,14 @@ export const en = { local: "Local", remoteSsh: "Remote SSH", }, + connectionKinds: { + local: "Local", + relay: "Relay", + tailscale: "Tailscale", + ssh: "SSH", + direct: "Direct", + routed: "Via", + }, connections: { title: "Connections", removeTitle: "Remove connection", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 630119dfac..f22c1a8a54 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2865,6 +2865,23 @@ export const es: TranslationResources = { name: { label: "Nombre", }, + icon: { + label: "Icono", + accessibilityLabel: "Icono, {{value}}", + auto: "Automático", + autoDetected: "Automático ({{icon}})", + options: { + server: "Servidor", + laptop: "Portátil", + desktop: "Escritorio", + mini: "Mini", + workstation: "Estación de trabajo", + cloud: "Nube", + container: "Contenedor", + board: "PC de placa única", + terminal: "Terminal", + }, + }, color: { label: "Color", accessibilityLabel: "Color, {{value}}", @@ -2901,6 +2918,14 @@ export const es: TranslationResources = { local: "Local", remoteSsh: "SSH remoto", }, + connectionKinds: { + local: "Local", + relay: "Relé", + tailscale: "Tailscale", + ssh: "SSH", + direct: "Directo", + routed: "Vía", + }, connections: { title: "Conexiones", removeTitle: "Quitar conexión", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index c96a46dbc5..acad2fb893 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2867,6 +2867,23 @@ export const fr: TranslationResources = { name: { label: "Nom", }, + icon: { + label: "Icône", + accessibilityLabel: "Icône, {{value}}", + auto: "Auto", + autoDetected: "Auto ({{icon}})", + options: { + server: "Serveur", + laptop: "Portable", + desktop: "Bureau", + mini: "Mini", + workstation: "Station de travail", + cloud: "Cloud", + container: "Conteneur", + board: "Ordinateur monocarte", + terminal: "Terminal", + }, + }, color: { label: "Couleur", accessibilityLabel: "Couleur, {{value}}", @@ -2903,6 +2920,14 @@ export const fr: TranslationResources = { local: "Local", remoteSsh: "SSH distant", }, + connectionKinds: { + local: "Local", + relay: "Relais", + tailscale: "Tailscale", + ssh: "SSH", + direct: "Direct", + routed: "Via", + }, connections: { title: "Connexions", removeTitle: "Supprimer la connexion", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 51c3446819..3ef0ae9fd0 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2833,6 +2833,23 @@ export const ja: TranslationResources = { name: { label: "名前", }, + icon: { + label: "アイコン", + accessibilityLabel: "アイコン、{{value}}", + auto: "自動", + autoDetected: "自動 ({{icon}})", + options: { + server: "サーバー", + laptop: "ノート PC", + desktop: "デスクトップ", + mini: "ミニ PC", + workstation: "ワークステーション", + cloud: "クラウド", + container: "コンテナ", + board: "シングルボード PC", + terminal: "ターミナル", + }, + }, color: { label: "色", accessibilityLabel: "色、{{value}}", @@ -2869,6 +2886,14 @@ export const ja: TranslationResources = { local: "ローカル", remoteSsh: "リモート SSH", }, + connectionKinds: { + local: "ローカル", + relay: "リレー", + tailscale: "Tailscale", + ssh: "SSH", + direct: "ダイレクト", + routed: "経由", + }, connections: { title: "接続", removeTitle: "接続を削除", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 7b4a2e59c6..17f4b60288 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -2819,6 +2819,23 @@ export const ko: TranslationResources = { name: { label: "이름", }, + icon: { + label: "아이콘", + accessibilityLabel: "아이콘, {{value}}", + auto: "자동", + autoDetected: "자동 ({{icon}})", + options: { + server: "서버", + laptop: "노트북", + desktop: "데스크톱", + mini: "미니", + workstation: "워크스테이션", + cloud: "클라우드", + container: "컨테이너", + board: "싱글보드 PC", + terminal: "터미널", + }, + }, color: { label: "색상", accessibilityLabel: "색상, {{value}}", @@ -2855,6 +2872,14 @@ export const ko: TranslationResources = { local: "로컬", remoteSsh: "원격 SSH", }, + connectionKinds: { + local: "로컬", + relay: "릴레이", + tailscale: "Tailscale", + ssh: "SSH", + direct: "직접 연결", + routed: "경유", + }, connections: { title: "연결", removeTitle: "연결 제거", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index fce0073077..3c6b05aac8 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2846,6 +2846,23 @@ export const ptBR: TranslationResources = { name: { label: "Nome", }, + icon: { + label: "Ícone", + accessibilityLabel: "Ícone, {{value}}", + auto: "Automático", + autoDetected: "Automático ({{icon}})", + options: { + server: "Servidor", + laptop: "Notebook", + desktop: "Desktop", + mini: "Mini", + workstation: "Estação de trabalho", + cloud: "Nuvem", + container: "Contêiner", + board: "PC de placa única", + terminal: "Terminal", + }, + }, color: { label: "Cor", accessibilityLabel: "Cor, {{value}}", @@ -2882,6 +2899,14 @@ export const ptBR: TranslationResources = { local: "Local", remoteSsh: "SSH remoto", }, + connectionKinds: { + local: "Local", + relay: "Relay", + tailscale: "Tailscale", + ssh: "SSH", + direct: "Direto", + routed: "Via", + }, connections: { title: "Conexões", removeTitle: "Remover conexão", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 37a5392f3d..d01777330c 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2854,6 +2854,23 @@ export const ru: TranslationResources = { name: { label: "Имя", }, + icon: { + label: "Значок", + accessibilityLabel: "Значок, {{value}}", + auto: "Авто", + autoDetected: "Авто ({{icon}})", + options: { + server: "Сервер", + laptop: "Ноутбук", + desktop: "Компьютер", + mini: "Мини-ПК", + workstation: "Рабочая станция", + cloud: "Облако", + container: "Контейнер", + board: "Одноплатный ПК", + terminal: "Терминал", + }, + }, color: { label: "Цвет", accessibilityLabel: "Цвет, {{value}}", @@ -2890,6 +2907,14 @@ export const ru: TranslationResources = { local: "Локальный", remoteSsh: "Удалённый SSH", }, + connectionKinds: { + local: "Локальный", + relay: "Ретранслятор", + tailscale: "Tailscale", + ssh: "SSH", + direct: "Прямой", + routed: "Через", + }, connections: { title: "Подключения", removeTitle: "Удалить подключение", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 62a67ad4ae..dc69a966de 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -2775,6 +2775,23 @@ export const zhCN: TranslationResources = { name: { label: "名称", }, + icon: { + label: "图标", + accessibilityLabel: "图标,{{value}}", + auto: "自动", + autoDetected: "自动 ({{icon}})", + options: { + server: "服务器", + laptop: "笔记本电脑", + desktop: "台式机", + mini: "迷你主机", + workstation: "工作站", + cloud: "云端", + container: "容器", + board: "单板机", + terminal: "终端", + }, + }, color: { label: "颜色", accessibilityLabel: "颜色,{{value}}", @@ -2811,6 +2828,14 @@ export const zhCN: TranslationResources = { local: "本地", remoteSsh: "远程 SSH", }, + connectionKinds: { + local: "本地", + relay: "中继", + tailscale: "Tailscale", + ssh: "SSH", + direct: "直连", + routed: "经由", + }, connections: { title: "连接", removeTitle: "移除连接", diff --git a/packages/app/src/runtime/host-runtime.test.ts b/packages/app/src/runtime/host-runtime.test.ts index 55c7479d08..39da25fde0 100644 --- a/packages/app/src/runtime/host-runtime.test.ts +++ b/packages/app/src/runtime/host-runtime.test.ts @@ -1114,6 +1114,106 @@ describe("HostRuntimeController", () => { expect(activeClient.latencyMeasurements()).toEqual([]); }); + it("measures active latency on demand when an online host has no sample yet", async () => { + useHostRuntimeClock(); + const initialClient = new FakeDaemonClient(); + initialClient.setConnectionState({ status: "connected" }); + initialClient.ping = async () => ({ rttMs: 14 }); + const controller = new HostRuntimeController({ + host: makeHost({ + connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }], + preferredConnectionId: "direct:lan:6767", + }), + deps: makeDeps({ "direct:lan:6767": 14 }, []), + }); + + await controller.start({ + autoProbe: false, + initialConnection: { + connectionId: "direct:lan:6767", + existingClient: initialClient as unknown as DaemonClient, + }, + }); + expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({ + status: "pending", + latencyMs: null, + }); + + await controller.refreshActiveLatency(); + + expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({ + status: "available", + latencyMs: 14, + }); + }); + + it("keeps an on-demand active latency sample when a slower probe on another connection finishes", async () => { + useHostRuntimeClock(); + const initialClient = new FakeDaemonClient(); + initialClient.setConnectionState({ status: "connected" }); + initialClient.ping = async () => ({ rttMs: 14 }); + const relayProbeStarted = createDeferred(); + const slowRelayProbe = createDeferred<{ + client: DaemonClient; + serverId: string; + hostname: string | null; + }>(); + const relayClient = new FakeDaemonClient(); + relayClient.setConnectionState({ status: "connected" }); + relayClient.ping = async () => ({ rttMs: 90 }); + + const controller = new HostRuntimeController({ + host: makeHost(), + deps: { + ...makeDeps({}, []), + connectToDaemon: async ({ host, connection }) => { + if (connection.id === "relay:relay.paseo.sh:443") { + relayProbeStarted.resolve(); + return slowRelayProbe.promise; + } + return { + client: initialClient as unknown as DaemonClient, + serverId: host.serverId, + hostname: null, + }; + }, + }, + }); + + // Startup runs the first probe cycle immediately; wait until the slower relay probe is in + // flight, then measure active latency on demand before the relay probe resolves. + const startPromise = controller.start({ + autoProbe: false, + initialConnection: { + connectionId: "direct:lan:6767", + existingClient: initialClient as unknown as DaemonClient, + }, + }); + await relayProbeStarted.promise; + + await controller.refreshActiveLatency(); + expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({ + status: "available", + latencyMs: 14, + }); + + slowRelayProbe.resolve({ + client: relayClient as unknown as DaemonClient, + serverId: "srv_test", + hostname: null, + }); + await startPromise; + + expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({ + status: "available", + latencyMs: 14, + }); + expect(controller.getSnapshot().probeByConnectionId.get("relay:relay.paseo.sh:443")).toEqual({ + status: "available", + latencyMs: 90, + }); + }); + it.each([12, null])( "falls back to relay when the direct client disconnects with heartbeat RTT %s", async (heartbeatRtt) => { @@ -3366,7 +3466,11 @@ describe("HostRuntimeStore", () => { store.boot(); await registryLoaded; - expect(store.getHosts()[0]?.appearance).toEqual({ color: "none", badgeDisplay: null }); + expect(store.getHosts()[0]?.appearance).toEqual({ + color: "none", + badgeDisplay: null, + }); + expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false); store.syncHosts([]); }); @@ -3391,6 +3495,7 @@ describe("HostRuntimeStore", () => { const updated = store.getHosts()[0]; expect(updated?.appearance).toEqual({ color: "teal", badgeDisplay: null }); + expect("icon" in (updated?.appearance ?? {})).toBe(false); expect(updated?.updatedAt).not.toBe(host.updatedAt); const persisted = await storage.getItem("@paseo:daemon-registry"); @@ -3402,10 +3507,60 @@ describe("HostRuntimeStore", () => { store.syncHosts([]); }); + it("records a chosen host icon and resets to auto without disturbing color or badge display", async () => { + const host = makeHost({ + serverId: "srv_appearance", + appearance: { color: "violet", badgeDisplay: "icon" }, + }); + const storage = createMemoryHostRuntimeStorage(); + await storage.setItem("@paseo:daemon-registry", JSON.stringify([host])); + await storage.setItem("@paseo:e2e", "1"); + const store = createAppearanceStore(storage); + + const registryLoaded = onceHostListMatches(store, () => store.isHostRegistryLoaded()); + store.boot(); + await registryLoaded; + + const hostListChanged = onceHostListMatches( + store, + () => store.getHosts()[0]?.appearance.icon === "laptop", + ); + await store.setHostIcon("srv_appearance", "laptop"); + await hostListChanged; + + expect(store.getHosts()[0]?.appearance).toEqual({ + color: "violet", + icon: "laptop", + badgeDisplay: "icon", + }); + + const persisted = await storage.getItem("@paseo:daemon-registry"); + expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({ + color: "violet", + icon: "laptop", + badgeDisplay: "icon", + }); + + const resetToAuto = onceHostListMatches( + store, + () => store.getHosts()[0]?.appearance.icon === undefined, + ); + await store.setHostIcon("srv_appearance", null); + await resetToAuto; + + expect(store.getHosts()[0]?.appearance).toEqual({ + color: "violet", + badgeDisplay: "icon", + }); + expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false); + + store.syncHosts([]); + }); + it("records a chosen badge display without disturbing the color", async () => { const host = makeHost({ serverId: "srv_appearance", - appearance: { color: "amber", badgeDisplay: null }, + appearance: { color: "amber", icon: "server", badgeDisplay: null }, }); const storage = createMemoryHostRuntimeStorage(); await storage.setItem("@paseo:daemon-registry", JSON.stringify([host])); @@ -3423,11 +3578,16 @@ describe("HostRuntimeStore", () => { await store.setHostBadgeDisplay("srv_appearance", "icon"); await hostListChanged; - expect(store.getHosts()[0]?.appearance).toEqual({ color: "amber", badgeDisplay: "icon" }); + expect(store.getHosts()[0]?.appearance).toEqual({ + color: "amber", + icon: "server", + badgeDisplay: "icon", + }); const persisted = await storage.getItem("@paseo:daemon-registry"); expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({ color: "amber", + icon: "server", badgeDisplay: "icon", }); @@ -3476,16 +3636,25 @@ describe("HostRuntimeStore", () => { }; const color = store.setHostColor("srv_appearance", "teal"); + const icon = store.setHostIcon("srv_appearance", "mini"); const display = store.setHostBadgeDisplay("srv_appearance", "icon"); await Promise.resolve(); expect(writeCount).toBe(1); firstWrite.resolve(); - await Promise.all([color, display]); + await Promise.all([color, icon, display]); - expect(store.getHosts()[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" }); + expect(store.getHosts()[0]?.appearance).toEqual({ + color: "teal", + icon: "mini", + badgeDisplay: "icon", + }); const persistedHosts = JSON.parse((await storage.getItem("@paseo:daemon-registry")) ?? "[]"); - expect(persistedHosts[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" }); + expect(persistedHosts[0]?.appearance).toEqual({ + color: "teal", + icon: "mini", + badgeDisplay: "icon", + }); store.syncHosts([]); }); diff --git a/packages/app/src/runtime/host-runtime.ts b/packages/app/src/runtime/host-runtime.ts index 0bfcbc825b..e4b5cc4583 100644 --- a/packages/app/src/runtime/host-runtime.ts +++ b/packages/app/src/runtime/host-runtime.ts @@ -28,7 +28,12 @@ import { type HostProfile, type UnreadableHostEntries, } from "@/types/host-connection"; -import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance"; +import { + defaultHostAppearance, + type HostBadgeDisplay, + type HostColor, + type HostIcon, +} from "@/hosts/appearance"; import { buildDaemonWebSocketUrl, buildRelayWebSocketUrl, @@ -945,6 +950,56 @@ export class HostRuntimeController { await this.switchToConnection(input); } + /** + * Measures the active connection's round-trip time when the host is online and no sample has + * landed yet (for example right after connecting, before the first heartbeat interval fires). + */ + async refreshActiveLatency(): Promise { + const activeConnectionId = this.snapshot.activeConnectionId; + const activeClient = this.snapshot.client; + if ( + this.snapshot.connectionStatus !== "online" || + !activeConnectionId || + !activeClient || + activeClient.getConnectionState().status !== "connected" + ) { + return; + } + const existing = this.snapshot.probeByConnectionId.get(activeConnectionId); + if (existing?.status === "available") { + return; + } + const existingRtt = activeClient.getLastLivenessRttMs(); + if (existingRtt !== null) { + this.recordActiveLatencySample(activeConnectionId, existingRtt); + return; + } + try { + const rttMs = await activeClient.measureLatency({ timeoutMs: 3_000 }); + if ( + this.snapshot.activeConnectionId !== activeConnectionId || + this.snapshot.client !== activeClient || + this.snapshot.connectionStatus !== "online" + ) { + return; + } + this.recordActiveLatencySample(activeConnectionId, rttMs); + } catch { + // A latency probe never drives teardown; the heartbeat owns liveness. + } + } + + private setConnectionProbe(connectionId: string, probe: ConnectionProbeState): void { + const probeByConnectionId = new Map(this.snapshot.probeByConnectionId); + probeByConnectionId.set(connectionId, probe); + this.updateSnapshot({ probeByConnectionId }); + } + + private recordActiveLatencySample(connectionId: string, rttMs: number): void { + this.recordActiveRttSample(rttMs, performance.now()); + this.setConnectionProbe(connectionId, { status: "available", latencyMs: rttMs }); + } + async runProbeCycleNow(): Promise { if (this.probeCycleInFlight) { return this.probeCycleInFlight; @@ -1001,30 +1056,32 @@ export class HostRuntimeController { return; } - const probeByConnectionId = new Map(this.snapshot.probeByConnectionId); + const initialProbes = new Map(this.snapshot.probeByConnectionId); for (const connection of connectionsToProbe) { this.connectionLastProbedAt.set(connection.id, performance.now()); - const existingProbe = probeByConnectionId.get(connection.id); + const existingProbe = initialProbes.get(connection.id); const shouldPreserveActiveLatency = isOnline && connection.id === activeConnectionId && existingProbe?.status === "available"; if (!shouldPreserveActiveLatency) { - probeByConnectionId.set(connection.id, { + initialProbes.set(connection.id, { status: "pending", latencyMs: null, }); } } - this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) }); + this.updateSnapshot({ probeByConnectionId: initialProbes }); let remaining = connectionsToProbe.length; let probeAuthFailure: "password_required" | "incorrect_password" | null = null; let activationLock: Promise | null = null; - const publishProbeState = (): void => { + // Merge each connection result into the live snapshot map so a slow probe on another + // connection cannot overwrite a fresher sample (e.g. from refreshActiveLatency) on the active one. + const publishConnectionProbe = (connectionId: string, probe: ConnectionProbeState): void => { if (!this.isCurrentProbeRequest(requestVersion)) { return; } - this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) }); + this.setConnectionProbe(connectionId, probe); }; const maybeActivateFirstAvailable = async ( @@ -1053,6 +1110,7 @@ export class HostRuntimeController { return; } + const probeByConnectionId = new Map(this.snapshot.probeByConnectionId); const currentActiveConnectionId = this.snapshot.activeConnectionId; if (currentActiveConnectionId) { this.reconcileActiveProbeWithClient(currentActiveConnectionId, probeByConnectionId); @@ -1208,11 +1266,10 @@ export class HostRuntimeController { if (activeClient) { if (activeClient.getConnectionState().status !== "connected") { - probeByConnectionId.set(connection.id, { + publishConnectionProbe(connection.id, { status: "unavailable", latencyMs: null, }); - publishProbeState(); return; } const rttMs = activeClient.getLastLivenessRttMs(); @@ -1221,11 +1278,10 @@ export class HostRuntimeController { } if (rttMs !== null) { this.recordActiveRttSample(rttMs, performance.now()); - probeByConnectionId.set(connection.id, { + publishConnectionProbe(connection.id, { status: "available", latencyMs: rttMs, }); - publishProbeState(); } return; } @@ -1235,11 +1291,10 @@ export class HostRuntimeController { return; } - probeByConnectionId.set(connection.id, { + publishConnectionProbe(connection.id, { status: "available", latencyMs: rttMs, }); - publishProbeState(); } catch (error) { if (this.isCurrentProbeRequest(requestVersion)) { const authFailure = getConnectionAuthFailureReason(error); @@ -1247,11 +1302,10 @@ export class HostRuntimeController { this.authRejectedConnectionIds.add(connection.id); probeAuthFailure = authFailure; } - probeByConnectionId.set(connection.id, { + publishConnectionProbe(connection.id, { status: "unavailable", latencyMs: null, }); - publishProbeState(); } } finally { if (connectedClient && shouldCloseClient) { @@ -2436,6 +2490,16 @@ export class HostRuntimeStore { })); } + async setHostIcon(serverId: string, icon: HostIcon | null): Promise { + await this.updateHostAppearance(serverId, (host) => { + const { icon: _previousIcon, ...rest } = host.appearance; + return { + ...host, + appearance: icon ? { ...rest, icon } : rest, + }; + }); + } + async setHostBadgeDisplay(serverId: string, badgeDisplay: HostBadgeDisplay): Promise { await this.updateHostAppearance(serverId, (host) => ({ ...host, @@ -2443,6 +2507,16 @@ export class HostRuntimeStore { })); } + refreshActiveLatencies(serverIds?: readonly string[]): void { + const targets = serverIds ?? this.hosts.map((host) => host.serverId); + for (const serverId of targets) { + const controller = this.controllers.get(serverId); + if (controller) { + void controller.refreshActiveLatency(); + } + } + } + private updateHostAppearance( serverId: string, apply: (host: HostProfile) => HostProfile, @@ -3296,6 +3370,7 @@ export interface HostMutations { beginLinkPairing: () => LinkPairing; renameHost: (serverId: string, label: string) => Promise; setHostColor: (serverId: string, color: HostColor) => Promise; + setHostIcon: (serverId: string, icon: HostIcon | null) => Promise; setHostBadgeDisplay: (serverId: string, badgeDisplay: HostBadgeDisplay) => Promise; removeHost: (serverId: string) => Promise; removeConnection: (serverId: string, connectionId: string) => Promise; @@ -3311,6 +3386,7 @@ export function useHostMutations(): HostMutations { beginLinkPairing: () => store.beginLinkPairing(), renameHost: (serverId, label) => store.renameHost(serverId, label), setHostColor: (serverId, color) => store.setHostColor(serverId, color), + setHostIcon: (serverId, icon) => store.setHostIcon(serverId, icon), setHostBadgeDisplay: (serverId, badgeDisplay) => store.setHostBadgeDisplay(serverId, badgeDisplay), removeHost: (serverId) => store.removeHost(serverId), diff --git a/packages/app/src/screens/new-workspace/form/index.tsx b/packages/app/src/screens/new-workspace/form/index.tsx index 2bb097b2a3..afacce7178 100644 --- a/packages/app/src/screens/new-workspace/form/index.tsx +++ b/packages/app/src/screens/new-workspace/form/index.tsx @@ -438,7 +438,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement searchable={false} title={t("newWorkspace.fields.host")} desktopPlacement="bottom-start" - desktopMinWidth={200} + desktopMinWidth={320} hostOptionTestID={hostOptionTestID} > diff --git a/packages/app/src/screens/settings/host-appearance-section.tsx b/packages/app/src/screens/settings/host-appearance-section.tsx index d5462f9cb9..8f342454fb 100644 --- a/packages/app/src/screens/settings/host-appearance-section.tsx +++ b/packages/app/src/screens/settings/host-appearance-section.tsx @@ -4,7 +4,12 @@ import { useTranslation } from "react-i18next"; import { Pressable, Text, View } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { Pencil } from "lucide-react-native"; -import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, +} from "@/components/ui/dropdown-menu"; import { DropdownTrigger } from "@/components/ui/dropdown-trigger"; import { AdaptiveRenameModal } from "@/components/rename-modal"; import { WorkspaceMetaRow } from "@/components/sidebar/workspace-meta-row"; @@ -13,12 +18,18 @@ import { SettingsSection } from "@/components/settings/headings/settings-section import { HOST_BADGE_DISPLAYS, HOST_COLORS, + HOST_ICONS, + normalizeDetectedHostIcon, resolveHostBadgeDisplay, + resolveHostIcon, type HostBadgeDisplay, type HostColor, + type HostIcon, } from "@/hosts/appearance"; +import { HostIconGlyph } from "@/hosts/host-icon-glyph"; import { useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon"; import { useHostMutations } from "@/runtime/host-runtime"; +import { useSessionStore } from "@/stores/session-store"; import { identityColor } from "@/styles/identity-colors"; import { settingsStyles } from "@/styles/settings"; import { ICON_SIZE, type Theme } from "@/styles/theme"; @@ -76,10 +87,112 @@ function colorLabel(t: TFunction, color: HostColor): string { return t(`settings.host.appearance.color.options.${color}`); } +function iconLabel(t: TFunction, icon: HostIcon): string { + return t(`settings.host.appearance.icon.options.${icon}`); +} + +function autoIconLabel(t: TFunction, detectedIcon: HostIcon | null): string { + if (detectedIcon) { + return t("settings.host.appearance.icon.autoDetected", { + icon: iconLabel(t, detectedIcon), + }); + } + return t("settings.host.appearance.icon.auto"); +} + function badgeDisplayLabel(t: TFunction, display: HostBadgeDisplay): string { return t(`settings.host.appearance.badge.options.${display}`); } +function IconMenuItem({ + icon, + color, + selected, + onChange, +}: { + icon: HostIcon; + color: HostColor; + selected: boolean; + onChange: (icon: HostIcon | null) => void; +}) { + const { t } = useTranslation(); + const handleSelect = useCallback(() => onChange(icon), [icon, onChange]); + const leading = useMemo( + () => , + [color, icon], + ); + return ( + + {iconLabel(t, icon)} + + ); +} + +function IconRow({ + icon, + detectedIcon, + resolvedIcon, + color, + onChange, +}: { + icon: HostIcon | null; + detectedIcon: HostIcon | null; + resolvedIcon: HostIcon; + color: HostColor; + onChange: (icon: HostIcon | null) => void; +}) { + const { t } = useTranslation(); + const autoLabel = autoIconLabel(t, detectedIcon); + const selectedLabel = icon ? iconLabel(t, icon) : autoLabel; + const handleSelectAuto = useCallback(() => onChange(null), [onChange]); + const triggerLeading = useMemo( + () => , + [color, resolvedIcon], + ); + const autoLeading = useMemo( + () => , + [color, detectedIcon], + ); + return ( + + + {t("settings.host.appearance.icon.label")} + + + + {selectedLabel} + + + + {autoLabel} + + + {HOST_ICONS.map((option) => ( + + ))} + + + + ); +} + function ColorSwatch({ color }: { color: HostColor }) { const swatchStyle = useMemo( () => [styles.swatch, color === "none" ? null : { backgroundColor: identityColor(color) }], @@ -205,9 +318,11 @@ function BadgeDisplayMenuItem({ */ function BadgePreview({ host, + resolvedIcon, badgeDisplay, }: { host: HostProfile; + resolvedIcon: HostIcon; badgeDisplay: HostBadgeDisplay; }) { const { t } = useTranslation(); @@ -219,9 +334,10 @@ function BadgePreview({ serverId: host.serverId, label: host.label, color: host.appearance.color, + icon: resolvedIcon, showLabel: badgeDisplay === "name", }, - [badgeDisplay, host.serverId, host.label, host.appearance.color], + [badgeDisplay, host.serverId, host.label, host.appearance.color, resolvedIcon], ); // The real sidebar row, so the preview can't drift from what the setting actually does. return ( @@ -244,8 +360,14 @@ function BadgePreview({ export function HostAppearanceSection({ host }: { host: HostProfile }) { const { t } = useTranslation(); const toast = useToast(); - const { setHostColor, setHostBadgeDisplay } = useHostMutations(); + const { setHostColor, setHostIcon, setHostBadgeDisplay } = useHostMutations(); const localDaemon = useLocalDaemonServerIdState(); + const detectedMachineKind = useSessionStore( + (state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null, + ); + const detectedIcon = normalizeDetectedHostIcon(detectedMachineKind); + const selectedIcon = normalizeDetectedHostIcon(host.appearance.icon); + const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind }); const isLocalHost = localDaemon.status === "resolved" && localDaemon.serverId === host.serverId; const badgeDisplay = resolveHostBadgeDisplay({ appearance: host.appearance, @@ -263,6 +385,16 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) { }, [host.serverId, setHostColor, t, toast], ); + const handleIconChange = useCallback( + async (icon: HostIcon | null) => { + try { + await setHostIcon(host.serverId, icon); + } catch { + toast.error(t("errors.unableToSave")); + } + }, + [host.serverId, setHostIcon, t, toast], + ); const handleBadgeDisplayChange = useCallback( async (next: HostBadgeDisplay) => { try { @@ -288,11 +420,18 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) { + {badgeDisplay === null ? null : ( <> - + )} diff --git a/packages/app/src/stores/session-store.ts b/packages/app/src/stores/session-store.ts index 55d2c43a23..76ec98a06f 100644 --- a/packages/app/src/stores/session-store.ts +++ b/packages/app/src/stores/session-store.ts @@ -293,6 +293,7 @@ export interface DaemonServerInfo { serverId: string; hostname: string | null; version: string | null; + machineKind?: string | null; desktopManaged?: boolean; capabilities?: ServerCapabilities; features?: ServerInfoStatusPayload["features"]; @@ -303,6 +304,7 @@ export function toDaemonServerInfo(serverInfo: ServerInfoStatusPayload): DaemonS serverId: serverInfo.serverId, hostname: serverInfo.hostname ?? null, version: serverInfo.version ?? null, + ...(serverInfo.machineKind !== undefined ? { machineKind: serverInfo.machineKind } : {}), ...(serverInfo.desktopManaged !== undefined ? { desktopManaged: serverInfo.desktopManaged } : {}), @@ -786,6 +788,7 @@ function isSessionServerInfoUnchanged(input: { currentServerInfo: SessionState["serverInfo"] | undefined; nextHostname: string | null; nextVersion: string | null; + nextMachineKind: string | null; nextDesktopManaged: boolean | undefined; nextCapabilities: ServerCapabilities | undefined; nextFeatures: ServerInfoStatusPayload["features"] | undefined; @@ -795,16 +798,19 @@ function isSessionServerInfoUnchanged(input: { currentServerInfo, nextHostname, nextVersion, + nextMachineKind, nextDesktopManaged, nextCapabilities, nextFeatures, } = input; const prevHostname = currentServerInfo?.hostname?.trim() || null; const prevVersion = currentServerInfo?.version?.trim() || null; + const prevMachineKind = currentServerInfo?.machineKind?.trim() || null; return ( currentServerInfo?.serverId === input.nextServerId && prevHostname === nextHostname && prevVersion === nextVersion && + prevMachineKind === nextMachineKind && currentServerInfo?.desktopManaged === nextDesktopManaged && areServerCapabilitiesEqual(currentServerInfo?.capabilities, nextCapabilities) && areServerInfoFeaturesEqual(currentServerInfo?.features, nextFeatures) @@ -942,6 +948,7 @@ export const useSessionStore = create()( const nextHostname = info.hostname?.trim() || null; const nextVersion = info.version?.trim() || null; + const nextMachineKind = info.machineKind?.trim() || null; const nextDesktopManaged = info.desktopManaged; const nextCapabilities = info.capabilities; const nextFeatures = info.features; @@ -951,6 +958,7 @@ export const useSessionStore = create()( currentServerInfo: session.serverInfo, nextHostname, nextVersion, + nextMachineKind, nextDesktopManaged, nextCapabilities, nextFeatures, @@ -970,6 +978,7 @@ export const useSessionStore = create()( serverId: info.serverId, hostname: nextHostname, version: nextVersion, + ...(nextMachineKind !== null ? { machineKind: nextMachineKind } : {}), ...(nextDesktopManaged !== undefined ? { desktopManaged: nextDesktopManaged } : {}), diff --git a/packages/app/src/types/host-connection.test.ts b/packages/app/src/types/host-connection.test.ts index 36c652ccab..8556e32161 100644 --- a/packages/app/src/types/host-connection.test.ts +++ b/packages/app/src/types/host-connection.test.ts @@ -152,7 +152,7 @@ describe("normalizeStoredHostProfile", () => { }); }); - it("gives a host stored before appearance existed the default appearance", () => { + it("gives a host stored before appearance existed the default appearance without an icon key", () => { const profile = normalizeStoredHostProfile({ serverId: "srv_old", connections: [ @@ -161,18 +161,35 @@ describe("normalizeStoredHostProfile", () => { }); expect(profile?.appearance).toEqual({ color: "none", badgeDisplay: null }); + expect(profile && "icon" in profile.appearance).toBe(false); }); it("loads a stored appearance the user chose", () => { const profile = normalizeStoredHostProfile({ serverId: "srv_new", - appearance: { color: "teal", badgeDisplay: "icon" }, + appearance: { color: "teal", icon: "laptop", badgeDisplay: "icon" }, connections: [ { id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" }, ], }); - expect(profile?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" }); + expect(profile?.appearance).toEqual({ color: "teal", icon: "laptop", badgeDisplay: "icon" }); + }); + + it("preserves an unknown stored icon intact without dropping the saved host", () => { + const profile = normalizeStoredHostProfile({ + serverId: "srv_future_icon", + appearance: { color: "violet", icon: "future-device", badgeDisplay: "name" }, + connections: [ + { id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" }, + ], + }); + + expect(profile?.appearance).toEqual({ + color: "violet", + icon: "future-device", + badgeDisplay: "name", + }); }); it("normalizes stored Remote SSH connection parameters", () => { @@ -340,12 +357,13 @@ describe("upsertHostConnectionInProfiles", () => { }); expect(profile.appearance).toEqual({ color: "none", badgeDisplay: null }); + expect("icon" in profile.appearance).toBe(false); }); it("keeps the appearance the user chose when the host reconnects", () => { const existing: HostProfile = { ...makeHost("srv_known"), - appearance: { color: "amber", badgeDisplay: "hidden" }, + appearance: { color: "amber", icon: "workstation", badgeDisplay: "hidden" }, connections: [], }; @@ -355,7 +373,11 @@ describe("upsertHostConnectionInProfiles", () => { connection, }); - expect(profile.appearance).toEqual({ color: "amber", badgeDisplay: "hidden" }); + expect(profile.appearance).toEqual({ + color: "amber", + icon: "workstation", + badgeDisplay: "hidden", + }); }); it("replaces a direct connection when its settings change", () => { diff --git a/packages/app/test-stubs/lucide-react-native.ts b/packages/app/test-stubs/lucide-react-native.ts index f3d785b54f..2d10083f99 100644 --- a/packages/app/test-stubs/lucide-react-native.ts +++ b/packages/app/test-stubs/lucide-react-native.ts @@ -143,3 +143,11 @@ export const Minimize = StubIcon; export const Rows2 = StubIcon; export const Gauge = StubIcon; export const GripVertical = StubIcon; +export const Cloud = StubIcon; +export const Computer = StubIcon; +export const Container = StubIcon; +export const Cpu = StubIcon; +export const Laptop = StubIcon; +export const Network = StubIcon; +export const PcCase = StubIcon; +export const Waypoints = StubIcon; diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 29f36feb28..d9b4a3f343 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -3970,6 +3970,9 @@ export const ServerInfoStatusPayloadSchema = z serverId: z.string().trim().min(1), hostname: ServerInfoHostnameSchema.optional(), version: ServerInfoVersionSchema.optional(), + // Best-effort machine kind detected by the daemon (e.g. "laptop", "mini", "cloud"). + // Loose string so unknown future kinds stay parseable across versions. + machineKind: z.string().nullable().optional(), // Authenticated producer for host registration ownership, separate from admission authority. sourceId: z.string().optional(), // COMPAT(sessionPermissions): optional while clients support older daemons. diff --git a/packages/protocol/src/messages.wire-compat.test.ts b/packages/protocol/src/messages.wire-compat.test.ts index b6e3fb5975..6ed61dcbc1 100644 --- a/packages/protocol/src/messages.wire-compat.test.ts +++ b/packages/protocol/src/messages.wire-compat.test.ts @@ -236,6 +236,34 @@ describe("wire schema compatibility", () => { }); }); + test("server info accepts optional machineKind and older clients drop it cleanly", () => { + const legacyServerInfo = z.object({ + status: z.literal("server_info"), + serverId: z.string().trim().min(1), + hostname: z.string().nullable().optional(), + version: z.string().nullable().optional(), + }); + const withKind = { + status: "server_info", + serverId: "macbook-server", + hostname: "mbp.local", + version: "0.9.5", + machineKind: "laptop", + }; + + expect(ServerInfoStatusPayloadSchema.parse(withKind).machineKind).toBe("laptop"); + expect( + ServerInfoStatusPayloadSchema.parse({ ...withKind, machineKind: null }).machineKind, + ).toBeNull(); + expect( + ServerInfoStatusPayloadSchema.parse({ + status: "server_info", + serverId: "older-server", + }).machineKind, + ).toBeUndefined(); + expect(legacyServerInfo.parse(withKind)).not.toHaveProperty("machineKind"); + }); + test("assistant timeline message ids are optional on the wire", () => { expect( AgentTimelineItemPayloadSchema.parse({ diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 9278d7ada5..d4eead0aed 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -16,6 +16,7 @@ import { createServer as createHTTPServer, type IncomingMessage, type ServerResp import { constants, existsSync, unlinkSync } from "fs"; import { open, rm, stat } from "fs/promises"; import { randomUUID } from "node:crypto"; +import { getCachedHostMachineKind, primeHostMachineKind } from "./host-machine-kind.js"; import { getHostName } from "./host-name.js"; import path from "node:path"; import { createMcpHandler } from "@modelcontextprotocol/server"; @@ -636,6 +637,9 @@ export async function createPaseoDaemon( rootLogger: Logger, dependencies: PaseoDaemonDependencies = {}, ): Promise { + // Start hardware detection at the beginning of bootstrap so it overlaps with disk/registry init + // and does not hold up the listener when probes are slow. + const hostMachineKindReady = primeHostMachineKind(); configureGitProcessPolicy(config.git ?? resolveGitProcessPolicy({ env: process.env })); const logger = rootLogger.child({ module: "bootstrap" }); const obsoleteTimelineDirectory = path.join(config.paseoHome, "agent-timelines"); @@ -874,11 +878,13 @@ export async function createPaseoDaemon( }); app.get("/api/status", (_req, res) => { + const machineKind = getCachedHostMachineKind(); res.json({ status: "server_info", serverId, hostname: getHostName(), version: daemonVersion, + ...(machineKind ? { machineKind } : {}), listen: formatListenTarget(boundListenTarget ?? listenTarget), }); }); @@ -1809,7 +1815,20 @@ export async function createPaseoDaemon( const start = async () => { let mainStarted = false; try { - localCredential = await writeLocalCredential(config.paseoHome); + let machineKindTimeout: ReturnType | null = null; + const [nextLocalCredential] = await Promise.all([ + writeLocalCredential(config.paseoHome), + Promise.race([ + hostMachineKindReady, + new Promise((resolve) => { + machineKindTimeout = setTimeout(resolve, 150); + machineKindTimeout.unref(); + }), + ]).finally(() => { + if (machineKindTimeout) clearTimeout(machineKindTimeout); + }), + ]); + localCredential = nextLocalCredential; if (serviceProxyListenTarget) { const boundServiceProxyTarget = await serviceProxy.startStandalone({ listenTarget: serviceProxyListenTarget, diff --git a/packages/server/src/server/host-machine-kind.test.ts b/packages/server/src/server/host-machine-kind.test.ts new file mode 100644 index 0000000000..be9d42a663 --- /dev/null +++ b/packages/server/src/server/host-machine-kind.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from "vitest"; +import { + classifyLinuxMachine, + classifyMacModel, + parseMacIoregProductName, + type LinuxMachineProbeInput, +} from "./host-machine-kind"; + +function linuxProbe(overrides: Partial = {}): LinuxMachineProbeInput { + return { + hasContainerMarker: false, + procVersion: null, + deviceTreeModel: null, + sysVendor: null, + productName: null, + biosVendor: null, + boardVendor: null, + chassisType: null, + ...overrides, + }; +} + +describe("classifyMacModel", () => { + it.each([ + ["MacBookPro18,3", "laptop"], + ["MacBookAir10,1", "laptop"], + ["Macmini9,1", "mini"], + ["iMac21,1", "desktop"], + ["MacStudio1,1", "workstation"], + ["MacPro7,1", "workstation"], + ["Mac15,6", null], + ["", null], + [null, null], + ] as const)("maps %s to %s", (model, expected) => { + expect(classifyMacModel(model)).toBe(expected); + }); + + it("extracts Apple Silicon product-name from ioreg output", () => { + const ioreg = ` + "model" = <"Mac15,6"> + "product-name" = <"MacBook Pro"> + `; + expect(classifyMacModel(parseMacIoregProductName(ioreg))).toBe("laptop"); + }); +}); + +describe("classifyLinuxMachine", () => { + it("detects containers before VM or chassis markers", () => { + expect( + classifyLinuxMachine( + linuxProbe({ hasContainerMarker: true, sysVendor: "Hetzner", chassisType: "17" }), + ), + ).toBe("container"); + }); + + it("detects WSL as desktop", () => { + expect( + classifyLinuxMachine( + linuxProbe({ procVersion: "Linux version 5.15.153.1-microsoft-standard-WSL2" }), + ), + ).toBe("desktop"); + }); + + it("detects single-board PCs from device-tree model", () => { + expect( + classifyLinuxMachine(linuxProbe({ deviceTreeModel: "Raspberry Pi 5 Model B Rev 1.0" })), + ).toBe("board"); + }); + + it("detects cloud VMs and hypervisors from DMI metadata", () => { + expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Hetzner", productName: "vServer" }))).toBe( + "cloud", + ); + expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Amazon EC2" }))).toBe("cloud"); + expect(classifyLinuxMachine(linuxProbe({ biosVendor: "QEMU" }))).toBe("cloud"); + }); + + it("classifies bare-metal Linux machines by SMBIOS chassis type", () => { + expect(classifyLinuxMachine(linuxProbe({ sysVendor: "LENOVO", chassisType: "10" }))).toBe( + "laptop", + ); + expect(classifyLinuxMachine(linuxProbe({ sysVendor: "ASUS", chassisType: "35" }))).toBe("mini"); + expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Dell Inc.", chassisType: "3" }))).toBe( + "desktop", + ); + expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Supermicro", chassisType: "23" }))).toBe( + "server", + ); + }); + + it("returns null when no marker matches", () => { + expect(classifyLinuxMachine(linuxProbe())).toBeNull(); + }); +}); diff --git a/packages/server/src/server/host-machine-kind.ts b/packages/server/src/server/host-machine-kind.ts new file mode 100644 index 0000000000..3ddf9cf9a3 --- /dev/null +++ b/packages/server/src/server/host-machine-kind.ts @@ -0,0 +1,251 @@ +import { execFile } from "node:child_process"; +import { access, readFile } from "node:fs/promises"; +import { promisify } from "node:util"; + +const execFileAsync = promisify(execFile); + +export type HostMachineKind = + | "laptop" + | "desktop" + | "mini" + | "workstation" + | "cloud" + | "container" + | "board" + | "server"; + +const PROBE_TIMEOUT_MS = 1_500; + +export function classifyMacModel(model: string | null | undefined): HostMachineKind | null { + const normalized = model?.trim().toLowerCase() ?? ""; + if (!normalized) return null; + if (normalized.includes("macbook")) return "laptop"; + if (normalized.includes("macmini") || normalized.includes("mac mini")) return "mini"; + if (normalized.includes("imac")) return "desktop"; + if ( + normalized.includes("macstudio") || + normalized.includes("mac studio") || + normalized.includes("macpro") || + normalized.includes("mac pro") + ) { + return "workstation"; + } + return null; +} + +export interface LinuxMachineProbeInput { + hasContainerMarker: boolean; + procVersion: string | null; + deviceTreeModel: string | null; + sysVendor: string | null; + productName: string | null; + biosVendor: string | null; + boardVendor: string | null; + chassisType: string | null; +} + +const BOARD_PATTERNS = [ + "raspberry pi", + "orange pi", + "banana pi", + "rock pi", + "jetson", + "beaglebone", + "odroid", + "pine64", + "radxa", +] as const; + +const CLOUD_OR_VM_MARKERS = [ + "amazon", + "aws", + "ec2", + "google", + "gce", + "digitalocean", + "hetzner", + "linode", + "akamai", + "vultr", + "ovh", + "scaleway", + "oracle", + "qemu", + "kvm", + "vmware", + "virtualbox", + "xen", + "bochs", + "parallels", + "proxmox", + "hyper-v", + "virtual machine", + "openstack", + "upcloud", + "fly.io", +] as const; + +const LAPTOP_CHASSIS_TYPES = new Set([8, 9, 10, 11, 14, 30, 31, 32]); +const DESKTOP_CHASSIS_TYPES = new Set([3, 4, 5, 6, 7, 13, 15, 16]); +const SERVER_CHASSIS_TYPES = new Set([17, 23, 25, 28, 29]); + +export function classifyLinuxMachine(input: LinuxMachineProbeInput): HostMachineKind | null { + if (input.hasContainerMarker) { + return "container"; + } + + const procVersion = input.procVersion?.toLowerCase() ?? ""; + if (procVersion.includes("microsoft") || procVersion.includes("wsl")) { + return "desktop"; + } + + const deviceTree = input.deviceTreeModel?.toLowerCase() ?? ""; + if (deviceTree && BOARD_PATTERNS.some((pattern) => deviceTree.includes(pattern))) { + return "board"; + } + + const dmiText = [input.sysVendor, input.productName, input.biosVendor, input.boardVendor] + .filter((value): value is string => Boolean(value)) + .join(" ") + .toLowerCase(); + + if (dmiText && CLOUD_OR_VM_MARKERS.some((marker) => dmiText.includes(marker))) { + return "cloud"; + } + + const chassis = Number.parseInt(input.chassisType?.trim() ?? "", 10); + if (Number.isInteger(chassis)) { + if (LAPTOP_CHASSIS_TYPES.has(chassis)) return "laptop"; + if (chassis === 35) return "mini"; + if (DESKTOP_CHASSIS_TYPES.has(chassis)) return "desktop"; + if (SERVER_CHASSIS_TYPES.has(chassis)) return "server"; + } + + return null; +} + +async function fileExists(path: string): Promise { + try { + await access(path); + return true; + } catch { + return false; + } +} + +async function readTrimmedFile(path: string): Promise { + try { + const content = (await readFile(path, "utf8")).replaceAll("\u0000", "").trim(); + return content.length > 0 ? content : null; + } catch { + return null; + } +} + +export function parseMacIoregProductName(output: string): string | null { + const productMatch = output.match(/"product-name"\s*=\s*<"([^"]+)">/i); + if (productMatch?.[1]?.trim()) { + return productMatch[1].trim(); + } + const modelMatch = output.match(/"model"\s*=\s*<"([^"]+)">/i); + return modelMatch?.[1]?.trim() ?? null; +} + +async function readMacModel(): Promise { + // Apple Silicon Macs report generic "Mac15,6" in sysctl hw.model, while IOPlatformExpertDevice + // exposes the human product name ("MacBook Pro", "Mac mini", "Mac Studio", etc.). + try { + const { stdout } = await execFileAsync( + "/usr/sbin/ioreg", + ["-rd1", "-c", "IOPlatformExpertDevice"], + { + encoding: "utf8", + timeout: PROBE_TIMEOUT_MS, + }, + ); + const parsed = parseMacIoregProductName(stdout); + if (parsed && classifyMacModel(parsed)) { + return parsed; + } + } catch { + // Fall back to sysctl below. + } + + try { + const { stdout } = await execFileAsync("/usr/sbin/sysctl", ["-n", "hw.model"], { + encoding: "utf8", + timeout: PROBE_TIMEOUT_MS, + }); + const trimmed = stdout.trim(); + return trimmed || null; + } catch { + return null; + } +} + +export async function detectHostMachineKind( + platform: NodeJS.Platform = process.platform, +): Promise { + if (platform === "darwin") { + return classifyMacModel(await readMacModel()); + } + if (platform === "linux") { + const [ + hasDockerEnv, + hasContainerEnv, + procVersion, + deviceTreeModel, + sysVendor, + productName, + biosVendor, + boardVendor, + chassisType, + ] = await Promise.all([ + fileExists("/.dockerenv"), + fileExists("/run/.containerenv"), + readTrimmedFile("/proc/version"), + readTrimmedFile("/proc/device-tree/model"), + readTrimmedFile("/sys/class/dmi/id/sys_vendor"), + readTrimmedFile("/sys/class/dmi/id/product_name"), + readTrimmedFile("/sys/class/dmi/id/bios_vendor"), + readTrimmedFile("/sys/class/dmi/id/board_vendor"), + readTrimmedFile("/sys/class/dmi/id/chassis_type"), + ]); + return classifyLinuxMachine({ + hasContainerMarker: hasDockerEnv || hasContainerEnv, + procVersion, + deviceTreeModel, + sysVendor, + productName, + biosVendor, + boardVendor, + chassisType, + }); + } + return null; +} + +let cachedMachineKind: HostMachineKind | null | undefined; +let pendingMachineKind: Promise | null = null; + +export function primeHostMachineKind(): Promise { + if (cachedMachineKind !== undefined) { + return Promise.resolve(cachedMachineKind); + } + if (!pendingMachineKind) { + pendingMachineKind = detectHostMachineKind() + .then((kind) => { + cachedMachineKind = kind; + return kind; + }) + .catch(() => { + cachedMachineKind = null; + return null; + }); + } + return pendingMachineKind; +} + +export function getCachedHostMachineKind(): HostMachineKind | null { + return cachedMachineKind ?? null; +} diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index 170499f1ec..341cb3f22f 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -26,6 +26,7 @@ import { MessageReceipts } from "./message-receipts/index.js"; import { WebSocket, WebSocketServer } from "ws"; import type { IncomingMessage, Server as HTTPServer } from "http"; import { join } from "path"; +import { getCachedHostMachineKind } from "./host-machine-kind.js"; import { getHostName } from "./host-name.js"; import { randomUUID } from "node:crypto"; import { monitorEventLoopDelay } from "node:perf_hooks"; @@ -2060,12 +2061,14 @@ export class VoiceAssistantWebSocketServer { } private buildServerInfoStatusPayload(session: Session): ServerInfoStatusPayload { + const machineKind = getCachedHostMachineKind(); return { status: "server_info", protocolVersion: WS_PROTOCOL_VERSION, serverId: this.serverId, hostname: getHostName(), version: this.daemonVersion, + ...(machineKind ? { machineKind } : {}), sourceId: session.getHostSourceId(), permissions: session.getPermissions(), // COMPAT(desktopManaged): added in v0.1.X, remove optional parsing after 2027-01-16. diff --git a/packages/website/src/components/mockup/hosts.tsx b/packages/website/src/components/mockup/hosts.tsx index 2fefb7a204..c2847a59c6 100644 --- a/packages/website/src/components/mockup/hosts.tsx +++ b/packages/website/src/components/mockup/hosts.tsx @@ -1,4 +1,4 @@ -import { Computer, Globe, Laptop, Monitor, PcCase, Plus, Server, Terminal, X } from "lucide-react"; +import { Computer, Globe, Laptop, Monitor, PcCase, Plus, Server, Terminal } from "lucide-react"; import type * as React from "react"; import { useTranslation } from "react-i18next"; import { TailscaleMark } from "./icons"; @@ -53,7 +53,6 @@ interface ConnectedHost { endpoint?: string; /** Round trip time, formatted as the app's `formatLatency` prints it. */ latency: string; - agents: number; } const CONNECTED_HOSTS: ConnectedHost[] = [ @@ -63,7 +62,6 @@ const CONNECTED_HOSTS: ConnectedHost[] = [ tone: "text-mock-fg-muted", link: "local", latency: "1ms", - agents: 4, }, { name: "devbox", @@ -72,7 +70,6 @@ const CONNECTED_HOSTS: ConnectedHost[] = [ link: "relay", endpoint: "relay.paseo.sh", latency: "38ms", - agents: 6, }, { name: "mac-mini", @@ -81,7 +78,6 @@ const CONNECTED_HOSTS: ConnectedHost[] = [ link: "tailscale", endpoint: "mac-mini:6767", latency: "12ms", - agents: 3, }, { name: "workstation", @@ -90,39 +86,41 @@ const CONNECTED_HOSTS: ConnectedHost[] = [ link: "ssh", endpoint: "mo@workstation", latency: "24ms", - agents: 2, }, ]; -function HostRow({ host }: { host: ConnectedHost }) { +function HostRow({ host, highlighted }: { host: ConnectedHost; highlighted?: boolean }) { const { t } = useTranslation(); const Device = host.device; const LinkIcon = LINK_ICON[host.link]; return ( -
- - - +
+ + - - {host.name} + + + + + + {host.name} + - - - {t(`landing.mockup.app.hostLinks.${host.link}`)} - {host.endpoint ? {host.endpoint} : null} + + + + + {t(`landing.mockup.app.hostLinks.${host.link}`)} + {host.endpoint ? ( + {host.endpoint} + ) : null} - - - {host.latency} - - - {t("landing.mockup.app.agentCount", { count: host.agents })} - + + {host.latency}
); @@ -130,25 +128,23 @@ function HostRow({ host }: { host: ConnectedHost }) { /** * Every machine this window is connected to: what kind of machine it is, how the app reaches it, - * the round trip time, and how many agents it runs. + * and its round trip time. */ export function HostsModal() { const { t } = useTranslation(); return ( -
-
- - {t("landing.mockup.app.hosts")} - - +
+
+ {t("landing.mockup.app.hosts")}
- {CONNECTED_HOSTS.map((host) => ( - + {CONNECTED_HOSTS.map((host, index) => ( + ))} -
- {/* The plus sits on the center line of the device tiles above it. */} - - +
+
+ {/* The plus sits on the center line of the status dots above it. */} + + {t("landing.mockup.app.addHost")}
diff --git a/packages/website/src/i18n/resources/en.json b/packages/website/src/i18n/resources/en.json index df20fa4218..02355b758e 100644 --- a/packages/website/src/i18n/resources/en.json +++ b/packages/website/src/i18n/resources/en.json @@ -498,7 +498,6 @@ "addProject": "Add project", "addHost": "Add host", "hosts": "Hosts", - "agentCount": "{{count}} agents", "hostLinks": { "local": "Local", "relay": "Relay", diff --git a/packages/website/src/i18n/resources/zh-CN.json b/packages/website/src/i18n/resources/zh-CN.json index 6ec6350150..7eaeff8b77 100644 --- a/packages/website/src/i18n/resources/zh-CN.json +++ b/packages/website/src/i18n/resources/zh-CN.json @@ -498,7 +498,6 @@ "addProject": "添加 project", "addHost": "添加主机", "hosts": "主机", - "agentCount": "{{count}} 个 Agent", "hostLinks": { "local": "本地", "relay": "中继",