Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 186df6fb53 feat(app): show only the Enable tools switch in setup
Setup is for getting started, so the Orchestration step shows a plain
Enable tools switch next to skills and the CLI. Tool groups stay in
Settings > Tools & prompts. Setup writes only the main switch, so the
groups a host already saved are never touched.
2026-11-28 17:32:07 +01:00
Mohamed Boudra d71f79570c fix(server): keep wire schemas out of the configuration entry point
tools-config.ts imported the default tool groups from protocol/messages,
which pulled every wire schema into @getpaseo/server/configuration. The
group constants now live in the Zod-free protocol/tool-groups module, and
messages re-exports them.

The WebSocket server read the config store behind a guard that only
existed for incomplete test stubs. The store is a required dependency, so
the guard is gone and the stubs provide get().
2026-11-28 17:32:07 +01:00
Mohamed Boudra 9e7e43c9ad fix(app): keep the host's tool groups when setup is shown again
The Orchestration step started its tool groups from the defaults and wrote
all four on Continue, so a host with Browser on or Schedules off lost those
choices when the user opened setup again. The groups sit in a collapsed row,
so the user never saw the switches. Setup now shows the host's groups and
writes only the groups the user changed.

The compact-layout setup test assumed the host starts with tools off; it now
turns them off first, since tools are on by default.
2026-11-28 17:32:07 +01:00
Mohamed Boudra 7e9f159b8a feat(server,app): group agent tools under one Enable tools setting
Replace the separate "Enable Paseo tools" and "Browser tools" settings with
one `daemon.tools` configuration: an `enabled` switch plus per-group switches
for orchestration, schedules, PR watching, and browser. Every built-in tool
now declares its group, scope, and daemon permission in one registry, so
native providers and the loopback MCP endpoint filter the same catalog.

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

Voice mode now requires tools. When tools are off it refuses with reasonCode
"tools_disabled" and the voice settings page offers a one-click Enable tools
action. Dictation is unaffected.
2026-11-28 17:32:06 +01:00
297 changed files with 4484 additions and 21179 deletions
-1
View File
@@ -60,7 +60,6 @@ sdk:
- "packages/client/**"
- "packages/highlight/**"
- "packages/protocol/**"
- "packages/workflows/**"
browser:
- "packages/server/src/server/agent/provider-snapshot-manager.ts"
-8
View File
@@ -128,14 +128,6 @@ jobs:
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run test --workspace=@getpaseo/highlight
- name: Build workflows package
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run build:workflows
- name: Run workflows tests
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run test --workspace=@getpaseo/workflows
- name: Typecheck client examples
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
run: npm run typecheck:examples --workspace=@getpaseo/client
+2 -2
View File
@@ -329,7 +329,7 @@ messages or transfers.
### Compatibility rules
- WebSocket schemas are append-only. Add fields, do not remove fields, and never make optional fields required.
- New wire enum values must be gated at serialization with `session.supports(CLIENT_CAPS.someCapability)`. An older reader skips an unknown value inside a list; gate it anyway when the old client must see something.
- New wire enum values must be gated at serialization with `session.supports(CLIENT_CAPS.someCapability)`.
- Capabilities belong to the physical source socket. `session.supports(...)` reads the requesting or observing source at the domain projection boundary; one socket must not borrow a sibling's capabilities.
Example: adding a new enum value
@@ -337,7 +337,7 @@ Example: adding a new enum value
```ts
// 1. Add CLIENT_CAPS.newThing = "new_thing"
// 2. Let new clients advertise it in WS hello
// 3. Add the value to the shared schema; no catch-all branch
// 3. Keep the shared producer schema strict
// 4. Gate the new emitted value: session.supports(CLIENT_CAPS.newThing) ? "new_value" : "old_value"
```
+7 -4
View File
@@ -209,7 +209,8 @@ snapshot so a mixed edit can apply its live subset and still name the paths that
listen: "127.0.0.1:6767",
hostnames: true | string[], // legacy alias `allowedHosts` is migrated on load
trustedProxies: true | string[], // defaults to ["loopback"]; Express proxy names/CIDRs
mcp: { enabled: boolean, injectIntoAgents: boolean },
tools: { enabled: boolean, groups: { orchestration, schedules, changeRequests, browser: boolean } },
mcp: { enabled: boolean, injectIntoAgents: boolean }, // legacy, read only when `tools` is absent
git: { maxProcessesPerSecond: number, maxProcessConcurrency: number },
appendSystemPrompt: string, // appended to supported provider system/developer prompts
terminalProfiles: TerminalProfile[], // named shell commands; omitted means DEFAULT_TERMINAL_PROFILES
@@ -311,12 +312,14 @@ Each entry may include a Paseo-tool policy:
Absent `paseoTools`, or absent fields within it, means Paseo tools are enabled and all tools are
allowed. `enabled: false` disables the provider's Paseo catalog; `disabledTools` lists exact tool
IDs to omit. The policy covers the core and browser catalog, not the voice-only `speak` tool.
Browser tools also require `daemon.browserTools.enabled` and a connected browser host.
Browser tools also require `daemon.tools.groups.browser` and a connected browser host.
This policy controls the catalog presented to an agent. It is not an authorization boundary for
agents that can access the host through a shell.
`daemon.mcp.injectIntoAgents` is the global override. When it is `false`, no provider receives
Paseo tools; otherwise the provider policy applies. Provider and global policy are resolved when a
`daemon.tools` is the global override. When `enabled` is `false`, no provider receives Paseo or
plugin tools; otherwise each group in `daemon.tools.groups` and then the provider policy applies.
When `daemon.tools` is absent, the daemon reads the legacy `daemon.mcp.injectIntoAgents` and
`daemon.browserTools.enabled` fields. Provider and global policy are resolved when a
session is created, resumed, imported, or reloaded, so configuration changes affect the next
session rather than an already-running one.
-4
View File
@@ -36,10 +36,6 @@ ordinary `WorkspaceTab` (`SheetTab` in the store) and is an `IsolatedBottomSheet
other sheet in the app, so it sits on the one app-wide stack: a sheet opened from any sheet lands on
top of it, and closing the top sheet (drag, Close, backdrop, or Android Back) uncovers the one below.
Because that stack is app-wide and hidden workspace screens stay mounted, a sheet is not presented
until its workspace has been on screen. A target opened in a workspace before the user gets there
waits in the store and appears on arrival.
A subagent chosen from the subagents list is the exception. It opens as a page of the list's own
sheet and replaces the list in place: Back returns to the list, Close ends both, and Open parent
closes the list, landing on the pane the list was opened from. The store's `selectSheetTab` describes
+5 -21
View File
@@ -301,10 +301,9 @@ translation scope is React context and does not cross it (Gotcha 7). It returns:
height with it; never animate height per frame.
Do not measure an anchor with `measureInWindow` and correct it by the keyboard
shift. On iOS the translate view uses the native driver, which moves the view
without updating the shadow tree. The translate view commits the resting lift to
the shadow tree once the keyboard settles, so `measureInWindow` includes the lift
at rest and misses it while the keyboard moves. Any correction double-lifts the
shift. On iOS the translate view uses the native driver, and `measureInWindow`
includes its transform only when the view happened to re-render since the
keyboard moved. Both results were observed, so any correction double-lifts the
popover or leaves it behind the keyboard. `measureAtRest` measures through
Fabric's transform-free `measureLayout` instead. Re-measure when `isMoving`
settles; the composer's resting position changes as the draft grows.
@@ -316,8 +315,8 @@ the anchor's rect against the layer and commits the placement with `flushSync`,
which runs after layout and before paint. On native a Reanimated frame callback
reads only the anchor's height on the UI thread and holds its bottom edge at
the rest measurement. A height carries no transform. On iOS the absolute
position does not include one while the keyboard moves: the lift runs on the
native driver and reaches the shadow tree only at rest. The
position does not reliably include one: the keyboard lift runs on the native
driver and reaches the shadow tree only when the view re-renders. The
fixed-bottom model is wrong for the centered New workspace composer on tablets,
which grows around its middle, and for width or x changes. The popover is off
there by half the growth, or by the old width, until the next rest measurement.
@@ -325,21 +324,6 @@ Keep the portal's `KeyboardTranslateView` host-sized with
`pointerEvents="box-none"` and position the popover inside it, so the popover
moves without leaving its parent's bounds (Gotcha 1).
The resting commit also keeps touches working. Pressability measures a
`Pressable`'s press region in the shadow tree. If the region stays at the
unlifted position, a tap that drifts a few points leaves it and the press is
dropped. This hit every control in the dock: Send, attach, and the model selector.
`Combobox` positions its native popover with floating-ui against the window, and
the software keyboard covers part of the window. It adds the settled keyboard
height (`useSettledKeyboardHeight`) to its bottom collision padding. The height
changes on `keyboardDidShow` and `keyboardDidHide`, at the end of the move. The new
padding re-measures the anchor on the next frame, when the resting lift is in the
shadow tree, so the popover follows an anchor that rides the keyboard.
Opening the model picker moves focus to its search input, and the keyboard hides
and shows again on the way. A height that changes at `keyboardWillShow` instead
measures the trigger before it lifts and leaves the popover over the keyboard.
The provider also reconciles iOS from the controller's native `onEnd` event.
The controller's stock iOS shared values update at move start and during an
interactive move, but not at the terminal event, so JS contention can otherwise
+1 -4
View File
@@ -127,10 +127,7 @@ With a Codex draft selected, set `_SCENARIO=growth` on a 402pt-wide iPhone to
check live wrapping, shrinking, the 12pt anchor gap, and command insertion. Set
`_SCENARIO=previews` on an SE-sized iPhone to check long and short descriptions
under an eight-line draft, selection with the keyboard shown and hidden, and
file mentions. Set `_SCENARIO=controls` to tap the attach button and the model
selector with a 3pt drag while the keyboard is open, then check that a wide
layout's model popover clears both the trigger and the keyboard. Run it on an
iPhone and on the iPhone Duo unfolded. These scenarios only need `_SERVER_ID` and `_WORKSPACE_ID`;
file mentions. These scenarios only need `_SERVER_ID` and `_WORKSPACE_ID`;
`_UDID` selects an exact simulator and `_ARTIFACTS_DIR` overrides the output path.
The Android sidebar scroll-retention flow requires a connected host with enough
+2 -12
View File
@@ -267,10 +267,6 @@ Plugin UI runs on desktop and mobile across multiple themes: color every `Text`
`theme.colors.foreground` or `theme.colors.foregroundMuted`, and size layout from `layout.compact`.
See `public-docs/plugins/reference.md`.
A plugin reads and arranges panes and tabs through `PluginWorkspaceLayout`. Its host,
`packages/app/src/plugins/workspace-layout/`, is a facade over the layout store and `workspace-tabs`,
so add behavior to those owners and keep layout mechanics out of the SDK types.
### SDK import boundaries
Classify every SDK export before adding it. All client entry points and implementations live under
@@ -643,12 +639,6 @@ effective configuration and execution environment, or
`undefined` for target-specific caching. Ignore `force` when choosing identity. Existing providers
need no change. See [catalogue ownership](providers.md#provider-snapshot-refresh-contract).
Both sides of the provider protocol ignore fields they do not know. A list element of an unknown
kind, such as a prompt content block, a command kind, or a timeline item, is dropped and the rest of
the input or event is kept. The daemon drops an event of a kind it does not know and keeps the
connection open. Paseo supplies the SDK at runtime, so both sides read with the daemon's parser. An
input the provider must act on still needs a connection capability, as `session.launch_wrap` does.
`send()` resolves after acceptance. Publish operation completion, prompt disposition, turn state,
configuration, permissions, persistence, and complete timeline snapshots through `onEvent()`.
Route messages, structured commands, steering, and command side effects through `session.prompt`.
@@ -1022,8 +1012,8 @@ payload that cannot be rendered intact. The daemon advertises this RPC through
`addSlashCommand` registers an agent- or workspace-context command in the composer. The
callback runs in the app, receives the trimmed text after the command name as `args`, and receives
the same `paseo`, `rpc`, `openScreen`, workspace, agent, and `workspaceLayout` capabilities as the
matching Command Center callback.
the same `paseo`, `rpc`, `openScreen`, workspace, agent, and `openPanel` capabilities as the matching
Command Center callback.
```ts
client.addSlashCommand({
-3
View File
@@ -17,9 +17,6 @@ A schema change must not break parsing in either direction. An old app still par
- A field you stop sending stays accepted. You stop writing it, you don't stop reading it.
- Wire schemas are pure structural declarations. No `.transform()`, `.catch()`, or `.preprocess()` on WebSocket message schemas — normalization happens in an explicit pass after validation. The reason is in [protocol-validation.md](protocol-validation.md): inbound validators are generated, and the generator only compiles pure schemas.
- Plain `z.union()` is forbidden when every branch shares a literal tag. Use `z.discriminatedUnion()`.
- Wire objects ignore keys they do not know. Never put `.strict()` or `z.strictObject` on a schema that reads another process's data. `packages/protocol/tests/validation/evolvability.test.ts` audits every app↔daemon schema. Strict objects belong to local files that should reject typos, such as the `config.json` copies in `packages/server/src/server/persisted-config.ts`. The browser automation request is the one wire exception: it rejects legacy tab targeting so a request cannot run against the wrong tab.
- An unknown variant inside a list costs one element. Readers parse through `safeParseSkippingUnknownVariants` (`packages/protocol/src/validation/unknown-variants.ts`): an unrecognized tag or enum value inside an array drops that element and keeps the message. Outside an array the read fails with `unknownVariant: true` and the reader drops that one message. Schemas stay closed, so consumer `switch`es stay exhaustive. Pruning reaches a list only through objects, arrays, and discriminated unions; a list under a plain `z.union()` branch or a record value is not pruned.
- Skipping is not support. When an old reader must see something for the feature to make sense, gate the new value at serialization ([architecture](architecture.md#compatibility-rules)).
- `.default()` belongs on primitive leaves only, never on item schemas inside large arrays or big inbound containers.
Two questions to ask before you commit a schema change:
+1 -1
View File
@@ -6,7 +6,7 @@ The reason is mobile performance. A captured 353 KB provider snapshot cost about
## Runtime Path
`packages/protocol/src/validation/ws-outbound.ts` is the shipped boundary. It validates the envelope with a generated validator that checks only each session message's `type` tag, then runs the generated validator for that one message type and returns the validated data. Issue paths from the message validator, including nested union branches, are prefixed with `message`, so callers see the same issues as when one validator covered the whole envelope. It does not normalize or repair the generated result. When the only failures are unknown variants inside lists, the boundary removes those elements and validates once more ([protocol-compatibility](protocol-compatibility.md#the-protocol-contract-always-compatible)). The reader classifies failures from the issue list, so it behaves the same over the generated validator and Zod, and a valid message pays nothing extra.
`packages/protocol/src/validation/ws-outbound.ts` is the shipped boundary. It validates the envelope with a generated validator that checks only each session message's `type` tag, then runs the generated validator for that one message type and returns the validated data. Issue paths from the message validator, including nested union branches, are prefixed with `message`, so callers see the same issues as when one validator covered the whole envelope. It does not normalize, repair, or re-validate the generated result.
Keep one generated function per message type. zod-aot inlines every nested schema into the function it compiles, so compiling `WSOutboundMessageSchema` as a whole produced one 11 MB function. On V8 (daemon clients, plugin hosts, the CLI, and Electron), the Maglev tier compiled that function once it was hot, allocating about 800 MB and stalling for seconds, and compiled it again after each deoptimization. Hermes has no JIT, so mobile never showed it. `packages/protocol/tests/validation/ws-outbound.test.ts` fails if a generated function grows past 1 MB.
-11
View File
@@ -73,17 +73,6 @@
"entry": ["src/index.ts", "src/**/*.test.ts"],
"project": ["src/**/*.ts"]
},
"packages/workflows": {
"entry": [
"src/index.ts",
"src/ir.ts",
"src/dsl.ts",
"src/yaml.ts",
"src/testing.ts",
"test/**/*.test.ts"
],
"project": ["src/**/*.ts", "test/**/*.ts"]
},
"packages/expo-two-way-audio": {
"entry": ["src/index.ts"],
"project": ["src/**/*.ts"]
+1 -1
View File
@@ -1 +1 @@
sha256-34bUBmRmjekbUSp93597GLTmSWKt23TCHaK3ViXG+iU=
sha256-aal9eR571blWuL7CZt1LR+KfA4QPJ0ivVl/GSTWy93o=
+3 -20
View File
@@ -16,7 +16,6 @@
"packages/highlight",
"packages/plugin",
"packages/protocol",
"packages/workflows",
"packages/client",
"packages/server",
"packages/app",
@@ -6710,10 +6709,6 @@
"resolved": "packages/website",
"link": true
},
"node_modules/@getpaseo/workflows": {
"resolved": "packages/workflows",
"link": true
},
"node_modules/@gorhom/bottom-sheet": {
"version": "5.2.14",
"resolved": "https://registry.npmjs.org/@gorhom/bottom-sheet/-/bottom-sheet-5.2.14.tgz",
@@ -14929,6 +14924,7 @@
"version": "8.11.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz",
"integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==",
"dev": true,
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.1",
@@ -31402,6 +31398,7 @@
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -36231,6 +36228,7 @@
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
"integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"punycode": "^2.1.0"
@@ -43161,21 +43159,6 @@
}
}
},
"packages/workflows": {
"name": "@getpaseo/workflows",
"version": "0.1.0",
"license": "Apache-2.0",
"dependencies": {
"ajv": "^8.11.0",
"js-yaml": "^4.1.1",
"zod": "^4.4.3"
},
"devDependencies": {
"@types/node": "^20.9.0",
"typescript": "^5.9.3",
"vitest": "^4.1.6"
}
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.18.1",
-3
View File
@@ -27,7 +27,6 @@
"packages/highlight",
"packages/plugin",
"packages/protocol",
"packages/workflows",
"packages/client",
"packages/server",
"packages/app",
@@ -61,8 +60,6 @@
"build:relay:clean": "npm run build:clean --workspace=@getpaseo/relay",
"build:protocol": "npm run build --workspace=@getpaseo/protocol",
"build:protocol:clean": "npm run build:clean --workspace=@getpaseo/protocol",
"build:workflows": "npm run build --workspace=@getpaseo/workflows",
"build:workflows:clean": "npm run build:clean --workspace=@getpaseo/workflows",
"build:client": "npm run build --workspace=@getpaseo/client",
"build:client:clean": "npm run build:protocol:clean && npm run build:clean --workspace=@getpaseo/client",
"build:server-deps": "npm run build:client && concurrently --kill-others-on-fail --names highlight,plugin,relay --prefix-colors yellow,green,blue \"npm run build:highlight\" \"npm run build:plugin\" \"npm run build:relay\"",
@@ -85,10 +85,13 @@ test.describe("Agent profiles in the model picker", () => {
await expectComposerMode(page, "Load test");
});
await test.step("the single-provider picker lists Profiles above the agent's models without a rail", async () => {
await test.step("the picker opens on the agent's provider with Profiles beside it", async () => {
await openModelPicker(page);
await expect(page.getByTestId("model-search-input").first()).toBeFocused();
await expect(page.getByTestId("model-picker-rail")).toHaveCount(0);
await expect(page.getByTestId("model-provider-mock")).toHaveAttribute(
"data-active",
"true",
);
await expectModelRowSelected(page, { provider: "mock", modelId: "ten-second-stream" });
await expectPickerProfile(page, {
name: PROFILE.name,
@@ -1,13 +0,0 @@
import {
expectBuiltinPluginSettings,
openBuiltinPluginSettings,
test,
} from "../support/helpers/builtin-plugin-settings";
test("a built-in plugin's settings link opens its screen", async ({
page,
builtinSettingsHost,
}) => {
await openBuiltinPluginSettings(page, builtinSettingsHost);
await expectBuiltinPluginSettings(page);
});
@@ -233,63 +233,6 @@ test("opening an agent focuses the composer when a mouse drives the UI", async (
}
});
/** The composer frame's border colour once its border-color transition has finished. */
async function readSettledFrameBorder(page: Page): Promise<string> {
return composerLocator(page).evaluate(async (input) => {
let frame = input.parentElement;
while (frame && parseFloat(getComputedStyle(frame).borderTopWidth) < 1) {
frame = frame.parentElement;
}
if (!frame) throw new Error("Composer frame has no border");
while (frame.getAnimations().length > 0) {
await new Promise((resolve) => requestAnimationFrame(resolve));
}
return getComputedStyle(frame).borderTopColor;
});
}
// `borderAccent` at rest, `surface4` while focused: greys in both themes, never the accent.
const FRAME_BORDERS = {
dark: { rest: "rgb(47, 53, 52)", focus: "rgb(89, 91, 91)" },
light: { rest: "rgb(236, 236, 241)", focus: "rgb(212, 212, 216)" },
} as const;
for (const colorScheme of ["dark", "light"] as const) {
test(`the composer frame takes a neutral border on focus in the ${colorScheme} theme`, async ({
page,
}) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "composer-frame-focus-",
title: "Composer frame focus",
});
const borders = FRAME_BORDERS[colorScheme];
try {
await page.emulateMedia({ colorScheme });
await openAgentRoute(page, agent);
const composer = composerLocator(page);
await expectComposerVisible(page);
await page.mouse.move(0, 0);
await blurComposerInput(page);
expect(await readSettledFrameBorder(page)).toBe(borders.rest);
await composer.click();
await page.mouse.move(0, 0);
await expectComposerFocused(page);
expect(await readSettledFrameBorder(page)).toBe(borders.focus);
await blurComposerInput(page);
expect(await readSettledFrameBorder(page)).toBe(borders.rest);
// Hover alone leaves the frame at rest, so the border only ever means focus.
await composer.hover();
expect(await readSettledFrameBorder(page)).toBe(borders.rest);
} finally {
await agent.cleanup();
}
});
}
async function waitForAnimationFrames(page: Page, count: number): Promise<void> {
await page.evaluate(async (frames) => {
for (let frame = 0; frame < frames; frame += 1) {
@@ -753,10 +753,6 @@ test.describe("CodeMirror workspace file editing", () => {
const imagePath = path.join(workspace.repoPath, "pixel.png");
await writeFile(markdownPath, "# First heading\n", "utf8");
await writeFile(imagePath, RED_PIXEL);
await writeFile(
path.join(workspace.repoPath, "shape.svg"),
await readFile(path.resolve(__dirname, "../mobile/fixtures/native-preview.svg")),
);
await workspace.navigateTo();
await openWorkspaceFile(page, "notes.md");
@@ -804,11 +800,6 @@ test.describe("CodeMirror workspace file editing", () => {
const initialSource = await image.getAttribute("src");
await writeFile(imagePath, BLUE_PIXEL);
await expect.poll(() => image.getAttribute("src")).not.toBe(initialSource);
await openWorkspaceFile(page, "shape.svg");
await expect(imageCanvas).toBeVisible();
await expect(image).toBeVisible();
await expect(image).toHaveJSProperty("naturalWidth", 240);
});
test("renders local relative images inside Markdown preview", async ({ page, withWorkspace }) => {
@@ -28,7 +28,6 @@ import {
} from "../support/helpers/composer";
import { openGlobalNewWorkspaceComposer } from "../support/helpers/new-workspace";
import { clickNewChat, clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { seedWorkspace } from "../support/helpers/seed-client";
const MOCK_PROVIDER_LABEL = "Mock Load Test";
@@ -316,50 +315,15 @@ test.describe("Cross-provider model search", () => {
await expectComposerFocused(page);
});
await test.step("the compact drawer surfaces collapsed Profiles above Model on Home and keeps provider headers stable on collapse", async () => {
await test.step("the compact drawer puts Profiles in the Model accordion and lets all groups collapse", async () => {
await page.setViewportSize({ width: 390, height: 800 });
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
const profilesToggle = page.getByTestId("agent-controls-profiles");
const modelRowButton = page.getByTestId("agent-controls-model");
await expect(profilesToggle).toBeVisible();
await expect(page.getByTestId("agent-controls-profiles-list")).toHaveCount(0);
const profilesBox = await profilesToggle.boundingBox();
const modelBox = await modelRowButton.boundingBox();
expect(profilesBox && modelBox && profilesBox.y < modelBox.y).toBe(true);
// Open Model: Profiles is extracted onto Home, and provider headers keep exact geometry when collapsed.
await modelRowButton.click();
await expect(page.getByTestId("agent-controls-profiles")).toHaveCount(0);
await page.getByTestId("agent-controls-model").click();
await expect(page.getByTestId("compact-model-list")).toBeVisible();
await expect(page.getByTestId("model-picker-rail-profiles")).toHaveCount(0);
const expandedHeader = page.locator('[data-testid^="model-provider-section-"]').first();
const expandedBox = await expandedHeader.boundingBox();
const expandedProviderId = (await expandedHeader.getAttribute("data-testid"))?.replace(
"model-provider-section-",
"",
);
await expandedHeader.click();
await page.locator('[data-testid^="model-provider-section-"]').first().click();
await expect(page.getByTestId("compact-model-list")).toHaveCount(0);
const collapsedHeader = page.getByTestId(`model-provider-${expandedProviderId}`);
const collapsedBox = await collapsedHeader.boundingBox();
expect(expandedBox && collapsedBox).toBeTruthy();
expect(Math.abs(expandedBox!.y - collapsedBox!.y)).toBeLessThanOrEqual(1);
expect(Math.abs(expandedBox!.height - collapsedBox!.height)).toBeLessThanOrEqual(1);
// Search dock matches the collapsed provider card's outer rails, height, and text rail.
const searchContainer = page.getByTestId("model-search-all-input-container");
const searchInput = page.getByTestId("model-search-all-input");
const searchBox = await searchContainer.boundingBox();
const searchInputBox = await searchInput.boundingBox();
const collapsedCardBox = await readCollapsedCardGeometry(collapsedHeader);
expect(searchBox && searchInputBox && collapsedCardBox).toBeTruthy();
expect(Math.abs(searchBox!.x - collapsedCardBox!.cardX)).toBeLessThanOrEqual(1);
expect(Math.abs(searchBox!.width - collapsedCardBox!.cardWidth)).toBeLessThanOrEqual(1);
expect(Math.abs(searchBox!.height - collapsedCardBox!.cardHeight)).toBeLessThanOrEqual(1);
expect(Math.abs(searchInputBox!.x - collapsedCardBox!.labelX)).toBeLessThanOrEqual(2);
// Return Home, expand Profiles in place, and apply the profile.
await page.getByTestId("sheet-header-back").click();
await profilesToggle.click();
await page.getByTestId("model-picker-rail-profiles").click();
const sheetProfileRow = page.getByTestId("model-profile-row-agent_profile_e2e_arrows");
await expect(sheetProfileRow).toBeVisible();
await sheetProfileRow.click();
@@ -409,193 +373,8 @@ test.describe("Cross-provider model search", () => {
await provider.restore();
}
});
test("reopening a deep selected model lands at its scroll offset on the first paint on desktop and mobile", async ({
page,
}) => {
const provider = await seedModelProvider(LARGE_CATALOG);
const workspace = await seedWorkspace({ repoPrefix: "model-picker-initial-scroll-" });
try {
await gotoWorkspace(page, workspace.workspaceId);
await clickNewChat(page);
await expectComposerVisible(page);
// Select a model deep in the 200-item catalog.
await openModelPicker(page);
await searchAllModels(page, "bulk model 80");
await page
.getByTestId("combobox-desktop-container")
.getByTestId(`model-row-${LARGE_CATALOG.id}-bulk-80`)
.click();
await expect(page.getByTestId("combobox-desktop-container")).toHaveCount(0);
await test.step("desktop opens directly at the selected row without flashing scrollTop 0", async () => {
await startScrollSampling(page, "model-picker-model-list");
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
const samples = await readScrollSamples(page, "model-picker-model-list");
expect(samples[0]).toBeGreaterThan(0);
await expect(
page
.getByTestId("combobox-desktop-container")
.getByTestId(`model-row-${LARGE_CATALOG.id}-bulk-80`),
).toBeInViewport();
await closeModelPicker(page);
});
await test.step("mobile opens directly at the selected row without flashing scrollTop 0", async () => {
await page.setViewportSize({ width: 390, height: 800 });
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
await expect(page.getByTestId("agent-controls-model")).toBeVisible();
await startScrollSampling(page, "compact-model-list");
await page.getByTestId("agent-controls-model").click();
const samples = await readScrollSamples(page, "compact-model-list");
expect(samples[0]).toBeGreaterThan(0);
const listBox = await page.getByTestId("compact-model-list").boundingBox();
const rowBox = await page
.getByTestId(`model-row-${LARGE_CATALOG.id}-bulk-80`)
.boundingBox();
expect(listBox && rowBox).toBeTruthy();
expect(rowBox!.y).toBeGreaterThanOrEqual(listBox!.y - 1);
expect(rowBox!.y + rowBox!.height).toBeLessThanOrEqual(listBox!.y + listBox!.height + 1);
});
} finally {
await workspace.cleanup();
await provider.restore();
}
});
test("compact single-provider picker keeps its header fixed and scrolls to the last model row", async ({
page,
}) => {
const extraModels = Array.from({ length: 24 }, (_, index) => ({
id: `extra-scroll-${String(index).padStart(2, "0")}`,
label: `Extra scroll model ${String(index).padStart(2, "0")}`,
description: `Extra row ${index}`,
}));
const client = await connectDaemonClient<DaemonClient>({
clientIdPrefix: "single-provider-scroll",
});
const workspace = await seedMockAgentWorkspace({
repoPrefix: "single-provider-scroll-",
title: "Single provider scroll",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await client.patchDaemonConfig({
providers: {
mock: {
additionalModels: extraModels,
},
},
});
await page.setViewportSize({ width: 390, height: 800 });
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
await expect(page.getByTestId("agent-controls-model")).toBeVisible();
await page.getByTestId("agent-controls-model").click();
const list = page.getByTestId("compact-model-list");
await expect(list).toBeVisible();
const header = page.getByTestId("model-provider-section-mock");
await expect(header).toBeVisible();
const headerBox = await header.boundingBox();
expect(headerBox).toBeTruthy();
expect(headerBox!.height).toBeGreaterThanOrEqual(16);
// Scroll to the bottom of the lone provider's list and confirm the final row is fully in view.
await list.evaluate((node) => {
node.scrollTop = node.scrollHeight;
});
const lastRow = page.getByTestId("model-row-mock-extra-scroll-23");
await expect(lastRow).toBeVisible();
const listBox = await list.boundingBox();
const lastRowBox = await lastRow.boundingBox();
expect(listBox && lastRowBox).toBeTruthy();
expect(lastRowBox!.y + lastRowBox!.height).toBeLessThanOrEqual(
listBox!.y + listBox!.height + 1,
);
await lastRow.click();
await expect(page.getByTestId("agent-controls-model")).toContainText("Extra scroll model 23");
} finally {
await client
.patchDaemonConfig({
providers: {
mock: {
additionalModels: [],
},
},
})
.catch(() => undefined);
await client.close().catch(() => undefined);
await workspace.cleanup();
}
});
});
async function readCollapsedCardGeometry(collapsedHeader: ReturnType<Page["getByTestId"]>) {
return collapsedHeader.evaluate((node) => {
// Walk up from the press overlay to the SettingsCard container (2px taller for borders).
const header = node.parentElement;
const card = header?.parentElement?.parentElement;
const rect = card?.getBoundingClientRect();
const label = header?.querySelector('[dir="auto"]');
const labelRect = label?.getBoundingClientRect();
return rect && labelRect
? {
cardX: rect.x,
cardWidth: rect.width,
cardHeight: rect.height,
labelX: labelRect.x,
}
: null;
});
}
async function startScrollSampling(page: Page, listTestId: string): Promise<void> {
await page.evaluate((testId) => {
const samples: number[] = [];
const win = window as unknown as {
__scrollSamples?: number[];
__scrollObserver?: MutationObserver;
};
win.__scrollObserver?.disconnect();
win.__scrollSamples = samples;
const capture = (el: Element) => {
samples.push(el.scrollTop);
let remaining = 4;
const tick = () => {
const current = document.querySelector(`[data-testid="${testId}"]`);
if (current) samples.push(current.scrollTop);
remaining -= 1;
if (remaining > 0) requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
};
const observer = new MutationObserver(() => {
const el = document.querySelector(`[data-testid="${testId}"]`);
if (!el) return;
observer.disconnect();
capture(el);
});
win.__scrollObserver = observer;
observer.observe(document.body, { childList: true, subtree: true });
}, listTestId);
}
async function readScrollSamples(page: Page, listTestId: string): Promise<number[]> {
await expect(page.getByTestId(listTestId)).toBeVisible({ timeout: 10_000 });
const readSamples = () =>
page.evaluate(
() => (window as unknown as { __scrollSamples?: number[] }).__scrollSamples ?? [],
);
await expect.poll(async () => (await readSamples()).length).toBeGreaterThanOrEqual(2);
return readSamples();
}
async function setRuntimeCatalog(client: DaemonClient, count: number, cwd: string) {
await client.patchDaemonConfig({
providers: {
+28 -1
View File
@@ -10,6 +10,7 @@ import {
finishSetup,
goToSetupStep,
hostGivesAgentsPaseoTools,
hostToolGroups,
openAppAsNewUser,
openRelayPairingFromSetup,
closeRelayPairing,
@@ -24,6 +25,7 @@ import {
recordFirstLaunch,
setupModal,
setupPrimaryButton,
setHostTools,
setupSheet,
showSetupAgainFromSettings,
skipSetup,
@@ -426,6 +428,30 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
}
});
test("setup offers only Enable tools and keeps the host's tool groups", async ({ page }) => {
const host = await startSetupHost("tool-groups");
try {
await setHostTools(host, { groups: { schedules: false, browser: true } });
await openAppAsNewUser(page, host);
await expectSetupStep(page, "Welcome to Paseo");
await goToSetupStep(page, "Orchestration");
await expectSetupStep(page, "Let agents use Paseo");
await expect(paseoToolsSwitch(setupModal(page))).toBeChecked();
// Setup offers only the main switch; tool groups live in Settings.
await expect(
setupModal(page).getByRole("switch", { name: "Browser", exact: true }),
).toHaveCount(0);
await continueSetup(page);
await expectSetupStep(page, "Take your agents with you");
await expect.poll(() => hostGivesAgentsPaseoTools(host), { timeout: 30_000 }).toBe(true);
expect(await hostToolGroups(host)).toMatchObject({ schedules: false, browser: true });
} finally {
await host.close();
}
});
test("with no skills picked, skills read as off and Continue moves on", async ({ page }) => {
const host = await startSetupHost("no-skills");
@@ -463,6 +489,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
const primary = (label: string) => page.getByRole("button", { name: label, exact: true });
try {
await setHostTools(host, { enabled: false });
await openAppAsNewUser(page, host);
await step("Welcome to Paseo");
await primary("Continue").click();
@@ -471,7 +498,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
await step("Add your projects");
await primary("Continue").click();
// The setup host starts with Paseo tools off; the switch starts on.
// The host has tools off; the setup switch still starts on.
expect(await hostGivesAgentsPaseoTools(host)).toBe(false);
await step("Let agents use Paseo");
await expect(paseoToolsSwitch(page)).toBeChecked();
@@ -1,324 +0,0 @@
import { writeFile } from "node:fs/promises";
import path from "node:path";
import type { Locator } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { openCommandCenter } from "../support/helpers/command-center";
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
import { submitMessageWithButton } from "../support/helpers/composer";
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { runCommand } from "../support/helpers/plugin-sidebar-items";
import {
closeSheet,
expectNoSheetOpen,
expectOneSheetOpen,
promptMentioning,
sheet,
} from "../support/helpers/sheet";
import {
closeMobileExplorer,
expectMobileExplorerHidden,
expectMobileExplorerVisible,
openMobileAgentSidebar,
selectWorkspaceInSidebar,
} from "../support/helpers/sidebar";
import { getServerId } from "../support/helpers/server-id";
const WIDE = { width: 1600, height: 900 };
const COMPACT = { width: 390, height: 844 };
const AGENT_TITLE = "Layout agent";
const FILE_LINK = "README.md:1";
const NO_FILE = "Focus a file to see its outline";
const REPO_FILES = [
{ path: "README.md", content: "# Guide\n\n## Install\n" },
{ path: "notes.md", content: "# Notes\n\n## Open questions\n" },
{ path: "src/app.ts", content: "// TODO: handle errors\nexport const ready = true;\n" },
];
const REVIEW_TAB = "workspace-tab-plugin_agent_16_workspace-layout_6_review_";
const FINDINGS_TAB = "workspace-tab-plugin_workspace_16_workspace-layout_8_findings";
const OUTLINE_TAB = "workspace-tab-plugin_workspace_16_workspace-layout_7_outline";
async function withLayoutExample(
initialPrompt: string | undefined,
run: (agent: { agentId: string; workspaceId: string }) => Promise<void>,
): Promise<void> {
const example = await copyPluginExample("workspace-layout");
const workspace = await seedMockAgentWorkspace({
repoPrefix: "plugin-workspace-layout-",
title: AGENT_TITLE,
repo: { files: REPO_FILES },
initialPrompt,
});
try {
await withPluginInstalled(example.directory, () => run(workspace));
} finally {
await workspace.cleanup();
await example.cleanup();
}
}
async function withPluginInstalled(directory: string, run: () => Promise<void>): Promise<void> {
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previous = await client.getDaemonConfig();
try {
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await run();
} finally {
await client.removePlugin("workspace-layout").catch(() => undefined);
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false });
await client.close();
}
}
/** `/open-elsewhere <id>` opens a file in that workspace, then one where the command ran. */
const OPEN_ELSEWHERE_ENTRY = `import type { PluginClientContext } from "@getpaseo/plugin/client";
export default function contribute(client: PluginClientContext) {
client.addSlashCommand({
name: "open-elsewhere",
description: "Open a file there, then one here",
argumentHint: "<workspaceId>",
context: "agent",
onSubmit({ args, workspaceLayout }) {
const there = client.workspaceLayout(args.trim());
there.open({ panelId: "paseo/file", params: { path: "README.md" } });
workspaceLayout.open({ panelId: "paseo/file", params: { path: "notes.md" } });
},
});
return () => {};
}
`;
async function withTwoWorkspaces(
run: (workspaces: {
first: { agentId: string; workspaceId: string };
second: { agentId: string; workspaceId: string };
}) => Promise<void>,
): Promise<void> {
const example = await copyPluginExample("workspace-layout");
await writeFile(path.join(example.directory, "index.client.tsx"), OPEN_ELSEWHERE_ENTRY);
const seed = (title: string) =>
seedMockAgentWorkspace({
repoPrefix: "plugin-workspace-layout-",
title,
repo: { files: REPO_FILES },
});
const first = await seed("First agent");
const second = await seed("Second agent");
try {
await withPluginInstalled(example.directory, () => run({ first, second }));
} finally {
await second.cleanup();
await first.cleanup();
await example.cleanup();
}
}
/** Picks a workspace in a phone's agent list. */
async function switchToWorkspace(page: Page, workspaceId: string): Promise<void> {
await openMobileAgentSidebar(page);
await selectWorkspaceInSidebar(page, workspaceId);
await expect(
page.getByTestId(`workspace-deck-entry-${getServerId()}:${workspaceId}`),
).toBeVisible();
await expect(composerIn(page.locator("body"))).toBeEditable({ timeout: 30_000 });
}
function mainPanes(page: Page): Locator {
return page.locator('[data-testid^="workspace-pane-"]').filter({ visible: true });
}
function explorer(page: Page): Locator {
return page.getByTestId("workspace-explorer-sidebar");
}
function agentTabs(scope: Locator): Locator {
return scope.locator('[data-testid^="workspace-tab-agent_"]');
}
function composerIn(scope: Locator): Locator {
return scope.getByRole("textbox", { name: "Message agent..." }).filter({ visible: true });
}
async function sendToMainChat(page: Page, text: string): Promise<void> {
const composer = composerIn(mainPanes(page).first());
await expect(composer).toBeEditable({ timeout: 30_000 });
await composer.fill(text);
await composer.press("Enter");
}
async function expectAsideChat(page: Page, input: { message: string; tabs: number }) {
const chats = agentTabs(explorer(page));
await expect(chats).toHaveCount(input.tabs, { timeout: 30_000 });
await expect(chats.last()).toHaveAttribute("aria-selected", "true");
await expect(
explorer(page).getByTestId("user-message").getByText(input.message, { exact: true }),
).toBeVisible();
await expect(composerIn(explorer(page))).toBeEditable();
}
/** Every visible tab chip, pane by pane, to compare the arrangement before and after. */
async function tabsByPane(page: Page): Promise<string[][]> {
const scopes = [...(await mainPanes(page).all()), explorer(page)];
return Promise.all(
scopes.map((scope) =>
scope
.getByTestId("workspace-tabs-row")
.locator('[data-testid^="workspace-tab-"]:not([data-testid^="workspace-tab-tooltip"])')
.evaluateAll((chips) => chips.map((chip) => chip.getAttribute("data-testid") ?? "")),
),
);
}
async function expectReviewLayout(page: Page, agentId: string): Promise<void> {
await expect(mainPanes(page)).toHaveCount(2);
const left = mainPanes(page).first();
const right = mainPanes(page).last();
await expect(left.getByTestId(`workspace-tab-agent_${agentId}`)).toBeVisible();
const review = right.getByTestId(`${REVIEW_TAB}${agentId.length}_${agentId}`);
await expect(review).toHaveAttribute("aria-selected", "true");
await expect(right.getByText(`Reviewing ${AGENT_TITLE}`, { exact: true })).toBeVisible();
await expect(right.getByTestId("workspace-tab-working_diff")).toHaveAttribute(
"aria-selected",
"false",
);
await expect(explorer(page).getByTestId(FINDINGS_TAB)).toBeVisible();
const [leftBox, rightBox] = [await left.boundingBox(), await right.boundingBox()];
if (!leftBox || !rightBox) throw new Error("Review layout panes have no bounds");
expect(rightBox.x).toBeGreaterThan(leftBox.x);
expect(rightBox.width / (leftBox.width + rightBox.width)).toBeCloseTo(0.4, 1);
}
async function openFileInFocusedPane(page: Page, name: string): Promise<void> {
await openFileExplorer(page);
await openFileFromExplorer(page, name);
await expect(mainPanes(page).getByTestId(`workspace-tab-file_${name}`)).toBeVisible();
}
async function expectOutline(page: Page, lines: string[]): Promise<void> {
const outline = page.getByTestId("workspace-layout-outline");
for (const line of lines) {
await expect(outline.getByText(line, { exact: true })).toHaveCount(1);
}
}
test("the workspace layout example arranges a wide workspace", async ({ page }) => {
test.setTimeout(180_000);
await withLayoutExample(undefined, async ({ agentId, workspaceId }) => {
await page.setViewportSize(WIDE);
await openAgentRoute(page, { workspaceId, agentId });
await test.step("/aside opens the child agent's chat in the Explorer", async () => {
await sendToMainChat(page, "/aside hey");
await expectAsideChat(page, { message: "hey", tabs: 1 });
await expect(agentTabs(mainPanes(page))).toHaveCount(1);
});
await test.step("a second /aside adds a second tab", async () => {
await sendToMainChat(page, "/aside again");
await expectAsideChat(page, { message: "again", tabs: 2 });
await expect(agentTabs(mainPanes(page))).toHaveCount(1);
});
await test.step("Review layout splits the workspace, and running it again changes nothing", async () => {
await runCommand(page, "Review layout");
await expectReviewLayout(page, agentId);
const arranged = await tabsByPane(page);
await mainPanes(page).first().getByTestId(`workspace-tab-agent_${agentId}`).click();
await runCommand(page, "Review layout");
await expectReviewLayout(page, agentId);
expect(await tabsByPane(page)).toEqual(arranged);
});
await test.step("the outline follows the focused file across split panes", async () => {
await mainPanes(page).first().getByTestId(`workspace-tab-agent_${agentId}`).click();
await runCommand(page, "Show outline");
await expectOutline(page, [NO_FILE]);
await openFileInFocusedPane(page, "README.md");
await explorer(page).getByTestId(OUTLINE_TAB).click();
await expectOutline(page, ["README.md", "Guide", "Install"]);
await runWorkspaceActionFromCommandCenter(page, "Split pane right");
await expect(mainPanes(page)).toHaveCount(3);
await openFileInFocusedPane(page, "notes.md");
await explorer(page).getByTestId(OUTLINE_TAB).click();
await expectOutline(page, ["notes.md", "Notes", "Open questions"]);
await mainPanes(page).getByTestId("workspace-tab-file_README.md").click();
await expectOutline(page, ["README.md", "Guide", "Install"]);
});
});
});
test("the workspace layout example opens over a phone's chat", async ({ page }) => {
test.setTimeout(180_000);
await withLayoutExample(promptMentioning(FILE_LINK), async ({ agentId, workspaceId }) => {
await page.setViewportSize(COMPACT);
await openAgentRoute(page, { workspaceId, agentId });
await test.step("/aside opens the Explorer over the chat", async () => {
await submitMessageWithButton(page, "/aside hey");
await expectMobileExplorerVisible(page);
await expectAsideChat(page, { message: "hey", tabs: 1 });
await closeMobileExplorer(page);
await expectMobileExplorerHidden(page);
await expect(
page.getByRole("button", { name: "Switch tabs (1 open)" }).filter({ visible: true }),
).toBeVisible();
});
await test.step("a file sheet updates the outline, and closing it restores it", async () => {
await openMobileAgentSidebar(page);
const commandCenter = await openCommandCenter(page);
await commandCenter.getByTestId("command-center-input").fill("Show outline");
await commandCenter.getByRole("button", { name: "Show outline", exact: true }).click();
await expectMobileExplorerVisible(page);
await expectOutline(page, [NO_FILE]);
await closeMobileExplorer(page);
await expectMobileExplorerHidden(page);
await page.getByText(FILE_LINK, { exact: true }).first().click();
await expect(sheet(page, "README.md")).toBeVisible();
// The sheet covers the Explorer, so the outline can only be read, not seen.
await expectOutline(page, ["README.md", "Guide", "Install"]);
await closeSheet(page, "README.md");
await expectOutline(page, [NO_FILE]);
});
});
});
test("a file a plugin opens in another workspace waits there on a phone", async ({ page }) => {
test.setTimeout(180_000);
await withTwoWorkspaces(async ({ first, second }) => {
await page.setViewportSize(COMPACT);
// Visiting the first workspace leaves its screen mounted behind the second.
await openAgentRoute(page, first);
await expect(composerIn(page.locator("body"))).toBeEditable({ timeout: 30_000 });
await switchToWorkspace(page, second.workspaceId);
await test.step("only the sheet of the workspace on screen is shown", async () => {
await submitMessageWithButton(page, `/open-elsewhere ${first.workspaceId}`);
await expect(sheet(page, "notes.md")).toBeVisible();
await expectOneSheetOpen(page);
await closeSheet(page, "notes.md");
await expectNoSheetOpen(page);
});
await test.step("the other sheet is there when the user goes to its workspace", async () => {
await switchToWorkspace(page, first.workspaceId);
await expect(sheet(page, "README.md")).toBeVisible();
await expectOneSheetOpen(page);
await closeSheet(page, "README.md");
await expectNoSheetOpen(page);
});
});
});
@@ -1,34 +0,0 @@
import { BuiltinPluginLoader } from "../../../../server/src/server/plugins/builtin/index.js";
import { createTestPaseoDaemon } from "../../../../server/src/server/test-utils/paseo-daemon.js";
import { DaemonClient } from "../../../../server/src/server/test-utils/daemon-client.js";
import assert from "node:assert/strict";
import pino from "pino";
const [, , root, origin, paseoHomeRoot, daemonVersion] = process.argv;
const daemon = await createTestPaseoDaemon({
corsAllowedOrigins: [origin!],
paseoHomeRoot,
daemonVersion,
logger: pino({ level: "error" }),
builtinPlugins: new BuiltinPluginLoader(root, ["builtin-settings"]),
});
const client = new DaemonClient({
appVersion: daemonVersion,
url: `ws://127.0.0.1:${daemon.port}/ws`,
});
try {
await client.connect();
const plugin = (await client.getPluginCatalog()).find(({ id }) => id === "builtin-settings");
assert.ok(plugin?.clientBundle, JSON.stringify(await client.getPluginLogs("builtin-settings")));
assert.deepEqual(await client.listPlugins(), []);
process.send!({ serverId: client.getLastServerInfoMessage()!.serverId, port: daemon.port });
await new Promise<void>((resolve) => {
process.once("disconnect", resolve);
process.once("SIGTERM", resolve);
});
} finally {
await client.close();
await daemon.close();
}
@@ -1,24 +0,0 @@
# Native SVG preview regression
Copy `../fixtures/native-preview.svg`, `../fixtures/native-preview-viewbox.svg`, and
`../../../assets/images/icon.png` into a workspace on a test daemon. In the Android
or iOS app, connect to that daemon, open the workspace's Files tab, and tap
`native-preview.svg`. The SVG should show a yellow circle on a green rectangle.
With that preview open, run:
```sh
agent-device test packages/app/e2e/mobile/agent-device/native-svg-preview.android.ad \
--metro-port <port> --artifacts-dir .artifacts/svg-preview
```
Run it again with `native-preview-viewbox.svg` open to cover SVG dimensions
inferred from `viewBox`, then with the PNG open to check raster images. Close and
reopen the SVG and rerun to cover cached file previews. Use English app language
for the zoom button selectors. The scripts are discovered by `npm run test:e2e:mobile`; the iOS counterpart is
`native-svg-preview.ios.ad`. They reopen the installed app with its current
preview and leave the daemon connection unchanged.
Before the fix the SVG remains blank and the canvas wait fails. The PNG passes.
The replay checks successful native dimension decoding and zoom/reset controls;
visually verify the circle and rectangle as well.
@@ -1,11 +0,0 @@
context platform=android timeout=60000 retries=0
env APP_ID=sh.paseo.debug
open "${APP_ID}"
wait "id=\"image-file-preview-canvas\"" 10000
wait "role=button label=\"Zoom in\"" 10000
press "role=button label=\"Zoom in\""
wait "role=button label=\"Reset view\" enabled=true" 10000
press "role=button label=\"Reset view\""
wait "role=button label=\"Reset view\" enabled=false" 10000
close
@@ -1,11 +0,0 @@
context platform=ios timeout=60000 retries=0
env APP_ID=sh.paseo.debug
open "${APP_ID}"
wait "id=\"image-file-preview-canvas\"" 10000
wait "role=button label=\"Zoom in\"" 10000
press "role=button label=\"Zoom in\""
wait "role=button label=\"Reset view\" enabled=true" 10000
press "role=button label=\"Reset view\""
wait "role=button label=\"Reset view\" enabled=false" 10000
close
@@ -317,80 +317,6 @@ async function runBoundedPreview() {
await runCase("preview", "files", fileCase);
}
// A finger drifts a few points during a tap, so tap the composer's controls with a
// short drag while the keyboard is open. The model picker must open, and on a wide
// layout its popover must end above the keyboard.
function dragTap(rect) {
ad(
"gesture",
"pan",
String(Math.round(rect.x + rect.width / 2)),
String(Math.round(rect.y + rect.height / 2)),
"0",
"3",
"120",
);
}
// Waits until the keyboard is shown and the node with `id` stops moving.
async function settledWithKeyboard(name, id) {
let previousTop;
return waitFor(name, (snap) => {
const node = nodeById(snap, id);
if (!node || !keyboardShown(snap)) return false;
const stable = node.rect.y === previousTop;
previousTop = node.rect.y;
return stable;
});
}
const keyboardTop = (snap) =>
snap.data.nodes.find((node) => node.type === "Keyboard" && node.rect).rect.y;
async function runControlTaps() {
await clearInput("controls");
const attach = nodeById(
await settledWithKeyboard("controls-attach-before", "message-input-root"),
"message-input-attach-button",
);
dragTap(attach.rect);
// Wide layouts show the attachment menu as a popover and phones as a sheet; both list the items.
await waitFor("controls-attach-menu", (snap) =>
Boolean(nodeById(snap, "message-input-attachment-menu-item-file")),
);
process.stdout.write("PASS drag tap on attach opened the attachment menu\n");
// The open menu hides the composer from accessibility. Its backdrop covers the top-left corner.
ad("press", "20", "120");
await waitFor("controls-attach-closed", (snap) => Boolean(nodeById(snap, "message-input-root")));
await clearInput("controls-model");
const trigger = nodeById(
await settledWithKeyboard("controls-model-before", "message-input-root"),
"combined-model-selector",
);
dragTap(trigger.rect);
const sheetOpen = (snap) =>
snap.data.nodes.some((node) => node.type === "Button" && node.label === "Close");
const opened = await waitFor(
"controls-model-picker",
(snap) => Boolean(nodeById(snap, "combobox-desktop-container")) || sheetOpen(snap),
);
process.stdout.write("PASS drag tap on the model selector opened the picker\n");
if (!nodeById(opened, "combobox-desktop-container")) return;
const settled = await settledWithKeyboard("controls-model-popover", "combobox-desktop-container");
const frame = nodeById(settled, "combobox-desktop-container").rect;
const bottom = frame.y + frame.height;
const covered = frame.y < trigger.rect.y + trigger.rect.height && bottom > trigger.rect.y;
if (covered || bottom > keyboardTop(settled) + 1) {
throw new Error(
`Model popover spans ${Math.round(frame.y)}-${Math.round(bottom)}; it must clear the trigger at ${Math.round(trigger.rect.y)} and the keyboard at ${Math.round(keyboardTop(settled))}`,
);
}
process.stdout.write(
`PASS model popover ${Math.round(frame.y)}-${Math.round(bottom)} clears the trigger and the keyboard\n`,
);
}
if (scenario !== "all") {
ad(
"open",
@@ -402,7 +328,6 @@ if (scenario !== "all") {
await waitFor("draft", (snap) => Boolean(nodeById(snap, "message-input-root")), 60_000);
if (scenario === "growth") await runLiveGrowth();
else if (scenario === "previews") await runBoundedPreview();
else if (scenario === "controls") await runControlTaps();
else throw new Error(`Unknown scenario: ${scenario}`);
process.stdout.write(`Composer ${scenario} regression passed. Artifacts: ${artifactsDir}\n`);
process.exit(0);
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 160"><rect width="240" height="160" fill="#08a040"/><circle cx="120" cy="80" r="50" fill="#ffcc00"/></svg>

Before

Width:  |  Height:  |  Size: 164 B

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="240" height="160" viewBox="0 0 240 160"><rect width="240" height="160" fill="#08a040"/><circle cx="120" cy="80" r="50" fill="#ffcc00"/></svg>

Before

Width:  |  Height:  |  Size: 188 B

@@ -603,12 +603,9 @@ export function profilePickerRow(page: Page, name: string): Locator {
.filter({ hasText: name });
}
/** Multi-provider desktop keeps profiles behind the rail; single-pane lists them inline. */
/** Desktop keeps profiles behind the rail's Profiles entry, beside the providers. */
export async function openPickerProfiles(page: Page): Promise<void> {
const rail = pickerViewport(page).getByTestId("model-picker-rail-profiles");
if (await rail.isVisible().catch(() => false)) {
await rail.click();
}
await pickerViewport(page).getByTestId("model-picker-rail-profiles").click();
}
export async function expectPickerProfile(
@@ -627,8 +624,7 @@ export async function expectProfilesEditLink(page: Page): Promise<void> {
exact: true,
});
await expect(edit).toBeVisible();
await expect(edit).toHaveText("");
await expect(edit.locator("svg")).toBeVisible();
await expect(edit).toHaveText("Edit");
}
/** With no profiles, the Profiles entry offers to create one instead of listing any. */
@@ -1,77 +0,0 @@
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { once } from "node:events";
import { spawnTsx, killProcessTree } from "./spawn-node";
import appPackage from "../../../package.json";
import { expect, test as base, type Page } from "../fixtures";
import { gotoAppShell } from "./app";
import { addConnectedHostAndReload } from "./hosts";
import { pluginRequirements } from "./plugin-fixture";
const pluginId = "builtin-settings";
const screenId = "general";
const settingsText = "Built-in settings body";
export const test = base.extend<{ builtinSettingsHost: { serverId: string; port: number } }>({
builtinSettingsHost: async ({ baseURL }, provide, testInfo) => {
const root = testInfo.outputPath("builtin-plugins");
const directory = path.join(root, pluginId);
await mkdir(directory, { recursive: true });
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: pluginId, requirements: pluginRequirements }),
);
await writeFile(
path.join(directory, "index.client.tsx"),
`import React from "react";
import { Text } from "react-native";
export default function contribute(client) {
client.addSettingsScreen({
id: "${screenId}",
title: "General",
icon: "SlidersHorizontal",
Component: () => <Text>${settingsText}</Text>,
});
return () => {};
}`,
);
await writeFile(
path.join(directory, "index.server.ts"),
"export default function contribute() { return () => {}; }",
);
const daemon = spawnTsx(
path.resolve(__dirname, "../../fixtures/builtin-settings/daemon.mts"),
[root, new URL(baseURL!).origin, testInfo.outputPath("daemon"), appPackage.version],
{ stdio: ["ignore", "inherit", "inherit", "ipc"] },
);
try {
const [host] = await Promise.race([
once(daemon, "message") as Promise<[{ serverId: string; port: number }]>,
once(daemon, "exit").then(([code]) => {
throw new Error(`Built-in settings daemon exited with code ${code}`);
}),
]);
await provide(host);
} finally {
await killProcessTree(daemon);
}
},
});
export async function openBuiltinPluginSettings(
page: Page,
host: { serverId: string; port: number },
) {
await gotoAppShell(page);
await addConnectedHostAndReload(page, {
...host,
label: "Built-in settings host",
destination: `/settings/hosts/${host.serverId}/plugins/${pluginId}/${screenId}`,
});
}
export async function expectBuiltinPluginSettings(page: Page) {
await expect(page.getByText(settingsText, { exact: true })).toBeVisible();
await expect(page.getByRole("switch", { name: /: Disable$/ })).toHaveCount(0);
}
+4 -14
View File
@@ -76,24 +76,15 @@ export async function addOfflineHostsAndReload(
export async function addConnectedHostAndReload(
page: Page,
input: {
serverId: string;
label: string;
port: number;
primaryLabel?: string;
destination?: string;
},
input: { serverId: string; label: string; port: number; primaryLabel?: string },
): Promise<void> {
await addConnectedHostsAndReload(page, [input], {
primaryLabel: input.primaryLabel,
destination: input.destination,
});
await addConnectedHostsAndReload(page, [input], { primaryLabel: input.primaryLabel });
}
export async function addConnectedHostsAndReload(
page: Page,
inputs: Array<{ serverId: string; label: string; port: number }>,
options?: { primaryLabel?: string; destination?: string },
options?: { primaryLabel?: string },
): Promise<void> {
const connectedHosts = inputs.map((input) =>
buildSeededHost({
@@ -132,8 +123,7 @@ export async function addConnectedHostsAndReload(
},
);
if (options?.destination) await page.goto(options.destination);
else await page.reload();
await page.reload();
}
export async function waitForConnectedHost(
+36 -2
View File
@@ -4,6 +4,10 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client";
import type {
MutableDaemonToolGroups,
MutableDaemonToolsConfigPatch,
} from "@getpaseo/protocol/messages";
import { addProjectFlow, addProjectFlowInput, expectAddProjectTab } from "./add-project-flow";
import { connectDaemonClient } from "./daemon-client-loader";
import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry";
@@ -138,7 +142,7 @@ export async function goToSetupStep(page: Page, label: string): Promise<void> {
}
export function paseoToolsSwitch(scope: Page | Locator): Locator {
return scope.getByRole("switch", { name: "Inject Paseo tools", exact: true });
return scope.getByRole("switch", { name: "Enable tools", exact: true });
}
/** Whether the host gives its agents Paseo tools, read from the host itself. */
@@ -147,7 +151,37 @@ export async function hostGivesAgentsPaseoTools(host: { port: number }): Promise
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
return (await client.getDaemonConfig()).config.mcp.injectIntoAgents !== false;
const config = (await client.getDaemonConfig()).config;
return config.tools?.enabled ?? config.mcp.injectIntoAgents !== false;
} finally {
await client.close();
}
}
/** The host's saved tool groups, read from the host itself. */
export async function hostToolGroups(host: {
port: number;
}): Promise<MutableDaemonToolGroups | undefined> {
const client = await connectDaemonClient<
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
return (await client.getDaemonConfig()).config.tools?.groups;
} finally {
await client.close();
}
}
/** Saves tool settings on the host, the way Settings does. */
export async function setHostTools(
host: { port: number },
tools: MutableDaemonToolsConfigPatch,
): Promise<void> {
const client = await connectDaemonClient<
Pick<InternalDaemonClient, "connect" | "close" | "patchDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
await client.patchDaemonConfig({ tools });
} finally {
await client.close();
}
+1 -1
View File
@@ -480,7 +480,7 @@ export async function expectHostConnectionsCard(page: Page, port: string): Promi
export async function expectHostInjectMcpCard(page: Page): Promise<void> {
const card = page.getByTestId("host-page-inject-mcp-card");
await expect(card).toBeVisible();
await expect(card.getByRole("switch", { name: "Inject Paseo tools" })).toBeVisible();
await expect(card.getByRole("switch", { name: "Enable tools" })).toBeVisible();
}
function idleAgentReleaseSwitch(page: Page) {
+14 -3
View File
@@ -3,12 +3,9 @@ import { useTranslation } from "react-i18next";
import { i18n } from "@/i18n/i18next";
import { useProviderIcon } from "@/components/provider-icons";
import type { PanelDescriptor } from "@/panels/panel-registry";
import { resolveAgentLabel } from "@/panels/tab-labels";
import { useSessionStore, selectAgentTurnPresentation, type Agent } from "@/stores/session-store";
import { deriveSidebarStateBucket } from "@/utils/sidebar-agent-state";
export { resolveAgentLabel };
function formatProviderLabel(provider: Agent["provider"]): string {
if (!provider) {
return "Agent";
@@ -20,6 +17,20 @@ function formatProviderLabel(provider: Agent["provider"]): string {
.join(" ");
}
export function resolveAgentLabel(title: string | null | undefined): string | null {
if (typeof title !== "string") {
return null;
}
const normalized = title.trim();
if (!normalized) {
return null;
}
if (normalized.toLowerCase() === "new agent") {
return null;
}
return normalized;
}
export function useAgentDescriptor(
target: { kind: "agent"; agentId: string },
context: { serverId: string },
-2
View File
@@ -78,7 +78,6 @@ import { HorizontalScrollProvider } from "@/contexts/horizontal-scroll-context";
import { SessionProvider } from "@/contexts/session-context";
import { SidebarCalloutProvider } from "@/contexts/sidebar-callout-context";
import { ToastProvider } from "@/contexts/toast-context";
import { WorkspaceTabCloseErrorToasts } from "@/workspace-tabs/close";
import { VoiceProvider } from "@/contexts/voice-context";
import {
resolveStartupBlocker,
@@ -1004,7 +1003,6 @@ function RootOverlayProviders({ children }: { children: ReactNode }) {
<BottomSheetModalProvider>
{children}
<WindowLayoutActionsHost />
<WorkspaceTabCloseErrorToasts />
</BottomSheetModalProvider>
</PortalProvider>
</ToastProvider>
@@ -5,7 +5,6 @@ import {
encodeAttachmentsForSend,
garbageCollectAttachments,
persistAttachmentFromBytes,
prepareImageAttachmentsForSend,
uploadImageAttachments,
} from "./service";
@@ -221,71 +220,4 @@ describe("attachment service", () => {
},
]);
});
it("uses file.upload.request when daemon advertises uploadedImageAttachments and falls back to inline base64 images on legacy daemons", async () => {
const store = createRecordingStore();
__setAttachmentStoreForTests(store);
const attachment = createAttachment({
id: "img-compat",
fileName: "photo.jpg",
mimeType: "image/jpeg",
});
const uploadCalls: string[] = [];
const modernClient = {
getLastServerInfoMessage: () => ({ features: { uploadedImageAttachments: true } }),
uploadFile: async (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => {
uploadCalls.push(input.fileName);
return {
requestId: "req-modern",
file: {
type: "uploaded_file" as const,
id: "upload_photo",
fileName: input.fileName,
mimeType: input.mimeType,
size: input.bytes.byteLength,
path: "/home/user/.paseo/uploads/upload_photo/photo.jpg",
},
error: null,
};
},
};
const modernResult = await prepareImageAttachmentsForSend({
client: modernClient,
images: [attachment],
});
expect(uploadCalls).toEqual(["photo.jpg"]);
expect(modernResult).toEqual({
attachments: [
{
type: "uploaded_file",
id: "upload_photo",
fileName: "photo.jpg",
mimeType: "image/jpeg",
size: new TextEncoder().encode("img-compat:bytes").byteLength,
path: "/home/user/.paseo/uploads/upload_photo/photo.jpg",
role: "image",
},
],
});
const legacyUploadCalls: string[] = [];
const legacyClient = {
getLastServerInfoMessage: () => ({ features: {} }),
uploadFile: async (input: { fileName: string }) => {
legacyUploadCalls.push(input.fileName);
throw new Error("uploadFile must not be called for legacy daemon image sends");
},
};
const legacyResult = await prepareImageAttachmentsForSend({
client: legacyClient,
images: [attachment],
});
expect(legacyUploadCalls).toEqual([]);
expect(legacyResult).toEqual({
images: [{ data: "img-compat:base64", mimeType: "image/jpeg" }],
});
});
});
+3 -39
View File
@@ -152,15 +152,6 @@ export interface ImageUploadClient {
}>;
}
export interface ImageSendClient extends ImageUploadClient {
getLastServerInfoMessage: () => { features?: { uploadedImageAttachments?: boolean } } | null;
}
export interface PreparedImagePayload {
images?: Array<{ data: string; mimeType: string }>;
attachments?: UploadedFileAttachment[];
}
export async function readAttachmentBytes(attachment: AttachmentMetadata): Promise<Uint8Array> {
const store = await getAttachmentStore();
return await store.readBytes({ attachment });
@@ -169,8 +160,9 @@ export async function readAttachmentBytes(attachment: AttachmentMetadata): Promi
/**
* Uploads persisted image attachments sequentially via `file.upload.request` so multi-photo
* batches drain cleanly between files instead of queueing concurrently on mobile sockets.
* Each uploaded image is marked with `role: "image"` inside `uploaded_file` so capable daemons
* resolve it into a native vision block + timeline thumbnail.
* Each uploaded image is marked with `role: "image"` inside `uploaded_file` so current daemons
* resolve it into a native vision block + timeline thumbnail, while older daemons (v0.1.91-v0.18.1)
* strip the unknown `role` field and still deliver the uploaded file path instead of dropping it.
*/
export async function uploadImageAttachments(input: {
client: ImageUploadClient;
@@ -204,34 +196,6 @@ export async function uploadImageAttachments(input: {
return uploaded;
}
/**
* Prepares image attachments for agent prompt/create RPCs.
*
* Hosts advertising `server_info.features.uploadedImageAttachments` receive sequential
* `file.upload.request` uploads tagged with `role: "image"`. Older hosts strip `role: "image"`
* and degrade the upload to plain file-path text, so they keep receiving inline base64 `images`.
*/
export async function prepareImageAttachmentsForSend(input: {
client: ImageSendClient;
images: readonly AttachmentMetadata[] | undefined;
}): Promise<PreparedImagePayload> {
if (!input.images || input.images.length === 0) {
return {};
}
// COMPAT(uploadedImageAttachments): added in v0.18.2, remove gate after 2027-06-01.
if (input.client.getLastServerInfoMessage()?.features?.uploadedImageAttachments === true) {
const attachments = await uploadImageAttachments({
client: input.client,
images: input.images,
});
return attachments ? { attachments } : {};
}
const images = await encodeAttachmentsForSend(input.images);
return images ? { images } : {};
}
export async function resolveAttachmentPreviewUrl(attachment: AttachmentMetadata): Promise<string> {
const store = await getAttachmentStore();
return await store.resolvePreviewUrl({ attachment });
@@ -14,7 +14,6 @@ import {
import { ModelProviderGlyph, useSelectedModelLabels } from "@/components/model-browser";
import { DesktopModelPicker, type ModelPickerActions } from "@/components/model-browser-panes";
import {
getSheetSearchFooterStyle,
MobileModelPageView,
SheetSearchDock,
useMobileModelPage,
@@ -314,7 +313,6 @@ function CompactCombinedModelSelector({
snapPoints={SHEET_SNAP_POINTS}
scrollable={false}
footer={footer}
footerContainerStyle={getSheetSearchFooterStyle()}
keyboard={keyboard}
contentStyle={styles.sheetBody}
testID="model-selector-sheet"
@@ -134,15 +134,17 @@ describe("mobile model page", () => {
providerId: section.providerId,
status: section.status,
expanded: section.expanded,
shown: section.shown,
total: section.total,
}
: section,
),
).toEqual([
{ providerId: "claude", status: "ready", expanded: true },
{ providerId: "codex", status: "ready", expanded: false },
{ providerId: "opencode", status: "loading", expanded: false },
{ providerId: "pi", status: "ready", expanded: false },
{ providerId: "copilot", status: "error", expanded: false },
{ providerId: "claude", status: "ready", expanded: true, shown: 4, total: 19 },
{ providerId: "codex", status: "ready", expanded: false, shown: 2, total: 2 },
{ providerId: "opencode", status: "loading", expanded: false, shown: 0, total: 0 },
{ providerId: "pi", status: "ready", expanded: false, shown: 2, total: 4 },
{ providerId: "copilot", status: "error", expanded: false, shown: 0, total: 0 },
]);
});
@@ -152,26 +154,12 @@ describe("mobile model page", () => {
expect(projection.sections[0]).toEqual({
kind: "profiles",
key: MODEL_PICKER_PROFILES_RAIL_KEY,
count: 2,
expanded: false,
});
expect(projection.sections.find((section) => section.expanded)?.key).toBe("claude");
});
it("omits the Profiles accordion when extracted to Home, while still searching profiles", () => {
const extractedInput: MobileModelPageInput = {
...inputWithProfiles,
showProfilesSection: false,
};
const browsed = browse(project([], extractedInput));
expect(browsed.sections.map((section) => section.key)).not.toContain(
MODEL_PICKER_PROFILES_RAIL_KEY,
);
const searched = project([{ kind: "query", query: "reviewer" }], extractedInput);
expect(searched.kind).toBe("search");
if (searched.kind !== "search") return;
expect(searched.profiles.map((item) => item.key)).toEqual(["profile:reviewer"]);
});
it("expands Profiles to list saved profiles, or Create profile when there are none", () => {
const expanded = browse(
project([{ kind: "toggleSection", key: MODEL_PICKER_PROFILES_RAIL_KEY }], inputWithProfiles),
@@ -1,27 +1,24 @@
import {
createModelPickerState,
MODEL_PICKER_PROFILES_RAIL_KEY,
orderProvidersForPicker,
projectModelPicker,
type ModelPickerInput,
type ModelPickerListItem,
type ModelPickerPane,
type ModelPickerState,
} from "@/components/model-browser-panes-view";
import {
MODEL_BROWSER_CREATE_PROFILE_KEY,
modelBrowserProfileKey,
type NavigableProfileRow,
} from "@/components/model-browser-view";
import type { NavigableProfileRow } from "@/components/model-browser-view";
import { partitionProviderModels } from "@/provider-selection/model-curation";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
/**
* The compact model picker: optional Profiles section and one section per provider, stacked as an
* accordion. At most one section is open at a time, and tapping the open section collapses it so
* every group can sit closed. A query replaces the accordion with ranked results across profiles
* and every provider, folded models included.
* The compact model picker: Profiles (when the surface offers them) and one section per provider,
* stacked as an accordion. At most one section is open at a time, and tapping the open section
* collapses it so every group can sit closed. A query replaces the accordion with ranked results
* across profiles and every provider, folded models included.
*
* It delegates model folding, ordering, and search to the desktop picker's projection so both form
* factors behave identically.
* It delegates to the desktop picker's projection so both form factors order, fold, rank and
* search the same way.
*/
export interface MobileModelPageInput<TProfile extends NavigableProfileRow = NavigableProfileRow> {
@@ -29,8 +26,6 @@ export interface MobileModelPageInput<TProfile extends NavigableProfileRow = Nav
/** `null` when the surface offers no profiles. */
profiles: readonly TProfile[] | null;
canCreateProfile: boolean;
/** False when Profiles is rendered outside this page (for example on Agent settings Home). */
showProfilesSection?: boolean;
selectedProvider: string;
selectedModel: string;
}
@@ -51,6 +46,7 @@ export type MobileModelPageAction =
export interface MobileProfilesSection {
kind: "profiles";
key: typeof MODEL_PICKER_PROFILES_RAIL_KEY;
count: number;
expanded: boolean;
}
@@ -60,6 +56,11 @@ export interface MobileProviderSection {
providerId: string;
label: string;
status: "ready" | "loading" | "error";
/** Models listed before the fold. */
shown: number;
total: number;
/** Some models sit behind a fold, so `shown` and `total` differ in meaning. */
folds: boolean;
expanded: boolean;
}
@@ -74,11 +75,11 @@ export type MobileModelPageProjection<TProfile extends NavigableProfileRow = Nav
| {
kind: "browse";
sections: MobileModelSection[];
/** False for a lone provider without a Profiles section: its models fill the page. */
/** False for a lone provider without profiles: its models are the page, with no header above them. */
showSectionHeaders: boolean;
/** What the open section lists, or `null` when every section is collapsed. */
body: MobileModelBody<TProfile> | null;
/** The selected model's row in the open list, which opens already in view. */
/** The selected model's row in the open list, which the list scrolls into view. */
selectedIndex: number | null;
}
| {
@@ -96,7 +97,7 @@ export function createMobileModelPageState<TProfile extends NavigableProfileRow>
): MobileModelPageState {
return {
query: "",
expandedKey: resolveInitialExpandedKey(input),
expandedKey: createModelPickerState(toPickerInput(input)).railKey,
foldOverrides: {},
};
}
@@ -121,47 +122,42 @@ export function reduceMobileModelPage(
}
}
export function buildMobileProfileListItems<TProfile extends NavigableProfileRow>(
profiles: readonly TProfile[],
canCreateProfile: boolean,
): ModelPickerListItem<TProfile>[] {
if (profiles.length === 0) {
return canCreateProfile
? [{ kind: "createProfile", key: MODEL_BROWSER_CREATE_PROFILE_KEY }]
: [];
}
return profiles.map((profile) => ({
kind: "profile",
key: modelBrowserProfileKey(profile.id),
profile,
}));
}
export function projectMobileModelPage<TProfile extends NavigableProfileRow>(
input: MobileModelPageInput<TProfile>,
state: MobileModelPageState,
): MobileModelPageProjection<TProfile> {
if (input.providers.length === 0) return { kind: "noProviders" };
if (state.query.trim().length > 0) {
const picker = projectModelPicker<TProfile>(toPickerInput(input), toPickerState(state));
if (picker.pane.kind === "noMatches") return { kind: "noMatches", query: picker.pane.query };
if (picker.pane.kind === "search") {
return {
kind: "search",
profiles: picker.pane.profiles,
models: picker.pane.models,
items: picker.pane.items,
};
const picker = projectModelPicker<TProfile>(toPickerInput(input), toPickerState(state));
const { pane } = picker;
if (pane.kind === "noMatches") return { kind: "noMatches", query: pane.query };
if (pane.kind === "search") {
return { kind: "search", profiles: pane.profiles, models: pane.models, items: pane.items };
}
const sections: MobileModelSection[] = [];
if (picker.layout === "twoPane") {
for (const item of picker.rail) {
if (item.kind === "profiles") {
sections.push({
kind: "profiles",
key: item.key,
count: item.count,
expanded: false,
});
} else {
const provider = input.providers.find((entry) => entry.id === item.providerId);
if (provider) sections.push(toProviderSection(provider, false));
}
}
} else {
const provider = input.providers.find((entry) => entry.id === picker.railKey);
if (provider) sections.push(toProviderSection(provider, true));
}
const sections = buildSections(input);
const showSectionHeaders = sections.length > 1;
const expandedKey = resolveExpandedKey(sections, state.expandedKey, showSectionHeaders);
const expandedKey = showSectionHeaders && state.expandedKey === null ? null : picker.railKey;
for (const section of sections) {
section.expanded = section.key === expandedKey;
}
const body = expandedKey === null ? null : buildSectionBody(input, state, expandedKey);
const body = expandedKey === null ? null : pane;
return {
kind: "browse",
sections,
@@ -171,81 +167,6 @@ export function projectMobileModelPage<TProfile extends NavigableProfileRow>(
};
}
function resolveInitialExpandedKey<TProfile extends NavigableProfileRow>(
input: MobileModelPageInput<TProfile>,
): string {
const selected = input.providers.find((provider) => provider.id === input.selectedProvider);
if (selected) return selected.id;
if (input.showProfilesSection !== false && (input.profiles?.length ?? 0) > 0) {
return MODEL_PICKER_PROFILES_RAIL_KEY;
}
const ready = input.providers.find((provider) => provider.modelSelection.kind === "models");
return (ready ?? input.providers[0])?.id ?? MODEL_PICKER_PROFILES_RAIL_KEY;
}
function buildSections<TProfile extends NavigableProfileRow>(
input: MobileModelPageInput<TProfile>,
): MobileModelSection[] {
const ordered: MobileModelSection[] = orderProvidersForPicker(input.providers).ordered.map(
(provider) => toProviderSection(provider),
);
if (input.showProfilesSection !== false && input.profiles !== null) {
ordered.unshift({
kind: "profiles",
key: MODEL_PICKER_PROFILES_RAIL_KEY,
expanded: false,
});
}
return ordered;
}
function resolveExpandedKey(
sections: readonly MobileModelSection[],
requestedKey: string | null,
showSectionHeaders: boolean,
): string | null {
if (showSectionHeaders && requestedKey === null) return null;
if (requestedKey !== null && sections.some((section) => section.key === requestedKey)) {
return requestedKey;
}
return sections[0]?.key ?? null;
}
function buildSectionBody<TProfile extends NavigableProfileRow>(
input: MobileModelPageInput<TProfile>,
state: MobileModelPageState,
expandedKey: string,
): MobileModelBody<TProfile> | null {
if (expandedKey === MODEL_PICKER_PROFILES_RAIL_KEY) {
return {
kind: "profiles",
items: buildMobileProfileListItems(input.profiles ?? [], input.canCreateProfile),
};
}
const provider = input.providers.find((entry) => entry.id === expandedKey);
if (!provider) return null;
// Pass only the expanded provider with profiles omitted so the shared picker projects that
// provider's own models, fold, loading, or error state cleanly.
const picker = projectModelPicker<TProfile>(
{
providers: [provider],
profiles: null,
canCreateProfile: false,
selectedProvider: input.selectedProvider,
selectedModel: input.selectedModel,
},
{
query: "",
railKey: provider.id,
focus: "list",
activeKey: null,
foldOverrides: state.foldOverrides,
},
);
if (picker.pane.kind === "search" || picker.pane.kind === "noMatches") return null;
return picker.pane;
}
function findSelectedIndex<TProfile extends NavigableProfileRow>(
body: MobileModelBody<TProfile>,
input: MobileModelPageInput<TProfile>,
@@ -279,17 +200,33 @@ function toPickerState(state: MobileModelPageState): ModelPickerState {
};
}
function toProviderSection(provider: ProviderSelectorProvider): MobileProviderSection {
const selection = provider.modelSelection;
let status: MobileProviderSection["status"] = "ready";
if (selection.kind === "loading") status = "loading";
else if (selection.kind === "error") status = "error";
return {
kind: "provider",
function toProviderSection(
provider: ProviderSelectorProvider,
expanded: boolean,
): MobileProviderSection {
const base = {
kind: "provider" as const,
key: provider.id,
providerId: provider.id,
label: provider.label,
status,
expanded: false,
expanded,
};
const selection = provider.modelSelection;
if (selection.kind !== "models") {
return {
...base,
status: selection.kind === "loading" ? "loading" : "error",
shown: 0,
total: 0,
folds: false,
};
}
const partition = partitionProviderModels(selection.rows, provider.shownModels, "");
return {
...base,
status: "ready",
shown: partition.primary.length,
total: selection.rows.length,
folds: partition.foldKind !== null,
};
}
+282 -358
View File
@@ -1,14 +1,14 @@
import { useCallback, useMemo, useRef, useState, type ReactElement, type ReactNode } from "react";
import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { FlatList, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { AlertTriangle, ChevronDown, Layers } from "lucide-react-native";
import { AlertTriangle, ChevronDown, ChevronUp, Layers, Pencil } from "lucide-react-native";
import type { AgentProfilePickerRow } from "@/agent-profiles";
import {
IndependentScrollBoundary,
MODEL_PICKER_ROW_HEIGHT,
ModelBrowserLoadingState,
ModelBrowserNoProviders,
ModelBrowserRow,
ModelBrowserSectionHeading,
ModelProviderGlyph,
ModelSearchNoMatches,
@@ -16,14 +16,12 @@ import {
} from "@/components/model-browser";
import {
CustomizeProviderButton,
EditProfilesButton,
ModelPickerItemRow,
type ModelPickerActions,
} from "@/components/model-browser-panes";
import type { ModelPickerListItem } from "@/components/model-browser-panes-view";
import { groupProfilesByProviderModel } from "@/components/model-browser-view";
import {
buildMobileProfileListItems,
createMobileModelPageState,
projectMobileModelPage,
reduceMobileModelPage,
@@ -32,39 +30,41 @@ import {
type MobileModelPageInput,
type MobileModelPageProjection,
type MobileModelSection,
type MobileProfilesSection,
type MobileProviderSection,
} from "@/components/mobile-model-page-view";
import { SettingsCard } from "@/components/settings";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { PressHighlight } from "@/components/ui/press-highlight";
import {
FlatList as SheetFlatList,
ScrollView as SheetScrollView,
} from "@/components/ui/scroll-view";
import { useInitialFlatListScroll } from "@/components/ui/scroll-reveal";
import { SearchField } from "@/components/ui/search-field";
import { isNative, isWeb } from "@/constants/platform";
import { useRevealActiveFlatListRow } from "@/components/ui/scroll-reveal";
import { isNative } from "@/constants/platform";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { settingsStyles } from "@/styles/settings";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
/**
* The open accordion section lists its rows in a box capped at about five rows that scrolls on its
* own. Opening another section, unfolding older models, or loading never moves the sections below
* it, so they stay where the thumb left them.
* The open accordion section lists its rows in a box of one fixed height, about five rows, that
* scrolls on its own. Opening another section, unfolding older models or loading never moves the
* sections below it, so they stay where the thumb left them.
*/
export const MOBILE_EXPANDED_PROVIDER_HEIGHT = 220;
/** Theme-free: the sheet scrollers drop a themed contentContainerStyle on web (docs/unistyles.md). */
const LIST_CONTENT = { paddingBottom: 4 };
const SHEET_LIST_CARD_LIST = { flexGrow: 0, flexShrink: 1, minHeight: 0 };
const SECTION_HEADER_HEIGHT = 44;
const EXPANDED_A11Y_STATE = { expanded: true };
const ThemedAlertTriangle = withUnistyles(AlertTriangle);
const ThemedChevronDown = withUnistyles(ChevronDown);
const ThemedChevronUp = withUnistyles(ChevronUp);
const ThemedLayers = withUnistyles(Layers);
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundMapping = (theme: Theme) => ({ color: theme.colors.foreground });
const foregroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
// React Native Web blurs the focused input on every scroll in "on-drag" mode.
const KEYBOARD_DISMISS_MODE = isNative ? "on-drag" : "none";
@@ -86,7 +86,6 @@ export function useMobileModelPage(input: {
providers: readonly ProviderSelectorProvider[];
profiles?: readonly AgentProfilePickerRow[] | null;
canCreateProfile?: boolean;
showProfilesSection?: boolean;
selectedProvider: string;
selectedModel: string;
}): MobileModelPage {
@@ -94,20 +93,12 @@ export function useMobileModelPage(input: {
providers,
profiles = null,
canCreateProfile = false,
showProfilesSection = true,
selectedProvider,
selectedModel,
} = input;
const pageInput = useMemo<MobileModelPageInput<AgentProfilePickerRow>>(
() => ({
providers,
profiles,
canCreateProfile,
showProfilesSection,
selectedProvider,
selectedModel,
}),
[canCreateProfile, profiles, providers, selectedModel, selectedProvider, showProfilesSection],
() => ({ providers, profiles, canCreateProfile, selectedProvider, selectedModel }),
[canCreateProfile, profiles, providers, selectedModel, selectedProvider],
);
const inputRef = useRef(pageInput);
inputRef.current = pageInput;
@@ -159,7 +150,6 @@ export function SheetSearchDock({
placeholder={placeholder}
clearAccessibilityLabel={t("providerCatalog.clearSearch")}
fullWidth
variant="card"
testID={testID}
clearTestID={testID ? `${testID}-clear` : undefined}
/>
@@ -265,21 +255,6 @@ export function MobileModelPageView({
),
[renderItem],
);
const singleProviderSection =
projection.kind === "browse" && !projection.showSectionHeaders
? projection.sections[0]
: undefined;
const singleProviderHeader = useMemo(
() =>
singleProviderSection?.kind === "provider" ? (
<ProviderSectionHeader
section={singleProviderSection}
serverId={serverId}
collapsible={false}
/>
) : undefined,
[serverId, singleProviderSection],
);
if (projection.kind === "noProviders") {
return (
@@ -313,8 +288,12 @@ export function MobileModelPageView({
);
}
if (!projection.showSectionHeaders) {
const section = projection.sections[0];
return (
<SheetListCard header={singleProviderHeader} testID="mobile-model-page">
<View style={styles.page} testID="mobile-model-page">
{section?.kind === "provider" ? (
<ExpandedProviderHeader section={section} serverId={serverId} />
) : null}
{projection.body ? (
<SectionBody
body={projection.body}
@@ -325,7 +304,7 @@ export function MobileModelPageView({
isRetryingProvider={actions.isRetryingProvider}
/>
) : null}
</SheetListCard>
</View>
);
}
return (
@@ -342,8 +321,8 @@ export function MobileModelPageView({
<AccordionSectionCard
key={section.key}
section={section}
body={section.expanded ? projection.body : null}
selectedIndex={section.expanded ? projection.selectedIndex : null}
body={projection.body}
selectedIndex={projection.selectedIndex}
serverId={serverId}
actions={actions}
renderItem={renderItem}
@@ -355,92 +334,6 @@ export function MobileModelPageView({
);
}
/**
* The collapsible Profiles card extracted onto Agent settings Home, using the same header and
* scrollable list as the Model accordion.
*/
export function CollapsibleProfilesCard({
profiles,
expanded,
onToggle,
serverId,
onApplyProfile,
onEditProfiles,
}: {
profiles: readonly AgentProfilePickerRow[];
expanded: boolean;
onToggle: () => void;
serverId: string | null;
onApplyProfile?: (profileId: string) => void;
onEditProfiles?: () => void;
}) {
const { t } = useTranslation();
const items = useMemo(
() => buildMobileProfileListItems(profiles, Boolean(onEditProfiles)),
[onEditProfiles, profiles],
);
const actions = useMemo<ModelPickerActions>(
() => ({
onSelect: noop,
onApplyProfile,
onEditProfiles,
isRetryingProvider: false,
}),
[onApplyProfile, onEditProfiles],
);
const emptyLookup = useMemo(() => new Map<string, AgentProfilePickerRow[]>(), []);
const renderItem = useCallback(
({ item }: { item: ModelPickerListItem<AgentProfilePickerRow> }) => (
<ModelPickerItemRow
item={item}
active={false}
selected={false}
inSearch={false}
serverId={serverId}
profiledLookup={emptyLookup}
onToggleFold={noop}
onActivate={noop}
actions={actions}
/>
),
[actions, emptyLookup, serverId],
);
const leading = useMemo(
() => <ThemedLayers size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />,
[],
);
const trailingAction = useMemo(
() => (expanded && onEditProfiles ? <EditProfilesButton onPress={onEditProfiles} /> : null),
[expanded, onEditProfiles],
);
const viewportHeight = computeBoundedListHeight(items.length);
return (
<SettingsCard testID="agent-controls-profiles-card">
<CollapsibleSectionHeader
leading={leading}
title={t("modelSelector.profiles")}
expanded={expanded}
trailing={trailingAction}
onToggle={onToggle}
testID="agent-controls-profiles"
/>
{expanded && items.length > 0 ? (
<IndependentScrollBoundary>
<SectionItemList
items={items}
selectedIndex={null}
renderItem={renderItem}
fill={false}
viewportHeight={viewportHeight}
testID="agent-controls-profiles-list"
/>
</IndependentScrollBoundary>
) : null}
</SettingsCard>
);
}
function AccordionSectionCard({
section,
body,
@@ -458,27 +351,29 @@ function AccordionSectionCard({
renderItem: ModelItemRenderer;
onToggle: (action: MobileModelPageAction) => void;
}) {
const handleToggle = useCallback(
() => onToggle({ kind: "toggleSection", key: section.key }),
[onToggle, section.key],
);
if (!section.expanded) {
return (
<SettingsCard>
{section.kind === "profiles" ? (
<CollapsedProfilesRow section={section} onToggle={onToggle} />
) : (
<CollapsedProviderRow section={section} serverId={serverId} onToggle={onToggle} />
)}
</SettingsCard>
);
}
return (
<SettingsCard>
{section.kind === "profiles" ? (
<ProfilesSectionHeader
expanded={section.expanded}
<ExpandedProfilesHeader
section={section}
onEditProfiles={actions.onEditProfiles}
onToggle={handleToggle}
onToggle={onToggle}
/>
) : (
<ProviderSectionHeader
section={section}
serverId={serverId}
collapsible
onToggle={handleToggle}
/>
<ExpandedProviderHeader section={section} serverId={serverId} onToggle={onToggle} />
)}
{section.expanded && body ? (
{body ? (
<SectionBody
body={body}
selectedIndex={selectedIndex}
@@ -494,25 +389,12 @@ function AccordionSectionCard({
/**
* An inset card holding one sheet list, on the same rail as the browse sections' cards. It grows
* with the list, then the list scrolls inside it while its optional header stays fixed.
* with the list, then the list scrolls inside it.
*/
function SheetListCard({
header,
children,
testID,
}: {
header?: ReactNode;
children: ReactNode;
testID?: string;
}) {
function SheetListCard({ children }: { children: ReactNode }) {
return (
<View style={styles.listCardPage} testID={testID}>
<View style={[settingsStyles.card, styles.listCard]}>
{header ? <View style={styles.listCardHeader}>{header}</View> : null}
<View style={[header ? settingsStyles.rowBorder : undefined, styles.listCardBody]}>
{children}
</View>
</View>
<View style={styles.listCardPage}>
<SettingsCard shrink>{children}</SettingsCard>
</View>
);
}
@@ -527,166 +409,269 @@ function getSearchEntryKey(entry: SearchEntry): string {
return entry.key;
}
function computeBoundedListHeight(itemCount: number): number {
return Math.min(
Math.max(itemCount, 1) * MODEL_PICKER_ROW_HEIGHT + LIST_CONTENT.paddingBottom,
MOBILE_EXPANDED_PROVIDER_HEIGHT,
);
function useSectionSummary(section: MobileProviderSection): string {
const { t } = useTranslation();
if (section.folds) {
return t("modelSelector.shownOfTotal", { shown: section.shown, total: section.total });
}
return String(section.total);
}
/**
* One header component shared across collapsed and expanded states so toggling never shifts the
* icon, label, or chevron.
*/
function CollapsibleSectionHeader({
function ExpandedSectionHeader({
leading,
title,
expanded,
summary,
trailing,
onToggle,
onCollapse,
testID,
}: {
leading: ReactNode;
title: string;
expanded: boolean;
summary: string | null;
trailing?: ReactNode;
onToggle?: () => void;
onCollapse?: () => void;
testID: string;
}) {
const accessibilityState = useMemo(() => ({ expanded }), [expanded]);
const webExpandedProps = useMemo(
() => (isWeb ? ({ "aria-expanded": expanded } as const) : null),
[expanded],
const titleContent = (
<>
<View style={styles.glyph}>{leading}</View>
<Text style={styles.expandedTitle} numberOfLines={1}>
{title}
{summary !== null ? <Text style={styles.summary}>{` · ${summary}`}</Text> : null}
</Text>
</>
);
if (!onCollapse) {
return (
<View style={styles.expandedHeader} testID={testID}>
<View style={styles.expandedTrigger}>{titleContent}</View>
{trailing}
</View>
);
}
return (
<View style={styles.sectionHeader}>
{onToggle ? (
<View style={styles.expandedHeader}>
<PressHighlight
onPress={onCollapse}
accessibilityRole="button"
accessibilityState={EXPANDED_A11Y_STATE}
style={styles.expandedTrigger}
testID={testID}
>
{titleContent}
</PressHighlight>
<View style={styles.expandedTrailing}>
{trailing}
<PressHighlight
{...webExpandedProps}
onPress={onToggle}
onPress={onCollapse}
hitSlop={8}
accessibilityRole="button"
accessibilityLabel={title}
accessibilityState={accessibilityState}
style={styles.sectionHeaderPress}
highlightStyle={styles.sectionHeaderPressed}
testID={testID}
/>
) : null}
<View style={[styles.glyph, styles.passThrough]}>{leading}</View>
<View style={[styles.sectionTitleWrap, styles.passThrough]}>
<Text style={styles.sectionTitle} numberOfLines={1} testID={onToggle ? undefined : testID}>
{title}
</Text>
</View>
<View style={[styles.sectionTrailing, styles.boxNone]}>
{trailing}
{onToggle ? (
<View
style={[styles.chevronSlot, expanded && styles.chevronExpanded, styles.passThrough]}
>
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
</View>
) : null}
accessibilityState={EXPANDED_A11Y_STATE}
style={styles.collapseChevron}
>
<ThemedChevronUp size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
</PressHighlight>
</View>
</View>
);
}
function ProfilesSectionHeader({
expanded,
function ExpandedProfilesHeader({
section,
onEditProfiles,
onToggle,
}: {
expanded: boolean;
section: MobileProfilesSection;
onEditProfiles?: () => void;
onToggle: () => void;
onToggle: (action: MobileModelPageAction) => void;
}) {
const { t } = useTranslation();
const handleCollapse = useCallback(
() => onToggle({ kind: "toggleSection", key: section.key }),
[onToggle, section.key],
);
const leading = useMemo(
() => <ThemedLayers size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />,
() => <ThemedLayers size={ICON_SIZE.sm} uniProps={foregroundMapping} />,
[],
);
const trailing = useMemo(
() => (expanded && onEditProfiles ? <EditProfilesButton onPress={onEditProfiles} /> : null),
[expanded, onEditProfiles],
() =>
onEditProfiles ? (
<Button
variant="ghost"
size="sm"
leftIcon={Pencil}
onPress={onEditProfiles}
accessibilityLabel={t("modelSelector.editProfilesLabel")}
testID="model-profiles-edit"
/>
) : null,
[onEditProfiles, t],
);
return (
<CollapsibleSectionHeader
<ExpandedSectionHeader
leading={leading}
title={t("modelSelector.profiles")}
expanded={expanded}
summary={String(section.count)}
trailing={trailing}
onToggle={onToggle}
testID={expanded ? "model-profiles-section" : "model-picker-rail-profiles"}
onCollapse={handleCollapse}
testID="model-profiles-section"
/>
);
}
function ProviderSectionHeader({
function CollapsedProfilesRow({
section,
onToggle,
}: {
section: MobileProfilesSection;
onToggle: (action: MobileModelPageAction) => void;
}) {
const { t } = useTranslation();
const handlePress = useCallback(
() => onToggle({ kind: "toggleSection", key: section.key }),
[onToggle, section.key],
);
const leadingSlot = useMemo(
() => <ThemedLayers size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />,
[],
);
const trailingSlot = useMemo(
() => (
<View style={styles.collapsedTrailing}>
<Text style={styles.summary}>{section.count}</Text>
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
</View>
),
[section.count],
);
return (
<ModelBrowserRow
label={t("modelSelector.profiles")}
leadingSlot={leadingSlot}
trailingSlot={trailingSlot}
spacing="provider"
onPress={handlePress}
testID="model-picker-rail-profiles"
/>
);
}
function ExpandedProviderHeader({
section,
serverId,
collapsible,
onToggle,
}: {
section: MobileProviderSection;
serverId: string | null;
collapsible: boolean;
onToggle?: () => void;
onToggle?: (action: MobileModelPageAction) => void;
}) {
const summary = useSectionSummary(section);
const handleCollapse = useCallback(
() => onToggle?.({ kind: "toggleSection", key: section.key }),
[onToggle, section.key],
);
const leading = useMemo(
() => (
<ModelProviderGlyph provider={section.providerId} serverId={serverId} size={ICON_SIZE.sm} />
<ModelProviderGlyph
provider={section.providerId}
serverId={serverId}
size={ICON_SIZE.sm}
tone="foreground"
/>
),
[section.providerId, serverId],
);
const trailing = useMemo(() => {
if (section.expanded) {
return serverId ? (
const trailing = useMemo(
() =>
serverId ? (
<CustomizeProviderButton
serverId={serverId}
providerId={section.providerId}
providerLabel={section.label}
/>
) : null;
}
if (section.status === "loading") {
return (
<View style={[styles.spinner, styles.passThrough]}>
<ThemedLoadingSpinner size="small" uniProps={foregroundMutedMapping} />
</View>
);
}
if (section.status === "error") {
return (
<View style={styles.passThrough}>
<ThemedAlertTriangle size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
</View>
);
}
return null;
}, [section.expanded, section.label, section.providerId, section.status, serverId]);
) : null,
[section.label, section.providerId, serverId],
);
return (
<CollapsibleSectionHeader
<ExpandedSectionHeader
leading={leading}
title={section.label}
expanded={section.expanded}
summary={section.status === "ready" ? summary : null}
trailing={trailing}
onToggle={collapsible ? onToggle : undefined}
testID={
section.expanded
? `model-provider-section-${section.providerId}`
: `model-provider-${section.providerId}`
}
onCollapse={onToggle ? handleCollapse : undefined}
testID={`model-provider-section-${section.providerId}`}
/>
);
}
function CollapsedProviderRow({
section,
serverId,
onToggle,
}: {
section: MobileProviderSection;
serverId: string | null;
onToggle: (action: MobileModelPageAction) => void;
}) {
const summary = useSectionSummary(section);
const handlePress = useCallback(
() => onToggle({ kind: "toggleSection", key: section.key }),
[onToggle, section.key],
);
const leadingSlot = useMemo(
() => (
<ModelProviderGlyph provider={section.providerId} serverId={serverId} size={ICON_SIZE.sm} />
),
[section.providerId, serverId],
);
const trailingSlot = useMemo(
() => (
<View style={styles.collapsedTrailing}>
<CollapsedStatus section={section} summary={summary} />
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
</View>
),
[section, summary],
);
return (
<ModelBrowserRow
label={section.label}
leadingSlot={leadingSlot}
trailingSlot={trailingSlot}
spacing="provider"
onPress={handlePress}
testID={`model-provider-${section.providerId}`}
/>
);
}
function CollapsedStatus({
section,
summary,
}: {
section: MobileProviderSection;
summary: string;
}) {
if (section.status === "loading") {
return (
<View style={styles.spinner}>
<ThemedLoadingSpinner size="small" uniProps={foregroundMutedMapping} />
</View>
);
}
if (section.status === "error") {
return <ThemedAlertTriangle size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />;
}
return <Text style={styles.summary}>{summary}</Text>;
}
type ModelItemRenderer = ({
item,
}: {
item: ModelPickerListItem<AgentProfilePickerRow>;
}) => ReactElement;
}) => React.ReactElement;
function SectionBody({
body,
@@ -704,7 +689,7 @@ function SectionBody({
onRetryProvider: ModelPickerActions["onRetryProvider"];
isRetryingProvider: boolean;
}) {
const frameStyle = fill ? styles.fillState : styles.fixedViewport;
const frameStyle = fill ? styles.page : styles.fixedViewport;
if (body.kind === "providerLoading") {
return (
<View style={[frameStyle, styles.centered]}>
@@ -725,91 +710,58 @@ function SectionBody({
);
}
const listKey = body.kind === "profiles" ? "profiles" : body.providerId;
const viewportHeight =
body.kind === "profiles"
? computeBoundedListHeight(body.items.length)
: MOBILE_EXPANDED_PROVIDER_HEIGHT;
const list = (
<SectionItemList
// Each section is a new list, which opens directly at its top or at the selected model.
// Each section is a new list, which opens at its top or at the selected model.
key={listKey}
items={body.items}
selectedIndex={selectedIndex}
renderItem={renderItem}
fill={fill}
viewportHeight={viewportHeight}
/>
);
// The lone provider's list is the page's only scroller; a fixed box scrolls inside the page's.
return fill ? list : <IndependentScrollBoundary>{list}</IndependentScrollBoundary>;
}
function getModelItemLayout(
_data: ArrayLike<ModelPickerListItem<AgentProfilePickerRow>> | null | undefined,
index: number,
) {
return {
length: MODEL_PICKER_ROW_HEIGHT,
offset: index * MODEL_PICKER_ROW_HEIGHT,
index,
};
}
function modelItemOffset(index: number): number {
return index * MODEL_PICKER_ROW_HEIGHT;
}
/** Opens with the selected model already in view via `getItemLayout` + `initialScrollIndex`. */
/** Opens with the selected model in view, such as an older model behind the opened fold. */
function SectionItemList({
items,
selectedIndex,
renderItem,
fill,
viewportHeight,
testID = "compact-model-list",
}: {
items: ModelPickerListItem<AgentProfilePickerRow>[];
selectedIndex: number | null;
renderItem: ModelItemRenderer;
fill: boolean;
viewportHeight: number;
testID?: string;
}) {
const listRef = useRef<FlatList<ModelPickerListItem<AgentProfilePickerRow>>>(null);
const { initialScrollIndex, contentOffset } = useInitialFlatListScroll({
// Waits for the first visible rows, so a selection already in view never scrolls the list.
const reveal = useRevealActiveFlatListRow({
listRef,
selectedIndex,
itemCount: items.length,
visibleCount: Math.max(1, Math.floor(viewportHeight / MODEL_PICKER_ROW_HEIGHT)),
offsetForIndex: modelItemOffset,
activeIndex: selectedIndex,
waitForViewable: true,
});
const boxStyle = useMemo(() => {
if (fill) return SHEET_LIST_CARD_LIST;
if (viewportHeight === MOBILE_EXPANDED_PROVIDER_HEIGHT) return styles.fixedViewport;
return [styles.boundedViewport, inlineUnistylesStyle({ height: viewportHeight })];
}, [fill, viewportHeight]);
// A lone provider's list is the sheet's own scroller, so it must integrate with the bottom sheet
// gesture handler (SheetFlatList); an accordion list scrolls independently inside SheetScrollView.
const ListComponent = fill ? SheetFlatList : FlatList;
return (
<ListComponent
<FlatList
ref={listRef}
data={items}
renderItem={renderItem}
keyExtractor={getItemKey}
getItemLayout={getModelItemLayout}
initialScrollIndex={initialScrollIndex}
contentOffset={contentOffset}
style={boxStyle}
style={fill ? styles.page : styles.fixedViewport}
contentContainerStyle={LIST_CONTENT}
keyboardShouldPersistTaps="handled"
keyboardDismissMode={KEYBOARD_DISMISS_MODE}
showsVerticalScrollIndicator
nestedScrollEnabled={!fill}
testID={testID}
nestedScrollEnabled
onScrollToIndexFailed={reveal.onScrollToIndexFailed}
onViewableItemsChanged={reveal.onViewableItemsChanged}
viewabilityConfig={reveal.viewabilityConfig}
onContentSizeChange={reveal.onContentSizeChange}
onLayout={reveal.onLayout}
testID="compact-model-list"
/>
);
}
@@ -826,77 +778,62 @@ const styles = StyleSheet.create((theme) => ({
paddingTop: theme.spacing[2],
paddingBottom: theme.spacing[2],
},
listCard: {
flexShrink: 1,
minHeight: 0,
},
listCardHeader: {
flexShrink: 0,
},
listCardBody: {
flexShrink: 1,
minHeight: 0,
},
fillState: {
minHeight: MOBILE_EXPANDED_PROVIDER_HEIGHT,
},
sections: {
paddingHorizontal: theme.spacing[4],
paddingTop: theme.spacing[2],
paddingBottom: theme.spacing[4],
gap: theme.spacing[2],
},
sectionHeader: {
height: SECTION_HEADER_HEIGHT,
position: "relative",
expandedHeader: {
minHeight: 44,
flexDirection: "row",
alignItems: "center",
// The model rows' leading rail (ModelBrowserRow), so the section glyph sits above theirs.
paddingLeft: isNative ? theme.spacing[6] : theme.spacing[3],
paddingRight: isNative ? theme.spacing[6] : theme.spacing[3],
},
expandedTrigger: {
flex: 1,
minWidth: 0,
minHeight: 44,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
// Matches ModelBrowserRow's leading/trailing rail so icons and chevrons line up cleanly.
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[3] },
},
sectionHeaderPress: {
...StyleSheet.absoluteFill,
expandedTrailing: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
},
sectionHeaderPressed: {
backgroundColor: theme.colors.surface2,
},
passThrough: {
pointerEvents: "none",
},
boxNone: {
pointerEvents: "box-none",
collapseChevron: {
minWidth: 24,
minHeight: 44,
alignItems: "center",
justifyContent: "center",
},
glyph: {
width: 16,
alignItems: "center",
justifyContent: "center",
},
sectionTitleWrap: {
expandedTitle: {
flex: 1,
minWidth: 0,
},
sectionTitle: {
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
fontWeight: theme.fontWeight.medium,
color: theme.colors.foreground,
},
sectionTrailing: {
summary: {
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.normal,
color: theme.colors.foregroundMuted,
fontVariant: ["tabular-nums"],
},
collapsedTrailing: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
// Optical: matches SettingsRowHeader's chevron overhang so the glyph sits on the trailing rail.
chevronSlot: {
width: ICON_SIZE.sm,
height: ICON_SIZE.sm,
marginRight: -theme.spacing[1],
alignItems: "center",
justifyContent: "center",
},
chevronExpanded: {
transform: [{ rotate: "180deg" }],
},
spinner: {
transform: [{ scale: 0.7 }],
},
@@ -904,9 +841,6 @@ const styles = StyleSheet.create((theme) => ({
height: MOBILE_EXPANDED_PROVIDER_HEIGHT,
flexGrow: 0,
},
boundedViewport: {
flexGrow: 0,
},
centered: {
alignItems: "center",
justifyContent: "center",
@@ -915,14 +849,4 @@ const styles = StyleSheet.create((theme) => ({
flex: 1,
flexDirection: "row",
},
searchFooter: {
// Matches the card inset (`styles.sections` / `styles.listCardPage`) so the search box shares
// its outer left and right rails with the provider cards above it.
paddingHorizontal: theme.spacing[4],
},
}));
/** Read at render time rather than module scope (docs/unistyles.md). */
export function getSheetSearchFooterStyle() {
return styles.searchFooter;
}
@@ -152,84 +152,20 @@ describe("model picker layout", () => {
expect(resolveModelPickerLayout(input({ profiles: null }))).toBe("twoPane");
});
it("uses a single pane for one provider even when the surface offers profiles", () => {
expect(resolveModelPickerLayout(input({ providers: [claude] }))).toBe("singlePane");
expect(resolveModelPickerLayout(input({ providers: [claude], profiles: [] }))).toBe(
"singlePane",
);
it("uses two panes for one provider with profiles", () => {
expect(resolveModelPickerLayout(input({ providers: [claude] }))).toBe("twoPane");
});
it("keeps two panes for one provider on a surface that offers profiles but has none", () => {
expect(resolveModelPickerLayout(input({ providers: [claude], profiles: [] }))).toBe("twoPane");
});
it("drops the rail for one provider on a surface without profiles", () => {
expect(resolveModelPickerLayout(input({ providers: [claude], profiles: null }))).toBe(
"singlePane",
);
});
it("lists matching profiles above models in a single-pane provider view", () => {
const { projection } = open(input({ providers: [claude], profiles: [profiles[1]] }));
expect(projection.layout).toBe("singlePane");
expect(projection.rail).toEqual([]);
expect(projection.pane).toMatchObject({
kind: "provider",
providerId: "claude",
label: "Claude",
});
if (projection.pane.kind !== "provider") return;
expect(keys(projection.pane.profiles)).toEqual(["profile:quick"]);
expect(keys(projection.pane.models)).toEqual([
"model:claude:opus-5.5",
"model:claude:fable-5.2",
"model:claude:sonnet-5.5",
"model:claude:haiku-5.5",
"fold:claude",
]);
expect(projection.activeKey).toBe("model:claude:opus-5.5");
});
it("keeps profiles usable in single-pane mode while the lone provider is loading or errored", () => {
const loading = open(
input({
providers: [opencode],
profiles: [profiles[0]],
selectedProvider: "opencode",
selectedModel: "",
}),
).projection;
expect(loading.layout).toBe("singlePane");
expect(loading.pane).toMatchObject({ kind: "providerLoading", providerId: "opencode" });
expect(keys(loading.pane.items)).toEqual(["profile:deep-review"]);
expect(loading.activeKey).toBe("profile:deep-review");
const errored = open(
input({
providers: [copilot],
profiles: [profiles[0]],
selectedProvider: "copilot",
selectedModel: "",
}),
).projection;
expect(errored.layout).toBe("singlePane");
expect(errored.pane).toMatchObject({ kind: "providerError", providerId: "copilot" });
expect(keys(errored.pane.items)).toEqual(["profile:deep-review"]);
expect(errored.activeKey).toBe("profile:deep-review");
});
it("includes Create profile at the end of a single-pane list when there are no profiles", () => {
const { projection } = open(
input({
providers: [codex],
profiles: [],
selectedProvider: "codex",
selectedModel: "gpt-5.4",
}),
);
expect(projection.layout).toBe("singlePane");
if (projection.pane.kind !== "provider") return;
expect(projection.pane.profiles).toEqual([]);
expect(keys(projection.pane.models)).toEqual([
"model:codex:gpt-5.4",
"model:codex:gpt-5.4-mini",
"create-profile",
]);
});
it("keeps a fixed two-pane height whatever the content", () => {
const tall = resolveModelPickerHeight(input());
expect(resolveModelPickerHeight(input({ providers: [codex, pi] }))).toBe(tall);
@@ -262,6 +198,12 @@ describe("model picker rail", () => {
});
});
it("counts profiles and the models each provider shows first", () => {
const { projection } = open(input());
const counts = Object.fromEntries(projection.rail.map((item) => [item.key, item.count]));
expect(counts).toMatchObject({ profiles: 2, claude: 4, codex: 2, pi: 2 });
});
it("omits the Profiles row when the surface shows no profiles", () => {
const { projection } = open(input({ profiles: null }));
expect(projection.rail.map((item) => item.key)).not.toContain(MODEL_PICKER_PROFILES_RAIL_KEY);
@@ -302,6 +244,9 @@ describe("model picker provider pane", () => {
kind: "provider",
providerId: "claude",
label: "Claude",
shown: 4,
total: 19,
foldKind: "older",
});
expect(modelIds(projection)).toEqual(claudeCurrent);
expect(projection.pane.items.at(-1)).toMatchObject({
@@ -341,6 +286,7 @@ describe("model picker provider pane", () => {
const state = reduceModelPicker(open(pickerInput).state, { kind: "selectRail", railKey: "pi" });
const projection = projectModelPicker(pickerInput, state);
expect(modelIds(projection)).toEqual(["anthropic/opus", "openai/gpt-5"]);
expect(projection.pane).toMatchObject({ shown: 2, total: 4, foldKind: "all" });
expect(projection.pane.items.at(-1)).toMatchObject({ kind: "fold", foldKind: "all", count: 2 });
});
@@ -351,7 +297,7 @@ describe("model picker provider pane", () => {
railKey: "codex",
});
const projection = projectModelPicker(pickerInput, state);
expect(projection.pane).toMatchObject({ kind: "provider", providerId: "codex" });
expect(projection.pane).toMatchObject({ kind: "provider", foldKind: null });
expect(keys(projection.pane.items)).toEqual([
"model:codex:gpt-5.4",
"model:codex:gpt-5.4-mini",
@@ -65,13 +65,14 @@ export type ModelPickerAction =
| { kind: "toggleFold"; providerId: string; expanded: boolean };
export type ModelPickerRailItem =
| { kind: "profiles"; key: typeof MODEL_PICKER_PROFILES_RAIL_KEY }
| { kind: "profiles"; key: typeof MODEL_PICKER_PROFILES_RAIL_KEY; count: number }
| {
kind: "provider";
key: string;
providerId: string;
label: string;
status: "ready" | "loading" | "error";
count: number;
/** The first errored provider after ready ones; the rail draws a divider above it. */
startsErrorGroup: boolean;
};
@@ -100,29 +101,13 @@ export type ModelPickerPane<TProfile extends NavigableProfileRow = NavigableProf
kind: "provider";
providerId: string;
label: string;
/** Single-pane only: profiles listed above this provider's models. */
profiles: ModelPickerListItem<TProfile>[];
/** Provider models, optional fold row, and trailing create-profile row in single-pane mode. */
models: ModelPickerListItem<TProfile>[];
items: ModelPickerListItem<TProfile>[];
}
| {
kind: "providerLoading";
providerId: string;
label: string;
/** Single-pane only: profiles kept usable while the provider catalog loads. */
profiles: ModelPickerListItem<TProfile>[];
items: ModelPickerListItem<TProfile>[];
}
| {
kind: "providerError";
providerId: string;
label: string;
message: string;
/** Single-pane only: profiles kept usable when the provider catalog fails. */
profiles: ModelPickerListItem<TProfile>[];
shown: number;
total: number;
foldKind: ModelFoldKind;
items: ModelPickerListItem<TProfile>[];
}
| { kind: "providerLoading"; providerId: string; label: string; items: [] }
| { kind: "providerError"; providerId: string; label: string; message: string; items: [] }
| { kind: "profiles"; items: ModelPickerListItem<TProfile>[] }
| {
kind: "search";
@@ -153,31 +138,22 @@ export function modelPickerFoldKey(providerId: string): string {
return `fold:${providerId}`;
}
/** Two panes only when there are several providers to switch between; a single provider keeps a
* compact single-pane list (with any matching profiles in a section above its models). */
/** Two panes whenever there is a rail to choose from: several providers, or a surface that offers
* profiles (even none yet, so the rail keeps the create-profile entry). */
export function resolveModelPickerLayout(input: ModelPickerInput): ModelPickerLayout {
return input.providers.length > 1 ? "twoPane" : "singlePane";
return input.providers.length > 1 || input.profiles !== null ? "twoPane" : "singlePane";
}
/**
* The popover keeps one height for its whole life, so switching providers, opening a fold, or
* searching never moves it. A single pane sizes to all its rows, profiles and folded ones included.
* searching never moves it. A single pane sizes to all its rows, folded ones included.
*/
export function resolveModelPickerHeight(input: ModelPickerInput): number {
if (resolveModelPickerLayout(input) === "twoPane") return TWO_PANE_HEIGHT;
const provider = input.providers[0];
const providerRows = provider ? countAllRows(provider) : 0;
let profileRows = 0;
if (input.profiles !== null) {
if (input.profiles.length > 0) {
// Profiles rows plus the Profiles and provider section headings.
profileRows = input.profiles.length + 2;
} else if (input.canCreateProfile) {
profileRows = 1;
}
}
const rowCount = provider ? countAllRows(provider) : 0;
return clamp(
SINGLE_PANE_CHROME_HEIGHT + (providerRows + profileRows) * LIST_ROW_HEIGHT,
SINGLE_PANE_CHROME_HEIGHT + rowCount * LIST_ROW_HEIGHT,
SINGLE_PANE_MIN_HEIGHT,
TWO_PANE_HEIGHT,
);
@@ -222,7 +198,7 @@ export function projectModelPicker<TProfile extends NavigableProfileRow>(
const normalizedQuery = normalizeQuery(state.query);
const pane = normalizedQuery
? buildSearchPane(input, normalizedQuery, state.query.trim())
: buildBrowsePane(input, state, layout, railKey);
: buildBrowsePane(input, state, railKey);
const focus: ModelPickerFocus =
layout === "twoPane" && !normalizedQuery && state.focus === "rail" ? "rail" : "list";
return {
@@ -381,31 +357,23 @@ function resolveRailKey(
return rail[0]?.key ?? MODEL_PICKER_PROFILES_RAIL_KEY;
}
/** Orders providers with working (ready/loading) ones first and errored ones last. */
export function orderProvidersForPicker(providers: readonly ProviderSelectorProvider[]): {
ordered: ProviderSelectorProvider[];
firstErroredId: string | null;
} {
const working = providers.filter((provider) => provider.modelSelection.kind !== "error");
const errored = providers.filter((provider) => provider.modelSelection.kind === "error");
return {
ordered: [...working, ...errored],
firstErroredId: working.length > 0 ? (errored[0]?.id ?? null) : null,
};
}
function buildRail(input: ModelPickerInput): ModelPickerRailItem[] {
const { ordered, firstErroredId } = orderProvidersForPicker(input.providers);
const providerItems = ordered.map((provider) =>
buildProviderRailItem(provider, provider.id === firstErroredId),
);
if (input.profiles === null) return providerItems;
return [{ kind: "profiles", key: MODEL_PICKER_PROFILES_RAIL_KEY }, ...providerItems];
const providerItems = input.providers.map((provider) => buildProviderRailItem(input, provider));
const working = providerItems.filter((item) => item.status !== "error");
const errored = providerItems.filter((item) => item.status === "error");
const firstErrored = errored[0];
if (firstErrored && working.length > 0) firstErrored.startsErrorGroup = true;
const ordered = [...working, ...errored];
if (input.profiles === null) return ordered;
return [
{ kind: "profiles", key: MODEL_PICKER_PROFILES_RAIL_KEY, count: input.profiles.length },
...ordered,
];
}
function buildProviderRailItem(
input: ModelPickerInput,
provider: ProviderSelectorProvider,
startsErrorGroup: boolean,
): Extract<ModelPickerRailItem, { kind: "provider" }> {
const selection = provider.modelSelection;
const base = {
@@ -413,17 +381,16 @@ function buildProviderRailItem(
key: provider.id,
providerId: provider.id,
label: provider.label,
startsErrorGroup,
startsErrorGroup: false,
};
if (selection.kind === "loading") return { ...base, status: "loading" };
if (selection.kind === "error") return { ...base, status: "error" };
return { ...base, status: "ready" };
if (selection.kind === "loading") return { ...base, status: "loading", count: 0 };
if (selection.kind === "error") return { ...base, status: "error", count: 0 };
return { ...base, status: "ready", count: partitionFor(input, provider).primary.length };
}
function buildBrowsePane<TProfile extends NavigableProfileRow>(
input: ModelPickerInput<TProfile>,
state: ModelPickerState,
layout: ModelPickerLayout,
railKey: string,
): ModelPickerPane<TProfile> {
if (railKey === MODEL_PICKER_PROFILES_RAIL_KEY) {
@@ -431,19 +398,9 @@ function buildBrowsePane<TProfile extends NavigableProfileRow>(
}
const provider = input.providers.find((entry) => entry.id === railKey);
if (!provider) return { kind: "profiles", items: buildProfileItems(input) };
const singlePaneProfiles: ModelPickerListItem<TProfile>[] =
layout === "singlePane" && input.profiles !== null && input.profiles.length > 0
? input.profiles.map((profile) => toProfileItem(profile))
: [];
const selection = provider.modelSelection;
if (selection.kind === "loading") {
return {
kind: "providerLoading",
providerId: provider.id,
label: provider.label,
profiles: singlePaneProfiles,
items: singlePaneProfiles,
};
return { kind: "providerLoading", providerId: provider.id, label: provider.label, items: [] };
}
if (selection.kind === "error") {
return {
@@ -451,45 +408,18 @@ function buildBrowsePane<TProfile extends NavigableProfileRow>(
providerId: provider.id,
label: provider.label,
message: selection.message,
profiles: singlePaneProfiles,
items: singlePaneProfiles,
items: [],
};
}
const partition = partitionFor(input, provider);
const providerModels = buildProviderItems<TProfile>(provider.id, partition, state);
if (layout === "singlePane" && input.profiles !== null) {
if (singlePaneProfiles.length > 0) {
return {
kind: "provider",
providerId: provider.id,
label: provider.label,
profiles: singlePaneProfiles,
models: providerModels,
items: [...singlePaneProfiles, ...providerModels],
};
}
if (input.canCreateProfile) {
const modelsWithCreate: ModelPickerListItem<TProfile>[] = [
...providerModels,
{ kind: "createProfile", key: MODEL_BROWSER_CREATE_PROFILE_KEY },
];
return {
kind: "provider",
providerId: provider.id,
label: provider.label,
profiles: [],
models: modelsWithCreate,
items: modelsWithCreate,
};
}
}
return {
kind: "provider",
providerId: provider.id,
label: provider.label,
profiles: [],
models: providerModels,
items: providerModels,
shown: partition.primary.length,
total: selection.rows.length,
foldKind: partition.foldKind,
items: buildProviderItems(provider.id, partition, state),
};
}
@@ -5,7 +5,6 @@ import {
useReducer,
useRef,
useState,
type ReactElement,
type ReactNode,
type RefObject,
} from "react";
@@ -34,8 +33,6 @@ import {
type SheetKeyboard,
} from "@/components/adaptive-modal-sheet";
import {
MODEL_PICKER_HEADING_HEIGHT,
MODEL_PICKER_ROW_HEIGHT,
ModelBrowserLoadingState,
ModelBrowserRow,
ModelBrowserSectionHeading,
@@ -63,11 +60,7 @@ import { groupProfilesByProviderModel } from "@/components/model-browser-view";
import { Button } from "@/components/ui/button";
import { Combobox, type ComboboxDesktopPlacement } from "@/components/ui/combobox";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import {
useInitialFlatListScroll,
useRevealActiveFlatListRow,
useRevealActiveItem,
} from "@/components/ui/scroll-reveal";
import { useRevealActiveFlatListRow, useRevealActiveItem } from "@/components/ui/scroll-reveal";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import type { KeyboardInputEvent } from "@/keyboard";
import { useCurrentOverlayLayer } from "@/lib/overlay-root";
@@ -172,7 +165,6 @@ export function DesktopModelPicker({
>
<ModelPickerBody
input={input}
pickerHeight={height}
serverId={serverId}
keyboardHandlerRef={keyboardHandlerRef}
{...actions}
@@ -184,13 +176,11 @@ export function DesktopModelPicker({
/** Mounted only while the popover is open, so every open starts from the current selection. */
function ModelPickerBody({
input,
pickerHeight,
serverId,
keyboardHandlerRef,
...actions
}: ModelPickerActions & {
input: ModelPickerInput<AgentProfilePickerRow>;
pickerHeight: number;
serverId: string | null;
keyboardHandlerRef: RefObject<KeyboardHandler | null>;
}) {
@@ -318,7 +308,6 @@ function ModelPickerBody({
body = (
<ListPane
projection={projection}
pickerHeight={pickerHeight}
query={state.query}
serverId={serverId}
input={input}
@@ -333,7 +322,6 @@ function ModelPickerBody({
<Rail projection={projection} serverId={serverId} onSelectRail={handleSelectRail} />
<ListPane
projection={projection}
pickerHeight={pickerHeight}
query={state.query}
serverId={serverId}
input={input}
@@ -456,9 +444,6 @@ function RailRow({
);
}
const INLINE_HEADER_HEIGHT = 56;
const PANE_HEADER_HEIGHT = 36;
function RailRowStatus({ item }: { item: ModelPickerRailItem }) {
if (item.kind === "provider" && item.status === "loading") {
return (
@@ -470,30 +455,14 @@ function RailRowStatus({ item }: { item: ModelPickerRailItem }) {
if (item.kind === "provider" && item.status === "error") {
return <ThemedAlertTriangle size={ICON_SIZE.xs} uniProps={foregroundMutedMapping} />;
}
return null;
return <Text style={styles.count}>{item.count}</Text>;
}
type ListEntry =
| {
kind: "heading";
key: string;
title: string;
action?:
| { kind: "editProfiles" }
| { kind: "customizeProvider"; providerId: string; providerLabel: string };
}
| { kind: "heading"; key: string; title: string }
| { kind: "item"; key: string; item: ModelPickerListItem<AgentProfilePickerRow> };
function paneHasInlineProfiles(pane: ModelPickerPane<AgentProfilePickerRow>): boolean {
return (
(pane.kind === "provider" ||
pane.kind === "providerLoading" ||
pane.kind === "providerError") &&
pane.profiles.length > 0
);
}
/** Search results and single-pane profiles+models carry section headings; every other pane is flat. */
/** Search results carry section headings between their groups; every other pane is a flat list. */
function useListEntries(pane: ModelPickerPane<AgentProfilePickerRow>): ListEntry[] {
const { t } = useTranslation();
return useMemo(() => {
@@ -502,35 +471,6 @@ function useListEntries(pane: ModelPickerPane<AgentProfilePickerRow>): ListEntry
key: item.key,
item,
});
if (paneHasInlineProfiles(pane)) {
if (
pane.kind !== "provider" &&
pane.kind !== "providerLoading" &&
pane.kind !== "providerError"
) {
return [];
}
return [
{
kind: "heading",
key: "heading:profiles",
title: t("modelSelector.profiles"),
action: { kind: "editProfiles" },
},
...pane.profiles.map(toEntry),
{
kind: "heading",
key: `heading:provider:${pane.providerId}`,
title: pane.label,
action: {
kind: "customizeProvider",
providerId: pane.providerId,
providerLabel: pane.label,
},
},
...(pane.kind === "provider" ? pane.models.map(toEntry) : []),
];
}
if (pane.kind !== "search") return pane.items.map(toEntry);
const entries: ListEntry[] = [];
if (pane.profiles.length > 0) {
@@ -549,22 +489,6 @@ function useListEntries(pane: ModelPickerPane<AgentProfilePickerRow>): ListEntry
}, [pane, t]);
}
function computeEntryLayout(entries: readonly ListEntry[]): {
lengths: number[];
offsets: number[];
} {
const lengths: number[] = [];
const offsets: number[] = [];
let offset = 0;
for (const entry of entries) {
const length = entry.kind === "heading" ? MODEL_PICKER_HEADING_HEIGHT : MODEL_PICKER_ROW_HEIGHT;
lengths.push(length);
offsets.push(offset);
offset += length;
}
return { lengths, offsets };
}
/** The first row reveals as the list top, so a section heading above it stays in view. */
function resolveRevealTarget(entries: readonly ListEntry[], activeKey: string | null) {
if (!activeKey) return null;
@@ -577,15 +501,8 @@ function getListEntryKey(entry: ListEntry): string {
return entry.key;
}
function paneShowsHeader(pane: ModelPickerPane<AgentProfilePickerRow>): boolean {
if (pane.kind === "search" || pane.kind === "noMatches") return false;
if (paneHasInlineProfiles(pane)) return false;
return true;
}
function ListPane({
projection,
pickerHeight,
query,
input,
serverId,
@@ -594,7 +511,6 @@ function ListPane({
actions,
}: {
projection: ModelPickerProjection<AgentProfilePickerRow>;
pickerHeight: number;
/** Each query is a new result list, which opens at its top. */
query: string;
input: ModelPickerInput<AgentProfilePickerRow>;
@@ -605,41 +521,23 @@ function ListPane({
}) {
const { pane, activeKey } = projection;
const entries = useListEntries(pane);
const listRef = useRef<FlatList<ListEntry>>(null);
const reveal = useRevealActiveFlatListRow({
listRef,
itemCount: entries.length,
activeIndex: resolveRevealTarget(entries, activeKey),
listKey: `${pane.kind}:${projection.railKey}:${query}`,
});
const profiledLookup = useMemo(
() => groupProfilesByProviderModel(input.profiles ?? []),
[input.profiles],
);
const inSearch = pane.kind === "search";
const { selectedProvider, selectedModel } = input;
const hasPaneHeader = paneShowsHeader(pane);
const visibleCount = Math.max(
1,
Math.floor(
(pickerHeight - INLINE_HEADER_HEIGHT - (hasPaneHeader ? PANE_HEADER_HEIGHT : 0)) /
MODEL_PICKER_ROW_HEIGHT,
),
);
// Keyed per browse pane so switching providers in the rail opens at the new provider's initial
// scroll position instead of flashing the previous provider's scroll offset for a frame.
const paneListKey = inSearch ? "search" : `${pane.kind}:${projection.railKey}`;
const renderEntry = useCallback(
({ item: entry }: { item: ListEntry }) => {
if (entry.kind === "heading") {
let headingAction: ReactNode = null;
if (entry.action?.kind === "editProfiles" && actions.onEditProfiles) {
headingAction = <EditProfilesButton onPress={actions.onEditProfiles} />;
} else if (entry.action?.kind === "customizeProvider" && serverId) {
headingAction = (
<CustomizeProviderButton
serverId={serverId}
providerId={entry.action.providerId}
providerLabel={entry.action.providerLabel}
/>
);
}
return <ModelBrowserSectionHeading title={entry.title} action={headingAction} />;
}
if (entry.kind === "heading") return <ModelBrowserSectionHeading title={entry.title} />;
const { item } = entry;
return (
<ModelPickerItemRow
@@ -672,102 +570,33 @@ function ListPane({
],
);
const inlineStateFooter = useMemo(
() => (entries.length > 0 ? <PaneState pane={pane} actions={actions} /> : null),
[actions, entries.length, pane],
);
return (
<View style={styles.listPane} testID="model-picker-list">
<ListPaneHeader pane={pane} serverId={serverId} onEditProfiles={actions.onEditProfiles} />
<PaneState pane={pane} actions={actions} />
{entries.length > 0 ? (
<PaneFlatList
key={paneListKey}
entries={entries}
activeKey={activeKey}
listKey={inSearch ? query : paneListKey}
visibleCount={visibleCount}
renderEntry={renderEntry}
listFooter={inlineStateFooter}
<FlatList
ref={listRef}
data={entries}
extraData={activeKey}
renderItem={renderEntry}
keyExtractor={getListEntryKey}
onScrollToIndexFailed={reveal.onScrollToIndexFailed}
onViewableItemsChanged={reveal.onViewableItemsChanged}
viewabilityConfig={reveal.viewabilityConfig}
onContentSizeChange={reveal.onContentSizeChange}
onLayout={reveal.onLayout}
style={styles.scroll}
contentContainerStyle={styles.listContent}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
testID="model-picker-model-list"
/>
) : (
<PaneState pane={pane} actions={actions} />
)}
) : null}
</View>
);
}
function PaneFlatList({
entries,
activeKey,
listKey,
visibleCount,
renderEntry,
listFooter,
}: {
entries: ListEntry[];
activeKey: string | null;
listKey: string;
visibleCount: number;
renderEntry: ({ item }: { item: ListEntry }) => React.ReactElement;
listFooter?: ReactElement | null;
}) {
const listRef = useRef<FlatList<ListEntry>>(null);
const entryLayout = useMemo(() => computeEntryLayout(entries), [entries]);
const getItemLayout = useCallback(
(_data: ArrayLike<ListEntry> | null | undefined, index: number) => ({
length: entryLayout.lengths[index] ?? MODEL_PICKER_ROW_HEIGHT,
offset: entryLayout.offsets[index] ?? index * MODEL_PICKER_ROW_HEIGHT,
index,
}),
[entryLayout],
);
const offsetForIndex = useCallback(
(index: number) => entryLayout.offsets[index] ?? index * MODEL_PICKER_ROW_HEIGHT,
[entryLayout],
);
const revealTarget = resolveRevealTarget(entries, activeKey);
const { initialScrollIndex, contentOffset, initialVisibleRange } = useInitialFlatListScroll({
listRef,
selectedIndex: typeof revealTarget === "number" ? revealTarget : null,
itemCount: entries.length,
visibleCount,
offsetForIndex,
});
const reveal = useRevealActiveFlatListRow({
listRef,
itemCount: entries.length,
activeIndex: revealTarget,
initialVisibleRange,
listKey,
});
return (
<FlatList
ref={listRef}
data={entries}
extraData={activeKey}
renderItem={renderEntry}
keyExtractor={getListEntryKey}
getItemLayout={getItemLayout}
initialScrollIndex={initialScrollIndex}
contentOffset={contentOffset}
ListFooterComponent={listFooter}
onScrollToIndexFailed={reveal.onScrollToIndexFailed}
onViewableItemsChanged={reveal.onViewableItemsChanged}
viewabilityConfig={reveal.viewabilityConfig}
onContentSizeChange={reveal.onContentSizeChange}
onLayout={reveal.onLayout}
style={styles.scroll}
contentContainerStyle={styles.listContent}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
testID="model-picker-model-list"
/>
);
}
function ListPaneHeader({
pane,
serverId,
@@ -778,22 +607,36 @@ function ListPaneHeader({
onEditProfiles?: () => void;
}) {
const { t } = useTranslation();
if (!paneShowsHeader(pane)) return null;
if (pane.kind === "search" || pane.kind === "noMatches") return null;
if (pane.kind === "profiles") {
return (
<View style={styles.paneHeader}>
<Text style={styles.paneTitle} numberOfLines={1}>
{t("modelSelector.profiles")}
</Text>
{onEditProfiles ? <EditProfilesButton onPress={onEditProfiles} /> : null}
{onEditProfiles ? (
<Button
variant="ghost"
size="sm"
onPress={onEditProfiles}
accessibilityLabel={t("modelSelector.editProfilesLabel")}
testID="model-profiles-edit"
>
{t("modelSelector.editProfiles")}
</Button>
) : null}
</View>
);
}
if (pane.kind === "search" || pane.kind === "noMatches") return null;
const summary =
pane.kind === "provider" && pane.foldKind !== null
? t("modelSelector.shownOfTotal", { shown: pane.shown, total: pane.total })
: null;
return (
<View style={styles.paneHeader}>
<Text style={styles.paneTitle} numberOfLines={1}>
{pane.label}
{summary ? <Text style={styles.paneSummary}>{` · ${summary}`}</Text> : null}
</Text>
{serverId ? (
<CustomizeProviderButton
@@ -806,20 +649,6 @@ function ListPaneHeader({
);
}
export function EditProfilesButton({ onPress }: { onPress: () => void }) {
const { t } = useTranslation();
return (
<Button
variant="ghost"
size="sm"
leftIcon={Pencil}
onPress={onPress}
accessibilityLabel={t("modelSelector.editProfilesLabel")}
testID="model-profiles-edit"
/>
);
}
export function CustomizeProviderButton({
serverId,
providerId,
@@ -1032,6 +861,11 @@ const styles = StyleSheet.create((theme) => ({
railSpinner: {
transform: [{ scale: 0.7 }],
},
count: {
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
fontVariant: ["tabular-nums"],
},
listPane: {
flex: 1,
minWidth: 0,
@@ -1044,7 +878,7 @@ const styles = StyleSheet.create((theme) => ({
paddingBottom: theme.spacing[2],
},
paneHeader: {
height: PANE_HEADER_HEIGHT,
height: 36,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
@@ -1058,4 +892,8 @@ const styles = StyleSheet.create((theme) => ({
fontWeight: theme.fontWeight.medium,
color: theme.colors.foreground,
},
paneSummary: {
fontWeight: theme.fontWeight.normal,
color: theme.colors.foregroundMuted,
},
}));
+12 -15
View File
@@ -101,10 +101,6 @@ const DESKTOP_PROVIDER_VIEW_MAX_HEIGHT = 400;
const DESKTOP_PROVIDER_VIEW_BASE_HEIGHT = 80;
const DESKTOP_MODEL_ROW_HEIGHT = 40;
/** Fixed picker row heights so virtualized lists can mount directly at the selected row via `getItemLayout`. */
export const MODEL_PICKER_ROW_HEIGHT = isWeb ? 36 : 44;
export const MODEL_PICKER_HEADING_HEIGHT = 32;
const ThemedAlertTriangle = withUnistyles(AlertTriangle);
const ThemedCheck = withUnistyles(Check);
const ThemedChevronRight = withUnistyles(ChevronRight);
@@ -2040,28 +2036,29 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.border,
},
sectionHeading: {
height: MODEL_PICKER_HEADING_HEIGHT,
position: "relative",
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[3] },
paddingHorizontal: isWeb ? theme.spacing[3] : theme.spacing[6],
paddingTop: theme.spacing[2],
paddingBottom: theme.spacing[1],
},
sectionHeadingAction: {
flexShrink: 0,
alignItems: "center",
justifyContent: "center",
position: "absolute",
top: theme.spacing[1],
right: isWeb ? theme.spacing[3] : theme.spacing[6],
},
sectionHeadingText: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.sm,
fontWeight: theme.fontWeight.normal,
color: theme.colors.foregroundMuted,
},
browserRow: {
flexDirection: "row",
alignItems: "center",
height: MODEL_PICKER_ROW_HEIGHT,
paddingVertical: theme.spacing[2],
minHeight: 36,
},
modelRowHoverBoundary: {
position: "relative",
@@ -2070,10 +2067,10 @@ const styles = StyleSheet.create((theme) => ({
position: "absolute",
top: 0,
bottom: 0,
right: { xs: theme.spacing[4], md: theme.spacing[3] },
right: isWeb ? theme.spacing[3] : theme.spacing[6],
justifyContent: "center",
},
browserModelRow: {},
browserModelRow: isWeb ? {} : { marginBottom: theme.spacing[1] },
browserRowHovered: {
backgroundColor: theme.colors.surface1,
},
@@ -2091,7 +2088,7 @@ const styles = StyleSheet.create((theme) => ({
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[3] },
paddingHorizontal: isWeb ? theme.spacing[3] : theme.spacing[6],
},
browserRowLeading: {
width: 16,
@@ -2,12 +2,19 @@ import { useCallback, useMemo, useState, type ReactNode } from "react";
import { View } from "react-native";
import { isWeb } from "@/constants/platform";
import { SettingsRowChildren } from "./row-children";
import { SettingsRowHeader } from "./row-header";
import { SettingsRowHeader, type SettingsRowHintStatus } from "./row-header";
interface SettingsCollapsibleRowProps {
label: string;
/** A line under the label explaining the group. */
hint?: string;
hintStatus?: SettingsRowHintStatus;
/** A short status shown before the chevron, so the row says something while collapsed. */
summary?: string;
/** A control acting on the row's subject in place, such as a switch, before the chevron. */
control?: ReactNode;
/** Names the expand/collapse button for assistive tech when the label alone is not enough. */
accessibilityLabel?: string;
defaultExpanded?: boolean;
testID?: string;
/** The rows revealed underneath, separated like the rows of a `SettingsCard` and laid out as nested rows. */
@@ -21,7 +28,11 @@ interface SettingsCollapsibleRowProps {
*/
export function SettingsCollapsibleRow({
label,
hint,
hintStatus,
summary,
control,
accessibilityLabel,
defaultExpanded = false,
testID,
children,
@@ -39,7 +50,11 @@ export function SettingsCollapsibleRow({
<View testID={testID}>
<SettingsRowHeader
label={label}
hint={hint}
hintStatus={hintStatus}
summary={summary}
control={control}
accessibilityLabel={accessibilityLabel}
onPress={toggle}
expanded={expanded}
accessibilityState={accessibilityState}
+15 -3
View File
@@ -56,13 +56,25 @@ interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtr
hint?: ReactNode;
}
export function SettingsCard({ children, testID }: { children: ReactNode; testID?: string }) {
/** Lets a card and its rows shrink below their content, so a list inside can scroll. */
const SHRINK = { flexShrink: 1, minHeight: 0 } as const;
export function SettingsCard({
children,
testID,
shrink = false,
}: {
children: ReactNode;
testID?: string;
/** The card shrinks to fit a parent with a bounded height, and a list inside it scrolls. */
shrink?: boolean;
}) {
return (
<View style={settingsStyles.card} testID={testID}>
<View style={[settingsStyles.card, shrink && SHRINK]} testID={testID}>
{Children.toArray(children).map((child, index) => (
<View
key={isValidElement(child) ? child.key : index}
style={index ? settingsStyles.rowBorder : undefined}
style={[index ? settingsStyles.rowBorder : undefined, shrink && SHRINK]}
>
{child}
</View>
@@ -151,8 +151,5 @@ describe("settings row density", () => {
const summary = textNode("short-summary", "Local").getBoundingClientRect();
// The summary's margin, the chevron and the row's padding: about 40px.
expect(row.right - summary.right).toBeLessThan(48);
expect(titleFontSize("short-summary", "Local")).toBe(
titleFontSize("short-summary", "Speech to text"),
);
});
});
@@ -141,7 +141,6 @@ export function SettingsRowHeader({
hovered={hovered}
summary={summary}
summaryLeading={summaryLeading}
titleStyle={layout.title}
/>
{external || disabled ? null : (
<View style={chevronStyle} {...HIDDEN_FROM_ASSISTIVE_TECH}>
@@ -168,17 +167,14 @@ function RowTrailing({
hovered,
summary,
summaryLeading,
titleStyle,
}: {
hinted: boolean;
external: boolean;
hovered: boolean;
summary: string | undefined;
summaryLeading: ReactNode;
titleStyle: SettingsRowLayout["title"];
}) {
const style = hinted ? styles.hintedTrailing : styles.labelTrailing;
const summaryStyle = useMemo(() => [titleStyle, styles.summary], [titleStyle]);
return (
<View style={[style, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
{/* Drawn the same as a section header's docs link, so the two read as one thing. */}
@@ -187,7 +183,7 @@ function RowTrailing({
<View style={styles.summaryLeading}>{summaryLeading}</View>
) : null}
{!external && summary ? (
<Text style={summaryStyle} numberOfLines={1}>
<Text style={styles.summary} numberOfLines={1}>
{summary}
</Text>
) : null}
@@ -319,6 +315,7 @@ const styles = StyleSheet.create((theme) => ({
summary: {
flexShrink: 1,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
marginRight: theme.spacing[2],
},
hovered: {
@@ -54,8 +54,6 @@ import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-
import {
collectAllPanes,
createDefaultLayout,
resolveGroupSizes,
resolveMainSplitTree,
selectExplorerSidebarPaneId,
useWorkspaceLayoutStore,
type SplitNode,
@@ -82,7 +80,7 @@ interface SplitContainerProps {
uiTabs: WorkspaceTab[];
hoveredCloseTabKey: string | null;
setHoveredCloseTabKey: Dispatch<SetStateAction<string | null>>;
closingTabIds: ReadonlySet<string>;
closingTabIds: Set<string>;
onNavigateTab: (tabId: string) => void;
onCloseTab: (tabId: string) => Promise<void> | void;
onCopyResumeCommand: (agentId: string) => Promise<void> | void;
@@ -207,7 +205,7 @@ export function SplitContainer({
);
const mainRoot = useMemo(
() => resolveMainSplitTree(layout.root, explorerSidebarPaneId),
() => removePaneFromSplitTree(layout.root, explorerSidebarPaneId),
[layout.root, explorerSidebarPaneId],
);
const workspaceHasMultiplePanes = Boolean(mainRoot && hasMultipleVisiblePanes(mainRoot));
@@ -461,10 +459,11 @@ function SplitNodeView({
);
const groupChildren = node.kind === "group" ? node.group.children : EMPTY_SPLIT_NODES;
// Dragged sizes live per group id, apart from the layout tree, and a group keeps its id when
// panes are added or removed. A list of the wrong length would leave the dividers past its end
// unable to move.
// panes are added or removed. They only apply while they still have one entry per child;
// otherwise the dividers past the end of the list could not move.
const layoutGroupSizes = node.kind === "group" ? node.group.sizes : EMPTY_SPLIT_SIZES;
const groupSizes =
node.kind === "group" ? resolveGroupSizes(node.group, storedGroupSizes) : EMPTY_SPLIT_SIZES;
storedGroupSizes?.length === groupChildren.length ? storedGroupSizes : layoutGroupSizes;
const visibleFlex = useMemo(
() => resolveVisibleGroupFlex(groupChildren, groupSizes, maximizedPaneId),
[groupChildren, groupSizes, maximizedPaneId],
@@ -911,6 +910,34 @@ function wrapRootPaneForStableMount(node: SplitNode): SplitNode {
};
}
function removePaneFromSplitTree(node: SplitNode, paneId: string | null): SplitNode | null {
if (!paneId) {
return node;
}
if (node.kind === "pane") {
return node.pane.id === paneId ? null : node;
}
const children = node.group.children.flatMap((child) => {
const nextChild = removePaneFromSplitTree(child, paneId);
return nextChild ? [nextChild] : [];
});
if (children.length === 0) {
return null;
}
if (children.length === 1) {
return children[0] ?? null;
}
return {
kind: "group",
group: {
...node.group,
children,
sizes: children.map(() => 1 / children.length),
},
};
}
const styles = StyleSheet.create((theme) => ({
workspaceShell: {
flex: 1,
@@ -89,7 +89,9 @@ const styles = StyleSheet.create((theme: Theme) => ({
top: 0,
bottom: 0,
width: INDENT_GUIDE_WIDTH,
backgroundColor: theme.colors.treeGuide,
// Translucent ink, not `border`: a solid line that colour disappears into a hovered row's fill.
backgroundColor: theme.colors.foregroundExtraMuted,
opacity: theme.opacity[50],
},
chevron: {
width: WORKSPACE_TREE_ICON_SIZE,
+5 -23
View File
@@ -1,5 +1,4 @@
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
import { useSettledKeyboardHeight } from "@/keyboard/shift";
import { Modal } from "@/components/ui/modal";
import {
useCallback,
@@ -944,34 +943,19 @@ function maybePinDesktopOptionsToBottom(
interface FloatingMiddlewareInput {
collisionPadding: number;
keyboardHeight: number;
isDesktopAboveSearch: boolean;
setAvailableSize: FloatingSizeSetters["setAvailableSize"];
setReferenceWidth: FloatingSizeSetters["setReferenceWidth"];
}
function buildFloatingMiddleware(input: FloatingMiddlewareInput) {
const {
collisionPadding,
keyboardHeight,
isDesktopAboveSearch,
setAvailableSize,
setReferenceWidth,
} = input;
// The native popover's boundary is the window, which the software keyboard covers. The keyboard
// height changes once the keyboard settles, so this also re-measures an anchor that rides it.
const padding = {
top: collisionPadding,
left: collisionPadding,
right: collisionPadding,
bottom: collisionPadding + keyboardHeight,
};
const { collisionPadding, isDesktopAboveSearch, setAvailableSize, setReferenceWidth } = input;
return [
floatingOffset(isWeb ? 5 : 4),
...(isWeb ? [] : [flip({ padding })]),
...(isDesktopAboveSearch ? [] : [shift({ padding })]),
...(isWeb ? [] : [flip({ padding: collisionPadding })]),
...(isDesktopAboveSearch ? [] : [shift({ padding: collisionPadding })]),
floatingSize({
padding,
padding: collisionPadding,
apply({ availableWidth, availableHeight, rects }) {
updateAvailableSize(setAvailableSize, availableWidth, availableHeight);
updateReferenceWidth(setReferenceWidth, rects.reference.width);
@@ -1512,18 +1496,16 @@ export function Combobox({
useResetSearchOnOpen(isOpen, setSearchQueryWithCallback, bumpSearchResetKey);
const collisionPadding = useMemo(computeCollisionPadding, []);
const keyboardHeight = useSettledKeyboardHeight();
const middleware = useMemo(
() =>
buildFloatingMiddleware({
collisionPadding,
keyboardHeight,
isDesktopAboveSearch,
setAvailableSize,
setReferenceWidth,
}),
[collisionPadding, isDesktopAboveSearch, keyboardHeight],
[collisionPadding, isDesktopAboveSearch],
);
const { refs, floatingStyles, update } = useFloating({
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { getScrollOffsetToRevealItem, resolveInitialScrollIndex } from "./scroll-reveal";
import { getScrollOffsetToRevealItem } from "./scroll-reveal";
describe("getScrollOffsetToRevealItem", () => {
it("keeps the offset when the item is already inside the viewport", () => {
@@ -46,38 +46,3 @@ describe("getScrollOffsetToRevealItem", () => {
).toBe(120);
});
});
describe("resolveInitialScrollIndex", () => {
it("stays at the top when the selected item is already in the first viewport", () => {
expect(resolveInitialScrollIndex({ selectedIndex: 0, itemCount: 20, visibleCount: 5 })).toBe(
undefined,
);
expect(resolveInitialScrollIndex({ selectedIndex: 4, itemCount: 20, visibleCount: 5 })).toBe(
undefined,
);
});
it("centers a deeper selected item inside the visible viewport", () => {
expect(resolveInitialScrollIndex({ selectedIndex: 9, itemCount: 236, visibleCount: 5 })).toBe(
7,
);
});
it("clamps near the end so the bottom viewport stays full", () => {
expect(resolveInitialScrollIndex({ selectedIndex: 235, itemCount: 236, visibleCount: 5 })).toBe(
231,
);
expect(resolveInitialScrollIndex({ selectedIndex: 19, itemCount: 20, visibleCount: 7 })).toBe(
13,
);
});
it("returns undefined for empty or out-of-range selections", () => {
expect(resolveInitialScrollIndex({ selectedIndex: null, itemCount: 20, visibleCount: 5 })).toBe(
undefined,
);
expect(resolveInitialScrollIndex({ selectedIndex: 5, itemCount: 3, visibleCount: 5 })).toBe(
undefined,
);
});
});
@@ -1,4 +1,4 @@
import { useCallback, useLayoutEffect, useRef, type RefObject } from "react";
import { useCallback, useEffect, useLayoutEffect, useRef, type RefObject } from "react";
import type {
FlatList,
LayoutChangeEvent,
@@ -8,7 +8,6 @@ import type {
View,
ViewToken,
} from "react-native";
import { isNative, isWeb } from "@/constants/platform";
export function getScrollOffsetToRevealItem(args: {
currentOffset: number;
@@ -126,88 +125,6 @@ interface VisibleRange {
last: number;
}
/**
* Computes the `FlatList` `initialScrollIndex` that opens with `selectedIndex` in view without
* flashing index 0 first. Returns `undefined` when the row is already inside the first page so
* the list starts cleanly at the top.
*/
export function resolveInitialScrollIndex(args: {
selectedIndex: number | null;
itemCount: number;
visibleCount: number;
}): number | undefined {
const { selectedIndex, itemCount, visibleCount } = args;
if (
selectedIndex === null ||
selectedIndex < 0 ||
selectedIndex >= itemCount ||
visibleCount <= 0
) {
return undefined;
}
if (selectedIndex < visibleCount) {
return undefined;
}
const maxStart = Math.max(0, itemCount - visibleCount);
const centered = selectedIndex - Math.floor(visibleCount / 2);
const index = Math.min(Math.max(0, centered), maxStart);
return index > 0 ? index : undefined;
}
/**
* Opens a virtualized `FlatList` directly at `selectedIndex` without flashing index 0 first.
* Captures the mount offset once, supplies `initialScrollIndex` (and iOS `contentOffset`), and
* sets the web scroll position synchronously before first paint.
*/
export function useInitialFlatListScroll<T>(options: {
listRef: RefObject<FlatList<T> | null>;
selectedIndex: number | null;
itemCount: number;
visibleCount: number;
offsetForIndex: (index: number) => number;
}): {
initialScrollIndex: number | undefined;
contentOffset: { x: number; y: number } | undefined;
initialVisibleRange: VisibleRange;
} {
const { listRef, selectedIndex, itemCount, visibleCount, offsetForIndex } = options;
const initialMount = useRef<{
initialScrollIndex: number | undefined;
offset: number;
contentOffset: { x: number; y: number } | undefined;
initialVisibleRange: VisibleRange;
} | null>(null);
if (initialMount.current === null) {
const initialScrollIndex = resolveInitialScrollIndex({
selectedIndex,
itemCount,
visibleCount,
});
const start = initialScrollIndex ?? 0;
const offset = initialScrollIndex !== undefined ? offsetForIndex(initialScrollIndex) : 0;
initialMount.current = {
initialScrollIndex,
offset,
// Both iOS and Android ScrollViews apply contentOffset during native layout before first paint.
contentOffset: isNative && offset > 0 ? { x: 0, y: offset } : undefined,
initialVisibleRange: { first: start, last: start + Math.max(visibleCount, 1) - 1 },
};
}
const initialOffset = initialMount.current.offset;
useLayoutEffect(() => {
if (isWeb && initialOffset > 0) {
listRef.current?.scrollToOffset({ offset: initialOffset, animated: false });
}
}, [initialOffset, listRef]);
return {
initialScrollIndex: initialMount.current.initialScrollIndex,
contentOffset: initialMount.current.contentOffset,
initialVisibleRange: initialMount.current.initialVisibleRange,
};
}
function nextVisibleRangeAfterReveal(
visible: VisibleRange | null,
row: number,
@@ -230,7 +147,6 @@ export function useRevealActiveFlatListRow<T>({
activeIndex,
hasHeader = false,
waitForViewable = false,
initialVisibleRange = null,
listKey,
}: {
listRef: RefObject<FlatList<T> | null>;
@@ -238,12 +154,9 @@ export function useRevealActiveFlatListRow<T>({
activeIndex: number | "top" | null;
hasHeader?: boolean;
waitForViewable?: boolean;
/** Seeded visible window when the list mounted at an `initialScrollIndex`. */
initialVisibleRange?: VisibleRange | null;
listKey?: unknown;
}): RevealActiveFlatListHandlers<T> {
const fullyVisibleRows = useRef<VisibleRange | null>(initialVisibleRange);
const prevListKey = useRef(listKey);
const fullyVisibleRows = useRef<VisibleRange | null>(null);
const pendingReveal = useRef<number | null>(null);
const isPendingRowMeasured = useRef(true);
const itemCountRef = useRef(itemCount);
@@ -309,11 +222,7 @@ export function useRevealActiveFlatListRow<T>({
[revealPendingRow],
);
useLayoutEffect(() => {
if (prevListKey.current !== listKey) {
prevListKey.current = listKey;
fullyVisibleRows.current = null;
}
useEffect(() => {
if (activeIndex === "top") {
pendingReveal.current = null;
listRef.current?.scrollToOffset({ offset: 0, animated: false });
@@ -7,7 +7,7 @@ import {
} from "react-native";
import { Search, X } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import type { Theme } from "@/styles/theme";
import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
@@ -35,11 +35,6 @@ export interface SearchFieldProps {
fullWidth?: boolean;
/** `sm` heads a list in tight chrome such as a sidebar pane. */
size?: "sm" | "md";
/**
* `card` matches a compact `SettingsCard` row's height, corner radius, horizontal inset, and
* leading glyph rail so a docked sheet search aligns with the cards above it.
*/
variant?: "default" | "card";
/** Escape empties the field. Off where Escape already closes the surface around it. */
clearOnEscape?: boolean;
testID?: string;
@@ -61,7 +56,6 @@ export function SearchField({
clearAccessibilityLabel,
fullWidth = false,
size = "md",
variant = "default",
clearOnEscape = false,
testID,
clearTestID,
@@ -85,21 +79,17 @@ export function SearchField({
if (value === "" && inputRef.current?.getText()) inputRef.current.replaceText("");
}, [value]);
const small = size === "sm";
const card = variant === "card";
const leadingIcon = <ThemedSearch size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
return (
<View
testID={testID ? `${testID}-container` : undefined}
style={[
styles.field,
small && styles.fieldSmall,
card && styles.fieldCard,
fullWidth && styles.fieldFullWidth,
isFocused && styles.fieldFocused,
]}
>
{card ? <View style={styles.leadingSlot}>{leadingIcon}</View> : leadingIcon}
<ThemedSearch size={14} uniProps={mutedColorMapping} />
<ThemedTextInput
testID={testID}
ref={inputRef}
@@ -122,9 +112,8 @@ export function SearchField({
accessibilityRole="button"
accessibilityLabel={clearAccessibilityLabel}
hitSlop={8}
style={card ? styles.clearSlot : undefined}
>
<ThemedX size={ICON_SIZE.sm} uniProps={mutedColorMapping} />
<ThemedX size={14} uniProps={mutedColorMapping} />
</Pressable>
) : null}
</View>
@@ -153,25 +142,6 @@ const styles = StyleSheet.create((theme) => ({
paddingVertical: 0,
paddingHorizontal: theme.spacing[1.5],
},
fieldCard: {
// Matches a collapsed SettingsCard row: 44pt inner row height + 1px top/bottom border = 46pt.
height: 46,
paddingVertical: 0,
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[3] },
borderRadius: theme.borderRadius.lg,
},
leadingSlot: {
width: 16,
alignItems: "center",
justifyContent: "center",
},
clearSlot: {
width: ICON_SIZE.sm,
height: ICON_SIZE.sm,
marginRight: -theme.spacing[1],
alignItems: "center",
justifyContent: "center",
},
fieldFullWidth: {
maxWidth: "100%",
},
@@ -24,7 +24,7 @@ import {
import { useWorkspaceSetupStore } from "@/stores/workspace-setup-store";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { applyLegacyDaemonWorkspaceOwnership } from "@/workspace/legacy-daemon-workspaces";
import { prepareImageAttachmentsForSend } from "@/attachments/service";
import { uploadImageAttachments } from "@/attachments/service";
import { toErrorMessage } from "@/utils/error-messages";
import {
resolveComposerAttachmentSubmitFormat,
@@ -122,7 +122,6 @@ function failureMessageForCreationMethod(
function buildCreateAgentOptions({
composerState,
text,
images,
attachments,
workspaceDirectory,
workspaceId,
@@ -135,7 +134,6 @@ function buildCreateAgentOptions({
selectedSystemPrompt: string;
};
text: string;
images?: CreateAgentRequestOptions["images"];
attachments: NonNullable<CreateAgentRequestOptions["attachments"]>;
workspaceDirectory: string;
workspaceId: string;
@@ -154,7 +152,6 @@ function buildCreateAgentOptions({
? { systemPrompt: composerState.selectedSystemPrompt }
: {}),
...(text.trim() ? { initialPrompt: text.trim() } : {}),
...(images && images.length > 0 ? { images } : {}),
...(attachments.length > 0 ? { attachments } : {}),
};
}
@@ -330,20 +327,19 @@ export function WorkspaceSetupDialog() {
supportsForgeAttachments: supportsForgeSearch,
}),
});
const imagePayload =
const uploadedImageAttachments =
wirePayload.images.length > 0
? await prepareImageAttachmentsForSend({
? await uploadImageAttachments({
client: withConnectedClient(),
images: wirePayload.images,
})
: {};
: undefined;
if (!pendingWorkspaceSetup) throw new Error(t("workspaceSetup.errors.pendingRequired"));
let createdAgent: AgentSnapshotPayload | undefined;
const { workspaceId: _workspaceId, ...agentInput } = buildCreateAgentOptions({
composerState,
text,
images: imagePayload.images,
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
attachments: [...wirePayload.attachments, ...(uploadedImageAttachments ?? [])],
workspaceDirectory: cwd,
workspaceId: "",
provider: composerState.selectedProvider,
@@ -1,13 +1,16 @@
import { Image } from "expo-image";
import { Image } from "react-native";
import type { ViewportSize } from "./geometry";
/**
* Resolves the image's natural size; rejects when the image cannot load or has no size. Decodes
* with Expo Image, the same decoder that draws the image: React Native's `Image.getSize` cannot
* decode SVG on Android or iOS.
*/
export async function measureImage(uri: string): Promise<ViewportSize> {
const { width, height } = await Image.loadAsync(uri);
if (width > 0 && height > 0) return { width, height };
throw new Error("Image has no size");
/** Resolves the image's natural size; rejects when the image cannot load or has no size. */
export function measureImage(uri: string): Promise<ViewportSize> {
return new Promise((resolve, reject) => {
Image.getSize(
uri,
(width, height) => {
if (width > 0 && height > 0) resolve({ width, height });
else reject(new Error("Image has no size"));
},
reject,
);
});
}
@@ -1,15 +1,11 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Image } from "expo-image";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Image, View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import type { ViewportFitOptions, ViewportSize } from "./geometry";
import { measureImage } from "./image-size";
import { ZoomableViewport } from "./index";
import type { ZoomableViewportAction } from "./types";
// Expo Image draws SVG as well as raster images; React Native's Image cannot draw SVG on native.
const ViewportImage = withUnistyles(Image);
interface ZoomableImageProps {
uri: string;
accessibilityLabel?: string;
@@ -81,12 +77,12 @@ export function ZoomableImage({
testID={testID}
wheelActivation={wheelActivation}
>
<ViewportImage
// No transition, so the image appears together with its toolbar.
transition={null}
contentFit="contain"
<Image
// Android fades a freshly decoded image in over 300ms; it appears with its toolbar instead.
fadeDuration={0}
onError={onError}
onLoad={handleLoad}
resizeMode="contain"
source={source}
style={styles.image}
testID={`${testID}-image`}
+3 -8
View File
@@ -191,11 +191,7 @@ interface FakeSendCall {
}
function createFakeSendClient(
options: {
rejection?: Error;
beforeRejection?: (call: FakeSendCall) => void;
uploadedImageAttachments?: boolean;
} = {},
options: { rejection?: Error; beforeRejection?: (call: FakeSendCall) => void } = {},
): ComposerSendClient & {
calls: FakeSendCall[];
uploadCalls: Array<{ fileName: string; mimeType: string; bytes: Uint8Array }>;
@@ -205,9 +201,6 @@ function createFakeSendClient(
return {
calls,
uploadCalls,
getLastServerInfoMessage: () => ({
features: { uploadedImageAttachments: options.uploadedImageAttachments ?? true },
}),
sendAgentMessage: async (agentId, text, opts) => {
const call = { agentId, text, options: opts };
calls.push(call);
@@ -1104,6 +1097,7 @@ describe("file upload preparation", () => {
const sent: string[] = [];
const upload = uploadFileAttachments({
client: {
sendAgentMessage: async () => {},
uploadFile: async (file) => {
sent.push(file.fileName);
expect(file.bytes).toEqual(new Uint8Array([1, 2]));
@@ -1143,6 +1137,7 @@ describe("file upload preparation", () => {
await expect(
uploadFileAttachments({
client: {
sendAgentMessage: async () => {},
uploadFile: async () => {
sends++;
throw new Error("unexpected send");
+6 -11
View File
@@ -1,5 +1,5 @@
import type { SelectedFile } from "@/attachments/selected-file";
import { prepareImageAttachmentsForSend } from "@/attachments/service";
import { uploadImageAttachments } from "@/attachments/service";
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
import type {
ActiveTurnBehavior,
@@ -65,7 +65,6 @@ export interface ComposerSendClient {
file: UploadedFileAttachment | null;
error: string | null;
}>;
getLastServerInfoMessage: () => { features?: { uploadedImageAttachments?: boolean } } | null;
}
export interface ComposerCancelClient {
@@ -122,7 +121,7 @@ export async function pickAndPersistImages(input: {
}
export async function uploadFileAttachments(input: {
client: Pick<ComposerSendClient, "uploadFile">;
client: ComposerSendClient;
files: SelectedFile[];
}): Promise<Extract<ComposerAttachment, { kind: "file" }>[]> {
const result: Extract<ComposerAttachment, { kind: "file" }>[] = [];
@@ -214,17 +213,13 @@ export async function dispatchComposerAgentMessage(
});
input.submission.begin(input.agentId, userMessage);
try {
const imagePayload = input.uploadImages
? { attachments: await input.uploadImages(wirePayload.images) }
: await prepareImageAttachmentsForSend({
client: input.client,
images: wirePayload.images,
});
const uploadedImageAttachments = input.uploadImages
? await input.uploadImages(wirePayload.images)
: await uploadImageAttachments({ client: input.client, images: wirePayload.images });
await input.client.sendAgentMessage(input.agentId, input.text, {
messageId: clientMessageId,
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
...(imagePayload.images ? { images: imagePayload.images } : {}),
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
attachments: [...wirePayload.attachments, ...(uploadedImageAttachments ?? [])],
});
input.submission.accept(input.agentId, clientMessageId);
} catch (error) {
@@ -12,8 +12,6 @@ import {
import { ModelProviderGlyph } from "@/components/model-browser";
import type { ModelPickerActions } from "@/components/model-browser-panes";
import {
CollapsibleProfilesCard,
getSheetSearchFooterStyle,
MobileModelPageView,
SheetSearchDock,
useMobileModelPage,
@@ -88,7 +86,6 @@ export function AgentSettingsDrawer({
}: AgentSettingsDrawerProps) {
const { t } = useTranslation();
const [page, setPage] = useState<AgentSheetPage>(AGENT_SHEET_HOME);
const [profilesExpanded, setProfilesExpanded] = useState(false);
// Select pages search with this; the Model page keeps its own.
const [pageQuery, setPageQuery] = useState("");
const [pageSearchKey, setPageSearchKey] = useState(0);
@@ -96,16 +93,10 @@ export function AgentSettingsDrawer({
providers,
profiles: profiles?.rows ?? null,
canCreateProfile: Boolean(onEditProfiles),
// Profiles lives directly on Agent settings Home above Model; unified search still covers it.
showProfilesSection: false,
selectedProvider,
selectedModel,
});
const toggleProfiles = useCallback(() => {
setProfilesExpanded((expanded) => !expanded);
}, []);
const goTo = useCallback((next: AgentSheetPage) => {
Keyboard.dismiss();
setPageQuery("");
@@ -125,7 +116,6 @@ export function AgentSettingsDrawer({
const close = useCallback(() => {
Keyboard.dismiss();
setPage(AGENT_SHEET_HOME);
setProfilesExpanded(false);
setPageQuery("");
modelPage.reset();
onClose();
@@ -272,39 +262,15 @@ export function AgentSettingsDrawer({
const topCard = useMemo(
() => (
<View style={styles.topStack}>
{profiles !== null ? (
<CollapsibleProfilesCard
profiles={profiles.rows}
expanded={profilesExpanded}
onToggle={toggleProfiles}
serverId={serverId}
onApplyProfile={handleApplyProfile}
onEditProfiles={onEditProfiles ? handleEditProfiles : undefined}
/>
) : null}
<AgentSheetTopCard
selectedProvider={selectedProvider}
serverId={serverId}
selectedModelLabel={selectedModelLabel}
disabled={disabled}
onOpenModel={openModel}
/>
</View>
<AgentSheetTopCard
selectedProvider={selectedProvider}
serverId={serverId}
selectedModelLabel={selectedModelLabel}
disabled={disabled}
onOpenModel={openModel}
/>
),
[
disabled,
handleApplyProfile,
handleEditProfiles,
onEditProfiles,
openModel,
profiles,
profilesExpanded,
selectedModelLabel,
selectedProvider,
serverId,
toggleProfiles,
],
[disabled, openModel, selectedModelLabel, selectedProvider, serverId],
);
let body: ReactNode;
@@ -353,7 +319,6 @@ export function AgentSettingsDrawer({
snapPoints={SNAP_POINTS}
scrollable={false}
footer={footer}
footerContainerStyle={getSheetSearchFooterStyle()}
keyboard={keyboard}
contentStyle={styles.sheetBody}
contextBridge={contextBridge}
@@ -445,16 +410,13 @@ function SelectSearchDock({
);
}
const styles = StyleSheet.create((theme) => ({
const styles = StyleSheet.create(() => ({
sheetBody: {
paddingHorizontal: 0,
paddingTop: 0,
paddingBottom: 0,
gap: 0,
},
topStack: {
gap: theme.spacing[3],
},
page: {
flex: 1,
minHeight: 0,
@@ -660,7 +660,7 @@ const styles = StyleSheet.create((theme) => ({
sliderValue: {
marginLeft: theme.spacing[3],
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
fontSize: theme.fontSize.sm,
},
radioRow: {
minHeight: 44,
@@ -155,39 +155,6 @@ describe("resolveAgentModelSelection", () => {
expect(selection.selectedThinkingId).toBe("high");
});
it("lists and selects the agent's thinking level when the model does not list it", () => {
const selection = resolveAgentModelSelection({
models: [
{
id: "opus",
provider: "claude",
label: "opus",
thinkingOptions: [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium" },
{ id: "high", label: "High", isDefault: true },
{ id: "max", label: "Max" },
],
defaultThinkingOptionId: "high",
},
],
runtimeModelId: "opus",
configuredModelId: "opus",
runtimeThinkingOptionId: null,
explicitThinkingOptionId: "xhigh",
});
expect(selection.selectedThinkingId).toBe("xhigh");
expect(selection.displayThinking).toBe("Extra high");
expect(selection.thinkingOptions?.map((option) => option.id)).toEqual([
"low",
"medium",
"high",
"max",
"xhigh",
]);
});
it("formats raw thinking labels in the selected model display", () => {
const selection = resolveAgentModelSelection({
models: [
@@ -130,21 +130,6 @@ function resolveEffectiveThinking(
return selectedThinking ?? thinkingOptions?.[0] ?? null;
}
// The agent runs on its level even when the model's list leaves it out. The level joins the
// list, so the controls show and check it and none of them falls back to the first option.
function includeResolvedThinkingOption(
thinkingOptions: ThinkingOption[] | null,
resolvedThinkingId: string | null,
): ThinkingOption[] | null {
if (!thinkingOptions || thinkingOptions.length === 0 || !resolvedThinkingId) {
return thinkingOptions;
}
if (thinkingOptions.some((option) => option.id === resolvedThinkingId)) {
return thinkingOptions;
}
return [...thinkingOptions, { id: resolvedThinkingId, label: resolvedThinkingId }];
}
function resolveModelDisplay(
selectedModel: AgentModelDefinition | null,
preferredModelId: string | null,
@@ -207,15 +192,12 @@ export function resolveAgentModelSelection(input: {
i18n.t("agentControls.model.unknown"),
);
const thinkingOptions = selectedModel?.thinkingOptions ?? null;
const resolvedThinkingId = resolveThinkingId(
runtimeThinkingOptionId,
explicitThinkingOptionId,
selectedModel,
);
const thinkingOptions = includeResolvedThinkingOption(
selectedModel?.thinkingOptions ?? null,
resolvedThinkingId,
);
const effectiveThinking = resolveEffectiveThinking(thinkingOptions, resolvedThinkingId);
const selectedThinkingId = effectiveThinking?.id ?? resolvedThinkingId;
const displayThinking = resolveThinkingDisplay(
@@ -4,22 +4,14 @@ import type { AttachmentMetadata, AttachmentStore } from "@/attachments/types";
import { __setAttachmentStoreForTests } from "@/attachments/store";
import { requestWorkspaceDraftAgent } from "./create-agent-request";
function createFakeStore(
bytesById: Record<string, Uint8Array>,
options: { allowEncodeBase64?: boolean } = {},
): AttachmentStore {
function createFakeStore(bytesById: Record<string, Uint8Array>): AttachmentStore {
return {
storageType: "web-indexeddb",
async save() {
throw new Error("not used");
},
async encodeBase64({ attachment }) {
if (!options.allowEncodeBase64) {
throw new Error("encodeBase64 must not be called when uploading images");
}
const bytes = bytesById[attachment.id];
if (!bytes) throw new Error(`missing ${attachment.id}`);
return Buffer.from(bytes).toString("base64");
async encodeBase64() {
throw new Error("encodeBase64 must not be called when uploading images");
},
async readBytes({ attachment }) {
const bytes = bytesById[attachment.id];
@@ -62,11 +54,7 @@ describe("requestWorkspaceDraftAgent", () => {
id: "agent-new",
...input,
}));
const client = {
uploadFile,
createAgent,
getLastServerInfoMessage: () => ({ features: { uploadedImageAttachments: true } }),
} as unknown as DaemonClient;
const client = { uploadFile, createAgent } as unknown as DaemonClient;
const images: AttachmentMetadata[] = [
{
@@ -122,50 +110,4 @@ describe("requestWorkspaceDraftAgent", () => {
},
]);
});
it("falls back to inline base64 images when the daemon does not advertise uploadedImageAttachments", async () => {
const photoBytes = new Uint8Array([9, 8, 7, 6]);
__setAttachmentStoreForTests(
createFakeStore({ imgLegacy: photoBytes }, { allowEncodeBase64: true }),
);
const uploadFile = vi.fn(async () => {
throw new Error("uploadFile must not be called against legacy daemons");
});
const createAgent = vi.fn(async (input: Record<string, unknown>) => ({
id: "agent-legacy",
...input,
}));
const client = {
uploadFile,
createAgent,
getLastServerInfoMessage: () => ({ features: {} }),
} as unknown as DaemonClient;
await requestWorkspaceDraftAgent(client, {
workspaceId: "ws-legacy",
config: { provider: "claude", cwd: "/repo" },
text: "Inspect legacy photo",
clientMessageId: "draft:legacy-image",
images: [
{
id: "imgLegacy",
mimeType: "image/png",
storageType: "web-indexeddb",
storageKey: "imgLegacy",
fileName: "legacy.png",
byteSize: photoBytes.byteLength,
createdAt: 1,
},
],
});
expect(uploadFile).not.toHaveBeenCalled();
expect(createAgent).toHaveBeenCalledTimes(1);
const createCall = createAgent.mock.calls[0]?.[0] as Record<string, unknown>;
expect(createCall.attachments).toBeUndefined();
expect(createCall.images).toEqual([
{ data: Buffer.from(photoBytes).toString("base64"), mimeType: "image/png" },
]);
});
});
@@ -1,7 +1,7 @@
import type { AgentSessionConfig } from "@getpaseo/protocol/agent-types";
import type { AgentSnapshotPayload, CreateAgentRequestMessage } from "@getpaseo/protocol/messages";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { prepareImageAttachmentsForSend } from "@/attachments/service";
import { uploadImageAttachments } from "@/attachments/service";
import type { AttachmentMetadata } from "@/attachments/types";
export interface WorkspaceDraftAgentRequest {
@@ -21,14 +21,13 @@ export async function requestWorkspaceDraftAgent(
client: DaemonClient,
request: WorkspaceDraftAgentRequest,
): Promise<AgentSnapshotPayload> {
const imagePayload = await prepareImageAttachmentsForSend({ client, images: request.images });
const mergedAttachments = [...(request.attachments ?? []), ...(imagePayload.attachments ?? [])];
const uploadedImageAttachments = await uploadImageAttachments({ client, images: request.images });
const mergedAttachments = [...(request.attachments ?? []), ...(uploadedImageAttachments ?? [])];
return await client.createAgent({
config: request.config,
workspaceId: request.workspaceId,
clientMessageId: request.clientMessageId,
...(request.text ? { initialPrompt: request.text } : {}),
...(imagePayload.images ? { images: imagePayload.images } : {}),
...(mergedAttachments.length > 0 ? { attachments: mergedAttachments } : {}),
});
}
@@ -22,7 +22,7 @@ import { useCreateFlowStore } from "@/stores/create-flow-store";
import type { Agent } from "@/stores/session-store";
import { useWorkspaceFields } from "@/stores/session-store-hooks";
import { useWorkspaceDraftSubmissionStore } from "@/stores/workspace-draft-submission-store";
import { prepareImageAttachmentsForSend } from "@/attachments/service";
import { uploadImageAttachments } from "@/attachments/service";
import { shouldAutoFocusWorkspaceDraftComposer } from "@/screens/workspace/workspace-draft-pane-focus";
import {
resolveDraftWorkingDirectory,
@@ -190,15 +190,14 @@ async function submitDraftCreateRequest(input: {
});
const attachmentsArray = Array.isArray(attachments) ? attachments : [];
const imagePayload = await prepareImageAttachmentsForSend({ client, images });
const mergedAttachments = [...attachmentsArray, ...(imagePayload.attachments ?? [])];
const uploadedImageAttachments = await uploadImageAttachments({ client, images });
const mergedAttachments = [...attachmentsArray, ...(uploadedImageAttachments ?? [])];
const request = {
config,
workspaceId,
initialPrompt: text,
clientMessageId: attempt.clientMessageId,
...(Object.keys(composerState.metadata).length > 0 ? { metadata: composerState.metadata } : {}),
...(imagePayload.images ? { images: imagePayload.images } : {}),
...(mergedAttachments.length > 0 ? { attachments: mergedAttachments } : {}),
};
const result = await client.createAgent({
+1 -15
View File
@@ -2038,24 +2038,15 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
void handleStopRealtimeVoice();
}, [handleStopRealtimeVoice]);
const showFocusBorder = isInputFocused && !readOnly && !disabled;
const inputWrapperCombinedStyle = useMemo(
() => [
styles.inputWrapper,
Platform.OS !== "ios" && isCompact && !isFullscreen && styles.inputWrapperCompact,
readOnly && styles.inputWrapperReadOnly,
showFocusBorder && styles.inputWrapperFocused,
inputWrapperStyle,
{ opacity: surfacePresentation.input.opacity },
],
[
inputWrapperStyle,
isCompact,
isFullscreen,
readOnly,
showFocusBorder,
surfacePresentation.input.opacity,
],
[inputWrapperStyle, isCompact, isFullscreen, readOnly, surfacePresentation.input.opacity],
);
// `withUnistyles` maps this component's `style` into a `.hash > *` child
// rule, which ties on specificity with react-native-web's own
@@ -2457,11 +2448,6 @@ const styles = StyleSheet.create((theme: Theme) => ({
inputWrapperReadOnly: {
borderStyle: "dotted",
},
// A neutral step up from the resting `borderAccent`, never the accent. There is no hover
// step: `surface3` is fainter than the resting border in the pure black theme.
inputWrapperFocused: {
borderColor: theme.colors.surface4,
},
// The band the fullscreen glyph sits in is the input's own padding, so a tap
// anywhere in it (under the glyph, or where the glyph would be) is a tap on the
// editor: it focuses, shows the keyboard, and places the caret. Reserved whether
+15 -2
View File
@@ -5,10 +5,23 @@ import invariant from "tiny-invariant";
import { BrowserPane } from "@/desktop/browser/pane";
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
import { definePanel, type PanelDescriptor, type PanelIconProps } from "@/panels/panel-registry";
import { browserTabLabel } from "@/panels/tab-labels";
import { useBrowserStore } from "@/desktop/browser/store";
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
function getBrowserLabel(input: { title: string; url: string }): string {
const title = input.title.trim();
if (title) {
return title;
}
try {
const parsed = new URL(input.url);
return parsed.hostname || input.url;
} catch {
return input.url;
}
}
function createBrowserTabIcon(faviconUrl: string | null) {
return function BrowserTabIcon({ size, color }: PanelIconProps) {
const source = useMemo(() => (faviconUrl ? { uri: faviconUrl } : undefined), []);
@@ -29,7 +42,7 @@ function useBrowserPanelDescriptor(target: {
const browser = useBrowserStore((state) => state.browsersById[target.browserId] ?? null);
const url = browser?.url ?? "https://example.com";
const icon = createBrowserTabIcon(browser?.faviconUrl ?? null);
const label = browserTabLabel({ title: browser?.title ?? "", url });
const label = getBrowserLabel({ title: browser?.title ?? "", url });
return {
label,
@@ -1,135 +0,0 @@
/** One workspace's file tree state, driven from inside and outside React. */
import {
loadExplorerDirectory,
type DirectoryListingResult,
} from "@/file-explorer/directory-listings";
import { clearFileFilter } from "@/file-explorer/filter";
import { useExplorerRevealStore } from "@/file-explorer/reveal-request";
import { revealExplorerEntry } from "@/file-explorer/tree";
import { i18n } from "@/i18n/i18next";
import { usePanelStore } from "@/stores/panel-store";
import { useSessionStore, type AgentFileExplorerState } from "@/stores/session-store";
export interface FileExplorerWorkspaceScope {
workspaceId?: string | null;
workspaceRoot?: string | null;
}
/** The tree being driven: its host, its state key, and the directory it lists. */
export interface WorkspaceFileTree {
serverId: string;
stateKey: string;
workspaceRoot: string | null;
}
function createExplorerState(): AgentFileExplorerState {
return {
listingGeneration: 0,
directories: new Map(),
isLoading: false,
lastError: null,
pendingRequest: null,
currentPath: ".",
history: ["."],
lastVisitedPath: ".",
selectedEntryPath: null,
};
}
export function normalizeWorkspaceValue(value: string | null | undefined): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
export function buildWorkspaceExplorerStateKey(scope: FileExplorerWorkspaceScope): string | null {
const normalizedWorkspaceId = normalizeWorkspaceValue(scope.workspaceId);
if (normalizedWorkspaceId) {
return `workspace:${normalizedWorkspaceId}`;
}
const normalizedWorkspaceRoot = normalizeWorkspaceValue(scope.workspaceRoot);
if (!normalizedWorkspaceRoot) {
return null;
}
return `root:${normalizedWorkspaceRoot}`;
}
export function updateWorkspaceExplorerState(
tree: Pick<WorkspaceFileTree, "serverId" | "stateKey">,
updater: (prev: AgentFileExplorerState) => AgentFileExplorerState,
): AgentFileExplorerState | null {
let updated: AgentFileExplorerState | null = null;
useSessionStore.getState().setFileExplorer(tree.serverId, (prev) => {
const next = new Map(prev);
const current = next.get(tree.stateKey) ?? createExplorerState();
updated = updater(current);
next.set(tree.stateKey, updated);
return next;
});
return updated;
}
export function listWorkspaceExplorerDirectory(
tree: WorkspaceFileTree,
path: string,
options?: { recordHistory?: boolean; setCurrentPath?: boolean },
): Promise<DirectoryListingResult> {
const normalizedPath = path && path.length > 0 ? path : ".";
return loadExplorerDirectory({
path: normalizedPath,
options,
updateState: (updater) => updateWorkspaceExplorerState(tree, updater),
fallbackError: i18n.t("workspace.fileExplorer.errors.failedToListDirectory"),
listDirectory: async () => {
if (!tree.workspaceRoot) {
throw new Error(i18n.t("workspace.fileExplorer.states.unavailable"));
}
const client = useSessionStore.getState().sessions[tree.serverId]?.client;
if (!client) throw new Error(i18n.t("workspace.terminal.hostDisconnected"));
return client.listDirectory(tree.workspaceRoot, normalizedPath);
},
});
}
export function showWorkspaceExplorerHiddenFiles(): void {
const panel = usePanelStore.getState();
if (!panel.explorerShowHiddenFiles) panel.toggleExplorerShowHiddenFiles();
}
export function expandWorkspaceExplorerPaths(stateKey: string, paths: string[]): void {
usePanelStore
.getState()
.setExpandedPathsForWorkspace(stateKey, (current) =>
Array.from(new Set([...current, ...paths])),
);
}
/** Selects an entry the tree has expanded to, and asks the tree to scroll to it. */
export function showWorkspaceExplorerEntry(
tree: Pick<WorkspaceFileTree, "serverId" | "stateKey">,
entryPath: string,
): void {
updateWorkspaceExplorerState(tree, (state) => ({ ...state, selectedEntryPath: entryPath }));
useExplorerRevealStore.getState().request(tree.stateKey, entryPath);
}
/** Expands to an entry, selects it, and asks the tree to scroll to it. */
export async function revealWorkspaceExplorerEntry(
tree: WorkspaceFileTree,
entryPath: string,
): Promise<boolean> {
const found = await revealExplorerEntry({
entryPath,
requestDirectoryListing: (path) =>
listWorkspaceExplorerDirectory(tree, path, { recordHistory: false, setCurrentPath: false }),
showHiddenFiles: showWorkspaceExplorerHiddenFiles,
expandPaths: (paths) => expandWorkspaceExplorerPaths(tree.stateKey, paths),
});
if (found) {
clearFileFilter(tree.stateKey);
showWorkspaceExplorerEntry(tree, entryPath);
}
return found;
}
+2 -3
View File
@@ -155,15 +155,14 @@ function MountedFilePanel({
revision: number;
onModifiedChange: (modified: boolean) => void;
}) {
const { tabId, state, setCurrentTabState } = usePaneContext();
const { state, setCurrentTabState } = usePaneContext();
const tab = useMemo<PluginTab>(
() => ({
id: tabId,
setModified: onModifiedChange,
state,
setState: setCurrentTabState,
}),
[tabId, onModifiedChange, state, setCurrentTabState],
[onModifiedChange, state, setCurrentTabState],
);
useEffect(() => () => onModifiedChange(false), [onModifiedChange]);
return <FilePanelView panel={panel} file={file} tab={tab} params={params} revision={revision} />;
+41 -49
View File
@@ -1,13 +1,13 @@
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { useCallback, useMemo } from "react";
import {
useMutation,
useQuery,
useQueryClient,
type MutationOptions,
type QueryClient,
type QueryKey,
} from "@tanstack/react-query";
import { i18n } from "@/i18n/i18next";
import { useTranslation } from "react-i18next";
import { useSessionStore } from "@/stores/session-store";
import { agentHistoryQueryKey, allAgentHistoryQueryRootKey } from "./agent-history-query-key";
@@ -380,95 +380,87 @@ export function usePendingArchiveAgentIds(serverId: string): ReadonlySet<string>
);
}
/**
* Archives an agent: hides it right away, then asks the daemon, and puts it back if that fails.
*/
export async function archiveAgent(
queryClient: QueryClient,
input: ArchiveAgentInput,
): Promise<void> {
const options: MutationOptions<
{ archivedAt: string },
Error,
ArchiveAgentInput,
ArchiveAgentMutationContext
> = {
mutationFn: async (variables) => {
const client = useSessionStore.getState().sessions[variables.serverId]?.client ?? null;
export function useArchiveAgent() {
const queryClient = useQueryClient();
const { t } = useTranslation();
const pendingQuery = useArchiveAgentPendingQuery();
const archiveMutation = useMutation({
mutationFn: async (input: ArchiveAgentInput): Promise<{ archivedAt: string }> => {
const client = useSessionStore.getState().sessions[input.serverId]?.client ?? null;
if (!client) {
throw new Error(i18n.t("common.errors.daemonClientUnavailable"));
throw new Error(t("common.errors.daemonClientUnavailable"));
}
return await client.archiveAgent(variables.agentId);
return await client.archiveAgent(input.agentId);
},
onMutate: (variables) => {
onMutate: (input) => {
const context: ArchiveAgentMutationContext = {
agent: getStoredAgentSnapshot(variables),
lists: getArchivedAgentListCacheSnapshot(queryClient, variables.serverId),
agent: getStoredAgentSnapshot(input),
lists: getArchivedAgentListCacheSnapshot(queryClient, input.serverId),
};
const archivedAt = new Date().toISOString();
applyArchivedAgentCloseResults({
queryClient,
serverId: variables.serverId,
results: [{ agentId: variables.agentId, archivedAt }],
serverId: input.serverId,
results: [{ agentId: input.agentId, archivedAt }],
invalidateQueries: false,
});
setAgentArchiving({
queryClient,
serverId: variables.serverId,
agentId: variables.agentId,
serverId: input.serverId,
agentId: input.agentId,
isArchiving: true,
});
return context;
},
onSuccess: (result, variables) => {
onSuccess: (result, input) => {
markAgentArchivedInStore({
serverId: variables.serverId,
agentId: variables.agentId,
serverId: input.serverId,
agentId: input.agentId,
archivedAt: result.archivedAt,
});
},
onError: (_error, variables, context) => {
onError: (_error, input, context) => {
if (!context) {
return;
}
restoreAgentSnapshot({
serverId: variables.serverId,
agentId: variables.agentId,
serverId: input.serverId,
agentId: input.agentId,
agent: context.agent,
});
restoreArchivedAgentListCacheSnapshot(queryClient, variables.serverId, context.lists);
restoreArchivedAgentListCacheSnapshot(queryClient, input.serverId, context.lists);
},
onSettled: (_result, _error, variables) => {
onSettled: (_result, _error, input) => {
clearArchiveAgentPending({
queryClient,
serverId: variables.serverId,
agentId: variables.agentId,
serverId: input.serverId,
agentId: input.agentId,
});
void queryClient.invalidateQueries({
queryKey: ["sidebarAgentsList", variables.serverId],
queryKey: ["sidebarAgentsList", input.serverId],
});
void queryClient.invalidateQueries({
queryKey: ["allAgents", variables.serverId],
queryKey: ["allAgents", input.serverId],
});
void queryClient.invalidateQueries({
queryKey: agentHistoryQueryKey(variables.serverId),
queryKey: agentHistoryQueryKey(input.serverId),
});
void queryClient.invalidateQueries({
queryKey: allAgentHistoryQueryRootKey(),
});
},
};
await queryClient.getMutationCache().build(queryClient, options).execute(input);
}
});
export function useArchiveAgent() {
const queryClient = useQueryClient();
const pendingQuery = useArchiveAgentPendingQuery();
const archiveMutateAsync = archiveMutation.mutateAsync;
const archive = useCallback(
(input: ArchiveAgentInput): Promise<void> => archiveAgent(queryClient, input),
[queryClient],
const archiveAgent = useCallback(
async (input: ArchiveAgentInput): Promise<void> => {
await archiveMutateAsync(input);
},
[archiveMutateAsync],
);
const isArchivingAgent = useCallback(
@@ -483,7 +475,7 @@ export function useArchiveAgent() {
);
return {
archiveAgent: archive,
archiveAgent,
isArchivingAgent,
};
}
@@ -1,32 +1,61 @@
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useSessionStore, type AgentFileExplorerState } from "@/stores/session-store";
import { revealExplorerDirectory } from "@/file-explorer/tree";
import { usePanelStore } from "@/stores/panel-store";
import { revealExplorerDirectory, revealExplorerEntry } from "@/file-explorer/tree";
import { useExplorerRevealStore } from "@/file-explorer/reveal-request";
import { clearFileFilter } from "@/file-explorer/filter";
import {
loadExplorerDirectory,
type DirectoryListingResult,
invalidateExplorerDirectoryListings,
} from "@/file-explorer/directory-listings";
import {
buildWorkspaceExplorerStateKey,
expandWorkspaceExplorerPaths,
listWorkspaceExplorerDirectory,
normalizeWorkspaceValue,
revealWorkspaceExplorerEntry,
showWorkspaceExplorerEntry,
showWorkspaceExplorerHiddenFiles,
updateWorkspaceExplorerState,
type FileExplorerWorkspaceScope,
type WorkspaceFileTree,
} from "@/file-explorer/workspace-tree";
import { parentExplorerPath } from "@/utils/explorer-paths";
export { buildWorkspaceExplorerStateKey, type FileExplorerWorkspaceScope };
function createExplorerState(): AgentFileExplorerState {
return {
listingGeneration: 0,
directories: new Map(),
isLoading: false,
lastError: null,
pendingRequest: null,
currentPath: ".",
history: ["."],
lastVisitedPath: ".",
selectedEntryPath: null,
};
}
export interface FileExplorerWorkspaceScope {
workspaceId?: string | null;
workspaceRoot?: string | null;
}
function normalizeWorkspaceValue(value: string | null | undefined): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
export function buildWorkspaceExplorerStateKey(scope: FileExplorerWorkspaceScope): string | null {
const normalizedWorkspaceId = normalizeWorkspaceValue(scope.workspaceId);
if (normalizedWorkspaceId) {
return `workspace:${normalizedWorkspaceId}`;
}
const normalizedWorkspaceRoot = normalizeWorkspaceValue(scope.workspaceRoot);
if (!normalizedWorkspaceRoot) {
return null;
}
return `root:${normalizedWorkspaceRoot}`;
}
export function useFileExplorerActions(params: { serverId: string } & FileExplorerWorkspaceScope) {
const { t } = useTranslation();
const { serverId, workspaceId, workspaceRoot } = params;
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
const setFileExplorer = useSessionStore((state) => state.setFileExplorer);
const normalizedWorkspaceRoot = useMemo(
() => normalizeWorkspaceValue(workspaceRoot),
[workspaceRoot],
@@ -40,28 +69,66 @@ export function useFileExplorerActions(params: { serverId: string } & FileExplor
[workspaceId, normalizedWorkspaceRoot],
);
const tree = useMemo<WorkspaceFileTree | null>(
() =>
workspaceStateKey
? { serverId, stateKey: workspaceStateKey, workspaceRoot: normalizedWorkspaceRoot }
: null,
[normalizedWorkspaceRoot, serverId, workspaceStateKey],
);
const updateExplorerState = useCallback(
(
updater: (prev: AgentFileExplorerState) => AgentFileExplorerState,
): AgentFileExplorerState | null => (tree ? updateWorkspaceExplorerState(tree, updater) : null),
[tree],
): AgentFileExplorerState | null => {
if (!workspaceStateKey) {
return null;
}
let updated: AgentFileExplorerState | null = null;
setFileExplorer(serverId, (prev) => {
const next = new Map(prev);
const current = next.get(workspaceStateKey) ?? createExplorerState();
updated = updater(current);
next.set(workspaceStateKey, updated);
return next;
});
return updated;
},
[serverId, setFileExplorer, workspaceStateKey],
);
const requestDirectoryListing = useCallback(
async (
path: string,
options?: { recordHistory?: boolean; setCurrentPath?: boolean },
): Promise<DirectoryListingResult> =>
tree ? listWorkspaceExplorerDirectory(tree, path, options) : null,
[tree],
): Promise<DirectoryListingResult> => {
if (!workspaceStateKey) {
return null;
}
const normalizedPath = path && path.length > 0 ? path : ".";
return loadExplorerDirectory({
path: normalizedPath,
options,
updateState: updateExplorerState,
fallbackError: t("workspace.fileExplorer.errors.failedToListDirectory"),
listDirectory: async () => {
if (!normalizedWorkspaceRoot)
throw new Error(t("workspace.fileExplorer.states.unavailable"));
if (!client) throw new Error(t("workspace.terminal.hostDisconnected"));
return client.listDirectory(normalizedWorkspaceRoot, normalizedPath);
},
});
},
[client, normalizedWorkspaceRoot, t, updateExplorerState, workspaceStateKey],
);
const showHiddenFiles = useCallback(() => {
const panel = usePanelStore.getState();
if (!panel.explorerShowHiddenFiles) panel.toggleExplorerShowHiddenFiles();
}, []);
const expandPaths = useCallback(
(paths: string[]) => {
if (!workspaceStateKey) return;
usePanelStore
.getState()
.setExpandedPathsForWorkspace(workspaceStateKey, (current) =>
Array.from(new Set([...current, ...paths])),
);
},
[workspaceStateKey],
);
const selectExplorerEntry = useCallback(
@@ -74,27 +141,50 @@ export function useFileExplorerActions(params: { serverId: string } & FileExplor
[updateExplorerState],
);
/** Selects an entry the tree has expanded to, and asks the tree to scroll to it. */
const showEntry = useCallback(
(entryPath: string) => {
if (!workspaceStateKey) return;
selectExplorerEntry(entryPath);
useExplorerRevealStore.getState().request(workspaceStateKey, entryPath);
},
[selectExplorerEntry, workspaceStateKey],
);
/** Expands to a directory and into it. `select` also selects it and scrolls the tree to it. */
const revealDirectory = useCallback(
async (directoryPath: string, { select = false }: { select?: boolean } = {}) => {
if (!tree) return;
if (!workspaceStateKey) return;
const listed = await revealExplorerDirectory({
directoryPath,
requestDirectoryListing,
showHiddenFiles: showWorkspaceExplorerHiddenFiles,
expandPaths: (paths) => expandWorkspaceExplorerPaths(tree.stateKey, paths),
showHiddenFiles,
expandPaths,
});
clearFileFilter(tree.stateKey);
if (listed && select) showWorkspaceExplorerEntry(tree, directoryPath);
clearFileFilter(workspaceStateKey);
if (listed && select) showEntry(directoryPath);
},
[requestDirectoryListing, tree],
[expandPaths, requestDirectoryListing, showEntry, showHiddenFiles, workspaceStateKey],
);
/** Expands to an entry, selects it, and asks the tree to scroll to it. */
const revealEntry = useCallback(
async (entryPath: string): Promise<boolean> =>
tree ? revealWorkspaceExplorerEntry(tree, entryPath) : false,
[tree],
async (entryPath: string): Promise<boolean> => {
if (!workspaceStateKey) return false;
const found = await revealExplorerEntry({
entryPath,
requestDirectoryListing: (path) =>
requestDirectoryListing(path, { recordHistory: false, setCurrentPath: false }),
showHiddenFiles,
expandPaths,
});
if (found) {
clearFileFilter(workspaceStateKey);
showEntry(entryPath);
}
return found;
},
[expandPaths, requestDirectoryListing, showEntry, showHiddenFiles, workspaceStateKey],
);
const requestFileDownloadToken = useCallback(
+1 -1
View File
@@ -385,7 +385,7 @@ describe("translation resources", () => {
expect(en.settings.host.notFound).toBe("Host not found");
expect(en.settings.host.connections.title).toBe("Connections");
expect(en.settings.host.daemon.restart.title).toBe("Restart daemon");
expect(en.settings.host.orchestration.enableTools.title).toBe("Enable Paseo tools");
expect(en.settings.host.orchestration.enableTools.title).toBe("Enable tools");
expect(en.settings.providers.title).toBe("Providers");
expect(en.settings.providers.models.addModel).toBe("Add model");
expect(en.settings.providers.diagnostic.title).toBe("Diagnostic");
+28 -4
View File
@@ -1889,6 +1889,7 @@ export const ar: TranslationResources = {
searchPlaceholder: "نماذج البحث...",
openProviderSettings: "افتح إعدادات{{provider}}",
searchModelsAndProfilesPlaceholder: "البحث في النماذج والملفات الشخصية...",
shownOfTotal: "{{shown}} معروضة من {{total}}",
olderModels: "نماذج أقدم ({{count}})",
allModels: "كل النماذج ({{count}})",
olderTag: "أقدم",
@@ -2642,6 +2643,9 @@ export const ar: TranslationResources = {
info: "يحوّل وضع الصوت كلامك إلى نص ويقرأ ردود الوكيل بصوت عالٍ.",
enabled: "وضع الصوت",
enabledHint: "تحدّث مع وكلائك دون استخدام يديك",
toolsRequiredTitle: "يتطلب وضع الصوت أدوات الوكلاء",
toolsRequiredDescription: "فعّل «تمكين الأدوات» حتى يتمكن الوكيل من نطق الردود.",
enablingTools: "جارٍ التمكين...",
},
openai: {
apiKey: "مفتاح API",
@@ -3133,15 +3137,35 @@ export const ar: TranslationResources = {
tools: {
instructionsTitle: "التعليمات",
toolsTitle: "أدوات الوكلاء",
pluginNote: "الأدوات التي تضيفها الإضافات تتبع أيضًا خيار تمكين الأدوات",
updateHostForGroups: "حدّث هذا المضيف لضبط مجموعات الأدوات الفردية",
groups: {
orchestration: {
title: "التنسيق",
hint: "إدارة مساحات العمل والوكلاء والطرفيات والسكربتات",
},
schedules: {
title: "الجداول الزمنية",
hint: "إنشاء وإدارة الجداول الزمنية ونبضات المتابعة",
},
changeRequests: {
title: "مراقبة طلبات السحب",
hint: "مراقبة تحديثات طلبات السحب والدمج",
},
browser: {
title: "المتصفح",
hint: "التحكم في علامات تبويب متصفح Paseo بما في ذلك الجلسات المسجّل الدخول إليها. فعّل هذا الخيار فقط للوكلاء الموثوقين.",
},
},
},
orchestration: {
title: "التنسيق",
unavailable: "اتصل بهذا المضيف لإدارة التنسيق",
enableTools: {
title: "تمكين أدوات Paseo",
hint: "سيتمكن الوكلاء من إدارة أشجار العمل والوكلاء والجداول الزمنية",
accessibilityLabel: "حقن أدوات Paseo",
updateFailed: "تعذر تحديث أدوات Paseo.",
title: "تمكين الأدوات",
hint: "يسمح لـ Paseo والإضافات بتوفير الأدوات للوكلاء. مطلوب لوضع الصوت.",
accessibilityLabel: "تمكين الأدوات",
updateFailed: "تعذر تحديث الأدوات.",
},
systemPrompt: {
title: "موجه النظام",
+28 -4
View File
@@ -1918,6 +1918,7 @@ export const en = {
searchPlaceholder: "Search models...",
openProviderSettings: "Open {{provider}} settings",
searchModelsAndProfilesPlaceholder: "Search models and profiles...",
shownOfTotal: "{{shown}} shown of {{total}}",
olderModels: "Older models ({{count}})",
allModels: "All models ({{count}})",
olderTag: "Older",
@@ -2740,6 +2741,9 @@ export const en = {
info: "Voice mode transcribes what you say and reads agent replies aloud.",
enabled: "Voice mode",
enabledHint: "Talk with your agents hands-free",
toolsRequiredTitle: "Voice mode requires agent tools",
toolsRequiredDescription: "Turn on Enable tools so the agent can speak replies.",
enablingTools: "Enabling...",
},
openai: {
apiKey: "API key",
@@ -3233,15 +3237,35 @@ export const en = {
tools: {
instructionsTitle: "Instructions",
toolsTitle: "Agent tools",
pluginNote: "Tools added by plugins also follow Enable tools",
updateHostForGroups: "Update this host to configure individual tool groups",
groups: {
orchestration: {
title: "Orchestration",
hint: "Manage workspaces, agents, terminals, and scripts",
},
schedules: {
title: "Schedules",
hint: "Create and manage schedules and heartbeats",
},
changeRequests: {
title: "PR watching",
hint: "Watch pull requests and merge requests for updates",
},
browser: {
title: "Browser",
hint: "Control Paseo browser tabs, including logged-in state. Enable only for agents you trust.",
},
},
},
orchestration: {
title: "Orchestration",
unavailable: "Connect to this host to manage orchestration",
enableTools: {
title: "Enable Paseo tools",
hint: "Agents will be able to manage worktrees, agents and schedules",
accessibilityLabel: "Inject Paseo tools",
updateFailed: "Unable to update Paseo tools.",
title: "Enable tools",
hint: "Let Paseo and plugins give tools to agents. Required for voice mode.",
accessibilityLabel: "Enable tools",
updateFailed: "Unable to update tools.",
},
systemPrompt: {
title: "System prompt",
+29 -4
View File
@@ -1939,6 +1939,7 @@ export const es: TranslationResources = {
searchPlaceholder: "Buscar modelos...",
openProviderSettings: "Abrir configuración de{{provider}}",
searchModelsAndProfilesPlaceholder: "Buscar modelos y perfiles...",
shownOfTotal: "{{shown}} visibles de {{total}}",
olderModels: "Modelos anteriores ({{count}})",
allModels: "Todos los modelos ({{count}})",
olderTag: "Anterior",
@@ -2664,6 +2665,10 @@ export const es: TranslationResources = {
info: "El modo de voz transcribe lo que dices y lee en voz alta las respuestas del agente.",
enabled: "Modo de voz",
enabledHint: "Habla con tus agentes sin usar las manos",
toolsRequiredTitle: "El modo de voz requiere herramientas de agentes",
toolsRequiredDescription:
"Activa Habilitar herramientas para que el agente pueda hablar sus respuestas.",
enablingTools: "Activando...",
},
openai: {
apiKey: "Clave de API",
@@ -3166,15 +3171,35 @@ export const es: TranslationResources = {
tools: {
instructionsTitle: "Instrucciones",
toolsTitle: "Herramientas de agentes",
pluginNote: "Las herramientas de los plugins también siguen Habilitar herramientas",
updateHostForGroups: "Actualiza este host para configurar grupos de herramientas",
groups: {
orchestration: {
title: "Orquestación",
hint: "Gestiona workspaces, agentes, terminales y scripts",
},
schedules: {
title: "Programaciones",
hint: "Crea y gestiona programaciones y heartbeats",
},
changeRequests: {
title: "Seguimiento de PR",
hint: "Supervisa pull requests y merge requests para ver actualizaciones",
},
browser: {
title: "Navegador",
hint: "Controla las pestañas del navegador de Paseo, incluido el estado con sesión iniciada. Actívalo solo para agentes de confianza.",
},
},
},
orchestration: {
title: "Orquestación",
unavailable: "Conéctese a este host para administrar la orquestación",
enableTools: {
title: "Habilitar herramientasPaseo",
hint: "Los agentes podrán gestionar árboles de trabajo, agentes y horarios.",
accessibilityLabel: "Inyectar herramientasPaseo",
updateFailed: "No se pudieron actualizar las herramientas de Paseo.",
title: "Habilitar herramientas",
hint: "Permite que Paseo y los plugins proporcionen herramientas a los agentes. Necesario para el modo de voz.",
accessibilityLabel: "Habilitar herramientas",
updateFailed: "No se pudieron actualizar las herramientas.",
},
systemPrompt: {
title: "Aviso del sistema",
+29 -4
View File
@@ -1937,6 +1937,7 @@ export const fr: TranslationResources = {
searchPlaceholder: "Rechercher des modèles…",
openProviderSettings: "Ouvrir les paramètres de {{provider}}",
searchModelsAndProfilesPlaceholder: "Rechercher des modèles et des profils…",
shownOfTotal: "{{shown}} affichés sur {{total}}",
olderModels: "Modèles plus anciens ({{count}})",
allModels: "Tous les modèles ({{count}})",
olderTag: "Ancien",
@@ -2664,6 +2665,10 @@ export const fr: TranslationResources = {
info: "Le mode vocal transcrit ce que vous dites et lit à voix haute les réponses de l'agent.",
enabled: "Mode vocal",
enabledHint: "Parlez à vos agents sans les mains",
toolsRequiredTitle: "Le mode vocal nécessite les outils des agents",
toolsRequiredDescription:
"Activez Activer les outils pour que l'agent puisse lire ses réponses à voix haute.",
enablingTools: "Activation...",
},
openai: {
apiKey: "Clé d'API",
@@ -3168,15 +3173,35 @@ export const fr: TranslationResources = {
tools: {
instructionsTitle: "Instructions",
toolsTitle: "Outils des agents",
pluginNote: "Les outils ajoutés par les plugins suivent aussi Activer les outils",
updateHostForGroups: "Mettez à jour cet hôte pour configurer chaque groupe d'outils",
groups: {
orchestration: {
title: "Orchestration",
hint: "Gérer les workspaces, les agents, les terminaux et les scripts",
},
schedules: {
title: "Planifications",
hint: "Créer et gérer des planifications et des heartbeats",
},
changeRequests: {
title: "Suivi des PR",
hint: "Surveiller les pull requests et merge requests",
},
browser: {
title: "Navigateur",
hint: "Contrôler les onglets du navigateur Paseo, y compris les sessions connectées. Activez uniquement pour des agents de confiance.",
},
},
},
orchestration: {
title: "Orchestration",
unavailable: "Connectez-vous à cet hôte pour gérer l’orchestration",
enableTools: {
title: "Activer les outils Paseo",
hint: "Les agents pourront gérer les worktrees, les agents et les planifications",
accessibilityLabel: "Injecter les outils Paseo",
updateFailed: "Impossible de mettre à jour les outils Paseo.",
title: "Activer les outils",
hint: "Autorise Paseo et les plugins à fournir des outils aux agents. Requis pour le mode vocal.",
accessibilityLabel: "Activer les outils",
updateFailed: "Impossible de mettre à jour les outils.",
},
systemPrompt: {
title: "Prompt système",
+29 -4
View File
@@ -1910,6 +1910,7 @@ export const ja: TranslationResources = {
searchPlaceholder: "モデルを検索...",
openProviderSettings: "{{provider}}の設定を開く",
searchModelsAndProfilesPlaceholder: "モデルとプロファイルを検索...",
shownOfTotal: "{{total}} 件中 {{shown}} 件を表示",
olderModels: "以前のモデル ({{count}})",
allModels: "すべてのモデル ({{count}})",
olderTag: "以前",
@@ -2632,6 +2633,10 @@ export const ja: TranslationResources = {
info: "ボイスモードは話した内容を文字起こしし、エージェントの返答を読み上げます。",
enabled: "ボイスモード",
enabledHint: "ハンズフリーでエージェントと会話します",
toolsRequiredTitle: "ボイスモードにはエージェントツールが必要です",
toolsRequiredDescription:
"エージェントが音声で返答できるように、ツールを有効にしてください。",
enablingTools: "有効化中...",
},
openai: {
apiKey: "API キー",
@@ -3128,15 +3133,35 @@ export const ja: TranslationResources = {
tools: {
instructionsTitle: "指示",
toolsTitle: "エージェントツール",
pluginNote: "プラグインが追加するツールもこのスイッチに従います",
updateHostForGroups: "ツールグループを個別に設定するにはホストを更新してください",
groups: {
orchestration: {
title: "オーケストレーション",
hint: "ワークスペース、エージェント、ターミナル、スクリプトを管理します",
},
schedules: {
title: "スケジュール",
hint: "スケジュールとハートビートを作成・管理します",
},
changeRequests: {
title: "PRの監視",
hint: "プルリクエストやマージリクエストの更新を監視します",
},
browser: {
title: "ブラウザ",
hint: "ログイン状態を含む Paseo のブラウザタブを操作します。信頼できるエージェントにのみ有効にしてください。",
},
},
},
orchestration: {
title: "オーケストレーション",
unavailable: "オーケストレーションを管理するにはこのホストに接続してください",
enableTools: {
title: "Paseoツールを有効にする",
hint: "エージェントがワークツリー、エージェント、スケジュールを管理できるようになります",
accessibilityLabel: "Paseoツールを有効にする",
updateFailed: "Paseoツールを更新できませんでした。",
title: "ツールを有効にする",
hint: "Paseo とプラグインからエージェントへツールを提供します。ボイスモードに必要です。",
accessibilityLabel: "ツールを有効にする",
updateFailed: "ツールを更新できませんでした。",
},
systemPrompt: {
title: "システムプロンプト",
+28 -4
View File
@@ -1901,6 +1901,7 @@ export const ko: TranslationResources = {
searchPlaceholder: "모델 검색...",
openProviderSettings: "{{provider}} 설정 열기",
searchModelsAndProfilesPlaceholder: "모델 및 프로필 검색...",
shownOfTotal: "{{total}}개 중 {{shown}}개 표시",
olderModels: "이전 모델 ({{count}})",
allModels: "모든 모델 ({{count}})",
olderTag: "이전",
@@ -2618,6 +2619,9 @@ export const ko: TranslationResources = {
info: "음성 모드는 말한 내용을 텍스트로 옮기고 에이전트의 답변을 소리 내어 읽어 줍니다.",
enabled: "음성 모드",
enabledHint: "손을 쓰지 않고 에이전트와 대화하세요",
toolsRequiredTitle: "음성 모드에는 에이전트 도구가 필요합니다",
toolsRequiredDescription: "에이전트가 음성으로 답할 수 있도록 도구 활성화를 켜세요.",
enablingTools: "활성화 중...",
},
openai: {
apiKey: "API 키",
@@ -3112,15 +3116,35 @@ export const ko: TranslationResources = {
tools: {
instructionsTitle: "지침",
toolsTitle: "에이전트 도구",
pluginNote: "플러그인이 추가한 도구도 도구 활성화 스위치를 따릅니다",
updateHostForGroups: "개별 도구 그룹을 설정하려면 이 호스트를 업데이트하세요",
groups: {
orchestration: {
title: "오케스트레이션",
hint: "워크스페이스, 에이전트, 터미널, 스크립트 관리",
},
schedules: {
title: "일정",
hint: "일정 및 하트비트 생성과 관리",
},
changeRequests: {
title: "PR 감시",
hint: "풀 리퀘스트와 머지 리퀘스트 업데이트 감시",
},
browser: {
title: "브라우저",
hint: "로그인된 상태를 포함해 Paseo 브라우저 탭을 제어합니다. 신뢰하는 에이전트에만 활성화하세요.",
},
},
},
orchestration: {
title: "오케스트레이션",
unavailable: "오케스트레이션을 관리하려면 이 호스트에 연결하세요",
enableTools: {
title: "Paseo 도구 활성화",
hint: "에이전트가 워크트리, 에이전트, 일정을 관리할 수 있습니다",
accessibilityLabel: "Paseo 도구 주입",
updateFailed: "Paseo 도구를 업데이트할 수 없습니다.",
title: "도구 활성화",
hint: "Paseo와 플러그인이 에이전트에 도구를 제공할 수 있게 합니다. 음성 모드에 필요합니다.",
accessibilityLabel: "도구 활성화",
updateFailed: "도구를 업데이트할 수 없습니다.",
},
systemPrompt: {
title: "시스템 프롬프트",
+29 -4
View File
@@ -1923,6 +1923,7 @@ export const ptBR: TranslationResources = {
searchPlaceholder: "Buscar modelos...",
openProviderSettings: "Abrir configurações de {{provider}}",
searchModelsAndProfilesPlaceholder: "Buscar modelos e perfis...",
shownOfTotal: "{{shown}} de {{total}} exibidos",
olderModels: "Modelos anteriores ({{count}})",
allModels: "Todos os modelos ({{count}})",
olderTag: "Anterior",
@@ -2649,6 +2650,10 @@ export const ptBR: TranslationResources = {
info: "O modo de voz transcreve o que você diz e lê em voz alta as respostas do agente.",
enabled: "Modo de voz",
enabledHint: "Converse com seus agentes sem usar as mãos",
toolsRequiredTitle: "O modo de voz requer ferramentas de agentes",
toolsRequiredDescription:
"Ative Ativar ferramentas para que o agente possa falar as respostas.",
enablingTools: "Ativando...",
},
openai: {
apiKey: "Chave de API",
@@ -3147,15 +3152,35 @@ export const ptBR: TranslationResources = {
tools: {
instructionsTitle: "Instruções",
toolsTitle: "Ferramentas de agentes",
pluginNote: "Ferramentas adicionadas por plugins também seguem Ativar ferramentas",
updateHostForGroups: "Atualize este host para configurar grupos de ferramentas",
groups: {
orchestration: {
title: "Orquestração",
hint: "Gerencie workspaces, agentes, terminais e scripts",
},
schedules: {
title: "Agendamentos",
hint: "Crie e gerencie agendamentos e heartbeats",
},
changeRequests: {
title: "Monitoramento de PR",
hint: "Acompanhe atualizações de pull requests e merge requests",
},
browser: {
title: "Navegador",
hint: "Controle abas do navegador do Paseo, incluindo sessões conectadas. Ative apenas para agentes confiáveis.",
},
},
},
orchestration: {
title: "Orquestração",
unavailable: "Conecte-se a este host para gerenciar a orquestração",
enableTools: {
title: "Ativar ferramentas do Paseo",
hint: "Agentes poderão gerenciar worktrees, agentes e agendamentos",
accessibilityLabel: "Injetar ferramentas do Paseo",
updateFailed: "Não foi possível atualizar as ferramentas do Paseo.",
title: "Ativar ferramentas",
hint: "Permite que o Paseo e plugins forneçam ferramentas aos agentes. Necessário para o modo de voz.",
accessibilityLabel: "Ativar ferramentas",
updateFailed: "Não foi possível atualizar as ferramentas.",
},
systemPrompt: {
title: "Prompt do sistema",
+29 -4
View File
@@ -1923,6 +1923,7 @@ export const ru: TranslationResources = {
searchPlaceholder: "Поиск моделей...",
openProviderSettings: "Открыть настройки {{provider}}",
searchModelsAndProfilesPlaceholder: "Поиск моделей и профилей...",
shownOfTotal: "Показано {{shown}} из {{total}}",
olderModels: "Старые модели ({{count}})",
allModels: "Все модели ({{count}})",
olderTag: "Старая",
@@ -2650,6 +2651,10 @@ export const ru: TranslationResources = {
info: "Голосовой режим расшифровывает вашу речь и зачитывает ответы агента вслух.",
enabled: "Голосовой режим",
enabledHint: "Общайтесь с агентами без рук",
toolsRequiredTitle: "Для голосового режима нужны инструменты агентов",
toolsRequiredDescription:
"Включите «Включить инструменты», чтобы агент мог озвучивать ответы.",
enablingTools: "Включение...",
},
openai: {
apiKey: "API-ключ",
@@ -3155,15 +3160,35 @@ export const ru: TranslationResources = {
tools: {
instructionsTitle: "Инструкции",
toolsTitle: "Инструменты агентов",
pluginNote: "Инструменты плагинов также зависят от переключателя «Включить инструменты»",
updateHostForGroups: "Обновите этот хост, чтобы настраивать отдельные группы инструментов",
groups: {
orchestration: {
title: "Оркестрация",
hint: "Управление рабочими пространствами, агентами, терминалами и скриптами",
},
schedules: {
title: "Расписания",
hint: "Создание и управление расписаниями и heartbeat",
},
changeRequests: {
title: "Отслеживание PR",
hint: "Отслеживание обновлений pull request и merge request",
},
browser: {
title: "Браузер",
hint: "Управление вкладками браузера Paseo, включая авторизованные сессии. Включайте только для доверенных агентов.",
},
},
},
orchestration: {
title: "Оркестрация",
unavailable: "Подключитесь к этому хосту, чтобы управлять оркестрацией.",
enableTools: {
title: "Включить инструменты Paseo",
hint: "Агенты смогут управлять worktree, агентами и расписаниями.",
accessibilityLabel: "Добавить инструменты Paseo",
updateFailed: "Не удалось обновить инструменты Paseo.",
title: "Включить инструменты",
hint: "Позволяет Paseo и плагинам предоставлять агентам инструменты. Требуется для голосового режима.",
accessibilityLabel: "Включить инструменты",
updateFailed: "Не удалось обновить инструменты.",
},
systemPrompt: {
title: "Системный промпт",
+28 -4
View File
@@ -1871,6 +1871,7 @@ export const zhCN: TranslationResources = {
searchPlaceholder: "搜索模型...",
openProviderSettings: "打开 {{provider}} 设置",
searchModelsAndProfilesPlaceholder: "搜索模型和配置文件...",
shownOfTotal: "显示 {{shown}} / {{total}}",
olderModels: "旧模型 ({{count}})",
allModels: "所有模型 ({{count}})",
olderTag: "旧版",
@@ -2581,6 +2582,9 @@ export const zhCN: TranslationResources = {
info: "语音模式会转写你说的话,并朗读智能体的回复。",
enabled: "语音模式",
enabledHint: "免手动与智能体对话",
toolsRequiredTitle: "语音模式需要启用代理工具",
toolsRequiredDescription: "开启“启用工具”后,智能体才能播报语音回复。",
enablingTools: "正在启用...",
},
openai: {
apiKey: "API 密钥",
@@ -3066,15 +3070,35 @@ export const zhCN: TranslationResources = {
tools: {
instructionsTitle: "指令",
toolsTitle: "代理工具",
pluginNote: "插件提供的工具同样受“启用工具”开关控制",
updateHostForGroups: "更新此 Host 以单独配置各个工具组",
groups: {
orchestration: {
title: "编排",
hint: "管理工作区、智能体、终端和脚本",
},
schedules: {
title: "计划任务",
hint: "创建和管理计划任务与心跳",
},
changeRequests: {
title: "PR 监控",
hint: "监控 Pull Request 和 Merge Request 的更新",
},
browser: {
title: "浏览器",
hint: "控制 Paseo 浏览器标签页,包括已登录状态。仅对受信任的智能体启用。",
},
},
},
orchestration: {
title: "编排",
unavailable: "连接到这个 Host 以管理编排",
enableTools: {
title: "启用 Paseo tools",
hint: "Agent 将能够管理 worktree、Agent 和计划",
accessibilityLabel: "注入 Paseo tools",
updateFailed: "无法更新 Paseo 工具。",
title: "启用工具",
hint: "允许 Paseo 和插件为智能体提供工具。语音模式需要开启此项。",
accessibilityLabel: "启用工具",
updateFailed: "无法更新工具设置。",
},
systemPrompt: {
title: "System prompt",
-1
View File
@@ -2,4 +2,3 @@ export { KeyboardShiftProvider, useKeyboardShiftStyle } from "./internal/provide
export { useKeyboardShift } from "./internal/context";
export { KeyboardTranslateView } from "./internal/translate";
export { useKeyboardAnchor } from "./internal/anchor";
export { useSettledKeyboardHeight } from "./internal/settled-height";
@@ -11,8 +11,8 @@ export function measureInWindow(element: View): Promise<WindowRect> {
/**
* The element's window rect with `frame`'s own transform left out. Whether
* `measureInWindow` includes a transform depends on the driver: Reanimated commits
* it to the shadow tree every frame, the iOS translate view commits it only once the
* keyboard settles. Fabric's `measureLayout` and a view's `measure` origin ignore
* it to the shadow tree, RN's native driver commits it only when the view happens
* to re-render. Fabric's `measureLayout` and a view's `measure` origin ignore
* transforms. The frame's parent must not move with the keyboard; the composer dock
* is the only anchor host, and its parent is the stationary dock viewport.
*/
@@ -1,27 +0,0 @@
import { useEffect, useState } from "react";
import { KeyboardController, KeyboardEvents } from "react-native-keyboard-controller";
/**
* The software keyboard's height once it has finished moving, or 0 while it is hidden.
*
* Views that ride the keyboard, like the composer, reach their final place only when the keyboard
* settles. Measure against them after this value changes, not when the keyboard starts to move.
*/
export function useSettledKeyboardHeight(): number {
const [height, setHeight] = useState(readSettledHeight);
useEffect(() => {
const subscriptions = [
KeyboardEvents.addListener("keyboardDidShow", (event) => setHeight(event.height)),
KeyboardEvents.addListener("keyboardDidHide", () => setHeight(0)),
];
setHeight(readSettledHeight());
return () => {
for (const subscription of subscriptions) subscription.remove();
};
}, []);
return height;
}
function readSettledHeight(): number {
return KeyboardController.isVisible() ? KeyboardController.state().height : 0;
}
@@ -1,12 +1,9 @@
import { useCallback, useMemo, useEffect, useRef, type ReactNode } from "react";
import { useMemo, useEffect, useRef, type ReactNode } from "react";
import { Animated, useAnimatedValue, type View, type ViewProps } from "react-native";
import { useKeyboardAnimation } from "react-native-keyboard-controller";
import { useAnimatedReaction } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { scheduleOnRN } from "react-native-worklets";
import { KeyboardTranslationContext, useKeyboardShift } from "./context";
import { KeyboardTranslationContext } from "./context";
import { useKeyboardTranslationScope } from "./measure";
import { resolveKeyboardLift } from "./policy";
interface KeyboardTranslateViewProps extends ViewProps {
children: ReactNode;
@@ -76,25 +73,6 @@ export function KeyboardTranslateView({
);
const scope = useKeyboardTranslationScope(frameRef, translation);
// The native driver moves the view without telling the shadow tree, and Pressability
// measures its press region there. With a stale region, a touch that drifts a few
// points leaves it and the press is dropped. Commit the lift once the keyboard settles.
const { layoutShift, isMoving } = useKeyboardShift();
const commitRestingLift = useCallback(
(shift: number) => {
const lift = resolveKeyboardLift({ shift, ...translation });
frameRef.current?.setNativeProps({ transform: [{ translateY: -lift }] });
},
[translation],
);
useAnimatedReaction(
() => (isMoving.value ? null : layoutShift.value),
(restingShift) => {
if (restingShift !== null) scheduleOnRN(commitRestingLift, restingShift);
},
[commitRestingLift],
);
return (
<Animated.View ref={frameRef} style={[style, keyboardStyle]} {...props}>
<KeyboardTranslationContext.Provider value={scope}>
@@ -9,6 +9,11 @@ import {
import { useToast } from "@/contexts/toast-context";
import { useCliInstall } from "@/desktop/hooks/use-install-status";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useHostFeature } from "@/runtime/host-features";
import {
createOnboardingAgentToolsPatch,
isHostAgentToolsEnabled,
} from "@/screens/settings/agent-tools-config";
export type OrchestrationChoice = "tools" | "skills" | "cli";
type Choices = Record<OrchestrationChoice, boolean>;
@@ -39,6 +44,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
const toast = useToast();
const skills = useAgentSkills(serverId);
const cli = useCliInstall();
const supportsToolsConfig = useHostFeature(serverId, "daemonToolsConfig");
const { config, patchConfig } = useDaemonConfig(serverId);
const [chosen, setChosen] = useState<Choices>(ALL_ON);
// With nothing picked there is nothing to install, so skills read as off, as they do in Settings.
@@ -60,7 +66,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
// What the host and this computer have now, or null while it is still being read. A choice is
// skipped only when it is known to match; an unknown state is always written.
const toolsOn = config ? config.mcp.injectIntoAgents !== false : null;
const toolsEnabled = config ? isHostAgentToolsEnabled(config) : null;
const skillsInstalled = skills.status ? areSkillsInstalled(skills.status) : null;
const cliInstalled = cli.status ? cli.status.installed : null;
const { reconcile, uninstall } = skills;
@@ -68,16 +74,21 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
const offersSkills = offered.skills;
const offersCli = offered.cli;
const setTools = useCallback(
(on: boolean) =>
patchConfig({ mcp: { injectIntoAgents: on } })
.then(Boolean, () => false)
.then((done) => {
if (!done) toast.error(t("settings.host.orchestration.enableTools.updateFailed"));
return done;
}),
[patchConfig, t, toast],
);
const applyTools = useCallback(() => {
const patch = createOnboardingAgentToolsPatch({
enabled: choices.tools,
currentEnabled: toolsEnabled,
supportsToolsConfig,
});
if (!patch) return Promise.resolve(true);
return patchConfig(patch)
.then(Boolean, () => false)
.then((done) => {
if (!done) toast.error(t("settings.host.orchestration.enableTools.updateFailed"));
return done;
});
}, [choices.tools, toolsEnabled, patchConfig, supportsToolsConfig, t, toast]);
const setSkillsInstalled = useCallback(
(on: boolean) => (on ? reconcile() : uninstall()),
[reconcile, uninstall],
@@ -87,7 +98,7 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
setIsApplying(true);
try {
const results = await Promise.all([
choices.tools === toolsOn ? true : setTools(choices.tools),
applyTools(),
!offersSkills || choices.skills === skillsInstalled
? true
: setSkillsInstalled(choices.skills),
@@ -98,16 +109,23 @@ export function useOrchestrationSetup(serverId: string): OrchestrationSetupContr
setIsApplying(false);
}
}, [
choices,
toolsOn,
setTools,
offersSkills,
applyTools,
choices.cli,
choices.skills,
skillsInstalled,
setSkillsInstalled,
offersSkills,
offersCli,
cliInstalled,
setCliInstalled,
]);
return { choices, setChoice, offered, skills, isApplying, apply };
return {
choices,
setChoice,
offered,
skills,
isApplying,
apply,
};
}
@@ -2,7 +2,7 @@ import { useCallback } from "react";
import { AgentSkillsRow } from "@/agent-skills";
import { SettingsCard } from "@/components/settings";
import { CommandLineRow } from "@/desktop/components/integrations-section";
import { PaseoToolsRow } from "@/screens/settings/paseo-tools-card";
import { EnableToolsSwitchRow } from "@/screens/settings/agent-tools-row";
import type { OrchestrationSetupController } from "../orchestration-setup";
/** Three switches, all on to start; Continue applies them. */
@@ -13,7 +13,7 @@ export function OrchestrationStep({ setup }: { setup: OrchestrationSetupControll
const setCli = useCallback((on: boolean) => setChoice("cli", on), [setChoice]);
return (
<SettingsCard>
<PaseoToolsRow value={choices.tools} onValueChange={setTools} disabled={isApplying} />
<EnableToolsSwitchRow value={choices.tools} onValueChange={setTools} disabled={isApplying} />
{offered.skills ? (
<AgentSkillsRow
skills={setup.skills}
+1 -2
View File
@@ -16,7 +16,6 @@ import { useChangesPreferences } from "@/hooks/use-changes-preferences";
import { useAppSettings } from "@/hooks/use-settings";
import { usePaneContext } from "@/panels/pane-context";
import { definePanel, type PanelDescriptor, type PanelPresentation } from "@/panels/panel-registry";
import { commitDiffTabLabel } from "@/panels/tab-labels";
import { useAddFileToChat } from "@/panels/use-add-file-to-chat";
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
@@ -229,7 +228,7 @@ function useCommitDiffPanelDescriptor(
): PanelDescriptor {
const { t } = useTranslation();
return {
label: commitDiffTabLabel(target.sha),
label: target.sha.slice(0, 7),
subtitle: t("panels.diff.commitSubtitle"),
tooltip: target.sha,
titleState: "ready",
@@ -1,7 +1,6 @@
import type { ComponentType } from "react";
import { i18n } from "@/i18n/i18next";
import type { PanelDescriptor, PanelIconProps } from "@/panels/panel-registry";
import { draftTabLabel } from "@/panels/tab-labels";
export function buildDraftPanelDescriptor(input: {
isCreating: boolean;
@@ -10,7 +9,7 @@ export function buildDraftPanelDescriptor(input: {
}): PanelDescriptor {
const { icon, isCreating, pendingPrompt } = input;
const newAgentLabel = i18n.t("panels.draft.newAgent");
const creatingLabel = draftTabLabel({ isCreating, pendingPrompt, newAgentLabel });
const creatingLabel = pendingPrompt?.trim() || newAgentLabel;
if (isCreating) {
return {
label: creatingLabel,
+1 -2
View File
@@ -5,7 +5,6 @@ import { useTranslation } from "react-i18next";
import { FilePane } from "@/file-pane/pane";
import { usePaneContext } from "@/panels/pane-context";
import { definePanel } from "@/panels/panel-registry";
import { fileTabLabel } from "@/panels/tab-labels";
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
import { createMaterialFileIcon } from "@/components/material-file-icon";
@@ -17,7 +16,7 @@ const CENTERED_PADDED_STYLE = {
} as const;
function useFilePanelDescriptor(target: { kind: "file"; path: string }) {
const fileName = fileTabLabel(target.path);
const fileName = target.path.split("/").findLast(Boolean) ?? target.path;
const icon = useMemo(() => createMaterialFileIcon(fileName), [fileName]);
return {
label: fileName,
@@ -60,21 +60,16 @@ export function setPanelInstanceAttributes(
for (const listener of allListeners) listener();
}
/** Calls back when any panel's attributes change. */
export function subscribeAllPanelInstanceAttributes(listener: () => void): () => void {
allListeners.add(listener);
return () => {
allListeners.delete(listener);
};
}
export function useModifiedPanelTabIds(input: {
serverId: string;
workspaceId: string;
tabIds: string[];
}): Set<string> {
const revision = useSyncExternalStore(
subscribeAllPanelInstanceAttributes,
useCallback((listener: () => void) => {
allListeners.add(listener);
return () => allListeners.delete(listener);
}, []),
() => attributesRevision,
() => attributesRevision,
);
-173
View File
@@ -1,7 +1,3 @@
import type { PluginPanelTargetParams } from "@getpaseo/plugin/client";
import { z } from "zod";
import { isAbsolutePath } from "@/utils/path";
import { normalizeWorkspaceTabTarget } from "@/workspace-tabs/identity";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
/** Where a tab renders: a split pane, the Explorer dock, or the compact workspace sheet. */
@@ -26,26 +22,6 @@ type CompactSheetRule<K extends WorkspaceTabTarget["kind"]> =
facts: PanelTargetFacts,
) => CompactSheetPolicy | null);
/** What opening a panel by its public identity asks the workspace to do. */
export interface PanelOpenRequest {
target: WorkspaceTabTarget;
/** A workspace-relative path the panel expands to and selects once it shows. */
revealPath?: string;
}
/**
* How plugins name a kind and spell one instance of it. Ids and param names are a published
* contract: add optional params, never rename, narrow or require one.
*/
export interface PanelPublicIdentity<
K extends WorkspaceTabTarget["kind"] = WorkspaceTabTarget["kind"],
> {
publicId: `paseo/${string}`;
toParams(target: Extract<WorkspaceTabTarget, { kind: K }>): PluginPanelTargetParams;
/** Null for params this panel does not accept. */
fromParams(params: PluginPanelTargetParams): PanelOpenRequest | null;
}
export interface PanelManifest<K extends WorkspaceTabTarget["kind"] = WorkspaceTabTarget["kind"]> {
kind: K;
/** The sheet is never listed: a kind renders there exactly when it has a `compactSheet` rule. */
@@ -58,219 +34,101 @@ export interface PanelManifest<K extends WorkspaceTabTarget["kind"] = WorkspaceT
*/
compactSheet: CompactSheetRule<K>;
resourceKey(target: Extract<WorkspaceTabTarget, { kind: K }>): string;
/** One instance, such as an agent's chat or a terminal, never has a second tab. */
oneTabPerInstance: boolean;
/** Null for a kind plugins cannot open. */
public: PanelPublicIdentity<K> | null;
}
type PanelManifestByKind = {
[K in WorkspaceTabTarget["kind"]]: PanelManifest<K>;
};
function publicPanel<K extends WorkspaceTabTarget["kind"], Params>(input: {
publicId: `paseo/${string}`;
params: z.ZodType<Params>;
toRequest(params: Params): PanelOpenRequest;
toParams(target: Extract<WorkspaceTabTarget, { kind: K }>): PluginPanelTargetParams;
}): PanelPublicIdentity<K> {
return {
publicId: input.publicId,
toParams: input.toParams,
fromParams(params) {
const parsed = input.params.safeParse(params);
if (!parsed.success) return null;
const request = input.toRequest(parsed.data);
const target = normalizeWorkspaceTabTarget(request.target);
return target ? { ...request, target } : null;
},
};
}
const noParams = z.strictObject({});
const lineNumber = z.number().int().positive();
const fileParams = z
.strictObject({
path: z.string(),
lineStart: lineNumber.optional(),
lineEnd: lineNumber.optional(),
})
.refine(
({ lineStart, lineEnd }) =>
lineEnd === undefined || (lineStart !== undefined && lineEnd >= lineStart),
);
const filesParams = z.strictObject({
reveal: z
.string()
.transform((path) => path.trim().replace(/\\/g, "/"))
.refine((path) => path.length > 0 && !isAbsolutePath(path) && !path.split("/").includes(".."))
.optional(),
});
const manifests = {
new_tab: {
kind: "new_tab",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: () => "new_tab",
public: null,
},
draft: {
kind: "draft",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) => target.draftId,
public: null,
},
agent: {
kind: "agent",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: true,
compactSheet: (target, facts) =>
facts.isWorkspaceRootAgent(target.agentId) ? null : { openAsTab: true },
resourceKey: (target) => target.agentId,
public: publicPanel<"agent", { agentId: string }>({
publicId: "paseo/agent",
params: z.strictObject({ agentId: z.string() }),
toRequest: ({ agentId }) => ({ target: { kind: "agent", agentId } }),
toParams: ({ agentId }) => ({ agentId }),
}),
},
provider_subagent: {
kind: "provider_subagent",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: { openAsTab: false },
resourceKey: (target) => `${target.parentAgentId}:${target.subagentId}`,
public: publicPanel<"provider_subagent", { parentAgentId: string; subagentId: string }>({
publicId: "paseo/subagent",
params: z.strictObject({ parentAgentId: z.string(), subagentId: z.string() }),
toRequest: (params) => ({ target: { kind: "provider_subagent", ...params } }),
toParams: ({ parentAgentId, subagentId }) => ({ parentAgentId, subagentId }),
}),
},
terminal: {
kind: "terminal",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: true,
compactSheet: null,
resourceKey: (target) => target.terminalId,
public: publicPanel<"terminal", { terminalId: string }>({
publicId: "paseo/terminal",
params: z.strictObject({ terminalId: z.string() }),
toRequest: ({ terminalId }) => ({ target: { kind: "terminal", terminalId } }),
toParams: ({ terminalId }) => ({ terminalId }),
}),
},
browser: {
kind: "browser",
supportedHosts: ["main"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: true,
compactSheet: null,
resourceKey: (target) => target.browserId,
public: publicPanel<"browser", { browserId: string }>({
publicId: "paseo/browser",
params: z.strictObject({ browserId: z.string() }),
toRequest: ({ browserId }) => ({ target: { kind: "browser", browserId } }),
toParams: ({ browserId }) => ({ browserId }),
}),
},
changes_tree: {
kind: "changes_tree",
supportedHosts: ["explorer"],
showCloseButton: false,
singleton: true,
oneTabPerInstance: true,
compactSheet: null,
resourceKey: () => "changes_tree",
public: publicPanel<"changes_tree", Record<string, never>>({
publicId: "paseo/changes",
params: noParams,
toRequest: () => ({ target: { kind: "changes_tree" } }),
toParams: () => ({}),
}),
},
files: {
kind: "files",
supportedHosts: ["explorer"],
showCloseButton: false,
singleton: true,
oneTabPerInstance: true,
compactSheet: null,
resourceKey: () => "files",
public: publicPanel<"files", { reveal?: string }>({
publicId: "paseo/files",
params: filesParams,
toRequest: ({ reveal }) => ({ target: { kind: "files" }, revealPath: reveal }),
// A reveal is something to do once, not part of which tab this is.
toParams: () => ({}),
}),
},
pull_request: {
kind: "pull_request",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: () => "pull_request",
public: publicPanel<"pull_request", Record<string, never>>({
publicId: "paseo/pull-request",
params: noParams,
toRequest: () => ({ target: { kind: "pull_request" } }),
toParams: () => ({}),
}),
},
file: {
kind: "file",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: { openAsTab: false },
resourceKey: (target) => target.path,
public: publicPanel<"file", z.infer<typeof fileParams>>({
publicId: "paseo/file",
params: fileParams,
toRequest: (params) => ({ target: { kind: "file", ...params } }),
toParams: ({ path, lineStart, lineEnd }) => ({
path,
...(lineStart ? { lineStart } : {}),
...(lineEnd ? { lineEnd } : {}),
}),
}),
},
working_diff: {
kind: "working_diff",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: () => "working_diff",
public: publicPanel<"working_diff", Record<string, never>>({
publicId: "paseo/diff",
params: noParams,
toRequest: () => ({ target: { kind: "working_diff" } }),
toParams: () => ({}),
}),
},
plugin: {
kind: "plugin",
@@ -278,39 +136,27 @@ const manifests = {
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) =>
target.context === "agent"
? `${target.pluginId}:${target.panelId}:agent:${target.agentId}`
: `${target.pluginId}:${target.panelId}:workspace`,
// Plugin panels are named by their registration, not by this kind.
public: null,
},
setup: {
kind: "setup",
supportedHosts: ["main"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) => target.workspaceId,
public: null,
},
commit_diff: {
kind: "commit_diff",
supportedHosts: ["main", "explorer"],
showCloseButton: true,
singleton: false,
oneTabPerInstance: false,
compactSheet: null,
resourceKey: (target) => target.sha,
public: publicPanel<"commit_diff", { sha: string }>({
publicId: "paseo/commit-diff",
params: z.strictObject({ sha: z.string() }),
toRequest: ({ sha }) => ({ target: { kind: "commit_diff", sha } }),
toParams: ({ sha }) => ({ sha }),
}),
},
} satisfies PanelManifestByKind;
@@ -343,22 +189,3 @@ export function panelResourceKey(target: WorkspaceTabTarget): string {
const manifest = getPanelManifest(target.kind);
return `${target.kind}:${manifest.resourceKey(target as never)}`;
}
/** How plugins read a built-in tab back. A kind they cannot open reads as its kind name. */
export function panelPublicReference(target: Exclude<WorkspaceTabTarget, { kind: "plugin" }>): {
panelId: string;
params: PluginPanelTargetParams;
} {
const identity = getPanelManifest(target.kind).public;
if (!identity) return { panelId: `paseo/${target.kind}`, params: {} };
return { panelId: identity.publicId, params: identity.toParams(target as never) };
}
export function findPublicPanel(publicId: string): PanelPublicIdentity | null {
for (const manifest of Object.values(manifests)) {
if (manifest.public?.publicId === publicId) {
return manifest.public as unknown as PanelPublicIdentity;
}
}
return null;
}
@@ -15,7 +15,6 @@ import type { AgentScreenAgent } from "@/hooks/use-agent-screen-state-machine";
import { usePaneContext } from "@/panels/pane-context";
import { PaneSubtitle } from "@/panels/pane-subtitle";
import { definePanel, type PanelDescriptor } from "@/panels/panel-registry";
import { providerSubagentTabLabel } from "@/panels/tab-labels";
import { useSessionStore } from "@/stores/session-store";
import type { SheetTab } from "@/stores/workspace-layout-store";
import { ParentAgentCallout } from "@/subagents/parent";
@@ -97,8 +96,9 @@ function useProviderSubagentDescriptor(
(state) => state.sessions[context.serverId]?.agents.get(target.parentAgentId)?.provider,
);
const provider = descriptor?.provider ?? parentProvider ?? "agent";
// The task names the tab; the subagent type is supporting detail beside the provider.
const subagentType = descriptor?.title?.trim();
const label = providerSubagentTabLabel(descriptor);
const label = descriptor?.description?.trim() || subagentType || "Subagent";
const providerLabel = `${formatProviderLabel(provider)} subagent`;
return {
label,
-60
View File
@@ -1,60 +0,0 @@
/** Naming rules shared by a tab's React descriptor and the title read outside React. */
/** Null until the agent has a name of its own. */
export function resolveAgentLabel(title: string | null | undefined): string | null {
if (typeof title !== "string") {
return null;
}
const normalized = title.trim();
if (!normalized) {
return null;
}
if (normalized.toLowerCase() === "new agent") {
return null;
}
return normalized;
}
export function terminalTabLabel(
terminal: { title?: string | null; name?: string | null } | null | undefined,
fallback: string,
): string {
return (terminal?.title ?? terminal?.name)?.trim() || fallback;
}
export function browserTabLabel(input: { title: string; url: string }): string {
const title = input.title.trim();
if (title) {
return title;
}
try {
const parsed = new URL(input.url);
return parsed.hostname || input.url;
} catch {
return input.url;
}
}
// The task names the tab; the subagent type is supporting detail.
export function providerSubagentTabLabel(
descriptor: { description?: string | null; title?: string | null } | null | undefined,
): string {
return descriptor?.description?.trim() || descriptor?.title?.trim() || "Subagent";
}
export function draftTabLabel(input: {
isCreating: boolean;
pendingPrompt?: string | null;
newAgentLabel: string;
}): string {
return (input.isCreating && input.pendingPrompt?.trim()) || input.newAgentLabel;
}
export function fileTabLabel(path: string): string {
return path.split("/").findLast(Boolean) ?? path;
}
export function commitDiffTabLabel(sha: string): string {
return sha.slice(0, 7);
}
-141
View File
@@ -1,141 +0,0 @@
import type { ListTerminalsResponse } from "@getpaseo/protocol/messages";
import { queryClient } from "@/data/query-client";
import { useBrowserStore } from "@/desktop/browser/store";
import type { CheckoutPrStatusPayload } from "@/git/pr-status";
import { formatPrTabLabel } from "@/git/pull-request-panel/tab-label";
import { checkoutPrStatusQueryKey } from "@/git/query-keys";
import { i18n } from "@/i18n/i18next";
import {
browserTabLabel,
commitDiffTabLabel,
draftTabLabel,
fileTabLabel,
providerSubagentTabLabel,
resolveAgentLabel,
terminalTabLabel,
} from "@/panels/tab-labels";
import { pluginRegistry } from "@/plugins/registry";
import { resolvePluginWorkspacePanel } from "@/plugins/workspace-panels/resolution";
import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state";
import { useCreateFlowStore } from "@/stores/create-flow-store";
import { useSessionStore } from "@/stores/session-store";
import { selectWorkspaceDirectory } from "@/stores/session-store-hooks/selectors";
import { providerSubagentKey, useProviderSubagentStore } from "@/subagents/provider-store";
import type { PluginWorkspaceTabTarget, WorkspaceTabTarget } from "@/workspace-tabs/model";
interface TabTitleInput {
serverId: string;
workspaceId: string;
target: WorkspaceTabTarget;
}
/**
* What a tab is called, from what the client already holds. Reads only: a terminal or pull
* request nobody has loaded yet keeps its generic name.
*/
export function readTabTitle({ serverId, workspaceId, target }: TabTitleInput): string {
switch (target.kind) {
case "new_tab":
return i18n.t("workspace.tabs.actions.newTab");
case "draft":
return readDraftTitle(serverId, target.draftId);
case "agent":
return readAgentTitle(serverId, target.agentId);
case "provider_subagent":
return providerSubagentTabLabel(
useProviderSubagentStore
.getState()
.descriptors.get(providerSubagentKey(serverId, target.parentAgentId, target.subagentId)),
);
case "terminal":
return readTerminalTitle(serverId, workspaceId, target.terminalId);
case "browser": {
const browser = useBrowserStore.getState().browsersById[target.browserId];
return browserTabLabel({
title: browser?.title ?? "",
url: browser?.url ?? "https://example.com",
});
}
case "changes_tree":
return i18n.t("panels.diff.changesLabel");
case "files":
return i18n.t("panels.files.label");
case "pull_request":
return readPullRequestTitle(serverId, workspaceId);
case "file":
return fileTabLabel(target.path);
case "working_diff":
return i18n.t("panels.diff.diffLabel");
case "plugin":
return readPluginPanelTitle(serverId, target);
case "setup":
return i18n.t("workspace.setup.descriptor.label");
case "commit_diff":
return commitDiffTabLabel(target.sha);
}
}
/** Calls back whenever a title may read differently. */
export function subscribeTabTitles(listener: () => void): () => void {
i18n.on("languageChanged", listener);
const releases = [
useSessionStore.subscribe(listener),
useCreateFlowStore.subscribe(listener),
useProviderSubagentStore.subscribe(listener),
useBrowserStore.subscribe(listener),
queryClient.getQueryCache().subscribe(listener),
pluginRegistry.subscribe(listener),
() => {
i18n.off("languageChanged", listener);
},
];
return () => {
for (const release of releases) release();
};
}
function readDraftTitle(serverId: string, draftId: string): string {
const pending = useCreateFlowStore.getState().pendingByDraftId[draftId];
return draftTabLabel({
isCreating: pending?.serverId === serverId && pending.lifecycle === "active",
pendingPrompt: pending?.text,
newAgentLabel: i18n.t("panels.draft.newAgent"),
});
}
function readAgentTitle(serverId: string, agentId: string): string {
const session = useSessionStore.getState().sessions[serverId];
const agent = session?.agents.get(agentId) ?? session?.agentDetails.get(agentId);
return resolveAgentLabel(agent?.title) ?? "";
}
function readTerminalTitle(serverId: string, workspaceId: string, terminalId: string): string {
const directory = selectWorkspaceDirectory(useSessionStore.getState(), serverId, workspaceId);
const list = queryClient.getQueryData<ListTerminalsResponse["payload"]>(
buildTerminalsQueryKey(serverId, directory, workspaceId),
);
return terminalTabLabel(
list?.terminals.find((terminal) => terminal.id === terminalId),
i18n.t("workspace.tabs.fallback.terminal"),
);
}
function readPullRequestTitle(serverId: string, workspaceId: string): string {
const directory = selectWorkspaceDirectory(useSessionStore.getState(), serverId, workspaceId);
const payload = queryClient.getQueryData<CheckoutPrStatusPayload>(
checkoutPrStatusQueryKey(serverId, directory ?? ""),
);
const prNumber = payload?.status?.number ?? null;
return prNumber === null ? i18n.t("panels.pullRequest.label") : formatPrTabLabel(prNumber);
}
function readPluginPanelTitle(serverId: string, target: PluginWorkspaceTabTarget): string {
const plugin =
pluginRegistry
.getSnapshot()
.find((candidate) => candidate.serverId === serverId && candidate.id === target.pluginId) ??
null;
const panel = resolvePluginWorkspacePanel(plugin, target);
if (!plugin || !panel) return "Plugin unavailable";
return plugin.i18n.resolve(panel.title, plugin.locale);
}
+11 -2
View File
@@ -10,7 +10,6 @@ import { TerminalPane } from "@/components/terminal-pane";
import { openUrlInWorkspaceBrowser } from "@/desktop/browser/open-url-in-workspace";
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
import { definePanel, type PanelDescriptor } from "@/panels/panel-registry";
import { terminalTabLabel } from "@/panels/tab-labels";
import { queryClient } from "@/data/query-client";
import { buildTerminalsQueryKey } from "@/screens/workspace/terminals/state";
import { showExplorerSidebar } from "@/workspace-tabs/explorer-sidebar";
@@ -28,6 +27,14 @@ const CENTERED_PADDED_STYLE = {
padding: 16,
} as const;
function trimNonEmpty(value: string | null | undefined): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function useTerminalPanelDescriptor(
target: { kind: "terminal"; terminalId: string },
context: { serverId: string; workspaceId: string },
@@ -57,7 +64,9 @@ function useTerminalPanelDescriptor(
);
const terminal =
terminalsQuery.data?.terminals.find((entry) => entry.id === target.terminalId) ?? null;
const label = terminalTabLabel(terminal, t("workspace.tabs.fallback.terminal"));
const label =
trimNonEmpty(terminal?.title ?? terminal?.name ?? null) ??
t("workspace.tabs.fallback.terminal");
return {
label,
-3
View File
@@ -12,7 +12,6 @@ import type { PluginClientStateSource } from "@getpaseo/plugin/client/host";
import { resolvePluginPanelOpenLocation } from "./workspace-panels/locations";
import { parsePluginOpenScreenInput } from "./surface-contribution";
import type { InstalledPlugin } from "./types";
import { pluginWorkspaceLayoutSource } from "./workspace-layout";
export interface PluginNavigation {
openSettings(pluginId: string, screenId: string): void;
@@ -65,7 +64,6 @@ export function createPluginAgentActionContext(input: {
...createPluginCapabilities(plugin, navigation),
workspace,
agent,
workspaceLayout: pluginWorkspaceLayoutSource(plugin).layout(workspace.id),
openPanel(panelId, options) {
const panel = plugin.workspacePanels.find((candidate) => candidate.id === panelId);
if (!panel) throw new Error(`Workspace panel is unavailable: ${panelId}`);
@@ -92,7 +90,6 @@ export function createPluginWorkspaceActionContext(input: {
context: "workspace",
...createPluginCapabilities(plugin, navigation),
workspace,
workspaceLayout: pluginWorkspaceLayoutSource(plugin).layout(workspace.id),
openPanel(panelId, options) {
const panel = plugin.workspacePanels.find(
(candidate) => candidate.id === panelId && candidate.context === "workspace",
@@ -153,9 +153,6 @@ function harness() {
openSurface() {},
composers: () => [],
async playAudio() {},
workspaceLayout: () => {
throw new Error("Layouts are not used here");
},
openPanel() {},
addComposerPill: () => ({ update() {}, remove() {} }),
addHeaderButton: () => ({ update() {}, remove() {} }),

Some files were not shown because too many files have changed in this diff Show More