Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 7762ce0639 chore(release): cut 0.18.2 2026-11-30 06:17:10 +01:00
Mohamed Boudra 10e0a4364e docs(changelog): add 0.18.2 release notes 2026-11-30 06:11:54 +01:00
96 changed files with 328 additions and 4409 deletions
+1 -1
View File
@@ -59,7 +59,7 @@ jobs:
filters: .github/ci-paths.yml
- name: Validate CI contracts
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs scripts/precompress-assets.test.mjs
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs
quality:
name: quality
-2
View File
@@ -523,8 +523,6 @@ Measured bundle size for a standard Expo web export:
- gzip: 2.55 MiB
- brotli: 1.93 MiB
`npm run build:desktop` runs the same `scripts/precompress-assets.mjs` over `packages/app/dist` before electron-builder copies it to `app-dist`, so the desktop-served UI also gets `.br`/`.gz` siblings.
The desktop-managed daemon disables the bundled web UI by default (`PASEO_WEB_UI_ENABLED=false`) because the desktop app already ships the renderer as `app-dist`. Shipping the same assets again inside `@getpaseo/server` would duplicate the ~10.8 MiB install. Desktop packaging also excludes `node_modules/@getpaseo/server/dist/server/web-ui/**` from the packaged app.
## Built workspace packages
+4 -11
View File
@@ -447,17 +447,10 @@ wide layouts keep local geometry. That export is
what `patches/@gorhom+bottom-sheet+*.patch` adds.
A sheet whose owner may veto the close (unsaved work) passes `enableDismissOnClose={false}`. Every
close path then parks the sheet at index -1 with its content mounted; the owner runs its guard and
either snaps back to 0 or drops its state, which unmounts the sheet and takes it off the stack.
Calling `dismiss()` on such a sheet bypasses the guard and unmounts it, so its backdrop and Back
press call `close()`.
Run that guard from the wrapper's `onClosed`. Gorhom only calls `onChange` when a close ends at a
different index than the one it already recorded, and an interrupted mount animation leaves that
record at -1, so the close that follows is invisible: the sheet parks with its backdrop still over
the app, and every tap in the covered area is lost. `onClosed` watches the close animation settle at
the closed detent and reports it either way. Keeping `onChange` as well is harmless as long as the
guard is idempotent.
close path then parks the sheet at index -1 with its content mounted; the owner hears
`onChange(-1)`, runs its guard, and either snaps back to 0 or drops its state, which unmounts the
sheet and takes it off the stack. Calling `dismiss()` on such a sheet bypasses the guard and
unmounts it, so its backdrop and Back press call `close()`.
The wrapper must give Gorhom an object ref. Gorhom accepts a callback ref at the React boundary
but stores it in the modal queue and later reads `.current`; provider dismissal, replacement,
+1 -1
View File
@@ -4,7 +4,7 @@ Paseo Hub is an explicit opt-in connection from one Paseo daemon to one Hub. Run
not register it with a Hub. The relationship begins only when a user runs
`paseo hub connect [url]` from the daemon machine with an explicit API key or matching stored CLI login.
The human CLI login and daemon relationship are separate identities. `paseo hub login [url]` stores a durable organization-scoped CLI credential keyed by normalized Hub origin under `PASEO_HOME`. Interactive login optionally connects the local daemon, then points to the Hub UI for trigger configuration; it does not scaffold or deploy configuration. `paseo hub init` remains the explicit triggers-as-code scaffold: it writes one self-contained organization trigger under `.paseo/triggers/`, validates it through the trigger API, and optionally installs it. `paseo hub deploy` validates and installs every trigger in that directory; passing `--project` keeps deploying the legacy project bundle instead. `paseo hub export [directory]` writes the active organization's current triggers in the same layout, using the active login unless another Hub or API key is selected. `paseo hub run` dispatches a `manual.run` trigger through `POST /api/v1/manual-runs`, which takes inputs and prompt as one string; the CLI rejects what Hub would silently read as prompt text (`packages/cli/src/commands/hub/run/`). Origin resolution uses explicit command input, `PASEO_HUB_URL`, active login, then `https://hub.paseo.sh`. Connect uses exact-origin authority to request a one-time enrollment token, then passes only that token to the daemon. The daemon generates and persists its own relationship credential.
The human CLI login and daemon relationship are separate identities. `paseo hub login [url]` stores a durable organization-scoped CLI credential keyed by normalized Hub origin under `PASEO_HOME`. Interactive login optionally connects the local daemon, then points to the Hub UI for trigger configuration; it does not scaffold or deploy configuration. `paseo hub init` remains the explicit triggers-as-code scaffold: it writes one self-contained organization trigger under `.paseo/triggers/`, validates it through the trigger API, and optionally installs it. `paseo hub deploy` validates and installs every trigger in that directory; passing `--project` keeps deploying the legacy project bundle instead. `paseo hub export [directory]` writes the active organization's current triggers in the same layout, using the active login unless another Hub or API key is selected. Origin resolution uses explicit command input, `PASEO_HUB_URL`, active login, then `https://hub.paseo.sh`. Connect uses exact-origin authority to request a one-time enrollment token, then passes only that token to the daemon. The daemon generates and persists its own relationship credential.
## Connection and authority
+1 -1
View File
@@ -1 +1 @@
sha256-vrmauZ6dprc1M88FePLIvVT6FhgnmS9HjHGzPcCypyk=
sha256-34bUBmRmjekbUSp93597GLTmSWKt23TCHaK3ViXG+iU=
+1 -1
View File
@@ -99,7 +99,7 @@
"web": "npm run web --workspace=@getpaseo/app",
"dev:desktop": "cross-env PASEO_LISTEN=127.0.0.1:6768 npm run dev --workspace=@getpaseo/desktop",
"dev:win:desktop": "npm run dev:win --workspace=@getpaseo/desktop",
"build:desktop": "npm run build:app-deps:clean && cd packages/app && cross-env PASEO_WEB_PLATFORM=electron npx expo export --platform web && cd ../.. && node scripts/precompress-assets.mjs packages/app/dist && npm run build --workspace=@getpaseo/desktop --",
"build:desktop": "npm run build:app-deps:clean && cd packages/app && cross-env PASEO_WEB_PLATFORM=electron npx expo export --platform web && cd ../.. && npm run build --workspace=@getpaseo/desktop --",
"db:query": "npm run db:query --workspace=@getpaseo/server --",
"cli": "./scripts/dev-home.sh npx tsx packages/cli/src/index.js",
"version": "npm run version:sync-internal && npm run fdroid:changelogs && npm run release:prepare && git add -A",
@@ -1,6 +1,6 @@
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type Page } from "../support/fixtures";
import { expect, test } from "../support/fixtures";
import { expectComposerVisible } from "../support/helpers/composer";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { installLocalDesktopHost } from "../support/helpers/local-desktop-host";
@@ -282,63 +282,3 @@ test("compact opens files and subagents in a sheet, leaving the tabs for agents"
await workspace.cleanup();
}
});
async function openFileAndDismissDuringAnimation(page: Page) {
const fileLink = page.getByText(FILE_LINK, { exact: true });
await expect(fileLink).toBeVisible({ timeout: 15_000 });
// Check and press in the same browser frame so automation cannot outlast the opening animation.
await fileLink.evaluate((link) => {
if (!(link instanceof HTMLElement)) throw new Error("Expected an HTML file link");
return new Promise<void>((resolve, reject) => {
const timeout = window.setTimeout(() => {
cancelAnimationFrame(frame);
reject(new Error("The file sheet did not pass through the opening position"));
}, 5_000);
const dismissDuringOpening = () => {
const header = document.querySelector('[data-testid="sheet-tab-header"]');
const top = header?.getBoundingClientRect().top ?? window.innerHeight;
const pressTarget = document.elementFromPoint(10, 10);
if (
top > window.innerHeight / 2 &&
top < window.innerHeight &&
pressTarget instanceof HTMLElement &&
pressTarget.getAttribute("aria-label") === "Bottom sheet backdrop"
) {
window.clearTimeout(timeout);
pressTarget.click();
resolve();
return;
}
frame = requestAnimationFrame(dismissDuringOpening);
};
let frame = requestAnimationFrame(dismissDuringOpening);
link.click();
});
});
}
test("a sheet dismissed while it is still opening closes its tab", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
const workspace = await seedMockAgentWorkspace({
repoPrefix: "compact-sheet-opening-dismiss-",
title: "Sheet parent",
initialPrompt: promptMentioning(FILE_LINK),
});
try {
await writeFile(path.join(workspace.cwd, "linked.ts"), "one\ntwo\nthree\n", "utf8");
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
await openFileAndDismissDuringAnimation(page);
await expectNoSheetOpen(page);
await expectOpenTabCount(page, 1);
await page
.getByRole("button", { name: /Switch tabs/ })
.filter({ visible: true })
.click();
await expect(page.getByText("Workspace tabs", { exact: true })).toBeVisible();
} finally {
await workspace.cleanup();
}
});
@@ -63,8 +63,6 @@ using namespace facebook::react;
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
// The iOS status-bar tap region can overlap app header buttons (#11027).
self.scrollView.scrollsToTop = NO;
#if defined(__IPHONE_26_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_26_0
if (@available(iOS 26.0, *)) {
UIScrollView *scrollView = self.scrollView;
@@ -7,7 +7,7 @@ import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { RetainedPanelActivity } from "@/components/retained-panel";
import { hydrateStreamState, reduceStreamUpdate, type StreamItem } from "@/types/stream";
import { reduceStreamUpdate, type StreamItem } from "@/types/stream";
import type { StreamRenderInput, StreamSegmentRenderers, StreamViewportHandle } from "./strategy";
import { createWebStreamStrategy } from "./strategy-web";
@@ -1660,86 +1660,4 @@ describe("createWebStreamStrategy", () => {
expect(container.querySelector('[data-testid="agent-chat-scroll"]')).toBe(scrollContainer);
expect(scrollTo).toHaveBeenCalledWith({ top: 2200, behavior: "auto" });
});
it("renders batched user messages sharing a provider messageId without duplicate React keys", () => {
const sharedProviderMessageId = "9ffc3d6e-f0ff-4005-8675-e76e9c5eb5a8";
const historyMounted = hydrateStreamState(
[
{
event: {
type: "timeline",
provider: "claude",
item: {
type: "user_message",
text: "first queued prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-queued-1",
},
},
timestamp: new Date("2026-11-29T13:00:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
{
event: {
type: "timeline",
provider: "claude",
item: {
type: "user_message",
text: "second direct prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-direct-2",
},
},
timestamp: new Date("2026-11-29T13:00:01.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
{ source: "canonical" },
);
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
const renderers = createRenderers(() => {});
const strategy = createWebStreamStrategy({ isMobileBreakpoint: false });
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
const rendered = strategy.render({
agentId: "agent",
segments: { historyVirtualized: [], historyMounted, liveHead: [] },
boundary: {
hasVirtualizedHistory: false,
hasMountedHistory: true,
hasLiveHead: false,
},
renderers,
listEmptyComponent: null,
viewportRef: React.createRef<StreamViewportHandle>(),
routeBottomAnchorRequest: null,
isAuthoritativeHistoryReady: true,
onNearBottomChange: () => {},
onNearHistoryStart: async () => true,
isLoadingOlderHistory: false,
hasOlderHistory: false,
olderHistoryProgressKey: null,
scrollEnabled: true,
listStyle: null,
baseListContentContainerStyle: null,
forwardListContentContainerStyle: null,
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
});
act(() => {
root?.render(rendered);
});
const isSameKeyMessage = (arg: unknown) => typeof arg === "string" && arg.includes("same key");
const duplicateKeyErrors = consoleError.mock.calls.filter((args) =>
args.some(isSameKeyMessage),
);
expect(duplicateKeyErrors).toEqual([]);
expect(
Array.from(container.querySelectorAll("[data-history-row-id]")).map((node) =>
node.getAttribute("data-history-row-id"),
),
).toEqual(["client-queued-1", "client-direct-2"]);
});
});
+2 -3
View File
@@ -4,7 +4,6 @@ import type {
CommandCenterRegistration,
CommandCenterRegistrationOwner,
} from "./contributions";
import { compareText } from "@/utils/collation";
export interface CommandCenterRegistry {
getSnapshot(): CommandCenterContributionSnapshot;
@@ -29,10 +28,10 @@ function compareContributions(
right: CommandCenterContribution,
): number {
if (left.groupRank !== right.groupRank) return left.groupRank - right.groupRank;
const groupDelta = compareText(left.group, right.group);
const groupDelta = left.group.localeCompare(right.group);
if (groupDelta !== 0) return groupDelta;
if (left.rank !== right.rank) return left.rank - right.rank;
return compareText(left.id, right.id);
return left.id.localeCompare(right.id);
}
function sameContributions(
@@ -205,7 +205,6 @@ export function useWorkspaceCommandCenterActions(): void {
const { overrides } = useKeyboardShortcutOverrides();
const { gitActions, isGit, archiveWorkspace } = useGitActions({
serverId: serverId ?? "",
workspaceId,
cwd: cwd ?? "",
icons: GIT_ACTION_ICONS,
});
@@ -688,32 +688,6 @@ it("keeps workspace-relative hover titles on explicit absolute file links", () =
);
});
it.each([
[
"an angle-bracket destination",
"[Open](</repo/src/file.ts>)",
'[Open](</repo/src/file.ts> "src/file.ts")',
],
["an escaped slash", "[Open](\\/repo/src/file.ts)", '[Open](\\/repo/src/file.ts "src/file.ts")'],
[
"an escaped separator",
"[Open](/repo\\/src/file.ts)",
'[Open](/repo\\/src/file.ts "src/file.ts")',
],
[
"a character reference",
"[Open](&#x2F;repo/src/file.ts)",
'[Open](&#x2F;repo/src/file.ts "src/file.ts")',
],
])("keeps the workspace hover title on a link written with %s", (_form, source, rendered) => {
expect(prepareMarkdownSource(source, "/repo").render()).toBe(rendered);
});
it("leaves links outside the workspace as written", () => {
const source = "[Docs](https://example.com/repo/x) and [Other](/repository/x) near /repo/x";
expect(prepareMarkdownSource(source, "/repo").render()).toBe(source);
});
it.each(['""', "''", "()"])("preserves an authored empty link title: %s", (title) => {
const source = `[Open](/repo/file.ts ${title})`;
expect(prepareMarkdownSource(source, "/repo").render()).toBe(source);
@@ -150,13 +150,6 @@ function workspaceHoverTitle(link: Link, markup: string, workspaceRoot?: string)
return link.url.slice(workspaceRoot.length + 1);
}
// Only a link into the workspace gets an edit, its hover title. A link's URL differs from its
// source text only by backslash escapes and character references, and `&` already takes the parse.
function mayLinkIntoWorkspace(source: string, workspaceRoot?: string): boolean {
if (!workspaceRoot || !source.includes("](")) return false;
return source.includes(`${workspaceRoot}/`) || source.includes("\\");
}
/** Preserve source spelling; adapt workspace images, spoiler delimiters, and entity text. */
export function prepareMarkdownSource(
source: string,
@@ -198,7 +191,7 @@ export function prepareMarkdownSource(
!/^[\t >]*[^\t >\r\n][^\r\n]*(?:\r\n|\r|\n)[^\r\n]+(?:\r\n|\r|\n)(?=[\t >:|-]*\|)[\t >|]*:?-[-\t :|]*$/m.test(
source,
) &&
!mayLinkIntoWorkspace(source, workspaceRoot) &&
!(workspaceRoot && source.includes("](")) &&
!(external && /\]|<[a-z]+:/i.test(source))
) {
return { images, ...metadata, render: () => source };
@@ -2,7 +2,6 @@ import {
BottomSheetModal as GorhomBottomSheetModal,
type BottomSheetModalProps,
type BottomSheetBackdropProps,
useBottomSheetInternal,
} from "@gorhom/bottom-sheet";
import React from "react";
import {
@@ -26,7 +25,6 @@ import {
type AttachSheetContentDrag,
type SheetContentDragGesture,
} from "@/components/ui/bottom-sheet-scope";
import { runOnJS, useAnimatedReaction, useSharedValue } from "react-native-reanimated";
import { SheetBackdrop } from "./sheet-backdrop";
type GorhomBottomSheetModalMethods = ElementRef<typeof GorhomBottomSheetModal>;
@@ -58,7 +56,7 @@ type IsolatedBottomSheetModalProps = Omit<
/**
* Whether closing (drag, backdrop, Back) also dismisses, which unmounts the content. Default
* true: the owner hears `onDismiss` and drops its state. Pass `false` for a sheet whose close the
* owner may veto: it parks at index -1 with its content mounted, the owner hears `onClosed`,
* owner may veto: it parks at index -1 with its content mounted, the owner hears `onChange(-1)`,
* and either snaps it back or unmounts it, which dismisses it from the stack.
*/
enableDismissOnClose?: boolean;
@@ -76,15 +74,6 @@ type IsolatedBottomSheetModalProps = Omit<
* inside the sheet and it throws on device only.
*/
contextBridge: ContextBridge | null;
/**
* Runs when a close animation settles at the closed detent, whoever started it.
*
* Gorhom reports that through `onChange(-1)`, but skips `onChange` when its index bookkeeping
* already reads -1. An interrupted mount animation leaves it there, so the next close ends where
* it began and the owner never hears about it. Watch this signal, not `onChange`, when a close
* the owner may veto still has to reach the owner.
*/
onClosed?: () => void;
};
export type IsolatedBottomSheetModalRef = GorhomBottomSheetModalMethods;
@@ -116,7 +105,6 @@ export const IsolatedBottomSheetModal = forwardRef<
contextBridge,
backdropOpacity,
enableDismissOnClose = true,
onClosed,
waitFor,
simultaneousHandlers,
...bottomSheetProps
@@ -163,7 +151,6 @@ export const IsolatedBottomSheetModal = forwardRef<
simultaneousHandlers={contentDragHandlers.simultaneousHandlers}
>
<BottomSheetScope attachContentDrag={attachContentDrag}>
{onClosed ? <SheetCloseSignal onClosed={onClosed} /> : null}
{contextBridge ? contextBridge(children) : children}
</BottomSheetScope>
</GorhomBottomSheetModal>
@@ -172,43 +159,6 @@ export const IsolatedBottomSheetModal = forwardRef<
return modal;
});
/**
* Reports a close animation that settles at the closed detent — the signal Gorhom only routes
* through `onChange(-1)`, which it drops when the sheet's current index already reads -1.
*
* `animatedAnimationState.nextIndex` is -1 for the whole close animation and undefined once it
* completes. The settled position then tells a real close from a spring back and an interruption.
*/
function SheetCloseSignal({ onClosed }: { onClosed: () => void }) {
const { animatedAnimationState, animatedDetentsState, animatedPosition } =
useBottomSheetInternal();
const closing = useSharedValue(false);
useAnimatedReaction(
() => {
const { nextIndex } = animatedAnimationState.get();
if (nextIndex === -1) return -1;
return nextIndex === undefined ? 0 : 1;
},
(phase, previousPhase) => {
if (phase === -1) {
closing.value = true;
return;
}
if (phase === 1) {
closing.value = false;
return;
}
if (previousPhase !== -1 || !closing.value) return;
closing.value = false;
const closedPosition = animatedDetentsState.get().closedDetentPosition;
if (closedPosition === undefined) return;
if (Math.abs(animatedPosition.value - closedPosition) < 1) runOnJS(onClosed)();
},
[animatedAnimationState, animatedDetentsState, animatedPosition, onClosed],
);
return null;
}
export function useIsolatedBottomSheetVisibility({
visible,
isEnabled,
@@ -6,13 +6,9 @@ import { createProviderSnapshotCache, type ProviderSnapshotCache } from "./provi
const SNAPSHOT_KEY_PREFIX = "@paseo/provider-snapshot/v2:";
const SNAPSHOT_INDEX_KEY = "@paseo/provider-snapshot-index/v2";
const STORED_INDEX_KEY = "@paseo/provider-snapshot-index/v3";
function createStorage(maxSnapshotBytes = Number.POSITIVE_INFINITY) {
const values = new Map<string, string>();
const stats = { getAllKeysCalls: 0, snapshotsRead: [] as string[] };
function recordRead(key: string) {
if (key.startsWith(SNAPSHOT_KEY_PREFIX)) stats.snapshotsRead.push(key);
}
const stats = { getAllKeysCalls: 0 };
type Operation = "setItem" | "removeItem" | "multiRemove";
let failure: { operation: Operation; timing: "before" | "after"; key?: string } | null = null;
@@ -35,7 +31,6 @@ function createStorage(maxSnapshotBytes = Number.POSITIVE_INFINITY) {
failure = { operation, timing, key };
},
async getItem(key: string) {
recordRead(key);
return values.get(key) ?? null;
},
async setItem(key: string, value: string) {
@@ -66,7 +61,6 @@ function createStorage(maxSnapshotBytes = Number.POSITIVE_INFINITY) {
return [...values.keys()];
},
async multiGet(keys: readonly string[]) {
keys.forEach(recordRead);
return keys.map((key) => [key, values.get(key) ?? null] as const);
},
async multiRemove(keys: readonly string[]) {
@@ -391,62 +385,6 @@ describe("provider snapshot cache", () => {
expect(storage.stats.getAllKeysCalls).toBe(1);
});
it("reads only the requested snapshot after a restart and still enforces the budget", async () => {
const storage = createStorage();
const cache = createProviderSnapshotCache(storage);
for (const [day, label] of ["one", "two", "three"].entries()) {
await writeSnapshot(cache, {
cwd: `/${label}`,
label,
generatedAt: `2026-08-0${day + 1}T00:00:00.000Z`,
});
}
const maxBytes = snapshotBytes(storage.values);
storage.stats.snapshotsRead.length = 0;
const restarted = createProviderSnapshotCache(storage, { maxBytes });
await expect(restarted.read("server-1", "/two")).resolves.toMatchObject({ hash: "two" });
expect(storage.stats.snapshotsRead).toEqual([
`${SNAPSHOT_KEY_PREFIX}["server-1","cwd","/two"]`,
`${SNAPSHOT_KEY_PREFIX}["server-1","hash","two"]`,
]);
await writeSnapshot(restarted, {
cwd: "/four",
label: "four",
generatedAt: "2026-08-04T00:00:00.000Z",
});
await expect(restarted.read("server-1", "/one")).resolves.toBeNull();
await expect(restarted.read("server-1", "/four")).resolves.not.toBeNull();
expect(snapshotBytes(storage.values)).toBeLessThanOrEqual(maxBytes);
expectConsistentSnapshots(storage.values);
});
it("counts snapshots that another cache instance stored after a restart", async () => {
const storage = createStorage();
const first = createProviderSnapshotCache(storage);
const second = createProviderSnapshotCache(storage);
await second.read("server-1", "/none");
await writeSnapshot(first, {
cwd: "/first",
label: "first",
generatedAt: "2026-08-01T00:00:00.000Z",
});
await writeSnapshot(second, {
cwd: "/second",
label: "second",
generatedAt: "2026-08-02T00:00:00.000Z",
});
const maxBytes = snapshotBytes(storage.values) - 1;
const restarted = createProviderSnapshotCache(storage, { maxBytes });
await expect(restarted.read("server-1", "/second")).resolves.toMatchObject({ hash: "second" });
await expect(restarted.read("server-1", "/first")).resolves.toBeNull();
expect(snapshotBytes(storage.values)).toBeLessThanOrEqual(maxBytes);
expectConsistentSnapshots(storage.values);
});
it("replaces an indexed snapshot without counting both versions", async () => {
const storage = createStorage();
const maxBytes = 1_000;
@@ -621,13 +559,6 @@ describe("provider snapshot cache", () => {
entries: [{ key: `${SNAPSHOT_KEY_PREFIX}phantom`, bytes: 999_999, writtenAt: "bad" }],
}),
);
storage.values.set(
STORED_INDEX_KEY,
JSON.stringify({
version: 3,
entries: [{ key: `${SNAPSHOT_KEY_PREFIX}phantom`, bytes: 999_999, writtenAt: "bad" }],
}),
);
const restarted = createProviderSnapshotCache(storage, { maxBytes });
await writeSnapshot(restarted, {
@@ -15,8 +15,7 @@ type SnapshotPayload = GetProvidersSnapshotResponseMessage["payload"];
const CACHE_VERSION = 2;
const CACHE_KEY_PREFIX = "@paseo/provider-snapshot/v2";
const CACHE_INDEX_VERSION = 3;
const CACHE_INDEX_KEY = "@paseo/provider-snapshot-index/v3";
const CACHE_INDEX_KEY = "@paseo/provider-snapshot-index/v2";
const DEFAULT_MAX_CACHE_BYTES = 4 * 1024 * 1024;
interface ProviderSnapshotStorage {
@@ -44,22 +43,8 @@ interface ProviderSnapshotIndexEntry {
key: string;
bytes: number;
writtenAt: string;
// A directory association names the body it depends on.
body?: string;
}
const ProviderSnapshotIndexSchema = z.object({
version: z.literal(CACHE_INDEX_VERSION),
entries: z.array(
z.object({
key: z.string(),
bytes: z.number(),
writtenAt: z.string(),
body: z.string().optional(),
}),
),
});
const StoredProviderSnapshotSchema: z.ZodType<StoredProviderSnapshot> = z.strictObject({
version: z.literal(CACHE_VERSION),
hash: z.string(),
@@ -124,26 +109,14 @@ function decodeCacheKey(key: string) {
return CacheKeySchema.parse(JSON.parse(key.slice(CACHE_KEY_PREFIX.length + 1)));
}
// Timestamps and keys are machine strings: code-unit order is the intended order, and it spares
// a collator call per comparison.
function oldestFirst(left: ProviderSnapshotIndexEntry, right: ProviderSnapshotIndexEntry): number {
if (left.writtenAt !== right.writtenAt) return left.writtenAt < right.writtenAt ? -1 : 1;
const writtenAtOrder = left.writtenAt.localeCompare(right.writtenAt);
if (writtenAtOrder !== 0) return writtenAtOrder;
// References must be evicted before equally recent bodies, regardless of key encoding.
const leftIsReference = left.body !== undefined;
if (leftIsReference !== (right.body !== undefined)) return leftIsReference ? -1 : 1;
if (left.key === right.key) return 0;
return left.key < right.key ? -1 : 1;
}
function parseStoredIndex(value: string | null): ProviderSnapshotIndexEntry[] {
if (value === null) return [];
try {
const result = ProviderSnapshotIndexSchema.safeParse(JSON.parse(value));
return result.success ? result.data.entries : [];
} catch (error) {
if (!(error instanceof SyntaxError)) throw error;
return [];
}
const leftKind = decodeCacheKey(left.key)[1];
const rightKind = decodeCacheKey(right.key)[1];
if (leftKind !== rightKind) return leftKind === "cwd" ? -1 : 1;
return left.key.localeCompare(right.key);
}
function parseStoredProviderSnapshot(key: string, value: string): StoredProviderSnapshot | null {
@@ -162,23 +135,9 @@ export function createProviderSnapshotCache(
): ProviderSnapshotCache {
const maxBytes = options.maxBytes ?? DEFAULT_MAX_CACHE_BYTES;
let index: ProviderSnapshotIndexEntry[] | null = null;
// The index value last read from or written to storage.
let storedIndex: string | null = null;
let operationQueue = Promise.resolve();
const bodies = new Map<string, CachedProviderSnapshot>();
// The stored index spares a restart from reading every snapshot to learn its size and age.
// Storage keys stay the authority on what exists: an indexed key that is gone is dropped, and
// a stored key the index does not list is read and measured here.
async function commitIndex(entries: ProviderSnapshotIndexEntry[]): Promise<void> {
const serialized = JSON.stringify({ version: CACHE_INDEX_VERSION, entries });
if (serialized !== storedIndex) {
await storage.setItem(CACHE_INDEX_KEY, serialized);
storedIndex = serialized;
}
index = entries;
}
async function reconcileCache(): Promise<void> {
const allKeys = await storage.getAllKeys();
// COMPAT(providerSnapshotCache): added in v0.7.2, remove legacy cleanup after 2027-03-06.
@@ -186,17 +145,14 @@ export function createProviderSnapshotCache(
(key) =>
key.startsWith("@paseo/provider-snapshot/v1:") ||
key === "@paseo/provider-snapshot-index/v1" ||
key === "@paseo/provider-snapshot-index/v2",
key === CACHE_INDEX_KEY,
);
if (legacyKeys.length) await storage.multiRemove(legacyKeys);
const keys = allKeys.filter((key) => key.startsWith(`${CACHE_KEY_PREFIX}:`));
storedIndex = allKeys.includes(CACHE_INDEX_KEY) ? await storage.getItem(CACHE_INDEX_KEY) : null;
const storedKeys = new Set(keys);
const entries = parseStoredIndex(storedIndex).filter((entry) => storedKeys.has(entry.key));
const indexedKeys = new Set(entries.map((entry) => entry.key));
const unindexedKeys = keys.filter((key) => !indexedKeys.has(key));
const values = unindexedKeys.length > 0 ? await storage.multiGet(unindexedKeys) : [];
const values = await storage.multiGet(keys);
const keysToRemove: string[] = [];
const entries: ProviderSnapshotIndexEntry[] = [];
const references: Array<{ key: string; body: string; writtenAt: string }> = [];
for (const [key, value] of values) {
if (value === null) continue;
try {
@@ -206,12 +162,13 @@ export function createProviderSnapshotCache(
continue;
}
const [serverId, kind] = decodeCacheKey(key);
entries.push({
key,
bytes: storedBytes(key, value),
writtenAt: stored.generatedAt,
...(kind === "cwd" ? { body: bodyKey(serverId, stored.hash) } : {}),
});
entries.push({ key, bytes: storedBytes(key, value), writtenAt: stored.generatedAt });
if (kind === "cwd")
references.push({
key,
body: bodyKey(serverId, stored.hash),
writtenAt: stored.generatedAt,
});
} catch (error) {
if (
!(error instanceof SyntaxError) &&
@@ -224,8 +181,7 @@ export function createProviderSnapshotCache(
}
// Reconstruct the dependency ordering before applying a possibly smaller budget.
for (const reference of entries) {
if (reference.body === undefined) continue;
for (const reference of references) {
const body = entries.find((entry) => entry.key === reference.body);
if (!body) keysToRemove.push(reference.key);
else if (body.writtenAt < reference.writtenAt) body.writtenAt = reference.writtenAt;
@@ -244,7 +200,7 @@ export function createProviderSnapshotCache(
for (const removedKey of keysToRemove) bodies.delete(removedKey);
await storage.multiRemove(keysToRemove);
}
await commitIndex(retainedEntries);
index = retainedEntries;
}
async function ensureCacheIndex(): Promise<ProviderSnapshotIndexEntry[]> {
@@ -279,7 +235,7 @@ export function createProviderSnapshotCache(
value,
};
}
const incoming = { ...prepare(key, input), body: requiredBody?.key };
const incoming = prepare(key, input);
// The index is committed last: membership proves a body was stored. Reusing it
// needs only its byte count, not another parse, expansion, or storage write.
const body = requiredBody
@@ -309,27 +265,29 @@ export function createProviderSnapshotCache(
const keysToRemove = [...replacedKeys].filter(
(replaced) => !admitted.some((entry) => entry.key === replaced),
);
if (projectedBytes > maxBytes) {
for (const candidate of [...retainedEntries].sort(oldestFirst)) {
if (projectedBytes <= maxBytes) break;
projectedBytes -= candidate.bytes;
keysToRemove.push(candidate.key);
}
for (const candidate of [...retainedEntries].sort(oldestFirst)) {
if (projectedBytes <= maxBytes) break;
projectedBytes -= candidate.bytes;
keysToRemove.push(candidate.key);
}
const removedKeys = new Set(keysToRemove);
if (keysToRemove.length > 0) {
for (const removedKey of keysToRemove) bodies.delete(removedKey);
await storage.multiRemove(keysToRemove);
}
// Body, then reference, then index. A failed write can leave a reusable
// Body, then reference, then in-memory index. A failed write can leave a reusable
// orphan body; reconciliation never retains a reference without its body.
for (const entry of admitted) {
if (entry.value !== undefined) await storage.setItem(entry.key, entry.value);
}
await commitIndex([
index = [
...retainedEntries.filter((entry) => !removedKeys.has(entry.key)),
...admitted.map(({ value: _value, ...entry }) => entry),
]);
...admitted.map(({ key: recordKey, bytes, writtenAt }) => ({
key: recordKey,
bytes,
writtenAt,
})),
];
}
async function readRecord(key: string): Promise<StoredProviderSnapshot | null> {
@@ -344,7 +302,7 @@ export function createProviderSnapshotCache(
if (!(error instanceof SyntaxError) && !(error instanceof RangeError)) throw error;
bodies.delete(key);
await storage.removeItem(key);
await commitIndex(currentIndex.filter((entry) => entry.key !== key));
index = currentIndex.filter((entry) => entry.key !== key);
return null;
}
}
@@ -65,7 +65,7 @@ const nativeRequire = createRequire(require.resolve("react-native/package.json")
const { AbortController: NativeAbortController }: { AbortController: typeof AbortController } =
nativeRequire("abort-controller/dist/abort-controller");
function createStorage(onWrite: (key: string) => void = () => {}) {
function createStorage(onWrite: () => void = () => {}) {
const values = new Map<string, string>();
return {
async getItem(key: string) {
@@ -73,7 +73,7 @@ function createStorage(onWrite: (key: string) => void = () => {}) {
},
async setItem(key: string, value: string) {
values.set(key, value);
onWrite(key);
onWrite();
},
async removeItem(key: string) {
values.delete(key);
@@ -164,9 +164,7 @@ describe.each([
async ({ abortOnWrite, hasBody, hasReference }) => {
const controller = new Controller();
let writes = 0;
const storage = createStorage((key) => {
// The boundaries are the stored snapshots, not the cache's own index of them.
if (!key.startsWith("@paseo/provider-snapshot/")) return;
const storage = createStorage(() => {
writes += 1;
if (writes === abortOnWrite) controller.abort();
});
@@ -1,80 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
import { selectGitActionsWorkspace } from "./actions-workspace";
const SERVER_ID = "git-actions-server";
function createWorkspace(id: string, workspaceDirectory: string): WorkspaceDescriptor {
return {
id,
projectId: "project-1",
projectDisplayName: "Project 1",
projectRootPath: workspaceDirectory,
workspaceDirectory,
projectKind: "git",
workspaceKind: "worktree",
name: id,
status: "done",
archivingAt: null,
statusEnteredAt: null,
diffStat: null,
scripts: [],
createdAt: null,
lastUserMessageAt: null,
};
}
function seed(workspaces: WorkspaceDescriptor[]): void {
const store = useSessionStore.getState();
store.initializeSession(SERVER_ID, null);
store.mergeWorkspaces(SERVER_ID, workspaces);
}
afterEach(() => {
useSessionStore.getState().clearSession(SERVER_ID);
});
describe("selectGitActionsWorkspace", () => {
it("resolves the workspace the git actions belong to, not another one in the same directory", () => {
seed([createWorkspace("ws-a", "/repo"), createWorkspace("ws-b", "/repo")]);
const workspace = selectGitActionsWorkspace(useSessionStore.getState(), {
serverId: SERVER_ID,
workspaceId: "ws-b",
workspaceDirectory: "/repo",
});
expect(workspace?.id).toBe("ws-b");
});
// Each retained workspace subscribes through this selector. Returning the same descriptor when
// another workspace on the host changes keeps hidden workspaces from re-rendering their git
// actions on every workspace switch.
it("keeps the descriptor reference when another workspace on the host changes", () => {
seed([createWorkspace("ws-a", "/repo-a"), createWorkspace("ws-b", "/repo-b")]);
const input = { serverId: SERVER_ID, workspaceId: "ws-a", workspaceDirectory: "/repo-a" };
const before = selectGitActionsWorkspace(useSessionStore.getState(), input);
useSessionStore
.getState()
.mergeWorkspaces(SERVER_ID, [{ ...createWorkspace("ws-b", "/repo-b"), status: "running" }]);
expect(useSessionStore.getState().sessions[SERVER_ID]?.workspaces.get("ws-b")?.status).toBe(
"running",
);
expect(before?.id).toBe("ws-a");
expect(selectGitActionsWorkspace(useSessionStore.getState(), input)).toBe(before);
});
it("falls back to the workspace in the checkout directory when the caller names no workspace", () => {
seed([createWorkspace("ws-a", "/repo-a"), createWorkspace("ws-b", "/repo-b")]);
const workspace = selectGitActionsWorkspace(useSessionStore.getState(), {
serverId: SERVER_ID,
workspaceId: null,
workspaceDirectory: "/repo-b",
});
expect(workspace?.id).toBe("ws-b");
});
});
-38
View File
@@ -1,38 +0,0 @@
import type { SessionsSnapshot } from "@/stores/session-store-hooks/selectors";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
export interface GitActionsWorkspaceInput {
serverId: string;
/** The workspace that renders the git actions, or null when the caller has none. */
workspaceId: string | null | undefined;
/** The checkout directory, used to find the workspace when the caller names none. */
workspaceDirectory: string | null | undefined;
}
/**
* The workspace descriptor the git actions archive. Returns the stored descriptor itself, so a
* subscriber re-renders only when this workspace changes, not when another workspace on the host
* does.
*/
export function selectGitActionsWorkspace(
state: SessionsSnapshot,
input: GitActionsWorkspaceInput,
): WorkspaceDescriptor | null {
const workspaces = state.sessions[input.serverId]?.workspaces;
const workspaceKey = input.workspaceId
? resolveWorkspaceMapKeyByIdentity({ workspaces, workspaceId: input.workspaceId })
: null;
if (workspaceKey) {
return workspaces?.get(workspaceKey) ?? null;
}
if (!input.workspaceDirectory) {
return null;
}
for (const candidate of workspaces?.values() ?? []) {
if (candidate.workspaceDirectory === input.workspaceDirectory) {
return candidate;
}
}
return null;
}
-1
View File
@@ -1767,7 +1767,6 @@ export function ChangesSurface({
);
const { gitActions, branchLabel } = useGitActions({
serverId,
workspaceId,
cwd,
icons: GIT_ACTION_ICONS,
});
+46 -20
View File
@@ -28,11 +28,14 @@ import type { CheckoutPrMergeMethod } from "@getpaseo/protocol/messages";
import { openExternalUrl } from "@/utils/open-external-url";
import { useToast } from "@/contexts/toast-context";
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
import {
useActiveWorkspaceSelection,
type ActiveWorkspaceSelection,
} from "@/stores/navigation-active-workspace-store";
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
import { getFocusedWorkspaceSelection } from "@/navigation/workspace-route-navigation";
import { selectGitActionsWorkspace } from "@/git/actions-workspace";
import { type WorktreeArchiveWarningLabels } from "@/git/worktree-archive-warning";
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
import { readValidatedString } from "@/storage/validated-storage";
export type { GitActionId, GitAction, GitActions } from "@/git/policy";
@@ -197,8 +200,6 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
interface UseGitActionsInput {
serverId: string;
/** The workspace these actions belong to; a retained, hidden workspace passes its own. */
workspaceId: string | null | undefined;
cwd: string;
icons: {
commit: ReactElement;
@@ -221,13 +222,38 @@ interface UseGitActionsResult {
interface UseWorkspaceScreenArchiveControllerInput {
serverId: string;
workspaceId: string | null | undefined;
activeWorkspaceSelection: ActiveWorkspaceSelection | null;
workspaceDirectory: string | null | undefined;
branchLabel: string;
gitStatus: CheckoutStatusPayload | null;
t: (key: string, options?: Record<string, unknown>) => string;
}
function resolveArchiveWorkspaceDescriptor(input: {
workspaces: Map<string, WorkspaceDescriptor> | undefined;
activeWorkspaceSelection: ActiveWorkspaceSelection | null;
workspaceDirectory: string | null | undefined;
}): WorkspaceDescriptor | null {
const activeWorkspaceKey = input.activeWorkspaceSelection
? resolveWorkspaceMapKeyByIdentity({
workspaces: input.workspaces,
workspaceId: input.activeWorkspaceSelection.workspaceId,
})
: null;
if (activeWorkspaceKey) {
return input.workspaces?.get(activeWorkspaceKey) ?? null;
}
if (!input.workspaceDirectory) {
return null;
}
for (const candidate of input.workspaces?.values() ?? []) {
if (candidate.workspaceDirectory === input.workspaceDirectory) {
return candidate;
}
}
return null;
}
function resolveWorkspaceArchiveRisk(
workspace: WorkspaceDescriptor | null,
gitStatus: CheckoutStatusPayload | null,
@@ -258,16 +284,23 @@ function availableArchive(
function useWorkspaceScreenArchiveController({
serverId,
workspaceId,
activeWorkspaceSelection,
workspaceDirectory,
branchLabel,
gitStatus,
t,
}: UseWorkspaceScreenArchiveControllerInput) {
const workspaceDescriptor = useSessionStore((state) =>
selectGitActionsWorkspace(state, { serverId, workspaceId, workspaceDirectory }),
);
const sessionWorkspaces = useSessionStore((state) => state.sessions[serverId]?.workspaces);
const [isHidingWorkspace, setIsHidingWorkspace] = useState(false);
const workspaceDescriptor = useMemo(
() =>
resolveArchiveWorkspaceDescriptor({
workspaces: sessionWorkspaces,
activeWorkspaceSelection,
workspaceDirectory,
}),
[activeWorkspaceSelection, sessionWorkspaces, workspaceDirectory],
);
const archiveRisk = resolveWorkspaceArchiveRisk(workspaceDescriptor, gitStatus);
const controller = useWorkspaceArchive({
@@ -280,10 +313,7 @@ function useWorkspaceScreenArchiveController({
warningLabels: getWorktreeArchiveWarningLabels(t),
onSetHiding: setIsHidingWorkspace,
onArchiveStarted: (archived) => {
redirectIfArchivingActiveWorkspace({
...archived,
activeWorkspaceSelection: getFocusedWorkspaceSelection(),
});
redirectIfArchivingActiveWorkspace({ ...archived, activeWorkspaceSelection });
},
});
@@ -294,14 +324,10 @@ function useWorkspaceScreenArchiveController({
};
}
export function useGitActions({
serverId,
workspaceId,
cwd,
icons,
}: UseGitActionsInput): UseGitActionsResult {
export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): UseGitActionsResult {
const { t } = useTranslation();
const toast = useToast();
const activeWorkspaceSelection = useActiveWorkspaceSelection();
const [postShipArchiveSuggested, setPostShipArchiveSuggested] = useState(false);
const [shipDefault, setShipDefault] = useState<"merge" | "pr">("pr");
@@ -620,7 +646,7 @@ export function useGitActions({
const archiveController = useWorkspaceScreenArchiveController({
serverId,
workspaceId,
activeWorkspaceSelection,
workspaceDirectory: status?.cwd,
branchLabel,
gitStatus,
+1 -3
View File
@@ -4,14 +4,12 @@ import { useGitActions } from "@/git/use-actions";
interface WorkspaceActionsProps {
serverId: string;
workspaceId: string;
cwd: string;
}
export function WorkspaceActions({ serverId, workspaceId, cwd }: WorkspaceActionsProps) {
export function WorkspaceActions({ serverId, cwd }: WorkspaceActionsProps) {
const { gitActions } = useGitActions({
serverId,
workspaceId,
cwd,
icons: GIT_ACTION_ICONS,
});
@@ -5,9 +5,7 @@
import { polyfillCrypto } from "./crypto";
import { polyfillNavigator } from "./navigator";
import { polyfillScreenOrientation } from "./screen-orientation";
import { configureZodJit } from "./zod-jit";
configureZodJit();
polyfillCrypto();
polyfillNavigator();
// Polyfill screen.orientation for WebKitGTK desktop runtimes that lack the API.
@@ -1,9 +0,0 @@
import { z } from "zod";
// Zod compiles a parser for each object schema with `new Function` the first time it parses.
// Hermes has no JIT: it pays to compile that source at runtime and the result runs no faster than
// Zod's plain parser. A cold launch on Android spent about 145 ms less in Zod with this off.
// A schema reads the setting when it is constructed, so this runs before any schema module loads.
export function configureZodJit(): void {
z.config({ jitless: true });
}
@@ -1,26 +0,0 @@
import { readFileSync } from "node:fs";
import ts from "typescript";
import { expect, it } from "vitest";
import { z } from "zod";
import { configureZodJit } from "./zod-jit.native";
it("turns off Zod's compiled parsers on native before the app entry loads schema modules", () => {
const early = ts.createSourceFile(
"install-early.ts",
readFileSync(new URL("./install-early.ts", import.meta.url), "utf8"),
ts.ScriptTarget.Latest,
);
expect(
early.statements.some(
(statement) =>
ts.isExpressionStatement(statement) &&
ts.isCallExpression(statement.expression) &&
statement.expression.expression.getText(early) === "configureZodJit",
),
).toBe(true);
configureZodJit();
expect(z.config().jitless).toBe(true);
expect(z.object({ id: z.string() }).parse({ id: "a", extra: 1 })).toEqual({ id: "a" });
});
-2
View File
@@ -1,2 +0,0 @@
// Browsers and Electron keep Zod's compiled parsers: V8 optimises them. See zod-jit.native.ts.
export function configureZodJit(): void {}
@@ -4,7 +4,6 @@ import type {
WorkspaceStructureProject,
} from "@/projects/workspace-structure";
import { createProjectViewKey } from "@/projects/workspace-structure";
import { compareNames, compareText } from "@/utils/collation";
export type HostProjectListItem = WorkspaceStructureProject;
@@ -153,9 +152,14 @@ function compareHostProjectsForServer(
serverId: string,
): number {
return (
compareNames(left.projectName, right.projectName) ||
compareText(getHostProjectId(left, serverId) ?? "", getHostProjectId(right, serverId) ?? "") ||
compareText(left.viewKey, right.viewKey)
left.projectName.localeCompare(right.projectName, undefined, {
numeric: true,
sensitivity: "base",
}) ||
(getHostProjectId(left, serverId) ?? "").localeCompare(
getHostProjectId(right, serverId) ?? "",
) ||
left.viewKey.localeCompare(right.viewKey)
);
}
@@ -1,6 +1,5 @@
import type { ProjectDescriptor, WorkspaceDescriptor } from "@/stores/session-store";
import { projectDisplayNameFromProjectId } from "@/utils/project-display-name";
import { compareNames, compareText } from "@/utils/collation";
export interface WorkspaceStructureHostPlacement {
serverId: string;
@@ -115,8 +114,10 @@ export function buildWorkspaceStructureProjects(input: {
}))
.sort(
(left, right) =>
compareNames(left.projectName, right.projectName) ||
compareText(left.viewKey, right.viewKey),
left.projectName.localeCompare(right.projectName, undefined, {
numeric: true,
sensitivity: "base",
}) || left.viewKey.localeCompare(right.viewKey),
);
}
@@ -206,8 +207,10 @@ function getOrCreate<K, V>(map: Map<K, V>, key: K, create: () => V): V {
function compareWorkspaceStructureItems(left: WorkspaceSortItem, right: WorkspaceSortItem): number {
return (
compareNames(left.workspaceName, right.workspaceName) ||
compareText(left.workspaceKey, right.workspaceKey)
left.workspaceName.localeCompare(right.workspaceName, undefined, {
numeric: true,
sensitivity: "base",
}) || left.workspaceKey.localeCompare(right.workspaceKey)
);
}
@@ -233,18 +233,6 @@ function timeline(text = "Cached") {
};
}
async function cacheMultiByteTimelineAfterOtherHost(
storage: MemoryStorage,
maxBytes?: number,
): Promise<void> {
const cache = new ReplicaCache(storage, { ...noLegacyCleanup, maxBytes });
cache.setHosts([SERVER_ID, "other-host"]);
cache.commitTimeline("other-host", "agent-1", timeline("other host"));
await cache.flush();
cache.commitTimeline(SERVER_ID, "agent-1", timeline(`plain café 日本語 ${"🙂".repeat(50)}`));
await cache.flush();
}
it("keeps the unsettled turn with the cached messages", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
@@ -989,26 +977,6 @@ describe("ReplicaCache", () => {
expect(storage.rows.has(`${SERVER_ID}:project:project-1`)).toBe(true);
});
it.each([
{ slack: 0, retained: [SERVER_ID, "other-host"] },
{ slack: -1, retained: [SERVER_ID] },
])(
"evicts on the exact stored size of text of every UTF-8 width (budget slack $slack)",
async ({ slack, retained }) => {
const unbounded = new MemoryStorage();
await cacheMultiByteTimelineAfterOtherHost(unbounded);
let storedBytes = 0;
for (const row of unbounded.rows.values()) storedBytes += Buffer.byteLength(row.payload);
const storage = new MemoryStorage();
await cacheMultiByteTimelineAfterOtherHost(storage, storedBytes + slack);
const cachedHosts = new Set<string>();
for (const row of storage.rows.values()) cachedHosts.add(row.serverId);
expect([...cachedHosts].sort()).toEqual(retained);
},
);
it("removes a targeted corrupt row from eviction bookkeeping", async () => {
const otherServerId = "other-host";
const storage = new MemoryStorage();
@@ -1424,52 +1392,6 @@ it("retains semantic agent messages across disk-cache reconstruction", async ()
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toEqual(value);
});
it("heals cached user_message rows whose stored id collided on a shared provider messageId", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const sharedProviderMessageId = "9ffc3d6e-f0ff-4005-8675-e76e9c5eb5a8";
const value = timeline();
value.items = [
{
kind: "user_message",
id: sharedProviderMessageId,
messageId: sharedProviderMessageId,
clientMessageId: "client-queued-1",
text: "first queued prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
{
kind: "user_message",
id: sharedProviderMessageId,
messageId: sharedProviderMessageId,
clientMessageId: "client-direct-2",
text: "second direct prompt",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
];
writer.commitTimeline(SERVER_ID, "agent-1", value);
await writer.flush();
const restored = await createCache(storage).readTimeline(SERVER_ID, "agent-1");
expect(restored?.items.map((item) => item.id)).toEqual(["client-queued-1", "client-direct-2"]);
expect(restored?.items).toMatchObject([
{
kind: "user_message",
id: "client-queued-1",
clientMessageId: "client-queued-1",
messageId: sharedProviderMessageId,
},
{
kind: "user_message",
id: "client-direct-2",
clientMessageId: "client-direct-2",
messageId: sharedProviderMessageId,
},
]);
});
it("retains workspace metadata across replica-cache reload and invalidates pre-metadata rows", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
@@ -564,14 +564,6 @@ function deserializeTimelineItem(item: StoredTimelineItem): StreamItem {
return deserializeBuiltinTimelineItem(item);
}
// COMPAT(userMessageRowId): added in v0.18.2, remove after 2027-06-01.
// Earlier builds stored batched user rows under the shared provider messageId instead of clientMessageId.
function storedUserMessageRowId(
item: Extract<StoredTimelineItem, { kind: "user_message" }>,
): string {
return item.clientMessageId && item.id === item.messageId ? item.clientMessageId : item.id;
}
function deserializeBuiltinTimelineItem(
item: Exclude<StoredTimelineItem, { kind: "plugin" }>,
): StreamItem {
@@ -585,7 +577,6 @@ function deserializeBuiltinTimelineItem(
case "user_message":
return {
...base,
id: storedUserMessageRowId(item),
kind: item.kind,
...(item.clientMessageId ? { clientMessageId: item.clientMessageId } : {}),
...(item.messageId ? { messageId: item.messageId } : {}),
@@ -1,29 +1,15 @@
const NON_ASCII_RUNS = /[\u0080-\uffff]+/g;
// The size the row stores report for a payload. Counting avoids the JS Buffer polyfill, which
// materialises the whole byte array just to measure it.
export function replicaPayloadBytes(payload: string): number {
// Payloads are JSON that is almost entirely ASCII, one byte per character. The regex engine
// finds the rest far faster than a character loop walks a megabyte of directory rows on Hermes.
let bytes = payload.length;
for (const run of payload.match(NON_ASCII_RUNS) ?? []) {
for (let index = 0; index < run.length; index += 1) {
const code = run.charCodeAt(index);
if (code < 0x800) bytes += 1;
else if (isHighSurrogate(code) && isLowSurrogate(run.charCodeAt(index + 1))) {
// Two code units become four bytes.
bytes += 2;
index += 1;
} else bytes += 2;
}
let bytes = 0;
for (let index = 0; index < payload.length; index += 1) {
const code = payload.charCodeAt(index);
if (code < 0x80) bytes += 1;
else if (code < 0x800) bytes += 2;
else if (code >= 0xd800 && code <= 0xdbff) {
bytes += 4;
index += 1;
} else bytes += 3;
}
return bytes;
}
function isHighSurrogate(code: number): boolean {
return code >= 0xd800 && code <= 0xdbff;
}
function isLowSurrogate(code: number): boolean {
return code >= 0xdc00 && code <= 0xdfff;
}
@@ -95,36 +95,20 @@ function SheetTabSheet({ sheet, isTop, onClose }: SheetTabSheetProps) {
};
}, []);
// Every close path (drag, backdrop, Close, Back) slides the sheet down first; the owner then runs
// the one guarded close. The sheet keeps its content through the close, so a declined
// Every close path (drag, backdrop, Close, Back) slides the sheet down first; `onChange(-1)` then
// runs the one guarded close. The sheet keeps its content through the close, so a declined
// unsaved-changes prompt only has to bring it back up.
//
// Both signals feed that one attempt. `onChange(-1)` covers the ordinary case; `onClosed` covers
// a close whose end index Gorhom's bookkeeping already held, which it therefore never reports as
// a change (an interrupted mount animation leaves it at -1).
const closeRequested = useRef(false);
const requestClose = useCallback(() => {
if (unmounted.current || closeRequested.current) return;
closeRequested.current = true;
void onClose(tab.tabId).then((stillOpen) => {
if (stillOpen) {
closeRequested.current = false;
sheetRef.current?.snapToIndex(0);
}
return stillOpen;
});
}, [onClose, tab.tabId]);
const close = useCallback(() => sheetRef.current?.close(), []);
const handleChange = useCallback(
(index: number) => {
if (index !== -1) {
closeRequested.current = false;
return;
}
requestClose();
if (index !== -1 || unmounted.current) return;
void onClose(tab.tabId).then((stillOpen) => {
if (stillOpen) sheetRef.current?.snapToIndex(0);
return stillOpen;
});
},
[requestClose],
[onClose, tab.tabId],
);
const close = useCallback(() => sheetRef.current?.close(), []);
// Hidden workspaces stay mounted in the deck and under Settings; only the visible one owns Back.
const ownsBackPress = isTop && isWorkspaceFocused && isScreenFocused;
useEffect(() => {
@@ -149,7 +133,6 @@ function SheetTabSheet({ sheet, isTop, onClose }: SheetTabSheetProps) {
handleComponent={SheetHandle}
backdropOpacity={0.45}
onChange={handleChange}
onClosed={requestClose}
accessible={false}
>
<SheetPane sheet={sheet} onClose={close} isTop={isTop} />
@@ -3298,11 +3298,7 @@ function WorkspaceScreenContent({
) : null}
{workspaceDirectory ? (
<>
<WorkspaceActions
serverId={normalizedServerId}
workspaceId={normalizedWorkspaceId}
cwd={workspaceDirectory}
/>
<WorkspaceActions serverId={normalizedServerId} cwd={workspaceDirectory} />
{workspaceActionsInBar ? null : explorerControls.headerAction}
</>
) : null}
@@ -432,75 +432,6 @@ describe("createArchiveFinishedSubagents", () => {
});
});
describe("closed managed subagents", () => {
it("counts a closed child as finished", () => {
const archive = createArchiveFinishedSubagents([paseo("closed-child", "closed")], {
parentAgentId: "parent",
getManagedSubagent: () => undefined,
archiveManagedSubagent: async () => undefined,
dismissProviderSubagents: () => undefined,
});
expect(archive.getState().eligibleCount).toBe(1);
});
it("archives a closed child instead of skipping it", async () => {
const current = new Map([
["closed-child", managed("closed-child", "closed")],
["idle-child", managed("idle-child")],
]);
const archived: string[] = [];
const archive = createArchiveFinishedSubagents(
[paseo("closed-child", "closed"), paseo("idle-child")],
{
parentAgentId: "parent",
getManagedSubagent: ({ agentId }) => current.get(agentId),
archiveManagedSubagent: async ({ agentId }) => {
archived.push(agentId);
},
dismissProviderSubagents: () => undefined,
},
);
await expect(archive.archiveFinished()).resolves.toEqual({
archivedPaseoIds: ["closed-child", "idle-child"],
dismissedProviderIds: [],
skippedPaseoIds: [],
failures: [],
});
expect(archived).toEqual(["closed-child", "idle-child"]);
});
it("still skips a closed child that was resumed and is running by archive time", async () => {
const current = new Map([["closed-child", managed("closed-child", "running")]]);
const archive = createArchiveFinishedSubagents([paseo("closed-child", "closed")], {
parentAgentId: "parent",
getManagedSubagent: ({ agentId }) => current.get(agentId),
archiveManagedSubagent: async () => undefined,
dismissProviderSubagents: () => undefined,
});
await expect(archive.archiveFinished()).resolves.toEqual({
archivedPaseoIds: [],
dismissedProviderIds: [],
skippedPaseoIds: ["closed-child"],
failures: [],
});
});
it("still skips a closed child that has live background work", async () => {
const active = { ...paseo("closed-child", "closed"), backgroundWork: { count: 1 } };
const archive = createArchiveFinishedSubagents([active], {
parentAgentId: "parent",
getManagedSubagent: () => undefined,
archiveManagedSubagent: async () => undefined,
dismissProviderSubagents: () => undefined,
});
expect(archive.getState().eligibleCount).toBe(0);
});
});
it("excludes live background work and rechecks it before each archive", async () => {
const first = deferred<void>();
const active = { ...paseo("active"), backgroundWork: { count: 1 } };
@@ -38,15 +38,11 @@ export interface ArchiveFinishedSubagents {
archiveFinished(): Promise<ArchiveFinishedOutcome>;
}
// A closed agent has no live runtime (finished, or released by idle cleanup), so it is
// finished for archiving purposes just like idle and error.
function isArchivableManagedStatus(status: ManagedSubagentSnapshot["status"]): boolean {
return status === "idle" || status === "error" || status === "closed";
}
export function isFinishedSubagent(row: SubagentRow): boolean {
if (row.kind === "paseo")
return isArchivableManagedStatus(row.status) && (row.backgroundWork?.count ?? 0) === 0;
return (
(row.status === "idle" || row.status === "error") && (row.backgroundWork?.count ?? 0) === 0
);
return row.status === "completed" || row.status === "failed" || row.status === "canceled";
}
@@ -59,7 +55,7 @@ function canArchiveManagedSubagent(
!agent.archivedAt &&
agent.parentAgentId === parentAgentId &&
(agent.backgroundWork?.count ?? 0) === 0 &&
isArchivableManagedStatus(agent.status),
(agent.status === "idle" || agent.status === "error"),
);
}
@@ -2495,63 +2495,7 @@ describe("processTimelineResponse", () => {
.map((item) => ({ id: item.id, messageId: item.messageId })),
).toEqual([
{ id: "local-prompt", messageId: undefined },
{ id: "remote-client-prompt", messageId: "remote-prompt" },
]);
});
it("assigns unique row ids when batched user messages share a provider messageId", () => {
const sharedProviderMessageId = "9ffc3d6e-f0ff-4005-8675-e76e9c5eb5a8";
const result = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
initRequestDirection: "tail",
payload: {
...baseTimelineInput.payload,
direction: "tail",
epoch: "epoch-1",
startCursor: { seq: 1 },
endCursor: { seq: 2 },
entries: [
{
...makeTimelineEntry(1, "first queued prompt", "user_message"),
item: {
type: "user_message",
text: "first queued prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-queued-1",
},
},
{
...makeTimelineEntry(2, "second direct prompt", "user_message"),
item: {
type: "user_message",
text: "second direct prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-direct-2",
},
},
],
},
});
expect(
result.tail.map((item) =>
item.kind === "user_message"
? { id: item.id, clientMessageId: item.clientMessageId, messageId: item.messageId }
: null,
),
).toEqual([
{
id: "client-queued-1",
clientMessageId: "client-queued-1",
messageId: sharedProviderMessageId,
},
{
id: "client-direct-2",
clientMessageId: "client-direct-2",
messageId: sharedProviderMessageId,
},
{ id: "remote-prompt", messageId: "remote-prompt" },
]);
});
-98
View File
@@ -329,104 +329,6 @@ describe("user message identity", () => {
},
]);
});
it("assigns distinct row ids to batched user messages that share a provider messageId", () => {
const sharedProviderMessageId = "9ffc3d6e-f0ff-4005-8675-e76e9c5eb5a8";
const firstTimestamp = new Date("2026-11-29T13:00:00.000Z");
const secondTimestamp = new Date("2026-11-29T13:00:01.000Z");
const hydrated = hydrateStreamState(
[
{
event: {
type: "timeline",
provider: "claude",
item: {
type: "user_message",
text: "first queued prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-queued-1",
},
},
timestamp: firstTimestamp,
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
{
event: {
type: "timeline",
provider: "claude",
item: {
type: "user_message",
text: "second direct prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-direct-2",
},
},
timestamp: secondTimestamp,
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
{ source: "canonical" },
);
expect(hydrated).toHaveLength(2);
expect(hydrated.map((item) => item.id)).toEqual(["client-queued-1", "client-direct-2"]);
expect(hydrated).toMatchObject([
{
kind: "user_message",
id: "client-queued-1",
clientMessageId: "client-queued-1",
messageId: sharedProviderMessageId,
text: "first queued prompt",
},
{
kind: "user_message",
id: "client-direct-2",
clientMessageId: "client-direct-2",
messageId: sharedProviderMessageId,
text: "second direct prompt",
},
]);
const afterFirstLive = applyStreamEvent({
tail: [],
head: [],
event: {
type: "timeline",
provider: "claude",
item: {
type: "user_message",
text: "first queued prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-queued-1",
},
},
timestamp: firstTimestamp,
timelineCursor: { epoch: "epoch-1", seq: 1 },
});
const afterSecondLive = applyStreamEvent({
tail: afterFirstLive.tail,
head: afterFirstLive.head,
event: {
type: "timeline",
provider: "claude",
item: {
type: "user_message",
text: "second direct prompt",
messageId: sharedProviderMessageId,
clientMessageId: "client-direct-2",
},
},
timestamp: secondTimestamp,
timelineCursor: { epoch: "epoch-1", seq: 2 },
});
expect(afterSecondLive.tail).toHaveLength(2);
expect(afterSecondLive.tail.map((item) => item.id)).toEqual([
"client-queued-1",
"client-direct-2",
]);
});
});
function assistantTimeline(
+2 -4
View File
@@ -969,7 +969,7 @@ function appendUserMessage(
const chunkSeed = chunk.trim() || chunk || images?.[0]?.id || "image";
const nextItem = createUserMessage({
id: clientMessageId || messageId || createUniqueTimelineId(state, "user", chunkSeed, timestamp),
id: messageId ?? createUniqueTimelineId(state, "user", chunkSeed, timestamp),
clientMessageId,
messageId,
timelineCursor,
@@ -1967,9 +1967,7 @@ function buildCanonicalUserMessage(params: {
const fallbackKey = normalized.chunk.trim() || images?.[0]?.id || "image";
const canonical = createUserMessage({
id:
item.clientMessageId ||
item.messageId ||
createUniqueTimelineId([...tail, ...head], "user", fallbackKey, timestamp),
item.messageId ?? createUniqueTimelineId([...tail, ...head], "user", fallbackKey, timestamp),
messageId: item.messageId,
clientMessageId: item.clientMessageId,
turnId,
-14
View File
@@ -1,14 +0,0 @@
// `String.prototype.localeCompare` builds a collator on every call. On Hermes that construction
// dominates a sort over a few hundred names, so comparisons that run in bulk share one collator.
const textCollator = new Intl.Collator();
const nameCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
/** The order of `left.localeCompare(right)`. */
export function compareText(left: string, right: string): number {
return textCollator.compare(left, right);
}
/** Display-name order: ignores case and accents, and sorts embedded numbers by value. */
export function compareNames(left: string, right: string): number {
return nameCollator.compare(left, right);
}
@@ -30,7 +30,6 @@ describe("Hub commands", () => {
"projects",
"export",
"deploy",
"run",
"logout",
]);
assert.match(connect?.helpInformation() ?? "", /--api-key <secret>/u);
-15
View File
@@ -1,25 +1,10 @@
/** What Hub itself answered, when a request reached it and failed. */
export interface HubProblem {
status: number;
code?: string;
}
export class HubCommandError extends Error {
// Private so `--json` error output, which spreads the error, does not gain a field.
readonly #hubProblem: HubProblem | undefined;
constructor(
readonly code: string,
message: string,
readonly details?: string,
hubProblem?: HubProblem,
) {
super(message);
this.name = "HubCommandError";
this.#hubProblem = hubProblem;
}
get hubProblem(): HubProblem | undefined {
return this.#hubProblem;
}
}
@@ -6,7 +6,6 @@ import {
configurationResourcesSchema,
enrollmentTokenSchema,
installResponseSchema,
manualRunResponseSchema,
projectsResponseSchema,
triggersResponseSchema,
triggerInstallationResponseSchema,
@@ -16,7 +15,6 @@ import {
type CliAuthorizationPoll,
type HubInstallResult,
type HubConfigurationResources,
type HubManualRun,
type HubProject,
type HubTrigger,
type HubTriggerInstallationResult,
@@ -30,7 +28,6 @@ export type {
CliAuthorizationPoll,
HubInstallResult,
HubConfigurationResources,
HubManualRun,
HubProject,
HubTrigger,
HubTriggerInstallationResult,
@@ -45,15 +42,6 @@ interface HubConfigurationInput {
files: readonly HubBundleFile[];
}
export interface HubManualRunRequest {
projectSlug: string;
trigger: string;
actor: string;
deliveryKey: string;
/** Hub reads inputs only from a string: leading `name=value` tokens, then the prompt. */
input: string;
}
export class HubHttpClient {
startCliAuthorization(origin: string): Promise<CliAuthorization> {
return requestHub({
@@ -112,28 +100,11 @@ export class HubHttpClient {
apiKey,
successStatus: 200,
schema: triggersResponseSchema,
failureMessage: "Hub trigger listing failed",
failureMessage: "Hub trigger export failed",
});
return response.triggers;
}
dispatchManualRun(
origin: string,
apiKey: string,
request: HubManualRunRequest,
): Promise<HubManualRun> {
return requestHub({
origin,
path: "/api/v1/manual-runs",
method: "POST",
apiKey,
body: request,
successStatus: 200,
schema: manualRunResponseSchema,
failureMessage: "Hub manual run failed",
});
}
validateTrigger(
origin: string,
apiKey: string,
@@ -62,16 +62,6 @@ export const triggerInstallationResponseSchema = z
})
.strict();
// Not strict: by the time this arrives the run exists. Rejecting a field a newer Hub adds
// would report a failure and invite a second run.
export const manualRunResponseSchema = z.object({
deliveryKey: z.string(),
providerEventReceiptId: z.string().min(1),
triggerRunId: z.string().min(1),
configuredTriggerName: z.string(),
workflowStatus: z.string().min(1),
});
export const configurationResourcesSchema = z
.object({
daemons: z.array(z.object({ id: z.string().uuid(), slug: z.string().min(1) }).strict()),
@@ -117,6 +107,5 @@ export type HubTrigger = z.infer<typeof triggerSchema>;
export type HubTriggerValidationResult = z.infer<typeof triggerValidationResponseSchema>;
export type HubTriggerInstallationResult = z.infer<typeof triggerInstallationResponseSchema>;
export type HubConfigurationResources = z.infer<typeof configurationResourcesSchema>;
export type HubManualRun = z.infer<typeof manualRunResponseSchema>;
export type HubInstallResult = z.infer<typeof installResponseSchema>;
export type HubValidationResult = z.infer<typeof validationResponseSchema>;
@@ -11,7 +11,6 @@ const problemSchema = z.object({
type: z.string().optional(),
title: z.string().optional(),
status: z.number().int().optional(),
code: z.string().optional(),
detail: z.string().optional(),
instance: z.string().optional(),
errors: z
@@ -30,8 +29,6 @@ export async function hubRequestFailure(
return new HubCommandError(
"HUB_REQUEST_FAILED",
`${failureMessage} with HTTP ${response.status}.`,
undefined,
{ status: response.status },
);
}
let body: unknown;
@@ -41,8 +38,6 @@ export async function hubRequestFailure(
return new HubCommandError(
"HUB_INVALID_RESPONSE",
`Hub returned malformed problem details for HTTP ${response.status}.`,
undefined,
{ status: response.status },
);
}
const parsed = problemSchema.safeParse(body);
@@ -53,8 +48,6 @@ export async function hubRequestFailure(
return new HubCommandError(
"HUB_INVALID_RESPONSE",
`Hub returned nonconforming problem details for HTTP ${response.status}.`,
undefined,
{ status: response.status },
);
}
const title = parsed.data.title ?? `${failureMessage} with HTTP ${response.status}`;
@@ -70,7 +63,6 @@ export async function hubRequestFailure(
code,
redactSecret(message, apiKey),
details === undefined ? undefined : redactSecret(details, apiKey),
{ status: response.status, code: parsed.data.code },
);
}
-10
View File
@@ -21,7 +21,6 @@ import { hubStatusResult } from "./status-output.js";
import { addHubResolutionHelp } from "./help.js";
import { addHubInitCommand, continueHubGuidedSetup } from "./init.js";
import { addHubPermissionsCommand } from "./permissions.js";
import { addHubRunCommand, terminalRunPrompts } from "./run/index.js";
interface HubCommandEnvironment {
env: Readonly<Record<string, string | undefined>>;
@@ -110,15 +109,6 @@ export function createHubCommand(overrides: Partial<HubCommandEnvironment> = {})
reporter: environment.reporter,
cwd: environment.cwd,
});
addHubRunCommand(hub, {
env: environment.env,
credentials: environment.credentials,
hub: environment.hub,
reporter: environment.reporter,
cwd: environment.cwd,
isInteractive: environment.isInteractive,
prompts: terminalRunPrompts,
});
addHubLogoutCommand(hub, {
credentials: environment.credentials,
daemon: environment.daemon,
@@ -1,750 +0,0 @@
import { strict as assert } from "node:assert";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, it } from "vitest";
import { render } from "../../../output/render.js";
import type { HubCredentialStore, StoredHubCredential } from "../credentials.js";
import { HubCommandError } from "../error.js";
import { HubHttpClient } from "../hub-client/index.js";
import { runHubRun, type HubRunOptions, type HubRunPrompts } from "./index.js";
const servers: Array<ReturnType<typeof createServer>> = [];
const directories: string[] = [];
afterEach(async () => {
await Promise.all(
servers.splice(0).map(
(server) =>
new Promise<void>((resolve) => {
server.closeAllConnections();
server.close(() => resolve());
}),
),
);
await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true })));
});
const deployTrigger = trigger(
"deploy",
`name: deploy
on:
manual.run: {}
inputs:
environment:
type: string
required: true
choices: [staging, production]
replicas:
type: number
default: 1
dry_run:
type: boolean
run:
prompt: Deploy.
`,
);
describe("Hub manual run", () => {
it("starts a trigger by name with the stored login and nothing else to type", async () => {
const hub = await startHub();
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const result = await cli.run("deploy", undefined);
assert.equal(hub.requests.length, 1);
const [request] = hub.requests;
assert.equal(request?.route, "POST /api/v1/manual-runs");
assert.equal(request?.authorization, "Bearer stored-secret");
const { deliveryKey, ...body } = (request?.body ?? {}) as Record<string, unknown>;
assert.match(String(deliveryKey), /^[0-9a-f-]{36}$/u);
assert.deepEqual(body, {
projectSlug: "default",
trigger: "deploy",
actor: "paseo-cli",
input: "",
});
assert.deepEqual(result.data, { ...dispatched(String(deliveryKey)), origin: hub.origin });
assert.deepEqual(cli.progress, [`Running deploy on ${hub.origin}`]);
});
it("renders a calm table, the run ID alone, and Hub's fields as JSON and YAML", async () => {
const hub = await startHub();
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const result = await cli.run("deploy", undefined, { deliveryKey: "build-42" });
const table = render(result, { format: "table", noColor: true });
assert.match(table, /^TRIGGER\s+RUN ID\s+STATUS\s+HUB/u);
assert.match(table, new RegExp(`deploy\\s+${runId}\\s+running\\s+${hub.origin}`, "u"));
assert.equal(render(result, { quiet: true }), runId);
assert.deepEqual(JSON.parse(render(result, { format: "json" })), {
...dispatched("build-42"),
origin: hub.origin,
});
assert.match(render(result, { format: "yaml" }), new RegExp(`triggerRunId: ${runId}`, "u"));
});
it("sends inputs as Hub's leading name=value tokens, followed by the prompt", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await cli.run("deploy", "ship the hotfix", {
input: ["environment=staging", "replicas=3"],
actor: "alice",
deliveryKey: "build-42",
});
assert.deepEqual(hub.dispatches(), [
{
projectSlug: "default",
trigger: "deploy",
actor: "alice",
deliveryKey: "build-42",
input: "environment=staging replicas=3 ship the hotfix",
},
]);
});
it("reads the prompt from a file and takes explicit Hub authority and project", async () => {
const hub = await startHub();
const cli = harness({
env: { PASEO_HUB_URL: hub.origin, PASEO_HUB_API_KEY: "env-secret" },
login: { origin: "https://other.test", credential: "stored-secret" },
});
const directory = await mkdtemp(path.join(tmpdir(), "paseo-hub-run-"));
directories.push(directory);
await writeFile(path.join(directory, "prompt.md"), "# Fix\n\nthe sync\n");
cli.cwd = directory;
await cli.run("deploy", undefined, {
promptFile: "prompt.md",
project: "payments",
apiKey: "flag-secret",
});
assert.equal(hub.requests[0]?.authorization, "Bearer flag-secret");
assert.deepEqual(
hub.dispatches().map(({ projectSlug, input }) => ({ projectSlug, input })),
[{ projectSlug: "payments", input: "# Fix\n\nthe sync" }],
);
});
it("refuses two prompt sources and an unreadable prompt file before contacting Hub", async () => {
const hub = await startHub();
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await rejectsWith(
cli.run("deploy", "text", { promptFile: "prompt.md" }),
"HUB_RUN_PROMPT_CONFLICT",
/prompt argument or --prompt-file/u,
);
await rejectsWith(
cli.run("deploy", undefined, { promptFile: "/nonexistent/prompt.md" }),
"HUB_RUN_PROMPT_UNREADABLE",
/\/nonexistent\/prompt\.md/u,
);
assert.deepEqual(hub.requests, []);
});
it.each([
["environment", /name=value/u],
["Environment=staging", /lowercase/u],
["environment=eu west", /cannot contain spaces/u],
])("refuses --input %j before contacting Hub", async (input, message) => {
const hub = await startHub();
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await rejectsWith(cli.run("deploy", undefined, { input: [input] }), "HUB_RUN_INPUT", message);
assert.deepEqual(hub.requests, []);
});
it("refuses an undeclared input, which Hub would silently read as prompt text", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const error = await rejectsWith(
cli.run("deploy", undefined, { input: ["enviroment=production"] }),
"HUB_RUN_INPUT",
/Trigger "deploy" has no input "enviroment"/u,
);
assert.equal(
error.details,
[
'Inputs of "deploy":',
" -i environment=<staging|production> required",
" -i replicas=<number> default 1",
" -i dry_run=<true|false>",
].join("\n"),
);
assert.deepEqual(hub.dispatches(), []);
});
it("reads declared inputs from a preserved legacy multistep trigger", async () => {
const legacy = {
...trigger(
"release",
`name: release
legacy_multistep:
trigger:
name: release
on: manual.run
inputs:
channel:
type: string
required: false
`,
),
format: "legacy_multistep" as const,
};
const hub = await startHub({ triggers: [legacy] });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await rejectsWith(
cli.run("release", undefined, { input: ["chanel=beta"] }),
"HUB_RUN_INPUT",
/no input "chanel"/u,
);
await cli.run("release", undefined, { input: ["channel=beta"] });
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["channel=beta"],
);
});
it("still runs with a dispatch-only API key and says the input names were not checked", async () => {
const hub = await startHub({
list: problem(403, "insufficient_scope", "Insufficient scope"),
});
const cli = harness({ env: { PASEO_HUB_URL: hub.origin, PASEO_HUB_API_KEY: "ci-secret" } });
await cli.run("deploy", undefined, { input: ["environment=staging"], json: true });
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["environment=staging"],
);
assert.deepEqual(cli.progress, [
"Input names were not checked: this credential cannot list triggers (configuration:validate).",
]);
});
it("does not run when the input names could not be checked because Hub failed", async () => {
const hub = await startHub({
list: problem(503, "infrastructure_unavailable", "Service unavailable"),
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await assert.rejects(cli.run("deploy", undefined, { input: ["environment=staging"] }));
assert.deepEqual(hub.dispatches(), []);
});
it.each([
["nope", 'No manual trigger "nope" on', "Manual triggers: deploy"],
["paused", 'Trigger "paused" is disabled on', "Enable it in Hub, then run it again."],
[
"on-push",
'Trigger "on-push" has no manual.run event',
"Add `manual.run: {}` under `on` and deploy it.",
],
])("explains why %s cannot run", async (name, message, details) => {
const hub = await startHub({
triggers: [
deployTrigger,
{ ...trigger("paused", "name: paused\non:\n manual.run: {}\n"), enabled: false },
trigger("on-push", "name: on-push\non:\n github.push: {}\n"),
],
run: problem(404, "trigger_not_found", "Trigger not found"),
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const error = await rejectsWith(
cli.run(name, undefined),
"HUB_TRIGGER_NOT_FOUND",
new RegExp(message, "u"),
);
assert.equal(error.details, details);
});
it("treats Hub's missing default project as an unknown trigger", async () => {
const hub = await startHub({
triggers: [deployTrigger],
run: problem(404, "project_not_found", "Project not found"),
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await rejectsWith(
cli.run("nope", undefined),
"HUB_TRIGGER_NOT_FOUND",
/No manual trigger "nope"/u,
);
await rejectsWith(
cli.run("nope", undefined, { project: "payments" }),
"HUB_NOT_FOUND",
/Project not found/u,
);
});
it("prints Hub's input validation verbatim, with the declared inputs", async () => {
const hub = await startHub({
triggers: [deployTrigger],
run: problem(400, "invalid_input", "Invalid trigger input", [
{ path: ["input"], message: "required input environment is missing" },
]),
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const error = await rejectsWith(
cli.run("deploy", undefined),
"HUB_INVALID_INPUT",
/^Invalid trigger input: required input environment is missing$/u,
);
assert.match(error.details ?? "", /^Inputs of "deploy":\n {2}-i environment=/u);
});
it.each([
[
problem(403, "actor_forbidden", "Actor forbidden"),
"HUB_REQUEST_FAILED",
/--actor <name>.*filters\.from_users/u,
],
[
problem(401, "unauthorized", "Authentication required"),
"HUB_REQUEST_FAILED",
/paseo hub login http/u,
],
[
problem(409, "dispatch_conflict", "Run not dispatched"),
"HUB_REQUEST_FAILED",
/--delivery-key build-42/u,
],
[
problem(503, "infrastructure_unavailable", "Service unavailable"),
"HUB_REQUEST_FAILED",
/--delivery-key build-42/u,
],
[
{ status: 200, body: { unexpected: true } },
"HUB_INVALID_RESPONSE",
/--delivery-key build-42/u,
],
])("says what to do after Hub answers %#", async (response, code, details) => {
const hub = await startHub({ run: response });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await assert.rejects(cli.run("deploy", undefined, { deliveryKey: "build-42" }), (error) => {
assert.ok(error instanceof HubCommandError);
assert.equal(error.code, code);
assert.match(error.details ?? "", details);
assert.equal(`${error.message}${error.details ?? ""}`.includes("stored-secret"), false);
return true;
});
});
it("offers a safe retry when Hub cannot be reached", async () => {
const cli = harness({
env: { PASEO_HUB_URL: "http://127.0.0.1:1", PASEO_HUB_API_KEY: "secret" },
});
const error = await rejectsWith(
cli.run("deploy", undefined, { deliveryKey: "build-42" }),
"HUB_NETWORK_ERROR",
/Could not reach Paseo Hub at http:\/\/127\.0\.0\.1:1/u,
);
assert.match(error.details ?? "", /--delivery-key build-42/u);
});
it("accepts a response with fields this CLI does not know yet", async () => {
const hub = await startHub({
run: { status: 200, body: { ...dispatched("build-42"), activityUrl: "https://hub.test/a" } },
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const result = await cli.run("deploy", undefined, { deliveryKey: "build-42" });
assert.equal(result.data.triggerRunId, runId);
});
it("points at hub login when there is no credential", async () => {
const cli = harness({ env: { PASEO_HUB_URL: "https://hub.test" } });
await rejectsWith(
cli.run("deploy", undefined),
"HUB_API_KEY_REQUIRED",
/paseo hub login https:\/\/hub\.test/u,
);
});
it("fails immediately without a trigger name when it cannot ask", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const login = { origin: hub.origin, credential: "stored-secret" };
for (const cli of [
harness({ login }),
harness({ login, interactive: true, options: { json: true } }),
harness({ login, interactive: true, options: { quiet: true } }),
harness({ login, interactive: true, options: { format: "yaml" } }),
]) {
await rejectsWith(
cli.run(undefined, undefined),
"HUB_TRIGGER_REQUIRED",
/paseo hub run <trigger>/u,
);
}
assert.deepEqual(hub.requests, []);
});
it("in a terminal, offers the manual triggers and asks for missing required inputs", async () => {
const hub = await startHub({
triggers: [
deployTrigger,
trigger(
"audit",
"name: audit\non:\n manual.run: {}\ninputs:\n repo: {type: string, required: true}\n",
),
trigger("on-push", "name: on-push\non:\n github.push: {}\n"),
{ ...trigger("paused", "name: paused\non:\n manual.run: {}\n"), enabled: false },
],
});
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
answers: ["deploy", "production"],
});
await cli.run(undefined, undefined);
assert.deepEqual(cli.asked, [
{ message: "Which trigger?", options: ["audit", "deploy"] },
{ message: "environment", options: ["staging", "production"] },
]);
assert.deepEqual(
hub.dispatches().map(({ trigger: name, input }) => ({ name, input })),
[{ name: "deploy", input: "environment=production" }],
);
});
it("asks for typed free text and rejects values Hub could not read", async () => {
const hub = await startHub({
triggers: [
trigger(
"scale",
"name: scale\non:\n manual.run: {}\ninputs:\n count: {type: number, required: true}\n",
),
],
});
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
answers: ["4"],
});
await cli.run("scale", undefined);
assert.equal(cli.validators[0]?.("four"), "Enter a number");
assert.equal(cli.validators[0]?.(""), "Required");
assert.equal(cli.validators[0]?.("4 5"), "No spaces");
assert.equal(cli.validators[0]?.("4"), undefined);
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["count=4"],
);
});
it("does not ask again for an input already typed at the start of the prompt", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
});
await cli.run("deploy", "environment=staging ship it");
assert.deepEqual(cli.asked, []);
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["environment=staging ship it"],
);
});
it.each([
["a legacy project trigger", "legacy-deploy", [deployTrigger]],
[
"a trigger document it cannot read",
"odd",
[deployTrigger, trigger("odd", "name: odd\non: nonsense\n")],
],
])("says the input names were not checked for %s", async (_case, name, triggers) => {
const hub = await startHub({ triggers });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await cli.run(name, undefined, { input: ["environment=staging"] });
assert.equal(
cli.progress.at(-1),
`Input names were not checked: no readable organization trigger "${name}".`,
);
});
it("is not blocked by another trigger's unreadable document, and reads YAML merge keys", async () => {
const hub = await startHub({
triggers: [
trigger("odd", "name: odd\non: nonsense\n"),
trigger(
"merged",
"name: merged\non:\n manual.run: {}\ninputs:\n a: &text {type: string}\n b: {<<: *text}\n",
),
],
});
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await cli.run("merged", undefined, { input: ["b=two"] });
assert.deepEqual(
hub.dispatches().map(({ input }) => input),
["b=two"],
);
assert.deepEqual(cli.progress, [`Running merged on ${hub.origin}`]);
});
it("adds nothing to the error output when an unchecked run fails", async () => {
const hub = await startHub({
list: problem(403, "insufficient_scope", "Insufficient scope"),
run: problem(503, "infrastructure_unavailable", "Service unavailable"),
});
const cli = harness({ env: { PASEO_HUB_URL: hub.origin, PASEO_HUB_API_KEY: "ci-secret" } });
await assert.rejects(cli.run("deploy", undefined, { input: ["a=b"], json: true }));
assert.deepEqual(cli.progress, []);
});
it("points at hub login when the credential expired before the triggers were listed", async () => {
const hub = await startHub({ list: problem(401, "unauthorized", "Authentication required") });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
await assert.rejects(cli.run("deploy", undefined, { input: ["a=b"] }), (error) => {
assert.ok(error instanceof HubCommandError);
assert.match(error.details ?? "", /paseo hub login http/u);
return true;
});
assert.deepEqual(hub.dispatches(), []);
});
it.each([
problem(403, "actor_forbidden", "Actor forbidden"),
problem(400, "invalid_input", "Invalid trigger input"),
])("asks for a new delivery key to correct a rejected request: %#", async (response) => {
const hub = await startHub({ run: response });
const cli = harness({ login: { origin: hub.origin, credential: "stored-secret" } });
const details = async (options: HubRunOptions) => {
let caught: unknown;
await cli.run("deploy", undefined, options).catch((error: unknown) => {
caught = error;
});
assert.ok(caught instanceof HubCommandError);
return caught.details ?? "";
};
assert.match(await details({ deliveryKey: "build-42" }), /new --delivery-key/u);
assert.doesNotMatch(await details({}), /--delivery-key/u);
});
it("does not send a picked choice that Hub would cut at the space", async () => {
const hub = await startHub({
triggers: [
trigger(
"region",
"name: region\non:\n manual.run: {}\ninputs:\n region: {type: string, required: true, choices: [us east]}\n",
),
],
});
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
answers: ["us east"],
});
await rejectsWith(cli.run("region", undefined), "HUB_RUN_INPUT", /cannot contain spaces/u);
assert.deepEqual(hub.dispatches(), []);
});
it("starts nothing when the question is cancelled", async () => {
const hub = await startHub({ triggers: [deployTrigger] });
const cli = harness({
login: { origin: hub.origin, credential: "stored-secret" },
interactive: true,
answers: [null],
});
await rejectsWith(cli.run("deploy", undefined), "HUB_RUN_CANCELLED", /Nothing was started/u);
assert.deepEqual(hub.dispatches(), []);
});
});
const runId = "f83dc934-02a0-4849-8de7-699110be24ed";
function dispatched(deliveryKey: string) {
return {
deliveryKey,
providerEventReceiptId: "845e9d26-7977-45e1-bc69-d80a7b55a9cc",
triggerRunId: runId,
configuredTriggerName: "deploy",
workflowStatus: "running",
};
}
function trigger(name: string, yaml: string) {
return {
id: "a50e05af-4f20-4c8f-8dcc-58e5ea360663",
name,
enabled: true,
format: "single_run" as "single_run" | "legacy_multistep",
yaml,
};
}
interface FakeResponse {
status: number;
body: unknown;
}
function problem(
status: number,
code: string,
title: string,
issues?: Array<{ path: string[]; message: string }>,
): FakeResponse {
return {
status,
body: { title, status, code, detail: `${title}.`, ...(issues ? { issues } : {}) },
};
}
async function startHub(
input: {
triggers?: ReturnType<typeof trigger>[];
list?: FakeResponse;
run?: FakeResponse;
} = {},
) {
const requests: Array<{ route: string; authorization: string | undefined; body: unknown }> = [];
const server = createServer((request, response) => {
let body = "";
request.setEncoding("utf8");
request.on("data", (chunk: string) => {
body += chunk;
});
request.on("end", () => {
const route = `${request.method} ${request.url}`;
const parsed: unknown = body === "" ? undefined : JSON.parse(body);
requests.push({ route, authorization: request.headers.authorization, body: parsed });
const reply =
route === "GET /api/v1/triggers"
? (input.list ?? { status: 200, body: { triggers: input.triggers ?? [] } })
: (input.run ?? {
status: 200,
body: dispatched((parsed as { deliveryKey: string }).deliveryKey),
});
response.writeHead(reply.status, {
"content-type": reply.status >= 400 ? "application/problem+json" : "application/json",
});
response.end(JSON.stringify(reply.body));
});
});
servers.push(server);
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const { port } = server.address() as AddressInfo;
return {
origin: `http://127.0.0.1:${port}`,
requests,
dispatches: () =>
requests
.filter(({ route }) => route === "POST /api/v1/manual-runs")
.map(({ body }) => body as Record<string, string>),
};
}
function harness(
input: {
env?: Record<string, string>;
login?: StoredHubCredential;
interactive?: boolean;
answers?: Array<string | null>;
options?: HubRunOptions;
} = {},
) {
const progress: string[] = [];
const asked: Array<{ message: string; options?: string[] }> = [];
const validators: Array<(value: string) => string | undefined> = [];
const answers = [...(input.answers ?? [])];
const prompts: HubRunPrompts = {
async select(question) {
asked.push({ message: question.message, options: question.options });
return answers.shift() ?? null;
},
async text(question) {
asked.push({ message: question.message });
validators.push(question.validate);
return answers.shift() ?? null;
},
};
const state = {
progress,
asked,
validators,
cwd: process.cwd(),
run(name: string | undefined, prompt: string | undefined, options: HubRunOptions = {}) {
return runHubRun(
name,
prompt,
{ ...input.options, ...options },
{
env: input.env ?? {},
credentials: memoryCredentials(input.login),
hub: new HubHttpClient(),
reporter: { progress: (message) => progress.push(message) },
cwd: () => state.cwd,
isInteractive: () => input.interactive ?? false,
prompts,
},
);
},
};
return state;
}
function memoryCredentials(login: StoredHubCredential | undefined): HubCredentialStore {
return {
active: () => login ?? null,
get: (origin) => (login?.origin === origin ? login : null),
save: () => assert.fail("a run never writes credentials"),
logoutActive: () => assert.fail("a run never writes credentials"),
};
}
async function rejectsWith(
operation: Promise<unknown>,
code: string,
message: RegExp,
): Promise<HubCommandError> {
let caught: unknown;
await operation.catch((error: unknown) => {
caught = error;
});
assert.ok(caught instanceof HubCommandError, `expected ${code}, got ${String(caught)}`);
assert.equal(caught.code, code);
assert.match(caught.message, message);
return caught;
}
-261
View File
@@ -1,261 +0,0 @@
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import path from "node:path";
import type { Command } from "commander";
import {
isHumanOutput,
withOutput,
type CommandOptions,
type OutputSchema,
type SingleResult,
} from "../../../output/index.js";
import { addJsonOption, collectMultiple } from "../../../utils/command-options.js";
import { resolveHubCredential, resolveHubOrigin } from "../authority.js";
import type { HubCredentialStore } from "../credentials.js";
import { HubCommandError } from "../error.js";
import { addHubResolutionHelp } from "../help.js";
import type { HubHttpClient } from "../hub-client/index.js";
import { reportHubProgress, type HubReporter } from "../reporter.js";
import { availableTriggers, explainRunFailure, explainSignIn } from "./internal/failures.js";
import {
assertDeclared,
encodeInvocation,
missingInputs,
parseInputFlags,
type InputValue,
} from "./internal/inputs.js";
import { isRunnable, readManualTrigger, type ManualTrigger } from "./internal/manual-trigger.js";
import { askInputs, chooseTrigger, type HubRunPrompts } from "./internal/prompts.js";
export { terminalRunPrompts, type HubRunPrompts } from "./internal/prompts.js";
const DEFAULT_ACTOR = "paseo-cli";
interface HubRunResult {
origin: string;
triggerRunId: string;
configuredTriggerName: string;
workflowStatus: string;
deliveryKey: string;
providerEventReceiptId: string;
}
const schema: OutputSchema<HubRunResult> = {
idField: "triggerRunId",
columns: [
{ header: "TRIGGER", field: "configuredTriggerName" },
{ header: "RUN ID", field: "triggerRunId" },
{ header: "STATUS", field: "workflowStatus" },
{ header: "HUB", field: "origin" },
],
};
export type HubRunOptions = Pick<CommandOptions, "json" | "quiet" | "format"> & {
input?: string[];
promptFile?: string;
actor?: string;
deliveryKey?: string;
project?: string;
hub?: string;
apiKey?: string;
};
export interface HubRunDependencies {
env: Readonly<Record<string, string | undefined>>;
credentials: HubCredentialStore;
hub: Pick<HubHttpClient, "listTriggers" | "dispatchManualRun">;
reporter: HubReporter;
cwd(): string;
isInteractive(): boolean;
prompts: HubRunPrompts;
}
export async function runHubRun(
triggerArgument: string | undefined,
promptArgument: string | undefined,
options: HubRunOptions,
dependencies: HubRunDependencies,
): Promise<SingleResult<HubRunResult>> {
const flags = parseInputFlags(options.input ?? []);
const prompt = await readPrompt(promptArgument, options.promptFile, dependencies.cwd());
const canAsk = dependencies.isInteractive() && isHumanOutput(options);
if (triggerArgument === undefined && !canAsk) throw triggerRequired();
const resolution = {
options: { origin: options.hub, apiKey: options.apiKey },
env: dependencies.env,
credentials: dependencies.credentials,
};
const origin = resolveHubOrigin(resolution);
const credential = resolveHubCredential({ ...resolution, origin });
const triggers = organizationTriggers(dependencies.hub, origin, credential);
const name = triggerArgument ?? (await pickTrigger(triggers, origin, dependencies.prompts));
const { inputs, unchecked } =
flags.length > 0 || canAsk
? await completeInputs({ name, flags, prompt, canAsk, dependencies, triggers })
: { inputs: flags, unchecked: undefined };
reportHubProgress(dependencies.reporter, options, `Running ${name} on ${origin}`);
const deliveryKey = options.deliveryKey ?? randomUUID();
try {
const run = await dependencies.hub.dispatchManualRun(origin, credential, {
// Required by Hub, and ignored when the name belongs to an organization trigger.
projectSlug: options.project ?? "default",
trigger: name,
actor: options.actor ?? DEFAULT_ACTOR,
deliveryKey,
input: encodeInvocation(inputs, prompt),
});
// Said once Hub has accepted: a failed `--json` run keeps stderr as the error alone.
if (unchecked !== undefined) {
dependencies.reporter.progress(`Input names were not checked: ${unchecked}.`);
}
return { type: "single", data: { ...run, origin }, schema };
} catch (error) {
throw await explainRunFailure(error, {
trigger: name,
origin,
project: options.project,
deliveryKey,
keyFromCaller: options.deliveryKey !== undefined,
triggers,
});
}
}
export function addHubRunCommand(parent: Command, dependencies: HubRunDependencies): void {
addJsonOption(
addHubResolutionHelp(
parent
.command("run")
.description("Run a manual trigger")
.argument("[trigger]", "Trigger name. Omit in a terminal to pick one")
.argument("[prompt]", "Text the trigger receives as ${{ paseo.prompt }}")
.option(
"-i, --input <name=value>",
"Set a declared input (repeatable)",
collectMultiple,
[],
)
.option("--prompt-file <path>", "Read the prompt from a UTF-8 text file")
.option("--actor <name>", "Name checked against filters.from_users", DEFAULT_ACTOR)
.option("--delivery-key <key>", "Reuse on retry to avoid starting a second run")
.option("-p, --project <slug>", "Run a trigger from a legacy project bundle")
.option("--hub <origin>", "Paseo Hub origin")
.option("--api-key <secret>", "Organization API key")
// An unquoted prompt must fail instead of silently losing every word after the first.
.allowExcessArguments(false)
.addHelpText(
"after",
'\nExamples:\n paseo hub run triage\n paseo hub run deploy -i environment=staging "ship the hotfix"\n RUN_ID=$(paseo hub run triage --prompt-file report.md --quiet)\n',
),
),
).action(
withOutput(async (...args) => {
const trigger = args[0] as string | undefined;
const prompt = args[1] as string | undefined;
const options = args.at(-2) as HubRunOptions;
return runHubRun(trigger, prompt, options, dependencies);
}),
);
}
type OrganizationTriggers = () => Promise<readonly ManualTrigger[] | null>;
/** Listed at most once, and only when needed. `null`: the credential may only dispatch. */
function organizationTriggers(
hub: Pick<HubHttpClient, "listTriggers">,
origin: string,
credential: string,
): OrganizationTriggers {
let listed: Promise<readonly ManualTrigger[] | null> | undefined;
const list = async () => {
try {
const documents = await hub.listTriggers(origin, credential);
return documents.flatMap((document) => readManualTrigger(document) ?? []);
} catch (error) {
if (error instanceof HubCommandError && error.hubProblem?.status === 403) return null;
throw explainSignIn(error, origin);
}
};
return () => (listed ??= list());
}
async function pickTrigger(
triggers: OrganizationTriggers,
origin: string,
prompts: HubRunPrompts,
): Promise<string> {
const listed = await triggers();
if (listed === null) throw triggerRequired();
const names = listed
.filter(isRunnable)
.map(({ name }) => name)
.toSorted();
if (names.length === 0) {
throw new HubCommandError(
"HUB_TRIGGER_NOT_FOUND",
`Nothing to run on ${origin}.`,
availableTriggers(listed),
);
}
return chooseTrigger(prompts, names);
}
async function completeInputs(input: {
name: string;
flags: InputValue[];
prompt: string;
canAsk: boolean;
dependencies: HubRunDependencies;
triggers: OrganizationTriggers;
}): Promise<{ inputs: InputValue[]; unchecked?: string }> {
const { name, flags, prompt, canAsk, dependencies } = input;
const listed = await input.triggers();
const trigger = listed?.find((candidate) => candidate.name === name);
if (trigger === undefined) {
if (flags.length === 0) return { inputs: flags };
const unchecked =
listed === null
? "this credential cannot list triggers (configuration:validate)"
: `no readable organization trigger "${name}"`;
return { inputs: flags, unchecked };
}
// A trigger that cannot run gets Hub's answer, not questions about its inputs.
if (!isRunnable(trigger)) return { inputs: flags };
assertDeclared(trigger, flags);
if (!canAsk) return { inputs: flags };
const missing = missingInputs(trigger, flags, prompt);
return { inputs: [...flags, ...(await askInputs(dependencies.prompts, missing))] };
}
async function readPrompt(
argument: string | undefined,
file: string | undefined,
cwd: string,
): Promise<string> {
if (file === undefined) return argument?.trim() ?? "";
if (argument !== undefined) {
throw new HubCommandError(
"HUB_RUN_PROMPT_CONFLICT",
"Pass the prompt as a prompt argument or --prompt-file, not both.",
);
}
const filePath = path.resolve(cwd, file);
try {
return (await readFile(filePath, "utf8")).trim();
} catch {
throw new HubCommandError(
"HUB_RUN_PROMPT_UNREADABLE",
`Could not read the prompt file ${filePath}.`,
);
}
}
function triggerRequired(): HubCommandError {
return new HubCommandError(
"HUB_TRIGGER_REQUIRED",
"Name the trigger to run: paseo hub run <trigger>",
);
}
@@ -1,133 +0,0 @@
import { HubCommandError } from "../../error.js";
import { describeInputs } from "./inputs.js";
import { isRunnable, type ManualTrigger } from "./manual-trigger.js";
interface RunAttempt {
trigger: string;
origin: string;
project: string | undefined;
deliveryKey: string;
keyFromCaller: boolean;
/** The organization's triggers, or null when they cannot be listed. */
triggers(): Promise<readonly ManualTrigger[] | null>;
}
/** Turn a failed dispatch into what went wrong and what to do next. */
export async function explainRunFailure(error: unknown, attempt: RunAttempt): Promise<unknown> {
if (!(error instanceof HubCommandError)) return error;
const problem = error.hubProblem;
// Hub answers `project_not_found` for an unknown name when no `default` project exists.
if (
attempt.project === undefined &&
(problem?.code === "trigger_not_found" || problem?.code === "project_not_found")
) {
return explainMissingTrigger(error, attempt);
}
if (problem?.code === "invalid_input") {
return forCorrection(await explainInvalidInput(error, attempt), attempt);
}
if (problem?.code === "actor_forbidden") {
const advice = "Pass --actor <name> with a name listed in the trigger's filters.from_users.";
return forCorrection(advise(error, advice), attempt);
}
if (problem?.status === 401) return explainSignIn(error, attempt.origin);
// Hub may hold the request already: only the same delivery key makes a retry safe.
if (
problem === undefined ||
problem.status >= 500 ||
problem.code === "dispatch_conflict" ||
error.code === "HUB_INVALID_RESPONSE"
) {
return advise(
error,
`If Hub received the request, retry with --delivery-key ${attempt.deliveryKey} to avoid starting it twice.`,
);
}
return error;
}
export function explainSignIn(error: unknown, origin: string): unknown {
if (!(error instanceof HubCommandError) || error.hubProblem?.status !== 401) return error;
return advise(
error,
`Run \`paseo hub login ${origin}\`, or check --api-key and PASEO_HUB_API_KEY.`,
);
}
// Hub stores a request before rejecting it, and replays the stored one for the same key.
function forCorrection(error: HubCommandError, attempt: RunAttempt): HubCommandError {
if (!attempt.keyFromCaller) return error;
return advise(error, "Send the corrected request with a new --delivery-key.");
}
async function explainInvalidInput(
error: HubCommandError,
attempt: RunAttempt,
): Promise<HubCommandError> {
const trigger = (await listForHint(attempt))?.find(({ name }) => name === attempt.trigger);
const reasons = error.details?.replace(/^input: /gmu, "").replaceAll("\n", "; ");
return new HubCommandError(
"HUB_INVALID_INPUT",
reasons === undefined ? error.message : `${error.message}: ${reasons}`,
trigger === undefined ? undefined : describeInputs(trigger),
error.hubProblem,
);
}
async function explainMissingTrigger(
error: HubCommandError,
attempt: RunAttempt,
): Promise<HubCommandError> {
const triggers = await listForHint(attempt);
const found = triggers?.find(({ name }) => name === attempt.trigger);
const notFound = (message: string, details?: string) =>
new HubCommandError("HUB_TRIGGER_NOT_FOUND", message, details, error.hubProblem);
if (found === undefined) {
return notFound(
`No manual trigger "${attempt.trigger}" on ${attempt.origin}.`,
triggers === null ? undefined : availableTriggers(triggers),
);
}
if (!found.enabled) {
return notFound(
`Trigger "${found.name}" is disabled on ${attempt.origin}.`,
"Enable it in Hub, then run it again.",
);
}
if (!found.manual) {
return notFound(
`Trigger "${found.name}" has no manual.run event on ${attempt.origin}.`,
"Add `manual.run: {}` under `on` and deploy it.",
);
}
return error;
}
export function availableTriggers(triggers: readonly ManualTrigger[]): string {
const names = triggers
.filter(isRunnable)
.map(({ name }) => name)
.toSorted();
return names.length === 0
? "No manual triggers yet. Add `manual.run: {}` under `on` and deploy one."
: `Manual triggers: ${names.join(", ")}`;
}
// A hint is optional: failing to fetch it must not replace the error the person needs.
async function listForHint(attempt: RunAttempt): Promise<readonly ManualTrigger[] | null> {
try {
return await attempt.triggers();
} catch {
return null;
}
}
function advise(error: HubCommandError, advice: string): HubCommandError {
return new HubCommandError(
error.code,
error.message,
error.details === undefined ? advice : `${error.details}\n${advice}`,
error.hubProblem,
);
}
@@ -1,103 +0,0 @@
import { HubCommandError } from "../../error.js";
import type { DeclaredInput, ManualTrigger } from "./manual-trigger.js";
// Hub's manual dispatch takes one string: leading `name=value` tokens, then the prompt. A token
// it does not recognise ends the inputs and becomes prompt text, and the run starts with defaults.
// These checks stop an `-i` value Hub would misread without saying so; Hub validates the rest.
// Pairs at the start of the prompt are Hub's own syntax and pass through.
const INPUT_NAME = /^[a-z][a-z0-9_-]*$/u;
const LEADING_TOKEN = /^([a-z][a-z0-9_-]*)=[^\s]*(?:\s+|$)/u;
export interface InputValue {
name: string;
value: string;
}
export function parseInputFlags(flags: readonly string[]): InputValue[] {
return flags.map((flag) => {
const separator = flag.indexOf("=");
if (separator < 1) throw invalidInput(`--input expects name=value, got "${flag}".`);
const name = flag.slice(0, separator);
const value = flag.slice(separator + 1);
if (!INPUT_NAME.test(name)) {
throw invalidInput(
`Input names are lowercase letters, digits, "-" and "_", starting with a letter. Got "${name}".`,
);
}
return sendableInput(name, value);
});
}
export function sendableInput(name: string, value: string): InputValue {
if (/\s/u.test(value)) {
throw invalidInput(
`Input "${name}" cannot contain spaces. Hub separates inputs by spaces; put free text in the prompt.`,
);
}
return { name, value };
}
export function encodeInvocation(inputs: readonly InputValue[], prompt: string): string {
return [...inputs.map(({ name, value }) => `${name}=${value}`), prompt]
.filter((part) => part !== "")
.join(" ");
}
export function assertDeclared(trigger: ManualTrigger, inputs: readonly InputValue[]): void {
const unknown = inputs.find(
({ name }) => !trigger.inputs.some((declared) => declared.name === name),
);
if (unknown === undefined) return;
throw invalidInput(
`Trigger "${trigger.name}" has no input "${unknown.name}".`,
describeInputs(trigger),
);
}
/** Required inputs that neither a flag nor a token typed at the start of the prompt supplies. */
export function missingInputs(
trigger: ManualTrigger,
inputs: readonly InputValue[],
prompt: string,
): DeclaredInput[] {
const supplied = new Set(inputs.map(({ name }) => name));
let rest = prompt;
for (let token = LEADING_TOKEN.exec(rest); token !== null; token = LEADING_TOKEN.exec(rest)) {
if (!trigger.inputs.some(({ name }) => name === token?.[1])) break;
supplied.add(token[1]!);
rest = rest.slice(token[0].length);
}
return trigger.inputs.filter(
(input) => input.required === true && input.default === undefined && !supplied.has(input.name),
);
}
export function describeInputs(trigger: ManualTrigger): string {
if (trigger.inputs.length === 0) {
return `Trigger "${trigger.name}" declares no inputs. Put free text in the prompt.`;
}
const rows = trigger.inputs.map((input) => ({
flag: `-i ${input.name}=<${input.choices?.join("|") ?? VALUE_PLACEHOLDERS[input.type]}>`,
note: inputNote(input),
}));
const width = Math.max(...rows.map(({ flag }) => flag.length));
return [
`Inputs of "${trigger.name}":`,
...rows.map(({ flag, note }) => ` ${flag.padEnd(width)} ${note}`.trimEnd()),
].join("\n");
}
const VALUE_PLACEHOLDERS: Record<DeclaredInput["type"], string> = {
string: "text",
number: "number",
boolean: "true|false",
};
function inputNote(input: DeclaredInput): string {
if (input.default !== undefined) return `default ${String(input.default)}`;
return input.required === true ? "required" : "";
}
function invalidInput(message: string, details?: string): HubCommandError {
return new HubCommandError("HUB_RUN_INPUT", message, details);
}
@@ -1,70 +0,0 @@
import YAML from "yaml";
import { z } from "zod";
import type { HubTrigger } from "../../hub-client/index.js";
const inputsSchema = z
.record(
z.string(),
z.object({
type: z.enum(["string", "number", "boolean"]),
required: z.boolean().optional(),
default: z.union([z.string(), z.number(), z.boolean()]).optional(),
choices: z.array(z.union([z.string(), z.number(), z.boolean()])).optional(),
}),
)
.optional();
const singleRunSchema = z.object({
on: z.record(z.string(), z.unknown()),
inputs: inputsSchema,
});
// Hub keeps migrated workflows it cannot express as one run in this shape.
const legacyMultistepSchema = z.object({
legacy_multistep: z.object({
trigger: z.object({ on: z.string(), inputs: inputsSchema }),
}),
});
export type DeclaredInput = NonNullable<z.infer<typeof inputsSchema>>[string] & { name: string };
export interface ManualTrigger {
name: string;
enabled: boolean;
/** Whether the document declares `manual.run`. */
manual: boolean;
inputs: DeclaredInput[];
}
/** `null`: a document this CLI cannot read. Hub still decides whether it runs. */
export function readManualTrigger(trigger: HubTrigger): ManualTrigger | null {
try {
// Hub's parser follows `<<` merge keys.
const document: unknown = YAML.parse(trigger.yaml, { merge: true });
const { manual, inputs } = readDocument(trigger.format, document);
return {
name: trigger.name,
enabled: trigger.enabled,
manual,
inputs: Object.entries(inputs ?? {}).map(([name, input]) => Object.assign(input, { name })),
};
} catch {
return null;
}
}
export function isRunnable(trigger: ManualTrigger): boolean {
return trigger.enabled && trigger.manual;
}
function readDocument(
format: HubTrigger["format"],
document: unknown,
): { manual: boolean; inputs: z.infer<typeof inputsSchema> } {
if (format === "legacy_multistep") {
const { on, inputs } = legacyMultistepSchema.parse(document).legacy_multistep.trigger;
return { manual: on === "manual.run", inputs };
}
const { on, inputs } = singleRunSchema.parse(document);
return { manual: Object.hasOwn(on, "manual.run"), inputs };
}
@@ -1,67 +0,0 @@
import { isCancel, select, text } from "@clack/prompts";
import { HubCommandError } from "../../error.js";
import { sendableInput, type InputValue } from "./inputs.js";
import type { DeclaredInput } from "./manual-trigger.js";
/** Questions asked in a terminal. `null` means the person cancelled. */
export interface HubRunPrompts {
select(question: { message: string; options: string[] }): Promise<string | null>;
text(question: {
message: string;
validate(value: string): string | undefined;
}): Promise<string | null>;
}
export const terminalRunPrompts: HubRunPrompts = {
async select({ message, options }) {
const answer = await select<string>({
message,
options: options.map((value) => ({ value, label: value })),
});
return isCancel(answer) ? null : answer;
},
async text({ message, validate }) {
const answer = await text({ message, validate: (value) => validate(value ?? "") });
return isCancel(answer) ? null : answer;
},
};
export async function chooseTrigger(prompts: HubRunPrompts, names: string[]): Promise<string> {
return answered(await prompts.select({ message: "Which trigger?", options: names }));
}
export async function askInputs(
prompts: HubRunPrompts,
inputs: readonly DeclaredInput[],
): Promise<InputValue[]> {
const values: InputValue[] = [];
for (const input of inputs) {
const options =
input.choices?.map(String) ?? (input.type === "boolean" ? ["true", "false"] : undefined);
const answer =
options === undefined
? await prompts.text({
message: input.name,
validate: (value) => invalidAnswer(input, value),
})
: await prompts.select({ message: input.name, options });
values.push(sendableInput(input.name, answered(answer)));
}
return values;
}
function invalidAnswer(input: DeclaredInput, value: string): string | undefined {
if (value === "") return "Required";
if (/\s/u.test(value)) return "No spaces";
if (input.type === "number" && !/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/u.test(value)) {
return "Enter a number";
}
return undefined;
}
function answered(answer: string | null): string {
if (answer === null) {
throw new HubCommandError("HUB_RUN_CANCELLED", "Cancelled. Nothing was started.");
}
return answer;
}
+2 -2
View File
@@ -42,7 +42,7 @@ function normalizeFormat(raw: unknown): OutputOptions["format"] {
}
/** Extract output options from command options */
function extractOutputOptions(options: Partial<CommandOptions>): OutputOptions {
function extractOutputOptions(options: CommandOptions): OutputOptions {
const hasStructuredOutputSchema =
typeof options.outputSchema === "string" && options.outputSchema.trim().length > 0;
@@ -63,7 +63,7 @@ function extractOutputOptions(options: Partial<CommandOptions>): OutputOptions {
};
}
export function isHumanOutput(options: Partial<CommandOptions>): boolean {
export function isHumanOutput(options: CommandOptions): boolean {
const { format, quiet } = extractOutputOptions(options);
return format === "table" && !quiet;
}
+6 -14
View File
@@ -24,7 +24,7 @@ import { $ } from "zx";
import { mkdtemp, rm, mkdir } from "fs/promises";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { runPaseoCli, startTestDaemon, type TestDaemonContext } from "./helpers/test-daemon.ts";
import { runPaseoCli, startTestDaemon } from "./helpers/test-daemon.ts";
import { tmpdir } from "os";
import { join } from "path";
@@ -174,11 +174,10 @@ try {
// Exercise repository selection through the real CLI and daemon. An empty
// request used to fail before Git could inspect even a valid repository.
const fixtureDir = await mkdtemp(join(tmpdir(), "paseo-worktree-test-"));
const repo = join(fixtureDir, "repository");
const daemon = await startTestDaemon();
const git = promisify(execFile);
let daemon: TestDaemonContext | undefined;
try {
const repo = join(daemon.workDir, "repository");
await mkdir(repo);
await git("git", ["init", repo]);
await git("git", [
@@ -194,9 +193,6 @@ try {
"Initial commit",
]);
// With an explicit endpoint, relative paths resolve from the daemon cwd.
daemon = await startTestDaemon({ cwd: repo });
for (const args of [
["worktree", "ls", "--json"],
["worktree", "ls", "--cwd", repo, "--json"],
@@ -205,7 +201,7 @@ try {
]) {
const explicit = args.includes("--cwd");
const result = await runPaseoCli(daemon, args, {
cwd: explicit ? fixtureDir : repo,
cwd: explicit ? daemon.workDir : repo,
env: { FORCE_COLOR: undefined },
});
assert.strictEqual(result.exitCode, 0, result.stderr);
@@ -228,18 +224,14 @@ try {
],
]) {
const result = await runPaseoCli(daemon, args, {
cwd: args.includes("--cwd") ? fixtureDir : repo,
cwd: args.includes("--cwd") ? daemon.workDir : repo,
env: { FORCE_COLOR: undefined },
});
assert.notStrictEqual(result.exitCode, 0);
assert.strictEqual(JSON.parse(result.stderr).error.code, "WORKTREE_NOT_FOUND", result.stderr);
}
} finally {
try {
await daemon?.stop();
} finally {
await rm(fixtureDir, { recursive: true, force: true });
}
await daemon.stop();
}
console.log("=== All worktree tests passed ===");
+1 -10
View File
@@ -6,16 +6,7 @@ import { createE2ETestContext } from "./helpers/test-daemon.ts";
import { connectToDaemon } from "../src/utils/client.ts";
import { resolveCliVersion } from "../src/version.ts";
// Built-in usage sources discover accounts from the daemon's environment.
const context = await createE2ETestContext({
baseEnv: {
PATH: process.env.PATH,
SystemRoot: process.env.SystemRoot,
TEMP: process.env.TEMP,
TMP: process.env.TMP,
TMPDIR: process.env.TMPDIR,
},
});
const context = await createE2ETestContext();
try {
const directory = join(context.workDir, "usage-plugin");
await mkdir(directory);
-109
View File
@@ -1,109 +0,0 @@
#!/usr/bin/env npx tsx
import assert from "node:assert/strict";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { runLocalPaseo } from "./helpers/local-cli.js";
const RUN_ID = "7f1c2a64-0b1e-4b55-9c52-6f0b7a1d2e90";
const dispatched: Record<string, unknown>[] = [];
const server = createServer((request, response) => {
let body = "";
request.setEncoding("utf8");
request.on("data", (chunk: string) => {
body += chunk;
});
request.on("end", () => {
const reply = (status: number, value: unknown) => {
response.writeHead(status, {
"content-type": status < 400 ? "application/json" : "application/problem+json",
});
response.end(JSON.stringify(value));
};
if (request.url === "/api/v1/triggers") {
reply(200, {
triggers: [
{
id: "0b0f4d3e-6a53-4a4b-8f0e-2f3c6a1b9d11",
name: "deploy",
enabled: true,
format: "single_run",
yaml: "name: deploy\non:\n manual.run: {}\ninputs:\n environment:\n type: string\n dry_run:\n type: boolean\nrun: {}\n",
},
],
});
return;
}
const dispatch = JSON.parse(body) as Record<string, unknown>;
dispatched.push(dispatch);
if (dispatch.trigger !== "deploy") {
reply(404, {
type: "about:blank",
title: "Trigger not found",
status: 404,
code: "trigger_not_found",
});
return;
}
reply(200, {
deliveryKey: dispatch.deliveryKey,
providerEventReceiptId: "receipt-1",
triggerRunId: RUN_ID,
configuredTriggerName: "deploy",
workflowStatus: "running",
});
});
});
try {
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
const connection = ["--hub", origin, "--api-key", "test-secret"];
const hubRun = (...args: string[]) => runLocalPaseo(["hub", "run", ...args, ...connection]);
const quiet = await hubRun(
"deploy",
"-i",
"environment=staging",
"--input",
"dry_run=false",
"ship the hotfix",
"--quiet",
);
assert.equal(quiet.exitCode, 0, quiet.stderr);
assert.equal(quiet.stdout, `${RUN_ID}\n`);
assert.equal(dispatched[0]?.input, "environment=staging dry_run=false ship the hotfix");
const yaml = await hubRun("deploy", "-o", "yaml");
assert.equal(yaml.exitCode, 0, yaml.stderr);
assert.match(yaml.stdout, new RegExp(`triggerRunId: ${RUN_ID}`, "u"));
const table = await hubRun("deploy", "--no-color");
assert.equal(table.exitCode, 0, table.stderr);
assert.match(table.stdout, /^TRIGGER\s+RUN ID\s+STATUS\s+HUB/u);
assert.equal(table.stderr, `Running deploy on ${origin}\n`);
const unknown = await hubRun("nope", "--json");
assert.equal(unknown.exitCode, 1);
assert.equal(unknown.stdout, "");
const { error } = JSON.parse(unknown.stderr) as { error: Record<string, unknown> };
assert.equal(error.code, "HUB_TRIGGER_NOT_FOUND");
assert.deepEqual(Object.keys(error).toSorted(), ["code", "details", "message", "name"]);
assert.doesNotMatch(unknown.stderr, /test-secret/u);
const before = dispatched.length;
// An unquoted prompt must not start a run with only its first word.
const unquoted = await hubRun("deploy", "ship", "the", "hotfix");
assert.equal(unquoted.exitCode, 1);
assert.match(unquoted.stderr, /too many arguments/u);
const unnamed = await hubRun();
assert.equal(unnamed.exitCode, 1);
assert.match(unnamed.stderr, /paseo hub run <trigger>/u);
assert.equal(dispatched.length, before);
console.log("✅ installed Paseo CLI runs Hub manual triggers");
} finally {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
+2 -9
View File
@@ -231,10 +231,7 @@ export async function startTestDaemon(options?: {
port?: number;
paseoHome?: string;
workDir?: string;
cwd?: string;
timeout?: number;
/** Environment to inherit before applying test defaults and explicit overrides. */
baseEnv?: NodeJS.ProcessEnv;
env?: NodeJS.ProcessEnv;
}): Promise<TestDaemonContext> {
// Let the listening process allocate its port, without a reserve/release race.
@@ -251,12 +248,9 @@ export async function startTestDaemon(options?: {
// Start daemon process using tsx to run TypeScript directly
const daemonProcess = spawn(process.execPath, [TSX_ENTRY, cliSrcPath, "daemon", "run"], {
cwd: options?.cwd,
env: {
...Object.fromEntries(
Object.entries(options?.baseEnv ?? process.env).filter(
([key]) => !key.startsWith("PASEO_"),
),
Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_")),
),
...TEST_DAEMON_ENV_DEFAULTS,
PASEO_HOME: paseoHome,
@@ -429,7 +423,6 @@ export async function runPaseoCli(
*/
export async function createE2ETestContext(options?: {
timeout?: number;
baseEnv?: NodeJS.ProcessEnv;
env?: NodeJS.ProcessEnv;
}): Promise<
TestDaemonContext & {
@@ -444,7 +437,7 @@ export async function createE2ETestContext(options?: {
}>;
}
> {
const ctx = await startTestDaemon(options);
const ctx = await startTestDaemon({ timeout: options?.timeout, env: options?.env });
const paseo = (
args: string[],
@@ -18,13 +18,6 @@ async function main() {
return path.join(release, matches[0]);
};
try {
if (installedOnly) {
const rpmFiles = execFileSync("rpm", ["-qpl", findArtifact(".rpm")], { encoding: "utf8" });
if (/^\/usr\/lib\/\.build-id\//m.test(rpmFiles)) {
throw new Error("The Paseo RPM claims build-ID paths shared by other Electron packages");
}
}
process.env.PASEO_DESKTOP_SMOKE_ARTIFACT_DIR = path.join(artifactRoot, "installed");
const helper = fs.statSync("/opt/Paseo/chrome-sandbox");
if (helper.uid !== 0 || (helper.mode & 0o7777) !== 0o4755) {
-3
View File
@@ -80,9 +80,6 @@ deb:
afterInstall: scripts/linux-sandbox/after-install.tpl
rpm:
afterInstall: scripts/linux-sandbox/after-install.tpl
# Electron apps can bundle the same binaries under different install paths.
fpm:
- "--rpm-rpmbuild-define=_build_id_links none"
appImage:
# A nonempty argument list replaces builder's hardcoded --no-sandbox default.
executableArgs: ["--class=Paseo"]
@@ -4641,303 +4641,6 @@ test("keeps the global Paseo-tools gate outside provider policy and MCP injectio
rmSync(workdir, { recursive: true, force: true });
});
test("voice-only delivery injects internal paseo MCP and native voiceOnly catalog even when Paseo tools are disabled", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const voiceActiveAgents = new Set<string>();
class VoiceMcpSession extends McpCapableTestAgentSession {
override readonly provider: AgentProvider;
constructor(config: AgentSessionConfig) {
super(config);
this.provider = config.provider;
}
override describePersistence(): AgentPersistenceHandle {
return {
provider: this.provider,
sessionId: this.id,
metadata: { cwd: workdir },
};
}
}
class VoiceMcpClient extends TestAgentClient {
override readonly capabilities = {
...TEST_CAPABILITIES,
supportsMcpServers: true,
};
readonly configs: AgentSessionConfig[] = [];
readonly launchContexts: Array<AgentLaunchContext | undefined> = [];
override async createSession(
config: AgentSessionConfig,
launchContext?: AgentLaunchContext,
): Promise<AgentSession> {
this.configs.push(config);
this.launchContexts.push(launchContext);
return new VoiceMcpSession(config);
}
override async resumeSession(
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
launchContext?: AgentLaunchContext,
): Promise<AgentSession> {
const config = {
provider: handle.provider,
cwd: workdir,
...overrides,
} as AgentSessionConfig;
this.configs.push(config);
this.launchContexts.push(launchContext);
return new VoiceMcpSession(config);
}
}
class VoiceNativeClient extends VoiceMcpClient {
override readonly capabilities = {
...TEST_CAPABILITIES,
supportsMcpServers: true,
supportsNativePaseoTools: true,
};
}
const speakCatalog: PaseoToolCatalog = {
tools: new Map([
[
"speak",
{
name: "speak",
description: "Speak text",
handler: async () => ({ content: [], structuredContent: { ok: true } }),
},
],
]),
getTool: (name) => (name === "speak" ? speakCatalog.tools.get("speak") : undefined),
executeTool: async () => ({ content: [], structuredContent: { ok: true } }),
};
const mcpClient = new VoiceMcpClient("claude");
const nativeClient = new VoiceNativeClient("opencode");
const catalogCalls: Array<{
callerAgentId?: string;
paseoToolPolicy?: unknown;
voiceOnly?: boolean;
}> = [];
const manager = new AgentManager({
clients: { claude: mcpClient, opencode: nativeClient },
registry: storage,
logger,
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
mcpAuthToken: "voice-token",
paseoToolsEnabled: false,
hasActiveVoiceTools: (agentId) => voiceActiveAgents.has(agentId),
paseoToolCatalogFactory: (context) => {
catalogCalls.push(context);
return speakCatalog;
},
});
try {
const claudeAgent = await manager.createAgent(
{ provider: "claude", cwd: workdir },
"00000000-0000-4000-8000-000000000201",
{ workspaceId: undefined },
);
const opencodeAgent = await manager.createAgent(
{ provider: "opencode", cwd: workdir },
"00000000-0000-4000-8000-000000000202",
{ workspaceId: undefined },
);
// Non-voice sessions receive zero Paseo MCP servers and zero native Paseo tools.
expect(mcpClient.configs.at(-1)?.mcpServers).toBeUndefined();
expect(mcpClient.launchContexts.at(-1)?.voiceToolsEnabled).toBeUndefined();
expect(nativeClient.configs.at(-1)?.mcpServers).toBeUndefined();
expect(nativeClient.launchContexts.at(-1)?.paseoTools).toBeUndefined();
expect(catalogCalls).toEqual([]);
// Enabling voice mode on MCP provider injects loopback paseo MCP and marks voiceToolsEnabled.
voiceActiveAgents.add(claudeAgent.id);
await manager.reloadAgentSession(
claudeAgent.id,
{ systemPrompt: "voice prompt" },
{ requireVoiceSpeak: true },
);
expect(mcpClient.configs.at(-1)?.mcpServers?.paseo).toEqual({
type: "http",
url: `http://127.0.0.1:6767/mcp/agents?callerAgentId=${claudeAgent.id}`,
headers: { Authorization: "Bearer voice-token" },
});
expect(mcpClient.launchContexts.at(-1)?.voiceToolsEnabled).toBe(true);
// Enabling voice mode on native-tools provider builds a voiceOnly catalog with speak only.
voiceActiveAgents.add(opencodeAgent.id);
await manager.reloadAgentSession(
opencodeAgent.id,
{ systemPrompt: "voice prompt" },
{ requireVoiceSpeak: true },
);
expect(catalogCalls).toEqual([
{
callerAgentId: opencodeAgent.id,
paseoToolPolicy: { enabled: false },
voiceOnly: true,
},
]);
expect(nativeClient.launchContexts.at(-1)?.paseoTools).toBe(speakCatalog);
expect(nativeClient.configs.at(-1)?.mcpServers?.paseo).toBeUndefined();
// Disabling voice mode removes paseo MCP and voiceToolsEnabled again.
voiceActiveAgents.delete(claudeAgent.id);
await manager.reloadAgentSession(claudeAgent.id, { systemPrompt: "normal prompt" });
expect(mcpClient.configs.at(-1)?.mcpServers).toBeUndefined();
expect(mcpClient.launchContexts.at(-1)?.voiceToolsEnabled).toBeUndefined();
} finally {
rmSync(workdir, { recursive: true, force: true });
}
});
test("reloadAgentSession rejects voice mode when the session cannot mount speak and preserves the live session", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
class PiNoMcpSession extends CloseRecordingTestAgentSession {
override readonly provider = "pi" as const;
override describePersistence(): AgentPersistenceHandle {
return {
provider: "pi",
sessionId: this.id,
metadata: { cwd: workdir },
};
}
}
const original = new PiNoMcpSession({ provider: "pi", cwd: workdir });
const reopened = new PiNoMcpSession({ provider: "pi", cwd: workdir });
let voiceActive = false;
class NoMcpPiClient extends TestAgentClient {
override readonly capabilities = {
...TEST_CAPABILITIES,
supportsMcpServers: false,
supportsNativePaseoTools: false,
};
override async createSession(): Promise<AgentSession> {
return original;
}
override async resumeSession(): Promise<AgentSession> {
return reopened;
}
}
class StdioOnlyAcpSession extends CloseRecordingTestAgentSession {
override readonly provider = "acp-stdio" as const;
override readonly capabilities = {
...TEST_CAPABILITIES,
supportsMcpServers: true,
supportsHttpMcpServers: false,
};
override describePersistence(): AgentPersistenceHandle {
return {
provider: "acp-stdio",
sessionId: this.id,
metadata: { cwd: workdir },
};
}
}
const acpOriginal = new StdioOnlyAcpSession({ provider: "acp-stdio", cwd: workdir });
const acpReopened = new StdioOnlyAcpSession({ provider: "acp-stdio", cwd: workdir });
class StdioOnlyAcpClient extends TestAgentClient {
override readonly capabilities = {
...TEST_CAPABILITIES,
supportsMcpServers: true,
};
override async createSession(): Promise<AgentSession> {
return acpOriginal;
}
override async resumeSession(): Promise<AgentSession> {
return acpReopened;
}
}
const manager = new AgentManager({
clients: {
pi: new NoMcpPiClient("pi"),
"acp-stdio": new StdioOnlyAcpClient("acp-stdio"),
},
registry: storage,
logger,
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
paseoToolsEnabled: false,
hasActiveVoiceTools: () => voiceActive,
});
try {
const created = await manager.createAgent(
{ provider: "pi", cwd: workdir, systemPrompt: "base prompt" },
"00000000-0000-4000-8000-000000000203",
{ workspaceId: undefined },
);
voiceActive = true;
await expect(
manager.reloadAgentSession(
created.id,
{ systemPrompt: "voice prompt" },
{ requireVoiceSpeak: true },
),
).rejects.toThrow(/speak/i);
expect(original.closed).toBe(false);
expect(reopened.closed).toBe(false);
expect(manager.getAgent(created.id)?.session).toBe(original);
expect(manager.getAgent(created.id)?.lifecycle).toBe("idle");
const stored = await storage.get(created.id);
expect(stored?.config?.systemPrompt).toBe("base prompt");
// ACP with mcpCapabilities.http=false still launches with stdio MCP servers,
// while rejecting voice mode cleanly without closing the live session.
voiceActive = false;
const acpAgent = await manager.createAgent(
{
provider: "acp-stdio",
cwd: workdir,
mcpServers: {
local: { type: "stdio", command: "node", args: ["mcp.js"] },
},
},
"00000000-0000-4000-8000-000000000204",
{ workspaceId: undefined },
);
expect(manager.getAgent(acpAgent.id)?.lifecycle).toBe("idle");
voiceActive = true;
await expect(
manager.reloadAgentSession(
acpAgent.id,
{ systemPrompt: "voice prompt" },
{ requireVoiceSpeak: true },
),
).rejects.toThrow(/speak/i);
expect(acpOriginal.closed).toBe(false);
expect(acpReopened.closed).toBe(false);
expect(manager.getAgent(acpAgent.id)?.session).toBe(acpOriginal);
expect(manager.getAgent(acpAgent.id)?.lifecycle).toBe("idle");
} finally {
rmSync(workdir, { recursive: true, force: true });
}
});
test("resumeAgentFromPersistence replaces stored internal paseo MCP with current runtime URL", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-test-"));
const storagePath = join(workdir, "agents");
@@ -437,7 +437,6 @@ export interface AgentManagerOptions {
pluginSessions?: PluginSessionsRuntime;
paseoToolsEnabled?: boolean;
paseoToolCatalogFactory?: PaseoToolCatalogFactory;
hasActiveVoiceTools?: (agentId: string) => boolean;
resolvePaseoToolPolicy?: (provider: AgentProvider) => ProviderPaseoToolsPolicy | undefined;
appendSystemPrompt?: string;
agentStreamCoalesceWindowMs?: number;
@@ -1001,7 +1000,6 @@ export class AgentManager {
private readonly pluginSessions: PluginSessionsRuntime | undefined;
private paseoToolsEnabled = true;
private paseoToolCatalogFactory: PaseoToolCatalogFactory | null = null;
private hasActiveVoiceTools: (agentId: string) => boolean = () => false;
private readonly paseoToolPolicies = new Map<string, ProviderPaseoToolsPolicy | undefined>();
private readonly resolvePaseoToolPolicy: (
provider: AgentProvider,
@@ -1054,7 +1052,6 @@ export class AgentManager {
private configurePaseoTools(options: AgentManagerOptions): void {
this.paseoToolsEnabled = options.paseoToolsEnabled ?? true;
this.paseoToolCatalogFactory = options.paseoToolCatalogFactory ?? null;
this.hasActiveVoiceTools = options.hasActiveVoiceTools ?? (() => false);
}
registerClient(provider: AgentProvider, client: AgentClient): void {
@@ -1119,10 +1116,6 @@ export class AgentManager {
this.paseoToolsEnabled = enabled;
}
isPaseoToolsEnabled(): boolean {
return this.paseoToolsEnabled;
}
setPaseoToolCatalogFactory(factory: PaseoToolCatalogFactory | null): void {
this.paseoToolCatalogFactory = factory;
}
@@ -2105,7 +2098,7 @@ export class AgentManager {
reloadAgentSession(
agentId: string,
overrides?: Partial<AgentSessionConfig>,
options?: { rehydrateFromDisk?: boolean; requireVoiceSpeak?: boolean },
options?: { rehydrateFromDisk?: boolean },
): Promise<ManagedAgent> {
return this.trackAgentRegistrationOperation(
this.runLifecycleMutation(agentId, () =>
@@ -2117,7 +2110,7 @@ export class AgentManager {
private reloadAgentSessionInternal(
agentId: string,
overrides?: Partial<AgentSessionConfig>,
options?: { rehydrateFromDisk?: boolean; requireVoiceSpeak?: boolean },
options?: { rehydrateFromDisk?: boolean },
): Promise<ManagedAgent> {
return this.launchAgent(agentId, () => this.reopenAgentSession(agentId, overrides, options));
}
@@ -2139,7 +2132,7 @@ export class AgentManager {
private async reopenAgentSession(
agentId: string,
overrides?: Partial<AgentSessionConfig>,
options?: { rehydrateFromDisk?: boolean; requireVoiceSpeak?: boolean },
options?: { rehydrateFromDisk?: boolean },
): Promise<ManagedAgent> {
this.assertAcceptingAgentRegistrations();
let existing = this.requireSessionAgent(agentId);
@@ -2188,7 +2181,6 @@ export class AgentManager {
existing,
launchConfig,
launchContext,
options,
);
let session: AgentSession | undefined;
@@ -2210,7 +2202,6 @@ export class AgentManager {
? await client.resumeSession(handle, providerLaunchConfig, launchContext)
: await client.createSession(providerLaunchConfig, launchContext);
await this.requireExternalMcpSupport(session, providerLaunchConfig, launchContext);
this.assertVoiceSpeakSupportIfRequired(session, providerLaunchConfig, launchContext, options);
this.assertAcceptingAgentRegistrations();
if (rehydrateFromDisk) {
@@ -2273,7 +2264,6 @@ export class AgentManager {
existing: ActiveManagedAgent,
launchConfig: AgentSessionConfig,
launchContext: AgentLaunchContext,
options?: { requireVoiceSpeak?: boolean },
): AgentSessionConfig {
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
const mcpServers = stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {};
@@ -2283,12 +2273,6 @@ export class AgentManager {
) {
throw this.unsupportedMcpError(providerLaunchConfig, launchContext);
}
this.assertVoiceSpeakSupportIfRequired(
existing.session,
providerLaunchConfig,
launchContext,
options,
);
return providerLaunchConfig;
}
@@ -4955,29 +4939,6 @@ export class AgentManager {
return new Error(`Provider '${config.provider}' does not support MCP servers${source}`);
}
private assertVoiceSpeakSupportIfRequired(
session: AgentSession,
launchConfig: AgentSessionConfig,
launchContext: AgentLaunchContext,
options?: { requireVoiceSpeak?: boolean },
): void {
if (!options?.requireVoiceSpeak) {
return;
}
const hasNativeSpeak = launchContext.paseoTools?.tools.has("speak") === true;
const supportsHttpMcp =
session.capabilities.supportsMcpServers === true &&
session.capabilities.supportsHttpMcpServers !== false;
const hasMcpSpeak =
Boolean(launchConfig.mcpServers?.[PASEO_MCP_SERVER_NAME]) && supportsHttpMcp;
if (hasNativeSpeak || hasMcpSpeak) {
return;
}
throw new Error(
`Voice mode is unavailable for provider '${launchConfig.provider}': the session does not expose Paseo's 'speak' tool (requires native Paseo tool support or HTTP MCP server support).`,
);
}
private async initializeAgentTimelineForRegister(params: {
agentId: string;
now: Date;
@@ -6808,16 +6769,17 @@ export class AgentManager {
purpose: options.purpose,
resolveDefaultModel: options.resolveDefaultModel,
});
const voiceActive = this.hasActiveVoiceTools(agentId);
const paseoToolPolicy = this.paseoToolsEnabled
? this.resolvePaseoToolPolicy(storedConfig.provider)
: { enabled: false };
const generalEnabled = this.paseoToolsEnabled && isPaseoToolPolicyEnabled(paseoToolPolicy);
const launchConfig = this.applyDaemonAppendSystemPrompt(
withRuntimePaseoMcpServer({
config: storedConfig,
agentId,
mcpBaseUrl: generalEnabled || voiceActive ? this.mcpBaseUrl : null,
mcpBaseUrl:
this.paseoToolsEnabled && isPaseoToolPolicyEnabled(paseoToolPolicy)
? this.mcpBaseUrl
: null,
mcpAuthToken: this.mcpAuthToken,
}),
);
@@ -6894,23 +6856,10 @@ export class AgentManager {
...agentIdentityEnv({ agentId, cwd, opening }),
},
};
await this.attachLaunchPaseoTools(context, agentId, client, paseoToolPolicy);
return context;
}
private async attachLaunchPaseoTools(
context: AgentLaunchContext,
agentId: string,
client: AgentClient,
paseoToolPolicy: ProviderPaseoToolsPolicy | undefined,
): Promise<void> {
const voiceActive = this.hasActiveVoiceTools(agentId);
if (voiceActive) {
context.voiceToolsEnabled = true;
}
const generalEnabled = this.paseoToolsEnabled && isPaseoToolPolicyEnabled(paseoToolPolicy);
const useNativeTools =
(generalEnabled || voiceActive) && client.capabilities.supportsNativePaseoTools;
this.paseoToolsEnabled &&
isPaseoToolPolicyEnabled(paseoToolPolicy) &&
client.capabilities.supportsNativePaseoTools;
if (
this.paseoToolCatalogFactory &&
(useNativeTools || this.getPluginTools(agentId).length > 0)
@@ -6919,10 +6868,10 @@ export class AgentManager {
const catalog = await this.paseoToolCatalogFactory({
callerAgentId: agentId,
paseoToolPolicy,
...(useNativeTools && voiceActive && !generalEnabled ? { voiceOnly: true } : {}),
});
if (useNativeTools) context.paseoTools = catalog;
}
return context;
}
private resolveProviderLaunchConfig(
@@ -1,9 +1,7 @@
import { EventEmitter } from "node:events";
import http from "node:http";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { Readable } from "node:stream";
import { existsSync } from "node:fs";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { describe, expect, test } from "vitest";
@@ -19,8 +17,6 @@ import pino from "pino";
import { withTimeout } from "../../utils/promise-timeout.js";
import { hashDaemonPassword } from "../auth.js";
import { createPaseoDaemon, type PaseoDaemonConfig } from "../bootstrap.js";
import type { SpeechService } from "../speech/speech-runtime.js";
import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
import type {
AgentClient,
@@ -1192,278 +1188,3 @@ describe("agent MCP protocol negotiation", () => {
}
}, 30_000);
});
describe("voice-only speak MCP delivery", () => {
function createFakeVoiceSpeechService(spokenTexts: string[]): SpeechService {
const ready = {
enabled: true,
available: true,
retryable: false,
reasonCode: "ready" as const,
message: "Ready",
missingModelIds: [],
};
return {
resolveStt: () => ({
id: "local",
createSession: () => {
const session = new EventEmitter();
return Object.assign(session, {
requiredSampleRate: 16000,
async connect() {},
appendPcm16() {},
commit() {},
clear() {},
close() {},
});
},
}),
resolveSttLanguage: () => "en",
resolveTts: () => ({
async synthesizeSpeech(text: string) {
spokenTexts.push(text);
return { stream: Readable.from([Buffer.from("pcm")]), format: "pcm;rate=24000" };
},
}),
resolveTurnDetection: () => ({
id: "local",
createSession: () => {
const session = new EventEmitter();
return Object.assign(session, {
requiredSampleRate: 16000,
async connect() {},
appendPcm16() {},
flush() {},
reset() {},
close() {},
});
},
}),
resolveDictationStt: () => null,
resolveDictationSttLanguage: () => "en",
getReadiness: () => ({
voiceFeature: ready,
realtimeVoice: ready,
dictation: ready,
localModels: [],
}),
onReadinessChange: () => () => {},
reconfigure: () => {},
listLocalModels: async () => [],
downloadLocalModel: () => {},
deleteLocalModel: async () => {},
start: () => {},
stop: async () => {},
};
}
async function listMcpToolsAndCallSpeak(
mcpUrl: string,
authToken: string | null,
text?: string,
): Promise<{ toolNames: string[]; speakResult?: unknown }> {
const client = new StandardMcpClient({ name: "voice-mcp-e2e", version: "0.0.0" });
await client.connect(
new StandardMcpHttpTransport(new URL(mcpUrl), {
requestInit: authToken ? { headers: { Authorization: `Bearer ${authToken}` } } : undefined,
}),
);
try {
const tools = await client.listTools();
const toolNames = tools.tools.map((tool) => tool.name);
let speakResult: unknown;
if (text !== undefined) {
speakResult = await client.callTool({ name: "speak", arguments: { text } });
}
return { toolNames, speakResult };
} finally {
await client.close();
}
}
class VoiceRecordingAgentClient implements AgentClient {
readonly provider: AgentClient["provider"];
readonly capabilities: AgentClient["capabilities"];
constructor(
private readonly inner: AgentClient,
readonly launches: AgentSessionConfig[],
supportsMcpServers: boolean,
) {
this.provider = inner.provider;
this.capabilities = {
...inner.capabilities,
supportsMcpServers,
supportsNativePaseoTools: false,
};
}
private wrapSession(session: AgentSession): AgentSession {
return Object.assign(Object.create(Object.getPrototypeOf(session)), session, {
capabilities: this.capabilities,
}) as AgentSession;
}
async createSession(
...args: Parameters<AgentClient["createSession"]>
): ReturnType<AgentClient["createSession"]> {
this.launches.push(args[0]);
return this.wrapSession(await this.inner.createSession(...args));
}
async resumeSession(
...args: Parameters<AgentClient["resumeSession"]>
): ReturnType<AgentClient["resumeSession"]> {
this.launches.push({
provider: this.provider,
cwd: args[1]?.cwd ?? String(args[0].metadata?.cwd ?? ""),
...args[1],
});
return this.wrapSession(await this.inner.resumeSession(...args));
}
fetchCatalog(
...args: Parameters<AgentClient["fetchCatalog"]>
): ReturnType<AgentClient["fetchCatalog"]> {
return this.inner.fetchCatalog(...args);
}
isAvailable(): Promise<boolean> {
return this.inner.isAvailable();
}
}
test.each([
{
name: "default config (mcp.injectIntoAgents=false, mcp.enabled=true)",
mcpEnabled: true,
mcpInjectIntoAgents: false,
providerOverrides: undefined,
},
{
name: "mcp.enabled=false on loopback",
mcpEnabled: false,
mcpInjectIntoAgents: false,
providerOverrides: undefined,
},
{
name: "per-provider paseoTools.enabled=false",
mcpEnabled: true,
mcpInjectIntoAgents: true,
providerOverrides: { claude: { paseoTools: { enabled: false } } },
},
])(
"delivers only speak on voice enable under $name and rejects unsupported providers",
async ({ mcpEnabled, mcpInjectIntoAgents, providerOverrides }) => {
const paseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-voice-home-"));
const staticDir = await mkdtemp(path.join(os.tmpdir(), "paseo-voice-static-"));
const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-voice-cwd-"));
const port = await getAvailablePort();
const spokenTexts: string[] = [];
const claudeLaunches: AgentSessionConfig[] = [];
const codexLaunches: AgentSessionConfig[] = [];
const baseClients = createTestAgentClients();
const claudeBase = baseClients.claude!;
const codexBase = baseClients.codex!;
const daemon = await createPaseoDaemon(
{
listen: `127.0.0.1:${port}`,
paseoHome,
corsAllowedOrigins: [],
hostnames: true,
mcpEnabled,
mcpInjectIntoAgents,
providerOverrides,
staticDir,
mcpDebug: false,
agentClients: {
...baseClients,
claude: new VoiceRecordingAgentClient(claudeBase, claudeLaunches, true),
codex: new VoiceRecordingAgentClient(codexBase, codexLaunches, false),
},
agentStoragePath: path.join(paseoHome, "agents"),
},
pino({ level: "silent" }),
{ speechService: createFakeVoiceSpeechService(spokenTexts) },
);
await daemon.start();
const wsClient = new DaemonClient({ url: `ws://127.0.0.1:${port}/ws` });
wsClient.on("audio_output", (msg) => {
if (msg.type === "audio_output" && msg.payload.id) {
void wsClient.sendSessionMessage({ type: "audio_played", id: msg.payload.id });
}
});
try {
await wsClient.connect();
// Non-voice agent receives zero Paseo MCP servers.
const claudeAgent = await daemon.agentManager.createAgent(
{
provider: "claude",
cwd: agentCwd,
model: "claude-test-model",
modeId: "bypassPermissions",
},
undefined,
{ workspaceId: undefined },
);
expect(claudeLaunches.at(-1)?.mcpServers?.paseo).toBeUndefined();
// When mcp.enabled=false, non-voice /mcp/agents requests still get 404.
if (!mcpEnabled) {
const nonVoiceRes = await fetch(
`http://127.0.0.1:${port}/mcp/agents?callerAgentId=${claudeAgent.id}`,
{ method: "POST", headers: { "content-type": "application/json" }, body: "{}" },
);
expect(nonVoiceRes.status).toBe(404);
}
// Enabling voice mode injects loopback paseo MCP and exposes ONLY speak.
await wsClient.setVoiceMode(true, claudeAgent.id);
const injected = claudeLaunches.at(-1)?.mcpServers?.paseo;
expect(injected).toBeDefined();
expect(injected?.type).toBe("http");
if (!injected || injected.type !== "http") {
throw new Error("Expected HTTP paseo MCP server");
}
const { toolNames } = await listMcpToolsAndCallSpeak(
injected.url,
daemon.agentManager.getMcpAuthToken(),
"Hello from voice mode",
);
expect(toolNames).toEqual(["speak"]);
expect(spokenTexts).toEqual(["Hello from voice mode"]);
// Disabling voice mode drops paseo MCP on the restored non-voice session.
await wsClient.setVoiceMode(false, claudeAgent.id);
expect(claudeLaunches.at(-1)?.mcpServers?.paseo).toBeUndefined();
// Provider without MCP/native tools rejects set_voice_mode cleanly.
const unsupportedAgent = await daemon.agentManager.createAgent(
{ provider: "codex", cwd: agentCwd },
undefined,
{ workspaceId: undefined },
);
await expect(wsClient.setVoiceMode(true, unsupportedAgent.id)).rejects.toThrow(/speak/i);
if (!mcpEnabled) {
const rejectedRes = await fetch(
`http://127.0.0.1:${port}/mcp/agents?callerAgentId=${unsupportedAgent.id}`,
{ method: "POST", headers: { "content-type": "application/json" }, body: "{}" },
);
expect(rejectedRes.status).toBe(404);
}
} finally {
await wsClient.close();
await daemon.stop();
await rm(paseoHome, { recursive: true, force: true });
await rm(staticDir, { recursive: true, force: true });
await rm(agentCwd, { recursive: true, force: true });
}
},
30_000,
);
});
@@ -189,8 +189,6 @@ export interface AgentCapabilityFlags {
supportsSessionListing?: boolean;
supportsDynamicModes: boolean;
supportsMcpServers: boolean;
/** When false, HTTP MCP servers (such as Paseo's loopback endpoint) are not supported even if stdio MCP works. */
supportsHttpMcpServers?: boolean;
supportsNativePaseoTools?: boolean;
supportsReasoningStream: boolean;
supportsToolInvocations: boolean;
@@ -713,8 +711,6 @@ export interface AgentLaunchContext {
* AgentSessionConfig; providers may adapt it to their native tool surface.
*/
paseoTools?: PaseoToolCatalog;
/** True while Paseo voice mode is active for this session launch (never persisted). */
voiceToolsEnabled?: boolean;
}
export interface AgentCreateSessionOptions {
@@ -8,11 +8,7 @@ import { createTestLogger } from "../../test-utils/test-logger.js";
import { AgentManager } from "./agent-manager.js";
import { validateProviderOptions } from "./provider-options.js";
import { applyClaudeToolPolicy, ClaudeProviderOptionsSchema } from "./providers/claude/options.js";
import {
applyCodexMcpToolApproval,
applyCodexToolPolicy,
CodexProviderOptionsSchema,
} from "./providers/codex/options.js";
import { applyCodexToolPolicy, CodexProviderOptionsSchema } from "./providers/codex/options.js";
import {
buildOpenCodePermissionRules,
OpenCodeProviderOptionsSchema,
@@ -200,52 +196,6 @@ describe("exact MCP preapproval mappings", () => {
});
});
test("Codex speak approval sets tools.speak.approval_mode without restricting enabled_tools", () => {
expect(
applyCodexMcpToolApproval(
{
"mcp_servers.paseo": { url: "http://127.0.0.1/mcp/agents?callerAgentId=a1" },
"mcp_servers.other": { command: "node" },
},
"paseo",
"speak",
),
).toEqual({
"mcp_servers.paseo": {
url: "http://127.0.0.1/mcp/agents?callerAgentId=a1",
tools: { speak: { approval_mode: "approve" } },
},
"mcp_servers.other": { command: "node" },
});
expect(
applyCodexMcpToolApproval(
{
mcp_servers: {
paseo: { url: "http://127.0.0.1/mcp/agents?callerAgentId=a1" },
"my.dotted": { url: "http://127.0.0.1/other" },
},
},
"paseo",
"speak",
),
).toEqual({
mcp_servers: {
paseo: {
url: "http://127.0.0.1/mcp/agents?callerAgentId=a1",
tools: { speak: { approval_mode: "approve" } },
},
"my.dotted": { url: "http://127.0.0.1/other" },
},
});
expect(
applyCodexMcpToolApproval({ "mcp_servers.other": { command: "node" } }, "paseo", "speak"),
).toEqual({
"mcp_servers.other": { command: "node" },
});
});
test("Claude adds the exact MCP identity without replacing deny rules", () => {
expect(
applyClaudeToolPolicy(
@@ -3562,92 +3562,6 @@ describe("ACPAgentSession", () => {
expect(asInternals<ACPSessionInternals>(session).acpMcpServers()).toEqual([]);
});
test("gates HTTP MCP servers and supportsHttpMcpServers on agentCapabilities.mcpCapabilities.http without breaking stdio MCP", async () => {
const newSession = vi.fn().mockResolvedValue({
sessionId: "acp-http-cap-session",
modes: null,
models: null,
configOptions: [],
});
class CapabilityTestSession extends ACPAgentSession {
constructor(
private readonly httpCap: boolean | undefined,
config: AgentSessionConfig,
) {
super(config, {
provider: "test-acp",
logger: createTestLogger(),
defaultCommand: ["test-acp", "serve"],
defaultModes: [],
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: true,
supportsMcpServers: true,
supportsReasoningStream: true,
supportsToolInvocations: true,
},
});
}
protected override async spawnProcess(): Promise<SpawnedACPProcess> {
return {
child: createProbeChildStub(),
connection: {
newSession,
} as unknown as ClientSideConnection,
initialize: {
protocolVersion: PROTOCOL_VERSION,
agentCapabilities:
this.httpCap === undefined ? {} : { mcpCapabilities: { http: this.httpCap } },
},
};
}
}
const mcpServers: AgentSessionConfig["mcpServers"] = {
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
local: { type: "stdio", command: "node", args: ["mcp.js"] },
};
const unsupported = new CapabilityTestSession(false, {
provider: "test-acp",
cwd: "/tmp/paseo-acp-test",
mcpServers,
});
await unsupported.initializeNewSession();
expect(unsupported.capabilities.supportsMcpServers).toBe(true);
expect(unsupported.capabilities.supportsHttpMcpServers).toBe(false);
expect(newSession).toHaveBeenLastCalledWith({
cwd: "/tmp/paseo-acp-test",
mcpServers: [{ name: "local", command: "node", args: ["mcp.js"], env: [] }],
});
const supported = new CapabilityTestSession(true, {
provider: "test-acp",
cwd: "/tmp/paseo-acp-test",
mcpServers,
});
await supported.initializeNewSession();
expect(supported.capabilities.supportsMcpServers).toBe(true);
expect(supported.capabilities.supportsHttpMcpServers).toBe(true);
expect(newSession).toHaveBeenLastCalledWith({
cwd: "/tmp/paseo-acp-test",
mcpServers: [
{
type: "http",
name: "paseo",
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
headers: [],
},
{ name: "local", command: "node", args: ["mcp.js"], env: [] },
],
});
});
test("summarizes JSON-RPC error details without stringifying objects", () => {
const summary = summarizeACPRequestError(
new RequestError(-32603, "Internal error", {
@@ -2014,7 +2014,7 @@ export class ACPAgentClient implements AgentClient {
export class ACPAgentSession implements AgentSession, ACPClient {
readonly provider: string;
private readonly baseCapabilities: AgentCapabilityFlags;
readonly capabilities: AgentCapabilityFlags;
private readonly logger: Logger;
private readonly runtimeSettings?: ProviderRuntimeSettings;
@@ -2111,7 +2111,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
this.interruptGraceMs = options.interruptGraceMs ?? ACP_INTERRUPT_GRACE_MS;
this.interruptKillGraceMs = options.interruptKillGraceMs ?? ACP_INTERRUPT_KILL_GRACE_MS;
this.terminateProcess = options.terminateProcess ?? terminateWithTreeKill;
this.baseCapabilities = { ...options.capabilities };
this.capabilities = options.capabilities;
this.logger = options.logger.child({ module: "agent", provider: options.provider });
this.runtimeSettings = options.runtimeSettings;
this.defaultCommand = options.defaultCommand;
@@ -2149,15 +2149,6 @@ export class ACPAgentSession implements AgentSession, ACPClient {
this.extensionCommandsParser = options.extensionCommandsParser;
}
get capabilities(): AgentCapabilityFlags {
return {
...this.baseCapabilities,
supportsHttpMcpServers:
this.baseCapabilities.supportsMcpServers &&
this.agentCapabilities?.mcpCapabilities?.http !== false,
};
}
get id(): string | null {
return this.sessionId;
}
@@ -3567,14 +3558,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
}
private acpMcpServers(): McpServer[] {
if (!this.baseCapabilities.supportsMcpServers) {
return [];
}
const servers = normalizeMcpServers(this.config.mcpServers);
if (this.agentCapabilities?.mcpCapabilities?.http === false) {
return servers.filter((server) => !("type" in server && server.type === "http"));
}
return servers;
return this.capabilities.supportsMcpServers ? normalizeMcpServers(this.config.mcpServers) : [];
}
private applySessionState(response: SessionStateResponse): void {
@@ -3635,7 +3619,9 @@ export class ACPAgentSession implements AgentSession, ACPClient {
);
}
}
await this.applyConfiguredThinkingOption();
if (this.config.thinkingOptionId && this.config.thinkingOptionId !== this.thinkingOptionId) {
await this.setThinkingOption(this.config.thinkingOptionId);
}
const configuredFeatureValues = this.config.providerOptions ?? {};
for (const featureOption of this.configFeatureOptions) {
if (!Object.prototype.hasOwnProperty.call(configuredFeatureValues, featureOption.id)) {
@@ -3658,41 +3644,6 @@ export class ACPAgentSession implements AgentSession, ACPClient {
this.openOptionsPatch = this.featureDifferences(configuredFeatureValues);
}
private async applyConfiguredThinkingOption(): Promise<void> {
if (this.initialHandle) {
// Restoring the saved mode or model can move the level, and those writes do not record it.
// Live switches keep their own behavior (#10336).
this.thinkingOptionId =
deriveCurrentConfigValue(this.configOptions, "thought_level") ?? this.thinkingOptionId;
}
const requested = this.config.thinkingOptionId;
if (!requested || requested === this.thinkingOptionId) {
return;
}
try {
await this.setThinkingOption(requested);
} catch (error) {
if (!this.initialHandle || this.thinkingOptionWriter || !isACPInvalidParams(error)) {
throw error;
}
const option = findSelectConfigOption({
configOptions: this.configOptions,
category: "thought_level",
});
if (!option || findSelectConfigChoice({ option, value: requested })) {
throw error;
}
this.logger.warn(
{ requested, current: this.thinkingOptionId, model: this.currentModel },
"Saved ACP thinking option is unavailable on resume; keeping the provider's current value",
);
}
}
/**
* A stored feature value is a preference carried over from whichever model the user
* last configured, so the session it lands on may have no such option. Paseo's own
@@ -449,11 +449,7 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
describe("a background subagent", () => {
// Shapes recorded from Claude Code 2.1.x: the launch returns at once with an async result,
// and a child stopped by an interrupt ends on the interrupt placeholder, not an end_turn.
function backgroundLaunch({
toolUseId = TOOL_USE_ID,
agentId = AGENT_ID,
name,
}: { toolUseId?: string; agentId?: string; name?: string } = {}): string[] {
function backgroundLaunch({ toolUseId = TOOL_USE_ID, agentId = AGENT_ID } = {}): string[] {
return [
parentEntry([
{
@@ -462,7 +458,6 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
name: "Agent",
input: {
subagent_type: "general-purpose",
...(name ? { name } : {}),
description: "probe sleeper",
run_in_background: true,
},
@@ -749,94 +744,6 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "completed" });
});
test.each([
{ history: "with the launch result", hasLaunchResult: true, hasStop: false },
{ history: "after a recorded stop", hasLaunchResult: true, hasStop: true },
{ history: "with only the launch sidecar", hasLaunchResult: false, hasStop: false },
])("completes a SendMessage-resumed child $history", async ({ hasLaunchResult, hasStop }) => {
const launch = hasLaunchResult ? backgroundLaunch() : backgroundLaunch().slice(0, 1);
const prior = hasStop
? [
taskNotification({
status: "stopped",
form: "queue-operation",
includeToolUseId: false,
}),
]
: [];
const resumeToolId = "toolu_resume";
const completion = taskNotification({ status: "completed", form: "queue-operation" }).replace(
TOOL_USE_ID,
resumeToolId,
);
writeSession({
parentLines: [
...launch,
...prior,
parentEntry([
{
type: "tool_use",
id: resumeToolId,
name: "SendMessage",
input: { to: AGENT_ID, message: "Continue the task." },
},
]),
completion,
],
meta: hasLaunchResult ? null : JSON.stringify({ toolUseId: TOOL_USE_ID, finished: true }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({
id: TOOL_USE_ID,
status: "completed",
});
});
test("completes a child resumed by name through SendMessage after a recorded stop", async () => {
const name = "probe-sleeper";
const resumeToolId = "toolu_resume";
writeSession({
parentLines: [
...backgroundLaunch({ name }),
taskNotification({ status: "stopped", form: "queue-operation", includeToolUseId: false }),
parentEntry([
{
type: "tool_use",
id: resumeToolId,
name: "SendMessage",
input: { to: name, message: "Continue the task." },
},
]),
JSON.stringify({
type: "user",
message: {
role: "user",
content: [
{
type: "tool_result",
tool_use_id: resumeToolId,
content: [{ type: "text", text: "Message delivered." }],
},
],
},
toolUseResult: { success: true, resumedAgentId: AGENT_ID },
}),
taskNotification({ status: "completed", form: "queue-operation" }).replace(
TOOL_USE_ID,
resumeToolId,
),
taskNotification({ status: "completed" }).replace(TOOL_USE_ID, resumeToolId),
],
meta: null,
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
const descriptors = upserts(await replayDescriptors());
for (const descriptor of descriptors) expect(descriptor.id).toBe(TOOL_USE_ID);
expect(descriptors.at(-1)).toMatchObject({ id: TOOL_USE_ID, status: "completed" });
});
test("honors a later task-only stopped notification after a tool-linked completion", async () => {
writeSession({
parentLines: [
@@ -6193,15 +6193,7 @@ class ClaudeAgentSession implements AgentSession {
private async ingestPersistedSidechains(
history: ClaudeReplayHistory,
): Promise<ClaudeReplayOwnership> {
const sidecarToolCallIdsByTaskId = new Map<string, string>();
for (const { agentId, meta } of history.subagents) {
const toolCallId = meta?.toolUseId?.trim();
if (toolCallId) sidecarToolCallIdsByTaskId.set(agentId, toolCallId);
}
const parentFacts = await readClaudeReplayParentFacts(
history.parentEntries,
sidecarToolCallIdsByTaskId,
);
const parentFacts = await readClaudeReplayParentFacts(history.parentEntries);
// Replay produces the same observations the live task protocol produces, then folds them
// with the same function, so identity and status are derived once for both paths.
@@ -6209,10 +6201,7 @@ class ClaudeAgentSession implements AgentSession {
for (const subagent of history.subagents) {
subagents.push({
...subagent,
parentFacts: await readClaudeReplayParentFacts(
subagent.entries,
sidecarToolCallIdsByTaskId,
),
parentFacts: await readClaudeReplayParentFacts(subagent.entries),
});
}
const subagentReplay = await observeReplaySubagents({
@@ -7094,28 +7083,12 @@ function labelReplayedSubagentCard(
*/
async function readClaudeReplayParentFacts(
entries: Iterable<ClaudeHistoryEntry> | AsyncIterable<ClaudeHistoryEntry>,
sidecarToolCallIdsByTaskId: ReadonlyMap<string, string>,
): Promise<ClaudeReplayParentFacts> {
const toolCalls = new Map<string, { title?: string; description?: string }>();
const linksByAgentId = new Map<string, { toolCallId: string }>();
const resumeTargetsByToolCallId = new Map<string, string>();
const outcomes: Map<string, { status: ProviderSubagentStatus }> = new Map();
const resolveLaunchToolCallId = (taskId: string): string | undefined => {
const sidecarToolCallId = sidecarToolCallIdsByTaskId.get(taskId);
return sidecarToolCallId && toolCalls.has(sidecarToolCallId)
? sidecarToolCallId
: linksByAgentId.get(taskId)?.toolCallId;
};
for await (const entry of entries) {
const notificationOutcomes = readClaudeReplayNotificationOutcomes(
entry,
linksByAgentId,
resumeTargetsByToolCallId,
resolveLaunchToolCallId,
);
for (const notificationOutcome of notificationOutcomes) {
for (const notificationOutcome of readClaudeReplayNotificationOutcomes(entry, linksByAgentId)) {
outcomes.set(notificationOutcome.toolCallId, { status: notificationOutcome.status });
}
const content = toObjectRecord(entry.message)?.content;
@@ -7124,20 +7097,13 @@ async function readClaudeReplayParentFacts(
const block = toObjectRecord(value);
const declaration = readClaudeReplayTaskDeclaration(entry.type, block);
if (declaration) toolCalls.set(declaration.id, declaration.identity);
const resume = readClaudeReplayResume(entry.type, block);
if (resume) resumeTargetsByToolCallId.set(resume.id, resume.target);
if (
entry.type !== "user" ||
block?.type !== "tool_result" ||
typeof block.tool_use_id !== "string"
)
continue;
const result = toObjectRecord(entry.toolUseResult);
const resumedTaskId = readClaudeReplayResumedTaskId(block, result);
if (resumedTaskId && resumeTargetsByToolCallId.has(block.tool_use_id)) {
resumeTargetsByToolCallId.set(block.tool_use_id, resumedTaskId);
}
if (result?.status !== "async_launched")
if (toObjectRecord(entry.toolUseResult)?.status !== "async_launched")
outcomes.set(block.tool_use_id, {
status: block.is_error === true ? "failed" : "completed",
});
@@ -7159,8 +7125,6 @@ async function readClaudeReplayParentFacts(
function* readClaudeReplayNotificationOutcomes(
entry: ClaudeHistoryEntry,
linksByAgentId: ReadonlyMap<string, { toolCallId: string }>,
resumeTargetsByToolCallId: ReadonlyMap<string, string>,
resolveLaunchToolCallId: (taskId: string) => string | undefined,
): Generator<{ toolCallId: string; status: ProviderSubagentStatus }> {
const notification = readTaskNotificationOutcomeFromHistoryRecord(entry);
if (!notification) return;
@@ -7168,11 +7132,7 @@ function* readClaudeReplayNotificationOutcomes(
if (!status) return;
if (notification.toolUseId) {
// A resumed child keeps its task ID, but Claude reports its outcome under the SendMessage call.
const taskId = resumeTargetsByToolCallId.get(notification.toolUseId);
const launchToolCallId =
taskId && taskId === notification.taskIds[0] ? resolveLaunchToolCallId(taskId) : undefined;
yield { toolCallId: launchToolCallId ?? notification.toolUseId, status };
yield { toolCallId: notification.toolUseId, status };
return;
}
// Stopped tasks can omit tool-use-id; their launch results already link the native IDs.
@@ -7182,30 +7142,6 @@ function* readClaudeReplayNotificationOutcomes(
}
}
function readClaudeReplayResume(
entryType: unknown,
block: Record<string, unknown> | undefined,
): { id: string; target: string } | null {
if (
entryType !== "assistant" ||
block?.type !== "tool_use" ||
block.name !== "SendMessage" ||
typeof block.id !== "string"
) {
return null;
}
const target = readNonEmptyString(toObjectRecord(block.input)?.to);
return target ? { id: block.id, target } : null;
}
function readClaudeReplayResumedTaskId(
block: Record<string, unknown>,
result: Record<string, unknown> | undefined,
): string | null {
if (block.is_error === true || result?.success !== true) return null;
return readNonEmptyString(result.resumedAgentId);
}
function readClaudeReplayTaskDeclaration(
entryType: unknown,
block: Record<string, unknown> | undefined,
@@ -1878,38 +1878,6 @@ describe("Codex app-server provider", () => {
}
});
test("auto-approves paseo speak tool during active voice sessions without restricting enabled_tools", async () => {
const appServer = createFakeCodexAppServer();
const session = await createProviderWithFakeAppServer(appServer).createSession(
createConfig({
modeId: "auto",
mcpServers: {
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
},
}),
{ voiceToolsEnabled: true },
);
try {
await session.startTurn("say hello");
const threadStart = appServer.requests().find((req) => req.method === "thread/start");
const startConfig = (threadStart?.params as { config?: Record<string, unknown> } | undefined)
?.config;
expect(startConfig).toEqual({
"mcp_servers.paseo": {
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
tools: { speak: { approval_mode: "approve" } },
},
});
expect(startConfig).not.toHaveProperty("mcp_servers");
expect(startConfig?.["mcp_servers.paseo"]).not.toHaveProperty("enabled_tools");
expect(startConfig?.["mcp_servers.paseo"]).not.toHaveProperty("default_tools_approval_mode");
appServer.completeTurn();
appServer.assertNoErrors();
} finally {
await session.close();
}
});
test("preapproves only granted tools on the injected Codex MCP server", async () => {
const session = createSession({
modeId: undefined,
@@ -144,12 +144,10 @@ import {
} from "../provider-notices.js";
import type { WorkspaceGitService } from "../../workspace-git-service.js";
import {
applyCodexMcpToolApproval,
applyCodexToolPolicy,
CodexProviderOptionsSchema,
type CodexProviderOptions,
} from "./codex/options.js";
import { PASEO_MCP_SERVER_NAME } from "../runtime-mcp-config.js";
function assertChildWithPipes(
child: ChildProcess,
@@ -355,7 +353,6 @@ interface CodexAppServerAgentDeps {
extends: string;
};
customCodexConfig?: CodexCustomProviderConfig | null;
voiceToolsEnabled?: boolean;
// The CODEX_HOME the session's app-server runs with; prompts and skills are read from it.
codexHome?: string;
_createCodexClient?: (
@@ -6169,10 +6166,7 @@ export class CodexAppServerAgentSession implements AgentSession {
}
}
}
let configured = applyCodexToolPolicy(innerConfig, this.config.toolPolicy);
if (this.deps.voiceToolsEnabled && this.config.mcpServers?.[PASEO_MCP_SERVER_NAME]) {
configured = applyCodexMcpToolApproval(configured, PASEO_MCP_SERVER_NAME, "speak");
}
const configured = applyCodexToolPolicy(innerConfig, this.config.toolPolicy);
return Object.keys(configured).length > 0 ? configured : null;
}
@@ -8429,11 +8423,7 @@ export class CodexAppServerAgentClient implements AgentClient {
null,
this.logger,
async () => spawn(),
{
...this.sessionDeps(launchContext?.env),
environment,
...(launchContext?.voiceToolsEnabled ? { voiceToolsEnabled: true } : {}),
},
{ ...this.sessionDeps(launchContext?.env), environment },
options?.persistSession === false,
goalsEnabled,
autoReviewEnabled,
@@ -8471,11 +8461,7 @@ export class CodexAppServerAgentClient implements AgentClient {
handle,
this.logger,
async () => spawn(),
{
...this.sessionDeps(launchContext?.env),
environment,
...(launchContext?.voiceToolsEnabled ? { voiceToolsEnabled: true } : {}),
},
{ ...this.sessionDeps(launchContext?.env), environment },
false,
goalsEnabled,
autoReviewEnabled,
@@ -133,49 +133,6 @@ export function applyCodexToolPolicy(
return next;
}
/**
* Auto-approves a single tool on an already-configured Codex MCP server without
* narrowing `enabled_tools` or changing `default_tools_approval_mode`, so other
* tools on the same server keep their existing visibility and approval policy.
*/
export function applyCodexMcpToolApproval(
config: Record<string, unknown>,
server: string,
tool: string,
): Record<string, unknown> {
const approveServerTool = (serverConfig: Record<string, unknown>): Record<string, unknown> => {
const existingTools = readRecord(serverConfig.tools);
let enabledTools: unknown[] | undefined;
if (Array.isArray(serverConfig.enabled_tools)) {
enabledTools = serverConfig.enabled_tools.includes(tool)
? serverConfig.enabled_tools
: [...serverConfig.enabled_tools, tool];
}
return {
...serverConfig,
...(enabledTools ? { enabled_tools: enabledTools } : {}),
tools: {
...existingTools,
[tool]: { approval_mode: "approve" },
},
};
};
if ("mcp_servers" in config) {
const mcpServers = readRecord(config.mcp_servers);
if (!(server in mcpServers)) return config;
mcpServers[server] = approveServerTool(readRecord(mcpServers[server]));
return { ...config, mcp_servers: mcpServers };
}
const key = `${MCP_SERVERS_PREFIX}${server}`;
if (!(key in config)) return config;
return {
...config,
[key]: approveServerTool(readRecord(config[key])),
};
}
function readRecord(value: unknown): Record<string, unknown> {
return value != null && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
}
@@ -1343,6 +1343,7 @@ export class PiRpcAgentSession implements AgentSession {
if (this.closed) throw new Error("Pi session is closed");
if (this.activeTurnId !== turnId) return { turnId };
this.activeNoTurnPromptText = payload.text;
const shouldProbeForNoTurnPrompt = this.parseSlashCommandInput(payload.text) !== null;
void (async () => {
try {
@@ -1368,11 +1369,7 @@ export class PiRpcAgentSession implements AgentSession {
await this.completeNoTurnPrompt(turnId);
return;
}
// Pi can acknowledge a prompt as handled even when the extension starts a run.
if (
agentInvoked === undefined &&
(ack.handledByExtension || this.parseSlashCommandInput(payload.text) !== null)
) {
if (agentInvoked === undefined && shouldProbeForNoTurnPrompt) {
await this.completePromptIfHandledWithoutTurn(turnId);
}
} catch (error) {
@@ -4,11 +4,9 @@ import path from "node:path";
import type { ChildProcessWithoutNullStreams } from "node:child_process";
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { setImmediate as waitForImmediate } from "node:timers/promises";
import pino from "pino";
import { describe, expect, onTestFinished, test, vi } from "vitest";
import { describe, expect, test, vi } from "vitest";
import { PiRpcAgentClient } from "./agent.js";
import { PiCliRuntime } from "./cli-runtime.js";
import type { PiRuntimeLaunch } from "./runtime.js";
@@ -497,97 +495,6 @@ describe("PiCliRuntime", () => {
expect(command.images).toBeUndefined();
});
test.each([
{ disposition: "started", agentInvoked: true },
{ disposition: "queued", agentInvoked: true },
])(
"maps a $disposition prompt disposition to agentInvoked $agentInvoked",
async ({ disposition, agentInvoked }) => {
const child = createPiChild();
replyToCommands(child, (command) => (command.type === "prompt" ? { disposition } : {}));
const session = await createRuntime(child).startSession({ cwd: "/workspace/project" });
await expect(session.prompt("summarize README.md")).resolves.toMatchObject({ agentInvoked });
},
);
test("preserves an explicit agentInvoked result in a prompt response", async () => {
const child = createPiChild();
replyToCommands(child, () => ({ disposition: "started", agentInvoked: false }));
const session = await createRuntime(child).startSession({ cwd: "/workspace/project" });
await expect(session.prompt("hello")).resolves.toEqual({
requestId: expect.any(String),
agentInvoked: false,
});
});
test("completes when an input extension handles a prompt without a model run", async () => {
const child = createPiChild();
replyToCommands(child, (command) => {
if (command.type === "prompt") {
const notification = {
type: "extension_ui_request",
id: "handled",
method: "notify",
message: "Handled by extension",
};
child.stdout.write(`${JSON.stringify(notification)}\n`);
return { disposition: "handled" };
}
return { sessionId: "pi-session-1", isStreaming: false };
});
const client = new PiRpcAgentClient({
logger: pino({ level: "silent" }),
runtime: createRuntime(child),
});
const session = await client.createSession({ provider: "pi", cwd: "/workspace/project" });
onTestFinished(() => session.close());
await expect(session.run("hello")).resolves.toMatchObject({
timeline: expect.arrayContaining([
expect.objectContaining({ type: "notification", message: "Handled by extension" }),
]),
});
});
test("waits for the reply when a handled slash command starts a model run", async () => {
const child = createPiChild();
let isStreaming = false;
replyToCommands(child, (command) => {
if (command.type === "prompt") {
isStreaming = true;
return { disposition: "handled" };
}
return { sessionId: "pi-session-1", isStreaming };
});
const client = new PiRpcAgentClient({
logger: pino({ level: "silent" }),
runtime: createRuntime(child),
});
const session = await client.createSession({ provider: "pi", cwd: "/workspace/project" });
onTestFinished(() => session.close());
const reply = session.run("/ask hello");
// Pi acknowledges the command while its model run is starting, before agent_start.
await waitForImmediate();
await waitForImmediate();
child.stdout.write(`${JSON.stringify({ type: "agent_start" })}\n`);
const message = { role: "assistant", content: [{ type: "text", text: "Hello" }] };
const update = {
type: "message_update",
message,
assistantMessageEvent: { type: "text_delta", delta: "Hello" },
};
child.stdout.write(`${JSON.stringify(update)}\n`);
child.stdout.write(
`${JSON.stringify({ type: "agent_end", messages: [message], willRetry: false })}\n`,
);
child.stdout.write(`${JSON.stringify({ type: "agent_settled" })}\n`);
await expect(reply).resolves.toMatchObject({ finalText: "Hello" });
});
test("sends the clear_queue RPC frame", async () => {
const child = createPiChild();
replyToCommands(child, () => ({}));
@@ -137,16 +137,10 @@ class PiCliRuntimeSession implements PiRuntimeSession {
});
const data = await promise;
if (typeof data === "object" && data !== null && !Array.isArray(data)) {
const { agentInvoked, disposition } = data as Record<string, unknown>;
const { agentInvoked } = data as Record<string, unknown>;
if (typeof agentInvoked === "boolean") {
return { requestId, agentInvoked };
}
if (disposition === "handled") {
return { requestId, handledByExtension: true };
}
if (disposition === "started" || disposition === "queued") {
return { requestId, agentInvoked: true };
}
}
return { requestId };
}
@@ -5,10 +5,13 @@ export interface PiImageContent {
data: string;
mimeType: string;
}
export interface PiPromptAck {
agentInvoked?: boolean;
}
export interface PiPromptAck {
requestId?: string;
agentInvoked?: boolean;
handledByExtension?: true;
}
export interface PiTextContent {
+26 -41
View File
@@ -102,7 +102,7 @@ import { formatAttachmentContentDisposition } from "./file-download/content-disp
import type { OpenAiSpeechProviderConfig } from "./speech/providers/openai/config.js";
import type { LocalSpeechProviderConfig } from "./speech/providers/local/config.js";
import type { RequestedSpeechProviders } from "./speech/speech-types.js";
import { createSpeechService, type SpeechService } from "./speech/speech-runtime.js";
import { createSpeechService } from "./speech/speech-runtime.js";
import { createSpeechSettingsOwner } from "./speech/speech-settings.js";
import { AgentManager } from "./agent/agent-manager.js";
import { AgentStorage } from "./agent/agent-storage.js";
@@ -133,7 +133,7 @@ import {
type ResolvedDaemonSettings,
type CliConfigOverrides,
} from "./config.js";
import { isPaseoToolPolicyEnabled, resolvePaseoToolPolicy } from "./agent/paseo-tool-policy.js";
import { resolvePaseoToolPolicy } from "./agent/paseo-tool-policy.js";
import { BrowserToolsBroker } from "./browser-tools/broker.js";
import { DaemonConfigBrowserToolsPolicy } from "./browser-tools/policy.js";
import { WorkspaceGitServiceImpl } from "./workspace-git-service.js";
@@ -441,7 +441,6 @@ export interface PaseoDaemon {
export interface PaseoDaemonDependencies {
builtinPlugins?: BuiltinPluginLoader;
lazyTerminalWorker?: boolean;
speechService?: SpeechService;
getTailscaleNetwork?: () => TailscaleNetwork;
hubRelationshipRemote?: HubRelationshipRemote;
hubRelationshipClock?: HubRelationshipClock;
@@ -587,13 +586,11 @@ export async function createPaseoDaemon(
const elapsed = () => `${(performance.now() - bootstrapStart).toFixed(0)}ms`;
const daemonVersion = config.daemonVersion ?? resolveDaemonVersion(import.meta.url);
const initialMutableConfig = createInitialMutableDaemonConfig(config);
const speechService =
dependencies.speechService ??
createSpeechService({
logger,
openaiConfig: config.openai,
speechConfig: config.speech,
});
const speechService = createSpeechService({
logger,
openaiConfig: config.openai,
speechConfig: config.speech,
});
logger.info({ elapsed: elapsed() }, "Speech service created");
const daemonConfigStore = new DaemonConfigStore(config.paseoHome, initialMutableConfig, logger, {
relayEnabledMutable: config.relayEnabledMutable ?? true,
@@ -996,8 +993,6 @@ export async function createPaseoDaemon(
const git = daemonConfigStore.get().git;
if (git) configureGitProcessPolicy(git);
});
const hasActiveVoiceTools = (agentId: string): boolean =>
wsServer?.resolveVoiceCallerContext(agentId)?.enableVoiceTools === true;
const initialAgentManagerState = providerSnapshotManager.getAgentManagerProviderState();
const agentManager = new AgentManager({
pluginLifecycle: pluginRuntime,
@@ -1010,7 +1005,6 @@ export async function createPaseoDaemon(
workspaceGitService.onWorkspaceStateMayHaveChanged(cwd);
},
mcpAuthToken: agentMcpAuthToken,
hasActiveVoiceTools,
resolvePaseoToolPolicy: (provider) =>
resolvePaseoToolPolicy(provider, daemonConfigStore.get().providers),
logger,
@@ -1650,6 +1644,7 @@ export async function createPaseoDaemon(
setAgentProviderToolsEnabled(config.mcpEnabled !== false && config.mcpInjectIntoAgents !== false);
let mcpEnabled = config.mcpEnabled ?? true;
let agentMcpBaseUrl: string | null = null;
{
const agentMcpRoute = "/mcp/agents";
@@ -1658,20 +1653,14 @@ export async function createPaseoDaemon(
// 2025-era clients through its stateless legacy fallback. No per-session
// state is retained between requests, matching the previous
// `sessionIdGenerator: undefined` transport.
const createAgentMcpSession = async (
callerAgentId?: string,
options?: { voiceOnly?: boolean },
) => {
if (callerAgentId && !options?.voiceOnly) {
await agentManager.refreshPluginTools(callerAgentId);
}
const createAgentMcpSession = async (callerAgentId?: string) => {
if (callerAgentId) await agentManager.refreshPluginTools(callerAgentId);
const agentMcpServer = await createAgentMcpServer(
createAgentToolHostDependencies({
callerAgentId,
paseoToolPolicy: callerAgentId
? agentManager.getPaseoToolPolicy(callerAgentId)
: undefined,
voiceOnly: options?.voiceOnly,
}),
);
@@ -1688,17 +1677,7 @@ export async function createPaseoDaemon(
req: express.Request,
res: express.Response,
): Promise<void> => {
const callerAgentIdRaw = req.query.callerAgentId;
let callerAgentId: string | undefined;
if (typeof callerAgentIdRaw === "string") {
callerAgentId = callerAgentIdRaw;
} else if (Array.isArray(callerAgentIdRaw) && typeof callerAgentIdRaw[0] === "string") {
callerAgentId = callerAgentIdRaw[0];
}
const voiceActive = Boolean(callerAgentId && hasActiveVoiceTools(callerAgentId));
const isActiveLoopbackVoiceRequest =
voiceActive && isLoopbackRemoteAddress(req.socket.remoteAddress);
if (!mcpEnabled && !isActiveLoopbackVoiceRequest) {
if (!mcpEnabled) {
res.status(404).json({ error: "Agent MCP endpoint disabled" });
return;
}
@@ -1743,11 +1722,14 @@ export async function createPaseoDaemon(
});
return;
}
const policy = callerAgentId ? agentManager.getPaseoToolPolicy(callerAgentId) : undefined;
const generalPaseoToolsEnabled =
mcpEnabled && agentManager.isPaseoToolsEnabled() && isPaseoToolPolicyEnabled(policy);
const voiceOnly = voiceActive && !generalPaseoToolsEnabled;
const { handler } = await createAgentMcpSession(callerAgentId, { voiceOnly });
const callerAgentIdRaw = req.query.callerAgentId;
let callerAgentId: string | undefined;
if (typeof callerAgentIdRaw === "string") {
callerAgentId = callerAgentIdRaw;
} else if (Array.isArray(callerAgentIdRaw) && typeof callerAgentIdRaw[0] === "string") {
callerAgentId = callerAgentIdRaw[0];
}
const { handler } = await createAgentMcpSession(callerAgentId);
try {
// express.json() already consumed the stream, so hand the parsed body over.
await toNodeHandler(handler)(
@@ -1848,18 +1830,21 @@ export async function createPaseoDaemon(
);
}
const mcpBaseUrl = loopbackAgentEndpoint.getMcpBaseUrl();
agentManager.setMcpBaseUrl(mcpBaseUrl);
agentMcpBaseUrl =
!mcpEnabled || config.mcpInjectIntoAgents === false ? null : mcpBaseUrl;
agentManager.setMcpBaseUrl(agentMcpBaseUrl);
agentManager.setPaseoToolsEnabled(mcpEnabled && config.mcpInjectIntoAgents !== false);
daemonConfigStore.onFieldChange("mcp.enabled", (value) => {
mcpEnabled = value !== false;
const inject = daemonConfigStore.get().mcp.injectIntoAgents !== false;
agentManager.setMcpBaseUrl(mcpEnabled && inject ? mcpBaseUrl : null);
agentManager.setPaseoToolsEnabled(mcpEnabled && inject);
setAgentProviderToolsEnabled(mcpEnabled && inject);
});
daemonConfigStore.onFieldChange("mcp.injectIntoAgents", (value) => {
const inject = value !== false;
agentManager.setPaseoToolsEnabled(mcpEnabled && inject);
setAgentProviderToolsEnabled(mcpEnabled && inject);
agentManager.setMcpBaseUrl(mcpEnabled && value ? mcpBaseUrl : null);
agentManager.setPaseoToolsEnabled(mcpEnabled && value !== false);
setAgentProviderToolsEnabled(mcpEnabled && value !== false);
});
daemonConfigStore.onFieldChange("appendSystemPrompt", (value) => {
agentManager.setAppendSystemPrompt(typeof value === "string" ? value : "");
@@ -1,104 +0,0 @@
// ACP peer that accepts a thinking level on creation but rejects it after load.
const readline = require("node:readline");
const sessionId = "thinking-resume-session";
let model = "startup-model";
let effort = "low";
let mode = "agent";
let loaded = false;
const send = (message) =>
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n");
function select(id, category, currentValue, values) {
return {
id,
name: id,
category,
type: "select",
currentValue,
options: values.map((value) => ({ value, name: value })),
};
}
function configOptions() {
return [
select("mode", "mode", mode, ["agent", "plan"]),
select("model", "model", model, ["startup-model", "second-model"]),
select(
"effort",
"thought_level",
effort,
loaded && model === "second-model"
? ["minimal", "low", "medium", "high", "xhigh"]
: ["low", "high", "max"],
),
];
}
function assistantMessage(text) {
send({
method: "session/update",
params: {
sessionId,
update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
},
});
}
readline.createInterface({ input: process.stdin }).on("line", (line) => {
const { id, method, params } = JSON.parse(line);
if (id === undefined) return;
let result;
switch (method) {
case "initialize":
result = {
protocolVersion: 1,
agentCapabilities: { loadSession: true, sessionCapabilities: { close: {} } },
};
break;
case "session/new":
result = { sessionId, configOptions: configOptions() };
break;
case "session/load":
loaded = true;
model = process.env.ACP_TEST_LOAD_MODEL;
effort = model === "second-model" && !process.env.ACP_TEST_SAVED_MODE ? "high" : "low";
assistantMessage("Response from the saved session");
result = { configOptions: configOptions() };
break;
case "session/set_config_option":
if (params.configId === "model") {
model = params.value;
if (loaded && model === "second-model") effort = "high";
} else if (params.configId === "mode") {
mode = params.value;
if (loaded && mode === process.env.ACP_TEST_SAVED_MODE) effort = "high";
} else if (loaded && params.value === "max") {
send({
id,
error: {
code: -32602,
message: "Invalid params",
data: "This model does not support that thinking level",
},
});
return;
} else {
effort = params.value;
}
result = { configOptions: configOptions() };
break;
case "session/prompt":
assistantMessage("Response from the saved session");
result = { stopReason: "end_turn" };
break;
case "session/close":
result = {};
break;
default:
send({ id, error: { code: -32601, message: "Method not found" } });
return;
}
send({ id, result });
});
@@ -576,114 +576,3 @@ test("bundled goose lists configured providers and switches models across provid
await rm(root, { recursive: true, force: true });
}
}, 60_000);
// Saves a chat with a thinking level the fixture rejects after load, then restarts the daemon.
async function withRestartedThinkingChat(
{ loadModel, savedMode }: { loadModel: string; savedMode?: string },
run: (client: DaemonClient, agentId: string) => Promise<void>,
): Promise<void> {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-acp-thinking-resume-"));
const options = {
paseoHomeRoot: root,
staticDir: path.join(root, "static"),
cleanup: false,
mcpEnabled: false,
pluginsEnabled: false,
providerOverrides: {
"thinking-fixture": {
extends: "acp" as const,
label: "Thinking fixture",
env: {
ACP_TEST_LOAD_MODEL: loadModel,
ACP_TEST_SAVED_MODE: savedMode ?? "",
},
command: [
process.execPath,
path.join(import.meta.dirname, "acp-thinking-resume-fixture.cjs"),
],
},
},
};
try {
const first = await createDaemonTestContext(options);
let agentId: string;
try {
const agent = await first.client.createAgent({
provider: "thinking-fixture",
cwd: root,
model: "second-model",
modeId: savedMode,
thinkingOptionId: "max",
});
agentId = agent.id;
expect(agent.thinkingOptionId).toBe("max");
await first.client.sendMessage(agentId, "Save this conversation");
expect((await first.client.waitForFinish(agentId, 10_000)).status).toBe("idle");
} finally {
await first.cleanup();
}
const restarted = await createDaemonTestContext(options);
try {
await run(restarted.client, agentId);
} finally {
await restarted.cleanup();
}
} finally {
await rm(root, { recursive: true, force: true });
}
}
test.each([
{ scenario: "the saved model loaded", loadModel: "second-model", savedMode: undefined },
{ scenario: "the saved model restored", loadModel: "startup-model", savedMode: undefined },
{ scenario: "the saved mode restored", loadModel: "second-model", savedMode: "plan" },
])(
"reopens an ACP chat with a rejected saved thinking level with $scenario",
async ({ loadModel, savedMode }) => {
await withRestartedThinkingChat({ loadModel, savedMode }, async (client, agentId) => {
const timeline = await client.fetchAgentTimeline(agentId, { limit: 40 });
expect(timeline.entries.map(({ item }) => item)).toContainEqual(
expect.objectContaining({
type: "assistant_message",
text: "Response from the saved session",
}),
);
expect((await client.fetchAgent(agentId))?.agent.runtimeInfo?.thinkingOptionId).toBe("high");
// Interactive writes still surface a provider rejection.
await expect(client.setAgentThinkingOption(agentId, "max")).rejects.toThrow("Invalid params");
await client.setAgentThinkingOption(agentId, "low");
expect((await client.fetchAgent(agentId))?.agent).toMatchObject({
thinkingOptionId: "low",
runtimeInfo: { thinkingOptionId: "low" },
});
});
},
60_000,
);
// The provider answers both live switches below with `high`. Publishing that value on an open
// chat belongs to #10336, so the picker keeps the level it had.
test("keeps the thinking level of a reopened ACP chat through live mode and model switches", async () => {
await withRestartedThinkingChat(
{ loadModel: "second-model", savedMode: "plan" },
async (client, agentId) => {
await client.setAgentThinkingOption(agentId, "low");
await client.setAgentMode(agentId, "agent");
await client.setAgentMode(agentId, "plan");
expect((await client.fetchAgent(agentId))?.agent).toMatchObject({
thinkingOptionId: "low",
runtimeInfo: { modeId: "plan", thinkingOptionId: "low" },
});
await client.setAgentModel(agentId, "startup-model");
await client.setAgentModel(agentId, "second-model");
expect((await client.fetchAgent(agentId))?.agent).toMatchObject({
thinkingOptionId: "low",
runtimeInfo: { model: "second-model", thinkingOptionId: "low" },
});
},
);
}, 60_000);
+2 -2
View File
@@ -1447,8 +1447,8 @@ export class Session {
agentStorage: this.agentStorage,
logger: this.sessionLogger,
}),
reloadAgentSession: (agentId, overrides, reloadOptions) =>
this.agentManager.reloadAgentSession(agentId, overrides, reloadOptions),
reloadAgentSession: (agentId, overrides) =>
this.agentManager.reloadAgentSession(agentId, overrides),
sendSpokenInput: async (agentId, text) => {
await this.handleSendAgentMessage(
agentId,
@@ -325,94 +325,4 @@ describe("VoiceSession streaming transcription", () => {
await voiceSession.cleanup();
});
test("rejects set_voice_mode and cleans up voice bridge when speak capability check fails", async () => {
const events: string[] = [];
const host = createFakeHost();
const reloadOptions: Array<unknown> = [];
host.reloadAgentSession = async (_agentId, _overrides, options) => {
reloadOptions.push(options);
throw new Error(
"Voice mode is unavailable for provider 'pi': the session does not expose Paseo's 'speak' tool",
);
};
const voiceSession = new VoiceSession({
host,
logger: pino({ level: "silent" }),
sessionId: "voice-capability-reject-test",
sttLanguage: "en",
tts: null,
stt: { id: "local", createSession: vi.fn(() => new FakeVoiceSttSession()) },
voice: {
turnDetection: {
id: "local",
createSession: vi.fn(() => new FakeVoiceTurnDetectionSession()),
},
},
voiceBridge: {
registerVoiceSpeakHandler: (id) => events.push(`register-speak:${id}`),
unregisterVoiceSpeakHandler: (id) => events.push(`unregister-speak:${id}`),
registerVoiceCallerContext: (id) => events.push(`register-ctx:${id}`),
unregisterVoiceCallerContext: (id) => events.push(`unregister-ctx:${id}`),
},
});
await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID, "req-voice-1");
expect(reloadOptions).toEqual([{ requireVoiceSpeak: true }]);
expect(events).toEqual([
`register-speak:${VOICE_AGENT_ID}`,
`register-ctx:${VOICE_AGENT_ID}`,
`unregister-speak:${VOICE_AGENT_ID}`,
`unregister-ctx:${VOICE_AGENT_ID}`,
]);
expect(voiceSession.isActiveForAgent(VOICE_AGENT_ID)).toBe(false);
expect(host.emitted).toContainEqual({
type: "set_voice_mode_response",
payload: {
requestId: "req-voice-1",
enabled: false,
agentId: null,
accepted: false,
error:
"Voice mode is unavailable for provider 'pi': the session does not expose Paseo's 'speak' tool",
},
});
});
test("unregisters voice bridge before reloading when disabling voice mode", async () => {
const order: string[] = [];
const host = createFakeHost();
host.reloadAgentSession = async (agentId) => {
order.push(`reload:${agentId}`);
return { id: agentId } as unknown as ManagedAgent;
};
const voiceSession = new VoiceSession({
host,
logger: pino({ level: "silent" }),
sessionId: "voice-disable-order-test",
sttLanguage: "en",
tts: null,
stt: { id: "local", createSession: vi.fn(() => new FakeVoiceSttSession()) },
voice: {
turnDetection: {
id: "local",
createSession: vi.fn(() => new FakeVoiceTurnDetectionSession()),
},
},
voiceBridge: {
registerVoiceSpeakHandler: () => order.push("register-speak"),
unregisterVoiceSpeakHandler: () => order.push("unregister-speak"),
registerVoiceCallerContext: () => order.push("register-ctx"),
unregisterVoiceCallerContext: () => order.push("unregister-ctx"),
},
});
await voiceSession.handleSetVoiceMode(true, VOICE_AGENT_ID, "req-on");
order.length = 0;
await voiceSession.handleSetVoiceMode(false, VOICE_AGENT_ID, "req-off");
expect(order).toEqual(["unregister-speak", "unregister-ctx", `reload:${VOICE_AGENT_ID}`]);
});
});
@@ -125,7 +125,6 @@ export interface VoiceSessionHost {
reloadAgentSession(
agentId: string,
overrides: Partial<AgentSessionConfig>,
options?: { requireVoiceSpeak?: boolean },
): Promise<ManagedAgent>;
sendSpokenInput(agentId: string, text: string): Promise<void>;
interruptAgentIfRunning(agentId: string): Promise<void>;
@@ -514,9 +513,7 @@ export class VoiceSession {
{ agentId, elapsedMs: Date.now() - startedAt },
"enableVoiceModeForAgent.reloadAgentSession.start",
);
const refreshed = await this.host.reloadAgentSession(agentId, refreshOverrides, {
requireVoiceSpeak: true,
});
const refreshed = await this.host.reloadAgentSession(agentId, refreshOverrides);
this.sessionLogger.info(
{ agentId, refreshedAgentId: refreshed.id, elapsedMs: Date.now() - startedAt },
"enableVoiceModeForAgent.reloadAgentSession.done",
@@ -539,9 +536,6 @@ export class VoiceSession {
return;
}
this.unregisterVoiceSpeakHandler?.(agentId);
this.unregisterVoiceCallerContext?.(agentId);
if (restoreAgentConfig && this.voiceModeBaseConfig) {
const baseConfig = this.voiceModeBaseConfig;
try {
@@ -556,6 +550,8 @@ export class VoiceSession {
}
}
this.unregisterVoiceSpeakHandler?.(agentId);
this.unregisterVoiceCallerContext?.(agentId);
this.voiceModeBaseConfig = null;
this.voiceModeAgentId = null;
}
@@ -1215,7 +1215,6 @@ describe.skipIf(isPlatform("win32"))("terminal title", () => {
const env = buildTerminalEnvironment({
shell: "/bin/zsh",
env: {},
baseEnv: {
HOME: homeDir,
PATH: `${appDir}:${appDir}/usr/sbin:/usr/local/bin:/usr/bin:/bin`,
+19 -21
View File
@@ -10,7 +10,6 @@ import type {
ProviderMcpServerConfig,
ProviderCatalog,
ProviderToolCallDetail,
ProviderUsage,
} from "@getpaseo/plugin/server/provider";
import type { z } from "zod";
import { MspConnection, commandId, type Notification } from "./connection.js";
@@ -46,16 +45,6 @@ import { Recovery } from "./recovery.js";
import { Questions } from "./questions.js";
import { Commands } from "./commands.js";
function tokenUsage(input: unknown): ProviderUsage {
const { cumulative, usage } = tokenUsageSchema.parse(input);
return {
inputTokens: cumulative.promptTokens,
outputTokens: cumulative.outputTokens,
cachedInputTokens: cumulative.cacheReadTokens ?? usage?.cachedTokens,
totalCostUsd: cumulative.cost?.partial === false ? cumulative.cost.usd : undefined,
};
}
interface SessionOptions {
serveArgs: string[];
id: string;
@@ -88,7 +77,6 @@ export class Session {
private opening = true;
private closing = false;
private systemPromptPending = true;
private lastUsage: ProviderUsage = {};
private interruptCompletion: {
turnId: string;
resolve(): void;
@@ -476,23 +464,33 @@ export class Session {
case "turn/completed":
this.completeTurn(notification.params);
break;
case "session/tokenUsage":
this.updateUsage(tokenUsage(notification.params));
case "session/tokenUsage": {
const params = tokenUsageSchema.parse(notification.params);
this.options.emit({
type: "session.usage",
sessionId: this.options.id,
usage: {
inputTokens: params.cumulative.promptTokens,
outputTokens: params.cumulative.outputTokens,
cachedInputTokens: params.usage?.cachedTokens,
},
});
break;
}
case "session/contextUsage": {
const params = contextUsageSchema.parse(notification.params);
this.updateUsage({
contextWindowUsedTokens: params.usedTokens,
contextWindowMaxTokens: params.windowTokens,
this.options.emit({
type: "session.usage",
sessionId: this.options.id,
usage: {
contextWindowUsedTokens: params.usedTokens,
contextWindowMaxTokens: params.windowTokens,
},
});
break;
}
}
}
private updateUsage(update: ProviderUsage): void {
this.lastUsage = { ...this.lastUsage, ...update };
this.options.emit({ type: "session.usage", sessionId: this.options.id, usage: this.lastUsage });
}
private startTurn(input: unknown): void {
const params = turnSchema.parse(input);
if (
+1 -6
View File
@@ -192,12 +192,7 @@ export const toolArgsSchema = z.object({
url: z.string().default(""),
});
export const tokenUsageSchema = z.object({
cumulative: z.object({
promptTokens: z.number(),
outputTokens: z.number(),
cacheReadTokens: z.number().optional(),
cost: z.object({ usd: z.number().nonnegative(), partial: z.boolean() }).optional(),
}),
cumulative: z.object({ promptTokens: z.number(), outputTokens: z.number() }),
usage: z.object({ cachedTokens: z.number().optional() }).optional(),
});
export const contextUsageSchema = z.object({
-16
View File
@@ -343,22 +343,6 @@ function applyWireVariants(message) {
}
}
function parityDelivery(message) {
if (message.method === "session/tokenUsage" && process.env.MUSE_TEST_PRICED_USAGE) {
const context = (usedTokens) => ({
jsonrpc: "2.0",
method: "session/contextUsage",
params: { sessionId: message.params.sessionId, usedTokens, windowTokens: 100000 },
});
message.params.cumulative.cacheReadTokens = 12000;
message.params.cumulative.cost = {
usd: 0.25,
partial: process.env.MUSE_TEST_PRICED_USAGE === "partial",
};
send(context(5000));
send(message);
send(context(7000));
return true;
}
if (process.env.MUSE_TEST_WORKFLOW && message.method === "turn/completed")
send({
jsonrpc: "2.0",
@@ -561,35 +561,6 @@ test("image turn sends a native image and the subsequent text turn succeeds", as
});
expect(turns[1].params.input).toEqual([{ type: "text", text: "hello" }]);
});
test.each(["complete", "partial"])(
"keeps context and token usage together with %s Muse pricing",
async (pricing) => {
const h = await harness("text-reasoning", { MUSE_TEST_PRICED_USAGE: pricing });
await h.open();
await h.prompt();
await h.wait((event) => event.type === "session.turn" && event.state === "completed");
const snapshots = h.events.flatMap((event) =>
event.type === "session.usage" ? [event.usage] : [],
);
const tokens = { inputTokens: 38169, outputTokens: 663, cachedInputTokens: 12000 };
expect(snapshots.slice(-3)).toEqual([
{ contextWindowUsedTokens: 5000, contextWindowMaxTokens: 100000 },
{
...tokens,
totalCostUsd: pricing === "complete" ? 0.25 : undefined,
contextWindowUsedTokens: 5000,
contextWindowMaxTokens: 100000,
},
{
...tokens,
totalCostUsd: pricing === "complete" ? 0.25 : undefined,
contextWindowUsedTokens: 7000,
contextWindowMaxTokens: 100000,
},
]);
},
);
for (const source of ["live", "history", "backfill"]) {
test(`reminder housekeeping emits no timeline items or child sessions from ${source}`, async () => {
const scenario = source === "history" ? "resume-without-cursor" : "text-reasoning";
-13
View File
@@ -449,7 +449,6 @@ paseo hub disconnect # End it
paseo hub deploy # Validate and install .paseo/triggers/*.yml
paseo hub deploy --dry-run # Validate without installing
paseo hub deploy -p <project> # Deploy an existing legacy project bundle
paseo hub run <trigger> [prompt] # Start a manual.run trigger
paseo hub logout # Remove the active stored CLI login
```
@@ -467,18 +466,6 @@ Providers that report zero execution modes (such as Pi) are filtered out by `pas
Setup next asks for the allowed sender identity (GitHub username, Slack member ID, or Discord user ID), validates the trigger against the connected daemon, writes `.paseo/triggers/<provider>-help.yml`, and asks whether to deploy. Replacing an existing starter file requires confirmation while preserving other trigger files. See the [generated starter trigger](/docs/hub/configuration#generated-starter-trigger).
`paseo hub run` starts a trigger that has a `manual.run` event:
```bash
paseo hub run triage
paseo hub run deploy -i environment=staging "ship the hotfix"
RUN_ID=$(paseo hub run triage --prompt-file report.md --quiet)
```
Set declared inputs with `-i name=value`, once per input. A value cannot contain spaces; put free text in the prompt or in `--prompt-file`. Hub receives inputs and prompt as one string, so `${{ paseo.prompt }}` starts with the `name=value` pairs, and pairs at the start of the prompt or prompt file set inputs too. If that text is untrusted, set every declared input with `-i`; Hub rejects a second value. In a terminal, omit the trigger to pick one, and answer for any required input you left out. Non-TTY, `--json`, and `--quiet` runs never prompt.
The command exits `0` when Hub accepts the run. It does not wait for the run to finish; follow it under **Activity** in Hub. In CI, set `PASEO_HUB_URL` and `PASEO_HUB_API_KEY`. The key needs `runs:dispatch`; add `configuration:validate` so `-i` names are checked before the run starts. The sender name is `paseo-cli`; pass `--actor <name>` when the trigger's `filters.from_users` restricts senders. If you don't know whether Hub received a request, retry with the `--delivery-key` from the error so the run starts once. Hub keeps the first request sent with a key, so use a new key when you change anything.
Interactive `paseo hub logout` checks for a daemon connected to the same Hub and asks whether to disconnect it before deleting the login. JSON and non-interactive logouts never prompt or disconnect unless you pass `--disconnect-daemon` (with optional `--force`). If disconnection fails, the login stays intact.
Every Hub command resolves its destination and credentials in order:
-13
View File
@@ -428,7 +428,6 @@ paseo hub disconnect # End it
paseo hub deploy # Validate and install .paseo/triggers/*.yml
paseo hub deploy --dry-run # Validate without installing
paseo hub deploy -p <project> # Deploy an existing legacy project bundle
paseo hub run <trigger> [prompt] # Start a manual.run trigger
paseo hub logout # Remove the active stored CLI login
```
@@ -446,18 +445,6 @@ paseo hub logout # Remove the active stored CLI login
接着设置会询问允许的发送者身份(GitHub 用户名、Slack 成员 ID 或 Discord 用户 ID),对照已连接的 daemon 校验触发器,写入 `.paseo/triggers/<provider>-help.yml` 并询问是否部署。替换已有入门文件需要确认,同时保留其他触发器文件。见[生成的入门触发器](/docs/hub/configuration#generated-starter-trigger)。
`paseo hub run` 启动带有 `manual.run` 事件的触发器:
```bash
paseo hub run triage
paseo hub run deploy -i environment=staging "ship the hotfix"
RUN_ID=$(paseo hub run triage --prompt-file report.md --quiet)
```
用 `-i name=value` 设置声明的输入,每个输入写一次。值不能包含空格;自由文本请放在提示词或 `--prompt-file` 中。Hub 以单个字符串接收输入和提示词,因此 `${{ paseo.prompt }}` 以这些 `name=value` 对开头;提示词或提示词文件开头的 `name=value` 对同样会设置输入。如果这段文本不可信,请用 `-i` 设置每个声明的输入;Hub 会拒绝同一输入的第二个值。在终端中省略触发器名称即可从列表中选择,缺少的必填输入会逐一询问。非 TTY、`--json` 和 `--quiet` 运行不会提示。
Hub 接受运行后命令即以 `0` 退出,不会等待运行结束;请在 Hub 的 **Activity** 中查看进展。在 CI 中设置 `PASEO_HUB_URL` 和 `PASEO_HUB_API_KEY`。密钥需要 `runs:dispatch`;再加上 `configuration:validate`,即可在运行开始前检查 `-i` 名称。发送者名称为 `paseo-cli`;当触发器的 `filters.from_users` 限制发送者时,请传入 `--actor <name>`。如果不确定 Hub 是否收到了请求,请用错误信息中的 `--delivery-key` 重试,这样运行只会启动一次。Hub 保留使用某个键发送的第一个请求,因此修改任何内容时请换用新的键。
交互式 `paseo hub logout` 会检查连接到同一 Hub 的 daemon,并在删除登录前询问是否断开。JSON 和非交互式退出不会提示或断开,除非传入 `--disconnect-daemon`(可配合 `--force`)。如果断开失败,登录凭据会保留。
每个 Hub 命令都按顺序解析目标和凭据:
+15 -9
View File
@@ -110,15 +110,6 @@ Each call replaces any previous secret immediately and shows the new secret only
`POST /api/v1/manual-runs` (`runs:dispatch`) starts a configured `manual.run` trigger. `actor` must match that trigger's `filters.from_users` allowlist (or `*` when omitted).
From a terminal or CI, use [`paseo hub run`](/docs/cli#hub) instead of calling the endpoint yourself:
```bash
paseo hub run manual-task "investigate the failed sync"
paseo hub run deploy -i environment=staging "ship the hotfix"
```
The endpoint accepts this body:
```json
{
"projectSlug": "default",
@@ -148,6 +139,21 @@ On success, Hub returns `200`:
}
```
Example:
```bash
curl --fail-with-body -sS -X POST "$PASEO_HUB_URL/api/v1/manual-runs" \
-H "Authorization: Bearer $PASEO_HUB_API_KEY" \
-H "Content-Type: application/json" \
--data '{
"projectSlug": "default",
"trigger": "manual-task",
"actor": "automation",
"deliveryKey": "manual-task-2026-09-09-001",
"input": "investigate the failed sync"
}'
```
## Daemon enrollment
`POST /api/v1/daemons/enrollment-tokens` (`daemons:enroll`) issues a single-use enrollment token that expires in 10 minutes. No request body is required.
+15 -9
View File
@@ -108,15 +108,6 @@ API 错误返回 RFC 9457 `application/problem+json` 格式并带有 `X-Request-
`POST /api/v1/manual-runs`(`runs:dispatch`)启动一个已配置的 `manual.run` 触发器。`actor` 必须匹配该触发器的 `filters.from_users` 白名单(省略时为 `*`)。
在终端或 CI 中,请使用 [`paseo hub run`](/docs/cli#hub),不必自己调用该端点:
```bash
paseo hub run manual-task "investigate the failed sync"
paseo hub run deploy -i environment=staging "ship the hotfix"
```
该端点接受以下请求体:
```json
{
"projectSlug": "default",
@@ -146,6 +137,21 @@ paseo hub run deploy -i environment=staging "ship the hotfix"
}
```
示例:
```bash
curl --fail-with-body -sS -X POST "$PASEO_HUB_URL/api/v1/manual-runs" \
-H "Authorization: Bearer $PASEO_HUB_API_KEY" \
-H "Content-Type: application/json" \
--data '{
"projectSlug": "default",
"trigger": "manual-task",
"actor": "automation",
"deliveryKey": "manual-task-2026-09-09-001",
"input": "investigate the failed sync"
}'
```
## Daemon 注册 {#daemon-enrollment}
`POST /api/v1/daemons/enrollment-tokens`(`daemons:enroll`)签发一个 10 分钟后过期的一次性注册令牌。不需要请求体。
+1 -1
View File
@@ -28,7 +28,7 @@ Each key under `on` is an event name:
- Provider events (`github.*`, `linear.*`, `slack.mention`, `discord.mention`) accept optional `connection` (integration slug) and `filters`. See [Triggers](/docs/hub/triggers#events) for the full event and filter tables.
- `schedule.tick` requires `recurrence` (`start`, `rule`, `timezone`) and rejects `connection` and `filters`. See [Scheduled triggers](/docs/hub/triggers/schedules).
- `webhook.received` accepts an empty object `{}` and rejects `connection` and `filters`. See [Inbound webhooks](/docs/hub/triggers/webhooks).
- `manual.run` accepts `{}` or `filters.from_users` for runs started with `paseo hub run` or the API. See [Hub public API](/docs/hub/api#manual-run-dispatch).
- `manual.run` accepts `{}` or `filters.from_users` for API dispatch. See [Hub public API](/docs/hub/api#manual-run-dispatch).
One trigger document can list more than one event under `on`. The dashboard visual form edits single-event triggers, and multi-event triggers stay editable in YAML view.
@@ -26,7 +26,7 @@ nav: 触发器 YAML 参考
- Provider 事件(`github.*`、`linear.*`、`slack.mention`、`discord.mention`)接受可选的 `connection`(集成 slug)和 `filters`。完整事件和过滤条件表见[触发器](/docs/hub/triggers#events)。
- `schedule.tick` 要求设置 `recurrence`(`start`、`rule`、`timezone`),并拒绝 `connection` 和 `filters`。参见[定时触发器](/docs/hub/triggers/schedules)。
- `webhook.received` 接受空对象 `{}`,并拒绝 `connection` 和 `filters`。参见[入站 webhook](/docs/hub/triggers/webhooks)。
- `manual.run` 接受 `{}` 或 `filters.from_users`,适用于通过 `paseo hub run` 或 API 发起的运行。参见 [Hub 公开 API](/docs/hub/api#manual-run-dispatch)。
- `manual.run` 接受 `{}` 或用于 API 派发的 `filters.from_users`。参见 [Hub 公开 API](/docs/hub/api#manual-run-dispatch)。
一个触发器文档可以在 `on` 下声明多个事件。控制台的可视化表单编辑单事件触发器,多事件触发器可在 YAML 视图中编辑。
+1 -1
View File
@@ -110,7 +110,7 @@ Hub includes an `executionId` in each prompt. On a continuing agent, pass that `
| `discord.mention` | The bot is mentioned in a Discord channel or thread. |
| `schedule.tick` | A recurring calendar schedule fires in your timezone. |
| `webhook.received` | An authenticated HTTP `POST` arrives at the trigger's webhook endpoint. |
| `manual.run` | A run is started with `paseo hub run` or the Hub API. |
| `manual.run` | A run is dispatched through the Hub API. |
Read the guide for each trigger source:
+18 -18
View File
@@ -91,24 +91,24 @@ Hub 会在每段提示词中附带 `executionId`。在持续运行的 Agent 上
## 事件 {#events}
| `on` | 触发时机 |
| -------------------------------------- | ------------------------------------------------ |
| `github.issue_created` | 创建了 GitHub issue。 |
| `github.pull_request_created` | 创建了 GitHub Pull Request。 |
| `github.pull_request_ready_for_review` | 草稿 Pull Request 被标记为可审查。 |
| `github.pull_request_synchronized` | 向打开的 Pull Request 推送了新提交。 |
| `github.issue_comment_created` | GitHub issue 上发表了评论。 |
| `github.pull_request_comment_created` | Pull Request 上发表了对话评论。 |
| `github.issue_label_added` | 为 GitHub issue 添加了标签。 |
| `github.pull_request_label_added` | 为 Pull Request 添加了标签。 |
| `linear.comment_created` | Linear issue 上发表了评论。 |
| `linear.issue_assigned` | Linear issue 被分配或重新分配。 |
| `linear.issue_entered_scope` | Linear issue 在范围内创建或进入范围。 |
| `slack.mention` | 机器人在 Slack 频道或讨论串中被提及。 |
| `discord.mention` | 机器人在 Discord 频道或讨论串中被提及。 |
| `schedule.tick` | 按你的时区触发周期性日历定时任务。 |
| `webhook.received` | 触发器的 webhook 端点收到已认证的 HTTP `POST`。 |
| `manual.run` | 通过 `paseo hub run` 或 Hub API 发起了一次运行。 |
| `on` | 触发时机 |
| -------------------------------------- | ----------------------------------------------- |
| `github.issue_created` | 创建了 GitHub issue。 |
| `github.pull_request_created` | 创建了 GitHub Pull Request。 |
| `github.pull_request_ready_for_review` | 草稿 Pull Request 被标记为可审查。 |
| `github.pull_request_synchronized` | 向打开的 Pull Request 推送了新提交。 |
| `github.issue_comment_created` | GitHub issue 上发表了评论。 |
| `github.pull_request_comment_created` | Pull Request 上发表了对话评论。 |
| `github.issue_label_added` | 为 GitHub issue 添加了标签。 |
| `github.pull_request_label_added` | 为 Pull Request 添加了标签。 |
| `linear.comment_created` | Linear issue 上发表了评论。 |
| `linear.issue_assigned` | Linear issue 被分配或重新分配。 |
| `linear.issue_entered_scope` | Linear issue 在范围内创建或进入范围。 |
| `slack.mention` | 机器人在 Slack 频道或讨论串中被提及。 |
| `discord.mention` | 机器人在 Discord 频道或讨论串中被提及。 |
| `schedule.tick` | 按你的时区触发周期性日历定时任务。 |
| `webhook.received` | 触发器的 webhook 端点收到已认证的 HTTP `POST`。 |
| `manual.run` | 通过 Hub API 发起了一次运行。 |
各触发器来源的详细指南:
+38 -1
View File
@@ -1,14 +1,17 @@
import { spawn } from "node:child_process";
import { createReadStream, createWriteStream } from "node:fs";
import { cp, mkdir, readdir, rm, stat } from "node:fs/promises";
import path from "node:path";
import { pipeline } from "node:stream/promises";
import { fileURLToPath } from "node:url";
import { precompressAssets } from "./precompress-assets.mjs";
import { constants as zlibConstants, createBrotliCompress, createGzip } from "node:zlib";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(__dirname, "..");
const APP_DIR = path.join(REPO_ROOT, "packages", "app");
const SOURCE_DIST = path.join(APP_DIR, "dist");
const TARGET_DIST = path.join(REPO_ROOT, "packages", "server", "dist", "server", "web-ui");
const COMPRESS_EXTENSIONS = new Set([".html", ".js", ".css", ".json", ".svg", ".map"]);
function fmtMiB(bytes) {
return `${(bytes / 1024 / 1024).toFixed(2)} MiB`;
@@ -50,6 +53,40 @@ async function copyAssets() {
await cp(SOURCE_DIST, TARGET_DIST, { recursive: true, force: true });
}
async function compressFile(filePath) {
const brotliPath = `${filePath}.br`;
const gzipPath = `${filePath}.gz`;
await Promise.all([
pipeline(
createReadStream(filePath),
createBrotliCompress({
params: {
[zlibConstants.BROTLI_PARAM_QUALITY]: zlibConstants.BROTLI_MAX_QUALITY,
},
}),
createWriteStream(brotliPath),
),
pipeline(createReadStream(filePath), createGzip(), createWriteStream(gzipPath)),
]);
}
async function precompressAssets(dir) {
const entries = await readdir(dir, { withFileTypes: true });
const files = entries.filter((entry) => entry.isFile());
const dirs = entries.filter((entry) => entry.isDirectory());
for (const file of files) {
const filePath = path.join(dir, file.name);
if (COMPRESS_EXTENSIONS.has(path.extname(file.name).toLowerCase())) {
await compressFile(filePath);
}
}
for (const subdir of dirs) {
await precompressAssets(path.join(dir, subdir.name));
}
}
async function measureBundle(dir) {
let raw = 0;
let gzip = 0;
-55
View File
@@ -1,55 +0,0 @@
import { createReadStream, createWriteStream } from "node:fs";
import { readdir } from "node:fs/promises";
import path from "node:path";
import { pipeline } from "node:stream/promises";
import { constants as zlibConstants, createBrotliCompress, createGzip } from "node:zlib";
import { isMainModule } from "./is-main-module.mjs";
// The daemon web server (packages/server/src/server/web-ui.ts) serves `<asset>.br` / `<asset>.gz`
// beside an asset when the client sends Accept-Encoding. Both the standalone daemon web UI and the
// desktop app's app-dist run this over the web export before it is packaged.
export const COMPRESS_EXTENSIONS = new Set([".html", ".js", ".css", ".json", ".svg", ".map"]);
export async function compressFile(filePath, { brotliQuality } = {}) {
await Promise.all([
pipeline(
createReadStream(filePath),
createBrotliCompress({
params: {
[zlibConstants.BROTLI_PARAM_QUALITY]: brotliQuality ?? zlibConstants.BROTLI_MAX_QUALITY,
},
}),
createWriteStream(`${filePath}.br`),
),
pipeline(createReadStream(filePath), createGzip(), createWriteStream(`${filePath}.gz`)),
]);
}
export async function precompressAssets(dir, options = {}) {
const entries = await readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const entryPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
await precompressAssets(entryPath, options);
} else if (entry.isFile() && COMPRESS_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) {
await compressFile(entryPath, options);
}
}
}
if (isMainModule(import.meta.url)) {
const dir = process.argv[2];
if (!dir) {
console.error("Usage: node scripts/precompress-assets.mjs <dir>");
process.exit(2);
}
const started = Date.now();
try {
await precompressAssets(path.resolve(dir));
console.log(`Precompressed ${dir} in ${((Date.now() - started) / 1000).toFixed(1)}s`);
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
process.exit(1);
}
}
-67
View File
@@ -1,67 +0,0 @@
import assert from "node:assert/strict";
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { test } from "node:test";
import { brotliDecompressSync, gunzipSync } from "node:zlib";
import { precompressAssets } from "./precompress-assets.mjs";
async function exists(filePath) {
return stat(filePath).then(
() => true,
() => false,
);
}
async function withDir(fn) {
const dir = await mkdtemp(path.join(os.tmpdir(), "precompress-"));
try {
await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
test("writes .br and .gz that decompress to the original, recursing into subdirectories", async () => {
await withDir(async (dir) => {
const body = "console.log('hello');\n".repeat(500);
await mkdir(path.join(dir, "_expo", "static"), { recursive: true });
const nested = path.join(dir, "_expo", "static", "index.js");
await writeFile(nested, body);
await precompressAssets(dir, { brotliQuality: 4 });
assert.equal(brotliDecompressSync(await readFile(`${nested}.br`)).toString(), body);
assert.equal(gunzipSync(await readFile(`${nested}.gz`)).toString(), body);
assert.ok((await stat(`${nested}.br`)).size < body.length);
});
});
test("skips extensions outside the compressible list", async () => {
await withDir(async (dir) => {
const png = path.join(dir, "logo.png");
await writeFile(png, Buffer.alloc(2048, 1));
await writeFile(path.join(dir, "app.css"), "a{color:red}");
await precompressAssets(dir, { brotliQuality: 4 });
assert.equal(await exists(`${png}.br`), false);
assert.equal(await exists(`${png}.gz`), false);
assert.equal(await exists(path.join(dir, "app.css.br")), true);
});
});
test("is idempotent and never compresses its own output", async () => {
await withDir(async (dir) => {
const file = path.join(dir, "index.html");
const body = "<html></html>".repeat(100);
await writeFile(file, body);
await precompressAssets(dir, { brotliQuality: 4 });
await precompressAssets(dir, { brotliQuality: 4 });
assert.equal(await exists(`${file}.br.br`), false);
assert.equal(await exists(`${file}.gz.gz`), false);
assert.equal(brotliDecompressSync(await readFile(`${file}.br`)).toString(), body);
});
});