Compare commits

..
Author SHA1 Message Date
Matchy d399c82f51 fix(server): keep plugin entries other writers put in config.json (#11501)
The daemon owns plugin source entries and `paseo reload` does not pick up
edits to `plugins`, so its in-memory copy goes stale when config.json is
edited while it runs. Every plugin operation (install, enable, disable,
update, remove) then wrote that whole stale map back to disk. A hand-added
entry was silently deleted by the next operation on any other plugin, and
an entry removed by hand was written back. Local directory plugins hit
this most, since they are the ones people add by editing config.json.

Persisting a plugins patch now applies only the entries that changed
relative to the in-memory copy onto the plugins read from disk. Reload
still ignores plugin edits; they now survive until the next restart loads
them, as docs/plugins.md describes.

Verified with new DaemonConfigStore tests covering a hand-added entry, a
hand-removed entry, and removing one plugin while another sits on disk;
all three failed before the change.
2026-11-30 19:42:40 +00:00
SunicemanandShane Su 9a520f0adc Keep attached plugin slash commands out of the agent conversation (#11483)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 17:12:44 +00:00
Mohamed Boudra 81357c6e7b fix(app): keep the Restoring screen up until a restored workspace is ready (#11486)
Two separate races let the restore gate drop early.

The daemon sends the workspace_update before the restore reply, but the
app batched workspace updates to the next animation frame. The reply
resolved first, the route never saw "restoring with the workspace
present", no post-restore handoff started, and the chat mounted while it
was still loading. Buffered workspace updates now flush when any reply
arrives, so a caller that reads the store after its reply sees the update.
Unsolicited updates keep their per-frame batching.

The handoff released after a fixed three frames, but the desktop tab row
shows tabs only after RN-web onLayout measures every label, which runs
through ResizeObserver and setTimeout and can land later. The gate then
dropped onto an empty tab strip. On-screen chrome behind the gate can now
hold the reveal; the tab row holds until its measured track matches its
labels. The 2.5s handoff timeout still bounds the hold.
2026-11-30 23:56:14 +07:00
Mohamed Boudra 95cc11ab7b Put agent tools behind one Enable tools setting with tool groups (#11189)
* feat(server,app): group agent tools under one Enable tools setting

Replace the separate "Enable Paseo tools" and "Browser tools" settings with
one `daemon.tools` configuration: an `enabled` switch plus per-group switches
for orchestration, schedules, PR watching, and browser. Every built-in tool
now declares its group, scope, and daemon permission in one registry, so
native providers and the loopback MCP endpoint filter the same catalog.

Tools are on by default for hosts that never set the legacy injection flag.
Hosts that set `daemon.mcp.injectIntoAgents: false` keep tools off. Legacy
`daemon.mcp.*` and `daemon.browserTools.enabled` are still read when
`daemon.tools` is absent; those shims are tagged COMPAT.

Voice mode now requires tools. When tools are off it refuses with reasonCode
"tools_disabled" and the voice settings page offers a one-click Enable tools
action. Dictation is unaffected.

* fix(app): keep the host's tool groups when setup is shown again

The Orchestration step started its tool groups from the defaults and wrote
all four on Continue, so a host with Browser on or Schedules off lost those
choices when the user opened setup again. The groups sit in a collapsed row,
so the user never saw the switches. Setup now shows the host's groups and
writes only the groups the user changed.

The compact-layout setup test assumed the host starts with tools off; it now
turns them off first, since tools are on by default.

* fix(server): keep wire schemas out of the configuration entry point

tools-config.ts imported the default tool groups from protocol/messages,
which pulled every wire schema into @getpaseo/server/configuration. The
group constants now live in the Zod-free protocol/tool-groups module, and
messages re-exports them.

The WebSocket server read the config store behind a guard that only
existed for incomplete test stubs. The store is a required dependency, so
the guard is gone and the stubs provide get().

* feat(app): show only the Enable tools switch in setup

Setup is for getting started, so the Orchestration step shows a plain
Enable tools switch next to skills and the CLI. Tool groups stay in
Settings > Tools & prompts. Setup writes only the main switch, so the
groups a host already saved are never touched.

* fix(server,app): let voice mode deliver speak when agent tools are off

Main now delivers a speak-only tool set to an agent in voice mode when
agent tools are off (#11161). This branch refused voice mode in that case
with reasonCode "tools_disabled", which blocked that path.

Voice mode no longer checks the Enable tools setting. The master switch
still removes every built-in and plugin tool, except speak for an active
voice session. The voice settings alert, its Enable tools button, the
"Required for voice mode" hint, and the tools_disabled server capability
are removed.

Also removes a duplicate DaemonClient import that the rebase onto main
left in agent-mcp.e2e.test.ts.
2026-11-30 23:42:56 +07:00
paseo-bot[bot] 93c883a398 test(server): restore the live Codex smoke prompt (#11473)
The smoke test stopped before sending its prompt because it read the retired features property. Check the Plan toggle in session controls to exercise the current provider interface.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-30 16:42:47 +00:00
SunicemanandShane Su d5880784e2 Return the browser URL after creating a GitHub pull request (#11439)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-11-30 16:12:45 +00:00
80 changed files with 2831 additions and 709 deletions
+7 -4
View File
@@ -249,7 +249,8 @@ snapshot so a mixed edit can apply its live subset and still name the paths that
listen: "127.0.0.1:6767",
hostnames: true | string[], // legacy alias `allowedHosts` is migrated on load
trustedProxies: true | string[], // defaults to ["loopback"]; Express proxy names/CIDRs
mcp: { enabled: boolean, injectIntoAgents: boolean },
tools: { enabled: boolean, groups: { orchestration, schedules, changeRequests, browser: boolean } },
mcp: { enabled: boolean, injectIntoAgents: boolean }, // legacy, read only when `tools` is absent
git: { maxProcessesPerSecond: number, maxProcessConcurrency: number },
appendSystemPrompt: string, // appended to supported provider system/developer prompts
terminalProfiles: TerminalProfile[], // named shell commands; omitted means DEFAULT_TERMINAL_PROFILES
@@ -351,12 +352,14 @@ Each entry may include a Paseo-tool policy:
Absent `paseoTools`, or absent fields within it, means Paseo tools are enabled and all tools are
allowed. `enabled: false` disables the provider's Paseo catalog; `disabledTools` lists exact tool
IDs to omit. The policy covers the core and browser catalog, not the voice-only `speak` tool.
Browser tools also require `daemon.browserTools.enabled` and a connected browser host.
Browser tools also require `daemon.tools.groups.browser` and a connected browser host.
This policy controls the catalog presented to an agent. It is not an authorization boundary for
agents that can access the host through a shell.
`daemon.mcp.injectIntoAgents` is the global override. When it is `false`, no provider receives
Paseo tools; otherwise the provider policy applies. Provider and global policy are resolved when a
`daemon.tools` is the global override. When `enabled` is `false`, no provider receives Paseo or
plugin tools; otherwise each group in `daemon.tools.groups` and then the provider policy applies.
When `daemon.tools` is absent, the daemon reads the legacy `daemon.mcp.injectIntoAgents` and
`daemon.browserTools.enabled` fields. Provider and global policy are resolved when a
session is created, resumed, imported, or reloaded, so configuration changes affect the next
session rather than an already-running one.
+6 -38
View File
@@ -22,31 +22,6 @@ value.
Animate only `transform` and `opacity`. Anything else is painted on the main thread every frame.
## Frames
Keeping the animation off the React thread does not make it free. Every time an indicator moves,
the platform composes and presents the whole window again: `RenderThread` on Android, the GPU
process and macOS's WindowServer on desktop. An indicator that moves with the display holds the
window at 60 or 120 frames a second for as long as an agent runs, with nothing else changing.
So an indicator moves in steps, and the step count is its frame rate:
| Indicator | Positions | Frames a second |
| ----------------- | ----------------------------------- | --------------- |
| Loader | 6 per 950 ms | 6 |
| Status ring | 27 per 900 ms (`STATUS_RING_STEPS`) | 30 |
| Tool-call shimmer | every display frame | 60 or 120 |
The ring is the one that matters most: it is on screen in the sidebar and the tab bar whenever any
agent runs, including while you read an idle chat. Its steps are positions the smooth turn passes
through, 1.2 px apart on a 12 px ring. Fewer steps start to read as ticking and buy little: measured
on an Android emulator with one ring on screen, the app used 12–15% of a core with a smooth ring,
8–10% with 27 steps, and 6–7% with either 18 or 12, because the native driver's own tick is what is
left.
Two indicators only share frames when their steps turn over at the same instants. The shimmer still
moves every frame, so a chat with a running tool call in view draws at the display's rate.
## Web
`useIndicatorLoop` runs a keyframe loop through the Web Animations API (`element.animate`). The
@@ -66,9 +41,8 @@ Two more reasons the stylesheet route does not work here:
Indicators that must move together use `phase: "shared"`, which starts the loop at the document
timeline's origin instead of at mount. Every ring and every loader is then at the same point of its
cycle wherever and whenever it mounted. A stepped animation sets its easing on the keyframes:
`step-end` to hold each keyframe until the next, `steps(n)` to cross between two keyframes in `n`
even steps. The compositor then draws a frame when a step changes and none in between.
cycle wherever and whenever it mounted. A stepped animation sets `easing: "step-end"` on each
keyframe; the compositor then draws a frame when a step changes and none in between.
## Native
@@ -83,9 +57,6 @@ its value from the frame timestamp instead of replaying a 60 fps recording, so i
refresh rate and needs no loop restart. `Animated.modulo` and `interpolate` turn the clock into a
rotation or a translation, all inside the native driver.
`cycle(periodMs, steps)` holds the position at each step. The driver still ticks every frame, but a
view whose transform did not change is not invalidated, so nothing is drawn between steps.
The loader changes six times per cycle, so it does not ride the frame clock. `step-ticker.ts` wakes
the JS thread once per step, aligned to wall-clock step boundaries, and publishes the step into a
native `Animated.Value`. A wake-up that arrives late publishes the step that is current by then, so
@@ -98,8 +69,7 @@ Do not apply Unistyles dynamic styles to these `Animated.View`s; see
`e2e/browser/running-indicators.spec.ts` holds the web budgets: animation-frame callbacks, style
recalculations, paints and main-thread commits per second on a quiet running turn, React renders of
the indicator components, the loader's and the ring's cadence, the frames a ring draws beside an
idle chat, reduced motion, and a hidden tab. Run it with
the indicator components, the loader's cadence, reduced motion, and a hidden tab. Run it with
`PASEO_RUNNING_INDICATORS_FRAMES=1` to also save reference frames of every indicator at fixed
points of its cycle, for a pixel comparison across a change.
@@ -107,8 +77,6 @@ To hold a turn in the running state without streaming, send the mock load-test a
`Hold a running shell tool call for <N>ms`.
On Android, compare `adb shell dumpsys gfxinfo <package>` frame counts and per-thread CPU from
`/proc/<pid>/task/*/stat` over a fixed window. A regression in how an indicator is driven shows up
on the UI thread (`sh.paseo.debug`); one in how often it moves shows up as frames rendered and on
`RenderThread`. `dumpsys gfxinfo <package> framestats` lists each frame's vsync, which shows whether
the steps are evenly spaced. On the emulator gfxinfo counts every frame that follows an idle vsync
as janky; read the frame count and the percentiles instead.
`/proc/<pid>/task/*/stat` over a fixed window. The UI thread (`sh.paseo.debug`) is the one a
regression shows up on; `RenderThread` draws 60 frames a second whenever a ring or a shimmer is on
screen, and that part is the cost of the motion itself.
@@ -1,5 +1,11 @@
import { expect, test, type Page } from "../support/fixtures";
import { composerLocator, expectComposerVisible, submitMessage } from "../support/helpers/composer";
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
import {
attachImageFromMenu,
composerLocator,
expectComposerVisible,
submitMessage,
} from "../support/helpers/composer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import {
expectSessionRowArchived,
@@ -140,6 +146,47 @@ async function waitForReplacementAgentId(page: Page, oldAgentId: string): Promis
}
test.describe("Client slash commands", () => {
test("keeps the draft when a typed plugin slash command has an attachment", async ({ page }) => {
test.setTimeout(90_000);
await withDirectoryPlugin({
pluginId: "attachment-slash-e2e",
source: `
export default function contribute(client) {
client.addSlashCommand({name:"picture", description:"Review an attached picture", argumentHint:"<question>", context:"agent",
onSubmit(){throw new Error("Plugin handler unexpectedly received this command");}});
return () => {};
}`,
run: async () => {
await withOpenReadyMockAgent(page, { title: "Attached slash command" }, async () => {
const input = composerLocator(page);
await input.fill("/pict");
await expect(
page.getByText("Review an attached picture", { exact: true }).first(),
).toBeVisible();
await input.fill("");
await attachImageFromMenu(page, {
name: "picture.png",
mimeType: "image/png",
buffer: Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
"base64",
),
});
await input.fill("/picture what is this?");
await input.press("Enter");
await expect(
page.getByRole("alert").filter({ hasText: "Remove attachments to run /picture." }),
).toBeVisible();
await expect(input).toHaveValue("/picture what is this?");
await expect(page.getByTestId("composer-image-attachment-pill")).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: "/picture what is this?" }),
).toHaveCount(0);
});
},
});
});
test("slash quit archives the active agent and removes its tab", async ({ page }) => {
await withOpenReadyMockAgent(page, { title: "Slash quit e2e" }, async ({ agentId, title }) => {
await runClientSlashCommand(page, "/quit");
+28 -1
View File
@@ -10,6 +10,7 @@ import {
finishSetup,
goToSetupStep,
hostGivesAgentsPaseoTools,
hostToolGroups,
openAppAsNewUser,
openRelayPairingFromSetup,
closeRelayPairing,
@@ -24,6 +25,7 @@ import {
recordFirstLaunch,
setupModal,
setupPrimaryButton,
setHostTools,
setupSheet,
showSetupAgainFromSettings,
skipSetup,
@@ -426,6 +428,30 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
}
});
test("setup offers only Enable tools and keeps the host's tool groups", async ({ page }) => {
const host = await startSetupHost("tool-groups");
try {
await setHostTools(host, { groups: { schedules: false, browser: true } });
await openAppAsNewUser(page, host);
await expectSetupStep(page, "Welcome to Paseo");
await goToSetupStep(page, "Orchestration");
await expectSetupStep(page, "Let agents use Paseo");
await expect(paseoToolsSwitch(setupModal(page))).toBeChecked();
// Setup offers only the main switch; tool groups live in Settings.
await expect(
setupModal(page).getByRole("switch", { name: "Browser", exact: true }),
).toHaveCount(0);
await continueSetup(page);
await expectSetupStep(page, "Take your agents with you");
await expect.poll(() => hostGivesAgentsPaseoTools(host), { timeout: 30_000 }).toBe(true);
expect(await hostToolGroups(host)).toMatchObject({ schedules: false, browser: true });
} finally {
await host.close();
}
});
test("with no skills picked, skills read as off and Continue moves on", async ({ page }) => {
const host = await startSetupHost("no-skills");
@@ -463,6 +489,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
const primary = (label: string) => page.getByRole("button", { name: label, exact: true });
try {
await setHostTools(host, { enabled: false });
await openAppAsNewUser(page, host);
await step("Welcome to Paseo");
await primary("Continue").click();
@@ -471,7 +498,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
await step("Add your projects");
await primary("Continue").click();
// The setup host starts with Paseo tools off; the switch starts on.
// The host has tools off; the setup switch still starts on.
expect(await hostGivesAgentsPaseoTools(host)).toBe(false);
await step("Let agents use Paseo");
await expect(paseoToolsSwitch(page)).toBeChecked();
@@ -8,13 +8,11 @@ import {
import {
captureLoaderSteps,
freezeAnimationsAt,
openIdleChatBesideRunningAgent,
openQuietRunningTurn,
readAnimatingTargets,
readLoaderStep,
readRunningAnimations,
recordLoaderStepChanges,
recordRingAngles,
runningToolCall,
statusRings,
workingLoader,
@@ -47,10 +45,6 @@ const PAINTED_VIEWPORTS_PER_SECOND_BUDGET = 4;
const LOADER_PERIOD_MS = 950;
const LOADER_STEP_MS = LOADER_PERIOD_MS / 6;
const STATUS_RING_PERIOD_MS = 900;
const STATUS_RING_STEPS = 27;
// Thirty ring positions a second, plus the few frames a second the rest of the page draws. A ring
// that turns with the display draws sixty or more.
const RING_ONLY_FRAMES_PER_SECOND_BUDGET = 36;
// React renders these once when the indicator appears. Rendering again while the turn is quiet
// means the animation is being driven through React.
@@ -115,45 +109,6 @@ test.describe("Running indicators", () => {
}
});
test("a ring beside an idle chat redraws the window thirty times a second", async ({
page,
browser,
}, testInfo) => {
test.setTimeout(180_000);
const scene = await openIdleChatBesideRunningAgent(page);
try {
const animating = await readAnimatingTargets(page);
const activity = await measureSteadyStateActivity({
browser,
page,
windowMs: SAMPLE_WINDOW_MS,
});
const angles = await recordRingAngles(page, STATUS_RING_PERIOD_MS * 3);
await writeFile(
testInfo.outputPath("evidence.json"),
JSON.stringify({ animating, activity, angles }, null, 2),
);
// Nothing but rings is moving, so every frame drawn is a ring's.
expect.soft(new Set(animating)).toEqual(new Set(["status-ring"]));
expect
.soft(activity.compositorFramesPerSecond)
.toBeLessThan(RING_ONLY_FRAMES_PER_SECOND_BUDGET);
// The cadence is part of the design: the quarter is only ever at one of its even steps.
const stepDegrees = 360 / STATUS_RING_STEPS;
const offStep = angles.filter((angle) => {
const stepsAlong = angle / stepDegrees;
return Math.abs(stepsAlong - Math.round(stepsAlong)) * stepDegrees > 0.05;
});
expect.soft(offStep).toEqual([]);
expect.soft(angles.length).toBeGreaterThan(STATUS_RING_STEPS / 2);
expect.soft(angles.length).toBeLessThanOrEqual(STATUS_RING_STEPS);
} finally {
await scene.cleanup();
}
});
test("hold still when the system asks for reduced motion", async ({
page,
browser,
+36 -2
View File
@@ -4,6 +4,10 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client";
import type {
MutableDaemonToolGroups,
MutableDaemonToolsConfigPatch,
} from "@getpaseo/protocol/messages";
import { addProjectFlow, addProjectFlowInput, expectAddProjectTab } from "./add-project-flow";
import { connectDaemonClient } from "./daemon-client-loader";
import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry";
@@ -138,7 +142,7 @@ export async function goToSetupStep(page: Page, label: string): Promise<void> {
}
export function paseoToolsSwitch(scope: Page | Locator): Locator {
return scope.getByRole("switch", { name: "Inject Paseo tools", exact: true });
return scope.getByRole("switch", { name: "Enable tools", exact: true });
}
/** Whether the host gives its agents Paseo tools, read from the host itself. */
@@ -147,7 +151,37 @@ export async function hostGivesAgentsPaseoTools(host: { port: number }): Promise
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
return (await client.getDaemonConfig()).config.mcp.injectIntoAgents !== false;
const config = (await client.getDaemonConfig()).config;
return config.tools?.enabled ?? config.mcp.injectIntoAgents !== false;
} finally {
await client.close();
}
}
/** The host's saved tool groups, read from the host itself. */
export async function hostToolGroups(host: {
port: number;
}): Promise<MutableDaemonToolGroups | undefined> {
const client = await connectDaemonClient<
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
return (await client.getDaemonConfig()).config.tools?.groups;
} finally {
await client.close();
}
}
/** Saves tool settings on the host, the way Settings does. */
export async function setHostTools(
host: { port: number },
tools: MutableDaemonToolsConfigPatch,
): Promise<void> {
const client = await connectDaemonClient<
Pick<InternalDaemonClient, "connect" | "close" | "patchDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
await client.patchDaemonConfig({ tools });
} finally {
await client.close();
}
@@ -50,76 +50,6 @@ export async function openQuietRunningTurn(page: Page): Promise<MockAgentWorkspa
}
}
/**
* Opens an idle chat while an agent runs in another workspace: the only thing moving on screen is
* the running workspace's status ring in the sidebar.
*/
export async function openIdleChatBesideRunningAgent(page: Page): Promise<{
cleanup(): Promise<void>;
}> {
const running = await seedMockAgentWorkspace({
repoPrefix: "running-beside-",
title: "Running beside",
initialPrompt: HELD_TOOL_CALL_PROMPT,
});
try {
const idle = await seedMockAgentWorkspace({ repoPrefix: "idle-chat-", title: "Idle chat" });
const cleanup = async () => {
await idle.cleanup();
await running.cleanup();
};
try {
await openAgentRoute(page, { workspaceId: idle.workspaceId, agentId: idle.agentId });
await expectComposerVisible(page);
await expect(statusRings(page).first()).toBeVisible({ timeout: 30_000 });
await expect(workingLoader(page)).toHaveCount(0);
await page.mouse.move(900, 300);
return { cleanup };
} catch (error) {
await cleanup();
throw error;
}
} catch (error) {
await running.cleanup().catch(() => undefined);
throw error;
}
}
/** Every angle the first visible status ring's quarter is seen at over the window, in degrees. */
export async function recordRingAngles(page: Page, windowMs: number): Promise<number[]> {
return statusRings(page)
.first()
.evaluate(
(ring, sampleWindowMs) =>
new Promise<number[]>((resolve, reject) => {
const turning = document
.getAnimations()
.map((animation) => animation.effect)
.filter((effect): effect is KeyframeEffect => effect instanceof KeyframeEffect)
.find((effect) => effect.target && ring.contains(effect.target));
const quarter = turning?.target;
if (!quarter) {
reject(new Error("The status ring is not turning"));
return;
}
const angles = new Set<number>();
const startedAt = performance.now();
const sample = () => {
const { a, b } = new DOMMatrixReadOnly(getComputedStyle(quarter).transform);
const degrees = (Math.atan2(b, a) * 180) / Math.PI;
angles.add(Math.round(((degrees + 360) % 360) * 100) / 100);
if (performance.now() - startedAt >= sampleWindowMs) {
resolve([...angles].sort((first, second) => first - second));
return;
}
requestAnimationFrame(sample);
};
sample();
}),
windowMs,
);
}
/** The loader's current step, or null while the dots are between two readable states. */
export async function readLoaderStep(page: Page): Promise<number | null> {
const opacities = await loaderDots(page).evaluateAll((dots) =>
+1 -1
View File
@@ -519,7 +519,7 @@ export async function expectHostConnectionsCard(page: Page, port: string): Promi
export async function expectHostInjectMcpCard(page: Page): Promise<void> {
const card = page.getByTestId("host-page-inject-mcp-card");
await expect(card).toBeVisible();
await expect(card.getByRole("switch", { name: "Inject Paseo tools" })).toBeVisible();
await expect(card.getByRole("switch", { name: "Enable tools" })).toBeVisible();
}
function idleAgentReleaseSwitch(page: Page) {
@@ -1,79 +0,0 @@
import { Animated } from "react-native";
import { describe, expect, test } from "vitest";
import { createIndicatorClock } from "./clock";
const PERIOD_MS = 900;
const STEPS = 27;
const STEP_MS = PERIOD_MS / STEPS;
// Animated only pushes a derived value to a mounted view, so this asks the node for it the way the
// view's props do.
function read(node: object): number {
if (!("__getValue" in node) || typeof node.__getValue !== "function") {
throw new Error("Not an Animated node");
}
return Number(node.__getValue());
}
// Where the cycle is at each of the given clock readings.
function positionsAt(elapsed: number[], steps?: number): number[] {
const elapsedMs = new Animated.Value(0);
const position = createIndicatorClock(elapsedMs).cycle(PERIOD_MS, steps);
return elapsed.map((ms) => {
elapsedMs.setValue(ms);
return Math.round(read(position) * 1e6) / 1e6;
});
}
// A display's frames, as the native driver's clock counts them: whole frames from zero.
function frames(hz: number, count: number): number[] {
return Array.from({ length: count }, (_, frame) => (frame * 1000) / hz);
}
describe("indicator clock", () => {
test("a cycle without steps advances with every frame", () => {
expect(positionsAt([0, 16, 450, 899, 900, 916])).toEqual([0, 16, 450, 899, 0, 16]);
});
test("a stepped cycle only ever sits on one of its even steps", () => {
const positions = positionsAt(frames(60, 3 * 54), STEPS);
expect(new Set(positions).size).toBe(STEPS);
for (const position of positions) {
expect(position / STEP_MS).toBeCloseTo(Math.round(position / STEP_MS), 4);
expect(position).toBeLessThan(PERIOD_MS);
}
});
test.each([60, 90, 120])("at %i Hz every step is held for the same number of frames", (hz) => {
const positions = positionsAt(frames(hz, hz * 3), STEPS);
const heldFor: number[] = [];
let run = 1;
for (let frame = 1; frame < positions.length; frame += 1) {
if (positions[frame] === positions[frame - 1]) {
run += 1;
} else {
heldFor.push(run);
run = 1;
}
}
// The first step is cut short by the lead; every step after it is whole.
expect(new Set(heldFor.slice(1))).toEqual(new Set([hz / 30]));
});
test("a frame that lands a hair early or late shows the same step", () => {
const onTime = positionsAt(frames(60, 120), STEPS);
const early = positionsAt(
frames(60, 120).map((ms) => ms - 0.2),
STEPS,
).slice(1);
const late = positionsAt(
frames(60, 120).map((ms) => ms + 0.2),
STEPS,
);
expect(early).toEqual(onTime.slice(1));
expect(late).toEqual(onTime);
});
});
@@ -7,12 +7,6 @@ import { Animated } from "react-native";
// rate and never ends or loops.
const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: true };
// The clock starts on a frame and advances a whole frame at a time, so at 60, 90 and 120 Hz a step
// that is a whole number of frames long would turn over exactly on a frame, and rounding would
// decide frame by frame which side of the step it fell on. Turning each step over this fraction of
// a step early puts the turn between two frames at all three rates.
const STEP_LEAD = 1 / 8;
/**
* Milliseconds, counted on the UI thread by React Native's native animation driver.
*
@@ -21,31 +15,20 @@ const STEP_LEAD = 1 / 8;
* on every frame it changes.
*/
export interface IndicatorClock {
/**
* Where a cycle of `periodMs` currently is, as milliseconds into the cycle.
*
* With `steps`, the position holds at each of that many even steps instead of advancing every
* frame. A view bound to a held position is not redrawn until the step turns over.
*/
cycle(periodMs: number, steps?: number): Animated.AnimatedInterpolation<number>;
/** Where a cycle of `periodMs` currently is, as milliseconds into the cycle. */
cycle(periodMs: number): Animated.AnimatedModulo<number>;
/** Runs the clock until the returned function is called. It restarts from zero when idle. */
run(): () => void;
}
export function createIndicatorClock(
elapsedMs = new Animated.Value(0, { useNativeDriver: true }),
): IndicatorClock {
export function createIndicatorClock(): IndicatorClock {
const elapsedMs = new Animated.Value(0, { useNativeDriver: true });
let runners = 0;
let ticking: Animated.CompositeAnimation | null = null;
return {
cycle(periodMs, steps) {
if (!steps) {
return Animated.modulo(elapsedMs, periodMs);
}
const stepMs = periodMs / steps;
const position = Animated.modulo(Animated.add(elapsedMs, stepMs * STEP_LEAD), periodMs);
return Animated.subtract(position, Animated.modulo(position, stepMs));
cycle(periodMs) {
return Animated.modulo(elapsedMs, periodMs);
},
run() {
runners += 1;
@@ -2,12 +2,19 @@ import { useCallback, useMemo, useState, type ReactNode } from "react";
import { View } from "react-native";
import { isWeb } from "@/constants/platform";
import { SettingsRowChildren } from "./row-children";
import { SettingsRowHeader } from "./row-header";
import { SettingsRowHeader, type SettingsRowHintStatus } from "./row-header";
interface SettingsCollapsibleRowProps {
label: string;
/** A line under the label explaining the group. */
hint?: string;
hintStatus?: SettingsRowHintStatus;
/** A short status shown before the chevron, so the row says something while collapsed. */
summary?: string;
/** A control acting on the row's subject in place, such as a switch, before the chevron. */
control?: ReactNode;
/** Names the expand/collapse button for assistive tech when the label alone is not enough. */
accessibilityLabel?: string;
defaultExpanded?: boolean;
testID?: string;
/** The rows revealed underneath, separated like the rows of a `SettingsCard` and laid out as nested rows. */
@@ -21,7 +28,11 @@ interface SettingsCollapsibleRowProps {
*/
export function SettingsCollapsibleRow({
label,
hint,
hintStatus,
summary,
control,
accessibilityLabel,
defaultExpanded = false,
testID,
children,
@@ -39,7 +50,11 @@ export function SettingsCollapsibleRow({
<View testID={testID}>
<SettingsRowHeader
label={label}
hint={hint}
hintStatus={hintStatus}
summary={summary}
control={control}
accessibilityLabel={accessibilityLabel}
onPress={toggle}
expanded={expanded}
accessibilityState={accessibilityState}
@@ -31,12 +31,6 @@ export const STATUS_RING_HEAD_OPACITY = 0.9;
// already turning.
export const STATUS_RING_PERIOD_MS = 900;
// The quarter takes thirty positions a second, not one per display refresh. A window is redrawn
// every time the ring moves, so a ring that moves with the display holds the whole window at the
// display's rate for as long as an agent runs. Each position is one the smooth turn passes through,
// 1.2 px further along a 12 px ring.
export const STATUS_RING_STEPS = 27;
/**
* Re-anchors a corner status dot's offset for the ring that replaces it.
*
@@ -8,11 +8,11 @@ import {
rotatorStyles,
styles,
} from "@/components/status-ring/frame";
import { STATUS_RING_PERIOD_MS, STATUS_RING_STEPS } from "@/components/status-ring/geometry";
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
// One rotation for every ring in the app, so a row that appears mid-flight lands in step with the
// rings already turning.
const rotation = sharedIndicatorClock.cycle(STATUS_RING_PERIOD_MS, STATUS_RING_STEPS).interpolate({
const rotation = sharedIndicatorClock.cycle(STATUS_RING_PERIOD_MS).interpolate({
inputRange: [0, STATUS_RING_PERIOD_MS],
outputRange: ["0deg", "360deg"],
});
@@ -8,15 +8,12 @@ import {
rotatorStyles,
styles,
} from "@/components/status-ring/frame";
import { STATUS_RING_PERIOD_MS, STATUS_RING_STEPS } from "@/components/status-ring/geometry";
import { STATUS_RING_PERIOD_MS } from "@/components/status-ring/geometry";
// A sidebar full of agents can hold dozens of rings at once; the shared phase keeps them turning as
// one, and a row that appears mid-flight lands in step with the rings already turning.
const TURNING: IndicatorLoop = {
keyframes: [
{ transform: "rotate(0deg)", easing: `steps(${STATUS_RING_STEPS})` },
{ transform: "rotate(360deg)" },
],
keyframes: [{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }],
durationMs: STATUS_RING_PERIOD_MS,
phase: "shared",
};
+19 -7
View File
@@ -1671,7 +1671,16 @@ function ComposerContentImpl({
);
const runPluginClientSlashCommand = useCallback(
(resolved: { command: (typeof pluginClientSlashCommands)[number]; args: string }): boolean => {
(
resolved: { command: (typeof pluginClientSlashCommands)[number]; args: string },
hasAttachments: boolean,
) => {
if (hasAttachments) {
setSendError(
t("composer.errors.removePluginCommandAttachments", { command: resolved.command.name }),
);
return;
}
if (blurOnSubmit) messageInputRef.current?.blur();
clearDraft("sent");
replaceUserInput("");
@@ -1686,9 +1695,8 @@ function ComposerContentImpl({
toastErrorRef.current(error instanceof Error ? error.message : String(error));
},
});
return true;
},
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments],
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments, t],
);
const { pickImages } = useImageAttachmentPicker();
@@ -1988,10 +1996,12 @@ function ComposerContentImpl({
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
if (blurOnSubmit) {
messageInputRef.current?.blur();
@@ -2261,10 +2271,12 @@ function ComposerContentImpl({
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
queueMessage(payload.text, outgoingAttachments);
},
[
+1 -1
View File
@@ -385,7 +385,7 @@ describe("translation resources", () => {
expect(en.settings.host.notFound).toBe("Host not found");
expect(en.settings.host.connections.title).toBe("Connections");
expect(en.settings.host.daemon.restart.title).toBe("Restart daemon");
expect(en.settings.host.orchestration.enableTools.title).toBe("Enable Paseo tools");
expect(en.settings.host.orchestration.enableTools.title).toBe("Enable tools");
expect(en.settings.providers.title).toBe("Providers");
expect(en.settings.providers.models.addModel).toBe("Add model");
expect(en.settings.providers.diagnostic.title).toBe("Diagnostic");
+25 -4
View File
@@ -195,6 +195,7 @@ export const ar: TranslationResources = {
removeReview: "إزالة مرفق المراجعة",
},
errors: {
removePluginCommandAttachments: "أزل المرفقات لتشغيل الأمر /{{command}}.",
failedToSend: "فشل في إرسال الرسالة",
failedToCreateAgent: "فشل في إنشاء الوكيل",
noHostSelected: "لم يتم تحديد مضيف",
@@ -3147,15 +3148,35 @@ export const ar: TranslationResources = {
tools: {
instructionsTitle: "التعليمات",
toolsTitle: "أدوات الوكلاء",
pluginNote: "الأدوات التي تضيفها الإضافات تتبع أيضًا خيار تمكين الأدوات",
updateHostForGroups: "حدّث هذا المضيف لضبط مجموعات الأدوات الفردية",
groups: {
orchestration: {
title: "التنسيق",
hint: "إدارة مساحات العمل والوكلاء والطرفيات والسكربتات",
},
schedules: {
title: "الجداول الزمنية",
hint: "إنشاء وإدارة الجداول الزمنية ونبضات المتابعة",
},
changeRequests: {
title: "مراقبة طلبات السحب",
hint: "مراقبة تحديثات طلبات السحب والدمج",
},
browser: {
title: "المتصفح",
hint: "التحكم في علامات تبويب متصفح Paseo بما في ذلك الجلسات المسجّل الدخول إليها. فعّل هذا الخيار فقط للوكلاء الموثوقين.",
},
},
},
orchestration: {
title: "التنسيق",
unavailable: "اتصل بهذا المضيف لإدارة التنسيق",
enableTools: {
title: "تمكين أدوات Paseo",
hint: "سيتمكن الوكلاء من إدارة أشجار العمل والوكلاء والجداول الزمنية",
accessibilityLabel: "حقن أدوات Paseo",
updateFailed: "تعذر تحديث أدوات Paseo.",
title: "تمكين الأدوات",
hint: "يسمح لـ Paseo والإضافات بتوفير الأدوات للوكلاء.",
accessibilityLabel: "تمكين الأدوات",
updateFailed: "تعذر تحديث الأدوات.",
},
systemPrompt: {
title: "موجه النظام",
+25 -4
View File
@@ -193,6 +193,7 @@ export const en = {
removeReview: "Remove review attachment",
},
errors: {
removePluginCommandAttachments: "Remove attachments to run /{{command}}.",
failedToSend: "Failed to send message",
failedToCreateAgent: "Failed to create agent",
noHostSelected: "No host selected",
@@ -3247,15 +3248,35 @@ export const en = {
tools: {
instructionsTitle: "Instructions",
toolsTitle: "Agent tools",
pluginNote: "Tools added by plugins also follow Enable tools",
updateHostForGroups: "Update this host to configure individual tool groups",
groups: {
orchestration: {
title: "Orchestration",
hint: "Manage workspaces, agents, terminals, and scripts",
},
schedules: {
title: "Schedules",
hint: "Create and manage schedules and heartbeats",
},
changeRequests: {
title: "PR watching",
hint: "Watch pull requests and merge requests for updates",
},
browser: {
title: "Browser",
hint: "Control Paseo browser tabs, including logged-in state. Enable only for agents you trust.",
},
},
},
orchestration: {
title: "Orchestration",
unavailable: "Connect to this host to manage orchestration",
enableTools: {
title: "Enable Paseo tools",
hint: "Agents will be able to manage worktrees, agents and schedules",
accessibilityLabel: "Inject Paseo tools",
updateFailed: "Unable to update Paseo tools.",
title: "Enable tools",
hint: "Let Paseo and plugins give tools to agents.",
accessibilityLabel: "Enable tools",
updateFailed: "Unable to update tools.",
},
systemPrompt: {
title: "System prompt",
+25 -4
View File
@@ -196,6 +196,7 @@ export const es: TranslationResources = {
removeReview: "Eliminar archivo adjunto de reseña",
},
errors: {
removePluginCommandAttachments: "Quita los archivos adjuntos para ejecutar /{{command}}.",
failedToSend: "No se pudo enviar el mensaje",
failedToCreateAgent: "No se pudo crear el agente",
noHostSelected: "Ningún anfitrión seleccionado",
@@ -3180,15 +3181,35 @@ export const es: TranslationResources = {
tools: {
instructionsTitle: "Instrucciones",
toolsTitle: "Herramientas de agentes",
pluginNote: "Las herramientas de los plugins también siguen Habilitar herramientas",
updateHostForGroups: "Actualiza este host para configurar grupos de herramientas",
groups: {
orchestration: {
title: "Orquestación",
hint: "Gestiona workspaces, agentes, terminales y scripts",
},
schedules: {
title: "Programaciones",
hint: "Crea y gestiona programaciones y heartbeats",
},
changeRequests: {
title: "Seguimiento de PR",
hint: "Supervisa pull requests y merge requests para ver actualizaciones",
},
browser: {
title: "Navegador",
hint: "Controla las pestañas del navegador de Paseo, incluido el estado con sesión iniciada. Actívalo solo para agentes de confianza.",
},
},
},
orchestration: {
title: "Orquestación",
unavailable: "Conéctese a este host para administrar la orquestación",
enableTools: {
title: "Habilitar herramientasPaseo",
hint: "Los agentes podrán gestionar árboles de trabajo, agentes y horarios.",
accessibilityLabel: "Inyectar herramientasPaseo",
updateFailed: "No se pudieron actualizar las herramientas de Paseo.",
title: "Habilitar herramientas",
hint: "Permite que Paseo y los plugins proporcionen herramientas a los agentes.",
accessibilityLabel: "Habilitar herramientas",
updateFailed: "No se pudieron actualizar las herramientas.",
},
systemPrompt: {
title: "Aviso del sistema",
+25 -4
View File
@@ -197,6 +197,7 @@ export const fr: TranslationResources = {
removeReview: "Retirer la revue jointe",
},
errors: {
removePluginCommandAttachments: "Retirez les pièces jointes pour exécuter /{{command}}.",
failedToSend: "Impossible d’envoyer le message",
failedToCreateAgent: "Impossible de créer l’agent",
noHostSelected: "Aucun hôte sélectionné",
@@ -3182,15 +3183,35 @@ export const fr: TranslationResources = {
tools: {
instructionsTitle: "Instructions",
toolsTitle: "Outils des agents",
pluginNote: "Les outils ajoutés par les plugins suivent aussi Activer les outils",
updateHostForGroups: "Mettez à jour cet hôte pour configurer chaque groupe d'outils",
groups: {
orchestration: {
title: "Orchestration",
hint: "Gérer les workspaces, les agents, les terminaux et les scripts",
},
schedules: {
title: "Planifications",
hint: "Créer et gérer des planifications et des heartbeats",
},
changeRequests: {
title: "Suivi des PR",
hint: "Surveiller les pull requests et merge requests",
},
browser: {
title: "Navigateur",
hint: "Contrôler les onglets du navigateur Paseo, y compris les sessions connectées. Activez uniquement pour des agents de confiance.",
},
},
},
orchestration: {
title: "Orchestration",
unavailable: "Connectez-vous à cet hôte pour gérer l’orchestration",
enableTools: {
title: "Activer les outils Paseo",
hint: "Les agents pourront gérer les worktrees, les agents et les planifications",
accessibilityLabel: "Injecter les outils Paseo",
updateFailed: "Impossible de mettre à jour les outils Paseo.",
title: "Activer les outils",
hint: "Autorise Paseo et les plugins à fournir des outils aux agents.",
accessibilityLabel: "Activer les outils",
updateFailed: "Impossible de mettre à jour les outils.",
},
systemPrompt: {
title: "Prompt système",
+25 -4
View File
@@ -196,6 +196,7 @@ export const ja: TranslationResources = {
removeReview: "レビュー添付ファイルを削除",
},
errors: {
removePluginCommandAttachments: "/{{command}} を実行するには添付ファイルを削除してください。",
failedToSend: "メッセージの送信に失敗しました",
failedToCreateAgent: "エージェントの作成に失敗しました",
noHostSelected: "ホストが選択されていません",
@@ -3142,15 +3143,35 @@ export const ja: TranslationResources = {
tools: {
instructionsTitle: "指示",
toolsTitle: "エージェントツール",
pluginNote: "プラグインが追加するツールもこのスイッチに従います",
updateHostForGroups: "ツールグループを個別に設定するにはホストを更新してください",
groups: {
orchestration: {
title: "オーケストレーション",
hint: "ワークスペース、エージェント、ターミナル、スクリプトを管理します",
},
schedules: {
title: "スケジュール",
hint: "スケジュールとハートビートを作成・管理します",
},
changeRequests: {
title: "PRの監視",
hint: "プルリクエストやマージリクエストの更新を監視します",
},
browser: {
title: "ブラウザ",
hint: "ログイン状態を含む Paseo のブラウザタブを操作します。信頼できるエージェントにのみ有効にしてください。",
},
},
},
orchestration: {
title: "オーケストレーション",
unavailable: "オーケストレーションを管理するにはこのホストに接続してください",
enableTools: {
title: "Paseoツールを有効にする",
hint: "エージェントがワークツリー、エージェント、スケジュールを管理できるようになります",
accessibilityLabel: "Paseoツールを有効にする",
updateFailed: "Paseoツールを更新できませんでした。",
title: "ツールを有効にする",
hint: "Paseo とプラグインからエージェントへツールを提供します。",
accessibilityLabel: "ツールを有効にする",
updateFailed: "ツールを更新できませんでした。",
},
systemPrompt: {
title: "システムプロンプト",
+25 -4
View File
@@ -195,6 +195,7 @@ export const ko: TranslationResources = {
removeReview: "리뷰 첨부 제거",
},
errors: {
removePluginCommandAttachments: "/{{command}} 명령을 실행하려면 첨부 파일을 제거하세요.",
failedToSend: "메시지를 보내지 못했습니다",
failedToCreateAgent: "에이전트를 생성하지 못했습니다",
noHostSelected: "선택된 호스트가 없습니다",
@@ -3126,15 +3127,35 @@ export const ko: TranslationResources = {
tools: {
instructionsTitle: "지침",
toolsTitle: "에이전트 도구",
pluginNote: "플러그인이 추가한 도구도 도구 활성화 스위치를 따릅니다",
updateHostForGroups: "개별 도구 그룹을 설정하려면 이 호스트를 업데이트하세요",
groups: {
orchestration: {
title: "오케스트레이션",
hint: "워크스페이스, 에이전트, 터미널, 스크립트 관리",
},
schedules: {
title: "일정",
hint: "일정 및 하트비트 생성과 관리",
},
changeRequests: {
title: "PR 감시",
hint: "풀 리퀘스트와 머지 리퀘스트 업데이트 감시",
},
browser: {
title: "브라우저",
hint: "로그인된 상태를 포함해 Paseo 브라우저 탭을 제어합니다. 신뢰하는 에이전트에만 활성화하세요.",
},
},
},
orchestration: {
title: "오케스트레이션",
unavailable: "오케스트레이션을 관리하려면 이 호스트에 연결하세요",
enableTools: {
title: "Paseo 도구 활성화",
hint: "에이전트가 워크트리, 에이전트, 일정을 관리할 수 있습니다",
accessibilityLabel: "Paseo 도구 주입",
updateFailed: "Paseo 도구를 업데이트할 수 없습니다.",
title: "도구 활성화",
hint: "Paseo와 플러그인이 에이전트에 도구를 제공할 수 있게 합니다.",
accessibilityLabel: "도구 활성화",
updateFailed: "도구를 업데이트할 수 없습니다.",
},
systemPrompt: {
title: "시스템 프롬프트",
+25 -4
View File
@@ -196,6 +196,7 @@ export const ptBR: TranslationResources = {
removeReview: "Remover anexo de revisão",
},
errors: {
removePluginCommandAttachments: "Remova os anexos para executar /{{command}}.",
failedToSend: "Falha ao enviar mensagem",
failedToCreateAgent: "Falha ao criar agente",
noHostSelected: "Nenhum host selecionado",
@@ -3161,15 +3162,35 @@ export const ptBR: TranslationResources = {
tools: {
instructionsTitle: "Instruções",
toolsTitle: "Ferramentas de agentes",
pluginNote: "Ferramentas adicionadas por plugins também seguem Ativar ferramentas",
updateHostForGroups: "Atualize este host para configurar grupos de ferramentas",
groups: {
orchestration: {
title: "Orquestração",
hint: "Gerencie workspaces, agentes, terminais e scripts",
},
schedules: {
title: "Agendamentos",
hint: "Crie e gerencie agendamentos e heartbeats",
},
changeRequests: {
title: "Monitoramento de PR",
hint: "Acompanhe atualizações de pull requests e merge requests",
},
browser: {
title: "Navegador",
hint: "Controle abas do navegador do Paseo, incluindo sessões conectadas. Ative apenas para agentes confiáveis.",
},
},
},
orchestration: {
title: "Orquestração",
unavailable: "Conecte-se a este host para gerenciar a orquestração",
enableTools: {
title: "Ativar ferramentas do Paseo",
hint: "Agentes poderão gerenciar worktrees, agentes e agendamentos",
accessibilityLabel: "Injetar ferramentas do Paseo",
updateFailed: "Não foi possível atualizar as ferramentas do Paseo.",
title: "Ativar ferramentas",
hint: "Permite que o Paseo e plugins forneçam ferramentas aos agentes.",
accessibilityLabel: "Ativar ferramentas",
updateFailed: "Não foi possível atualizar as ferramentas.",
},
systemPrompt: {
title: "Prompt do sistema",
+25 -4
View File
@@ -196,6 +196,7 @@ export const ru: TranslationResources = {
removeReview: "Удалить вложение проверки",
},
errors: {
removePluginCommandAttachments: "Чтобы выполнить /{{command}}, удалите вложения.",
failedToSend: "Не удалось отправить сообщение",
failedToCreateAgent: "Не удалось создать агента.",
noHostSelected: "Хост не выбран",
@@ -3169,15 +3170,35 @@ export const ru: TranslationResources = {
tools: {
instructionsTitle: "Инструкции",
toolsTitle: "Инструменты агентов",
pluginNote: "Инструменты плагинов также зависят от переключателя «Включить инструменты»",
updateHostForGroups: "Обновите этот хост, чтобы настраивать отдельные группы инструментов",
groups: {
orchestration: {
title: "Оркестрация",
hint: "Управление рабочими пространствами, агентами, терминалами и скриптами",
},
schedules: {
title: "Расписания",
hint: "Создание и управление расписаниями и heartbeat",
},
changeRequests: {
title: "Отслеживание PR",
hint: "Отслеживание обновлений pull request и merge request",
},
browser: {
title: "Браузер",
hint: "Управление вкладками браузера Paseo, включая авторизованные сессии. Включайте только для доверенных агентов.",
},
},
},
orchestration: {
title: "Оркестрация",
unavailable: "Подключитесь к этому хосту, чтобы управлять оркестрацией.",
enableTools: {
title: "Включить инструменты Paseo",
hint: "Агенты смогут управлять worktree, агентами и расписаниями.",
accessibilityLabel: "Добавить инструменты Paseo",
updateFailed: "Не удалось обновить инструменты Paseo.",
title: "Включить инструменты",
hint: "Позволяет Paseo и плагинам предоставлять агентам инструменты.",
accessibilityLabel: "Включить инструменты",
updateFailed: "Не удалось обновить инструменты.",
},
systemPrompt: {
title: "Системный промпт",
+25 -4
View File
@@ -195,6 +195,7 @@ export const zhCN: TranslationResources = {
removeReview: "移除 review 附件",
},
errors: {
removePluginCommandAttachments: "请先移除附件,再运行 /{{command}}。",
failedToSend: "发送消息失败",
failedToCreateAgent: "创建 Agent 失败",
noHostSelected: "未选择 Host",
@@ -3080,15 +3081,35 @@ export const zhCN: TranslationResources = {
tools: {
instructionsTitle: "指令",
toolsTitle: "代理工具",
pluginNote: "插件提供的工具同样受“启用工具”开关控制",
updateHostForGroups: "更新此 Host 以单独配置各个工具组",
groups: {
orchestration: {
title: "编排",
hint: "管理工作区、智能体、终端和脚本",
},
schedules: {
title: "计划任务",
hint: "创建和管理计划任务与心跳",
},
changeRequests: {
title: "PR 监控",
hint: "监控 Pull Request 和 Merge Request 的更新",
},
browser: {
title: "浏览器",
hint: "控制 Paseo 浏览器标签页,包括已登录状态。仅对受信任的智能体启用。",
},
},
},
orchestration: {
title: "编排",
unavailable: "连接到这个 Host 以管理编排",
enableTools: {
title: "启用 Paseo tools",
hint: "Agent 将能够管理 worktree、Agent 和计划",
accessibilityLabel: "注入 Paseo tools",
updateFailed: "无法更新 Paseo 工具。",
title: "启用工具",
hint: "允许 Paseo 和插件为智能体提供工具。",
accessibilityLabel: "启用工具",
updateFailed: "无法更新工具设置。",
},
systemPrompt: {
title: "System prompt",
@@ -9,6 +9,11 @@ import {
import { useToast } from "@/contexts/toast-context";
import { useCliInstall } from "@/desktop/hooks/use-install-status";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostFeature } from "@/runtime/host-features";
import {
createOnboardingAgentToolsPatch,
isHostAgentToolsEnabled,
} from "@/screens/settings/agent-tools-config";
export type OrchestrationChoice = "tools" | "skills" | "cli";
type Choices = Record<OrchestrationChoice, boolean>;
@@ -39,6 +44,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
const toast = useToast();
const skills = useAgentSkills(serverId);
const cli = useCliInstall();
const supportsToolsConfig = useHostFeature(serverId, "daemonToolsConfig");
const { config, patchConfig } = useDaemonConfig(serverId);
const [chosen, setChosen] = useState<Choices>(ALL_ON);
// With nothing picked there is nothing to install, so skills read as off, as they do in Settings.
@@ -60,7 +66,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
// What the host and this computer have now, or null while it is still being read. A choice is
// skipped only when it is known to match; an unknown state is always written.
const toolsOn = config ? config.mcp.injectIntoAgents !== false : null;
const toolsEnabled = config ? isHostAgentToolsEnabled(config) : null;
const skillsInstalled = skills.status ? areSkillsInstalled(skills.status) : null;
const cliInstalled = cli.status ? cli.status.installed : null;
const { reconcile, uninstall } = skills;
@@ -68,16 +74,21 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
const offersSkills = offered.skills;
const offersCli = offered.cli;
const setTools = useCallback(
(on: boolean) =>
patchConfig({ mcp: { injectIntoAgents: on } })
.then(Boolean, () => false)
.then((done) => {
if (!done) toast.error(t("settings.host.orchestration.enableTools.updateFailed"));
return done;
}),
[patchConfig, t, toast],
);
const applyTools = useCallback(() => {
const patch = createOnboardingAgentToolsPatch({
enabled: choices.tools,
currentEnabled: toolsEnabled,
supportsToolsConfig,
});
if (!patch) return Promise.resolve(true);
return patchConfig(patch)
.then(Boolean, () => false)
.then((done) => {
if (!done) toast.error(t("settings.host.orchestration.enableTools.updateFailed"));
return done;
});
}, [choices.tools, toolsEnabled, patchConfig, supportsToolsConfig, t, toast]);
const setSkillsInstalled = useCallback(
(on: boolean) => (on ? reconcile() : uninstall()),
[reconcile, uninstall],
@@ -87,7 +98,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
setIsApplying(true);
try {
const results = await Promise.all([
choices.tools === toolsOn ? true : setTools(choices.tools),
applyTools(),
!offersSkills || choices.skills === skillsInstalled
? true
: setSkillsInstalled(choices.skills),
@@ -98,16 +109,23 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
setIsApplying(false);
}
}, [
choices,
toolsOn,
setTools,
offersSkills,
applyTools,
choices.cli,
choices.skills,
skillsInstalled,
setSkillsInstalled,
offersSkills,
offersCli,
cliInstalled,
setCliInstalled,
]);
return { choices, setChoice, offered, skills, isApplying, apply };
return {
choices,
setChoice,
offered,
skills,
isApplying,
apply,
};
}
@@ -2,7 +2,7 @@ import { useCallback } from "react";
import { AgentSkillsRow } from "@/agent-skills";
import { SettingsCard } from "@/components/settings";
import { CommandLineRow } from "@/desktop/components/integrations-section";
import { PaseoToolsRow } from "@/screens/settings/paseo-tools-card";
import { EnableToolsSwitchRow } from "@/screens/settings/agent-tools-row";
import type { OrchestrationSetupController } from "../orchestration-setup";
/** Three switches, all on to start; Continue applies them. */
@@ -13,7 +13,7 @@ export function OrchestrationStep({ setup }: { setup: OrchestrationSetupControll
const setCli = useCallback((on: boolean) => setChoice("cli", on), [setChoice]);
return (
<SettingsCard>
<PaseoToolsRow value={choices.tools} onValueChange={setTools} disabled={isApplying} />
<EnableToolsSwitchRow value={choices.tools} onValueChange={setTools} disabled={isApplying} />
{offered.skills ? (
<AgentSkillsRow
skills={setup.skills}
@@ -33,14 +33,12 @@ describe("plugin client slash commands", () => {
expect(
resolvePluginClientSlashCommand({
text: " /review foo bar ",
hasAttachments: false,
commands: [command],
}),
).toEqual({ command, args: "foo bar" });
expect(
resolvePluginClientSlashCommand({
text: "/review foo",
hasAttachments: true,
text: "/another-command foo",
commands: [command],
}),
).toBeNull();
@@ -47,10 +47,8 @@ export function mergeSlashCommandSources<
export function resolvePluginClientSlashCommand<Command extends SlashCommandDescriptor>(input: {
text: string;
hasAttachments: boolean;
commands: readonly Command[];
}): { command: Command; args: string } | null {
if (input.hasAttachments) return null;
const match = /^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(input.text.trim());
if (!match) return null;
const command = input.commands.find((candidate) => candidate.name === match[1]);
@@ -73,10 +73,29 @@ class FakeDirectoryClient {
return () => handlers.delete(registered);
}
private readonly rawListeners = new Set<(message: SessionOutboundMessage) => void>();
private readonly replyWaiters = new Map<string, () => void>();
subscribeRawMessages(handler: (message: SessionOutboundMessage) => void): () => void {
this.rawListeners.add(handler);
return () => this.rawListeners.delete(handler);
}
/** Resolves when a reply carrying `requestId` arrives, after every listener saw it. */
awaitReply(requestId: string): Promise<void> {
return new Promise((resolve) => this.replyWaiters.set(requestId, resolve));
}
emit<TType extends SessionOutboundMessage["type"]>(
message: Extract<SessionOutboundMessage, { type: TType }>,
): void {
for (const listener of this.rawListeners) listener(message);
for (const handler of this.handlers.get(message.type) ?? []) handler(message);
if (!("payload" in message)) return;
const requestId = (message.payload as { requestId?: unknown }).requestId;
if (typeof requestId !== "string") return;
this.replyWaiters.get(requestId)?.();
this.replyWaiters.delete(requestId);
}
holdWorkspaceFetch(): (result: WorkspaceFetchResult) => void {
@@ -2417,3 +2436,40 @@ it("coalesces duplicate upserts and removals within a single workspace_update ba
directory.dispose();
}
});
it("applies workspace updates the host sent before a reply by the time the reply resolves", async () => {
const serverId = "workspace-update-before-reply";
const { client, directory } = createDirectory(serverId);
const store = useSessionStore.getState();
store.initializeSession(serverId, client as unknown as DaemonClient, 1);
store.updateSessionServerInfo(serverId, {
serverId,
hostname: null,
version: "test",
features: { workspaceMultiplicity: true, directorySync: true },
});
directory.setDemand({}, true);
await directory.refreshDemand();
try {
const restored = client.awaitReply("restore-1");
client.emit({
type: "workspace_update",
payload: {
kind: "upsert",
workspace: createWorkspaceEntry("ws-restored"),
generation: "gen-restore",
seq: 1,
},
});
client.emit({
type: "workspace.recovery.restore.response",
payload: { requestId: "restore-1", workspaceId: "ws-restored", accepted: true, error: null },
});
await restored;
expect(useSessionStore.getState().sessions[serverId]?.workspaces.has("ws-restored")).toBe(true);
} finally {
directory.dispose();
}
});
@@ -4,7 +4,7 @@ import type {
FetchAgentsEntry,
FetchAgentsOptions,
} from "@getpaseo/client/internal/daemon-client";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import type { AgentSnapshotPayload, SessionOutboundMessage } from "@getpaseo/protocol/messages";
import { fetchAgentTimelineOnce } from "@/timeline/fetch-agent-timeline-once";
import {
normalizeProjectDescriptor,
@@ -49,6 +49,17 @@ interface WorkspaceDeltaFlushHandle {
cancel: () => void;
}
function isReply(message: SessionOutboundMessage): boolean {
if (!("payload" in message)) return false;
const payload: unknown = message.payload;
return (
typeof payload === "object" &&
payload !== null &&
"requestId" in payload &&
typeof payload.requestId === "string"
);
}
function scheduleWorkspaceDeltaFlush(callback: () => void): WorkspaceDeltaFlushHandle {
let done = false;
let rafId: number | null = null;
@@ -204,6 +215,7 @@ export class DirectorySync {
delta: WorkspaceDirectoryDelta;
}> = [];
private workspaceDeltaFlush: WorkspaceDeltaFlushHandle | null = null;
private stopObservingReplies: (() => void) | null = null;
constructor(
private readonly serverId: string,
@@ -235,10 +247,13 @@ export class DirectorySync {
this.flushAbortedTransactions();
this.releaseSubscriptions();
this.releaseScriptStatusEvents();
this.stopObservingReplies?.();
this.stopObservingReplies = null;
workspaceLabels.disconnect(this.serverId);
this.connection = connection;
this.abortPendingSessionWaits();
if (!connection.client || connection.status !== "online") return true;
this.stopObservingReplies = this.applyWorkspaceUpdatesBeforeReplies(connection.client);
if (this.scriptStatusDemand.size > 0) this.observeScriptStatusEvents();
// Reattach labels here because route-only demand can satisfy the epoch before full demand requests them.
void this.connectWorkspaceLabels().catch(() => undefined);
@@ -294,6 +309,8 @@ export class DirectorySync {
}
dispose(): void {
this.stopObservingReplies?.();
this.stopObservingReplies = null;
this.cancelPendingWorkspaceDeltas();
this.flushAbortedTransactions();
this.abortPendingSessionWaits();
@@ -357,6 +374,16 @@ export class DirectorySync {
this.applyWorkspaceDeltas([{ source, delta }]);
}
/**
* The host sends a workspace update before the reply to the request that caused it, so a
* caller reading the store after its reply must see the update. Buffered updates end at a reply.
*/
private applyWorkspaceUpdatesBeforeReplies(client: DaemonClient): () => void {
return client.subscribeRawMessages((message) => {
if (isReply(message)) this.flushPendingWorkspaceDeltas();
});
}
private flushPendingWorkspaceDeltas(): void {
if (this.workspaceDeltaFlush) {
this.workspaceDeltaFlush.cancel();
@@ -206,6 +206,10 @@ class FakeDaemonClient {
this.setConnectionState({ status: "connected" });
}
subscribeRawMessages(_handler: (message: SessionOutboundMessage) => void): () => void {
return () => {};
}
subscribeConnectionStatus(listener: (status: ConnectionState) => void): () => void {
this.listeners.add(listener);
listener(this.state);
@@ -0,0 +1,178 @@
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
import { describe, expect, it } from "vitest";
import {
createAgentToolGroupPatch,
createAgentToolsMasterPatch,
createOnboardingAgentToolsPatch,
DEFAULT_AGENT_TOOL_GROUPS,
isHostAgentToolsEnabled,
resolveAgentToolsState,
} from "./agent-tools-config";
function makeConfig(overrides: Partial<MutableDaemonConfig> = {}): MutableDaemonConfig {
return {
relay: { enabled: false },
mcp: { injectIntoAgents: true },
browserTools: { enabled: false },
providers: {},
metadataGeneration: { providers: [] },
autoArchiveAfterMerge: false,
enableTerminalAgentHooks: false,
appendSystemPrompt: "",
...overrides,
};
}
describe("agent tools UI state and legacy daemon compatibility", () => {
it("reads unified daemon.tools state from a modern daemon", () => {
const state = resolveAgentToolsState({
config: makeConfig({
tools: {
enabled: true,
groups: {
orchestration: true,
schedules: false,
changeRequests: true,
browser: true,
},
},
mcp: { injectIntoAgents: true },
browserTools: { enabled: true },
}),
supportsToolsConfig: true,
});
expect(state).toEqual({
enabled: true,
groups: {
orchestration: true,
schedules: false,
changeRequests: true,
browser: true,
},
supportsGroupControls: true,
});
});
it("preserves saved group values when master enabled is false", () => {
const state = resolveAgentToolsState({
config: makeConfig({
tools: {
enabled: false,
groups: {
orchestration: false,
schedules: true,
changeRequests: false,
browser: true,
},
},
mcp: { injectIntoAgents: false },
browserTools: { enabled: true },
}),
supportsToolsConfig: true,
});
expect(state.enabled).toBe(false);
expect(state.groups).toEqual({
orchestration: false,
schedules: true,
changeRequests: false,
browser: true,
});
});
it("falls back cleanly to legacy mcp.injectIntoAgents and browserTools.enabled on older daemons", () => {
const state = resolveAgentToolsState({
config: makeConfig({
mcp: { injectIntoAgents: false },
browserTools: { enabled: true },
}),
supportsToolsConfig: false,
});
expect(state).toEqual({
enabled: false,
groups: {
...DEFAULT_AGENT_TOOL_GROUPS,
browser: true,
},
supportsGroupControls: false,
});
});
it("builds tools.* patches for modern daemons and legacy mcp/browserTools patches for older daemons", () => {
expect(createAgentToolsMasterPatch({ enabled: false, supportsToolsConfig: true })).toEqual({
tools: { enabled: false },
});
expect(createAgentToolsMasterPatch({ enabled: false, supportsToolsConfig: false })).toEqual({
mcp: { injectIntoAgents: false },
});
expect(
createAgentToolGroupPatch({
group: "schedules",
enabled: false,
supportsToolsConfig: true,
}),
).toEqual({
tools: { groups: { schedules: false } },
});
expect(
createAgentToolGroupPatch({
group: "browser",
enabled: true,
supportsToolsConfig: false,
}),
).toEqual({
browserTools: { enabled: true },
});
expect(
createAgentToolGroupPatch({
group: "orchestration",
enabled: false,
supportsToolsConfig: false,
}),
).toBeNull();
});
it("setup writes only the main switch, and only when it differs from the host", () => {
expect(
createOnboardingAgentToolsPatch({
enabled: true,
currentEnabled: true,
supportsToolsConfig: true,
}),
).toBeNull();
expect(
createOnboardingAgentToolsPatch({
enabled: true,
currentEnabled: false,
supportsToolsConfig: true,
}),
).toEqual({ tools: { enabled: true } });
expect(
createOnboardingAgentToolsPatch({
enabled: true,
currentEnabled: null,
supportsToolsConfig: true,
}),
).toEqual({ tools: { enabled: true } });
expect(
createOnboardingAgentToolsPatch({
enabled: false,
currentEnabled: true,
supportsToolsConfig: false,
}),
).toEqual({ mcp: { injectIntoAgents: false } });
});
it("reports whether host agent tools are enabled", () => {
expect(isHostAgentToolsEnabled(null)).toBe(true);
expect(isHostAgentToolsEnabled(makeConfig({ tools: { enabled: true } }))).toBe(true);
expect(isHostAgentToolsEnabled(makeConfig({ tools: { enabled: false } }))).toBe(false);
expect(isHostAgentToolsEnabled(makeConfig({ mcp: { injectIntoAgents: false } }))).toBe(false);
});
});
@@ -0,0 +1,85 @@
import {
BUILTIN_TOOL_GROUPS,
DEFAULT_DAEMON_TOOL_GROUPS,
type BuiltInToolGroup,
type MutableDaemonConfig,
type MutableDaemonConfigPatch,
} from "@getpaseo/protocol/messages";
export type AgentToolGroupId = BuiltInToolGroup;
export type AgentToolGroupsState = Record<AgentToolGroupId, boolean>;
export const AGENT_TOOL_GROUP_ORDER: readonly AgentToolGroupId[] = BUILTIN_TOOL_GROUPS;
export const DEFAULT_AGENT_TOOL_GROUPS: AgentToolGroupsState = { ...DEFAULT_DAEMON_TOOL_GROUPS };
export interface ResolvedAgentToolsState {
enabled: boolean;
groups: AgentToolGroupsState;
supportsGroupControls: boolean;
}
export function isHostAgentToolsEnabled(config: MutableDaemonConfig | null | undefined): boolean {
if (!config) return true;
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
return config.tools?.enabled ?? config.mcp.injectIntoAgents !== false;
}
export function resolveAgentToolsState(input: {
config: MutableDaemonConfig | null | undefined;
supportsToolsConfig: boolean;
}): ResolvedAgentToolsState {
const { config, supportsToolsConfig } = input;
const enabled = isHostAgentToolsEnabled(config);
const groups: AgentToolGroupsState = {
orchestration: config?.tools?.groups?.orchestration ?? DEFAULT_AGENT_TOOL_GROUPS.orchestration,
schedules: config?.tools?.groups?.schedules ?? DEFAULT_AGENT_TOOL_GROUPS.schedules,
changeRequests:
config?.tools?.groups?.changeRequests ?? DEFAULT_AGENT_TOOL_GROUPS.changeRequests,
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
browser: config?.tools?.groups?.browser ?? config?.browserTools.enabled === true,
};
return {
enabled,
groups,
supportsGroupControls: supportsToolsConfig,
};
}
export function createAgentToolsMasterPatch(input: {
enabled: boolean;
supportsToolsConfig: boolean;
}): MutableDaemonConfigPatch {
if (input.supportsToolsConfig) {
return { tools: { enabled: input.enabled } };
}
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
return { mcp: { injectIntoAgents: input.enabled } };
}
export function createAgentToolGroupPatch(input: {
group: AgentToolGroupId;
enabled: boolean;
supportsToolsConfig: boolean;
}): MutableDaemonConfigPatch | null {
if (input.supportsToolsConfig) {
return { tools: { groups: { [input.group]: input.enabled } } };
}
// COMPAT(daemonToolsConfig): added in v0.18.2, remove after 2027-06-01.
if (input.group === "browser") {
return { browserTools: { enabled: input.enabled } };
}
return null;
}
/**
* Setup only sets the main switch. It never writes tool groups, so the host keeps the groups saved
* in Settings. An unknown host state is always written.
*/
export function createOnboardingAgentToolsPatch(input: {
enabled: boolean;
currentEnabled: boolean | null;
supportsToolsConfig: boolean;
}): MutableDaemonConfigPatch | null {
if (input.currentEnabled === input.enabled) return null;
return createAgentToolsMasterPatch(input);
}
@@ -0,0 +1,147 @@
import React, { act, useCallback, useState } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, describe, expect, it } from "vitest";
import { I18nextProvider } from "react-i18next";
import { SettingsCard } from "@/components/settings";
import { i18n } from "@/i18n/i18next";
import {
DEFAULT_AGENT_TOOL_GROUPS,
type AgentToolGroupId,
type AgentToolGroupsState,
} from "./agent-tools-config";
import { AgentToolsRow } from "./agent-tools-row";
let root: Root | null = null;
let container: HTMLDivElement | null = null;
afterEach(() => {
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
function Harness({
initialEnabled = true,
initialGroups = DEFAULT_AGENT_TOOL_GROUPS,
supportsGroupControls = true,
}: {
initialEnabled?: boolean;
initialGroups?: AgentToolGroupsState;
supportsGroupControls?: boolean;
}) {
const [enabled, setEnabled] = useState(initialEnabled);
const [groups, setGroups] = useState<AgentToolGroupsState>(initialGroups);
const handleGroupChange = useCallback((group: AgentToolGroupId, next: boolean) => {
setGroups((current) => ({ ...current, [group]: next }));
}, []);
return (
<I18nextProvider i18n={i18n}>
<SettingsCard>
<AgentToolsRow
enabled={enabled}
groups={groups}
supportsGroupControls={supportsGroupControls}
onEnabledChange={setEnabled}
onGroupChange={handleGroupChange}
/>
</SettingsCard>
</I18nextProvider>
);
}
function mount(props?: React.ComponentProps<typeof Harness>) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => {
root?.render(<Harness {...props} />);
});
}
function byTestId(testID: string): HTMLElement | null {
return document.querySelector(`[data-testid="${testID}"]`);
}
function expandButton(): HTMLElement {
const row = byTestId("host-page-tools-row-toggle");
const button = row?.querySelector('[role="button"]');
if (!(button instanceof HTMLElement)) {
throw new Error("Expected expand button in host-page-tools-row-toggle");
}
return button;
}
describe("AgentToolsRow collapsible behavior", () => {
it("starts collapsed, expands to show all four groups, and preserves selections when toggled off and on", () => {
mount({
initialEnabled: true,
initialGroups: {
orchestration: true,
schedules: false,
changeRequests: true,
browser: true,
},
});
const masterSwitch = byTestId("host-page-tools-master-switch");
expect(masterSwitch?.getAttribute("aria-checked")).toBe("true");
expect(byTestId("host-page-tool-group-orchestration")).toBeNull();
// Expand the row
act(() => {
expandButton().click();
});
expect(byTestId("host-page-tool-group-orchestration")).not.toBeNull();
expect(byTestId("host-page-tool-group-schedules")).not.toBeNull();
expect(byTestId("host-page-tool-group-changeRequests")).not.toBeNull();
expect(byTestId("host-page-browser-tools-card")).not.toBeNull();
expect(document.body.textContent).toContain("Tools added by plugins also follow Enable tools");
expect(document.body.textContent).not.toContain("MCP");
const browserSwitch = byTestId("host-page-browser-tools-switch")!;
const schedulesSwitch = byTestId("host-page-tool-group-schedules-switch")!;
expect(browserSwitch.getAttribute("aria-checked")).toBe("true");
expect(schedulesSwitch.getAttribute("aria-checked")).toBe("false");
expect(browserSwitch.getAttribute("aria-disabled")).not.toBe("true");
// Turn master switch off: stays expanded, disables group switches, preserves selections
act(() => {
masterSwitch?.click();
});
expect(masterSwitch?.getAttribute("aria-checked")).toBe("false");
expect(browserSwitch.getAttribute("aria-disabled")).toBe("true");
expect(browserSwitch.getAttribute("aria-checked")).toBe("true");
expect(schedulesSwitch.getAttribute("aria-disabled")).toBe("true");
expect(schedulesSwitch.getAttribute("aria-checked")).toBe("false");
// Turn master switch back on: group switches become interactive again with saved state
act(() => {
masterSwitch?.click();
});
expect(masterSwitch?.getAttribute("aria-checked")).toBe("true");
expect(browserSwitch.getAttribute("aria-disabled")).not.toBe("true");
expect(browserSwitch.getAttribute("aria-checked")).toBe("true");
});
it("shows only Browser and an update hint on older daemons without daemonToolsConfig", () => {
mount({ supportsGroupControls: false });
act(() => {
expandButton().click();
});
expect(byTestId("host-page-browser-tools-card")).not.toBeNull();
expect(byTestId("host-page-tool-group-orchestration")).toBeNull();
expect(byTestId("host-page-tool-group-schedules")).toBeNull();
expect(byTestId("host-page-tool-group-changeRequests")).toBeNull();
expect(document.body.textContent).toContain(
"Update this host to configure individual tool groups",
);
});
});
@@ -0,0 +1,272 @@
import { useMutation } from "@tanstack/react-query";
import { useCallback, useMemo } from "react";
import { Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import type { MutableDaemonConfigPatch } from "@getpaseo/protocol/messages";
import { SettingsCollapsibleRow, SettingsRow } from "@/components/settings";
import { Switch } from "@/components/ui/switch";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostFeature } from "@/runtime/host-features";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
import {
AGENT_TOOL_GROUP_ORDER,
createAgentToolGroupPatch,
createAgentToolsMasterPatch,
resolveAgentToolsState,
type AgentToolGroupId,
type AgentToolGroupsState,
} from "./agent-tools-config";
const GROUP_TRANSLATION_KEYS: Record<
AgentToolGroupId,
{
title:
| "settings.host.tools.groups.orchestration.title"
| "settings.host.tools.groups.schedules.title"
| "settings.host.tools.groups.changeRequests.title"
| "settings.host.tools.groups.browser.title";
hint:
| "settings.host.tools.groups.orchestration.hint"
| "settings.host.tools.groups.schedules.hint"
| "settings.host.tools.groups.changeRequests.hint"
| "settings.host.tools.groups.browser.hint";
}
> = {
orchestration: {
title: "settings.host.tools.groups.orchestration.title",
hint: "settings.host.tools.groups.orchestration.hint",
},
schedules: {
title: "settings.host.tools.groups.schedules.title",
hint: "settings.host.tools.groups.schedules.hint",
},
changeRequests: {
title: "settings.host.tools.groups.changeRequests.title",
hint: "settings.host.tools.groups.changeRequests.hint",
},
browser: {
title: "settings.host.tools.groups.browser.title",
hint: "settings.host.tools.groups.browser.hint",
},
};
function toErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function resolveHintStatus(
error: string | null | undefined,
isPending: boolean | undefined,
): "error" | "busy" | undefined {
if (error) return "error";
if (isPending) return "busy";
return undefined;
}
/** The host's expandable "Enable tools" row, bound to the host's config, for composing inside a SettingsCard. */
export function HostAgentToolsRow({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const isConnected = useHostRuntimeIsConnected(serverId);
const supportsToolsConfig = useHostFeature(serverId, "daemonToolsConfig");
const { config, patchConfig } = useDaemonConfig(serverId);
const state = useMemo(
() => resolveAgentToolsState({ config, supportsToolsConfig }),
[config, supportsToolsConfig],
);
const mutation = useMutation({
mutationFn: async (patch: MutableDaemonConfigPatch) => {
const result = await patchConfig(patch);
if (!result) {
throw new Error(t("workspace.terminal.hostDisconnected"));
}
return result;
},
});
const handleEnabledChange = useCallback(
(enabled: boolean) => {
mutation.mutate(createAgentToolsMasterPatch({ enabled, supportsToolsConfig }));
},
[mutation, supportsToolsConfig],
);
const handleGroupChange = useCallback(
(group: AgentToolGroupId, enabled: boolean) => {
const patch = createAgentToolGroupPatch({ group, enabled, supportsToolsConfig });
if (!patch) return;
mutation.mutate(patch);
},
[mutation, supportsToolsConfig],
);
if (!isConnected) return null;
return (
<AgentToolsRow
enabled={state.enabled}
groups={state.groups}
supportsGroupControls={state.supportsGroupControls}
onEnabledChange={handleEnabledChange}
onGroupChange={handleGroupChange}
isPending={mutation.isPending}
error={mutation.error ? toErrorMessage(mutation.error) : null}
/>
);
}
/** Plain "Enable tools" switch with no group controls, for setup. Groups stay in Settings. */
export function EnableToolsSwitchRow({
value,
onValueChange,
disabled,
}: {
value: boolean;
onValueChange: (enabled: boolean) => void;
disabled?: boolean;
}) {
const { t } = useTranslation();
return (
<SettingsRow
label={t("settings.host.orchestration.enableTools.title")}
hint={t("settings.host.orchestration.enableTools.hint")}
>
<Switch
value={value}
onValueChange={onValueChange}
disabled={disabled}
accessibilityLabel={t("settings.host.orchestration.enableTools.accessibilityLabel")}
/>
</SettingsRow>
);
}
/** Expandable "Enable tools" row on its own, for callers that control the state. */
export function AgentToolsRow({
enabled,
groups,
supportsGroupControls,
onEnabledChange,
onGroupChange,
disabled,
isPending,
error,
}: {
enabled: boolean;
groups: AgentToolGroupsState;
supportsGroupControls: boolean;
onEnabledChange: (enabled: boolean) => void;
onGroupChange: (group: AgentToolGroupId, enabled: boolean) => void;
disabled?: boolean;
isPending?: boolean;
error?: string | null;
}) {
const { t } = useTranslation();
const visibleGroups: readonly AgentToolGroupId[] = supportsGroupControls
? AGENT_TOOL_GROUP_ORDER
: ["browser"];
const controlsDisabled = Boolean(disabled || isPending);
const hint = error ?? t("settings.host.orchestration.enableTools.hint");
const hintStatus = resolveHintStatus(error, isPending);
const masterControl = useMemo(
() => (
<Switch
value={enabled}
onValueChange={onEnabledChange}
disabled={controlsDisabled}
accessibilityLabel={t("settings.host.orchestration.enableTools.accessibilityLabel")}
testID="host-page-tools-master-switch"
/>
),
[controlsDisabled, enabled, onEnabledChange, t],
);
return (
<SettingsCollapsibleRow
label={t("settings.host.orchestration.enableTools.title")}
hint={hint}
hintStatus={hintStatus}
control={masterControl}
testID="host-page-tools-row"
>
{visibleGroups.map((group) => (
<ToolGroupSwitchRow
key={group}
group={group}
value={groups[group]}
disabled={controlsDisabled || !enabled}
dimmed={!enabled}
onGroupChange={onGroupChange}
/>
))}
<View style={styles.noteRow}>
<Text style={settingsStyles.rowHint}>
{supportsGroupControls
? t("settings.host.tools.pluginNote")
: t("settings.host.tools.updateHostForGroups")}
</Text>
</View>
</SettingsCollapsibleRow>
);
}
function ToolGroupSwitchRow({
group,
value,
disabled,
dimmed,
onGroupChange,
}: {
group: AgentToolGroupId;
value: boolean;
disabled: boolean;
dimmed: boolean;
onGroupChange: (group: AgentToolGroupId, enabled: boolean) => void;
}) {
const { t } = useTranslation();
const keys = GROUP_TRANSLATION_KEYS[group];
const label = t(keys.title);
const handleChange = useCallback(
(next: boolean) => {
onGroupChange(group, next);
},
[group, onGroupChange],
);
return (
<View style={dimmed ? styles.disabledGroup : undefined}>
<SettingsRow
label={label}
hint={t(keys.hint)}
testID={
group === "browser" ? "host-page-browser-tools-card" : `host-page-tool-group-${group}`
}
>
<Switch
value={value}
onValueChange={handleChange}
disabled={disabled}
accessibilityLabel={label}
testID={
group === "browser"
? "host-page-browser-tools-switch"
: `host-page-tool-group-${group}-switch`
}
/>
</SettingsRow>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
disabledGroup: {
opacity: theme.opacity[50],
},
noteRow: {
paddingHorizontal: theme.spacing[4],
paddingVertical: theme.spacing[2],
},
}));
@@ -1,74 +0,0 @@
import React, { useCallback, useMemo } from "react";
import { Text, View } from "react-native";
import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { SettingsRow } from "@/components/settings";
import { Switch } from "@/components/ui/switch";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { settingsStyles } from "@/styles/settings";
import {
createBrowserToolsPatch,
getBrowserToolsCardState,
getBrowserToolsMutationViewState,
} from "./browser-tools-config";
export function BrowserToolsRow({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const isConnected = useHostRuntimeIsConnected(serverId);
const { config, patchConfig } = useDaemonConfig(serverId);
const state = getBrowserToolsCardState({ isConnected, config });
const mutation = useMutation({
mutationFn: async (next: boolean) => {
const result = await patchConfig(createBrowserToolsPatch(next));
if (!result) {
throw new Error(t("workspace.terminal.hostDisconnected"));
}
return result;
},
});
const mutationView = getBrowserToolsMutationViewState({
isPending: mutation.isPending,
error: mutation.error,
});
const handleValueChange = useCallback(
(next: boolean) => {
mutation.mutate(next);
},
[mutation],
);
const hint = useMemo(
() => (
<View>
<Text style={settingsStyles.rowHint}>{state.warning}</Text>
{mutationView.loadingText ? (
<Text style={settingsStyles.rowHint} testID="host-page-browser-tools-loading">
{mutationView.loadingText}
</Text>
) : null}
</View>
),
[mutationView.loadingText, state.warning],
);
if (!state.isVisible) return null;
return (
<SettingsRow
label={state.title}
hint={hint}
error={mutationView.errorText ?? undefined}
testID="host-page-browser-tools-card"
>
<Switch
value={state.isEnabled}
onValueChange={handleValueChange}
disabled={mutationView.isSwitchDisabled}
accessibilityLabel="Enable browser tools"
testID="host-page-browser-tools-switch"
/>
</SettingsRow>
);
}
@@ -1,71 +0,0 @@
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
import { describe, expect, it } from "vitest";
import {
BROWSER_TOOLS_WARNING,
createBrowserToolsPatch,
getBrowserToolsCardState,
getBrowserToolsMutationViewState,
} from "./browser-tools-config";
function makeConfig(browserToolsEnabled = false): MutableDaemonConfig {
return {
relay: { enabled: false },
mcp: { injectIntoAgents: false },
browserTools: { enabled: browserToolsEnabled },
providers: {},
metadataGeneration: { providers: [] },
autoArchiveAfterMerge: false,
enableTerminalAgentHooks: false,
appendSystemPrompt: "",
};
}
describe("browser tools opt-in config", () => {
it("shows the card with the logged-in browser state warning when connected", () => {
expect(getBrowserToolsCardState({ isConnected: true, config: makeConfig(false) })).toEqual({
isVisible: true,
isEnabled: false,
title: "Browser tools",
warning: BROWSER_TOOLS_WARNING,
});
});
it("reads enabled state from daemon config", () => {
expect(getBrowserToolsCardState({ isConnected: true, config: makeConfig(true) })).toMatchObject(
{
isEnabled: true,
},
);
});
it("hides the card when the host is disconnected", () => {
expect(
getBrowserToolsCardState({ isConnected: false, config: makeConfig(true) }),
).toMatchObject({
isVisible: false,
});
});
it("writes daemon.browserTools.enabled when toggled", () => {
expect(createBrowserToolsPatch(true)).toEqual({ browserTools: { enabled: true } });
expect(createBrowserToolsPatch(false)).toEqual({ browserTools: { enabled: false } });
});
it("shows loading and disables the toggle while browser tool settings save", () => {
expect(getBrowserToolsMutationViewState({ isPending: true, error: null })).toEqual({
isSwitchDisabled: true,
loadingText: "Updating browser tools…",
errorText: null,
});
});
it("shows the save error when browser tool settings fail", () => {
expect(
getBrowserToolsMutationViewState({ isPending: false, error: new Error("Disk full") }),
).toEqual({
isSwitchDisabled: false,
loadingText: null,
errorText: "Disk full",
});
});
});
@@ -1,49 +0,0 @@
import type { MutableDaemonConfig } from "@getpaseo/protocol/messages";
export const BROWSER_TOOLS_TITLE = "Browser tools";
export const BROWSER_TOOLS_WARNING =
"Allow agents to access and control Paseo browser tabs, including logged-in browser state. Only enable this for agents you trust.";
export interface BrowserToolsCardState {
isVisible: boolean;
isEnabled: boolean;
title: string;
warning: string;
}
export interface BrowserToolsMutationViewState {
isSwitchDisabled: boolean;
loadingText: string | null;
errorText: string | null;
}
export function getBrowserToolsCardState(input: {
isConnected: boolean;
config: MutableDaemonConfig | null;
}): BrowserToolsCardState {
return {
isVisible: input.isConnected,
isEnabled: input.config?.browserTools.enabled === true,
title: BROWSER_TOOLS_TITLE,
warning: BROWSER_TOOLS_WARNING,
};
}
export function createBrowserToolsPatch(enabled: boolean): Partial<MutableDaemonConfig> {
return { browserTools: { enabled } };
}
export function getBrowserToolsMutationViewState(input: {
isPending: boolean;
error: unknown;
}): BrowserToolsMutationViewState {
return {
isSwitchDisabled: input.isPending,
loadingText: input.isPending ? "Updating browser tools…" : null,
errorText: input.error ? toErrorMessage(input.error) : null,
};
}
function toErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
@@ -61,8 +61,7 @@ import { formatConnectionStatus, getConnectionStatusTone } from "@/utils/daemons
import { ICON_SIZE } from "@/styles/theme";
import type { Theme } from "@/styles/theme";
import { useProviderIcon } from "@/components/provider-icons";
import { BrowserToolsRow } from "./browser-tools-card";
import { HostPaseoToolsRow } from "./paseo-tools-card";
import { HostAgentToolsRow } from "./agent-tools-row";
import { RestartRecoveryRow } from "./restart-recovery-card";
import { IdleRuntimeCleanupRow } from "./idle-runtime-cleanup-card";
import { restartDaemonFromSettings, updateDaemonFromSettings } from "./daemon-lifecycle";
@@ -261,8 +260,7 @@ export function HostToolsPage({ serverId }: { serverId: string }) {
</SettingsSection>
<SettingsSection title={t("settings.host.tools.toolsTitle")}>
<SettingsCard testID="host-page-inject-mcp-card">
<HostPaseoToolsRow serverId={serverId} />
<BrowserToolsRow serverId={serverId} />
<HostAgentToolsRow serverId={serverId} />
</SettingsCard>
</SettingsSection>
</>
@@ -1,54 +0,0 @@
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { SettingsRow } from "@/components/settings";
import { Switch } from "@/components/ui/switch";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
/** The host's "give agents Paseo tools" row, bound to the host's config, for composing inside a SettingsCard. */
export function HostPaseoToolsRow({ serverId }: { serverId: string }) {
const isConnected = useHostRuntimeIsConnected(serverId);
const { config, patchConfig } = useDaemonConfig(serverId);
const handleValueChange = useCallback(
(next: boolean) => {
void patchConfig({ mcp: { injectIntoAgents: next } });
},
[patchConfig],
);
if (!isConnected) return null;
return (
<PaseoToolsRow
value={config?.mcp.injectIntoAgents !== false}
onValueChange={handleValueChange}
/>
);
}
/** The Paseo tools row on its own, for a caller that decides what the switch is bound to. */
export function PaseoToolsRow({
value,
onValueChange,
disabled,
}: {
value: boolean;
onValueChange: (next: boolean) => void;
disabled?: boolean;
}) {
const { t } = useTranslation();
return (
<SettingsRow
label={t("settings.host.orchestration.enableTools.title")}
hint={t("settings.host.orchestration.enableTools.hint")}
>
<Switch
value={value}
onValueChange={onValueChange}
disabled={disabled}
accessibilityLabel={t("settings.host.orchestration.enableTools.accessibilityLabel")}
/>
</SettingsRow>
);
}
@@ -0,0 +1,62 @@
// @vitest-environment jsdom
import { render } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { RetainedPanelActivity } from "@/components/retained-panel";
import {
createPostRestoreRevealHolds,
type PostRestoreRevealHolds,
PostRestoreRevealHoldsProvider,
usePostRestoreRevealHold,
} from "./post-restore-reveal-holds";
function Chrome({ pending }: { pending: boolean }) {
usePostRestoreRevealHold(pending);
return null;
}
function Workspace(props: {
holds: PostRestoreRevealHolds | null;
pending: boolean;
onScreen: boolean;
mounted?: boolean;
}) {
return (
<PostRestoreRevealHoldsProvider holds={props.holds}>
<RetainedPanelActivity active={props.onScreen}>
{props.mounted === false ? null : <Chrome pending={props.pending} />}
</RetainedPanelActivity>
</PostRestoreRevealHoldsProvider>
);
}
describe("post-restore reveal holds", () => {
it("holds the reveal while on-screen chrome is pending and releases when it settles", () => {
const holds = createPostRestoreRevealHolds();
const view = render(<Workspace holds={holds} pending onScreen />);
expect(holds.isHeld()).toBe(true);
view.rerender(<Workspace holds={holds} pending={false} onScreen />);
expect(holds.isHeld()).toBe(false);
});
it("does not hold for chrome in a hidden pane", () => {
const holds = createPostRestoreRevealHolds();
render(<Workspace holds={holds} pending onScreen={false} />);
expect(holds.isHeld()).toBe(false);
});
it("releases when pending chrome unmounts", () => {
const holds = createPostRestoreRevealHolds();
const view = render(<Workspace holds={holds} pending onScreen />);
view.rerender(<Workspace holds={holds} pending onScreen mounted={false} />);
expect(holds.isHeld()).toBe(false);
});
it("releases when the handoff ends and the provider stops offering holds", () => {
const holds = createPostRestoreRevealHolds();
const view = render(<Workspace holds={holds} pending onScreen />);
view.rerender(<Workspace holds={null} pending onScreen />);
expect(holds.isHeld()).toBe(false);
});
});
@@ -0,0 +1,77 @@
import {
createContext,
type ReactNode,
useContext,
useLayoutEffect,
useSyncExternalStore,
} from "react";
import { useRetainedPanelActive } from "@/components/retained-panel";
/**
* Workspace chrome mounted behind the `Restoring...` gate that has nothing to show until a layout
* pass answers it. The gate stays up while any on-screen chrome holds it.
*/
export interface PostRestoreRevealHolds {
hold: () => () => void;
subscribe: (listener: () => void) => () => void;
isHeld: () => boolean;
}
export function createPostRestoreRevealHolds(): PostRestoreRevealHolds {
let count = 0;
const listeners = new Set<() => void>();
const notify = () => {
for (const listener of listeners) listener();
};
return {
hold: () => {
count += 1;
notify();
let released = false;
return () => {
if (released) return;
released = true;
count -= 1;
notify();
};
},
subscribe: (listener) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
isHeld: () => count > 0,
};
}
const PostRestoreRevealHoldsContext = createContext<PostRestoreRevealHolds | null>(null);
/** `holds` is null outside a post-restore handoff, so chrome mounting normally never holds. */
export function PostRestoreRevealHoldsProvider({
holds,
children,
}: {
holds: PostRestoreRevealHolds | null;
children: ReactNode;
}) {
return <PostRestoreRevealHoldsContext value={holds}>{children}</PostRestoreRevealHoldsContext>;
}
/**
* Holds the post-restore reveal while `pending`. A hidden pane or a closed explorer never lays
* out, so only chrome that is on screen holds.
*/
export function usePostRestoreRevealHold(pending: boolean): void {
const holds = useContext(PostRestoreRevealHoldsContext);
const isOnScreen = useRetainedPanelActive();
const isHolding = pending && isOnScreen;
useLayoutEffect(() => {
if (!isHolding || !holds) return;
return holds.hold();
}, [holds, isHolding]);
}
export function usePostRestoreRevealHeld(holds: PostRestoreRevealHolds): boolean {
return useSyncExternalStore(holds.subscribe, holds.isHeld, holds.isHeld);
}
@@ -1,4 +1,9 @@
import { useCallback, useEffect, useState, useSyncExternalStore } from "react";
import {
createPostRestoreRevealHolds,
type PostRestoreRevealHolds,
usePostRestoreRevealHeld,
} from "@/screens/workspace/post-restore-reveal-holds";
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import type { WorkspaceRouteState } from "@/screens/workspace/workspace-route-state";
@@ -101,6 +106,7 @@ export function resolvePostRestoreDisplayedRouteState(input: {
visibleAgentsTimelineSynced: boolean;
visibleAgentsVisibilityStatus: ViewedTimelineStatus;
visibleAgentsLoadingOlder: boolean;
isRevealHeld: boolean;
routeState: WorkspaceRouteState;
}): {
displayedRouteState: WorkspaceRouteState;
@@ -119,6 +125,7 @@ export function resolvePostRestoreDisplayedRouteState(input: {
visibleAgentsTimelineSynced,
visibleAgentsVisibilityStatus,
visibleAgentsLoadingOlder,
isRevealHeld,
routeState,
} = input;
const isRestoringNow =
@@ -138,6 +145,7 @@ export function resolvePostRestoreDisplayedRouteState(input: {
const isHandoffReadyToMount = hasReconciledTabs && areVisibleAgentsReadyToMount;
const isHandoffReadyToRelease =
isHandoffReadyToMount &&
!isRevealHeld &&
(visibleAgentsVisibilityStatus === "error" || !visibleAgentsLoadingOlder);
return {
displayedRouteState: isWaitingForHandoffReveal ? handoff.archivedState : routeState,
@@ -168,6 +176,7 @@ export function usePostRestoreWorkspaceRouteState(input: {
paneFocusSuspended: boolean;
}): {
displayedRouteState: WorkspaceRouteState;
revealHolds: PostRestoreRevealHolds;
isHoldingHandoff: boolean;
isPaneRouteFocused: boolean;
effectivePaneFocusSuspended: boolean;
@@ -191,6 +200,8 @@ export function usePostRestoreWorkspaceRouteState(input: {
const scopeKey = `${serverId}:${workspaceId}`;
const [handoff, setHandoff] = useState<PostRestoreHandoffState | null>(null);
const [mountedHandoff, setMountedHandoff] = useState<PostRestoreHandoffState | null>(null);
const [revealHolds] = useState(createPostRestoreRevealHolds);
const isRevealHeld = usePostRestoreRevealHeld(revealHolds);
const reconciledHandoff = nextPostRestoreHandoff({ current: handoff, scopeKey, routeState });
if (reconciledHandoff !== handoff) {
@@ -271,6 +282,7 @@ export function usePostRestoreWorkspaceRouteState(input: {
visibleAgentsTimelineSynced,
visibleAgentsVisibilityStatus,
visibleAgentsLoadingOlder,
isRevealHeld,
routeState,
});
@@ -286,8 +298,8 @@ export function usePostRestoreWorkspaceRouteState(input: {
useEffect(() => {
if (!isWaitingForHandoffReveal) return;
if (isHandoffReadyToRelease) {
// Wait 3 rAFs after hidden workspace chrome mounts so tab label `onLayout` and stream row
// ResizeObservers commit (and any underfilled history fetch starts) before lifting overlay.
// Chrome that waits on its own layout (tab label measurement) holds the reveal explicitly.
// The frames let stream row ResizeObservers commit and any underfilled history fetch start.
return scheduleAnimationFrames(POST_RESTORE_LAYOUT_SETTLE_FRAMES, () => {
setHandoff(null);
});
@@ -300,6 +312,7 @@ export function usePostRestoreWorkspaceRouteState(input: {
return {
displayedRouteState,
revealHolds,
isHoldingHandoff: isMountedBehindOverlay,
isPaneRouteFocused: isRouteFocused && !isMountedBehindOverlay,
effectivePaneFocusSuspended: paneFocusSuspended || isMountedBehindOverlay,
@@ -96,6 +96,7 @@ import {
useHorizontalScrollBoundary,
} from "@/components/ui/horizontal-scroll-boundary";
import { useSessionStore } from "@/stores/session-store";
import { usePostRestoreRevealHold } from "@/screens/workspace/post-restore-reveal-holds";
const DROPDOWN_WIDTH = 220;
const DEFAULT_INLINE_ADD_BUTTON_RESERVED_WIDTH = 36;
@@ -1062,6 +1063,7 @@ export function WorkspaceDesktopTabsRow(props: WorkspaceDesktopTabsRowProps) {
}),
[presentations, props.tabs],
);
usePostRestoreRevealHold(resolvedTabs.length < props.tabs.length);
return (
<>
@@ -1245,6 +1247,7 @@ function ResolvedWorkspaceDesktopTabsRow({
useLayoutEffect(() => {
publishMeasuredTrack();
}, [publishMeasuredTrack]);
usePostRestoreRevealHold(tabs.length > 0 && trackSnapshot?.signature !== tabLabelSignature);
const handleTabLabelLayout = useCallback(
(key: string, label: string, event: LayoutChangeEvent) => {
@@ -264,6 +264,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(waitingTabs.displayedRouteState).toBe(restoringState);
@@ -283,6 +284,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: false,
visibleAgentsVisibilityStatus: "checking",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(waitingTimeline.displayedRouteState).toBe(restoringState);
@@ -301,6 +303,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "checking",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(waitingCatchUp.displayedRouteState).toBe(restoringState);
@@ -319,6 +322,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: true,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(waitingOlderFill.isHandoffReadyToMount).toBe(true);
@@ -336,6 +340,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(revealed.displayedRouteState).toBe(restoringState);
@@ -355,6 +360,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(cleared.displayedRouteState).toEqual({ kind: "ready" });
@@ -372,11 +378,38 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: false,
visibleAgentsVisibilityStatus: "error",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(errored.isHandoffReadyToRelease).toBe(true);
});
it("keeps Restoring up while on-screen workspace chrome holds the reveal", () => {
const handoff = nextPostRestoreHandoff({ current: null, scopeKey, routeState: restoringState });
const settled = {
handoff,
scopeKey,
hasActiveWorkspace: true,
hasHydratedWorkspaceLayoutStore: true,
hasHydratedAgents: true,
hasReconciledAutoOpenAgentTabs: true,
visibleAgentCount: 1,
visibleAgentsTimelineSynced: true,
visibleAgentsVisibilityStatus: "ready" as const,
visibleAgentsLoadingOlder: false,
routeState: { kind: "ready" as const },
};
// A tab row mounted behind the gate has not measured its tabs yet.
const held = resolvePostRestoreDisplayedRouteState({ ...settled, isRevealHeld: true });
expect(held.displayedRouteState).toBe(restoringState);
expect(held.isHandoffReadyToMount).toBe(true);
expect(held.isHandoffReadyToRelease).toBe(false);
const released = resolvePostRestoreDisplayedRouteState({ ...settled, isRevealHeld: false });
expect(released.isHandoffReadyToRelease).toBe(true);
});
it("marks handoff ready to release immediately when the workspace only has non-auto-open agents", () => {
const captured = nextPostRestoreHandoff({
current: null,
@@ -394,6 +427,7 @@ describe("post-restore handoff state machine", () => {
visibleAgentsTimelineSynced: false,
visibleAgentsVisibilityStatus: "ready",
visibleAgentsLoadingOlder: false,
isRevealHeld: false,
routeState: { kind: "ready" },
});
expect(resolved.isHandoffReadyToRelease).toBe(true);
@@ -164,6 +164,10 @@ import {
canSyncVisibleAgents,
usePostRestoreWorkspaceRouteState,
} from "@/screens/workspace/use-post-restore-handoff";
import {
type PostRestoreRevealHolds,
PostRestoreRevealHoldsProvider,
} from "@/screens/workspace/post-restore-reveal-holds";
import {
renderWorkspaceRouteGate,
WorkspaceLoading,
@@ -1432,6 +1436,7 @@ function WorkspaceScreenContent({
const {
displayedRouteState: displayedWorkspaceRouteState,
revealHolds,
isHoldingHandoff,
isPaneRouteFocused,
effectivePaneFocusSuspended,
@@ -3506,6 +3511,7 @@ function WorkspaceScreenContent({
return (
<PostRestoreOverlayShell
isHoldingHandoff={isHoldingHandoff}
revealHolds={revealHolds}
overlay={gatedWorkspaceScreen}
workspaceKey={persistenceKey}
sheetPaneHost={sheetPaneHost}
@@ -3529,12 +3535,14 @@ function WorkspaceScreenContent({
/** Keeps mounted workspace chrome hidden beneath the restoring gate during layout settle. */
function PostRestoreOverlayShell({
isHoldingHandoff,
revealHolds,
overlay,
workspaceKey,
sheetPaneHost,
children,
}: {
isHoldingHandoff: boolean;
revealHolds: PostRestoreRevealHolds;
overlay: ReactNode;
workspaceKey: string | null;
sheetPaneHost: Parameters<typeof WorkspaceContentProviders>[0]["sheetPaneHost"];
@@ -3552,13 +3560,15 @@ function PostRestoreOverlayShell({
accessibilityElementsHidden={isHoldingHandoff}
importantForAccessibility={isHoldingHandoff ? "no-hide-descendants" : "auto"}
>
<WorkspaceContentProviders
key={workspaceKey}
workspaceKey={workspaceKey}
sheetPaneHost={sheetPaneHost}
>
{children}
</WorkspaceContentProviders>
<PostRestoreRevealHoldsProvider holds={isHoldingHandoff ? revealHolds : null}>
<WorkspaceContentProviders
key={workspaceKey}
workspaceKey={workspaceKey}
sheetPaneHost={sheetPaneHost}
>
{children}
</WorkspaceContentProviders>
</PostRestoreRevealHoldsProvider>
</View>
) : null}
{overlay ? <View style={styles.postRestoreOverlay}>{overlay}</View> : null}
+44
View File
@@ -239,6 +239,40 @@ const MutableBrowserToolsConfigSchema = z
enabled: z.boolean().default(false),
})
.passthrough();
export {
BUILTIN_TOOL_GROUPS,
DEFAULT_DAEMON_TOOL_GROUPS,
type BuiltInToolGroup,
} from "./tool-groups.js";
export const MutableDaemonToolGroupsSchema = z
.object({
orchestration: z.boolean().optional(),
schedules: z.boolean().optional(),
changeRequests: z.boolean().optional(),
browser: z.boolean().optional(),
})
.passthrough();
export const MutableDaemonToolsConfigSchema = z
.object({
enabled: z.boolean(),
groups: MutableDaemonToolGroupsSchema.optional(),
})
.passthrough();
export const MutableDaemonToolsConfigPatchSchema = z
.object({
enabled: z.boolean().optional(),
groups: MutableDaemonToolGroupsSchema.optional(),
})
.passthrough();
export type MutableDaemonToolGroups = z.infer<typeof MutableDaemonToolGroupsSchema>;
export type MutableDaemonToolsConfig = z.infer<typeof MutableDaemonToolsConfigSchema>;
export type MutableDaemonToolsConfigPatch = z.infer<typeof MutableDaemonToolsConfigPatchSchema>;
const MutableRelayConfigSchema = z
.object({
enabled: z.boolean(),
@@ -252,12 +286,15 @@ export const MutableDaemonConfigSchema = z
.object({
// COMPAT(relayConfig): added in v0.2.6, remove after 2027-01-31 when old daemons are unsupported.
relay: MutableRelayConfigSchema.optional(),
// COMPAT(legacyToolsConfig): added in v0.18.2, keep while older clients read mcp.injectIntoAgents.
mcp: z
.object({
enabled: z.boolean().optional(),
injectIntoAgents: z.boolean(),
})
.passthrough(),
// COMPAT(daemonToolsConfig): added in v0.18.2, optional while older daemons omit it.
tools: MutableDaemonToolsConfigSchema.optional(),
hostnames: z.union([z.literal(true), z.array(z.string())]).optional(),
cors: z
.object({
@@ -276,6 +313,7 @@ export const MutableDaemonConfigSchema = z
catalogRefreshTimeoutMs: z.number().int().positive().optional(),
// COMPAT(usageSetting): added in v0.14, remove after 2027-05-01.
usage: z.object({ enabled: z.boolean() }).optional(),
// COMPAT(legacyToolsConfig): added in v0.18.2, keep while older clients read browserTools.enabled.
browserTools: MutableBrowserToolsConfigSchema.default({ enabled: false }),
providers: z.record(z.string(), MutableDaemonProviderConfigSchema).default({}),
metadataGeneration: MutableMetadataGenerationConfigSchema.default({ providers: [] }),
@@ -302,8 +340,12 @@ export const MutableDaemonConfigSchema = z
export const MutableDaemonConfigPatchSchema = z
.object({
relay: MutableRelayConfigSchema.partial().optional(),
// COMPAT(legacyToolsConfig): added in v0.18.2, keep while older clients patch mcp.injectIntoAgents.
mcp: z.object({ injectIntoAgents: z.boolean().optional() }).passthrough().optional(),
// COMPAT(daemonToolsConfig): added in v0.18.2, optional while older clients omit it.
tools: MutableDaemonToolsConfigPatchSchema.optional(),
usage: z.object({ enabled: z.boolean() }).optional(),
// COMPAT(legacyToolsConfig): added in v0.18.2, keep while older clients patch browserTools.enabled.
browserTools: MutableBrowserToolsConfigSchema.partial().optional(),
providers: z
.record(z.string(), MutableDaemonProviderConfigSchema.partial().passthrough())
@@ -4127,6 +4169,8 @@ export const ServerInfoStatusPayloadSchema = z
// COMPAT(usageSetting): added in v0.14, remove after 2027-05-01.
usageSetting: z.boolean().optional(),
usageSources: z.boolean().optional(),
// COMPAT(daemonToolsConfig): added in v0.18.2, remove gate after 2027-06-01.
daemonToolsConfig: z.boolean().optional(),
// COMPAT(providerInstallation): added in v0.17.0, remove gate after 2027-05-13.
providerInstallation: z.boolean().optional(),
// COMPAT(providersSnapshotCwd): added in v0.3.2, remove gate after 2027-02-10.
@@ -858,3 +858,56 @@ describe("provider metrics", () => {
).toBe(false);
});
});
describe("daemon tools config wire compatibility", () => {
const baseConfig = {
mcp: { enabled: true, injectIntoAgents: true },
browserTools: { enabled: false },
};
const tools = {
enabled: true,
groups: {
orchestration: true,
schedules: true,
changeRequests: true,
browser: false,
},
};
test("new apps read daemon.tools and daemonToolsConfig feature from a new daemon", () => {
const parsed = MutableDaemonConfigSchema.parse({ ...baseConfig, tools });
expect(parsed.tools).toEqual(tools);
const serverInfo = ServerInfoStatusPayloadSchema.parse({
status: "server_info",
serverId: "srv_1",
features: { daemonToolsConfig: true },
});
expect(serverInfo.features?.daemonToolsConfig).toBe(true);
});
test("new apps accept configs from older daemons that omit tools and daemonToolsConfig", () => {
const parsed = MutableDaemonConfigSchema.parse(baseConfig);
expect(parsed.tools).toBeUndefined();
expect(parsed.mcp.injectIntoAgents).toBe(true);
expect(parsed.browserTools.enabled).toBe(false);
});
test("patches accept both unified tools patches and legacy mcp/browserTools patches", () => {
expect(
MutableDaemonConfigPatchSchema.parse({
tools: { enabled: false, groups: { browser: true } },
}).tools,
).toEqual({ enabled: false, groups: { browser: true } });
expect(
MutableDaemonConfigPatchSchema.parse({
mcp: { injectIntoAgents: false },
browserTools: { enabled: true },
}),
).toMatchObject({
mcp: { injectIntoAgents: false },
browserTools: { enabled: true },
});
});
});
+16
View File
@@ -0,0 +1,16 @@
// Kept free of Zod so configuration code can read tool groups without loading the wire schemas.
export const BUILTIN_TOOL_GROUPS = [
"orchestration",
"schedules",
"changeRequests",
"browser",
] as const;
export type BuiltInToolGroup = (typeof BUILTIN_TOOL_GROUPS)[number];
export const DEFAULT_DAEMON_TOOL_GROUPS = {
orchestration: true,
schedules: true,
changeRequests: true,
browser: false,
} as const satisfies Record<BuiltInToolGroup, boolean>;
@@ -22,6 +22,7 @@ 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 { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
import type {
AgentClient,
AgentPersistenceHandle,
@@ -573,6 +574,63 @@ describe("agent MCP end-to-end (offline)", () => {
}
}, 30_000);
test("tool settings saved by a client change the agent's MCP catalog without a restart", async () => {
const daemon = await createTestPaseoDaemon();
const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-agent-cwd-tools-"));
const mcpUrl = `http://127.0.0.1:${daemon.port}/mcp/agents`;
const client = await createMcpClient(mcpUrl);
const settingsClient = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.18.2",
});
let agentId: string | null = null;
async function agentToolNames(): Promise<string[]> {
const agentClient = new StandardMcpClient({ name: "agent-mcp-e2e", version: "0.0.0" });
await agentClient.connect(
new StandardMcpHttpTransport(new URL(`${mcpUrl}?callerAgentId=${agentId!}`)),
);
try {
return (await agentClient.listTools()).tools.map((tool) => tool.name);
} finally {
await agentClient.close();
}
}
try {
await settingsClient.connect();
const created = await client.callTool({
name: "create_agent",
args: {
cwd: agentCwd,
title: "Tool settings",
provider: "claude/claude-test-model",
mode: "bypassPermissions",
initialPrompt: "reply with done and stop",
},
});
const payload = getStructuredContent(created);
agentId = typeof payload?.agentId === "string" ? payload.agentId : null;
expect(agentId).toBeTruthy();
const defaults = await agentToolNames();
expect(defaults).toEqual(expect.arrayContaining(["create_agent", "create_schedule"]));
await settingsClient.patchDaemonConfig({ tools: { groups: { schedules: false } } });
const withoutSchedules = await agentToolNames();
expect(withoutSchedules).toContain("create_agent");
expect(withoutSchedules).not.toContain("create_schedule");
expect(withoutSchedules).not.toContain("create_heartbeat");
} finally {
if (agentId) {
await client.callTool({ name: "kill_agent", args: { agentId } });
}
await settingsClient.close();
await client.close();
await daemon.close();
await rm(agentCwd, { recursive: true, force: true });
}
}, 30_000);
test("create_agent injects a loopback MCP URL when the daemon listens on all interfaces", async () => {
const paseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-home-"));
const staticDir = await mkdtemp(path.join(os.tmpdir(), "paseo-static-"));
@@ -27,6 +27,7 @@ interface McpToolResult {
interface McpClient {
callTool: (input: { name: string; args?: StructuredContent }) => Promise<McpToolResult>;
listTools: () => Promise<{ tools: Array<{ name: string }> }>;
close: () => Promise<void>;
}
@@ -86,7 +87,10 @@ async function createMcpClient(url: string): Promise<McpClient> {
const transport = new StreamableHTTPClientTransport(new URL(url));
const rawClient = await experimental_createMCPClient({ transport });
const boundCallTool: McpClient["callTool"] = Reflect.get(rawClient, "callTool").bind(rawClient);
return { callTool: boundCallTool, close: () => rawClient.close() };
const boundListTools: McpClient["listTools"] = Reflect.get(rawClient, "listTools").bind(
rawClient,
);
return { callTool: boundCallTool, listTools: boundListTools, close: () => rawClient.close() };
}
async function callToolStructured(
@@ -1110,16 +1114,18 @@ describe("Suite C: Schedule Tools", () => {
}
});
test("create_heartbeat without callerAgentId throws", async () => {
await expectToolError(
topLevelClient,
"create_heartbeat",
{
prompt: "say hello",
cron: "*/5 * * * *",
},
/requires an agent-scoped session/i,
);
test("create_heartbeat is omitted without callerAgentId", async () => {
const listed = await topLevelClient.listTools();
expect(listed.tools.some((tool) => tool.name === "create_heartbeat")).toBe(false);
await expect(
topLevelClient.callTool({
name: "create_heartbeat",
args: {
prompt: "say hello",
cron: "*/5 * * * *",
},
}),
).rejects.toThrow(/create_heartbeat/i);
});
});
@@ -6616,7 +6616,7 @@ describe("create_heartbeat MCP tool", () => {
);
});
it("requires an agent-scoped session", async () => {
it("is omitted outside an agent-scoped session", async () => {
const { agentManager, agentStorage } = createTestDeps();
const createOrReplace = vi.fn();
const server = await createAgentMcpServer({
@@ -6626,15 +6626,9 @@ describe("create_heartbeat MCP tool", () => {
scheduleService: { createOrReplace } as unknown as ScheduleService,
logger,
});
const tool = registeredTool(server, "create_heartbeat");
await expect(
tool.handler({
prompt: "check status",
cron: "*/15 * * * *",
}),
).rejects.toThrow("create_heartbeat requires an agent-scoped session");
expect(lookupTool(server, "create_heartbeat")).toBeUndefined();
expect(lookupTool(server, "delete_heartbeat")).toBeUndefined();
expect(createOrReplace).not.toHaveBeenCalled();
});
});
@@ -34,7 +34,11 @@ describe("Codex app-server provider (real)", () => {
modeId: "auto",
});
try {
expect(session.features?.some((feature) => feature.id === "plan_mode")).toBe(true);
expect(
session.controls?.some(
(control) => control.type === "toggle" && control.key === "plan_mode",
),
).toBe(true);
const result = await session.run("Say hello in one sentence.");
expect(result.finalText.length).toBeGreaterThan(0);
@@ -24,8 +24,16 @@ import {
ActiveTurnBehaviorSchema,
AgentActiveTurnBehaviorSchema,
AgentProfileSchema,
type DaemonPermission,
} from "@getpaseo/protocol/messages";
import type { DaemonConfigStore } from "../../daemon-config-store.js";
import { normalizeDaemonToolGroups, type ResolvedDaemonToolsConfig } from "../../tools-config.js";
import {
BUILTIN_TOOL_METADATA,
isBuiltInToolGroup,
isToolAllowedInScope,
type BuiltInToolName,
} from "./tool-metadata.js";
import { featuresFromControls } from "@getpaseo/protocol/option-controls";
import {
AgentFeatureSchema,
@@ -175,6 +183,9 @@ export interface PaseoToolHostDependencies {
firstAgentContext?: FirstAgentContext,
context?: { background?: boolean; callerWorkspaceId?: string },
) => Promise<string>;
toolsConfig?: ResolvedDaemonToolsConfig;
allowedPermissions?: ReadonlySet<DaemonPermission>;
// COMPAT(legacyBrowserToolsOption): added in v0.18.2, prefer toolsConfig.groups.browser.
browserToolsEnabled?: boolean;
browserToolsBroker?: BrowserToolsBroker | null;
paseoToolPolicy?: ProviderPaseoToolsPolicy;
@@ -791,13 +802,31 @@ function createToolCatalog(
listAgents: (args, context) => localHostOperations.get("list_agents")!(args, context),
},
});
const toolsConfig: ResolvedDaemonToolsConfig = options.toolsConfig ?? {
enabled: true,
groups: normalizeDaemonToolGroups(undefined, options.browserToolsEnabled),
};
const registerTool = (
name: string,
name: BuiltInToolName,
config: PaseoToolConfig,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Tool handlers are schema-validated at registration boundaries.
handler: (input: any, context: PaseoToolExecutionContext) => Promise<PaseoToolResult>,
) => {
builtinNames.add(name);
const metadata = BUILTIN_TOOL_METADATA[name];
if (!isToolAllowedInScope(metadata.scope, scope)) {
return;
}
// Voice mode delivers `speak` on its own, whether or not agent tools are enabled.
if (scope === "agent" && !toolsConfig.enabled && metadata.group !== "voice") {
return;
}
if (isBuiltInToolGroup(metadata.group) && !toolsConfig.groups[metadata.group]) {
return;
}
if (options.allowedPermissions && !options.allowedPermissions.has(metadata.permission)) {
return;
}
if (!isPaseoToolEnabled(options.paseoToolPolicy, name)) {
return;
}
@@ -861,6 +890,9 @@ function createToolCatalog(
name,
title: config.title,
description: config.description ?? name,
group: metadata.group,
scope: metadata.scope,
permission: metadata.permission,
inputSchema: config.inputSchema,
outputSchema: config.outputSchema,
handler: handler as PaseoToolDefinition["handler"],
@@ -1450,7 +1482,7 @@ function createToolCatalog(
return toCatalog();
}
if (options.browserToolsEnabled && options.browserToolsBroker) {
if (options.browserToolsBroker) {
registerBrowserTools({
registerTool,
broker: options.browserToolsBroker,
@@ -3566,6 +3598,8 @@ function createToolCatalog(
agentManager,
callerAgentId,
scope,
toolsEnabled: toolsConfig.enabled,
allowedPermissions: options.allowedPermissions,
tools,
builtinNames,
policy: options.paseoToolPolicy,
@@ -1,20 +1,35 @@
import { z } from "zod";
import type { DaemonPermission } from "@getpaseo/protocol/messages";
import type { ProviderPaseoToolsPolicy } from "@getpaseo/protocol/provider-config";
import type { AgentManager } from "../agent-manager.js";
import { isPaseoToolEnabled } from "../paseo-tool-policy.js";
import type { PaseoToolDefinition } from "./types.js";
import { addModelVisibleStructuredContent } from "./paseo-tool-serialization.js";
const PLUGIN_TOOL_PERMISSION: DaemonPermission = "workspace.write";
export function registerPluginTools(options: {
agentManager: AgentManager;
callerAgentId?: string;
scope: "agent" | "top-level";
toolsEnabled?: boolean;
allowedPermissions?: ReadonlySet<DaemonPermission>;
tools: Map<string, PaseoToolDefinition>;
builtinNames: Set<string>;
policy?: ProviderPaseoToolsPolicy;
}): void {
const { agentManager, callerAgentId, scope, tools, builtinNames, policy } = options;
if (scope !== "agent" || !callerAgentId) return;
const {
agentManager,
callerAgentId,
scope,
toolsEnabled = true,
allowedPermissions,
tools,
builtinNames,
policy,
} = options;
if (scope !== "agent" || !callerAgentId || !toolsEnabled) return;
if (allowedPermissions && !allowedPermissions.has(PLUGIN_TOOL_PERMISSION)) return;
for (const tool of agentManager.getPluginTools(callerAgentId)) {
if (builtinNames.has(tool.name)) {
throw new Error(
@@ -26,6 +41,9 @@ export function registerPluginTools(options: {
name: tool.name,
title: tool.title,
description: tool.description,
group: "plugin",
scope: "agent",
permission: PLUGIN_TOOL_PERMISSION,
inputSchema: z.fromJSONSchema(tool.inputSchema),
async handler(input, { signal }) {
const result = await agentManager.executePluginTool({
@@ -0,0 +1,114 @@
import {
BUILTIN_TOOL_GROUPS,
type BuiltInToolGroup,
type DaemonPermission,
} from "@getpaseo/protocol/messages";
import type { PaseoToolGroup, PaseoToolScope } from "./types.js";
export interface PaseoToolMetadata {
readonly group: PaseoToolGroup;
readonly scope: PaseoToolScope;
readonly permission: DaemonPermission;
}
const BUILTIN_TOOL_GROUP_SET: ReadonlySet<string> = new Set(BUILTIN_TOOL_GROUPS);
export function isBuiltInToolGroup(group: PaseoToolGroup): group is BuiltInToolGroup {
return BUILTIN_TOOL_GROUP_SET.has(group);
}
export function isToolAllowedInScope(
toolScope: PaseoToolScope,
catalogScope: "agent" | "top-level",
): boolean {
return toolScope === "both" || toolScope === catalogScope;
}
export const BUILTIN_TOOL_METADATA = {
// Voice (internal session-attached)
speak: { group: "voice", scope: "agent", permission: "workspace.write" },
// Browser automation (opt-in group, bound to agent workspace)
browser_list_hosts: { group: "browser", scope: "agent", permission: "workspace.read" },
browser_list_tabs: { group: "browser", scope: "agent", permission: "workspace.read" },
browser_new_tab: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_snapshot: { group: "browser", scope: "agent", permission: "workspace.read" },
browser_click: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_fill: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_wait: { group: "browser", scope: "agent", permission: "workspace.read" },
browser_type: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_keypress: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_navigate: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_back: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_forward: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_reload: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_screenshot: { group: "browser", scope: "agent", permission: "workspace.read" },
browser_upload: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_hover: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_select: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_drag: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_logs: { group: "browser", scope: "agent", permission: "workspace.read" },
browser_evaluate: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_scroll: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_resize: { group: "browser", scope: "agent", permission: "workspace.write" },
browser_close_tab: { group: "browser", scope: "agent", permission: "workspace.write" },
// Orchestration (hosts, workspaces, agents, prompts, permissions, providers, scripts, terminals)
list_hosts: { group: "orchestration", scope: "both", permission: "daemon.read" },
create_workspace: { group: "orchestration", scope: "both", permission: "workspace.manage" },
list_workspaces: { group: "orchestration", scope: "both", permission: "workspace.read" },
archive_workspace: { group: "orchestration", scope: "both", permission: "workspace.manage" },
rename_workspace: { group: "orchestration", scope: "both", permission: "workspace.manage" },
update_workspace: { group: "orchestration", scope: "both", permission: "workspace.manage" },
create_agent: { group: "orchestration", scope: "both", permission: "workspace.write" },
send_agent_prompt: { group: "orchestration", scope: "both", permission: "workspace.write" },
get_agent_status: { group: "orchestration", scope: "both", permission: "workspace.read" },
get_agent_activity: { group: "orchestration", scope: "both", permission: "workspace.read" },
list_agents: { group: "orchestration", scope: "both", permission: "workspace.read" },
cancel_agent: { group: "orchestration", scope: "both", permission: "workspace.write" },
archive_agent: { group: "orchestration", scope: "both", permission: "workspace.write" },
kill_agent: { group: "orchestration", scope: "both", permission: "workspace.write" },
update_agent: { group: "orchestration", scope: "both", permission: "workspace.write" },
set_agent_mode: { group: "orchestration", scope: "both", permission: "workspace.write" },
list_pending_permissions: { group: "orchestration", scope: "both", permission: "workspace.read" },
respond_to_permission: { group: "orchestration", scope: "both", permission: "workspace.write" },
list_providers: { group: "orchestration", scope: "both", permission: "daemon.read" },
list_models: { group: "orchestration", scope: "both", permission: "daemon.read" },
list_profiles: { group: "orchestration", scope: "both", permission: "daemon.read" },
inspect_provider: { group: "orchestration", scope: "both", permission: "daemon.read" },
list_workspace_scripts: { group: "orchestration", scope: "both", permission: "workspace.read" },
start_workspace_script: { group: "orchestration", scope: "both", permission: "workspace.write" },
stop_workspace_script: { group: "orchestration", scope: "both", permission: "workspace.write" },
list_terminals: { group: "orchestration", scope: "both", permission: "workspace.read" },
create_terminal: { group: "orchestration", scope: "both", permission: "workspace.write" },
kill_terminal: { group: "orchestration", scope: "both", permission: "workspace.write" },
capture_terminal: { group: "orchestration", scope: "both", permission: "workspace.read" },
send_terminal_keys: { group: "orchestration", scope: "both", permission: "workspace.write" },
// Schedules & agent-scoped heartbeats
create_schedule: { group: "schedules", scope: "both", permission: "automation.manage" },
create_heartbeat: { group: "schedules", scope: "agent", permission: "automation.manage" },
delete_heartbeat: { group: "schedules", scope: "agent", permission: "automation.manage" },
list_schedules: { group: "schedules", scope: "both", permission: "automation.manage" },
inspect_schedule: { group: "schedules", scope: "both", permission: "automation.manage" },
pause_schedule: { group: "schedules", scope: "both", permission: "automation.manage" },
resume_schedule: { group: "schedules", scope: "both", permission: "automation.manage" },
delete_schedule: { group: "schedules", scope: "both", permission: "automation.manage" },
update_schedule: { group: "schedules", scope: "both", permission: "automation.manage" },
schedule_logs: { group: "schedules", scope: "both", permission: "automation.manage" },
run_schedule_once: { group: "schedules", scope: "both", permission: "automation.manage" },
// Change request watching (PR/MR subscriptions)
subscribe_change_request: {
group: "changeRequests",
scope: "agent",
permission: "workspace.read",
},
unsubscribe_change_request: {
group: "changeRequests",
scope: "agent",
permission: "workspace.read",
},
} as const satisfies Record<string, PaseoToolMetadata>;
export type BuiltInToolName = keyof typeof BUILTIN_TOOL_METADATA;
@@ -0,0 +1,273 @@
import { DAEMON_PERMISSIONS } from "@getpaseo/protocol/messages";
import pino from "pino";
import { describe, expect, test } from "vitest";
import { createAgentMcpServer } from "../mcp-server.js";
import type { AgentManager } from "../agent-manager.js";
import type { AgentStorage } from "../agent-storage.js";
import type { ProviderSnapshotManager } from "../provider-snapshot-manager.js";
import type { BrowserToolsBroker } from "../../browser-tools/broker.js";
import type { ChangeRequestWatches } from "../change-request-watches/index.js";
import { createPaseoToolCatalog, type PaseoToolHostDependencies } from "./paseo-tools.js";
function createMinimalDeps(
overrides: Partial<PaseoToolHostDependencies> = {},
): PaseoToolHostDependencies {
const pluginTools = [
{
pluginId: "demo-plugin",
pluginInstanceId: "inst-1",
name: "demo_plugin_tool",
title: "Demo plugin tool",
description: "Contributed by plugin",
inputSchema: { type: "object", properties: {} },
},
];
const agentManager = {
getAgent: () => ({
id: "agent-1",
provider: "codex",
cwd: "/tmp/repo",
workspaceId: "ws-1",
lifecycle: "idle",
currentModeId: "default",
availableModes: [],
config: { title: "Test Agent" },
}),
getPluginTools: (agentId: string) => (agentId === "agent-1" ? pluginTools : []),
executePluginTool: async () => ({ text: "ok" }),
} as unknown as AgentManager;
const agentStorage = {
getAgent: async () => null,
listAgents: async () => [],
} as unknown as AgentStorage;
const providerSnapshotManager = {
getSnapshot: () => [],
} as unknown as ProviderSnapshotManager;
const browserToolsBroker = {
listBrowserHosts: () => [],
execute: async () => ({
requestId: "req-1",
ok: true,
result: { command: "list_tabs", tabs: [] },
}),
} as unknown as BrowserToolsBroker;
const changeRequestWatches = {
subscribe: async () => ({}),
unsubscribe: async () => ({ url: "", removed: true }),
} as unknown as ChangeRequestWatches;
return {
agentManager,
agentStorage,
providerSnapshotManager,
browserToolsBroker,
changeRequestWatches,
logger: pino({ level: "silent" }),
...overrides,
};
}
describe("Paseo Tool Registry grouping, scope, and permission metadata", () => {
test("every registered tool declares a valid group, scope, and semantic permission", () => {
const validPermissions = new Set<string>(DAEMON_PERMISSIONS);
const catalog = createPaseoToolCatalog(
createMinimalDeps({
callerAgentId: "agent-1",
enableVoiceTools: true,
toolsConfig: {
enabled: true,
groups: {
orchestration: true,
schedules: true,
changeRequests: true,
browser: true,
},
},
}),
);
expect(catalog.tools.size).toBeGreaterThan(45);
for (const tool of catalog.tools.values()) {
expect([
"orchestration",
"schedules",
"changeRequests",
"browser",
"voice",
"plugin",
]).toContain(tool.group);
expect(["agent", "top-level", "both"]).toContain(tool.scope);
expect(validPermissions.has(tool.permission)).toBe(true);
}
expect(catalog.getTool("create_agent")).toMatchObject({
group: "orchestration",
scope: "both",
permission: "workspace.write",
});
expect(catalog.getTool("list_agents")).toMatchObject({
group: "orchestration",
scope: "both",
permission: "workspace.read",
});
expect(catalog.getTool("list_hosts")).toMatchObject({
group: "orchestration",
scope: "both",
permission: "daemon.read",
});
expect(catalog.getTool("create_schedule")).toMatchObject({
group: "schedules",
scope: "both",
permission: "automation.manage",
});
expect(catalog.getTool("create_heartbeat")).toMatchObject({
group: "schedules",
scope: "agent",
permission: "automation.manage",
});
expect(catalog.getTool("subscribe_change_request")).toMatchObject({
group: "changeRequests",
scope: "agent",
permission: "workspace.read",
});
expect(catalog.getTool("browser_list_tabs")).toMatchObject({
group: "browser",
scope: "agent",
permission: "workspace.read",
});
expect(catalog.getTool("browser_click")).toMatchObject({
group: "browser",
scope: "agent",
permission: "workspace.write",
});
expect(catalog.getTool("speak")).toMatchObject({
group: "voice",
scope: "agent",
permission: "workspace.write",
});
expect(catalog.getTool("demo_plugin_tool")).toMatchObject({
group: "plugin",
scope: "agent",
permission: "workspace.write",
});
});
test("filters built-in groups consistently in both native catalog and MCP server adapter", async () => {
const deps = createMinimalDeps({
callerAgentId: "agent-1",
toolsConfig: {
enabled: true,
groups: {
orchestration: false,
schedules: true,
changeRequests: false,
browser: false,
},
},
});
const catalog = createPaseoToolCatalog(deps);
const mcpServer = await createAgentMcpServer(deps);
const mcpRegisteredNames = Object.keys(
(mcpServer as unknown as { _registeredTools: Record<string, unknown> })._registeredTools,
).sort();
expect([...catalog.tools.keys()].sort()).toEqual(mcpRegisteredNames);
expect(catalog.getTool("list_agents")).toBeUndefined();
expect(catalog.getTool("subscribe_change_request")).toBeUndefined();
expect(catalog.getTool("browser_list_tabs")).toBeUndefined();
expect(catalog.getTool("create_schedule")).toBeDefined();
expect(catalog.getTool("create_heartbeat")).toBeDefined();
expect(catalog.getTool("demo_plugin_tool")).toBeDefined();
});
test("keeps voice speak tool and plugin tools available when all built-in groups are disabled", () => {
const catalog = createPaseoToolCatalog(
createMinimalDeps({
callerAgentId: "agent-1",
enableVoiceTools: true,
toolsConfig: {
enabled: true,
groups: {
orchestration: false,
schedules: false,
changeRequests: false,
browser: false,
},
},
}),
);
expect([...catalog.tools.keys()].sort()).toEqual(["demo_plugin_tool", "speak"]);
});
test("keeps only speak for an active voice session when master tools.enabled is false", () => {
const catalog = createPaseoToolCatalog(
createMinimalDeps({
callerAgentId: "agent-1",
enableVoiceTools: true,
toolsConfig: {
enabled: false,
groups: {
orchestration: true,
schedules: true,
changeRequests: true,
browser: true,
},
},
}),
);
expect([...catalog.tools.keys()]).toEqual(["speak"]);
});
test("top-level catalog excludes agent-only tools and supports permission filtering for external MCP", () => {
const fullTopLevel = createPaseoToolCatalog(
createMinimalDeps({
enableVoiceTools: true,
toolsConfig: {
enabled: true,
groups: {
orchestration: true,
schedules: true,
changeRequests: true,
browser: true,
},
},
}),
);
expect(fullTopLevel.getTool("list_agents")).toBeDefined();
expect(fullTopLevel.getTool("create_schedule")).toBeDefined();
expect(fullTopLevel.getTool("create_heartbeat")).toBeUndefined();
expect(fullTopLevel.getTool("delete_heartbeat")).toBeUndefined();
expect(fullTopLevel.getTool("subscribe_change_request")).toBeUndefined();
expect(fullTopLevel.getTool("unsubscribe_change_request")).toBeUndefined();
expect(fullTopLevel.getTool("browser_list_tabs")).toBeUndefined();
expect(fullTopLevel.getTool("speak")).toBeUndefined();
expect(fullTopLevel.getTool("demo_plugin_tool")).toBeUndefined();
const readOnlyTopLevel = createPaseoToolCatalog(
createMinimalDeps({
toolsConfig: {
enabled: true,
groups: {
orchestration: true,
schedules: true,
changeRequests: true,
browser: true,
},
},
allowedPermissions: new Set(["daemon.read", "workspace.read"]),
}),
);
expect(readOnlyTopLevel.getTool("list_hosts")).toBeDefined();
expect(readOnlyTopLevel.getTool("list_agents")).toBeDefined();
expect(readOnlyTopLevel.getTool("create_agent")).toBeUndefined();
expect(readOnlyTopLevel.getTool("create_workspace")).toBeUndefined();
expect(readOnlyTopLevel.getTool("create_schedule")).toBeUndefined();
for (const tool of readOnlyTopLevel.tools.values()) {
expect(["daemon.read", "workspace.read"]).toContain(tool.permission);
}
});
});
@@ -1,6 +1,10 @@
import type { z } from "zod";
import type { BuiltInToolGroup, DaemonPermission } from "@getpaseo/protocol/messages";
import type { ProviderPaseoToolsPolicy } from "@getpaseo/protocol/provider-config";
export type PaseoToolGroup = BuiltInToolGroup | "voice" | "plugin";
export type PaseoToolScope = "agent" | "top-level" | "both";
export class PaseoToolInputError extends Error {
readonly status = 400;
@@ -34,6 +38,9 @@ export interface PaseoToolConfig {
export interface PaseoToolDefinition extends PaseoToolConfig {
name: string;
description: string;
group: PaseoToolGroup;
scope: PaseoToolScope;
permission: DaemonPermission;
handler: (input: unknown, context: PaseoToolExecutionContext) => Promise<PaseoToolResult>;
}
+44 -13
View File
@@ -136,6 +136,11 @@ import {
import { CheckoutDiffManager } from "./checkout-diff-manager.js";
import { ScheduleService } from "./schedule/service.js";
import { DaemonConfigStore, type MutableDaemonConfig } from "./daemon-config-store.js";
import {
resolveDaemonToolsFromConfigOptions,
resolveDaemonToolsFromMutableConfig,
type ResolvedDaemonToolsConfig,
} from "./tools-config.js";
import { createOrchestrationSkills } from "./orchestration-skills/index.js";
import {
resolveReloadableConfig,
@@ -357,6 +362,7 @@ export interface PaseoDaemonConfig {
allowedHosts?: HostnamesConfig;
hostnames?: HostnamesConfig;
trustedProxies?: true | string[];
tools?: ResolvedDaemonToolsConfig;
mcpEnabled?: boolean;
mcpInjectIntoAgents?: boolean;
usageEnabled?: boolean;
@@ -535,12 +541,23 @@ function isListenOverridden(config: PaseoDaemonConfig): boolean {
function createInitialMutableDaemonConfig(config: ResolvedDaemonSettings): MutableDaemonConfig {
const providers = config.providerOverrides ?? {};
const tools = resolveDaemonToolsFromConfigOptions({
tools: config.tools,
mcpEnabled: config.mcpEnabled,
mcpInjectIntoAgents: config.mcpInjectIntoAgents,
browserToolsEnabled: config.browserToolsEnabled,
});
const initialConfig: MutableDaemonConfig = {
relay: createInitialRelayConfig(config),
tools: {
enabled: tools.enabled,
groups: { ...tools.groups },
},
// COMPAT(legacyToolsConfig): added in v0.18.2, keep legacy fields synced for older clients.
mcp: {
enabled: config.mcpEnabled ?? true,
injectIntoAgents: config.mcpInjectIntoAgents ?? true,
injectIntoAgents: tools.enabled,
},
...(config.hostnames !== undefined ? { hostnames: config.hostnames } : {}),
cors: { allowedOrigins: config.corsAllowedOrigins },
@@ -551,7 +568,8 @@ function createInitialMutableDaemonConfig(config: ResolvedDaemonSettings): Mutab
? { catalogRefreshTimeoutMs: config.providerCatalogRefreshTimeoutMs }
: {}),
usage: { enabled: config.usageEnabled !== false },
browserTools: { enabled: config.browserToolsEnabled ?? false },
// COMPAT(legacyToolsConfig): added in v0.18.2, keep legacy field synced for older clients.
browserTools: { enabled: tools.groups.browser },
providers,
metadataGeneration: createInitialMetadataGenerationConfig(config),
autoArchiveAfterMerge: config.autoArchiveAfterMerge ?? false,
@@ -1676,6 +1694,7 @@ async function assemblePaseoDaemon({
clearWorkspaceArchiving,
ensureWorkspaceForCreate: createAgentCommandDependencies.ensureWorkspaceForCreate,
createPaseoWorktree: createAgentCommandDependencies.createPaseoWorktree,
toolsConfig: getCurrentToolsConfig(),
browserToolsEnabled: browserToolsPolicy.isEnabled(),
browserToolsBroker,
paseoToolPolicy:
@@ -1692,16 +1711,19 @@ async function assemblePaseoDaemon({
});
const createAgentToolCatalog = (runtime: PaseoToolRuntimeContext) =>
createPaseoToolCatalog(createAgentToolHostDependencies(runtime));
const getCurrentToolsConfig = () => resolveDaemonToolsFromMutableConfig(daemonConfigStore.get());
let mcpEnabled = config.mcpEnabled ?? true;
const setAgentProviderToolsEnabled = (enabled: boolean) => {
agentProviderRuntime.setPaseoToolCatalog(
enabled ? createPaseoAgentToolManifest(createAgentToolHostDependencies({})) : null,
);
};
agentManager.setPaseoToolCatalogFactory(createAgentToolCatalog);
agentManager.setPaseoToolsEnabled(config.mcpInjectIntoAgents !== false);
setAgentProviderToolsEnabled(config.mcpEnabled !== false && config.mcpInjectIntoAgents !== false);
const initialTools = getCurrentToolsConfig();
const initialInject = mcpEnabled && initialTools.enabled;
agentManager.setPaseoToolsEnabled(initialInject);
setAgentProviderToolsEnabled(initialInject);
let mcpEnabled = config.mcpEnabled ?? true;
{
const agentMcpRoute = "/mcp/agents";
@@ -1901,17 +1923,26 @@ async function assemblePaseoDaemon({
}
const mcpBaseUrl = loopbackAgentEndpoint.getMcpBaseUrl();
agentManager.setMcpBaseUrl(mcpBaseUrl);
agentManager.setPaseoToolsEnabled(mcpEnabled && config.mcpInjectIntoAgents !== false);
const syncAgentToolsState = () => {
const currentTools = getCurrentToolsConfig();
const inject = mcpEnabled && currentTools.enabled;
agentManager.setPaseoToolsEnabled(inject);
setAgentProviderToolsEnabled(inject);
};
syncAgentToolsState();
daemonConfigStore.onFieldChange("mcp.enabled", (value) => {
mcpEnabled = value !== false;
const inject = daemonConfigStore.get().mcp.injectIntoAgents !== false;
agentManager.setPaseoToolsEnabled(mcpEnabled && inject);
setAgentProviderToolsEnabled(mcpEnabled && inject);
syncAgentToolsState();
});
daemonConfigStore.onFieldChange("mcp.injectIntoAgents", (value) => {
const inject = value !== false;
agentManager.setPaseoToolsEnabled(mcpEnabled && inject);
setAgentProviderToolsEnabled(mcpEnabled && inject);
daemonConfigStore.onFieldChange("tools", () => {
syncAgentToolsState();
});
// COMPAT(legacyToolsConfig): added in v0.18.2, keep older config watchers in sync.
daemonConfigStore.onFieldChange("mcp.injectIntoAgents", () => {
syncAgentToolsState();
});
daemonConfigStore.onFieldChange("browserTools.enabled", () => {
syncAgentToolsState();
});
daemonConfigStore.onFieldChange("appendSystemPrompt", (value) => {
agentManager.setAppendSystemPrompt(typeof value === "string" ? value : "");
@@ -1,4 +1,5 @@
import type { DaemonConfigStore, MutableDaemonConfig } from "../daemon-config-store.js";
import type { DaemonConfigStore } from "../daemon-config-store.js";
import { resolveDaemonToolsFromMutableConfig } from "../tools-config.js";
export interface BrowserToolsPolicy {
isEnabled(): boolean;
@@ -8,14 +9,7 @@ export class DaemonConfigBrowserToolsPolicy implements BrowserToolsPolicy {
public constructor(private readonly configStore: Pick<DaemonConfigStore, "get">) {}
public isEnabled(): boolean {
return readBrowserToolsEnabled(this.configStore.get());
const tools = resolveDaemonToolsFromMutableConfig(this.configStore.get());
return tools.enabled && tools.groups.browser;
}
}
function readBrowserToolsEnabled(config: MutableDaemonConfig): boolean {
const browserTools = config.browserTools;
if (typeof browserTools !== "object" || browserTools === null || Array.isArray(browserTools)) {
return false;
}
return browserTools.enabled === true;
}
@@ -2,6 +2,7 @@ import { z } from "zod";
import { BrowserAutomationBrowserIdSchema } from "@getpaseo/protocol/browser-automation/rpc-schemas";
import type { BrowserToolsBroker } from "./broker.js";
import type { BrowserHostTarget, BrowserToolsResponsePayload } from "./errors.js";
import type { BuiltInToolName } from "../agent/tools/tool-metadata.js";
import type {
PaseoToolConfig,
PaseoToolExecutionContext,
@@ -16,7 +17,7 @@ interface CallerAgentContext {
export interface RegisterBrowserToolsOptions {
registerTool: (
name: string,
name: BuiltInToolName,
config: PaseoToolConfig,
handler: (
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Tool inputs are validated by the catalog before execution.
@@ -0,0 +1,297 @@
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, test } from "vitest";
import { DaemonConfigBrowserToolsPolicy } from "./browser-tools/policy.js";
import { loadConfig, resolveReloadableConfig } from "./config.js";
import { DaemonConfigStore } from "./daemon-config-store.js";
import { loadPersistedConfig } from "./persisted-config.js";
import { resolveDaemonToolsFromConfigOptions } from "./tools-config.js";
const roots: string[] = [];
async function createPaseoHome(config: unknown): Promise<string> {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-config-tools-"));
roots.push(root);
const paseoHome = path.join(root, ".paseo");
await mkdir(paseoHome, { recursive: true });
await writeFile(path.join(paseoHome, "config.json"), JSON.stringify(config, null, 2));
return paseoHome;
}
describe("daemon.tools config resolution and backward compatibility", () => {
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
test("defaults tools.enabled to true and browser group to false on fresh installs", async () => {
const home = await createPaseoHome({ version: 1 });
const config = loadConfig(home, { env: {} });
expect(config.tools).toEqual({
enabled: true,
groups: {
orchestration: true,
schedules: true,
changeRequests: true,
browser: false,
},
});
expect(config.mcpInjectIntoAgents).toBe(true);
expect(config.browserToolsEnabled).toBe(false);
});
test("reads explicit daemon.tools config including individual group overrides", async () => {
const home = await createPaseoHome({
version: 1,
daemon: {
tools: {
enabled: true,
groups: {
orchestration: false,
schedules: false,
changeRequests: true,
browser: true,
},
},
},
});
const config = loadConfig(home, { env: {} });
expect(config.tools).toEqual({
enabled: true,
groups: {
orchestration: false,
schedules: false,
changeRequests: true,
browser: true,
},
});
expect(config.browserToolsEnabled).toBe(true);
});
test("falls back to legacy daemon.mcp.enabled and daemon.mcp.injectIntoAgents when daemon.tools is absent", async () => {
const disabledMcpHome = await createPaseoHome({
version: 1,
daemon: { mcp: { enabled: false } },
});
expect(loadConfig(disabledMcpHome, { env: {} }).tools?.enabled).toBe(false);
const disabledInjectHome = await createPaseoHome({
version: 1,
daemon: { mcp: { enabled: true, injectIntoAgents: false } },
});
expect(loadConfig(disabledInjectHome, { env: {} }).tools?.enabled).toBe(false);
const enabledInjectHome = await createPaseoHome({
version: 1,
daemon: { mcp: { enabled: true, injectIntoAgents: true } },
});
expect(loadConfig(enabledInjectHome, { env: {} }).tools?.enabled).toBe(true);
});
test("falls back to legacy daemon.browserTools.enabled when daemon.tools.groups.browser is absent", async () => {
const home = await createPaseoHome({
version: 1,
daemon: { browserTools: { enabled: true } },
});
const config = loadConfig(home, { env: {} });
expect(config.tools).toEqual({
enabled: true,
groups: {
orchestration: true,
schedules: true,
changeRequests: true,
browser: true,
},
});
expect(config.browserToolsEnabled).toBe(true);
});
test("prefers explicit daemon.tools over legacy daemon.mcp and daemon.browserTools fields", async () => {
const home = await createPaseoHome({
version: 1,
daemon: {
mcp: { enabled: false, injectIntoAgents: false },
browserTools: { enabled: true },
tools: {
enabled: true,
groups: { browser: false },
},
},
});
const config = loadConfig(home, { env: {} });
expect(config.tools).toEqual({
enabled: true,
groups: {
orchestration: true,
schedules: true,
changeRequests: true,
browser: false,
},
});
expect(config.browserToolsEnabled).toBe(false);
});
test("preserves legacy CLI override flags (--no-mcp, --no-inject-mcp)", async () => {
const home = await createPaseoHome({
version: 1,
daemon: { tools: { enabled: true } },
});
expect(loadConfig(home, { env: {}, cli: { mcpEnabled: false } }).tools?.enabled).toBe(false);
expect(loadConfig(home, { env: {}, cli: { mcpInjectIntoAgents: false } }).tools?.enabled).toBe(
false,
);
});
test("DaemonConfigStore patches tools, preserves group choices across master off/on, and syncs legacy fields", async () => {
const home = await createPaseoHome({ version: 1 });
const store = new DaemonConfigStore(home, {
relay: { enabled: false },
tools: {
enabled: true,
groups: {
orchestration: true,
schedules: true,
changeRequests: true,
browser: false,
},
},
mcp: { enabled: true, injectIntoAgents: true },
browserTools: { enabled: false },
providers: {},
metadataGeneration: { providers: [] },
autoArchiveAfterMerge: false,
enableTerminalAgentHooks: false,
appendSystemPrompt: "",
});
const browserPolicy = new DaemonConfigBrowserToolsPolicy(store);
expect(browserPolicy.isEnabled()).toBe(false);
await store.patch({ tools: { groups: { browser: true, schedules: false } } });
expect(store.get().tools).toEqual({
enabled: true,
groups: {
orchestration: true,
schedules: false,
changeRequests: true,
browser: true,
},
});
expect(store.get().browserTools.enabled).toBe(true);
expect(browserPolicy.isEnabled()).toBe(true);
// Turning master switch off disables browser policy while preserving saved group selections.
await store.patch({ tools: { enabled: false } });
expect(store.get().tools).toEqual({
enabled: false,
groups: {
orchestration: true,
schedules: false,
changeRequests: true,
browser: true,
},
});
expect(store.get().mcp.injectIntoAgents).toBe(false);
expect(browserPolicy.isEnabled()).toBe(false);
// Turning master switch back on restores saved group selections.
await store.patch({ tools: { enabled: true } });
expect(store.get().tools?.groups).toEqual({
orchestration: true,
schedules: false,
changeRequests: true,
browser: true,
});
expect(store.get().mcp.injectIntoAgents).toBe(true);
expect(browserPolicy.isEnabled()).toBe(true);
expect(loadPersistedConfig(home).daemon?.tools).toEqual({
enabled: true,
groups: {
schedules: false,
browser: true,
},
});
});
test("legacy patches update tools and live reload applies daemon.tools changes without restart", async () => {
const home = await createPaseoHome({ version: 1 });
const toMutable = (persisted: ReturnType<typeof loadPersistedConfig>) => {
const reloaded = resolveReloadableConfig(persisted, { env: {} });
const tools = resolveDaemonToolsFromConfigOptions({
tools: reloaded.tools,
mcpEnabled: reloaded.mcpEnabled,
mcpInjectIntoAgents: reloaded.mcpInjectIntoAgents,
browserToolsEnabled: reloaded.browserToolsEnabled,
});
return {
mutable: {
relay: { enabled: false },
tools,
mcp: { enabled: reloaded.mcpEnabled ?? true, injectIntoAgents: tools.enabled },
browserTools: { enabled: tools.groups.browser },
providers: {},
metadataGeneration: { providers: [] },
autoArchiveAfterMerge: false,
enableTerminalAgentHooks: false,
appendSystemPrompt: "",
},
overrideControlledPaths: reloaded.overrideControlledPaths,
};
};
const initial = loadPersistedConfig(home);
const store = new DaemonConfigStore(home, toMutable(initial).mutable, undefined, {
startupPersisted: initial,
reloadSource: { resolve: toMutable },
});
await store.patch({ mcp: { injectIntoAgents: false }, browserTools: { enabled: true } });
expect(store.get().tools).toEqual({
enabled: false,
groups: {
orchestration: true,
schedules: true,
changeRequests: true,
browser: true,
},
});
await store.patch({ tools: { enabled: false, groups: { browser: true } } });
const persistedAfterPatch = loadPersistedConfig(home);
await writeFile(
path.join(home, "config.json"),
JSON.stringify({
...persistedAfterPatch,
daemon: {
...persistedAfterPatch.daemon,
tools: {
enabled: true,
groups: { orchestration: false, schedules: true, changeRequests: false, browser: true },
},
},
}),
);
const reloadResult = await store.reload();
expect(reloadResult.restartRequiredPaths).toEqual([]);
expect(reloadResult.appliedPaths).toEqual([
"daemon.tools.enabled",
"daemon.tools.groups.changeRequests",
"daemon.tools.groups.orchestration",
]);
expect(store.get().tools).toEqual({
enabled: true,
groups: {
orchestration: false,
schedules: true,
changeRequests: false,
browser: true,
},
});
});
});
+46 -6
View File
@@ -25,6 +25,7 @@ import { resolveSpeechConfig } from "./speech/speech-config-resolver.js";
import { readSpeechSettings } from "./speech/speech-settings.js";
import { mergeHostnames, parseHostnamesEnv, type HostnamesConfig } from "./hostnames.js";
import { resolveGitProcessPolicy } from "../utils/git-process-scheduler.js";
import { normalizeDaemonToolGroups, type ResolvedDaemonToolsConfig } from "./tools-config.js";
export {
loadPersistedConfig,
@@ -114,6 +115,8 @@ export type CliConfigOverrides = Partial<{
listen: string;
relayEnabled: boolean;
relayUseTls: boolean;
toolsEnabled: boolean;
// COMPAT(legacyMcpCliFlags): added in v0.18.2, remove after 2027-06-01.
mcpEnabled: boolean;
mcpInjectIntoAgents: boolean;
webUiEnabled: boolean;
@@ -528,8 +531,37 @@ function resolveUsageEnabled(persisted: ReturnType<typeof loadPersistedConfig>):
return persisted.daemon?.usage?.enabled !== false;
}
function resolveBrowserToolsEnabled(persisted: ReturnType<typeof loadPersistedConfig>): boolean {
return persisted.daemon?.browserTools?.enabled ?? false;
function resolveToolsEnabledFromCli(cli: CliConfigOverrides | undefined): boolean | undefined {
if (cli?.toolsEnabled !== undefined) return cli.toolsEnabled;
// COMPAT(legacyMcpCliFlags): added in v0.18.2, remove after 2027-06-01.
if (cli?.mcpEnabled === false || cli?.mcpInjectIntoAgents === false) return false;
if (cli?.mcpInjectIntoAgents === true) return true;
return undefined;
}
function resolveToolsEnabledFromPersisted(
persisted: ReturnType<typeof loadPersistedConfig>,
): boolean {
const explicit = persisted.daemon?.tools?.enabled;
if (explicit !== undefined) return explicit;
// COMPAT(legacyToolsConfig): added in v0.18.2, remove after 2027-06-01.
const legacyMcp = persisted.daemon?.mcp;
if (legacyMcp?.enabled === false || legacyMcp?.injectIntoAgents === false) return false;
return true;
}
function resolveToolsConfig(
cli: CliConfigOverrides | undefined,
persisted: ReturnType<typeof loadPersistedConfig>,
): ResolvedDaemonToolsConfig {
const enabled = resolveToolsEnabledFromCli(cli) ?? resolveToolsEnabledFromPersisted(persisted);
return {
enabled,
groups: normalizeDaemonToolGroups(
persisted.daemon?.tools?.groups,
persisted.daemon?.browserTools?.enabled,
),
};
}
/**
@@ -549,12 +581,18 @@ function resolveStaticLoadConfigSettings(
cli: CliConfigOverrides | undefined,
persisted: ReturnType<typeof loadPersistedConfig>,
) {
const tools = resolveToolsConfig(cli, persisted);
// COMPAT(legacyToolsConfig): added in v0.18.2, remove after 2027-06-01.
const mcpEnabled =
cli?.mcpEnabled ??
(persisted.daemon?.tools?.enabled !== undefined ? true : persisted.daemon?.mcp?.enabled) ??
true;
return {
mcpEnabled: cli?.mcpEnabled ?? persisted.daemon?.mcp?.enabled ?? true,
mcpInjectIntoAgents:
cli?.mcpInjectIntoAgents ?? persisted.daemon?.mcp?.injectIntoAgents ?? false,
tools,
mcpEnabled,
mcpInjectIntoAgents: tools.enabled,
usageEnabled: resolveUsageEnabled(persisted),
browserToolsEnabled: resolveBrowserToolsEnabled(persisted),
browserToolsEnabled: tools.groups.browser,
autoArchiveAfterMerge: persisted.daemon?.autoArchiveAfterMerge ?? false,
appendSystemPrompt: resolveAppendSystemPrompt(persisted),
...resolveProfileLists(persisted),
@@ -580,6 +618,7 @@ export type ResolvedDaemonSettings = Pick<
| "corsAllowedOrigins"
| "hostnames"
| "trustedProxies"
| "tools"
| "mcpEnabled"
| "mcpInjectIntoAgents"
| "usageEnabled"
@@ -743,6 +782,7 @@ function resolveCoreDaemonOverridePaths(
if (cli?.listen !== undefined || env.PASEO_LISTEN !== undefined) {
paths.push("daemon.listen");
}
if (cli?.toolsEnabled !== undefined) paths.push("daemon.tools.enabled");
if (cli?.mcpEnabled !== undefined) paths.push("daemon.mcp.enabled");
if (cli?.mcpInjectIntoAgents !== undefined) paths.push("daemon.mcp.injectIntoAgents");
// Hostname sources append instead of replacing one another, so a launch value
@@ -1548,6 +1548,64 @@ describe("DaemonConfigStore reload", () => {
});
});
describe("plugin entries edited in config.json while the daemon runs", () => {
const other = { source: "directory", path: "/other", enabled: true } as const;
const local = { source: "directory", path: "/local", enabled: true } as const;
function disableOther(store: DaemonConfigStore) {
return store.patch((current) => ({
plugins: { ...current.plugins, other: { ...current.plugins.other!, enabled: false } },
}));
}
function removeOther(store: DaemonConfigStore) {
return store.patch((current) => {
const { other: _removed, ...rest } = current.plugins;
return { plugins: rest };
});
}
test("keeps a hand-added entry on disk when another plugin changes", async () => {
const { paseoHome, store, persisted } = createReloadableStore({
initialPersisted: { version: 1, plugins: { other } },
});
writeConfig(paseoHome, { ...persisted, plugins: { other, local } });
await disableOther(store);
expect(loadPersistedConfig(paseoHome).plugins).toEqual({
other: { ...other, enabled: false },
local,
});
expect(store.get().plugins).toEqual({ other: { ...other, enabled: false } });
});
test("does not write back an entry removed by hand when another plugin changes", async () => {
const { paseoHome, store, persisted } = createReloadableStore({
initialPersisted: { version: 1, plugins: { other, local } },
});
writeConfig(paseoHome, { ...persisted, plugins: { other } });
await disableOther(store);
expect(loadPersistedConfig(paseoHome).plugins).toEqual({
other: { ...other, enabled: false },
});
});
test("removing a plugin deletes only that entry from disk", async () => {
const { paseoHome, store, persisted } = createReloadableStore({
initialPersisted: { version: 1, plugins: { other } },
});
writeConfig(paseoHome, { ...persisted, plugins: { other, local } });
await removeOther(store);
expect(loadPersistedConfig(paseoHome).plugins).toEqual({ local });
expect(store.get().plugins).toEqual({});
});
});
test("serializes overlapping patches before committing their combined state", async () => {
const { paseoHome, store } = createReloadableStore();
const first = store.patch({ appendSystemPrompt: "first" });
@@ -21,6 +21,7 @@ import {
import type { AgentSkillSelection } from "@getpaseo/protocol/messages";
import type { SpeechSettingsPatch } from "@getpaseo/protocol/speech/rpc-schemas";
import { mergeSpeechSettingsPatch, type SpeechSettingsOwner } from "./speech/speech-settings.js";
import { resolveDaemonToolsFromMutableConfig } from "./tools-config.js";
export type { MutableDaemonConfig, MutableDaemonConfigPatch } from "@getpaseo/protocol/messages";
@@ -30,8 +31,19 @@ type ProviderOverride = import("./agent/provider-launch-config.js").ProviderOver
interface SupportedMutableConfigPatch {
relay?: { enabled?: boolean; requireProtectedSecurity?: boolean };
// COMPAT(legacyToolsConfig): added in v0.18.2, remove after 2027-06-01.
mcp?: { injectIntoAgents?: boolean };
tools?: {
enabled?: boolean;
groups?: {
orchestration?: boolean;
schedules?: boolean;
changeRequests?: boolean;
browser?: boolean;
};
};
usage?: { enabled: boolean };
// COMPAT(legacyToolsConfig): added in v0.18.2, remove after 2027-06-01.
browserTools?: { enabled?: boolean };
providers?: MutableDaemonConfig["providers"];
removeProviders?: string[];
@@ -289,6 +301,11 @@ const RELOADABLE_PATHS = [
"daemon.relay.requireProtectedSecurity",
"daemon.mcp.enabled",
"daemon.mcp.injectIntoAgents",
"daemon.tools.enabled",
"daemon.tools.groups.orchestration",
"daemon.tools.groups.schedules",
"daemon.tools.groups.changeRequests",
"daemon.tools.groups.browser",
"daemon.usage.enabled",
"daemon.browserTools.enabled",
"daemon.hostnames",
@@ -317,6 +334,11 @@ const PERSISTED_TO_MUTABLE_PATH = new Map<string, string>([
["daemon.relay.requireProtectedSecurity", "relay.requireProtectedSecurity"],
["daemon.mcp.enabled", "mcp.enabled"],
["daemon.mcp.injectIntoAgents", "mcp.injectIntoAgents"],
["daemon.tools.enabled", "tools.enabled"],
["daemon.tools.groups.orchestration", "tools.groups.orchestration"],
["daemon.tools.groups.schedules", "tools.groups.schedules"],
["daemon.tools.groups.changeRequests", "tools.groups.changeRequests"],
["daemon.tools.groups.browser", "tools.groups.browser"],
["daemon.usage.enabled", "usage.enabled"],
["daemon.browserTools.enabled", "browserTools.enabled"],
["daemon.hostnames", "hostnames"],
@@ -340,6 +362,17 @@ const PERSISTED_TO_MUTABLE_PATH = new Map<string, string>([
["pluginsEnabled", "pluginsEnabled"],
]);
// COMPAT(legacyToolsConfig): added in v0.18.2, remove after 2027-06-01.
// Legacy mcp/browserTools paths mirror into daemon.tools on the mutable snapshot;
// only report the persisted leaf that actually changed on disk during reload.
const ALIASED_TOOL_RELOAD_PATHS = new Set<string>([
"daemon.mcp.enabled",
"daemon.mcp.injectIntoAgents",
"daemon.browserTools.enabled",
"daemon.tools.enabled",
"daemon.tools.groups.browser",
]);
function pathBelongsTo(path: string, owner: string): boolean {
return path === owner || path.startsWith(`${owner}.`);
}
@@ -401,9 +434,95 @@ function pickMetadataGenerationPatch(
return Object.keys(picked).length > 0 ? { metadataGeneration: picked } : {};
}
function mergePatchedToolGroups(
currentGroups: ReturnType<typeof resolveDaemonToolsFromMutableConfig>["groups"],
patch: Pick<SupportedMutableConfigPatch, "tools" | "browserTools">,
) {
const patchGroups = patch.tools?.groups;
return {
orchestration: patchGroups?.orchestration ?? currentGroups.orchestration,
schedules: patchGroups?.schedules ?? currentGroups.schedules,
changeRequests: patchGroups?.changeRequests ?? currentGroups.changeRequests,
browser: patchGroups?.browser ?? patch.browserTools?.enabled ?? currentGroups.browser,
};
}
function syncToolsConfigOnMerged(
merged: MutableDaemonConfig,
current: MutableDaemonConfig,
patch: Pick<SupportedMutableConfigPatch, "tools" | "mcp" | "browserTools">,
): void {
const hasToolsChange =
patch.tools !== undefined ||
patch.mcp?.injectIntoAgents !== undefined ||
patch.browserTools?.enabled !== undefined;
if (!hasToolsChange) return;
const currentTools = resolveDaemonToolsFromMutableConfig(current);
const nextTools = {
enabled: patch.tools?.enabled ?? patch.mcp?.injectIntoAgents ?? currentTools.enabled,
groups: mergePatchedToolGroups(currentTools.groups, patch),
};
merged.tools = nextTools;
// COMPAT(legacyToolsConfig): added in v0.18.2, keep legacy wire fields synced for older clients.
merged.mcp = { ...merged.mcp, injectIntoAgents: nextTools.enabled };
merged.browserTools = { ...merged.browserTools, enabled: nextTools.groups.browser };
}
function mergeToolsDaemonPatch(
next: NonNullable<PersistedConfig["daemon"]>,
patch: Pick<SupportedMutableConfigPatch, "tools" | "mcp" | "browserTools">,
): void {
if (patch.tools !== undefined) {
next.tools = {
...next.tools,
...(patch.tools.enabled !== undefined ? { enabled: patch.tools.enabled } : {}),
...(patch.tools.groups ? { groups: { ...next.tools?.groups, ...patch.tools.groups } } : {}),
};
}
// COMPAT(legacyToolsConfig): added in v0.18.2, remove after 2027-06-01.
if (patch.mcp?.injectIntoAgents !== undefined) {
next.mcp = { ...next.mcp, injectIntoAgents: patch.mcp.injectIntoAgents };
if (patch.tools?.enabled === undefined && next.tools !== undefined) {
next.tools = { ...next.tools, enabled: patch.mcp.injectIntoAgents };
}
}
// COMPAT(legacyToolsConfig): added in v0.18.2, remove after 2027-06-01.
if (patch.browserTools?.enabled !== undefined) {
next.browserTools = { ...next.browserTools, enabled: patch.browserTools.enabled };
if (patch.tools?.groups?.browser === undefined && next.tools?.groups?.browser !== undefined) {
next.tools = {
...next.tools,
groups: { ...next.tools.groups, browser: patch.browserTools.enabled },
};
}
}
}
function pickToolsPatch(
tools: MutableDaemonConfigPatch["tools"],
): Pick<SupportedMutableConfigPatch, "tools"> {
if (!tools) return {};
const groups: NonNullable<NonNullable<SupportedMutableConfigPatch["tools"]>["groups"]> = {
...(tools.groups?.orchestration !== undefined
? { orchestration: tools.groups.orchestration }
: {}),
...(tools.groups?.schedules !== undefined ? { schedules: tools.groups.schedules } : {}),
...(tools.groups?.changeRequests !== undefined
? { changeRequests: tools.groups.changeRequests }
: {}),
...(tools.groups?.browser !== undefined ? { browser: tools.groups.browser } : {}),
};
const picked: NonNullable<SupportedMutableConfigPatch["tools"]> = {
...(tools.enabled !== undefined ? { enabled: tools.enabled } : {}),
...(Object.keys(groups).length > 0 ? { groups } : {}),
};
return Object.keys(picked).length > 0 ? { tools: picked } : {};
}
function pickSupportedPatchFields(patch: MutableDaemonConfigPatch): SupportedMutableConfigPatch {
return {
...pickRelayPatch(patch.relay),
...pickToolsPatch(patch.tools),
usage: patch.usage,
...(patch.mcp?.injectIntoAgents !== undefined
? { mcp: { injectIntoAgents: patch.mcp.injectIntoAgents } }
@@ -574,6 +693,7 @@ export class DaemonConfigStore {
const removedProviders = Array.from(new Set(removeProviders));
const merged = deepMerge(this.current, configPatch);
merged.providers = withNormalizedProvidersShownModels(merged.providers);
syncToolsConfigOnMerged(merged, this.current, patch);
if (speechPatch !== undefined) Object.assign(merged, this.readPatchedSpeech(speechPatch));
if (parsedPatch.skills?.selection !== undefined) {
merged.skills = { selection: parsedPatch.skills.selection };
@@ -712,6 +832,12 @@ export class DaemonConfigStore {
if (resolved.overrideControlledPaths.some((owner) => pathBelongsTo(persistedPath, owner))) {
return false;
}
if (
ALIASED_TOOL_RELOAD_PATHS.has(persistedPath) &&
!changedSinceLastApply.some((path) => pathBelongsTo(path, persistedPath))
) {
return false;
}
const mutablePath = PERSISTED_TO_MUTABLE_PATH.get(persistedPath);
return (
mutablePath !== undefined &&
@@ -886,6 +1012,7 @@ export class DaemonConfigStore {
patch,
removeProviders,
persistRelayEnabled: this.relayEnabledMutable,
pluginsBeforePatch: this.current.plugins ?? {},
});
const nextPersisted = merge(persisted);
const knownNext = merge(this.lastKnownPersisted);
@@ -899,8 +1026,9 @@ function mergeMutablePatchIntoPersistedConfig(params: {
patch: Omit<SupportedMutableConfigPatch, "removeProviders">;
removeProviders: readonly string[];
persistRelayEnabled: boolean;
pluginsBeforePatch: PluginSources;
}): PersistedConfig {
const { persisted, patch, removeProviders, persistRelayEnabled } = params;
const { persisted, patch, removeProviders, persistRelayEnabled, pluginsBeforePatch } = params;
const daemon = mergeMutableDaemonPatch(persisted.daemon, patch, persistRelayEnabled);
const agents = mergeMutableAgentPatch(persisted.agents, patch, removeProviders);
const withSpeech = patch.features
@@ -909,12 +1037,40 @@ function mergeMutablePatchIntoPersistedConfig(params: {
return {
...withSpeech,
...(patch.pluginsEnabled !== undefined ? { pluginsEnabled: patch.pluginsEnabled } : {}),
...(patch.plugins !== undefined ? { plugins: patch.plugins } : {}),
...(patch.plugins !== undefined
? {
plugins: applyChangedPluginEntries({
persisted: persisted.plugins,
before: pluginsBeforePatch,
after: patch.plugins,
}),
}
: {}),
...(daemon ? { daemon } : { daemon: undefined }),
...(agents ? { agents } : { agents: undefined }),
} as PersistedConfig;
}
type PluginSources = NonNullable<MutableDaemonConfig["plugins"]>;
// The daemon never reloads plugin entries from config.json, so its copy can be stale. Writing only
// the entries this patch changed keeps entries other writers put on disk until the next restart.
function applyChangedPluginEntries(params: {
persisted: PersistedConfig["plugins"];
before: PluginSources;
after: PluginSources;
}): PluginSources {
const { persisted, before, after } = params;
const next: PluginSources = { ...persisted };
for (const [pluginId, source] of Object.entries(after)) {
if (!isEqualValue(before[pluginId], source)) next[pluginId] = source;
}
for (const pluginId of Object.keys(before)) {
if (!(pluginId in after)) delete next[pluginId];
}
return next;
}
function mergeMutableAgentPatch(
persistedAgents: PersistedConfig["agents"],
patch: Omit<SupportedMutableConfigPatch, "removeProviders">,
@@ -975,13 +1131,8 @@ function mergeMutableDaemonPatch(
if (patch.relay?.requireProtectedSecurity !== undefined) {
next.relay = { ...next.relay, requireProtectedSecurity: patch.relay.requireProtectedSecurity };
}
if (patch.mcp?.injectIntoAgents !== undefined) {
next.mcp = { ...next.mcp, injectIntoAgents: patch.mcp.injectIntoAgents };
}
mergeToolsDaemonPatch(next, patch);
if (patch.usage) next.usage = patch.usage;
if (patch.browserTools?.enabled !== undefined) {
next.browserTools = { ...next.browserTools, enabled: patch.browserTools.enabled };
}
if (patch.autoArchiveAfterMerge !== undefined) {
next.autoArchiveAfterMerge = patch.autoArchiveAfterMerge;
}
@@ -111,11 +111,13 @@ function applyCliFlagOverrides(config: ReturnType<typeof loadConfig>): void {
}
if (process.argv.includes("--no-mcp")) {
config.mcpEnabled = false;
if (config.tools) config.tools = { ...config.tools, enabled: false };
cli.mcpEnabled = false;
override("daemon.mcp.enabled");
}
if (process.argv.includes("--no-inject-mcp")) {
config.mcpInjectIntoAgents = false;
if (config.tools) config.tools = { ...config.tools, enabled: false };
cli.mcpInjectIntoAgents = false;
override("daemon.mcp.injectIntoAgents");
}
@@ -285,6 +285,7 @@ export const PersistedConfigSchema = z
.describe(
'Express trusted proxy setting for X-Forwarded-* headers. Defaults to ["loopback"]. Use true only when the final trusted proxy overwrites client-supplied forwarded headers.',
),
// COMPAT(legacyToolsConfig): added in v0.18.2, remove after 2027-06-01.
mcp: z
.object({
enabled: z.boolean().optional(),
@@ -292,7 +293,23 @@ export const PersistedConfigSchema = z
})
.passthrough()
.optional(),
tools: z
.object({
enabled: z.boolean().optional(),
groups: z
.object({
orchestration: z.boolean().optional(),
schedules: z.boolean().optional(),
changeRequests: z.boolean().optional(),
browser: z.boolean().optional(),
})
.strict()
.optional(),
})
.strict()
.optional(),
usage: z.object({ enabled: z.boolean().optional() }).optional(),
// COMPAT(legacyToolsConfig): added in v0.18.2, remove after 2027-06-01.
browserTools: z
.object({
enabled: z.boolean().optional(),
@@ -0,0 +1,47 @@
import type { MutableDaemonConfig, MutableDaemonToolGroups } from "@getpaseo/protocol/messages";
import { DEFAULT_DAEMON_TOOL_GROUPS, type BuiltInToolGroup } from "@getpaseo/protocol/tool-groups";
export type ResolvedDaemonToolGroups = Record<BuiltInToolGroup, boolean>;
export interface ResolvedDaemonToolsConfig {
enabled: boolean;
groups: ResolvedDaemonToolGroups;
}
export function normalizeDaemonToolGroups(
groups?: MutableDaemonToolGroups,
legacyBrowserEnabled?: boolean,
): ResolvedDaemonToolGroups {
return {
orchestration: groups?.orchestration ?? DEFAULT_DAEMON_TOOL_GROUPS.orchestration,
schedules: groups?.schedules ?? DEFAULT_DAEMON_TOOL_GROUPS.schedules,
changeRequests: groups?.changeRequests ?? DEFAULT_DAEMON_TOOL_GROUPS.changeRequests,
// COMPAT(legacyBrowserToolsConfig): added in v0.18.2, remove after 2027-06-01.
browser: groups?.browser ?? legacyBrowserEnabled ?? DEFAULT_DAEMON_TOOL_GROUPS.browser,
};
}
export function resolveDaemonToolsFromMutableConfig(
config: Pick<MutableDaemonConfig, "tools" | "mcp" | "browserTools">,
): ResolvedDaemonToolsConfig {
// COMPAT(legacyToolsConfig): added in v0.18.2, remove after 2027-06-01.
const enabled =
config.tools?.enabled ??
(config.mcp.enabled !== false && config.mcp.injectIntoAgents !== false);
const groups = normalizeDaemonToolGroups(config.tools?.groups, config.browserTools?.enabled);
return { enabled, groups };
}
export function resolveDaemonToolsFromConfigOptions(options: {
tools?: { enabled?: boolean; groups?: MutableDaemonToolGroups };
mcpEnabled?: boolean;
mcpInjectIntoAgents?: boolean;
browserToolsEnabled?: boolean;
}): ResolvedDaemonToolsConfig {
// COMPAT(legacyToolsConfig): added in v0.18.2, remove after 2027-06-01.
const enabled =
options.tools?.enabled ??
(options.mcpEnabled !== false && options.mcpInjectIntoAgents !== false);
const groups = normalizeDaemonToolGroups(options.tools?.groups, options.browserToolsEnabled);
return { enabled, groups };
}
@@ -1153,6 +1153,7 @@ describe("relay external socket reconnect behavior", () => {
expect(serverInfo.features?.stableProjectIdentity).toBe(true);
expect(serverInfo.features?.canonicalSubmittedPrompts).toBe(true);
expect(serverInfo.features?.providersSnapshotCwd).toBe(true);
expect(serverInfo.features?.daemonToolsConfig).toBe(true);
expect(serverInfo.features?.hopliteProvider).toBe(false);
expect(serverInfo.features?.fxProvider).toBe(false);
expect(serverInfo.features?.pluginLogs).toBe(true);
@@ -2139,6 +2139,8 @@ export class VoiceAssistantWebSocketServer {
relayProtectedSecurity: true,
usageSetting: true,
usageSources: true,
// COMPAT(daemonToolsConfig): added in v0.18.2, remove gate after 2027-06-01.
daemonToolsConfig: true,
providerInstallation: true,
ownedSubscriptions: true,
providerOptionControls: true,
@@ -168,7 +168,7 @@ if [ "$1" = "repo" ] && [ "$2" = "view" ]; then
exit 0
fi
if [ "$1" = "api" ]; then
echo '{"url":"https://github.acme.internal/acme/repo/pull/7","number":7}'
echo '{"url":"https://github.acme.internal/api/v3/repos/acme/repo/pulls/7","html_url":"https://github.acme.internal/acme/repo/pull/7","number":7}'
exit 0
fi
echo "unexpected gh args: $*" >&2
@@ -4827,7 +4827,11 @@ describe("ForgeService", () => {
it("resolves the repo slug from the workspace when creating a pull request", async () => {
const runner = createRunner([
JSON.stringify({ owner: { login: "acme" }, name: "repo" }),
JSON.stringify({ url: "https://github.com/acme/repo/pull/7", number: 7 }),
JSON.stringify({
url: "https://api.github.com/repos/acme/repo/pulls/7",
html_url: "https://github.com/acme/repo/pull/7",
number: 7,
}),
]);
const service = createGitHubService({
runner: runner.runner,
@@ -4866,7 +4870,11 @@ describe("ForgeService", () => {
it("routes gh calls to the resolved GitHub Enterprise host via GH_HOST", async () => {
const runner = createRunner([
JSON.stringify({ owner: { login: "acme" }, name: "repo" }),
JSON.stringify({ url: "https://github.acme.internal/acme/repo/pull/7", number: 7 }),
JSON.stringify({
url: "https://github.acme.internal/api/v3/repos/acme/repo/pulls/7",
html_url: "https://github.acme.internal/acme/repo/pull/7",
number: 7,
}),
]);
const service = createGitHubService({
runner: runner.runner,
@@ -2805,12 +2805,12 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
args,
{ cwd: input.cwd },
z.object({
url: z.string(),
html_url: z.string(),
number: z.number(),
}),
"{}",
);
return parsed;
return { url: parsed.html_url, number: parsed.number };
},
async mergePullRequest(input) {
@@ -70,6 +70,33 @@
},
"additionalProperties": {}
},
"tools": {
"type": "object",
"properties": {
"enabled": {
"type": "boolean"
},
"groups": {
"type": "object",
"properties": {
"orchestration": {
"type": "boolean"
},
"schedules": {
"type": "boolean"
},
"changeRequests": {
"type": "boolean"
},
"browser": {
"type": "boolean"
}
},
"additionalProperties": false
}
},
"additionalProperties": false
},
"usage": {
"type": "object",
"properties": {
+7 -4
View File
@@ -25,20 +25,23 @@ Because you share the browser with the agent, you can watch it work — and step
Browser tools are off by default. Turn them on per host:
- **In the app:** open **Settings → Host → Tools & prompts** and turn on **Browser tools**.
- **In the app:** open **Settings → Host → Tools & prompts**. Turn on **Enable tools**, expand it, and turn on **Browser**.
- **In `config.json`** (`~/.paseo/config.json`):
```json
{
"daemon": {
"browserTools": {
"enabled": true
"tools": {
"enabled": true,
"groups": {
"browser": true
}
}
}
}
```
The tools are part of the [Paseo MCP toolset](/docs/mcp), so **Enable Paseo tools** on the same page must also be on for agents to receive them. Existing agents may need a reload to pick up new tools.
The tools are part of the [Paseo toolset](/docs/mcp). Start a new agent or reload an existing one to pick up new tools.
> Browser tools let agents access and control Paseo browser tabs, including logged-in browser state. Only enable this for agents you trust.
+7 -4
View File
@@ -23,20 +23,23 @@ Paseo 中的 Agent 可以操作真实的浏览器标签页,也就是你在 Pas
浏览器工具默认关闭。按主机开启:
- **在应用中**:打开 **设置 → 主机 → 工具与提示词**,开启 **Browser tools**。
- **在应用中**:打开 **设置 → 主机 → 工具与提示词**。开启 **启用工具**,展开它,然后开启 **浏览器**。
- **在 `config.json` 中**(`~/.paseo/config.json`):
```json
{
"daemon": {
"browserTools": {
"enabled": true
"tools": {
"enabled": true,
"groups": {
"browser": true
}
}
}
}
```
这些工具属于 [Paseo MCP 工具集](/docs/mcp),因此同一页面上的 **启用 Paseo tools** 也必须开启,Agent 才能获得它们。已有的 Agent 可能需要重新加载才能获得新工具。
这些工具属于 [Paseo 工具集](/docs/mcp)。启动新的 Agent 或重新加载已有的 Agent 以获得新工具。
> 浏览器工具允许 Agent 访问和控制 Paseo 浏览器标签页,包括已登录的浏览器状态。只为你信任的 Agent 启用。
+17 -11
View File
@@ -12,26 +12,32 @@ category: Orchestration
## Configuration
| Setting | Default | Purpose |
| ----------------------------- | ------- | -------------------------------------------------- |
| `daemon.mcp.enabled` | `true` | Run the MCP server. |
| `daemon.mcp.injectIntoAgents` | `false` | Give agents launched by Paseo access to its tools. |
| Setting | Default | Purpose |
| ------------------------------------ | ------- | ------------------------------------------------------------- |
| `daemon.tools.enabled` | `true` | Give agents launched by Paseo access to its tools. |
| `daemon.tools.groups.orchestration` | `true` | Hosts, workspaces, agents, providers, scripts, and terminals. |
| `daemon.tools.groups.schedules` | `true` | Schedules and heartbeats. |
| `daemon.tools.groups.changeRequests` | `true` | Watching pull requests and merge requests. |
| `daemon.tools.groups.browser` | `false` | [Browser automation](/docs/browser). |
Depending on the provider, Paseo delivers tools through its native tool interface or MCP. The capabilities are the same. Start a new agent or reload an existing one after changing injection settings.
In the app, open **Settings → Host → Tools & prompts**. Turn on **Enable tools**, then expand it to turn each group on or off. Tools added by plugins follow **Enable tools**.
Depending on the provider, Paseo delivers tools through its native tool interface or MCP. The capabilities are the same. Start a new agent or reload an existing one after changing tool settings.
If `daemon.tools` is absent, Paseo reads the older `daemon.mcp.injectIntoAgents` and `daemon.browserTools.enabled` settings.
## Limit Paseo tools by provider
Use provider policies when different agent profiles should receive different Paseo tools. Enable
tool injection globally, then add `paseoTools` to the exact provider IDs you launch:
Use provider policies when different agent profiles should receive different Paseo tools. Keep
`daemon.tools.enabled` on, then add `paseoTools` to the exact provider IDs you launch:
```json
{
"$schema": "https://paseo.sh/schemas/paseo.config.v1.json",
"version": 1,
"daemon": {
"mcp": {
"enabled": true,
"injectIntoAgents": true
"tools": {
"enabled": true
}
},
"agents": {
@@ -66,7 +72,7 @@ Omitting `paseoTools` enables the complete catalog. Set `enabled` to `false` to
or list exact tool IDs in `disabledTools` to remove selected tools. Custom profiles do not inherit
this policy from `extends`; configure each custom provider ID separately.
Browser tools still require browser tools to be enabled and a connected browser host. The
Browser tools still require the `browser` tool group and a connected browser host. The
voice-only `speak` tool is separate from this policy.
This setting limits the catalog presented to an agent. It is not a security boundary for an agent
+16 -10
View File
@@ -10,25 +10,31 @@ nav: MCP 参考
## 配置 {#configuration}
| 设置 | 默认值 | 用途 |
| ----------------------------- | ------- | ---------------------------------------- |
| `daemon.mcp.enabled` | `true` | 运行 MCP 服务器。 |
| `daemon.mcp.injectIntoAgents` | `false` | 让 Paseo 启动的 Agent 可以使用它的工具。 |
| 设置 | 默认值 | 用途 |
| ------------------------------------ | ------- | ------------------------------------------- |
| `daemon.tools.enabled` | `true` | 让 Paseo 启动的 Agent 可以使用它的工具。 |
| `daemon.tools.groups.orchestration` | `true` | 主机、工作区、Agent、Provider、脚本和终端。 |
| `daemon.tools.groups.schedules` | `true` | 计划任务和心跳。 |
| `daemon.tools.groups.changeRequests` | `true` | 监控 Pull Request 和 Merge Request。 |
| `daemon.tools.groups.browser` | `false` | [浏览器自动化](/docs/browser)。 |
根据 Provider 的不同,Paseo 通过其原生工具接口或 MCP 提供工具,能力是相同的。修改注入设置后,请启动新的 Agent 或重新加载已有的 Agent。
在应用中,打开 **设置 → 主机 → 工具与提示词**。开启 **启用工具**,然后展开它来开关各个工具组。插件提供的工具同样受 **启用工具** 控制。
根据 Provider 的不同,Paseo 通过其原生工具接口或 MCP 提供工具,能力是相同的。修改工具设置后,请启动新的 Agent 或重新加载已有的 Agent。
如果没有 `daemon.tools`,Paseo 会读取旧的 `daemon.mcp.injectIntoAgents` 和 `daemon.browserTools.enabled` 设置。
## 按 Provider 限制 Paseo 工具 {#limit-paseo-tools-by-provider}
当不同的 Agent 配置应获得不同的 Paseo 工具时,请使用 Provider 策略。先全局启用工具注入,然后在你启动所用的确切 Provider ID 上添加 `paseoTools`:
当不同的 Agent 配置应获得不同的 Paseo 工具时,请使用 Provider 策略。保持 `daemon.tools.enabled` 开启,然后在你启动所用的确切 Provider ID 上添加 `paseoTools`:
```json
{
"$schema": "https://paseo.sh/schemas/paseo.config.v1.json",
"version": 1,
"daemon": {
"mcp": {
"enabled": true,
"injectIntoAgents": true
"tools": {
"enabled": true
}
},
"agents": {
@@ -60,7 +66,7 @@ nav: MCP 参考
省略 `paseoTools` 会启用完整的工具目录。把 `enabled` 设为 `false` 会移除整个目录,在 `disabledTools` 中列出确切的工具 ID 则只移除所选的工具。自定义配置不会从 `extends` 继承这一策略;请为每个自定义 Provider ID 分别配置。
浏览器工具仍然需要启用浏览器工具并连接一个浏览器主机。仅用于语音的 `speak` 工具不受此策略控制。
浏览器工具仍然需要开启 `browser` 工具组并连接一个浏览器主机。仅用于语音的 `speak` 工具不受此策略控制。
这项设置限制的是呈现给 Agent 的工具目录。对于可以通过 shell 访问主机的 Agent,它不是安全边界。
+2 -2
View File
@@ -33,7 +33,7 @@ Use built-in Paseo tools or the CLI. Both let an agent launch and coordinate wor
Enable Paseo tools so agents running inside Paseo can manage agents and workspaces on their host directly.
1. Open **Settings → Host → Tools & prompts**.
2. Turn on **Enable Paseo tools**. Tool injection is off by default.
2. Make sure that **Enable tools** is on. It is on by default.
3. Start a new agent, or reload an existing agent so it receives the tools.
4. Ask:
@@ -45,7 +45,7 @@ See the [MCP reference](/docs/mcp) for tool configuration and the full catalog.
### CLI
Agents with shell access can also use the Paseo CLI. This route does not require enabling tool injection. With Paseo installed, a running host, and Codex configured:
Agents with shell access can also use the Paseo CLI. This route does not require **Enable tools**. With Paseo installed, a running host, and Codex configured:
```bash
paseo run --provider codex --no-wait \
+2 -2
View File
@@ -31,7 +31,7 @@ Paseo 让你的编程 Agent 协调其他 Agent,把工作分配到不同的 Pro
启用 Paseo 工具后,在 Paseo 中运行的 Agent 可以直接管理其主机上的 Agent 和工作区。
1. 打开 **设置 → 主机 → 工具与提示词**。
2. 打开 **启用 Paseo tools**。工具注入默认关闭。
2. 确认 **启用工具** 已开启。它默认开启。
3. 启动一个新的 Agent,或重新加载已有的 Agent,让它获得这些工具。
4. 提出要求:
@@ -43,7 +43,7 @@ Paseo 让你的编程 Agent 协调其他 Agent,把工作分配到不同的 Pro
### CLI {#cli}
有 shell 访问权限的 Agent 也可以使用 Paseo CLI。这种方式不需要启用工具注入。在已安装 Paseo、主机正在运行并且配置了 Codex 的情况下:
有 shell 访问权限的 Agent 也可以使用 Paseo CLI。这种方式不需要开启 **启用工具**。在已安装 Paseo、主机正在运行并且配置了 Codex 的情况下:
```bash
paseo run --provider codex --no-wait \