mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-02 06:33:05 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67439dc7fc | ||
|
|
4b03f96f80 | ||
|
|
11556aaf4c | ||
|
|
1614903862 | ||
|
|
509ca80e4e | ||
|
|
9233e8cd38 | ||
|
|
c689b5626e | ||
|
|
efc64a5443 | ||
|
|
7efa14238d | ||
|
|
dbbcb103ba | ||
|
|
7f318bf7cf | ||
|
|
04fe4be40f | ||
|
|
2d75cc80b2 | ||
|
|
bfac132920 | ||
|
|
34f996b32a | ||
|
|
3e83f433da | ||
|
|
674530152e | ||
|
|
919e44b319 | ||
|
|
4fe44038e3 | ||
|
|
9b0542d127 | ||
|
|
8130147426 | ||
|
|
fa89738e3a |
@@ -135,32 +135,6 @@ jobs:
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# Backport electron-builder#10172 to the pinned build tool only.
|
||||
# Remove this step when app-builder-lib is upgraded to a release containing it.
|
||||
- name: Repair temporary keychain password in signing tool
|
||||
shell: bash
|
||||
run: |
|
||||
node <<'KEYCHAIN_FIX'
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const manifestPath = require.resolve('app-builder-lib/package.json');
|
||||
if (JSON.parse(fs.readFileSync(manifestPath, 'utf8')).version !== '26.8.1') {
|
||||
throw new Error('Reassess/remove the signing backport for the new app-builder-lib version');
|
||||
}
|
||||
const sourcePath = path.join(path.dirname(manifestPath), 'out/codeSign/macCodeSign.js');
|
||||
let source = fs.readFileSync(sourcePath, 'utf8');
|
||||
const replacements = [
|
||||
['importCerts(keychainFile, certPaths, cscPasswords)', 'importCerts(keychainFile, certPaths, cscPasswords, keychainPassword)'],
|
||||
['importCerts(keychainFile, paths, keyPasswords)', 'importCerts(keychainFile, paths, keyPasswords, keychainPassword)'],
|
||||
['["set-key-partition-list", "-S", "apple-tool:,apple:", "-s", "-k", password, keychainFile]', '["set-key-partition-list", "-S", "apple-tool:,apple:", "-s", "-k", keychainPassword, keychainFile]'],
|
||||
];
|
||||
for (const [before, after] of replacements) {
|
||||
if (source.split(before).length !== 2) throw new Error('Unexpected signing tool source; refusing to patch');
|
||||
source = source.replace(before, after);
|
||||
}
|
||||
fs.writeFileSync(sourcePath, source);
|
||||
KEYCHAIN_FIX
|
||||
|
||||
- name: Set desktop package version from tag
|
||||
shell: bash
|
||||
run: |
|
||||
|
||||
@@ -74,7 +74,10 @@ registrations remain inspectable; a changed destination requires explicit identi
|
||||
|
||||
Both daemons advertise `connectedHosts`; the shared link additionally requires `hostMultiplexing`.
|
||||
A completes capability and pinned-identity checks on each physical recovery before admitting channels. There is no local fallback. An older daemon continues to serve existing local
|
||||
operations; requesting this feature gives update guidance.
|
||||
operations; requesting this feature gives update guidance. The registry retries an older destination
|
||||
with capped backoff, so it comes online once updated. Self, duplicate, changed-identity, and
|
||||
authentication failures stay in `error` until an update changes the connection, `enabled`, or
|
||||
`replaceIdentity`, or A restarts.
|
||||
|
||||
Disposing a routed API releases its observations and session. It does not remove the saved host or
|
||||
affect sibling API scopes. Disposing the origin cascades to its derived scopes. Observations restore
|
||||
|
||||
+21
-3
@@ -357,9 +357,27 @@ keys are stored under a `param.` prefix; plugins never see it and may use any ke
|
||||
`openScreen` validates its input once (`parsePluginOpenScreenInput`); code past it trusts the
|
||||
params.
|
||||
|
||||
RPC contracts validate inputs and outputs in both the app and plugin subprocess. `useRpc` returns a
|
||||
typed async function. Use the host-provided `@tanstack/react-query` for request state and caching;
|
||||
Paseo gives each plugin installation its own query client.
|
||||
RPC and subscription contracts validate inputs, outputs, and events in both the app and plugin
|
||||
subprocess. `useRpc` returns a typed async function. Use the host-provided `@tanstack/react-query`
|
||||
for request state and caching; Paseo gives each plugin installation its own query client.
|
||||
|
||||
A subscription is a session-owned observation (`plugin-rpc` delivery family): the session that
|
||||
subscribed owns its lifetime, so release, disconnect, plugin stop, and reload need no plugin code.
|
||||
Each subscriber gets its own handler call in the subprocess; there is no fan-out or replay. The
|
||||
runtime buffers pushes until the session has sent `plugin.rpc.subscribe.response`, so a client
|
||||
never sees an event for an unknown subscription. The app installation's lifetime aborts every
|
||||
subscription its surfaces left open, and a reload replaces the installation, which resubscribes
|
||||
mounted hooks.
|
||||
|
||||
The byte rule (a top-level `Uint8Array` is binary, a nested one is a validation error) is checked
|
||||
once per hop by `assertPluginWireValue`. Bytes ride plugin binary frames, opcodes `0x20`-`0x2f`
|
||||
(`packages/protocol/src/binary-frames/plugin.ts`); nothing on the path copies or re-encodes them,
|
||||
and `plugin-subscriptions.perf.e2e.test.ts` locks that. Keep it that way: never stringify a plugin
|
||||
payload for a log, and the client's bootstrap buffer holds bytes only until the first observer
|
||||
attaches. Binary outputs reach only clients that send `pluginBinaryPayloads`. A binary input
|
||||
frame (`0x22`) becomes a synthetic `plugin.rpc.invoke.request` and runs through the normal message
|
||||
path, so it is authorized like any other invoke. The author contract, including the native upload
|
||||
limit, is in [stream events from the daemon](../public-docs/plugins/reference.md#subscriptions).
|
||||
|
||||
`usePaseo()` and the handler's `{ paseo }` context expose the same `PaseoApi`: projects,
|
||||
workspaces, agents, terminals, providers, and daemon config. They do not expose connection lifecycle.
|
||||
|
||||
+3
-62
@@ -30,65 +30,6 @@ at session startup. See [provider configuration](custom-providers.md#provider-op
|
||||
for defaults and merge rules, and the [SDK guide](../public-docs/sdk/provider-options.md)
|
||||
for native keys and examples.
|
||||
|
||||
### Options flow
|
||||
|
||||
`options` on the agent snapshot is the only option state. Controls describe how to draw an
|
||||
option and read `options`; they hold no value of their own. Any option can be read and set with
|
||||
or without a control.
|
||||
|
||||
- **Create and resume.** The provider opens with the options it is given and emits nothing about
|
||||
them while opening. `openOptionsPatch` carries every option the session ended up with that
|
||||
differs from what it was given, including a setting nobody asked for (a native default such as
|
||||
Cursor opening with Fast on). It is set before `createSession`/`resumeSession` resolves and the
|
||||
daemon stores it before the agent is published. A reopened agent resumes that state, so a
|
||||
native default the provider later changes does not follow. `options` on the snapshot is what
|
||||
the session opened with, and afterwards it moves only through an apply or an `options_changed`.
|
||||
Editing a provider default in `config.json` affects agents the next time they open.
|
||||
- **Live apply.** `applyOptions` receives the keys the patch touches, resolved against the
|
||||
`config.json` defaults. A removal arrives as the default the key falls back to, or `null` when
|
||||
there is none; the provider returns the setting to its own default if it can, or throws to
|
||||
reject. A key the running session cannot apply (one the provider reads only when it opens) is
|
||||
rejected too, so a stored option always describes what runs. Claude reads most options when it
|
||||
starts its query, and replacing a started query would end its background work, so after the
|
||||
first prompt only Fast can change. Codex fixes its approval policy and sandbox when the thread
|
||||
starts, so it applies only `service_tier` and `plan_mode` live. A session with no
|
||||
`applyOptions` rejects every patch; the daemon enforces this. The provider returns the options
|
||||
it ended up with when they differ from the request. The daemon
|
||||
stores the patch and that result in one step after the call resolves, onto the agent's options
|
||||
as they are at that moment, so the last write wins. Throwing rejects the whole patch and
|
||||
none of it is stored. Emit nothing from inside the call. If the provider's own state moved
|
||||
before it refused, it reports the moved values once as `options_changed` after the call has
|
||||
ended, because the stored options must match what runs.
|
||||
- **Old data converts in the agent manager.** Codex used to take `fast_mode`; it takes
|
||||
`service_tier` now. `AgentManager` runs `convertLegacyOptions` (`option-controls.ts`) on an
|
||||
agent's own options when it creates, resumes, imports, reloads or applies to it, and on draft
|
||||
controls, before defaults merge and before anything is stored (`true` is `"fast"`, `false` is
|
||||
`"default"`, and a `service_tier` in the same input wins). The manager converts for the adapter
|
||||
behind the provider id, following `derivedFromProviderId`, so a custom provider with
|
||||
`extends: "codex"` is converted too. Configured defaults convert in the provider registry. A
|
||||
stored record keeps `fast_mode` until the agent is next opened or applied to, and is stored
|
||||
converted from then on. Nothing past the manager sees `fast_mode` for Codex. Codex resolves
|
||||
`"fast"` to the model's Fast tier and reports the id it runs through `openOptionsPatch` or the
|
||||
`applyOptions` result like any other value. The `featureValues` to `options` fold is separate
|
||||
and provider-agnostic; it stays at the protocol and legacy edges.
|
||||
- **Clients draw from the daemon's answer.** The app reads `controls` and `options` from the
|
||||
agent snapshot for a running or closed agent. A draft and a profile form send everything they
|
||||
would create with (seed, the provider's last-used control values once the provider has said it
|
||||
still draws them, and the user's edits) in `provider.controls.list.request` and draw only what
|
||||
comes back, so an alias such as a legacy Fast profile's `service_tier: "fast"` is resolved once,
|
||||
by the daemon. A toggle shows over the last answer until its own answer arrives. The draft's
|
||||
layers live in a plain model (`agent-controls/draft-options-model.ts`): applying a profile
|
||||
replaces provider and options in one step, while choosing a provider by hand starts over. A
|
||||
profile saves its stored options plus the form's edits, so options no control draws survive an
|
||||
edit. A daemon without `server_info.features.providerOptionControls` sends `features` and
|
||||
`featureValues`; `packages/client/src/compat/legacy-provider-options.ts` is the one place that
|
||||
turns those into `controls` and `options` and back, so nothing in the app branches on it. A
|
||||
create that carries options first lists the controls for its own provider, model, mode and
|
||||
thinking level, since which options are controls differs by model, and sends those as
|
||||
`featureValues`; callers do not prime anything.
|
||||
- **Provider-initiated changes.** A setting the provider changes on its own is an
|
||||
`options_changed` event. The daemon stores and forwards it and does not push the old value back.
|
||||
|
||||
Exact MCP preapproval is a separate daemon-owned contract. A new provider must fail
|
||||
closed for Hub unattended execution until it can approve one exact injected MCP
|
||||
server and tool identity without approving native tools.
|
||||
@@ -174,7 +115,7 @@ Submitted user-message wire items carry the same Paseo ID in `messageId` and `cl
|
||||
|
||||
Provider adapters must terminalize every transient timeline row before emitting the turn's terminal event. Codex may omit the completed `contextCompaction` item when a turn ends during compaction, so its adapter closes any pending root compaction before forwarding `turn_completed`, `turn_failed`, or `turn_canceled`. A terminal turn must never leave the client showing an operation as still loading.
|
||||
|
||||
Draft metadata lookups should avoid creating provider sessions when the upstream provider has top-level APIs for that metadata. Prefer `AgentClient.fetchCatalog`, `listCommands`, or `listControls` over creating a scratch `AgentSession`; scratch sessions can show up as empty native sessions in provider import/history UIs. `fetchCatalog` is the single discovery API for models and modes — provider implementations may use one process, separate upstream calls, or static data internally, but callers outside the provider do not get separate runtime model/mode probes. Draft command listing and scratch-session control listing require an explicit draft model. Do not resolve a default model through catalog discovery. A client-level `listControls` implementation may return controls from an incomplete, model-less draft and owns which features are valid in that state.
|
||||
Draft metadata lookups should avoid creating provider sessions when the upstream provider has top-level APIs for that metadata. Prefer `AgentClient.fetchCatalog`, `listCommands`, or `listFeatures` over creating a scratch `AgentSession`; scratch sessions can show up as empty native sessions in provider import/history UIs. `fetchCatalog` is the single discovery API for models and modes — provider implementations may use one process, separate upstream calls, or static data internally, but callers outside the provider do not get separate runtime model/mode probes. Draft command listing and scratch-session feature listing require an explicit draft model. Do not resolve a default model through catalog discovery. A client-level `listFeatures` implementation may return features from an incomplete, model-less draft and owns which features are valid in that state.
|
||||
|
||||
Provider session import has its own contract. The picker calls `listImportableSessions` and receives rows only: provider handle, cwd, title, prompt previews, and last activity. Import calls `importSession({ providerHandleId, cwd })` for the selected row and must not call listing again. The provider returns the resumed session, storage config, persistence handle, and hydrated timeline for that one native session; `AgentManager.importProviderSession` seeds the daemon timeline and publishes the Paseo agent only after it is ready.
|
||||
|
||||
@@ -537,7 +478,7 @@ interface AgentSession {
|
||||
readonly provider: AgentProvider;
|
||||
readonly id: string | null;
|
||||
readonly capabilities: AgentCapabilityFlags;
|
||||
readonly controls?: AgentOptionControl[];
|
||||
readonly features?: AgentFeature[];
|
||||
run(prompt: AgentPromptInput, options?: AgentRunOptions): Promise<AgentRunResult>;
|
||||
startTurn(prompt: AgentPromptInput, options?: AgentRunOptions): Promise<{ turnId: string }>;
|
||||
steerActiveTurn?(prompt: AgentPromptInput, options: SteerActiveTurnOptions): Promise<SteerResult>;
|
||||
@@ -559,7 +500,7 @@ interface AgentSession {
|
||||
listCommands?(): Promise<AgentSlashCommand[]>;
|
||||
setModel?(modelId: string | null): Promise<void>;
|
||||
setThinkingOption?(thinkingOptionId: string | null): Promise<void | AgentProviderNotice>;
|
||||
applyOptions?(options: ProviderOptions): Promise<void>;
|
||||
setFeature?(featureId: string, value: unknown): Promise<void>;
|
||||
tryHandleOutOfBand?(prompt: AgentPromptInput): {
|
||||
run(ctx: { emit: (event: AgentStreamEvent) => void }): Promise<void>;
|
||||
} | null;
|
||||
|
||||
@@ -127,7 +127,7 @@ buildNpmPackage {
|
||||
# The Nix output is not a distributable DMG, so leave it unsigned and
|
||||
# disable the hardened runtime that requires a matching signature.
|
||||
CSC_IDENTITY_AUTO_DISCOVERY=false \
|
||||
../../node_modules/.bin/electron-builder \
|
||||
npm exec --offline -- electron-builder \
|
||||
--config electron-builder.yml \
|
||||
--dir \
|
||||
--mac \
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-CeT2PtYIAFwvBC9LIku8VkTl0pvKxYzSCn0QW2ManfU=
|
||||
sha256-KN/AVZV/o0TleLLpmggSrdJqjFDJ/NJYVHiC54xb4jQ=
|
||||
|
||||
Generated
+1018
-1295
File diff suppressed because it is too large
Load Diff
@@ -62,7 +62,7 @@ async function readProviderFeaturePreferences(page: Page, provider: string): Pro
|
||||
const raw = localStorage.getItem(preferencesKey);
|
||||
if (!raw) return null;
|
||||
const preferences = JSON.parse(raw) as FormPreferences;
|
||||
return preferences.providerPreferences?.[providerId]?.options ?? null;
|
||||
return preferences.providerPreferences?.[providerId]?.featureValues ?? null;
|
||||
},
|
||||
{ preferencesKey: CREATE_AGENT_PREFERENCES_KEY, providerId: provider },
|
||||
);
|
||||
@@ -145,7 +145,7 @@ test.describe("Agent profiles repair modeless provider preferences", () => {
|
||||
provider: featureProviderId,
|
||||
model: featureModelId,
|
||||
modeId: "bypassPermissions",
|
||||
options: { fast_mode: true },
|
||||
featureValues: { fast_mode: true },
|
||||
},
|
||||
]);
|
||||
const provider = await seedModelProvider({
|
||||
@@ -181,7 +181,7 @@ test.describe("Agent profiles repair modeless provider preferences", () => {
|
||||
expect(createAgentRequest).toMatchObject({
|
||||
config: {
|
||||
provider: featureProviderId,
|
||||
providerOptions: { fast_mode: true },
|
||||
featureValues: { fast_mode: true },
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
composerLocator,
|
||||
expectComposerDraft,
|
||||
expectComposerVisible,
|
||||
submitMessage,
|
||||
fillComposerDraft,
|
||||
typeIntoFocusedComposer,
|
||||
} from "../support/helpers/composer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
@@ -12,8 +12,14 @@ function userMessages(page: Page) {
|
||||
return page.getByTestId("user-message");
|
||||
}
|
||||
|
||||
async function sendDraftWhenReady(page: Page) {
|
||||
await expect(page.getByRole("button", { name: "Send message", exact: true })).toBeEnabled();
|
||||
await pressInComposer(page, "Enter");
|
||||
}
|
||||
|
||||
async function sendAndWaitForMessage(page: Page, text: string, expectedCount: number) {
|
||||
await submitMessage(page, text);
|
||||
await fillComposerDraft(page, text);
|
||||
await sendDraftWhenReady(page);
|
||||
await expect(userMessages(page)).toHaveCount(expectedCount, { timeout: 30_000 });
|
||||
await expectComposerDraft(page, "");
|
||||
}
|
||||
@@ -49,7 +55,7 @@ test.describe("Composer recall", () => {
|
||||
await pressInComposer(page, "ArrowUp");
|
||||
await expectComposerDraft(page, "add tests for login");
|
||||
|
||||
await pressInComposer(page, "Enter");
|
||||
await sendDraftWhenReady(page);
|
||||
await expect(userMessages(page)).toHaveCount(3, { timeout: 30_000 });
|
||||
await expect(userMessages(page).last()).toContainText("add tests for login");
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { openCommandCenter } from "../support/helpers/command-center";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import {
|
||||
switchWorkspaceViaSidebar,
|
||||
waitForWorkspaceInSidebar,
|
||||
} from "../support/helpers/workspace-ui";
|
||||
|
||||
async function runCommand(page: Page, title: string): Promise<void> {
|
||||
const panel = await openCommandCenter(page);
|
||||
await panel.getByTestId("command-center-input").fill(title);
|
||||
await panel.getByRole("button", { name: title, exact: true }).click();
|
||||
await expect(panel).not.toBeVisible();
|
||||
}
|
||||
|
||||
/** Installs a plugin example, opens a seeded workspace, and runs `exercise` against them. */
|
||||
async function withExample(
|
||||
page: Page,
|
||||
example: { name: string; id: string },
|
||||
exercise: (workspace: SeededWorkspace) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const previous = await client.getDaemonConfig();
|
||||
const copy = await copyPluginExample(example.name);
|
||||
const workspace = await seedWorkspace({ repoPrefix: `${example.name}-` });
|
||||
try {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(copy.directory);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
await gotoAppShell(page);
|
||||
const target = { serverId: getServerId(), workspaceId: workspace.workspaceId };
|
||||
await waitForWorkspaceInSidebar(page, target);
|
||||
await switchWorkspaceViaSidebar({ page, ...target });
|
||||
await exercise(workspace);
|
||||
} finally {
|
||||
try {
|
||||
await client.removePlugin(example.id);
|
||||
} finally {
|
||||
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled });
|
||||
await workspace.cleanup();
|
||||
await client.close();
|
||||
await copy.cleanup();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test.describe("plugin subscriptions", () => {
|
||||
test.describe.configure({ timeout: 180_000 });
|
||||
|
||||
test("a panel follows events the daemon pushes as files change", async ({ page }) => {
|
||||
await withExample(page, { name: "diff-watch", id: "diff-watch" }, async (workspace) => {
|
||||
await runCommand(page, "Open live changes");
|
||||
await expect(page.getByText("No changes", { exact: true })).toBeVisible();
|
||||
|
||||
await writeFile(path.join(workspace.repoPath, "pushed.txt"), "from the test\n");
|
||||
await expect(page.getByText("1 file changed", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("pushed.txt", { exact: true })).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test("a panel plays streamed bytes and sends bytes back", async ({ page }) => {
|
||||
await withExample(page, { name: "media-stream", id: "media-stream" }, async () => {
|
||||
await runCommand(page, "Open media stream");
|
||||
await expect(page.getByText("live", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText(/^[1-9]\d* video frames/)).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "Send this frame back", exact: true }).click();
|
||||
await expect(
|
||||
page.getByText(/^The daemon received [1-9]\d* bytes, sha256 [0-9a-f]{12}$/),
|
||||
).toBeVisible();
|
||||
});
|
||||
});
|
||||
});
|
||||
+2
-2
@@ -18,7 +18,7 @@ export interface AgentCommandsDraftConfig {
|
||||
modeId?: string;
|
||||
model?: string;
|
||||
thinkingOptionId?: string;
|
||||
providerOptions?: Record<string, unknown>;
|
||||
featureValues?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function normalizeAgentCommandsCwd(cwd: string): string {
|
||||
@@ -98,7 +98,7 @@ export function draftAgentCommandsQueryKey(input: {
|
||||
"thinking",
|
||||
draftConfig.thinkingOptionId ?? null,
|
||||
"features",
|
||||
draftConfig.providerOptions ?? null,
|
||||
draftConfig.featureValues ?? null,
|
||||
] as const;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AgentOptionControl } from "@getpaseo/protocol/agent-types";
|
||||
import { isControlActive } from "./option-controls";
|
||||
import {
|
||||
draftControlsRequest,
|
||||
openDraftOptions,
|
||||
ownDraftOptions,
|
||||
viewDraftOptions,
|
||||
} from "./draft-options-model";
|
||||
|
||||
const SPEED: AgentOptionControl = {
|
||||
type: "select",
|
||||
key: "service_tier",
|
||||
label: "Speed",
|
||||
defaultValue: "default",
|
||||
choices: [
|
||||
{ value: "default", label: "Standard" },
|
||||
{ value: "priority", label: "Fast" },
|
||||
],
|
||||
};
|
||||
const WEB_SEARCH: AgentOptionControl = { type: "toggle", key: "web_search", label: "Web search" };
|
||||
|
||||
function answer(
|
||||
provider: string,
|
||||
requestKey: string,
|
||||
options: Record<string, unknown>,
|
||||
controls = [SPEED, WEB_SEARCH],
|
||||
) {
|
||||
return { provider, requestKey, controls, options };
|
||||
}
|
||||
|
||||
describe("draft options model", () => {
|
||||
it("draws a legacy Fast profile as the Fast tier the daemon resolved", () => {
|
||||
const model = openDraftOptions({ provider: "codex", seed: { service_tier: "fast" } });
|
||||
model.applyResolved(answer("codex", "k1", { service_tier: "priority" }));
|
||||
|
||||
const view = viewDraftOptions(model.getState(), { provider: "codex", requestKey: "k1" });
|
||||
|
||||
expect(view?.options).toEqual({ service_tier: "priority" });
|
||||
expect(view && isControlActive(SPEED, view.options)).toBe(true);
|
||||
// The daemon still gets the stored value to resolve, and so does create.
|
||||
expect(ownDraftOptions(model.getState())).toEqual({ service_tier: "fast" });
|
||||
});
|
||||
|
||||
it("applying a profile from another provider keeps its options through the provider change", () => {
|
||||
const model = openDraftOptions({ provider: "claude" });
|
||||
model.applyResolved(answer("claude", "k1", {}));
|
||||
|
||||
model.applyProfile({
|
||||
provider: "codex",
|
||||
options: { sandbox_mode: "read-only", service_tier: "fast" },
|
||||
});
|
||||
// The form follows the profile to its provider.
|
||||
model.observeProvider("codex");
|
||||
|
||||
expect(ownDraftOptions(model.getState())).toEqual({
|
||||
sandbox_mode: "read-only",
|
||||
service_tier: "fast",
|
||||
});
|
||||
expect(model.getState().resolved).toBeNull();
|
||||
});
|
||||
|
||||
it("choosing another provider by hand starts the options over", () => {
|
||||
const model = openDraftOptions({ provider: "codex", seed: { sandbox_mode: "read-only" } });
|
||||
model.setOption("web_search", true);
|
||||
|
||||
model.observeProvider("claude");
|
||||
|
||||
expect(ownDraftOptions(model.getState())).toBeUndefined();
|
||||
expect(model.getState().resolved).toBeNull();
|
||||
});
|
||||
|
||||
it("never pairs a manually chosen provider with the previous provider's options", () => {
|
||||
const model = openDraftOptions({ provider: "claude" });
|
||||
model.applyResolved(answer("claude", "k1", { fast_mode: true }));
|
||||
model.setOption("fast_mode", true);
|
||||
const form = { provider: "claude", cwd: "/repo" };
|
||||
expect(draftControlsRequest(model.getState(), form)).toMatchObject({
|
||||
provider: "claude",
|
||||
providerOptions: { fast_mode: true },
|
||||
});
|
||||
|
||||
// The form shows OpenCode on its next render; the model has not observed it yet.
|
||||
expect(draftControlsRequest(model.getState(), { ...form, provider: "opencode" })).toBeNull();
|
||||
|
||||
model.observeProvider("opencode");
|
||||
const request = draftControlsRequest(model.getState(), { ...form, provider: "opencode" });
|
||||
expect(request).toEqual({ provider: "opencode", cwd: "/repo" });
|
||||
});
|
||||
|
||||
it("keeps a draft's seed when the first provider is chosen", () => {
|
||||
const model = openDraftOptions({ provider: null, seed: { web_search: true } });
|
||||
|
||||
model.observeProvider("claude");
|
||||
|
||||
expect(ownDraftOptions(model.getState())).toEqual({ web_search: true });
|
||||
});
|
||||
|
||||
it("sends a remembered value to the daemon, and draws only what comes back", () => {
|
||||
const model = openDraftOptions({ provider: "codex" });
|
||||
model.setRemembered({ service_tier: "fast", retired: true });
|
||||
// Nothing is known about the provider's controls yet.
|
||||
expect(ownDraftOptions(model.getState())).toBeUndefined();
|
||||
|
||||
model.applyResolved(answer("codex", "k1", { service_tier: "default" }));
|
||||
expect(ownDraftOptions(model.getState())).toEqual({ service_tier: "fast" });
|
||||
// The answer to the first request does not show the remembered value as if it applied.
|
||||
expect(
|
||||
viewDraftOptions(model.getState(), { provider: "codex", requestKey: "k2" })?.options,
|
||||
).toEqual({ service_tier: "default" });
|
||||
|
||||
model.applyResolved(answer("codex", "k2", { service_tier: "priority" }));
|
||||
expect(
|
||||
viewDraftOptions(model.getState(), { provider: "codex", requestKey: "k2" })?.options,
|
||||
).toEqual({ service_tier: "priority" });
|
||||
});
|
||||
|
||||
it("does not let a remembered value override the seed", () => {
|
||||
const model = openDraftOptions({ provider: "codex", seed: { service_tier: "default" } });
|
||||
model.applyResolved(answer("codex", "k1", { service_tier: "default" }));
|
||||
model.setRemembered({ service_tier: "fast" });
|
||||
|
||||
expect(ownDraftOptions(model.getState())).toEqual({ service_tier: "default" });
|
||||
});
|
||||
|
||||
it("lays a toggle over the previous answer until the new one arrives", () => {
|
||||
const model = openDraftOptions({ provider: "claude" });
|
||||
model.applyResolved(answer("claude", "k1", { web_search: false }));
|
||||
|
||||
model.setOption("web_search", true);
|
||||
|
||||
expect(
|
||||
viewDraftOptions(model.getState(), { provider: "claude", requestKey: "k2" })?.options,
|
||||
).toEqual({ web_search: true });
|
||||
model.applyResolved(answer("claude", "k2", { web_search: true }));
|
||||
expect(
|
||||
viewDraftOptions(model.getState(), { provider: "claude", requestKey: "k2" })?.options,
|
||||
).toEqual({ web_search: true });
|
||||
});
|
||||
|
||||
it("draws nothing for a provider the answer is not for", () => {
|
||||
const model = openDraftOptions({ provider: "claude" });
|
||||
model.applyResolved(answer("claude", "k1", {}));
|
||||
|
||||
expect(viewDraftOptions(model.getState(), { provider: "codex", requestKey: "k1" })).toBe(
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,168 +0,0 @@
|
||||
import type {
|
||||
AgentOptionControl,
|
||||
AgentSessionConfig,
|
||||
ProviderOptions,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
|
||||
/**
|
||||
* The options of one draft agent, as a plain model (see docs/forms.md). It owns which layers
|
||||
* make up the draft's options; the daemon owns what they mean. Every layer is sent to the daemon
|
||||
* (`ownDraftOptions`) and the UI draws what comes back (`viewDraftOptions`), so no alias,
|
||||
* default or legacy key is resolved here.
|
||||
*
|
||||
* - `seed`: options the draft started from (a profile, a forked agent).
|
||||
* - `remembered`: the provider's last-used control values.
|
||||
* - `edits`: toggles made in this draft.
|
||||
*
|
||||
* Choosing a provider by hand starts the options over; applying a profile replaces the provider
|
||||
* and the options in one step, so the provider change that follows does not clear them.
|
||||
*/
|
||||
export interface ResolvedDraftOptions {
|
||||
provider: string;
|
||||
/** Names the request that produced this answer; see `viewDraftOptions`. */
|
||||
requestKey: string;
|
||||
controls: AgentOptionControl[];
|
||||
options: ProviderOptions;
|
||||
}
|
||||
|
||||
export interface DraftOptionsState {
|
||||
provider: string | null;
|
||||
seed: ProviderOptions;
|
||||
remembered: ProviderOptions;
|
||||
edits: ProviderOptions;
|
||||
resolved: ResolvedDraftOptions | null;
|
||||
}
|
||||
|
||||
export interface DraftOptionsModel {
|
||||
getState: () => DraftOptionsState;
|
||||
subscribe: (listener: () => void) => () => void;
|
||||
/** The provider the draft's form now has. A different one than the model's is a manual choice. */
|
||||
observeProvider: (provider: string | null) => void;
|
||||
applyProfile: (profile: { provider: string; options: ProviderOptions }) => void;
|
||||
setRemembered: (remembered: ProviderOptions) => void;
|
||||
setOption: (key: string, value: unknown) => void;
|
||||
applyResolved: (resolved: ResolvedDraftOptions) => void;
|
||||
}
|
||||
|
||||
export function openDraftOptions(input: {
|
||||
provider: string | null;
|
||||
seed?: ProviderOptions;
|
||||
}): DraftOptionsModel {
|
||||
let state: DraftOptionsState = {
|
||||
provider: input.provider,
|
||||
seed: input.seed ?? {},
|
||||
remembered: {},
|
||||
edits: {},
|
||||
resolved: null,
|
||||
};
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function publish(update: (current: DraftOptionsState) => DraftOptionsState): void {
|
||||
const next = update(state);
|
||||
if (next === state) return;
|
||||
state = next;
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
return {
|
||||
getState: () => state,
|
||||
subscribe: (listener) => {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
observeProvider: (provider) =>
|
||||
publish((current) => {
|
||||
if (provider === current.provider) return current;
|
||||
// The first provider a draft picks does not discard what it was opened with.
|
||||
if (current.provider === null) return { ...current, provider };
|
||||
return { ...current, provider, seed: {}, edits: {}, resolved: null };
|
||||
}),
|
||||
applyProfile: (profile) =>
|
||||
publish((current) => ({
|
||||
...current,
|
||||
provider: profile.provider,
|
||||
seed: profile.options,
|
||||
edits: {},
|
||||
resolved: current.provider === profile.provider ? current.resolved : null,
|
||||
})),
|
||||
setRemembered: (remembered) => publish((current) => ({ ...current, remembered })),
|
||||
setOption: (key, value) =>
|
||||
publish((current) =>
|
||||
Object.is(current.edits[key], value)
|
||||
? current
|
||||
: { ...current, edits: { ...current.edits, [key]: value } },
|
||||
),
|
||||
applyResolved: (resolved) => publish((current) => ({ ...current, resolved })),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything the draft would create with, for the daemon to resolve. A last-used value applies
|
||||
* once the provider has told us it still draws a control for that key, and never over the seed.
|
||||
*/
|
||||
export function ownDraftOptions(state: DraftOptionsState): ProviderOptions | undefined {
|
||||
const controlKeys = new Set((state.resolved?.controls ?? []).map((control) => control.key));
|
||||
const remembered = Object.fromEntries(
|
||||
Object.entries(state.remembered).filter(
|
||||
([key]) => controlKeys.has(key) && !(key in state.seed),
|
||||
),
|
||||
);
|
||||
const own = { ...state.seed, ...remembered, ...state.edits };
|
||||
return Object.keys(own).length > 0 ? own : undefined;
|
||||
}
|
||||
|
||||
export type DraftControlsRequest = Pick<
|
||||
AgentSessionConfig,
|
||||
"provider" | "cwd" | "modeId" | "model" | "thinkingOptionId" | "providerOptions"
|
||||
>;
|
||||
|
||||
/**
|
||||
* The listing request for the draft's form, built from one snapshot of the model. The form
|
||||
* reaches a new provider before the model has observed it, and the model still holds the
|
||||
* previous provider's options until it does; that render has no request, so a request never
|
||||
* pairs one provider with another's options.
|
||||
*/
|
||||
export function draftControlsRequest(
|
||||
state: DraftOptionsState,
|
||||
form: {
|
||||
provider: string | null;
|
||||
cwd: string;
|
||||
modeId?: string | null;
|
||||
modelId?: string | null;
|
||||
thinkingOptionId?: string | null;
|
||||
},
|
||||
): DraftControlsRequest | null {
|
||||
if (!form.provider || !form.cwd || form.provider !== state.provider) return null;
|
||||
const providerOptions = ownDraftOptions(state);
|
||||
return {
|
||||
provider: form.provider,
|
||||
cwd: form.cwd,
|
||||
...(form.modeId ? { modeId: form.modeId } : {}),
|
||||
...(form.modelId ? { model: form.modelId } : {}),
|
||||
...(form.thinkingOptionId ? { thinkingOptionId: form.thinkingOptionId } : {}),
|
||||
...(providerOptions ? { providerOptions } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What the controls draw: the daemon's answer for this provider. The last answer stays up while
|
||||
* a newer request is in flight, with the toggles made since laid over it, so a switch does not
|
||||
* wait for the round trip. It never carries a seed or remembered value the daemon has not
|
||||
* resolved.
|
||||
*/
|
||||
export function viewDraftOptions(
|
||||
state: DraftOptionsState,
|
||||
current: { provider: string | null; requestKey: string },
|
||||
): { controls: AgentOptionControl[]; options: ProviderOptions } | undefined {
|
||||
const { resolved } = state;
|
||||
if (!resolved || resolved.provider !== current.provider) return undefined;
|
||||
return {
|
||||
controls: resolved.controls,
|
||||
options:
|
||||
resolved.requestKey === current.requestKey
|
||||
? resolved.options
|
||||
: { ...resolved.options, ...state.edits },
|
||||
};
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AgentOptionControl } from "@getpaseo/protocol/agent-types";
|
||||
import {
|
||||
getControlTooltip,
|
||||
isControlActive,
|
||||
readSelectOption,
|
||||
readToggleOption,
|
||||
} from "./option-controls";
|
||||
|
||||
const speed: AgentOptionControl = {
|
||||
type: "select",
|
||||
key: "service_tier",
|
||||
label: "Speed",
|
||||
defaultValue: "default",
|
||||
choices: [
|
||||
{ value: "default", label: "Normal" },
|
||||
{ value: "priority", label: "Fast" },
|
||||
],
|
||||
};
|
||||
const fast: AgentOptionControl = { type: "toggle", key: "fast_mode", label: "Fast" };
|
||||
|
||||
describe("option controls", () => {
|
||||
it("reads a select from options and falls back to the control's default", () => {
|
||||
if (speed.type !== "select") throw new Error("select expected");
|
||||
expect(readSelectOption(speed, { service_tier: "priority" })).toBe("priority");
|
||||
expect(readSelectOption(speed, {})).toBe("default");
|
||||
expect(readSelectOption(speed, { service_tier: "unknown-tier" })).toBe("default");
|
||||
});
|
||||
|
||||
it("reads a toggle from options and is off when unset", () => {
|
||||
if (fast.type !== "toggle") throw new Error("toggle expected");
|
||||
expect(readToggleOption(fast, { fast_mode: true })).toBe(true);
|
||||
expect(readToggleOption(fast, {})).toBe(false);
|
||||
});
|
||||
|
||||
it("is active when the option differs from the control's default", () => {
|
||||
expect(isControlActive(speed, { service_tier: "priority" })).toBe(true);
|
||||
expect(isControlActive(speed, { service_tier: "default" })).toBe(false);
|
||||
expect(isControlActive(speed, {})).toBe(false);
|
||||
expect(isControlActive(fast, { fast_mode: true })).toBe(true);
|
||||
expect(isControlActive(fast, {})).toBe(false);
|
||||
});
|
||||
|
||||
it("prefers a control's tooltip over its label", () => {
|
||||
expect(getControlTooltip({ label: "Plan", tooltip: "Toggle plan mode" })).toBe(
|
||||
"Toggle plan mode",
|
||||
);
|
||||
expect(getControlTooltip({ label: "Custom" })).toBe("Custom");
|
||||
});
|
||||
});
|
||||
@@ -1,47 +0,0 @@
|
||||
import type {
|
||||
AgentOptionControl,
|
||||
AgentOptionSelectControl,
|
||||
AgentOptionToggleControl,
|
||||
ProviderOptions,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
|
||||
/**
|
||||
* The composer's option controls. A control only describes how to draw one option key; the
|
||||
* value is read from `options`, which the daemon resolved (defaults, aliases, what runs).
|
||||
*/
|
||||
export interface ComposerOptionControls {
|
||||
controls: AgentOptionControl[];
|
||||
options: ProviderOptions;
|
||||
onSetOption: (key: string, value: unknown) => void;
|
||||
}
|
||||
|
||||
export function readToggleOption(
|
||||
control: AgentOptionToggleControl,
|
||||
options: ProviderOptions,
|
||||
): boolean {
|
||||
const value = options[control.key];
|
||||
return typeof value === "boolean" ? value : (control.defaultValue ?? false);
|
||||
}
|
||||
|
||||
/** The selected choice's value, or the control's default when the option names no choice. */
|
||||
export function readSelectOption(
|
||||
control: AgentOptionSelectControl,
|
||||
options: ProviderOptions,
|
||||
): string | null {
|
||||
const value = options[control.key];
|
||||
if (typeof value === "string" && control.choices.some((choice) => choice.value === value)) {
|
||||
return value;
|
||||
}
|
||||
return control.defaultValue ?? null;
|
||||
}
|
||||
|
||||
/** Whether the option is set to something other than the control's default. */
|
||||
export function isControlActive(control: AgentOptionControl, options: ProviderOptions): boolean {
|
||||
if (control.type === "toggle") return readToggleOption(control, options);
|
||||
const value = readSelectOption(control, options);
|
||||
return value !== null && value !== control.defaultValue;
|
||||
}
|
||||
|
||||
export function getControlTooltip(control: Pick<AgentOptionControl, "label" | "tooltip">): string {
|
||||
return control.tooltip ?? control.label;
|
||||
}
|
||||
@@ -23,7 +23,7 @@ describe("materializeAgentProfile", () => {
|
||||
model: "claude-opus-5",
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "think-hard",
|
||||
options: { web_search: true },
|
||||
featureValues: { web_search: true },
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
@@ -31,7 +31,7 @@ describe("materializeAgentProfile", () => {
|
||||
modelId: "claude-opus-5",
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "think-hard",
|
||||
options: { web_search: true },
|
||||
featureValues: { web_search: true },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -41,7 +41,7 @@ describe("materializeAgentProfile", () => {
|
||||
modelId: "",
|
||||
modeId: "",
|
||||
thinkingOptionId: "",
|
||||
options: {},
|
||||
featureValues: {},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -61,7 +61,7 @@ describe("toAgentConfigApply", () => {
|
||||
model: "claude-opus-5",
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "think-hard",
|
||||
options: { web_search: true },
|
||||
featureValues: { web_search: true },
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -69,7 +69,7 @@ describe("toAgentConfigApply", () => {
|
||||
modelId: "claude-opus-5",
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "think-hard",
|
||||
options: { web_search: true },
|
||||
featureValues: { web_search: true },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -81,8 +81,8 @@ describe("toAgentConfigApply", () => {
|
||||
|
||||
it("omits an empty feature map so the agent keeps its own feature values", () => {
|
||||
expect(
|
||||
toAgentConfigApply(materializeAgentProfile(profile({ options: {} }))),
|
||||
).not.toHaveProperty("options");
|
||||
toAgentConfigApply(materializeAgentProfile(profile({ featureValues: {} }))),
|
||||
).not.toHaveProperty("featureValues");
|
||||
});
|
||||
|
||||
it("never carries a provider, which a running agent cannot change", () => {
|
||||
|
||||
@@ -12,7 +12,7 @@ export interface MaterializedAgentProfile {
|
||||
modelId: string;
|
||||
modeId: string;
|
||||
thinkingOptionId: string;
|
||||
options: Record<string, unknown>;
|
||||
featureValues: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function trimmed(value: string | undefined): string {
|
||||
@@ -25,7 +25,7 @@ export function materializeAgentProfile(profile: AgentProfile): MaterializedAgen
|
||||
modelId: trimmed(profile.model),
|
||||
modeId: trimmed(profile.modeId),
|
||||
thinkingOptionId: trimmed(profile.thinkingOptionId),
|
||||
options: profile.options ?? {},
|
||||
featureValues: profile.featureValues ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -52,6 +52,8 @@ export function toAgentConfigApply(profile: MaterializedAgentProfile): AgentConf
|
||||
...(profile.modelId ? { modelId: profile.modelId } : {}),
|
||||
...(profile.modeId ? { modeId: profile.modeId } : {}),
|
||||
...(profile.thinkingOptionId ? { thinkingOptionId: profile.thinkingOptionId } : {}),
|
||||
...(Object.keys(profile.options).length > 0 ? { options: profile.options } : {}),
|
||||
...(Object.keys(profile.featureValues).length > 0
|
||||
? { featureValues: profile.featureValues }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildControlsRequestKey,
|
||||
buildFeatureRequestKey,
|
||||
openAgentProfileForm,
|
||||
type AgentProfileFormModel,
|
||||
} from "./profile-form-model";
|
||||
@@ -173,7 +173,7 @@ describe("openAgentProfileForm", () => {
|
||||
model: "claude-opus-5",
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "think-hard",
|
||||
options: { webSearch: true },
|
||||
featureValues: { webSearch: true },
|
||||
notes: "Visual work only.",
|
||||
},
|
||||
});
|
||||
@@ -229,11 +229,10 @@ describe("openAgentProfileForm", () => {
|
||||
selectClaude(model);
|
||||
model.setModel("claude-opus-5", { label: "Opus 5" });
|
||||
model.setThinking("think-hard", { label: "Think hard" });
|
||||
model.applyControls(model.getState().controlsRequestKey ?? "", {
|
||||
controls: [{ type: "toggle", key: "webSearch", label: "Web search" }],
|
||||
options: { webSearch: false },
|
||||
});
|
||||
model.setOption("webSearch", true);
|
||||
model.applyFeatures(model.getState().featureRequestKey ?? "", [
|
||||
{ type: "toggle", id: "webSearch", label: "Web search", value: false },
|
||||
]);
|
||||
model.setFeatureValue("webSearch", true);
|
||||
|
||||
model.setProvider("codex", { label: "Codex" });
|
||||
const state = model.getState();
|
||||
@@ -243,9 +242,8 @@ describe("openAgentProfileForm", () => {
|
||||
expect(state.modelDisplay).toEqual({ label: "GPT-5.2 Codex" });
|
||||
expect(state.thinkingOptionId).toBe("");
|
||||
expect(state.thinkingDisplay).toBeNull();
|
||||
expect(state.options).toEqual({});
|
||||
expect(state.optionEdits).toEqual({});
|
||||
expect(state.controls).toEqual([]);
|
||||
expect(state.featureValues).toEqual({});
|
||||
expect(state.features).toEqual([]);
|
||||
expect(state.name).toBe("Test writer");
|
||||
});
|
||||
|
||||
@@ -336,28 +334,23 @@ describe("openAgentProfileForm", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const WEB_SEARCH_CONTROLS = {
|
||||
controls: [{ type: "toggle" as const, key: "webSearch", label: "Web search" }],
|
||||
options: { webSearch: false },
|
||||
};
|
||||
|
||||
describe("controls", () => {
|
||||
it("asks for controls per provider/model/mode/thinking combination", () => {
|
||||
describe("features", () => {
|
||||
it("asks for features per provider/model/mode/thinking combination", () => {
|
||||
const model = openWithCatalog({ mode: "create" });
|
||||
selectClaude(model);
|
||||
|
||||
expect(model.getState().controlsRequest).toEqual({
|
||||
expect(model.getState().featureRequest).toEqual({
|
||||
provider: "claude",
|
||||
model: "claude-opus-5",
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "think",
|
||||
});
|
||||
const firstKey = model.getState().controlsRequestKey;
|
||||
const firstKey = model.getState().featureRequestKey;
|
||||
|
||||
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
|
||||
|
||||
expect(model.getState().controlsRequestKey).not.toBe(firstKey);
|
||||
expect(model.getState().controlsRequest).toEqual({
|
||||
expect(model.getState().featureRequestKey).not.toBe(firstKey);
|
||||
expect(model.getState().featureRequest).toEqual({
|
||||
provider: "claude",
|
||||
model: "claude-haiku-4-5",
|
||||
modeId: "plan",
|
||||
@@ -368,168 +361,77 @@ describe("openAgentProfileForm", () => {
|
||||
it("moves from pending to complete only for the current request", () => {
|
||||
const model = openWithCatalog({ mode: "create" });
|
||||
selectClaude(model);
|
||||
const key = model.getState().controlsRequestKey ?? "";
|
||||
expect(model.getState().controlsResolution).toBe("pending");
|
||||
const key = model.getState().featureRequestKey ?? "";
|
||||
expect(model.getState().featureResolution).toBe("pending");
|
||||
|
||||
model.applyControls("stale-key", {
|
||||
controls: [{ type: "toggle", key: "webSearch", label: "Web search" }],
|
||||
options: { webSearch: false },
|
||||
});
|
||||
expect(model.getState().controlsResolution).toBe("pending");
|
||||
expect(model.getState().controls).toEqual([]);
|
||||
model.applyFeatures("stale-key", [
|
||||
{ type: "toggle", id: "webSearch", label: "Web search", value: false },
|
||||
]);
|
||||
expect(model.getState().featureResolution).toBe("pending");
|
||||
expect(model.getState().features).toEqual([]);
|
||||
|
||||
model.applyControls(key, {
|
||||
controls: [{ type: "toggle", key: "webSearch", label: "Web search" }],
|
||||
options: { webSearch: false },
|
||||
});
|
||||
expect(model.getState().controlsResolution).toBe("complete");
|
||||
expect(model.getState().disclosure.showControlsField).toBe(true);
|
||||
model.applyFeatures(key, [
|
||||
{ type: "toggle", id: "webSearch", label: "Web search", value: false },
|
||||
]);
|
||||
expect(model.getState().featureResolution).toBe("complete");
|
||||
expect(model.getState().disclosure.showFeaturesField).toBe(true);
|
||||
});
|
||||
|
||||
it("reflects a set option back into the rendered controls", () => {
|
||||
it("reflects a set feature value back into the rendered feature", () => {
|
||||
const model = openWithCatalog({ mode: "create" });
|
||||
model.setName("Searcher");
|
||||
selectClaude(model);
|
||||
model.applyControls(model.getState().controlsRequestKey ?? "", WEB_SEARCH_CONTROLS);
|
||||
model.applyFeatures(model.getState().featureRequestKey ?? "", [
|
||||
{ type: "toggle", id: "webSearch", label: "Web search", value: false },
|
||||
]);
|
||||
|
||||
model.setOption("webSearch", true);
|
||||
model.setFeatureValue("webSearch", true);
|
||||
|
||||
expect(model.getState().controls[0]).toMatchObject({ key: "webSearch" });
|
||||
expect(model.getState().controlOptions).toEqual({ webSearch: true });
|
||||
expect(model.getState().submitValue?.options).toEqual({ webSearch: true });
|
||||
expect(model.getState().features[0]).toMatchObject({ id: "webSearch", value: true });
|
||||
expect(model.getState().featureValues).toEqual({ webSearch: true });
|
||||
});
|
||||
|
||||
it("keeps stored options while the controls are still pending", () => {
|
||||
const model = openAgentProfileForm({
|
||||
mode: "edit",
|
||||
profile: { id: "p1", name: "UI work", provider: "claude", options: { webSearch: true } },
|
||||
});
|
||||
model.applyProviderCatalog(ENTRIES);
|
||||
|
||||
expect(model.getState().controlsResolution).toBe("pending");
|
||||
expect(model.getState().submitValue?.options).toEqual({ webSearch: true });
|
||||
});
|
||||
|
||||
it("keeps options no control draws, so editing a profile does not drop them", () => {
|
||||
it("keeps stored feature values while the feature list is still pending", () => {
|
||||
const model = openAgentProfileForm({
|
||||
mode: "edit",
|
||||
profile: {
|
||||
id: "p1",
|
||||
name: "UI work",
|
||||
provider: "claude",
|
||||
options: { webSearch: true, sandbox_mode: "read-only" },
|
||||
featureValues: { webSearch: true },
|
||||
},
|
||||
});
|
||||
model.applyProviderCatalog(ENTRIES);
|
||||
model.applyControls(model.getState().controlsRequestKey ?? "", WEB_SEARCH_CONTROLS);
|
||||
model.setOption("webSearch", false);
|
||||
|
||||
expect(model.getState().submitValue?.options).toEqual({
|
||||
webSearch: false,
|
||||
sandbox_mode: "read-only",
|
||||
});
|
||||
expect(model.getState().featureResolution).toBe("pending");
|
||||
expect(model.getState().submitValue?.featureValues).toEqual({ webSearch: true });
|
||||
});
|
||||
|
||||
it("draws the options the daemon resolved from the stored ones, then the edits", () => {
|
||||
const model = openAgentProfileForm({
|
||||
mode: "edit",
|
||||
profile: { id: "p1", name: "Fast", provider: "codex", options: { service_tier: "fast" } },
|
||||
});
|
||||
model.applyProviderCatalog(ENTRIES);
|
||||
|
||||
// The request carries the stored options so the daemon can resolve the legacy tier.
|
||||
expect(model.getState().controlsRequest?.providerOptions).toEqual({ service_tier: "fast" });
|
||||
|
||||
model.applyControls(model.getState().controlsRequestKey ?? "", {
|
||||
controls: [
|
||||
{
|
||||
type: "select",
|
||||
key: "service_tier",
|
||||
label: "Speed",
|
||||
defaultValue: "default",
|
||||
choices: [
|
||||
{ value: "default", label: "Standard" },
|
||||
{ value: "priority", label: "Fast" },
|
||||
],
|
||||
},
|
||||
],
|
||||
options: { service_tier: "priority" },
|
||||
});
|
||||
|
||||
expect(model.getState().controlOptions).toEqual({ service_tier: "priority" });
|
||||
// Nothing was edited, so the stored value is saved as it was.
|
||||
expect(model.getState().submitValue?.options).toEqual({ service_tier: "fast" });
|
||||
});
|
||||
|
||||
it("sends an edit to the daemon with the stored options, and draws the answer", () => {
|
||||
it("prunes stored values the provider no longer reports", () => {
|
||||
const model = openAgentProfileForm({
|
||||
mode: "edit",
|
||||
profile: {
|
||||
id: "p1",
|
||||
name: "Fast",
|
||||
provider: "codex",
|
||||
options: { service_tier: "fast", sandbox_mode: "read-only" },
|
||||
name: "UI work",
|
||||
provider: "claude",
|
||||
featureValues: { webSearch: true, retiredFlag: true },
|
||||
},
|
||||
});
|
||||
model.applyProviderCatalog(ENTRIES);
|
||||
const speed = {
|
||||
controls: [
|
||||
{
|
||||
type: "select" as const,
|
||||
key: "service_tier",
|
||||
label: "Speed",
|
||||
defaultValue: "default",
|
||||
choices: [
|
||||
{ value: "default", label: "Standard" },
|
||||
{ value: "priority", label: "Fast" },
|
||||
],
|
||||
},
|
||||
],
|
||||
options: { service_tier: "priority", sandbox_mode: "read-only" },
|
||||
};
|
||||
model.applyControls(model.getState().controlsRequestKey ?? "", speed);
|
||||
model.applyFeatures(model.getState().featureRequestKey ?? "", [
|
||||
{ type: "toggle", id: "webSearch", label: "Web search", value: false },
|
||||
]);
|
||||
|
||||
model.setOption("service_tier", "default");
|
||||
|
||||
// The controls stay up while the daemon answers, with the toggle laid over the last answer.
|
||||
expect(model.getState().controls).toHaveLength(1);
|
||||
expect(model.getState().controlOptions).toMatchObject({ service_tier: "default" });
|
||||
// The request carries everything the profile would save, so the daemon resolves it.
|
||||
expect(model.getState().controlsRequest?.providerOptions).toEqual({
|
||||
service_tier: "default",
|
||||
sandbox_mode: "read-only",
|
||||
});
|
||||
expect(model.getState().controlsResolution).toBe("pending");
|
||||
|
||||
model.applyControls(model.getState().controlsRequestKey ?? "", {
|
||||
...speed,
|
||||
options: { service_tier: "default", sandbox_mode: "read-only" },
|
||||
});
|
||||
expect(model.getState().controlsResolution).toBe("complete");
|
||||
expect(model.getState().controlOptions).toEqual({
|
||||
service_tier: "default",
|
||||
sandbox_mode: "read-only",
|
||||
});
|
||||
});
|
||||
|
||||
it("draws no controls for the previous model while another model's answer is pending", () => {
|
||||
const model = openWithCatalog({ mode: "create" });
|
||||
selectClaude(model);
|
||||
model.applyControls(model.getState().controlsRequestKey ?? "", WEB_SEARCH_CONTROLS);
|
||||
|
||||
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
|
||||
|
||||
expect(model.getState().controls).toEqual([]);
|
||||
expect(model.getState().featureValues).toEqual({ webSearch: true });
|
||||
});
|
||||
|
||||
it("resolves an unavailable feature listing without showing the field", () => {
|
||||
const model = openWithCatalog({ mode: "create" });
|
||||
selectClaude(model);
|
||||
|
||||
model.applyControlsUnavailable(model.getState().controlsRequestKey ?? "");
|
||||
model.applyFeaturesUnavailable(model.getState().featureRequestKey ?? "");
|
||||
|
||||
expect(model.getState().controlsResolution).toBe("complete");
|
||||
expect(model.getState().disclosure.showControlsField).toBe(false);
|
||||
expect(model.getState().featureResolution).toBe("complete");
|
||||
expect(model.getState().disclosure.showFeaturesField).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -562,15 +464,15 @@ describe("openAgentProfileForm", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildControlsRequestKey", () => {
|
||||
describe("buildFeatureRequestKey", () => {
|
||||
it("is null without a provider", () => {
|
||||
expect(buildControlsRequestKey(null)).toBeNull();
|
||||
expect(buildFeatureRequestKey(null)).toBeNull();
|
||||
});
|
||||
|
||||
it("separates the fields so a value cannot bleed across positions", () => {
|
||||
expect(buildControlsRequestKey({ provider: "claude", model: "a|b" })).toBe("claude|a|b||");
|
||||
expect(buildControlsRequestKey({ provider: "claude", modeId: "a" })).not.toBe(
|
||||
buildControlsRequestKey({ provider: "claude", model: "a" }),
|
||||
expect(buildFeatureRequestKey({ provider: "claude", model: "a|b" })).toBe("claude|a|b||");
|
||||
expect(buildFeatureRequestKey({ provider: "claude", modeId: "a" })).not.toBe(
|
||||
buildFeatureRequestKey({ provider: "claude", model: "a" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type {
|
||||
AgentOptionControl,
|
||||
ProviderOptions,
|
||||
AgentFeature,
|
||||
AgentMode,
|
||||
AgentModelDefinition,
|
||||
AgentSelectOption,
|
||||
@@ -8,6 +7,7 @@ import type {
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { formatAgentModeLabel, formatThinkingOptionLabel } from "@/agent-controls/labels";
|
||||
import { applyFeatureValues, pruneFeatureValues } from "@/hooks/feature-preferences";
|
||||
import { filterSelectableModels } from "@/provider-selection/model-catalog";
|
||||
|
||||
/**
|
||||
@@ -57,15 +57,11 @@ export interface AgentProfileFormSnapshot {
|
||||
}
|
||||
|
||||
/**
|
||||
* The inputs a controls listing needs. Controls are provider-scoped and change
|
||||
* with model/mode/thinking, so every one of those is part of the request. The
|
||||
* profile's own options ride along so the daemon can resolve them (a legacy
|
||||
* `service_tier: "fast"` is drawn as the model's Fast tier); they are the same
|
||||
* for the life of one provider, so they are not part of the key.
|
||||
* The inputs a feature listing needs. Features are provider-scoped and change
|
||||
* with model/mode/thinking, so every one of those is part of the request.
|
||||
*/
|
||||
export interface AgentProfileControlsRequest {
|
||||
export interface AgentProfileFeatureRequest {
|
||||
provider: string;
|
||||
providerOptions?: ProviderOptions;
|
||||
model?: string;
|
||||
modeId?: string;
|
||||
thinkingOptionId?: string;
|
||||
@@ -77,7 +73,7 @@ export interface AgentProfileFormDisclosure {
|
||||
showModelField: boolean;
|
||||
showModeField: boolean;
|
||||
showThinkingField: boolean;
|
||||
showControlsField: boolean;
|
||||
showFeaturesField: boolean;
|
||||
}
|
||||
|
||||
export interface AgentProfileFormState {
|
||||
@@ -90,18 +86,13 @@ export interface AgentProfileFormState {
|
||||
modelId: string;
|
||||
modeId: string;
|
||||
thinkingOptionId: string;
|
||||
/** The options the profile was opened with, including ones no control draws. */
|
||||
options: ProviderOptions;
|
||||
/** Changes made in this form, over `options`. */
|
||||
optionEdits: ProviderOptions;
|
||||
featureValues: Record<string, unknown>;
|
||||
|
||||
providerOptions: AgentProfileFormOption[];
|
||||
modelOptions: AgentProfileFormOption[];
|
||||
modeOptions: AgentProfileFormOption[];
|
||||
thinkingOptions: AgentProfileFormOption[];
|
||||
controls: AgentOptionControl[];
|
||||
/** What the controls show: the options the daemon resolved from `options`, then the edits. */
|
||||
controlOptions: ProviderOptions;
|
||||
features: AgentFeature[];
|
||||
|
||||
providerDisplay: AgentProfileFormDisplay | null;
|
||||
modelDisplay: AgentProfileFormDisplay | null;
|
||||
@@ -109,9 +100,9 @@ export interface AgentProfileFormState {
|
||||
thinkingDisplay: AgentProfileFormDisplay | null;
|
||||
|
||||
catalogResolution: AgentProfileResolutionStatus;
|
||||
controlsResolution: AgentProfileResolutionStatus;
|
||||
controlsRequest: AgentProfileControlsRequest | null;
|
||||
controlsRequestKey: string | null;
|
||||
featureResolution: AgentProfileResolutionStatus;
|
||||
featureRequest: AgentProfileFeatureRequest | null;
|
||||
featureRequestKey: string | null;
|
||||
|
||||
disclosure: AgentProfileFormDisclosure;
|
||||
isSubmitting: boolean;
|
||||
@@ -127,12 +118,9 @@ export interface AgentProfileFormModel {
|
||||
/** Late input: the host-scoped provider catalog. Never touches selections. */
|
||||
applyProviderCatalog: (entries: readonly ProviderSnapshotEntry[]) => void;
|
||||
/** Late input: the feature list for one request. Stale keys are ignored. */
|
||||
applyControls: (
|
||||
requestKey: string,
|
||||
resolved: { controls: readonly AgentOptionControl[]; options: ProviderOptions },
|
||||
) => void;
|
||||
applyFeatures: (requestKey: string, features: readonly AgentFeature[]) => void;
|
||||
/** Resolve a request that produced no usable features (provider error). */
|
||||
applyControlsUnavailable: (requestKey: string) => void;
|
||||
applyFeaturesUnavailable: (requestKey: string) => void;
|
||||
setName: (value: string) => void;
|
||||
setAppearance: (value: { icon: string; color: string }) => void;
|
||||
setNotes: (value: string) => void;
|
||||
@@ -140,7 +128,7 @@ export interface AgentProfileFormModel {
|
||||
setModel: (modelId: string, display: AgentProfileFormDisplay | null) => void;
|
||||
setMode: (modeId: string, display: AgentProfileFormDisplay | null) => void;
|
||||
setThinking: (thinkingOptionId: string, display: AgentProfileFormDisplay | null) => void;
|
||||
setOption: (key: string, value: unknown) => void;
|
||||
setFeatureValue: (featureId: string, value: unknown) => void;
|
||||
setSubmitting: (value: boolean) => void;
|
||||
setSubmitError: (value: string | null) => void;
|
||||
}
|
||||
@@ -324,29 +312,19 @@ function refineDisplay(
|
||||
return current ?? { label: selectedId };
|
||||
}
|
||||
|
||||
function buildControlsRequest(state: AgentProfileFormState): AgentProfileControlsRequest | null {
|
||||
function buildFeatureRequest(state: AgentProfileFormState): AgentProfileFeatureRequest | null {
|
||||
if (!state.provider) {
|
||||
return null;
|
||||
}
|
||||
const ownOptions = ownOptionsOf(state);
|
||||
return {
|
||||
provider: state.provider,
|
||||
...(state.modelId ? { model: state.modelId } : {}),
|
||||
...(state.modeId ? { modeId: state.modeId } : {}),
|
||||
...(state.thinkingOptionId ? { thinkingOptionId: state.thinkingOptionId } : {}),
|
||||
...(Object.keys(ownOptions).length > 0 ? { providerOptions: ownOptions } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Everything the profile would save as its options; the daemon resolves them for the form. */
|
||||
function ownOptionsOf(
|
||||
state: Pick<AgentProfileFormState, "options" | "optionEdits">,
|
||||
): ProviderOptions {
|
||||
return { ...state.options, ...state.optionEdits };
|
||||
}
|
||||
|
||||
/** The part of a request that decides which controls exist; options only change their values. */
|
||||
function buildControlsScopeKey(request: AgentProfileControlsRequest | null): string | null {
|
||||
export function buildFeatureRequestKey(request: AgentProfileFeatureRequest | null): string | null {
|
||||
if (!request) {
|
||||
return null;
|
||||
}
|
||||
@@ -358,25 +336,12 @@ function buildControlsScopeKey(request: AgentProfileControlsRequest | null): str
|
||||
].join("|");
|
||||
}
|
||||
|
||||
export function buildControlsRequestKey(
|
||||
request: AgentProfileControlsRequest | null,
|
||||
): string | null {
|
||||
if (!request) {
|
||||
return null;
|
||||
}
|
||||
const scope = buildControlsScopeKey(request);
|
||||
return request.providerOptions
|
||||
? `${scope}|${JSON.stringify(Object.entries(request.providerOptions).sort(([a], [b]) => a.localeCompare(b)))}`
|
||||
: scope;
|
||||
}
|
||||
|
||||
function buildSubmitValue(state: AgentProfileFormState): AgentProfileValue | null {
|
||||
const name = state.name.trim();
|
||||
const notes = state.notes.trim();
|
||||
if (!name || !state.provider) {
|
||||
return null;
|
||||
}
|
||||
const options = ownOptionsOf(state);
|
||||
return {
|
||||
name,
|
||||
...(state.icon ? { icon: state.icon } : {}),
|
||||
@@ -385,16 +350,16 @@ function buildSubmitValue(state: AgentProfileFormState): AgentProfileValue | nul
|
||||
...(state.modelId ? { model: state.modelId } : {}),
|
||||
...(state.modeId ? { modeId: state.modeId } : {}),
|
||||
...(state.thinkingOptionId ? { thinkingOptionId: state.thinkingOptionId } : {}),
|
||||
...(Object.keys(options).length > 0 ? { options } : {}),
|
||||
...(Object.keys(state.featureValues).length > 0 ? { featureValues: state.featureValues } : {}),
|
||||
...(notes ? { notes } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function resolveControlsStatus(
|
||||
controlsRequestKey: string | null,
|
||||
function resolveFeatureStatus(
|
||||
featureRequestKey: string | null,
|
||||
featuresAreCurrent: boolean,
|
||||
): AgentProfileResolutionStatus {
|
||||
if (controlsRequestKey === null) {
|
||||
if (featureRequestKey === null) {
|
||||
return "idle";
|
||||
}
|
||||
return featuresAreCurrent ? "complete" : "pending";
|
||||
@@ -427,27 +392,25 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
||||
modelId,
|
||||
modeId: profile.modeId ?? "",
|
||||
thinkingOptionId: profile.thinkingOptionId ?? "",
|
||||
options: { ...profile.options },
|
||||
optionEdits: {},
|
||||
featureValues: { ...profile.featureValues },
|
||||
providerOptions: [],
|
||||
modelOptions: [],
|
||||
modeOptions: [],
|
||||
thinkingOptions: [],
|
||||
controls: [],
|
||||
controlOptions: {},
|
||||
features: [],
|
||||
providerDisplay: seedDisplay(provider),
|
||||
modelDisplay: seedDisplay(modelId),
|
||||
modeDisplay: seedDisplay(profile.modeId),
|
||||
thinkingDisplay: seedDisplay(profile.thinkingOptionId),
|
||||
catalogResolution: "idle",
|
||||
controlsResolution: "idle",
|
||||
controlsRequest: null,
|
||||
controlsRequestKey: null,
|
||||
featureResolution: "idle",
|
||||
featureRequest: null,
|
||||
featureRequestKey: null,
|
||||
disclosure: {
|
||||
showModelField: false,
|
||||
showModeField: false,
|
||||
showThinkingField: false,
|
||||
showControlsField: false,
|
||||
showFeaturesField: false,
|
||||
},
|
||||
isSubmitting: false,
|
||||
submitError: null,
|
||||
@@ -459,10 +422,8 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
||||
export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentProfileFormModel {
|
||||
let entries: readonly ProviderSnapshotEntry[] = [];
|
||||
let catalogResolution: AgentProfileResolutionStatus = "idle";
|
||||
let resolvedControlsKey: string | null = null;
|
||||
let resolvedScopeKey: string | null = null;
|
||||
let resolvedControls: AgentOptionControl[] = [];
|
||||
let resolvedOptions: ProviderOptions = {};
|
||||
let resolvedFeatureKey: string | null = null;
|
||||
let resolvedFeatures: AgentFeature[] = [];
|
||||
let listeners = new Set<() => void>();
|
||||
let closed = false;
|
||||
|
||||
@@ -475,23 +436,14 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
modes,
|
||||
});
|
||||
const thinking = resolveThinkingOptions(entries, next.provider, next.modelId);
|
||||
const controlsRequest = buildControlsRequest(next);
|
||||
const controlsRequestKey = buildControlsRequestKey(controlsRequest);
|
||||
const controlsScopeKey = buildControlsScopeKey(controlsRequest);
|
||||
const featureRequest = buildFeatureRequest(next);
|
||||
const featureRequestKey = buildFeatureRequestKey(featureRequest);
|
||||
const featuresAreCurrent =
|
||||
controlsRequestKey !== null && controlsRequestKey === resolvedControlsKey;
|
||||
// A toggle changes only the options, so the controls stay up while the daemon answers and the
|
||||
// toggle shows over the last answer. A change of provider, model, mode or thinking draws none
|
||||
// until its own answer arrives.
|
||||
const controlsApply = controlsScopeKey !== null && controlsScopeKey === resolvedScopeKey;
|
||||
const controls = controlsApply ? resolvedControls : [];
|
||||
let controlOptions: ProviderOptions = next.options;
|
||||
if (controlsApply) {
|
||||
controlOptions = featuresAreCurrent
|
||||
? resolvedOptions
|
||||
: { ...resolvedOptions, ...next.optionEdits };
|
||||
}
|
||||
const controlsResolution = resolveControlsStatus(controlsRequestKey, featuresAreCurrent);
|
||||
featureRequestKey !== null && featureRequestKey === resolvedFeatureKey;
|
||||
const features = featuresAreCurrent
|
||||
? applyFeatureValues(resolvedFeatures, next.featureValues)
|
||||
: [];
|
||||
const featureResolution = resolveFeatureStatus(featureRequestKey, featuresAreCurrent);
|
||||
|
||||
const withOptions: AgentProfileFormState = {
|
||||
...next,
|
||||
@@ -499,8 +451,7 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
modelOptions: buildModelOptions(models),
|
||||
modeOptions: buildModeOptions(modes),
|
||||
thinkingOptions: buildThinkingOptions(thinking),
|
||||
controls,
|
||||
controlOptions,
|
||||
features,
|
||||
providerDisplay: refineDisplay(
|
||||
next.providerDisplay,
|
||||
next.provider,
|
||||
@@ -528,9 +479,9 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
})(),
|
||||
),
|
||||
catalogResolution,
|
||||
controlsResolution,
|
||||
controlsRequest,
|
||||
controlsRequestKey,
|
||||
featureResolution,
|
||||
featureRequest,
|
||||
featureRequestKey,
|
||||
};
|
||||
|
||||
// A field appears once the catalog can populate it, and stays visible while
|
||||
@@ -541,7 +492,7 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
showModeField: hasProvider && (modes.length > 0 || Boolean(withOptions.modeId)),
|
||||
showThinkingField:
|
||||
hasProvider && (thinking.length > 0 || Boolean(withOptions.thinkingOptionId)),
|
||||
showControlsField: hasProvider && controls.length > 0,
|
||||
showFeaturesField: hasProvider && features.length > 0,
|
||||
};
|
||||
const canSubmit =
|
||||
withOptions.name.trim().length > 0 &&
|
||||
@@ -580,24 +531,23 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
catalogResolution = "complete";
|
||||
publish((current) => current);
|
||||
},
|
||||
applyControls: (requestKey, resolved) => {
|
||||
if (requestKey !== state.controlsRequestKey) {
|
||||
applyFeatures: (requestKey, features) => {
|
||||
if (requestKey !== state.featureRequestKey) {
|
||||
return;
|
||||
}
|
||||
resolvedControlsKey = requestKey;
|
||||
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
|
||||
resolvedControls = [...resolved.controls];
|
||||
resolvedOptions = resolved.options;
|
||||
publish((current) => current);
|
||||
resolvedFeatureKey = requestKey;
|
||||
resolvedFeatures = [...features];
|
||||
publish((current) => ({
|
||||
...current,
|
||||
featureValues: pruneFeatureValues(current.featureValues, resolvedFeatures),
|
||||
}));
|
||||
},
|
||||
applyControlsUnavailable: (requestKey) => {
|
||||
if (requestKey !== state.controlsRequestKey) {
|
||||
applyFeaturesUnavailable: (requestKey) => {
|
||||
if (requestKey !== state.featureRequestKey) {
|
||||
return;
|
||||
}
|
||||
resolvedControlsKey = requestKey;
|
||||
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
|
||||
resolvedControls = [];
|
||||
resolvedOptions = {};
|
||||
resolvedFeatureKey = requestKey;
|
||||
resolvedFeatures = [];
|
||||
publish((current) => current);
|
||||
},
|
||||
setName: (value) => publish((current) => ({ ...current, name: value })),
|
||||
@@ -622,8 +572,7 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
modeDisplay: null,
|
||||
thinkingOptionId: "",
|
||||
thinkingDisplay: null,
|
||||
options: {},
|
||||
optionEdits: {},
|
||||
featureValues: {},
|
||||
};
|
||||
}),
|
||||
setModel: (modelId, display) =>
|
||||
@@ -649,10 +598,10 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
publish((current) => ({ ...current, modeId, modeDisplay: display })),
|
||||
setThinking: (thinkingOptionId, display) =>
|
||||
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display })),
|
||||
setOption: (key, value) =>
|
||||
setFeatureValue: (featureId, value) =>
|
||||
publish((current) => ({
|
||||
...current,
|
||||
optionEdits: { ...current.optionEdits, [key]: value },
|
||||
featureValues: { ...current.featureValues, [featureId]: value },
|
||||
})),
|
||||
setSubmitting: (value) => publish((current) => ({ ...current, isSubmitting: value })),
|
||||
setSubmitError: (value) => publish((current) => ({ ...current, submitError: value })),
|
||||
|
||||
@@ -47,7 +47,7 @@ export function buildAgentProfileTags(input: {
|
||||
tags.push({ id: "thinking", label: formatThinkingOptionLabel({ id: thinkingOptionId }) });
|
||||
}
|
||||
|
||||
const featureCount = Object.keys(input.profile.options ?? {}).length;
|
||||
const featureCount = Object.keys(input.profile.featureValues ?? {}).length;
|
||||
if (featureCount > 0) {
|
||||
tags.push({ id: "features", label: input.formatFeatureCount(featureCount) });
|
||||
}
|
||||
|
||||
@@ -117,7 +117,9 @@ export function useAgentProfilePicker(
|
||||
modelId: resolved.modelId,
|
||||
modeId: resolved.modeId,
|
||||
thinkingOptionId: resolved.thinkingOptionId,
|
||||
...(Object.keys(resolved.options).length > 0 ? { options: resolved.options } : {}),
|
||||
...(Object.keys(resolved.featureValues).length > 0
|
||||
? { featureValues: resolved.featureValues }
|
||||
: {}),
|
||||
}),
|
||||
).catch((error) => {
|
||||
console.warn("[useAgentProfilePicker] persist profile selection failed", error);
|
||||
|
||||
@@ -27,7 +27,7 @@ export function useAgentProfileFormCatalog(input: {
|
||||
}, [entries, input.model]);
|
||||
}
|
||||
|
||||
export function useAgentProfileFormControls(input: {
|
||||
export function useAgentProfileFormFeatures(input: {
|
||||
serverId: string;
|
||||
model: AgentProfileFormModel;
|
||||
state: AgentProfileFormState;
|
||||
@@ -35,14 +35,14 @@ export function useAgentProfileFormControls(input: {
|
||||
const { t } = useTranslation();
|
||||
const client = useHostRuntimeClient(input.serverId);
|
||||
const isConnected = useHostRuntimeIsConnected(input.serverId);
|
||||
const request = input.state.controlsRequest;
|
||||
const requestKey = input.state.controlsRequestKey;
|
||||
const request = input.state.featureRequest;
|
||||
const requestKey = input.state.featureRequestKey;
|
||||
|
||||
// `dataShape: "value"` and not `"list"`: a list shape keeps the previous
|
||||
// page's data while the next request is in flight, which would hand the
|
||||
// features of one provider/model combination to the key of another.
|
||||
const controlsQuery = useFetchQuery({
|
||||
queryKey: ["agentProfileControls", input.serverId, requestKey],
|
||||
const featuresQuery = useFetchQuery({
|
||||
queryKey: ["agentProfileFeatures", input.serverId, requestKey],
|
||||
dataShape: "value",
|
||||
staleTimeMs: 5 * 60 * 1000,
|
||||
enabled: Boolean(client && isConnected && request),
|
||||
@@ -51,28 +51,28 @@ export function useAgentProfileFormControls(input: {
|
||||
if (!client || !request) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
const payload = await client.listProviderControls({ ...request, cwd: HOME_SCOPE_CWD });
|
||||
const payload = await client.listProviderFeatures({ ...request, cwd: HOME_SCOPE_CWD });
|
||||
if (payload.error) {
|
||||
throw new Error(payload.error);
|
||||
}
|
||||
return { controls: payload.controls ?? [], options: payload.options ?? {} };
|
||||
return payload.features ?? [];
|
||||
},
|
||||
});
|
||||
|
||||
const { data, isError } = controlsQuery;
|
||||
const { data, isError } = featuresQuery;
|
||||
const { model } = input;
|
||||
|
||||
useEffect(() => {
|
||||
if (!requestKey || !data) {
|
||||
return;
|
||||
}
|
||||
model.applyControls(requestKey, data);
|
||||
model.applyFeatures(requestKey, data);
|
||||
}, [data, model, requestKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!requestKey || !isError) {
|
||||
return;
|
||||
}
|
||||
model.applyControlsUnavailable(requestKey);
|
||||
model.applyFeaturesUnavailable(requestKey);
|
||||
}, [isError, model, requestKey]);
|
||||
}
|
||||
|
||||
@@ -2,8 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement }
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { AgentOptionControl, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import { readSelectOption, readToggleOption } from "@/agent-controls/option-controls";
|
||||
import type { AgentFeature } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -26,7 +25,7 @@ import type {
|
||||
} from "../internal/profile-form-model";
|
||||
import {
|
||||
useAgentProfileFormCatalog,
|
||||
useAgentProfileFormControls,
|
||||
useAgentProfileFormFeatures,
|
||||
} from "../internal/use-profile-form-inputs";
|
||||
import {
|
||||
useAgentProfileFormModel,
|
||||
@@ -142,7 +141,7 @@ function OpenAgentProfileEditModal({
|
||||
const model = useAgentProfileFormModel(snapshot);
|
||||
const state = useAgentProfileFormState(model);
|
||||
useAgentProfileFormCatalog({ serverId, model });
|
||||
useAgentProfileFormControls({ serverId, model, state });
|
||||
useAgentProfileFormFeatures({ serverId, model, state });
|
||||
|
||||
const sheetHeader = useMemo<SheetHeader>(
|
||||
() => ({
|
||||
@@ -329,17 +328,16 @@ function OpenAgentProfileEditModal({
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{state.disclosure.showControlsField ? (
|
||||
{state.disclosure.showFeaturesField ? (
|
||||
<Field
|
||||
label={t("settings.host.agentProfiles.featuresLabel")}
|
||||
testID="agent-profile-features-field"
|
||||
>
|
||||
<View style={styles.featureCard} testID="agent-profile-features-card">
|
||||
{state.controls.map((control, index) => (
|
||||
<AgentProfileControlRow
|
||||
key={control.key}
|
||||
control={control}
|
||||
options={state.controlOptions}
|
||||
{state.features.map((feature, index) => (
|
||||
<AgentProfileFeatureRow
|
||||
key={feature.id}
|
||||
feature={feature}
|
||||
isFirst={index === 0}
|
||||
disabled={state.isSubmitting}
|
||||
size={controlSize}
|
||||
@@ -402,16 +400,14 @@ function OpenAgentProfileEditModal({
|
||||
);
|
||||
}
|
||||
|
||||
function AgentProfileControlRow({
|
||||
control,
|
||||
options,
|
||||
function AgentProfileFeatureRow({
|
||||
feature,
|
||||
isFirst,
|
||||
disabled,
|
||||
size,
|
||||
model,
|
||||
}: {
|
||||
control: AgentOptionControl;
|
||||
options: ProviderOptions;
|
||||
feature: AgentFeature;
|
||||
isFirst: boolean;
|
||||
disabled: boolean;
|
||||
size: FieldControlSize;
|
||||
@@ -422,75 +418,74 @@ function AgentProfileControlRow({
|
||||
[isFirst],
|
||||
);
|
||||
const handleToggle = useCallback(
|
||||
(value: boolean) => model.setOption(control.key, value),
|
||||
[control.key, model],
|
||||
(value: boolean) => model.setFeatureValue(feature.id, value),
|
||||
[feature.id, model],
|
||||
);
|
||||
const handleSelect = useCallback(
|
||||
(value: string) => model.setOption(control.key, value),
|
||||
[control.key, model],
|
||||
(value: string) => model.setFeatureValue(feature.id, value),
|
||||
[feature.id, model],
|
||||
);
|
||||
const selectOptions = useMemo<SelectFieldOption<string>[]>(
|
||||
() =>
|
||||
control.type === "select"
|
||||
? control.choices.map((choice) => ({
|
||||
id: choice.value,
|
||||
value: choice.value,
|
||||
label: choice.label,
|
||||
...(choice.description ? { description: choice.description } : {}),
|
||||
testID: `agent-profile-feature-option-${control.key}-${choice.value}`,
|
||||
feature.type === "select"
|
||||
? feature.options.map((option) => ({
|
||||
id: option.id,
|
||||
value: option.id,
|
||||
label: option.label,
|
||||
...(option.description ? { description: option.description } : {}),
|
||||
testID: `agent-profile-feature-option-${feature.id}-${option.id}`,
|
||||
}))
|
||||
: [],
|
||||
[control],
|
||||
[feature],
|
||||
);
|
||||
const selectedValue = control.type === "select" ? readSelectOption(control, options) : null;
|
||||
const selectedDisplay = useMemo<SelectFieldDisplay | null>(() => {
|
||||
if (control.type !== "select" || !selectedValue) {
|
||||
if (feature.type !== "select" || !feature.value) {
|
||||
return null;
|
||||
}
|
||||
const choice = control.choices.find((candidate) => candidate.value === selectedValue);
|
||||
return { label: choice?.label ?? selectedValue };
|
||||
}, [control, selectedValue]);
|
||||
const option = feature.options.find((candidate) => candidate.id === feature.value);
|
||||
return { label: option?.label ?? feature.value };
|
||||
}, [feature]);
|
||||
|
||||
if (control.type === "select") {
|
||||
if (feature.type === "select") {
|
||||
return (
|
||||
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
|
||||
<View style={rowStyle} testID={`agent-profile-feature-row-${feature.id}`}>
|
||||
<SelectField
|
||||
label={control.label}
|
||||
value={selectedValue}
|
||||
label={feature.label}
|
||||
value={feature.value}
|
||||
selectedDisplay={selectedDisplay}
|
||||
options={selectOptions}
|
||||
onChange={handleSelect}
|
||||
placeholder={control.label}
|
||||
emptyText={control.label}
|
||||
placeholder={feature.label}
|
||||
emptyText={feature.label}
|
||||
disabled={disabled}
|
||||
{...(control.description ? { hint: control.description } : {})}
|
||||
title={control.label}
|
||||
{...(feature.description ? { hint: feature.description } : {})}
|
||||
title={feature.label}
|
||||
size={size}
|
||||
testID={`agent-profile-feature-field-${control.key}`}
|
||||
triggerTestID={`agent-profile-feature-trigger-${control.key}`}
|
||||
testID={`agent-profile-feature-field-${feature.id}`}
|
||||
triggerTestID={`agent-profile-feature-trigger-${feature.id}`}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
|
||||
<View style={rowStyle} testID={`agent-profile-feature-row-${feature.id}`}>
|
||||
<View style={styles.featureMeta}>
|
||||
<Text style={styles.featureLabel} numberOfLines={1}>
|
||||
{control.label}
|
||||
{feature.label}
|
||||
</Text>
|
||||
{control.description ? (
|
||||
{feature.description ? (
|
||||
<Text style={styles.featureDescription} numberOfLines={2}>
|
||||
{control.description}
|
||||
{feature.description}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Switch
|
||||
value={readToggleOption(control, options)}
|
||||
value={feature.value === true}
|
||||
onValueChange={handleToggle}
|
||||
disabled={disabled}
|
||||
accessibilityLabel={control.label}
|
||||
testID={`agent-profile-feature-switch-${control.key}`}
|
||||
accessibilityLabel={feature.label}
|
||||
testID={`agent-profile-feature-switch-${feature.id}`}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -69,6 +69,9 @@ function installProbe(
|
||||
queryClient: new QueryClient(),
|
||||
paseo: {} as InstalledPlugin["paseo"],
|
||||
invoke: async () => undefined,
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1304,8 +1304,7 @@ function collectAgentSetupDiffs(left: AgentScreenAgent, right: AgentScreenAgent)
|
||||
if (left.runtimeInfo?.thinkingOptionId !== right.runtimeInfo?.thinkingOptionId) {
|
||||
reasons.push("agent.runtimeInfo.thinkingOptionId");
|
||||
}
|
||||
if (left.options !== right.options) reasons.push("agent.options");
|
||||
if (left.controls !== right.controls) reasons.push("agent.controls");
|
||||
if (left.features !== right.features) reasons.push("agent.features");
|
||||
return reasons;
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,16 @@ function createAgent(overrides: Partial<Agent> = {}): Agent {
|
||||
cwd: "/repo",
|
||||
model: "agent-model",
|
||||
thinkingOptionId: "think-hard",
|
||||
options: { "web-search": true, effort: "high" },
|
||||
features: [
|
||||
{ type: "toggle", id: "web-search", label: "Web search", value: true },
|
||||
{
|
||||
type: "select",
|
||||
id: "effort",
|
||||
label: "Effort",
|
||||
value: "high",
|
||||
options: [{ id: "high", label: "High" }],
|
||||
},
|
||||
],
|
||||
parentAgentId: null,
|
||||
labels: {},
|
||||
...overrides,
|
||||
@@ -105,7 +114,7 @@ describe("buildDraftAgentSetup", () => {
|
||||
modeId: "mode-current",
|
||||
model: "agent-model",
|
||||
thinkingOptionId: "think-hard",
|
||||
providerOptions: {
|
||||
featureValues: {
|
||||
"web-search": true,
|
||||
effort: "high",
|
||||
},
|
||||
|
||||
@@ -65,12 +65,17 @@ export function resolveClientSlashCommand(input: {
|
||||
}
|
||||
|
||||
export function buildDraftAgentSetup(agent: Agent): WorkspaceDraftTabSetup {
|
||||
const featureValues: Record<string, unknown> = {};
|
||||
for (const feature of agent.features ?? []) {
|
||||
featureValues[feature.id] = feature.value;
|
||||
}
|
||||
|
||||
return {
|
||||
provider: agent.provider,
|
||||
cwd: agent.cwd,
|
||||
modeId: agent.currentModeId ?? agent.runtimeInfo?.modeId ?? null,
|
||||
model: agent.model ?? agent.runtimeInfo?.model ?? null,
|
||||
thinkingOptionId: agent.thinkingOptionId ?? agent.runtimeInfo?.thinkingOptionId ?? null,
|
||||
providerOptions: { ...agent.options },
|
||||
featureValues,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type {
|
||||
AgentMode,
|
||||
AgentOptionControl,
|
||||
AgentSelectOption,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentFeature, AgentMode, AgentSelectOption } from "@getpaseo/protocol/agent-types";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import type { CommandCenterContribution } from "./contributions";
|
||||
import {
|
||||
@@ -35,7 +31,7 @@ const ICONS: AgentControlContributionSource["icons"] = {
|
||||
thinking: TestIcon,
|
||||
planMode: TestIcon,
|
||||
mode: () => TestIcon,
|
||||
control: () => TestIcon,
|
||||
feature: () => TestIcon,
|
||||
};
|
||||
|
||||
function provider(input: {
|
||||
@@ -69,8 +65,8 @@ function provider(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function toggleControl(key: string, icon?: string): AgentOptionControl {
|
||||
return { type: "toggle", key, label: key, icon };
|
||||
function toggleFeature(id: string, value = false, icon?: string): AgentFeature {
|
||||
return { type: "toggle", id, label: id, value, icon };
|
||||
}
|
||||
|
||||
function makeSource(
|
||||
@@ -79,7 +75,7 @@ function makeSource(
|
||||
models?: Partial<AgentControlContributionSource["models"]>;
|
||||
thinking?: Partial<AgentControlContributionSource["thinking"]>;
|
||||
modes?: Partial<NonNullable<AgentControlContributionSource["modes"]>>;
|
||||
optionControls?: Partial<AgentControlContributionSource["optionControls"]>;
|
||||
features?: Partial<AgentControlContributionSource["features"]>;
|
||||
} = {},
|
||||
): AgentControlContributionSource {
|
||||
return {
|
||||
@@ -108,11 +104,10 @@ function makeSource(
|
||||
select: () => undefined,
|
||||
...overrides.modes,
|
||||
},
|
||||
optionControls: {
|
||||
controls: [],
|
||||
options: {},
|
||||
onSetOption: () => undefined,
|
||||
...overrides.optionControls,
|
||||
features: {
|
||||
list: [],
|
||||
set: () => undefined,
|
||||
...overrides.features,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -138,7 +133,7 @@ describe("Command Center agent-control contributions", () => {
|
||||
const contributions = buildAgentControlContributions({
|
||||
...makeSource({
|
||||
models: { providers: [provider({ id: "claude", label: "Claude" })] },
|
||||
optionControls: { controls: [toggleControl("plan_mode")], options: { plan_mode: true } },
|
||||
features: { list: [toggleFeature("plan_mode", true)] },
|
||||
}),
|
||||
modes: undefined,
|
||||
});
|
||||
@@ -328,10 +323,9 @@ describe("Command Center agent-control contributions", () => {
|
||||
selectedId: "default",
|
||||
defaultModeId: "default",
|
||||
},
|
||||
optionControls: {
|
||||
controls: [toggleControl("plan_mode", "list-todo")],
|
||||
options: { plan_mode: true },
|
||||
onSetOption: (id, value) => {
|
||||
features: {
|
||||
list: [toggleFeature("plan_mode", true, "list-todo")],
|
||||
set: (id, value) => {
|
||||
calls.push([id, value]);
|
||||
},
|
||||
},
|
||||
@@ -347,10 +341,9 @@ describe("Command Center agent-control contributions", () => {
|
||||
const calls: [string, unknown][] = [];
|
||||
const contributions = buildAgentControlContributions(
|
||||
makeSource({
|
||||
optionControls: {
|
||||
controls: [toggleControl("fast_mode", "zap"), toggleControl("auto_accept")],
|
||||
options: { fast_mode: false, auto_accept: true },
|
||||
onSetOption: (id, value) => {
|
||||
features: {
|
||||
list: [toggleFeature("fast_mode", false, "zap"), toggleFeature("auto_accept", true)],
|
||||
set: (id, value) => {
|
||||
calls.push([id, value]);
|
||||
},
|
||||
},
|
||||
@@ -383,7 +376,7 @@ describe("Command Center agent-control contributions", () => {
|
||||
selectedId: "default",
|
||||
defaultModeId: "default",
|
||||
},
|
||||
optionControls: { controls: [toggleControl("fast_mode")], options: {} },
|
||||
features: { list: [toggleFeature("fast_mode")] },
|
||||
}),
|
||||
);
|
||||
const ranks = new Map<string, number>();
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import type {
|
||||
AgentFeature,
|
||||
AgentMode,
|
||||
AgentOptionControl,
|
||||
AgentProvider,
|
||||
AgentSelectOption,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import { readToggleOption, type ComposerOptionControls } from "@/agent-controls/option-controls";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import { formatAgentModeLabel, formatThinkingOptionLabel } from "@/agent-controls/labels";
|
||||
import {
|
||||
@@ -62,7 +61,7 @@ export interface AgentControlContributionIcons {
|
||||
thinking: CommandCenterIcon;
|
||||
planMode: CommandCenterIcon;
|
||||
mode(modeId: string): CommandCenterIcon;
|
||||
control(control: AgentOptionControl): CommandCenterIcon;
|
||||
feature(feature: AgentFeature): CommandCenterIcon;
|
||||
}
|
||||
|
||||
interface CommandCenterChoice {
|
||||
@@ -106,7 +105,10 @@ export interface AgentControlContributionSource {
|
||||
defaultModeId: string | null;
|
||||
select(modeId: string): void | Promise<void>;
|
||||
};
|
||||
optionControls: ComposerOptionControls;
|
||||
features: {
|
||||
list: readonly AgentFeature[];
|
||||
set(featureId: string, value: unknown): void | Promise<void>;
|
||||
};
|
||||
}
|
||||
|
||||
function buildContributions(
|
||||
@@ -240,19 +242,18 @@ function toggleChoices(input: {
|
||||
}
|
||||
|
||||
function buildPlanModeGroup(source: AgentControlContributionSource): CommandCenterChoiceGroup {
|
||||
const { controls, options, onSetOption } = source.optionControls;
|
||||
const planControl = controls.find(
|
||||
(control) => control.key === PLAN_MODE_FEATURE_ID && control.type === "toggle",
|
||||
const planFeature = source.features.list.find(
|
||||
(feature) => feature.id === PLAN_MODE_FEATURE_ID && feature.type === "toggle",
|
||||
);
|
||||
let choices: CommandCenterChoice[] = [];
|
||||
if (planControl?.type === "toggle") {
|
||||
if (planFeature?.type === "toggle") {
|
||||
choices = toggleChoices({
|
||||
source,
|
||||
key: "plan",
|
||||
icon: source.icons.control(planControl),
|
||||
isOn: readToggleOption(planControl, options),
|
||||
turnOn: () => onSetOption(PLAN_MODE_FEATURE_ID, true),
|
||||
turnOff: () => onSetOption(PLAN_MODE_FEATURE_ID, false),
|
||||
icon: source.icons.feature(planFeature),
|
||||
isOn: planFeature.value,
|
||||
turnOn: () => source.features.set(PLAN_MODE_FEATURE_ID, true),
|
||||
turnOff: () => source.features.set(PLAN_MODE_FEATURE_ID, false),
|
||||
});
|
||||
} else if (source.modes) {
|
||||
const modes = source.modes;
|
||||
@@ -279,19 +280,18 @@ function buildPlanModeGroup(source: AgentControlContributionSource): CommandCent
|
||||
}
|
||||
|
||||
function buildFastModeGroup(source: AgentControlContributionSource): CommandCenterChoiceGroup {
|
||||
const { controls, options, onSetOption } = source.optionControls;
|
||||
const fastControl = controls.find(
|
||||
(control) => control.key === FAST_MODE_FEATURE_ID && control.type === "toggle",
|
||||
const fastFeature = source.features.list.find(
|
||||
(feature) => feature.id === FAST_MODE_FEATURE_ID && feature.type === "toggle",
|
||||
);
|
||||
const choices =
|
||||
fastControl?.type === "toggle"
|
||||
fastFeature?.type === "toggle"
|
||||
? toggleChoices({
|
||||
source,
|
||||
key: "fast",
|
||||
icon: source.icons.control(fastControl),
|
||||
isOn: readToggleOption(fastControl, options),
|
||||
turnOn: () => onSetOption(FAST_MODE_FEATURE_ID, true),
|
||||
turnOff: () => onSetOption(FAST_MODE_FEATURE_ID, false),
|
||||
icon: source.icons.feature(fastFeature),
|
||||
isOn: fastFeature.value,
|
||||
turnOn: () => source.features.set(FAST_MODE_FEATURE_ID, true),
|
||||
turnOff: () => source.features.set(FAST_MODE_FEATURE_ID, false),
|
||||
})
|
||||
: [];
|
||||
return {
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { AgentMode, AgentProvider, AgentSelectOption } from "@getpaseo/protocol/agent-types";
|
||||
import type {
|
||||
AgentFeature,
|
||||
AgentMode,
|
||||
AgentProvider,
|
||||
AgentSelectOption,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
|
||||
import {
|
||||
getAgentFeatureIcon,
|
||||
@@ -9,7 +14,6 @@ import {
|
||||
ThinkingIcon,
|
||||
} from "@/agent-controls/icons";
|
||||
import { useProviderIcons } from "@/components/provider-icons";
|
||||
import type { ComposerOptionControls } from "@/agent-controls/option-controls";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import {
|
||||
buildAgentControlContributions,
|
||||
@@ -40,15 +44,15 @@ export interface AgentControlCommandCenterSource {
|
||||
selectedId: string | null | undefined;
|
||||
select(modeId: string): void | Promise<void>;
|
||||
};
|
||||
/** Absent when the surface cannot change options (the agent has no client). */
|
||||
optionControls: ComposerOptionControls | null;
|
||||
features: {
|
||||
list: readonly AgentFeature[] | undefined;
|
||||
set?: (featureId: string, value: unknown) => void | Promise<void>;
|
||||
};
|
||||
}
|
||||
|
||||
const NO_OPTION_CONTROLS: ComposerOptionControls = {
|
||||
controls: [],
|
||||
options: {},
|
||||
onSetOption: () => undefined,
|
||||
};
|
||||
function ignoreAgentFeatureChange(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
function resolveDefaultModeId(
|
||||
provider: string | null | undefined,
|
||||
@@ -83,7 +87,7 @@ export function useAgentControlCommandCenterActions(input: {
|
||||
}): void {
|
||||
const { t } = useTranslation();
|
||||
const { controls } = input;
|
||||
const { optionControls, models, modes, thinking } = controls;
|
||||
const { features, models, modes, thinking } = controls;
|
||||
const getProviderIcon = useProviderIcons(controls.serverId);
|
||||
const actions = useMemo(
|
||||
() =>
|
||||
@@ -100,7 +104,7 @@ export function useAgentControlCommandCenterActions(input: {
|
||||
getCommandCenterIcon(
|
||||
getAgentModeIcon(controls.provider ?? "", modeId, controls.providerDefinitions),
|
||||
),
|
||||
control: (control) => getCommandCenterIcon(getAgentFeatureIcon(control.icon)),
|
||||
feature: (feature) => getCommandCenterIcon(getAgentFeatureIcon(feature.icon)),
|
||||
},
|
||||
models: {
|
||||
providers: models.providers,
|
||||
@@ -119,7 +123,10 @@ export function useAgentControlCommandCenterActions(input: {
|
||||
modes?.select,
|
||||
resolveDefaultModeId(controls.provider, controls.providerDefinitions),
|
||||
),
|
||||
optionControls: optionControls ?? NO_OPTION_CONTROLS,
|
||||
features: {
|
||||
list: features.set ? (features.list ?? []) : [],
|
||||
set: features.set ?? ignoreAgentFeatureChange,
|
||||
},
|
||||
}),
|
||||
[
|
||||
getProviderIcon,
|
||||
@@ -127,7 +134,8 @@ export function useAgentControlCommandCenterActions(input: {
|
||||
controls.provider,
|
||||
controls.providerDefinitions,
|
||||
controls.serverId,
|
||||
optionControls,
|
||||
features.list,
|
||||
features.set,
|
||||
models.providers,
|
||||
models.select,
|
||||
models.selectedModelId,
|
||||
|
||||
@@ -25,13 +25,6 @@ import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import { Settings2 } from "lucide-react-native";
|
||||
import { getAgentFeatureIcon, ThinkingIcon } from "@/agent-controls/icons";
|
||||
import {
|
||||
getControlTooltip,
|
||||
isControlActive,
|
||||
readSelectOption,
|
||||
readToggleOption,
|
||||
type ComposerOptionControls,
|
||||
} from "@/agent-controls/option-controls";
|
||||
import { formatThinkingOptionLabel } from "@/agent-controls/labels";
|
||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||
import { CombinedModelSelector } from "@/components/combined-model-selector";
|
||||
@@ -54,8 +47,7 @@ import {
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import type {
|
||||
AgentOptionControl,
|
||||
ProviderOptions,
|
||||
AgentFeature,
|
||||
AgentMode,
|
||||
AgentModelDefinition,
|
||||
AgentProvider,
|
||||
@@ -63,6 +55,8 @@ import type {
|
||||
import type { AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
|
||||
import {
|
||||
getFeatureHighlightColor,
|
||||
isFeatureActive,
|
||||
getFeatureTooltip,
|
||||
getAgentControlHintKey,
|
||||
resolveAgentModelSelection,
|
||||
} from "@/composer/agent-controls/utils";
|
||||
@@ -107,7 +101,6 @@ interface AgentControlOption {
|
||||
type AgentControlSelector = "provider" | "mode" | "model" | "thinking" | `feature-${string}`;
|
||||
|
||||
const EMPTY_AGENT_PROVIDER_DEFINITIONS: AgentProviderDefinition[] = [];
|
||||
const EMPTY_OPTIONS: ProviderOptions = {};
|
||||
|
||||
interface ControlledAgentControlsProps {
|
||||
provider: string;
|
||||
@@ -129,7 +122,8 @@ interface ControlledAgentControlsProps {
|
||||
onEditAgentProfiles?: () => void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditAgentProfile?: (profileId: string) => void;
|
||||
optionControls?: ComposerOptionControls;
|
||||
features?: AgentFeature[];
|
||||
onSetFeature?: (featureId: string, value: unknown) => void;
|
||||
onDropdownClose?: () => void;
|
||||
onModelSelectorOpen?: () => void;
|
||||
onRetryModelProvider?: (provider: AgentProvider) => void;
|
||||
@@ -156,7 +150,8 @@ export interface DraftAgentControlsProps {
|
||||
selectedThinkingOptionId: string;
|
||||
onSelectThinkingOption: (thinkingOptionId: string) => void;
|
||||
onApplyAgentProfile: DraftAgentProfileControls["applyProfile"];
|
||||
optionControls?: ComposerOptionControls;
|
||||
features?: AgentFeature[];
|
||||
onSetFeature?: (featureId: string, value: unknown) => void;
|
||||
onDropdownClose?: () => void;
|
||||
onModelSelectorOpen?: () => void;
|
||||
onRetryModelProvider?: (provider: AgentProvider) => void;
|
||||
@@ -217,8 +212,7 @@ function getModeProviderDefinitions(modeControl: AgentModeControlValue | null) {
|
||||
}
|
||||
|
||||
function getFeatureIconColor(
|
||||
control: AgentOptionControl,
|
||||
options: ProviderOptions,
|
||||
feature: AgentFeature,
|
||||
palette: {
|
||||
blue: { 400: string };
|
||||
green: { 400: string };
|
||||
@@ -226,11 +220,11 @@ function getFeatureIconColor(
|
||||
},
|
||||
foregroundMuted: string,
|
||||
): string {
|
||||
if (!isControlActive(control, options)) {
|
||||
if (!isFeatureActive(feature)) {
|
||||
return foregroundMuted;
|
||||
}
|
||||
|
||||
switch (getFeatureHighlightColor(control.key)) {
|
||||
switch (getFeatureHighlightColor(feature.id)) {
|
||||
case "blue":
|
||||
return palette.blue[400];
|
||||
case "green":
|
||||
@@ -248,20 +242,20 @@ function resolveHasAnyControl({
|
||||
providerOptions,
|
||||
canSelectModel,
|
||||
thinkingOptions,
|
||||
controls,
|
||||
features,
|
||||
hasMode,
|
||||
}: {
|
||||
providerOptions: AgentControlOption[] | undefined;
|
||||
canSelectModel: boolean;
|
||||
thinkingOptions: AgentControlOption[] | undefined;
|
||||
controls: readonly AgentOptionControl[] | undefined;
|
||||
features: AgentFeature[] | undefined;
|
||||
hasMode: boolean;
|
||||
}) {
|
||||
return (
|
||||
Boolean(providerOptions?.length) ||
|
||||
canSelectModel ||
|
||||
Boolean(thinkingOptions?.length) ||
|
||||
Boolean(controls?.length) ||
|
||||
Boolean(features?.length) ||
|
||||
hasMode
|
||||
);
|
||||
}
|
||||
@@ -399,8 +393,7 @@ type AgentControlsSlice = {
|
||||
cwd: string | null;
|
||||
runtimeModelId: string | null;
|
||||
model: string | null | undefined;
|
||||
options: ProviderOptions | undefined;
|
||||
controls: AgentOptionControl[] | undefined;
|
||||
features: AgentFeature[] | undefined;
|
||||
runtimeThinkingOptionId: string | null;
|
||||
thinkingOptionId: string | null | undefined;
|
||||
lastUsage: unknown;
|
||||
@@ -420,8 +413,7 @@ function selectAgentControlsSlice(
|
||||
cwd: currentAgent.cwd,
|
||||
runtimeModelId: currentAgent.runtimeInfo?.model ?? null,
|
||||
model: currentAgent.model,
|
||||
options: currentAgent.options,
|
||||
controls: currentAgent.controls,
|
||||
features: currentAgent.features,
|
||||
runtimeThinkingOptionId: currentAgent.runtimeInfo?.thinkingOptionId ?? null,
|
||||
thinkingOptionId: currentAgent.thinkingOptionId,
|
||||
lastUsage: currentAgent.lastUsage,
|
||||
@@ -501,7 +493,8 @@ function ControlledAgentControls({
|
||||
onEditAgentProfiles,
|
||||
onCreateAgentProfile,
|
||||
onEditAgentProfile,
|
||||
optionControls,
|
||||
features,
|
||||
onSetFeature,
|
||||
onDropdownClose,
|
||||
onModelSelectorOpen,
|
||||
onRetryModelProvider,
|
||||
@@ -553,21 +546,20 @@ function ControlledAgentControls({
|
||||
providerOptions,
|
||||
canSelectModel,
|
||||
thinkingOptions,
|
||||
controls: optionControls?.controls,
|
||||
features,
|
||||
hasMode: modeControl !== null && modeControl !== undefined,
|
||||
});
|
||||
const featureControls = useMemo(
|
||||
() =>
|
||||
(optionControls?.controls ?? []).map((control) => {
|
||||
if (control.type === "toggle") return { type: "toggle" as const };
|
||||
const selected = readSelectOption(control, optionControls?.options ?? {});
|
||||
const choice = control.choices.find((candidate) => candidate.value === selected);
|
||||
(features ?? []).map((feature) => {
|
||||
if (feature.type === "toggle") return { type: "toggle" as const };
|
||||
const selectedOption = feature.options.find((option) => option.id === feature.value);
|
||||
return {
|
||||
type: "select" as const,
|
||||
label: choice?.label ?? control.label,
|
||||
label: selectedOption?.label ?? feature.label,
|
||||
};
|
||||
}),
|
||||
[optionControls],
|
||||
[features],
|
||||
);
|
||||
const controlPresence = useMemo(
|
||||
() => ({
|
||||
@@ -751,7 +743,8 @@ function ControlledAgentControls({
|
||||
selectedModelId={selectedModelId}
|
||||
thinkingOptions={formattedThinkingOptions}
|
||||
selectedThinkingOptionId={selectedThinkingOptionId}
|
||||
optionControls={optionControls}
|
||||
features={features}
|
||||
onSetFeature={onSetFeature}
|
||||
onApplyAgentProfile={onApplyAgentProfile}
|
||||
onEditAgentProfiles={onEditAgentProfiles}
|
||||
onCreateAgentProfile={onCreateAgentProfile}
|
||||
@@ -799,7 +792,8 @@ function ControlledAgentControls({
|
||||
provider={provider}
|
||||
selectedModelId={selectedModelId}
|
||||
selectedThinkingOptionId={selectedThinkingOptionId}
|
||||
optionControls={optionControls}
|
||||
features={features}
|
||||
onSetFeature={onSetFeature}
|
||||
onApplyAgentProfile={onApplyAgentProfile}
|
||||
onEditAgentProfiles={onEditAgentProfiles}
|
||||
onCreateAgentProfile={onCreateAgentProfile}
|
||||
@@ -844,7 +838,8 @@ interface DesktopAgentControlsContentProps {
|
||||
selectedModelId?: string;
|
||||
thinkingOptions?: AgentControlOption[];
|
||||
selectedThinkingOptionId?: string;
|
||||
optionControls?: ComposerOptionControls;
|
||||
features?: AgentFeature[];
|
||||
onSetFeature?: (featureId: string, value: unknown) => void;
|
||||
onApplyAgentProfile?: (profileId: string) => void;
|
||||
onEditAgentProfiles?: () => void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => void;
|
||||
@@ -905,7 +900,8 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
|
||||
selectedModelId,
|
||||
thinkingOptions,
|
||||
selectedThinkingOptionId,
|
||||
optionControls,
|
||||
features,
|
||||
onSetFeature,
|
||||
onApplyAgentProfile,
|
||||
onEditAgentProfiles,
|
||||
onCreateAgentProfile,
|
||||
@@ -1061,7 +1057,7 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
|
||||
|
||||
{modeControl ? <AgentModeControl {...modeControl} onClose={onDropdownClose} /> : null}
|
||||
|
||||
{presentation.aggregateFeatures && optionControls?.controls.length ? (
|
||||
{presentation.aggregateFeatures && features?.length ? (
|
||||
<>
|
||||
<Pressable
|
||||
onPress={handleOpenFeatures}
|
||||
@@ -1081,29 +1077,27 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
|
||||
onClose={handleCloseSheet}
|
||||
testID="agent-features-sheet"
|
||||
>
|
||||
{optionControls.controls.map((control) => (
|
||||
{features.map((feature) => (
|
||||
<SheetFeatureItem
|
||||
key={`feature-${control.key}`}
|
||||
control={control}
|
||||
options={optionControls.options}
|
||||
key={`feature-${feature.id}`}
|
||||
feature={feature}
|
||||
disabled={disabled}
|
||||
openSelector={openSelector}
|
||||
handleOpenChange={handleNestedOpenChange}
|
||||
onSetOption={optionControls.onSetOption}
|
||||
onSetFeature={onSetFeature}
|
||||
/>
|
||||
))}
|
||||
</AdaptiveModalSheet>
|
||||
</>
|
||||
) : (
|
||||
optionControls?.controls.map((control) => (
|
||||
features?.map((feature) => (
|
||||
<DesktopFeatureItem
|
||||
key={`feature-${control.key}`}
|
||||
control={control}
|
||||
options={optionControls.options}
|
||||
key={`feature-${feature.id}`}
|
||||
feature={feature}
|
||||
disabled={disabled}
|
||||
openSelector={openSelector}
|
||||
handleOpenChange={handleOpenChange}
|
||||
onSetOption={optionControls.onSetOption}
|
||||
onSetFeature={onSetFeature}
|
||||
onActionComplete={onDropdownClose}
|
||||
/>
|
||||
))
|
||||
@@ -1116,7 +1110,8 @@ interface SheetAgentControlsContentProps {
|
||||
provider: string;
|
||||
selectedModelId?: string;
|
||||
selectedThinkingOptionId?: string;
|
||||
optionControls?: ComposerOptionControls;
|
||||
features?: AgentFeature[];
|
||||
onSetFeature?: (featureId: string, value: unknown) => void;
|
||||
onApplyAgentProfile?: (profileId: string) => void;
|
||||
onEditAgentProfiles?: () => void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => void;
|
||||
@@ -1159,7 +1154,8 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
|
||||
provider,
|
||||
selectedModelId,
|
||||
selectedThinkingOptionId,
|
||||
optionControls,
|
||||
features,
|
||||
onSetFeature,
|
||||
onApplyAgentProfile,
|
||||
onEditAgentProfiles,
|
||||
onCreateAgentProfile,
|
||||
@@ -1192,7 +1188,6 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
|
||||
} = props;
|
||||
|
||||
const thinkingAnchorRef = useRef<View | null>(null);
|
||||
const sheetOptions = optionControls?.options ?? EMPTY_OPTIONS;
|
||||
|
||||
const hasThinking = comboboxThinkingOptions.length > 0;
|
||||
|
||||
@@ -1243,15 +1238,14 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
|
||||
|
||||
{modeControl ? <AgentModeControl {...modeControl} surface="sheet" /> : null}
|
||||
|
||||
{(optionControls?.controls ?? []).map((control) => (
|
||||
{(features ?? []).map((feature) => (
|
||||
<SheetFeatureItem
|
||||
key={`feature-${control.key}`}
|
||||
control={control}
|
||||
options={sheetOptions}
|
||||
key={`feature-${feature.id}`}
|
||||
feature={feature}
|
||||
disabled={disabled}
|
||||
openSelector={openSelector}
|
||||
handleOpenChange={handleOpenChange}
|
||||
onSetOption={optionControls?.onSetOption}
|
||||
onSetFeature={onSetFeature}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
@@ -1285,24 +1279,22 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
|
||||
}
|
||||
|
||||
function DesktopFeatureItem({
|
||||
control,
|
||||
options,
|
||||
feature,
|
||||
disabled,
|
||||
openSelector,
|
||||
handleOpenChange,
|
||||
onSetOption,
|
||||
onSetFeature,
|
||||
onActionComplete,
|
||||
}: {
|
||||
control: AgentOptionControl;
|
||||
options: ProviderOptions;
|
||||
feature: AgentFeature;
|
||||
disabled: boolean;
|
||||
openSelector: AgentControlSelector | null;
|
||||
handleOpenChange: (selector: AgentControlSelector) => (nextOpen: boolean) => void;
|
||||
onSetOption?: (key: string, value: unknown) => void;
|
||||
onSetFeature?: (featureId: string, value: unknown) => void;
|
||||
onActionComplete?: () => void;
|
||||
}) {
|
||||
const { theme } = useUnistyles();
|
||||
const featureSelector: AgentControlSelector = `feature-${control.key}`;
|
||||
const featureSelector: AgentControlSelector = `feature-${feature.id}`;
|
||||
const featureAnchorRef = useRef<View>(null);
|
||||
|
||||
const handleFeatureOpenChange = useMemo(
|
||||
@@ -1315,117 +1307,120 @@ function DesktopFeatureItem({
|
||||
);
|
||||
|
||||
const handleTogglePress = useCallback(() => {
|
||||
if (control.type === "toggle") {
|
||||
onSetOption?.(control.key, !readToggleOption(control, options));
|
||||
if (feature.type === "toggle") {
|
||||
onSetFeature?.(feature.id, !feature.value);
|
||||
onActionComplete?.();
|
||||
}
|
||||
}, [control, onActionComplete, onSetOption, options]);
|
||||
}, [feature, onActionComplete, onSetFeature]);
|
||||
|
||||
const handleSelectOption = useCallback(
|
||||
(choiceValue: string) => {
|
||||
onSetOption?.(control.key, choiceValue);
|
||||
(optionId: string) => {
|
||||
onSetFeature?.(feature.id, optionId);
|
||||
},
|
||||
[control.key, onSetOption],
|
||||
[feature.id, onSetFeature],
|
||||
);
|
||||
const comboboxOptions = useMemo<ComboboxOption[]>(
|
||||
() =>
|
||||
control.type === "select"
|
||||
? control.choices.map((choice) => ({ id: choice.value, label: choice.label }))
|
||||
feature.type === "select"
|
||||
? feature.options.map((option) => ({ id: option.id, label: option.label }))
|
||||
: [],
|
||||
[control],
|
||||
[feature],
|
||||
);
|
||||
|
||||
const FeatureIcon = getAgentFeatureIcon(control.icon);
|
||||
const iconColor = getFeatureIconColor(
|
||||
control,
|
||||
options,
|
||||
theme.colors.palette,
|
||||
theme.colors.foregroundMuted,
|
||||
);
|
||||
|
||||
if (control.type === "toggle") {
|
||||
if (feature.type === "toggle") {
|
||||
const FeatureIcon = getAgentFeatureIcon(feature.icon);
|
||||
return (
|
||||
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
|
||||
<TooltipTrigger asChild triggerRefProp="ref">
|
||||
<AgentControlTrigger
|
||||
icon={FeatureIcon}
|
||||
iconColor={iconColor}
|
||||
iconColor={getFeatureIconColor(
|
||||
feature,
|
||||
theme.colors.palette,
|
||||
theme.colors.foregroundMuted,
|
||||
)}
|
||||
surface="toolbar"
|
||||
label={control.label}
|
||||
label={feature.label}
|
||||
showToolbarLabel={false}
|
||||
disabled={disabled}
|
||||
onPress={handleTogglePress}
|
||||
accessibilityLabel={getControlTooltip(control)}
|
||||
testID={`agent-feature-${control.key}`}
|
||||
accessibilityLabel={getFeatureTooltip(feature)}
|
||||
testID={`agent-feature-${feature.id}`}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center" offset={8}>
|
||||
<Text style={styles.tooltipText}>{getControlTooltip(control)}</Text>
|
||||
<Text style={styles.tooltipText}>{getFeatureTooltip(feature)}</Text>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
const selectedValue = readSelectOption(control, options);
|
||||
const selectedChoice = control.choices.find((choice) => choice.value === selectedValue);
|
||||
const iconOnly = control.desktopTrigger === "icon";
|
||||
const tooltip = iconOnly
|
||||
? `${control.label}: ${selectedChoice?.label ?? control.label}`
|
||||
: getControlTooltip(control);
|
||||
return (
|
||||
<>
|
||||
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
|
||||
<TooltipTrigger asChild triggerRefProp="ref">
|
||||
<AgentControlTrigger
|
||||
ref={featureAnchorRef}
|
||||
icon={FeatureIcon}
|
||||
iconColor={iconColor}
|
||||
surface="toolbar"
|
||||
label={control.label}
|
||||
value={selectedChoice?.label ?? control.label}
|
||||
showToolbarLabel={!iconOnly}
|
||||
open={openSelector === featureSelector}
|
||||
disabled={disabled}
|
||||
onPress={handleSelectPress}
|
||||
accessibilityLabel={tooltip}
|
||||
testID={`agent-feature-${control.key}`}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center" offset={8}>
|
||||
<Text style={styles.tooltipText}>{tooltip}</Text>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<Combobox
|
||||
options={comboboxOptions}
|
||||
value={String(selectedValue)}
|
||||
onSelect={handleSelectOption}
|
||||
open={openSelector === featureSelector}
|
||||
onOpenChange={handleFeatureOpenChange}
|
||||
anchorRef={featureAnchorRef}
|
||||
desktopPlacement="top-start"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
if (feature.type === "select") {
|
||||
const FeatureIcon = getAgentFeatureIcon(feature.icon);
|
||||
const selectedOption = feature.options.find((o) => o.id === feature.value);
|
||||
const iconOnly = feature.desktopTrigger === "icon";
|
||||
const tooltip = iconOnly
|
||||
? `${feature.label}: ${selectedOption?.label ?? feature.label}`
|
||||
: getFeatureTooltip(feature);
|
||||
return (
|
||||
<>
|
||||
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
|
||||
<TooltipTrigger asChild triggerRefProp="ref">
|
||||
<AgentControlTrigger
|
||||
ref={featureAnchorRef}
|
||||
icon={FeatureIcon}
|
||||
iconColor={getFeatureIconColor(
|
||||
feature,
|
||||
theme.colors.palette,
|
||||
theme.colors.foregroundMuted,
|
||||
)}
|
||||
surface="toolbar"
|
||||
label={feature.label}
|
||||
value={selectedOption?.label ?? feature.label}
|
||||
showToolbarLabel={!iconOnly}
|
||||
open={openSelector === featureSelector}
|
||||
disabled={disabled}
|
||||
onPress={handleSelectPress}
|
||||
accessibilityLabel={tooltip}
|
||||
testID={`agent-feature-${feature.id}`}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center" offset={8}>
|
||||
<Text style={styles.tooltipText}>{tooltip}</Text>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<Combobox
|
||||
options={comboboxOptions}
|
||||
value={String(feature.value)}
|
||||
onSelect={handleSelectOption}
|
||||
open={openSelector === featureSelector}
|
||||
onOpenChange={handleFeatureOpenChange}
|
||||
anchorRef={featureAnchorRef}
|
||||
desktopPlacement="top-start"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function SheetFeatureItem({
|
||||
control,
|
||||
options,
|
||||
feature,
|
||||
disabled,
|
||||
openSelector,
|
||||
handleOpenChange,
|
||||
onSetOption,
|
||||
onSetFeature,
|
||||
}: {
|
||||
control: AgentOptionControl;
|
||||
options: ProviderOptions;
|
||||
feature: AgentFeature;
|
||||
disabled: boolean;
|
||||
openSelector: AgentControlSelector | null;
|
||||
handleOpenChange: (selector: AgentControlSelector) => (nextOpen: boolean) => void;
|
||||
onSetOption?: (key: string, value: unknown) => void;
|
||||
onSetFeature?: (featureId: string, value: unknown) => void;
|
||||
}) {
|
||||
const { theme } = useUnistyles();
|
||||
const { t } = useTranslation();
|
||||
const featureSelector: AgentControlSelector = `feature-${control.key}`;
|
||||
const featureSelector: AgentControlSelector = `feature-${feature.id}`;
|
||||
const featureAnchorRef = useRef<View>(null);
|
||||
|
||||
const handleFeatureOpenChange = useMemo(
|
||||
@@ -1436,71 +1431,97 @@ function SheetFeatureItem({
|
||||
() => handleFeatureOpenChange(openSelector !== featureSelector),
|
||||
[featureSelector, handleFeatureOpenChange, openSelector],
|
||||
);
|
||||
const sheetHeader = useMemo<SheetHeader>(() => ({ title: control.label }), [control.label]);
|
||||
const sheetHeader = useMemo<SheetHeader>(() => ({ title: feature.label }), [feature.label]);
|
||||
|
||||
const handleSelectOption = useCallback(
|
||||
(choiceValue: string) => {
|
||||
onSetOption?.(control.key, control.type === "toggle" ? choiceValue === "true" : choiceValue);
|
||||
(optionId: string) => {
|
||||
onSetFeature?.(feature.id, feature.type === "toggle" ? optionId === "true" : optionId);
|
||||
},
|
||||
[control.key, control.type, onSetOption],
|
||||
[feature.id, feature.type, onSetFeature],
|
||||
);
|
||||
const comboboxOptions = useMemo<ComboboxOption[]>(() => {
|
||||
if (control.type === "select") {
|
||||
return control.choices.map((choice) => ({ id: choice.value, label: choice.label }));
|
||||
if (feature.type === "select") {
|
||||
return feature.options.map((option) => ({ id: option.id, label: option.label }));
|
||||
}
|
||||
return [
|
||||
{ id: "true", label: t("agentControls.features.on") },
|
||||
{ id: "false", label: t("agentControls.features.off") },
|
||||
];
|
||||
}, [control, t]);
|
||||
}, [feature, t]);
|
||||
|
||||
const FeatureIcon = getAgentFeatureIcon(control.icon);
|
||||
const iconColor = getFeatureIconColor(
|
||||
control,
|
||||
options,
|
||||
theme.colors.palette,
|
||||
theme.colors.foregroundMuted,
|
||||
);
|
||||
let selectedValue: string;
|
||||
let displayValue: string;
|
||||
if (control.type === "toggle") {
|
||||
const isOn = readToggleOption(control, options);
|
||||
selectedValue = String(isOn);
|
||||
displayValue = isOn ? t("agentControls.features.on") : t("agentControls.features.off");
|
||||
} else {
|
||||
const selected = readSelectOption(control, options);
|
||||
selectedValue = String(selected);
|
||||
displayValue =
|
||||
control.choices.find((choice) => choice.value === selected)?.label ?? control.label;
|
||||
if (feature.type === "toggle") {
|
||||
const FeatureIcon = getAgentFeatureIcon(feature.icon);
|
||||
return (
|
||||
<>
|
||||
<AgentControlTrigger
|
||||
ref={featureAnchorRef}
|
||||
icon={FeatureIcon}
|
||||
iconColor={getFeatureIconColor(
|
||||
feature,
|
||||
theme.colors.palette,
|
||||
theme.colors.foregroundMuted,
|
||||
)}
|
||||
surface="sheet"
|
||||
label={feature.label}
|
||||
value={feature.value ? t("agentControls.features.on") : t("agentControls.features.off")}
|
||||
open={openSelector === featureSelector}
|
||||
disabled={disabled}
|
||||
onPress={handleSelectPress}
|
||||
accessibilityLabel={getFeatureTooltip(feature)}
|
||||
testID={`agent-feature-${feature.id}`}
|
||||
/>
|
||||
<Combobox
|
||||
options={comboboxOptions}
|
||||
value={String(feature.value)}
|
||||
onSelect={handleSelectOption}
|
||||
open={openSelector === featureSelector}
|
||||
onOpenChange={handleFeatureOpenChange}
|
||||
anchorRef={featureAnchorRef}
|
||||
presentation="push"
|
||||
searchable={false}
|
||||
header={sheetHeader}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<AgentControlTrigger
|
||||
ref={featureAnchorRef}
|
||||
icon={FeatureIcon}
|
||||
iconColor={iconColor}
|
||||
surface="sheet"
|
||||
label={control.label}
|
||||
value={displayValue}
|
||||
open={openSelector === featureSelector}
|
||||
disabled={disabled}
|
||||
onPress={handleSelectPress}
|
||||
accessibilityLabel={getControlTooltip(control)}
|
||||
testID={`agent-feature-${control.key}`}
|
||||
/>
|
||||
<Combobox
|
||||
options={comboboxOptions}
|
||||
value={selectedValue}
|
||||
onSelect={handleSelectOption}
|
||||
open={openSelector === featureSelector}
|
||||
onOpenChange={handleFeatureOpenChange}
|
||||
anchorRef={featureAnchorRef}
|
||||
presentation="push"
|
||||
searchable={control.type === "toggle" ? false : undefined}
|
||||
header={sheetHeader}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
if (feature.type === "select") {
|
||||
const FeatureIcon = getAgentFeatureIcon(feature.icon);
|
||||
const selectedOption = feature.options.find((o) => o.id === feature.value);
|
||||
return (
|
||||
<>
|
||||
<AgentControlTrigger
|
||||
ref={featureAnchorRef}
|
||||
icon={FeatureIcon}
|
||||
iconColor={getFeatureIconColor(
|
||||
feature,
|
||||
theme.colors.palette,
|
||||
theme.colors.foregroundMuted,
|
||||
)}
|
||||
surface="sheet"
|
||||
label={feature.label}
|
||||
value={selectedOption?.label ?? feature.label}
|
||||
open={openSelector === featureSelector}
|
||||
disabled={disabled}
|
||||
onPress={handleSelectPress}
|
||||
accessibilityLabel={getFeatureTooltip(feature)}
|
||||
testID={`agent-feature-${feature.id}`}
|
||||
/>
|
||||
<Combobox
|
||||
options={comboboxOptions}
|
||||
value={String(feature.value)}
|
||||
onSelect={handleSelectOption}
|
||||
open={openSelector === featureSelector}
|
||||
onOpenChange={handleFeatureOpenChange}
|
||||
anchorRef={featureAnchorRef}
|
||||
presentation="push"
|
||||
header={sheetHeader}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function ThinkingComboboxOption({
|
||||
@@ -1528,18 +1549,6 @@ function ThinkingComboboxOption({
|
||||
);
|
||||
}
|
||||
|
||||
function useAgentOptionControls(
|
||||
agent: { controls?: AgentOptionControl[]; options?: ProviderOptions } | null | undefined,
|
||||
onSetOption: ComposerOptionControls["onSetOption"],
|
||||
): ComposerOptionControls {
|
||||
const controls = agent?.controls;
|
||||
const options = agent?.options;
|
||||
return useMemo(
|
||||
() => ({ controls: controls ?? [], options: options ?? EMPTY_OPTIONS, onSetOption }),
|
||||
[controls, onSetOption, options],
|
||||
);
|
||||
}
|
||||
|
||||
export const AgentControls = memo(function AgentControls({
|
||||
agentId,
|
||||
serverId,
|
||||
@@ -1691,8 +1700,8 @@ export const AgentControls = memo(function AgentControls({
|
||||
[activeModelId, agentId, agentProvider, client, toast, updatePreferences],
|
||||
);
|
||||
|
||||
const handleSetOption = useCallback(
|
||||
(key: string, value: unknown) => {
|
||||
const handleSetFeature = useCallback(
|
||||
(featureId: string, value: unknown) => {
|
||||
if (!client || !agentProvider) {
|
||||
return;
|
||||
}
|
||||
@@ -1701,24 +1710,22 @@ export const AgentControls = memo(function AgentControls({
|
||||
preferences: current,
|
||||
provider: agentProvider,
|
||||
updates: {
|
||||
options: {
|
||||
[key]: value,
|
||||
featureValues: {
|
||||
[featureId]: value,
|
||||
},
|
||||
},
|
||||
}),
|
||||
).catch((error) => {
|
||||
console.warn("[AgentControls] persist option preference failed", error);
|
||||
console.warn("[AgentControls] persist feature preference failed", error);
|
||||
});
|
||||
void client.setAgentOptions(agentId, { [key]: value }).catch((error) => {
|
||||
console.warn("[AgentControls] setAgentOptions failed", error);
|
||||
void client.setAgentFeature(agentId, featureId, value).catch((error) => {
|
||||
console.warn("[AgentControls] setAgentFeature failed", error);
|
||||
toast.error(toErrorMessage(error));
|
||||
});
|
||||
},
|
||||
[agentId, agentProvider, client, toast, updatePreferences],
|
||||
);
|
||||
|
||||
const agentOptionControls = useAgentOptionControls(agent, handleSetOption);
|
||||
|
||||
const commandCenterControls = useMemo<AgentControlCommandCenterSource>(
|
||||
() => ({
|
||||
serverId,
|
||||
@@ -1737,18 +1744,21 @@ export const AgentControls = memo(function AgentControls({
|
||||
select: handleSelectThinkingOption,
|
||||
},
|
||||
modes: commandCenterModes,
|
||||
optionControls: client ? agentOptionControls : null,
|
||||
features: {
|
||||
list: agent?.features,
|
||||
set: handleSetFeature,
|
||||
},
|
||||
}),
|
||||
[
|
||||
activeModelId,
|
||||
agentOptionControls,
|
||||
client,
|
||||
agent?.features,
|
||||
agentId,
|
||||
agentModelSelectorProviders,
|
||||
agentProvider,
|
||||
commandCenterModes,
|
||||
handleSelectCommandCenterModel,
|
||||
handleSelectThinkingOption,
|
||||
handleSetFeature,
|
||||
modeProviderDefinitions,
|
||||
modelSelection.selectedThinkingId,
|
||||
modelSelection.thinkingOptions,
|
||||
@@ -1797,7 +1807,8 @@ export const AgentControls = memo(function AgentControls({
|
||||
thinkingOptions={thinkingOptions.length > 0 ? thinkingOptions : undefined}
|
||||
selectedThinkingOptionId={modelSelection.selectedThinkingId ?? undefined}
|
||||
onSelectThinkingOption={handleSelectThinkingOption}
|
||||
optionControls={agentOptionControls}
|
||||
features={agent.features}
|
||||
onSetFeature={handleSetFeature}
|
||||
isModelLoading={snapshotIsLoading || selectedProviderIsLoading}
|
||||
onModelSelectorOpen={handleModelSelectorOpen}
|
||||
onRetryModelProvider={handleRetryModelProvider}
|
||||
@@ -1829,7 +1840,8 @@ export function DraftAgentControls({
|
||||
selectedThinkingOptionId,
|
||||
onSelectThinkingOption,
|
||||
onApplyAgentProfile,
|
||||
optionControls,
|
||||
features,
|
||||
onSetFeature,
|
||||
onDropdownClose,
|
||||
onModelSelectorOpen,
|
||||
onRetryModelProvider,
|
||||
@@ -1915,7 +1927,8 @@ export function DraftAgentControls({
|
||||
thinkingOptions={mappedThinkingOptions.length > 0 ? mappedThinkingOptions : undefined}
|
||||
selectedThinkingOptionId={effectiveSelectedThinkingOption}
|
||||
onSelectThinkingOption={onSelectThinkingOption}
|
||||
optionControls={optionControls}
|
||||
features={features}
|
||||
onSetFeature={onSetFeature}
|
||||
onDropdownClose={onDropdownClose}
|
||||
onModelSelectorOpen={onModelSelectorOpen}
|
||||
onRetryModelProvider={onRetryModelProvider}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
getFeatureHighlightColor,
|
||||
getFeatureTooltip,
|
||||
getAgentControlHintKey,
|
||||
isFeatureActive,
|
||||
normalizeModelId,
|
||||
resolveAgentModelSelection,
|
||||
} from "./utils";
|
||||
@@ -15,12 +17,51 @@ describe("getAgentControlHintKey", () => {
|
||||
});
|
||||
|
||||
describe("feature metadata helpers", () => {
|
||||
it("prefers explicit feature tooltip copy", () => {
|
||||
expect(
|
||||
getFeatureTooltip({
|
||||
label: "Plan",
|
||||
tooltip: "Toggle plan mode",
|
||||
}),
|
||||
).toBe("Toggle plan mode");
|
||||
});
|
||||
|
||||
it("falls back to the feature label when no tooltip is provided", () => {
|
||||
expect(
|
||||
getFeatureTooltip({
|
||||
label: "Custom",
|
||||
}),
|
||||
).toBe("Custom");
|
||||
});
|
||||
|
||||
it("maps feature highlight colors by feature id", () => {
|
||||
expect(getFeatureHighlightColor("fast_mode")).toBe("yellow");
|
||||
expect(getFeatureHighlightColor("service_tier")).toBe("yellow");
|
||||
expect(getFeatureHighlightColor("plan_mode")).toBe("blue");
|
||||
expect(getFeatureHighlightColor("other")).toBe("default");
|
||||
});
|
||||
|
||||
it("treats a select feature as active when a non-default option is selected", () => {
|
||||
const speed = {
|
||||
type: "select" as const,
|
||||
id: "service_tier",
|
||||
label: "Speed",
|
||||
options: [
|
||||
{ id: "default", label: "Normal", isDefault: true },
|
||||
{ id: "fast", label: "Fast" },
|
||||
],
|
||||
};
|
||||
expect(isFeatureActive({ ...speed, value: "default" })).toBe(false);
|
||||
expect(isFeatureActive({ ...speed, value: "fast" })).toBe(true);
|
||||
expect(
|
||||
isFeatureActive({
|
||||
type: "toggle",
|
||||
id: "fast_mode",
|
||||
label: "Fast",
|
||||
value: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeModelId", () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AgentModelDefinition } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentFeature, AgentModelDefinition } from "@getpaseo/protocol/agent-types";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { formatThinkingOptionLabel } from "@/agent-controls/labels";
|
||||
import {
|
||||
@@ -35,6 +35,16 @@ export function normalizeModelId(modelId: string | null | undefined): string | n
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function getFeatureTooltip(feature: Pick<AgentFeature, "label" | "tooltip">): string {
|
||||
return feature.tooltip ?? feature.label;
|
||||
}
|
||||
|
||||
export function isFeatureActive(feature: AgentFeature): boolean {
|
||||
if (feature.type === "toggle") return feature.value;
|
||||
const selectedOption = feature.options.find((option) => option.id === feature.value);
|
||||
return selectedOption !== undefined && !selectedOption.isDefault;
|
||||
}
|
||||
|
||||
export function getFeatureHighlightColor(featureId: string): FeatureHighlightColor {
|
||||
switch (featureId) {
|
||||
case FAST_MODE_FEATURE_ID:
|
||||
|
||||
@@ -20,11 +20,12 @@ export function resolveDraftKey(input: {
|
||||
|
||||
export function buildDraftAgentControls(input: {
|
||||
formState: UseAgentFormStateResult;
|
||||
optionControls?: DraftAgentControlsProps["optionControls"];
|
||||
features?: DraftAgentControlsProps["features"];
|
||||
onSetFeature?: DraftAgentControlsProps["onSetFeature"];
|
||||
onApplyAgentProfile: DraftAgentControlsProps["onApplyAgentProfile"];
|
||||
onDropdownClose?: DraftAgentControlsProps["onDropdownClose"];
|
||||
}): DraftAgentControlsProps {
|
||||
const { formState, optionControls, onApplyAgentProfile, onDropdownClose } = input;
|
||||
const { formState, features, onSetFeature, onApplyAgentProfile, onDropdownClose } = input;
|
||||
return {
|
||||
providerDefinitions: formState.providerDefinitions,
|
||||
selectedProvider: formState.selectedProvider,
|
||||
@@ -42,7 +43,8 @@ export function buildDraftAgentControls(input: {
|
||||
selectedThinkingOptionId: formState.selectedThinkingOptionId,
|
||||
onSelectThinkingOption: formState.setThinkingOptionFromUser,
|
||||
onApplyAgentProfile,
|
||||
optionControls,
|
||||
features,
|
||||
onSetFeature,
|
||||
onDropdownClose,
|
||||
onModelSelectorOpen: formState.refetchProviderModelsIfStale,
|
||||
onRetryModelProvider: formState.refreshProviderModels,
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
type CreateAgentInitialValues,
|
||||
type UseAgentFormStateResult,
|
||||
} from "@/hooks/use-agent-form-state";
|
||||
import { useDraftProviderOptions } from "@/hooks/use-draft-provider-options";
|
||||
import { useDraftAgentFeatures } from "@/hooks/use-draft-agent-features";
|
||||
import {
|
||||
buildDraftAgentControls,
|
||||
hasDraftContent,
|
||||
@@ -35,7 +35,7 @@ type AttachmentUpdater =
|
||||
interface AgentInputDraftComposerOptions {
|
||||
initialServerId: string | null;
|
||||
initialValues?: CreateAgentInitialValues;
|
||||
initialProviderOptions?: Record<string, unknown>;
|
||||
initialFeatureValues?: Record<string, unknown>;
|
||||
isVisible?: boolean;
|
||||
lockedWorkingDir?: string;
|
||||
}
|
||||
@@ -50,7 +50,7 @@ type DraftComposerState = UseAgentFormStateResult & {
|
||||
effectiveModeId: string;
|
||||
effectiveModelId: string;
|
||||
effectiveThinkingOptionId: string;
|
||||
providerOptions: Record<string, unknown> | undefined;
|
||||
featureValues: Record<string, unknown> | undefined;
|
||||
agentControls: DraftAgentControlsProps;
|
||||
commandDraft: DraftCommandTarget;
|
||||
};
|
||||
@@ -274,25 +274,26 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
);
|
||||
|
||||
const {
|
||||
optionControls: draftOptionControls,
|
||||
options: draftOptions,
|
||||
applyProfile: applyProfileOptions,
|
||||
} = useDraftProviderOptions({
|
||||
features: draftFeatures,
|
||||
featureValues: draftFeatureValues,
|
||||
setFeatureValue: setDraftFeatureValue,
|
||||
applyProfileFeatureValues,
|
||||
} = useDraftAgentFeatures({
|
||||
serverId: formState.selectedServerId,
|
||||
provider: formState.selectedProvider,
|
||||
cwd: workingDir,
|
||||
modeId: formState.selectedMode,
|
||||
modelId: effectiveModelId,
|
||||
thinkingOptionId: effectiveThinkingOptionId,
|
||||
initialOptions: composerOptions?.initialProviderOptions,
|
||||
initialFeatureValues: composerOptions?.initialFeatureValues,
|
||||
});
|
||||
|
||||
const applyDraftAgentProfile = useCallback(
|
||||
(profile: Parameters<typeof formState.applyProfileFromUser>[0]) => {
|
||||
formState.applyProfileFromUser(profile);
|
||||
applyProfileOptions({ provider: profile.provider, options: profile.options });
|
||||
applyProfileFeatureValues(profile.featureValues);
|
||||
},
|
||||
[applyProfileOptions, formState],
|
||||
[applyProfileFeatureValues, formState],
|
||||
);
|
||||
|
||||
const commandDraft = useMemo(
|
||||
@@ -302,9 +303,15 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
cwd: workingDir,
|
||||
effectiveModelId,
|
||||
effectiveThinkingOptionId,
|
||||
providerOptions: draftOptions,
|
||||
featureValues: draftFeatureValues,
|
||||
}),
|
||||
[effectiveModelId, effectiveThinkingOptionId, draftOptions, providerSelection, workingDir],
|
||||
[
|
||||
effectiveModelId,
|
||||
effectiveThinkingOptionId,
|
||||
draftFeatureValues,
|
||||
providerSelection,
|
||||
workingDir,
|
||||
],
|
||||
);
|
||||
|
||||
const composerState = useMemo<DraftComposerState | null>(() => {
|
||||
@@ -318,10 +325,11 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
effectiveModeId,
|
||||
effectiveModelId,
|
||||
effectiveThinkingOptionId,
|
||||
providerOptions: draftOptions,
|
||||
featureValues: draftFeatureValues,
|
||||
agentControls: buildDraftAgentControls({
|
||||
formState,
|
||||
optionControls: draftOptionControls,
|
||||
features: draftFeatures,
|
||||
onSetFeature: setDraftFeatureValue,
|
||||
onApplyAgentProfile: applyDraftAgentProfile,
|
||||
}),
|
||||
commandDraft,
|
||||
@@ -332,10 +340,11 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
effectiveModeId,
|
||||
effectiveModelId,
|
||||
effectiveThinkingOptionId,
|
||||
draftOptionControls,
|
||||
draftOptions,
|
||||
draftFeatures,
|
||||
draftFeatureValues,
|
||||
applyDraftAgentProfile,
|
||||
formState,
|
||||
setDraftFeatureValue,
|
||||
workingDir,
|
||||
]);
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { ComposerOptionControls } from "@/agent-controls/option-controls";
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import { Keyboard, ScrollView, StyleSheet as RNStyleSheet, Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -66,7 +65,7 @@ interface AutoSubmitConfig {
|
||||
modeId: string | null;
|
||||
model: string | null;
|
||||
thinkingOptionId: string | null;
|
||||
providerOptions: Record<string, unknown>;
|
||||
featureValues: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function resolveAutoSubmitConfig(
|
||||
@@ -75,7 +74,7 @@ function resolveAutoSubmitConfig(
|
||||
modeId?: string | null;
|
||||
model?: string | null;
|
||||
thinkingOptionId?: string | null;
|
||||
providerOptions?: Record<string, unknown>;
|
||||
featureValues?: Record<string, unknown>;
|
||||
} | null,
|
||||
): AutoSubmitConfig | null {
|
||||
if (!pending) return null;
|
||||
@@ -84,7 +83,7 @@ function resolveAutoSubmitConfig(
|
||||
modeId: pending.modeId ?? null,
|
||||
model: pending.model ?? null,
|
||||
thinkingOptionId: pending.thinkingOptionId ?? null,
|
||||
providerOptions: pending.providerOptions ?? {},
|
||||
featureValues: pending.featureValues ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -132,7 +131,7 @@ async function submitDraftCreateRequest(input: {
|
||||
effectiveModeId: string;
|
||||
effectiveModelId: string | null;
|
||||
effectiveThinkingOptionId: string | null;
|
||||
providerOptions: Record<string, unknown> | undefined;
|
||||
featureValues: Record<string, unknown> | undefined;
|
||||
};
|
||||
hostDisconnectedMessage: string;
|
||||
selectModelMessage: string;
|
||||
@@ -171,7 +170,7 @@ async function submitDraftCreateRequest(input: {
|
||||
model: autoSubmitConfig?.model ?? (composerState.effectiveModelId || undefined),
|
||||
thinkingOptionId:
|
||||
autoSubmitConfig?.thinkingOptionId ?? (composerState.effectiveThinkingOptionId || undefined),
|
||||
providerOptions: autoSubmitConfig?.providerOptions ?? composerState.providerOptions,
|
||||
featureValues: autoSubmitConfig?.featureValues ?? composerState.featureValues,
|
||||
});
|
||||
|
||||
const attachmentsArray = Array.isArray(attachments) ? attachments : undefined;
|
||||
@@ -205,7 +204,7 @@ function buildDraftAgentSnapshot(input: {
|
||||
effectiveThinkingOptionId: string | null;
|
||||
effectiveModeId: string;
|
||||
selectedProvider: string | null;
|
||||
agentControls: { optionControls?: ComposerOptionControls };
|
||||
agentControls: { features?: Agent["features"] };
|
||||
};
|
||||
selectModelMessage: string;
|
||||
}): Agent {
|
||||
@@ -242,8 +241,7 @@ function buildDraftAgentSnapshot(input: {
|
||||
title: "Agent",
|
||||
cwd: workspaceDirectory,
|
||||
model,
|
||||
options: composerState.agentControls.optionControls?.options,
|
||||
controls: composerState.agentControls.optionControls?.controls,
|
||||
features: composerState.agentControls.features,
|
||||
thinkingOptionId,
|
||||
parentAgentId: null,
|
||||
labels: {},
|
||||
@@ -335,7 +333,7 @@ export function WorkspaceDraftAgentTab({
|
||||
composer: {
|
||||
initialServerId: serverId,
|
||||
initialValues: draftInitialValues,
|
||||
initialProviderOptions: draftSetup?.providerOptions,
|
||||
initialFeatureValues: draftSetup?.featureValues,
|
||||
isVisible: true,
|
||||
lockedWorkingDir: draftWorkingDirectory ?? undefined,
|
||||
},
|
||||
@@ -353,7 +351,8 @@ export function WorkspaceDraftAgentTab({
|
||||
const draftModeOptions = composerState.modeOptions;
|
||||
const draftSelectedMode = composerState.selectedMode;
|
||||
const draftSetMode = composerState.setModeFromUser;
|
||||
const draftOptionControls = composerState.agentControls.optionControls;
|
||||
const draftFeatures = composerState.agentControls.features;
|
||||
const draftOnSetFeature = composerState.agentControls.onSetFeature;
|
||||
|
||||
const clearDraftInput = draftInput.clear;
|
||||
const replaceDraftText = draftInput.replaceText;
|
||||
@@ -522,7 +521,10 @@ export function WorkspaceDraftAgentTab({
|
||||
selectedId: draftSelectedMode,
|
||||
select: draftSetMode,
|
||||
},
|
||||
optionControls: draftOptionControls ?? null,
|
||||
features: {
|
||||
list: draftFeatures,
|
||||
set: draftOnSetFeature,
|
||||
},
|
||||
},
|
||||
});
|
||||
const isReadyForPendingAutoSubmit = Boolean(
|
||||
|
||||
@@ -80,7 +80,7 @@ describe("create agent preferences", () => {
|
||||
modelId: "gpt-5.5",
|
||||
modeId: "full-access",
|
||||
thinkingOptionId: "high",
|
||||
options: { fast_mode: true },
|
||||
featureValues: { fast_mode: true },
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -95,7 +95,7 @@ describe("create agent preferences", () => {
|
||||
model: "gpt-5.5",
|
||||
mode: "full-access",
|
||||
thinkingByModel: { "gpt-5.5": "high" },
|
||||
options: { fast_mode: true },
|
||||
featureValues: { fast_mode: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -119,7 +119,7 @@ describe("create agent preferences", () => {
|
||||
model: "gpt-5.6",
|
||||
mode: undefined,
|
||||
thinkingByModel: undefined,
|
||||
options: undefined,
|
||||
featureValues: undefined,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
@@ -167,13 +167,13 @@ describe("create agent preferences", () => {
|
||||
modelId: "one-minute-stream",
|
||||
modeId: "approval-test",
|
||||
thinkingOptionId: "",
|
||||
options: {},
|
||||
featureValues: {},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: "mock",
|
||||
providerPreferences: {
|
||||
pi: { model: "anthropic/sonnet" },
|
||||
mock: { model: "one-minute-stream", mode: "approval-test", options: {} },
|
||||
mock: { model: "one-minute-stream", mode: "approval-test", featureValues: {} },
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -208,29 +208,6 @@ describe("create agent preferences", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reads preferences saved as featureValues as options", () => {
|
||||
expect(
|
||||
parseFormPreferences({
|
||||
provider: "codex",
|
||||
providerPreferences: { codex: { featureValues: { service_tier: "priority" } } },
|
||||
}),
|
||||
).toEqual({
|
||||
provider: "codex",
|
||||
providerPreferences: { codex: { options: { service_tier: "priority" } } },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps options that are not booleans or strings, such as a profile's sandbox settings", () => {
|
||||
const options = {
|
||||
sandbox_workspace_write: { network_access: true, writable_roots: ["/tmp"] },
|
||||
max_turns: 3,
|
||||
};
|
||||
|
||||
expect(
|
||||
parseFormPreferences({ provider: "codex", providerPreferences: { codex: { options } } }),
|
||||
).toEqual({ provider: "codex", providerPreferences: { codex: { options } } });
|
||||
});
|
||||
|
||||
it("rejects unknown persisted fields outside the explicit legacy shape", () => {
|
||||
expect(parseFormPreferences({ provider: "codex", surprise: true })).toEqual({});
|
||||
});
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { z } from "zod";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
|
||||
const optionsSchema = z.record(z.string(), z.json());
|
||||
const featureValuesSchema = z.record(z.string(), z.union([z.boolean(), z.string(), z.null()]));
|
||||
|
||||
export interface ProviderPreferences {
|
||||
model?: string;
|
||||
mode?: string;
|
||||
thinkingByModel?: Record<string, string>;
|
||||
/** Last-used values of the provider's option controls, by option key. */
|
||||
options?: Record<string, unknown>;
|
||||
featureValues?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export type LaunchTarget = { kind: "chat" } | { kind: "terminal"; profileId: string };
|
||||
@@ -21,23 +20,12 @@ export interface FormPreferences {
|
||||
launchTarget?: LaunchTarget;
|
||||
}
|
||||
|
||||
// COMPAT(providerOptionControls): added in v0.15.0, remove after 2027-05-01. Preferences written
|
||||
// before the rename stored the same record as `featureValues`.
|
||||
function renameLegacyFeatureValues(value: unknown): unknown {
|
||||
if (typeof value !== "object" || value === null || !("featureValues" in value)) return value;
|
||||
const { featureValues, ...rest } = value as { featureValues: unknown } & Record<string, unknown>;
|
||||
return "options" in rest ? rest : { ...rest, options: featureValues };
|
||||
}
|
||||
|
||||
const providerPreferencesSchema: z.ZodType<ProviderPreferences> = z.preprocess(
|
||||
renameLegacyFeatureValues,
|
||||
z.strictObject({
|
||||
model: z.string().optional(),
|
||||
mode: z.string().optional(),
|
||||
thinkingByModel: z.record(z.string(), z.string()).optional(),
|
||||
options: optionsSchema.optional(),
|
||||
}),
|
||||
);
|
||||
const providerPreferencesSchema: z.ZodType<ProviderPreferences> = z.strictObject({
|
||||
model: z.string().optional(),
|
||||
mode: z.string().optional(),
|
||||
thinkingByModel: z.record(z.string(), z.string()).optional(),
|
||||
featureValues: featureValuesSchema.optional(),
|
||||
});
|
||||
|
||||
const launchTargetSchema: z.ZodType<LaunchTarget> = z.discriminatedUnion("kind", [
|
||||
z.strictObject({ kind: z.literal("chat") }),
|
||||
@@ -128,7 +116,7 @@ function applyProviderPreferenceUpdates(
|
||||
): ProviderPreferences {
|
||||
const next: ProviderPreferences = { ...existing };
|
||||
const nextThinkingByModel = mergeDefinedRecord(existing.thinkingByModel, updates.thinkingByModel);
|
||||
const nextOptions = mergeDefinedRecord(existing.options, updates.options);
|
||||
const nextFeatureValues = mergeDefinedRecord(existing.featureValues, updates.featureValues);
|
||||
|
||||
if (updates.model !== undefined) {
|
||||
next.model = updates.model;
|
||||
@@ -141,8 +129,8 @@ function applyProviderPreferenceUpdates(
|
||||
if (nextThinkingByModel !== undefined) {
|
||||
next.thinkingByModel = nextThinkingByModel;
|
||||
}
|
||||
if (nextOptions !== undefined) {
|
||||
next.options = nextOptions;
|
||||
if (nextFeatureValues !== undefined) {
|
||||
next.featureValues = nextFeatureValues;
|
||||
}
|
||||
|
||||
return next;
|
||||
@@ -173,7 +161,7 @@ export function mergeCreateAgentSelectionPreferences(args: {
|
||||
modelId?: string | null;
|
||||
modeId?: string | null;
|
||||
thinkingOptionId?: string | null;
|
||||
options?: Record<string, unknown>;
|
||||
featureValues?: Record<string, unknown>;
|
||||
}): FormPreferences {
|
||||
if (!args.provider) {
|
||||
return args.preferences;
|
||||
@@ -182,7 +170,7 @@ export function mergeCreateAgentSelectionPreferences(args: {
|
||||
const modelId = args.modelId?.trim() ?? "";
|
||||
const modeId = args.modeId?.trim() ?? "";
|
||||
const thinkingOptionId = args.thinkingOptionId?.trim() ?? "";
|
||||
const options = optionsSchema.safeParse(args.options);
|
||||
const featureValues = featureValuesSchema.safeParse(args.featureValues);
|
||||
|
||||
return mergeProviderPreferences({
|
||||
preferences: args.preferences,
|
||||
@@ -191,7 +179,7 @@ export function mergeCreateAgentSelectionPreferences(args: {
|
||||
model: modelId || undefined,
|
||||
mode: args.modeId === undefined ? undefined : modeId || null,
|
||||
...(modelId && thinkingOptionId ? { thinkingByModel: { [modelId]: thinkingOptionId } } : {}),
|
||||
...(options.success ? { options: options.data } : {}),
|
||||
...(featureValues.success ? { featureValues: featureValues.data } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -204,7 +192,7 @@ export function applyAgentProfilePreferences(args: {
|
||||
modelId: string;
|
||||
modeId: string;
|
||||
thinkingOptionId: string;
|
||||
options: Record<string, unknown>;
|
||||
featureValues: Record<string, unknown>;
|
||||
}): FormPreferences {
|
||||
let next = args.preferences;
|
||||
if (args.previousProvider) {
|
||||
@@ -227,7 +215,7 @@ export function applyAgentProfilePreferences(args: {
|
||||
...(args.modelId && args.thinkingOptionId
|
||||
? { thinkingByModel: { [args.modelId]: args.thinkingOptionId } }
|
||||
: {}),
|
||||
options: args.options,
|
||||
featureValues: args.featureValues,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveFeatureValues } from "./feature-preferences";
|
||||
|
||||
describe("feature-preferences", () => {
|
||||
const features = [
|
||||
{
|
||||
type: "toggle" as const,
|
||||
id: "fast_mode",
|
||||
label: "Fast",
|
||||
value: false,
|
||||
},
|
||||
{
|
||||
type: "toggle" as const,
|
||||
id: "plan_mode",
|
||||
label: "Plan",
|
||||
value: false,
|
||||
},
|
||||
];
|
||||
|
||||
it("restores persisted values for available features", () => {
|
||||
expect(
|
||||
resolveFeatureValues({
|
||||
features,
|
||||
persistedFeatureValues: {
|
||||
fast_mode: true,
|
||||
unknown_feature: true,
|
||||
},
|
||||
localFeatureValues: {},
|
||||
}),
|
||||
).toEqual({
|
||||
fast_mode: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers local values over persisted values", () => {
|
||||
expect(
|
||||
resolveFeatureValues({
|
||||
features,
|
||||
persistedFeatureValues: {
|
||||
fast_mode: true,
|
||||
plan_mode: false,
|
||||
},
|
||||
localFeatureValues: {
|
||||
fast_mode: false,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
fast_mode: false,
|
||||
plan_mode: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { AgentFeature } from "@getpaseo/protocol/agent-types";
|
||||
|
||||
export function pruneFeatureValues(
|
||||
featureValues: Record<string, unknown>,
|
||||
features: AgentFeature[],
|
||||
): Record<string, unknown> {
|
||||
const allowedFeatureIds = new Set(features.map((feature) => feature.id));
|
||||
let changed = false;
|
||||
const next: Record<string, unknown> = {};
|
||||
|
||||
for (const [featureId, value] of Object.entries(featureValues)) {
|
||||
if (!allowedFeatureIds.has(featureId)) {
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
next[featureId] = value;
|
||||
}
|
||||
|
||||
return changed ? next : featureValues;
|
||||
}
|
||||
|
||||
export function applyFeatureValues(
|
||||
features: AgentFeature[],
|
||||
featureValues: Record<string, unknown>,
|
||||
): AgentFeature[] {
|
||||
if (Object.keys(featureValues).length === 0) {
|
||||
return features;
|
||||
}
|
||||
|
||||
return features.map((feature) => {
|
||||
if (!Object.prototype.hasOwnProperty.call(featureValues, feature.id)) {
|
||||
return feature;
|
||||
}
|
||||
|
||||
return {
|
||||
...feature,
|
||||
value: featureValues[feature.id],
|
||||
} as AgentFeature;
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveFeatureValues(args: {
|
||||
features: AgentFeature[];
|
||||
persistedFeatureValues: Record<string, unknown>;
|
||||
localFeatureValues: Record<string, unknown>;
|
||||
}): Record<string, unknown> {
|
||||
const next: Record<string, unknown> = {};
|
||||
|
||||
for (const feature of args.features) {
|
||||
if (Object.prototype.hasOwnProperty.call(args.localFeatureValues, feature.id)) {
|
||||
next[feature.id] = args.localFeatureValues[feature.id];
|
||||
continue;
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(args.persistedFeatureValues, feature.id)) {
|
||||
next[feature.id] = args.persistedFeatureValues[feature.id];
|
||||
}
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
@@ -128,14 +128,14 @@ function resolveDraftQueryConfig(draft?: DraftCommandTarget): DraftCommandConfig
|
||||
const modeId = draftConfig.modeId?.trim() ?? "";
|
||||
const model = draftConfig.model?.trim() ?? "";
|
||||
const thinkingOptionId = draftConfig.thinkingOptionId?.trim() ?? "";
|
||||
const providerOptions = draftConfig.providerOptions;
|
||||
const featureValues = draftConfig.featureValues;
|
||||
return {
|
||||
provider: draftConfig.provider,
|
||||
cwd,
|
||||
...(modeId ? { modeId } : {}),
|
||||
...(model ? { model } : {}),
|
||||
...(thinkingOptionId ? { thinkingOptionId } : {}),
|
||||
...(providerOptions && Object.keys(providerOptions).length > 0 ? { providerOptions } : {}),
|
||||
...(featureValues && Object.keys(featureValues).length > 0 ? { featureValues } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -352,7 +352,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
||||
modelId: model,
|
||||
modeId,
|
||||
thinkingOptionId,
|
||||
options: profile.options,
|
||||
featureValues: profile.featureValues,
|
||||
});
|
||||
}).catch((error) => {
|
||||
console.warn("[useAgentFormState] persist profile preference failed", error);
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { useRef } from "react";
|
||||
import type { AgentCapabilityFlags, AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import type { Agent } from "@/stores/session-store";
|
||||
import type {
|
||||
AgentCapabilityFlags,
|
||||
AgentFeature,
|
||||
AgentProvider,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import type { ViewedTimelineStatus } from "@/timeline/viewed-timeline-sync";
|
||||
|
||||
export interface AgentScreenAgent {
|
||||
@@ -19,8 +22,7 @@ export interface AgentScreenAgent {
|
||||
modeId?: string | null;
|
||||
thinkingOptionId?: string | null;
|
||||
} | null;
|
||||
options?: Agent["options"];
|
||||
controls?: Agent["controls"];
|
||||
features?: readonly AgentFeature[];
|
||||
lastError?: string | null;
|
||||
projectPlacement?: {
|
||||
projectKey?: string;
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { AgentProvider, AgentSessionConfig } from "@getpaseo/protocol/agent-types";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { mergeProviderPreferences, useFormPreferences } from "./use-form-preferences";
|
||||
import {
|
||||
applyFeatureValues,
|
||||
pruneFeatureValues,
|
||||
resolveFeatureValues,
|
||||
} from "./feature-preferences";
|
||||
|
||||
type DraftFeatureConfig = Pick<
|
||||
AgentSessionConfig,
|
||||
"provider" | "cwd" | "modeId" | "model" | "thinkingOptionId"
|
||||
>;
|
||||
|
||||
export function useDraftAgentFeatures(input: {
|
||||
serverId: string | null | undefined;
|
||||
provider: AgentProvider | null;
|
||||
cwd: string | null | undefined;
|
||||
modeId: string | null | undefined;
|
||||
modelId: string | null | undefined;
|
||||
thinkingOptionId: string | null | undefined;
|
||||
initialFeatureValues?: Record<string, unknown>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { serverId, provider, cwd, modeId, modelId, thinkingOptionId, initialFeatureValues } =
|
||||
input;
|
||||
const [localFeatureValues, setLocalFeatureValues] = useState<Record<string, unknown>>(
|
||||
() => initialFeatureValues ?? {},
|
||||
);
|
||||
const client = useHostRuntimeClient(serverId ?? "");
|
||||
const isConnected = useHostRuntimeIsConnected(serverId ?? "");
|
||||
const { preferences, updatePreferences } = useFormPreferences();
|
||||
const normalizedCwd = cwd?.trim() || "";
|
||||
const normalizedProvider = provider ?? null;
|
||||
const previousProviderRef = useRef<AgentProvider | null>(normalizedProvider);
|
||||
const persistedFeatureValues = useMemo(
|
||||
() => (provider ? (preferences.providerPreferences?.[provider]?.featureValues ?? {}) : {}),
|
||||
[preferences.providerPreferences, provider],
|
||||
);
|
||||
|
||||
const draftConfig = useMemo<DraftFeatureConfig | null>(() => {
|
||||
if (!normalizedProvider || !normalizedCwd) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
provider: normalizedProvider,
|
||||
cwd: normalizedCwd,
|
||||
...(modeId ? { modeId } : {}),
|
||||
...(modelId ? { model: modelId } : {}),
|
||||
...(thinkingOptionId ? { thinkingOptionId } : {}),
|
||||
};
|
||||
}, [modeId, modelId, normalizedCwd, normalizedProvider, thinkingOptionId]);
|
||||
|
||||
const featuresQuery = useQuery({
|
||||
queryKey: [
|
||||
"providerFeatures",
|
||||
serverId ?? null,
|
||||
normalizedProvider,
|
||||
normalizedCwd || null,
|
||||
modeId ?? null,
|
||||
modelId ?? null,
|
||||
thinkingOptionId ?? null,
|
||||
],
|
||||
enabled: Boolean(serverId && client && isConnected && draftConfig),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
queryFn: async () => {
|
||||
if (!client || !draftConfig) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
const payload = await client.listProviderFeatures(draftConfig);
|
||||
if (payload.error) {
|
||||
throw new Error(payload.error);
|
||||
}
|
||||
return payload.features ?? [];
|
||||
},
|
||||
});
|
||||
const availableFeaturesRaw = featuresQuery.data;
|
||||
const availableFeatures = useMemo(() => availableFeaturesRaw ?? [], [availableFeaturesRaw]);
|
||||
const featureValues = useMemo(
|
||||
() =>
|
||||
resolveFeatureValues({
|
||||
features: availableFeatures,
|
||||
persistedFeatureValues,
|
||||
localFeatureValues,
|
||||
}),
|
||||
[availableFeatures, localFeatureValues, persistedFeatureValues],
|
||||
);
|
||||
|
||||
const features = useMemo(() => {
|
||||
return applyFeatureValues(availableFeatures, featureValues);
|
||||
}, [availableFeatures, featureValues]);
|
||||
|
||||
useEffect(() => {
|
||||
const previousProvider = previousProviderRef.current;
|
||||
previousProviderRef.current = normalizedProvider;
|
||||
if (previousProvider === null) {
|
||||
return;
|
||||
}
|
||||
if (previousProvider !== normalizedProvider) {
|
||||
setLocalFeatureValues({});
|
||||
}
|
||||
}, [normalizedProvider]);
|
||||
|
||||
useEffect(() => {
|
||||
if (availableFeaturesRaw === undefined) {
|
||||
return;
|
||||
}
|
||||
const next = pruneFeatureValues(localFeatureValues, availableFeatures);
|
||||
if (next !== localFeatureValues) {
|
||||
setLocalFeatureValues(next);
|
||||
}
|
||||
}, [availableFeatures, availableFeaturesRaw, localFeatureValues]);
|
||||
|
||||
const effectiveFeatureValues = Object.keys(featureValues).length > 0 ? featureValues : undefined;
|
||||
const setFeatureValue = useCallback(
|
||||
(featureId: string, value: unknown) => {
|
||||
setLocalFeatureValues((current) => {
|
||||
if (Object.is(current[featureId], value)) {
|
||||
return current;
|
||||
}
|
||||
|
||||
return { ...current, [featureId]: value };
|
||||
});
|
||||
if (!provider) {
|
||||
return;
|
||||
}
|
||||
void updatePreferences((current) =>
|
||||
mergeProviderPreferences({
|
||||
preferences: current,
|
||||
provider,
|
||||
updates: {
|
||||
featureValues: {
|
||||
[featureId]: value,
|
||||
},
|
||||
},
|
||||
}),
|
||||
).catch((error) => {
|
||||
console.warn("[useDraftAgentFeatures] persist feature preference failed", error);
|
||||
});
|
||||
},
|
||||
[provider, updatePreferences],
|
||||
);
|
||||
|
||||
const applyProfileFeatureValues = useCallback((values: Record<string, unknown>) => {
|
||||
setLocalFeatureValues(values);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
features,
|
||||
featureValues: effectiveFeatureValues,
|
||||
isLoading: featuresQuery.isLoading,
|
||||
setFeatureValue,
|
||||
applyProfileFeatureValues,
|
||||
};
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import {
|
||||
draftControlsRequest,
|
||||
openDraftOptions,
|
||||
ownDraftOptions,
|
||||
viewDraftOptions,
|
||||
} from "@/agent-controls/draft-options-model";
|
||||
import type { ComposerOptionControls } from "@/agent-controls/option-controls";
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { mergeProviderPreferences, useFormPreferences } from "./use-form-preferences";
|
||||
|
||||
/**
|
||||
* Adapter between a draft's options model and the screen: it sends the model's complete options
|
||||
* to the daemon, hands the answer back, and persists the user's toggles as last-used values.
|
||||
*/
|
||||
export function useDraftProviderOptions(input: {
|
||||
serverId: string | null | undefined;
|
||||
provider: AgentProvider | null;
|
||||
cwd: string | null | undefined;
|
||||
modeId: string | null | undefined;
|
||||
modelId: string | null | undefined;
|
||||
thinkingOptionId: string | null | undefined;
|
||||
initialOptions?: ProviderOptions;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { serverId, provider, cwd, modeId, modelId, thinkingOptionId, initialOptions } = input;
|
||||
const [model] = useState(() => openDraftOptions({ provider, seed: initialOptions }));
|
||||
const state = useSyncExternalStore(model.subscribe, model.getState, model.getState);
|
||||
const client = useHostRuntimeClient(serverId ?? "");
|
||||
const isConnected = useHostRuntimeIsConnected(serverId ?? "");
|
||||
const { preferences, updatePreferences } = useFormPreferences();
|
||||
const normalizedCwd = cwd?.trim() || "";
|
||||
const persisted = preferences.providerPreferences?.[provider ?? ""]?.options;
|
||||
|
||||
useEffect(() => model.observeProvider(provider), [model, provider]);
|
||||
useEffect(() => model.setRemembered(persisted ?? {}), [model, persisted]);
|
||||
|
||||
const ownOptions = ownDraftOptions(state);
|
||||
const draftConfig = useMemo(
|
||||
() =>
|
||||
draftControlsRequest(state, {
|
||||
provider,
|
||||
cwd: normalizedCwd,
|
||||
modeId,
|
||||
modelId,
|
||||
thinkingOptionId,
|
||||
}),
|
||||
[modeId, modelId, normalizedCwd, provider, state, thinkingOptionId],
|
||||
);
|
||||
const queryKey = useMemo(
|
||||
() => ["providerControls", serverId ?? null, draftConfig],
|
||||
[draftConfig, serverId],
|
||||
);
|
||||
const requestKey = JSON.stringify(queryKey);
|
||||
|
||||
const { data } = useFetchQuery({
|
||||
queryKey,
|
||||
dataShape: "value",
|
||||
staleTimeMs: 5 * 60 * 1000,
|
||||
enabled: Boolean(serverId && client && isConnected && draftConfig),
|
||||
queryFn: async () => {
|
||||
if (!client || !draftConfig) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
const payload = await client.listProviderControls(draftConfig);
|
||||
if (payload.error) {
|
||||
throw new Error(payload.error);
|
||||
}
|
||||
return { controls: payload.controls ?? [], options: payload.options ?? {} };
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (provider && data) model.applyResolved({ provider, requestKey, ...data });
|
||||
}, [data, model, provider, requestKey]);
|
||||
|
||||
const setOption = useCallback(
|
||||
(key: string, value: unknown) => {
|
||||
model.setOption(key, value);
|
||||
if (!provider) return;
|
||||
void updatePreferences((current) =>
|
||||
mergeProviderPreferences({
|
||||
preferences: current,
|
||||
provider,
|
||||
updates: { options: { [key]: value } },
|
||||
}),
|
||||
).catch((error) => {
|
||||
console.warn("[useDraftProviderOptions] persist option preference failed", error);
|
||||
});
|
||||
},
|
||||
[model, provider, updatePreferences],
|
||||
);
|
||||
|
||||
const view = viewDraftOptions(state, { provider, requestKey });
|
||||
const viewControls = view?.controls;
|
||||
const viewOptions = view?.options;
|
||||
const optionControls = useMemo<ComposerOptionControls | undefined>(
|
||||
() =>
|
||||
viewControls && viewOptions
|
||||
? { controls: viewControls, options: viewOptions, onSetOption: setOption }
|
||||
: undefined,
|
||||
[setOption, viewControls, viewOptions],
|
||||
);
|
||||
|
||||
return { optionControls, options: ownOptions, applyProfile: model.applyProfile };
|
||||
}
|
||||
@@ -36,7 +36,7 @@ export type ForkAgentSource = Pick<
|
||||
| "model"
|
||||
| "thinkingOptionId"
|
||||
| "runtimeInfo"
|
||||
| "options"
|
||||
| "features"
|
||||
| "projectPlacement"
|
||||
>;
|
||||
|
||||
@@ -95,13 +95,18 @@ function buildForkDraftSetup(agent: ForkAgentSource): WorkspaceDraftTabSetup | u
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const featureValues: Record<string, unknown> = {};
|
||||
for (const feature of agent.features ?? []) {
|
||||
featureValues[feature.id] = feature.value;
|
||||
}
|
||||
|
||||
return {
|
||||
provider: agent.provider,
|
||||
cwd: agent.cwd,
|
||||
modeId: agent.currentModeId ?? agent.runtimeInfo?.modeId ?? null,
|
||||
model: agent.model ?? agent.runtimeInfo?.model ?? null,
|
||||
thinkingOptionId: agent.thinkingOptionId ?? agent.runtimeInfo?.thinkingOptionId ?? null,
|
||||
providerOptions: { ...agent.options },
|
||||
featureValues,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ describe("mergeProviderPreferences", () => {
|
||||
providerPreferences: {
|
||||
codex: {
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
featureValues: {
|
||||
fast_mode: true,
|
||||
},
|
||||
},
|
||||
@@ -71,7 +71,7 @@ describe("mergeProviderPreferences", () => {
|
||||
},
|
||||
provider: "codex",
|
||||
updates: {
|
||||
options: {
|
||||
featureValues: {
|
||||
plan_mode: true,
|
||||
},
|
||||
},
|
||||
@@ -81,7 +81,7 @@ describe("mergeProviderPreferences", () => {
|
||||
providerPreferences: {
|
||||
codex: {
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
featureValues: {
|
||||
fast_mode: true,
|
||||
plan_mode: true,
|
||||
},
|
||||
|
||||
@@ -118,8 +118,7 @@ interface ChatAgentStateShape {
|
||||
model?: Agent["model"];
|
||||
thinkingOptionId?: Agent["thinkingOptionId"];
|
||||
runtimeInfo?: Agent["runtimeInfo"];
|
||||
options?: Agent["options"];
|
||||
controls?: Agent["controls"];
|
||||
features?: Agent["features"];
|
||||
lastError?: Agent["lastError"] | null;
|
||||
}
|
||||
|
||||
@@ -178,8 +177,7 @@ function selectChatAgentState(
|
||||
model: agent.model,
|
||||
thinkingOptionId: agent.thinkingOptionId,
|
||||
runtimeInfo: agent.runtimeInfo,
|
||||
options: agent.options,
|
||||
controls: agent.controls,
|
||||
features: agent.features,
|
||||
lastError: agent.lastError ?? null,
|
||||
archivedAt: agent.archivedAt ?? null,
|
||||
requiresAttention: agent.requiresAttention ?? false,
|
||||
@@ -206,8 +204,7 @@ function buildChatAgentFromState(
|
||||
model: state.model,
|
||||
thinkingOptionId: state.thinkingOptionId,
|
||||
runtimeInfo: state.runtimeInfo,
|
||||
options: state.options,
|
||||
controls: state.controls,
|
||||
features: state.features,
|
||||
lastError: state.lastError ?? null,
|
||||
projectPlacement,
|
||||
};
|
||||
@@ -640,8 +637,7 @@ function AgentPanelBody({
|
||||
model: agentState.model,
|
||||
thinkingOptionId: agentState.thinkingOptionId,
|
||||
runtimeInfo: agentState.runtimeInfo,
|
||||
options: agentState.options,
|
||||
controls: agentState.controls,
|
||||
features: agentState.features,
|
||||
lastError: agentState.lastError ?? null,
|
||||
projectPlacement,
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ function installation(): InstalledPlugin {
|
||||
queryClient: new QueryClient(),
|
||||
paseo: {} as InstalledPlugin["paseo"],
|
||||
invoke: async () => undefined,
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
cleanup: () => undefined,
|
||||
settingsScreens: [],
|
||||
surfaces: [],
|
||||
|
||||
@@ -153,6 +153,9 @@ function harness() {
|
||||
openPanel() {},
|
||||
addComposerPill: () => ({ update() {}, remove() {} }),
|
||||
addHeaderButton: () => ({ update() {}, remove() {} }),
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createPlayAudio, type AudioEngine } from "@/audio";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { createPluginHosts } from "./hosts";
|
||||
import type { PluginClientOpenPanelOptions } from "@getpaseo/plugin/client";
|
||||
import { subscribePluginRpc } from "@getpaseo/plugin/client/host";
|
||||
import {
|
||||
createPluginAgentActionContext,
|
||||
createPluginCapabilities,
|
||||
@@ -36,6 +37,8 @@ export function createPluginClientRuntime(
|
||||
openPanel(panelId, options) {
|
||||
openClientPanel({ installation, state, panelId, options });
|
||||
},
|
||||
subscribe: (contract, input, onEvent, options) =>
|
||||
subscribePluginRpc(contract, installation.subscribe, input, onEvent, options),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -71,6 +71,9 @@ function plugin(onAgentSelect: AgentCommandItem["onSelect"]): InstalledPlugin {
|
||||
clientType: "cli",
|
||||
}),
|
||||
),
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
invoke: async (method: string, input: unknown) => {
|
||||
expect(method).toBe("review.inspect");
|
||||
return { value: inspect.input.parse(input).value + 1 };
|
||||
|
||||
@@ -111,6 +111,7 @@ export type PluginClientRuntime = Pick<
|
||||
| "openScreen"
|
||||
| "openSurface"
|
||||
| "openPanel"
|
||||
| "subscribe"
|
||||
| "addComposerPill"
|
||||
| "addHeaderButton"
|
||||
> & { hosts: ReturnType<typeof createPluginHosts> };
|
||||
|
||||
@@ -29,6 +29,9 @@ function installation(invoked: string[]): InstalledPlugin {
|
||||
invoked.push(method);
|
||||
return { state: "green" };
|
||||
},
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
queryClient: new QueryClient(),
|
||||
cleanup: () => undefined,
|
||||
settingsScreens: [],
|
||||
|
||||
@@ -18,7 +18,7 @@ export function PluginInstallationProvider({
|
||||
return (
|
||||
<QueryClientProvider client={plugin.queryClient}>
|
||||
<PaseoApiProvider paseo={plugin.paseo}>
|
||||
<PluginRpcProvider invoke={plugin.invoke}>
|
||||
<PluginRpcProvider invoke={plugin.invoke} subscribe={plugin.subscribe}>
|
||||
<PluginTranslationProvider runtime={plugin.i18n}>{children}</PluginTranslationProvider>
|
||||
</PluginRpcProvider>
|
||||
</PaseoApiProvider>
|
||||
|
||||
@@ -62,6 +62,9 @@ function registry(
|
||||
openPanel: () => {},
|
||||
addComposerPill: () => ({ update() {}, remove() {} }),
|
||||
addHeaderButton: () => ({ update() {}, remove() {} }),
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -39,6 +39,9 @@ function registry(version: string) {
|
||||
openPanel() {},
|
||||
addComposerPill: () => ({ update() {}, remove() {} }),
|
||||
addHeaderButton: () => ({ update() {}, remove() {} }),
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { assertPluginCompatibility } from "@getpaseo/protocol/plugin-requirements";
|
||||
import { resolveAppVersion } from "@/utils/app-version";
|
||||
import { createPluginClientRuntime } from "./client-runtime";
|
||||
import { createPluginSubscribe } from "./subscriptions";
|
||||
import { runPluginClientBundle } from "./evaluate";
|
||||
import type { InstalledPlugin } from "./types";
|
||||
|
||||
@@ -89,12 +90,18 @@ export class PluginRegistry {
|
||||
return [existing];
|
||||
}
|
||||
const client = options.client;
|
||||
const lifetime = new AbortController();
|
||||
installation = {
|
||||
lifetime: new AbortController(),
|
||||
lifetime,
|
||||
locale: this.dependencies.localeSource.getLocale(),
|
||||
i18n: new PluginTranslationRuntime(this.dependencies.localeSource),
|
||||
paseo: createPaseoApi(client),
|
||||
invoke: (method, input) => client.invokePluginRpc(entry.id, method, input),
|
||||
subscribe: createPluginSubscribe({
|
||||
client,
|
||||
pluginId: entry.id,
|
||||
lifetime: lifetime.signal,
|
||||
}),
|
||||
id: entry.id,
|
||||
serverId,
|
||||
clientBundle: entry.clientBundle,
|
||||
|
||||
@@ -26,6 +26,9 @@ function installed(
|
||||
queryClient: new QueryClient(),
|
||||
paseo: {} as InstalledPlugin["paseo"],
|
||||
invoke: async () => undefined,
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
settingsScreens: [],
|
||||
surfaces: [{ id: "surface", title: "Surface", Component: () => null }],
|
||||
sidebarItems: {
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { defineSubscription } from "@getpaseo/plugin";
|
||||
import type { PluginSubscriptionClosed } from "@getpaseo/plugin/client";
|
||||
import { subscribePluginRpc } from "@getpaseo/plugin/client/host";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { SubscriptionObserver } from "@getpaseo/client";
|
||||
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { createPluginSubscribe } from "./subscriptions";
|
||||
|
||||
const changes = defineSubscription({
|
||||
name: "diff.watch",
|
||||
input: z.object({ ref: z.string() }),
|
||||
event: z.union([z.instanceof(Uint8Array), z.object({ path: z.string() })]),
|
||||
});
|
||||
|
||||
type Observed = Parameters<DaemonClient["observePluginRpc"]>;
|
||||
|
||||
/** One host-side subscription as the daemon client exposes it, driven by the test. */
|
||||
class HostSubscription {
|
||||
readonly released: Promise<void>;
|
||||
isReleased = false;
|
||||
private observer: SubscriptionObserver<never> | null = null;
|
||||
private accept!: () => void;
|
||||
private refuse!: (error: Error) => void;
|
||||
private markReleased!: () => void;
|
||||
readonly ready = new Promise<never>((resolve, reject) => {
|
||||
this.accept = () => resolve({ requestId: "r", subscriptionId: "s" } as never);
|
||||
this.refuse = reject;
|
||||
});
|
||||
|
||||
constructor(
|
||||
readonly method: string,
|
||||
readonly input: unknown,
|
||||
readonly signal: AbortSignal | undefined,
|
||||
) {
|
||||
void this.ready.catch(() => undefined);
|
||||
this.released = new Promise((resolve) => {
|
||||
this.markReleased = resolve;
|
||||
});
|
||||
signal?.addEventListener("abort", () => void this.release(), { once: true });
|
||||
}
|
||||
|
||||
handle() {
|
||||
return {
|
||||
subscriptionId: "s",
|
||||
ready: this.ready,
|
||||
subscribe: (observer: SubscriptionObserver<never>) => {
|
||||
this.observer = observer;
|
||||
return () => undefined;
|
||||
},
|
||||
release: () => this.release(),
|
||||
};
|
||||
}
|
||||
|
||||
acknowledge() {
|
||||
this.accept();
|
||||
}
|
||||
|
||||
refuseWith(error: Error) {
|
||||
this.refuse(error);
|
||||
this.observer?.error?.(error);
|
||||
}
|
||||
|
||||
event(event: unknown) {
|
||||
this.observer?.update({
|
||||
type: "plugin.rpc.event",
|
||||
payload: { subscriptionId: "s", event },
|
||||
} as SessionOutboundMessage);
|
||||
}
|
||||
|
||||
bytes(payload: Uint8Array) {
|
||||
this.observer?.binary?.(payload);
|
||||
}
|
||||
|
||||
closed(error?: string) {
|
||||
this.observer?.update({
|
||||
type: "plugin.rpc.closed",
|
||||
payload: { subscriptionId: "s", ...(error ? { error } : {}) },
|
||||
} as SessionOutboundMessage);
|
||||
}
|
||||
|
||||
async release() {
|
||||
this.isReleased = true;
|
||||
this.markReleased();
|
||||
}
|
||||
}
|
||||
|
||||
/** An installation's subscribe on a host the test drives, and what one subscriber observed. */
|
||||
function installation() {
|
||||
const subscriptions: HostSubscription[] = [];
|
||||
const client = {
|
||||
observePluginRpc: (...[pluginId, method, input, options]: Observed) => {
|
||||
expect(pluginId).toBe("diffs");
|
||||
const subscription = new HostSubscription(method, input, options?.signal);
|
||||
subscriptions.push(subscription);
|
||||
return subscription.handle() as unknown as ReturnType<DaemonClient["observePluginRpc"]>;
|
||||
},
|
||||
};
|
||||
const lifetime = new AbortController();
|
||||
const subscribe = createPluginSubscribe({ client, pluginId: "diffs", lifetime: lifetime.signal });
|
||||
function open(ref: string, signal?: AbortSignal) {
|
||||
const received: string[] = [];
|
||||
const closed: PluginSubscriptionClosed[] = [];
|
||||
const handle = subscribePluginRpc(
|
||||
changes,
|
||||
subscribe,
|
||||
{ ref },
|
||||
(event) =>
|
||||
received.push(event instanceof Uint8Array ? `bytes:${[...event]}` : `path:${event.path}`),
|
||||
{ signal, onClosed: (result) => closed.push(result) },
|
||||
);
|
||||
return { handle, received, closed, host: subscriptions[subscriptions.length - 1]! };
|
||||
}
|
||||
return { open, lifetime };
|
||||
}
|
||||
|
||||
it("delivers JSON and byte events in order and releases the host subscription", async () => {
|
||||
const { open } = installation();
|
||||
const { handle, received, closed, host } = open("main");
|
||||
expect(host.method).toBe("diff.watch");
|
||||
expect(host.input).toEqual({ ref: "main" });
|
||||
host.acknowledge();
|
||||
await handle.ready;
|
||||
|
||||
host.event({ path: "a.ts" });
|
||||
host.bytes(new Uint8Array([1, 2]));
|
||||
expect(received).toEqual(["path:a.ts", "bytes:1,2"]);
|
||||
|
||||
handle();
|
||||
await host.released;
|
||||
expect(closed).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports a refusal, a failure after going live, and a clean close", async () => {
|
||||
const { open } = installation();
|
||||
const refused = open("a");
|
||||
refused.host.refuseWith(new Error("no such ref"));
|
||||
await expect(refused.handle.ready).rejects.toThrow("no such ref");
|
||||
expect(refused.closed).toEqual([{ error: new Error("no such ref") }]);
|
||||
|
||||
const failed = open("b");
|
||||
failed.host.acknowledge();
|
||||
await failed.handle.ready;
|
||||
failed.host.closed("Plugin stopped: diffs");
|
||||
expect(failed.closed).toEqual([{ error: new Error("Plugin stopped: diffs") }]);
|
||||
await failed.host.released;
|
||||
|
||||
// A handler that returns at once closes in the same tick the host accepts it.
|
||||
const finished = open("c");
|
||||
finished.host.acknowledge();
|
||||
finished.host.closed();
|
||||
await expect(finished.handle.ready).resolves.toBeUndefined();
|
||||
expect(finished.closed).toEqual([{}]);
|
||||
});
|
||||
|
||||
it("closes a subscription whose event fails the contract and drops what follows", async () => {
|
||||
const { open } = installation();
|
||||
const { handle, received, closed, host } = open("a");
|
||||
host.acknowledge();
|
||||
await handle.ready;
|
||||
host.event({ path: 3 });
|
||||
host.event({ path: "late.ts" });
|
||||
expect(received).toEqual([]);
|
||||
expect(closed).toEqual([
|
||||
{ error: new Error("Plugin subscription diff.watch sent an invalid event") },
|
||||
]);
|
||||
await host.released;
|
||||
});
|
||||
|
||||
it("releases on its signal, on its remover, and when the installation stops", async () => {
|
||||
const { open, lifetime } = installation();
|
||||
const controller = new AbortController();
|
||||
const bySignal = open("a", controller.signal);
|
||||
bySignal.host.acknowledge();
|
||||
await bySignal.handle.ready;
|
||||
controller.abort();
|
||||
await bySignal.host.released;
|
||||
|
||||
const byRemover = open("b");
|
||||
byRemover.handle();
|
||||
await byRemover.host.released;
|
||||
|
||||
const byLifetime = open("c");
|
||||
byLifetime.host.event({ path: "a.ts" });
|
||||
expect(byLifetime.received).toEqual(["path:a.ts"]);
|
||||
lifetime.abort();
|
||||
await byLifetime.host.released;
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { PluginSubscribe } from "@getpaseo/plugin/client/host";
|
||||
|
||||
/**
|
||||
* Plugin subscriptions on the installation's client. The client re-subscribes after a reconnect;
|
||||
* the installation's lifetime releases whatever its surfaces left open.
|
||||
*/
|
||||
export function createPluginSubscribe(input: {
|
||||
client: Pick<DaemonClient, "observePluginRpc">;
|
||||
pluginId: string;
|
||||
lifetime: AbortSignal;
|
||||
}): PluginSubscribe {
|
||||
const { client, pluginId, lifetime } = input;
|
||||
return (method, subscriptionInput, observer) => {
|
||||
const controller = new AbortController();
|
||||
const abort = () => controller.abort();
|
||||
lifetime.addEventListener("abort", abort, { once: true });
|
||||
controller.signal.addEventListener(
|
||||
"abort",
|
||||
() => lifetime.removeEventListener("abort", abort),
|
||||
{ once: true },
|
||||
);
|
||||
if (lifetime.aborted) controller.abort();
|
||||
const subscription = client.observePluginRpc(pluginId, method, subscriptionInput, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
subscription.subscribe({
|
||||
snapshot: () => undefined,
|
||||
update: (message) => {
|
||||
if (message.type === "plugin.rpc.event") observer.event(message.payload.event);
|
||||
else if (message.type === "plugin.rpc.closed") {
|
||||
controller.abort();
|
||||
const error = message.payload.error;
|
||||
observer.closed(error === undefined ? undefined : new Error(error));
|
||||
}
|
||||
},
|
||||
binary: (payload) => observer.event(payload),
|
||||
error: (error) => {
|
||||
controller.abort();
|
||||
observer.closed(error instanceof Error ? error : new Error(String(error)));
|
||||
},
|
||||
});
|
||||
const release = () => {
|
||||
controller.abort();
|
||||
return subscription.release();
|
||||
};
|
||||
return Object.assign(() => void release().catch(() => undefined), {
|
||||
ready: subscription.ready.then(() => undefined),
|
||||
release,
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -26,6 +26,9 @@ function installation(
|
||||
queryClient: new QueryClient(),
|
||||
paseo: {} as InstalledPlugin["paseo"],
|
||||
invoke: async () => undefined,
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
cleanup: () => undefined,
|
||||
settingsScreens: [],
|
||||
surfaces: surfaces.map((id) => ({ id, title: id, Component: () => null })),
|
||||
|
||||
@@ -56,6 +56,9 @@ function installed(serverId: string, themes: PluginThemeContribution[]): Install
|
||||
queryClient: new QueryClient(),
|
||||
paseo: {} as InstalledPlugin["paseo"],
|
||||
invoke: async () => undefined,
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
settingsScreens: [],
|
||||
surfaces: [],
|
||||
sidebarItems: { header: [], footer: [] },
|
||||
|
||||
@@ -18,6 +18,9 @@ function plugin(input: {
|
||||
queryClient: new QueryClient(),
|
||||
paseo: {} as InstalledPlugin["paseo"],
|
||||
invoke: async () => undefined,
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
cleanup: () => {},
|
||||
settingsScreens: [],
|
||||
surfaces: [],
|
||||
|
||||
@@ -71,6 +71,8 @@ export interface InstalledPlugin extends EvaluatedPlugin {
|
||||
paseo: PaseoApi;
|
||||
/** Calls one of the plugin's server RPC methods on its host. */
|
||||
invoke(method: string, input: unknown): Promise<unknown>;
|
||||
/** Subscribes to one of the plugin's server subscriptions; released with the lifetime. */
|
||||
subscribe: import("@getpaseo/plugin/client/host").PluginSubscribe;
|
||||
serverId: string;
|
||||
requirements?: PluginRequirements;
|
||||
clientBundle: string;
|
||||
|
||||
@@ -15,6 +15,9 @@ function installed(): InstalledPlugin {
|
||||
queryClient: new QueryClient(),
|
||||
paseo: {} as InstalledPlugin["paseo"],
|
||||
invoke: async () => undefined,
|
||||
subscribe: () => {
|
||||
throw new Error("Subscriptions are not used here");
|
||||
},
|
||||
cleanup: () => {},
|
||||
settingsScreens: [],
|
||||
surfaces: [],
|
||||
|
||||
@@ -312,7 +312,7 @@ export function buildDraftCommandTarget(input: {
|
||||
cwd: string;
|
||||
effectiveModelId: string;
|
||||
effectiveThinkingOptionId: string;
|
||||
providerOptions?: Record<string, unknown>;
|
||||
featureValues?: Record<string, unknown>;
|
||||
}): DraftCommandTarget {
|
||||
const cwd = input.cwd.trim();
|
||||
if (!cwd) {
|
||||
@@ -332,7 +332,7 @@ export function buildDraftCommandTarget(input: {
|
||||
...(input.effectiveThinkingOptionId
|
||||
? { thinkingOptionId: input.effectiveThinkingOptionId }
|
||||
: {}),
|
||||
...(input.providerOptions ? { providerOptions: input.providerOptions } : {}),
|
||||
...(input.featureValues ? { featureValues: input.featureValues } : {}),
|
||||
};
|
||||
return { status: "ready", config };
|
||||
}
|
||||
|
||||
@@ -284,7 +284,7 @@ describe("mergeSelectedComposerPreferences", () => {
|
||||
codex: {
|
||||
mode: "full-access",
|
||||
thinkingByModel: { "gpt-5.4-mini": "medium" },
|
||||
options: { fast_mode: true },
|
||||
featureValues: { fast_mode: true },
|
||||
},
|
||||
claude: { model: "claude-sonnet-4-6" },
|
||||
},
|
||||
@@ -299,7 +299,7 @@ describe("mergeSelectedComposerPreferences", () => {
|
||||
model: "gpt-5.4",
|
||||
mode: "full-access",
|
||||
thinkingByModel: { "gpt-5.4-mini": "medium" },
|
||||
options: { fast_mode: true },
|
||||
featureValues: { fast_mode: true },
|
||||
},
|
||||
claude: { model: "claude-sonnet-4-6" },
|
||||
},
|
||||
|
||||
@@ -271,7 +271,7 @@ interface WorkspaceDraftSubmissionConfig {
|
||||
modeId: string | null;
|
||||
model: string | null;
|
||||
thinkingOptionId: string | null;
|
||||
providerOptions: Record<string, unknown> | undefined;
|
||||
featureValues: Record<string, unknown> | undefined;
|
||||
target: WorkspaceTabTarget;
|
||||
}
|
||||
|
||||
@@ -374,7 +374,7 @@ function buildWorkspaceDraftSetupFromComposer(input: {
|
||||
modeId: input.composerState.effectiveModeId || null,
|
||||
model: input.composerState.effectiveModelId || null,
|
||||
thinkingOptionId: input.composerState.effectiveThinkingOptionId || null,
|
||||
providerOptions: input.composerState.providerOptions ?? {},
|
||||
featureValues: input.composerState.featureValues ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -454,7 +454,7 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise<Su
|
||||
modeId: composerState.effectiveModeId || undefined,
|
||||
model: composerState.effectiveModelId || undefined,
|
||||
thinkingOptionId: composerState.effectiveThinkingOptionId || undefined,
|
||||
providerOptions: composerState.providerOptions,
|
||||
featureValues: composerState.featureValues,
|
||||
},
|
||||
initialPrompt: text,
|
||||
clientMessageId: `${input.draftId}:initial-message`,
|
||||
@@ -534,7 +534,7 @@ function buildComposerConfig(input: {
|
||||
return {
|
||||
initialServerId: serverId || null,
|
||||
initialValues: buildComposerInitialValues({ initialSetup }),
|
||||
initialProviderOptions: initialSetup?.providerOptions,
|
||||
initialFeatureValues: initialSetup?.featureValues,
|
||||
isVisible: true,
|
||||
lockedWorkingDir: workingDir,
|
||||
};
|
||||
@@ -567,7 +567,7 @@ function resolveWorkspaceDraftSubmissionConfig(input: {
|
||||
modeId: initialSetup.modeId,
|
||||
model: initialSetup.model,
|
||||
thinkingOptionId: initialSetup.thinkingOptionId,
|
||||
providerOptions: initialSetup.providerOptions,
|
||||
featureValues: initialSetup.featureValues,
|
||||
target: { kind: "draft", draftId, setup: initialSetup },
|
||||
};
|
||||
}
|
||||
@@ -577,7 +577,7 @@ function resolveWorkspaceDraftSubmissionConfig(input: {
|
||||
modeId: composerState.effectiveModeId || null,
|
||||
model: composerState.effectiveModelId || null,
|
||||
thinkingOptionId: composerState.effectiveThinkingOptionId || null,
|
||||
providerOptions: composerState.providerOptions,
|
||||
featureValues: composerState.featureValues,
|
||||
target: { kind: "draft", draftId },
|
||||
};
|
||||
}
|
||||
@@ -635,7 +635,7 @@ function submitWorkspaceDraft(input: SubmitDraftInput): SubmitOutcome {
|
||||
...(submission.modeId ? { modeId: submission.modeId } : {}),
|
||||
...(submission.model ? { model: submission.model } : {}),
|
||||
...(submission.thinkingOptionId ? { thinkingOptionId: submission.thinkingOptionId } : {}),
|
||||
...(submission.providerOptions ? { providerOptions: submission.providerOptions } : {}),
|
||||
...(submission.featureValues ? { featureValues: submission.featureValues } : {}),
|
||||
allowEmptyText: true,
|
||||
agentCreation: input.agentCreation,
|
||||
});
|
||||
|
||||
@@ -69,7 +69,7 @@ describe("createWorkspaceAgentInBackground", () => {
|
||||
modeId: null,
|
||||
model: null,
|
||||
thinkingOptionId: null,
|
||||
providerOptions: {},
|
||||
featureValues: {},
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -89,7 +89,7 @@ describe("createWorkspaceAgentInBackground", () => {
|
||||
modeId: null,
|
||||
model: null,
|
||||
thinkingOptionId: null,
|
||||
providerOptions: {},
|
||||
featureValues: {},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ export function buildWorkspaceDraftAgentConfig(input: {
|
||||
modeId?: string;
|
||||
model?: string;
|
||||
thinkingOptionId?: string;
|
||||
providerOptions?: Record<string, unknown>;
|
||||
featureValues?: Record<string, unknown>;
|
||||
}): AgentSessionConfig {
|
||||
return {
|
||||
provider: input.provider,
|
||||
@@ -14,6 +14,6 @@ export function buildWorkspaceDraftAgentConfig(input: {
|
||||
...(input.modeId ? { modeId: input.modeId } : {}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
...(input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {}),
|
||||
...(input.providerOptions ? { providerOptions: input.providerOptions } : {}),
|
||||
...(input.featureValues ? { featureValues: input.featureValues } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -26,8 +26,7 @@ import type { ComposerAttachment } from "@/attachments/types";
|
||||
import type { AgentLifecycleStatus } from "@getpaseo/protocol/agent-lifecycle";
|
||||
import type {
|
||||
AgentPermissionRequest,
|
||||
AgentOptionControl,
|
||||
ProviderOptions,
|
||||
AgentFeature,
|
||||
AgentProvider,
|
||||
AgentMode,
|
||||
AgentCapabilityFlags,
|
||||
@@ -92,8 +91,7 @@ export interface Agent {
|
||||
cwd: string;
|
||||
workspaceId?: string;
|
||||
model: string | null;
|
||||
options?: ProviderOptions;
|
||||
controls?: AgentOptionControl[];
|
||||
features?: AgentFeature[];
|
||||
thinkingOptionId?: string | null;
|
||||
requiresAttention?: boolean;
|
||||
attentionReason?: "finished" | "error" | "permission" | null;
|
||||
|
||||
@@ -23,7 +23,7 @@ export interface PendingWorkspaceDraftSubmission {
|
||||
modeId?: string;
|
||||
model?: string;
|
||||
thinkingOptionId?: string;
|
||||
providerOptions?: Record<string, unknown>;
|
||||
featureValues?: Record<string, unknown>;
|
||||
allowEmptyText?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -95,53 +95,6 @@ it("keeps the saved layout when the shell publishes its layout mode before hydra
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps every saved layout when a draft tab's setup carries a nested provider option", async () => {
|
||||
const values = new Map<string, string>();
|
||||
const storage: StateStorage = {
|
||||
getItem: (name) => values.get(name) ?? null,
|
||||
setItem: (name, value) => {
|
||||
values.set(name, value);
|
||||
},
|
||||
removeItem: (name) => {
|
||||
values.delete(name);
|
||||
},
|
||||
};
|
||||
const store = createWorkspaceLayoutStore(undefined, storage);
|
||||
await store.persist.rehydrate();
|
||||
store.getState().openTab({
|
||||
workspaceKey: "server:kept",
|
||||
target: { kind: "agent", agentId: "agent-1" },
|
||||
intent: "reveal",
|
||||
});
|
||||
store.getState().openTab({
|
||||
workspaceKey: "server:forked",
|
||||
target: {
|
||||
kind: "draft",
|
||||
draftId: "draft-1",
|
||||
setup: {
|
||||
provider: "codex",
|
||||
cwd: "/repo",
|
||||
modeId: null,
|
||||
model: null,
|
||||
thinkingOptionId: null,
|
||||
providerOptions: { sandbox_workspace_write: { network_access: true }, max_turns: 3 },
|
||||
},
|
||||
},
|
||||
intent: "reveal",
|
||||
});
|
||||
|
||||
const restored = createWorkspaceLayoutStore(undefined, storage);
|
||||
await restored.persist.rehydrate();
|
||||
|
||||
expect(Object.keys(restored.getState().layoutByWorkspace).sort()).toEqual([
|
||||
"server:forked",
|
||||
"server:kept",
|
||||
]);
|
||||
expect(JSON.stringify(restored.getState().layoutByWorkspace["server:forked"])).toContain(
|
||||
"network_access",
|
||||
);
|
||||
});
|
||||
|
||||
it.each([1, 2])(
|
||||
"restores the agent pane after parked focus in storage version %i",
|
||||
async (version) => {
|
||||
|
||||
@@ -1,25 +1,14 @@
|
||||
import { z } from "zod";
|
||||
import type { SplitNode, WorkspaceLayout } from "./workspace-layout-actions";
|
||||
|
||||
// COMPAT(providerOptionControls): added in v0.15.0, remove after 2027-05-01. Layouts saved before
|
||||
// the rename stored the same record as `featureValues`.
|
||||
function renameLegacyFeatureValues(value: unknown): unknown {
|
||||
if (typeof value !== "object" || value === null || !("featureValues" in value)) return value;
|
||||
const { featureValues, ...rest } = value as { featureValues: unknown } & Record<string, unknown>;
|
||||
return "providerOptions" in rest ? rest : { ...rest, providerOptions: featureValues };
|
||||
}
|
||||
|
||||
const WorkspaceDraftTabSetupStorageSchema = z.preprocess(
|
||||
renameLegacyFeatureValues,
|
||||
z.strictObject({
|
||||
provider: z.string(),
|
||||
cwd: z.string(),
|
||||
modeId: z.string().nullable(),
|
||||
model: z.string().nullable(),
|
||||
thinkingOptionId: z.string().nullable(),
|
||||
providerOptions: z.record(z.string(), z.json()),
|
||||
}),
|
||||
);
|
||||
const WorkspaceDraftTabSetupStorageSchema = z.strictObject({
|
||||
provider: z.string(),
|
||||
cwd: z.string(),
|
||||
modeId: z.string().nullable(),
|
||||
model: z.string().nullable(),
|
||||
thinkingOptionId: z.string().nullable(),
|
||||
featureValues: z.record(z.string(), z.union([z.boolean(), z.string(), z.null()])),
|
||||
});
|
||||
const WorkspaceTabTargetStorageSchema = z.discriminatedUnion("kind", [
|
||||
z.strictObject({ kind: z.literal("new_tab") }),
|
||||
z.strictObject({
|
||||
|
||||
@@ -4551,6 +4551,7 @@ describe("compact workspace sheet", () => {
|
||||
title: agent.id,
|
||||
cwd: "/repo",
|
||||
model: null,
|
||||
features: undefined,
|
||||
thinkingOptionId: undefined,
|
||||
requiresAttention: false,
|
||||
attentionReason: null,
|
||||
|
||||
@@ -63,6 +63,7 @@ const AGENT_DEFAULTS: Agent = {
|
||||
cwd: WORKSPACE_DIRECTORY,
|
||||
workspaceId: WORKSPACE_ID,
|
||||
model: null,
|
||||
features: undefined,
|
||||
thinkingOptionId: undefined,
|
||||
requiresAttention: false,
|
||||
attentionReason: null,
|
||||
|
||||
@@ -41,6 +41,7 @@ const AGENT_DEFAULTS: Agent = {
|
||||
title: "Agent",
|
||||
cwd: "/tmp/project",
|
||||
model: null,
|
||||
features: undefined,
|
||||
thinkingOptionId: undefined,
|
||||
requiresAttention: false,
|
||||
attentionReason: null,
|
||||
|
||||
@@ -60,6 +60,7 @@ const AGENT_DEFAULTS: Agent = {
|
||||
cwd: "/repo/worktree",
|
||||
workspaceId: WORKSPACE_ID,
|
||||
model: null,
|
||||
features: undefined,
|
||||
thinkingOptionId: undefined,
|
||||
requiresAttention: false,
|
||||
attentionReason: null,
|
||||
|
||||
@@ -717,11 +717,13 @@ describe("terminal emulator runtime in a real browser", () => {
|
||||
{ name: "DA1-zero", bytes: "\x1b[0c" },
|
||||
{ name: "DA2", bytes: "\x1b[>c" },
|
||||
{ name: "DA3", bytes: "\x1b[=c" },
|
||||
{ name: "XTVERSION", bytes: "\x1b[>q" },
|
||||
{ name: "DSR-5", bytes: "\x1b[5n" },
|
||||
{ name: "DSR-6", bytes: "\x1b[6n" },
|
||||
{ name: "DSR-?6", bytes: "\x1b[?6n" },
|
||||
{ name: "DECRQM", bytes: "\x1b[1$p" },
|
||||
{ name: "DECRQM-?", bytes: "\x1b[?1$p" },
|
||||
{ name: "DECRQSS", bytes: "\x1bP$qm\x1b\\" },
|
||||
{ name: "OSC-10-foreground-color", bytes: "\x1b]10;?\x07" },
|
||||
{ name: "OSC-11-background-color", bytes: "\x1b]11;?\x07" },
|
||||
{ name: "OSC-12-cursor-color", bytes: "\x1b]12;?\x07" },
|
||||
|
||||
@@ -647,6 +647,7 @@ export class TerminalEmulatorRuntime {
|
||||
terminal.parser.registerCsiHandler({ final: "c" }, () => true);
|
||||
terminal.parser.registerCsiHandler({ prefix: ">", final: "c" }, () => true);
|
||||
terminal.parser.registerCsiHandler({ prefix: "=", final: "c" }, () => true);
|
||||
terminal.parser.registerCsiHandler({ prefix: ">", final: "q" }, () => true);
|
||||
terminal.parser.registerCsiHandler({ final: "n" }, () => true);
|
||||
terminal.parser.registerCsiHandler({ prefix: "?", final: "n" }, () => true);
|
||||
terminal.parser.registerCsiHandler({ final: "R" }, () => true);
|
||||
@@ -655,6 +656,7 @@ export class TerminalEmulatorRuntime {
|
||||
{ prefix: "?", intermediates: "$", final: "p" },
|
||||
() => true,
|
||||
);
|
||||
terminal.parser.registerDcsHandler({ intermediates: "$", final: "q" }, () => true);
|
||||
for (const code of [10, 11, 12]) {
|
||||
terminal.parser.registerOscHandler(code, (data) => data.trim() === "?");
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
|
||||
import { PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels";
|
||||
import { isControlActive, readSelectOption } from "@/agent-controls/option-controls";
|
||||
import { normalizeAgentSnapshot, projectAgentSnapshot } from "./agent-snapshots";
|
||||
|
||||
function createSnapshot(
|
||||
@@ -33,39 +32,10 @@ function createSnapshot(
|
||||
persistence: input.persistence ?? null,
|
||||
title: input.title ?? null,
|
||||
labels: (input.labels ?? {}) as AgentSnapshotPayload["labels"],
|
||||
...(input.controls ? { controls: input.controls } : {}),
|
||||
...(input.options ? { options: input.options } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
describe("normalizeAgentSnapshot", () => {
|
||||
it("keeps a closed agent's stored options and controls, so its Fast control draws", () => {
|
||||
const speed = {
|
||||
type: "select" as const,
|
||||
key: "service_tier",
|
||||
label: "Speed",
|
||||
defaultValue: "default",
|
||||
choices: [
|
||||
{ value: "default", label: "Normal" },
|
||||
{ value: "priority", label: "Fast" },
|
||||
],
|
||||
};
|
||||
const agent = normalizeAgentSnapshot(
|
||||
createSnapshot({
|
||||
status: "closed",
|
||||
controls: [speed],
|
||||
options: { service_tier: "priority", sandbox_mode: "read-only" },
|
||||
}),
|
||||
"server-1",
|
||||
);
|
||||
|
||||
expect(agent.status).toBe("closed");
|
||||
expect(agent.controls).toEqual([speed]);
|
||||
expect(agent.options).toEqual({ service_tier: "priority", sandbox_mode: "read-only" });
|
||||
expect(readSelectOption(speed, agent.options ?? {})).toBe("priority");
|
||||
expect(isControlActive(speed, agent.options ?? {})).toBe(true);
|
||||
});
|
||||
|
||||
it("round-trips identified active turns through the canonical snapshot boundary", () => {
|
||||
const snapshot = createSnapshot({
|
||||
status: "running",
|
||||
|
||||
@@ -64,8 +64,7 @@ export function projectAgentSnapshot(agent: Agent): AgentSnapshotPayload {
|
||||
cwd: agent.cwd,
|
||||
...(agent.workspaceId ? { workspaceId: agent.workspaceId } : {}),
|
||||
model: agent.model,
|
||||
...(agent.options ? { options: agent.options } : {}),
|
||||
...(agent.controls ? { controls: agent.controls } : {}),
|
||||
...(agent.features ? { features: agent.features } : {}),
|
||||
thinkingOptionId: agent.thinkingOptionId ?? null,
|
||||
createdAt: agent.createdAt.toISOString(),
|
||||
updatedAt: agent.updatedAt.toISOString(),
|
||||
@@ -128,8 +127,7 @@ export function normalizeAgentSnapshot(snapshot: AgentSnapshotPayload, serverId:
|
||||
cwd: snapshot.cwd,
|
||||
workspaceId: snapshot.workspaceId,
|
||||
model: snapshot.model ?? null,
|
||||
options: snapshot.options,
|
||||
controls: snapshot.controls,
|
||||
features: snapshot.features,
|
||||
thinkingOptionId: snapshot.thinkingOptionId ?? null,
|
||||
requiresAttention: snapshot.requiresAttention ?? false,
|
||||
attentionReason: snapshot.attentionReason ?? null,
|
||||
|
||||
@@ -92,7 +92,7 @@ export function normalizeWorkspaceDraftTabSetup(
|
||||
thinkingOptionId: trimOptionalString(
|
||||
typeof record.thinkingOptionId === "string" ? record.thinkingOptionId : null,
|
||||
),
|
||||
providerOptions: isPlainRecord(record.providerOptions) ? { ...record.providerOptions } : {},
|
||||
featureValues: isPlainRecord(record.featureValues) ? { ...record.featureValues } : {},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -171,7 +171,7 @@ function workspaceDraftTabSetupsEqual(
|
||||
left.modeId === right.modeId &&
|
||||
left.model === right.model &&
|
||||
left.thinkingOptionId === right.thinkingOptionId &&
|
||||
recordsShallowEqual(left.providerOptions, right.providerOptions)
|
||||
recordsShallowEqual(left.featureValues, right.featureValues)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ export interface WorkspaceDraftTabSetup {
|
||||
modeId: string | null;
|
||||
model: string | null;
|
||||
thinkingOptionId: string | null;
|
||||
providerOptions: Record<string, unknown>;
|
||||
featureValues: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface WorkspaceWorkingDiffTabTarget {
|
||||
|
||||
@@ -1,217 +0,0 @@
|
||||
import { controlsFromFeatures, optionsFromFeatures } from "@getpaseo/protocol/option-controls";
|
||||
import type {
|
||||
AgentProfile,
|
||||
AgentSnapshotPayload,
|
||||
MutableDaemonConfig,
|
||||
ListProviderFeaturesResponseMessage,
|
||||
ProviderControlsListResponseMessage,
|
||||
ServerInfoStatusPayload,
|
||||
SessionInboundMessage,
|
||||
SessionOutboundMessage,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
|
||||
/**
|
||||
* COMPAT(providerOptionControls): added in v0.15.0, remove after 2027-05-01 once daemon floor >=
|
||||
* v0.15.0.
|
||||
*
|
||||
* A daemon without `server_info.features.providerOptionControls` sends `features` (a control with
|
||||
* its value attached) and takes composer values as `featureValues`. This is the one place that
|
||||
* turns that into the shape everyone else uses: `controls` over `options`, written through
|
||||
* `providerOptions`.
|
||||
*/
|
||||
export function usesLegacyProviderOptions(info: ServerInfoStatusPayload): boolean {
|
||||
return info.features?.providerOptionControls !== true;
|
||||
}
|
||||
|
||||
export class LegacyProviderOptions {
|
||||
/** Gives agent snapshots `controls` and `options`, built from their `features`. */
|
||||
normalize(message: SessionOutboundMessage): SessionOutboundMessage {
|
||||
switch (message.type) {
|
||||
case "agent_update":
|
||||
if (message.payload.kind !== "upsert") return message;
|
||||
return {
|
||||
...message,
|
||||
payload: { ...message.payload, agent: this.snapshot(message.payload.agent) },
|
||||
};
|
||||
case "agent_status":
|
||||
return {
|
||||
...message,
|
||||
payload: { ...message.payload, info: this.snapshot(message.payload.info) },
|
||||
};
|
||||
case "fetch_agents_response":
|
||||
return {
|
||||
...message,
|
||||
payload: {
|
||||
...message.payload,
|
||||
entries: message.payload.entries.map((entry) => ({
|
||||
...entry,
|
||||
agent: this.snapshot(entry.agent),
|
||||
})),
|
||||
},
|
||||
};
|
||||
case "fetch_agent_response":
|
||||
case "agent.create.response":
|
||||
case "cancel_agent_response":
|
||||
return {
|
||||
...message,
|
||||
payload: {
|
||||
...message.payload,
|
||||
agent: message.payload.agent && this.snapshot(message.payload.agent),
|
||||
},
|
||||
} as SessionOutboundMessage;
|
||||
case "workspace.create.response":
|
||||
return {
|
||||
...message,
|
||||
payload: {
|
||||
...message.payload,
|
||||
...(message.payload.agent ? { agent: this.snapshot(message.payload.agent) } : {}),
|
||||
},
|
||||
};
|
||||
case "wait_for_finish_response":
|
||||
return {
|
||||
...message,
|
||||
payload: {
|
||||
...message.payload,
|
||||
final: message.payload.final && this.snapshot(message.payload.final),
|
||||
},
|
||||
};
|
||||
case "get_daemon_config_response":
|
||||
case "set_daemon_config_response":
|
||||
return {
|
||||
...message,
|
||||
payload: { ...message.payload, config: this.daemonConfig(message.payload.config) },
|
||||
};
|
||||
case "fetch_agent_timeline_response":
|
||||
return {
|
||||
...message,
|
||||
payload: {
|
||||
...message.payload,
|
||||
agent: message.payload.agent && this.snapshot(message.payload.agent),
|
||||
},
|
||||
};
|
||||
case "status":
|
||||
return this.status(message);
|
||||
default:
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
private status(
|
||||
message: Extract<SessionOutboundMessage, { type: "status" }>,
|
||||
): SessionOutboundMessage {
|
||||
const { payload } = message;
|
||||
if (payload.status === "agent_created" || payload.status === "agent_resumed") {
|
||||
const { agent } = payload as unknown as { agent: AgentSnapshotPayload };
|
||||
return { ...message, payload: { ...payload, agent: this.snapshot(agent) } };
|
||||
}
|
||||
if (payload.status === "daemon_config_changed") {
|
||||
const config = payload.config as MutableDaemonConfig;
|
||||
return { ...message, payload: { ...payload, config: this.daemonConfig(config) } };
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a create's options for a legacy daemon: the ids it lists as features for that very
|
||||
* config go out as `featureValues`, which is where it reads them, and the rest stay
|
||||
* `providerOptions`. Which options are features depends on the model, mode and thinking level
|
||||
* as well as the provider, so the ids come from a listing for this config, never from memory.
|
||||
*/
|
||||
routeCreateConfig<
|
||||
T extends {
|
||||
providerOptions?: Record<string, unknown>;
|
||||
featureValues?: Record<string, unknown>;
|
||||
},
|
||||
>(config: T, featureIds: ReadonlySet<string>): T {
|
||||
if (!config.providerOptions) return config;
|
||||
const featureValues: Record<string, unknown> = {};
|
||||
const providerOptions: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(config.providerOptions)) {
|
||||
(featureIds.has(key) ? featureValues : providerOptions)[key] = value;
|
||||
}
|
||||
const { providerOptions: _options, ...rest } = config;
|
||||
return {
|
||||
...(rest as T),
|
||||
...(Object.keys(providerOptions).length > 0 ? { providerOptions } : {}),
|
||||
...(Object.keys(featureValues).length > 0
|
||||
? { featureValues: { ...config.featureValues, ...featureValues } }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Sends options as `featureValues`, which is where a legacy daemon reads them. */
|
||||
prepare(message: SessionInboundMessage): SessionInboundMessage {
|
||||
switch (message.type) {
|
||||
case "agent.config.apply.request": {
|
||||
const { options, ...config } = message.config;
|
||||
if (!options) return message;
|
||||
return {
|
||||
...message,
|
||||
config: { ...config, featureValues: { ...config.featureValues, ...options } },
|
||||
};
|
||||
}
|
||||
case "list_commands_request": {
|
||||
if (!message.draftConfig?.providerOptions) return message;
|
||||
const { providerOptions, ...draftConfig } = message.draftConfig;
|
||||
return {
|
||||
...message,
|
||||
draftConfig: {
|
||||
...draftConfig,
|
||||
featureValues: { ...draftConfig.featureValues, ...providerOptions },
|
||||
},
|
||||
};
|
||||
}
|
||||
case "set_daemon_config_request":
|
||||
if (!message.config.agentProfiles) return message;
|
||||
return {
|
||||
...message,
|
||||
config: {
|
||||
...message.config,
|
||||
agentProfiles: message.config.agentProfiles.map(profileWithFeatureValues),
|
||||
},
|
||||
};
|
||||
default:
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
/** The legacy answer to a controls listing, in the shape of the current response. */
|
||||
controlsResponse(
|
||||
legacy: ListProviderFeaturesResponseMessage["payload"],
|
||||
): ProviderControlsListResponseMessage["payload"] {
|
||||
const { features, ...rest } = legacy;
|
||||
return {
|
||||
...rest,
|
||||
...(features
|
||||
? { controls: controlsFromFeatures(features), options: optionsFromFeatures(features) }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
private daemonConfig(config: MutableDaemonConfig): MutableDaemonConfig {
|
||||
if (!config.agentProfiles) return config;
|
||||
return { ...config, agentProfiles: config.agentProfiles.map(profileWithOptions) };
|
||||
}
|
||||
|
||||
private readonly snapshot = (agent: AgentSnapshotPayload): AgentSnapshotPayload => {
|
||||
if (agent.controls || !agent.features) return agent;
|
||||
return {
|
||||
...agent,
|
||||
controls: controlsFromFeatures(agent.features),
|
||||
options: optionsFromFeatures(agent.features),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/** A legacy daemon stores a profile's options under `featureValues`. */
|
||||
function profileWithOptions(profile: AgentProfile): AgentProfile {
|
||||
if (profile.options || !profile.featureValues) return profile;
|
||||
const { featureValues, ...rest } = profile;
|
||||
return { ...rest, options: featureValues };
|
||||
}
|
||||
|
||||
function profileWithFeatureValues(profile: AgentProfile): AgentProfile {
|
||||
if (!profile.options) return profile;
|
||||
const { options, ...rest } = profile;
|
||||
return { ...rest, featureValues: options };
|
||||
}
|
||||
@@ -144,6 +144,7 @@ export const DEFAULT_CLIENT_CAPABILITIES = {
|
||||
[CLIENT_CAPS.pluginTimelineItems]: true,
|
||||
[CLIENT_CAPS.workspaceSetupBlocked]: true,
|
||||
[CLIENT_CAPS.workspaceSetupObservation]: true,
|
||||
[CLIENT_CAPS.pluginBinaryPayloads]: true,
|
||||
[CLIENT_CAPS.explicitEventSubscriptions]: true,
|
||||
} satisfies Record<Exclude<ClientCapability, typeof CLIENT_CAPS.browserHost>, true>;
|
||||
|
||||
|
||||
@@ -83,6 +83,26 @@ test("cancellation before the ID waits for bootstrap and releases exactly that I
|
||||
expect(c.released).toEqual(["cancelled"]);
|
||||
});
|
||||
|
||||
test("a release right after the host accepts still reports the subscription as accepted", async () => {
|
||||
const c = connection();
|
||||
const handle = c.observe();
|
||||
c.requests[0]!("closing");
|
||||
const released = handle.release();
|
||||
await expect(handle.ready).resolves.toMatchObject({ subscriptionId: "closing" });
|
||||
await released;
|
||||
expect(c.released).toEqual(["closing"]);
|
||||
});
|
||||
|
||||
test("a release before the host accepts rejects ready", async () => {
|
||||
const c = connection();
|
||||
const handle = c.observe();
|
||||
const released = handle.release();
|
||||
await expect(handle.ready).rejects.toThrow("Subscription released");
|
||||
c.requests[0]!("late");
|
||||
await released;
|
||||
expect(c.released).toEqual(["late"]);
|
||||
});
|
||||
|
||||
test("surviving handles use new remote IDs after reconnect and released handles stay gone", async () => {
|
||||
const c = connection();
|
||||
const a = c.observe();
|
||||
|
||||
@@ -5,6 +5,8 @@ export type SubscriptionSnapshot<T> = T & { subscriptionId: string };
|
||||
export interface SubscriptionObserver<T> {
|
||||
snapshot(snapshot: T): void;
|
||||
update(message: SessionOutboundMessage): void;
|
||||
/** A binary frame the host addressed to this subscription; the payload is a view. */
|
||||
binary?(payload: Uint8Array): void;
|
||||
error?(error: unknown): void;
|
||||
}
|
||||
|
||||
@@ -20,9 +22,12 @@ interface Registration {
|
||||
start(): void;
|
||||
disconnected(): void;
|
||||
receive(message: SessionOutboundMessage): void;
|
||||
receiveBinary(payload: Uint8Array): void;
|
||||
release(): Promise<void>;
|
||||
}
|
||||
|
||||
type Update = { message: SessionOutboundMessage } | { binary: Uint8Array };
|
||||
|
||||
export interface OwnedSubscriptionsHost {
|
||||
release(subscriptionId: string): Promise<void>;
|
||||
failed(error: unknown): void;
|
||||
@@ -50,7 +55,7 @@ export class OwnedSubscriptions {
|
||||
let teardown: Promise<void> | null = null;
|
||||
let disposed = false;
|
||||
let overflow = false;
|
||||
const buffered: SessionOutboundMessage[] = [];
|
||||
const buffered: Update[] = [];
|
||||
const observers = new Set<SubscriptionObserver<SubscriptionSnapshot<T>>>();
|
||||
let resolve!: (snapshot: SubscriptionSnapshot<T>) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
@@ -60,12 +65,10 @@ export class OwnedSubscriptions {
|
||||
});
|
||||
void ready.catch(() => {});
|
||||
|
||||
const deliver = (
|
||||
observer: SubscriptionObserver<SubscriptionSnapshot<T>>,
|
||||
message?: SessionOutboundMessage,
|
||||
) => {
|
||||
const deliver = (observer: SubscriptionObserver<SubscriptionSnapshot<T>>, update?: Update) => {
|
||||
try {
|
||||
if (message) observer.update(message);
|
||||
if (update && "binary" in update) observer.binary?.(update.binary);
|
||||
else if (update) observer.update(update.message);
|
||||
else if (snapshot) observer.snapshot(snapshot);
|
||||
} catch (error) {
|
||||
this.host.failed(error);
|
||||
@@ -78,6 +81,13 @@ export class OwnedSubscriptions {
|
||||
this.routes.delete(released);
|
||||
await this.host.release(released);
|
||||
};
|
||||
const buffer = (update: Update) => {
|
||||
if (buffered.length < MAX_BOOTSTRAP_UPDATES && !overflow) buffered.push(update);
|
||||
else {
|
||||
buffered.length = 0;
|
||||
overflow = true;
|
||||
}
|
||||
};
|
||||
const registration: Registration = {
|
||||
start: () => {
|
||||
if (disposed || pending || id || !this.connected) return;
|
||||
@@ -128,12 +138,14 @@ export class OwnedSubscriptions {
|
||||
},
|
||||
receive: (message) => {
|
||||
if (disposed || ("payload" in message && Object.is(message.payload, snapshot))) return;
|
||||
if (buffered.length < MAX_BOOTSTRAP_UPDATES && !overflow) buffered.push(message);
|
||||
else {
|
||||
buffered.length = 0;
|
||||
overflow = true;
|
||||
}
|
||||
for (const observer of observers) deliver(observer, message);
|
||||
buffer({ message });
|
||||
for (const observer of observers) deliver(observer, { message });
|
||||
},
|
||||
receiveBinary: (payload) => {
|
||||
if (disposed) return;
|
||||
// Bytes wait only for the first observer; retaining them after would hold every frame.
|
||||
if (observers.size === 0) buffer({ binary: payload });
|
||||
for (const observer of observers) deliver(observer, { binary: payload });
|
||||
},
|
||||
release: () => {
|
||||
if (teardown) return teardown;
|
||||
@@ -142,7 +154,9 @@ export class OwnedSubscriptions {
|
||||
observers.clear();
|
||||
buffered.length = 0;
|
||||
if (id) this.routes.delete(id);
|
||||
reject(new Error("Subscription released"));
|
||||
// A host that already accepted keeps `ready` resolved, even if released in the same tick.
|
||||
if (snapshot) resolve(snapshot);
|
||||
else reject(new Error("Subscription released"));
|
||||
teardown = (async () => {
|
||||
await pending;
|
||||
await releaseId();
|
||||
@@ -174,7 +188,7 @@ export class OwnedSubscriptions {
|
||||
.catch(this.host.failed);
|
||||
} else {
|
||||
deliver(observer);
|
||||
for (const message of buffered) deliver(observer, message);
|
||||
for (const update of buffered) deliver(observer, update);
|
||||
}
|
||||
return () => {
|
||||
observers.delete(observer);
|
||||
@@ -205,6 +219,10 @@ export class OwnedSubscriptions {
|
||||
this.routes.get(payload.subscriptionId)?.receive(message);
|
||||
}
|
||||
|
||||
receiveBinary(subscriptionId: string, payload: Uint8Array): void {
|
||||
this.routes.get(subscriptionId)?.receiveBinary(payload);
|
||||
}
|
||||
|
||||
restore(): void {
|
||||
this.connected = true;
|
||||
for (const registration of this.registrations) registration.start();
|
||||
|
||||
@@ -1106,6 +1106,7 @@ test("advertises client capabilities in hello", async () => {
|
||||
terminal_chunked_replay: true,
|
||||
timeline_notifications: true,
|
||||
plugin_timeline_items: true,
|
||||
plugin_binary_payloads: true,
|
||||
workspace_setup_blocked: true,
|
||||
workspace_setup_observation: true,
|
||||
hello_rejection: true,
|
||||
@@ -8924,394 +8925,3 @@ test("routed channels inherit an origin without drain support", async () => {
|
||||
expect(route.supportsDrain).toBe(false);
|
||||
route.close();
|
||||
});
|
||||
|
||||
describe("provider options across daemon versions", () => {
|
||||
const agentSnapshot = {
|
||||
id: "agent-1",
|
||||
provider: "codex",
|
||||
cwd: "/repo",
|
||||
model: null,
|
||||
thinkingOptionId: null,
|
||||
effectiveThinkingOptionId: null,
|
||||
createdAt: "2026-04-30T00:00:00.000Z",
|
||||
updatedAt: "2026-04-30T00:00:00.000Z",
|
||||
lastUserMessageAt: null,
|
||||
status: "idle",
|
||||
capabilities: {
|
||||
supportsStreaming: false,
|
||||
supportsSessionPersistence: false,
|
||||
supportsDynamicModes: false,
|
||||
supportsMcpServers: false,
|
||||
supportsReasoningStream: false,
|
||||
supportsToolInvocations: false,
|
||||
},
|
||||
currentModeId: null,
|
||||
availableModes: [],
|
||||
pendingPermissions: [],
|
||||
persistence: null,
|
||||
title: null,
|
||||
labels: {},
|
||||
requiresAttention: false,
|
||||
attentionReason: null,
|
||||
};
|
||||
const speedFeature = {
|
||||
type: "select",
|
||||
id: "service_tier",
|
||||
label: "Speed",
|
||||
value: "priority",
|
||||
options: [
|
||||
{ id: "default", label: "Normal", isDefault: true },
|
||||
{ id: "priority", label: "Fast" },
|
||||
],
|
||||
};
|
||||
|
||||
async function connect(features: Record<string, boolean>) {
|
||||
const mock = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "provider_options",
|
||||
transportFactory: () => mock.transport,
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
clients.push(client);
|
||||
const connecting = client.connect();
|
||||
mock.triggerOpen({ features });
|
||||
await connecting;
|
||||
const sentMessages = () =>
|
||||
mock.sent.map(
|
||||
(frame) => (JSON.parse(frame as string) as { message: Record<string, unknown> }).message,
|
||||
);
|
||||
return { mock, client, sentMessages };
|
||||
}
|
||||
|
||||
test("a legacy create and a timeline read return the agent with controls over options", async () => {
|
||||
const { mock, client, sentMessages } = await connect({});
|
||||
const legacyAgent = { ...agentSnapshot, features: [speedFeature] };
|
||||
const answerLast = (reply: (requestId: string) => Record<string, unknown>) => {
|
||||
const sent = sentMessages();
|
||||
const requestId = String(sent[sent.length - 1].requestId);
|
||||
mock.triggerMessage(wrapSessionMessage(reply(requestId) as never));
|
||||
};
|
||||
|
||||
const creating = client.createAgent({ provider: "codex", cwd: "/repo" });
|
||||
answerLast((requestId) => ({
|
||||
type: "status",
|
||||
payload: { status: "agent_created", requestId, agentId: "agent-1", agent: legacyAgent },
|
||||
}));
|
||||
const created = await creating;
|
||||
|
||||
const reading = client.fetchAgentTimeline("agent-1");
|
||||
answerLast((requestId) => ({
|
||||
type: "fetch_agent_timeline_response",
|
||||
payload: {
|
||||
requestId,
|
||||
agentId: "agent-1",
|
||||
agent: legacyAgent,
|
||||
direction: "tail",
|
||||
projection: "projected",
|
||||
epoch: "epoch-1",
|
||||
reset: false,
|
||||
staleCursor: false,
|
||||
gap: false,
|
||||
window: { minSeq: 0, maxSeq: 0, nextSeq: 1 },
|
||||
startCursor: null,
|
||||
endCursor: null,
|
||||
hasOlder: false,
|
||||
hasNewer: false,
|
||||
entries: [],
|
||||
error: null,
|
||||
},
|
||||
}));
|
||||
const timeline = await reading;
|
||||
|
||||
expect(created.options).toEqual({ service_tier: "priority" });
|
||||
expect(created.controls).toEqual([expect.objectContaining({ key: "service_tier" })]);
|
||||
expect(timeline.agent?.options).toEqual({ service_tier: "priority" });
|
||||
expect(timeline.agent?.controls).toEqual([expect.objectContaining({ key: "service_tier" })]);
|
||||
});
|
||||
|
||||
test("a legacy daemon's features arrive as controls over options", async () => {
|
||||
const { mock, client } = await connect({});
|
||||
const received: Array<{ controls?: unknown; options?: unknown }> = [];
|
||||
client.on("agent_update", (message) => {
|
||||
if (message.payload.kind === "upsert") received.push(message.payload.agent);
|
||||
});
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "agent_update",
|
||||
payload: { kind: "upsert", agent: { ...agentSnapshot, features: [speedFeature] } },
|
||||
}),
|
||||
);
|
||||
expect(received).toEqual([
|
||||
expect.objectContaining({
|
||||
options: { service_tier: "priority" },
|
||||
controls: [
|
||||
expect.objectContaining({
|
||||
type: "select",
|
||||
key: "service_tier",
|
||||
defaultValue: "default",
|
||||
choices: [
|
||||
{ value: "default", label: "Normal" },
|
||||
{ value: "priority", label: "Fast" },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
test("a legacy daemon takes option writes as feature writes", async () => {
|
||||
const { client, sentMessages, mock } = await connect({});
|
||||
const write = client.setAgentOptions("agent-1", { service_tier: "default" });
|
||||
const [request] = sentMessages();
|
||||
expect(request).toMatchObject({
|
||||
type: "set_agent_feature_request",
|
||||
agentId: "agent-1",
|
||||
featureId: "service_tier",
|
||||
value: "default",
|
||||
});
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "set_agent_feature_response",
|
||||
payload: { requestId: request.requestId, agentId: "agent-1", accepted: true, error: null },
|
||||
}),
|
||||
);
|
||||
await write;
|
||||
});
|
||||
|
||||
test("a current daemon takes option writes as one options patch", async () => {
|
||||
const { client, sentMessages, mock } = await connect({ providerOptionControls: true });
|
||||
const write = client.setAgentOptions("agent-1", { service_tier: null, sandbox_mode: "x" });
|
||||
const [request] = sentMessages();
|
||||
expect(request).toMatchObject({
|
||||
type: "agent.config.apply.request",
|
||||
agentId: "agent-1",
|
||||
config: { options: { service_tier: null, sandbox_mode: "x" } },
|
||||
});
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "agent.config.apply.response",
|
||||
payload: { requestId: request.requestId, agentId: "agent-1", accepted: true, error: null },
|
||||
}),
|
||||
);
|
||||
await write;
|
||||
});
|
||||
|
||||
test("a legacy draft listing answers with controls and options", async () => {
|
||||
const { client, sentMessages, mock } = await connect({});
|
||||
const listing = client.listProviderControls({
|
||||
provider: "codex",
|
||||
cwd: "/repo",
|
||||
providerOptions: { service_tier: "default" },
|
||||
});
|
||||
const [request] = sentMessages();
|
||||
expect(request).toMatchObject({
|
||||
type: "list_provider_features_request",
|
||||
draftConfig: { provider: "codex", featureValues: { service_tier: "default" } },
|
||||
});
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "list_provider_features_response",
|
||||
payload: {
|
||||
provider: "codex",
|
||||
features: [{ ...speedFeature, value: "default" }],
|
||||
error: null,
|
||||
fetchedAt: "2026-04-30T00:00:00.000Z",
|
||||
requestId: request.requestId,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await expect(listing).resolves.toMatchObject({
|
||||
provider: "codex",
|
||||
options: { service_tier: "default" },
|
||||
controls: [expect.objectContaining({ key: "service_tier" })],
|
||||
});
|
||||
});
|
||||
|
||||
test("a legacy daemon's profiles are read and saved by their options", async () => {
|
||||
const { client, sentMessages, mock } = await connect({});
|
||||
const reading = client.getDaemonConfig();
|
||||
const [read] = sentMessages();
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "get_daemon_config_response",
|
||||
payload: {
|
||||
requestId: read.requestId,
|
||||
config: {
|
||||
mcp: { injectIntoAgents: true },
|
||||
agentProfiles: [
|
||||
{
|
||||
id: "p1",
|
||||
name: "Fast",
|
||||
provider: "codex",
|
||||
featureValues: { service_tier: "fast" },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const { config } = await reading;
|
||||
expect(config.agentProfiles?.[0]).toMatchObject({ options: { service_tier: "fast" } });
|
||||
expect(config.agentProfiles?.[0]).not.toHaveProperty("featureValues");
|
||||
|
||||
void client.patchDaemonConfig({ agentProfiles: config.agentProfiles }).catch(() => {});
|
||||
const written = sentMessages().find((message) => message.type === "set_daemon_config_request");
|
||||
expect(written).toMatchObject({
|
||||
config: { agentProfiles: [{ featureValues: { service_tier: "fast" } }] },
|
||||
});
|
||||
expect(written).not.toMatchObject({ config: { agentProfiles: [{ options: {} }] } });
|
||||
});
|
||||
|
||||
test("a legacy daemon applies a profile's options as feature values", async () => {
|
||||
const { client, sentMessages } = await connect({});
|
||||
void client.applyAgentConfig("agent-1", { options: { service_tier: "fast" } }).catch(() => {});
|
||||
const [request] = sentMessages();
|
||||
expect(request).toMatchObject({
|
||||
type: "agent.config.apply.request",
|
||||
config: { featureValues: { service_tier: "fast" } },
|
||||
});
|
||||
});
|
||||
|
||||
test("a cold legacy create lists the provider's features before routing its options", async () => {
|
||||
const { client, sentMessages, mock } = await connect({});
|
||||
void client
|
||||
.createAgent({
|
||||
config: {
|
||||
provider: "claude",
|
||||
cwd: "/repo",
|
||||
providerOptions: { fast_mode: true, sandbox_mode: "read-only" },
|
||||
},
|
||||
})
|
||||
.catch(() => {});
|
||||
await vi.waitFor(() => expect(sentMessages()).toHaveLength(1));
|
||||
const [listing] = sentMessages();
|
||||
expect(listing).toMatchObject({
|
||||
type: "list_provider_features_request",
|
||||
draftConfig: { provider: "claude", cwd: "/repo" },
|
||||
});
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "list_provider_features_response",
|
||||
payload: {
|
||||
provider: "claude",
|
||||
features: [{ type: "toggle", id: "fast_mode", label: "Fast", value: false }],
|
||||
error: null,
|
||||
fetchedAt: "2026-04-30T00:00:00.000Z",
|
||||
requestId: listing.requestId,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await vi.waitFor(() => expect(sentMessages()).toHaveLength(2));
|
||||
expect(sentMessages()[1].config).toMatchObject({
|
||||
featureValues: { fast_mode: true },
|
||||
providerOptions: { sandbox_mode: "read-only" },
|
||||
});
|
||||
});
|
||||
|
||||
test("a legacy workspace create routes its agent's options from its own model's controls", async () => {
|
||||
const { client, sentMessages, mock } = await connect({ creationLifecycle: true });
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "agent_update",
|
||||
payload: {
|
||||
kind: "upsert",
|
||||
agent: { ...agentSnapshot, provider: "codex", model: "mini", features: [] },
|
||||
},
|
||||
}),
|
||||
);
|
||||
void client
|
||||
.createWorkspace({
|
||||
source: { kind: "directory", path: "/repo" },
|
||||
agent: {
|
||||
config: {
|
||||
provider: "codex",
|
||||
cwd: "/repo",
|
||||
model: "gpt-5.5",
|
||||
providerOptions: { service_tier: "fast" },
|
||||
},
|
||||
},
|
||||
} as never)
|
||||
.catch(() => {});
|
||||
await vi.waitFor(() => expect(sentMessages()).toHaveLength(1));
|
||||
const [listing] = sentMessages();
|
||||
expect(listing).toMatchObject({
|
||||
type: "list_provider_features_request",
|
||||
draftConfig: { provider: "codex", cwd: "/repo", model: "gpt-5.5" },
|
||||
});
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "list_provider_features_response",
|
||||
payload: {
|
||||
provider: "codex",
|
||||
features: [speedFeature],
|
||||
error: null,
|
||||
fetchedAt: "2026-04-30T00:00:00.000Z",
|
||||
requestId: listing.requestId,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const sentTypes = () => sentMessages().map((message) => message.type);
|
||||
await vi.waitFor(() => expect(sentTypes()).toContain("workspace.create.request"));
|
||||
const created = sentMessages()[sentTypes().indexOf("workspace.create.request")];
|
||||
expect(created).toMatchObject({
|
||||
agent: { config: { featureValues: { service_tier: "fast" } } },
|
||||
});
|
||||
});
|
||||
|
||||
test("a legacy create lists the controls of its own model, whatever a snapshot showed", async () => {
|
||||
const { client, sentMessages, mock } = await connect({});
|
||||
// A Haiku agent has no Fast control; that says nothing about Opus.
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "agent_update",
|
||||
payload: {
|
||||
kind: "upsert",
|
||||
agent: { ...agentSnapshot, provider: "claude", model: "haiku", features: [] },
|
||||
},
|
||||
}),
|
||||
);
|
||||
void client
|
||||
.createAgent({
|
||||
config: {
|
||||
provider: "claude",
|
||||
cwd: "/repo",
|
||||
model: "opus",
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "high",
|
||||
providerOptions: { fast_mode: true, sandbox_mode: "read-only" },
|
||||
},
|
||||
})
|
||||
.catch(() => {});
|
||||
await vi.waitFor(() => expect(sentMessages()).toHaveLength(1));
|
||||
const [listing] = sentMessages();
|
||||
expect(listing).toMatchObject({
|
||||
type: "list_provider_features_request",
|
||||
draftConfig: {
|
||||
provider: "claude",
|
||||
cwd: "/repo",
|
||||
model: "opus",
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "high",
|
||||
},
|
||||
});
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "list_provider_features_response",
|
||||
payload: {
|
||||
provider: "claude",
|
||||
features: [{ type: "toggle", id: "fast_mode", label: "Fast", value: false }],
|
||||
error: null,
|
||||
fetchedAt: "2026-04-30T00:00:00.000Z",
|
||||
requestId: listing.requestId,
|
||||
},
|
||||
}),
|
||||
);
|
||||
await vi.waitFor(() => expect(sentMessages()).toHaveLength(2));
|
||||
expect(sentMessages()[1].config).toMatchObject({
|
||||
model: "opus",
|
||||
featureValues: { fast_mode: true },
|
||||
providerOptions: { sandbox_mode: "read-only" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -102,7 +102,6 @@ import type {
|
||||
WorkspaceSetupStatusResponseMessage,
|
||||
ListCommandsResponse,
|
||||
ListProviderFeaturesResponseMessage,
|
||||
ProviderControlsListResponseMessage,
|
||||
ListProviderModelsResponseMessage,
|
||||
ListProviderModesResponseMessage,
|
||||
ListAvailableProvidersResponse,
|
||||
@@ -165,6 +164,11 @@ import {
|
||||
FileTransferOpcode,
|
||||
TerminalStreamOpcode,
|
||||
type FileTransferFrame,
|
||||
assertPluginWireValue,
|
||||
decodePluginFrame,
|
||||
encodePluginInputFrame,
|
||||
isPluginFrameOpcode,
|
||||
PluginFrameOpcode,
|
||||
} from "@getpaseo/protocol/binary-frames/index";
|
||||
import {
|
||||
createRelayE2eeTransportFactory,
|
||||
@@ -185,10 +189,6 @@ import {
|
||||
normalizeProviderSnapshotUpdateMessage,
|
||||
normalizeProvidersSnapshotPayload,
|
||||
} from "./compat/normalize-provider-models.js";
|
||||
import {
|
||||
LegacyProviderOptions,
|
||||
usesLegacyProviderOptions,
|
||||
} from "./compat/legacy-provider-options.js";
|
||||
import { TerminalStreamRouter, type TerminalStreamEvent } from "./terminal-stream-router.js";
|
||||
import type {
|
||||
BrowserAutomationExecuteRequest,
|
||||
@@ -603,7 +603,6 @@ export interface FileUploadInput {
|
||||
export type FileUploadResult = FileUploadResponse["payload"];
|
||||
type FileDownloadTokenPayload = FileDownloadTokenResponse["payload"];
|
||||
type ListProviderFeaturesPayload = ListProviderFeaturesResponseMessage["payload"];
|
||||
export type ListProviderControlsPayload = ProviderControlsListResponseMessage["payload"];
|
||||
type ListProviderModelsPayload = ListProviderModelsResponseMessage["payload"];
|
||||
type ListProviderModesPayload = ListProviderModesResponseMessage["payload"];
|
||||
type ListAvailableProvidersPayload = ListAvailableProvidersResponse["payload"];
|
||||
@@ -630,7 +629,7 @@ type WriteProjectConfigPayload = Extract<
|
||||
type ListCommandsPayload = ListCommandsResponse["payload"];
|
||||
type ListCommandsDraftConfig = Pick<
|
||||
AgentSessionConfig,
|
||||
"provider" | "cwd" | "modeId" | "model" | "thinkingOptionId" | "featureValues" | "providerOptions"
|
||||
"provider" | "cwd" | "modeId" | "model" | "thinkingOptionId" | "featureValues"
|
||||
>;
|
||||
export interface WriteProjectConfigInput {
|
||||
repoRoot: string;
|
||||
@@ -2095,13 +2094,17 @@ export class DaemonClient {
|
||||
}
|
||||
|
||||
private sendSessionPayload(payload: SessionInboundMessage): Promise<void> {
|
||||
const wire = this.legacyProviderOptions()?.prepare(payload) ?? payload;
|
||||
return this.sendJsonMessage("session", payload.type, { type: "session", message: wire }, () => {
|
||||
if (!("requestId" in payload) || typeof payload.requestId !== "string") return;
|
||||
for (const waiter of this.waiters) {
|
||||
if (waiter.requestId === payload.requestId) waiter.submitted = true;
|
||||
}
|
||||
});
|
||||
return this.sendJsonMessage(
|
||||
"session",
|
||||
payload.type,
|
||||
{ type: "session", message: payload },
|
||||
() => {
|
||||
if (!("requestId" in payload) || typeof payload.requestId !== "string") return;
|
||||
for (const waiter of this.waiters) {
|
||||
if (waiter.requestId === payload.requestId) waiter.submitted = true;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private sendTransportFrame(
|
||||
@@ -2262,6 +2265,8 @@ export class DaemonClient {
|
||||
timeout?: number;
|
||||
select: (msg: SessionOutboundMessage) => T | null;
|
||||
options?: { skipQueue?: boolean };
|
||||
/** Sends the request in another form, such as a binary frame; defaults to `message`. */
|
||||
transmit?: () => Promise<void>;
|
||||
}): Promise<T> {
|
||||
const wire = this.owned.prepareRequest(params.message);
|
||||
const timeout = params.timeout ?? DEFAULT_SESSION_RPC_TIMEOUT_MS;
|
||||
@@ -2292,7 +2297,9 @@ export class DaemonClient {
|
||||
// The response deadline still applies while the transport waits for drain.
|
||||
void promise.catch(() => undefined);
|
||||
try {
|
||||
const sent = this.sendSessionMessageOrThrow(wire.message);
|
||||
const sent = params.transmit
|
||||
? params.transmit()
|
||||
: this.sendSessionMessageOrThrow(wire.message);
|
||||
const result = await Promise.race([promise, sent.then(() => promise)]);
|
||||
if (result.kind === "error") throw result.error;
|
||||
return result.value;
|
||||
@@ -2315,12 +2322,14 @@ export class DaemonClient {
|
||||
responseType: TResponseType;
|
||||
options?: { skipQueue?: boolean };
|
||||
selectPayload?: (payload: CorrelatedResponsePayload<TResponseType>) => TResult | null;
|
||||
transmit?: () => Promise<void>;
|
||||
}): Promise<TResult> {
|
||||
return this.sendRequest({
|
||||
requestId: params.requestId,
|
||||
message: params.message,
|
||||
timeout: params.timeout,
|
||||
options: params.options,
|
||||
...(params.transmit ? { transmit: params.transmit } : {}),
|
||||
select: (msg) => {
|
||||
const correlated = msg as CorrelatedResponseMessage;
|
||||
if (correlated.type !== params.responseType) {
|
||||
@@ -2652,6 +2661,7 @@ export class DaemonClient {
|
||||
resetSource = false;
|
||||
if (query.type === "workspace.setup.subscribe.request")
|
||||
this.requireWorkspaceSetupObservation();
|
||||
if (query.type === "plugin.rpc.subscribe.request") this.requirePluginSubscriptions();
|
||||
const requestId = this.createRequestId(options?.requestId);
|
||||
const request = SessionInboundMessageSchema.parse({ ...query, requestId });
|
||||
try {
|
||||
@@ -3269,44 +3279,14 @@ export class DaemonClient {
|
||||
);
|
||||
}
|
||||
if (options.background !== undefined) this.requireBackgroundWorkspaces();
|
||||
const config = resolveAgentConfig(options);
|
||||
const result = await this.creations.createAgent({
|
||||
...options,
|
||||
config: this.carriesLegacyOptions(config)
|
||||
? await this.routeLegacyCreateConfig(config)
|
||||
: config,
|
||||
config: resolveAgentConfig(options),
|
||||
});
|
||||
if (result.error || !result.agent) throw new Error(result.error ?? "Agent creation failed");
|
||||
return result.agent;
|
||||
}
|
||||
|
||||
/**
|
||||
* A legacy daemon reads control options as `featureValues`, and which options are controls
|
||||
* depends on the config (Claude's differ by model), so a create that carries options first lists
|
||||
* the controls for its own config. Callers never prime anything.
|
||||
*/
|
||||
private carriesLegacyOptions(config: AgentSessionConfig): boolean {
|
||||
return (
|
||||
this.legacyProviderOptions() !== null && Object.keys(config.providerOptions ?? {}).length > 0
|
||||
);
|
||||
}
|
||||
|
||||
private async routeLegacyCreateConfig(config: AgentSessionConfig): Promise<AgentSessionConfig> {
|
||||
const payload = await this.listProviderFeatures({
|
||||
provider: config.provider,
|
||||
cwd: config.cwd || "~",
|
||||
...(config.modeId ? { modeId: config.modeId } : {}),
|
||||
...(config.model ? { model: config.model } : {}),
|
||||
...(config.thinkingOptionId ? { thinkingOptionId: config.thinkingOptionId } : {}),
|
||||
featureValues: config.providerOptions,
|
||||
});
|
||||
if (payload.error) throw new Error(payload.error);
|
||||
return this.legacyOptions.routeCreateConfig(
|
||||
config,
|
||||
new Set((payload.features ?? []).map((feature) => feature.id)),
|
||||
);
|
||||
}
|
||||
|
||||
private async createLegacyAgent(
|
||||
options: CreateAgentRequestOptions,
|
||||
): Promise<AgentSnapshotPayload> {
|
||||
@@ -4097,24 +4077,6 @@ export class DaemonClient {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the agent's own provider options: top-level keys replace, `null` removes the key.
|
||||
* A daemon without `providerOptionControls` takes each key as a feature write.
|
||||
*/
|
||||
async setAgentOptions(
|
||||
agentId: string,
|
||||
patch: Record<string, unknown>,
|
||||
): Promise<AgentProviderNotice | null> {
|
||||
if (this.legacyProviderOptions()) {
|
||||
// COMPAT(providerOptionControls): added in v0.15.0, remove after 2027-05-01.
|
||||
for (const [featureId, value] of Object.entries(patch)) {
|
||||
await this.setAgentFeature(agentId, featureId, value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return this.applyAgentConfig(agentId, { options: patch });
|
||||
}
|
||||
|
||||
async setAgentThinkingOption(
|
||||
agentId: string,
|
||||
thinkingOptionId: string | null,
|
||||
@@ -5058,14 +5020,12 @@ export class DaemonClient {
|
||||
if (input.background !== undefined || input.callerAgentId) this.requireBackgroundWorkspaces();
|
||||
if (input.agent?.background !== undefined)
|
||||
throw new Error("Configure background on the workspace, not its initial agent.");
|
||||
let agentConfig = input.agent ? resolveAgentConfig(input.agent) : undefined;
|
||||
if (agentConfig && this.carriesLegacyOptions(agentConfig)) {
|
||||
agentConfig = await this.routeLegacyCreateConfig(agentConfig);
|
||||
}
|
||||
const result = await this.creations.createWorkspace({
|
||||
...input,
|
||||
requestId: resolvedRequestId,
|
||||
...(input.agent && agentConfig ? { agent: { ...input.agent, config: agentConfig } } : {}),
|
||||
...(input.agent
|
||||
? { agent: { ...input.agent, config: resolveAgentConfig(input.agent) } }
|
||||
: {}),
|
||||
});
|
||||
return {
|
||||
...result,
|
||||
@@ -5546,36 +5506,6 @@ export class DaemonClient {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The controls a draft agent would show and the options it would run with: `config.json`
|
||||
* defaults merged with the draft's own `providerOptions`, resolved by the daemon.
|
||||
*/
|
||||
async listProviderControls(
|
||||
draftConfig: ListCommandsDraftConfig,
|
||||
options?: { requestId?: string },
|
||||
): Promise<ListProviderControlsPayload> {
|
||||
const legacy = this.legacyProviderOptions();
|
||||
if (legacy) {
|
||||
const { providerOptions, ...rest } = draftConfig;
|
||||
const payload = await this.listProviderFeatures(
|
||||
{
|
||||
...rest,
|
||||
// A legacy daemon reads the options it exposes as features, whatever the others are.
|
||||
...(providerOptions ? { featureValues: providerOptions } : {}),
|
||||
},
|
||||
options,
|
||||
);
|
||||
return legacy.controlsResponse(payload);
|
||||
}
|
||||
return this.sendCorrelatedSessionRequest({
|
||||
requestId: options?.requestId,
|
||||
message: { type: "provider.controls.list.request", draftConfig },
|
||||
responseType: "provider.controls.list.response",
|
||||
timeout: 90000,
|
||||
});
|
||||
}
|
||||
|
||||
/** @deprecated Use `listProviderControls`. */
|
||||
async listProviderFeatures(
|
||||
draftConfig: ListCommandsDraftConfig,
|
||||
options?: { requestId?: string },
|
||||
@@ -6279,22 +6209,59 @@ export class DaemonClient {
|
||||
return payload.plugin;
|
||||
}
|
||||
|
||||
/**
|
||||
* A `Uint8Array` input or output crosses the wire as a binary frame. Any other value is JSON and
|
||||
* must not contain a `Uint8Array`.
|
||||
*/
|
||||
async invokePluginRpc(pluginId: string, method: string, input: unknown): Promise<unknown> {
|
||||
assertPluginWireValue(input, "input");
|
||||
const requestId = this.createRequestId();
|
||||
const payload = await this.sendCorrelatedSessionRequest({
|
||||
requestId,
|
||||
message: {
|
||||
type: "plugin.rpc.invoke.request",
|
||||
if (!(input instanceof Uint8Array)) {
|
||||
const payload = await this.sendCorrelatedSessionRequest({
|
||||
requestId,
|
||||
pluginId,
|
||||
method,
|
||||
input,
|
||||
},
|
||||
message: {
|
||||
type: "plugin.rpc.invoke.request",
|
||||
requestId,
|
||||
pluginId,
|
||||
method,
|
||||
input,
|
||||
},
|
||||
responseType: "plugin.rpc.invoke.response",
|
||||
});
|
||||
return payload.output;
|
||||
}
|
||||
this.requirePluginSubscriptions();
|
||||
const frame = encodePluginInputFrame({ requestId, pluginId, method, payload: input });
|
||||
const payload = await this.sendCorrelatedRequest({
|
||||
requestId,
|
||||
message: { type: "plugin.rpc.invoke.request", requestId, pluginId, method, input: null },
|
||||
responseType: "plugin.rpc.invoke.response",
|
||||
options: { skipQueue: true },
|
||||
transmit: () => this.sendBinaryFrame(frame),
|
||||
});
|
||||
return payload.output;
|
||||
}
|
||||
|
||||
/** One subscription to a plugin subscription handler; events arrive as updates and binary. */
|
||||
observePluginRpc(
|
||||
pluginId: string,
|
||||
method: string,
|
||||
input: unknown,
|
||||
options?: { signal?: AbortSignal },
|
||||
): OwnedSubscription<CorrelatedResponsePayload<"plugin.rpc.subscribe.response">> {
|
||||
assertPluginWireValue(input, "input");
|
||||
return this.observe(
|
||||
"plugin.rpc.subscribe.response",
|
||||
{ type: "plugin.rpc.subscribe.request", pluginId, method, input },
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
private requirePluginSubscriptions(): void {
|
||||
if (this.lastServerInfoMessage?.features?.pluginSubscriptions !== true)
|
||||
throw new Error("Update the host to use plugin subscriptions and binary plugin RPC");
|
||||
}
|
||||
|
||||
async respondToPermissionAndWait(
|
||||
agentId: string,
|
||||
requestId: string,
|
||||
@@ -6829,14 +6796,6 @@ export class DaemonClient {
|
||||
return requestId ?? crypto.randomUUID();
|
||||
}
|
||||
|
||||
private readonly legacyOptions = new LegacyProviderOptions();
|
||||
|
||||
/** The translation for a daemon without `providerOptionControls`; null for a current one. */
|
||||
private legacyProviderOptions(): LegacyProviderOptions | null {
|
||||
const info = this.lastServerInfoMessage;
|
||||
return info && usesLegacyProviderOptions(info) ? this.legacyOptions : null;
|
||||
}
|
||||
|
||||
getLastServerInfoMessage(): ServerInfoStatusPayload | null {
|
||||
return this.lastServerInfoMessage;
|
||||
}
|
||||
@@ -7065,6 +7024,23 @@ export class DaemonClient {
|
||||
}
|
||||
}
|
||||
|
||||
private handlePluginFrame(rawBytes: Uint8Array): void {
|
||||
const frame = decodePluginFrame(rawBytes);
|
||||
this.consecutiveLivenessFailures = 0;
|
||||
this.runtimeMetrics?.recordBinaryFrame("plugin", rawBytes.byteLength, 0);
|
||||
if (frame?.opcode === PluginFrameOpcode.Event) {
|
||||
this.owned.receiveBinary(frame.subscriptionId, frame.payload);
|
||||
return;
|
||||
}
|
||||
if (frame?.opcode === PluginFrameOpcode.Output) {
|
||||
// The binary form of plugin.rpc.invoke.response.
|
||||
this.resolveWaiters({
|
||||
type: "plugin.rpc.invoke.response",
|
||||
payload: { requestId: frame.requestId, output: frame.payload },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private tryHandleBinaryFrame(rawBytes: Uint8Array): boolean {
|
||||
const hostFrame = decodeHostRouteFrame(rawBytes);
|
||||
if (rawBytes[0] === HOST_ROUTE_OPCODE && !hostFrame) {
|
||||
@@ -7076,6 +7052,10 @@ export class DaemonClient {
|
||||
for (const handler of this.hostFrameListeners) handler(hostFrame);
|
||||
return true;
|
||||
}
|
||||
if (isPluginFrameOpcode(rawBytes[0])) {
|
||||
this.handlePluginFrame(rawBytes);
|
||||
return true;
|
||||
}
|
||||
const fileFrame = decodeFileTransferFrame(rawBytes);
|
||||
if (fileFrame) {
|
||||
this.traceInstant("paseo.ws.message.inbound", {
|
||||
@@ -7398,7 +7378,6 @@ export class DaemonClient {
|
||||
|
||||
private handleSessionMessage(msg: SessionOutboundMessage): void {
|
||||
msg = this.owned.normalize(msg);
|
||||
msg = this.legacyProviderOptions()?.normalize(msg) ?? msg;
|
||||
if (
|
||||
msg.type === "providers_snapshot_update" &&
|
||||
this.config.providerSnapshots !== "wire" &&
|
||||
|
||||
@@ -1601,12 +1601,7 @@ test("config actions delegate to existing daemon config RPCs", async () => {
|
||||
});
|
||||
|
||||
test("agent config maps provider/model and provider-native options to the daemon", async () => {
|
||||
const { client, ws } = await connectClient({
|
||||
providerUsageList: true,
|
||||
providersSnapshotCwd: true,
|
||||
ownedSubscriptions: true,
|
||||
providerOptionControls: true,
|
||||
});
|
||||
const { client, ws } = await connectClient();
|
||||
const createdAgent = createAgent({
|
||||
model: "gpt-5.4",
|
||||
currentModeId: "full-access",
|
||||
@@ -1638,8 +1633,8 @@ test("agent config maps provider/model and provider-native options to the daemon
|
||||
model: "gpt-5.4",
|
||||
modeId: "full-access",
|
||||
thinkingOptionId: "high",
|
||||
featureValues: { webSearch: true },
|
||||
providerOptions: {
|
||||
webSearch: true,
|
||||
approval_policy: "never",
|
||||
sandbox_mode: "workspace-write",
|
||||
sandbox_workspace_write: {
|
||||
|
||||
@@ -20,8 +20,6 @@ import type {
|
||||
ListCommandsResponse,
|
||||
ListProviderFeaturesRequestMessage,
|
||||
ListProviderFeaturesResponseMessage,
|
||||
ProviderControlsListRequestMessage,
|
||||
ProviderControlsListResponseMessage,
|
||||
ListProviderModelsResponseMessage,
|
||||
ProjectListRequestMessage,
|
||||
ProjectListResponseMessage,
|
||||
@@ -241,12 +239,8 @@ export interface PaseoAgentConfig {
|
||||
provider: string;
|
||||
modeId?: PaseoAgentSessionConfig["modeId"];
|
||||
thinkingOptionId?: PaseoAgentSessionConfig["thinkingOptionId"];
|
||||
/** @deprecated Put these in `options`; they are folded into it on send. */
|
||||
featureValues?: PaseoProviderFeatureValues;
|
||||
/**
|
||||
* JSON-safe provider settings, validated by the selected provider. They include the settings the
|
||||
* provider offers a composer control for, such as `service_tier` or `fast_mode`.
|
||||
*/
|
||||
/** JSON-safe provider-native settings, validated by the selected provider. */
|
||||
options?: PaseoAgentSessionConfig["providerOptions"];
|
||||
systemPrompt?: PaseoAgentSessionConfig["systemPrompt"];
|
||||
toolPolicy?: PaseoAgentSessionConfig["toolPolicy"];
|
||||
@@ -370,12 +364,7 @@ export interface PaseoAgentHandle {
|
||||
readonly activeTurn: NonNullable<PaseoAgent["activeTurn"]> | null;
|
||||
readonly lastUsage: NonNullable<PaseoAgent["lastUsage"]> | null;
|
||||
readonly lastError: NonNullable<PaseoAgent["lastError"]> | null;
|
||||
/** @deprecated Use `controls` and `options`. */
|
||||
readonly features: NonNullable<PaseoAgent["features"]> | null;
|
||||
/** The provider options the agent runs with: `config.json` defaults merged with its own. */
|
||||
readonly options: NonNullable<PaseoAgent["options"]> | null;
|
||||
/** How the provider wants its options drawn. Controls hold no value; read `options`. */
|
||||
readonly controls: NonNullable<PaseoAgent["controls"]> | null;
|
||||
readonly runtimeInfo: NonNullable<PaseoAgent["runtimeInfo"]> | null;
|
||||
readonly archivedAt: NonNullable<PaseoAgent["archivedAt"]> | null;
|
||||
readonly timeline: PaseoAgentTimelineHandle;
|
||||
@@ -388,12 +377,6 @@ export interface PaseoAgentHandle {
|
||||
reload(options?: { requestId?: string }): Promise<PaseoAgentRefetchResult | null>;
|
||||
send(text: string, options?: PaseoAgentSendOptions): Promise<void>;
|
||||
respondToPermission(options: PaseoAgentRespondToPermissionOptions): Promise<void>;
|
||||
/**
|
||||
* Changes the agent's own options: top-level keys replace, `null` removes the key so the
|
||||
* `config.json` default (or the provider's own default) applies again. Resolves once the
|
||||
* provider has applied the patch; a provider that cannot apply a key live rejects it.
|
||||
*/
|
||||
setOptions(patch: Record<string, unknown>): Promise<void>;
|
||||
/** Sends a prompt and resolves when that turn finishes or needs attention. */
|
||||
run(text: string, options?: PaseoAgentRunOptions): Promise<PaseoAgentRunResult>;
|
||||
/** Waits for the current turn, including one started with `prompt`. */
|
||||
@@ -430,21 +413,14 @@ export interface PaseoAgentActions {
|
||||
|
||||
export type PaseoProviderModelsResult = ListProviderModelsResponseMessage["payload"];
|
||||
export type PaseoProviderModesResult = ListProviderModesResponseMessage["payload"];
|
||||
type PaseoProviderControlsDraft = ProviderControlsListRequestMessage["draftConfig"];
|
||||
export interface PaseoProviderControlsInput extends Omit<
|
||||
PaseoProviderControlsDraft,
|
||||
type PaseoProviderFeaturesDraft = ListProviderFeaturesRequestMessage["draftConfig"];
|
||||
export interface PaseoProviderFeaturesInput extends Omit<
|
||||
PaseoProviderFeaturesDraft,
|
||||
"provider" | "model"
|
||||
> {
|
||||
/** Provider and model in `provider/model` format. */
|
||||
provider: string;
|
||||
}
|
||||
export type PaseoProviderControlsResult = ProviderControlsListResponseMessage["payload"];
|
||||
/** @deprecated Use `PaseoProviderControlsInput`. */
|
||||
export type PaseoProviderFeaturesInput = Omit<
|
||||
ListProviderFeaturesRequestMessage["draftConfig"],
|
||||
"provider" | "model"
|
||||
> & { provider: string };
|
||||
/** @deprecated Use `PaseoProviderControlsResult`. */
|
||||
export type PaseoProviderFeaturesResult = ListProviderFeaturesResponseMessage["payload"];
|
||||
export type PaseoProviderAvailabilityResult = ListAvailableProvidersResponse["payload"];
|
||||
export type PaseoProviderSnapshotResult = GetProvidersSnapshotResponseMessage["payload"];
|
||||
@@ -483,15 +459,6 @@ export interface PaseoProviderActions {
|
||||
provider: PaseoAgentProvider,
|
||||
options?: PaseoProviderListOptions,
|
||||
): Promise<PaseoProviderModesResult>;
|
||||
/**
|
||||
* The controls a draft agent would show and the options it would run with, resolved by the
|
||||
* daemon from `config.json` defaults and the draft's own `providerOptions`.
|
||||
*/
|
||||
listControls(
|
||||
draftConfig: PaseoProviderControlsInput,
|
||||
options?: { requestId?: string },
|
||||
): Promise<PaseoProviderControlsResult>;
|
||||
/** @deprecated Use `listControls`. */
|
||||
listFeatures(
|
||||
draftConfig: PaseoProviderFeaturesInput,
|
||||
options?: { requestId?: string },
|
||||
@@ -576,14 +543,7 @@ function toDaemonAgentCreateOptions(
|
||||
serverId?: string,
|
||||
): CreateAgentRequestOptions {
|
||||
const { config: agentConfig, cwd, parent, title, prompt, ...requestOptions } = options;
|
||||
const {
|
||||
provider: providerModel,
|
||||
options: ownOptions,
|
||||
featureValues,
|
||||
...runtimeConfig
|
||||
} = agentConfig;
|
||||
// COMPAT(featureValues): added in v0.15.0, remove after 2027-05-01. An explicit option wins.
|
||||
const providerOptions = featureValues ? { ...featureValues, ...ownOptions } : ownOptions;
|
||||
const { provider: providerModel, options: providerOptions, ...runtimeConfig } = agentConfig;
|
||||
const { provider, model } = parseProviderModel(providerModel);
|
||||
const relationship = parent ? encodeParent(parent, serverId) : {};
|
||||
return {
|
||||
@@ -816,10 +776,6 @@ export function createPaseoApi(
|
||||
const { provider, model } = parseProviderModel(providerModel);
|
||||
return daemonClient.listProviderFeatures({ ...draftConfig, provider, model }, options);
|
||||
},
|
||||
listControls: ({ provider: providerModel, ...draftConfig }, options) => {
|
||||
const { provider, model } = parseProviderModel(providerModel);
|
||||
return daemonClient.listProviderControls({ ...draftConfig, provider, model }, options);
|
||||
},
|
||||
listAvailable: (options) => daemonClient.listAvailableProviders(options),
|
||||
snapshot: (options) => daemonClient.getProvidersSnapshot(options),
|
||||
waitForReady: (options) =>
|
||||
@@ -1019,12 +975,6 @@ function createAgentHandleFactory(
|
||||
get features() {
|
||||
return current?.features ?? null;
|
||||
},
|
||||
get options() {
|
||||
return current?.options ?? null;
|
||||
},
|
||||
get controls() {
|
||||
return current?.controls ?? null;
|
||||
},
|
||||
get runtimeInfo() {
|
||||
return current?.runtimeInfo ?? null;
|
||||
},
|
||||
@@ -1046,9 +996,6 @@ function createAgentHandleFactory(
|
||||
send: async (text, options) => {
|
||||
await daemonClient.sendAgentMessage(id, text, options);
|
||||
},
|
||||
setOptions: async (patch) => {
|
||||
await daemonClient.setAgentOptions(id, patch);
|
||||
},
|
||||
respondToPermission: async ({ requestId, response }) => {
|
||||
await daemonClient.respondToPermission(id, requestId, response);
|
||||
},
|
||||
|
||||
@@ -204,15 +204,16 @@ export function createHostTransportFactory(
|
||||
}
|
||||
export function createHostClient(
|
||||
connection: string,
|
||||
config: Omit<DaemonClientConfig, "url" | "transportFactory"> & HostTransportOptions,
|
||||
config: Omit<DaemonClientConfig, "url"> & HostTransportOptions,
|
||||
budget?: HostTransportBudget,
|
||||
): DaemonClient {
|
||||
const target = parseHostTarget(connection);
|
||||
const { webSocketAgent, ...clientConfig } = config;
|
||||
const { webSocketAgent, transportFactory, ...clientConfig } = config;
|
||||
return new DaemonClient({
|
||||
...clientConfig,
|
||||
url: "ws://host-connector/ws",
|
||||
...(target.password ? { password: target.password } : {}),
|
||||
transportFactory: createHostTransportFactory(connection, budget, { webSocketAgent }),
|
||||
transportFactory:
|
||||
transportFactory ?? createHostTransportFactory(connection, budget, { webSocketAgent }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
"@types/node": "24.6.0",
|
||||
"@types/ws": "^8.5.14",
|
||||
"electron": "44.2.0",
|
||||
"electron-builder": "26.8.1",
|
||||
"electron-builder": "26.18.0",
|
||||
"typescript": "5.9.3",
|
||||
"unzip-crx-3": "^0.2.0",
|
||||
"vitest": "^4.1.6",
|
||||
|
||||
@@ -323,3 +323,68 @@ describe("agent session reload SDK boundary", () => {
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("plugin subscription SDK boundary", () => {
|
||||
it("types contracts, overloaded handlers, the client hook, and the client entry handle", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
import { defineRpc, defineSubscription, type SubscriptionEvent, type SubscriptionInput } from "@getpaseo/plugin";
|
||||
import type { PluginClientContext } from "@getpaseo/plugin/client";
|
||||
import { useRpc, useSubscription } from "@getpaseo/plugin/client";
|
||||
import type { PluginServerContext, PluginSubscriptionContext } from "@getpaseo/plugin/server";
|
||||
import { z } from "zod";
|
||||
const diffWatch = defineSubscription({
|
||||
name: "diff.watch",
|
||||
input: z.object({ a: z.string(), b: z.string() }),
|
||||
event: z.object({ path: z.string(), status: z.enum(["added", "modified", "deleted"]) }),
|
||||
});
|
||||
const frames = defineSubscription({
|
||||
name: "screen.capture",
|
||||
input: z.object({ display: z.number() }),
|
||||
event: z.union([z.instanceof(Uint8Array), z.object({ type: z.literal("resized"), width: z.number() })]),
|
||||
});
|
||||
const thumbnail = defineRpc({ name: "thumbnail.render", input: z.object({ path: z.string() }), output: z.instanceof(Uint8Array) });
|
||||
const input: SubscriptionInput<typeof diffWatch> = { a: "main", b: "HEAD" };
|
||||
const event: SubscriptionEvent<typeof diffWatch> = { path: "a.ts", status: "added" };
|
||||
function server(server: PluginServerContext) {
|
||||
server.handle(diffWatch, ({ a, b }, { push, signal, paseo }: PluginSubscriptionContext<SubscriptionEvent<typeof diffWatch>>) => {
|
||||
const pushed: Promise<void> = push({ path: a + b, status: "modified" });
|
||||
// @ts-expect-error events follow the contract
|
||||
void push({ path: 1, status: "modified" });
|
||||
signal.addEventListener("abort", () => undefined, { once: true });
|
||||
});
|
||||
server.handle(frames, async (_input, { push }) => {
|
||||
await push(new Uint8Array(4));
|
||||
await push({ type: "resized", width: 2 });
|
||||
});
|
||||
server.handle(thumbnail, ({ path }) => new Uint8Array(path.length));
|
||||
// @ts-expect-error subscription handlers receive push, not an output
|
||||
server.handle(diffWatch, () => ({ path: "a", status: "added" as const }) as unknown as number);
|
||||
}
|
||||
function Panel() {
|
||||
const state = useSubscription(diffWatch, { a: "main", b: "HEAD" }, (change) => {
|
||||
const status: "added" | "modified" | "deleted" = change.status;
|
||||
});
|
||||
if (state.status === "error") state.error.message;
|
||||
// @ts-expect-error the hook has no ready state, only live
|
||||
if (state.status === "ready") return null;
|
||||
useSubscription(frames, { display: 1 }, (event) => {
|
||||
if (event instanceof Uint8Array) event.byteLength;
|
||||
else event.width;
|
||||
});
|
||||
const render = useRpc(thumbnail);
|
||||
void render({ path: "x" }).then((png: Uint8Array) => png.byteLength);
|
||||
return null;
|
||||
}
|
||||
function client(client: PluginClientContext) {
|
||||
const controller = new AbortController();
|
||||
const remover = client.subscribe(diffWatch, { a: "main", b: "HEAD" }, (change) => change.path, { signal: controller.signal });
|
||||
const ready: Promise<void> = remover.ready;
|
||||
const released: Promise<void> = remover.release();
|
||||
remover();
|
||||
return () => {};
|
||||
}
|
||||
`),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,13 @@ import type { PaseoApi } from "@getpaseo/client";
|
||||
import type { AgentTimelineItem, JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { ZodType, input as ZodInput, output as ZodOutput } from "zod";
|
||||
import type { PluginFile } from "./file.js";
|
||||
import type { PluginRpcContract } from "../rpc.js";
|
||||
import type {
|
||||
PluginRpcContract,
|
||||
PluginSubscribeOptions,
|
||||
PluginSubscriptionContract,
|
||||
PluginSubscriptionHandle,
|
||||
PluginWireInput,
|
||||
} from "../rpc.js";
|
||||
import type {
|
||||
PluginButtonRegistration,
|
||||
PluginHeaderButtonContribution,
|
||||
@@ -203,6 +209,16 @@ export interface PluginClientContext extends PluginCommandCapabilities, PluginCl
|
||||
contribution: PluginTimelineRendererContribution<Schema>,
|
||||
): PluginCleanup;
|
||||
openPanel(id: string, options: PluginClientOpenPanelOptions): void;
|
||||
/**
|
||||
* Subscribes to a plugin subscription on this client's host. Paseo re-subscribes after a
|
||||
* reconnect and releases what is left when the plugin stops.
|
||||
*/
|
||||
subscribe<InputSchema extends ZodType, EventSchema extends ZodType>(
|
||||
contract: PluginSubscriptionContract<InputSchema, EventSchema>,
|
||||
input: PluginWireInput<ZodInput<InputSchema>>,
|
||||
onEvent: (event: ZodOutput<EventSchema>) => void,
|
||||
options?: PluginSubscribeOptions,
|
||||
): PluginSubscriptionHandle;
|
||||
}
|
||||
|
||||
export type PluginClientContribution = (client: PluginClientContext) => PluginCleanup;
|
||||
@@ -295,7 +311,7 @@ export interface PluginCommandCapabilities {
|
||||
paseo: PaseoApi;
|
||||
rpc<InputSchema extends ZodType, OutputSchema extends ZodType>(
|
||||
contract: PluginRpcContract<InputSchema, OutputSchema>,
|
||||
input: ZodInput<InputSchema>,
|
||||
input: PluginWireInput<ZodInput<InputSchema>>,
|
||||
): Promise<ZodOutput<OutputSchema>>;
|
||||
openScreen(input: PluginOpenScreenInput): void;
|
||||
/** @deprecated Use `openScreen`. */
|
||||
|
||||
@@ -8,7 +8,7 @@ export {
|
||||
import type { PluginAttachmentSourceContribution } from "../contracts.js";
|
||||
import { PluginRpcProvider } from "./rpc-context.js";
|
||||
import { PaseoApiProvider } from "./paseo-context.js";
|
||||
import { callPluginRpc } from "../rpc.js";
|
||||
import { callPluginRpc, subscribePluginRpc, type PluginSubscriptionObserver } from "../rpc.js";
|
||||
|
||||
export async function searchPluginAttachments(
|
||||
source: PluginAttachmentSourceContribution<PluginText>,
|
||||
@@ -19,7 +19,9 @@ export async function searchPluginAttachments(
|
||||
return PluginAttachmentSearchPayloadSchema.parseAsync(output);
|
||||
}
|
||||
|
||||
export { callPluginRpc, PaseoApiProvider, PluginRpcProvider };
|
||||
export { callPluginRpc, subscribePluginRpc, PaseoApiProvider, PluginRpcProvider };
|
||||
export type { PluginSubscriptionObserver };
|
||||
export type { PluginSubscribe } from "./rpc-context.js";
|
||||
|
||||
export {
|
||||
PluginTranslationRuntime,
|
||||
|
||||
@@ -71,7 +71,12 @@ export {
|
||||
} from "./file.js";
|
||||
export { usePaseo } from "./paseo-context.js";
|
||||
export { useAgent, useWorkspace } from "./client-state.js";
|
||||
export { useRpc } from "./rpc-context.js";
|
||||
export { useRpc, useSubscription, type PluginSubscriptionState } from "./rpc-context.js";
|
||||
export type {
|
||||
PluginSubscribeOptions,
|
||||
PluginSubscriptionClosed,
|
||||
PluginSubscriptionHandle,
|
||||
} from "../rpc.js";
|
||||
import type { SettingsDefinition } from "../settings.js";
|
||||
import type { SettingsState } from "./contracts.js";
|
||||
import type { ZodType } from "zod";
|
||||
|
||||
@@ -1,9 +1,34 @@
|
||||
import { createContext, useCallback, useContext, useMemo, type ReactNode } from "react";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import type { ZodType, input as ZodInput, output as ZodOutput } from "zod";
|
||||
import { callPluginRpc, type PluginRpcContract } from "../rpc.js";
|
||||
import {
|
||||
callPluginRpc,
|
||||
subscribePluginRpc,
|
||||
type PluginRpcContract,
|
||||
type PluginSubscriptionContract,
|
||||
type PluginSubscriptionHandle,
|
||||
type PluginSubscriptionObserver,
|
||||
type PluginWireInput,
|
||||
} from "../rpc.js";
|
||||
import { shallowEqual } from "./shallow.js";
|
||||
|
||||
export type PluginSubscribe = (
|
||||
method: string,
|
||||
input: unknown,
|
||||
observer: PluginSubscriptionObserver,
|
||||
) => PluginSubscriptionHandle;
|
||||
|
||||
export interface PluginRpcContextValue {
|
||||
invoke(method: string, input: unknown): Promise<unknown>;
|
||||
subscribe: PluginSubscribe;
|
||||
}
|
||||
|
||||
const PluginRpcContext = createContext<PluginRpcContextValue | null>(null);
|
||||
@@ -15,22 +40,100 @@ export function usePluginRpcContextValue(): PluginRpcContextValue | null {
|
||||
export function PluginRpcProvider({
|
||||
children,
|
||||
invoke,
|
||||
subscribe,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
invoke(method: string, input: unknown): Promise<unknown>;
|
||||
subscribe: PluginSubscribe;
|
||||
}) {
|
||||
const value = useMemo(() => ({ invoke }), [invoke]);
|
||||
const value = useMemo(() => ({ invoke, subscribe }), [invoke, subscribe]);
|
||||
return <PluginRpcContext.Provider value={value}>{children}</PluginRpcContext.Provider>;
|
||||
}
|
||||
|
||||
export function useRpc<InputSchema extends ZodType, OutputSchema extends ZodType>(
|
||||
contract: PluginRpcContract<InputSchema, OutputSchema>,
|
||||
): (input: ZodInput<InputSchema>) => Promise<ZodOutput<OutputSchema>> {
|
||||
): (input: PluginWireInput<ZodInput<InputSchema>>) => Promise<ZodOutput<OutputSchema>> {
|
||||
const context = usePluginRpcContextValue();
|
||||
if (!context) throw new Error("useRpc must run inside a contributed plugin surface");
|
||||
|
||||
return useCallback(
|
||||
(input: ZodInput<InputSchema>) => callPluginRpc(contract, context.invoke, input),
|
||||
(input: PluginWireInput<ZodInput<InputSchema>>) =>
|
||||
callPluginRpc(contract, context.invoke, input),
|
||||
[context, contract],
|
||||
);
|
||||
}
|
||||
|
||||
export type PluginSubscriptionState =
|
||||
| { status: "connecting" }
|
||||
| { status: "live" }
|
||||
/** The plugin's handler finished. The hook subscribes again when `input` changes. */
|
||||
| { status: "closed" }
|
||||
| { status: "error"; error: Error };
|
||||
|
||||
/**
|
||||
* Subscribes while the component is mounted. Re-subscribes when `input` changes by shallow
|
||||
* comparison; `onEvent` always runs the latest callback.
|
||||
*/
|
||||
export function useSubscription<InputSchema extends ZodType, EventSchema extends ZodType>(
|
||||
contract: PluginSubscriptionContract<InputSchema, EventSchema>,
|
||||
input: PluginWireInput<ZodInput<InputSchema>>,
|
||||
onEvent: (event: ZodOutput<EventSchema>) => void,
|
||||
): PluginSubscriptionState {
|
||||
const context = usePluginRpcContextValue();
|
||||
if (!context) throw new Error("useSubscription must run inside a contributed plugin surface");
|
||||
const subscribe = context.subscribe;
|
||||
const onEventRef = useRef(onEvent);
|
||||
onEventRef.current = onEvent;
|
||||
const stableInput = useShallowStable(input);
|
||||
const [state, setState] = useState<PluginSubscriptionState>({ status: "connecting" });
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setState({ status: "connecting" });
|
||||
let handle: PluginSubscriptionHandle;
|
||||
try {
|
||||
handle = subscribePluginRpc(
|
||||
contract,
|
||||
subscribe,
|
||||
stableInput,
|
||||
(event) => onEventRef.current(event),
|
||||
{
|
||||
onClosed: ({ error }) => {
|
||||
if (active) setState(error ? { status: "error", error } : CLOSED);
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
setState({ status: "error", error: toError(error) });
|
||||
return;
|
||||
}
|
||||
handle.ready.then(
|
||||
() => {
|
||||
if (active) setState((current) => (current.status === "connecting" ? LIVE : current));
|
||||
return undefined;
|
||||
},
|
||||
(error: unknown) => {
|
||||
if (active) setState({ status: "error", error: toError(error) });
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
active = false;
|
||||
handle();
|
||||
};
|
||||
}, [contract, subscribe, stableInput]);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
const LIVE: PluginSubscriptionState = { status: "live" };
|
||||
const CLOSED: PluginSubscriptionState = { status: "closed" };
|
||||
|
||||
function useShallowStable<Value>(value: Value): Value {
|
||||
const ref = useRef(value);
|
||||
if (!shallowEqual(ref.current, value)) ref.current = value;
|
||||
return ref.current;
|
||||
}
|
||||
|
||||
function toError(error: unknown): Error {
|
||||
return error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user