mirror of
https://github.com/getpaseo/paseo.git
synced 2026-10-29 20:52:51 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
213a42e68b | ||
|
|
6eeb1a0e75 | ||
|
|
54dd93ad7a |
@@ -95,8 +95,4 @@ Callout crops are in native capture pixels. To find them, overlay a 100 px grid
|
||||
|
||||
6. Copy the captures into `raw/iphone/` or `raw/ipad/` under the names `render.mjs` uses, render, and check the preview.
|
||||
|
||||
## Publish
|
||||
|
||||
The stable release uploads these exports to the App Store and Google Play, and F-Droid reads the Google ones from the repo. See [Store screenshots](../../docs/release.md#store-screenshots). The Android metadata holds links to the Google exports, and every render rewrites them, so commit the links with the exports.
|
||||
|
||||
Dimensions are checked against [Apple's screenshot specifications](https://developer.apple.com/help/app-store-connect/reference/app-information/screenshot-specifications/) and [Google Play's preview asset requirements](https://support.google.com/googleplay/android-developer/answer/9866151?hl=en).
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// elsewhere point SF_FONT_DIR at a folder holding SFNS.ttf copied from a Mac.
|
||||
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
@@ -23,7 +23,6 @@ const root = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repo = path.resolve(root, "../..");
|
||||
const raw = (device, name) => path.join(root, "raw", device, `${name}.png`);
|
||||
const output = path.join(root, "output");
|
||||
const androidImages = path.join(repo, "fastlane/metadata/android/en-US/images");
|
||||
|
||||
// Native captures per device: iPhone 16 Pro Max at 3x and iPad Pro 13-inch at
|
||||
// 2x. The frame's screen radius and Dynamic Island are in capture pixels.
|
||||
@@ -117,7 +116,6 @@ const STORES = {
|
||||
},
|
||||
google: {
|
||||
device: "iphone",
|
||||
androidScreenshots: "phoneScreenshots",
|
||||
width: 1440,
|
||||
height: 2560,
|
||||
textTop: 150,
|
||||
@@ -136,7 +134,6 @@ const STORES = {
|
||||
},
|
||||
"google-tablet": {
|
||||
device: "ipad",
|
||||
androidScreenshots: "tenInchScreenshots",
|
||||
width: 1800,
|
||||
height: 3200,
|
||||
textTop: 200,
|
||||
@@ -355,18 +352,6 @@ async function expectLines(view, selector, expected, label) {
|
||||
if (lines !== expected) throw new Error(`${label} wraps to ${lines} lines, expected ${expected}`);
|
||||
}
|
||||
|
||||
// Google Play and F-Droid read their screenshots from the Android metadata,
|
||||
// which holds links to these renders. Rewriting the links on every render keeps
|
||||
// added, removed and renamed panels in step with the App Store.
|
||||
async function linkAndroidScreenshots(folder, files) {
|
||||
const dir = path.join(androidImages, folder);
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
await mkdir(dir, { recursive: true });
|
||||
for (const [index, file] of files.entries()) {
|
||||
await symlink(path.relative(dir, file), path.join(dir, `${index + 1}.png`));
|
||||
}
|
||||
}
|
||||
|
||||
async function renderPreview(rows) {
|
||||
const tile = 440;
|
||||
const gap = 40;
|
||||
@@ -402,9 +387,7 @@ try {
|
||||
const marks = await loadAgentMarks(work);
|
||||
const rows = [];
|
||||
for (const [name, store] of Object.entries(STORES)) {
|
||||
const files = await renderStore(browser, name, store, font, marks, work);
|
||||
if (store.androidScreenshots) await linkAndroidScreenshots(store.androidScreenshots, files);
|
||||
rows.push(files);
|
||||
rows.push(await renderStore(browser, name, store, font, marks, work));
|
||||
}
|
||||
await renderPreview(rows);
|
||||
} finally {
|
||||
|
||||
+1
-4
@@ -215,8 +215,7 @@ fastlane/metadata/android/
|
||||
│ ├── images/
|
||||
│ │ ├── icon.png (512x512)
|
||||
│ │ ├── featureGraphic.png (1024x500)
|
||||
│ │ ├── phoneScreenshots/ (1.png, 2.png, ... linked to the store renders)
|
||||
│ │ └── tenInchScreenshots/ (1.png, 2.png, ... linked to the store renders)
|
||||
│ │ └── phoneScreenshots/ (1.png, 2.png, ...)
|
||||
│ └── changelogs/ (generated — see below)
|
||||
├── ja/
|
||||
└── zh-CN/
|
||||
@@ -224,8 +223,6 @@ fastlane/metadata/android/
|
||||
|
||||
Locale directories generally match `packages/app/src/i18n/locales.ts`, but note that `en` becomes `en-US`.
|
||||
|
||||
Google Play reads its screenshots from the same folders; see [Store screenshots](release.md#store-screenshots).
|
||||
|
||||
F-Droid changelogs are generated from `CHANGELOG.md`. Run `npm run fdroid:changelogs`; `npm run fdroid:changelogs:check` verifies without writing. It is wired into the npm `version` lifecycle, so a release picks it up automatically and `git add -A` stages the result.
|
||||
|
||||
One changelog must be generated per-ABI-split, so each version will create **four** identical version-coded entries. F-Droid caps changelogs at 500 characters, so the generator strips some content and adds a link to the full notes.
|
||||
|
||||
@@ -38,6 +38,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
|
||||
- **Usage source** — Plugin registration that discovers accounts and fetches plan usage. Code: `UsageSourceRegistration` (`packages/plugin/src/server/usage.ts`).
|
||||
- **Report ID** — Stable daemon-composed identity for one source account: `<sourceId>:<accountKey>`. The source owns the account key; clients treat the whole ID as opaque. Code: `UsageReportEntry.id` (`packages/protocol/src/messages.ts`).
|
||||
- **Usage report** — A source's normalized usage for one account, including status and optional windows, balances, and details. Its entry carries the Report ID, account label, and fetch time. Each report renders as one card in the Usage modal, in host Settings, and in an agent's context window details (a hover card on desktop web, a tooltip on native wide screens, a sheet on compact ones), which show only the account that agent runs under, without pins. The hover card and the sheet have Refresh; the native tooltip takes no presses. Code: `UsageReport` (`packages/plugin/src/server/usage.ts`), `UsageCard` (`packages/app/src/usage/card.tsx`), `AgentUsage` (`packages/app/src/usage/agent-usage.tsx`).
|
||||
- **Check usage** — Host-wide switch in Usage Settings, on by default. Turning it off stops login discovery and vendor requests on that host for every device. Usage shows an off state with **Turn on**; the sidebar summary and agent usage sections disappear.
|
||||
- **Usage (sidebar item)** — The sidebar footer item showing each pinned window's source icon and percent, hidden while no pinned window has data (the footer's Usage icon remains available); both entry points open the Usage modal over the current screen: a dialog on wide layouts, a bottom sheet on compact ones. Usage has no route of its own. Off until the user turns on **Summary in sidebar** (Usage Settings) or the Usage row in Settings > Sidebar; window rows pin only while it is on, and saved pins come back when it is turned on again. A pin is `{ sourceId, windowId }` and shows once per account of that source. Pins and the used/remaining choice are one per-device preference (`AppSettings.usage`) that every usage surface follows. It reads the active workspace's host, else the first connected host with usage sources. Code: `packages/app/src/usage/sidebar-item.tsx`, `usage/usage-modal.tsx`, `usage/pinned.ts`, `usage/preferences.ts`.
|
||||
- **Model** — A specific LLM offered by a provider. UI: "Model" / "Select model". Code: `AgentModelDefinition` (`packages/protocol/src/messages.ts:187`).
|
||||
- **Tab** — UI surface representing one session inside a workspace. Not a conceptual unit; use **Agent session** when talking about the model. Code: `WorkspaceTabDescriptor` (`packages/app/src/screens/workspace/workspace-tabs-types.ts`).
|
||||
|
||||
@@ -44,15 +44,6 @@ fall back to creating a fresh agent when continuation was requested.
|
||||
Hub owns conversation keys, trigger policy, execution records, and the mapping to workspace/agent
|
||||
IDs. None of these routing concepts are part of the generic daemon RPCs. Creation accepts ordinary
|
||||
provider configuration, exact MCP tool policy, environment, and workspace/worktree selection.
|
||||
|
||||
`server_info.features.optionalMcpSupport` advertises optional MCP launch requirements.
|
||||
Hub sends `toolPolicy.enforcement: "if-supported"` and
|
||||
`mcpServerRequirements: { hub: "optional" }` only when this flag is true.
|
||||
Without it, Hub preserves its existing strict tool-policy request. Available
|
||||
providers remain selectable; providers lacking strict approval support need an
|
||||
updated daemon to launch from Hub. Required external/plugin servers and explicitly
|
||||
required tool policies keep their existing refusal semantics.
|
||||
|
||||
Private session configuration is persisted for recovery and is not exposed in agent snapshots.
|
||||
Provider controls remain provider-native; see [providers.md](providers.md).
|
||||
|
||||
|
||||
+1
-1
@@ -550,7 +550,7 @@ string is never inline SVG or a URL.
|
||||
|
||||
Register a usage source from `index.server.ts` with `server.registerUsageSource()`. Import `UsageSourceRegistration` and normalization helpers from `@getpaseo/plugin/server/usage`. The plugin owns account discovery, harness labels, and credential-store reads; the daemon owns account grouping and the fetch cache. Agent popovers use only the agent's own login. The host-wide Usage modal falls back across an account's logins; any success shows usage only, and all failures show every login's labeled error and remedy. Follow the [usage source discovery contract](../public-docs/plugins/reference.md#usage-sources). The resolved launch environment crosses into the trusted, unsandboxed plugin subprocess for session discovery. Usage queries never run lifecycle hooks. Inputs are validated in the plugin process and remain daemon-side. `icon` uses the same SVG file rules as provider icons.
|
||||
|
||||
The daemon calls discovery for `usage.list_reports`; the client gates this RPC on `server_info.features.usageSources`. The old `provider.usage.list` RPC maps discovered reports for older clients.
|
||||
When the host’s **Check usage** switch is off, the daemon rejects usage requests before discovery, without reading logins or calling vendors. Otherwise, the daemon calls discovery for `usage.list_reports`; the client gates this RPC on `server_info.features.usageSources`. The old `provider.usage.list` RPC maps discovered reports for older clients.
|
||||
|
||||
## Contribute sidebar items
|
||||
|
||||
|
||||
+3
-10
@@ -30,16 +30,9 @@ at session startup. See [provider configuration](custom-providers.md#provider-op
|
||||
for defaults and merge rules, and the [SDK guide](../public-docs/sdk/provider-options.md)
|
||||
for native keys and examples.
|
||||
|
||||
Exact MCP preapproval is a separate daemon-owned contract. A required tool policy
|
||||
(the default) fails closed unless the provider can approve exact injected server/tool
|
||||
identities without approving native tools. Native agent creation also accepts
|
||||
`toolPolicy.enforcement: "if-supported"` for automatic approval convenience:
|
||||
unsupported providers retain ordinary MCP configuration and native permissions.
|
||||
Hub uses that optional request; MCP support and exact approval are not provider
|
||||
eligibility requirements. Optional injection is declared separately with
|
||||
`mcpServerRequirements: { [serverName]: "optional" }`; other injected servers
|
||||
(including plugin-owned servers) keep their required semantics. The daemon
|
||||
advertises this native launch contract as `features.optionalMcpSupport`. The legacy Hub create API remains strict-only.
|
||||
Exact MCP preapproval is a separate daemon-owned contract. A new provider must fail
|
||||
closed for Hub unattended execution until it can approve one exact injected MCP
|
||||
server and tool identity without approving native tools.
|
||||
|
||||
## Core adapter patterns
|
||||
|
||||
|
||||
+2
-13
@@ -305,8 +305,8 @@ macOS 13 maps to Darwin 22. The two values use different version domains; do not
|
||||
|
||||
iOS and Android store builds are not in `.github/workflows`. They are triggered by the EAS GitHub app the moment the `v*` tag is pushed:
|
||||
|
||||
- **Android (Play Store)** — EAS builds with profile `production` and auto-submits to the Play Store via `eas submit` (EAS-managed credentials). A Fastlane lane then replaces the store screenshots.
|
||||
- **iOS (TestFlight + App Store)** — EAS builds with profile `production`, uploads once through a `testflight` job, distributes the build to the `Paseo Beta` external group with Beta App Review submission, and a Fastlane lane uploads the store screenshots and submits that same build for App Store review.
|
||||
- **Android (Play Store)** — EAS builds with profile `production` and auto-submits to the Play Store via `eas submit` (EAS-managed credentials, no Fastlane).
|
||||
- **iOS (TestFlight + App Store)** — EAS builds with profile `production`, uploads once through a `testflight` job, distributes the build to the `Paseo Beta` external group with Beta App Review submission, and a Fastlane lane submits that same build for App Store review.
|
||||
- **Android APK (GitHub Release asset)** — separate, via `.github/workflows/android-apk-release.yml`. This is the only Android-related workflow that lives in this repo.
|
||||
|
||||
EAS uses the local app version source. `packages/app/app.config.js` derives the native version from the package version. Android `versionCode` is `major * 1_000_000 + minor * 1_000 + patch`. iOS reserves 1,000 build slots per app version: beta `N` uses slot `N`, and stable uses slot `999`. For example, `0.2.6-beta.2` appears in App Store Connect as version `0.2.6` build `2006002`; stable uses build `2006999`. Rebuilding the same tag produces the same native build number; if a store has already accepted a binary and you need a different binary, cut the next beta or patch instead of relying on EAS remote auto-increment.
|
||||
@@ -317,16 +317,6 @@ Stable iOS releases use one binary for two Apple review paths: Beta App Review f
|
||||
|
||||
There is no mobile-release workflow under `.github/workflows`. The EAS GitHub app reads the workflows under `packages/app/.eas/workflows` and handles tag triggering directly.
|
||||
|
||||
### Store screenshots
|
||||
|
||||
Each stable release publishes the screenshots committed under `assets/store-screenshots/output/` (see [its README](../assets/store-screenshots/README.md) for how they are made). To change the store screenshots, re-render and commit them before you tag.
|
||||
|
||||
- **App Store:** `submit_review` uploads `output/apple/` and `output/apple-ipad/` to the version it submits, replacing that version's `en-US` screenshots. Apple ties screenshots to an app version, so a version that is already live keeps the ones it shipped with. `Resubmit iOS for App Store review` uploads them again.
|
||||
- **Google Play:** `upload_android_screenshots` runs `fastlane android upload_screenshots` after `submit_android`. It replaces only the phone and 10-inch tablet screenshots, never the listing text or changelogs, and skips images whose checksum already matches.
|
||||
- **F-Droid:** reads the same files as Google Play. `fastlane/metadata/android/en-US/images/phoneScreenshots/` and `tenInchScreenshots/` hold symlinks to the Google renders. `render.mjs` rewrites them on every render, so added or renamed panels reach Google Play and F-Droid as well.
|
||||
|
||||
Fastlane cannot use the Play key Expo stores for `eas submit`. The Play lane reads its own copy of the same service-account key from the `GOOGLE_PLAY_JSON_KEY` file secret in the EAS `production` environment, and that service account needs the Play Console permission **Manage store presence**.
|
||||
|
||||
### Watching mobile builds from the terminal
|
||||
|
||||
Use the EAS CLI from `packages/app/`:
|
||||
@@ -369,7 +359,6 @@ For the `Release Mobile` EAS workflow, these jobs must pass:
|
||||
- `submit_ios_for_review` — iOS build submitted for App Store review via Fastlane
|
||||
- `build_android` — Android store binary built
|
||||
- `submit_android` — Android binary submitted to the Play Store
|
||||
- `upload_android_screenshots` — Google Play screenshots replaced from the repo
|
||||
|
||||
Do not treat `build_ios: SUCCESS` or `distribute_ios: SUCCESS` as a completed iOS release. `submit_ios_for_review: FAILURE` means the iOS release is blocked even if the build is visible in TestFlight.
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
../../../../../../assets/store-screenshots/output/google/01-sidebar.png
|
||||
../../../../../../packages/website/public/phone-1.png
|
||||
@@ -1 +1 @@
|
||||
../../../../../../assets/store-screenshots/output/google/02-chat.png
|
||||
../../../../../../packages/website/public/phone-2.png
|
||||
@@ -1 +1 @@
|
||||
../../../../../../assets/store-screenshots/output/google/03-plugins.png
|
||||
../../../../../../packages/website/public/phone-3.png
|
||||
@@ -1 +0,0 @@
|
||||
../../../../../../assets/store-screenshots/output/google/04-review.png
|
||||
@@ -1 +0,0 @@
|
||||
../../../../../../assets/store-screenshots/output/google/05-terminal.png
|
||||
@@ -1 +0,0 @@
|
||||
../../../../../../assets/store-screenshots/output/google-tablet/01-sidebar.png
|
||||
@@ -1 +0,0 @@
|
||||
../../../../../../assets/store-screenshots/output/google-tablet/02-chat.png
|
||||
@@ -1 +0,0 @@
|
||||
../../../../../../assets/store-screenshots/output/google-tablet/03-plugins.png
|
||||
@@ -1 +0,0 @@
|
||||
../../../../../../assets/store-screenshots/output/google-tablet/04-review.png
|
||||
@@ -1 +0,0 @@
|
||||
../../../../../../assets/store-screenshots/output/google-tablet/05-terminal.png
|
||||
@@ -42,20 +42,6 @@ jobs:
|
||||
build_id: ${{ needs.build_android.outputs.build_id }}
|
||||
profile: production
|
||||
|
||||
upload_android_screenshots:
|
||||
name: Upload Google Play screenshots
|
||||
needs: [build_android, submit_android]
|
||||
environment: production
|
||||
runs_on: macos-medium
|
||||
steps:
|
||||
- uses: eas/checkout
|
||||
- name: Install fastlane
|
||||
run: bundle install
|
||||
- name: Upload screenshots
|
||||
run: |
|
||||
export ANDROID_VERSION_CODE="${{ needs.build_android.outputs.app_build_version }}"
|
||||
bundle exec fastlane android upload_screenshots
|
||||
|
||||
submit_ios_for_review:
|
||||
name: Submit iOS for App Store review
|
||||
needs: [build_ios, distribute_ios]
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
|
||||
import { installUsageReportsFixture } from "../support/helpers/usage-reports";
|
||||
import {
|
||||
claudeAndCodexReports,
|
||||
openUsageFromIcon,
|
||||
openUsageOptions,
|
||||
closeUsageOptions,
|
||||
closeUsage,
|
||||
expectNoUsageItem,
|
||||
expectPinnedUsage,
|
||||
} from "../support/helpers/usage-sidebar-item";
|
||||
|
||||
test("Check usage applies to the host and Turn on restores cards", async ({
|
||||
page,
|
||||
e2eWorkerClient,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
const previous = (await e2eWorkerClient.getDaemonConfig()).config.usage ?? { enabled: true };
|
||||
try {
|
||||
const usage = await installUsageReportsFixture(page, {
|
||||
lists: [() => claudeAndCodexReports()],
|
||||
});
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
|
||||
await gotoAppShell(page);
|
||||
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
|
||||
await openUsageFromIcon(page);
|
||||
await usage.waitForListRequests(1);
|
||||
await openUsageOptions(page);
|
||||
await page.getByRole("switch", { name: "Check usage", exact: true }).click();
|
||||
await closeUsageOptions(page);
|
||||
await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toHaveCount(0);
|
||||
expect((await e2eWorkerClient.getDaemonConfig()).config.usage).toEqual({ enabled: false });
|
||||
await expectNoUsageItem(page);
|
||||
const before = usage.listRequests().length;
|
||||
await closeUsage(page);
|
||||
await page.reload();
|
||||
await openUsageFromIcon(page);
|
||||
await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible();
|
||||
expect(usage.listRequests()).toHaveLength(before);
|
||||
await page.getByRole("button", { name: "Turn on", exact: true }).click();
|
||||
await expect(page.getByText("Claude", { exact: true })).toBeVisible();
|
||||
expect((await e2eWorkerClient.getDaemonConfig()).config.usage).toEqual({ enabled: true });
|
||||
// A separate client changes the policy, as another device would.
|
||||
await e2eWorkerClient.patchDaemonConfig({ usage: { enabled: false } });
|
||||
await expect(page.getByRole("button", { name: "Turn on", exact: true })).toBeVisible();
|
||||
await e2eWorkerClient.patchDaemonConfig({ usage: { enabled: true } });
|
||||
await expect(page.getByText("Claude", { exact: true })).toBeVisible();
|
||||
} finally {
|
||||
await e2eWorkerClient.patchDaemonConfig({ usage: previous });
|
||||
}
|
||||
});
|
||||
|
||||
test("older hosts keep usage without a Check usage switch", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await installUsageReportsFixture(page, {
|
||||
usageSettingSupported: false,
|
||||
lists: [() => claudeAndCodexReports()],
|
||||
});
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await gotoAppShell(page);
|
||||
await openUsageFromIcon(page);
|
||||
await expect(page.getByText("Claude", { exact: true })).toBeVisible();
|
||||
await openUsageOptions(page);
|
||||
await expect(page.getByRole("switch", { name: "Check usage", exact: true })).toHaveCount(0);
|
||||
});
|
||||
@@ -441,3 +441,31 @@ test("released hosts supply source logos through the client conversion", async (
|
||||
).toHaveAttribute("d", codexPath);
|
||||
await qaScreenshot(page, "released-host-usage-modal");
|
||||
});
|
||||
|
||||
test("hidden usage sends no requests until opened", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] });
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoAppShell(page);
|
||||
await expectNoUsageItem(page);
|
||||
await expect(page.getByRole("button", { name: "Usage", exact: true })).toBeVisible({
|
||||
timeout: 90_000,
|
||||
});
|
||||
await openSidebarNavSettings(page);
|
||||
await expectFooterItemSetting(page, "usage", false);
|
||||
await leaveSettings(page);
|
||||
expect(usage.listRequests()).toHaveLength(0);
|
||||
await openUsageFromIcon(page);
|
||||
await usage.waitForListRequests(1);
|
||||
expect(usage.listRequests()).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("visible usage summary requests reports on load", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
const usage = await installUsageReportsFixture(page, { lists: [() => claudeAndCodexReports()] });
|
||||
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoAppShell(page);
|
||||
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
|
||||
expect(usage.listRequests()).toHaveLength(1);
|
||||
});
|
||||
|
||||
@@ -28,6 +28,10 @@ interface SeedProjectDescriptor {
|
||||
* prefer those wrappers over reaching for this client directly.
|
||||
*/
|
||||
export interface SeedDaemonClient {
|
||||
patchDaemonConfig(
|
||||
config: import("@getpaseo/protocol/messages").MutableDaemonConfigPatch,
|
||||
): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>;
|
||||
getDaemonConfig(): Promise<{ config: import("@getpaseo/protocol/messages").MutableDaemonConfig }>;
|
||||
connect(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
addProject(cwd: string): Promise<{
|
||||
|
||||
@@ -25,6 +25,7 @@ interface UsageReportsFixtureOptions {
|
||||
* app connects, so a reload can switch it.
|
||||
*/
|
||||
usageSupported?: boolean | (() => boolean);
|
||||
usageSettingSupported?: boolean;
|
||||
/** Released hosts expose provider.usage.list with no source icons. */
|
||||
providerUsageListOnly?: boolean;
|
||||
/** The host daemon's port; defaults to the E2E daemon. */
|
||||
@@ -63,6 +64,7 @@ function withUsageSupportFeature(
|
||||
message: WebSocketMessage,
|
||||
enabled: boolean,
|
||||
providerUsageListOnly: boolean,
|
||||
usageSettingSupported: boolean,
|
||||
): string | null {
|
||||
const envelope = parseJson(message) as {
|
||||
type?: unknown;
|
||||
@@ -86,6 +88,7 @@ function withUsageSupportFeature(
|
||||
...payload,
|
||||
features: {
|
||||
...features,
|
||||
usageSetting: usageSettingSupported ? true : undefined,
|
||||
usageSources: enabled && !providerUsageListOnly,
|
||||
providerUsageList: enabled,
|
||||
},
|
||||
@@ -229,7 +232,12 @@ export async function installUsageReportsFixture(
|
||||
server.onMessage((message) => {
|
||||
const serverInfo =
|
||||
typeof message === "string"
|
||||
? withUsageSupportFeature(message, isUsageSupported(), providerUsageListOnly)
|
||||
? withUsageSupportFeature(
|
||||
message,
|
||||
isUsageSupported(),
|
||||
providerUsageListOnly,
|
||||
options.usageSettingSupported ?? true,
|
||||
)
|
||||
: null;
|
||||
ws.send(serverInfo ?? message);
|
||||
});
|
||||
|
||||
@@ -1,31 +1,7 @@
|
||||
require "fileutils"
|
||||
require "tmpdir"
|
||||
|
||||
default_platform(:ios)
|
||||
|
||||
APP_IDENTIFIER = "sh.paseo"
|
||||
|
||||
# Store screenshots are rendered into assets/store-screenshots/output; see the
|
||||
# README there. Google Play and F-Droid both read fastlane/metadata/android at
|
||||
# the repo root, whose screenshot files link to those renders.
|
||||
REPO_ROOT = File.expand_path("../../..", __dir__)
|
||||
STORE_SCREENSHOTS = File.join(REPO_ROOT, "assets/store-screenshots/output")
|
||||
ANDROID_METADATA = File.join(REPO_ROOT, "fastlane/metadata/android")
|
||||
|
||||
# deliver reads screenshots from one folder per language and picks the device
|
||||
# slot from each image's size, so both Apple sets go into en-US together.
|
||||
def stage_app_store_screenshots
|
||||
root = Dir.mktmpdir("app-store-screenshots")
|
||||
locale = File.join(root, "en-US")
|
||||
FileUtils.mkdir_p(locale)
|
||||
{ "apple" => "iphone", "apple-ipad" => "ipad" }.each do |set, device|
|
||||
Dir.glob(File.join(STORE_SCREENSHOTS, set, "*.png")).sort.each do |file|
|
||||
FileUtils.cp(file, File.join(locale, "#{device}-#{File.basename(file)}"))
|
||||
end
|
||||
end
|
||||
root
|
||||
end
|
||||
|
||||
platform :ios do
|
||||
desc "Submit the latest TestFlight build to App Store Review"
|
||||
lane :submit_review do
|
||||
@@ -111,8 +87,7 @@ platform :ios do
|
||||
},
|
||||
force: true,
|
||||
skip_binary_upload: true,
|
||||
screenshots_path: stage_app_store_screenshots,
|
||||
overwrite_screenshots: true,
|
||||
skip_screenshots: true,
|
||||
precheck_include_in_app_purchases: false,
|
||||
submission_information: {
|
||||
add_id_info_uses_idfa: false,
|
||||
@@ -121,25 +96,3 @@ platform :ios do
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
platform :android do
|
||||
desc "Replace the Google Play store screenshots with the ones in the repo"
|
||||
lane :upload_screenshots do
|
||||
# supply attaches listing changes to a release on the production track.
|
||||
# The release workflow passes the version code it just submitted; without
|
||||
# it, supply uses the track's only release.
|
||||
version_code = ENV["ANDROID_VERSION_CODE"].to_s.strip
|
||||
supply(
|
||||
package_name: APP_IDENTIFIER,
|
||||
json_key: ENV.fetch("GOOGLE_PLAY_JSON_KEY"),
|
||||
metadata_path: ANDROID_METADATA,
|
||||
version_code: version_code.empty? ? nil : version_code.to_i,
|
||||
skip_upload_apk: true,
|
||||
skip_upload_aab: true,
|
||||
skip_upload_metadata: true,
|
||||
skip_upload_changelogs: true,
|
||||
skip_upload_images: true,
|
||||
sync_image_upload: true,
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -64,12 +64,7 @@ import { useCloseAgentListGesture } from "@/mobile-panels/gestures";
|
||||
import { MobilePanelOverlay } from "@/mobile-panels/presentation";
|
||||
import { buildSettingsAddHostRoute, buildSettingsRoute } from "@/utils/host-routes";
|
||||
import { openHostOverview } from "@/navigation/settings-navigation";
|
||||
import {
|
||||
UsageSidebarItem,
|
||||
UsageSidebarRoot,
|
||||
useHasUsageSummary,
|
||||
useOpenSidebarUsage,
|
||||
} from "@/usage";
|
||||
import { UsageSidebarItem, UsageSidebarRoot, useUsageSummary, useOpenSidebarUsage } from "@/usage";
|
||||
import { SidebarAgentListSkeleton } from "./sidebar-agent-list-skeleton";
|
||||
import { SidebarCalloutSlot } from "./sidebar-callout-slot";
|
||||
import { SidebarWorkspaceList } from "./sidebar-workspace-list";
|
||||
@@ -480,10 +475,10 @@ function SidebarUsageIcon({ label }: { label: string }) {
|
||||
*/
|
||||
function SidebarFooterRows({ onBeforeNavigate }: { onBeforeNavigate?: () => void }) {
|
||||
const { items } = useSidebarNavItems("footer");
|
||||
const hasUsageSummary = useHasUsageSummary();
|
||||
const usageSummary = useUsageSummary();
|
||||
const rowsRef = useRef<View | null>(null);
|
||||
const visibleItems = items.filter(
|
||||
(item) => item.visible && (item.kind === "plugin" || hasUsageSummary),
|
||||
(item) => item.visible && (item.kind === "plugin" || usageSummary.length > 0),
|
||||
);
|
||||
if (visibleItems.length === 0) return null;
|
||||
return (
|
||||
@@ -499,7 +494,7 @@ function SidebarFooterRows({ onBeforeNavigate }: { onBeforeNavigate?: () => void
|
||||
onBeforeNavigate={onBeforeNavigate}
|
||||
/>
|
||||
) : (
|
||||
<UsageSidebarItem key={item.key} />
|
||||
<UsageSidebarItem key={item.key} sources={usageSummary} />
|
||||
),
|
||||
)}
|
||||
</View>
|
||||
|
||||
@@ -2092,6 +2092,11 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
},
|
||||
providerUsage: {
|
||||
checkUsage: "التحقق من الاستخدام",
|
||||
checkUsageHint: "ينطبق على {{host}} على جميع الأجهزة",
|
||||
off: "التحقق من الاستخدام متوقف على {{host}}.",
|
||||
turnOn: "تشغيل",
|
||||
|
||||
options: "الإعدادات",
|
||||
refreshFailed: "تعذّر تحديث الاستخدام",
|
||||
noHosts: "لا توجد مضيفات متصلة",
|
||||
|
||||
@@ -2117,6 +2117,11 @@ export const en = {
|
||||
},
|
||||
},
|
||||
providerUsage: {
|
||||
checkUsage: "Check usage",
|
||||
checkUsageHint: "Applies to {{host}} on every device",
|
||||
off: "Usage is off on {{host}}.",
|
||||
turnOn: "Turn on",
|
||||
|
||||
options: "Settings",
|
||||
refreshFailed: "Unable to refresh usage",
|
||||
noHosts: "No connected hosts",
|
||||
|
||||
@@ -2140,6 +2140,11 @@ export const es: TranslationResources = {
|
||||
},
|
||||
},
|
||||
providerUsage: {
|
||||
checkUsage: "Consultar uso",
|
||||
checkUsageHint: "Se aplica a {{host}} en todos los dispositivos",
|
||||
off: "El uso está desactivado en {{host}}.",
|
||||
turnOn: "Activar",
|
||||
|
||||
options: "Configuración",
|
||||
refreshFailed: "No se pudo actualizar el uso",
|
||||
noHosts: "No hay hosts conectados",
|
||||
|
||||
@@ -2140,6 +2140,11 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
},
|
||||
providerUsage: {
|
||||
checkUsage: "Vérifier l’utilisation",
|
||||
checkUsageHint: "S’applique à {{host}} sur tous les appareils",
|
||||
off: "L’utilisation est désactivée sur {{host}}.",
|
||||
turnOn: "Activer",
|
||||
|
||||
options: "Paramètres",
|
||||
refreshFailed: "Impossible d’actualiser l’utilisation",
|
||||
noHosts: "Aucun hôte connecté",
|
||||
|
||||
@@ -2113,6 +2113,11 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
},
|
||||
providerUsage: {
|
||||
checkUsage: "使用状況を確認",
|
||||
checkUsageHint: "すべてのデバイスで {{host}} に適用",
|
||||
off: "{{host}} の使用状況確認はオフです。",
|
||||
turnOn: "オンにする",
|
||||
|
||||
options: "設定",
|
||||
refreshFailed: "使用状況を更新できません",
|
||||
noHosts: "接続中のホストがありません",
|
||||
|
||||
@@ -2102,6 +2102,11 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
},
|
||||
providerUsage: {
|
||||
checkUsage: "사용량 확인",
|
||||
checkUsageHint: "모든 기기에서 {{host}}에 적용",
|
||||
off: "{{host}}의 사용량 확인이 꺼져 있습니다.",
|
||||
turnOn: "켜기",
|
||||
|
||||
options: "설정",
|
||||
refreshFailed: "사용량을 새로 고칠 수 없습니다",
|
||||
noHosts: "연결된 호스트가 없습니다",
|
||||
|
||||
@@ -2125,6 +2125,11 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
},
|
||||
providerUsage: {
|
||||
checkUsage: "Consultar uso",
|
||||
checkUsageHint: "Aplica-se a {{host}} em todos os dispositivos",
|
||||
off: "O uso está desativado em {{host}}.",
|
||||
turnOn: "Ativar",
|
||||
|
||||
options: "Configurações",
|
||||
refreshFailed: "Não foi possível atualizar o uso",
|
||||
noHosts: "Nenhum host conectado",
|
||||
|
||||
@@ -2125,6 +2125,11 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
},
|
||||
providerUsage: {
|
||||
checkUsage: "Проверять использование",
|
||||
checkUsageHint: "Применяется к {{host}} на всех устройствах",
|
||||
off: "Проверка использования отключена на {{host}}.",
|
||||
turnOn: "Включить",
|
||||
|
||||
options: "Настройки",
|
||||
refreshFailed: "Не удалось обновить использование",
|
||||
noHosts: "Нет подключённых хостов",
|
||||
|
||||
@@ -2070,6 +2070,11 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
},
|
||||
providerUsage: {
|
||||
checkUsage: "检查用量",
|
||||
checkUsageHint: "在所有设备上应用于 {{host}}",
|
||||
off: "{{host}} 的用量检查已关闭。",
|
||||
turnOn: "开启",
|
||||
|
||||
options: "设置",
|
||||
refreshFailed: "无法刷新用量",
|
||||
noHosts: "没有已连接的主机",
|
||||
|
||||
@@ -21,10 +21,12 @@ export interface UsageHostSelection {
|
||||
*/
|
||||
export function UsageControls({
|
||||
view,
|
||||
serverId,
|
||||
onRefresh,
|
||||
hostSelection,
|
||||
}: {
|
||||
view: UsageView;
|
||||
serverId: string;
|
||||
onRefresh: () => void;
|
||||
hostSelection?: UsageHostSelection;
|
||||
}) {
|
||||
@@ -43,8 +45,8 @@ export function UsageControls({
|
||||
) : null}
|
||||
{view.kind === "unavailable" ? null : (
|
||||
<>
|
||||
<UsageRefreshButton busy={busy} onRefresh={onRefresh} />
|
||||
<UsageOptions />
|
||||
{view.kind === "off" ? null : <UsageRefreshButton busy={busy} onRefresh={onRefresh} />}
|
||||
<UsageOptions serverId={serverId} />
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
@@ -84,7 +86,12 @@ export function useHostUsageWithControls(hostSelection: UsageHostSelection): {
|
||||
const controls = useMemo(
|
||||
() =>
|
||||
hasControls ? (
|
||||
<UsageControls view={view} onRefresh={refresh} hostSelection={hostSelection} />
|
||||
<UsageControls
|
||||
serverId={hostSelection.serverId}
|
||||
view={view}
|
||||
onRefresh={refresh}
|
||||
hostSelection={hostSelection}
|
||||
/>
|
||||
) : null,
|
||||
[hasControls, hostSelection, refresh, view],
|
||||
);
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useAppSettings } from "@/hooks/use-settings";
|
||||
import { useUsageHostId } from "./hosts";
|
||||
import { useUsageHostReports } from "./queries";
|
||||
import {
|
||||
isUsagePinned,
|
||||
setUsageDisplayAs,
|
||||
@@ -25,12 +23,6 @@ interface UsagePreferencesState {
|
||||
display: UsageDisplay;
|
||||
}
|
||||
|
||||
/** The device's usage preferences, with pins resolved against a host's reports. */
|
||||
export function useUsagePreferences(serverId?: string): UsagePreferencesState {
|
||||
const defaultServerId = useUsageHostId();
|
||||
return useUsageDisplay(useUsageHostReports(serverId ?? defaultServerId));
|
||||
}
|
||||
|
||||
/** The device's usage preferences, with pins resolved against the given reports. */
|
||||
export function useUsageDisplay(reports: readonly UsageReportEntry[]): UsagePreferencesState {
|
||||
const { settings, updateSettings } = useAppSettings();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useUsagePreferences } from "./display";
|
||||
import { useUsageDisplay } from "./display";
|
||||
import { useHostUsage } from "./queries";
|
||||
import { UsageSection } from "./usage-section";
|
||||
|
||||
@@ -7,7 +7,7 @@ import { UsageSection } from "./usage-section";
|
||||
export function HostUsageSection({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const { view, refresh } = useHostUsage(serverId);
|
||||
const { display } = useUsagePreferences(serverId);
|
||||
const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []);
|
||||
return (
|
||||
<UsageSection
|
||||
serverId={serverId}
|
||||
|
||||
@@ -4,6 +4,6 @@ export { useHostReportsUsage } from "./queries";
|
||||
export {
|
||||
UsageSidebarItem,
|
||||
UsageSidebarRoot,
|
||||
useHasUsageSummary,
|
||||
useUsageSummary,
|
||||
useOpenSidebarUsage,
|
||||
} from "./sidebar-item";
|
||||
|
||||
@@ -405,3 +405,15 @@ it("available and retained usage show the same successful completion time", () =
|
||||
);
|
||||
expect(upsertReport([failure], success)).toEqual([failure]);
|
||||
});
|
||||
|
||||
it("disabled host shows off even with cached reports", () => {
|
||||
expect(
|
||||
resolveUsageView({
|
||||
hostLabel: "Laptop",
|
||||
isConnected: true,
|
||||
supportsUsage: true,
|
||||
enabled: false,
|
||||
query: { data: [], error: null, isFetching: false },
|
||||
}),
|
||||
).toMatchObject({ kind: "off" });
|
||||
});
|
||||
|
||||
@@ -106,6 +106,7 @@ export interface UsageQueryState {
|
||||
|
||||
export function resolveUsageView(
|
||||
input: {
|
||||
enabled?: boolean;
|
||||
hostLabel: string;
|
||||
isConnected: boolean;
|
||||
supportsUsage: boolean;
|
||||
@@ -125,6 +126,8 @@ export function resolveUsageView(
|
||||
message: t("providerUsage.hostUpgradeRequired", { host: hostLabel }),
|
||||
};
|
||||
}
|
||||
if (input.enabled === false)
|
||||
return { kind: "off", message: t("providerUsage.off", { host: hostLabel }) };
|
||||
if (query?.data) {
|
||||
return { kind: "ready", reports: query.data, isRefreshing: query.isFetching };
|
||||
}
|
||||
|
||||
@@ -8,15 +8,20 @@ import { ToolbarButton, paneContentToolbarIconSize } from "@/components/ui/pane-
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { SettingsRow, SettingsSwitch } from "@/components/settings";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { useUsagePreferences } from "./display";
|
||||
import { useUsageSetting } from "./setting";
|
||||
import { useUsageDisplay } from "./display";
|
||||
import { useUsageInSidebar } from "./in-sidebar";
|
||||
import type { UsageDisplayAs } from "./preferences";
|
||||
|
||||
const ThemedSettings = withUnistyles(Settings);
|
||||
|
||||
/** The shared usage preferences, opened from a cog as a popover or compact sheet. */
|
||||
export function UsageOptions() {
|
||||
export function UsageOptions({ serverId }: { serverId: string | null }) {
|
||||
const setting = useUsageSetting(serverId);
|
||||
const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId;
|
||||
const { t } = useTranslation();
|
||||
const displayAsOptions: SegmentedControlOption<UsageDisplayAs>[] = [
|
||||
{ value: "used", label: t("providerUsage.displayUsed"), testID: "usage-display-used" },
|
||||
@@ -27,7 +32,7 @@ export function UsageOptions() {
|
||||
},
|
||||
];
|
||||
const compact = useIsCompactFormFactor();
|
||||
const { display } = useUsagePreferences();
|
||||
const { display } = useUsageDisplay([]);
|
||||
const { inSidebar, setInSidebar } = useUsageInSidebar();
|
||||
return (
|
||||
<DropdownMenu compactMode="sheet">
|
||||
@@ -49,13 +54,25 @@ export function UsageOptions() {
|
||||
testID="usage-options-surface"
|
||||
>
|
||||
<View testID="usage-options-fields">
|
||||
<SettingsSwitch
|
||||
label={t("providerUsage.showInSidebar")}
|
||||
hint={t("providerUsage.showInSidebarHint")}
|
||||
value={inSidebar}
|
||||
onValueChange={setInSidebar}
|
||||
testID="usage-show-in-sidebar"
|
||||
/>
|
||||
{setting.error ? <Alert variant="error" description={setting.error.message} /> : null}
|
||||
{setting.supported ? (
|
||||
<SettingsSwitch
|
||||
label={t("providerUsage.checkUsage")}
|
||||
hint={t("providerUsage.checkUsageHint", { host: hostLabel })}
|
||||
disabled={!setting.ready}
|
||||
value={setting.enabled}
|
||||
onValueChange={setting.setEnabled}
|
||||
/>
|
||||
) : null}
|
||||
<View style={setting.supported ? settingsStyles.rowBorder : undefined}>
|
||||
<SettingsSwitch
|
||||
label={t("providerUsage.showInSidebar")}
|
||||
hint={t("providerUsage.showInSidebarHint")}
|
||||
value={inSidebar}
|
||||
onValueChange={setInSidebar}
|
||||
testID="usage-show-in-sidebar"
|
||||
/>
|
||||
</View>
|
||||
<View style={settingsStyles.rowBorder}>
|
||||
<SettingsRow label={t("providerUsage.displayAs")}>
|
||||
<SegmentedControl
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
useHosts,
|
||||
} from "@/runtime/host-runtime";
|
||||
import { useSessionStore, type SessionState } from "@/stores/session-store";
|
||||
import { useUsageSetting } from "./setting";
|
||||
import { usageCopy } from "./copy";
|
||||
import {
|
||||
replaceReport,
|
||||
@@ -132,13 +133,14 @@ function toQueryState(query: {
|
||||
|
||||
/** Usage reports for one host, as shown on its settings page. */
|
||||
export function useHostUsage(serverId: string): { view: UsageView; refresh: () => void } {
|
||||
const setting = useUsageSetting(serverId);
|
||||
const queryClient = useQueryClient();
|
||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||
const isSupported = useSessionStore((state) => supportsUsage(state.sessions[serverId]));
|
||||
const query = useFetchQuery({
|
||||
queryKey: usageReportsQueryKey(serverId),
|
||||
queryFn: () => listReports(queryClient, serverId),
|
||||
enabled: isConnected && isSupported,
|
||||
enabled: isConnected && isSupported && setting.enabled,
|
||||
dataShape: "list",
|
||||
staleTimeMs: REPORTS_STALE_TIME_MS,
|
||||
});
|
||||
@@ -150,6 +152,7 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
|
||||
const view = resolveUsageView(
|
||||
{
|
||||
hostLabel,
|
||||
enabled: setting.ready ? setting.enabled : undefined,
|
||||
isConnected,
|
||||
supportsUsage: isSupported,
|
||||
query: toQueryState(query),
|
||||
@@ -166,14 +169,16 @@ const NO_REPORTS: UsageReportEntry[] = [];
|
||||
* load, or without a host.
|
||||
*/
|
||||
export function useUsageHostReports(serverId: string | null): UsageReportEntry[] {
|
||||
const setting = useUsageSetting(serverId);
|
||||
const queryClient = useQueryClient();
|
||||
const query = useFetchQuery({
|
||||
enabled: setting.enabled,
|
||||
queryKey: usageReportsQueryKey(serverId ?? ""),
|
||||
queryFn: serverId ? () => listReports(queryClient, serverId) : skipToken,
|
||||
dataShape: "list",
|
||||
staleTimeMs: REPORTS_STALE_TIME_MS,
|
||||
});
|
||||
return query.data ?? NO_REPORTS;
|
||||
return setting.enabled ? (query.data ?? NO_REPORTS) : NO_REPORTS;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -209,7 +214,8 @@ export function useAgentUsage(serverId: string, agentId: string): AgentUsageView
|
||||
export function useHostReportsUsage(serverId: string): boolean {
|
||||
const isConnected = useHostRuntimeIsConnected(serverId);
|
||||
const isSupported = useSessionStore((state) => supportsUsage(state.sessions[serverId]));
|
||||
return isConnected && isSupported;
|
||||
const setting = useUsageSetting(serverId);
|
||||
return isConnected && isSupported && setting.enabled;
|
||||
}
|
||||
|
||||
/** Every host with whether it is connected and reports usage, in host order. */
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useCallback } from "react";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
|
||||
/** Host policy comes from the live daemon config replica. */
|
||||
export function useUsageSetting(serverId: string | null) {
|
||||
const supported = useSessionStore((state) =>
|
||||
Boolean(serverId && state.sessions[serverId]?.serverInfo?.features?.usageSetting),
|
||||
);
|
||||
const { config, patchConfig } = useDaemonConfig(supported ? serverId : null);
|
||||
const mutation = useMutation({
|
||||
mutationFn: (enabled: boolean) => patchConfig({ usage: { enabled } }),
|
||||
});
|
||||
const setEnabled = mutation.mutate;
|
||||
const turnOn = useCallback(() => setEnabled(true), [setEnabled]);
|
||||
return {
|
||||
supported,
|
||||
error: mutation.error,
|
||||
// COMPAT(usageSetting): added in v0.14, remove after 2027-05-01.
|
||||
enabled: !supported || (config !== null && config.usage?.enabled !== false),
|
||||
ready: !supported || config !== null,
|
||||
setEnabled,
|
||||
turnOn,
|
||||
};
|
||||
}
|
||||
@@ -17,7 +17,8 @@ import {
|
||||
} from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model";
|
||||
import { useUsagePreferences } from "./display";
|
||||
import { useUsageDisplay } from "./display";
|
||||
import { useUsageInSidebar } from "./in-sidebar";
|
||||
import { useUsageHostId } from "./hosts";
|
||||
import { useUsageHostReports } from "./queries";
|
||||
import { UsageSourceIcon } from "./source-icon";
|
||||
@@ -33,28 +34,24 @@ import {
|
||||
import { UsageModal } from "./usage-modal";
|
||||
|
||||
/** Each summary window with data on the usage host, under its source; empty while none has. */
|
||||
function useUsageSummary(): readonly PinnedUsageSource[] {
|
||||
export function useUsageSummary(): readonly PinnedUsageSource[] {
|
||||
const { t } = useTranslation();
|
||||
const { preferences } = useUsagePreferences();
|
||||
const reports = useUsageHostReports(useUsageHostId());
|
||||
const { inSidebar } = useUsageInSidebar();
|
||||
const serverId = useUsageHostId();
|
||||
const reports = useUsageHostReports(inSidebar ? serverId : null);
|
||||
const { preferences } = useUsageDisplay(reports);
|
||||
return useMemo(() => resolvePinnedUsage(reports, preferences, t), [preferences, reports, t]);
|
||||
}
|
||||
|
||||
/** Whether the sidebar Usage item has anything to show. */
|
||||
export function useHasUsageSummary(): boolean {
|
||||
return useUsageSummary().length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sidebar footer's usage entry: each summary window's source icon and percent, and nothing
|
||||
* while no summary window has data, since the footer's Usage icon already opens Usage.
|
||||
* Pressing it opens the Usage modal.
|
||||
*/
|
||||
export function UsageSidebarItem() {
|
||||
export function UsageSidebarItem({ sources }: { sources: readonly PinnedUsageSource[] }) {
|
||||
const { t } = useTranslation();
|
||||
const label = t(builtinSidebarNavLabelKey("usage"));
|
||||
const openUsage = useOpenSidebarUsage();
|
||||
const sources = useUsageSummary();
|
||||
if (sources.length === 0) return null;
|
||||
return <PinnedUsageTrigger label={label} sources={sources} onPress={openUsage} />;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ export type UsageBalanceUnit = UsageBalance["unit"];
|
||||
|
||||
/** What a host's usage surface shows. `unavailable` is a host state, not a failed request. */
|
||||
export type UsageView =
|
||||
| { kind: "off"; message: string }
|
||||
| { kind: "unavailable"; message: string }
|
||||
| { kind: "loading" }
|
||||
| { kind: "error"; message: string }
|
||||
|
||||
@@ -4,7 +4,7 @@ import { View } from "react-native";
|
||||
import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet";
|
||||
import { builtinSidebarNavLabelKey } from "@/sidebar-nav/model";
|
||||
import { useHostUsageWithControls } from "./controls";
|
||||
import { useUsagePreferences } from "./display";
|
||||
import { useUsageDisplay } from "./display";
|
||||
import { useUsageHostSelection } from "./hosts";
|
||||
import type { UsageHost } from "./model";
|
||||
import { UsageBody, UsageMessage } from "./usage-section";
|
||||
@@ -52,12 +52,12 @@ function HostUsageModal({
|
||||
hosts: UsageHost[];
|
||||
onSelectHost: (serverId: string) => void;
|
||||
}) {
|
||||
const { display } = useUsagePreferences();
|
||||
const hostSelection = useMemo(
|
||||
() => ({ hosts, serverId, onSelect: onSelectHost }),
|
||||
[hosts, onSelectHost, serverId],
|
||||
);
|
||||
const { view, refresh, controls } = useHostUsageWithControls(hostSelection);
|
||||
const { display } = useUsageDisplay(view.kind === "ready" ? view.reports : []);
|
||||
return (
|
||||
<UsageModalFrame {...props} actions={controls}>
|
||||
<View testID={`usage-host-${serverId}`}>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { SettingsSection } from "@/components/settings/headings/settings-section";
|
||||
import type { UsageDisplay } from "./display";
|
||||
import { useUsageSetting } from "./setting";
|
||||
import { UsageControls } from "./controls";
|
||||
import { UsageList } from "./list";
|
||||
import type { UsageView } from "./types";
|
||||
@@ -27,8 +28,8 @@ export function UsageSection({
|
||||
testID?: string;
|
||||
}) {
|
||||
const trailing = useMemo(
|
||||
() => <UsageControls view={view} onRefresh={onRefresh} />,
|
||||
[onRefresh, view],
|
||||
() => <UsageControls serverId={serverId} view={view} onRefresh={onRefresh} />,
|
||||
[onRefresh, view, serverId],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -51,6 +52,15 @@ export function UsageBody({
|
||||
onRefresh: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const setting = useUsageSetting(serverId);
|
||||
if (view.kind === "off")
|
||||
return (
|
||||
<View>
|
||||
<UsageMessage text={view.message} />
|
||||
{setting.error ? <Alert variant="error" description={setting.error.message} /> : null}
|
||||
<Button onPress={setting.turnOn}>{t("providerUsage.turnOn")}</Button>
|
||||
</View>
|
||||
);
|
||||
if (view.kind === "unavailable") {
|
||||
return <UsageMessage text={view.message} />;
|
||||
}
|
||||
|
||||
@@ -509,14 +509,10 @@ export interface McpToolRef {
|
||||
}
|
||||
|
||||
export interface ToolPolicy {
|
||||
/** Missing or required fails closed; if-supported requests approval convenience only. */
|
||||
enforcement?: "required" | "if-supported";
|
||||
preapproved: McpToolRef[];
|
||||
}
|
||||
|
||||
export interface AgentSessionConfig {
|
||||
/** Per-server launch requirement; unspecified servers are required. */
|
||||
mcpServerRequirements?: Record<string, "optional" | "required">;
|
||||
provider: AgentProvider;
|
||||
cwd: string;
|
||||
/**
|
||||
|
||||
@@ -571,38 +571,3 @@ test.each(["all", "base", "uncommitted"] as const)(
|
||||
expect(parsed.attachments).toEqual([attachment]);
|
||||
},
|
||||
);
|
||||
|
||||
test("native agent creation accepts optional approval without weakening legacy strict acknowledgement", () => {
|
||||
const toolPolicy = {
|
||||
preapproved: [{ kind: "mcp", server: "hub", tool: "finish_execution" }],
|
||||
enforcement: "if-supported",
|
||||
};
|
||||
const parsed = SessionInboundMessageSchema.parse({
|
||||
type: "create_agent_request",
|
||||
requestId: "req",
|
||||
config: { provider: "pi", cwd: "/tmp", toolPolicy },
|
||||
});
|
||||
expect(parsed).toMatchObject({ config: { toolPolicy } });
|
||||
expect(
|
||||
SessionInboundMessageSchema.safeParse({
|
||||
type: "hub.execution.agent.create.request",
|
||||
requestId: "req",
|
||||
executionId: "exec",
|
||||
provider: "pi",
|
||||
cwd: "/tmp",
|
||||
prompt: "test",
|
||||
toolPolicy: { preapproved: toolPolicy.preapproved },
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
SessionInboundMessageSchema.safeParse({
|
||||
type: "hub.execution.agent.create.request",
|
||||
requestId: "req",
|
||||
executionId: "exec",
|
||||
provider: "pi",
|
||||
cwd: "/tmp",
|
||||
prompt: "test",
|
||||
toolPolicy,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
@@ -229,6 +229,8 @@ export const MutableDaemonConfigSchema = z
|
||||
.optional(),
|
||||
app: z.object({ baseUrl: z.string() }).optional(),
|
||||
catalogRefreshTimeoutMs: z.number().int().positive().optional(),
|
||||
// COMPAT(usageSetting): added in v0.14, remove after 2027-05-01.
|
||||
usage: z.object({ enabled: z.boolean() }).optional(),
|
||||
browserTools: MutableBrowserToolsConfigSchema.default({ enabled: false }),
|
||||
providers: z.record(z.string(), MutableDaemonProviderConfigSchema).default({}),
|
||||
metadataGeneration: MutableMetadataGenerationConfigSchema.default({ providers: [] }),
|
||||
@@ -256,6 +258,7 @@ export const MutableDaemonConfigPatchSchema = z
|
||||
.object({
|
||||
relay: MutableRelayConfigSchema.partial().optional(),
|
||||
mcp: z.object({ injectIntoAgents: z.boolean().optional() }).passthrough().optional(),
|
||||
usage: z.object({ enabled: z.boolean() }).optional(),
|
||||
browserTools: MutableBrowserToolsConfigSchema.partial().optional(),
|
||||
providers: z
|
||||
.record(z.string(), MutableDaemonProviderConfigSchema.partial().passthrough())
|
||||
@@ -490,11 +493,8 @@ const AgentSessionConfigSchema = z.object({
|
||||
featureValues: z.record(z.string(), z.unknown()).optional(),
|
||||
title: z.string().trim().min(1).max(MAX_EXPLICIT_AGENT_TITLE_CHARS).optional().nullable(),
|
||||
providerOptions: ProviderOptionsSchema.optional(),
|
||||
toolPolicy: ToolPolicySchema.extend({
|
||||
enforcement: z.enum(["required", "if-supported"]).optional(),
|
||||
}).optional(),
|
||||
toolPolicy: ToolPolicySchema.optional(),
|
||||
systemPrompt: z.string().optional(),
|
||||
mcpServerRequirements: z.record(z.string(), z.enum(["optional", "required"])).optional(),
|
||||
mcpServers: z.record(z.string(), McpServerConfigSchema).optional(),
|
||||
});
|
||||
|
||||
@@ -3674,9 +3674,10 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
internalWorkspaces: z.boolean().optional(),
|
||||
backgroundWorkspaces: z.boolean().optional(),
|
||||
providersSnapshot: z.boolean().optional(),
|
||||
optionalMcpSupport: z.boolean().optional(),
|
||||
connectedHosts: z.boolean().optional(),
|
||||
hostMultiplexing: z.boolean().optional(),
|
||||
// COMPAT(usageSetting): added in v0.14, remove after 2027-05-01.
|
||||
usageSetting: z.boolean().optional(),
|
||||
usageSources: z.boolean().optional(),
|
||||
// COMPAT(providersSnapshotCwd): added in v0.3.2, remove gate after 2027-02-10.
|
||||
providersSnapshotCwd: z.boolean().optional(),
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
type AgentManagerEvent,
|
||||
type ManagedAgent,
|
||||
} from "./agent-manager.js";
|
||||
import { buildProviderRegistry } from "./provider-registry.js";
|
||||
import { AgentStorage } from "./agent-storage.js";
|
||||
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
|
||||
import { toAgentPayload } from "./agent-projections.js";
|
||||
@@ -446,7 +445,7 @@ class EnvProbeAgentClient extends TestAgentClient {
|
||||
}
|
||||
|
||||
class TestAgentSession implements AgentSession {
|
||||
readonly provider: AgentProvider;
|
||||
readonly provider = "codex" as const;
|
||||
readonly capabilities = TEST_CAPABILITIES;
|
||||
readonly id = randomUUID();
|
||||
private runtimeModel: string | null = null;
|
||||
@@ -454,9 +453,7 @@ class TestAgentSession implements AgentSession {
|
||||
private turnIdCounter = 0;
|
||||
private interrupted = false;
|
||||
|
||||
constructor(private readonly config: AgentSessionConfig) {
|
||||
this.provider = config.provider;
|
||||
}
|
||||
constructor(private readonly config: AgentSessionConfig) {}
|
||||
|
||||
async run(): Promise<AgentRunResult> {
|
||||
return {
|
||||
@@ -959,131 +956,6 @@ test("unavailable steer interrupts once and starts one replacement turn", async
|
||||
}
|
||||
});
|
||||
|
||||
test("steers a send that arrives while the previous turn is still starting", async () => {
|
||||
const startHeld = deferred<void>();
|
||||
class SlowStartSteeringSession extends SteeringTestSession {
|
||||
override async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> {
|
||||
await startHeld.promise;
|
||||
return await super.startTurn(prompt);
|
||||
}
|
||||
}
|
||||
const session = new SlowStartSteeringSession({
|
||||
provider: "codex",
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-steer-starting-"));
|
||||
const manager = new AgentManager({
|
||||
clients: {
|
||||
codex: new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})(),
|
||||
},
|
||||
logger,
|
||||
});
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
agentId = agent.id;
|
||||
const steerOptions = (clientMessageId: string) => ({
|
||||
replaceRunning: true,
|
||||
activeTurnBehavior: "steer" as const,
|
||||
runOptions: { clientMessageId },
|
||||
});
|
||||
await startAgentRun(manager, agent.id, "FIRST", logger, steerOptions("first-client"));
|
||||
const second = startAgentRun(
|
||||
manager,
|
||||
agent.id,
|
||||
"SECOND",
|
||||
logger,
|
||||
steerOptions("second-client"),
|
||||
);
|
||||
|
||||
startHeld.resolve();
|
||||
await expect(second).resolves.toEqual({ disposition: "steered" });
|
||||
|
||||
expect(session.startPrompts).toEqual(["FIRST"]);
|
||||
expect(session.interruptCount).toBe(0);
|
||||
expect(
|
||||
manager
|
||||
.fetchTimeline(agent.id, { limit: 0 })
|
||||
.rows.filter((row) => row.item.type === "user_message")
|
||||
.map((row) => ({
|
||||
text: row.item.type === "user_message" ? row.item.text : null,
|
||||
turnId: row.turnId,
|
||||
})),
|
||||
).toEqual([
|
||||
{ text: "FIRST", turnId: "active-turn-1" },
|
||||
{ text: "SECOND", turnId: "active-turn-1" },
|
||||
]);
|
||||
} finally {
|
||||
startHeld.resolve();
|
||||
if (agentId) await manager.closeAgent(agentId).catch(() => undefined);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("starts its own turn when the previous turn fails to start under a steer send", async () => {
|
||||
const startHeld = deferred<void>();
|
||||
class FailingFirstStartSession extends SteeringTestSession {
|
||||
override async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> {
|
||||
if (prompt === "FIRST") {
|
||||
this.startPrompts.push(prompt);
|
||||
await startHeld.promise;
|
||||
throw new Error("first start failed");
|
||||
}
|
||||
return await super.startTurn(prompt);
|
||||
}
|
||||
}
|
||||
const session = new FailingFirstStartSession({
|
||||
provider: "codex",
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-steer-failed-start-"));
|
||||
const manager = new AgentManager({
|
||||
clients: {
|
||||
codex: new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})(),
|
||||
},
|
||||
logger,
|
||||
});
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
agentId = agent.id;
|
||||
const steerOptions = (clientMessageId: string) => ({
|
||||
replaceRunning: true,
|
||||
activeTurnBehavior: "steer" as const,
|
||||
runOptions: { clientMessageId },
|
||||
});
|
||||
await startAgentRun(manager, agent.id, "FIRST", logger, steerOptions("first-client"));
|
||||
const second = startAgentRun(
|
||||
manager,
|
||||
agent.id,
|
||||
"SECOND",
|
||||
logger,
|
||||
steerOptions("second-client"),
|
||||
);
|
||||
|
||||
startHeld.resolve();
|
||||
await expect(second).resolves.toEqual({ disposition: "turn_started" });
|
||||
await vi.waitFor(() => expect(session.startPrompts).toEqual(["FIRST", "SECOND"]));
|
||||
expect(session.interruptCount).toBe(0);
|
||||
} finally {
|
||||
startHeld.resolve();
|
||||
if (agentId) await manager.closeAgent(agentId).catch(() => undefined);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("orders an accepted steer before output emitted while acknowledgement is pending", async () => {
|
||||
const entered = deferred<void>();
|
||||
const release = deferred<void>();
|
||||
@@ -3825,85 +3697,54 @@ test("resumeAgentFromPersistence drops stored internal paseo MCP when runtime in
|
||||
expect(snapshot.config.mcpServers).toBeUndefined();
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ provider: "pi", supportsMcp: true },
|
||||
{ provider: "pi", supportsMcp: false },
|
||||
{ provider: "codex", supportsMcp: false },
|
||||
])(
|
||||
"createAgent permits optional approval for $provider with MCP capability $supportsMcp",
|
||||
async ({ provider, supportsMcp }) => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
const storagePath = join(workdir, "agents");
|
||||
const storage = new AgentStorage(storagePath, logger);
|
||||
test("createAgent preserves a user-provided paseo MCP config", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
const storagePath = join(workdir, "agents");
|
||||
const storage = new AgentStorage(storagePath, logger);
|
||||
|
||||
class CaptureClient extends TestAgentClient {
|
||||
lastConfig: AgentSessionConfig | null = null;
|
||||
class CaptureClient extends TestAgentClient {
|
||||
lastConfig: AgentSessionConfig | null = null;
|
||||
|
||||
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
|
||||
this.lastConfig = config;
|
||||
return supportsMcp ? new McpCapableTestAgentSession(config) : new TestAgentSession(config);
|
||||
}
|
||||
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
|
||||
this.lastConfig = config;
|
||||
return new McpCapableTestAgentSession(config);
|
||||
}
|
||||
}
|
||||
|
||||
const client = new CaptureClient(provider);
|
||||
const manager = new AgentManager({
|
||||
clients: {
|
||||
[provider]: client,
|
||||
},
|
||||
providerDefinitions: {
|
||||
[provider]: {
|
||||
enabled: true,
|
||||
applyToolPolicy: buildProviderRegistry(logger)[provider]!.applyToolPolicy,
|
||||
const client = new CaptureClient();
|
||||
const manager = new AgentManager({
|
||||
clients: {
|
||||
codex: client,
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
idFactory: () => "00000000-0000-4000-8000-000000000104",
|
||||
});
|
||||
|
||||
const snapshot = await manager.createAgent(
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: workdir,
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "https://example.com/custom-paseo",
|
||||
},
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
idFactory: () => "00000000-0000-4000-8000-000000000104",
|
||||
});
|
||||
},
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
|
||||
const snapshot = await manager.createAgent(
|
||||
{
|
||||
provider,
|
||||
mcpServerRequirements: { paseo: "optional" },
|
||||
cwd: workdir,
|
||||
toolPolicy: {
|
||||
enforcement: "if-supported",
|
||||
preapproved: [{ kind: "mcp", server: "paseo", tool: "finish_execution" }],
|
||||
},
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "https://example.com/custom-paseo",
|
||||
},
|
||||
},
|
||||
},
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
|
||||
expect(snapshot.config.mcpServers).toEqual({
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "https://example.com/custom-paseo",
|
||||
},
|
||||
});
|
||||
expect((await storage.get(snapshot.id))?.config?.mcpServerRequirements).toEqual({
|
||||
paseo: "optional",
|
||||
});
|
||||
await manager.reloadAgentSession(snapshot.id);
|
||||
expect(manager.getAgent(snapshot.id)?.config.mcpServerRequirements).toEqual({
|
||||
paseo: "optional",
|
||||
});
|
||||
const expectedPolicy =
|
||||
provider === "codex"
|
||||
? { preapproved: [{ kind: "mcp", server: "paseo", tool: "finish_execution" }] }
|
||||
: undefined;
|
||||
expect(snapshot.config.toolPolicy).toEqual(expectedPolicy);
|
||||
expect(client.lastConfig?.toolPolicy).toEqual(expectedPolicy);
|
||||
expect(client.lastConfig?.mcpServers).toEqual(snapshot.config.mcpServers);
|
||||
},
|
||||
);
|
||||
expect(snapshot.config.mcpServers).toEqual({
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "https://example.com/custom-paseo",
|
||||
},
|
||||
});
|
||||
expect(client.lastConfig?.mcpServers).toEqual(snapshot.config.mcpServers);
|
||||
});
|
||||
|
||||
test("createAgent fails when cwd does not exist", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
@@ -12609,21 +12450,3 @@ test("an out-of-band command racing idle cleanup waits for the resumed runtime",
|
||||
expect(h.commands).toEqual(["/maintenance"]);
|
||||
expect(h.prompts).toEqual([]);
|
||||
});
|
||||
|
||||
test("MCP requirements cannot mark a later plugin server optional", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: new TestAgentClient() },
|
||||
registry: new AgentStorage(join(workdir, "agents"), logger),
|
||||
logger,
|
||||
});
|
||||
await expect(
|
||||
manager.createAgent(
|
||||
{ provider: "codex", cwd: workdir, mcpServerRequirements: { plugin: "optional" } },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
),
|
||||
).rejects.toThrow(
|
||||
"MCP server requirement 'plugin' requires MCP server 'plugin' in the same agent request",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -216,8 +216,6 @@ function buildStoredAgentConfig(record: StoredAgentRecord): AgentSessionConfig {
|
||||
if (record.config.providerOptions != null) {
|
||||
config.providerOptions = record.config.providerOptions;
|
||||
}
|
||||
if (record.config.mcpServerRequirements != null)
|
||||
config.mcpServerRequirements = record.config.mcpServerRequirements;
|
||||
if (record.config.toolPolicy != null) config.toolPolicy = record.config.toolPolicy;
|
||||
if (record.config.systemPrompt != null) {
|
||||
config.systemPrompt = record.config.systemPrompt;
|
||||
@@ -1688,7 +1686,7 @@ export class AgentManager {
|
||||
);
|
||||
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
|
||||
if (
|
||||
this.hasRequiredExternalMcpServers(providerLaunchConfig) &&
|
||||
Object.keys(stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {}).length > 0 &&
|
||||
existing.session.capabilities.supportsMcpServers !== true
|
||||
) {
|
||||
throw this.unsupportedMcpError(providerLaunchConfig, launchContext);
|
||||
@@ -2736,7 +2734,7 @@ export class AgentManager {
|
||||
throw error;
|
||||
}
|
||||
if (isStaleProviderSessionError(error)) {
|
||||
this.runs.settleForegroundStart(pendingRun, { status: "failed", error: error.message });
|
||||
pendingRun.start = { status: "failed", error: error.message };
|
||||
agent.pendingReplacement = false;
|
||||
if (!agent.activeForegroundTurnId) agent.lifecycle = "idle";
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
@@ -2744,24 +2742,20 @@ export class AgentManager {
|
||||
}
|
||||
agent.pendingReplacement = false;
|
||||
const errorMsg = error instanceof Error ? error.message : "Failed to start turn";
|
||||
this.runs.settleForegroundStart(pendingRun, { status: "failed", error: errorMsg });
|
||||
try {
|
||||
// A terminal rejection belongs after the submitted prompt even though no provider turn exists.
|
||||
if (options?.clientMessageId) {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", {
|
||||
messageId: options.clientMessageId,
|
||||
});
|
||||
}
|
||||
await this.handleStreamEvent(agent, {
|
||||
type: "turn_failed",
|
||||
provider: agent.provider,
|
||||
error: errorMsg,
|
||||
pendingRun.start = { status: "failed", error: errorMsg };
|
||||
// A terminal rejection belongs after the submitted prompt even though no provider turn exists.
|
||||
if (options?.clientMessageId) {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", {
|
||||
messageId: options.clientMessageId,
|
||||
});
|
||||
this.finalizeForegroundTurn(agent);
|
||||
} finally {
|
||||
// A steer waiting on this start is released only once the run is cleared.
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
}
|
||||
await this.handleStreamEvent(agent, {
|
||||
type: "turn_failed",
|
||||
provider: agent.provider,
|
||||
error: errorMsg,
|
||||
});
|
||||
this.finalizeForegroundTurn(agent);
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -2838,7 +2832,7 @@ export class AgentManager {
|
||||
agent.pendingReplacement = false;
|
||||
}
|
||||
const turnStartedAt = new Date();
|
||||
this.runs.settleForegroundStart(pendingRun, { status: "started", turnId });
|
||||
pendingRun.start = { status: "started", turnId };
|
||||
agent.activeForegroundTurnId = turnId;
|
||||
this.openActiveTurn(agent, turnId, turnStartedAt);
|
||||
agent.lifecycle = "running";
|
||||
@@ -3047,9 +3041,6 @@ export class AgentManager {
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentSteerOptions,
|
||||
): Promise<ActiveTurnSteerDispatchResult> {
|
||||
// A turn that is still starting has no id to steer yet. Replacing it would drop its
|
||||
// prompt, so wait until it is accepted (or fails) and steer the turn it became.
|
||||
await this.runs.waitForForegroundStart(agentId);
|
||||
const agent = this.requireSessionAgent(agentId);
|
||||
const expectedTurnId = agent.activeForegroundTurnId ?? agent.activeTurnId;
|
||||
if (!expectedTurnId) {
|
||||
@@ -3890,19 +3881,13 @@ export class AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
private hasRequiredExternalMcpServers(config: AgentSessionConfig): boolean {
|
||||
return Object.keys(stripInternalPaseoMcpServer(config).mcpServers ?? {}).some(
|
||||
(name) => config.mcpServerRequirements?.[name] !== "optional",
|
||||
);
|
||||
}
|
||||
|
||||
private async requireExternalMcpSupport(
|
||||
session: AgentSession,
|
||||
launchConfig: AgentSessionConfig,
|
||||
launchContext: AgentLaunchContext,
|
||||
): Promise<void> {
|
||||
if (
|
||||
!this.hasRequiredExternalMcpServers(launchConfig) ||
|
||||
Object.keys(stripInternalPaseoMcpServer(launchConfig).mcpServers ?? {}).length === 0 ||
|
||||
session.capabilities.supportsMcpServers === true
|
||||
) {
|
||||
return;
|
||||
@@ -5465,7 +5450,6 @@ export class AgentManager {
|
||||
private applyProviderConfiguration(config: AgentSessionConfig): AgentSessionConfig {
|
||||
const definition = this.providerDefinitions.get(config.provider);
|
||||
this.validateToolPolicyServers(config);
|
||||
this.validateMcpServerRequirements(config);
|
||||
if (config.toolPolicy && !definition?.applyToolPolicy) {
|
||||
throw new Error(
|
||||
`Provider '${config.provider}' cannot preapprove exact MCP tools for unattended execution`,
|
||||
@@ -5476,16 +5460,6 @@ export class AgentManager {
|
||||
: config;
|
||||
}
|
||||
|
||||
private validateMcpServerRequirements(config: AgentSessionConfig): void {
|
||||
for (const name of Object.keys(config.mcpServerRequirements ?? {})) {
|
||||
if (!Object.hasOwn(config.mcpServers ?? {}, name)) {
|
||||
throw new Error(
|
||||
`MCP server requirement '${name}' requires MCP server '${name}' in the same agent request`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private validateToolPolicyServers(config: AgentSessionConfig): void {
|
||||
if (!config.toolPolicy) return;
|
||||
const serverNames = new Set(Object.keys(config.mcpServers ?? {}));
|
||||
|
||||
@@ -395,9 +395,6 @@ function buildSerializableConfig(config: AgentSessionConfig): SerializableAgentC
|
||||
if (config.systemPrompt) {
|
||||
serializable.systemPrompt = config.systemPrompt;
|
||||
}
|
||||
if (config.mcpServerRequirements) {
|
||||
serializable.mcpServerRequirements = config.mcpServerRequirements;
|
||||
}
|
||||
if (config.mcpServers) {
|
||||
serializable.mcpServers = config.mcpServers;
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { AgentRunState } from "./agent-run-state.js";
|
||||
|
||||
function track(promise: Promise<void>): { readonly resolved: boolean } {
|
||||
const state = { resolved: false };
|
||||
void (async () => {
|
||||
await promise;
|
||||
state.resolved = true;
|
||||
})();
|
||||
return state;
|
||||
}
|
||||
|
||||
async function flushMicrotasks(): Promise<void> {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
|
||||
describe("waitForForegroundStart", () => {
|
||||
test("resolves once the starting turn has an id", async () => {
|
||||
const runs = new AgentRunState();
|
||||
const run = runs.createPendingRun("agent");
|
||||
const wait = track(runs.waitForForegroundStart("agent"));
|
||||
|
||||
await flushMicrotasks();
|
||||
expect(wait.resolved).toBe(false);
|
||||
|
||||
runs.settleForegroundStart(run, { status: "started", turnId: "turn-1" });
|
||||
await flushMicrotasks();
|
||||
expect(wait.resolved).toBe(true);
|
||||
});
|
||||
|
||||
test("waits for a failed start's run to be cleared", async () => {
|
||||
const runs = new AgentRunState();
|
||||
const run = runs.createPendingRun("agent");
|
||||
const wait = track(runs.waitForForegroundStart("agent"));
|
||||
|
||||
runs.settleForegroundStart(run, { status: "failed", error: "start failed" });
|
||||
await flushMicrotasks();
|
||||
expect(wait.resolved).toBe(false);
|
||||
expect(runs.hasPendingRun("agent")).toBe(true);
|
||||
|
||||
runs.settleForegroundRun("agent", run.token);
|
||||
await flushMicrotasks();
|
||||
expect(wait.resolved).toBe(true);
|
||||
});
|
||||
|
||||
test("resolves at once when no turn is starting", async () => {
|
||||
const runs = new AgentRunState();
|
||||
await expect(runs.waitForForegroundStart("agent")).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -10,18 +10,14 @@ export interface ForegroundTurnWaiter {
|
||||
resolveSettled: () => void;
|
||||
}
|
||||
|
||||
type ForegroundRunStart =
|
||||
| { status: "pending" }
|
||||
| { status: "started"; turnId: string }
|
||||
| { status: "failed"; error: string };
|
||||
|
||||
export interface PendingForegroundRun {
|
||||
token: string;
|
||||
kind: "foreground";
|
||||
stagedEvents: AgentStreamEvent[];
|
||||
start: ForegroundRunStart;
|
||||
turnStartedPromise: Promise<void>;
|
||||
resolveTurnStarted: () => void;
|
||||
start:
|
||||
| { status: "pending" }
|
||||
| { status: "started"; turnId: string }
|
||||
| { status: "failed"; error: string };
|
||||
settled: boolean;
|
||||
settledPromise: Promise<void>;
|
||||
resolveSettled: () => void;
|
||||
@@ -58,28 +54,6 @@ export class AgentRunState {
|
||||
return run?.kind === "foreground" ? run : null;
|
||||
}
|
||||
|
||||
settleForegroundStart(
|
||||
run: PendingForegroundRun,
|
||||
start: Exclude<ForegroundRunStart, { status: "pending" }>,
|
||||
): void {
|
||||
run.start = start;
|
||||
if (start.status === "started") {
|
||||
run.resolveTurnStarted();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves once the agent's foreground run has a turn id or has ended. A failed start
|
||||
* resolves only once its run is cleared, so callers never see a failed run still tracked.
|
||||
*/
|
||||
async waitForForegroundStart(agentId: string): Promise<void> {
|
||||
const run = this.getPendingRun(agentId);
|
||||
if (run?.start.status !== "pending") {
|
||||
return;
|
||||
}
|
||||
await Promise.race([run.turnStartedPromise, run.settledPromise]);
|
||||
}
|
||||
|
||||
hasPendingRun(agentId: string): boolean {
|
||||
return this.getPendingRun(agentId) !== null;
|
||||
}
|
||||
@@ -303,16 +277,10 @@ export class ForegroundTurnStream {
|
||||
}
|
||||
|
||||
function createPendingForegroundRun(): PendingForegroundRun {
|
||||
let resolveTurnStarted!: () => void;
|
||||
const turnStartedPromise = new Promise<void>((resolvePromise) => {
|
||||
resolveTurnStarted = resolvePromise;
|
||||
});
|
||||
return {
|
||||
...createTrackedRunState(),
|
||||
kind: "foreground",
|
||||
start: { status: "pending" },
|
||||
turnStartedPromise,
|
||||
resolveTurnStarted,
|
||||
stagedEvents: [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -607,7 +607,6 @@ export interface AgentSessionConfig {
|
||||
title?: string | null;
|
||||
providerOptions?: ProviderOptions;
|
||||
toolPolicy?: ToolPolicy;
|
||||
mcpServerRequirements?: Record<string, "optional" | "required">;
|
||||
mcpServers?: Record<string, McpServerConfig>;
|
||||
/**
|
||||
* Internal agents are hidden from listings and don't trigger notifications.
|
||||
|
||||
@@ -27,10 +27,6 @@ const SERIALIZABLE_CONFIG_SCHEMA = z
|
||||
.nullable()
|
||||
.optional(),
|
||||
systemPrompt: z.string().nullable().optional(),
|
||||
mcpServerRequirements: z
|
||||
.record(z.string(), z.enum(["optional", "required"]))
|
||||
.nullable()
|
||||
.optional(),
|
||||
mcpServers: z.record(z.string(), z.any()).nullable().optional(),
|
||||
})
|
||||
.nullable()
|
||||
@@ -93,7 +89,6 @@ export type SerializableAgentConfig = Pick<
|
||||
| "toolPolicy"
|
||||
| "systemPrompt"
|
||||
| "mcpServers"
|
||||
| "mcpServerRequirements"
|
||||
>;
|
||||
|
||||
export type StoredAgentRecord = z.infer<typeof STORED_AGENT_SCHEMA>;
|
||||
|
||||
@@ -135,29 +135,6 @@ describe("provider-owned option schemas", () => {
|
||||
});
|
||||
|
||||
describe("exact MCP preapproval mappings", () => {
|
||||
test("optional exact preapproval permits unsupported providers without changing their MCP config", () => {
|
||||
const registry = buildProviderRegistry(createTestLogger());
|
||||
const config = {
|
||||
provider: "pi",
|
||||
cwd: "/tmp",
|
||||
mcpServers: { hub: { type: "http" as const, url: "http://localhost/hub" } },
|
||||
};
|
||||
expect(
|
||||
registry.pi.applyToolPolicy(config, { ...hubPolicy, enforcement: "if-supported" }),
|
||||
).toEqual({ ...config, toolPolicy: undefined });
|
||||
});
|
||||
test.each(["claude", "codex", "opencode"])(
|
||||
"optional grants retain exact approval for %s",
|
||||
(provider) => {
|
||||
const registry = buildProviderRegistry(createTestLogger());
|
||||
const config = { provider, cwd: "/tmp" };
|
||||
expect(
|
||||
registry[provider]!.applyToolPolicy(config, { ...hubPolicy, enforcement: "if-supported" })
|
||||
.toolPolicy,
|
||||
).toEqual(hubPolicy);
|
||||
},
|
||||
);
|
||||
|
||||
test("unsupported providers fail closed with an unattended-execution error", () => {
|
||||
const registry = buildProviderRegistry(createTestLogger());
|
||||
expect(() =>
|
||||
|
||||
@@ -652,15 +652,12 @@ function createRegistryEntry(
|
||||
supportsExactMcpPreapproval: resolved.contract.supportsExactMcpPreapproval,
|
||||
applyToolPolicy: (config, toolPolicy) => {
|
||||
if (toolPolicy && !resolved.contract.supportsExactMcpPreapproval) {
|
||||
if (toolPolicy.enforcement !== "if-supported")
|
||||
throw new ToolPolicyUnsupportedError(provider);
|
||||
return { ...config, toolPolicy: undefined };
|
||||
throw new ToolPolicyUnsupportedError(provider);
|
||||
}
|
||||
const exactPolicy = toolPolicy ? { preapproved: toolPolicy.preapproved } : undefined;
|
||||
return {
|
||||
...config,
|
||||
toolPolicy: exactPolicy
|
||||
? (resolved.contract.applyToolPolicy?.(provider, exactPolicy) ?? exactPolicy)
|
||||
toolPolicy: toolPolicy
|
||||
? (resolved.contract.applyToolPolicy?.(provider, toolPolicy) ?? toolPolicy)
|
||||
: undefined,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -30,20 +30,16 @@ function createQueryMock(events: unknown[]): Query {
|
||||
}
|
||||
|
||||
describe("Claude SDK env", () => {
|
||||
test.each(
|
||||
["node", "bun", process.execPath].flatMap((command) =>
|
||||
[undefined, "Paseo", "custom-client"].map((entrypoint) => ({ command, entrypoint })),
|
||||
),
|
||||
)(
|
||||
"preserves explicit launch identity $entrypoint in $command while clearing inherited session env",
|
||||
async ({ command, entrypoint }) => {
|
||||
test.each(["node", "bun", process.execPath])(
|
||||
"identifies the spawned %s process as Paseo after clearing parent session env",
|
||||
async (command) => {
|
||||
let output = "";
|
||||
let exited = Promise.resolve<unknown[]>([]);
|
||||
const query = claudeQuery(
|
||||
{ prompt: "", options: {} },
|
||||
{
|
||||
runtimeSettings: { env: { CLAUDE_CODE_ENTRYPOINT: "sdk-ts" } },
|
||||
launchEnv: entrypoint === undefined ? {} : { CLAUDE_CODE_ENTRYPOINT: entrypoint },
|
||||
launchEnv: { CLAUDE_CODE_ENTRYPOINT: "sdk-cli" },
|
||||
queryFactory: ({ options }) => {
|
||||
if (!options.spawnClaudeCodeProcess) {
|
||||
throw new Error("Missing Claude process launcher");
|
||||
@@ -69,10 +65,7 @@ describe("Claude SDK env", () => {
|
||||
|
||||
try {
|
||||
expect(await exited).toEqual([0, null]);
|
||||
expect(JSON.parse(output)).toEqual({
|
||||
...(entrypoint === undefined ? {} : { entrypoint }),
|
||||
parentSession: null,
|
||||
});
|
||||
expect(JSON.parse(output)).toEqual({ entrypoint: "Paseo", parentSession: null });
|
||||
} finally {
|
||||
query.close();
|
||||
}
|
||||
|
||||
@@ -73,9 +73,8 @@ function applyRuntimeSettingsToClaudeOptions(
|
||||
runtimeSettings,
|
||||
overlays: [launchEnv],
|
||||
});
|
||||
// Session-open hooks may explicitly supply a client identity. Keep inherited
|
||||
// SDK/parent identities cleared while honoring this launch-only contribution.
|
||||
providerEnvSpec.envOverlay.CLAUDE_CODE_ENTRYPOINT = launchEnv?.CLAUDE_CODE_ENTRYPOINT;
|
||||
// Set our identity after sanitization clears the parent session's entrypoint.
|
||||
providerEnvSpec.envOverlay.CLAUDE_CODE_ENTRYPOINT = "Paseo";
|
||||
const providerEnv = createExternalProcessEnv(spawnOptions.env, providerEnvSpec.envOverlay);
|
||||
const selfNodeCommand = isDefaultRuntime
|
||||
? buildSelfNodeCommand(resolved.args, providerEnv)
|
||||
|
||||
@@ -226,64 +226,6 @@ function deferred<T>() {
|
||||
}
|
||||
|
||||
describe("Codex active-turn steering admission", () => {
|
||||
test("steers an accepted turn whose native id arrives after startTurn returns", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
const { turnId } = await session.startTurn("FIRST");
|
||||
const steer = session.steerActiveTurn("SECOND", { expectedTurnId: turnId });
|
||||
appServer.startsTurn({ threadId: "thread-1", turnId: "native-A" });
|
||||
|
||||
await expect(steer).resolves.toEqual({ status: "accepted" });
|
||||
expect(
|
||||
appServer.requests().filter((request) => request.method === "turn/start"),
|
||||
).toHaveLength(1);
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/interrupt")).toEqual(
|
||||
[],
|
||||
);
|
||||
expect(appServer.requests().find((request) => request.method === "turn/steer")).toMatchObject(
|
||||
{
|
||||
params: {
|
||||
threadId: "thread-1",
|
||||
expectedTurnId: "native-A",
|
||||
input: [{ type: "text", text: "SECOND" }],
|
||||
},
|
||||
},
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("releases a waiting steer when the accepted turn ends before identification", async () => {
|
||||
const appServer = createFakeCodexAppServer();
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
const { turnId } = await session.startTurn("FIRST");
|
||||
const steer = session.steerActiveTurn("SECOND", { expectedTurnId: turnId });
|
||||
appServer.completeTurn();
|
||||
|
||||
await expect(steer).resolves.toEqual({ status: "unavailable" });
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a steer without the clearing contract leaves permissions open", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
|
||||
@@ -4456,18 +4456,9 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
): Promise<SteerResult> {
|
||||
const client = this.client;
|
||||
const threadId = this.currentThreadId;
|
||||
let nativeTurnId = this.currentTurnId;
|
||||
const nativeTurnId = this.currentTurnId;
|
||||
const foregroundTurnId = this.activeForegroundTurnId;
|
||||
if (!client || !threadId || foregroundTurnId !== options.expectedTurnId) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
const pendingIdentification = this.pendingForegroundTurnIdentification;
|
||||
// The start acknowledgement precedes the notification that identifies the native
|
||||
// turn. Keep this steer attached to the accepted foreground turn while it arrives.
|
||||
if (!nativeTurnId && pendingIdentification?.foregroundTurnId === foregroundTurnId) {
|
||||
nativeTurnId = await pendingIdentification.promise;
|
||||
}
|
||||
if (!nativeTurnId) {
|
||||
if (!client || !threadId || !nativeTurnId || foregroundTurnId !== options.expectedTurnId) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
if (await this.resolveSlashCommandInvocation(prompt)) return { status: "unavailable" };
|
||||
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
{"type": "session", "version": 3, "id": "e56a0006-f421-45be-9aef-e4019db1cf24", "timestamp": "2026-10-21T13:05:57.384Z", "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", "name": "[marker] Fixture marker verification", "parentSession": "/tmp/paseo-edxeth-fixture/lean/sessions/2026-10-21T13-05-53-085Z_01a15e91-73bd-7282-82c6-d3974711a941.jsonl"}
|
||||
{"type": "custom", "customType": "pi-subagents_launch_metadata", "data": {"version": 1, "timestamp": "2026-10-21T13:05:57.385Z", "name": "fixture-marker", "title": "Fixture marker verification", "sessionTitle": "[marker] Fixture marker verification", "agent": "marker", "mode": "background", "sessionMode": "lineage-only", "autoExit": true, "parentClosePolicy": "terminate", "reportContextUsage": true, "async": true, "model": "openai-codex/gpt-5.6-sol", "thinking": "high", "modelRef": "openai-codex/gpt-5.6-sol:high", "definitionModel": "openai-codex/gpt-5.6-sol", "definitionThinking": "high", "allowModelOverride": true, "modelSource": "agent", "tools": "read", "denyTools": ["subagent", "subagent_resume", "subagent_kill"], "spawnableAgents": [], "spawnBudget": null, "extensions": [], "noContextFiles": false, "inheritAppendSystem": false, "noSession": false, "trustProject": false, "agentConfigDir": "/tmp/paseo-edxeth-fixture/lean/agent", "cwd": "/tmp/paseo-edxeth-fixture/lean/workspace", "boundarySystemPrompt": false}, "id": "57355eeb", "parentId": null, "timestamp": "2026-10-21T13:05:57.386Z"}
|
||||
{"type": "session_info", "id": "847415e4", "parentId": "57355eeb", "timestamp": "2026-10-21T13:05:57.566Z", "name": "[marker] Fixture marker verification"}
|
||||
{"type": "model_change", "id": "d4ad59be", "parentId": "847415e4", "timestamp": "2026-10-21T13:05:57.672Z", "provider": "openai-codex", "modelId": "gpt-5.6-sol"}
|
||||
{"type": "thinking_level_change", "id": "7f6bf9d2", "parentId": "d4ad59be", "timestamp": "2026-10-21T13:05:57.672Z", "thinkingLevel": "high"}
|
||||
{"type": "message", "id": "737b762e", "parentId": "6b436446", "timestamp": "2026-10-21T13:05:57.679Z", "message": {"role": "user", "content": [{"type": "text", "text": "<file name=\"/home/pi-user/.pi/history/workspace/artifacts/01a15e91-73bd-7282-82c6-d3974711a941/context/fixture-marker-2026-10-21T13-05-57.md\">\n\n\nReturn only the exact marker supplied by the user. Do not use tools.\n\nComplete your task autonomously.\n\nReturn only PASEO_EDXETH_LEAN_OK\n\nYour FINAL assistant message should summarize what you accomplished.\n</file>\n"}], "timestamp": 1792587957678}}
|
||||
{"type": "message", "id": "100b110d", "parentId": "737b762e", "timestamp": "2026-10-21T13:06:02.050Z", "message": {"role": "assistant", "content": [{"type": "text", "text": "PASEO_EDXETH_LEAN_OK"}], "api": "openai-codex-responses", "provider": "openai-codex", "model": "gpt-5.6-sol", "usage": {"input": 1713, "output": 13, "cacheRead": 0, "cacheWrite": 0, "reasoning": 0, "totalTokens": 1726, "cost": {"input": 0.006852, "output": 0.00026000000000000003, "cacheRead": 0, "cacheWrite": 0, "total": 0.007111999999999999}}, "stopReason": "stop", "timestamp": 1792587957684, "responseId": "resp_0bc8bfaee079148a016ad8b8b7edb08191924676ed8dcfd447", "rawStopReason": "completed"}}
|
||||
{"type": "custom", "customType": "pi-subagent-completion", "data": {"reason": "normal"}, "id": "80bbd3bb", "parentId": "100b110d", "timestamp": "2026-10-21T13:06:02.054Z"}
|
||||
-263
@@ -1,263 +0,0 @@
|
||||
{
|
||||
"provenance": {
|
||||
"package": "Zeno2019/pi-subagents-lean",
|
||||
"version": "2.9.2-lean.1",
|
||||
"sourceCommit": "e10fe855808abcae193a205ea98f8ccd70d25620",
|
||||
"piVersion": "0.87.1",
|
||||
"captureDate": "2026-10-21"
|
||||
},
|
||||
"events": [
|
||||
{
|
||||
"type": "tool_execution_start",
|
||||
"toolCallId": "call_f28b261de3c6440b953f0f56c3fec7d0|fc_0d35cf51b3ed48b9016ad8b8b4a63c81918a55903d0a4f12cb",
|
||||
"toolName": "subagent",
|
||||
"args": {
|
||||
"agent": "marker",
|
||||
"name": "fixture-marker",
|
||||
"title": "Fixture marker verification",
|
||||
"task": "Return only PASEO_EDXETH_LEAN_OK"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "tool_execution_end",
|
||||
"toolCallId": "call_f28b261de3c6440b953f0f56c3fec7d0|fc_0d35cf51b3ed48b9016ad8b8b4a63c81918a55903d0a4f12cb",
|
||||
"toolName": "subagent",
|
||||
"result": {
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Sub-agent \"fixture-marker\" launched async with id 1bfdf3b3. Results will be delivered automatically as a steer message when it finishes. Use this exact id if you need to resume or stop this child.\n\nActivity: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl\nRun evidence: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json\nRead these on demand for progress or failure diagnosis; activity is evidence, not a completion verdict."
|
||||
}
|
||||
],
|
||||
"details": {
|
||||
"evidence": {
|
||||
"runId": "1bfdf3b3",
|
||||
"cwd": "/tmp/paseo-edxeth-fixture/lean/workspace",
|
||||
"activityFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl",
|
||||
"resultFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json"
|
||||
},
|
||||
"id": "1bfdf3b3",
|
||||
"name": "fixture-marker",
|
||||
"title": "Fixture marker verification",
|
||||
"task": "Return only PASEO_EDXETH_LEAN_OK",
|
||||
"agent": "marker",
|
||||
"sessionFile": "/tmp/paseo-edxeth-fixture/background/child-session.jsonl",
|
||||
"noSession": false,
|
||||
"status": "started",
|
||||
"mode": "background",
|
||||
"deliveryState": "detached",
|
||||
"parentClosePolicy": "terminate",
|
||||
"async": true,
|
||||
"autoExit": true
|
||||
}
|
||||
},
|
||||
"isError": false
|
||||
},
|
||||
{
|
||||
"type": "message_end",
|
||||
"message": {
|
||||
"role": "custom",
|
||||
"customType": "subagent_result",
|
||||
"content": "Sub-agent \"fixture-marker\" completed (7s).\n\nPASEO_EDXETH_LEAN_OK\n\nSession: /tmp/paseo-edxeth-fixture/background/child-session.jsonl\nResume: pi --session /tmp/paseo-edxeth-fixture/background/child-session.jsonl\n\nSub-agent context: 2K/372K tokens (0%) used at finish.\n\nActivity: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl\nRun evidence: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json\nRead these on demand for progress or failure diagnosis; activity is evidence, not a completion verdict.",
|
||||
"display": true,
|
||||
"details": {
|
||||
"evidence": {
|
||||
"runId": "1bfdf3b3",
|
||||
"cwd": "/tmp/paseo-edxeth-fixture/lean/workspace",
|
||||
"activityFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl",
|
||||
"resultFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json",
|
||||
"finalized": true
|
||||
},
|
||||
"id": "1bfdf3b3",
|
||||
"name": "fixture-marker",
|
||||
"task": "Return only PASEO_EDXETH_LEAN_OK",
|
||||
"agent": "marker",
|
||||
"mode": "background",
|
||||
"status": "completed",
|
||||
"deliveryState": "detached",
|
||||
"parentClosePolicy": "terminate",
|
||||
"async": true,
|
||||
"exitCode": 0,
|
||||
"elapsed": 7,
|
||||
"outputTokens": 13,
|
||||
"contextTokens": 1775,
|
||||
"contextWindow": 372000,
|
||||
"sessionFile": "/tmp/paseo-edxeth-fixture/background/child-session.jsonl"
|
||||
},
|
||||
"timestamp": 1792587964414
|
||||
}
|
||||
}
|
||||
],
|
||||
"messages": [
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": [
|
||||
{
|
||||
"type": "toolCall",
|
||||
"id": "call_f28b261de3c6440b953f0f56c3fec7d0|fc_0d35cf51b3ed48b9016ad8b8b4a63c81918a55903d0a4f12cb",
|
||||
"name": "subagent",
|
||||
"arguments": {
|
||||
"agent": "marker",
|
||||
"name": "fixture-marker",
|
||||
"title": "Fixture marker verification",
|
||||
"task": "Return only PASEO_EDXETH_LEAN_OK"
|
||||
}
|
||||
}
|
||||
],
|
||||
"api": "openai-codex-responses",
|
||||
"provider": "openai-codex",
|
||||
"model": "gpt-5.6-sol",
|
||||
"usage": {
|
||||
"input": 2020,
|
||||
"output": 43,
|
||||
"cacheRead": 0,
|
||||
"cacheWrite": 0,
|
||||
"reasoning": 0,
|
||||
"totalTokens": 2063,
|
||||
"cost": {
|
||||
"input": 0.00808,
|
||||
"output": 0.0008600000000000001,
|
||||
"cacheRead": 0,
|
||||
"cacheWrite": 0,
|
||||
"total": 0.00894
|
||||
}
|
||||
},
|
||||
"stopReason": "toolUse",
|
||||
"timestamp": 1792587953256,
|
||||
"responseId": "resp_0d35cf51b3ed48b9016ad8b8b3698481918f82962b6eaf2788",
|
||||
"rawStopReason": "completed"
|
||||
},
|
||||
{
|
||||
"role": "toolResult",
|
||||
"toolCallId": "call_f28b261de3c6440b953f0f56c3fec7d0|fc_0d35cf51b3ed48b9016ad8b8b4a63c81918a55903d0a4f12cb",
|
||||
"toolName": "subagent",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Sub-agent \"fixture-marker\" launched async with id 1bfdf3b3. Results will be delivered automatically as a steer message when it finishes. Use this exact id if you need to resume or stop this child.\n\nActivity: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl\nRun evidence: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json\nRead these on demand for progress or failure diagnosis; activity is evidence, not a completion verdict."
|
||||
}
|
||||
],
|
||||
"details": {
|
||||
"evidence": {
|
||||
"runId": "1bfdf3b3",
|
||||
"cwd": "/tmp/paseo-edxeth-fixture/lean/workspace",
|
||||
"activityFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl",
|
||||
"resultFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json",
|
||||
"finalized": true
|
||||
},
|
||||
"id": "1bfdf3b3",
|
||||
"name": "fixture-marker",
|
||||
"title": "Fixture marker verification",
|
||||
"task": "Return only PASEO_EDXETH_LEAN_OK",
|
||||
"agent": "marker",
|
||||
"sessionFile": "/tmp/paseo-edxeth-fixture/background/child-session.jsonl",
|
||||
"noSession": false,
|
||||
"status": "started",
|
||||
"mode": "background",
|
||||
"deliveryState": "detached",
|
||||
"parentClosePolicy": "terminate",
|
||||
"async": true,
|
||||
"autoExit": true
|
||||
},
|
||||
"isError": false,
|
||||
"timestamp": 1792587957399
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": [
|
||||
{
|
||||
"type": "thinking",
|
||||
"thinking": "**Identifying need for await keyword**"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"text": "DONE"
|
||||
}
|
||||
],
|
||||
"api": "openai-codex-responses",
|
||||
"provider": "openai-codex",
|
||||
"model": "gpt-5.6-sol",
|
||||
"usage": {
|
||||
"input": 2258,
|
||||
"output": 18,
|
||||
"cacheRead": 0,
|
||||
"cacheWrite": 0,
|
||||
"reasoning": 11,
|
||||
"totalTokens": 2276,
|
||||
"cost": {
|
||||
"input": 0.009032,
|
||||
"output": 0.00036,
|
||||
"cacheRead": 0,
|
||||
"cacheWrite": 0,
|
||||
"total": 0.009392
|
||||
}
|
||||
},
|
||||
"stopReason": "stop",
|
||||
"timestamp": 1792587957402,
|
||||
"responseId": "resp_0d35cf51b3ed48b9016ad8b8b602108191a8e8f7fd77fbe5b5",
|
||||
"rawStopReason": "completed"
|
||||
},
|
||||
{
|
||||
"role": "custom",
|
||||
"customType": "subagent_result",
|
||||
"content": "Sub-agent \"fixture-marker\" completed (7s).\n\nPASEO_EDXETH_LEAN_OK\n\nSession: /tmp/paseo-edxeth-fixture/background/child-session.jsonl\nResume: pi --session /tmp/paseo-edxeth-fixture/background/child-session.jsonl\n\nSub-agent context: 2K/372K tokens (0%) used at finish.\n\nActivity: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl\nRun evidence: /home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json\nRead these on demand for progress or failure diagnosis; activity is evidence, not a completion verdict.",
|
||||
"display": true,
|
||||
"details": {
|
||||
"evidence": {
|
||||
"runId": "1bfdf3b3",
|
||||
"cwd": "/tmp/paseo-edxeth-fixture/lean/workspace",
|
||||
"activityFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/activity.jsonl",
|
||||
"resultFile": "/home/pi-user/.pi/history/workspace/artifacts/2026-10-21T13-05-57-380Z_db802a71-7bb32177-573971ee-535c/subagents/1bfdf3b3/result.json",
|
||||
"finalized": true
|
||||
},
|
||||
"id": "1bfdf3b3",
|
||||
"name": "fixture-marker",
|
||||
"task": "Return only PASEO_EDXETH_LEAN_OK",
|
||||
"agent": "marker",
|
||||
"mode": "background",
|
||||
"status": "completed",
|
||||
"deliveryState": "detached",
|
||||
"parentClosePolicy": "terminate",
|
||||
"async": true,
|
||||
"exitCode": 0,
|
||||
"elapsed": 7,
|
||||
"outputTokens": 13,
|
||||
"contextTokens": 1775,
|
||||
"contextWindow": 372000,
|
||||
"sessionFile": "/tmp/paseo-edxeth-fixture/background/child-session.jsonl"
|
||||
},
|
||||
"timestamp": 1792587964414
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "DONE"
|
||||
}
|
||||
],
|
||||
"api": "openai-codex-responses",
|
||||
"provider": "openai-codex",
|
||||
"model": "gpt-5.6-sol",
|
||||
"usage": {
|
||||
"input": 389,
|
||||
"output": 5,
|
||||
"cacheRead": 2176,
|
||||
"cacheWrite": 0,
|
||||
"reasoning": 0,
|
||||
"totalTokens": 2570,
|
||||
"cost": {
|
||||
"input": 0.0015559999999999999,
|
||||
"output": 0.0001,
|
||||
"cacheRead": 0.0008704000000000001,
|
||||
"cacheWrite": 0,
|
||||
"total": 0.0025264
|
||||
}
|
||||
},
|
||||
"stopReason": "stop",
|
||||
"timestamp": 1792587964417,
|
||||
"responseId": "resp_0d35cf51b3ed48b9016ad8b8bd0c548191bddd1fe3410a1c82",
|
||||
"rawStopReason": "completed"
|
||||
}
|
||||
]
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
{"type": "session", "version": 3, "id": "afbea6e0-7858-4ecf-8ef1-e26af9b7d6e0", "timestamp": "2026-10-21T13:05:17.628Z", "cwd": "/tmp/paseo-edxeth-fixture/upstream/workspace", "name": "[marker] Fixture marker verification", "parentSession": "/tmp/paseo-edxeth-fixture/upstream/sessions/2026-10-21T13-05-12-212Z_01a15e90-d414-7243-a701-4eb4b0bec880.jsonl"}
|
||||
{"type": "custom", "customType": "pi-subagents_launch_metadata", "data": {"version": 1, "timestamp": "2026-10-21T13:05:17.628Z", "name": "fixture-marker", "title": "Fixture marker verification", "sessionTitle": "[marker] Fixture marker verification", "agent": "marker", "mode": "background", "sessionMode": "lineage-only", "autoExit": true, "parentClosePolicy": "terminate", "reportContextUsage": true, "async": false, "model": "openai-codex/gpt-5.6-sol", "thinking": "high", "modelRef": "openai-codex/gpt-5.6-sol:high", "definitionModel": "openai-codex/gpt-5.6-sol", "definitionThinking": "high", "allowModelOverride": true, "modelSource": "agent", "tools": "read", "denyTools": ["subagent", "subagent_resume", "subagent_kill"], "spawnableAgents": [], "spawnBudget": null, "extensions": [], "noContextFiles": false, "inheritAppendSystem": false, "noSession": false, "trustProject": false, "agentConfigDir": "/tmp/paseo-edxeth-fixture/upstream/agent", "cwd": "/tmp/paseo-edxeth-fixture/upstream/workspace", "boundarySystemPrompt": false}, "id": "3f7d3c3f", "parentId": null, "timestamp": "2026-10-21T13:05:17.629Z"}
|
||||
{"type": "session_info", "id": "6e198450", "parentId": "3f7d3c3f", "timestamp": "2026-10-21T13:05:17.825Z", "name": "[marker] Fixture marker verification"}
|
||||
{"type": "model_change", "id": "94bf4c0b", "parentId": "6e198450", "timestamp": "2026-10-21T13:05:17.962Z", "provider": "openai-codex", "modelId": "gpt-5.6-sol"}
|
||||
{"type": "thinking_level_change", "id": "57cc6428", "parentId": "94bf4c0b", "timestamp": "2026-10-21T13:05:17.962Z", "thinkingLevel": "high"}
|
||||
{"type": "message", "id": "a9e47f08", "parentId": "8c186624", "timestamp": "2026-10-21T13:05:17.970Z", "message": {"role": "user", "content": [{"type": "text", "text": "<file name=\"/home/pi-user/.pi/history/workspace/artifacts/01a15e90-d414-7243-a701-4eb4b0bec880/context/fixture-marker-2026-10-21T13-05-17.md\">\n\n\nReturn only the exact marker supplied by the user. Do not use tools.\n\nComplete your task autonomously.\n\nReturn only PASEO_EDXETH_UPSTREAM_OK\n\nYour FINAL assistant message should summarize what you accomplished.\n</file>\n"}], "timestamp": 1792587917968}}
|
||||
{"type": "message", "id": "bc221a13", "parentId": "a9e47f08", "timestamp": "2026-10-21T13:05:23.476Z", "message": {"role": "assistant", "content": [{"type": "thinking", "thinking": "**Following user file marker exactly**"}, {"type": "text", "text": "PASEO_EDXETH_UPSTREAM_OK"}], "api": "openai-codex-responses", "provider": "openai-codex", "model": "gpt-5.6-sol", "usage": {"input": 1673, "output": 49, "cacheRead": 0, "cacheWrite": 0, "reasoning": 34, "totalTokens": 1722, "cost": {"input": 0.006692, "output": 0.0009800000000000002, "cacheRead": 0, "cacheWrite": 0, "total": 0.007672}}, "stopReason": "stop", "timestamp": 1792587917974, "responseId": "resp_09445c1733d532e7016ad8b8909c908191ba803c059497945e", "rawStopReason": "completed"}}
|
||||
{"type": "custom", "customType": "pi-subagent-completion", "data": {"reason": "normal"}, "id": "832fc8c9", "parentId": "bc221a13", "timestamp": "2026-10-21T13:05:23.477Z"}
|
||||
-156
@@ -1,156 +0,0 @@
|
||||
{
|
||||
"provenance": {
|
||||
"package": "edxeth/pi-subagents",
|
||||
"version": "2.9.2",
|
||||
"sourceCommit": "cf6dbf41c17986f3882e6804a68e8fb8282d25e6",
|
||||
"piVersion": "0.87.1",
|
||||
"captureDate": "2026-10-21"
|
||||
},
|
||||
"events": [
|
||||
{
|
||||
"type": "tool_execution_start",
|
||||
"toolCallId": "call_0bc6fc2213cd49aa92950947bde5dd8a|fc_0a0ca4aa78cd296a016ad8b88d018481919eadbf09eb191a1a",
|
||||
"toolName": "subagent",
|
||||
"args": {
|
||||
"agent": "marker",
|
||||
"name": "fixture-marker",
|
||||
"title": "Fixture marker verification",
|
||||
"task": "Return only PASEO_EDXETH_UPSTREAM_OK"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "tool_execution_end",
|
||||
"toolCallId": "call_0bc6fc2213cd49aa92950947bde5dd8a|fc_0a0ca4aa78cd296a016ad8b88d018481919eadbf09eb191a1a",
|
||||
"toolName": "subagent",
|
||||
"result": {
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Sub-agent \"fixture-marker\" completed (7s).\n\nPASEO_EDXETH_UPSTREAM_OK\n\nSession: /tmp/paseo-edxeth-fixture/foreground/child-session.jsonl\nResume: pi --session /tmp/paseo-edxeth-fixture/foreground/child-session.jsonl\n\nSub-agent context: 2K/372K tokens (0%) used at finish."
|
||||
}
|
||||
],
|
||||
"details": {
|
||||
"id": "dd7f94e8",
|
||||
"name": "fixture-marker",
|
||||
"agent": "marker",
|
||||
"status": "completed",
|
||||
"mode": "background",
|
||||
"parentClosePolicy": "terminate",
|
||||
"deliveryState": "awaited",
|
||||
"async": false,
|
||||
"autoExit": true,
|
||||
"exitCode": 0,
|
||||
"elapsed": 7,
|
||||
"outputTokens": 49,
|
||||
"contextTokens": 1777,
|
||||
"contextWindow": 372000,
|
||||
"summary": "PASEO_EDXETH_UPSTREAM_OK",
|
||||
"sessionFile": "/tmp/paseo-edxeth-fixture/foreground/child-session.jsonl"
|
||||
}
|
||||
},
|
||||
"isError": false
|
||||
}
|
||||
],
|
||||
"messages": [
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": [
|
||||
{
|
||||
"type": "toolCall",
|
||||
"id": "call_0bc6fc2213cd49aa92950947bde5dd8a|fc_0a0ca4aa78cd296a016ad8b88d018481919eadbf09eb191a1a",
|
||||
"name": "subagent",
|
||||
"arguments": {
|
||||
"agent": "marker",
|
||||
"name": "fixture-marker",
|
||||
"title": "Fixture marker verification",
|
||||
"task": "Return only PASEO_EDXETH_UPSTREAM_OK"
|
||||
}
|
||||
}
|
||||
],
|
||||
"api": "openai-codex-responses",
|
||||
"provider": "openai-codex",
|
||||
"model": "gpt-5.6-sol",
|
||||
"usage": {
|
||||
"input": 3256,
|
||||
"output": 43,
|
||||
"cacheRead": 0,
|
||||
"cacheWrite": 0,
|
||||
"reasoning": 0,
|
||||
"totalTokens": 3299,
|
||||
"cost": {
|
||||
"input": 0.013023999999999999,
|
||||
"output": 0.0008600000000000001,
|
||||
"cacheRead": 0,
|
||||
"cacheWrite": 0,
|
||||
"total": 0.013883999999999999
|
||||
}
|
||||
},
|
||||
"stopReason": "toolUse",
|
||||
"timestamp": 1792587912428,
|
||||
"responseId": "resp_0a0ca4aa78cd296a016ad8b88bd52881918cbb9b8326b3060a",
|
||||
"rawStopReason": "completed"
|
||||
},
|
||||
{
|
||||
"role": "toolResult",
|
||||
"toolCallId": "call_0bc6fc2213cd49aa92950947bde5dd8a|fc_0a0ca4aa78cd296a016ad8b88d018481919eadbf09eb191a1a",
|
||||
"toolName": "subagent",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Sub-agent \"fixture-marker\" completed (7s).\n\nPASEO_EDXETH_UPSTREAM_OK\n\nSession: /tmp/paseo-edxeth-fixture/foreground/child-session.jsonl\nResume: pi --session /tmp/paseo-edxeth-fixture/foreground/child-session.jsonl\n\nSub-agent context: 2K/372K tokens (0%) used at finish."
|
||||
}
|
||||
],
|
||||
"details": {
|
||||
"id": "dd7f94e8",
|
||||
"name": "fixture-marker",
|
||||
"agent": "marker",
|
||||
"status": "completed",
|
||||
"mode": "background",
|
||||
"parentClosePolicy": "terminate",
|
||||
"deliveryState": "awaited",
|
||||
"async": false,
|
||||
"autoExit": true,
|
||||
"exitCode": 0,
|
||||
"elapsed": 7,
|
||||
"outputTokens": 49,
|
||||
"contextTokens": 1777,
|
||||
"contextWindow": 372000,
|
||||
"summary": "PASEO_EDXETH_UPSTREAM_OK",
|
||||
"sessionFile": "/tmp/paseo-edxeth-fixture/foreground/child-session.jsonl"
|
||||
},
|
||||
"isError": false,
|
||||
"timestamp": 1792587924671
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "DONE"
|
||||
}
|
||||
],
|
||||
"api": "openai-codex-responses",
|
||||
"provider": "openai-codex",
|
||||
"model": "gpt-5.6-sol",
|
||||
"usage": {
|
||||
"input": 388,
|
||||
"output": 5,
|
||||
"cacheRead": 3072,
|
||||
"cacheWrite": 0,
|
||||
"reasoning": 0,
|
||||
"totalTokens": 3465,
|
||||
"cost": {
|
||||
"input": 0.001552,
|
||||
"output": 0.0001,
|
||||
"cacheRead": 0.0012288000000000002,
|
||||
"cacheWrite": 0,
|
||||
"total": 0.0028808
|
||||
}
|
||||
},
|
||||
"stopReason": "stop",
|
||||
"timestamp": 1792587924675,
|
||||
"responseId": "resp_0a0ca4aa78cd296a016ad8b896af2c81919c0ef586dd50f2f0",
|
||||
"rawStopReason": "completed"
|
||||
}
|
||||
]
|
||||
}
|
||||
-336
@@ -1,336 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createPiExtensionHost } from "../index.js";
|
||||
import { readSubagentFixture, verifySubagentFixture } from "../subagent-fixture-test.js";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { edxethPiSubagents } from "./index.js";
|
||||
import { streamPiHistory } from "../../history-mapper.js";
|
||||
import { ProviderSubagentStore } from "../../../../provider-subagents/store.js";
|
||||
|
||||
const args = {
|
||||
agent: "scout",
|
||||
name: "status-scout",
|
||||
title: "Check child status",
|
||||
task: "Return the completion marker",
|
||||
};
|
||||
|
||||
describe("edxeth/pi-subagents adapter", () => {
|
||||
test.each(["tool", "notification"])("ends a child that requested help via %s", (delivery) => {
|
||||
const host = createPiExtensionHost();
|
||||
const call = { callId: "spawn-1", toolName: "subagent", args, status: "completed" as const };
|
||||
host.mapToolCall({
|
||||
...call,
|
||||
result: { details: { id: "run-1", name: args.name, status: "started" } },
|
||||
});
|
||||
const details = { id: "run-1", name: args.name, message: "Please clarify the task" };
|
||||
const result =
|
||||
delivery === "tool"
|
||||
? host.mapToolCall({ ...call, result: { details: { ...details, status: "pinged" } } })
|
||||
: host.mapCustomMessage({
|
||||
role: "custom",
|
||||
customType: "subagent_ping",
|
||||
content: "Child requested help and exited",
|
||||
details,
|
||||
});
|
||||
expect(result?.subagents).toEqual([
|
||||
expect.objectContaining({
|
||||
type: "upsert",
|
||||
id: "spawn-1",
|
||||
status: "canceled",
|
||||
subtitle: "Needs help",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
test("leaves unrelated tools and other subagent protocols to their adapters", () => {
|
||||
const host = createPiExtensionHost(undefined, [edxethPiSubagents]);
|
||||
const call = { callId: "other", toolName: "subagent", args, status: "completed" as const };
|
||||
for (const details of [null, {}, { mode: "single", results: [] }, { id: "run-1" }]) {
|
||||
expect(host.mapToolCall({ ...call, result: { details } })).toBeUndefined();
|
||||
}
|
||||
expect(
|
||||
host.mapToolCall({
|
||||
...call,
|
||||
toolName: "unrelated",
|
||||
result: { details: { id: "run-1", name: args.name, status: "completed" } },
|
||||
}),
|
||||
).toBeUndefined();
|
||||
for (const details of [{ id: "run-1" }, { id: "run-1", status: "unknown" }]) {
|
||||
expect(
|
||||
host.mapCustomMessage({
|
||||
role: "custom",
|
||||
customType: "subagent_result",
|
||||
content: "Unrecognized result",
|
||||
details,
|
||||
}),
|
||||
).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
test("waits for cancellation after a kill acknowledgement reports stopping", () => {
|
||||
const host = createPiExtensionHost();
|
||||
host.mapToolCall({
|
||||
callId: "spawn-1",
|
||||
toolName: "subagent",
|
||||
args,
|
||||
status: "completed",
|
||||
result: { details: { id: "run-1", name: args.name, status: "started" } },
|
||||
});
|
||||
const stopping = host.mapToolCall({
|
||||
callId: "kill-1",
|
||||
toolName: "subagent_kill",
|
||||
args: { id: "run-1" },
|
||||
status: "completed",
|
||||
result: { details: { id: "run-1", name: args.name, status: "stopping" } },
|
||||
});
|
||||
expect(stopping?.subagents ?? []).toEqual([]);
|
||||
expect(
|
||||
host.mapCustomMessage({
|
||||
role: "custom",
|
||||
customType: "subagent_result",
|
||||
content: "Cancelled",
|
||||
details: { id: "run-1", status: "cancelled" },
|
||||
})?.subagents,
|
||||
).toEqual([{ type: "upsert", id: "spawn-1", status: "canceled" }]);
|
||||
});
|
||||
|
||||
test("preserves a completion that arrives before its launch acknowledgement", () => {
|
||||
const host = createPiExtensionHost();
|
||||
const early = host.mapCustomMessage({
|
||||
role: "custom",
|
||||
customType: "subagent_result",
|
||||
content: "Already done",
|
||||
details: { id: "fast-run", status: "completed" },
|
||||
});
|
||||
expect(early?.subagents ?? []).toEqual([]);
|
||||
const started = host.mapToolCall({
|
||||
callId: "fast-call",
|
||||
toolName: "subagent",
|
||||
args,
|
||||
status: "completed",
|
||||
result: {
|
||||
details: { id: "fast-run", name: args.name, agent: args.agent, status: "started" },
|
||||
},
|
||||
});
|
||||
expect(started?.subagents).toEqual([
|
||||
{
|
||||
type: "upsert",
|
||||
id: "fast-call",
|
||||
title: "scout",
|
||||
description: args.task,
|
||||
toolCallId: "fast-call",
|
||||
status: "completed",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ details: { status: "completed" }, expected: "completed" },
|
||||
{ details: { status: "failed" }, expected: "failed" },
|
||||
{ details: { status: "cancelled" }, expected: "canceled" },
|
||||
{ details: { error: "Child watcher exited unexpectedly" }, expected: "failed" },
|
||||
])("maps completion $details to $expected", ({ details, expected }) => {
|
||||
const host = createPiExtensionHost();
|
||||
host.mapToolCall({
|
||||
callId: "spawn-1",
|
||||
toolName: "subagent",
|
||||
args,
|
||||
status: "completed",
|
||||
result: { details: { id: "run-1", name: args.name, status: "started" } },
|
||||
});
|
||||
expect(
|
||||
host.mapCustomMessage({
|
||||
role: "custom",
|
||||
customType: "subagent_result",
|
||||
content: "Child result",
|
||||
details: { id: "run-1", ...details },
|
||||
})?.subagents,
|
||||
).toEqual([{ type: "upsert", id: "spawn-1", status: expected }]);
|
||||
});
|
||||
|
||||
test("a resume gets its own run and reads the retained child session", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "paseo-edxeth-resume-"));
|
||||
const file = join(dir, "child.jsonl");
|
||||
const host = createPiExtensionHost();
|
||||
try {
|
||||
await writeFile(
|
||||
file,
|
||||
JSON.stringify({
|
||||
type: "message",
|
||||
message: { role: "assistant", content: [{ type: "text", text: "RESUMED" }] },
|
||||
}) + "\n",
|
||||
);
|
||||
const original = host.mapToolCall({
|
||||
callId: "spawn-1",
|
||||
toolName: "subagent",
|
||||
args,
|
||||
status: "completed",
|
||||
result: {
|
||||
details: { id: "run-1", name: args.name, status: "completed", sessionFile: file },
|
||||
},
|
||||
});
|
||||
await original?.hydration;
|
||||
const resumed = host.mapToolCall({
|
||||
callId: "resume-1",
|
||||
toolName: "subagent_resume",
|
||||
args: { sessionFile: file, task: "Continue" },
|
||||
status: "completed",
|
||||
result: {
|
||||
details: { id: "run-2", name: args.name, status: "started", sessionFile: file },
|
||||
},
|
||||
});
|
||||
expect(resumed?.childSessions).toEqual([{ id: "resume-1", file }]);
|
||||
expect(await resumed?.hydration).toEqual([
|
||||
{
|
||||
type: "provider_subagent",
|
||||
provider: "pi",
|
||||
event: {
|
||||
type: "timeline",
|
||||
id: "resume-1",
|
||||
item: expect.objectContaining({ type: "assistant_message", text: "RESUMED" }),
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(
|
||||
host.mapCustomMessage({
|
||||
role: "custom",
|
||||
customType: "subagent_result",
|
||||
content: "Resumed run complete",
|
||||
details: { id: "run-2", status: "completed", sessionFile: file },
|
||||
})?.subagents,
|
||||
).toEqual([{ type: "upsert", id: "resume-1", status: "completed" }]);
|
||||
} finally {
|
||||
host.close();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("settles each batched child by run id without creating a parent-call card", () => {
|
||||
const host = createPiExtensionHost();
|
||||
const result = host.mapToolCall({
|
||||
callId: "batch-1",
|
||||
toolName: "subagent",
|
||||
args: { children: [args, { ...args, agent: "reviewer", name: "status-reviewer" }] },
|
||||
status: "completed",
|
||||
result: {
|
||||
details: {
|
||||
status: "batch",
|
||||
children: [
|
||||
{ id: "run-1", ...args, mode: "background", status: "completed" },
|
||||
{ id: "run-2", name: "status-reviewer", agent: "reviewer", status: "started" },
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(result?.subagents).toEqual([
|
||||
{
|
||||
type: "upsert",
|
||||
id: "batch-1:0",
|
||||
title: "scout",
|
||||
description: args.task,
|
||||
toolCallId: "batch-1",
|
||||
status: "completed",
|
||||
},
|
||||
{
|
||||
type: "upsert",
|
||||
id: "batch-1:1",
|
||||
title: "reviewer",
|
||||
description: undefined,
|
||||
toolCallId: "batch-1",
|
||||
status: "running",
|
||||
},
|
||||
]);
|
||||
expect(
|
||||
host.mapCustomMessage({
|
||||
role: "custom",
|
||||
customType: "subagent_result",
|
||||
content: "Done",
|
||||
details: { id: "run-2", status: "completed" },
|
||||
})?.subagents,
|
||||
).toEqual([{ type: "upsert", id: "batch-1:1", status: "completed" }]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ mode: "foreground", statuses: ["running", "completed"] },
|
||||
{ mode: "background", statuses: ["running", "running", "completed"] },
|
||||
])("settles the captured $mode run live and on replay", async ({ mode, statuses }) => {
|
||||
const fixture = readSubagentFixture(new URL(`./fixtures/${mode}.json`, import.meta.url), {
|
||||
from: `/tmp/paseo-edxeth-fixture/${mode}/child-session.jsonl`,
|
||||
to: fileURLToPath(new URL(`./fixtures/${mode}-child-session.jsonl`, import.meta.url)),
|
||||
});
|
||||
const events = await verifySubagentFixture(fixture);
|
||||
const updates = events.flatMap(({ event }) => (event.type === "upsert" ? [event] : []));
|
||||
expect(updates.map((event) => event.status)).toEqual(statuses);
|
||||
expect(new Set(updates.map((event) => event.id)).size).toBe(1);
|
||||
expect(events.some(({ event }) => event.type === "timeline")).toBe(true);
|
||||
});
|
||||
|
||||
test.each(["foreground", "background"])(
|
||||
"restores a completed %s child and its transcript to the consumer store",
|
||||
async (mode) => {
|
||||
const fixture = readSubagentFixture(new URL(`./fixtures/${mode}.json`, import.meta.url), {
|
||||
from: `/tmp/paseo-edxeth-fixture/${mode}/child-session.jsonl`,
|
||||
to: fileURLToPath(new URL(`./fixtures/${mode}-child-session.jsonl`, import.meta.url)),
|
||||
});
|
||||
const store = new ProviderSubagentStore();
|
||||
for await (const event of streamPiHistory("pi", fixture.messages)) {
|
||||
if (event.type === "provider_subagent") store.apply("parent", "pi", event.event);
|
||||
}
|
||||
const children = store.list("parent");
|
||||
expect(children).toEqual([expect.objectContaining({ status: "completed", title: "marker" })]);
|
||||
const transcript = store.fetchTimeline("parent", children[0]!.id);
|
||||
expect(transcript.rows).toContainEqual(
|
||||
expect.objectContaining({
|
||||
item: expect.objectContaining({
|
||||
type: "assistant_message",
|
||||
text: mode === "foreground" ? "PASEO_EDXETH_UPSTREAM_OK" : "PASEO_EDXETH_LEAN_OK",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test("settles a synchronous result on the card created when the tool started", () => {
|
||||
const host = createPiExtensionHost();
|
||||
const call = { callId: "spawn-1", toolName: "subagent", args };
|
||||
const start = host.mapToolCall({ ...call, status: "running", result: null });
|
||||
expect(start?.subagents).toEqual([
|
||||
{
|
||||
type: "upsert",
|
||||
id: "spawn-1",
|
||||
title: "scout",
|
||||
description: args.task,
|
||||
toolCallId: "spawn-1",
|
||||
status: "running",
|
||||
},
|
||||
]);
|
||||
const end = host.mapToolCall({
|
||||
...call,
|
||||
status: "completed",
|
||||
result: {
|
||||
content: [{ type: "text", text: "DONE" }],
|
||||
details: {
|
||||
id: "run-1",
|
||||
name: args.name,
|
||||
agent: args.agent,
|
||||
mode: "background",
|
||||
status: "completed",
|
||||
deliveryState: "awaited",
|
||||
exitCode: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(end?.subagents).toEqual([
|
||||
{
|
||||
type: "upsert",
|
||||
id: "spawn-1",
|
||||
title: "scout",
|
||||
description: args.task,
|
||||
toolCallId: "spawn-1",
|
||||
status: "completed",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
-119
@@ -1,119 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import { extractTextFromToolResult } from "../../tool-call-mapper.js";
|
||||
import type { PiChildSessionFile, PiExtension } from "../contract.js";
|
||||
import type { ProviderSubagentInputEvent } from "../../../../provider-subagents/store.js";
|
||||
|
||||
const Run = z
|
||||
.object({
|
||||
id: z.string().trim().min(1),
|
||||
name: z.string().trim().min(1),
|
||||
agent: z.string().trim().min(1).optional(),
|
||||
task: z.string().optional(),
|
||||
status: z.enum(["started", "completed", "failed", "cancelled", "pinged"]),
|
||||
sessionFile: z.string().trim().min(1).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
const Args = z.object({ task: z.string().optional() }).passthrough();
|
||||
const Batch = z.object({ status: z.enum(["started", "batch"]), children: z.array(Run).min(1) });
|
||||
const Completion = z
|
||||
.object({
|
||||
id: z.string().trim().min(1),
|
||||
status: z.enum(["completed", "failed", "cancelled", "pinged"]).optional(),
|
||||
error: z.string().optional(),
|
||||
sessionFile: z.string().trim().min(1).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
const Ping = Completion.extend({ message: z.string() });
|
||||
|
||||
function childStatus(status: z.infer<typeof Run>["status"]) {
|
||||
if (status === "started") return "running";
|
||||
// A ping ends the child process and needs a new resume run. It is not success.
|
||||
if (status === "cancelled" || status === "pinged") return "canceled";
|
||||
return status;
|
||||
}
|
||||
|
||||
export const edxethPiSubagents: PiExtension = {
|
||||
id: "edxeth/pi-subagents",
|
||||
createSession: () => {
|
||||
const callsByRun = new Map<string, string>();
|
||||
const completions = new Map<string, z.infer<typeof Completion>>();
|
||||
const readSessions = new Map<string, string>();
|
||||
const childSession = (id: string, file: string | undefined): PiChildSessionFile[] => {
|
||||
if (!file || readSessions.get(id) === file) return [];
|
||||
readSessions.set(id, file);
|
||||
return [{ id, file }];
|
||||
};
|
||||
const completeRun = (result: z.infer<typeof Completion>) => {
|
||||
const status = result.status ?? (result.error === undefined ? undefined : "failed");
|
||||
if (!status) return undefined;
|
||||
// A fast child can finish before the tool returns its run id. Keep the
|
||||
// terminal outcome so a later "started" acknowledgement cannot regress it.
|
||||
completions.set(result.id, { ...result, status });
|
||||
const id = callsByRun.get(result.id);
|
||||
if (!id) return undefined;
|
||||
const subagents: ProviderSubagentInputEvent[] = [
|
||||
{
|
||||
type: "upsert",
|
||||
id,
|
||||
status: childStatus(status),
|
||||
...(status === "pinged" ? { subtitle: "Needs help" } : {}),
|
||||
},
|
||||
];
|
||||
return { subagents, childSessions: childSession(id, result.sessionFile) };
|
||||
};
|
||||
return {
|
||||
mapToolCall(call) {
|
||||
const isLaunch = call.toolName === "subagent" || call.toolName === "subagent_resume";
|
||||
if (!isLaunch || call.status === "running") return undefined;
|
||||
const details = typeof call.result === "object" ? call.result?.details : null;
|
||||
const single = Run.safeParse(details);
|
||||
let runs: z.infer<typeof Run>[];
|
||||
if (single.success) {
|
||||
runs = [single.data];
|
||||
} else {
|
||||
const batch = Batch.safeParse(details);
|
||||
if (!batch.success) return undefined;
|
||||
runs = batch.data.children;
|
||||
}
|
||||
const args = Args.safeParse(call.args);
|
||||
const description = args.success ? args.data.task : undefined;
|
||||
const subagents: ProviderSubagentInputEvent[] = [];
|
||||
const childSessions: PiChildSessionFile[] = [];
|
||||
for (const [index, run] of runs.entries()) {
|
||||
const id = runs.length === 1 ? call.callId : `${call.callId}:${index}`;
|
||||
const completion = completions.get(run.id);
|
||||
const status = completion?.status ?? run.status;
|
||||
callsByRun.set(run.id, id);
|
||||
subagents.push({
|
||||
type: "upsert",
|
||||
id,
|
||||
title: run.agent ?? run.name,
|
||||
description: run.task ?? description,
|
||||
toolCallId: call.callId,
|
||||
status: childStatus(status),
|
||||
...(status === "pinged" ? { subtitle: "Needs help" } : {}),
|
||||
});
|
||||
childSessions.push(...childSession(id, completion?.sessionFile ?? run.sessionFile));
|
||||
}
|
||||
return {
|
||||
detail: {
|
||||
type: "sub_agent",
|
||||
description,
|
||||
log: extractTextFromToolResult(call.result)?.trim() ?? "",
|
||||
},
|
||||
subagents,
|
||||
childSessions,
|
||||
};
|
||||
},
|
||||
mapCustomMessage(message) {
|
||||
if (message.customType === "subagent_ping") {
|
||||
const ping = Ping.safeParse(message.details);
|
||||
return ping.success ? completeRun({ ...ping.data, status: "pinged" }) : undefined;
|
||||
}
|
||||
if (message.customType !== "subagent_result") return undefined;
|
||||
const parsed = Completion.safeParse(message.details);
|
||||
return parsed.success ? completeRun(parsed.data) : undefined;
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -1,6 +1,5 @@
|
||||
import { piAskUser } from "./pi-ask-user/index.js";
|
||||
import { piSubagents } from "./pi-subagents/index.js";
|
||||
import { edxethPiSubagents } from "./edxeth-pi-subagents/index.js";
|
||||
import { piMcpAdapter } from "./pi-mcp-adapter/index.js";
|
||||
import { rpivTodo } from "./rpiv-todo/index.js";
|
||||
import { piExampleTodo } from "./pi-example-todo/index.js";
|
||||
@@ -11,7 +10,6 @@ import { rpivAskUserQuestion } from "./rpiv-ask-user-question/index.js";
|
||||
|
||||
export const piExtensions = [
|
||||
piAskUser, // Dialog correlation
|
||||
edxethPiSubagents, // Structured results before the generic subagent tool matcher
|
||||
piSubagents, // Delegation calls
|
||||
tintinwebPiSubagents,
|
||||
gotgenesPiSubagents,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import type { AgentSessionConfig } from "./agent-sdk-types.js";
|
||||
import { stripInternalPaseoMcpServer, withRuntimePaseoMcpServer } from "./runtime-mcp-config.js";
|
||||
import { withRuntimePaseoMcpServer } from "./runtime-mcp-config.js";
|
||||
|
||||
const BASE_CONFIG: AgentSessionConfig = {
|
||||
provider: "claude",
|
||||
@@ -49,15 +49,3 @@ describe("withRuntimePaseoMcpServer", () => {
|
||||
expect(result.mcpServers).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
test("stripping an internal MCP server also strips its launch requirement", () => {
|
||||
const result = stripInternalPaseoMcpServer({
|
||||
...BASE_CONFIG,
|
||||
mcpServerRequirements: { paseo: "optional", hub: "optional" },
|
||||
mcpServers: {
|
||||
paseo: { type: "http", url: "http://127.0.0.1/mcp/agents?callerAgentId=agent-1" },
|
||||
hub: { type: "http", url: "https://hub.test/mcp" },
|
||||
},
|
||||
});
|
||||
expect(result.mcpServerRequirements).toEqual({ hub: "optional" });
|
||||
});
|
||||
|
||||
@@ -18,11 +18,6 @@ export function stripInternalPaseoMcpServer(config: AgentSessionConfig): AgentSe
|
||||
delete nextMcpServers[PASEO_MCP_SERVER_NAME];
|
||||
|
||||
const next = { ...config };
|
||||
if (next.mcpServerRequirements?.[PASEO_MCP_SERVER_NAME]) {
|
||||
next.mcpServerRequirements = { ...next.mcpServerRequirements };
|
||||
delete next.mcpServerRequirements[PASEO_MCP_SERVER_NAME];
|
||||
if (Object.keys(next.mcpServerRequirements).length === 0) delete next.mcpServerRequirements;
|
||||
}
|
||||
if (Object.keys(nextMcpServers).length > 0) {
|
||||
next.mcpServers = nextMcpServers;
|
||||
} else {
|
||||
|
||||
@@ -420,6 +420,7 @@ export interface PaseoDaemonConfig {
|
||||
trustedProxies?: true | string[];
|
||||
mcpEnabled?: boolean;
|
||||
mcpInjectIntoAgents?: boolean;
|
||||
usageEnabled?: boolean;
|
||||
browserToolsEnabled?: boolean;
|
||||
git?: {
|
||||
maxProcessesPerSecond: number;
|
||||
@@ -590,6 +591,7 @@ function createInitialMutableDaemonConfig(config: ResolvedDaemonSettings): Mutab
|
||||
...(config.providerCatalogRefreshTimeoutMs !== undefined
|
||||
? { catalogRefreshTimeoutMs: config.providerCatalogRefreshTimeoutMs }
|
||||
: {}),
|
||||
usage: { enabled: config.usageEnabled !== false },
|
||||
browserTools: { enabled: config.browserToolsEnabled ?? false },
|
||||
providers,
|
||||
metadataGeneration: {
|
||||
|
||||
@@ -523,6 +523,10 @@ function resolveAppendSystemPrompt(persisted: ReturnType<typeof loadPersistedCon
|
||||
return persisted.daemon?.appendSystemPrompt ?? "";
|
||||
}
|
||||
|
||||
function resolveUsageEnabled(persisted: ReturnType<typeof loadPersistedConfig>): boolean {
|
||||
return persisted.daemon?.usage?.enabled !== false;
|
||||
}
|
||||
|
||||
function resolveBrowserToolsEnabled(persisted: ReturnType<typeof loadPersistedConfig>): boolean {
|
||||
return persisted.daemon?.browserTools?.enabled ?? false;
|
||||
}
|
||||
@@ -548,6 +552,7 @@ function resolveStaticLoadConfigSettings(
|
||||
mcpEnabled: cli?.mcpEnabled ?? persisted.daemon?.mcp?.enabled ?? true,
|
||||
mcpInjectIntoAgents:
|
||||
cli?.mcpInjectIntoAgents ?? persisted.daemon?.mcp?.injectIntoAgents ?? false,
|
||||
usageEnabled: resolveUsageEnabled(persisted),
|
||||
browserToolsEnabled: resolveBrowserToolsEnabled(persisted),
|
||||
autoArchiveAfterMerge: persisted.daemon?.autoArchiveAfterMerge ?? false,
|
||||
appendSystemPrompt: resolveAppendSystemPrompt(persisted),
|
||||
@@ -576,6 +581,7 @@ export type ResolvedDaemonSettings = Pick<
|
||||
| "trustedProxies"
|
||||
| "mcpEnabled"
|
||||
| "mcpInjectIntoAgents"
|
||||
| "usageEnabled"
|
||||
| "browserToolsEnabled"
|
||||
| "git"
|
||||
| "autoArchiveAfterMerge"
|
||||
|
||||
@@ -10,6 +10,10 @@ import { readSpeechSettings } from "./speech/speech-settings.js";
|
||||
import type { PersistedConfig } from "./persisted-config.js";
|
||||
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
|
||||
|
||||
function usageEnabled(persisted: PersistedConfig): boolean {
|
||||
return persisted.daemon?.usage?.enabled !== false;
|
||||
}
|
||||
|
||||
function reloadableConfig(
|
||||
persisted: PersistedConfig,
|
||||
options: { relayEnabledFallback?: boolean } = {},
|
||||
@@ -23,6 +27,7 @@ function reloadableConfig(
|
||||
enabled: relay.enabled ?? options.relayEnabledFallback ?? true,
|
||||
},
|
||||
mcp: { enabled: true, injectIntoAgents: false },
|
||||
usage: { enabled: usageEnabled(persisted) },
|
||||
browserTools: { enabled: daemon.browserTools?.enabled ?? false },
|
||||
providers: (agents.providers ?? {}) as MutableDaemonConfig["providers"],
|
||||
metadataGeneration: { providers: agents.metadataGeneration?.providers ?? [] },
|
||||
@@ -1572,3 +1577,31 @@ describe("DaemonConfigStore speech settings", () => {
|
||||
expect(JSON.stringify(other.get())).not.toContain("secret");
|
||||
});
|
||||
});
|
||||
|
||||
test("usage policy persists across restart and live reload", async () => {
|
||||
const paseoHome = mkdtempSync(path.join(tmpdir(), "usage-policy-"));
|
||||
try {
|
||||
const initial = reloadableConfig({});
|
||||
const store = new DaemonConfigStore(paseoHome, initial, undefined, {
|
||||
reloadSource: {
|
||||
resolve: (persisted) => ({
|
||||
mutable: reloadableConfig(persisted),
|
||||
overrideControlledPaths: [],
|
||||
}),
|
||||
},
|
||||
});
|
||||
await store.patch({ usage: { enabled: false } });
|
||||
expect(loadConfig(paseoHome, { env: {} }).usageEnabled).toBe(false);
|
||||
const persisted = loadPersistedConfig(paseoHome);
|
||||
const restarted = new DaemonConfigStore(paseoHome, reloadableConfig(persisted));
|
||||
expect(restarted.get().usage).toEqual({ enabled: false });
|
||||
writeFileSync(
|
||||
path.join(paseoHome, "config.json"),
|
||||
JSON.stringify({ daemon: { usage: { enabled: true } } }),
|
||||
);
|
||||
await store.reload();
|
||||
expect(store.get().usage).toEqual({ enabled: true });
|
||||
} finally {
|
||||
rmSync(paseoHome, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -22,6 +22,7 @@ type ProviderOverride = import("./agent/provider-launch-config.js").ProviderOver
|
||||
interface SupportedMutableConfigPatch {
|
||||
relay?: { enabled?: boolean; requireProtectedSecurity?: boolean };
|
||||
mcp?: { injectIntoAgents?: boolean };
|
||||
usage?: { enabled: boolean };
|
||||
browserTools?: { enabled?: boolean };
|
||||
providers?: MutableDaemonConfig["providers"];
|
||||
removeProviders?: string[];
|
||||
@@ -182,6 +183,7 @@ const RELOADABLE_PATHS = [
|
||||
"daemon.relay.requireProtectedSecurity",
|
||||
"daemon.mcp.enabled",
|
||||
"daemon.mcp.injectIntoAgents",
|
||||
"daemon.usage.enabled",
|
||||
"daemon.browserTools.enabled",
|
||||
"daemon.hostnames",
|
||||
"daemon.cors.allowedOrigins",
|
||||
@@ -209,6 +211,7 @@ const PERSISTED_TO_MUTABLE_PATH = new Map<string, string>([
|
||||
["daemon.relay.requireProtectedSecurity", "relay.requireProtectedSecurity"],
|
||||
["daemon.mcp.enabled", "mcp.enabled"],
|
||||
["daemon.mcp.injectIntoAgents", "mcp.injectIntoAgents"],
|
||||
["daemon.usage.enabled", "usage.enabled"],
|
||||
["daemon.browserTools.enabled", "browserTools.enabled"],
|
||||
["daemon.hostnames", "hostnames"],
|
||||
["daemon.cors.allowedOrigins", "cors.allowedOrigins"],
|
||||
@@ -281,6 +284,7 @@ function pickRelayPatch(
|
||||
function pickSupportedPatchFields(patch: MutableDaemonConfigPatch): SupportedMutableConfigPatch {
|
||||
return {
|
||||
...pickRelayPatch(patch.relay),
|
||||
usage: patch.usage,
|
||||
...(patch.mcp?.injectIntoAgents !== undefined
|
||||
? { mcp: { injectIntoAgents: patch.mcp.injectIntoAgents } }
|
||||
: {}),
|
||||
@@ -767,6 +771,7 @@ function mergeMutableDaemonPatch(
|
||||
if (patch.mcp?.injectIntoAgents !== undefined) {
|
||||
next.mcp = { ...next.mcp, injectIntoAgents: patch.mcp.injectIntoAgents };
|
||||
}
|
||||
if (patch.usage) next.usage = patch.usage;
|
||||
if (patch.browserTools?.enabled !== undefined) {
|
||||
next.browserTools = { ...next.browserTools, enabled: patch.browserTools.enabled };
|
||||
}
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import pino from "pino";
|
||||
|
||||
import { CodexAppServerAgentClient } from "../agent/providers/codex-app-server-agent.js";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createMessageCollector } from "../test-utils/message-collector.js";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { canRunRealProvider } from "./real-provider-test-config.js";
|
||||
|
||||
test("keeps two concurrent startup steer messages in one real Codex turn", async (context) => {
|
||||
if (!(await canRunRealProvider("codex"))) {
|
||||
context.skip();
|
||||
return;
|
||||
}
|
||||
const cwd = mkdtempSync(path.join(tmpdir(), "codex-steer-starting-"));
|
||||
const logger = pino({ level: "silent" });
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
agentClients: { codex: new CodexAppServerAgentClient(logger) },
|
||||
logger,
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
const collector = createMessageCollector(client);
|
||||
const subscriptions: ReturnType<DaemonClient["subscribeAgentTimeline"]>[] = [];
|
||||
try {
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
const agent = await client.createAgent({
|
||||
cwd,
|
||||
provider: "codex",
|
||||
modeId: "full-access",
|
||||
});
|
||||
const subscription = client.subscribeAgentTimeline(agent.id, () => {});
|
||||
subscriptions.push(subscription);
|
||||
await subscription.ready;
|
||||
await Promise.all([
|
||||
client.sendAgentMessage(agent.id, "Reply exactly: FIRST", {
|
||||
messageId: `first-${attempt}`,
|
||||
activeTurnBehavior: "steer",
|
||||
}),
|
||||
client.sendAgentMessage(agent.id, "Reply exactly: SECOND", {
|
||||
messageId: `second-${attempt}`,
|
||||
activeTurnBehavior: "steer",
|
||||
}),
|
||||
]);
|
||||
await client.waitForFinish(agent.id, 90_000);
|
||||
const timeline = await client.fetchAgentTimeline(agent.id, { limit: 100 });
|
||||
const users = timeline.entries.filter((entry) => entry.item.type === "user_message");
|
||||
const events = collector.messages.flatMap((message) =>
|
||||
message.type === "agent_stream" && message.payload.agentId === agent.id
|
||||
? [message.payload.event]
|
||||
: [],
|
||||
);
|
||||
expect(users.map((entry) => entry.item.text).sort()).toEqual([
|
||||
"Reply exactly: FIRST",
|
||||
"Reply exactly: SECOND",
|
||||
]);
|
||||
expect(new Set(users.map((entry) => entry.turnId)).size).toBe(1);
|
||||
expect(events.filter((event) => event.type === "turn_started")).toHaveLength(1);
|
||||
expect(
|
||||
events.filter((event) => event.type === "turn_canceled" || event.type === "turn_failed"),
|
||||
).toHaveLength(0);
|
||||
expect(
|
||||
timeline.entries.some(
|
||||
(entry) =>
|
||||
entry.item.type === "assistant_message" && entry.item.text.includes("[System Error]"),
|
||||
),
|
||||
).toBe(false);
|
||||
}
|
||||
} finally {
|
||||
await Promise.all(subscriptions.map((subscription) => subscription.release()));
|
||||
collector.unsubscribe();
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
}, 300_000);
|
||||
@@ -248,7 +248,7 @@ test("ordinary Hub requests survive daemon restart and restore an archived works
|
||||
}),
|
||||
).toMatchObject({ payload: { agentId, accepted: true } });
|
||||
expect(hub.providerPromptTexts().filter((text) => text === "follow up")).toHaveLength(1);
|
||||
});
|
||||
}, 20_000);
|
||||
|
||||
test("Hub completes the standard hello before rejecting a second hello", async () => {
|
||||
const hub = await launchRelationship();
|
||||
|
||||
@@ -259,6 +259,7 @@ export const PersistedConfigSchema = z
|
||||
})
|
||||
.passthrough()
|
||||
.optional(),
|
||||
usage: z.object({ enabled: z.boolean().optional() }).optional(),
|
||||
browserTools: z
|
||||
.object({
|
||||
enabled: z.boolean().optional(),
|
||||
|
||||
@@ -214,14 +214,3 @@ describe("persistence hooks", () => {
|
||||
expect(handle).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
test("restores optional MCP requirements for continuation", () => {
|
||||
const record = createRecord({
|
||||
config: {
|
||||
mcpServerRequirements: { hub: "optional" },
|
||||
mcpServers: { hub: { type: "http", url: "https://hub.test/mcp" } },
|
||||
},
|
||||
});
|
||||
expect(buildConfigOverrides(record).mcpServerRequirements).toEqual({ hub: "optional" });
|
||||
expect(buildSessionConfig(record)?.mcpServerRequirements).toEqual({ hub: "optional" });
|
||||
});
|
||||
|
||||
@@ -78,7 +78,6 @@ export function buildConfigOverrides(record: StoredAgentRecord): Partial<AgentSe
|
||||
toolPolicy: record.config?.toolPolicy ?? undefined,
|
||||
systemPrompt: record.config?.systemPrompt ?? undefined,
|
||||
mcpServers: record.config?.mcpServers ?? undefined,
|
||||
mcpServerRequirements: record.config?.mcpServerRequirements ?? undefined,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -101,7 +100,6 @@ export function buildSessionConfig(
|
||||
toolPolicy: overrides.toolPolicy,
|
||||
systemPrompt: overrides.systemPrompt,
|
||||
mcpServers: overrides.mcpServers,
|
||||
mcpServerRequirements: overrides.mcpServerRequirements,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, test } from "vitest";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import type { AgentClient, AgentSessionConfig } from "../agent/agent-sdk-types.js";
|
||||
import type { AgentSessionConfig } from "../agent/agent-sdk-types.js";
|
||||
import { createTestAgentClient } from "../test-utils/fake-agent-client.js";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
|
||||
@@ -72,71 +72,3 @@ test("the configuration example saves Codex options and injects launch-only MCP
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("session-open entrypoint contributions are optional and rederived for existing agents", async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-entrypoint-hook-"));
|
||||
const launches: { provider: string; env?: Record<string, string> }[] = [];
|
||||
function recordingProvider(provider: "claude" | "codex"): AgentClient {
|
||||
const inner = createTestAgentClient(provider);
|
||||
return {
|
||||
provider: inner.provider,
|
||||
capabilities: inner.capabilities,
|
||||
isAvailable: () => inner.isAvailable(),
|
||||
fetchCatalog: (options) => inner.fetchCatalog(options),
|
||||
createSession: async (...args: Parameters<typeof inner.createSession>) => {
|
||||
launches.push({ provider, env: args[1]?.env });
|
||||
return inner.createSession(...args);
|
||||
},
|
||||
resumeSession: async (...args: Parameters<typeof inner.resumeSession>) => {
|
||||
launches.push({ provider, env: args[2]?.env });
|
||||
return inner.resumeSession(...args);
|
||||
},
|
||||
};
|
||||
}
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
daemonVersion: "0.14.0-beta.2",
|
||||
agentClients: { claude: recordingProvider("claude"), codex: recordingProvider("codex") },
|
||||
mcpEnabled: false,
|
||||
});
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
appVersion: "0.14.0-beta.2",
|
||||
});
|
||||
try {
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "entrypoint-test", requirements: { paseo: ">=0.14.0-beta.2" } }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(directory, "index.server.ts"),
|
||||
`
|
||||
export default function contribute(server) {
|
||||
return server.before("agent.session_open", ({ request }) => {
|
||||
if (request.provider !== "claude") return;
|
||||
return { ...request, env: { ...request.env, CLAUDE_CODE_ENTRYPOINT: "custom-client" } };
|
||||
});
|
||||
}
|
||||
`,
|
||||
);
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
const existing = await client.createAgent({ provider: "claude", cwd: directory });
|
||||
expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBeUndefined();
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(directory);
|
||||
await daemon.daemon.agentManager.reloadAgentSession(existing.id);
|
||||
expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBe("custom-client");
|
||||
await client.createAgent({ provider: "claude", cwd: directory });
|
||||
expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBe("custom-client");
|
||||
await client.createAgent({ provider: "codex", cwd: directory });
|
||||
expect(launches.at(-1)).toMatchObject({ provider: "codex" });
|
||||
expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBeUndefined();
|
||||
await client.disablePlugin("entrypoint-test");
|
||||
await daemon.daemon.agentManager.reloadAgentSession(existing.id);
|
||||
expect(launches.at(-1)?.env?.CLAUDE_CODE_ENTRYPOINT).toBeUndefined();
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
@@ -1042,6 +1042,7 @@ export class Session {
|
||||
logger: this.sessionLogger,
|
||||
});
|
||||
this.usageSession = new UsageSession({
|
||||
isEnabled: () => daemonConfigStore.get().usage?.enabled !== false,
|
||||
emit: (msg) => this.emit(msg),
|
||||
runtime: pluginRuntime,
|
||||
logger: this.sessionLogger,
|
||||
|
||||
@@ -15,6 +15,7 @@ test("lists reports from usage sources", async () => {
|
||||
report: { status: "available" as const, windows: [] },
|
||||
};
|
||||
const usage = new UsageSession({
|
||||
isEnabled: () => true,
|
||||
emit: (message) => emitted.push(message),
|
||||
runtime: {
|
||||
async listUsageReports(options) {
|
||||
@@ -40,6 +41,7 @@ test("lists reports from usage sources", async () => {
|
||||
test("surfaces a legacy usage-list failure as an rpc_error envelope", async () => {
|
||||
const emitted: SessionOutboundMessage[] = [];
|
||||
const usage = new UsageSession({
|
||||
isEnabled: () => true,
|
||||
emit: (message) => emitted.push(message),
|
||||
runtime: {
|
||||
async listUsageReports() {
|
||||
@@ -61,6 +63,7 @@ test("surfaces a legacy usage-list failure as an rpc_error envelope", async () =
|
||||
test("request failures terminate with an error response and no updates", async () => {
|
||||
const emitted: SessionOutboundMessage[] = [];
|
||||
const usage = new UsageSession({
|
||||
isEnabled: () => true,
|
||||
emit: (message) => emitted.push(message),
|
||||
logger: pino({ level: "silent" }),
|
||||
});
|
||||
@@ -72,3 +75,36 @@ test("request failures terminate with an error response and no updates", async (
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("off rejects both protocols before runtime discovery and turning on restores reports", async () => {
|
||||
let enabled = false;
|
||||
let calls = 0;
|
||||
const emitted: SessionOutboundMessage[] = [];
|
||||
const usage = new UsageSession({
|
||||
isEnabled: () => enabled,
|
||||
emit: (message) => emitted.push(message),
|
||||
logger: pino({ level: "silent" }),
|
||||
runtime: {
|
||||
async listUsageReports() {
|
||||
calls++;
|
||||
return [];
|
||||
},
|
||||
async listLegacyUsage() {
|
||||
calls++;
|
||||
return { fetchedAt: "now", providers: [] };
|
||||
},
|
||||
},
|
||||
});
|
||||
await usage.handleListReports({ type: "usage.list_reports.request", requestId: "off" });
|
||||
await usage.handleLegacyList({ type: "provider.usage.list.request", requestId: "old" });
|
||||
expect(calls).toBe(0);
|
||||
expect(emitted[0]).toMatchObject({ payload: { error: "Usage is off on this host." } });
|
||||
expect(emitted[1]).toMatchObject({
|
||||
type: "rpc_error",
|
||||
payload: { error: "Usage is off on this host." },
|
||||
});
|
||||
enabled = true;
|
||||
await usage.handleListReports({ type: "usage.list_reports.request", requestId: "on" });
|
||||
expect(calls).toBe(1);
|
||||
expect(emitted[2]).toMatchObject({ payload: { error: null } });
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ export interface UsageSessionOptions {
|
||||
listUsageReports(options: ListUsageReportsOptions): Promise<UsageReportEntry[]>;
|
||||
listLegacyUsage(): Promise<{ fetchedAt: string; providers: ProviderUsage[] }>;
|
||||
};
|
||||
isEnabled: () => boolean;
|
||||
logger: pino.Logger;
|
||||
}
|
||||
|
||||
@@ -19,6 +20,7 @@ export class UsageSession {
|
||||
msg: Extract<SessionInboundMessage, { type: "usage.list_reports.request" }>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (!this.options.isEnabled()) throw new Error("Usage is off on this host.");
|
||||
if (!this.options.runtime) throw new Error("Plugin runtime is unavailable");
|
||||
await this.options.runtime.listUsageReports({
|
||||
forceRefresh: msg.forceRefresh,
|
||||
@@ -49,6 +51,18 @@ export class UsageSession {
|
||||
async handleLegacyList(
|
||||
msg: Extract<SessionInboundMessage, { type: "provider.usage.list.request" }>,
|
||||
): Promise<void> {
|
||||
if (!this.options.isEnabled()) {
|
||||
this.options.emit({
|
||||
type: "rpc_error",
|
||||
payload: {
|
||||
requestId: msg.requestId,
|
||||
requestType: msg.type,
|
||||
error: "Usage is off on this host.",
|
||||
code: "provider_usage_list_failed",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (!this.options.runtime) throw new Error("Plugin runtime is unavailable");
|
||||
const usage = await this.options.runtime.listLegacyUsage();
|
||||
|
||||
@@ -1949,6 +1949,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
hostMultiplexing: true,
|
||||
// COMPAT(relayProtectedSecurity): added in v0.13.0, remove gate after 2027-04-21.
|
||||
relayProtectedSecurity: true,
|
||||
usageSetting: true,
|
||||
usageSources: true,
|
||||
ownedSubscriptions: true,
|
||||
agentRequestReceipts: true,
|
||||
@@ -1966,7 +1967,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
workspaceSortTimes: true,
|
||||
// COMPAT(providersSnapshot): keep optional until all clients rely on snapshot flow.
|
||||
providersSnapshot: true,
|
||||
optionalMcpSupport: true,
|
||||
// COMPAT(providersSnapshotCwd): added in v0.3.2, remove gate after 2027-02-10.
|
||||
providersSnapshotCwd: true,
|
||||
// COMPAT(checkoutForgeSetAutoMerge): added in v0.2.0-beta.1. Remove the
|
||||
|
||||
@@ -70,6 +70,14 @@
|
||||
},
|
||||
"additionalProperties": {}
|
||||
},
|
||||
"usage": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
},
|
||||
"browserTools": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
Reference in New Issue
Block a user