mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-19 23:05:21 +00:00
Compare commits
95
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ba207ff5ef | ||
|
|
c4d5915732 | ||
|
|
46f3ac94a3 | ||
|
|
4d5b761bc8 | ||
|
|
f9fde693cf | ||
|
|
173a1197db | ||
|
|
9e528c5776 | ||
|
|
3685a08c43 | ||
|
|
d165b07682 | ||
|
|
4e96928c64 | ||
|
|
5828fd5ce4 | ||
|
|
c22b97506f | ||
|
|
4216cdc7b5 | ||
|
|
e07440ae06 | ||
|
|
4713ba8819 | ||
|
|
762f5f023e | ||
|
|
50e830ac01 | ||
|
|
f2f8a84041 | ||
|
|
7ddaf59aa7 | ||
|
|
35e136314d | ||
|
|
f4ddcf7a5b | ||
|
|
46b0466f3b | ||
|
|
429cf715ca | ||
|
|
4196fae928 | ||
|
|
bbd93f76ee | ||
|
|
9e70f5665a | ||
|
|
f4210f39aa | ||
|
|
448f258583 | ||
|
|
152a5ae731 | ||
|
|
9f39663722 | ||
|
|
568bd447e3 | ||
|
|
41a36fa593 | ||
|
|
f91ec81f7c | ||
|
|
af2fb8ab35 | ||
|
|
cdc64ecfa4 | ||
|
|
042bc36ba5 | ||
|
|
4f6e71e8d6 | ||
|
|
51505a7d3b | ||
|
|
13c318838f | ||
|
|
d9fb2ffe93 | ||
|
|
0d82eed6b5 | ||
|
|
2ec0ac3c25 | ||
|
|
6cb9685a6d | ||
|
|
8a972b8c2e | ||
|
|
cc56b392de | ||
|
|
cb331532ad | ||
|
|
da994fb400 | ||
|
|
c4baf750f2 | ||
|
|
31a408d108 | ||
|
|
3be00f5105 | ||
|
|
6e704f803c | ||
|
|
949462f39b | ||
|
|
53d91d63da | ||
|
|
4709b49dc4 | ||
|
|
f938bf963d | ||
|
|
1131241b73 | ||
|
|
ce39ab6f09 | ||
|
|
c242f4d8db | ||
|
|
66aeff70d1 | ||
|
|
adf8badade | ||
|
|
1b45d92dac | ||
|
|
42ed0a8a99 | ||
|
|
d8fca6fdc6 | ||
|
|
77f97f82bc | ||
|
|
26b1e122ae | ||
|
|
7dfb63d0c4 | ||
|
|
5c81d08959 | ||
|
|
96b2bea130 | ||
|
|
33338be16e | ||
|
|
32230e24c5 | ||
|
|
d641cb5179 | ||
|
|
58094053dc | ||
|
|
3f75a11a49 | ||
|
|
f0807c5deb | ||
|
|
e0ff0959a1 | ||
|
|
591dd3bc92 | ||
|
|
8fb31cf8c0 | ||
|
|
b99d2a010d | ||
|
|
41011ddc60 | ||
|
|
e9d440259c | ||
|
|
0d697e6330 | ||
|
|
5413b8122c | ||
|
|
8960e76d19 | ||
|
|
218bcaaa6b | ||
|
|
30cc0a8c21 | ||
|
|
a362664f47 | ||
|
|
20ce734367 | ||
|
|
ca2bdd66eb | ||
|
|
1aaac5b231 | ||
|
|
b60b74384b | ||
|
|
034f639c88 | ||
|
|
55e8cff9f4 | ||
|
|
06be203c5c | ||
|
|
007a8e36ae | ||
|
|
eb6bed8447 |
@@ -92,6 +92,7 @@ Each agent is stored as a separate JSON file, grouped by project directory.
|
|||||||
| `lastUserMessageAt` | `string?` (ISO 8601) | Last user message timestamp |
|
| `lastUserMessageAt` | `string?` (ISO 8601) | Last user message timestamp |
|
||||||
| `title` | `string?` | User-visible title |
|
| `title` | `string?` | User-visible title |
|
||||||
| `labels` | `Record<string, string>` | Key-value labels (default `{}`). Paseo uses `paseo.parent-agent-id` for parentage and client-scoped `paseo.open-agent-tab.*` labels while managed subagent tabs are open — see [agent-lifecycle.md](./agent-lifecycle.md) |
|
| `labels` | `Record<string, string>` | Key-value labels (default `{}`). Paseo uses `paseo.parent-agent-id` for parentage and client-scoped `paseo.open-agent-tab.*` labels while managed subagent tabs are open — see [agent-lifecycle.md](./agent-lifecycle.md) |
|
||||||
|
| `metadata` | `Record<string, JsonValue>` | Plugin-owned data (default `{}`). Paseo stores and forwards it and never reads a key. Set at creation or through `agent.metadata.update.request`; `null` in a patch removes a key |
|
||||||
| `lastStatus` | `AgentStatus` | One of: `"initializing"`, `"idle"`, `"running"`, `"error"`, `"closed"`. `closed` means the record is resumable but has no live provider runtime; archive remains represented separately by `archivedAt`. |
|
| `lastStatus` | `AgentStatus` | One of: `"initializing"`, `"idle"`, `"running"`, `"error"`, `"closed"`. `closed` means the record is resumable but has no live provider runtime; archive remains represented separately by `archivedAt`. |
|
||||||
| `lastModeId` | `string?` | Last active mode ID |
|
| `lastModeId` | `string?` | Last active mode ID |
|
||||||
| `config` | `SerializableConfig?` | Agent session configuration (see below) |
|
| `config` | `SerializableConfig?` | Agent session configuration (see below) |
|
||||||
@@ -478,6 +479,7 @@ Array of workspace records. A workspace is a specific working directory within a
|
|||||||
| `archivedAt` | `string \| null` (ISO 8601) | Soft-delete; required nullable |
|
| `archivedAt` | `string \| null` (ISO 8601) | Soft-delete; required nullable |
|
||||||
| `autoArchivedChangeRequestUrl` | `string \| null` | Change request whose merged state triggered auto-archive. Restore replaces it with the current merged change request, when present, so repeated snapshots cannot archive the workspace again. |
|
| `autoArchivedChangeRequestUrl` | `string \| null` | Change request whose merged state triggered auto-archive. Restore replaces it with the current merged change request, when present, so repeated snapshots cannot archive the workspace again. |
|
||||||
| `labels` | `string[]?` | Normalized display names assigned from this host's shared label catalog. Missing means unlabelled. |
|
| `labels` | `string[]?` | Normalized display names assigned from this host's shared label catalog. Missing means unlabelled. |
|
||||||
|
| `metadata` | `Record<string, JsonValue>` | Plugin-owned data (default `{}`). Paseo stores and forwards it and never reads a key. Set at creation or through `workspace.metadata.update.request`. |
|
||||||
| `pinnedAt` | `string \| null` (ISO 8601) | Pinned-to-top-of-sidebar timestamp; null means "not pinned" |
|
| `pinnedAt` | `string \| null` (ISO 8601) | Pinned-to-top-of-sidebar timestamp; null means "not pinned" |
|
||||||
| `untrustedSource` | `{ kind: "change_request", forge, number, headRepository }?` | Provenance captured when a cross-repository change request creates the workspace. Missing means repository automation is allowed; explicit setup removes the field. |
|
| `untrustedSource` | `{ kind: "change_request", forge, number, headRepository }?` | Provenance captured when a cross-repository change request creates the workspace. Missing means repository automation is allowed; explicit setup removes the field. |
|
||||||
|
|
||||||
|
|||||||
+43
-3
@@ -474,6 +474,9 @@ path shape: a plugin can place a worktree several directories below the default
|
|||||||
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
|
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
|
||||||
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
|
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
|
||||||
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
|
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
|
||||||
|
The same holds for a hook that runs inside an agent's lifecycle lane: an `agent.open.before` hook
|
||||||
|
that awaits a write to the agent being opened (`setMetadata`, `setLabels`) waits on the open, which
|
||||||
|
waits on the hook. The hooks reference tells plugin authors to start such a write without awaiting it.
|
||||||
|
|
||||||
## Contribute a provider
|
## Contribute a provider
|
||||||
|
|
||||||
@@ -529,13 +532,21 @@ need no change. See [catalogue ownership](providers.md#provider-snapshot-refresh
|
|||||||
`send()` resolves after acceptance. Publish operation completion, prompt disposition, turn state,
|
`send()` resolves after acceptance. Publish operation completion, prompt disposition, turn state,
|
||||||
configuration, permissions, persistence, and complete timeline snapshots through `onEvent()`.
|
configuration, permissions, persistence, and complete timeline snapshots through `onEvent()`.
|
||||||
Route messages, structured commands, steering, and command side effects through `session.prompt`.
|
Route messages, structured commands, steering, and command side effects through `session.prompt`.
|
||||||
Provider settings are toggle/select data that Paseo renders in the composer. Keep private options in
|
A provider's configuration is the opaque `ProviderSessionConfig.providerOptions` object on
|
||||||
the opaque `ProviderSessionConfig.providerOptions` object on `session.open`.
|
`session.open`. It contains the provider defaults and per-agent overrides merged by the daemon.
|
||||||
It contains the provider defaults and per-agent overrides merged by the daemon.
|
|
||||||
Validate and apply it inside the provider; core does not know your option shape.
|
Validate and apply it inside the provider; core does not know your option shape.
|
||||||
See [provider options](custom-providers.md#provider-options) for configuration and
|
See [provider options](custom-providers.md#provider-options) for configuration and
|
||||||
merge semantics.
|
merge semantics.
|
||||||
|
|
||||||
|
The provider draws some of those keys in the composer by reporting `controls` and the values it runs
|
||||||
|
(`providerOptions`) in `session.config`. A running-agent change arrives as
|
||||||
|
`session.configure` with `changes.providerOptions` and follows the same apply-or-throw contract as
|
||||||
|
built-in providers ([options flow](providers.md#options-flow)). `PluginAgentSession` in
|
||||||
|
`packages/server/src/server/agent/plugin-provider.ts` is that adapter. A provider still reporting
|
||||||
|
`settings` is read through `plugin-provider-options.ts`, which turns each setting into a control and
|
||||||
|
its value into an option and is sent both shapes in `session.configure`; delete it with
|
||||||
|
`COMPAT(plugin-provider-settings)`. The ACP shim still reports `settings`.
|
||||||
|
|
||||||
Providers add an optional veto to daemon baseline cleanup through the per-session
|
Providers add an optional veto to daemon baseline cleanup through the per-session
|
||||||
[runtime safety query](../public-docs/plugins/providers.md#permit-idle-runtime-cleanup).
|
[runtime safety query](../public-docs/plugins/providers.md#permit-idle-runtime-cleanup).
|
||||||
The daemon calls the same `AgentSession.canStopRuntime()` interface for built-ins and plugins;
|
The daemon calls the same `AgentSession.canStopRuntime()` interface for built-ins and plugins;
|
||||||
@@ -654,6 +665,35 @@ Mounted surfaces and command invocations have shorter API lifetimes.
|
|||||||
Keep the client entry synchronous: return its cleanup function immediately and start asynchronous
|
Keep the client entry synchronous: return its cleanup function immediately and start asynchronous
|
||||||
work inside it. See the maintained [composer pill example](../plugin-examples/local-plugin/client/main.tsx).
|
work inside it. See the maintained [composer pill example](../plugin-examples/local-plugin/client/main.tsx).
|
||||||
|
|
||||||
|
## Contribute composer items
|
||||||
|
|
||||||
|
`addComposerItem` mounts a plugin component in the agent, draft and New workspace composers. The
|
||||||
|
public contract is the [composer items reference](../public-docs/plugins/reference.md#composer-items).
|
||||||
|
|
||||||
|
The composer is two contexts, provided by two owners (`packages/app/src/composer/session.tsx`).
|
||||||
|
`Composer` provides `ComposerInput` (prompt and attachments). `AgentControls` and
|
||||||
|
`DraftAgentControls` provide `ComposerAgent` (provider, model, mode, thinking, options, metadata and
|
||||||
|
their commands). `toPluginComposer` (`packages/app/src/plugins/composer-items/`) joins them into the
|
||||||
|
`PluginComposer` an item reads, so a plugin cannot tell which composer a command reaches. Add a
|
||||||
|
capability to `ComposerAgent` and both implementations; never branch on `context` in the model.
|
||||||
|
|
||||||
|
Plugin `Toggle`, `Select` and `Action`, the thinking select and provider option controls all
|
||||||
|
render through `ComposerControl` (`packages/app/src/composer/agent-controls/composer-control.tsx`),
|
||||||
|
a toolbar icon or a row in the overflow sheet. Model and mode stay specialized but share its trigger,
|
||||||
|
density and overflow. Plugin items count in the density presence in `layout.ts`, so a composer
|
||||||
|
condenses to make room for them. A custom component renders wherever its item is placed, and an
|
||||||
|
item that renders nothing still counts for density; there is no registration for either.
|
||||||
|
|
||||||
|
A command runs against the owner's current state, not the render that built the callback. The
|
||||||
|
draft's form (`openAgentForm`) and options (`openDraftOptions`) are plain stores for that reason,
|
||||||
|
and `draftComposerAgent` rejects a provider the host does not offer or a model its loaded catalog
|
||||||
|
does not list. `ComposerControl` owns the pending state and the error toast for callbacks that
|
||||||
|
return a promise.
|
||||||
|
|
||||||
|
The overflow sheet's content portals to the app root, away from the composer. Pass
|
||||||
|
`useComposerSheetBridge()` as the sheet's `contextBridge`, or `useComposer()` returns nothing and
|
||||||
|
the sheet draws no plugin rows.
|
||||||
|
|
||||||
## Contribute timeline items
|
## Contribute timeline items
|
||||||
|
|
||||||
Timeline transformers and renderers are client contributions. The daemon's canonical rows and
|
Timeline transformers and renderers are client contributions. The daemon's canonical rows and
|
||||||
|
|||||||
+62
-3
@@ -30,6 +30,65 @@ 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 defaults and merge rules, and the [SDK guide](../public-docs/sdk/provider-options.md)
|
||||||
for native keys and examples.
|
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
|
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
|
closed for Hub unattended execution until it can approve one exact injected MCP
|
||||||
server and tool identity without approving native tools.
|
server and tool identity without approving native tools.
|
||||||
@@ -115,7 +174,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.
|
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 `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.
|
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.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -478,7 +537,7 @@ interface AgentSession {
|
|||||||
readonly provider: AgentProvider;
|
readonly provider: AgentProvider;
|
||||||
readonly id: string | null;
|
readonly id: string | null;
|
||||||
readonly capabilities: AgentCapabilityFlags;
|
readonly capabilities: AgentCapabilityFlags;
|
||||||
readonly features?: AgentFeature[];
|
readonly controls?: AgentOptionControl[];
|
||||||
run(prompt: AgentPromptInput, options?: AgentRunOptions): Promise<AgentRunResult>;
|
run(prompt: AgentPromptInput, options?: AgentRunOptions): Promise<AgentRunResult>;
|
||||||
startTurn(prompt: AgentPromptInput, options?: AgentRunOptions): Promise<{ turnId: string }>;
|
startTurn(prompt: AgentPromptInput, options?: AgentRunOptions): Promise<{ turnId: string }>;
|
||||||
steerActiveTurn?(prompt: AgentPromptInput, options: SteerActiveTurnOptions): Promise<SteerResult>;
|
steerActiveTurn?(prompt: AgentPromptInput, options: SteerActiveTurnOptions): Promise<SteerResult>;
|
||||||
@@ -500,7 +559,7 @@ interface AgentSession {
|
|||||||
listCommands?(): Promise<AgentSlashCommand[]>;
|
listCommands?(): Promise<AgentSlashCommand[]>;
|
||||||
setModel?(modelId: string | null): Promise<void>;
|
setModel?(modelId: string | null): Promise<void>;
|
||||||
setThinkingOption?(thinkingOptionId: string | null): Promise<void | AgentProviderNotice>;
|
setThinkingOption?(thinkingOptionId: string | null): Promise<void | AgentProviderNotice>;
|
||||||
setFeature?(featureId: string, value: unknown): Promise<void>;
|
applyOptions?(options: ProviderOptions): Promise<void>;
|
||||||
tryHandleOutOfBand?(prompt: AgentPromptInput): {
|
tryHandleOutOfBand?(prompt: AgentPromptInput): {
|
||||||
run(ctx: { emit: (event: AgentStreamEvent) => void }): Promise<void>;
|
run(ctx: { emit: (event: AgentStreamEvent) => void }): Promise<void>;
|
||||||
} | null;
|
} | null;
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ async function readProviderFeaturePreferences(page: Page, provider: string): Pro
|
|||||||
const raw = localStorage.getItem(preferencesKey);
|
const raw = localStorage.getItem(preferencesKey);
|
||||||
if (!raw) return null;
|
if (!raw) return null;
|
||||||
const preferences = JSON.parse(raw) as FormPreferences;
|
const preferences = JSON.parse(raw) as FormPreferences;
|
||||||
return preferences.providerPreferences?.[providerId]?.featureValues ?? null;
|
return preferences.providerPreferences?.[providerId]?.options ?? null;
|
||||||
},
|
},
|
||||||
{ preferencesKey: CREATE_AGENT_PREFERENCES_KEY, providerId: provider },
|
{ preferencesKey: CREATE_AGENT_PREFERENCES_KEY, providerId: provider },
|
||||||
);
|
);
|
||||||
@@ -145,7 +145,7 @@ test.describe("Agent profiles repair modeless provider preferences", () => {
|
|||||||
provider: featureProviderId,
|
provider: featureProviderId,
|
||||||
model: featureModelId,
|
model: featureModelId,
|
||||||
modeId: "bypassPermissions",
|
modeId: "bypassPermissions",
|
||||||
featureValues: { fast_mode: true },
|
options: { fast_mode: true },
|
||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
const provider = await seedModelProvider({
|
const provider = await seedModelProvider({
|
||||||
@@ -181,7 +181,7 @@ test.describe("Agent profiles repair modeless provider preferences", () => {
|
|||||||
expect(createAgentRequest).toMatchObject({
|
expect(createAgentRequest).toMatchObject({
|
||||||
config: {
|
config: {
|
||||||
provider: featureProviderId,
|
provider: featureProviderId,
|
||||||
featureValues: { fast_mode: true },
|
providerOptions: { fast_mode: true },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { test } from "../support/fixtures";
|
||||||
|
import { withComposerControlsExample } from "../support/helpers/plugin-composer-items";
|
||||||
|
|
||||||
|
test("a narrow composer's overflow sheet shows a plugin item's row", async ({ page }) => {
|
||||||
|
test.setTimeout(120_000);
|
||||||
|
await withComposerControlsExample(page, async (composer) => {
|
||||||
|
await composer.narrowTheWindow();
|
||||||
|
await composer.openAgentFeatures();
|
||||||
|
await composer.expectFeatureRow("Needs review");
|
||||||
|
await composer.expectFeatureRow("Insert checklist");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { expect, test, type Page } from "@playwright/test";
|
||||||
|
import { gotoAppShell } from "./app";
|
||||||
|
import { openAgentRoute } from "./mock-agent";
|
||||||
|
import { connectNewWorkspaceDaemonClient } from "./new-workspace";
|
||||||
|
import { copyPluginExample } from "./plugin-fixture";
|
||||||
|
import { seedWorkspace } from "./seed-client";
|
||||||
|
|
||||||
|
const PLUGIN_ID = "composer-controls-example";
|
||||||
|
const NARROW = { width: 500, height: 800 };
|
||||||
|
|
||||||
|
/** Runs `run` in an agent's composer with the composer-controls example installed. */
|
||||||
|
export async function withComposerControlsExample(
|
||||||
|
page: Page,
|
||||||
|
run: (composer: {
|
||||||
|
narrowTheWindow(): Promise<void>;
|
||||||
|
openAgentFeatures(): Promise<void>;
|
||||||
|
expectFeatureRow(name: string): Promise<void>;
|
||||||
|
}) => Promise<void>,
|
||||||
|
) {
|
||||||
|
const workspace = await seedWorkspace({
|
||||||
|
repoPrefix: "composer-items-",
|
||||||
|
title: "Composer items",
|
||||||
|
});
|
||||||
|
const agent = await workspace.client.createAgent({
|
||||||
|
provider: "mock",
|
||||||
|
cwd: workspace.repoPath,
|
||||||
|
workspaceId: workspace.workspaceId,
|
||||||
|
title: "Composer items agent",
|
||||||
|
model: "ten-second-stream",
|
||||||
|
modeId: "load-test",
|
||||||
|
});
|
||||||
|
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||||
|
const previous = await client.getDaemonConfig();
|
||||||
|
const example = await copyPluginExample("composer-controls");
|
||||||
|
try {
|
||||||
|
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||||
|
await client.installDirectoryPlugin(example.directory);
|
||||||
|
await gotoAppShell(page);
|
||||||
|
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: agent.id });
|
||||||
|
await run({
|
||||||
|
narrowTheWindow: () =>
|
||||||
|
test.step("narrow the window until the composer folds its controls away", () =>
|
||||||
|
page.setViewportSize(NARROW)),
|
||||||
|
openAgentFeatures: () =>
|
||||||
|
test.step("open the agent features sheet", async () => {
|
||||||
|
await page.getByRole("button", { name: "Open agent features", exact: true }).click();
|
||||||
|
}),
|
||||||
|
expectFeatureRow: (name) =>
|
||||||
|
test.step(`the sheet has a row for "${name}"`, () =>
|
||||||
|
expect(page.getByRole("button", { name, exact: true })).toBeVisible()),
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await client.removePlugin(PLUGIN_ID);
|
||||||
|
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled });
|
||||||
|
await client.close();
|
||||||
|
await example.cleanup();
|
||||||
|
await workspace.cleanup();
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -18,7 +18,7 @@ export interface AgentCommandsDraftConfig {
|
|||||||
modeId?: string;
|
modeId?: string;
|
||||||
model?: string;
|
model?: string;
|
||||||
thinkingOptionId?: string;
|
thinkingOptionId?: string;
|
||||||
featureValues?: Record<string, unknown>;
|
providerOptions?: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function normalizeAgentCommandsCwd(cwd: string): string {
|
export function normalizeAgentCommandsCwd(cwd: string): string {
|
||||||
@@ -98,7 +98,7 @@ export function draftAgentCommandsQueryKey(input: {
|
|||||||
"thinking",
|
"thinking",
|
||||||
draftConfig.thinkingOptionId ?? null,
|
draftConfig.thinkingOptionId ?? null,
|
||||||
"features",
|
"features",
|
||||||
draftConfig.featureValues ?? null,
|
draftConfig.providerOptions ?? null,
|
||||||
] as const;
|
] as const;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,189 @@
|
|||||||
|
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 }, [
|
||||||
|
{ type: "toggle", key: "fast_mode", label: "Fast" },
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
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("stops sending a toggle once the model in use draws no control for it", () => {
|
||||||
|
const FAST_MODE: AgentOptionControl = { type: "toggle", key: "fast_mode", label: "Fast" };
|
||||||
|
const model = openDraftOptions({ provider: "claude", seed: { sandbox_mode: "read-only" } });
|
||||||
|
model.applyResolved(answer("claude", "opus", { fast_mode: false }, [FAST_MODE]));
|
||||||
|
model.setOption("fast_mode", true);
|
||||||
|
expect(ownDraftOptions(model.getState())).toEqual({
|
||||||
|
sandbox_mode: "read-only",
|
||||||
|
fast_mode: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// The form moves to a model without Fast; its answer lists no such control.
|
||||||
|
model.applyResolved(answer("claude", "haiku", {}, []));
|
||||||
|
|
||||||
|
expect(ownDraftOptions(model.getState())).toEqual({ sandbox_mode: "read-only" });
|
||||||
|
|
||||||
|
// Back on a model that draws the control, the toggle applies again. The daemon's answer
|
||||||
|
// for the request without it said Fast was off; the request that carries it follows.
|
||||||
|
model.applyResolved(answer("claude", "opus-again", { fast_mode: false }, [FAST_MODE]));
|
||||||
|
expect(ownDraftOptions(model.getState())).toEqual({
|
||||||
|
sandbox_mode: "read-only",
|
||||||
|
fast_mode: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("always sends an option no control has drawn", () => {
|
||||||
|
const FAST_MODE: AgentOptionControl = { type: "toggle", key: "fast_mode", label: "Fast" };
|
||||||
|
const model = openDraftOptions({ provider: "claude" });
|
||||||
|
model.applyResolved(answer("claude", "k1", {}, [FAST_MODE]));
|
||||||
|
|
||||||
|
model.setOption("token_budget", 5);
|
||||||
|
|
||||||
|
expect(ownDraftOptions(model.getState())).toEqual({ token_budget: 5 });
|
||||||
|
model.applyResolved(answer("claude", "k2", {}, []));
|
||||||
|
expect(ownDraftOptions(model.getState())).toEqual({ token_budget: 5 });
|
||||||
|
});
|
||||||
|
|
||||||
|
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,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
import type {
|
||||||
|
AgentOptionControl,
|
||||||
|
AgentSessionConfig,
|
||||||
|
ProviderOptions,
|
||||||
|
} from "@getpaseo/protocol/agent-types";
|
||||||
|
import { withoutLostControls } from "./lost-controls";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* An edit of `null` removes the key from every layer, the way a patch does on a running agent, so
|
||||||
|
* the provider's default applies again.
|
||||||
|
*
|
||||||
|
* 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;
|
||||||
|
/** Every key an answer for this provider has drawn as a control. */
|
||||||
|
drawn: ReadonlySet<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
/**
|
||||||
|
* The provider the draft's form has now. An edit belongs to it even before the screen has
|
||||||
|
* rendered the change, so `setOption` observes it first.
|
||||||
|
*/
|
||||||
|
currentProvider?: () => string | null;
|
||||||
|
}): DraftOptionsModel {
|
||||||
|
let state: DraftOptionsState = {
|
||||||
|
provider: input.provider,
|
||||||
|
seed: input.seed ?? {},
|
||||||
|
remembered: {},
|
||||||
|
edits: {},
|
||||||
|
resolved: null,
|
||||||
|
drawn: new Set(),
|
||||||
|
};
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
function observeProvider(provider: string | null): void {
|
||||||
|
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, drawn: new Set() };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
getState: () => state,
|
||||||
|
subscribe: (listener) => {
|
||||||
|
listeners.add(listener);
|
||||||
|
return () => {
|
||||||
|
listeners.delete(listener);
|
||||||
|
};
|
||||||
|
},
|
||||||
|
observeProvider,
|
||||||
|
applyProfile: (profile) =>
|
||||||
|
publish((current) => ({
|
||||||
|
...current,
|
||||||
|
provider: profile.provider,
|
||||||
|
seed: profile.options,
|
||||||
|
edits: {},
|
||||||
|
resolved: current.provider === profile.provider ? current.resolved : null,
|
||||||
|
drawn: current.provider === profile.provider ? current.drawn : new Set(),
|
||||||
|
})),
|
||||||
|
setRemembered: (remembered) => publish((current) => ({ ...current, remembered })),
|
||||||
|
setOption: (key, value) => {
|
||||||
|
if (input.currentProvider) observeProvider(input.currentProvider());
|
||||||
|
publish((current) =>
|
||||||
|
Object.is(current.edits[key], value)
|
||||||
|
? current
|
||||||
|
: { ...current, edits: { ...current.edits, [key]: value } },
|
||||||
|
);
|
||||||
|
},
|
||||||
|
applyResolved: (resolved) =>
|
||||||
|
publish((current) => ({
|
||||||
|
...current,
|
||||||
|
resolved,
|
||||||
|
drawn: new Set([...current.drawn, ...resolved.controls.map((control) => control.key)]),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
* An edit of a key an earlier answer drew as a control stops applying when the latest answer
|
||||||
|
* draws none for it (the model changed to one without that control) and applies again when a
|
||||||
|
* control for it returns. An edit of a key no answer has drawn is an option without a control
|
||||||
|
* and always applies.
|
||||||
|
*/
|
||||||
|
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 edits = withoutLostControls(state.edits, state.drawn, controlKeys);
|
||||||
|
const own = withoutRemovals({ ...state.seed, ...remembered, ...edits });
|
||||||
|
return Object.keys(own).length > 0 ? own : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function withoutRemovals(options: ProviderOptions): ProviderOptions {
|
||||||
|
return Object.fromEntries(Object.entries(options).filter(([, value]) => value !== null));
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DraftControlsRequest = Pick<
|
||||||
|
AgentSessionConfig,
|
||||||
|
"provider" | "cwd" | "modeId" | "model" | "thinkingOptionId" | "providerOptions"
|
||||||
|
>;
|
||||||
|
|
||||||
|
/** What the draft's form has chosen; the options come from the model. */
|
||||||
|
export interface DraftControlsForm {
|
||||||
|
provider: string | null;
|
||||||
|
cwd: string;
|
||||||
|
modeId?: string | null;
|
||||||
|
modelId?: string | null;
|
||||||
|
thinkingOptionId?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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: DraftControlsForm,
|
||||||
|
): 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
|
||||||
|
: withoutRemovals({ ...resolved.options, ...state.edits }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const NO_OPTIONS: ProviderOptions = {};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The options the draft will create with, for a plugin or a control to read: the daemon's answer
|
||||||
|
* for this provider when there is one, otherwise the draft's own layers, so an edit shows before
|
||||||
|
* the daemon has answered.
|
||||||
|
*/
|
||||||
|
export function shownDraftOptions(
|
||||||
|
state: DraftOptionsState,
|
||||||
|
current: { provider: string | null; requestKey: string },
|
||||||
|
): ProviderOptions {
|
||||||
|
return viewDraftOptions(state, current)?.options ?? ownDraftOptions(state) ?? NO_OPTIONS;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { Settings2 } from "lucide-react-native";
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { getAgentFeatureIcon } from "./icons";
|
||||||
|
|
||||||
|
describe("getAgentFeatureIcon", () => {
|
||||||
|
it("draws the Lucide icon a plugin provider names", () => {
|
||||||
|
const icon = getAgentFeatureIcon("Mic");
|
||||||
|
expect(icon).not.toBe(Settings2);
|
||||||
|
expect(getAgentFeatureIcon("Mic")).toBe(icon);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to the generic icon for a missing or unknown name", () => {
|
||||||
|
expect(getAgentFeatureIcon()).toBe(Settings2);
|
||||||
|
expect(getAgentFeatureIcon("not-an-icon")).toBe(Settings2);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
ShieldQuestionMark,
|
ShieldQuestionMark,
|
||||||
Zap,
|
Zap,
|
||||||
} from "lucide-react-native";
|
} from "lucide-react-native";
|
||||||
|
import { isLucideIconName, pluginIconComponent } from "@/plugins/icons";
|
||||||
import { getModeVisuals, type AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
|
import { getModeVisuals, type AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
|
||||||
|
|
||||||
export interface AgentControlIconProps {
|
export interface AgentControlIconProps {
|
||||||
@@ -60,6 +61,9 @@ export function getAgentModeOptionIcon(
|
|||||||
return icon ? MODE_ICONS[icon] : undefined;
|
return icon ? MODE_ICONS[icon] : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A built-in control names its icon in kebab case; a plugin provider names a Lucide icon. */
|
||||||
export function getAgentFeatureIcon(icon?: string): AgentControlIcon {
|
export function getAgentFeatureIcon(icon?: string): AgentControlIcon {
|
||||||
return (icon ? FEATURE_ICONS[icon] : undefined) ?? Settings2;
|
if (!icon) return Settings2;
|
||||||
|
if (FEATURE_ICONS[icon]) return FEATURE_ICONS[icon];
|
||||||
|
return isLucideIconName(icon) ? pluginIconComponent(icon) : Settings2;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The options that still apply after an answer from the daemon. A key an earlier answer drew as a
|
||||||
|
* control and the latest answer does not (the model changed to one without that control) is
|
||||||
|
* dropped, and applies again if a control for it returns. A key no answer has drawn is an option
|
||||||
|
* without a control and always applies.
|
||||||
|
*/
|
||||||
|
export function withoutLostControls(
|
||||||
|
options: ProviderOptions,
|
||||||
|
drawn: ReadonlySet<string>,
|
||||||
|
current: ReadonlySet<string>,
|
||||||
|
): ProviderOptions {
|
||||||
|
return Object.fromEntries(
|
||||||
|
Object.entries(options).filter(([key]) => !drawn.has(key) || current.has(key)),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
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");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
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",
|
model: "claude-opus-5",
|
||||||
modeId: "plan",
|
modeId: "plan",
|
||||||
thinkingOptionId: "think-hard",
|
thinkingOptionId: "think-hard",
|
||||||
featureValues: { web_search: true },
|
options: { web_search: true },
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
).toEqual({
|
).toEqual({
|
||||||
@@ -31,7 +31,7 @@ describe("materializeAgentProfile", () => {
|
|||||||
modelId: "claude-opus-5",
|
modelId: "claude-opus-5",
|
||||||
modeId: "plan",
|
modeId: "plan",
|
||||||
thinkingOptionId: "think-hard",
|
thinkingOptionId: "think-hard",
|
||||||
featureValues: { web_search: true },
|
options: { web_search: true },
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -41,7 +41,7 @@ describe("materializeAgentProfile", () => {
|
|||||||
modelId: "",
|
modelId: "",
|
||||||
modeId: "",
|
modeId: "",
|
||||||
thinkingOptionId: "",
|
thinkingOptionId: "",
|
||||||
featureValues: {},
|
options: {},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -61,7 +61,7 @@ describe("toAgentConfigApply", () => {
|
|||||||
model: "claude-opus-5",
|
model: "claude-opus-5",
|
||||||
modeId: "plan",
|
modeId: "plan",
|
||||||
thinkingOptionId: "think-hard",
|
thinkingOptionId: "think-hard",
|
||||||
featureValues: { web_search: true },
|
options: { web_search: true },
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -69,7 +69,7 @@ describe("toAgentConfigApply", () => {
|
|||||||
modelId: "claude-opus-5",
|
modelId: "claude-opus-5",
|
||||||
modeId: "plan",
|
modeId: "plan",
|
||||||
thinkingOptionId: "think-hard",
|
thinkingOptionId: "think-hard",
|
||||||
featureValues: { web_search: true },
|
options: { web_search: true },
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -81,8 +81,8 @@ describe("toAgentConfigApply", () => {
|
|||||||
|
|
||||||
it("omits an empty feature map so the agent keeps its own feature values", () => {
|
it("omits an empty feature map so the agent keeps its own feature values", () => {
|
||||||
expect(
|
expect(
|
||||||
toAgentConfigApply(materializeAgentProfile(profile({ featureValues: {} }))),
|
toAgentConfigApply(materializeAgentProfile(profile({ options: {} }))),
|
||||||
).not.toHaveProperty("featureValues");
|
).not.toHaveProperty("options");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("never carries a provider, which a running agent cannot change", () => {
|
it("never carries a provider, which a running agent cannot change", () => {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export interface MaterializedAgentProfile {
|
|||||||
modelId: string;
|
modelId: string;
|
||||||
modeId: string;
|
modeId: string;
|
||||||
thinkingOptionId: string;
|
thinkingOptionId: string;
|
||||||
featureValues: Record<string, unknown>;
|
options: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function trimmed(value: string | undefined): string {
|
function trimmed(value: string | undefined): string {
|
||||||
@@ -25,7 +25,7 @@ export function materializeAgentProfile(profile: AgentProfile): MaterializedAgen
|
|||||||
modelId: trimmed(profile.model),
|
modelId: trimmed(profile.model),
|
||||||
modeId: trimmed(profile.modeId),
|
modeId: trimmed(profile.modeId),
|
||||||
thinkingOptionId: trimmed(profile.thinkingOptionId),
|
thinkingOptionId: trimmed(profile.thinkingOptionId),
|
||||||
featureValues: profile.featureValues ?? {},
|
options: profile.options ?? {},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,8 +52,6 @@ export function toAgentConfigApply(profile: MaterializedAgentProfile): AgentConf
|
|||||||
...(profile.modelId ? { modelId: profile.modelId } : {}),
|
...(profile.modelId ? { modelId: profile.modelId } : {}),
|
||||||
...(profile.modeId ? { modeId: profile.modeId } : {}),
|
...(profile.modeId ? { modeId: profile.modeId } : {}),
|
||||||
...(profile.thinkingOptionId ? { thinkingOptionId: profile.thinkingOptionId } : {}),
|
...(profile.thinkingOptionId ? { thinkingOptionId: profile.thinkingOptionId } : {}),
|
||||||
...(Object.keys(profile.featureValues).length > 0
|
...(Object.keys(profile.options).length > 0 ? { options: profile.options } : {}),
|
||||||
? { featureValues: profile.featureValues }
|
|
||||||
: {}),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import {
|
import {
|
||||||
buildFeatureRequestKey,
|
buildControlsRequestKey,
|
||||||
openAgentProfileForm,
|
openAgentProfileForm,
|
||||||
type AgentProfileFormModel,
|
type AgentProfileFormModel,
|
||||||
} from "./profile-form-model";
|
} from "./profile-form-model";
|
||||||
@@ -70,6 +70,21 @@ function optionValues(options: readonly { value: string }[]): string[] {
|
|||||||
return options.map((option) => option.value);
|
return options.map((option) => option.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const FAST = {
|
||||||
|
controls: [{ type: "toggle" as const, key: "fast_mode", label: "Fast" }],
|
||||||
|
options: { fast_mode: false },
|
||||||
|
};
|
||||||
|
const NO_CONTROLS = { controls: [], options: {} };
|
||||||
|
|
||||||
|
function toggledOnOpus(): AgentProfileFormModel {
|
||||||
|
const model = openWithCatalog({ mode: "create" });
|
||||||
|
model.setName("Fast");
|
||||||
|
selectClaude(model);
|
||||||
|
model.applyControls(model.getState().controlsRequestKey ?? "", FAST);
|
||||||
|
model.setOption("fast_mode", true);
|
||||||
|
return model;
|
||||||
|
}
|
||||||
|
|
||||||
describe("openAgentProfileForm", () => {
|
describe("openAgentProfileForm", () => {
|
||||||
it("starts a create form empty and cannot submit", () => {
|
it("starts a create form empty and cannot submit", () => {
|
||||||
const model = openWithCatalog({ mode: "create" });
|
const model = openWithCatalog({ mode: "create" });
|
||||||
@@ -173,7 +188,7 @@ describe("openAgentProfileForm", () => {
|
|||||||
model: "claude-opus-5",
|
model: "claude-opus-5",
|
||||||
modeId: "plan",
|
modeId: "plan",
|
||||||
thinkingOptionId: "think-hard",
|
thinkingOptionId: "think-hard",
|
||||||
featureValues: { webSearch: true },
|
options: { webSearch: true },
|
||||||
notes: "Visual work only.",
|
notes: "Visual work only.",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -229,10 +244,11 @@ describe("openAgentProfileForm", () => {
|
|||||||
selectClaude(model);
|
selectClaude(model);
|
||||||
model.setModel("claude-opus-5", { label: "Opus 5" });
|
model.setModel("claude-opus-5", { label: "Opus 5" });
|
||||||
model.setThinking("think-hard", { label: "Think hard" });
|
model.setThinking("think-hard", { label: "Think hard" });
|
||||||
model.applyFeatures(model.getState().featureRequestKey ?? "", [
|
model.applyControls(model.getState().controlsRequestKey ?? "", {
|
||||||
{ type: "toggle", id: "webSearch", label: "Web search", value: false },
|
controls: [{ type: "toggle", key: "webSearch", label: "Web search" }],
|
||||||
]);
|
options: { webSearch: false },
|
||||||
model.setFeatureValue("webSearch", true);
|
});
|
||||||
|
model.setOption("webSearch", true);
|
||||||
|
|
||||||
model.setProvider("codex", { label: "Codex" });
|
model.setProvider("codex", { label: "Codex" });
|
||||||
const state = model.getState();
|
const state = model.getState();
|
||||||
@@ -242,8 +258,9 @@ describe("openAgentProfileForm", () => {
|
|||||||
expect(state.modelDisplay).toEqual({ label: "GPT-5.2 Codex" });
|
expect(state.modelDisplay).toEqual({ label: "GPT-5.2 Codex" });
|
||||||
expect(state.thinkingOptionId).toBe("");
|
expect(state.thinkingOptionId).toBe("");
|
||||||
expect(state.thinkingDisplay).toBeNull();
|
expect(state.thinkingDisplay).toBeNull();
|
||||||
expect(state.featureValues).toEqual({});
|
expect(state.options).toEqual({});
|
||||||
expect(state.features).toEqual([]);
|
expect(state.optionEdits).toEqual({});
|
||||||
|
expect(state.controls).toEqual([]);
|
||||||
expect(state.name).toBe("Test writer");
|
expect(state.name).toBe("Test writer");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -334,23 +351,28 @@ describe("openAgentProfileForm", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("features", () => {
|
const WEB_SEARCH_CONTROLS = {
|
||||||
it("asks for features per provider/model/mode/thinking combination", () => {
|
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", () => {
|
||||||
const model = openWithCatalog({ mode: "create" });
|
const model = openWithCatalog({ mode: "create" });
|
||||||
selectClaude(model);
|
selectClaude(model);
|
||||||
|
|
||||||
expect(model.getState().featureRequest).toEqual({
|
expect(model.getState().controlsRequest).toEqual({
|
||||||
provider: "claude",
|
provider: "claude",
|
||||||
model: "claude-opus-5",
|
model: "claude-opus-5",
|
||||||
modeId: "plan",
|
modeId: "plan",
|
||||||
thinkingOptionId: "think",
|
thinkingOptionId: "think",
|
||||||
});
|
});
|
||||||
const firstKey = model.getState().featureRequestKey;
|
const firstKey = model.getState().controlsRequestKey;
|
||||||
|
|
||||||
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
|
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
|
||||||
|
|
||||||
expect(model.getState().featureRequestKey).not.toBe(firstKey);
|
expect(model.getState().controlsRequestKey).not.toBe(firstKey);
|
||||||
expect(model.getState().featureRequest).toEqual({
|
expect(model.getState().controlsRequest).toEqual({
|
||||||
provider: "claude",
|
provider: "claude",
|
||||||
model: "claude-haiku-4-5",
|
model: "claude-haiku-4-5",
|
||||||
modeId: "plan",
|
modeId: "plan",
|
||||||
@@ -361,77 +383,233 @@ describe("openAgentProfileForm", () => {
|
|||||||
it("moves from pending to complete only for the current request", () => {
|
it("moves from pending to complete only for the current request", () => {
|
||||||
const model = openWithCatalog({ mode: "create" });
|
const model = openWithCatalog({ mode: "create" });
|
||||||
selectClaude(model);
|
selectClaude(model);
|
||||||
const key = model.getState().featureRequestKey ?? "";
|
const key = model.getState().controlsRequestKey ?? "";
|
||||||
expect(model.getState().featureResolution).toBe("pending");
|
expect(model.getState().controlsResolution).toBe("pending");
|
||||||
|
|
||||||
model.applyFeatures("stale-key", [
|
model.applyControls("stale-key", {
|
||||||
{ type: "toggle", id: "webSearch", label: "Web search", value: false },
|
controls: [{ type: "toggle", key: "webSearch", label: "Web search" }],
|
||||||
]);
|
options: { webSearch: false },
|
||||||
expect(model.getState().featureResolution).toBe("pending");
|
});
|
||||||
expect(model.getState().features).toEqual([]);
|
expect(model.getState().controlsResolution).toBe("pending");
|
||||||
|
expect(model.getState().controls).toEqual([]);
|
||||||
|
|
||||||
model.applyFeatures(key, [
|
model.applyControls(key, {
|
||||||
{ type: "toggle", id: "webSearch", label: "Web search", value: false },
|
controls: [{ type: "toggle", key: "webSearch", label: "Web search" }],
|
||||||
]);
|
options: { webSearch: false },
|
||||||
expect(model.getState().featureResolution).toBe("complete");
|
});
|
||||||
expect(model.getState().disclosure.showFeaturesField).toBe(true);
|
expect(model.getState().controlsResolution).toBe("complete");
|
||||||
|
expect(model.getState().disclosure.showControlsField).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("reflects a set feature value back into the rendered feature", () => {
|
it("reflects a set option back into the rendered controls", () => {
|
||||||
|
const model = openWithCatalog({ mode: "create" });
|
||||||
|
model.setName("Searcher");
|
||||||
|
selectClaude(model);
|
||||||
|
model.applyControls(model.getState().controlsRequestKey ?? "", WEB_SEARCH_CONTROLS);
|
||||||
|
|
||||||
|
model.setOption("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 });
|
||||||
|
});
|
||||||
|
|
||||||
|
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", () => {
|
||||||
|
const model = openAgentProfileForm({
|
||||||
|
mode: "edit",
|
||||||
|
profile: {
|
||||||
|
id: "p1",
|
||||||
|
name: "UI work",
|
||||||
|
provider: "claude",
|
||||||
|
options: { webSearch: true, sandbox_mode: "read-only" },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
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",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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", () => {
|
||||||
|
const model = openAgentProfileForm({
|
||||||
|
mode: "edit",
|
||||||
|
profile: {
|
||||||
|
id: "p1",
|
||||||
|
name: "Fast",
|
||||||
|
provider: "codex",
|
||||||
|
options: { service_tier: "fast", sandbox_mode: "read-only" },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
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.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" });
|
const model = openWithCatalog({ mode: "create" });
|
||||||
selectClaude(model);
|
selectClaude(model);
|
||||||
model.applyFeatures(model.getState().featureRequestKey ?? "", [
|
model.applyControls(model.getState().controlsRequestKey ?? "", WEB_SEARCH_CONTROLS);
|
||||||
{ type: "toggle", id: "webSearch", label: "Web search", value: false },
|
|
||||||
]);
|
|
||||||
|
|
||||||
model.setFeatureValue("webSearch", true);
|
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
|
||||||
|
|
||||||
expect(model.getState().features[0]).toMatchObject({ id: "webSearch", value: true });
|
expect(model.getState().controls).toEqual([]);
|
||||||
expect(model.getState().featureValues).toEqual({ webSearch: true });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("keeps stored feature values while the feature list is still pending", () => {
|
it("does not save a toggle once the model that drew it is replaced by one without it", () => {
|
||||||
|
const model = toggledOnOpus();
|
||||||
|
expect(model.getState().submitValue?.options).toEqual({ fast_mode: true });
|
||||||
|
|
||||||
|
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
|
||||||
|
model.applyControls(model.getState().controlsRequestKey ?? "", NO_CONTROLS);
|
||||||
|
|
||||||
|
expect(model.getState().submitValue?.options).toBeUndefined();
|
||||||
|
expect(model.getState().controlsRequest?.providerOptions).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("saves a toggle again when the model that draws it returns", () => {
|
||||||
|
const model = toggledOnOpus();
|
||||||
|
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
|
||||||
|
model.applyControls(model.getState().controlsRequestKey ?? "", NO_CONTROLS);
|
||||||
|
|
||||||
|
model.setModel("claude-opus-5", { label: "Opus 5" });
|
||||||
|
model.applyControls(model.getState().controlsRequestKey ?? "", FAST);
|
||||||
|
|
||||||
|
expect(model.getState().submitValue?.options).toEqual({ fast_mode: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not save a stored toggle profile either", () => {
|
||||||
const model = openAgentProfileForm({
|
const model = openAgentProfileForm({
|
||||||
mode: "edit",
|
mode: "edit",
|
||||||
profile: {
|
profile: {
|
||||||
id: "p1",
|
id: "p1",
|
||||||
name: "UI work",
|
name: "Fast",
|
||||||
provider: "claude",
|
provider: "claude",
|
||||||
featureValues: { webSearch: true },
|
model: "claude-opus-5",
|
||||||
|
options: { fast_mode: true },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
model.applyProviderCatalog(ENTRIES);
|
model.applyProviderCatalog(ENTRIES);
|
||||||
|
model.applyControls(model.getState().controlsRequestKey ?? "", FAST);
|
||||||
|
|
||||||
expect(model.getState().featureResolution).toBe("pending");
|
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
|
||||||
expect(model.getState().submitValue?.featureValues).toEqual({ webSearch: true });
|
model.applyControls(model.getState().controlsRequestKey ?? "", NO_CONTROLS);
|
||||||
|
|
||||||
|
expect(model.getState().submitValue?.options).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("prunes stored values the provider no longer reports", () => {
|
it("never drops an option no control has drawn", () => {
|
||||||
const model = openAgentProfileForm({
|
const model = openWithCatalog({ mode: "create" });
|
||||||
mode: "edit",
|
model.setName("Fast");
|
||||||
profile: {
|
selectClaude(model);
|
||||||
id: "p1",
|
model.applyControls(model.getState().controlsRequestKey ?? "", FAST);
|
||||||
name: "UI work",
|
model.setOption("token_budget", 8000);
|
||||||
provider: "claude",
|
model.setOption("fast_mode", true);
|
||||||
featureValues: { webSearch: true, retiredFlag: true },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
model.applyProviderCatalog(ENTRIES);
|
|
||||||
model.applyFeatures(model.getState().featureRequestKey ?? "", [
|
|
||||||
{ type: "toggle", id: "webSearch", label: "Web search", value: false },
|
|
||||||
]);
|
|
||||||
|
|
||||||
expect(model.getState().featureValues).toEqual({ webSearch: true });
|
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
|
||||||
|
model.applyControls(model.getState().controlsRequestKey ?? "", NO_CONTROLS);
|
||||||
|
|
||||||
|
expect(model.getState().submitValue?.options).toEqual({ token_budget: 8000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps a toggle when the daemon cannot list controls", () => {
|
||||||
|
const model = toggledOnOpus();
|
||||||
|
|
||||||
|
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
|
||||||
|
model.applyControlsUnavailable(model.getState().controlsRequestKey ?? "");
|
||||||
|
|
||||||
|
expect(model.getState().submitValue?.options).toEqual({ fast_mode: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("resolves an unavailable feature listing without showing the field", () => {
|
it("resolves an unavailable feature listing without showing the field", () => {
|
||||||
const model = openWithCatalog({ mode: "create" });
|
const model = openWithCatalog({ mode: "create" });
|
||||||
selectClaude(model);
|
selectClaude(model);
|
||||||
|
|
||||||
model.applyFeaturesUnavailable(model.getState().featureRequestKey ?? "");
|
model.applyControlsUnavailable(model.getState().controlsRequestKey ?? "");
|
||||||
|
|
||||||
expect(model.getState().featureResolution).toBe("complete");
|
expect(model.getState().controlsResolution).toBe("complete");
|
||||||
expect(model.getState().disclosure.showFeaturesField).toBe(false);
|
expect(model.getState().disclosure.showControlsField).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -464,15 +642,15 @@ describe("openAgentProfileForm", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("buildFeatureRequestKey", () => {
|
describe("buildControlsRequestKey", () => {
|
||||||
it("is null without a provider", () => {
|
it("is null without a provider", () => {
|
||||||
expect(buildFeatureRequestKey(null)).toBeNull();
|
expect(buildControlsRequestKey(null)).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("separates the fields so a value cannot bleed across positions", () => {
|
it("separates the fields so a value cannot bleed across positions", () => {
|
||||||
expect(buildFeatureRequestKey({ provider: "claude", model: "a|b" })).toBe("claude|a|b||");
|
expect(buildControlsRequestKey({ provider: "claude", model: "a|b" })).toBe("claude|a|b||");
|
||||||
expect(buildFeatureRequestKey({ provider: "claude", modeId: "a" })).not.toBe(
|
expect(buildControlsRequestKey({ provider: "claude", modeId: "a" })).not.toBe(
|
||||||
buildFeatureRequestKey({ provider: "claude", model: "a" }),
|
buildControlsRequestKey({ provider: "claude", model: "a" }),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
import type {
|
import type {
|
||||||
AgentFeature,
|
AgentOptionControl,
|
||||||
|
ProviderOptions,
|
||||||
AgentMode,
|
AgentMode,
|
||||||
AgentModelDefinition,
|
AgentModelDefinition,
|
||||||
AgentSelectOption,
|
AgentSelectOption,
|
||||||
ProviderSnapshotEntry,
|
ProviderSnapshotEntry,
|
||||||
} from "@getpaseo/protocol/agent-types";
|
} from "@getpaseo/protocol/agent-types";
|
||||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||||
|
import { withoutLostControls } from "@/agent-controls/lost-controls";
|
||||||
import { formatAgentModeLabel, formatThinkingOptionLabel } from "@/agent-controls/labels";
|
import { formatAgentModeLabel, formatThinkingOptionLabel } from "@/agent-controls/labels";
|
||||||
import { applyFeatureValues, pruneFeatureValues } from "@/hooks/feature-preferences";
|
|
||||||
import { filterSelectableModels } from "@/provider-selection/model-catalog";
|
import { filterSelectableModels } from "@/provider-selection/model-catalog";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -57,11 +58,15 @@ export interface AgentProfileFormSnapshot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The inputs a feature listing needs. Features are provider-scoped and change
|
* 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.
|
* 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.
|
||||||
*/
|
*/
|
||||||
export interface AgentProfileFeatureRequest {
|
export interface AgentProfileControlsRequest {
|
||||||
provider: string;
|
provider: string;
|
||||||
|
providerOptions?: ProviderOptions;
|
||||||
model?: string;
|
model?: string;
|
||||||
modeId?: string;
|
modeId?: string;
|
||||||
thinkingOptionId?: string;
|
thinkingOptionId?: string;
|
||||||
@@ -73,7 +78,7 @@ export interface AgentProfileFormDisclosure {
|
|||||||
showModelField: boolean;
|
showModelField: boolean;
|
||||||
showModeField: boolean;
|
showModeField: boolean;
|
||||||
showThinkingField: boolean;
|
showThinkingField: boolean;
|
||||||
showFeaturesField: boolean;
|
showControlsField: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AgentProfileFormState {
|
export interface AgentProfileFormState {
|
||||||
@@ -86,13 +91,22 @@ export interface AgentProfileFormState {
|
|||||||
modelId: string;
|
modelId: string;
|
||||||
modeId: string;
|
modeId: string;
|
||||||
thinkingOptionId: string;
|
thinkingOptionId: string;
|
||||||
featureValues: Record<string, unknown>;
|
/** The options the profile was opened with, including ones no control draws. */
|
||||||
|
options: ProviderOptions;
|
||||||
|
/** Changes made in this form, over `options`. */
|
||||||
|
optionEdits: ProviderOptions;
|
||||||
|
|
||||||
providerOptions: AgentProfileFormOption[];
|
providerOptions: AgentProfileFormOption[];
|
||||||
modelOptions: AgentProfileFormOption[];
|
modelOptions: AgentProfileFormOption[];
|
||||||
modeOptions: AgentProfileFormOption[];
|
modeOptions: AgentProfileFormOption[];
|
||||||
thinkingOptions: AgentProfileFormOption[];
|
thinkingOptions: AgentProfileFormOption[];
|
||||||
features: AgentFeature[];
|
controls: AgentOptionControl[];
|
||||||
|
/** What the controls show: the options the daemon resolved from `options`, then the edits. */
|
||||||
|
controlOptions: ProviderOptions;
|
||||||
|
/** Every key an answer for this provider has drawn as a control. */
|
||||||
|
drawnControlKeys: ReadonlySet<string>;
|
||||||
|
/** The keys the latest answer draws as controls. */
|
||||||
|
answeredControlKeys: ReadonlySet<string>;
|
||||||
|
|
||||||
providerDisplay: AgentProfileFormDisplay | null;
|
providerDisplay: AgentProfileFormDisplay | null;
|
||||||
modelDisplay: AgentProfileFormDisplay | null;
|
modelDisplay: AgentProfileFormDisplay | null;
|
||||||
@@ -100,9 +114,9 @@ export interface AgentProfileFormState {
|
|||||||
thinkingDisplay: AgentProfileFormDisplay | null;
|
thinkingDisplay: AgentProfileFormDisplay | null;
|
||||||
|
|
||||||
catalogResolution: AgentProfileResolutionStatus;
|
catalogResolution: AgentProfileResolutionStatus;
|
||||||
featureResolution: AgentProfileResolutionStatus;
|
controlsResolution: AgentProfileResolutionStatus;
|
||||||
featureRequest: AgentProfileFeatureRequest | null;
|
controlsRequest: AgentProfileControlsRequest | null;
|
||||||
featureRequestKey: string | null;
|
controlsRequestKey: string | null;
|
||||||
|
|
||||||
disclosure: AgentProfileFormDisclosure;
|
disclosure: AgentProfileFormDisclosure;
|
||||||
isSubmitting: boolean;
|
isSubmitting: boolean;
|
||||||
@@ -118,9 +132,12 @@ export interface AgentProfileFormModel {
|
|||||||
/** Late input: the host-scoped provider catalog. Never touches selections. */
|
/** Late input: the host-scoped provider catalog. Never touches selections. */
|
||||||
applyProviderCatalog: (entries: readonly ProviderSnapshotEntry[]) => void;
|
applyProviderCatalog: (entries: readonly ProviderSnapshotEntry[]) => void;
|
||||||
/** Late input: the feature list for one request. Stale keys are ignored. */
|
/** Late input: the feature list for one request. Stale keys are ignored. */
|
||||||
applyFeatures: (requestKey: string, features: readonly AgentFeature[]) => void;
|
applyControls: (
|
||||||
|
requestKey: string,
|
||||||
|
resolved: { controls: readonly AgentOptionControl[]; options: ProviderOptions },
|
||||||
|
) => void;
|
||||||
/** Resolve a request that produced no usable features (provider error). */
|
/** Resolve a request that produced no usable features (provider error). */
|
||||||
applyFeaturesUnavailable: (requestKey: string) => void;
|
applyControlsUnavailable: (requestKey: string) => void;
|
||||||
setName: (value: string) => void;
|
setName: (value: string) => void;
|
||||||
setAppearance: (value: { icon: string; color: string }) => void;
|
setAppearance: (value: { icon: string; color: string }) => void;
|
||||||
setNotes: (value: string) => void;
|
setNotes: (value: string) => void;
|
||||||
@@ -128,7 +145,7 @@ export interface AgentProfileFormModel {
|
|||||||
setModel: (modelId: string, display: AgentProfileFormDisplay | null) => void;
|
setModel: (modelId: string, display: AgentProfileFormDisplay | null) => void;
|
||||||
setMode: (modeId: string, display: AgentProfileFormDisplay | null) => void;
|
setMode: (modeId: string, display: AgentProfileFormDisplay | null) => void;
|
||||||
setThinking: (thinkingOptionId: string, display: AgentProfileFormDisplay | null) => void;
|
setThinking: (thinkingOptionId: string, display: AgentProfileFormDisplay | null) => void;
|
||||||
setFeatureValue: (featureId: string, value: unknown) => void;
|
setOption: (key: string, value: unknown) => void;
|
||||||
setSubmitting: (value: boolean) => void;
|
setSubmitting: (value: boolean) => void;
|
||||||
setSubmitError: (value: string | null) => void;
|
setSubmitError: (value: string | null) => void;
|
||||||
}
|
}
|
||||||
@@ -312,19 +329,39 @@ function refineDisplay(
|
|||||||
return current ?? { label: selectedId };
|
return current ?? { label: selectedId };
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildFeatureRequest(state: AgentProfileFormState): AgentProfileFeatureRequest | null {
|
function buildControlsRequest(state: AgentProfileFormState): AgentProfileControlsRequest | null {
|
||||||
if (!state.provider) {
|
if (!state.provider) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
const ownOptions = ownOptionsOf(state);
|
||||||
return {
|
return {
|
||||||
provider: state.provider,
|
provider: state.provider,
|
||||||
...(state.modelId ? { model: state.modelId } : {}),
|
...(state.modelId ? { model: state.modelId } : {}),
|
||||||
...(state.modeId ? { modeId: state.modeId } : {}),
|
...(state.modeId ? { modeId: state.modeId } : {}),
|
||||||
...(state.thinkingOptionId ? { thinkingOptionId: state.thinkingOptionId } : {}),
|
...(state.thinkingOptionId ? { thinkingOptionId: state.thinkingOptionId } : {}),
|
||||||
|
...(Object.keys(ownOptions).length > 0 ? { providerOptions: ownOptions } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildFeatureRequestKey(request: AgentProfileFeatureRequest | null): string | null {
|
/**
|
||||||
|
* Everything the profile would save as its options; the daemon resolves them for the form. A
|
||||||
|
* toggle the model in use does not draw is not saved (see `withoutLostControls`).
|
||||||
|
*/
|
||||||
|
function ownOptionsOf(
|
||||||
|
state: Pick<
|
||||||
|
AgentProfileFormState,
|
||||||
|
"options" | "optionEdits" | "drawnControlKeys" | "answeredControlKeys"
|
||||||
|
>,
|
||||||
|
): ProviderOptions {
|
||||||
|
return withoutLostControls(
|
||||||
|
{ ...state.options, ...state.optionEdits },
|
||||||
|
state.drawnControlKeys,
|
||||||
|
state.answeredControlKeys,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The part of a request that decides which controls exist; options only change their values. */
|
||||||
|
function buildControlsScopeKey(request: AgentProfileControlsRequest | null): string | null {
|
||||||
if (!request) {
|
if (!request) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -336,12 +373,25 @@ export function buildFeatureRequestKey(request: AgentProfileFeatureRequest | nul
|
|||||||
].join("|");
|
].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 {
|
function buildSubmitValue(state: AgentProfileFormState): AgentProfileValue | null {
|
||||||
const name = state.name.trim();
|
const name = state.name.trim();
|
||||||
const notes = state.notes.trim();
|
const notes = state.notes.trim();
|
||||||
if (!name || !state.provider) {
|
if (!name || !state.provider) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
const options = ownOptionsOf(state);
|
||||||
return {
|
return {
|
||||||
name,
|
name,
|
||||||
...(state.icon ? { icon: state.icon } : {}),
|
...(state.icon ? { icon: state.icon } : {}),
|
||||||
@@ -350,16 +400,16 @@ function buildSubmitValue(state: AgentProfileFormState): AgentProfileValue | nul
|
|||||||
...(state.modelId ? { model: state.modelId } : {}),
|
...(state.modelId ? { model: state.modelId } : {}),
|
||||||
...(state.modeId ? { modeId: state.modeId } : {}),
|
...(state.modeId ? { modeId: state.modeId } : {}),
|
||||||
...(state.thinkingOptionId ? { thinkingOptionId: state.thinkingOptionId } : {}),
|
...(state.thinkingOptionId ? { thinkingOptionId: state.thinkingOptionId } : {}),
|
||||||
...(Object.keys(state.featureValues).length > 0 ? { featureValues: state.featureValues } : {}),
|
...(Object.keys(options).length > 0 ? { options } : {}),
|
||||||
...(notes ? { notes } : {}),
|
...(notes ? { notes } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveFeatureStatus(
|
function resolveControlsStatus(
|
||||||
featureRequestKey: string | null,
|
controlsRequestKey: string | null,
|
||||||
featuresAreCurrent: boolean,
|
featuresAreCurrent: boolean,
|
||||||
): AgentProfileResolutionStatus {
|
): AgentProfileResolutionStatus {
|
||||||
if (featureRequestKey === null) {
|
if (controlsRequestKey === null) {
|
||||||
return "idle";
|
return "idle";
|
||||||
}
|
}
|
||||||
return featuresAreCurrent ? "complete" : "pending";
|
return featuresAreCurrent ? "complete" : "pending";
|
||||||
@@ -392,25 +442,29 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
|||||||
modelId,
|
modelId,
|
||||||
modeId: profile.modeId ?? "",
|
modeId: profile.modeId ?? "",
|
||||||
thinkingOptionId: profile.thinkingOptionId ?? "",
|
thinkingOptionId: profile.thinkingOptionId ?? "",
|
||||||
featureValues: { ...profile.featureValues },
|
options: { ...profile.options },
|
||||||
|
optionEdits: {},
|
||||||
providerOptions: [],
|
providerOptions: [],
|
||||||
modelOptions: [],
|
modelOptions: [],
|
||||||
modeOptions: [],
|
modeOptions: [],
|
||||||
thinkingOptions: [],
|
thinkingOptions: [],
|
||||||
features: [],
|
controls: [],
|
||||||
|
controlOptions: {},
|
||||||
|
drawnControlKeys: new Set(),
|
||||||
|
answeredControlKeys: new Set(),
|
||||||
providerDisplay: seedDisplay(provider),
|
providerDisplay: seedDisplay(provider),
|
||||||
modelDisplay: seedDisplay(modelId),
|
modelDisplay: seedDisplay(modelId),
|
||||||
modeDisplay: seedDisplay(profile.modeId),
|
modeDisplay: seedDisplay(profile.modeId),
|
||||||
thinkingDisplay: seedDisplay(profile.thinkingOptionId),
|
thinkingDisplay: seedDisplay(profile.thinkingOptionId),
|
||||||
catalogResolution: "idle",
|
catalogResolution: "idle",
|
||||||
featureResolution: "idle",
|
controlsResolution: "idle",
|
||||||
featureRequest: null,
|
controlsRequest: null,
|
||||||
featureRequestKey: null,
|
controlsRequestKey: null,
|
||||||
disclosure: {
|
disclosure: {
|
||||||
showModelField: false,
|
showModelField: false,
|
||||||
showModeField: false,
|
showModeField: false,
|
||||||
showThinkingField: false,
|
showThinkingField: false,
|
||||||
showFeaturesField: false,
|
showControlsField: false,
|
||||||
},
|
},
|
||||||
isSubmitting: false,
|
isSubmitting: false,
|
||||||
submitError: null,
|
submitError: null,
|
||||||
@@ -422,28 +476,45 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
|||||||
export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentProfileFormModel {
|
export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentProfileFormModel {
|
||||||
let entries: readonly ProviderSnapshotEntry[] = [];
|
let entries: readonly ProviderSnapshotEntry[] = [];
|
||||||
let catalogResolution: AgentProfileResolutionStatus = "idle";
|
let catalogResolution: AgentProfileResolutionStatus = "idle";
|
||||||
let resolvedFeatureKey: string | null = null;
|
let resolvedControlsKey: string | null = null;
|
||||||
let resolvedFeatures: AgentFeature[] = [];
|
let resolvedScopeKey: string | null = null;
|
||||||
|
let resolvedControls: AgentOptionControl[] = [];
|
||||||
|
let resolvedOptions: ProviderOptions = {};
|
||||||
|
let drawnKeys: ReadonlySet<string> = new Set();
|
||||||
|
let answeredKeys: ReadonlySet<string> = new Set();
|
||||||
let listeners = new Set<() => void>();
|
let listeners = new Set<() => void>();
|
||||||
let closed = false;
|
let closed = false;
|
||||||
|
|
||||||
function derive(incoming: AgentProfileFormState): AgentProfileFormState {
|
function derive(incoming: AgentProfileFormState): AgentProfileFormState {
|
||||||
const models = resolveModels(entries, incoming.provider);
|
const models = resolveModels(entries, incoming.provider);
|
||||||
const modes = resolveModes(entries, incoming.provider);
|
const modes = resolveModes(entries, incoming.provider);
|
||||||
const next = seedSelections(incoming, {
|
const next: AgentProfileFormState = {
|
||||||
|
...seedSelections(incoming, {
|
||||||
entry: findEntry(entries, incoming.provider),
|
entry: findEntry(entries, incoming.provider),
|
||||||
models,
|
models,
|
||||||
modes,
|
modes,
|
||||||
});
|
}),
|
||||||
|
drawnControlKeys: drawnKeys,
|
||||||
|
answeredControlKeys: answeredKeys,
|
||||||
|
};
|
||||||
const thinking = resolveThinkingOptions(entries, next.provider, next.modelId);
|
const thinking = resolveThinkingOptions(entries, next.provider, next.modelId);
|
||||||
const featureRequest = buildFeatureRequest(next);
|
const controlsRequest = buildControlsRequest(next);
|
||||||
const featureRequestKey = buildFeatureRequestKey(featureRequest);
|
const controlsRequestKey = buildControlsRequestKey(controlsRequest);
|
||||||
|
const controlsScopeKey = buildControlsScopeKey(controlsRequest);
|
||||||
const featuresAreCurrent =
|
const featuresAreCurrent =
|
||||||
featureRequestKey !== null && featureRequestKey === resolvedFeatureKey;
|
controlsRequestKey !== null && controlsRequestKey === resolvedControlsKey;
|
||||||
const features = featuresAreCurrent
|
// A toggle changes only the options, so the controls stay up while the daemon answers and the
|
||||||
? applyFeatureValues(resolvedFeatures, next.featureValues)
|
// toggle shows over the last answer. A change of provider, model, mode or thinking draws none
|
||||||
: [];
|
// until its own answer arrives.
|
||||||
const featureResolution = resolveFeatureStatus(featureRequestKey, featuresAreCurrent);
|
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);
|
||||||
|
|
||||||
const withOptions: AgentProfileFormState = {
|
const withOptions: AgentProfileFormState = {
|
||||||
...next,
|
...next,
|
||||||
@@ -451,7 +522,8 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
|||||||
modelOptions: buildModelOptions(models),
|
modelOptions: buildModelOptions(models),
|
||||||
modeOptions: buildModeOptions(modes),
|
modeOptions: buildModeOptions(modes),
|
||||||
thinkingOptions: buildThinkingOptions(thinking),
|
thinkingOptions: buildThinkingOptions(thinking),
|
||||||
features,
|
controls,
|
||||||
|
controlOptions,
|
||||||
providerDisplay: refineDisplay(
|
providerDisplay: refineDisplay(
|
||||||
next.providerDisplay,
|
next.providerDisplay,
|
||||||
next.provider,
|
next.provider,
|
||||||
@@ -479,9 +551,9 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
|||||||
})(),
|
})(),
|
||||||
),
|
),
|
||||||
catalogResolution,
|
catalogResolution,
|
||||||
featureResolution,
|
controlsResolution,
|
||||||
featureRequest,
|
controlsRequest,
|
||||||
featureRequestKey,
|
controlsRequestKey,
|
||||||
};
|
};
|
||||||
|
|
||||||
// A field appears once the catalog can populate it, and stays visible while
|
// A field appears once the catalog can populate it, and stays visible while
|
||||||
@@ -492,7 +564,7 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
|||||||
showModeField: hasProvider && (modes.length > 0 || Boolean(withOptions.modeId)),
|
showModeField: hasProvider && (modes.length > 0 || Boolean(withOptions.modeId)),
|
||||||
showThinkingField:
|
showThinkingField:
|
||||||
hasProvider && (thinking.length > 0 || Boolean(withOptions.thinkingOptionId)),
|
hasProvider && (thinking.length > 0 || Boolean(withOptions.thinkingOptionId)),
|
||||||
showFeaturesField: hasProvider && features.length > 0,
|
showControlsField: hasProvider && controls.length > 0,
|
||||||
};
|
};
|
||||||
const canSubmit =
|
const canSubmit =
|
||||||
withOptions.name.trim().length > 0 &&
|
withOptions.name.trim().length > 0 &&
|
||||||
@@ -531,23 +603,26 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
|||||||
catalogResolution = "complete";
|
catalogResolution = "complete";
|
||||||
publish((current) => current);
|
publish((current) => current);
|
||||||
},
|
},
|
||||||
applyFeatures: (requestKey, features) => {
|
applyControls: (requestKey, resolved) => {
|
||||||
if (requestKey !== state.featureRequestKey) {
|
if (requestKey !== state.controlsRequestKey) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
resolvedFeatureKey = requestKey;
|
resolvedControlsKey = requestKey;
|
||||||
resolvedFeatures = [...features];
|
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
|
||||||
publish((current) => ({
|
resolvedControls = [...resolved.controls];
|
||||||
...current,
|
resolvedOptions = resolved.options;
|
||||||
featureValues: pruneFeatureValues(current.featureValues, resolvedFeatures),
|
answeredKeys = new Set(resolved.controls.map((control) => control.key));
|
||||||
}));
|
drawnKeys = new Set([...drawnKeys, ...answeredKeys]);
|
||||||
|
publish((current) => current);
|
||||||
},
|
},
|
||||||
applyFeaturesUnavailable: (requestKey) => {
|
applyControlsUnavailable: (requestKey) => {
|
||||||
if (requestKey !== state.featureRequestKey) {
|
if (requestKey !== state.controlsRequestKey) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
resolvedFeatureKey = requestKey;
|
resolvedControlsKey = requestKey;
|
||||||
resolvedFeatures = [];
|
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
|
||||||
|
resolvedControls = [];
|
||||||
|
resolvedOptions = {};
|
||||||
publish((current) => current);
|
publish((current) => current);
|
||||||
},
|
},
|
||||||
setName: (value) => publish((current) => ({ ...current, name: value })),
|
setName: (value) => publish((current) => ({ ...current, name: value })),
|
||||||
@@ -562,6 +637,8 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
|||||||
// Everything below the provider is provider-scoped: a model id, mode id,
|
// Everything below the provider is provider-scoped: a model id, mode id,
|
||||||
// thinking id or feature id from the old provider means nothing here.
|
// thinking id or feature id from the old provider means nothing here.
|
||||||
// Clearing them is enough — `derive` seeds the new provider's defaults.
|
// Clearing them is enough — `derive` seeds the new provider's defaults.
|
||||||
|
drawnKeys = new Set();
|
||||||
|
answeredKeys = new Set();
|
||||||
return {
|
return {
|
||||||
...current,
|
...current,
|
||||||
provider: providerId,
|
provider: providerId,
|
||||||
@@ -572,7 +649,8 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
|||||||
modeDisplay: null,
|
modeDisplay: null,
|
||||||
thinkingOptionId: "",
|
thinkingOptionId: "",
|
||||||
thinkingDisplay: null,
|
thinkingDisplay: null,
|
||||||
featureValues: {},
|
options: {},
|
||||||
|
optionEdits: {},
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
setModel: (modelId, display) =>
|
setModel: (modelId, display) =>
|
||||||
@@ -598,10 +676,10 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
|||||||
publish((current) => ({ ...current, modeId, modeDisplay: display })),
|
publish((current) => ({ ...current, modeId, modeDisplay: display })),
|
||||||
setThinking: (thinkingOptionId, display) =>
|
setThinking: (thinkingOptionId, display) =>
|
||||||
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display })),
|
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display })),
|
||||||
setFeatureValue: (featureId, value) =>
|
setOption: (key, value) =>
|
||||||
publish((current) => ({
|
publish((current) => ({
|
||||||
...current,
|
...current,
|
||||||
featureValues: { ...current.featureValues, [featureId]: value },
|
optionEdits: { ...current.optionEdits, [key]: value },
|
||||||
})),
|
})),
|
||||||
setSubmitting: (value) => publish((current) => ({ ...current, isSubmitting: value })),
|
setSubmitting: (value) => publish((current) => ({ ...current, isSubmitting: value })),
|
||||||
setSubmitError: (value) => publish((current) => ({ ...current, submitError: value })),
|
setSubmitError: (value) => publish((current) => ({ ...current, submitError: value })),
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ export function buildAgentProfileTags(input: {
|
|||||||
tags.push({ id: "thinking", label: formatThinkingOptionLabel({ id: thinkingOptionId }) });
|
tags.push({ id: "thinking", label: formatThinkingOptionLabel({ id: thinkingOptionId }) });
|
||||||
}
|
}
|
||||||
|
|
||||||
const featureCount = Object.keys(input.profile.featureValues ?? {}).length;
|
const featureCount = Object.keys(input.profile.options ?? {}).length;
|
||||||
if (featureCount > 0) {
|
if (featureCount > 0) {
|
||||||
tags.push({ id: "features", label: input.formatFeatureCount(featureCount) });
|
tags.push({ id: "features", label: input.formatFeatureCount(featureCount) });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -117,9 +117,7 @@ export function useAgentProfilePicker(
|
|||||||
modelId: resolved.modelId,
|
modelId: resolved.modelId,
|
||||||
modeId: resolved.modeId,
|
modeId: resolved.modeId,
|
||||||
thinkingOptionId: resolved.thinkingOptionId,
|
thinkingOptionId: resolved.thinkingOptionId,
|
||||||
...(Object.keys(resolved.featureValues).length > 0
|
...(Object.keys(resolved.options).length > 0 ? { options: resolved.options } : {}),
|
||||||
? { featureValues: resolved.featureValues }
|
|
||||||
: {}),
|
|
||||||
}),
|
}),
|
||||||
).catch((error) => {
|
).catch((error) => {
|
||||||
console.warn("[useAgentProfilePicker] persist profile selection failed", error);
|
console.warn("[useAgentProfilePicker] persist profile selection failed", error);
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ export function useAgentProfileFormCatalog(input: {
|
|||||||
}, [entries, input.model]);
|
}, [entries, input.model]);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAgentProfileFormFeatures(input: {
|
export function useAgentProfileFormControls(input: {
|
||||||
serverId: string;
|
serverId: string;
|
||||||
model: AgentProfileFormModel;
|
model: AgentProfileFormModel;
|
||||||
state: AgentProfileFormState;
|
state: AgentProfileFormState;
|
||||||
@@ -35,14 +35,14 @@ export function useAgentProfileFormFeatures(input: {
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const client = useHostRuntimeClient(input.serverId);
|
const client = useHostRuntimeClient(input.serverId);
|
||||||
const isConnected = useHostRuntimeIsConnected(input.serverId);
|
const isConnected = useHostRuntimeIsConnected(input.serverId);
|
||||||
const request = input.state.featureRequest;
|
const request = input.state.controlsRequest;
|
||||||
const requestKey = input.state.featureRequestKey;
|
const requestKey = input.state.controlsRequestKey;
|
||||||
|
|
||||||
// `dataShape: "value"` and not `"list"`: a list shape keeps the previous
|
// `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
|
// 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.
|
// features of one provider/model combination to the key of another.
|
||||||
const featuresQuery = useFetchQuery({
|
const controlsQuery = useFetchQuery({
|
||||||
queryKey: ["agentProfileFeatures", input.serverId, requestKey],
|
queryKey: ["agentProfileControls", input.serverId, requestKey],
|
||||||
dataShape: "value",
|
dataShape: "value",
|
||||||
staleTimeMs: 5 * 60 * 1000,
|
staleTimeMs: 5 * 60 * 1000,
|
||||||
enabled: Boolean(client && isConnected && request),
|
enabled: Boolean(client && isConnected && request),
|
||||||
@@ -51,28 +51,28 @@ export function useAgentProfileFormFeatures(input: {
|
|||||||
if (!client || !request) {
|
if (!client || !request) {
|
||||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||||
}
|
}
|
||||||
const payload = await client.listProviderFeatures({ ...request, cwd: HOME_SCOPE_CWD });
|
const payload = await client.listProviderControls({ ...request, cwd: HOME_SCOPE_CWD });
|
||||||
if (payload.error) {
|
if (payload.error) {
|
||||||
throw new Error(payload.error);
|
throw new Error(payload.error);
|
||||||
}
|
}
|
||||||
return payload.features ?? [];
|
return { controls: payload.controls ?? [], options: payload.options ?? {} };
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data, isError } = featuresQuery;
|
const { data, isError } = controlsQuery;
|
||||||
const { model } = input;
|
const { model } = input;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!requestKey || !data) {
|
if (!requestKey || !data) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
model.applyFeatures(requestKey, data);
|
model.applyControls(requestKey, data);
|
||||||
}, [data, model, requestKey]);
|
}, [data, model, requestKey]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!requestKey || !isError) {
|
if (!requestKey || !isError) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
model.applyFeaturesUnavailable(requestKey);
|
model.applyControlsUnavailable(requestKey);
|
||||||
}, [isError, model, requestKey]);
|
}, [isError, model, requestKey]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement }
|
|||||||
import { Text, View } from "react-native";
|
import { Text, View } from "react-native";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { StyleSheet } from "react-native-unistyles";
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
import type { AgentFeature } from "@getpaseo/protocol/agent-types";
|
import type { AgentOptionControl, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||||
|
import { readSelectOption, readToggleOption } from "@/agent-controls/option-controls";
|
||||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -24,7 +25,7 @@ import type {
|
|||||||
} from "../internal/profile-form-model";
|
} from "../internal/profile-form-model";
|
||||||
import {
|
import {
|
||||||
useAgentProfileFormCatalog,
|
useAgentProfileFormCatalog,
|
||||||
useAgentProfileFormFeatures,
|
useAgentProfileFormControls,
|
||||||
} from "../internal/use-profile-form-inputs";
|
} from "../internal/use-profile-form-inputs";
|
||||||
import {
|
import {
|
||||||
useAgentProfileFormModel,
|
useAgentProfileFormModel,
|
||||||
@@ -140,7 +141,7 @@ function OpenAgentProfileEditModal({
|
|||||||
const model = useAgentProfileFormModel(snapshot);
|
const model = useAgentProfileFormModel(snapshot);
|
||||||
const state = useAgentProfileFormState(model);
|
const state = useAgentProfileFormState(model);
|
||||||
useAgentProfileFormCatalog({ serverId, model });
|
useAgentProfileFormCatalog({ serverId, model });
|
||||||
useAgentProfileFormFeatures({ serverId, model, state });
|
useAgentProfileFormControls({ serverId, model, state });
|
||||||
|
|
||||||
const sheetHeader = useMemo<SheetHeader>(
|
const sheetHeader = useMemo<SheetHeader>(
|
||||||
() => ({
|
() => ({
|
||||||
@@ -327,16 +328,17 @@ function OpenAgentProfileEditModal({
|
|||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{state.disclosure.showFeaturesField ? (
|
{state.disclosure.showControlsField ? (
|
||||||
<Field
|
<Field
|
||||||
label={t("settings.host.agentProfiles.featuresLabel")}
|
label={t("settings.host.agentProfiles.featuresLabel")}
|
||||||
testID="agent-profile-features-field"
|
testID="agent-profile-features-field"
|
||||||
>
|
>
|
||||||
<View style={styles.featureCard} testID="agent-profile-features-card">
|
<View style={styles.featureCard} testID="agent-profile-features-card">
|
||||||
{state.features.map((feature, index) => (
|
{state.controls.map((control, index) => (
|
||||||
<AgentProfileFeatureRow
|
<AgentProfileControlRow
|
||||||
key={feature.id}
|
key={control.key}
|
||||||
feature={feature}
|
control={control}
|
||||||
|
options={state.controlOptions}
|
||||||
isFirst={index === 0}
|
isFirst={index === 0}
|
||||||
disabled={state.isSubmitting}
|
disabled={state.isSubmitting}
|
||||||
size={controlSize}
|
size={controlSize}
|
||||||
@@ -399,14 +401,16 @@ function OpenAgentProfileEditModal({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function AgentProfileFeatureRow({
|
function AgentProfileControlRow({
|
||||||
feature,
|
control,
|
||||||
|
options,
|
||||||
isFirst,
|
isFirst,
|
||||||
disabled,
|
disabled,
|
||||||
size,
|
size,
|
||||||
model,
|
model,
|
||||||
}: {
|
}: {
|
||||||
feature: AgentFeature;
|
control: AgentOptionControl;
|
||||||
|
options: ProviderOptions;
|
||||||
isFirst: boolean;
|
isFirst: boolean;
|
||||||
disabled: boolean;
|
disabled: boolean;
|
||||||
size: ControlSize;
|
size: ControlSize;
|
||||||
@@ -417,74 +421,75 @@ function AgentProfileFeatureRow({
|
|||||||
[isFirst],
|
[isFirst],
|
||||||
);
|
);
|
||||||
const handleToggle = useCallback(
|
const handleToggle = useCallback(
|
||||||
(value: boolean) => model.setFeatureValue(feature.id, value),
|
(value: boolean) => model.setOption(control.key, value),
|
||||||
[feature.id, model],
|
[control.key, model],
|
||||||
);
|
);
|
||||||
const handleSelect = useCallback(
|
const handleSelect = useCallback(
|
||||||
(value: string) => model.setFeatureValue(feature.id, value),
|
(value: string) => model.setOption(control.key, value),
|
||||||
[feature.id, model],
|
[control.key, model],
|
||||||
);
|
);
|
||||||
const selectOptions = useMemo<SelectFieldOption<string>[]>(
|
const selectOptions = useMemo<SelectFieldOption<string>[]>(
|
||||||
() =>
|
() =>
|
||||||
feature.type === "select"
|
control.type === "select"
|
||||||
? feature.options.map((option) => ({
|
? control.choices.map((choice) => ({
|
||||||
id: option.id,
|
id: choice.value,
|
||||||
value: option.id,
|
value: choice.value,
|
||||||
label: option.label,
|
label: choice.label,
|
||||||
...(option.description ? { description: option.description } : {}),
|
...(choice.description ? { description: choice.description } : {}),
|
||||||
testID: `agent-profile-feature-option-${feature.id}-${option.id}`,
|
testID: `agent-profile-feature-option-${control.key}-${choice.value}`,
|
||||||
}))
|
}))
|
||||||
: [],
|
: [],
|
||||||
[feature],
|
[control],
|
||||||
);
|
);
|
||||||
|
const selectedValue = control.type === "select" ? readSelectOption(control, options) : null;
|
||||||
const selectedDisplay = useMemo<SelectFieldDisplay | null>(() => {
|
const selectedDisplay = useMemo<SelectFieldDisplay | null>(() => {
|
||||||
if (feature.type !== "select" || !feature.value) {
|
if (control.type !== "select" || !selectedValue) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const option = feature.options.find((candidate) => candidate.id === feature.value);
|
const choice = control.choices.find((candidate) => candidate.value === selectedValue);
|
||||||
return { label: option?.label ?? feature.value };
|
return { label: choice?.label ?? selectedValue };
|
||||||
}, [feature]);
|
}, [control, selectedValue]);
|
||||||
|
|
||||||
if (feature.type === "select") {
|
if (control.type === "select") {
|
||||||
return (
|
return (
|
||||||
<View style={rowStyle} testID={`agent-profile-feature-row-${feature.id}`}>
|
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
|
||||||
<SelectField
|
<SelectField
|
||||||
label={feature.label}
|
label={control.label}
|
||||||
value={feature.value}
|
value={selectedValue}
|
||||||
selectedDisplay={selectedDisplay}
|
selectedDisplay={selectedDisplay}
|
||||||
options={selectOptions}
|
options={selectOptions}
|
||||||
onChange={handleSelect}
|
onChange={handleSelect}
|
||||||
placeholder={feature.label}
|
placeholder={control.label}
|
||||||
emptyText={feature.label}
|
emptyText={control.label}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
{...(feature.description ? { hint: feature.description } : {})}
|
{...(control.description ? { hint: control.description } : {})}
|
||||||
title={feature.label}
|
title={control.label}
|
||||||
size={size}
|
size={size}
|
||||||
testID={`agent-profile-feature-field-${feature.id}`}
|
testID={`agent-profile-feature-field-${control.key}`}
|
||||||
triggerTestID={`agent-profile-feature-trigger-${feature.id}`}
|
triggerTestID={`agent-profile-feature-trigger-${control.key}`}
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<View style={rowStyle} testID={`agent-profile-feature-row-${feature.id}`}>
|
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
|
||||||
<View style={styles.featureMeta}>
|
<View style={styles.featureMeta}>
|
||||||
<Text style={styles.featureLabel} numberOfLines={1}>
|
<Text style={styles.featureLabel} numberOfLines={1}>
|
||||||
{feature.label}
|
{control.label}
|
||||||
</Text>
|
</Text>
|
||||||
{feature.description ? (
|
{control.description ? (
|
||||||
<Text style={styles.featureDescription} numberOfLines={2}>
|
<Text style={styles.featureDescription} numberOfLines={2}>
|
||||||
{feature.description}
|
{control.description}
|
||||||
</Text>
|
</Text>
|
||||||
) : null}
|
) : null}
|
||||||
</View>
|
</View>
|
||||||
<Switch
|
<Switch
|
||||||
value={feature.value === true}
|
value={readToggleOption(control, options)}
|
||||||
onValueChange={handleToggle}
|
onValueChange={handleToggle}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
accessibilityLabel={feature.label}
|
accessibilityLabel={control.label}
|
||||||
testID={`agent-profile-feature-switch-${feature.id}`}
|
testID={`agent-profile-feature-switch-${control.key}`}
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1304,7 +1304,8 @@ function collectAgentSetupDiffs(left: AgentScreenAgent, right: AgentScreenAgent)
|
|||||||
if (left.runtimeInfo?.thinkingOptionId !== right.runtimeInfo?.thinkingOptionId) {
|
if (left.runtimeInfo?.thinkingOptionId !== right.runtimeInfo?.thinkingOptionId) {
|
||||||
reasons.push("agent.runtimeInfo.thinkingOptionId");
|
reasons.push("agent.runtimeInfo.thinkingOptionId");
|
||||||
}
|
}
|
||||||
if (left.features !== right.features) reasons.push("agent.features");
|
if (left.options !== right.options) reasons.push("agent.options");
|
||||||
|
if (left.controls !== right.controls) reasons.push("agent.controls");
|
||||||
return reasons;
|
return reasons;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -40,16 +40,7 @@ function createAgent(overrides: Partial<Agent> = {}): Agent {
|
|||||||
cwd: "/repo",
|
cwd: "/repo",
|
||||||
model: "agent-model",
|
model: "agent-model",
|
||||||
thinkingOptionId: "think-hard",
|
thinkingOptionId: "think-hard",
|
||||||
features: [
|
options: { "web-search": true, effort: "high" },
|
||||||
{ 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,
|
parentAgentId: null,
|
||||||
labels: {},
|
labels: {},
|
||||||
...overrides,
|
...overrides,
|
||||||
@@ -114,7 +105,7 @@ describe("buildDraftAgentSetup", () => {
|
|||||||
modeId: "mode-current",
|
modeId: "mode-current",
|
||||||
model: "agent-model",
|
model: "agent-model",
|
||||||
thinkingOptionId: "think-hard",
|
thinkingOptionId: "think-hard",
|
||||||
featureValues: {
|
providerOptions: {
|
||||||
"web-search": true,
|
"web-search": true,
|
||||||
effort: "high",
|
effort: "high",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -65,17 +65,12 @@ export function resolveClientSlashCommand(input: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function buildDraftAgentSetup(agent: Agent): WorkspaceDraftTabSetup {
|
export function buildDraftAgentSetup(agent: Agent): WorkspaceDraftTabSetup {
|
||||||
const featureValues: Record<string, unknown> = {};
|
|
||||||
for (const feature of agent.features ?? []) {
|
|
||||||
featureValues[feature.id] = feature.value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
provider: agent.provider,
|
provider: agent.provider,
|
||||||
cwd: agent.cwd,
|
cwd: agent.cwd,
|
||||||
modeId: agent.currentModeId ?? agent.runtimeInfo?.modeId ?? null,
|
modeId: agent.currentModeId ?? agent.runtimeInfo?.modeId ?? null,
|
||||||
model: agent.model ?? agent.runtimeInfo?.model ?? null,
|
model: agent.model ?? agent.runtimeInfo?.model ?? null,
|
||||||
thinkingOptionId: agent.thinkingOptionId ?? agent.runtimeInfo?.thinkingOptionId ?? null,
|
thinkingOptionId: agent.thinkingOptionId ?? agent.runtimeInfo?.thinkingOptionId ?? null,
|
||||||
featureValues,
|
providerOptions: { ...agent.options },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import type { AgentFeature, AgentMode, AgentSelectOption } from "@getpaseo/protocol/agent-types";
|
import type {
|
||||||
|
AgentMode,
|
||||||
|
AgentOptionControl,
|
||||||
|
AgentSelectOption,
|
||||||
|
} from "@getpaseo/protocol/agent-types";
|
||||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||||
import type { CommandCenterContribution } from "./contributions";
|
import type { CommandCenterContribution } from "./contributions";
|
||||||
import {
|
import {
|
||||||
@@ -31,7 +35,7 @@ const ICONS: AgentControlContributionSource["icons"] = {
|
|||||||
thinking: TestIcon,
|
thinking: TestIcon,
|
||||||
planMode: TestIcon,
|
planMode: TestIcon,
|
||||||
mode: () => TestIcon,
|
mode: () => TestIcon,
|
||||||
feature: () => TestIcon,
|
control: () => TestIcon,
|
||||||
};
|
};
|
||||||
|
|
||||||
function provider(input: {
|
function provider(input: {
|
||||||
@@ -65,8 +69,8 @@ function provider(input: {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleFeature(id: string, value = false, icon?: string): AgentFeature {
|
function toggleControl(key: string, icon?: string): AgentOptionControl {
|
||||||
return { type: "toggle", id, label: id, value, icon };
|
return { type: "toggle", key, label: key, icon };
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeSource(
|
function makeSource(
|
||||||
@@ -75,7 +79,7 @@ function makeSource(
|
|||||||
models?: Partial<AgentControlContributionSource["models"]>;
|
models?: Partial<AgentControlContributionSource["models"]>;
|
||||||
thinking?: Partial<AgentControlContributionSource["thinking"]>;
|
thinking?: Partial<AgentControlContributionSource["thinking"]>;
|
||||||
modes?: Partial<NonNullable<AgentControlContributionSource["modes"]>>;
|
modes?: Partial<NonNullable<AgentControlContributionSource["modes"]>>;
|
||||||
features?: Partial<AgentControlContributionSource["features"]>;
|
optionControls?: Partial<AgentControlContributionSource["optionControls"]>;
|
||||||
} = {},
|
} = {},
|
||||||
): AgentControlContributionSource {
|
): AgentControlContributionSource {
|
||||||
return {
|
return {
|
||||||
@@ -104,10 +108,11 @@ function makeSource(
|
|||||||
select: () => undefined,
|
select: () => undefined,
|
||||||
...overrides.modes,
|
...overrides.modes,
|
||||||
},
|
},
|
||||||
features: {
|
optionControls: {
|
||||||
list: [],
|
controls: [],
|
||||||
set: () => undefined,
|
options: {},
|
||||||
...overrides.features,
|
onSetOption: () => undefined,
|
||||||
|
...overrides.optionControls,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -133,7 +138,7 @@ describe("Command Center agent-control contributions", () => {
|
|||||||
const contributions = buildAgentControlContributions({
|
const contributions = buildAgentControlContributions({
|
||||||
...makeSource({
|
...makeSource({
|
||||||
models: { providers: [provider({ id: "claude", label: "Claude" })] },
|
models: { providers: [provider({ id: "claude", label: "Claude" })] },
|
||||||
features: { list: [toggleFeature("plan_mode", true)] },
|
optionControls: { controls: [toggleControl("plan_mode")], options: { plan_mode: true } },
|
||||||
}),
|
}),
|
||||||
modes: undefined,
|
modes: undefined,
|
||||||
});
|
});
|
||||||
@@ -323,9 +328,10 @@ describe("Command Center agent-control contributions", () => {
|
|||||||
selectedId: "default",
|
selectedId: "default",
|
||||||
defaultModeId: "default",
|
defaultModeId: "default",
|
||||||
},
|
},
|
||||||
features: {
|
optionControls: {
|
||||||
list: [toggleFeature("plan_mode", true, "list-todo")],
|
controls: [toggleControl("plan_mode", "list-todo")],
|
||||||
set: (id, value) => {
|
options: { plan_mode: true },
|
||||||
|
onSetOption: (id, value) => {
|
||||||
calls.push([id, value]);
|
calls.push([id, value]);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -341,9 +347,10 @@ describe("Command Center agent-control contributions", () => {
|
|||||||
const calls: [string, unknown][] = [];
|
const calls: [string, unknown][] = [];
|
||||||
const contributions = buildAgentControlContributions(
|
const contributions = buildAgentControlContributions(
|
||||||
makeSource({
|
makeSource({
|
||||||
features: {
|
optionControls: {
|
||||||
list: [toggleFeature("fast_mode", false, "zap"), toggleFeature("auto_accept", true)],
|
controls: [toggleControl("fast_mode", "zap"), toggleControl("auto_accept")],
|
||||||
set: (id, value) => {
|
options: { fast_mode: false, auto_accept: true },
|
||||||
|
onSetOption: (id, value) => {
|
||||||
calls.push([id, value]);
|
calls.push([id, value]);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -376,7 +383,7 @@ describe("Command Center agent-control contributions", () => {
|
|||||||
selectedId: "default",
|
selectedId: "default",
|
||||||
defaultModeId: "default",
|
defaultModeId: "default",
|
||||||
},
|
},
|
||||||
features: { list: [toggleFeature("fast_mode")] },
|
optionControls: { controls: [toggleControl("fast_mode")], options: {} },
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
const ranks = new Map<string, number>();
|
const ranks = new Map<string, number>();
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import type {
|
import type {
|
||||||
AgentFeature,
|
|
||||||
AgentMode,
|
AgentMode,
|
||||||
|
AgentOptionControl,
|
||||||
AgentProvider,
|
AgentProvider,
|
||||||
AgentSelectOption,
|
AgentSelectOption,
|
||||||
} from "@getpaseo/protocol/agent-types";
|
} from "@getpaseo/protocol/agent-types";
|
||||||
|
import { readToggleOption, type ComposerOptionControls } from "@/agent-controls/option-controls";
|
||||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||||
import { formatAgentModeLabel, formatThinkingOptionLabel } from "@/agent-controls/labels";
|
import { formatAgentModeLabel, formatThinkingOptionLabel } from "@/agent-controls/labels";
|
||||||
import {
|
import {
|
||||||
@@ -61,7 +62,7 @@ export interface AgentControlContributionIcons {
|
|||||||
thinking: CommandCenterIcon;
|
thinking: CommandCenterIcon;
|
||||||
planMode: CommandCenterIcon;
|
planMode: CommandCenterIcon;
|
||||||
mode(modeId: string): CommandCenterIcon;
|
mode(modeId: string): CommandCenterIcon;
|
||||||
feature(feature: AgentFeature): CommandCenterIcon;
|
control(control: AgentOptionControl): CommandCenterIcon;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CommandCenterChoice {
|
interface CommandCenterChoice {
|
||||||
@@ -105,10 +106,7 @@ export interface AgentControlContributionSource {
|
|||||||
defaultModeId: string | null;
|
defaultModeId: string | null;
|
||||||
select(modeId: string): void | Promise<void>;
|
select(modeId: string): void | Promise<void>;
|
||||||
};
|
};
|
||||||
features: {
|
optionControls: ComposerOptionControls;
|
||||||
list: readonly AgentFeature[];
|
|
||||||
set(featureId: string, value: unknown): void | Promise<void>;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildContributions(
|
function buildContributions(
|
||||||
@@ -242,18 +240,19 @@ function toggleChoices(input: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function buildPlanModeGroup(source: AgentControlContributionSource): CommandCenterChoiceGroup {
|
function buildPlanModeGroup(source: AgentControlContributionSource): CommandCenterChoiceGroup {
|
||||||
const planFeature = source.features.list.find(
|
const { controls, options, onSetOption } = source.optionControls;
|
||||||
(feature) => feature.id === PLAN_MODE_FEATURE_ID && feature.type === "toggle",
|
const planControl = controls.find(
|
||||||
|
(control) => control.key === PLAN_MODE_FEATURE_ID && control.type === "toggle",
|
||||||
);
|
);
|
||||||
let choices: CommandCenterChoice[] = [];
|
let choices: CommandCenterChoice[] = [];
|
||||||
if (planFeature?.type === "toggle") {
|
if (planControl?.type === "toggle") {
|
||||||
choices = toggleChoices({
|
choices = toggleChoices({
|
||||||
source,
|
source,
|
||||||
key: "plan",
|
key: "plan",
|
||||||
icon: source.icons.feature(planFeature),
|
icon: source.icons.control(planControl),
|
||||||
isOn: planFeature.value,
|
isOn: readToggleOption(planControl, options),
|
||||||
turnOn: () => source.features.set(PLAN_MODE_FEATURE_ID, true),
|
turnOn: () => onSetOption(PLAN_MODE_FEATURE_ID, true),
|
||||||
turnOff: () => source.features.set(PLAN_MODE_FEATURE_ID, false),
|
turnOff: () => onSetOption(PLAN_MODE_FEATURE_ID, false),
|
||||||
});
|
});
|
||||||
} else if (source.modes) {
|
} else if (source.modes) {
|
||||||
const modes = source.modes;
|
const modes = source.modes;
|
||||||
@@ -280,18 +279,19 @@ function buildPlanModeGroup(source: AgentControlContributionSource): CommandCent
|
|||||||
}
|
}
|
||||||
|
|
||||||
function buildFastModeGroup(source: AgentControlContributionSource): CommandCenterChoiceGroup {
|
function buildFastModeGroup(source: AgentControlContributionSource): CommandCenterChoiceGroup {
|
||||||
const fastFeature = source.features.list.find(
|
const { controls, options, onSetOption } = source.optionControls;
|
||||||
(feature) => feature.id === FAST_MODE_FEATURE_ID && feature.type === "toggle",
|
const fastControl = controls.find(
|
||||||
|
(control) => control.key === FAST_MODE_FEATURE_ID && control.type === "toggle",
|
||||||
);
|
);
|
||||||
const choices =
|
const choices =
|
||||||
fastFeature?.type === "toggle"
|
fastControl?.type === "toggle"
|
||||||
? toggleChoices({
|
? toggleChoices({
|
||||||
source,
|
source,
|
||||||
key: "fast",
|
key: "fast",
|
||||||
icon: source.icons.feature(fastFeature),
|
icon: source.icons.control(fastControl),
|
||||||
isOn: fastFeature.value,
|
isOn: readToggleOption(fastControl, options),
|
||||||
turnOn: () => source.features.set(FAST_MODE_FEATURE_ID, true),
|
turnOn: () => onSetOption(FAST_MODE_FEATURE_ID, true),
|
||||||
turnOff: () => source.features.set(FAST_MODE_FEATURE_ID, false),
|
turnOff: () => onSetOption(FAST_MODE_FEATURE_ID, false),
|
||||||
})
|
})
|
||||||
: [];
|
: [];
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1,11 +1,6 @@
|
|||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import type {
|
import type { AgentMode, AgentProvider, AgentSelectOption } from "@getpaseo/protocol/agent-types";
|
||||||
AgentFeature,
|
|
||||||
AgentMode,
|
|
||||||
AgentProvider,
|
|
||||||
AgentSelectOption,
|
|
||||||
} from "@getpaseo/protocol/agent-types";
|
|
||||||
import type { AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
|
import type { AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
|
||||||
import {
|
import {
|
||||||
getAgentFeatureIcon,
|
getAgentFeatureIcon,
|
||||||
@@ -14,6 +9,7 @@ import {
|
|||||||
ThinkingIcon,
|
ThinkingIcon,
|
||||||
} from "@/agent-controls/icons";
|
} from "@/agent-controls/icons";
|
||||||
import { useProviderIcons } from "@/components/provider-icons";
|
import { useProviderIcons } from "@/components/provider-icons";
|
||||||
|
import type { ComposerOptionControls } from "@/agent-controls/option-controls";
|
||||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||||
import {
|
import {
|
||||||
buildAgentControlContributions,
|
buildAgentControlContributions,
|
||||||
@@ -44,15 +40,15 @@ export interface AgentControlCommandCenterSource {
|
|||||||
selectedId: string | null | undefined;
|
selectedId: string | null | undefined;
|
||||||
select(modeId: string): void | Promise<void>;
|
select(modeId: string): void | Promise<void>;
|
||||||
};
|
};
|
||||||
features: {
|
/** Absent when the surface cannot change options (the agent has no client). */
|
||||||
list: readonly AgentFeature[] | undefined;
|
optionControls: ComposerOptionControls | null;
|
||||||
set?: (featureId: string, value: unknown) => void | Promise<void>;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function ignoreAgentFeatureChange(): void {
|
const NO_OPTION_CONTROLS: ComposerOptionControls = {
|
||||||
return;
|
controls: [],
|
||||||
}
|
options: {},
|
||||||
|
onSetOption: () => undefined,
|
||||||
|
};
|
||||||
|
|
||||||
function resolveDefaultModeId(
|
function resolveDefaultModeId(
|
||||||
provider: string | null | undefined,
|
provider: string | null | undefined,
|
||||||
@@ -87,7 +83,7 @@ export function useAgentControlCommandCenterActions(input: {
|
|||||||
}): void {
|
}): void {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { controls } = input;
|
const { controls } = input;
|
||||||
const { features, models, modes, thinking } = controls;
|
const { optionControls, models, modes, thinking } = controls;
|
||||||
const getProviderIcon = useProviderIcons(controls.serverId);
|
const getProviderIcon = useProviderIcons(controls.serverId);
|
||||||
const actions = useMemo(
|
const actions = useMemo(
|
||||||
() =>
|
() =>
|
||||||
@@ -104,7 +100,7 @@ export function useAgentControlCommandCenterActions(input: {
|
|||||||
getCommandCenterIcon(
|
getCommandCenterIcon(
|
||||||
getAgentModeIcon(controls.provider ?? "", modeId, controls.providerDefinitions),
|
getAgentModeIcon(controls.provider ?? "", modeId, controls.providerDefinitions),
|
||||||
),
|
),
|
||||||
feature: (feature) => getCommandCenterIcon(getAgentFeatureIcon(feature.icon)),
|
control: (control) => getCommandCenterIcon(getAgentFeatureIcon(control.icon)),
|
||||||
},
|
},
|
||||||
models: {
|
models: {
|
||||||
providers: models.providers,
|
providers: models.providers,
|
||||||
@@ -123,10 +119,7 @@ export function useAgentControlCommandCenterActions(input: {
|
|||||||
modes?.select,
|
modes?.select,
|
||||||
resolveDefaultModeId(controls.provider, controls.providerDefinitions),
|
resolveDefaultModeId(controls.provider, controls.providerDefinitions),
|
||||||
),
|
),
|
||||||
features: {
|
optionControls: optionControls ?? NO_OPTION_CONTROLS,
|
||||||
list: features.set ? (features.list ?? []) : [],
|
|
||||||
set: features.set ?? ignoreAgentFeatureChange,
|
|
||||||
},
|
|
||||||
}),
|
}),
|
||||||
[
|
[
|
||||||
getProviderIcon,
|
getProviderIcon,
|
||||||
@@ -134,8 +127,7 @@ export function useAgentControlCommandCenterActions(input: {
|
|||||||
controls.provider,
|
controls.provider,
|
||||||
controls.providerDefinitions,
|
controls.providerDefinitions,
|
||||||
controls.serverId,
|
controls.serverId,
|
||||||
features.list,
|
optionControls,
|
||||||
features.set,
|
|
||||||
models.providers,
|
models.providers,
|
||||||
models.select,
|
models.select,
|
||||||
models.selectedModelId,
|
models.selectedModelId,
|
||||||
|
|||||||
@@ -0,0 +1,175 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
|
import { Scan } from "lucide-react-native";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import type { AgentOptionControl } from "@getpaseo/protocol/agent-types";
|
||||||
|
import type { ToastApi } from "@/components/toast-host";
|
||||||
|
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||||
|
import { ComposerControls, type ComposerControlItem } from "./composer-control";
|
||||||
|
import { useAgentControlItems } from "./control-items";
|
||||||
|
import { resolveComposerControlPresentation } from "./layout";
|
||||||
|
|
||||||
|
beforeEach(() => vi.stubGlobal("React", React));
|
||||||
|
afterEach(cleanup);
|
||||||
|
|
||||||
|
const base = { id: "x", title: "Context", icon: Scan };
|
||||||
|
|
||||||
|
type RecordingToast = ToastApi & { error: ReturnType<typeof vi.fn> };
|
||||||
|
|
||||||
|
function createToast(): RecordingToast {
|
||||||
|
return { error: vi.fn() } as unknown as RecordingToast;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ignoreOpenChange() {}
|
||||||
|
|
||||||
|
function Controls({
|
||||||
|
items,
|
||||||
|
surface,
|
||||||
|
toast,
|
||||||
|
}: {
|
||||||
|
items: ComposerControlItem[];
|
||||||
|
surface: "toolbar" | "sheet";
|
||||||
|
toast: ToastApi;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ToastApiProvider api={toast}>
|
||||||
|
<ComposerControls
|
||||||
|
items={items}
|
||||||
|
surface={surface}
|
||||||
|
openId={null}
|
||||||
|
onOpenIdChange={ignoreOpenChange}
|
||||||
|
/>
|
||||||
|
</ToastApiProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderControls(items: ComposerControlItem[], surface: "toolbar" | "sheet" = "toolbar") {
|
||||||
|
const toast = createToast();
|
||||||
|
render(<Controls items={items} surface={surface} toast={toast} />);
|
||||||
|
return toast;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("ComposerControls", () => {
|
||||||
|
it("shows a select's chosen label, or only its icon when asked", () => {
|
||||||
|
const select: ComposerControlItem = {
|
||||||
|
...base,
|
||||||
|
type: "select",
|
||||||
|
value: "large",
|
||||||
|
choices: [
|
||||||
|
{ value: "small", label: "Small" },
|
||||||
|
{ value: "large", label: "Large" },
|
||||||
|
],
|
||||||
|
onChange: () => undefined,
|
||||||
|
};
|
||||||
|
renderControls([select]);
|
||||||
|
expect(screen.getByRole("button", { name: "Context" }).textContent).toContain("Large");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("names the choice on an icon-only select, without drawing it", () => {
|
||||||
|
renderControls([
|
||||||
|
{
|
||||||
|
...base,
|
||||||
|
type: "select",
|
||||||
|
value: "large",
|
||||||
|
iconOnly: true,
|
||||||
|
choices: [{ value: "large", label: "Large" }],
|
||||||
|
onChange: () => undefined,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
const trigger = screen.getByRole("button", { name: "Context: Large" });
|
||||||
|
expect(trigger.textContent).not.toContain("Large");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("flips a toggle on press in the toolbar", () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
renderControls([{ ...base, type: "toggle", value: true, onChange }]);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Context" }));
|
||||||
|
expect(onChange).toHaveBeenCalledWith(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lists a toggle as On or Off in the sheet", () => {
|
||||||
|
renderControls([{ ...base, type: "toggle", value: true, onChange: () => undefined }], "sheet");
|
||||||
|
expect(screen.getByRole("button", { name: "Context" }).textContent).toContain("On");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports a failed command the way a built-in control does, and frees the control", async () => {
|
||||||
|
let reject: (error: Error) => void = () => undefined;
|
||||||
|
const onPress = vi.fn(
|
||||||
|
() =>
|
||||||
|
new Promise<void>((_resolve, rejectPromise) => {
|
||||||
|
reject = rejectPromise;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const toast = renderControls([{ ...base, type: "action", onPress }]);
|
||||||
|
const button = screen.getByRole("button", { name: "Context" });
|
||||||
|
|
||||||
|
fireEvent.click(button);
|
||||||
|
// While the command is in flight the control cannot be pressed again.
|
||||||
|
await waitFor(() => expect(button.getAttribute("aria-disabled")).toBe("true"));
|
||||||
|
fireEvent.click(button);
|
||||||
|
expect(onPress).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
reject(new Error("Unknown or unavailable provider: x"));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(toast.error).toHaveBeenCalledWith("Unknown or unavailable provider: x"),
|
||||||
|
);
|
||||||
|
await waitFor(() => expect(button.getAttribute("aria-disabled")).not.toBe("true"));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports a command that throws before it returns", () => {
|
||||||
|
const toast = renderControls([
|
||||||
|
{
|
||||||
|
...base,
|
||||||
|
type: "action",
|
||||||
|
onPress: () => {
|
||||||
|
throw new Error("No such control");
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Context" }));
|
||||||
|
expect(toast.error).toHaveBeenCalledWith("No such control");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const FAST_ON = { fast_mode: true };
|
||||||
|
|
||||||
|
describe("provider option controls", () => {
|
||||||
|
const fastMode: AgentOptionControl = {
|
||||||
|
type: "toggle",
|
||||||
|
key: "fast_mode",
|
||||||
|
label: "Fast",
|
||||||
|
defaultValue: false,
|
||||||
|
};
|
||||||
|
function OptionControls({
|
||||||
|
options,
|
||||||
|
onSetOption,
|
||||||
|
}: {
|
||||||
|
options: Record<string, unknown>;
|
||||||
|
onSetOption: (key: string, value: unknown) => void;
|
||||||
|
}) {
|
||||||
|
const optionControls = React.useMemo(
|
||||||
|
() => ({ controls: [fastMode], options, onSetOption }),
|
||||||
|
[onSetOption, options],
|
||||||
|
);
|
||||||
|
const items = useAgentControlItems({
|
||||||
|
surface: "toolbar",
|
||||||
|
presentation: resolveComposerControlPresentation("full"),
|
||||||
|
thinking: null,
|
||||||
|
optionControls,
|
||||||
|
});
|
||||||
|
return <Controls items={items.features} surface="toolbar" toast={TOAST} />;
|
||||||
|
}
|
||||||
|
const TOAST = createToast();
|
||||||
|
|
||||||
|
function recordWrites(writes: Array<[string, unknown]>) {
|
||||||
|
return (key: string, value: unknown) => void writes.push([key, value]);
|
||||||
|
}
|
||||||
|
|
||||||
|
it("write the toggled option from the agent's current options", () => {
|
||||||
|
const writes: Array<[string, unknown]> = [];
|
||||||
|
const onSetOption = recordWrites(writes);
|
||||||
|
render(<OptionControls options={FAST_ON} onSetOption={onSetOption} />);
|
||||||
|
fireEvent.click(screen.getByTestId("agent-feature-fast_mode"));
|
||||||
|
expect(writes).toEqual([["fast_mode", false]]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
type ReactElement,
|
||||||
|
} from "react";
|
||||||
|
import type { TFunction } from "i18next";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { Text, View } from "react-native";
|
||||||
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
|
import type { AgentControlIcon } from "@/agent-controls/icons";
|
||||||
|
import type { SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||||
|
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
|
||||||
|
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||||
|
import { AgentControlTrigger } from "@/composer/agent-controls/control";
|
||||||
|
import { useToast } from "@/contexts/toast-api-context";
|
||||||
|
import { toErrorMessage } from "@/utils/error-messages";
|
||||||
|
|
||||||
|
interface ComposerControlBase {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
icon: AgentControlIcon;
|
||||||
|
/** Tints the icon; muted when absent. */
|
||||||
|
highlight?: "blue" | "green" | "yellow";
|
||||||
|
/** Defaults to the title, or to "title: choice" on an icon-only select. */
|
||||||
|
tooltip?: string;
|
||||||
|
/** Defaults to the tooltip. */
|
||||||
|
accessibilityLabel?: string;
|
||||||
|
testID?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ComposerControlChoice {
|
||||||
|
value: string;
|
||||||
|
label: string;
|
||||||
|
description?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One control in the composer's toolbar, drawn from data. Provider option controls, thinking and
|
||||||
|
* plugin controls all come through here, so each is an icon in the toolbar and a row in the sheet.
|
||||||
|
*/
|
||||||
|
export type ComposerControlItem =
|
||||||
|
| (ComposerControlBase & {
|
||||||
|
type: "toggle";
|
||||||
|
value: boolean;
|
||||||
|
onChange: (value: boolean) => void | Promise<void>;
|
||||||
|
})
|
||||||
|
| (ComposerControlBase & {
|
||||||
|
type: "select";
|
||||||
|
value: string | null;
|
||||||
|
choices: readonly ComposerControlChoice[];
|
||||||
|
onChange: (value: string) => void | Promise<void>;
|
||||||
|
/** The toolbar trigger shows only the icon. */
|
||||||
|
iconOnly?: boolean;
|
||||||
|
showCaret?: boolean;
|
||||||
|
searchable?: boolean;
|
||||||
|
desktopMinWidth?: number;
|
||||||
|
renderOption?: (args: {
|
||||||
|
option: ComboboxOption;
|
||||||
|
selected: boolean;
|
||||||
|
active: boolean;
|
||||||
|
onPress: () => void;
|
||||||
|
}) => ReactElement;
|
||||||
|
})
|
||||||
|
| (ComposerControlBase & {
|
||||||
|
type: "action";
|
||||||
|
onPress: () => void | Promise<void>;
|
||||||
|
});
|
||||||
|
|
||||||
|
export type ComposerControlSurface = "toolbar" | "sheet";
|
||||||
|
|
||||||
|
const ComposerControlSurfaceContext = createContext<ComposerControlSurface>("toolbar");
|
||||||
|
export const ComposerControlSurfaceProvider = ComposerControlSurfaceContext.Provider;
|
||||||
|
|
||||||
|
/** Where the control being drawn sits: the toolbar, or a row in the overflow sheet. */
|
||||||
|
export function useComposerControlSurface(): ComposerControlSurface {
|
||||||
|
return useContext(ComposerControlSurfaceContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ComposerControlProps {
|
||||||
|
item: ComposerControlItem;
|
||||||
|
surface: ComposerControlSurface;
|
||||||
|
disabled?: boolean;
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
/** Runs after a toolbar toggle or action, so the composer can take focus back. */
|
||||||
|
onActionComplete?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ControlView {
|
||||||
|
options: ComboboxOption[];
|
||||||
|
/** The list's selected id. */
|
||||||
|
selectedId: string;
|
||||||
|
/** What the trigger shows beside the icon. */
|
||||||
|
value: string;
|
||||||
|
iconOnly: boolean;
|
||||||
|
tooltip: string;
|
||||||
|
/** Whether pressing the trigger opens a list instead of acting. */
|
||||||
|
opensList: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function describeControl(
|
||||||
|
item: ComposerControlItem,
|
||||||
|
surface: ComposerControlSurface,
|
||||||
|
t: TFunction,
|
||||||
|
): ControlView {
|
||||||
|
const isSheet = surface === "sheet";
|
||||||
|
if (item.type === "action") {
|
||||||
|
return {
|
||||||
|
options: [],
|
||||||
|
selectedId: "",
|
||||||
|
value: "",
|
||||||
|
iconOnly: true,
|
||||||
|
tooltip: item.tooltip ?? item.title,
|
||||||
|
opensList: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (item.type === "toggle") {
|
||||||
|
const label = item.value ? t("agentControls.features.on") : t("agentControls.features.off");
|
||||||
|
return {
|
||||||
|
options: [
|
||||||
|
{ id: "true", label: t("agentControls.features.on") },
|
||||||
|
{ id: "false", label: t("agentControls.features.off") },
|
||||||
|
],
|
||||||
|
selectedId: String(item.value),
|
||||||
|
value: label,
|
||||||
|
iconOnly: true,
|
||||||
|
tooltip: item.tooltip ?? item.title,
|
||||||
|
opensList: isSheet,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const choiceLabel =
|
||||||
|
item.choices.find((choice) => choice.value === item.value)?.label ?? item.title;
|
||||||
|
const iconOnly = item.iconOnly === true;
|
||||||
|
return {
|
||||||
|
options: item.choices.map((choice) => ({
|
||||||
|
id: choice.value,
|
||||||
|
label: choice.label,
|
||||||
|
description: choice.description,
|
||||||
|
})),
|
||||||
|
selectedId: String(item.value ?? ""),
|
||||||
|
value: choiceLabel,
|
||||||
|
iconOnly,
|
||||||
|
// An icon-only trigger names its value; a sheet row shows the value, so it names the action.
|
||||||
|
tooltip: iconOnly && !isSheet ? `${item.title}: ${choiceLabel}` : (item.tooltip ?? item.title),
|
||||||
|
opensList: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ComposerControl({
|
||||||
|
item,
|
||||||
|
surface,
|
||||||
|
disabled = false,
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
onActionComplete,
|
||||||
|
}: ComposerControlProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const anchorRef = useRef<View>(null);
|
||||||
|
const isSheet = surface === "sheet";
|
||||||
|
const sheetHeader = useMemo<SheetHeader>(() => ({ title: item.title }), [item.title]);
|
||||||
|
const view = useMemo(() => describeControl(item, surface, t), [item, surface, t]);
|
||||||
|
|
||||||
|
// A command that returns a promise keeps the control pending until it settles, and a failure
|
||||||
|
// reaches the user the way a built-in live control's does.
|
||||||
|
const toast = useToast();
|
||||||
|
const [pending, setPending] = useState(false);
|
||||||
|
const run = useCallback(
|
||||||
|
(invoke: () => void | Promise<void>) => {
|
||||||
|
try {
|
||||||
|
const result = invoke();
|
||||||
|
if (!result) return;
|
||||||
|
setPending(true);
|
||||||
|
result
|
||||||
|
.catch((error: unknown) => toast.error(toErrorMessage(error)))
|
||||||
|
.finally(() => setPending(false));
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(toErrorMessage(error));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[toast],
|
||||||
|
);
|
||||||
|
const handlePress = useCallback(() => {
|
||||||
|
if (item.type === "toggle") run(() => item.onChange(!item.value));
|
||||||
|
else if (item.type === "action") run(item.onPress);
|
||||||
|
onActionComplete?.();
|
||||||
|
}, [item, onActionComplete, run]);
|
||||||
|
const handleOpenPress = useCallback(() => onOpenChange(!open), [onOpenChange, open]);
|
||||||
|
const handleSelect = useCallback(
|
||||||
|
(value: string) => {
|
||||||
|
if (item.type === "select") run(() => item.onChange(value));
|
||||||
|
else if (item.type === "toggle") run(() => item.onChange(value === "true"));
|
||||||
|
},
|
||||||
|
[item, run],
|
||||||
|
);
|
||||||
|
|
||||||
|
const select = item.type === "select" ? item : null;
|
||||||
|
const trigger = (
|
||||||
|
<AgentControlTrigger
|
||||||
|
ref={anchorRef}
|
||||||
|
icon={item.icon}
|
||||||
|
iconColor={item.highlight ? styles[item.highlight].color : undefined}
|
||||||
|
surface={surface}
|
||||||
|
label={item.title}
|
||||||
|
value={view.value}
|
||||||
|
showToolbarLabel={!view.iconOnly}
|
||||||
|
showCaret={select?.showCaret === true && !isSheet}
|
||||||
|
open={view.opensList && open}
|
||||||
|
disabled={disabled || pending}
|
||||||
|
onPress={view.opensList ? handleOpenPress : handlePress}
|
||||||
|
accessibilityLabel={item.accessibilityLabel ?? view.tooltip}
|
||||||
|
testID={item.testID}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{isSheet ? (
|
||||||
|
trigger
|
||||||
|
) : (
|
||||||
|
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
|
||||||
|
<TooltipTrigger asChild triggerRefProp="ref">
|
||||||
|
{trigger}
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="top" align="center" offset={8}>
|
||||||
|
<Text style={styles.tooltipText}>{view.tooltip}</Text>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
{view.opensList ? (
|
||||||
|
<Combobox
|
||||||
|
options={view.options}
|
||||||
|
value={view.selectedId}
|
||||||
|
onSelect={handleSelect}
|
||||||
|
open={open}
|
||||||
|
onOpenChange={onOpenChange}
|
||||||
|
anchorRef={anchorRef}
|
||||||
|
presentation={isSheet ? "push" : undefined}
|
||||||
|
desktopPlacement={isSheet ? undefined : "top-start"}
|
||||||
|
desktopMinWidth={select?.desktopMinWidth}
|
||||||
|
searchable={select ? select.searchable : false}
|
||||||
|
renderOption={select?.renderOption}
|
||||||
|
header={isSheet ? sheetHeader : undefined}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ComposerControlsProps {
|
||||||
|
items: readonly ComposerControlItem[];
|
||||||
|
surface: ComposerControlSurface;
|
||||||
|
disabled?: boolean;
|
||||||
|
/** The id of the item whose list is open. */
|
||||||
|
openId: string | null;
|
||||||
|
onOpenIdChange: (id: string | null) => void;
|
||||||
|
onActionComplete?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A row of Paseo-owned controls that share one open list at a time. */
|
||||||
|
export function ComposerControls({
|
||||||
|
items,
|
||||||
|
onOpenIdChange,
|
||||||
|
openId,
|
||||||
|
...rest
|
||||||
|
}: ComposerControlsProps) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{items.map((item) => (
|
||||||
|
<ComposerControlSlot
|
||||||
|
key={item.id}
|
||||||
|
item={item}
|
||||||
|
open={openId === item.id}
|
||||||
|
onOpenIdChange={onOpenIdChange}
|
||||||
|
{...rest}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ComposerControlSlot({
|
||||||
|
item,
|
||||||
|
open,
|
||||||
|
onOpenIdChange,
|
||||||
|
...rest
|
||||||
|
}: Omit<ComposerControlsProps, "items" | "openId"> & { item: ComposerControlItem; open: boolean }) {
|
||||||
|
const handleOpenChange = useCallback(
|
||||||
|
(next: boolean) => onOpenIdChange(next ? item.id : null),
|
||||||
|
[item.id, onOpenIdChange],
|
||||||
|
);
|
||||||
|
return <ComposerControl item={item} open={open} onOpenChange={handleOpenChange} {...rest} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const styles = StyleSheet.create((theme) => ({
|
||||||
|
blue: { color: theme.colors.palette.blue[400] },
|
||||||
|
green: { color: theme.colors.palette.green[400] },
|
||||||
|
yellow: { color: theme.colors.palette.yellow[400] },
|
||||||
|
tooltipText: {
|
||||||
|
color: theme.colors.foreground,
|
||||||
|
fontSize: theme.fontSize.base,
|
||||||
|
lineHeight: theme.fontSize.base * 1.4,
|
||||||
|
},
|
||||||
|
}));
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
import { useMemo } from "react";
|
||||||
|
import type { TFunction } from "i18next";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
|
import type { AgentOptionControl, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||||
|
import { getAgentFeatureIcon, ThinkingIcon } from "@/agent-controls/icons";
|
||||||
|
import {
|
||||||
|
getControlTooltip,
|
||||||
|
isControlActive,
|
||||||
|
readSelectOption,
|
||||||
|
readToggleOption,
|
||||||
|
type ComposerOptionControls,
|
||||||
|
} from "@/agent-controls/option-controls";
|
||||||
|
import { ComboboxItem, type ComboboxOption } from "@/components/ui/combobox";
|
||||||
|
import {
|
||||||
|
type ComposerControlItem,
|
||||||
|
type ComposerControlSurface,
|
||||||
|
} from "@/composer/agent-controls/composer-control";
|
||||||
|
import type { ComposerControlPresentation } from "@/composer/agent-controls/layout";
|
||||||
|
import { getAgentControlHintKey, getFeatureHighlightColor } from "@/composer/agent-controls/utils";
|
||||||
|
|
||||||
|
const SEARCH_THRESHOLD = 6;
|
||||||
|
|
||||||
|
function getFeatureHighlight(
|
||||||
|
control: AgentOptionControl,
|
||||||
|
options: ProviderOptions,
|
||||||
|
): ComposerControlItem["highlight"] {
|
||||||
|
if (!isControlActive(control, options)) return undefined;
|
||||||
|
const color = getFeatureHighlightColor(control.key);
|
||||||
|
return color === "default" ? undefined : color;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toFeatureItem(
|
||||||
|
control: AgentOptionControl,
|
||||||
|
optionControls: ComposerOptionControls,
|
||||||
|
): ComposerControlItem {
|
||||||
|
const { options, onSetOption } = optionControls;
|
||||||
|
const base = {
|
||||||
|
id: `feature-${control.key}`,
|
||||||
|
title: control.label,
|
||||||
|
icon: getAgentFeatureIcon(control.icon),
|
||||||
|
highlight: getFeatureHighlight(control, options),
|
||||||
|
testID: `agent-feature-${control.key}`,
|
||||||
|
};
|
||||||
|
if (control.type === "toggle") {
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
type: "toggle",
|
||||||
|
tooltip: getControlTooltip(control),
|
||||||
|
value: readToggleOption(control, options),
|
||||||
|
onChange: (value) => onSetOption(control.key, value),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const iconOnly = control.desktopTrigger === "icon";
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
type: "select",
|
||||||
|
tooltip: getControlTooltip(control),
|
||||||
|
value: readSelectOption(control, options),
|
||||||
|
choices: control.choices,
|
||||||
|
iconOnly,
|
||||||
|
onChange: (value) => onSetOption(control.key, value),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ThinkingControl {
|
||||||
|
options: readonly { id: string; label: string }[];
|
||||||
|
selectedId: string | undefined;
|
||||||
|
onSelect: (id: string) => void;
|
||||||
|
/** The select's displayed label, falling back like the compact model sheet. */
|
||||||
|
displayLabel: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The thinking select and the option controls, as the data `ComposerControl` draws. */
|
||||||
|
export function useAgentControlItems({
|
||||||
|
surface,
|
||||||
|
presentation,
|
||||||
|
thinking,
|
||||||
|
optionControls,
|
||||||
|
}: {
|
||||||
|
surface: ComposerControlSurface;
|
||||||
|
presentation: ComposerControlPresentation;
|
||||||
|
thinking: ThinkingControl | null;
|
||||||
|
optionControls: ComposerOptionControls | undefined;
|
||||||
|
}): { thinking: ComposerControlItem[]; features: ComposerControlItem[] } {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
const thinkingItem = useMemo(
|
||||||
|
() => (thinking ? [toThinkingItem({ thinking, surface, presentation, t })] : []),
|
||||||
|
[presentation, surface, t, thinking],
|
||||||
|
);
|
||||||
|
const features = useMemo(
|
||||||
|
() =>
|
||||||
|
optionControls
|
||||||
|
? optionControls.controls.map((control) => toFeatureItem(control, optionControls))
|
||||||
|
: [],
|
||||||
|
[optionControls],
|
||||||
|
);
|
||||||
|
return { thinking: thinkingItem, features };
|
||||||
|
}
|
||||||
|
|
||||||
|
function toThinkingItem({
|
||||||
|
thinking,
|
||||||
|
surface,
|
||||||
|
presentation,
|
||||||
|
t,
|
||||||
|
}: {
|
||||||
|
thinking: ThinkingControl;
|
||||||
|
surface: ComposerControlSurface;
|
||||||
|
presentation: ComposerControlPresentation;
|
||||||
|
t: TFunction;
|
||||||
|
}): ComposerControlItem {
|
||||||
|
const isSheet = surface === "sheet";
|
||||||
|
return {
|
||||||
|
id: "thinking",
|
||||||
|
type: "select",
|
||||||
|
title: t("agentControls.thinking.title"),
|
||||||
|
icon: ThinkingIcon,
|
||||||
|
tooltip: t(getAgentControlHintKey("thinking")),
|
||||||
|
accessibilityLabel: t("agentControls.thinking.selectWithValue", {
|
||||||
|
value: thinking.displayLabel,
|
||||||
|
}),
|
||||||
|
testID: isSheet ? "agent-controls-thinking" : "agent-thinking-selector",
|
||||||
|
value: thinking.options.some((option) => option.id === thinking.selectedId)
|
||||||
|
? (thinking.selectedId ?? null)
|
||||||
|
: (thinking.options[0]?.id ?? null),
|
||||||
|
choices: thinking.options.map((option) => ({ value: option.id, label: option.label })),
|
||||||
|
onChange: thinking.onSelect,
|
||||||
|
iconOnly: !presentation.showThinkingLabel,
|
||||||
|
showCaret: presentation.showCarets,
|
||||||
|
searchable: !isSheet && thinking.options.length > SEARCH_THRESHOLD,
|
||||||
|
desktopMinWidth: 200,
|
||||||
|
renderOption: (args) => <ThinkingOption {...args} />,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function ThinkingOption({
|
||||||
|
option,
|
||||||
|
selected,
|
||||||
|
active,
|
||||||
|
onPress,
|
||||||
|
}: {
|
||||||
|
option: ComboboxOption;
|
||||||
|
selected: boolean;
|
||||||
|
active: boolean;
|
||||||
|
onPress: () => void;
|
||||||
|
}) {
|
||||||
|
const leadingSlot = useMemo(
|
||||||
|
() => <ThinkingIcon size={16} color={styles.thinkingIcon.color} />,
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<ComboboxItem
|
||||||
|
label={option.label}
|
||||||
|
selected={selected}
|
||||||
|
active={active}
|
||||||
|
onPress={onPress}
|
||||||
|
leadingSlot={leadingSlot}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const styles = StyleSheet.create((theme) => ({
|
||||||
|
thinkingIcon: { color: theme.colors.foreground },
|
||||||
|
}));
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -34,6 +34,7 @@ describe("composer control layout", () => {
|
|||||||
hasThinking: true,
|
hasThinking: true,
|
||||||
hasMode: true,
|
hasMode: true,
|
||||||
features: [{ type: "toggle" as const }],
|
features: [{ type: "toggle" as const }],
|
||||||
|
pluginItems: 0,
|
||||||
fontScale: 1,
|
fontScale: 1,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -95,6 +96,7 @@ describe("composer control layout", () => {
|
|||||||
hasThinking: true,
|
hasThinking: true,
|
||||||
hasMode: true,
|
hasMode: true,
|
||||||
features: [{ type: "toggle" }],
|
features: [{ type: "toggle" }],
|
||||||
|
pluginItems: 0,
|
||||||
fontScale: 1,
|
fontScale: 1,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
@@ -107,6 +109,7 @@ describe("composer control layout", () => {
|
|||||||
hasThinking: true,
|
hasThinking: true,
|
||||||
hasMode: true,
|
hasMode: true,
|
||||||
features: [{ type: "toggle" }, { type: "select", label: "Tools" }],
|
features: [{ type: "toggle" }, { type: "select", label: "Tools" }],
|
||||||
|
pluginItems: 0,
|
||||||
fontScale: 1,
|
fontScale: 1,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
@@ -119,6 +122,7 @@ describe("composer control layout", () => {
|
|||||||
hasThinking: true,
|
hasThinking: true,
|
||||||
hasMode: true,
|
hasMode: true,
|
||||||
features: [{ type: "toggle" }],
|
features: [{ type: "toggle" }],
|
||||||
|
pluginItems: 0,
|
||||||
fontScale: 1.25,
|
fontScale: 1.25,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
@@ -133,6 +137,7 @@ describe("composer control layout", () => {
|
|||||||
hasModel: true,
|
hasModel: true,
|
||||||
hasThinking: true,
|
hasThinking: true,
|
||||||
hasMode: true,
|
hasMode: true,
|
||||||
|
pluginItems: 0,
|
||||||
fontScale: 1,
|
fontScale: 1,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -154,6 +159,34 @@ describe("composer control layout", () => {
|
|||||||
).toBe("condensed");
|
).toBe("condensed");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("condenses to make room for plugin items and keeps them in the overflow", () => {
|
||||||
|
const base = {
|
||||||
|
availableWidth: 430,
|
||||||
|
currentDensity: "full" as const,
|
||||||
|
controls: {
|
||||||
|
hasModel: true,
|
||||||
|
hasThinking: true,
|
||||||
|
hasMode: true,
|
||||||
|
features: [],
|
||||||
|
fontScale: 1,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(
|
||||||
|
resolveComposerControlDensity({ ...base, controls: { ...base.controls, pluginItems: 0 } }),
|
||||||
|
).toBe("full");
|
||||||
|
expect(
|
||||||
|
resolveComposerControlDensity({ ...base, controls: { ...base.controls, pluginItems: 2 } }),
|
||||||
|
).toBe("condensed");
|
||||||
|
expect(
|
||||||
|
resolveComposerControlDensity({
|
||||||
|
...base,
|
||||||
|
availableWidth: 250,
|
||||||
|
controls: { ...base.controls, pluginItems: 2 },
|
||||||
|
}),
|
||||||
|
).toBe("tight");
|
||||||
|
});
|
||||||
|
|
||||||
it("gives every toolbar control one shell and one platform glyph envelope", () => {
|
it("gives every toolbar control one shell and one platform glyph envelope", () => {
|
||||||
expect(COMPOSER_TOOLBAR_GEOMETRY).toEqual({
|
expect(COMPOSER_TOOLBAR_GEOMETRY).toEqual({
|
||||||
controlSize: 28,
|
controlSize: 28,
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ export interface ComposerControlPresence {
|
|||||||
hasThinking: boolean;
|
hasThinking: boolean;
|
||||||
hasMode: boolean;
|
hasMode: boolean;
|
||||||
features: readonly ComposerFeatureControlPresence[];
|
features: readonly ComposerFeatureControlPresence[];
|
||||||
|
/** Plugin composer items. Each is budgeted like a select with a short label. */
|
||||||
|
pluginItems: number;
|
||||||
fontScale: number;
|
fontScale: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,6 +28,7 @@ export const COMPOSER_TOOLBAR_GEOMETRY = {
|
|||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
const DENSITY_HYSTERESIS = 12;
|
const DENSITY_HYSTERESIS = 12;
|
||||||
|
const PLUGIN_ITEM_LABEL = "Plugin item";
|
||||||
|
|
||||||
function normalizedFontScale(fontScale: number): number {
|
function normalizedFontScale(fontScale: number): number {
|
||||||
return Number.isFinite(fontScale) ? Math.max(1, fontScale) : 1;
|
return Number.isFinite(fontScale) ? Math.max(1, fontScale) : 1;
|
||||||
@@ -62,7 +65,9 @@ function resolveCondensedFloor(controls: ComposerControlPresence): number {
|
|||||||
if (controls.hasModel) widths.push(36 + 60 * fontScale);
|
if (controls.hasModel) widths.push(36 + 60 * fontScale);
|
||||||
if (controls.hasThinking) widths.push(COMPOSER_TOOLBAR_GEOMETRY.controlSize);
|
if (controls.hasThinking) widths.push(COMPOSER_TOOLBAR_GEOMETRY.controlSize);
|
||||||
if (controls.hasMode) widths.push(36 + 96 * fontScale);
|
if (controls.hasMode) widths.push(36 + 96 * fontScale);
|
||||||
if (controls.features.length > 0) widths.push(COMPOSER_TOOLBAR_GEOMETRY.controlSize);
|
if (controls.features.length > 0 || controls.pluginItems > 0) {
|
||||||
|
widths.push(COMPOSER_TOOLBAR_GEOMETRY.controlSize);
|
||||||
|
}
|
||||||
return sumControlWidths(widths);
|
return sumControlWidths(widths);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,6 +80,11 @@ function resolveFullFloor(controls: ComposerControlPresence): number {
|
|||||||
for (const feature of controls.features) {
|
for (const feature of controls.features) {
|
||||||
widths.push(resolveFeatureControlWidth(feature, fontScale));
|
widths.push(resolveFeatureControlWidth(feature, fontScale));
|
||||||
}
|
}
|
||||||
|
for (let index = 0; index < controls.pluginItems; index++) {
|
||||||
|
widths.push(
|
||||||
|
resolveFeatureControlWidth({ type: "select", label: PLUGIN_ITEM_LABEL }, fontScale),
|
||||||
|
);
|
||||||
|
}
|
||||||
return sumControlWidths(widths);
|
return sumControlWidths(widths);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,15 +25,19 @@ describe("resolveAgentControlsMode", () => {
|
|||||||
onSelectMode: () => undefined,
|
onSelectMode: () => undefined,
|
||||||
models: [],
|
models: [],
|
||||||
selectedModel: "",
|
selectedModel: "",
|
||||||
onSelectModel: () => undefined,
|
onSelectModel: () => true,
|
||||||
isModelLoading: false,
|
isModelLoading: false,
|
||||||
modelSelectorProviders: [],
|
modelSelectorProviders: [],
|
||||||
isAllModelsLoading: false,
|
isAllModelsLoading: false,
|
||||||
onSelectProviderAndModel: () => undefined,
|
onSelectProviderAndModel: () => true,
|
||||||
|
options: {},
|
||||||
|
onSetOption: () => undefined,
|
||||||
thinkingOptions: [],
|
thinkingOptions: [],
|
||||||
selectedThinkingOptionId: "",
|
selectedThinkingOptionId: "",
|
||||||
onSelectThinkingOption: () => undefined,
|
onSelectThinkingOption: () => undefined,
|
||||||
onApplyAgentProfile: () => undefined,
|
onApplyAgentProfile: () => undefined,
|
||||||
|
metadata: {},
|
||||||
|
onSetMetadata: () => undefined,
|
||||||
}),
|
}),
|
||||||
).toBe("draft");
|
).toBe("draft");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { StyleSheet } from "react-native-unistyles";
|
|||||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||||
import type { AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
import type { AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||||
import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet";
|
import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet";
|
||||||
|
import type { ContextBridge } from "@/components/ui/isolated-bottom-sheet-modal";
|
||||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||||
import { useProviderIcon } from "@/components/provider-icons";
|
import { useProviderIcon } from "@/components/provider-icons";
|
||||||
import { ModelBrowser, useModelBrowser } from "@/components/model-browser";
|
import { ModelBrowser, useModelBrowser } from "@/components/model-browser";
|
||||||
@@ -43,6 +44,8 @@ interface CompactModelSheetProps {
|
|||||||
serverId?: string | null;
|
serverId?: string | null;
|
||||||
glyphSize: number;
|
glyphSize: number;
|
||||||
canSwitchProvider: boolean;
|
canSwitchProvider: boolean;
|
||||||
|
/** Carries the composer's contexts into the sheets, which draw away from it. */
|
||||||
|
contextBridge?: ContextBridge | null;
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,6 +98,7 @@ export function CompactModelSheet({
|
|||||||
serverId = null,
|
serverId = null,
|
||||||
glyphSize,
|
glyphSize,
|
||||||
canSwitchProvider,
|
canSwitchProvider,
|
||||||
|
contextBridge = null,
|
||||||
children,
|
children,
|
||||||
}: CompactModelSheetProps) {
|
}: CompactModelSheetProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -299,6 +303,7 @@ export function CompactModelSheet({
|
|||||||
snapPoints={SNAP_POINTS}
|
snapPoints={SNAP_POINTS}
|
||||||
scrollable={false}
|
scrollable={false}
|
||||||
contentStyle={styles.sheetBody}
|
contentStyle={styles.sheetBody}
|
||||||
|
contextBridge={contextBridge}
|
||||||
testID="agent-controls-model-sheet"
|
testID="agent-controls-model-sheet"
|
||||||
>
|
>
|
||||||
<View
|
<View
|
||||||
@@ -347,6 +352,7 @@ export function CompactModelSheet({
|
|||||||
scrollable={false}
|
scrollable={false}
|
||||||
presentation="push"
|
presentation="push"
|
||||||
contentStyle={styles.sheetBody}
|
contentStyle={styles.sheetBody}
|
||||||
|
contextBridge={contextBridge}
|
||||||
testID="agent-controls-model-browser-sheet"
|
testID="agent-controls-model-browser-sheet"
|
||||||
>
|
>
|
||||||
<View
|
<View
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { useCallback } from "react";
|
||||||
|
import { QueryClientProvider, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import type { ContextBridge } from "@/components/ui/isolated-bottom-sheet-modal";
|
||||||
|
import { ComposerControlLayoutProvider, useComposerControlLayout } from "./layout-context";
|
||||||
|
import {
|
||||||
|
ComposerAgentProvider,
|
||||||
|
ComposerInputProvider,
|
||||||
|
useComposerAgent,
|
||||||
|
useComposerInput,
|
||||||
|
} from "@/composer/session";
|
||||||
|
import { ToastApiProvider, useToast } from "@/contexts/toast-api-context";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A phone's overflow draws in a sheet whose content lands at the app root, away from the
|
||||||
|
* composer. This carries across what a control in it reads from the composer: the agent and input
|
||||||
|
* a plugin's `useComposer()` sits on, the layout, and the toast and query client the controls use.
|
||||||
|
* Call it from inside the composer, outside any sheet.
|
||||||
|
*/
|
||||||
|
export function useComposerSheetBridge(): ContextBridge {
|
||||||
|
const layout = useComposerControlLayout();
|
||||||
|
const agent = useComposerAgent();
|
||||||
|
const input = useComposerInput();
|
||||||
|
const toast = useToast();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useCallback<ContextBridge>(
|
||||||
|
(content) => (
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<ToastApiProvider api={toast}>
|
||||||
|
<ComposerControlLayoutProvider value={layout}>
|
||||||
|
<ComposerAgentProvider value={agent}>
|
||||||
|
{input ? (
|
||||||
|
<ComposerInputProvider value={input}>{content}</ComposerInputProvider>
|
||||||
|
) : (
|
||||||
|
content
|
||||||
|
)}
|
||||||
|
</ComposerAgentProvider>
|
||||||
|
</ComposerControlLayoutProvider>
|
||||||
|
</ToastApiProvider>
|
||||||
|
</QueryClientProvider>
|
||||||
|
),
|
||||||
|
[agent, input, layout, queryClient, toast],
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,9 +1,7 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import {
|
import {
|
||||||
getFeatureHighlightColor,
|
getFeatureHighlightColor,
|
||||||
getFeatureTooltip,
|
|
||||||
getAgentControlHintKey,
|
getAgentControlHintKey,
|
||||||
isFeatureActive,
|
|
||||||
normalizeModelId,
|
normalizeModelId,
|
||||||
resolveAgentModelSelection,
|
resolveAgentModelSelection,
|
||||||
} from "./utils";
|
} from "./utils";
|
||||||
@@ -17,51 +15,12 @@ describe("getAgentControlHintKey", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("feature metadata helpers", () => {
|
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", () => {
|
it("maps feature highlight colors by feature id", () => {
|
||||||
expect(getFeatureHighlightColor("fast_mode")).toBe("yellow");
|
expect(getFeatureHighlightColor("fast_mode")).toBe("yellow");
|
||||||
expect(getFeatureHighlightColor("service_tier")).toBe("yellow");
|
expect(getFeatureHighlightColor("service_tier")).toBe("yellow");
|
||||||
expect(getFeatureHighlightColor("plan_mode")).toBe("blue");
|
expect(getFeatureHighlightColor("plan_mode")).toBe("blue");
|
||||||
expect(getFeatureHighlightColor("other")).toBe("default");
|
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", () => {
|
describe("normalizeModelId", () => {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { AgentFeature, AgentModelDefinition } from "@getpaseo/protocol/agent-types";
|
import type { AgentModelDefinition } from "@getpaseo/protocol/agent-types";
|
||||||
import { i18n } from "@/i18n/i18next";
|
import { i18n } from "@/i18n/i18next";
|
||||||
import { formatThinkingOptionLabel } from "@/agent-controls/labels";
|
import { formatThinkingOptionLabel } from "@/agent-controls/labels";
|
||||||
import {
|
import {
|
||||||
@@ -35,16 +35,6 @@ export function normalizeModelId(modelId: string | null | undefined): string | n
|
|||||||
return normalized;
|
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 {
|
export function getFeatureHighlightColor(featureId: string): FeatureHighlightColor {
|
||||||
switch (featureId) {
|
switch (featureId) {
|
||||||
case FAST_MODE_FEATURE_ID:
|
case FAST_MODE_FEATURE_ID:
|
||||||
|
|||||||
@@ -0,0 +1,182 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import type { AgentModelDefinition } from "@getpaseo/protocol/agent-types";
|
||||||
|
import type { AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
|
||||||
|
import {
|
||||||
|
draftControlsRequest,
|
||||||
|
openDraftOptions,
|
||||||
|
shownDraftOptions,
|
||||||
|
} from "@/agent-controls/draft-options-model";
|
||||||
|
import { openAgentForm, type AgentFormCatalog } from "@/provider-selection/agent-form-store";
|
||||||
|
import { draftComposerAgent } from "./composer-agent";
|
||||||
|
|
||||||
|
function definition(id: string, modeId: string): AgentProviderDefinition {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
label: id,
|
||||||
|
description: id,
|
||||||
|
defaultModeId: modeId,
|
||||||
|
modes: [{ id: modeId, label: modeId, icon: "ShieldCheck", colorTier: "safe" }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function model(provider: string, id: string, isDefault = false): AgentModelDefinition {
|
||||||
|
return { provider, id, label: id, isDefault };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The host: two providers with catalogs, and one that is ready but lists no models. */
|
||||||
|
const catalog: AgentFormCatalog = {
|
||||||
|
selectableProviders: new Map([
|
||||||
|
["claude", definition("claude", "default")],
|
||||||
|
["codex", definition("codex", "auto")],
|
||||||
|
["opencode", definition("opencode", "build")],
|
||||||
|
]),
|
||||||
|
models: new Map([
|
||||||
|
["claude", [model("claude", "sonnet", true)]],
|
||||||
|
["codex", [model("codex", "gpt-5.4", true), model("codex", "gpt-5.5")]],
|
||||||
|
["opencode", []],
|
||||||
|
]),
|
||||||
|
providerPreferences: () => undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A draft composer on the real form and options models. */
|
||||||
|
function openDraft(context: "draft" | "new-workspace") {
|
||||||
|
const form = openAgentForm(() => catalog);
|
||||||
|
const options = openDraftOptions({
|
||||||
|
provider: null,
|
||||||
|
currentProvider: () => form.getState().form.provider,
|
||||||
|
});
|
||||||
|
// The screen hands the options the provider the form reaches.
|
||||||
|
form.subscribe(() => options.observeProvider(form.getState().form.provider));
|
||||||
|
form.setProviderAndModel("claude", "");
|
||||||
|
|
||||||
|
function agent() {
|
||||||
|
const { form: current } = form.getState();
|
||||||
|
return draftComposerAgent({
|
||||||
|
context,
|
||||||
|
selectedProvider: current.provider,
|
||||||
|
selectedModel: current.model,
|
||||||
|
selectedMode: current.modeId,
|
||||||
|
thinking: current.thinkingOptionId || null,
|
||||||
|
isLocked: () => false,
|
||||||
|
options: shownDraftOptions(options.getState(), {
|
||||||
|
provider: current.provider,
|
||||||
|
requestKey: "",
|
||||||
|
}),
|
||||||
|
metadata: {},
|
||||||
|
onSelectProviderAndModel: form.setProviderAndModel,
|
||||||
|
onSelectModel: form.setModel,
|
||||||
|
onSelectMode: () => undefined,
|
||||||
|
onSelectThinkingOption: () => undefined,
|
||||||
|
onSetOption: options.setOption,
|
||||||
|
onSetMetadata: () => undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the daemon is asked to resolve for the agent this draft would create. */
|
||||||
|
function request() {
|
||||||
|
const { form: current } = form.getState();
|
||||||
|
return draftControlsRequest(options.getState(), {
|
||||||
|
provider: current.provider,
|
||||||
|
cwd: "/repo",
|
||||||
|
modeId: current.modeId,
|
||||||
|
modelId: current.model,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { form, agent, request };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("a draft's options", () => {
|
||||||
|
it("belong to the provider the form has now, before the screen has rendered the change", () => {
|
||||||
|
const form = openAgentForm(() => catalog);
|
||||||
|
const options = openDraftOptions({
|
||||||
|
provider: null,
|
||||||
|
currentProvider: () => form.getState().form.provider,
|
||||||
|
});
|
||||||
|
// No subscription: the screen observes the provider in an effect, after the command ran.
|
||||||
|
form.setProviderAndModel("claude", "");
|
||||||
|
options.observeProvider("claude");
|
||||||
|
options.setOption("context", "1m");
|
||||||
|
|
||||||
|
form.setProviderAndModel("codex", "");
|
||||||
|
options.setOption("effort", "high");
|
||||||
|
|
||||||
|
expect(options.getState()).toMatchObject({ provider: "codex", edits: { effort: "high" } });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe.each(["draft", "new-workspace"] as const)("the %s composer's agent", (context) => {
|
||||||
|
it("applies each awaited command before the next one runs", async () => {
|
||||||
|
const draft = openDraft(context);
|
||||||
|
// A plugin keeps the object it was handed across its awaits.
|
||||||
|
const retained = draft.agent();
|
||||||
|
|
||||||
|
await retained.setProvider("codex");
|
||||||
|
await retained.setModel("gpt-5.5");
|
||||||
|
await retained.setOptions({ context: "1m" });
|
||||||
|
|
||||||
|
const agent = draft.agent();
|
||||||
|
expect(agent).toMatchObject({
|
||||||
|
context,
|
||||||
|
provider: "codex",
|
||||||
|
model: "gpt-5.5",
|
||||||
|
options: { context: "1m" },
|
||||||
|
});
|
||||||
|
expect(draft.request()).toMatchObject({
|
||||||
|
provider: "codex",
|
||||||
|
model: "gpt-5.5",
|
||||||
|
providerOptions: { context: "1m" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("starts the options over when the provider is chosen by hand", async () => {
|
||||||
|
const draft = openDraft(context);
|
||||||
|
const retained = draft.agent();
|
||||||
|
|
||||||
|
await retained.setOptions({ context: "1m" });
|
||||||
|
expect(draft.agent().options).toEqual({ context: "1m" });
|
||||||
|
await retained.setProvider("codex");
|
||||||
|
|
||||||
|
expect(draft.agent().options).toEqual({});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("creates with the provider's default again once a plugin resets an option", async () => {
|
||||||
|
const draft = openDraft(context);
|
||||||
|
const retained = draft.agent();
|
||||||
|
|
||||||
|
await retained.setOptions({ context: "1m", effort: "high" });
|
||||||
|
await retained.setOptions({ context: null });
|
||||||
|
|
||||||
|
expect(draft.agent().options).toEqual({ effort: "high" });
|
||||||
|
expect(draft.request()?.providerOptions).toEqual({ effort: "high" });
|
||||||
|
|
||||||
|
await retained.setOptions({ effort: null });
|
||||||
|
|
||||||
|
expect(draft.agent().options).toEqual({});
|
||||||
|
expect(draft.request()?.providerOptions).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a provider the host cannot run and a model the catalog does not list", async () => {
|
||||||
|
const draft = openDraft(context);
|
||||||
|
const retained = draft.agent();
|
||||||
|
|
||||||
|
await expect(retained.setProvider("nope")).rejects.toThrow(
|
||||||
|
"Unknown or unavailable provider: nope",
|
||||||
|
);
|
||||||
|
expect(draft.agent().provider).toBe("claude");
|
||||||
|
|
||||||
|
await retained.setProvider("codex");
|
||||||
|
await expect(retained.setModel("missing")).rejects.toThrow("Unknown model: missing");
|
||||||
|
expect(draft.agent()).toMatchObject({ provider: "codex", model: "gpt-5.4" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps a model id as given when the provider lists no catalog", async () => {
|
||||||
|
const draft = openDraft(context);
|
||||||
|
const retained = draft.agent();
|
||||||
|
|
||||||
|
await retained.setProvider("opencode");
|
||||||
|
await retained.setModel("anthropic/claude-x");
|
||||||
|
|
||||||
|
expect(draft.agent().model).toBe("anthropic/claude-x");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import type { ComposerAgent } from "@/composer/session";
|
||||||
|
import type { DraftAgentControlsProps } from "@/composer/agent-controls";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The agent a draft composer creates, as a plugin sees it. Its commands go to the form and the
|
||||||
|
* options model, which apply them as they run, so a plugin can `await` one and issue the next.
|
||||||
|
*/
|
||||||
|
export function draftComposerAgent(
|
||||||
|
props: Pick<
|
||||||
|
DraftAgentControlsProps,
|
||||||
|
| "context"
|
||||||
|
| "disabled"
|
||||||
|
| "selectedProvider"
|
||||||
|
| "selectedModel"
|
||||||
|
| "selectedMode"
|
||||||
|
| "options"
|
||||||
|
| "metadata"
|
||||||
|
| "onSelectProviderAndModel"
|
||||||
|
| "onSelectModel"
|
||||||
|
| "onSelectMode"
|
||||||
|
| "onSelectThinkingOption"
|
||||||
|
| "onSetOption"
|
||||||
|
| "onSetMetadata"
|
||||||
|
> & { thinking: string | null; isLocked: () => boolean },
|
||||||
|
): ComposerAgent {
|
||||||
|
return {
|
||||||
|
context: props.context ?? "draft",
|
||||||
|
locked: props.disabled ?? false,
|
||||||
|
isLocked: props.isLocked,
|
||||||
|
provider: props.selectedProvider,
|
||||||
|
model: props.selectedModel || null,
|
||||||
|
mode: props.selectedMode || null,
|
||||||
|
thinking: props.thinking,
|
||||||
|
options: props.options,
|
||||||
|
metadata: props.metadata,
|
||||||
|
// An empty model id picks the provider's default model.
|
||||||
|
setProvider: async (provider) => {
|
||||||
|
if (!props.onSelectProviderAndModel(provider, "")) {
|
||||||
|
throw new Error(`Unknown or unavailable provider: ${provider}`);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
setModel: async (modelId) => {
|
||||||
|
if (!props.onSelectModel(modelId)) throw new Error(`Unknown model: ${modelId}`);
|
||||||
|
},
|
||||||
|
setMode: async (modeId) => props.onSelectMode(modeId),
|
||||||
|
setThinking: async (thinkingOptionId) => props.onSelectThinkingOption(thinkingOptionId),
|
||||||
|
setOptions: async (patch) => {
|
||||||
|
for (const [key, value] of Object.entries(patch)) props.onSetOption(key, value);
|
||||||
|
},
|
||||||
|
setMetadata: async (patch) => props.onSetMetadata(patch),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||||
import type { UserComposerAttachment } from "@/attachments/types";
|
import type { UserComposerAttachment } from "@/attachments/types";
|
||||||
import type { DraftAgentControlsProps } from "@/composer/agent-controls";
|
import type { DraftAgentControlsProps } from "@/composer/agent-controls";
|
||||||
import type { UseAgentFormStateResult } from "@/hooks/use-agent-form-state";
|
import type { UseAgentFormStateResult } from "@/hooks/use-agent-form-state";
|
||||||
@@ -20,12 +21,26 @@ export function resolveDraftKey(input: {
|
|||||||
|
|
||||||
export function buildDraftAgentControls(input: {
|
export function buildDraftAgentControls(input: {
|
||||||
formState: UseAgentFormStateResult;
|
formState: UseAgentFormStateResult;
|
||||||
features?: DraftAgentControlsProps["features"];
|
optionControls?: DraftAgentControlsProps["optionControls"];
|
||||||
onSetFeature?: DraftAgentControlsProps["onSetFeature"];
|
options: DraftAgentControlsProps["options"];
|
||||||
|
onSetOption: DraftAgentControlsProps["onSetOption"];
|
||||||
onApplyAgentProfile: DraftAgentControlsProps["onApplyAgentProfile"];
|
onApplyAgentProfile: DraftAgentControlsProps["onApplyAgentProfile"];
|
||||||
onDropdownClose?: DraftAgentControlsProps["onDropdownClose"];
|
onDropdownClose?: DraftAgentControlsProps["onDropdownClose"];
|
||||||
|
context: NonNullable<DraftAgentControlsProps["context"]>;
|
||||||
|
metadata: Record<string, JsonValue>;
|
||||||
|
onSetMetadata: (patch: Record<string, JsonValue>) => void;
|
||||||
}): DraftAgentControlsProps {
|
}): DraftAgentControlsProps {
|
||||||
const { formState, features, onSetFeature, onApplyAgentProfile, onDropdownClose } = input;
|
const {
|
||||||
|
formState,
|
||||||
|
optionControls,
|
||||||
|
options,
|
||||||
|
onSetOption,
|
||||||
|
onApplyAgentProfile,
|
||||||
|
onDropdownClose,
|
||||||
|
context,
|
||||||
|
metadata,
|
||||||
|
onSetMetadata,
|
||||||
|
} = input;
|
||||||
return {
|
return {
|
||||||
providerDefinitions: formState.providerDefinitions,
|
providerDefinitions: formState.providerDefinitions,
|
||||||
selectedProvider: formState.selectedProvider,
|
selectedProvider: formState.selectedProvider,
|
||||||
@@ -43,13 +58,17 @@ export function buildDraftAgentControls(input: {
|
|||||||
selectedThinkingOptionId: formState.selectedThinkingOptionId,
|
selectedThinkingOptionId: formState.selectedThinkingOptionId,
|
||||||
onSelectThinkingOption: formState.setThinkingOptionFromUser,
|
onSelectThinkingOption: formState.setThinkingOptionFromUser,
|
||||||
onApplyAgentProfile,
|
onApplyAgentProfile,
|
||||||
features,
|
optionControls,
|
||||||
onSetFeature,
|
options,
|
||||||
|
onSetOption,
|
||||||
onDropdownClose,
|
onDropdownClose,
|
||||||
onModelSelectorOpen: formState.refetchProviderModelsIfStale,
|
onModelSelectorOpen: formState.refetchProviderModelsIfStale,
|
||||||
onRetryModelProvider: formState.refreshProviderModels,
|
onRetryModelProvider: formState.refreshProviderModels,
|
||||||
isRetryingModelProvider: formState.isProviderModelsRefreshing,
|
isRetryingModelProvider: formState.isProviderModelsRefreshing,
|
||||||
modelSelectorServerId: formState.selectedServerId,
|
modelSelectorServerId: formState.selectedServerId,
|
||||||
|
context,
|
||||||
|
metadata,
|
||||||
|
onSetMetadata,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||||
import type { UserComposerAttachment } from "@/attachments/types";
|
import type { UserComposerAttachment } from "@/attachments/types";
|
||||||
import type { TextReplacement } from "@/composer/types";
|
import type { TextReplacement } from "@/composer/types";
|
||||||
import type { DraftAgentControlsProps } from "@/composer/agent-controls";
|
import type { DraftAgentControlsProps } from "@/composer/agent-controls";
|
||||||
@@ -8,7 +9,7 @@ import {
|
|||||||
type CreateAgentInitialValues,
|
type CreateAgentInitialValues,
|
||||||
type UseAgentFormStateResult,
|
type UseAgentFormStateResult,
|
||||||
} from "@/hooks/use-agent-form-state";
|
} from "@/hooks/use-agent-form-state";
|
||||||
import { useDraftAgentFeatures } from "@/hooks/use-draft-agent-features";
|
import { useDraftProviderOptions } from "@/hooks/use-draft-provider-options";
|
||||||
import {
|
import {
|
||||||
buildDraftAgentControls,
|
buildDraftAgentControls,
|
||||||
hasDraftContent,
|
hasDraftContent,
|
||||||
@@ -28,6 +29,8 @@ import { useShallow } from "zustand/shallow";
|
|||||||
import type { ComposerTextSource } from "@/composer/text-source";
|
import type { ComposerTextSource } from "@/composer/text-source";
|
||||||
import { isWeb } from "@/constants/platform";
|
import { isWeb } from "@/constants/platform";
|
||||||
|
|
||||||
|
const NO_METADATA: Record<string, JsonValue> = {};
|
||||||
|
|
||||||
type AttachmentUpdater =
|
type AttachmentUpdater =
|
||||||
| UserComposerAttachment[]
|
| UserComposerAttachment[]
|
||||||
| ((prev: UserComposerAttachment[]) => UserComposerAttachment[]);
|
| ((prev: UserComposerAttachment[]) => UserComposerAttachment[]);
|
||||||
@@ -35,7 +38,9 @@ type AttachmentUpdater =
|
|||||||
interface AgentInputDraftComposerOptions {
|
interface AgentInputDraftComposerOptions {
|
||||||
initialServerId: string | null;
|
initialServerId: string | null;
|
||||||
initialValues?: CreateAgentInitialValues;
|
initialValues?: CreateAgentInitialValues;
|
||||||
initialFeatureValues?: Record<string, unknown>;
|
initialProviderOptions?: Record<string, unknown>;
|
||||||
|
/** Which composer a plugin's `useComposer()` reports. */
|
||||||
|
context?: "draft" | "new-workspace";
|
||||||
isVisible?: boolean;
|
isVisible?: boolean;
|
||||||
lockedWorkingDir?: string;
|
lockedWorkingDir?: string;
|
||||||
}
|
}
|
||||||
@@ -50,7 +55,9 @@ type DraftComposerState = UseAgentFormStateResult & {
|
|||||||
effectiveModeId: string;
|
effectiveModeId: string;
|
||||||
effectiveModelId: string;
|
effectiveModelId: string;
|
||||||
effectiveThinkingOptionId: string;
|
effectiveThinkingOptionId: string;
|
||||||
featureValues: Record<string, unknown> | undefined;
|
providerOptions: Record<string, unknown> | undefined;
|
||||||
|
/** What plugins set on the agent this draft creates. */
|
||||||
|
metadata: Record<string, JsonValue>;
|
||||||
agentControls: DraftAgentControlsProps;
|
agentControls: DraftAgentControlsProps;
|
||||||
commandDraft: DraftCommandTarget;
|
commandDraft: DraftCommandTarget;
|
||||||
};
|
};
|
||||||
@@ -191,10 +198,18 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
|||||||
[saveDraft],
|
[saveDraft],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const metadata = useDraftStore((state) => state.metadataByDraftKey[draftKey] ?? NO_METADATA);
|
||||||
|
const setMetadata = useCallback(
|
||||||
|
(patch: Record<string, JsonValue>) =>
|
||||||
|
useDraftStore.getState().patchDraftMetadata({ draftKey, patch }),
|
||||||
|
[draftKey],
|
||||||
|
);
|
||||||
|
|
||||||
const clear = useCallback(
|
const clear = useCallback(
|
||||||
(lifecycle: "sent" | "abandoned") => {
|
(lifecycle: "sent" | "abandoned") => {
|
||||||
textPublication.cancel();
|
textPublication.cancel();
|
||||||
useDraftStore.getState().clearDraftInput({ draftKey, lifecycle });
|
useDraftStore.getState().clearDraftInput({ draftKey, lifecycle });
|
||||||
|
if (lifecycle === "sent") useDraftStore.getState().clearDraftMetadata({ draftKey });
|
||||||
},
|
},
|
||||||
[draftKey, textPublication],
|
[draftKey, textPublication],
|
||||||
);
|
);
|
||||||
@@ -274,26 +289,28 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
|||||||
);
|
);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
features: draftFeatures,
|
optionControls: draftOptionControls,
|
||||||
featureValues: draftFeatureValues,
|
options: draftOptions,
|
||||||
setFeatureValue: setDraftFeatureValue,
|
shownOptions: draftShownOptions,
|
||||||
applyProfileFeatureValues,
|
setOption: setDraftOption,
|
||||||
} = useDraftAgentFeatures({
|
applyProfile: applyProfileOptions,
|
||||||
|
} = useDraftProviderOptions({
|
||||||
serverId: formState.selectedServerId,
|
serverId: formState.selectedServerId,
|
||||||
provider: formState.selectedProvider,
|
provider: formState.selectedProvider,
|
||||||
|
getProvider: formState.getSelectedProvider,
|
||||||
cwd: workingDir,
|
cwd: workingDir,
|
||||||
modeId: formState.selectedMode,
|
modeId: formState.selectedMode,
|
||||||
modelId: effectiveModelId,
|
modelId: effectiveModelId,
|
||||||
thinkingOptionId: effectiveThinkingOptionId,
|
thinkingOptionId: effectiveThinkingOptionId,
|
||||||
initialFeatureValues: composerOptions?.initialFeatureValues,
|
initialOptions: composerOptions?.initialProviderOptions,
|
||||||
});
|
});
|
||||||
|
|
||||||
const applyDraftAgentProfile = useCallback(
|
const applyDraftAgentProfile = useCallback(
|
||||||
(profile: Parameters<typeof formState.applyProfileFromUser>[0]) => {
|
(profile: Parameters<typeof formState.applyProfileFromUser>[0]) => {
|
||||||
formState.applyProfileFromUser(profile);
|
formState.applyProfileFromUser(profile);
|
||||||
applyProfileFeatureValues(profile.featureValues);
|
applyProfileOptions({ provider: profile.provider, options: profile.options });
|
||||||
},
|
},
|
||||||
[applyProfileFeatureValues, formState],
|
[applyProfileOptions, formState],
|
||||||
);
|
);
|
||||||
|
|
||||||
const commandDraft = useMemo(
|
const commandDraft = useMemo(
|
||||||
@@ -303,15 +320,9 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
|||||||
cwd: workingDir,
|
cwd: workingDir,
|
||||||
effectiveModelId,
|
effectiveModelId,
|
||||||
effectiveThinkingOptionId,
|
effectiveThinkingOptionId,
|
||||||
featureValues: draftFeatureValues,
|
providerOptions: draftOptions,
|
||||||
}),
|
}),
|
||||||
[
|
[effectiveModelId, effectiveThinkingOptionId, draftOptions, providerSelection, workingDir],
|
||||||
effectiveModelId,
|
|
||||||
effectiveThinkingOptionId,
|
|
||||||
draftFeatureValues,
|
|
||||||
providerSelection,
|
|
||||||
workingDir,
|
|
||||||
],
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const composerState = useMemo<DraftComposerState | null>(() => {
|
const composerState = useMemo<DraftComposerState | null>(() => {
|
||||||
@@ -325,12 +336,17 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
|||||||
effectiveModeId,
|
effectiveModeId,
|
||||||
effectiveModelId,
|
effectiveModelId,
|
||||||
effectiveThinkingOptionId,
|
effectiveThinkingOptionId,
|
||||||
featureValues: draftFeatureValues,
|
providerOptions: draftOptions,
|
||||||
|
metadata,
|
||||||
agentControls: buildDraftAgentControls({
|
agentControls: buildDraftAgentControls({
|
||||||
formState,
|
formState,
|
||||||
features: draftFeatures,
|
optionControls: draftOptionControls,
|
||||||
onSetFeature: setDraftFeatureValue,
|
options: draftShownOptions,
|
||||||
|
onSetOption: setDraftOption,
|
||||||
onApplyAgentProfile: applyDraftAgentProfile,
|
onApplyAgentProfile: applyDraftAgentProfile,
|
||||||
|
context: composerOptions.context ?? "draft",
|
||||||
|
metadata,
|
||||||
|
onSetMetadata: setMetadata,
|
||||||
}),
|
}),
|
||||||
commandDraft,
|
commandDraft,
|
||||||
};
|
};
|
||||||
@@ -340,11 +356,14 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
|||||||
effectiveModeId,
|
effectiveModeId,
|
||||||
effectiveModelId,
|
effectiveModelId,
|
||||||
effectiveThinkingOptionId,
|
effectiveThinkingOptionId,
|
||||||
draftFeatures,
|
draftOptionControls,
|
||||||
draftFeatureValues,
|
draftOptions,
|
||||||
|
draftShownOptions,
|
||||||
|
setDraftOption,
|
||||||
applyDraftAgentProfile,
|
applyDraftAgentProfile,
|
||||||
formState,
|
formState,
|
||||||
setDraftFeatureValue,
|
metadata,
|
||||||
|
setMetadata,
|
||||||
workingDir,
|
workingDir,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { applyMetadataPatch } from "./metadata";
|
||||||
|
|
||||||
|
describe("applyMetadataPatch", () => {
|
||||||
|
it("replaces top-level keys and removes keys patched to null", () => {
|
||||||
|
expect(
|
||||||
|
applyMetadataPatch(
|
||||||
|
{ "linear.issue": { id: "ENG-1" }, review: true },
|
||||||
|
{ "linear.issue": { id: "ENG-2" }, review: null, extra: [1] },
|
||||||
|
),
|
||||||
|
).toEqual({ "linear.issue": { id: "ENG-2" }, extra: [1] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves the current record untouched", () => {
|
||||||
|
const current = { review: true };
|
||||||
|
applyMetadataPatch(current, { review: null });
|
||||||
|
expect(current).toEqual({ review: true });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||||
|
|
||||||
|
/** Top-level keys replace; `null` removes the key. The daemon applies the same rule to an agent. */
|
||||||
|
export function applyMetadataPatch(
|
||||||
|
current: Readonly<Record<string, JsonValue>>,
|
||||||
|
patch: Readonly<Record<string, JsonValue>>,
|
||||||
|
): Record<string, JsonValue> {
|
||||||
|
const next = { ...current };
|
||||||
|
for (const [key, value] of Object.entries(patch)) {
|
||||||
|
if (value === null) delete next[key];
|
||||||
|
else next[key] = value;
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
|
import type { ComposerOptionControls } from "@/agent-controls/option-controls";
|
||||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||||
|
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||||
import { Keyboard, ScrollView, StyleSheet as RNStyleSheet, Text, View } from "react-native";
|
import { Keyboard, ScrollView, StyleSheet as RNStyleSheet, Text, View } from "react-native";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { StyleSheet } from "react-native-unistyles";
|
import { StyleSheet } from "react-native-unistyles";
|
||||||
@@ -65,7 +67,7 @@ interface AutoSubmitConfig {
|
|||||||
modeId: string | null;
|
modeId: string | null;
|
||||||
model: string | null;
|
model: string | null;
|
||||||
thinkingOptionId: string | null;
|
thinkingOptionId: string | null;
|
||||||
featureValues: Record<string, unknown>;
|
providerOptions: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveAutoSubmitConfig(
|
function resolveAutoSubmitConfig(
|
||||||
@@ -74,7 +76,7 @@ function resolveAutoSubmitConfig(
|
|||||||
modeId?: string | null;
|
modeId?: string | null;
|
||||||
model?: string | null;
|
model?: string | null;
|
||||||
thinkingOptionId?: string | null;
|
thinkingOptionId?: string | null;
|
||||||
featureValues?: Record<string, unknown>;
|
providerOptions?: Record<string, unknown>;
|
||||||
} | null,
|
} | null,
|
||||||
): AutoSubmitConfig | null {
|
): AutoSubmitConfig | null {
|
||||||
if (!pending) return null;
|
if (!pending) return null;
|
||||||
@@ -83,7 +85,7 @@ function resolveAutoSubmitConfig(
|
|||||||
modeId: pending.modeId ?? null,
|
modeId: pending.modeId ?? null,
|
||||||
model: pending.model ?? null,
|
model: pending.model ?? null,
|
||||||
thinkingOptionId: pending.thinkingOptionId ?? null,
|
thinkingOptionId: pending.thinkingOptionId ?? null,
|
||||||
featureValues: pending.featureValues ?? {},
|
providerOptions: pending.providerOptions ?? {},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,7 +133,8 @@ async function submitDraftCreateRequest(input: {
|
|||||||
effectiveModeId: string;
|
effectiveModeId: string;
|
||||||
effectiveModelId: string | null;
|
effectiveModelId: string | null;
|
||||||
effectiveThinkingOptionId: string | null;
|
effectiveThinkingOptionId: string | null;
|
||||||
featureValues: Record<string, unknown> | undefined;
|
providerOptions: Record<string, unknown> | undefined;
|
||||||
|
metadata: Record<string, JsonValue>;
|
||||||
};
|
};
|
||||||
hostDisconnectedMessage: string;
|
hostDisconnectedMessage: string;
|
||||||
selectModelMessage: string;
|
selectModelMessage: string;
|
||||||
@@ -170,7 +173,7 @@ async function submitDraftCreateRequest(input: {
|
|||||||
model: autoSubmitConfig?.model ?? (composerState.effectiveModelId || undefined),
|
model: autoSubmitConfig?.model ?? (composerState.effectiveModelId || undefined),
|
||||||
thinkingOptionId:
|
thinkingOptionId:
|
||||||
autoSubmitConfig?.thinkingOptionId ?? (composerState.effectiveThinkingOptionId || undefined),
|
autoSubmitConfig?.thinkingOptionId ?? (composerState.effectiveThinkingOptionId || undefined),
|
||||||
featureValues: autoSubmitConfig?.featureValues ?? composerState.featureValues,
|
providerOptions: autoSubmitConfig?.providerOptions ?? composerState.providerOptions,
|
||||||
});
|
});
|
||||||
|
|
||||||
const attachmentsArray = Array.isArray(attachments) ? attachments : undefined;
|
const attachmentsArray = Array.isArray(attachments) ? attachments : undefined;
|
||||||
@@ -181,6 +184,7 @@ async function submitDraftCreateRequest(input: {
|
|||||||
workspaceId,
|
workspaceId,
|
||||||
initialPrompt: text,
|
initialPrompt: text,
|
||||||
clientMessageId: attempt.clientMessageId,
|
clientMessageId: attempt.clientMessageId,
|
||||||
|
...(Object.keys(composerState.metadata).length > 0 ? { metadata: composerState.metadata } : {}),
|
||||||
...(imagesData && imagesData.length > 0 ? { images: imagesData } : {}),
|
...(imagesData && imagesData.length > 0 ? { images: imagesData } : {}),
|
||||||
...(attachmentsArray && attachmentsArray.length > 0 ? { attachments: attachmentsArray } : {}),
|
...(attachmentsArray && attachmentsArray.length > 0 ? { attachments: attachmentsArray } : {}),
|
||||||
};
|
};
|
||||||
@@ -204,7 +208,7 @@ function buildDraftAgentSnapshot(input: {
|
|||||||
effectiveThinkingOptionId: string | null;
|
effectiveThinkingOptionId: string | null;
|
||||||
effectiveModeId: string;
|
effectiveModeId: string;
|
||||||
selectedProvider: string | null;
|
selectedProvider: string | null;
|
||||||
agentControls: { features?: Agent["features"] };
|
agentControls: { optionControls?: ComposerOptionControls };
|
||||||
};
|
};
|
||||||
selectModelMessage: string;
|
selectModelMessage: string;
|
||||||
}): Agent {
|
}): Agent {
|
||||||
@@ -241,7 +245,8 @@ function buildDraftAgentSnapshot(input: {
|
|||||||
title: "Agent",
|
title: "Agent",
|
||||||
cwd: workspaceDirectory,
|
cwd: workspaceDirectory,
|
||||||
model,
|
model,
|
||||||
features: composerState.agentControls.features,
|
options: composerState.agentControls.optionControls?.options,
|
||||||
|
controls: composerState.agentControls.optionControls?.controls,
|
||||||
thinkingOptionId,
|
thinkingOptionId,
|
||||||
parentAgentId: null,
|
parentAgentId: null,
|
||||||
labels: {},
|
labels: {},
|
||||||
@@ -333,7 +338,7 @@ export function WorkspaceDraftAgentTab({
|
|||||||
composer: {
|
composer: {
|
||||||
initialServerId: serverId,
|
initialServerId: serverId,
|
||||||
initialValues: draftInitialValues,
|
initialValues: draftInitialValues,
|
||||||
initialFeatureValues: draftSetup?.featureValues,
|
initialProviderOptions: draftSetup?.providerOptions,
|
||||||
isVisible: true,
|
isVisible: true,
|
||||||
lockedWorkingDir: draftWorkingDirectory ?? undefined,
|
lockedWorkingDir: draftWorkingDirectory ?? undefined,
|
||||||
},
|
},
|
||||||
@@ -351,8 +356,7 @@ export function WorkspaceDraftAgentTab({
|
|||||||
const draftModeOptions = composerState.modeOptions;
|
const draftModeOptions = composerState.modeOptions;
|
||||||
const draftSelectedMode = composerState.selectedMode;
|
const draftSelectedMode = composerState.selectedMode;
|
||||||
const draftSetMode = composerState.setModeFromUser;
|
const draftSetMode = composerState.setModeFromUser;
|
||||||
const draftFeatures = composerState.agentControls.features;
|
const draftOptionControls = composerState.agentControls.optionControls;
|
||||||
const draftOnSetFeature = composerState.agentControls.onSetFeature;
|
|
||||||
|
|
||||||
const clearDraftInput = draftInput.clear;
|
const clearDraftInput = draftInput.clear;
|
||||||
const replaceDraftText = draftInput.replaceText;
|
const replaceDraftText = draftInput.replaceText;
|
||||||
@@ -509,7 +513,9 @@ export function WorkspaceDraftAgentTab({
|
|||||||
providers: composerState.modelSelectorProviders,
|
providers: composerState.modelSelectorProviders,
|
||||||
selectedProvider: draftProvider,
|
selectedProvider: draftProvider,
|
||||||
selectedModelId: composerState.effectiveModelId,
|
selectedModelId: composerState.effectiveModelId,
|
||||||
select: composerState.setProviderAndModelFromUser,
|
select: (provider, modelId) => {
|
||||||
|
composerState.setProviderAndModelFromUser(provider, modelId);
|
||||||
|
},
|
||||||
},
|
},
|
||||||
thinking: {
|
thinking: {
|
||||||
options: draftThinkingOptions,
|
options: draftThinkingOptions,
|
||||||
@@ -521,10 +527,7 @@ export function WorkspaceDraftAgentTab({
|
|||||||
selectedId: draftSelectedMode,
|
selectedId: draftSelectedMode,
|
||||||
select: draftSetMode,
|
select: draftSetMode,
|
||||||
},
|
},
|
||||||
features: {
|
optionControls: draftOptionControls ?? null,
|
||||||
list: draftFeatures,
|
|
||||||
set: draftOnSetFeature,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const isReadyForPendingAutoSubmit = Boolean(
|
const isReadyForPendingAutoSubmit = Boolean(
|
||||||
|
|||||||
@@ -139,6 +139,8 @@ import type {
|
|||||||
} from "@/attachments/types";
|
} from "@/attachments/types";
|
||||||
import type { SelectedFile } from "@/attachments/selected-file";
|
import type { SelectedFile } from "@/attachments/selected-file";
|
||||||
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
|
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
|
||||||
|
import { ComposerInputProvider, type ComposerInput } from "@/composer/session";
|
||||||
|
import { insertAtSelection } from "@/composer/insert-text";
|
||||||
import { composerWorkspaceAttachment } from "@/composer/attachments/workspace";
|
import { composerWorkspaceAttachment } from "@/composer/attachments/workspace";
|
||||||
import { useWorkspaceAttachmentsForScopes } from "@/attachments/workspace-attachments-store";
|
import { useWorkspaceAttachmentsForScopes } from "@/attachments/workspace-attachments-store";
|
||||||
import { droppedItemsToSelectedFiles } from "@/composer/attachments/drop";
|
import { droppedItemsToSelectedFiles } from "@/composer/attachments/drop";
|
||||||
@@ -1419,6 +1421,40 @@ function ComposerContentImpl({
|
|||||||
[onChangeText],
|
[onChangeText],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const insertUserInput = useCallback(
|
||||||
|
(text: string) => {
|
||||||
|
const input = messageInputRef.current;
|
||||||
|
if (!input) {
|
||||||
|
onChangeText(textSource.getSnapshot() + text);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const inserted = insertAtSelection(input.getInputSnapshot(), text);
|
||||||
|
input.replaceText(inserted.text, inserted.selection);
|
||||||
|
},
|
||||||
|
[onChangeText, textSource],
|
||||||
|
);
|
||||||
|
const isComposerLockedRef = useRef(isComposerLocked);
|
||||||
|
isComposerLockedRef.current = isComposerLocked;
|
||||||
|
const composerInput = useMemo<ComposerInput>(
|
||||||
|
() => ({
|
||||||
|
locked: isComposerLocked,
|
||||||
|
isLocked: () => isComposerLockedRef.current,
|
||||||
|
textSource,
|
||||||
|
setText: replaceUserInput,
|
||||||
|
insertText: insertUserInput,
|
||||||
|
attachments,
|
||||||
|
changeAttachments: setSelectedAttachments,
|
||||||
|
}),
|
||||||
|
[
|
||||||
|
attachments,
|
||||||
|
insertUserInput,
|
||||||
|
isComposerLocked,
|
||||||
|
replaceUserInput,
|
||||||
|
setSelectedAttachments,
|
||||||
|
textSource,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
const runClientSlashCommand = useCallback(
|
const runClientSlashCommand = useCallback(
|
||||||
(command: ClientSlashCommand): boolean => {
|
(command: ClientSlashCommand): boolean => {
|
||||||
if (command.execution !== "immediate" || !onClientSlashCommand) {
|
if (command.execution !== "immediate" || !onClientSlashCommand) {
|
||||||
@@ -2223,18 +2259,27 @@ function ComposerContentImpl({
|
|||||||
[attachments, setSelectedAttachments, setGithubSearchQuery, setIsGithubPickerOpen],
|
[attachments, setSelectedAttachments, setGithubSearchQuery, setIsGithubPickerOpen],
|
||||||
);
|
);
|
||||||
|
|
||||||
const leftContent = useMemo(
|
const leftContent = useMemo(() => {
|
||||||
() =>
|
const controls = renderLeftContent({
|
||||||
renderLeftContent({
|
|
||||||
agentControls,
|
agentControls,
|
||||||
agentId,
|
agentId,
|
||||||
serverId,
|
serverId,
|
||||||
focusInput,
|
focusInput,
|
||||||
isCompactLayout,
|
isCompactLayout,
|
||||||
showAgentControls: mode.showAgentControls,
|
showAgentControls: mode.showAgentControls,
|
||||||
}),
|
});
|
||||||
[agentControls, agentId, focusInput, isCompactLayout, mode.showAgentControls, serverId],
|
return controls ? (
|
||||||
);
|
<ComposerInputProvider value={composerInput}>{controls}</ComposerInputProvider>
|
||||||
|
) : null;
|
||||||
|
}, [
|
||||||
|
agentControls,
|
||||||
|
agentId,
|
||||||
|
composerInput,
|
||||||
|
focusInput,
|
||||||
|
isCompactLayout,
|
||||||
|
mode.showAgentControls,
|
||||||
|
serverId,
|
||||||
|
]);
|
||||||
|
|
||||||
const handleAttachButtonRef = useCallback((node: View | null) => {
|
const handleAttachButtonRef = useCallback((node: View | null) => {
|
||||||
attachButtonRef.current = node;
|
attachButtonRef.current = node;
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { insertAtSelection } from "./insert-text";
|
||||||
|
|
||||||
|
describe("insertAtSelection", () => {
|
||||||
|
it("inserts at the caret and moves the caret after the insertion", () => {
|
||||||
|
expect(insertAtSelection({ text: "ab", selection: { start: 1, end: 1 } }, "XY")).toEqual({
|
||||||
|
text: "aXYb",
|
||||||
|
selection: { start: 3, end: 3 },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("replaces the selection, however it was dragged", () => {
|
||||||
|
expect(insertAtSelection({ text: "abcd", selection: { start: 3, end: 1 } }, "-")).toEqual({
|
||||||
|
text: "a-d",
|
||||||
|
selection: { start: 2, end: 2 },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import type { ComposerInputSnapshot } from "@/composer/input/input";
|
||||||
|
|
||||||
|
/** The text with `inserted` in place of the selection, and the caret after it. */
|
||||||
|
export function insertAtSelection(
|
||||||
|
{ text, selection }: ComposerInputSnapshot,
|
||||||
|
inserted: string,
|
||||||
|
): ComposerInputSnapshot {
|
||||||
|
const start = Math.min(selection.start, selection.end);
|
||||||
|
const end = Math.max(selection.start, selection.end);
|
||||||
|
const caret = start + inserted.length;
|
||||||
|
return {
|
||||||
|
text: text.slice(0, start) + inserted + text.slice(end),
|
||||||
|
selection: { start: caret, end: caret },
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import { createContext, useContext, type ReactNode } from "react";
|
||||||
|
import type { JsonValue, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||||
|
import type { UserComposerAttachment } from "@/attachments/types";
|
||||||
|
import type { ComposerTextSource } from "@/composer/text-source";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The text and attachments of the composer a control sits in. `Composer` provides it, so a
|
||||||
|
* control reaches the prompt without knowing which screen mounted the composer.
|
||||||
|
*/
|
||||||
|
export interface ComposerInput {
|
||||||
|
/** The prompt is held while the composer submits; the built-in input is read-only meanwhile. */
|
||||||
|
locked: boolean;
|
||||||
|
/** `locked` as it is now. A command a plugin kept from an earlier render asks this. */
|
||||||
|
isLocked: () => boolean;
|
||||||
|
textSource: ComposerTextSource;
|
||||||
|
setText: (text: string) => void;
|
||||||
|
/** Inserts at the cursor, replacing the selection. */
|
||||||
|
insertText: (text: string) => void;
|
||||||
|
attachments: readonly UserComposerAttachment[];
|
||||||
|
changeAttachments: (
|
||||||
|
updater: (current: UserComposerAttachment[]) => UserComposerAttachment[],
|
||||||
|
) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The agent a composer configures, as one set of reads and commands. A running agent sends each
|
||||||
|
* command to the daemon; a draft keeps it locally until the agent is created. Controls call the
|
||||||
|
* same command either way.
|
||||||
|
*/
|
||||||
|
export interface ComposerAgent {
|
||||||
|
context: "agent" | "draft" | "new-workspace";
|
||||||
|
/** The agent is being created; the built-in controls are disabled meanwhile. */
|
||||||
|
locked: boolean;
|
||||||
|
/** `locked` as it is now. A command a plugin kept from an earlier render asks this. */
|
||||||
|
isLocked: () => boolean;
|
||||||
|
provider: string | null;
|
||||||
|
model: string | null;
|
||||||
|
mode: string | null;
|
||||||
|
thinking: string | null;
|
||||||
|
/** The options the agent runs with, defaults included. */
|
||||||
|
options: ProviderOptions;
|
||||||
|
metadata: Record<string, JsonValue>;
|
||||||
|
setProvider: (provider: string) => Promise<void>;
|
||||||
|
setModel: (modelId: string) => Promise<void>;
|
||||||
|
setMode: (modeId: string) => Promise<void>;
|
||||||
|
setThinking: (thinkingOptionId: string) => Promise<void>;
|
||||||
|
/** Top-level keys replace; `null` removes the agent's own value. */
|
||||||
|
setOptions: (patch: ProviderOptions) => Promise<void>;
|
||||||
|
/** Top-level keys replace; `null` removes the key. */
|
||||||
|
setMetadata: (patch: Record<string, JsonValue>) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ComposerInputContext = createContext<ComposerInput | null>(null);
|
||||||
|
const ComposerAgentContext = createContext<ComposerAgent | null>(null);
|
||||||
|
|
||||||
|
export function ComposerInputProvider({
|
||||||
|
value,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
value: ComposerInput;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
return <ComposerInputContext.Provider value={value}>{children}</ComposerInputContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ComposerAgentProvider({
|
||||||
|
value,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
value: ComposerAgent | null;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
return <ComposerAgentContext.Provider value={value}>{children}</ComposerAgentContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useComposerInput(): ComposerInput | null {
|
||||||
|
return useContext(ComposerInputContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useComposerAgent(): ComposerAgent | null {
|
||||||
|
return useContext(ComposerAgentContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True while the composer holds its prompt or its agent's settings for a submit in flight. */
|
||||||
|
export function useComposerLocked(): boolean {
|
||||||
|
const input = useComposerInput();
|
||||||
|
const agent = useComposerAgent();
|
||||||
|
return Boolean(input?.locked || agent?.locked);
|
||||||
|
}
|
||||||
@@ -80,7 +80,7 @@ describe("create agent preferences", () => {
|
|||||||
modelId: "gpt-5.5",
|
modelId: "gpt-5.5",
|
||||||
modeId: "full-access",
|
modeId: "full-access",
|
||||||
thinkingOptionId: "high",
|
thinkingOptionId: "high",
|
||||||
featureValues: { fast_mode: true },
|
options: { fast_mode: true },
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -95,7 +95,7 @@ describe("create agent preferences", () => {
|
|||||||
model: "gpt-5.5",
|
model: "gpt-5.5",
|
||||||
mode: "full-access",
|
mode: "full-access",
|
||||||
thinkingByModel: { "gpt-5.5": "high" },
|
thinkingByModel: { "gpt-5.5": "high" },
|
||||||
featureValues: { fast_mode: true },
|
options: { fast_mode: true },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -119,7 +119,7 @@ describe("create agent preferences", () => {
|
|||||||
model: "gpt-5.6",
|
model: "gpt-5.6",
|
||||||
mode: undefined,
|
mode: undefined,
|
||||||
thinkingByModel: undefined,
|
thinkingByModel: undefined,
|
||||||
featureValues: undefined,
|
options: undefined,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
).toEqual({
|
).toEqual({
|
||||||
@@ -167,13 +167,13 @@ describe("create agent preferences", () => {
|
|||||||
modelId: "one-minute-stream",
|
modelId: "one-minute-stream",
|
||||||
modeId: "approval-test",
|
modeId: "approval-test",
|
||||||
thinkingOptionId: "",
|
thinkingOptionId: "",
|
||||||
featureValues: {},
|
options: {},
|
||||||
}),
|
}),
|
||||||
).toEqual({
|
).toEqual({
|
||||||
provider: "mock",
|
provider: "mock",
|
||||||
providerPreferences: {
|
providerPreferences: {
|
||||||
pi: { model: "anthropic/sonnet" },
|
pi: { model: "anthropic/sonnet" },
|
||||||
mock: { model: "one-minute-stream", mode: "approval-test", featureValues: {} },
|
mock: { model: "one-minute-stream", mode: "approval-test", options: {} },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -208,6 +208,29 @@ 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", () => {
|
it("rejects unknown persisted fields outside the explicit legacy shape", () => {
|
||||||
expect(parseFormPreferences({ provider: "codex", surprise: true })).toEqual({});
|
expect(parseFormPreferences({ provider: "codex", surprise: true })).toEqual({});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||||
|
|
||||||
const featureValuesSchema = z.record(z.string(), z.union([z.boolean(), z.string(), z.null()]));
|
const optionsSchema = z.record(z.string(), z.json());
|
||||||
|
|
||||||
export interface ProviderPreferences {
|
export interface ProviderPreferences {
|
||||||
model?: string;
|
model?: string;
|
||||||
mode?: string;
|
mode?: string;
|
||||||
thinkingByModel?: Record<string, string>;
|
thinkingByModel?: Record<string, string>;
|
||||||
featureValues?: Record<string, unknown>;
|
/** Last-used values of the provider's option controls, by option key. */
|
||||||
|
options?: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type LaunchTarget = { kind: "chat" } | { kind: "terminal"; profileId: string };
|
export type LaunchTarget = { kind: "chat" } | { kind: "terminal"; profileId: string };
|
||||||
@@ -20,12 +21,23 @@ export interface FormPreferences {
|
|||||||
launchTarget?: LaunchTarget;
|
launchTarget?: LaunchTarget;
|
||||||
}
|
}
|
||||||
|
|
||||||
const providerPreferencesSchema: z.ZodType<ProviderPreferences> = z.strictObject({
|
// 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(),
|
model: z.string().optional(),
|
||||||
mode: z.string().optional(),
|
mode: z.string().optional(),
|
||||||
thinkingByModel: z.record(z.string(), z.string()).optional(),
|
thinkingByModel: z.record(z.string(), z.string()).optional(),
|
||||||
featureValues: featureValuesSchema.optional(),
|
options: optionsSchema.optional(),
|
||||||
});
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
const launchTargetSchema: z.ZodType<LaunchTarget> = z.discriminatedUnion("kind", [
|
const launchTargetSchema: z.ZodType<LaunchTarget> = z.discriminatedUnion("kind", [
|
||||||
z.strictObject({ kind: z.literal("chat") }),
|
z.strictObject({ kind: z.literal("chat") }),
|
||||||
@@ -116,7 +128,7 @@ function applyProviderPreferenceUpdates(
|
|||||||
): ProviderPreferences {
|
): ProviderPreferences {
|
||||||
const next: ProviderPreferences = { ...existing };
|
const next: ProviderPreferences = { ...existing };
|
||||||
const nextThinkingByModel = mergeDefinedRecord(existing.thinkingByModel, updates.thinkingByModel);
|
const nextThinkingByModel = mergeDefinedRecord(existing.thinkingByModel, updates.thinkingByModel);
|
||||||
const nextFeatureValues = mergeDefinedRecord(existing.featureValues, updates.featureValues);
|
const nextOptions = mergeDefinedRecord(existing.options, updates.options);
|
||||||
|
|
||||||
if (updates.model !== undefined) {
|
if (updates.model !== undefined) {
|
||||||
next.model = updates.model;
|
next.model = updates.model;
|
||||||
@@ -129,8 +141,8 @@ function applyProviderPreferenceUpdates(
|
|||||||
if (nextThinkingByModel !== undefined) {
|
if (nextThinkingByModel !== undefined) {
|
||||||
next.thinkingByModel = nextThinkingByModel;
|
next.thinkingByModel = nextThinkingByModel;
|
||||||
}
|
}
|
||||||
if (nextFeatureValues !== undefined) {
|
if (nextOptions !== undefined) {
|
||||||
next.featureValues = nextFeatureValues;
|
next.options = nextOptions;
|
||||||
}
|
}
|
||||||
|
|
||||||
return next;
|
return next;
|
||||||
@@ -161,7 +173,7 @@ export function mergeCreateAgentSelectionPreferences(args: {
|
|||||||
modelId?: string | null;
|
modelId?: string | null;
|
||||||
modeId?: string | null;
|
modeId?: string | null;
|
||||||
thinkingOptionId?: string | null;
|
thinkingOptionId?: string | null;
|
||||||
featureValues?: Record<string, unknown>;
|
options?: Record<string, unknown>;
|
||||||
}): FormPreferences {
|
}): FormPreferences {
|
||||||
if (!args.provider) {
|
if (!args.provider) {
|
||||||
return args.preferences;
|
return args.preferences;
|
||||||
@@ -170,7 +182,7 @@ export function mergeCreateAgentSelectionPreferences(args: {
|
|||||||
const modelId = args.modelId?.trim() ?? "";
|
const modelId = args.modelId?.trim() ?? "";
|
||||||
const modeId = args.modeId?.trim() ?? "";
|
const modeId = args.modeId?.trim() ?? "";
|
||||||
const thinkingOptionId = args.thinkingOptionId?.trim() ?? "";
|
const thinkingOptionId = args.thinkingOptionId?.trim() ?? "";
|
||||||
const featureValues = featureValuesSchema.safeParse(args.featureValues);
|
const options = optionsSchema.safeParse(args.options);
|
||||||
|
|
||||||
return mergeProviderPreferences({
|
return mergeProviderPreferences({
|
||||||
preferences: args.preferences,
|
preferences: args.preferences,
|
||||||
@@ -179,7 +191,7 @@ export function mergeCreateAgentSelectionPreferences(args: {
|
|||||||
model: modelId || undefined,
|
model: modelId || undefined,
|
||||||
mode: args.modeId === undefined ? undefined : modeId || null,
|
mode: args.modeId === undefined ? undefined : modeId || null,
|
||||||
...(modelId && thinkingOptionId ? { thinkingByModel: { [modelId]: thinkingOptionId } } : {}),
|
...(modelId && thinkingOptionId ? { thinkingByModel: { [modelId]: thinkingOptionId } } : {}),
|
||||||
...(featureValues.success ? { featureValues: featureValues.data } : {}),
|
...(options.success ? { options: options.data } : {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -192,7 +204,7 @@ export function applyAgentProfilePreferences(args: {
|
|||||||
modelId: string;
|
modelId: string;
|
||||||
modeId: string;
|
modeId: string;
|
||||||
thinkingOptionId: string;
|
thinkingOptionId: string;
|
||||||
featureValues: Record<string, unknown>;
|
options: Record<string, unknown>;
|
||||||
}): FormPreferences {
|
}): FormPreferences {
|
||||||
let next = args.preferences;
|
let next = args.preferences;
|
||||||
if (args.previousProvider) {
|
if (args.previousProvider) {
|
||||||
@@ -215,7 +227,7 @@ export function applyAgentProfilePreferences(args: {
|
|||||||
...(args.modelId && args.thinkingOptionId
|
...(args.modelId && args.thinkingOptionId
|
||||||
? { thinkingByModel: { [args.modelId]: args.thinkingOptionId } }
|
? { thinkingByModel: { [args.modelId]: args.thinkingOptionId } }
|
||||||
: {}),
|
: {}),
|
||||||
featureValues: args.featureValues,
|
options: args.options,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,53 +0,0 @@
|
|||||||
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,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
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 modeId = draftConfig.modeId?.trim() ?? "";
|
||||||
const model = draftConfig.model?.trim() ?? "";
|
const model = draftConfig.model?.trim() ?? "";
|
||||||
const thinkingOptionId = draftConfig.thinkingOptionId?.trim() ?? "";
|
const thinkingOptionId = draftConfig.thinkingOptionId?.trim() ?? "";
|
||||||
const featureValues = draftConfig.featureValues;
|
const providerOptions = draftConfig.providerOptions;
|
||||||
return {
|
return {
|
||||||
provider: draftConfig.provider,
|
provider: draftConfig.provider,
|
||||||
cwd,
|
cwd,
|
||||||
...(modeId ? { modeId } : {}),
|
...(modeId ? { modeId } : {}),
|
||||||
...(model ? { model } : {}),
|
...(model ? { model } : {}),
|
||||||
...(thinkingOptionId ? { thinkingOptionId } : {}),
|
...(thinkingOptionId ? { thinkingOptionId } : {}),
|
||||||
...(featureValues && Object.keys(featureValues).length > 0 ? { featureValues } : {}),
|
...(providerOptions && Object.keys(providerOptions).length > 0 ? { providerOptions } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useCallback, useEffect, useMemo, useReducer, useRef } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||||
import type { AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
|
import type { AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
|
||||||
import type {
|
import type {
|
||||||
AgentMode,
|
AgentMode,
|
||||||
@@ -28,14 +28,13 @@ import {
|
|||||||
mergeSelectedComposerPreferences,
|
mergeSelectedComposerPreferences,
|
||||||
buildProviderDefinitionMap,
|
buildProviderDefinitionMap,
|
||||||
buildProviderDefinitionMapForStatuses,
|
buildProviderDefinitionMapForStatuses,
|
||||||
INITIAL_AGENT_FORM_RESOLUTION,
|
|
||||||
INITIAL_USER_MODIFIED,
|
|
||||||
RESOLVABLE_PROVIDER_STATUSES,
|
RESOLVABLE_PROVIDER_STATUSES,
|
||||||
SELECTABLE_PROVIDER_STATUSES,
|
SELECTABLE_PROVIDER_STATUSES,
|
||||||
type FormInitialValues,
|
type FormInitialValues,
|
||||||
type FormState,
|
type FormState,
|
||||||
type ProviderModelsByProvider,
|
type ProviderModelsByProvider,
|
||||||
} from "@/provider-selection/resolve-agent-form";
|
} from "@/provider-selection/resolve-agent-form";
|
||||||
|
import { openAgentForm, type AgentFormCatalog } from "@/provider-selection/agent-form-store";
|
||||||
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
import { useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||||
import type { MaterializedAgentProfile } from "@/agent-profiles";
|
import type { MaterializedAgentProfile } from "@/agent-profiles";
|
||||||
|
|
||||||
@@ -52,10 +51,13 @@ export interface UseAgentFormStateOptions {
|
|||||||
export interface UseAgentFormStateResult {
|
export interface UseAgentFormStateResult {
|
||||||
selectedServerId: string | null;
|
selectedServerId: string | null;
|
||||||
selectedProvider: AgentProvider | null;
|
selectedProvider: AgentProvider | null;
|
||||||
|
/** The provider as it is now, which a render may not have reached yet. */
|
||||||
|
getSelectedProvider: () => AgentProvider | null;
|
||||||
selectedMode: string;
|
selectedMode: string;
|
||||||
setModeFromUser: (modeId: string) => void;
|
setModeFromUser: (modeId: string) => void;
|
||||||
selectedModel: string;
|
selectedModel: string;
|
||||||
setModelFromUser: (modelId: string) => void;
|
/** `false` when the provider's loaded catalog does not list the model. */
|
||||||
|
setModelFromUser: (modelId: string) => boolean;
|
||||||
selectedThinkingOptionId: string;
|
selectedThinkingOptionId: string;
|
||||||
setThinkingOptionFromUser: (thinkingOptionId: string) => void;
|
setThinkingOptionFromUser: (thinkingOptionId: string) => void;
|
||||||
workingDir: string;
|
workingDir: string;
|
||||||
@@ -74,13 +76,20 @@ export interface UseAgentFormStateResult {
|
|||||||
modelError: string | null;
|
modelError: string | null;
|
||||||
refreshProviderModels: (provider?: AgentProvider) => void;
|
refreshProviderModels: (provider?: AgentProvider) => void;
|
||||||
refetchProviderModelsIfStale: () => void;
|
refetchProviderModelsIfStale: () => void;
|
||||||
setProviderAndModelFromUser: (provider: AgentProvider, modelId: string) => void;
|
/** `false` when the provider is unknown or not ready. */
|
||||||
|
setProviderAndModelFromUser: (provider: AgentProvider, modelId: string) => boolean;
|
||||||
applyProfileFromUser: (profile: MaterializedAgentProfile) => void;
|
applyProfileFromUser: (profile: MaterializedAgentProfile) => void;
|
||||||
clearProviderSelectionFromUser: () => void;
|
clearProviderSelectionFromUser: () => void;
|
||||||
workingDirIsEmpty: boolean;
|
workingDirIsEmpty: boolean;
|
||||||
persistFormPreferences: () => Promise<void>;
|
persistFormPreferences: () => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const EMPTY_CATALOG: AgentFormCatalog = {
|
||||||
|
selectableProviders: new Map(),
|
||||||
|
models: new Map(),
|
||||||
|
providerPreferences: () => undefined,
|
||||||
|
};
|
||||||
|
|
||||||
function resolveSelectedProviderModes(input: {
|
function resolveSelectedProviderModes(input: {
|
||||||
selectedEntry: ProviderSnapshotEntry | null;
|
selectedEntry: ProviderSnapshotEntry | null;
|
||||||
provider: AgentProvider | null;
|
provider: AgentProvider | null;
|
||||||
@@ -172,11 +181,15 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
|||||||
[updatePreferences],
|
[updatePreferences],
|
||||||
);
|
);
|
||||||
|
|
||||||
const [{ form: formState, userModified, resolution }, dispatch] = useReducer(resolveAgentForm, {
|
// The store reads what the host offers when a command runs; each render publishes the latest.
|
||||||
form: { provider: null, modeId: "", model: "", thinkingOptionId: "" },
|
const catalogRef = useRef<AgentFormCatalog>(EMPTY_CATALOG);
|
||||||
userModified: INITIAL_USER_MODIFIED,
|
const [formStore] = useState(() => openAgentForm(() => catalogRef.current));
|
||||||
resolution: INITIAL_AGENT_FORM_RESOLUTION,
|
const { form: formState, resolution } = useSyncExternalStore(
|
||||||
});
|
formStore.subscribe,
|
||||||
|
formStore.getState,
|
||||||
|
formStore.getState,
|
||||||
|
);
|
||||||
|
const dispatch = formStore.dispatch;
|
||||||
|
|
||||||
const {
|
const {
|
||||||
entries: snapshotEntries,
|
entries: snapshotEntries,
|
||||||
@@ -246,6 +259,12 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
|||||||
const providerDefinitionMap = snapshotProviderDefinitionMap;
|
const providerDefinitionMap = snapshotProviderDefinitionMap;
|
||||||
const selectableProviderDefinitionMap = snapshotSelectableProviderDefinitionMap;
|
const selectableProviderDefinitionMap = snapshotSelectableProviderDefinitionMap;
|
||||||
const allProviderModels = snapshotAllProviderModels;
|
const allProviderModels = snapshotAllProviderModels;
|
||||||
|
catalogRef.current = {
|
||||||
|
selectableProviders: selectableProviderDefinitionMap,
|
||||||
|
models: allProviderModels,
|
||||||
|
providerPreferences: (provider) =>
|
||||||
|
preferenceOverlayRef.current.current().providerPreferences?.[provider],
|
||||||
|
};
|
||||||
const modelSelectorProviders = snapshotModelSelectorProviders;
|
const modelSelectorProviders = snapshotModelSelectorProviders;
|
||||||
const availableModels = snapshotSelectedProviderModels;
|
const availableModels = snapshotSelectedProviderModels;
|
||||||
const modeOptions = snapshotSelectedProviderModes;
|
const modeOptions = snapshotSelectedProviderModes;
|
||||||
@@ -277,27 +296,15 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
|||||||
preferences,
|
preferences,
|
||||||
snapshotProviderModelsByProvider,
|
snapshotProviderModelsByProvider,
|
||||||
snapshotResolvableProviderDefinitionMap,
|
snapshotResolvableProviderDefinitionMap,
|
||||||
|
dispatch,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const setProviderAndModelFromUser = useCallback(
|
const setProviderAndModelFromUser = useCallback(
|
||||||
(provider: AgentProvider, modelId: string) => {
|
(provider: AgentProvider, modelId: string): boolean => {
|
||||||
if (!selectableProviderDefinitionMap.has(provider)) {
|
if (!formStore.setProviderAndModel(provider, modelId)) return false;
|
||||||
return;
|
|
||||||
}
|
|
||||||
const providerDef = selectableProviderDefinitionMap.get(provider);
|
|
||||||
const providerModels = allProviderModels.get(provider) ?? null;
|
const providerModels = allProviderModels.get(provider) ?? null;
|
||||||
const providerPrefs = preferenceOverlayRef.current.current().providerPreferences?.[provider];
|
const nextModelId =
|
||||||
const normalizedModelId = normalizeSelectedModelId(modelId);
|
normalizeSelectedModelId(modelId) || resolveDefaultModelId(providerModels);
|
||||||
const nextModelId = normalizedModelId || resolveDefaultModelId(providerModels);
|
|
||||||
|
|
||||||
dispatch({
|
|
||||||
type: "SET_PROVIDER_AND_MODEL_FROM_USER",
|
|
||||||
provider,
|
|
||||||
modelId,
|
|
||||||
providerDef,
|
|
||||||
providerModels,
|
|
||||||
providerPrefs,
|
|
||||||
});
|
|
||||||
void updateCurrentPreferences((current) =>
|
void updateCurrentPreferences((current) =>
|
||||||
mergeSelectedComposerPreferences({
|
mergeSelectedComposerPreferences({
|
||||||
preferences: current,
|
preferences: current,
|
||||||
@@ -307,13 +314,14 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
return true;
|
||||||
},
|
},
|
||||||
[allProviderModels, selectableProviderDefinitionMap, updateCurrentPreferences],
|
[allProviderModels, formStore, updateCurrentPreferences],
|
||||||
);
|
);
|
||||||
|
|
||||||
const clearProviderSelectionFromUser = useCallback(() => {
|
const clearProviderSelectionFromUser = useCallback(() => {
|
||||||
dispatch({ type: "CLEAR_PROVIDER_SELECTION_FROM_USER" });
|
dispatch({ type: "CLEAR_PROVIDER_SELECTION_FROM_USER" });
|
||||||
}, []);
|
}, [dispatch]);
|
||||||
|
|
||||||
const applyProfileFromUser = useCallback(
|
const applyProfileFromUser = useCallback(
|
||||||
(profile: MaterializedAgentProfile) => {
|
(profile: MaterializedAgentProfile) => {
|
||||||
@@ -322,7 +330,8 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const previousProvider = formState.provider;
|
const formBefore = formStore.getState();
|
||||||
|
const previousProvider = formBefore.form.provider;
|
||||||
const providerDef = selectableProviderDefinitionMap.get(provider);
|
const providerDef = selectableProviderDefinitionMap.get(provider);
|
||||||
const providerModels = allProviderModels.get(provider) ?? null;
|
const providerModels = allProviderModels.get(provider) ?? null;
|
||||||
const providerPrefs = preferenceOverlayRef.current.current().providerPreferences?.[provider];
|
const providerPrefs = preferenceOverlayRef.current.current().providerPreferences?.[provider];
|
||||||
@@ -336,7 +345,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
|||||||
providerModels,
|
providerModels,
|
||||||
providerPrefs,
|
providerPrefs,
|
||||||
};
|
};
|
||||||
const nextState = resolveAgentForm({ form: formState, userModified, resolution }, action);
|
const nextState = resolveAgentForm(formBefore, action);
|
||||||
const previousProviderModeIds = previousProvider
|
const previousProviderModeIds = previousProvider
|
||||||
? (providerDefinitionMap.get(previousProvider)?.modes.map((mode) => mode.id) ?? [])
|
? (providerDefinitionMap.get(previousProvider)?.modes.map((mode) => mode.id) ?? [])
|
||||||
: [];
|
: [];
|
||||||
@@ -352,7 +361,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
|||||||
modelId: model,
|
modelId: model,
|
||||||
modeId,
|
modeId,
|
||||||
thinkingOptionId,
|
thinkingOptionId,
|
||||||
featureValues: profile.featureValues,
|
options: profile.options,
|
||||||
});
|
});
|
||||||
}).catch((error) => {
|
}).catch((error) => {
|
||||||
console.warn("[useAgentFormState] persist profile preference failed", error);
|
console.warn("[useAgentFormState] persist profile preference failed", error);
|
||||||
@@ -360,19 +369,18 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
|||||||
},
|
},
|
||||||
[
|
[
|
||||||
allProviderModels,
|
allProviderModels,
|
||||||
formState,
|
dispatch,
|
||||||
|
formStore,
|
||||||
providerDefinitionMap,
|
providerDefinitionMap,
|
||||||
resolution,
|
|
||||||
selectableProviderDefinitionMap,
|
selectableProviderDefinitionMap,
|
||||||
updateCurrentPreferences,
|
updateCurrentPreferences,
|
||||||
userModified,
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
const setModeFromUser = useCallback(
|
const setModeFromUser = useCallback(
|
||||||
(modeId: string) => {
|
(modeId: string) => {
|
||||||
dispatch({ type: "SET_MODE_FROM_USER", modeId });
|
dispatch({ type: "SET_MODE_FROM_USER", modeId });
|
||||||
const provider = formState.provider;
|
const { provider } = formStore.getState().form;
|
||||||
if (provider) {
|
if (provider) {
|
||||||
void updateCurrentPreferences((current) =>
|
void updateCurrentPreferences((current) =>
|
||||||
mergeSelectedComposerPreferences({
|
mergeSelectedComposerPreferences({
|
||||||
@@ -385,24 +393,18 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[formState.provider, updateCurrentPreferences],
|
[dispatch, formStore, updateCurrentPreferences],
|
||||||
);
|
);
|
||||||
|
|
||||||
const setModelFromUser = useCallback(
|
const setModelFromUser = useCallback(
|
||||||
(modelId: string) => {
|
(modelId: string): boolean => {
|
||||||
const provider = formState.provider;
|
if (!formStore.setModel(modelId)) return false;
|
||||||
const providerPrefs = provider
|
const { provider } = formStore.getState().form;
|
||||||
? preferenceOverlayRef.current.current().providerPreferences?.[provider]
|
|
||||||
: undefined;
|
|
||||||
dispatch({
|
|
||||||
type: "SET_MODEL_FROM_USER",
|
|
||||||
modelId,
|
|
||||||
availableModels,
|
|
||||||
providerPrefs,
|
|
||||||
});
|
|
||||||
if (provider) {
|
if (provider) {
|
||||||
const normalizedModelId = normalizeSelectedModelId(modelId);
|
const listed = allProviderModels.get(provider);
|
||||||
const nextModelId = normalizedModelId || resolveDefaultModelId(availableModels);
|
const nextModelId =
|
||||||
|
normalizeSelectedModelId(modelId) ||
|
||||||
|
resolveDefaultModelId(listed?.length ? listed : null);
|
||||||
void updateCurrentPreferences((current) =>
|
void updateCurrentPreferences((current) =>
|
||||||
mergeSelectedComposerPreferences({
|
mergeSelectedComposerPreferences({
|
||||||
preferences: current,
|
preferences: current,
|
||||||
@@ -413,14 +415,15 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
return true;
|
||||||
},
|
},
|
||||||
[availableModels, formState.provider, updateCurrentPreferences],
|
[allProviderModels, formStore, updateCurrentPreferences],
|
||||||
);
|
);
|
||||||
|
|
||||||
const setThinkingOptionFromUser = useCallback(
|
const setThinkingOptionFromUser = useCallback(
|
||||||
(thinkingOptionId: string) => {
|
(thinkingOptionId: string) => {
|
||||||
dispatch({ type: "SET_THINKING_OPTION_FROM_USER", thinkingOptionId });
|
dispatch({ type: "SET_THINKING_OPTION_FROM_USER", thinkingOptionId });
|
||||||
const { provider, model: modelId } = formState;
|
const { provider, model: modelId } = formStore.getState().form;
|
||||||
if (provider && modelId) {
|
if (provider && modelId) {
|
||||||
void updateCurrentPreferences((current) =>
|
void updateCurrentPreferences((current) =>
|
||||||
mergeSelectedComposerPreferences({
|
mergeSelectedComposerPreferences({
|
||||||
@@ -435,9 +438,11 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[formState, updateCurrentPreferences],
|
[dispatch, formStore, updateCurrentPreferences],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const getSelectedProvider = useCallback(() => formStore.getState().form.provider, [formStore]);
|
||||||
|
|
||||||
const refreshProviderModels = useCallback(
|
const refreshProviderModels = useCallback(
|
||||||
(provider?: AgentProvider) => {
|
(provider?: AgentProvider) => {
|
||||||
void refreshSnapshot(provider ? [provider] : undefined);
|
void refreshSnapshot(provider ? [provider] : undefined);
|
||||||
@@ -479,6 +484,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
|||||||
() => ({
|
() => ({
|
||||||
selectedServerId: serverId,
|
selectedServerId: serverId,
|
||||||
selectedProvider: formState.provider,
|
selectedProvider: formState.provider,
|
||||||
|
getSelectedProvider,
|
||||||
selectedMode: formState.modeId,
|
selectedMode: formState.modeId,
|
||||||
setModeFromUser,
|
setModeFromUser,
|
||||||
selectedModel: formState.model,
|
selectedModel: formState.model,
|
||||||
@@ -509,6 +515,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
|
|||||||
}),
|
}),
|
||||||
[
|
[
|
||||||
serverId,
|
serverId,
|
||||||
|
getSelectedProvider,
|
||||||
formState.provider,
|
formState.provider,
|
||||||
formState.modeId,
|
formState.modeId,
|
||||||
formState.model,
|
formState.model,
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
import { useRef } from "react";
|
import { useRef } from "react";
|
||||||
import type {
|
import type { AgentCapabilityFlags, AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||||
AgentCapabilityFlags,
|
import type { Agent } from "@/stores/session-store";
|
||||||
AgentFeature,
|
|
||||||
AgentProvider,
|
|
||||||
} from "@getpaseo/protocol/agent-types";
|
|
||||||
import type { ViewedTimelineStatus } from "@/timeline/viewed-timeline-sync";
|
import type { ViewedTimelineStatus } from "@/timeline/viewed-timeline-sync";
|
||||||
|
|
||||||
export interface AgentScreenAgent {
|
export interface AgentScreenAgent {
|
||||||
@@ -22,7 +19,8 @@ export interface AgentScreenAgent {
|
|||||||
modeId?: string | null;
|
modeId?: string | null;
|
||||||
thinkingOptionId?: string | null;
|
thinkingOptionId?: string | null;
|
||||||
} | null;
|
} | null;
|
||||||
features?: readonly AgentFeature[];
|
options?: Agent["options"];
|
||||||
|
controls?: Agent["controls"];
|
||||||
lastError?: string | null;
|
lastError?: string | null;
|
||||||
projectPlacement?: {
|
projectPlacement?: {
|
||||||
projectKey?: string;
|
projectKey?: string;
|
||||||
|
|||||||
@@ -1,159 +0,0 @@
|
|||||||
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,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
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,
|
||||||
|
shownDraftOptions,
|
||||||
|
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;
|
||||||
|
/** The form's provider as it is now, which a render may not have reached yet. */
|
||||||
|
getProvider: () => 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,
|
||||||
|
getProvider,
|
||||||
|
cwd,
|
||||||
|
modeId,
|
||||||
|
modelId,
|
||||||
|
thinkingOptionId,
|
||||||
|
initialOptions,
|
||||||
|
} = input;
|
||||||
|
const [model] = useState(() =>
|
||||||
|
openDraftOptions({ provider, seed: initialOptions, currentProvider: getProvider }),
|
||||||
|
);
|
||||||
|
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]);
|
||||||
|
|
||||||
|
// An edit belongs to the provider the form has now, even before the render that shows it.
|
||||||
|
const setOption = useCallback(
|
||||||
|
(key: string, value: unknown) => {
|
||||||
|
model.setOption(key, value);
|
||||||
|
const current = getProvider();
|
||||||
|
if (!current) return;
|
||||||
|
void updatePreferences((stored) =>
|
||||||
|
mergeProviderPreferences({
|
||||||
|
preferences: stored,
|
||||||
|
provider: current,
|
||||||
|
updates: { options: { [key]: value } },
|
||||||
|
}),
|
||||||
|
).catch((error) => {
|
||||||
|
console.warn("[useDraftProviderOptions] persist option preference failed", error);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[getProvider, model, 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],
|
||||||
|
);
|
||||||
|
|
||||||
|
// What the draft will create with, the plugin's own edits included, before the daemon answers.
|
||||||
|
const shownOptions = shownDraftOptions(state, { provider, requestKey });
|
||||||
|
|
||||||
|
return {
|
||||||
|
optionControls,
|
||||||
|
options: ownOptions,
|
||||||
|
shownOptions,
|
||||||
|
setOption,
|
||||||
|
applyProfile: model.applyProfile,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -36,7 +36,7 @@ export type ForkAgentSource = Pick<
|
|||||||
| "model"
|
| "model"
|
||||||
| "thinkingOptionId"
|
| "thinkingOptionId"
|
||||||
| "runtimeInfo"
|
| "runtimeInfo"
|
||||||
| "features"
|
| "options"
|
||||||
| "projectPlacement"
|
| "projectPlacement"
|
||||||
>;
|
>;
|
||||||
|
|
||||||
@@ -95,18 +95,13 @@ function buildForkDraftSetup(agent: ForkAgentSource): WorkspaceDraftTabSetup | u
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
const featureValues: Record<string, unknown> = {};
|
|
||||||
for (const feature of agent.features ?? []) {
|
|
||||||
featureValues[feature.id] = feature.value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
provider: agent.provider,
|
provider: agent.provider,
|
||||||
cwd: agent.cwd,
|
cwd: agent.cwd,
|
||||||
modeId: agent.currentModeId ?? agent.runtimeInfo?.modeId ?? null,
|
modeId: agent.currentModeId ?? agent.runtimeInfo?.modeId ?? null,
|
||||||
model: agent.model ?? agent.runtimeInfo?.model ?? null,
|
model: agent.model ?? agent.runtimeInfo?.model ?? null,
|
||||||
thinkingOptionId: agent.thinkingOptionId ?? agent.runtimeInfo?.thinkingOptionId ?? null,
|
thinkingOptionId: agent.thinkingOptionId ?? agent.runtimeInfo?.thinkingOptionId ?? null,
|
||||||
featureValues,
|
providerOptions: { ...agent.options },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ describe("mergeProviderPreferences", () => {
|
|||||||
providerPreferences: {
|
providerPreferences: {
|
||||||
codex: {
|
codex: {
|
||||||
model: "gpt-5.4",
|
model: "gpt-5.4",
|
||||||
featureValues: {
|
options: {
|
||||||
fast_mode: true,
|
fast_mode: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -71,7 +71,7 @@ describe("mergeProviderPreferences", () => {
|
|||||||
},
|
},
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
updates: {
|
updates: {
|
||||||
featureValues: {
|
options: {
|
||||||
plan_mode: true,
|
plan_mode: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -81,7 +81,7 @@ describe("mergeProviderPreferences", () => {
|
|||||||
providerPreferences: {
|
providerPreferences: {
|
||||||
codex: {
|
codex: {
|
||||||
model: "gpt-5.4",
|
model: "gpt-5.4",
|
||||||
featureValues: {
|
options: {
|
||||||
fast_mode: true,
|
fast_mode: true,
|
||||||
plan_mode: true,
|
plan_mode: true,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -116,7 +116,8 @@ interface ChatAgentStateShape {
|
|||||||
model?: Agent["model"];
|
model?: Agent["model"];
|
||||||
thinkingOptionId?: Agent["thinkingOptionId"];
|
thinkingOptionId?: Agent["thinkingOptionId"];
|
||||||
runtimeInfo?: Agent["runtimeInfo"];
|
runtimeInfo?: Agent["runtimeInfo"];
|
||||||
features?: Agent["features"];
|
options?: Agent["options"];
|
||||||
|
controls?: Agent["controls"];
|
||||||
lastError?: Agent["lastError"] | null;
|
lastError?: Agent["lastError"] | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,7 +176,8 @@ function selectChatAgentState(
|
|||||||
model: agent.model,
|
model: agent.model,
|
||||||
thinkingOptionId: agent.thinkingOptionId,
|
thinkingOptionId: agent.thinkingOptionId,
|
||||||
runtimeInfo: agent.runtimeInfo,
|
runtimeInfo: agent.runtimeInfo,
|
||||||
features: agent.features,
|
options: agent.options,
|
||||||
|
controls: agent.controls,
|
||||||
lastError: agent.lastError ?? null,
|
lastError: agent.lastError ?? null,
|
||||||
archivedAt: agent.archivedAt ?? null,
|
archivedAt: agent.archivedAt ?? null,
|
||||||
requiresAttention: agent.requiresAttention ?? false,
|
requiresAttention: agent.requiresAttention ?? false,
|
||||||
@@ -202,7 +204,8 @@ function buildChatAgentFromState(
|
|||||||
model: state.model,
|
model: state.model,
|
||||||
thinkingOptionId: state.thinkingOptionId,
|
thinkingOptionId: state.thinkingOptionId,
|
||||||
runtimeInfo: state.runtimeInfo,
|
runtimeInfo: state.runtimeInfo,
|
||||||
features: state.features,
|
options: state.options,
|
||||||
|
controls: state.controls,
|
||||||
lastError: state.lastError ?? null,
|
lastError: state.lastError ?? null,
|
||||||
projectPlacement,
|
projectPlacement,
|
||||||
};
|
};
|
||||||
@@ -635,7 +638,8 @@ function AgentPanelBody({
|
|||||||
model: agentState.model,
|
model: agentState.model,
|
||||||
thinkingOptionId: agentState.thinkingOptionId,
|
thinkingOptionId: agentState.thinkingOptionId,
|
||||||
runtimeInfo: agentState.runtimeInfo,
|
runtimeInfo: agentState.runtimeInfo,
|
||||||
features: agentState.features,
|
options: agentState.options,
|
||||||
|
controls: agentState.controls,
|
||||||
lastError: agentState.lastError ?? null,
|
lastError: agentState.lastError ?? null,
|
||||||
projectPlacement,
|
projectPlacement,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ function installation(): InstalledPlugin {
|
|||||||
sidebarItems: { header: [], footer: [] },
|
sidebarItems: { header: [], footer: [] },
|
||||||
legacySidebarItems: [],
|
legacySidebarItems: [],
|
||||||
filePanels: [],
|
filePanels: [],
|
||||||
|
composerItems: [],
|
||||||
workspacePanels: [],
|
workspacePanels: [],
|
||||||
commandCenterItems: [],
|
commandCenterItems: [],
|
||||||
clientSlashCommands: [],
|
clientSlashCommands: [],
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ const agent: Agent = {
|
|||||||
attentionReason: "permission",
|
attentionReason: "permission",
|
||||||
parentAgentId: null,
|
parentAgentId: null,
|
||||||
labels: { phase: "implementation" },
|
labels: { phase: "implementation" },
|
||||||
|
metadata: { "linear.issue": { id: "ENG-1" } },
|
||||||
};
|
};
|
||||||
|
|
||||||
describe("plugin context snapshots", () => {
|
describe("plugin context snapshots", () => {
|
||||||
@@ -107,12 +108,16 @@ describe("plugin context snapshots", () => {
|
|||||||
attentionReason: "permission",
|
attentionReason: "permission",
|
||||||
parentAgentId: null,
|
parentAgentId: null,
|
||||||
labels: { phase: "implementation" },
|
labels: { phase: "implementation" },
|
||||||
|
metadata: { "linear.issue": { id: "ENG-1" } },
|
||||||
});
|
});
|
||||||
expect(snapshot.labels).not.toBe(agent.labels);
|
expect(snapshot.labels).not.toBe(agent.labels);
|
||||||
expect(Object.isFrozen(snapshot)).toBe(true);
|
expect(Object.isFrozen(snapshot)).toBe(true);
|
||||||
expect(Object.isFrozen(snapshot.labels)).toBe(true);
|
expect(Object.isFrozen(snapshot.labels)).toBe(true);
|
||||||
expect(Reflect.set(snapshot, "title", "Hostile rename")).toBe(false);
|
expect(Reflect.set(snapshot, "title", "Hostile rename")).toBe(false);
|
||||||
expect(Reflect.set(snapshot.labels, "phase", "hostile")).toBe(false);
|
expect(Reflect.set(snapshot.labels, "phase", "hostile")).toBe(false);
|
||||||
|
const issue = snapshot.metadata["linear.issue"] as { id: string };
|
||||||
|
expect(Reflect.set(issue, "id", "hostile")).toBe(false);
|
||||||
|
expect(agent.metadata?.["linear.issue"]).toEqual({ id: "ENG-1" });
|
||||||
expect(snapshot.title).toBe("Implement plugin panels");
|
expect(snapshot.title).toBe("Implement plugin panels");
|
||||||
expect(snapshot.labels).toEqual({ phase: "implementation" });
|
expect(snapshot.labels).toEqual({ phase: "implementation" });
|
||||||
expect(agent.title).toBe("Implement plugin panels");
|
expect(agent.title).toBe("Implement plugin panels");
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { PluginAgentSnapshot, PluginWorkspaceSnapshot } from "@getpaseo/plugin";
|
import type { PluginAgentSnapshot, PluginWorkspaceSnapshot } from "@getpaseo/plugin";
|
||||||
import type { Agent, WorkspaceDescriptor } from "@/stores/session-store";
|
import type { Agent, WorkspaceDescriptor } from "@/stores/session-store";
|
||||||
|
import { cloneAndFreeze } from "../freeze";
|
||||||
|
|
||||||
const workspaceSnapshots = new WeakMap<WorkspaceDescriptor, PluginWorkspaceSnapshot>();
|
const workspaceSnapshots = new WeakMap<WorkspaceDescriptor, PluginWorkspaceSnapshot>();
|
||||||
const agentSnapshots = new WeakMap<Agent, Map<string, PluginAgentSnapshot>>();
|
const agentSnapshots = new WeakMap<Agent, Map<string, PluginAgentSnapshot>>();
|
||||||
@@ -49,6 +50,7 @@ export function createPluginAgentSnapshot(agent: Agent, workspaceId: string): Pl
|
|||||||
attentionReason: agent.attentionReason ?? null,
|
attentionReason: agent.attentionReason ?? null,
|
||||||
parentAgentId: agent.parentAgentId,
|
parentAgentId: agent.parentAgentId,
|
||||||
labels: Object.freeze({ ...agent.labels }),
|
labels: Object.freeze({ ...agent.labels }),
|
||||||
|
metadata: cloneAndFreeze(agent.metadata ?? {}),
|
||||||
});
|
});
|
||||||
const byWorkspace = agentSnapshots.get(agent) ?? new Map<string, PluginAgentSnapshot>();
|
const byWorkspace = agentSnapshots.get(agent) ?? new Map<string, PluginAgentSnapshot>();
|
||||||
byWorkspace.set(workspaceId, snapshot);
|
byWorkspace.set(workspaceId, snapshot);
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ const agent: PluginAgentSnapshot = {
|
|||||||
attentionReason: null,
|
attentionReason: null,
|
||||||
parentAgentId: null,
|
parentAgentId: null,
|
||||||
labels: {},
|
labels: {},
|
||||||
|
metadata: {},
|
||||||
};
|
};
|
||||||
|
|
||||||
const inspect = defineRpc({
|
const inspect = defineRpc({
|
||||||
@@ -85,6 +86,7 @@ function plugin(onAgentSelect: AgentCommandItem["onSelect"]): InstalledPlugin {
|
|||||||
sidebarItems: { header: [], footer: [] },
|
sidebarItems: { header: [], footer: [] },
|
||||||
legacySidebarItems: [],
|
legacySidebarItems: [],
|
||||||
filePanels: [],
|
filePanels: [],
|
||||||
|
composerItems: [],
|
||||||
workspacePanels: [
|
workspacePanels: [
|
||||||
{
|
{
|
||||||
id: "details",
|
id: "details",
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { useMemo, useSyncExternalStore } from "react";
|
||||||
|
import type { PluginHostProps } from "@getpaseo/plugin/client";
|
||||||
|
import { PluginComposerProvider } from "@getpaseo/plugin/client/host";
|
||||||
|
import { withUnistyles } from "react-native-unistyles";
|
||||||
|
import {
|
||||||
|
ComposerControlSurfaceProvider,
|
||||||
|
type ComposerControlSurface,
|
||||||
|
} from "@/composer/agent-controls/composer-control";
|
||||||
|
import { useComposerAgent, useComposerInput } from "@/composer/session";
|
||||||
|
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||||
|
import { useToast } from "@/contexts/toast-api-context";
|
||||||
|
import { useHosts } from "@/runtime/host-runtime";
|
||||||
|
import type { Theme } from "@/styles/theme";
|
||||||
|
import { createPluginClientStateSource } from "../client-state/source";
|
||||||
|
import { resolvePluginPlatform } from "../platform";
|
||||||
|
import { PluginEnvironmentProvider, type PluginEnvironment } from "../popover";
|
||||||
|
import { useInstalledPlugins } from "../registry";
|
||||||
|
import { SurfaceErrorBoundary } from "../surface-error-boundary";
|
||||||
|
import { toPluginTheme } from "../theme";
|
||||||
|
import type { InstalledPlugin } from "../types";
|
||||||
|
import { toPluginComposer } from "./model";
|
||||||
|
|
||||||
|
const pluginThemeMapping = (theme: Theme) => ({ theme: toPluginTheme(theme) });
|
||||||
|
|
||||||
|
function renderNothing() {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function useServerPlugins(serverId: string | null): InstalledPlugin[] {
|
||||||
|
const installed = useInstalledPlugins();
|
||||||
|
return useMemo(
|
||||||
|
() =>
|
||||||
|
serverId === null
|
||||||
|
? []
|
||||||
|
: installed.filter(
|
||||||
|
(plugin) => plugin.serverId === serverId && plugin.composerItems.length > 0,
|
||||||
|
),
|
||||||
|
[installed, serverId],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How many composer items the host's plugins registered; the toolbar budgets room for them. */
|
||||||
|
export function usePluginComposerItemCount(serverId: string | null): number {
|
||||||
|
const plugins = useServerPlugins(serverId);
|
||||||
|
return plugins.reduce((count, plugin) => count + plugin.composerItems.length, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The host's plugin composer items. They read and command the composer they are mounted in, so
|
||||||
|
* they render only where a composer provides its input and agent.
|
||||||
|
*/
|
||||||
|
export function PluginComposerItems({
|
||||||
|
serverId,
|
||||||
|
surface,
|
||||||
|
}: {
|
||||||
|
serverId: string | null;
|
||||||
|
surface: ComposerControlSurface;
|
||||||
|
}) {
|
||||||
|
const plugins = useServerPlugins(serverId);
|
||||||
|
if (serverId === null || plugins.length === 0) return null;
|
||||||
|
return (
|
||||||
|
<ComposerControlSurfaceProvider value={surface}>
|
||||||
|
{plugins.map((plugin) => (
|
||||||
|
<ThemedPluginComposerItems key={plugin.id} plugin={plugin} uniProps={pluginThemeMapping} />
|
||||||
|
))}
|
||||||
|
</ComposerControlSurfaceProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PluginComposerItemsHost({
|
||||||
|
plugin,
|
||||||
|
theme,
|
||||||
|
}: {
|
||||||
|
plugin: InstalledPlugin;
|
||||||
|
theme: PluginHostProps["theme"];
|
||||||
|
}) {
|
||||||
|
const agent = useComposerAgent();
|
||||||
|
const composerInput = useComposerInput();
|
||||||
|
const toast = useToast();
|
||||||
|
const compact = useIsCompactFormFactor();
|
||||||
|
const hosts = useHosts();
|
||||||
|
const hostLabel =
|
||||||
|
hosts.find((host) => host.serverId === plugin.serverId)?.label ?? plugin.serverId;
|
||||||
|
const textSource = composerInput?.textSource;
|
||||||
|
const prompt = useSyncExternalStore(
|
||||||
|
textSource?.subscribe ?? subscribeNothing,
|
||||||
|
textSource?.getSnapshot ?? emptyText,
|
||||||
|
textSource?.getSnapshot ?? emptyText,
|
||||||
|
);
|
||||||
|
const environment = useMemo<PluginEnvironment>(
|
||||||
|
() => ({
|
||||||
|
installation: plugin,
|
||||||
|
toast,
|
||||||
|
state: createPluginClientStateSource(plugin.serverId),
|
||||||
|
}),
|
||||||
|
[plugin, toast],
|
||||||
|
);
|
||||||
|
const composer = useMemo(
|
||||||
|
() =>
|
||||||
|
agent && composerInput ? toPluginComposer({ plugin, agent, composerInput, prompt }) : null,
|
||||||
|
[agent, composerInput, plugin, prompt],
|
||||||
|
);
|
||||||
|
const props = useMemo<PluginHostProps>(
|
||||||
|
() => ({
|
||||||
|
theme,
|
||||||
|
host: { id: plugin.serverId, label: hostLabel },
|
||||||
|
layout: { compact, platform: resolvePluginPlatform() },
|
||||||
|
}),
|
||||||
|
[compact, hostLabel, plugin.serverId, theme],
|
||||||
|
);
|
||||||
|
if (!composer) return null;
|
||||||
|
return (
|
||||||
|
<PluginEnvironmentProvider environment={environment}>
|
||||||
|
<PluginComposerProvider composer={composer}>
|
||||||
|
{plugin.composerItems.map(({ id, Component }) => (
|
||||||
|
<SurfaceErrorBoundary
|
||||||
|
key={id}
|
||||||
|
installation={plugin}
|
||||||
|
Surface={Component}
|
||||||
|
renderError={renderNothing}
|
||||||
|
>
|
||||||
|
<Component {...props} />
|
||||||
|
</SurfaceErrorBoundary>
|
||||||
|
))}
|
||||||
|
</PluginComposerProvider>
|
||||||
|
</PluginEnvironmentProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ThemedPluginComposerItems = withUnistyles(PluginComposerItemsHost);
|
||||||
|
|
||||||
|
function subscribeNothing() {
|
||||||
|
return () => undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function emptyText() {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,314 @@
|
|||||||
|
import { defineRpc } from "@getpaseo/plugin";
|
||||||
|
import { PluginTranslationRuntime } from "@getpaseo/plugin/client/host";
|
||||||
|
import { QueryClient } from "@tanstack/react-query";
|
||||||
|
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import type { UserComposerAttachment } from "@/attachments/types";
|
||||||
|
import type { ComposerAgent, ComposerInput } from "@/composer/session";
|
||||||
|
import type { InstalledPlugin } from "../types";
|
||||||
|
import { toPluginComposer } from "./model";
|
||||||
|
|
||||||
|
function installed(): InstalledPlugin {
|
||||||
|
return {
|
||||||
|
id: "review",
|
||||||
|
serverId: "host-1",
|
||||||
|
clientBundle: "bundle",
|
||||||
|
lifetime: new AbortController(),
|
||||||
|
locale: "en",
|
||||||
|
i18n: new PluginTranslationRuntime({ getLocale: () => "en", subscribe: () => () => {} }),
|
||||||
|
queryClient: new QueryClient(),
|
||||||
|
paseo: {} as InstalledPlugin["paseo"],
|
||||||
|
invoke: async () => undefined,
|
||||||
|
subscribe: () => {
|
||||||
|
throw new Error("Subscriptions are not used here");
|
||||||
|
},
|
||||||
|
cleanup: () => {},
|
||||||
|
settingsScreens: [],
|
||||||
|
surfaces: [],
|
||||||
|
sidebarItems: { header: [], footer: [] },
|
||||||
|
legacySidebarItems: [],
|
||||||
|
filePanels: [],
|
||||||
|
composerItems: [],
|
||||||
|
workspacePanels: [],
|
||||||
|
commandCenterItems: [],
|
||||||
|
clientSlashCommands: [],
|
||||||
|
attachmentSources: [
|
||||||
|
{
|
||||||
|
id: "issues",
|
||||||
|
title: "Issues",
|
||||||
|
pickerTitle: "Issues",
|
||||||
|
searchPlaceholder: "Search issues",
|
||||||
|
icon: "Bug",
|
||||||
|
search: defineRpc({
|
||||||
|
name: "issues.search",
|
||||||
|
input: z.object({}),
|
||||||
|
output: z.array(z.object({})),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
themes: [],
|
||||||
|
timelineTransformers: [],
|
||||||
|
timelineRenderers: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const issue = {
|
||||||
|
id: "ISS-1",
|
||||||
|
identifier: "ISS-1",
|
||||||
|
title: "Fix it",
|
||||||
|
url: "https://example.com/ISS-1",
|
||||||
|
text: "Fix it",
|
||||||
|
resourceType: "issue",
|
||||||
|
};
|
||||||
|
|
||||||
|
function fakeAgent(context: ComposerAgent["context"], locked = false) {
|
||||||
|
const calls: string[] = [];
|
||||||
|
const agent: ComposerAgent = {
|
||||||
|
context,
|
||||||
|
locked,
|
||||||
|
isLocked: () => locked,
|
||||||
|
provider: "claude",
|
||||||
|
model: "sonnet",
|
||||||
|
mode: "default",
|
||||||
|
thinking: null,
|
||||||
|
options: { effort: "high" },
|
||||||
|
metadata: { flag: true },
|
||||||
|
// A running agent keeps its provider, as the real adapter does.
|
||||||
|
setProvider: async (provider) => {
|
||||||
|
if (context === "agent") throw new Error("A running agent cannot change provider.");
|
||||||
|
calls.push(`provider:${provider}`);
|
||||||
|
},
|
||||||
|
setModel: async (model) => void calls.push(`model:${model}`),
|
||||||
|
setMode: async (mode) => void calls.push(`mode:${mode}`),
|
||||||
|
setThinking: async (thinking) => void calls.push(`thinking:${thinking}`),
|
||||||
|
setOptions: async (patch) => void calls.push(`options:${JSON.stringify(patch)}`),
|
||||||
|
setMetadata: async (patch: Record<string, JsonValue>) =>
|
||||||
|
void calls.push(`metadata:${JSON.stringify(patch)}`),
|
||||||
|
};
|
||||||
|
return { agent, calls };
|
||||||
|
}
|
||||||
|
|
||||||
|
function fakeInput(initial: UserComposerAttachment[] = [], locked = false) {
|
||||||
|
const state = { text: "", attachments: initial };
|
||||||
|
const input: ComposerInput = {
|
||||||
|
locked,
|
||||||
|
isLocked: () => locked,
|
||||||
|
textSource: { getSnapshot: () => state.text, subscribe: () => () => {} },
|
||||||
|
setText: (text) => {
|
||||||
|
state.text = text;
|
||||||
|
},
|
||||||
|
insertText: (text) => {
|
||||||
|
state.text += text;
|
||||||
|
},
|
||||||
|
get attachments() {
|
||||||
|
return state.attachments;
|
||||||
|
},
|
||||||
|
changeAttachments: (updater) => {
|
||||||
|
state.attachments = updater(state.attachments);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return { input, state };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("toPluginComposer", () => {
|
||||||
|
it("reads the agent the composer configures and the context it sits in", () => {
|
||||||
|
const { agent } = fakeAgent("new-workspace");
|
||||||
|
const { input } = fakeInput();
|
||||||
|
const composer = toPluginComposer({
|
||||||
|
plugin: installed(),
|
||||||
|
agent,
|
||||||
|
composerInput: input,
|
||||||
|
prompt: "hello",
|
||||||
|
});
|
||||||
|
expect(composer.context).toBe("new-workspace");
|
||||||
|
expect(composer.prompt).toBe("hello");
|
||||||
|
expect(composer.agent).toEqual({
|
||||||
|
provider: "claude",
|
||||||
|
model: "sonnet",
|
||||||
|
mode: "default",
|
||||||
|
thinking: null,
|
||||||
|
options: { effort: "high" },
|
||||||
|
metadata: { flag: true },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["agent", "draft"] as const)(
|
||||||
|
"sends every command to the %s composer's agent",
|
||||||
|
async (context) => {
|
||||||
|
const { agent, calls } = fakeAgent(context);
|
||||||
|
const { input } = fakeInput();
|
||||||
|
const composer = toPluginComposer({
|
||||||
|
plugin: installed(),
|
||||||
|
agent,
|
||||||
|
composerInput: input,
|
||||||
|
prompt: "",
|
||||||
|
});
|
||||||
|
await composer.setModel("gpt");
|
||||||
|
await composer.setMode("plan");
|
||||||
|
await composer.setThinking("high");
|
||||||
|
await composer.setOptions({ effort: "low" });
|
||||||
|
await composer.setMetadata({ flag: null });
|
||||||
|
expect(calls).toEqual([
|
||||||
|
"model:gpt",
|
||||||
|
"mode:plan",
|
||||||
|
"thinking:high",
|
||||||
|
'options:{"effort":"low"}',
|
||||||
|
'metadata:{"flag":null}',
|
||||||
|
]);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it("lets a draft change provider and tells a running agent it cannot", async () => {
|
||||||
|
const { input } = fakeInput();
|
||||||
|
const draft = fakeAgent("draft");
|
||||||
|
await toPluginComposer({
|
||||||
|
plugin: installed(),
|
||||||
|
agent: draft.agent,
|
||||||
|
composerInput: input,
|
||||||
|
prompt: "",
|
||||||
|
}).setProvider("codex");
|
||||||
|
expect(draft.calls).toEqual(["provider:codex"]);
|
||||||
|
|
||||||
|
const running = fakeAgent("agent");
|
||||||
|
await expect(
|
||||||
|
toPluginComposer({
|
||||||
|
plugin: installed(),
|
||||||
|
agent: running.agent,
|
||||||
|
composerInput: input,
|
||||||
|
prompt: "",
|
||||||
|
}).setProvider("codex"),
|
||||||
|
).rejects.toThrow("A running agent cannot change provider.");
|
||||||
|
expect(running.calls).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("changes the prompt and inserts at the cursor", () => {
|
||||||
|
const { agent } = fakeAgent("draft");
|
||||||
|
const { input, state } = fakeInput();
|
||||||
|
const composer = toPluginComposer({
|
||||||
|
plugin: installed(),
|
||||||
|
agent,
|
||||||
|
composerInput: input,
|
||||||
|
prompt: "",
|
||||||
|
});
|
||||||
|
composer.setPrompt("a");
|
||||||
|
composer.insertText("b");
|
||||||
|
expect(state.text).toBe("ab");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refuses every prompt and agent command while the composer is locked", async () => {
|
||||||
|
const { agent, calls } = fakeAgent("new-workspace", true);
|
||||||
|
const { input, state } = fakeInput([], true);
|
||||||
|
const composer = toPluginComposer({
|
||||||
|
plugin: installed(),
|
||||||
|
agent,
|
||||||
|
composerInput: input,
|
||||||
|
prompt: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(() => composer.setPrompt("a")).toThrow("The composer is locked");
|
||||||
|
expect(() => composer.insertText("b")).toThrow("The composer is locked");
|
||||||
|
expect(() => composer.addAttachment({ sourceId: "issues", item: issue })).toThrow(
|
||||||
|
"The composer is locked",
|
||||||
|
);
|
||||||
|
await expect(composer.setProvider("codex")).rejects.toThrow("The composer is locked");
|
||||||
|
await expect(composer.setModel("gpt")).rejects.toThrow("The composer is locked");
|
||||||
|
await expect(composer.setMode("plan")).rejects.toThrow("The composer is locked");
|
||||||
|
await expect(composer.setThinking("high")).rejects.toThrow("The composer is locked");
|
||||||
|
await expect(composer.setOptions({ effort: "low" })).rejects.toThrow("The composer is locked");
|
||||||
|
await expect(composer.setMetadata({ flag: null })).rejects.toThrow("The composer is locked");
|
||||||
|
expect(state.text).toBe("");
|
||||||
|
expect(calls).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refuses a command a plugin kept from before the composer locked", async () => {
|
||||||
|
const { agent } = fakeAgent("new-workspace");
|
||||||
|
const { input } = fakeInput();
|
||||||
|
const composer = toPluginComposer({
|
||||||
|
plugin: installed(),
|
||||||
|
agent,
|
||||||
|
composerInput: input,
|
||||||
|
prompt: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
// The plugin's action was awaiting an RPC when the user submitted.
|
||||||
|
const lock = { locked: true };
|
||||||
|
agent.isLocked = () => lock.locked;
|
||||||
|
input.isLocked = () => lock.locked;
|
||||||
|
|
||||||
|
expect(() => composer.insertText("late")).toThrow("The composer is locked");
|
||||||
|
expect(() => composer.addAttachment({ sourceId: "issues", item: issue })).toThrow(
|
||||||
|
"The composer is locked",
|
||||||
|
);
|
||||||
|
expect(() => composer.removeAttachment({ sourceId: "issues", itemId: issue.id })).toThrow(
|
||||||
|
"The composer is locked",
|
||||||
|
);
|
||||||
|
await expect(composer.setOptions({ effort: "low" })).rejects.toThrow("The composer is locked");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hands out options and metadata a plugin cannot change", () => {
|
||||||
|
const { agent } = fakeAgent("draft");
|
||||||
|
agent.metadata = { nested: { list: [1] } };
|
||||||
|
const { input } = fakeInput();
|
||||||
|
const composer = toPluginComposer({
|
||||||
|
plugin: installed(),
|
||||||
|
agent,
|
||||||
|
composerInput: input,
|
||||||
|
prompt: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(Object.isFrozen(composer.agent.options)).toBe(true);
|
||||||
|
expect(Object.isFrozen(composer.agent.metadata)).toBe(true);
|
||||||
|
expect(Object.isFrozen((composer.agent.metadata as { nested: object }).nested)).toBe(true);
|
||||||
|
expect(agent.metadata).toEqual({ nested: { list: [1] } });
|
||||||
|
expect(Object.isFrozen(agent.metadata)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("adds and removes the plugin's own attachments only", () => {
|
||||||
|
const { agent } = fakeAgent("agent");
|
||||||
|
const other: UserComposerAttachment = {
|
||||||
|
kind: "plugin_resource",
|
||||||
|
pluginId: "other",
|
||||||
|
sourceId: "issues",
|
||||||
|
sourceTitle: "Issues",
|
||||||
|
sourceIcon: "Bug",
|
||||||
|
item: issue,
|
||||||
|
};
|
||||||
|
const { input, state } = fakeInput([other]);
|
||||||
|
const composer = toPluginComposer({
|
||||||
|
plugin: installed(),
|
||||||
|
agent,
|
||||||
|
composerInput: input,
|
||||||
|
prompt: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
composer.addAttachment({ sourceId: "issues", item: issue });
|
||||||
|
composer.addAttachment({ sourceId: "issues", item: issue });
|
||||||
|
expect(state.attachments).toHaveLength(2);
|
||||||
|
|
||||||
|
const next = toPluginComposer({
|
||||||
|
plugin: installed(),
|
||||||
|
agent,
|
||||||
|
composerInput: input,
|
||||||
|
prompt: "",
|
||||||
|
});
|
||||||
|
expect(next.attachments).toEqual([{ sourceId: "issues", item: issue }]);
|
||||||
|
|
||||||
|
composer.removeAttachment({ sourceId: "issues", itemId: "ISS-1" });
|
||||||
|
expect(state.attachments).toEqual([other]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects an attachment from a source the plugin did not register", () => {
|
||||||
|
const { agent } = fakeAgent("agent");
|
||||||
|
const { input } = fakeInput();
|
||||||
|
const composer = toPluginComposer({
|
||||||
|
plugin: installed(),
|
||||||
|
agent,
|
||||||
|
composerInput: input,
|
||||||
|
prompt: "",
|
||||||
|
});
|
||||||
|
expect(() => composer.addAttachment({ sourceId: "nope", item: issue })).toThrow(
|
||||||
|
"Unknown attachment source: nope",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||||
|
import type { PluginComposer } from "@getpaseo/plugin/client";
|
||||||
|
import type { UserComposerAttachment } from "@/attachments/types";
|
||||||
|
import type { ComposerAgent, ComposerInput } from "@/composer/session";
|
||||||
|
import type { InstalledPlugin } from "../types";
|
||||||
|
import { createPluginResourceAttachment } from "../attachments/model";
|
||||||
|
import { cloneAndFreeze } from "../freeze";
|
||||||
|
|
||||||
|
function isPluginAttachment(
|
||||||
|
attachment: UserComposerAttachment,
|
||||||
|
pluginId: string,
|
||||||
|
sourceId: string,
|
||||||
|
itemId?: string,
|
||||||
|
): boolean {
|
||||||
|
return (
|
||||||
|
attachment.kind === "plugin_resource" &&
|
||||||
|
attachment.pluginId === pluginId &&
|
||||||
|
attachment.sourceId === sourceId &&
|
||||||
|
(itemId === undefined || attachment.item.id === itemId)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const LOCKED_MESSAGE = "The composer is locked while the agent is being created.";
|
||||||
|
|
||||||
|
function assertUnlocked(isLocked: () => boolean): void {
|
||||||
|
if (isLocked()) throw new Error(LOCKED_MESSAGE);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function whenUnlocked(agent: ComposerAgent, command: () => Promise<void>): Promise<void> {
|
||||||
|
assertUnlocked(agent.isLocked);
|
||||||
|
await command();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a plugin sees of the composer it sits in. `agent` and `input` are the composer's own
|
||||||
|
* halves, so the plugin's commands reach the same models the built-in controls use.
|
||||||
|
*/
|
||||||
|
export function toPluginComposer(input: {
|
||||||
|
plugin: InstalledPlugin;
|
||||||
|
agent: ComposerAgent;
|
||||||
|
composerInput: ComposerInput;
|
||||||
|
prompt: string;
|
||||||
|
}): PluginComposer {
|
||||||
|
const { plugin, agent, composerInput, prompt } = input;
|
||||||
|
return {
|
||||||
|
context: agent.context,
|
||||||
|
prompt,
|
||||||
|
attachments: composerInput.attachments.flatMap((attachment) =>
|
||||||
|
attachment.kind === "plugin_resource" && attachment.pluginId === plugin.id
|
||||||
|
? [{ sourceId: attachment.sourceId, item: attachment.item }]
|
||||||
|
: [],
|
||||||
|
),
|
||||||
|
// Provider options are JSON on the wire.
|
||||||
|
agent: {
|
||||||
|
provider: agent.provider,
|
||||||
|
model: agent.model,
|
||||||
|
mode: agent.mode,
|
||||||
|
thinking: agent.thinking,
|
||||||
|
options: cloneAndFreeze(agent.options as Record<string, JsonValue>),
|
||||||
|
metadata: cloneAndFreeze(agent.metadata),
|
||||||
|
},
|
||||||
|
setPrompt: (text) => {
|
||||||
|
assertUnlocked(composerInput.isLocked);
|
||||||
|
composerInput.setText(text);
|
||||||
|
},
|
||||||
|
insertText: (text) => {
|
||||||
|
assertUnlocked(composerInput.isLocked);
|
||||||
|
composerInput.insertText(text);
|
||||||
|
},
|
||||||
|
addAttachment({ sourceId, item }) {
|
||||||
|
assertUnlocked(composerInput.isLocked);
|
||||||
|
const source = plugin.attachmentSources.find((candidate) => candidate.id === sourceId);
|
||||||
|
if (!source) throw new Error(`Unknown attachment source: ${sourceId}`);
|
||||||
|
const attachment = createPluginResourceAttachment(
|
||||||
|
{
|
||||||
|
pluginId: plugin.id,
|
||||||
|
sourceId,
|
||||||
|
sourceTitle: plugin.i18n.resolve(source.title, plugin.locale),
|
||||||
|
sourceIcon: source.icon,
|
||||||
|
},
|
||||||
|
item,
|
||||||
|
);
|
||||||
|
composerInput.changeAttachments((current) =>
|
||||||
|
current.some((candidate) => isPluginAttachment(candidate, plugin.id, sourceId, item.id))
|
||||||
|
? current
|
||||||
|
: [...current, attachment],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
removeAttachment({ sourceId, itemId }) {
|
||||||
|
assertUnlocked(composerInput.isLocked);
|
||||||
|
composerInput.changeAttachments((current) =>
|
||||||
|
current.filter((candidate) => !isPluginAttachment(candidate, plugin.id, sourceId, itemId)),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
setProvider: (provider) => whenUnlocked(agent, () => agent.setProvider(provider)),
|
||||||
|
setModel: (modelId) => whenUnlocked(agent, () => agent.setModel(modelId)),
|
||||||
|
setMode: (modeId) => whenUnlocked(agent, () => agent.setMode(modeId)),
|
||||||
|
setThinking: (thinkingOptionId) =>
|
||||||
|
whenUnlocked(agent, () => agent.setThinking(thinkingOptionId)),
|
||||||
|
setOptions: (patch) => whenUnlocked(agent, () => agent.setOptions(patch)),
|
||||||
|
setMetadata: (patch) => whenUnlocked(agent, () => agent.setMetadata(patch)),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -531,6 +531,38 @@ describe("evaluatePluginClientBundle", () => {
|
|||||||
).toThrow("Duplicate Command Center item: review");
|
).toThrow("Duplicate Command Center item: review");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("collects composer items and releases an id on removal", () => {
|
||||||
|
const plugin = evaluatePluginClientBundle(
|
||||||
|
"review",
|
||||||
|
bundle(`
|
||||||
|
function Item() { return null; }
|
||||||
|
const remove = plugin.addComposerItem({ id: "flag", Component: Item });
|
||||||
|
remove();
|
||||||
|
plugin.addComposerItem({ id: "flag", Component: Item });
|
||||||
|
`),
|
||||||
|
);
|
||||||
|
expect(plugin.composerItems.map((item) => item.id)).toEqual(["flag"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects duplicate and non-component composer items", () => {
|
||||||
|
expect(() =>
|
||||||
|
evaluatePluginClientBundle(
|
||||||
|
"review",
|
||||||
|
bundle(`
|
||||||
|
function Item() { return null; }
|
||||||
|
plugin.addComposerItem({ id: "flag", Component: Item });
|
||||||
|
plugin.addComposerItem({ id: "flag", Component: Item });
|
||||||
|
`),
|
||||||
|
),
|
||||||
|
).toThrow("Duplicate composer item: flag");
|
||||||
|
expect(() =>
|
||||||
|
evaluatePluginClientBundle(
|
||||||
|
"review",
|
||||||
|
bundle(`plugin.addComposerItem({ id: "flag", Component: "nope" })`),
|
||||||
|
),
|
||||||
|
).toThrow("Composer item flag is not a component");
|
||||||
|
});
|
||||||
|
|
||||||
it("runs the client entry with the full runtime context", () => {
|
it("runs the client entry with the full runtime context", () => {
|
||||||
const plugin = evaluatePluginClientBundle(
|
const plugin = evaluatePluginClientBundle(
|
||||||
"review",
|
"review",
|
||||||
|
|||||||
@@ -132,6 +132,7 @@ export function runPluginClientBundle(
|
|||||||
sidebarItems: { header: [], footer: [] },
|
sidebarItems: { header: [], footer: [] },
|
||||||
legacySidebarItems: [],
|
legacySidebarItems: [],
|
||||||
filePanels: [],
|
filePanels: [],
|
||||||
|
composerItems: [],
|
||||||
workspacePanels: [],
|
workspacePanels: [],
|
||||||
commandCenterItems: [],
|
commandCenterItems: [],
|
||||||
clientSlashCommands: [],
|
clientSlashCommands: [],
|
||||||
@@ -147,6 +148,7 @@ export function runPluginClientBundle(
|
|||||||
footer: new Set(),
|
footer: new Set(),
|
||||||
};
|
};
|
||||||
const filePanelIds = new Set<string>();
|
const filePanelIds = new Set<string>();
|
||||||
|
const composerItemIds = new Set<string>();
|
||||||
const workspacePanelIds = new Set<string>();
|
const workspacePanelIds = new Set<string>();
|
||||||
const commandCenterItemIds = new Set<string>();
|
const commandCenterItemIds = new Set<string>();
|
||||||
const clientSlashCommandNames = new Set<string>();
|
const clientSlashCommandNames = new Set<string>();
|
||||||
@@ -270,6 +272,20 @@ export function runPluginClientBundle(
|
|||||||
() => surfaceIds.delete(normalizedId),
|
() => surfaceIds.delete(normalizedId),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
addComposerItem(contribution) {
|
||||||
|
const normalizedId = requireId(contribution.id, "composer item id");
|
||||||
|
if (composerItemIds.has(normalizedId))
|
||||||
|
throw new Error(`Duplicate composer item: ${normalizedId}`);
|
||||||
|
if (!isComponentType(contribution.Component)) {
|
||||||
|
throw new Error(`Composer item ${normalizedId} is not a component`);
|
||||||
|
}
|
||||||
|
composerItemIds.add(normalizedId);
|
||||||
|
return register(
|
||||||
|
collector.composerItems,
|
||||||
|
{ id: normalizedId, Component: contribution.Component },
|
||||||
|
() => composerItemIds.delete(normalizedId),
|
||||||
|
);
|
||||||
|
},
|
||||||
addSidebarHeaderItem(contribution: PluginSidebarItemContribution) {
|
addSidebarHeaderItem(contribution: PluginSidebarItemContribution) {
|
||||||
return addSidebarItem("header", contribution);
|
return addSidebarItem("header", contribution);
|
||||||
},
|
},
|
||||||
@@ -586,6 +602,7 @@ export function runPluginClientBundle(
|
|||||||
sidebarItems: collector.sidebarItems,
|
sidebarItems: collector.sidebarItems,
|
||||||
legacySidebarItems: collector.legacySidebarItems,
|
legacySidebarItems: collector.legacySidebarItems,
|
||||||
filePanels: collector.filePanels,
|
filePanels: collector.filePanels,
|
||||||
|
composerItems: collector.composerItems,
|
||||||
workspacePanels: collector.workspacePanels as EvaluatedPlugin["workspacePanels"],
|
workspacePanels: collector.workspacePanels as EvaluatedPlugin["workspacePanels"],
|
||||||
commandCenterItems: collector.commandCenterItems,
|
commandCenterItems: collector.commandCenterItems,
|
||||||
clientSlashCommands: collector.clientSlashCommands,
|
clientSlashCommands: collector.clientSlashCommands,
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
/** A deep copy no plugin can change. Plugins read data through it, never the host's own objects. */
|
||||||
|
export function cloneAndFreeze<T>(value: T): T {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return Object.freeze(value.map((entry) => cloneAndFreeze(entry))) as T;
|
||||||
|
}
|
||||||
|
if (value !== null && typeof value === "object") {
|
||||||
|
return Object.freeze(
|
||||||
|
Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, cloneAndFreeze(entry)])),
|
||||||
|
) as T;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
@@ -25,6 +25,11 @@ function findLucideIcon(name: string): LucideIcon | null {
|
|||||||
return isComponent(candidate) ? (candidate as LucideIcon) : null;
|
return isComponent(candidate) ? (candidate as LucideIcon) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Whether `name` is a Lucide icon, so a caller can fall back before drawing nothing. */
|
||||||
|
export function isLucideIconName(name: string): boolean {
|
||||||
|
return findLucideIcon(name) !== null;
|
||||||
|
}
|
||||||
|
|
||||||
function isComponent(value: unknown): boolean {
|
function isComponent(value: unknown): boolean {
|
||||||
return (
|
return (
|
||||||
typeof value === "function" ||
|
typeof value === "function" ||
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ function installation(invoked: string[]): InstalledPlugin {
|
|||||||
sidebarItems: { header: [], footer: [] },
|
sidebarItems: { header: [], footer: [] },
|
||||||
legacySidebarItems: [],
|
legacySidebarItems: [],
|
||||||
filePanels: [],
|
filePanels: [],
|
||||||
|
composerItems: [],
|
||||||
workspacePanels: [],
|
workspacePanels: [],
|
||||||
commandCenterItems: [],
|
commandCenterItems: [],
|
||||||
clientSlashCommands: [],
|
clientSlashCommands: [],
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import type { ActionProps, SelectProps, ToggleProps } from "@getpaseo/plugin/client/ui";
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import {
|
||||||
|
ComposerControl,
|
||||||
|
useComposerControlSurface,
|
||||||
|
type ComposerControlItem,
|
||||||
|
} from "@/composer/agent-controls/composer-control";
|
||||||
|
import { useComposerLocked } from "@/composer/session";
|
||||||
|
import { parsePluginIcon, pluginIconComponent } from "../icons";
|
||||||
|
|
||||||
|
/** Icons resolve at render, so an invalid one throws to the item's boundary. */
|
||||||
|
function usePluginControlIcon(icon: ToggleProps["icon"]) {
|
||||||
|
return useMemo(() => pluginIconComponent(parsePluginIcon("Composer control", icon)), [icon]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Draws one plugin control where its composer item sits: inline, or as a row in the sheet. */
|
||||||
|
function PluginComposerControl({
|
||||||
|
item,
|
||||||
|
disabled,
|
||||||
|
}: {
|
||||||
|
item: ComposerControlItem;
|
||||||
|
disabled: boolean | undefined;
|
||||||
|
}) {
|
||||||
|
const surface = useComposerControlSurface();
|
||||||
|
const locked = useComposerLocked();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
return (
|
||||||
|
<ComposerControl
|
||||||
|
item={item}
|
||||||
|
surface={surface}
|
||||||
|
disabled={disabled || locked}
|
||||||
|
open={open}
|
||||||
|
onOpenChange={setOpen}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Toggle({ title, icon, disabled, value, onValueChange }: ToggleProps) {
|
||||||
|
const Icon = usePluginControlIcon(icon);
|
||||||
|
const item = useMemo<ComposerControlItem>(
|
||||||
|
() => ({
|
||||||
|
id: "plugin-toggle",
|
||||||
|
type: "toggle",
|
||||||
|
title,
|
||||||
|
icon: Icon,
|
||||||
|
highlight: value ? "blue" : undefined,
|
||||||
|
value,
|
||||||
|
onChange: (next) => onValueChange({ value: next }),
|
||||||
|
}),
|
||||||
|
[Icon, onValueChange, title, value],
|
||||||
|
);
|
||||||
|
return <PluginComposerControl item={item} disabled={disabled} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Select<Value extends string>({
|
||||||
|
title,
|
||||||
|
icon,
|
||||||
|
disabled,
|
||||||
|
value,
|
||||||
|
options,
|
||||||
|
onValueChange,
|
||||||
|
}: SelectProps<Value>) {
|
||||||
|
const Icon = usePluginControlIcon(icon);
|
||||||
|
const item = useMemo<ComposerControlItem>(
|
||||||
|
() => ({
|
||||||
|
id: "plugin-select",
|
||||||
|
type: "select",
|
||||||
|
title,
|
||||||
|
icon: Icon,
|
||||||
|
value,
|
||||||
|
choices: options,
|
||||||
|
onChange: (next) => onValueChange({ value: next as Value }),
|
||||||
|
showCaret: true,
|
||||||
|
}),
|
||||||
|
[Icon, onValueChange, options, title, value],
|
||||||
|
);
|
||||||
|
return <PluginComposerControl item={item} disabled={disabled} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Action({ title, icon, disabled, onPress }: ActionProps) {
|
||||||
|
const Icon = usePluginControlIcon(icon);
|
||||||
|
const item = useMemo<ComposerControlItem>(
|
||||||
|
() => ({ id: "plugin-action", type: "action", title, icon: Icon, onPress: () => onPress({}) }),
|
||||||
|
[Icon, onPress, title],
|
||||||
|
);
|
||||||
|
return <PluginComposerControl item={item} disabled={disabled} />;
|
||||||
|
}
|
||||||
@@ -20,6 +20,7 @@ export { FilePanelLoading as Loading } from "@/file-panels/loading";
|
|||||||
export { SettingsGroup } from "@/components/settings";
|
export { SettingsGroup } from "@/components/settings";
|
||||||
|
|
||||||
export { Icon } from "../icons";
|
export { Icon } from "../icons";
|
||||||
|
export { Action, Select, Toggle } from "./composer-controls";
|
||||||
export { Modal } from "./modal";
|
export { Modal } from "./modal";
|
||||||
export { ScrollView, FlatList } from "./scroll-view";
|
export { ScrollView, FlatList } from "./scroll-view";
|
||||||
export { TextInput } from "./text-input";
|
export { TextInput } from "./text-input";
|
||||||
|
|||||||
@@ -125,6 +125,7 @@ export class PluginRegistry {
|
|||||||
sidebarItems: { header: [], footer: [] },
|
sidebarItems: { header: [], footer: [] },
|
||||||
legacySidebarItems: [],
|
legacySidebarItems: [],
|
||||||
filePanels: [],
|
filePanels: [],
|
||||||
|
composerItems: [],
|
||||||
workspacePanels: [],
|
workspacePanels: [],
|
||||||
commandCenterItems: [],
|
commandCenterItems: [],
|
||||||
clientSlashCommands: [],
|
clientSlashCommands: [],
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ function installed(
|
|||||||
},
|
},
|
||||||
legacySidebarItems,
|
legacySidebarItems,
|
||||||
filePanels: [],
|
filePanels: [],
|
||||||
|
composerItems: [],
|
||||||
workspacePanels: [],
|
workspacePanels: [],
|
||||||
commandCenterItems: [],
|
commandCenterItems: [],
|
||||||
clientSlashCommands: [],
|
clientSlashCommands: [],
|
||||||
|
|||||||
@@ -56,6 +56,7 @@ function installation(
|
|||||||
icon: "Blocks",
|
icon: "Blocks",
|
||||||
})),
|
})),
|
||||||
filePanels: [],
|
filePanels: [],
|
||||||
|
composerItems: [],
|
||||||
workspacePanels: [],
|
workspacePanels: [],
|
||||||
commandCenterItems: [],
|
commandCenterItems: [],
|
||||||
clientSlashCommands: [],
|
clientSlashCommands: [],
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ function installed(serverId: string, themes: PluginThemeContribution[]): Install
|
|||||||
sidebarItems: { header: [], footer: [] },
|
sidebarItems: { header: [], footer: [] },
|
||||||
legacySidebarItems: [],
|
legacySidebarItems: [],
|
||||||
filePanels: [],
|
filePanels: [],
|
||||||
|
composerItems: [],
|
||||||
workspacePanels: [],
|
workspacePanels: [],
|
||||||
commandCenterItems: [],
|
commandCenterItems: [],
|
||||||
clientSlashCommands: [],
|
clientSlashCommands: [],
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ function plugin(input: {
|
|||||||
sidebarItems: { header: [], footer: [] },
|
sidebarItems: { header: [], footer: [] },
|
||||||
legacySidebarItems: [],
|
legacySidebarItems: [],
|
||||||
filePanels: [],
|
filePanels: [],
|
||||||
|
composerItems: [],
|
||||||
workspacePanels: [],
|
workspacePanels: [],
|
||||||
commandCenterItems: [],
|
commandCenterItems: [],
|
||||||
clientSlashCommands: [],
|
clientSlashCommands: [],
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { AgentTimelineItem, ToolCallTimelineItem } from "@getpaseo/protocol/agent-types";
|
import type { AgentTimelineItem, ToolCallTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||||
import type { AgentToolCallData, PluginTimelineStreamItem, StreamItem } from "@/types/stream";
|
import type { AgentToolCallData, PluginTimelineStreamItem, StreamItem } from "@/types/stream";
|
||||||
|
import { cloneAndFreeze } from "../freeze";
|
||||||
import type { TimelineItemTransform } from "./model";
|
import type { TimelineItemTransform } from "./model";
|
||||||
|
|
||||||
type AssistantPhase = "streaming" | "complete";
|
type AssistantPhase = "streaming" | "complete";
|
||||||
@@ -9,18 +10,6 @@ const projectionCache = new WeakMap<
|
|||||||
WeakMap<StreamItem, Partial<Record<AssistantPhase, StreamItem[]>>>
|
WeakMap<StreamItem, Partial<Record<AssistantPhase, StreamItem[]>>>
|
||||||
>();
|
>();
|
||||||
|
|
||||||
function cloneAndFreeze<T>(value: T): T {
|
|
||||||
if (Array.isArray(value)) {
|
|
||||||
return Object.freeze(value.map((entry) => cloneAndFreeze(entry))) as T;
|
|
||||||
}
|
|
||||||
if (value !== null && typeof value === "object") {
|
|
||||||
return Object.freeze(
|
|
||||||
Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, cloneAndFreeze(entry)])),
|
|
||||||
) as T;
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function sourceToolCallTimelineItem(data: AgentToolCallData): ToolCallTimelineItem {
|
function sourceToolCallTimelineItem(data: AgentToolCallData): ToolCallTimelineItem {
|
||||||
const { callId, name, status, error, detail, metadata, agentMessage } = data;
|
const { callId, name, status, error, detail, metadata, agentMessage } = data;
|
||||||
const base = {
|
const base = {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import type {
|
|||||||
PluginFilePanelContribution as SDKPluginFilePanelContribution,
|
PluginFilePanelContribution as SDKPluginFilePanelContribution,
|
||||||
PluginCommandCenterItemContribution as SDKPluginCommandCenterItemContribution,
|
PluginCommandCenterItemContribution as SDKPluginCommandCenterItemContribution,
|
||||||
PluginClientSlashCommandContribution as SDKPluginClientSlashCommandContribution,
|
PluginClientSlashCommandContribution as SDKPluginClientSlashCommandContribution,
|
||||||
|
PluginComposerItemContribution,
|
||||||
PluginComposerPillContribution as SDKPluginComposerPillContribution,
|
PluginComposerPillContribution as SDKPluginComposerPillContribution,
|
||||||
PluginSidebarContribution as SDKPluginSidebarContribution,
|
PluginSidebarContribution as SDKPluginSidebarContribution,
|
||||||
PluginSidebarItemContribution as SDKPluginSidebarItemContribution,
|
PluginSidebarItemContribution as SDKPluginSidebarItemContribution,
|
||||||
@@ -53,6 +54,7 @@ export interface EvaluatedPlugin {
|
|||||||
/** `addSidebarItem` registrations, so `/plugin/<id>/sidebar/<item>` routes keep resolving. */
|
/** `addSidebarItem` registrations, so `/plugin/<id>/sidebar/<item>` routes keep resolving. */
|
||||||
legacySidebarItems: PluginSidebarContribution[];
|
legacySidebarItems: PluginSidebarContribution[];
|
||||||
filePanels: PluginFilePanelContribution[];
|
filePanels: PluginFilePanelContribution[];
|
||||||
|
composerItems: PluginComposerItemContribution[];
|
||||||
workspacePanels: EvaluatedPluginWorkspacePanelContribution[];
|
workspacePanels: EvaluatedPluginWorkspacePanelContribution[];
|
||||||
commandCenterItems: PluginCommandCenterItemContribution[];
|
commandCenterItems: PluginCommandCenterItemContribution[];
|
||||||
clientSlashCommands: PluginClientSlashCommandContribution[];
|
clientSlashCommands: PluginClientSlashCommandContribution[];
|
||||||
@@ -84,6 +86,7 @@ export type {
|
|||||||
PluginAttachmentSourceContribution,
|
PluginAttachmentSourceContribution,
|
||||||
PluginCommandCenterItemContribution,
|
PluginCommandCenterItemContribution,
|
||||||
PluginClientSlashCommandContribution,
|
PluginClientSlashCommandContribution,
|
||||||
|
PluginComposerItemContribution,
|
||||||
PluginComposerPillContribution,
|
PluginComposerPillContribution,
|
||||||
PluginSidebarContribution,
|
PluginSidebarContribution,
|
||||||
PluginSidebarItemContribution,
|
PluginSidebarItemContribution,
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ function installed(): InstalledPlugin {
|
|||||||
sidebarItems: { header: [], footer: [] },
|
sidebarItems: { header: [], footer: [] },
|
||||||
legacySidebarItems: [],
|
legacySidebarItems: [],
|
||||||
filePanels: [],
|
filePanels: [],
|
||||||
|
composerItems: [],
|
||||||
workspacePanels: [
|
workspacePanels: [
|
||||||
{
|
{
|
||||||
id: "details",
|
id: "details",
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import type { AgentProviderDefinition } from "@getpaseo/protocol/provider-manifest";
|
||||||
|
import type { AgentModelDefinition, AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||||
|
import type { FormPreferences } from "@/hooks/use-form-preferences";
|
||||||
|
import {
|
||||||
|
INITIAL_AGENT_FORM_RESOLUTION,
|
||||||
|
INITIAL_USER_MODIFIED,
|
||||||
|
isUnlistedModel,
|
||||||
|
resolveAgentForm,
|
||||||
|
type AgentFormAction,
|
||||||
|
type AgentFormReducerState,
|
||||||
|
} from "@/provider-selection/resolve-agent-form";
|
||||||
|
|
||||||
|
/** What the host offers right now. The store reads it when a command runs, never earlier. */
|
||||||
|
export interface AgentFormCatalog {
|
||||||
|
/** The providers the host can run. */
|
||||||
|
selectableProviders: ReadonlyMap<AgentProvider, AgentProviderDefinition>;
|
||||||
|
/** Each provider's selectable models; empty when the host has listed none. */
|
||||||
|
models: ReadonlyMap<string, AgentModelDefinition[]>;
|
||||||
|
providerPreferences: (
|
||||||
|
provider: AgentProvider,
|
||||||
|
) => NonNullable<FormPreferences["providerPreferences"]>[AgentProvider] | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The draft form as a plain model: `resolveAgentForm` applied synchronously. A command reads
|
||||||
|
* `getState()` and the catalog when it runs, so the one after `await setProvider(...)` sees the
|
||||||
|
* new provider instead of the render that created it.
|
||||||
|
*/
|
||||||
|
export interface AgentFormStore {
|
||||||
|
getState: () => AgentFormReducerState;
|
||||||
|
dispatch: (action: AgentFormAction) => void;
|
||||||
|
subscribe: (listener: () => void) => () => void;
|
||||||
|
/** `false` when the provider is unknown or not ready; the form is left as it was. */
|
||||||
|
setProviderAndModel: (provider: AgentProvider, modelId: string) => boolean;
|
||||||
|
/**
|
||||||
|
* `false` when the provider's catalog is loaded and does not list the model. A catalog that has
|
||||||
|
* not arrived keeps the id as given.
|
||||||
|
*/
|
||||||
|
setModel: (modelId: string) => boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function openAgentForm(catalog: () => AgentFormCatalog): AgentFormStore {
|
||||||
|
let state: AgentFormReducerState = {
|
||||||
|
form: { provider: null, modeId: "", model: "", thinkingOptionId: "" },
|
||||||
|
userModified: INITIAL_USER_MODIFIED,
|
||||||
|
resolution: INITIAL_AGENT_FORM_RESOLUTION,
|
||||||
|
};
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
function dispatch(action: AgentFormAction): void {
|
||||||
|
const next = resolveAgentForm(state, action);
|
||||||
|
if (next === state) return;
|
||||||
|
state = next;
|
||||||
|
for (const listener of listeners) listener();
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
getState: () => state,
|
||||||
|
dispatch,
|
||||||
|
setProviderAndModel: (provider, modelId) => {
|
||||||
|
const host = catalog();
|
||||||
|
const providerDef = host.selectableProviders.get(provider);
|
||||||
|
if (!providerDef) return false;
|
||||||
|
dispatch({
|
||||||
|
type: "SET_PROVIDER_AND_MODEL_FROM_USER",
|
||||||
|
provider,
|
||||||
|
modelId,
|
||||||
|
providerDef,
|
||||||
|
providerModels: host.models.get(provider) ?? null,
|
||||||
|
providerPrefs: host.providerPreferences(provider),
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
setModel: (modelId) => {
|
||||||
|
const { provider } = state.form;
|
||||||
|
const host = catalog();
|
||||||
|
const listed = provider ? host.models.get(provider) : undefined;
|
||||||
|
const models = listed?.length ? listed : null;
|
||||||
|
if (isUnlistedModel(models, modelId)) return false;
|
||||||
|
dispatch({
|
||||||
|
type: "SET_MODEL_FROM_USER",
|
||||||
|
modelId,
|
||||||
|
availableModels: models,
|
||||||
|
providerPrefs: provider ? host.providerPreferences(provider) : undefined,
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
subscribe: (listener) => {
|
||||||
|
listeners.add(listener);
|
||||||
|
return () => {
|
||||||
|
listeners.delete(listener);
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -312,7 +312,7 @@ export function buildDraftCommandTarget(input: {
|
|||||||
cwd: string;
|
cwd: string;
|
||||||
effectiveModelId: string;
|
effectiveModelId: string;
|
||||||
effectiveThinkingOptionId: string;
|
effectiveThinkingOptionId: string;
|
||||||
featureValues?: Record<string, unknown>;
|
providerOptions?: Record<string, unknown>;
|
||||||
}): DraftCommandTarget {
|
}): DraftCommandTarget {
|
||||||
const cwd = input.cwd.trim();
|
const cwd = input.cwd.trim();
|
||||||
if (!cwd) {
|
if (!cwd) {
|
||||||
@@ -332,7 +332,7 @@ export function buildDraftCommandTarget(input: {
|
|||||||
...(input.effectiveThinkingOptionId
|
...(input.effectiveThinkingOptionId
|
||||||
? { thinkingOptionId: input.effectiveThinkingOptionId }
|
? { thinkingOptionId: input.effectiveThinkingOptionId }
|
||||||
: {}),
|
: {}),
|
||||||
...(input.featureValues ? { featureValues: input.featureValues } : {}),
|
...(input.providerOptions ? { providerOptions: input.providerOptions } : {}),
|
||||||
};
|
};
|
||||||
return { status: "ready", config };
|
return { status: "ready", config };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
resolveAgentForm,
|
resolveAgentForm,
|
||||||
resolveFormState,
|
resolveFormState,
|
||||||
resolveEffectiveModel,
|
resolveEffectiveModel,
|
||||||
|
isUnlistedModel,
|
||||||
resolveThinkingOptionId,
|
resolveThinkingOptionId,
|
||||||
mergeSelectedComposerPreferences,
|
mergeSelectedComposerPreferences,
|
||||||
buildProviderDefinitionMap,
|
buildProviderDefinitionMap,
|
||||||
@@ -131,6 +132,19 @@ describe("resolveDefaultModel", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("isUnlistedModel", () => {
|
||||||
|
it("rejects an id the provider's catalog lacks, and accepts a listed id or alias", () => {
|
||||||
|
expect(isUnlistedModel(ALIASED_CODEX_MODELS, "not-in-the-catalog")).toBe(true);
|
||||||
|
expect(isUnlistedModel(ALIASED_CODEX_MODELS, "gpt-5.3-codex")).toBe(false);
|
||||||
|
expect(isUnlistedModel(ALIASED_CODEX_MODELS, "gpt-5.3-codex-legacy")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("accepts any id while the provider has listed no models", () => {
|
||||||
|
expect(isUnlistedModel(null, "anything")).toBe(false);
|
||||||
|
expect(isUnlistedModel([], "anything")).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("model aliases", () => {
|
describe("model aliases", () => {
|
||||||
it("canonicalizes a retired preferred model and restores thinking from its alias key", () => {
|
it("canonicalizes a retired preferred model and restores thinking from its alias key", () => {
|
||||||
const resolved = resolveFormState(
|
const resolved = resolveFormState(
|
||||||
@@ -284,7 +298,7 @@ describe("mergeSelectedComposerPreferences", () => {
|
|||||||
codex: {
|
codex: {
|
||||||
mode: "full-access",
|
mode: "full-access",
|
||||||
thinkingByModel: { "gpt-5.4-mini": "medium" },
|
thinkingByModel: { "gpt-5.4-mini": "medium" },
|
||||||
featureValues: { fast_mode: true },
|
options: { fast_mode: true },
|
||||||
},
|
},
|
||||||
claude: { model: "claude-sonnet-4-6" },
|
claude: { model: "claude-sonnet-4-6" },
|
||||||
},
|
},
|
||||||
@@ -299,7 +313,7 @@ describe("mergeSelectedComposerPreferences", () => {
|
|||||||
model: "gpt-5.4",
|
model: "gpt-5.4",
|
||||||
mode: "full-access",
|
mode: "full-access",
|
||||||
thinkingByModel: { "gpt-5.4-mini": "medium" },
|
thinkingByModel: { "gpt-5.4-mini": "medium" },
|
||||||
featureValues: { fast_mode: true },
|
options: { fast_mode: true },
|
||||||
},
|
},
|
||||||
claude: { model: "claude-sonnet-4-6" },
|
claude: { model: "claude-sonnet-4-6" },
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -153,6 +153,19 @@ export function resolveEffectiveModel(
|
|||||||
return findModelByReference(availableModels, modelId) ?? null;
|
return findModelByReference(availableModels, modelId) ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when the provider has listed its models and this id is not among them. A provider that
|
||||||
|
* lists none accepts any id.
|
||||||
|
*/
|
||||||
|
export function isUnlistedModel(
|
||||||
|
availableModels: AgentModelDefinition[] | null,
|
||||||
|
modelId: string,
|
||||||
|
): boolean {
|
||||||
|
if (!availableModels || availableModels.length === 0) return false;
|
||||||
|
if (!normalizeSelectedModelId(modelId)) return false;
|
||||||
|
return !resolveEffectiveModel(availableModels, modelId);
|
||||||
|
}
|
||||||
|
|
||||||
function resolvePreferredThinkingOptionId(input: {
|
function resolvePreferredThinkingOptionId(input: {
|
||||||
availableModels: AgentModelDefinition[] | null;
|
availableModels: AgentModelDefinition[] | null;
|
||||||
providerPrefs: ProviderPrefs | undefined;
|
providerPrefs: ProviderPrefs | undefined;
|
||||||
|
|||||||
@@ -270,7 +270,7 @@ interface WorkspaceDraftSubmissionConfig {
|
|||||||
modeId: string | null;
|
modeId: string | null;
|
||||||
model: string | null;
|
model: string | null;
|
||||||
thinkingOptionId: string | null;
|
thinkingOptionId: string | null;
|
||||||
featureValues: Record<string, unknown> | undefined;
|
providerOptions: Record<string, unknown> | undefined;
|
||||||
target: WorkspaceTabTarget;
|
target: WorkspaceTabTarget;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -373,7 +373,7 @@ function buildWorkspaceDraftSetupFromComposer(input: {
|
|||||||
modeId: input.composerState.effectiveModeId || null,
|
modeId: input.composerState.effectiveModeId || null,
|
||||||
model: input.composerState.effectiveModelId || null,
|
model: input.composerState.effectiveModelId || null,
|
||||||
thinkingOptionId: input.composerState.effectiveThinkingOptionId || null,
|
thinkingOptionId: input.composerState.effectiveThinkingOptionId || null,
|
||||||
featureValues: input.composerState.featureValues ?? {},
|
providerOptions: input.composerState.providerOptions ?? {},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -453,8 +453,9 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise<Su
|
|||||||
modeId: composerState.effectiveModeId || undefined,
|
modeId: composerState.effectiveModeId || undefined,
|
||||||
model: composerState.effectiveModelId || undefined,
|
model: composerState.effectiveModelId || undefined,
|
||||||
thinkingOptionId: composerState.effectiveThinkingOptionId || undefined,
|
thinkingOptionId: composerState.effectiveThinkingOptionId || undefined,
|
||||||
featureValues: composerState.featureValues,
|
providerOptions: composerState.providerOptions,
|
||||||
},
|
},
|
||||||
|
...(Object.keys(composerState.metadata).length > 0 ? { metadata: composerState.metadata } : {}),
|
||||||
initialPrompt: text,
|
initialPrompt: text,
|
||||||
clientMessageId: `${input.draftId}:initial-message`,
|
clientMessageId: `${input.draftId}:initial-message`,
|
||||||
images: images?.length ? images : undefined,
|
images: images?.length ? images : undefined,
|
||||||
@@ -533,7 +534,8 @@ function buildComposerConfig(input: {
|
|||||||
return {
|
return {
|
||||||
initialServerId: serverId || null,
|
initialServerId: serverId || null,
|
||||||
initialValues: buildComposerInitialValues({ initialSetup }),
|
initialValues: buildComposerInitialValues({ initialSetup }),
|
||||||
initialFeatureValues: initialSetup?.featureValues,
|
initialProviderOptions: initialSetup?.providerOptions,
|
||||||
|
context: "new-workspace" as const,
|
||||||
isVisible: true,
|
isVisible: true,
|
||||||
lockedWorkingDir: workingDir,
|
lockedWorkingDir: workingDir,
|
||||||
};
|
};
|
||||||
@@ -566,7 +568,7 @@ function resolveWorkspaceDraftSubmissionConfig(input: {
|
|||||||
modeId: initialSetup.modeId,
|
modeId: initialSetup.modeId,
|
||||||
model: initialSetup.model,
|
model: initialSetup.model,
|
||||||
thinkingOptionId: initialSetup.thinkingOptionId,
|
thinkingOptionId: initialSetup.thinkingOptionId,
|
||||||
featureValues: initialSetup.featureValues,
|
providerOptions: initialSetup.providerOptions,
|
||||||
target: { kind: "draft", draftId, setup: initialSetup },
|
target: { kind: "draft", draftId, setup: initialSetup },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -576,7 +578,7 @@ function resolveWorkspaceDraftSubmissionConfig(input: {
|
|||||||
modeId: composerState.effectiveModeId || null,
|
modeId: composerState.effectiveModeId || null,
|
||||||
model: composerState.effectiveModelId || null,
|
model: composerState.effectiveModelId || null,
|
||||||
thinkingOptionId: composerState.effectiveThinkingOptionId || null,
|
thinkingOptionId: composerState.effectiveThinkingOptionId || null,
|
||||||
featureValues: composerState.featureValues,
|
providerOptions: composerState.providerOptions,
|
||||||
target: { kind: "draft", draftId },
|
target: { kind: "draft", draftId },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -634,7 +636,7 @@ function submitWorkspaceDraft(input: SubmitDraftInput): SubmitOutcome {
|
|||||||
...(submission.modeId ? { modeId: submission.modeId } : {}),
|
...(submission.modeId ? { modeId: submission.modeId } : {}),
|
||||||
...(submission.model ? { model: submission.model } : {}),
|
...(submission.model ? { model: submission.model } : {}),
|
||||||
...(submission.thinkingOptionId ? { thinkingOptionId: submission.thinkingOptionId } : {}),
|
...(submission.thinkingOptionId ? { thinkingOptionId: submission.thinkingOptionId } : {}),
|
||||||
...(submission.featureValues ? { featureValues: submission.featureValues } : {}),
|
...(submission.providerOptions ? { providerOptions: submission.providerOptions } : {}),
|
||||||
allowEmptyText: true,
|
allowEmptyText: true,
|
||||||
agentCreation: input.agentCreation,
|
agentCreation: input.agentCreation,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ describe("createWorkspaceAgentInBackground", () => {
|
|||||||
modeId: null,
|
modeId: null,
|
||||||
model: null,
|
model: null,
|
||||||
thinkingOptionId: null,
|
thinkingOptionId: null,
|
||||||
featureValues: {},
|
providerOptions: {},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -89,7 +89,7 @@ describe("createWorkspaceAgentInBackground", () => {
|
|||||||
modeId: null,
|
modeId: null,
|
||||||
model: null,
|
model: null,
|
||||||
thinkingOptionId: null,
|
thinkingOptionId: null,
|
||||||
featureValues: {},
|
providerOptions: {},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ export function buildWorkspaceDraftAgentConfig(input: {
|
|||||||
modeId?: string;
|
modeId?: string;
|
||||||
model?: string;
|
model?: string;
|
||||||
thinkingOptionId?: string;
|
thinkingOptionId?: string;
|
||||||
featureValues?: Record<string, unknown>;
|
providerOptions?: Record<string, unknown>;
|
||||||
}): AgentSessionConfig {
|
}): AgentSessionConfig {
|
||||||
return {
|
return {
|
||||||
provider: input.provider,
|
provider: input.provider,
|
||||||
@@ -14,6 +14,6 @@ export function buildWorkspaceDraftAgentConfig(input: {
|
|||||||
...(input.modeId ? { modeId: input.modeId } : {}),
|
...(input.modeId ? { modeId: input.modeId } : {}),
|
||||||
...(input.model ? { model: input.model } : {}),
|
...(input.model ? { model: input.model } : {}),
|
||||||
...(input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {}),
|
...(input.thinkingOptionId ? { thinkingOptionId: input.thinkingOptionId } : {}),
|
||||||
...(input.featureValues ? { featureValues: input.featureValues } : {}),
|
...(input.providerOptions ? { providerOptions: input.providerOptions } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,6 +36,8 @@ import {
|
|||||||
} from "./migration";
|
} from "./migration";
|
||||||
import { createDraftPersistStorage } from "./persistence";
|
import { createDraftPersistStorage } from "./persistence";
|
||||||
import { createValidatedPersistStorage } from "@/storage/validated-persist-storage";
|
import { createValidatedPersistStorage } from "@/storage/validated-persist-storage";
|
||||||
|
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||||
|
import { applyMetadataPatch } from "@/composer/draft/metadata";
|
||||||
|
|
||||||
export type { DraftInput, DraftLifecycleState } from "./state";
|
export type { DraftInput, DraftLifecycleState } from "./state";
|
||||||
|
|
||||||
@@ -49,6 +51,9 @@ interface DraftStoreActions {
|
|||||||
draftKey: string;
|
draftKey: string;
|
||||||
lifecycle?: Exclude<DraftLifecycleState, "active">;
|
lifecycle?: Exclude<DraftLifecycleState, "active">;
|
||||||
}) => void;
|
}) => void;
|
||||||
|
/** Plugin metadata the draft will create its agent with; see `composer/draft/metadata`. */
|
||||||
|
patchDraftMetadata: (input: { draftKey: string; patch: Record<string, JsonValue> }) => void;
|
||||||
|
clearDraftMetadata: (input: { draftKey: string }) => void;
|
||||||
attachWorkspaceFile: (input: {
|
attachWorkspaceFile: (input: {
|
||||||
draftKey: string;
|
draftKey: string;
|
||||||
attachment: WorkspaceFileComposerAttachment;
|
attachment: WorkspaceFileComposerAttachment;
|
||||||
@@ -60,6 +65,11 @@ interface DraftStoreActions {
|
|||||||
|
|
||||||
interface DraftStoreRuntimeState {
|
interface DraftStoreRuntimeState {
|
||||||
attachmentFocusRequestByDraftKey: Record<string, number>;
|
attachmentFocusRequestByDraftKey: Record<string, number>;
|
||||||
|
/**
|
||||||
|
* Kept beside the prompt so a composer that remounts finds it. Not persisted, and not cleared
|
||||||
|
* with an emptied prompt: a plugin's choice outlives the text until the draft is sent.
|
||||||
|
*/
|
||||||
|
metadataByDraftKey: Record<string, Record<string, JsonValue>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
type DraftStore = DraftStoreState & DraftStoreRuntimeState & DraftStoreActions;
|
type DraftStore = DraftStoreState & DraftStoreRuntimeState & DraftStoreActions;
|
||||||
@@ -256,6 +266,7 @@ export const useDraftStore = create<DraftStore>()(
|
|||||||
drafts: {},
|
drafts: {},
|
||||||
createModalDraft: null,
|
createModalDraft: null,
|
||||||
attachmentFocusRequestByDraftKey: {},
|
attachmentFocusRequestByDraftKey: {},
|
||||||
|
metadataByDraftKey: {},
|
||||||
|
|
||||||
getDraftInput: (draftKey) => {
|
getDraftInput: (draftKey) => {
|
||||||
const record = get().drafts[draftKey];
|
const record = get().drafts[draftKey];
|
||||||
@@ -374,6 +385,25 @@ export const useDraftStore = create<DraftStore>()(
|
|||||||
scheduleAttachmentGc();
|
scheduleAttachmentGc();
|
||||||
},
|
},
|
||||||
|
|
||||||
|
patchDraftMetadata: ({ draftKey, patch }) => {
|
||||||
|
set((state) => {
|
||||||
|
const next = applyMetadataPatch(state.metadataByDraftKey[draftKey] ?? {}, patch);
|
||||||
|
const { [draftKey]: _previous, ...others } = state.metadataByDraftKey;
|
||||||
|
return {
|
||||||
|
metadataByDraftKey:
|
||||||
|
Object.keys(next).length > 0 ? { ...others, [draftKey]: next } : others,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
clearDraftMetadata: ({ draftKey }) => {
|
||||||
|
set((state) => {
|
||||||
|
if (!(draftKey in state.metadataByDraftKey)) return state;
|
||||||
|
const { [draftKey]: _removed, ...others } = state.metadataByDraftKey;
|
||||||
|
return { metadataByDraftKey: others };
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
attachWorkspaceFile: async ({ draftKey, attachment }) => {
|
attachWorkspaceFile: async ({ draftKey, attachment }) => {
|
||||||
await get().hydrateDraftInput({ draftKey });
|
await get().hydrateDraftInput({ draftKey });
|
||||||
set((state) => {
|
set((state) => {
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import { useDraftStore } from "./index";
|
||||||
|
|
||||||
|
const draftKey = "draft:metadata";
|
||||||
|
|
||||||
|
describe("a draft's plugin metadata", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
useDraftStore.setState({ drafts: {}, metadataByDraftKey: {} });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is there when the draft's composer mounts again", () => {
|
||||||
|
const store = useDraftStore.getState();
|
||||||
|
store.editDraftText({ draftKey, text: "review this" });
|
||||||
|
store.patchDraftMetadata({ draftKey, patch: { "plugin.review": true, "plugin.tag": "a" } });
|
||||||
|
store.patchDraftMetadata({ draftKey, patch: { "plugin.tag": null } });
|
||||||
|
|
||||||
|
// A remount reads the store again; nothing from the unmounted composer is kept.
|
||||||
|
const remounted = useDraftStore.getState();
|
||||||
|
expect(remounted.getDraftInput(draftKey)?.text).toBe("review this");
|
||||||
|
expect(remounted.metadataByDraftKey[draftKey]).toEqual({ "plugin.review": true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is dropped with the prompt once the draft is sent, and not before", () => {
|
||||||
|
const store = useDraftStore.getState();
|
||||||
|
store.patchDraftMetadata({ draftKey, patch: { "plugin.review": true } });
|
||||||
|
|
||||||
|
store.clearDraftInput({ draftKey, lifecycle: "abandoned" });
|
||||||
|
expect(useDraftStore.getState().metadataByDraftKey[draftKey]).toEqual({
|
||||||
|
"plugin.review": true,
|
||||||
|
});
|
||||||
|
|
||||||
|
store.clearDraftMetadata({ draftKey });
|
||||||
|
expect(useDraftStore.getState().metadataByDraftKey[draftKey]).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -26,7 +26,9 @@ import type { ComposerAttachment } from "@/attachments/types";
|
|||||||
import type { AgentLifecycleStatus } from "@getpaseo/protocol/agent-lifecycle";
|
import type { AgentLifecycleStatus } from "@getpaseo/protocol/agent-lifecycle";
|
||||||
import type {
|
import type {
|
||||||
AgentPermissionRequest,
|
AgentPermissionRequest,
|
||||||
AgentFeature,
|
AgentOptionControl,
|
||||||
|
JsonValue,
|
||||||
|
ProviderOptions,
|
||||||
AgentProvider,
|
AgentProvider,
|
||||||
AgentMode,
|
AgentMode,
|
||||||
AgentCapabilityFlags,
|
AgentCapabilityFlags,
|
||||||
@@ -91,7 +93,8 @@ export interface Agent {
|
|||||||
cwd: string;
|
cwd: string;
|
||||||
workspaceId?: string;
|
workspaceId?: string;
|
||||||
model: string | null;
|
model: string | null;
|
||||||
features?: AgentFeature[];
|
options?: ProviderOptions;
|
||||||
|
controls?: AgentOptionControl[];
|
||||||
thinkingOptionId?: string | null;
|
thinkingOptionId?: string | null;
|
||||||
requiresAttention?: boolean;
|
requiresAttention?: boolean;
|
||||||
attentionReason?: "finished" | "error" | "permission" | null;
|
attentionReason?: "finished" | "error" | "permission" | null;
|
||||||
@@ -101,6 +104,7 @@ export interface Agent {
|
|||||||
background?: boolean;
|
background?: boolean;
|
||||||
parentAgentId: string | null;
|
parentAgentId: string | null;
|
||||||
labels: Record<string, string>;
|
labels: Record<string, string>;
|
||||||
|
metadata?: Record<string, JsonValue>;
|
||||||
projectPlacement?: ProjectPlacementPayload | null;
|
projectPlacement?: ProjectPlacementPayload | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ export interface PendingWorkspaceDraftSubmission {
|
|||||||
modeId?: string;
|
modeId?: string;
|
||||||
model?: string;
|
model?: string;
|
||||||
thinkingOptionId?: string;
|
thinkingOptionId?: string;
|
||||||
featureValues?: Record<string, unknown>;
|
providerOptions?: Record<string, unknown>;
|
||||||
allowEmptyText?: boolean;
|
allowEmptyText?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -95,6 +95,53 @@ 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])(
|
it.each([1, 2])(
|
||||||
"restores the agent pane after parked focus in storage version %i",
|
"restores the agent pane after parked focus in storage version %i",
|
||||||
async (version) => {
|
async (version) => {
|
||||||
|
|||||||
@@ -1,14 +1,25 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { SplitNode, WorkspaceLayout } from "./workspace-layout-actions";
|
import type { SplitNode, WorkspaceLayout } from "./workspace-layout-actions";
|
||||||
|
|
||||||
const WorkspaceDraftTabSetupStorageSchema = z.strictObject({
|
// 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(),
|
provider: z.string(),
|
||||||
cwd: z.string(),
|
cwd: z.string(),
|
||||||
modeId: z.string().nullable(),
|
modeId: z.string().nullable(),
|
||||||
model: z.string().nullable(),
|
model: z.string().nullable(),
|
||||||
thinkingOptionId: z.string().nullable(),
|
thinkingOptionId: z.string().nullable(),
|
||||||
featureValues: z.record(z.string(), z.union([z.boolean(), z.string(), z.null()])),
|
providerOptions: z.record(z.string(), z.json()),
|
||||||
});
|
}),
|
||||||
|
);
|
||||||
const WorkspaceTabTargetStorageSchema = z.discriminatedUnion("kind", [
|
const WorkspaceTabTargetStorageSchema = z.discriminatedUnion("kind", [
|
||||||
z.strictObject({ kind: z.literal("new_tab") }),
|
z.strictObject({ kind: z.literal("new_tab") }),
|
||||||
z.strictObject({
|
z.strictObject({
|
||||||
|
|||||||
@@ -4551,7 +4551,6 @@ describe("compact workspace sheet", () => {
|
|||||||
title: agent.id,
|
title: agent.id,
|
||||||
cwd: "/repo",
|
cwd: "/repo",
|
||||||
model: null,
|
model: null,
|
||||||
features: undefined,
|
|
||||||
thinkingOptionId: undefined,
|
thinkingOptionId: undefined,
|
||||||
requiresAttention: false,
|
requiresAttention: false,
|
||||||
attentionReason: null,
|
attentionReason: null,
|
||||||
|
|||||||
@@ -63,7 +63,6 @@ const AGENT_DEFAULTS: Agent = {
|
|||||||
cwd: WORKSPACE_DIRECTORY,
|
cwd: WORKSPACE_DIRECTORY,
|
||||||
workspaceId: WORKSPACE_ID,
|
workspaceId: WORKSPACE_ID,
|
||||||
model: null,
|
model: null,
|
||||||
features: undefined,
|
|
||||||
thinkingOptionId: undefined,
|
thinkingOptionId: undefined,
|
||||||
requiresAttention: false,
|
requiresAttention: false,
|
||||||
attentionReason: null,
|
attentionReason: null,
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ const AGENT_DEFAULTS: Agent = {
|
|||||||
title: "Agent",
|
title: "Agent",
|
||||||
cwd: "/tmp/project",
|
cwd: "/tmp/project",
|
||||||
model: null,
|
model: null,
|
||||||
features: undefined,
|
|
||||||
thinkingOptionId: undefined,
|
thinkingOptionId: undefined,
|
||||||
requiresAttention: false,
|
requiresAttention: false,
|
||||||
attentionReason: null,
|
attentionReason: null,
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user