Compare commits

...
Author SHA1 Message Date
paseo-bot[bot] 306b9bfb7b test(server): compare profiled and plain config reads on Windows 2026-10-30 12:39:56 +00:00
paseo-bot[bot] 14329d1b98 test(server): diagnose recurring config responsiveness failure 2026-10-30 12:08:00 +00:00
paseo-ai[bot] fbe24fcdb6 fix: update lockfile signatures and Nix hash [skip ci] 2026-10-30 11:06:08 +00:00
Mohamed Boudra 787edb1bf9 Respect proxy variables throughout the daemon (#8177)
* fix(server): respect environment proxies across daemon traffic

Install proxy routing at daemon and plugin process startup, with a separate HTTP agent for outbound WebSockets. Always exempt loopback so local provider bridges remain reachable.

* test(server): run usage source regressions in CI

* fix(server): validate proxy settings without blocking startup

Normalize scheme-less proxies and share HTTP-only validation across fetch and WebSockets. Record ignored variables without credentials in the daemon log. Separate built-in and directory plugin regressions through a typed fixture.

* refactor(server): treat ignored proxy variables as unset

* fix(server): read Windows proxy environment entries once

* fix(server): apply proxy policy to connected host links

* test(server): isolate proxy fixture credential directories

* fix(server): keep proxy routing and authentication consistent

Normalize Windows environment names and wildcard bypass rules at the network boundary. Compare bypass ports numerically and keep Basic proxy credentials on the CONNECT pool, including empty credential fields.
2026-10-30 17:57:57 +07:00
Mohamed Boudra 385c29b655 Keep failed chat history available for retry (#8278)
* fix(app): keep failed chat history until retry

Automatic retries repeatedly reopen provider sessions after persistent failures. Keep the error visible until the user retries, while retaining reconnect recovery.

* fix(app): catch up chats after subscription failure

A failed replacement subscription leaves chats unsubscribed, so discard its old catch-up state and fetch missed history after retry.

* fix(app): recover gaps during history retry

Keep gap recovery active while a user-initiated retry is running so the chat is not marked current before its follow-up fetch.

* fix(app): show history errors in archived chats

Cached archived chats need the same manual retry affordance when history synchronization fails.
2026-10-30 17:57:52 +07:00
Mohamed Boudra 9477fe0c00 fix(app): refresh Android layout after background fold changes (#8285)
Backport the Unistyles 3.5.3 Activity configuration fix while keeping 3.2.4 and its existing fixes. Application resources could leave the responsive shell on the previous fold size after resume. Cover the real device-state sequence with a native UI regression.
2026-10-30 17:22:53 +07:00
531370c4ce fix(pi): show tool-result images live and after reload (#8280)
* pi: render tool-result images as inline image rows (paseo #1717 parity)

* fix(pi): preserve turn ownership while rendering images

* fix(pi): preserve metadata when stripping nested image payloads

---------

Co-authored-by: be-my-bot <bot@be-my-code.local>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: duyiliu <duyiliu@users.noreply.github.com>
2026-10-30 10:10:39 +00:00
paseo-bot[bot] e299b21e94 test(server): measure Git filter work within its callback (#8270)
Exclude unrelated callbacks and fixture garbage from the cold event-filter budget. Keep the 20ms limit and IO assertions, with unrelated CPU work as a regression control.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-30 09:17:50 +00:00
PeanutandPeanut-HZM 1f79efcd62 fix(providers): name the MiniMax Code binary so npx can resolve it (#8201)
The MiniMax Code catalog entry ran `npx -y @minimax-ai/code@0.6.13 acp`.
npx derives the executable from the unscoped package name, which is `code`,
but the package publishes `mcode` and `mcode-tools`. npm therefore exits
with "could not determine executable to run" before the agent starts.

Paseo reports this as a provider that timed out during `initialize`, so the
entry looks like a broken agent rather than a malformed command.

Name the package and the binary separately. The ACP handshake then completes
and the provider reports its models and modes.

Co-authored-by: Peanut-HZM <peanut@hzm.me>
2026-10-30 08:08:14 +00:00
Mohamed Boudra e3682ba18c Usage fetches only when shown, and can be turned off (#8181)
* fix(usage): fetch only when shown and add a host-wide off switch

* fix(usage): restore policy defaults and isolate usage test state

* refactor(usage): give the sidebar footer sole ownership of its summary
2026-10-30 14:32:19 +07:00
80 changed files with 1977 additions and 310 deletions
+10
View File
@@ -493,6 +493,16 @@ The supervisor alone publishes its ready worker's endpoint in `paseo.pid`, clear
Worker restart retains supervisor arguments/environment and rereads the configuration file. Updating a package and observing its new worker version do not refresh the running supervisor code; the launcher owns full-process replacement. See [CLI lifecycle contracts](../public-docs/cli.md#daemon-management).
## Outbound networking
The daemon and its plugin processes honor `HTTPS_PROXY`, `HTTP_PROXY`, and `NO_PROXY`
(including lowercase forms, which take precedence). Fetch and relay, Hub, and connected-host WebSockets
share this policy. Loopback (`localhost`, `127.0.0.1`, `::1`) always goes direct.
A proxy without a scheme uses HTTP. Invalid values and unsupported proxy schemes
are treated as unset, with one warning naming the variable in `daemon.log`.
Agent and terminal environments are unchanged. System proxy settings and SOCKS-only
`ALL_PROXY` configurations are not supported.
## Deployment models
1. **Local daemon** (default): `paseo daemon start` on `127.0.0.1:6767`
+1
View File
@@ -38,6 +38,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
- **Usage source** — Plugin registration that discovers accounts and fetches plan usage. Code: `UsageSourceRegistration` (`packages/plugin/src/server/usage.ts`).
- **Report ID** — Stable daemon-composed identity for one source account: `<sourceId>:<accountKey>`. The source owns the account key; clients treat the whole ID as opaque. Code: `UsageReportEntry.id` (`packages/protocol/src/messages.ts`).
- **Usage report** — A source's normalized usage for one account, including status and optional windows, balances, and details. Its entry carries the Report ID, account label, and fetch time. Each report renders as one card in the Usage modal, in host Settings, and in an agent's context window details (a hover card on desktop web, a tooltip on native wide screens, a sheet on compact ones), which show only the account that agent runs under, without pins. The hover card and the sheet have Refresh; the native tooltip takes no presses. Code: `UsageReport` (`packages/plugin/src/server/usage.ts`), `UsageCard` (`packages/app/src/usage/card.tsx`), `AgentUsage` (`packages/app/src/usage/agent-usage.tsx`).
- **Check usage** — Host-wide switch in Usage Settings, on by default. Turning it off stops login discovery and vendor requests on that host for every device. Usage shows an off state with **Turn on**; the sidebar summary and agent usage sections disappear.
- **Usage (sidebar item)** — The sidebar footer item showing each pinned window's source icon and percent, hidden while no pinned window has data (the footer's Usage icon remains available); both entry points open the Usage modal over the current screen: a dialog on wide layouts, a bottom sheet on compact ones. Usage has no route of its own. Off until the user turns on **Summary in sidebar** (Usage Settings) or the Usage row in Settings > Sidebar; window rows pin only while it is on, and saved pins come back when it is turned on again. A pin is `{ sourceId, windowId }` and shows once per account of that source. Pins and the used/remaining choice are one per-device preference (`AppSettings.usage`) that every usage surface follows. It reads the active workspace's host, else the first connected host with usage sources. Code: `packages/app/src/usage/sidebar-item.tsx`, `usage/usage-modal.tsx`, `usage/pinned.ts`, `usage/preferences.ts`.
- **Model** — A specific LLM offered by a provider. UI: "Model" / "Select model". Code: `AgentModelDefinition` (`packages/protocol/src/messages.ts:187`).
- **Tab** — UI surface representing one session inside a workspace. Not a conceptual unit; use **Agent session** when talking about the model. Code: `WorkspaceTabDescriptor` (`packages/app/src/screens/workspace/workspace-tabs-types.ts`).
+14
View File
@@ -35,6 +35,20 @@ PASEO_MOBILE_E2E_METRO_PORT=62093 npm run test:e2e:mobile
[native-terminal-basic.ios.ad](../packages/app/e2e/mobile/agent-device/native-terminal-basic.ios.ad) and [native-terminal-basic.android.ad](../packages/app/e2e/mobile/agent-device/native-terminal-basic.android.ad) are the smallest examples. Each opens a fresh terminal, types a command at zero delay, submits it, and asserts its distinct output. The app must be connected to a daemon with an active workspace.
For Android background fold recovery, install the release APK on a foldable AVD, open a
connected workspace, close the keyboard, and run:
```bash
ANDROID_SERIAL=emulator-5574 node packages/app/e2e/mobile/fold/android.mjs
```
The AVD must expose `CLOSED` and `OPENED` device states. The test backgrounds the app,
changes posture, resumes immediately, and asserts compact/wide workspace controls without
restarting the process. It writes snapshots and native failure state under
`.dev/agent-device-artifacts/android-fold`. Set `PASEO_MOBILE_APP_ID=sh.paseo` for a
production package. This needs a native rebuild when the Unistyles patch changes; a Metro
reload cannot update it.
For Android keyboard continuity, run the current checkout in the app, open an idle terminal
with an empty prompt, hide its keyboard, and run:
+1 -1
View File
@@ -550,7 +550,7 @@ string is never inline SVG or a URL.
Register a usage source from `index.server.ts` with `server.registerUsageSource()`. Import `UsageSourceRegistration` and normalization helpers from `@getpaseo/plugin/server/usage`. The plugin owns account discovery, harness labels, and credential-store reads; the daemon owns account grouping and the fetch cache. Agent popovers use only the agent's own login. The host-wide Usage modal falls back across an account's logins; any success shows usage only, and all failures show every login's labeled error and remedy. Follow the [usage source discovery contract](../public-docs/plugins/reference.md#usage-sources). The resolved launch environment crosses into the trusted, unsandboxed plugin subprocess for session discovery. Usage queries never run lifecycle hooks. Inputs are validated in the plugin process and remain daemon-side. `icon` uses the same SVG file rules as provider icons.
The daemon calls discovery for `usage.list_reports`; the client gates this RPC on `server_info.features.usageSources`. The old `provider.usage.list` RPC maps discovered reports for older clients.
When the host’s **Check usage** switch is off, the daemon rejects usage requests before discovery, without reading logins or calling vendors. Otherwise, the daemon calls discovery for `usage.list_reports`; the client gates this RPC on `server_info.features.usageSources`. The old `provider.usage.list` RPC maps discovered reports for older clients.
## Contribute sidebar items
+1 -1
View File
@@ -1 +1 @@
sha256-6C4Rjh0mRVrC9akBVGK0NZaCaLJhwKObT7HrgPmcvyw=
sha256-8NOrrCAxraQ74lP3Vy59MRhloBfzStTc4rW+ltc42Fg=
+24
View File
@@ -40690,6 +40690,7 @@
"esbuild": "^0.25.12",
"express": "^4.18.2",
"fast-deep-equal": "^3.1.3",
"https-proxy-agent": "^7.0.6",
"lru-cache": "^11.5.1",
"markdown-it": "^10.0.0",
"mnemonic-id": "^3.2.7",
@@ -40707,6 +40708,7 @@
"strip-ansi": "^7.1.2",
"tree-kill": "^1.2.2",
"typescript": "^5.9.3",
"undici": "^7.24.8",
"uuid": "^9.0.1",
"which": "^5.0.0",
"ws": "^8.14.2",
@@ -41280,6 +41282,15 @@
"url": "https://opencollective.com/vitest"
}
},
"packages/server/node_modules/agent-base": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
"integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
"license": "MIT",
"engines": {
"node": ">= 14"
}
},
"packages/server/node_modules/ajv": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
@@ -41349,6 +41360,19 @@
"@esbuild/win32-x64": "0.25.12"
}
},
"packages/server/node_modules/https-proxy-agent": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
"integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
"license": "MIT",
"dependencies": {
"agent-base": "^7.1.2",
"debug": "4"
},
"engines": {
"node": ">= 14"
}
},
"packages/server/node_modules/isexe": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz",
@@ -0,0 +1,69 @@
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
import { installUsageReportsFixture } from "../support/helpers/usage-reports";
import {
claudeAndCodexReports,
openUsageFromIcon,
openUsageOptions,
closeUsageOptions,
closeUsage,
expectNoUsageItem,
expectPinnedUsage,
} from "../support/helpers/usage-sidebar-item";
test("Check usage applies to the host and Turn on restores cards", async ({
page,
e2eWorkerClient,
}) => {
test.setTimeout(180_000);
const previous = (await e2eWorkerClient.getDaemonConfig()).config.usage ?? { enabled: true };
try {
const usage = await installUsageReportsFixture(page, {
lists: [() => claudeAndCodexReports()],
});
await page.setViewportSize({ width: 1440, height: 1000 });
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await gotoAppShell(page);
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
await openUsageFromIcon(page);
await usage.waitForListRequests(1);
await openUsageOptions(page);
await page.getByRole("switch", { name: "Check usage", exact: true }).click();
await closeUsageOptions(page);
await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toHaveCount(0);
expect((await e2eWorkerClient.getDaemonConfig()).config.usage).toEqual({ enabled: false });
await expectNoUsageItem(page);
const before = usage.listRequests().length;
await closeUsage(page);
await page.reload();
await openUsageFromIcon(page);
await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible();
expect(usage.listRequests()).toHaveLength(before);
await page.getByRole("button", { name: "Turn on", exact: true }).click();
await expect(page.getByText("Claude", { exact: true })).toBeVisible();
expect((await e2eWorkerClient.getDaemonConfig()).config.usage).toEqual({ enabled: true });
// A separate client changes the policy, as another device would.
await e2eWorkerClient.patchDaemonConfig({ usage: { enabled: false } });
await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible();
await e2eWorkerClient.patchDaemonConfig({ usage: { enabled: true } });
await expect(page.getByText("Claude", { exact: true })).toBeVisible();
} finally {
await e2eWorkerClient.patchDaemonConfig({ usage: previous });
}
});
test("older hosts keep usage without a Check usage switch", async ({ page }) => {
test.setTimeout(180_000);
await installUsageReportsFixture(page, {
usageSettingSupported: false,
lists: [() => claudeAndCodexReports()],
});
await page.setViewportSize({ width: 1440, height: 1000 });
await gotoAppShell(page);
await openUsageFromIcon(page);
await expect(page.getByText("Claude", { exact: true })).toBeVisible();
await openUsageOptions(page);
await expect(page.getByRole("switch", { name: "Check usage", exact: true })).toHaveCount(0);
});
@@ -441,3 +441,31 @@ test("released hosts supply source logos through the client conversion", async (
).toHaveAttribute("d", codexPath);
await qaScreenshot(page, "released-host-usage-modal");
});
test("hidden usage sends no requests until opened", async ({ page }) => {
test.setTimeout(180_000);
const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] });
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await expectNoUsageItem(page);
await expect(page.getByRole("button", { name: "Usage", exact: true })).toBeVisible({
timeout: 90_000,
});
await openSidebarNavSettings(page);
await expectFooterItemSetting(page, "usage", false);
await leaveSettings(page);
expect(usage.listRequests()).toHaveLength(0);
await openUsageFromIcon(page);
await usage.waitForListRequests(1);
expect(usage.listRequests()).toHaveLength(1);
});
test("visible usage summary requests reports on load", async ({ page }) => {
test.setTimeout(180_000);
const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] });
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await page.setViewportSize(WIDE);
await gotoAppShell(page);
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
expect(usage.listRequests()).toHaveLength(1);
});
+104
View File
@@ -0,0 +1,104 @@
// Run a release build with a connected workspace open and the keyboard hidden.
// ANDROID_SERIAL=emulator-5574 node packages/app/e2e/mobile/fold/android.mjs
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
const serial = process.env.ANDROID_SERIAL;
assert(serial, "Set ANDROID_SERIAL to a booted Android foldable emulator");
const appId = process.env.PASEO_MOBILE_APP_ID ?? "sh.paseo.debug";
const session = "android-fold";
const artifacts = resolve(".dev/agent-device-artifacts/android-fold");
const env = {
...process.env,
AGENT_DEVICE_STATE_DIR: resolve(".dev/agent-device-android-fold"),
};
mkdirSync(artifacts, { recursive: true });
function run(binary, args) {
return execFileSync(binary, args, { env, encoding: "utf8", timeout: 60_000 });
}
function adb(...args) {
return run("adb", ["-s", serial, ...args]);
}
function ad(...args) {
return run("agent-device", [...args, "--session", session]);
}
function pid() {
return adb("shell", "pidof", appId).trim();
}
function open() {
ad("open", appId, "--platform", "android", "--serial", serial, "--no-test-ime");
}
function stateId(name) {
const states = adb("shell", "cmd", "device_state", "print-states");
const match = states.match(new RegExp(`identifier=(\\d+), name='${name}'`));
assert(match, `Emulator must expose the ${name} posture: ${states}`);
return match[1];
}
async function expectLayout(posture) {
const compact = posture === "CLOSED";
const expectedId = compact ? "workspace-tab-switcher-trigger" : "workspace-tabs-scroll";
const unexpectedId = compact ? "workspace-tabs-scroll" : "workspace-tab-switcher-trigger";
const deadline = Date.now() + 15_000;
let nodes = [];
do {
let data;
try {
({ data } = JSON.parse(ad("snapshot", "-i", "--json")));
} catch (error) {
// During display handoff Android briefly has no capturable app window.
if (!error.stdout?.includes("insufficient foreground app content")) throw error;
await delay(200);
continue;
}
assert.equal(data.appBundleId, appId, "Snapshot must belong to Paseo");
nodes = data.nodes;
if (
nodes.some((node) => node.identifier === expectedId) &&
!nodes.some((node) => node.identifier === unexpectedId)
) {
writeFileSync(resolve(artifacts, `${posture}.json`), JSON.stringify(data, null, 2));
console.log(`PASS: ${posture} uses ${compact ? "compact" : "wide"} workspace controls`);
return;
}
await delay(200);
} while (Date.now() < deadline);
writeFileSync(resolve(artifacts, `${posture}-failure.json`), JSON.stringify(nodes, null, 2));
writeFileSync(
resolve(artifacts, "native-failure.txt"),
adb("shell", "dumpsys", "activity", "top"),
);
assert.fail(`${posture}: expected ${expectedId}, without ${unexpectedId}`);
}
const closed = stateId("CLOSED");
const opened = stateId("OPENED");
const initialState = adb("shell", "cmd", "device_state", "state").match(
/Committed state: DeviceState\{identifier=(\d+)/,
)?.[1];
assert(initialState, "Could not read the initial fold state");
try {
adb("shell", "cmd", "device_state", "state", opened);
open();
await expectLayout("OPENED");
const initialPid = pid();
for (const [posture, id] of [
["CLOSED", closed],
["OPENED", opened],
]) {
adb("shell", "input", "keyevent", "KEYCODE_HOME");
adb("shell", "cmd", "device_state", "state", id);
// Resume immediately: waiting for configuration delivery hides the regression.
open();
await expectLayout(posture);
assert.equal(pid(), initialPid, "Fold/resume must preserve the app process");
}
} finally {
adb("shell", "cmd", "device_state", "state", initialState);
ad("close");
}
@@ -28,6 +28,10 @@ interface SeedProjectDescriptor {
* prefer those wrappers over reaching for this client directly.
*/
export interface SeedDaemonClient {
patchDaemonConfig(
config: import("@getpaseo/protocol/messages").MutableDaemonConfigPatch,
): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>;
getDaemonConfig(): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>;
connect(): Promise<void>;
close(): Promise<void>;
addProject(cwd: string): Promise<{
@@ -25,6 +25,7 @@ interface UsageReportsFixtureOptions {
* app connects, so a reload can switch it.
*/
usageSupported?: boolean | (() => boolean);
usageSettingSupported?: boolean;
/** Released hosts expose provider.usage.list with no source icons. */
providerUsageListOnly?: boolean;
/** The host daemon's port; defaults to the E2E daemon. */
@@ -63,6 +64,7 @@ function withUsageSupportFeature(
message: WebSocketMessage,
enabled: boolean,
providerUsageListOnly: boolean,
usageSettingSupported: boolean,
): string | null {
const envelope = parseJson(message) as {
type?: unknown;
@@ -86,6 +88,7 @@ function withUsageSupportFeature(
...payload,
features: {
...features,
usageSetting: usageSettingSupported ? true : undefined,
usageSources: enabled && !providerUsageListOnly,
providerUsageList: enabled,
},
@@ -229,7 +232,12 @@ export async function installUsageReportsFixture(
server.onMessage((message) => {
const serverInfo =
typeof message === "string"
? withUsageSupportFeature(message, isUsageSupported(), providerUsageListOnly)
? withUsageSupportFeature(
message,
isUsageSupported(),
providerUsageListOnly,
options.usageSettingSupported ?? true,
)
: null;
ws.send(serverInfo ?? message);
});
+4 -9
View File
@@ -64,12 +64,7 @@ import { useCloseAgentListGesture } from "@/mobile-panels/gestures";
import { MobilePanelOverlay } from "@/mobile-panels/presentation";
import { buildSettingsAddHostRoute, buildSettingsRoute } from "@/utils/host-routes";
import { openHostOverview } from "@/navigation/settings-navigation";
import {
UsageSidebarItem,
UsageSidebarRoot,
useHasUsageSummary,
useOpenSidebarUsage,
} from "@/usage";
import { UsageSidebarItem, UsageSidebarRoot, useUsageSummary, useOpenSidebarUsage } from "@/usage";
import { SidebarAgentListSkeleton } from "./sidebar-agent-list-skeleton";
import { SidebarCalloutSlot } from "./sidebar-callout-slot";
import { SidebarWorkspaceList } from "./sidebar-workspace-list";
@@ -480,10 +475,10 @@ function SidebarUsageIcon({ label }: { label: string }) {
*/
function SidebarFooterRows({ onBeforeNavigate }: { onBeforeNavigate?: () => void }) {
const { items } = useSidebarNavItems("footer");
const hasUsageSummary = useHasUsageSummary();
const usageSummary = useUsageSummary();
const rowsRef = useRef<View | null>(null);
const visibleItems = items.filter(
(item) => item.visible && (item.kind === "plugin" || hasUsageSummary),
(item) => item.visible && (item.kind === "plugin" || usageSummary.length > 0),
);
if (visibleItems.length === 0) return null;
return (
@@ -499,7 +494,7 @@ function SidebarFooterRows({ onBeforeNavigate }: { onBeforeNavigate?: () => void
onBeforeNavigate={onBeforeNavigate}
/>
) : (
<UsageSidebarItem key={item.key} />
<UsageSidebarItem key={item.key} sources={usageSummary} />
),
)}
</View>
@@ -455,10 +455,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
reportError: (error) => {
console.warn("[Session] viewed timeline synchronization failed", { serverId, error });
},
schedule: (task, delayMs) => {
const timeout = setTimeout(task, delayMs);
return () => clearTimeout(timeout);
},
});
viewedTimelineSyncRef.current = sync;
setViewedTimelineSync(serverId, sync);
@@ -292,7 +292,10 @@ const CATALOG_DATA = [
version: "0.6.13",
iconId: "minimax-code",
installLink: "https://agent.minimax.io",
command: ["npx", "-y", "@minimax-ai/code@0.6.13", "acp"],
// `-p <pkg>` names the package and `mcode` names its binary. Without the
// explicit binary, npx resolves the executable from the unscoped package
// name (`code`), which this package does not publish.
command: ["npx", "-y", "-p", "@minimax-ai/code@0.6.13", "mcode", "acp"],
},
{
id: "minion-code",
@@ -62,7 +62,9 @@ describe("ACP provider catalog", () => {
expect(findProvider("minimax-code")).toMatchObject({
title: "MiniMax Code",
version: "0.6.13",
command: ["npx", "-y", "@minimax-ai/code@0.6.13", "acp"],
// The package publishes `mcode`, not `code`, so npx needs the package and
// the binary named separately.
command: ["npx", "-y", "-p", "@minimax-ai/code@0.6.13", "mcode", "acp"],
});
expect(findProvider("minimax-code").iconSvg).toContain("<svg");
});
@@ -422,6 +422,23 @@ describe("deriveAgentScreenViewState", () => {
expect(result.memory.lastReadyAgent).toBeNull();
});
it.each(["error", "retrying"] as const)("shows archived history sync %s", (status) => {
const result = deriveAgentScreenViewState({
input: {
...createBaseInput(),
agent: createAgent("agent-1"),
isArchived: true,
hasHydratedHistoryBefore: true,
visibilityCatchUpStatus: status,
},
memory: createBaseMemory(),
});
expect(expectReadyState(result.state).sync).toEqual({
status: "sync_error",
isRetrying: status === "retrying",
});
});
it("renders an archived agent before provider history is initialized", () => {
const result = deriveAgentScreenViewState({
input: {
@@ -175,10 +175,14 @@ function resolveAgentScreenSync(args: {
hadInitialSyncFailure: boolean;
}): AgentScreenReadySyncState {
const { input, hadInitialSyncFailure } = args;
if (input.isArchived) {
if (
input.isArchived &&
input.visibilityCatchUpStatus !== "error" &&
input.visibilityCatchUpStatus !== "retrying"
) {
return { status: "idle" };
}
if (!input.isConnected) {
if (!input.isConnected && !input.isArchived) {
return { status: "reconnecting" };
}
if (input.missingAgentState.kind === "error") {
+5
View File
@@ -2092,6 +2092,11 @@ export const ar: TranslationResources = {
},
},
providerUsage: {
checkUsage: "التحقق من الاستخدام",
checkUsageHint: "ينطبق على {{host}} على جميع الأجهزة",
off: "التحقق من الاستخدام متوقف على {{host}}.",
turnOn: "تشغيل",
options: "الإعدادات",
refreshFailed: "تعذّر تحديث الاستخدام",
noHosts: "لا توجد مضيفات متصلة",
+5
View File
@@ -2117,6 +2117,11 @@ export const en = {
},
},
providerUsage: {
checkUsage: "Check usage",
checkUsageHint: "Applies to {{host}} on every device",
off: "Usage is off on {{host}}.",
turnOn: "Turn on",
options: "Settings",
refreshFailed: "Unable to refresh usage",
noHosts: "No connected hosts",
+5
View File
@@ -2140,6 +2140,11 @@ export const es: TranslationResources = {
},
},
providerUsage: {
checkUsage: "Consultar uso",
checkUsageHint: "Se aplica a {{host}} en todos los dispositivos",
off: "El uso está desactivado en {{host}}.",
turnOn: "Activar",
options: "Configuración",
refreshFailed: "No se pudo actualizar el uso",
noHosts: "No hay hosts conectados",
+5
View File
@@ -2140,6 +2140,11 @@ export const fr: TranslationResources = {
},
},
providerUsage: {
checkUsage: "Vérifier l’utilisation",
checkUsageHint: "S’applique à {{host}} sur tous les appareils",
off: "L’utilisation est désactivée sur {{host}}.",
turnOn: "Activer",
options: "Paramètres",
refreshFailed: "Impossible d’actualiser l’utilisation",
noHosts: "Aucun hôte connecté",
+5
View File
@@ -2113,6 +2113,11 @@ export const ja: TranslationResources = {
},
},
providerUsage: {
checkUsage: "使用状況を確認",
checkUsageHint: "すべてのデバイスで {{host}} に適用",
off: "{{host}} の使用状況確認はオフです。",
turnOn: "オンにする",
options: "設定",
refreshFailed: "使用状況を更新できません",
noHosts: "接続中のホストがありません",
+5
View File
@@ -2102,6 +2102,11 @@ export const ko: TranslationResources = {
},
},
providerUsage: {
checkUsage: "사용량 확인",
checkUsageHint: "모든 기기에서 {{host}}에 적용",
off: "{{host}}의 사용량 확인이 꺼져 있습니다.",
turnOn: "켜기",
options: "설정",
refreshFailed: "사용량을 새로 고칠 수 없습니다",
noHosts: "연결된 호스트가 없습니다",
+5
View File
@@ -2125,6 +2125,11 @@ export const ptBR: TranslationResources = {
},
},
providerUsage: {
checkUsage: "Consultar uso",
checkUsageHint: "Aplica-se a {{host}} em todos os dispositivos",
off: "O uso está desativado em {{host}}.",
turnOn: "Ativar",
options: "Configurações",
refreshFailed: "Não foi possível atualizar o uso",
noHosts: "Nenhum host conectado",
+5
View File
@@ -2125,6 +2125,11 @@ export const ru: TranslationResources = {
},
},
providerUsage: {
checkUsage: "Проверять использование",
checkUsageHint: "Применяется к {{host}} на всех устройствах",
off: "Проверка использования отключена на {{host}}.",
turnOn: "Включить",
options: "Настройки",
refreshFailed: "Не удалось обновить использование",
noHosts: "Нет подключённых хостов",
+5
View File
@@ -2070,6 +2070,11 @@ export const zhCN: TranslationResources = {
},
},
providerUsage: {
checkUsage: "检查用量",
checkUsageHint: "在所有设备上应用于 {{host}}",
off: "{{host}} 的用量检查已关闭。",
turnOn: "开启",
options: "设置",
refreshFailed: "无法刷新用量",
noHosts: "没有已连接的主机",
@@ -174,7 +174,6 @@ it("feeds restored layout to timeline sync as a release signal, not a subscripti
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
onCatchUpEnded: () => undefined,
reportError: () => undefined,
schedule: () => () => undefined,
});
// The edge session-context.tsx owns. Pointing it at subscription instead would resume every
// agent behind a restored tab on the daemon.
@@ -57,7 +57,6 @@ function createOwner(storage: TimelineReplicaStorage): ViewedTimelineOwner {
fetchPage: async () => ({ hasNewer: false, endCursor: null }),
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
reportError: () => undefined,
schedule: () => () => undefined,
},
});
}
@@ -617,7 +616,6 @@ describe("create handoff lifetime", () => {
},
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
reportError: () => undefined,
schedule: () => () => undefined,
},
});
@@ -90,7 +90,7 @@ test("visible catch-up settles before hidden open chats start fetching", async (
world.sync.dispose();
});
test("a failed visible catch-up releases hidden chats without bypassing its retry delay", async () => {
test("a failed visible catch-up releases hidden chats without bypassing its error", async () => {
const world = new TimelineWorld();
world.openedEarlier(["a-hidden"]);
world.sync.replaceVisibleAgentIds("pane", ["z-visible"]);
@@ -103,7 +103,7 @@ test("a failed visible catch-up releases hidden chats without bypassing its retr
hidden.respond({ hasNewer: false });
await world.nextError();
world.expectNoPendingFetch();
(await world.nextRetry())();
world.sync.retryVisibleAgentTimeline("z-visible");
(await world.nextFetch("z-visible")).respond({ hasNewer: false });
world.sync.dispose();
});
@@ -200,20 +200,6 @@ class TimelineWorld {
const waiter = this.errorWaiters.shift();
if (waiter) waiter(this.errors.at(-1) ?? "");
},
schedule: (task, delayMs) => {
const scheduled = { task, delayMs };
this.scheduled.push(scheduled);
const waiterIndex = this.retryWaiters.findIndex((waiter) => waiter.delayMs === delayMs);
if (waiterIndex >= 0) {
const [waiter] = this.retryWaiters.splice(waiterIndex, 1);
this.scheduled.splice(this.scheduled.indexOf(scheduled), 1);
waiter.resolve(task);
}
return () => {
const index = this.scheduled.indexOf(scheduled);
if (index >= 0) this.scheduled.splice(index, 1);
};
},
});
show(sourceId: string, agentIds: string[]): void {
@@ -235,12 +221,6 @@ class TimelineWorld {
}> = [];
private readonly errorWaiters: Array<(message: string) => void> = [];
private readonly cacheRequestWaiters: Array<(agentId: string) => void> = [];
private readonly scheduled: Array<{ task: () => void; delayMs: number }> = [];
private readonly retryWaiters: Array<{
delayMs: number;
resolve(retry: () => void): void;
}> = [];
get pendingFetchCount(): number {
return this.fetches.length;
}
@@ -300,22 +280,6 @@ class TimelineWorld {
return new Promise((resolve) => this.errorWaiters.push(resolve));
}
nextRetry(delayMs = 1_000): Promise<() => void> {
const index = this.scheduled.findIndex((entry) => entry.delayMs === delayMs);
if (index >= 0) return Promise.resolve(this.scheduled.splice(index, 1)[0].task);
return new Promise((resolve) => this.retryWaiters.push({ delayMs, resolve }));
}
elapse(elapsedMs: number): void {
const due = this.scheduled.filter((entry) => entry.delayMs <= elapsedMs);
this.scheduled.splice(
0,
this.scheduled.length,
...this.scheduled.filter((entry) => entry.delayMs > elapsedMs),
);
for (const entry of due) entry.task();
}
private releaseMembershipWaiter(): void {
const waiter = this.membershipWaiters.shift();
if (!waiter) return;
@@ -483,6 +447,28 @@ test("reports a chat current only once its parked follow-up page completes", asy
world.sync.dispose();
});
test("a gap during manual retry is recovered before reporting ready", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
world.show("workspace", ["agent-a"]);
(await world.nextMembership()).succeed();
(await world.nextFetch("agent-a")).fail("unavailable");
await world.nextError();
world.sync.retryVisibleAgentTimeline("agent-a");
const retry = await world.nextFetch("agent-a");
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 9 });
retry.respond({ hasNewer: false });
await vi.waitFor(() => expect(world.pendingFetchCount).toBe(1));
const recovery = await world.nextFetch("agent-a");
expect(recovery.request).toMatchObject({
direction: "after",
cursor: { epoch: "epoch-agent-a", seq: 9 },
});
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying");
recovery.respond({ hasNewer: false });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
});
test("reports a chat current once the latest-tail fallback replaces an overflowing catch-up", async () => {
const world = new TimelineWorld();
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 42 });
@@ -780,6 +766,21 @@ test("overlapping sources deduplicate membership and retain open hidden chats",
world.expectNoPendingFetch();
});
test("failed timeline fetch does not schedule a retry", async () => {
vi.useFakeTimers();
const world = new TimelineWorld();
world.sync.setConnected(true);
world.show("workspace", ["agent-a"]);
(await world.nextMembership()).succeed();
(await world.nextFetch("agent-a")).fail("unavailable");
await world.nextError();
expect(vi.getTimerCount()).toBe(0);
await vi.advanceTimersByTimeAsync(120_000);
world.expectNoPendingFetch();
world.expectNoPendingMembership();
vi.useRealTimers();
});
test("a failed catch-up reports once and retries through the explicit retry policy", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
@@ -788,12 +789,12 @@ test("a failed catch-up reports once and retries through the explicit retry poli
membership.succeed();
const failed = await world.nextFetch("agent-a");
failed.fail("timeline unavailable");
const [error, retryCatchUp] = await Promise.all([world.nextError(), world.nextRetry()]);
const error = await world.nextError();
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
retryCatchUp();
world.sync.retryVisibleAgentTimeline("agent-a");
const retry = await world.nextFetch("agent-a");
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying");
retry.respond({ hasNewer: false });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
@@ -804,35 +805,6 @@ test("a failed catch-up reports once and retries through the explicit retry poli
world.expectNoPendingMembership();
});
test("a failed catch-up retries with exponential backoff", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
const membership = await world.nextMembership();
membership.succeed();
const first = await world.nextFetch("agent-a");
first.fail("timeline unavailable");
const [firstError, retryAfterFirstFailure] = await Promise.all([
world.nextError(),
world.nextRetry(),
]);
expect(firstError).toBe("timeline unavailable");
retryAfterFirstFailure();
const second = await world.nextFetch("agent-a");
second.fail("timeline unavailable");
await world.nextError();
const retryAfterSecondFailure = await world.nextRetry(2_000);
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
retryAfterSecondFailure();
const third = await world.nextFetch("agent-a");
third.respond({ hasNewer: false });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
});
test("manual retries can immediately re-attempt a failed catch-up", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
@@ -842,7 +814,7 @@ test("manual retries can immediately re-attempt a failed catch-up", async () =>
const failed = await world.nextFetch("agent-a");
failed.fail("timeline unavailable");
await world.nextRetry();
await world.nextError();
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
world.sync.retryVisibleAgentTimeline("agent-a");
@@ -853,7 +825,7 @@ test("manual retries can immediately re-attempt a failed catch-up", async () =>
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
});
test("redeclaring unchanged visibility does not bypass catch-up backoff", async () => {
test("redeclaring unchanged visibility does not bypass catch-up error", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
@@ -862,9 +834,11 @@ test("redeclaring unchanged visibility does not bypass catch-up backoff", async
const failed = await world.nextFetch("agent-a");
failed.fail("timeline unavailable");
await world.nextRetry();
await world.nextError();
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
world.sync.setActive(false);
world.sync.setActive(true);
world.expectNoPendingMembership();
world.expectNoPendingFetch();
@@ -880,7 +854,7 @@ test("a manual retry that fails returns to the error state", async () => {
const failed = await world.nextFetch("agent-a");
failed.fail("timeline unavailable");
await world.nextRetry();
await world.nextError();
world.sync.retryVisibleAgentTimeline("agent-a");
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying");
@@ -943,20 +917,34 @@ test("repeated recovery for the same running gap reuses the in-flight fetch", as
gapPage.respond({ hasNewer: false });
});
test("membership failure autonomously retries without another visibility declaration", async () => {
test("failed membership does not schedule a retry", async () => {
vi.useFakeTimers();
const world = new TimelineWorld();
world.sync.setConnected(true);
world.show("workspace", ["agent-a"]);
(await world.nextMembership()).fail("unavailable");
await world.nextError();
expect(vi.getTimerCount()).toBe(0);
await vi.advanceTimersByTimeAsync(120_000);
world.expectNoPendingFetch();
world.expectNoPendingMembership();
vi.useRealTimers();
});
test("membership failure waits for manual retry", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
const failed = await world.nextMembership();
failed.fail("subscription unavailable");
const [error, retryMembership] = await Promise.all([world.nextError(), world.nextRetry()]);
const error = await world.nextError();
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
retryMembership();
world.sync.retryVisibleAgentTimeline("agent-a");
const retry = await world.nextMembership();
retry.succeed();
const catchUp = await world.nextFetch("agent-a");
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying");
catchUp.respond({ hasNewer: false });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
@@ -967,44 +955,68 @@ test("membership failure autonomously retries without another visibility declara
});
});
test("membership failures retry with exponential backoff", async () => {
test("retrying membership restores a previously loaded chat", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
const first = await world.nextMembership();
first.fail("subscription unavailable");
const [firstError, retryAfterFirstFailure] = await Promise.all([
world.nextError(),
world.nextRetry(),
]);
expect(firstError).toBe("subscription unavailable");
retryAfterFirstFailure();
const second = await world.nextMembership();
second.fail("subscription unavailable again");
const retryAfterSecondFailure = await world.nextRetry(2_000);
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
retryAfterSecondFailure();
const retry = await world.nextMembership();
retry.succeed();
const catchUp = await world.nextFetch("agent-a");
catchUp.respond({ hasNewer: false });
world.show("workspace", ["agent-a"]);
(await world.nextMembership()).succeed();
(await world.nextFetch("agent-a")).respond({ hasNewer: false });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 10 });
world.show("workspace", ["agent-b"]);
(await world.nextMembership()).fail("subscription unavailable");
await world.nextError();
world.sync.retryVisibleAgentTimeline("agent-a");
(await world.nextMembership()).succeed();
(await world.nextFetch("agent-b")).respond({ hasNewer: false });
const resumed = await world.nextFetch("agent-a");
expect(resumed.request).toMatchObject({
direction: "after",
cursor: { epoch: "epoch-agent-a", seq: 10 },
});
resumed.respond({ hasNewer: false });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
});
test("redeclaring unchanged visibility does not bypass membership backoff", async () => {
test("a fetch that finishes after membership failure cannot clear the error", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
world.show("workspace", ["agent-a"]);
(await world.nextMembership()).succeed();
const inFlight = await world.nextFetch("agent-a");
world.show("workspace", ["agent-b"]);
(await world.nextMembership()).fail("subscription unavailable");
await world.nextError();
inFlight.respond({ hasNewer: false });
await Promise.resolve();
await Promise.resolve();
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
});
test("a failed membership retry returns to error", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
world.show("workspace", ["agent-a"]);
(await world.nextMembership()).fail("unavailable");
await world.nextError();
world.sync.retryVisibleAgentTimeline("agent-a");
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying");
(await world.nextMembership()).fail("still unavailable");
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"));
});
test("redeclaring unchanged visibility does not bypass membership error", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
const failed = await world.nextMembership();
failed.fail("subscription unavailable");
await world.nextRetry();
await world.nextError();
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
world.sync.setActive(false);
world.sync.setActive(true);
world.expectNoPendingMembership();
world.expectNoPendingFetch();
@@ -1050,7 +1062,6 @@ test("backgrounding preserves subscriptions and returning verifies the visible c
world.sync.setActive(false);
world.expectNoPendingMembership();
world.elapse(60_000);
world.sync.setActive(true);
world.expectNoPendingMembership();
@@ -1067,11 +1078,10 @@ test("stale membership retry cannot overwrite a newer effective set", async () =
world.show("workspace", ["agent-a"]);
const failed = await world.nextMembership();
failed.fail("subscription unavailable");
const staleRetry = await world.nextRetry();
await world.nextError();
world.show("workspace", ["agent-b"]);
const current = await world.nextMembership();
staleRetry();
current.succeed();
const agentB = await world.nextFetch("agent-b");
agentB.respond({ hasNewer: false });
@@ -1088,10 +1098,9 @@ test("membership retry cannot run while disconnected", async () => {
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
const failed = await world.nextMembership();
failed.fail("subscription unavailable");
const disconnectedRetry = await world.nextRetry();
await world.nextError();
world.sync.setConnected(false);
disconnectedRetry();
world.expectNoPendingMembership();
world.sync.setConnected(true);
const restored = await world.nextMembership();
@@ -1118,7 +1127,6 @@ test("returning to an open hidden agent stays live after inactivity", async () =
agentBCatchUp.respond({ hasNewer: false });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-b")).toBe("ready"));
world.elapse(60_000);
world.show("workspace", ["agent-a"]);
world.expectNoPendingMembership();
@@ -329,7 +329,6 @@ export interface ViewedTimelineSyncPorts {
*/
onCatchUpEnded(agentId: string): void;
reportError(error: unknown): void;
schedule(task: () => void, delayMs: number): () => void;
}
export type ViewedTimelineStatus = "ready" | "pending" | "error" | "retrying";
@@ -423,26 +422,14 @@ export function createViewedTimelineOwner(input: {
};
}
const RETRY_DELAY_MS = 1_000;
const MAX_RETRY_DELAY_MS = 30_000;
type CatchUpStatus = "running" | "complete" | "error";
interface CatchUpState {
generation: number;
status: CatchUpStatus;
request?: ProjectedTimelineForwardFetchPlan;
cancelRetry?: () => void;
retryDelayMs?: number;
}
const getNextRetryDelayMs = (previousDelayMs: number | undefined): number => {
if (previousDelayMs == null) {
return RETRY_DELAY_MS;
}
return Math.min(previousDelayMs * 2, MAX_RETRY_DELAY_MS);
};
function isSameCatchUpRequest(
left: ProjectedTimelineForwardFetchPlan | undefined,
right: ProjectedTimelineForwardFetchPlan | undefined,
@@ -472,9 +459,7 @@ function decideCatchUp(input: {
}
return "replace";
}
return input.current.status === "running" || input.current.status === "complete"
? "keep"
: "replace";
return "keep";
}
function normalizeAgentIds(agentIds: string[]): string[] {
@@ -494,8 +479,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
const pendingCatchUps = new Map<string, ProjectedTimelineForwardFetchPlan>();
const visibilityCatchUpPending = new Set<string>();
const visibilityCatchUpErrors = new Map<string, string>();
// User-initiated retries only. Background retries stay silent; a retry the user asked for
// owes them a pending state until it settles.
// A user-initiated retry owes a pending state until it settles.
const manualRetries = new Set<string>();
const loadedCache = new Set<string>();
const cacheLoads = new Map<string, Promise<void>>();
@@ -511,8 +495,6 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
let acknowledged: string[] = [];
let membershipGeneration = 0;
let membershipNeedsRetry = false;
let membershipRetryDelayMs: number | undefined;
let cancelMembershipRetry: (() => void) | null = null;
// Chats this session has opened. Visibility is the only way in, so an agent is never
// subscribed — and never resumed on the daemon — until the user actually opens it.
// Membership then survives hiding, workspace switches, backgrounding and reconnect;
@@ -563,7 +545,6 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
const cancelCatchUp = (agentId: string) => {
catchUpGenerations.set(agentId, (catchUpGenerations.get(agentId) ?? 0) + 1);
catchUps.get(agentId)?.cancelRetry?.();
catchUps.delete(agentId);
pendingCatchUps.delete(agentId);
};
@@ -607,19 +588,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
setVisibilityCatchUpReady(agentId);
} catch (error) {
if (catchUps.get(agentId)?.generation === generation) {
const nextRetryDelayMs = getNextRetryDelayMs(catchUps.get(agentId)?.retryDelayMs);
const cancelRetry = ports.schedule(() => {
const current = catchUps.get(agentId);
if (current?.generation !== generation || current.status !== "error") return;
startCatchUp(agentId);
}, nextRetryDelayMs);
catchUps.set(agentId, {
generation,
status: "error",
request,
cancelRetry,
retryDelayMs: nextRetryDelayMs,
});
catchUps.set(agentId, { generation, status: "error", request });
setVisibilityCatchUpError([agentId], error);
ports.reportError(error);
}
@@ -686,17 +655,9 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
if (decision === "keep") {
return;
}
current?.cancelRetry?.();
const generation = (catchUpGenerations.get(agentId) ?? 0) + 1;
catchUpGenerations.set(agentId, generation);
const retryDelayMs =
supersede || current?.status !== "error" ? undefined : current.retryDelayMs;
catchUps.set(agentId, {
generation,
status: "running",
request: nextRequest,
retryDelayMs,
});
catchUps.set(agentId, { generation, status: "running", request: nextRequest });
pendingCatchUps.delete(agentId);
void fetchUntilCurrent(
agentId,
@@ -715,7 +676,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
for (const agentId of ordered) {
const pendingCatchUp = pendingCatchUps.get(agentId);
const current = catchUps.get(agentId);
// Completion of a different chat must not bypass a failed chat's backoff or
// Completion of a different chat must not bypass a failed chat's error or
// supersede an in-flight tail that owns its parked gap recovery.
if (current && !(current.status === "complete" && pendingCatchUp)) continue;
startCatchUp(agentId, {
@@ -741,42 +702,31 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
} catch (error) {
if (disposed || !connected || generation !== membershipGeneration) return;
membershipNeedsRetry = true;
acknowledged = [];
for (const agentId of requested) cancelCatchUp(agentId);
setVisibilityCatchUpError(requested, error);
cancelMembershipRetry?.();
const nextRetryDelayMs = getNextRetryDelayMs(membershipRetryDelayMs);
cancelMembershipRetry = ports.schedule(() => {
cancelMembershipRetry = null;
if (disposed || !connected || membershipGeneration !== generation) return;
void reconcileMembership();
}, nextRetryDelayMs);
membershipRetryDelayMs = nextRetryDelayMs;
ports.reportError(error);
return;
}
if (disposed || !connected || generation !== membershipGeneration) return;
cancelMembershipRetry?.();
cancelMembershipRetry = null;
membershipRetryDelayMs = undefined;
acknowledged = requested;
startAcknowledgedCatchUps();
};
const retryVisibleAgentTimeline = (agentId: string) => {
if (!isDesired(agentId) || manualRetries.has(agentId)) return;
if (!connected || !isDesired(agentId) || manualRetries.has(agentId)) return;
const catchUp = catchUps.get(agentId);
const membershipRetryable = membershipNeedsRetry && connected;
if (catchUp?.status !== "error" && !membershipRetryable) return;
manualRetries.add(agentId);
notifyListeners();
if (catchUp?.status === "error") {
catchUp.cancelRetry?.();
startCatchUp(agentId, { request: catchUp.request, supersede: true });
if (membershipRetryable) {
void reconcileMembership();
return;
}
cancelMembershipRetry?.();
cancelMembershipRetry = null;
membershipRetryDelayMs = undefined;
void reconcileMembership();
if (catchUp?.status === "error") {
startCatchUp(agentId, { request: catchUp.request, supersede: true });
}
};
const commitDesiredMembership = (
@@ -817,8 +767,6 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
ensureCacheLoaded(agentId);
}
}
cancelMembershipRetry?.();
cancelMembershipRetry = null;
desired = nextDesired;
ports.replaceDemandedAgentIds(desired);
membershipGeneration += 1;
@@ -869,6 +817,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
return;
}
for (const agentId of visibleAgentIds()) {
if (visibilityCatchUpErrors.has(agentId)) continue;
visibilityCatchUpPending.add(agentId);
visibilityCatchUpErrors.delete(agentId);
startCatchUp(agentId, { supersede: true });
@@ -880,9 +829,6 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
connected = nextConnected;
if (!connected) {
commitDesiredMembership(desired, { resetCatchUpStatus: true });
cancelMembershipRetry?.();
cancelMembershipRetry = null;
membershipRetryDelayMs = undefined;
void observation?.handle.release().catch(ports.reportError);
observation = null;
acknowledged = [];
@@ -894,7 +840,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
void reconcileMembership();
},
recoverGap(agentId, cursor) {
if (!isDesired(agentId)) return;
if (!isDesired(agentId) || catchUps.get(agentId)?.status === "error") return;
startCatchUp(agentId, {
request: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }),
supersede: true,
@@ -904,10 +850,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
disposed = true;
void observation?.handle.release().catch(ports.reportError);
observation = null;
cancelMembershipRetry?.();
cancelMembershipRetry = null;
membershipNeedsRetry = false;
membershipRetryDelayMs = undefined;
sources.clear();
membershipGeneration += 1;
for (const agentId of desired) cancelCatchUp(agentId);
+10 -3
View File
@@ -21,10 +21,12 @@ export interface UsageHostSelection {
*/
export function UsageControls({
view,
serverId,
onRefresh,
hostSelection,
}: {
view: UsageView;
serverId: string;
onRefresh: () => void;
hostSelection?: UsageHostSelection;
}) {
@@ -43,8 +45,8 @@ export function UsageControls({
) : null}
{view.kind === "unavailable" ? null : (
<>
<UsageRefreshButton busy={busy} onRefresh={onRefresh} />
<UsageOptions />
{view.kind === "off" ? null : <UsageRefreshButton busy={busy} onRefresh={onRefresh} />}
<UsageOptions serverId={serverId} />
</>
)}
</View>
@@ -84,7 +86,12 @@ export function useHostUsageWithControls(hostSelection: UsageHostSelection): {
const controls = useMemo(
() =>
hasControls ? (
<UsageControls view={view} onRefresh={refresh} hostSelection={hostSelection} />
<UsageControls
serverId={hostSelection.serverId}
view={view}
onRefresh={refresh}
hostSelection={hostSelection}
/>
) : null,
[hasControls, hostSelection, refresh, view],
);
-8
View File
@@ -1,7 +1,5 @@
import { useCallback, useMemo } from "react";
import { useAppSettings } from "@/hooks/use-settings";
import { useUsageHostId } from "./hosts";
import { useUsageHostReports } from "./queries";
import {
isUsagePinned,
setUsageDisplayAs,
@@ -25,12 +23,6 @@ interface UsagePreferencesState {
display: UsageDisplay;
}
/** The device's usage preferences, with pins resolved against a host's reports. */
export function useUsagePreferences(serverId?: string): UsagePreferencesState {
const defaultServerId = useUsageHostId();
return useUsageDisplay(useUsageHostReports(serverId ?? defaultServerId));
}
/** The device's usage preferences, with pins resolved against the given reports. */
export function useUsageDisplay(reports: readonly UsageReportEntry[]): UsagePreferencesState {
const { settings, updateSettings } = useAppSettings();
@@ -1,5 +1,5 @@
import { useTranslation } from "react-i18next";
import { useUsagePreferences } from "./display";
import { useUsageDisplay } from "./display";
import { useHostUsage } from "./queries";
import { UsageSection } from "./usage-section";
@@ -7,7 +7,7 @@ import { UsageSection } from "./usage-section";
export function HostUsageSection({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const { view, refresh } = useHostUsage(serverId);
const { display } = useUsagePreferences(serverId);
const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []);
return (
<UsageSection
serverId={serverId}
+1 -1
View File
@@ -4,6 +4,6 @@ export { useHostReportsUsage } from "./queries";
export {
UsageSidebarItem,
UsageSidebarRoot,
useHasUsageSummary,
useUsageSummary,
useOpenSidebarUsage,
} from "./sidebar-item";
+12
View File
@@ -405,3 +405,15 @@ it("available and retained usage show the same successful completion time", () =
);
expect(upsertReport([failure], success)).toEqual([failure]);
});
it("disabled host shows off even with cached reports", () => {
expect(
resolveUsageView({
hostLabel: "Laptop",
isConnected: true,
supportsUsage: true,
enabled: false,
query: { data: [], error: null, isFetching: false },
}),
).toMatchObject({ kind: "off" });
});
+3
View File
@@ -106,6 +106,7 @@ export interface UsageQueryState {
export function resolveUsageView(
input: {
enabled?: boolean;
hostLabel: string;
isConnected: boolean;
supportsUsage: boolean;
@@ -125,6 +126,8 @@ export function resolveUsageView(
message: t("providerUsage.hostUpgradeRequired", { host: hostLabel }),
};
}
if (input.enabled === false)
return { kind: "off", message: t("providerUsage.off", { host: hostLabel }) };
if (query?.data) {
return { kind: "ready", reports: query.data, isRefreshing: query.isFetching };
}
+27 -10
View File
@@ -8,15 +8,20 @@ import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-
import { useIsCompactFormFactor } from "@/constants/layout";
import { SettingsRow, SettingsSwitch } from "@/components/settings";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import { Alert } from "@/components/ui/alert";
import { useHosts } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
import { useUsagePreferences } from "./display";
import { useUsageSetting } from "./setting";
import { useUsageDisplay } from "./display";
import { useUsageInSidebar } from "./in-sidebar";
import type { UsageDisplayAs } from "./preferences";
const ThemedSettings = withUnistyles(Settings);
/** The shared usage preferences, opened from a cog as a popover or compact sheet. */
export function UsageOptions() {
export function UsageOptions({ serverId }: { serverId: string | null }) {
const setting = useUsageSetting(serverId);
const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId;
const { t } = useTranslation();
const displayAsOptions: SegmentedControlOption<UsageDisplayAs>[] = [
{ value: "used", label: t("providerUsage.displayUsed"), testID: "usage-display-used" },
@@ -27,7 +32,7 @@ export function UsageOptions() {
},
];
const compact = useIsCompactFormFactor();
const { display } = useUsagePreferences();
const { display } = useUsageDisplay([]);
const { inSidebar, setInSidebar } = useUsageInSidebar();
return (
<DropdownMenu compactMode="sheet">
@@ -49,13 +54,25 @@ export function UsageOptions() {
testID="usage-options-surface"
>
<View testID="usage-options-fields">
<SettingsSwitch
label={t("providerUsage.showInSidebar")}
hint={t("providerUsage.showInSidebarHint")}
value={inSidebar}
onValueChange={setInSidebar}
testID="usage-show-in-sidebar"
/>
{setting.error ? <Alert variant="error" description={setting.error.message} /> : null}
{setting.supported ? (
<SettingsSwitch
label={t("providerUsage.checkUsage")}
hint={t("providerUsage.checkUsageHint", { host: hostLabel })}
disabled={!setting.ready}
value={setting.enabled}
onValueChange={setting.setEnabled}
/>
) : null}
<View style={setting.supported ? settingsStyles.rowBorder : undefined}>
<SettingsSwitch
label={t("providerUsage.showInSidebar")}
hint={t("providerUsage.showInSidebarHint")}
value={inSidebar}
onValueChange={setInSidebar}
testID="usage-show-in-sidebar"
/>
</View>
<View style={settingsStyles.rowBorder}>
<SettingsRow label={t("providerUsage.displayAs")}>
<SegmentedControl
+9 -3
View File
@@ -17,6 +17,7 @@ import {
useHosts,
} from "@/runtime/host-runtime";
import { useSessionStore, type SessionState } from "@/stores/session-store";
import { useUsageSetting } from "./setting";
import { usageCopy } from "./copy";
import {
replaceReport,
@@ -132,13 +133,14 @@ function toQueryState(query: {
/** Usage reports for one host, as shown on its settings page. */
export function useHostUsage(serverId: string): { view: UsageView; refresh: () => void } {
const setting = useUsageSetting(serverId);
const queryClient = useQueryClient();
const isConnected = useHostRuntimeIsConnected(serverId);
const isSupported = useSessionStore((state) => supportsUsage(state.sessions[serverId]));
const query = useFetchQuery({
queryKey: usageReportsQueryKey(serverId),
queryFn: () => listReports(queryClient, serverId),
enabled: isConnected && isSupported,
enabled: isConnected && isSupported && setting.enabled,
dataShape: "list",
staleTimeMs: REPORTS_STALE_TIME_MS,
});
@@ -150,6 +152,7 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
const view = resolveUsageView(
{
hostLabel,
enabled: setting.ready ? setting.enabled : undefined,
isConnected,
supportsUsage: isSupported,
query: toQueryState(query),
@@ -166,14 +169,16 @@ const NO_REPORTS: UsageReportEntry[] = [];
* load, or without a host.
*/
export function useUsageHostReports(serverId: string | null): UsageReportEntry[] {
const setting = useUsageSetting(serverId);
const queryClient = useQueryClient();
const query = useFetchQuery({
enabled: setting.enabled,
queryKey: usageReportsQueryKey(serverId ?? ""),
queryFn: serverId ? () => listReports(queryClient, serverId) : skipToken,
dataShape: "list",
staleTimeMs: REPORTS_STALE_TIME_MS,
});
return query.data ?? NO_REPORTS;
return setting.enabled ? (query.data ?? NO_REPORTS) : NO_REPORTS;
}
/**
@@ -209,7 +214,8 @@ export function useAgentUsage(serverId: string, agentId: string): AgentUsageView
export function useHostReportsUsage(serverId: string): boolean {
const isConnected = useHostRuntimeIsConnected(serverId);
const isSupported = useSessionStore((state) => supportsUsage(state.sessions[serverId]));
return isConnected && isSupported;
const setting = useUsageSetting(serverId);
return isConnected && isSupported && setting.enabled;
}
/** Every host with whether it is connected and reports usage, in host order. */
+26
View File
@@ -0,0 +1,26 @@
import { useMutation } from "@tanstack/react-query";
import { useCallback } from "react";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useSessionStore } from "@/stores/session-store";
/** Host policy comes from the live daemon config replica. */
export function useUsageSetting(serverId: string | null) {
const supported = useSessionStore((state) =>
Boolean(serverId && state.sessions[serverId]?.serverInfo?.features?.usageSetting),
);
const { config, patchConfig } = useDaemonConfig(supported ? serverId : null);
const mutation = useMutation({
mutationFn: (enabled: boolean) => patchConfig({ usage: { enabled } }),
});
const setEnabled = mutation.mutate;
const turnOn = useCallback(() => setEnabled(true), [setEnabled]);
return {
supported,
error: mutation.error,
// COMPAT(usageSetting): added in v0.14, remove after 2027-05-01.
enabled: !supported || (config !== null && config.usage?.enabled !== false),
ready: !supported || config !== null,
setEnabled,
turnOn,
};
}
+8 -11
View File
@@ -17,7 +17,8 @@ import {
} from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model";
import { useUsagePreferences } from "./display";
import { useUsageDisplay } from "./display";
import { useUsageInSidebar } from "./in-sidebar";
import { useUsageHostId } from "./hosts";
import { useUsageHostReports } from "./queries";
import { UsageSourceIcon } from "./source-icon";
@@ -33,28 +34,24 @@ import {
import { UsageModal } from "./usage-modal";
/** Each summary window with data on the usage host, under its source; empty while none has. */
function useUsageSummary(): readonly PinnedUsageSource[] {
export function useUsageSummary(): readonly PinnedUsageSource[] {
const { t } = useTranslation();
const { preferences } = useUsagePreferences();
const reports = useUsageHostReports(useUsageHostId());
const { inSidebar } = useUsageInSidebar();
const serverId = useUsageHostId();
const reports = useUsageHostReports(inSidebar ? serverId : null);
const { preferences } = useUsageDisplay(reports);
return useMemo(() => resolvePinnedUsage(reports, preferences, t), [preferences, reports, t]);
}
/** Whether the sidebar Usage item has anything to show. */
export function useHasUsageSummary(): boolean {
return useUsageSummary().length > 0;
}
/**
* The sidebar footer's usage entry: each summary window's source icon and percent, and nothing
* while no summary window has data, since the footer's Usage icon already opens Usage.
* Pressing it opens the Usage modal.
*/
export function UsageSidebarItem() {
export function UsageSidebarItem({ sources }: { sources: readonly PinnedUsageSource[] }) {
const { t } = useTranslation();
const label = t(builtinSidebarNavLabelKey("usage"));
const openUsage = useOpenSidebarUsage();
const sources = useUsageSummary();
if (sources.length === 0) return null;
return <PinnedUsageTrigger label={label} sources={sources} onPress={openUsage} />;
}
+1
View File
@@ -10,6 +10,7 @@ export type UsageBalanceUnit = UsageBalance["unit"];
/** What a host's usage surface shows. `unavailable` is a host state, not a failed request. */
export type UsageView =
| { kind: "off"; message: string }
| { kind: "unavailable"; message: string }
| { kind: "loading" }
| { kind: "error"; message: string }
+2 -2
View File
@@ -4,7 +4,7 @@ import { View } from "react-native";
import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet";
import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model";
import { useHostUsageWithControls } from "./controls";
import { useUsagePreferences } from "./display";
import { useUsageDisplay } from "./display";
import { useUsageHostSelection } from "./hosts";
import type { UsageHost } from "./model";
import { UsageBody, UsageMessage } from "./usage-section";
@@ -52,12 +52,12 @@ function HostUsageModal({
hosts: UsageHost[];
onSelectHost: (serverId: string) => void;
}) {
const { display } = useUsagePreferences();
const hostSelection = useMemo(
() => ({ hosts, serverId, onSelect: onSelectHost }),
[hosts, onSelectHost, serverId],
);
const { view, refresh, controls } = useHostUsageWithControls(hostSelection);
const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []);
return (
<UsageModalFrame {...props} actions={controls}>
<View testID={`usage-host-${serverId}`}>
+12 -2
View File
@@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button";
import { settingsStyles } from "@/styles/settings";
import { SettingsSection } from "@/components/settings/headings/settings-section";
import type { UsageDisplay } from "./display";
import { useUsageSetting } from "./setting";
import { UsageControls } from "./controls";
import { UsageList } from "./list";
import type { UsageView } from "./types";
@@ -27,8 +28,8 @@ export function UsageSection({
testID?: string;
}) {
const trailing = useMemo(
() => <UsageControls view={view} onRefresh={onRefresh} />,
[onRefresh, view],
() => <UsageControls serverId={serverId} view={view} onRefresh={onRefresh} />,
[onRefresh, view, serverId],
);
return (
@@ -51,6 +52,15 @@ export function UsageBody({
onRefresh: () => void;
}) {
const { t } = useTranslation();
const setting = useUsageSetting(serverId);
if (view.kind === "off")
return (
<View>
<UsageMessage text={view.message} />
{setting.error ? <Alert variant="error" description={setting.error.message} /> : null}
<Button onPress={setting.turnOn}>{t("providerUsage.turnOn")}</Button>
</View>
);
if (view.kind === "unavailable") {
return <UsageMessage text={view.message} />;
}
+14 -6
View File
@@ -2,6 +2,7 @@ export { createHostChannelTransport } from "../hosts/index.js";
import { HostTransportBudget } from "./buffering.js";
export { HostTransportBudget } from "./buffering.js";
import { homedir } from "node:os";
import type { Agent } from "node:http";
import { WebSocket } from "ws";
import { parseHostTarget, type HostTarget } from "@getpaseo/protocol/host-target";
import { createSshTunnel, type SshTunnel } from "./ssh-tunnel.js";
@@ -19,10 +20,15 @@ export { parseHostTarget };
export type { SshTunnel } from "./ssh-tunnel.js";
export { createSshTunnel, resolveSshFailureDetail } from "./ssh-tunnel.js";
export interface HostTransportOptions {
webSocketAgent?: (url: string) => Agent | undefined;
}
/** A factory owns one attempt, including a fresh SSH process and its teardown. */
export function createHostTransportFactory(
connection: string,
budget = new HostTransportBudget(),
options: HostTransportOptions = {},
): DaemonTransportFactory {
const target = parseHostTarget(connection);
// Rises to "protected" once the daemon negotiates it, so a later attempt
@@ -68,12 +74,13 @@ export function createHostTransportFactory(
return;
}
const socketPath = socketTarget.socketPath?.replace(/^~(?=\/)/, homedir());
let factory = createWebSocketTransportFactory((url, options) => {
let factory = createWebSocketTransportFactory((url, socketOptions) => {
const socket = new WebSocket(
socketPath && url.startsWith("ws+unix:") ? `ws+unix://${socketPath}:/ws` : url,
options?.protocols,
socketOptions?.protocols,
{
headers: options?.headers,
headers: socketOptions?.headers,
agent: socketPath ? undefined : options.webSocketAgent?.(url),
...(socketPath ? { socketPath } : {}),
maxPayload: 100 * 1024 * 1024,
},
@@ -191,14 +198,15 @@ export function createHostTransportFactory(
}
export function createHostClient(
connection: string,
config: Omit<DaemonClientConfig, "url" | "transportFactory">,
config: Omit<DaemonClientConfig, "url" | "transportFactory"> & HostTransportOptions,
budget?: HostTransportBudget,
): DaemonClient {
const target = parseHostTarget(connection);
const { webSocketAgent, ...clientConfig } = config;
return new DaemonClient({
...config,
...clientConfig,
url: "ws://host-connector/ws",
...(target.password ? { password: target.password } : {}),
transportFactory: createHostTransportFactory(connection, budget),
transportFactory: createHostTransportFactory(connection, budget, { webSocketAgent }),
});
}
+5
View File
@@ -229,6 +229,8 @@ export const MutableDaemonConfigSchema = z
.optional(),
app: z.object({ baseUrl: z.string() }).optional(),
catalogRefreshTimeoutMs: z.number().int().positive().optional(),
// COMPAT(usageSetting): added in v0.14, remove after 2027-05-01.
usage: z.object({ enabled: z.boolean() }).optional(),
browserTools: MutableBrowserToolsConfigSchema.default({ enabled: false }),
providers: z.record(z.string(), MutableDaemonProviderConfigSchema).default({}),
metadataGeneration: MutableMetadataGenerationConfigSchema.default({ providers: [] }),
@@ -256,6 +258,7 @@ export const MutableDaemonConfigPatchSchema = z
.object({
relay: MutableRelayConfigSchema.partial().optional(),
mcp: z.object({ injectIntoAgents: z.boolean().optional() }).passthrough().optional(),
usage: z.object({ enabled: z.boolean() }).optional(),
browserTools: MutableBrowserToolsConfigSchema.partial().optional(),
providers: z
.record(z.string(), MutableDaemonProviderConfigSchema.partial().passthrough())
@@ -3673,6 +3676,8 @@ export const ServerInfoStatusPayloadSchema = z
providersSnapshot: z.boolean().optional(),
connectedHosts: z.boolean().optional(),
hostMultiplexing: z.boolean().optional(),
// COMPAT(usageSetting): added in v0.14, remove after 2027-05-01.
usageSetting: z.boolean().optional(),
usageSources: z.boolean().optional(),
// COMPAT(providersSnapshotCwd): added in v0.3.2, remove gate after 2027-02-10.
providersSnapshotCwd: z.boolean().optional(),
+3 -1
View File
@@ -89,7 +89,7 @@
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
"test": "npm run test:unit && npm run test:integration",
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
"test:integration:all": "npm run test:e2e",
"test:integration:real": "vitest run real.e2e.test.ts",
@@ -124,6 +124,7 @@
"esbuild": "^0.25.12",
"express": "^4.18.2",
"fast-deep-equal": "^3.1.3",
"https-proxy-agent": "^7.0.6",
"lru-cache": "^11.5.1",
"markdown-it": "^10.0.0",
"mnemonic-id": "^3.2.7",
@@ -141,6 +142,7 @@
"strip-ansi": "^7.1.2",
"tree-kill": "^1.2.2",
"typescript": "^5.9.3",
"undici": "^7.24.8",
"uuid": "^9.0.1",
"which": "^5.0.0",
"ws": "^8.14.2",
@@ -3643,3 +3643,114 @@ test("closing Pi during image conversion rejects its pending start", async () =>
await session.close();
await rejected;
});
describe("Pi tool-result images", () => {
test.each([false, true])(
"tool-result images precede the reply and completion (isError=%s)",
async (isError) => {
const { pi, session, events } = await createSession();
onTestFinished(() => session.close());
const fakeSession = pi.latestSession();
await session.startTurn("run");
fakeSession.emit({
type: "tool_execution_start",
toolCallId: "shot-1",
toolName: "screenshot",
args: {},
});
fakeSession.emit({
type: "tool_execution_end",
toolCallId: "shot-1",
toolName: "screenshot",
result: {
content: [
{ type: "text", text: "captured" },
{ type: "image", data: Buffer.from("hello").toString("base64"), mimeType: "image/png" },
],
structuredContent: {
type: "image",
data: Buffer.from("hello").toString("base64"),
mimeType: "image/png",
note: "captured",
},
},
isError,
});
fakeSession.emit({
type: "message_update",
assistantMessageEvent: { type: "text_delta", delta: "Image read complete." },
});
fakeSession.finishTurn();
await events.nextTurnCompletion();
const items = events.timelineItems();
const toolIndex = items.findIndex(
(item) =>
item.type === "tool_call" &&
item.callId === "shot-1" &&
item.status === (isError ? "failed" : "completed"),
);
expect(toolIndex).toBeGreaterThanOrEqual(0);
// Base64 must never reach the tool output stringifier.
expect(JSON.stringify(items[toolIndex])).not.toContain(
Buffer.from("hello").toString("base64"),
);
expect(items.slice(toolIndex + 1)).toEqual([
expect.objectContaining({
type: "assistant_message",
text: expect.stringContaining("![Image]("),
}),
expect.objectContaining({ type: "assistant_message", text: "Image read complete." }),
]);
expect(events.timelineAndCompletionEvents().at(-1)).toEqual({ type: "turn_completed" });
},
);
});
test("Pi image rendering preserves turn ownership across an interrupt and follow-up", async () => {
const { pi, session, events } = await createSession();
onTestFinished(() => session.close());
const emitted: AgentStreamEvent[] = [];
session.subscribe((event) => emitted.push(event));
const native = pi.latestSession();
const first = await session.startTurn("read image");
native.emit({
type: "tool_execution_end",
toolCallId: "large-image",
toolName: "screenshot",
result: {
content: [
{
type: "image",
data: Buffer.alloc(8 * 1024 * 1024, 73).toString("base64"),
mimeType: "image/png",
},
],
},
isError: false,
});
native.finishTurn();
await session.interrupt();
const followup = await session.startTurn("follow-up after image");
await waitForImmediate();
await waitForImmediate();
await expect
.poll(() =>
events
.timelineItems()
.some((item) => item.type === "assistant_message" && item.text.includes("![Image](")),
)
.toBe(true);
expect(events.turnCompletedEvents().some((event) => event.turnId === followup.turnId)).toBe(
false,
);
const imageEvent = emitted.find(
(event) =>
event.type === "timeline" &&
event.item.type === "assistant_message" &&
event.item.text.includes("![Image]("),
);
expect(imageEvent).toMatchObject({ turnId: first.turnId });
native.finishTurn();
await events.nextTurnCompletion();
});
@@ -64,7 +64,11 @@ import {
streamPiHistory,
type PiCapturedUserMessageEntry,
} from "./history-mapper.js";
import { materializeProviderImage } from "../provider-image-output.js";
import {
materializeProviderImage,
renderProviderImageOutputAsAssistantMarkdown,
type ProviderImageOutput,
} from "../provider-image-output.js";
import { PiCliRuntime } from "./cli-runtime.js";
import {
createPiExtensionHost,
@@ -89,6 +93,7 @@ import {
mapToolDetail,
parseToolArgs,
parseToolResult,
splitPiToolResultImages,
type PiToolResult,
type PiTrackedToolCall,
} from "./tool-call-mapper.js";
@@ -1201,6 +1206,7 @@ export class PiRpcAgentSession implements AgentSession {
private closed = false;
private readonly closeController = new AbortController();
private readonly pendingExtensionHydrations = new Set<Promise<void>>();
private pendingOutput: Promise<void> | null = null;
// Pi publishes the terminal before acknowledging abort. Autonomous runs have no
// turn ID; retain their errors too until the cancellation request settles.
private interruptingTurn: { turnId: string | undefined; error: string | null } | null = null;
@@ -1602,6 +1608,7 @@ export class PiRpcAgentSession implements AgentSession {
this.pendingExtensionUiRequests.size ||
this.pendingExtensionResults.size ||
this.pendingExtensionHydrations.size ||
this.pendingOutput ||
this.pendingSteerSubmissions.length ||
this.pendingNoTurnOutputs.length ||
this.interruptingTurn
@@ -1622,7 +1629,7 @@ export class PiRpcAgentSession implements AgentSession {
try {
await this.runtimeSession.close();
} finally {
await Promise.all(this.pendingExtensionHydrations);
await Promise.all([this.pendingOutput, ...this.pendingExtensionHydrations]);
this.rejectAllExtensionResults(new Error("Pi session closed"));
this.cleanup?.();
}
@@ -1686,9 +1693,31 @@ export class PiRpcAgentSession implements AgentSession {
}
private emit(event: AgentStreamEvent): void {
for (const subscriber of this.subscribers) {
subscriber(event);
if (this.pendingOutput) {
this.emitAsync(() => Promise.resolve([event]));
return;
}
this.publish(event);
}
private publish(event: AgentStreamEvent): void {
for (const subscriber of this.subscribers) subscriber(event);
}
// Keep timeline order while images are materialized, without delaying provider state changes.
private emitAsync(render: () => Promise<AgentStreamEvent[]>): void {
const pending = (this.pendingOutput ?? Promise.resolve())
.then(render)
.then((events) => {
if (!this.closed) for (const event of events) this.publish(event);
return undefined;
})
.catch((error) => this.logger.error({ err: error }, "Pi output rendering failed"));
this.pendingOutput = pending;
void pending.then(() => {
if (this.pendingOutput === pending) this.pendingOutput = null;
return undefined;
});
}
private emitExtensionOutput(output: PiExtensionEventOutput | undefined, turnId?: string): void {
@@ -2315,8 +2344,11 @@ export class PiRpcAgentSession implements AgentSession {
this.activeToolCalls.get(event.toolCallId) ?? parseToolArgs(event.toolName, null);
this.activeToolCalls.delete(event.toolCallId);
const result = parseToolResult(event.result);
const error = event.isError ? event.result : null;
// Pull image blocks out of the result so base64 never reaches the tool output, then render
// each one as an assistant_message markdown image after the tool_call (mirroring the Claude
// provider, upstream #1717).
const { images, result } = splitPiToolResultImages(parseToolResult(event.result));
const error = event.isError ? result : null;
const status = event.isError ? "failed" : "completed";
this.extensionHost.onToolEnd({
callId: event.toolCallId,
@@ -2326,6 +2358,30 @@ export class PiRpcAgentSession implements AgentSession {
result,
});
this.emitToolCallEvent(event.toolCallId, toolCall, status, result, error);
if (images.length === 0) return;
const turnId = this.currentTurnIdForEvent();
this.emitAsync(() => this.renderToolResultImages(images, turnId));
}
private async renderToolResultImages(
images: ProviderImageOutput[],
turnId: string | undefined,
): Promise<AgentStreamEvent[]> {
const events: AgentStreamEvent[] = [];
for (const image of images) {
const imageItem = await renderProviderImageOutputAsAssistantMarkdown(image, {
materialize: materializeProviderImage,
});
if (imageItem && !this.closed) {
events.push({
type: "timeline",
provider: this.provider,
turnId,
item: imageItem,
});
}
}
return events;
}
private emitCompactionTimeline(input: {
@@ -21,11 +21,11 @@ export function mapPiChildSession(
return new PiChildSessionFollower(id, file, maxBytes).readNew();
}
function mapChildLine(
async function mapChildLine(
mapper: PiHistoryMapper,
id: string,
line: string,
): ProviderSubagentInputEvent[] {
): Promise<ProviderSubagentInputEvent[]> {
let entry: { message?: PiAgentMessage; timestamp?: string };
try {
entry = JSON.parse(line);
@@ -33,7 +33,7 @@ function mapChildLine(
return [];
}
if (!entry.message || typeof entry.message !== "object" || !("role" in entry.message)) return [];
return mapper.mapMessages([entry.message]).flatMap((mapped) =>
return (await mapper.mapMessages([entry.message])).flatMap((mapped) =>
mapped.type === "timeline"
? [
{
@@ -83,7 +83,10 @@ export class PiChildSessionFollower {
const events: ProviderSubagentInputEvent[] = [];
for (const line of data.subarray(0, lastNewline).toString("utf8").split("\n")) {
if (this.items >= MAX_ITEMS) break;
const mapped = mapChildLine(this.mapper, this.id, line).slice(0, MAX_ITEMS - this.items);
const mapped = (await mapChildLine(this.mapper, this.id, line)).slice(
0,
MAX_ITEMS - this.items,
);
this.items += mapped.length;
events.push(...mapped);
}
@@ -83,7 +83,7 @@ describe("Pi extension host", () => {
test("declines a throwing adapter and preserves generic history", async () => {
const host = createPiExtensionHost(undefined, [throwingAdapter]);
const mapper = new PiHistoryMapper("pi", [], {}, host);
const events = mapper.mapMessages([
const events = await mapper.mapMessages([
{
role: "assistant",
content: [{ type: "toolCall", id: "call-1", name: "other", arguments: {} }],
@@ -193,7 +193,7 @@ describe("Pi extension host", () => {
await output?.hydration;
expect(reads).toHaveLength(8);
});
test("claims a tool, declines an unrelated one, and maps history like live events", () => {
test("claims a tool, declines an unrelated one, and maps history like live events", async () => {
const host = createPiExtensionHost();
const args = { agent: "scout", task: "Inspect files" };
const result = parseToolResult({ content: [{ type: "text", text: "Found two files" }] });
@@ -225,7 +225,7 @@ describe("Pi extension host", () => {
).toBeUndefined();
const mapper = new PiHistoryMapper("pi");
const events = mapper.mapMessages([
const events = await mapper.mapMessages([
{
role: "assistant",
content: [{ type: "toolCall", id: "call-1", name: "subagent", arguments: args }],
@@ -79,7 +79,7 @@ test("cancellation declines each remaining real RPC dialog", () => {
}
});
test("captured result renders in live and history tool rows, while foreign shapes decline", () => {
test("captured result renders in live and history tool rows, while foreign shapes decline", async () => {
const call = {
callId: end.toolCallId,
toolName: end.toolName,
@@ -93,7 +93,7 @@ test("captured result renders in live and history tool rows, while foreign shape
label: "Questions",
text: "Which snack?: Cookie\nWhich colors?: Red, Blue\nWhat project name?: Nebula",
});
const history = new PiHistoryMapper("pi").mapMessages([
const history = await new PiHistoryMapper("pi").mapMessages([
{
role: "assistant",
content: [
@@ -89,7 +89,7 @@ export async function verifyTaskFixture(path: URL, expectedStatuses: string[]):
for (const event of fixture.events) pi.latestSession().emit(event);
pi.latestSession().finishTurn();
expect(todos(live)).toEqual(mapped);
const replay = new PiHistoryMapper("pi").mapMessages(fixture.messages);
const replay = await new PiHistoryMapper("pi").mapMessages(fixture.messages);
expect(todos(replay)).toEqual(mapped);
expect(
replay.filter(
@@ -221,3 +221,75 @@ describe("Pi history mapper", () => {
]);
});
});
describe("Pi tool-result image replay", () => {
test("recreates an image from native tool-result history without its source file", async () => {
const events = await collectHistory([
{
role: "assistant",
content: [
{
type: "toolCall",
id: "image-read",
name: "read",
arguments: { path: "missing-preview.png" },
},
],
},
{
role: "toolResult",
toolCallId: "image-read",
toolName: "read",
content: [
{ type: "text", text: "Read image file [image/png]" },
{ type: "image", data: "aGVsbG8=", mimeType: "image/png" },
],
},
]);
expect(events.map((event) => event.item?.type)).toEqual([
"tool_call",
"tool_call",
"assistant_message",
]);
const image = events.find(
(event) => event.type === "timeline" && event.item.type === "assistant_message",
);
expect(image).toMatchObject({
type: "timeline",
item: { type: "assistant_message", text: expect.stringContaining("![Image](file://") },
});
if (image?.type !== "timeline" || image.item.type !== "assistant_message")
throw new Error("Missing image");
const url = image.item.text.match(/\((file:[^)]+)\)/)![1];
const { readFile, unlink } = await import("node:fs/promises");
expect(await readFile(new URL(url))).toEqual(Buffer.from("hello"));
await unlink(new URL(url));
const replay = await collectHistory([
{
role: "toolResult",
toolCallId: "image-read",
toolName: "read",
content: [{ type: "image", data: "aGVsbG8=", mimeType: "image/png" }],
},
]);
expect(replay).toContainEqual(image);
expect(await readFile(new URL(url))).toEqual(Buffer.from("hello"));
});
});
test("replayed Pi images keep their position before the following reply", async () => {
const events = await collectHistory([
{
role: "toolResult",
toolCallId: "image-position",
toolName: "read",
content: [{ type: "image", data: "aGVsbG8=", mimeType: "image/png" }],
},
{ role: "assistant", content: [{ type: "text", text: "Image read complete." }] },
]);
expect(
events.map((event) =>
event.item?.type === "assistant_message" ? event.item.text : event.item?.type,
),
).toEqual(["tool_call", expect.stringContaining("![Image]("), "Image read complete."]);
});
@@ -1,5 +1,9 @@
import { mapCustomMessageToToolCall } from "../custom-message.js";
import type { AgentStreamEvent, AgentTimelineItem, ToolCallDetail } from "../../agent-sdk-types.js";
import {
materializeProviderImage,
renderProviderImageOutputAsAssistantMarkdown,
} from "../provider-image-output.js";
import {
createPiExtensionHost,
type PiExtensionEventOutput,
@@ -11,6 +15,7 @@ import {
mapToolDetail,
parseToolArgs,
parseToolResult,
splitPiToolResultImages,
type PiToolResult,
type PiTrackedToolCall,
} from "./tool-call-mapper.js";
@@ -71,7 +76,7 @@ export class PiHistoryMapper {
private readonly extensionHost: PiExtensionHost = createPiExtensionHost(),
) {}
mapMessages(messages: readonly PiAgentMessage[]): AgentStreamEvent[] {
async mapMessages(messages: readonly PiAgentMessage[]): Promise<AgentStreamEvent[]> {
const events: AgentStreamEvent[] = [];
for (const message of messages) {
@@ -86,7 +91,7 @@ export class PiHistoryMapper {
events.push(...this.mapAssistantMessage(message));
break;
case "toolResult": {
events.push(...this.mapToolResultMessage(message));
events.push(...(await this.mapToolResultMessage(message)));
break;
}
case "bashExecution":
@@ -207,24 +212,35 @@ export class PiHistoryMapper {
return events;
}
private mapToolResultMessage(
private async mapToolResultMessage(
message: Extract<PiAgentMessage, { role: "toolResult" }>,
): AgentStreamEvent[] {
): Promise<AgentStreamEvent[]> {
const tracked =
this.pendingToolCalls.get(message.toolCallId) ?? parseToolArgs(message.toolName, null);
this.pendingToolCalls.delete(message.toolCallId);
const result = parseToolResult({ content: message.content, details: message.details });
// Pull image blocks out of the result so base64 never reaches the tool output, then render
// each one as an assistant_message markdown image after the tool_call (mirroring the live
// path and the Claude provider, upstream #1717).
const { images, result: splitResult } = splitPiToolResultImages(result);
const mapping = this.extensionHost.mapToolCall({
callId: message.toolCallId,
toolName: tracked.toolName,
args: tracked.args,
status: message.isError ? "failed" : "completed",
result,
result: splitResult,
});
const detail = this.mapToolDetail(message.toolCallId, tracked, result, mapping?.detail);
const detail = this.mapToolDetail(message.toolCallId, tracked, splitResult, mapping?.detail);
if (!detail) {
return [];
}
const imageEvents: AgentStreamEvent[] = [];
for (const image of images) {
const item = await renderProviderImageOutputAsAssistantMarkdown(image, {
materialize: materializeProviderImage,
});
if (item) imageEvents.push({ type: "timeline", provider: this.provider, item });
}
return [
{
type: "timeline",
@@ -234,9 +250,10 @@ export class PiHistoryMapper {
name: mapping?.name ?? tracked.toolName,
isError: Boolean(message.isError),
detail,
errorText: extractTextFromToolResult(result) ?? "Tool call failed",
errorText: extractTextFromToolResult(splitResult) ?? "Tool call failed",
}),
},
...imageEvents,
...this.extensionEvents(mapping),
];
}
@@ -297,9 +314,10 @@ export async function* streamPiHistory(
signal?: AbortSignal,
): AsyncGenerator<AgentStreamEvent> {
const mapper = new PiHistoryMapper(provider, userEntries, hooks, extensionHost);
for (const event of mapper.mapMessages(messages)) {
for (const message of messages) {
if (signal?.aborted) return;
if (event) {
for (const event of await mapper.mapMessages([message])) {
if (signal?.aborted) return;
yield event;
}
}
@@ -1,6 +1,12 @@
import { describe, expect, test } from "vitest";
import { mapToolDetail, parseToolArgs, parseToolResult } from "./tool-call-mapper.js";
import {
extractTextFromToolResult,
mapToolDetail,
parseToolArgs,
parseToolResult,
splitPiToolResultImages,
} from "./tool-call-mapper.js";
describe("Pi tool call mapper", () => {
test("maps bash args and result to shell detail", () => {
@@ -56,3 +62,77 @@ describe("Pi tool call mapper", () => {
});
});
});
describe("splitPiToolResultImages", () => {
test("extracts image blocks and replaces them with [image] placeholders", () => {
const parsed = parseToolResult({
content: [
{ type: "text", text: "shot taken" },
{ type: "image", data: "aGVsbG8=", mimeType: "image/png" },
],
});
const { images, result } = splitPiToolResultImages(parsed);
expect(images).toEqual([{ data: "aGVsbG8=", mimeType: "image/png" }]);
expect(result).toEqual({
content: [
{ type: "text", text: "shot taken" },
{ type: "text", text: "[image]" },
],
});
});
test("replaces image-only results with a non-empty placeholder", () => {
const parsed = parseToolResult({
content: [{ type: "image", data: "aGVsbG8=", mimeType: "image/jpeg" }],
});
const { images, result } = splitPiToolResultImages(parsed);
expect(images).toHaveLength(1);
expect(extractTextFromToolResult(result)).toBe("[image]");
});
test("passes through string results and results without images", () => {
expect(splitPiToolResultImages("plain output")).toEqual({
images: [],
result: "plain output",
});
const textOnly = parseToolResult({ content: [{ type: "text", text: "no images" }] });
expect(splitPiToolResultImages(textOnly)).toEqual({ images: [], result: textOnly });
expect(splitPiToolResultImages(null)).toEqual({ images: [], result: null });
});
test("keeps other fields on the result object", () => {
const parsed = parseToolResult({
exitCode: 0,
content: [{ type: "image", data: "aGVsbG8=" }],
});
const { result } = splitPiToolResultImages(parsed);
expect(result).toMatchObject({ exitCode: 0 });
});
});
test("tool-result images remove nested structured image data while preserving metadata", () => {
const data = Buffer.from("nested screenshot bytes").toString("base64");
const result = parseToolResult({
content: [{ type: "image", data, mimeType: "image/png" }],
structuredContent: {
content: [{ type: "image", data, mimeType: "image/png", width: 64 }],
captureId: "capture-1",
read: { type: "image", data, mimeType: "image/png", note: "Read image file" },
extra: { data: "keep ordinary data" },
},
});
const split = splitPiToolResultImages(result);
const detail = mapToolDetail(parseToolArgs("screenshot", {}), split.result);
expect(JSON.stringify(detail)).not.toContain(data);
expect(split.images).toEqual([{ data, mimeType: "image/png" }]);
expect(split.result).toMatchObject({
structuredContent: {
content: [{ type: "image", data: "[image]", mimeType: "image/png", width: 64 }],
captureId: "capture-1",
read: { type: "image", data: "[image]", mimeType: "image/png", note: "Read image file" },
extra: { data: "keep ordinary data" },
},
});
});
@@ -1,6 +1,7 @@
import { z } from "zod";
import type { ToolCallDetail } from "../../agent-sdk-types.js";
import type { ProviderImageOutput } from "../provider-image-output.js";
interface BashToolInput {
command: string;
@@ -52,6 +53,7 @@ interface PiToolResultObject {
stdout?: string;
text?: string;
content?: PiToolResultContent[];
structuredContent?: unknown;
exitCode?: number;
code?: number;
details?: PiToolResultDetails;
@@ -67,6 +69,12 @@ interface PiToolResultTextContent {
text: string;
}
const PiToolResultImageContentSchema = z.object({
type: z.literal("image"),
data: z.string().min(1),
mimeType: z.string().optional(),
});
interface PiToolResultUnknownContent {
type: string;
}
@@ -236,6 +244,61 @@ export function parseToolResult(rawResult: unknown): PiToolResult {
return null;
}
// Pi returns images inside tool-result content as base64 blocks. Left in place they reach the
// tool-output stringifier, which dumps base64 into the tool output. We pull those blocks out to
// render them as image markdown and leave a "[image]" placeholder so image-only results still
// produce non-empty output (mirroring splitClaudeToolResultImages).
export function splitPiToolResultImages(result: PiToolResult): {
images: ProviderImageOutput[];
result: PiToolResult;
} {
if (!result || typeof result === "string" || !result.content) {
return { images: [], result };
}
const images: ProviderImageOutput[] = [];
let replaced = false;
const content = result.content.map((block) => {
const image = toPiImageOutput(block);
if (image) {
images.push(image);
replaced = true;
return { type: "text", text: "[image]" } satisfies PiToolResultTextContent;
}
return block;
});
if (!replaced) {
return { images: [], result };
}
return {
images,
result: {
...result,
content,
...(result.structuredContent === undefined
? {}
: { structuredContent: withoutImageData(result.structuredContent) }),
},
};
}
function withoutImageData(value: unknown): unknown {
if (Array.isArray(value)) return value.map(withoutImageData);
if (value === null || typeof value !== "object") return value;
const image = toPiImageOutput(value);
return Object.fromEntries(
Object.entries(value).map(([key, child]) => [
key,
image && key === "data" ? "[image]" : withoutImageData(child),
]),
);
}
function toPiImageOutput(block: unknown): ProviderImageOutput | null {
const parsed = PiToolResultImageContentSchema.safeParse(block);
if (!parsed.success) return null;
return { data: parsed.data.data, mimeType: parsed.data.mimeType ?? null };
}
export function extractTextFromToolResult(result: PiToolResult): string | undefined {
if (typeof result === "string") {
return result;
+2
View File
@@ -420,6 +420,7 @@ export interface PaseoDaemonConfig {
trustedProxies?: true | string[];
mcpEnabled?: boolean;
mcpInjectIntoAgents?: boolean;
usageEnabled?: boolean;
browserToolsEnabled?: boolean;
git?: {
maxProcessesPerSecond: number;
@@ -590,6 +591,7 @@ function createInitialMutableDaemonConfig(config: ResolvedDaemonSettings): Mutab
...(config.providerCatalogRefreshTimeoutMs !== undefined
? { catalogRefreshTimeoutMs: config.providerCatalogRefreshTimeoutMs }
: {}),
usage: { enabled: config.usageEnabled !== false },
browserTools: { enabled: config.browserToolsEnabled ?? false },
providers,
metadataGeneration: {
+6
View File
@@ -523,6 +523,10 @@ function resolveAppendSystemPrompt(persisted: ReturnType<typeof loadPersistedCon
return persisted.daemon?.appendSystemPrompt ?? "";
}
function resolveUsageEnabled(persisted: ReturnType<typeof loadPersistedConfig>): boolean {
return persisted.daemon?.usage?.enabled !== false;
}
function resolveBrowserToolsEnabled(persisted: ReturnType<typeof loadPersistedConfig>): boolean {
return persisted.daemon?.browserTools?.enabled ?? false;
}
@@ -548,6 +552,7 @@ function resolveStaticLoadConfigSettings(
mcpEnabled: cli?.mcpEnabled ?? persisted.daemon?.mcp?.enabled ?? true,
mcpInjectIntoAgents:
cli?.mcpInjectIntoAgents ?? persisted.daemon?.mcp?.injectIntoAgents ?? false,
usageEnabled: resolveUsageEnabled(persisted),
browserToolsEnabled: resolveBrowserToolsEnabled(persisted),
autoArchiveAfterMerge: persisted.daemon?.autoArchiveAfterMerge ?? false,
appendSystemPrompt: resolveAppendSystemPrompt(persisted),
@@ -576,6 +581,7 @@ export type ResolvedDaemonSettings = Pick<
| "trustedProxies"
| "mcpEnabled"
| "mcpInjectIntoAgents"
| "usageEnabled"
| "browserToolsEnabled"
| "git"
| "autoArchiveAfterMerge"
@@ -21,6 +21,7 @@ import {
type HostUpdate,
} from "@getpaseo/protocol/hosts";
import type { DaemonPermission, WSHelloMessage } from "@getpaseo/protocol/messages";
import { webSocketProxyAgent } from "../network/index.js";
export class HostError extends Error {
constructor(
@@ -242,6 +243,7 @@ export class ConnectedHosts {
{
clientId: `host-link-${this.self.serverId}-${row.registrationId}`,
connectTimeoutMs: 10000,
webSocketAgent: webSocketProxyAgent,
},
this.budget,
);
@@ -10,6 +10,10 @@ import { readSpeechSettings } from "./speech/speech-settings.js";
import type { PersistedConfig } from "./persisted-config.js";
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
function usageEnabled(persisted: PersistedConfig): boolean {
return persisted.daemon?.usage?.enabled !== false;
}
function reloadableConfig(
persisted: PersistedConfig,
options: { relayEnabledFallback?: boolean } = {},
@@ -23,6 +27,7 @@ function reloadableConfig(
enabled: relay.enabled ?? options.relayEnabledFallback ?? true,
},
mcp: { enabled: true, injectIntoAgents: false },
usage: { enabled: usageEnabled(persisted) },
browserTools: { enabled: daemon.browserTools?.enabled ?? false },
providers: (agents.providers ?? {}) as MutableDaemonConfig["providers"],
metadataGeneration: { providers: agents.metadataGeneration?.providers ?? [] },
@@ -1572,3 +1577,31 @@ describe("DaemonConfigStore speech settings", () => {
expect(JSON.stringify(other.get())).not.toContain("secret");
});
});
test("usage policy persists across restart and live reload", async () => {
const paseoHome = mkdtempSync(path.join(tmpdir(), "usage-policy-"));
try {
const initial = reloadableConfig({});
const store = new DaemonConfigStore(paseoHome, initial, undefined, {
reloadSource: {
resolve: (persisted) => ({
mutable: reloadableConfig(persisted),
overrideControlledPaths: [],
}),
},
});
await store.patch({ usage: { enabled: false } });
expect(loadConfig(paseoHome, { env: {} }).usageEnabled).toBe(false);
const persisted = loadPersistedConfig(paseoHome);
const restarted = new DaemonConfigStore(paseoHome, reloadableConfig(persisted));
expect(restarted.get().usage).toEqual({ enabled: false });
writeFileSync(
path.join(paseoHome, "config.json"),
JSON.stringify({ daemon: { usage: { enabled: true } } }),
);
await store.reload();
expect(store.get().usage).toEqual({ enabled: true });
} finally {
rmSync(paseoHome, { recursive: true, force: true });
}
});
@@ -22,6 +22,7 @@ type ProviderOverride = import("./agent/provider-launch-config.js").ProviderOver
interface SupportedMutableConfigPatch {
relay?: { enabled?: boolean; requireProtectedSecurity?: boolean };
mcp?: { injectIntoAgents?: boolean };
usage?: { enabled: boolean };
browserTools?: { enabled?: boolean };
providers?: MutableDaemonConfig["providers"];
removeProviders?: string[];
@@ -182,6 +183,7 @@ const RELOADABLE_PATHS = [
"daemon.relay.requireProtectedSecurity",
"daemon.mcp.enabled",
"daemon.mcp.injectIntoAgents",
"daemon.usage.enabled",
"daemon.browserTools.enabled",
"daemon.hostnames",
"daemon.cors.allowedOrigins",
@@ -209,6 +211,7 @@ const PERSISTED_TO_MUTABLE_PATH = new Map<string, string>([
["daemon.relay.requireProtectedSecurity", "relay.requireProtectedSecurity"],
["daemon.mcp.enabled", "mcp.enabled"],
["daemon.mcp.injectIntoAgents", "mcp.injectIntoAgents"],
["daemon.usage.enabled", "usage.enabled"],
["daemon.browserTools.enabled", "browserTools.enabled"],
["daemon.hostnames", "hostnames"],
["daemon.cors.allowedOrigins", "cors.allowedOrigins"],
@@ -281,6 +284,7 @@ function pickRelayPatch(
function pickSupportedPatchFields(patch: MutableDaemonConfigPatch): SupportedMutableConfigPatch {
return {
...pickRelayPatch(patch.relay),
usage: patch.usage,
...(patch.mcp?.injectIntoAgents !== undefined
? { mcp: { injectIntoAgents: patch.mcp.injectIntoAgents } }
: {}),
@@ -767,6 +771,7 @@ function mergeMutableDaemonPatch(
if (patch.mcp?.injectIntoAgents !== undefined) {
next.mcp = { ...next.mcp, injectIntoAgents: patch.mcp.injectIntoAgents };
}
if (patch.usage) next.usage = patch.usage;
if (patch.browserTools?.enabled !== undefined) {
next.browserTools = { ...next.browserTools, enabled: patch.browserTools.enabled };
}
@@ -1,5 +1,6 @@
import { appendFileSync, mkdirSync } from "node:fs";
import path from "node:path";
import { initializeEnvironmentProxy } from "./network/index.js";
import { createPaseoDaemon, formatListenTarget } from "./bootstrap.js";
import { loadConfig } from "./config.js";
import { resolvePaseoHome } from "./paseo-home.js";
@@ -132,6 +133,11 @@ function applyCliFlagOverrides(config: ReturnType<typeof loadConfig>): void {
async function main() {
const { paseoHome, logger, config } = bootstrapFromEnvironment();
for (const variable of initializeEnvironmentProxy()) {
writeWorkerLifecycleLog(paseoHome, "Ignoring invalid or unsupported HTTP proxy variable", {
variable,
});
}
let daemon: Awaited<ReturnType<typeof createPaseoDaemon>> | null = null;
let shutdownPromise: Promise<number> | null = null;
let exitHookInstalled = false;
@@ -1,5 +1,6 @@
import { WebSocket } from "ws";
import { z } from "zod";
import { webSocketProxyAgent } from "../network/index.js";
import type { WebSocketLike } from "../websocket-server.js";
const SOCKET_PING_INTERVAL_MS = 10_000;
@@ -166,6 +167,7 @@ export class DirectHubRelationshipRemote implements HubRelationshipRemote {
openSocket(input: HubSocketCredentials, events: HubSocketEvents): HubSocketConnection {
let sessionProtocol: "legacy" | "session-v1" = "legacy";
const socket = new WebSocket(input.webSocketUrl, {
agent: webSocketProxyAgent(input.webSocketUrl),
handshakeTimeout: this.requestTimeoutMs,
headers: {
authorization: `Bearer ${input.credential}`,
+116
View File
@@ -0,0 +1,116 @@
import type { Agent } from "node:http";
import { EnvHttpProxyAgent, Pool, setGlobalDispatcher } from "undici";
import { HttpsProxyAgent } from "https-proxy-agent";
interface ProxyEnvironment {
httpProxy: string;
httpsProxy: string;
noProxy: string;
}
let environment = readEnvironment(process.env, process.platform).environment;
function readEnvironment(
env: NodeJS.ProcessEnv,
platform: NodeJS.Platform,
): {
environment: ProxyEnvironment;
ignored: string[];
} {
// process.env lookups are case-insensitive on Windows. Read each actual entry once.
const values = new Map(
Object.entries(env).map(([name, value]) => [
platform === "win32" ? name.toLowerCase() : name,
value,
]),
);
const ignored: string[] = [];
function proxy(variable: string): string | undefined {
const value = values.get(variable);
if (value === undefined) return undefined;
if (!value.trim()) return undefined;
try {
const url = new URL(value.includes("://") ? value : `http://${value}`);
if (url.protocol !== "http:" && url.protocol !== "https:")
throw new Error("Unsupported proxy protocol");
decodeURIComponent(url.username);
decodeURIComponent(url.password);
return url.href;
} catch {
ignored.push(variable);
return undefined;
}
}
const httpProxy = proxy("http_proxy") ?? proxy("HTTP_PROXY") ?? "";
return {
environment: {
httpProxy,
httpsProxy: proxy("https_proxy") ?? proxy("HTTPS_PROXY") ?? httpProxy,
noProxy: values.get("no_proxy") ?? values.get("NO_PROXY") ?? "",
},
ignored,
};
}
function bypassList(noProxy: string): string {
return noProxy.split(/[,\s]+/).includes("*") ? "*" : `${noProxy},localhost,127.0.0.1,[::1],::1`;
}
function proxyClient(origin: URL, options: object) {
const pool = new Pool(origin, options);
if (!origin.username && !origin.password) return pool;
const credentials = `${decodeURIComponent(origin.username)}:${decodeURIComponent(origin.password)}`;
const authorization = `Basic ${Buffer.from(credentials).toString("base64")}`;
// This pool only sends CONNECT requests to this proxy, never requests to the origin.
// undici's URL auth requires both fields; HTTP Basic also permits either field to be empty.
return pool.compose(
(dispatch) => (request, handler) =>
dispatch(
{
...request,
headers: { ...request.headers, "proxy-authorization": authorization },
},
handler,
),
);
}
/** Install once at startup; return ignored variable names for logging without exposing credentials. */
export function initializeEnvironmentProxy(
env: NodeJS.ProcessEnv = process.env,
platform: NodeJS.Platform = process.platform,
): string[] {
const resolved = readEnvironment(env, platform);
environment = resolved.environment;
setGlobalDispatcher(
new EnvHttpProxyAgent({
httpProxy: environment.httpProxy,
httpsProxy: environment.httpsProxy,
noProxy: bypassList(environment.noProxy),
clientFactory: proxyClient,
}),
);
return resolved.ignored;
}
/** ws uses Node HTTP agents rather than the fetch dispatcher. */
export function webSocketProxyAgent(address: string): Agent | undefined {
const url = new URL(address);
const hostname = url.hostname.toLowerCase();
const port = url.port || (url.protocol === "wss:" ? "443" : "80");
const entries = bypassList(environment.noProxy)
.toLowerCase()
.split(/[,\s]+/);
if (
entries.some((entry) => {
if (entry === "*") return true;
const match = entry.match(/^(.+):(\d+)$/);
if (match && Number(match[2]) !== Number(port)) return false;
const host = (match ? match[1]! : entry).replace(/^\*?\./, "");
return host !== "" && (hostname === host || hostname.endsWith(`.${host}`));
})
)
return undefined;
const proxy = url.protocol === "wss:" ? environment.httpsProxy : environment.httpProxy;
return proxy ? new HttpsProxyAgent(proxy) : undefined;
}
@@ -0,0 +1,341 @@
import { fork } from "node:child_process";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createServer, type Server } from "node:http";
import { once } from "node:events";
import { connect } from "node:net";
import { afterEach, expect, test } from "vitest";
import { WebSocket, WebSocketServer } from "ws";
import { getGlobalDispatcher, setGlobalDispatcher } from "undici";
import { initializeEnvironmentProxy, webSocketProxyAgent } from "./index.js";
import { ConnectedHosts } from "../connected-hosts/index.js";
const original = getGlobalDispatcher();
const servers: Server[] = [];
afterEach(async () => {
const installed = getGlobalDispatcher();
setGlobalDispatcher(original);
if (installed !== original) await installed.close();
await Promise.all(
servers.splice(0).map(
(server) =>
new Promise<void>((resolve) => {
server.closeAllConnections();
server.close(() => resolve());
}),
),
);
});
async function listen(server: Server) {
servers.push(server);
server.listen(0, "127.0.0.1");
await once(server, "listening");
const address = server.address();
if (!address || typeof address === "string") throw new Error("Missing address");
return `127.0.0.1:${address.port}`;
}
async function proxy() {
const tunnels: string[] = [];
const server = createServer();
server.on("connect", (request, socket) => {
tunnels.push(request.url!);
socket.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n");
});
return { url: `http://${await listen(server)}`, tunnels };
}
test("loopback fetch and WebSockets bypass HTTP_PROXY with empty NO_PROXY", async () => {
const recorder = await proxy();
initializeEnvironmentProxy({ HTTP_PROXY: recorder.url, NO_PROXY: "" });
const server = createServer((_, response) => response.end("direct"));
const sockets = new WebSocketServer({ server });
sockets.on("connection", (socket) => socket.send("direct"));
const address = await listen(server);
expect(await (await fetch(`http://${address}`)).text()).toBe("direct");
const socket = new WebSocket(`ws://${address}`, {
agent: webSocketProxyAgent(`ws://${address}`),
});
expect((await once(socket, "message"))[0].toString()).toBe("direct");
socket.close();
await once(socket, "close");
await new Promise<void>((resolve) => sockets.close(() => resolve()));
for (const host of ["localhost", "127.0.0.1", "[::1]"])
expect(webSocketProxyAgent(`wss://${host}:1234`)).toBeUndefined();
expect(recorder.tunnels).toEqual([]);
});
test("fetch and WebSockets send non-loopback traffic through CONNECT", async () => {
const recorder = await proxy();
initializeEnvironmentProxy({ http_proxy: recorder.url });
await expect(
fetch("https://vendor.invalid/", { signal: AbortSignal.timeout(500) }),
).rejects.toThrow();
const socket = new WebSocket("wss://vendor.invalid", {
agent: webSocketProxyAgent("wss://vendor.invalid"),
});
await once(socket, "error");
expect(
recorder.tunnels.filter((host) => host === "vendor.invalid:443").length,
).toBeGreaterThanOrEqual(2);
});
test("NO_PROXY and absent variables keep matching WebSockets direct", async () => {
const recorder = await proxy();
initializeEnvironmentProxy({
HTTPS_PROXY: recorder.url,
NO_PROXY: "vendor.invalid,.example.invalid:443",
});
expect(webSocketProxyAgent("wss://vendor.invalid")).toBeUndefined();
await expect(
fetch("https://vendor.invalid/", { signal: AbortSignal.timeout(500) }),
).rejects.toThrow();
expect(webSocketProxyAgent("wss://sub.example.invalid")).toBeUndefined();
expect(webSocketProxyAgent("wss://example.invalid:444")).toBeDefined();
initializeEnvironmentProxy({ HTTP_PROXY: recorder.url, no_proxy: "*" });
expect(webSocketProxyAgent("ws://vendor.invalid")).toBeUndefined();
initializeEnvironmentProxy({});
expect(webSocketProxyAgent("wss://vendor.invalid")).toBeUndefined();
const address = await listen(createServer((_, response) => response.end("direct")));
expect(await (await fetch(`http://${address}`)).text()).toBe("direct");
expect(recorder.tunnels).toEqual([]);
});
test.each(["127.0.0.1", "localhost"])(
"scheme-less %s proxies work for fetch and WebSockets",
async (host) => {
const recorder = await proxy();
const address = new URL(recorder.url);
initializeEnvironmentProxy({ https_proxy: `${host}:${address.port}` });
await expect(
fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }),
).rejects.toThrow();
const socket = new WebSocket("wss://vendor.invalid", {
agent: webSocketProxyAgent("wss://vendor.invalid"),
});
await once(socket, "error");
expect(recorder.tunnels).toContain("vendor.invalid:443");
},
);
test.each([
"http://[",
"http://user%zz:secret@proxy.corp",
"socks5://127.0.0.1:7890",
"ftp://proxy.corp:8080",
])("ignores invalid or unsupported proxy %s without stopping startup", async (value) => {
const recorder = await proxy();
expect(initializeEnvironmentProxy({ HTTP_PROXY: recorder.url, https_proxy: value })).toEqual([
"https_proxy",
]);
expect(webSocketProxyAgent("wss://vendor.invalid")).toBeDefined();
await expect(
fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }),
).rejects.toThrow();
const socket = new WebSocket("wss://vendor.invalid", {
agent: webSocketProxyAgent("wss://vendor.invalid"),
});
await once(socket, "error");
expect(recorder.tunnels).toEqual(["vendor.invalid:443", "vendor.invalid:443"]);
});
test("daemon starts with an ignored proxy and writes one redacted warning to daemon.log", async () => {
const home = await mkdtemp(path.join(os.tmpdir(), "daemon-invalid-proxy-"));
const env = Object.fromEntries(
Object.entries(process.env).filter(
([key]) => !["http_proxy", "https_proxy"].includes(key.toLowerCase()),
),
);
const worker = fork(fileURLToPath(new URL("../daemon-worker.ts", import.meta.url)), [], {
execArgv: ["--import", "tsx"],
silent: true,
env: {
...env,
PASEO_HOME: home,
HOME: home,
USERPROFILE: home,
PASEO_LISTEN: "127.0.0.1:0",
PASEO_RELAY_ENABLED: "0",
https_proxy: "socks5://private:secret@127.0.0.1:7890",
},
});
worker.stdout?.resume();
let stderr = "";
worker.stderr?.on("data", (chunk) => {
stderr += String(chunk);
});
try {
await new Promise<void>((resolve, reject) => {
worker.on("message", (message) => {
if (
typeof message === "object" &&
message !== null &&
"type" in message &&
message.type === "paseo:ready"
)
resolve();
});
worker.on("exit", (code) => reject(new Error(`Worker exited ${code}: ${stderr}`)));
});
const log = await readFile(path.join(home, "daemon.log"), "utf8");
const warnings = log
.split("\n")
.filter((line) => line.includes("Ignoring invalid or unsupported HTTP proxy variable"));
expect(warnings).toHaveLength(1);
expect(JSON.parse(warnings[0]!).variable).toBe("https_proxy");
expect(warnings[0]).not.toContain("secret");
} finally {
if (worker.exitCode === null && worker.signalCode === null) {
const exited = once(worker, "exit");
worker.kill("SIGTERM");
await exited;
}
await rm(home, { recursive: true, force: true });
}
}, 60_000);
test("accepts a scheme-less corporate proxy hostname", () => {
expect(initializeEnvironmentProxy({ https_proxy: "proxy.corp:8080" })).toEqual([]);
expect(webSocketProxyAgent("wss://vendor.invalid")).toBeDefined();
});
test("an ignored lowercase variable falls back to the uppercase variable", async () => {
const recorder = await proxy();
expect(
initializeEnvironmentProxy(
{
https_proxy: "socks5://proxy.invalid",
HTTPS_PROXY: recorder.url,
},
"linux",
),
).toEqual(["https_proxy"]);
await expect(
fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }),
).rejects.toThrow();
const socket = new WebSocket("wss://vendor.invalid", {
agent: webSocketProxyAgent("wss://vendor.invalid"),
});
await once(socket, "error");
expect(recorder.tunnels).toEqual(["vendor.invalid:443", "vendor.invalid:443"]);
});
test("case-insensitive environment access reports a variable only once", () => {
const env = new Proxy(
{ https_proxy: "socks5://127.0.0.1:7890" },
{
get(target, key) {
return Reflect.get(target, typeof key === "string" ? key.toLowerCase() : key);
},
},
);
expect(initializeEnvironmentProxy(env)).toEqual(["https_proxy"]);
});
test("connected-host links send remote WebSockets through the environment proxy", async () => {
const recorder = await proxy();
initializeEnvironmentProxy({ HTTPS_PROXY: recorder.url });
const home = await mkdtemp(path.join(os.tmpdir(), "connected-host-proxy-"));
const hosts = new ConnectedHosts(home, { serverId: "self", label: "Self" });
try {
await hosts.add(
{ connection: "wss://remote.invalid/ws" },
{ sourceId: "test", manageSources: true },
);
await expect.poll(() => recorder.tunnels).toContain("remote.invalid:443");
} finally {
await hosts.close();
await rm(home, { recursive: true, force: true });
}
});
test.each(["corp.internal,*", "vendor.invalid:0443"])(
"fetch and WebSockets share NO_PROXY=%s",
async (noProxy) => {
const recorder = await proxy();
initializeEnvironmentProxy({ HTTPS_PROXY: recorder.url, NO_PROXY: noProxy });
expect(webSocketProxyAgent("wss://vendor.invalid")).toBeUndefined();
await expect(
fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }),
).rejects.toThrow();
expect(recorder.tunnels).toEqual([]);
},
);
test("Windows mixed-case environment names route and bypass both transports", async () => {
const recorder = await proxy();
// Windows preserves spelling but treats environment names without regard to case.
initializeEnvironmentProxy({ Https_Proxy: recorder.url, No_Proxy: "other.invalid" }, "win32");
expect(webSocketProxyAgent("wss://other.invalid")).toBeUndefined();
await expect(
fetch("https://other.invalid", { signal: AbortSignal.timeout(500) }),
).rejects.toThrow();
expect(webSocketProxyAgent("wss://vendor.invalid")).toBeDefined();
await expect(
fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }),
).rejects.toThrow();
const socket = new WebSocket("wss://vendor.invalid", {
agent: webSocketProxyAgent("wss://vendor.invalid"),
});
await once(socket, "error");
expect(recorder.tunnels).toEqual(["vendor.invalid:443", "vendor.invalid:443"]);
});
test("POSIX mixed-case names do not override standard proxy names", async () => {
const recorder = await proxy();
initializeEnvironmentProxy(
{ Https_Proxy: recorder.url, HTTPS_PROXY: recorder.url, No_Proxy: "*" },
"linux",
);
expect(webSocketProxyAgent("wss://vendor.invalid")).toBeDefined();
await expect(
fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }),
).rejects.toThrow();
expect(recorder.tunnels).toEqual(["vendor.invalid:443"]);
});
test("proxy credentials stay on CONNECT and do not reach the HTTP origin", async () => {
let originAuthorization: string | undefined;
const origin = createServer((request, response) => {
originAuthorization = request.headers["proxy-authorization"];
response.end("through proxy");
});
const originAddress = new URL(`http://${await listen(origin)}`);
const authorizations: (string | undefined)[] = [];
const server = createServer();
server.on("connect", (request, socket, head) => {
authorizations.push(request.headers["proxy-authorization"]);
const upstream = connect(Number(originAddress.port), "127.0.0.1", () => {
socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
if (head.length) upstream.write(head);
socket.pipe(upstream).pipe(socket);
});
socket.on("error", () => upstream.destroy());
upstream.on("error", () => socket.destroy());
socket.on("close", () => upstream.destroy());
});
initializeEnvironmentProxy({ HTTP_PROXY: `http://user:@${await listen(server)}` });
const response = await fetch("http://vendor.invalid", { signal: AbortSignal.timeout(3000) });
expect(await response.text()).toBe("through proxy");
expect(authorizations).toEqual([`Basic ${Buffer.from("user:").toString("base64")}`]);
expect(originAuthorization).toBeUndefined();
});
test.each(["user:@", ":secret@", "user:secret@"])(
"fetch and WebSockets authenticate proxy credentials %s",
async (credentials) => {
const authorizations: (string | undefined)[] = [];
const server = createServer();
server.on("connect", (request, socket) => {
authorizations.push(request.headers["proxy-authorization"]);
socket.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n");
});
initializeEnvironmentProxy({ HTTPS_PROXY: `http://${credentials}${await listen(server)}` });
await expect(
fetch("https://vendor.invalid", { signal: AbortSignal.timeout(500) }),
).rejects.toThrow();
const socket = new WebSocket("wss://vendor.invalid", {
agent: webSocketProxyAgent("wss://vendor.invalid"),
});
await once(socket, "error");
const expected = `Basic ${Buffer.from(credentials.slice(0, -1)).toString("base64")}`;
expect(authorizations).toEqual([expected, expected]);
},
);
@@ -259,6 +259,7 @@ export const PersistedConfigSchema = z
})
.passthrough()
.optional(),
usage: z.object({ enabled: z.boolean().optional() }).optional(),
browserTools: z
.object({
enabled: z.boolean().optional(),
@@ -24,6 +24,7 @@ import { createPluginClientId } from "./plugin-session-identity.js";
import { PluginSettingsStore } from "./settings/index.js";
import { readPluginProviderIcon } from "./provider-icon.js";
import { initializeEnvironmentProxy } from "../network/index.js";
function describeError(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
@@ -606,6 +607,7 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
const parsed = PluginProcessRequestSchema.safeParse(raw);
if (!worker && parsed.success && parsed.data.type === "initialize") {
try {
initializeEnvironmentProxy();
worker = createPluginWorker({ channel, contribute: evaluateBundle(parsed.data.bundle) });
} catch (error) {
channel.send({ type: "fatal", error: describeError(error) });
@@ -0,0 +1,31 @@
import path from "node:path";
import { initializeEnvironmentProxy } from "../../network/index.js";
import { DaemonClient } from "../../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../../test-utils/paseo-daemon.js";
import { BuiltinPluginLoader, resolveBuiltinPluginsRoot } from "../builtin/index.js";
const mode = process.argv[2];
if (mode !== "builtin" && mode !== "directory") throw new Error("Expected builtin or directory");
const sources = ["claude-usage-source", "codex-usage-source"];
// Built-ins run inside the daemon; directory plugins initialize their own subprocess network.
if (mode === "builtin") initializeEnvironmentProxy();
const daemon = await createTestPaseoDaemon({
pluginsEnabled: mode === "directory",
builtinPlugins: new BuiltinPluginLoader(
resolveBuiltinPluginsRoot(),
mode === "builtin" ? sources : [],
),
});
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
try {
await client.connect();
if (mode === "directory") {
for (const source of sources) {
await client.installDirectoryPlugin(path.join(resolveBuiltinPluginsRoot(), source), source);
}
}
await client.listUsageReports();
} finally {
await client.close();
await daemon.close();
}
@@ -1,7 +1,11 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { createServer } from "node:http";
import { once } from "node:events";
import { expect, test } from "vitest";
import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
@@ -335,3 +339,74 @@ export default function contribute(server) {
await rm(root, { recursive: true, force: true });
}
}, 60_000);
test.each(["builtin", "directory"])(
"%s usage plugins reach the environment proxy",
async (mode) => {
const root = await mkdtemp(path.join(os.tmpdir(), "usage-proxy-"));
const tunnels: string[] = [];
const proxy = createServer();
proxy.on("connect", (request, socket) => {
tunnels.push(request.url!);
socket.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n");
});
proxy.listen(0, "127.0.0.1");
await once(proxy, "listening");
const address = proxy.address();
if (!address || typeof address === "string") throw new Error("Missing proxy address");
const guard = path.join(root, "network-guard.cjs");
// Prevent vendor DNS/network access even when proxy support is broken.
await writeFile(
guard,
`const dns = require('node:dns');
const lookup = dns.lookup;
dns.lookup = function(host, ...args) {
if (host === 'localhost' || host === '127.0.0.1' || host === '::1') return lookup.call(this, host, ...args);
args.at(-1)(Object.assign(new Error('External DNS forbidden in proxy test'), { code: 'ENOTFOUND' }));
};`,
);
await mkdir(path.join(root, ".claude"));
await mkdir(path.join(root, ".codex"));
await writeFile(
path.join(root, ".claude", ".credentials.json"),
JSON.stringify({ claudeAiOauth: { accessToken: "fixture-claude" } }),
);
await writeFile(
path.join(root, ".codex", "auth.json"),
JSON.stringify({ tokens: { access_token: "fixture-codex", account_id: "fixture-account" } }),
);
try {
await promisify(execFile)(
process.execPath,
[
"--import",
"tsx",
fileURLToPath(new URL("./test-fixtures/usage-proxy-daemon.ts", import.meta.url)),
mode,
],
{
timeout: 45_000,
maxBuffer: 1024 * 1024,
env: {
...process.env,
HOME: root,
USERPROFILE: root,
CODEX_HOME: path.join(root, ".codex"),
CLAUDE_CONFIG_DIR: path.join(root, ".claude"),
NODE_OPTIONS: `--require=${JSON.stringify(guard.replaceAll("\\", "/"))}`,
https_proxy: `http://127.0.0.1:${address.port}`,
no_proxy: "",
NO_PROXY: "",
},
},
);
expect(tunnels).toContain("api.anthropic.com:443");
expect(tunnels).toContain("chatgpt.com:443");
} finally {
proxy.closeAllConnections();
await new Promise<void>((resolve) => proxy.close(() => resolve()));
await rm(root, { recursive: true, force: true });
}
},
60_000,
);
@@ -2,6 +2,7 @@
import { WebSocket } from "ws";
import type pino from "pino";
import { buildRelayWebSocketUrl } from "@getpaseo/protocol/daemon-endpoints";
import { webSocketProxyAgent } from "./network/index.js";
import type { ExternalSocketMetadata } from "./websocket-server.js";
export interface RelayTransportOptions {
@@ -56,7 +57,7 @@ const RELAY_WEBSOCKET_OPTIONS = {
} as const;
function createDefaultRelayWebSocket(url: string): RelayWebSocketLike {
return new WebSocket(url, RELAY_WEBSOCKET_OPTIONS);
return new WebSocket(url, { ...RELAY_WEBSOCKET_OPTIONS, agent: webSocketProxyAgent(url) });
}
function isRecord(value: unknown): value is Record<string, unknown> {
+1
View File
@@ -1042,6 +1042,7 @@ export class Session {
logger: this.sessionLogger,
});
this.usageSession = new UsageSession({
isEnabled: () => daemonConfigStore.get().usage?.enabled !== false,
emit: (msg) => this.emit(msg),
runtime: pluginRuntime,
logger: this.sessionLogger,
@@ -15,6 +15,7 @@ test("lists reports from usage sources", async () => {
report: { status: "available" as const, windows: [] },
};
const usage = new UsageSession({
isEnabled: () => true,
emit: (message) => emitted.push(message),
runtime: {
async listUsageReports(options) {
@@ -40,6 +41,7 @@ test("lists reports from usage sources", async () => {
test("surfaces a legacy usage-list failure as an rpc_error envelope", async () => {
const emitted: SessionOutboundMessage[] = [];
const usage = new UsageSession({
isEnabled: () => true,
emit: (message) => emitted.push(message),
runtime: {
async listUsageReports() {
@@ -61,6 +63,7 @@ test("surfaces a legacy usage-list failure as an rpc_error envelope", async () =
test("request failures terminate with an error response and no updates", async () => {
const emitted: SessionOutboundMessage[] = [];
const usage = new UsageSession({
isEnabled: () => true,
emit: (message) => emitted.push(message),
logger: pino({ level: "silent" }),
});
@@ -72,3 +75,36 @@ test("request failures terminate with an error response and no updates", async (
},
]);
});
test("off rejects both protocols before runtime discovery and turning on restores reports", async () => {
let enabled = false;
let calls = 0;
const emitted: SessionOutboundMessage[] = [];
const usage = new UsageSession({
isEnabled: () => enabled,
emit: (message) => emitted.push(message),
logger: pino({ level: "silent" }),
runtime: {
async listUsageReports() {
calls++;
return [];
},
async listLegacyUsage() {
calls++;
return { fetchedAt: "now", providers: [] };
},
},
});
await usage.handleListReports({ type: "usage.list_reports.request", requestId: "off" });
await usage.handleLegacyList({ type: "provider.usage.list.request", requestId: "old" });
expect(calls).toBe(0);
expect(emitted[0]).toMatchObject({ payload: { error: "Usage is off on this host." } });
expect(emitted[1]).toMatchObject({
type: "rpc_error",
payload: { error: "Usage is off on this host." },
});
enabled = true;
await usage.handleListReports({ type: "usage.list_reports.request", requestId: "on" });
expect(calls).toBe(1);
expect(emitted[2]).toMatchObject({ payload: { error: null } });
});
@@ -9,6 +9,7 @@ export interface UsageSessionOptions {
listUsageReports(options: ListUsageReportsOptions): Promise<UsageReportEntry[]>;
listLegacyUsage(): Promise<{ fetchedAt: string; providers: ProviderUsage[] }>;
};
isEnabled: () => boolean;
logger: pino.Logger;
}
@@ -19,6 +20,7 @@ export class UsageSession {
msg: Extract<SessionInboundMessage, { type: "usage.list_reports.request" }>,
): Promise<void> {
try {
if (!this.options.isEnabled()) throw new Error("Usage is off on this host.");
if (!this.options.runtime) throw new Error("Plugin runtime is unavailable");
await this.options.runtime.listUsageReports({
forceRefresh: msg.forceRefresh,
@@ -49,6 +51,18 @@ export class UsageSession {
async handleLegacyList(
msg: Extract<SessionInboundMessage, { type: "provider.usage.list.request" }>,
): Promise<void> {
if (!this.options.isEnabled()) {
this.options.emit({
type: "rpc_error",
payload: {
requestId: msg.requestId,
requestType: msg.type,
error: "Usage is off on this host.",
code: "provider_usage_list_failed",
},
});
return;
}
try {
if (!this.options.runtime) throw new Error("Plugin runtime is unavailable");
const usage = await this.options.runtime.listLegacyUsage();
@@ -1949,6 +1949,7 @@ export class VoiceAssistantWebSocketServer {
hostMultiplexing: true,
// COMPAT(relayProtectedSecurity): added in v0.13.0, remove gate after 2027-04-21.
relayProtectedSecurity: true,
usageSetting: true,
usageSources: true,
ownedSubscriptions: true,
agentRequestReceipts: true,
@@ -536,7 +536,6 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro
const repositoryRoot = fileURLToPath(new URL("../../../../", import.meta.url));
const source = `
import assert from 'node:assert/strict';
import { measureMainThreadWork } from './packages/server/src/test-utils/main-thread-work.ts';
import { write } from 'node:fs';
import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
@@ -580,17 +579,36 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro
const events = Array.from({ length: process.env.GIT_IO_TRACE ? 2 : 10000 }, (_, i) => ({ type: 'update', path: join(i % 2 ? alias : worktree, 'ignored', 'noise') }));
let fsCalls = 0;
const hook = createHook({ init(_id, type) { if (type.startsWith('FSREQ')) fsCalls++; } });
// Collect repository setup and event-fixture garbage before measuring
// the cold filter. Allocations made by the filter still count.
global.gc();
await tick();
const { blockingMs } = await measureMainThreadWork('Git filter main-thread work', async () => {
await marker('FILTER_START');
hook.enable();
try {
callback(null, events);
} finally {
hook.disable();
await marker('FILTER_END');
// Unrelated callbacks must not consume the synchronous filter's budget.
const threadCpuUsage = Reflect.get(process, 'threadCpuUsage');
const unrelatedWork = tick().then(() => {
const started = threadCpuUsage();
while (true) {
const cpu = threadCpuUsage(started);
if (cpu.user + cpu.system >= 80000) break;
}
});
await marker('FILTER_START');
hook.enable();
let blockingMs;
try {
// This callback is synchronous: measure its own span, without waiting
// for marker IO, loader messages or other event-loop callbacks.
const startedAt = performance.now();
const startedCpu = threadCpuUsage();
callback(null, events);
const cpu = threadCpuUsage(startedCpu);
// Cap coarse Windows CPU accounting by elapsed time; exclude descheduling.
blockingMs = Math.min(performance.now() - startedAt, (cpu.user + cpu.system) / 1000);
} finally {
hook.disable();
await marker('FILTER_END');
}
await unrelatedWork;
assert.equal(fsCalls, 0, "filesystem calls");
assert.equal(notifications, 0, "ignored event notification");
assert.ok(blockingMs < 20, 'blocking filter work: ' + blockingMs);
@@ -614,6 +632,7 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro
const { stdout, stderr } = await promisify(execFile)(
process.execPath,
[
"--expose-gc",
"--import",
"tsx",
...(tracing ? ["--trace-sync-io"] : []),
@@ -634,7 +653,9 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro
const output = stderr.split(`${phase}_START\n`)[1]?.split(`${phase}_END\n`)[0];
expect(output, `${phase}: synchronous filesystem IO`).toBe("");
}
expect(JSON.parse(stdout.trim().split("\n")[0])).toMatchObject({ fsCalls: 0 });
const measurement = JSON.parse(stdout.trim().split("\n")[0]);
console.info("Git filter budget", { tracing, ...measurement });
expect(measurement).toMatchObject({ fsCalls: 0 });
}
}, 60_000);
@@ -44,10 +44,14 @@ afterAll(() => {
rmSync(probeDirectory, { recursive: true, force: true });
});
async function measureConfigRead(directory: string) {
const { stdout, stderr } = await promisify(execFile)(process.execPath, [probePath, directory], {
timeout: 15_000,
});
async function measureConfigRead(directory: string, profile = false) {
const { stdout, stderr } = await promisify(execFile)(
process.execPath,
[probePath, directory, profile ? "profile" : "plain"],
{
timeout: 15_000,
},
);
process.stderr.write(stderr);
return JSON.parse(stdout) as {
result: Awaited<ReturnType<typeof readPaseoConfigForEdit>>;
@@ -133,22 +137,29 @@ describe("paseo config file substrate", () => {
expect(blockingMs).toBeLessThan(20);
});
it("keeps main-thread work below 20ms while admitting large configs", async () => {
const config = {
scripts: Object.fromEntries(
Array.from({ length: 7_000 }, (_, i) => [`script${i}`, { command: "echo hi" }]),
),
worktree: { setup: "npm ci" },
};
await writeFile(join(tempDir, "paseo.json"), JSON.stringify(config));
const { result, blockingMs, filesystemRequests, yields, workerMessages } =
await measureConfigRead(tempDir);
expect(result).toEqual({ ok: true, config, revision: await statPaseoConfigPath(tempDir) });
expect(blockingMs).toBeLessThan(20);
expect(filesystemRequests).toBeGreaterThan(0);
expect(yields).toBeGreaterThan(0);
expect(workerMessages).toBe(0);
});
it.each(
Array.from({ length: 150 }, (_, repetition) =>
[false, true].map((profile) => ({ repetition, profile })),
).flat(),
)(
"keeps main-thread work below 20ms while admitting large configs (repetition=$repetition, profile=$profile)",
async ({ profile }) => {
const config = {
scripts: Object.fromEntries(
Array.from({ length: 7_000 }, (_, i) => [`script${i}`, { command: "echo hi" }]),
),
worktree: { setup: "npm ci" },
};
await writeFile(join(tempDir, "paseo.json"), JSON.stringify(config));
const { result, blockingMs, filesystemRequests, yields, workerMessages } =
await measureConfigRead(tempDir, profile);
expect(result).toEqual({ ok: true, config, revision: await statPaseoConfigPath(tempDir) });
expect(blockingMs).toBeLessThan(20);
expect(filesystemRequests).toBeGreaterThan(0);
expect(yields).toBeGreaterThan(0);
expect(workerMessages).toBe(0);
},
);
it("rejects a 32MiB config with main-thread work below 20ms", async () => {
await writeFile(
@@ -1,4 +1,5 @@
import { createHook, executionAsyncResource } from "node:async_hooks";
import { Session } from "node:inspector/promises";
import { MessagePort } from "node:worker_threads";
import assert from "node:assert/strict";
import { setImmediate as nextTurn } from "node:timers/promises";
@@ -17,8 +18,48 @@ const activity = createHook({
if (executionAsyncResource() instanceof MessagePort) workerMessages++;
},
}).enable();
const profiler = process.argv[3] === "profile" ? new Session() : null;
if (profiler) {
profiler.connect();
await profiler.post("Profiler.enable");
await profiler.post("Profiler.setSamplingInterval", { interval: 100 });
await profiler.post("Profiler.start");
}
const measured = await measureMainThreadWork("project config main-thread work", () =>
readPaseoConfigForEdit(directory),
);
activity.disable();
process.stderr.write(`Config profiling: ${Boolean(profiler)}\n`);
const profile = profiler ? (await profiler.post("Profiler.stop")).profile : null;
profiler?.disconnect();
if (profile && measured.blockingMs >= 20) {
const nodes = new Map(profile.nodes.map((node) => [node.id, node]));
const parents = new Map<number, number>();
for (const node of profile.nodes) {
for (const child of node.children ?? []) parents.set(child, node.id);
}
const samples = new Map<number, number>();
for (const [index, id] of (profile.samples ?? []).entries()) {
samples.set(id, (samples.get(id) ?? 0) + (profile.timeDeltas?.[index] ?? 0));
}
const hottest = [...samples]
.sort((a, b) => b[1] - a[1])
.slice(0, 20)
.map(([id, micros]) => {
const frame = nodes.get(id)!.callFrame;
const callers: string[] = [];
let parent = parents.get(id);
while (parent !== undefined && callers.length < 5) {
callers.push(nodes.get(parent)!.callFrame.functionName);
parent = parents.get(parent);
}
return {
function: frame.functionName,
callers,
line: frame.lineNumber,
milliseconds: micros / 1000,
};
});
process.stderr.write(`Config CPU diagnostic: ${JSON.stringify(hottest)}\n`);
}
process.stdout.write(JSON.stringify({ ...measured, workerMessages }));
@@ -70,6 +70,14 @@
},
"additionalProperties": {}
},
"usage": {
"type": "object",
"properties": {
"enabled": {
"type": "boolean"
}
}
},
"browserTools": {
"type": "object",
"properties": {
+148
View File
@@ -557,3 +557,151 @@ index a16dac0..6519858 100644
return ColorScheme.Dark
default:
return ColorScheme.Unspecified
diff --git a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt b/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt
index 0f8d1f0..154a12a 100644
--- a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt
+++ b/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+android.kt
@@ -3,11 +3,16 @@ package com.unistyles
import android.os.Build
import android.content.Context
import android.content.res.Configuration
+import android.content.res.Resources
+import android.os.Handler
+import android.os.Looper
import android.util.DisplayMetrics
import android.view.View
import android.view.WindowManager
import androidx.annotation.Keep
+import androidx.core.content.OnConfigurationChangedProvider
import androidx.core.text.TextUtilsCompat
+import androidx.core.util.Consumer
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
@@ -22,6 +27,7 @@ import com.margelo.nitro.unistyles.Insets
import com.margelo.nitro.unistyles.Orientation
import com.margelo.nitro.unistyles.UnistyleDependency
import com.margelo.nitro.unistyles.UnistylesNativeMiniRuntime
+import java.lang.ref.WeakReference
import java.util.Locale
@Keep
@@ -30,6 +36,14 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext):
private val _insets = NativePlatformInsets(reactContext, this::getMiniRuntime) { this.onConfigChange() }
private var _miniRuntime: UnistylesNativeMiniRuntime = buildMiniRuntime()
private val _listener = NativePlatformListener(reactContext, this::getMiniRuntime) { this.diffMiniRuntime() }
+ private var _configurationProvider: WeakReference<OnConfigurationChangedProvider>? = null
+ private val _activityConfigurationListener = Consumer<Configuration> {
+ Handler(Looper.getMainLooper()).post { this.onConfigChange() }
+ }
+
+ // Application resources can lag behind configuration changes
+ private val configurationResources: Resources
+ get() = reactContext.currentActivity?.resources ?: reactContext.resources
init {
checkEdgeToEdge()
@@ -37,12 +51,16 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext):
}
fun onDestroy() {
+ stopObservingActivityConfiguration()
_listener.onDestroy()
_insets.onDestroy()
reactContext.removeLifecycleEventListener(this)
}
override fun onHostResume() {
+ observeActivityConfiguration()
+ // catch configuration changes missed while no Activity was attached
+ onConfigChange()
_insets.getInitialInsets(false)
_insets.startInsetsListener()
}
@@ -51,7 +69,26 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext):
_insets.stopInsetsListener()
}
- override fun onHostDestroy() {}
+ override fun onHostDestroy() {
+ stopObservingActivityConfiguration()
+ }
+
+ private fun observeActivityConfiguration() {
+ val provider = reactContext.currentActivity as? OnConfigurationChangedProvider
+
+ if (_configurationProvider?.get() === provider) {
+ return
+ }
+
+ stopObservingActivityConfiguration()
+ provider?.addOnConfigurationChangedListener(_activityConfigurationListener)
+ _configurationProvider = provider?.let { WeakReference(it) }
+ }
+
+ private fun stopObservingActivityConfiguration() {
+ _configurationProvider?.get()?.removeOnConfigurationChangedListener(_activityConfigurationListener)
+ _configurationProvider = null
+ }
override val memorySize: Long
get() = 0
@@ -61,7 +98,7 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext):
}
override fun getColorScheme(): ColorScheme {
- val uiMode = reactContext.resources.configuration.uiMode
+ val uiMode = configurationResources.configuration.uiMode
val colorScheme = when (uiMode.and(Configuration.UI_MODE_NIGHT_MASK)) {
Configuration.UI_MODE_NIGHT_YES -> ColorScheme.DARK
@@ -73,15 +110,15 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext):
}
override fun getFontScale(): Double {
- return reactContext.resources.configuration.fontScale.toDouble()
+ return configurationResources.configuration.fontScale.toDouble()
}
override fun getPixelRatio(): Double {
- return reactContext.resources.displayMetrics.density.toDouble()
+ return configurationResources.displayMetrics.density.toDouble()
}
override fun getOrientation(): Orientation {
- val orientation = when (reactContext.resources.configuration.orientation) {
+ val orientation = when (configurationResources.configuration.orientation) {
Configuration.ORIENTATION_PORTRAIT -> Orientation.PORTRAIT
Configuration.ORIENTATION_LANDSCAPE -> Orientation.LANDSCAPE
else -> Orientation.PORTRAIT
@@ -122,7 +159,7 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext):
return Dimensions(screenWidth, screenHeight)
}
else -> {
- val displayMetrics = reactContext.resources.displayMetrics
+ val displayMetrics = configurationResources.displayMetrics
reactContext.currentActivity?.windowManager?.currentWindowMetrics?.bounds?.let {
val boundsWidth = (it.width() / displayMetrics.density).toDouble()
@@ -157,7 +194,7 @@ class NativePlatformAndroid(private val reactContext: ReactApplicationContext):
"com.facebook.react.modules.i18nmanager.I18nUtil",
Context.MODE_PRIVATE
)
- val resourcesLocale = reactContext.resources.configuration.locales[0]
+ val resourcesLocale = configurationResources.configuration.locales[0]
val hasForcedRtl = sharedPrefs.getBoolean("RCTI18nUtil_forceRTL", false)
// user preferences
val isRtl = TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == ViewCompat.LAYOUT_DIRECTION_RTL
diff --git a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+insets.kt b/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+insets.kt
index a9c1804..f5a3c20 100644
--- a/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+insets.kt
+++ b/node_modules/react-native-unistyles/android/src/main/java/com/unistyles/NativePlatform+insets.kt
@@ -38,7 +38,7 @@ class NativePlatformInsets(
}
fun getInsets(): Insets {
- val density = reactContext.resources.displayMetrics.density
+ val density = (reactContext.currentActivity?.resources ?: reactContext.resources).displayMetrics.density
return Insets(
this._insets.top / density,
+2
View File
@@ -26,6 +26,8 @@ const patchedPackages = [
// https://github.com/jpudysz/react-native-unistyles/pull/1203.
// Adaptive themes: keep until colorScheme reads no longer consume listener-owned media changes.
// withUnistyles: also keep the uniProps filter until upstream consumes its control prop.
// Android configuration: backport 3.5.3; remove the two NativePlatform hunks at >= 3.5.3.
// https://github.com/jpudysz/react-native-unistyles/compare/v3.5.2...v3.5.3
{
nodeModulesPath: "node_modules/react-native-unistyles",
patchPrefix: "react-native-unistyles+",