Compare commits

..
Author SHA1 Message Date
Mohamed Boudra bce306238b fix(server): keep a gotgenes foreground answer on replay
A foreground @gotgenes/pi-subagents child finds its session file only
through the live runtime marker, which history does not keep. Without a
file, emit the spawn result text as the child's assistant message.
2026-10-30 12:01:23 +01:00
Mohamed Boudra c1bcfd930b fix(server): settle child compactions and keep sub-agent cards stable
- Codex: a child compaction shown as loading now completes on the
  child's thread/compacted or turn end, once.
- Claude: a streamed child tool call's empty start input is a
  placeholder, so the assistant message's input reaches its card.
- OMP: the task card follows only its first child, so later children
  no longer re-send an unchanged card.
2026-10-30 11:47:33 +01:00
Mohamed Boudra 6953ba6506 fix(server): put a tintinweb foreground answer in the child timeline
A foreground @tintinweb/pi-subagents child has no session file, so its
answer only exists in the Agent tool result. Emit that text as the
child's assistant message when the child finishes. Tag every sub_agent
producer's `log: ""` with COMPAT(subagent-log) so the shim removal
finds them.
2026-10-30 09:49:51 +01:00
Mohamed Boudra a68a0c2c5f fix: make sub-agent cards launch markers
Sub-agent tool calls no longer accumulate the child's activity into
`log`. Claude, Codex, OpenCode, OMP and Pi emit the card when the child
starts and when its label or status changes; the child's messages and
tool calls stay in the sub-agent's own timeline. The app no longer
renders a sub-agent log.

The wire schema makes `log` optional. Daemons still send `log: ""` so
apps that require the field keep parsing the card.
2026-10-30 08:35:04 +01:00
88 changed files with 403 additions and 2230 deletions
-10
View File
@@ -493,16 +493,6 @@ 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). 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 ## Deployment models
1. **Local daemon** (default): `paseo daemon start` on `127.0.0.1:6767` 1. **Local daemon** (default): `paseo daemon start` on `127.0.0.1:6767`
-1
View File
@@ -38,7 +38,6 @@ 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`). - **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`). - **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`). - **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`. - **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`). - **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`). - **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,20 +35,6 @@ 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. [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 For Android keyboard continuity, run the current checkout in the app, open an idle terminal
with an empty prompt, hide its keyboard, and run: 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. 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.
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. 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 ## Contribute sidebar items
+4 -10
View File
@@ -21,16 +21,10 @@ The invariants are:
> agent establishes the daemon's current tail in one complete-turn request, with older history reachable > agent establishes the daemon's current tail in one complete-turn request, with older history reachable
> through backward pagination. > through backward pagination.
Every item is bounded before it enters either delivery path, because a timeline page is one Tool output is bounded before it enters either delivery path. Canonical shell tool output is sliced
WebSocket message and the daemon closes a socket whose outbound buffer passes 64 MiB. Tool calls get to 64 KiB, and the same bounded item is used for runtime timeline rows and live stream events.
64 KiB and other items 256 KiB. Over budget, the largest strings are cut to a shared length with a Provider history hydration applies the same rule so reopening an agent cannot restore an oversized
`…[truncated 12.3 MB]` marker, and an oversized `data:` URL is replaced by the marker. Strings up tool payload.
to 1 KiB stay whole, so ids and paths survive. Arrays drop their trailing elements without a marker
element, so typed arrays still match the wire schema. Limiting an item twice gives the same item. The
budget does not bound wide objects or multi-byte text. The same
bounded item is used for runtime timeline rows and live stream events. Provider history hydration
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
again to assistant and reasoning rows the projection merges from many chunks.
## Presence is not delivery ## Presence is not delivery
+1 -1
View File
@@ -1 +1 @@
sha256-8NOrrCAxraQ74lP3Vy59MRhloBfzStTc4rW+ltc42Fg= sha256-6C4Rjh0mRVrC9akBVGK0NZaCaLJhwKObT7HrgPmcvyw=
-24
View File
@@ -40690,7 +40690,6 @@
"esbuild": "^0.25.12", "esbuild": "^0.25.12",
"express": "^4.18.2", "express": "^4.18.2",
"fast-deep-equal": "^3.1.3", "fast-deep-equal": "^3.1.3",
"https-proxy-agent": "^7.0.6",
"lru-cache": "^11.5.1", "lru-cache": "^11.5.1",
"markdown-it": "^10.0.0", "markdown-it": "^10.0.0",
"mnemonic-id": "^3.2.7", "mnemonic-id": "^3.2.7",
@@ -40708,7 +40707,6 @@
"strip-ansi": "^7.1.2", "strip-ansi": "^7.1.2",
"tree-kill": "^1.2.2", "tree-kill": "^1.2.2",
"typescript": "^5.9.3", "typescript": "^5.9.3",
"undici": "^7.24.8",
"uuid": "^9.0.1", "uuid": "^9.0.1",
"which": "^5.0.0", "which": "^5.0.0",
"ws": "^8.14.2", "ws": "^8.14.2",
@@ -41282,15 +41280,6 @@
"url": "https://opencollective.com/vitest" "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": { "packages/server/node_modules/ajv": {
"version": "8.20.0", "version": "8.20.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
@@ -41360,19 +41349,6 @@
"@esbuild/win32-x64": "0.25.12" "@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": { "packages/server/node_modules/isexe": {
"version": "3.1.5", "version": "3.1.5",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz",
@@ -1,69 +0,0 @@
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,31 +441,3 @@ test("released hosts supply source logos through the client conversion", async (
).toHaveAttribute("d", codexPath); ).toHaveAttribute("d", codexPath);
await qaScreenshot(page, "released-host-usage-modal"); 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
@@ -1,104 +0,0 @@
// 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,10 +28,6 @@ interface SeedProjectDescriptor {
* prefer those wrappers over reaching for this client directly. * prefer those wrappers over reaching for this client directly.
*/ */
export interface SeedDaemonClient { 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>; connect(): Promise<void>;
close(): Promise<void>; close(): Promise<void>;
addProject(cwd: string): Promise<{ addProject(cwd: string): Promise<{
@@ -25,7 +25,6 @@ interface UsageReportsFixtureOptions {
* app connects, so a reload can switch it. * app connects, so a reload can switch it.
*/ */
usageSupported?: boolean | (() => boolean); usageSupported?: boolean | (() => boolean);
usageSettingSupported?: boolean;
/** Released hosts expose provider.usage.list with no source icons. */ /** Released hosts expose provider.usage.list with no source icons. */
providerUsageListOnly?: boolean; providerUsageListOnly?: boolean;
/** The host daemon's port; defaults to the E2E daemon. */ /** The host daemon's port; defaults to the E2E daemon. */
@@ -64,7 +63,6 @@ function withUsageSupportFeature(
message: WebSocketMessage, message: WebSocketMessage,
enabled: boolean, enabled: boolean,
providerUsageListOnly: boolean, providerUsageListOnly: boolean,
usageSettingSupported: boolean,
): string | null { ): string | null {
const envelope = parseJson(message) as { const envelope = parseJson(message) as {
type?: unknown; type?: unknown;
@@ -88,7 +86,6 @@ function withUsageSupportFeature(
...payload, ...payload,
features: { features: {
...features, ...features,
usageSetting: usageSettingSupported ? true : undefined,
usageSources: enabled && !providerUsageListOnly, usageSources: enabled && !providerUsageListOnly,
providerUsageList: enabled, providerUsageList: enabled,
}, },
@@ -232,12 +229,7 @@ export async function installUsageReportsFixture(
server.onMessage((message) => { server.onMessage((message) => {
const serverInfo = const serverInfo =
typeof message === "string" typeof message === "string"
? withUsageSupportFeature( ? withUsageSupportFeature(message, isUsageSupported(), providerUsageListOnly)
message,
isUsageSupported(),
providerUsageListOnly,
options.usageSettingSupported ?? true,
)
: null; : null;
ws.send(serverInfo ?? message); ws.send(serverInfo ?? message);
}); });
+9 -4
View File
@@ -64,7 +64,12 @@ import { useCloseAgentListGesture } from "@/mobile-panels/gestures";
import { MobilePanelOverlay } from "@/mobile-panels/presentation"; import { MobilePanelOverlay } from "@/mobile-panels/presentation";
import { buildSettingsAddHostRoute, buildSettingsRoute } from "@/utils/host-routes"; import { buildSettingsAddHostRoute, buildSettingsRoute } from "@/utils/host-routes";
import { openHostOverview } from "@/navigation/settings-navigation"; import { openHostOverview } from "@/navigation/settings-navigation";
import { UsageSidebarItem, UsageSidebarRoot, useUsageSummary, useOpenSidebarUsage } from "@/usage"; import {
UsageSidebarItem,
UsageSidebarRoot,
useHasUsageSummary,
useOpenSidebarUsage,
} from "@/usage";
import { SidebarAgentListSkeleton } from "./sidebar-agent-list-skeleton"; import { SidebarAgentListSkeleton } from "./sidebar-agent-list-skeleton";
import { SidebarCalloutSlot } from "./sidebar-callout-slot"; import { SidebarCalloutSlot } from "./sidebar-callout-slot";
import { SidebarWorkspaceList } from "./sidebar-workspace-list"; import { SidebarWorkspaceList } from "./sidebar-workspace-list";
@@ -475,10 +480,10 @@ function SidebarUsageIcon({ label }: { label: string }) {
*/ */
function SidebarFooterRows({ onBeforeNavigate }: { onBeforeNavigate?: () => void }) { function SidebarFooterRows({ onBeforeNavigate }: { onBeforeNavigate?: () => void }) {
const { items } = useSidebarNavItems("footer"); const { items } = useSidebarNavItems("footer");
const usageSummary = useUsageSummary(); const hasUsageSummary = useHasUsageSummary();
const rowsRef = useRef<View | null>(null); const rowsRef = useRef<View | null>(null);
const visibleItems = items.filter( const visibleItems = items.filter(
(item) => item.visible && (item.kind === "plugin" || usageSummary.length > 0), (item) => item.visible && (item.kind === "plugin" || hasUsageSummary),
); );
if (visibleItems.length === 0) return null; if (visibleItems.length === 0) return null;
return ( return (
@@ -494,7 +499,7 @@ function SidebarFooterRows({ onBeforeNavigate }: { onBeforeNavigate?: () => void
onBeforeNavigate={onBeforeNavigate} onBeforeNavigate={onBeforeNavigate}
/> />
) : ( ) : (
<UsageSidebarItem key={item.key} sources={usageSummary} /> <UsageSidebarItem key={item.key} />
), ),
)} )}
</View> </View>
@@ -455,6 +455,10 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
reportError: (error) => { reportError: (error) => {
console.warn("[Session] viewed timeline synchronization failed", { serverId, error }); console.warn("[Session] viewed timeline synchronization failed", { serverId, error });
}, },
schedule: (task, delayMs) => {
const timeout = setTimeout(task, delayMs);
return () => clearTimeout(timeout);
},
}); });
viewedTimelineSyncRef.current = sync; viewedTimelineSyncRef.current = sync;
setViewedTimelineSync(serverId, sync); setViewedTimelineSync(serverId, sync);
@@ -292,10 +292,7 @@ const CATALOG_DATA = [
version: "0.6.13", version: "0.6.13",
iconId: "minimax-code", iconId: "minimax-code",
installLink: "https://agent.minimax.io", installLink: "https://agent.minimax.io",
// `-p <pkg>` names the package and `mcode` names its binary. Without the command: ["npx", "-y", "@minimax-ai/code@0.6.13", "acp"],
// 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", id: "minion-code",
@@ -62,9 +62,7 @@ describe("ACP provider catalog", () => {
expect(findProvider("minimax-code")).toMatchObject({ expect(findProvider("minimax-code")).toMatchObject({
title: "MiniMax Code", title: "MiniMax Code",
version: "0.6.13", version: "0.6.13",
// The package publishes `mcode`, not `code`, so npx needs the package and command: ["npx", "-y", "@minimax-ai/code@0.6.13", "acp"],
// the binary named separately.
command: ["npx", "-y", "-p", "@minimax-ai/code@0.6.13", "mcode", "acp"],
}); });
expect(findProvider("minimax-code").iconSvg).toContain("<svg"); expect(findProvider("minimax-code").iconSvg).toContain("<svg");
}); });
@@ -422,23 +422,6 @@ describe("deriveAgentScreenViewState", () => {
expect(result.memory.lastReadyAgent).toBeNull(); 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", () => { it("renders an archived agent before provider history is initialized", () => {
const result = deriveAgentScreenViewState({ const result = deriveAgentScreenViewState({
input: { input: {
@@ -175,14 +175,10 @@ function resolveAgentScreenSync(args: {
hadInitialSyncFailure: boolean; hadInitialSyncFailure: boolean;
}): AgentScreenReadySyncState { }): AgentScreenReadySyncState {
const { input, hadInitialSyncFailure } = args; const { input, hadInitialSyncFailure } = args;
if ( if (input.isArchived) {
input.isArchived &&
input.visibilityCatchUpStatus !== "error" &&
input.visibilityCatchUpStatus !== "retrying"
) {
return { status: "idle" }; return { status: "idle" };
} }
if (!input.isConnected && !input.isArchived) { if (!input.isConnected) {
return { status: "reconnecting" }; return { status: "reconnecting" };
} }
if (input.missingAgentState.kind === "error") { if (input.missingAgentState.kind === "error") {
-5
View File
@@ -2091,11 +2091,6 @@ export const ar: TranslationResources = {
}, },
}, },
providerUsage: { providerUsage: {
checkUsage: "التحقق من الاستخدام",
checkUsageHint: "ينطبق على {{host}} على جميع الأجهزة",
off: "التحقق من الاستخدام متوقف على {{host}}.",
turnOn: "تشغيل",
options: "الإعدادات", options: "الإعدادات",
refreshFailed: "تعذّر تحديث الاستخدام", refreshFailed: "تعذّر تحديث الاستخدام",
noHosts: "لا توجد مضيفات متصلة", noHosts: "لا توجد مضيفات متصلة",
-5
View File
@@ -2116,11 +2116,6 @@ export const en = {
}, },
}, },
providerUsage: { providerUsage: {
checkUsage: "Check usage",
checkUsageHint: "Applies to {{host}} on every device",
off: "Usage is off on {{host}}.",
turnOn: "Turn on",
options: "Settings", options: "Settings",
refreshFailed: "Unable to refresh usage", refreshFailed: "Unable to refresh usage",
noHosts: "No connected hosts", noHosts: "No connected hosts",
-5
View File
@@ -2139,11 +2139,6 @@ export const es: TranslationResources = {
}, },
}, },
providerUsage: { 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", options: "Configuración",
refreshFailed: "No se pudo actualizar el uso", refreshFailed: "No se pudo actualizar el uso",
noHosts: "No hay hosts conectados", noHosts: "No hay hosts conectados",
-5
View File
@@ -2139,11 +2139,6 @@ export const fr: TranslationResources = {
}, },
}, },
providerUsage: { 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", options: "Paramètres",
refreshFailed: "Impossible d’actualiser l’utilisation", refreshFailed: "Impossible d’actualiser l’utilisation",
noHosts: "Aucun hôte connecté", noHosts: "Aucun hôte connecté",
-5
View File
@@ -2112,11 +2112,6 @@ export const ja: TranslationResources = {
}, },
}, },
providerUsage: { providerUsage: {
checkUsage: "使用状況を確認",
checkUsageHint: "すべてのデバイスで {{host}} に適用",
off: "{{host}} の使用状況確認はオフです。",
turnOn: "オンにする",
options: "設定", options: "設定",
refreshFailed: "使用状況を更新できません", refreshFailed: "使用状況を更新できません",
noHosts: "接続中のホストがありません", noHosts: "接続中のホストがありません",
-5
View File
@@ -2101,11 +2101,6 @@ export const ko: TranslationResources = {
}, },
}, },
providerUsage: { providerUsage: {
checkUsage: "사용량 확인",
checkUsageHint: "모든 기기에서 {{host}}에 적용",
off: "{{host}}의 사용량 확인이 꺼져 있습니다.",
turnOn: "켜기",
options: "설정", options: "설정",
refreshFailed: "사용량을 새로 고칠 수 없습니다", refreshFailed: "사용량을 새로 고칠 수 없습니다",
noHosts: "연결된 호스트가 없습니다", noHosts: "연결된 호스트가 없습니다",
-5
View File
@@ -2124,11 +2124,6 @@ export const ptBR: TranslationResources = {
}, },
}, },
providerUsage: { 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", options: "Configurações",
refreshFailed: "Não foi possível atualizar o uso", refreshFailed: "Não foi possível atualizar o uso",
noHosts: "Nenhum host conectado", noHosts: "Nenhum host conectado",
-5
View File
@@ -2124,11 +2124,6 @@ export const ru: TranslationResources = {
}, },
}, },
providerUsage: { providerUsage: {
checkUsage: "Проверять использование",
checkUsageHint: "Применяется к {{host}} на всех устройствах",
off: "Проверка использования отключена на {{host}}.",
turnOn: "Включить",
options: "Настройки", options: "Настройки",
refreshFailed: "Не удалось обновить использование", refreshFailed: "Не удалось обновить использование",
noHosts: "Нет подключённых хостов", noHosts: "Нет подключённых хостов",
-5
View File
@@ -2069,11 +2069,6 @@ export const zhCN: TranslationResources = {
}, },
}, },
providerUsage: { providerUsage: {
checkUsage: "检查用量",
checkUsageHint: "在所有设备上应用于 {{host}}",
off: "{{host}} 的用量检查已关闭。",
turnOn: "开启",
options: "设置", options: "设置",
refreshFailed: "无法刷新用量", refreshFailed: "无法刷新用量",
noHosts: "没有已连接的主机", noHosts: "没有已连接的主机",
@@ -174,6 +174,7 @@ it("feeds restored layout to timeline sync as a release signal, not a subscripti
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }), fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
onCatchUpEnded: () => undefined, onCatchUpEnded: () => undefined,
reportError: () => undefined, reportError: () => undefined,
schedule: () => () => undefined,
}); });
// The edge session-context.tsx owns. Pointing it at subscription instead would resume every // The edge session-context.tsx owns. Pointing it at subscription instead would resume every
// agent behind a restored tab on the daemon. // agent behind a restored tab on the daemon.
@@ -57,6 +57,7 @@ function createOwner(storage: TimelineReplicaStorage): ViewedTimelineOwner {
fetchPage: async () => ({ hasNewer: false, endCursor: null }), fetchPage: async () => ({ hasNewer: false, endCursor: null }),
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }), fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
reportError: () => undefined, reportError: () => undefined,
schedule: () => () => undefined,
}, },
}); });
} }
@@ -616,6 +617,7 @@ describe("create handoff lifetime", () => {
}, },
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }), fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
reportError: () => undefined, reportError: () => undefined,
schedule: () => () => undefined,
}, },
}); });
@@ -90,7 +90,7 @@ test("visible catch-up settles before hidden open chats start fetching", async (
world.sync.dispose(); world.sync.dispose();
}); });
test("a failed visible catch-up releases hidden chats without bypassing its error", async () => { test("a failed visible catch-up releases hidden chats without bypassing its retry delay", async () => {
const world = new TimelineWorld(); const world = new TimelineWorld();
world.openedEarlier(["a-hidden"]); world.openedEarlier(["a-hidden"]);
world.sync.replaceVisibleAgentIds("pane", ["z-visible"]); world.sync.replaceVisibleAgentIds("pane", ["z-visible"]);
@@ -103,7 +103,7 @@ test("a failed visible catch-up releases hidden chats without bypassing its erro
hidden.respond({ hasNewer: false }); hidden.respond({ hasNewer: false });
await world.nextError(); await world.nextError();
world.expectNoPendingFetch(); world.expectNoPendingFetch();
world.sync.retryVisibleAgentTimeline("z-visible"); (await world.nextRetry())();
(await world.nextFetch("z-visible")).respond({ hasNewer: false }); (await world.nextFetch("z-visible")).respond({ hasNewer: false });
world.sync.dispose(); world.sync.dispose();
}); });
@@ -200,6 +200,20 @@ class TimelineWorld {
const waiter = this.errorWaiters.shift(); const waiter = this.errorWaiters.shift();
if (waiter) waiter(this.errors.at(-1) ?? ""); 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 { show(sourceId: string, agentIds: string[]): void {
@@ -221,6 +235,12 @@ class TimelineWorld {
}> = []; }> = [];
private readonly errorWaiters: Array<(message: string) => void> = []; private readonly errorWaiters: Array<(message: string) => void> = [];
private readonly cacheRequestWaiters: Array<(agentId: 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 { get pendingFetchCount(): number {
return this.fetches.length; return this.fetches.length;
} }
@@ -280,6 +300,22 @@ class TimelineWorld {
return new Promise((resolve) => this.errorWaiters.push(resolve)); 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 { private releaseMembershipWaiter(): void {
const waiter = this.membershipWaiters.shift(); const waiter = this.membershipWaiters.shift();
if (!waiter) return; if (!waiter) return;
@@ -447,28 +483,6 @@ test("reports a chat current only once its parked follow-up page completes", asy
world.sync.dispose(); 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 () => { test("reports a chat current once the latest-tail fallback replaces an overflowing catch-up", async () => {
const world = new TimelineWorld(); const world = new TimelineWorld();
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 42 }); world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 42 });
@@ -766,21 +780,6 @@ test("overlapping sources deduplicate membership and retain open hidden chats",
world.expectNoPendingFetch(); 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 () => { test("a failed catch-up reports once and retries through the explicit retry policy", async () => {
const world = new TimelineWorld(); const world = new TimelineWorld();
world.sync.setConnected(true); world.sync.setConnected(true);
@@ -789,12 +788,12 @@ test("a failed catch-up reports once and retries through the explicit retry poli
membership.succeed(); membership.succeed();
const failed = await world.nextFetch("agent-a"); const failed = await world.nextFetch("agent-a");
failed.fail("timeline unavailable"); failed.fail("timeline unavailable");
const error = await world.nextError(); const [error, retryCatchUp] = await Promise.all([world.nextError(), world.nextRetry()]);
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
world.sync.retryVisibleAgentTimeline("agent-a"); retryCatchUp();
const retry = await world.nextFetch("agent-a"); const retry = await world.nextFetch("agent-a");
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying"); expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
retry.respond({ hasNewer: false }); retry.respond({ hasNewer: false });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
@@ -805,6 +804,35 @@ test("a failed catch-up reports once and retries through the explicit retry poli
world.expectNoPendingMembership(); 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 () => { test("manual retries can immediately re-attempt a failed catch-up", async () => {
const world = new TimelineWorld(); const world = new TimelineWorld();
world.sync.setConnected(true); world.sync.setConnected(true);
@@ -814,7 +842,7 @@ test("manual retries can immediately re-attempt a failed catch-up", async () =>
const failed = await world.nextFetch("agent-a"); const failed = await world.nextFetch("agent-a");
failed.fail("timeline unavailable"); failed.fail("timeline unavailable");
await world.nextError(); await world.nextRetry();
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
world.sync.retryVisibleAgentTimeline("agent-a"); world.sync.retryVisibleAgentTimeline("agent-a");
@@ -825,7 +853,7 @@ test("manual retries can immediately re-attempt a failed catch-up", async () =>
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
}); });
test("redeclaring unchanged visibility does not bypass catch-up error", async () => { test("redeclaring unchanged visibility does not bypass catch-up backoff", async () => {
const world = new TimelineWorld(); const world = new TimelineWorld();
world.sync.setConnected(true); world.sync.setConnected(true);
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
@@ -834,11 +862,9 @@ test("redeclaring unchanged visibility does not bypass catch-up error", async ()
const failed = await world.nextFetch("agent-a"); const failed = await world.nextFetch("agent-a");
failed.fail("timeline unavailable"); failed.fail("timeline unavailable");
await world.nextError(); await world.nextRetry();
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
world.sync.setActive(false);
world.sync.setActive(true);
world.expectNoPendingMembership(); world.expectNoPendingMembership();
world.expectNoPendingFetch(); world.expectNoPendingFetch();
@@ -854,7 +880,7 @@ test("a manual retry that fails returns to the error state", async () => {
const failed = await world.nextFetch("agent-a"); const failed = await world.nextFetch("agent-a");
failed.fail("timeline unavailable"); failed.fail("timeline unavailable");
await world.nextError(); await world.nextRetry();
world.sync.retryVisibleAgentTimeline("agent-a"); world.sync.retryVisibleAgentTimeline("agent-a");
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying"); expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying");
@@ -917,34 +943,20 @@ test("repeated recovery for the same running gap reuses the in-flight fetch", as
gapPage.respond({ hasNewer: false }); gapPage.respond({ hasNewer: false });
}); });
test("failed membership does not schedule a retry", async () => { test("membership failure autonomously retries without another visibility declaration", 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(); const world = new TimelineWorld();
world.sync.setConnected(true); world.sync.setConnected(true);
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
const failed = await world.nextMembership(); const failed = await world.nextMembership();
failed.fail("subscription unavailable"); failed.fail("subscription unavailable");
const error = await world.nextError(); const [error, retryMembership] = await Promise.all([world.nextError(), world.nextRetry()]);
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
world.sync.retryVisibleAgentTimeline("agent-a"); retryMembership();
const retry = await world.nextMembership(); const retry = await world.nextMembership();
retry.succeed(); retry.succeed();
const catchUp = await world.nextFetch("agent-a"); const catchUp = await world.nextFetch("agent-a");
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("retrying"); expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error");
catchUp.respond({ hasNewer: false }); catchUp.respond({ hasNewer: false });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready")); await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
@@ -955,68 +967,44 @@ test("membership failure waits for manual retry", async () => {
}); });
}); });
test("retrying membership restores a previously loaded chat", async () => { test("membership failures retry with exponential backoff", async () => {
const world = new TimelineWorld(); const world = new TimelineWorld();
world.sync.setConnected(true); world.sync.setConnected(true);
world.show("workspace", ["agent-a"]); world.sync.replaceVisibleAgentIds("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("a fetch that finishes after membership failure cannot clear the error", async () => { const first = await world.nextMembership();
const world = new TimelineWorld(); first.fail("subscription unavailable");
world.sync.setConnected(true); const [firstError, retryAfterFirstFailure] = await Promise.all([
world.show("workspace", ["agent-a"]); world.nextError(),
(await world.nextMembership()).succeed(); world.nextRetry(),
const inFlight = await world.nextFetch("agent-a"); ]);
world.show("workspace", ["agent-b"]); expect(firstError).toBe("subscription unavailable");
(await world.nextMembership()).fail("subscription unavailable");
await world.nextError(); retryAfterFirstFailure();
inFlight.respond({ hasNewer: false }); const second = await world.nextMembership();
await Promise.resolve(); second.fail("subscription unavailable again");
await Promise.resolve();
const retryAfterSecondFailure = await world.nextRetry(2_000);
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("error"); 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 });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
}); });
test("a failed membership retry returns to error", async () => { test("redeclaring unchanged visibility does not bypass membership backoff", 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(); const world = new TimelineWorld();
world.sync.setConnected(true); world.sync.setConnected(true);
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
const failed = await world.nextMembership(); const failed = await world.nextMembership();
failed.fail("subscription unavailable"); failed.fail("subscription unavailable");
await world.nextError(); await world.nextRetry();
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
world.sync.setActive(false);
world.sync.setActive(true);
world.expectNoPendingMembership(); world.expectNoPendingMembership();
world.expectNoPendingFetch(); world.expectNoPendingFetch();
@@ -1062,6 +1050,7 @@ test("backgrounding preserves subscriptions and returning verifies the visible c
world.sync.setActive(false); world.sync.setActive(false);
world.expectNoPendingMembership(); world.expectNoPendingMembership();
world.elapse(60_000);
world.sync.setActive(true); world.sync.setActive(true);
world.expectNoPendingMembership(); world.expectNoPendingMembership();
@@ -1078,10 +1067,11 @@ test("stale membership retry cannot overwrite a newer effective set", async () =
world.show("workspace", ["agent-a"]); world.show("workspace", ["agent-a"]);
const failed = await world.nextMembership(); const failed = await world.nextMembership();
failed.fail("subscription unavailable"); failed.fail("subscription unavailable");
await world.nextError(); const staleRetry = await world.nextRetry();
world.show("workspace", ["agent-b"]); world.show("workspace", ["agent-b"]);
const current = await world.nextMembership(); const current = await world.nextMembership();
staleRetry();
current.succeed(); current.succeed();
const agentB = await world.nextFetch("agent-b"); const agentB = await world.nextFetch("agent-b");
agentB.respond({ hasNewer: false }); agentB.respond({ hasNewer: false });
@@ -1098,9 +1088,10 @@ test("membership retry cannot run while disconnected", async () => {
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]); world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
const failed = await world.nextMembership(); const failed = await world.nextMembership();
failed.fail("subscription unavailable"); failed.fail("subscription unavailable");
await world.nextError(); const disconnectedRetry = await world.nextRetry();
world.sync.setConnected(false); world.sync.setConnected(false);
disconnectedRetry();
world.expectNoPendingMembership(); world.expectNoPendingMembership();
world.sync.setConnected(true); world.sync.setConnected(true);
const restored = await world.nextMembership(); const restored = await world.nextMembership();
@@ -1127,6 +1118,7 @@ test("returning to an open hidden agent stays live after inactivity", async () =
agentBCatchUp.respond({ hasNewer: false }); agentBCatchUp.respond({ hasNewer: false });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-b")).toBe("ready")); await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-b")).toBe("ready"));
world.elapse(60_000);
world.show("workspace", ["agent-a"]); world.show("workspace", ["agent-a"]);
world.expectNoPendingMembership(); world.expectNoPendingMembership();
@@ -329,6 +329,7 @@ export interface ViewedTimelineSyncPorts {
*/ */
onCatchUpEnded(agentId: string): void; onCatchUpEnded(agentId: string): void;
reportError(error: unknown): void; reportError(error: unknown): void;
schedule(task: () => void, delayMs: number): () => void;
} }
export type ViewedTimelineStatus = "ready" | "pending" | "error" | "retrying"; export type ViewedTimelineStatus = "ready" | "pending" | "error" | "retrying";
@@ -422,14 +423,26 @@ export function createViewedTimelineOwner(input: {
}; };
} }
const RETRY_DELAY_MS = 1_000;
const MAX_RETRY_DELAY_MS = 30_000;
type CatchUpStatus = "running" | "complete" | "error"; type CatchUpStatus = "running" | "complete" | "error";
interface CatchUpState { interface CatchUpState {
generation: number; generation: number;
status: CatchUpStatus; status: CatchUpStatus;
request?: ProjectedTimelineForwardFetchPlan; 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( function isSameCatchUpRequest(
left: ProjectedTimelineForwardFetchPlan | undefined, left: ProjectedTimelineForwardFetchPlan | undefined,
right: ProjectedTimelineForwardFetchPlan | undefined, right: ProjectedTimelineForwardFetchPlan | undefined,
@@ -459,7 +472,9 @@ function decideCatchUp(input: {
} }
return "replace"; return "replace";
} }
return "keep"; return input.current.status === "running" || input.current.status === "complete"
? "keep"
: "replace";
} }
function normalizeAgentIds(agentIds: string[]): string[] { function normalizeAgentIds(agentIds: string[]): string[] {
@@ -479,7 +494,8 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
const pendingCatchUps = new Map<string, ProjectedTimelineForwardFetchPlan>(); const pendingCatchUps = new Map<string, ProjectedTimelineForwardFetchPlan>();
const visibilityCatchUpPending = new Set<string>(); const visibilityCatchUpPending = new Set<string>();
const visibilityCatchUpErrors = new Map<string, string>(); const visibilityCatchUpErrors = new Map<string, string>();
// A user-initiated retry owes a pending state until it settles. // User-initiated retries only. Background retries stay silent; a retry the user asked for
// owes them a pending state until it settles.
const manualRetries = new Set<string>(); const manualRetries = new Set<string>();
const loadedCache = new Set<string>(); const loadedCache = new Set<string>();
const cacheLoads = new Map<string, Promise<void>>(); const cacheLoads = new Map<string, Promise<void>>();
@@ -495,6 +511,8 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
let acknowledged: string[] = []; let acknowledged: string[] = [];
let membershipGeneration = 0; let membershipGeneration = 0;
let membershipNeedsRetry = false; 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 // 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. // subscribed — and never resumed on the daemon — until the user actually opens it.
// Membership then survives hiding, workspace switches, backgrounding and reconnect; // Membership then survives hiding, workspace switches, backgrounding and reconnect;
@@ -545,6 +563,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
const cancelCatchUp = (agentId: string) => { const cancelCatchUp = (agentId: string) => {
catchUpGenerations.set(agentId, (catchUpGenerations.get(agentId) ?? 0) + 1); catchUpGenerations.set(agentId, (catchUpGenerations.get(agentId) ?? 0) + 1);
catchUps.get(agentId)?.cancelRetry?.();
catchUps.delete(agentId); catchUps.delete(agentId);
pendingCatchUps.delete(agentId); pendingCatchUps.delete(agentId);
}; };
@@ -588,7 +607,19 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
setVisibilityCatchUpReady(agentId); setVisibilityCatchUpReady(agentId);
} catch (error) { } catch (error) {
if (catchUps.get(agentId)?.generation === generation) { if (catchUps.get(agentId)?.generation === generation) {
catchUps.set(agentId, { generation, status: "error", request }); 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,
});
setVisibilityCatchUpError([agentId], error); setVisibilityCatchUpError([agentId], error);
ports.reportError(error); ports.reportError(error);
} }
@@ -655,9 +686,17 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
if (decision === "keep") { if (decision === "keep") {
return; return;
} }
current?.cancelRetry?.();
const generation = (catchUpGenerations.get(agentId) ?? 0) + 1; const generation = (catchUpGenerations.get(agentId) ?? 0) + 1;
catchUpGenerations.set(agentId, generation); catchUpGenerations.set(agentId, generation);
catchUps.set(agentId, { generation, status: "running", request: nextRequest }); const retryDelayMs =
supersede || current?.status !== "error" ? undefined : current.retryDelayMs;
catchUps.set(agentId, {
generation,
status: "running",
request: nextRequest,
retryDelayMs,
});
pendingCatchUps.delete(agentId); pendingCatchUps.delete(agentId);
void fetchUntilCurrent( void fetchUntilCurrent(
agentId, agentId,
@@ -676,7 +715,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
for (const agentId of ordered) { for (const agentId of ordered) {
const pendingCatchUp = pendingCatchUps.get(agentId); const pendingCatchUp = pendingCatchUps.get(agentId);
const current = catchUps.get(agentId); const current = catchUps.get(agentId);
// Completion of a different chat must not bypass a failed chat's error or // Completion of a different chat must not bypass a failed chat's backoff or
// supersede an in-flight tail that owns its parked gap recovery. // supersede an in-flight tail that owns its parked gap recovery.
if (current && !(current.status === "complete" && pendingCatchUp)) continue; if (current && !(current.status === "complete" && pendingCatchUp)) continue;
startCatchUp(agentId, { startCatchUp(agentId, {
@@ -702,31 +741,42 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
} catch (error) { } catch (error) {
if (disposed || !connected || generation !== membershipGeneration) return; if (disposed || !connected || generation !== membershipGeneration) return;
membershipNeedsRetry = true; membershipNeedsRetry = true;
acknowledged = [];
for (const agentId of requested) cancelCatchUp(agentId);
setVisibilityCatchUpError(requested, error); 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); ports.reportError(error);
return; return;
} }
if (disposed || !connected || generation !== membershipGeneration) return; if (disposed || !connected || generation !== membershipGeneration) return;
cancelMembershipRetry?.();
cancelMembershipRetry = null;
membershipRetryDelayMs = undefined;
acknowledged = requested; acknowledged = requested;
startAcknowledgedCatchUps(); startAcknowledgedCatchUps();
}; };
const retryVisibleAgentTimeline = (agentId: string) => { const retryVisibleAgentTimeline = (agentId: string) => {
if (!connected || !isDesired(agentId) || manualRetries.has(agentId)) return; if (!isDesired(agentId) || manualRetries.has(agentId)) return;
const catchUp = catchUps.get(agentId); const catchUp = catchUps.get(agentId);
const membershipRetryable = membershipNeedsRetry && connected; const membershipRetryable = membershipNeedsRetry && connected;
if (catchUp?.status !== "error" && !membershipRetryable) return; if (catchUp?.status !== "error" && !membershipRetryable) return;
manualRetries.add(agentId); manualRetries.add(agentId);
notifyListeners(); notifyListeners();
if (membershipRetryable) { if (catchUp?.status === "error") {
void reconcileMembership(); catchUp.cancelRetry?.();
startCatchUp(agentId, { request: catchUp.request, supersede: true });
return; return;
} }
if (catchUp?.status === "error") { cancelMembershipRetry?.();
startCatchUp(agentId, { request: catchUp.request, supersede: true }); cancelMembershipRetry = null;
} membershipRetryDelayMs = undefined;
void reconcileMembership();
}; };
const commitDesiredMembership = ( const commitDesiredMembership = (
@@ -767,6 +817,8 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
ensureCacheLoaded(agentId); ensureCacheLoaded(agentId);
} }
} }
cancelMembershipRetry?.();
cancelMembershipRetry = null;
desired = nextDesired; desired = nextDesired;
ports.replaceDemandedAgentIds(desired); ports.replaceDemandedAgentIds(desired);
membershipGeneration += 1; membershipGeneration += 1;
@@ -817,7 +869,6 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
return; return;
} }
for (const agentId of visibleAgentIds()) { for (const agentId of visibleAgentIds()) {
if (visibilityCatchUpErrors.has(agentId)) continue;
visibilityCatchUpPending.add(agentId); visibilityCatchUpPending.add(agentId);
visibilityCatchUpErrors.delete(agentId); visibilityCatchUpErrors.delete(agentId);
startCatchUp(agentId, { supersede: true }); startCatchUp(agentId, { supersede: true });
@@ -829,6 +880,9 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
connected = nextConnected; connected = nextConnected;
if (!connected) { if (!connected) {
commitDesiredMembership(desired, { resetCatchUpStatus: true }); commitDesiredMembership(desired, { resetCatchUpStatus: true });
cancelMembershipRetry?.();
cancelMembershipRetry = null;
membershipRetryDelayMs = undefined;
void observation?.handle.release().catch(ports.reportError); void observation?.handle.release().catch(ports.reportError);
observation = null; observation = null;
acknowledged = []; acknowledged = [];
@@ -840,7 +894,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
void reconcileMembership(); void reconcileMembership();
}, },
recoverGap(agentId, cursor) { recoverGap(agentId, cursor) {
if (!isDesired(agentId) || catchUps.get(agentId)?.status === "error") return; if (!isDesired(agentId)) return;
startCatchUp(agentId, { startCatchUp(agentId, {
request: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }), request: planTimelineCatchUpAfter({ epoch: cursor.epoch, seq: cursor.endSeq }),
supersede: true, supersede: true,
@@ -850,7 +904,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
disposed = true; disposed = true;
void observation?.handle.release().catch(ports.reportError); void observation?.handle.release().catch(ports.reportError);
observation = null; observation = null;
cancelMembershipRetry?.();
cancelMembershipRetry = null;
membershipNeedsRetry = false; membershipNeedsRetry = false;
membershipRetryDelayMs = undefined;
sources.clear(); sources.clear();
membershipGeneration += 1; membershipGeneration += 1;
for (const agentId of desired) cancelCatchUp(agentId); for (const agentId of desired) cancelCatchUp(agentId);
+3 -10
View File
@@ -21,12 +21,10 @@ export interface UsageHostSelection {
*/ */
export function UsageControls({ export function UsageControls({
view, view,
serverId,
onRefresh, onRefresh,
hostSelection, hostSelection,
}: { }: {
view: UsageView; view: UsageView;
serverId: string;
onRefresh: () => void; onRefresh: () => void;
hostSelection?: UsageHostSelection; hostSelection?: UsageHostSelection;
}) { }) {
@@ -45,8 +43,8 @@ export function UsageControls({
) : null} ) : null}
{view.kind === "unavailable" ? null : ( {view.kind === "unavailable" ? null : (
<> <>
{view.kind === "off" ? null : <UsageRefreshButton busy={busy} onRefresh={onRefresh} />} <UsageRefreshButton busy={busy} onRefresh={onRefresh} />
<UsageOptions serverId={serverId} /> <UsageOptions />
</> </>
)} )}
</View> </View>
@@ -86,12 +84,7 @@ export function useHostUsageWithControls(hostSelection: UsageHostSelection): {
const controls = useMemo( const controls = useMemo(
() => () =>
hasControls ? ( hasControls ? (
<UsageControls <UsageControls view={view} onRefresh={refresh} hostSelection={hostSelection} />
serverId={hostSelection.serverId}
view={view}
onRefresh={refresh}
hostSelection={hostSelection}
/>
) : null, ) : null,
[hasControls, hostSelection, refresh, view], [hasControls, hostSelection, refresh, view],
); );
+8
View File
@@ -1,5 +1,7 @@
import { useCallback, useMemo } from "react"; import { useCallback, useMemo } from "react";
import { useAppSettings } from "@/hooks/use-settings"; import { useAppSettings } from "@/hooks/use-settings";
import { useUsageHostId } from "./hosts";
import { useUsageHostReports } from "./queries";
import { import {
isUsagePinned, isUsagePinned,
setUsageDisplayAs, setUsageDisplayAs,
@@ -23,6 +25,12 @@ interface UsagePreferencesState {
display: UsageDisplay; 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. */ /** The device's usage preferences, with pins resolved against the given reports. */
export function useUsageDisplay(reports: readonly UsageReportEntry[]): UsagePreferencesState { export function useUsageDisplay(reports: readonly UsageReportEntry[]): UsagePreferencesState {
const { settings, updateSettings } = useAppSettings(); const { settings, updateSettings } = useAppSettings();
@@ -1,5 +1,5 @@
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useUsageDisplay } from "./display"; import { useUsagePreferences } from "./display";
import { useHostUsage } from "./queries"; import { useHostUsage } from "./queries";
import { UsageSection } from "./usage-section"; import { UsageSection } from "./usage-section";
@@ -7,7 +7,7 @@ import { UsageSection } from "./usage-section";
export function HostUsageSection({ serverId }: { serverId: string }) { export function HostUsageSection({ serverId }: { serverId: string }) {
const { t } = useTranslation(); const { t } = useTranslation();
const { view, refresh } = useHostUsage(serverId); const { view, refresh } = useHostUsage(serverId);
const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []); const { display } = useUsagePreferences(serverId);
return ( return (
<UsageSection <UsageSection
serverId={serverId} serverId={serverId}
+1 -1
View File
@@ -4,6 +4,6 @@ export { useHostReportsUsage } from "./queries";
export { export {
UsageSidebarItem, UsageSidebarItem,
UsageSidebarRoot, UsageSidebarRoot,
useUsageSummary, useHasUsageSummary,
useOpenSidebarUsage, useOpenSidebarUsage,
} from "./sidebar-item"; } from "./sidebar-item";
-12
View File
@@ -405,15 +405,3 @@ it("available and retained usage show the same successful completion time", () =
); );
expect(upsertReport([failure], success)).toEqual([failure]); 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,7 +106,6 @@ export interface UsageQueryState {
export function resolveUsageView( export function resolveUsageView(
input: { input: {
enabled?: boolean;
hostLabel: string; hostLabel: string;
isConnected: boolean; isConnected: boolean;
supportsUsage: boolean; supportsUsage: boolean;
@@ -126,8 +125,6 @@ export function resolveUsageView(
message: t("providerUsage.hostUpgradeRequired", { host: hostLabel }), message: t("providerUsage.hostUpgradeRequired", { host: hostLabel }),
}; };
} }
if (input.enabled === false)
return { kind: "off", message: t("providerUsage.off", { host: hostLabel }) };
if (query?.data) { if (query?.data) {
return { kind: "ready", reports: query.data, isRefreshing: query.isFetching }; return { kind: "ready", reports: query.data, isRefreshing: query.isFetching };
} }
+10 -27
View File
@@ -8,20 +8,15 @@ import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-
import { useIsCompactFormFactor } from "@/constants/layout"; import { useIsCompactFormFactor } from "@/constants/layout";
import { SettingsRow, SettingsSwitch } from "@/components/settings"; import { SettingsRow, SettingsSwitch } from "@/components/settings";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control"; 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 { settingsStyles } from "@/styles/settings";
import { useUsageSetting } from "./setting"; import { useUsagePreferences } from "./display";
import { useUsageDisplay } from "./display";
import { useUsageInSidebar } from "./in-sidebar"; import { useUsageInSidebar } from "./in-sidebar";
import type { UsageDisplayAs } from "./preferences"; import type { UsageDisplayAs } from "./preferences";
const ThemedSettings = withUnistyles(Settings); const ThemedSettings = withUnistyles(Settings);
/** The shared usage preferences, opened from a cog as a popover or compact sheet. */ /** The shared usage preferences, opened from a cog as a popover or compact sheet. */
export function UsageOptions({ serverId }: { serverId: string | null }) { export function UsageOptions() {
const setting = useUsageSetting(serverId);
const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId;
const { t } = useTranslation(); const { t } = useTranslation();
const displayAsOptions: SegmentedControlOption<UsageDisplayAs>[] = [ const displayAsOptions: SegmentedControlOption<UsageDisplayAs>[] = [
{ value: "used", label: t("providerUsage.displayUsed"), testID: "usage-display-used" }, { value: "used", label: t("providerUsage.displayUsed"), testID: "usage-display-used" },
@@ -32,7 +27,7 @@ export function UsageOptions({ serverId }: { serverId: string | null }) {
}, },
]; ];
const compact = useIsCompactFormFactor(); const compact = useIsCompactFormFactor();
const { display } = useUsageDisplay([]); const { display } = useUsagePreferences();
const { inSidebar, setInSidebar } = useUsageInSidebar(); const { inSidebar, setInSidebar } = useUsageInSidebar();
return ( return (
<DropdownMenu compactMode="sheet"> <DropdownMenu compactMode="sheet">
@@ -54,25 +49,13 @@ export function UsageOptions({ serverId }: { serverId: string | null }) {
testID="usage-options-surface" testID="usage-options-surface"
> >
<View testID="usage-options-fields"> <View testID="usage-options-fields">
{setting.error ? <Alert variant="error" description={setting.error.message} /> : null} <SettingsSwitch
{setting.supported ? ( label={t("providerUsage.showInSidebar")}
<SettingsSwitch hint={t("providerUsage.showInSidebarHint")}
label={t("providerUsage.checkUsage")} value={inSidebar}
hint={t("providerUsage.checkUsageHint", { host: hostLabel })} onValueChange={setInSidebar}
disabled={!setting.ready} testID="usage-show-in-sidebar"
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}> <View style={settingsStyles.rowBorder}>
<SettingsRow label={t("providerUsage.displayAs")}> <SettingsRow label={t("providerUsage.displayAs")}>
<SegmentedControl <SegmentedControl
+3 -9
View File
@@ -17,7 +17,6 @@ import {
useHosts, useHosts,
} from "@/runtime/host-runtime"; } from "@/runtime/host-runtime";
import { useSessionStore, type SessionState } from "@/stores/session-store"; import { useSessionStore, type SessionState } from "@/stores/session-store";
import { useUsageSetting } from "./setting";
import { usageCopy } from "./copy"; import { usageCopy } from "./copy";
import { import {
replaceReport, replaceReport,
@@ -133,14 +132,13 @@ function toQueryState(query: {
/** Usage reports for one host, as shown on its settings page. */ /** Usage reports for one host, as shown on its settings page. */
export function useHostUsage(serverId: string): { view: UsageView; refresh: () => void } { export function useHostUsage(serverId: string): { view: UsageView; refresh: () => void } {
const setting = useUsageSetting(serverId);
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const isConnected = useHostRuntimeIsConnected(serverId); const isConnected = useHostRuntimeIsConnected(serverId);
const isSupported = useSessionStore((state) => supportsUsage(state.sessions[serverId])); const isSupported = useSessionStore((state) => supportsUsage(state.sessions[serverId]));
const query = useFetchQuery({ const query = useFetchQuery({
queryKey: usageReportsQueryKey(serverId), queryKey: usageReportsQueryKey(serverId),
queryFn: () => listReports(queryClient, serverId), queryFn: () => listReports(queryClient, serverId),
enabled: isConnected && isSupported && setting.enabled, enabled: isConnected && isSupported,
dataShape: "list", dataShape: "list",
staleTimeMs: REPORTS_STALE_TIME_MS, staleTimeMs: REPORTS_STALE_TIME_MS,
}); });
@@ -152,7 +150,6 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
const view = resolveUsageView( const view = resolveUsageView(
{ {
hostLabel, hostLabel,
enabled: setting.ready ? setting.enabled : undefined,
isConnected, isConnected,
supportsUsage: isSupported, supportsUsage: isSupported,
query: toQueryState(query), query: toQueryState(query),
@@ -169,16 +166,14 @@ const NO_REPORTS: UsageReportEntry[] = [];
* load, or without a host. * load, or without a host.
*/ */
export function useUsageHostReports(serverId: string | null): UsageReportEntry[] { export function useUsageHostReports(serverId: string | null): UsageReportEntry[] {
const setting = useUsageSetting(serverId);
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const query = useFetchQuery({ const query = useFetchQuery({
enabled: setting.enabled,
queryKey: usageReportsQueryKey(serverId ?? ""), queryKey: usageReportsQueryKey(serverId ?? ""),
queryFn: serverId ? () => listReports(queryClient, serverId) : skipToken, queryFn: serverId ? () => listReports(queryClient, serverId) : skipToken,
dataShape: "list", dataShape: "list",
staleTimeMs: REPORTS_STALE_TIME_MS, staleTimeMs: REPORTS_STALE_TIME_MS,
}); });
return setting.enabled ? (query.data ?? NO_REPORTS) : NO_REPORTS; return query.data ?? NO_REPORTS;
} }
/** /**
@@ -214,8 +209,7 @@ export function useAgentUsage(serverId: string, agentId: string): AgentUsageView
export function useHostReportsUsage(serverId: string): boolean { export function useHostReportsUsage(serverId: string): boolean {
const isConnected = useHostRuntimeIsConnected(serverId); const isConnected = useHostRuntimeIsConnected(serverId);
const isSupported = useSessionStore((state) => supportsUsage(state.sessions[serverId])); const isSupported = useSessionStore((state) => supportsUsage(state.sessions[serverId]));
const setting = useUsageSetting(serverId); return isConnected && isSupported;
return isConnected && isSupported && setting.enabled;
} }
/** Every host with whether it is connected and reports usage, in host order. */ /** Every host with whether it is connected and reports usage, in host order. */
-26
View File
@@ -1,26 +0,0 @@
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,
};
}
+11 -8
View File
@@ -17,8 +17,7 @@ import {
} from "react-native"; } from "react-native";
import { StyleSheet } from "react-native-unistyles"; import { StyleSheet } from "react-native-unistyles";
import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model"; import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model";
import { useUsageDisplay } from "./display"; import { useUsagePreferences } from "./display";
import { useUsageInSidebar } from "./in-sidebar";
import { useUsageHostId } from "./hosts"; import { useUsageHostId } from "./hosts";
import { useUsageHostReports } from "./queries"; import { useUsageHostReports } from "./queries";
import { UsageSourceIcon } from "./source-icon"; import { UsageSourceIcon } from "./source-icon";
@@ -34,24 +33,28 @@ import {
import { UsageModal } from "./usage-modal"; import { UsageModal } from "./usage-modal";
/** Each summary window with data on the usage host, under its source; empty while none has. */ /** Each summary window with data on the usage host, under its source; empty while none has. */
export function useUsageSummary(): readonly PinnedUsageSource[] { function useUsageSummary(): readonly PinnedUsageSource[] {
const { t } = useTranslation(); const { t } = useTranslation();
const { inSidebar } = useUsageInSidebar(); const { preferences } = useUsagePreferences();
const serverId = useUsageHostId(); const reports = useUsageHostReports(useUsageHostId());
const reports = useUsageHostReports(inSidebar ? serverId : null);
const { preferences } = useUsageDisplay(reports);
return useMemo(() => resolvePinnedUsage(reports, preferences, t), [preferences, reports, t]); 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 * 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. * while no summary window has data, since the footer's Usage icon already opens Usage.
* Pressing it opens the Usage modal. * Pressing it opens the Usage modal.
*/ */
export function UsageSidebarItem({ sources }: { sources: readonly PinnedUsageSource[] }) { export function UsageSidebarItem() {
const { t } = useTranslation(); const { t } = useTranslation();
const label = t(builtinSidebarNavLabelKey("usage")); const label = t(builtinSidebarNavLabelKey("usage"));
const openUsage = useOpenSidebarUsage(); const openUsage = useOpenSidebarUsage();
const sources = useUsageSummary();
if (sources.length === 0) return null; if (sources.length === 0) return null;
return <PinnedUsageTrigger label={label} sources={sources} onPress={openUsage} />; return <PinnedUsageTrigger label={label} sources={sources} onPress={openUsage} />;
} }
-1
View File
@@ -10,7 +10,6 @@ export type UsageBalanceUnit = UsageBalance["unit"];
/** What a host's usage surface shows. `unavailable` is a host state, not a failed request. */ /** What a host's usage surface shows. `unavailable` is a host state, not a failed request. */
export type UsageView = export type UsageView =
| { kind: "off"; message: string }
| { kind: "unavailable"; message: string } | { kind: "unavailable"; message: string }
| { kind: "loading" } | { kind: "loading" }
| { kind: "error"; message: string } | { 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 { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet";
import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model"; import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model";
import { useHostUsageWithControls } from "./controls"; import { useHostUsageWithControls } from "./controls";
import { useUsageDisplay } from "./display"; import { useUsagePreferences } from "./display";
import { useUsageHostSelection } from "./hosts"; import { useUsageHostSelection } from "./hosts";
import type { UsageHost } from "./model"; import type { UsageHost } from "./model";
import { UsageBody, UsageMessage } from "./usage-section"; import { UsageBody, UsageMessage } from "./usage-section";
@@ -52,12 +52,12 @@ function HostUsageModal({
hosts: UsageHost[]; hosts: UsageHost[];
onSelectHost: (serverId: string) => void; onSelectHost: (serverId: string) => void;
}) { }) {
const { display } = useUsagePreferences();
const hostSelection = useMemo( const hostSelection = useMemo(
() => ({ hosts, serverId, onSelect: onSelectHost }), () => ({ hosts, serverId, onSelect: onSelectHost }),
[hosts, onSelectHost, serverId], [hosts, onSelectHost, serverId],
); );
const { view, refresh, controls } = useHostUsageWithControls(hostSelection); const { view, refresh, controls } = useHostUsageWithControls(hostSelection);
const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []);
return ( return (
<UsageModalFrame {...props} actions={controls}> <UsageModalFrame {...props} actions={controls}>
<View testID={`usage-host-${serverId}`}> <View testID={`usage-host-${serverId}`}>
+2 -12
View File
@@ -7,7 +7,6 @@ import { Button } from "@/components/ui/button";
import { settingsStyles } from "@/styles/settings"; import { settingsStyles } from "@/styles/settings";
import { SettingsSection } from "@/components/settings/headings/settings-section"; import { SettingsSection } from "@/components/settings/headings/settings-section";
import type { UsageDisplay } from "./display"; import type { UsageDisplay } from "./display";
import { useUsageSetting } from "./setting";
import { UsageControls } from "./controls"; import { UsageControls } from "./controls";
import { UsageList } from "./list"; import { UsageList } from "./list";
import type { UsageView } from "./types"; import type { UsageView } from "./types";
@@ -28,8 +27,8 @@ export function UsageSection({
testID?: string; testID?: string;
}) { }) {
const trailing = useMemo( const trailing = useMemo(
() => <UsageControls serverId={serverId} view={view} onRefresh={onRefresh} />, () => <UsageControls view={view} onRefresh={onRefresh} />,
[onRefresh, view, serverId], [onRefresh, view],
); );
return ( return (
@@ -52,15 +51,6 @@ export function UsageBody({
onRefresh: () => void; onRefresh: () => void;
}) { }) {
const { t } = useTranslation(); 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") { if (view.kind === "unavailable") {
return <UsageMessage text={view.message} />; return <UsageMessage text={view.message} />;
} }
+6 -14
View File
@@ -2,7 +2,6 @@ export { createHostChannelTransport } from "../hosts/index.js";
import { HostTransportBudget } from "./buffering.js"; import { HostTransportBudget } from "./buffering.js";
export { HostTransportBudget } from "./buffering.js"; export { HostTransportBudget } from "./buffering.js";
import { homedir } from "node:os"; import { homedir } from "node:os";
import type { Agent } from "node:http";
import { WebSocket } from "ws"; import { WebSocket } from "ws";
import { parseHostTarget, type HostTarget } from "@getpaseo/protocol/host-target"; import { parseHostTarget, type HostTarget } from "@getpaseo/protocol/host-target";
import { createSshTunnel, type SshTunnel } from "./ssh-tunnel.js"; import { createSshTunnel, type SshTunnel } from "./ssh-tunnel.js";
@@ -20,15 +19,10 @@ export { parseHostTarget };
export type { SshTunnel } from "./ssh-tunnel.js"; export type { SshTunnel } from "./ssh-tunnel.js";
export { createSshTunnel, resolveSshFailureDetail } 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. */ /** A factory owns one attempt, including a fresh SSH process and its teardown. */
export function createHostTransportFactory( export function createHostTransportFactory(
connection: string, connection: string,
budget = new HostTransportBudget(), budget = new HostTransportBudget(),
options: HostTransportOptions = {},
): DaemonTransportFactory { ): DaemonTransportFactory {
const target = parseHostTarget(connection); const target = parseHostTarget(connection);
// Rises to "protected" once the daemon negotiates it, so a later attempt // Rises to "protected" once the daemon negotiates it, so a later attempt
@@ -74,13 +68,12 @@ export function createHostTransportFactory(
return; return;
} }
const socketPath = socketTarget.socketPath?.replace(/^~(?=\/)/, homedir()); const socketPath = socketTarget.socketPath?.replace(/^~(?=\/)/, homedir());
let factory = createWebSocketTransportFactory((url, socketOptions) => { let factory = createWebSocketTransportFactory((url, options) => {
const socket = new WebSocket( const socket = new WebSocket(
socketPath && url.startsWith("ws+unix:") ? `ws+unix://${socketPath}:/ws` : url, socketPath && url.startsWith("ws+unix:") ? `ws+unix://${socketPath}:/ws` : url,
socketOptions?.protocols, options?.protocols,
{ {
headers: socketOptions?.headers, headers: options?.headers,
agent: socketPath ? undefined : options.webSocketAgent?.(url),
...(socketPath ? { socketPath } : {}), ...(socketPath ? { socketPath } : {}),
maxPayload: 100 * 1024 * 1024, maxPayload: 100 * 1024 * 1024,
}, },
@@ -198,15 +191,14 @@ export function createHostTransportFactory(
} }
export function createHostClient( export function createHostClient(
connection: string, connection: string,
config: Omit<DaemonClientConfig, "url" | "transportFactory"> & HostTransportOptions, config: Omit<DaemonClientConfig, "url" | "transportFactory">,
budget?: HostTransportBudget, budget?: HostTransportBudget,
): DaemonClient { ): DaemonClient {
const target = parseHostTarget(connection); const target = parseHostTarget(connection);
const { webSocketAgent, ...clientConfig } = config;
return new DaemonClient({ return new DaemonClient({
...clientConfig, ...config,
url: "ws://host-connector/ws", url: "ws://host-connector/ws",
...(target.password ? { password: target.password } : {}), ...(target.password ? { password: target.password } : {}),
transportFactory: createHostTransportFactory(connection, budget, { webSocketAgent }), transportFactory: createHostTransportFactory(connection, budget),
}); });
} }
-5
View File
@@ -229,8 +229,6 @@ export const MutableDaemonConfigSchema = z
.optional(), .optional(),
app: z.object({ baseUrl: z.string() }).optional(), app: z.object({ baseUrl: z.string() }).optional(),
catalogRefreshTimeoutMs: z.number().int().positive().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 }), browserTools: MutableBrowserToolsConfigSchema.default({ enabled: false }),
providers: z.record(z.string(), MutableDaemonProviderConfigSchema).default({}), providers: z.record(z.string(), MutableDaemonProviderConfigSchema).default({}),
metadataGeneration: MutableMetadataGenerationConfigSchema.default({ providers: [] }), metadataGeneration: MutableMetadataGenerationConfigSchema.default({ providers: [] }),
@@ -258,7 +256,6 @@ export const MutableDaemonConfigPatchSchema = z
.object({ .object({
relay: MutableRelayConfigSchema.partial().optional(), relay: MutableRelayConfigSchema.partial().optional(),
mcp: z.object({ injectIntoAgents: z.boolean().optional() }).passthrough().optional(), mcp: z.object({ injectIntoAgents: z.boolean().optional() }).passthrough().optional(),
usage: z.object({ enabled: z.boolean() }).optional(),
browserTools: MutableBrowserToolsConfigSchema.partial().optional(), browserTools: MutableBrowserToolsConfigSchema.partial().optional(),
providers: z providers: z
.record(z.string(), MutableDaemonProviderConfigSchema.partial().passthrough()) .record(z.string(), MutableDaemonProviderConfigSchema.partial().passthrough())
@@ -3678,8 +3675,6 @@ export const ServerInfoStatusPayloadSchema = z
providersSnapshot: z.boolean().optional(), providersSnapshot: z.boolean().optional(),
connectedHosts: z.boolean().optional(), connectedHosts: z.boolean().optional(),
hostMultiplexing: 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(), usageSources: z.boolean().optional(),
// COMPAT(providersSnapshotCwd): added in v0.3.2, remove gate after 2027-02-10. // COMPAT(providersSnapshotCwd): added in v0.3.2, remove gate after 2027-02-10.
providersSnapshotCwd: z.boolean().optional(), providersSnapshotCwd: z.boolean().optional(),
+1 -3
View File
@@ -89,7 +89,7 @@
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts", "speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
"test": "npm run test:unit && npm run test:integration", "test": "npm run test:unit && npm run test:integration",
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"", "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/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: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:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts", "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:all": "npm run test:e2e",
"test:integration:real": "vitest run real.e2e.test.ts", "test:integration:real": "vitest run real.e2e.test.ts",
@@ -124,7 +124,6 @@
"esbuild": "^0.25.12", "esbuild": "^0.25.12",
"express": "^4.18.2", "express": "^4.18.2",
"fast-deep-equal": "^3.1.3", "fast-deep-equal": "^3.1.3",
"https-proxy-agent": "^7.0.6",
"lru-cache": "^11.5.1", "lru-cache": "^11.5.1",
"markdown-it": "^10.0.0", "markdown-it": "^10.0.0",
"mnemonic-id": "^3.2.7", "mnemonic-id": "^3.2.7",
@@ -142,7 +141,6 @@
"strip-ansi": "^7.1.2", "strip-ansi": "^7.1.2",
"tree-kill": "^1.2.2", "tree-kill": "^1.2.2",
"typescript": "^5.9.3", "typescript": "^5.9.3",
"undici": "^7.24.8",
"uuid": "^9.0.1", "uuid": "^9.0.1",
"which": "^5.0.0", "which": "^5.0.0",
"ws": "^8.14.2", "ws": "^8.14.2",
@@ -6,7 +6,6 @@ import { afterEach, describe, expect, test, vi } from "vitest";
import { createTestLogger } from "../../test-utils/test-logger.js"; import { createTestLogger } from "../../test-utils/test-logger.js";
import { AgentManager, type AgentManagerEvent } from "./agent-manager.js"; import { AgentManager, type AgentManagerEvent } from "./agent-manager.js";
import { AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS } from "./agent-stream-coalescer.js"; import { AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS } from "./agent-stream-coalescer.js";
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
import type { AgentTimelineRow } from "./agent-timeline-store-types.js"; import type { AgentTimelineRow } from "./agent-timeline-store-types.js";
import { projectTimelineRows } from "./timeline-projection.js"; import { projectTimelineRows } from "./timeline-projection.js";
import type { import type {
@@ -32,6 +31,7 @@ import type {
const COALESCE_WINDOW_MS = AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS; const COALESCE_WINDOW_MS = AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS;
const BEFORE_COALESCE_WINDOW_MS = Math.max(COALESCE_WINDOW_MS - 1, 0); const BEFORE_COALESCE_WINDOW_MS = Math.max(COALESCE_WINDOW_MS - 1, 0);
const TOOL_CALL_CONTENT_MAX_LENGTH = 64 * 1024;
const TEST_CAPABILITIES: AgentCapabilityFlags = { const TEST_CAPABILITIES: AgentCapabilityFlags = {
supportsStreaming: false, supportsStreaming: false,
@@ -400,7 +400,10 @@ describe("target coalesced behavior", () => {
try { try {
const { agentId, session } = await createManagedSession(harness); const { agentId, session } = await createManagedSession(harness);
const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`;
const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output })); const expectedItem = toolCall({
status: "completed",
output: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH),
});
session.pushEvent(timelineEvent(toolCall({ status: "completed", output }))); session.pushEvent(timelineEvent(toolCall({ status: "completed", output })));
await waitForSessionEventQueue(); await waitForSessionEventQueue();
@@ -422,7 +425,10 @@ describe("target coalesced behavior", () => {
try { try {
const { agentId } = await createManagedSession(harness); const { agentId } = await createManagedSession(harness);
const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`;
const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output })); const expectedItem = toolCall({
status: "completed",
output: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH),
});
await harness.manager.appendTimelineItem(agentId, toolCall({ status: "completed", output })); await harness.manager.appendTimelineItem(agentId, toolCall({ status: "completed", output }));
@@ -443,7 +449,10 @@ describe("target coalesced behavior", () => {
try { try {
const { agentId, session } = await createManagedSession(harness); const { agentId, session } = await createManagedSession(harness);
const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`;
const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output })); const expectedItem = toolCall({
status: "completed",
output: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH),
});
session.setHistory([timelineEvent(toolCall({ status: "completed", output }))]); session.setHistory([timelineEvent(toolCall({ status: "completed", output }))]);
await harness.manager.hydrateTimelineFromProvider(agentId, { force: true }); await harness.manager.hydrateTimelineFromProvider(agentId, { force: true });
@@ -461,7 +470,10 @@ describe("target coalesced behavior", () => {
try { try {
const { agentId } = await createManagedSession(harness); const { agentId } = await createManagedSession(harness);
const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`;
const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output })); const expectedItem = toolCall({
status: "completed",
output: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH),
});
await harness.manager.emitLiveTimelineItem( await harness.manager.emitLiveTimelineItem(
agentId, agentId,
@@ -483,9 +495,10 @@ describe("target coalesced behavior", () => {
try { try {
const { agentId, session } = await createManagedSession(harness); const { agentId, session } = await createManagedSession(harness);
const content = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`; const content = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`;
const expectedItem = limitAgentTimelineItemContent( const expectedItem = toolCall({
toolCall({ status: "failed", error: { content } }), status: "failed",
); error: { content: "a".repeat(TOOL_CALL_CONTENT_MAX_LENGTH) },
});
session.pushEvent(timelineEvent(toolCall({ status: "failed", error: { content } }))); session.pushEvent(timelineEvent(toolCall({ status: "failed", error: { content } })));
await waitForSessionEventQueue(); await waitForSessionEventQueue();
@@ -21,7 +21,6 @@ import {
} from "./agent-manager.js"; } from "./agent-manager.js";
import { AgentStorage } from "./agent-storage.js"; import { AgentStorage } from "./agent-storage.js";
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js"; import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
import { toAgentPayload } from "./agent-projections.js"; import { toAgentPayload } from "./agent-projections.js";
import { projectTimelineRows } from "./timeline-projection.js"; import { projectTimelineRows } from "./timeline-projection.js";
import { getOpenAgentTabLabel, PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels"; import { getOpenAgentTabLabel, PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels";
@@ -4593,7 +4592,7 @@ test("importProviderSession imports the selected session without listing and pub
expect(manager.getTimeline(imported.id)).toEqual([ expect(manager.getTimeline(imported.id)).toEqual([
{ type: "user_message", text: "Trace provider imports" }, { type: "user_message", text: "Trace provider imports" },
{ type: "assistant_message", text: "Done" }, { type: "assistant_message", text: "Done" },
limitAgentTimelineItemContent({ {
type: "tool_call", type: "tool_call",
callId: "large-shell-result", callId: "large-shell-result",
name: "shell", name: "shell",
@@ -4602,10 +4601,10 @@ test("importProviderSession imports the selected session without listing and pub
detail: { detail: {
type: "shell", type: "shell",
command: "print output", command: "print output",
output: "x".repeat(1024 * 1024), output: "x".repeat(64 * 1024),
exitCode: 0, exitCode: 0,
}, },
}), },
]); ]);
expect(manager.listProviderSubagents(imported.id)).toEqual([ expect(manager.listProviderSubagents(imported.id)).toEqual([
expect.objectContaining({ id: "thread-child", title: "Imported child", status: "completed" }), expect.objectContaining({ id: "thread-child", title: "Imported child", status: "completed" }),
@@ -11958,7 +11957,10 @@ test("commits startup notices once on create and after restored history", async
exitCode: 0, exitCode: 0,
}, },
}; };
const limitedToolOutput = limitAgentTimelineItemContent(toolOutput); const limitedToolOutput: AgentTimelineItem = {
...toolOutput,
detail: { type: "shell", command: "print output", output: "x".repeat(64 * 1024), exitCode: 0 },
};
class NotifyingSession extends TestAgentSession { class NotifyingSession extends TestAgentSession {
readonly initialTimeline = [{ item: notice, timestamp: "2026-09-22T00:00:00.000Z" }]; readonly initialTimeline = [{ item: notice, timestamp: "2026-09-22T00:00:00.000Z" }];
override async *streamHistory(): AsyncGenerator<AgentStreamEvent> { override async *streamHistory(): AsyncGenerator<AgentStreamEvent> {
@@ -1,30 +1,12 @@
import { AgentTimelineItemPayloadSchema } from "@getpaseo/protocol/messages";
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import type { AgentTimelineItem } from "./agent-sdk-types.js";
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js"; import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
function serializedBytes(item: AgentTimelineItem): number {
return Buffer.byteLength(JSON.stringify(item), "utf8");
}
describe("agent timeline content", () => { describe("agent timeline content", () => {
test("returns an item within budget unchanged", () => {
const item: AgentTimelineItem = {
type: "tool_call",
callId: "small",
name: "Bash",
status: "completed",
error: null,
detail: { type: "shell", command: "ls", output: "x".repeat(60 * 1024) },
};
expect(limitAgentTimelineItemContent(item)).toBe(item);
});
test.each([false, true])( test.each([false, true])(
"cuts oversized shell output and keeps short fields whole (failed=%s)", "preserves the exact UTF-16 prefix for oversized shell output (failed=%s)",
(failed) => { (failed) => {
const text = "x".repeat(1024 * 1024) + "🙂"; const text = "x".repeat(64 * 1024 - 1) + "🙂";
const item = limitAgentTimelineItemContent({ const item = limitAgentTimelineItemContent({
type: "tool_call", type: "tool_call",
callId: "large-shell", callId: "large-shell",
@@ -33,116 +15,45 @@ describe("agent timeline content", () => {
detail: { type: "shell", command: "echo large", output: text }, detail: { type: "shell", command: "echo large", output: text },
error: failed ? { content: text } : null, error: failed ? { content: text } : null,
}); });
expect(item).toMatchObject({ expect(item).toEqual({
type: "tool_call",
callId: "large-shell", callId: "large-shell",
name: "Bash", name: "Bash",
detail: { type: "shell", command: "echo large" }, status: failed ? "failed" : "completed",
detail: { type: "shell", command: "echo large", output: text.slice(0, 64 * 1024) },
error: failed ? { content: text.slice(0, 64 * 1024) } : null,
}); });
if (item.type !== "tool_call" || item.detail.type !== "shell") throw new Error("shape");
expect(item.detail.output).toMatch(/^x+…\[truncated \d{3}\.\d KB\]$/);
expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024);
}, },
); );
test("replaces an oversized data URL in an unknown tool result with a marker", () => { test("marks truncated plain-text tool content within the content budget", () => {
const url = `data:image/jpeg;base64,${"A".repeat(14 * 1024 * 1024)}`; const oversizedInput = "x".repeat(64 * 1024 + 1);
const item = limitAgentTimelineItemContent({ const item = limitAgentTimelineItemContent({
type: "tool_call", type: "tool_call",
callId: "screenshot", callId: "terminal-session-4242",
name: "node_repl.js", name: "terminal",
status: "completed", status: "completed",
error: null, error: null,
detail: { detail: {
type: "unknown", type: "plain_text",
input: { index: 1 }, text: oversizedInput,
output: { content: [{ type: "image", url }], note: "captured" }, icon: "square_terminal",
}, },
}); });
expect(limitAgentTimelineItemContent(item)).toEqual(item);
expect(item).toEqual({ expect(item).toEqual({
type: "tool_call", type: "tool_call",
callId: "screenshot", callId: "terminal-session-4242",
name: "node_repl.js", name: "terminal",
status: "completed", status: "completed",
error: null, error: null,
detail: { detail: {
type: "unknown", type: "plain_text",
input: { index: 1 }, text: "x".repeat(64 * 1024 - "\n\n[Content truncated]".length) + "\n\n[Content truncated]",
output: { content: [{ type: "image", url: "…[truncated 14.0 MB]" }], note: "captured" }, icon: "square_terminal",
}, },
}); });
}); });
test("gives non-tool items a 256 KiB budget", () => {
const text = "a".repeat(10 * 1024 * 1024);
const item = limitAgentTimelineItemContent({ type: "assistant_message", text });
if (item.type !== "assistant_message") throw new Error("shape");
expect(item.text).toMatch(/^a+…\[truncated 9\.\d MB\]$/);
expect(item.text.length).toBeGreaterThan(200 * 1024);
expect(serializedBytes(item)).toBeLessThanOrEqual(256 * 1024);
});
test("bounds an item whose structure alone exceeds the budget", () => {
const item = limitAgentTimelineItemContent({
type: "tool_call",
callId: "many",
name: "query",
status: "completed",
error: null,
detail: { type: "unknown", input: null, output: Array.from({ length: 1_000_000 }, () => 1) },
});
if (item.type !== "tool_call" || item.detail.type !== "unknown") throw new Error("shape");
const output = item.detail.output as unknown[];
expect(output.length).toBeLessThan(1_000_000);
expect(output.every((value) => value === 1)).toBe(true);
expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024);
});
test("keeps short strings whole and limits idempotently when an item has many strings", () => {
const callId = "3f2b8c1e-9a4d-4e6f-8b2a-1c3d5e7f9a0b";
const item = limitAgentTimelineItemContent({
type: "tool_call",
callId,
name: "mcp__search__files",
status: "completed",
error: null,
detail: {
type: "unknown",
input: { query: "useWorkspaceSomethingVeryDescriptive" },
output: Array.from(
{ length: 10_000 },
(_, index) => `${String(index).padStart(5, "0")}${"p".repeat(28)}`,
),
},
});
if (item.type !== "tool_call" || item.detail.type !== "unknown") throw new Error("shape");
expect(item.callId).toBe(callId);
expect(item.detail.input).toEqual({ query: "useWorkspaceSomethingVeryDescriptive" });
const output = item.detail.output as string[];
expect(output.length).toBeLessThan(10_000);
expect(output.every((path) => path.length === 33)).toBe(true);
expect(serializedBytes(item)).toBeLessThanOrEqual(64 * 1024);
expect(limitAgentTimelineItemContent(item)).toBe(item);
});
test("keeps a long typed array valid against the wire schema", () => {
const item = limitAgentTimelineItemContent({
type: "todo",
items: Array.from({ length: 20_000 }, (_, index) => ({
text: `Task ${index}`,
completed: false,
})),
});
if (item.type !== "todo") throw new Error("shape");
expect(item.items.length).toBeLessThan(20_000);
expect(AgentTimelineItemPayloadSchema.safeParse(item).success).toBe(true);
expect(serializedBytes(item)).toBeLessThanOrEqual(256 * 1024);
});
test("is stable on an already-limited item", () => {
const item = limitAgentTimelineItemContent({
type: "reasoning",
text: "r".repeat(1024 * 1024),
});
expect(limitAgentTimelineItemContent(item)).toBe(item);
});
}); });
@@ -1,19 +1,9 @@
import type { AgentTimelineItem } from "./agent-sdk-types.js"; import type { AgentTimelineItem } from "./agent-sdk-types.js";
import type { JsonValue } from "@getpaseo/protocol/agent-types"; import type { JsonValue } from "@getpaseo/protocol/agent-types";
const TOOL_CALL_CONTENT_MAX_LENGTH = 64 * 1024;
export const PLUGIN_TIMELINE_DATA_MAX_BYTES = 64 * 1024; export const PLUGIN_TIMELINE_DATA_MAX_BYTES = 64 * 1024;
// One timeline fetch sends its entries in one WebSocket message, so every item must stay small.
// Budgets count UTF-16 units plus a fixed cost per node; neither is exact JSON bytes. They bound
// long strings and long arrays, not wide objects (every entry is kept) or multi-byte text.
const TOOL_CALL_BUDGET = 64 * 1024;
const ITEM_BUDGET = 256 * 1024;
const NODE_COST = 8;
const MARKER_COST = 32;
// Ids, names, paths and queries stay whole, so an item keeps its identity across passes.
const SHORT_STRING = 1024;
const MAX_DEPTH = 64;
export function assertPluginTimelineDataSize(data: JsonValue): void { export function assertPluginTimelineDataSize(data: JsonValue): void {
const serializedBytes = Buffer.byteLength(JSON.stringify(data), "utf8"); const serializedBytes = Buffer.byteLength(JSON.stringify(data), "utf8");
if (serializedBytes > PLUGIN_TIMELINE_DATA_MAX_BYTES) { if (serializedBytes > PLUGIN_TIMELINE_DATA_MAX_BYTES) {
@@ -27,119 +17,66 @@ function retainTextPrefix(text: string, length: number): string {
return Buffer.from(text.slice(0, length), "utf16le").toString("utf16le"); return Buffer.from(text.slice(0, length), "utf16le").toString("utf16le");
} }
function formatSize(units: number): string { function limitFailedShellError(item: AgentTimelineItem): AgentTimelineItem {
if (units < 1024) return `${units} B`; if (
if (units < 1024 * 1024) return `${(units / 1024).toFixed(1)} KB`; item.type !== "tool_call" ||
return `${(units / (1024 * 1024)).toFixed(1)} MB`; item.detail.type !== "shell" ||
} item.status !== "failed" ||
typeof item.error !== "object" ||
function truncatedMarker(units: number): string { item.error === null ||
return `…[truncated ${formatSize(units)}]`; !("content" in item.error) ||
} typeof item.error.content !== "string" ||
item.error.content.length <= TOOL_CALL_CONTENT_MAX_LENGTH
interface ItemSize { ) {
nodeCost: number; return item;
stringLengths: number[];
tooDeep: boolean;
}
function measure(value: unknown, depth: number, size: ItemSize): void {
size.nodeCost += NODE_COST;
if (depth > MAX_DEPTH) {
size.tooDeep = true;
} else if (typeof value === "string") {
size.stringLengths.push(value.length);
} else if (Array.isArray(value)) {
for (const element of value) measure(element, depth + 1, size);
} else if (typeof value === "object" && value !== null) {
for (const [key, child] of Object.entries(value)) {
size.nodeCost += key.length;
measure(child, depth + 1, size);
}
} }
return {
...item,
error: {
...item.error,
content: retainTextPrefix(item.error.content, TOOL_CALL_CONTENT_MAX_LENGTH),
},
};
} }
/** The largest per-string length that keeps all strings, once cut, within `available`. */ function limitPlainText(item: AgentTimelineItem): AgentTimelineItem {
function findStringCap(lengths: readonly number[], available: number): number { if (
let low = 0; item.type !== "tool_call" ||
let high = 0; item.detail.type !== "plain_text" ||
for (const length of lengths) high = Math.max(high, length); typeof item.detail.text !== "string" ||
while (low < high) { item.detail.text.length <= TOOL_CALL_CONTENT_MAX_LENGTH
const cap = Math.ceil((low + high) / 2); ) {
let total = 0; return item;
for (const length of lengths) total += Math.min(length, cap);
if (total <= available) low = cap;
else high = cap - 1;
} }
return low; const notice = "\n\n[Content truncated]";
return {
...item,
detail: {
...item.detail,
text:
retainTextPrefix(item.detail.text, TOOL_CALL_CONTENT_MAX_LENGTH - notice.length) + notice,
},
};
} }
interface CutState {
stringCap: number;
remaining: number;
}
function cutString(text: string, cap: number): string {
if (text.length <= cap) return text;
// A partial data URL is useless to every reader, so drop it whole.
if (text.startsWith("data:")) return truncatedMarker(text.length);
return retainTextPrefix(text, cap) + truncatedMarker(text.length - cap);
}
function cut(value: unknown, depth: number, state: CutState): unknown {
state.remaining -= NODE_COST;
if (depth > MAX_DEPTH) return "…[truncated]";
if (typeof value === "string") {
const text = cutString(value, state.stringCap);
state.remaining -= text.length;
return text;
}
if (Array.isArray(value)) {
let changed = false;
const output: unknown[] = [];
for (const element of value) {
const remainingBefore = state.remaining;
const next = cut(element, depth + 1, state);
if (state.remaining < 0) {
// Drop this and later elements. A marker element would break typed arrays.
state.remaining = remainingBefore;
changed = true;
break;
}
changed ||= next !== element;
output.push(next);
}
return changed ? output : value;
}
if (typeof value === "object" && value !== null) {
let changed = false;
const output: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value)) {
state.remaining -= key.length;
const next = cut(child, depth + 1, state);
changed ||= next !== child;
output[key] = next;
}
return changed ? output : value;
}
return value;
}
/** Returns the item itself when it fits its budget; otherwise a copy with its largest strings cut. */
export function limitAgentTimelineItemContent(item: AgentTimelineItem): AgentTimelineItem { export function limitAgentTimelineItemContent(item: AgentTimelineItem): AgentTimelineItem {
const budget = item.type === "tool_call" ? TOOL_CALL_BUDGET : ITEM_BUDGET; item = limitFailedShellError(item);
const size: ItemSize = { nodeCost: 0, stringLengths: [], tooDeep: false }; item = limitPlainText(item);
measure(item, 0, size); if (
let stringTotal = 0; item.type !== "tool_call" ||
for (const length of size.stringLengths) stringTotal += length; item.detail.type !== "shell" ||
if (!size.tooDeep && size.nodeCost + stringTotal <= budget) return item; typeof item.detail.output !== "string"
) {
// Strings get what structure leaves, but at least half the budget, less a margin for JSON return item;
// escaping. Arrays drop the elements that do not fit, which bounds items whose short strings }
// or structure alone are too big. if (item.detail.output.length <= TOOL_CALL_CONTENT_MAX_LENGTH) {
const markerCost = return item;
MARKER_COST * size.stringLengths.filter((length) => length > SHORT_STRING).length; }
const available = (budget * 15) / 16 - Math.min(size.nodeCost, budget / 2) - markerCost; return {
const stringCap = Math.max(SHORT_STRING, findStringCap(size.stringLengths, available)); ...item,
return cut(item, 0, { stringCap, remaining: budget }) as AgentTimelineItem; detail: {
...item.detail,
output: retainTextPrefix(item.detail.output, TOOL_CALL_CONTENT_MAX_LENGTH),
},
};
} }
@@ -181,20 +181,6 @@ describe("projected timeline retention", () => {
}, },
]); ]);
}); });
it("serves a merged assistant message within the item budget", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent", { epoch: "e" });
const chunk = "a".repeat(200 * 1024);
for (let index = 0; index < 10; index++) {
store.append("agent", { type: "assistant_message", messageId: "m", text: chunk });
}
const [row] = store.fetch("agent", { limit: 1 }).rows;
expect(row).toMatchObject({ seqStart: 1, seqEnd: 10 });
expect(row.item).toMatchObject({ type: "assistant_message", messageId: "m" });
expect(Buffer.byteLength(JSON.stringify(row.item))).toBeLessThanOrEqual(256 * 1024);
expect(store.getLastAssistantMessage("agent")).toHaveLength(10 * chunk.length);
});
}); });
describe("projected sequence ownership", () => { describe("projected sequence ownership", () => {
@@ -1,6 +1,5 @@
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { TimelineProjection, type ProjectedTimelineRow } from "./timeline-projection.js"; import { TimelineProjection, type ProjectedTimelineRow } from "./timeline-projection.js";
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
import type { AgentTimelineItem } from "./agent-sdk-types.js"; import type { AgentTimelineItem } from "./agent-sdk-types.js";
import type { import type {
AgentTimelineFetchOptions, AgentTimelineFetchOptions,
@@ -121,12 +120,7 @@ export class InMemoryAgentTimelineStore {
hasNewer: page.hasNewer, hasNewer: page.hasNewer,
startSeq: page.startSeq, startSeq: page.startSeq,
endSeq: page.endSeq, endSeq: page.endSeq,
// Stored rows are already within budget; this bounds assistant and reasoning merges. rows: page.entries.map((entry) => Object.assign({ seq: entry.seqEnd }, entry)),
rows: page.entries.map((entry) =>
Object.assign({ seq: entry.seqEnd }, entry, {
item: limitAgentTimelineItemContent(entry.item),
}),
),
}; };
} }
@@ -80,7 +80,7 @@ describe("ProviderSubagentStore", () => {
const [row] = subagents.fetchTimeline("parent-a", "child-1").rows; const [row] = subagents.fetchTimeline("parent-a", "child-1").rows;
expect(row?.item).toMatchObject({ expect(row?.item).toMatchObject({
type: "tool_call", type: "tool_call",
detail: { type: "shell", output: expect.stringMatching(/^x+…\[truncated \d+\.\d KB\]$/) }, detail: { type: "shell", output: "x".repeat(64 * 1024) },
}); });
}); });
@@ -737,7 +737,7 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
); );
}, 120_000); }, 120_000);
test("limits retained child shell output to the timeline item budget", async () => { test("limits retained child shell output to the timeline's existing content limit", async () => {
const output = "x".repeat(128 * 1024); const output = "x".repeat(128 * 1024);
writeSession({ writeSession({
parentLines: [taskToolUse(), taskToolResult()], parentLines: [taskToolUse(), taskToolResult()],
@@ -782,10 +782,7 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
type: "timeline", type: "timeline",
id: TOOL_USE_ID, id: TOOL_USE_ID,
item: expect.objectContaining({ item: expect.objectContaining({
detail: expect.objectContaining({ detail: expect.objectContaining({ type: "shell", output: output.slice(0, 64 * 1024) }),
type: "shell",
output: expect.stringMatching(/^x+…\[truncated \d+\.\d KB\]$/),
}),
}), }),
}), }),
]); ]);
@@ -3643,114 +3643,3 @@ test("closing Pi during image conversion rejects its pending start", async () =>
await session.close(); await session.close();
await rejected; 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,11 +64,7 @@ import {
streamPiHistory, streamPiHistory,
type PiCapturedUserMessageEntry, type PiCapturedUserMessageEntry,
} from "./history-mapper.js"; } from "./history-mapper.js";
import { import { materializeProviderImage } from "../provider-image-output.js";
materializeProviderImage,
renderProviderImageOutputAsAssistantMarkdown,
type ProviderImageOutput,
} from "../provider-image-output.js";
import { PiCliRuntime } from "./cli-runtime.js"; import { PiCliRuntime } from "./cli-runtime.js";
import { import {
createPiExtensionHost, createPiExtensionHost,
@@ -93,7 +89,6 @@ import {
mapToolDetail, mapToolDetail,
parseToolArgs, parseToolArgs,
parseToolResult, parseToolResult,
splitPiToolResultImages,
type PiToolResult, type PiToolResult,
type PiTrackedToolCall, type PiTrackedToolCall,
} from "./tool-call-mapper.js"; } from "./tool-call-mapper.js";
@@ -1206,7 +1201,6 @@ export class PiRpcAgentSession implements AgentSession {
private closed = false; private closed = false;
private readonly closeController = new AbortController(); private readonly closeController = new AbortController();
private readonly pendingExtensionHydrations = new Set<Promise<void>>(); private readonly pendingExtensionHydrations = new Set<Promise<void>>();
private pendingOutput: Promise<void> | null = null;
// Pi publishes the terminal before acknowledging abort. Autonomous runs have no // Pi publishes the terminal before acknowledging abort. Autonomous runs have no
// turn ID; retain their errors too until the cancellation request settles. // turn ID; retain their errors too until the cancellation request settles.
private interruptingTurn: { turnId: string | undefined; error: string | null } | null = null; private interruptingTurn: { turnId: string | undefined; error: string | null } | null = null;
@@ -1608,7 +1602,6 @@ export class PiRpcAgentSession implements AgentSession {
this.pendingExtensionUiRequests.size || this.pendingExtensionUiRequests.size ||
this.pendingExtensionResults.size || this.pendingExtensionResults.size ||
this.pendingExtensionHydrations.size || this.pendingExtensionHydrations.size ||
this.pendingOutput ||
this.pendingSteerSubmissions.length || this.pendingSteerSubmissions.length ||
this.pendingNoTurnOutputs.length || this.pendingNoTurnOutputs.length ||
this.interruptingTurn this.interruptingTurn
@@ -1629,7 +1622,7 @@ export class PiRpcAgentSession implements AgentSession {
try { try {
await this.runtimeSession.close(); await this.runtimeSession.close();
} finally { } finally {
await Promise.all([this.pendingOutput, ...this.pendingExtensionHydrations]); await Promise.all(this.pendingExtensionHydrations);
this.rejectAllExtensionResults(new Error("Pi session closed")); this.rejectAllExtensionResults(new Error("Pi session closed"));
this.cleanup?.(); this.cleanup?.();
} }
@@ -1693,31 +1686,9 @@ export class PiRpcAgentSession implements AgentSession {
} }
private emit(event: AgentStreamEvent): void { private emit(event: AgentStreamEvent): void {
if (this.pendingOutput) { for (const subscriber of this.subscribers) {
this.emitAsync(() => Promise.resolve([event])); subscriber(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 { private emitExtensionOutput(output: PiExtensionEventOutput | undefined, turnId?: string): void {
@@ -2344,11 +2315,8 @@ export class PiRpcAgentSession implements AgentSession {
this.activeToolCalls.get(event.toolCallId) ?? parseToolArgs(event.toolName, null); this.activeToolCalls.get(event.toolCallId) ?? parseToolArgs(event.toolName, null);
this.activeToolCalls.delete(event.toolCallId); this.activeToolCalls.delete(event.toolCallId);
// Pull image blocks out of the result so base64 never reaches the tool output, then render const result = parseToolResult(event.result);
// each one as an assistant_message markdown image after the tool_call (mirroring the Claude const error = event.isError ? event.result : null;
// provider, upstream #1717).
const { images, result } = splitPiToolResultImages(parseToolResult(event.result));
const error = event.isError ? result : null;
const status = event.isError ? "failed" : "completed"; const status = event.isError ? "failed" : "completed";
this.extensionHost.onToolEnd({ this.extensionHost.onToolEnd({
callId: event.toolCallId, callId: event.toolCallId,
@@ -2358,30 +2326,6 @@ export class PiRpcAgentSession implements AgentSession {
result, result,
}); });
this.emitToolCallEvent(event.toolCallId, toolCall, status, result, error); 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: { private emitCompactionTimeline(input: {
@@ -21,11 +21,11 @@ export function mapPiChildSession(
return new PiChildSessionFollower(id, file, maxBytes).readNew(); return new PiChildSessionFollower(id, file, maxBytes).readNew();
} }
async function mapChildLine( function mapChildLine(
mapper: PiHistoryMapper, mapper: PiHistoryMapper,
id: string, id: string,
line: string, line: string,
): Promise<ProviderSubagentInputEvent[]> { ): ProviderSubagentInputEvent[] {
let entry: { message?: PiAgentMessage; timestamp?: string }; let entry: { message?: PiAgentMessage; timestamp?: string };
try { try {
entry = JSON.parse(line); entry = JSON.parse(line);
@@ -33,7 +33,7 @@ async function mapChildLine(
return []; return [];
} }
if (!entry.message || typeof entry.message !== "object" || !("role" in entry.message)) return []; if (!entry.message || typeof entry.message !== "object" || !("role" in entry.message)) return [];
return (await mapper.mapMessages([entry.message])).flatMap((mapped) => return mapper.mapMessages([entry.message]).flatMap((mapped) =>
mapped.type === "timeline" mapped.type === "timeline"
? [ ? [
{ {
@@ -83,10 +83,7 @@ export class PiChildSessionFollower {
const events: ProviderSubagentInputEvent[] = []; const events: ProviderSubagentInputEvent[] = [];
for (const line of data.subarray(0, lastNewline).toString("utf8").split("\n")) { for (const line of data.subarray(0, lastNewline).toString("utf8").split("\n")) {
if (this.items >= MAX_ITEMS) break; if (this.items >= MAX_ITEMS) break;
const mapped = (await mapChildLine(this.mapper, this.id, line)).slice( const mapped = mapChildLine(this.mapper, this.id, line).slice(0, MAX_ITEMS - this.items);
0,
MAX_ITEMS - this.items,
);
this.items += mapped.length; this.items += mapped.length;
events.push(...mapped); events.push(...mapped);
} }
@@ -83,7 +83,7 @@ describe("Pi extension host", () => {
test("declines a throwing adapter and preserves generic history", async () => { test("declines a throwing adapter and preserves generic history", async () => {
const host = createPiExtensionHost(undefined, [throwingAdapter]); const host = createPiExtensionHost(undefined, [throwingAdapter]);
const mapper = new PiHistoryMapper("pi", [], {}, host); const mapper = new PiHistoryMapper("pi", [], {}, host);
const events = await mapper.mapMessages([ const events = mapper.mapMessages([
{ {
role: "assistant", role: "assistant",
content: [{ type: "toolCall", id: "call-1", name: "other", arguments: {} }], content: [{ type: "toolCall", id: "call-1", name: "other", arguments: {} }],
@@ -193,7 +193,7 @@ describe("Pi extension host", () => {
await output?.hydration; await output?.hydration;
expect(reads).toHaveLength(8); expect(reads).toHaveLength(8);
}); });
test("claims a tool, declines an unrelated one, and maps history like live events", async () => { test("claims a tool, declines an unrelated one, and maps history like live events", () => {
const host = createPiExtensionHost(); const host = createPiExtensionHost();
const args = { agent: "scout", task: "Inspect files" }; const args = { agent: "scout", task: "Inspect files" };
const result = parseToolResult({ content: [{ type: "text", text: "Found two files" }] }); const result = parseToolResult({ content: [{ type: "text", text: "Found two files" }] });
@@ -225,7 +225,7 @@ describe("Pi extension host", () => {
).toBeUndefined(); ).toBeUndefined();
const mapper = new PiHistoryMapper("pi"); const mapper = new PiHistoryMapper("pi");
const events = await mapper.mapMessages([ const events = mapper.mapMessages([
{ {
role: "assistant", role: "assistant",
content: [{ type: "toolCall", id: "call-1", name: "subagent", arguments: args }], 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", async () => { test("captured result renders in live and history tool rows, while foreign shapes decline", () => {
const call = { const call = {
callId: end.toolCallId, callId: end.toolCallId,
toolName: end.toolName, toolName: end.toolName,
@@ -93,7 +93,7 @@ test("captured result renders in live and history tool rows, while foreign shape
label: "Questions", label: "Questions",
text: "Which snack?: Cookie\nWhich colors?: Red, Blue\nWhat project name?: Nebula", text: "Which snack?: Cookie\nWhich colors?: Red, Blue\nWhat project name?: Nebula",
}); });
const history = await new PiHistoryMapper("pi").mapMessages([ const history = new PiHistoryMapper("pi").mapMessages([
{ {
role: "assistant", role: "assistant",
content: [ content: [
@@ -89,7 +89,7 @@ export async function verifyTaskFixture(path: URL, expectedStatuses: string[]):
for (const event of fixture.events) pi.latestSession().emit(event); for (const event of fixture.events) pi.latestSession().emit(event);
pi.latestSession().finishTurn(); pi.latestSession().finishTurn();
expect(todos(live)).toEqual(mapped); expect(todos(live)).toEqual(mapped);
const replay = await new PiHistoryMapper("pi").mapMessages(fixture.messages); const replay = new PiHistoryMapper("pi").mapMessages(fixture.messages);
expect(todos(replay)).toEqual(mapped); expect(todos(replay)).toEqual(mapped);
expect( expect(
replay.filter( replay.filter(
@@ -221,75 +221,3 @@ 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,9 +1,5 @@
import { mapCustomMessageToToolCall } from "../custom-message.js"; import { mapCustomMessageToToolCall } from "../custom-message.js";
import type { AgentStreamEvent, AgentTimelineItem, ToolCallDetail } from "../../agent-sdk-types.js"; import type { AgentStreamEvent, AgentTimelineItem, ToolCallDetail } from "../../agent-sdk-types.js";
import {
materializeProviderImage,
renderProviderImageOutputAsAssistantMarkdown,
} from "../provider-image-output.js";
import { import {
createPiExtensionHost, createPiExtensionHost,
type PiExtensionEventOutput, type PiExtensionEventOutput,
@@ -15,7 +11,6 @@ import {
mapToolDetail, mapToolDetail,
parseToolArgs, parseToolArgs,
parseToolResult, parseToolResult,
splitPiToolResultImages,
type PiToolResult, type PiToolResult,
type PiTrackedToolCall, type PiTrackedToolCall,
} from "./tool-call-mapper.js"; } from "./tool-call-mapper.js";
@@ -76,7 +71,7 @@ export class PiHistoryMapper {
private readonly extensionHost: PiExtensionHost = createPiExtensionHost(), private readonly extensionHost: PiExtensionHost = createPiExtensionHost(),
) {} ) {}
async mapMessages(messages: readonly PiAgentMessage[]): Promise<AgentStreamEvent[]> { mapMessages(messages: readonly PiAgentMessage[]): AgentStreamEvent[] {
const events: AgentStreamEvent[] = []; const events: AgentStreamEvent[] = [];
for (const message of messages) { for (const message of messages) {
@@ -91,7 +86,7 @@ export class PiHistoryMapper {
events.push(...this.mapAssistantMessage(message)); events.push(...this.mapAssistantMessage(message));
break; break;
case "toolResult": { case "toolResult": {
events.push(...(await this.mapToolResultMessage(message))); events.push(...this.mapToolResultMessage(message));
break; break;
} }
case "bashExecution": case "bashExecution":
@@ -212,35 +207,24 @@ export class PiHistoryMapper {
return events; return events;
} }
private async mapToolResultMessage( private mapToolResultMessage(
message: Extract<PiAgentMessage, { role: "toolResult" }>, message: Extract<PiAgentMessage, { role: "toolResult" }>,
): Promise<AgentStreamEvent[]> { ): AgentStreamEvent[] {
const tracked = const tracked =
this.pendingToolCalls.get(message.toolCallId) ?? parseToolArgs(message.toolName, null); this.pendingToolCalls.get(message.toolCallId) ?? parseToolArgs(message.toolName, null);
this.pendingToolCalls.delete(message.toolCallId); this.pendingToolCalls.delete(message.toolCallId);
const result = parseToolResult({ content: message.content, details: message.details }); 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({ const mapping = this.extensionHost.mapToolCall({
callId: message.toolCallId, callId: message.toolCallId,
toolName: tracked.toolName, toolName: tracked.toolName,
args: tracked.args, args: tracked.args,
status: message.isError ? "failed" : "completed", status: message.isError ? "failed" : "completed",
result: splitResult, result,
}); });
const detail = this.mapToolDetail(message.toolCallId, tracked, splitResult, mapping?.detail); const detail = this.mapToolDetail(message.toolCallId, tracked, result, mapping?.detail);
if (!detail) { if (!detail) {
return []; 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 [ return [
{ {
type: "timeline", type: "timeline",
@@ -250,10 +234,9 @@ export class PiHistoryMapper {
name: mapping?.name ?? tracked.toolName, name: mapping?.name ?? tracked.toolName,
isError: Boolean(message.isError), isError: Boolean(message.isError),
detail, detail,
errorText: extractTextFromToolResult(splitResult) ?? "Tool call failed", errorText: extractTextFromToolResult(result) ?? "Tool call failed",
}), }),
}, },
...imageEvents,
...this.extensionEvents(mapping), ...this.extensionEvents(mapping),
]; ];
} }
@@ -314,10 +297,9 @@ export async function* streamPiHistory(
signal?: AbortSignal, signal?: AbortSignal,
): AsyncGenerator<AgentStreamEvent> { ): AsyncGenerator<AgentStreamEvent> {
const mapper = new PiHistoryMapper(provider, userEntries, hooks, extensionHost); const mapper = new PiHistoryMapper(provider, userEntries, hooks, extensionHost);
for (const message of messages) { for (const event of mapper.mapMessages(messages)) {
if (signal?.aborted) return; if (signal?.aborted) return;
for (const event of await mapper.mapMessages([message])) { if (event) {
if (signal?.aborted) return;
yield event; yield event;
} }
} }
@@ -1,12 +1,6 @@
import { describe, expect, test } from "vitest"; import { describe, expect, test } from "vitest";
import { import { mapToolDetail, parseToolArgs, parseToolResult } from "./tool-call-mapper.js";
extractTextFromToolResult,
mapToolDetail,
parseToolArgs,
parseToolResult,
splitPiToolResultImages,
} from "./tool-call-mapper.js";
describe("Pi tool call mapper", () => { describe("Pi tool call mapper", () => {
test("maps bash args and result to shell detail", () => { test("maps bash args and result to shell detail", () => {
@@ -62,77 +56,3 @@ 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,7 +1,6 @@
import { z } from "zod"; import { z } from "zod";
import type { ToolCallDetail } from "../../agent-sdk-types.js"; import type { ToolCallDetail } from "../../agent-sdk-types.js";
import type { ProviderImageOutput } from "../provider-image-output.js";
interface BashToolInput { interface BashToolInput {
command: string; command: string;
@@ -53,7 +52,6 @@ interface PiToolResultObject {
stdout?: string; stdout?: string;
text?: string; text?: string;
content?: PiToolResultContent[]; content?: PiToolResultContent[];
structuredContent?: unknown;
exitCode?: number; exitCode?: number;
code?: number; code?: number;
details?: PiToolResultDetails; details?: PiToolResultDetails;
@@ -69,12 +67,6 @@ interface PiToolResultTextContent {
text: string; text: string;
} }
const PiToolResultImageContentSchema = z.object({
type: z.literal("image"),
data: z.string().min(1),
mimeType: z.string().optional(),
});
interface PiToolResultUnknownContent { interface PiToolResultUnknownContent {
type: string; type: string;
} }
@@ -244,61 +236,6 @@ export function parseToolResult(rawResult: unknown): PiToolResult {
return null; 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 { export function extractTextFromToolResult(result: PiToolResult): string | undefined {
if (typeof result === "string") { if (typeof result === "string") {
return result; return result;
-2
View File
@@ -420,7 +420,6 @@ export interface PaseoDaemonConfig {
trustedProxies?: true | string[]; trustedProxies?: true | string[];
mcpEnabled?: boolean; mcpEnabled?: boolean;
mcpInjectIntoAgents?: boolean; mcpInjectIntoAgents?: boolean;
usageEnabled?: boolean;
browserToolsEnabled?: boolean; browserToolsEnabled?: boolean;
git?: { git?: {
maxProcessesPerSecond: number; maxProcessesPerSecond: number;
@@ -591,7 +590,6 @@ function createInitialMutableDaemonConfig(config: ResolvedDaemonSettings): Mutab
...(config.providerCatalogRefreshTimeoutMs !== undefined ...(config.providerCatalogRefreshTimeoutMs !== undefined
? { catalogRefreshTimeoutMs: config.providerCatalogRefreshTimeoutMs } ? { catalogRefreshTimeoutMs: config.providerCatalogRefreshTimeoutMs }
: {}), : {}),
usage: { enabled: config.usageEnabled !== false },
browserTools: { enabled: config.browserToolsEnabled ?? false }, browserTools: { enabled: config.browserToolsEnabled ?? false },
providers, providers,
metadataGeneration: { metadataGeneration: {
-6
View File
@@ -523,10 +523,6 @@ function resolveAppendSystemPrompt(persisted: ReturnType<typeof loadPersistedCon
return persisted.daemon?.appendSystemPrompt ?? ""; return persisted.daemon?.appendSystemPrompt ?? "";
} }
function resolveUsageEnabled(persisted: ReturnType<typeof loadPersistedConfig>): boolean {
return persisted.daemon?.usage?.enabled !== false;
}
function resolveBrowserToolsEnabled(persisted: ReturnType<typeof loadPersistedConfig>): boolean { function resolveBrowserToolsEnabled(persisted: ReturnType<typeof loadPersistedConfig>): boolean {
return persisted.daemon?.browserTools?.enabled ?? false; return persisted.daemon?.browserTools?.enabled ?? false;
} }
@@ -552,7 +548,6 @@ function resolveStaticLoadConfigSettings(
mcpEnabled: cli?.mcpEnabled ?? persisted.daemon?.mcp?.enabled ?? true, mcpEnabled: cli?.mcpEnabled ?? persisted.daemon?.mcp?.enabled ?? true,
mcpInjectIntoAgents: mcpInjectIntoAgents:
cli?.mcpInjectIntoAgents ?? persisted.daemon?.mcp?.injectIntoAgents ?? false, cli?.mcpInjectIntoAgents ?? persisted.daemon?.mcp?.injectIntoAgents ?? false,
usageEnabled: resolveUsageEnabled(persisted),
browserToolsEnabled: resolveBrowserToolsEnabled(persisted), browserToolsEnabled: resolveBrowserToolsEnabled(persisted),
autoArchiveAfterMerge: persisted.daemon?.autoArchiveAfterMerge ?? false, autoArchiveAfterMerge: persisted.daemon?.autoArchiveAfterMerge ?? false,
appendSystemPrompt: resolveAppendSystemPrompt(persisted), appendSystemPrompt: resolveAppendSystemPrompt(persisted),
@@ -581,7 +576,6 @@ export type ResolvedDaemonSettings = Pick<
| "trustedProxies" | "trustedProxies"
| "mcpEnabled" | "mcpEnabled"
| "mcpInjectIntoAgents" | "mcpInjectIntoAgents"
| "usageEnabled"
| "browserToolsEnabled" | "browserToolsEnabled"
| "git" | "git"
| "autoArchiveAfterMerge" | "autoArchiveAfterMerge"
@@ -21,7 +21,6 @@ import {
type HostUpdate, type HostUpdate,
} from "@getpaseo/protocol/hosts"; } from "@getpaseo/protocol/hosts";
import type { DaemonPermission, WSHelloMessage } from "@getpaseo/protocol/messages"; import type { DaemonPermission, WSHelloMessage } from "@getpaseo/protocol/messages";
import { webSocketProxyAgent } from "../network/index.js";
export class HostError extends Error { export class HostError extends Error {
constructor( constructor(
@@ -243,7 +242,6 @@ export class ConnectedHosts {
{ {
clientId: `host-link-${this.self.serverId}-${row.registrationId}`, clientId: `host-link-${this.self.serverId}-${row.registrationId}`,
connectTimeoutMs: 10000, connectTimeoutMs: 10000,
webSocketAgent: webSocketProxyAgent,
}, },
this.budget, this.budget,
); );
@@ -10,10 +10,6 @@ import { readSpeechSettings } from "./speech/speech-settings.js";
import type { PersistedConfig } from "./persisted-config.js"; import type { PersistedConfig } from "./persisted-config.js";
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages"; import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
function usageEnabled(persisted: PersistedConfig): boolean {
return persisted.daemon?.usage?.enabled !== false;
}
function reloadableConfig( function reloadableConfig(
persisted: PersistedConfig, persisted: PersistedConfig,
options: { relayEnabledFallback?: boolean } = {}, options: { relayEnabledFallback?: boolean } = {},
@@ -27,7 +23,6 @@ function reloadableConfig(
enabled: relay.enabled ?? options.relayEnabledFallback ?? true, enabled: relay.enabled ?? options.relayEnabledFallback ?? true,
}, },
mcp: { enabled: true, injectIntoAgents: false }, mcp: { enabled: true, injectIntoAgents: false },
usage: { enabled: usageEnabled(persisted) },
browserTools: { enabled: daemon.browserTools?.enabled ?? false }, browserTools: { enabled: daemon.browserTools?.enabled ?? false },
providers: (agents.providers ?? {}) as MutableDaemonConfig["providers"], providers: (agents.providers ?? {}) as MutableDaemonConfig["providers"],
metadataGeneration: { providers: agents.metadataGeneration?.providers ?? [] }, metadataGeneration: { providers: agents.metadataGeneration?.providers ?? [] },
@@ -1577,31 +1572,3 @@ describe("DaemonConfigStore speech settings", () => {
expect(JSON.stringify(other.get())).not.toContain("secret"); 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,7 +22,6 @@ type ProviderOverride = import("./agent/provider-launch-config.js").ProviderOver
interface SupportedMutableConfigPatch { interface SupportedMutableConfigPatch {
relay?: { enabled?: boolean; requireProtectedSecurity?: boolean }; relay?: { enabled?: boolean; requireProtectedSecurity?: boolean };
mcp?: { injectIntoAgents?: boolean }; mcp?: { injectIntoAgents?: boolean };
usage?: { enabled: boolean };
browserTools?: { enabled?: boolean }; browserTools?: { enabled?: boolean };
providers?: MutableDaemonConfig["providers"]; providers?: MutableDaemonConfig["providers"];
removeProviders?: string[]; removeProviders?: string[];
@@ -183,7 +182,6 @@ const RELOADABLE_PATHS = [
"daemon.relay.requireProtectedSecurity", "daemon.relay.requireProtectedSecurity",
"daemon.mcp.enabled", "daemon.mcp.enabled",
"daemon.mcp.injectIntoAgents", "daemon.mcp.injectIntoAgents",
"daemon.usage.enabled",
"daemon.browserTools.enabled", "daemon.browserTools.enabled",
"daemon.hostnames", "daemon.hostnames",
"daemon.cors.allowedOrigins", "daemon.cors.allowedOrigins",
@@ -211,7 +209,6 @@ const PERSISTED_TO_MUTABLE_PATH = new Map<string, string>([
["daemon.relay.requireProtectedSecurity", "relay.requireProtectedSecurity"], ["daemon.relay.requireProtectedSecurity", "relay.requireProtectedSecurity"],
["daemon.mcp.enabled", "mcp.enabled"], ["daemon.mcp.enabled", "mcp.enabled"],
["daemon.mcp.injectIntoAgents", "mcp.injectIntoAgents"], ["daemon.mcp.injectIntoAgents", "mcp.injectIntoAgents"],
["daemon.usage.enabled", "usage.enabled"],
["daemon.browserTools.enabled", "browserTools.enabled"], ["daemon.browserTools.enabled", "browserTools.enabled"],
["daemon.hostnames", "hostnames"], ["daemon.hostnames", "hostnames"],
["daemon.cors.allowedOrigins", "cors.allowedOrigins"], ["daemon.cors.allowedOrigins", "cors.allowedOrigins"],
@@ -284,7 +281,6 @@ function pickRelayPatch(
function pickSupportedPatchFields(patch: MutableDaemonConfigPatch): SupportedMutableConfigPatch { function pickSupportedPatchFields(patch: MutableDaemonConfigPatch): SupportedMutableConfigPatch {
return { return {
...pickRelayPatch(patch.relay), ...pickRelayPatch(patch.relay),
usage: patch.usage,
...(patch.mcp?.injectIntoAgents !== undefined ...(patch.mcp?.injectIntoAgents !== undefined
? { mcp: { injectIntoAgents: patch.mcp.injectIntoAgents } } ? { mcp: { injectIntoAgents: patch.mcp.injectIntoAgents } }
: {}), : {}),
@@ -771,7 +767,6 @@ function mergeMutableDaemonPatch(
if (patch.mcp?.injectIntoAgents !== undefined) { if (patch.mcp?.injectIntoAgents !== undefined) {
next.mcp = { ...next.mcp, injectIntoAgents: patch.mcp.injectIntoAgents }; next.mcp = { ...next.mcp, injectIntoAgents: patch.mcp.injectIntoAgents };
} }
if (patch.usage) next.usage = patch.usage;
if (patch.browserTools?.enabled !== undefined) { if (patch.browserTools?.enabled !== undefined) {
next.browserTools = { ...next.browserTools, enabled: patch.browserTools.enabled }; next.browserTools = { ...next.browserTools, enabled: patch.browserTools.enabled };
} }
@@ -1,46 +0,0 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { expect, test } from "vitest";
import { createDaemonTestContext } from "../test-utils/index.js";
// #2220: a timeline page is one WebSocket message, so a few huge entries used to close the socket.
test.each([40, 0])(
"fetching image-heavy history with limit %i keeps the direct connection usable",
async (limit) => {
const ctx = await createDaemonTestContext();
const cwd = mkdtempSync(path.join(tmpdir(), "oversized-timeline-"));
try {
const agent = await ctx.client.createAgent({ provider: "codex", cwd });
const imageUrl = `data:image/jpeg;base64,${"A".repeat(14 * 1024 * 1024)}`;
for (let index = 0; index < 5; index += 1) {
await ctx.daemon.daemon.agentManager.appendTimelineItem(agent.id, {
type: "tool_call",
callId: `screenshot-${index}`,
name: "node_repl.js",
status: "completed",
error: null,
detail: {
type: "unknown",
input: { index },
output: { _meta: { "codex/toolSurface": { screenshot: { url: imageUrl } } } },
},
});
}
const page = await ctx.client.fetchAgentTimeline(agent.id, { direction: "tail", limit });
const screenshots = page.entries.filter((entry) => entry.item.type === "tool_call");
expect(screenshots).toHaveLength(5);
for (const entry of screenshots) {
expect(Buffer.byteLength(JSON.stringify(entry.item))).toBeLessThanOrEqual(64 * 1024);
}
const next = await ctx.client.fetchAgentTimeline(agent.id, { direction: "tail", limit: 1 });
expect(next.entries).toHaveLength(1);
} finally {
await ctx.cleanup();
rmSync(cwd, { recursive: true, force: true });
}
},
60_000,
);
@@ -1,6 +1,5 @@
import { appendFileSync, mkdirSync } from "node:fs"; import { appendFileSync, mkdirSync } from "node:fs";
import path from "node:path"; import path from "node:path";
import { initializeEnvironmentProxy } from "./network/index.js";
import { createPaseoDaemon, formatListenTarget } from "./bootstrap.js"; import { createPaseoDaemon, formatListenTarget } from "./bootstrap.js";
import { loadConfig } from "./config.js"; import { loadConfig } from "./config.js";
import { resolvePaseoHome } from "./paseo-home.js"; import { resolvePaseoHome } from "./paseo-home.js";
@@ -133,11 +132,6 @@ function applyCliFlagOverrides(config: ReturnType<typeof loadConfig>): void {
async function main() { async function main() {
const { paseoHome, logger, config } = bootstrapFromEnvironment(); 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 daemon: Awaited<ReturnType<typeof createPaseoDaemon>> | null = null;
let shutdownPromise: Promise<number> | null = null; let shutdownPromise: Promise<number> | null = null;
let exitHookInstalled = false; let exitHookInstalled = false;
@@ -1,6 +1,5 @@
import { WebSocket } from "ws"; import { WebSocket } from "ws";
import { z } from "zod"; import { z } from "zod";
import { webSocketProxyAgent } from "../network/index.js";
import type { WebSocketLike } from "../websocket-server.js"; import type { WebSocketLike } from "../websocket-server.js";
const SOCKET_PING_INTERVAL_MS = 10_000; const SOCKET_PING_INTERVAL_MS = 10_000;
@@ -167,7 +166,6 @@ export class DirectHubRelationshipRemote implements HubRelationshipRemote {
openSocket(input: HubSocketCredentials, events: HubSocketEvents): HubSocketConnection { openSocket(input: HubSocketCredentials, events: HubSocketEvents): HubSocketConnection {
let sessionProtocol: "legacy" | "session-v1" = "legacy"; let sessionProtocol: "legacy" | "session-v1" = "legacy";
const socket = new WebSocket(input.webSocketUrl, { const socket = new WebSocket(input.webSocketUrl, {
agent: webSocketProxyAgent(input.webSocketUrl),
handshakeTimeout: this.requestTimeoutMs, handshakeTimeout: this.requestTimeoutMs,
headers: { headers: {
authorization: `Bearer ${input.credential}`, authorization: `Bearer ${input.credential}`,
-116
View File
@@ -1,116 +0,0 @@
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;
}
@@ -1,341 +0,0 @@
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,7 +259,6 @@ export const PersistedConfigSchema = z
}) })
.passthrough() .passthrough()
.optional(), .optional(),
usage: z.object({ enabled: z.boolean().optional() }).optional(),
browserTools: z browserTools: z
.object({ .object({
enabled: z.boolean().optional(), enabled: z.boolean().optional(),
@@ -24,7 +24,6 @@ import { createPluginClientId } from "./plugin-session-identity.js";
import { PluginSettingsStore } from "./settings/index.js"; import { PluginSettingsStore } from "./settings/index.js";
import { readPluginProviderIcon } from "./provider-icon.js"; import { readPluginProviderIcon } from "./provider-icon.js";
import { initializeEnvironmentProxy } from "../network/index.js";
function describeError(error: unknown): string { function describeError(error: unknown): string {
return error instanceof Error ? error.message : String(error); return error instanceof Error ? error.message : String(error);
} }
@@ -607,7 +606,6 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
const parsed = PluginProcessRequestSchema.safeParse(raw); const parsed = PluginProcessRequestSchema.safeParse(raw);
if (!worker && parsed.success && parsed.data.type === "initialize") { if (!worker && parsed.success && parsed.data.type === "initialize") {
try { try {
initializeEnvironmentProxy();
worker = createPluginWorker({ channel, contribute: evaluateBundle(parsed.data.bundle) }); worker = createPluginWorker({ channel, contribute: evaluateBundle(parsed.data.bundle) });
} catch (error) { } catch (error) {
channel.send({ type: "fatal", error: describeError(error) }); channel.send({ type: "fatal", error: describeError(error) });
@@ -1,31 +0,0 @@
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,11 +1,7 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url"; import { fileURLToPath, pathToFileURL } from "node:url";
import { createServer } from "node:http";
import { once } from "node:events";
import { expect, test } from "vitest"; import { expect, test } from "vitest";
import { DaemonClient } from "../test-utils/daemon-client.js"; import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
@@ -339,74 +335,3 @@ export default function contribute(server) {
await rm(root, { recursive: true, force: true }); await rm(root, { recursive: true, force: true });
} }
}, 60_000); }, 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,7 +2,6 @@
import { WebSocket } from "ws"; import { WebSocket } from "ws";
import type pino from "pino"; import type pino from "pino";
import { buildRelayWebSocketUrl } from "@getpaseo/protocol/daemon-endpoints"; import { buildRelayWebSocketUrl } from "@getpaseo/protocol/daemon-endpoints";
import { webSocketProxyAgent } from "./network/index.js";
import type { ExternalSocketMetadata } from "./websocket-server.js"; import type { ExternalSocketMetadata } from "./websocket-server.js";
export interface RelayTransportOptions { export interface RelayTransportOptions {
@@ -57,7 +56,7 @@ const RELAY_WEBSOCKET_OPTIONS = {
} as const; } as const;
function createDefaultRelayWebSocket(url: string): RelayWebSocketLike { function createDefaultRelayWebSocket(url: string): RelayWebSocketLike {
return new WebSocket(url, { ...RELAY_WEBSOCKET_OPTIONS, agent: webSocketProxyAgent(url) }); return new WebSocket(url, RELAY_WEBSOCKET_OPTIONS);
} }
function isRecord(value: unknown): value is Record<string, unknown> { function isRecord(value: unknown): value is Record<string, unknown> {
-1
View File
@@ -1042,7 +1042,6 @@ export class Session {
logger: this.sessionLogger, logger: this.sessionLogger,
}); });
this.usageSession = new UsageSession({ this.usageSession = new UsageSession({
isEnabled: () => daemonConfigStore.get().usage?.enabled !== false,
emit: (msg) => this.emit(msg), emit: (msg) => this.emit(msg),
runtime: pluginRuntime, runtime: pluginRuntime,
logger: this.sessionLogger, logger: this.sessionLogger,
@@ -15,7 +15,6 @@ test("lists reports from usage sources", async () => {
report: { status: "available" as const, windows: [] }, report: { status: "available" as const, windows: [] },
}; };
const usage = new UsageSession({ const usage = new UsageSession({
isEnabled: () => true,
emit: (message) => emitted.push(message), emit: (message) => emitted.push(message),
runtime: { runtime: {
async listUsageReports(options) { async listUsageReports(options) {
@@ -41,7 +40,6 @@ test("lists reports from usage sources", async () => {
test("surfaces a legacy usage-list failure as an rpc_error envelope", async () => { test("surfaces a legacy usage-list failure as an rpc_error envelope", async () => {
const emitted: SessionOutboundMessage[] = []; const emitted: SessionOutboundMessage[] = [];
const usage = new UsageSession({ const usage = new UsageSession({
isEnabled: () => true,
emit: (message) => emitted.push(message), emit: (message) => emitted.push(message),
runtime: { runtime: {
async listUsageReports() { async listUsageReports() {
@@ -63,7 +61,6 @@ 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 () => { test("request failures terminate with an error response and no updates", async () => {
const emitted: SessionOutboundMessage[] = []; const emitted: SessionOutboundMessage[] = [];
const usage = new UsageSession({ const usage = new UsageSession({
isEnabled: () => true,
emit: (message) => emitted.push(message), emit: (message) => emitted.push(message),
logger: pino({ level: "silent" }), logger: pino({ level: "silent" }),
}); });
@@ -75,36 +72,3 @@ 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,7 +9,6 @@ export interface UsageSessionOptions {
listUsageReports(options: ListUsageReportsOptions): Promise<UsageReportEntry[]>; listUsageReports(options: ListUsageReportsOptions): Promise<UsageReportEntry[]>;
listLegacyUsage(): Promise<{ fetchedAt: string; providers: ProviderUsage[] }>; listLegacyUsage(): Promise<{ fetchedAt: string; providers: ProviderUsage[] }>;
}; };
isEnabled: () => boolean;
logger: pino.Logger; logger: pino.Logger;
} }
@@ -20,7 +19,6 @@ export class UsageSession {
msg: Extract<SessionInboundMessage, { type: "usage.list_reports.request" }>, msg: Extract<SessionInboundMessage, { type: "usage.list_reports.request" }>,
): Promise<void> { ): Promise<void> {
try { 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"); if (!this.options.runtime) throw new Error("Plugin runtime is unavailable");
await this.options.runtime.listUsageReports({ await this.options.runtime.listUsageReports({
forceRefresh: msg.forceRefresh, forceRefresh: msg.forceRefresh,
@@ -51,18 +49,6 @@ export class UsageSession {
async handleLegacyList( async handleLegacyList(
msg: Extract<SessionInboundMessage, { type: "provider.usage.list.request" }>, msg: Extract<SessionInboundMessage, { type: "provider.usage.list.request" }>,
): Promise<void> { ): 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 { try {
if (!this.options.runtime) throw new Error("Plugin runtime is unavailable"); if (!this.options.runtime) throw new Error("Plugin runtime is unavailable");
const usage = await this.options.runtime.listLegacyUsage(); const usage = await this.options.runtime.listLegacyUsage();
@@ -1949,7 +1949,6 @@ export class VoiceAssistantWebSocketServer {
hostMultiplexing: true, hostMultiplexing: true,
// COMPAT(relayProtectedSecurity): added in v0.13.0, remove gate after 2027-04-21. // COMPAT(relayProtectedSecurity): added in v0.13.0, remove gate after 2027-04-21.
relayProtectedSecurity: true, relayProtectedSecurity: true,
usageSetting: true,
usageSources: true, usageSources: true,
ownedSubscriptions: true, ownedSubscriptions: true,
agentRequestReceipts: true, agentRequestReceipts: true,
@@ -536,6 +536,7 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro
const repositoryRoot = fileURLToPath(new URL("../../../../", import.meta.url)); const repositoryRoot = fileURLToPath(new URL("../../../../", import.meta.url));
const source = ` const source = `
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { measureMainThreadWork } from './packages/server/src/test-utils/main-thread-work.ts';
import { write } from 'node:fs'; import { write } from 'node:fs';
import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises'; import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os'; import { tmpdir } from 'node:os';
@@ -579,36 +580,17 @@ 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') })); 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; let fsCalls = 0;
const hook = createHook({ init(_id, type) { if (type.startsWith('FSREQ')) fsCalls++; } }); 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(); await tick();
// Unrelated callbacks must not consume the synchronous filter's budget. const { blockingMs } = await measureMainThreadWork('Git filter main-thread work', async () => {
const threadCpuUsage = Reflect.get(process, 'threadCpuUsage'); await marker('FILTER_START');
const unrelatedWork = tick().then(() => { hook.enable();
const started = threadCpuUsage(); try {
while (true) { callback(null, events);
const cpu = threadCpuUsage(started); } finally {
if (cpu.user + cpu.system >= 80000) break; hook.disable();
await marker('FILTER_END');
} }
}); });
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(fsCalls, 0, "filesystem calls");
assert.equal(notifications, 0, "ignored event notification"); assert.equal(notifications, 0, "ignored event notification");
assert.ok(blockingMs < 20, 'blocking filter work: ' + blockingMs); assert.ok(blockingMs < 20, 'blocking filter work: ' + blockingMs);
@@ -632,7 +614,6 @@ test("Git refresh, command tracing and 10,000 ignored alias events do no synchro
const { stdout, stderr } = await promisify(execFile)( const { stdout, stderr } = await promisify(execFile)(
process.execPath, process.execPath,
[ [
"--expose-gc",
"--import", "--import",
"tsx", "tsx",
...(tracing ? ["--trace-sync-io"] : []), ...(tracing ? ["--trace-sync-io"] : []),
@@ -653,9 +634,7 @@ 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]; const output = stderr.split(`${phase}_START\n`)[1]?.split(`${phase}_END\n`)[0];
expect(output, `${phase}: synchronous filesystem IO`).toBe(""); expect(output, `${phase}: synchronous filesystem IO`).toBe("");
} }
const measurement = JSON.parse(stdout.trim().split("\n")[0]); expect(JSON.parse(stdout.trim().split("\n")[0])).toMatchObject({ fsCalls: 0 });
console.info("Git filter budget", { tracing, ...measurement });
expect(measurement).toMatchObject({ fsCalls: 0 });
} }
}, 60_000); }, 60_000);
@@ -70,14 +70,6 @@
}, },
"additionalProperties": {} "additionalProperties": {}
}, },
"usage": {
"type": "object",
"properties": {
"enabled": {
"type": "boolean"
}
}
},
"browserTools": { "browserTools": {
"type": "object", "type": "object",
"properties": { "properties": {
-148
View File
@@ -557,151 +557,3 @@ index a16dac0..6519858 100644
return ColorScheme.Dark return ColorScheme.Dark
default: default:
return ColorScheme.Unspecified 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,8 +26,6 @@ const patchedPackages = [
// https://github.com/jpudysz/react-native-unistyles/pull/1203. // https://github.com/jpudysz/react-native-unistyles/pull/1203.
// Adaptive themes: keep until colorScheme reads no longer consume listener-owned media changes. // 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. // 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", nodeModulesPath: "node_modules/react-native-unistyles",
patchPrefix: "react-native-unistyles+", patchPrefix: "react-native-unistyles+",