mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-29 11:46:12 +00:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97628dfd13 | ||
|
|
25441b1845 | ||
|
|
e1bb1f8ff1 | ||
|
|
20354c13b9 | ||
|
|
f3e59c1c86 | ||
|
|
ce5b60a9e6 | ||
|
|
59a5724460 | ||
|
|
e713f5acf7 | ||
|
|
a271074716 | ||
|
|
c026b27639 | ||
|
|
526aa3133e |
@@ -60,6 +60,7 @@ sdk:
|
||||
- "packages/client/**"
|
||||
- "packages/highlight/**"
|
||||
- "packages/protocol/**"
|
||||
- "packages/workflows/**"
|
||||
|
||||
browser:
|
||||
- "packages/server/src/server/agent/provider-snapshot-manager.ts"
|
||||
|
||||
@@ -128,6 +128,14 @@ 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
|
||||
|
||||
@@ -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)`.
|
||||
- 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.
|
||||
- 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. Keep the shared producer schema strict
|
||||
// 3. Add the value to the shared schema; no catch-all branch
|
||||
// 4. Gate the new emitted value: session.supports(CLIENT_CAPS.newThing) ? "new_value" : "old_value"
|
||||
```
|
||||
|
||||
|
||||
@@ -639,6 +639,12 @@ 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`.
|
||||
|
||||
@@ -17,6 +17,9 @@ 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:
|
||||
|
||||
@@ -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, repair, or re-validate the generated result.
|
||||
`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.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -73,6 +73,17 @@
|
||||
"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
@@ -1 +1 @@
|
||||
sha256-aal9eR571blWuL7CZt1LR+KfA4QPJ0ivVl/GSTWy93o=
|
||||
sha256-34bUBmRmjekbUSp93597GLTmSWKt23TCHaK3ViXG+iU=
|
||||
|
||||
Generated
+20
-3
@@ -16,6 +16,7 @@
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
"packages/workflows",
|
||||
"packages/client",
|
||||
"packages/server",
|
||||
"packages/app",
|
||||
@@ -6709,6 +6710,10 @@
|
||||
"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",
|
||||
@@ -14924,7 +14929,6 @@
|
||||
"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",
|
||||
@@ -31398,7 +31402,6 @@
|
||||
"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"
|
||||
@@ -36228,7 +36231,6 @@
|
||||
"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"
|
||||
@@ -43159,6 +43161,21 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"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",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
"packages/workflows",
|
||||
"packages/client",
|
||||
"packages/server",
|
||||
"packages/app",
|
||||
@@ -60,6 +61,8 @@
|
||||
"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,13 +85,10 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
await expectComposerMode(page, "Load test");
|
||||
});
|
||||
|
||||
await test.step("the picker opens on the agent's provider with Profiles beside it", async () => {
|
||||
await test.step("the single-provider picker lists Profiles above the agent's models without a rail", async () => {
|
||||
await openModelPicker(page);
|
||||
await expect(page.getByTestId("model-search-input").first()).toBeFocused();
|
||||
await expect(page.getByTestId("model-provider-mock")).toHaveAttribute(
|
||||
"data-active",
|
||||
"true",
|
||||
);
|
||||
await expect(page.getByTestId("model-picker-rail")).toHaveCount(0);
|
||||
await expectModelRowSelected(page, { provider: "mock", modelId: "ten-second-stream" });
|
||||
await expectPickerProfile(page, {
|
||||
name: PROFILE.name,
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
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);
|
||||
});
|
||||
@@ -28,6 +28,7 @@ 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";
|
||||
@@ -315,15 +316,50 @@ test.describe("Cross-provider model search", () => {
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("the compact drawer puts Profiles in the Model accordion and lets all groups collapse", async () => {
|
||||
await test.step("the compact drawer surfaces collapsed Profiles above Model on Home and keeps provider headers stable on collapse", 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-profiles")).toHaveCount(0);
|
||||
await page.getByTestId("agent-controls-model").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("compact-model-list")).toBeVisible();
|
||||
await page.locator('[data-testid^="model-provider-section-"]').first().click();
|
||||
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 expect(page.getByTestId("compact-model-list")).toHaveCount(0);
|
||||
await page.getByTestId("model-picker-rail-profiles").click();
|
||||
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();
|
||||
const sheetProfileRow = page.getByTestId("model-profile-row-agent_profile_e2e_arrows");
|
||||
await expect(sheetProfileRow).toBeVisible();
|
||||
await sheetProfileRow.click();
|
||||
@@ -373,8 +409,193 @@ 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: {
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
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();
|
||||
}
|
||||
@@ -603,9 +603,12 @@ export function profilePickerRow(page: Page, name: string): Locator {
|
||||
.filter({ hasText: name });
|
||||
}
|
||||
|
||||
/** Desktop keeps profiles behind the rail's Profiles entry, beside the providers. */
|
||||
/** Multi-provider desktop keeps profiles behind the rail; single-pane lists them inline. */
|
||||
export async function openPickerProfiles(page: Page): Promise<void> {
|
||||
await pickerViewport(page).getByTestId("model-picker-rail-profiles").click();
|
||||
const rail = pickerViewport(page).getByTestId("model-picker-rail-profiles");
|
||||
if (await rail.isVisible().catch(() => false)) {
|
||||
await rail.click();
|
||||
}
|
||||
}
|
||||
|
||||
export async function expectPickerProfile(
|
||||
@@ -624,7 +627,8 @@ export async function expectProfilesEditLink(page: Page): Promise<void> {
|
||||
exact: true,
|
||||
});
|
||||
await expect(edit).toBeVisible();
|
||||
await expect(edit).toHaveText("Edit");
|
||||
await expect(edit).toHaveText("");
|
||||
await expect(edit.locator("svg")).toBeVisible();
|
||||
}
|
||||
|
||||
/** With no profiles, the Profiles entry offers to create one instead of listing any. */
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
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);
|
||||
}
|
||||
@@ -76,15 +76,24 @@ export async function addOfflineHostsAndReload(
|
||||
|
||||
export async function addConnectedHostAndReload(
|
||||
page: Page,
|
||||
input: { serverId: string; label: string; port: number; primaryLabel?: string },
|
||||
input: {
|
||||
serverId: string;
|
||||
label: string;
|
||||
port: number;
|
||||
primaryLabel?: string;
|
||||
destination?: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
await addConnectedHostsAndReload(page, [input], { primaryLabel: input.primaryLabel });
|
||||
await addConnectedHostsAndReload(page, [input], {
|
||||
primaryLabel: input.primaryLabel,
|
||||
destination: input.destination,
|
||||
});
|
||||
}
|
||||
|
||||
export async function addConnectedHostsAndReload(
|
||||
page: Page,
|
||||
inputs: Array<{ serverId: string; label: string; port: number }>,
|
||||
options?: { primaryLabel?: string },
|
||||
options?: { primaryLabel?: string; destination?: string },
|
||||
): Promise<void> {
|
||||
const connectedHosts = inputs.map((input) =>
|
||||
buildSeededHost({
|
||||
@@ -123,7 +132,8 @@ export async function addConnectedHostsAndReload(
|
||||
},
|
||||
);
|
||||
|
||||
await page.reload();
|
||||
if (options?.destination) await page.goto(options.destination);
|
||||
else await page.reload();
|
||||
}
|
||||
|
||||
export async function waitForConnectedHost(
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
encodeAttachmentsForSend,
|
||||
garbageCollectAttachments,
|
||||
persistAttachmentFromBytes,
|
||||
prepareImageAttachmentsForSend,
|
||||
uploadImageAttachments,
|
||||
} from "./service";
|
||||
|
||||
@@ -220,4 +221,71 @@ 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" }],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -152,6 +152,15 @@ 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 });
|
||||
@@ -160,9 +169,8 @@ 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 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.
|
||||
* Each uploaded image is marked with `role: "image"` inside `uploaded_file` so capable daemons
|
||||
* resolve it into a native vision block + timeline thumbnail.
|
||||
*/
|
||||
export async function uploadImageAttachments(input: {
|
||||
client: ImageUploadClient;
|
||||
@@ -196,6 +204,34 @@ 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,6 +14,7 @@ import {
|
||||
import { ModelProviderGlyph, useSelectedModelLabels } from "@/components/model-browser";
|
||||
import { DesktopModelPicker, type ModelPickerActions } from "@/components/model-browser-panes";
|
||||
import {
|
||||
getSheetSearchFooterStyle,
|
||||
MobileModelPageView,
|
||||
SheetSearchDock,
|
||||
useMobileModelPage,
|
||||
@@ -313,6 +314,7 @@ function CompactCombinedModelSelector({
|
||||
snapPoints={SHEET_SNAP_POINTS}
|
||||
scrollable={false}
|
||||
footer={footer}
|
||||
footerContainerStyle={getSheetSearchFooterStyle()}
|
||||
keyboard={keyboard}
|
||||
contentStyle={styles.sheetBody}
|
||||
testID="model-selector-sheet"
|
||||
|
||||
@@ -134,17 +134,15 @@ 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, 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 },
|
||||
{ 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 },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -154,12 +152,26 @@ 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,24 +1,27 @@
|
||||
import {
|
||||
createModelPickerState,
|
||||
MODEL_PICKER_PROFILES_RAIL_KEY,
|
||||
orderProvidersForPicker,
|
||||
projectModelPicker,
|
||||
type ModelPickerInput,
|
||||
type ModelPickerListItem,
|
||||
type ModelPickerPane,
|
||||
type ModelPickerState,
|
||||
} from "@/components/model-browser-panes-view";
|
||||
import type { NavigableProfileRow } from "@/components/model-browser-view";
|
||||
import { partitionProviderModels } from "@/provider-selection/model-curation";
|
||||
import {
|
||||
MODEL_BROWSER_CREATE_PROFILE_KEY,
|
||||
modelBrowserProfileKey,
|
||||
type NavigableProfileRow,
|
||||
} from "@/components/model-browser-view";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*
|
||||
* It delegates to the desktop picker's projection so both form factors order, fold, rank and
|
||||
* search the same way.
|
||||
* It delegates model folding, ordering, and search to the desktop picker's projection so both form
|
||||
* factors behave identically.
|
||||
*/
|
||||
|
||||
export interface MobileModelPageInput<TProfile extends NavigableProfileRow = NavigableProfileRow> {
|
||||
@@ -26,6 +29,8 @@ 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;
|
||||
}
|
||||
@@ -46,7 +51,6 @@ export type MobileModelPageAction =
|
||||
export interface MobileProfilesSection {
|
||||
kind: "profiles";
|
||||
key: typeof MODEL_PICKER_PROFILES_RAIL_KEY;
|
||||
count: number;
|
||||
expanded: boolean;
|
||||
}
|
||||
|
||||
@@ -56,11 +60,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -75,11 +74,11 @@ export type MobileModelPageProjection<TProfile extends NavigableProfileRow = Nav
|
||||
| {
|
||||
kind: "browse";
|
||||
sections: MobileModelSection[];
|
||||
/** False for a lone provider without profiles: its models are the page, with no header above them. */
|
||||
/** False for a lone provider without a Profiles section: its models fill the page. */
|
||||
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 the list scrolls into view. */
|
||||
/** The selected model's row in the open list, which opens already in view. */
|
||||
selectedIndex: number | null;
|
||||
}
|
||||
| {
|
||||
@@ -97,7 +96,7 @@ export function createMobileModelPageState<TProfile extends NavigableProfileRow>
|
||||
): MobileModelPageState {
|
||||
return {
|
||||
query: "",
|
||||
expandedKey: createModelPickerState(toPickerInput(input)).railKey,
|
||||
expandedKey: resolveInitialExpandedKey(input),
|
||||
foldOverrides: {},
|
||||
};
|
||||
}
|
||||
@@ -122,42 +121,47 @@ 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" };
|
||||
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));
|
||||
}
|
||||
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,
|
||||
};
|
||||
}
|
||||
} 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 = showSectionHeaders && state.expandedKey === null ? null : picker.railKey;
|
||||
const expandedKey = resolveExpandedKey(sections, state.expandedKey, showSectionHeaders);
|
||||
for (const section of sections) {
|
||||
section.expanded = section.key === expandedKey;
|
||||
}
|
||||
const body = expandedKey === null ? null : pane;
|
||||
const body = expandedKey === null ? null : buildSectionBody(input, state, expandedKey);
|
||||
return {
|
||||
kind: "browse",
|
||||
sections,
|
||||
@@ -167,6 +171,81 @@ 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>,
|
||||
@@ -200,33 +279,17 @@ function toPickerState(state: MobileModelPageState): ModelPickerState {
|
||||
};
|
||||
}
|
||||
|
||||
function toProviderSection(
|
||||
provider: ProviderSelectorProvider,
|
||||
expanded: boolean,
|
||||
): MobileProviderSection {
|
||||
const base = {
|
||||
kind: "provider" as const,
|
||||
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",
|
||||
key: provider.id,
|
||||
providerId: provider.id,
|
||||
label: provider.label,
|
||||
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,
|
||||
status,
|
||||
expanded: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { useCallback, useMemo, useRef, useState, type ReactElement, 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, ChevronUp, Layers, Pencil } from "lucide-react-native";
|
||||
import { AlertTriangle, ChevronDown, Layers } from "lucide-react-native";
|
||||
import type { AgentProfilePickerRow } from "@/agent-profiles";
|
||||
import {
|
||||
IndependentScrollBoundary,
|
||||
MODEL_PICKER_ROW_HEIGHT,
|
||||
ModelBrowserLoadingState,
|
||||
ModelBrowserNoProviders,
|
||||
ModelBrowserRow,
|
||||
ModelBrowserSectionHeading,
|
||||
ModelProviderGlyph,
|
||||
ModelSearchNoMatches,
|
||||
@@ -16,12 +16,14 @@ 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,
|
||||
@@ -30,41 +32,39 @@ 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 { useRevealActiveFlatListRow } from "@/components/ui/scroll-reveal";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { isNative, isWeb } 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 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.
|
||||
* 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.
|
||||
*/
|
||||
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 EXPANDED_A11Y_STATE = { expanded: true };
|
||||
const SECTION_HEADER_HEIGHT = 44;
|
||||
|
||||
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,6 +86,7 @@ export function useMobileModelPage(input: {
|
||||
providers: readonly ProviderSelectorProvider[];
|
||||
profiles?: readonly AgentProfilePickerRow[] | null;
|
||||
canCreateProfile?: boolean;
|
||||
showProfilesSection?: boolean;
|
||||
selectedProvider: string;
|
||||
selectedModel: string;
|
||||
}): MobileModelPage {
|
||||
@@ -93,12 +94,20 @@ export function useMobileModelPage(input: {
|
||||
providers,
|
||||
profiles = null,
|
||||
canCreateProfile = false,
|
||||
showProfilesSection = true,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
} = input;
|
||||
const pageInput = useMemo<MobileModelPageInput<AgentProfilePickerRow>>(
|
||||
() => ({ providers, profiles, canCreateProfile, selectedProvider, selectedModel }),
|
||||
[canCreateProfile, profiles, providers, selectedModel, selectedProvider],
|
||||
() => ({
|
||||
providers,
|
||||
profiles,
|
||||
canCreateProfile,
|
||||
showProfilesSection,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
}),
|
||||
[canCreateProfile, profiles, providers, selectedModel, selectedProvider, showProfilesSection],
|
||||
);
|
||||
const inputRef = useRef(pageInput);
|
||||
inputRef.current = pageInput;
|
||||
@@ -150,6 +159,7 @@ export function SheetSearchDock({
|
||||
placeholder={placeholder}
|
||||
clearAccessibilityLabel={t("providerCatalog.clearSearch")}
|
||||
fullWidth
|
||||
variant="card"
|
||||
testID={testID}
|
||||
clearTestID={testID ? `${testID}-clear` : undefined}
|
||||
/>
|
||||
@@ -255,6 +265,21 @@ 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 (
|
||||
@@ -288,12 +313,8 @@ export function MobileModelPageView({
|
||||
);
|
||||
}
|
||||
if (!projection.showSectionHeaders) {
|
||||
const section = projection.sections[0];
|
||||
return (
|
||||
<View style={styles.page} testID="mobile-model-page">
|
||||
{section?.kind === "provider" ? (
|
||||
<ExpandedProviderHeader section={section} serverId={serverId} />
|
||||
) : null}
|
||||
<SheetListCard header={singleProviderHeader} testID="mobile-model-page">
|
||||
{projection.body ? (
|
||||
<SectionBody
|
||||
body={projection.body}
|
||||
@@ -304,7 +325,7 @@ export function MobileModelPageView({
|
||||
isRetryingProvider={actions.isRetryingProvider}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</SheetListCard>
|
||||
);
|
||||
}
|
||||
return (
|
||||
@@ -321,8 +342,8 @@ export function MobileModelPageView({
|
||||
<AccordionSectionCard
|
||||
key={section.key}
|
||||
section={section}
|
||||
body={projection.body}
|
||||
selectedIndex={projection.selectedIndex}
|
||||
body={section.expanded ? projection.body : null}
|
||||
selectedIndex={section.expanded ? projection.selectedIndex : null}
|
||||
serverId={serverId}
|
||||
actions={actions}
|
||||
renderItem={renderItem}
|
||||
@@ -334,6 +355,92 @@ 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,
|
||||
@@ -351,29 +458,27 @@ function AccordionSectionCard({
|
||||
renderItem: ModelItemRenderer;
|
||||
onToggle: (action: MobileModelPageAction) => void;
|
||||
}) {
|
||||
if (!section.expanded) {
|
||||
return (
|
||||
<SettingsCard>
|
||||
{section.kind === "profiles" ? (
|
||||
<CollapsedProfilesRow section={section} onToggle={onToggle} />
|
||||
) : (
|
||||
<CollapsedProviderRow section={section} serverId={serverId} onToggle={onToggle} />
|
||||
)}
|
||||
</SettingsCard>
|
||||
);
|
||||
}
|
||||
const handleToggle = useCallback(
|
||||
() => onToggle({ kind: "toggleSection", key: section.key }),
|
||||
[onToggle, section.key],
|
||||
);
|
||||
return (
|
||||
<SettingsCard>
|
||||
{section.kind === "profiles" ? (
|
||||
<ExpandedProfilesHeader
|
||||
section={section}
|
||||
<ProfilesSectionHeader
|
||||
expanded={section.expanded}
|
||||
onEditProfiles={actions.onEditProfiles}
|
||||
onToggle={onToggle}
|
||||
onToggle={handleToggle}
|
||||
/>
|
||||
) : (
|
||||
<ExpandedProviderHeader section={section} serverId={serverId} onToggle={onToggle} />
|
||||
<ProviderSectionHeader
|
||||
section={section}
|
||||
serverId={serverId}
|
||||
collapsible
|
||||
onToggle={handleToggle}
|
||||
/>
|
||||
)}
|
||||
{body ? (
|
||||
{section.expanded && body ? (
|
||||
<SectionBody
|
||||
body={body}
|
||||
selectedIndex={selectedIndex}
|
||||
@@ -389,12 +494,25 @@ 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.
|
||||
* with the list, then the list scrolls inside it while its optional header stays fixed.
|
||||
*/
|
||||
function SheetListCard({ children }: { children: ReactNode }) {
|
||||
function SheetListCard({
|
||||
header,
|
||||
children,
|
||||
testID,
|
||||
}: {
|
||||
header?: ReactNode;
|
||||
children: ReactNode;
|
||||
testID?: string;
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.listCardPage}>
|
||||
<SettingsCard shrink>{children}</SettingsCard>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -409,269 +527,166 @@ function getSearchEntryKey(entry: SearchEntry): string {
|
||||
return entry.key;
|
||||
}
|
||||
|
||||
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);
|
||||
function computeBoundedListHeight(itemCount: number): number {
|
||||
return Math.min(
|
||||
Math.max(itemCount, 1) * MODEL_PICKER_ROW_HEIGHT + LIST_CONTENT.paddingBottom,
|
||||
MOBILE_EXPANDED_PROVIDER_HEIGHT,
|
||||
);
|
||||
}
|
||||
|
||||
function ExpandedSectionHeader({
|
||||
/**
|
||||
* One header component shared across collapsed and expanded states so toggling never shifts the
|
||||
* icon, label, or chevron.
|
||||
*/
|
||||
function CollapsibleSectionHeader({
|
||||
leading,
|
||||
title,
|
||||
summary,
|
||||
expanded,
|
||||
trailing,
|
||||
onCollapse,
|
||||
onToggle,
|
||||
testID,
|
||||
}: {
|
||||
leading: ReactNode;
|
||||
title: string;
|
||||
summary: string | null;
|
||||
expanded: boolean;
|
||||
trailing?: ReactNode;
|
||||
onCollapse?: () => void;
|
||||
onToggle?: () => void;
|
||||
testID: string;
|
||||
}) {
|
||||
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>
|
||||
</>
|
||||
const accessibilityState = useMemo(() => ({ expanded }), [expanded]);
|
||||
const webExpandedProps = useMemo(
|
||||
() => (isWeb ? ({ "aria-expanded": expanded } as const) : null),
|
||||
[expanded],
|
||||
);
|
||||
if (!onCollapse) {
|
||||
return (
|
||||
<View style={styles.expandedHeader} testID={testID}>
|
||||
<View style={styles.expandedTrigger}>{titleContent}</View>
|
||||
{trailing}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<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}
|
||||
<View style={styles.sectionHeader}>
|
||||
{onToggle ? (
|
||||
<PressHighlight
|
||||
onPress={onCollapse}
|
||||
hitSlop={8}
|
||||
{...webExpandedProps}
|
||||
onPress={onToggle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={title}
|
||||
accessibilityState={EXPANDED_A11Y_STATE}
|
||||
style={styles.collapseChevron}
|
||||
>
|
||||
<ThemedChevronUp size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
||||
</PressHighlight>
|
||||
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}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ExpandedProfilesHeader({
|
||||
section,
|
||||
function ProfilesSectionHeader({
|
||||
expanded,
|
||||
onEditProfiles,
|
||||
onToggle,
|
||||
}: {
|
||||
section: MobileProfilesSection;
|
||||
expanded: boolean;
|
||||
onEditProfiles?: () => void;
|
||||
onToggle: (action: MobileModelPageAction) => void;
|
||||
onToggle: () => 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={foregroundMapping} />,
|
||||
[],
|
||||
);
|
||||
const trailing = useMemo(
|
||||
() =>
|
||||
onEditProfiles ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
leftIcon={Pencil}
|
||||
onPress={onEditProfiles}
|
||||
accessibilityLabel={t("modelSelector.editProfilesLabel")}
|
||||
testID="model-profiles-edit"
|
||||
/>
|
||||
) : null,
|
||||
[onEditProfiles, t],
|
||||
);
|
||||
return (
|
||||
<ExpandedSectionHeader
|
||||
leading={leading}
|
||||
title={t("modelSelector.profiles")}
|
||||
summary={String(section.count)}
|
||||
trailing={trailing}
|
||||
onCollapse={handleCollapse}
|
||||
testID="model-profiles-section"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
onToggle,
|
||||
}: {
|
||||
section: MobileProviderSection;
|
||||
serverId: string | null;
|
||||
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}
|
||||
tone="foreground"
|
||||
/>
|
||||
),
|
||||
[section.providerId, serverId],
|
||||
);
|
||||
const trailing = useMemo(
|
||||
() =>
|
||||
serverId ? (
|
||||
<CustomizeProviderButton
|
||||
serverId={serverId}
|
||||
providerId={section.providerId}
|
||||
providerLabel={section.label}
|
||||
/>
|
||||
) : null,
|
||||
[section.label, section.providerId, serverId],
|
||||
() => (expanded && onEditProfiles ? <EditProfilesButton onPress={onEditProfiles} /> : null),
|
||||
[expanded, onEditProfiles],
|
||||
);
|
||||
return (
|
||||
<ExpandedSectionHeader
|
||||
<CollapsibleSectionHeader
|
||||
leading={leading}
|
||||
title={section.label}
|
||||
summary={section.status === "ready" ? summary : null}
|
||||
title={t("modelSelector.profiles")}
|
||||
expanded={expanded}
|
||||
trailing={trailing}
|
||||
onCollapse={onToggle ? handleCollapse : undefined}
|
||||
testID={`model-provider-section-${section.providerId}`}
|
||||
onToggle={onToggle}
|
||||
testID={expanded ? "model-profiles-section" : "model-picker-rail-profiles"}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CollapsedProviderRow({
|
||||
function ProviderSectionHeader({
|
||||
section,
|
||||
serverId,
|
||||
collapsible,
|
||||
onToggle,
|
||||
}: {
|
||||
section: MobileProviderSection;
|
||||
serverId: string | null;
|
||||
onToggle: (action: MobileModelPageAction) => void;
|
||||
collapsible: boolean;
|
||||
onToggle?: () => void;
|
||||
}) {
|
||||
const summary = useSectionSummary(section);
|
||||
const handlePress = useCallback(
|
||||
() => onToggle({ kind: "toggleSection", key: section.key }),
|
||||
[onToggle, section.key],
|
||||
);
|
||||
const leadingSlot = useMemo(
|
||||
const leading = 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],
|
||||
);
|
||||
const trailing = useMemo(() => {
|
||||
if (section.expanded) {
|
||||
return 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]);
|
||||
|
||||
return (
|
||||
<ModelBrowserRow
|
||||
label={section.label}
|
||||
leadingSlot={leadingSlot}
|
||||
trailingSlot={trailingSlot}
|
||||
spacing="provider"
|
||||
onPress={handlePress}
|
||||
testID={`model-provider-${section.providerId}`}
|
||||
<CollapsibleSectionHeader
|
||||
leading={leading}
|
||||
title={section.label}
|
||||
expanded={section.expanded}
|
||||
trailing={trailing}
|
||||
onToggle={collapsible ? onToggle : undefined}
|
||||
testID={
|
||||
section.expanded
|
||||
? `model-provider-section-${section.providerId}`
|
||||
: `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>;
|
||||
}) => React.ReactElement;
|
||||
}) => ReactElement;
|
||||
|
||||
function SectionBody({
|
||||
body,
|
||||
@@ -689,7 +704,7 @@ function SectionBody({
|
||||
onRetryProvider: ModelPickerActions["onRetryProvider"];
|
||||
isRetryingProvider: boolean;
|
||||
}) {
|
||||
const frameStyle = fill ? styles.page : styles.fixedViewport;
|
||||
const frameStyle = fill ? styles.fillState : styles.fixedViewport;
|
||||
if (body.kind === "providerLoading") {
|
||||
return (
|
||||
<View style={[frameStyle, styles.centered]}>
|
||||
@@ -710,58 +725,91 @@ 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 at its top or at the selected model.
|
||||
// Each section is a new list, which opens directly 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>;
|
||||
}
|
||||
|
||||
/** Opens with the selected model in view, such as an older model behind the opened fold. */
|
||||
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`. */
|
||||
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);
|
||||
// Waits for the first visible rows, so a selection already in view never scrolls the list.
|
||||
const reveal = useRevealActiveFlatListRow({
|
||||
const { initialScrollIndex, contentOffset } = useInitialFlatListScroll({
|
||||
listRef,
|
||||
selectedIndex,
|
||||
itemCount: items.length,
|
||||
activeIndex: selectedIndex,
|
||||
waitForViewable: true,
|
||||
visibleCount: Math.max(1, Math.floor(viewportHeight / MODEL_PICKER_ROW_HEIGHT)),
|
||||
offsetForIndex: modelItemOffset,
|
||||
});
|
||||
|
||||
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 (
|
||||
<FlatList
|
||||
<ListComponent
|
||||
ref={listRef}
|
||||
data={items}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={getItemKey}
|
||||
style={fill ? styles.page : styles.fixedViewport}
|
||||
getItemLayout={getModelItemLayout}
|
||||
initialScrollIndex={initialScrollIndex}
|
||||
contentOffset={contentOffset}
|
||||
style={boxStyle}
|
||||
contentContainerStyle={LIST_CONTENT}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
keyboardDismissMode={KEYBOARD_DISMISS_MODE}
|
||||
showsVerticalScrollIndicator
|
||||
nestedScrollEnabled
|
||||
onScrollToIndexFailed={reveal.onScrollToIndexFailed}
|
||||
onViewableItemsChanged={reveal.onViewableItemsChanged}
|
||||
viewabilityConfig={reveal.viewabilityConfig}
|
||||
onContentSizeChange={reveal.onContentSizeChange}
|
||||
onLayout={reveal.onLayout}
|
||||
testID="compact-model-list"
|
||||
nestedScrollEnabled={!fill}
|
||||
testID={testID}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -778,62 +826,77 @@ 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],
|
||||
},
|
||||
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,
|
||||
sectionHeader: {
|
||||
height: SECTION_HEADER_HEIGHT,
|
||||
position: "relative",
|
||||
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] },
|
||||
},
|
||||
expandedTrailing: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
sectionHeaderPress: {
|
||||
...StyleSheet.absoluteFill,
|
||||
},
|
||||
collapseChevron: {
|
||||
minWidth: 24,
|
||||
minHeight: 44,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
sectionHeaderPressed: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
passThrough: {
|
||||
pointerEvents: "none",
|
||||
},
|
||||
boxNone: {
|
||||
pointerEvents: "box-none",
|
||||
},
|
||||
glyph: {
|
||||
width: 16,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
expandedTitle: {
|
||||
sectionTitleWrap: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
sectionTitle: {
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
summary: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontVariant: ["tabular-nums"],
|
||||
},
|
||||
collapsedTrailing: {
|
||||
sectionTrailing: {
|
||||
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 }],
|
||||
},
|
||||
@@ -841,6 +904,9 @@ const styles = StyleSheet.create((theme) => ({
|
||||
height: MOBILE_EXPANDED_PROVIDER_HEIGHT,
|
||||
flexGrow: 0,
|
||||
},
|
||||
boundedViewport: {
|
||||
flexGrow: 0,
|
||||
},
|
||||
centered: {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
@@ -849,4 +915,14 @@ 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,20 +152,84 @@ describe("model picker layout", () => {
|
||||
expect(resolveModelPickerLayout(input({ profiles: null }))).toBe("twoPane");
|
||||
});
|
||||
|
||||
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", () => {
|
||||
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",
|
||||
);
|
||||
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);
|
||||
@@ -198,12 +262,6 @@ 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);
|
||||
@@ -244,9 +302,6 @@ 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({
|
||||
@@ -286,7 +341,6 @@ 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 });
|
||||
});
|
||||
|
||||
@@ -297,7 +351,7 @@ describe("model picker provider pane", () => {
|
||||
railKey: "codex",
|
||||
});
|
||||
const projection = projectModelPicker(pickerInput, state);
|
||||
expect(projection.pane).toMatchObject({ kind: "provider", foldKind: null });
|
||||
expect(projection.pane).toMatchObject({ kind: "provider", providerId: "codex" });
|
||||
expect(keys(projection.pane.items)).toEqual([
|
||||
"model:codex:gpt-5.4",
|
||||
"model:codex:gpt-5.4-mini",
|
||||
|
||||
@@ -65,14 +65,13 @@ export type ModelPickerAction =
|
||||
| { kind: "toggleFold"; providerId: string; expanded: boolean };
|
||||
|
||||
export type ModelPickerRailItem =
|
||||
| { kind: "profiles"; key: typeof MODEL_PICKER_PROFILES_RAIL_KEY; count: number }
|
||||
| { kind: "profiles"; key: typeof MODEL_PICKER_PROFILES_RAIL_KEY }
|
||||
| {
|
||||
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;
|
||||
};
|
||||
@@ -101,13 +100,29 @@ export type ModelPickerPane<TProfile extends NavigableProfileRow = NavigableProf
|
||||
kind: "provider";
|
||||
providerId: string;
|
||||
label: string;
|
||||
shown: number;
|
||||
total: number;
|
||||
foldKind: ModelFoldKind;
|
||||
/** 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>[];
|
||||
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";
|
||||
@@ -138,22 +153,31 @@ export function modelPickerFoldKey(providerId: string): string {
|
||||
return `fold:${providerId}`;
|
||||
}
|
||||
|
||||
/** 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). */
|
||||
/** 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). */
|
||||
export function resolveModelPickerLayout(input: ModelPickerInput): ModelPickerLayout {
|
||||
return input.providers.length > 1 || input.profiles !== null ? "twoPane" : "singlePane";
|
||||
return input.providers.length > 1 ? "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, folded ones included.
|
||||
* searching never moves it. A single pane sizes to all its rows, profiles and folded ones included.
|
||||
*/
|
||||
export function resolveModelPickerHeight(input: ModelPickerInput): number {
|
||||
if (resolveModelPickerLayout(input) === "twoPane") return TWO_PANE_HEIGHT;
|
||||
const provider = input.providers[0];
|
||||
const rowCount = provider ? countAllRows(provider) : 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;
|
||||
}
|
||||
}
|
||||
return clamp(
|
||||
SINGLE_PANE_CHROME_HEIGHT + rowCount * LIST_ROW_HEIGHT,
|
||||
SINGLE_PANE_CHROME_HEIGHT + (providerRows + profileRows) * LIST_ROW_HEIGHT,
|
||||
SINGLE_PANE_MIN_HEIGHT,
|
||||
TWO_PANE_HEIGHT,
|
||||
);
|
||||
@@ -198,7 +222,7 @@ export function projectModelPicker<TProfile extends NavigableProfileRow>(
|
||||
const normalizedQuery = normalizeQuery(state.query);
|
||||
const pane = normalizedQuery
|
||||
? buildSearchPane(input, normalizedQuery, state.query.trim())
|
||||
: buildBrowsePane(input, state, railKey);
|
||||
: buildBrowsePane(input, state, layout, railKey);
|
||||
const focus: ModelPickerFocus =
|
||||
layout === "twoPane" && !normalizedQuery && state.focus === "rail" ? "rail" : "list";
|
||||
return {
|
||||
@@ -357,23 +381,31 @@ 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 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,
|
||||
];
|
||||
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];
|
||||
}
|
||||
|
||||
function buildProviderRailItem(
|
||||
input: ModelPickerInput,
|
||||
provider: ProviderSelectorProvider,
|
||||
startsErrorGroup: boolean,
|
||||
): Extract<ModelPickerRailItem, { kind: "provider" }> {
|
||||
const selection = provider.modelSelection;
|
||||
const base = {
|
||||
@@ -381,16 +413,17 @@ function buildProviderRailItem(
|
||||
key: provider.id,
|
||||
providerId: provider.id,
|
||||
label: provider.label,
|
||||
startsErrorGroup: false,
|
||||
startsErrorGroup,
|
||||
};
|
||||
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 };
|
||||
if (selection.kind === "loading") return { ...base, status: "loading" };
|
||||
if (selection.kind === "error") return { ...base, status: "error" };
|
||||
return { ...base, status: "ready" };
|
||||
}
|
||||
|
||||
function buildBrowsePane<TProfile extends NavigableProfileRow>(
|
||||
input: ModelPickerInput<TProfile>,
|
||||
state: ModelPickerState,
|
||||
layout: ModelPickerLayout,
|
||||
railKey: string,
|
||||
): ModelPickerPane<TProfile> {
|
||||
if (railKey === MODEL_PICKER_PROFILES_RAIL_KEY) {
|
||||
@@ -398,9 +431,19 @@ 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, items: [] };
|
||||
return {
|
||||
kind: "providerLoading",
|
||||
providerId: provider.id,
|
||||
label: provider.label,
|
||||
profiles: singlePaneProfiles,
|
||||
items: singlePaneProfiles,
|
||||
};
|
||||
}
|
||||
if (selection.kind === "error") {
|
||||
return {
|
||||
@@ -408,18 +451,45 @@ function buildBrowsePane<TProfile extends NavigableProfileRow>(
|
||||
providerId: provider.id,
|
||||
label: provider.label,
|
||||
message: selection.message,
|
||||
items: [],
|
||||
profiles: singlePaneProfiles,
|
||||
items: singlePaneProfiles,
|
||||
};
|
||||
}
|
||||
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,
|
||||
shown: partition.primary.length,
|
||||
total: selection.rows.length,
|
||||
foldKind: partition.foldKind,
|
||||
items: buildProviderItems(provider.id, partition, state),
|
||||
profiles: [],
|
||||
models: providerModels,
|
||||
items: providerModels,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
useReducer,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
@@ -33,6 +34,8 @@ import {
|
||||
type SheetKeyboard,
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import {
|
||||
MODEL_PICKER_HEADING_HEIGHT,
|
||||
MODEL_PICKER_ROW_HEIGHT,
|
||||
ModelBrowserLoadingState,
|
||||
ModelBrowserRow,
|
||||
ModelBrowserSectionHeading,
|
||||
@@ -60,7 +63,11 @@ 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 { useRevealActiveFlatListRow, useRevealActiveItem } from "@/components/ui/scroll-reveal";
|
||||
import {
|
||||
useInitialFlatListScroll,
|
||||
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";
|
||||
@@ -165,6 +172,7 @@ export function DesktopModelPicker({
|
||||
>
|
||||
<ModelPickerBody
|
||||
input={input}
|
||||
pickerHeight={height}
|
||||
serverId={serverId}
|
||||
keyboardHandlerRef={keyboardHandlerRef}
|
||||
{...actions}
|
||||
@@ -176,11 +184,13 @@ 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>;
|
||||
}) {
|
||||
@@ -308,6 +318,7 @@ function ModelPickerBody({
|
||||
body = (
|
||||
<ListPane
|
||||
projection={projection}
|
||||
pickerHeight={pickerHeight}
|
||||
query={state.query}
|
||||
serverId={serverId}
|
||||
input={input}
|
||||
@@ -322,6 +333,7 @@ function ModelPickerBody({
|
||||
<Rail projection={projection} serverId={serverId} onSelectRail={handleSelectRail} />
|
||||
<ListPane
|
||||
projection={projection}
|
||||
pickerHeight={pickerHeight}
|
||||
query={state.query}
|
||||
serverId={serverId}
|
||||
input={input}
|
||||
@@ -444,6 +456,9 @@ 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 (
|
||||
@@ -455,14 +470,30 @@ function RailRowStatus({ item }: { item: ModelPickerRailItem }) {
|
||||
if (item.kind === "provider" && item.status === "error") {
|
||||
return <ThemedAlertTriangle size={ICON_SIZE.xs} uniProps={foregroundMutedMapping} />;
|
||||
}
|
||||
return <Text style={styles.count}>{item.count}</Text>;
|
||||
return null;
|
||||
}
|
||||
|
||||
type ListEntry =
|
||||
| { kind: "heading"; key: string; title: string }
|
||||
| {
|
||||
kind: "heading";
|
||||
key: string;
|
||||
title: string;
|
||||
action?:
|
||||
| { kind: "editProfiles" }
|
||||
| { kind: "customizeProvider"; providerId: string; providerLabel: string };
|
||||
}
|
||||
| { kind: "item"; key: string; item: ModelPickerListItem<AgentProfilePickerRow> };
|
||||
|
||||
/** Search results carry section headings between their groups; every other pane is a flat list. */
|
||||
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. */
|
||||
function useListEntries(pane: ModelPickerPane<AgentProfilePickerRow>): ListEntry[] {
|
||||
const { t } = useTranslation();
|
||||
return useMemo(() => {
|
||||
@@ -471,6 +502,35 @@ 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) {
|
||||
@@ -489,6 +549,22 @@ 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;
|
||||
@@ -501,8 +577,15 @@ 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,
|
||||
@@ -511,6 +594,7 @@ 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>;
|
||||
@@ -521,23 +605,41 @@ 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") return <ModelBrowserSectionHeading title={entry.title} />;
|
||||
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} />;
|
||||
}
|
||||
const { item } = entry;
|
||||
return (
|
||||
<ModelPickerItemRow
|
||||
@@ -570,33 +672,102 @@ 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 ? (
|
||||
<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"
|
||||
<PaneFlatList
|
||||
key={paneListKey}
|
||||
entries={entries}
|
||||
activeKey={activeKey}
|
||||
listKey={inSearch ? query : paneListKey}
|
||||
visibleCount={visibleCount}
|
||||
renderEntry={renderEntry}
|
||||
listFooter={inlineStateFooter}
|
||||
/>
|
||||
) : null}
|
||||
) : (
|
||||
<PaneState pane={pane} actions={actions} />
|
||||
)}
|
||||
</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,
|
||||
@@ -607,36 +778,22 @@ function ListPaneHeader({
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
if (pane.kind === "search" || pane.kind === "noMatches") return null;
|
||||
if (!paneShowsHeader(pane)) return null;
|
||||
if (pane.kind === "profiles") {
|
||||
return (
|
||||
<View style={styles.paneHeader}>
|
||||
<Text style={styles.paneTitle} numberOfLines={1}>
|
||||
{t("modelSelector.profiles")}
|
||||
</Text>
|
||||
{onEditProfiles ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onPress={onEditProfiles}
|
||||
accessibilityLabel={t("modelSelector.editProfilesLabel")}
|
||||
testID="model-profiles-edit"
|
||||
>
|
||||
{t("modelSelector.editProfiles")}
|
||||
</Button>
|
||||
) : null}
|
||||
{onEditProfiles ? <EditProfilesButton onPress={onEditProfiles} /> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
const summary =
|
||||
pane.kind === "provider" && pane.foldKind !== null
|
||||
? t("modelSelector.shownOfTotal", { shown: pane.shown, total: pane.total })
|
||||
: null;
|
||||
if (pane.kind === "search" || pane.kind === "noMatches") return 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
|
||||
@@ -649,6 +806,20 @@ 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,
|
||||
@@ -861,11 +1032,6 @@ 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,
|
||||
@@ -878,7 +1044,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
paddingBottom: theme.spacing[2],
|
||||
},
|
||||
paneHeader: {
|
||||
height: 36,
|
||||
height: PANE_HEADER_HEIGHT,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
@@ -892,8 +1058,4 @@ const styles = StyleSheet.create((theme) => ({
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
paneSummary: {
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -101,6 +101,10 @@ 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);
|
||||
@@ -2036,29 +2040,28 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: theme.colors.border,
|
||||
},
|
||||
sectionHeading: {
|
||||
position: "relative",
|
||||
height: MODEL_PICKER_HEADING_HEIGHT,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
paddingHorizontal: isWeb ? theme.spacing[3] : theme.spacing[6],
|
||||
paddingTop: theme.spacing[2],
|
||||
paddingBottom: theme.spacing[1],
|
||||
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[3] },
|
||||
},
|
||||
sectionHeadingAction: {
|
||||
position: "absolute",
|
||||
top: theme.spacing[1],
|
||||
right: isWeb ? theme.spacing[3] : theme.spacing[6],
|
||||
flexShrink: 0,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
sectionHeadingText: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
browserRow: {
|
||||
flexDirection: "row",
|
||||
paddingVertical: theme.spacing[2],
|
||||
minHeight: 36,
|
||||
alignItems: "center",
|
||||
height: MODEL_PICKER_ROW_HEIGHT,
|
||||
},
|
||||
modelRowHoverBoundary: {
|
||||
position: "relative",
|
||||
@@ -2067,10 +2070,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
right: isWeb ? theme.spacing[3] : theme.spacing[6],
|
||||
right: { xs: theme.spacing[4], md: theme.spacing[3] },
|
||||
justifyContent: "center",
|
||||
},
|
||||
browserModelRow: isWeb ? {} : { marginBottom: theme.spacing[1] },
|
||||
browserModelRow: {},
|
||||
browserRowHovered: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
},
|
||||
@@ -2088,7 +2091,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
paddingHorizontal: isWeb ? theme.spacing[3] : theme.spacing[6],
|
||||
paddingHorizontal: { xs: theme.spacing[4], md: theme.spacing[3] },
|
||||
},
|
||||
browserRowLeading: {
|
||||
width: 16,
|
||||
|
||||
@@ -56,25 +56,13 @@ interface AppSettingsRowProps extends Omit<SettingsRowProps, "hint">, AppRowExtr
|
||||
hint?: ReactNode;
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}) {
|
||||
export function SettingsCard({ children, testID }: { children: ReactNode; testID?: string }) {
|
||||
return (
|
||||
<View style={[settingsStyles.card, shrink && SHRINK]} testID={testID}>
|
||||
<View style={settingsStyles.card} testID={testID}>
|
||||
{Children.toArray(children).map((child, index) => (
|
||||
<View
|
||||
key={isValidElement(child) ? child.key : index}
|
||||
style={[index ? settingsStyles.rowBorder : undefined, shrink && SHRINK]}
|
||||
style={index ? settingsStyles.rowBorder : undefined}
|
||||
>
|
||||
{child}
|
||||
</View>
|
||||
|
||||
@@ -151,5 +151,8 @@ 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,6 +141,7 @@ export function SettingsRowHeader({
|
||||
hovered={hovered}
|
||||
summary={summary}
|
||||
summaryLeading={summaryLeading}
|
||||
titleStyle={layout.title}
|
||||
/>
|
||||
{external || disabled ? null : (
|
||||
<View style={chevronStyle} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
@@ -167,14 +168,17 @@ 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. */}
|
||||
@@ -183,7 +187,7 @@ function RowTrailing({
|
||||
<View style={styles.summaryLeading}>{summaryLeading}</View>
|
||||
) : null}
|
||||
{!external && summary ? (
|
||||
<Text style={styles.summary} numberOfLines={1}>
|
||||
<Text style={summaryStyle} numberOfLines={1}>
|
||||
{summary}
|
||||
</Text>
|
||||
) : null}
|
||||
@@ -315,7 +319,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
summary: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
marginRight: theme.spacing[2],
|
||||
},
|
||||
hovered: {
|
||||
|
||||
@@ -89,9 +89,7 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
width: INDENT_GUIDE_WIDTH,
|
||||
// Translucent ink, not `border`: a solid line that colour disappears into a hovered row's fill.
|
||||
backgroundColor: theme.colors.foregroundExtraMuted,
|
||||
opacity: theme.opacity[50],
|
||||
backgroundColor: theme.colors.treeGuide,
|
||||
},
|
||||
chevron: {
|
||||
width: WORKSPACE_TREE_ICON_SIZE,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getScrollOffsetToRevealItem } from "./scroll-reveal";
|
||||
import { getScrollOffsetToRevealItem, resolveInitialScrollIndex } from "./scroll-reveal";
|
||||
|
||||
describe("getScrollOffsetToRevealItem", () => {
|
||||
it("keeps the offset when the item is already inside the viewport", () => {
|
||||
@@ -46,3 +46,38 @@ 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, useEffect, useLayoutEffect, useRef, type RefObject } from "react";
|
||||
import { useCallback, useLayoutEffect, useRef, type RefObject } from "react";
|
||||
import type {
|
||||
FlatList,
|
||||
LayoutChangeEvent,
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
View,
|
||||
ViewToken,
|
||||
} from "react-native";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
|
||||
export function getScrollOffsetToRevealItem(args: {
|
||||
currentOffset: number;
|
||||
@@ -125,6 +126,88 @@ 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,
|
||||
@@ -147,6 +230,7 @@ export function useRevealActiveFlatListRow<T>({
|
||||
activeIndex,
|
||||
hasHeader = false,
|
||||
waitForViewable = false,
|
||||
initialVisibleRange = null,
|
||||
listKey,
|
||||
}: {
|
||||
listRef: RefObject<FlatList<T> | null>;
|
||||
@@ -154,9 +238,12 @@ 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>(null);
|
||||
const fullyVisibleRows = useRef<VisibleRange | null>(initialVisibleRange);
|
||||
const prevListKey = useRef(listKey);
|
||||
const pendingReveal = useRef<number | null>(null);
|
||||
const isPendingRowMeasured = useRef(true);
|
||||
const itemCountRef = useRef(itemCount);
|
||||
@@ -222,7 +309,11 @@ export function useRevealActiveFlatListRow<T>({
|
||||
[revealPendingRow],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
useLayoutEffect(() => {
|
||||
if (prevListKey.current !== listKey) {
|
||||
prevListKey.current = listKey;
|
||||
fullyVisibleRows.current = null;
|
||||
}
|
||||
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 type { Theme } from "@/styles/theme";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import {
|
||||
EditingTextInput as TextInput,
|
||||
type EditingTextInputHandle,
|
||||
@@ -35,6 +35,11 @@ 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;
|
||||
@@ -56,6 +61,7 @@ export function SearchField({
|
||||
clearAccessibilityLabel,
|
||||
fullWidth = false,
|
||||
size = "md",
|
||||
variant = "default",
|
||||
clearOnEscape = false,
|
||||
testID,
|
||||
clearTestID,
|
||||
@@ -79,17 +85,21 @@ 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,
|
||||
]}
|
||||
>
|
||||
<ThemedSearch size={14} uniProps={mutedColorMapping} />
|
||||
{card ? <View style={styles.leadingSlot}>{leadingIcon}</View> : leadingIcon}
|
||||
<ThemedTextInput
|
||||
testID={testID}
|
||||
ref={inputRef}
|
||||
@@ -112,8 +122,9 @@ export function SearchField({
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={clearAccessibilityLabel}
|
||||
hitSlop={8}
|
||||
style={card ? styles.clearSlot : undefined}
|
||||
>
|
||||
<ThemedX size={14} uniProps={mutedColorMapping} />
|
||||
<ThemedX size={ICON_SIZE.sm} uniProps={mutedColorMapping} />
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
@@ -142,6 +153,25 @@ 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 { uploadImageAttachments } from "@/attachments/service";
|
||||
import { prepareImageAttachmentsForSend } from "@/attachments/service";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
import {
|
||||
resolveComposerAttachmentSubmitFormat,
|
||||
@@ -122,6 +122,7 @@ function failureMessageForCreationMethod(
|
||||
function buildCreateAgentOptions({
|
||||
composerState,
|
||||
text,
|
||||
images,
|
||||
attachments,
|
||||
workspaceDirectory,
|
||||
workspaceId,
|
||||
@@ -134,6 +135,7 @@ function buildCreateAgentOptions({
|
||||
selectedSystemPrompt: string;
|
||||
};
|
||||
text: string;
|
||||
images?: CreateAgentRequestOptions["images"];
|
||||
attachments: NonNullable<CreateAgentRequestOptions["attachments"]>;
|
||||
workspaceDirectory: string;
|
||||
workspaceId: string;
|
||||
@@ -152,6 +154,7 @@ function buildCreateAgentOptions({
|
||||
? { systemPrompt: composerState.selectedSystemPrompt }
|
||||
: {}),
|
||||
...(text.trim() ? { initialPrompt: text.trim() } : {}),
|
||||
...(images && images.length > 0 ? { images } : {}),
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
};
|
||||
}
|
||||
@@ -327,19 +330,20 @@ export function WorkspaceSetupDialog() {
|
||||
supportsForgeAttachments: supportsForgeSearch,
|
||||
}),
|
||||
});
|
||||
const uploadedImageAttachments =
|
||||
const imagePayload =
|
||||
wirePayload.images.length > 0
|
||||
? await uploadImageAttachments({
|
||||
? await prepareImageAttachmentsForSend({
|
||||
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,
|
||||
attachments: [...wirePayload.attachments, ...(uploadedImageAttachments ?? [])],
|
||||
images: imagePayload.images,
|
||||
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
|
||||
workspaceDirectory: cwd,
|
||||
workspaceId: "",
|
||||
provider: composerState.selectedProvider,
|
||||
|
||||
@@ -191,7 +191,11 @@ interface FakeSendCall {
|
||||
}
|
||||
|
||||
function createFakeSendClient(
|
||||
options: { rejection?: Error; beforeRejection?: (call: FakeSendCall) => void } = {},
|
||||
options: {
|
||||
rejection?: Error;
|
||||
beforeRejection?: (call: FakeSendCall) => void;
|
||||
uploadedImageAttachments?: boolean;
|
||||
} = {},
|
||||
): ComposerSendClient & {
|
||||
calls: FakeSendCall[];
|
||||
uploadCalls: Array<{ fileName: string; mimeType: string; bytes: Uint8Array }>;
|
||||
@@ -201,6 +205,9 @@ 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);
|
||||
@@ -1097,7 +1104,6 @@ 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]));
|
||||
@@ -1137,7 +1143,6 @@ describe("file upload preparation", () => {
|
||||
await expect(
|
||||
uploadFileAttachments({
|
||||
client: {
|
||||
sendAgentMessage: async () => {},
|
||||
uploadFile: async () => {
|
||||
sends++;
|
||||
throw new Error("unexpected send");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { SelectedFile } from "@/attachments/selected-file";
|
||||
import { uploadImageAttachments } from "@/attachments/service";
|
||||
import { prepareImageAttachmentsForSend } from "@/attachments/service";
|
||||
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
import type {
|
||||
ActiveTurnBehavior,
|
||||
@@ -65,6 +65,7 @@ export interface ComposerSendClient {
|
||||
file: UploadedFileAttachment | null;
|
||||
error: string | null;
|
||||
}>;
|
||||
getLastServerInfoMessage: () => { features?: { uploadedImageAttachments?: boolean } } | null;
|
||||
}
|
||||
|
||||
export interface ComposerCancelClient {
|
||||
@@ -121,7 +122,7 @@ export async function pickAndPersistImages(input: {
|
||||
}
|
||||
|
||||
export async function uploadFileAttachments(input: {
|
||||
client: ComposerSendClient;
|
||||
client: Pick<ComposerSendClient, "uploadFile">;
|
||||
files: SelectedFile[];
|
||||
}): Promise<Extract<ComposerAttachment, { kind: "file" }>[]> {
|
||||
const result: Extract<ComposerAttachment, { kind: "file" }>[] = [];
|
||||
@@ -213,13 +214,17 @@ export async function dispatchComposerAgentMessage(
|
||||
});
|
||||
input.submission.begin(input.agentId, userMessage);
|
||||
try {
|
||||
const uploadedImageAttachments = input.uploadImages
|
||||
? await input.uploadImages(wirePayload.images)
|
||||
: await uploadImageAttachments({ client: input.client, images: wirePayload.images });
|
||||
const imagePayload = input.uploadImages
|
||||
? { attachments: await input.uploadImages(wirePayload.images) }
|
||||
: await prepareImageAttachmentsForSend({
|
||||
client: input.client,
|
||||
images: wirePayload.images,
|
||||
});
|
||||
await input.client.sendAgentMessage(input.agentId, input.text, {
|
||||
messageId: clientMessageId,
|
||||
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
|
||||
attachments: [...wirePayload.attachments, ...(uploadedImageAttachments ?? [])],
|
||||
...(imagePayload.images ? { images: imagePayload.images } : {}),
|
||||
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
|
||||
});
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
} catch (error) {
|
||||
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
import { ModelProviderGlyph } from "@/components/model-browser";
|
||||
import type { ModelPickerActions } from "@/components/model-browser-panes";
|
||||
import {
|
||||
CollapsibleProfilesCard,
|
||||
getSheetSearchFooterStyle,
|
||||
MobileModelPageView,
|
||||
SheetSearchDock,
|
||||
useMobileModelPage,
|
||||
@@ -86,6 +88,7 @@ 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);
|
||||
@@ -93,10 +96,16 @@ 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("");
|
||||
@@ -116,6 +125,7 @@ export function AgentSettingsDrawer({
|
||||
const close = useCallback(() => {
|
||||
Keyboard.dismiss();
|
||||
setPage(AGENT_SHEET_HOME);
|
||||
setProfilesExpanded(false);
|
||||
setPageQuery("");
|
||||
modelPage.reset();
|
||||
onClose();
|
||||
@@ -262,15 +272,39 @@ export function AgentSettingsDrawer({
|
||||
|
||||
const topCard = useMemo(
|
||||
() => (
|
||||
<AgentSheetTopCard
|
||||
selectedProvider={selectedProvider}
|
||||
serverId={serverId}
|
||||
selectedModelLabel={selectedModelLabel}
|
||||
disabled={disabled}
|
||||
onOpenModel={openModel}
|
||||
/>
|
||||
<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>
|
||||
),
|
||||
[disabled, openModel, selectedModelLabel, selectedProvider, serverId],
|
||||
[
|
||||
disabled,
|
||||
handleApplyProfile,
|
||||
handleEditProfiles,
|
||||
onEditProfiles,
|
||||
openModel,
|
||||
profiles,
|
||||
profilesExpanded,
|
||||
selectedModelLabel,
|
||||
selectedProvider,
|
||||
serverId,
|
||||
toggleProfiles,
|
||||
],
|
||||
);
|
||||
|
||||
let body: ReactNode;
|
||||
@@ -319,6 +353,7 @@ export function AgentSettingsDrawer({
|
||||
snapPoints={SNAP_POINTS}
|
||||
scrollable={false}
|
||||
footer={footer}
|
||||
footerContainerStyle={getSheetSearchFooterStyle()}
|
||||
keyboard={keyboard}
|
||||
contentStyle={styles.sheetBody}
|
||||
contextBridge={contextBridge}
|
||||
@@ -410,13 +445,16 @@ function SelectSearchDock({
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create(() => ({
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
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.sm,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
radioRow: {
|
||||
minHeight: 44,
|
||||
|
||||
@@ -4,14 +4,22 @@ import type { AttachmentMetadata, AttachmentStore } from "@/attachments/types";
|
||||
import { __setAttachmentStoreForTests } from "@/attachments/store";
|
||||
import { requestWorkspaceDraftAgent } from "./create-agent-request";
|
||||
|
||||
function createFakeStore(bytesById: Record<string, Uint8Array>): AttachmentStore {
|
||||
function createFakeStore(
|
||||
bytesById: Record<string, Uint8Array>,
|
||||
options: { allowEncodeBase64?: boolean } = {},
|
||||
): AttachmentStore {
|
||||
return {
|
||||
storageType: "web-indexeddb",
|
||||
async save() {
|
||||
throw new Error("not used");
|
||||
},
|
||||
async encodeBase64() {
|
||||
throw new Error("encodeBase64 must not be called when uploading images");
|
||||
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 readBytes({ attachment }) {
|
||||
const bytes = bytesById[attachment.id];
|
||||
@@ -54,7 +62,11 @@ describe("requestWorkspaceDraftAgent", () => {
|
||||
id: "agent-new",
|
||||
...input,
|
||||
}));
|
||||
const client = { uploadFile, createAgent } as unknown as DaemonClient;
|
||||
const client = {
|
||||
uploadFile,
|
||||
createAgent,
|
||||
getLastServerInfoMessage: () => ({ features: { uploadedImageAttachments: true } }),
|
||||
} as unknown as DaemonClient;
|
||||
|
||||
const images: AttachmentMetadata[] = [
|
||||
{
|
||||
@@ -110,4 +122,50 @@ 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 { uploadImageAttachments } from "@/attachments/service";
|
||||
import { prepareImageAttachmentsForSend } from "@/attachments/service";
|
||||
import type { AttachmentMetadata } from "@/attachments/types";
|
||||
|
||||
export interface WorkspaceDraftAgentRequest {
|
||||
@@ -21,13 +21,14 @@ export async function requestWorkspaceDraftAgent(
|
||||
client: DaemonClient,
|
||||
request: WorkspaceDraftAgentRequest,
|
||||
): Promise<AgentSnapshotPayload> {
|
||||
const uploadedImageAttachments = await uploadImageAttachments({ client, images: request.images });
|
||||
const mergedAttachments = [...(request.attachments ?? []), ...(uploadedImageAttachments ?? [])];
|
||||
const imagePayload = await prepareImageAttachmentsForSend({ client, images: request.images });
|
||||
const mergedAttachments = [...(request.attachments ?? []), ...(imagePayload.attachments ?? [])];
|
||||
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 { uploadImageAttachments } from "@/attachments/service";
|
||||
import { prepareImageAttachmentsForSend } from "@/attachments/service";
|
||||
import { shouldAutoFocusWorkspaceDraftComposer } from "@/screens/workspace/workspace-draft-pane-focus";
|
||||
import {
|
||||
resolveDraftWorkingDirectory,
|
||||
@@ -190,14 +190,15 @@ async function submitDraftCreateRequest(input: {
|
||||
});
|
||||
|
||||
const attachmentsArray = Array.isArray(attachments) ? attachments : [];
|
||||
const uploadedImageAttachments = await uploadImageAttachments({ client, images });
|
||||
const mergedAttachments = [...attachmentsArray, ...(uploadedImageAttachments ?? [])];
|
||||
const imagePayload = await prepareImageAttachmentsForSend({ client, images });
|
||||
const mergedAttachments = [...attachmentsArray, ...(imagePayload.attachments ?? [])];
|
||||
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({
|
||||
|
||||
@@ -1889,7 +1889,6 @@ export const ar: TranslationResources = {
|
||||
searchPlaceholder: "نماذج البحث...",
|
||||
openProviderSettings: "افتح إعدادات{{provider}}",
|
||||
searchModelsAndProfilesPlaceholder: "البحث في النماذج والملفات الشخصية...",
|
||||
shownOfTotal: "{{shown}} معروضة من {{total}}",
|
||||
olderModels: "نماذج أقدم ({{count}})",
|
||||
allModels: "كل النماذج ({{count}})",
|
||||
olderTag: "أقدم",
|
||||
|
||||
@@ -1918,7 +1918,6 @@ 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",
|
||||
|
||||
@@ -1939,7 +1939,6 @@ 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",
|
||||
|
||||
@@ -1937,7 +1937,6 @@ 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",
|
||||
|
||||
@@ -1910,7 +1910,6 @@ export const ja: TranslationResources = {
|
||||
searchPlaceholder: "モデルを検索...",
|
||||
openProviderSettings: "{{provider}}の設定を開く",
|
||||
searchModelsAndProfilesPlaceholder: "モデルとプロファイルを検索...",
|
||||
shownOfTotal: "{{total}} 件中 {{shown}} 件を表示",
|
||||
olderModels: "以前のモデル ({{count}})",
|
||||
allModels: "すべてのモデル ({{count}})",
|
||||
olderTag: "以前",
|
||||
|
||||
@@ -1901,7 +1901,6 @@ export const ko: TranslationResources = {
|
||||
searchPlaceholder: "모델 검색...",
|
||||
openProviderSettings: "{{provider}} 설정 열기",
|
||||
searchModelsAndProfilesPlaceholder: "모델 및 프로필 검색...",
|
||||
shownOfTotal: "{{total}}개 중 {{shown}}개 표시",
|
||||
olderModels: "이전 모델 ({{count}})",
|
||||
allModels: "모든 모델 ({{count}})",
|
||||
olderTag: "이전",
|
||||
|
||||
@@ -1923,7 +1923,6 @@ 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",
|
||||
|
||||
@@ -1923,7 +1923,6 @@ export const ru: TranslationResources = {
|
||||
searchPlaceholder: "Поиск моделей...",
|
||||
openProviderSettings: "Открыть настройки {{provider}}",
|
||||
searchModelsAndProfilesPlaceholder: "Поиск моделей и профилей...",
|
||||
shownOfTotal: "Показано {{shown}} из {{total}}",
|
||||
olderModels: "Старые модели ({{count}})",
|
||||
allModels: "Все модели ({{count}})",
|
||||
olderTag: "Старая",
|
||||
|
||||
@@ -1871,7 +1871,6 @@ export const zhCN: TranslationResources = {
|
||||
searchPlaceholder: "搜索模型...",
|
||||
openProviderSettings: "打开 {{provider}} 设置",
|
||||
searchModelsAndProfilesPlaceholder: "搜索模型和配置文件...",
|
||||
shownOfTotal: "显示 {{shown}} / {{total}}",
|
||||
olderModels: "旧模型 ({{count}})",
|
||||
allModels: "所有模型 ({{count}})",
|
||||
olderTag: "旧版",
|
||||
|
||||
@@ -27,8 +27,12 @@ import { StatusBadge } from "@/components/ui/status-badge";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useToast } from "@/contexts/toast-api-context";
|
||||
import { useHostRuntimeClient } from "@/runtime/host-runtime";
|
||||
import { useInstalledPlugin, usePluginEvaluationError } from "@/plugins/registry";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import {
|
||||
useInstalledPlugin,
|
||||
usePluginCatalogStatus,
|
||||
usePluginEvaluationError,
|
||||
} from "@/plugins/registry";
|
||||
import { pluginDisplayName } from "@/plugins/plugin-list";
|
||||
import { PluginSettingsContent } from "@/plugins/settings";
|
||||
import { usePluginActions, type PluginAction } from "./actions";
|
||||
@@ -276,8 +280,6 @@ interface PluginPageModel {
|
||||
error?: string;
|
||||
/** Why the last update failed, while the update is still offered. The installed version keeps running. */
|
||||
updateError?: string;
|
||||
/** The plugin's own settings screen, shown inline. */
|
||||
screenId?: string;
|
||||
overview?: string;
|
||||
}
|
||||
|
||||
@@ -301,12 +303,10 @@ function usePluginPageModel({
|
||||
const directory = usePluginDirectory(serverId);
|
||||
const meta = useListingMeta();
|
||||
const pluginId = plugin?.id ?? "";
|
||||
const installedPlugin = useInstalledPlugin(serverId, pluginId);
|
||||
const evaluationError = usePluginEvaluationError(serverId, pluginId);
|
||||
const pluginOperation = usePluginOperation(serverId, pluginId);
|
||||
const updates = usePluginUpdates(serverId);
|
||||
const text = listing ? listingText(listing, i18n.language) : undefined;
|
||||
const requestedScreen = subject.kind === "installed" ? subject.screenId : undefined;
|
||||
return {
|
||||
name: plugin ? pluginDisplayName(plugin) : (text?.name ?? subjectId(subject)),
|
||||
description: text?.description ?? plugin?.description,
|
||||
@@ -316,11 +316,22 @@ function usePluginPageModel({
|
||||
authorAvatar: listing && listingAuthorAvatar(listing),
|
||||
error: plugin ? (evaluationError ?? plugin.error) : failedError(installOperation),
|
||||
updateError: failedUpdateError(pluginOperation, updates.data, pluginId),
|
||||
screenId: plugin ? (requestedScreen ?? installedPlugin?.settingsScreens[0]?.id) : undefined,
|
||||
overview: detail && listingOverview(detail, i18n.language),
|
||||
};
|
||||
}
|
||||
|
||||
function usePluginPageSettings(
|
||||
serverId: string,
|
||||
subject: PluginPageSubject,
|
||||
plugin: PluginListItem | undefined,
|
||||
) {
|
||||
const pluginId = subject.kind === "installed" ? subject.pluginId : (plugin?.id ?? "");
|
||||
const installedPlugin = useInstalledPlugin(serverId, pluginId);
|
||||
const requestedScreen = subject.kind === "installed" ? subject.screenId : undefined;
|
||||
const screenId = requestedScreen ?? installedPlugin?.settingsScreens[0]?.id;
|
||||
return (plugin || installedPlugin) && screenId ? { pluginId, screenId } : undefined;
|
||||
}
|
||||
|
||||
function subjectId(subject: PluginPageSubject): string {
|
||||
return subject.kind === "listing" ? subject.listingId : subject.pluginId;
|
||||
}
|
||||
@@ -408,6 +419,9 @@ export function PluginPage({
|
||||
const { t } = useTranslation();
|
||||
const compact = useIsCompactFormFactor();
|
||||
const { plugin, listingId, listing, detail, loading } = useResolvedPlugin(serverId, subject);
|
||||
const settings = usePluginPageSettings(serverId, subject, plugin);
|
||||
const catalogStatus = usePluginCatalogStatus(serverId);
|
||||
const connected = useHostRuntimeIsConnected(serverId);
|
||||
const installOperation = usePluginOperation(serverId, listingId);
|
||||
const model = usePluginPageModel({
|
||||
serverId,
|
||||
@@ -436,14 +450,20 @@ export function PluginPage({
|
||||
<SettingsBackLink label={t("settings.plugins.screens.backToPlugins")} onPress={onBack} />
|
||||
</View>
|
||||
);
|
||||
if (loading)
|
||||
const waitingForSettings =
|
||||
subject.kind === "installed" &&
|
||||
!plugin &&
|
||||
!settings &&
|
||||
connected &&
|
||||
catalogStatus === "loading";
|
||||
if (loading || waitingForSettings)
|
||||
return (
|
||||
<View>
|
||||
{back}
|
||||
<PluginPageSkeleton />
|
||||
</View>
|
||||
);
|
||||
if (!plugin && !listing)
|
||||
if (!plugin && !listing && !settings)
|
||||
return (
|
||||
<Alert
|
||||
size="sm"
|
||||
@@ -486,6 +506,7 @@ export function PluginPage({
|
||||
listing={listing}
|
||||
overviewLoading={detail.isLoading}
|
||||
model={model}
|
||||
settings={settings}
|
||||
/>
|
||||
{installTarget ? (
|
||||
<InstallPluginSheet serverId={serverId} target={installTarget} onClose={closeInstall} />
|
||||
@@ -500,12 +521,14 @@ function PluginPageBody({
|
||||
listing,
|
||||
overviewLoading,
|
||||
model,
|
||||
settings,
|
||||
}: {
|
||||
serverId: string;
|
||||
plugin?: PluginListItem;
|
||||
listing?: PluginListing;
|
||||
overviewLoading: boolean;
|
||||
model: PluginPageModel;
|
||||
settings?: { pluginId: string; screenId: string };
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
@@ -523,9 +546,9 @@ function PluginPageBody({
|
||||
</View>
|
||||
) : null}
|
||||
{listing ? <MediaStrip urls={listingImages(listing)} /> : null}
|
||||
{plugin && model.screenId ? (
|
||||
{settings ? (
|
||||
// The plugin's settings screen brings its own sections.
|
||||
<PluginSettingsContent serverId={serverId} pluginId={plugin.id} screenId={model.screenId} />
|
||||
<PluginSettingsContent serverId={serverId} {...settings} />
|
||||
) : null}
|
||||
{model.overview || (listing && overviewLoading) ? (
|
||||
<SettingsSection title={t("settings.plugins.gallery.sections.overview")}>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useAddHost } from "@/hosts/add-host";
|
||||
import type { CreateWorkspaceRequestOptions } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { AgentSnapshotPayload, CreationSnapshot } from "@getpaseo/protocol/messages";
|
||||
import { uploadImageAttachments } from "@/attachments/service";
|
||||
import { prepareImageAttachmentsForSend } from "@/attachments/service";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
@@ -520,13 +520,16 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise<Su
|
||||
const wirePayload = splitComposerAttachmentsForSubmit(attachments, {
|
||||
format: attachmentSubmitFormat,
|
||||
});
|
||||
const uploadedImageAttachments =
|
||||
const imagePayload =
|
||||
wirePayload.images.length > 0
|
||||
? await uploadImageAttachments({ client: input.resolveClient(), images: wirePayload.images })
|
||||
: undefined;
|
||||
? await prepareImageAttachmentsForSend({
|
||||
client: input.resolveClient(),
|
||||
images: wirePayload.images,
|
||||
})
|
||||
: {};
|
||||
const mergedAttachments = [
|
||||
...(wirePayload.attachments ?? []),
|
||||
...(uploadedImageAttachments ?? []),
|
||||
...(imagePayload.attachments ?? []),
|
||||
];
|
||||
let navigated = false;
|
||||
const delivery: { outcome: SubmitOutcome } = { outcome: "background" };
|
||||
@@ -545,6 +548,7 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise<Su
|
||||
...(Object.keys(composerState.metadata).length > 0 ? { metadata: composerState.metadata } : {}),
|
||||
initialPrompt: text,
|
||||
clientMessageId: `${input.draftId}:initial-message`,
|
||||
...(imagePayload.images ? { images: imagePayload.images } : {}),
|
||||
attachments: mergedAttachments.length > 0 ? mergedAttachments : undefined,
|
||||
};
|
||||
const execute = async (): Promise<AgentSnapshotPayload> => {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
* A ratio keeps the step equally visible on every base; a lightness delta disappears near black.
|
||||
* The numbers come from the default themes: Paseo dark and Light.
|
||||
*/
|
||||
import { contrastRatio, mixHexColors, stepContrast } from "@/utils/color";
|
||||
import { contrastRatio, mixHexColors, stepContrast, translucentStep } from "@/utils/color";
|
||||
|
||||
export type ColorScheme = "light" | "dark";
|
||||
|
||||
@@ -19,6 +19,11 @@ const SURFACE_STATE_STEPS = {
|
||||
light: { hover: 1.15, selected: 1.35 },
|
||||
} as const;
|
||||
|
||||
// The 1px line under each open folder in a tree, measured on the sidebar. It starts above the
|
||||
// selected fill so a hovered row does not swallow it. Light needs the larger step to read as the
|
||||
// same weight.
|
||||
const TREE_GUIDE_STEPS = { dark: 1.35, light: 1.47 } as const;
|
||||
|
||||
// Fills for chips, bubbles, tracks and secondary buttons, as `surface3` and `surface4`.
|
||||
const NEUTRAL_FILL_STEPS = {
|
||||
dark: { surface3: 1.8, surface4: 2.5 },
|
||||
@@ -53,6 +58,14 @@ export function deriveSurfaceStates(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Translucent, because trees also sit on the page, workspace panes and sheets. A solid color picked
|
||||
* for the sidebar fades on those.
|
||||
*/
|
||||
export function deriveTreeGuide(sidebar: string, foreground: string, scheme: ColorScheme): string {
|
||||
return translucentStep(sidebar, foreground, TREE_GUIDE_STEPS[scheme]);
|
||||
}
|
||||
|
||||
/** The neutral fills that sit on the page background. */
|
||||
export function deriveNeutralFills(
|
||||
background: string,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { PluginThemeContribution } from "@getpaseo/plugin";
|
||||
import { buildPluginTheme } from "@/plugins/themes";
|
||||
import { contrastRatio } from "@/utils/color";
|
||||
import { contrastRatio, mixHexColors } from "@/utils/color";
|
||||
import { THEME_OPTIONS, type Theme } from "./theme";
|
||||
|
||||
// Palettes of the plugin themes users run into: Catppuccin (the e2e fixture) and
|
||||
@@ -92,10 +92,21 @@ const SELECTED_TEXT_FLOOR = 2.5;
|
||||
const NEUTRAL_FILL_STEP = 1.2;
|
||||
const NEUTRAL_FILL_TEXT_FLOOR = 3;
|
||||
const TERTIARY_TEXT_FLOOR = 2.5;
|
||||
// A tree guide is one quiet line in every theme. Trees also sit on the page, a workspace pane and
|
||||
// a hovered row, and the line has to stay a line on all of them.
|
||||
const TREE_GUIDE_STEP = { dark: 1.35, light: 1.47 };
|
||||
const TREE_GUIDE_FLOOR = 1.18;
|
||||
// The bright hues are dim on a cream or white background by design; the floor only has to catch a
|
||||
// color that disappears.
|
||||
const TERMINAL_COLOR_FLOOR = 1.5;
|
||||
|
||||
/** The color a translucent `rgba()` token shows once painted over `surface`. */
|
||||
function paintedOver(surface: string, token: string): string {
|
||||
const [r, g, b, alpha] = (token.match(/[\d.]+/g) ?? []).map(Number);
|
||||
const ink = `#${[r, g, b].map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
|
||||
return mixHexColors(surface, ink, alpha);
|
||||
}
|
||||
|
||||
it("keeps Solarized Dark's selected workspace timestamp readable", () => {
|
||||
const { colors } = buildPluginTheme(SOLARIZED_DARK);
|
||||
expect(
|
||||
@@ -118,6 +129,22 @@ describe.each(themes)("$name", ({ theme }) => {
|
||||
).toBeGreaterThanOrEqual(SELECTED_OVER_HOVER_STEP);
|
||||
});
|
||||
|
||||
it("draws tree guides at the same strength on the sidebar", () => {
|
||||
const painted = paintedOver(colors.surfaceSidebar, colors.treeGuide);
|
||||
expect(contrastRatio(colors.surfaceSidebar, painted)).toBeCloseTo(
|
||||
TREE_GUIDE_STEP[theme.colorScheme],
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["surfaceSidebarHover", "surface0", "surfaceWorkspace"] as const)(
|
||||
"keeps tree guides visible on %s",
|
||||
(surface) => {
|
||||
const painted = paintedOver(colors[surface], colors.treeGuide);
|
||||
expect(contrastRatio(colors[surface], painted)).toBeGreaterThanOrEqual(TREE_GUIDE_FLOOR);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the selected row's title readable", () => {
|
||||
const onSidebar = contrastRatio(colors.foreground, colors.surfaceSidebar);
|
||||
const onSelected = contrastRatio(colors.foreground, colors.surfaceSidebarSelected);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Platform, type ViewStyle } from "react-native";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { darkHighlightColors, lightHighlightColors } from "@getpaseo/highlight";
|
||||
import { deriveSurfaceStates } from "./derive-colors";
|
||||
import { deriveSurfaceStates, deriveTreeGuide } from "./derive-colors";
|
||||
|
||||
export const baseColors = {
|
||||
// Base colors
|
||||
@@ -276,6 +276,7 @@ export function buildLightSemanticColors(tint: LightThemeConfig) {
|
||||
surfaceSidebarSelected: tint.surfaceSidebarSelected ?? sidebarStates.selected,
|
||||
foregroundSidebarHover: tint.foregroundSidebarHover ?? tint.foregroundExtraMuted,
|
||||
foregroundSidebarSelected: tint.foregroundSidebarSelected ?? tint.foregroundExtraMuted,
|
||||
treeGuide: deriveTreeGuide(tint.surfaceSidebar, tint.foreground, "light"),
|
||||
surfaceWorkspace: tint.surface0,
|
||||
interactionHighlight: "rgba(0, 0, 0, 0.06)",
|
||||
|
||||
@@ -404,6 +405,7 @@ export function buildDarkSemanticColors(tint: DarkThemeConfig) {
|
||||
surfaceSidebarSelected: tint.surfaceSidebarSelected ?? sidebarStates.selected,
|
||||
foregroundSidebarHover: tint.foregroundSidebarHover ?? tint.foregroundExtraMuted,
|
||||
foregroundSidebarSelected: tint.foregroundSidebarSelected ?? tint.foregroundExtraMuted,
|
||||
treeGuide: deriveTreeGuide(tint.surfaceSidebar, foreground, "dark"),
|
||||
surfaceWorkspace: tint.surface1,
|
||||
interactionHighlight: "rgba(255, 255, 255, 0.08)",
|
||||
|
||||
|
||||
@@ -159,6 +159,22 @@ export function stepContrast(hex: string, toward: string, ratio: number): string
|
||||
return `#${channels.join("")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `ink` made translucent enough to sit at `ratio` WCAG contrast from `surface` once painted on it.
|
||||
* Unlike `stepContrast`, the result follows whatever it is painted over, so it keeps its weight on
|
||||
* neighbouring surfaces too.
|
||||
*/
|
||||
export function translucentStep(surface: string, ink: string, ratio: number): string {
|
||||
let low = 0;
|
||||
let high = 1;
|
||||
for (let step = 0; step < 8; step += 1) {
|
||||
const middle = (low + high) / 2;
|
||||
if (contrastRatio(surface, mixHexColors(surface, ink, middle)) < ratio) low = middle;
|
||||
else high = middle;
|
||||
}
|
||||
return hexColorWithAlpha(mixHexColors(ink, ink, 0), Number(high.toFixed(3)));
|
||||
}
|
||||
|
||||
/** Blends `hex` toward `toward` by `amount` (0 keeps `hex`, 1 is `toward`) in sRGB. */
|
||||
export function mixHexColors(hex: string, toward: string, amount: number): string {
|
||||
const from = requireRgb(hex);
|
||||
|
||||
@@ -1,11 +1,147 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
import type {
|
||||
DaemonClient,
|
||||
FetchAgentTimelinePayload,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import {
|
||||
createFollowJsonWriter,
|
||||
createFollowTranscriptWriter,
|
||||
formatAgentActivityTranscript,
|
||||
fetchOneShotTimelineItems,
|
||||
} from "./logs.js";
|
||||
|
||||
function page(seq: number, hasOlder: boolean): FetchAgentTimelinePayload {
|
||||
return {
|
||||
requestId: "request",
|
||||
agentId: "agent",
|
||||
agent: null,
|
||||
direction: "tail",
|
||||
projection: "projected",
|
||||
epoch: "epoch",
|
||||
reset: false,
|
||||
staleCursor: false,
|
||||
gap: false,
|
||||
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
|
||||
startCursor: { epoch: "epoch", seq },
|
||||
endCursor: { epoch: "epoch", seq },
|
||||
hasOlder,
|
||||
hasNewer: false,
|
||||
error: null,
|
||||
entries: [
|
||||
{
|
||||
provider: "codex",
|
||||
item: { type: "user_message", text: `row ${seq}` },
|
||||
timestamp: "2026-01-01T00:00:00Z",
|
||||
seqStart: seq,
|
||||
seqEnd: seq,
|
||||
sourceSeqRanges: [{ startSeq: seq, endSeq: seq }],
|
||||
collapsed: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("one-shot timeline paging", () => {
|
||||
it("retries only oversized pages at the same cursor with a smaller limit", async () => {
|
||||
const requests: Array<Parameters<DaemonClient["fetchAgentTimeline"]>[1]> = [];
|
||||
const client = {
|
||||
async fetchAgentTimeline(
|
||||
_agentId: string,
|
||||
options?: Parameters<DaemonClient["fetchAgentTimeline"]>[1],
|
||||
) {
|
||||
requests.push(options);
|
||||
if (requests.length === 1) return page(3, true);
|
||||
if (requests.length === 2) throw new Error("Logical message too large");
|
||||
return page(1, false);
|
||||
},
|
||||
};
|
||||
expect(await fetchOneShotTimelineItems(client, "agent", undefined, undefined)).toEqual([
|
||||
{ type: "user_message", text: "row 1" },
|
||||
{ type: "user_message", text: "row 3" },
|
||||
]);
|
||||
expect(
|
||||
requests.map((request) => [request?.direction, request?.limit, request?.cursor]),
|
||||
).toEqual([
|
||||
["tail", 200, undefined],
|
||||
["before", 200, { epoch: "epoch", seq: 3 }],
|
||||
["before", 100, { epoch: "epoch", seq: 3 }],
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails promptly if a single-row page is still oversized", async () => {
|
||||
let calls = 0;
|
||||
const client = {
|
||||
async fetchAgentTimeline() {
|
||||
calls++;
|
||||
throw new Error("Logical message too large");
|
||||
},
|
||||
};
|
||||
await expect(fetchOneShotTimelineItems(client, "agent", undefined, 1)).rejects.toThrow(
|
||||
"even at limit 1",
|
||||
);
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it("does not retry other errors", async () => {
|
||||
let calls = 0;
|
||||
const client = {
|
||||
async fetchAgentTimeline() {
|
||||
calls++;
|
||||
throw new Error("disconnected");
|
||||
},
|
||||
};
|
||||
await expect(fetchOneShotTimelineItems(client, "agent", undefined, undefined)).rejects.toThrow(
|
||||
"disconnected",
|
||||
);
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
it.each([
|
||||
["zero", { ...page(2, true), startCursor: { epoch: "epoch", seq: 0 } }],
|
||||
[
|
||||
"unsafe",
|
||||
{ ...page(2, true), startCursor: { epoch: "epoch", seq: Number.MAX_SAFE_INTEGER + 1 } },
|
||||
],
|
||||
["wrong epoch", { ...page(2, true), startCursor: { epoch: "other", seq: 2 } }],
|
||||
["past first row", { ...page(2, true), startCursor: { epoch: "epoch", seq: 3 } }],
|
||||
["missing", { ...page(2, true), startCursor: null }],
|
||||
["reset", { ...page(2, true), reset: true }],
|
||||
["stale", { ...page(2, true), staleCursor: true }],
|
||||
["gap", { ...page(2, true), gap: true }],
|
||||
])("rejects %s on the first page", async (_name, response) => {
|
||||
const client = { fetchAgentTimeline: async () => response };
|
||||
await expect(
|
||||
fetchOneShotTimelineItems(client, "agent", undefined, undefined),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("rejects a repeated cursor and an epoch change", async () => {
|
||||
for (const next of [page(2, true), { ...page(1, false), epoch: "other" }]) {
|
||||
const pages = [page(2, true), next];
|
||||
const client = { fetchAgentTimeline: async () => pages.shift()! };
|
||||
await expect(
|
||||
fetchOneShotTimelineItems(client, "agent", undefined, undefined),
|
||||
).rejects.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps older matches when timestamps are not monotonic", async () => {
|
||||
const newer = {
|
||||
...page(3, true),
|
||||
entries: [{ ...page(3, true).entries[0], timestamp: "2000-01-01T00:00:00Z" }],
|
||||
};
|
||||
const older = {
|
||||
...page(1, false),
|
||||
entries: [{ ...page(1, false).entries[0], timestamp: "2100-01-01T00:00:00Z" }],
|
||||
};
|
||||
const pages = [newer, older];
|
||||
const client = { fetchAgentTimeline: async () => pages.shift()! };
|
||||
expect(
|
||||
await fetchOneShotTimelineItems(client, "agent", Date.parse("2050-01-01"), undefined),
|
||||
).toEqual([{ type: "user_message", text: "row 1" }]);
|
||||
});
|
||||
});
|
||||
|
||||
function collect(items: readonly AgentTimelineItem[], turnId?: string): string {
|
||||
let output = "";
|
||||
const writer = createFollowTranscriptWriter((chunk) => {
|
||||
|
||||
@@ -6,7 +6,11 @@ import {
|
||||
fetchProjectedTimelineItems,
|
||||
LIVE_HISTORY_FETCH_TIMEOUT_MS,
|
||||
} from "../../utils/timeline.js";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type {
|
||||
DaemonClient,
|
||||
FetchAgentTimelineCursor,
|
||||
FetchAgentTimelinePayload,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
import { curateAgentActivity } from "@getpaseo/server/agent-activity";
|
||||
|
||||
@@ -57,6 +61,76 @@ export async function fetchAgentTimelineItems(
|
||||
});
|
||||
}
|
||||
|
||||
function validateTimelinePage(
|
||||
page: FetchAgentTimelinePayload,
|
||||
cursor?: FetchAgentTimelineCursor,
|
||||
): void {
|
||||
const start = page.startCursor;
|
||||
if (
|
||||
(page.hasOlder && !start) ||
|
||||
(start &&
|
||||
(start.epoch !== page.epoch ||
|
||||
!Number.isSafeInteger(start.seq) ||
|
||||
start.seq <= 0 ||
|
||||
(page.entries[0] !== undefined && start.seq > page.entries[0].seqStart) ||
|
||||
(cursor && start.seq >= cursor.seq)))
|
||||
) {
|
||||
throw new Error("Invalid timeline cursor while reading history.");
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchOneShotTimelineItems(
|
||||
client: Pick<DaemonClient, "fetchAgentTimeline">,
|
||||
agentId: string,
|
||||
sinceTimestampMs: number | undefined,
|
||||
tailCount: number | undefined,
|
||||
): Promise<AgentTimelineItem[]> {
|
||||
if (tailCount === 0) return [];
|
||||
const pages: AgentTimelineItem[][] = [];
|
||||
let cursor: FetchAgentTimelineCursor | undefined;
|
||||
let epoch: string | undefined;
|
||||
let count = 0;
|
||||
let pageLimit = 200;
|
||||
for (;;) {
|
||||
const limit = Math.min(pageLimit, tailCount === undefined ? pageLimit : tailCount - count);
|
||||
let page: FetchAgentTimelinePayload;
|
||||
try {
|
||||
page = await client.fetchAgentTimeline(agentId, {
|
||||
direction: cursor ? "before" : "tail",
|
||||
...(cursor ? { cursor } : {}),
|
||||
limit,
|
||||
projection: "projected",
|
||||
});
|
||||
} catch (error) {
|
||||
if (!(error instanceof Error) || error.message !== "Logical message too large") throw error;
|
||||
if (limit === 1)
|
||||
throw new Error("A timeline page exceeds the transport size limit even at limit 1.", {
|
||||
cause: error,
|
||||
});
|
||||
pageLimit = Math.max(1, Math.floor(limit / 2));
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
page.reset ||
|
||||
page.staleCursor ||
|
||||
page.gap ||
|
||||
(epoch !== undefined && page.epoch !== epoch)
|
||||
) {
|
||||
throw new Error("Timeline changed while reading history; retry the command.");
|
||||
}
|
||||
epoch = page.epoch;
|
||||
validateTimelinePage(page, cursor);
|
||||
const entries = page.entries.filter(
|
||||
(entry) => sinceTimestampMs === undefined || Date.parse(entry.timestamp) >= sinceTimestampMs,
|
||||
);
|
||||
pages.push(entries.map((entry) => entry.item));
|
||||
count += entries.length;
|
||||
if (!page.hasOlder || (tailCount !== undefined && count >= tailCount)) break;
|
||||
cursor = page.startCursor ?? undefined;
|
||||
}
|
||||
return pages.toReversed().flat();
|
||||
}
|
||||
|
||||
export function formatAgentActivityTranscript(
|
||||
timelineItems: AgentTimelineItem[],
|
||||
tailCount?: number,
|
||||
@@ -330,16 +404,6 @@ export async function runLogsCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch timeline directly via cursor RPC.
|
||||
let timelineItems = await fetchAgentTimelineItems(client, resolvedId, {
|
||||
sinceTimestampMs,
|
||||
});
|
||||
|
||||
// Apply filter
|
||||
if (options.filter) {
|
||||
timelineItems = timelineItems.filter((item) => matchesFilter(item, options.filter));
|
||||
}
|
||||
|
||||
const tailCount = parseTailCount(options.tail);
|
||||
if (options.tail !== undefined && tailCount === undefined) {
|
||||
console.error(`Error: Invalid --tail value: ${options.tail}`);
|
||||
@@ -348,6 +412,25 @@ export async function runLogsCommand(
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Filtered output must inspect every page: timestamps can be non-monotonic,
|
||||
// and text curation can merge entries after applying a filter.
|
||||
let fetchTailCount = tailCount;
|
||||
if (
|
||||
tailCount !== 0 &&
|
||||
(!usesJsonOutput(options) || options.filter || sinceTimestampMs !== undefined)
|
||||
) {
|
||||
fetchTailCount = undefined;
|
||||
}
|
||||
let timelineItems = await fetchOneShotTimelineItems(
|
||||
client,
|
||||
resolvedId,
|
||||
sinceTimestampMs,
|
||||
fetchTailCount,
|
||||
);
|
||||
if (options.filter) {
|
||||
timelineItems = timelineItems.filter((item) => matchesFilter(item, options.filter));
|
||||
}
|
||||
|
||||
await client.close();
|
||||
|
||||
if (usesJsonOutput(options)) {
|
||||
|
||||
@@ -30,7 +30,8 @@ import { CreationClient } from "./creation/index.js";
|
||||
import type { CreationSnapshot } from "@getpaseo/protocol/messages";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { z } from "zod";
|
||||
import type { SessionEventSubscription } from "@getpaseo/protocol/messages";
|
||||
import type { SessionEventSubscription, WSOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
import type { WirePath } from "@getpaseo/protocol/validation/unknown-variants";
|
||||
import type { LocalSpeechModel } from "@getpaseo/protocol/speech/rpc-schemas";
|
||||
import { CLIENT_CAPS, type ClientCapability } from "@getpaseo/protocol/client-capabilities";
|
||||
import type { AgentAttentionNotificationPayload } from "@getpaseo/protocol/agent-attention-notification";
|
||||
@@ -7749,6 +7750,17 @@ export class DaemonClientCore {
|
||||
}
|
||||
}
|
||||
|
||||
private logSkippedElements(message: WSOutboundMessage, skipped: readonly WirePath[]): void {
|
||||
if (skipped.length === 0) return;
|
||||
this.logger.warn(
|
||||
{
|
||||
msgType: message.type === "session" ? message.message.type : message.type,
|
||||
skipped: skipped.map((path) => path.join(".")),
|
||||
},
|
||||
"Skipped message elements this client does not recognize",
|
||||
);
|
||||
}
|
||||
|
||||
private handleJsonPayload(payload: string, rawBytesLength: number | undefined): void {
|
||||
const bytes = rawBytesLength ?? payload.length;
|
||||
const startMs = perfNow();
|
||||
@@ -7795,6 +7807,7 @@ export class DaemonClientCore {
|
||||
}
|
||||
|
||||
this.consecutiveLivenessFailures = 0;
|
||||
this.logSkippedElements(parsed.data, parsed.skipped);
|
||||
|
||||
if (parsed.data.type === "pong") {
|
||||
this.traceInstant("paseo.ws.message.inbound", {
|
||||
|
||||
@@ -7936,17 +7936,8 @@ test("rejects and logs a correlated response that violates the protocol schema",
|
||||
seqEnd: 1,
|
||||
sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }],
|
||||
collapsed: [],
|
||||
item: {
|
||||
type: "tool_call",
|
||||
callId: "call_cli_invalid",
|
||||
name: "shell",
|
||||
status: "inProgress",
|
||||
detail: {
|
||||
type: "unknown",
|
||||
input: { command: "pwd" },
|
||||
output: null,
|
||||
},
|
||||
},
|
||||
// A known item type missing its required text is a producer bug, not a newer variant.
|
||||
item: { type: "assistant_message" },
|
||||
},
|
||||
],
|
||||
error: null,
|
||||
@@ -7961,6 +7952,87 @@ test("rejects and logs a correlated response that violates the protocol schema",
|
||||
expect(warnings).toEqual(["Message validation failed"]);
|
||||
});
|
||||
|
||||
test("resolves a timeline page from a newer daemon without the entries it does not recognize", async () => {
|
||||
const mock = createMockTransport();
|
||||
const warnings: Array<{ fields: unknown; message: string }> = [];
|
||||
const logger: Logger = {
|
||||
...noopLogger,
|
||||
warn: (fields, message) => warnings.push({ fields, message: message ?? "" }),
|
||||
};
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_unit_test",
|
||||
logger,
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => mock.transport,
|
||||
});
|
||||
clients.push(client);
|
||||
const connectPromise = client.connect();
|
||||
mock.triggerOpen();
|
||||
await connectPromise;
|
||||
|
||||
const entry = (seq: number, item: Record<string, unknown>) => ({
|
||||
timestamp: "2026-11-29T00:00:00.000Z",
|
||||
provider: "codex",
|
||||
seqStart: seq,
|
||||
seqEnd: seq,
|
||||
sourceSeqRanges: [{ startSeq: seq, endSeq: seq }],
|
||||
collapsed: [],
|
||||
item,
|
||||
});
|
||||
const response = client.fetchAgentTimeline("agent_cli", { requestId: "req-newer" });
|
||||
|
||||
mock.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "fetch_agent_timeline_response",
|
||||
payload: {
|
||||
requestId: "req-newer",
|
||||
agentId: "agent_cli",
|
||||
agent: null,
|
||||
direction: "tail",
|
||||
projection: "projected",
|
||||
epoch: "epoch-1",
|
||||
reset: false,
|
||||
staleCursor: false,
|
||||
gap: false,
|
||||
window: { minSeq: 1, maxSeq: 3, nextSeq: 4 },
|
||||
startCursor: { epoch: "epoch-1", seq: 1 },
|
||||
endCursor: { epoch: "epoch-1", seq: 3 },
|
||||
hasOlder: false,
|
||||
hasNewer: false,
|
||||
entries: [
|
||||
entry(1, { type: "assistant_message", text: "Before" }),
|
||||
entry(2, { type: "hologram", frames: 3 }),
|
||||
entry(3, {
|
||||
type: "tool_call",
|
||||
callId: "call-1",
|
||||
name: "shell",
|
||||
status: "inProgress",
|
||||
error: null,
|
||||
detail: { type: "shell", command: "pwd" },
|
||||
}),
|
||||
],
|
||||
error: null,
|
||||
cacheHint: "from a newer daemon",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(response).resolves.toMatchObject({
|
||||
entries: [{ seqStart: 1, item: { type: "assistant_message", text: "Before" } }],
|
||||
});
|
||||
expect((await response).entries).toHaveLength(1);
|
||||
expect(warnings).toEqual([
|
||||
{
|
||||
fields: {
|
||||
msgType: "fetch_agent_timeline_response",
|
||||
skipped: ["message.payload.entries.1", "message.payload.entries.2"],
|
||||
},
|
||||
message: "Skipped message elements this client does not recognize",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("does not reject a request for an invalid correlated progress event", async () => {
|
||||
const mock = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
|
||||
@@ -65,13 +65,13 @@ function validateOutbound(input: unknown): OutboundValidationResult {
|
||||
) {
|
||||
return { success: false, error: { message: "Invalid pong timestamp" } };
|
||||
}
|
||||
return { success: true, data: input as unknown as WSOutboundMessage };
|
||||
return { success: true, data: input as unknown as WSOutboundMessage, skipped: [] };
|
||||
}
|
||||
if (input.type === "hello.rejected") {
|
||||
if (typeof input.reason !== "string" || !HELLO_REJECTED_REASON_SET.has(input.reason)) {
|
||||
return { success: false, error: { message: "Invalid hello.rejected reason" } };
|
||||
}
|
||||
return { success: true, data: input as unknown as WSOutboundMessage };
|
||||
return { success: true, data: input as unknown as WSOutboundMessage, skipped: [] };
|
||||
}
|
||||
if (input.type === "session") {
|
||||
if (!isRecord(input.message) || typeof input.message.type !== "string") {
|
||||
@@ -80,7 +80,7 @@ function validateOutbound(input: unknown): OutboundValidationResult {
|
||||
const normalizedMessage = applySessionOutboundDefaults(input.message);
|
||||
const data =
|
||||
normalizedMessage === input.message ? input : { ...input, message: normalizedMessage };
|
||||
return { success: true, data: data as unknown as WSOutboundMessage };
|
||||
return { success: true, data: data as unknown as WSOutboundMessage, skipped: [] };
|
||||
}
|
||||
return { success: false, error: { message: `Unknown envelope type: ${input.type}` } };
|
||||
}
|
||||
|
||||
@@ -12,9 +12,11 @@ import type {
|
||||
ShutdownRequestedStatusPayloadSchema,
|
||||
WSOutboundMessage,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type { WirePath } from "@getpaseo/protocol/validation/unknown-variants";
|
||||
|
||||
export type OutboundValidationResult =
|
||||
| { success: true; data: WSOutboundMessage }
|
||||
/** `skipped`: paths of list elements dropped because their variant is unknown to this client. */
|
||||
| { success: true; data: WSOutboundMessage; skipped: readonly WirePath[] }
|
||||
| { success: false; error: { message: string } };
|
||||
|
||||
export type AgentCreatedStatusPayload = z.infer<typeof AgentCreatedStatusPayloadSchema>;
|
||||
|
||||
@@ -40,8 +40,8 @@ import { standardToolCallDetail } from "./tool-call-detail.js";
|
||||
import {
|
||||
PROVIDER_PROTOCOL_VERSION,
|
||||
ProviderEventSchema,
|
||||
ProviderInputSchema,
|
||||
negotiateProviderCapabilities,
|
||||
parseProviderInput,
|
||||
requireProviderCapabilities,
|
||||
type ProviderCatalog,
|
||||
type ProviderCapability,
|
||||
@@ -197,7 +197,7 @@ export async function createAcpProviderConnection(
|
||||
capabilities,
|
||||
async send(input) {
|
||||
if (closed) throw new Error("ACP provider connection is closed");
|
||||
input = ProviderInputSchema.parse(input);
|
||||
input = parseProviderInput(input);
|
||||
validateAdmission(input, { capabilities, sessions });
|
||||
if (input.type === "request.cancel") {
|
||||
cancellable.get(input.requestId)?.abort(new Error("Paseo canceled the request"));
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { findStrictObjectPaths } from "@getpaseo/protocol/validation/wire-schema-audit";
|
||||
import {
|
||||
ProviderEventSchema,
|
||||
ProviderInputSchema,
|
||||
negotiateProviderCapabilities,
|
||||
parseProviderEvent,
|
||||
parseProviderInput,
|
||||
requireProviderCapabilities,
|
||||
type ProviderEvent,
|
||||
type ProviderInput,
|
||||
@@ -161,3 +164,111 @@ describe("Provider launch wrap", () => {
|
||||
expect(() => open([] as unknown as [string])).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// A daemon and a plugin are built against different versions of this package. These tests pin
|
||||
// what an older reader does with what a newer peer sends.
|
||||
describe("Provider protocol evolvability", () => {
|
||||
it("has no object that rejects keys a newer peer adds", () => {
|
||||
expect(findStrictObjectPaths(ProviderInputSchema)).toEqual([]);
|
||||
expect(findStrictObjectPaths(ProviderEventSchema)).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts fields a newer Paseo adds to a session open and a prompt", () => {
|
||||
const open = parseProviderInput({
|
||||
type: "session.open",
|
||||
requestId: "open",
|
||||
sessionId: "session-1",
|
||||
history: "skip",
|
||||
config: {
|
||||
cwd: "/workspace",
|
||||
env: {},
|
||||
mcpServers: { docs: { type: "http", url: "https://docs.test", timeoutMs: 5_000 } },
|
||||
toolPolicy: { preapproved: [{ kind: "mcp", server: "docs", tool: "search", note: "x" }] },
|
||||
settings: {},
|
||||
persist: true,
|
||||
sandbox: { network: false },
|
||||
},
|
||||
});
|
||||
const prompt = parseProviderInput({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "message-1",
|
||||
delivery: "auto",
|
||||
priority: "high",
|
||||
input: {
|
||||
type: "message",
|
||||
content: [{ type: "image", data: "aGk=", mimeType: "image/png", altText: "a cat" }],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(open).toMatchObject({ config: { cwd: "/workspace" } });
|
||||
expect(prompt).toEqual({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "message-1",
|
||||
delivery: "auto",
|
||||
input: {
|
||||
type: "message",
|
||||
content: [{ type: "image", data: "aGk=", mimeType: "image/png" }],
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("skips a prompt content block of a kind this plugin does not know", () => {
|
||||
const input = parseProviderInput({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "message-1",
|
||||
delivery: "auto",
|
||||
input: {
|
||||
type: "message",
|
||||
content: [
|
||||
{ type: "text", text: "Look at this" },
|
||||
{ type: "video", url: "file:///clip.mp4" },
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(input).toMatchObject({
|
||||
prompt: { input: { content: [{ type: "text", text: "Look at this" }] } },
|
||||
});
|
||||
});
|
||||
|
||||
it("skips a list element a newer plugin adds and keeps the event", () => {
|
||||
expect(
|
||||
parseProviderEvent({
|
||||
type: "session.commands",
|
||||
sessionId: "session-1",
|
||||
commands: [
|
||||
{ name: "review", description: "Review the diff", kind: "skill" },
|
||||
{ name: "deploy", description: "Deploy", kind: "workflow" },
|
||||
],
|
||||
}),
|
||||
).toEqual({
|
||||
type: "session.commands",
|
||||
sessionId: "session-1",
|
||||
commands: [{ name: "review", description: "Review the diff", kind: "skill" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("drops an event this Paseo does not know instead of failing the connection", () => {
|
||||
expect(parseProviderEvent({ type: "session.hologram", sessionId: "session-1" })).toBeNull();
|
||||
expect(
|
||||
parseProviderEvent({
|
||||
type: "timeline.item",
|
||||
sessionId: "session-1",
|
||||
item: { id: "item-1", type: "hologram", frames: 3 },
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("still rejects a malformed event of a known kind", () => {
|
||||
expect(() => parseProviderEvent({ type: "session.turn", sessionId: "session-1" })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import { z } from "zod";
|
||||
import { safeParseSkippingUnknownVariants } from "@getpaseo/protocol/validation/unknown-variants";
|
||||
|
||||
export const PROVIDER_PROTOCOL_VERSION = 1 as const;
|
||||
|
||||
@@ -889,7 +890,7 @@ const mcpServerSchema = z.discriminatedUnion("type", [
|
||||
env: z.record(z.string(), z.string()).optional(),
|
||||
alwaysLoad: z.boolean().optional(),
|
||||
})
|
||||
.strict(),
|
||||
.strip(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("http"),
|
||||
@@ -897,7 +898,7 @@ const mcpServerSchema = z.discriminatedUnion("type", [
|
||||
headers: z.record(z.string(), z.string()).optional(),
|
||||
alwaysLoad: z.boolean().optional(),
|
||||
})
|
||||
.strict(),
|
||||
.strip(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("sse"),
|
||||
@@ -905,15 +906,15 @@ const mcpServerSchema = z.discriminatedUnion("type", [
|
||||
headers: z.record(z.string(), z.string()).optional(),
|
||||
alwaysLoad: z.boolean().optional(),
|
||||
})
|
||||
.strict(),
|
||||
.strip(),
|
||||
]);
|
||||
const toolPolicySchema = z
|
||||
.object({
|
||||
preapproved: z.array(
|
||||
z.object({ kind: z.literal("mcp"), server: idSchema, tool: idSchema }).strict(),
|
||||
z.object({ kind: z.literal("mcp"), server: idSchema, tool: idSchema }).strip(),
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
.strip();
|
||||
const providerPermissionResponseSchema: z.ZodType<ProviderPermissionResponse> =
|
||||
z.discriminatedUnion("behavior", [
|
||||
z
|
||||
@@ -949,7 +950,7 @@ const sessionConfigSchema = z
|
||||
persist: z.boolean(),
|
||||
wrap: z.tuple([z.string().min(1)], z.string()).optional(),
|
||||
})
|
||||
.strict();
|
||||
.strip();
|
||||
const externalResourceSchema = z
|
||||
.object({
|
||||
provider: z.string(),
|
||||
@@ -970,8 +971,8 @@ const reviewContextLineSchema = z
|
||||
})
|
||||
.strip();
|
||||
const providerContentSchema: z.ZodType<ProviderContent> = z.union([
|
||||
z.object({ type: z.literal("text"), text: z.string() }).strict(),
|
||||
z.object({ type: z.literal("image"), data: z.string(), mimeType: z.string() }).strict(),
|
||||
z.object({ type: z.literal("text"), text: z.string() }).strip(),
|
||||
z.object({ type: z.literal("image"), data: z.string(), mimeType: z.string() }).strip(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("forge_change_request"),
|
||||
@@ -1071,14 +1072,14 @@ const promptSchema = z
|
||||
.object({
|
||||
clientMessageId: idSchema,
|
||||
delivery: z.enum(["auto", "steer"]),
|
||||
input: z.union([
|
||||
z.object({ type: z.literal("message"), content: z.array(providerContentSchema) }).strict(),
|
||||
z.object({ type: z.literal("command"), name: idSchema, arguments: z.string() }).strict(),
|
||||
input: z.discriminatedUnion("type", [
|
||||
z.object({ type: z.literal("message"), content: z.array(providerContentSchema) }).strip(),
|
||||
z.object({ type: z.literal("command"), name: idSchema, arguments: z.string() }).strip(),
|
||||
]),
|
||||
outputSchema: z.json().optional(),
|
||||
clearPendingPermissions: z.boolean().optional(),
|
||||
})
|
||||
.strict();
|
||||
.strip();
|
||||
const configChangesSchema = z
|
||||
.object({
|
||||
model: z.string().nullable().optional(),
|
||||
@@ -1087,12 +1088,10 @@ const configChangesSchema = z
|
||||
providerOptions: jsonObjectSchema.optional(),
|
||||
settings: jsonObjectSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
.strip();
|
||||
|
||||
export const ProviderInputSchema: z.ZodType<ProviderInput> = z.discriminatedUnion("type", [
|
||||
z
|
||||
.object({ type: z.literal("catalog"), requestId: idSchema, cwd: z.string().optional() })
|
||||
.strict(),
|
||||
z.object({ type: z.literal("catalog"), requestId: idSchema, cwd: z.string().optional() }).strip(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("sessions"),
|
||||
@@ -1101,7 +1100,7 @@ export const ProviderInputSchema: z.ZodType<ProviderInput> = z.discriminatedUnio
|
||||
cwd: z.string().optional(),
|
||||
limit: z.number().int().positive().optional(),
|
||||
})
|
||||
.strict(),
|
||||
.strip(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("session.open"),
|
||||
@@ -1111,13 +1110,13 @@ export const ProviderInputSchema: z.ZodType<ProviderInput> = z.discriminatedUnio
|
||||
persistence: persistenceSchema.optional(),
|
||||
history: z.enum(["replay", "skip"]),
|
||||
})
|
||||
.strict(),
|
||||
.strip(),
|
||||
z
|
||||
.object({ type: z.literal("session.prompt"), sessionId: idSchema, prompt: promptSchema })
|
||||
.strict(),
|
||||
.strip(),
|
||||
z
|
||||
.object({ type: z.literal("session.interrupt"), requestId: idSchema, sessionId: idSchema })
|
||||
.strict(),
|
||||
.strip(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("session.permission"),
|
||||
@@ -1125,7 +1124,7 @@ export const ProviderInputSchema: z.ZodType<ProviderInput> = z.discriminatedUnio
|
||||
permissionId: idSchema,
|
||||
response: providerPermissionResponseSchema,
|
||||
})
|
||||
.strict(),
|
||||
.strip(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("session.configure"),
|
||||
@@ -1133,7 +1132,7 @@ export const ProviderInputSchema: z.ZodType<ProviderInput> = z.discriminatedUnio
|
||||
sessionId: idSchema,
|
||||
changes: configChangesSchema,
|
||||
})
|
||||
.strict(),
|
||||
.strip(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("session.revert"),
|
||||
@@ -1142,30 +1141,30 @@ export const ProviderInputSchema: z.ZodType<ProviderInput> = z.discriminatedUnio
|
||||
token: z.json(),
|
||||
scope: z.enum(["conversation", "files", "both"]),
|
||||
})
|
||||
.strict(),
|
||||
.strip(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("session.archive"),
|
||||
requestId: idSchema,
|
||||
persistence: persistenceSchema,
|
||||
})
|
||||
.strict(),
|
||||
.strip(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("session.unarchive"),
|
||||
requestId: idSchema,
|
||||
persistence: persistenceSchema,
|
||||
})
|
||||
.strict(),
|
||||
.strip(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("session.can_stop_runtime"),
|
||||
requestId: idSchema,
|
||||
sessionId: idSchema,
|
||||
})
|
||||
.strict(),
|
||||
z.object({ type: z.literal("session.close"), requestId: idSchema, sessionId: idSchema }).strict(),
|
||||
z.object({ type: z.literal("request.cancel"), requestId: idSchema }).strict(),
|
||||
.strip(),
|
||||
z.object({ type: z.literal("session.close"), requestId: idSchema, sessionId: idSchema }).strip(),
|
||||
z.object({ type: z.literal("request.cancel"), requestId: idSchema }).strip(),
|
||||
]);
|
||||
|
||||
const modeSchema = z
|
||||
@@ -1611,7 +1610,7 @@ export const ProviderEventSchema: z.ZodType<ProviderEvent> = z.discriminatedUnio
|
||||
type: z.literal("session.prompt_result"),
|
||||
sessionId: idSchema,
|
||||
clientMessageId: idSchema,
|
||||
result: z.union([
|
||||
result: z.discriminatedUnion("type", [
|
||||
z.object({ type: z.literal("turn"), turnId: idSchema }).strip(),
|
||||
z.object({ type: z.literal("steer"), turnId: idSchema }).strip(),
|
||||
z.object({ type: z.literal("completed") }).strip(),
|
||||
@@ -1680,3 +1679,25 @@ export const ProviderEventSchema: z.ZodType<ProviderEvent> = z.discriminatedUnio
|
||||
})
|
||||
.strip(),
|
||||
]);
|
||||
|
||||
// The daemon and a plugin are built against different versions of this package, so both readers
|
||||
// ignore keys they do not know and skip list elements of a kind they do not know. New behavior a
|
||||
// reader must not ignore is negotiated through provider capabilities.
|
||||
|
||||
/** Reads input from Paseo. Throws when it is not valid input this plugin understands. */
|
||||
export function parseProviderInput(input: unknown): ProviderInput {
|
||||
const result = safeParseSkippingUnknownVariants(ProviderInputSchema, input);
|
||||
if (!result.success) throw result.error;
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads an event from a provider. Returns `null` for an event of a kind this Paseo does not know,
|
||||
* which the caller drops; throws when the event is malformed.
|
||||
*/
|
||||
export function parseProviderEvent(event: unknown): ProviderEvent | null {
|
||||
const result = safeParseSkippingUnknownVariants(ProviderEventSchema, event);
|
||||
if (result.success) return result.data;
|
||||
if (result.unknownVariant) return null;
|
||||
throw result.error;
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ export const AgentProfileSchema = z
|
||||
export type AgentProfile = z.infer<typeof AgentProfileSchema>;
|
||||
|
||||
export const AgentSkillSelectionSchema = z.discriminatedUnion("mode", [
|
||||
z.object({ mode: z.literal("all") }).strict(),
|
||||
z.object({ mode: z.literal("custom"), skills: z.array(z.string()) }).strict(),
|
||||
z.object({ mode: z.literal("all") }),
|
||||
z.object({ mode: z.literal("custom"), skills: z.array(z.string()) }),
|
||||
]);
|
||||
export type AgentSkillSelection = z.infer<typeof AgentSkillSelectionSchema>;
|
||||
|
||||
@@ -279,15 +279,13 @@ export const BrowserAutomationNewTabResultSchema = z.object({
|
||||
url: z.string().min(1),
|
||||
});
|
||||
|
||||
export const BrowserAutomationSnapshotStatsSchema = z
|
||||
.object({
|
||||
nodeCount: z.number().int().nonnegative(),
|
||||
refCount: z.number().int().nonnegative(),
|
||||
textLength: z.number().int().nonnegative(),
|
||||
iframeCount: z.number().int().nonnegative().optional(),
|
||||
maxDepth: z.number().int().nonnegative().optional(),
|
||||
})
|
||||
.strict();
|
||||
export const BrowserAutomationSnapshotStatsSchema = z.object({
|
||||
nodeCount: z.number().int().nonnegative(),
|
||||
refCount: z.number().int().nonnegative(),
|
||||
textLength: z.number().int().nonnegative(),
|
||||
iframeCount: z.number().int().nonnegative().optional(),
|
||||
maxDepth: z.number().int().nonnegative().optional(),
|
||||
});
|
||||
|
||||
export const BrowserAutomationSnapshotResultSchema = z.object({
|
||||
command: z.literal("snapshot"),
|
||||
|
||||
@@ -47,6 +47,7 @@ describe("network tunnel protocol messages", () => {
|
||||
expect(validateWSOutboundMessage(response)).toEqual({
|
||||
success: true,
|
||||
data: response,
|
||||
skipped: [],
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -317,7 +317,7 @@ describe("plugin protocol compatibility", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("requires plugin action payloads and keeps remove empty", () => {
|
||||
it("requires plugin action payloads and reads remove as its request id only", () => {
|
||||
expect(() =>
|
||||
SessionOutboundMessageSchema.parse({
|
||||
type: "plugin.reload.response",
|
||||
@@ -330,12 +330,12 @@ describe("plugin protocol compatibility", () => {
|
||||
payload: { requestId: "request-2" },
|
||||
}),
|
||||
).toEqual({ type: "plugin.remove.response", payload: { requestId: "request-2" } });
|
||||
expect(() =>
|
||||
expect(
|
||||
SessionOutboundMessageSchema.parse({
|
||||
type: "plugin.remove.response",
|
||||
payload: { requestId: "request-2", plugin: { id: "extra" } },
|
||||
}),
|
||||
).toThrow();
|
||||
).toEqual({ type: "plugin.remove.response", payload: { requestId: "request-2" } });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -290,7 +290,7 @@ export const MutableDaemonConfigSchema = z
|
||||
appendSystemPrompt: z.string().default(""),
|
||||
terminalProfiles: z.array(TerminalProfileSchema).optional(),
|
||||
agentProfiles: z.array(AgentProfileSchema).optional(),
|
||||
skills: z.object({ selection: AgentSkillSelectionSchema.optional() }).strict().optional(),
|
||||
skills: z.object({ selection: AgentSkillSelectionSchema.optional() }).optional(),
|
||||
pluginsEnabled: z.boolean().optional(),
|
||||
plugins: z.record(PluginIdSchema, PluginSourceSchema).optional(),
|
||||
// COMPAT(speechSettings): added in v0.12.0, optional because older daemons omit it.
|
||||
@@ -562,19 +562,15 @@ const McpServerConfigSchema = z.discriminatedUnion("type", [
|
||||
|
||||
const ProviderOptionsSchema = z.record(z.string(), z.unknown());
|
||||
|
||||
const McpToolRefSchema = z
|
||||
.object({
|
||||
kind: z.literal("mcp"),
|
||||
server: z.string().trim().min(1),
|
||||
tool: z.string().trim().min(1),
|
||||
})
|
||||
.strict();
|
||||
const McpToolRefSchema = z.object({
|
||||
kind: z.literal("mcp"),
|
||||
server: z.string().trim().min(1),
|
||||
tool: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
const ToolPolicySchema = z
|
||||
.object({
|
||||
preapproved: z.array(McpToolRefSchema),
|
||||
})
|
||||
.strict();
|
||||
const ToolPolicySchema = z.object({
|
||||
preapproved: z.array(McpToolRefSchema),
|
||||
});
|
||||
|
||||
const AgentSessionConfigSchema = z.object({
|
||||
provider: AgentProviderSchema,
|
||||
@@ -1816,9 +1812,9 @@ export const AgentTimelineAppendRequestSchema = z.object({
|
||||
});
|
||||
|
||||
export const AgentSkillOperationSchema = z.discriminatedUnion("kind", [
|
||||
z.object({ kind: z.literal("add"), name: z.string() }).strict(),
|
||||
z.object({ kind: z.literal("update"), name: z.string() }).strict(),
|
||||
z.object({ kind: z.literal("delete"), name: z.string() }).strict(),
|
||||
z.object({ kind: z.literal("add"), name: z.string() }),
|
||||
z.object({ kind: z.literal("update"), name: z.string() }),
|
||||
z.object({ kind: z.literal("delete"), name: z.string() }),
|
||||
]);
|
||||
export type AgentSkillOperation = z.infer<typeof AgentSkillOperationSchema>;
|
||||
|
||||
@@ -1831,7 +1827,7 @@ export const AgentSkillsStatusSchema = z.object({
|
||||
});
|
||||
export type AgentSkillsStatus = z.infer<typeof AgentSkillsStatusSchema>;
|
||||
|
||||
export const AgentSkillsConfirmationSchema = z.object({ removals: z.array(z.string()) }).strict();
|
||||
export const AgentSkillsConfirmationSchema = z.object({ removals: z.array(z.string()) });
|
||||
export type AgentSkillsConfirmation = z.infer<typeof AgentSkillsConfirmationSchema>;
|
||||
|
||||
export const AgentSkillsSaveResultSchema = AgentSkillsStatusSchema.extend({
|
||||
@@ -1840,7 +1836,7 @@ export const AgentSkillsSaveResultSchema = AgentSkillsStatusSchema.extend({
|
||||
export type AgentSkillsSaveResult = z.infer<typeof AgentSkillsSaveResultSchema>;
|
||||
|
||||
function agentSkillsRequest<const Type extends string>(type: Type) {
|
||||
return z.object({ type: z.literal(type), requestId: z.string() }).strict();
|
||||
return z.object({ type: z.literal(type), requestId: z.string() });
|
||||
}
|
||||
|
||||
export const AgentSkillsGetStatusRequestSchema = agentSkillsRequest(
|
||||
@@ -1852,21 +1848,17 @@ export const AgentSkillsReconcileRequestSchema = agentSkillsRequest(
|
||||
export const AgentSkillsUninstallRequestSchema = agentSkillsRequest(
|
||||
"agent.skills.uninstall.request",
|
||||
);
|
||||
export const AgentSkillsSaveSelectionRequestSchema = z
|
||||
.object({
|
||||
type: z.literal("agent.skills.save_selection.request"),
|
||||
requestId: z.string(),
|
||||
selection: AgentSkillSelectionSchema,
|
||||
confirmedRemovals: z.array(z.string()).optional(),
|
||||
})
|
||||
.strict();
|
||||
export const AgentSkillsImportLegacySelectionRequestSchema = z
|
||||
.object({
|
||||
type: z.literal("agent.skills.import_legacy_selection.request"),
|
||||
requestId: z.string(),
|
||||
selection: AgentSkillSelectionSchema,
|
||||
})
|
||||
.strict();
|
||||
export const AgentSkillsSaveSelectionRequestSchema = z.object({
|
||||
type: z.literal("agent.skills.save_selection.request"),
|
||||
requestId: z.string(),
|
||||
selection: AgentSkillSelectionSchema,
|
||||
confirmedRemovals: z.array(z.string()).optional(),
|
||||
});
|
||||
export const AgentSkillsImportLegacySelectionRequestSchema = z.object({
|
||||
type: z.literal("agent.skills.import_legacy_selection.request"),
|
||||
requestId: z.string(),
|
||||
selection: AgentSkillSelectionSchema,
|
||||
});
|
||||
|
||||
export const GetDaemonConfigRequestMessageSchema = z.object({
|
||||
type: z.literal("get_daemon_config_request"),
|
||||
@@ -4334,6 +4326,10 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
networkTunnel: z.boolean().optional(),
|
||||
// COMPAT(providerShownModels): added in v0.18.1, remove gate after 2027-05-28.
|
||||
providerShownModels: z.boolean().optional(),
|
||||
// COMPAT(uploadedImageAttachments): added in v0.18.2, remove gate after 2027-06-01.
|
||||
// Older hosts strip `role: "image"` from `uploaded_file` attachments and render them
|
||||
// as plain file-path text instead of vision blocks.
|
||||
uploadedImageAttachments: z.boolean().optional(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
@@ -7809,7 +7805,7 @@ export const PluginEnableResponseSchema = pluginActionResponse("plugin.enable.re
|
||||
export const PluginDisableResponseSchema = pluginActionResponse("plugin.disable.response");
|
||||
export const PluginRemoveResponseSchema = z.object({
|
||||
type: z.literal("plugin.remove.response"),
|
||||
payload: z.object({ requestId: z.string() }).strict(),
|
||||
payload: z.object({ requestId: z.string() }),
|
||||
});
|
||||
|
||||
export const PluginRpcInvokeResponseSchema = z.object({
|
||||
|
||||
@@ -7,7 +7,6 @@ export const PaseoServicePortAllocationSchema = z
|
||||
range: z.string().trim().regex(TCP_PORT_RANGE_PATTERN).optional(),
|
||||
portScript: z.string().trim().min(1).optional(),
|
||||
})
|
||||
.strict()
|
||||
.refine(
|
||||
(value) => value.range !== undefined || value.portScript !== undefined,
|
||||
"Expected range or portScript",
|
||||
|
||||
@@ -5,13 +5,11 @@ export const PluginIdSchema = z.string().regex(/^[a-z][a-z0-9-]*$/);
|
||||
export const PluginRequirementsSchema = z.object({ paseo: z.string().optional() });
|
||||
export type PluginRequirements = z.infer<typeof PluginRequirementsSchema>;
|
||||
|
||||
export const DirectoryPluginSourceSchema = z
|
||||
.object({
|
||||
source: z.literal("directory"),
|
||||
path: z.string().min(1),
|
||||
enabled: z.boolean().optional(),
|
||||
})
|
||||
.strict();
|
||||
export const DirectoryPluginSourceSchema = z.object({
|
||||
source: z.literal("directory"),
|
||||
path: z.string().min(1),
|
||||
enabled: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const PluginSourceSchema = z.discriminatedUnion("source", [DirectoryPluginSourceSchema]);
|
||||
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import type { z } from "zod";
|
||||
|
||||
// A newer peer can send a tag or enum value this reader has never seen. Inside a list, that element
|
||||
// is skipped and the rest of the message is kept. Outside a list, the read fails with
|
||||
// `unknownVariant: true`, so the caller can drop that one message instead of treating it as
|
||||
// corrupt. Known variants with missing or mistyped fields still fail.
|
||||
//
|
||||
// Schemas stay closed, so their types stay exhaustive, and the generated validators need no
|
||||
// catch-all branch. This works on issues, so generated validators and Zod behave the same.
|
||||
|
||||
export type WirePath = readonly PropertyKey[];
|
||||
|
||||
export type WireValidationResult<T> =
|
||||
| { success: true; data: T }
|
||||
| { success: false; error: z.ZodError };
|
||||
|
||||
export interface WireValidator<T> {
|
||||
safeParse(input: unknown): WireValidationResult<T>;
|
||||
}
|
||||
|
||||
export type WireReadResult<T> =
|
||||
| { success: true; data: T; skipped: WirePath[] }
|
||||
| { success: false; error: z.ZodError; unknownVariant: boolean };
|
||||
|
||||
export function safeParseSkippingUnknownVariants<T>(
|
||||
validator: WireValidator<T>,
|
||||
input: unknown,
|
||||
): WireReadResult<T> {
|
||||
const first = validator.safeParse(input);
|
||||
if (first.success) return { success: true, data: first.data, skipped: [] };
|
||||
|
||||
// Each issue belongs to its innermost list element, or to the whole value. A unit is an unknown
|
||||
// variant when any of its issues is: a single-tag object reports its missing fields alongside
|
||||
// the tag it did not recognize.
|
||||
const units = new Map<string, { element: WirePath | null; unknownVariant: boolean }>();
|
||||
for (const issue of first.error.issues) {
|
||||
const { element, value } = locate(input, issue.path);
|
||||
const key = element ? JSON.stringify(element.map(String)) : "";
|
||||
const unit = units.get(key) ?? { element, unknownVariant: false };
|
||||
// A missing tag or enum value is a malformed message, not a newer variant.
|
||||
unit.unknownVariant ||= value !== undefined && isUnknownVariant(issue);
|
||||
units.set(key, unit);
|
||||
}
|
||||
|
||||
const unitList = [...units.values()];
|
||||
const unknownVariant = unitList.every((unit) => unit.unknownVariant);
|
||||
const fail = { success: false as const, error: first.error, unknownVariant };
|
||||
if (!unknownVariant) return fail;
|
||||
const elements: WirePath[] = [];
|
||||
for (const unit of unitList) {
|
||||
if (!unit.element) return fail;
|
||||
elements.push(unit.element);
|
||||
}
|
||||
|
||||
const skipped = outermost(elements);
|
||||
// Last-first, so removing one element never shifts the path of another.
|
||||
let pruned = input;
|
||||
for (let index = skipped.length - 1; index >= 0; index -= 1) {
|
||||
pruned = removeAt(pruned, skipped[index], 0);
|
||||
}
|
||||
const retry = validator.safeParse(pruned);
|
||||
return retry.success ? { success: true, data: retry.data, skipped } : fail;
|
||||
}
|
||||
|
||||
function isUnknownVariant(issue: z.core.$ZodIssue): boolean {
|
||||
if (issue.code === "invalid_value") return true;
|
||||
if (issue.code !== "invalid_union" || issue.inclusive === false) return false;
|
||||
// A discriminated union reports an unrecognized tag with no branch errors.
|
||||
if (issue.errors.length === 0) return issue.discriminator !== undefined;
|
||||
// A plain union fails on an unknown tag in every branch.
|
||||
return issue.errors.every((branch) => branch.some(isUnknownVariant));
|
||||
}
|
||||
|
||||
// The value at `path`, and the path of the innermost array element that contains it, if any.
|
||||
function locate(
|
||||
input: unknown,
|
||||
path: readonly PropertyKey[],
|
||||
): { element: WirePath | null; value: unknown } {
|
||||
let element: WirePath | null = null;
|
||||
let value = input;
|
||||
for (let depth = 0; depth < path.length; depth += 1) {
|
||||
const segment = path[depth];
|
||||
if (Array.isArray(value) && typeof segment === "number") {
|
||||
element = path.slice(0, depth + 1);
|
||||
}
|
||||
if (value === null || typeof value !== "object") return { element, value: undefined };
|
||||
value = (value as Record<PropertyKey, unknown>)[segment as PropertyKey];
|
||||
}
|
||||
return { element, value };
|
||||
}
|
||||
|
||||
function isPrefix(prefix: WirePath, path: WirePath): boolean {
|
||||
return prefix.length <= path.length && prefix.every((segment, index) => segment === path[index]);
|
||||
}
|
||||
|
||||
function comparePaths(a: WirePath, b: WirePath): number {
|
||||
for (let index = 0; index < Math.min(a.length, b.length); index += 1) {
|
||||
const left = a[index];
|
||||
const right = b[index];
|
||||
if (left === right) continue;
|
||||
if (typeof left === "number" && typeof right === "number") return left - right;
|
||||
return String(left) < String(right) ? -1 : 1;
|
||||
}
|
||||
return a.length - b.length;
|
||||
}
|
||||
|
||||
// Unique element paths, dropping any inside another skipped element, in document order.
|
||||
function outermost(elements: WirePath[]): WirePath[] {
|
||||
const sorted = [...elements].sort(comparePaths);
|
||||
const kept: WirePath[] = [];
|
||||
for (const element of sorted) {
|
||||
const previous = kept[kept.length - 1];
|
||||
if (!previous || !isPrefix(previous, element)) kept.push(element);
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
// Removes one array element, copying only the containers along its path.
|
||||
function removeAt(value: unknown, path: WirePath, depth: number): unknown {
|
||||
const segment = path[depth];
|
||||
if (Array.isArray(value)) {
|
||||
const position = segment as number;
|
||||
if (depth === path.length - 1) {
|
||||
return [...value.slice(0, position), ...value.slice(position + 1)];
|
||||
}
|
||||
const copy = [...value];
|
||||
copy[position] = removeAt(value[position], path, depth + 1);
|
||||
return copy;
|
||||
}
|
||||
const record = value as Record<PropertyKey, unknown>;
|
||||
return {
|
||||
...record,
|
||||
[segment as PropertyKey]: removeAt(record[segment as PropertyKey], path, depth + 1),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { z } from "zod";
|
||||
|
||||
// Wire readers must ignore keys a newer peer adds. Contract tests run this over every schema that
|
||||
// parses data from another process and expect an empty list. Local files that should reject typos
|
||||
// are not wire schemas and are not audited.
|
||||
|
||||
type SchemaDef = z.core.$ZodTypeDef & Record<string, unknown>;
|
||||
|
||||
function defOf(schema: unknown): SchemaDef {
|
||||
return (schema as z.core.$ZodType)._zod.def as SchemaDef;
|
||||
}
|
||||
|
||||
// Names a union branch by its literal tag so a failing audit points at a message, not an index.
|
||||
function optionTag(option: unknown, discriminator: unknown): string | undefined {
|
||||
const def = defOf(option);
|
||||
if (def.type !== "object") return undefined;
|
||||
const key = typeof discriminator === "string" ? discriminator : "type";
|
||||
const tag = (def.shape as Record<string, unknown>)[key];
|
||||
if (!tag) return undefined;
|
||||
const tagDef = defOf(tag);
|
||||
return tagDef.type === "literal" ? (tagDef.values as unknown[]).join(",") : undefined;
|
||||
}
|
||||
|
||||
// Wrappers whose one child is `def.innerType`.
|
||||
const WRAPPER_TYPES = new Set([
|
||||
"optional",
|
||||
"nullable",
|
||||
"default",
|
||||
"prefault",
|
||||
"nonoptional",
|
||||
"readonly",
|
||||
"catch",
|
||||
"success",
|
||||
"promise",
|
||||
]);
|
||||
|
||||
function childrenOf(def: SchemaDef): Array<[string, unknown]> {
|
||||
if (WRAPPER_TYPES.has(def.type)) return [["", def.innerType]];
|
||||
switch (def.type) {
|
||||
case "object":
|
||||
return Object.entries(def.shape as Record<string, unknown>).map(([key, child]) => [
|
||||
`.${key}`,
|
||||
child,
|
||||
]);
|
||||
case "array":
|
||||
case "set":
|
||||
return [["[]", def.element ?? def.valueType]];
|
||||
case "union":
|
||||
return (def.options as unknown[]).map((option, index) => [
|
||||
`|${optionTag(option, def.discriminator) ?? index}`,
|
||||
option,
|
||||
]);
|
||||
case "intersection":
|
||||
return [
|
||||
["&left", def.left],
|
||||
["&right", def.right],
|
||||
];
|
||||
case "tuple":
|
||||
return [
|
||||
...(def.items as unknown[]).map((item, index): [string, unknown] => [`[${index}]`, item]),
|
||||
...(def.rest ? [["[...]", def.rest] as [string, unknown]] : []),
|
||||
];
|
||||
case "record":
|
||||
case "map":
|
||||
return [
|
||||
["{key}", def.keyType],
|
||||
["{value}", def.valueType],
|
||||
];
|
||||
case "pipe":
|
||||
return [
|
||||
["<in>", def.in],
|
||||
["<out>", def.out],
|
||||
];
|
||||
case "lazy":
|
||||
return [["", (def.getter as () => unknown)()]];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Paths of every object in `schema` that rejects unknown keys (`.strict()` / `z.strictObject`). */
|
||||
export function findStrictObjectPaths(schema: z.ZodType): string[] {
|
||||
const strict: string[] = [];
|
||||
const visited = new Set<unknown>();
|
||||
const visit = (node: unknown, path: string): void => {
|
||||
if (visited.has(node)) return;
|
||||
visited.add(node);
|
||||
const def = defOf(node);
|
||||
if (def.type === "object" && def.catchall && defOf(def.catchall).type === "never") {
|
||||
strict.push(path || "<root>");
|
||||
}
|
||||
for (const [segment, child] of childrenOf(def)) {
|
||||
visit(child, `${path}${segment}`);
|
||||
}
|
||||
};
|
||||
visit(schema, "");
|
||||
return strict;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
WSOutboundEnvelope,
|
||||
} from "../generated/validation/ws-outbound.aot.js";
|
||||
import type { SessionOutboundMessage, WSOutboundMessage } from "../messages.js";
|
||||
import { safeParseSkippingUnknownVariants, type WireReadResult } from "./unknown-variants.js";
|
||||
|
||||
type ValidationResult<T> = { success: true; data: T } | { success: false; error: z.ZodError };
|
||||
|
||||
@@ -36,7 +37,15 @@ function underMessage(issue: z.core.$ZodIssue): z.core.$ZodIssue {
|
||||
}
|
||||
}
|
||||
|
||||
export function validateWSOutboundMessage(input: unknown): ValidationResult<WSOutboundMessage> {
|
||||
/**
|
||||
* Validates one daemon message. List elements with a variant this client does not know are
|
||||
* skipped and reported in `skipped`; see `unknown-variants.ts`.
|
||||
*/
|
||||
export function validateWSOutboundMessage(input: unknown): WireReadResult<WSOutboundMessage> {
|
||||
return safeParseSkippingUnknownVariants({ safeParse: validateExactly }, input);
|
||||
}
|
||||
|
||||
function validateExactly(input: unknown): ValidationResult<WSOutboundMessage> {
|
||||
const envelope = envelopeValidator.safeParse(input);
|
||||
if (!envelope.success || envelope.data.type !== "session") {
|
||||
return envelope;
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
SessionInboundMessageSchema,
|
||||
WSInboundMessageSchema,
|
||||
WSOutboundMessageSchema,
|
||||
} from "../../src/messages.js";
|
||||
import { PaseoConfigRawSchema } from "../../src/paseo-config-schema.js";
|
||||
import { findStrictObjectPaths } from "../../src/validation/wire-schema-audit.js";
|
||||
import { safeParseSkippingUnknownVariants } from "../../src/validation/unknown-variants.js";
|
||||
import { validateWSOutboundMessage } from "../../src/validation/ws-outbound.js";
|
||||
|
||||
// A newer peer adds fields and variants. These tests pin what an older reader does with them:
|
||||
// unknown keys are ignored, and a list element whose variant it does not know is skipped
|
||||
// without losing the rest of the message.
|
||||
|
||||
function session(message: Record<string, unknown>) {
|
||||
return { type: "session", message };
|
||||
}
|
||||
|
||||
function timelineEntry(seq: number, item: Record<string, unknown>) {
|
||||
return {
|
||||
provider: "claude",
|
||||
item,
|
||||
timestamp: "2026-11-29T00:00:00.000Z",
|
||||
seqStart: seq,
|
||||
seqEnd: seq,
|
||||
sourceSeqRanges: [{ startSeq: seq, endSeq: seq }],
|
||||
collapsed: [],
|
||||
};
|
||||
}
|
||||
|
||||
function timelinePage(entries: unknown[]) {
|
||||
return session({
|
||||
type: "fetch_agent_timeline_response",
|
||||
payload: {
|
||||
requestId: "request-1",
|
||||
agentId: "agent-1",
|
||||
agent: null,
|
||||
direction: "tail",
|
||||
projection: "projected",
|
||||
epoch: "epoch-1",
|
||||
reset: false,
|
||||
staleCursor: false,
|
||||
gap: false,
|
||||
window: { minSeq: 1, maxSeq: 3, nextSeq: 4 },
|
||||
startCursor: null,
|
||||
endCursor: null,
|
||||
hasOlder: false,
|
||||
hasNewer: false,
|
||||
entries,
|
||||
error: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const assistantEntry = timelineEntry(1, { type: "assistant_message", text: "Before" });
|
||||
const futureEntry = timelineEntry(2, { type: "hologram", frames: 3 });
|
||||
const laterEntry = timelineEntry(3, { type: "assistant_message", text: "After" });
|
||||
|
||||
function entriesOf(result: ReturnType<typeof validateWSOutboundMessage>): unknown {
|
||||
if (!result.success || result.data.type !== "session") return result;
|
||||
const message = result.data.message;
|
||||
return message.type === "fetch_agent_timeline_response" ? message.payload.entries : message;
|
||||
}
|
||||
|
||||
function skillsStatus(op: Record<string, unknown>) {
|
||||
return session({
|
||||
type: "agent.skills.get_status.response",
|
||||
payload: {
|
||||
requestId: "request-1",
|
||||
state: "drift",
|
||||
ops: [op],
|
||||
available: ["review"],
|
||||
installed: [],
|
||||
selection: { mode: "all" },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Browser automation requests are agent-issued tab operations. They stay strict so a request that
|
||||
// names its tab or workspace in the legacy place fails instead of running against the wrong tab.
|
||||
// New commands are gated by the host's advertised `supportedCommands`.
|
||||
const BROWSER_AUTOMATION_REQUEST = "|session.message|browser.automation.execute.request";
|
||||
|
||||
describe("wire schemas never reject unknown keys", () => {
|
||||
it("has no strict object in any app↔daemon message", () => {
|
||||
const outbound = findStrictObjectPaths(WSOutboundMessageSchema);
|
||||
expect(outbound.filter((path) => !path.startsWith(BROWSER_AUTOMATION_REQUEST))).toEqual([]);
|
||||
expect(findStrictObjectPaths(WSInboundMessageSchema)).toEqual([]);
|
||||
expect(findStrictObjectPaths(PaseoConfigRawSchema)).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts a field added by a newer daemon in the generated client validator and in Zod", () => {
|
||||
const envelope = skillsStatus({ kind: "add", name: "review", reason: "new upstream skill" });
|
||||
|
||||
expect(validateWSOutboundMessage(envelope).success).toBe(true);
|
||||
expect(WSOutboundMessageSchema.safeParse(envelope).success).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts a field added by a newer app on a daemon request", () => {
|
||||
const request = {
|
||||
type: "agent.skills.save_selection.request",
|
||||
requestId: "request-1",
|
||||
selection: { mode: "custom", skills: ["review"], pinned: true },
|
||||
source: "settings",
|
||||
};
|
||||
|
||||
expect(SessionInboundMessageSchema.safeParse(request).success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("unknown list variants degrade to one skipped element", () => {
|
||||
it("keeps a timeline page when one entry has an unknown item type", () => {
|
||||
const result = validateWSOutboundMessage(
|
||||
timelinePage([assistantEntry, futureEntry, laterEntry]),
|
||||
);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(entriesOf(result)).toEqual([assistantEntry, laterEntry]);
|
||||
});
|
||||
|
||||
it("keeps a timeline page when a tool call carries an unknown detail type", () => {
|
||||
const toolCall = timelineEntry(2, {
|
||||
type: "tool_call",
|
||||
callId: "call-1",
|
||||
name: "teleport",
|
||||
status: "running",
|
||||
error: null,
|
||||
detail: { type: "teleport", destination: "mars" },
|
||||
});
|
||||
|
||||
const result = validateWSOutboundMessage(timelinePage([assistantEntry, toolCall, laterEntry]));
|
||||
|
||||
expect(entriesOf(result)).toEqual([assistantEntry, laterEntry]);
|
||||
});
|
||||
|
||||
it("skips an unknown enum value inside a list", () => {
|
||||
const merged = { ...assistantEntry, collapsed: ["assistant_merge", "hologram_merge"] };
|
||||
|
||||
const result = validateWSOutboundMessage(timelinePage([merged]));
|
||||
|
||||
expect(entriesOf(result)).toEqual([{ ...assistantEntry, collapsed: ["assistant_merge"] }]);
|
||||
});
|
||||
|
||||
it("skips an unknown skill operation and keeps the status response", () => {
|
||||
const result = validateWSOutboundMessage(skillsStatus({ kind: "rename", name: "review" }));
|
||||
|
||||
expect(result).toMatchObject({
|
||||
success: true,
|
||||
data: { message: { payload: { ops: [], state: "drift" } } },
|
||||
});
|
||||
});
|
||||
|
||||
it("matches the generated validator when reading with Zod", () => {
|
||||
const envelope = timelinePage([assistantEntry, futureEntry, laterEntry]);
|
||||
|
||||
const generated = validateWSOutboundMessage(envelope);
|
||||
const zod = safeParseSkippingUnknownVariants(WSOutboundMessageSchema, envelope);
|
||||
|
||||
expect(zod.success).toBe(true);
|
||||
expect(zod.success && zod.data).toEqual(generated.success && generated.data);
|
||||
expect(zod.success && zod.skipped).toEqual([["message", "payload", "entries", 1]]);
|
||||
});
|
||||
|
||||
it("does not mutate the message it reads", () => {
|
||||
const envelope = timelinePage([assistantEntry, futureEntry, laterEntry]);
|
||||
const snapshot = structuredClone(envelope);
|
||||
|
||||
validateWSOutboundMessage(envelope);
|
||||
|
||||
expect(envelope).toEqual(snapshot);
|
||||
});
|
||||
|
||||
it("skips an unknown tool pre-approval on a daemon request", () => {
|
||||
const request = {
|
||||
type: "create_agent_request",
|
||||
requestId: "request-1",
|
||||
config: {
|
||||
provider: "claude",
|
||||
cwd: "/workspace",
|
||||
toolPolicy: {
|
||||
preapproved: [
|
||||
{ kind: "mcp", server: "paseo", tool: "list_agents" },
|
||||
{ kind: "plugin_tool", plugin: "jira", tool: "search" },
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const result = safeParseSkippingUnknownVariants(SessionInboundMessageSchema, request);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
success: true,
|
||||
data: {
|
||||
config: {
|
||||
toolPolicy: { preapproved: [{ kind: "mcp", server: "paseo", tool: "list_agents" }] },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("what still fails", () => {
|
||||
it("rejects a known item that is missing a required field", () => {
|
||||
const broken = timelineEntry(2, { type: "assistant_message" });
|
||||
|
||||
expect(validateWSOutboundMessage(timelinePage([assistantEntry, broken])).success).toBe(false);
|
||||
});
|
||||
|
||||
it("reports an unknown variant outside any list so the reader can drop that one message", () => {
|
||||
const envelope = session({
|
||||
type: "agent_stream",
|
||||
payload: {
|
||||
agentId: "agent-1",
|
||||
timestamp: "2026-11-29T00:00:00.000Z",
|
||||
event: { type: "hologram_started", provider: "claude" },
|
||||
},
|
||||
});
|
||||
|
||||
const generated = validateWSOutboundMessage(envelope);
|
||||
const zod = safeParseSkippingUnknownVariants(WSOutboundMessageSchema, envelope);
|
||||
|
||||
expect(generated).toMatchObject({ success: false, unknownVariant: true });
|
||||
expect(zod).toMatchObject({ success: false, unknownVariant: true });
|
||||
});
|
||||
|
||||
it("does not report a malformed known message as an unknown variant", () => {
|
||||
const envelope = session({
|
||||
type: "agent_stream",
|
||||
payload: { agentId: "agent-1", timestamp: "now", event: { type: "turn_started" } },
|
||||
});
|
||||
|
||||
expect(validateWSOutboundMessage(envelope)).toMatchObject({
|
||||
success: false,
|
||||
unknownVariant: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -198,6 +198,7 @@ const SourceSchema = z.object({
|
||||
expect(validateWSOutboundMessage(envelope)).toEqual({
|
||||
success: true,
|
||||
data: envelope,
|
||||
skipped: [],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -257,6 +258,7 @@ const SourceSchema = z.object({
|
||||
expect(validateWSOutboundMessage(envelope)).toEqual({
|
||||
success: true,
|
||||
data: envelope,
|
||||
skipped: [],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -312,8 +314,16 @@ const SourceSchema = z.object({
|
||||
},
|
||||
};
|
||||
|
||||
expect(validateWSOutboundMessage(completed)).toEqual({ success: true, data: completed });
|
||||
expect(validateWSOutboundMessage(timeline)).toEqual({ success: true, data: timeline });
|
||||
expect(validateWSOutboundMessage(completed)).toEqual({
|
||||
success: true,
|
||||
data: completed,
|
||||
skipped: [],
|
||||
});
|
||||
expect(validateWSOutboundMessage(timeline)).toEqual({
|
||||
success: true,
|
||||
data: timeline,
|
||||
skipped: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("emits runtime imports with .js extensions", async () => {
|
||||
@@ -451,7 +461,7 @@ const SourceSchema = z.object({
|
||||
const expected = WSOutboundMessageSchema.safeParse(envelope);
|
||||
|
||||
expect(expected.success).toBe(true);
|
||||
expect(result).toEqual(expected);
|
||||
expect(result).toEqual({ ...expected, skipped: [] });
|
||||
expect(result.success && result.data).toMatchObject({
|
||||
message: { payload: { agent: { capabilities: { supportsRewindConversation: false } } } },
|
||||
});
|
||||
|
||||
@@ -73,7 +73,7 @@ import {
|
||||
type ListImportableSessionsOptions,
|
||||
} from "./agent-sdk-types.js";
|
||||
import { buildArchivedAgentRecord, type ArchivedStoredAgentRecord } from "./agent-archive.js";
|
||||
import type { JsonValue, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import type { JsonValue, ProviderOptions, UploadedImage } from "@getpaseo/protocol/agent-types";
|
||||
import { toStoredAgentRecord } from "./agent-projections.js";
|
||||
import { sanitizeAgentMetrics, withModelMetric } from "./agent-metrics.js";
|
||||
import {
|
||||
@@ -168,17 +168,6 @@ function submittedPromptText(prompt: AgentPromptInput): string {
|
||||
.trim();
|
||||
}
|
||||
|
||||
function submittedPromptImages(
|
||||
prompt: AgentPromptInput,
|
||||
): import("@getpaseo/protocol/agent-types").UploadedImage[] {
|
||||
if (typeof prompt === "string") {
|
||||
return [];
|
||||
}
|
||||
return prompt.flatMap((block) =>
|
||||
block.type === "image" && block.uploadedImage ? [block.uploadedImage] : [],
|
||||
);
|
||||
}
|
||||
|
||||
export class AgentManagerShuttingDownError extends Error {
|
||||
constructor() {
|
||||
super("Agent manager is shutting down");
|
||||
@@ -463,12 +452,36 @@ export type ActiveTurnSteerDispatchResult =
|
||||
| { status: "inactive" | "steered" }
|
||||
| { status: "replaced"; iterator: AsyncGenerator<AgentStreamEvent> };
|
||||
|
||||
function stripSteerOptions(options?: AgentSteerOptions): AgentRunOptions | undefined {
|
||||
export interface AgentPromptSubmissionOptions extends AgentRunOptions {
|
||||
/** Daemon timeline metadata for uploaded image attachments; never forwarded to providers. */
|
||||
uploadedImages?: readonly UploadedImage[];
|
||||
}
|
||||
|
||||
export interface AgentPromptSteerOptions extends AgentSteerOptions {
|
||||
/** Daemon timeline metadata for uploaded image attachments; never forwarded to providers. */
|
||||
uploadedImages?: readonly UploadedImage[];
|
||||
}
|
||||
|
||||
function stripSteerOptions(
|
||||
options?: AgentPromptSteerOptions,
|
||||
): AgentPromptSubmissionOptions | undefined {
|
||||
if (!options) return undefined;
|
||||
const { clearPendingPermissions: _, ...runOptions } = options;
|
||||
return runOptions;
|
||||
}
|
||||
|
||||
function toProviderRunOptions(options?: AgentPromptSubmissionOptions): AgentRunOptions | undefined {
|
||||
if (!options) return undefined;
|
||||
const { uploadedImages: _, ...providerOptions } = options;
|
||||
return providerOptions;
|
||||
}
|
||||
|
||||
function toProviderSteerOptions(options?: AgentPromptSteerOptions): AgentSteerOptions | undefined {
|
||||
if (!options) return undefined;
|
||||
const { uploadedImages: _, ...providerOptions } = options;
|
||||
return providerOptions;
|
||||
}
|
||||
|
||||
export interface WaitForAgentOptions {
|
||||
signal?: AbortSignal;
|
||||
waitForActive?: boolean;
|
||||
@@ -3308,7 +3321,7 @@ export class AgentManager {
|
||||
async runAgent(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
options?: AgentPromptSubmissionOptions,
|
||||
): Promise<AgentRunResult> {
|
||||
try {
|
||||
return await this.runAgentOnce(agentId, prompt, options);
|
||||
@@ -3328,7 +3341,7 @@ export class AgentManager {
|
||||
private async runAgentOnce(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
options?: AgentPromptSubmissionOptions,
|
||||
): Promise<AgentRunResult> {
|
||||
const events = this.streamAgent(agentId, prompt, options);
|
||||
const timeline: AgentTimelineItem[] = [];
|
||||
@@ -3374,7 +3387,7 @@ export class AgentManager {
|
||||
async tryRunOutOfBand(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
options?: AgentPromptSubmissionOptions,
|
||||
onAccepted?: () => void,
|
||||
): Promise<boolean> {
|
||||
const agent = await this.findOutOfBandRecipient(agentId);
|
||||
@@ -3391,7 +3404,9 @@ export class AgentManager {
|
||||
onAccepted?.();
|
||||
this.touchUpdatedAt(agent);
|
||||
if (options?.clientMessageId) {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted");
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted", {
|
||||
uploadedImages: options.uploadedImages,
|
||||
});
|
||||
this.emitState(agent);
|
||||
}
|
||||
const dispatch = (event: AgentStreamEvent): void => {
|
||||
@@ -3489,7 +3504,7 @@ export class AgentManager {
|
||||
agentId: string;
|
||||
pendingRun: PendingForegroundRun;
|
||||
prompt: AgentPromptInput;
|
||||
options?: AgentRunOptions;
|
||||
options?: AgentPromptSubmissionOptions;
|
||||
promptStart?: ForegroundPromptStart;
|
||||
}): Promise<string | null> {
|
||||
const { agent, agentId, pendingRun, prompt, options, promptStart } = params;
|
||||
@@ -3498,7 +3513,7 @@ export class AgentManager {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const result = await agent.session.startTurn(prompt, options);
|
||||
const result = await agent.session.startTurn(prompt, toProviderRunOptions(options));
|
||||
if (pendingRun.settled) {
|
||||
throw new Error(`Agent ${agentId} run was canceled before its turn started`);
|
||||
}
|
||||
@@ -3509,6 +3524,7 @@ export class AgentManager {
|
||||
if (options?.clientMessageId) {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", {
|
||||
messageId: options.clientMessageId,
|
||||
uploadedImages: options.uploadedImages,
|
||||
});
|
||||
}
|
||||
await this.handleStreamEvent(agent, {
|
||||
@@ -3543,6 +3559,7 @@ export class AgentManager {
|
||||
if (options?.clientMessageId) {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "rejected", {
|
||||
messageId: options.clientMessageId,
|
||||
uploadedImages: options.uploadedImages,
|
||||
});
|
||||
}
|
||||
await this.handleStreamEvent(agent, {
|
||||
@@ -3620,7 +3637,7 @@ export class AgentManager {
|
||||
private async *streamAfterHistoryLoad(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
options?: AgentPromptSubmissionOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): AsyncGenerator<AgentStreamEvent> {
|
||||
await this.ensureInteractiveSession(agentId);
|
||||
@@ -3630,7 +3647,7 @@ export class AgentManager {
|
||||
private async *streamAfterRuntimeCollection(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
options?: AgentPromptSubmissionOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): AsyncGenerator<AgentStreamEvent> {
|
||||
await this.waitForAgentClose(agentId);
|
||||
@@ -3645,7 +3662,7 @@ export class AgentManager {
|
||||
streamAgent(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
options?: AgentPromptSubmissionOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): AsyncGenerator<AgentStreamEvent> {
|
||||
if (this.collectingRuntimes.has(agentId) || (!this.agents.has(agentId) && this.registry))
|
||||
@@ -3740,6 +3757,7 @@ export class AgentManager {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted", {
|
||||
messageId: options.clientMessageId,
|
||||
turnId,
|
||||
uploadedImages: options.uploadedImages,
|
||||
providerMessageId:
|
||||
stagedSubmittedPromptEcho?.item.type === "user_message"
|
||||
? stagedSubmittedPromptEcho.item.messageId
|
||||
@@ -3862,7 +3880,7 @@ export class AgentManager {
|
||||
async replaceAgentRun(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
options?: AgentPromptSubmissionOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
this.requireSessionAgent(agentId);
|
||||
@@ -3872,7 +3890,7 @@ export class AgentManager {
|
||||
async steerAgentRun(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentSteerOptions,
|
||||
options?: AgentPromptSteerOptions,
|
||||
): Promise<SteerResult> {
|
||||
const agent = this.requireSessionAgent(agentId);
|
||||
const expectedTurnId = agent.activeForegroundTurnId ?? agent.activeTurnId;
|
||||
@@ -3881,7 +3899,7 @@ export class AgentManager {
|
||||
}
|
||||
const result = await this.runSteerAdmission(agent, expectedTurnId, async () => {
|
||||
const admission = await agent.session.steerActiveTurn!(prompt, {
|
||||
...options,
|
||||
...toProviderSteerOptions(options),
|
||||
expectedTurnId,
|
||||
});
|
||||
if (admission.status === "accepted") {
|
||||
@@ -3891,6 +3909,7 @@ export class AgentManager {
|
||||
options?.clientMessageId,
|
||||
expectedTurnId,
|
||||
admission.providerMessageId,
|
||||
options?.uploadedImages,
|
||||
);
|
||||
}
|
||||
return admission;
|
||||
@@ -3906,7 +3925,7 @@ export class AgentManager {
|
||||
async steerOrReplaceActiveTurn(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentSteerOptions,
|
||||
options?: AgentPromptSteerOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): Promise<ActiveTurnSteerDispatchResult> {
|
||||
// A turn that is still starting has no id to steer yet. Replacing it would drop its
|
||||
@@ -3921,7 +3940,7 @@ export class AgentManager {
|
||||
const result = agent.session.steerActiveTurn
|
||||
? await this.runSteerAdmission(agent, expectedTurnId, async () => {
|
||||
const admission = await agent.session.steerActiveTurn!(prompt, {
|
||||
...options,
|
||||
...toProviderSteerOptions(options),
|
||||
expectedTurnId,
|
||||
});
|
||||
if (admission.status === "accepted") {
|
||||
@@ -3931,6 +3950,7 @@ export class AgentManager {
|
||||
options?.clientMessageId,
|
||||
expectedTurnId,
|
||||
admission.providerMessageId,
|
||||
options?.uploadedImages,
|
||||
);
|
||||
}
|
||||
return admission;
|
||||
@@ -4020,7 +4040,7 @@ export class AgentManager {
|
||||
agent: ActiveManagedAgent,
|
||||
expectedTurnId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
options?: AgentPromptSubmissionOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
|
||||
@@ -4036,7 +4056,7 @@ export class AgentManager {
|
||||
private async replaceRunInForegroundLane(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options: AgentRunOptions | undefined,
|
||||
options: AgentPromptSubmissionOptions | undefined,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
assertAdmission?: (agent: ActiveManagedAgent) => void,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
@@ -4050,7 +4070,7 @@ export class AgentManager {
|
||||
private async replaceRunWhenAdmitted(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options: AgentRunOptions | undefined,
|
||||
options: AgentPromptSubmissionOptions | undefined,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
assertAdmission?: (agent: ActiveManagedAgent) => void,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
@@ -4113,6 +4133,7 @@ export class AgentManager {
|
||||
clientMessageId: string | undefined,
|
||||
expectedTurnId: string,
|
||||
providerMessageId: string | undefined,
|
||||
uploadedImages?: readonly UploadedImage[],
|
||||
): Promise<void> {
|
||||
if (!clientMessageId) {
|
||||
return;
|
||||
@@ -4120,6 +4141,7 @@ export class AgentManager {
|
||||
this.recordSubmittedPrompt(agent, prompt, clientMessageId, "accepted", {
|
||||
messageId: clientMessageId,
|
||||
turnId: expectedTurnId,
|
||||
uploadedImages,
|
||||
...(providerMessageId ? { providerMessageId } : {}),
|
||||
});
|
||||
this.emitState(agent);
|
||||
@@ -6193,9 +6215,14 @@ export class AgentManager {
|
||||
prompt: AgentPromptInput,
|
||||
clientMessageId: string,
|
||||
outcome: "accepted" | "rejected",
|
||||
options?: { messageId?: string; providerMessageId?: string; turnId?: string },
|
||||
options?: {
|
||||
messageId?: string;
|
||||
providerMessageId?: string;
|
||||
turnId?: string;
|
||||
uploadedImages?: readonly UploadedImage[];
|
||||
},
|
||||
): void {
|
||||
const images = submittedPromptImages(prompt);
|
||||
const images = options?.uploadedImages ? [...options.uploadedImages] : [];
|
||||
const items = projectAgentMessages({
|
||||
type: "user_message",
|
||||
text: submittedPromptText(prompt),
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
type PromptDispatchResult,
|
||||
} from "../agent-prompt.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { UploadedImage } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentPromptInput, AgentPromptContentBlock } from "../agent-sdk-types.js";
|
||||
import { envelopeMessage, prepareAgentMessage, type AgentPromptSource } from "./envelope.js";
|
||||
import { describeAgentMessage, type AgentMessageBehavior } from "./guidance.js";
|
||||
@@ -19,6 +20,7 @@ interface Message {
|
||||
messageId?: string;
|
||||
source?: AgentPromptSource;
|
||||
prompt: AgentPromptInput;
|
||||
uploadedImages?: readonly UploadedImage[];
|
||||
sessionMode?: string;
|
||||
unarchive?: boolean;
|
||||
clearPendingPermissions?: boolean;
|
||||
@@ -73,6 +75,7 @@ interface DispatchRequest {
|
||||
recipientId: string;
|
||||
messageIds: readonly string[];
|
||||
prompt: AgentPromptInput;
|
||||
uploadedImages: readonly UploadedImage[];
|
||||
activeTurnBehavior: "steer" | "interrupt";
|
||||
idleOnly: boolean;
|
||||
/**
|
||||
@@ -88,6 +91,7 @@ interface DispatchRequest {
|
||||
interface DirectPrompt {
|
||||
recipientId: string;
|
||||
prompt: AgentPromptInput;
|
||||
uploadedImages?: readonly UploadedImage[];
|
||||
source?: AgentPromptSource;
|
||||
messageId?: string;
|
||||
sessionMode?: string;
|
||||
@@ -96,6 +100,7 @@ interface DirectPrompt {
|
||||
/** The provider prompt a direct prompt became. Unchanged when nothing was queued. */
|
||||
interface JoinedPrompt {
|
||||
prompt: AgentPromptInput;
|
||||
uploadedImages: readonly UploadedImage[];
|
||||
messageId?: string;
|
||||
sessionMode?: string;
|
||||
unarchive: boolean;
|
||||
@@ -254,6 +259,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
},
|
||||
messageIds: messages.map((message) => message.receipt.messageId),
|
||||
prompt: formatBatch(messages),
|
||||
uploadedImages: messages.flatMap((message) => message.uploadedImages ?? []),
|
||||
// A batch that waited for the turn to end is dispatched idle-only, so it never steers.
|
||||
activeTurnBehavior: messages.some((message) => message.urgency === "interrupt")
|
||||
? "interrupt"
|
||||
@@ -514,6 +520,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
const own = prepareAgentMessage(direct.prompt, direct.source, direct.messageId);
|
||||
return {
|
||||
prompt: own.prompt,
|
||||
uploadedImages: direct.uploadedImages ?? [],
|
||||
messageId: own.messageId,
|
||||
sessionMode: direct.sessionMode,
|
||||
unarchive: direct.unarchive !== false,
|
||||
@@ -524,6 +531,10 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
const own = envelopeMessage(direct.prompt, direct.source ?? null, direct.messageId);
|
||||
return {
|
||||
prompt: combine([...queued.map(envelopeEntry), own.prompt]),
|
||||
uploadedImages: [
|
||||
...queued.flatMap((message) => message.uploadedImages ?? []),
|
||||
...(direct.uploadedImages ?? []),
|
||||
],
|
||||
messageId: own.messageId,
|
||||
sessionMode:
|
||||
direct.sessionMode ?? queued.findLast((message) => message.sessionMode)?.sessionMode,
|
||||
|
||||
@@ -5,8 +5,9 @@ import {
|
||||
} from "./agent-messages/index.js";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { UploadedImage } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentPromptInput, AgentRunOptions } from "./agent-sdk-types.js";
|
||||
import type { AgentManager, ManagedAgent } from "./agent-manager.js";
|
||||
import type { AgentManager, AgentPromptSubmissionOptions, ManagedAgent } from "./agent-manager.js";
|
||||
import { ForegroundPromptStart } from "./agent-run-state.js";
|
||||
import type { AgentStorage } from "./agent-storage.js";
|
||||
import { ensureAgentLoaded } from "./agent-loading.js";
|
||||
@@ -41,10 +42,22 @@ export interface StartAgentRunOptions {
|
||||
replaceRunning?: boolean;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
runOptions?: AgentRunOptions;
|
||||
/** Daemon timeline metadata for uploaded image attachments; never forwarded to providers. */
|
||||
uploadedImages?: readonly UploadedImage[];
|
||||
/** Ask the provider to deny permissions blocking this steer. */
|
||||
clearPendingPermissions?: boolean;
|
||||
}
|
||||
|
||||
function toSubmissionOptions(
|
||||
runOptions: AgentRunOptions | undefined,
|
||||
uploadedImages: readonly UploadedImage[] | undefined,
|
||||
): AgentPromptSubmissionOptions | undefined {
|
||||
if (!uploadedImages || uploadedImages.length === 0) {
|
||||
return runOptions;
|
||||
}
|
||||
return { ...runOptions, uploadedImages };
|
||||
}
|
||||
|
||||
export type PromptDispatchDisposition = "out_of_band" | "steered" | "turn_started";
|
||||
|
||||
/** A dispatched prompt. A started turn carries its sender's start outcome. */
|
||||
@@ -69,9 +82,10 @@ async function steerOrReplaceActiveRun(
|
||||
if (options?.activeTurnBehavior !== "steer") {
|
||||
return null;
|
||||
}
|
||||
const submissionOptions = toSubmissionOptions(options.runOptions, options.uploadedImages);
|
||||
const steerOptions = options.clearPendingPermissions
|
||||
? { ...options.runOptions, clearPendingPermissions: true }
|
||||
: options.runOptions;
|
||||
? { ...submissionOptions, clearPendingPermissions: true }
|
||||
: submissionOptions;
|
||||
const result = await agentManager.steerOrReplaceActiveTurn(
|
||||
agentId,
|
||||
prompt,
|
||||
@@ -97,10 +111,11 @@ async function startOrReplaceRun(
|
||||
iterator: AsyncGenerator<import("./agent-sdk-types.js").AgentStreamEvent>;
|
||||
replaced: boolean;
|
||||
}> {
|
||||
const submissionOptions = toSubmissionOptions(options?.runOptions, options?.uploadedImages);
|
||||
const replaced = Boolean(options?.replaceRunning && agentManager.hasInFlightRun(agentId));
|
||||
const iterator = replaced
|
||||
? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions, promptStart)
|
||||
: agentManager.streamAgent(agentId, prompt, options?.runOptions, promptStart);
|
||||
? await agentManager.replaceAgentRun(agentId, prompt, submissionOptions, promptStart)
|
||||
: agentManager.streamAgent(agentId, prompt, submissionOptions, promptStart);
|
||||
return { iterator, replaced };
|
||||
}
|
||||
|
||||
@@ -141,7 +156,14 @@ export async function startAgentRun(
|
||||
if (!admit()) throw new Error("Queued agent message was withdrawn");
|
||||
}
|
||||
: undefined;
|
||||
if (await agentManager.tryRunOutOfBand(agentId, prompt, options?.runOptions, admitCommand)) {
|
||||
if (
|
||||
await agentManager.tryRunOutOfBand(
|
||||
agentId,
|
||||
prompt,
|
||||
toSubmissionOptions(options?.runOptions, options?.uploadedImages),
|
||||
admitCommand,
|
||||
)
|
||||
) {
|
||||
options?.onDispatch?.("out_of_band");
|
||||
return { disposition: "out_of_band" };
|
||||
}
|
||||
@@ -267,6 +289,8 @@ export interface SendPromptToAgentParams {
|
||||
agentId: string;
|
||||
/** Prompt to dispatch to the provider (may include image blocks or wrapped text). */
|
||||
prompt: AgentPromptInput;
|
||||
/** Daemon timeline metadata for uploaded image attachments; never forwarded to providers. */
|
||||
uploadedImages?: readonly UploadedImage[];
|
||||
source?: AgentPromptSource;
|
||||
messageId?: string;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
@@ -295,6 +319,7 @@ export interface StartCreatedAgentInitialPromptParams {
|
||||
agentId: string;
|
||||
snapshot?: ManagedAgent;
|
||||
prompt: AgentPromptInput | null;
|
||||
uploadedImages?: readonly UploadedImage[];
|
||||
source?: AgentPromptSource;
|
||||
runOptions?: AgentRunOptions;
|
||||
logger: Logger;
|
||||
@@ -388,6 +413,7 @@ export async function sendPromptToAgent(
|
||||
{
|
||||
recipientId: params.agentId,
|
||||
prompt: params.prompt,
|
||||
uploadedImages: params.uploadedImages,
|
||||
source: await resolvePromptSource(source, params.agentManager, params.agentStorage),
|
||||
messageId,
|
||||
sessionMode: params.sessionMode,
|
||||
@@ -397,6 +423,7 @@ export async function sendPromptToAgent(
|
||||
sendPreparedPromptToAgent({
|
||||
...send,
|
||||
prompt: joined.prompt,
|
||||
uploadedImages: joined.uploadedImages,
|
||||
sessionMode: joined.sessionMode,
|
||||
unarchive: joined.unarchive,
|
||||
runOptions: joined.messageId
|
||||
@@ -457,6 +484,7 @@ export async function sendPreparedPromptToAgent(
|
||||
activeTurnBehavior: params.activeTurnBehavior,
|
||||
clearPendingPermissions: params.clearPendingPermissions,
|
||||
runOptions: params.runOptions,
|
||||
uploadedImages: params.uploadedImages,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -482,7 +510,10 @@ export async function startCreatedAgentInitialPrompt(
|
||||
params.agentId,
|
||||
delivery.prompt,
|
||||
params.logger,
|
||||
{ runOptions: { ...params.runOptions, clientMessageId: delivery.messageId } },
|
||||
{
|
||||
runOptions: { ...params.runOptions, clientMessageId: delivery.messageId },
|
||||
uploadedImages: params.uploadedImages,
|
||||
},
|
||||
);
|
||||
|
||||
if (dispatchResult.disposition === "turn_started") {
|
||||
|
||||
@@ -214,7 +214,6 @@ export type AgentPromptContentBlock =
|
||||
type: "image";
|
||||
data: string;
|
||||
mimeType: string;
|
||||
uploadedImage?: import("@getpaseo/protocol/agent-types").UploadedImage;
|
||||
}
|
||||
| AgentAttachment;
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
inheritWorkspaceBackground,
|
||||
resolveCreateAgentIntent,
|
||||
} from "./intent.js";
|
||||
import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import type { ProviderOptions, UploadedImage } from "@getpaseo/protocol/agent-types";
|
||||
import { foldFeatureValues, type LegacyFeatureValues } from "../option-controls.js";
|
||||
|
||||
/** How a workspace this creation makes inherits its creator's visibility. */
|
||||
@@ -163,6 +163,7 @@ interface ResolvedCreateAgent {
|
||||
config: AgentSessionConfig;
|
||||
createOptions: CreateAgentOptions;
|
||||
prompt?: AgentPromptInput;
|
||||
uploadedImages?: readonly UploadedImage[];
|
||||
source?: AgentPromptSource;
|
||||
runOptions?: AgentRunOptions;
|
||||
promptFailure: CreateAgentPromptFailureMode;
|
||||
@@ -249,7 +250,7 @@ async function resolveSessionCreateAgent(
|
||||
modeId: resolvedCreateConfig.modeId,
|
||||
providerOptions: resolvedCreateConfig.providerOptions,
|
||||
};
|
||||
const prompt = await resolveAgentPrompt({
|
||||
const { prompt, uploadedImages } = await resolveAgentPrompt({
|
||||
paseoHome: dependencies.paseoHome,
|
||||
text: trimmedPrompt ?? "",
|
||||
images: input.images,
|
||||
@@ -281,6 +282,7 @@ async function resolveSessionCreateAgent(
|
||||
background: input.background,
|
||||
},
|
||||
prompt: hasPromptContent ? prompt : undefined,
|
||||
...(uploadedImages.length > 0 ? { uploadedImages } : {}),
|
||||
source: input.source,
|
||||
runOptions,
|
||||
// Registration commits creation. First-turn failures belong to the created agent.
|
||||
@@ -468,6 +470,7 @@ async function sendInitialPrompt(
|
||||
agentId: snapshot.id,
|
||||
snapshot,
|
||||
prompt,
|
||||
...(resolved.uploadedImages ? { uploadedImages: resolved.uploadedImages } : {}),
|
||||
source: resolved.source,
|
||||
runOptions: resolved.runOptions,
|
||||
logger: resolved.promptLogger ?? dependencies.logger,
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { mkdtemp, readFile as readFsFile, rm, writeFile as writeFsFile } from "node:fs/promises";
|
||||
import {
|
||||
mkdir as makeDir,
|
||||
mkdtemp,
|
||||
readFile as readFsFile,
|
||||
realpath,
|
||||
rm,
|
||||
writeFile as writeFsFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { AgentStorage } from "./agent-storage.js";
|
||||
import { resolveAgentPrompt } from "./prompt-attachments.js";
|
||||
import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js";
|
||||
import { relative } from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
@@ -4095,3 +4103,185 @@ describe("plugin ACP hung-cancel retirement through AgentManager (#3256)", () =>
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test("plugin provider receives only { type, data, mimeType } for uploaded images while timeline retains uploadedImage metadata", async () => {
|
||||
const dir = await realpath(await mkdtemp(join(tmpdir(), "paseo-plugin-uploaded-img-")));
|
||||
const logger = createTestLogger();
|
||||
const uploadDir = join(dir, "uploads", "upload_img_1");
|
||||
await makeDir(uploadDir, { recursive: true });
|
||||
const rawBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
const imagePath = join(uploadDir, "screenshot.png");
|
||||
await writeFsFile(imagePath, rawBytes);
|
||||
|
||||
const receivedPromptInputs: ProviderInput[] = [];
|
||||
let completeTurnOne!: () => void;
|
||||
const turnOneDone = new Promise<void>((resolve) => {
|
||||
completeTurnOne = resolve;
|
||||
});
|
||||
const harness = createProviderHarness({
|
||||
capabilities: [...CAPABILITIES, "prompt.image", "prompt.steer"],
|
||||
completeTurn: false,
|
||||
async handleInput(input, emit) {
|
||||
if (input.type !== "session.prompt") return false;
|
||||
receivedPromptInputs.push(input);
|
||||
if (input.prompt.delivery === "steer") {
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "steer", turnId: "turn-img-1" },
|
||||
});
|
||||
completeTurnOne();
|
||||
return true;
|
||||
}
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "turn", turnId: "turn-img-1" },
|
||||
});
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: input.sessionId,
|
||||
turnId: "turn-img-1",
|
||||
state: "started",
|
||||
});
|
||||
void turnOneDone.then(() => {
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: input.sessionId,
|
||||
item: { type: "assistant_message", id: "img-answer", text: "Saw screenshot" },
|
||||
});
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: input.sessionId,
|
||||
turnId: "turn-img-1",
|
||||
state: "completed",
|
||||
});
|
||||
return undefined;
|
||||
});
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([
|
||||
{
|
||||
...harness.registration,
|
||||
id: "image-plugin",
|
||||
label: "Image Plugin",
|
||||
},
|
||||
]);
|
||||
const manager = new AgentManager({
|
||||
logger,
|
||||
clients: plugins.clients(),
|
||||
providerDefinitions: plugins.definitions(),
|
||||
});
|
||||
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: "image-plugin", cwd: dir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
|
||||
const firstResolved = await resolveAgentPrompt({
|
||||
paseoHome: dir,
|
||||
text: "Inspect this screenshot",
|
||||
attachments: [
|
||||
{
|
||||
type: "uploaded_file",
|
||||
id: "upload_img_1",
|
||||
fileName: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
size: rawBytes.byteLength,
|
||||
path: imagePath,
|
||||
role: "image",
|
||||
},
|
||||
],
|
||||
});
|
||||
const steerResolved = await resolveAgentPrompt({
|
||||
paseoHome: dir,
|
||||
text: "Check the top corner too",
|
||||
attachments: [
|
||||
{
|
||||
type: "uploaded_file",
|
||||
id: "upload_img_1",
|
||||
fileName: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
size: rawBytes.byteLength,
|
||||
path: imagePath,
|
||||
role: "image",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const runPromise = manager.runAgent(agent.id, firstResolved.prompt, {
|
||||
clientMessageId: "client-img-1",
|
||||
uploadedImages: firstResolved.uploadedImages,
|
||||
});
|
||||
|
||||
await expect.poll(() => receivedPromptInputs.length, { timeout: 2_000 }).toBe(1);
|
||||
|
||||
const steerResult = await manager.steerAgentRun(agent.id, steerResolved.prompt, {
|
||||
clientMessageId: "client-img-steer",
|
||||
uploadedImages: steerResolved.uploadedImages,
|
||||
});
|
||||
expect(steerResult.status).toBe("accepted");
|
||||
|
||||
await runPromise;
|
||||
|
||||
expect(receivedPromptInputs).toHaveLength(2);
|
||||
for (const promptInput of receivedPromptInputs) {
|
||||
expect(promptInput.type).toBe("session.prompt");
|
||||
if (promptInput.type !== "session.prompt") continue;
|
||||
expect(promptInput.prompt.input.type).toBe("message");
|
||||
if (promptInput.prompt.input.type !== "message") continue;
|
||||
const imageBlock = promptInput.prompt.input.content.find((block) => block.type === "image");
|
||||
expect(imageBlock).toEqual({
|
||||
type: "image",
|
||||
data: rawBytes.toString("base64"),
|
||||
mimeType: "image/png",
|
||||
});
|
||||
expect(Object.keys(imageBlock!)).toEqual(["type", "data", "mimeType"]);
|
||||
expect(JSON.stringify(promptInput)).not.toContain(imagePath);
|
||||
expect(JSON.stringify(promptInput)).not.toContain("uploadedImage");
|
||||
}
|
||||
|
||||
const timeline = manager.getTimeline(agent.id);
|
||||
const firstUser = timeline.find(
|
||||
(item) => item.type === "user_message" && item.clientMessageId === "client-img-1",
|
||||
);
|
||||
const steeredUser = timeline.find(
|
||||
(item) => item.type === "user_message" && item.clientMessageId === "client-img-steer",
|
||||
);
|
||||
expect(firstUser).toMatchObject({
|
||||
type: "user_message",
|
||||
text: "Inspect this screenshot",
|
||||
images: [
|
||||
{
|
||||
id: "upload_img_1",
|
||||
fileName: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
size: rawBytes.byteLength,
|
||||
path: imagePath,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(steeredUser).toMatchObject({
|
||||
type: "user_message",
|
||||
text: "Check the top corner too",
|
||||
images: [
|
||||
{
|
||||
id: "upload_img_1",
|
||||
fileName: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
size: rawBytes.byteLength,
|
||||
path: imagePath,
|
||||
},
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -10,9 +10,9 @@ import { z } from "zod";
|
||||
import {
|
||||
PROVIDER_CAPABILITIES,
|
||||
PROVIDER_PROTOCOL_VERSION,
|
||||
ProviderEventSchema,
|
||||
ProviderInputSchema,
|
||||
ProviderStatusSchema,
|
||||
parseProviderEvent,
|
||||
type ProviderCatalogRefreshMode,
|
||||
type ProviderClientInfo,
|
||||
type ProviderStatus,
|
||||
@@ -1070,7 +1070,11 @@ function normalizeConnection(connection: ProviderConnection): ProviderConnection
|
||||
capabilities,
|
||||
send: (input) => connection.send(ProviderInputSchema.parse(input)),
|
||||
onEvent: (listener) =>
|
||||
connection.onEvent((event) => listener(ProviderEventSchema.parse(event))),
|
||||
connection.onEvent((event) => {
|
||||
// An event kind this daemon does not know is dropped; the connection stays open.
|
||||
const parsed = parseProviderEvent(event);
|
||||
if (parsed) listener(parsed);
|
||||
}),
|
||||
close: () => connection.close(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -230,7 +230,7 @@ describe("resolveAgentPrompt uploaded images", () => {
|
||||
path: join(home, "uploads", "upload_plain", "report.pdf"),
|
||||
};
|
||||
|
||||
const prompt = await resolveAgentPrompt({
|
||||
const resolved = await resolveAgentPrompt({
|
||||
paseoHome: home,
|
||||
text: "What is in this image?",
|
||||
attachments: [
|
||||
@@ -247,22 +247,29 @@ describe("resolveAgentPrompt uploaded images", () => {
|
||||
],
|
||||
});
|
||||
|
||||
expect(prompt).toEqual([
|
||||
expect(resolved.prompt).toEqual([
|
||||
{ type: "text", text: "What is in this image?" },
|
||||
{
|
||||
type: "image",
|
||||
data: rawBytes.toString("base64"),
|
||||
mimeType: "image/png",
|
||||
uploadedImage: {
|
||||
id: "upload_1",
|
||||
fileName: "photo.png",
|
||||
mimeType: "image/png",
|
||||
size: rawBytes.byteLength,
|
||||
path: imagePath,
|
||||
},
|
||||
},
|
||||
plainFileAttachment,
|
||||
]);
|
||||
expect(Array.isArray(resolved.prompt) ? Object.keys(resolved.prompt[1]!) : []).toEqual([
|
||||
"type",
|
||||
"data",
|
||||
"mimeType",
|
||||
]);
|
||||
expect(resolved.uploadedImages).toEqual([
|
||||
{
|
||||
id: "upload_1",
|
||||
fileName: "photo.png",
|
||||
mimeType: "image/png",
|
||||
size: rawBytes.byteLength,
|
||||
path: imagePath,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("supports image-only prompts with empty text", async () => {
|
||||
@@ -271,7 +278,7 @@ describe("resolveAgentPrompt uploaded images", () => {
|
||||
const imagePath = join(home, "uploads", "upload_1", "only.jpg");
|
||||
await writeFile(imagePath, rawBytes);
|
||||
|
||||
const prompt = await resolveAgentPrompt({
|
||||
const resolved = await resolveAgentPrompt({
|
||||
paseoHome: home,
|
||||
text: " ",
|
||||
attachments: [
|
||||
@@ -287,18 +294,20 @@ describe("resolveAgentPrompt uploaded images", () => {
|
||||
],
|
||||
});
|
||||
|
||||
expect(prompt).toEqual([
|
||||
expect(resolved.prompt).toEqual([
|
||||
{
|
||||
type: "image",
|
||||
data: rawBytes.toString("base64"),
|
||||
mimeType: "image/jpeg",
|
||||
uploadedImage: {
|
||||
id: "upload_1",
|
||||
fileName: "only.jpg",
|
||||
mimeType: "image/jpeg",
|
||||
size: rawBytes.byteLength,
|
||||
path: imagePath,
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(resolved.uploadedImages).toEqual([
|
||||
{
|
||||
id: "upload_1",
|
||||
fileName: "only.jpg",
|
||||
mimeType: "image/jpeg",
|
||||
size: rawBytes.byteLength,
|
||||
path: imagePath,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -9,15 +9,14 @@ import type { AgentPromptContentBlock, AgentPromptInput } from "./agent-sdk-type
|
||||
|
||||
const REVIEW_LINE_MARKERS = { add: "+", remove: "-", context: " " } as const;
|
||||
|
||||
export interface ResolvedPromptImage {
|
||||
data: string;
|
||||
mimeType: string;
|
||||
uploadedImage?: UploadedImage;
|
||||
export interface ResolvedAgentPrompt {
|
||||
prompt: AgentPromptInput;
|
||||
uploadedImages: UploadedImage[];
|
||||
}
|
||||
|
||||
export function buildAgentPrompt(
|
||||
text: string,
|
||||
images?: Array<ResolvedPromptImage>,
|
||||
images?: Array<{ data: string; mimeType: string }>,
|
||||
attachments?: AgentAttachment[],
|
||||
): AgentPromptInput {
|
||||
const normalized = text.trim();
|
||||
@@ -46,7 +45,6 @@ export function buildAgentPrompt(
|
||||
type: "image",
|
||||
data: image.data,
|
||||
mimeType: image.mimeType,
|
||||
...(image.uploadedImage ? { uploadedImage: image.uploadedImage } : {}),
|
||||
});
|
||||
}
|
||||
blocks.push(...otherAttachments);
|
||||
@@ -64,8 +62,9 @@ export async function resolveAgentPrompt(input: {
|
||||
text: string;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments?: AgentAttachment[];
|
||||
}): Promise<AgentPromptInput> {
|
||||
const resolvedImages: ResolvedPromptImage[] = [...(input.images ?? [])];
|
||||
}): Promise<ResolvedAgentPrompt> {
|
||||
const resolvedImages: Array<{ data: string; mimeType: string }> = [...(input.images ?? [])];
|
||||
const uploadedImages: UploadedImage[] = [];
|
||||
const uploadedImageAttachments: Array<UploadedFileAttachment & { role: "image" }> = [];
|
||||
const remainingAttachments: AgentAttachment[] = [];
|
||||
for (const attachment of input.attachments ?? []) {
|
||||
@@ -95,15 +94,18 @@ export async function resolveAgentPrompt(input: {
|
||||
resolvedImages.push({
|
||||
data: file.bytes.toString("base64"),
|
||||
mimeType: attachment.mimeType,
|
||||
uploadedImage: {
|
||||
...uploadedImage,
|
||||
size: file.size,
|
||||
path: file.resolvedPath,
|
||||
},
|
||||
});
|
||||
uploadedImages.push({
|
||||
...uploadedImage,
|
||||
size: file.size,
|
||||
path: file.resolvedPath,
|
||||
});
|
||||
}
|
||||
}
|
||||
return buildAgentPrompt(input.text, resolvedImages, remainingAttachments);
|
||||
return {
|
||||
prompt: buildAgentPrompt(input.text, resolvedImages, remainingAttachments),
|
||||
uploadedImages,
|
||||
};
|
||||
}
|
||||
|
||||
export function renderPromptAttachmentAsText(attachment: AgentAttachment): string {
|
||||
|
||||
@@ -154,8 +154,12 @@ describe("respectful ACP probing", () => {
|
||||
});
|
||||
try {
|
||||
manager1.replacePluginProviders([registration]);
|
||||
// The global read binds the probe first, as the daemon's warm-up does. When all four start
|
||||
// together, launch resolution timing decides which read runs the probe and in which cwd.
|
||||
const globalRead = manager1.getProvider({ provider: "fake-acp", wait: true });
|
||||
await expect.poll(async () => acpSpawns(await readEvents(logFile))).toHaveLength(1);
|
||||
await Promise.all([
|
||||
manager1.getProvider({ provider: "fake-acp", wait: true }),
|
||||
globalRead,
|
||||
manager1.getProvider({ provider: "fake-acp", cwd: path.join(dir, "ws-1"), wait: true }),
|
||||
manager1.getProvider({ provider: "fake-acp", cwd: path.join(dir, "ws-2"), wait: true }),
|
||||
manager1.getProvider({ provider: "fake-acp", cwd: path.join(dir, "ws-3"), wait: true }),
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { test } from "vitest";
|
||||
import assert from "node:assert";
|
||||
import { spawn } from "node:child_process";
|
||||
import { execFile, spawn } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { once } from "node:events";
|
||||
import { WebSocket, WebSocketServer } from "ws";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -281,3 +284,296 @@ test("logs --since filters history and live output through the CLI and daemon",
|
||||
await rm(cliHome, { recursive: true, force: true });
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
test("one-shot logs preserve history order across pages", async () => {
|
||||
const ctx = await createDaemonTestContext();
|
||||
try {
|
||||
const proxy = new WebSocketServer({ port: 0, host: "127.0.0.1" });
|
||||
const upstreams: WebSocket[] = [];
|
||||
try {
|
||||
await once(proxy, "listening");
|
||||
const address = proxy.address();
|
||||
if (!address || typeof address === "string") throw new Error("Missing proxy port");
|
||||
const requests: Array<{
|
||||
direction?: string;
|
||||
limit?: number;
|
||||
cursor?: { epoch: string; seq: number };
|
||||
}> = [];
|
||||
proxy.on("connection", (downstream) => {
|
||||
const upstream = new WebSocket(`ws://127.0.0.1:${ctx.daemon.port}/ws`);
|
||||
upstreams.push(upstream);
|
||||
const connected = once(upstream, "open");
|
||||
void connected.catch(() => {});
|
||||
downstream.on("error", () => {});
|
||||
upstream.on("error", () => {});
|
||||
downstream.on("message", async (data, binary) => {
|
||||
try {
|
||||
await connected;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (upstream.readyState !== WebSocket.OPEN) return;
|
||||
try {
|
||||
const frame = binary ? undefined : JSON.parse(data.toString());
|
||||
if (frame?.message?.type === "fetch_agent_timeline_request") {
|
||||
requests.push({
|
||||
direction: frame.message.direction,
|
||||
limit: frame.message.limit,
|
||||
cursor: frame.message.cursor,
|
||||
});
|
||||
}
|
||||
upstream.send(data, { binary });
|
||||
} catch {
|
||||
downstream.terminate();
|
||||
upstream.terminate();
|
||||
}
|
||||
});
|
||||
upstream.on("message", (data, binary) => {
|
||||
if (downstream.readyState === WebSocket.OPEN) downstream.send(data, { binary });
|
||||
});
|
||||
upstream.on("close", () => downstream.terminate());
|
||||
downstream.on("close", () => upstream.terminate());
|
||||
});
|
||||
const agent = await ctx.client.createAgent({
|
||||
provider: "codex",
|
||||
cwd: ctx.daemon.paseoHome,
|
||||
title: "paged logs",
|
||||
});
|
||||
const manager = ctx.daemon.daemon.agentManager;
|
||||
for (let index = 0; index < 405; index++) {
|
||||
const text = `row-${String(index).padStart(3, "0")} ${"x".repeat(4096)}`;
|
||||
await manager.appendTimelineItem(
|
||||
agent.id,
|
||||
[0, 1, 210, 270, 330, 380].includes(index)
|
||||
? { type: "user_message", text }
|
||||
: { type: "assistant_message", text, messageId: `message-${index}` },
|
||||
);
|
||||
}
|
||||
const epoch = manager.fetchTimeline(agent.id, { direction: "tail", limit: 1 }).epoch;
|
||||
const prefix = [
|
||||
"--no-warnings",
|
||||
"--conditions=source",
|
||||
"--import",
|
||||
import.meta.resolve("tsx"),
|
||||
fileURLToPath(new URL("../../../cli/src/index.ts", import.meta.url)),
|
||||
"--host",
|
||||
`127.0.0.1:${address.port}`,
|
||||
"agent",
|
||||
"logs",
|
||||
agent.id,
|
||||
];
|
||||
const cases = [
|
||||
{
|
||||
flags: ["--tail", "5", "--json"],
|
||||
expected: Array.from({ length: 5 }, (_, i) => i + 400),
|
||||
json: true,
|
||||
},
|
||||
{
|
||||
flags: ["--tail", "5"],
|
||||
expected: Array.from({ length: 5 }, (_, i) => i + 400),
|
||||
json: false,
|
||||
},
|
||||
{
|
||||
flags: ["--tail", "205", "--json"],
|
||||
expected: Array.from({ length: 205 }, (_, i) => i + 200),
|
||||
json: true,
|
||||
},
|
||||
{ flags: ["--json"], expected: Array.from({ length: 405 }, (_, i) => i), json: true },
|
||||
{ flags: [], expected: Array.from({ length: 405 }, (_, i) => i), json: false },
|
||||
{ flags: ["--tail", "0", "--json"], expected: [], json: true },
|
||||
{ flags: ["--tail", "0"], expected: [], json: false },
|
||||
{
|
||||
flags: [
|
||||
"--filter",
|
||||
"user_message",
|
||||
"--tail",
|
||||
"5",
|
||||
"--since",
|
||||
"2000-01-01T00:00:00Z",
|
||||
"--json",
|
||||
],
|
||||
expected: [1, 210, 270, 330, 380],
|
||||
json: true,
|
||||
},
|
||||
{ flags: ["--since", "2100-01-01T00:00:00Z", "--json"], expected: [], json: true },
|
||||
{ flags: ["--tail", "0", "--filter", "text", "--json"], expected: [], json: true },
|
||||
{ flags: ["--tail", "0", "--since", "2000-01-01T00:00:00Z"], expected: [], json: false },
|
||||
{
|
||||
flags: ["--tail", "205"],
|
||||
expected: Array.from({ length: 205 }, (_, i) => i + 200),
|
||||
json: false,
|
||||
},
|
||||
{
|
||||
flags: ["--filter", "user_message", "--tail", "5", "--since", "2000-01-01T00:00:00Z"],
|
||||
expected: [1, 210, 270, 330, 380],
|
||||
json: false,
|
||||
},
|
||||
];
|
||||
const observed: Array<typeof requests> = [];
|
||||
for (const entry of cases) {
|
||||
requests.length = 0;
|
||||
const { stdout, stderr } = await promisify(execFile)(
|
||||
process.execPath,
|
||||
[...prefix, ...entry.flags],
|
||||
{
|
||||
cwd: ctx.daemon.paseoHome,
|
||||
env: {
|
||||
...Object.fromEntries(
|
||||
Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_")),
|
||||
),
|
||||
HOME: ctx.daemon.paseoHome,
|
||||
USERPROFILE: ctx.daemon.paseoHome,
|
||||
},
|
||||
maxBuffer: 8 * 1024 * 1024,
|
||||
timeout: 30_000,
|
||||
},
|
||||
);
|
||||
const parsed = entry.json
|
||||
? (JSON.parse(stdout) as { agentId: string; items: Array<{ text: string }> })
|
||||
: undefined;
|
||||
if (parsed) assert.strictEqual(parsed.agentId, agent.id);
|
||||
const rows = parsed
|
||||
? parsed.items.map((item) => item.text.slice(0, 7))
|
||||
: [...stdout.matchAll(/row-\d{3}/g)].map((match) => match[0]);
|
||||
const expected = entry.expected.map((i) => `row-${String(i).padStart(3, "0")}`);
|
||||
console.log(
|
||||
`paseo agent logs <id> ${entry.flags.join(" ")}: exit=0 count=${rows.length} first=${rows[0] ?? "-"} last=${rows.at(-1) ?? "-"} requests=${JSON.stringify(requests)} stderr=${JSON.stringify(stderr)}`,
|
||||
);
|
||||
assert.deepStrictEqual(rows, expected);
|
||||
assert.strictEqual(stderr, "");
|
||||
if (!entry.json) {
|
||||
const expectedText = entry.expected
|
||||
.map(
|
||||
(i) =>
|
||||
`${[0, 1, 210, 270, 330, 380].includes(i) ? "[User] " : ""}row-${String(i).padStart(3, "0")} ${"x".repeat(4096)}\n`,
|
||||
)
|
||||
.join("");
|
||||
assert.strictEqual(stdout, expectedText);
|
||||
}
|
||||
observed.push([...requests]);
|
||||
}
|
||||
assert.deepStrictEqual(observed[0], [{ direction: "tail", limit: 5, cursor: undefined }]);
|
||||
for (const index of [1, 2, 3, 4, 7, 8, 11, 12]) {
|
||||
assert(observed[index].length >= 2);
|
||||
assert.strictEqual(observed[index][0].direction, "tail");
|
||||
assert.strictEqual(observed[index][0].cursor, undefined);
|
||||
assert(
|
||||
observed[index].every(
|
||||
(request) => request.limit !== undefined && request.limit > 0 && request.limit <= 200,
|
||||
),
|
||||
);
|
||||
assert(
|
||||
observed[index]
|
||||
.slice(1)
|
||||
.every((request) => request.direction === "before" && request.cursor !== undefined),
|
||||
);
|
||||
const cursors = observed[index].slice(1).map((request) => request.cursor!);
|
||||
assert(cursors.every((cursor) => cursor.epoch === epoch));
|
||||
assert(cursors.every((cursor, i) => i === 0 || cursor.seq < cursors[i - 1].seq));
|
||||
}
|
||||
for (const index of [1, 3, 4, 8, 11, 12]) assert(observed[index].length >= 3);
|
||||
assert.strictEqual(observed[2].length, 2);
|
||||
assert.deepStrictEqual(observed[5], []);
|
||||
assert.deepStrictEqual(observed[6], []);
|
||||
assert.deepStrictEqual(observed[9], []);
|
||||
assert.deepStrictEqual(observed[10], []);
|
||||
} finally {
|
||||
for (const downstream of proxy.clients) downstream.terminate();
|
||||
for (const upstream of upstreams) upstream.terminate();
|
||||
await new Promise<void>((resolve) => proxy.close(() => resolve()));
|
||||
}
|
||||
} finally {
|
||||
await ctx.cleanup();
|
||||
}
|
||||
}, 240_000);
|
||||
|
||||
test("text tail retains older items when curation merges across turns", async () => {
|
||||
const historyEvents: AgentStreamEvent[] = [
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
timestamp: "2026-01-01T00:00:00Z",
|
||||
turnId: "t1",
|
||||
item: { type: "user_message", text: "u1" },
|
||||
},
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
timestamp: "2026-01-01T00:00:01Z",
|
||||
turnId: "t1",
|
||||
item: { type: "reasoning", text: "r1" },
|
||||
},
|
||||
{
|
||||
type: "timeline",
|
||||
provider: "codex",
|
||||
timestamp: "2026-01-01T00:00:02Z",
|
||||
turnId: "t2",
|
||||
item: { type: "reasoning", text: "r2" },
|
||||
},
|
||||
];
|
||||
const agentClients = createTestAgentClients({ historyEvents });
|
||||
let publish: ((event: AgentStreamEvent) => void) | undefined;
|
||||
const fake = agentClients.codex;
|
||||
const createSession = fake.createSession.bind(fake);
|
||||
fake.createSession = async (...args) => {
|
||||
const session = await createSession(...args);
|
||||
const subscribe = session.subscribe.bind(session);
|
||||
session.subscribe = (listener) => {
|
||||
publish = listener;
|
||||
return subscribe(listener);
|
||||
};
|
||||
return session;
|
||||
};
|
||||
const ctx = await createDaemonTestContext({ agentClients });
|
||||
try {
|
||||
const agent = await ctx.client.createAgent({ provider: "codex", cwd: ctx.daemon.paseoHome });
|
||||
assert(publish);
|
||||
for (const event of historyEvents) publish(event);
|
||||
await ctx.daemon.daemon.agentManager.flush();
|
||||
await ctx.daemon.daemon.agentManager.flush();
|
||||
const timeline = await ctx.client.fetchAgentTimeline(agent.id, {
|
||||
direction: "tail",
|
||||
limit: 0,
|
||||
projection: "projected",
|
||||
});
|
||||
assert.deepStrictEqual(
|
||||
timeline.entries.map((entry) => [entry.turnId, entry.item]),
|
||||
[
|
||||
["t1", { type: "user_message", text: "u1" }],
|
||||
["t1", { type: "reasoning", text: "r1" }],
|
||||
["t2", { type: "reasoning", text: "r2" }],
|
||||
],
|
||||
);
|
||||
const args = [
|
||||
"--no-warnings",
|
||||
"--conditions=source",
|
||||
"--import",
|
||||
import.meta.resolve("tsx"),
|
||||
fileURLToPath(new URL("../../../cli/src/index.ts", import.meta.url)),
|
||||
"--host",
|
||||
`127.0.0.1:${ctx.daemon.port}`,
|
||||
"logs",
|
||||
agent.id,
|
||||
"--tail",
|
||||
"2",
|
||||
];
|
||||
const { stdout, stderr } = await promisify(execFile)(process.execPath, args, {
|
||||
cwd: ctx.daemon.paseoHome,
|
||||
env: {
|
||||
...Object.fromEntries(
|
||||
Object.entries(process.env).filter(([key]) => !key.startsWith("PASEO_")),
|
||||
),
|
||||
HOME: ctx.daemon.paseoHome,
|
||||
USERPROFILE: ctx.daemon.paseoHome,
|
||||
},
|
||||
timeout: 30_000,
|
||||
});
|
||||
console.log(
|
||||
`paseo logs <id> --tail 2: exit=0 stdout=${JSON.stringify(stdout)} stderr=${JSON.stringify(stderr)}`,
|
||||
);
|
||||
assert.strictEqual(stdout, "[User] u1\n[Thought] r1r2\n");
|
||||
assert.strictEqual(stderr, "");
|
||||
} finally {
|
||||
await ctx.cleanup();
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
DaemonClient,
|
||||
} from "./test-utils/index.js";
|
||||
import { createTestPaseoDaemon } from "./test-utils/paseo-daemon.js";
|
||||
import { resolveDaemonVersion } from "./daemon-version.js";
|
||||
import { createTestAgentClients } from "./test-utils/fake-agent-client.js";
|
||||
import { getFullAccessConfig, getAskModeConfig } from "./daemon-e2e/agent-configs.js";
|
||||
import { parsePcm16MonoWav, wordSimilarity } from "./test-utils/dictation-e2e.js";
|
||||
@@ -335,6 +336,210 @@ test("DaemonClient uploads a >24 MiB multi-photo batch sequentially with support
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("DaemonClient delivers uploaded image attachments to plugin providers without leaking uploadedImage metadata", async () => {
|
||||
const root = mkdtempSync(path.join(tmpdir(), "paseo-plugin-img-e2e-"));
|
||||
const pluginDir = path.join(root, "plugin");
|
||||
const promptLogPath = path.join(root, "received-prompts.jsonl");
|
||||
const providerId = "vision-plugin-provider";
|
||||
const pluginId = "vision-plugin-provider-plugin";
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
path.join(pluginDir, "paseo-plugin.json"),
|
||||
JSON.stringify({
|
||||
id: pluginId,
|
||||
requirements: { paseo: `>=${resolveDaemonVersion(import.meta.url)}` },
|
||||
}),
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(pluginDir, "index.server.ts"),
|
||||
`import { appendFileSync } from "node:fs";
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderInput,
|
||||
ProviderRegistration,
|
||||
} from "@getpaseo/plugin/server/provider";
|
||||
|
||||
const CAPABILITIES = ["prompt.message", "prompt.image", "session.persistence"];
|
||||
const LOG_PATH = ${JSON.stringify(promptLogPath)};
|
||||
|
||||
const provider: ProviderRegistration = {
|
||||
id: ${JSON.stringify(providerId)},
|
||||
label: "Vision plugin provider",
|
||||
async connect() {
|
||||
let listener: ((event: ProviderEvent) => void) | null = null;
|
||||
const emit = (event: ProviderEvent) => listener?.(event);
|
||||
let turn = 0;
|
||||
return {
|
||||
version: 1,
|
||||
capabilities: CAPABILITIES,
|
||||
async send(input: ProviderInput) {
|
||||
if (input.type === "catalog") {
|
||||
emit({
|
||||
type: "catalog",
|
||||
requestId: input.requestId,
|
||||
catalog: {
|
||||
models: [{ id: "vision-model", label: "Vision model" }],
|
||||
modes: [],
|
||||
thinkingOptions: [],
|
||||
defaultModel: "vision-model",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (input.type === "session.open") {
|
||||
emit({
|
||||
type: "session.opened",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
capabilities: CAPABILITIES,
|
||||
restoration: "core",
|
||||
persistence: { version: 1, data: { token: "vision" } },
|
||||
cwd: input.config.cwd,
|
||||
});
|
||||
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
||||
return;
|
||||
}
|
||||
if (input.type === "session.prompt") {
|
||||
appendFileSync(LOG_PATH, JSON.stringify(input.prompt) + "\\n");
|
||||
turn += 1;
|
||||
const turnId = "turn-" + turn;
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "turn", turnId },
|
||||
});
|
||||
emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "started" });
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: input.sessionId,
|
||||
item: { type: "assistant_message", id: "reply-" + turn, text: "Received image #" + turn },
|
||||
});
|
||||
emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "completed" });
|
||||
return;
|
||||
}
|
||||
if (input.type === "session.close") {
|
||||
emit({ type: "session.closed", sessionId: input.sessionId });
|
||||
}
|
||||
if ("requestId" in input) {
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
}
|
||||
},
|
||||
onEvent(next) {
|
||||
listener = next;
|
||||
return () => {
|
||||
if (listener === next) listener = null;
|
||||
};
|
||||
},
|
||||
close() {},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default function contribute(server: { registerProvider(p: ProviderRegistration): void }) {
|
||||
server.registerProvider(provider);
|
||||
return () => undefined;
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
paseoHomeRoot: path.join(root, "home"),
|
||||
staticDir: path.join(root, "static"),
|
||||
pluginsEnabled: true,
|
||||
plugins: {
|
||||
[pluginId]: { source: "directory", path: pluginDir, enabled: true },
|
||||
},
|
||||
});
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
});
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
expect(client.getLastServerInfoMessage()?.features?.uploadedImageAttachments).toBe(true);
|
||||
|
||||
const pngBytes = Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x42]);
|
||||
const upload = await client.uploadFile({
|
||||
fileName: "plugin-photo.png",
|
||||
mimeType: "image/png",
|
||||
bytes: pngBytes,
|
||||
});
|
||||
expect(upload.error).toBeNull();
|
||||
expect(upload.file).not.toBeNull();
|
||||
const uploadedImageAttachment = { ...upload.file!, role: "image" as const };
|
||||
|
||||
const agent = await client.createAgent({
|
||||
provider: providerId,
|
||||
cwd: tmpCwd(),
|
||||
title: "Plugin vision agent",
|
||||
initialPrompt: "Inspect on create",
|
||||
clientMessageId: "plugin-create-img",
|
||||
attachments: [uploadedImageAttachment],
|
||||
});
|
||||
await client.waitForFinish(agent.id, 10_000);
|
||||
|
||||
await client.sendAgentMessage(agent.id, "Inspect on send", {
|
||||
messageId: "plugin-send-img",
|
||||
attachments: [uploadedImageAttachment],
|
||||
});
|
||||
await client.waitForFinish(agent.id, 10_000);
|
||||
|
||||
await client.sendAgentMessage(agent.id, "Inspect on queue", {
|
||||
messageId: "plugin-queue-img",
|
||||
activeTurnBehavior: "queue",
|
||||
attachments: [uploadedImageAttachment],
|
||||
});
|
||||
await client.waitForFinish(agent.id, 10_000);
|
||||
|
||||
const loggedLines = (await readFile(promptLogPath, "utf8"))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map(
|
||||
(line) =>
|
||||
JSON.parse(line) as { input: { type: string; content: Array<Record<string, unknown>> } },
|
||||
);
|
||||
expect(loggedLines).toHaveLength(3);
|
||||
for (const logged of loggedLines) {
|
||||
expect(logged.input.type).toBe("message");
|
||||
const imageBlocks = logged.input.content.filter((block) => block.type === "image");
|
||||
expect(imageBlocks).toEqual([
|
||||
{
|
||||
type: "image",
|
||||
data: Buffer.from(pngBytes).toString("base64"),
|
||||
mimeType: "image/png",
|
||||
},
|
||||
]);
|
||||
expect(Object.keys(imageBlocks[0]!)).toEqual(["type", "data", "mimeType"]);
|
||||
expect(JSON.stringify(logged)).not.toContain("uploadedImage");
|
||||
expect(JSON.stringify(logged)).not.toContain(upload.file!.path);
|
||||
}
|
||||
|
||||
const timeline = await client.fetchAgentTimeline(agent.id, { projection: "canonical" });
|
||||
for (const clientMessageId of ["plugin-create-img", "plugin-send-img", "plugin-queue-img"]) {
|
||||
const userRow = timeline.entries.find(
|
||||
(entry) =>
|
||||
entry.item.type === "user_message" && entry.item.clientMessageId === clientMessageId,
|
||||
);
|
||||
expect(userRow?.item).toMatchObject({
|
||||
type: "user_message",
|
||||
images: [
|
||||
{
|
||||
id: upload.file!.id,
|
||||
fileName: "plugin-photo.png",
|
||||
mimeType: "image/png",
|
||||
size: pngBytes.byteLength,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("agent.config.apply sets an option that has no control and the next snapshot reports it", async () => {
|
||||
const clients = createTestAgentClients();
|
||||
const codex = clients.codex as AgentClient;
|
||||
|
||||
@@ -17,10 +17,21 @@ import {
|
||||
writePrivateFileAtomicSync,
|
||||
} from "./private-files.js";
|
||||
import { AgentProfileSchema, AgentSkillSelectionSchema } from "@getpaseo/protocol/agent-profile";
|
||||
import { PluginIdSchema, PluginSourceSchema } from "@getpaseo/protocol/plugin-config";
|
||||
import { DirectoryPluginSourceSchema, PluginIdSchema } from "@getpaseo/protocol/plugin-config";
|
||||
import { TerminalProfileSchema } from "@getpaseo/protocol/terminal-profile";
|
||||
import { PaseoServicePortAllocationSchema } from "@getpaseo/protocol/paseo-config-schema";
|
||||
|
||||
// config.json rejects unknown keys so a typo fails at load. The shapes it shares with the
|
||||
// protocol are wire schemas there, which ignore unknown keys, so tighten them here.
|
||||
const ConfigServicePortAllocationSchema = PaseoServicePortAllocationSchema.strict();
|
||||
const ConfigPluginSourceSchema = z.discriminatedUnion("source", [
|
||||
DirectoryPluginSourceSchema.strict(),
|
||||
]);
|
||||
const ConfigAgentSkillSelectionSchema = z.discriminatedUnion("mode", [
|
||||
AgentSkillSelectionSchema.options[0].strict(),
|
||||
AgentSkillSelectionSchema.options[1].strict(),
|
||||
]);
|
||||
|
||||
export const LogLevelSchema = z.enum(["trace", "debug", "info", "warn", "error", "fatal"]);
|
||||
export const LogFormatSchema = z.enum(["pretty", "json"]);
|
||||
|
||||
@@ -70,7 +81,7 @@ const ProvidersSchema = z
|
||||
const WorktreesConfigSchema = z
|
||||
.object({
|
||||
root: z.string().min(1).optional(),
|
||||
servicePorts: PaseoServicePortAllocationSchema.optional(),
|
||||
servicePorts: ConfigServicePortAllocationSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
@@ -365,7 +376,7 @@ export const PersistedConfigSchema = z
|
||||
providers: ProvidersSchema.optional(),
|
||||
pluginRegistries: PluginRegistriesSchema.optional(),
|
||||
pluginsEnabled: z.boolean().optional(),
|
||||
plugins: z.record(PluginIdSchema, PluginSourceSchema).optional(),
|
||||
plugins: z.record(PluginIdSchema, ConfigPluginSourceSchema).optional(),
|
||||
worktrees: WorktreesConfigSchema.optional(),
|
||||
agents: z
|
||||
.object({
|
||||
@@ -375,7 +386,10 @@ export const PersistedConfigSchema = z
|
||||
resumePrompt: z.string().optional(),
|
||||
catalogRefreshTimeoutMs: z.number().int().positive().max(2_147_483_647).optional(),
|
||||
metadataGeneration: AgentMetadataGenerationSchema.optional(),
|
||||
skills: z.object({ selection: AgentSkillSelectionSchema.optional() }).strict().optional(),
|
||||
skills: z
|
||||
.object({ selection: ConfigAgentSkillSelectionSchema.optional() })
|
||||
.strict()
|
||||
.optional(),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
|
||||
@@ -38,7 +38,7 @@ import { fileURLToPath } from "node:url";
|
||||
import type { ZodType } from "zod";
|
||||
import {
|
||||
ProviderCatalogRefreshModeSchema,
|
||||
ProviderEventSchema,
|
||||
parseProviderEvent,
|
||||
type ProviderConnection,
|
||||
type ProviderRegistration,
|
||||
ProviderStatusSchema,
|
||||
@@ -509,11 +509,10 @@ export function createPluginWorker(options: {
|
||||
let unsubscribe = () => {};
|
||||
unsubscribe = connection.onEvent((event) => {
|
||||
try {
|
||||
send({
|
||||
type: "provider.event",
|
||||
connectionId: message.connectionId,
|
||||
event: ProviderEventSchema.parse(jsonTransportValue(event)),
|
||||
});
|
||||
// An event kind this daemon does not know is dropped; a malformed event closes the connection.
|
||||
const parsed = parseProviderEvent(jsonTransportValue(event));
|
||||
if (!parsed) return;
|
||||
send({ type: "provider.event", connectionId: message.connectionId, event: parsed });
|
||||
} catch (error) {
|
||||
providerConnections.delete(message.connectionId);
|
||||
unsubscribe();
|
||||
|
||||
@@ -825,6 +825,92 @@ export default function contribute(server: any) { server.registerProvider(provid
|
||||
await runtime.stopAll();
|
||||
});
|
||||
|
||||
it("drops events of a kind this daemon does not know and keeps the connection", async () => {
|
||||
const directory = await createPlugin(
|
||||
"newer-provider",
|
||||
`import type { ProviderEvent, ProviderRegistration } from "@getpaseo/plugin/server/provider";
|
||||
const provider: ProviderRegistration = {
|
||||
id: "newer",
|
||||
label: "Newer",
|
||||
async connect(request) {
|
||||
const listeners = new Set<(event: ProviderEvent) => void>();
|
||||
const emit = (event: unknown) => {
|
||||
for (const listener of listeners) listener(event as ProviderEvent);
|
||||
};
|
||||
return {
|
||||
version: request.versions[0] ?? 1,
|
||||
capabilities: ["prompt.message"],
|
||||
async send(input) {
|
||||
if (input.type === "session.open") {
|
||||
emit({ type: "session.opened", requestId: input.requestId, sessionId: input.sessionId, capabilities: ["prompt.message"], restoration: "core", cwd: input.config.cwd });
|
||||
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
||||
return;
|
||||
}
|
||||
if (input.type !== "session.prompt") return;
|
||||
emit({ type: "session.hologram", sessionId: input.sessionId, frames: 3 });
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId: input.sessionId,
|
||||
item: { type: "hologram", id: "item-1", frames: 3 },
|
||||
});
|
||||
emit({
|
||||
type: "session.commands",
|
||||
sessionId: input.sessionId,
|
||||
commands: [
|
||||
{ name: "review", description: "Review", kind: "skill" },
|
||||
{ name: "deploy", description: "Deploy", kind: "workflow" },
|
||||
],
|
||||
});
|
||||
},
|
||||
onEvent(listener) { listeners.add(listener); return () => listeners.delete(listener); },
|
||||
async close() {},
|
||||
};
|
||||
},
|
||||
};
|
||||
export default function contribute(server: any) { server.registerProvider(provider); return () => undefined; }`,
|
||||
);
|
||||
const runtime = createTestRuntime();
|
||||
await runtime.startPlugin("newer-provider", directory);
|
||||
const connection = await runtime.connectProvider("newer-provider", "newer", {
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
await connection.send({
|
||||
type: "session.open",
|
||||
requestId: "open-1",
|
||||
sessionId: "session-1",
|
||||
config: { cwd: "/repo", env: {}, mcpServers: {}, settings: {}, persist: true },
|
||||
history: "skip",
|
||||
});
|
||||
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "session-1",
|
||||
prompt: {
|
||||
clientMessageId: "message-1",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "hello" }] },
|
||||
},
|
||||
});
|
||||
|
||||
// Events arrive in order, so the unknown ones before this would already be here.
|
||||
await expect.poll(() => events.at(-1)?.type).toBe("session.commands");
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"session.opened",
|
||||
"session.ready",
|
||||
"session.commands",
|
||||
]);
|
||||
expect(events.at(-1)).toEqual({
|
||||
type: "session.commands",
|
||||
sessionId: "session-1",
|
||||
commands: [{ name: "review", description: "Review", kind: "skill" }],
|
||||
});
|
||||
await connection.close();
|
||||
await runtime.stopAll();
|
||||
});
|
||||
|
||||
it("emits runtime failure for live sessions when a real plugin process dies", async () => {
|
||||
const directory = await createPlugin(
|
||||
"dying-provider",
|
||||
|
||||
@@ -9028,51 +9028,58 @@ export class Session {
|
||||
this.supportsTimelineItem(entry.item, source),
|
||||
);
|
||||
|
||||
this.emitForSource(
|
||||
{
|
||||
type: "fetch_agent_timeline_response",
|
||||
payload: {
|
||||
requestId: msg.requestId,
|
||||
agentId: msg.agentId,
|
||||
agent: agentPayload,
|
||||
direction,
|
||||
projection,
|
||||
epoch: selectedTimeline.timeline.epoch,
|
||||
reset: fetchedControlTimeline.reset,
|
||||
staleCursor: fetchedControlTimeline.staleCursor,
|
||||
gap: fetchedControlTimeline.gap,
|
||||
window: selectedTimeline.timeline.window,
|
||||
startCursor,
|
||||
endCursor,
|
||||
hasOlder: selectedTimeline.hasOlder,
|
||||
hasNewer: selectedTimeline.hasNewer,
|
||||
...(msg.mergeWindow === true ? { mergeWindow: true } : {}),
|
||||
entries: entries.map((entry) => {
|
||||
const payloadEntry = {
|
||||
provider: snapshot.provider,
|
||||
item: entry.item,
|
||||
timestamp: entry.timestamp,
|
||||
seqStart: entry.seqStart,
|
||||
seqEnd: entry.seqEnd,
|
||||
sourceSeqRanges: entry.sourceSeqRanges,
|
||||
turnMetrics: entry.turnMetrics,
|
||||
turnId: undefined as string | undefined,
|
||||
collapsed: (
|
||||
source
|
||||
? this.supportsForSource(CLIENT_CAPS.reasoningMergeEnum, source)
|
||||
: this.supports(CLIENT_CAPS.reasoningMergeEnum)
|
||||
)
|
||||
? entry.collapsed
|
||||
: entry.collapsed.filter((value) => value !== "reasoning_merge"),
|
||||
};
|
||||
payloadEntry.turnId = entry.turnId;
|
||||
return payloadEntry;
|
||||
}),
|
||||
error: null,
|
||||
},
|
||||
const response: SessionOutboundMessage = {
|
||||
type: "fetch_agent_timeline_response",
|
||||
payload: {
|
||||
requestId: msg.requestId,
|
||||
agentId: msg.agentId,
|
||||
agent: agentPayload,
|
||||
direction,
|
||||
projection,
|
||||
epoch: selectedTimeline.timeline.epoch,
|
||||
reset: fetchedControlTimeline.reset,
|
||||
staleCursor: fetchedControlTimeline.staleCursor,
|
||||
gap: fetchedControlTimeline.gap,
|
||||
window: selectedTimeline.timeline.window,
|
||||
startCursor,
|
||||
endCursor,
|
||||
hasOlder: selectedTimeline.hasOlder,
|
||||
hasNewer: selectedTimeline.hasNewer,
|
||||
...(msg.mergeWindow === true ? { mergeWindow: true } : {}),
|
||||
entries: entries.map((entry) => {
|
||||
const payloadEntry = {
|
||||
provider: snapshot.provider,
|
||||
item: entry.item,
|
||||
timestamp: entry.timestamp,
|
||||
seqStart: entry.seqStart,
|
||||
seqEnd: entry.seqEnd,
|
||||
sourceSeqRanges: entry.sourceSeqRanges,
|
||||
turnMetrics: entry.turnMetrics,
|
||||
turnId: undefined as string | undefined,
|
||||
collapsed: (
|
||||
source
|
||||
? this.supportsForSource(CLIENT_CAPS.reasoningMergeEnum, source)
|
||||
: this.supports(CLIENT_CAPS.reasoningMergeEnum)
|
||||
)
|
||||
? entry.collapsed
|
||||
: entry.collapsed.filter((value) => value !== "reasoning_merge"),
|
||||
};
|
||||
payloadEntry.turnId = entry.turnId;
|
||||
return payloadEntry;
|
||||
}),
|
||||
error: null,
|
||||
},
|
||||
source,
|
||||
);
|
||||
};
|
||||
if (source && this.onMessageToSource) {
|
||||
try {
|
||||
await this.onMessageToSource(source, this.delivery.authorizeReply(response, source));
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === "Logical message too large") throw error;
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
this.emit(response);
|
||||
}
|
||||
} catch (error) {
|
||||
this.sessionLogger.error(
|
||||
{ err: error, agentId: msg.agentId },
|
||||
@@ -9533,7 +9540,7 @@ export class Session {
|
||||
try {
|
||||
const agentId = resolved.agentId;
|
||||
|
||||
const prompt = await resolveAgentPrompt({
|
||||
const { prompt, uploadedImages } = await resolveAgentPrompt({
|
||||
paseoHome: this.paseoHome,
|
||||
text: msg.text,
|
||||
images: msg.images,
|
||||
@@ -9563,6 +9570,7 @@ export class Session {
|
||||
recipientId: agentId,
|
||||
messageId: msg.messageId,
|
||||
prompt,
|
||||
...(uploadedImages.length > 0 ? { uploadedImages } : {}),
|
||||
...(msg.sourceAgentId
|
||||
? {
|
||||
source: {
|
||||
@@ -9591,6 +9599,7 @@ export class Session {
|
||||
agentStorage: this.agentStorage,
|
||||
agentId,
|
||||
prompt,
|
||||
...(uploadedImages.length > 0 ? { uploadedImages } : {}),
|
||||
messageId: msg.messageId,
|
||||
activeTurnBehavior: requested === "steer" ? "steer" : "interrupt",
|
||||
sessionMode: msg.sessionMode,
|
||||
@@ -9613,6 +9622,7 @@ export class Session {
|
||||
messageId: msg.messageId,
|
||||
request: {
|
||||
prompt,
|
||||
...(uploadedImages.length > 0 ? { uploadedImages } : {}),
|
||||
sourceAgentId: msg.sourceAgentId,
|
||||
sourceAgentServerId: msg.sourceAgentServerId,
|
||||
sessionMode: msg.sessionMode,
|
||||
|
||||
@@ -19,7 +19,10 @@ export function createTestAgentMessages(params: {
|
||||
params.agentManager.tryRunOutOfBand(
|
||||
request.recipientId,
|
||||
request.prompt,
|
||||
{ clientMessageId: request.messageIds[0] },
|
||||
{
|
||||
clientMessageId: request.messageIds[0],
|
||||
...(request.uploadedImages.length > 0 ? { uploadedImages: request.uploadedImages } : {}),
|
||||
},
|
||||
onAccepted,
|
||||
),
|
||||
isRunning: (agentId) => params.agentManager.hasInFlightRun(agentId),
|
||||
@@ -44,6 +47,7 @@ export function createTestAgentMessages(params: {
|
||||
...params,
|
||||
agentId: request.recipientId,
|
||||
prompt: request.prompt,
|
||||
...(request.uploadedImages.length > 0 ? { uploadedImages: request.uploadedImages } : {}),
|
||||
sessionMode: request.sessionMode,
|
||||
unarchive: request.unarchive,
|
||||
activeTurnBehavior: request.activeTurnBehavior,
|
||||
|
||||
@@ -62,6 +62,10 @@ import { NetworkTunnelService } from "./network-tunnel/index.js";
|
||||
import { asUint8Array, decodeBinaryFrame } from "@getpaseo/protocol/binary-frames/index";
|
||||
import type { TerminalActivity } from "@getpaseo/protocol/terminal-activity";
|
||||
import { MAX_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit";
|
||||
import {
|
||||
safeParseSkippingUnknownVariants,
|
||||
type WirePath,
|
||||
} from "@getpaseo/protocol/validation/unknown-variants";
|
||||
import type { HostnamesConfig } from "./hostnames.js";
|
||||
import { isHostnameAllowed } from "./hostnames.js";
|
||||
import {
|
||||
@@ -779,7 +783,12 @@ export class VoiceAssistantWebSocketServer {
|
||||
agentManager.tryRunOutOfBand(
|
||||
request.recipientId,
|
||||
request.prompt,
|
||||
{ clientMessageId: request.messageIds[0] },
|
||||
{
|
||||
clientMessageId: request.messageIds[0],
|
||||
...(request.uploadedImages.length > 0
|
||||
? { uploadedImages: request.uploadedImages }
|
||||
: {}),
|
||||
},
|
||||
onAccepted,
|
||||
),
|
||||
isRunning: (agentId) => agentManager.hasInFlightRun(agentId),
|
||||
@@ -799,6 +808,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
agentStorage,
|
||||
agentId: batch.recipientId,
|
||||
prompt: batch.prompt,
|
||||
...(batch.uploadedImages.length > 0 ? { uploadedImages: batch.uploadedImages } : {}),
|
||||
activeTurnBehavior: batch.activeTurnBehavior,
|
||||
idleOnly: batch.idleOnly,
|
||||
admit: batch.admit,
|
||||
@@ -2356,6 +2366,8 @@ export class VoiceAssistantWebSocketServer {
|
||||
networkTunnel: true,
|
||||
// COMPAT(providerShownModels): added in v0.18.1, remove gate after 2027-05-28.
|
||||
providerShownModels: true,
|
||||
// COMPAT(uploadedImageAttachments): added in v0.18.2, remove gate after 2027-06-01.
|
||||
uploadedImageAttachments: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -2816,7 +2828,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(buffer.toString());
|
||||
const parsedMessage = WSInboundMessageSchema.safeParse(parsed);
|
||||
const parsedMessage = safeParseSkippingUnknownVariants(WSInboundMessageSchema, parsed);
|
||||
if (!parsedMessage.success) {
|
||||
this.handleInvalidInboundMessage({
|
||||
ws,
|
||||
@@ -2831,6 +2843,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
|
||||
const message = parsedMessage.data;
|
||||
this.recordInboundMessageType(message.type);
|
||||
logSkippedInboundElements(log, message, parsedMessage.skipped);
|
||||
|
||||
if (message.type === "ping" && activeConnection) {
|
||||
// A plugin socket is IPC to a child this daemon already supervises, not
|
||||
@@ -3448,6 +3461,21 @@ function createWebSocketConnectionIdentity(
|
||||
};
|
||||
}
|
||||
|
||||
function logSkippedInboundElements(
|
||||
log: pino.Logger,
|
||||
message: WSInboundMessage,
|
||||
skipped: readonly WirePath[],
|
||||
): void {
|
||||
if (skipped.length === 0) return;
|
||||
log.warn(
|
||||
{
|
||||
messageType: message.type === "session" ? message.message.type : message.type,
|
||||
skipped: skipped.map((path) => path.join(".")),
|
||||
},
|
||||
"Skipped inbound message elements this daemon does not recognize",
|
||||
);
|
||||
}
|
||||
|
||||
function isHandshakeMessage(message: WSInboundMessage): boolean {
|
||||
return message.type === "hello" || message.type === "tunnel_hello";
|
||||
}
|
||||
|
||||
@@ -340,6 +340,46 @@ async function emitTimelineResponse(options?: {
|
||||
return response;
|
||||
}
|
||||
|
||||
test("oversized timeline replies return a correlated error to the requesting source", async () => {
|
||||
const source = {};
|
||||
const replies: SessionOutboundMessage[] = [];
|
||||
let session!: Session;
|
||||
session = createSessionForWireCompatTest({
|
||||
onMessageToSource: async (target, message) => {
|
||||
expect(target).toBe(source);
|
||||
expect(session.delivery.permits(target, message)).toBe(true);
|
||||
replies.push(message);
|
||||
if (replies.length === 1) throw new Error("Logical message too large");
|
||||
},
|
||||
});
|
||||
session.updateClientCapabilities({ owned_subscriptions: true }, source);
|
||||
try {
|
||||
await session.handleMessage(
|
||||
{
|
||||
type: "fetch_agent_timeline_request",
|
||||
requestId: "oversized-request",
|
||||
agentId: "agent-1",
|
||||
direction: "tail",
|
||||
limit: 200,
|
||||
projection: "projected",
|
||||
},
|
||||
source,
|
||||
);
|
||||
expect(replies).toHaveLength(2);
|
||||
expect(replies[1]).toMatchObject({
|
||||
type: "fetch_agent_timeline_response",
|
||||
payload: {
|
||||
requestId: "oversized-request",
|
||||
agentId: "agent-1",
|
||||
entries: [],
|
||||
error: "Logical message too large",
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
describe("wire compatibility", () => {
|
||||
test("sends project updates only to clients that declare support", async () => {
|
||||
const project = createPersistedProjectRecord({
|
||||
|
||||
@@ -2672,11 +2672,19 @@ it.each([false, true])(
|
||||
process.stdout.write(Array.from({ length: count }, nextRow).join(""));
|
||||
}
|
||||
process.stdout.write("READY\\r\\n");
|
||||
// A PTY can split one input write across reads (ConPTY does on Windows),
|
||||
// so match commands against everything read so far, not one chunk.
|
||||
let input = "";
|
||||
process.stdin.on("data", data => {
|
||||
if(data.toString().includes("BURST")) {
|
||||
input += data.toString();
|
||||
if (input.includes("BURST")) {
|
||||
input = "";
|
||||
for (let i = 0; i < 4000; i++) process.stdout.write(nextRow());
|
||||
process.stdout.write("BURST-DONE\\r\\n");
|
||||
} else process.stdout.write("ECHO:" + data.toString() + "\\r\\n");
|
||||
} else if (input.includes("AFTER-CATCH-UP")) {
|
||||
input = "";
|
||||
process.stdout.write("ECHO:AFTER-CATCH-UP\\r\\n");
|
||||
}
|
||||
});
|
||||
setInterval(()=>{},1000);
|
||||
`),
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
Copyright (c) 2025-present Mohamed Boudra
|
||||
|
||||
Portions of this software are licensed as follows:
|
||||
|
||||
* Third-party components incorporated into Paseo remain licensed under
|
||||
the licenses provided by their respective copyright holders.
|
||||
* Except for those third-party components, Paseo is licensed under the
|
||||
Apache License, Version 2.0, reproduced below.
|
||||
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"name": "@getpaseo/workflows",
|
||||
"version": "0.1.0",
|
||||
"description": "Durable, subject-keyed workflow state machine, IR, DSL, and YAML compiler for Paseo",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
"dist",
|
||||
"!dist/**/*.map",
|
||||
"LICENSE"
|
||||
],
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"source": "./src/index.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./ir": {
|
||||
"types": "./dist/ir.d.ts",
|
||||
"source": "./src/ir.ts",
|
||||
"default": "./dist/ir.js"
|
||||
},
|
||||
"./dsl": {
|
||||
"types": "./dist/dsl.d.ts",
|
||||
"source": "./src/dsl.ts",
|
||||
"default": "./dist/dsl.js"
|
||||
},
|
||||
"./yaml": {
|
||||
"types": "./dist/yaml.d.ts",
|
||||
"source": "./src/yaml.ts",
|
||||
"default": "./dist/yaml.js"
|
||||
},
|
||||
"./testing": {
|
||||
"types": "./dist/testing.d.ts",
|
||||
"source": "./src/testing.ts",
|
||||
"default": "./dist/testing.js"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "node ../../scripts/clean-package-dist.mjs",
|
||||
"build": "tsc -p tsconfig.json --incremental false",
|
||||
"build:clean": "npm run clean && npm run build",
|
||||
"prepack": "npm run build:clean",
|
||||
"typecheck": "tsgo --noEmit && tsgo -p tsconfig.typecheck.json --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user