Compare commits

..
Author SHA1 Message Date
QSothoth 555391d8b5 fix(server): lazily probe plugin providers for session listing
PluginAgentClient.capabilities previously derived supportsSessionListing
solely from already-negotiated connection capabilities, returning false
before first connect(). Command-backed plugins with custom status() hooks
(such as Antigravity ACP and Muse) were therefore skipped by
AgentManager.listImportableSessions() right after daemon startup.

Allow unconnected, non-closed plugin clients to report
supportsSessionListing so listImportableSessions() can lazily connect on
demand. Coalesce cold listing setup so executable resolution runs once
per connection attempt, return an empty list without connecting when the
executable is missing (typed ProviderExecutableNotFoundError) or when
status() reports unavailable, surface unexpected status() failures to
providerErrors, avoid blocking shutdown on in-flight status() probes,
and fall back to negotiated capabilities once connected.

Fixes #10412

Co-authored-by: QSothoth <15178718+QSothoth@users.noreply.github.com>
2026-11-28 23:48:01 +00:00
08298dcc10 Show an agent's thinking level when its model does not list it (#10937)
When an agent's thinking level was missing from its model's list, the
composer button, the picker's check mark and the facts line each fell
back to the list's first option. An agent on Extra High with a Claude
settings model (Low, Medium, High, Max) showed Low. The agent's level
now joins the list the controls read, so they show and check it.

Co-authored-by: Orcun Simsek <1612171+ortschun@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 22:42:58 +00:00
Fohong WangandClaude Opus 5.5 cafb42560c fix(desktop): open the Antigravity IDE instead of the agy CLI (#10893)
Open in Antigravity resolved `agy` first. agy is now the standalone
Antigravity CLI agent, so the editor never opened. Resolve the IDE's
`antigravity-ide` launcher (or the Antigravity IDE app) instead, and do
not treat Antigravity.app (com.google.antigravity), a separate app, as
the editor.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:42:36 +00:00
Tomblarom 6655aa77b3 Apply current plugin instructions when Claude resumes (#10917)
Rebuild the Claude system prompt on resume so plugin append changes and removals reach the next turn while keeping the conversation history.
2026-11-28 22:12:42 +00:00
Tomblarom 291d54fa71 fix(muse): send the current system prompt after resume (#10915) 2026-11-28 21:12:39 +00:00
paseo-bot[bot]andShane Su ddb15230b3 Show existing-agent schedules in CLI listings on request (#11243)
* Show how to include agent targets in schedule listings

* fix(cli): show the schedule hint in every table format

Use the renderer's output settings so the table alias includes the same hint about agent-target schedules.

Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>

---------

Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-28 20:42:37 +00:00
Matt Cowger 9dc533fcd2 fix(omp): skip skills, session, and title in catalogue sessions (#11129)
- Background catalogue refresh started full OMP sessions whose startup routing-hint calls were cancelled on close every tick (#11128).
- Pass --no-skills --no-session --no-title to fetchCatalog sessions only; agent sessions keep skills.
- Test that the flags apply to catalogue launches and not agent launches.
2026-11-28 20:13:03 +00:00
LiebeLee 0ee4a57981 fix(omp): keep the idle deadline on provider silence (#11079)
* fix(omp): keep the idle deadline on provider silence

- Honor agent_end.isTerminal: a queued continuation or async delivery no longer starts the 600 s failure clock; the final end owns the idle wait.
- Measure the deadline from the last provider event and suspend it while an extension-UI question or approval waits for the user.
- Abort the provider before failing a timed-out turn so the next prompt is not rejected with "Agent is already processing"; replace the runtime on the next prompt if the abort fails.
- Clear pending UI requests when the turn settles so idle runtime collection is not blocked.

Refs #8908.

* test(omp): prove the idle gate skips non-terminal agent_end

The first version observed getState counts, but the gate calls getState once before it blocks on the scheduler, so the assertion could pass on the old code. Count scheduler waits instead: the broken gate waits, the fixed one does not.
2026-11-28 20:12:40 +00:00
Konrad Karkosz aa957c9ca9 fix(app): show focus on the composer frame (#11097)
* fix(app): show focus on the composer frame

The composer frame kept its resting border whatever you did, so it was the
only text input that never showed hover or focus, and its 200ms
border-color transition on web never ran.

Focus now turns the frame's border the theme accent, as other inputs show
their focus ring. On web, hovering an unfocused frame raises the border to
surface4: the controlHover colour (borderAccent) is already the composer's
resting border, so reusing it would change nothing. Read-only and disabled
composers stay at rest. The phase comes from getControlInteractionPhase,
the helper the other inputs use, and hover follows docs/hover.md (pointer
events on the plain frame View).

* test(app): cover composer frame hover and focus

Reads the frame's settled border colour at rest, on hover, while focused and after blur.
2026-11-28 19:13:06 +00:00
Juns a96a4d61f1 fix(acp): do not settle deferred turn after interim reply when a background tool completes (#10924) 2026-11-28 19:12:37 +00:00
Mohamed Boudra 6916ceee47 test: fix the Claude listing heap test and the hero opening-scene race (#11204)
The Claude listing heap test capped its child at 96 MB, but most of
that budget went to loading the modules. Since prompt attachments
import the file-upload module, agent.ts also loads the protocol message
schemas, about 50 MB more. The 14 MB listing then ran out of heap on
runs where GC ran late. The test now measures what the imports retain
in a first child, then caps the listing child at that plus 64 MiB. That
is still below the 128 MiB transcript, so loading a whole history still
runs out of heap.

The opening-scene tests advanced the paused page clock once, right
after the scroll. The scene starts a few page tasks later
(IntersectionObserver, then a React render and effect). When the clock
advance ran first, the scene started on a paused clock and the request
never appeared. The tests now advance the clock in 1 s steps until the
request shows.

CI also uploads the website Playwright results when that step fails,
so the next stall has a trace.
2026-11-28 22:40:58 +07:00
75 changed files with 1452 additions and 2747 deletions
+9
View File
@@ -217,6 +217,15 @@ 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,6 +233,57 @@ 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,5 +1,3 @@
import { createHostClient } from "@getpaseo/client/node";
import { expect } from "@playwright/test";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import {
addDirectHostFromSettings,
@@ -26,51 +24,11 @@ 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 },
@@ -123,7 +81,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(180_000);
test.setTimeout(120_000);
if (!baseURL) throw new Error("Expected the app base URL");
const daemon = await startTailscaleTestDaemon(baseURL);
try {
@@ -13,8 +13,6 @@ 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,56 +66,6 @@ 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,
@@ -124,9 +74,9 @@ export async function preparePairingHost(
await openAppOnPairingHost(page, daemon, additionalHosts);
await openSettings(page);
await openSettingsHost(page, daemon.serverId);
await expect(page.getByTestId("devices-pair-button")).toHaveCount(0);
await expect(page.getByTestId("devices-relay")).toHaveCount(0);
await openSettingsHostSection(page, daemon.serverId, "devices");
await openPairDeviceWaysSheet(page);
await expect(page.getByTestId("devices-relay")).toBeVisible();
}
/** Loads the app afresh with `daemon` as its first host, then opens the setup's Mobile step. */
@@ -235,12 +185,10 @@ export async function cancelTailscaleTurnOff(page: Page, address: string): Promi
*/
export async function confirmTailscaleTurnOff(page: Page, address: string): Promise<void> {
const question = answerNextDialog(page, "accept");
const sheet = page.getByTestId("devices-pair-sheet");
const scope = (await sheet.isVisible()) ? sheet : page;
await scope.getByRole("switch", { name: "Tailscale", exact: true }).click();
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
expect(await question).toBe(TURN_OFF_QUESTION);
await expect(scope.getByText("Host is not connected", { exact: true })).toBeVisible();
await expect(scope.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
await expect(page.getByText("Host is not connected", { exact: true })).toBeVisible();
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
await expectHostUnreachableAt(address);
}
@@ -424,12 +372,9 @@ function deliverInOrderAfter(delay: () => number, deliver: (message: string | Bu
}
export async function expectTailscaleUpdateRequired(page: Page): Promise<void> {
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();
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();
}
export async function expectTailscaleUnavailable(page: Page): Promise<void> {
@@ -515,7 +460,6 @@ 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();
}
@@ -635,14 +579,9 @@ 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 openPairDeviceWaysSheet(page);
await expect(page.getByTestId("devices-relay")).toBeVisible();
}
export async function openRelaySecurityDocs(page: Page): Promise<void> {
@@ -137,9 +137,9 @@ export function PageTitle({
descriptionTestID,
}: PageTitleProps) {
return (
<View style={styles.titleBlock}>
<View style={styles.titleBlock} testID={testID}>
<View style={styles.titleRow}>
<View style={styles.titleParts} testID={testID}>
<View style={styles.titleParts}>
{parent ? (
<PressHighlight
accessibilityRole="button"
@@ -2,19 +2,12 @@ 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, type SettingsRowHintStatus } from "./row-header";
import { SettingsRowHeader } 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. */
@@ -28,11 +21,7 @@ interface SettingsCollapsibleRowProps {
*/
export function SettingsCollapsibleRow({
label,
leading,
hint,
hintStatus,
summary,
trailing,
defaultExpanded = false,
testID,
children,
@@ -50,11 +39,7 @@ 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,8 +36,6 @@ 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. */
@@ -77,7 +75,6 @@ export function SettingsRowHeader({
hintStatus,
summary,
summaryLeading,
trailing,
onPress,
disabled,
expanded = false,
@@ -138,14 +135,6 @@ 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}
@@ -257,10 +246,6 @@ 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,
@@ -155,6 +155,39 @@ describe("resolveAgentModelSelection", () => {
expect(selection.selectedThinkingId).toBe("high");
});
it("lists and selects the agent's thinking level when the model does not list it", () => {
const selection = resolveAgentModelSelection({
models: [
{
id: "opus",
provider: "claude",
label: "opus",
thinkingOptions: [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium" },
{ id: "high", label: "High", isDefault: true },
{ id: "max", label: "Max" },
],
defaultThinkingOptionId: "high",
},
],
runtimeModelId: "opus",
configuredModelId: "opus",
runtimeThinkingOptionId: null,
explicitThinkingOptionId: "xhigh",
});
expect(selection.selectedThinkingId).toBe("xhigh");
expect(selection.displayThinking).toBe("Extra high");
expect(selection.thinkingOptions?.map((option) => option.id)).toEqual([
"low",
"medium",
"high",
"max",
"xhigh",
]);
});
it("formats raw thinking labels in the selected model display", () => {
const selection = resolveAgentModelSelection({
models: [
@@ -130,6 +130,21 @@ function resolveEffectiveThinking(
return selectedThinking ?? thinkingOptions?.[0] ?? null;
}
// The agent runs on its level even when the model's list leaves it out. The level joins the
// list, so the controls show and check it and none of them falls back to the first option.
function includeResolvedThinkingOption(
thinkingOptions: ThinkingOption[] | null,
resolvedThinkingId: string | null,
): ThinkingOption[] | null {
if (!thinkingOptions || thinkingOptions.length === 0 || !resolvedThinkingId) {
return thinkingOptions;
}
if (thinkingOptions.some((option) => option.id === resolvedThinkingId)) {
return thinkingOptions;
}
return [...thinkingOptions, { id: resolvedThinkingId, label: resolvedThinkingId }];
}
function resolveModelDisplay(
selectedModel: AgentModelDefinition | null,
preferredModelId: string | null,
@@ -192,12 +207,15 @@ export function resolveAgentModelSelection(input: {
i18n.t("agentControls.model.unknown"),
);
const thinkingOptions = selectedModel?.thinkingOptions ?? null;
const resolvedThinkingId = resolveThinkingId(
runtimeThinkingOptionId,
explicitThinkingOptionId,
selectedModel,
);
const thinkingOptions = includeResolvedThinkingOption(
selectedModel?.thinkingOptions ?? null,
resolvedThinkingId,
);
const effectiveThinking = resolveEffectiveThinking(thinkingOptions, resolvedThinkingId);
const selectedThinkingId = effectiveThinking?.id ?? resolvedThinkingId;
const displayThinking = resolveThinkingDisplay(
+32 -1
View File
@@ -110,6 +110,7 @@ import {
applyDictationTranscript,
computeCanStartDictation,
resolveAlternateSendAction,
resolveComposerFramePhase,
resolveComposerSurfacePresentation,
resolveComposerSurfaceText,
resolveMessageInputEnterAction,
@@ -1368,6 +1369,8 @@ 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.
@@ -2038,15 +2041,32 @@ 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 },
],
[inputWrapperStyle, isCompact, isFullscreen, readOnly, surfacePresentation.input.opacity],
[
framePhase,
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
@@ -2394,6 +2414,8 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
onExit={exitFullscreen}
inputWrapperRef={inputWrapperRef}
inputWrapperStyle={inputWrapperCombinedStyle}
onInputWrapperPointerEnter={handleInputWrapperPointerEnter}
onInputWrapperPointerLeave={handleInputWrapperPointerLeave}
inputPointerEvents={surfacePresentation.input.pointerEvents}
attachmentSlot={attachmentSlot}
showFullscreenButton={shouldShowFullscreenControl(
@@ -2448,6 +2470,15 @@ 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,6 +37,8 @@ export function ComposerInputPresentation({
onExit,
inputWrapperRef,
inputWrapperStyle,
onInputWrapperPointerEnter,
onInputWrapperPointerLeave,
inputPointerEvents,
attachmentSlot,
showFullscreenButton,
@@ -53,6 +55,9 @@ 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;
@@ -107,6 +112,8 @@ 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,6 +4,7 @@ import {
computeCanStartDictation,
type MessageInputEnterContext,
resolveActiveSendBehavior,
resolveComposerFramePhase,
resolveComposerSurfacePresentation,
resolveComposerSurfaceText,
resolveGlyphRailOffset,
@@ -614,3 +615,23 @@ 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");
});
});
+21
View File
@@ -3,6 +3,10 @@ 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";
@@ -246,6 +250,23 @@ 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,
@@ -1,24 +0,0 @@
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) } : {}),
},
};
}
-49
View File
@@ -1,49 +0,0 @@
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 } : {}),
},
};
}
@@ -1,558 +0,0 @@
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,
},
}));
-2
View File
@@ -1,4 +1,2 @@
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";
@@ -1,83 +0,0 @@
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>
</>
);
}
@@ -1,41 +0,0 @@
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();
});
});
-37
View File
@@ -1,37 +0,0 @@
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) };
}
+8 -22
View File
@@ -5,26 +5,14 @@ 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, onOpenRelay }: WaysToConnectProps) {
export function WaysToConnect({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const [pairing, setPairing] = useState(false);
const openPairing = useCallback(() => {
if (onOpenRelay) {
onOpenRelay();
return;
}
setPairing(true);
}, [onOpenRelay]);
const openPairing = useCallback(() => setPairing(true), []);
const closePairing = useCallback(() => setPairing(false), []);
const docsLink = useMemo(
() => ({
@@ -46,14 +34,12 @@ export function WaysToConnect({ serverId, onOpenRelay }: WaysToConnectProps) {
/>
<TailscaleRow serverId={serverId} />
</SettingsCard>
{onOpenRelay ? null : (
<PairDeviceModal
serverId={serverId}
visible={pairing}
onClose={closePairing}
testID="devices-relay-pairing"
/>
)}
<PairDeviceModal
serverId={serverId}
visible={pairing}
onClose={closePairing}
testID="devices-relay-pairing"
/>
</SettingsSection>
);
}
-63
View File
@@ -1958,69 +1958,6 @@ 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: {
-63
View File
@@ -1988,69 +1988,6 @@ 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: {
-63
View File
@@ -2012,69 +2012,6 @@ 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: {
-63
View File
@@ -2009,69 +2009,6 @@ 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: {
-63
View File
@@ -1979,69 +1979,6 @@ 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: {
-63
View File
@@ -1970,69 +1970,6 @@ 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: {
-63
View File
@@ -1996,69 +1996,6 @@ 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: {
-63
View File
@@ -1995,69 +1995,6 @@ 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: {
-63
View File
@@ -1940,69 +1940,6 @@ 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: {
+1 -4
View File
@@ -43,7 +43,6 @@ 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";
@@ -585,12 +584,10 @@ function createDefaultDeps(
createClient: ({ host, connection, clientId, runtimeGeneration }) => {
const desktopTransportFactory = createDesktopDaemonTransportFactory();
const webSocketConfig = { webSocketFactory: createAppWebSocketFactory() };
const appIdentity = resolveAppClientIdentity();
const base = {
suppressSendErrors: true,
clientId,
clientType: appIdentity.clientType,
clientInfo: appIdentity.clientInfo,
clientType: "mobile",
appVersion: resolveAppVersion() ?? undefined,
runtimeGeneration,
capabilities: appCapabilities,
+5 -7
View File
@@ -94,7 +94,6 @@ import {
type AppLanguage,
type SupportedLocale,
} from "@/i18n/locales";
import { PairDeviceHeaderAction } from "@/devices";
import {
HostDevicesPage,
HostToolsPage,
@@ -1454,12 +1453,11 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
const pluginGalleryServerId =
view.kind === "host" && view.section === "plugins" ? view.serverId : null;
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]);
const detailActions = useMemo(
() =>
pluginGalleryServerId ? <PluginGalleryMenu serverId={pluginGalleryServerId} /> : undefined,
[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 { ConnectedDevicesView } from "@/devices";
import { WaysToConnect } 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 <ConnectedDevicesView serverId={serverId} />;
return <WaysToConnect serverId={serverId} />;
}
export function HostToolsPage({ serverId }: { serverId: string }) {
-2
View File
@@ -298,7 +298,6 @@ export interface DaemonServerInfo {
version: string | null;
machineKind?: string | null;
desktopManaged?: boolean;
permissions?: ServerInfoStatusPayload["permissions"];
capabilities?: ServerCapabilities;
features?: ServerInfoStatusPayload["features"];
}
@@ -312,7 +311,6 @@ 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 } : {}),
};
+6 -3
View File
@@ -41,9 +41,12 @@ export function createScheduleCommand(): Command {
.option("--expires-in <duration>", "Time to live for the schedule"),
).action(withOutput(runCreateCommand));
addJsonAndDaemonHostOptions(schedule.command("ls").description("List schedules")).action(
withOutput(runLsCommand),
);
addJsonAndDaemonHostOptions(
schedule
.command("ls")
.description("List new-agent schedules")
.option("--all", "Include schedules targeting existing agents"),
).action(withOutput(runLsCommand));
addJsonAndDaemonHostOptions(
schedule.command("inspect").description("Inspect a schedule").argument("<id>", "Schedule ID"),
+12 -5
View File
@@ -1,5 +1,5 @@
import type { Command } from "commander";
import type { ListResult } from "../../output/index.js";
import { isHumanOutput, type ListResult } from "../../output/index.js";
import { scheduleSchema } from "./schema.js";
import {
connectScheduleClient,
@@ -10,7 +10,7 @@ import {
} from "./shared.js";
export async function runLsCommand(
options: ScheduleCommandOptions,
options: ScheduleCommandOptions & { all?: boolean },
_command: Command,
): Promise<ListResult<ScheduleRow>> {
const { client } = await connectScheduleClient(options.daemonTarget);
@@ -19,11 +19,18 @@ export async function runLsCommand(
if (payload.error) {
throw new Error(payload.error);
}
const visible = options.all
? payload.schedules
: payload.schedules.filter((schedule) => schedule.target.type === "new-agent");
const hiddenCount = payload.schedules.length - visible.length;
if (hiddenCount > 0 && isHumanOutput(options)) {
console.error(
`Schedules targeting existing agents: ${hiddenCount} hidden. Use --all to include them.`,
);
}
return {
type: "list",
data: payload.schedules
.filter((schedule) => schedule.target.type === "new-agent")
.map(toScheduleRow),
data: visible.map(toScheduleRow),
schema: scheduleSchema,
};
} catch (error) {
+6 -1
View File
@@ -60,4 +60,9 @@ export {
} from "./render-async.js";
// Command wrapper
export { withOutput, createOutputOptions, type CommandOptions } from "./with-output.js";
export {
withOutput,
createOutputOptions,
isHumanOutput,
type CommandOptions,
} from "./with-output.js";
+5
View File
@@ -63,6 +63,11 @@ function extractOutputOptions(options: CommandOptions): OutputOptions {
};
}
export function isHumanOutput(options: CommandOptions): boolean {
const { format, quiet } = extractOutputOptions(options);
return format === "table" && !quiet;
}
/**
* Wrap a command handler to automatically render output.
*
+18
View File
@@ -294,6 +294,24 @@ try {
const createdJson = JSON.parse(created.stdout);
assert.strictEqual(createdJson.target, "agent:0000000");
const human = await ctx.paseo(["schedule", "ls"]);
assert.strictEqual(human.exitCode, 0, human.stderr);
assert.match(human.stderr, /1 hidden.*--all/);
const alias = await ctx.paseo(["--format", "cli", "schedule", "ls"]);
assert.strictEqual(alias.exitCode, 0, alias.stderr);
assert.match(alias.stderr, /1 hidden.*--all/);
const all = await ctx.paseo(["schedule", "ls", "--all", "--json"]);
assert.strictEqual(all.exitCode, 0, all.stderr);
assert(
JSON.parse(all.stdout).some(
(row: { id: string; target: string }) =>
row.id === createdJson.id && row.target === createdJson.target,
),
all.stdout,
);
const deleted = await ctx.paseo(["schedule", "delete", createdJson.id, "--json"]);
assert.strictEqual(deleted.exitCode, 0, deleted.stderr);
assert.strictEqual(JSON.parse(deleted.stdout).id, createdJson.id);
-37
View File
@@ -16,7 +16,6 @@ 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";
@@ -457,7 +456,6 @@ 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>;
@@ -1963,40 +1961,6 @@ 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 (
@@ -7687,7 +7651,6 @@ 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";
-11
View File
@@ -6,17 +6,6 @@ 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";
@@ -6,6 +6,7 @@ import type {
EditorTargetIcon,
EditorTargetRuntime,
} from "./target.js";
import { antigravityTarget } from "./targets/antigravity.js";
import { cursorTarget } from "./targets/cursor.js";
import { explorerTarget, fileManagerTarget, finderTarget } from "./targets/file-manager.js";
import { intellijIdeaTarget } from "./targets/intellij-idea.js";
@@ -243,6 +244,41 @@ describe("editor target registry", () => {
]);
});
it("never mistakes the agy CLI agent or Antigravity.app for the Antigravity IDE", async () => {
const runtime = new FakeEditorTargets("darwin");
runtime.installCommand("agy");
runtime.installMacApplication("Antigravity");
expect(await antigravityTarget.isInstalled(runtime)).toBe(false);
});
it("launches Antigravity through the IDE's bundled antigravity-ide command", async () => {
const runtime = new FakeEditorTargets("darwin");
const bundled = "/Applications/Antigravity IDE.app/Contents/Resources/app/bin/antigravity-ide";
runtime.installCommand("agy");
runtime.installCommand(bundled, bundled);
await antigravityTarget.launch(
{ workspacePath: "/repo", filePath: "/repo/a.ts", line: 3 },
runtime,
);
expect(runtime.launches).toEqual([
{ command: bundled, args: ["/repo", "--goto", "/repo/a.ts:3"] },
]);
});
it("opens the Antigravity IDE application when no launcher command resolves", async () => {
const runtime = new FakeEditorTargets("darwin");
runtime.installMacApplication("Antigravity IDE");
await antigravityTarget.launch({ workspacePath: "/repo" }, runtime);
expect(runtime.openedMacApplications).toEqual([
{ applicationName: "Antigravity IDE", paths: ["/repo"] },
]);
});
it("detects and launches the macOS application when the command is absent", async () => {
const runtime = new FakeEditorTargets("darwin");
runtime.installMacApplication("Cursor");
@@ -1,6 +1,23 @@
import type { EditorTarget, EditorTargetLaunchInput } from "../target.js";
import type { EditorTarget, EditorTargetLaunchInput, EditorTargetRuntime } from "../target.js";
const COMMANDS = ["agy", "antigravity"] as const;
// On macOS the IDE ships `antigravity-ide`. `agy` is the standalone Antigravity CLI agent and
// `Antigravity.app` (com.google.antigravity) is a separate app: neither opens the editor.
// IDE builds from before the rename keep their launcher at Antigravity.app/.../bin/antigravity.
const APP_NAME = "Antigravity IDE";
function commands(runtime: EditorTargetRuntime): string[] {
// `antigravity` is the launcher on other platforms and in builds before the rename.
const candidates = ["antigravity-ide", "antigravity"];
if (runtime.platform === "darwin") {
const roots = ["/Applications"];
if (runtime.env.HOME) roots.push(`${runtime.env.HOME}/Applications`);
for (const root of roots) {
candidates.push(`${root}/Antigravity IDE.app/Contents/Resources/app/bin/antigravity-ide`);
candidates.push(`${root}/Antigravity.app/Contents/Resources/app/bin/antigravity`);
}
}
return candidates;
}
function location(input: EditorTargetLaunchInput): string {
if (!input.line) return input.filePath!;
@@ -26,11 +43,23 @@ export const antigravityTarget: EditorTarget = {
};
},
async isInstalled(runtime) {
return runtime.resolveCommand(COMMANDS) !== null;
return (
runtime.resolveCommand(commands(runtime)) !== null || runtime.hasMacApplication(APP_NAME)
);
},
async launch(input, runtime) {
const command = runtime.resolveCommand(COMMANDS);
if (!command) throw new Error("Antigravity is not installed");
await runtime.spawnDetached({ command, args: launchArgs(input) });
const command = runtime.resolveCommand(commands(runtime));
if (command) {
await runtime.spawnDetached({ command, args: launchArgs(input) });
return;
}
if (runtime.hasMacApplication(APP_NAME)) {
await runtime.openMacApplication({
applicationName: APP_NAME,
paths: input.filePath ? [input.workspacePath, input.filePath] : [input.workspacePath],
});
return;
}
throw new Error("Antigravity is not installed");
},
};
@@ -2304,7 +2304,14 @@ class AcpRuntime {
if (!active.deferred && wasOpenQualifying && !isOpen && this.toolKeepsTurnOpen(snapshot)) {
active.crossedEndTurn = true;
}
if (isOpenQualifying) active.replyState = "idle";
if (
isOpenQualifying ||
(!isOpen &&
this.toolKeepsTurnOpen(snapshot) &&
active.replyState === "settled_with_open_tools")
) {
active.replyState = "idle";
}
if (active.deferred) this.scheduleDeferredSettle();
}
+284 -21
View File
@@ -5518,7 +5518,7 @@ describe("deferTurnOnRunningTools", () => {
}
});
it("settles on the reply timer when reply usage arrives before the final background tool completes", async () => {
it("keeps the turn open after an interim status reply while another background tool is still running", 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-u1",
toolCallId: "bg-interim-1",
name: "run_command",
title: "Job 1",
title: "Build",
status: "in_progress",
},
});
@@ -5536,9 +5536,9 @@ describe("deferTurnOnRunningTools", () => {
sessionId: "connector-session",
update: {
sessionUpdate: "tool_call",
toolCallId: "bg-u2",
toolCallId: "bg-interim-2",
name: "run_command",
title: "Job 2",
title: "Review",
status: "in_progress",
},
});
@@ -5547,12 +5547,12 @@ describe("deferTurnOnRunningTools", () => {
},
});
const registration = runAcpProvider({
id: "deferred-usage-before-tool",
label: "Deferred Usage Before Tool",
id: "deferred-interim-reply-two-tools",
label: "Deferred Interim Reply Two Tools",
connector,
acpOptions: {
deferTurnOnRunningTools: {
settleDelayMs: 30,
settleDelayMs: 40,
quietLimitMs: 1_500,
},
},
@@ -5570,9 +5570,9 @@ describe("deferTurnOnRunningTools", () => {
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId: "usage-first-turn",
clientMessageId: "interim-two-tools-turn",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "run jobs" }] },
input: { type: "message", content: [{ type: "text", text: "build and review" }] },
},
});
await waitForEvent(
@@ -5580,47 +5580,310 @@ describe("deferTurnOnRunningTools", () => {
(event) =>
event.type === "timeline.item" &&
event.item.type === "tool_call" &&
event.item.id === "bg-u2",
event.item.id === "bg-interim-2",
);
await new Promise((resolve) => setTimeout(resolve, 20));
// Job 1 finishes, reply + usage_update arrive while Job 2 is still running.
// Job 1 completes and the agent sends an interim status reply + usage while Job 2 is still running.
instances[1].notify("session/update", {
sessionId: "connector-session",
update: { sessionUpdate: "tool_call_update", toolCallId: "bg-u1", status: "completed" },
update: {
sessionUpdate: "tool_call_update",
toolCallId: "bg-interim-1",
status: "completed",
},
});
instances[1].notify("session/update", {
sessionId: "connector-session",
update: textChunk("All done."),
update: textChunk("Build passed, waiting on review."),
});
instances[1].notify("session/update", {
sessionId: "connector-session",
update: { sessionUpdate: "usage_update", used: 300, size: 1000 },
});
await new Promise((resolve) => setTimeout(resolve, 50));
// Still running because Job 2 has not completed yet.
await new Promise((resolve) => setTimeout(resolve, 60));
expect(
events.some(
(event) =>
event.type === "session.turn" &&
event.turnId === "acp:usage-first-turn" &&
event.turnId === "acp:interim-two-tools-turn" &&
event.state !== "started",
),
).toBe(false);
// Job 2 completes -> should settle via settleDelayMs, not quietLimitMs.
// 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."),
});
const startedAt = Date.now();
instances[1].notify("session/update", {
sessionId: "connector-session",
update: { sessionUpdate: "tool_call_update", toolCallId: "bg-u2", status: "completed" },
update: { sessionUpdate: "usage_update", used: 450, size: 1000 },
});
await waitForEvent(
events,
(event) =>
event.type === "session.turn" &&
event.turnId === "acp:usage-first-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.state === "completed",
400,
);
expect(Date.now() - startedAt).toBeLessThan(400);
} finally {
-127
View File
@@ -1,127 +0,0 @@
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>;
@@ -1,16 +0,0 @@
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>;
-5
View File
@@ -1,5 +1,4 @@
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({
@@ -27,10 +26,6 @@ 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() }),
+13 -20
View File
@@ -1,16 +1,4 @@
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,
@@ -186,7 +174,19 @@ export {
// Mutable daemon config schemas (shared between server store and client)
// ---------------------------------------------------------------------------
export { DAEMON_PERMISSIONS, DaemonPermissionSchema, type DaemonPermission };
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 const HexColorSchema = z
.string()
@@ -3656,7 +3656,6 @@ export const SubscriptionReleaseResponseSchema = z.object({
});
export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
DaemonClientsListRequestSchema,
HostsListRequestSchema,
HostsAddRequestSchema,
HostsUpdateRequestSchema,
@@ -4139,8 +4138,6 @@ 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.
@@ -7878,8 +7875,6 @@ export const AgentSkillsImportLegacySelectionResponseSchema = z.object({
});
export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
DaemonClientsListResponseSchema,
DaemonClientsChangedSchema,
HostsListResponseSchema,
HostsChangedSchema,
HostsAddResponseSchema,
@@ -8681,8 +8676,6 @@ 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(),
@@ -14,6 +14,7 @@ import type {
ProviderEvent,
ProviderInput,
ProviderRegistration,
ProviderStatus,
} from "@getpaseo/plugin/server/provider";
import { sendPreparedPromptToAgent, startAgentRun } from "./agent-prompt.js";
import { setImmediate as nextTurn } from "node:timers/promises";
@@ -4095,3 +4096,307 @@ describe("plugin ACP hung-cancel retirement through AgentManager (#3256)", () =>
}
});
});
test("lazily connects command-backed plugin providers for session listing", async () => {
const logger = createTestLogger();
const cwd = tmpdir();
let listableStatusCalls = 0;
let listableConnects = 0;
let missingConnects = 0;
let noListConnects = 0;
let gatedAvailable = false;
let gatedConnects = 0;
const listableHarness = createProviderHarness({
capabilities: ["prompt.message", "session.list"],
handleInput: async (input, emit) => {
if (input.type !== "sessions") return false;
emit({
type: "sessions",
requestId: input.requestId,
sessions: [
{
persistence: { version: 1, data: { sessionId: "native-lazy-1" } },
cwd,
title: "Lazy listed session",
updatedAt: "2026-04-01T00:00:00.000Z",
},
],
});
return true;
},
});
const noListHarness = createProviderHarness({
capabilities: ["prompt.message"],
});
const gatedHarness = createProviderHarness({
capabilities: ["prompt.message", "session.list"],
handleInput: async (input, emit) => {
if (input.type !== "sessions") return false;
emit({
type: "sessions",
requestId: input.requestId,
sessions: [
{
persistence: { version: 1, data: { sessionId: "native-gated-1" } },
cwd,
title: "Gated session",
updatedAt: "2026-04-02T00:00:00.000Z",
},
],
});
return true;
},
});
const listableRegistration: ProviderRegistration = {
...listableHarness.registration,
id: "lazy-listable",
label: "Lazy Listable",
command: [process.execPath, "-e", ""],
async status() {
listableStatusCalls += 1;
await nextTurn();
return { available: true };
},
async connect(request) {
listableConnects += 1;
return listableHarness.registration.connect(request);
},
};
const missingRegistration: ProviderRegistration = {
id: "lazy-missing",
label: "Lazy Missing",
command: [join(cwd, `paseo-missing-binary-${process.pid}`)],
async connect() {
missingConnects += 1;
throw new Error("should not connect when executable is missing");
},
};
const noListRegistration: ProviderRegistration = {
...noListHarness.registration,
id: "lazy-no-list",
label: "Lazy No List",
command: [process.execPath, "-e", ""],
async connect(request) {
noListConnects += 1;
return noListHarness.registration.connect(request);
},
};
const gatedRegistration: ProviderRegistration = {
...gatedHarness.registration,
id: "lazy-gated",
label: "Lazy Gated",
command: [process.execPath, "-e", ""],
async status() {
return gatedAvailable
? { available: true }
: { available: false, diagnostic: "Sign in first" };
},
async connect(request) {
gatedConnects += 1;
return gatedHarness.registration.connect(request);
},
};
const plugins = new PluginAgentClientRegistry(logger);
plugins.replace([
listableRegistration,
missingRegistration,
noListRegistration,
gatedRegistration,
]);
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
const clients = {
"lazy-listable": registry["lazy-listable"].createClient(logger),
"lazy-missing": registry["lazy-missing"].createClient(logger),
"lazy-no-list": registry["lazy-no-list"].createClient(logger),
"lazy-gated": registry["lazy-gated"].createClient(logger),
};
const manager = new AgentManager({
logger,
clients,
providerDefinitions: {
"lazy-listable": registry["lazy-listable"],
"lazy-missing": registry["lazy-missing"],
"lazy-no-list": registry["lazy-no-list"],
"lazy-gated": registry["lazy-gated"],
},
});
try {
expect(listableConnects).toBe(0);
expect(noListConnects).toBe(0);
// Concurrent cold listings share one availability probe and connection attempt.
const [listing, concurrentListing] = await Promise.all([
manager.listImportableSessions({ limit: 20 }),
manager.listImportableSessions({ limit: 20 }),
]);
for (const result of [listing, concurrentListing]) {
expect(result.providerErrors).toEqual([]);
expect(result.sessions).toEqual([
expect.objectContaining({
provider: "lazy-listable",
cwd,
title: "Lazy listed session",
}),
]);
}
expect(listableStatusCalls).toBe(1);
expect(listableConnects).toBe(1);
expect(missingConnects).toBe(0);
expect(noListConnects).toBe(1);
expect(gatedConnects).toBe(0);
expect(clients["lazy-listable"].capabilities.supportsSessionListing).toBe(true);
expect(clients["lazy-no-list"].capabilities.supportsSessionListing).toBe(false);
// Once an unavailable provider becomes available, cold listing connects and returns its rows.
gatedAvailable = true;
const afterSignIn = await manager.listImportableSessions({ limit: 20 });
expect(afterSignIn.providerErrors).toEqual([]);
expect(afterSignIn.sessions).toEqual([
expect.objectContaining({
provider: "lazy-gated",
cwd,
title: "Gated session",
}),
expect.objectContaining({
provider: "lazy-listable",
cwd,
title: "Lazy listed session",
}),
]);
expect(listableConnects).toBe(1);
expect(noListConnects).toBe(1);
expect(gatedConnects).toBe(1);
expect(noListHarness.inputs).toEqual([]);
} finally {
await plugins.shutdown();
}
expect(clients["lazy-listable"].capabilities.supportsSessionListing).toBe(false);
await expect(clients["lazy-missing"].listImportableSessions?.()).rejects.toThrow(
"Provider runtime is closed",
);
});
test("coalesces cold listings during a concurrent launch-wrap connection", async () => {
const statusStarted = Promise.withResolvers<void>();
const finishStatus = Promise.withResolvers<ProviderStatus>();
const connectionStarted = Promise.withResolvers<void>();
const finishConnection = Promise.withResolvers<void>();
const unavailable: ProviderStatus = { available: false, diagnostic: "Sign in first" };
const harness = createProviderHarness({
capabilities: ["prompt.message", "session.list", "session.launch_wrap"],
async handleInput(input) {
throw new Error(`Unexpected provider input: ${input.type}`);
},
});
const registry = new PluginAgentClientRegistry(createTestLogger());
registry.replace([
{
...harness.registration,
command: [process.execPath],
launchWrap: true,
status() {
statusStarted.resolve();
return finishStatus.promise;
},
async connect(request) {
connectionStarted.resolve();
await finishConnection.promise;
return harness.registration.connect(request);
},
},
]);
const client = registry.clients()[harness.registration.id]!;
try {
const first = client.listImportableSessions!();
await statusStarted.promise;
const wrap = client.requireLaunchWrap!();
await connectionStarted.promise;
const second = client.listImportableSessions!();
finishStatus.resolve(unavailable);
finishConnection.resolve();
await Promise.all([
expect(Promise.all([first, second])).resolves.toEqual([[], []]),
expect(wrap).resolves.toBeUndefined(),
]);
expect(harness.inputs).toEqual([]);
} finally {
finishStatus.resolve(unavailable);
finishConnection.resolve();
await registry.shutdown();
}
});
test("cold listing surfaces status() failures and does not block shutdown", async () => {
const logger = createTestLogger();
let resolveHangingStatus: ((value: { available: true }) => void) | undefined;
let hangingConnects = 0;
const failingRegistration: ProviderRegistration = {
id: "lazy-status-error",
label: "Lazy Status Error",
command: [process.execPath, "-e", ""],
async status() {
throw new Error("Plugin RPC timed out");
},
async connect() {
throw new Error("should not connect after status() failure");
},
};
const hangingRegistration: ProviderRegistration = {
id: "lazy-status-hang",
label: "Lazy Status Hang",
command: [process.execPath, "-e", ""],
status() {
return new Promise((resolve) => {
resolveHangingStatus = resolve;
});
},
async connect() {
hangingConnects += 1;
throw new Error("should not connect after shutdown");
},
};
const plugins = new PluginAgentClientRegistry(logger);
plugins.replace([failingRegistration, hangingRegistration]);
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
const clients = {
"lazy-status-error": registry["lazy-status-error"].createClient(logger),
"lazy-status-hang": registry["lazy-status-hang"].createClient(logger),
};
const manager = new AgentManager({
logger,
clients,
providerDefinitions: {
"lazy-status-error": registry["lazy-status-error"],
"lazy-status-hang": registry["lazy-status-hang"],
},
});
const errorListing = await manager.listImportableSessions({
limit: 20,
providerFilter: new Set(["lazy-status-error"]),
});
expect(errorListing.sessions).toEqual([]);
expect(errorListing.providerErrors).toEqual([
{
provider: "lazy-status-error",
message: "Plugin RPC timed out",
},
]);
const hangingListing = clients["lazy-status-hang"].listImportableSessions?.();
await expect.poll(() => resolveHangingStatus, { timeout: 2_000 }).toBeDefined();
// Shutdown must complete without waiting on an in-flight cold status() probe.
await plugins.shutdown();
resolveHangingStatus?.({ available: true });
await expect(hangingListing).rejects.toThrow("Provider runtime is closed");
expect(hangingConnects).toBe(0);
});
@@ -183,10 +183,18 @@ function toProviderLaunch(launch: ProviderInstallationLaunch): ProviderLaunch {
return { command: launch.command, args: launch.args, env: launch.env };
}
class ProviderExecutableNotFoundError extends Error {
constructor(public readonly command: string) {
super(`${command} not found on PATH`);
this.name = "ProviderExecutableNotFoundError";
}
}
class ProviderRuntime {
private connection: ProviderConnection | null = null;
connectedLaunch: ProviderLaunch | undefined;
private connecting: Promise<ProviderConnection> | null = null;
private listingConnect: Promise<ProviderConnection | null> | null = null;
private closed = false;
private generation = 0;
private closePromise: Promise<void> | null = null;
@@ -252,7 +260,7 @@ class ProviderRuntime {
this.registration.status ? { probe: false } : undefined,
);
if (!launch) return undefined;
if (!launch.resolved) throw new Error(`${launch.command} not found on PATH`);
if (!launch.resolved) throw new ProviderExecutableNotFoundError(launch.command);
return toProviderLaunch(launch);
}
@@ -380,6 +388,10 @@ class ProviderRuntime {
return callback({ ...options, launch: launch && toProviderLaunch(launch) });
}
get canProbeSessionListing(): boolean {
return !this.closed && this.connection === null;
}
get negotiatedCapabilities(): readonly string[] {
return this.connection?.capabilities ?? [];
}
@@ -413,8 +425,8 @@ class ProviderRuntime {
limit?: number;
} = {},
): Promise<Extract<ProviderEvent, { type: "sessions" }>["sessions"]> {
const connection = await this.getConnection();
if (!connection.capabilities.includes("session.list")) return [];
const connection = await this.ensureConnectionForListing();
if (!connection || !connection.capabilities.includes("session.list")) return [];
const event = await this.complete({ type: "sessions", requestId: randomUUID(), ...input });
if (event.type !== "sessions")
throw new Error("Provider returned an invalid sessions response");
@@ -498,6 +510,8 @@ class ProviderRuntime {
const connection = this.connection;
const connecting = connection ? null : this.connecting;
this.connection = null;
// A plugin's status hook can outlive shutdown.
this.listingConnect = null;
this.unsubscribe?.();
this.unsubscribe = null;
for (const session of this.sessions.values()) session.connectionClosed();
@@ -564,12 +578,44 @@ class ProviderRuntime {
this.providerSessions.delete(providerSessionId);
}
private getConnection(): Promise<ProviderConnection> {
private ensureConnectionForListing(): Promise<ProviderConnection | null> {
if (this.closed) return Promise.reject(new Error("Provider runtime is closed"));
if (this.connection) return Promise.resolve(this.connection);
if (this.listingConnect) return this.listingConnect;
const attempt = this.connecting ?? this.connectForListing();
const pending = attempt
.catch((error: unknown) => {
if (error instanceof ProviderExecutableNotFoundError) return null;
throw error;
})
.finally(() => {
if (this.listingConnect === pending) this.listingConnect = null;
});
this.listingConnect = pending;
return pending;
}
private async connectForListing(): Promise<ProviderConnection | null> {
const launchPromise = this.resolveLaunch();
const launch = await launchPromise;
if (this.closed) throw new Error("Provider runtime is closed");
if (this.registration.status) {
const status = ProviderStatusSchema.parse(await this.registration.status({ launch }));
if (this.closed) throw new Error("Provider runtime is closed");
if (!status.available) return null;
}
return this.getConnection(launchPromise);
}
private getConnection(
launchPromise?: Promise<ProviderLaunch | undefined>,
): Promise<ProviderConnection> {
if (this.closed) return Promise.reject(new Error("Provider runtime is closed"));
if (this.connection) return Promise.resolve(this.connection);
if (this.connecting) return this.connecting;
const generation = this.generation;
const connecting = this.establishConnection(generation);
const connecting = this.establishConnection(generation, launchPromise ?? this.resolveLaunch());
this.connecting = connecting;
connecting.then(
() => {
@@ -584,8 +630,12 @@ class ProviderRuntime {
return connecting;
}
private async establishConnection(generation: number): Promise<ProviderConnection> {
const launch = await this.resolveLaunch();
private async establishConnection(
generation: number,
launchPromise: Promise<ProviderLaunch | undefined>,
): Promise<ProviderConnection> {
const launch = await launchPromise;
if (this.closed) throw new Error("Provider runtime is closed");
const rawConnection = await this.registration.connect({
launch,
clientInfo: resolvePluginClientInfo(),
@@ -1212,7 +1262,9 @@ class PluginAgentClient implements AgentClient {
}
get capabilities(): AgentCapabilityFlags {
return agentCapabilities(this.runtime.negotiatedCapabilities);
const capabilities = agentCapabilities(this.runtime.negotiatedCapabilities);
if (this.runtime.canProbeSessionListing) capabilities.supportsSessionListing = true;
return capabilities;
}
async requireLaunchWrap(): Promise<void> {
@@ -196,7 +196,7 @@ describe("Claude SDK env", () => {
await resumed.run("after disable");
expect(prompts).toEqual([
{ type: "preset", preset: "claude_code", append: "Plugin instructions" },
{ type: "preset", preset: "claude_code", append: "" },
{ type: "preset", preset: "claude_code", append: "", snapshot: false },
]);
} finally {
await resumed.close();
@@ -2847,18 +2847,37 @@ 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=96",
`--max-old-space-size=${heapCapMiB}`,
"--import",
import.meta.resolve("tsx"),
"--input-type=module",
"--eval",
`
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"))};
`${childImports}
import { mkdir, symlink } from "node:fs/promises";
import path from "node:path";
const clients = [];
@@ -4240,6 +4240,8 @@ class ClaudeAgentSession implements AgentSession {
type: "preset",
preset: "claude_code",
append: appendedSystemPrompt,
// Rebuild on resume so the current launch can replace or remove plugin instructions.
...(sessionBinding.resume ? { snapshot: false } : {}),
},
settingSources: CLAUDE_SETTING_SOURCES,
stderr: (data: string) => {
@@ -1,5 +1,5 @@
import { describe, expect, onTestFinished, test } from "vitest";
import { setImmediate as waitForImmediate } from "node:timers/promises";
import { setImmediate as waitForImmediate, setTimeout as delay } from "node:timers/promises";
import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -148,6 +148,9 @@ class ManualIdleScheduler implements OmpProviderIdleScheduler {
if (this.waitCount >= count) return Promise.resolve();
return new Promise((resolve) => this.waiters.push({ count, resolve }));
}
waits(): number {
return this.waitCount;
}
retry(): void {
const resolve = this.retries.shift();
@@ -540,10 +543,78 @@ describe("OMP agent client and session", () => {
args: { command: "sleep 30" },
});
expect(omp.runningToolCallIds()).toEqual(["tool-at-deadline"]);
await new Promise((resolve) => setTimeout(resolve, 60));
await delay(60);
scheduler.retry();
await expect(completion).rejects.toThrow(/provider idle/i);
expect(omp.runningToolCallIds()).toEqual([]);
// The provider still owned the turn when the gate expired. Abort it so the
// next prompt is not rejected with "Agent is already processing".
expect(omp.wasAborted()).toBe(true);
});
test("does not start the idle wait for a non-terminal agent_end", async () => {
const scheduler = new ManualIdleScheduler();
const omp = new OmpHarness({ providerIdleScheduler: scheduler, providerIdleDeadlineMs: 50 });
await omp.start();
const { completion } = await omp.startPromptWithNonTerminalEnd("first", "first done");
await delay(70);
expect(scheduler.waits()).toBe(0);
expect(omp.completedTurnCount()).toBe(0);
const runtime = omp.runtime();
runtime.beginTurn();
runtime.streamAssistantText("continued");
runtime.state = { ...runtime.state, isStreaming: false, isCompacting: false };
runtime.finishTurn();
await expect(completion).resolves.toMatchObject({
finalText: expect.stringContaining("continued"),
});
});
test("extends the idle deadline while the provider keeps producing events", async () => {
const scheduler = new ManualIdleScheduler();
const omp = new OmpHarness({ providerIdleScheduler: scheduler, providerIdleDeadlineMs: 80 });
await omp.start();
const { completion } = await omp.startPromptUntilProviderIdle("first", "first done", {
isStreaming: true,
isCompacting: false,
});
await scheduler.waitForWaits(1);
await delay(50);
omp.runtime().emit({ type: "turn_start" });
await delay(50);
scheduler.retry();
await waitForImmediate();
expect(omp.completedTurnCount()).toBe(0);
omp.reportProviderState({ isStreaming: false, isCompacting: false });
scheduler.retry();
await expect(completion).resolves.toMatchObject({ finalText: "first done" });
});
test("keeps the turn active while an OMP question waits for the user", async () => {
const scheduler = new ManualIdleScheduler();
const omp = new OmpHarness({ providerIdleScheduler: scheduler, providerIdleDeadlineMs: 50 });
await omp.start();
const { completion } = await omp.startPromptUntilProviderIdle("first", "first done", {
isStreaming: true,
isCompacting: false,
});
await scheduler.waitForWaits(1);
omp.requestToolApproval({ id: "approval-1", tool: "bash", detail: "echo hi" });
scheduler.retry();
await delay(70);
expect(omp.completedTurnCount()).toBe(0);
omp.reportProviderState({ isStreaming: false, isCompacting: false });
await omp.respondToPermission("approval-1", { behavior: "allow" });
await expect(completion).resolves.toMatchObject({ finalText: "first done" });
});
test("steers a running turn and correlates a template-expanded echo exactly once", async () => {
@@ -2296,3 +2367,26 @@ describe("OMP catalog model labels", () => {
expect(catalog.models[0]?.id).toBe(`${model.provider}/${model.id}`);
});
});
test("OMP catalog sessions skip startup work that agent sessions keep", async () => {
const runtime = new FakeOmp();
const client = new OmpAgentClient({ logger: createTestLogger(), runtime });
const catalogOnlyFlags = ["--no-skills", "--no-session", "--no-title"];
await client.fetchCatalog({ scope: "workspace", cwd: "/workspace/project", force: false });
const session = await client.createSession({ provider: "omp", cwd: "/workspace/project" });
onTestFinished(() => session.close());
const [catalogLaunch, agentLaunch] = runtime.recordedLaunches;
expect(catalogLaunch?.argv).toEqual([
"omp",
"--mode",
"rpc-ui",
"--approval-mode",
"yolo",
...catalogOnlyFlags,
]);
for (const flag of catalogOnlyFlags) {
expect(agentLaunch?.argv).not.toContain(flag);
}
});
@@ -721,6 +721,8 @@ export class OmpAgentSession implements AgentSession {
);
private closed = false;
private live: boolean;
private lastProviderActivityAt = Date.now();
private readonly extensionUiWaiters = new Set<() => void>();
private readonly emittedUserMessageIds = new Set<string>();
private readonly usageSessionKey = randomUUID();
@@ -891,6 +893,7 @@ export class OmpAgentSession implements AgentSession {
throw new Error("An OMP turn is already active");
}
this.lastProviderActivityAt = Date.now();
const turnId = randomUUID();
this.live = true;
this.activeTurnId = turnId;
@@ -978,6 +981,7 @@ export class OmpAgentSession implements AgentSession {
return { status: "unavailable" };
if (this.parseSlashCommandInput(payload.text)) return { status: "unavailable" };
const submission = this.rememberClientMessage(options.clientMessageId ?? null, payload.text);
this.lastProviderActivityAt = Date.now();
try {
await this.runtimeSession.steer(payload.text, payload.images);
} catch (error) {
@@ -1150,6 +1154,8 @@ export class OmpAgentSession implements AgentSession {
throw new Error(`No pending permission request with id '${requestId}'`);
}
this.pendingExtensionUiRequests.delete(requestId);
this.lastProviderActivityAt = Date.now();
this.notifyExtensionUiWaiters();
const approvalResponse = buildOmpRpcUiPermissionResponse(request, response);
if (approvalResponse) {
@@ -1188,6 +1194,7 @@ export class OmpAgentSession implements AgentSession {
async interrupt(): Promise<void> {
const turnId = this.activeTurnId;
await this.runtimeSession.abort();
this.clearPendingExtensionUiRequests();
if (turnId && this.activeTurnId === turnId) {
this.usagePoller.stopTurn();
this.resetActiveTurn({ terminalizeWork: true });
@@ -1242,6 +1249,7 @@ export class OmpAgentSession implements AgentSession {
this.unsubscribeRuntime?.();
this.usagePoller.close();
this.cancelNoTurnPromptCompletion();
this.clearPendingExtensionUiRequests();
try {
await this.runtimeSession.close();
} finally {
@@ -1289,6 +1297,7 @@ export class OmpAgentSession implements AgentSession {
this.pendingClientMessages.length = 0;
this.turnMeter.reset();
this.clearNoTurnBuffers();
this.wakeExtensionUiWaiters();
}
async listCommands(): Promise<AgentSlashCommand[]> {
@@ -1671,6 +1680,8 @@ export class OmpAgentSession implements AgentSession {
/** OMP aborted or timed out a dialog: close its card without a reply OMP would reject. */
private closeExtensionUiRequest(requestId: string): void {
if (!this.pendingExtensionUiRequests.delete(requestId)) return;
this.lastProviderActivityAt = Date.now();
this.notifyExtensionUiWaiters();
this.questionUi.forget(requestId);
this.emit({
type: "permission_resolved",
@@ -1681,6 +1692,29 @@ export class OmpAgentSession implements AgentSession {
});
}
private waitForExtensionUiRequestsToClear(): Promise<void> {
if (this.pendingExtensionUiRequests.size === 0) return Promise.resolve();
return new Promise((resolve) => this.extensionUiWaiters.add(resolve));
}
private notifyExtensionUiWaiters(): void {
if (this.pendingExtensionUiRequests.size > 0) return;
this.wakeExtensionUiWaiters();
}
private wakeExtensionUiWaiters(): void {
for (const resolve of this.extensionUiWaiters) resolve();
this.extensionUiWaiters.clear();
}
private clearPendingExtensionUiRequests(): void {
for (const requestId of this.pendingExtensionUiRequests.keys()) {
this.questionUi.forget(requestId);
}
this.pendingExtensionUiRequests.clear();
this.wakeExtensionUiWaiters();
}
private mapExtensionUiSideEffect(
event: Extract<OmpRuntimeEvent, { type: "extension_ui_request" }>,
): AgentTimelineItem | null {
@@ -1851,6 +1885,9 @@ export class OmpAgentSession implements AgentSession {
}
private handleRuntimeEvent(event: OmpRuntimeEvent): void {
// The idle deadline measures provider silence. Any event, including a
// non-terminal agent_end or a subagent update, proves OMP is still alive.
this.lastProviderActivityAt = Date.now();
if (isExtensionUiRequestEvent(event)) {
this.handleExtensionUiRequest(event);
return;
@@ -1989,6 +2026,12 @@ export class OmpAgentSession implements AgentSession {
this.handleCompactionEvent(event, turnId);
return;
case "agent_end": {
// OMP reports a turn that has a queued continuation or async delivery
// as non-terminal. The final end owns the idle wait; starting the
// failure clock here would fail a turn that is still running.
if (event.isTerminal === false) {
return;
}
const messages = event.messages ?? [];
let terminalMessages: OmpAgentMessage[] | null = null;
if (messages.some((message) => message.role === "assistant")) {
@@ -2321,17 +2364,16 @@ export class OmpAgentSession implements AgentSession {
turnId: string | undefined,
messages: OmpAgentMessage[],
): Promise<void> {
const deadline = Date.now() + this.providerIdleDeadlineMs;
while (!this.closed && this.activeTurnStarted && this.currentTurnIdForEvent() === turnId) {
if (Date.now() >= deadline) {
// A question or approval waiting for the user is not a hung provider.
// Wait for the card to settle instead of counting the wait as silence.
if (this.pendingExtensionUiRequests.size > 0) {
await this.waitForExtensionUiRequestsToClear();
continue;
}
if (Date.now() - this.lastProviderActivityAt >= this.providerIdleDeadlineMs) {
this.usagePoller.stopTurn();
this.resetActiveTurn({ terminalizeWork: true });
this.emit({
type: "turn_failed",
provider: this.provider,
turnId,
error: "OMP provider idle deadline exceeded",
});
await this.failProviderIdleTurn(turnId);
return;
}
try {
@@ -2352,6 +2394,34 @@ export class OmpAgentSession implements AgentSession {
}
}
/**
* The provider still owns the turn after the idle deadline. Abort it before
* failing so the next prompt is not rejected with "Agent is already
* processing"; if the abort fails, replace the runtime on the next prompt.
*/
private async failProviderIdleTurn(turnId: string | undefined): Promise<void> {
try {
await this.runtimeSession.abort();
} catch (error) {
this.logger.warn(
{ err: error },
"OMP idle deadline abort failed; the next prompt will replace the runtime",
);
this.runtimeDead = true;
}
this.clearPendingExtensionUiRequests();
if (this.closed || this.currentTurnIdForEvent() !== turnId) {
return;
}
this.resetActiveTurn({ terminalizeWork: true });
this.emit({
type: "turn_failed",
provider: this.provider,
turnId,
error: "OMP provider idle deadline exceeded",
});
}
private async refreshState(): Promise<void> {
this.installState(await this.runtimeSession.getState());
}
@@ -2660,7 +2730,11 @@ export class OmpAgentClient implements AgentClient {
cwd: options.scope === "global" ? homedir() : options.cwd,
protocolMode: "rpc-ui",
modeId: launchMode.modeId,
extraArgs: launchMode.extraArgs,
// Catalogue sessions only answer get_available_models. --no-skills stops OMP's
// startup routing-hint compression calls, which the close would cancel every
// refresh. Never add --no-tools: it skips provider extensions, and
// get_available_models then never answers.
extraArgs: [...launchMode.extraArgs, "--no-skills", "--no-session", "--no-title"],
signal: context?.signal,
});
if (context?.signal.aborted) await closeSession();
@@ -384,7 +384,13 @@ export const OmpAgentSessionEventSchema = z.discriminatedUnion("type", [
})
.passthrough(),
z
.object({ type: z.literal("agent_end"), messages: z.array(OmpAgentMessageSchema).optional() })
.object({
type: z.literal("agent_end"),
messages: z.array(OmpAgentMessageSchema).optional(),
// OMP marks an end that still has a queued continuation or async delivery
// as non-terminal. The final end is the one that owns the idle wait.
isTerminal: z.boolean().optional(),
})
.passthrough(),
]);
@@ -488,9 +488,16 @@ export class FakeOmpSession implements OmpRuntimeSession {
}
}
finishTurn(message: OmpAgentMessage = { role: "assistant", content: [] }): void {
finishTurn(
message: OmpAgentMessage = { role: "assistant", content: [] },
options: { isTerminal?: boolean } = {},
): void {
this.messages = [...this.messages, message];
this.emit({ type: "agent_end", messages: this.messages });
this.emit({
type: "agent_end",
messages: this.messages,
...(options.isTerminal === undefined ? {} : { isTerminal: options.isTerminal }),
});
}
finishTurnWithEmptyAgentEnd(message: OmpAgentMessage = { role: "assistant", content: [] }): void {
@@ -283,6 +283,23 @@ export class OmpHarness {
return { completion: run };
}
async startPromptWithNonTerminalEnd(
input: string,
output: string,
): Promise<{ completion: Promise<unknown> }> {
const session = this.requireSession();
const promptStarted = this.omp.latestSession().nextPrompt();
const completion = session.run(input);
await promptStarted;
const runtime = this.omp.latestSession();
runtime.beginTurn();
runtime.acceptPrompt(input, "user-1");
runtime.streamAssistantText(output);
runtime.state = { ...runtime.state, isStreaming: true, isCompacting: false };
runtime.finishTurn(undefined, { isTerminal: false });
return { completion };
}
waitForProviderStateChecks(count: number): Promise<void> {
return this.omp.latestSession().waitForStateRequests(count);
}
@@ -83,7 +83,6 @@ 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",
@@ -345,8 +344,6 @@ 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",
-1
View File
@@ -1928,7 +1928,6 @@ 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,
@@ -1,181 +0,0 @@
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);
});
});
@@ -1,163 +0,0 @@
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"],
},
],
},
]);
});
});
@@ -1,262 +0,0 @@
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,9 +43,6 @@ export interface HostActor {
interface Live {
client: DaemonClient;
accepted: boolean;
version: string | null;
permissions?: DaemonPermission[];
connectedAt: string | null;
stop(): void;
}
interface Route {
@@ -65,7 +62,7 @@ export class ConnectedHosts {
private closed = false;
constructor(
private readonly home: string,
private readonly self: HostDirectory["self"] & { version?: string },
private readonly self: HostDirectory["self"],
) {
this.ready = this.load();
void this.ready.catch(() => {});
@@ -89,8 +86,8 @@ export class ConnectedHosts {
async list(): Promise<HostDirectory> {
await this.ready;
return {
self: { serverId: this.self.serverId, label: this.self.label },
hosts: this.rows.map((row) => this.summary(row)),
self: { ...this.self },
hosts: this.rows.map(({ connection: _secret, ...row }) => structuredClone(row)),
};
}
observe(changed: () => void): () => void {
@@ -121,17 +118,7 @@ export class ConnectedHosts {
}
private summary(row: Saved): HostSummary {
const { connection: _secret, ...summary } = row;
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);
return structuredClone(summary);
}
add(input: HostAdd, actor: HostActor): Promise<HostSummary> {
return this.mutate(async () => {
@@ -267,18 +254,10 @@ 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);
@@ -334,9 +313,6 @@ 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();
});
@@ -360,9 +336,6 @@ 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,15 +77,8 @@ 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" ||
@@ -135,7 +128,6 @@ 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.
@@ -179,7 +171,6 @@ 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";
@@ -209,7 +200,6 @@ 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) {
-13
View File
@@ -296,21 +296,8 @@ 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);
@@ -1,12 +1,15 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import pino from "pino";
import { expect, test } from "vitest";
import { DaemonClient } from "../test-utils/daemon-client.js";
import type { AgentClient, AgentSessionConfig } from "../agent/agent-sdk-types.js";
import { ClaudeAgentClient } from "../agent/providers/claude/agent.js";
import { createTestAgentClient } from "../test-utils/fake-agent-client.js";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
import { createTestPaseoDaemon, type TestPaseoDaemon } from "../test-utils/paseo-daemon.js";
test("the configuration example saves Codex options and injects launch-only MCP servers while preserving other configuration", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-config-example-"));
@@ -73,6 +76,132 @@ test("the configuration example saves Codex options and injects launch-only MCP
}
}, 60_000);
test("Claude sends the current plugin system prompt after refreshing a session", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-claude-append-"));
const configDir = path.join(directory, "claude");
const pluginId = "claude-append-test";
const requests: { markers: string[]; hasPriorTurn: boolean }[] = [];
const model = "claude-haiku-4-5-20251001";
// Run Claude Code's real prompt assembly and resume logic with a local Messages endpoint.
const server = createServer(async (request, response) => {
let body = "";
for await (const chunk of request) body += chunk;
if (!request.url?.match(/^\/v1\/messages(?:\?|$)/)) {
response.writeHead(200, { "content-type": "application/json" });
response.end("{}");
return;
}
const payload = JSON.parse(body);
const system = JSON.stringify(payload.system ?? "");
requests.push({
markers: ["PASEO-APPEND-ALPHA", "PASEO-APPEND-BETA"].filter((marker) =>
system.includes(marker),
),
hasPriorTurn: JSON.stringify(payload.messages).includes("First turn of the append test."),
});
const events = [
{
type: "message_start",
message: {
id: `msg_append_${requests.length}`,
type: "message",
role: "assistant",
model,
content: [],
stop_reason: null,
stop_sequence: null,
usage: { input_tokens: 100, output_tokens: 0 },
},
},
{ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
{ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "OK" } },
{ type: "content_block_stop", index: 0 },
{ type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
{ type: "message_stop" },
];
response.writeHead(200, { "content-type": "text/event-stream" });
response.end(
events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""),
);
});
async function writeHook(marker: string) {
await writeFile(
path.join(directory, "index.server.ts"),
`export default function contribute(server) {
return server.addHook("agent.open.before", ({ request }) => ({
...request,
appendSystemPrompt: [${JSON.stringify(marker)}],
}));
}`,
);
}
let daemon: TestPaseoDaemon | undefined;
let client: DaemonClient | undefined;
try {
await mkdir(configDir);
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: pluginId, requirements: { paseo: ">=0.17.0" } }),
);
await writeHook("PASEO-APPEND-ALPHA");
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Fixture has no TCP address");
const logger = pino({ level: "silent" });
daemon = await createTestPaseoDaemon({
daemonVersion: "0.17.5",
agentClients: {
claude: new ClaudeAgentClient({
logger,
runtimeSettings: {
env: {
ANTHROPIC_BASE_URL: `http://127.0.0.1:${address.port}`,
ANTHROPIC_AUTH_TOKEN: "fixture-token",
ANTHROPIC_API_KEY: "",
CLAUDE_CODE_OAUTH_TOKEN: "",
CLAUDE_CONFIG_DIR: configDir,
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
},
},
}),
},
mcpEnabled: false,
});
client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.17.5" });
await client.connect();
await client.fetchAgents({ subscribe: {} });
await client.patchDaemonConfig({ pluginsEnabled: true });
expect((await client.installDirectoryPlugin(directory)).status).toBe("running");
const agent = await client.createAgent({ provider: "claude", cwd: directory, model });
await client.sendMessage(agent.id, "First turn of the append test.");
expect((await client.waitForFinish(agent.id, 15_000)).status).toBe("idle");
expect(requests.at(-1)?.markers).toEqual(["PASEO-APPEND-ALPHA"]);
await writeHook("PASEO-APPEND-BETA");
expect((await client.reloadPlugin(pluginId)).status).toBe("running");
await client.refreshAgent(agent.id);
await client.sendMessage(agent.id, "Second turn of the append test.");
expect((await client.waitForFinish(agent.id, 15_000)).status).toBe("idle");
expect(requests.at(-1)).toEqual({ markers: ["PASEO-APPEND-BETA"], hasPriorTurn: true });
await client.disablePlugin(pluginId);
await client.refreshAgent(agent.id);
await client.sendMessage(agent.id, "Third turn of the append test.");
expect((await client.waitForFinish(agent.id, 15_000)).status).toBe("idle");
expect(requests.at(-1)).toEqual({ markers: [], hasPriorTurn: true });
expect(requests).toHaveLength(3);
} finally {
await client?.close();
await daemon?.close();
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
await rm(directory, { recursive: true, force: true });
}
}, 60_000);
test("session-open entrypoint contributions are optional and rederived for existing agents", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-entrypoint-hook-"));
const launches: { provider: string; env?: Record<string, string> }[] = [];
-8
View File
@@ -661,10 +661,6 @@ 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 =
@@ -1261,8 +1257,6 @@ export class Session {
daemonVersion,
daemonRuntimeConfig,
getWebSocketRuntimeMetrics,
listConnectedClients: options.listConnectedClients,
observeConnectedClients: options.observeConnectedClients,
getObservationMetrics: () => ({
Registrations: this.delivery.registrationCount,
"Source registrations": this.delivery.sourceRegistrationCount(),
@@ -3481,8 +3475,6 @@ 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,12 +2,7 @@ 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 {
DaemonClientsSnapshot,
SessionInboundMessage,
SessionOutboundMessage,
} from "../../messages.js";
import type { SessionDelivery } from "../owned-subscriptions/index.js";
import type { SessionInboundMessage, SessionOutboundMessage } from "../../messages.js";
import { getPidLockInfo } from "../../pid-lock.js";
import { readUnconfirmedTerminalCleanup } from "../../../terminal/terminal-worker-reaper.js";
import { generateLocalPairingOffer } from "../../pairing-offer.js";
@@ -31,7 +26,6 @@ export interface DaemonRuntimeConfig {
) =>
| ReturnType<ReturnType<typeof createDaemonListeners>["status"]>
| Promise<ReturnType<ReturnType<typeof createDaemonListeners>["status"]>>;
isTailscaleEndpoint?: (localEndpoint?: string) => boolean;
setTailscaleEnabled?: DaemonConfigStore["setTailscaleEnabled"];
getRelayConfig(): {
enabled: boolean;
@@ -69,8 +63,6 @@ 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>;
@@ -97,8 +89,6 @@ 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;
@@ -118,8 +108,6 @@ 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;
@@ -209,57 +197,6 @@ 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,
+14 -160
View File
@@ -15,12 +15,6 @@ 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 {
@@ -498,12 +492,8 @@ 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>;
}
@@ -536,8 +526,6 @@ interface SocketSessionOptions {
onLifecycleIntent?: (intent: SessionLifecycleIntent) => void;
hubExecutionAgents?: HubExecutionAgents;
hubRelationships?: HubRelationshipManagement;
listConnectedClients?: SessionOptions["listConnectedClients"];
observeConnectedClients?: SessionOptions["observeConnectedClients"];
}
interface ClosePhysicalSocketParams {
@@ -640,7 +628,6 @@ export class VoiceAssistantWebSocketServer {
private readonly downloadTokenStore: DownloadTokenStore;
private readonly paseoHome: string;
private readonly connectedHosts: ConnectedHosts;
private readonly connectedClientsNotifier = createConnectedClientsNotifier();
toolHosts() {
return createToolHosts(this.connectedHosts);
@@ -861,11 +848,7 @@ export class VoiceAssistantWebSocketServer {
this.workspaceAutoName = workspaceAutoName;
this.downloadTokenStore = downloadTokenStore;
this.paseoHome = paseoHome;
this.connectedHosts = new ConnectedHosts(paseoHome, {
serverId,
label: getHostName(),
version: this.daemonVersion,
});
this.connectedHosts = new ConnectedHosts(paseoHome, { serverId, label: getHostName() });
this.passwordHash = auth?.password;
this.daemonConfigStore = daemonConfigStore;
this.mcpBaseUrl = mcpBaseUrl;
@@ -1248,7 +1231,6 @@ export class VoiceAssistantWebSocketServer {
);
}
}
this.connectedClientsNotifier.notify();
}
public prepareForShutdown(): void {
@@ -1264,7 +1246,6 @@ 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?.();
@@ -1658,27 +1639,14 @@ 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,
clientType,
clientInfo,
appVersion,
clientCapabilities,
connectionLogger,
lifecycle,
admission,
identity,
} = params;
const { ws, clientId, appVersion, clientCapabilities, connectionLogger, lifecycle, admission } =
params;
let connection: SessionConnection | null = null;
const session = this.createSocketSession({
@@ -1692,9 +1660,6 @@ 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;
@@ -1748,12 +1713,8 @@ 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]),
};
@@ -1881,90 +1842,6 @@ 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,
});
}
@@ -2029,7 +1906,15 @@ export class VoiceAssistantWebSocketServer {
}
this.clearPendingConnection(ws);
const admitted = applySessionPermissionCeiling(pending.admission, message.sessionPermissions);
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),
),
};
pending.admission = admitted;
pending.identity.clientId = clientId;
if (message.appVersion) {
@@ -2047,14 +1932,11 @@ 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);
@@ -2065,7 +1947,6 @@ export class VoiceAssistantWebSocketServer {
}
pending.identity.sessionId = connection.session.getSessionId();
this.sendHelloResponse(ws, connection.session, message);
this.connectedClientsNotifier.notify();
connection.connectionLogger.info(
{
...toConnectionLogFields(pending.identity),
@@ -2179,9 +2060,6 @@ 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);
@@ -2205,7 +2083,6 @@ 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),
@@ -2311,8 +2188,6 @@ 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.
@@ -2618,7 +2493,6 @@ 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") {
@@ -2708,7 +2582,6 @@ export class VoiceAssistantWebSocketServer {
logMessage,
);
await connection.session.cleanup();
this.connectedClientsNotifier.notify();
}
private handleInvalidInboundMessage(args: {
@@ -3026,10 +2899,8 @@ export class VoiceAssistantWebSocketServer {
principalId: connection.principalId,
permissions,
}),
onChannelsChanged: () => this.connectedClientsNotifier.notify(),
});
this.hostLinks.set(ws, link);
this.connectedClientsNotifier.notify();
}
return link;
}
@@ -3039,11 +2910,8 @@ export class VoiceAssistantWebSocketServer {
activeConnection: SessionConnection,
message: Extract<WSInboundMessage, { type: "session" }>,
): Promise<void> {
const link =
message.message.type === "hosts.link.open.request" || this.hostLinks.has(ws)
? this.hostLink(ws, activeConnection)
: null;
if (link?.handles(message.message)) {
const link = this.hostLink(ws, activeConnection);
if (link.handles(message.message)) {
await activeConnection.session.delivery.request(ws, message.message, () =>
link.dispatch(message.message),
);
@@ -3584,20 +3452,6 @@ 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]);
}
+20 -4
View File
@@ -26,6 +26,24 @@ 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 () => {
@@ -178,8 +196,7 @@ 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 page.clock.runFor(4500);
await expect(request).toBeVisible();
await playUntilVisible(page, request);
});
test("the opening scene starts in a window shorter than most of the mockup", async ({ page }) => {
@@ -189,8 +206,7 @@ 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 page.clock.runFor(4500);
await expect(request).toBeVisible();
await playUntilVisible(page, request);
});
test("the plugins scene installs the panel, then changes it on request", async ({ page }) => {
+3 -4
View File
@@ -76,7 +76,7 @@ export class Session {
private readonly buffered: Notification[] = [];
private opening = true;
private closing = false;
private firstTurn = true;
private systemPromptPending = true;
private interruptCompletion: {
turnId: string;
resolve(): void;
@@ -122,7 +122,6 @@ export class Session {
model: this.config.model ?? saved.model,
thinkingOption: this.config.thinkingOption ?? saved.thinkingOption,
};
this.firstTurn = false;
} else {
response = await this.host.command(
"session/start",
@@ -242,7 +241,7 @@ export class Session {
this.messages.set(id, prompt.clientMessageId);
const input: TurnStartParams["input"] = [];
const text: string[] = [];
if (this.firstTurn && this.config.systemPrompt)
if (this.systemPromptPending && this.config.systemPrompt)
input.push({
type: "text",
text: `<system_instructions>\n${this.config.systemPrompt}\n</system_instructions>`,
@@ -272,7 +271,7 @@ export class Session {
: undefined,
};
const response = await this.host.command("turn/start", params, promptResultSchema);
this.firstTurn = false;
this.systemPromptPending = false;
if (response.disposition === "started" && this.turns.get(response.turnId) !== "completed")
this.turns.set(response.turnId, "active");
this.live().recovery.activity(undefined, this.activeTurnIds().length > 0);
+29 -11
View File
@@ -89,8 +89,11 @@ async function harness(
}
async function open(
persistence?: Extract<ProviderInput, { type: "session.open" }>["persistence"],
mode = "onRequest",
model: string | null = "meta/muse-spark-1.3",
{
mode = "onRequest",
model = "meta/muse-spark-1.3",
systemPrompt = "Test instructions",
}: { mode?: string; model?: string | null; systemPrompt?: string } = {},
) {
await send({
type: "session.open",
@@ -106,7 +109,7 @@ async function harness(
mode,
model: model ?? undefined,
thinkingOption: "high",
systemPrompt: "Test instructions",
systemPrompt,
},
persistence,
history: "replay",
@@ -411,7 +414,7 @@ test("multi-stage approvals surface Stage 2 then Stage 3 and send the current re
});
test("Full access automatically answers every escalated stage with the published allow-once choice", async () => {
const h = await harness("multi-stage-approval");
await h.open(undefined, "allowAll");
await h.open(undefined, { mode: "allowAll" });
await h.prompt();
await h.wait((event) => event.type === "session.turn" && event.state === "completed");
expect(h.events.filter((event) => event.type === "session.permission")).toEqual([]);
@@ -438,8 +441,8 @@ test("interrupt awaits cancelled terminal and reconciles the tool", async () =>
),
).toBeGreaterThan(terminalIndex);
});
test("a fresh connection restores earlier messages from persisted session state", async () => {
const original = await harness();
test("resume restores earlier messages and sends the current system prompt once", async () => {
const original = await harness("image-followup");
const historyPath = path.join(original.root, "native-history.ndjson");
original.launch.env.MUSE_TEST_HISTORY = historyPath;
await original.open();
@@ -467,10 +470,12 @@ test("a fresh connection restores earlier messages from persisted session state"
}),
);
await original.connection.close();
const reopened = await harness("text-reasoning", { MUSE_TEST_HISTORY: historyPath });
expect(await reopened.open(JSON.parse(await readFile(persistencePath, "utf8")))).toMatchObject({
type: "session.ready",
});
const reopened = await harness("image-followup", { MUSE_TEST_HISTORY: historyPath });
expect(
await reopened.open(JSON.parse(await readFile(persistencePath, "utf8")), {
systemPrompt: "Updated instructions",
}),
).toMatchObject({ type: "session.ready" });
const restored = reopened.events
.filter((event) => event.type === "timeline.item")
.map((event) => event.item)
@@ -483,6 +488,19 @@ test("a fresh connection restores earlier messages from persisted session state"
expect(reopened.events.filter((event) => event.type === "session.turn")).toEqual([]);
await reopened.prompt();
await reopened.wait((event) => event.type === "session.turn" && event.state === "completed");
const from = await reopened.prompt();
await reopened.wait(
(event) => event.type === "session.turn" && event.state === "completed",
from,
);
const turns = (await reopened.recorded()).filter((frame) => frame.method === "turn/start");
expect(turns.map((frame) => frame.params.input)).toEqual([
[
{ type: "text", text: "<system_instructions>\nUpdated instructions\n</system_instructions>" },
{ type: "text", text: "hello" },
],
[{ type: "text", text: "hello" }],
]);
});
for (const cursor of [undefined, "v:old:7"]) {
@@ -890,7 +908,7 @@ for (const [configuredModel, catalogModels, expectedModel] of [
MUSE_TEST_NULL_MODEL: "1",
MUSE_TEST_MODELS: JSON.stringify(catalogModels),
});
expect(await h.open(undefined, "onRequest", configuredModel || null)).toEqual({
expect(await h.open(undefined, { model: configuredModel || null })).toEqual({
type: "session.ready",
requestId: "open",
sessionId: "paseo-session",