diff --git a/packages/app/e2e/support/helpers/pair-device.ts b/packages/app/e2e/support/helpers/pair-device.ts index 1f9b16eced..0efdf55ade 100644 --- a/packages/app/e2e/support/helpers/pair-device.ts +++ b/packages/app/e2e/support/helpers/pair-device.ts @@ -66,6 +66,12 @@ type PairingHost = | Pick | Pick; +export async function openPairDeviceWaysSheet(page: Page): Promise { + await expect(page.getByTestId("devices-pair-button")).toBeVisible(); + await page.getByTestId("devices-pair-button").click(); + await expect(page.getByTestId("devices-relay")).toBeVisible(); +} + export async function preparePairingHost( page: Page, daemon: PairingHost, @@ -74,9 +80,9 @@ export async function preparePairingHost( await openAppOnPairingHost(page, daemon, additionalHosts); await openSettings(page); await openSettingsHost(page, daemon.serverId); - await expect(page.getByTestId("devices-relay")).toHaveCount(0); + await expect(page.getByTestId("devices-pair-button")).toHaveCount(0); await openSettingsHostSection(page, daemon.serverId, "devices"); - await expect(page.getByTestId("devices-relay")).toBeVisible(); + await openPairDeviceWaysSheet(page); } /** Loads the app afresh with `daemon` as its first host, then opens the setup's Mobile step. */ @@ -372,6 +378,12 @@ function deliverInOrderAfter(delay: () => number, deliver: (message: string | Bu } export async function expectTailscaleUpdateRequired(page: Page): Promise { + if ( + (await page.getByTestId("devices-pair-button").count()) > 0 && + (await page.getByTestId("devices-relay").count()) === 0 + ) { + await openPairDeviceWaysSheet(page); + } await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled(); await expect(page.getByText("Update this host to use Tailscale", { exact: true })).toBeVisible(); await expect(page.getByRole("link", { name: "How to update", exact: true })).toBeVisible(); @@ -460,6 +472,11 @@ export function observeDaemonStatusPolling(page: Page, port: number) { } export async function openPairDeviceModal(page: Page): Promise { + const pairButton = page.getByTestId("devices-pair-button"); + if ((await pairButton.count()) > 0 && (await page.getByTestId("devices-relay").count()) === 0) { + await pairButton.click(); + await expect(page.getByTestId("devices-relay")).toBeVisible(); + } await page.getByRole("button", { name: "Relay", exact: true }).click(); await expect(page.getByTestId("devices-relay-pairing")).toBeVisible(); } @@ -581,7 +598,7 @@ export async function expectPairingDisconnected(page: Page): Promise { export async function switchPairDeviceToHost(page: Page, serverId: string): Promise { await selectSettingsHost(page, serverId); await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "devices")); - await expect(page.getByTestId("devices-relay")).toBeVisible(); + await openPairDeviceWaysSheet(page); } export async function openRelaySecurityDocs(page: Page): Promise { diff --git a/packages/app/src/components/settings/collapsible-row.tsx b/packages/app/src/components/settings/collapsible-row.tsx index 00b54ac3c7..5bb49aee6c 100644 --- a/packages/app/src/components/settings/collapsible-row.tsx +++ b/packages/app/src/components/settings/collapsible-row.tsx @@ -2,12 +2,19 @@ import { useCallback, useMemo, useState, type ReactNode } from "react"; import { View } from "react-native"; import { isWeb } from "@/constants/platform"; import { SettingsRowChildren } from "./row-children"; -import { SettingsRowHeader } from "./row-header"; +import { SettingsRowHeader, type SettingsRowHintStatus } from "./row-header"; interface SettingsCollapsibleRowProps { label: string; + /** An icon or status indicator shown before the label. */ + leading?: ReactNode; + /** A line under the label describing the row's subject. */ + hint?: string; + hintStatus?: SettingsRowHintStatus; /** A short status shown before the chevron, so the row says something while collapsed. */ summary?: string; + /** Passive trailing element (such as a pill) shown before the chevron. */ + trailing?: ReactNode; defaultExpanded?: boolean; testID?: string; /** The rows revealed underneath, separated like the rows of a `SettingsCard` and laid out as nested rows. */ @@ -21,7 +28,11 @@ interface SettingsCollapsibleRowProps { */ export function SettingsCollapsibleRow({ label, + leading, + hint, + hintStatus, summary, + trailing, defaultExpanded = false, testID, children, @@ -39,7 +50,11 @@ export function SettingsCollapsibleRow({ void; disabled?: boolean; /** Turns the chevron down, for a row whose children are revealed in place. */ @@ -75,6 +77,7 @@ export function SettingsRowHeader({ hintStatus, summary, summaryLeading, + trailing, onPress, disabled, expanded = false, @@ -135,6 +138,14 @@ export function SettingsRowHeader({ {control} ) : null} + {trailing ? ( + + {trailing} + + ) : null} ({ control: { marginRight: theme.spacing[3], }, + trailingAccessory: { + marginRight: theme.spacing[2], + flexShrink: 0, + }, // The button under the row's content; it fills the row, padding included. pressTarget: { ...StyleSheet.absoluteFill, diff --git a/packages/app/src/devices/client-info.native.ts b/packages/app/src/devices/client-info.native.ts new file mode 100644 index 0000000000..07579fe24b --- /dev/null +++ b/packages/app/src/devices/client-info.native.ts @@ -0,0 +1,24 @@ +import Constants from "expo-constants"; +import { Platform } from "react-native"; +import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients"; + +function mapNativePlatform(os: string): HelloClientPlatform { + if (os === "ios") return "ios"; + if (os === "android") return "android"; + return "unknown"; +} + +export function resolveAppClientIdentity(): { + clientType: "mobile" | "browser"; + clientInfo: HelloClientInfo; +} { + const deviceName = Constants.deviceName?.trim(); + return { + clientType: "mobile", + clientInfo: { + kind: "mobile", + platform: mapNativePlatform(Platform.OS), + ...(deviceName ? { name: deviceName.slice(0, 128) } : {}), + }, + }; +} diff --git a/packages/app/src/devices/client-info.ts b/packages/app/src/devices/client-info.ts new file mode 100644 index 0000000000..8d60d4c373 --- /dev/null +++ b/packages/app/src/devices/client-info.ts @@ -0,0 +1,49 @@ +import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients"; +import { getIsElectron } from "@/constants/platform"; +import { getDesktopHost } from "@/desktop/host"; + +function mapDesktopPlatform(raw: string | undefined): HelloClientPlatform { + const normalized = raw?.toLowerCase(); + if (normalized === "darwin" || normalized === "macos") return "macos"; + if (normalized === "linux") return "linux"; + if (normalized === "win32" || normalized === "windows") return "windows"; + return "unknown"; +} + +function parseBrowserName(userAgent: string | undefined): string | undefined { + if (!userAgent) return undefined; + if (/Edg\//.test(userAgent)) return "Edge"; + if (/Firefox\//.test(userAgent)) return "Firefox"; + if (/Chrome\//.test(userAgent) && !/Edg\//.test(userAgent)) return "Chrome"; + if (/Safari\//.test(userAgent) && !/Chrome\//.test(userAgent)) return "Safari"; + return undefined; +} + +export function resolveAppClientIdentity(): { + clientType: "mobile" | "browser"; + clientInfo: HelloClientInfo; +} { + if (getIsElectron()) { + const desktop = getDesktopHost(); + const label = desktop?.browserHostLabel?.trim(); + return { + clientType: "mobile", + clientInfo: { + kind: "desktop", + platform: mapDesktopPlatform(desktop?.platform), + ...(label ? { name: label.slice(0, 128) } : {}), + }, + }; + } + + const browserName = + typeof navigator !== "undefined" ? parseBrowserName(navigator.userAgent) : undefined; + return { + clientType: "browser", + clientInfo: { + kind: "web", + platform: "web", + ...(browserName ? { name: browserName } : {}), + }, + }; +} diff --git a/packages/app/src/devices/connected-devices-view.tsx b/packages/app/src/devices/connected-devices-view.tsx new file mode 100644 index 0000000000..24e13eff13 --- /dev/null +++ b/packages/app/src/devices/connected-devices-view.tsx @@ -0,0 +1,559 @@ +import { useEffect, useMemo, useState } from "react"; +import { Text, View } from "react-native"; +import { useTranslation } from "react-i18next"; +import { StyleSheet } from "react-native-unistyles"; +import type { TFunction } from "i18next"; +import type { + ConnectedClientKind, + ConnectedClientSummary, + ConnectedClientTransport, + DaemonClientsSnapshot, + InboundDaemonSummary, +} from "@getpaseo/protocol/daemon-clients"; +import type { DaemonPermission } from "@getpaseo/protocol/messages"; +import type { HostDirectory, HostSummary } from "@getpaseo/protocol/hosts"; +import { + SettingsCard, + SettingsCollapsibleRow, + SettingsRow, + SettingsSection, +} from "@/components/settings"; +import { StatusBadge } from "@/components/ui/status-badge"; +import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime"; +import { useSessionStore } from "@/stores/session-store"; +import { formatConnectedDuration, summarizePermissions } from "./scope-summary"; + +const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates"; + +type StatusDotTone = "online" | "warning" | "error" | "offline"; + +function StatusDot({ tone }: { tone: StatusDotTone }) { + return ( + + + + ); +} + +const STATUS_DOTS: Record = { + online: , + warning: , + error: , + offline: , +}; + +function ScopePill({ permissions, t }: { permissions: readonly DaemonPermission[]; t: TFunction }) { + const summary = summarizePermissions(permissions); + let label: string; + if (summary.kind === "full") { + label = t("devices.scopes.fullAccess"); + } else if (summary.kind === "read_only") { + label = t("devices.scopes.readOnly"); + } else if (summary.count === 1) { + label = t("devices.scopes.countOne"); + } else { + label = t("devices.scopes.countOther", { count: summary.count }); + } + return ; +} + +function PermissionPillsRow({ + permissions, + t, +}: { + permissions: readonly DaemonPermission[]; + t: TFunction; +}) { + return ( + + + {permissions.length > 0 ? ( + permissions.map((permission) => ( + + )) + ) : ( + {t("devices.scopes.none")} + )} + + + ); +} + +function formatDurationLabel(isoTimestamp: string | null | undefined, t: TFunction): string | null { + if (!isoTimestamp) return null; + const duration = formatConnectedDuration(isoTimestamp); + if (!duration) return null; + if (duration.kind === "just_now") return t("devices.time.justNow"); + if (duration.kind === "minutes") return t("devices.time.minutesAgo", { count: duration.count }); + if (duration.kind === "hours") return t("devices.time.hoursAgo", { count: duration.count }); + return t("devices.time.daysAgo", { count: duration.count }); +} + +function formatTransportLabel( + transport: ConnectedClientTransport, + securityMode: "protected" | "legacy" | undefined, + t: TFunction, +): string { + switch (transport) { + case "local_ipc": + case "local": + return t("devices.transport.local"); + case "tailscale": + return t("devices.transport.tailscale"); + case "relay": + return securityMode === "protected" + ? t("devices.transport.relay") + : t("devices.transport.relay"); + case "hub": + return t("devices.transport.hub"); + case "direct": + return t("devices.transport.direct"); + } +} + +function formatClientPlatformLabel( + kind: ConnectedClientKind, + platform: string | null, + t: TFunction, +): string { + if (platform === "ios") return "iOS"; + if (platform === "android") return "Android"; + if (kind === "desktop") return t("devices.kind.desktop"); + if (kind === "web") return t("devices.kind.web"); + if (kind === "mobile") return t("devices.kind.mobile"); + if (kind === "hub") return t("devices.kind.hub"); + if (kind === "cli") return "CLI"; + if (kind === "mcp") return "MCP"; + if (kind === "plugin") return t("devices.kind.plugin"); + return t("devices.kind.client"); +} + +function formatClientTitle(client: ConnectedClientSummary, t: TFunction): string { + if (client.isCurrentSession) return t("devices.connected.thisDevice"); + if (client.name) return client.name; + return formatClientPlatformLabel(client.kind, client.platform, t); +} + +function formatHubHost(hubOrigin: string | null | undefined): string | null { + if (!hubOrigin) return null; + try { + return new URL(hubOrigin).host; + } catch { + return hubOrigin; + } +} + +function formatClientHint(client: ConnectedClientSummary, t: TFunction): string { + const parts: string[] = [formatTransportLabel(client.transport, client.securityMode, t)]; + if (client.kind === "hub") { + const host = formatHubHost(client.hubOrigin); + if (host) parts.push(host); + } else { + const platform = formatClientPlatformLabel(client.kind, client.platform, t); + parts.push(client.appVersion ? `${platform} ${client.appVersion}` : platform); + } + return parts.join(" · "); +} + +function ConnectedClientRow({ client }: { client: ConnectedClientSummary }) { + const { t } = useTranslation(); + const tone: StatusDotTone = client.socketCount > 0 ? "online" : "warning"; + const connectedLabel = formatDurationLabel(client.connectedAt, t); + const trailing = useMemo( + () => , + [client.permissions, t], + ); + + return ( + + + {connectedLabel ? ( + + {connectedLabel} + + ) : null} + {client.socketCount === 0 ? ( + + {t("devices.status.reconnecting")} + + ) : null} + + ); +} + +function InboundDaemonRow({ daemon }: { daemon: InboundDaemonSummary }) { + const { t } = useTranslation(); + const tone: StatusDotTone = daemon.socketCount > 0 ? "online" : "warning"; + const label = daemon.name ?? daemon.peerServerId ?? t("devices.hosts.unnamed"); + const transport = formatTransportLabel(daemon.transport, daemon.securityMode, t); + const hintParts = [t("devices.hosts.inbound"), transport]; + if (daemon.routedSessions.length > 0) { + hintParts.push(t("devices.hosts.routedCount", { count: daemon.routedSessions.length })); + } + const connectedLabel = formatDurationLabel(daemon.connectedAt, t); + const trailing = useMemo( + () => , + [daemon.permissions, t], + ); + + return ( + + + {daemon.routedSessions.map((routed) => ( + + + + ))} + {connectedLabel ? ( + + {connectedLabel} + + ) : null} + + ); +} + +function outboundHostTone(status: HostSummary["status"]): StatusDotTone { + switch (status) { + case "online": + return "online"; + case "connecting": + return "warning"; + case "error": + return "error"; + case "offline": + case "disabled": + return "offline"; + } +} + +function outboundHostStatusLabel(status: HostSummary["status"], t: TFunction): string | undefined { + switch (status) { + case "connecting": + return t("devices.status.connecting"); + case "error": + return t("devices.status.error"); + case "disabled": + return t("devices.status.disabled"); + case "offline": + return t("devices.status.offline"); + case "online": + return undefined; + } +} + +function OutboundHostRow({ host }: { host: HostSummary }) { + const { t } = useTranslation(); + const tone = outboundHostTone(host.status); + const label = host.label ?? host.serverId ?? host.targetDescription; + const hintParts = [t("devices.hosts.outbound"), host.targetDescription]; + const statusSummary = outboundHostStatusLabel(host.status, t); + const connectedLabel = formatDurationLabel(host.connectedAt ?? host.lastOnlineAt, t); + const trailing = useMemo( + () => + host.status === "online" && host.permissions ? ( + + ) : undefined, + [host.permissions, host.status, t], + ); + + return ( + + {host.permissions ? : null} + {host.error ? ( + + {host.error.message} + + ) : null} + {host.version ? ( + + {host.version} + + ) : null} + {connectedLabel ? ( + + {connectedLabel} + + ) : null} + + ); +} + +type ConnectedClientsLoadState = + | { status: "loading" } + | { status: "ready"; snapshot: DaemonClientsSnapshot } + | { status: "error"; message: string }; + +function useConnectedClients(serverId: string, enabled: boolean): ConnectedClientsLoadState { + const client = useHostRuntimeClient(serverId); + const [state, setState] = useState({ status: "loading" }); + + useEffect(() => { + if (!enabled || !client) { + setState({ status: "loading" }); + return; + } + let active = true; + const observation = client.observeConnectedClients(); + const apply = (snapshot: DaemonClientsSnapshot) => { + if (active) setState({ status: "ready", snapshot }); + }; + const unsubscribe = observation.subscribe({ + snapshot: apply, + update: (message) => { + if (message.type === "daemon.clients.changed") { + apply({ + clients: message.payload.clients, + inboundDaemons: message.payload.inboundDaemons, + }); + } + }, + error: (err) => { + if (!active) return; + setState({ + status: "error", + message: err instanceof Error ? err.message : String(err), + }); + }, + }); + void observation.ready.then(apply).catch((err: unknown) => { + if (!active) return; + setState({ + status: "error", + message: err instanceof Error ? err.message : String(err), + }); + }); + + return () => { + active = false; + unsubscribe(); + void observation.release(); + }; + }, [client, enabled]); + + return state; +} + +function useOutboundHosts(serverId: string, enabled: boolean): HostDirectory | null { + const client = useHostRuntimeClient(serverId); + const [directory, setDirectory] = useState(null); + + useEffect(() => { + if (!enabled || !client) { + setDirectory(null); + return; + } + let active = true; + const observation = client.observeHosts(); + const apply = (next: HostDirectory) => { + if (active) setDirectory(next); + }; + const unsubscribe = observation.subscribe({ + snapshot: apply, + update: (message) => { + if (message.type === "hosts.changed") apply(message.payload.directory); + }, + }); + void observation.ready.then(apply).catch(() => undefined); + + return () => { + active = false; + unsubscribe(); + void observation.release(); + }; + }, [client, enabled]); + + return directory; +} + +function ConnectedClientsCardBody({ + isOnline, + hasServerInfo, + supportsConnectedClients, + canViewClients, + clientsState, +}: { + isOnline: boolean; + hasServerInfo: boolean; + supportsConnectedClients: boolean; + canViewClients: boolean; + clientsState: ConnectedClientsLoadState; +}) { + const { t } = useTranslation(); + const updateLink = useMemo( + () => ({ href: UPDATES_DOCS_URL, label: t("devices.tailscale.updateDocs") }), + [t], + ); + + if (!isOnline) { + return ( + + ); + } + if (hasServerInfo && !supportsConnectedClients) { + return ( + + ); + } + if (!canViewClients) { + return ( + + ); + } + if (clientsState.status === "loading") { + return ; + } + if (clientsState.status === "error") { + return ; + } + if (clientsState.snapshot.clients.length === 0) { + return ; + } + return ( + <> + {clientsState.snapshot.clients.map((entry) => ( + + ))} + + ); +} + +export function ConnectedDevicesView({ serverId }: { serverId: string }) { + const { t } = useTranslation(); + const connectionStatus = useHostRuntimeSnapshot(serverId)?.connectionStatus; + const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null); + + const isOnline = connectionStatus === "online"; + // COMPAT(connectedClients): added in v0.19.0, remove gate after 2027-06-01. + const supportsConnectedClients = serverInfo?.features?.connectedClients === true; + const supportsConnectedHosts = serverInfo?.features?.connectedHosts === true; + const canViewClients = + !serverInfo?.permissions || serverInfo.permissions.includes("access.manage"); + + const clientsState = useConnectedClients( + serverId, + isOnline && supportsConnectedClients && canViewClients, + ); + const outboundDirectory = useOutboundHosts(serverId, isOnline && supportsConnectedHosts); + + const inboundDaemons = + clientsState.status === "ready" ? clientsState.snapshot.inboundDaemons : []; + const outboundHosts = outboundDirectory?.hosts ?? []; + const hasConnectedHosts = inboundDaemons.length > 0 || outboundHosts.length > 0; + + return ( + + + + + + + + {isOnline && hasConnectedHosts ? ( + + + {inboundDaemons.map((daemon) => ( + + ))} + {outboundHosts.map((host) => ( + + ))} + + + ) : null} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + dotSlot: { + width: 10, + alignItems: "center", + justifyContent: "center", + }, + dot: { + width: 7, + height: 7, + borderRadius: theme.borderRadius.full, + }, + dotOnline: { + backgroundColor: theme.colors.statusDotSuccess, + }, + dotWarning: { + backgroundColor: theme.colors.statusDotWarning, + }, + dotError: { + backgroundColor: theme.colors.statusDotDanger, + }, + dotOffline: { + backgroundColor: theme.colors.foregroundExtraMuted, + }, + scopePills: { + flexDirection: "row", + flexWrap: "wrap", + justifyContent: "flex-end", + gap: theme.spacing[1.5], + }, + nestedValue: { + fontSize: theme.fontSize.sm, + color: theme.colors.foregroundMuted, + }, + nestedError: { + fontSize: theme.fontSize.sm, + color: theme.colors.statusDanger, + }, +})); diff --git a/packages/app/src/devices/index.tsx b/packages/app/src/devices/index.tsx index db8a4248c7..a5ff2e46e3 100644 --- a/packages/app/src/devices/index.tsx +++ b/packages/app/src/devices/index.tsx @@ -1,2 +1,4 @@ +export { ConnectedDevicesView } from "./connected-devices-view"; +export { PairDeviceHeaderAction } from "./pair-device-header-action"; export { PairDeviceModal } from "./pair-device-modal"; export { WaysToConnect } from "./ways-to-connect"; diff --git a/packages/app/src/devices/pair-device-header-action.tsx b/packages/app/src/devices/pair-device-header-action.tsx new file mode 100644 index 0000000000..9d67cdbcbe --- /dev/null +++ b/packages/app/src/devices/pair-device-header-action.tsx @@ -0,0 +1,79 @@ +import { useCallback, useMemo, useState } from "react"; +import { Plus } from "lucide-react-native"; +import { useTranslation } from "react-i18next"; +import { withUnistyles } from "react-native-unistyles"; +import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; +import { Button } from "@/components/ui/button"; +import type { Theme } from "@/styles/theme"; +import { PairDeviceSection } from "./pair-device-section"; +import { WaysToConnect } from "./ways-to-connect"; + +const SNAP_POINTS: string[] = ["72%", "92%"]; +const ThemedPlus = withUnistyles(Plus); +const iconProps = (theme: Theme) => ({ + size: theme.iconSize.sm, + color: theme.colors.foreground, +}); +const plusIcon = ; + +type PairStep = "ways" | "relay"; + +export function PairDeviceHeaderAction({ serverId }: { serverId: string }) { + const { t } = useTranslation(); + const [visible, setVisible] = useState(false); + const [step, setStep] = useState("ways"); + + const handleOpen = useCallback(() => { + setStep("ways"); + setVisible(true); + }, []); + const handleClose = useCallback(() => { + setVisible(false); + setStep("ways"); + }, []); + const handleOpenRelay = useCallback(() => setStep("relay"), []); + const handleBackToWays = useCallback(() => setStep("ways"), []); + + const header = useMemo( + () => + step === "relay" + ? { + title: t("devices.relay.title"), + back: { + onPress: handleBackToWays, + label: t("common.actions.back"), + }, + } + : { + title: t("settings.host.pairDevices.rowTitle"), + }, + [handleBackToWays, step, t], + ); + + return ( + <> + + + {step === "relay" ? ( + + ) : ( + + )} + + + ); +} diff --git a/packages/app/src/devices/scope-summary.test.ts b/packages/app/src/devices/scope-summary.test.ts new file mode 100644 index 0000000000..eac3995149 --- /dev/null +++ b/packages/app/src/devices/scope-summary.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from "vitest"; +import { DAEMON_PERMISSIONS } from "@getpaseo/protocol/messages"; +import { formatConnectedDuration, summarizePermissions } from "./scope-summary"; + +describe("summarizePermissions", () => { + it("detects full access, read-only, and custom scope counts", () => { + expect(summarizePermissions(DAEMON_PERMISSIONS)).toEqual({ kind: "full" }); + expect(summarizePermissions(["daemon.read", "workspace.read"])).toEqual({ + kind: "read_only", + }); + expect(summarizePermissions(["workspace.read"])).toEqual({ kind: "read_only" }); + expect(summarizePermissions(["hub.execute", "workspace.read"])).toEqual({ + kind: "count", + count: 2, + }); + expect(summarizePermissions([])).toEqual({ kind: "count", count: 0 }); + }); +}); + +describe("formatConnectedDuration", () => { + const now = Date.parse("2026-11-28T15:00:00.000Z"); + + it("formats relative durations cleanly", () => { + expect(formatConnectedDuration("2026-11-28T14:59:30.000Z", now)).toEqual({ + kind: "just_now", + }); + expect(formatConnectedDuration("2026-11-28T14:46:00.000Z", now)).toEqual({ + kind: "minutes", + count: 14, + }); + expect(formatConnectedDuration("2026-11-28T13:00:00.000Z", now)).toEqual({ + kind: "hours", + count: 2, + }); + expect(formatConnectedDuration("2026-11-25T15:00:00.000Z", now)).toEqual({ + kind: "days", + count: 3, + }); + expect(formatConnectedDuration("not-a-date", now)).toBeNull(); + }); +}); diff --git a/packages/app/src/devices/scope-summary.ts b/packages/app/src/devices/scope-summary.ts new file mode 100644 index 0000000000..56b797aac3 --- /dev/null +++ b/packages/app/src/devices/scope-summary.ts @@ -0,0 +1,37 @@ +import { DAEMON_PERMISSIONS, type DaemonPermission } from "@getpaseo/protocol/messages"; + +const READ_ONLY_PERMISSIONS: ReadonlySet = new Set([ + "daemon.read", + "workspace.read", +]); + +export type PermissionSummary = + | { kind: "full" } + | { kind: "read_only" } + | { kind: "count"; count: number }; + +export function summarizePermissions(permissions: readonly DaemonPermission[]): PermissionSummary { + const unique = new Set(permissions); + if (unique.size >= DAEMON_PERMISSIONS.length) { + return { kind: "full" }; + } + if (unique.size > 0 && [...unique].every((permission) => READ_ONLY_PERMISSIONS.has(permission))) { + return { kind: "read_only" }; + } + return { kind: "count", count: unique.size }; +} + +export function formatConnectedDuration( + isoTimestamp: string, + nowMs = Date.now(), +): { kind: "just_now" } | { kind: "minutes" | "hours" | "days"; count: number } | null { + const parsedMs = Date.parse(isoTimestamp); + if (!Number.isFinite(parsedMs)) return null; + const elapsedSeconds = Math.max(0, Math.floor((nowMs - parsedMs) / 1000)); + if (elapsedSeconds < 60) return { kind: "just_now" }; + const minutes = Math.floor(elapsedSeconds / 60); + if (minutes < 60) return { kind: "minutes", count: minutes }; + const hours = Math.floor(minutes / 60); + if (hours < 24) return { kind: "hours", count: hours }; + return { kind: "days", count: Math.floor(hours / 24) }; +} diff --git a/packages/app/src/devices/ways-to-connect.tsx b/packages/app/src/devices/ways-to-connect.tsx index 9777a2f45a..09f135abd2 100644 --- a/packages/app/src/devices/ways-to-connect.tsx +++ b/packages/app/src/devices/ways-to-connect.tsx @@ -5,14 +5,26 @@ import { PairDeviceModal } from "./pair-device-modal"; import { CONNECTIVITY_DOCS_URL } from "./pair-device-section"; import { TailscaleRow } from "./tailscale-row"; +export interface WaysToConnectProps { + serverId: string; + /** When provided, tapping Relay delegates to the caller (e.g., to advance inside an existing sheet) instead of opening a stacked modal. */ + onOpenRelay?: () => void; +} + /** * The ways another device can connect to a host: Relay, which pairs through a QR code in a sheet, * and Tailscale, a switch and an address. Settings and the setup's phone step show this same block. */ -export function WaysToConnect({ serverId }: { serverId: string }) { +export function WaysToConnect({ serverId, onOpenRelay }: WaysToConnectProps) { const { t } = useTranslation(); const [pairing, setPairing] = useState(false); - const openPairing = useCallback(() => setPairing(true), []); + const openPairing = useCallback(() => { + if (onOpenRelay) { + onOpenRelay(); + return; + } + setPairing(true); + }, [onOpenRelay]); const closePairing = useCallback(() => setPairing(false), []); const docsLink = useMemo( () => ({ @@ -34,12 +46,14 @@ export function WaysToConnect({ serverId }: { serverId: string }) { /> - + {onOpenRelay ? null : ( + + )} ); } diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 05551653f9..ac8b2104e0 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -1958,6 +1958,69 @@ export const ar: TranslationResources = { confirmMessage: "هذا الجهاز متصل عبر Tailscale وسيفقد اتصاله بالمضيف.", confirmAction: "إيقاف", }, + connected: { + title: "العملاء المتصلون", + thisDevice: "هذا الجهاز", + loading: "جارٍ تحميل العملاء المتصلين...", + empty: "لا يوجد عملاء متصلون", + unavailable: "تعذّر تحميل العملاء المتصلين", + updateTitle: "حدّث هذا المضيف لعرض العملاء المتصلين", + updateHint: "هذا المضيف لا يبلّغ عن العملاء المتصلين بعد", + permissionTitle: "مطلوب إذن إدارة الوصول", + permissionHint: "جلستك لا تملك إذن عرض العملاء المتصلين", + errorTitle: "تعذّر تحميل العملاء المتصلين", + }, + hosts: { + title: "المضيفون المتصلون", + inbound: "وارد", + outbound: "صادر", + unnamed: "مضيف متصل", + routedCount: "{{count}} موجّهة", + routedSession: "جلسة موجّهة", + }, + scopes: { + fullAccess: "وصول كامل", + readOnly: "للقراءة فقط", + countOne: "نطاق واحد", + countOther: "{{count}} نطاقات", + none: "لا شيء", + }, + transport: { + local: "محلي", + tailscale: "Tailscale", + relay: "التتابع", + hub: "Hub", + direct: "مباشر", + }, + kind: { + desktop: "سطح المكتب", + web: "الويب", + mobile: "الجوّال", + hub: "Hub", + plugin: "إضافة", + client: "عميل", + }, + details: { + permissions: "الأذونات", + connected: "متصل", + lastSeen: "آخر اتصال", + status: "الحالة", + version: "الإصدار", + error: "خطأ", + }, + status: { + connecting: "جارٍ الاتصال", + reconnecting: "إعادة الاتصال", + offline: "غير متصل", + disabled: "معطّل", + error: "خطأ", + }, + time: { + justNow: "الآن", + minutesAgo: "منذ {{count}} د", + hoursAgo: "منذ {{count}} س", + daysAgo: "منذ {{count}} ي", + }, }, pairing: { hostPassword: { diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 01a91a3f5c..57cf4f4095 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -1988,6 +1988,69 @@ export const en = { "This device is connected through Tailscale and will lose its connection to the host.", confirmAction: "Turn off", }, + connected: { + title: "Connected clients", + thisDevice: "This device", + loading: "Loading connected clients...", + empty: "No connected clients", + unavailable: "Unable to load connected clients", + updateTitle: "Update this host to view connected clients", + updateHint: "This host does not report connected clients yet", + permissionTitle: "Access management required", + permissionHint: "Your session does not have permission to view connected clients", + errorTitle: "Could not load connected clients", + }, + hosts: { + title: "Connected hosts", + inbound: "Inbound", + outbound: "Outbound", + unnamed: "Connected host", + routedCount: "{{count}} routed", + routedSession: "Routed session", + }, + scopes: { + fullAccess: "Full access", + readOnly: "Read-only", + countOne: "1 scope", + countOther: "{{count}} scopes", + none: "None", + }, + transport: { + local: "Local", + tailscale: "Tailscale", + relay: "Relay", + hub: "Hub", + direct: "Direct", + }, + kind: { + desktop: "Desktop", + web: "Web", + mobile: "Mobile", + hub: "Hub", + plugin: "Plugin", + client: "Client", + }, + details: { + permissions: "Permissions", + connected: "Connected", + lastSeen: "Last online", + status: "Status", + version: "Version", + error: "Error", + }, + status: { + connecting: "Connecting", + reconnecting: "Reconnecting", + offline: "Offline", + disabled: "Disabled", + error: "Error", + }, + time: { + justNow: "Just now", + minutesAgo: "{{count}}m ago", + hoursAgo: "{{count}}h ago", + daysAgo: "{{count}}d ago", + }, }, pairing: { hostPassword: { diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 2b4cda4ab7..307df44786 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2012,6 +2012,69 @@ export const es: TranslationResources = { "Este dispositivo está conectado mediante Tailscale y perderá la conexión con el host.", confirmAction: "Desactivar", }, + connected: { + title: "Clientes conectados", + thisDevice: "Este dispositivo", + loading: "Cargando clientes conectados...", + empty: "No hay clientes conectados", + unavailable: "No se pudieron cargar los clientes conectados", + updateTitle: "Actualiza este host para ver los clientes conectados", + updateHint: "Este host todavía no informa de los clientes conectados", + permissionTitle: "Se requiere gestión de acceso", + permissionHint: "Tu sesión no tiene permiso para ver los clientes conectados", + errorTitle: "No se pudieron cargar los clientes conectados", + }, + hosts: { + title: "Hosts conectados", + inbound: "Entrante", + outbound: "Saliente", + unnamed: "Host conectado", + routedCount: "{{count}} enrutadas", + routedSession: "Sesión enrutada", + }, + scopes: { + fullAccess: "Acceso completo", + readOnly: "Solo lectura", + countOne: "1 ámbito", + countOther: "{{count}} ámbitos", + none: "Ninguno", + }, + transport: { + local: "Local", + tailscale: "Tailscale", + relay: "Relé", + hub: "Hub", + direct: "Directo", + }, + kind: { + desktop: "Escritorio", + web: "Web", + mobile: "Móvil", + hub: "Hub", + plugin: "Plugin", + client: "Cliente", + }, + details: { + permissions: "Permisos", + connected: "Conectado", + lastSeen: "Última conexión", + status: "Estado", + version: "Versión", + error: "Error", + }, + status: { + connecting: "Conectando", + reconnecting: "Reconectando", + offline: "Sin conexión", + disabled: "Desactivado", + error: "Error", + }, + time: { + justNow: "Ahora mismo", + minutesAgo: "hace {{count}} min", + hoursAgo: "hace {{count}} h", + daysAgo: "hace {{count}} d", + }, }, pairing: { hostPassword: { diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 3ec1dfd5f0..5d6d5256f8 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2009,6 +2009,69 @@ export const fr: TranslationResources = { confirmMessage: "Cet appareil est connecté via Tailscale et perdra sa connexion à l’hôte.", confirmAction: "Désactiver", }, + connected: { + title: "Clients connectés", + thisDevice: "Cet appareil", + loading: "Chargement des clients connectés...", + empty: "Aucun client connecté", + unavailable: "Impossible de charger les clients connectés", + updateTitle: "Mettez cet hôte à jour pour voir les clients connectés", + updateHint: "Cet hôte ne signale pas encore les clients connectés", + permissionTitle: "Gestion des accès requise", + permissionHint: "Votre session n’est pas autorisée à voir les clients connectés", + errorTitle: "Impossible de charger les clients connectés", + }, + hosts: { + title: "Hôtes connectés", + inbound: "Entrant", + outbound: "Sortant", + unnamed: "Hôte connecté", + routedCount: "{{count}} routées", + routedSession: "Session routée", + }, + scopes: { + fullAccess: "Accès complet", + readOnly: "Lecture seule", + countOne: "1 portée", + countOther: "{{count}} portées", + none: "Aucune", + }, + transport: { + local: "Local", + tailscale: "Tailscale", + relay: "Relais", + hub: "Hub", + direct: "Direct", + }, + kind: { + desktop: "Bureau", + web: "Web", + mobile: "Mobile", + hub: "Hub", + plugin: "Plugin", + client: "Client", + }, + details: { + permissions: "Autorisations", + connected: "Connecté", + lastSeen: "Dernière connexion", + status: "Statut", + version: "Version", + error: "Erreur", + }, + status: { + connecting: "Connexion", + reconnecting: "Reconnexion", + offline: "Hors ligne", + disabled: "Désactivé", + error: "Erreur", + }, + time: { + justNow: "À l’instant", + minutesAgo: "il y a {{count}} min", + hoursAgo: "il y a {{count}} h", + daysAgo: "il y a {{count}} j", + }, }, pairing: { hostPassword: { diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 610885746a..426f9960a9 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -1979,6 +1979,69 @@ export const ja: TranslationResources = { confirmMessage: "このデバイスは Tailscale 経由で接続しているため、ホストとの接続が切れます。", confirmAction: "オフにする", }, + connected: { + title: "接続中のクライアント", + thisDevice: "このデバイス", + loading: "接続中のクライアントを読み込み中...", + empty: "接続中のクライアントはありません", + unavailable: "接続中のクライアントを読み込めません", + updateTitle: "接続中のクライアントを表示するにはこのホストを更新してください", + updateHint: "このホストはまだ接続中のクライアントの報告に対応していません", + permissionTitle: "アクセス管理権限が必要です", + permissionHint: "このセッションには接続中のクライアントを表示する権限がありません", + errorTitle: "接続中のクライアントを読み込めませんでした", + }, + hosts: { + title: "接続されたホスト", + inbound: "インバウンド", + outbound: "アウトバウンド", + unnamed: "接続されたホスト", + routedCount: "{{count}} 件のルート", + routedSession: "ルーティング済みセッション", + }, + scopes: { + fullAccess: "フルアクセス", + readOnly: "読み取り専用", + countOne: "1 スコープ", + countOther: "{{count}} スコープ", + none: "なし", + }, + transport: { + local: "ローカル", + tailscale: "Tailscale", + relay: "リレー", + hub: "Hub", + direct: "ダイレクト", + }, + kind: { + desktop: "デスクトップ", + web: "Web", + mobile: "モバイル", + hub: "Hub", + plugin: "プラグイン", + client: "クライアント", + }, + details: { + permissions: "権限", + connected: "接続時間", + lastSeen: "最終オンライン", + status: "ステータス", + version: "バージョン", + error: "エラー", + }, + status: { + connecting: "接続中", + reconnecting: "再接続中", + offline: "オフライン", + disabled: "無効", + error: "エラー", + }, + time: { + justNow: "たった今", + minutesAgo: "{{count}}分前", + hoursAgo: "{{count}}時間前", + daysAgo: "{{count}}日前", + }, }, pairing: { hostPassword: { diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index b34dfea6d8..2fed6b5262 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -1970,6 +1970,69 @@ export const ko: TranslationResources = { confirmMessage: "이 기기는 Tailscale로 연결되어 있어 호스트와의 연결이 끊깁니다.", confirmAction: "끄기", }, + connected: { + title: "연결된 클라이언트", + thisDevice: "이 기기", + loading: "연결된 클라이언트를 불러오는 중...", + empty: "연결된 클라이언트가 없습니다", + unavailable: "연결된 클라이언트를 불러올 수 없습니다", + updateTitle: "연결된 클라이언트를 보려면 이 호스트를 업데이트하세요", + updateHint: "이 호스트는 아직 연결된 클라이언트 보고를 지원하지 않습니다", + permissionTitle: "접근 관리 권한이 필요합니다", + permissionHint: "현재 세션에는 연결된 클라이언트를 볼 권한이 없습니다", + errorTitle: "연결된 클라이언트를 불러오지 못했습니다", + }, + hosts: { + title: "연결된 호스트", + inbound: "인바운드", + outbound: "아웃바운드", + unnamed: "연결된 호스트", + routedCount: "라우팅 {{count}}개", + routedSession: "라우팅된 세션", + }, + scopes: { + fullAccess: "전체 권한", + readOnly: "읽기 전용", + countOne: "범위 1개", + countOther: "범위 {{count}}개", + none: "없음", + }, + transport: { + local: "로컬", + tailscale: "Tailscale", + relay: "릴레이", + hub: "Hub", + direct: "직접 연결", + }, + kind: { + desktop: "데스크톱", + web: "웹", + mobile: "모바일", + hub: "Hub", + plugin: "플러그인", + client: "클라이언트", + }, + details: { + permissions: "권한", + connected: "연결됨", + lastSeen: "마지막 온라인", + status: "상태", + version: "버전", + error: "오류", + }, + status: { + connecting: "연결 중", + reconnecting: "다시 연결 중", + offline: "오프라인", + disabled: "비활성화됨", + error: "오류", + }, + time: { + justNow: "방금 전", + minutesAgo: "{{count}}분 전", + hoursAgo: "{{count}}시간 전", + daysAgo: "{{count}}일 전", + }, }, pairing: { hostPassword: { diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 3d98834772..5f1392c0f5 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -1996,6 +1996,69 @@ export const ptBR: TranslationResources = { "Este dispositivo está conectado pelo Tailscale e perderá a conexão com o host.", confirmAction: "Desativar", }, + connected: { + title: "Clientes conectados", + thisDevice: "Este dispositivo", + loading: "Carregando clientes conectados...", + empty: "Nenhum cliente conectado", + unavailable: "Não foi possível carregar os clientes conectados", + updateTitle: "Atualize este host para ver clientes conectados", + updateHint: "Este host ainda não informa clientes conectados", + permissionTitle: "Gerenciamento de acesso necessário", + permissionHint: "Sua sessão não tem permissão para ver clientes conectados", + errorTitle: "Não foi possível carregar os clientes conectados", + }, + hosts: { + title: "Hosts conectados", + inbound: "Entrada", + outbound: "Saída", + unnamed: "Host conectado", + routedCount: "{{count}} roteadas", + routedSession: "Sessão roteada", + }, + scopes: { + fullAccess: "Acesso total", + readOnly: "Somente leitura", + countOne: "1 escopo", + countOther: "{{count}} escopos", + none: "Nenhum", + }, + transport: { + local: "Local", + tailscale: "Tailscale", + relay: "Relay", + hub: "Hub", + direct: "Direto", + }, + kind: { + desktop: "Desktop", + web: "Web", + mobile: "Celular", + hub: "Hub", + plugin: "Plugin", + client: "Cliente", + }, + details: { + permissions: "Permissões", + connected: "Conectado", + lastSeen: "Última vez online", + status: "Status", + version: "Versão", + error: "Erro", + }, + status: { + connecting: "Conectando", + reconnecting: "Reconectando", + offline: "Offline", + disabled: "Desativado", + error: "Erro", + }, + time: { + justNow: "Agora mesmo", + minutesAgo: "há {{count}}m", + hoursAgo: "há {{count}}h", + daysAgo: "há {{count}}d", + }, }, pairing: { hostPassword: { diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 5d5fedf6f2..1c1206f3f6 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -1995,6 +1995,69 @@ export const ru: TranslationResources = { confirmMessage: "Это устройство подключено через Tailscale и потеряет соединение с хостом.", confirmAction: "Выключить", }, + connected: { + title: "Подключённые клиенты", + thisDevice: "Это устройство", + loading: "Загрузка подключённых клиентов...", + empty: "Нет подключённых клиентов", + unavailable: "Не удалось загрузить подключённых клиентов", + updateTitle: "Обновите этот хост, чтобы видеть подключённых клиентов", + updateHint: "Этот хост ещё не передаёт список подключённых клиентов", + permissionTitle: "Требуются права управления доступом", + permissionHint: "У текущей сессии нет прав для просмотра подключённых клиентов", + errorTitle: "Не удалось загрузить подключённых клиентов", + }, + hosts: { + title: "Подключённые хосты", + inbound: "Входящее", + outbound: "Исходящее", + unnamed: "Подключённый хост", + routedCount: "{{count}} маршр.", + routedSession: "Маршрутизируемая сессия", + }, + scopes: { + fullAccess: "Полный доступ", + readOnly: "Только чтение", + countOne: "1 право", + countOther: "{{count}} прав", + none: "Нет", + }, + transport: { + local: "Локально", + tailscale: "Tailscale", + relay: "Ретранслятор", + hub: "Hub", + direct: "Напрямую", + }, + kind: { + desktop: "Десктоп", + web: "Веб", + mobile: "Мобильный", + hub: "Hub", + plugin: "Плагин", + client: "Клиент", + }, + details: { + permissions: "Разрешения", + connected: "Подключено", + lastSeen: "Последний раз в сети", + status: "Статус", + version: "Версия", + error: "Ошибка", + }, + status: { + connecting: "Подключение", + reconnecting: "Переподключение", + offline: "Не в сети", + disabled: "Отключено", + error: "Ошибка", + }, + time: { + justNow: "Только что", + minutesAgo: "{{count}} мин назад", + hoursAgo: "{{count}} ч назад", + daysAgo: "{{count}} дн назад", + }, }, pairing: { hostPassword: { diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 44024a663e..2ebcd846f2 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -1940,6 +1940,69 @@ export const zhCN: TranslationResources = { confirmMessage: "此设备通过 Tailscale 连接,关闭后将与主机断开连接。", confirmAction: "关闭", }, + connected: { + title: "已连接的客户端", + thisDevice: "此设备", + loading: "正在加载已连接的客户端...", + empty: "没有已连接的客户端", + unavailable: "无法加载已连接的客户端", + updateTitle: "更新此主机以查看已连接的客户端", + updateHint: "此主机暂不支持报告已连接的客户端", + permissionTitle: "需要访问管理权限", + permissionHint: "当前会话无权查看已连接的客户端", + errorTitle: "无法加载已连接的客户端", + }, + hosts: { + title: "已连接的主机", + inbound: "入站", + outbound: "出站", + unnamed: "已连接的主机", + routedCount: "{{count}} 个路由", + routedSession: "路由会话", + }, + scopes: { + fullAccess: "完全访问", + readOnly: "只读", + countOne: "1 项权限", + countOther: "{{count}} 项权限", + none: "无", + }, + transport: { + local: "本地", + tailscale: "Tailscale", + relay: "中继", + hub: "Hub", + direct: "直连", + }, + kind: { + desktop: "桌面端", + web: "网页端", + mobile: "移动端", + hub: "Hub", + plugin: "插件", + client: "客户端", + }, + details: { + permissions: "权限", + connected: "连接时间", + lastSeen: "上次在线", + status: "状态", + version: "版本", + error: "错误", + }, + status: { + connecting: "连接中", + reconnecting: "重新连接中", + offline: "离线", + disabled: "已禁用", + error: "错误", + }, + time: { + justNow: "刚刚", + minutesAgo: "{{count}} 分钟前", + hoursAgo: "{{count}} 小时前", + daysAgo: "{{count}} 天前", + }, }, pairing: { hostPassword: { diff --git a/packages/app/src/runtime/host-runtime.ts b/packages/app/src/runtime/host-runtime.ts index 5c59aed77c..e4f9b1c383 100644 --- a/packages/app/src/runtime/host-runtime.ts +++ b/packages/app/src/runtime/host-runtime.ts @@ -43,6 +43,7 @@ import { shouldUseTlsForDefaultHostedRelay, } from "@/utils/daemon-endpoints"; import { resolveAppVersion } from "@/utils/app-version"; +import { resolveAppClientIdentity } from "@/devices/client-info"; import { ConnectionOfferSchema, type ConnectionOffer } from "@getpaseo/protocol/connection-offer"; import { HostConfirmations, type HostConfirmationRequest } from "./host-confirmation"; import { shouldUseDesktopDaemon } from "@/desktop/daemon/desktop-daemon"; @@ -584,10 +585,12 @@ function createDefaultDeps( createClient: ({ host, connection, clientId, runtimeGeneration }) => { const desktopTransportFactory = createDesktopDaemonTransportFactory(); const webSocketConfig = { webSocketFactory: createAppWebSocketFactory() }; + const appIdentity = resolveAppClientIdentity(); const base = { suppressSendErrors: true, clientId, - clientType: "mobile", + clientType: appIdentity.clientType, + clientInfo: appIdentity.clientInfo, appVersion: resolveAppVersion() ?? undefined, runtimeGeneration, capabilities: appCapabilities, diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index cb685e387b..fbd2f4ad2a 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -94,6 +94,7 @@ import { type AppLanguage, type SupportedLocale, } from "@/i18n/locales"; +import { PairDeviceHeaderAction } from "@/devices"; import { HostDevicesPage, HostToolsPage, @@ -1453,11 +1454,12 @@ export default function SettingsScreen({ view }: SettingsScreenProps) { const pluginGalleryServerId = view.kind === "host" && view.section === "plugins" ? view.serverId : null; - const detailActions = useMemo( - () => - pluginGalleryServerId ? : undefined, - [pluginGalleryServerId], - ); + const devicesServerId = view.kind === "host" && view.section === "devices" ? view.serverId : null; + const detailActions = useMemo(() => { + if (pluginGalleryServerId) return ; + if (devicesServerId) return ; + return undefined; + }, [devicesServerId, pluginGalleryServerId]); // The gallery and a plugin's page share one width, so opening a plugin keeps the page edges put. const detailWidth = pluginGalleryServerId || pluginPage ? "wide" : "default"; diff --git a/packages/app/src/screens/settings/host-page.tsx b/packages/app/src/screens/settings/host-page.tsx index 0bc2f3db7b..b6f9233efc 100644 --- a/packages/app/src/screens/settings/host-page.tsx +++ b/packages/app/src/screens/settings/host-page.tsx @@ -35,7 +35,7 @@ import { TerminalProfileEditModal, } from "@/screens/settings/terminal-profile-edit-modal"; import { LocalDaemonSection } from "@/desktop/components/desktop-updates-section"; -import { WaysToConnect } from "@/devices"; +import { ConnectedDevicesView } from "@/devices"; import { useDaemonConfig } from "@/hooks/use-daemon-config"; import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon"; import { useHostFeature } from "@/runtime/host-features"; @@ -238,7 +238,7 @@ export function HostDevicesPage({ serverId }: { serverId: string }) { return ; } - return ; + return ; } export function HostToolsPage({ serverId }: { serverId: string }) { diff --git a/packages/app/src/stores/session-store.ts b/packages/app/src/stores/session-store.ts index 99e0972033..ad67d4f715 100644 --- a/packages/app/src/stores/session-store.ts +++ b/packages/app/src/stores/session-store.ts @@ -298,6 +298,7 @@ export interface DaemonServerInfo { version: string | null; machineKind?: string | null; desktopManaged?: boolean; + permissions?: ServerInfoStatusPayload["permissions"]; capabilities?: ServerCapabilities; features?: ServerInfoStatusPayload["features"]; } @@ -311,6 +312,7 @@ export function toDaemonServerInfo(serverInfo: ServerInfoStatusPayload): DaemonS ...(serverInfo.desktopManaged !== undefined ? { desktopManaged: serverInfo.desktopManaged } : {}), + ...(serverInfo.permissions ? { permissions: serverInfo.permissions } : {}), ...(serverInfo.capabilities ? { capabilities: serverInfo.capabilities } : {}), ...(serverInfo.features ? { features: serverInfo.features } : {}), }; diff --git a/packages/client/src/daemon-client-core.ts b/packages/client/src/daemon-client-core.ts index 19d79a4ab3..cbf81f80a4 100644 --- a/packages/client/src/daemon-client-core.ts +++ b/packages/client/src/daemon-client-core.ts @@ -16,6 +16,7 @@ import { } from "@getpaseo/protocol/binary-frames/host-route"; import { messageTooLargeError } from "./daemon-client-transport-utils.js"; import type { HostAdd, HostUpdate, HostDirectory } from "@getpaseo/protocol/hosts"; +import type { DaemonClientsSnapshot, HelloClientInfo } from "@getpaseo/protocol/daemon-clients"; import type { PluginListingDetail, PluginListingIndex } from "@getpaseo/protocol/plugin-registry"; import { legacyUsageIcon } from "./legacy-usage-icons.js"; import { subscribeTimeline, type TimelineMessage } from "./timeline-subscription/index.js"; @@ -456,6 +457,7 @@ export interface DaemonClientConfig { createPluginClientBundleStore?: (serverId: string) => PluginClientBundleStore; clientType?: "mobile" | "browser" | "cli" | "mcp" | "hub"; appVersion?: string; + clientInfo?: HelloClientInfo; runtimeGeneration?: number | null; password?: string; localCredential?: () => string | undefined | Promise; @@ -1961,6 +1963,40 @@ export class DaemonClientCore { return snapshot; }); } + async listConnectedClients(options?: { + includeInternal?: boolean; + }): Promise { + const result = await this.sendCorrelatedSessionRequest({ + message: { + type: "daemon.clients.list.request", + ...(options?.includeInternal ? { includeInternal: true } : {}), + }, + responseType: "daemon.clients.list.response", + }); + return { clients: result.clients, inboundDaemons: result.inboundDaemons }; + } + observeConnectedClients(options?: { + includeInternal?: boolean; + }): OwnedSubscription { + return this.owned.observe(async (accept) => { + const result = await this.sendCorrelatedSessionRequest({ + message: { + type: "daemon.clients.list.request", + observe: true, + ...(options?.includeInternal ? { includeInternal: true } : {}), + }, + responseType: "daemon.clients.list.response", + }); + if (!result.subscriptionId) throw new Error("Host omitted subscription identity"); + const snapshot = { + clients: result.clients, + inboundDaemons: result.inboundDaemons, + subscriptionId: result.subscriptionId, + }; + accept(snapshot); + return snapshot; + }); + } async addHost(input: HostAdd) { this.requireConnectedHosts(); return ( @@ -7651,6 +7687,7 @@ export class DaemonClientCore { ...this.config.capabilities, }, ...(this.config.appVersion ? { appVersion: this.config.appVersion } : {}), + ...(this.config.clientInfo ? { clientInfo: this.config.clientInfo } : {}), }); } catch (error) { const message = error instanceof Error ? error.message : "Failed to send hello message"; diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 1a056de459..bc07cdf987 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -6,6 +6,17 @@ export type { AgentAddress } from "@getpaseo/protocol/addresses"; import { createHostActions, type PaseoHostActions } from "./hosts/index.js"; export type { PaseoHostActions } from "./hosts/index.js"; export type { HostAdd, HostUpdate, HostSummary, HostDirectory } from "@getpaseo/protocol/hosts"; +export type { + ConnectedClientKind, + ConnectedClientSummary, + ConnectedClientTransport, + DaemonClientsSnapshot, + HelloClientInfo, + HelloClientKind, + HelloClientPlatform, + InboundDaemonSummary, + RoutedClientSummary, +} from "@getpaseo/protocol/daemon-clients"; import type { OwnedSubscription } from "./connection/index.js"; export type { OwnedSubscription, SubscriptionObserver } from "./connection/index.js"; import type { DaemonClientConfig } from "./daemon-client.js"; diff --git a/packages/protocol/src/daemon-clients.ts b/packages/protocol/src/daemon-clients.ts new file mode 100644 index 0000000000..17b0a8cf37 --- /dev/null +++ b/packages/protocol/src/daemon-clients.ts @@ -0,0 +1,137 @@ +import { z } from "zod"; +import { DaemonPermissionSchema } from "./daemon-permissions.js"; + +export const HelloClientPlatformSchema = z.enum([ + "macos", + "linux", + "windows", + "ios", + "android", + "web", + "unknown", +]); +export type HelloClientPlatform = z.infer; + +export const HelloClientKindSchema = z.enum([ + "desktop", + "mobile", + "web", + "cli", + "mcp", + "hub", + "daemon", + "plugin", +]); +export type HelloClientKind = z.infer; + +export const HelloClientInfoSchema = z.object({ + name: z.string().max(128).optional(), + platform: HelloClientPlatformSchema.optional(), + kind: HelloClientKindSchema.optional(), + peerServerId: z.string().max(256).optional(), +}); +export type HelloClientInfo = z.infer; + +export const ConnectedClientKindSchema = z.enum([ + "desktop", + "mobile", + "web", + "cli", + "mcp", + "hub", + "plugin", + "unknown", +]); +export type ConnectedClientKind = z.infer; + +export const ConnectedClientTransportSchema = z.enum([ + "local_ipc", + "local", + "tailscale", + "direct", + "relay", + "hub", +]); +export type ConnectedClientTransport = z.infer; + +export const ConnectedClientSummarySchema = z.object({ + sessionId: z.string(), + clientId: z.string(), + isCurrentSession: z.boolean(), + principalId: z.string(), + kind: ConnectedClientKindSchema, + name: z.string().nullable(), + platform: z.string().nullable(), + appVersion: z.string().nullable(), + transport: ConnectedClientTransportSchema, + securityMode: z.enum(["protected", "legacy"]).optional(), + hubOrigin: z.string().nullable().optional(), + permissions: z.array(DaemonPermissionSchema), + attenuated: z.boolean(), + connectedAt: z.string(), + socketCount: z.number().int().nonnegative(), +}); +export type ConnectedClientSummary = z.infer; + +export const RoutedClientSummarySchema = z.object({ + sessionId: z.string(), + sourceId: z.string(), + name: z.string().nullable(), + kind: ConnectedClientKindSchema, + appVersion: z.string().nullable(), + permissions: z.array(DaemonPermissionSchema), + attenuated: z.boolean(), + connectedAt: z.string(), +}); +export type RoutedClientSummary = z.infer; + +export const InboundDaemonSummarySchema = z.object({ + sessionId: z.string(), + peerServerId: z.string().nullable(), + name: z.string().nullable(), + appVersion: z.string().nullable(), + principalId: z.string(), + transport: ConnectedClientTransportSchema, + securityMode: z.enum(["protected", "legacy"]).optional(), + permissions: z.array(DaemonPermissionSchema), + connectedAt: z.string(), + socketCount: z.number().int().nonnegative(), + routedSessions: z.array(RoutedClientSummarySchema), +}); +export type InboundDaemonSummary = z.infer; + +export const DaemonClientsSnapshotSchema = z.object({ + clients: z.array(ConnectedClientSummarySchema), + inboundDaemons: z.array(InboundDaemonSummarySchema), +}); +export type DaemonClientsSnapshot = z.infer; + +export const DaemonClientsListRequestSchema = z.object({ + type: z.literal("daemon.clients.list.request"), + requestId: z.string(), + observe: z.boolean().optional(), + includeInternal: z.boolean().optional(), +}); + +export const DaemonClientsListResponseSchema = z.object({ + type: z.literal("daemon.clients.list.response"), + payload: z.object({ + requestId: z.string(), + subscriptionId: z.string().optional(), + clients: z.array(ConnectedClientSummarySchema), + inboundDaemons: z.array(InboundDaemonSummarySchema), + }), +}); + +export const DaemonClientsChangedSchema = z.object({ + type: z.literal("daemon.clients.changed"), + payload: z.object({ + subscriptionId: z.string(), + clients: z.array(ConnectedClientSummarySchema), + inboundDaemons: z.array(InboundDaemonSummarySchema), + }), +}); + +export type DaemonClientsListRequest = z.infer; +export type DaemonClientsListResponse = z.infer; +export type DaemonClientsChanged = z.infer; diff --git a/packages/protocol/src/daemon-permissions.ts b/packages/protocol/src/daemon-permissions.ts new file mode 100644 index 0000000000..7ab5e2cb2c --- /dev/null +++ b/packages/protocol/src/daemon-permissions.ts @@ -0,0 +1,16 @@ +import { z } from "zod"; + +export const DAEMON_PERMISSIONS = [ + "daemon.read", + "daemon.manage", + "tunnel.manage", + "access.manage", + "workspace.read", + "workspace.write", + "workspace.manage", + "automation.manage", + "hub.execute", +] as const; + +export const DaemonPermissionSchema = z.enum(DAEMON_PERMISSIONS); +export type DaemonPermission = z.infer; diff --git a/packages/protocol/src/hosts.ts b/packages/protocol/src/hosts.ts index 8311d4268c..279db0172d 100644 --- a/packages/protocol/src/hosts.ts +++ b/packages/protocol/src/hosts.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { DaemonPermissionSchema } from "./daemon-permissions.js"; export const HostMetadataSchema = z.record(z.string().max(256), z.string().max(4096)); export const HostAddSchema = z.object({ @@ -26,6 +27,10 @@ export const HostSummarySchema = z.object({ lastOnlineAt: z.string().nullable(), nextRetryAt: z.string().nullable(), error: z.object({ code: z.string(), message: z.string() }).nullable(), + // COMPAT(connectedClients): added in v0.19.0; older daemons omit version, permissions, and connectedAt. + version: z.string().nullable().optional(), + permissions: z.array(DaemonPermissionSchema).optional(), + connectedAt: z.string().nullable().optional(), }); export const HostDirectorySchema = z.object({ self: z.object({ serverId: z.string(), label: z.string() }), diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 91882fdb7b..4adcd9856d 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -1,4 +1,16 @@ import { AgentMessageSchema } from "./agent-message.js"; +import { + DAEMON_PERMISSIONS, + DaemonPermissionSchema, + type DaemonPermission, +} from "./daemon-permissions.js"; +import { + HelloClientInfoSchema, + DaemonClientsListRequestSchema, + DaemonClientsListResponseSchema, + DaemonClientsChangedSchema, +} from "./daemon-clients.js"; +export * from "./daemon-clients.js"; import { HostsListRequestSchema, HostsAddRequestSchema, @@ -174,19 +186,7 @@ export { // Mutable daemon config schemas (shared between server store and client) // --------------------------------------------------------------------------- -export const DAEMON_PERMISSIONS = [ - "daemon.read", - "daemon.manage", - "tunnel.manage", - "access.manage", - "workspace.read", - "workspace.write", - "workspace.manage", - "automation.manage", - "hub.execute", -] as const; -export const DaemonPermissionSchema = z.enum(DAEMON_PERMISSIONS); -export type DaemonPermission = z.infer; +export { DAEMON_PERMISSIONS, DaemonPermissionSchema, type DaemonPermission }; export const HexColorSchema = z .string() @@ -3656,6 +3656,7 @@ export const SubscriptionReleaseResponseSchema = z.object({ }); export const SessionInboundMessageSchema = z.discriminatedUnion("type", [ + DaemonClientsListRequestSchema, HostsListRequestSchema, HostsAddRequestSchema, HostsUpdateRequestSchema, @@ -4138,6 +4139,8 @@ export const ServerInfoStatusPayloadSchema = z // COMPAT(daemonStatusRpc): added in v0.1.76, remove gate after 2026-11-18. daemonStatusRpc: z.boolean().optional(), tailscale: z.boolean().optional(), + // COMPAT(connectedClients): added in v0.19.0, remove gate after 2027-06-01. + connectedClients: z.boolean().optional(), // COMPAT(daemonConfigReload): added in v0.4.0, remove gate after 2027-02-14. daemonConfigReload: z.boolean().optional(), // COMPAT(speechSettings): added in v0.12.0, remove gate after 2027-04-18. @@ -7875,6 +7878,8 @@ export const AgentSkillsImportLegacySelectionResponseSchema = z.object({ }); export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [ + DaemonClientsListResponseSchema, + DaemonClientsChangedSchema, HostsListResponseSchema, HostsChangedSchema, HostsAddResponseSchema, @@ -8676,6 +8681,8 @@ export const WSHelloMessageSchema = z.object({ ]) .optional(), appVersion: z.string().optional(), + // COMPAT(connectedClients): added in v0.19.0; older clients omit clientInfo and older daemons ignore it. + clientInfo: HelloClientInfoSchema.optional(), capabilities: z .object({ voice: z.boolean().optional(), diff --git a/packages/server/src/server/authorization/operation-permissions.ts b/packages/server/src/server/authorization/operation-permissions.ts index fafc6e877d..0694513265 100644 --- a/packages/server/src/server/authorization/operation-permissions.ts +++ b/packages/server/src/server/authorization/operation-permissions.ts @@ -83,6 +83,7 @@ const INBOUND_PERMISSION = { "creation.subscribe.request": "workspace.read", create_paseo_worktree_request: "workspace.manage", create_terminal_request: "workspace.write", + "daemon.clients.list.request": "access.manage", "daemon.config.reload.request": "daemon.manage", "daemon.get_pairing_offer.request": "access.manage", "daemon.get_status.request": "daemon.read", @@ -344,6 +345,8 @@ const OUTBOUND_PERMISSION = { close_items_response: "workspace.manage", create_paseo_worktree_response: "workspace.manage", create_terminal_response: "workspace.write", + "daemon.clients.list.response": "access.manage", + "daemon.clients.changed": "access.manage", "daemon.config.reload.response": "daemon.manage", "daemon.get_pairing_offer.response": "access.manage", "daemon.get_status.response": "daemon.read", diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index f75551f0ff..7f33352d86 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -1928,6 +1928,7 @@ export async function createPaseoDaemon( { listen: formatListenTarget(boundListenTarget ?? listenTarget), getListenStatus: listeners.refreshStatus, + isTailscaleEndpoint: listeners.isTailscaleEndpoint, setTailscaleEnabled: (enabled, localEndpoint, confirmed) => daemonConfigStore.setTailscaleEnabled(enabled, localEndpoint, confirmed), worktreesRoot: config.worktreesRoot, diff --git a/packages/server/src/server/connected-clients.e2e.test.ts b/packages/server/src/server/connected-clients.e2e.test.ts new file mode 100644 index 0000000000..13e3711552 --- /dev/null +++ b/packages/server/src/server/connected-clients.e2e.test.ts @@ -0,0 +1,184 @@ +import { afterEach, describe, expect, test } from "vitest"; +import { createPaseoApi, type DaemonClientsSnapshot } from "@getpaseo/client"; +import { createHostClient } from "@getpaseo/client/node"; +import { createTestPaseoDaemon, type TestPaseoDaemon } from "./test-utils/paseo-daemon.js"; + +const cleanup: Array<() => Promise> = []; + +afterEach(async () => { + for (const close of cleanup.splice(0).toReversed()) { + await close(); + } +}); + +async function startDaemon(): Promise { + const instance = await createTestPaseoDaemon(); + cleanup.push(() => instance.close()); + return instance; +} + +function findClientSocketCount( + snapshots: readonly DaemonClientsSnapshot[], + clientId: string, +): number | undefined { + return snapshots.at(-1)?.clients.find((entry) => entry.clientId === clientId)?.socketCount; +} + +describe("daemon.clients.list", () => { + test("lists and observes live clients with clientInfo, scopes, and access.manage enforcement", async () => { + const host = await startDaemon(); + + const owner = createHostClient(`127.0.0.1:${host.port}`, { + clientId: "cid_desktop_owner", + clientType: "mobile", + appVersion: "0.18.1", + clientInfo: { name: "Mo's MacBook Pro", platform: "macos", kind: "desktop" }, + reconnect: { enabled: false }, + }); + await owner.connect(); + cleanup.push(() => owner.close()); + + expect(owner.getLastServerInfoMessage()?.features?.connectedClients).toBe(true); + + const observed: DaemonClientsSnapshot[] = []; + const subscription = owner.observeConnectedClients(); + const unsubscribe = subscription.subscribe({ + snapshot: (snapshot) => observed.push(snapshot), + update: (message) => { + if (message.type === "daemon.clients.changed") { + observed.push({ + clients: message.payload.clients, + inboundDaemons: message.payload.inboundDaemons, + }); + } + }, + }); + cleanup.push(async () => { + unsubscribe(); + await subscription.release(); + }); + + const initial = await subscription.ready; + expect(initial.clients).toHaveLength(1); + expect(initial.clients[0]).toMatchObject({ + clientId: "cid_desktop_owner", + isCurrentSession: true, + name: "Mo's MacBook Pro", + kind: "desktop", + platform: "macos", + appVersion: "0.18.1", + transport: "local", + attenuated: false, + socketCount: 1, + }); + + // Connect a second client with narrowed read-only permissions. + const viewer = createHostClient(`127.0.0.1:${host.port}`, { + clientId: "cid_phone_viewer", + clientType: "mobile", + appVersion: "0.18.1", + clientInfo: { name: "Mo's iPhone", platform: "ios", kind: "mobile" }, + sessionPermissions: ["daemon.read", "workspace.read"], + reconnect: { enabled: false }, + }); + await viewer.connect(); + cleanup.push(() => viewer.close()); + + await expect.poll(() => observed.at(-1)?.clients.length ?? 0, { timeout: 5000 }).toBe(2); + + const latest = observed.at(-1)!; + const phone = latest.clients.find((entry) => entry.clientId === "cid_phone_viewer"); + expect(phone).toMatchObject({ + isCurrentSession: false, + name: "Mo's iPhone", + kind: "mobile", + platform: "ios", + permissions: ["daemon.read", "workspace.read"], + attenuated: true, + socketCount: 1, + }); + + // The read-only client lacks access.manage and must be denied. + await expect(viewer.listConnectedClients()).rejects.toThrow(); + + // Closing the second client drops its live socketCount to 0 (reconnect grace) and notifies observers. + await viewer.close(); + await expect + .poll(() => findClientSocketCount(observed, "cid_phone_viewer"), { timeout: 5000 }) + .toBe(0); + }); + + test("reports outbound host scopes/version on A and inbound daemon + routed sessions on B", async () => { + const a = await startDaemon(); + const b = await startDaemon(); + + const clientA = createHostClient(`127.0.0.1:${a.port}`, { + clientId: "cid_a_owner", + clientType: "mobile", + clientInfo: { name: "Laptop", platform: "macos", kind: "desktop" }, + reconnect: { enabled: false }, + }); + await clientA.connect(); + const paseoA = createPaseoApi(clientA); + cleanup.push(async () => { + await paseoA.dispose(); + await clientA.close(); + }); + + const clientB = createHostClient(`127.0.0.1:${b.port}`, { + clientId: "cid_b_owner", + clientType: "mobile", + clientInfo: { name: "Server UI", platform: "linux", kind: "desktop" }, + reconnect: { enabled: false }, + }); + await clientB.connect(); + cleanup.push(() => clientB.close()); + + await paseoA.hosts.add({ + connection: `127.0.0.1:${b.port}`, + label: "build-box", + }); + + let outboundHost: Awaited>["hosts"][number] | undefined; + await expect + .poll( + async () => { + const dir = await paseoA.hosts.list(); + outboundHost = dir.hosts[0]; + return outboundHost?.status; + }, + { timeout: 15000 }, + ) + .toBe("online"); + + expect(outboundHost?.version).toBeTruthy(); + expect(outboundHost?.permissions?.length).toBeGreaterThan(0); + expect(outboundHost?.connectedAt).toBeTruthy(); + + // Open a routed client from A to B so B observes both the inbound daemon link and its routed session. + const serverIdA = clientA.getLastServerInfoMessage()!.serverId; + const serverIdB = clientB.getLastServerInfoMessage()!.serverId; + const remoteB = await paseoA.hosts.client(serverIdB); + cleanup.push(() => remoteB.dispose()); + + await expect + .poll( + async () => { + const snapshot = await clientB.listConnectedClients(); + return snapshot.inboundDaemons[0]?.routedSessions.length ?? 0; + }, + { timeout: 10000 }, + ) + .toBe(1); + + const snapshotB = await clientB.listConnectedClients(); + expect(snapshotB.inboundDaemons).toHaveLength(1); + expect(snapshotB.inboundDaemons[0]).toMatchObject({ + peerServerId: serverIdA, + transport: "local", + socketCount: 1, + }); + expect(snapshotB.inboundDaemons[0]?.permissions.length).toBeGreaterThan(0); + expect(snapshotB.inboundDaemons[0]?.routedSessions).toHaveLength(1); + }); +}); diff --git a/packages/server/src/server/connected-clients.test.ts b/packages/server/src/server/connected-clients.test.ts new file mode 100644 index 0000000000..0417043738 --- /dev/null +++ b/packages/server/src/server/connected-clients.test.ts @@ -0,0 +1,181 @@ +import { describe, expect, it } from "vitest"; +import { OWNER_PERMISSIONS } from "./authorization/index.js"; +import { buildConnectedClientsSnapshot, type ConnectedClientRecord } from "./connected-clients.js"; + +function makeRecord(overrides: Partial = {}): ConnectedClientRecord { + return { + sessionId: "sess_1", + clientId: "cid_1", + principalId: "owner", + sourceId: "owner", + clientType: "mobile", + clientInfo: { name: "Mo's MacBook Pro", platform: "macos", kind: "desktop" }, + appVersion: "0.18.1", + permissions: OWNER_PERMISSIONS, + principalPermissions: OWNER_PERMISSIONS, + connectedAt: "2026-11-28T10:00:00.000Z", + socketCount: 1, + isCurrentSession: false, + isEphemeralPlugin: false, + pluginId: null, + isRouted: false, + identity: { transport: "direct", peer: "local_ipc" }, + hubOrigin: null, + routedChildren: [], + hasHostLink: false, + ...overrides, + }; +} + +describe("buildConnectedClientsSnapshot", () => { + it("sorts current session first, classifies transports, and tracks attenuated scopes", () => { + const snapshot = buildConnectedClientsSnapshot( + [ + makeRecord({ + sessionId: "sess_hub", + clientId: "hub:dmn_1", + principalId: "hub:dmn_1", + clientType: "hub", + clientInfo: null, + appVersion: null, + permissions: ["hub.execute", "workspace.read"], + principalPermissions: ["hub.execute", "workspace.read"], + identity: { transport: "hub", peer: "external", hubDaemonId: "dmn_1" }, + hubOrigin: "https://hub.paseo.sh", + connectedAt: "2026-11-25T10:00:00.000Z", + }), + makeRecord({ + sessionId: "sess_phone", + clientId: "cid_phone", + clientInfo: { name: "Mo's iPhone", platform: "ios", kind: "mobile" }, + permissions: ["daemon.read", "workspace.read"], + principalPermissions: OWNER_PERMISSIONS, + identity: { + transport: "direct", + peer: "external", + localEndpoint: "100.87.1.2:6767", + }, + connectedAt: "2026-11-28T11:00:00.000Z", + }), + makeRecord({ + sessionId: "sess_me", + clientId: "cid_me", + isCurrentSession: true, + connectedAt: "2026-11-28T12:00:00.000Z", + }), + ], + { + isTailscaleEndpoint: (endpoint) => endpoint === "100.87.1.2:6767", + }, + ); + + expect(snapshot.clients.map((entry) => entry.sessionId)).toEqual([ + "sess_me", + "sess_hub", + "sess_phone", + ]); + expect(snapshot.clients[0]).toMatchObject({ + isCurrentSession: true, + kind: "desktop", + transport: "local_ipc", + attenuated: false, + }); + expect(snapshot.clients[1]).toMatchObject({ + kind: "hub", + name: "Paseo Hub", + transport: "hub", + hubOrigin: "https://hub.paseo.sh", + permissions: ["hub.execute", "workspace.read"], + attenuated: false, + }); + expect(snapshot.clients[2]).toMatchObject({ + kind: "mobile", + name: "Mo's iPhone", + transport: "tailscale", + permissions: ["daemon.read", "workspace.read"], + attenuated: true, + }); + }); + + it("hides ephemeral plugin and cli/mcp sessions by default unless includeInternal is true", () => { + const records = [ + makeRecord({ sessionId: "sess_app", isCurrentSession: true }), + makeRecord({ + sessionId: "sess_cli", + clientId: "cli_1", + clientType: "cli", + clientInfo: null, + }), + makeRecord({ + sessionId: "sess_plugin", + clientId: "plugin:foo", + clientType: "cli", + clientInfo: null, + isEphemeralPlugin: true, + pluginId: "foo", + }), + ]; + + expect(buildConnectedClientsSnapshot(records).clients.map((c) => c.sessionId)).toEqual([ + "sess_app", + ]); + expect( + buildConnectedClientsSnapshot(records, { includeInternal: true }).clients.map( + (c) => c.sessionId, + ), + ).toEqual(["sess_app", "sess_cli", "sess_plugin"]); + }); + + it("separates inbound daemons and nests their active routed sessions", () => { + const routedChild = makeRecord({ + sessionId: "sess_routed", + clientId: "link-abc", + sourceId: "route:owner:srv_peer:owner", + clientInfo: { name: "Mo's iPhone", platform: "ios", kind: "mobile" }, + permissions: ["daemon.read", "workspace.read"], + principalPermissions: ["daemon.read", "workspace.read", "workspace.write"], + isRouted: true, + }); + + const peerDaemon = makeRecord({ + sessionId: "sess_peer", + clientId: "host-link-srv_peer-hst_123", + clientType: "cli", + clientInfo: { name: "mac-studio", kind: "daemon", peerServerId: "srv_peer" }, + permissions: ["daemon.read", "workspace.read", "workspace.write"], + principalPermissions: ["daemon.read", "workspace.read", "workspace.write"], + identity: { transport: "relay", peer: "external", securityMode: "protected" }, + hasHostLink: true, + routedChildren: [routedChild], + }); + + const snapshot = buildConnectedClientsSnapshot([peerDaemon, routedChild]); + expect(snapshot.clients).toEqual([]); + expect(snapshot.inboundDaemons).toEqual([ + { + sessionId: "sess_peer", + peerServerId: "srv_peer", + name: "mac-studio", + appVersion: "0.18.1", + principalId: "owner", + transport: "relay", + securityMode: "protected", + permissions: ["daemon.read", "workspace.read", "workspace.write"], + connectedAt: "2026-11-28T10:00:00.000Z", + socketCount: 1, + routedSessions: [ + { + sessionId: "sess_routed", + sourceId: "route:owner:srv_peer:owner", + name: "Mo's iPhone", + kind: "mobile", + appVersion: "0.18.1", + permissions: ["daemon.read", "workspace.read"], + attenuated: true, + connectedAt: "2026-11-28T10:00:00.000Z", + }, + ], + }, + ]); + }); +}); diff --git a/packages/server/src/server/connected-clients.ts b/packages/server/src/server/connected-clients.ts new file mode 100644 index 0000000000..43557b2663 --- /dev/null +++ b/packages/server/src/server/connected-clients.ts @@ -0,0 +1,289 @@ +import type { + ConnectedClientKind, + ConnectedClientSummary, + ConnectedClientTransport, + DaemonClientsSnapshot, + DaemonPermission, + HelloClientInfo, + InboundDaemonSummary, + RoutedClientSummary, + WSHelloMessage, +} from "@getpaseo/protocol/messages"; + +export interface ConnectedClientIdentity { + transport: "direct" | "relay" | "hub"; + peer: "loopback" | "local_ipc" | "external"; + securityMode?: "protected" | "legacy"; + userAgent?: string; + localEndpoint?: string; + hubDaemonId?: string; +} + +export interface ConnectedClientRecord { + sessionId: string; + clientId: string; + principalId: string; + sourceId: string; + clientType: WSHelloMessage["clientType"]; + clientInfo: HelloClientInfo | null; + appVersion: string | null; + permissions: readonly DaemonPermission[]; + principalPermissions: readonly DaemonPermission[]; + connectedAt: string; + socketCount: number; + isCurrentSession: boolean; + isEphemeralPlugin: boolean; + pluginId: string | null; + isRouted: boolean; + identity: ConnectedClientIdentity | null; + hubOrigin: string | null; + /** Routed child sessions currently multiplexed over this record's physical daemon link. */ + routedChildren: readonly ConnectedClientRecord[]; + /** True when this physical connection owns an active `DaemonLinkEndpoint`. */ + hasHostLink: boolean; +} + +export interface BuildConnectedClientsOptions { + includeInternal?: boolean; + isTailscaleEndpoint?: (localEndpoint: string) => boolean; +} + +const HOST_LINK_CLIENT_ID_PREFIX = "host-link-"; + +function parsePeerServerIdFromClientId(clientId: string): string | null { + if (!clientId.startsWith(HOST_LINK_CLIENT_ID_PREFIX)) return null; + const rest = clientId.slice(HOST_LINK_CLIENT_ID_PREFIX.length); + const marker = rest.lastIndexOf("-hst_"); + if (marker > 0) return rest.slice(0, marker); + return null; +} + +function isInboundDaemonRecord(record: ConnectedClientRecord): boolean { + if (record.isRouted) return false; + if (record.clientInfo?.kind === "daemon") return true; + if (record.hasHostLink) return true; + return record.clientId.startsWith(HOST_LINK_CLIENT_ID_PREFIX); +} + +function resolveClientKind(record: ConnectedClientRecord): ConnectedClientKind { + if (record.isEphemeralPlugin) return "plugin"; + const infoKind = record.clientInfo?.kind; + if (infoKind && infoKind !== "daemon") return infoKind; + if (record.identity?.transport === "hub" || record.clientType === "hub") return "hub"; + switch (record.clientType) { + case "mobile": + return "mobile"; + case "browser": + return "web"; + case "cli": + return "cli"; + case "mcp": + return "mcp"; + default: + return "unknown"; + } +} + +function parseBrowserName(userAgent: string | undefined): string | null { + if (!userAgent) return null; + if (/Edg\//.test(userAgent)) return "Edge"; + if (/Firefox\//.test(userAgent)) return "Firefox"; + if (/Chrome\//.test(userAgent) && !/Edg\//.test(userAgent)) return "Chrome"; + if (/Safari\//.test(userAgent) && !/Chrome\//.test(userAgent)) return "Safari"; + return null; +} + +function resolveClientName( + record: ConnectedClientRecord, + kind: ConnectedClientKind, +): string | null { + const explicit = record.clientInfo?.name?.trim(); + if (explicit) return explicit; + if (record.pluginId) return record.pluginId; + if (kind === "hub") return "Paseo Hub"; + if (kind === "web") return parseBrowserName(record.identity?.userAgent); + return null; +} + +function resolveTransport( + identity: ConnectedClientIdentity | null, + isTailscaleEndpoint?: (localEndpoint: string) => boolean, +): ConnectedClientTransport { + if (!identity) return "direct"; + if (identity.transport === "relay") return "relay"; + if (identity.transport === "hub") return "hub"; + if (identity.peer === "local_ipc") return "local_ipc"; + if (identity.peer === "loopback") return "local"; + if (identity.localEndpoint && isTailscaleEndpoint?.(identity.localEndpoint)) { + return "tailscale"; + } + return "direct"; +} + +function isAttenuated( + effective: readonly DaemonPermission[], + ceiling: readonly DaemonPermission[], +): boolean { + if (ceiling.length === 0) return false; + const effectiveSet = new Set(effective); + return ceiling.some((permission) => !effectiveSet.has(permission)); +} + +function isInternalClient(record: ConnectedClientRecord, kind: ConnectedClientKind): boolean { + if (record.isEphemeralPlugin || kind === "plugin") return true; + return kind === "cli" || kind === "mcp"; +} + +function toRoutedSummary(record: ConnectedClientRecord): RoutedClientSummary { + const kind = resolveClientKind(record); + return { + sessionId: record.sessionId, + sourceId: record.sourceId, + name: resolveClientName(record, kind), + kind, + appVersion: record.appVersion, + permissions: [...record.permissions], + attenuated: isAttenuated(record.permissions, record.principalPermissions), + connectedAt: record.connectedAt, + }; +} + +function toInboundDaemonSummary( + record: ConnectedClientRecord, + isTailscaleEndpoint?: (localEndpoint: string) => boolean, +): InboundDaemonSummary { + const transport = resolveTransport(record.identity, isTailscaleEndpoint); + const peerServerId = + record.clientInfo?.peerServerId?.trim() || + parsePeerServerIdFromClientId(record.clientId) || + null; + const routedSessions = record.routedChildren + .map(toRoutedSummary) + .sort((a, b) => a.connectedAt.localeCompare(b.connectedAt)); + return { + sessionId: record.sessionId, + peerServerId, + name: record.clientInfo?.name?.trim() || null, + appVersion: record.appVersion, + principalId: record.principalId, + transport, + ...(transport === "relay" && record.identity?.securityMode + ? { securityMode: record.identity.securityMode } + : {}), + permissions: [...record.permissions], + connectedAt: record.connectedAt, + socketCount: record.socketCount, + routedSessions, + }; +} + +function toConnectedClientSummary( + record: ConnectedClientRecord, + kind: ConnectedClientKind, + isTailscaleEndpoint?: (localEndpoint: string) => boolean, +): ConnectedClientSummary { + const transport = resolveTransport(record.identity, isTailscaleEndpoint); + return { + sessionId: record.sessionId, + clientId: record.clientId, + isCurrentSession: record.isCurrentSession, + principalId: record.principalId, + kind, + name: resolveClientName(record, kind), + platform: record.clientInfo?.platform ?? null, + appVersion: record.appVersion, + transport, + ...(transport === "relay" && record.identity?.securityMode + ? { securityMode: record.identity.securityMode } + : {}), + ...(transport === "hub" && record.hubOrigin ? { hubOrigin: record.hubOrigin } : {}), + permissions: [...record.permissions], + attenuated: isAttenuated(record.permissions, record.principalPermissions), + connectedAt: record.connectedAt, + socketCount: record.socketCount, + }; +} + +function compareByLiveThenTime( + a: { socketCount: number; connectedAt: string }, + b: { socketCount: number; connectedAt: string }, +): number { + const aLive = a.socketCount > 0 ? 1 : 0; + const bLive = b.socketCount > 0 ? 1 : 0; + if (aLive !== bLive) return bLive - aLive; + return a.connectedAt.localeCompare(b.connectedAt); +} + +export function buildConnectedClientsSnapshot( + records: readonly ConnectedClientRecord[], + options: BuildConnectedClientsOptions = {}, +): DaemonClientsSnapshot { + const includeInternal = options.includeInternal === true; + const clients: ConnectedClientSummary[] = []; + const inboundDaemons: InboundDaemonSummary[] = []; + + for (const record of records) { + if (record.isRouted) continue; + + if (isInboundDaemonRecord(record)) { + inboundDaemons.push(toInboundDaemonSummary(record, options.isTailscaleEndpoint)); + continue; + } + + const kind = resolveClientKind(record); + if (!includeInternal && !record.isCurrentSession && isInternalClient(record, kind)) { + continue; + } + + clients.push(toConnectedClientSummary(record, kind, options.isTailscaleEndpoint)); + } + + clients.sort((a, b) => { + if (a.isCurrentSession !== b.isCurrentSession) return a.isCurrentSession ? -1 : 1; + return compareByLiveThenTime(a, b); + }); + + inboundDaemons.sort(compareByLiveThenTime); + + return { clients, inboundDaemons }; +} + +export function createConnectedClientsNotifier(debounceMs = 100): { + observe(listener: () => void): () => void; + notify(): void; + close(): void; +} { + const listeners = new Set<() => void>(); + let timer: ReturnType | null = null; + let closed = false; + + return { + observe(listener) { + if (closed) return () => {}; + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + notify() { + if (closed || listeners.size === 0) return; + if (timer) return; + timer = setTimeout(() => { + timer = null; + if (closed) return; + for (const listener of listeners) { + listener(); + } + }, debounceMs); + timer.unref?.(); + }, + close() { + closed = true; + if (timer) { + clearTimeout(timer); + timer = null; + } + listeners.clear(); + }, + }; +} diff --git a/packages/server/src/server/connected-hosts/index.ts b/packages/server/src/server/connected-hosts/index.ts index 526910f5cc..68be7cdc04 100644 --- a/packages/server/src/server/connected-hosts/index.ts +++ b/packages/server/src/server/connected-hosts/index.ts @@ -43,6 +43,9 @@ export interface HostActor { interface Live { client: DaemonClient; accepted: boolean; + version: string | null; + permissions?: DaemonPermission[]; + connectedAt: string | null; stop(): void; } interface Route { @@ -62,7 +65,7 @@ export class ConnectedHosts { private closed = false; constructor( private readonly home: string, - private readonly self: HostDirectory["self"], + private readonly self: HostDirectory["self"] & { version?: string }, ) { this.ready = this.load(); void this.ready.catch(() => {}); @@ -86,8 +89,8 @@ export class ConnectedHosts { async list(): Promise { await this.ready; return { - self: { ...this.self }, - hosts: this.rows.map(({ connection: _secret, ...row }) => structuredClone(row)), + self: { serverId: this.self.serverId, label: this.self.label }, + hosts: this.rows.map((row) => this.summary(row)), }; } observe(changed: () => void): () => void { @@ -118,7 +121,17 @@ export class ConnectedHosts { } private summary(row: Saved): HostSummary { const { connection: _secret, ...summary } = row; - return structuredClone(summary); + const live = this.live.get(row.registrationId); + const enriched = + live?.accepted && row.status === "online" + ? { + ...summary, + ...(live.version !== null ? { version: live.version } : {}), + ...(live.permissions ? { permissions: [...live.permissions] } : {}), + ...(live.connectedAt ? { connectedAt: live.connectedAt } : {}), + } + : summary; + return structuredClone(enriched); } add(input: HostAdd, actor: HostActor): Promise { return this.mutate(async () => { @@ -254,10 +267,18 @@ export class ConnectedHosts { clientId: `host-link-${this.self.serverId}-${row.registrationId}`, connectTimeoutMs: 10000, transportFactory: transports, + ...(this.self.version ? { appVersion: this.self.version } : {}), + clientInfo: { + name: this.self.label, + kind: "daemon", + peerServerId: this.self.serverId, + }, }); const live: Live = { client, accepted: false, + version: null, + connectedAt: null, stop: () => { stopped = true; clearTimeout(retry); @@ -313,6 +334,9 @@ export class ConnectedHosts { if (stopped || client.getLastServerInfoMessage() !== info || !client.isConnected) return; Object.assign(row, next); live.accepted = true; + live.version = info.version ?? null; + live.permissions = info.permissions ? [...info.permissions] : undefined; + live.connectedAt = next.lastOnlineAt; attempts = 0; this.changed(); }); @@ -336,6 +360,9 @@ export class ConnectedHosts { client.subscribeConnectionStatus((state) => { if (stopped || row.status === "error") return; live.accepted = false; + live.version = null; + live.permissions = undefined; + live.connectedAt = null; if (state.status === "connected") { void accept(); return; diff --git a/packages/server/src/server/connected-hosts/link.ts b/packages/server/src/server/connected-hosts/link.ts index 7f917ba2d6..12905fbaba 100644 --- a/packages/server/src/server/connected-hosts/link.ts +++ b/packages/server/src/server/connected-hosts/link.ts @@ -77,8 +77,15 @@ export class DaemonLinkEndpoint { bufferedAmount(): number | null; delivery: SessionDelivery; admit(socket: VirtualHostSocket, permissions: readonly DaemonPermission[]): Promise; + onChannelsChanged?: () => void; }, ) {} + listChannelSockets(): VirtualHostSocket[] { + return [...this.channels.values()].map((channel) => channel.socket); + } + private notifyChannelsChanged(): void { + this.parent.onChannelsChanged?.(); + } handles(message: SessionInboundMessage): boolean { return ( message.type === "hosts.link.open.request" || @@ -128,6 +135,7 @@ export class DaemonLinkEndpoint { this.channels.delete(owner.id); flowControl?.close(); socket?.close(); + this.notifyChannelsChanged(); }); const id = owner.id; // Capture actual authenticated authority. The caller hello can only reduce it. @@ -171,6 +179,7 @@ export class DaemonLinkEndpoint { (code, reason) => { this.channels.delete(id); flowControl?.close(); + this.notifyChannelsChanged(); let failure = "host_offline"; if (code === 1009) failure = "resource_limit"; if (code === 1008) failure = "permission_denied"; @@ -200,6 +209,7 @@ export class DaemonLinkEndpoint { }, ); this.channels.set(id, { scopeId: message.channelId, socket, flowControl }); + this.notifyChannelsChanged(); try { await this.parent.admit(socket, ceiling); if (this.closed || socket.readyState !== 1) { diff --git a/packages/server/src/server/listeners.ts b/packages/server/src/server/listeners.ts index 56d79a3c66..3f74f6174d 100644 --- a/packages/server/src/server/listeners.ts +++ b/packages/server/src/server/listeners.ts @@ -296,8 +296,21 @@ export function createDaemonListeners(options: { }; } + function isTailscaleEndpoint(localEndpoint?: string): boolean { + if (!localEndpoint) return false; + try { + const target = parseListenString(localEndpoint); + if (target.type !== "tcp") return false; + const network = getTailscaleNetwork(); + return !network.otherAddresses.has(target.host) && network.addresses.includes(target.host); + } catch { + return false; + } + } + return { status, + isTailscaleEndpoint, async refreshStatus(localEndpoint?: string) { if (!stopped) await extras.retryWaiting(); return status(localEndpoint); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index 941e0e7daf..cb69ce3257 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -661,6 +661,10 @@ export interface SessionOptions { daemonRuntimeConfig?: DaemonRuntimeConfig; getSourceLocalEndpoint?: (source: object) => string | undefined; getWebSocketRuntimeMetrics?: () => DaemonWebSocketRuntimeDiagnosticSnapshot | null; + listConnectedClients?: (options?: { + includeInternal?: boolean; + }) => import("@getpaseo/protocol/messages").DaemonClientsSnapshot; + observeConnectedClients?: (listener: () => void) => () => void; } export type SessionLifecycleIntent = @@ -1257,6 +1261,8 @@ export class Session { daemonVersion, daemonRuntimeConfig, getWebSocketRuntimeMetrics, + listConnectedClients: options.listConnectedClients, + observeConnectedClients: options.observeConnectedClients, getObservationMetrics: () => ({ Registrations: this.delivery.registrationCount, "Source registrations": this.delivery.sourceRegistrationCount(), @@ -3475,6 +3481,8 @@ export class Session { msg, source && this.getSourceLocalEndpoint?.(source), ); + case "daemon.clients.list.request": + return this.daemonSession.handleListClientsRequest(msg, this.delivery); case "daemon.get_pairing_offer.request": return this.daemonSession.handleGetPairingOfferRequest(msg); case "daemon.config.reload.request": diff --git a/packages/server/src/server/session/daemon/daemon-session.ts b/packages/server/src/server/session/daemon/daemon-session.ts index 4db76e402a..730c00d50d 100644 --- a/packages/server/src/server/session/daemon/daemon-session.ts +++ b/packages/server/src/server/session/daemon/daemon-session.ts @@ -2,7 +2,12 @@ import type { createDaemonListeners } from "../../listeners.js"; import type { DaemonConfigStore } from "../../daemon-config-store.js"; import type pino from "pino"; import type { ProviderAvailability } from "../../agent/agent-manager.js"; -import type { SessionInboundMessage, SessionOutboundMessage } from "../../messages.js"; +import type { + DaemonClientsSnapshot, + SessionInboundMessage, + SessionOutboundMessage, +} from "../../messages.js"; +import type { SessionDelivery } from "../owned-subscriptions/index.js"; import { getPidLockInfo } from "../../pid-lock.js"; import { readUnconfirmedTerminalCleanup } from "../../../terminal/terminal-worker-reaper.js"; import { generateLocalPairingOffer } from "../../pairing-offer.js"; @@ -26,6 +31,7 @@ export interface DaemonRuntimeConfig { ) => | ReturnType["status"]> | Promise["status"]>>; + isTailscaleEndpoint?: (localEndpoint?: string) => boolean; setTailscaleEnabled?: DaemonConfigStore["setTailscaleEnabled"]; getRelayConfig(): { enabled: boolean; @@ -63,6 +69,8 @@ export interface DaemonSessionOptions { getTerminalsUnavailable?: () => string | null; getWebSocketRuntimeMetrics?: () => DaemonWebSocketRuntimeDiagnosticSnapshot | null; getObservationMetrics?: () => Record; + listConnectedClients?: (options?: { includeInternal?: boolean }) => DaemonClientsSnapshot; + observeConnectedClients?: (listener: () => void) => () => void; logger: pino.Logger; hubRelationships?: HubRelationshipManagement; reloadConfig: () => Promise; @@ -89,6 +97,8 @@ export class DaemonSession { private readonly getTerminalsUnavailable: () => string | null; private readonly getWebSocketRuntimeMetrics: () => DaemonWebSocketRuntimeDiagnosticSnapshot | null; private readonly getObservationMetrics: DaemonSessionOptions["getObservationMetrics"]; + private readonly listConnectedClients: DaemonSessionOptions["listConnectedClients"]; + private readonly observeConnectedClients: DaemonSessionOptions["observeConnectedClients"]; private readonly logger: pino.Logger; private readonly selfUpdate: DaemonSelfUpdateSessionController; private readonly hubRelationships: HubRelationshipManagement | null; @@ -108,6 +118,8 @@ export class DaemonSession { this.getTerminalsUnavailable = options.getTerminalsUnavailable ?? (() => null); this.getWebSocketRuntimeMetrics = options.getWebSocketRuntimeMetrics ?? (() => null); this.getObservationMetrics = options.getObservationMetrics; + this.listConnectedClients = options.listConnectedClients; + this.observeConnectedClients = options.observeConnectedClients; this.logger = options.logger; this.hubRelationships = options.hubRelationships ?? null; this.reloadConfig = options.reloadConfig; @@ -197,6 +209,57 @@ export class DaemonSession { }); } + async handleListClientsRequest( + msg: Extract, + delivery: SessionDelivery, + ): Promise { + const readSnapshot = (): DaemonClientsSnapshot => + this.listConnectedClients?.({ includeInternal: msg.includeInternal === true }) ?? { + clients: [], + inboundDaemons: [], + }; + if (!msg.observe || !this.observeConnectedClients) { + const snapshot = readSnapshot(); + this.host.emit({ + type: "daemon.clients.list.response", + payload: { + requestId: msg.requestId, + clients: snapshot.clients, + inboundDaemons: snapshot.inboundDaemons, + }, + }); + return; + } + let stop = () => {}; + const owner = delivery.begin("daemon-clients", undefined, () => stop()); + try { + stop = this.observeConnectedClients(() => { + const snapshot = readSnapshot(); + owner.emit({ + type: "daemon.clients.changed", + payload: { + subscriptionId: owner.id, + clients: snapshot.clients, + inboundDaemons: snapshot.inboundDaemons, + }, + }); + }); + const snapshot = readSnapshot(); + this.host.emit({ + type: "daemon.clients.list.response", + payload: { + requestId: msg.requestId, + subscriptionId: owner.id, + clients: snapshot.clients, + inboundDaemons: snapshot.inboundDaemons, + }, + }); + } catch (error) { + await owner.release(); + throw error; + } + } + async handleGetStatusRequest( msg: Extract, localEndpoint?: string, diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index e9800ce869..409053c1e4 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -15,6 +15,12 @@ import { createToolHosts } from "./agent/host-operations/index.js"; import { HOST_ROUTE_OPCODE } from "@getpaseo/protocol/binary-frames/index"; import { DaemonLinkEndpoint, VirtualHostSocket } from "./connected-hosts/index.js"; import { ConnectedHosts } from "./connected-hosts/index.js"; +import { + buildConnectedClientsSnapshot, + createConnectedClientsNotifier, + type ConnectedClientIdentity, + type ConnectedClientRecord, +} from "./connected-clients.js"; import type { TunnelManager } from "./tunnels/index.js"; import { stat } from "node:fs/promises"; import { @@ -488,12 +494,17 @@ export interface WebSocketLike { interface SessionConnectionBase { hubExecutionAgents?: HubExecutionAgents; permissionCeiling?: readonly DaemonPermission[]; + principalPermissions: readonly DaemonPermission[]; session: Session; principalId: string; sessionKey: string; clientId: string; + clientType: WSHelloMessage["clientType"]; + clientInfo: NonNullable | null; appVersion: string | null; clientCapabilities: Record | null; + connectedAt: string; + lastIdentity: ConnectedClientIdentity | null; connectionLogger: pino.Logger; sockets: Set; } @@ -526,6 +537,8 @@ interface SocketSessionOptions { onLifecycleIntent?: (intent: SessionLifecycleIntent) => void; hubExecutionAgents?: HubExecutionAgents; hubRelationships?: HubRelationshipManagement; + listConnectedClients?: SessionOptions["listConnectedClients"]; + observeConnectedClients?: SessionOptions["observeConnectedClients"]; } interface ClosePhysicalSocketParams { @@ -628,6 +641,7 @@ export class VoiceAssistantWebSocketServer { private readonly downloadTokenStore: DownloadTokenStore; private readonly paseoHome: string; private readonly connectedHosts: ConnectedHosts; + private readonly connectedClientsNotifier = createConnectedClientsNotifier(); toolHosts() { return createToolHosts(this.connectedHosts); @@ -848,7 +862,11 @@ export class VoiceAssistantWebSocketServer { this.workspaceAutoName = workspaceAutoName; this.downloadTokenStore = downloadTokenStore; this.paseoHome = paseoHome; - this.connectedHosts = new ConnectedHosts(paseoHome, { serverId, label: getHostName() }); + this.connectedHosts = new ConnectedHosts(paseoHome, { + serverId, + label: getHostName(), + version: this.daemonVersion, + }); this.passwordHash = auth?.password; this.daemonConfigStore = daemonConfigStore; this.mcpBaseUrl = mcpBaseUrl; @@ -1224,6 +1242,7 @@ export class VoiceAssistantWebSocketServer { } for (const connection of new Set(this.externalSessionsByKey.values())) { if (connection.principalId === principalId) { + connection.principalPermissions = [...permissions]; connection.session.setPermissions( connection.permissionCeiling ? permissions.filter((permission) => connection.permissionCeiling!.includes(permission)) @@ -1231,6 +1250,7 @@ export class VoiceAssistantWebSocketServer { ); } } + this.connectedClientsNotifier.notify(); } public prepareForShutdown(): void { @@ -1246,6 +1266,7 @@ export class VoiceAssistantWebSocketServer { public async close(): Promise { this.prepareForShutdown(); this.networkTunnel.close(); + this.connectedClientsNotifier.close(); await this.agentMessages.close(); await this.connectedHosts.close(); this.unsubscribeSpeechReadiness?.(); @@ -1639,14 +1660,29 @@ export class VoiceAssistantWebSocketServer { private createSessionConnection(params: { ws: WebSocketLike; clientId: string; + clientType: WSHelloMessage["clientType"]; + clientInfo: NonNullable | null; appVersion: string | null; clientCapabilities: Record | null; connectionLogger: pino.Logger; lifecycle: { kind: "reconnectable" } | { kind: "ephemeral-plugin"; pluginId: string }; admission: SessionAdmission; + principalPermissions: readonly DaemonPermission[]; + identity: WebSocketConnectionIdentity; }): SessionConnection { - const { ws, clientId, appVersion, clientCapabilities, connectionLogger, lifecycle, admission } = - params; + const { + ws, + clientId, + clientType, + clientInfo, + appVersion, + clientCapabilities, + connectionLogger, + lifecycle, + admission, + principalPermissions, + identity, + } = params; let connection: SessionConnection | null = null; const session = this.createSocketSession({ @@ -1660,6 +1696,9 @@ export class VoiceAssistantWebSocketServer { ? `plugin:${lifecycle.pluginId}` : admission.principalId, connectionLogger, + listConnectedClients: (options) => + this.listConnectedClientsForSession(connection?.session ?? null, options), + observeConnectedClients: (listener) => this.connectedClientsNotifier.observe(listener), onMessage: (msg) => { if (!connection) { return; @@ -1710,11 +1749,16 @@ export class VoiceAssistantWebSocketServer { const base: SessionConnectionBase = { session, principalId: admission.principalId, + principalPermissions: [...principalPermissions], hubExecutionAgents: admission.hubExecutionAgents, sessionKey: sessionConnectionKey(admission.principalId, clientId), clientId, + clientType, + clientInfo, appVersion, clientCapabilities, + connectedAt: new Date().toISOString(), + lastIdentity: this.toConnectedClientIdentity(ws, identity), connectionLogger, sockets: new Set([ws]), }; @@ -1842,6 +1886,94 @@ export class VoiceAssistantWebSocketServer { daemonVersion: this.daemonVersion, daemonRuntimeConfig: this.daemonRuntimeConfig, getWebSocketRuntimeMetrics: () => this.lastRuntimeMetricsSnapshot, + listConnectedClients: options.listConnectedClients, + observeConnectedClients: options.observeConnectedClients, + }); + } + + private toConnectedClientIdentity( + ws: WebSocketLike, + identity: WebSocketConnectionIdentity | undefined, + ): ConnectedClientIdentity | null { + if (!identity) return null; + const localEndpoint = this.socketLocalEndpoints.get(ws); + return { + transport: identity.transport, + peer: identity.peer, + ...(identity.securityMode ? { securityMode: identity.securityMode } : {}), + ...(identity.userAgent ? { userAgent: identity.userAgent } : {}), + ...(localEndpoint ? { localEndpoint } : {}), + ...(identity.hubDaemonId ? { hubDaemonId: identity.hubDaemonId } : {}), + }; + } + + private listConnectedClientsForSession( + callerSession: Session | null, + options?: { includeInternal?: boolean }, + ) { + const allConnections = new Set([ + ...this.sessions.values(), + ...this.externalSessionsByKey.values(), + ]); + const hubOrigin = this.hubRelationships?.status().hubOrigin ?? null; + + const toRecord = ( + connection: SessionConnection, + routedChildren: readonly ConnectedClientRecord[], + hasHostLink: boolean, + ): ConnectedClientRecord => { + let identity = connection.lastIdentity; + for (const socket of connection.sockets) { + const current = this.toConnectedClientIdentity(socket, this.socketIdentities.get(socket)); + if (current) { + identity = current; + break; + } + } + return { + sessionId: connection.session.getSessionId(), + clientId: connection.clientId, + principalId: connection.principalId, + sourceId: connection.session.getHostSourceId(), + clientType: connection.clientType, + clientInfo: connection.clientInfo, + appVersion: connection.appVersion, + permissions: connection.session.getPermissions(), + principalPermissions: connection.principalPermissions, + connectedAt: connection.connectedAt, + socketCount: connection.sockets.size, + isCurrentSession: callerSession !== null && connection.session === callerSession, + isEphemeralPlugin: connection.lifecycle === "ephemeral-plugin", + pluginId: connection.lifecycle === "ephemeral-plugin" ? connection.pluginId : null, + isRouted: connection.session.isRouted(), + identity, + hubOrigin: connection.principalId.startsWith("hub:") ? hubOrigin : null, + routedChildren, + hasHostLink, + }; + }; + + const records: ConnectedClientRecord[] = []; + for (const connection of allConnections) { + let hasHostLink = false; + const childConnections = new Set(); + for (const socket of connection.sockets) { + const link = this.hostLinks.get(socket); + if (!link) continue; + hasHostLink = true; + for (const childSocket of link.listChannelSockets()) { + const child = this.sessions.get(childSocket); + if (child) childConnections.add(child); + } + } + const routedChildren = [...childConnections].map((child) => toRecord(child, [], false)); + records.push(toRecord(connection, routedChildren, hasHostLink)); + } + + return buildConnectedClientsSnapshot(records, { + includeInternal: options?.includeInternal === true, + isTailscaleEndpoint: (localEndpoint) => + this.daemonRuntimeConfig?.isTailscaleEndpoint?.(localEndpoint) === true, }); } @@ -1906,15 +2038,10 @@ export class VoiceAssistantWebSocketServer { } this.clearPendingConnection(ws); - let admitted = pending.admission; - if (!admitted) throw new Error("Admitted hello has no session admission"); - if (message.sessionPermissions) - admitted = { - ...admitted, - permissions: admitted.permissions.filter((permission) => - message.sessionPermissions!.includes(permission), - ), - }; + const { admitted, principalPermissions } = applySessionPermissionCeiling( + pending.admission, + message.sessionPermissions, + ); pending.admission = admitted; pending.identity.clientId = clientId; if (message.appVersion) { @@ -1923,7 +2050,7 @@ export class VoiceAssistantWebSocketServer { const sessionKey = sessionConnectionKey(admitted.principalId, clientId); const existing = pluginId ? undefined : this.externalSessionsByKey.get(sessionKey); if (existing) { - this.resumeSession({ ws, message, pending, existing }); + this.resumeSession({ ws, message, pending, existing, principalPermissions }); return; } @@ -1932,11 +2059,15 @@ export class VoiceAssistantWebSocketServer { const connection = this.createSessionConnection({ ws, clientId, + clientType: message.clientType, + clientInfo: message.clientInfo ?? null, appVersion: message.appVersion ?? null, clientCapabilities: message.capabilities ?? null, connectionLogger, lifecycle: pluginId ? { kind: "ephemeral-plugin", pluginId } : { kind: "reconnectable" }, admission: admitted, + principalPermissions, + identity: pending.identity, }); connection.permissionCeiling = message.sessionPermissions; connection.session.setRouted(message.routed === true); @@ -1947,6 +2078,7 @@ export class VoiceAssistantWebSocketServer { } pending.identity.sessionId = connection.session.getSessionId(); this.sendHelloResponse(ws, connection.session, message); + this.connectedClientsNotifier.notify(); connection.connectionLogger.info( { ...toConnectionLogFields(pending.identity), @@ -2048,8 +2180,9 @@ export class VoiceAssistantWebSocketServer { message: WSHelloMessage; pending: PendingConnection; existing: ReconnectableSessionConnection; + principalPermissions: readonly DaemonPermission[]; }): void { - const { ws, message, pending, existing } = params; + const { ws, message, pending, existing, principalPermissions } = params; this.incrementRuntimeCounter("helloResumed"); if (existing.externalDisconnectCleanupTimeout) { clearTimeout(existing.externalDisconnectCleanupTimeout); @@ -2060,6 +2193,10 @@ export class VoiceAssistantWebSocketServer { this.hostLinks.delete(socket); } existing.permissionCeiling = message.sessionPermissions; + existing.principalPermissions = [...principalPermissions]; + existing.clientType = message.clientType; + if (message.clientInfo) existing.clientInfo = message.clientInfo; + existing.lastIdentity = this.toConnectedClientIdentity(ws, pending.identity); existing.session.setPermissions(pending.admission!.permissions); existing.session.setRouted(message.routed === true); this.assignHostSource(existing, message, pending.admission!.principalId); @@ -2083,6 +2220,7 @@ export class VoiceAssistantWebSocketServer { this.sessions.set(ws, existing); pending.identity.sessionId = existing.session.getSessionId(); this.sendHelloResponse(ws, existing.session, message); + this.connectedClientsNotifier.notify(); pending.connectionLogger.info( { ...toConnectionLogFields(pending.identity), @@ -2188,6 +2326,8 @@ export class VoiceAssistantWebSocketServer { ...(this.advertiseDaemonStatusRpc && this.daemonRuntimeConfig?.setTailscaleEnabled ? { tailscale: true } : {}), + // COMPAT(connectedClients): added in v0.19.0, remove gate after 2027-06-01. + connectedClients: true, // COMPAT(speechSettings): added in v0.12.0, remove gate after 2027-04-18. speechSettings: true, // COMPAT(relayConfig): added in v0.2.6, remove gate after 2027-01-31. @@ -2493,6 +2633,7 @@ export class VoiceAssistantWebSocketServer { connection.sockets.delete(ws); connection.session.clearAgentTimelineSubscription(ws); this.socketIdentities.delete(ws); + this.connectedClientsNotifier.notify(); if (connection.sockets.size === 0) { if (connection.lifecycle === "ephemeral-plugin") { @@ -2582,6 +2723,7 @@ export class VoiceAssistantWebSocketServer { logMessage, ); await connection.session.cleanup(); + this.connectedClientsNotifier.notify(); } private handleInvalidInboundMessage(args: { @@ -2899,8 +3041,10 @@ export class VoiceAssistantWebSocketServer { principalId: connection.principalId, permissions, }), + onChannelsChanged: () => this.connectedClientsNotifier.notify(), }); this.hostLinks.set(ws, link); + this.connectedClientsNotifier.notify(); } return link; } @@ -2910,8 +3054,11 @@ export class VoiceAssistantWebSocketServer { activeConnection: SessionConnection, message: Extract, ): Promise { - const link = this.hostLink(ws, activeConnection); - if (link.handles(message.message)) { + const link = + message.message.type === "hosts.link.open.request" || this.hostLinks.has(ws) + ? this.hostLink(ws, activeConnection) + : null; + if (link?.handles(message.message)) { await activeConnection.session.delivery.request(ws, message.message, () => link.dispatch(message.message), ); @@ -3452,6 +3599,24 @@ function isHandshakeMessage(message: WSInboundMessage): boolean { return message.type === "hello" || message.type === "tunnel_hello"; } +function applySessionPermissionCeiling( + admission: SessionAdmission | null, + sessionPermissions: readonly DaemonPermission[] | undefined, +): { admitted: SessionAdmission; principalPermissions: DaemonPermission[] } { + if (!admission) throw new Error("Admitted hello has no session admission"); + const principalPermissions = [...admission.permissions]; + if (!sessionPermissions) return { admitted: admission, principalPermissions }; + return { + admitted: { + ...admission, + permissions: admission.permissions.filter((permission) => + sessionPermissions.includes(permission), + ), + }, + principalPermissions, + }; +} + function sessionConnectionKey(principalId: string, clientId: string): string { return JSON.stringify([principalId, clientId]); }