mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-28 19:25:45 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f40bb3c09c | ||
|
|
c542d5b1d1 | ||
|
|
d4c9a21d89 | ||
|
|
5ddfbb82aa |
@@ -217,15 +217,6 @@ jobs:
|
||||
- name: Verify website mockups
|
||||
run: npm run test:e2e --workspace=@getpaseo/website
|
||||
|
||||
- name: Upload website test artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: website-playwright-results
|
||||
path: packages/website/test-results/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
|
||||
- name: Verify public package contents
|
||||
run: |
|
||||
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
|
||||
|
||||
@@ -233,57 +233,6 @@ test("opening an agent focuses the composer when a mouse drives the UI", async (
|
||||
}
|
||||
});
|
||||
|
||||
/** The composer frame's border colour once its border-color transition has finished. */
|
||||
async function readSettledFrameBorder(page: Page): Promise<string> {
|
||||
return composerLocator(page).evaluate(async (input) => {
|
||||
let frame = input.parentElement;
|
||||
while (frame && parseFloat(getComputedStyle(frame).borderTopWidth) < 1) {
|
||||
frame = frame.parentElement;
|
||||
}
|
||||
if (!frame) throw new Error("Composer frame has no border");
|
||||
while (frame.getAnimations().length > 0) {
|
||||
await new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
}
|
||||
return getComputedStyle(frame).borderTopColor;
|
||||
});
|
||||
}
|
||||
|
||||
test("the composer frame shows hover and focus", async ({ page }) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "composer-frame-focus-",
|
||||
title: "Composer frame focus",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
const composer = composerLocator(page);
|
||||
await expectComposerVisible(page);
|
||||
await page.mouse.move(0, 0);
|
||||
await blurComposerInput(page);
|
||||
const rest = await readSettledFrameBorder(page);
|
||||
|
||||
await composer.hover();
|
||||
const hover = await readSettledFrameBorder(page);
|
||||
expect(hover).not.toBe(rest);
|
||||
|
||||
await composer.click();
|
||||
await page.mouse.move(0, 0);
|
||||
await expectComposerFocused(page);
|
||||
const focus = await readSettledFrameBorder(page);
|
||||
expect(focus).not.toBe(rest);
|
||||
expect(focus).not.toBe(hover);
|
||||
|
||||
await composer.hover();
|
||||
expect(await readSettledFrameBorder(page)).toBe(focus);
|
||||
|
||||
await page.mouse.move(0, 0);
|
||||
await blurComposerInput(page);
|
||||
expect(await readSettledFrameBorder(page)).toBe(rest);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
async function waitForAnimationFrames(page: Page, count: number): Promise<void> {
|
||||
await page.evaluate(async (frames) => {
|
||||
for (let frame = 0; frame < frames; frame += 1) {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { createHostClient } from "@getpaseo/client/node";
|
||||
import { expect } from "@playwright/test";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import {
|
||||
addDirectHostFromSettings,
|
||||
@@ -24,11 +26,51 @@ import {
|
||||
slowConnectionToHost,
|
||||
expectTailscaleUpdateRequired,
|
||||
expectCompletePairingQr,
|
||||
expectConnectedClientRow,
|
||||
expectRelayConsent,
|
||||
expandConnectedClientRow,
|
||||
openDevicesPage,
|
||||
openPairDeviceModal,
|
||||
preparePairingHost,
|
||||
returnFromRelayToWaysToConnect,
|
||||
} from "../support/helpers/pair-device";
|
||||
|
||||
test("lists connected clients with scopes and navigates Pair a device → Relay → Back", async ({
|
||||
page,
|
||||
}) => {
|
||||
const daemon = await startIsolatedHostDaemon("pair-device-connected-clients", {
|
||||
mutableRelay: { enabled: true },
|
||||
});
|
||||
const viewer = createHostClient(`127.0.0.1:${daemon.port}`, {
|
||||
clientId: "cid_e2e_phone_viewer",
|
||||
clientType: "mobile",
|
||||
appVersion: "0.18.1",
|
||||
clientInfo: { name: "Test Phone", platform: "ios", kind: "mobile" },
|
||||
sessionPermissions: ["daemon.read", "workspace.read"],
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
try {
|
||||
await openDevicesPage(page, daemon);
|
||||
await expectConnectedClientRow(page, "This device", "Full access");
|
||||
await expandConnectedClientRow(page, "This device");
|
||||
await expect(
|
||||
page
|
||||
.getByTestId("devices-connected-clients-card")
|
||||
.getByText("access.manage", { exact: true }),
|
||||
).toBeVisible();
|
||||
|
||||
await viewer.connect();
|
||||
await expectConnectedClientRow(page, "Test Phone", "Read-only");
|
||||
|
||||
await openPairDeviceModal(page);
|
||||
await expectPairingOffer(page);
|
||||
await returnFromRelayToWaysToConnect(page);
|
||||
} finally {
|
||||
await viewer.close();
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("opens relay consent in browser web", async ({ page }) => {
|
||||
const daemon = await startIsolatedHostDaemon("pair-device-browser-relay-off", {
|
||||
mutableRelay: { enabled: false },
|
||||
@@ -81,7 +123,7 @@ test("turns Tailscale on and off from Devices, asking first over Tailscale", asy
|
||||
}, testInfo) => {
|
||||
test.skip(process.platform !== "linux", "Uses a second IPv4 loopback address");
|
||||
// The journey opens Devices or the setup six times, two of them over a slowed connection.
|
||||
test.setTimeout(120_000);
|
||||
test.setTimeout(180_000);
|
||||
if (!baseURL) throw new Error("Expected the app base URL");
|
||||
const daemon = await startTailscaleTestDaemon(baseURL);
|
||||
try {
|
||||
|
||||
@@ -13,6 +13,8 @@ function ad(...args) {
|
||||
});
|
||||
}
|
||||
|
||||
ad("press", 'label="Pair a device"', "--settle");
|
||||
ad("wait", "text", "Relay", "10000");
|
||||
ad("press", 'label="Relay"', "--settle");
|
||||
ad("wait", "text", "Pairing QR code", "10000");
|
||||
const { data } = JSON.parse(ad("snapshot", "-i", "--json"));
|
||||
|
||||
@@ -66,6 +66,56 @@ type PairingHost =
|
||||
| Pick<IsolatedHostDaemon, "serverId" | "port">
|
||||
| Pick<OutdatedDaemon, "serverId" | "endpoint">;
|
||||
|
||||
export async function openDevicesPage(page: Page, daemon: PairingHost): Promise<void> {
|
||||
await openAppOnPairingHost(page, daemon);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, daemon.serverId);
|
||||
await openSettingsHostSection(page, daemon.serverId, "devices");
|
||||
await expect(page.getByTestId("devices-connected-clients-card")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectConnectedClientRow(
|
||||
page: Page,
|
||||
title: string,
|
||||
scopeLabel: string,
|
||||
): Promise<void> {
|
||||
const card = page.getByTestId("devices-connected-clients-card");
|
||||
const row = card.getByRole("button", { name: title, exact: true });
|
||||
await expect(row).toBeVisible();
|
||||
await expect(card.getByText(scopeLabel, { exact: true }).first()).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expandConnectedClientRow(page: Page, title: string): Promise<void> {
|
||||
const card = page.getByTestId("devices-connected-clients-card");
|
||||
await card.getByRole("button", { name: title, exact: true }).click();
|
||||
await expect(card.getByText("Permissions", { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function returnFromRelayToWaysToConnect(page: Page): Promise<void> {
|
||||
await page
|
||||
.getByTestId("devices-relay-pairing")
|
||||
.getByRole("button", { name: "Back", exact: true })
|
||||
.click();
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function openPairDeviceWaysSheet(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("devices-pair-button")).toBeVisible();
|
||||
await page.getByTestId("devices-pair-button").click();
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
}
|
||||
|
||||
async function ensurePairDeviceWaysSheetOpen(page: Page): Promise<void> {
|
||||
const relayRow = page.getByTestId("devices-relay");
|
||||
const pairButton = page.getByTestId("devices-pair-button");
|
||||
await relayRow.or(pairButton).first().waitFor({ state: "visible" });
|
||||
if (!(await relayRow.isVisible())) {
|
||||
await pairButton.click();
|
||||
await expect(relayRow).toBeVisible();
|
||||
}
|
||||
}
|
||||
|
||||
export async function preparePairingHost(
|
||||
page: Page,
|
||||
daemon: PairingHost,
|
||||
@@ -74,9 +124,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. */
|
||||
@@ -185,10 +235,12 @@ export async function cancelTailscaleTurnOff(page: Page, address: string): Promi
|
||||
*/
|
||||
export async function confirmTailscaleTurnOff(page: Page, address: string): Promise<void> {
|
||||
const question = answerNextDialog(page, "accept");
|
||||
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
||||
const sheet = page.getByTestId("devices-pair-sheet");
|
||||
const scope = (await sheet.isVisible()) ? sheet : page;
|
||||
await scope.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
||||
expect(await question).toBe(TURN_OFF_QUESTION);
|
||||
await expect(page.getByText("Host is not connected", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
|
||||
await expect(scope.getByText("Host is not connected", { exact: true })).toBeVisible();
|
||||
await expect(scope.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
|
||||
await expectHostUnreachableAt(address);
|
||||
}
|
||||
|
||||
@@ -372,9 +424,12 @@ function deliverInOrderAfter(delay: () => number, deliver: (message: string | Bu
|
||||
}
|
||||
|
||||
export async function expectTailscaleUpdateRequired(page: Page): Promise<void> {
|
||||
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();
|
||||
await ensurePairDeviceWaysSheetOpen(page);
|
||||
const sheet = page.getByTestId("devices-pair-sheet");
|
||||
const scope = (await sheet.isVisible()) ? sheet : page;
|
||||
await expect(scope.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
||||
await expect(scope.getByText("Update this host to use Tailscale", { exact: true })).toBeVisible();
|
||||
await expect(scope.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectTailscaleUnavailable(page: Page): Promise<void> {
|
||||
@@ -460,6 +515,7 @@ export function observeDaemonStatusPolling(page: Page, port: number) {
|
||||
}
|
||||
|
||||
export async function openPairDeviceModal(page: Page): Promise<void> {
|
||||
await ensurePairDeviceWaysSheetOpen(page);
|
||||
await page.getByRole("button", { name: "Relay", exact: true }).click();
|
||||
await expect(page.getByTestId("devices-relay-pairing")).toBeVisible();
|
||||
}
|
||||
@@ -579,9 +635,14 @@ export async function expectPairingDisconnected(page: Page): Promise<void> {
|
||||
}
|
||||
|
||||
export async function switchPairDeviceToHost(page: Page, serverId: string): Promise<void> {
|
||||
const sheet = page.getByTestId("devices-pair-sheet");
|
||||
if (await sheet.isVisible()) {
|
||||
await sheet.getByRole("button", { name: "Close", exact: true }).click();
|
||||
await expect(sheet).toHaveCount(0);
|
||||
}
|
||||
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<void> {
|
||||
|
||||
@@ -137,9 +137,9 @@ export function PageTitle({
|
||||
descriptionTestID,
|
||||
}: PageTitleProps) {
|
||||
return (
|
||||
<View style={styles.titleBlock} testID={testID}>
|
||||
<View style={styles.titleBlock}>
|
||||
<View style={styles.titleRow}>
|
||||
<View style={styles.titleParts}>
|
||||
<View style={styles.titleParts} testID={testID}>
|
||||
{parent ? (
|
||||
<PressHighlight
|
||||
accessibilityRole="button"
|
||||
|
||||
@@ -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({
|
||||
<View testID={testID}>
|
||||
<SettingsRowHeader
|
||||
label={label}
|
||||
leading={leading}
|
||||
hint={hint}
|
||||
hintStatus={hintStatus}
|
||||
summary={summary}
|
||||
trailing={trailing}
|
||||
onPress={toggle}
|
||||
expanded={expanded}
|
||||
accessibilityState={accessibilityState}
|
||||
|
||||
@@ -36,6 +36,8 @@ export interface SettingsRowHeaderProps {
|
||||
summary?: string;
|
||||
/** An icon drawn directly before the summary text, such as a provider glyph beside a model name. */
|
||||
summaryLeading?: ReactNode;
|
||||
/** Passive trailing element (such as a status pill) shown before the chevron; lets presses pass through to the row. */
|
||||
trailing?: ReactNode;
|
||||
onPress: () => 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({
|
||||
<ControlSizeProvider size={layout.controlSize}>{control}</ControlSizeProvider>
|
||||
</View>
|
||||
) : null}
|
||||
{trailing ? (
|
||||
<View
|
||||
style={[styles.trailingAccessory, styles.passThrough]}
|
||||
{...HIDDEN_FROM_ASSISTIVE_TECH}
|
||||
>
|
||||
{trailing}
|
||||
</View>
|
||||
) : null}
|
||||
<RowTrailing
|
||||
hinted={hinted}
|
||||
external={external}
|
||||
@@ -246,6 +257,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
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,
|
||||
|
||||
@@ -110,7 +110,6 @@ import {
|
||||
applyDictationTranscript,
|
||||
computeCanStartDictation,
|
||||
resolveAlternateSendAction,
|
||||
resolveComposerFramePhase,
|
||||
resolveComposerSurfacePresentation,
|
||||
resolveComposerSurfaceText,
|
||||
resolveMessageInputEnterAction,
|
||||
@@ -1369,8 +1368,6 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
const dictationToggleKeys = useShortcutKeys("dictation-toggle");
|
||||
const focusInputKeys = useShortcutKeys("focus-message-input");
|
||||
const [isInputFocused, setIsInputFocused] = useState(false);
|
||||
// Only the frame's pointer events set it, so hover stays a web thing; see docs/hover.md.
|
||||
const [isInputHovered, setIsInputHovered] = useState(false);
|
||||
useKeyboardFocusSurface("message-input", isInputFocused && isPaneFocused);
|
||||
// Web text is DOM-owned between deferred draft publications. The action button only needs
|
||||
// this boundary, so publish empty/non-empty transitions without rerendering for every key.
|
||||
@@ -2041,32 +2038,15 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
void handleStopRealtimeVoice();
|
||||
}, [handleStopRealtimeVoice]);
|
||||
|
||||
const handleInputWrapperPointerEnter = useCallback(() => setIsInputHovered(true), []);
|
||||
const handleInputWrapperPointerLeave = useCallback(() => setIsInputHovered(false), []);
|
||||
const framePhase = resolveComposerFramePhase({
|
||||
hovered: isInputHovered,
|
||||
focused: isInputFocused,
|
||||
readOnly,
|
||||
disabled,
|
||||
});
|
||||
const inputWrapperCombinedStyle = useMemo(
|
||||
() => [
|
||||
styles.inputWrapper,
|
||||
Platform.OS !== "ios" && isCompact && !isFullscreen && styles.inputWrapperCompact,
|
||||
readOnly && styles.inputWrapperReadOnly,
|
||||
framePhase === "hover" && styles.inputWrapperHovered,
|
||||
framePhase === "active" && styles.inputWrapperFocused,
|
||||
inputWrapperStyle,
|
||||
{ opacity: surfacePresentation.input.opacity },
|
||||
],
|
||||
[
|
||||
framePhase,
|
||||
inputWrapperStyle,
|
||||
isCompact,
|
||||
isFullscreen,
|
||||
readOnly,
|
||||
surfacePresentation.input.opacity,
|
||||
],
|
||||
[inputWrapperStyle, isCompact, isFullscreen, readOnly, surfacePresentation.input.opacity],
|
||||
);
|
||||
// `withUnistyles` maps this component's `style` into a `.hash > *` child
|
||||
// rule, which ties on specificity with react-native-web's own
|
||||
@@ -2414,8 +2394,6 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
onExit={exitFullscreen}
|
||||
inputWrapperRef={inputWrapperRef}
|
||||
inputWrapperStyle={inputWrapperCombinedStyle}
|
||||
onInputWrapperPointerEnter={handleInputWrapperPointerEnter}
|
||||
onInputWrapperPointerLeave={handleInputWrapperPointerLeave}
|
||||
inputPointerEvents={surfacePresentation.input.pointerEvents}
|
||||
attachmentSlot={attachmentSlot}
|
||||
showFullscreenButton={shouldShowFullscreenControl(
|
||||
@@ -2470,15 +2448,6 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
inputWrapperReadOnly: {
|
||||
borderStyle: "dotted",
|
||||
},
|
||||
// The rest border is already the `borderAccent` that `controlHover` gives other inputs, so
|
||||
// hover steps up one surface; focus takes the accent, like their focus ring. Colour only:
|
||||
// the border width stays put, so the frame never shifts under the pointer.
|
||||
inputWrapperHovered: {
|
||||
borderColor: theme.colors.surface4,
|
||||
},
|
||||
inputWrapperFocused: {
|
||||
borderColor: theme.colors.accent,
|
||||
},
|
||||
// The band the fullscreen glyph sits in is the input's own padding, so a tap
|
||||
// anywhere in it (under the glyph, or where the glyph would be) is a tap on the
|
||||
// editor: it focuses, shows the keyboard, and places the caret. Reserved whether
|
||||
|
||||
@@ -37,8 +37,6 @@ export function ComposerInputPresentation({
|
||||
onExit,
|
||||
inputWrapperRef,
|
||||
inputWrapperStyle,
|
||||
onInputWrapperPointerEnter,
|
||||
onInputWrapperPointerLeave,
|
||||
inputPointerEvents,
|
||||
attachmentSlot,
|
||||
showFullscreenButton,
|
||||
@@ -55,9 +53,6 @@ export function ComposerInputPresentation({
|
||||
onExit: () => void;
|
||||
inputWrapperRef: Ref<View>;
|
||||
inputWrapperStyle: ViewProps["style"];
|
||||
/** Hover tracking for the frame's border; the frame is a plain View, per docs/hover.md. */
|
||||
onInputWrapperPointerEnter: () => void;
|
||||
onInputWrapperPointerLeave: () => void;
|
||||
inputPointerEvents: ViewProps["pointerEvents"];
|
||||
attachmentSlot: ReactNode;
|
||||
showFullscreenButton: boolean;
|
||||
@@ -112,8 +107,6 @@ export function ComposerInputPresentation({
|
||||
ref={inputWrapperRef}
|
||||
style={fullscreen ? styles.fullscreenInputWrapper : inputWrapperStyle}
|
||||
pointerEvents={inputPointerEvents}
|
||||
onPointerEnter={onInputWrapperPointerEnter}
|
||||
onPointerLeave={onInputWrapperPointerLeave}
|
||||
>
|
||||
{fullscreen ? null : attachmentSlot}
|
||||
<View style={fullscreen ? styles.fullscreenTextSurface : styles.inlineTextSurface}>
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
computeCanStartDictation,
|
||||
type MessageInputEnterContext,
|
||||
resolveActiveSendBehavior,
|
||||
resolveComposerFramePhase,
|
||||
resolveComposerSurfacePresentation,
|
||||
resolveComposerSurfaceText,
|
||||
resolveGlyphRailOffset,
|
||||
@@ -615,23 +614,3 @@ describe("fullscreen glyph rail", () => {
|
||||
expect(offset + inkInset).toBeCloseTo(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composer frame phase", () => {
|
||||
const rest = { hovered: false, focused: false, readOnly: false, disabled: false };
|
||||
|
||||
it("shows the focus border while the editor has focus, hovered or not", () => {
|
||||
expect(resolveComposerFramePhase({ ...rest, focused: true })).toBe("active");
|
||||
expect(resolveComposerFramePhase({ ...rest, focused: true, hovered: true })).toBe("active");
|
||||
});
|
||||
|
||||
it("shows the hover border only while the pointer is over an unfocused frame", () => {
|
||||
expect(resolveComposerFramePhase({ ...rest, hovered: true })).toBe("hover");
|
||||
expect(resolveComposerFramePhase(rest)).toBe("rest");
|
||||
});
|
||||
|
||||
it("keeps a read-only or disabled frame at rest", () => {
|
||||
const engaged = { ...rest, hovered: true, focused: true };
|
||||
expect(resolveComposerFramePhase({ ...engaged, readOnly: true })).toBe("rest");
|
||||
expect(resolveComposerFramePhase({ ...engaged, disabled: true })).toBe("rest");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,10 +3,6 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
import type { MessagePayload, TextReplacement } from "@/composer/types";
|
||||
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
|
||||
import {
|
||||
getControlInteractionPhase,
|
||||
type ControlInteractionPhase,
|
||||
} from "@/components/ui/control-geometry";
|
||||
|
||||
export type SendBehavior = ActiveTurnBehavior | "queue";
|
||||
|
||||
@@ -250,23 +246,6 @@ export function resolveGlyphRailOffset(input: {
|
||||
return -inkInset;
|
||||
}
|
||||
|
||||
/**
|
||||
* The composer frame follows the phases of the app's other inputs: focus wins over hover, and
|
||||
* a frame you can't type into (read-only, disabled) stays at rest.
|
||||
*/
|
||||
export function resolveComposerFramePhase(input: {
|
||||
hovered: boolean;
|
||||
focused: boolean;
|
||||
readOnly: boolean;
|
||||
disabled: boolean;
|
||||
}): ControlInteractionPhase {
|
||||
return getControlInteractionPhase({
|
||||
hovered: input.hovered,
|
||||
focused: input.focused,
|
||||
disabled: input.readOnly || input.disabled,
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveComposerSurfaceText(
|
||||
liveText: string,
|
||||
replacement: TextReplacement,
|
||||
|
||||
@@ -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) } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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 } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,558 @@
|
||||
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 (
|
||||
<View style={styles.dotSlot}>
|
||||
<View
|
||||
style={[
|
||||
styles.dot,
|
||||
tone === "online" && styles.dotOnline,
|
||||
tone === "warning" && styles.dotWarning,
|
||||
tone === "error" && styles.dotError,
|
||||
tone === "offline" && styles.dotOffline,
|
||||
]}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const STATUS_DOTS: Record<StatusDotTone, React.ReactNode> = {
|
||||
online: <StatusDot tone="online" />,
|
||||
warning: <StatusDot tone="warning" />,
|
||||
error: <StatusDot tone="error" />,
|
||||
offline: <StatusDot tone="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 <StatusBadge label={label} variant="muted" size="xs" />;
|
||||
}
|
||||
|
||||
function PermissionPillsRow({
|
||||
permissions,
|
||||
t,
|
||||
}: {
|
||||
permissions: readonly DaemonPermission[];
|
||||
t: TFunction;
|
||||
}) {
|
||||
return (
|
||||
<SettingsRow label={t("devices.details.permissions")}>
|
||||
<View style={styles.scopePills}>
|
||||
{permissions.length > 0 ? (
|
||||
permissions.map((permission) => (
|
||||
<StatusBadge key={permission} label={permission} variant="muted" size="xs" />
|
||||
))
|
||||
) : (
|
||||
<Text style={styles.nestedValue}>{t("devices.scopes.none")}</Text>
|
||||
)}
|
||||
</View>
|
||||
</SettingsRow>
|
||||
);
|
||||
}
|
||||
|
||||
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, 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 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, 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(
|
||||
() => <ScopePill permissions={client.permissions} t={t} />,
|
||||
[client.permissions, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsCollapsibleRow
|
||||
label={formatClientTitle(client, t)}
|
||||
leading={STATUS_DOTS[tone]}
|
||||
hint={formatClientHint(client, t)}
|
||||
trailing={trailing}
|
||||
testID={`devices-client-${client.sessionId}`}
|
||||
>
|
||||
<PermissionPillsRow permissions={client.permissions} t={t} />
|
||||
{connectedLabel ? (
|
||||
<SettingsRow label={t("devices.details.connected")}>
|
||||
<Text style={styles.nestedValue}>{connectedLabel}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{client.socketCount === 0 ? (
|
||||
<SettingsRow label={t("devices.details.status")}>
|
||||
<Text style={styles.nestedValue}>{t("devices.status.reconnecting")}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
</SettingsCollapsibleRow>
|
||||
);
|
||||
}
|
||||
|
||||
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, 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(
|
||||
() => <ScopePill permissions={daemon.permissions} t={t} />,
|
||||
[daemon.permissions, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsCollapsibleRow
|
||||
label={label}
|
||||
leading={STATUS_DOTS[tone]}
|
||||
hint={hintParts.join(" · ")}
|
||||
trailing={trailing}
|
||||
testID={`devices-inbound-host-${daemon.sessionId}`}
|
||||
>
|
||||
<PermissionPillsRow permissions={daemon.permissions} t={t} />
|
||||
{daemon.routedSessions.map((routed) => (
|
||||
<SettingsRow
|
||||
key={routed.sessionId}
|
||||
label={routed.name ?? formatClientPlatformLabel(routed.kind, null, t)}
|
||||
hint={t("devices.hosts.routedSession")}
|
||||
>
|
||||
<ScopePill permissions={routed.permissions} t={t} />
|
||||
</SettingsRow>
|
||||
))}
|
||||
{daemon.appVersion ? (
|
||||
<SettingsRow label={t("devices.details.version")}>
|
||||
<Text style={styles.nestedValue}>{daemon.appVersion}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{connectedLabel ? (
|
||||
<SettingsRow label={t("devices.details.connected")}>
|
||||
<Text style={styles.nestedValue}>{connectedLabel}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
</SettingsCollapsibleRow>
|
||||
);
|
||||
}
|
||||
|
||||
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 ? (
|
||||
<ScopePill permissions={host.permissions} t={t} />
|
||||
) : undefined,
|
||||
[host.permissions, host.status, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsCollapsibleRow
|
||||
label={label}
|
||||
leading={STATUS_DOTS[tone]}
|
||||
hint={hintParts.join(" · ")}
|
||||
hintStatus={host.status === "error" ? "error" : undefined}
|
||||
summary={statusSummary}
|
||||
trailing={trailing}
|
||||
testID={`devices-outbound-host-${host.registrationId}`}
|
||||
>
|
||||
{host.permissions ? <PermissionPillsRow permissions={host.permissions} t={t} /> : null}
|
||||
{host.error ? (
|
||||
<SettingsRow label={t("devices.details.error")}>
|
||||
<Text style={styles.nestedError}>{host.error.message}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{host.version ? (
|
||||
<SettingsRow label={t("devices.details.version")}>
|
||||
<Text style={styles.nestedValue}>{host.version}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{connectedLabel ? (
|
||||
<SettingsRow
|
||||
label={
|
||||
host.status === "online"
|
||||
? t("devices.details.connected")
|
||||
: t("devices.details.lastSeen")
|
||||
}
|
||||
>
|
||||
<Text style={styles.nestedValue}>{connectedLabel}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
</SettingsCollapsibleRow>
|
||||
);
|
||||
}
|
||||
|
||||
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<ConnectedClientsLoadState>({ 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<HostDirectory | null>(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 (
|
||||
<SettingsRow
|
||||
label={t("devices.connected.unavailable")}
|
||||
hint={t("workspace.terminal.hostDisconnected")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (hasServerInfo && !supportsConnectedClients) {
|
||||
return (
|
||||
<SettingsRow
|
||||
label={t("devices.connected.updateTitle")}
|
||||
hint={t("devices.connected.updateHint")}
|
||||
link={updateLink}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!canViewClients) {
|
||||
return (
|
||||
<SettingsRow
|
||||
label={t("devices.connected.permissionTitle")}
|
||||
hint={t("devices.connected.permissionHint")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (clientsState.status === "loading") {
|
||||
return <SettingsRow label={t("devices.connected.loading")} />;
|
||||
}
|
||||
if (clientsState.status === "error") {
|
||||
return <SettingsRow label={t("devices.connected.errorTitle")} error={clientsState.message} />;
|
||||
}
|
||||
if (clientsState.snapshot.clients.length === 0) {
|
||||
return <SettingsRow label={t("devices.connected.empty")} />;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{clientsState.snapshot.clients.map((entry) => (
|
||||
<ConnectedClientRow key={entry.sessionId} client={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 (
|
||||
<View>
|
||||
<SettingsSection title={t("devices.connected.title")}>
|
||||
<SettingsCard testID="devices-connected-clients-card">
|
||||
<ConnectedClientsCardBody
|
||||
isOnline={isOnline}
|
||||
hasServerInfo={Boolean(serverInfo)}
|
||||
supportsConnectedClients={supportsConnectedClients}
|
||||
canViewClients={canViewClients}
|
||||
clientsState={clientsState}
|
||||
/>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
|
||||
{isOnline && hasConnectedHosts ? (
|
||||
<SettingsSection title={t("devices.hosts.title")}>
|
||||
<SettingsCard testID="devices-connected-hosts-card">
|
||||
{inboundDaemons.map((daemon) => (
|
||||
<InboundDaemonRow key={daemon.sessionId} daemon={daemon} />
|
||||
))}
|
||||
{outboundHosts.map((host) => (
|
||||
<OutboundHostRow key={host.registrationId} host={host} />
|
||||
))}
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
}));
|
||||
@@ -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";
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
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 = <ThemedPlus uniProps={iconProps} />;
|
||||
|
||||
type PairStep = "ways" | "relay";
|
||||
|
||||
export function PairDeviceHeaderAction({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [step, setStep] = useState<PairStep>("ways");
|
||||
|
||||
const handleOpen = useCallback(() => {
|
||||
setStep("ways");
|
||||
setVisible(true);
|
||||
}, []);
|
||||
const handleClose = useCallback(() => {
|
||||
setVisible(false);
|
||||
}, []);
|
||||
const handleDismiss = useCallback(() => {
|
||||
setStep("ways");
|
||||
}, []);
|
||||
const handleOpenRelay = useCallback(() => setStep("relay"), []);
|
||||
const handleBackToWays = useCallback(() => setStep("ways"), []);
|
||||
|
||||
const header = useMemo<SheetHeader>(
|
||||
() =>
|
||||
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 (
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
leftIcon={plusIcon}
|
||||
onPress={handleOpen}
|
||||
testID="devices-pair-button"
|
||||
>
|
||||
{t("settings.host.pairDevices.rowTitle")}
|
||||
</Button>
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={handleClose}
|
||||
onDismiss={handleDismiss}
|
||||
snapPoints={SNAP_POINTS}
|
||||
desktopMaxWidth={480}
|
||||
desktopHeight={520}
|
||||
testID={step === "relay" ? "devices-relay-pairing" : "devices-pair-sheet"}
|
||||
>
|
||||
{step === "relay" ? (
|
||||
<PairDeviceSection serverId={serverId} onClose={handleClose} />
|
||||
) : (
|
||||
<WaysToConnect serverId={serverId} onOpenRelay={handleOpenRelay} />
|
||||
)}
|
||||
</AdaptiveModalSheet>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { DAEMON_PERMISSIONS, type DaemonPermission } from "@getpaseo/protocol/messages";
|
||||
|
||||
const READ_ONLY_PERMISSIONS: ReadonlySet<DaemonPermission> = 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) };
|
||||
}
|
||||
@@ -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 }) {
|
||||
/>
|
||||
<TailscaleRow serverId={serverId} />
|
||||
</SettingsCard>
|
||||
<PairDeviceModal
|
||||
serverId={serverId}
|
||||
visible={pairing}
|
||||
onClose={closePairing}
|
||||
testID="devices-relay-pairing"
|
||||
/>
|
||||
{onOpenRelay ? null : (
|
||||
<PairDeviceModal
|
||||
serverId={serverId}
|
||||
visible={pairing}
|
||||
onClose={closePairing}
|
||||
testID="devices-relay-pairing"
|
||||
/>
|
||||
)}
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 ? <PluginGalleryMenu serverId={pluginGalleryServerId} /> : undefined,
|
||||
[pluginGalleryServerId],
|
||||
);
|
||||
const devicesServerId = view.kind === "host" && view.section === "devices" ? view.serverId : null;
|
||||
const detailActions = useMemo(() => {
|
||||
if (pluginGalleryServerId) return <PluginGalleryMenu serverId={pluginGalleryServerId} />;
|
||||
if (devicesServerId) return <PairDeviceHeaderAction serverId={devicesServerId} />;
|
||||
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";
|
||||
|
||||
|
||||
@@ -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 <HostNotFound />;
|
||||
}
|
||||
|
||||
return <WaysToConnect serverId={serverId} />;
|
||||
return <ConnectedDevicesView serverId={serverId} />;
|
||||
}
|
||||
|
||||
export function HostToolsPage({ serverId }: { serverId: string }) {
|
||||
|
||||
@@ -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 } : {}),
|
||||
};
|
||||
|
||||
@@ -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<string | undefined>;
|
||||
@@ -1961,6 +1963,40 @@ export class DaemonClientCore {
|
||||
return snapshot;
|
||||
});
|
||||
}
|
||||
async listConnectedClients(options?: {
|
||||
includeInternal?: boolean;
|
||||
}): Promise<DaemonClientsSnapshot> {
|
||||
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<DaemonClientsSnapshot> {
|
||||
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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -2304,14 +2304,7 @@ class AcpRuntime {
|
||||
if (!active.deferred && wasOpenQualifying && !isOpen && this.toolKeepsTurnOpen(snapshot)) {
|
||||
active.crossedEndTurn = true;
|
||||
}
|
||||
if (
|
||||
isOpenQualifying ||
|
||||
(!isOpen &&
|
||||
this.toolKeepsTurnOpen(snapshot) &&
|
||||
active.replyState === "settled_with_open_tools")
|
||||
) {
|
||||
active.replyState = "idle";
|
||||
}
|
||||
if (isOpenQualifying) active.replyState = "idle";
|
||||
if (active.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
|
||||
@@ -5518,7 +5518,7 @@ describe("deferTurnOnRunningTools", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the turn open after an interim status reply while another background tool is still running", async () => {
|
||||
it("settles on the reply timer when reply usage arrives before the final background tool completes", async () => {
|
||||
const { connector, instances } = connectorHarness({
|
||||
handleRequest(instance, request) {
|
||||
if (request.method !== "session/prompt") return false;
|
||||
@@ -5526,9 +5526,9 @@ describe("deferTurnOnRunningTools", () => {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "bg-interim-1",
|
||||
toolCallId: "bg-u1",
|
||||
name: "run_command",
|
||||
title: "Build",
|
||||
title: "Job 1",
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
@@ -5536,9 +5536,9 @@ describe("deferTurnOnRunningTools", () => {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "bg-interim-2",
|
||||
toolCallId: "bg-u2",
|
||||
name: "run_command",
|
||||
title: "Review",
|
||||
title: "Job 2",
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
@@ -5547,12 +5547,12 @@ describe("deferTurnOnRunningTools", () => {
|
||||
},
|
||||
});
|
||||
const registration = runAcpProvider({
|
||||
id: "deferred-interim-reply-two-tools",
|
||||
label: "Deferred Interim Reply Two Tools",
|
||||
id: "deferred-usage-before-tool",
|
||||
label: "Deferred Usage Before Tool",
|
||||
connector,
|
||||
acpOptions: {
|
||||
deferTurnOnRunningTools: {
|
||||
settleDelayMs: 40,
|
||||
settleDelayMs: 30,
|
||||
quietLimitMs: 1_500,
|
||||
},
|
||||
},
|
||||
@@ -5570,9 +5570,9 @@ describe("deferTurnOnRunningTools", () => {
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "interim-two-tools-turn",
|
||||
clientMessageId: "usage-first-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "build and review" }] },
|
||||
input: { type: "message", content: [{ type: "text", text: "run jobs" }] },
|
||||
},
|
||||
});
|
||||
await waitForEvent(
|
||||
@@ -5580,310 +5580,47 @@ describe("deferTurnOnRunningTools", () => {
|
||||
(event) =>
|
||||
event.type === "timeline.item" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.id === "bg-interim-2",
|
||||
event.item.id === "bg-u2",
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
|
||||
// Job 1 completes and the agent sends an interim status reply + usage while Job 2 is still running.
|
||||
// Job 1 finishes, reply + usage_update arrive while Job 2 is still running.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "bg-interim-1",
|
||||
status: "completed",
|
||||
},
|
||||
update: { sessionUpdate: "tool_call_update", toolCallId: "bg-u1", status: "completed" },
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: textChunk("Build passed, waiting on review."),
|
||||
update: textChunk("All done."),
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: { sessionUpdate: "usage_update", used: 300, size: 1000 },
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
// Still running because Job 2 has not completed yet.
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:interim-two-tools-turn" &&
|
||||
event.turnId === "acp:usage-first-turn" &&
|
||||
event.state !== "started",
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
// Job 2 completes; pause longer than settleDelayMs to simulate LLM TTFB before wakeup chunks stream.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "bg-interim-2",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 160));
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:interim-two-tools-turn" &&
|
||||
event.state !== "started",
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
// Follow-up reply arrives after all tools are complete -> settles via settleDelayMs.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "agent_thought_chunk",
|
||||
content: { type: "text", text: "Reviewing findings..." },
|
||||
},
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: textChunk("Review complete and applied."),
|
||||
});
|
||||
// Job 2 completes -> should settle via settleDelayMs, not quietLimitMs.
|
||||
const startedAt = Date.now();
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: { sessionUpdate: "usage_update", used: 450, size: 1000 },
|
||||
update: { sessionUpdate: "tool_call_update", toolCallId: "bg-u2", status: "completed" },
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:interim-two-tools-turn" &&
|
||||
event.state === "completed",
|
||||
);
|
||||
expect(Date.now() - startedAt).toBeLessThan(400);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the turn open after a mid-wait status check reply on a single background tool", async () => {
|
||||
const { connector, instances } = connectorHarness({
|
||||
handleRequest(instance, request) {
|
||||
if (request.method !== "session/prompt") return false;
|
||||
instance.notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "bg-long",
|
||||
name: "run_command",
|
||||
title: "Long review",
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
instance.respond(request, { stopReason: "end_turn" });
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const registration = runAcpProvider({
|
||||
id: "deferred-interim-status-check",
|
||||
label: "Deferred Interim Status Check",
|
||||
connector,
|
||||
acpOptions: {
|
||||
deferTurnOnRunningTools: {
|
||||
settleDelayMs: 40,
|
||||
quietLimitMs: 1_500,
|
||||
},
|
||||
},
|
||||
});
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "interim-status-check-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "run long review" }] },
|
||||
},
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) =>
|
||||
event.type === "timeline.item" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.id === "bg-long",
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
|
||||
// Mid-wait notification wakes the agent to inspect task status and send a progress update.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "check-1",
|
||||
name: "manage_task",
|
||||
title: "Manage task",
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "check-1",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: textChunk("Still running, continuing to wait."),
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: { sessionUpdate: "usage_update", used: 250, size: 1000 },
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
|
||||
// Long background job finally completes; turn must remain open past settleDelayMs for follow-up.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "bg-long",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 160));
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:interim-status-check-turn" &&
|
||||
event.state !== "started",
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
// Final reply arrives -> settles quickly via settleDelayMs.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: textChunk("Long review finished."),
|
||||
});
|
||||
const startedAt = Date.now();
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: { sessionUpdate: "usage_update", used: 400, size: 1000 },
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:interim-status-check-turn" &&
|
||||
event.state === "completed",
|
||||
);
|
||||
expect(Date.now() - startedAt).toBeLessThan(400);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("settles on the reply timer when an open tool is reclassified as an excluded daemon after reply usage", async () => {
|
||||
const { connector, instances } = connectorHarness({
|
||||
handleRequest(instance, request) {
|
||||
if (request.method !== "session/prompt") return false;
|
||||
instance.notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "late-daemon",
|
||||
name: "run_command",
|
||||
title: "Dev server",
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
instance.respond(request, { stopReason: "end_turn" });
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const registration = runAcpProvider({
|
||||
id: "deferred-daemon-reclassify-after-usage",
|
||||
label: "Deferred Daemon Reclassify After Usage",
|
||||
connector,
|
||||
acpOptions: {
|
||||
deferTurnOnRunningTools: {
|
||||
settleDelayMs: 40,
|
||||
quietLimitMs: 1_500,
|
||||
keepsTurnOpen(toolCall) {
|
||||
const input = toolCall.input;
|
||||
if (typeof input !== "object" || input === null || Array.isArray(input)) return true;
|
||||
return input.IsDaemon !== true;
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send(openInput());
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "daemon-reclassify-after-usage-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "start dev server" }] },
|
||||
},
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) =>
|
||||
event.type === "timeline.item" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.id === "late-daemon",
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
|
||||
// Final reply + usage arrive before rawInput identifies the running tool as a daemon.
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: textChunk("Dev server is up."),
|
||||
});
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: { sessionUpdate: "usage_update", used: 200, size: 1000 },
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:daemon-reclassify-after-usage-turn" &&
|
||||
event.state !== "started",
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
// Reclassifying the still-running tool as a daemon releases the settled reply on settleDelayMs.
|
||||
const startedAt = Date.now();
|
||||
instances[1].notify("session/update", {
|
||||
sessionId: "connector-session",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "late-daemon",
|
||||
status: "in_progress",
|
||||
rawInput: { CommandLine: "npm run dev", IsDaemon: true },
|
||||
},
|
||||
});
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:daemon-reclassify-after-usage-turn" &&
|
||||
event.turnId === "acp:usage-first-turn" &&
|
||||
event.state === "completed",
|
||||
400,
|
||||
);
|
||||
expect(Date.now() - startedAt).toBeLessThan(400);
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
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<typeof HelloClientPlatformSchema>;
|
||||
|
||||
export const HelloClientKindSchema = z.enum([
|
||||
"desktop",
|
||||
"mobile",
|
||||
"web",
|
||||
"cli",
|
||||
"mcp",
|
||||
"hub",
|
||||
"daemon",
|
||||
"plugin",
|
||||
]);
|
||||
export type HelloClientKind = z.infer<typeof HelloClientKindSchema>;
|
||||
|
||||
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<typeof HelloClientInfoSchema>;
|
||||
|
||||
export const ConnectedClientKindSchema = z.enum([
|
||||
"desktop",
|
||||
"mobile",
|
||||
"web",
|
||||
"cli",
|
||||
"mcp",
|
||||
"hub",
|
||||
"plugin",
|
||||
"unknown",
|
||||
]);
|
||||
export type ConnectedClientKind = z.infer<typeof ConnectedClientKindSchema>;
|
||||
|
||||
export const ConnectedClientTransportSchema = z.enum([
|
||||
"local_ipc",
|
||||
"local",
|
||||
"tailscale",
|
||||
"direct",
|
||||
"relay",
|
||||
"hub",
|
||||
]);
|
||||
export type ConnectedClientTransport = z.infer<typeof ConnectedClientTransportSchema>;
|
||||
|
||||
export const ConnectedClientSummarySchema = z.object({
|
||||
sessionId: z.string(),
|
||||
isCurrentSession: z.boolean(),
|
||||
kind: ConnectedClientKindSchema,
|
||||
name: z.string().nullable(),
|
||||
platform: z.string().nullable(),
|
||||
appVersion: z.string().nullable(),
|
||||
transport: ConnectedClientTransportSchema,
|
||||
hubOrigin: z.string().nullable().optional(),
|
||||
permissions: z.array(DaemonPermissionSchema),
|
||||
connectedAt: z.string(),
|
||||
socketCount: z.number().int().nonnegative(),
|
||||
});
|
||||
export type ConnectedClientSummary = z.infer<typeof ConnectedClientSummarySchema>;
|
||||
|
||||
export const RoutedClientSummarySchema = z.object({
|
||||
sessionId: z.string(),
|
||||
name: z.string().nullable(),
|
||||
kind: ConnectedClientKindSchema,
|
||||
permissions: z.array(DaemonPermissionSchema),
|
||||
});
|
||||
export type RoutedClientSummary = z.infer<typeof RoutedClientSummarySchema>;
|
||||
|
||||
export const InboundDaemonSummarySchema = z.object({
|
||||
sessionId: z.string(),
|
||||
peerServerId: z.string().nullable(),
|
||||
name: z.string().nullable(),
|
||||
appVersion: z.string().nullable(),
|
||||
transport: ConnectedClientTransportSchema,
|
||||
permissions: z.array(DaemonPermissionSchema),
|
||||
connectedAt: z.string(),
|
||||
socketCount: z.number().int().nonnegative(),
|
||||
routedSessions: z.array(RoutedClientSummarySchema),
|
||||
});
|
||||
export type InboundDaemonSummary = z.infer<typeof InboundDaemonSummarySchema>;
|
||||
|
||||
export const DaemonClientsSnapshotSchema = z.object({
|
||||
clients: z.array(ConnectedClientSummarySchema),
|
||||
inboundDaemons: z.array(InboundDaemonSummarySchema),
|
||||
});
|
||||
export type DaemonClientsSnapshot = z.infer<typeof DaemonClientsSnapshotSchema>;
|
||||
|
||||
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<typeof DaemonClientsListRequestSchema>;
|
||||
export type DaemonClientsListResponse = z.infer<typeof DaemonClientsListResponseSchema>;
|
||||
export type DaemonClientsChanged = z.infer<typeof DaemonClientsChangedSchema>;
|
||||
@@ -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<typeof DaemonPermissionSchema>;
|
||||
@@ -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() }),
|
||||
|
||||
@@ -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<typeof DaemonPermissionSchema>;
|
||||
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(),
|
||||
|
||||
@@ -2847,37 +2847,18 @@ describe("ClaudeAgentClient.listImportableSessions", () => {
|
||||
await transcript.close();
|
||||
}
|
||||
|
||||
const childImports = `
|
||||
import { deepStrictEqual } from "node:assert";
|
||||
import { ClaudeAgentClient } from ${JSON.stringify(new URL("./agent.ts", import.meta.url).href)};
|
||||
import pino from ${JSON.stringify(import.meta.resolve("pino"))};
|
||||
`;
|
||||
// Cap the listing at its own budget on top of what loading the modules retains. A fixed
|
||||
// cap also counted the module graph, which grows with unrelated imports.
|
||||
const { stdout: loadedHeap } = await promisify(execFile)(process.execPath, [
|
||||
"--expose-gc",
|
||||
"--import",
|
||||
import.meta.resolve("tsx"),
|
||||
"--input-type=module",
|
||||
"--eval",
|
||||
`${childImports}
|
||||
globalThis.gc();
|
||||
console.log(process.memoryUsage().heapUsed);
|
||||
`,
|
||||
]);
|
||||
// Well under the 128 MiB transcript, so loading a whole history still runs out of heap.
|
||||
const listingBudgetMiB = 64;
|
||||
const heapCapMiB = Math.ceil(Number(loadedHeap) / (1024 * 1024)) + listingBudgetMiB;
|
||||
|
||||
const { stdout } = await promisify(execFile)(
|
||||
process.execPath,
|
||||
[
|
||||
`--max-old-space-size=${heapCapMiB}`,
|
||||
"--max-old-space-size=96",
|
||||
"--import",
|
||||
import.meta.resolve("tsx"),
|
||||
"--input-type=module",
|
||||
"--eval",
|
||||
`${childImports}
|
||||
`
|
||||
import { deepStrictEqual } from "node:assert";
|
||||
import { ClaudeAgentClient } from ${JSON.stringify(new URL("./agent.ts", import.meta.url).href)};
|
||||
import pino from ${JSON.stringify(import.meta.resolve("pino"))};
|
||||
import { mkdir, symlink } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
const clients = [];
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
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<unknown>> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).toReversed()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
async function startDaemon(): Promise<TestPaseoDaemon> {
|
||||
const instance = await createTestPaseoDaemon();
|
||||
cleanup.push(() => instance.close());
|
||||
return instance;
|
||||
}
|
||||
|
||||
function findClientSocketCount(
|
||||
snapshots: readonly DaemonClientsSnapshot[],
|
||||
name: string,
|
||||
): number | undefined {
|
||||
return snapshots.at(-1)?.clients.find((entry) => entry.name === name)?.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({
|
||||
isCurrentSession: true,
|
||||
name: "Mo's MacBook Pro",
|
||||
kind: "desktop",
|
||||
platform: "macos",
|
||||
appVersion: "0.18.1",
|
||||
transport: "local",
|
||||
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.name === "Mo's iPhone");
|
||||
expect(phone).toMatchObject({
|
||||
isCurrentSession: false,
|
||||
name: "Mo's iPhone",
|
||||
kind: "mobile",
|
||||
platform: "ios",
|
||||
permissions: ["daemon.read", "workspace.read"],
|
||||
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, "Mo's iPhone"), { 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<ReturnType<typeof paseoA.hosts.list>>["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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
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> = {}): ConnectedClientRecord {
|
||||
return {
|
||||
sessionId: "sess_1",
|
||||
clientId: "cid_1",
|
||||
clientType: "mobile",
|
||||
clientInfo: { name: "Mo's MacBook Pro", platform: "macos", kind: "desktop" },
|
||||
appVersion: "0.18.1",
|
||||
permissions: 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 reports granted permissions", () => {
|
||||
const snapshot = buildConnectedClientsSnapshot(
|
||||
[
|
||||
makeRecord({
|
||||
sessionId: "sess_hub",
|
||||
clientId: "hub:dmn_1",
|
||||
clientType: "hub",
|
||||
clientInfo: null,
|
||||
appVersion: null,
|
||||
permissions: ["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"],
|
||||
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",
|
||||
});
|
||||
expect(snapshot.clients[1]).toMatchObject({
|
||||
kind: "hub",
|
||||
name: "Paseo Hub",
|
||||
transport: "hub",
|
||||
hubOrigin: "https://hub.paseo.sh",
|
||||
permissions: ["hub.execute", "workspace.read"],
|
||||
});
|
||||
expect(snapshot.clients[2]).toMatchObject({
|
||||
kind: "mobile",
|
||||
name: "Mo's iPhone",
|
||||
transport: "tailscale",
|
||||
permissions: ["daemon.read", "workspace.read"],
|
||||
});
|
||||
});
|
||||
|
||||
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",
|
||||
clientInfo: { name: "Mo's iPhone", platform: "ios", kind: "mobile" },
|
||||
permissions: ["daemon.read", "workspace.read"],
|
||||
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"],
|
||||
identity: { transport: "relay", peer: "external" },
|
||||
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",
|
||||
transport: "relay",
|
||||
permissions: ["daemon.read", "workspace.read", "workspace.write"],
|
||||
connectedAt: "2026-11-28T10:00:00.000Z",
|
||||
socketCount: 1,
|
||||
routedSessions: [
|
||||
{
|
||||
sessionId: "sess_routed",
|
||||
name: "Mo's iPhone",
|
||||
kind: "mobile",
|
||||
permissions: ["daemon.read", "workspace.read"],
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,262 @@
|
||||
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";
|
||||
userAgent?: string;
|
||||
localEndpoint?: string;
|
||||
hubDaemonId?: string;
|
||||
}
|
||||
|
||||
export interface ConnectedClientRecord {
|
||||
sessionId: string;
|
||||
clientId: string;
|
||||
clientType: WSHelloMessage["clientType"];
|
||||
clientInfo: HelloClientInfo | null;
|
||||
appVersion: string | null;
|
||||
permissions: 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 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,
|
||||
name: resolveClientName(record, kind),
|
||||
kind,
|
||||
permissions: [...record.permissions],
|
||||
};
|
||||
}
|
||||
|
||||
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]
|
||||
.sort((a, b) => a.connectedAt.localeCompare(b.connectedAt))
|
||||
.map(toRoutedSummary);
|
||||
return {
|
||||
sessionId: record.sessionId,
|
||||
peerServerId,
|
||||
name: record.clientInfo?.name?.trim() || null,
|
||||
appVersion: record.appVersion,
|
||||
transport,
|
||||
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,
|
||||
isCurrentSession: record.isCurrentSession,
|
||||
kind,
|
||||
name: resolveClientName(record, kind),
|
||||
platform: record.clientInfo?.platform ?? null,
|
||||
appVersion: record.appVersion,
|
||||
transport,
|
||||
...(transport === "hub" && record.hubOrigin ? { hubOrigin: record.hubOrigin } : {}),
|
||||
permissions: [...record.permissions],
|
||||
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<typeof setTimeout> | 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();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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<HostDirectory> {
|
||||
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<HostSummary> {
|
||||
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;
|
||||
|
||||
@@ -77,8 +77,15 @@ export class DaemonLinkEndpoint {
|
||||
bufferedAmount(): number | null;
|
||||
delivery: SessionDelivery;
|
||||
admit(socket: VirtualHostSocket, permissions: readonly DaemonPermission[]): Promise<void>;
|
||||
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) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -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<ReturnType<typeof createDaemonListeners>["status"]>
|
||||
| Promise<ReturnType<ReturnType<typeof createDaemonListeners>["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<string, number>;
|
||||
listConnectedClients?: (options?: { includeInternal?: boolean }) => DaemonClientsSnapshot;
|
||||
observeConnectedClients?: (listener: () => void) => () => void;
|
||||
logger: pino.Logger;
|
||||
hubRelationships?: HubRelationshipManagement;
|
||||
reloadConfig: () => Promise<DaemonConfigReloadResult>;
|
||||
@@ -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<SessionInboundMessage, { type: "daemon.clients.list.request" }>,
|
||||
delivery: SessionDelivery,
|
||||
): Promise<void> {
|
||||
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<SessionInboundMessage, { type: "daemon.get_status.request" }>,
|
||||
localEndpoint?: string,
|
||||
|
||||
@@ -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 {
|
||||
@@ -492,8 +498,12 @@ interface SessionConnectionBase {
|
||||
principalId: string;
|
||||
sessionKey: string;
|
||||
clientId: string;
|
||||
clientType: WSHelloMessage["clientType"];
|
||||
clientInfo: NonNullable<WSHelloMessage["clientInfo"]> | null;
|
||||
appVersion: string | null;
|
||||
clientCapabilities: Record<string, unknown> | null;
|
||||
connectedAt: string;
|
||||
lastIdentity: ConnectedClientIdentity | null;
|
||||
connectionLogger: pino.Logger;
|
||||
sockets: Set<WebSocketLike>;
|
||||
}
|
||||
@@ -526,6 +536,8 @@ interface SocketSessionOptions {
|
||||
onLifecycleIntent?: (intent: SessionLifecycleIntent) => void;
|
||||
hubExecutionAgents?: HubExecutionAgents;
|
||||
hubRelationships?: HubRelationshipManagement;
|
||||
listConnectedClients?: SessionOptions["listConnectedClients"];
|
||||
observeConnectedClients?: SessionOptions["observeConnectedClients"];
|
||||
}
|
||||
|
||||
interface ClosePhysicalSocketParams {
|
||||
@@ -628,6 +640,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 +861,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;
|
||||
@@ -1231,6 +1248,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
);
|
||||
}
|
||||
}
|
||||
this.connectedClientsNotifier.notify();
|
||||
}
|
||||
|
||||
public prepareForShutdown(): void {
|
||||
@@ -1246,6 +1264,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
public async close(): Promise<void> {
|
||||
this.prepareForShutdown();
|
||||
this.networkTunnel.close();
|
||||
this.connectedClientsNotifier.close();
|
||||
await this.agentMessages.close();
|
||||
await this.connectedHosts.close();
|
||||
this.unsubscribeSpeechReadiness?.();
|
||||
@@ -1639,14 +1658,27 @@ export class VoiceAssistantWebSocketServer {
|
||||
private createSessionConnection(params: {
|
||||
ws: WebSocketLike;
|
||||
clientId: string;
|
||||
clientType: WSHelloMessage["clientType"];
|
||||
clientInfo: NonNullable<WSHelloMessage["clientInfo"]> | null;
|
||||
appVersion: string | null;
|
||||
clientCapabilities: Record<string, unknown> | null;
|
||||
connectionLogger: pino.Logger;
|
||||
lifecycle: { kind: "reconnectable" } | { kind: "ephemeral-plugin"; pluginId: string };
|
||||
admission: SessionAdmission;
|
||||
identity: WebSocketConnectionIdentity;
|
||||
}): SessionConnection {
|
||||
const { ws, clientId, appVersion, clientCapabilities, connectionLogger, lifecycle, admission } =
|
||||
params;
|
||||
const {
|
||||
ws,
|
||||
clientId,
|
||||
clientType,
|
||||
clientInfo,
|
||||
appVersion,
|
||||
clientCapabilities,
|
||||
connectionLogger,
|
||||
lifecycle,
|
||||
admission,
|
||||
identity,
|
||||
} = params;
|
||||
let connection: SessionConnection | null = null;
|
||||
|
||||
const session = this.createSocketSession({
|
||||
@@ -1660,6 +1692,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;
|
||||
@@ -1713,8 +1748,12 @@ export class VoiceAssistantWebSocketServer {
|
||||
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 +1881,90 @@ 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.userAgent ? { userAgent: identity.userAgent } : {}),
|
||||
...(localEndpoint ? { localEndpoint } : {}),
|
||||
...(identity.hubDaemonId ? { hubDaemonId: identity.hubDaemonId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
private listConnectedClientsForSession(
|
||||
callerSession: Session | null,
|
||||
options?: { includeInternal?: boolean },
|
||||
) {
|
||||
const allConnections = new Set<SessionConnection>([
|
||||
...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,
|
||||
clientType: connection.clientType,
|
||||
clientInfo: connection.clientInfo,
|
||||
appVersion: connection.appVersion,
|
||||
permissions: connection.session.getPermissions(),
|
||||
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<SessionConnection>();
|
||||
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 +2029,7 @@ 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 = applySessionPermissionCeiling(pending.admission, message.sessionPermissions);
|
||||
pending.admission = admitted;
|
||||
pending.identity.clientId = clientId;
|
||||
if (message.appVersion) {
|
||||
@@ -1932,11 +2047,14 @@ 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,
|
||||
identity: pending.identity,
|
||||
});
|
||||
connection.permissionCeiling = message.sessionPermissions;
|
||||
connection.session.setRouted(message.routed === true);
|
||||
@@ -1947,6 +2065,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),
|
||||
@@ -2060,6 +2179,9 @@ export class VoiceAssistantWebSocketServer {
|
||||
this.hostLinks.delete(socket);
|
||||
}
|
||||
existing.permissionCeiling = message.sessionPermissions;
|
||||
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 +2205,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 +2311,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 +2618,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 +2708,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
logMessage,
|
||||
);
|
||||
await connection.session.cleanup();
|
||||
this.connectedClientsNotifier.notify();
|
||||
}
|
||||
|
||||
private handleInvalidInboundMessage(args: {
|
||||
@@ -2899,8 +3026,10 @@ export class VoiceAssistantWebSocketServer {
|
||||
principalId: connection.principalId,
|
||||
permissions,
|
||||
}),
|
||||
onChannelsChanged: () => this.connectedClientsNotifier.notify(),
|
||||
});
|
||||
this.hostLinks.set(ws, link);
|
||||
this.connectedClientsNotifier.notify();
|
||||
}
|
||||
return link;
|
||||
}
|
||||
@@ -2910,8 +3039,11 @@ export class VoiceAssistantWebSocketServer {
|
||||
activeConnection: SessionConnection,
|
||||
message: Extract<WSInboundMessage, { type: "session" }>,
|
||||
): Promise<void> {
|
||||
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 +3584,20 @@ function isHandshakeMessage(message: WSInboundMessage): boolean {
|
||||
return message.type === "hello" || message.type === "tunnel_hello";
|
||||
}
|
||||
|
||||
function applySessionPermissionCeiling(
|
||||
admission: SessionAdmission | null,
|
||||
sessionPermissions: readonly DaemonPermission[] | undefined,
|
||||
): SessionAdmission {
|
||||
if (!admission) throw new Error("Admitted hello has no session admission");
|
||||
if (!sessionPermissions) return admission;
|
||||
return {
|
||||
...admission,
|
||||
permissions: admission.permissions.filter((permission) =>
|
||||
sessionPermissions.includes(permission),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function sessionConnectionKey(principalId: string, clientId: string): string {
|
||||
return JSON.stringify([principalId, clientId]);
|
||||
}
|
||||
|
||||
@@ -26,24 +26,6 @@ async function centerMockup(mockup: Locator) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Plays the scene clock until `shows` is visible. Bringing the mockup on screen starts the opening
|
||||
* scene a few page tasks later: the start line's IntersectionObserver fires, then React runs the
|
||||
* effect that starts the player. A clock advance sent right after the scroll can run before that.
|
||||
*/
|
||||
async function playUntilVisible(page: Page, shows: Locator) {
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
await page.clock.runFor(1000);
|
||||
return shows.isVisible();
|
||||
},
|
||||
// The page clock is paused, so waiting between checks only spends the test's time.
|
||||
{ intervals: [0], timeout: 15_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
async function finishPanelSwap(page: Page, mockup: Locator, outgoingPanel: Locator) {
|
||||
await expect
|
||||
.poll(async () => {
|
||||
@@ -196,7 +178,8 @@ test("the opening scene waits until most of the mockup is on screen", async ({ p
|
||||
|
||||
await centerMockup(mockup);
|
||||
await expect(mockup).toBeInViewport({ ratio: 0.6 });
|
||||
await playUntilVisible(page, request);
|
||||
await page.clock.runFor(4500);
|
||||
await expect(request).toBeVisible();
|
||||
});
|
||||
|
||||
test("the opening scene starts in a window shorter than most of the mockup", async ({ page }) => {
|
||||
@@ -206,7 +189,8 @@ test("the opening scene starts in a window shorter than most of the mockup", asy
|
||||
await centerMockup(mockup);
|
||||
await expect(mockup).toBeInViewport();
|
||||
await expect(mockup).not.toBeInViewport({ ratio: 0.6 });
|
||||
await playUntilVisible(page, request);
|
||||
await page.clock.runFor(4500);
|
||||
await expect(request).toBeVisible();
|
||||
});
|
||||
|
||||
test("the plugins scene installs the panel, then changes it on request", async ({ page }) => {
|
||||
|
||||
Reference in New Issue
Block a user