mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 17:55:18 +00:00
Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd4e817951 | ||
|
|
9f999bd570 | ||
|
|
bf10ea8732 | ||
|
|
a8528ad3d2 | ||
|
|
2c661fb076 | ||
|
|
531f6e549d | ||
|
|
e32564f2bc | ||
|
|
0258d6752e | ||
|
|
de5f139d33 | ||
|
|
372c1ba949 | ||
|
|
4dc1730a62 | ||
|
|
2581f2af45 | ||
|
|
6973c48d7e | ||
|
|
9dd0cbc146 | ||
|
|
f088fa5049 | ||
|
|
5dcd1e1e57 | ||
|
|
7ba54499d9 | ||
|
|
cbd5b7a73b | ||
|
|
8e88ce3a56 | ||
|
|
fb59e58ef1 | ||
|
|
825fa04467 | ||
|
|
8338e77f46 | ||
|
|
e5d81304f7 | ||
|
|
6b0fbfc640 | ||
|
|
b4e4803df2 | ||
|
|
3153f6f94a | ||
|
|
ecf8c812cd | ||
|
|
ab4bd6d59d | ||
|
|
2547edefcc | ||
|
|
5c82a2e999 | ||
|
|
60943dde1c | ||
|
|
e52bb6e3c4 | ||
|
|
307f65d8f7 | ||
|
|
163162e9f3 | ||
|
|
4a6b8ae080 | ||
|
|
465db78ab6 | ||
|
|
30a155127d |
@@ -56,6 +56,7 @@ sdk:
|
||||
- "packages/plugin/**"
|
||||
- "plugin-examples/**"
|
||||
- "public-docs/plugins/**"
|
||||
- "skills/paseo-plugin/**"
|
||||
- "packages/client/**"
|
||||
- "packages/highlight/**"
|
||||
- "packages/protocol/**"
|
||||
|
||||
@@ -131,6 +131,29 @@ jobs:
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run typecheck:examples --workspace=@getpaseo/client
|
||||
|
||||
# Plugin process launches and launch wraps quote for cmd.exe, which only real Windows checks.
|
||||
sdk-tests-windows:
|
||||
name: sdk-tests (windows-latest)
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: node scripts/npm-retry.mjs ci
|
||||
|
||||
- name: Build plugin SDK
|
||||
run: npm run build:relay && npm run build:client && npm run build:plugin
|
||||
|
||||
- name: Run plugin SDK tests
|
||||
run: npm run test --workspace=@getpaseo/plugin
|
||||
|
||||
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
|
||||
typecheck:
|
||||
name: typecheck
|
||||
|
||||
+64
-2
@@ -462,8 +462,55 @@ Server entries register async handlers with `server.addHook(name, handler)`, ret
|
||||
function. Names follow `subject.operation.position`, ending in `before` or `after`. Waiting is a per-hook
|
||||
registry property, independent of position. The [hooks reference](../public-docs/plugins/hooks.md)
|
||||
owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved
|
||||
configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on
|
||||
every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
|
||||
configuration; `agent.open.before` contributes launch-only `env`, `tools`, `mcpServers`, and a
|
||||
[launch wrap](#launch-wrap) on every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
|
||||
`packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to
|
||||
each live session. A plugin start, stop, or reload reruns only that plugin's callback per session,
|
||||
swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes
|
||||
the provider process, so a reload must not reopen agents the plugin does not change.
|
||||
|
||||
### Launch wrap
|
||||
|
||||
An `agent.open.before` result can carry `wrap: [executable, ...args]`. The provider then starts that
|
||||
session's harness as `[...wrap, command, ...args]` with the final hook env. It starts with no shell,
|
||||
except Windows script launchers, which go through cmd.exe like any provider launcher
|
||||
(`spawnProcess` quotes each argument). An argument with spaces stays one element. `executable` must
|
||||
be an absolute path.
|
||||
The wrap is never saved on the agent; every open asks the hooks again, and a plugin session reopen
|
||||
reuses the wrap it opened with.
|
||||
|
||||
- **Support is a provider property.** The provider snapshot entry carries `launchWrap: true` when the
|
||||
provider can apply a wrap. Read it in `agent.create.before` with `paseo.providers.snapshot()`; an
|
||||
absent field means unsupported, which is also what a host without this feature reports. Core
|
||||
providers declare it in the provider contract table in `provider-registry.ts`; every core provider
|
||||
that starts a local harness declares it, and custom ACP providers and providers that extend a core
|
||||
one inherit it. A plugin provider declares `ProviderRegistration.launchWrap`;
|
||||
`runAcpProvider({ command })` sets it, a connector declares it itself (Muse Code does). The declaration travels with the
|
||||
registration metadata, so it is in the snapshot before the provider first connects.
|
||||
- **One wrap per open.** A later hook, in the same plugin or a later one, may omit the wrap or return
|
||||
the same value. A different value fails the open.
|
||||
- **Fail closed.** `buildLaunchContext` admits a wrapped open before any session harness starts. It
|
||||
throws `LaunchWrapUnsupportedError` (`code: "launch_wrap_unsupported"`) when the provider does not
|
||||
declare support, or when a plugin provider's live connection lacks `session.launch_wrap`. A host
|
||||
that predates `wrap` rejects the key: the hook result schema is strict. A missing launcher fails the
|
||||
spawn; nothing retries the bare command.
|
||||
|
||||
Once an open selects a wrap, a supported provider runs that session's harness through it or fails
|
||||
before starting the harness. Every provider starts through `spawnProcess({ wrap })`, which owns the
|
||||
argv and Windows launcher handling; `applyLaunchWrap` covers the launches that do not go through it
|
||||
(pty terminals, MCP stdio transports, worktree commands). The wrap also covers what Paseo starts for
|
||||
the session: stdio MCP servers Paseo hosts for the agent (OMP, OpenCode v2), Pi's MCP probe, and ACP
|
||||
client terminals. OpenCode shares one server between sessions, so a wrapped session gets a dedicated
|
||||
server instead; an explicitly configured external OpenCode server cannot be wrapped and the open
|
||||
fails. The guarantee does not cover:
|
||||
|
||||
1. Paseo's host terminal tools (`create_terminal`, `send_terminal_keys`) run outside the wrap.
|
||||
2. Work before the open hook runs unwrapped: draft command and control discovery, and the catalog
|
||||
lookup during create when no model is set.
|
||||
3. Host-side operations run unwrapped: availability and capability probes (the ACP connection's
|
||||
initialize probe included), catalog and session listing, version and update commands, usage
|
||||
queries, and Codex native archive and unarchive.
|
||||
4. Losing the plugin that chose the wrap is not covered: a later open without it runs unwrapped.
|
||||
|
||||
Worktree placement is resolved before Git source planning, so a hook can change the branch and base
|
||||
without undoing fetched refs. Restores use the recorded destination and bypass creation hooks.
|
||||
@@ -483,6 +530,17 @@ change requests; `remove` and `restore` fall back to built-in Git when the plugi
|
||||
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
|
||||
`plugin-examples/worktrunk`.
|
||||
|
||||
`terminal.create.before` runs in `withTerminalCreateHook`, which wraps the daemon's one terminal manager, so every creation path is covered and adopted terminals are not; callers pass an `origin` to name the source. `command.run.before` runs inside the setup and teardown runners through `commandRunHook`. Setup and archive dependencies take `lifecycle` as a required field so a new caller cannot skip the hook by omission; pass `null` only where no plugins run.
|
||||
|
||||
Both hooks change only `env` and a [launch wrap](#launch-wrap); `keepSelectedWrap` in the lifecycle
|
||||
module applies the one-wrap rule to all three wrap hooks. The terminal wrap becomes the terminal's
|
||||
`command` and `args` in `withTerminalCreateHook`, so the terminal worker protocol does not change and
|
||||
no previous-version adapter is needed. A default-shell terminal resolves the shell there through
|
||||
`default-terminal-shell.ts`, which stays apart from `terminal.ts` so the daemon does not load node-pty.
|
||||
The wrapped shell starts without Paseo's shell integration, which is why a wrapped script does not
|
||||
report command completion. A setup or teardown wrap goes in front of the
|
||||
`buildStringCommandShellInvocation` argv.
|
||||
|
||||
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
|
||||
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
|
||||
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
|
||||
@@ -582,6 +640,10 @@ persistence. Re-read credentials and provider-owned configuration on `session.op
|
||||
daemon launch from `connect` and the per-session env and MCP servers from `session.open`. There is
|
||||
no provider reload input.
|
||||
|
||||
Declare `ProviderRegistration.launchWrap: true` when every session spawns its own harness and can
|
||||
run it as `[...config.wrap, command, ...args]`; offer `session.launch_wrap` on the connection. See
|
||||
[Launch wrap](#launch-wrap). `runAcpProvider({ command })` does both.
|
||||
|
||||
For an ACP command, register `runAcpProvider({ id, label, command })` from
|
||||
`@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind`
|
||||
(`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the
|
||||
|
||||
@@ -2,8 +2,10 @@ import { expect, test } from "../support/fixtures";
|
||||
import {
|
||||
applyProfileFromPicker,
|
||||
closeModelPicker,
|
||||
expectAgentProfileNameDraft,
|
||||
expectComposerDoesNotName,
|
||||
expectAgentProfilesEmptyPrompt,
|
||||
expectHostAgentProfiles,
|
||||
expectProfileEditTooltip,
|
||||
expectComposerMode,
|
||||
expectCreateProfileFromModelRow,
|
||||
@@ -14,8 +16,11 @@ import {
|
||||
expectProfileReachableByScrolling,
|
||||
expectProfileSearchResult,
|
||||
expectProfileVisibleForProvider,
|
||||
fillAgentProfileName,
|
||||
openEditProfileFromModelRow,
|
||||
openModelPicker,
|
||||
openAgentProfilesFromEmptyPrompt,
|
||||
removeOpenModalAgentProfileWithConfirm,
|
||||
searchModelPicker,
|
||||
seedAgentProfiles,
|
||||
selectModelRow,
|
||||
@@ -146,10 +151,10 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
await openModelPicker(page);
|
||||
await expectModelRowProfileActionBesideRow(page, oneMinute);
|
||||
await expectCreateProfileFromModelRow(page, oneMinute);
|
||||
await expectComposerModel(page, "Ten second stream");
|
||||
await openModelPicker(page);
|
||||
await selectModelRow(page, oneMinute);
|
||||
await expectComposerModel(page, oneMinute.modelLabel);
|
||||
await openModelPicker(page);
|
||||
await selectModelRow(page, { provider: "mock", modelId: "ten-second-stream" });
|
||||
await expectComposerModel(page, "Ten second stream");
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await seed.restore();
|
||||
@@ -234,4 +239,44 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("canceling Remove in the composer profile editor keeps the editor and draft open", async ({
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([PROFILE]);
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "agent-profiles-remove-cancel-",
|
||||
title: "Agent profiles remove cancel",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
await openModelPicker(page);
|
||||
await openEditProfileFromModelRow(page, {
|
||||
provider: "mock",
|
||||
modelId: "one-minute-stream",
|
||||
});
|
||||
await fillAgentProfileName(page, "Draft name");
|
||||
|
||||
await test.step("canceling Remove keeps the modal and draft intact", async () => {
|
||||
await removeOpenModalAgentProfileWithConfirm(page, "dismiss");
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
|
||||
await expectAgentProfileNameDraft(page, "Draft name");
|
||||
});
|
||||
|
||||
await test.step("confirming Remove deletes the profile and closes the modal", async () => {
|
||||
await removeOpenModalAgentProfileWithConfirm(page, "accept");
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expectHostAgentProfiles([]);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,19 +1,32 @@
|
||||
import { test } from "../support/fixtures";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import {
|
||||
browserBackWithConfirm,
|
||||
browserHistoryJumpWithConfirm,
|
||||
createAgentProfile,
|
||||
createAgentProfileFromEmptyState,
|
||||
duplicateOpenAgentProfileWithConfirm,
|
||||
editAgentProfile,
|
||||
expectAgentProfile,
|
||||
expectAgentProfileForm,
|
||||
expectAgentProfileNameDraft,
|
||||
expectAgentProfileNotesDraft,
|
||||
expectAgentProfileOrder,
|
||||
expectAgentProfileTagsGone,
|
||||
expectHostAgentProfiles,
|
||||
expectNoAgentProfiles,
|
||||
fillAgentProfileName,
|
||||
fillAgentProfileNotes,
|
||||
moveAgentProfileUp,
|
||||
openAgentProfileEditor,
|
||||
openAgentProfileSettings,
|
||||
openCompactAgentProfileSettings,
|
||||
openCreateAgentProfileEditor,
|
||||
removeAgentProfile,
|
||||
saveOpenAgentProfile,
|
||||
seedAgentProfiles,
|
||||
stageLegacyFavoritesForHostMigration,
|
||||
switchSettingsSectionWithConfirm,
|
||||
toggleAgentProfileCustomize,
|
||||
} from "../support/helpers/agent-profiles";
|
||||
|
||||
const MOCK_PROVIDER_LABEL = "Mock Load Test";
|
||||
@@ -125,4 +138,252 @@ test.describe("Agent profiles settings", () => {
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("remounting the profile form keeps draft text across resize and collapsible toggles", async ({
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([
|
||||
{
|
||||
id: "agent_profile_e2e_remount",
|
||||
name: "Original profile",
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
notes: "Original note",
|
||||
},
|
||||
]);
|
||||
|
||||
try {
|
||||
await page.setViewportSize({ width: 1680, height: 900 });
|
||||
await openAgentProfileSettings(page);
|
||||
|
||||
await test.step("drawer-to-modal and compact resizes keep the edited name and save it", async () => {
|
||||
await openAgentProfileEditor(page, "Original profile");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
await fillAgentProfileName(page, "Draft rename");
|
||||
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
|
||||
await expectAgentProfileNameDraft(page, "Draft rename");
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
|
||||
await expectAgentProfileNameDraft(page, "Draft rename");
|
||||
|
||||
await saveOpenAgentProfile(page);
|
||||
await expectAgentProfile(page, {
|
||||
name: "Draft rename",
|
||||
tags: [MOCK_PROVIDER_LABEL, "One minute stream"],
|
||||
notes: "Original note",
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("collapsing and reopening advanced settings keeps the draft note", async () => {
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
await openCreateAgentProfileEditor(page);
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
|
||||
await toggleAgentProfileCustomize(page);
|
||||
await fillAgentProfileNotes(page, "Draft routing note");
|
||||
await toggleAgentProfileCustomize(page);
|
||||
await toggleAgentProfileCustomize(page);
|
||||
await expectAgentProfileNotesDraft(page, "Draft routing note");
|
||||
});
|
||||
} finally {
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("duplicating while editing asks before discarding unsaved changes", async ({ page }) => {
|
||||
const seed = await seedAgentProfiles([
|
||||
{
|
||||
id: "agent_profile_e2e_duplicate",
|
||||
name: "UI work",
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
},
|
||||
]);
|
||||
|
||||
try {
|
||||
await page.setViewportSize({ width: 1680, height: 900 });
|
||||
await openAgentProfileSettings(page);
|
||||
await openAgentProfileEditor(page, "UI work");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
await fillAgentProfileName(page, "Draft name");
|
||||
|
||||
await test.step("dismissing the prompt keeps the draft and does not create a copy", async () => {
|
||||
await duplicateOpenAgentProfileWithConfirm(page, "dismiss");
|
||||
await expectAgentProfileNameDraft(page, "Draft name");
|
||||
await expectAgentProfileOrder(page, ["UI work"]);
|
||||
});
|
||||
|
||||
await test.step("accepting the prompt creates and opens the copy", async () => {
|
||||
await duplicateOpenAgentProfileWithConfirm(page, "accept");
|
||||
await expectAgentProfileOrder(page, ["UI work", "UI work (copy)"]);
|
||||
await expectAgentProfileNameDraft(page, "UI work (copy)");
|
||||
});
|
||||
} finally {
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("docked drawer allows roster search and section switches ask before discarding a draft", async ({
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([
|
||||
{
|
||||
id: "agent_profile_e2e_docked_1",
|
||||
name: "UI work",
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
},
|
||||
{
|
||||
id: "agent_profile_e2e_docked_2",
|
||||
name: "Deep review",
|
||||
provider: "mock",
|
||||
model: "five-minute-stream",
|
||||
},
|
||||
]);
|
||||
|
||||
try {
|
||||
await page.setViewportSize({ width: 1680, height: 900 });
|
||||
await openAgentProfileSettings(page);
|
||||
await openAgentProfileEditor(page, "UI work");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
|
||||
await test.step("typing in roster search works while the docked drawer is open", async () => {
|
||||
const searchInput = page.getByTestId("agent-profiles-search-input");
|
||||
await searchInput.click();
|
||||
await page.keyboard.type("Deep");
|
||||
await expect(searchInput).toHaveValue("Deep");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
await expectAgentProfileOrder(page, ["Deep review"]);
|
||||
await page.getByTestId("agent-profiles-search-clear").click();
|
||||
});
|
||||
|
||||
await test.step("browser Back asks before discarding a draft and canceling keeps route and draft", async () => {
|
||||
await fillAgentProfileName(page, "Unsaved browser back edit");
|
||||
const profilesUrl = page.url();
|
||||
|
||||
await browserBackWithConfirm(page, "dismiss");
|
||||
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
await expectAgentProfileNameDraft(page, "Unsaved browser back edit");
|
||||
});
|
||||
|
||||
await test.step("switching Settings sections asks before discarding an edited draft", async () => {
|
||||
await fillAgentProfileName(page, "Unsaved sidebar edit");
|
||||
|
||||
await switchSettingsSectionWithConfirm(page, "Agents", "dismiss");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
await expectAgentProfileNameDraft(page, "Unsaved sidebar edit");
|
||||
|
||||
await switchSettingsSectionWithConfirm(page, "Agents", "accept");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
|
||||
await expect(page.getByTestId("settings-detail-header-title")).toHaveText("Agents");
|
||||
});
|
||||
|
||||
await test.step("confirming browser Back leaves Agent profiles and discards the draft", async () => {
|
||||
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
|
||||
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||
await openAgentProfileEditor(page, "UI work");
|
||||
await fillAgentProfileName(page, "Discard on browser back");
|
||||
const profilesUrl = page.url();
|
||||
|
||||
await browserBackWithConfirm(page, "accept");
|
||||
await expect(page).not.toHaveURL(profilesUrl, { timeout: 15_000 });
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
|
||||
});
|
||||
} finally {
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("canceling a multi-step Back jump keeps intervening browser history and confirming reaches the destination", async ({
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([
|
||||
{
|
||||
id: "agent_profile_e2e_multistep",
|
||||
name: "UI work",
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
},
|
||||
]);
|
||||
|
||||
try {
|
||||
// Narrow viewport pushes Open project -> Settings -> Agent profiles onto history.
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await openCompactAgentProfileSettings(page);
|
||||
const profilesUrl = page.url();
|
||||
|
||||
await openAgentProfileEditor(page, "UI work");
|
||||
await fillAgentProfileName(page, "Unsaved multi-step edit");
|
||||
|
||||
await test.step("canceling a two-step Back jump keeps Agent profiles, draft, and Settings in history", async () => {
|
||||
await browserHistoryJumpWithConfirm(page, -2, "dismiss");
|
||||
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
|
||||
await expectAgentProfileNameDraft(page, "Unsaved multi-step edit");
|
||||
});
|
||||
|
||||
await test.step("canceling a two-step Back jump after reload still restores the Agent profiles URL", async () => {
|
||||
await page.reload();
|
||||
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||
await openAgentProfileEditor(page, "UI work");
|
||||
await fillAgentProfileName(page, "Post-reload draft");
|
||||
|
||||
await browserHistoryJumpWithConfirm(page, -2, "dismiss");
|
||||
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
|
||||
await expectAgentProfileNameDraft(page, "Post-reload draft");
|
||||
});
|
||||
|
||||
await test.step("confirming a two-step Back jump lands directly on the selected destination", async () => {
|
||||
await browserHistoryJumpWithConfirm(page, -2, "accept");
|
||||
await expect(page).toHaveURL(/\/open-project/, { timeout: 15_000 });
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("forward navigation confirms the intervening Settings entry survived", async () => {
|
||||
await page.goForward();
|
||||
await expect(page).toHaveURL(/\/settings(?:\?|$)/, { timeout: 15_000 });
|
||||
});
|
||||
} finally {
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("canceling an untouched provider-and-model-only profile closes without a discard prompt", async ({
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([
|
||||
{
|
||||
id: "legacy_favorite:mock:one-minute-stream",
|
||||
name: "One minute stream",
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
},
|
||||
]);
|
||||
|
||||
let dialogTriggered = false;
|
||||
const onDialog = async (dialog: { dismiss: () => Promise<void> }) => {
|
||||
dialogTriggered = true;
|
||||
await dialog.dismiss();
|
||||
};
|
||||
page.on("dialog", onDialog);
|
||||
|
||||
try {
|
||||
await page.setViewportSize({ width: 1680, height: 900 });
|
||||
await openAgentProfileSettings(page);
|
||||
await openAgentProfileEditor(page, "One minute stream");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
await page.getByTestId("agent-profile-cancel-button").click();
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
|
||||
expect(dialogTriggered).toBe(false);
|
||||
} finally {
|
||||
page.off("dialog", onDialog);
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import {
|
||||
chooseProjectWithKeyboard,
|
||||
connectNewWorkspaceDaemonClient,
|
||||
expectNewWorkspaceControlsEnabled,
|
||||
expectNewWorkspaceProjectSelected,
|
||||
@@ -176,6 +177,33 @@ test.describe("New workspace entry points", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("choosing a project returns focus to the composer, even when the picker was opened by clicking it", async ({
|
||||
page,
|
||||
}) => {
|
||||
const projectA: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-a-" });
|
||||
const projectB: SeededWorkspace = await seedWorkspace({ repoPrefix: "entry-focus-b-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await openGlobalNewWorkspaceComposer(page);
|
||||
const composer = page.getByRole("textbox", { name: "Message agent..." });
|
||||
|
||||
await page.getByTestId("new-workspace-project-picker-trigger").click();
|
||||
await chooseProjectWithKeyboard(page, projectB.projectDisplayName);
|
||||
await expectNewWorkspaceProjectSelected(page, projectB.projectDisplayName);
|
||||
await expect(composer).toBeFocused();
|
||||
|
||||
await page.keyboard.press("Control+N");
|
||||
await chooseProjectWithKeyboard(page, projectA.projectDisplayName);
|
||||
await expectNewWorkspaceProjectSelected(page, projectA.projectDisplayName);
|
||||
await expect(composer).toBeFocused();
|
||||
} finally {
|
||||
await projectA.cleanup();
|
||||
await projectB.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the in-progress form when the remembered workspace is archived elsewhere", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { expect, test, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
|
||||
import {
|
||||
chooseProjectWithKeyboard,
|
||||
expectNewWorkspaceDraft,
|
||||
fillNewWorkspaceDraft,
|
||||
openNewWorkspaceComposer,
|
||||
@@ -109,6 +110,27 @@ test.describe("New workspace: launching a terminal", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("with a profile that takes no prompt, choosing a project keeps focus on the Project field", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await openNewWorkspaceComposer(page, {
|
||||
projectKey: workspace.projectKey,
|
||||
projectDisplayName: workspace.projectDisplayName,
|
||||
});
|
||||
await selectLaunchOption(page, BARE_PROFILE.id);
|
||||
await expect(terminalPromptInput(page)).toHaveCount(0);
|
||||
|
||||
// The read-only command preview has nothing to type into, so the picker
|
||||
// hands focus back to the field that opened it.
|
||||
const projectTrigger = page.getByTestId("new-workspace-project-picker-trigger");
|
||||
await projectTrigger.focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await chooseProjectWithKeyboard(page, workspace.projectDisplayName);
|
||||
await expect(projectTrigger).toBeFocused();
|
||||
});
|
||||
|
||||
test("switching terminal profiles restores the prompt and its fullscreen affordance", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -372,6 +372,25 @@ test.describe("Plugin sidebar items", () => {
|
||||
await expect(page.getByText("Plugin failed", { exact: false })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("a plugin screen keeps the sidebar toggle before its title", async ({ page }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeVisible({ timeout: 30_000 });
|
||||
await runCommand(page, "Open plugin workspaces");
|
||||
await expect(screenTitle(page)).toHaveText("Workspaces");
|
||||
await page.keyboard.press("ControlOrMeta+b");
|
||||
await expect(page.getByTestId("sidebar-global-new-workspace")).not.toBeVisible();
|
||||
|
||||
await expect(visibleTestId(page, "menu-button")).toBeVisible();
|
||||
const toggle = await boxOf(visibleTestId(page, "menu-button"));
|
||||
const title = await boxOf(screenTitle(page));
|
||||
expect(toggle.x + toggle.width).toBeLessThanOrEqual(title.x);
|
||||
await qaScreenshot(page, "plugin-screen-sidebar-collapsed");
|
||||
|
||||
await visibleTestId(page, "menu-button").click();
|
||||
await expect(page.getByTestId("sidebar-global-new-workspace")).toBeVisible();
|
||||
});
|
||||
|
||||
test("a header row's shortcut hint presses the row", async ({ page }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
|
||||
@@ -15,8 +15,8 @@ press "id=\"model-provider-${PROVIDER_ID}\""
|
||||
wait "id=\"compact-model-list\"" 3000
|
||||
# The row's profile action sits inside Android's independent scroll viewport.
|
||||
press "id=\"model-create-profile-${PROVIDER_ID}-${PROFILE_MODEL_ID}\""
|
||||
wait "text=\"Add agent profile\"" 5000
|
||||
# Closing the form keeps the remembered model: the tap did not also select the row.
|
||||
back
|
||||
wait "id=\"combined-model-selector\" label=\"Select model (${MODEL_LABEL})\"" 3000
|
||||
wait "id=\"model-profile-created-toast\"" 5000
|
||||
# Undo removes the created profile after selecting the model and closing the picker.
|
||||
press "id=\"model-profile-created-undo\""
|
||||
wait "id=\"combined-model-selector\"" 3000
|
||||
close
|
||||
|
||||
@@ -142,8 +142,22 @@ export async function openAgentProfileSettings(page: Page): Promise<void> {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, serverId);
|
||||
await page.getByRole("button", { name: "Agents", exact: true }).click();
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agents"));
|
||||
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agent-profiles"));
|
||||
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
/** Reach agent profiles on a compact viewport so Open project -> Settings -> Agent profiles are pushed. */
|
||||
export async function openCompactAgentProfileSettings(page: Page): Promise<void> {
|
||||
const serverId = getServerId();
|
||||
await gotoAppShell(page);
|
||||
await page.getByRole("button", { name: "Open menu", exact: true }).click();
|
||||
const settingsButton = page.locator('[data-testid="sidebar-settings"]:visible').first();
|
||||
await expect(settingsButton).toBeVisible({ timeout: 30_000 });
|
||||
await settingsButton.click();
|
||||
await expect(page).toHaveURL(/\/settings(?:\?|$)/, { timeout: 30_000 });
|
||||
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agent-profiles"));
|
||||
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
@@ -156,7 +170,9 @@ export async function expectNoAgentProfiles(page: Page): Promise<void> {
|
||||
// ─── Settings: the profile list ────────────────────────────────────────────
|
||||
|
||||
export function agentProfileRow(page: Page, name: string): Locator {
|
||||
return page.locator('[data-testid^="agent-profile-row-"]').filter({ hasText: name });
|
||||
return page
|
||||
.locator('[data-testid^="agent-profile-row-"]')
|
||||
.filter({ has: page.getByText(name, { exact: true }) });
|
||||
}
|
||||
|
||||
export async function expectAgentProfile(
|
||||
@@ -165,7 +181,9 @@ export async function expectAgentProfile(
|
||||
): Promise<void> {
|
||||
const row = agentProfileRow(page, expected.name);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await expect(row.getByText(expected.tags.join(" · "), { exact: true })).toBeVisible();
|
||||
for (const tag of expected.tags) {
|
||||
await expect(row).toContainText(tag);
|
||||
}
|
||||
if (expected.notes !== undefined) {
|
||||
await expect(row.getByText(expected.notes, { exact: true })).toBeVisible();
|
||||
}
|
||||
@@ -177,7 +195,7 @@ export async function expectAgentProfileTagsGone(
|
||||
): Promise<void> {
|
||||
const row = agentProfileRow(page, input.name);
|
||||
for (const tag of input.tags) {
|
||||
await expect(row.getByText(tag, { exact: true })).toHaveCount(0);
|
||||
await expect(row).not.toContainText(tag);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,12 +214,22 @@ export async function expectAgentProfileOrder(page: Page, names: string[]): Prom
|
||||
.toEqual(names);
|
||||
}
|
||||
|
||||
async function openRowActionMenu(page: Page, name: string): Promise<void> {
|
||||
const row = agentProfileRow(page, name);
|
||||
await row.hover();
|
||||
const trigger = row.locator('[data-testid^="agent-profile-menu-"]');
|
||||
await expect(trigger).toBeVisible({ timeout: 15_000 });
|
||||
await trigger.click();
|
||||
}
|
||||
|
||||
export async function moveAgentProfileUp(page: Page, name: string): Promise<void> {
|
||||
await agentProfileRow(page, name).getByRole("button", { name: "Move up", exact: true }).click();
|
||||
await openRowActionMenu(page, name);
|
||||
await page.getByRole("menuitem", { name: "Move up", exact: true }).click();
|
||||
}
|
||||
|
||||
export async function moveAgentProfileDown(page: Page, name: string): Promise<void> {
|
||||
await agentProfileRow(page, name).getByRole("button", { name: "Move down", exact: true }).click();
|
||||
await openRowActionMenu(page, name);
|
||||
await page.getByRole("menuitem", { name: "Move down", exact: true }).click();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -215,12 +243,13 @@ export async function removeAgentProfile(page: Page, name: string): Promise<void
|
||||
await dialog.accept();
|
||||
return message;
|
||||
});
|
||||
await agentProfileRow(page, name).getByRole("button", { name: "Remove", exact: true }).click();
|
||||
await openRowActionMenu(page, name);
|
||||
await page.getByRole("menuitem", { name: "Remove", exact: true }).click();
|
||||
expect(await dialogMessage).toContain(`Remove "${name}"?`);
|
||||
await expect(agentProfileRow(page, name)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
// ─── Settings: the edit modal ──────────────────────────────────────────────
|
||||
// ─── Settings: the inspector drawer / edit sheet ───────────────────────────
|
||||
|
||||
export interface AgentProfileDraft {
|
||||
name?: string;
|
||||
@@ -231,62 +260,96 @@ export interface AgentProfileDraft {
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
function editModal(page: Page): Locator {
|
||||
return page.getByTestId("agent-profile-edit-modal");
|
||||
function editSurface(page: Page): Locator {
|
||||
return page.locator(
|
||||
'[data-testid="agent-profile-drawer"], [data-testid="agent-profile-edit-modal"]',
|
||||
);
|
||||
}
|
||||
|
||||
async function chooseSelectFieldOption(
|
||||
page: Page,
|
||||
input: { field: "provider" | "model" | "mode" | "thinking"; option: string },
|
||||
input: { field: "model" | "mode" | "thinking"; option: string },
|
||||
): Promise<void> {
|
||||
await editModal(page).getByTestId(`agent-profile-${input.field}-trigger`).click();
|
||||
await editSurface(page).getByTestId(`agent-profile-${input.field}-trigger`).click();
|
||||
const option = page
|
||||
.getByTestId("combobox-desktop-container")
|
||||
.getByRole("button", { name: input.option, exact: true });
|
||||
await expect(option).toBeVisible({ timeout: 30_000 });
|
||||
await option.click();
|
||||
await expect(
|
||||
page.getByRole("button", { name: `${capitalize(input.field)} (${input.option})` }),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
function capitalize(value: string): string {
|
||||
return value.charAt(0).toUpperCase() + value.slice(1);
|
||||
async function ensureCustomizeExpanded(surface: Locator): Promise<void> {
|
||||
const toggle = surface.getByTestId("agent-profile-customize-toggle");
|
||||
if ((await toggle.count()) > 0 && (await toggle.isVisible())) {
|
||||
await toggle.click();
|
||||
}
|
||||
}
|
||||
|
||||
async function chooseProfileModel(
|
||||
page: Page,
|
||||
input: { provider?: string; model?: string },
|
||||
): Promise<void> {
|
||||
await editSurface(page).getByTestId("agent-profile-model-trigger").click();
|
||||
const container = page.getByTestId("combobox-desktop-container");
|
||||
await expect(container).toBeVisible({ timeout: 30_000 });
|
||||
if (input.provider) {
|
||||
const providerRow = container.getByRole("button", {
|
||||
name: new RegExp(escapeForRegex(input.provider)),
|
||||
});
|
||||
if ((await providerRow.count()) > 0 && (await providerRow.first().isVisible())) {
|
||||
await providerRow.first().click();
|
||||
}
|
||||
}
|
||||
const targetLabel = input.model ?? input.provider;
|
||||
if (targetLabel) {
|
||||
const option = container
|
||||
.getByRole("button", { name: new RegExp(escapeForRegex(targetLabel)) })
|
||||
.first();
|
||||
await expect(option).toBeVisible({ timeout: 30_000 });
|
||||
await option.click();
|
||||
}
|
||||
}
|
||||
|
||||
async function fillAgentProfileForm(page: Page, draft: AgentProfileDraft): Promise<void> {
|
||||
const modal = editModal(page);
|
||||
const surface = editSurface(page);
|
||||
// Model first: CombinedModelSelector sets provider + model and auto-suggests defaults.
|
||||
if (draft.model !== undefined || draft.provider !== undefined) {
|
||||
await chooseProfileModel(page, { provider: draft.provider, model: draft.model });
|
||||
}
|
||||
if (draft.name !== undefined) {
|
||||
await modal.getByRole("textbox", { name: "Name", exact: true }).fill(draft.name);
|
||||
await surface.getByRole("textbox", { name: "Name", exact: true }).fill(draft.name);
|
||||
}
|
||||
// Provider first: it resets every provider-scoped field below it.
|
||||
if (draft.provider !== undefined) {
|
||||
await chooseSelectFieldOption(page, { field: "provider", option: draft.provider });
|
||||
}
|
||||
// Thinking after model: thinking levels hang off the model, and switching the
|
||||
// model drops a level the new one does not offer.
|
||||
if (draft.model !== undefined) {
|
||||
await chooseSelectFieldOption(page, { field: "model", option: draft.model });
|
||||
}
|
||||
if (draft.thinking !== undefined) {
|
||||
await chooseSelectFieldOption(page, { field: "thinking", option: draft.thinking });
|
||||
if (draft.thinking !== undefined || draft.mode !== undefined || draft.notes !== undefined) {
|
||||
await ensureCustomizeExpanded(surface);
|
||||
}
|
||||
if (draft.mode !== undefined) {
|
||||
await chooseSelectFieldOption(page, { field: "mode", option: draft.mode });
|
||||
}
|
||||
if (draft.thinking !== undefined) {
|
||||
const thinkingContainer = surface.getByTestId("agent-profile-thinking-field");
|
||||
const segmentButton = thinkingContainer.getByRole("button", {
|
||||
name: draft.thinking,
|
||||
exact: true,
|
||||
});
|
||||
if ((await segmentButton.count()) > 0) {
|
||||
await segmentButton.click();
|
||||
} else {
|
||||
await chooseSelectFieldOption(page, { field: "thinking", option: draft.thinking });
|
||||
}
|
||||
}
|
||||
if (draft.notes !== undefined) {
|
||||
await modal.getByRole("textbox", { name: "When to use", exact: true }).fill(draft.notes);
|
||||
await surface.getByRole("textbox", { name: "When to use", exact: true }).fill(draft.notes);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveAgentProfile(page: Page): Promise<void> {
|
||||
await editModal(page).getByRole("button", { name: "Save", exact: true }).click();
|
||||
await expect(editModal(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
await page.getByTestId("agent-profile-save-button").click();
|
||||
await expect(editSurface(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function createAgentProfile(page: Page, draft: AgentProfileDraft): Promise<void> {
|
||||
await page.getByRole("button", { name: "Add agent profile", exact: true }).click();
|
||||
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
|
||||
await page.getByTestId("agent-profiles-add-button").click();
|
||||
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||
await fillAgentProfileForm(page, draft);
|
||||
await saveAgentProfile(page);
|
||||
}
|
||||
@@ -299,7 +362,7 @@ export async function createAgentProfileFromEmptyState(
|
||||
.getByTestId("agent-profiles-card")
|
||||
.getByRole("button", { name: "New profile", exact: true })
|
||||
.click();
|
||||
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
|
||||
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||
await fillAgentProfileForm(page, draft);
|
||||
await saveAgentProfile(page);
|
||||
}
|
||||
@@ -309,46 +372,183 @@ export async function editAgentProfile(
|
||||
name: string,
|
||||
changes: AgentProfileDraft,
|
||||
): Promise<void> {
|
||||
await agentProfileRow(page, name)
|
||||
.getByRole("button", { name: "Edit profile", exact: true })
|
||||
.click();
|
||||
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
|
||||
await agentProfileRow(page, name).click();
|
||||
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||
await fillAgentProfileForm(page, changes);
|
||||
await saveAgentProfile(page);
|
||||
}
|
||||
|
||||
/** Opens the modal for a profile purely to read back what it stored. */
|
||||
export async function openAgentProfileEditor(page: Page, name: string): Promise<void> {
|
||||
await agentProfileRow(page, name).click();
|
||||
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function openCreateAgentProfileEditor(page: Page): Promise<void> {
|
||||
await page.getByTestId("agent-profiles-add-button").click();
|
||||
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function fillAgentProfileName(page: Page, name: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "Name", exact: true }).fill(name);
|
||||
}
|
||||
|
||||
export async function expectAgentProfileNameDraft(page: Page, name: string): Promise<void> {
|
||||
await expect(page.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
|
||||
}
|
||||
|
||||
export async function toggleAgentProfileCustomize(page: Page): Promise<void> {
|
||||
await page.getByTestId("agent-profile-customize-toggle").click();
|
||||
}
|
||||
|
||||
export async function fillAgentProfileNotes(page: Page, notes: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "When to use", exact: true }).fill(notes);
|
||||
}
|
||||
|
||||
export async function expectAgentProfileNotesDraft(page: Page, notes: string): Promise<void> {
|
||||
await expect(page.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(notes);
|
||||
}
|
||||
|
||||
export async function saveOpenAgentProfile(page: Page): Promise<void> {
|
||||
await saveAgentProfile(page);
|
||||
}
|
||||
|
||||
export async function duplicateOpenAgentProfileWithConfirm(
|
||||
page: Page,
|
||||
decision: "accept" | "dismiss",
|
||||
): Promise<void> {
|
||||
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||
const message = dialog.message();
|
||||
if (decision === "accept") {
|
||||
await dialog.accept();
|
||||
} else {
|
||||
await dialog.dismiss();
|
||||
}
|
||||
return message;
|
||||
});
|
||||
await page.getByTestId("agent-profile-drawer-more").click();
|
||||
await page.getByTestId("agent-profile-drawer-duplicate").click();
|
||||
expect(await dialogMessage).toMatch(/discard|unsaved/i);
|
||||
}
|
||||
|
||||
export async function openEditProfileFromModelRow(
|
||||
page: Page,
|
||||
input: { provider: string; modelId: string },
|
||||
): Promise<void> {
|
||||
const row = modelRow(page, input);
|
||||
await row.hover();
|
||||
const editButton = pickerViewport(page).getByTestId(
|
||||
`model-edit-profile-${input.provider}-${input.modelId}`,
|
||||
);
|
||||
await expect(editButton).toBeVisible({ timeout: 30_000 });
|
||||
await editButton.click();
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function removeOpenModalAgentProfileWithConfirm(
|
||||
page: Page,
|
||||
decision: "accept" | "dismiss",
|
||||
): Promise<void> {
|
||||
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||
const message = dialog.message();
|
||||
if (decision === "accept") {
|
||||
await dialog.accept();
|
||||
} else {
|
||||
await dialog.dismiss();
|
||||
}
|
||||
return message;
|
||||
});
|
||||
await page.getByTestId("agent-profile-modal-remove-button").click();
|
||||
expect(await dialogMessage).toMatch(/remove/i);
|
||||
}
|
||||
|
||||
export async function switchSettingsSectionWithConfirm(
|
||||
page: Page,
|
||||
sectionName: string,
|
||||
decision: "accept" | "dismiss",
|
||||
): Promise<void> {
|
||||
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||
const message = dialog.message();
|
||||
if (decision === "accept") {
|
||||
await dialog.accept();
|
||||
} else {
|
||||
await dialog.dismiss();
|
||||
}
|
||||
return message;
|
||||
});
|
||||
await page.getByRole("button", { name: sectionName, exact: true }).click();
|
||||
expect(await dialogMessage).toMatch(/discard|unsaved/i);
|
||||
}
|
||||
|
||||
export async function browserBackWithConfirm(
|
||||
page: Page,
|
||||
decision: "accept" | "dismiss",
|
||||
): Promise<void> {
|
||||
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||
const message = dialog.message();
|
||||
if (decision === "accept") {
|
||||
await dialog.accept();
|
||||
} else {
|
||||
await dialog.dismiss();
|
||||
}
|
||||
return message;
|
||||
});
|
||||
await page.goBack();
|
||||
expect(await dialogMessage).toMatch(/discard|unsaved/i);
|
||||
}
|
||||
|
||||
export async function browserHistoryJumpWithConfirm(
|
||||
page: Page,
|
||||
delta: number,
|
||||
decision: "accept" | "dismiss",
|
||||
): Promise<void> {
|
||||
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||
const message = dialog.message();
|
||||
if (decision === "accept") {
|
||||
await dialog.accept();
|
||||
} else {
|
||||
await dialog.dismiss();
|
||||
}
|
||||
return message;
|
||||
});
|
||||
await page.evaluate((step) => window.history.go(step), delta);
|
||||
expect(await dialogMessage).toMatch(/discard|unsaved/i);
|
||||
}
|
||||
|
||||
/** Opens the inspector for a profile purely to read back what it stored. */
|
||||
export async function expectAgentProfileForm(
|
||||
page: Page,
|
||||
name: string,
|
||||
expected: { provider?: string; model?: string; mode?: string; notes?: string },
|
||||
): Promise<void> {
|
||||
await agentProfileRow(page, name)
|
||||
.getByRole("button", { name: "Edit profile", exact: true })
|
||||
.click();
|
||||
const modal = editModal(page);
|
||||
await expect(modal).toBeVisible({ timeout: 30_000 });
|
||||
await expect(modal.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
|
||||
const notesHint = modal.getByTestId("agent-profile-notes-field-hint");
|
||||
await expect(notesHint).toHaveText(
|
||||
"Helps agents choose this profile when starting another agent.",
|
||||
);
|
||||
await agentProfileRow(page, name).click();
|
||||
const surface = editSurface(page);
|
||||
await expect(surface).toBeVisible({ timeout: 30_000 });
|
||||
await expect(surface.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
|
||||
const notesHint = surface.getByTestId("agent-profile-notes-field-hint");
|
||||
await expect(notesHint).toHaveText("Tells agents when to pick this profile");
|
||||
expect(await notesHint.evaluate((element) => getComputedStyle(element).webkitLineClamp)).not.toBe(
|
||||
"1",
|
||||
);
|
||||
for (const [field, value] of Object.entries(expected)) {
|
||||
if (field === "notes") {
|
||||
await expect(modal.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(
|
||||
value,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
await expect(
|
||||
modal.getByRole("button", { name: `${capitalize(field)} (${value})` }),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
if (expected.model) {
|
||||
await expect(surface.getByTestId("agent-profile-model-trigger")).toContainText(expected.model);
|
||||
} else if (expected.provider) {
|
||||
await expect(surface.getByTestId("agent-profile-model-trigger")).toContainText(
|
||||
expected.provider,
|
||||
);
|
||||
}
|
||||
await modal.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(editModal(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
if (expected.provider) {
|
||||
await expect(surface).toContainText(expected.provider);
|
||||
}
|
||||
if (expected.mode) {
|
||||
await expect(surface.getByTestId("agent-profile-mode-trigger")).toContainText(expected.mode);
|
||||
}
|
||||
if (expected.notes !== undefined) {
|
||||
await expect(surface.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(
|
||||
expected.notes,
|
||||
);
|
||||
}
|
||||
await surface.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(editSurface(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
// ─── The model picker ──────────────────────────────────────────────────────
|
||||
@@ -535,7 +735,10 @@ export async function expectModelRowProfileActionBesideRow(
|
||||
await expect(row.getByRole("button")).toHaveCount(0);
|
||||
}
|
||||
|
||||
/** The hover-revealed plus on an unprofiled model row opens a seeded profile form. */
|
||||
/**
|
||||
* The hover-revealed plus on an unprofiled model row saves the profile,
|
||||
* selects the model immediately, closes the picker, and surfaces an Edit / Undo toast.
|
||||
*/
|
||||
export async function expectCreateProfileFromModelRow(
|
||||
page: Page,
|
||||
input: { provider: string; modelId: string; modelLabel: string },
|
||||
@@ -548,14 +751,14 @@ export async function expectCreateProfileFromModelRow(
|
||||
await modelRow(page, input).hover();
|
||||
await expect(action).toHaveCSS("pointer-events", "auto");
|
||||
await action.click();
|
||||
const modal = editModal(page);
|
||||
await expect(modal).toBeVisible({ timeout: 30_000 });
|
||||
await expect(modal.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(
|
||||
input.modelLabel,
|
||||
);
|
||||
await expect(modal.getByRole("button", { name: `Model (${input.modelLabel})` })).toBeVisible();
|
||||
await modal.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(modal).toHaveCount(0, { timeout: 30_000 });
|
||||
|
||||
const toast = page.getByTestId("model-profile-created-toast");
|
||||
await expect(toast).toBeVisible({ timeout: 30_000 });
|
||||
await expect(toast).toContainText(input.modelLabel);
|
||||
|
||||
// Undo removes the newly saved profile from the toast.
|
||||
await toast.getByTestId("model-profile-created-undo").click();
|
||||
await expect(toast).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function selectModelRow(
|
||||
|
||||
@@ -243,6 +243,14 @@ export async function openNewWorkspaceProjectPickerWithShortcut(
|
||||
await expect(searchInput).toBeFocused();
|
||||
}
|
||||
|
||||
export async function chooseProjectWithKeyboard(page: Page, projectName: string): Promise<void> {
|
||||
const searchInput = page.getByPlaceholder("Search projects");
|
||||
await expect(searchInput).toBeFocused({ timeout: 30_000 });
|
||||
await page.keyboard.type(projectName);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(searchInput).toBeHidden({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
export async function expectNewWorkspaceProjectSelected(
|
||||
page: Page,
|
||||
projectDisplayName: string,
|
||||
|
||||
@@ -1,11 +1,76 @@
|
||||
import { useCallback, useMemo, useState, type ReactElement } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
import { AgentProfileEditModal } from "./settings/agent-profile-edit-modal";
|
||||
import { generateAgentProfileId } from "./internal/profile-id";
|
||||
import type { AgentProfileSeed, AgentProfileValue } from "./internal/profile-form-model";
|
||||
import { useAgentProfiles } from "./internal/use-agent-profiles";
|
||||
import {
|
||||
buildInstantAgentProfile,
|
||||
type AgentProfileSeed,
|
||||
type AgentProfileValue,
|
||||
} from "./internal/profile-form-model";
|
||||
import { removeAgentProfileById, useAgentProfiles } from "./internal/use-agent-profiles";
|
||||
|
||||
const PROFILE_SAVED_TOAST_DURATION_MS = 6000;
|
||||
|
||||
function ProfileSavedToastContent({
|
||||
name,
|
||||
onEdit,
|
||||
onUndo,
|
||||
}: {
|
||||
name: string;
|
||||
onEdit: () => void;
|
||||
onUndo: () => void;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.toastRow}>
|
||||
<Text style={styles.toastText} numberOfLines={1}>
|
||||
{t("modelSelector.profileSaved", { name })}
|
||||
</Text>
|
||||
<View style={styles.toastActions}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onPress={onEdit}
|
||||
accessibilityLabel={t("modelSelector.editProfileLabel", { name })}
|
||||
testID="model-profile-created-edit"
|
||||
>
|
||||
{t("modelSelector.editProfiles")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onPress={onUndo}
|
||||
accessibilityLabel={t("modelSelector.undoProfileSave")}
|
||||
testID="model-profile-created-undo"
|
||||
>
|
||||
{t("modelSelector.undo")}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function createProfileSavedToast(input: {
|
||||
name: string;
|
||||
onEdit: () => void;
|
||||
onUndo: () => void;
|
||||
}): ReactElement {
|
||||
return <ProfileSavedToastContent name={input.name} onEdit={input.onEdit} onUndo={input.onUndo} />;
|
||||
}
|
||||
|
||||
export interface AgentProfileEditorControls {
|
||||
/** Save a profile immediately from a model row with defaults and show an Edit/Undo toast. */
|
||||
quickCreateFromModel: (seed: AgentProfileSeed) => Promise<AgentProfile | null>;
|
||||
/** Undo an instant creation without a confirmation prompt. */
|
||||
undoCreate: (profileId: string) => Promise<void>;
|
||||
/** Open the create form pre-filled with provider, model, and suggested name. */
|
||||
openCreateFromModel: (seed: AgentProfileSeed) => void;
|
||||
/** Open the edit form for one profile. */
|
||||
@@ -23,8 +88,78 @@ type EditorRequest =
|
||||
* never see `saveProfiles` or construct profile records themselves.
|
||||
*/
|
||||
export function useAgentProfileEditor(serverId: string | null): AgentProfileEditorControls {
|
||||
const { profiles, saveProfiles } = useAgentProfiles(serverId);
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const { profiles, mutateProfiles } = useAgentProfiles(serverId);
|
||||
const { entries } = useProvidersSnapshot(serverId, { cwd: null });
|
||||
const [request, setRequest] = useState<EditorRequest | null>(null);
|
||||
const mountedRef = useRef(true);
|
||||
const dismissSavedToastRef = useRef<(() => void) | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
dismissSavedToastRef.current?.();
|
||||
dismissSavedToastRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const undoCreate = useCallback(
|
||||
async (profileId: string): Promise<void> => {
|
||||
try {
|
||||
await mutateProfiles((current) => removeAgentProfileById(current, profileId));
|
||||
} catch (error) {
|
||||
toast.error(toErrorMessage(error));
|
||||
}
|
||||
},
|
||||
[mutateProfiles, toast],
|
||||
);
|
||||
|
||||
const quickCreateFromModel = useCallback(
|
||||
async (seed: AgentProfileSeed): Promise<AgentProfile | null> => {
|
||||
const value = buildInstantAgentProfile({ seed, entries });
|
||||
const created: AgentProfile = { id: generateAgentProfileId(), ...value };
|
||||
try {
|
||||
const written = await mutateProfiles((current) => [...current, created]);
|
||||
if (!written || !mountedRef.current) {
|
||||
return written ? created : null;
|
||||
}
|
||||
dismissSavedToastRef.current?.();
|
||||
let dismiss: (() => void) | null = null;
|
||||
const clearToast = () => {
|
||||
dismiss?.();
|
||||
if (dismissSavedToastRef.current === dismiss) {
|
||||
dismissSavedToastRef.current = null;
|
||||
}
|
||||
};
|
||||
dismiss = toast.show(
|
||||
createProfileSavedToast({
|
||||
name: created.name,
|
||||
onEdit: () => {
|
||||
clearToast();
|
||||
setRequest({ mode: "edit", profile: created });
|
||||
},
|
||||
onUndo: () => {
|
||||
clearToast();
|
||||
void undoCreate(created.id);
|
||||
},
|
||||
}),
|
||||
{
|
||||
variant: "success",
|
||||
durationMs: PROFILE_SAVED_TOAST_DURATION_MS,
|
||||
testID: "model-profile-created-toast",
|
||||
},
|
||||
);
|
||||
dismissSavedToastRef.current = dismiss;
|
||||
return created;
|
||||
} catch (error) {
|
||||
toast.error(toErrorMessage(error));
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[entries, mutateProfiles, toast, undoCreate],
|
||||
);
|
||||
|
||||
const openCreateFromModel = useCallback((seed: AgentProfileSeed) => {
|
||||
setRequest({ mode: "create", seed });
|
||||
@@ -45,15 +180,59 @@ export function useAgentProfileEditor(serverId: string | null): AgentProfileEdit
|
||||
|
||||
const handleSave = useCallback(
|
||||
async (value: AgentProfileValue) => {
|
||||
const current = profiles ?? [];
|
||||
const editing = request?.mode === "edit" ? request.profile : undefined;
|
||||
const next: AgentProfile[] = editing
|
||||
? current.map((entry) => (entry.id === editing.id ? { id: entry.id, ...value } : entry))
|
||||
: [...current, { id: generateAgentProfileId(), ...value }];
|
||||
await saveProfiles(next);
|
||||
setRequest(null);
|
||||
const savedRequest = request;
|
||||
const editing = savedRequest?.mode === "edit" ? savedRequest.profile : undefined;
|
||||
const written = await mutateProfiles((current) =>
|
||||
editing
|
||||
? current.map((entry) => (entry.id === editing.id ? { id: entry.id, ...value } : entry))
|
||||
: [...current, { id: generateAgentProfileId(), ...value }],
|
||||
);
|
||||
if (!written) {
|
||||
return;
|
||||
}
|
||||
setRequest((current) => (current === savedRequest ? null : current));
|
||||
},
|
||||
[profiles, request, saveProfiles],
|
||||
[mutateProfiles, request],
|
||||
);
|
||||
|
||||
const handleRemove = useCallback(
|
||||
(profileId: string) => {
|
||||
const profile = profiles?.find((entry) => entry.id === profileId);
|
||||
if (!profile) {
|
||||
return;
|
||||
}
|
||||
const confirmAndRemove = async () => {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("settings.host.agentProfiles.removeConfirmTitle"),
|
||||
message: t("settings.host.agentProfiles.removeConfirmMessage", { name: profile.name }),
|
||||
confirmLabel: t("settings.host.agentProfiles.remove"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
destructive: true,
|
||||
});
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const updated = await mutateProfiles((current) =>
|
||||
removeAgentProfileById(current, profileId),
|
||||
);
|
||||
if (updated) {
|
||||
setRequest((current) =>
|
||||
current?.mode === "edit" && current.profile.id === profileId ? null : current,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
const detail = toErrorMessage(error);
|
||||
toast.error(
|
||||
detail
|
||||
? `${t("common.errors.unableToSave")}: ${detail}`
|
||||
: t("common.errors.unableToSave"),
|
||||
);
|
||||
}
|
||||
};
|
||||
void confirmAndRemove();
|
||||
},
|
||||
[mutateProfiles, profiles, t, toast],
|
||||
);
|
||||
|
||||
const element = useMemo(
|
||||
@@ -66,13 +245,34 @@ export function useAgentProfileEditor(serverId: string | null): AgentProfileEdit
|
||||
{...(request?.mode === "create" && request.seed ? { seed: request.seed } : {})}
|
||||
onClose={close}
|
||||
onSave={handleSave}
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
),
|
||||
[close, handleSave, request, serverId],
|
||||
[close, handleRemove, handleSave, request, serverId],
|
||||
);
|
||||
|
||||
return useMemo(
|
||||
() => ({ openCreateFromModel, openEdit, element }),
|
||||
[openCreateFromModel, openEdit, element],
|
||||
() => ({ quickCreateFromModel, undoCreate, openCreateFromModel, openEdit, element }),
|
||||
[element, openCreateFromModel, openEdit, quickCreateFromModel, undoCreate],
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
toastRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[3],
|
||||
maxWidth: "100%",
|
||||
},
|
||||
toastText: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
toastActions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1.5],
|
||||
flexShrink: 0,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -27,4 +27,7 @@ export {
|
||||
type DraftAgentProfileControls,
|
||||
} from "./internal/use-agent-profile-picker";
|
||||
export { AgentProfileGlyph } from "./internal/agent-profile-glyph";
|
||||
export { AgentProfilesSection } from "./settings/agent-profiles-section";
|
||||
export {
|
||||
AgentProfilesPage,
|
||||
type AgentProfilesBeforeLeaveGuard,
|
||||
} from "./settings/agent-profiles-section";
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
TestTube,
|
||||
Wrench,
|
||||
} from "lucide-react-native";
|
||||
import { useProviderIcon } from "@/components/provider-icons";
|
||||
import { identityForeground } from "@/styles/identity-colors";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import {
|
||||
@@ -108,21 +109,57 @@ export function agentProfileColorMapping(
|
||||
return COLOR_MAPPINGS[color];
|
||||
}
|
||||
|
||||
function ProviderFallbackIcon({
|
||||
provider,
|
||||
serverId,
|
||||
size,
|
||||
color = "",
|
||||
}: {
|
||||
provider: string;
|
||||
serverId?: string | null;
|
||||
size: number;
|
||||
color?: string;
|
||||
}) {
|
||||
const Icon = useProviderIcon(provider, serverId);
|
||||
return <Icon size={size} color={color} />;
|
||||
}
|
||||
|
||||
const ThemedProviderFallbackIcon = withUnistyles(ProviderFallbackIcon);
|
||||
|
||||
/**
|
||||
* How a profile is drawn everywhere it appears — settings list, model picker,
|
||||
* and the picker grid's own cells. One component so the three can't drift.
|
||||
* How a profile is drawn everywhere it appears — settings roster, model picker,
|
||||
* drawer/sheet header, and the picker grid's own cells. When no custom icon is
|
||||
* chosen and a provider is known, it falls back to that provider's mark instead
|
||||
* of repeating identical generic stars across every row.
|
||||
*/
|
||||
export function AgentProfileGlyph({
|
||||
icon,
|
||||
color,
|
||||
provider,
|
||||
serverId,
|
||||
size = ICON_SIZE.md,
|
||||
}: {
|
||||
icon?: string | undefined;
|
||||
color?: string | undefined;
|
||||
provider?: string | undefined;
|
||||
serverId?: string | null | undefined;
|
||||
size?: number;
|
||||
}) {
|
||||
const iconKey = resolveAgentProfileIconKey(icon);
|
||||
const mapping = COLOR_MAPPINGS[resolveAgentProfileColor(color)];
|
||||
const Icon = iconKey ? THEMED_ICONS[iconKey] : ThemedDefaultIcon;
|
||||
return <Icon size={size} uniProps={mapping} />;
|
||||
if (iconKey) {
|
||||
const Icon = THEMED_ICONS[iconKey];
|
||||
return <Icon size={size} uniProps={mapping} />;
|
||||
}
|
||||
if (provider) {
|
||||
return (
|
||||
<ThemedProviderFallbackIcon
|
||||
provider={provider}
|
||||
serverId={serverId}
|
||||
size={size}
|
||||
uniProps={mapping}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <ThemedDefaultIcon size={size} uniProps={mapping} />;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildControlsRequestKey,
|
||||
buildInstantAgentProfile,
|
||||
openAgentProfileForm,
|
||||
type AgentProfileFormModel,
|
||||
} from "./profile-form-model";
|
||||
@@ -70,6 +71,10 @@ function optionValues(options: readonly { value: string }[]): string[] {
|
||||
return options.map((option) => option.value);
|
||||
}
|
||||
|
||||
function optionIds(options: readonly { id: string }[]): string[] {
|
||||
return options.map((option) => option.id);
|
||||
}
|
||||
|
||||
const FAST = {
|
||||
controls: [{ type: "toggle" as const, key: "fast_mode", label: "Fast" }],
|
||||
options: { fast_mode: false },
|
||||
@@ -528,16 +533,71 @@ describe("openAgentProfileForm", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("draws no controls for the previous model while another model's answer is pending", () => {
|
||||
it("keeps previous provider controls mounted while another model's answer is pending to prevent layout jank", () => {
|
||||
const model = openWithCatalog({ mode: "create" });
|
||||
selectClaude(model);
|
||||
model.applyControls(model.getState().controlsRequestKey ?? "", WEB_SEARCH_CONTROLS);
|
||||
|
||||
model.setModel("claude-haiku-4-5", { label: "Haiku 4.5" });
|
||||
|
||||
expect(model.getState().controlsResolution).toBe("pending");
|
||||
expect(model.getState().controlsPending).toBe(true);
|
||||
expect(model.getState().controls).toHaveLength(1);
|
||||
|
||||
// Switching providers clears controls immediately so stale controls never cross providers.
|
||||
model.setProvider("codex", { label: "Codex" });
|
||||
expect(model.getState().controls).toEqual([]);
|
||||
});
|
||||
|
||||
it("seeds the catalog synchronously when entries are passed in the initial snapshot", () => {
|
||||
const model = openAgentProfileForm({
|
||||
mode: "edit",
|
||||
profile: { id: "p1", name: "UI work", provider: "claude", model: "claude-opus-5" },
|
||||
entries: ENTRIES,
|
||||
});
|
||||
const state = model.getState();
|
||||
|
||||
expect(state.catalogResolution).toBe("complete");
|
||||
expect(state.providerDisplay).toEqual({ label: "Claude Code" });
|
||||
expect(state.modelDisplay).toEqual({ label: "Opus 5" });
|
||||
expect(optionIds(state.unifiedModelOptions)).toEqual([
|
||||
"claude:claude-opus-5",
|
||||
"claude:claude-haiku-4-5",
|
||||
"codex:gpt-5.2-codex",
|
||||
]);
|
||||
});
|
||||
|
||||
it("updates provider, model, and auto-suggested name together via setProviderModel", () => {
|
||||
const model = openAgentProfileForm({ mode: "create", entries: ENTRIES });
|
||||
|
||||
model.setProviderModel("claude", "claude-opus-5", {
|
||||
provider: { label: "Claude Code" },
|
||||
model: { label: "Opus 5" },
|
||||
});
|
||||
expect(model.getState().name).toBe("Opus 5");
|
||||
expect(model.getState().provider).toBe("claude");
|
||||
expect(model.getState().modelId).toBe("claude-opus-5");
|
||||
expect(model.getState().modeId).toBe("plan");
|
||||
expect(model.getState().thinkingOptionId).toBe("think");
|
||||
|
||||
// Switching to another model while untouched updates the suggested name.
|
||||
model.setProviderModel("codex", "gpt-5.2-codex", {
|
||||
provider: { label: "Codex" },
|
||||
model: { label: "GPT-5.2 Codex" },
|
||||
});
|
||||
expect(model.getState().name).toBe("GPT-5.2 Codex");
|
||||
expect(model.getState().provider).toBe("codex");
|
||||
expect(model.getState().modeId).toBe("read-only");
|
||||
|
||||
// Once the user types a custom name, changing model preserves it.
|
||||
model.setName("My Custom Worker");
|
||||
model.setProviderModel("claude", "claude-haiku-4-5", {
|
||||
provider: { label: "Claude Code" },
|
||||
model: { label: "Haiku 4.5" },
|
||||
});
|
||||
expect(model.getState().name).toBe("My Custom Worker");
|
||||
});
|
||||
|
||||
it("does not save a toggle once the model that drew it is replaced by one without it", () => {
|
||||
const model = toggledOnOpus();
|
||||
expect(model.getState().submitValue?.options).toEqual({ fast_mode: true });
|
||||
@@ -643,6 +703,36 @@ describe("openAgentProfileForm", () => {
|
||||
expect(notifications).toBe(1);
|
||||
expect(model.getState().name).toBe("a");
|
||||
});
|
||||
|
||||
it("does not treat catalog-prefilled defaults on a minimal profile as an unsaved edit", () => {
|
||||
const model = openAgentProfileForm({
|
||||
mode: "edit",
|
||||
profile: {
|
||||
id: "legacy_favorite:claude:claude-opus-5",
|
||||
name: "Opus 5",
|
||||
provider: "claude",
|
||||
model: "claude-opus-5",
|
||||
},
|
||||
});
|
||||
expect(model.getState().isDirty).toBe(false);
|
||||
|
||||
// Catalog fills in default modeId ("plan") and thinkingOptionId ("think").
|
||||
model.applyProviderCatalog(ENTRIES);
|
||||
expect(model.getState().modeId).toBe("plan");
|
||||
expect(model.getState().thinkingOptionId).toBe("think");
|
||||
expect(model.getState().isDirty).toBe(false);
|
||||
|
||||
// User edit marks dirty and advances draftRevision; a subsequent edit advances it again.
|
||||
expect(model.getState().draftRevision).toBe(0);
|
||||
model.setName("Renamed");
|
||||
expect(model.getState().isDirty).toBe(true);
|
||||
expect(model.getState().draftRevision).toBe(1);
|
||||
model.setName("Renamed again");
|
||||
expect(model.getState().draftRevision).toBe(2);
|
||||
model.setName("Opus 5");
|
||||
expect(model.getState().isDirty).toBe(false);
|
||||
expect(model.getState().draftRevision).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildControlsRequestKey", () => {
|
||||
@@ -657,3 +747,55 @@ describe("buildControlsRequestKey", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildInstantAgentProfile", () => {
|
||||
it("builds a concrete profile with provider defaults from a model seed", () => {
|
||||
expect(
|
||||
buildInstantAgentProfile({
|
||||
seed: { provider: "claude", modelId: "claude-opus-5", name: "Opus 5" },
|
||||
entries: ENTRIES,
|
||||
}),
|
||||
).toEqual({
|
||||
name: "Opus 5",
|
||||
provider: "claude",
|
||||
model: "claude-opus-5",
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "think",
|
||||
options: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps compatible preferred mode and thinking levels and ignores incompatible ones", () => {
|
||||
expect(
|
||||
buildInstantAgentProfile({
|
||||
seed: { provider: "claude", modelId: "claude-opus-5" },
|
||||
entries: ENTRIES,
|
||||
preferredModeId: "accept-edits",
|
||||
preferredThinkingOptionId: "think-hard",
|
||||
}),
|
||||
).toEqual({
|
||||
name: "Opus 5",
|
||||
provider: "claude",
|
||||
model: "claude-opus-5",
|
||||
modeId: "accept-edits",
|
||||
thinkingOptionId: "think-hard",
|
||||
options: {},
|
||||
});
|
||||
|
||||
expect(
|
||||
buildInstantAgentProfile({
|
||||
seed: { provider: "claude", modelId: "claude-haiku-4-5" },
|
||||
entries: ENTRIES,
|
||||
preferredModeId: "unknown-mode",
|
||||
preferredThinkingOptionId: "think-hard",
|
||||
}),
|
||||
).toEqual({
|
||||
name: "Haiku 4.5",
|
||||
provider: "claude",
|
||||
model: "claude-haiku-4-5",
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "think",
|
||||
options: {},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -41,6 +41,16 @@ export interface AgentProfileFormOption {
|
||||
testID: string;
|
||||
}
|
||||
|
||||
export interface AgentProfileUnifiedModelOption {
|
||||
id: string;
|
||||
provider: string;
|
||||
providerLabel: string;
|
||||
modelId: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
testID: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-fill values for create mode. Only used when `mode === "create"`; edit
|
||||
* mode always seeds from the stored `profile` and ignores this.
|
||||
@@ -55,6 +65,8 @@ export interface AgentProfileFormSnapshot {
|
||||
mode: "create" | "edit";
|
||||
profile?: AgentProfile;
|
||||
seed?: AgentProfileSeed;
|
||||
/** Optional cached host catalog so the first render is already hydrated without a layout flash. */
|
||||
entries?: readonly ProviderSnapshotEntry[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -97,6 +109,7 @@ export interface AgentProfileFormState {
|
||||
optionEdits: ProviderOptions;
|
||||
|
||||
providerOptions: AgentProfileFormOption[];
|
||||
unifiedModelOptions: AgentProfileUnifiedModelOption[];
|
||||
modelOptions: AgentProfileFormOption[];
|
||||
modeOptions: AgentProfileFormOption[];
|
||||
thinkingOptions: AgentProfileFormOption[];
|
||||
@@ -115,10 +128,14 @@ export interface AgentProfileFormState {
|
||||
|
||||
catalogResolution: AgentProfileResolutionStatus;
|
||||
controlsResolution: AgentProfileResolutionStatus;
|
||||
controlsPending: boolean;
|
||||
controlsRequest: AgentProfileControlsRequest | null;
|
||||
controlsRequestKey: string | null;
|
||||
|
||||
disclosure: AgentProfileFormDisclosure;
|
||||
isDirty: boolean;
|
||||
/** Monotonic counter incremented on every user edit that changes the draft. */
|
||||
draftRevision: number;
|
||||
isSubmitting: boolean;
|
||||
submitError: string | null;
|
||||
canSubmit: boolean;
|
||||
@@ -142,6 +159,11 @@ export interface AgentProfileFormModel {
|
||||
setAppearance: (value: { icon: string; color: string }) => void;
|
||||
setNotes: (value: string) => void;
|
||||
setProvider: (providerId: string, display: AgentProfileFormDisplay) => void;
|
||||
setProviderModel: (
|
||||
providerId: string,
|
||||
modelId: string,
|
||||
displays: { provider: AgentProfileFormDisplay; model: AgentProfileFormDisplay | null },
|
||||
) => void;
|
||||
setModel: (modelId: string, display: AgentProfileFormDisplay | null) => void;
|
||||
setMode: (modeId: string, display: AgentProfileFormDisplay | null) => void;
|
||||
setThinking: (thinkingOptionId: string, display: AgentProfileFormDisplay | null) => void;
|
||||
@@ -224,6 +246,53 @@ function buildProviderOptions(entries: readonly ProviderSnapshotEntry[]): AgentP
|
||||
);
|
||||
}
|
||||
|
||||
function formatUnifiedModelDescription(providerLabel: string, model: AgentModelDefinition): string {
|
||||
if (model.description && model.description !== providerLabel) {
|
||||
return `${providerLabel} · ${model.description}`;
|
||||
}
|
||||
if (model.id !== model.label) {
|
||||
return `${providerLabel} · ${model.id}`;
|
||||
}
|
||||
return providerLabel;
|
||||
}
|
||||
|
||||
function buildUnifiedModelOptions(
|
||||
entries: readonly ProviderSnapshotEntry[],
|
||||
): AgentProfileUnifiedModelOption[] {
|
||||
const options: AgentProfileUnifiedModelOption[] = [];
|
||||
for (const entry of entries) {
|
||||
if (!entry.enabled) {
|
||||
continue;
|
||||
}
|
||||
const providerLabel = entry.label ?? entry.provider;
|
||||
const models = filterSelectableModels(entry.models ?? null) ?? [];
|
||||
if (models.length === 0) {
|
||||
options.push({
|
||||
id: `${entry.provider}:`,
|
||||
provider: entry.provider,
|
||||
providerLabel,
|
||||
modelId: "",
|
||||
label: providerLabel,
|
||||
...(entry.description ? { description: entry.description } : {}),
|
||||
testID: `agent-profile-unified-model-${entry.provider}`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
for (const model of models) {
|
||||
options.push({
|
||||
id: `${entry.provider}:${model.id}`,
|
||||
provider: entry.provider,
|
||||
providerLabel,
|
||||
modelId: model.id,
|
||||
label: model.label,
|
||||
description: formatUnifiedModelDescription(providerLabel, model),
|
||||
testID: `agent-profile-unified-model-${entry.provider}-${model.id}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function buildModelOptions(models: readonly AgentModelDefinition[]): AgentProfileFormOption[] {
|
||||
return models.map((model) =>
|
||||
formOption({
|
||||
@@ -385,6 +454,28 @@ export function buildControlsRequestKey(
|
||||
: scope;
|
||||
}
|
||||
|
||||
function stableOptionsKey(record: ProviderOptions): string {
|
||||
const keys = Object.keys(record).sort();
|
||||
if (keys.length === 0) {
|
||||
return "";
|
||||
}
|
||||
return JSON.stringify(keys.map((key) => [key, record[key]]));
|
||||
}
|
||||
|
||||
function formDraftFingerprint(state: AgentProfileFormState): string {
|
||||
return JSON.stringify([
|
||||
state.name.trim(),
|
||||
state.icon,
|
||||
state.color,
|
||||
state.provider,
|
||||
state.modelId,
|
||||
state.modeId,
|
||||
state.thinkingOptionId,
|
||||
state.notes.trim(),
|
||||
stableOptionsKey(ownOptionsOf(state)),
|
||||
]);
|
||||
}
|
||||
|
||||
function buildSubmitValue(state: AgentProfileFormState): AgentProfileValue | null {
|
||||
const name = state.name.trim();
|
||||
const notes = state.notes.trim();
|
||||
@@ -446,6 +537,7 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
||||
options: { ...profile.options },
|
||||
optionEdits: {},
|
||||
providerOptions: [],
|
||||
unifiedModelOptions: [],
|
||||
modelOptions: [],
|
||||
modeOptions: [],
|
||||
thinkingOptions: [],
|
||||
@@ -459,6 +551,7 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
||||
thinkingDisplay: seedDisplay(profile.thinkingOptionId),
|
||||
catalogResolution: "idle",
|
||||
controlsResolution: "idle",
|
||||
controlsPending: false,
|
||||
controlsRequest: null,
|
||||
controlsRequestKey: null,
|
||||
disclosure: {
|
||||
@@ -467,6 +560,8 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
||||
showThinkingField: false,
|
||||
showControlsField: false,
|
||||
},
|
||||
isDirty: false,
|
||||
draftRevision: 0,
|
||||
isSubmitting: false,
|
||||
submitError: null,
|
||||
canSubmit: false,
|
||||
@@ -474,17 +569,118 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
||||
};
|
||||
}
|
||||
|
||||
function pickMatchingId(
|
||||
preferred: string | null | undefined,
|
||||
options: readonly { id: string }[],
|
||||
fallback: string,
|
||||
): string {
|
||||
const trimmed = preferred?.trim() ?? "";
|
||||
if (trimmed && options.some((option) => option.id === trimmed)) {
|
||||
return trimmed;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a ready-to-save profile in one tap (for composer model-row `+` creation).
|
||||
* Resolves defaults from the host catalog and preserves compatible composer mode/thinking
|
||||
* when provided, so the stored profile is concrete from the moment it is created.
|
||||
*/
|
||||
export function buildInstantAgentProfile(input: {
|
||||
seed: AgentProfileSeed;
|
||||
entries: readonly ProviderSnapshotEntry[] | undefined;
|
||||
preferredModeId?: string | null;
|
||||
preferredThinkingOptionId?: string | null;
|
||||
}): AgentProfileValue {
|
||||
const entries = input.entries ?? [];
|
||||
const entry = findEntry(entries, input.seed.provider);
|
||||
const models = resolveModels(entries, input.seed.provider);
|
||||
const modes = resolveModes(entries, input.seed.provider);
|
||||
const modelId = input.seed.modelId?.trim() || defaultModelId(models);
|
||||
const effectiveModel = resolveEffectiveModel(models, modelId);
|
||||
const matchedModel = models.find((candidate) => candidate.id === modelId);
|
||||
const modeId = pickMatchingId(input.preferredModeId, modes, defaultModeId(entry, modes));
|
||||
const thinkingOptionId = pickMatchingId(
|
||||
input.preferredThinkingOptionId,
|
||||
effectiveModel?.thinkingOptions ?? [],
|
||||
defaultThinkingOptionId(effectiveModel),
|
||||
);
|
||||
const name =
|
||||
[input.seed.name?.trim(), matchedModel?.label, modelId, entry?.label, input.seed.provider].find(
|
||||
(candidate): candidate is string => Boolean(candidate),
|
||||
) ?? input.seed.provider;
|
||||
|
||||
return {
|
||||
name,
|
||||
provider: input.seed.provider,
|
||||
...(modelId ? { model: modelId } : {}),
|
||||
...(modeId ? { modeId } : {}),
|
||||
...(thinkingOptionId ? { thinkingOptionId } : {}),
|
||||
options: {},
|
||||
};
|
||||
}
|
||||
|
||||
function resolveModeLabel(modes: readonly AgentMode[], modeId: string): string | null {
|
||||
const mode = modes.find((entry) => entry.id === modeId);
|
||||
return mode ? formatAgentModeLabel(mode) : null;
|
||||
}
|
||||
|
||||
function resolveThinkingLabel(options: readonly AgentSelectOption[], id: string): string | null {
|
||||
const option = options.find((entry) => entry.id === id);
|
||||
return option ? formatThinkingOptionLabel(option) : null;
|
||||
}
|
||||
|
||||
function resolveControlsSlice(input: {
|
||||
next: AgentProfileFormState;
|
||||
controlsRequestKey: string | null;
|
||||
controlsScopeKey: string | null;
|
||||
resolvedControlsKey: string | null;
|
||||
resolvedScopeKey: string | null;
|
||||
resolvedProvider: string | null;
|
||||
resolvedControls: AgentOptionControl[];
|
||||
resolvedOptions: ProviderOptions;
|
||||
}): {
|
||||
controls: AgentOptionControl[];
|
||||
controlOptions: ProviderOptions;
|
||||
controlsResolution: AgentProfileResolutionStatus;
|
||||
} {
|
||||
const featuresAreCurrent =
|
||||
input.controlsRequestKey !== null && input.controlsRequestKey === input.resolvedControlsKey;
|
||||
const controlsApply =
|
||||
input.controlsScopeKey !== null &&
|
||||
(input.controlsScopeKey === input.resolvedScopeKey ||
|
||||
(input.next.provider.length > 0 && input.next.provider === input.resolvedProvider));
|
||||
const controls = controlsApply ? input.resolvedControls : [];
|
||||
let controlOptions: ProviderOptions = input.next.options;
|
||||
if (controlsApply) {
|
||||
controlOptions = featuresAreCurrent
|
||||
? input.resolvedOptions
|
||||
: { ...input.resolvedOptions, ...input.next.optionEdits };
|
||||
}
|
||||
return {
|
||||
controls,
|
||||
controlOptions,
|
||||
controlsResolution: resolveControlsStatus(input.controlsRequestKey, featuresAreCurrent),
|
||||
};
|
||||
}
|
||||
|
||||
export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentProfileFormModel {
|
||||
let entries: readonly ProviderSnapshotEntry[] = [];
|
||||
let catalogResolution: AgentProfileResolutionStatus = "idle";
|
||||
let entries: readonly ProviderSnapshotEntry[] = snapshot.entries ? [...snapshot.entries] : [];
|
||||
let catalogResolution: AgentProfileResolutionStatus = snapshot.entries ? "complete" : "idle";
|
||||
let resolvedControlsKey: string | null = null;
|
||||
let resolvedScopeKey: string | null = null;
|
||||
let resolvedProvider: string | null = null;
|
||||
let resolvedControls: AgentOptionControl[] = [];
|
||||
let resolvedOptions: ProviderOptions = {};
|
||||
let drawnKeys: ReadonlySet<string> = new Set();
|
||||
let answeredKeys: ReadonlySet<string> = new Set();
|
||||
let listeners = new Set<() => void>();
|
||||
let closed = false;
|
||||
let hasUserEdited = false;
|
||||
let draftRevision = 0;
|
||||
let baselineFingerprint = "";
|
||||
let autoSuggestedName: string | null =
|
||||
snapshot.mode === "create" ? (snapshot.seed?.name ?? null) : null;
|
||||
|
||||
function derive(incoming: AgentProfileFormState): AgentProfileFormState {
|
||||
const models = resolveModels(entries, incoming.provider);
|
||||
@@ -502,24 +698,21 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
const controlsRequest = buildControlsRequest(next);
|
||||
const controlsRequestKey = buildControlsRequestKey(controlsRequest);
|
||||
const controlsScopeKey = buildControlsScopeKey(controlsRequest);
|
||||
const featuresAreCurrent =
|
||||
controlsRequestKey !== null && controlsRequestKey === resolvedControlsKey;
|
||||
// A toggle changes only the options, so the controls stay up while the daemon answers and the
|
||||
// toggle shows over the last answer. A change of provider, model, mode or thinking draws none
|
||||
// until its own answer arrives.
|
||||
const controlsApply = controlsScopeKey !== null && controlsScopeKey === resolvedScopeKey;
|
||||
const controls = controlsApply ? resolvedControls : [];
|
||||
let controlOptions: ProviderOptions = next.options;
|
||||
if (controlsApply) {
|
||||
controlOptions = featuresAreCurrent
|
||||
? resolvedOptions
|
||||
: { ...resolvedOptions, ...next.optionEdits };
|
||||
}
|
||||
const controlsResolution = resolveControlsStatus(controlsRequestKey, featuresAreCurrent);
|
||||
const { controls, controlOptions, controlsResolution } = resolveControlsSlice({
|
||||
next,
|
||||
controlsRequestKey,
|
||||
controlsScopeKey,
|
||||
resolvedControlsKey,
|
||||
resolvedScopeKey,
|
||||
resolvedProvider,
|
||||
resolvedControls,
|
||||
resolvedOptions,
|
||||
});
|
||||
|
||||
const withOptions: AgentProfileFormState = {
|
||||
...next,
|
||||
providerOptions: buildProviderOptions(entries),
|
||||
unifiedModelOptions: buildUnifiedModelOptions(entries),
|
||||
modelOptions: buildModelOptions(models),
|
||||
modeOptions: buildModeOptions(modes),
|
||||
thinkingOptions: buildThinkingOptions(thinking),
|
||||
@@ -538,21 +731,16 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
modeDisplay: refineDisplay(
|
||||
next.modeDisplay,
|
||||
next.modeId,
|
||||
(() => {
|
||||
const mode = modes.find((entry) => entry.id === next.modeId);
|
||||
return mode ? formatAgentModeLabel(mode) : null;
|
||||
})(),
|
||||
resolveModeLabel(modes, next.modeId),
|
||||
),
|
||||
thinkingDisplay: refineDisplay(
|
||||
next.thinkingDisplay,
|
||||
next.thinkingOptionId,
|
||||
(() => {
|
||||
const option = thinking.find((entry) => entry.id === next.thinkingOptionId);
|
||||
return option ? formatThinkingOptionLabel(option) : null;
|
||||
})(),
|
||||
resolveThinkingLabel(thinking, next.thinkingOptionId),
|
||||
),
|
||||
catalogResolution,
|
||||
controlsResolution,
|
||||
controlsPending: controlsResolution === "pending",
|
||||
controlsRequest,
|
||||
controlsRequestKey,
|
||||
};
|
||||
@@ -572,16 +760,40 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
withOptions.provider.length > 0 &&
|
||||
!withOptions.isSubmitting;
|
||||
const resolved: AgentProfileFormState = { ...withOptions, disclosure, canSubmit };
|
||||
return { ...resolved, submitValue: canSubmit ? buildSubmitValue(resolved) : null };
|
||||
const submitValue = canSubmit ? buildSubmitValue(resolved) : null;
|
||||
const isDirty =
|
||||
baselineFingerprint.length > 0 && formDraftFingerprint(resolved) !== baselineFingerprint;
|
||||
return { ...resolved, isDirty, draftRevision, submitValue };
|
||||
}
|
||||
|
||||
let state: AgentProfileFormState = derive(buildInitialState(snapshot));
|
||||
baselineFingerprint = formDraftFingerprint(state);
|
||||
|
||||
function publish(mutate: (current: AgentProfileFormState) => AgentProfileFormState): void {
|
||||
function publish(
|
||||
mutate: (current: AgentProfileFormState) => AgentProfileFormState,
|
||||
options?: { userEdit?: boolean },
|
||||
): void {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
state = derive(mutate(state));
|
||||
const previousFingerprint = formDraftFingerprint(state);
|
||||
if (options?.userEdit) {
|
||||
hasUserEdited = true;
|
||||
}
|
||||
let nextState = derive(mutate(state));
|
||||
if (options?.userEdit && formDraftFingerprint(nextState) !== previousFingerprint) {
|
||||
draftRevision += 1;
|
||||
nextState = { ...nextState, draftRevision };
|
||||
}
|
||||
// Catalog hydration fills in missing provider defaults (e.g., default mode on a
|
||||
// migrated favorite); refresh the clean baseline until the user makes an edit.
|
||||
if (!hasUserEdited) {
|
||||
baselineFingerprint = formDraftFingerprint(nextState);
|
||||
if (nextState.isDirty) {
|
||||
nextState = { ...nextState, isDirty: false };
|
||||
}
|
||||
}
|
||||
state = nextState;
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
@@ -610,6 +822,7 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
}
|
||||
resolvedControlsKey = requestKey;
|
||||
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
|
||||
resolvedProvider = state.provider || null;
|
||||
resolvedControls = [...resolved.controls];
|
||||
resolvedOptions = resolved.options;
|
||||
answeredKeys = new Set(resolved.controls.map((control) => control.key));
|
||||
@@ -622,66 +835,149 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
}
|
||||
resolvedControlsKey = requestKey;
|
||||
resolvedScopeKey = buildControlsScopeKey(state.controlsRequest);
|
||||
resolvedProvider = state.provider || null;
|
||||
resolvedControls = [];
|
||||
resolvedOptions = {};
|
||||
publish((current) => current);
|
||||
},
|
||||
setName: (value) => publish((current) => ({ ...current, name: value })),
|
||||
setName: (value) =>
|
||||
publish(
|
||||
(current) => {
|
||||
if (value !== autoSuggestedName) {
|
||||
autoSuggestedName = null;
|
||||
}
|
||||
return { ...current, name: value };
|
||||
},
|
||||
{ userEdit: true },
|
||||
),
|
||||
setAppearance: (value) =>
|
||||
publish((current) => ({ ...current, icon: value.icon, color: value.color })),
|
||||
setNotes: (value) => publish((current) => ({ ...current, notes: value })),
|
||||
publish((current) => ({ ...current, icon: value.icon, color: value.color }), {
|
||||
userEdit: true,
|
||||
}),
|
||||
setNotes: (value) => publish((current) => ({ ...current, notes: value }), { userEdit: true }),
|
||||
setProvider: (providerId, display) =>
|
||||
publish((current) => {
|
||||
if (current.provider === providerId) {
|
||||
return current;
|
||||
}
|
||||
// Everything below the provider is provider-scoped: a model id, mode id,
|
||||
// thinking id or feature id from the old provider means nothing here.
|
||||
// Clearing them is enough — `derive` seeds the new provider's defaults.
|
||||
drawnKeys = new Set();
|
||||
answeredKeys = new Set();
|
||||
return {
|
||||
...current,
|
||||
provider: providerId,
|
||||
providerDisplay: display,
|
||||
modelId: "",
|
||||
modelDisplay: null,
|
||||
modeId: "",
|
||||
modeDisplay: null,
|
||||
thinkingOptionId: "",
|
||||
thinkingDisplay: null,
|
||||
options: {},
|
||||
optionEdits: {},
|
||||
};
|
||||
}),
|
||||
publish(
|
||||
(current) => {
|
||||
if (current.provider === providerId) {
|
||||
return current;
|
||||
}
|
||||
// Everything below the provider is provider-scoped: a model id, mode id,
|
||||
// thinking id or feature id from the old provider means nothing here.
|
||||
// Clearing them is enough — `derive` seeds the new provider's defaults.
|
||||
drawnKeys = new Set();
|
||||
answeredKeys = new Set();
|
||||
resolvedProvider = null;
|
||||
resolvedScopeKey = null;
|
||||
resolvedControlsKey = null;
|
||||
resolvedControls = [];
|
||||
resolvedOptions = {};
|
||||
return {
|
||||
...current,
|
||||
provider: providerId,
|
||||
providerDisplay: display,
|
||||
modelId: "",
|
||||
modelDisplay: null,
|
||||
modeId: "",
|
||||
modeDisplay: null,
|
||||
thinkingOptionId: "",
|
||||
thinkingDisplay: null,
|
||||
options: {},
|
||||
optionEdits: {},
|
||||
};
|
||||
},
|
||||
{ userEdit: true },
|
||||
),
|
||||
setProviderModel: (providerId, modelId, displays) =>
|
||||
publish(
|
||||
(current) => {
|
||||
const providerChanged = current.provider !== providerId;
|
||||
const modelChanged = current.modelId !== modelId;
|
||||
if (!providerChanged && !modelChanged) {
|
||||
return current;
|
||||
}
|
||||
const suggested = displays.model?.label ?? displays.provider.label;
|
||||
const shouldAutoName =
|
||||
current.mode === "create" &&
|
||||
(current.name.trim().length === 0 ||
|
||||
(autoSuggestedName !== null && current.name === autoSuggestedName));
|
||||
const nextName = shouldAutoName ? suggested : current.name;
|
||||
if (shouldAutoName) {
|
||||
autoSuggestedName = suggested;
|
||||
}
|
||||
if (providerChanged) {
|
||||
drawnKeys = new Set();
|
||||
answeredKeys = new Set();
|
||||
resolvedProvider = null;
|
||||
resolvedScopeKey = null;
|
||||
resolvedControlsKey = null;
|
||||
resolvedControls = [];
|
||||
resolvedOptions = {};
|
||||
return {
|
||||
...current,
|
||||
name: nextName,
|
||||
provider: providerId,
|
||||
providerDisplay: displays.provider,
|
||||
modelId,
|
||||
modelDisplay: displays.model,
|
||||
modeId: "",
|
||||
modeDisplay: null,
|
||||
thinkingOptionId: "",
|
||||
thinkingDisplay: null,
|
||||
options: {},
|
||||
optionEdits: {},
|
||||
};
|
||||
}
|
||||
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
|
||||
const keepsThinking =
|
||||
current.thinkingOptionId.length > 0 &&
|
||||
nextThinking.some((option) => option.id === current.thinkingOptionId);
|
||||
return {
|
||||
...current,
|
||||
name: nextName,
|
||||
modelId,
|
||||
modelDisplay: displays.model,
|
||||
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
|
||||
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
|
||||
};
|
||||
},
|
||||
{ userEdit: true },
|
||||
),
|
||||
setModel: (modelId, display) =>
|
||||
publish((current) => {
|
||||
if (current.modelId === modelId) {
|
||||
return current;
|
||||
}
|
||||
// Thinking options are a property of the model, so a level the new model
|
||||
// does not offer has to go.
|
||||
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
|
||||
const keepsThinking =
|
||||
current.thinkingOptionId.length > 0 &&
|
||||
nextThinking.some((option) => option.id === current.thinkingOptionId);
|
||||
return {
|
||||
...current,
|
||||
modelId,
|
||||
modelDisplay: display,
|
||||
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
|
||||
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
|
||||
};
|
||||
}),
|
||||
publish(
|
||||
(current) => {
|
||||
if (current.modelId === modelId) {
|
||||
return current;
|
||||
}
|
||||
// Thinking options are a property of the model, so a level the new model
|
||||
// does not offer has to go.
|
||||
const nextThinking = resolveThinkingOptions(entries, current.provider, modelId);
|
||||
const keepsThinking =
|
||||
current.thinkingOptionId.length > 0 &&
|
||||
nextThinking.some((option) => option.id === current.thinkingOptionId);
|
||||
return {
|
||||
...current,
|
||||
modelId,
|
||||
modelDisplay: display,
|
||||
thinkingOptionId: keepsThinking ? current.thinkingOptionId : "",
|
||||
thinkingDisplay: keepsThinking ? current.thinkingDisplay : null,
|
||||
};
|
||||
},
|
||||
{ userEdit: true },
|
||||
),
|
||||
setMode: (modeId, display) =>
|
||||
publish((current) => ({ ...current, modeId, modeDisplay: display })),
|
||||
publish((current) => ({ ...current, modeId, modeDisplay: display }), { userEdit: true }),
|
||||
setThinking: (thinkingOptionId, display) =>
|
||||
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display })),
|
||||
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display }), {
|
||||
userEdit: true,
|
||||
}),
|
||||
setOption: (key, value) =>
|
||||
publish((current) => ({
|
||||
...current,
|
||||
optionEdits: { ...current.optionEdits, [key]: value },
|
||||
})),
|
||||
publish(
|
||||
(current) => ({
|
||||
...current,
|
||||
optionEdits: { ...current.optionEdits, [key]: value },
|
||||
}),
|
||||
{ userEdit: true },
|
||||
),
|
||||
setSubmitting: (value) => publish((current) => ({ ...current, isSubmitting: value })),
|
||||
setSubmitError: (value) => publish((current) => ({ ...current, submitError: value })),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { buildAgentProfileRosterSummary, formatShortModelLabel } from "./profile-summary";
|
||||
|
||||
const formatFeatureCount = (count: number) => `${count} option${count === 1 ? "" : "s"}`;
|
||||
|
||||
describe("formatShortModelLabel", () => {
|
||||
it("keeps plain model names intact with no prefix", () => {
|
||||
expect(formatShortModelLabel("Claude Opus 4.6")).toEqual({
|
||||
prefix: null,
|
||||
name: "Claude Opus 4.6",
|
||||
});
|
||||
});
|
||||
|
||||
it("splits slash-qualified router model ids into prefix and short name", () => {
|
||||
expect(formatShortModelLabel("openrouter/moonshotai/kimi-k3.1-pro")).toEqual({
|
||||
prefix: "openrouter/moonshotai/",
|
||||
name: "kimi-k3.1-pro",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores leading or trailing slashes", () => {
|
||||
expect(formatShortModelLabel("/leading")).toEqual({ prefix: null, name: "/leading" });
|
||||
expect(formatShortModelLabel("trailing/")).toEqual({ prefix: null, name: "trailing/" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAgentProfileRosterSummary", () => {
|
||||
const entries: ProviderSnapshotEntry[] = [
|
||||
{
|
||||
provider: "opencode",
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
label: "OpenCode",
|
||||
models: [
|
||||
{
|
||||
provider: "opencode",
|
||||
id: "openrouter/moonshotai/kimi-k3.1-pro",
|
||||
label: "openrouter/moonshotai/kimi-k3.1-pro",
|
||||
},
|
||||
],
|
||||
modes: [{ id: "build", label: "Build" }],
|
||||
},
|
||||
];
|
||||
|
||||
it("separates short model label from provider/mode/thinking/option details", () => {
|
||||
const profile: AgentProfile = {
|
||||
id: "p1",
|
||||
name: "Kimi fast",
|
||||
provider: "opencode",
|
||||
model: "openrouter/moonshotai/kimi-k3.1-pro",
|
||||
modeId: "build",
|
||||
thinkingOptionId: "high",
|
||||
options: { fast_mode: true },
|
||||
};
|
||||
|
||||
const summary = buildAgentProfileRosterSummary({ profile, entries, formatFeatureCount });
|
||||
|
||||
expect(summary.providerLabel).toBe("OpenCode");
|
||||
expect(summary.modelLabel).toBe("kimi-k3.1-pro");
|
||||
expect(summary.modelPrefix).toBe("openrouter/moonshotai/");
|
||||
expect(summary.runtimeDetails).toEqual(["OpenCode", "Build", "High", "1 option"]);
|
||||
});
|
||||
|
||||
it("falls back to stored provider id when catalog is unavailable", () => {
|
||||
const profile: AgentProfile = {
|
||||
id: "p2",
|
||||
name: "Offline profile",
|
||||
provider: "custom-agent",
|
||||
};
|
||||
|
||||
const summary = buildAgentProfileRosterSummary({
|
||||
profile,
|
||||
entries: undefined,
|
||||
formatFeatureCount,
|
||||
});
|
||||
|
||||
expect(summary.providerLabel).toBe("custom-agent");
|
||||
expect(summary.modelLabel).toBeNull();
|
||||
expect(summary.runtimeDetails).toEqual(["custom-agent"]);
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,55 @@ export interface AgentProfileTag {
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface ShortModelLabel {
|
||||
prefix: string | null;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits slash-qualified routing IDs (e.g. `openrouter/moonshotai/kimi-k3.1-pro`)
|
||||
* into a quiet prefix and the model's short name so dense roster rows stay readable.
|
||||
*/
|
||||
export function formatShortModelLabel(modelIdOrLabel: string): ShortModelLabel {
|
||||
const trimmed = modelIdOrLabel.trim();
|
||||
const lastSlash = trimmed.lastIndexOf("/");
|
||||
if (lastSlash <= 0 || lastSlash >= trimmed.length - 1) {
|
||||
return { prefix: null, name: trimmed };
|
||||
}
|
||||
return {
|
||||
prefix: trimmed.slice(0, lastSlash + 1),
|
||||
name: trimmed.slice(lastSlash + 1),
|
||||
};
|
||||
}
|
||||
|
||||
export interface AgentProfileRosterSummary {
|
||||
providerLabel: string;
|
||||
modelLabel: string | null;
|
||||
modelPrefix: string | null;
|
||||
runtimeDetails: string[];
|
||||
allTags: AgentProfileTag[];
|
||||
}
|
||||
|
||||
export function buildAgentProfileRosterSummary(input: {
|
||||
profile: AgentProfile;
|
||||
entries: readonly ProviderSnapshotEntry[] | undefined;
|
||||
formatFeatureCount: (count: number) => string;
|
||||
}): AgentProfileRosterSummary {
|
||||
const allTags = buildAgentProfileTags(input);
|
||||
const providerLabel =
|
||||
allTags.find((tag) => tag.id === "provider")?.label ?? input.profile.provider;
|
||||
const rawModel = allTags.find((tag) => tag.id === "model")?.label ?? null;
|
||||
const shortModel = rawModel ? formatShortModelLabel(rawModel) : null;
|
||||
const runtimeDetails = allTags.filter((tag) => tag.id !== "model").map((tag) => tag.label);
|
||||
return {
|
||||
providerLabel,
|
||||
modelLabel: shortModel?.name ?? null,
|
||||
modelPrefix: shortModel?.prefix ?? null,
|
||||
runtimeDetails,
|
||||
allTags,
|
||||
};
|
||||
}
|
||||
|
||||
function findEntry(
|
||||
entries: readonly ProviderSnapshotEntry[],
|
||||
provider: string,
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createAgentProfileWriteQueue } from "./profile-write-queue";
|
||||
|
||||
function profile(id: string, name = id): AgentProfile {
|
||||
return { id, name, provider: "claude", model: "claude-opus-5" };
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
describe("createAgentProfileWriteQueue", () => {
|
||||
it("serializes overlapping appends on the same host so both profiles persist", async () => {
|
||||
const queue = createAgentProfileWriteQueue();
|
||||
let stored: AgentProfile[] = [profile("p0")];
|
||||
const firstGate = deferred<void>();
|
||||
const writes: string[][] = [];
|
||||
|
||||
const write = async (next: AgentProfile[]) => {
|
||||
writes.push(next.map((entry) => entry.id));
|
||||
if (writes.length === 1) {
|
||||
await firstGate.promise;
|
||||
}
|
||||
stored = next;
|
||||
return stored;
|
||||
};
|
||||
|
||||
const first = queue.enqueue("host-a", {
|
||||
readCurrent: () => stored,
|
||||
write,
|
||||
updater: (current) => [...current, profile("p1")],
|
||||
});
|
||||
const second = queue.enqueue("host-a", {
|
||||
readCurrent: () => stored,
|
||||
write,
|
||||
updater: (current) => [...current, profile("p2")],
|
||||
});
|
||||
|
||||
// Wait a microtask so the first write is in flight before releasing it.
|
||||
await Promise.resolve();
|
||||
expect(writes).toEqual([["p0", "p1"]]);
|
||||
|
||||
firstGate.resolve();
|
||||
await expect(first).resolves.toEqual([profile("p0"), profile("p1")]);
|
||||
await expect(second).resolves.toEqual([profile("p0"), profile("p1"), profile("p2")]);
|
||||
expect(writes).toEqual([
|
||||
["p0", "p1"],
|
||||
["p0", "p1", "p2"],
|
||||
]);
|
||||
expect(stored.map((entry) => entry.id)).toEqual(["p0", "p1", "p2"]);
|
||||
});
|
||||
|
||||
it("removes only the undone profile when Undo overlaps another in-flight save", async () => {
|
||||
const queue = createAgentProfileWriteQueue();
|
||||
let stored: AgentProfile[] = [profile("p0"), profile("p1")];
|
||||
const saveGate = deferred<void>();
|
||||
|
||||
const appendSecond = queue.enqueue("host-a", {
|
||||
readCurrent: () => stored,
|
||||
write: async (next) => {
|
||||
await saveGate.promise;
|
||||
stored = next;
|
||||
return stored;
|
||||
},
|
||||
updater: (current) => [...current, profile("p2")],
|
||||
});
|
||||
|
||||
const undoFirst = queue.enqueue("host-a", {
|
||||
readCurrent: () => stored,
|
||||
write: async (next) => {
|
||||
stored = next;
|
||||
return stored;
|
||||
},
|
||||
updater: (current) => current.filter((entry) => entry.id !== "p1"),
|
||||
});
|
||||
|
||||
saveGate.resolve();
|
||||
await appendSecond;
|
||||
await undoFirst;
|
||||
|
||||
expect(stored.map((entry) => entry.id)).toEqual(["p0", "p2"]);
|
||||
});
|
||||
|
||||
it("recovers after a rejected write so subsequent mutations still run", async () => {
|
||||
const queue = createAgentProfileWriteQueue();
|
||||
let stored: AgentProfile[] = [profile("p0")];
|
||||
|
||||
const failing = queue.enqueue("host-a", {
|
||||
readCurrent: () => stored,
|
||||
write: async () => {
|
||||
throw new Error("network blip");
|
||||
},
|
||||
updater: (current) => [...current, profile("p1")],
|
||||
});
|
||||
|
||||
const succeeding = queue.enqueue("host-a", {
|
||||
readCurrent: () => stored,
|
||||
write: async (next) => {
|
||||
stored = next;
|
||||
return stored;
|
||||
},
|
||||
updater: (current) => [...current, profile("p2")],
|
||||
});
|
||||
|
||||
await expect(failing).rejects.toThrow("network blip");
|
||||
await expect(succeeding).resolves.toEqual([profile("p0"), profile("p2")]);
|
||||
});
|
||||
|
||||
it("skips writing when current profiles are unloaded or the updater returns null", async () => {
|
||||
const queue = createAgentProfileWriteQueue();
|
||||
let writeCalls = 0;
|
||||
|
||||
const unloaded = await queue.enqueue("host-a", {
|
||||
readCurrent: () => null,
|
||||
write: async (next) => {
|
||||
writeCalls += 1;
|
||||
return next;
|
||||
},
|
||||
updater: (current) => [...current, profile("p1")],
|
||||
});
|
||||
expect(unloaded).toBeNull();
|
||||
|
||||
const noop = await queue.enqueue("host-a", {
|
||||
readCurrent: () => [profile("p0")],
|
||||
write: async (next) => {
|
||||
writeCalls += 1;
|
||||
return next;
|
||||
},
|
||||
updater: () => null,
|
||||
});
|
||||
expect(noop).toBeNull();
|
||||
expect(writeCalls).toBe(0);
|
||||
});
|
||||
|
||||
it("does not block writes to a different host", async () => {
|
||||
const queue = createAgentProfileWriteQueue();
|
||||
const hostAGate = deferred<void>();
|
||||
let hostA: AgentProfile[] = [];
|
||||
let hostB: AgentProfile[] = [];
|
||||
|
||||
const writeA = queue.enqueue("host-a", {
|
||||
readCurrent: () => hostA,
|
||||
write: async (next) => {
|
||||
await hostAGate.promise;
|
||||
hostA = next;
|
||||
return hostA;
|
||||
},
|
||||
updater: (current) => [...current, profile("a1")],
|
||||
});
|
||||
|
||||
const writeB = await queue.enqueue("host-b", {
|
||||
readCurrent: () => hostB,
|
||||
write: async (next) => {
|
||||
hostB = next;
|
||||
return hostB;
|
||||
},
|
||||
updater: (current) => [...current, profile("b1")],
|
||||
});
|
||||
|
||||
expect(writeB).toEqual([profile("b1")]);
|
||||
hostAGate.resolve();
|
||||
await expect(writeA).resolves.toEqual([profile("a1")]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
|
||||
export type AgentProfileListUpdater = (current: readonly AgentProfile[]) => AgentProfile[] | null;
|
||||
|
||||
export interface AgentProfileWriteStep {
|
||||
readCurrent: () => readonly AgentProfile[] | null;
|
||||
write: (next: AgentProfile[]) => Promise<AgentProfile[]>;
|
||||
updater: AgentProfileListUpdater;
|
||||
}
|
||||
|
||||
export interface AgentProfileWriteQueue {
|
||||
enqueue(serverId: string, step: AgentProfileWriteStep): Promise<AgentProfile[] | null>;
|
||||
}
|
||||
|
||||
/** Removes one profile by id, returning `null` if it is already absent so callers skip no-op writes. */
|
||||
export function removeAgentProfileById(
|
||||
current: readonly AgentProfile[],
|
||||
profileId: string,
|
||||
): AgentProfile[] | null {
|
||||
const next = current.filter((entry) => entry.id !== profileId);
|
||||
return next.length === current.length ? null : next;
|
||||
}
|
||||
|
||||
async function runQueuedWrite(
|
||||
previous: Promise<void>,
|
||||
step: AgentProfileWriteStep,
|
||||
): Promise<AgentProfile[] | null> {
|
||||
await previous;
|
||||
const current = step.readCurrent();
|
||||
if (current === null) {
|
||||
return null;
|
||||
}
|
||||
const next = step.updater(current);
|
||||
if (next === null) {
|
||||
return null;
|
||||
}
|
||||
return step.write(next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes profile list writes per host so overlapping mutations (rapid composer
|
||||
* `+` saves, Undo while another save is in flight, split-pane composers) each compute
|
||||
* their update against the result of the previous write instead of overwriting it.
|
||||
*/
|
||||
export function createAgentProfileWriteQueue(): AgentProfileWriteQueue {
|
||||
const tails = new Map<string, Promise<void>>();
|
||||
|
||||
return {
|
||||
enqueue(serverId, step) {
|
||||
const previous = tails.get(serverId) ?? Promise.resolve();
|
||||
const result = runQueuedWrite(previous, step);
|
||||
const tail = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
tails.set(serverId, tail);
|
||||
void tail.finally(() => {
|
||||
if (tails.get(serverId) === tail) {
|
||||
tails.delete(serverId);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,8 +1,21 @@
|
||||
import { useCallback } from "react";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { AgentProfile, MutableDaemonConfig } from "@getpaseo/protocol/messages";
|
||||
import { daemonConfigQueryKey } from "@/data/daemon-config";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { supportsAgentProfiles } from "./capabilities";
|
||||
import {
|
||||
createAgentProfileWriteQueue,
|
||||
removeAgentProfileById,
|
||||
type AgentProfileListUpdater,
|
||||
} from "./profile-write-queue";
|
||||
|
||||
const sharedProfileWriteQueue = createAgentProfileWriteQueue();
|
||||
|
||||
export { removeAgentProfileById };
|
||||
export type { AgentProfileListUpdater };
|
||||
|
||||
export interface UseAgentProfilesResult {
|
||||
/** `null` until the daemon config has arrived. */
|
||||
@@ -11,24 +24,56 @@ export interface UseAgentProfilesResult {
|
||||
isSupported: boolean;
|
||||
/** Writes the whole list; there is no per-profile RPC. */
|
||||
saveProfiles: (next: AgentProfile[]) => Promise<void>;
|
||||
/**
|
||||
* Applies a serialized mutation against the latest host profile list so
|
||||
* overlapping writes compose instead of overwriting each other.
|
||||
*/
|
||||
mutateProfiles: (updater: AgentProfileListUpdater) => Promise<AgentProfile[] | null>;
|
||||
}
|
||||
|
||||
export function useAgentProfiles(serverId: string | null): UseAgentProfilesResult {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const { config, patchConfig } = useDaemonConfig(serverId);
|
||||
const queryKey = useMemo(() => daemonConfigQueryKey(serverId), [serverId]);
|
||||
const isSupported = useSessionStore((state) => {
|
||||
return supportsAgentProfiles(state.sessions[serverId ?? ""]?.serverInfo?.features);
|
||||
});
|
||||
|
||||
const mutateProfiles = useCallback(
|
||||
async (updater: AgentProfileListUpdater): Promise<AgentProfile[] | null> => {
|
||||
if (!serverId) {
|
||||
return null;
|
||||
}
|
||||
return sharedProfileWriteQueue.enqueue(serverId, {
|
||||
readCurrent: () => {
|
||||
const cached = queryClient.getQueryData<MutableDaemonConfig>(queryKey);
|
||||
return cached ? (cached.agentProfiles ?? []) : null;
|
||||
},
|
||||
write: async (next) => {
|
||||
const updated = await patchConfig({ agentProfiles: next });
|
||||
if (!updated) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
return updated.agentProfiles ?? next;
|
||||
},
|
||||
updater,
|
||||
});
|
||||
},
|
||||
[patchConfig, queryClient, queryKey, serverId, t],
|
||||
);
|
||||
|
||||
const saveProfiles = useCallback(
|
||||
async (next: AgentProfile[]) => {
|
||||
await patchConfig({ agentProfiles: next });
|
||||
await mutateProfiles(() => next);
|
||||
},
|
||||
[patchConfig],
|
||||
[mutateProfiles],
|
||||
);
|
||||
|
||||
return {
|
||||
profiles: config ? (config.agentProfiles ?? []) : null,
|
||||
isSupported,
|
||||
saveProfiles,
|
||||
mutateProfiles,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
import { useEffect, useState, useSyncExternalStore } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
import {
|
||||
openAgentProfileForm,
|
||||
type AgentProfileFormModel,
|
||||
type AgentProfileFormSnapshot,
|
||||
type AgentProfileFormState,
|
||||
type AgentProfileSeed,
|
||||
type AgentProfileValue,
|
||||
} from "./profile-form-model";
|
||||
import { useAgentProfileFormCatalog, useAgentProfileFormControls } from "./use-profile-form-inputs";
|
||||
|
||||
/**
|
||||
* One model per mount. The modal keys its body on mode + profile id, so create
|
||||
* and edit never share an instance and reopening always starts from the record.
|
||||
* One model per mount. The sheet or drawer host keys its session on mode + profile id,
|
||||
* so create and edit never share an instance and reopening always starts from the record.
|
||||
*/
|
||||
export function useAgentProfileFormModel(
|
||||
snapshot: AgentProfileFormSnapshot,
|
||||
@@ -27,3 +33,78 @@ export function useAgentProfileFormModel(
|
||||
export function useAgentProfileFormState(model: AgentProfileFormModel): AgentProfileFormState {
|
||||
return useSyncExternalStore(model.subscribe, model.getState, model.getState);
|
||||
}
|
||||
|
||||
export interface AgentProfileFormSession {
|
||||
model: AgentProfileFormModel;
|
||||
state: AgentProfileFormState;
|
||||
isDirty: boolean;
|
||||
save: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared form session used by both the desktop inspector drawer and the modal sheet.
|
||||
* Lifting this above drawer/modal framing lets responsive switches preserve unsaved edits.
|
||||
*/
|
||||
export function useAgentProfileFormSession({
|
||||
serverId,
|
||||
mode,
|
||||
profile,
|
||||
seed,
|
||||
onSave,
|
||||
onSaved,
|
||||
}: {
|
||||
serverId: string;
|
||||
mode: "create" | "edit";
|
||||
profile?: AgentProfile;
|
||||
seed?: AgentProfileSeed;
|
||||
onSave: (value: AgentProfileValue) => Promise<void>;
|
||||
onSaved: () => void;
|
||||
}): AgentProfileFormSession {
|
||||
const { entries } = useProvidersSnapshot(serverId, { cwd: null });
|
||||
const snapshot = useMemo<AgentProfileFormSnapshot>(
|
||||
() => ({
|
||||
mode,
|
||||
...(profile ? { profile } : {}),
|
||||
...(seed ? { seed } : {}),
|
||||
...(entries ? { entries } : {}),
|
||||
}),
|
||||
[entries, mode, profile, seed],
|
||||
);
|
||||
const model = useAgentProfileFormModel(snapshot);
|
||||
const state = useAgentProfileFormState(model);
|
||||
useAgentProfileFormCatalog({ serverId, model });
|
||||
useAgentProfileFormControls({ serverId, model, state });
|
||||
const mountedRef = useRef(true);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const save = useCallback(async (): Promise<boolean> => {
|
||||
const value = model.getState().submitValue;
|
||||
if (!value) {
|
||||
return false;
|
||||
}
|
||||
model.setSubmitError(null);
|
||||
model.setSubmitting(true);
|
||||
try {
|
||||
await onSave(value);
|
||||
// Only notify completion while this session is still active; switching profiles
|
||||
// mid-save unmounts this session and must not close the next editor's draft.
|
||||
if (mountedRef.current) {
|
||||
onSaved();
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
model.setSubmitError(toErrorMessage(error));
|
||||
return false;
|
||||
} finally {
|
||||
model.setSubmitting(false);
|
||||
}
|
||||
}, [model, onSave, onSaved]);
|
||||
|
||||
return useMemo(() => ({ model, state, isDirty: state.isDirty, save }), [model, save, state]);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import { useCallback, useMemo, useRef, useState, type ReactElement } from "react";
|
||||
import { Pressable, View, type PressableStateCallbackType } from "react-native";
|
||||
import { View, type PressableStateCallbackType } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Check, ChevronDown } from "lucide-react-native";
|
||||
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
|
||||
import {
|
||||
bySizing,
|
||||
createControlGeometry,
|
||||
resolveControlInteractionStyles,
|
||||
TOUCH_TARGET,
|
||||
type ControlSize,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { Field } from "@/components/ui/form-field";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { identityForeground } from "@/styles/identity-colors";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
|
||||
@@ -37,7 +40,6 @@ const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = [];
|
||||
const ThemedChevronDown = withUnistyles(ChevronDown);
|
||||
const ThemedCheck = withUnistyles(Check);
|
||||
|
||||
const foregroundMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
const onIdentityMapping = (theme: Theme) => ({ color: theme.colors.background });
|
||||
|
||||
/**
|
||||
@@ -56,39 +58,43 @@ function IconCell({
|
||||
iconKey,
|
||||
selected,
|
||||
color,
|
||||
provider,
|
||||
serverId,
|
||||
onSelect,
|
||||
}: {
|
||||
iconKey: AgentProfileIconKey | null;
|
||||
selected: boolean;
|
||||
color: AgentProfileColor;
|
||||
provider?: string;
|
||||
serverId?: string | null;
|
||||
onSelect: (iconKey: AgentProfileIconKey | null) => void;
|
||||
}) {
|
||||
const handlePress = useCallback(() => onSelect(iconKey), [iconKey, onSelect]);
|
||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||
const cellStyle = useCallback(
|
||||
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
styles.cell,
|
||||
Boolean(hovered) && styles.cellHovered,
|
||||
pressed && styles.cellPressed,
|
||||
selected && styles.cellSelected,
|
||||
],
|
||||
[selected],
|
||||
);
|
||||
return (
|
||||
<Pressable
|
||||
<PressHighlight
|
||||
onPress={handlePress}
|
||||
style={cellStyle}
|
||||
highlightStyle={styles.cellPressed}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={accessibilityState}
|
||||
accessibilityLabel={iconKey ?? "default"}
|
||||
testID={`agent-profile-icon-cell-${iconKey ?? "default"}`}
|
||||
>
|
||||
<AgentProfileGlyph
|
||||
{...(iconKey ? { icon: iconKey } : {})}
|
||||
{...(iconKey ? { icon: iconKey } : { provider, serverId })}
|
||||
color={color}
|
||||
size={ICON_SIZE.lg}
|
||||
/>
|
||||
</Pressable>
|
||||
</PressHighlight>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -104,58 +110,54 @@ function ColorCell({
|
||||
const { t } = useTranslation();
|
||||
const handlePress = useCallback(() => onSelect(color), [color, onSelect]);
|
||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||
const swatchStyle = useMemo(
|
||||
() => [styles.swatch, color === "none" ? styles.swatchNone : identitySwatch(color)],
|
||||
[color],
|
||||
);
|
||||
const cellStyle = useCallback(
|
||||
({ pressed }: PressableStateCallbackType) => [styles.colorCell, pressed && styles.cellPressed],
|
||||
[],
|
||||
);
|
||||
return (
|
||||
<Pressable
|
||||
<PressHighlight
|
||||
onPress={handlePress}
|
||||
style={cellStyle}
|
||||
style={styles.colorCell}
|
||||
highlightStyle={styles.cellPressed}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={accessibilityState}
|
||||
accessibilityLabel={colorLabel(t, color)}
|
||||
testID={`agent-profile-color-cell-${color}`}
|
||||
>
|
||||
<View style={swatchStyle}>
|
||||
<View style={[styles.swatch, color === "none" ? styles.swatchNone : identitySwatch(color)]}>
|
||||
{selected ? (
|
||||
<ThemedCheck
|
||||
size={ICON_SIZE.sm}
|
||||
uniProps={color === "none" ? foregroundMutedMapping : onIdentityMapping}
|
||||
uniProps={color === "none" ? mutedIconColorMapping : onIdentityMapping}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</Pressable>
|
||||
</PressHighlight>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Icon and colour in one popover rather than two fields: the pair is a single
|
||||
* visual decision, and picking them apart means never seeing the result until
|
||||
* both are closed. The grid redraws in the chosen colour as you switch colours,
|
||||
* so the swatch row sits above it.
|
||||
* Compact clickable icon+color tile that opens the appearance popover without
|
||||
* requiring a separate labeled field box. Used inline beside the Name input
|
||||
* and in the inspector drawer header.
|
||||
*/
|
||||
export function AgentProfileAppearanceField({
|
||||
export function AgentProfileIconButton({
|
||||
label,
|
||||
icon,
|
||||
color,
|
||||
provider,
|
||||
serverId,
|
||||
onChange,
|
||||
size = "md",
|
||||
variant = "field",
|
||||
disabled = false,
|
||||
testID,
|
||||
triggerTestID,
|
||||
}: {
|
||||
label: string;
|
||||
icon: string;
|
||||
color: string;
|
||||
provider?: string;
|
||||
serverId?: string | null;
|
||||
onChange: (next: { icon: string; color: string }) => void;
|
||||
size?: ControlSize;
|
||||
variant?: "field" | "hero";
|
||||
disabled?: boolean;
|
||||
testID?: string;
|
||||
triggerTestID?: string;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
@@ -188,8 +190,10 @@ export function AgentProfileAppearanceField({
|
||||
const triggerStyle = useCallback(
|
||||
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
styles.trigger,
|
||||
size === "sm" ? styles.triggerSm : styles.triggerMd,
|
||||
styles.triggerIconOnly,
|
||||
variant === "hero" && styles.triggerHero,
|
||||
variant !== "hero" && size === "sm" && styles.triggerSm,
|
||||
variant !== "hero" && size !== "sm" && styles.triggerMd,
|
||||
variant === "field" && styles.triggerIconOnly,
|
||||
resolveControlInteractionStyles(
|
||||
{
|
||||
controlRest: styles.controlRest,
|
||||
@@ -200,29 +204,36 @@ export function AgentProfileAppearanceField({
|
||||
{ hovered: Boolean(hovered), active: pressed || open, disabled },
|
||||
),
|
||||
],
|
||||
[disabled, open, size],
|
||||
[disabled, open, size, variant],
|
||||
);
|
||||
|
||||
const header = useMemo(() => ({ title: label }), [label]);
|
||||
|
||||
return (
|
||||
<Field label={label} testID={testID}>
|
||||
<>
|
||||
<View ref={anchorRef} collapsable={false}>
|
||||
<Pressable
|
||||
<PressHighlight
|
||||
onPress={handleTriggerPress}
|
||||
disabled={disabled}
|
||||
style={triggerStyle}
|
||||
highlightStyle={styles.triggerPressed}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`${label} (${colorLabel(t, selectedColor)})`}
|
||||
testID={triggerTestID}
|
||||
>
|
||||
<AgentProfileGlyph
|
||||
{...(selectedIcon ? { icon: selectedIcon } : {})}
|
||||
{...(selectedIcon ? { icon: selectedIcon } : { provider, serverId })}
|
||||
color={selectedColor}
|
||||
size={ICON_SIZE.md}
|
||||
size={variant === "hero" ? ICON_SIZE.lg : ICON_SIZE.md}
|
||||
/>
|
||||
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
||||
</Pressable>
|
||||
{variant === "hero" ? (
|
||||
<View style={styles.heroCaretBadge}>
|
||||
<ThemedChevronDown size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
</View>
|
||||
) : (
|
||||
<ThemedChevronDown size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
)}
|
||||
</PressHighlight>
|
||||
</View>
|
||||
<Combobox
|
||||
options={EMPTY_COMBOBOX_OPTIONS}
|
||||
@@ -251,6 +262,8 @@ export function AgentProfileAppearanceField({
|
||||
iconKey={null}
|
||||
selected={selectedIcon === null}
|
||||
color={selectedColor}
|
||||
provider={provider}
|
||||
serverId={serverId}
|
||||
onSelect={handleIconSelect}
|
||||
/>
|
||||
{AGENT_PROFILE_ICON_KEYS.map((key) => (
|
||||
@@ -265,7 +278,7 @@ export function AgentProfileAppearanceField({
|
||||
</View>
|
||||
</View>
|
||||
</Combobox>
|
||||
</Field>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -279,6 +292,8 @@ function identitySwatch(color: Exclude<AgentProfileColor, "none">) {
|
||||
return styles[IDENTITY_SWATCH_STYLE_KEYS[color]];
|
||||
}
|
||||
|
||||
const HERO_BUTTON_SIZE = bySizing({ touch: TOUCH_TARGET, pointer: 40 });
|
||||
|
||||
const styles = StyleSheet.create((theme) => {
|
||||
const geometry = createControlGeometry(theme);
|
||||
|
||||
@@ -292,6 +307,29 @@ const styles = StyleSheet.create((theme) => {
|
||||
},
|
||||
triggerSm: { ...geometry.fieldControlSm },
|
||||
triggerMd: { ...geometry.fieldControlMd },
|
||||
triggerHero: {
|
||||
width: HERO_BUTTON_SIZE,
|
||||
height: HERO_BUTTON_SIZE,
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
paddingHorizontal: 0,
|
||||
position: "relative",
|
||||
},
|
||||
triggerPressed: {
|
||||
backgroundColor: theme.colors.surface3,
|
||||
},
|
||||
heroCaretBadge: {
|
||||
position: "absolute",
|
||||
right: -theme.spacing[1],
|
||||
bottom: -theme.spacing[1],
|
||||
width: theme.spacing[4],
|
||||
height: theme.spacing[4],
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.surface1,
|
||||
borderWidth: theme.borderWidth[1],
|
||||
borderColor: theme.colors.borderAccent,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
// The field geometry pads for a line of text. This trigger holds a glyph and
|
||||
// a chevron, so it keeps the shared height and drops the text-sized inset.
|
||||
triggerIconOnly: {
|
||||
@@ -339,7 +377,7 @@ const styles = StyleSheet.create((theme) => {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
cellPressed: {
|
||||
opacity: 0.7,
|
||||
opacity: theme.opacity[50],
|
||||
},
|
||||
cellSelected: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
|
||||
@@ -0,0 +1,503 @@
|
||||
import { useCallback, useMemo, type ReactElement } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ArrowDown, ArrowUp, Copy, MoreVertical, Trash2, X } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DismissBackdrop } from "@/components/ui/dismiss-backdrop";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
|
||||
import { ScrollView } from "@/components/ui/scroll-view";
|
||||
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { OverlayLayerProvider, useOverlayLayer } from "@/lib/overlay-root";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { WindowChromeRegion, WindowChromeSafeArea } from "@/utils/desktop-window";
|
||||
import type { AgentProfileSeed, AgentProfileValue } from "../internal/profile-form-model";
|
||||
import {
|
||||
useAgentProfileFormSession,
|
||||
type AgentProfileFormSession,
|
||||
} from "../internal/use-profile-form-model";
|
||||
import { AgentProfileIconButton } from "./agent-profile-appearance-field";
|
||||
import { AgentProfileFormFields } from "./agent-profile-form-fields";
|
||||
|
||||
export const AGENT_PROFILE_DRAWER_WIDTH = 440;
|
||||
|
||||
const ThemedArrowUp = withUnistyles(ArrowUp);
|
||||
const ThemedArrowDown = withUnistyles(ArrowDown);
|
||||
const ThemedMoreVertical = withUnistyles(MoreVertical);
|
||||
const ThemedCopy = withUnistyles(Copy);
|
||||
const ThemedTrash2 = withUnistyles(Trash2);
|
||||
const ThemedX = withUnistyles(X);
|
||||
const destructiveIconColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||
|
||||
const duplicateMenuIcon = <ThemedCopy size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||
const removeMenuIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveIconColorMapping} />;
|
||||
|
||||
export interface AgentProfileDrawerProps {
|
||||
serverId: string;
|
||||
mode: "create" | "edit";
|
||||
profile?: AgentProfile;
|
||||
seed?: AgentProfileSeed;
|
||||
/** Optional pre-owned session so resizing between drawer and modal preserves unsaved edits. */
|
||||
session?: AgentProfileFormSession;
|
||||
/** Renders as an absolute right-edge slide-over instead of reflowing the roster beside it. */
|
||||
overlay?: boolean;
|
||||
canStepPrev?: boolean;
|
||||
canStepNext?: boolean;
|
||||
onStepPrev?: () => void;
|
||||
onStepNext?: () => void;
|
||||
onClose: () => void;
|
||||
onSave: (value: AgentProfileValue) => Promise<void>;
|
||||
onDuplicate?: (profileId: string) => void;
|
||||
onRemove?: (profileId: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Full-height right inspector drawer for creating and editing agent profiles.
|
||||
* Pinned header + independent scroll + pinned footer prevent vertical re-centering
|
||||
* when async provider options resolve.
|
||||
*/
|
||||
export function AgentProfileDrawer(props: AgentProfileDrawerProps): ReactElement {
|
||||
if (props.session) {
|
||||
return <AgentProfileDrawerContent {...props} session={props.session} />;
|
||||
}
|
||||
const key =
|
||||
props.mode === "edit"
|
||||
? `drawer-edit:${props.profile?.id ?? ""}`
|
||||
: `drawer-create:${props.seed?.provider ?? ""}:${props.seed?.modelId ?? ""}`;
|
||||
return <StandaloneAgentProfileDrawer key={key} {...props} />;
|
||||
}
|
||||
|
||||
function StandaloneAgentProfileDrawer(props: AgentProfileDrawerProps): ReactElement {
|
||||
const session = useAgentProfileFormSession({
|
||||
serverId: props.serverId,
|
||||
mode: props.mode,
|
||||
profile: props.profile,
|
||||
seed: props.seed,
|
||||
onSave: props.onSave,
|
||||
onSaved: props.onClose,
|
||||
});
|
||||
return <AgentProfileDrawerContent {...props} session={session} />;
|
||||
}
|
||||
|
||||
function DrawerOverflowMenu({
|
||||
profileName,
|
||||
disabled,
|
||||
onDuplicate,
|
||||
onRemove,
|
||||
}: {
|
||||
profileName: string;
|
||||
disabled: boolean;
|
||||
onDuplicate?: () => void;
|
||||
onRemove?: () => void;
|
||||
}): ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
if (!onDuplicate && !onRemove) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<DropdownMenu compactMode="sheet">
|
||||
<ToolbarButton
|
||||
kind="menu"
|
||||
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
|
||||
disabled={disabled}
|
||||
testID="agent-profile-drawer-more"
|
||||
>
|
||||
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
<DropdownMenuContent side="bottom" align="end" width={180}>
|
||||
{onDuplicate ? (
|
||||
<DropdownMenuItem
|
||||
leading={duplicateMenuIcon}
|
||||
onSelect={onDuplicate}
|
||||
testID="agent-profile-drawer-duplicate"
|
||||
>
|
||||
{t("settings.host.agentProfiles.duplicate")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{onDuplicate && onRemove ? <DropdownMenuSeparator /> : null}
|
||||
{onRemove ? (
|
||||
<DropdownMenuItem
|
||||
destructive
|
||||
leading={removeMenuIcon}
|
||||
onSelect={onRemove}
|
||||
testID="agent-profile-drawer-remove"
|
||||
>
|
||||
{t("settings.host.agentProfiles.remove")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function DrawerHeader({
|
||||
serverId,
|
||||
mode,
|
||||
state,
|
||||
canStepPrev,
|
||||
canStepNext,
|
||||
onStepPrev,
|
||||
onStepNext,
|
||||
onDuplicate,
|
||||
onRemove,
|
||||
onAppearanceChange,
|
||||
onClose,
|
||||
}: {
|
||||
serverId: string;
|
||||
mode: "create" | "edit";
|
||||
state: AgentProfileFormSession["state"];
|
||||
canStepPrev: boolean;
|
||||
canStepNext: boolean;
|
||||
onStepPrev?: () => void;
|
||||
onStepNext?: () => void;
|
||||
onDuplicate?: () => void;
|
||||
onRemove?: () => void;
|
||||
onAppearanceChange: (value: { icon: string; color: string }) => void;
|
||||
onClose: () => void;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const fallbackTitle =
|
||||
mode === "edit"
|
||||
? t("settings.host.agentProfiles.editProfileTitle")
|
||||
: t("settings.host.agentProfiles.addProfileTitle");
|
||||
const title = state.name.trim() || fallbackTitle;
|
||||
const parts = [state.providerDisplay?.label, state.modelDisplay?.label].filter(Boolean);
|
||||
const subtitle =
|
||||
parts.length > 0 ? parts.join(" · ") : t("settings.host.agentProfiles.chooseModelPlaceholder");
|
||||
const showSteppers = mode === "edit" && Boolean(onStepPrev && onStepNext);
|
||||
|
||||
return (
|
||||
<View style={styles.headerChrome}>
|
||||
<TitlebarDragRegion />
|
||||
<WindowChromeSafeArea placement="below" />
|
||||
<View style={styles.header}>
|
||||
<View style={styles.headerIdentity}>
|
||||
<AgentProfileIconButton
|
||||
label={t("settings.host.agentProfiles.iconLabel")}
|
||||
icon={state.icon}
|
||||
color={state.color}
|
||||
provider={state.provider || undefined}
|
||||
serverId={serverId}
|
||||
onChange={onAppearanceChange}
|
||||
variant="hero"
|
||||
disabled={state.isSubmitting}
|
||||
triggerTestID="agent-profile-icon-trigger"
|
||||
/>
|
||||
<View style={styles.headerText}>
|
||||
<Text style={styles.headerTitle} numberOfLines={1} testID="agent-profile-drawer-title">
|
||||
{title}
|
||||
</Text>
|
||||
<Text style={styles.headerSubtitle} numberOfLines={1}>
|
||||
{subtitle}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.headerActions}>
|
||||
{showSteppers && onStepPrev && onStepNext ? (
|
||||
<>
|
||||
<ToolbarButton
|
||||
label={t("settings.host.agentProfiles.previousProfile")}
|
||||
onPress={onStepPrev}
|
||||
disabled={!canStepPrev || state.isSubmitting}
|
||||
testID="agent-profile-drawer-prev"
|
||||
>
|
||||
<ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
<ToolbarButton
|
||||
label={t("settings.host.agentProfiles.nextProfile")}
|
||||
onPress={onStepNext}
|
||||
disabled={!canStepNext || state.isSubmitting}
|
||||
testID="agent-profile-drawer-next"
|
||||
>
|
||||
<ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
</>
|
||||
) : null}
|
||||
{mode === "edit" ? (
|
||||
<DrawerOverflowMenu
|
||||
profileName={title}
|
||||
disabled={state.isSubmitting}
|
||||
onDuplicate={onDuplicate}
|
||||
onRemove={onRemove}
|
||||
/>
|
||||
) : null}
|
||||
<ToolbarButton
|
||||
label={t("common.actions.close")}
|
||||
onPress={onClose}
|
||||
disabled={state.isSubmitting}
|
||||
testID="agent-profile-drawer-close"
|
||||
>
|
||||
<ThemedX size={ICON_SIZE.md} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function DrawerFooter({
|
||||
canSubmit,
|
||||
isSubmitting,
|
||||
onClose,
|
||||
onSave,
|
||||
}: {
|
||||
canSubmit: boolean;
|
||||
isSubmitting: boolean;
|
||||
onClose: () => void;
|
||||
onSave: () => void;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.footer}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onPress={onClose}
|
||||
disabled={isSubmitting}
|
||||
testID="agent-profile-cancel-button"
|
||||
>
|
||||
{t("common.actions.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="default"
|
||||
onPress={onSave}
|
||||
disabled={!canSubmit}
|
||||
loading={isSubmitting}
|
||||
testID="agent-profile-save-button"
|
||||
>
|
||||
{t("settings.host.agentProfiles.save")}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentProfileDrawerContent({
|
||||
serverId,
|
||||
mode,
|
||||
profile,
|
||||
session,
|
||||
overlay = false,
|
||||
canStepPrev = false,
|
||||
canStepNext = false,
|
||||
onStepPrev,
|
||||
onStepNext,
|
||||
onClose,
|
||||
onDuplicate,
|
||||
onRemove,
|
||||
}: AgentProfileDrawerProps & { session: AgentProfileFormSession }): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const { model, state, save } = session;
|
||||
const drawerLayer = useOverlayLayer("floating");
|
||||
|
||||
const handleOverlayKeyDown = useCallback(
|
||||
(event: KeyboardInputEvent) => {
|
||||
if (event.key !== "Escape") {
|
||||
return false;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!state.isSubmitting) {
|
||||
onClose();
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[onClose, state.isSubmitting],
|
||||
);
|
||||
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
keys: ["Escape"],
|
||||
active: true,
|
||||
layer: drawerLayer,
|
||||
// Only trap focus in slide-over overlay mode; a docked drawer sits beside the
|
||||
// interactive roster and must let users click and type in roster search.
|
||||
manageFocus: overlay,
|
||||
onKeyDown: handleOverlayKeyDown,
|
||||
});
|
||||
|
||||
const handleAppearanceChange = useCallback(
|
||||
(value: { icon: string; color: string }) => model.setAppearance(value),
|
||||
[model],
|
||||
);
|
||||
|
||||
const handleSavePress = useCallback(() => {
|
||||
void save();
|
||||
}, [save]);
|
||||
|
||||
const handleDuplicate = useCallback(() => {
|
||||
if (profile && onDuplicate) {
|
||||
onDuplicate(profile.id);
|
||||
}
|
||||
}, [onDuplicate, profile]);
|
||||
|
||||
const handleRemove = useCallback(() => {
|
||||
if (profile && onRemove) {
|
||||
onRemove(profile.id);
|
||||
}
|
||||
}, [onRemove, profile]);
|
||||
|
||||
const handleBackdropPress = useCallback(() => {
|
||||
if (!state.isSubmitting) {
|
||||
onClose();
|
||||
}
|
||||
}, [onClose, state.isSubmitting]);
|
||||
|
||||
const drawerStyle = useMemo(
|
||||
() => [styles.drawer, overlay && styles.drawerOverlay, overlay && { zIndex: drawerLayer }],
|
||||
[drawerLayer, overlay],
|
||||
);
|
||||
const overlayHostStyle = useMemo(
|
||||
() => [styles.overlayHost, { zIndex: drawerLayer }],
|
||||
[drawerLayer],
|
||||
);
|
||||
|
||||
const drawerPanel = (
|
||||
<WindowChromeRegion corners="top-right">
|
||||
<OverlayLayerProvider layer={drawerLayer}>
|
||||
<View ref={setOverlayScope} style={drawerStyle} testID="agent-profile-drawer">
|
||||
<DrawerHeader
|
||||
serverId={serverId}
|
||||
mode={mode}
|
||||
state={state}
|
||||
canStepPrev={canStepPrev}
|
||||
canStepNext={canStepNext}
|
||||
onStepPrev={onStepPrev}
|
||||
onStepNext={onStepNext}
|
||||
onDuplicate={profile && onDuplicate ? handleDuplicate : undefined}
|
||||
onRemove={profile && onRemove ? handleRemove : undefined}
|
||||
onAppearanceChange={handleAppearanceChange}
|
||||
onClose={onClose}
|
||||
/>
|
||||
|
||||
<ScrollView style={styles.scroll} keyboardShouldPersistTaps="handled">
|
||||
<View style={styles.scrollContent}>
|
||||
<AgentProfileFormFields
|
||||
serverId={serverId}
|
||||
model={model}
|
||||
state={state}
|
||||
showInlineIcon={false}
|
||||
collapsibleDefaults={false}
|
||||
/>
|
||||
</View>
|
||||
</ScrollView>
|
||||
|
||||
<DrawerFooter
|
||||
canSubmit={state.canSubmit}
|
||||
isSubmitting={state.isSubmitting}
|
||||
onClose={onClose}
|
||||
onSave={handleSavePress}
|
||||
/>
|
||||
</View>
|
||||
</OverlayLayerProvider>
|
||||
</WindowChromeRegion>
|
||||
);
|
||||
|
||||
if (!overlay) {
|
||||
return drawerPanel;
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={overlayHostStyle} pointerEvents="box-none">
|
||||
<View style={styles.overlayBackdrop} pointerEvents="none" />
|
||||
<DismissBackdrop label={t("common.actions.close")} onPress={handleBackdropPress} />
|
||||
{drawerPanel}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
overlayHost: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
flexDirection: "row",
|
||||
justifyContent: "flex-end",
|
||||
},
|
||||
overlayBackdrop: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
backgroundColor: theme.colors.background,
|
||||
opacity: theme.opacity[50],
|
||||
},
|
||||
drawer: {
|
||||
width: AGENT_PROFILE_DRAWER_WIDTH,
|
||||
flexShrink: 0,
|
||||
backgroundColor: theme.colors.surface0,
|
||||
borderLeftWidth: theme.borderWidth[1],
|
||||
borderLeftColor: theme.colors.borderAccent,
|
||||
},
|
||||
drawerOverlay: {
|
||||
height: "100%",
|
||||
...theme.shadow.lg,
|
||||
},
|
||||
headerChrome: {
|
||||
position: "relative",
|
||||
borderBottomWidth: theme.borderWidth[1],
|
||||
borderBottomColor: theme.colors.border,
|
||||
},
|
||||
header: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: theme.spacing[3],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingVertical: theme.spacing[4],
|
||||
},
|
||||
headerIdentity: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
headerText: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
gap: theme.spacing[0.5],
|
||||
},
|
||||
headerTitle: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
headerSubtitle: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
headerActions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
flexShrink: 0,
|
||||
},
|
||||
scroll: {
|
||||
flex: 1,
|
||||
},
|
||||
scrollContent: {
|
||||
padding: theme.spacing[4],
|
||||
paddingBottom: theme.spacing[8],
|
||||
},
|
||||
footer: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "flex-end",
|
||||
gap: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingVertical: theme.spacing[3],
|
||||
borderTopWidth: theme.borderWidth[1],
|
||||
borderTopColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface0,
|
||||
},
|
||||
}));
|
||||
@@ -1,36 +1,16 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { AgentOptionControl, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import { readSelectOption, readToggleOption } from "@/agent-controls/option-controls";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { type ControlSize } from "@/components/ui/control-geometry";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import type { AgentProfileSeed, AgentProfileValue } from "../internal/profile-form-model";
|
||||
import {
|
||||
SelectField,
|
||||
type SelectFieldDisplay,
|
||||
type SelectFieldOption,
|
||||
} from "@/components/ui/select-field";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
import { AgentProfileAppearanceField } from "./agent-profile-appearance-field";
|
||||
import type {
|
||||
AgentProfileFormModel,
|
||||
AgentProfileFormOption,
|
||||
AgentProfileSeed,
|
||||
AgentProfileValue,
|
||||
} from "../internal/profile-form-model";
|
||||
import {
|
||||
useAgentProfileFormCatalog,
|
||||
useAgentProfileFormControls,
|
||||
} from "../internal/use-profile-form-inputs";
|
||||
import {
|
||||
useAgentProfileFormModel,
|
||||
useAgentProfileFormState,
|
||||
useAgentProfileFormSession,
|
||||
type AgentProfileFormSession,
|
||||
} from "../internal/use-profile-form-model";
|
||||
import { AgentProfileFormFields } from "./agent-profile-form-fields";
|
||||
|
||||
export interface AgentProfileEditModalProps {
|
||||
serverId: string;
|
||||
@@ -38,16 +18,15 @@ export interface AgentProfileEditModalProps {
|
||||
mode: "create" | "edit";
|
||||
profile?: AgentProfile;
|
||||
seed?: AgentProfileSeed;
|
||||
/** Optional pre-owned session so resizing between drawer and modal preserves unsaved edits. */
|
||||
session?: AgentProfileFormSession;
|
||||
/** Starts create mode with Mode, Thinking, Notes & Options collapsed behind a summary row. */
|
||||
collapsibleDefaults?: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (value: AgentProfileValue) => Promise<void>;
|
||||
onRemove?: (profileId: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only reachable before the catalog lands. Every select is seeded to a concrete
|
||||
* id as soon as one exists, and none of them offer an "unset" row.
|
||||
*/
|
||||
const UNSET_VALUE = "";
|
||||
|
||||
function openKey(props: AgentProfileEditModalProps): string {
|
||||
if (props.mode === "edit") {
|
||||
return `edit:${props.profile?.id ?? ""}`;
|
||||
@@ -57,7 +36,11 @@ function openKey(props: AgentProfileEditModalProps): string {
|
||||
|
||||
/**
|
||||
* Create and edit never share a mounted instance: the body is keyed on mode plus
|
||||
* profile id, so every open constructs a form model seeded from that record.
|
||||
* profile id (unless the caller lifts `session`), so every open constructs a form
|
||||
* model seeded from that record.
|
||||
*
|
||||
* Used for editing from the composer model picker and on compact/narrow screens
|
||||
* where Settings cannot host a slide-over drawer.
|
||||
*/
|
||||
export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactElement | null {
|
||||
const [renderedProps, setRenderedProps] = useState<AgentProfileEditModalProps | null>(() =>
|
||||
@@ -101,10 +84,24 @@ export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactE
|
||||
return null;
|
||||
}
|
||||
|
||||
const activeProps = props.visible ? props : renderedProps;
|
||||
|
||||
if (activeProps.session) {
|
||||
return (
|
||||
<AgentProfileEditModalContent
|
||||
{...activeProps}
|
||||
session={activeProps.session}
|
||||
visible={sheetVisible}
|
||||
onClose={requestClose}
|
||||
onDismiss={handleDismiss}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<OpenAgentProfileEditModal
|
||||
key={openKey(renderedProps)}
|
||||
{...renderedProps}
|
||||
<StandaloneAgentProfileEditModal
|
||||
key={openKey(activeProps)}
|
||||
{...activeProps}
|
||||
visible={sheetVisible}
|
||||
onClose={requestClose}
|
||||
onDismiss={handleDismiss}
|
||||
@@ -112,36 +109,36 @@ export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactE
|
||||
);
|
||||
}
|
||||
|
||||
function toSelectOptions(options: AgentProfileFormOption[]): SelectFieldOption<string>[] {
|
||||
return options.map((option) => ({
|
||||
id: option.id,
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
...(option.description ? { description: option.description } : {}),
|
||||
testID: option.testID,
|
||||
}));
|
||||
function StandaloneAgentProfileEditModal(
|
||||
props: AgentProfileEditModalProps & { onDismiss: () => void },
|
||||
): ReactElement {
|
||||
const session = useAgentProfileFormSession({
|
||||
serverId: props.serverId,
|
||||
mode: props.mode,
|
||||
profile: props.profile,
|
||||
seed: props.seed,
|
||||
onSave: props.onSave,
|
||||
onSaved: props.onClose,
|
||||
});
|
||||
return <AgentProfileEditModalContent {...props} session={session} />;
|
||||
}
|
||||
|
||||
function OpenAgentProfileEditModal({
|
||||
function AgentProfileEditModalContent({
|
||||
serverId,
|
||||
visible,
|
||||
mode,
|
||||
profile,
|
||||
seed,
|
||||
session,
|
||||
collapsibleDefaults,
|
||||
onClose,
|
||||
onDismiss,
|
||||
onSave,
|
||||
}: AgentProfileEditModalProps & { onDismiss: () => void }): ReactElement {
|
||||
onRemove,
|
||||
}: AgentProfileEditModalProps & {
|
||||
session: AgentProfileFormSession;
|
||||
onDismiss: () => void;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const controlSize: ControlSize = "md";
|
||||
const snapshot = useMemo(
|
||||
() => ({ mode, ...(profile ? { profile } : {}), ...(seed ? { seed } : {}) }),
|
||||
[mode, profile, seed],
|
||||
);
|
||||
const model = useAgentProfileFormModel(snapshot);
|
||||
const state = useAgentProfileFormState(model);
|
||||
useAgentProfileFormCatalog({ serverId, model });
|
||||
useAgentProfileFormControls({ serverId, model, state });
|
||||
const { model, state, save } = session;
|
||||
|
||||
const sheetHeader = useMemo<SheetHeader>(
|
||||
() => ({
|
||||
@@ -153,59 +150,9 @@ function OpenAgentProfileEditModal({
|
||||
[mode, t],
|
||||
);
|
||||
|
||||
const providerOptions = useMemo(
|
||||
() => toSelectOptions(state.providerOptions),
|
||||
[state.providerOptions],
|
||||
);
|
||||
const modelOptions = useMemo(() => toSelectOptions(state.modelOptions), [state.modelOptions]);
|
||||
const modeOptions = useMemo(() => toSelectOptions(state.modeOptions), [state.modeOptions]);
|
||||
const thinkingOptions = useMemo(
|
||||
() => toSelectOptions(state.thinkingOptions),
|
||||
[state.thinkingOptions],
|
||||
);
|
||||
|
||||
const handleAppearanceChange = useCallback(
|
||||
(value: { icon: string; color: string }) => model.setAppearance(value),
|
||||
[model],
|
||||
);
|
||||
const handleProviderChange = useCallback(
|
||||
(value: string, display: SelectFieldDisplay) => model.setProvider(value, display),
|
||||
[model],
|
||||
);
|
||||
const handleModelChange = useCallback(
|
||||
(value: string, display: SelectFieldDisplay) => model.setModel(value, value ? display : null),
|
||||
[model],
|
||||
);
|
||||
const handleModeChange = useCallback(
|
||||
(value: string, display: SelectFieldDisplay) => model.setMode(value, value ? display : null),
|
||||
[model],
|
||||
);
|
||||
const handleThinkingChange = useCallback(
|
||||
(value: string, display: SelectFieldDisplay) =>
|
||||
model.setThinking(value, value ? display : null),
|
||||
[model],
|
||||
);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
const value = model.getState().submitValue;
|
||||
if (!value) {
|
||||
return;
|
||||
}
|
||||
model.setSubmitError(null);
|
||||
model.setSubmitting(true);
|
||||
try {
|
||||
await onSave(value);
|
||||
onClose();
|
||||
} catch (error) {
|
||||
model.setSubmitError(toErrorMessage(error));
|
||||
} finally {
|
||||
model.setSubmitting(false);
|
||||
}
|
||||
}, [model, onClose, onSave]);
|
||||
|
||||
const handleSavePress = useCallback(() => {
|
||||
void handleSave();
|
||||
}, [handleSave]);
|
||||
void save();
|
||||
}, [save]);
|
||||
|
||||
const handleCancel = useCallback(() => {
|
||||
if (state.isSubmitting) {
|
||||
@@ -214,170 +161,31 @@ function OpenAgentProfileEditModal({
|
||||
onClose();
|
||||
}, [onClose, state.isSubmitting]);
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
visible={visible}
|
||||
header={sheetHeader}
|
||||
onClose={handleCancel}
|
||||
onDismiss={onDismiss}
|
||||
desktopMaxWidth={520}
|
||||
testID="agent-profile-edit-modal"
|
||||
>
|
||||
<View style={styles.body}>
|
||||
<View style={styles.nameRow}>
|
||||
<View style={styles.iconField}>
|
||||
<AgentProfileAppearanceField
|
||||
label={t("settings.host.agentProfiles.iconLabel")}
|
||||
icon={state.icon}
|
||||
color={state.color}
|
||||
onChange={handleAppearanceChange}
|
||||
const handleRemove = useCallback(() => {
|
||||
if (!profile || !onRemove) {
|
||||
return;
|
||||
}
|
||||
onRemove(profile.id);
|
||||
}, [onRemove, profile]);
|
||||
|
||||
const footer = useMemo(
|
||||
() => (
|
||||
<View style={styles.footer}>
|
||||
<View style={styles.footerStart}>
|
||||
{mode === "edit" && profile && onRemove ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onPress={handleRemove}
|
||||
disabled={state.isSubmitting}
|
||||
size={controlSize}
|
||||
testID="agent-profile-icon-field"
|
||||
triggerTestID="agent-profile-icon-trigger"
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.nameField}>
|
||||
<Field
|
||||
label={t("settings.host.agentProfiles.nameLabel")}
|
||||
testID="agent-profile-name-field"
|
||||
testID="agent-profile-modal-remove-button"
|
||||
>
|
||||
<FormTextInput
|
||||
initialValue={seed?.name ?? profile?.name ?? ""}
|
||||
onChangeText={model.setName}
|
||||
placeholder={t("settings.host.agentProfiles.namePlaceholder")}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
editable={!state.isSubmitting}
|
||||
size={controlSize}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.nameLabel")}
|
||||
testID="agent-profile-name-input"
|
||||
/>
|
||||
</Field>
|
||||
</View>
|
||||
{t("settings.host.agentProfiles.remove")}
|
||||
</Button>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<SelectField
|
||||
label={t("settings.host.agentProfiles.providerLabel")}
|
||||
value={state.provider || null}
|
||||
selectedDisplay={state.providerDisplay}
|
||||
options={providerOptions}
|
||||
onChange={handleProviderChange}
|
||||
placeholder={t("settings.host.agentProfiles.providerPlaceholder")}
|
||||
emptyText={t("settings.host.agentProfiles.noProviders")}
|
||||
loading={state.catalogResolution !== "complete"}
|
||||
disabled={state.isSubmitting}
|
||||
searchable={providerOptions.length > 6}
|
||||
title={t("settings.host.agentProfiles.providerLabel")}
|
||||
size={controlSize}
|
||||
testID="agent-profile-provider-field"
|
||||
triggerTestID="agent-profile-provider-trigger"
|
||||
/>
|
||||
|
||||
{state.disclosure.showModelField ? (
|
||||
<SelectField
|
||||
label={t("settings.host.agentProfiles.modelLabel")}
|
||||
value={state.modelId || UNSET_VALUE}
|
||||
selectedDisplay={state.modelDisplay}
|
||||
options={modelOptions}
|
||||
onChange={handleModelChange}
|
||||
placeholder={t("settings.host.agentProfiles.modelLabel")}
|
||||
emptyText={t("settings.host.agentProfiles.noModels")}
|
||||
disabled={state.isSubmitting}
|
||||
searchable={modelOptions.length > 6}
|
||||
title={t("settings.host.agentProfiles.modelLabel")}
|
||||
size={controlSize}
|
||||
testID="agent-profile-model-field"
|
||||
triggerTestID="agent-profile-model-trigger"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{state.disclosure.showModeField ? (
|
||||
<SelectField
|
||||
label={t("settings.host.agentProfiles.modeLabel")}
|
||||
value={state.modeId || UNSET_VALUE}
|
||||
selectedDisplay={state.modeDisplay}
|
||||
options={modeOptions}
|
||||
onChange={handleModeChange}
|
||||
placeholder={t("settings.host.agentProfiles.modeLabel")}
|
||||
emptyText={t("settings.host.agentProfiles.noModes")}
|
||||
disabled={state.isSubmitting}
|
||||
searchable={modeOptions.length > 6}
|
||||
title={t("settings.host.agentProfiles.modeLabel")}
|
||||
size={controlSize}
|
||||
testID="agent-profile-mode-field"
|
||||
triggerTestID="agent-profile-mode-trigger"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{state.disclosure.showThinkingField ? (
|
||||
<SelectField
|
||||
label={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
value={state.thinkingOptionId || UNSET_VALUE}
|
||||
selectedDisplay={state.thinkingDisplay}
|
||||
options={thinkingOptions}
|
||||
onChange={handleThinkingChange}
|
||||
placeholder={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
emptyText={t("settings.host.agentProfiles.noThinkingOptions")}
|
||||
disabled={state.isSubmitting}
|
||||
searchable={thinkingOptions.length > 6}
|
||||
title={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
size={controlSize}
|
||||
testID="agent-profile-thinking-field"
|
||||
triggerTestID="agent-profile-thinking-trigger"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{state.disclosure.showControlsField ? (
|
||||
<Field
|
||||
label={t("settings.host.agentProfiles.featuresLabel")}
|
||||
testID="agent-profile-features-field"
|
||||
>
|
||||
<View style={styles.featureCard} testID="agent-profile-features-card">
|
||||
{state.controls.map((control, index) => (
|
||||
<AgentProfileControlRow
|
||||
key={control.key}
|
||||
control={control}
|
||||
options={state.controlOptions}
|
||||
isFirst={index === 0}
|
||||
disabled={state.isSubmitting}
|
||||
size={controlSize}
|
||||
model={model}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</Field>
|
||||
) : null}
|
||||
|
||||
<Field
|
||||
label={t("settings.host.agentProfiles.notesLabel")}
|
||||
hint={t("settings.host.agentProfiles.notesHint")}
|
||||
testID="agent-profile-notes-field"
|
||||
>
|
||||
<FormTextInput
|
||||
initialValue={profile?.notes ?? ""}
|
||||
onChangeText={model.setNotes}
|
||||
placeholder={t("settings.host.agentProfiles.notesPlaceholder")}
|
||||
multiline
|
||||
numberOfLines={4}
|
||||
style={styles.notesInput}
|
||||
editable={!state.isSubmitting}
|
||||
size={controlSize}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.notesLabel")}
|
||||
testID="agent-profile-notes-input"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
{state.submitError ? (
|
||||
<Text style={styles.submitError} testID="agent-profile-submit-error">
|
||||
{state.submitError}
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
<View style={styles.actions}>
|
||||
<View style={styles.footerEnd}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
style={styles.actionButton}
|
||||
onPress={handleCancel}
|
||||
disabled={state.isSubmitting}
|
||||
testID="agent-profile-cancel-button"
|
||||
@@ -386,177 +194,65 @@ function OpenAgentProfileEditModal({
|
||||
</Button>
|
||||
<Button
|
||||
variant="default"
|
||||
style={styles.actionButton}
|
||||
onPress={handleSavePress}
|
||||
disabled={!state.canSubmit}
|
||||
loading={state.isSubmitting}
|
||||
testID="agent-profile-save-button"
|
||||
>
|
||||
{state.isSubmitting
|
||||
? t("settings.host.agentProfiles.saving")
|
||||
: t("settings.host.agentProfiles.save")}
|
||||
{t("settings.host.agentProfiles.save")}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
),
|
||||
[
|
||||
handleCancel,
|
||||
handleRemove,
|
||||
handleSavePress,
|
||||
mode,
|
||||
onRemove,
|
||||
profile,
|
||||
state.canSubmit,
|
||||
state.isSubmitting,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
visible={visible}
|
||||
header={sheetHeader}
|
||||
footer={footer}
|
||||
onClose={handleCancel}
|
||||
onDismiss={onDismiss}
|
||||
desktopMaxWidth={500}
|
||||
testID="agent-profile-edit-modal"
|
||||
>
|
||||
<AgentProfileFormFields
|
||||
serverId={serverId}
|
||||
model={model}
|
||||
state={state}
|
||||
collapsibleDefaults={collapsibleDefaults ?? mode === "create"}
|
||||
/>
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentProfileControlRow({
|
||||
control,
|
||||
options,
|
||||
isFirst,
|
||||
disabled,
|
||||
size,
|
||||
model,
|
||||
}: {
|
||||
control: AgentOptionControl;
|
||||
options: ProviderOptions;
|
||||
isFirst: boolean;
|
||||
disabled: boolean;
|
||||
size: ControlSize;
|
||||
model: AgentProfileFormModel;
|
||||
}): ReactElement {
|
||||
const rowStyle = useMemo(
|
||||
() => [styles.featureRow, isFirst ? null : styles.featureRowBorder],
|
||||
[isFirst],
|
||||
);
|
||||
const handleToggle = useCallback(
|
||||
(value: boolean) => model.setOption(control.key, value),
|
||||
[control.key, model],
|
||||
);
|
||||
const handleSelect = useCallback(
|
||||
(value: string) => model.setOption(control.key, value),
|
||||
[control.key, model],
|
||||
);
|
||||
const selectOptions = useMemo<SelectFieldOption<string>[]>(
|
||||
() =>
|
||||
control.type === "select"
|
||||
? control.choices.map((choice) => ({
|
||||
id: choice.value,
|
||||
value: choice.value,
|
||||
label: choice.label,
|
||||
...(choice.description ? { description: choice.description } : {}),
|
||||
testID: `agent-profile-feature-option-${control.key}-${choice.value}`,
|
||||
}))
|
||||
: [],
|
||||
[control],
|
||||
);
|
||||
const selectedValue = control.type === "select" ? readSelectOption(control, options) : null;
|
||||
const selectedDisplay = useMemo<SelectFieldDisplay | null>(() => {
|
||||
if (control.type !== "select" || !selectedValue) {
|
||||
return null;
|
||||
}
|
||||
const choice = control.choices.find((candidate) => candidate.value === selectedValue);
|
||||
return { label: choice?.label ?? selectedValue };
|
||||
}, [control, selectedValue]);
|
||||
|
||||
if (control.type === "select") {
|
||||
return (
|
||||
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
|
||||
<SelectField
|
||||
label={control.label}
|
||||
value={selectedValue}
|
||||
selectedDisplay={selectedDisplay}
|
||||
options={selectOptions}
|
||||
onChange={handleSelect}
|
||||
placeholder={control.label}
|
||||
emptyText={control.label}
|
||||
disabled={disabled}
|
||||
{...(control.description ? { hint: control.description } : {})}
|
||||
title={control.label}
|
||||
size={size}
|
||||
testID={`agent-profile-feature-field-${control.key}`}
|
||||
triggerTestID={`agent-profile-feature-trigger-${control.key}`}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
|
||||
<View style={styles.featureMeta}>
|
||||
<Text style={styles.featureLabel} numberOfLines={1}>
|
||||
{control.label}
|
||||
</Text>
|
||||
{control.description ? (
|
||||
<Text style={styles.featureDescription} numberOfLines={2}>
|
||||
{control.description}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Switch
|
||||
value={readToggleOption(control, options)}
|
||||
onValueChange={handleToggle}
|
||||
disabled={disabled}
|
||||
accessibilityLabel={control.label}
|
||||
testID={`agent-profile-feature-switch-${control.key}`}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
body: {
|
||||
gap: theme.spacing[4],
|
||||
paddingBottom: theme.spacing[2],
|
||||
},
|
||||
nameRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
// No width: the trigger is a glyph and a chevron, so it sizes to them.
|
||||
iconField: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
nameField: {
|
||||
footer: {
|
||||
flex: 1,
|
||||
},
|
||||
featureCard: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
borderRadius: theme.borderRadius.md,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
},
|
||||
featureRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: theme.spacing[3],
|
||||
paddingVertical: theme.spacing[3],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
featureRowBorder: {
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: theme.colors.border,
|
||||
},
|
||||
featureMeta: {
|
||||
flex: 1,
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
featureLabel: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
featureDescription: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
notesInput: {
|
||||
minHeight: 88,
|
||||
textAlignVertical: "top",
|
||||
},
|
||||
submitError: {
|
||||
color: theme.colors.statusDanger,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
actions: {
|
||||
footerStart: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
marginTop: theme.spacing[2],
|
||||
},
|
||||
actionButton: {
|
||||
flex: 1,
|
||||
footerEnd: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,567 @@
|
||||
import { useCallback, useMemo, useRef, type ReactElement, type ReactNode } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type {
|
||||
AgentOptionControl,
|
||||
AgentProvider,
|
||||
ProviderOptions,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import { readSelectOption, readToggleOption } from "@/agent-controls/option-controls";
|
||||
import { CombinedModelSelector } from "@/components/combined-model-selector";
|
||||
import {
|
||||
SettingsCard,
|
||||
SettingsCollapsibleRow,
|
||||
SettingsSelect,
|
||||
SettingsSwitch,
|
||||
} from "@/components/settings";
|
||||
import type { ControlSize } from "@/components/ui/control-geometry";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import {
|
||||
SelectField,
|
||||
SelectFieldTrigger,
|
||||
type SelectFieldDisplay,
|
||||
type SelectFieldOption,
|
||||
} from "@/components/ui/select-field";
|
||||
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { buildSelectableProviderSelectorProviders } from "@/provider-selection/provider-selection";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
|
||||
import type {
|
||||
AgentProfileFormModel,
|
||||
AgentProfileFormOption,
|
||||
AgentProfileFormState,
|
||||
} from "../internal/profile-form-model";
|
||||
import { AgentProfileIconButton } from "./agent-profile-appearance-field";
|
||||
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
|
||||
const UNSET_VALUE = "";
|
||||
|
||||
function toSelectOptions(options: AgentProfileFormOption[]): SelectFieldOption<string>[] {
|
||||
return options.map((option) => ({
|
||||
id: option.id,
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
...(option.description ? { description: option.description } : {}),
|
||||
testID: option.testID,
|
||||
}));
|
||||
}
|
||||
|
||||
function canUseSegmentedThinking(options: readonly AgentProfileFormOption[]): boolean {
|
||||
return (
|
||||
options.length >= 2 &&
|
||||
options.length <= 4 &&
|
||||
options.every((option) => option.label.trim().length <= 12)
|
||||
);
|
||||
}
|
||||
|
||||
export interface AgentProfileFormFieldsProps {
|
||||
serverId: string;
|
||||
model: AgentProfileFormModel;
|
||||
state: AgentProfileFormState;
|
||||
controlSize?: ControlSize;
|
||||
/** Embeds the icon+color picker beside the Name input (used in sheets; drawer places it in its hero). */
|
||||
showInlineIcon?: boolean;
|
||||
/** Collapses Mode, Thinking, Notes, and Options behind a SettingsCollapsibleRow until expanded. */
|
||||
collapsibleDefaults?: boolean;
|
||||
}
|
||||
|
||||
function ThinkingField({
|
||||
state,
|
||||
controlSize,
|
||||
onSelectChange,
|
||||
onSegmentChange,
|
||||
}: {
|
||||
state: AgentProfileFormState;
|
||||
controlSize: ControlSize;
|
||||
onSelectChange: (value: string, display: SelectFieldDisplay) => void;
|
||||
onSegmentChange: (value: string) => void;
|
||||
}): ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
const thinkingOptions = useMemo(
|
||||
() => toSelectOptions(state.thinkingOptions),
|
||||
[state.thinkingOptions],
|
||||
);
|
||||
const segmentedThinkingOptions = useMemo<SegmentedControlOption<string>[]>(
|
||||
() =>
|
||||
state.thinkingOptions.map((option) => ({
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
disabled: state.isSubmitting,
|
||||
testID: option.testID,
|
||||
})),
|
||||
[state.isSubmitting, state.thinkingOptions],
|
||||
);
|
||||
if (!state.disclosure.showThinkingField) {
|
||||
return null;
|
||||
}
|
||||
if (canUseSegmentedThinking(state.thinkingOptions)) {
|
||||
return (
|
||||
<Field
|
||||
label={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
testID="agent-profile-thinking-field"
|
||||
>
|
||||
<SegmentedControl
|
||||
options={segmentedThinkingOptions}
|
||||
value={state.thinkingOptionId || null}
|
||||
onValueChange={onSegmentChange}
|
||||
size={controlSize}
|
||||
testID="agent-profile-thinking-trigger"
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<SelectField
|
||||
label={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
value={state.thinkingOptionId || UNSET_VALUE}
|
||||
selectedDisplay={state.thinkingDisplay}
|
||||
options={thinkingOptions}
|
||||
onChange={onSelectChange}
|
||||
placeholder={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
emptyText={t("settings.host.agentProfiles.noThinkingOptions")}
|
||||
disabled={state.isSubmitting}
|
||||
searchable={thinkingOptions.length > 6}
|
||||
title={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
size={controlSize}
|
||||
testID="agent-profile-thinking-field"
|
||||
triggerTestID="agent-profile-thinking-trigger"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentProfileControlRow({
|
||||
control,
|
||||
options,
|
||||
disabled,
|
||||
model,
|
||||
}: {
|
||||
control: AgentOptionControl;
|
||||
options: ProviderOptions;
|
||||
disabled: boolean;
|
||||
model: AgentProfileFormModel;
|
||||
}): ReactElement {
|
||||
const handleToggle = useCallback(
|
||||
(value: boolean) => model.setOption(control.key, value),
|
||||
[control.key, model],
|
||||
);
|
||||
const handleSelect = useCallback(
|
||||
(value: string) => model.setOption(control.key, value),
|
||||
[control.key, model],
|
||||
);
|
||||
const selectOptions = useMemo(
|
||||
() =>
|
||||
control.type === "select"
|
||||
? control.choices.map((choice) => ({ label: choice.label, value: choice.value }))
|
||||
: [],
|
||||
[control],
|
||||
);
|
||||
|
||||
if (control.type === "select") {
|
||||
const selectedValue = readSelectOption(control, options) ?? control.choices[0]?.value ?? "";
|
||||
return (
|
||||
<SettingsSelect
|
||||
label={control.label}
|
||||
hint={control.description}
|
||||
value={selectedValue}
|
||||
options={selectOptions}
|
||||
onValueChange={handleSelect}
|
||||
disabled={disabled}
|
||||
testID={`agent-profile-feature-row-${control.key}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsSwitch
|
||||
label={control.label}
|
||||
hint={control.description}
|
||||
value={readToggleOption(control, options)}
|
||||
onValueChange={handleToggle}
|
||||
disabled={disabled}
|
||||
testID={`agent-profile-feature-row-${control.key}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentProfileAdvancedFields({
|
||||
model,
|
||||
state,
|
||||
controlSize,
|
||||
onModeChange,
|
||||
onThinkingSelectChange,
|
||||
onThinkingSegmentChange,
|
||||
}: {
|
||||
model: AgentProfileFormModel;
|
||||
state: AgentProfileFormState;
|
||||
controlSize: ControlSize;
|
||||
onModeChange: (value: string, display: SelectFieldDisplay) => void;
|
||||
onThinkingSelectChange: (value: string, display: SelectFieldDisplay) => void;
|
||||
onThinkingSegmentChange: (value: string) => void;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const modeOptions = useMemo(() => toSelectOptions(state.modeOptions), [state.modeOptions]);
|
||||
const providerOptionsTitle = state.providerDisplay?.label
|
||||
? t("settings.host.agentProfiles.providerOptionsLabel", {
|
||||
provider: state.providerDisplay.label,
|
||||
})
|
||||
: t("settings.host.agentProfiles.featuresLabel");
|
||||
const optionsPendingSpinner = useMemo(
|
||||
() =>
|
||||
state.controlsPending ? (
|
||||
<ThemedLoadingSpinner size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
) : null,
|
||||
[state.controlsPending],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{state.disclosure.showModeField ? (
|
||||
<SelectField
|
||||
label={t("settings.host.agentProfiles.modeLabel")}
|
||||
value={state.modeId || UNSET_VALUE}
|
||||
selectedDisplay={state.modeDisplay}
|
||||
options={modeOptions}
|
||||
onChange={onModeChange}
|
||||
placeholder={t("settings.host.agentProfiles.modeLabel")}
|
||||
emptyText={t("settings.host.agentProfiles.noModes")}
|
||||
disabled={state.isSubmitting}
|
||||
searchable={modeOptions.length > 6}
|
||||
title={t("settings.host.agentProfiles.modeLabel")}
|
||||
size={controlSize}
|
||||
testID="agent-profile-mode-field"
|
||||
triggerTestID="agent-profile-mode-trigger"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<ThinkingField
|
||||
state={state}
|
||||
controlSize={controlSize}
|
||||
onSelectChange={onThinkingSelectChange}
|
||||
onSegmentChange={onThinkingSegmentChange}
|
||||
/>
|
||||
|
||||
<Field
|
||||
label={t("settings.host.agentProfiles.notesLabel")}
|
||||
hint={t("settings.host.agentProfiles.notesHint")}
|
||||
testID="agent-profile-notes-field"
|
||||
>
|
||||
<FormTextInput
|
||||
initialValue={state.notes}
|
||||
onChangeText={model.setNotes}
|
||||
placeholder={t("settings.host.agentProfiles.notesPlaceholder")}
|
||||
multiline
|
||||
numberOfLines={3}
|
||||
style={styles.notesInput}
|
||||
editable={!state.isSubmitting}
|
||||
size={controlSize}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.notesLabel")}
|
||||
testID="agent-profile-notes-input"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
{state.disclosure.showControlsField ? (
|
||||
<Field
|
||||
label={providerOptionsTitle}
|
||||
trailing={optionsPendingSpinner}
|
||||
testID="agent-profile-features-field"
|
||||
>
|
||||
<View style={state.controlsPending ? styles.featureCardPending : undefined}>
|
||||
<SettingsCard testID="agent-profile-features-card">
|
||||
{state.controls.map((control) => (
|
||||
<AgentProfileControlRow
|
||||
key={control.key}
|
||||
control={control}
|
||||
options={state.controlOptions}
|
||||
disabled={state.isSubmitting || state.controlsPending}
|
||||
model={model}
|
||||
/>
|
||||
))}
|
||||
</SettingsCard>
|
||||
</View>
|
||||
</Field>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared profile form body used by both the desktop inspector drawer and the modal sheet.
|
||||
*
|
||||
* Layout order keeps inputs above async provider options: Model first (using Paseo's
|
||||
* shared CombinedModelSelector), Name + icon second, Mode & Thinking, "When to use",
|
||||
* and provider options last so loading options never shift controls above them.
|
||||
*/
|
||||
export function AgentProfileFormFields({
|
||||
serverId,
|
||||
model,
|
||||
state,
|
||||
controlSize = "md",
|
||||
showInlineIcon = true,
|
||||
collapsibleDefaults = false,
|
||||
}: AgentProfileFormFieldsProps): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const nameInputRef = useRef<EditingTextInputHandle>(null);
|
||||
const { entries, isLoading, isFetching, isRefreshing, refresh } = useProvidersSnapshot(serverId, {
|
||||
cwd: null,
|
||||
});
|
||||
|
||||
const modelSelectorProviders = useMemo(
|
||||
() =>
|
||||
buildSelectableProviderSelectorProviders(entries, {
|
||||
selectedProvider: state.provider || null,
|
||||
}),
|
||||
[entries, state.provider],
|
||||
);
|
||||
|
||||
const modelTriggerLeading = useMemo(
|
||||
() =>
|
||||
state.provider ? (
|
||||
<AgentProfileGlyph provider={state.provider} serverId={serverId} size={ICON_SIZE.sm} />
|
||||
) : null,
|
||||
[serverId, state.provider],
|
||||
);
|
||||
|
||||
const renderModelTrigger = useCallback(
|
||||
({
|
||||
selectedModelLabel,
|
||||
disabled,
|
||||
isOpen,
|
||||
hovered,
|
||||
pressed,
|
||||
}: {
|
||||
selectedModelLabel: string;
|
||||
onPress: () => void;
|
||||
disabled: boolean;
|
||||
isOpen: boolean;
|
||||
hovered: boolean;
|
||||
pressed: boolean;
|
||||
}): ReactNode => {
|
||||
const displayLabel =
|
||||
state.modelDisplay?.label ?? state.providerDisplay?.label ?? selectedModelLabel;
|
||||
return (
|
||||
<SelectFieldTrigger
|
||||
label={displayLabel}
|
||||
isPlaceholder={!state.provider}
|
||||
placeholder={t("settings.host.agentProfiles.chooseModelPlaceholder")}
|
||||
leading={modelTriggerLeading}
|
||||
disabled={disabled}
|
||||
active={hovered || pressed || isOpen}
|
||||
size={controlSize}
|
||||
testID="agent-profile-model-trigger"
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
controlSize,
|
||||
modelTriggerLeading,
|
||||
state.modelDisplay?.label,
|
||||
state.provider,
|
||||
state.providerDisplay?.label,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
const handleAppearanceChange = useCallback(
|
||||
(value: { icon: string; color: string }) => model.setAppearance(value),
|
||||
[model],
|
||||
);
|
||||
|
||||
const handleModelSelect = useCallback(
|
||||
(provider: AgentProvider, modelId: string) => {
|
||||
const previousName = model.getState().name;
|
||||
const entry = entries?.find((candidate) => candidate.provider === provider);
|
||||
const modelDef = entry?.models?.find((candidate) => candidate.id === modelId);
|
||||
model.setProviderModel(provider, modelId, {
|
||||
provider: { label: entry?.label ?? provider },
|
||||
model: modelId ? { label: modelDef?.label ?? modelId } : null,
|
||||
});
|
||||
const suggestedName = model.getState().name;
|
||||
if (suggestedName !== previousName) {
|
||||
nameInputRef.current?.replaceText(suggestedName);
|
||||
}
|
||||
},
|
||||
[entries, model],
|
||||
);
|
||||
|
||||
const handleRetryProvider = useCallback(
|
||||
(provider: AgentProvider) => {
|
||||
void refresh([provider]);
|
||||
},
|
||||
[refresh],
|
||||
);
|
||||
|
||||
const handleModeChange = useCallback(
|
||||
(value: string, display: SelectFieldDisplay) => model.setMode(value, value ? display : null),
|
||||
[model],
|
||||
);
|
||||
|
||||
const handleThinkingSelectChange = useCallback(
|
||||
(value: string, display: SelectFieldDisplay) =>
|
||||
model.setThinking(value, value ? display : null),
|
||||
[model],
|
||||
);
|
||||
|
||||
const handleThinkingSegmentChange = useCallback(
|
||||
(value: string) => {
|
||||
const option = state.thinkingOptions.find((candidate) => candidate.value === value);
|
||||
model.setThinking(value, option ? { label: option.label } : null);
|
||||
},
|
||||
[model, state.thinkingOptions],
|
||||
);
|
||||
|
||||
const hasRuntimeDefaults =
|
||||
state.disclosure.showModeField ||
|
||||
state.disclosure.showThinkingField ||
|
||||
state.disclosure.showControlsField;
|
||||
|
||||
const defaultsSummary = useMemo(() => {
|
||||
const parts: string[] = [];
|
||||
if (state.modeDisplay?.label) {
|
||||
parts.push(state.modeDisplay.label);
|
||||
}
|
||||
if (state.thinkingDisplay?.label) {
|
||||
parts.push(state.thinkingDisplay.label);
|
||||
}
|
||||
if (state.controls.length > 0) {
|
||||
parts.push(
|
||||
state.controls.length === 1
|
||||
? t("settings.host.agentProfiles.featureCountOne", { count: state.controls.length })
|
||||
: t("settings.host.agentProfiles.featureCount", { count: state.controls.length }),
|
||||
);
|
||||
}
|
||||
if (!state.notes.trim() && hasRuntimeDefaults) {
|
||||
parts.push(t("settings.host.agentProfiles.addRoutingNoteShort"));
|
||||
}
|
||||
return parts.join(" · ");
|
||||
}, [
|
||||
hasRuntimeDefaults,
|
||||
state.controls.length,
|
||||
state.modeDisplay?.label,
|
||||
state.notes,
|
||||
state.thinkingDisplay?.label,
|
||||
t,
|
||||
]);
|
||||
|
||||
const collapsibleLabel = hasRuntimeDefaults
|
||||
? t("settings.host.agentProfiles.customizeSettings")
|
||||
: t("settings.host.agentProfiles.addRoutingNoteShort");
|
||||
|
||||
const advancedFields = (
|
||||
<AgentProfileAdvancedFields
|
||||
model={model}
|
||||
state={state}
|
||||
controlSize={controlSize}
|
||||
onModeChange={handleModeChange}
|
||||
onThinkingSelectChange={handleThinkingSelectChange}
|
||||
onThinkingSegmentChange={handleThinkingSegmentChange}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={styles.body}>
|
||||
<Field label={t("settings.host.agentProfiles.modelLabel")} testID="agent-profile-model-field">
|
||||
<CombinedModelSelector
|
||||
providers={modelSelectorProviders}
|
||||
selectedProvider={state.provider}
|
||||
selectedModel={state.modelId}
|
||||
onSelect={handleModelSelect}
|
||||
isLoading={isLoading || isFetching}
|
||||
renderTrigger={renderModelTrigger}
|
||||
triggerFill
|
||||
serverId={serverId}
|
||||
disabled={state.isSubmitting}
|
||||
onRetryProvider={handleRetryProvider}
|
||||
isRetryingProvider={isRefreshing}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field label={t("settings.host.agentProfiles.nameLabel")} testID="agent-profile-name-field">
|
||||
<View style={styles.nameRow}>
|
||||
{showInlineIcon ? (
|
||||
<AgentProfileIconButton
|
||||
label={t("settings.host.agentProfiles.iconLabel")}
|
||||
icon={state.icon}
|
||||
color={state.color}
|
||||
provider={state.provider || undefined}
|
||||
serverId={serverId}
|
||||
onChange={handleAppearanceChange}
|
||||
disabled={state.isSubmitting}
|
||||
size={controlSize}
|
||||
triggerTestID="agent-profile-icon-trigger"
|
||||
/>
|
||||
) : null}
|
||||
<View style={styles.nameInputWrap}>
|
||||
<FormTextInput
|
||||
ref={nameInputRef}
|
||||
initialValue={state.name}
|
||||
onChangeText={model.setName}
|
||||
placeholder={t("settings.host.agentProfiles.namePlaceholder")}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
editable={!state.isSubmitting}
|
||||
size={controlSize}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.nameLabel")}
|
||||
testID="agent-profile-name-input"
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</Field>
|
||||
|
||||
{collapsibleDefaults ? (
|
||||
<SettingsCard>
|
||||
<SettingsCollapsibleRow
|
||||
label={collapsibleLabel}
|
||||
summary={defaultsSummary || undefined}
|
||||
testID="agent-profile-customize"
|
||||
>
|
||||
<View style={styles.collapsibleFields}>{advancedFields}</View>
|
||||
</SettingsCollapsibleRow>
|
||||
</SettingsCard>
|
||||
) : (
|
||||
advancedFields
|
||||
)}
|
||||
|
||||
{state.submitError ? (
|
||||
<Text style={styles.submitError} testID="agent-profile-submit-error">
|
||||
{state.submitError}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
body: {
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
nameRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
nameInputWrap: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
collapsibleFields: {
|
||||
padding: theme.spacing[4],
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
featureCardPending: {
|
||||
opacity: theme.opacity[50],
|
||||
},
|
||||
notesInput: {
|
||||
minHeight: theme.spacing[20],
|
||||
textAlignVertical: "top",
|
||||
},
|
||||
submitError: {
|
||||
color: theme.colors.palette.red[300],
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
}));
|
||||
@@ -1,57 +1,342 @@
|
||||
import { useCallback, useMemo, type ReactElement } from "react";
|
||||
import { useCallback, useMemo, useState, type ReactElement } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ArrowDown, ArrowUp, FileText, Pencil, Trash2 } from "lucide-react-native";
|
||||
import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
ArrowUpToLine,
|
||||
ChevronRight,
|
||||
Copy,
|
||||
GripVertical,
|
||||
MoreVertical,
|
||||
Pencil,
|
||||
Trash2,
|
||||
} from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DraggableListHandle } from "@/components/draggable-list";
|
||||
import { useOpenKebabMenuVisibility } from "@/components/sidebar/use-open-kebab-menu-visibility";
|
||||
import { bySizing, TOUCH_TARGET } from "@/components/ui/control-geometry";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
extraMutedIconColorMapping,
|
||||
foregroundIconColorMapping,
|
||||
mutedIconColorMapping,
|
||||
} from "@/components/ui/icon-color";
|
||||
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
|
||||
import { buildAgentProfileTags } from "../internal/profile-summary";
|
||||
import { buildAgentProfileRosterSummary } from "../internal/profile-summary";
|
||||
|
||||
/** Shared column & rail geometry consumed by both RosterTableHeader and AgentProfileRow. */
|
||||
export const ROSTER_COL_PROFILE_WIDTH = 184;
|
||||
export const ROSTER_COL_RUNTIME_WIDTH = 248;
|
||||
export const ROSTER_GRIP_WIDTH = bySizing({ touch: 28, pointer: 20 });
|
||||
export const ROSTER_TRAILING_WIDTH = bySizing({ touch: TOUCH_TARGET + 14, pointer: 42 });
|
||||
|
||||
const ROW_MIN_HEIGHT = bySizing({ touch: TOUCH_TARGET + 16, pointer: 56 });
|
||||
const GRIP_HANDLE_HEIGHT = bySizing({ touch: TOUCH_TARGET, pointer: 28 });
|
||||
|
||||
const ThemedGripVertical = withUnistyles(GripVertical);
|
||||
const ThemedMoreVertical = withUnistyles(MoreVertical);
|
||||
const ThemedChevronRight = withUnistyles(ChevronRight);
|
||||
const ThemedPencil = withUnistyles(Pencil);
|
||||
const ThemedCopy = withUnistyles(Copy);
|
||||
const ThemedArrowUp = withUnistyles(ArrowUp);
|
||||
const ThemedArrowDown = withUnistyles(ArrowDown);
|
||||
const ThemedPencil = withUnistyles(Pencil);
|
||||
const ThemedArrowUpToLine = withUnistyles(ArrowUpToLine);
|
||||
const ThemedTrash2 = withUnistyles(Trash2);
|
||||
const ThemedFileText = withUnistyles(FileText);
|
||||
|
||||
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||
const destructiveIconColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||
|
||||
const moveUpIcon = <ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
|
||||
const moveDownIcon = <ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
|
||||
const editIcon = <ThemedPencil size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
|
||||
const removeIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveColorMapping} />;
|
||||
const editMenuIcon = <ThemedPencil size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||
const duplicateMenuIcon = <ThemedCopy size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||
const moveUpMenuIcon = <ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||
const moveDownMenuIcon = <ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||
const moveTopMenuIcon = (
|
||||
<ThemedArrowUpToLine size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
);
|
||||
const removeMenuIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveIconColorMapping} />;
|
||||
|
||||
const HIDDEN_FROM_ASSISTIVE_TECH = {
|
||||
accessibilityElementsHidden: true,
|
||||
importantForAccessibility: "no-hide-descendants",
|
||||
"aria-hidden": true,
|
||||
} as const;
|
||||
|
||||
export interface AgentProfileRowProps {
|
||||
serverId: string;
|
||||
profile: AgentProfile;
|
||||
entries: readonly ProviderSnapshotEntry[] | undefined;
|
||||
isFirst: boolean;
|
||||
isLast: boolean;
|
||||
selected?: boolean;
|
||||
dragging?: boolean;
|
||||
/** Stacked layout when narrow or on compact form factors. */
|
||||
compactLayout?: boolean;
|
||||
/** Hides the drag handle when showing filtered search results while preserving the rail. */
|
||||
reorderable?: boolean;
|
||||
onEdit: (id: string) => void;
|
||||
onDuplicate: (id: string) => void;
|
||||
onRemove: (id: string) => void;
|
||||
onMoveUp: (id: string) => void;
|
||||
onMoveDown: (id: string) => void;
|
||||
onMoveToTop: (id: string) => void;
|
||||
}
|
||||
|
||||
function AgentProfileRowMenu({
|
||||
profileId,
|
||||
profileName,
|
||||
isFirst,
|
||||
isLast,
|
||||
reorderable,
|
||||
menuProps,
|
||||
onEdit,
|
||||
onDuplicate,
|
||||
onMoveUp,
|
||||
onMoveDown,
|
||||
onMoveToTop,
|
||||
onRemove,
|
||||
}: {
|
||||
profileId: string;
|
||||
profileName: string;
|
||||
isFirst: boolean;
|
||||
isLast: boolean;
|
||||
reorderable: boolean;
|
||||
menuProps: { open: boolean; onOpenChange: (open: boolean) => void };
|
||||
onEdit: () => void;
|
||||
onDuplicate: () => void;
|
||||
onMoveUp: () => void;
|
||||
onMoveDown: () => void;
|
||||
onMoveToTop: () => void;
|
||||
onRemove: () => void;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const showReorderItems = reorderable && (!isFirst || !isLast);
|
||||
return (
|
||||
<DropdownMenu {...menuProps} compactMode="sheet">
|
||||
<ToolbarButton
|
||||
kind="menu"
|
||||
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
|
||||
testID={`agent-profile-menu-${profileId}`}
|
||||
>
|
||||
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
<DropdownMenuContent side="bottom" align="end" width={180}>
|
||||
<DropdownMenuItem
|
||||
leading={editMenuIcon}
|
||||
onSelect={onEdit}
|
||||
testID={`agent-profile-edit-${profileId}`}
|
||||
>
|
||||
{t("settings.host.agentProfiles.editProfile")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
leading={duplicateMenuIcon}
|
||||
onSelect={onDuplicate}
|
||||
testID={`agent-profile-duplicate-${profileId}`}
|
||||
>
|
||||
{t("settings.host.agentProfiles.duplicate")}
|
||||
</DropdownMenuItem>
|
||||
{showReorderItems ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
{!isFirst ? (
|
||||
<DropdownMenuItem
|
||||
leading={moveUpMenuIcon}
|
||||
onSelect={onMoveUp}
|
||||
testID={`agent-profile-move-up-${profileId}`}
|
||||
>
|
||||
{t("settings.host.agentProfiles.moveUp")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{!isLast ? (
|
||||
<DropdownMenuItem
|
||||
leading={moveDownMenuIcon}
|
||||
onSelect={onMoveDown}
|
||||
testID={`agent-profile-move-down-${profileId}`}
|
||||
>
|
||||
{t("settings.host.agentProfiles.moveDown")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{!isFirst ? (
|
||||
<DropdownMenuItem
|
||||
leading={moveTopMenuIcon}
|
||||
onSelect={onMoveToTop}
|
||||
testID={`agent-profile-move-top-${profileId}`}
|
||||
>
|
||||
{t("settings.host.agentProfiles.moveToTop")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
destructive
|
||||
leading={removeMenuIcon}
|
||||
onSelect={onRemove}
|
||||
testID={`agent-profile-remove-${profileId}`}
|
||||
>
|
||||
{t("settings.host.agentProfiles.remove")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentProfileRowContent({
|
||||
serverId,
|
||||
profile,
|
||||
modelLabel,
|
||||
providerLabel,
|
||||
runtimeSubline,
|
||||
fullSummary,
|
||||
isStacked,
|
||||
}: {
|
||||
serverId: string;
|
||||
profile: AgentProfile;
|
||||
modelLabel: string | null;
|
||||
providerLabel: string;
|
||||
runtimeSubline: string;
|
||||
fullSummary: string;
|
||||
isStacked: boolean;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const iconTile = (
|
||||
<View style={styles.iconTile}>
|
||||
<AgentProfileGlyph
|
||||
icon={profile.icon}
|
||||
color={profile.color}
|
||||
provider={profile.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.sm}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
|
||||
if (isStacked) {
|
||||
return (
|
||||
<View style={[styles.stackedMain, styles.passThrough]}>
|
||||
{iconTile}
|
||||
<View style={styles.stackedContent}>
|
||||
<Text style={styles.nameText} numberOfLines={1}>
|
||||
{profile.name}
|
||||
</Text>
|
||||
<View style={styles.stackedSpecLine}>
|
||||
<AgentProfileGlyph
|
||||
provider={profile.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.xs}
|
||||
/>
|
||||
<Text style={styles.stackedSpecText} numberOfLines={1}>
|
||||
{fullSummary}
|
||||
</Text>
|
||||
</View>
|
||||
{profile.notes ? (
|
||||
<Text
|
||||
style={styles.stackedNotesText}
|
||||
numberOfLines={2}
|
||||
testID={`agent-profile-notes-${profile.id}`}
|
||||
>
|
||||
{profile.notes}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={[styles.columns, styles.passThrough]}>
|
||||
<View style={styles.colProfile}>
|
||||
{iconTile}
|
||||
<Text style={styles.nameText} numberOfLines={1}>
|
||||
{profile.name}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.colRuntime}>
|
||||
<View style={styles.modelLine}>
|
||||
<AgentProfileGlyph provider={profile.provider} serverId={serverId} size={ICON_SIZE.xs} />
|
||||
<Text style={styles.modelText} numberOfLines={1}>
|
||||
{modelLabel ?? providerLabel}
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={styles.runtimeSubtext} numberOfLines={1}>
|
||||
{runtimeSubline}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.colNotes}>
|
||||
{profile.notes ? (
|
||||
<Text
|
||||
style={styles.notesText}
|
||||
numberOfLines={2}
|
||||
testID={`agent-profile-notes-${profile.id}`}
|
||||
>
|
||||
{profile.notes}
|
||||
</Text>
|
||||
) : (
|
||||
<Text style={styles.notesEmptyText} numberOfLines={1}>
|
||||
{t("settings.host.agentProfiles.noRoutingNote")}
|
||||
</Text>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wide roster row (Profile | Model & runtime | When to use) that stacks on narrow panes.
|
||||
*
|
||||
* Follows docs/hover.md: hover lives on the outer plain View, tap lives on an
|
||||
* underlying PressHighlight, and the kebab menu's open state is lifted via
|
||||
* `useOpenKebabMenuVisibility` so losing hover never unmounts an open menu.
|
||||
*/
|
||||
export function AgentProfileRow({
|
||||
serverId,
|
||||
profile,
|
||||
entries,
|
||||
isFirst,
|
||||
isLast,
|
||||
selected = false,
|
||||
dragging = false,
|
||||
compactLayout = false,
|
||||
reorderable = true,
|
||||
onEdit,
|
||||
onDuplicate,
|
||||
onRemove,
|
||||
onMoveUp,
|
||||
onMoveDown,
|
||||
onMoveToTop,
|
||||
}: AgentProfileRowProps): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const isCompactFormFactor = useIsCompactFormFactor();
|
||||
const { finePointer, touchScreen } = usePointerCapabilities();
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
|
||||
const alwaysShowAffordances = !finePointer || touchScreen || isCompactFormFactor;
|
||||
const { showKebab, menuProps } = useOpenKebabMenuVisibility(
|
||||
isHovered || dragging || alwaysShowAffordances,
|
||||
);
|
||||
const showRowAffordances = showKebab;
|
||||
|
||||
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
|
||||
const handlePointerLeave = useCallback(() => setIsHovered(false), []);
|
||||
|
||||
const handleEdit = useCallback(() => onEdit(profile.id), [onEdit, profile.id]);
|
||||
const handleDuplicate = useCallback(() => onDuplicate(profile.id), [onDuplicate, profile.id]);
|
||||
const handleRemove = useCallback(() => onRemove(profile.id), [onRemove, profile.id]);
|
||||
const handleMoveUp = useCallback(() => onMoveUp(profile.id), [onMoveUp, profile.id]);
|
||||
const handleMoveDown = useCallback(() => onMoveDown(profile.id), [onMoveDown, profile.id]);
|
||||
const handleMoveToTop = useCallback(() => onMoveToTop(profile.id), [onMoveToTop, profile.id]);
|
||||
|
||||
const formatFeatureCount = useCallback(
|
||||
(count: number) =>
|
||||
@@ -60,77 +345,109 @@ export function AgentProfileRow({
|
||||
: t("settings.host.agentProfiles.featureCount", { count }),
|
||||
[t],
|
||||
);
|
||||
const tags = useMemo(
|
||||
() => buildAgentProfileTags({ profile, entries, formatFeatureCount }),
|
||||
|
||||
const rosterSummary = useMemo(
|
||||
() => buildAgentProfileRosterSummary({ profile, entries, formatFeatureCount }),
|
||||
[entries, formatFeatureCount, profile],
|
||||
);
|
||||
const summary = useMemo(() => tags.map((tag) => tag.label).join(" · "), [tags]);
|
||||
const fullSummary = useMemo(
|
||||
() => rosterSummary.allTags.map((tag) => tag.label).join(" · "),
|
||||
[rosterSummary.allTags],
|
||||
);
|
||||
const runtimeSubline = useMemo(
|
||||
() => rosterSummary.runtimeDetails.join(" · "),
|
||||
[rosterSummary.runtimeDetails],
|
||||
);
|
||||
|
||||
const rowStyle = useMemo(
|
||||
() => [settingsStyles.row, isFirst ? null : settingsStyles.rowBorder, styles.row],
|
||||
[isFirst],
|
||||
const isStacked = compactLayout || isCompactFormFactor;
|
||||
|
||||
const rowContainerStyle = useMemo(
|
||||
() => [
|
||||
styles.row,
|
||||
!isFirst && settingsStyles.rowBorder,
|
||||
selected && styles.rowSelected,
|
||||
(isHovered || menuProps.open) && !selected && styles.rowHovered,
|
||||
dragging && styles.rowDragging,
|
||||
],
|
||||
[dragging, isFirst, isHovered, menuProps.open, selected],
|
||||
);
|
||||
|
||||
const gripVisibilityStyle = useMemo(
|
||||
() => [styles.gripSlot, !showRowAffordances && styles.affordanceHidden],
|
||||
[showRowAffordances],
|
||||
);
|
||||
const kebabVisibilityStyle = useMemo(
|
||||
() => [styles.kebabSlot, !showRowAffordances && styles.affordanceHidden],
|
||||
[showRowAffordances],
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={rowStyle} testID={`agent-profile-row-${profile.id}`}>
|
||||
<View style={styles.rowMain}>
|
||||
<View style={styles.iconWrapper}>
|
||||
<AgentProfileGlyph icon={profile.icon} color={profile.color} size={ICON_SIZE.md} />
|
||||
<View
|
||||
style={rowContainerStyle}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
testID={`agent-profile-row-${profile.id}`}
|
||||
>
|
||||
<PressHighlight
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`${profile.name}, ${fullSummary}`}
|
||||
onPress={handleEdit}
|
||||
style={styles.pressTarget}
|
||||
highlightStyle={styles.rowPressed}
|
||||
testID={`agent-profile-row-press-${profile.id}`}
|
||||
/>
|
||||
|
||||
{selected ? <View style={styles.selectedIndicator} pointerEvents="none" /> : null}
|
||||
|
||||
{reorderable ? (
|
||||
<View style={gripVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
|
||||
<DraggableListHandle
|
||||
accessibilityLabel={t("settings.host.agentProfiles.reorderProfile", {
|
||||
name: profile.name,
|
||||
})}
|
||||
style={styles.gripHandle}
|
||||
testID={`agent-profile-drag-${profile.id}`}
|
||||
>
|
||||
<ThemedGripVertical size={ICON_SIZE.sm} uniProps={extraMutedIconColorMapping} />
|
||||
</DraggableListHandle>
|
||||
</View>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<View style={styles.titleLine}>
|
||||
<Text style={settingsStyles.rowTitle} numberOfLines={1}>
|
||||
{profile.name}
|
||||
</Text>
|
||||
<Text style={styles.summary} numberOfLines={1}>
|
||||
{summary}
|
||||
</Text>
|
||||
</View>
|
||||
{profile.notes ? (
|
||||
<View style={styles.notes}>
|
||||
<ThemedFileText size={ICON_SIZE.xs} uniProps={mutedColorMapping} />
|
||||
<Text
|
||||
style={styles.notesText}
|
||||
numberOfLines={2}
|
||||
testID={`agent-profile-notes-${profile.id}`}
|
||||
>
|
||||
{profile.notes}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
) : (
|
||||
<View style={isStacked ? styles.gripSpacerCompact : styles.gripSlot} />
|
||||
)}
|
||||
|
||||
<AgentProfileRowContent
|
||||
serverId={serverId}
|
||||
profile={profile}
|
||||
modelLabel={rosterSummary.modelLabel}
|
||||
providerLabel={rosterSummary.providerLabel}
|
||||
runtimeSubline={runtimeSubline}
|
||||
fullSummary={fullSummary}
|
||||
isStacked={isStacked}
|
||||
/>
|
||||
|
||||
<View style={styles.trailing}>
|
||||
<View style={kebabVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
|
||||
<AgentProfileRowMenu
|
||||
profileId={profile.id}
|
||||
profileName={profile.name}
|
||||
isFirst={isFirst}
|
||||
isLast={isLast}
|
||||
reorderable={reorderable}
|
||||
menuProps={menuProps}
|
||||
onEdit={handleEdit}
|
||||
onDuplicate={handleDuplicate}
|
||||
onMoveUp={handleMoveUp}
|
||||
onMoveDown={handleMoveDown}
|
||||
onMoveToTop={handleMoveToTop}
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
</View>
|
||||
<View style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<ThemedChevronRight
|
||||
size={ICON_SIZE.sm}
|
||||
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.rowActions}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
leftIcon={moveUpIcon}
|
||||
onPress={handleMoveUp}
|
||||
disabled={isFirst}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.moveUp")}
|
||||
testID={`agent-profile-move-up-${profile.id}`}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
leftIcon={moveDownIcon}
|
||||
onPress={handleMoveDown}
|
||||
disabled={isLast}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.moveDown")}
|
||||
testID={`agent-profile-move-down-${profile.id}`}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
leftIcon={editIcon}
|
||||
onPress={handleEdit}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.editProfile")}
|
||||
testID={`agent-profile-edit-${profile.id}`}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
leftIcon={removeIcon}
|
||||
onPress={handleRemove}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.remove")}
|
||||
testID={`agent-profile-remove-${profile.id}`}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
@@ -138,47 +455,166 @@ export function AgentProfileRow({
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
row: {
|
||||
gap: theme.spacing[2],
|
||||
minHeight: 56,
|
||||
alignItems: "center",
|
||||
paddingVertical: theme.spacing[3],
|
||||
},
|
||||
rowMain: {
|
||||
flex: 1,
|
||||
position: "relative",
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
alignItems: "center",
|
||||
minHeight: ROW_MIN_HEIGHT,
|
||||
paddingVertical: theme.spacing[3],
|
||||
paddingLeft: theme.spacing[2],
|
||||
paddingRight: theme.spacing[4],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
iconWrapper: {
|
||||
width: theme.iconSize.md,
|
||||
rowHovered: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
rowSelected: {
|
||||
backgroundColor: theme.colors.surface3,
|
||||
},
|
||||
selectedIndicator: {
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
top: theme.spacing[2],
|
||||
bottom: theme.spacing[2],
|
||||
width: theme.borderWidth[2],
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
rowPressed: {
|
||||
backgroundColor: theme.colors.surface3,
|
||||
},
|
||||
rowDragging: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
pressTarget: {
|
||||
...StyleSheet.absoluteFill,
|
||||
},
|
||||
passThrough: {
|
||||
pointerEvents: "none",
|
||||
},
|
||||
gripSlot: {
|
||||
width: ROSTER_GRIP_WIDTH,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
marginTop: 1,
|
||||
flexShrink: 0,
|
||||
},
|
||||
titleLine: {
|
||||
gripSpacerCompact: {
|
||||
width: theme.spacing[2],
|
||||
flexShrink: 0,
|
||||
},
|
||||
gripHandle: {
|
||||
width: ROSTER_GRIP_WIDTH,
|
||||
height: GRIP_HANDLE_HEIGHT,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
affordanceHidden: {
|
||||
opacity: 0,
|
||||
},
|
||||
iconTile: {
|
||||
width: theme.spacing[7],
|
||||
height: theme.spacing[7],
|
||||
borderRadius: theme.borderRadius.md,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
},
|
||||
columns: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "baseline",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
colProfile: {
|
||||
width: ROSTER_COL_PROFILE_WIDTH,
|
||||
flexShrink: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
minWidth: 0,
|
||||
},
|
||||
summary: {
|
||||
colRuntime: {
|
||||
width: ROSTER_COL_RUNTIME_WIDTH,
|
||||
flexShrink: 0,
|
||||
gap: theme.spacing[0.5],
|
||||
minWidth: 0,
|
||||
},
|
||||
colNotes: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
nameText: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
modelLine: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1.5],
|
||||
minWidth: 0,
|
||||
},
|
||||
modelText: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
runtimeSubtext: {
|
||||
color: theme.colors.foregroundExtraMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
notesText: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
notesEmptyText: {
|
||||
color: theme.colors.foregroundExtraMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
stackedMain: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
stackedContent: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
gap: theme.spacing[0.5],
|
||||
},
|
||||
stackedSpecLine: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1.5],
|
||||
minWidth: 0,
|
||||
},
|
||||
stackedSpecText: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
notes: {
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
gap: theme.spacing[1],
|
||||
marginTop: theme.spacing[1],
|
||||
},
|
||||
notesText: {
|
||||
flex: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
stackedNotesText: {
|
||||
color: theme.colors.foregroundExtraMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
marginTop: theme.spacing[0.5],
|
||||
},
|
||||
rowActions: {
|
||||
trailing: {
|
||||
width: ROSTER_TRAILING_WIDTH,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "flex-end",
|
||||
gap: theme.spacing[1],
|
||||
flexShrink: 0,
|
||||
},
|
||||
kebabSlot: {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
// Optical: matches SettingsRowHeader so the chevron sits on the card's trailing rail.
|
||||
chevron: {
|
||||
marginRight: -theme.spacing[1],
|
||||
},
|
||||
}));
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,7 +3,7 @@ import { Pressable, Text, View, type PressableStateCallbackType } from "react-na
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||
import type { AgentProfile, AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { Combobox, type ComboboxOption, type ComboboxProps } from "@/components/ui/combobox";
|
||||
@@ -40,7 +40,7 @@ interface CombinedModelSelectorProps {
|
||||
profiles?: AgentProfilePicker | null;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
renderTrigger?: (input: {
|
||||
selectedModelLabel: string;
|
||||
@@ -195,12 +195,17 @@ export function CombinedModelSelector({
|
||||
onEditProfiles?.();
|
||||
}, [handleOpenChange, onEditProfiles]);
|
||||
|
||||
// 1-tap `+` saves the profile, selects the model immediately, and closes the picker;
|
||||
// useAgentProfileEditor surfaces a toast with Edit and Undo actions.
|
||||
const handleCreateProfile = useCallback(
|
||||
(seed: AgentProfileSeed) => {
|
||||
if (seed.modelId) {
|
||||
onSelect(seed.provider, seed.modelId);
|
||||
}
|
||||
handleOpenChange(false);
|
||||
onCreateProfile?.(seed);
|
||||
void onCreateProfile?.(seed);
|
||||
},
|
||||
[handleOpenChange, onCreateProfile],
|
||||
[handleOpenChange, onCreateProfile, onSelect],
|
||||
);
|
||||
|
||||
const handleEditProfile = useCallback(
|
||||
|
||||
@@ -232,6 +232,7 @@ export interface HostPickerProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
anchorRef: React.RefObject<View | null>;
|
||||
restoreFocusRef?: ComboboxProps["restoreFocusRef"];
|
||||
includeAllHost?: boolean;
|
||||
includeAddHost?: boolean;
|
||||
onAddHost?: () => void;
|
||||
@@ -254,6 +255,7 @@ export function HostPicker({
|
||||
open,
|
||||
onOpenChange,
|
||||
anchorRef,
|
||||
restoreFocusRef,
|
||||
includeAllHost,
|
||||
includeAddHost,
|
||||
onAddHost,
|
||||
@@ -404,6 +406,7 @@ export function HostPicker({
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
desktopPlacement={desktopPlacement}
|
||||
desktopMinWidth={desktopMinWidth}
|
||||
/>
|
||||
|
||||
@@ -55,6 +55,7 @@ import { HostPicker } from "@/components/hosts/host-picker";
|
||||
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
|
||||
import { SidebarSeparator } from "@/components/sidebar/sidebar-separator";
|
||||
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
|
||||
import { SidebarSelectionHost } from "@/sidebar-selection";
|
||||
import { SidebarNavRows, useVisibleSidebarNavItems } from "@/components/sidebar/sidebar-nav-rows";
|
||||
import { SidebarFooterIconHighlight } from "@/components/sidebar/sidebar-footer-icon-highlight";
|
||||
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
|
||||
@@ -667,6 +668,7 @@ function MobileSidebar({
|
||||
listHeaderComponent={workspacesSectionHeaderElement}
|
||||
/>
|
||||
)}
|
||||
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
|
||||
</SidebarToastRegion>
|
||||
</SidebarViewSlot>
|
||||
|
||||
@@ -922,6 +924,7 @@ function DesktopSidebar({
|
||||
listHeaderComponent={workspacesSectionHeaderElement}
|
||||
/>
|
||||
)}
|
||||
<SidebarSelectionHost active={active} workspaceEntriesByKey={workspaceEntriesByKey} />
|
||||
</SidebarToastRegion>
|
||||
</SidebarViewSlot>
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import {
|
||||
AgentProfileGlyph,
|
||||
type AgentProfile,
|
||||
type AgentProfilePicker,
|
||||
type AgentProfilePickerRow as AgentProfilePickerRowModel,
|
||||
type AgentProfileSeed,
|
||||
@@ -221,7 +222,7 @@ interface ModelBrowserProps {
|
||||
/** Applying a profile resolves the pick and dismisses, exactly like a model row. */
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onRetryProvider?: (provider: AgentProvider) => void;
|
||||
isRetryingProvider?: boolean;
|
||||
@@ -695,7 +696,7 @@ function ModelRow({
|
||||
showProviderLabel?: boolean;
|
||||
onPress: () => void;
|
||||
profiledRows: AgentProfilePickerRowModel[];
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -758,7 +759,13 @@ function ModelRow({
|
||||
label={t("modelSelector.editProfileLabel", { name: primary.name })}
|
||||
testID={`model-edit-profile-${row.provider}-${row.modelId}`}
|
||||
>
|
||||
<AgentProfileGlyph icon={primary.icon} color={primary.color} size={ICON_SIZE.xs} />
|
||||
<AgentProfileGlyph
|
||||
icon={primary.icon}
|
||||
color={primary.color}
|
||||
provider={primary.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.xs}
|
||||
/>
|
||||
</ModelRowProfileAction>
|
||||
);
|
||||
}
|
||||
@@ -772,7 +779,13 @@ function ModelRow({
|
||||
label={t("modelSelector.editProfilesCount", { count: profiledRows.length })}
|
||||
testID={`model-edit-profiles-${row.provider}-${row.modelId}`}
|
||||
>
|
||||
<AgentProfileGlyph icon={primary.icon} color={primary.color} size={ICON_SIZE.xs} />
|
||||
<AgentProfileGlyph
|
||||
icon={primary.icon}
|
||||
color={primary.color}
|
||||
provider={primary.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.xs}
|
||||
/>
|
||||
</ModelRowProfileAction>
|
||||
);
|
||||
}, [
|
||||
@@ -787,6 +800,7 @@ function ModelRow({
|
||||
profiledRows,
|
||||
row.modelId,
|
||||
row.provider,
|
||||
serverId,
|
||||
t,
|
||||
]);
|
||||
|
||||
@@ -861,7 +875,7 @@ function SelectableModelRow({
|
||||
showProviderLabel?: boolean;
|
||||
onSelect: (provider: string, modelId: string) => void;
|
||||
profiledRows: AgentProfilePickerRowModel[];
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -885,15 +899,25 @@ function SelectableModelRow({
|
||||
|
||||
function AgentProfilePickerRowView({
|
||||
row,
|
||||
serverId,
|
||||
onApply,
|
||||
}: {
|
||||
row: AgentProfilePickerRowModel;
|
||||
serverId: string | null;
|
||||
onApply: (profileId: string) => void;
|
||||
}) {
|
||||
const handlePress = useCallback(() => onApply(row.id), [onApply, row.id]);
|
||||
const leadingSlot = useMemo(
|
||||
() => <AgentProfileGlyph icon={row.icon} color={row.color} size={ICON_SIZE.sm} />,
|
||||
[row.color, row.icon],
|
||||
() => (
|
||||
<AgentProfileGlyph
|
||||
icon={row.icon}
|
||||
color={row.color}
|
||||
provider={row.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.sm}
|
||||
/>
|
||||
),
|
||||
[row.color, row.icon, row.provider, serverId],
|
||||
);
|
||||
return (
|
||||
<ModelBrowserRow
|
||||
@@ -914,10 +938,12 @@ function AgentProfilePickerRowView({
|
||||
*/
|
||||
function AgentProfilesPickerSection({
|
||||
rows,
|
||||
serverId,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
}: {
|
||||
rows: AgentProfilePickerRowModel[];
|
||||
serverId: string | null;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -937,7 +963,12 @@ function AgentProfilesPickerSection({
|
||||
) : null}
|
||||
</View>
|
||||
{rows.map((row) => (
|
||||
<AgentProfilePickerRowView key={row.id} row={row} onApply={handleApply} />
|
||||
<AgentProfilePickerRowView
|
||||
key={row.id}
|
||||
row={row}
|
||||
serverId={serverId}
|
||||
onApply={handleApply}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
@@ -966,10 +997,12 @@ function CreateAgentProfileRow({ onPress }: { onPress: () => void }) {
|
||||
|
||||
function AgentProfilesPickerContent({
|
||||
rows,
|
||||
serverId,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
}: {
|
||||
rows: AgentProfilePickerRowModel[];
|
||||
serverId: string | null;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -979,6 +1012,7 @@ function AgentProfilesPickerContent({
|
||||
return (
|
||||
<AgentProfilesPickerSection
|
||||
rows={rows}
|
||||
serverId={serverId}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
@@ -991,11 +1025,13 @@ function AgentProfilesPickerContent({
|
||||
*/
|
||||
function ProfileSearchResultsHeader({
|
||||
rows,
|
||||
serverId,
|
||||
hasModelRows,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
}: {
|
||||
rows: AgentProfilePickerRowModel[];
|
||||
serverId: string | null;
|
||||
hasModelRows: boolean;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
@@ -1005,6 +1041,7 @@ function ProfileSearchResultsHeader({
|
||||
<View>
|
||||
<AgentProfilesPickerSection
|
||||
rows={rows}
|
||||
serverId={serverId}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
@@ -1207,7 +1244,7 @@ function ModelRowList({
|
||||
header?: React.ReactElement;
|
||||
scrolling: "sheet" | "independent";
|
||||
profiledLookup: Map<string, AgentProfilePickerRowModel[]>;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -1336,7 +1373,7 @@ function ProviderModelBrowserContent({
|
||||
onSelect: (provider: string, modelId: string) => void;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
profiledLookup: Map<string, AgentProfilePickerRowModel[]>;
|
||||
showProfilesSection?: boolean;
|
||||
@@ -1363,6 +1400,7 @@ function ProviderModelBrowserContent({
|
||||
return (
|
||||
<AgentProfilesPickerContent
|
||||
rows={providerProfileRows}
|
||||
serverId={serverId}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
@@ -1371,6 +1409,7 @@ function ProviderModelBrowserContent({
|
||||
return matchedProfileRows.length > 0 ? (
|
||||
<ProfileSearchResultsHeader
|
||||
rows={matchedProfileRows}
|
||||
serverId={serverId}
|
||||
hasModelRows={visibleRows.length > 0}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
@@ -1383,6 +1422,7 @@ function ProviderModelBrowserContent({
|
||||
onEditProfiles,
|
||||
profiles,
|
||||
providerProfileRows,
|
||||
serverId,
|
||||
showProfilesSection,
|
||||
visibleRows.length,
|
||||
]);
|
||||
@@ -1485,12 +1525,13 @@ function ModelBrowserContent({
|
||||
allView.kind === "searchResults" && allView.profiles.length > 0 ? (
|
||||
<ProfileSearchResultsHeader
|
||||
rows={allView.profiles}
|
||||
serverId={serverId}
|
||||
hasModelRows={allView.rows.length > 0}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
) : undefined,
|
||||
[allView, onApplyProfile, onEditProfiles],
|
||||
[allView, onApplyProfile, onEditProfiles, serverId],
|
||||
);
|
||||
|
||||
if (view.kind === "provider") {
|
||||
@@ -1552,6 +1593,7 @@ function ModelBrowserContent({
|
||||
{showProfilesSection && profiles ? (
|
||||
<AgentProfilesPickerContent
|
||||
rows={profiles.rows}
|
||||
serverId={serverId}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
|
||||
@@ -101,7 +101,17 @@ import {
|
||||
import { useLongPressDragInteraction } from "@/components/sidebar/use-long-press-drag-interaction";
|
||||
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
|
||||
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
|
||||
import { createWorkspaceVisibilityPolicy } from "@/components/sidebar/sidebar-group-visibility";
|
||||
import {
|
||||
createWorkspaceVisibilityPolicy,
|
||||
selectSidebarGroupVisibility,
|
||||
} from "@/components/sidebar/sidebar-group-visibility";
|
||||
import {
|
||||
isShiftPressEvent,
|
||||
registerSidebarVisibleWorkspaceKeysReader,
|
||||
useIsSidebarSelectionMode,
|
||||
useIsWorkspaceBulkSelected,
|
||||
useSidebarSelectionStore,
|
||||
} from "@/sidebar-selection";
|
||||
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
|
||||
import {
|
||||
SidebarWorkspaceRowFrame,
|
||||
@@ -284,6 +294,7 @@ interface WorkspaceRowInnerProps {
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
archivePendingLabel?: string;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive?: () => void;
|
||||
onCopyBranchName?: () => void;
|
||||
onCopyPath?: () => void;
|
||||
@@ -607,12 +618,14 @@ function WorkspaceRowRightGroup({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
isCreating,
|
||||
isSelectionMode,
|
||||
showShortcutBadge,
|
||||
shortcutNumber,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
archivePendingLabel,
|
||||
archiveShortcutKeys,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
@@ -627,12 +640,14 @@ function WorkspaceRowRightGroup({
|
||||
isHovered: boolean;
|
||||
isTouchPlatform: boolean;
|
||||
isCreating: boolean;
|
||||
isSelectionMode: boolean;
|
||||
showShortcutBadge: boolean;
|
||||
shortcutNumber: number | null;
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
archivePendingLabel?: string;
|
||||
archiveShortcutKeys?: ShortcutKey[][] | null;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive?: () => void;
|
||||
onMarkAsRead?: () => void;
|
||||
onMarkAsUnread?: () => void;
|
||||
@@ -660,6 +675,7 @@ function WorkspaceRowRightGroup({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode,
|
||||
});
|
||||
const kebab = useOpenKebabMenuVisibility(showKebabInSlot);
|
||||
|
||||
@@ -695,6 +711,7 @@ function WorkspaceRowRightGroup({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -1065,6 +1082,7 @@ function WorkspaceRowInner({
|
||||
archiveLabel,
|
||||
archiveStatus = "idle",
|
||||
archivePendingLabel,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
onCopyBranchName,
|
||||
onCopyPath,
|
||||
@@ -1079,6 +1097,8 @@ function WorkspaceRowInner({
|
||||
}: WorkspaceRowInnerProps) {
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const [isHighlighted, setIsHighlighted] = useState(false);
|
||||
const isSelectionMode = useIsSidebarSelectionMode();
|
||||
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
|
||||
const isTouchPlatform = platformIsNative || isCompact;
|
||||
const interaction = useLongPressDragInteraction({
|
||||
drag,
|
||||
@@ -1091,30 +1111,75 @@ function WorkspaceRowInner({
|
||||
...dragAttributes
|
||||
} = dragHandleProps?.attributes ?? {};
|
||||
|
||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
||||
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
|
||||
didLongPressRef: interaction.didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
});
|
||||
|
||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||
const handleRowPress = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
const shiftKey = isShiftPressEvent(event);
|
||||
if (isSelectionMode || shiftKey) {
|
||||
if (interaction.didLongPressRef.current) {
|
||||
interaction.didLongPressRef.current = false;
|
||||
return;
|
||||
}
|
||||
event.preventDefault?.();
|
||||
useSidebarSelectionStore.getState().pressWorkspace(workspace.workspaceKey, { shiftKey });
|
||||
return;
|
||||
}
|
||||
handleNavigatePress();
|
||||
},
|
||||
[handleNavigatePress, interaction.didLongPressRef, isSelectionMode, workspace.workspaceKey],
|
||||
);
|
||||
|
||||
const handleRowPressIn = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
if (isShiftPressEvent(event)) {
|
||||
event.preventDefault?.();
|
||||
return;
|
||||
}
|
||||
if (!isSelectionMode) {
|
||||
interaction.handlePressIn(event);
|
||||
}
|
||||
},
|
||||
[interaction, isSelectionMode],
|
||||
);
|
||||
|
||||
const rowSelected = isSelectionMode ? isBulkSelected : selected;
|
||||
const accessibilityState = useMemo(
|
||||
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
|
||||
[isSelectionMode, isBulkSelected, selected],
|
||||
);
|
||||
const isEditingTitle = titleEditor !== null;
|
||||
const disableDrag = isEditingTitle || isSelectionMode;
|
||||
|
||||
return (
|
||||
<SidebarWorkspaceRowFrame
|
||||
workspace={workspace}
|
||||
isDragging={isDragging}
|
||||
isEditingTitle={isEditingTitle}
|
||||
isSelectionMode={isSelectionMode}
|
||||
>
|
||||
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
|
||||
const isDesktop = !isTouchPlatform;
|
||||
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
|
||||
const workspaceRowStyle = getProjectWorkspaceRowStyle({ isDragging, selected, isHovered });
|
||||
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
|
||||
const workspaceRowStyle = getProjectWorkspaceRowStyle({
|
||||
isDragging,
|
||||
selected: rowSelected,
|
||||
isHovered,
|
||||
});
|
||||
const backdrop = getSidebarRowBackdrop({
|
||||
isDragging,
|
||||
isHighlighted,
|
||||
selected: rowSelected,
|
||||
isHovered,
|
||||
});
|
||||
return (
|
||||
<View
|
||||
{...dragAttributes}
|
||||
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
|
||||
{...(disableDrag ? null : dragHandleProps?.listeners)}
|
||||
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
|
||||
style={styles.workspaceRowContainer}
|
||||
{...hoverHandlers}
|
||||
@@ -1131,6 +1196,7 @@ function WorkspaceRowInner({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -1140,17 +1206,18 @@ function WorkspaceRowInner({
|
||||
onTogglePin={onTogglePin}
|
||||
openInFileManagerPath={workspace.workspaceDirectory}
|
||||
disabled={isArchiving}
|
||||
enabled={!isEditingTitle}
|
||||
aria-selected={selected}
|
||||
accessibilityRole="button"
|
||||
enabled={!isEditingTitle && !isSelectionMode}
|
||||
aria-selected={isSelectionMode ? undefined : selected}
|
||||
aria-checked={isSelectionMode ? isBulkSelected : undefined}
|
||||
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
|
||||
accessibilityState={accessibilityState}
|
||||
style={workspaceRowStyle}
|
||||
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
|
||||
onHighlightChange={setIsHighlighted}
|
||||
onPressIn={isEditingTitle ? undefined : interaction.handlePressIn}
|
||||
onTouchMove={isEditingTitle ? undefined : interaction.handleTouchMove}
|
||||
onPressOut={isEditingTitle ? undefined : interaction.handlePressOut}
|
||||
onPress={isEditingTitle ? undefined : handlePress}
|
||||
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
|
||||
onTouchMove={disableDrag ? undefined : interaction.handleTouchMove}
|
||||
onPressOut={disableDrag ? undefined : interaction.handlePressOut}
|
||||
onPress={isEditingTitle ? undefined : handleRowPress}
|
||||
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
|
||||
>
|
||||
<SidebarWorkspaceRowContent
|
||||
@@ -1163,6 +1230,8 @@ function WorkspaceRowInner({
|
||||
isHovered={isHovered}
|
||||
isLoading={isArchiving || isCreating}
|
||||
isCreating={isCreating}
|
||||
isSelectionMode={isSelectionMode}
|
||||
isBulkSelected={isBulkSelected}
|
||||
shortcutNumber={shortcutNumber}
|
||||
showShortcutBadge={showShortcutBadge}
|
||||
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
|
||||
@@ -1174,12 +1243,14 @@ function WorkspaceRowInner({
|
||||
isHovered={isHovered}
|
||||
isTouchPlatform={isTouchPlatform}
|
||||
isCreating={isCreating}
|
||||
isSelectionMode={isSelectionMode}
|
||||
showShortcutBadge={showShortcutBadge}
|
||||
shortcutNumber={shortcutNumber}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
archivePendingLabel={archivePendingLabel}
|
||||
archiveShortcutKeys={archiveShortcutKeys}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
onCopyBranchName={onCopyBranchName}
|
||||
onCopyPath={onCopyPath}
|
||||
@@ -1265,6 +1336,10 @@ function WorkspaceRowWithMenu({
|
||||
archiveController.archive();
|
||||
}, [archiveController, isArchiving]);
|
||||
|
||||
const handleSelectWorkspace = useCallback(() => {
|
||||
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
|
||||
}, [workspace.workspaceKey]);
|
||||
|
||||
const clipboard = useWorkspaceClipboardActions();
|
||||
const handleCopyPath = useCallback(() => {
|
||||
clipboard.copyPath(workspace);
|
||||
@@ -1317,6 +1392,7 @@ function WorkspaceRowWithMenu({
|
||||
archiveLabel={t("sidebar.workspace.actions.archive")}
|
||||
archiveStatus={isArchiving ? "pending" : "idle"}
|
||||
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
|
||||
onSelectWorkspace={handleSelectWorkspace}
|
||||
onArchive={handleArchive}
|
||||
onCopyBranchName={canCopyBranchName ? handleCopyBranchName : undefined}
|
||||
onCopyPath={handleCopyPath}
|
||||
@@ -2199,6 +2275,62 @@ function ProjectModeList({
|
||||
selection: selectionEnabled ? activeWorkspaceSelection : null,
|
||||
expanded: pinnedChatsExpanded,
|
||||
});
|
||||
|
||||
const visibleOrderInputRef = useRef({
|
||||
pinnedCollapsed,
|
||||
leadingPinnedChat,
|
||||
visiblePinnedChats,
|
||||
unpinnedProjects,
|
||||
collapsedProjectKeys,
|
||||
expandedProjectKeys,
|
||||
selectionEnabled,
|
||||
activeWorkspaceSelection,
|
||||
workspaceEntriesByKey,
|
||||
});
|
||||
visibleOrderInputRef.current = {
|
||||
pinnedCollapsed,
|
||||
leadingPinnedChat,
|
||||
visiblePinnedChats,
|
||||
unpinnedProjects,
|
||||
collapsedProjectKeys,
|
||||
expandedProjectKeys,
|
||||
selectionEnabled,
|
||||
activeWorkspaceSelection,
|
||||
workspaceEntriesByKey,
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
return registerSidebarVisibleWorkspaceKeysReader(() => {
|
||||
const current = visibleOrderInputRef.current;
|
||||
const keys: string[] = [];
|
||||
if (!current.pinnedCollapsed) {
|
||||
if (current.leadingPinnedChat) keys.push(current.leadingPinnedChat.workspaceKey);
|
||||
for (const item of current.visiblePinnedChats) {
|
||||
keys.push(item.workspaceKey);
|
||||
}
|
||||
}
|
||||
const policy = createWorkspaceVisibilityPolicy<SidebarWorkspacePlacement>(
|
||||
current.workspaceEntriesByKey,
|
||||
);
|
||||
const selection = current.selectionEnabled ? current.activeWorkspaceSelection : null;
|
||||
for (const project of current.unpinnedProjects) {
|
||||
if (current.collapsedProjectKeys.has(project.viewKey) || project.workspaces.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
|
||||
items: project.workspaces,
|
||||
selection,
|
||||
expanded: current.expandedProjectKeys.has(project.viewKey),
|
||||
policy,
|
||||
});
|
||||
if (leadingItem) keys.push(leadingItem.workspaceKey);
|
||||
for (const item of visibleItems) {
|
||||
keys.push(item.workspaceKey);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
});
|
||||
}, []);
|
||||
const nativeScrollGestureProps = useMemo(
|
||||
() =>
|
||||
parentGestureRef
|
||||
|
||||
@@ -3,14 +3,16 @@ import { PressHighlight as Pressable } from "@/components/ui/press-highlight";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type MutableRefObject,
|
||||
type ReactNode,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { View, Text, ScrollView } from "react-native";
|
||||
import { View, Text, ScrollView, type GestureResponderEvent } from "react-native";
|
||||
import { NestableScrollContainer } from "react-native-draggable-flatlist";
|
||||
import type { GestureType } from "react-native-gesture-handler";
|
||||
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
|
||||
@@ -69,7 +71,15 @@ import {
|
||||
} from "@/components/sidebar/sidebar-workspace-menu";
|
||||
import { SidebarSectionHeader } from "@/components/sidebar/sidebar-section-header";
|
||||
import { SidebarGroupToggleRow } from "@/components/sidebar/sidebar-group-toggle-row";
|
||||
import { selectSidebarGroupVisibility } from "@/components/sidebar/sidebar-group-visibility";
|
||||
import { useLimitedSidebarGroup } from "@/components/sidebar/use-limited-sidebar-group";
|
||||
import {
|
||||
isShiftPressEvent,
|
||||
registerSidebarVisibleWorkspaceKeysReader,
|
||||
useIsSidebarSelectionMode,
|
||||
useIsWorkspaceBulkSelected,
|
||||
useSidebarSelectionStore,
|
||||
} from "@/sidebar-selection";
|
||||
import type { ToggleSidebarWorkspacePin } from "@/hooks/use-sidebar-workspace-pin";
|
||||
import { DraggableList, type DraggableRenderItemInfo } from "@/components/draggable-list";
|
||||
import type { DraggableListDragHandleProps } from "@/components/draggable-list.types";
|
||||
@@ -154,6 +164,14 @@ export function SidebarStatusWorkspaceList({
|
||||
() => setPinnedWorkspacesExpanded((current) => !current),
|
||||
[],
|
||||
);
|
||||
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const toggleGroupWorkspacesExpanded = useCallback((groupKey: string) => {
|
||||
setExpandedGroupKeys((current) => {
|
||||
const next = new Set(current);
|
||||
if (!next.delete(groupKey)) next.add(groupKey);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
const {
|
||||
leadingItem: leadingPinnedWorkspace,
|
||||
visibleItems: visiblePinnedWorkspaces,
|
||||
@@ -164,6 +182,56 @@ export function SidebarStatusWorkspaceList({
|
||||
expanded: pinnedWorkspacesExpanded,
|
||||
});
|
||||
|
||||
const visibleOrderInputRef = useRef({
|
||||
pinnedCollapsed,
|
||||
leadingPinnedWorkspace,
|
||||
visiblePinnedWorkspaces,
|
||||
groups,
|
||||
collapsedWorkspaceGroupKeys,
|
||||
expandedGroupKeys,
|
||||
activeWorkspaceSelection,
|
||||
});
|
||||
visibleOrderInputRef.current = {
|
||||
pinnedCollapsed,
|
||||
leadingPinnedWorkspace,
|
||||
visiblePinnedWorkspaces,
|
||||
groups,
|
||||
collapsedWorkspaceGroupKeys,
|
||||
expandedGroupKeys,
|
||||
activeWorkspaceSelection,
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
return registerSidebarVisibleWorkspaceKeysReader(() => {
|
||||
const current = visibleOrderInputRef.current;
|
||||
const keys: string[] = [];
|
||||
if (!current.pinnedCollapsed) {
|
||||
if (current.leadingPinnedWorkspace) {
|
||||
keys.push(current.leadingPinnedWorkspace.workspaceKey);
|
||||
}
|
||||
for (const item of current.visiblePinnedWorkspaces) {
|
||||
keys.push(item.workspaceKey);
|
||||
}
|
||||
}
|
||||
for (const group of current.groups) {
|
||||
if (current.collapsedWorkspaceGroupKeys.has(group.key) || group.rows.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const { leadingItem, visibleItems } = selectSidebarGroupVisibility({
|
||||
items: group.rows,
|
||||
selection: current.activeWorkspaceSelection,
|
||||
expanded: current.expandedGroupKeys.has(group.key),
|
||||
policy: STATUS_GROUP_VISIBILITY,
|
||||
});
|
||||
if (leadingItem) keys.push(leadingItem.workspaceKey);
|
||||
for (const item of visibleItems) {
|
||||
keys.push(item.workspaceKey);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const statusShortcutIndex = showShortcutBadges
|
||||
? shortcutIndexByWorkspaceKey
|
||||
: EMPTY_SHORTCUT_INDEX;
|
||||
@@ -262,6 +330,8 @@ export function SidebarStatusWorkspaceList({
|
||||
<StatusGroupList
|
||||
groups={groups}
|
||||
collapsedWorkspaceGroupKeys={collapsedWorkspaceGroupKeys}
|
||||
expandedGroupKeys={expandedGroupKeys}
|
||||
onToggleGroupWorkspacesExpanded={toggleGroupWorkspacesExpanded}
|
||||
projectIconByProjectViewKey={projectIconByProjectViewKey}
|
||||
shortcutIndex={statusShortcutIndex}
|
||||
showShortcutBadges={showShortcutBadges}
|
||||
@@ -303,6 +373,8 @@ export function SidebarStatusWorkspaceList({
|
||||
function StatusGroupList({
|
||||
groups,
|
||||
collapsedWorkspaceGroupKeys,
|
||||
expandedGroupKeys,
|
||||
onToggleGroupWorkspacesExpanded,
|
||||
projectIconByProjectViewKey,
|
||||
shortcutIndex,
|
||||
showShortcutBadges,
|
||||
@@ -313,6 +385,8 @@ function StatusGroupList({
|
||||
}: {
|
||||
groups: SidebarWorkspaceGroup[];
|
||||
collapsedWorkspaceGroupKeys: ReadonlySet<string>;
|
||||
expandedGroupKeys: ReadonlySet<string>;
|
||||
onToggleGroupWorkspacesExpanded: (groupKey: string) => void;
|
||||
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
|
||||
shortcutIndex: Map<string, number>;
|
||||
showShortcutBadges: boolean;
|
||||
@@ -328,6 +402,8 @@ function StatusGroupList({
|
||||
key={group.key}
|
||||
group={group}
|
||||
collapsed={collapsedWorkspaceGroupKeys.has(group.key)}
|
||||
workspacesExpanded={expandedGroupKeys.has(group.key)}
|
||||
onToggleWorkspacesExpanded={onToggleGroupWorkspacesExpanded}
|
||||
projectIconByProjectViewKey={projectIconByProjectViewKey}
|
||||
shortcutIndex={shortcutIndex}
|
||||
showShortcutBadges={showShortcutBadges}
|
||||
@@ -349,6 +425,8 @@ const STATUS_GROUP_VISIBILITY = {
|
||||
function StatusGroupRows({
|
||||
group,
|
||||
collapsed,
|
||||
workspacesExpanded,
|
||||
onToggleWorkspacesExpanded,
|
||||
projectIconByProjectViewKey,
|
||||
shortcutIndex,
|
||||
showShortcutBadges,
|
||||
@@ -359,6 +437,8 @@ function StatusGroupRows({
|
||||
}: {
|
||||
group: SidebarWorkspaceGroup;
|
||||
collapsed: boolean;
|
||||
workspacesExpanded: boolean;
|
||||
onToggleWorkspacesExpanded: (groupKey: string) => void;
|
||||
projectIconByProjectViewKey: ReadonlyMap<string, string | null>;
|
||||
shortcutIndex: Map<string, number>;
|
||||
showShortcutBadges: boolean;
|
||||
@@ -368,10 +448,9 @@ function StatusGroupRows({
|
||||
onToggleWorkspacePin: ToggleSidebarWorkspacePin;
|
||||
}) {
|
||||
const activeWorkspaceSelection = useActiveWorkspaceSelection();
|
||||
const [workspacesExpanded, setWorkspacesExpanded] = useState(false);
|
||||
const toggleWorkspacesExpanded = useCallback(
|
||||
() => setWorkspacesExpanded((current) => !current),
|
||||
[],
|
||||
() => onToggleWorkspacesExpanded(group.key),
|
||||
[group.key, onToggleWorkspacesExpanded],
|
||||
);
|
||||
const {
|
||||
leadingItem: leadingWorkspace,
|
||||
@@ -669,6 +748,10 @@ function StatusWorkspaceRowWithMenu({
|
||||
archiveController.archive();
|
||||
}, [archiveController, isArchiving]);
|
||||
|
||||
const handleSelectWorkspace = useCallback(() => {
|
||||
useSidebarSelectionStore.getState().enter(workspace.workspaceKey);
|
||||
}, [workspace.workspaceKey]);
|
||||
|
||||
const clipboard = useWorkspaceClipboardActions();
|
||||
const handleCopyPath = useCallback(() => {
|
||||
clipboard.copyPath(workspace);
|
||||
@@ -716,6 +799,7 @@ function StatusWorkspaceRowWithMenu({
|
||||
archiveLabel={t("sidebar.workspace.actions.archive")}
|
||||
archiveStatus={isArchiving ? "pending" : "idle"}
|
||||
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
|
||||
onSelectWorkspace={handleSelectWorkspace}
|
||||
onArchive={handleArchive}
|
||||
onCopyBranchName={workspace.projectKind === "git" ? handleCopyBranchName : undefined}
|
||||
onCopyPath={handleCopyPath}
|
||||
@@ -750,6 +834,7 @@ interface StatusWorkspaceRowInnerProps {
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
archivePendingLabel?: string;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive?: () => void;
|
||||
onCopyBranchName?: () => void;
|
||||
onCopyPath?: () => void;
|
||||
@@ -799,6 +884,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
archiveLabel,
|
||||
archiveStatus = "idle",
|
||||
archivePendingLabel,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
onCopyBranchName,
|
||||
onCopyPath,
|
||||
@@ -820,6 +906,8 @@ function StatusWorkspaceRowInnerContent({
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const isTouchPlatform = platformIsNative || isCompact;
|
||||
const [isHighlighted, setIsHighlighted] = useState(false);
|
||||
const isSelectionMode = useIsSidebarSelectionMode();
|
||||
const isBulkSelected = useIsWorkspaceBulkSelected(workspace.workspaceKey);
|
||||
const trailing = useSidebarWorkspaceTrailing();
|
||||
const {
|
||||
role: _dragRole,
|
||||
@@ -831,23 +919,59 @@ function StatusWorkspaceRowInnerContent({
|
||||
const isDesktop = !isTouchPlatform;
|
||||
const serviceSummary = isDesktop ? selectWorkspaceServiceSummary(workspace.scripts) : null;
|
||||
|
||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||
const rowSelected = isSelectionMode ? isBulkSelected : selected;
|
||||
const accessibilityState = useMemo(
|
||||
() => (isSelectionMode ? { checked: isBulkSelected } : { selected }),
|
||||
[isSelectionMode, isBulkSelected, selected],
|
||||
);
|
||||
const isEditingTitle = titleEditor !== null;
|
||||
const disableDrag = isEditingTitle || isSelectionMode;
|
||||
const didLongPressRef = dragInteraction?.didLongPressRef;
|
||||
const startDragPress = dragInteraction?.handlePressIn;
|
||||
const moveDragPress = dragInteraction?.handleTouchMove;
|
||||
const endDragPress = dragInteraction?.handlePressOut;
|
||||
const { onPress: handlePress, feedback } = useWorkspaceRowPress({
|
||||
const { onPress: handleNavigatePress, feedback } = useWorkspaceRowPress({
|
||||
didLongPressRef,
|
||||
onPress,
|
||||
selected,
|
||||
});
|
||||
|
||||
const handleRowPress = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
const shiftKey = isShiftPressEvent(event);
|
||||
if (isSelectionMode || shiftKey) {
|
||||
if (didLongPressRef?.current) {
|
||||
didLongPressRef.current = false;
|
||||
return;
|
||||
}
|
||||
event.preventDefault?.();
|
||||
useSidebarSelectionStore.getState().pressWorkspace(workspace.workspaceKey, { shiftKey });
|
||||
return;
|
||||
}
|
||||
handleNavigatePress();
|
||||
},
|
||||
[didLongPressRef, handleNavigatePress, isSelectionMode, workspace.workspaceKey],
|
||||
);
|
||||
|
||||
const handleRowPressIn = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
if (isShiftPressEvent(event)) {
|
||||
event.preventDefault?.();
|
||||
return;
|
||||
}
|
||||
if (!isSelectionMode) {
|
||||
startDragPress?.(event);
|
||||
}
|
||||
},
|
||||
[isSelectionMode, startDragPress],
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarWorkspaceRowFrame
|
||||
workspace={workspace}
|
||||
isDragging={isDragging}
|
||||
isEditingTitle={isEditingTitle}
|
||||
isSelectionMode={isSelectionMode}
|
||||
>
|
||||
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
|
||||
const showShortcut = showShortcutBadge && shortcutNumber !== null;
|
||||
@@ -865,18 +989,24 @@ function StatusWorkspaceRowInnerContent({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode,
|
||||
});
|
||||
const workspaceRowStyle = getStatusWorkspaceRowStyle({
|
||||
selected,
|
||||
selected: rowSelected,
|
||||
isHovered,
|
||||
inStatusGroup,
|
||||
isDragging,
|
||||
});
|
||||
const backdrop = getSidebarRowBackdrop({ isDragging, isHighlighted, selected, isHovered });
|
||||
const backdrop = getSidebarRowBackdrop({
|
||||
isDragging,
|
||||
isHighlighted,
|
||||
selected: rowSelected,
|
||||
isHovered,
|
||||
});
|
||||
return (
|
||||
<View
|
||||
{...dragAttributes}
|
||||
{...(isEditingTitle ? null : dragHandleProps?.listeners)}
|
||||
{...(disableDrag ? null : dragHandleProps?.listeners)}
|
||||
ref={dragHandleProps?.setActivatorNodeRef as unknown as Ref<View>}
|
||||
style={styles.workspaceRowContainer}
|
||||
{...hoverHandlers}
|
||||
@@ -894,6 +1024,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -903,16 +1034,18 @@ function StatusWorkspaceRowInnerContent({
|
||||
onTogglePin={onTogglePin}
|
||||
openInFileManagerPath={workspace.workspaceDirectory}
|
||||
disabled={isArchiving}
|
||||
enabled={!isEditingTitle}
|
||||
accessibilityRole="button"
|
||||
enabled={!isEditingTitle && !isSelectionMode}
|
||||
aria-selected={isSelectionMode ? undefined : selected}
|
||||
aria-checked={isSelectionMode ? isBulkSelected : undefined}
|
||||
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
|
||||
accessibilityState={accessibilityState}
|
||||
style={workspaceRowStyle}
|
||||
highlightStyle={isEditingTitle ? undefined : styles.workspaceRowPressed}
|
||||
onHighlightChange={setIsHighlighted}
|
||||
onPressIn={isEditingTitle ? undefined : startDragPress}
|
||||
onTouchMove={isEditingTitle ? undefined : moveDragPress}
|
||||
onPressOut={isEditingTitle ? undefined : endDragPress}
|
||||
onPress={isEditingTitle ? undefined : handlePress}
|
||||
onPressIn={isEditingTitle ? undefined : handleRowPressIn}
|
||||
onTouchMove={disableDrag ? undefined : moveDragPress}
|
||||
onPressOut={disableDrag ? undefined : endDragPress}
|
||||
onPress={isEditingTitle ? undefined : handleRowPress}
|
||||
testID={`sidebar-workspace-row-${workspace.workspaceKey}`}
|
||||
>
|
||||
<SidebarWorkspaceRowContent
|
||||
@@ -924,6 +1057,8 @@ function StatusWorkspaceRowInnerContent({
|
||||
backdrop={backdrop}
|
||||
isHovered={isHovered}
|
||||
isLoading={isArchiving}
|
||||
isSelectionMode={isSelectionMode}
|
||||
isBulkSelected={isBulkSelected}
|
||||
shortcutNumber={shortcutNumber}
|
||||
showShortcutBadge={showShortcutBadge}
|
||||
reserveIdleStatusIndicatorSpace={reserveIdleStatusIndicatorSpace}
|
||||
@@ -946,6 +1081,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -979,6 +1115,7 @@ function StatusWorkspaceActionSlot({
|
||||
onRename,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
@@ -1000,6 +1137,7 @@ function StatusWorkspaceActionSlot({
|
||||
onRename?: () => void;
|
||||
onMarkAsRead?: () => void;
|
||||
onMarkAsUnread?: () => void;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive?: () => void;
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
@@ -1034,6 +1172,7 @@ function StatusWorkspaceActionSlot({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { View } from "react-native";
|
||||
@@ -15,7 +16,13 @@ import Animated, {
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { TOAST_FADE_MS, ToastViewport, useToastHost, type ToastApi } from "@/components/toast-host";
|
||||
import {
|
||||
TOAST_FADE_MS,
|
||||
ToastViewport,
|
||||
useToastHost,
|
||||
type ToastApi,
|
||||
type ToastState,
|
||||
} from "@/components/toast-host";
|
||||
import { ToastApiProvider, useToast } from "@/contexts/toast-context";
|
||||
|
||||
interface SidebarToastCoverage {
|
||||
@@ -25,6 +32,10 @@ interface SidebarToastCoverage {
|
||||
}
|
||||
|
||||
const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(null);
|
||||
const SidebarPersistentToastContext = createContext<((toast: ToastState | null) => void) | null>(
|
||||
null,
|
||||
);
|
||||
const SidebarAppToastContext = createContext<ToastApi | null>(null);
|
||||
|
||||
/**
|
||||
* Shows toasts raised by the sidebar's list over its bottom edge, just above the footer.
|
||||
@@ -36,9 +47,10 @@ const SidebarToastCoverageContext = createContext<SidebarToastCoverage | null>(n
|
||||
export function SidebarToastRegion({ active, children }: { active: boolean; children: ReactNode }) {
|
||||
const appToast = useToast();
|
||||
const { api: sidebarToast, toast, dismiss } = useToastHost();
|
||||
const [persistentToast, setPersistentToast] = useState<ToastState | null>(null);
|
||||
const activeRef = useRef(active);
|
||||
const coverageHeight = useSharedValue(0);
|
||||
const toastVisible = toast !== null;
|
||||
const toastVisible = toast !== null || persistentToast !== null;
|
||||
|
||||
useEffect(() => {
|
||||
activeRef.current = active;
|
||||
@@ -72,19 +84,48 @@ export function SidebarToastRegion({ active, children }: { active: boolean; chil
|
||||
|
||||
return (
|
||||
<View style={styles.region}>
|
||||
<SidebarToastCoverageContext.Provider value={coverage}>
|
||||
<ToastApiProvider api={api}>{children}</ToastApiProvider>
|
||||
</SidebarToastCoverageContext.Provider>
|
||||
<ToastViewport
|
||||
toast={toast}
|
||||
onDismiss={dismiss}
|
||||
placement="sidebar"
|
||||
onBottomCoverageChange={handleCoverageChange}
|
||||
/>
|
||||
<ToastApiProvider api={api}>
|
||||
<SidebarAppToastContext.Provider value={appToast}>
|
||||
<SidebarPersistentToastContext.Provider value={setPersistentToast}>
|
||||
<SidebarToastCoverageContext.Provider value={coverage}>
|
||||
{children}
|
||||
</SidebarToastCoverageContext.Provider>
|
||||
</SidebarPersistentToastContext.Provider>
|
||||
</SidebarAppToastContext.Provider>
|
||||
<ToastViewport
|
||||
toast={toast}
|
||||
persistentToast={persistentToast}
|
||||
onDismiss={dismiss}
|
||||
placement="sidebar"
|
||||
onBottomCoverageChange={handleCoverageChange}
|
||||
/>
|
||||
</ToastApiProvider>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** Returns the enclosing app-level toast API so sidebar callers can report errors without displacing an active sidebar undo toast. */
|
||||
export function useSidebarAppToast(): ToastApi {
|
||||
const fallbackToast = useToast();
|
||||
return useContext(SidebarAppToastContext) ?? fallbackToast;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a persistent toast in the enclosing `SidebarToastRegion`, stacked below any active
|
||||
* transient toast so controls stay reachable while a previous toast is up.
|
||||
*/
|
||||
export function useSidebarPersistentToast(toast: ToastState | null): void {
|
||||
const setPersistentToast = useContext(SidebarPersistentToastContext);
|
||||
useEffect(() => {
|
||||
setPersistentToast?.(toast);
|
||||
}, [setPersistentToast, toast]);
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setPersistentToast?.(null);
|
||||
};
|
||||
}, [setPersistentToast]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Space at the end of a sidebar list that matches the toast covering it, so the last row can
|
||||
* scroll clear of the toast. It sits below every row, so growing it moves nothing. It shrinks
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useMemo, type ComponentProps, type PropsWithChildren, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { PressableStateCallbackType } from "react-native";
|
||||
import type { GestureResponderEvent, PressableStateCallbackType } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
Archive,
|
||||
CheckSquare,
|
||||
Circle,
|
||||
CircleCheck,
|
||||
Copy,
|
||||
@@ -56,6 +57,7 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
const ThemedMoreVertical = withUnistyles(MoreVertical);
|
||||
const ThemedCopy = withUnistyles(Copy);
|
||||
const ThemedArchive = withUnistyles(Archive);
|
||||
const ThemedCheckSquare = withUnistyles(CheckSquare);
|
||||
const ThemedCircle = withUnistyles(Circle);
|
||||
const ThemedPencil = withUnistyles(Pencil);
|
||||
const ThemedCircleCheck = withUnistyles(CircleCheck);
|
||||
@@ -69,6 +71,7 @@ const markAsReadLeadingIcon = (
|
||||
<ThemedCircleCheck size={14} uniProps={foregroundMutedColorMapping} />
|
||||
);
|
||||
const markAsUnreadLeadingIcon = <ThemedCircle size={14} uniProps={foregroundMutedColorMapping} />;
|
||||
const selectLeadingIcon = <ThemedCheckSquare size={14} uniProps={foregroundMutedColorMapping} />;
|
||||
const archiveLeadingIcon = <ThemedArchive size={14} uniProps={foregroundMutedColorMapping} />;
|
||||
const pinLeadingIcon = <ThemedPin size={14} uniProps={foregroundMutedColorMapping} />;
|
||||
const unpinLeadingIcon = <ThemedPinOff size={14} uniProps={foregroundMutedColorMapping} />;
|
||||
@@ -124,6 +127,7 @@ export interface SidebarWorkspaceMenuProps {
|
||||
onRename?: () => void;
|
||||
onMarkAsRead?: () => void;
|
||||
onMarkAsUnread?: () => void;
|
||||
onSelectWorkspace?: () => void;
|
||||
onArchive: () => void;
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
@@ -172,6 +176,7 @@ function SidebarWorkspaceMenuItems({
|
||||
onRename,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
@@ -267,6 +272,16 @@ function SidebarWorkspaceMenuItems({
|
||||
path={openInFileManagerPath}
|
||||
testID={`sidebar-workspace-menu-open-folder-${workspaceKey}`}
|
||||
/>
|
||||
{onSelectWorkspace ? (
|
||||
<WorkspaceMenuItem
|
||||
surface={surface}
|
||||
testID={`sidebar-workspace-menu-select-${workspaceKey}`}
|
||||
leading={selectLeadingIcon}
|
||||
onSelect={onSelectWorkspace}
|
||||
>
|
||||
{t("sidebar.workspace.actions.select")}
|
||||
</WorkspaceMenuItem>
|
||||
) : null}
|
||||
{onArchive ? (
|
||||
<WorkspaceMenuItem
|
||||
surface={surface}
|
||||
@@ -294,6 +309,7 @@ export function SidebarWorkspaceMenu({
|
||||
onRename,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
@@ -340,6 +356,7 @@ export function SidebarWorkspaceMenu({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
@@ -373,6 +390,7 @@ export function SidebarWorkspaceContextMenu({
|
||||
onRename,
|
||||
onMarkAsRead,
|
||||
onMarkAsUnread,
|
||||
onSelectWorkspace,
|
||||
onArchive,
|
||||
archiveLabel,
|
||||
archiveStatus,
|
||||
@@ -426,11 +444,37 @@ export function SidebarWorkspaceContextMenu({
|
||||
[workspace],
|
||||
);
|
||||
const pages = useWorkspaceLabelMenuPages(workspaceTarget);
|
||||
const checkboxSpaceKeyProps = useMemo(() => {
|
||||
if (!isWeb || triggerProps.accessibilityRole !== "checkbox" || !triggerProps.onPress) {
|
||||
return {};
|
||||
}
|
||||
const onPress = triggerProps.onPress;
|
||||
return {
|
||||
// React Native Web's Pressable activates Space only for role="button", not checkbox.
|
||||
onKeyDown: (event: {
|
||||
key?: string;
|
||||
repeat?: boolean;
|
||||
target?: unknown;
|
||||
currentTarget?: unknown;
|
||||
preventDefault?: () => void;
|
||||
}) => {
|
||||
if (triggerProps.disabled) return;
|
||||
if (event.target !== event.currentTarget) return;
|
||||
if (event.key === " " || event.key === "Spacebar") {
|
||||
event.preventDefault?.();
|
||||
if (!event.repeat) {
|
||||
onPress(event as unknown as GestureResponderEvent);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}, [triggerProps.accessibilityRole, triggerProps.disabled, triggerProps.onPress]);
|
||||
|
||||
return (
|
||||
<ContextMenu open={contextMenuOpen} onOpenChange={onContextMenuOpenChange}>
|
||||
<ContextMenuTrigger
|
||||
{...triggerProps}
|
||||
{...checkboxSpaceKeyProps}
|
||||
enabledOnMobile={false}
|
||||
accessibilityLabel={accessibilityLabel ?? rowAccessibilityLabel}
|
||||
highlightStyle={highlightStyle}
|
||||
@@ -454,6 +498,7 @@ export function SidebarWorkspaceContextMenu({
|
||||
onRename={onRename}
|
||||
onMarkAsRead={onMarkAsRead}
|
||||
onMarkAsUnread={onMarkAsUnread}
|
||||
onSelectWorkspace={onSelectWorkspace}
|
||||
onArchive={onArchive}
|
||||
archiveLabel={archiveLabel}
|
||||
archiveStatus={archiveStatus}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { memo, useMemo, useCallback, useState, type ReactNode } from "react";
|
||||
import { Text, View, type ViewStyle } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
|
||||
import { Check, CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
|
||||
import { bySizing } from "@/components/ui/control-geometry";
|
||||
import { ProjectStatusIndicator } from "@/components/sidebar/project-leading-visual";
|
||||
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
|
||||
import {
|
||||
@@ -40,19 +41,26 @@ const needsInputColorMapping = (theme: Theme) => ({
|
||||
color: theme.colors.surface0,
|
||||
fill: getStatusDotColor({ theme, bucket: "needs_input" }) ?? undefined,
|
||||
});
|
||||
const checkedIconMapping = (theme: Theme) => ({
|
||||
color: theme.colors.accentForeground,
|
||||
});
|
||||
|
||||
const ThemedCheck = withUnistyles(Check);
|
||||
const ThemedCircleAlert = withUnistyles(CircleAlert);
|
||||
|
||||
export function SidebarWorkspaceRowFrame({
|
||||
workspace,
|
||||
isDragging = false,
|
||||
isEditingTitle = false,
|
||||
isSelectionMode = false,
|
||||
children,
|
||||
}: {
|
||||
workspace: SidebarWorkspaceEntry;
|
||||
isDragging?: boolean;
|
||||
/** Hover would fade the kebab in over the title being edited and open the hover card. */
|
||||
isEditingTitle?: boolean;
|
||||
/** Hover cards would cover neighbouring rows while the user clicks through a selection. */
|
||||
isSelectionMode?: boolean;
|
||||
children: (input: {
|
||||
isHovered: boolean;
|
||||
contextMenuOpen: boolean;
|
||||
@@ -80,7 +88,7 @@ export function SidebarWorkspaceRowFrame({
|
||||
workspace={workspace}
|
||||
prHint={workspace.prHint}
|
||||
isDragging={isDragging}
|
||||
disabled={contextMenuOpen || isEditingTitle}
|
||||
disabled={contextMenuOpen || isEditingTitle || isSelectionMode}
|
||||
>
|
||||
{children({
|
||||
isHovered: isHovered && !contextMenuOpen && !isDragging && !isEditingTitle,
|
||||
@@ -102,6 +110,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
isHovered,
|
||||
isLoading,
|
||||
isCreating = false,
|
||||
isSelectionMode = false,
|
||||
isBulkSelected = false,
|
||||
shortcutNumber = null,
|
||||
showShortcutBadge = false,
|
||||
reserveIdleStatusIndicatorSpace = true,
|
||||
@@ -119,6 +129,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
isHovered: boolean;
|
||||
isLoading: boolean;
|
||||
isCreating?: boolean;
|
||||
isSelectionMode?: boolean;
|
||||
isBulkSelected?: boolean;
|
||||
shortcutNumber?: number | null;
|
||||
showShortcutBadge?: boolean;
|
||||
/** Keep the empty leading slot when the workspace has no active status. */
|
||||
@@ -137,33 +149,44 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
const workspaceBranchTextStyle = useMemo(
|
||||
() => [
|
||||
styles.workspaceBranchText,
|
||||
isHovered && styles.workspaceBranchTextHovered,
|
||||
(isHovered || isBulkSelected) && styles.workspaceBranchTextHovered,
|
||||
isCreating && styles.workspaceBranchTextCreating,
|
||||
],
|
||||
[isHovered, isCreating],
|
||||
[isHovered, isBulkSelected, isCreating],
|
||||
);
|
||||
|
||||
let leadingVisual: ReactNode;
|
||||
if (isSelectionMode) {
|
||||
leadingVisual = (
|
||||
<WorkspaceSelectionCheckbox checked={isBulkSelected} workspaceKey={workspace.workspaceKey} />
|
||||
);
|
||||
} else if (leadingProjectName) {
|
||||
leadingVisual = (
|
||||
<ProjectStatusIndicator
|
||||
iconDataUri={leadingProjectIconDataUri}
|
||||
displayName={leadingProjectName}
|
||||
projectViewKey={workspace.projectViewKey}
|
||||
statusBucket={workspace.statusBucket}
|
||||
backdrop={backdrop}
|
||||
loading={isLoading}
|
||||
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
leadingVisual = (
|
||||
<WorkspaceStatusIndicator
|
||||
bucket={workspace.statusBucket}
|
||||
workspaceKind={workspace.workspaceKind}
|
||||
loading={isLoading}
|
||||
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.workspaceRowContent}>
|
||||
<View style={styles.workspaceRowMain}>
|
||||
{leadingProjectName ? (
|
||||
<ProjectStatusIndicator
|
||||
iconDataUri={leadingProjectIconDataUri}
|
||||
displayName={leadingProjectName}
|
||||
projectViewKey={workspace.projectViewKey}
|
||||
statusBucket={workspace.statusBucket}
|
||||
backdrop={backdrop}
|
||||
loading={isLoading}
|
||||
testID={`sidebar-row-project-icon-${workspace.workspaceKey}`}
|
||||
/>
|
||||
) : (
|
||||
<WorkspaceStatusIndicator
|
||||
bucket={workspace.statusBucket}
|
||||
workspaceKind={workspace.workspaceKind}
|
||||
loading={isLoading}
|
||||
reserveIdleSpace={reserveIdleStatusIndicatorSpace}
|
||||
/>
|
||||
)}
|
||||
{leadingVisual}
|
||||
<View style={styles.workspaceContentColumn}>
|
||||
<View style={styles.workspaceTitleRow}>
|
||||
{titleEditor ? (
|
||||
@@ -191,7 +214,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
{showShortcutBadge && shortcutNumber !== null ? (
|
||||
{!isSelectionMode && showShortcutBadge && shortcutNumber !== null ? (
|
||||
<View style={styles.shortcutBadgeOverlay} pointerEvents="none">
|
||||
<SidebarWorkspaceShortcutBadge number={shortcutNumber} />
|
||||
</View>
|
||||
@@ -200,6 +223,22 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
);
|
||||
});
|
||||
|
||||
function WorkspaceSelectionCheckbox({
|
||||
checked,
|
||||
workspaceKey,
|
||||
}: {
|
||||
checked: boolean;
|
||||
workspaceKey: string;
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.workspaceStatusDot} testID={`sidebar-workspace-checkbox-${workspaceKey}`}>
|
||||
<View style={checked ? styles.selectionCheckboxChecked : styles.selectionCheckbox}>
|
||||
{checked ? <ThemedCheck size={11} strokeWidth={2.5} uniProps={checkedIconMapping} /> : null}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceStatusIndicator({
|
||||
bucket,
|
||||
workspaceKind,
|
||||
@@ -382,6 +421,7 @@ export function resolveTrailingActionVisibility({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode = false,
|
||||
}: {
|
||||
workspace: SidebarWorkspaceEntry;
|
||||
trailing: SidebarWorkspaceTrailing;
|
||||
@@ -389,6 +429,7 @@ export function resolveTrailingActionVisibility({
|
||||
isHovered: boolean;
|
||||
isTouchPlatform: boolean;
|
||||
showShortcut: boolean;
|
||||
isSelectionMode?: boolean;
|
||||
}): {
|
||||
trailingPresentation: SidebarWorkspaceTrailingPresentation;
|
||||
showKebab: boolean;
|
||||
@@ -398,10 +439,11 @@ export function resolveTrailingActionVisibility({
|
||||
reserveSlotWidth: boolean;
|
||||
} {
|
||||
const hasTrailing = hasSidebarWorkspaceTrailing({ workspace, trailing });
|
||||
const showKebab = Boolean(hasArchiveAction && (isHovered || isTouchPlatform)) && !showShortcut;
|
||||
const allowRowActions = hasArchiveAction && !isSelectionMode;
|
||||
const showKebab = Boolean(allowRowActions && (isHovered || isTouchPlatform)) && !showShortcut;
|
||||
// Touch permanently replaces the stats with the menu. Only temporary shortcut hints
|
||||
// conceal content while retaining its width, so desktop rows do not shift.
|
||||
const hasContent = hasTrailing && !(hasArchiveAction && isTouchPlatform);
|
||||
const hasContent = hasTrailing && !(allowRowActions && isTouchPlatform);
|
||||
let trailingPresentation: SidebarWorkspaceTrailingPresentation = "absent";
|
||||
if (hasContent) trailingPresentation = showShortcut ? "hidden" : "visible";
|
||||
return {
|
||||
@@ -414,12 +456,12 @@ export function resolveTrailingActionVisibility({
|
||||
// row — over an unhovered one the gradient fades to the wrong color. That is also why
|
||||
// touch, which shows the kebab without ever hovering, never gets one.
|
||||
showScrim: showKebab && isHovered,
|
||||
renderSlot: hasArchiveAction || hasTrailing,
|
||||
renderSlot: allowRowActions || hasTrailing,
|
||||
// The slot only holds width for something that permanently sits in it. Trailing content
|
||||
// does; the kebab only does on touch, where there is no hover for it to appear on and so
|
||||
// no scrim to let it overlay the title. Everywhere else the width goes back to the title
|
||||
// and the kebab fades in over its tail.
|
||||
reserveSlotWidth: hasContent || (hasArchiveAction && isTouchPlatform),
|
||||
reserveSlotWidth: hasContent || (allowRowActions && isTouchPlatform),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -536,6 +578,25 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
selectionCheckbox: {
|
||||
width: bySizing({ touch: 18, pointer: 15 }),
|
||||
height: bySizing({ touch: 18, pointer: 15 }),
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
borderWidth: 1.5,
|
||||
borderColor: theme.colors.borderAccent,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
selectionCheckboxChecked: {
|
||||
width: bySizing({ touch: 18, pointer: 15 }),
|
||||
height: bySizing({ touch: 18, pointer: 15 }),
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
borderWidth: 1.5,
|
||||
borderColor: theme.colors.accent,
|
||||
backgroundColor: theme.colors.accent,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
statusDotOverlay: {
|
||||
position: "absolute",
|
||||
right: 0,
|
||||
|
||||
@@ -16,6 +16,7 @@ import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { SPACING, type Theme } from "@/styles/theme";
|
||||
import { CONTROL_HEIGHTS, mapLayout } from "@/components/ui/control-geometry";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
@@ -28,10 +29,16 @@ import {
|
||||
} from "@/constants/layout";
|
||||
|
||||
export type ToastVariant = "default" | "info" | "success" | "warning" | "error";
|
||||
/**
|
||||
* `action` tightens vertical and trailing insets around `size="sm"` pill controls and uses a
|
||||
* concentric corner radius (`controlHeight / 2 + inset`) so buttons nest evenly in the shell.
|
||||
*/
|
||||
export type ToastLayout = "default" | "action";
|
||||
|
||||
export interface ToastShowOptions {
|
||||
icon?: ReactNode;
|
||||
variant?: ToastVariant;
|
||||
layout?: ToastLayout;
|
||||
durationMs?: number | null;
|
||||
nativeAndroid?: boolean;
|
||||
testID?: string;
|
||||
@@ -45,6 +52,7 @@ export interface ToastState {
|
||||
nativeMessage: string | null;
|
||||
icon?: ReactNode;
|
||||
variant: ToastVariant;
|
||||
layout?: ToastLayout;
|
||||
durationMs: number | null;
|
||||
testID?: string;
|
||||
onDismiss?: () => void;
|
||||
@@ -73,6 +81,11 @@ const TOAST_MAX_WIDTH = 480;
|
||||
/** How long a toast takes to fade in or out. */
|
||||
export const TOAST_FADE_MS = 140;
|
||||
const SIDEBAR_TOAST_INSET = SPACING[2];
|
||||
const ACTION_TOAST_INSET = SPACING[1.5];
|
||||
const ACTION_TOAST_RADIUS = mapLayout(
|
||||
CONTROL_HEIGHTS.sm,
|
||||
(height) => height / 2 + ACTION_TOAST_INSET,
|
||||
);
|
||||
const toastEntering = FadeIn.duration(TOAST_FADE_MS);
|
||||
const toastExiting = FadeOut.duration(TOAST_FADE_MS);
|
||||
const ThemedCheckCircle = withUnistyles(CheckCircle2);
|
||||
@@ -136,6 +149,7 @@ export function useToastHost(): {
|
||||
nativeMessage,
|
||||
icon: options?.icon,
|
||||
variant,
|
||||
layout: options?.layout,
|
||||
durationMs,
|
||||
testID: options?.testID,
|
||||
onDismiss: options?.onDismiss,
|
||||
@@ -163,11 +177,14 @@ export function useToastHost(): {
|
||||
|
||||
export function ToastViewport({
|
||||
toast,
|
||||
persistentToast = null,
|
||||
onDismiss,
|
||||
placement = "app-shell",
|
||||
onBottomCoverageChange,
|
||||
}: {
|
||||
toast: ToastState | null;
|
||||
/** Sidebar placement: persistent bar (such as select mode) that stays visible below transient toasts. */
|
||||
persistentToast?: ToastState | null;
|
||||
/** Called with the ID of the toast that timed out. */
|
||||
onDismiss: (id: number) => void;
|
||||
placement?: ToastViewportPlacement;
|
||||
@@ -232,7 +249,10 @@ export function ToastViewport({
|
||||
|
||||
const handleSidebarLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
onBottomCoverageChange?.(event.nativeEvent.layout.height + SIDEBAR_TOAST_INSET);
|
||||
const height = event.nativeEvent.layout.height;
|
||||
if (height > 0) {
|
||||
onBottomCoverageChange?.(height + SIDEBAR_TOAST_INSET);
|
||||
}
|
||||
},
|
||||
[onBottomCoverageChange],
|
||||
);
|
||||
@@ -243,28 +263,41 @@ export function ToastViewport({
|
||||
const topOffset =
|
||||
placement === "app-shell" ? insets.top + headerTopPadding + headerHeight : panelClearance;
|
||||
|
||||
if (placement === "sidebar") {
|
||||
return (
|
||||
<View
|
||||
style={animatedStyles.sidebarContainer}
|
||||
pointerEvents="box-none"
|
||||
collapsable={false}
|
||||
onLayout={handleSidebarLayout}
|
||||
>
|
||||
<SidebarToastSlot
|
||||
toast={toast}
|
||||
onPointerEnter={pauseDismiss}
|
||||
onPointerLeave={resumeDismiss}
|
||||
/>
|
||||
<SidebarToastSlot
|
||||
toast={persistentToast}
|
||||
onPointerEnter={noopDismiss}
|
||||
onPointerLeave={noopDismiss}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
// Keep the bottom anchor and its contents together while the native exit retains the view.
|
||||
const content = toast ? (
|
||||
<Animated.View
|
||||
entering={toastEntering}
|
||||
exiting={toastExiting}
|
||||
style={
|
||||
placement === "sidebar"
|
||||
? animatedStyles.sidebarContainer
|
||||
: [
|
||||
animatedStyles.container,
|
||||
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
|
||||
]
|
||||
}
|
||||
style={[
|
||||
animatedStyles.container,
|
||||
{ top: topOffset + (placement === "app-shell" ? SPACING[2] : SPACING[3]) },
|
||||
]}
|
||||
pointerEvents="box-none"
|
||||
collapsable={false}
|
||||
onLayout={placement === "sidebar" ? handleSidebarLayout : undefined}
|
||||
>
|
||||
<View
|
||||
style={placement === "sidebar" ? styles.sidebarWidthBoundary : styles.widthBoundary}
|
||||
pointerEvents="box-none"
|
||||
collapsable={false}
|
||||
>
|
||||
<View style={styles.widthBoundary} pointerEvents="box-none" collapsable={false}>
|
||||
<View
|
||||
style={animatedStyles.surface}
|
||||
testID={toast.testID ?? "app-toast"}
|
||||
@@ -283,6 +316,35 @@ export function ToastViewport({
|
||||
return placement === "panel" ? <FloatingHeaderOverlay>{content}</FloatingHeaderOverlay> : content;
|
||||
}
|
||||
|
||||
function SidebarToastSlot({
|
||||
toast,
|
||||
onPointerEnter,
|
||||
onPointerLeave,
|
||||
}: {
|
||||
toast: ToastState | null;
|
||||
onPointerEnter: () => void;
|
||||
onPointerLeave: () => void;
|
||||
}) {
|
||||
if (!toast) return null;
|
||||
return (
|
||||
<Animated.View
|
||||
entering={toastEntering}
|
||||
exiting={toastExiting}
|
||||
style={styles.sidebarWidthBoundary}
|
||||
pointerEvents="box-none"
|
||||
collapsable={false}
|
||||
>
|
||||
<View
|
||||
style={animatedStyles.surface}
|
||||
testID={toast.testID ?? "app-toast"}
|
||||
accessibilityRole="alert"
|
||||
>
|
||||
<ToastCard toast={toast} onPointerEnter={onPointerEnter} onPointerLeave={onPointerLeave} />
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
function ToastCard({
|
||||
toast,
|
||||
onPointerEnter,
|
||||
@@ -310,6 +372,7 @@ function ToastCard({
|
||||
onPointerLeave={onPointerLeave}
|
||||
style={[
|
||||
styles.toast,
|
||||
toast.layout === "action" ? styles.toastAction : null,
|
||||
toast.variant === "info" ? styles.toastInfo : null,
|
||||
toast.variant === "warning" ? styles.toastWarning : null,
|
||||
toast.variant === "error" ? styles.toastError : null,
|
||||
@@ -344,6 +407,7 @@ const animatedStyles = NativeStyleSheet.create({
|
||||
bottom: SIDEBAR_TOAST_INSET,
|
||||
zIndex: OVERLAY_Z.toast,
|
||||
alignItems: "center",
|
||||
gap: SIDEBAR_TOAST_INSET,
|
||||
},
|
||||
surface: { alignSelf: "center", maxWidth: "100%" },
|
||||
});
|
||||
@@ -372,6 +436,12 @@ const styles = StyleSheet.create((theme) => ({
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
...theme.shadow.md,
|
||||
},
|
||||
toastAction: {
|
||||
borderRadius: ACTION_TOAST_RADIUS,
|
||||
paddingVertical: theme.spacing[1.5],
|
||||
paddingLeft: theme.spacing[3.5],
|
||||
paddingRight: theme.spacing[1.5],
|
||||
},
|
||||
toastInfo: {
|
||||
borderColor: theme.colors.palette.blue[300],
|
||||
},
|
||||
|
||||
@@ -146,6 +146,8 @@ export interface ComboboxProps {
|
||||
/** When true, selecting an option does not close the picker (multi-select mode). */
|
||||
keepOpenOnSelect?: boolean;
|
||||
anchorRef: React.RefObject<View | null>;
|
||||
/** Where focus goes when the picker closes. Defaults to whatever had focus when it opened. */
|
||||
restoreFocusRef?: React.RefObject<unknown>;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
@@ -1437,6 +1439,7 @@ export function Combobox({
|
||||
footer,
|
||||
keepOpenOnSelect = false,
|
||||
anchorRef,
|
||||
restoreFocusRef,
|
||||
children,
|
||||
}: ComboboxProps): ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
@@ -1728,6 +1731,7 @@ export function Combobox({
|
||||
layer: floatingLayer,
|
||||
keys: ["Escape", "Enter", "ArrowUp", "ArrowDown"],
|
||||
onKeyDown: (event) => (isDesktopKey(event.key) ? handleDesktopKey(event.key, event) : false),
|
||||
restoreFocusRef,
|
||||
});
|
||||
|
||||
const effectiveSearchPlaceholder = searchPlaceholder ?? resolvedPlaceholder;
|
||||
|
||||
@@ -96,6 +96,7 @@ import {
|
||||
import {
|
||||
useAgentProfileEditor,
|
||||
useAgentProfilePicker,
|
||||
type AgentProfile,
|
||||
type AgentProfileApplyTarget,
|
||||
type AgentProfileEditorControls,
|
||||
type AgentProfilePicker,
|
||||
@@ -127,7 +128,7 @@ interface ControlledAgentControlsProps {
|
||||
agentProfiles?: AgentProfilePicker | null;
|
||||
onApplyAgentProfile?: (profileId: string) => void;
|
||||
onEditAgentProfiles?: () => void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditAgentProfile?: (profileId: string) => void;
|
||||
optionControls?: ComposerOptionControls;
|
||||
onDropdownClose?: () => void;
|
||||
@@ -269,7 +270,7 @@ function useEditAgentProfilesNavigation(
|
||||
): (() => void) | undefined {
|
||||
const handleEdit = useCallback(() => {
|
||||
if (!serverId) return;
|
||||
router.push(buildSettingsHostSectionRoute(serverId, "agents"));
|
||||
router.push(buildSettingsHostSectionRoute(serverId, "agent-profiles"));
|
||||
}, [serverId]);
|
||||
return serverId && isSupported ? handleEdit : undefined;
|
||||
}
|
||||
@@ -278,14 +279,14 @@ function resolveAgentProfileEditorActions(
|
||||
isSupported: boolean,
|
||||
editor: AgentProfileEditorControls,
|
||||
): {
|
||||
create?: (seed: AgentProfileSeed) => void;
|
||||
create?: (seed: AgentProfileSeed) => Promise<AgentProfile | null>;
|
||||
edit?: (profileId: string) => void;
|
||||
} {
|
||||
if (!isSupported) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
create: editor.openCreateFromModel,
|
||||
create: editor.quickCreateFromModel,
|
||||
edit: editor.openEdit,
|
||||
};
|
||||
}
|
||||
@@ -732,7 +733,7 @@ interface AgentControlsContentProps {
|
||||
featureItems: ComposerControlItem[];
|
||||
onApplyAgentProfile?: (profileId: string) => void;
|
||||
onEditAgentProfiles?: () => void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditAgentProfile?: (profileId: string) => void;
|
||||
onDropdownClose?: () => void;
|
||||
onModelSelectorOpen?: () => void;
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||
import type { AgentProfile, AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||
import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet";
|
||||
import type { ContextBridge } from "@/components/ui/isolated-bottom-sheet-modal";
|
||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||
@@ -56,7 +56,7 @@ interface CompactModelSheetProps {
|
||||
profiles?: AgentProfilePicker | null;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onOpen?: () => void;
|
||||
onClose?: () => void;
|
||||
@@ -74,8 +74,9 @@ interface CompactModelSheetProps {
|
||||
}
|
||||
|
||||
function resolveModelSheetProfileActions(
|
||||
onCreateProfile: ((seed: AgentProfileSeed) => void) | undefined,
|
||||
onCreateProfile: ((seed: AgentProfileSeed) => Promise<AgentProfile | null> | void) | undefined,
|
||||
onEditProfile: ((profileId: string) => void) | undefined,
|
||||
onSelect: (provider: string, modelId: string) => void,
|
||||
close: () => void,
|
||||
): {
|
||||
create?: (seed: AgentProfileSeed) => void;
|
||||
@@ -84,8 +85,11 @@ function resolveModelSheetProfileActions(
|
||||
return {
|
||||
create: onCreateProfile
|
||||
? (seed: AgentProfileSeed) => {
|
||||
if (seed.modelId) {
|
||||
onSelect(seed.provider, seed.modelId);
|
||||
}
|
||||
close();
|
||||
onCreateProfile(seed);
|
||||
void onCreateProfile(seed);
|
||||
}
|
||||
: undefined,
|
||||
edit: onEditProfile
|
||||
@@ -281,7 +285,12 @@ export function CompactModelSheet({
|
||||
onEditProfiles?.();
|
||||
}, [close, onEditProfiles]);
|
||||
|
||||
const profileActions = resolveModelSheetProfileActions(onCreateProfile, onEditProfile, close);
|
||||
const profileActions = resolveModelSheetProfileActions(
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
onSelect,
|
||||
close,
|
||||
);
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
if (isOpen) {
|
||||
|
||||
@@ -146,3 +146,41 @@ export async function confirmRiskyWorktreeArchive(
|
||||
destructive: true,
|
||||
});
|
||||
}
|
||||
|
||||
export async function confirmRiskyBulkWorktreeArchive(
|
||||
input: {
|
||||
totalCount: number;
|
||||
riskyWorkspaces: readonly WorktreeArchiveConfirmationInput[];
|
||||
},
|
||||
labels: WorktreeArchiveWarningLabels = DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS,
|
||||
): Promise<boolean> {
|
||||
const lines: string[] = [];
|
||||
let singleRisky: WorktreeArchiveConfirmationInput | null = null;
|
||||
for (const workspace of input.riskyWorkspaces) {
|
||||
const reasons = buildWorktreeArchiveRiskReasons(workspace, labels);
|
||||
if (reasons.length === 0) continue;
|
||||
singleRisky = workspace;
|
||||
lines.push(
|
||||
i18n.t("workspace.git.actions.archiveWarning.bulkWorkspaceReason", {
|
||||
workspaceName: workspace.workspaceName,
|
||||
reason: reasons.join(", "),
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (lines.length === 0) {
|
||||
return true;
|
||||
}
|
||||
if (input.totalCount === 1 && singleRisky) {
|
||||
return await confirmRiskyWorktreeArchive(singleRisky, labels);
|
||||
}
|
||||
|
||||
return await confirmDialog({
|
||||
title: i18n.t("workspace.git.actions.archiveWarning.bulkTitle", {
|
||||
count: input.totalCount,
|
||||
}),
|
||||
message: lines.join("\n"),
|
||||
confirmLabel: labels.confirm,
|
||||
cancelLabel: labels.cancel,
|
||||
destructive: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -960,6 +960,8 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: 'الأرشيف "{{workspaceName}}"؟',
|
||||
bulkTitle: "أرشفة {{count}} مساحات عمل؟",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "أرشيف",
|
||||
cancel: "يلغي",
|
||||
uncommittedChanges: "تغييرات غير ملتزم بها",
|
||||
@@ -1369,6 +1371,7 @@ export const ar: TranslationResources = {
|
||||
rename: "إعادة تسمية مساحة العمل",
|
||||
pin: "تثبيت في الأعلى",
|
||||
unpin: "إلغاء التثبيت",
|
||||
select: "تحديد",
|
||||
archive: "أرشيف",
|
||||
archiveWorkspace: "أرشفة مساحة العمل",
|
||||
hideFromSidebar: "إخفاء من الشريط الجانبي",
|
||||
@@ -1387,6 +1390,10 @@ export const ar: TranslationResources = {
|
||||
submit: "إعادة تسمية",
|
||||
invalidBranchName: "اسم الفرع غير صالح",
|
||||
},
|
||||
selection: {
|
||||
count: "تم تحديد {{count}}",
|
||||
exit: "إنهاء التحديد",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "مسار Workspace غير متوفر",
|
||||
pathCopied: "تم نسخ المسار",
|
||||
@@ -1394,7 +1401,9 @@ export const ar: TranslationResources = {
|
||||
hostDisconnected: "Host غير متصل",
|
||||
hideFailed: "فشل في إخفاء مساحة العمل",
|
||||
archiveFailed: "فشل في أرشفة مساحة العمل",
|
||||
archiveMultipleFailed: "فشل في أرشفة {{count}} مساحات عمل",
|
||||
archived: "تمت أرشفة مساحة العمل",
|
||||
archivedCount: "تمت أرشفة {{count}} مساحات عمل",
|
||||
undoArchive: "تراجع",
|
||||
undoArchiveFailed: "تعذّر التراجع عن الأرشفة",
|
||||
},
|
||||
@@ -1814,6 +1823,9 @@ export const ar: TranslationResources = {
|
||||
editProfilesLabel: "تحرير ملفات الوكيل",
|
||||
createProfile: "إنشاء ملف شخصي",
|
||||
createProfileFromModel: "إنشاء ملف شخصي من هذا النموذج",
|
||||
profileSaved: 'تم حفظ "{{name}}"',
|
||||
undo: "تراجع",
|
||||
undoProfileSave: "التراجع عن حفظ الملف الشخصي",
|
||||
editProfileLabel: "تحرير {{name}}",
|
||||
editProfilesCount: "تحرير الملفات الشخصية ({{count}})",
|
||||
modelCount: "{{count}} نموذج",
|
||||
@@ -2430,6 +2442,7 @@ export const ar: TranslationResources = {
|
||||
projects: "المشاريع",
|
||||
connections: "اتصالات",
|
||||
agents: "Agents",
|
||||
agentProfiles: "ملفات الوكيل",
|
||||
metadata: "البيانات الوصفية",
|
||||
voice: "الصوت",
|
||||
workspaces: "Workspaces",
|
||||
@@ -3057,6 +3070,31 @@ export const ar: TranslationResources = {
|
||||
removeConfirmMessage: 'إزالة "{{name}}"؟',
|
||||
moveUp: "نقل لأعلى",
|
||||
moveDown: "نقل لأسفل",
|
||||
searchPlaceholder: "ابحث عن الملفات",
|
||||
clearSearch: "مسح البحث",
|
||||
noSearchMatches: 'لا توجد ملفات تطابق "{{query}}"',
|
||||
noRoutingNote: "بدون ملاحظة",
|
||||
duplicate: "تكرار",
|
||||
copyName: "{{name}} (نسخة)",
|
||||
moveToTop: "نقل إلى الأعلى",
|
||||
profileActions: "إجراءات {{name}}",
|
||||
reorderProfile: "إعادة ترتيب {{name}}",
|
||||
previousProfile: "الملف السابق",
|
||||
nextProfile: "الملف التالي",
|
||||
chooseModelPlaceholder: "اختر نموذجًا",
|
||||
searchModelsPlaceholder: "ابحث عن النماذج",
|
||||
chooseModelSubtitle: "اختر نموذجًا",
|
||||
customizeSettings: "تخصيص الإعدادات",
|
||||
addRoutingNoteShort: "إضافة ملاحظة",
|
||||
providerOptionsLabel: "خيارات {{provider}}",
|
||||
discardTitle: "تجاهل التغييرات؟",
|
||||
discardMessage: "لديك تغييرات غير محفوظة في هذا الملف.",
|
||||
discardConfirm: "تجاهل",
|
||||
columns: {
|
||||
profile: "الملف",
|
||||
runtime: "النموذج والتشغيل",
|
||||
whenToUse: "متى يُستخدم",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -971,6 +971,8 @@ export const en = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: 'Archive "{{workspaceName}}"?',
|
||||
bulkTitle: "Archive {{count}} workspaces?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "Archive",
|
||||
cancel: "Cancel",
|
||||
uncommittedChanges: "Uncommitted changes",
|
||||
@@ -1380,6 +1382,7 @@ export const en = {
|
||||
rename: "Rename workspace",
|
||||
pin: "Pin to top",
|
||||
unpin: "Unpin",
|
||||
select: "Select",
|
||||
archive: "Archive",
|
||||
archiveWorkspace: "Archive workspace",
|
||||
hideFromSidebar: "Hide from sidebar",
|
||||
@@ -1398,6 +1401,10 @@ export const en = {
|
||||
submit: "Rename",
|
||||
invalidBranchName: "Invalid branch name",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}} selected",
|
||||
exit: "Exit selection",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "Workspace path not available",
|
||||
pathCopied: "Path copied",
|
||||
@@ -1405,7 +1412,9 @@ export const en = {
|
||||
hostDisconnected: "Host is not connected",
|
||||
hideFailed: "Failed to hide workspace",
|
||||
archiveFailed: "Failed to archive workspace",
|
||||
archiveMultipleFailed: "Failed to archive {{count}} workspaces",
|
||||
archived: "Workspace archived",
|
||||
archivedCount: "{{count}} workspaces archived",
|
||||
undoArchive: "Undo",
|
||||
undoArchiveFailed: "Couldn't undo the archive",
|
||||
},
|
||||
@@ -1843,6 +1852,9 @@ export const en = {
|
||||
editProfilesLabel: "Edit agent profiles",
|
||||
createProfile: "Create profile",
|
||||
createProfileFromModel: "Create profile from this model",
|
||||
profileSaved: 'Saved "{{name}}"',
|
||||
undo: "Undo",
|
||||
undoProfileSave: "Undo saving profile",
|
||||
editProfileLabel: "Edit {{name}}",
|
||||
editProfilesCount: "Edit profiles ({{count}})",
|
||||
modelCount: "{{count}} model",
|
||||
@@ -2461,6 +2473,7 @@ export const en = {
|
||||
projects: "Projects",
|
||||
connections: "Connections",
|
||||
agents: "Agents",
|
||||
agentProfiles: "Agent profiles",
|
||||
metadata: "Metadata",
|
||||
voice: "Voice",
|
||||
workspaces: "Workspaces",
|
||||
@@ -3147,7 +3160,7 @@ export const en = {
|
||||
featureCountOne: "{{count}} feature",
|
||||
notesLabel: "When to use",
|
||||
notesPlaceholder: "Use for UI work — components, layout and design tokens.",
|
||||
notesHint: "Helps agents choose this profile when starting another agent.",
|
||||
notesHint: "Tells agents when to pick this profile",
|
||||
save: "Save",
|
||||
saving: "Saving...",
|
||||
remove: "Remove",
|
||||
@@ -3155,6 +3168,31 @@ export const en = {
|
||||
removeConfirmMessage: 'Remove "{{name}}"?',
|
||||
moveUp: "Move up",
|
||||
moveDown: "Move down",
|
||||
searchPlaceholder: "Search profiles",
|
||||
clearSearch: "Clear search",
|
||||
noSearchMatches: 'No profiles match "{{query}}"',
|
||||
noRoutingNote: "No note",
|
||||
duplicate: "Duplicate",
|
||||
copyName: "{{name}} (copy)",
|
||||
moveToTop: "Move to top",
|
||||
profileActions: "Actions for {{name}}",
|
||||
reorderProfile: "Reorder {{name}}",
|
||||
previousProfile: "Previous profile",
|
||||
nextProfile: "Next profile",
|
||||
chooseModelPlaceholder: "Select a model",
|
||||
searchModelsPlaceholder: "Search models",
|
||||
chooseModelSubtitle: "Select a model",
|
||||
customizeSettings: "Customize settings",
|
||||
addRoutingNoteShort: "Add a note",
|
||||
providerOptionsLabel: "{{provider}} options",
|
||||
discardTitle: "Discard changes?",
|
||||
discardMessage: "You have unsaved changes to this profile.",
|
||||
discardConfirm: "Discard",
|
||||
columns: {
|
||||
profile: "Profile",
|
||||
runtime: "Model & runtime",
|
||||
whenToUse: "When to use",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -994,6 +994,8 @@ export const es: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: '¿Archivo "{{workspaceName}}"?',
|
||||
bulkTitle: "¿Archivar {{count}} espacios de trabajo?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "Archivo",
|
||||
cancel: "Cancelar",
|
||||
uncommittedChanges: "Cambios no confirmados",
|
||||
@@ -1406,6 +1408,7 @@ export const es: TranslationResources = {
|
||||
rename: "Cambiar nombre del espacio de trabajo",
|
||||
pin: "Anclar arriba",
|
||||
unpin: "Desanclar",
|
||||
select: "Seleccionar",
|
||||
archive: "Archivo",
|
||||
archiveWorkspace: "Archivar espacio de trabajo",
|
||||
hideFromSidebar: "Ocultar de la barra lateral",
|
||||
@@ -1424,6 +1427,10 @@ export const es: TranslationResources = {
|
||||
submit: "Rebautizar",
|
||||
invalidBranchName: "Nombre de sucursal no válido",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}} seleccionados",
|
||||
exit: "Salir de la selección",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "RutaWorkspaceno disponible",
|
||||
pathCopied: "Ruta copiada",
|
||||
@@ -1431,7 +1438,9 @@ export const es: TranslationResources = {
|
||||
hostDisconnected: "Hostno está conectado",
|
||||
hideFailed: "No se pudo ocultar el espacio de trabajo",
|
||||
archiveFailed: "No se pudo archivar el espacio de trabajo",
|
||||
archiveMultipleFailed: "No se pudieron archivar {{count}} espacios de trabajo",
|
||||
archived: "Espacio de trabajo archivado",
|
||||
archivedCount: "{{count}} espacios de trabajo archivados",
|
||||
undoArchive: "Deshacer",
|
||||
undoArchiveFailed: "No se pudo deshacer el archivado",
|
||||
},
|
||||
@@ -1862,6 +1871,9 @@ export const es: TranslationResources = {
|
||||
editProfilesLabel: "Editar perfiles de agente",
|
||||
createProfile: "Crear perfil",
|
||||
createProfileFromModel: "Crear perfil desde este modelo",
|
||||
profileSaved: 'Guardado "{{name}}"',
|
||||
undo: "Deshacer",
|
||||
undoProfileSave: "Deshacer perfil guardado",
|
||||
editProfileLabel: "Editar {{name}}",
|
||||
editProfilesCount: "Editar perfiles ({{count}})",
|
||||
modelCount: "{{count}} modelo",
|
||||
@@ -2444,6 +2456,7 @@ export const es: TranslationResources = {
|
||||
projects: "Proyectos",
|
||||
connections: "Conexiones",
|
||||
agents: "Agents",
|
||||
agentProfiles: "Perfiles de agente",
|
||||
metadata: "Metadatos",
|
||||
voice: "Voz",
|
||||
workspaces: "Workspaces",
|
||||
@@ -3083,6 +3096,31 @@ export const es: TranslationResources = {
|
||||
removeConfirmMessage: '¿Eliminar "{{name}}"?',
|
||||
moveUp: "Mover hacia arriba",
|
||||
moveDown: "Mover hacia abajo",
|
||||
searchPlaceholder: "Buscar perfiles",
|
||||
clearSearch: "Limpiar búsqueda",
|
||||
noSearchMatches: 'Ningún perfil coincide con "{{query}}"',
|
||||
noRoutingNote: "Sin nota",
|
||||
duplicate: "Duplicar",
|
||||
copyName: "{{name}} (copia)",
|
||||
moveToTop: "Mover al principio",
|
||||
profileActions: "Acciones para {{name}}",
|
||||
reorderProfile: "Reordenar {{name}}",
|
||||
previousProfile: "Perfil anterior",
|
||||
nextProfile: "Perfil siguiente",
|
||||
chooseModelPlaceholder: "Seleccionar un modelo",
|
||||
searchModelsPlaceholder: "Buscar modelos",
|
||||
chooseModelSubtitle: "Seleccionar un modelo",
|
||||
customizeSettings: "Personalizar ajustes",
|
||||
addRoutingNoteShort: "Añadir una nota",
|
||||
providerOptionsLabel: "Opciones de {{provider}}",
|
||||
discardTitle: "¿Descartar cambios?",
|
||||
discardMessage: "Tienes cambios sin guardar en este perfil.",
|
||||
discardConfirm: "Descartar",
|
||||
columns: {
|
||||
profile: "Perfil",
|
||||
runtime: "Modelo y ejecución",
|
||||
whenToUse: "Cuándo usarlo",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -986,6 +986,8 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: "Archiver « {{workspaceName}} » ?",
|
||||
bulkTitle: "Archiver {{count}} espaces de travail ?",
|
||||
bulkWorkspaceReason: "{{workspaceName}} : {{reason}}",
|
||||
confirm: "Archiver",
|
||||
cancel: "Annuler",
|
||||
uncommittedChanges: "Modifications non commitées",
|
||||
@@ -1399,6 +1401,7 @@ export const fr: TranslationResources = {
|
||||
rename: "Renommer l’espace de travail",
|
||||
pin: "Épingler en haut",
|
||||
unpin: "Désépingler",
|
||||
select: "Sélectionner",
|
||||
archive: "Archiver",
|
||||
archiveWorkspace: "Archiver l’espace de travail",
|
||||
hideFromSidebar: "Masquer de la barre latérale",
|
||||
@@ -1417,6 +1420,10 @@ export const fr: TranslationResources = {
|
||||
submit: "Renommer",
|
||||
invalidBranchName: "Nom de branche invalide",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}} sélectionnés",
|
||||
exit: "Quitter la sélection",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "Chemin de l’espace de travail indisponible",
|
||||
pathCopied: "Chemin copié",
|
||||
@@ -1424,7 +1431,9 @@ export const fr: TranslationResources = {
|
||||
hostDisconnected: "L’hôte n’est pas connecté",
|
||||
hideFailed: "Impossible de masquer l’espace de travail",
|
||||
archiveFailed: "Impossible d’archiver l’espace de travail",
|
||||
archiveMultipleFailed: "Impossible d’archiver {{count}} espaces de travail",
|
||||
archived: "Espace de travail archivé",
|
||||
archivedCount: "{{count}} espaces de travail archivés",
|
||||
undoArchive: "Annuler",
|
||||
undoArchiveFailed: "Impossible d’annuler l’archivage",
|
||||
},
|
||||
@@ -1860,6 +1869,9 @@ export const fr: TranslationResources = {
|
||||
editProfilesLabel: "Modifier les profils d’agent",
|
||||
createProfile: "Créer un profil",
|
||||
createProfileFromModel: "Créer un profil à partir de ce modèle",
|
||||
profileSaved: "« {{name}} » enregistré",
|
||||
undo: "Annuler",
|
||||
undoProfileSave: "Annuler l’enregistrement du profil",
|
||||
editProfileLabel: "Modifier {{name}}",
|
||||
editProfilesCount: "Modifier les profils ({{count}})",
|
||||
modelCount: "{{count}} modèle",
|
||||
@@ -2444,6 +2456,7 @@ export const fr: TranslationResources = {
|
||||
projects: "Projets",
|
||||
connections: "Connexions",
|
||||
agents: "Agents",
|
||||
agentProfiles: "Profils d’agent",
|
||||
metadata: "Métadonnées",
|
||||
voice: "Voix",
|
||||
workspaces: "Espaces de travail",
|
||||
@@ -3087,6 +3100,31 @@ export const fr: TranslationResources = {
|
||||
removeConfirmMessage: "Supprimer « {{name}} » ?",
|
||||
moveUp: "Monter",
|
||||
moveDown: "Descendre",
|
||||
searchPlaceholder: "Rechercher des profils",
|
||||
clearSearch: "Effacer la recherche",
|
||||
noSearchMatches: "Aucun profil ne correspond à « {{query}} »",
|
||||
noRoutingNote: "Aucune note",
|
||||
duplicate: "Dupliquer",
|
||||
copyName: "{{name}} (copie)",
|
||||
moveToTop: "Placer en haut",
|
||||
profileActions: "Actions pour {{name}}",
|
||||
reorderProfile: "Réorganiser {{name}}",
|
||||
previousProfile: "Profil précédent",
|
||||
nextProfile: "Profil suivant",
|
||||
chooseModelPlaceholder: "Sélectionner un modèle",
|
||||
searchModelsPlaceholder: "Rechercher des modèles",
|
||||
chooseModelSubtitle: "Sélectionner un modèle",
|
||||
customizeSettings: "Personnaliser les réglages",
|
||||
addRoutingNoteShort: "Ajouter une note",
|
||||
providerOptionsLabel: "Options {{provider}}",
|
||||
discardTitle: "Ignorer les modifications ?",
|
||||
discardMessage: "Vous avez des modifications non enregistrées pour ce profil.",
|
||||
discardConfirm: "Ignorer",
|
||||
columns: {
|
||||
profile: "Profil",
|
||||
runtime: "Modèle et exécution",
|
||||
whenToUse: "Quand l’utiliser",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -974,6 +974,8 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: '"{{workspaceName}}"をアーカイブしますか?',
|
||||
bulkTitle: "{{count}}件のワークスペースをアーカイブしますか?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
|
||||
confirm: "アーカイブ",
|
||||
cancel: "キャンセル",
|
||||
uncommittedChanges: "未コミットの変更",
|
||||
@@ -1384,6 +1386,7 @@ export const ja: TranslationResources = {
|
||||
rename: "ワークスペースの名前を変更",
|
||||
pin: "上部に固定",
|
||||
unpin: "固定解除",
|
||||
select: "選択",
|
||||
archive: "アーカイブ",
|
||||
archiveWorkspace: "ワークスペースをアーカイブ",
|
||||
hideFromSidebar: "サイドバーから非表示",
|
||||
@@ -1402,6 +1405,10 @@ export const ja: TranslationResources = {
|
||||
submit: "名前を変更",
|
||||
invalidBranchName: "無効なブランチ名",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}}件選択中",
|
||||
exit: "選択を終了",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "ワークスペースパスが利用できません",
|
||||
pathCopied: "パスをコピーしました",
|
||||
@@ -1409,7 +1416,9 @@ export const ja: TranslationResources = {
|
||||
hostDisconnected: "ホストが接続されていません",
|
||||
hideFailed: "ワークスペースの非表示に失敗しました",
|
||||
archiveFailed: "ワークスペースのアーカイブに失敗しました",
|
||||
archiveMultipleFailed: "{{count}}件のワークスペースのアーカイブに失敗しました",
|
||||
archived: "ワークスペースをアーカイブしました",
|
||||
archivedCount: "{{count}}件のワークスペースをアーカイブしました",
|
||||
undoArchive: "元に戻す",
|
||||
undoArchiveFailed: "アーカイブを元に戻せませんでした",
|
||||
},
|
||||
@@ -1834,6 +1843,9 @@ export const ja: TranslationResources = {
|
||||
editProfilesLabel: "エージェントプロファイルを編集",
|
||||
createProfile: "プロファイルを作成",
|
||||
createProfileFromModel: "このモデルからプロファイルを作成",
|
||||
profileSaved: "「{{name}}」を保存しました",
|
||||
undo: "元に戻す",
|
||||
undoProfileSave: "プロファイル保存を取り消す",
|
||||
editProfileLabel: "{{name}}を編集",
|
||||
editProfilesCount: "プロファイルを編集({{count}})",
|
||||
modelCount: "{{count}}つのモデル",
|
||||
@@ -2418,6 +2430,7 @@ export const ja: TranslationResources = {
|
||||
projects: "プロジェクト",
|
||||
connections: "接続",
|
||||
agents: "エージェント",
|
||||
agentProfiles: "エージェントプロファイル",
|
||||
metadata: "メタデータ",
|
||||
voice: "音声",
|
||||
workspaces: "ワークスペース",
|
||||
@@ -3052,6 +3065,31 @@ export const ja: TranslationResources = {
|
||||
removeConfirmMessage: '"{{name}}"を削除しますか?',
|
||||
moveUp: "上に移動",
|
||||
moveDown: "下に移動",
|
||||
searchPlaceholder: "プロファイルを検索",
|
||||
clearSearch: "検索をクリア",
|
||||
noSearchMatches: "「{{query}}」に一致するプロファイルはありません",
|
||||
noRoutingNote: "メモなし",
|
||||
duplicate: "複製",
|
||||
copyName: "{{name}}(コピー)",
|
||||
moveToTop: "一番上に移動",
|
||||
profileActions: "{{name}} の操作",
|
||||
reorderProfile: "{{name}} を並べ替え",
|
||||
previousProfile: "前のプロファイル",
|
||||
nextProfile: "次のプロファイル",
|
||||
chooseModelPlaceholder: "モデルを選択",
|
||||
searchModelsPlaceholder: "モデルを検索",
|
||||
chooseModelSubtitle: "モデルを選択",
|
||||
customizeSettings: "設定をカスタマイズ",
|
||||
addRoutingNoteShort: "メモを追加",
|
||||
providerOptionsLabel: "{{provider}} オプション",
|
||||
discardTitle: "変更を破棄しますか?",
|
||||
discardMessage: "このプロファイルに未保存の変更があります。",
|
||||
discardConfirm: "破棄",
|
||||
columns: {
|
||||
profile: "プロファイル",
|
||||
runtime: "モデルと実行",
|
||||
whenToUse: "使用場面",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -967,6 +967,8 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: '"{{workspaceName}}"를 보관하시겠습니까?',
|
||||
bulkTitle: "워크스페이스 {{count}}개를 보관하시겠습니까?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "보관",
|
||||
cancel: "취소",
|
||||
uncommittedChanges: "커밋되지 않은 변경 사항",
|
||||
@@ -1376,6 +1378,7 @@ export const ko: TranslationResources = {
|
||||
rename: "워크스페이스 이름 변경",
|
||||
pin: "상단에 고정",
|
||||
unpin: "고정 해제",
|
||||
select: "선택",
|
||||
archive: "보관",
|
||||
archiveWorkspace: "워크스페이스 보관",
|
||||
hideFromSidebar: "사이드바에서 숨기기",
|
||||
@@ -1394,6 +1397,10 @@ export const ko: TranslationResources = {
|
||||
submit: "이름 변경",
|
||||
invalidBranchName: "잘못된 브랜치 이름",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}}개 선택됨",
|
||||
exit: "선택 종료",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "워크스페이스 경로를 사용할 수 없습니다",
|
||||
pathCopied: "경로가 복사되었습니다",
|
||||
@@ -1401,7 +1408,9 @@ export const ko: TranslationResources = {
|
||||
hostDisconnected: "호스트가 연결되어 있지 않습니다",
|
||||
hideFailed: "워크스페이스를 숨기지 못했습니다",
|
||||
archiveFailed: "워크스페이스를 보관하지 못했습니다.",
|
||||
archiveMultipleFailed: "워크스페이스 {{count}}개를 보관하지 못했습니다",
|
||||
archived: "워크스페이스를 보관했습니다",
|
||||
archivedCount: "워크스페이스 {{count}}개를 보관했습니다",
|
||||
undoArchive: "실행 취소",
|
||||
undoArchiveFailed: "보관을 취소하지 못했습니다",
|
||||
},
|
||||
@@ -1825,6 +1834,9 @@ export const ko: TranslationResources = {
|
||||
editProfilesLabel: "에이전트 프로필 편집",
|
||||
createProfile: "프로필 만들기",
|
||||
createProfileFromModel: "이 모델에서 프로필 만들기",
|
||||
profileSaved: '"{{name}}" 저장됨',
|
||||
undo: "실행 취소",
|
||||
undoProfileSave: "프로필 저장 취소",
|
||||
editProfileLabel: "{{name}} 편집",
|
||||
editProfilesCount: "프로필 편집 ({{count}})",
|
||||
modelCount: "모델 {{count}}개",
|
||||
@@ -2405,6 +2417,7 @@ export const ko: TranslationResources = {
|
||||
projects: "프로젝트",
|
||||
connections: "연결",
|
||||
agents: "에이전트",
|
||||
agentProfiles: "에이전트 프로필",
|
||||
metadata: "메타데이터",
|
||||
voice: "음성",
|
||||
workspaces: "워크스페이스",
|
||||
@@ -3036,6 +3049,31 @@ export const ko: TranslationResources = {
|
||||
removeConfirmMessage: '"{{name}}"을(를) 제거할까요?',
|
||||
moveUp: "위로 이동",
|
||||
moveDown: "아래로 이동",
|
||||
searchPlaceholder: "프로필 검색",
|
||||
clearSearch: "검색 지우기",
|
||||
noSearchMatches: '"{{query}}"와 일치하는 프로필이 없습니다',
|
||||
noRoutingNote: "메모 없음",
|
||||
duplicate: "복제",
|
||||
copyName: "{{name}} (사본)",
|
||||
moveToTop: "맨 위로 이동",
|
||||
profileActions: "{{name}} 작업",
|
||||
reorderProfile: "{{name}} 순서 변경",
|
||||
previousProfile: "이전 프로필",
|
||||
nextProfile: "다음 프로필",
|
||||
chooseModelPlaceholder: "모델 선택",
|
||||
searchModelsPlaceholder: "모델 검색",
|
||||
chooseModelSubtitle: "모델 선택",
|
||||
customizeSettings: "설정 사용자 지정",
|
||||
addRoutingNoteShort: "메모 추가",
|
||||
providerOptionsLabel: "{{provider}} 옵션",
|
||||
discardTitle: "변경 사항을 버리시겠습니까?",
|
||||
discardMessage: "이 프로필에 저장되지 않은 변경 사항이 있습니다.",
|
||||
discardConfirm: "버리기",
|
||||
columns: {
|
||||
profile: "프로필",
|
||||
runtime: "모델 및 런타임",
|
||||
whenToUse: "사용 시기",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -984,6 +984,8 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: 'Arquivar "{{workspaceName}}"?',
|
||||
bulkTitle: "Arquivar {{count}} workspaces?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "Arquivar",
|
||||
cancel: "Cancelar",
|
||||
uncommittedChanges: "Alterações sem commit",
|
||||
@@ -1396,6 +1398,7 @@ export const ptBR: TranslationResources = {
|
||||
rename: "Renomear workspace",
|
||||
pin: "Fixar no topo",
|
||||
unpin: "Desafixar",
|
||||
select: "Selecionar",
|
||||
archive: "Arquivar",
|
||||
archiveWorkspace: "Arquivar workspace",
|
||||
hideFromSidebar: "Ocultar da barra lateral",
|
||||
@@ -1414,6 +1417,10 @@ export const ptBR: TranslationResources = {
|
||||
submit: "Renomear",
|
||||
invalidBranchName: "Nome de branch inválido",
|
||||
},
|
||||
selection: {
|
||||
count: "{{count}} selecionados",
|
||||
exit: "Sair da seleção",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "Caminho do workspace indisponível",
|
||||
pathCopied: "Caminho copiado",
|
||||
@@ -1421,7 +1428,9 @@ export const ptBR: TranslationResources = {
|
||||
hostDisconnected: "Host não está conectado",
|
||||
hideFailed: "Falha ao ocultar workspace",
|
||||
archiveFailed: "Falha ao arquivar workspace",
|
||||
archiveMultipleFailed: "Falha ao arquivar {{count}} workspaces",
|
||||
archived: "Workspace arquivado",
|
||||
archivedCount: "{{count}} workspaces arquivados",
|
||||
undoArchive: "Desfazer",
|
||||
undoArchiveFailed: "Não foi possível desfazer o arquivamento",
|
||||
},
|
||||
@@ -1847,6 +1856,9 @@ export const ptBR: TranslationResources = {
|
||||
editProfilesLabel: "Editar perfis de agente",
|
||||
createProfile: "Criar perfil",
|
||||
createProfileFromModel: "Criar perfil a partir deste modelo",
|
||||
profileSaved: 'Salvo "{{name}}"',
|
||||
undo: "Desfazer",
|
||||
undoProfileSave: "Desfazer salvamento do perfil",
|
||||
editProfileLabel: "Editar {{name}}",
|
||||
editProfilesCount: "Editar perfis ({{count}})",
|
||||
modelCount: "{{count}} modelo",
|
||||
@@ -2429,6 +2441,7 @@ export const ptBR: TranslationResources = {
|
||||
projects: "Projetos",
|
||||
connections: "Conexões",
|
||||
agents: "Agentes",
|
||||
agentProfiles: "Perfis de agente",
|
||||
metadata: "Metadados",
|
||||
voice: "Voz",
|
||||
workspaces: "Workspaces",
|
||||
@@ -3065,6 +3078,31 @@ export const ptBR: TranslationResources = {
|
||||
removeConfirmMessage: 'Remover "{{name}}"?',
|
||||
moveUp: "Mover para cima",
|
||||
moveDown: "Mover para baixo",
|
||||
searchPlaceholder: "Buscar perfis",
|
||||
clearSearch: "Limpar busca",
|
||||
noSearchMatches: 'Nenhum perfil corresponde a "{{query}}"',
|
||||
noRoutingNote: "Sem nota",
|
||||
duplicate: "Duplicar",
|
||||
copyName: "{{name}} (cópia)",
|
||||
moveToTop: "Mover para o topo",
|
||||
profileActions: "Ações para {{name}}",
|
||||
reorderProfile: "Reordenar {{name}}",
|
||||
previousProfile: "Perfil anterior",
|
||||
nextProfile: "Próximo perfil",
|
||||
chooseModelPlaceholder: "Selecionar um modelo",
|
||||
searchModelsPlaceholder: "Buscar modelos",
|
||||
chooseModelSubtitle: "Selecionar um modelo",
|
||||
customizeSettings: "Personalizar configurações",
|
||||
addRoutingNoteShort: "Adicionar uma nota",
|
||||
providerOptionsLabel: "Opções de {{provider}}",
|
||||
discardTitle: "Descartar alterações?",
|
||||
discardMessage: "Você tem alterações não salvas neste perfil.",
|
||||
discardConfirm: "Descartar",
|
||||
columns: {
|
||||
profile: "Perfil",
|
||||
runtime: "Modelo e execução",
|
||||
whenToUse: "Quando usar",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -979,6 +979,8 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: "Архивировать «{{workspaceName}}»?",
|
||||
bulkTitle: "Архивировать рабочие пространства ({{count}})?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}: {{reason}}",
|
||||
confirm: "Архивировать",
|
||||
cancel: "Отмена",
|
||||
uncommittedChanges: "Незафиксированные изменения",
|
||||
@@ -1389,6 +1391,7 @@ export const ru: TranslationResources = {
|
||||
rename: "Переименовать рабочее пространство",
|
||||
pin: "Закрепить вверху",
|
||||
unpin: "Открепить",
|
||||
select: "Выбрать",
|
||||
archive: "Архивировать",
|
||||
archiveWorkspace: "Архивировать рабочее пространство",
|
||||
hideFromSidebar: "Скрыть на боковой панели",
|
||||
@@ -1407,6 +1410,10 @@ export const ru: TranslationResources = {
|
||||
submit: "Переименовать",
|
||||
invalidBranchName: "Недопустимое имя ветки",
|
||||
},
|
||||
selection: {
|
||||
count: "Выбрано: {{count}}",
|
||||
exit: "Выйти из выбора",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "Путь к рабочему пространству недоступен",
|
||||
pathCopied: "Путь скопирован",
|
||||
@@ -1414,7 +1421,9 @@ export const ru: TranslationResources = {
|
||||
hostDisconnected: "Хост не подключён",
|
||||
hideFailed: "Не удалось скрыть рабочее пространство",
|
||||
archiveFailed: "Не удалось архивировать рабочее пространство",
|
||||
archiveMultipleFailed: "Не удалось архивировать рабочие пространства ({{count}})",
|
||||
archived: "Рабочее пространство архивировано",
|
||||
archivedCount: "Архивировано рабочих пространств: {{count}}",
|
||||
undoArchive: "Отменить",
|
||||
undoArchiveFailed: "Не удалось отменить архивацию",
|
||||
},
|
||||
@@ -1847,6 +1856,9 @@ export const ru: TranslationResources = {
|
||||
editProfilesLabel: "Изменить профили агентов",
|
||||
createProfile: "Создать профиль",
|
||||
createProfileFromModel: "Создать профиль из этой модели",
|
||||
profileSaved: "Сохранено: «{{name}}»",
|
||||
undo: "Отменить",
|
||||
undoProfileSave: "Отменить сохранение профиля",
|
||||
editProfileLabel: "Изменить {{name}}",
|
||||
editProfilesCount: "Изменить профили ({{count}})",
|
||||
modelCount: "{{count}} модель",
|
||||
@@ -2431,6 +2443,7 @@ export const ru: TranslationResources = {
|
||||
projects: "Проекты",
|
||||
connections: "Подключения",
|
||||
agents: "Агенты",
|
||||
agentProfiles: "Профили агентов",
|
||||
metadata: "Метаданные",
|
||||
voice: "Голос",
|
||||
workspaces: "Рабочие пространства",
|
||||
@@ -3076,6 +3089,31 @@ export const ru: TranslationResources = {
|
||||
removeConfirmMessage: "Удалить «{{name}}»?",
|
||||
moveUp: "Переместить вверх",
|
||||
moveDown: "Переместить вниз",
|
||||
searchPlaceholder: "Поиск профилей",
|
||||
clearSearch: "Очистить поиск",
|
||||
noSearchMatches: "Нет профилей по запросу «{{query}}»",
|
||||
noRoutingNote: "Без заметки",
|
||||
duplicate: "Дублировать",
|
||||
copyName: "{{name}} (копия)",
|
||||
moveToTop: "В начало списка",
|
||||
profileActions: "Действия для {{name}}",
|
||||
reorderProfile: "Изменить порядок {{name}}",
|
||||
previousProfile: "Предыдущий профиль",
|
||||
nextProfile: "Следующий профиль",
|
||||
chooseModelPlaceholder: "Выберите модель",
|
||||
searchModelsPlaceholder: "Поиск моделей",
|
||||
chooseModelSubtitle: "Выберите модель",
|
||||
customizeSettings: "Настроить параметры",
|
||||
addRoutingNoteShort: "Добавить заметку",
|
||||
providerOptionsLabel: "Параметры {{provider}}",
|
||||
discardTitle: "Отменить изменения?",
|
||||
discardMessage: "В этом профиле есть несохранённые изменения.",
|
||||
discardConfirm: "Отменить",
|
||||
columns: {
|
||||
profile: "Профиль",
|
||||
runtime: "Модель и запуск",
|
||||
whenToUse: "Когда использовать",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -952,6 +952,8 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
archiveWarning: {
|
||||
title: "归档「{{workspaceName}}」?",
|
||||
bulkTitle: "归档 {{count}} 个工作区?",
|
||||
bulkWorkspaceReason: "{{workspaceName}}:{{reason}}",
|
||||
confirm: "归档",
|
||||
cancel: "取消",
|
||||
uncommittedChanges: "未 commit 的变更",
|
||||
@@ -1359,6 +1361,7 @@ export const zhCN: TranslationResources = {
|
||||
rename: "重命名 workspace",
|
||||
pin: "置顶",
|
||||
unpin: "取消置顶",
|
||||
select: "选择",
|
||||
archive: "归档",
|
||||
archiveWorkspace: "归档工作区",
|
||||
hideFromSidebar: "从侧边栏隐藏",
|
||||
@@ -1376,6 +1379,10 @@ export const zhCN: TranslationResources = {
|
||||
submit: "重命名",
|
||||
invalidBranchName: "无效的分支名称",
|
||||
},
|
||||
selection: {
|
||||
count: "已选 {{count}} 项",
|
||||
exit: "退出选择",
|
||||
},
|
||||
toasts: {
|
||||
workspacePathUnavailable: "Workspace 路径不可用",
|
||||
pathCopied: "路径已复制",
|
||||
@@ -1383,7 +1390,9 @@ export const zhCN: TranslationResources = {
|
||||
hostDisconnected: "Host 未连接",
|
||||
hideFailed: "隐藏 workspace 失败",
|
||||
archiveFailed: "归档工作区失败",
|
||||
archiveMultipleFailed: "归档 {{count}} 个工作区失败",
|
||||
archived: "工作区已归档",
|
||||
archivedCount: "已归档 {{count}} 个工作区",
|
||||
undoArchive: "撤销",
|
||||
undoArchiveFailed: "无法撤销归档",
|
||||
},
|
||||
@@ -1796,6 +1805,9 @@ export const zhCN: TranslationResources = {
|
||||
editProfilesLabel: "编辑智能体配置文件",
|
||||
createProfile: "创建配置文件",
|
||||
createProfileFromModel: "从此模型创建配置文件",
|
||||
profileSaved: "已保存“{{name}}”",
|
||||
undo: "撤销",
|
||||
undoProfileSave: "撤销保存配置文件",
|
||||
editProfileLabel: "编辑 {{name}}",
|
||||
editProfilesCount: "编辑配置文件 ({{count}})",
|
||||
modelCount: "{{count}} 个模型",
|
||||
@@ -2371,6 +2383,7 @@ export const zhCN: TranslationResources = {
|
||||
projects: "项目",
|
||||
connections: "连接",
|
||||
agents: "Agents",
|
||||
agentProfiles: "智能体配置文件",
|
||||
metadata: "元数据",
|
||||
voice: "语音",
|
||||
workspaces: "Workspaces",
|
||||
@@ -2991,6 +3004,31 @@ export const zhCN: TranslationResources = {
|
||||
removeConfirmMessage: "移除「{{name}}」?",
|
||||
moveUp: "上移",
|
||||
moveDown: "下移",
|
||||
searchPlaceholder: "搜索配置文件",
|
||||
clearSearch: "清除搜索",
|
||||
noSearchMatches: "没有匹配“{{query}}”的配置文件",
|
||||
noRoutingNote: "无说明",
|
||||
duplicate: "复制",
|
||||
copyName: "{{name}}(副本)",
|
||||
moveToTop: "移至顶部",
|
||||
profileActions: "{{name}} 的操作",
|
||||
reorderProfile: "调整 {{name}} 顺序",
|
||||
previousProfile: "上一个配置文件",
|
||||
nextProfile: "下一个配置文件",
|
||||
chooseModelPlaceholder: "选择模型",
|
||||
searchModelsPlaceholder: "搜索模型",
|
||||
chooseModelSubtitle: "选择模型",
|
||||
customizeSettings: "自定义设置",
|
||||
addRoutingNoteShort: "添加说明",
|
||||
providerOptionsLabel: "{{provider}} 选项",
|
||||
discardTitle: "放弃更改?",
|
||||
discardMessage: "此配置文件有未保存的更改。",
|
||||
discardConfirm: "放弃",
|
||||
columns: {
|
||||
profile: "配置文件",
|
||||
runtime: "模型与运行时",
|
||||
whenToUse: "适用场景",
|
||||
},
|
||||
},
|
||||
daemon: {
|
||||
rename: {
|
||||
|
||||
@@ -14,3 +14,4 @@ export type { HardwareKeyboardEvent } from "./internal/sources/hardware";
|
||||
export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions";
|
||||
export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser";
|
||||
export { useHardwareKeyboardPresent } from "./availability";
|
||||
export { isShiftKeyDown } from "./internal/shift-modifier";
|
||||
|
||||
@@ -9,6 +9,10 @@ export interface OverlayRegistration {
|
||||
*/
|
||||
keys: readonly string[];
|
||||
onKeyDown(event: KeyboardInputEvent): boolean;
|
||||
/**
|
||||
* Where focus goes when the overlay closes: an element, or any handle with `focus()`. Defaults
|
||||
* to whatever had focus when the overlay opened.
|
||||
*/
|
||||
restoreFocusRef?: RefObject<unknown>;
|
||||
manageFocus?: boolean;
|
||||
}
|
||||
|
||||
@@ -3,12 +3,29 @@ import { overlays, type OverlayEntry, type KeyboardInputEvent } from "./overlays
|
||||
import type { OverlayRegistration } from "./overlay-contract";
|
||||
type WebOverlayKeyHandler = (event: KeyboardInputEvent) => boolean;
|
||||
|
||||
/** A DOM element, or a component handle that knows how to focus itself (such as a text input). */
|
||||
interface FocusTarget {
|
||||
focus(): void;
|
||||
}
|
||||
|
||||
function isFocusTarget(value: unknown): value is FocusTarget {
|
||||
return (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
typeof (value as Partial<FocusTarget>).focus === "function"
|
||||
);
|
||||
}
|
||||
|
||||
function canRestoreFocusTo(target: FocusTarget): boolean {
|
||||
return !(target instanceof HTMLElement) || document.contains(target);
|
||||
}
|
||||
|
||||
interface WebOverlayEntry {
|
||||
getLayer: () => number;
|
||||
getKeys: () => readonly string[];
|
||||
getScope: () => HTMLElement | null;
|
||||
getKeyHandler: () => WebOverlayKeyHandler;
|
||||
restoreFocus: HTMLElement | null;
|
||||
restoreFocus: FocusTarget | null;
|
||||
manageFocus: boolean;
|
||||
}
|
||||
|
||||
@@ -156,7 +173,7 @@ function addWebOverlay(entry: WebOverlayEntry): (options?: RemoveWebOverlayOptio
|
||||
entry.manageFocus &&
|
||||
options?.restoreFocus !== false &&
|
||||
entry.restoreFocus &&
|
||||
document.contains(entry.restoreFocus)
|
||||
canRestoreFocusTo(entry.restoreFocus)
|
||||
) {
|
||||
entry.restoreFocus.focus();
|
||||
}
|
||||
@@ -181,7 +198,7 @@ export function useOverlayRegistration({
|
||||
keysRef.current = keys;
|
||||
const layerRef = useRef(layer);
|
||||
const keyHandlerRef = useRef(onKeyDown);
|
||||
const capturedRestoreFocusRef = useRef<HTMLElement | null>(null);
|
||||
const capturedRestoreFocusRef = useRef<FocusTarget | null>(null);
|
||||
const removeEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
|
||||
const detachedRemoveEntryRef = useRef<((options?: RemoveWebOverlayOptions) => void) | null>(null);
|
||||
const registeredRef = useRef(false);
|
||||
@@ -193,7 +210,7 @@ export function useOverlayRegistration({
|
||||
keyHandlerRef.current = onKeyDown;
|
||||
if (active && !wasActiveRef.current && typeof document !== "undefined") {
|
||||
const requestedRestoreTarget = preferredRestoreFocusRef?.current;
|
||||
if (requestedRestoreTarget instanceof HTMLElement) {
|
||||
if (isFocusTarget(requestedRestoreTarget)) {
|
||||
capturedRestoreFocusRef.current = requestedRestoreTarget;
|
||||
} else {
|
||||
capturedRestoreFocusRef.current =
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
export interface ShiftModifierKeyEvent {
|
||||
key: string;
|
||||
code?: string;
|
||||
shiftKey: boolean;
|
||||
}
|
||||
|
||||
export interface ShiftModifierTracker {
|
||||
isDown(): boolean;
|
||||
handleKeyDown(event: ShiftModifierKeyEvent): void;
|
||||
handleKeyUp(event: ShiftModifierKeyEvent): void;
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks whether a physical Shift key is currently held across DOM and native
|
||||
* hardware keyboard streams so touch/pointer press handlers that omit
|
||||
* `shiftKey` (native GestureResponderEvent, touch-synthesized clicks) can still
|
||||
* observe Shift+tap and Shift+click.
|
||||
*/
|
||||
export function createShiftModifierTracker(): ShiftModifierTracker {
|
||||
const pressedCodes = new Set<string>();
|
||||
return {
|
||||
isDown: () => pressedCodes.size > 0,
|
||||
handleKeyDown(event) {
|
||||
if (event.key === "Shift") {
|
||||
pressedCodes.add(event.code || "Shift");
|
||||
} else if (!event.shiftKey && pressedCodes.size > 0) {
|
||||
pressedCodes.clear();
|
||||
}
|
||||
},
|
||||
handleKeyUp(event) {
|
||||
if (event.key === "Shift") {
|
||||
pressedCodes.delete(event.code || "Shift");
|
||||
if (!event.shiftKey) {
|
||||
pressedCodes.clear();
|
||||
}
|
||||
} else if (!event.shiftKey && pressedCodes.size > 0) {
|
||||
pressedCodes.clear();
|
||||
}
|
||||
},
|
||||
reset() {
|
||||
pressedCodes.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const shiftModifier = createShiftModifierTracker();
|
||||
|
||||
export function isShiftKeyDown(): boolean {
|
||||
return shiftModifier.isDown();
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AppState } from "react-native";
|
||||
import type { KeyboardPolicyInput, KeyboardSourceHandlers } from "./contract";
|
||||
import {
|
||||
setHardwareKeyboardClaimedShortcuts,
|
||||
@@ -7,6 +8,14 @@ import {
|
||||
import { createHardwareKeyboardSource } from "./native";
|
||||
const hardwareKeyboard = createHardwareKeyboardSource({
|
||||
subscribe: subscribeHardwareKeyboard,
|
||||
subscribeBlur: (onBlur) => {
|
||||
const subscription = AppState.addEventListener("change", (nextState) => {
|
||||
if (nextState !== "active") {
|
||||
onBlur();
|
||||
}
|
||||
});
|
||||
return () => subscription.remove();
|
||||
},
|
||||
setOverlayKeys: setHardwareKeyboardOverlayKeys,
|
||||
setClaimedShortcuts: setHardwareKeyboardClaimedShortcuts,
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
import type { ClaimedShortcut, HardwareKeyboardEvent } from "./hardware";
|
||||
interface HardwareKeySource {
|
||||
subscribe(handler: (event: HardwareKeyboardEvent) => void): () => void;
|
||||
subscribeBlur?(handler: () => void): () => void;
|
||||
setOverlayKeys(keys: readonly string[]): void;
|
||||
setClaimedShortcuts(shortcuts: readonly ClaimedShortcut[]): void;
|
||||
}
|
||||
@@ -78,7 +79,9 @@ export function createHardwareKeyboardSource(source: HardwareKeySource) {
|
||||
nativeKeyboardInput(event, focusSurfaces.resolve(handlers.commandCenterOpen())),
|
||||
);
|
||||
});
|
||||
const unsubscribeBlur = source.subscribeBlur?.(() => handlers.blur()) ?? (() => {});
|
||||
return () => {
|
||||
unsubscribeBlur();
|
||||
unsubscribeHardware();
|
||||
unsubscribeFocus();
|
||||
unsubscribeCommandCenter();
|
||||
|
||||
@@ -269,4 +269,80 @@ describe("hardware source adapter", () => {
|
||||
expect(claimed).toEqual([]);
|
||||
releaseFinal();
|
||||
});
|
||||
|
||||
it("forwards native blur events and unsubscribes on detach", async () => {
|
||||
const { createHardwareKeyboardSource } = await import("./internal/sources/native");
|
||||
const blurListeners = new Set<() => void>();
|
||||
let blurCalls = 0;
|
||||
const detach = createHardwareKeyboardSource({
|
||||
subscribe: () => () => {},
|
||||
subscribeBlur(listener) {
|
||||
blurListeners.add(listener);
|
||||
return () => {
|
||||
blurListeners.delete(listener);
|
||||
};
|
||||
},
|
||||
setOverlayKeys() {},
|
||||
setClaimedShortcuts() {},
|
||||
}).attach({
|
||||
keyDown() {},
|
||||
keyUp() {},
|
||||
blur() {
|
||||
blurCalls += 1;
|
||||
},
|
||||
commandCenterOpen: () => false,
|
||||
subscribeCommandCenter: () => () => {},
|
||||
});
|
||||
for (const listener of blurListeners) listener();
|
||||
expect(blurCalls).toBe(1);
|
||||
detach();
|
||||
expect(blurListeners.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shift modifier tracking", () => {
|
||||
it("tracks left/right Shift holds, self-heals on non-shifted keys, and resets on blur", async () => {
|
||||
const { createShiftModifierTracker } = await import("./internal/shift-modifier");
|
||||
const tracker = createShiftModifierTracker();
|
||||
expect(tracker.isDown()).toBe(false);
|
||||
|
||||
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(tracker.isDown()).toBe(true);
|
||||
|
||||
tracker.handleKeyDown({ key: "Shift", code: "ShiftRight", shiftKey: true });
|
||||
tracker.handleKeyUp({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(tracker.isDown()).toBe(true);
|
||||
|
||||
tracker.handleKeyUp({ key: "Shift", code: "ShiftRight", shiftKey: false });
|
||||
expect(tracker.isDown()).toBe(false);
|
||||
|
||||
// Self-heals if a Shift key-up was swallowed by the OS.
|
||||
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(tracker.isDown()).toBe(true);
|
||||
tracker.handleKeyDown({ key: "a", code: "KeyA", shiftKey: false });
|
||||
expect(tracker.isDown()).toBe(false);
|
||||
|
||||
// Clears on blur / backgrounding.
|
||||
tracker.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(tracker.isDown()).toBe(true);
|
||||
tracker.reset();
|
||||
expect(tracker.isDown()).toBe(false);
|
||||
});
|
||||
|
||||
it("exposes live hardware Shift state through isShiftKeyDown", async () => {
|
||||
const { shiftModifier } = await import("./internal/shift-modifier");
|
||||
const { isShiftKeyDown } = await import("./index");
|
||||
try {
|
||||
shiftModifier.reset();
|
||||
expect(isShiftKeyDown()).toBe(false);
|
||||
|
||||
shiftModifier.handleKeyDown({ key: "Shift", code: "ShiftLeft", shiftKey: true });
|
||||
expect(isShiftKeyDown()).toBe(true);
|
||||
|
||||
shiftModifier.handleKeyUp({ key: "Shift", code: "ShiftLeft", shiftKey: false });
|
||||
expect(isShiftKeyDown()).toBe(false);
|
||||
} finally {
|
||||
shiftModifier.reset();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { usesDesktopBindings } from "./internal/conventions";
|
||||
import { createKeyboardPipeline } from "./internal/pipeline";
|
||||
import { overlays } from "./internal/overlays";
|
||||
import { shiftModifier } from "./internal/shift-modifier";
|
||||
import { attachKeyboardSources, publishKeyboardPolicy } from "./internal/sources";
|
||||
import type { KeyboardSourceInput } from "./internal/sources/contract";
|
||||
import type { KeyboardInputEvent } from "./internal/overlays";
|
||||
@@ -249,19 +250,30 @@ export function useKeyboardShortcuts({
|
||||
[getContext, getBindings, isCapturing, dispatchMatch, beforeResolve, chordChanged],
|
||||
);
|
||||
|
||||
const handleKeyDown = useStableEvent((input: KeyboardSourceInput) => {
|
||||
shiftModifier.handleKeyDown(input.event);
|
||||
return pipeline.keyDown(input);
|
||||
});
|
||||
|
||||
const handleKeyUp = useStableEvent((event: KeyboardInputEvent) => {
|
||||
shiftModifier.handleKeyUp(event);
|
||||
const key = event.key ?? "";
|
||||
if (key === badgeModifierKey) {
|
||||
setBadgeModifierDown(false);
|
||||
}
|
||||
});
|
||||
|
||||
const handleBlur = useStableEvent(() => {
|
||||
shiftModifier.reset();
|
||||
resetModifiers();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const detach = attachKeyboardSources({
|
||||
keyDown: pipeline.keyDown,
|
||||
keyDown: handleKeyDown,
|
||||
keyUp: handleKeyUp,
|
||||
blur: resetModifiers,
|
||||
blur: handleBlur,
|
||||
commandCenterOpen: () => useKeyboardShortcutsStore.getState().commandCenterOpen,
|
||||
subscribeCommandCenter: (listener) =>
|
||||
useKeyboardShortcutsStore.subscribe((state, previous) => {
|
||||
@@ -270,7 +282,8 @@ export function useKeyboardShortcuts({
|
||||
});
|
||||
return () => {
|
||||
detach();
|
||||
shiftModifier.reset();
|
||||
pipeline.dispose();
|
||||
};
|
||||
}, [enabled, pipeline, handleKeyUp, resetModifiers]);
|
||||
}, [enabled, pipeline, handleKeyDown, handleKeyUp, handleBlur]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
export interface RouteLeaveGuard {
|
||||
isDirty: () => boolean;
|
||||
confirmDiscard: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the web browser history (`popstate`) guard before Expo Router mounts
|
||||
* its own `popstate` listener. No-op on native, where React Navigation's
|
||||
* `beforeRemove` owns swipe-back and hardware Back interception.
|
||||
*/
|
||||
export function installRouteLeavePopStateGuard(): void {
|
||||
// Native platforms handle back navigation through React Navigation's beforeRemove event.
|
||||
}
|
||||
|
||||
/** Registers the active screen's leave guard for browser Back/Forward interception. */
|
||||
export function registerRouteLeaveGuard(_guard: RouteLeaveGuard | null): () => void {
|
||||
return () => {};
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createWebPopStateGuard,
|
||||
type PopStateStorageLike,
|
||||
type PopStateWindowLike,
|
||||
} from "./index.web";
|
||||
|
||||
interface FakeHistoryEntry {
|
||||
state: unknown;
|
||||
path: string;
|
||||
}
|
||||
|
||||
function createMemoryStorage(): PopStateStorageLike {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
store.set(key, value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createFakeWindow(
|
||||
initialEntries: FakeHistoryEntry[],
|
||||
options?: { index?: number; sessionStorage?: PopStateStorageLike },
|
||||
) {
|
||||
let entries: FakeHistoryEntry[] = [...initialEntries];
|
||||
let index = options?.index ?? entries.length - 1;
|
||||
const listeners: Array<(event: PopStateEvent) => void> = [];
|
||||
|
||||
const current = () => entries[index] ?? { state: null, path: "/" };
|
||||
|
||||
const dispatchPopState = (state: unknown) => {
|
||||
let stopped = false;
|
||||
const event = {
|
||||
state,
|
||||
stopImmediatePropagation() {
|
||||
stopped = true;
|
||||
},
|
||||
} as unknown as PopStateEvent;
|
||||
for (const listener of listeners.slice()) {
|
||||
if (stopped) {
|
||||
break;
|
||||
}
|
||||
listener(event);
|
||||
}
|
||||
return { stopped };
|
||||
};
|
||||
|
||||
const win: PopStateWindowLike = {
|
||||
...(options?.sessionStorage ? { sessionStorage: options.sessionStorage } : {}),
|
||||
history: {
|
||||
get state() {
|
||||
return current().state;
|
||||
},
|
||||
pushState(state, _unused, url) {
|
||||
const path = typeof url === "string" ? url : String(url ?? "/");
|
||||
entries = entries.slice(0, index + 1);
|
||||
entries.push({ state, path });
|
||||
index = entries.length - 1;
|
||||
},
|
||||
replaceState(state, _unused, url) {
|
||||
const path = typeof url === "string" ? url : String(url ?? "/");
|
||||
entries[index] = { state, path };
|
||||
},
|
||||
go(delta = 0) {
|
||||
const nextIndex = index + delta;
|
||||
if (nextIndex < 0 || nextIndex >= entries.length || nextIndex === index) {
|
||||
return;
|
||||
}
|
||||
index = nextIndex;
|
||||
dispatchPopState(current().state);
|
||||
},
|
||||
},
|
||||
addEventListener(_type, listener) {
|
||||
listeners.push(listener);
|
||||
},
|
||||
removeEventListener(_type, listener) {
|
||||
const idx = listeners.indexOf(listener);
|
||||
if (idx >= 0) {
|
||||
listeners.splice(idx, 1);
|
||||
}
|
||||
},
|
||||
dispatchEvent(event) {
|
||||
const popEvent = event as PopStateEvent;
|
||||
dispatchPopState(popEvent.state);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
win,
|
||||
getPath: () => current().path,
|
||||
getEntries: () => entries.map((entry) => entry.path),
|
||||
getIndex: () => index,
|
||||
simulateHistoryJump: (delta: number) => {
|
||||
const nextIndex = index + delta;
|
||||
index = Math.max(0, Math.min(entries.length - 1, nextIndex));
|
||||
return dispatchPopState(current().state);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("createWebPopStateGuard", () => {
|
||||
it("preserves intervening history entries when canceling a two-step Back jump", async () => {
|
||||
const fake = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }], {
|
||||
sessionStorage: createMemoryStorage(),
|
||||
});
|
||||
const guard = createWebPopStateGuard(fake.win);
|
||||
guard.install();
|
||||
|
||||
const routerSeenPaths: string[] = [];
|
||||
fake.win.addEventListener("popstate", () => {
|
||||
routerSeenPaths.push(fake.getPath());
|
||||
});
|
||||
|
||||
fake.win.history.pushState({ id: "id-1" }, "", "/settings");
|
||||
fake.win.history.pushState({ id: "id-2" }, "", "/settings/hosts/srv/agent-profiles");
|
||||
|
||||
let dirty = true;
|
||||
guard.register({
|
||||
isDirty: () => dirty,
|
||||
confirmDiscard: async () => false,
|
||||
});
|
||||
|
||||
// Jump straight from Agent profiles back two entries to Open project and cancel.
|
||||
const { stopped } = fake.simulateHistoryJump(-2);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(stopped).toBe(true);
|
||||
expect(routerSeenPaths).toEqual([]);
|
||||
expect(fake.getPath()).toBe("/settings/hosts/srv/agent-profiles");
|
||||
expect(fake.getEntries()).toEqual([
|
||||
"/open-project",
|
||||
"/settings",
|
||||
"/settings/hosts/srv/agent-profiles",
|
||||
]);
|
||||
expect(fake.getIndex()).toBe(2);
|
||||
|
||||
// After closing the editor, a normal one-step Back still reaches Settings.
|
||||
dirty = false;
|
||||
fake.simulateHistoryJump(-1);
|
||||
expect(fake.getPath()).toBe("/settings");
|
||||
expect(routerSeenPaths).toEqual(["/settings"]);
|
||||
});
|
||||
|
||||
it("restores the editor URL on a two-step Back jump after a reload (with sessionStorage)", async () => {
|
||||
const storage = createMemoryStorage();
|
||||
const beforeReload = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }], {
|
||||
sessionStorage: storage,
|
||||
});
|
||||
const firstGuard = createWebPopStateGuard(beforeReload.win);
|
||||
firstGuard.install();
|
||||
beforeReload.win.history.pushState({ id: "id-1" }, "", "/settings");
|
||||
beforeReload.win.history.pushState({ id: "id-2" }, "", "/settings/hosts/srv/agent-profiles");
|
||||
firstGuard.dispose();
|
||||
|
||||
// Simulate reload on Agent profiles with the same browser history and tab sessionStorage.
|
||||
const afterReload = createFakeWindow(
|
||||
[
|
||||
{ state: { id: "id-0" }, path: "/open-project" },
|
||||
{ state: { id: "id-1" }, path: "/settings" },
|
||||
{ state: { id: "id-2" }, path: "/settings/hosts/srv/agent-profiles" },
|
||||
],
|
||||
{ index: 2, sessionStorage: storage },
|
||||
);
|
||||
const guard = createWebPopStateGuard(afterReload.win);
|
||||
guard.install();
|
||||
guard.register({
|
||||
isDirty: () => true,
|
||||
confirmDiscard: async () => false,
|
||||
});
|
||||
|
||||
afterReload.simulateHistoryJump(-2);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(afterReload.getPath()).toBe("/settings/hosts/srv/agent-profiles");
|
||||
expect(afterReload.getIndex()).toBe(2);
|
||||
});
|
||||
|
||||
it("steps back to the exact editor entry after a reload even without sessionStorage", async () => {
|
||||
const afterReload = createFakeWindow(
|
||||
[
|
||||
{ state: { id: "id-0" }, path: "/open-project" },
|
||||
{ state: { id: "id-1" }, path: "/settings" },
|
||||
{ state: { id: "id-2" }, path: "/settings/hosts/srv/agent-profiles" },
|
||||
],
|
||||
{ index: 2 },
|
||||
);
|
||||
const guard = createWebPopStateGuard(afterReload.win);
|
||||
guard.install();
|
||||
|
||||
const routerSeenPaths: string[] = [];
|
||||
afterReload.win.addEventListener("popstate", () => {
|
||||
routerSeenPaths.push(afterReload.getPath());
|
||||
});
|
||||
|
||||
guard.register({
|
||||
isDirty: () => true,
|
||||
confirmDiscard: async () => false,
|
||||
});
|
||||
|
||||
afterReload.simulateHistoryJump(-2);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(routerSeenPaths).toEqual([]);
|
||||
expect(afterReload.getPath()).toBe("/settings/hosts/srv/agent-profiles");
|
||||
expect(afterReload.getIndex()).toBe(2);
|
||||
});
|
||||
|
||||
it("reaches the exact two-step destination when confirming a multi-step Back jump", async () => {
|
||||
const fake = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }], {
|
||||
sessionStorage: createMemoryStorage(),
|
||||
});
|
||||
const guard = createWebPopStateGuard(fake.win);
|
||||
guard.install();
|
||||
|
||||
const routerSeenPaths: string[] = [];
|
||||
fake.win.addEventListener("popstate", () => {
|
||||
routerSeenPaths.push(fake.getPath());
|
||||
});
|
||||
|
||||
fake.win.history.pushState({ id: "id-1" }, "", "/settings");
|
||||
fake.win.history.pushState({ id: "id-2" }, "", "/settings/hosts/srv/agent-profiles");
|
||||
|
||||
let dirty = true;
|
||||
guard.register({
|
||||
isDirty: () => dirty,
|
||||
confirmDiscard: async () => {
|
||||
dirty = false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
fake.simulateHistoryJump(-2);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(routerSeenPaths).toEqual(["/open-project"]);
|
||||
expect(fake.getPath()).toBe("/open-project");
|
||||
expect(fake.getIndex()).toBe(0);
|
||||
});
|
||||
|
||||
it("passes browser Back straight through when the guard is not dirty", () => {
|
||||
const fake = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }]);
|
||||
const guard = createWebPopStateGuard(fake.win);
|
||||
guard.install();
|
||||
|
||||
let routerSawPopState = 0;
|
||||
fake.win.addEventListener("popstate", () => {
|
||||
routerSawPopState += 1;
|
||||
});
|
||||
|
||||
fake.win.history.pushState({ id: "id-1" }, "", "/settings/hosts/srv/agent-profiles");
|
||||
|
||||
guard.register({
|
||||
isDirty: () => false,
|
||||
confirmDiscard: async () => {
|
||||
throw new Error("should not prompt when clean");
|
||||
},
|
||||
});
|
||||
|
||||
const { stopped } = fake.simulateHistoryJump(-1);
|
||||
|
||||
expect(stopped).toBe(false);
|
||||
expect(routerSawPopState).toBe(1);
|
||||
expect(fake.getPath()).toBe("/open-project");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,307 @@
|
||||
import type { RouteLeaveGuard } from "./index";
|
||||
|
||||
export type { RouteLeaveGuard } from "./index";
|
||||
|
||||
const HISTORY_STORAGE_KEY = "@paseo:route-leave-history:v1";
|
||||
const MAX_REVERT_STEPS = 20;
|
||||
const REVERT_TIMEOUT_MS = 400;
|
||||
|
||||
export interface PopStateStorageLike {
|
||||
getItem(key: string): string | null;
|
||||
setItem(key: string, value: string): void;
|
||||
}
|
||||
|
||||
export interface PopStateWindowLike {
|
||||
history: {
|
||||
readonly state: unknown;
|
||||
pushState(data: unknown, unused: string, url?: string | URL | null): void;
|
||||
replaceState(data: unknown, unused: string, url?: string | URL | null): void;
|
||||
go(delta?: number): void;
|
||||
};
|
||||
sessionStorage?: PopStateStorageLike;
|
||||
addEventListener(type: "popstate", listener: (event: PopStateEvent) => void): void;
|
||||
removeEventListener(type: "popstate", listener: (event: PopStateEvent) => void): void;
|
||||
dispatchEvent(event: Event): boolean;
|
||||
}
|
||||
|
||||
export interface WebPopStateGuardController {
|
||||
install(): void;
|
||||
register(guard: RouteLeaveGuard | null): () => void;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
function readHistoryStateId(state: unknown): string | null {
|
||||
if (typeof state === "object" && state !== null && "id" in state) {
|
||||
const id = (state as { id?: unknown }).id;
|
||||
return typeof id === "string" && id.length > 0 ? id : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function createPopStateEvent(state: unknown): PopStateEvent {
|
||||
if (typeof PopStateEvent === "function") {
|
||||
return new PopStateEvent("popstate", { state });
|
||||
}
|
||||
const event = new Event("popstate") as PopStateEvent;
|
||||
Object.defineProperty(event, "state", { value: state });
|
||||
return event;
|
||||
}
|
||||
|
||||
function loadStoredEntryIds(storage: PopStateStorageLike | undefined): Array<string | null> | null {
|
||||
if (!storage) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const raw = storage.getItem(HISTORY_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (!Array.isArray(parsed)) {
|
||||
return null;
|
||||
}
|
||||
if (!parsed.every((item) => item === null || typeof item === "string")) {
|
||||
return null;
|
||||
}
|
||||
return parsed as Array<string | null>;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function persistEntryIds(
|
||||
storage: PopStateStorageLike | undefined,
|
||||
entryIds: readonly (string | null)[],
|
||||
): void {
|
||||
if (!storage) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
storage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(entryIds));
|
||||
} catch {
|
||||
// Ignore storage quota or private-mode restrictions; fallback stepping still works.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Intercepts browser Back/Forward (`popstate`) before Expo Router's
|
||||
* `createMemoryHistory` listener runs.
|
||||
*
|
||||
* Tracks the ordered history entry IDs written by Expo Router (persisted in
|
||||
* `sessionStorage` so reloads keep the tab's full index). Canceling any
|
||||
* traversal reverts via `history.go(delta)` without calling `pushState` or
|
||||
* truncating intervening entries — and verifies it landed back on the saved
|
||||
* entry ID (stepping forward if pre-reload history was unknown). Confirming
|
||||
* replays `popstate` at the browser's exact selected destination.
|
||||
*/
|
||||
export function createWebPopStateGuard(win: PopStateWindowLike): WebPopStateGuardController {
|
||||
let installed = false;
|
||||
let activeGuard: RouteLeaveGuard | null = null;
|
||||
let confirmInFlight = false;
|
||||
let isReverting = false;
|
||||
let revertingTargetId: string | null = null;
|
||||
let revertStepDirection: 1 | -1 = 1;
|
||||
let revertStepsRemaining = 0;
|
||||
let isReplaying = false;
|
||||
let revertResetTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let entryIds: Array<string | null> = [];
|
||||
let currentIdx = 0;
|
||||
|
||||
let origPushState: PopStateWindowLike["history"]["pushState"] | null = null;
|
||||
let origReplaceState: PopStateWindowLike["history"]["replaceState"] | null = null;
|
||||
|
||||
const clearRevertState = () => {
|
||||
isReverting = false;
|
||||
revertingTargetId = null;
|
||||
revertStepsRemaining = 0;
|
||||
if (revertResetTimer !== null) {
|
||||
clearTimeout(revertResetTimer);
|
||||
revertResetTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const armRevertTimer = () => {
|
||||
if (revertResetTimer !== null) {
|
||||
clearTimeout(revertResetTimer);
|
||||
}
|
||||
revertResetTimer = setTimeout(() => {
|
||||
clearRevertState();
|
||||
}, REVERT_TIMEOUT_MS);
|
||||
};
|
||||
|
||||
const revertToSavedEntry = (savedId: string | null, returnDelta: number) => {
|
||||
isReverting = true;
|
||||
revertingTargetId = savedId;
|
||||
revertStepDirection = returnDelta >= 0 ? 1 : -1;
|
||||
revertStepsRemaining = MAX_REVERT_STEPS;
|
||||
armRevertTimer();
|
||||
win.history.go(returnDelta);
|
||||
};
|
||||
|
||||
const resolveTargetIndex = (state: unknown): number => {
|
||||
const targetId = readHistoryStateId(state);
|
||||
if (!targetId) {
|
||||
return -1;
|
||||
}
|
||||
return entryIds.indexOf(targetId);
|
||||
};
|
||||
|
||||
const handleRevertPopState = (event: PopStateEvent) => {
|
||||
event.stopImmediatePropagation();
|
||||
const landedId = readHistoryStateId(event.state);
|
||||
if (revertingTargetId !== null && landedId !== revertingTargetId && revertStepsRemaining > 0) {
|
||||
revertStepsRemaining -= 1;
|
||||
armRevertTimer();
|
||||
win.history.go(revertStepDirection);
|
||||
return;
|
||||
}
|
||||
const landedIdx = resolveTargetIndex(event.state);
|
||||
if (landedIdx >= 0) {
|
||||
currentIdx = landedIdx;
|
||||
}
|
||||
clearRevertState();
|
||||
};
|
||||
|
||||
const handlePopState = (event: PopStateEvent) => {
|
||||
if (isReverting) {
|
||||
handleRevertPopState(event);
|
||||
return;
|
||||
}
|
||||
|
||||
const targetIdx = resolveTargetIndex(event.state);
|
||||
|
||||
if (isReplaying) {
|
||||
isReplaying = false;
|
||||
if (targetIdx >= 0) {
|
||||
currentIdx = targetIdx;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const guard = activeGuard;
|
||||
if (!guard?.isDirty()) {
|
||||
if (targetIdx >= 0) {
|
||||
currentIdx = targetIdx;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
event.stopImmediatePropagation();
|
||||
const savedId = entryIds[currentIdx] ?? null;
|
||||
const returnDelta = targetIdx >= 0 ? currentIdx - targetIdx : 1;
|
||||
|
||||
if (confirmInFlight) {
|
||||
if (returnDelta !== 0) {
|
||||
revertToSavedEntry(savedId, returnDelta);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
confirmInFlight = true;
|
||||
const confirmAndResolve = async () => {
|
||||
try {
|
||||
const confirmed = await guard.confirmDiscard();
|
||||
if (confirmed) {
|
||||
isReplaying = true;
|
||||
win.dispatchEvent(createPopStateEvent(event.state));
|
||||
} else if (returnDelta !== 0) {
|
||||
revertToSavedEntry(savedId, returnDelta);
|
||||
}
|
||||
} finally {
|
||||
confirmInFlight = false;
|
||||
}
|
||||
};
|
||||
void confirmAndResolve();
|
||||
};
|
||||
|
||||
return {
|
||||
install() {
|
||||
if (installed) {
|
||||
return;
|
||||
}
|
||||
installed = true;
|
||||
const initialId = readHistoryStateId(win.history.state);
|
||||
const stored = loadStoredEntryIds(win.sessionStorage);
|
||||
const storedIdx = stored && initialId ? stored.indexOf(initialId) : -1;
|
||||
if (stored && storedIdx >= 0) {
|
||||
entryIds = stored;
|
||||
currentIdx = storedIdx;
|
||||
} else {
|
||||
entryIds = [initialId];
|
||||
currentIdx = 0;
|
||||
persistEntryIds(win.sessionStorage, entryIds);
|
||||
}
|
||||
|
||||
origPushState = win.history.pushState;
|
||||
origReplaceState = win.history.replaceState;
|
||||
|
||||
win.history.pushState = (data, unused, url) => {
|
||||
origPushState?.call(win.history, data, unused, url);
|
||||
entryIds = entryIds.slice(0, currentIdx + 1);
|
||||
entryIds.push(readHistoryStateId(data));
|
||||
currentIdx = entryIds.length - 1;
|
||||
persistEntryIds(win.sessionStorage, entryIds);
|
||||
};
|
||||
|
||||
win.history.replaceState = (data, unused, url) => {
|
||||
origReplaceState?.call(win.history, data, unused, url);
|
||||
entryIds[currentIdx] = readHistoryStateId(data);
|
||||
persistEntryIds(win.sessionStorage, entryIds);
|
||||
};
|
||||
|
||||
win.addEventListener("popstate", handlePopState);
|
||||
},
|
||||
register(guard) {
|
||||
activeGuard = guard;
|
||||
return () => {
|
||||
if (activeGuard === guard) {
|
||||
activeGuard = null;
|
||||
}
|
||||
};
|
||||
},
|
||||
dispose() {
|
||||
if (!installed) {
|
||||
return;
|
||||
}
|
||||
installed = false;
|
||||
activeGuard = null;
|
||||
confirmInFlight = false;
|
||||
isReplaying = false;
|
||||
clearRevertState();
|
||||
win.removeEventListener("popstate", handlePopState);
|
||||
if (origPushState) {
|
||||
win.history.pushState = origPushState;
|
||||
origPushState = null;
|
||||
}
|
||||
if (origReplaceState) {
|
||||
win.history.replaceState = origReplaceState;
|
||||
origReplaceState = null;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let sharedController: WebPopStateGuardController | null = null;
|
||||
|
||||
function getSharedController(): WebPopStateGuardController | null {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
if (!sharedController) {
|
||||
sharedController = createWebPopStateGuard(window);
|
||||
}
|
||||
return sharedController;
|
||||
}
|
||||
|
||||
export function installRouteLeavePopStateGuard(): void {
|
||||
getSharedController()?.install();
|
||||
}
|
||||
|
||||
export function registerRouteLeaveGuard(guard: RouteLeaveGuard | null): () => void {
|
||||
const controller = getSharedController();
|
||||
if (!controller) {
|
||||
return () => {};
|
||||
}
|
||||
controller.install();
|
||||
return controller.register(guard);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
|
||||
import { CompactHeader } from "@/components/headers/compact-header";
|
||||
import { ScreenHeader } from "@/components/headers/screen-header";
|
||||
import { ScreenTitle } from "@/components/headers/screen-title";
|
||||
import { SidebarMenuToggle } from "@/components/headers/sidebar-menu-toggle";
|
||||
import { HostFilter } from "@/components/hosts/host-filter";
|
||||
import type { HostPickerHost } from "@/components/hosts/host-picker";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
@@ -199,6 +200,7 @@ export function PluginSurfaceScreen() {
|
||||
const headerLeft = useMemo(
|
||||
() => (
|
||||
<>
|
||||
<SidebarMenuToggle />
|
||||
{icon ? (
|
||||
<HeaderIconBadge>
|
||||
<ThemedPluginHeaderIcon icon={icon} uniProps={mutedColorMapping} />
|
||||
|
||||
@@ -6,6 +6,7 @@ import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import { SafeAreaProvider } from "react-native-safe-area-context";
|
||||
import { queryClient } from "@/data/query-client";
|
||||
import { I18nProvider } from "@/i18n/provider";
|
||||
import { installRouteLeavePopStateGuard } from "@/navigation/route-leave-guard";
|
||||
import { RootErrorBoundary } from "@/components/root-error-boundary";
|
||||
|
||||
// Keep Expo's platform filtering, route root, and lazy import configuration.
|
||||
@@ -22,6 +23,11 @@ export function RootApp() {
|
||||
}
|
||||
|
||||
export function RootRouter({ context: routes }: Pick<ComponentProps<typeof ExpoRoot>, "context">) {
|
||||
// Attach the web popstate guard before ExpoRoot's effect registers its history listener.
|
||||
useState(() => {
|
||||
installRouteLeavePopStateGuard();
|
||||
return true;
|
||||
});
|
||||
const [generation, setGeneration] = useState(0);
|
||||
const reload = useCallback(() => setGeneration((value) => value + 1), []);
|
||||
|
||||
|
||||
@@ -1578,9 +1578,18 @@ export function NewWorkspaceScreen({
|
||||
? t("newWorkspace.refPicker.searching")
|
||||
: t("newWorkspace.refPicker.noMatchingRefs");
|
||||
|
||||
// The prompt is where the user types; when a field's picker closes, focus returns there rather
|
||||
// than to whatever had focus when the picker opened. A terminal profile that takes no prompt
|
||||
// shows a read-only command preview, so its pickers keep returning focus to their field.
|
||||
const composerFocusRef = useRef<{ focus: () => void } | null>(null);
|
||||
const handleComposerFocusInput = useCallback((focus: () => void) => {
|
||||
composerFocusRef.current = { focus };
|
||||
}, []);
|
||||
|
||||
const formStack = useNewWorkspaceForm({
|
||||
isCompact,
|
||||
isPending,
|
||||
restoreFocusRef: terminalTakesPrompt ? composerFocusRef : undefined,
|
||||
pluginItems: (
|
||||
<PluginNewWorkspaceItems serverId={selectedServerId} screen={pluginScreen} setup={setup} />
|
||||
),
|
||||
@@ -1682,6 +1691,7 @@ export function NewWorkspaceScreen({
|
||||
clearDraft={noopClearDraft}
|
||||
autoFocus={terminalTakesPrompt}
|
||||
autoFocusKey={launchFocusKey}
|
||||
onFocusInput={handleComposerFocusInput}
|
||||
error={errorMessage}
|
||||
/>
|
||||
) : (
|
||||
@@ -1712,6 +1722,7 @@ export function NewWorkspaceScreen({
|
||||
clearDraft={handleClearDraft}
|
||||
autoFocus
|
||||
autoFocusKey={launchFocusKey}
|
||||
onFocusInput={handleComposerFocusInput}
|
||||
commandDraft={composerState?.commandDraft}
|
||||
agentControls={agentControlsWithDisabled}
|
||||
error={errorMessage}
|
||||
|
||||
@@ -67,6 +67,11 @@ export interface NewWorkspaceFormProps {
|
||||
isPending: boolean;
|
||||
/** Plugin fields, drawn after the base ref. */
|
||||
pluginItems: ReactNode;
|
||||
/**
|
||||
* Where focus goes when a field's picker closes, so the user keeps typing the prompt. Without
|
||||
* one, focus returns to the field that opened the picker.
|
||||
*/
|
||||
restoreFocusRef?: RefObject<unknown>;
|
||||
project: PickerControl & {
|
||||
options: ComboboxOption[];
|
||||
projectByOptionId: Map<string, HostProjectListItem>;
|
||||
@@ -373,7 +378,17 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) {
|
||||
*/
|
||||
export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const { isCompact, isPending, pluginItems, project, host, isolation, base, launch } = props;
|
||||
const {
|
||||
isCompact,
|
||||
isPending,
|
||||
pluginItems,
|
||||
restoreFocusRef,
|
||||
project,
|
||||
host,
|
||||
isolation,
|
||||
base,
|
||||
launch,
|
||||
} = props;
|
||||
const variant: FieldTriggerVariant = isCompact ? "field" : "badge";
|
||||
const projectPicker = useProjectPicker(project, isPending);
|
||||
const isolationPicker = useIsolationPicker({
|
||||
@@ -432,6 +447,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
open={host.openState}
|
||||
onOpenChange={host.onOpenChange}
|
||||
anchorRef={host.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
includeAddHost
|
||||
onAddHost={host.onAddHost}
|
||||
addHostTestID="new-workspace-host-picker-add-host"
|
||||
@@ -525,6 +541,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
desktopPlacement="bottom-start"
|
||||
desktopMinWidth={360}
|
||||
anchorRef={project.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
emptyText="No projects available."
|
||||
renderOption={projectPicker.renderOption}
|
||||
footer={projectPicker.footer}
|
||||
@@ -539,6 +556,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
searchable={false}
|
||||
desktopPlacement="bottom-start"
|
||||
anchorRef={isolation.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
desktopMinWidth={280}
|
||||
renderOption={isolationPicker.renderOption}
|
||||
/>
|
||||
@@ -555,6 +573,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
desktopPlacement="bottom-start"
|
||||
desktopMinWidth={440}
|
||||
anchorRef={base.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
emptyText={base.emptyText}
|
||||
toolbar={refPicker.toolbar}
|
||||
renderOption={refPicker.renderOption}
|
||||
@@ -571,6 +590,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
|
||||
desktopPlacement="bottom-start"
|
||||
desktopMinWidth={360}
|
||||
anchorRef={worktreePicker.anchorRef}
|
||||
restoreFocusRef={restoreFocusRef}
|
||||
emptyText={t("newWorkspace.worktreePicker.empty")}
|
||||
renderOption={worktreePicker.renderOption}
|
||||
/>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { useSettingsContentPresented } from "@/navigation/settings-presentation";
|
||||
import { registerRouteLeaveGuard } from "@/navigation/route-leave-guard";
|
||||
import { AppearanceText as Text } from "@/appearance/text";
|
||||
import { useHardwareKeyboardPresent } from "@/keyboard";
|
||||
import { useAddHost } from "@/hosts/add-host";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { Alert, Pressable, ScrollView, View, type PressableStateCallbackType } from "react-native";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useFocusEffect } from "expo-router/react-navigation";
|
||||
import { useNavigation, useRouter } from "expo-router";
|
||||
import { useFocusEffect, usePreventRemove } from "expo-router/react-navigation";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -40,6 +41,7 @@ import {
|
||||
PanelLeft,
|
||||
MessageSquare,
|
||||
ChevronRight,
|
||||
Layers,
|
||||
} from "lucide-react-native";
|
||||
import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
|
||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||
@@ -102,6 +104,7 @@ import {
|
||||
HostConnectionsPage,
|
||||
HostPairDevicePage,
|
||||
HostAgentsPage,
|
||||
HostAgentProfilesPage,
|
||||
HostSettingsPage,
|
||||
HostProvidersPage,
|
||||
HostUsagePage,
|
||||
@@ -249,6 +252,7 @@ const HOST_SECTION_ITEMS: HostSectionItem[] = [
|
||||
{ id: "connections", labelKey: "settings.hostSections.connections", icon: Network },
|
||||
{ id: "pair-device", labelKey: "openProject.tiles.pairDevice.title", icon: Smartphone },
|
||||
{ id: "agents", labelKey: "settings.hostSections.agents", icon: Bot },
|
||||
{ id: "agent-profiles", labelKey: "settings.hostSections.agentProfiles", icon: Layers },
|
||||
{ id: "metadata", labelKey: "settings.hostSections.metadata", icon: Sparkles },
|
||||
{ id: "voice", labelKey: "settings.hostSections.voice", icon: Mic },
|
||||
{ id: "workspaces", labelKey: "settings.hostSections.workspaces", icon: FolderGit2 },
|
||||
@@ -271,6 +275,9 @@ function renderHostSettingsContent(
|
||||
return <HostPairDevicePage serverId={view.serverId} />;
|
||||
case "agents":
|
||||
return <HostAgentsPage serverId={view.serverId} />;
|
||||
case "agent-profiles":
|
||||
// Rendered directly in SettingsScreen so AgentProfilesPage owns its wide PageLayout + drawer split.
|
||||
return null;
|
||||
case "metadata":
|
||||
return <MetadataGenerationPage serverId={view.serverId} />;
|
||||
case "voice":
|
||||
@@ -1104,6 +1111,139 @@ function SettingsSidebar({
|
||||
);
|
||||
}
|
||||
|
||||
interface SettingsBeforeLeaveGuard {
|
||||
isDirty: () => boolean;
|
||||
confirmDiscard: () => Promise<boolean>;
|
||||
subscribeDirty?: (listener: () => void) => () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets an active Settings editor (such as Agent profiles) veto both in-app
|
||||
* section switches and route-boundary exits (browser Back, native swipe-back,
|
||||
* hardware Back) with a single discard confirmation.
|
||||
*
|
||||
* Uses `usePreventRemove` so native stacks set `preventNativeDismiss` before
|
||||
* iOS can interactively dismiss the screen on a back swipe.
|
||||
*/
|
||||
function useSettingsBeforeLeaveGuard() {
|
||||
const navigation = useNavigation();
|
||||
const beforeLeaveRef = useRef<SettingsBeforeLeaveGuard | null>(null);
|
||||
const dirtyUnsubRef = useRef<(() => void) | null>(null);
|
||||
const [preventRemove, setPreventRemove] = useState(false);
|
||||
|
||||
const registerBeforeLeave = useCallback((guard: SettingsBeforeLeaveGuard | null) => {
|
||||
dirtyUnsubRef.current?.();
|
||||
dirtyUnsubRef.current = null;
|
||||
beforeLeaveRef.current = guard;
|
||||
const syncDirty = () => {
|
||||
setPreventRemove(Boolean(beforeLeaveRef.current?.isDirty()));
|
||||
};
|
||||
syncDirty();
|
||||
if (guard?.subscribeDirty) {
|
||||
dirtyUnsubRef.current = guard.subscribeDirty(syncDirty);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
dirtyUnsubRef.current?.();
|
||||
dirtyUnsubRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return registerRouteLeaveGuard({
|
||||
isDirty: () => Boolean(beforeLeaveRef.current?.isDirty()),
|
||||
confirmDiscard: async () => (await beforeLeaveRef.current?.confirmDiscard()) ?? true,
|
||||
});
|
||||
}, []);
|
||||
|
||||
usePreventRemove(preventRemove, ({ data }) => {
|
||||
const guard = beforeLeaveRef.current;
|
||||
if (!guard?.isDirty()) {
|
||||
navigation.dispatch(data.action);
|
||||
return;
|
||||
}
|
||||
const confirmAndLeave = async () => {
|
||||
if (await guard.confirmDiscard()) {
|
||||
navigation.dispatch(data.action);
|
||||
}
|
||||
};
|
||||
void confirmAndLeave();
|
||||
});
|
||||
|
||||
const guardNavigation = useCallback((navigate: () => void) => {
|
||||
const guard = beforeLeaveRef.current;
|
||||
if (!guard?.isDirty()) {
|
||||
navigate();
|
||||
return;
|
||||
}
|
||||
const run = async () => {
|
||||
if (await guard.confirmDiscard()) {
|
||||
navigate();
|
||||
}
|
||||
};
|
||||
void run();
|
||||
}, []);
|
||||
|
||||
return { registerBeforeLeave, guardNavigation };
|
||||
}
|
||||
|
||||
function SettingsDetailPane({
|
||||
view,
|
||||
isCompactLayout,
|
||||
detailTitle,
|
||||
detailActions,
|
||||
detailWidth,
|
||||
onBack,
|
||||
onRegisterBeforeLeave,
|
||||
content,
|
||||
}: {
|
||||
view: SettingsView;
|
||||
isCompactLayout: boolean;
|
||||
detailTitle: string | undefined;
|
||||
detailActions: React.ReactNode;
|
||||
detailWidth: React.ComponentProps<typeof PageLayout>["width"];
|
||||
onBack: () => void;
|
||||
onRegisterBeforeLeave: (guard: SettingsBeforeLeaveGuard | null) => void;
|
||||
content: React.ReactNode;
|
||||
}) {
|
||||
const isStandaloneAgentProfilesView = view.kind === "host" && view.section === "agent-profiles";
|
||||
const pageTitle =
|
||||
!isCompactLayout && (view.kind === "project" || view.kind === "provider")
|
||||
? undefined
|
||||
: detailTitle;
|
||||
|
||||
return (
|
||||
<WindowChromeRegion corners={isCompactLayout ? "both" : "top-right"}>
|
||||
<View
|
||||
style={isCompactLayout ? desktopStyles.compactContentPane : desktopStyles.contentPane}
|
||||
testID={isCompactLayout ? undefined : "settings-detail-pane"}
|
||||
>
|
||||
{isStandaloneAgentProfilesView ? (
|
||||
<HostAgentProfilesPage
|
||||
serverId={view.serverId}
|
||||
onBack={isCompactLayout ? onBack : undefined}
|
||||
onRegisterBeforeLeave={onRegisterBeforeLeave}
|
||||
/>
|
||||
) : (
|
||||
<PageLayout
|
||||
// A project or provider page draws its own title on desktop, naming the list it came from.
|
||||
title={pageTitle}
|
||||
onBack={isCompactLayout ? onBack : undefined}
|
||||
actions={detailActions}
|
||||
width={detailWidth}
|
||||
titleTestID={isCompactLayout ? undefined : "settings-detail-header-title"}
|
||||
testID={isCompactLayout ? undefined : "settings-detail-scroll-body"}
|
||||
>
|
||||
{content}
|
||||
</PageLayout>
|
||||
)}
|
||||
</View>
|
||||
</WindowChromeRegion>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main screen
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1201,10 +1341,10 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
|
||||
);
|
||||
|
||||
const handleAddHost = useAddHost({ onAdded: handleHostAdded });
|
||||
const { registerBeforeLeave, guardNavigation } = useSettingsBeforeLeaveGuard();
|
||||
|
||||
const handleSelectSection = useCallback(
|
||||
(section: SettingsSectionSlug) => {
|
||||
const target = buildSettingsSectionRoute(section);
|
||||
const navigateRoute = useCallback(
|
||||
(target: Parameters<typeof router.push>[0]) => {
|
||||
if (isCompactLayout) {
|
||||
router.push(target);
|
||||
} else {
|
||||
@@ -1214,51 +1354,62 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
|
||||
[isCompactLayout, router],
|
||||
);
|
||||
|
||||
const handleSelectSection = useCallback(
|
||||
(section: SettingsSectionSlug) => {
|
||||
if (view.kind === "section" && view.section === section) {
|
||||
return;
|
||||
}
|
||||
const target = buildSettingsSectionRoute(section);
|
||||
guardNavigation(() => navigateRoute(target));
|
||||
},
|
||||
[guardNavigation, navigateRoute, view],
|
||||
);
|
||||
|
||||
// Picker: choose the host for host-section rows. If the user is already on a
|
||||
// host detail route, keep that detail section and swap only the host segment.
|
||||
const handleSelectHost = useCallback(
|
||||
(serverId: string) => {
|
||||
selectSettingsHost(serverId);
|
||||
if (view.kind === "project" || view.kind === "provider") {
|
||||
// The detail belongs to the old host; open the same list on the new one.
|
||||
const target = buildSettingsHostSectionRoute(
|
||||
serverId,
|
||||
view.kind === "project" ? "projects" : "providers",
|
||||
);
|
||||
if (isCompactLayout) {
|
||||
router.push(target);
|
||||
} else {
|
||||
router.replace(target);
|
||||
if (view.kind === "host" && view.serverId === serverId) {
|
||||
return;
|
||||
}
|
||||
const applySelection = () => {
|
||||
selectSettingsHost(serverId);
|
||||
if (view.kind === "project" || view.kind === "provider") {
|
||||
// The detail belongs to the old host; open the same list on the new one.
|
||||
navigateRoute(
|
||||
buildSettingsHostSectionRoute(
|
||||
serverId,
|
||||
view.kind === "project" ? "projects" : "providers",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (view.kind !== "host") {
|
||||
return;
|
||||
}
|
||||
const target = buildSettingsHostSectionRoute(serverId, view.section);
|
||||
if (isCompactLayout) {
|
||||
router.push(target);
|
||||
} else {
|
||||
router.replace(target);
|
||||
}
|
||||
if (view.kind === "host") {
|
||||
navigateRoute(buildSettingsHostSectionRoute(serverId, view.section));
|
||||
}
|
||||
};
|
||||
guardNavigation(applySelection);
|
||||
},
|
||||
[isCompactLayout, router, view],
|
||||
[guardNavigation, navigateRoute, view],
|
||||
);
|
||||
|
||||
const handleSelectHostSection = useCallback(
|
||||
(section: HostSectionSlug) => {
|
||||
if (!activeHostServerId) {
|
||||
handleAddHost();
|
||||
guardNavigation(handleAddHost);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
view.kind === "host" &&
|
||||
view.serverId === activeHostServerId &&
|
||||
view.section === section
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const target = buildSettingsHostSectionRoute(activeHostServerId, section);
|
||||
if (isCompactLayout) {
|
||||
router.push(target);
|
||||
} else {
|
||||
router.replace(target);
|
||||
}
|
||||
guardNavigation(() => navigateRoute(target));
|
||||
},
|
||||
[activeHostServerId, handleAddHost, isCompactLayout, router],
|
||||
[activeHostServerId, guardNavigation, handleAddHost, navigateRoute, view],
|
||||
);
|
||||
|
||||
const handleHostRemoved = useCallback(() => {
|
||||
@@ -1271,12 +1422,12 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
|
||||
}, [isCompactLayout, router]);
|
||||
|
||||
const handleBackFromDetail = useCallback(() => {
|
||||
returnFromSettings(view);
|
||||
}, [view]);
|
||||
guardNavigation(() => returnFromSettings(view));
|
||||
}, [guardNavigation, view]);
|
||||
|
||||
const handleBackToWorkspace = useCallback(() => {
|
||||
returnFromSettings({ kind: "root" });
|
||||
}, []);
|
||||
guardNavigation(() => returnFromSettings({ kind: "root" }));
|
||||
}, [guardNavigation]);
|
||||
|
||||
// A plugin's page draws its own header; the compact back header names the plugin.
|
||||
const pluginPage = useMemo((): { serverId: string; subject: PluginPageSubject } | null => {
|
||||
@@ -1412,53 +1563,36 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
|
||||
);
|
||||
}
|
||||
|
||||
if (isCompactLayout) {
|
||||
return (
|
||||
<View style={styles.container} onLayout={onContentLayout}>
|
||||
<PageLayout
|
||||
title={detailTitle}
|
||||
onBack={handleBackFromDetail}
|
||||
actions={detailActions}
|
||||
width={detailWidth}
|
||||
>
|
||||
{content}
|
||||
</PageLayout>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
// Desktop split view — mirrors AppContainer: sidebar owns the titlebar drag
|
||||
// region + traffic-light padding; detail pane renders whatever header the
|
||||
// selected section provides.
|
||||
// Desktop split view and compact detail view share one wrapper tree around the
|
||||
// detail pane so resizing across the compact breakpoint never unmounts active
|
||||
// detail screens or discards in-progress edits (e.g., Agent profiles drawer → sheet).
|
||||
return (
|
||||
<View style={styles.container} onLayout={onContentLayout}>
|
||||
<View style={desktopStyles.row}>
|
||||
<WindowChromeRegion corners="top-left">
|
||||
<SettingsSidebar
|
||||
view={view}
|
||||
onSelectSection={handleSelectSection}
|
||||
onSelectHostSection={handleSelectHostSection}
|
||||
onSelectHost={handleSelectHost}
|
||||
onAddHost={handleAddHost}
|
||||
onBackToWorkspace={handleBackToWorkspace}
|
||||
activeHostServerId={activeHostServerId}
|
||||
layout="desktop"
|
||||
/>
|
||||
</WindowChromeRegion>
|
||||
<WindowChromeRegion corners="top-right">
|
||||
<View style={desktopStyles.contentPane} testID="settings-detail-pane">
|
||||
<PageLayout
|
||||
// A project or provider page draws its own title, which names the list it came from.
|
||||
title={view.kind === "project" || view.kind === "provider" ? undefined : detailTitle}
|
||||
actions={detailActions}
|
||||
width={detailWidth}
|
||||
titleTestID="settings-detail-header-title"
|
||||
testID="settings-detail-scroll-body"
|
||||
>
|
||||
{content}
|
||||
</PageLayout>
|
||||
</View>
|
||||
</WindowChromeRegion>
|
||||
{isCompactLayout ? null : (
|
||||
<WindowChromeRegion corners="top-left">
|
||||
<SettingsSidebar
|
||||
view={view}
|
||||
onSelectSection={handleSelectSection}
|
||||
onSelectHostSection={handleSelectHostSection}
|
||||
onSelectHost={handleSelectHost}
|
||||
onAddHost={handleAddHost}
|
||||
onBackToWorkspace={handleBackToWorkspace}
|
||||
activeHostServerId={activeHostServerId}
|
||||
layout="desktop"
|
||||
/>
|
||||
</WindowChromeRegion>
|
||||
)}
|
||||
<SettingsDetailPane
|
||||
view={view}
|
||||
isCompactLayout={isCompactLayout}
|
||||
detailTitle={detailTitle}
|
||||
detailActions={detailActions}
|
||||
detailWidth={detailWidth}
|
||||
onBack={handleBackFromDetail}
|
||||
onRegisterBeforeLeave={registerBeforeLeave}
|
||||
content={content}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
@@ -1527,6 +1661,10 @@ const desktopStyles = StyleSheet.create({
|
||||
flex: 1,
|
||||
minWidth: SETTINGS_DESKTOP_DETAIL_MIN_WIDTH,
|
||||
},
|
||||
compactContentPane: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const sidebarStyles = StyleSheet.create((theme) => ({
|
||||
@@ -1548,8 +1686,10 @@ const sidebarStyles = StyleSheet.create((theme) => ({
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
},
|
||||
// Compact values draw each group as an island of tiles; desktop keeps a plain list.
|
||||
// Use vertical margin rather than padding so trailing empty group padding cannot
|
||||
// intersect the scrollport top alone and capture browser scroll anchoring.
|
||||
group: {
|
||||
paddingVertical: theme.spacing[2],
|
||||
marginVertical: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
gap: { xs: theme.spacing[1], md: theme.spacing[0.5] },
|
||||
},
|
||||
|
||||
@@ -21,9 +21,10 @@ import {
|
||||
getTerminalProfileIcon,
|
||||
DEFAULT_TERMINAL_PROFILES,
|
||||
} from "@getpaseo/protocol/terminal-profiles";
|
||||
import { AgentProfilesSection } from "@/agent-profiles";
|
||||
import { AgentProfilesPage, type AgentProfilesBeforeLeaveGuard } from "@/agent-profiles";
|
||||
import { AgentSkillsSection } from "@/agent-skills";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { PageLayout } from "@/components/page-layout";
|
||||
import { SettingsTextAreaCard } from "@/components/settings-textarea";
|
||||
import { Alert as InlineAlert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -304,11 +305,43 @@ export function HostAgentsPage({ serverId }: { serverId: string }) {
|
||||
</View>
|
||||
)}
|
||||
<AgentSkillsSection serverId={serverId} />
|
||||
<AgentProfilesSection serverId={serverId} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function HostAgentProfilesPage({
|
||||
serverId,
|
||||
onBack,
|
||||
onRegisterBeforeLeave,
|
||||
}: {
|
||||
serverId: string;
|
||||
onBack?: () => void;
|
||||
onRegisterBeforeLeave?: (guard: AgentProfilesBeforeLeaveGuard | null) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const host = useHostProfile(serverId);
|
||||
|
||||
if (!host) {
|
||||
return (
|
||||
<PageLayout
|
||||
title={t("settings.host.agentProfiles.sectionTitle")}
|
||||
onBack={onBack}
|
||||
titleTestID="settings-detail-header-title"
|
||||
>
|
||||
<HostNotFound />
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AgentProfilesPage
|
||||
serverId={serverId}
|
||||
onBack={onBack}
|
||||
onRegisterBeforeLeave={onRegisterBeforeLeave}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function HostWorkspacesPage({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const host = useHostProfile(serverId);
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
export { isShiftPressEvent } from "./internal/selection-state";
|
||||
export {
|
||||
registerSidebarVisibleWorkspaceKeysReader,
|
||||
useIsSidebarSelectionMode,
|
||||
useIsWorkspaceBulkSelected,
|
||||
useSidebarSelectionStore,
|
||||
} from "./internal/selection-store";
|
||||
export { SidebarSelectionHost } from "./internal/sidebar-selection-host";
|
||||
@@ -0,0 +1,280 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
|
||||
import {
|
||||
archiveSelectedWorkspaces,
|
||||
type BulkArchiveClient,
|
||||
type BulkArchiveWorkspacesDeps,
|
||||
} from "./archive-selected";
|
||||
|
||||
function makeEntry(
|
||||
overrides: Partial<SidebarWorkspaceEntry> & { workspaceId: string },
|
||||
): SidebarWorkspaceEntry {
|
||||
return {
|
||||
workspaceKey: `srv:${overrides.workspaceId}`,
|
||||
serverId: "srv",
|
||||
projectViewKey: "prj-view",
|
||||
projectName: "Repo",
|
||||
projectRootPath: "/repo",
|
||||
workspaceDirectory: `/repo/${overrides.workspaceId}`,
|
||||
workspaceDirectoryLabel: overrides.workspaceId,
|
||||
projectKind: "git",
|
||||
workspaceKind: "local_checkout",
|
||||
name: overrides.workspaceId,
|
||||
title: null,
|
||||
currentBranch: overrides.workspaceId,
|
||||
statusBucket: "done",
|
||||
statusEnteredAt: null,
|
||||
archivingAt: null,
|
||||
diffStat: null,
|
||||
prHint: null,
|
||||
pinnedAt: null,
|
||||
background: false,
|
||||
labels: [],
|
||||
scripts: [],
|
||||
hasRunningScripts: false,
|
||||
archiveHasUncommittedChanges: null,
|
||||
archiveUnpushedCommitCount: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createFakeToast(): { toast: ToastApi; errors: string[] } {
|
||||
const errors: string[] = [];
|
||||
return {
|
||||
errors,
|
||||
toast: {
|
||||
show: () => () => {},
|
||||
copied: () => {},
|
||||
error: (message) => errors.push(message),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createFakeClient(): BulkArchiveClient {
|
||||
return {
|
||||
archiveWorkspace: async () => ({ error: null }),
|
||||
undoWorkspaceArchive: async () => {},
|
||||
getCheckoutStatus: async () =>
|
||||
({
|
||||
isGit: true,
|
||||
isDirty: false,
|
||||
aheadOfOrigin: 0,
|
||||
}) as Awaited<ReturnType<BulkArchiveClient["getCheckoutStatus"]>>,
|
||||
};
|
||||
}
|
||||
|
||||
describe("archiveSelectedWorkspaces", () => {
|
||||
it("archives multiple workspaces with one undo batch and redirects active workspace first", async () => {
|
||||
const order: string[] = [];
|
||||
const client = createFakeClient();
|
||||
const { toast, errors } = createFakeToast();
|
||||
const confirmRiskyBulkArchive = vi.fn(async () => true);
|
||||
const deps: BulkArchiveWorkspacesDeps = {
|
||||
getClient: () => client,
|
||||
supportsUndo: () => true,
|
||||
readWorktreeRisk: async () => ({ isDirty: false, aheadOfOrigin: 0 }),
|
||||
confirmRiskyBulkArchive,
|
||||
archiveWithUndo: async (input) => {
|
||||
order.push(
|
||||
`archive:${input.entries.map((entry) => entry.workspace.workspaceId).join(",")}`,
|
||||
);
|
||||
return { failures: [], showPartialFailure: () => false };
|
||||
},
|
||||
archiveWithoutUndo: async () => "archived",
|
||||
hasActiveUndo: () => false,
|
||||
purgeWorkspaceState: vi.fn(),
|
||||
redirectActiveWorkspace: (workspace) => {
|
||||
order.push(`redirect:${workspace.workspaceId}`);
|
||||
},
|
||||
};
|
||||
|
||||
const ok = await archiveSelectedWorkspaces({
|
||||
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
|
||||
toast,
|
||||
onArchiveStarted: () => order.push("exit-selection"),
|
||||
deps,
|
||||
});
|
||||
|
||||
expect(ok).toBe(true);
|
||||
expect(errors).toEqual([]);
|
||||
expect(order).toEqual(["redirect:w1", "redirect:w2", "exit-selection", "archive:w1,w2"]);
|
||||
expect(confirmRiskyBulkArchive).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps select mode open when the user cancels a risky worktree confirmation", async () => {
|
||||
const client = createFakeClient();
|
||||
const { toast, errors } = createFakeToast();
|
||||
const onArchiveStarted = vi.fn();
|
||||
const archiveWithUndo = vi.fn(async () => ({
|
||||
failures: [],
|
||||
showPartialFailure: () => false,
|
||||
}));
|
||||
const confirmRiskyBulkArchive = vi.fn(async () => false);
|
||||
|
||||
const ok = await archiveSelectedWorkspaces({
|
||||
workspaces: [
|
||||
makeEntry({ workspaceId: "w1", workspaceKind: "worktree", name: "feat-wip" }),
|
||||
makeEntry({ workspaceId: "w2", workspaceKind: "local_checkout", name: "main" }),
|
||||
],
|
||||
toast,
|
||||
onArchiveStarted,
|
||||
deps: {
|
||||
getClient: () => client,
|
||||
supportsUndo: () => true,
|
||||
readWorktreeRisk: async () => ({ isDirty: true, aheadOfOrigin: 1 }),
|
||||
confirmRiskyBulkArchive,
|
||||
archiveWithUndo,
|
||||
archiveWithoutUndo: async () => "archived",
|
||||
hasActiveUndo: () => false,
|
||||
purgeWorkspaceState: vi.fn(),
|
||||
redirectActiveWorkspace: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(errors).toEqual([]);
|
||||
expect(confirmRiskyBulkArchive).toHaveBeenCalledWith({
|
||||
totalCount: 2,
|
||||
riskyWorkspaces: [
|
||||
{
|
||||
workspaceName: "feat-wip",
|
||||
diffStat: null,
|
||||
isDirty: true,
|
||||
aheadOfOrigin: 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(onArchiveStarted).not.toHaveBeenCalled();
|
||||
expect(archiveWithUndo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows a disconnect error and aborts before archiving when any host is offline", async () => {
|
||||
const { toast, errors } = createFakeToast();
|
||||
const onArchiveStarted = vi.fn();
|
||||
|
||||
const ok = await archiveSelectedWorkspaces({
|
||||
workspaces: [makeEntry({ workspaceId: "w1" })],
|
||||
toast,
|
||||
onArchiveStarted,
|
||||
deps: {
|
||||
getClient: () => null,
|
||||
supportsUndo: () => true,
|
||||
readWorktreeRisk: vi.fn(),
|
||||
confirmRiskyBulkArchive: vi.fn(),
|
||||
archiveWithUndo: vi.fn(),
|
||||
archiveWithoutUndo: vi.fn(),
|
||||
hasActiveUndo: () => false,
|
||||
purgeWorkspaceState: vi.fn(),
|
||||
redirectActiveWorkspace: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(errors).toEqual(["Host is not connected"]);
|
||||
expect(onArchiveStarted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports multi-workspace failures when more than one archive fails", async () => {
|
||||
const client = createFakeClient();
|
||||
const { toast, errors } = createFakeToast();
|
||||
|
||||
const ok = await archiveSelectedWorkspaces({
|
||||
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
|
||||
toast,
|
||||
onArchiveStarted: vi.fn(),
|
||||
deps: {
|
||||
getClient: () => client,
|
||||
supportsUndo: () => true,
|
||||
readWorktreeRisk: vi.fn(),
|
||||
confirmRiskyBulkArchive: vi.fn(),
|
||||
archiveWithUndo: async () => ({
|
||||
failures: [
|
||||
{ workspace: { serverId: "srv", workspaceId: "w1" }, error: new Error("boom 1") },
|
||||
{ workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("boom 2") },
|
||||
],
|
||||
showPartialFailure: () => false,
|
||||
}),
|
||||
archiveWithoutUndo: vi.fn(),
|
||||
hasActiveUndo: () => false,
|
||||
purgeWorkspaceState: vi.fn(),
|
||||
redirectActiveWorkspace: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(errors).toEqual(["Failed to archive 2 workspaces"]);
|
||||
});
|
||||
|
||||
it("keeps Undo open via showPartialFailure instead of replacing it with toast.error on partial failure", async () => {
|
||||
const client = createFakeClient();
|
||||
const { toast, errors } = createFakeToast();
|
||||
const partialErrors: string[] = [];
|
||||
|
||||
const ok = await archiveSelectedWorkspaces({
|
||||
workspaces: [makeEntry({ workspaceId: "w1" }), makeEntry({ workspaceId: "w2" })],
|
||||
toast,
|
||||
onArchiveStarted: vi.fn(),
|
||||
deps: {
|
||||
getClient: () => client,
|
||||
supportsUndo: () => true,
|
||||
readWorktreeRisk: vi.fn(),
|
||||
confirmRiskyBulkArchive: vi.fn(),
|
||||
archiveWithUndo: async () => ({
|
||||
failures: [
|
||||
{ workspace: { serverId: "srv", workspaceId: "w2" }, error: new Error("Host offline") },
|
||||
],
|
||||
showPartialFailure: (message) => {
|
||||
partialErrors.push(message);
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
archiveWithoutUndo: vi.fn(),
|
||||
hasActiveUndo: () => false,
|
||||
purgeWorkspaceState: vi.fn(),
|
||||
redirectActiveWorkspace: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(partialErrors).toEqual(["Host offline"]);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it("routes a late failure from a superseded batch to fallbackErrorToast so a newer batch keeps its Undo", async () => {
|
||||
const client = createFakeClient();
|
||||
const sidebar = createFakeToast();
|
||||
const app = createFakeToast();
|
||||
|
||||
const ok = await archiveSelectedWorkspaces({
|
||||
workspaces: [makeEntry({ workspaceId: "w1" })],
|
||||
toast: sidebar.toast,
|
||||
fallbackErrorToast: app.toast,
|
||||
onArchiveStarted: vi.fn(),
|
||||
deps: {
|
||||
getClient: () => client,
|
||||
supportsUndo: () => true,
|
||||
readWorktreeRisk: vi.fn(),
|
||||
confirmRiskyBulkArchive: vi.fn(),
|
||||
archiveWithUndo: async () => ({
|
||||
failures: [
|
||||
{
|
||||
workspace: { serverId: "srv", workspaceId: "w1" },
|
||||
error: new Error("Host timed out"),
|
||||
},
|
||||
],
|
||||
// This batch's own undo window was closed when a newer batch superseded it.
|
||||
showPartialFailure: () => false,
|
||||
}),
|
||||
archiveWithoutUndo: vi.fn(),
|
||||
hasActiveUndo: () => true,
|
||||
purgeWorkspaceState: vi.fn(),
|
||||
redirectActiveWorkspace: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(sidebar.errors).toEqual([]);
|
||||
expect(app.errors).toEqual(["Host timed out"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import type { CheckoutStatusClient } from "@/git/checkout-status-cache";
|
||||
import {
|
||||
confirmRiskyBulkWorktreeArchive,
|
||||
readWorktreeArchiveRisk,
|
||||
type WorktreeArchiveConfirmationInput,
|
||||
} from "@/git/worktree-archive-warning";
|
||||
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import type { ActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
|
||||
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
import {
|
||||
archiveWorkspacesWithUndo,
|
||||
hasUndoableWorkspaceArchive,
|
||||
supportsWorkspaceArchiveUndo,
|
||||
type UndoableWorkspaceArchiveClient,
|
||||
} from "@/workspace/archive-undo";
|
||||
import {
|
||||
archiveWorkspaceOptimistically,
|
||||
type WorkspaceArchiveTarget,
|
||||
} from "@/workspace/workspace-archive";
|
||||
|
||||
export interface BulkArchiveClient extends UndoableWorkspaceArchiveClient, CheckoutStatusClient {}
|
||||
|
||||
export interface BulkArchiveWorkspacesDeps {
|
||||
getClient: (serverId: string) => BulkArchiveClient | null;
|
||||
supportsUndo: (serverId: string) => boolean;
|
||||
readWorktreeRisk: typeof readWorktreeArchiveRisk;
|
||||
confirmRiskyBulkArchive: typeof confirmRiskyBulkWorktreeArchive;
|
||||
archiveWithUndo: typeof archiveWorkspacesWithUndo;
|
||||
archiveWithoutUndo: typeof archiveWorkspaceOptimistically;
|
||||
hasActiveUndo: () => boolean;
|
||||
purgeWorkspaceState: (workspace: WorkspaceArchiveTarget) => void;
|
||||
redirectActiveWorkspace: (workspace: WorkspaceArchiveTarget) => void;
|
||||
}
|
||||
|
||||
function defaultPurgeWorkspaceState(workspace: WorkspaceArchiveTarget): void {
|
||||
const workspaceKey = buildWorkspaceTabPersistenceKey(workspace);
|
||||
if (workspaceKey) {
|
||||
useWorkspaceLayoutStore.getState().purgeWorkspace(workspaceKey);
|
||||
}
|
||||
}
|
||||
|
||||
export function createDefaultBulkArchiveDeps(
|
||||
getActiveWorkspaceSelection: () => ActiveWorkspaceSelection | null,
|
||||
): BulkArchiveWorkspacesDeps {
|
||||
return {
|
||||
getClient: (serverId) => getHostRuntimeStore().getClient(serverId),
|
||||
supportsUndo: supportsWorkspaceArchiveUndo,
|
||||
readWorktreeRisk: readWorktreeArchiveRisk,
|
||||
confirmRiskyBulkArchive: confirmRiskyBulkWorktreeArchive,
|
||||
archiveWithUndo: archiveWorkspacesWithUndo,
|
||||
archiveWithoutUndo: archiveWorkspaceOptimistically,
|
||||
hasActiveUndo: hasUndoableWorkspaceArchive,
|
||||
purgeWorkspaceState: defaultPurgeWorkspaceState,
|
||||
redirectActiveWorkspace: (workspace) => {
|
||||
redirectIfArchivingActiveWorkspace({
|
||||
serverId: workspace.serverId,
|
||||
workspaceId: workspace.workspaceId,
|
||||
activeWorkspaceSelection: getActiveWorkspaceSelection(),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function formatArchiveFailureMessage(failures: ReadonlyArray<{ error: unknown }>): string {
|
||||
if (failures.length > 1) {
|
||||
return i18n.t("sidebar.workspace.toasts.archiveMultipleFailed", { count: failures.length });
|
||||
}
|
||||
const error = failures[0]?.error;
|
||||
return error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed");
|
||||
}
|
||||
|
||||
interface ResolvedWorkspaceTarget {
|
||||
entry: SidebarWorkspaceEntry;
|
||||
client: BulkArchiveClient;
|
||||
}
|
||||
|
||||
export async function archiveSelectedWorkspaces(input: {
|
||||
workspaces: readonly SidebarWorkspaceEntry[];
|
||||
toast: ToastApi;
|
||||
fallbackErrorToast?: ToastApi;
|
||||
onArchiveStarted: () => void;
|
||||
deps: BulkArchiveWorkspacesDeps;
|
||||
}): Promise<boolean> {
|
||||
const { workspaces, toast, fallbackErrorToast, onArchiveStarted, deps } = input;
|
||||
if (workspaces.length === 0) return false;
|
||||
|
||||
const resolved: ResolvedWorkspaceTarget[] = [];
|
||||
for (const entry of workspaces) {
|
||||
const client = deps.getClient(entry.serverId);
|
||||
if (!client) {
|
||||
toast.error(i18n.t("sidebar.workspace.toasts.hostDisconnected"));
|
||||
return false;
|
||||
}
|
||||
resolved.push({ entry, client });
|
||||
}
|
||||
|
||||
const riskyWorkspaces: WorktreeArchiveConfirmationInput[] = [];
|
||||
const worktrees = resolved.filter((item) => item.entry.workspaceKind === "worktree");
|
||||
if (worktrees.length > 0) {
|
||||
try {
|
||||
const risks = await Promise.all(
|
||||
worktrees.map(async ({ entry, client }) => {
|
||||
const risk = await deps.readWorktreeRisk(client, entry.workspaceDirectory);
|
||||
return {
|
||||
workspaceName: entry.name,
|
||||
diffStat: entry.diffStat,
|
||||
isDirty: risk.isDirty,
|
||||
aheadOfOrigin: risk.aheadOfOrigin,
|
||||
} satisfies WorktreeArchiveConfirmationInput;
|
||||
}),
|
||||
);
|
||||
riskyWorkspaces.push(...risks);
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : i18n.t("sidebar.workspace.toasts.archiveFailed"),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (riskyWorkspaces.length > 0) {
|
||||
const confirmed = await deps.confirmRiskyBulkArchive({
|
||||
totalCount: resolved.length,
|
||||
riskyWorkspaces,
|
||||
});
|
||||
if (!confirmed) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Redirect before optimistic removal hides the active workspace from the session store.
|
||||
for (const { entry } of resolved) {
|
||||
deps.redirectActiveWorkspace({ serverId: entry.serverId, workspaceId: entry.workspaceId });
|
||||
}
|
||||
|
||||
onArchiveStarted();
|
||||
|
||||
const undoable: ResolvedWorkspaceTarget[] = [];
|
||||
const legacy: ResolvedWorkspaceTarget[] = [];
|
||||
for (const item of resolved) {
|
||||
if (deps.supportsUndo(item.entry.serverId)) {
|
||||
undoable.push(item);
|
||||
} else {
|
||||
legacy.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
const failures: Array<{ error: unknown }> = [];
|
||||
let showPartialFailure: (message: string) => boolean = () => false;
|
||||
|
||||
await Promise.all([
|
||||
undoable.length > 0
|
||||
? (async () => {
|
||||
const result = await deps.archiveWithUndo({
|
||||
entries: undoable.map(({ entry, client }) => {
|
||||
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
|
||||
return {
|
||||
client,
|
||||
workspace,
|
||||
onArchiveCommitted: () => deps.purgeWorkspaceState(workspace),
|
||||
};
|
||||
}),
|
||||
toast,
|
||||
});
|
||||
failures.push(...result.failures);
|
||||
showPartialFailure = result.showPartialFailure;
|
||||
})()
|
||||
: Promise.resolve(),
|
||||
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
|
||||
...legacy.map(async ({ entry, client }) => {
|
||||
const workspace = { serverId: entry.serverId, workspaceId: entry.workspaceId };
|
||||
try {
|
||||
await deps.archiveWithoutUndo({ client, workspace });
|
||||
deps.purgeWorkspaceState(workspace);
|
||||
} catch (error) {
|
||||
failures.push({ error });
|
||||
}
|
||||
}),
|
||||
]);
|
||||
|
||||
if (failures.length > 0) {
|
||||
const errorMessage = formatArchiveFailureMessage(failures);
|
||||
if (!showPartialFailure(errorMessage)) {
|
||||
// If a newer batch now owns the sidebar Undo toast, surface this older failure on the
|
||||
// app-level toast instead of displacing the active Undo window and purging its layouts.
|
||||
const errorToast = deps.hasActiveUndo() ? (fallbackErrorToast ?? toast) : toast;
|
||||
errorToast.error(errorMessage);
|
||||
}
|
||||
}
|
||||
|
||||
return failures.length === 0;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
enterWorkspaceSelection,
|
||||
exitWorkspaceSelection,
|
||||
INITIAL_WORKSPACE_SELECTION_STATE,
|
||||
isShiftPressEvent,
|
||||
reconcileWorkspaceSelection,
|
||||
selectWorkspaceRange,
|
||||
toggleWorkspaceSelection,
|
||||
} from "./selection-state";
|
||||
|
||||
describe("sidebar workspace selection state", () => {
|
||||
it("enters selection with the clicked workspace as anchor", () => {
|
||||
const state = enterWorkspaceSelection("ws-2");
|
||||
expect({
|
||||
active: state.active,
|
||||
selected: [...state.selectedKeys],
|
||||
anchorKey: state.anchorKey,
|
||||
}).toEqual({
|
||||
active: true,
|
||||
selected: ["ws-2"],
|
||||
anchorKey: "ws-2",
|
||||
});
|
||||
});
|
||||
|
||||
it("toggles workspaces on plain click without needing Shift", () => {
|
||||
let state = enterWorkspaceSelection("ws-1");
|
||||
state = toggleWorkspaceSelection(state, "ws-3");
|
||||
expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3"]);
|
||||
expect(state.anchorKey).toBe("ws-3");
|
||||
|
||||
state = toggleWorkspaceSelection(state, "ws-1");
|
||||
expect([...state.selectedKeys]).toEqual(["ws-3"]);
|
||||
expect(state.anchorKey).toBe("ws-1");
|
||||
|
||||
state = toggleWorkspaceSelection(state, "ws-3");
|
||||
expect(state.active).toBe(true);
|
||||
expect([...state.selectedKeys]).toEqual([]);
|
||||
});
|
||||
|
||||
it("selects an inclusive range on Shift+click in either direction while keeping prior picks", () => {
|
||||
const visible = ["ws-1", "ws-2", "ws-3", "ws-4", "ws-5"];
|
||||
let state = enterWorkspaceSelection("ws-1");
|
||||
state = toggleWorkspaceSelection(state, "ws-3");
|
||||
|
||||
state = selectWorkspaceRange(state, "ws-5", visible);
|
||||
expect([...state.selectedKeys]).toEqual(["ws-1", "ws-3", "ws-4", "ws-5"]);
|
||||
expect(state.anchorKey).toBe("ws-3");
|
||||
|
||||
const backward = selectWorkspaceRange(enterWorkspaceSelection("ws-4"), "ws-2", visible);
|
||||
expect([...backward.selectedKeys].sort()).toEqual(["ws-2", "ws-3", "ws-4"]);
|
||||
});
|
||||
|
||||
it("falls back to adding the target when the anchor is no longer in the visible list", () => {
|
||||
const state = selectWorkspaceRange(enterWorkspaceSelection("ws-hidden"), "ws-2", [
|
||||
"ws-1",
|
||||
"ws-2",
|
||||
]);
|
||||
expect([...state.selectedKeys]).toEqual(["ws-hidden", "ws-2"]);
|
||||
expect(state.anchorKey).toBe("ws-2");
|
||||
});
|
||||
|
||||
it("reconciles removed workspaces and clears a missing anchor", () => {
|
||||
let state = enterWorkspaceSelection("ws-1");
|
||||
state = toggleWorkspaceSelection(state, "ws-2");
|
||||
const reconciled = reconcileWorkspaceSelection(state, new Set(["ws-1"]));
|
||||
expect({
|
||||
active: reconciled.active,
|
||||
selected: [...reconciled.selectedKeys],
|
||||
anchorKey: reconciled.anchorKey,
|
||||
}).toEqual({
|
||||
active: true,
|
||||
selected: ["ws-1"],
|
||||
anchorKey: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("resets completely on exit", () => {
|
||||
expect(exitWorkspaceSelection()).toBe(INITIAL_WORKSPACE_SELECTION_STATE);
|
||||
});
|
||||
|
||||
it("detects Shift on direct, nativeEvent, or hardware modifier payloads", () => {
|
||||
expect(isShiftPressEvent({ shiftKey: true })).toBe(true);
|
||||
expect(isShiftPressEvent({ nativeEvent: { shiftKey: true } })).toBe(true);
|
||||
expect(isShiftPressEvent({ shiftKey: false, nativeEvent: { shiftKey: false } })).toBe(false);
|
||||
expect(isShiftPressEvent(null)).toBe(false);
|
||||
|
||||
// Native GestureResponderEvent omits shiftKey; falls back to hardware Shift state.
|
||||
const nativeResponderEvent = { nativeEvent: { locationX: 12, locationY: 8 } };
|
||||
expect(isShiftPressEvent(nativeResponderEvent, () => false)).toBe(false);
|
||||
expect(isShiftPressEvent(nativeResponderEvent, () => true)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import { isShiftKeyDown } from "@/keyboard";
|
||||
|
||||
export interface WorkspaceSelectionState {
|
||||
active: boolean;
|
||||
selectedKeys: ReadonlySet<string>;
|
||||
anchorKey: string | null;
|
||||
}
|
||||
|
||||
const EMPTY_KEYS: ReadonlySet<string> = new Set();
|
||||
|
||||
export const INITIAL_WORKSPACE_SELECTION_STATE: WorkspaceSelectionState = {
|
||||
active: false,
|
||||
selectedKeys: EMPTY_KEYS,
|
||||
anchorKey: null,
|
||||
};
|
||||
|
||||
export function enterWorkspaceSelection(workspaceKey: string): WorkspaceSelectionState {
|
||||
return {
|
||||
active: true,
|
||||
selectedKeys: new Set([workspaceKey]),
|
||||
anchorKey: workspaceKey,
|
||||
};
|
||||
}
|
||||
|
||||
export function toggleWorkspaceSelection(
|
||||
state: WorkspaceSelectionState,
|
||||
workspaceKey: string,
|
||||
): WorkspaceSelectionState {
|
||||
if (!state.active) {
|
||||
return enterWorkspaceSelection(workspaceKey);
|
||||
}
|
||||
const next = new Set(state.selectedKeys);
|
||||
if (!next.delete(workspaceKey)) {
|
||||
next.add(workspaceKey);
|
||||
}
|
||||
return {
|
||||
active: true,
|
||||
selectedKeys: next,
|
||||
anchorKey: workspaceKey,
|
||||
};
|
||||
}
|
||||
|
||||
export function selectWorkspaceRange(
|
||||
state: WorkspaceSelectionState,
|
||||
targetKey: string,
|
||||
orderedVisibleKeys: readonly string[],
|
||||
): WorkspaceSelectionState {
|
||||
if (!state.active) {
|
||||
return enterWorkspaceSelection(targetKey);
|
||||
}
|
||||
if (!state.anchorKey) {
|
||||
const next = new Set(state.selectedKeys);
|
||||
next.add(targetKey);
|
||||
return { active: true, selectedKeys: next, anchorKey: targetKey };
|
||||
}
|
||||
|
||||
const anchorIndex = orderedVisibleKeys.indexOf(state.anchorKey);
|
||||
const targetIndex = orderedVisibleKeys.indexOf(targetKey);
|
||||
if (anchorIndex < 0 || targetIndex < 0) {
|
||||
const next = new Set(state.selectedKeys);
|
||||
next.add(targetKey);
|
||||
return { active: true, selectedKeys: next, anchorKey: targetKey };
|
||||
}
|
||||
|
||||
const start = Math.min(anchorIndex, targetIndex);
|
||||
const end = Math.max(anchorIndex, targetIndex);
|
||||
const next = new Set(state.selectedKeys);
|
||||
for (let index = start; index <= end; index += 1) {
|
||||
const key = orderedVisibleKeys[index];
|
||||
if (key !== undefined) {
|
||||
next.add(key);
|
||||
}
|
||||
}
|
||||
return {
|
||||
active: true,
|
||||
selectedKeys: next,
|
||||
anchorKey: state.anchorKey,
|
||||
};
|
||||
}
|
||||
|
||||
export function reconcileWorkspaceSelection(
|
||||
state: WorkspaceSelectionState,
|
||||
availableKeys: ReadonlySet<string>,
|
||||
): WorkspaceSelectionState {
|
||||
if (!state.active) return state;
|
||||
|
||||
let changed = false;
|
||||
const next = new Set<string>();
|
||||
for (const key of state.selectedKeys) {
|
||||
if (availableKeys.has(key)) {
|
||||
next.add(key);
|
||||
} else {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
const nextAnchor = state.anchorKey && availableKeys.has(state.anchorKey) ? state.anchorKey : null;
|
||||
if (!changed && nextAnchor === state.anchorKey) {
|
||||
return state;
|
||||
}
|
||||
|
||||
return {
|
||||
active: true,
|
||||
selectedKeys: changed ? next : state.selectedKeys,
|
||||
anchorKey: nextAnchor,
|
||||
};
|
||||
}
|
||||
|
||||
export function exitWorkspaceSelection(): WorkspaceSelectionState {
|
||||
return INITIAL_WORKSPACE_SELECTION_STATE;
|
||||
}
|
||||
|
||||
export function isShiftPressEvent(
|
||||
event: unknown,
|
||||
isHardwareShiftDown: () => boolean = isShiftKeyDown,
|
||||
): boolean {
|
||||
if (typeof event === "object" && event !== null) {
|
||||
if (Reflect.get(event, "shiftKey") === true) return true;
|
||||
const nativeEvent = Reflect.get(event, "nativeEvent");
|
||||
if (
|
||||
typeof nativeEvent === "object" &&
|
||||
nativeEvent !== null &&
|
||||
Reflect.get(nativeEvent, "shiftKey") === true
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return isHardwareShiftDown();
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { create } from "zustand";
|
||||
import {
|
||||
enterWorkspaceSelection,
|
||||
exitWorkspaceSelection,
|
||||
INITIAL_WORKSPACE_SELECTION_STATE,
|
||||
reconcileWorkspaceSelection,
|
||||
selectWorkspaceRange,
|
||||
toggleWorkspaceSelection,
|
||||
type WorkspaceSelectionState,
|
||||
} from "./selection-state";
|
||||
|
||||
type VisibleKeysReader = () => readonly string[];
|
||||
|
||||
let visibleKeysReader: VisibleKeysReader = () => [];
|
||||
|
||||
/**
|
||||
* Registers a synchronous reader for the currently rendered sidebar workspace order so Shift+click
|
||||
* range selection walks only rows on screen without causing re-renders when the order changes.
|
||||
*/
|
||||
export function registerSidebarVisibleWorkspaceKeysReader(reader: VisibleKeysReader): () => void {
|
||||
visibleKeysReader = reader;
|
||||
return () => {
|
||||
if (visibleKeysReader === reader) {
|
||||
visibleKeysReader = () => [];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
interface SidebarSelectionStoreState extends WorkspaceSelectionState {
|
||||
isArchiving: boolean;
|
||||
enter: (workspaceKey: string) => void;
|
||||
pressWorkspace: (workspaceKey: string, options: { shiftKey: boolean }) => void;
|
||||
reconcile: (availableKeys: ReadonlySet<string>) => void;
|
||||
setArchiving: (archiving: boolean) => void;
|
||||
exit: () => void;
|
||||
}
|
||||
|
||||
export const useSidebarSelectionStore = create<SidebarSelectionStoreState>((set) => ({
|
||||
...INITIAL_WORKSPACE_SELECTION_STATE,
|
||||
isArchiving: false,
|
||||
enter: (workspaceKey) =>
|
||||
set(() => ({
|
||||
...enterWorkspaceSelection(workspaceKey),
|
||||
isArchiving: false,
|
||||
})),
|
||||
pressWorkspace: (workspaceKey, { shiftKey }) =>
|
||||
set((state) => {
|
||||
if (state.isArchiving) return state;
|
||||
const next = shiftKey
|
||||
? selectWorkspaceRange(state, workspaceKey, visibleKeysReader())
|
||||
: toggleWorkspaceSelection(state, workspaceKey);
|
||||
return next === state ? state : { ...next };
|
||||
}),
|
||||
reconcile: (availableKeys) =>
|
||||
set((state) => {
|
||||
const next = reconcileWorkspaceSelection(state, availableKeys);
|
||||
return next === state ? state : { ...next };
|
||||
}),
|
||||
setArchiving: (isArchiving) => set({ isArchiving }),
|
||||
exit: () =>
|
||||
set((state) =>
|
||||
state.active || state.isArchiving
|
||||
? { ...exitWorkspaceSelection(), isArchiving: false }
|
||||
: state,
|
||||
),
|
||||
}));
|
||||
|
||||
export function useIsSidebarSelectionMode(): boolean {
|
||||
return useSidebarSelectionStore((state) => state.active);
|
||||
}
|
||||
|
||||
export function useIsWorkspaceBulkSelected(workspaceKey: string): boolean {
|
||||
return useSidebarSelectionStore((state) => state.active && state.selectedKeys.has(workspaceKey));
|
||||
}
|
||||
|
||||
export function useSidebarSelectionCount(): number {
|
||||
return useSidebarSelectionStore((state) => (state.active ? state.selectedKeys.size : 0));
|
||||
}
|
||||
|
||||
export function useSidebarSelectionArchiving(): boolean {
|
||||
return useSidebarSelectionStore((state) => state.isArchiving);
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import React, { act, useCallback } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import { Text } from "react-native";
|
||||
import { SafeAreaProvider } from "react-native-safe-area-context";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { SidebarToastRegion } from "@/components/sidebar/sidebar-toast-region";
|
||||
import { SidebarWorkspaceContextMenu } from "@/components/sidebar/sidebar-workspace-menu";
|
||||
import { ToastProvider, useToast } from "@/contexts/toast-context";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { dispatchTopOverlayKeyDown } from "@/keyboard";
|
||||
import {
|
||||
KeyboardActionDispatcherProvider,
|
||||
useKeyboardActionDispatcher,
|
||||
} from "@/keyboard/keyboard-action-dispatcher-context";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import {
|
||||
isShiftPressEvent,
|
||||
registerSidebarVisibleWorkspaceKeysReader,
|
||||
SidebarSelectionHost,
|
||||
useIsSidebarSelectionMode,
|
||||
useIsWorkspaceBulkSelected,
|
||||
useSidebarSelectionStore,
|
||||
} from "@/sidebar-selection";
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement | null = null;
|
||||
let releaseVisibleKeys: (() => void) | null = null;
|
||||
|
||||
function makeEntry(id: string): SidebarWorkspaceEntry {
|
||||
return {
|
||||
workspaceKey: `srv:${id}`,
|
||||
workspaceId: id,
|
||||
serverId: "srv",
|
||||
projectViewKey: "prj-view",
|
||||
projectName: "Repo",
|
||||
projectRootPath: "/repo",
|
||||
workspaceDirectory: `/repo/${id}`,
|
||||
workspaceDirectoryLabel: id,
|
||||
projectKind: "git",
|
||||
workspaceKind: "local_checkout",
|
||||
name: id,
|
||||
title: null,
|
||||
currentBranch: id,
|
||||
statusBucket: "done",
|
||||
statusEnteredAt: null,
|
||||
archivingAt: null,
|
||||
diffStat: null,
|
||||
prHint: null,
|
||||
pinnedAt: null,
|
||||
background: false,
|
||||
labels: [],
|
||||
scripts: [],
|
||||
hasRunningScripts: false,
|
||||
archiveHasUncommittedChanges: null,
|
||||
archiveUnpushedCommitCount: null,
|
||||
};
|
||||
}
|
||||
|
||||
let capturedDispatcher: ReturnType<typeof useKeyboardActionDispatcher> | null = null;
|
||||
let capturedSidebarToast: ToastApi | null = null;
|
||||
let fallbackArchiveCount = 0;
|
||||
|
||||
function FallbackArchiveProbe() {
|
||||
capturedDispatcher = useKeyboardActionDispatcher();
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "test-global-workspace-archive-fallback",
|
||||
actions: ["workspace.archive"],
|
||||
enabled: true,
|
||||
priority: 0,
|
||||
handle: () => {
|
||||
fallbackArchiveCount += 1;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
function SidebarToastProbe() {
|
||||
capturedSidebarToast = useToast();
|
||||
return null;
|
||||
}
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
function SelectableRowProbe({ entry }: { entry: SidebarWorkspaceEntry }) {
|
||||
const isSelectionMode = useIsSidebarSelectionMode();
|
||||
const isBulkSelected = useIsWorkspaceBulkSelected(entry.workspaceKey);
|
||||
const handlePress = useCallback(
|
||||
(event: unknown) => {
|
||||
const shiftKey = isShiftPressEvent(event);
|
||||
if (isSelectionMode || shiftKey) {
|
||||
useSidebarSelectionStore.getState().pressWorkspace(entry.workspaceKey, { shiftKey });
|
||||
}
|
||||
},
|
||||
[entry.workspaceKey, isSelectionMode],
|
||||
);
|
||||
return (
|
||||
<SidebarWorkspaceContextMenu
|
||||
contextMenuOpen={false}
|
||||
onContextMenuOpenChange={noop}
|
||||
workspace={entry}
|
||||
workspaceKey={entry.workspaceKey}
|
||||
enabled={!isSelectionMode}
|
||||
accessibilityRole={isSelectionMode ? "checkbox" : "button"}
|
||||
aria-checked={isSelectionMode ? isBulkSelected : undefined}
|
||||
highlightStyle={undefined}
|
||||
onPress={handlePress}
|
||||
testID={`sidebar-workspace-row-${entry.workspaceKey}`}
|
||||
>
|
||||
<Text>{entry.name}</Text>
|
||||
</SidebarWorkspaceContextMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function mountHost(entries: readonly SidebarWorkspaceEntry[]) {
|
||||
const entriesByKey = new Map(entries.map((entry) => [entry.workspaceKey, entry]));
|
||||
releaseVisibleKeys = registerSidebarVisibleWorkspaceKeysReader(() =>
|
||||
entries.map((entry) => entry.workspaceKey),
|
||||
);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<SafeAreaProvider>
|
||||
<KeyboardActionDispatcherProvider>
|
||||
<FallbackArchiveProbe />
|
||||
<ToastProvider>
|
||||
<SidebarToastRegion active>
|
||||
<SidebarToastProbe />
|
||||
{entries.map((entry) => (
|
||||
<SelectableRowProbe key={entry.workspaceKey} entry={entry} />
|
||||
))}
|
||||
<SidebarSelectionHost active workspaceEntriesByKey={entriesByKey} />
|
||||
</SidebarToastRegion>
|
||||
</ToastProvider>
|
||||
</KeyboardActionDispatcherProvider>
|
||||
</SafeAreaProvider>
|
||||
</I18nextProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
capturedDispatcher = null;
|
||||
capturedSidebarToast = null;
|
||||
fallbackArchiveCount = 0;
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().exit();
|
||||
});
|
||||
releaseVisibleKeys?.();
|
||||
releaseVisibleKeys = null;
|
||||
act(() => root?.unmount());
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
});
|
||||
|
||||
describe("SidebarSelectionHost", () => {
|
||||
it("shows a persistent sidebar toast while selecting, updates without Shift, and exits via button or Escape", async () => {
|
||||
mountHost([makeEntry("a"), makeEntry("b"), makeEntry("c")]);
|
||||
expect(document.querySelector('[data-testid="workspace-selection-toast"]')).toBeNull();
|
||||
|
||||
// Enter select mode via Shift+click on "a", then plain-click "c" without Shift.
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: true });
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"1 selected",
|
||||
);
|
||||
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { shiftKey: false });
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"2 selected",
|
||||
);
|
||||
|
||||
// Clicking the Exit button leaves select mode and fades the persistent toast out.
|
||||
const exitButton = document.querySelector<HTMLElement>(
|
||||
'[data-testid="workspace-selection-exit"]',
|
||||
);
|
||||
expect(exitButton).not.toBeNull();
|
||||
act(() => {
|
||||
exitButton?.click();
|
||||
});
|
||||
expect(useSidebarSelectionStore.getState().active).toBe(false);
|
||||
await expect
|
||||
.poll(() => document.querySelector('[data-testid="workspace-selection-toast"]'))
|
||||
.toBeNull();
|
||||
|
||||
// Re-enter with Shift+click, then Shift+click "c" for a range of 3, and exit with Escape.
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: true });
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:c", { shiftKey: true });
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"3 selected",
|
||||
);
|
||||
|
||||
let prevented = false;
|
||||
act(() => {
|
||||
const handled = dispatchTopOverlayKeyDown({
|
||||
key: "Escape",
|
||||
code: "Escape",
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
repeat: false,
|
||||
preventDefault: () => {
|
||||
prevented = true;
|
||||
},
|
||||
stopPropagation: () => {},
|
||||
});
|
||||
expect(handled).toBe(true);
|
||||
});
|
||||
expect(prevented).toBe(true);
|
||||
expect(useSidebarSelectionStore.getState().active).toBe(false);
|
||||
await expect
|
||||
.poll(() => document.querySelector('[data-testid="workspace-selection-toast"]'))
|
||||
.toBeNull();
|
||||
});
|
||||
|
||||
it("consumes workspace.archive while in select mode even with zero rows selected or while archiving", () => {
|
||||
mountHost([makeEntry("a"), makeEntry("b")]);
|
||||
|
||||
// Outside select mode, the global fallback receives workspace.archive.
|
||||
act(() => {
|
||||
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
expect(fallbackArchiveCount).toBe(1);
|
||||
|
||||
// Enter select mode then deselect the only row -> 0 selected.
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().enter("srv:a");
|
||||
useSidebarSelectionStore.getState().pressWorkspace("srv:a", { shiftKey: false });
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"0 selected",
|
||||
);
|
||||
|
||||
// The archive shortcut must be absorbed by select mode rather than archiving the open workspace.
|
||||
act(() => {
|
||||
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
expect(fallbackArchiveCount).toBe(1);
|
||||
|
||||
// Same while a worktree safety check is in progress (both archive shortcut and Escape stay owned).
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().enter("srv:a");
|
||||
useSidebarSelectionStore.getState().setArchiving(true);
|
||||
});
|
||||
act(() => {
|
||||
expect(capturedDispatcher?.dispatch({ id: "workspace.archive", scope: "sidebar" })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
dispatchTopOverlayKeyDown({
|
||||
key: "Escape",
|
||||
code: "Escape",
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
repeat: false,
|
||||
preventDefault: () => {},
|
||||
stopPropagation: () => {},
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
expect(fallbackArchiveCount).toBe(1);
|
||||
expect(useSidebarSelectionStore.getState().active).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the selection bar visible when an Undo toast is already displayed in the sidebar", () => {
|
||||
mountHost([makeEntry("a"), makeEntry("b")]);
|
||||
|
||||
let dismissUndo: (() => void) | undefined;
|
||||
act(() => {
|
||||
dismissUndo = capturedSidebarToast?.show("Workspace archived", {
|
||||
durationMs: 6000,
|
||||
testID: "workspace-archived-toast",
|
||||
});
|
||||
});
|
||||
expect(document.querySelector('[data-testid="workspace-archived-toast"]')).not.toBeNull();
|
||||
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().enter("srv:a");
|
||||
});
|
||||
|
||||
// Both the Undo toast and the selection bar (count, Archive, Exit) must remain visible.
|
||||
expect(document.querySelector('[data-testid="workspace-archived-toast"]')).not.toBeNull();
|
||||
expect(document.querySelector('[data-testid="workspace-selection-toast"]')).not.toBeNull();
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"1 selected",
|
||||
);
|
||||
expect(document.querySelector('[data-testid="workspace-selection-archive"]')).not.toBeNull();
|
||||
expect(document.querySelector('[data-testid="workspace-selection-exit"]')).not.toBeNull();
|
||||
|
||||
act(() => {
|
||||
dismissUndo?.();
|
||||
});
|
||||
});
|
||||
|
||||
it("toggles focused workspace checkboxes when pressing Space in select mode", () => {
|
||||
mountHost([makeEntry("a"), makeEntry("b")]);
|
||||
|
||||
act(() => {
|
||||
useSidebarSelectionStore.getState().enter("srv:a");
|
||||
});
|
||||
|
||||
const rowB = document.querySelector<HTMLElement>('[data-testid="sidebar-workspace-row-srv:b"]');
|
||||
expect(rowB?.getAttribute("role")).toBe("checkbox");
|
||||
expect(rowB?.getAttribute("aria-checked")).toBe("false");
|
||||
|
||||
act(() => {
|
||||
rowB?.focus();
|
||||
rowB?.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true }),
|
||||
);
|
||||
rowB?.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: " ", repeat: true, bubbles: true, cancelable: true }),
|
||||
);
|
||||
});
|
||||
expect(rowB?.getAttribute("aria-checked")).toBe("true");
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"2 selected",
|
||||
);
|
||||
|
||||
act(() => {
|
||||
rowB?.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: " ", bubbles: true, cancelable: true }),
|
||||
);
|
||||
});
|
||||
expect(rowB?.getAttribute("aria-checked")).toBe("false");
|
||||
expect(document.querySelector('[data-testid="workspace-selection-count"]')?.textContent).toBe(
|
||||
"1 selected",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import {
|
||||
useSidebarAppToast,
|
||||
useSidebarPersistentToast,
|
||||
} from "@/components/sidebar/sidebar-toast-region";
|
||||
import type { ToastState } from "@/components/toast-host";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
|
||||
import { useOverlayRegistration } from "@/keyboard";
|
||||
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { archiveSelectedWorkspaces, createDefaultBulkArchiveDeps } from "./archive-selected";
|
||||
import {
|
||||
useIsSidebarSelectionMode,
|
||||
useSidebarSelectionArchiving,
|
||||
useSidebarSelectionCount,
|
||||
useSidebarSelectionStore,
|
||||
} from "./selection-store";
|
||||
import { WorkspaceSelectionToast } from "./workspace-selection-toast";
|
||||
|
||||
const SELECTION_TOAST_ID = -1;
|
||||
const ESCAPE_OVERLAY_KEYS = ["Escape"] as const;
|
||||
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
|
||||
|
||||
/**
|
||||
* Coordinates sidebar workspace select mode: reconciles removed workspaces, binds Escape and
|
||||
* the archive shortcut, and keeps the persistent selection bar up in `SidebarToastRegion`.
|
||||
*/
|
||||
export function SidebarSelectionHost({
|
||||
active,
|
||||
workspaceEntriesByKey,
|
||||
}: {
|
||||
active: boolean;
|
||||
workspaceEntriesByKey: ReadonlyMap<string, SidebarWorkspaceEntry>;
|
||||
}): null {
|
||||
const toast = useToast();
|
||||
const appToast = useSidebarAppToast();
|
||||
const activeWorkspaceSelection = useActiveWorkspaceSelection();
|
||||
const selectionMode = useIsSidebarSelectionMode();
|
||||
const selectedCount = useSidebarSelectionCount();
|
||||
const isArchiving = useSidebarSelectionArchiving();
|
||||
|
||||
const entriesRef = useRef(workspaceEntriesByKey);
|
||||
entriesRef.current = workspaceEntriesByKey;
|
||||
const activeSelectionRef = useRef(activeWorkspaceSelection);
|
||||
activeSelectionRef.current = activeWorkspaceSelection;
|
||||
const archiveAttemptRef = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectionMode) return;
|
||||
useSidebarSelectionStore.getState().reconcile(new Set(workspaceEntriesByKey.keys()));
|
||||
}, [selectionMode, workspaceEntriesByKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (active) return;
|
||||
const state = useSidebarSelectionStore.getState();
|
||||
if (state.active && !state.isArchiving) {
|
||||
state.exit();
|
||||
}
|
||||
}, [active]);
|
||||
|
||||
const handleExit = useCallback(() => {
|
||||
const state = useSidebarSelectionStore.getState();
|
||||
if (state.isArchiving) return;
|
||||
state.exit();
|
||||
}, []);
|
||||
|
||||
const handleArchiveSelected = useCallback(() => {
|
||||
const store = useSidebarSelectionStore.getState();
|
||||
if (!store.active || store.isArchiving || store.selectedKeys.size === 0) return;
|
||||
|
||||
const entries: SidebarWorkspaceEntry[] = [];
|
||||
for (const key of store.selectedKeys) {
|
||||
const entry = entriesRef.current.get(key);
|
||||
if (entry && entry.archivingAt === null) {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
if (entries.length === 0) {
|
||||
store.exit();
|
||||
return;
|
||||
}
|
||||
|
||||
const attemptId = archiveAttemptRef.current + 1;
|
||||
archiveAttemptRef.current = attemptId;
|
||||
store.setArchiving(true);
|
||||
void archiveSelectedWorkspaces({
|
||||
workspaces: entries,
|
||||
toast,
|
||||
fallbackErrorToast: appToast,
|
||||
onArchiveStarted: () => {
|
||||
useSidebarSelectionStore.getState().exit();
|
||||
},
|
||||
deps: createDefaultBulkArchiveDeps(() => activeSelectionRef.current),
|
||||
}).finally(() => {
|
||||
if (archiveAttemptRef.current !== attemptId) return;
|
||||
const current = useSidebarSelectionStore.getState();
|
||||
if (current.isArchiving) {
|
||||
current.setArchiving(false);
|
||||
}
|
||||
});
|
||||
}, [appToast, toast]);
|
||||
|
||||
useOverlayRegistration({
|
||||
keys: ESCAPE_OVERLAY_KEYS,
|
||||
// Keep Escape owned while select mode is active (including during worktree checks) so it
|
||||
// never falls through to interrupt a running agent in the open workspace; any higher-layer
|
||||
// confirmation dialog still receives Escape first.
|
||||
active: selectionMode && active,
|
||||
layer: 0,
|
||||
manageFocus: false,
|
||||
onKeyDown: (event) => {
|
||||
if (event.key !== "Escape") return false;
|
||||
event.preventDefault();
|
||||
handleExit();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "sidebar-selection-archive",
|
||||
actions: WORKSPACE_ARCHIVE_ACTIONS,
|
||||
// Keep ownership of workspace.archive for the entire lifetime of select mode so pressing it
|
||||
// at 0 selected or during a worktree check never falls through to archive the open workspace.
|
||||
enabled: selectionMode && active,
|
||||
priority: 10,
|
||||
handle: () => {
|
||||
handleArchiveSelected();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
const persistentToast = useMemo<ToastState | null>(() => {
|
||||
if (!selectionMode || !active) return null;
|
||||
return {
|
||||
id: SELECTION_TOAST_ID,
|
||||
content: (
|
||||
<WorkspaceSelectionToast
|
||||
selectedCount={selectedCount}
|
||||
isArchiving={isArchiving}
|
||||
onArchive={handleArchiveSelected}
|
||||
onExit={handleExit}
|
||||
/>
|
||||
),
|
||||
nativeMessage: null,
|
||||
variant: "default",
|
||||
layout: "action",
|
||||
durationMs: null,
|
||||
testID: "workspace-selection-toast",
|
||||
};
|
||||
}, [active, handleArchiveSelected, handleExit, isArchiving, selectedCount, selectionMode]);
|
||||
|
||||
useSidebarPersistentToast(persistentToast);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { X } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry";
|
||||
import { DensityIcon } from "@/components/ui/density-icon";
|
||||
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
|
||||
const EXIT_SHORTCUT_CHORD: ShortcutKey[][] = [["Esc"]];
|
||||
|
||||
export function WorkspaceSelectionToast({
|
||||
selectedCount,
|
||||
isArchiving,
|
||||
onArchive,
|
||||
onExit,
|
||||
}: {
|
||||
selectedCount: number;
|
||||
isArchiving: boolean;
|
||||
onArchive: () => void;
|
||||
onExit: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const exitLabel = t("sidebar.workspace.selection.exit");
|
||||
|
||||
return (
|
||||
<View style={styles.row}>
|
||||
<Text style={styles.message} numberOfLines={1} testID="workspace-selection-count">
|
||||
{t("sidebar.workspace.selection.count", { count: selectedCount })}
|
||||
</Text>
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
size="sm"
|
||||
onPress={onArchive}
|
||||
disabled={selectedCount === 0}
|
||||
loading={isArchiving}
|
||||
testID="workspace-selection-archive"
|
||||
>
|
||||
{t("sidebar.workspace.actions.archive")}
|
||||
</Button>
|
||||
<ToolbarButton
|
||||
round
|
||||
tooltipSide="top"
|
||||
label={exitLabel}
|
||||
shortcut={EXIT_SHORTCUT_CHORD}
|
||||
onPress={onExit}
|
||||
disabled={isArchiving}
|
||||
style={styles.exitButton}
|
||||
testID="workspace-selection-exit"
|
||||
>
|
||||
<DensityIcon icon={X} size="sm" color="foregroundMuted" />
|
||||
</ToolbarButton>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
message: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
// Matches the Archive button's sm pill height so the circular hover fill sits concentrically
|
||||
// in the action toast's trailing corner.
|
||||
exitButton: {
|
||||
width: CONTROL_HEIGHTS.sm,
|
||||
height: CONTROL_HEIGHTS.sm,
|
||||
},
|
||||
}));
|
||||
@@ -517,6 +517,7 @@ export const HOST_SECTION_SLUGS = [
|
||||
"connections",
|
||||
"pair-device",
|
||||
"agents",
|
||||
"agent-profiles",
|
||||
"metadata",
|
||||
"voice",
|
||||
"workspaces",
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
export {
|
||||
archiveWorkspaceWithUndo,
|
||||
archiveWorkspacesWithUndo,
|
||||
hasUndoableWorkspaceArchive,
|
||||
undoLatestWorkspaceArchive,
|
||||
type UndoableWorkspaceArchiveClient,
|
||||
type UndoableWorkspaceArchiveEntryInput,
|
||||
type WorkspaceArchiveBatchFailure,
|
||||
type WorkspaceArchiveBatchResult,
|
||||
} from "./internal/undo-window";
|
||||
export { WorkspaceArchiveUndoShortcutHost } from "./internal/undo-shortcut-host";
|
||||
export { supportsWorkspaceArchiveUndo } from "./internal/capability";
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-stor
|
||||
import { seedSessionHosts } from "@/test/seed-session";
|
||||
import {
|
||||
archiveWorkspaceWithUndo,
|
||||
archiveWorkspacesWithUndo,
|
||||
undoLatestWorkspaceArchive,
|
||||
type UndoableWorkspaceArchiveClient,
|
||||
} from "@/workspace/archive-undo";
|
||||
@@ -82,6 +83,9 @@ function createToastHost() {
|
||||
get shownTestID() {
|
||||
return shown?.options?.testID ?? null;
|
||||
},
|
||||
get shownVariant() {
|
||||
return shown?.options?.variant ?? null;
|
||||
},
|
||||
timeOut: () => shown?.dismiss(),
|
||||
};
|
||||
}
|
||||
@@ -299,3 +303,166 @@ describe("archiveWorkspaceWithUndo", () => {
|
||||
}).toEqual({ toast: null, undone: false, row: workspace("a") });
|
||||
});
|
||||
});
|
||||
|
||||
describe("archiveWorkspacesWithUndo", () => {
|
||||
it("hides every workspace in the batch and undoes all of them together", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
const committed: string[] = [];
|
||||
|
||||
const batch = archiveWorkspacesWithUndo({
|
||||
entries: [
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "a" },
|
||||
onArchiveCommitted: () => committed.push("a"),
|
||||
},
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "b" },
|
||||
onArchiveCommitted: () => committed.push("b"),
|
||||
},
|
||||
],
|
||||
toast: toast.api,
|
||||
});
|
||||
|
||||
expect(storedWorkspace("a")).toBeUndefined();
|
||||
expect(storedWorkspace("b")).toBeUndefined();
|
||||
expect(toast.shownTestID).toBe("workspace-archived-toast");
|
||||
|
||||
expect(undoLatestWorkspaceArchive()).toBe(true);
|
||||
expect({
|
||||
a: storedWorkspace("a"),
|
||||
b: storedWorkspace("b"),
|
||||
undoA: host.undoRequested("a"),
|
||||
undoB: host.undoRequested("b"),
|
||||
toast: toast.shownTestID,
|
||||
}).toEqual({
|
||||
a: workspace("a"),
|
||||
b: workspace("b"),
|
||||
undoA: true,
|
||||
undoB: true,
|
||||
toast: null,
|
||||
});
|
||||
|
||||
host.finishArchive("a", { canceled: true });
|
||||
host.finishArchive("b", { canceled: true });
|
||||
await expect(batch.then((result) => result.failures)).resolves.toEqual([]);
|
||||
host.finishUndo("a");
|
||||
host.finishUndo("b");
|
||||
expect(committed).toEqual([]);
|
||||
});
|
||||
|
||||
it("commits every workspace in the batch when the toast times out", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
const committed: string[] = [];
|
||||
|
||||
const batch = archiveWorkspacesWithUndo({
|
||||
entries: [
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "a" },
|
||||
onArchiveCommitted: () => committed.push("a"),
|
||||
},
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "b" },
|
||||
onArchiveCommitted: () => committed.push("b"),
|
||||
},
|
||||
],
|
||||
toast: toast.api,
|
||||
});
|
||||
|
||||
host.finishArchive("a");
|
||||
host.finishArchive("b");
|
||||
await expect(batch.then((result) => result.failures)).resolves.toEqual([]);
|
||||
expect(committed).toEqual([]);
|
||||
|
||||
toast.timeOut();
|
||||
expect(committed).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
it("restores only the failed workspace on partial failure and keeps undo open when surfacing the error", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
const committed: string[] = [];
|
||||
|
||||
const batch = archiveWorkspacesWithUndo({
|
||||
entries: [
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "a" },
|
||||
onArchiveCommitted: () => committed.push("a"),
|
||||
},
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "b" },
|
||||
onArchiveCommitted: () => committed.push("b"),
|
||||
},
|
||||
],
|
||||
toast: toast.api,
|
||||
});
|
||||
|
||||
host.finishArchive("a");
|
||||
host.finishArchive("b", { error: "busy" });
|
||||
const { failures, showPartialFailure } = await batch;
|
||||
|
||||
expect(failures).toHaveLength(1);
|
||||
expect(failures[0]?.workspace.workspaceId).toBe("b");
|
||||
expect(storedWorkspace("a")).toBeUndefined();
|
||||
expect(storedWorkspace("b")).toEqual(workspace("b"));
|
||||
|
||||
// Updating the toast with the partial-failure error must not dismiss Undo or commit "a".
|
||||
expect(showPartialFailure("busy")).toBe(true);
|
||||
expect({
|
||||
toast: toast.shownTestID,
|
||||
variant: toast.shownVariant,
|
||||
committed,
|
||||
}).toEqual({
|
||||
toast: "workspace-archived-toast",
|
||||
variant: "error",
|
||||
committed: [],
|
||||
});
|
||||
|
||||
expect(undoLatestWorkspaceArchive()).toBe(true);
|
||||
expect({ undoA: host.undoRequested("a"), undoB: host.undoRequested("b") }).toEqual({
|
||||
undoA: true,
|
||||
undoB: false,
|
||||
});
|
||||
expect(committed).toEqual([]);
|
||||
});
|
||||
|
||||
it("commits surviving workspaces once a partial-failure undo toast times out", async () => {
|
||||
const host = createClient();
|
||||
const toast = createToastHost();
|
||||
const committed: string[] = [];
|
||||
|
||||
const batch = archiveWorkspacesWithUndo({
|
||||
entries: [
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "a" },
|
||||
onArchiveCommitted: () => committed.push("a"),
|
||||
},
|
||||
{
|
||||
client: host.client,
|
||||
workspace: { serverId: SERVER_ID, workspaceId: "b" },
|
||||
onArchiveCommitted: () => committed.push("b"),
|
||||
},
|
||||
],
|
||||
toast: toast.api,
|
||||
});
|
||||
|
||||
host.finishArchive("a");
|
||||
host.finishArchive("b", { error: "busy" });
|
||||
const { showPartialFailure } = await batch;
|
||||
|
||||
expect(showPartialFailure("busy")).toBe(true);
|
||||
expect(committed).toEqual([]);
|
||||
|
||||
toast.timeOut();
|
||||
expect(committed).toEqual(["a"]);
|
||||
expect(undoLatestWorkspaceArchive()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,18 +17,28 @@ export interface UndoableWorkspaceArchiveClient {
|
||||
undoWorkspaceArchive: (workspaceId: string) => Promise<void>;
|
||||
}
|
||||
|
||||
interface UndoWindowInput {
|
||||
export interface UndoableWorkspaceArchiveEntryInput {
|
||||
client: UndoableWorkspaceArchiveClient;
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
toast: ToastApi;
|
||||
hidden: WorkspaceDescriptor | null;
|
||||
onArchiveCommitted: () => void;
|
||||
}
|
||||
|
||||
interface UndoWindowEntry extends UndoableWorkspaceArchiveEntryInput {
|
||||
hidden: WorkspaceDescriptor | null;
|
||||
archived: boolean;
|
||||
failed: boolean;
|
||||
committed: boolean;
|
||||
}
|
||||
|
||||
interface UndoWindowInput {
|
||||
entries: UndoWindowEntry[];
|
||||
toast: ToastApi;
|
||||
}
|
||||
|
||||
let latest: UndoWindow | null = null;
|
||||
|
||||
/**
|
||||
* One archive's chance to be undone. It opens when the row hides and closes when its toast
|
||||
* One archive batch's chance to be undone. It opens when the row(s) hide and closes when its toast
|
||||
* leaves the screen (timeout, replaced by another toast, or undo).
|
||||
*
|
||||
* - `open`: undo is offered.
|
||||
@@ -37,40 +47,78 @@ let latest: UndoWindow | null = null;
|
||||
*/
|
||||
class UndoWindow {
|
||||
phase: "open" | "closed" | "undone" = "open";
|
||||
private archived = false;
|
||||
private readonly dismissToast: DismissToast;
|
||||
private dismissToast: DismissToast = () => {};
|
||||
private toastToken: object | null = null;
|
||||
|
||||
constructor(private readonly input: UndoWindowInput) {
|
||||
this.dismissToast = input.toast.show(<WorkspaceArchivedToast onUndo={this.undo} />, {
|
||||
durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS,
|
||||
testID: "workspace-archived-toast",
|
||||
onDismiss: this.close,
|
||||
});
|
||||
this.showToast({ variant: "default" });
|
||||
}
|
||||
|
||||
/** The host finished the archive. It commits now if undo is no longer offered. */
|
||||
archiveFinished(): void {
|
||||
this.archived = true;
|
||||
if (this.phase === "closed") this.commit();
|
||||
private showToast(options: { message?: string; variant: "default" | "error" }): void {
|
||||
const token = {};
|
||||
this.toastToken = token;
|
||||
const remainingCount = this.input.entries.filter((entry) => !entry.failed).length;
|
||||
this.dismissToast = this.input.toast.show(
|
||||
<WorkspaceArchivedToast
|
||||
count={remainingCount}
|
||||
message={options.message}
|
||||
onUndo={this.undo}
|
||||
/>,
|
||||
{
|
||||
variant: options.variant,
|
||||
layout: "action",
|
||||
durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS,
|
||||
testID: "workspace-archived-toast",
|
||||
onDismiss: () => {
|
||||
// Replacing our own toast in place (for example to surface a partial failure) must not
|
||||
// close the undo window or purge surviving workspaces.
|
||||
if (this.toastToken !== token) return;
|
||||
this.close();
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** The archive failed on the host, so there is nothing left to undo. */
|
||||
archiveFailed(): void {
|
||||
this.close();
|
||||
this.dismissToast();
|
||||
/**
|
||||
* Surfaces a partial-failure message on the active undo toast without dismissing Undo for the
|
||||
* workspaces that did archive. Returns false once the window is closed, undone, or superseded.
|
||||
*/
|
||||
showPartialFailure(message: string): boolean {
|
||||
if (this.phase !== "open" || latest !== this) return false;
|
||||
this.showToast({ message, variant: "error" });
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The host finished archiving this entry. It commits now if undo is no longer offered. */
|
||||
entryFinished(entry: UndoWindowEntry): void {
|
||||
entry.archived = true;
|
||||
if (this.phase === "closed") this.commitEntry(entry);
|
||||
}
|
||||
|
||||
/** The archive failed on the host. Dismisses the toast once every entry has failed. */
|
||||
entryFailed(entry: UndoWindowEntry): void {
|
||||
entry.failed = true;
|
||||
if (this.input.entries.every((item) => item.failed)) {
|
||||
this.close();
|
||||
this.dismissToast();
|
||||
}
|
||||
}
|
||||
|
||||
readonly close = (): void => {
|
||||
if (this.phase !== "open") return;
|
||||
this.phase = "closed";
|
||||
this.release();
|
||||
if (this.archived) this.commit();
|
||||
for (const entry of this.input.entries) {
|
||||
if (entry.archived) this.commitEntry(entry);
|
||||
}
|
||||
};
|
||||
|
||||
/** Commits unless the workspace is back by now, for example restored from another client. */
|
||||
private commit(): void {
|
||||
if (isWorkspaceListed(this.input.workspace)) return;
|
||||
this.input.onArchiveCommitted();
|
||||
private commitEntry(entry: UndoWindowEntry): void {
|
||||
if (entry.committed || entry.failed) return;
|
||||
if (isWorkspaceListed(entry.workspace)) return;
|
||||
entry.committed = true;
|
||||
entry.onArchiveCommitted();
|
||||
}
|
||||
|
||||
readonly undo = (): boolean => {
|
||||
@@ -78,10 +126,19 @@ class UndoWindow {
|
||||
this.phase = "undone";
|
||||
this.release();
|
||||
this.dismissToast();
|
||||
void undoWorkspaceArchiveOptimistically(this.input).catch((error: unknown) => {
|
||||
console.warn("[workspace-archive-undo] undo failed", error);
|
||||
this.input.toast.error(i18n.t("sidebar.workspace.toasts.undoArchiveFailed"));
|
||||
});
|
||||
const undoable = this.input.entries.filter((entry) => !entry.failed);
|
||||
void (async () => {
|
||||
const results = await Promise.allSettled(
|
||||
undoable.map((entry) => undoWorkspaceArchiveOptimistically(entry)),
|
||||
);
|
||||
const failed = results.filter(
|
||||
(result): result is PromiseRejectedResult => result.status === "rejected",
|
||||
);
|
||||
if (failed.length > 0) {
|
||||
console.warn("[workspace-archive-undo] undo failed", failed[0]?.reason);
|
||||
this.input.toast.error(i18n.t("sidebar.workspace.toasts.undoArchiveFailed"));
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -90,6 +147,75 @@ class UndoWindow {
|
||||
}
|
||||
}
|
||||
|
||||
export interface WorkspaceArchiveBatchFailure {
|
||||
workspace: WorkspaceArchiveTarget;
|
||||
error: unknown;
|
||||
}
|
||||
|
||||
export interface WorkspaceArchiveBatchResult {
|
||||
failures: WorkspaceArchiveBatchFailure[];
|
||||
/**
|
||||
* Updates this batch's live undo toast to show a partial-failure error while keeping Undo active
|
||||
* for the workspaces that succeeded. Returns false if the undo window is no longer open.
|
||||
*/
|
||||
showPartialFailure: (message: string) => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Archives one or more workspaces together and offers one undo until the toast goes away.
|
||||
*
|
||||
* `onArchiveCommitted` runs per workspace once that archive both finished on the host and can no
|
||||
* longer be undone, and only if the workspace is still gone then. Returns failures for any
|
||||
* workspace whose archive failed while not undone; those rows are already restored.
|
||||
*/
|
||||
export async function archiveWorkspacesWithUndo(input: {
|
||||
entries: readonly UndoableWorkspaceArchiveEntryInput[];
|
||||
toast: ToastApi;
|
||||
}): Promise<WorkspaceArchiveBatchResult> {
|
||||
if (input.entries.length === 0) {
|
||||
return { failures: [], showPartialFailure: () => false };
|
||||
}
|
||||
|
||||
const started = input.entries.map((entry) => {
|
||||
const archive = beginOptimisticWorkspaceArchive(entry);
|
||||
const windowEntry: UndoWindowEntry = {
|
||||
...entry,
|
||||
hidden: archive.hidden,
|
||||
archived: false,
|
||||
failed: false,
|
||||
committed: false,
|
||||
};
|
||||
return { windowEntry, done: archive.done };
|
||||
});
|
||||
|
||||
const window = new UndoWindow({
|
||||
entries: started.map((item) => item.windowEntry),
|
||||
toast: input.toast,
|
||||
});
|
||||
latest = window;
|
||||
|
||||
const failures: WorkspaceArchiveBatchFailure[] = [];
|
||||
await Promise.all(
|
||||
started.map(async ({ windowEntry, done }) => {
|
||||
let outcome: Awaited<typeof done>;
|
||||
try {
|
||||
outcome = await done;
|
||||
} catch (error) {
|
||||
if (window.phase === "undone") return;
|
||||
window.entryFailed(windowEntry);
|
||||
failures.push({ workspace: windowEntry.workspace, error });
|
||||
return;
|
||||
}
|
||||
if (outcome === "archived") window.entryFinished(windowEntry);
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
failures,
|
||||
showPartialFailure: (message) => window.showPartialFailure(message),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Archives a workspace and offers to undo it until the toast goes away.
|
||||
*
|
||||
@@ -104,19 +230,19 @@ export async function archiveWorkspaceWithUndo(input: {
|
||||
toast: ToastApi;
|
||||
onArchiveCommitted: () => void;
|
||||
}): Promise<void> {
|
||||
const archive = beginOptimisticWorkspaceArchive(input);
|
||||
const window = new UndoWindow({ ...input, hidden: archive.hidden });
|
||||
latest = window;
|
||||
|
||||
let outcome: Awaited<typeof archive.done>;
|
||||
try {
|
||||
outcome = await archive.done;
|
||||
} catch (error) {
|
||||
if (window.phase === "undone") return;
|
||||
window.archiveFailed();
|
||||
throw error;
|
||||
const { failures } = await archiveWorkspacesWithUndo({
|
||||
entries: [
|
||||
{
|
||||
client: input.client,
|
||||
workspace: input.workspace,
|
||||
onArchiveCommitted: input.onArchiveCommitted,
|
||||
},
|
||||
],
|
||||
toast: input.toast,
|
||||
});
|
||||
if (failures[0]) {
|
||||
throw failures[0].error;
|
||||
}
|
||||
if (outcome === "archived") window.archiveFinished();
|
||||
}
|
||||
|
||||
/** Undoes the most recent archive while its toast is up. Returns false when there is none. */
|
||||
|
||||
@@ -6,17 +6,30 @@ import { Button } from "@/components/ui/button";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
|
||||
export function WorkspaceArchivedToast({ onUndo }: { onUndo: () => void }) {
|
||||
export function WorkspaceArchivedToast({
|
||||
count = 1,
|
||||
message: customMessage,
|
||||
onUndo,
|
||||
}: {
|
||||
count?: number;
|
||||
message?: string;
|
||||
onUndo: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const undoKeys = useShortcutKeys("undo-archive-workspace");
|
||||
const undoShortcut = useMemo(
|
||||
() => (undoKeys ? <Shortcut chord={undoKeys} style={styles.shortcut} /> : null),
|
||||
[undoKeys],
|
||||
);
|
||||
const message =
|
||||
customMessage ??
|
||||
(count === 1
|
||||
? t("sidebar.workspace.toasts.archived")
|
||||
: t("sidebar.workspace.toasts.archivedCount", { count }));
|
||||
|
||||
return (
|
||||
<View style={styles.row}>
|
||||
<Text style={styles.message}>{t("sidebar.workspace.toasts.archived")}</Text>
|
||||
<Text style={styles.message}>{message}</Text>
|
||||
<Button
|
||||
size="sm"
|
||||
onPress={onUndo}
|
||||
@@ -34,7 +47,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
// Cancels the badge's own inset, which would otherwise add to the button's gap.
|
||||
shortcut: {
|
||||
|
||||
@@ -44,6 +44,7 @@ export const EyeOff = StubIcon;
|
||||
export const File = StubIcon;
|
||||
export const FileText = StubIcon;
|
||||
export const Folder = StubIcon;
|
||||
export const FolderOpen = StubIcon;
|
||||
export const FolderPlus = StubIcon;
|
||||
export const FolderTree = StubIcon;
|
||||
export const Gift = StubIcon;
|
||||
@@ -107,6 +108,7 @@ export const SquareSlash = StubIcon;
|
||||
export const SquareTerminal = StubIcon;
|
||||
export const Star = StubIcon;
|
||||
export const Sun = StubIcon;
|
||||
export const Tag = StubIcon;
|
||||
export const Terminal = StubIcon;
|
||||
export const Trash2 = StubIcon;
|
||||
export const TriangleAlert = StubIcon;
|
||||
|
||||
@@ -58,6 +58,11 @@
|
||||
"types": "./dist/server/lifecycle.d.ts",
|
||||
"source": "./src/server/lifecycle.ts",
|
||||
"default": "./dist/server/lifecycle.js"
|
||||
},
|
||||
"./internal/windows-command": {
|
||||
"types": "./dist/server/process-internal/windows-command.d.ts",
|
||||
"source": "./src/server/process-internal/windows-command.ts",
|
||||
"default": "./dist/server/process-internal/windows-command.js"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
|
||||
@@ -14,6 +14,7 @@ const entries = {
|
||||
"./server/usage": "server",
|
||||
"./server/acp": "server",
|
||||
"./internal/lifecycle": "server",
|
||||
"./internal/windows-command": "server",
|
||||
"./client": "client",
|
||||
"./client/host": "client",
|
||||
"./client/ui": "client",
|
||||
@@ -392,7 +393,7 @@ describe("lifecycle hook SDK types", () => {
|
||||
it("infers payloads and replacement requests and requires async handlers and new names", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult } from "@getpaseo/plugin/server";
|
||||
import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult, PluginLaunchWrap } from "@getpaseo/plugin/server";
|
||||
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
server.addHook("worktree.create.before", async ({ request }) => {
|
||||
@@ -427,6 +428,38 @@ describe("lifecycle hook SDK types", () => {
|
||||
const { metadata, ...withoutMetadata } = request;
|
||||
return withoutMetadata;
|
||||
});
|
||||
server.addHook("agent.create.before", async ({ request }) => {
|
||||
const workspace: string | null = request.workspaceId;
|
||||
// @ts-expect-error The agent's workspace is read-only.
|
||||
request.workspaceId = "wks_other";
|
||||
});
|
||||
// Results built before workspaceId existed still typecheck; the daemon keeps the id.
|
||||
server.addHook("agent.create.before", async ({ request }) => ({ config: request.config, env: request.env }));
|
||||
server.before("agent.create", ({ request }) => ({ config: request.config, env: request.env }));
|
||||
server.addHook("terminal.create.before", async ({ request }) => {
|
||||
const source: "client" | "agent" | "script" | "worktree" = request.source;
|
||||
const input: string | null = request.input;
|
||||
const program: string | null = request.command;
|
||||
// @ts-expect-error The terminal's workspace is read-only.
|
||||
request.workspaceId = "wks_other";
|
||||
// @ts-expect-error The terminal's program is read-only; return a wrap instead.
|
||||
request.command = "/usr/bin/other";
|
||||
const wrap: PluginLaunchWrap = ["/usr/bin/sandbox", "--workspace", request.workspaceId];
|
||||
return { ...request, env: { A: "1" }, wrap };
|
||||
});
|
||||
server.addHook("command.run.before", async ({ request }) => {
|
||||
const workspace: string | null = request.workspaceId;
|
||||
const purpose: "setup" | "teardown" = request.purpose;
|
||||
// @ts-expect-error A command's purpose is read-only.
|
||||
request.purpose = "setup";
|
||||
// @ts-expect-error The configured command is read-only; return a wrap instead.
|
||||
request.command = "wrapper " + request.command;
|
||||
return { ...request, wrap: ["/usr/bin/sandbox"] };
|
||||
});
|
||||
server.addHook("agent.open.before", async ({ request }) => ({
|
||||
...request,
|
||||
wrap: ["/usr/bin/sandbox", "--workspace", request.workspaceId ?? "none"],
|
||||
}));
|
||||
server.addHook("agent.turn.after", async (event, { paseo, signal }) => {
|
||||
const { agent, outcome } = event;
|
||||
const kind: "completed" | "failed" | "canceled" = outcome.kind;
|
||||
|
||||
@@ -86,6 +86,8 @@ export async function createAcpProviderConnection(
|
||||
emit: () => undefined,
|
||||
});
|
||||
const supportedCapabilities: ProviderCapability[] = [...ADAPTER_CAPABILITIES];
|
||||
// A connector stream has no process of its own to wrap.
|
||||
if (options.command) supportedCapabilities.push("session.launch_wrap");
|
||||
if (probe.agentCapabilities.promptCapabilities?.image) {
|
||||
supportedCapabilities.push("prompt.image");
|
||||
}
|
||||
@@ -333,6 +335,7 @@ async function openSession(
|
||||
boundarySessionId: input.sessionId,
|
||||
cwd: input.config.cwd,
|
||||
env: input.config.env,
|
||||
wrap: input.config.wrap,
|
||||
emit: state.emit,
|
||||
onRetired: () => retireSession(state, input.sessionId),
|
||||
});
|
||||
@@ -375,6 +378,7 @@ interface StartRuntimeOptions {
|
||||
boundarySessionId: string;
|
||||
cwd?: string;
|
||||
env: Readonly<Record<string, string>>;
|
||||
wrap?: readonly [string, ...string[]];
|
||||
emit(event: ProviderEvent): void;
|
||||
onRetired?: () => void;
|
||||
}
|
||||
@@ -498,6 +502,7 @@ class AcpRuntime {
|
||||
env: process.env,
|
||||
};
|
||||
child = spawnProcess(launch.command, launch.args, {
|
||||
wrap: options.wrap,
|
||||
cwd: options.cwd,
|
||||
env: { ...launch.env, ...options.env },
|
||||
stdio: "pipe",
|
||||
@@ -511,6 +516,7 @@ class AcpRuntime {
|
||||
>[1];
|
||||
stream = ndJsonStream(output, input);
|
||||
} else {
|
||||
if (options.wrap) throw new Error("An ACP connector cannot run behind a launch wrap");
|
||||
const owned = ownConnectorStream(await options.options.connector());
|
||||
stream = owned.stream;
|
||||
closeConnector = owned.close;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import diagnosticsChannel from "node:diagnostics_channel";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -6166,7 +6168,6 @@ describe("deferTurnOnRunningTools", () => {
|
||||
);
|
||||
|
||||
const childPid = Number((await readFile(pidFile, "utf8")).trim());
|
||||
const startedAt = Date.now();
|
||||
await Promise.all([
|
||||
connection.send({
|
||||
type: "session.interrupt",
|
||||
@@ -6188,8 +6189,8 @@ describe("deferTurnOnRunningTools", () => {
|
||||
(event) => event.type === "request.completed" && event.requestId === "int-2",
|
||||
);
|
||||
|
||||
// Both interrupts waited for the 250ms SIGTERM exit, and process is now dead.
|
||||
expect(Date.now() - startedAt).toBeGreaterThanOrEqual(200);
|
||||
// Both interrupts waited for the process to exit. On POSIX it lives 250ms past SIGTERM, so an
|
||||
// interrupt that returned early would find it alive; Windows ends it at once.
|
||||
expect(() => process.kill(childPid, 0)).toThrow();
|
||||
|
||||
// Canceled turn and session.closed were each emitted exactly once.
|
||||
@@ -7125,3 +7126,187 @@ describe("ACP tool call rows", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("runAcpProvider launch wrap", () => {
|
||||
async function wrapFixture(): Promise<{
|
||||
agent: string;
|
||||
launchLog: string;
|
||||
/** The wrap that runs the recording launcher as Node, tagged so the agent can tell. */
|
||||
wrap: (tag: string) => [string, ...string[]];
|
||||
launches: () => Promise<Array<{ argv: string[]; token: string | null }>>;
|
||||
agentStarts: () => Promise<string[]>;
|
||||
}> {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-acp-wrap-"));
|
||||
temporaryDirectories.push(directory);
|
||||
const launchLog = path.join(directory, "launches.jsonl");
|
||||
const agentLog = path.join(directory, "agent.log");
|
||||
const launcher = path.join(directory, "launcher.cjs");
|
||||
// Consumes two arguments of its own (log path, tag), records what it saw, then runs the rest.
|
||||
await writeFile(
|
||||
launcher,
|
||||
`const { appendFileSync } = require("node:fs");
|
||||
const { spawn } = require("node:child_process");
|
||||
const [log, tag, command, ...args] = process.argv.slice(2);
|
||||
appendFileSync(log, JSON.stringify({ argv: process.argv.slice(2), token: process.env.SESSION_TOKEN ?? null }) + "\\n");
|
||||
const child = spawn(command, args, { stdio: "inherit", env: { ...process.env, WRAPPED_BY: tag } });
|
||||
process.on("SIGTERM", () => child.kill("SIGTERM"));
|
||||
child.on("exit", (code) => process.exit(code ?? 1));
|
||||
`,
|
||||
"utf8",
|
||||
);
|
||||
const agent = path.join(directory, "agent.cjs");
|
||||
await writeFile(
|
||||
agent,
|
||||
`const { appendFileSync } = require("node:fs");
|
||||
const record = (event) => appendFileSync(${JSON.stringify(agentLog)}, event + ":" + (process.env.WRAPPED_BY ?? "bare") + "\\n");
|
||||
const readline = require("node:readline");
|
||||
const lines = readline.createInterface({ input: process.stdin });
|
||||
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
|
||||
lines.on("line", (line) => {
|
||||
const message = JSON.parse(line);
|
||||
if (message.method === "initialize") { record("init"); send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, agentCapabilities: {} } }); }
|
||||
else if (message.method === "session/new") { record("new"); send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "native-" + Math.random(), modes: null, configOptions: [] } }); }
|
||||
});`,
|
||||
"utf8",
|
||||
);
|
||||
const readLines = async (file: string) =>
|
||||
(await readFile(file, "utf8").catch(() => "")).split("\n").filter(Boolean);
|
||||
return {
|
||||
agent,
|
||||
launchLog,
|
||||
wrap: (tag) => [process.execPath, launcher, launchLog, tag],
|
||||
launches: async () => (await readLines(launchLog)).map((line) => JSON.parse(line)),
|
||||
agentStarts: async () => await readLines(agentLog),
|
||||
};
|
||||
}
|
||||
|
||||
function wrappedOpen(
|
||||
sessionId: string,
|
||||
wrap: readonly [string, ...string[]] | undefined,
|
||||
): Extract<ProviderInput, { type: "session.open" }> {
|
||||
const input = openInput();
|
||||
return {
|
||||
...input,
|
||||
requestId: `open-${sessionId}`,
|
||||
sessionId,
|
||||
config: { ...input.config, env: { SESSION_TOKEN: sessionId }, ...(wrap ? { wrap } : {}) },
|
||||
};
|
||||
}
|
||||
|
||||
async function connectWrapped(command: readonly [string, ...string[]]) {
|
||||
const registration = runAcpProvider({ id: "wrap-acp", label: "Wrap ACP", command });
|
||||
expect(registration.launchWrap).toBe(true);
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message", "session.launch_wrap"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
return { connection, events };
|
||||
}
|
||||
|
||||
it("spawns the session as [...wrap, command, ...args] with the session env", async () => {
|
||||
const fixture = await wrapFixture();
|
||||
const { launchLog } = fixture;
|
||||
const { connection, events } = await connectWrapped([process.execPath, fixture.agent]);
|
||||
expect(connection.capabilities).toContain("session.launch_wrap");
|
||||
try {
|
||||
await connection.send(wrappedOpen("one", fixture.wrap("sandbox")));
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
expect(await fixture.launches()).toEqual([
|
||||
{ argv: [launchLog, "sandbox", process.execPath, fixture.agent], token: "one" },
|
||||
]);
|
||||
expect(await fixture.agentStarts()).toEqual(["init:bare", "init:sandbox", "new:sandbox"]);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("passes wrap and command arguments that contain spaces as single argv elements", async () => {
|
||||
const fixture = await wrapFixture();
|
||||
const { launchLog } = fixture;
|
||||
const { connection, events } = await connectWrapped([
|
||||
process.execPath,
|
||||
fixture.agent,
|
||||
"--profile name with spaces",
|
||||
]);
|
||||
try {
|
||||
await connection.send(wrappedOpen("one", fixture.wrap("tag with spaces")));
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
expect((await fixture.launches())[0]?.argv).toEqual([
|
||||
launchLog,
|
||||
"tag with spaces",
|
||||
process.execPath,
|
||||
fixture.agent,
|
||||
"--profile name with spaces",
|
||||
]);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("wraps only the session that selected a wrap on a shared connection", async () => {
|
||||
const fixture = await wrapFixture();
|
||||
const { launchLog } = fixture;
|
||||
const { connection, events } = await connectWrapped([process.execPath, fixture.agent]);
|
||||
try {
|
||||
await connection.send(wrappedOpen("wrapped", fixture.wrap("sandbox")));
|
||||
await connection.send(wrappedOpen("bare", undefined));
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.ready" && event.sessionId === "wrapped",
|
||||
);
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.ready" && event.sessionId === "bare",
|
||||
);
|
||||
expect(await fixture.launches()).toEqual([
|
||||
{ argv: [launchLog, "sandbox", process.execPath, fixture.agent], token: "wrapped" },
|
||||
]);
|
||||
expect(
|
||||
(await fixture.agentStarts()).filter((line) => line.startsWith("new:")).sort(),
|
||||
).toEqual(["new:bare", "new:sandbox"]);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("fails the open when the launcher is missing and never starts the bare command", async () => {
|
||||
const fixture = await wrapFixture();
|
||||
const missing = path.join(path.dirname(fixture.agent), "missing-launcher");
|
||||
const { connection, events } = await connectWrapped([process.execPath, fixture.agent]);
|
||||
// Node publishes every spawn attempt, a failed one included, before it fills in the fields.
|
||||
const spawned: ChildProcess[] = [];
|
||||
const onSpawn = (message: unknown) =>
|
||||
spawned.push((message as { process: ChildProcess }).process);
|
||||
diagnosticsChannel.subscribe("child_process", onSpawn);
|
||||
try {
|
||||
await connection.send(wrappedOpen("one", [missing, "--profile", "a b"]));
|
||||
expect(await waitForEvent(events, (event) => event.type === "request.failed")).toMatchObject({
|
||||
requestId: "open-one",
|
||||
error: { message: expect.stringMatching(/ENOENT/u) },
|
||||
});
|
||||
expect(spawned.map((child) => child.spawnargs)).toEqual([
|
||||
[missing, "--profile", "a b", process.execPath, fixture.agent],
|
||||
]);
|
||||
// The only start of the agent is the connection's capability probe, before the open.
|
||||
expect(await fixture.agentStarts()).toEqual(["init:bare"]);
|
||||
expect(events.some((event) => event.type === "session.opened")).toBe(false);
|
||||
} finally {
|
||||
diagnosticsChannel.unsubscribe("child_process", onSpawn);
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not offer launch wrap through a connector", async () => {
|
||||
const { connector } = connectorHarness();
|
||||
const registration = runAcpProvider({ id: "connector-acp", label: "Connector", connector });
|
||||
expect(registration).not.toHaveProperty("launchWrap");
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message", "session.launch_wrap"],
|
||||
});
|
||||
expect(connection.capabilities).not.toContain("session.launch_wrap");
|
||||
await connection.close();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -181,6 +181,8 @@ export function runAcpProvider(options: RunAcpProviderOptions): ProviderRegistra
|
||||
description: options.description,
|
||||
icon: options.icon,
|
||||
command: options.command,
|
||||
// Each command-based session spawns its own process, so it can run behind that session's wrap.
|
||||
...(hasCommand ? { launchWrap: true } : {}),
|
||||
connect(request) {
|
||||
return createAcpProviderConnection(options, request);
|
||||
},
|
||||
|
||||
@@ -23,6 +23,9 @@ export type {
|
||||
PluginHookWorkspace,
|
||||
PluginHookWorktree,
|
||||
PluginWorktreeCreateRequest,
|
||||
PluginLaunchWrap,
|
||||
PluginTerminalCreateRequest,
|
||||
PluginCommandRunRequest,
|
||||
PluginHookAgent,
|
||||
PluginSessionOpenRequest,
|
||||
PluginTurnOutcome,
|
||||
@@ -32,6 +35,7 @@ export type {
|
||||
} from "./lifecycle.js";
|
||||
|
||||
export { spawnProcess, execCommand, terminateProcess } from "./process.js";
|
||||
export type { SpawnProcessOptions } from "./process.js";
|
||||
|
||||
export { defineAgentTool } from "./agent-tools.js";
|
||||
export type { AgentToolDefinition, AgentToolResult, AgentToolContext } from "./agent-tools.js";
|
||||
|
||||
@@ -68,6 +68,49 @@ export type PluginWorktreeCreateRequest = {
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* A launcher Paseo starts a process behind: the process runs as `[...wrap, command, ...args]`.
|
||||
* The executable is an absolute path on the daemon host. Each element is one argument; no shell
|
||||
* parses them, except that Windows runs a `.cmd` or `.bat` executable through cmd.exe. A later
|
||||
* hook may omit the wrap or return the same one; a different wrap fails the operation.
|
||||
*/
|
||||
export type PluginLaunchWrap = readonly [executable: string, ...args: string[]];
|
||||
|
||||
/** A terminal Paseo is about to create in a workspace. */
|
||||
export interface PluginTerminalCreateRequest {
|
||||
readonly workspaceId: string;
|
||||
readonly cwd: string;
|
||||
/**
|
||||
* `agent`: an agent's Paseo tool. `script`: a `paseo.json` script or service. `worktree`: a
|
||||
* `paseo.json` worktree terminal. `client`: everything else (the app, CLI, SDK, plugins).
|
||||
*/
|
||||
readonly source: "client" | "agent" | "script" | "worktree";
|
||||
readonly name: string | null;
|
||||
/** The program the terminal starts, or `null` for the user's default shell. */
|
||||
readonly command: string | null;
|
||||
readonly args: readonly string[];
|
||||
/** What Paseo types into the shell once it starts: the command of a script or worktree terminal. */
|
||||
readonly input: string | null;
|
||||
/** Environment overrides for the terminal; excludes the daemon's inherited environment. */
|
||||
env: Record<string, string>;
|
||||
/** Start the terminal as `[...wrap, command, ...args]`; with no `command`, the default shell. */
|
||||
wrap?: PluginLaunchWrap;
|
||||
}
|
||||
|
||||
/** A `paseo.json` worktree setup or teardown command Paseo is about to run. */
|
||||
export interface PluginCommandRunRequest {
|
||||
/** Null when a worktree is archived by path and no workspace record remains. */
|
||||
readonly workspaceId: string | null;
|
||||
readonly cwd: string;
|
||||
readonly purpose: "setup" | "teardown";
|
||||
/** The command as written in `paseo.json`. Paseo runs it through a shell. */
|
||||
readonly command: string;
|
||||
/** Environment overrides for the command; excludes the daemon's inherited environment. */
|
||||
env: Record<string, string>;
|
||||
/** Start the command's shell as `[...wrap, shell, ...shellArgs]`. */
|
||||
wrap?: PluginLaunchWrap;
|
||||
}
|
||||
|
||||
export interface PluginHookAgent {
|
||||
id: string;
|
||||
workspaceId: string | null;
|
||||
@@ -98,6 +141,12 @@ export interface PluginSessionOpenRequest {
|
||||
tools: AgentToolDefinition[];
|
||||
env: Record<string, string>;
|
||||
mcpServers: NonNullable<AgentSessionConfig["mcpServers"]>;
|
||||
/**
|
||||
* Start the provider's harness as `[...wrap, command, ...args]`. Only a provider whose snapshot
|
||||
* entry has `launchWrap: true` applies it; any other provider fails the open. Not saved on the
|
||||
* agent.
|
||||
*/
|
||||
wrap?: PluginLaunchWrap;
|
||||
}
|
||||
|
||||
export type PluginTurnOutcome =
|
||||
@@ -138,18 +187,28 @@ export interface PluginHookRequests {
|
||||
env?: Record<string, string>;
|
||||
/** Stored on the new agent. Always present in the payload; return it changed to change it. */
|
||||
metadata?: Record<string, JsonValue>;
|
||||
/** The workspace the agent is created in, which `config.cwd` alone does not identify. */
|
||||
readonly workspaceId: string | null;
|
||||
};
|
||||
"agent.open.before": PluginSessionOpenRequest;
|
||||
"workspace.create.before": Omit<WorkspaceCreateRequest, "type" | "requestId">;
|
||||
"terminal.create.before": PluginTerminalCreateRequest;
|
||||
"command.run.before": PluginCommandRunRequest;
|
||||
}
|
||||
|
||||
/** What a hook may return. An omitted `metadata` stays as it was. */
|
||||
type PluginHookRequestResults = Omit<PluginHookRequests, "agent.open.before"> & {
|
||||
/** What a hook may return. An omitted `metadata` or `workspaceId` stays as it was. */
|
||||
type PluginHookRequestResults = Omit<
|
||||
PluginHookRequests,
|
||||
"agent.open.before" | "agent.create.before"
|
||||
> & {
|
||||
// Read-only fields added after the first SDK stay optional in a result; omitted means unchanged.
|
||||
"agent.open.before": Omit<PluginSessionOpenRequest, "metadata" | "background"> & {
|
||||
readonly background?: boolean;
|
||||
metadata?: Readonly<Record<string, JsonValue>>;
|
||||
};
|
||||
"agent.create.before": Omit<PluginHookRequests["agent.create.before"], "workspaceId"> & {
|
||||
readonly workspaceId?: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
export type PluginHooks = {
|
||||
@@ -217,6 +276,8 @@ export const pluginHookRegistry = {
|
||||
"agent.turn.after": { waits: false },
|
||||
"agent.permission.before": { waits: false },
|
||||
"agent.permission.after": { waits: false },
|
||||
"terminal.create.before": { waits: true },
|
||||
"command.run.before": { waits: true },
|
||||
} as const satisfies Record<keyof PluginHooks, { waits: boolean }>;
|
||||
|
||||
// COMPAT(pluginHookNames): added in v0.14, remove after 2027-04-30
|
||||
|
||||
@@ -1,117 +1,92 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { quoteWindowsArgument, quoteWindowsCommand } from "./windows-command.js";
|
||||
import { findWindowsCommand, quoteWindowsCommand, windowsCommandLine } from "./windows-command.js";
|
||||
|
||||
const program = { commandScript: false } as const;
|
||||
const script = { commandScript: true } as const;
|
||||
|
||||
describe("quoteWindowsCommand", () => {
|
||||
const originalPlatform = process.platform;
|
||||
|
||||
function setPlatform(value: string) {
|
||||
Object.defineProperty(process, "platform", { value, writable: true });
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setPlatform(originalPlatform);
|
||||
});
|
||||
|
||||
test("quotes a Windows path with spaces", () => {
|
||||
setPlatform("win32");
|
||||
test("quotes a path with spaces and keeps cmd.exe syntax in it as text", () => {
|
||||
expect(quoteWindowsCommand("C:\\Program Files\\Anthropic\\claude.exe")).toBe(
|
||||
'"C:\\Program Files\\Anthropic\\claude.exe"',
|
||||
);
|
||||
});
|
||||
|
||||
test("does not double-quote an already-quoted path", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand('"C:\\Program Files\\Anthropic\\claude.exe"')).toBe(
|
||||
'"C:\\Program Files\\Anthropic\\claude.exe"',
|
||||
expect(quoteWindowsCommand("C:\\Program Files (x86)\\Tool & Co\\run.cmd")).toBe(
|
||||
'"C:\\Program Files (x86)\\Tool & Co\\run.cmd"',
|
||||
);
|
||||
});
|
||||
|
||||
test("returns the command unchanged when there are no spaces", () => {
|
||||
setPlatform("win32");
|
||||
test("leaves a plain or already quoted path as given", () => {
|
||||
expect(quoteWindowsCommand("C:\\nvm4w\\nodejs\\codex")).toBe("C:\\nvm4w\\nodejs\\codex");
|
||||
});
|
||||
|
||||
test("escapes ampersands", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("feature&bugfix")).toBe("feature^&bugfix");
|
||||
});
|
||||
|
||||
test("escapes pipes", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("feature|bugfix")).toBe("feature^|bugfix");
|
||||
});
|
||||
|
||||
test("does not double percent signs", () => {
|
||||
setPlatform("win32");
|
||||
// cmd.exe only collapses %% → % inside batch files; on the command line
|
||||
// it stays literal, which corrupts git --format atoms etc.
|
||||
expect(quoteWindowsCommand("100%")).toBe("100%");
|
||||
});
|
||||
|
||||
test("preserves git --format atoms verbatim", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("--format=%(refname)%09%(committerdate:unix)")).toBe(
|
||||
"--format=%^(refname^)%09%^(committerdate:unix^)",
|
||||
);
|
||||
});
|
||||
|
||||
test("escapes carets", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("feature^bugfix")).toBe("feature^^bugfix");
|
||||
});
|
||||
|
||||
test("escapes multiple metacharacters", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("build&(test|deploy)!<output>")).toBe(
|
||||
"build^&^(test^|deploy^)^!^<output^>",
|
||||
);
|
||||
});
|
||||
|
||||
test("quotes commands with spaces after escaping metacharacters", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("C:\\Program Files\\My Tool&Stuff\\run 100%.cmd")).toBe(
|
||||
'"C:\\Program Files\\My Tool^&Stuff\\run 100%.cmd"',
|
||||
);
|
||||
});
|
||||
|
||||
test("returns the command unchanged on non-Windows platforms", () => {
|
||||
setPlatform("darwin");
|
||||
expect(quoteWindowsCommand("/usr/local/bin/claude code")).toBe("/usr/local/bin/claude code");
|
||||
expect(quoteWindowsCommand('"C:\\Program Files\\x.exe"')).toBe('"C:\\Program Files\\x.exe"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("quoteWindowsArgument", () => {
|
||||
const originalPlatform = process.platform;
|
||||
|
||||
function setPlatform(value: string) {
|
||||
Object.defineProperty(process, "platform", { value, writable: true });
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setPlatform(originalPlatform);
|
||||
});
|
||||
|
||||
test("quotes a Windows argument with spaces", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsArgument("C:\\Program Files\\Anthropic\\cli.js")).toBe(
|
||||
'"C:\\Program Files\\Anthropic\\cli.js"',
|
||||
describe("windowsCommandLine", () => {
|
||||
test("passes an argument without a cmd.exe metacharacter as given", () => {
|
||||
expect(windowsCommandLine("echo", ["hello", "--flag", "feature/x", "C:\\dir"], program)).toBe(
|
||||
'"echo hello --flag feature/x C:\\dir"',
|
||||
);
|
||||
});
|
||||
|
||||
test("does not double-quote an already-quoted argument", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsArgument('"C:\\Program Files\\Anthropic\\cli.js"')).toBe(
|
||||
'"C:\\Program Files\\Anthropic\\cli.js"',
|
||||
test("quotes and caret-escapes every other argument once, the qntm way", () => {
|
||||
expect(windowsCommandLine("node", ["feature&bugfix", "work profile", ""], program)).toBe(
|
||||
'"node ^"feature^&bugfix^" ^"work^ profile^" ^"^""',
|
||||
);
|
||||
// A caret before each `%` keeps cmd.exe from reading a variable name, inside the quotes too.
|
||||
expect(windowsCommandLine("node", ["%PATH%", "100% of %PATH%"], program)).toBe(
|
||||
'"node ^"^%PATH^%^" ^"100^%^ of^ ^%PATH^%^""',
|
||||
);
|
||||
// Backslashes before the closing quote double, as the program's argv parser expects.
|
||||
expect(windowsCommandLine("node", ["C:\\path with space\\"], program)).toBe(
|
||||
'"node ^"C:\\path^ with^ space\\\\^""',
|
||||
);
|
||||
});
|
||||
|
||||
test("returns the argument unchanged when there are no spaces", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsArgument("--version")).toBe("--version");
|
||||
test("quotes =, comma and semicolon, where a batch script splits its arguments", () => {
|
||||
expect(windowsCommandLine("run.cmd", ["--profile=restricted", "a,b;c"], script)).toBe(
|
||||
'"run.cmd ^"--profile=restricted^" ^"a^,b^;c^""',
|
||||
);
|
||||
});
|
||||
|
||||
test("returns the argument unchanged on non-Windows platforms", () => {
|
||||
setPlatform("darwin");
|
||||
expect(quoteWindowsArgument("/usr/local/bin/claude code")).toBe("/usr/local/bin/claude code");
|
||||
test("escapes an argument with a quote twice for a batch script, which reads it again", () => {
|
||||
expect(windowsCommandLine("node", ['say "hi"'], program)).toBe('"node ^"say^ \\^"hi\\^"^""');
|
||||
expect(windowsCommandLine("run.cmd", ['say "hi"', "a & b"], script)).toBe(
|
||||
'"run.cmd ^^^"say^^^ \\^^^"hi\\^^^"^^^" ^"a^ ^&^ b^""',
|
||||
);
|
||||
});
|
||||
|
||||
test("quotes the command path at the start of the line", () => {
|
||||
expect(windowsCommandLine("C:\\Program Files (x86)\\run.cmd", ["acp"], script)).toBe(
|
||||
'""C:\\Program Files (x86)\\run.cmd" acp"',
|
||||
);
|
||||
});
|
||||
|
||||
test("refuses a line break, which ends a cmd.exe command whatever the quoting", () => {
|
||||
for (const argument of ["line one\nline two", "line one\r\n& calc"]) {
|
||||
expect(() => windowsCommandLine("run.cmd", ["--", argument], script)).toThrow(
|
||||
"cmd.exe cannot pass an argument with a line break to run.cmd",
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("findWindowsCommand", () => {
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
test("finds a bare name on PATH with each PATHEXT extension, whatever the env key case", async () => {
|
||||
const empty = await mkdtemp(path.join(os.tmpdir(), "windows-command-empty-"));
|
||||
const tools = await mkdtemp(path.join(os.tmpdir(), "windows-command-tools-"));
|
||||
roots.push(empty, tools);
|
||||
await writeFile(path.join(tools, "agent.CMD"), "");
|
||||
const env = { Path: `${empty};${tools}`, PathExt: ".EXE;.CMD" };
|
||||
expect(findWindowsCommand("agent", env)).toBe(path.join(tools, "agent.CMD"));
|
||||
expect(findWindowsCommand("echo", env)).toBeUndefined();
|
||||
expect(findWindowsCommand("agent.cmd", env)).toBeUndefined();
|
||||
expect(findWindowsCommand(path.join(tools, "agent"), env)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,46 +1,100 @@
|
||||
import { extname } from "node:path";
|
||||
import { statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
export function isWindowsCommandScript(executablePath: string): boolean {
|
||||
/**
|
||||
* How Paseo starts a program through cmd.exe on Windows: `cmd.exe /d /s /c "<line>"`, with the line
|
||||
* passed verbatim. The SDK process functions and the daemon's terminals share this one dialect.
|
||||
*/
|
||||
|
||||
export function isWindowsCommandScript(
|
||||
executablePath: string,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): boolean {
|
||||
const extension = extname(executablePath).toLowerCase();
|
||||
return process.platform === "win32" && (extension === ".cmd" || extension === ".bat");
|
||||
}
|
||||
|
||||
function escapeWindowsCmdValue(value: string): string {
|
||||
if (process.platform !== "win32") return value;
|
||||
|
||||
const isQuoted = value.startsWith('"') && value.endsWith('"');
|
||||
const unquoted = isQuoted ? value.slice(1, -1) : value;
|
||||
// Do NOT double `%` here. cmd.exe only collapses `%%` → `%` inside batch
|
||||
// files; on the command line / `cmd /c "..."` `%%` stays literal, which
|
||||
// breaks args like git's `--format=%(refname)` (git treats `%%` as the
|
||||
// escape for a literal `%`, so the format atoms become literals).
|
||||
const escaped = unquoted.replace(/([&|^<>()!])/g, "^$1");
|
||||
|
||||
if (isQuoted || /[\s"]/u.test(unquoted)) {
|
||||
const quoted = escaped
|
||||
.replace(/(\\*)"/g, (_match, slashes: string) => `${slashes}${slashes}\\"`)
|
||||
.replace(/\\+$/u, (slashes) => `${slashes}${slashes}`);
|
||||
return `"${quoted}"`;
|
||||
}
|
||||
|
||||
return escaped;
|
||||
return platform === "win32" && (extension === ".cmd" || extension === ".bat");
|
||||
}
|
||||
|
||||
/**
|
||||
* When spawning with `shell: true` on Windows, the command is passed to
|
||||
* `cmd.exe /d /s /c "command args"`. The `/s` strips outer quotes, so a
|
||||
* command path with spaces (e.g. `C:\Program Files\...`) is split at the
|
||||
* space. Wrapping it in quotes produces the correct `"C:\Program Files\..." args`.
|
||||
* Find a bare command name the way cmd.exe would on `PATH`, trying each `PATHEXT` extension. The
|
||||
* current directory is not searched. Returns undefined for a name with a path or an extension, and
|
||||
* for a name that is not on `PATH`, such as a cmd.exe builtin.
|
||||
*/
|
||||
export function findWindowsCommand(name: string, env: NodeJS.ProcessEnv): string | undefined {
|
||||
if (name.includes("/") || name.includes("\\") || extname(name)) return undefined;
|
||||
const extensions = (readEnv(env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
|
||||
for (const directory of (readEnv(env, "PATH") ?? "").split(";").filter(Boolean)) {
|
||||
for (const extension of extensions) {
|
||||
const candidate = join(directory, name + extension);
|
||||
if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The cmd.exe that runs a command line: the child's `ComSpec`, else the daemon's. */
|
||||
export function windowsCommandShell(env: NodeJS.ProcessEnv): string {
|
||||
return readEnv(env, "ComSpec") ?? readEnv(process.env, "ComSpec") ?? "cmd.exe";
|
||||
}
|
||||
|
||||
// Windows environment names ignore case, and a copied env object keeps whatever case it had.
|
||||
function readEnv(env: NodeJS.ProcessEnv, name: string): string | undefined {
|
||||
const key = Object.keys(env).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
|
||||
return key === undefined ? undefined : env[key] || undefined;
|
||||
}
|
||||
|
||||
// The cmd.exe metacharacters, as cross-spawn's `lib/util/escape.js` lists them.
|
||||
const CMD_METACHARACTERS = /([()\][%!^"`<>&|;, *?])/g;
|
||||
// A batch script also splits its arguments at `=` and tab.
|
||||
const NEEDS_ESCAPE = /[()\][%!^"`<>&|;, *?=\t]/u;
|
||||
|
||||
/**
|
||||
* Escape one argument for a `cmd.exe /c` line by the qntm algorithm (https://qntm.org/cmd), the
|
||||
* one cross-spawn's `lib/util/escape.js` implements: quote it for the program's own argv parser,
|
||||
* then put a `^` before every cmd.exe metacharacter, the added quotes included. cmd.exe then sees
|
||||
* no quoted region, so a `%NAME%` never expands, and the program gets the argument unchanged.
|
||||
* `twice` escapes again for a batch script that reads the argument a second time.
|
||||
*/
|
||||
function escapeCmdArgument(argument: string, twice: boolean): string {
|
||||
const quoted = `"${argument.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"`;
|
||||
const escaped = quoted.replace(CMD_METACHARACTERS, "^$1");
|
||||
return twice ? escaped.replace(CMD_METACHARACTERS, "^$1") : escaped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quote the program path for the start of a cmd.exe line. Inside the quotes cmd.exe reads `&`, `(`
|
||||
* and `)` as text, so a path such as `C:\Program Files (x86)\...` starts.
|
||||
*/
|
||||
export function quoteWindowsCommand(command: string): string {
|
||||
return escapeWindowsCmdValue(command);
|
||||
if (command.startsWith('"') && command.endsWith('"')) return command;
|
||||
if (command === "" || /[\s()!^"<>&|%;,=]/u.test(command)) return `"${command}"`;
|
||||
return command;
|
||||
}
|
||||
|
||||
/**
|
||||
* `spawn(..., { shell: true })` on Windows also passes argv through `cmd.exe`.
|
||||
* Any argument containing spaces must be quoted or it will be split before the
|
||||
* child process sees it.
|
||||
* The quoted line for `cmd.exe /d /s /c <line>` that starts `command` with `args`.
|
||||
*
|
||||
* - An argument without a metacharacter needs no escape and stays as given, so cmd.exe builtins
|
||||
* and batch scripts that read `%1` get it unchanged.
|
||||
* - Any other argument is escaped once. A batch script that reads it as `%~1` gets it without the
|
||||
* quotes, and one that forwards it with `%*` hands the program the quoted argument, where cmd.exe
|
||||
* reads every metacharacter as text.
|
||||
* - For a batch script (`commandScript`), an argument with a `"` is escaped twice. Its quotes
|
||||
* would otherwise open and close regions when the script reads it again, and leave the
|
||||
* arguments after it outside the quotes.
|
||||
*
|
||||
* cmd.exe ends a command at a line break whatever the quoting, so an argument with one throws.
|
||||
*/
|
||||
export function quoteWindowsArgument(argument: string): string {
|
||||
return escapeWindowsCmdValue(argument);
|
||||
export function windowsCommandLine(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
{ commandScript }: { commandScript: boolean },
|
||||
): string {
|
||||
const escaped = args.map((argument) => {
|
||||
if (/[\r\n]/u.test(argument)) {
|
||||
throw new Error(`cmd.exe cannot pass an argument with a line break to ${command}`);
|
||||
}
|
||||
if (argument !== "" && !NEEDS_ESCAPE.test(argument)) return argument;
|
||||
return escapeCmdArgument(argument, commandScript && argument.includes('"'));
|
||||
});
|
||||
return `"${[quoteWindowsCommand(command), ...escaped].join(" ")}"`;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { execCommand, spawnProcess } from "./index.js";
|
||||
import { resolveSpawnInvocation } from "./process.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
@@ -26,8 +27,8 @@ const argumentsToPreserve = [
|
||||
"feature^bugfix",
|
||||
];
|
||||
|
||||
// A bare extensionless command selects the Windows shell; an absolute node.exe path would
|
||||
// skip that path. The real child checks quoting through the public process capabilities.
|
||||
// A real child checks quoting through the public process capabilities. On Windows the bare name
|
||||
// resolves on PATH to node.exe, which starts directly.
|
||||
test("execCommand delivers shell arguments to the real child unchanged", async () => {
|
||||
const script = await writeArgumentReader();
|
||||
const { stdout } = await execCommand("node", [script, ...argumentsToPreserve]);
|
||||
@@ -51,3 +52,299 @@ test("spawnProcess delivers shell arguments to the real child unchanged", async
|
||||
});
|
||||
expect(JSON.parse(stdout)).toEqual(argumentsToPreserve);
|
||||
});
|
||||
|
||||
// A Windows environment with an empty PATH, so a bare name is never found on the test host.
|
||||
const windowsEnv = { ComSpec: "C:\\Windows\\System32\\cmd.exe", PATH: "" };
|
||||
|
||||
function onWindows(command: string, args: string[], shell?: boolean | string) {
|
||||
return resolveSpawnInvocation(command, args, shell, "win32", windowsEnv);
|
||||
}
|
||||
|
||||
// A launch wrap prepends a Windows script wrapper to the provider launch; spawnProcess starts it as
|
||||
// one verbatim cmd.exe line.
|
||||
test("a Windows script launch wrap starts as one verbatim cmd.exe line", () => {
|
||||
const wrapped = [
|
||||
"C:\\Program Files\\Sandbox\\run.cmd",
|
||||
"--profile",
|
||||
"work profile",
|
||||
"",
|
||||
"C:\\tools\\agy.cmd",
|
||||
"acp",
|
||||
];
|
||||
expect(onWindows(wrapped[0]!, wrapped.slice(1))).toEqual({
|
||||
command: "C:\\Windows\\System32\\cmd.exe",
|
||||
args: [
|
||||
"/d",
|
||||
"/s",
|
||||
"/c",
|
||||
'""C:\\Program Files\\Sandbox\\run.cmd" --profile ^"work^ profile^" ^"^" C:\\tools\\agy.cmd acp"',
|
||||
],
|
||||
shell: false,
|
||||
windowsVerbatimArguments: true,
|
||||
});
|
||||
expect(resolveSpawnInvocation(wrapped[0]!, wrapped.slice(1), undefined, "linux")).toEqual({
|
||||
command: wrapped[0],
|
||||
args: wrapped.slice(1),
|
||||
shell: false,
|
||||
});
|
||||
});
|
||||
|
||||
// cmd.exe ends a command at a line break, and the text after it would run as a second command.
|
||||
test("a Windows cmd.exe launch refuses an argument with a line break before it starts", () => {
|
||||
for (const argument of ["line one\nline two", "line one\r\n& calc"]) {
|
||||
expect(() => onWindows("C:\\Sandbox\\run.cmd", ["--", argument])).toThrow(
|
||||
"cmd.exe cannot pass an argument with a line break to C:\\Sandbox\\run.cmd",
|
||||
);
|
||||
expect(() => onWindows("codex", [argument])).toThrow(
|
||||
"cmd.exe cannot pass an argument with a line break to codex",
|
||||
);
|
||||
}
|
||||
expect(onWindows("C:\\tools\\node.exe", ["a\nb"]).args).toEqual(["a\nb"]);
|
||||
expect(resolveSpawnInvocation("/usr/bin/sandbox", ["a\nb"], undefined, "linux").args).toEqual([
|
||||
"a\nb",
|
||||
]);
|
||||
});
|
||||
|
||||
// Only cmd.exe reads cmd.exe quoting. A shell the caller names parses the line by its own rules.
|
||||
test("a Windows launch quotes for cmd.exe only when cmd.exe parses the command line", () => {
|
||||
// `shell: true` runs the child's ComSpec; a cmd.exe the caller names runs as named.
|
||||
for (const [shell, cmd] of [
|
||||
[true, windowsEnv.ComSpec],
|
||||
["cmd.exe", "cmd.exe"],
|
||||
["D:\\Tools\\CMD.EXE", "D:\\Tools\\CMD.EXE"],
|
||||
] as const) {
|
||||
expect(onWindows("echo", ["hello", "a & b"], shell)).toEqual({
|
||||
command: cmd,
|
||||
args: ["/d", "/s", "/c", '"echo hello ^"a^ ^&^ b^""'],
|
||||
shell: false,
|
||||
windowsVerbatimArguments: true,
|
||||
});
|
||||
}
|
||||
for (const shell of ["bash.exe", "C:\\Program Files\\Git\\bin\\bash.exe", "pwsh"]) {
|
||||
expect(onWindows("echo", ["'a & b'", "line\nbreak"], shell)).toEqual({
|
||||
command: "echo",
|
||||
args: ["'a & b'", "line\nbreak"],
|
||||
shell,
|
||||
});
|
||||
}
|
||||
// A program starts directly, and `shell: false` keeps a bare name that is not on PATH direct.
|
||||
expect(onWindows("C:\\tools\\node.exe", ["a & b"])).toEqual({
|
||||
command: "C:\\tools\\node.exe",
|
||||
args: ["a & b"],
|
||||
shell: false,
|
||||
});
|
||||
expect(onWindows("missing", ["a & b"], false)).toEqual({
|
||||
command: "missing",
|
||||
args: ["a & b"],
|
||||
shell: false,
|
||||
});
|
||||
});
|
||||
|
||||
// The daemon runs git with `shell: false` on hot paths that must not block on synchronous IO, so
|
||||
// an explicit `shell: false` starts a bare name directly and leaves the PATH search to Windows.
|
||||
test("a Windows bare name searches PATH for a script only when the caller allows a shell", async () => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin-path-shim-"));
|
||||
roots.push(directory);
|
||||
await writeFile(path.join(directory, "tool.CMD"), "");
|
||||
const env = { ...windowsEnv, PATH: directory };
|
||||
expect(resolveSpawnInvocation("tool", ["a & b"], false, "win32", env)).toEqual({
|
||||
command: "tool",
|
||||
args: ["a & b"],
|
||||
shell: false,
|
||||
});
|
||||
expect(resolveSpawnInvocation("tool", ["a & b"], undefined, "win32", env)).toEqual({
|
||||
command: windowsEnv.ComSpec,
|
||||
args: ["/d", "/s", "/c", `"${path.join(directory, "tool.CMD")} ^"a^ ^&^ b^""`],
|
||||
shell: false,
|
||||
windowsVerbatimArguments: true,
|
||||
});
|
||||
});
|
||||
|
||||
// Real Git Bash on Windows: the arguments reach Bash as given, without cmd.exe escapes.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"execCommand passes arguments as given to a Windows shell other than cmd.exe",
|
||||
async () => {
|
||||
const bash = path.join(
|
||||
process.env.ProgramFiles ?? "C:\\Program Files",
|
||||
"Git",
|
||||
"bin",
|
||||
"bash.exe",
|
||||
);
|
||||
const { stdout } = await execCommand("printf", ["'%s|'", "hello", "'a & b'"], {
|
||||
shell: bash,
|
||||
});
|
||||
expect(stdout).toBe("hello|a & b|");
|
||||
},
|
||||
);
|
||||
|
||||
// A launch wrap starts its executable with the command and its arguments after the wrap's own.
|
||||
// The caller's shell choice belongs to the unwrapped command, so a wrap ignores it.
|
||||
test("spawnProcess starts a wrap's executable with the command after the wrap arguments", async () => {
|
||||
const launcher = await writeArgumentReader();
|
||||
const child = spawnProcess("harness", ["--flag", ...argumentsToPreserve], {
|
||||
wrap: [process.execPath, launcher, "--sandbox profile"],
|
||||
shell: true,
|
||||
stdio: "pipe",
|
||||
});
|
||||
let stdout = "";
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk: string) => {
|
||||
stdout += chunk;
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("close", (code) => {
|
||||
if (code === 0) resolve();
|
||||
else reject(new Error(`Launcher exited with ${code}`));
|
||||
});
|
||||
});
|
||||
expect(JSON.parse(stdout)).toEqual([
|
||||
"--sandbox profile",
|
||||
"harness",
|
||||
"--flag",
|
||||
...argumentsToPreserve,
|
||||
]);
|
||||
});
|
||||
|
||||
// Arguments that cmd.exe reads as syntax unless they are escaped for it. A `.cmd` launcher reads
|
||||
// its arguments a second time when it forwards them with `%*`.
|
||||
const commandScriptArguments = [
|
||||
...argumentsToPreserve,
|
||||
'say "hi"',
|
||||
'"quoted"',
|
||||
"",
|
||||
"a & b",
|
||||
"(parenthesized) arg",
|
||||
"100% done",
|
||||
"%PATH%",
|
||||
"!bang!",
|
||||
"C:\\path with space\\",
|
||||
'mixed "a & b" quote',
|
||||
"--profile=restricted",
|
||||
"a,b;c",
|
||||
// cmd.exe expands a set variable inside a quoted region, so this checks that none opens.
|
||||
"value with %PATH% inside",
|
||||
'quote "then %PATH%" & more',
|
||||
];
|
||||
|
||||
async function writeCommandScriptLauncher(): Promise<string> {
|
||||
const reader = await writeArgumentReader();
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin wrap (x86) & launcher "));
|
||||
roots.push(directory);
|
||||
const launcher = path.join(directory, "sandbox run.cmd");
|
||||
await writeFile(launcher, `@"${process.execPath}" "${reader}" %*\r\n`);
|
||||
return launcher;
|
||||
}
|
||||
|
||||
async function readStdout(child: ReturnType<typeof spawnProcess>): Promise<string> {
|
||||
let stdout = "";
|
||||
child.stdout?.setEncoding("utf8");
|
||||
child.stdout?.on("data", (chunk: string) => {
|
||||
stdout += chunk;
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("close", (code) => {
|
||||
if (code === 0) resolve();
|
||||
else reject(new Error(`Child exited with ${code}`));
|
||||
});
|
||||
});
|
||||
return stdout;
|
||||
}
|
||||
|
||||
// Real cmd.exe: a `.cmd` launch wrap in a directory with spaces and cmd.exe syntax forwards the
|
||||
// harness command and every argument to the program it starts, unchanged.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"a .cmd launch wrap forwards the command and its arguments unchanged on Windows",
|
||||
async () => {
|
||||
const launcher = await writeCommandScriptLauncher();
|
||||
const child = spawnProcess("harness", commandScriptArguments, {
|
||||
wrap: [launcher, "--sandbox profile", 'say "hi"', ""],
|
||||
stdio: "pipe",
|
||||
});
|
||||
expect(JSON.parse(await readStdout(child))).toEqual([
|
||||
"--sandbox profile",
|
||||
'say "hi"',
|
||||
"",
|
||||
"harness",
|
||||
...commandScriptArguments,
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
test.runIf(process.platform === "win32")(
|
||||
"execCommand runs a .cmd script with its arguments unchanged on Windows",
|
||||
async () => {
|
||||
const launcher = await writeCommandScriptLauncher();
|
||||
const { stdout } = await execCommand(launcher, commandScriptArguments);
|
||||
expect(JSON.parse(stdout)).toEqual(commandScriptArguments);
|
||||
},
|
||||
);
|
||||
|
||||
// Real cmd.exe: a script that reads `%~1` gets each argument as given, without escapes.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"a .cmd script that reads its arguments one by one gets each one as given on Windows",
|
||||
async () => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin script reader "));
|
||||
roots.push(directory);
|
||||
const script = path.join(directory, "read.cmd");
|
||||
// `set /p` without input exits 1, so the script exits 0 on its own.
|
||||
await writeFile(
|
||||
script,
|
||||
'@echo off\r\n<nul set /p "=%~1|%~2|%~3|%~4|%~5|%~6|%~7|%~8|%~9"\r\nexit /b 0\r\n',
|
||||
);
|
||||
const { stdout } = await execCommand(script, [
|
||||
"plain",
|
||||
"with space",
|
||||
"feature&bugfix",
|
||||
"100%",
|
||||
"--profile=restricted",
|
||||
"a,b",
|
||||
"a;b",
|
||||
"value with %PATH% inside",
|
||||
"",
|
||||
]);
|
||||
expect(stdout).toBe(
|
||||
"plain|with space|feature&bugfix|100%|--profile=restricted|a,b|a;b|value with %PATH% inside|",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// Real cmd.exe: a bare name is found on PATH like cmd.exe finds it. A `.cmd` shim that forwards
|
||||
// `%*`, as npm writes them, passes every argument on unchanged; a program starts directly.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"a bare command name found on PATH gets its arguments unchanged on Windows",
|
||||
async () => {
|
||||
const reader = await writeArgumentReader();
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin bare shim "));
|
||||
roots.push(directory);
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-forward.cmd"),
|
||||
`@"${process.execPath}" "${reader}" %*\r\n`,
|
||||
);
|
||||
// Windows env names ignore case, so drop the inherited `Path` before setting the new one.
|
||||
const inherited = Object.entries(process.env).filter(([key]) => key.toLowerCase() !== "path");
|
||||
const env = {
|
||||
...Object.fromEntries(inherited),
|
||||
PATH: `${directory};${process.env.PATH ?? ""}`,
|
||||
};
|
||||
const shim = await execCommand("paseo-forward", commandScriptArguments, { env });
|
||||
expect(JSON.parse(shim.stdout)).toEqual(commandScriptArguments);
|
||||
const program = await execCommand("node", [reader, ...commandScriptArguments], { env });
|
||||
expect(JSON.parse(program.stdout)).toEqual(commandScriptArguments);
|
||||
},
|
||||
);
|
||||
|
||||
// Real cmd.exe: a caller that formats its own cmd.exe line asks Node to pass it verbatim.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"spawnProcess passes a caller's verbatim cmd.exe line unchanged on Windows",
|
||||
async () => {
|
||||
const reader = await writeArgumentReader();
|
||||
const child = spawnProcess(
|
||||
process.env.ComSpec ?? "cmd.exe",
|
||||
["/d", "/s", "/c", `""${process.execPath}" "${reader}" "a b" c"`],
|
||||
{ shell: false, windowsVerbatimArguments: true, stdio: "pipe" },
|
||||
);
|
||||
expect(JSON.parse(await readStdout(child))).toEqual(["a b", "c"]);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -8,10 +8,12 @@ import {
|
||||
import { extname } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import {
|
||||
findWindowsCommand,
|
||||
isWindowsCommandScript,
|
||||
quoteWindowsArgument,
|
||||
quoteWindowsCommand,
|
||||
windowsCommandLine,
|
||||
windowsCommandShell,
|
||||
} from "./process-internal/windows-command.js";
|
||||
import type { PluginLaunchWrap } from "./lifecycle.js";
|
||||
const execFileAsync = promisify(execFile);
|
||||
export interface ExecCommandOptions {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
@@ -20,6 +22,10 @@ export interface ExecCommandOptions {
|
||||
killSignal?: NodeJS.Signals;
|
||||
timeout?: number;
|
||||
maxBuffer?: number;
|
||||
/**
|
||||
* `true` runs the command through cmd.exe on Windows, quoted for it. A shell named here other
|
||||
* than cmd.exe gets the command and arguments as given, on every platform; quote for it.
|
||||
*/
|
||||
shell?: boolean | string;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
@@ -27,47 +33,96 @@ interface ExecCommandResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}
|
||||
function hasPathSeparator(value: string): boolean {
|
||||
return value.includes("/") || value.includes("\\");
|
||||
|
||||
export interface SpawnInvocation {
|
||||
command: string;
|
||||
args: string[];
|
||||
shell: boolean | string;
|
||||
/** The args are one cmd.exe line that Node must pass as given. */
|
||||
windowsVerbatimArguments?: boolean;
|
||||
}
|
||||
|
||||
function shouldUseWindowsShell(
|
||||
function namesCmd(shell: boolean | string | undefined): boolean {
|
||||
return (
|
||||
shell === true || (typeof shell === "string" && /^(?:.*[\\/])?cmd(?:\.exe)?$/iu.test(shell))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* How `spawnProcess` and `execCommand` start `command` on `platform`.
|
||||
*
|
||||
* On Windows a bare name is first found on `PATH`, as cmd.exe would find it, unless the caller
|
||||
* passes `shell: false`. A program then starts directly. A `.cmd` or `.bat` script, a name that is not on `PATH` (a cmd.exe builtin), or a
|
||||
* `shell: true` launch runs as `cmd.exe /d /s /c "..."`, quoted by `windowsCommandLine`. A shell
|
||||
* the caller names other than cmd.exe gets the command and arguments as given.
|
||||
*/
|
||||
export function resolveSpawnInvocation(
|
||||
command: string,
|
||||
requestedShell?: boolean | string,
|
||||
): boolean | string {
|
||||
if (isWindowsCommandScript(command)) {
|
||||
return true;
|
||||
args: readonly string[],
|
||||
requestedShell: boolean | string | undefined,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): SpawnInvocation {
|
||||
if (platform !== "win32") return { command, args: [...args], shell: requestedShell ?? false };
|
||||
if (typeof requestedShell === "string" && !namesCmd(requestedShell)) {
|
||||
return { command, args: [...args], shell: requestedShell };
|
||||
}
|
||||
if (requestedShell !== undefined) {
|
||||
return requestedShell;
|
||||
const bareName = !/[\\/]/u.test(command) && !extname(command);
|
||||
// `shell: false` starts a bare name directly, and Windows searches PATH without blocking Node.
|
||||
const found = bareName && requestedShell !== false ? findWindowsCommand(command, env) : undefined;
|
||||
const target = found ?? command;
|
||||
const commandScript = isWindowsCommandScript(target, platform);
|
||||
// Only cmd.exe knows a builtin, so a bare name off `PATH` goes to it unless the caller said no shell.
|
||||
const builtin = bareName && !found && requestedShell === undefined;
|
||||
if (!commandScript && !namesCmd(requestedShell) && !builtin) {
|
||||
return { command: target, args: [...args], shell: false };
|
||||
}
|
||||
return process.platform === "win32" && !hasPathSeparator(command) && !extname(command);
|
||||
// A cmd.exe the caller names runs the line; otherwise the child's ComSpec does.
|
||||
return {
|
||||
command: typeof requestedShell === "string" ? requestedShell : windowsCommandShell(env),
|
||||
args: ["/d", "/s", "/c", windowsCommandLine(target, args, { commandScript })],
|
||||
shell: false,
|
||||
windowsVerbatimArguments: true,
|
||||
};
|
||||
}
|
||||
|
||||
export interface SpawnProcessOptions extends SpawnOptions {
|
||||
/**
|
||||
* Start `[...wrap, command, ...args]`: the wrap's executable runs the command. `shell` is then
|
||||
* ignored; the wrap's executable runs through cmd.exe only when it is a `.cmd` or `.bat` file.
|
||||
*/
|
||||
wrap?: PluginLaunchWrap;
|
||||
}
|
||||
|
||||
/** Launch a CLI with Windows command-script handling and argv quoting. The caller owns env. */
|
||||
export function spawnProcess(
|
||||
command: string,
|
||||
args: string[],
|
||||
options: SpawnOptions & { stdio: "pipe" },
|
||||
options: SpawnProcessOptions & { stdio: "pipe" },
|
||||
): ChildProcessWithoutNullStreams;
|
||||
export function spawnProcess(command: string, args: string[], options?: SpawnOptions): ChildProcess;
|
||||
export function spawnProcess(
|
||||
command: string,
|
||||
args: string[],
|
||||
options?: SpawnOptions,
|
||||
options?: SpawnProcessOptions,
|
||||
): ChildProcess;
|
||||
export function spawnProcess(
|
||||
command: string,
|
||||
args: string[],
|
||||
options?: SpawnProcessOptions,
|
||||
): ChildProcess {
|
||||
const spawnOptions = options ?? {};
|
||||
const isWindows = process.platform === "win32";
|
||||
const shell = shouldUseWindowsShell(command, spawnOptions.shell);
|
||||
const { wrap, ...spawnOptions } = options ?? {};
|
||||
const env = options?.env ?? process.env;
|
||||
const invocation = wrap
|
||||
? resolveSpawnInvocation(wrap[0], [...wrap.slice(1), command, ...args], false, undefined, env)
|
||||
: resolveSpawnInvocation(command, args, spawnOptions.shell, undefined, env);
|
||||
|
||||
const shouldQuoteForShell = isWindows && shell !== false;
|
||||
const resolvedCommand = shouldQuoteForShell ? quoteWindowsCommand(command) : command;
|
||||
const resolvedArgs = shouldQuoteForShell ? args.map(quoteWindowsArgument) : args;
|
||||
|
||||
return spawn(resolvedCommand, resolvedArgs, {
|
||||
return spawn(invocation.command, invocation.args, {
|
||||
...spawnOptions,
|
||||
env: options?.env,
|
||||
shell,
|
||||
shell: invocation.shell,
|
||||
// Paseo's own cmd.exe line is verbatim; a direct launch keeps the caller's choice.
|
||||
windowsVerbatimArguments:
|
||||
invocation.windowsVerbatimArguments ?? spawnOptions.windowsVerbatimArguments,
|
||||
signal: options?.signal,
|
||||
windowsHide: true,
|
||||
});
|
||||
@@ -78,13 +133,15 @@ export async function execCommand(
|
||||
args: string[],
|
||||
options?: ExecCommandOptions,
|
||||
): Promise<ExecCommandResult> {
|
||||
const isWindows = process.platform === "win32";
|
||||
const shell = shouldUseWindowsShell(command, options?.shell);
|
||||
const shouldQuoteForShell = isWindows && shell !== false;
|
||||
const resolvedCommand = shouldQuoteForShell ? quoteWindowsCommand(command) : command;
|
||||
const resolvedArgs = shouldQuoteForShell ? args.map(quoteWindowsArgument) : args;
|
||||
const invocation = resolveSpawnInvocation(
|
||||
command,
|
||||
args,
|
||||
options?.shell,
|
||||
undefined,
|
||||
options?.env ?? process.env,
|
||||
);
|
||||
|
||||
return execFileAsync(resolvedCommand, resolvedArgs, {
|
||||
return execFileAsync(invocation.command, invocation.args, {
|
||||
cwd: options?.cwd,
|
||||
env: options?.env,
|
||||
encoding: options?.encoding ?? "utf8",
|
||||
@@ -92,7 +149,8 @@ export async function execCommand(
|
||||
killSignal: options?.killSignal,
|
||||
timeout: options?.timeout,
|
||||
maxBuffer: options?.maxBuffer,
|
||||
shell,
|
||||
shell: invocation.shell,
|
||||
windowsVerbatimArguments: invocation.windowsVerbatimArguments,
|
||||
windowsHide: true,
|
||||
}) as Promise<ExecCommandResult>;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
ProviderEventSchema,
|
||||
ProviderInputSchema,
|
||||
negotiateProviderCapabilities,
|
||||
requireProviderCapabilities,
|
||||
type ProviderEvent,
|
||||
type ProviderInput,
|
||||
type ProviderMetric,
|
||||
@@ -125,3 +126,38 @@ describe("Provider metrics", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Provider launch wrap", () => {
|
||||
const open = (wrap?: readonly [string, ...string[]]): ProviderInput =>
|
||||
ProviderInputSchema.parse({
|
||||
type: "session.open",
|
||||
requestId: "open",
|
||||
sessionId: "session-1",
|
||||
history: "skip",
|
||||
config: {
|
||||
cwd: "/workspace",
|
||||
env: {},
|
||||
mcpServers: {},
|
||||
settings: {},
|
||||
persist: true,
|
||||
...(wrap ? { wrap } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
it("requires session.launch_wrap only for an open that carries a wrap", () => {
|
||||
expect(() => requireProviderCapabilities([], open(["/bin/sandbox", "a b"]))).toThrow(
|
||||
"session.launch_wrap",
|
||||
);
|
||||
expect(() =>
|
||||
requireProviderCapabilities(["session.launch_wrap"], open(["/bin/sandbox"])),
|
||||
).not.toThrow();
|
||||
expect(() => requireProviderCapabilities([], open())).not.toThrow();
|
||||
});
|
||||
|
||||
it("keeps each wrap element whole and rejects an empty wrap", () => {
|
||||
expect(open(["/bin/sandbox", "a b"])).toMatchObject({
|
||||
config: { wrap: ["/bin/sandbox", "a b"] },
|
||||
});
|
||||
expect(() => open([] as unknown as [string])).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ export const PROVIDER_CAPABILITIES = [
|
||||
"session.can_stop_runtime",
|
||||
"session.archive",
|
||||
"session.configure",
|
||||
"session.launch_wrap",
|
||||
"session.list",
|
||||
"session.metrics",
|
||||
"session.persistence",
|
||||
@@ -34,6 +35,12 @@ export interface ProviderRegistration {
|
||||
getCatalogCacheKey?(options: ProviderCatalogOptions): Promise<string | undefined>;
|
||||
/** Default executable and arguments; the daemon resolves overrides before status/connect. */
|
||||
command?: readonly [string, ...string[]];
|
||||
/**
|
||||
* Sessions can run behind an `agent.open.before` wrap: the connection offers `session.launch_wrap`
|
||||
* and spawns each session as `[...config.wrap, command, ...args]`. Paseo publishes it on the
|
||||
* provider snapshot before the first connection.
|
||||
*/
|
||||
launchWrap?: boolean;
|
||||
status?(request: ProviderStatusRequest): Promise<ProviderStatus>;
|
||||
id: string;
|
||||
label: string;
|
||||
@@ -212,6 +219,8 @@ export interface ProviderSessionConfig {
|
||||
providerOptions?: Readonly<Record<string, unknown>>;
|
||||
title?: string;
|
||||
persist: boolean;
|
||||
/** Spawn the session as `[...wrap, command, ...args]`. Sent only with `session.launch_wrap`. */
|
||||
wrap?: readonly [string, ...string[]];
|
||||
}
|
||||
|
||||
export interface ProviderConfigChanges {
|
||||
@@ -804,6 +813,7 @@ export function requiredProviderCapabilities(input: ProviderInput): readonly Pro
|
||||
const capabilities: ProviderCapability[] = [];
|
||||
if (input.persistence) capabilities.push("session.persistence");
|
||||
if (input.config.toolPolicy) capabilities.push("permission.tool_policy");
|
||||
if (input.config.wrap) capabilities.push("session.launch_wrap");
|
||||
return capabilities;
|
||||
}
|
||||
case "session.prompt":
|
||||
@@ -907,6 +917,7 @@ const sessionConfigSchema = z
|
||||
providerOptions: z.record(z.string(), z.unknown()).optional(),
|
||||
title: z.string().optional(),
|
||||
persist: z.boolean(),
|
||||
wrap: z.tuple([z.string().min(1)], z.string()).optional(),
|
||||
})
|
||||
.strict();
|
||||
const externalResourceSchema = z
|
||||
|
||||
@@ -5,44 +5,89 @@ import ts from "typescript";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const repository = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
const skill = readFileSync(path.join(repository, "skills/paseo-plugin/SKILL.md"), "utf8");
|
||||
// A Windows checkout writes CRLF line endings.
|
||||
const skill = readFileSync(
|
||||
path.join(repository, "skills/paseo-plugin/SKILL.md"),
|
||||
"utf8",
|
||||
).replaceAll("\r\n", "\n");
|
||||
const pluginRoot = path.join(repository, "plugin-examples/skill-example");
|
||||
|
||||
function sectionCode(heading: string): string {
|
||||
const section = skill.slice(skill.indexOf(`\n## ${heading}\n`));
|
||||
const code = /```tsx\n([\s\S]*?)\n```/.exec(section)?.[1];
|
||||
if (!code) throw new Error(`No tsx example under "${heading}"`);
|
||||
return code;
|
||||
interface SkillExample {
|
||||
heading: string;
|
||||
files: Record<string, string>;
|
||||
}
|
||||
|
||||
// Checks the example as a plugin client file, with the same options as the plugin examples.
|
||||
function typeErrors(code: string): string[] {
|
||||
// Groups every ts and tsx block under its nearest heading. Each block starts with a `// <path>`
|
||||
// comment that places it in a plugin, so the blocks of one heading form one plugin.
|
||||
function skillExamples(): SkillExample[] {
|
||||
const examples: SkillExample[] = [];
|
||||
let heading = "";
|
||||
for (const match of skill.matchAll(/^(#{1,6}) (.+)$|^```(tsx?)\n([\s\S]*?)\n```$/gm)) {
|
||||
if (match[2]) {
|
||||
heading = match[2];
|
||||
continue;
|
||||
}
|
||||
const code = match[4] ?? "";
|
||||
const file = /^\/\/ ([\w./-]+\.tsx?)\n/.exec(code)?.[1];
|
||||
if (!file)
|
||||
throw new Error(`A ${match[3]} block under "${heading}" does not start with // <path>`);
|
||||
let example = examples.at(-1);
|
||||
if (example?.heading !== heading) {
|
||||
example = { heading, files: {} };
|
||||
examples.push(example);
|
||||
}
|
||||
if (example.files[file]) throw new Error(`"${heading}" has two blocks for ${file}`);
|
||||
example.files[file] = code;
|
||||
}
|
||||
return examples;
|
||||
}
|
||||
|
||||
// Checks plugin files, keyed by path in the plugin, with the same options as the plugin examples.
|
||||
function typeErrors(files: Record<string, string>): string[] {
|
||||
const configPath = path.join(repository, "packages/plugin/tsconfig.examples.json");
|
||||
const { config } = ts.readConfigFile(configPath, ts.sys.readFile);
|
||||
const { options } = ts.parseJsonConfigFileContent(config, ts.sys, path.dirname(configPath));
|
||||
const file = path.join(repository, "plugin-examples/skill-example/client/example.tsx");
|
||||
const sources = new Map(
|
||||
Object.entries(files).map(([file, code]) => [path.join(pluginRoot, file), code]),
|
||||
);
|
||||
const host = ts.createCompilerHost(options);
|
||||
const getSourceFile = host.getSourceFile;
|
||||
host.getSourceFile = (name, language, ...rest) =>
|
||||
path.resolve(name) === file
|
||||
? ts.createSourceFile(name, code, language)
|
||||
: getSourceFile.call(host, name, language, ...rest);
|
||||
host.fileExists = (name) => path.resolve(name) === file || ts.sys.fileExists(name);
|
||||
const program = ts.createProgram([file], options, host);
|
||||
host.getSourceFile = (name, language, ...rest) => {
|
||||
const code = sources.get(path.resolve(name));
|
||||
return code === undefined
|
||||
? getSourceFile.call(host, name, language, ...rest)
|
||||
: ts.createSourceFile(name, code, language);
|
||||
};
|
||||
host.fileExists = (name) => sources.has(path.resolve(name)) || ts.sys.fileExists(name);
|
||||
host.directoryExists = (name) =>
|
||||
[...sources.keys()].some((file) => file.startsWith(`${path.resolve(name)}${path.sep}`)) ||
|
||||
ts.sys.directoryExists(name);
|
||||
const program = ts.createProgram([...sources.keys()], options, host);
|
||||
return ts
|
||||
.getPreEmitDiagnostics(program)
|
||||
.map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
|
||||
}
|
||||
|
||||
describe("paseo-plugin skill examples", () => {
|
||||
it("composer pill example typechecks against the plugin SDK", () => {
|
||||
expect(typeErrors(sectionCode("Add a composer pill"))).toEqual([]);
|
||||
const examples = skillExamples();
|
||||
|
||||
it("has examples", () => {
|
||||
expect(examples.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it.each(examples.map((example) => [example.heading, example.files] as const))(
|
||||
"%s typechecks against the plugin SDK",
|
||||
(_heading, files) => {
|
||||
expect(typeErrors(files)).toEqual([]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("plugin translation author types", () => {
|
||||
it("checks JSON keys, plural counts, literal interpolation names and imperative translation", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
typeErrors({
|
||||
"client/example.tsx": `
|
||||
import { defineTranslations, useTranslation, type PluginClientContext } from "@getpaseo/plugin/client";
|
||||
import en from "../../translations/client/locales/en.json";
|
||||
const json = defineTranslations({ resources: { en } });
|
||||
@@ -67,14 +112,16 @@ describe("plugin translation author types", () => {
|
||||
// @ts-expect-error imperative keys are checked
|
||||
client.i18n.t(json, "missing");
|
||||
}
|
||||
`),
|
||||
`,
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps historical string descriptor helpers while accepting translated registrations", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
typeErrors({
|
||||
"client/example.tsx": `
|
||||
import { defineTranslations, type PluginText, type PluginFilePanelContribution, type PluginClientContext, type PluginScreenContribution, type PluginWorkspacePanelContribution, type PluginSettingsScreenContribution, type PluginSidebarItemContribution, type PluginSidebarContribution, type PluginCommandCenterItemContribution, type PluginClientSlashCommandContribution, type PluginButton, type PluginHeaderButtonContribution, type PluginComposerPillContribution, type PluginButtonMenuEntry } from "@getpaseo/plugin/client";
|
||||
import { z } from "zod";
|
||||
import { defineAttachmentSource, type PluginThemeContribution, type PluginAttachmentSourceContribution } from "@getpaseo/plugin";
|
||||
@@ -110,6 +157,7 @@ it("keeps historical string descriptor helpers while accepting translated regist
|
||||
// @ts-expect-error a translated reference is never typed as a string
|
||||
source.title.trim();
|
||||
}
|
||||
`),
|
||||
`,
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -136,6 +136,8 @@ export interface ProviderSnapshotEntry {
|
||||
/** The page that helps users set up and troubleshoot this provider. */
|
||||
docsUrl?: string;
|
||||
defaultModeId?: string | null;
|
||||
/** The provider can run a session behind an `agent.open.before` wrap. Absent means it cannot. */
|
||||
launchWrap?: boolean;
|
||||
}
|
||||
|
||||
export interface AgentFeatureToggle {
|
||||
|
||||
@@ -50,6 +50,12 @@ describe("provider snapshot message schemas", () => {
|
||||
expect(parsed.source).toBe("custom");
|
||||
});
|
||||
|
||||
test("keeps launch-wrap support and leaves it absent when not reported", () => {
|
||||
const entry = { provider: "codex", status: "loading", label: "Codex" };
|
||||
expect(ProviderSnapshotEntrySchema.parse({ ...entry, launchWrap: true }).launchWrap).toBe(true);
|
||||
expect(ProviderSnapshotEntrySchema.parse(entry)).not.toHaveProperty("launchWrap");
|
||||
});
|
||||
|
||||
test("defaults missing enabled state in providers snapshot response entries", () => {
|
||||
const parsed = GetProvidersSnapshotResponseMessageSchema.parse({
|
||||
type: "get_providers_snapshot_response",
|
||||
|
||||
@@ -432,6 +432,7 @@ export const ProviderSnapshotEntrySchema = z.object({
|
||||
iconSvg: z.string().optional(),
|
||||
docsUrl: z.string().optional(),
|
||||
defaultModeId: z.string().nullable().optional(),
|
||||
launchWrap: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const CompactProviderSnapshotModelSchema = AgentModelDefinitionSchema.omit({
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user