diff --git a/.github/ci-paths.yml b/.github/ci-paths.yml index baf6de02e7..ed18172a28 100644 --- a/.github/ci-paths.yml +++ b/.github/ci-paths.yml @@ -56,6 +56,7 @@ sdk: - "packages/plugin/**" - "plugin-examples/**" - "public-docs/plugins/**" + - "skills/paseo-plugin/**" - "packages/client/**" - "packages/highlight/**" - "packages/protocol/**" diff --git a/docs/plugins.md b/docs/plugins.md index 17a97cd9aa..d2a4adecff 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -887,6 +887,13 @@ its Zod schema, and mounts the component inside the normal plugin runtime and er optional output `id` distinguishes several stable replacements from the same source item; its output index is the default. +Each replacement keeps a reference to the source row (`source` on the projected stream item), and +turn logic reads a replaced reply through it. A reply split into several cards stays one reply: turn +folding keeps every card visible, and the turn footer hangs under the last card, copies the original +reply text once, forks at its message, and shows its duration and stats. Read the reply with +`getAssistantReply` (`packages/app/src/types/stream.ts`) instead of checking `kind === +"assistant_message"`. + Transformers run synchronously and must be deterministic. When several transformers match, the first one that returns a result owns that source item. Plugin and registration ordering is stable. See `plugin-examples/timeline-items` for the complete contract. diff --git a/packages/app/e2e/browser/agent-profiles-picker.spec.ts b/packages/app/e2e/browser/agent-profiles-picker.spec.ts index ad4bf2aff1..5665566ee1 100644 --- a/packages/app/e2e/browser/agent-profiles-picker.spec.ts +++ b/packages/app/e2e/browser/agent-profiles-picker.spec.ts @@ -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(); + } + }); }); diff --git a/packages/app/e2e/browser/agent-profiles-settings.spec.ts b/packages/app/e2e/browser/agent-profiles-settings.spec.ts index 8aa2f3864d..d0625f6de5 100644 --- a/packages/app/e2e/browser/agent-profiles-settings.spec.ts +++ b/packages/app/e2e/browser/agent-profiles-settings.spec.ts @@ -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 }) => { + 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(); + } + }); }); diff --git a/packages/app/e2e/browser/plugin-sidebar-items.spec.ts b/packages/app/e2e/browser/plugin-sidebar-items.spec.ts index e9858c1ab4..1e2222ee8e 100644 --- a/packages/app/e2e/browser/plugin-sidebar-items.spec.ts +++ b/packages/app/e2e/browser/plugin-sidebar-items.spec.ts @@ -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); diff --git a/packages/app/e2e/browser/plugin-timeline.spec.ts b/packages/app/e2e/browser/plugin-timeline.spec.ts index aacd7c187b..d3719df65f 100644 --- a/packages/app/e2e/browser/plugin-timeline.spec.ts +++ b/packages/app/e2e/browser/plugin-timeline.spec.ts @@ -1,6 +1,12 @@ -import { test } from "../support/fixtures"; +import { expect, test } from "../support/fixtures"; +import { + expectChatHistoryAttachment, + forkMostRecentAssistantTurnToNewTab, + observeForkAttachment, +} from "../support/helpers/assistant-fork"; import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate"; import { + ASSISTANT_TEXT, withTimelinePlugin, viewInlineThinkingExample, requestPluginTimeline, @@ -55,3 +61,24 @@ test("inline-thinking example renders a streamed thought through host UI", async }, info) => { await viewInlineThinkingExample(page, info); }); + +test("plugin-transformed assistant reply keeps copy, fork, and turn duration in its footer", async ({ + page, +}, info) => { + const forkAttachment = observeForkAttachment(page); + await withTimelinePlugin(page, info, "assistant", async (agent) => { + await requestPluginTimeline(agent); + await agent.client.waitForFinish(agent.agentId, 30_000); + await expectWholeCompletedCard(page); + + const footer = page.getByTestId("turn-footer").last(); + await expect(footer).toBeVisible(); + await expect(footer.getByRole("button", { name: "Copy turn" })).toBeVisible(); + await expect(footer.getByRole("button", { name: "Fork chat from here" })).toBeVisible(); + await expect(footer.getByText(/^Worked for /)).toBeVisible(); + + await forkMostRecentAssistantTurnToNewTab(page); + await expectChatHistoryAttachment(page); + expect(await forkAttachment.waitForText()).toContain(ASSISTANT_TEXT); + }); +}); diff --git a/packages/app/e2e/mobile/modal-sheet/model-tablet-profile.android.ad b/packages/app/e2e/mobile/modal-sheet/model-tablet-profile.android.ad index 1b84493ed6..e2f7540a59 100644 --- a/packages/app/e2e/mobile/modal-sheet/model-tablet-profile.android.ad +++ b/packages/app/e2e/mobile/modal-sheet/model-tablet-profile.android.ad @@ -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 diff --git a/packages/app/e2e/support/helpers/agent-profiles.ts b/packages/app/e2e/support/helpers/agent-profiles.ts index 27789a7bc7..e947ff93fd 100644 --- a/packages/app/e2e/support/helpers/agent-profiles.ts +++ b/packages/app/e2e/support/helpers/agent-profiles.ts @@ -142,8 +142,22 @@ export async function openAgentProfileSettings(page: Page): Promise { 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 { + 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 { // ─── 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 { 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 { 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 { + 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 { - 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 { - 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 { - 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 { + 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 { + 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 { - 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 { - 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 { - 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 { - 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 { + await agentProfileRow(page, name).click(); + await expect(editSurface(page)).toBeVisible({ timeout: 30_000 }); +} + +export async function openCreateAgentProfileEditor(page: Page): Promise { + 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 { + await page.getByRole("textbox", { name: "Name", exact: true }).fill(name); +} + +export async function expectAgentProfileNameDraft(page: Page, name: string): Promise { + await expect(page.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name); +} + +export async function toggleAgentProfileCustomize(page: Page): Promise { + await page.getByTestId("agent-profile-customize-toggle").click(); +} + +export async function fillAgentProfileNotes(page: Page, notes: string): Promise { + await page.getByRole("textbox", { name: "When to use", exact: true }).fill(notes); +} + +export async function expectAgentProfileNotesDraft(page: Page, notes: string): Promise { + await expect(page.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(notes); +} + +export async function saveOpenAgentProfile(page: Page): Promise { + await saveAgentProfile(page); +} + +export async function duplicateOpenAgentProfileWithConfirm( + page: Page, + decision: "accept" | "dismiss", +): Promise { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { - 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( diff --git a/packages/app/src/agent-profiles/agent-profile-editor.tsx b/packages/app/src/agent-profiles/agent-profile-editor.tsx index b30e051852..fe9be8d971 100644 --- a/packages/app/src/agent-profiles/agent-profile-editor.tsx +++ b/packages/app/src/agent-profiles/agent-profile-editor.tsx @@ -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 ( + + + {t("modelSelector.profileSaved", { name })} + + + + + + + ); +} + +function createProfileSavedToast(input: { + name: string; + onEdit: () => void; + onUndo: () => void; +}): ReactElement { + return ; +} export interface AgentProfileEditorControls { + /** Save a profile immediately from a model row with defaults and show an Edit/Undo toast. */ + quickCreateFromModel: (seed: AgentProfileSeed) => Promise; + /** Undo an instant creation without a confirmation prompt. */ + undoCreate: (profileId: string) => Promise; /** 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(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 => { + try { + await mutateProfiles((current) => removeAgentProfileById(current, profileId)); + } catch (error) { + toast.error(toErrorMessage(error)); + } + }, + [mutateProfiles, toast], + ); + + const quickCreateFromModel = useCallback( + async (seed: AgentProfileSeed): Promise => { + 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, + }, +})); diff --git a/packages/app/src/agent-profiles/index.ts b/packages/app/src/agent-profiles/index.ts index 84c8691747..c97d7d68db 100644 --- a/packages/app/src/agent-profiles/index.ts +++ b/packages/app/src/agent-profiles/index.ts @@ -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"; diff --git a/packages/app/src/agent-profiles/internal/agent-profile-glyph.tsx b/packages/app/src/agent-profiles/internal/agent-profile-glyph.tsx index 35ff3c0998..61d29973bf 100644 --- a/packages/app/src/agent-profiles/internal/agent-profile-glyph.tsx +++ b/packages/app/src/agent-profiles/internal/agent-profile-glyph.tsx @@ -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 ; +} + +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 ; + if (iconKey) { + const Icon = THEMED_ICONS[iconKey]; + return ; + } + if (provider) { + return ( + + ); + } + return ; } diff --git a/packages/app/src/agent-profiles/internal/profile-form-model.test.ts b/packages/app/src/agent-profiles/internal/profile-form-model.test.ts index 4756bc127a..1729851934 100644 --- a/packages/app/src/agent-profiles/internal/profile-form-model.test.ts +++ b/packages/app/src/agent-profiles/internal/profile-form-model.test.ts @@ -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: {}, + }); + }); +}); diff --git a/packages/app/src/agent-profiles/internal/profile-form-model.ts b/packages/app/src/agent-profiles/internal/profile-form-model.ts index 37756376bd..1afc71849a 100644 --- a/packages/app/src/agent-profiles/internal/profile-form-model.ts +++ b/packages/app/src/agent-profiles/internal/profile-form-model.ts @@ -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 = new Set(); let answeredKeys: ReadonlySet = 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 })), }; diff --git a/packages/app/src/agent-profiles/internal/profile-summary.test.ts b/packages/app/src/agent-profiles/internal/profile-summary.test.ts new file mode 100644 index 0000000000..2601d95ba9 --- /dev/null +++ b/packages/app/src/agent-profiles/internal/profile-summary.test.ts @@ -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"]); + }); +}); diff --git a/packages/app/src/agent-profiles/internal/profile-summary.ts b/packages/app/src/agent-profiles/internal/profile-summary.ts index 28431b093c..a800bd9279 100644 --- a/packages/app/src/agent-profiles/internal/profile-summary.ts +++ b/packages/app/src/agent-profiles/internal/profile-summary.ts @@ -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, diff --git a/packages/app/src/agent-profiles/internal/profile-write-queue.test.ts b/packages/app/src/agent-profiles/internal/profile-write-queue.test.ts new file mode 100644 index 0000000000..9fc3469c0a --- /dev/null +++ b/packages/app/src/agent-profiles/internal/profile-write-queue.test.ts @@ -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() { + let resolve!: (value: T) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((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(); + 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(); + + 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(); + 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")]); + }); +}); diff --git a/packages/app/src/agent-profiles/internal/profile-write-queue.ts b/packages/app/src/agent-profiles/internal/profile-write-queue.ts new file mode 100644 index 0000000000..7781758e11 --- /dev/null +++ b/packages/app/src/agent-profiles/internal/profile-write-queue.ts @@ -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; + updater: AgentProfileListUpdater; +} + +export interface AgentProfileWriteQueue { + enqueue(serverId: string, step: AgentProfileWriteStep): Promise; +} + +/** 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, + step: AgentProfileWriteStep, +): Promise { + 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>(); + + 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; + }, + }; +} diff --git a/packages/app/src/agent-profiles/internal/use-agent-profiles.ts b/packages/app/src/agent-profiles/internal/use-agent-profiles.ts index fe5105b18c..a1da561348 100644 --- a/packages/app/src/agent-profiles/internal/use-agent-profiles.ts +++ b/packages/app/src/agent-profiles/internal/use-agent-profiles.ts @@ -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; + /** + * Applies a serialized mutation against the latest host profile list so + * overlapping writes compose instead of overwriting each other. + */ + mutateProfiles: (updater: AgentProfileListUpdater) => Promise; } 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 => { + if (!serverId) { + return null; + } + return sharedProfileWriteQueue.enqueue(serverId, { + readCurrent: () => { + const cached = queryClient.getQueryData(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, }; } diff --git a/packages/app/src/agent-profiles/internal/use-profile-form-model.ts b/packages/app/src/agent-profiles/internal/use-profile-form-model.ts index f800252be4..3a263d3452 100644 --- a/packages/app/src/agent-profiles/internal/use-profile-form-model.ts +++ b/packages/app/src/agent-profiles/internal/use-profile-form-model.ts @@ -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; +} + +/** + * 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; + onSaved: () => void; +}): AgentProfileFormSession { + const { entries } = useProvidersSnapshot(serverId, { cwd: null }); + const snapshot = useMemo( + () => ({ + 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 => { + 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]); +} diff --git a/packages/app/src/agent-profiles/settings/agent-profile-appearance-field.tsx b/packages/app/src/agent-profiles/settings/agent-profile-appearance-field.tsx index f9200b1565..5671ab43d0 100644 --- a/packages/app/src/agent-profiles/settings/agent-profile-appearance-field.tsx +++ b/packages/app/src/agent-profiles/settings/agent-profile-appearance-field.tsx @@ -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 ( - - + ); } @@ -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 ( - - + {selected ? ( ) : null} - + ); } /** - * 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 ( - + <> - - - + {variant === "hero" ? ( + + + + ) : ( + + )} + {AGENT_PROFILE_ICON_KEYS.map((key) => ( @@ -265,7 +278,7 @@ export function AgentProfileAppearanceField({ - + ); } @@ -279,6 +292,8 @@ function identitySwatch(color: Exclude) { 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, diff --git a/packages/app/src/agent-profiles/settings/agent-profile-drawer.tsx b/packages/app/src/agent-profiles/settings/agent-profile-drawer.tsx new file mode 100644 index 0000000000..c82dbada38 --- /dev/null +++ b/packages/app/src/agent-profiles/settings/agent-profile-drawer.tsx @@ -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 = ; +const removeMenuIcon = ; + +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; + 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 ; + } + const key = + props.mode === "edit" + ? `drawer-edit:${props.profile?.id ?? ""}` + : `drawer-create:${props.seed?.provider ?? ""}:${props.seed?.modelId ?? ""}`; + return ; +} + +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 ; +} + +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 ( + + + + + + {onDuplicate ? ( + + {t("settings.host.agentProfiles.duplicate")} + + ) : null} + {onDuplicate && onRemove ? : null} + {onRemove ? ( + + {t("settings.host.agentProfiles.remove")} + + ) : null} + + + ); +} + +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 ( + + + + + + + + + {title} + + + {subtitle} + + + + + {showSteppers && onStepPrev && onStepNext ? ( + <> + + + + + + + + ) : null} + {mode === "edit" ? ( + + ) : null} + + + + + + + ); +} + +function DrawerFooter({ + canSubmit, + isSubmitting, + onClose, + onSave, +}: { + canSubmit: boolean; + isSubmitting: boolean; + onClose: () => void; + onSave: () => void; +}): ReactElement { + const { t } = useTranslation(); + return ( + + + + + ); +} + +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 = ( + + + + + + + + + + + + + + + + ); + + if (!overlay) { + return drawerPanel; + } + + return ( + + + + {drawerPanel} + + ); +} + +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, + }, +})); diff --git a/packages/app/src/agent-profiles/settings/agent-profile-edit-modal.tsx b/packages/app/src/agent-profiles/settings/agent-profile-edit-modal.tsx index 1fb3c0620a..b0c395eba3 100644 --- a/packages/app/src/agent-profiles/settings/agent-profile-edit-modal.tsx +++ b/packages/app/src/agent-profiles/settings/agent-profile-edit-modal.tsx @@ -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; + 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(() => @@ -101,10 +84,24 @@ export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactE return null; } + const activeProps = props.visible ? props : renderedProps; + + if (activeProps.session) { + return ( + + ); + } + return ( - [] { - 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 ; } -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( () => ({ @@ -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 ( - - - - - { + if (!profile || !onRemove) { + return; + } + onRemove(profile.id); + }, [onRemove, profile]); + + const footer = useMemo( + () => ( + + + {mode === "edit" && profile && onRemove ? ( + + ) : null} - - 6} - title={t("settings.host.agentProfiles.providerLabel")} - size={controlSize} - testID="agent-profile-provider-field" - triggerTestID="agent-profile-provider-trigger" - /> - - {state.disclosure.showModelField ? ( - 6} - title={t("settings.host.agentProfiles.modelLabel")} - size={controlSize} - testID="agent-profile-model-field" - triggerTestID="agent-profile-model-trigger" - /> - ) : null} - - {state.disclosure.showModeField ? ( - 6} - title={t("settings.host.agentProfiles.modeLabel")} - size={controlSize} - testID="agent-profile-mode-field" - triggerTestID="agent-profile-mode-trigger" - /> - ) : null} - - {state.disclosure.showThinkingField ? ( - 6} - title={t("settings.host.agentProfiles.thinkingLabel")} - size={controlSize} - testID="agent-profile-thinking-field" - triggerTestID="agent-profile-thinking-trigger" - /> - ) : null} - - {state.disclosure.showControlsField ? ( - - - {state.controls.map((control, index) => ( - - ))} - - - ) : null} - - - - - - {state.submitError ? ( - - {state.submitError} - - ) : null} - - + + ), + [ + handleCancel, + handleRemove, + handleSavePress, + mode, + onRemove, + profile, + state.canSubmit, + state.isSubmitting, + t, + ], + ); + + return ( + + ); } -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[]>( - () => - 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(() => { - 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 ( - - - - ); - } - - return ( - - - - {control.label} - - {control.description ? ( - - {control.description} - - ) : null} - - - - ); -} - 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], }, })); diff --git a/packages/app/src/agent-profiles/settings/agent-profile-form-fields.tsx b/packages/app/src/agent-profiles/settings/agent-profile-form-fields.tsx new file mode 100644 index 0000000000..3cfa2c250b --- /dev/null +++ b/packages/app/src/agent-profiles/settings/agent-profile-form-fields.tsx @@ -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[] { + 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[]>( + () => + 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 ( + + + + ); + } + return ( + 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 ( + + ); + } + + return ( + + ); +} + +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 ? ( + + ) : null, + [state.controlsPending], + ); + + return ( + <> + {state.disclosure.showModeField ? ( + 6} + title={t("settings.host.agentProfiles.modeLabel")} + size={controlSize} + testID="agent-profile-mode-field" + triggerTestID="agent-profile-mode-trigger" + /> + ) : null} + + + + + + + + {state.disclosure.showControlsField ? ( + + + + {state.controls.map((control) => ( + + ))} + + + + ) : 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(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 ? ( + + ) : 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 ( + + ); + }, + [ + 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 = ( + + ); + + return ( + + + + + + + + {showInlineIcon ? ( + + ) : null} + + + + + + + {collapsibleDefaults ? ( + + + {advancedFields} + + + ) : ( + advancedFields + )} + + {state.submitError ? ( + + {state.submitError} + + ) : null} + + ); +} + +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, + }, +})); diff --git a/packages/app/src/agent-profiles/settings/agent-profile-row.tsx b/packages/app/src/agent-profiles/settings/agent-profile-row.tsx index 260bec4668..869013d9e5 100644 --- a/packages/app/src/agent-profiles/settings/agent-profile-row.tsx +++ b/packages/app/src/agent-profiles/settings/agent-profile-row.tsx @@ -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 = ; -const moveDownIcon = ; -const editIcon = ; -const removeIcon = ; +const editMenuIcon = ; +const duplicateMenuIcon = ; +const moveUpMenuIcon = ; +const moveDownMenuIcon = ; +const moveTopMenuIcon = ( + +); +const removeMenuIcon = ; + +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 ( + + + + + + + {t("settings.host.agentProfiles.editProfile")} + + + {t("settings.host.agentProfiles.duplicate")} + + {showReorderItems ? ( + <> + + {!isFirst ? ( + + {t("settings.host.agentProfiles.moveUp")} + + ) : null} + {!isLast ? ( + + {t("settings.host.agentProfiles.moveDown")} + + ) : null} + {!isFirst ? ( + + {t("settings.host.agentProfiles.moveToTop")} + + ) : null} + + ) : null} + + + {t("settings.host.agentProfiles.remove")} + + + + ); +} + +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 = ( + + + + ); + + if (isStacked) { + return ( + + {iconTile} + + + {profile.name} + + + + + {fullSummary} + + + {profile.notes ? ( + + {profile.notes} + + ) : null} + + + ); + } + + return ( + + + {iconTile} + + {profile.name} + + + + + + + {modelLabel ?? providerLabel} + + + + {runtimeSubline} + + + + {profile.notes ? ( + + {profile.notes} + + ) : ( + + {t("settings.host.agentProfiles.noRoutingNote")} + + )} + + + ); +} + +/** + * 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 ( - - - - + + + + {selected ? : null} + + {reorderable ? ( + + + + - - - - {profile.name} - - - {summary} - - - {profile.notes ? ( - - - - {profile.notes} - - - ) : null} + ) : ( + + )} + + + + + + + + + - - - + + + ); + } + if (filteredProfiles.length === 0) { + return ( + + + {t("settings.host.agentProfiles.noSearchMatches", { query: searchQuery.trim() })} + + + ); + } + return ( + <> + {!useCompactRows ? : null} + {isFiltering ? ( + + {filteredProfiles.map((profile, index) => ( + + ))} + + ) : ( + + )} + + + + + ); +} + +function duplicateAgentProfileById( + current: readonly AgentProfile[], + id: string, + formatCopyName: (name: string) => string, +): { next: AgentProfile[]; copyId: string } | null { + const index = current.findIndex((entry) => entry.id === id); + if (index < 0) { + return null; + } + const source = current[index]; + const copy: AgentProfile = { + ...source, + id: generateAgentProfileId(), + name: formatCopyName(source.name), + }; + const next = [...current]; + next.splice(index + 1, 0, copy); + return { next, copyId: copy.id }; +} + +interface DiscardApprovalTicket { + token: number; + revision: number; +} + +function useAgentProfileRosterActions({ + profiles, + mutateProfiles, + confirmDiscardIfDirty, + editTarget, + applyDelayedEditTarget, + closeIfEditingProfile, +}: { + profiles: AgentProfile[] | null | undefined; + mutateProfiles: (updater: AgentProfileListUpdater) => Promise; + confirmDiscardIfDirty: () => Promise; + editTarget: EditTarget | null; + applyDelayedEditTarget: ( + expectedToken: number, + next: EditTarget | null, + options?: { approvedRevision?: number }, + ) => void; + closeIfEditingProfile: (profileId: string) => void; +}) { + const { t } = useTranslation(); + const toast = useToast(); const handleSave = useCallback( async (value: AgentProfileValue) => { - const current = profiles ?? []; - const editing = editTarget?.mode === "edit" ? editTarget.profile : undefined; - // The edited profile is replaced, not merged: `value` omits the fields the - // user cleared, so spreading it over the stored record would silently keep - // the old model, mode, thinking option or notes. - const next: AgentProfile[] = editing - ? current.map((entry) => (entry.id === editing.id ? { id: entry.id, ...value } : entry)) - : [...current, { id: generateAgentProfileId(), ...value }]; - await saveProfiles(next); + const editingId = editTarget?.mode === "edit" ? editTarget.profileId : null; + // The edited profile is replaced, not merged: `value` omits cleared fields. + await mutateProfiles((current) => + editingId + ? current.map((entry) => (entry.id === editingId ? { id: entry.id, ...value } : entry)) + : [...current, { id: generateAgentProfileId(), ...value }], + ); }, - [editTarget, profiles, saveProfiles], + [editTarget, mutateProfiles], ); - const reorder = useCallback( - async (id: string, offset: -1 | 1) => { - if (!profiles) { - return; - } - const index = profiles.findIndex((entry) => entry.id === id); - const target = index + offset; - if (index < 0 || target < 0 || target >= profiles.length) { - return; - } - const next = [...profiles]; - const [item] = next.splice(index, 1); - next.splice(target, 0, item); + const persistMutation = useCallback( + async (updater: AgentProfileListUpdater): Promise => { try { - await saveProfiles(next); + const written = await mutateProfiles(updater); + return written !== null; } catch (error) { - Alert.alert( - t("common.errors.unableToSave"), - error instanceof Error ? error.message : String(error), + const detail = toErrorMessage(error); + toast.error( + detail + ? `${t("common.errors.unableToSave")}: ${detail}` + : t("common.errors.unableToSave"), ); + return false; } }, - [profiles, saveProfiles, t], + [mutateProfiles, t, toast], ); - const handleMoveUp = useCallback((id: string) => void reorder(id, -1), [reorder]); - const handleMoveDown = useCallback((id: string) => void reorder(id, 1), [reorder]); + const handleDragEnd = useCallback( + (reordered: AgentProfile[]) => { + const orderedIds = reordered.map((entry) => entry.id); + void persistMutation((current) => { + const byId = new Map(current.map((entry) => [entry.id, entry])); + const next: AgentProfile[] = []; + for (const id of orderedIds) { + const entry = byId.get(id); + if (entry) { + next.push(entry); + byId.delete(id); + } + } + for (const remaining of byId.values()) { + next.push(remaining); + } + return next; + }); + }, + [persistMutation], + ); + + const reorderByOffset = useCallback( + (id: string, offset: -1 | 1) => { + void persistMutation((current) => { + const index = current.findIndex((entry) => entry.id === id); + const target = index + offset; + if (index < 0 || target < 0 || target >= current.length) { + return null; + } + const next = [...current]; + const [item] = next.splice(index, 1); + next.splice(target, 0, item); + return next; + }); + }, + [persistMutation], + ); + + const handleMoveUp = useCallback((id: string) => reorderByOffset(id, -1), [reorderByOffset]); + const handleMoveDown = useCallback((id: string) => reorderByOffset(id, 1), [reorderByOffset]); + + const handleMoveToTop = useCallback( + (id: string) => { + void persistMutation((current) => { + const index = current.findIndex((entry) => entry.id === id); + if (index <= 0) { + return null; + } + const next = [...current]; + const [item] = next.splice(index, 1); + next.unshift(item); + return next; + }); + }, + [persistMutation], + ); + + const handleDuplicate = useCallback( + (id: string) => { + const formatCopyName = (name: string) => t("settings.host.agentProfiles.copyName", { name }); + const duplicate = async () => { + const ticket = await confirmDiscardIfDirty(); + if (!ticket) { + return; + } + let copyId: string | null = null; + const saved = await persistMutation((current) => { + const result = duplicateAgentProfileById(current, id, formatCopyName); + if (!result) { + return null; + } + copyId = result.copyId; + return result.next; + }); + if (saved && copyId) { + // Only open the copy if no newer editor session or draft edit happened since confirmation. + applyDelayedEditTarget( + ticket.token, + { mode: "edit", profileId: copyId }, + { approvedRevision: ticket.revision }, + ); + } + }; + void duplicate(); + }, + [applyDelayedEditTarget, confirmDiscardIfDirty, persistMutation, t], + ); const handleRemove = useCallback( (id: string) => { @@ -96,120 +398,687 @@ export function AgentProfilesSection({ serverId }: { serverId: string }): ReactE if (!profile) { return; } - void 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, - }).then(async (confirmed) => { - if (!confirmed || !profiles) { + 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 { - await saveProfiles(profiles.filter((entry) => entry.id !== id)); - } catch (error) { - Alert.alert( - t("common.errors.unableToSave"), - error instanceof Error ? error.message : String(error), - ); + const removed = await persistMutation((current) => removeAgentProfileById(current, id)); + if (removed) { + closeIfEditingProfile(id); } - return; - }); + }; + void confirmAndRemove(); }, - [profiles, saveProfiles, t], + [closeIfEditingProfile, persistMutation, profiles, t], ); - const addButton = useMemo( - () => ( - - - )} + + - + - - + {editorTarget ? ( + 0} + canStepNext={canStepNext} + activeFormRef={activeFormRef} + onDirtyChange={notifyDirtyListeners} + onStepPrev={handleStepPrev} + onStepNext={handleStepNext} + onClose={handleEditClose} + onSaved={handleSavedClose} + onSave={handleSave} + onDuplicate={handleDuplicate} + onRemove={handleRemove} + /> + ) : null} + ); } const styles = StyleSheet.create((theme) => ({ - emptyCard: { - paddingVertical: theme.spacing[6], - paddingHorizontal: theme.spacing[4], + splitContainer: { + position: "relative", + flex: 1, + minWidth: 0, + minHeight: 0, + flexDirection: "row", + }, + rosterPane: { + flex: 1, + minWidth: 0, + minHeight: 0, + }, + rosterContainer: { + gap: theme.spacing[4], + }, + toolbar: { + flexDirection: "row", alignItems: "center", - gap: theme.spacing[3], + }, + tableHeader: { + flexDirection: "row", + alignItems: "center", + paddingVertical: theme.spacing[2], + paddingLeft: theme.spacing[2], + paddingRight: theme.spacing[4], + gap: theme.spacing[2], + borderBottomWidth: theme.borderWidth[1], + borderBottomColor: theme.colors.border, + }, + tableHeaderGripSpacer: { + width: ROSTER_GRIP_WIDTH, + flexShrink: 0, + }, + tableHeaderColumns: { + flex: 1, + minWidth: 0, + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[4], + }, + tableHeaderTrailingSpacer: { + width: ROSTER_TRAILING_WIDTH, + flexShrink: 0, + }, + tableHeaderText: { + color: theme.colors.foregroundExtraMuted, + fontSize: theme.fontSize.sm, + fontWeight: theme.fontWeight.medium, + }, + colProfileHeader: { + width: ROSTER_COL_PROFILE_WIDTH, + flexShrink: 0, + }, + colRuntimeHeader: { + width: ROSTER_COL_RUNTIME_WIDTH, + flexShrink: 0, + }, + colNotesHeader: { + flex: 1, + minWidth: 0, + }, + emptyCard: { + paddingHorizontal: theme.spacing[4], + paddingVertical: theme.spacing[6], + gap: theme.spacing[2], + alignItems: "flex-start", }, emptyText: { color: theme.colors.foregroundMuted, - fontSize: theme.fontSize.base, - textAlign: "center", + fontSize: theme.fontSize.sm, + }, + emptyAction: { + marginTop: theme.spacing[2], }, })); diff --git a/packages/app/src/agent-stream/layout.test.ts b/packages/app/src/agent-stream/layout.test.ts index e41c05dec9..fd2a35491d 100644 --- a/packages/app/src/agent-stream/layout.test.ts +++ b/packages/app/src/agent-stream/layout.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from "vitest"; import type { TurnTiming } from "@/timeline/turn-time"; +import type { TimelineItemTransform } from "@/plugins/timeline"; +import { projectPluginTimelineItems } from "@/plugins/timeline/projection"; import type { StreamItem } from "@/types/stream"; import { orderHeadForStreamRenderStrategy, @@ -578,4 +580,40 @@ describe("layoutStream", () => { expect(footerOwners(layout)).toEqual([]); }, ); + + it.each(["web", "android"] as const)( + "attaches the turn footer to the final card of a plugin-split reply on %s", + (platform) => { + const metrics = [{ label: "Model", value: "opus" }]; + const first = { ...assistantMessage("a1", 2), turnMetrics: [{ label: "Steps", value: "1" }] }; + const latest = { ...assistantMessage("a2", 4), turnMetrics: metrics }; + const splitIntoCards: TimelineItemTransform = ({ item, sourceId }) => + item.type !== "assistant_message" + ? undefined + : ["text", "card"].map((part) => ({ + type: "plugin", + id: `${sourceId}/${part}`, + pluginId: "genui", + kind: `genui-${part}`, + version: 1, + data: {}, + })); + const tail = projectPluginTimelineItems( + [userMessage("u1", 1), first, userMessage("u2", 3), latest], + splitIntoCards, + ); + + const layout = layoutFor({ + platform, + tail, + timingIds: ["genui/a1/card", "genui/a2/card"], + }); + + expect(footerOwners(layout)).toEqual(["genui/a1/card", "genui/a2/card"]); + expect(findLayoutItem(layout, "genui/a1/card").completedFooter?.turnMetrics).toBe( + first.turnMetrics, + ); + expect(layout.auxiliaryTurnFooter?.turnMetrics).toBe(metrics); + }, + ); }); diff --git a/packages/app/src/agent-stream/layout.ts b/packages/app/src/agent-stream/layout.ts index e1918ddc4f..7b459cb9d2 100644 --- a/packages/app/src/agent-stream/layout.ts +++ b/packages/app/src/agent-stream/layout.ts @@ -1,6 +1,6 @@ import type { AgentMetric } from "@getpaseo/protocol/agent-types"; import type { TurnTiming } from "@/timeline/turn-time"; -import type { StreamItem } from "@/types/stream"; +import { getAssistantReply, type StreamItem } from "@/types/stream"; import { getAssistantMessageSpacing, getGapBetweenStreamItems } from "./spacing"; import type { StreamFrameChildOrder, StreamStrategy } from "./strategy"; import { continuesResponse, continuesTurn, isResponseBoundary } from "./turn-membership"; @@ -72,9 +72,9 @@ function createTurnFooterHost(input: { timingByItemId: Map; }): TurnFooterHost { const turnMetrics = - input.item.kind === "assistant_message" || input.item.kind === "tool_call" + input.item.kind === "tool_call" ? input.item.turnMetrics - : undefined; + : getAssistantReply(input.item)?.turnMetrics; return { itemId: input.item.id, items: input.items, @@ -109,7 +109,7 @@ function findTurnFooterSource(input: { if (!item || (laterItem && !continuesResponse(item, laterItem))) { return toolFallback; } - if (item.kind === "assistant_message") { + if (getAssistantReply(item)) { return { item, items, index }; } laterItem = item; diff --git a/packages/app/src/agent-stream/render-strategy.test.ts b/packages/app/src/agent-stream/render-strategy.test.ts index 5e5ab7f7a2..14a6418956 100644 --- a/packages/app/src/agent-stream/render-strategy.test.ts +++ b/packages/app/src/agent-stream/render-strategy.test.ts @@ -28,7 +28,11 @@ function userMessage(id: string, text: string, seed: number): StreamItem { }; } -function assistantMessage(id: string, text: string, seed: number): StreamItem { +function assistantMessage( + id: string, + text: string, + seed: number, +): Extract { return { kind: "assistant_message", id, @@ -243,4 +247,38 @@ describe("layout strategy edges", () => { "content-then-footer", ); }); + + it.each(PLATFORMS)("copies a reply split into plugin cards once on %s", (platform) => { + const strategy = strategyFor(platform); + const splitReply = assistantMessage("a2", 'Summary\n\n```ui\nCard("Hi", [])\n```', 3); + const card = (part: string): StreamItem => ({ + kind: "plugin", + id: `genui/a2/${part}`, + source: splitReply, + timestamp: splitReply.timestamp, + pluginId: "genui", + pluginItemId: `a2/${part}`, + itemKind: `genui-${part}`, + version: 1, + data: {}, + }); + const items = orderTailForStreamRenderStrategy({ + strategy, + streamItems: [ + userMessage("u1", "prompt", 1), + assistantMessage("a1", "Before card", 2), + card("text"), + card("card"), + ], + }); + const startIndex = items.findIndex((item) => item.id === "genui/a2/card"); + + expect( + collectAssistantResponseContentForStreamRenderStrategy({ + strategy, + items, + startIndex, + }), + ).toBe(`Before card\n\n${splitReply.text}`); + }); }); diff --git a/packages/app/src/agent-stream/strategy.ts b/packages/app/src/agent-stream/strategy.ts index 7507f3442b..6a5db45c05 100644 --- a/packages/app/src/agent-stream/strategy.ts +++ b/packages/app/src/agent-stream/strategy.ts @@ -1,6 +1,6 @@ import type { ComponentType, ReactElement, ReactNode, RefObject } from "react"; import type { StyleProp, ViewStyle } from "react-native"; -import type { StreamItem } from "@/types/stream"; +import { getAssistantReply, type StreamItem } from "@/types/stream"; import type { ReadingRowReplacements } from "./reading-anchor"; import { continuesResponse } from "./turn-membership"; import type { StreamHistoryBoundary, StreamRenderSegments } from "./model"; @@ -185,6 +185,7 @@ export function createStreamStrategy(config: StreamStrategyConfig): StreamStrate }, collectAssistantResponseContent: (items, startIndex) => { const messages: string[] = []; + const seenReplies = new Set(); let laterItem: StreamItem | null = null; for ( let index = startIndex; @@ -195,8 +196,11 @@ export function createStreamStrategy(config: StreamStrategyConfig): StreamStrate if (!currentItem || (laterItem && !continuesResponse(currentItem, laterItem))) { break; } - if (currentItem.kind === "assistant_message") { - messages.push(currentItem.text); + // A transformer can split one reply into several cards; copy the reply once. + const reply = getAssistantReply(currentItem); + if (reply && !seenReplies.has(reply)) { + seenReplies.add(reply); + messages.push(reply.text); } laterItem = currentItem; } diff --git a/packages/app/src/agent-stream/turn-boundary.test.ts b/packages/app/src/agent-stream/turn-boundary.test.ts index 14e5ea776d..9cfc14a622 100644 --- a/packages/app/src/agent-stream/turn-boundary.test.ts +++ b/packages/app/src/agent-stream/turn-boundary.test.ts @@ -112,4 +112,63 @@ describe("resolveAssistantTurnForkBoundary", () => { }), ).toBeUndefined(); }); + + it("resolves a fork boundary from the reply a plugin card replaced", () => { + const reply = { + ...assistantMessage("assistant-1", 2, "msg-assistant-1"), + timelineCursor: { epoch: "timeline-1", seq: 42 }, + }; + const card: StreamItem = { + kind: "plugin", + id: "genui/assistant-1/1", + source: reply, + timelineCursor: reply.timelineCursor, + timestamp: reply.timestamp, + pluginId: "genui", + pluginItemId: "assistant-1/1", + itemKind: "genui-block", + version: 1, + data: {}, + }; + + expect( + resolveAssistantTurnForkBoundary({ + items: [userMessage("user-1", 1), card], + startIndex: 1, + supportsTimelineCursor: true, + }), + ).toEqual({ + boundaryCursor: { epoch: "timeline-1", seq: 42 }, + boundaryMessageId: "msg-assistant-1", + }); + expect( + resolveAssistantTurnForkBoundary({ + items: [userMessage("user-1", 1), card], + startIndex: 1, + supportsTimelineCursor: false, + }), + ).toEqual({ boundaryMessageId: "msg-assistant-1" }); + }); + + it("ignores plugin cards that did not replace a reply", () => { + const appended: StreamItem = { + kind: "plugin", + id: "plugin/card-1", + timelineCursor: { epoch: "timeline-1", seq: 42 }, + timestamp: timestamp(2), + pluginId: "plugin", + pluginItemId: "card-1", + itemKind: "card", + version: 1, + data: {}, + }; + + expect( + resolveAssistantTurnForkBoundary({ + items: [userMessage("user-1", 1), appended], + startIndex: 1, + supportsTimelineCursor: true, + }), + ).toBeUndefined(); + }); }); diff --git a/packages/app/src/agent-stream/turn-boundary.ts b/packages/app/src/agent-stream/turn-boundary.ts index f7cbe8c00f..659ff4a254 100644 --- a/packages/app/src/agent-stream/turn-boundary.ts +++ b/packages/app/src/agent-stream/turn-boundary.ts @@ -1,4 +1,4 @@ -import type { StreamItem, TimelinePosition } from "@/types/stream"; +import { getAssistantReply, type StreamItem, type TimelinePosition } from "@/types/stream"; export type AssistantTurnForkBoundary = | { boundaryCursor: TimelinePosition; boundaryMessageId?: string } @@ -9,15 +9,15 @@ export function resolveAssistantTurnForkBoundary(input: { startIndex: number; supportsTimelineCursor: boolean; }): AssistantTurnForkBoundary | undefined { - const item = input.items[input.startIndex]; - if (item?.kind !== "assistant_message") { + const reply = getAssistantReply(input.items[input.startIndex]); + if (!reply) { return undefined; } - if (input.supportsTimelineCursor && item.timelineCursor) { + if (input.supportsTimelineCursor && reply.timelineCursor) { return { - boundaryCursor: item.timelineCursor, - ...(item.messageId ? { boundaryMessageId: item.messageId } : {}), + boundaryCursor: reply.timelineCursor, + ...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}), }; } - return item.messageId ? { boundaryMessageId: item.messageId } : undefined; + return reply.messageId ? { boundaryMessageId: reply.messageId } : undefined; } diff --git a/packages/app/src/agent-stream/turn-collapse/model.test.ts b/packages/app/src/agent-stream/turn-collapse/model.test.ts index 9c48f5695a..6438ca19d9 100644 --- a/packages/app/src/agent-stream/turn-collapse/model.test.ts +++ b/packages/app/src/agent-stream/turn-collapse/model.test.ts @@ -16,8 +16,7 @@ function pluginReply(sourceId: string, part = "0"): StreamItem { return { kind: "plugin", id: `math/${sourceId}/${part}`, - sourceId, - sourceKind: "assistant_message", + source: reply(sourceId), timestamp: at, pluginId: "math", pluginItemId: `${sourceId}/${part}`, @@ -99,10 +98,10 @@ describe("collapseTurns", () => { expect(result.hostIdByFoldedMessageId.get("intermediate")).toBe("prompt"); }); - it.each([undefined, "thought", "tool_call"] as const)( - "does not treat a plugin row with source kind %s as a reply", - (sourceKind) => { - const card = { ...pluginReply("card"), sourceKind }; + it.each([undefined, thought("card"), shell("card")])( + "does not treat a plugin row replacing %o as a reply", + (source) => { + const card = { ...pluginReply("card"), source }; const items = [user("prompt"), shell("call"), card]; expect(collapse(items).tail).toEqual(items); expect(collapse(items).summaryRowsByHostId.size).toBe(0); diff --git a/packages/app/src/agent-stream/turn-collapse/model.ts b/packages/app/src/agent-stream/turn-collapse/model.ts index fe931afed5..dae4fa8556 100644 --- a/packages/app/src/agent-stream/turn-collapse/model.ts +++ b/packages/app/src/agent-stream/turn-collapse/model.ts @@ -1,6 +1,7 @@ import { isTurnBoundary, isTurnTrigger } from "../turn-membership"; import { getStreamItemMessageId, + getAssistantReply, type StreamItem, type ThoughtItem, type TimelinePosition, @@ -103,22 +104,15 @@ function staysVisibleWhenCollapsed(item: StreamItem): boolean { return isTurnTrigger(item) || item.kind === "compaction"; } -function isAssistantReply(item: StreamItem): boolean { - return ( - item.kind === "assistant_message" || - (item.kind === "plugin" && item.sourceKind === "assistant_message") - ); -} - function findLastReplyIndex(tail: StreamItem[], start: number, end: number): number { for (let index = end - 1; index >= start; index -= 1) { const item = tail[index]!; - if (!isAssistantReply(item)) continue; + if (!getAssistantReply(item)) continue; const messageId = getStreamItemMessageId(item); // A transformer can split one reply into several cards; keep the whole reply visible. while (index > start) { const previous = tail[index - 1]!; - if (!isAssistantReply(previous) || getStreamItemMessageId(previous) !== messageId) break; + if (!getAssistantReply(previous) || getStreamItemMessageId(previous) !== messageId) break; index -= 1; } return index; @@ -156,7 +150,7 @@ export function collapseTurns(input: CollapseTurnsInput): TurnCollapse { } const folded = tail.slice(runStart, replyIndex); const tools = summarizeTurn(folded, input.getGroupedCalls); - if (!hasWork(tools) && !folded.some(isAssistantReply)) { + if (!hasWork(tools) && !folded.some((item) => getAssistantReply(item))) { output.push(...tail.slice(runStart, runEnd)); return; } diff --git a/packages/app/src/agent-stream/turn-footer.browser.test.tsx b/packages/app/src/agent-stream/turn-footer.browser.test.tsx index 46a51c0f34..3851c66fb8 100644 --- a/packages/app/src/agent-stream/turn-footer.browser.test.tsx +++ b/packages/app/src/agent-stream/turn-footer.browser.test.tsx @@ -150,3 +150,44 @@ describe("turn stats", () => { expect(host.getBoundingClientRect().height).toBe(without); }); }); + +const projectedReply: StreamItem = { + kind: "plugin", + id: "genui/reply/1", + source: { + kind: "assistant_message", + id: "reply", + messageId: "provider-reply-1", + text: 'Done.\n\n```ui\nCard("Summary", [])\n```', + timelineCursor: { epoch: "e1", seq: 5 }, + timestamp: FRIDAY_NIGHT, + }, + timelineCursor: { epoch: "e1", seq: 5 }, + timestamp: FRIDAY_NIGHT, + pluginId: "genui", + pluginItemId: "reply/1", + itemKind: "genui-block", + version: 1, + data: {}, +}; + +it("renders copy, fork, and duration for a plugin-projected assistant reply", () => { + const onFork = vi.fn(); + + act(() => + root.render( + , + ), + ); + + expect(host.querySelector('[aria-label="Copy turn"]')).not.toBeNull(); + expect(host.querySelector('[aria-label="Fork chat from here"]')).not.toBeNull(); + expect(host.textContent).toContain("Worked for 26s"); +}); diff --git a/packages/app/src/agent-stream/turn-footer.tsx b/packages/app/src/agent-stream/turn-footer.tsx index 93574a61d2..4d9d87e97f 100644 --- a/packages/app/src/agent-stream/turn-footer.tsx +++ b/packages/app/src/agent-stream/turn-footer.tsx @@ -4,7 +4,7 @@ import { View } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { SPACING, type Theme } from "@/styles/theme"; import type { TurnTiming } from "@/timeline/turn-time"; -import type { StreamItem } from "@/types/stream"; +import { getAssistantReply, type StreamItem } from "@/types/stream"; import { collectAssistantResponseContentForStreamRenderStrategy, type StreamStrategy, @@ -208,7 +208,7 @@ function CompletedTurnFooter({ return ( void; onEditProfiles?: () => void; - onCreateProfile?: (seed: AgentProfileSeed) => void; + onCreateProfile?: (seed: AgentProfileSeed) => Promise | 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( diff --git a/packages/app/src/components/model-browser.tsx b/packages/app/src/components/model-browser.tsx index 8f49230219..3fd13ee6c7 100644 --- a/packages/app/src/components/model-browser.tsx +++ b/packages/app/src/components/model-browser.tsx @@ -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 | 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 | 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}`} > - + ); } @@ -772,7 +779,13 @@ function ModelRow({ label={t("modelSelector.editProfilesCount", { count: profiledRows.length })} testID={`model-edit-profiles-${row.provider}-${row.modelId}`} > - + ); }, [ @@ -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 | 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( - () => , - [row.color, row.icon], + () => ( + + ), + [row.color, row.icon, row.provider, serverId], ); return ( void; onEditProfiles?: () => void; }) { @@ -937,7 +963,12 @@ function AgentProfilesPickerSection({ ) : null} {rows.map((row) => ( - + ))} ); @@ -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 ( @@ -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({ @@ -1207,7 +1244,7 @@ function ModelRowList({ header?: React.ReactElement; scrolling: "sheet" | "independent"; profiledLookup: Map; - onCreateProfile?: (seed: AgentProfileSeed) => void; + onCreateProfile?: (seed: AgentProfileSeed) => Promise | 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 | void; onEditProfile?: (profileId: string) => void; profiledLookup: Map; showProfilesSection?: boolean; @@ -1363,6 +1400,7 @@ function ProviderModelBrowserContent({ return ( @@ -1371,6 +1409,7 @@ function ProviderModelBrowserContent({ return matchedProfileRows.length > 0 ? ( 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 ? ( 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 ? ( diff --git a/packages/app/src/composer/agent-controls/index.tsx b/packages/app/src/composer/agent-controls/index.tsx index a362a13107..679dba7595 100644 --- a/packages/app/src/composer/agent-controls/index.tsx +++ b/packages/app/src/composer/agent-controls/index.tsx @@ -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 | 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; 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 | void; onEditAgentProfile?: (profileId: string) => void; onDropdownClose?: () => void; onModelSelectorOpen?: () => void; diff --git a/packages/app/src/composer/agent-controls/model-sheet.tsx b/packages/app/src/composer/agent-controls/model-sheet.tsx index cf95e9d9cc..8a754082a9 100644 --- a/packages/app/src/composer/agent-controls/model-sheet.tsx +++ b/packages/app/src/composer/agent-controls/model-sheet.tsx @@ -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 | 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 | 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) { diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index c7c61bed15..0acd7bbdfb 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -1814,6 +1814,9 @@ export const ar: TranslationResources = { editProfilesLabel: "تحرير ملفات الوكيل", createProfile: "إنشاء ملف شخصي", createProfileFromModel: "إنشاء ملف شخصي من هذا النموذج", + profileSaved: 'تم حفظ "{{name}}"', + undo: "تراجع", + undoProfileSave: "التراجع عن حفظ الملف الشخصي", editProfileLabel: "تحرير {{name}}", editProfilesCount: "تحرير الملفات الشخصية ({{count}})", modelCount: "{{count}} نموذج", @@ -2430,6 +2433,7 @@ export const ar: TranslationResources = { projects: "المشاريع", connections: "اتصالات", agents: "Agents", + agentProfiles: "ملفات الوكيل", metadata: "البيانات الوصفية", voice: "الصوت", workspaces: "Workspaces", @@ -3057,6 +3061,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: { diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 5a787a9563..a9b5f7ffcc 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -1843,6 +1843,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 +2464,7 @@ export const en = { projects: "Projects", connections: "Connections", agents: "Agents", + agentProfiles: "Agent profiles", metadata: "Metadata", voice: "Voice", workspaces: "Workspaces", @@ -3147,7 +3151,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 +3159,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: { diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 7b11474b7b..903bf9b193 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -1862,6 +1862,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 +2447,7 @@ export const es: TranslationResources = { projects: "Proyectos", connections: "Conexiones", agents: "Agents", + agentProfiles: "Perfiles de agente", metadata: "Metadatos", voice: "Voz", workspaces: "Workspaces", @@ -3083,6 +3087,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: { diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 2078ebcf85..09f2cb71b4 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -1860,6 +1860,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 +2447,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 +3091,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: { diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index cc52090564..0b9b8f1bc4 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -1834,6 +1834,9 @@ export const ja: TranslationResources = { editProfilesLabel: "エージェントプロファイルを編集", createProfile: "プロファイルを作成", createProfileFromModel: "このモデルからプロファイルを作成", + profileSaved: "「{{name}}」を保存しました", + undo: "元に戻す", + undoProfileSave: "プロファイル保存を取り消す", editProfileLabel: "{{name}}を編集", editProfilesCount: "プロファイルを編集({{count}})", modelCount: "{{count}}つのモデル", @@ -2418,6 +2421,7 @@ export const ja: TranslationResources = { projects: "プロジェクト", connections: "接続", agents: "エージェント", + agentProfiles: "エージェントプロファイル", metadata: "メタデータ", voice: "音声", workspaces: "ワークスペース", @@ -3052,6 +3056,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: { diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 7ac0c76ce1..176ba8c5e1 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -1825,6 +1825,9 @@ export const ko: TranslationResources = { editProfilesLabel: "에이전트 프로필 편집", createProfile: "프로필 만들기", createProfileFromModel: "이 모델에서 프로필 만들기", + profileSaved: '"{{name}}" 저장됨', + undo: "실행 취소", + undoProfileSave: "프로필 저장 취소", editProfileLabel: "{{name}} 편집", editProfilesCount: "프로필 편집 ({{count}})", modelCount: "모델 {{count}}개", @@ -2405,6 +2408,7 @@ export const ko: TranslationResources = { projects: "프로젝트", connections: "연결", agents: "에이전트", + agentProfiles: "에이전트 프로필", metadata: "메타데이터", voice: "음성", workspaces: "워크스페이스", @@ -3036,6 +3040,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: { diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index cb37456400..23862bd4df 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -1847,6 +1847,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 +2432,7 @@ export const ptBR: TranslationResources = { projects: "Projetos", connections: "Conexões", agents: "Agentes", + agentProfiles: "Perfis de agente", metadata: "Metadados", voice: "Voz", workspaces: "Workspaces", @@ -3065,6 +3069,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: { diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 6ca09b5584..0dd150c59c 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -1847,6 +1847,9 @@ export const ru: TranslationResources = { editProfilesLabel: "Изменить профили агентов", createProfile: "Создать профиль", createProfileFromModel: "Создать профиль из этой модели", + profileSaved: "Сохранено: «{{name}}»", + undo: "Отменить", + undoProfileSave: "Отменить сохранение профиля", editProfileLabel: "Изменить {{name}}", editProfilesCount: "Изменить профили ({{count}})", modelCount: "{{count}} модель", @@ -2431,6 +2434,7 @@ export const ru: TranslationResources = { projects: "Проекты", connections: "Подключения", agents: "Агенты", + agentProfiles: "Профили агентов", metadata: "Метаданные", voice: "Голос", workspaces: "Рабочие пространства", @@ -3076,6 +3080,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: { diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 3cb5ccf3de..2a3aa4ccf5 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -1796,6 +1796,9 @@ export const zhCN: TranslationResources = { editProfilesLabel: "编辑智能体配置文件", createProfile: "创建配置文件", createProfileFromModel: "从此模型创建配置文件", + profileSaved: "已保存“{{name}}”", + undo: "撤销", + undoProfileSave: "撤销保存配置文件", editProfileLabel: "编辑 {{name}}", editProfilesCount: "编辑配置文件 ({{count}})", modelCount: "{{count}} 个模型", @@ -2371,6 +2374,7 @@ export const zhCN: TranslationResources = { projects: "项目", connections: "连接", agents: "Agents", + agentProfiles: "智能体配置文件", metadata: "元数据", voice: "语音", workspaces: "Workspaces", @@ -2991,6 +2995,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: { diff --git a/packages/app/src/navigation/route-leave-guard/index.ts b/packages/app/src/navigation/route-leave-guard/index.ts new file mode 100644 index 0000000000..bd6173c3d4 --- /dev/null +++ b/packages/app/src/navigation/route-leave-guard/index.ts @@ -0,0 +1,18 @@ +export interface RouteLeaveGuard { + isDirty: () => boolean; + confirmDiscard: () => Promise; +} + +/** + * 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 () => {}; +} diff --git a/packages/app/src/navigation/route-leave-guard/index.web.test.ts b/packages/app/src/navigation/route-leave-guard/index.web.test.ts new file mode 100644 index 0000000000..7864b0c489 --- /dev/null +++ b/packages/app/src/navigation/route-leave-guard/index.web.test.ts @@ -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(); + 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"); + }); +}); diff --git a/packages/app/src/navigation/route-leave-guard/index.web.ts b/packages/app/src/navigation/route-leave-guard/index.web.ts new file mode 100644 index 0000000000..73018da0e6 --- /dev/null +++ b/packages/app/src/navigation/route-leave-guard/index.web.ts @@ -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 | 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; + } 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 | null = null; + let entryIds: Array = []; + 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); +} diff --git a/packages/app/src/plugins/surface-screen.tsx b/packages/app/src/plugins/surface-screen.tsx index b0d4a2368b..43cbe82288 100644 --- a/packages/app/src/plugins/surface-screen.tsx +++ b/packages/app/src/plugins/surface-screen.tsx @@ -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( () => ( <> + {icon ? ( diff --git a/packages/app/src/plugins/timeline/projection.test.ts b/packages/app/src/plugins/timeline/projection.test.ts index 58d36ad87c..373975b456 100644 --- a/packages/app/src/plugins/timeline/projection.test.ts +++ b/packages/app/src/plugins/timeline/projection.test.ts @@ -98,8 +98,7 @@ describe("plugin timeline projection", () => { { kind: "plugin", id: "inline-thinking/thought-1/0", - sourceId: "thought-1", - sourceKind: "thought", + source: { kind: "thought", id: "thought-1" }, data: { text: "First", phase: "streaming" }, }, ]); @@ -192,4 +191,54 @@ describe("plugin timeline projection", () => { ]); expect(filtered).toEqual([]); }); + + it("keeps the replaced reply on every card it was split into", () => { + const source: StreamItem = { + kind: "assistant_message", + id: "assistant-1", + messageId: "provider-msg-1", + timelineCursor: { epoch: "e1", seq: 7 }, + turnId: "turn-1", + text: 'Summary\n\n```ui\nCard("Hi", [])\n```', + timestamp: new Date("2026-01-01T00:00:02.000Z"), + }; + const split: TimelineItemTransform = ({ sourceId }) => [ + { + type: "plugin", + id: `${sourceId}/text`, + pluginId: "genui", + kind: "genui-text", + version: 1, + data: { part: "text" }, + }, + { + type: "plugin", + id: `${sourceId}/card`, + pluginId: "genui", + kind: "genui-block", + version: 1, + data: { part: "card" }, + }, + ]; + const projected = projectPluginTimelineItems([source], split); + + expect(projected).toMatchObject([ + { + kind: "plugin", + id: "genui/assistant-1/text", + timelineCursor: { epoch: "e1", seq: 7 }, + turnId: "turn-1", + }, + { + kind: "plugin", + id: "genui/assistant-1/card", + timelineCursor: { epoch: "e1", seq: 7 }, + turnId: "turn-1", + }, + ]); + expect(projected.map((item) => item.kind === "plugin" && item.source)).toEqual([ + source, + source, + ]); + }); }); diff --git a/packages/app/src/plugins/timeline/projection.ts b/packages/app/src/plugins/timeline/projection.ts index 4670191746..5836e75aeb 100644 --- a/packages/app/src/plugins/timeline/projection.ts +++ b/packages/app/src/plugins/timeline/projection.ts @@ -95,8 +95,7 @@ function transformSourceItem( const projected: PluginTimelineStreamItem = { kind: "plugin", id: `${pluginItem.pluginId}/${pluginItem.id}`, - sourceId: item.id, - sourceKind: item.kind, + source: item, timestamp: item.timestamp, pluginId: pluginItem.pluginId, pluginItemId: pluginItem.id, diff --git a/packages/app/src/root-app.tsx b/packages/app/src/root-app.tsx index 746a008d58..85ab3fd368 100644 --- a/packages/app/src/root-app.tsx +++ b/packages/app/src/root-app.tsx @@ -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, "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), []); diff --git a/packages/app/src/screens/settings-screen.tsx b/packages/app/src/screens/settings-screen.tsx index cb62c1f6a6..ad6eeb0e4b 100644 --- a/packages/app/src/screens/settings-screen.tsx +++ b/packages/app/src/screens/settings-screen.tsx @@ -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 ; case "agents": return ; + case "agent-profiles": + // Rendered directly in SettingsScreen so AgentProfilesPage owns its wide PageLayout + drawer split. + return null; case "metadata": return ; case "voice": @@ -1104,6 +1111,139 @@ function SettingsSidebar({ ); } +interface SettingsBeforeLeaveGuard { + isDirty: () => boolean; + confirmDiscard: () => Promise; + 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(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["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 ( + + + {isStandaloneAgentProfilesView ? ( + + ) : ( + + {content} + + )} + + + ); +} + // --------------------------------------------------------------------------- // 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[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 ( - - - {content} - - - ); - } - - // 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 ( - - - - - - - {content} - - - + {isCompactLayout ? null : ( + + + + )} + ); @@ -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] }, }, diff --git a/packages/app/src/screens/settings/host-page.tsx b/packages/app/src/screens/settings/host-page.tsx index 6e27f70650..8a1f8c75e5 100644 --- a/packages/app/src/screens/settings/host-page.tsx +++ b/packages/app/src/screens/settings/host-page.tsx @@ -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 }) { )} - ); } +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 ( + + + + ); + } + + return ( + + ); +} + export function HostWorkspacesPage({ serverId }: { serverId: string }) { const { t } = useTranslation(); const host = useHostProfile(serverId); diff --git a/packages/app/src/timeline/turn-time.test.ts b/packages/app/src/timeline/turn-time.test.ts index f3e97b2e49..ab795c6e48 100644 --- a/packages/app/src/timeline/turn-time.test.ts +++ b/packages/app/src/timeline/turn-time.test.ts @@ -247,3 +247,37 @@ it("times a heartbeat that ends with tools and no assistant text", () => { }); assert.equal(timing.byItemId.get("last")?.durationMs, 5000); }); + +it("times a reply that a plugin split into cards", () => { + const userAt = new Date("2026-05-15T00:00:00.000Z"); + const replyAt = new Date("2026-05-15T00:00:06.000Z"); + const reply: StreamItem = { + kind: "assistant_message", + id: "a1", + text: "Intro", + timestamp: replyAt, + }; + const card = (part: string): StreamItem => ({ + kind: "plugin", + id: `genui/a1/${part}`, + source: reply, + timestamp: replyAt, + pluginId: "genui", + pluginItemId: `a1/${part}`, + itemKind: `genui-${part}`, + version: 1, + data: {}, + }); + + const timing = deriveStreamTurnTiming({ + isTurnActive: false, + activeTurnStartedAt: null, + tail: [user("u1", userAt), card("text"), card("card")], + head: [], + }); + + assert.deepEqual(timing.byItemId.get("genui/a1/card"), { + completedAt: replyAt, + durationMs: 6000, + }); +}); diff --git a/packages/app/src/timeline/turn-time.ts b/packages/app/src/timeline/turn-time.ts index 8d1aa00648..a6f11afcf2 100644 --- a/packages/app/src/timeline/turn-time.ts +++ b/packages/app/src/timeline/turn-time.ts @@ -1,4 +1,4 @@ -import type { StreamItem } from "@/types/stream"; +import { getAssistantReply, type StreamItem } from "@/types/stream"; import { startsNewTurn, isTurnTrigger } from "@/agent-stream/turn-membership"; export interface TurnTiming { @@ -70,7 +70,7 @@ function walkTurns( assistantIds = []; } lastItemAt = item.timestamp; - if (item.kind === "assistant_message") { + if (getAssistantReply(item)) { assistantIds.push(item.id); } previousItem = item; diff --git a/packages/app/src/types/stream.ts b/packages/app/src/types/stream.ts index 47138a2575..8f6a572c80 100644 --- a/packages/app/src/types/stream.ts +++ b/packages/app/src/types/stream.ts @@ -783,7 +783,7 @@ export type AgentToolCallItem = ToolCallItem & { /** Find and scrolling address a plugin row by the source it replaces. */ export function getStreamItemMessageId(item: StreamItem): string { - if (item.kind === "plugin") return item.sourceId ?? item.id; + if (item.kind === "plugin") return item.source?.id ?? item.id; return item.id; } @@ -791,6 +791,15 @@ export function isAgentToolCallItem(item: StreamItem): item is AgentToolCallItem return item.kind === "tool_call" && item.payload.source === "agent"; } +/** The assistant reply a row shows: the row itself, or the reply a timeline plugin replaced. */ +export function getAssistantReply( + item: StreamItem | null | undefined, +): AssistantMessageItem | null { + if (item?.kind === "assistant_message") return item; + if (item?.kind === "plugin" && item.source?.kind === "assistant_message") return item.source; + return null; +} + type NotificationLevel = "info" | "warning" | "error"; export interface NotificationItem { @@ -818,10 +827,12 @@ export interface CompactionItem { export interface PluginTimelineStreamItem { kind: "plugin"; id: string; - /** The id of the stream item a timeline transformer replaced; set only by projection. */ - sourceId?: string; - /** The original row kind, retained by projection for turn folding. */ - sourceKind?: StreamItem["kind"]; + /** + * The row a timeline transformer replaced; set only by projection. Turn folding, timing, and the + * turn footer read the replaced row through it, so a transformed reply keeps its copy, fork, + * duration, and stats. + */ + source?: StreamItem; timelineCursor?: TimelinePosition; turnId?: string; timestamp: Date; diff --git a/packages/app/src/utils/host-routes.ts b/packages/app/src/utils/host-routes.ts index 14db64125d..dfbee07821 100644 --- a/packages/app/src/utils/host-routes.ts +++ b/packages/app/src/utils/host-routes.ts @@ -517,6 +517,7 @@ export const HOST_SECTION_SLUGS = [ "connections", "pair-device", "agents", + "agent-profiles", "metadata", "voice", "workspaces", diff --git a/packages/plugin/src/skill-examples.test.ts b/packages/plugin/src/skill-examples.test.ts index 6296178b3d..9561641d8f 100644 --- a/packages/plugin/src/skill-examples.test.ts +++ b/packages/plugin/src/skill-examples.test.ts @@ -6,43 +6,84 @@ 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"); +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; } -// 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 `// ` +// 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 // `); + 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[] { 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 +108,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 +153,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([]); }); diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts index 975ea8c8e9..90cdd1cbc6 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.test.ts @@ -1470,6 +1470,31 @@ describe("Codex app-server provider", () => { } }); + test.each(["thread/start", "thread/resume"] as const)( + "%s appends plugin instructions to the developer instructions configured in Codex", + async (method) => { + const appServer = createFakeCodexAppServer({ + "config/read": () => ({ config: { developer_instructions: "Configured role" } }), + }); + const provider = createProviderWithFakeAppServer(appServer); + const config = { pluginAppendSystemPrompt: ["Plugin instructions"] }; + const session = + method === "thread/start" + ? await provider.createSession(createConfig(config)) + : await provider.resumeSession({ sessionId: "saved-thread" }, config); + try { + await session.startTurn("hello"); + await appServer.waitForTurnStart(); + expect( + appServer.requests().find((request) => request.method === method)?.params, + ).toMatchObject({ developerInstructions: "Configured role\n\nPlugin instructions" }); + appServer.assertNoErrors(); + } finally { + await session.close(); + } + }, + ); + test("reopen injects current instructions once, including an explicit empty snapshot", async () => { const handlers = { initialize: () => ({ userAgent: "codex/0.165.0" }), diff --git a/packages/server/src/server/agent/providers/codex-app-server-agent.ts b/packages/server/src/server/agent/providers/codex-app-server-agent.ts index 1974de11c5..2e9b3ee558 100644 --- a/packages/server/src/server/agent/providers/codex-app-server-agent.ts +++ b/packages/server/src/server/agent/providers/codex-app-server-agent.ts @@ -57,7 +57,7 @@ import path from "node:path"; import { isDeepStrictEqual } from "node:util"; import { z } from "zod"; import { renderPromptAttachmentAsText } from "../prompt-attachments.js"; -import { composeAgentSystemPrompt } from "../system-prompt.js"; +import { composeAgentSystemPrompt, composeSystemPromptParts } from "../system-prompt.js"; import { CodexInstructionSnapshot } from "./codex/instruction-snapshot.js"; import { CodexAsyncQuestions, codexAsyncQuestionToTimeline } from "./codex/async-questions.js"; import { @@ -3797,6 +3797,7 @@ export class CodexAppServerAgentSession implements AgentSession { private resolvedWorkspaceWrite: NonNullable< CodexProviderOptions["sandbox_workspace_write"] > | null = null; + private configuredDeveloperInstructions: string | undefined; private resolvedSandboxPolicy: Record | null = null; private currentThreadId: string | null = null; // Codex writes a new thread's rollout at its first turn. Until then the thread exists only @@ -4062,7 +4063,7 @@ export class CodexAppServerAgentSession implements AgentSession { this.speedModels = CodexModelListResponseSchema.parse(await client.request("model/list", {})).data ?? []; this.normalizeSpeed(); - await this.loadResolvedWorkspaceWrite(); + await this.loadResolvedConfig(); await this.loadCollaborationModes(); await this.loadSkills(); @@ -4093,7 +4094,7 @@ export class CodexAppServerAgentSession implements AgentSession { } } - private async loadResolvedWorkspaceWrite(): Promise { + private async loadResolvedConfig(): Promise { if (!this.client) return; try { const response = toObjectRecord( @@ -4101,11 +4102,25 @@ export class CodexAppServerAgentSession implements AgentSession { ); const config = toObjectRecord(response?.config); this.resolvedWorkspaceWrite = readSandboxWorkspaceWrite(config?.sandbox_workspace_write); + this.configuredDeveloperInstructions = + typeof config?.developer_instructions === "string" + ? config.developer_instructions + : undefined; } catch (error) { - this.logger.debug({ error }, "Failed to read resolved Codex workspace-write config"); + this.logger.debug({ error }, "Failed to read resolved Codex config"); } } + /** + * Codex uses a thread's developerInstructions in place of the developer_instructions in its + * config, so Paseo's instructions carry the configured ones ahead of them. + */ + private threadDeveloperInstructions(): string | undefined { + const paseoInstructions = composeAgentSystemPrompt(this.config); + if (!paseoInstructions) return undefined; + return composeSystemPromptParts(this.configuredDeveloperInstructions, paseoInstructions); + } + private rememberResolvedSandboxPolicy(response: unknown): void { const sandbox = toObjectRecord(toObjectRecord(response)?.sandbox); this.resolvedSandboxPolicy = sandbox ?? null; @@ -4561,7 +4576,7 @@ export class CodexAppServerAgentSession implements AgentSession { // the unnamespaced key emitted by earlier Paseo versions. params.modelProvider = this.deps.customCodexConfig.model_provider; } - const developerInstructions = composeAgentSystemPrompt(this.config); + const developerInstructions = this.threadDeveloperInstructions(); if (developerInstructions) { params.developerInstructions = developerInstructions; } @@ -5526,7 +5541,7 @@ export class CodexAppServerAgentSession implements AgentSession { model: this.config.model ?? null, serviceTier: this.serviceTier, config: this.buildCodexInnerConfig(), - developerInstructions: composeAgentSystemPrompt(this.config), + developerInstructions: this.threadDeveloperInstructions(), userMessageTurns: this.codexUserMessageTurns(), threadRollbackAvailable: this.threadRollbackAvailable, setThreadId: async (threadId) => { @@ -6082,7 +6097,7 @@ export class CodexAppServerAgentSession implements AgentSession { const approvalPolicy = this.hasWorkflowModeOverride ? preset.approvalPolicy : undefined; const sandbox = this.hasWorkflowModeOverride ? preset.sandbox : undefined; const innerConfig = this.buildCodexInnerConfig(); - const developerInstructions = composeAgentSystemPrompt(this.config); + const developerInstructions = this.threadDeveloperInstructions(); const params: Record = { model, cwd: this.config.cwd ?? null, diff --git a/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts b/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts index fa74dfe0bb..895711907e 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/agent.test.ts @@ -1,11 +1,15 @@ -import type { FormInfo, ModelInfo, SessionMessageInfo } from "@opencode/client"; +import { once } from "node:events"; +import { createServer } from "node:http"; +import type { FormInfo, ModelInfo, SessionInfo, SessionMessageInfo } from "@opencode/client"; import { describe, expect, test } from "vitest"; import { createTestLogger } from "../../../../../test-utils/test-logger.js"; import type { AgentStreamEvent } from "../../../agent-sdk-types.js"; +import { ProviderSubagentStore } from "../../../provider-subagents/store.js"; import { OpenCodeV2AgentClient } from "./agent.js"; import { V2Harness } from "../test-utils/v2-harness.js"; import type { V2Api } from "./api.js"; +import { V2Runtime } from "./runtime.js"; function terminalEvents(events: AgentStreamEvent[]) { return events.filter( @@ -756,6 +760,124 @@ describe("OpenCode v2 session lifecycle", () => { } }); + test.each(["with", "without"])( + "removes a tracked child deleted during disconnect %s a launch environment", + async (launchEnvironment) => { + const harness = new V2Harness(); + const child: SessionInfo = { ...harness.info, id: "deleted", parentID: "session" }; + const sibling: SessionInfo = { ...harness.info, id: "sibling", parentID: "session" }; + const grandchild: SessionInfo = { ...harness.info, id: "grandchild", parentID: sibling.id }; + const sessions = new Map([[harness.info.id, harness.info]]); + harness.api.session.list = async ({ parentID } = {}) => ({ + data: parentID ? [...sessions.values()].filter((info) => info.parentID === parentID) : [], + cursor: {}, + }); + harness.api.session.active = async () => + sessions.has(child.id) ? { [child.id]: { type: "running" } } : {}; + + const server = createServer(async (request, response) => { + const pathname = new URL(request.url ?? "/", "http://localhost").pathname; + if (pathname === "/api/info") { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ version: "2.3.0", pid: 1, urls: [], paths: { tmp: "/tmp" } }), + ); + return; + } + const sessionPath = /^\/api\/session\/([^/]+)(\/environment)?$/.exec(pathname); + if (!sessionPath) { + response.writeHead(404).end(); + return; + } + const [, sessionID, environmentPath] = sessionPath; + const info = sessions.get(sessionID); + if (!info) { + response.writeHead(404, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + _tag: "SessionNotFoundError", + sessionID, + message: "Session not found", + }), + ); + return; + } + if (environmentPath && request.method === "PUT") { + const chunks: Buffer[] = []; + for await (const chunk of request) chunks.push(chunk); + const { variables } = JSON.parse(Buffer.concat(chunks).toString("utf8")); + harness.environments.push({ sessionID, variables }); + response.writeHead(204).end(); + return; + } + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ data: info })); + }).listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Missing test server port"); + const logger = createTestLogger(); + const runtime = new V2Runtime({ + logger, + selection: { kind: "explicit", server: { url: `http://127.0.0.1:${address.port}` } }, + }); + + try { + // Keep control of the event stream and turn completion while sending session lookups + // and environment requests through the same HTTP transport as a real server. + const connection = await runtime.acquire(); + harness.api.session.get = connection.client.session.get; + harness.api.session.environment = connection.client.session.environment; + const client = new OpenCodeV2AgentClient({ logger, runtime: harness.runtime }); + const session = await client.createSession( + { provider: "opencode", cwd: "/tmp/project" }, + launchEnvironment === "with" ? { env: { PASEO_AGENT_ID: "parent" } } : undefined, + ); + const store = new ProviderSubagentStore(); + session.subscribe((event) => { + if (event.type === "provider_subagent") store.apply("parent", "opencode", event.event); + }); + try { + for (const info of [child, sibling, grandchild]) sessions.set(info.id, info); + harness.push({ id: child.id, created: 2, type: "session.created", data: child }); + const ids = () => + store + .list("parent") + .map(({ id }) => id) + .sort(); + await expect.poll(ids).toEqual([child.id, grandchild.id, sibling.id]); + expect(store.list("parent").find(({ id }) => id === child.id)?.status).toBe("running"); + + sessions.delete(child.id); + harness.environments.length = 0; + harness.push({ id: "reconnected", created: 3, type: "server.connected", data: {} }); + + await expect.poll(ids).toEqual([grandchild.id, sibling.id]); + if (launchEnvironment === "with") { + await expect + .poll(() => harness.environments) + .toMatchObject([ + { sessionID: harness.info.id, variables: { PASEO_AGENT_ID: "parent" } }, + { sessionID: sibling.id, variables: { PASEO_AGENT_ID: "parent" } }, + { sessionID: grandchild.id, variables: { PASEO_AGENT_ID: "parent" } }, + ]); + } + await expect(session.run("continue after reconnect")).resolves.toMatchObject({ + sessionId: harness.info.id, + }); + } finally { + await session.close(); + } + } finally { + await runtime.shutdown(); + const closed = once(server, "close"); + server.close(); + server.closeAllConnections(); + await closed; + } + }, + ); + test("reconnects after a helper exits and restores session configuration on the next turn", async () => { const first = new V2Harness(); const second = new V2Harness(1); diff --git a/packages/server/src/server/agent/providers/opencode/v2/children.test.ts b/packages/server/src/server/agent/providers/opencode/v2/children.test.ts index 21e2520f80..1ea5f02810 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/children.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/children.test.ts @@ -4,6 +4,7 @@ import { describe, expect, test } from "vitest"; import type { AgentStreamEvent } from "../../../agent-sdk-types.js"; import { V2Harness } from "../test-utils/v2-harness.js"; import { SessionChildren } from "./children.js"; +import { ProviderSubagentStore } from "../../../provider-subagents/store.js"; function setup() { const harness = new V2Harness(); @@ -35,7 +36,204 @@ function setup() { return { children, child, upserts }; } +function setupTree() { + const harness = new V2Harness(); + const sessions = new Map( + [ + { ...harness.info, id: "first", parentID: "session" }, + { ...harness.info, id: "second", parentID: "session" }, + { ...harness.info, id: "grandchild", parentID: "first" }, + ].map((info) => [info.id, info]), + ); + harness.api.session.list = async (input) => ({ + data: [...sessions.values()].filter((info) => info.parentID === input?.parentID), + cursor: {}, + }); + harness.api.session.get = async ({ sessionID }) => { + const info = sessions.get(sessionID); + if (!info) throw { _tag: "SessionNotFoundError", sessionID }; + return info; + }; + const store = new ProviderSubagentStore(); + const children = new SessionChildren({ + client: () => harness.api, + id: "session", + emit: (event) => { + if (event.type === "provider_subagent") store.apply("parent", "opencode", event.event); + }, + reconcilePermissions: async () => {}, + }); + const ids = () => + store + .list("parent") + .map((child) => child.id) + .sort(); + return { harness, sessions, children, ids, store }; +} + describe("OpenCode v2 child presentation", () => { + test.each(["deletion event", "reconnect"])("removes a deleted child on %s", async (trigger) => { + const harness = new V2Harness(); + const child: SessionInfo = { ...harness.info, id: "child", parentID: "session" }; + let exists = true; + harness.api.session.list = async (input) => ({ + data: exists && input?.parentID === "session" ? [child] : [], + cursor: {}, + }); + harness.api.session.get = async () => { + if (!exists) throw { _tag: "SessionNotFoundError", sessionID: child.id }; + return child; + }; + harness.api.session.active = async () => (exists ? { child: { type: "running" } } : {}); + const store = new ProviderSubagentStore(); + const children = new SessionChildren({ + client: () => harness.api, + id: "session", + emit: (event) => { + if (event.type === "provider_subagent") store.apply("parent", "opencode", event.event); + }, + reconcilePermissions: async () => {}, + }); + await children.reconcile("session"); + expect(store.list("parent")).toMatchObject([{ id: "child", status: "running" }]); + exists = false; + if (trigger === "reconnect") await children.reconcile("session"); + else + await children.observe({ + id: "deleted", + created: 2, + type: "session.deleted", + durable: { aggregateID: "child", seq: 1, version: 1 }, + data: { sessionID: "child" }, + }); + expect(store.list("parent")).toEqual([]); + }); + + test.each(["deletion event", "reconnect"])( + "removes a deleted child's descendants on %s without removing its sibling", + async (trigger) => { + const { sessions, children, ids } = setupTree(); + await children.reconcile("session"); + expect(ids()).toEqual(["first", "grandchild", "second"]); + sessions.delete("first"); + sessions.delete("grandchild"); + if (trigger === "reconnect") await children.reconcile("session"); + else + await children.observe({ + id: "deleted", + created: 2, + type: "session.deleted", + durable: { aggregateID: "first", seq: 1, version: 1 }, + data: { sessionID: "first" }, + }); + expect(ids()).toEqual(["second"]); + }, + ); + + test("retains children on later pages and when reconciling only another subtree", async () => { + const { harness, sessions, children, ids } = setupTree(); + await children.reconcile("session"); + const list = harness.api.session.list; + harness.api.session.list = async (input) => { + if (input?.cursor === "second-page") return { data: [sessions.get("second")!], cursor: {} }; + if (input?.parentID === "session") + return { data: [sessions.get("first")!], cursor: { next: "second-page" } }; + return list(input); + }; + await children.reconcile("session"); + await children.reconcile("first"); + expect(ids()).toEqual(["first", "grandchild", "second"]); + }); + + test.each(["present", "deleted"])( + "reconciles a live child skipped by the reconnect cursor when its grandchild is %s", + async (grandchild) => { + const { harness, sessions, children, ids, store } = setupTree(); + for (let i = 3; i <= 101; i++) { + sessions.set(`child-${i}`, { + ...harness.info, + id: `child-${i}`, + parentID: "session", + time: { created: i, updated: i }, + }); + } + sessions.get("second")!.time = { created: 2, updated: 2 }; + await children.reconcile("session"); + const expected = ids(); + expect(expected).toHaveLength(102); + if (grandchild === "deleted") sessions.delete("grandchild"); + const remaining = expected.filter((id) => grandchild === "present" || id !== "grandchild"); + const list = harness.api.session.list; + harness.api.session.list = async (input) => { + if (input?.parentID !== "session" && !input?.cursor) return list(input); + const page = [...sessions.values()] + .filter((info) => info.parentID === "session") + .filter((info) => !input.cursor || info.time.updated < Number(input.cursor)) + .sort((a, b) => b.time.updated - a.time.updated) + .slice(0, input.limit); + const next = page.length === input.limit ? String(page.at(-1)!.time.updated) : undefined; + if (!input.cursor) { + // The oldest child was not on page one. Updating it moves it ahead of that page's cursor. + const first = sessions.get("first")!; + first.time = { ...first.time, updated: 200 }; + first.title = "Updated during reconnect"; + } + return { data: page, cursor: { next } }; + }; + await children.reconcile("session"); + expect(ids()).toEqual(remaining); + expect(store.list("parent").find((child) => child.id === "first")).toMatchObject({ + title: "Updated during reconnect", + }); + await children.observe({ + id: "queued-update", + created: 200, + type: "session.execution.started", + durable: { aggregateID: "first", seq: 1, version: 1 }, + data: { sessionID: "first" }, + }); + expect(ids()).toEqual(remaining); + expect(store.list("parent").find((child) => child.id === "first")).toMatchObject({ + title: "Updated during reconnect", + }); + }, + ); + + test("retains an absent child's subtree when its existence cannot be confirmed", async () => { + const { harness, sessions, children, ids } = setupTree(); + await children.reconcile("session"); + sessions.delete("first"); + sessions.delete("grandchild"); + const get = harness.api.session.get; + harness.api.session.get = async () => { + throw new Error("Provider disconnected"); + }; + await children.reconcile("session"); + expect(ids()).toEqual(["first", "grandchild", "second"]); + harness.api.session.get = get; + await children.reconcile("session"); + expect(ids()).toEqual(["second"]); + }); + + test("keeps missing children when a listing fails before its last page", async () => { + const { harness, sessions, children, ids } = setupTree(); + await children.reconcile("session"); + sessions.delete("first"); + sessions.delete("grandchild"); + const list = harness.api.session.list; + harness.api.session.list = async (input) => { + if (input?.cursor) throw new Error("Provider disconnected"); + if (input?.parentID === "session") + return { data: [sessions.get("second")!], cursor: { next: "second-page" } }; + return list(input); + }; + await expect(children.reconcile("session")).rejects.toThrow("Provider disconnected"); + expect(ids()).toEqual(["first", "grandchild", "second"]); + harness.api.session.list = list; + await children.reconcile("session"); + expect(ids()).toEqual(["second"]); + }); + test("restores agent, model, variant and all token categories in the child subtitle", async () => { const { children, upserts } = setup(); await children.reconcile("session"); diff --git a/packages/server/src/server/agent/providers/opencode/v2/children.ts b/packages/server/src/server/agent/providers/opencode/v2/children.ts index 520d95a306..6dcb55baf5 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/children.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/children.ts @@ -1,6 +1,6 @@ import { V2Timeline } from "./timeline.js"; -import type { SessionInfo } from "@opencode/client"; +import { isSessionNotFoundError, type SessionInfo } from "@opencode/client"; import type { AgentStreamEvent } from "../../../agent-sdk-types.js"; @@ -15,18 +15,34 @@ interface ChildrenOptions { id: string; emit(event: AgentStreamEvent): void; reconcilePermissions(id: string): Promise; - /** Prepares a newly seen descendant session. */ + /** Prepares a descendant session for the current connection. */ adoptChild?: (id: string) => Promise; } +interface Child { + parentID: string; + timeline: V2Timeline; + signature?: string; +} export class SessionChildren { - private readonly children = new Map(); - private readonly childStates = new Map(); + private readonly children = new Map(); constructor(private readonly options: ChildrenOptions) {} - /** Every descendant session seen so far. */ - ids(): string[] { - return [...this.children.keys()]; + async restoreAdoptions() { + const { adoptChild } = this.options; + if (!adoptChild) return; + for (const id of this.children.keys()) { + try { + await adoptChild(id); + } catch (error) { + if (!isSessionNotFoundError(error)) throw error; + this.remove(id); + } + } } async observe(event: import("@opencode/client").OpenCodeEvent) { + if (event.type === "session.deleted") { + this.remove(event.data.sessionID); + return; + } if ( event.type === "session.created" && event.data.parentID && @@ -34,17 +50,18 @@ export class SessionChildren { ) { await this.reconcile(event.data.parentID); } - if ( - "sessionID" in event.data && - typeof event.data.sessionID === "string" && - this.children.has(event.data.sessionID) - ) { - await this.reconcileChild( - await this.options.client().session.get({ sessionID: event.data.sessionID }), - ); + if ("sessionID" in event.data && typeof event.data.sessionID === "string") { + const child = this.children.get(event.data.sessionID); + if (child) + await this.reconcileChild( + await this.options.client().session.get({ sessionID: event.data.sessionID }), + child.parentID, + ); } } async reconcile(parentID: string) { + const previous = [...this.children].filter(([, child]) => child.parentID === parentID); + const seen = new Set(); let cursor: string | undefined; do { const page = await this.options.client().session.list({ @@ -52,19 +69,45 @@ export class SessionChildren { limit: 100, }); for (const child of page.data) { - await this.reconcileChild(child); + seen.add(child.id); + await this.reconcileChild(child, parentID); await this.reconcile(child.id); } cursor = page.cursor.next ?? undefined; } while (cursor); + // Updates can move a live child ahead of the cursor. Confirm deletion before pruning. + for (const [id] of previous) { + if (seen.has(id)) continue; + let info: SessionInfo; + try { + info = await this.options.client().session.get({ sessionID: id }); + } catch (error) { + if (isSessionNotFoundError(error)) this.remove(id); + continue; + } + await this.reconcileChild(info, parentID); + await this.reconcile(id); + } } - private async reconcileChild(info: SessionInfo) { + private remove(id: string) { + if (!this.children.delete(id)) return; + // OpenCode deletes a session's descendants with it. + for (const [childID, child] of this.children) { + if (child.parentID === id) this.remove(childID); + } + this.options.emit({ + type: "provider_subagent", + provider: "opencode", + event: { type: "remove", id }, + }); + } + private async reconcileChild(info: SessionInfo, parentID: string) { await this.options.reconcilePermissions(info.id); - let timeline = this.children.get(info.id); - if (!timeline) { + let child = this.children.get(info.id); + if (!child) { await this.options.adoptChild?.(info.id); - timeline = this.children.get(info.id) ?? new V2Timeline(); - this.children.set(info.id, timeline); + child = this.children.get(info.id) ?? { parentID, timeline: new V2Timeline() }; + this.children.set(info.id, child); } const active = await this.options.client().session.active(); let status: "running" | "failed" | "canceled" | "completed" = "completed"; @@ -93,11 +136,11 @@ export class SessionChildren { timestamp: new Date(info.time.updated).toISOString(), }; const signature = JSON.stringify(presentation); - if (this.childStates.get(info.id) !== signature) { - this.childStates.set(info.id, signature); + if (child.signature !== signature) { + child.signature = signature; this.options.emit({ type: "provider_subagent", provider: "opencode", event: presentation }); } - await timeline.messages(await messages(this.options.client(), info.id), (event) => { + await child.timeline.messages(await messages(this.options.client(), info.id), (event) => { if (event.type === "timeline") this.options.emit({ type: "provider_subagent", diff --git a/packages/server/src/server/agent/providers/opencode/v2/external-runtime.test.ts b/packages/server/src/server/agent/providers/opencode/v2/external-runtime.test.ts index d2cfdaada5..b08502bee1 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/external-runtime.test.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/external-runtime.test.ts @@ -4,6 +4,7 @@ import { createServer as createNetServer } from "node:net"; import { afterEach, describe, expect, test } from "vitest"; import { createTestLogger } from "../../../../../test-utils/test-logger.js"; +import { OpenCodeHttpError } from "../http-error.js"; import { V2Runtime } from "./runtime.js"; import { EXTERNAL_SERVER_PASSWORD_ENV, EXTERNAL_SERVER_URL_ENV } from "./external-server.js"; @@ -101,6 +102,51 @@ describe("V2Runtime against an external server", () => { expect(requests).toHaveLength(1); }); + test.each([ + { + status: 404, + contentType: "application/json", + body: '{"_tag":"LocationNotFoundError","message":"Location not found"}', + }, + { status: 404, contentType: "application/json", body: "invalid JSON" }, + { status: 404, contentType: "text/html", body: "Not found" }, + { status: 500, contentType: "application/json", body: '{"_tag":"SessionNotFoundError"}' }, + ])( + "keeps unrelated HTTP $status $contentType failures", + async ({ status, contentType, body }) => { + server = createServer((request, response) => { + if (request.url === "/api/info") { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ version: "2.3.0", pid: 1, urls: [], paths: { tmp: "/tmp" } }), + ); + return; + } + response.writeHead(status, { "content-type": contentType }); + response.end(body); + }); + const port = await listen(server); + const runtime = new V2Runtime({ + logger: createTestLogger(), + externalServer: { url: `http://127.0.0.1:${port}` }, + }); + try { + const connection = await runtime.acquire(); + await expect(connection.client.session.get({ sessionID: "missing" })).rejects.toMatchObject( + { + cause: expect.objectContaining({ + name: OpenCodeHttpError.name, + status, + html: contentType === "text/html", + }), + }, + ); + } finally { + await runtime.shutdown(); + } + }, + ); + test("reports the external server as exited once it stops accepting connections", async () => { server = createServer((request, response) => { if (request.url !== "/api/info") { diff --git a/packages/server/src/server/agent/providers/opencode/v2/http-response.ts b/packages/server/src/server/agent/providers/opencode/v2/http-response.ts new file mode 100644 index 0000000000..cd21a7bbc1 --- /dev/null +++ b/packages/server/src/server/agent/providers/opencode/v2/http-response.ts @@ -0,0 +1,23 @@ +import { isSessionNotFoundError } from "@opencode/client"; +import { OpenCodeHttpError } from "../http-error.js"; + +export async function validateOpenCodeResponse( + request: RequestInfo | URL, + response: Response, +): Promise { + const contentType = response.headers.get("content-type"); + const html = contentType?.includes("text/html") ?? false; + if (response.ok && !html) return response; + + // The SDK needs the original body to decode the provider's missing-session error. + if (response.status === 404 && !html && contentType?.includes("application/json")) { + const body: unknown = await response + .clone() + .json() + .catch(() => null); + if (isSessionNotFoundError(body)) return response; + } + + const url = request instanceof Request ? request.url : String(request); + throw new OpenCodeHttpError(new URL(url).pathname, response.status, html); +} diff --git a/packages/server/src/server/agent/providers/opencode/v2/runtime.ts b/packages/server/src/server/agent/providers/opencode/v2/runtime.ts index 66f08b6eda..567d70f6a3 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/runtime.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/runtime.ts @@ -14,7 +14,7 @@ import { } from "../../../provider-launch-config.js"; import type { ManagedProcessRegistry } from "../../../../managed-processes/managed-processes.js"; import { resolveOpenCodeHomeDir } from "../paths.js"; -import { OpenCodeHttpError } from "../http-error.js"; +import { validateOpenCodeResponse } from "./http-response.js"; import { raceProviderRefreshAbort } from "../../../provider-refresh-deadline.js"; import { resolveExternalOpenCodeServer, type ExternalOpenCodeServer } from "./external-server.js"; import { @@ -316,12 +316,7 @@ export class V2Runtime { ? AbortSignal.any([init.signal, processAbort.signal]) : processAbort.signal; const response = await fetch(request, { ...init, signal }); - const html = response.headers.get("content-type")?.includes("text/html") ?? false; - if (!response.ok || html) { - const requestUrl = request instanceof Request ? request.url : String(request); - throw new OpenCodeHttpError(new URL(requestUrl).pathname, response.status, html); - } - return response; + return validateOpenCodeResponse(request, response); }, }); await client.server.info({ signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())) }); diff --git a/packages/server/src/server/agent/providers/opencode/v2/session.ts b/packages/server/src/server/agent/providers/opencode/v2/session.ts index 47552a5a98..bd75d215af 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/session.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/session.ts @@ -534,7 +534,7 @@ export class OpenCodeV2Session implements AgentSession { // reconciling a new connection, including event-stream reconnections. if (this.environment) await this.client.session.environment({ sessionID: this.id, variables: this.environment }); - for (const id of this.children.ids()) await this.adoptDescendant(id); + await this.children.restoreAdoptions(); await this.reconcile(); await this.children.reconcile(this.id); await this.turns.reconcile(); diff --git a/packages/server/src/server/agent/providers/opencode/v2/shared-service.ts b/packages/server/src/server/agent/providers/opencode/v2/shared-service.ts index 219ae8b913..b432904e3c 100644 --- a/packages/server/src/server/agent/providers/opencode/v2/shared-service.ts +++ b/packages/server/src/server/agent/providers/opencode/v2/shared-service.ts @@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url"; import type { Logger } from "pino"; import type { ProviderRuntimeSettings } from "../../../provider-launch-config.js"; import type { OpenCodeBridge } from "../bridge.js"; -import { OpenCodeHttpError } from "../http-error.js"; +import { validateOpenCodeResponse } from "./http-response.js"; import { resolveOpenCodeHomeDir } from "../paths.js"; import { openCodeConfigDirectory, provisionLocalBridge } from "./bridge-provisioning.js"; import { awaitPaseoPlugin } from "./readiness.js"; @@ -61,12 +61,7 @@ export async function connectSharedService( if (isConnectionRefused(error)) markExited(error); throw error; } - const html = response.headers.get("content-type")?.includes("text/html") ?? false; - if (!response.ok || html) { - const requestUrl = request instanceof Request ? request.url : String(request); - throw new OpenCodeHttpError(new URL(requestUrl).pathname, response.status, html); - } - return response; + return validateOpenCodeResponse(request, response); }, }); const markExited = (cause: unknown) => { diff --git a/packages/website/e2e/i18n.spec.ts b/packages/website/e2e/i18n.spec.ts index 20271cebf3..7c0b8989ae 100644 --- a/packages/website/e2e/i18n.spec.ts +++ b/packages/website/e2e/i18n.spec.ts @@ -9,19 +9,23 @@ async function chooseLanguage(page: Page, language: string) { await page.getByRole("menuitemradio", { name: language }).click(); } -async function withPageScriptsHeld(page: Page, run: (release: () => void) => Promise) { - let releaseScripts!: () => void; - const scriptsReleased = new Promise((resolve) => { - releaseScripts = resolve; +async function withRequestsHeld( + page: Page, + pattern: string, + run: (release: () => void) => Promise, +) { + let releaseRequests!: () => void; + const requestsReleased = new Promise((resolve) => { + releaseRequests = resolve; }); - await page.route("**/*.js", async (route) => { - await scriptsReleased; + await page.route(pattern, async (route) => { + await requestsReleased; await route.continue(); }); try { - await run(releaseScripts); + await run(releaseRequests); } finally { - releaseScripts(); + releaseRequests(); await page.unrouteAll({ behavior: "wait" }); } } @@ -198,13 +202,17 @@ test("switches language from the keyboard", async ({ page }) => { await expect(languageButton(page)).toBeFocused(); await page.keyboard.press("ArrowDown"); + await expect(page.getByRole("menuitemradio", { name: "English" })).toBeFocused(); await page.keyboard.press("ArrowDown"); await expect(page.getByRole("menuitemradio", { name: /简体中文/ })).toBeFocused(); - await page.keyboard.press("Enter"); - await expect(page).toHaveURL(/\/zh-CN$/); - await expect(languageButton(page)).toHaveText("ZH"); - await expect(languageButton(page)).toBeFocused(); + // A slow plugin count must not delay the new language or lose keyboard focus. + await withRequestsHeld(page, "**/_serverFn/**", async () => { + await page.keyboard.press("Enter"); + await expect(page).toHaveURL(/\/zh-CN$/); + await expect(languageButton(page)).toHaveText("ZH"); + await expect(languageButton(page)).toBeFocused(); + }); }); test.describe("on a phone", () => { @@ -260,7 +268,7 @@ test("shows the changelog in Chinese", async ({ page }) => { }); test("waits for scripts before enabling the language menu", async ({ page }) => { - await withPageScriptsHeld(page, async (releaseScripts) => { + await withRequestsHeld(page, "**/*.js", async (releaseScripts) => { await page.goto("/docs/cli#running-agents", { waitUntil: "commit" }); await expect(languageButton(page)).toBeVisible(); await expect(languageButton(page)).toBeDisabled(); diff --git a/packages/website/e2e/mockups.spec.ts b/packages/website/e2e/mockups.spec.ts index 8a84f92701..afdcf8b27e 100644 --- a/packages/website/e2e/mockups.spec.ts +++ b/packages/website/e2e/mockups.spec.ts @@ -10,6 +10,37 @@ async function openHomepage(page: Page, window = { width: 1512, height: 930 }) { await waitForHydration(page); } +/** The scene advances at most 64 ms per frame. Drive its frames independently of CI paint speed. */ +async function openHomepageWithSceneClock( + page: Page, + viewport?: { width: number; height: number }, +) { + await page.clock.install(); + await openHomepage(page, viewport); + await page.clock.pauseAt(await page.evaluate(() => Date.now() + 1000)); +} + +async function centerMockup(mockup: Locator) { + await mockup.evaluate((element) => + element.scrollIntoView({ block: "center", behavior: "instant" }), + ); +} + +async function finishPanelSwap(page: Page, mockup: Locator, outgoingPanel: Locator) { + await expect + .poll(async () => { + await page.clock.runFor(250); + // Playwright's clock drives JavaScript frames. Native animations use the document timeline. + await mockup.evaluate((element) => { + for (const animation of element.getAnimations({ subtree: true })) { + if (Number.isFinite(animation.effect?.getComputedTiming().endTime)) animation.finish(); + } + }); + return outgoingPanel.count(); + }) + .toBe(0); +} + async function viewPhones(page: Page) { await page.getByRole("img", { name: "Paseo agent chat", exact: true }).scrollIntoViewIfNeeded(); } @@ -110,12 +141,7 @@ test("the hero opens on orchestration across providers and machines", async ({ p test("the orchestration scene plays from an empty chat to the open roster of subagents", async ({ page, }) => { - // The scene clock moves at most 64ms per animation frame. Headless WebKit on a busy CI runner - // paints a few frames a second, so on the real clock the scene plays in slow motion and misses - // any wall-clock timeout. The test holds the page clock and plays the scene itself. - await page.clock.install(); - await openHomepage(page); - await page.clock.pauseAt(await page.evaluate(() => Date.now() + 1000)); + await openHomepageWithSceneClock(page); const mockup = page.getByRole("img", { name: desktopName, exact: true }); const composer = mockup.getByText("Message the agent, tag @files, or use /commands and /skills"); await playScene(page, "Orchestration", composer); @@ -141,30 +167,34 @@ test("the orchestration scene plays from an empty chat to the open roster of sub }); test("the opening scene waits until most of the mockup is on screen", async ({ page }) => { - await openHomepage(page); + await openHomepageWithSceneClock(page); const mockup = page.getByRole("img", { name: desktopName, exact: true }); const request = mockup.getByText("Fix the issues labeled ready, one worktree each."); await expect(mockup).not.toBeInViewport({ ratio: 0.6 }); // A scene that started at load sends the request within three seconds. - await page.waitForTimeout(4500); + await page.clock.runFor(4500); await expect(request).toHaveCount(0); - await mockup.scrollIntoViewIfNeeded(); - await expect(request).toBeVisible({ timeout: 10_000 }); + await centerMockup(mockup); + await expect(mockup).toBeInViewport({ ratio: 0.6 }); + await page.clock.runFor(4500); + await expect(request).toBeVisible(); }); test("the opening scene starts in a window shorter than most of the mockup", async ({ page }) => { - await openHomepage(page, { width: 1400, height: 320 }); + await openHomepageWithSceneClock(page, { width: 1400, height: 320 }); const mockup = page.getByRole("img", { name: desktopName, exact: true }); const request = mockup.getByText("Fix the issues labeled ready, one worktree each."); - await mockup.scrollIntoViewIfNeeded(); + await centerMockup(mockup); + await expect(mockup).toBeInViewport(); await expect(mockup).not.toBeInViewport({ ratio: 0.6 }); - await expect(request).toBeVisible({ timeout: 10_000 }); + await page.clock.runFor(4500); + await expect(request).toBeVisible(); }); test("the plugins scene installs the panel, then changes it on request", async ({ page }) => { - await openHomepage(page); + await openHomepageWithSceneClock(page); const mockup = page.getByRole("img", { name: desktopName, exact: true }); const changesPanel = mockup.getByText("Uncommitted", { exact: true }); const pluginPanel = mockup.getByText("Recently merged", { exact: true }); @@ -174,12 +204,14 @@ test("the plugins scene installs the panel, then changes it on request", async ( await expect(pluginPanel).toHaveCount(0); // Installing the plugin swaps the docked panel for the one the agent built. - await expect(pluginPanel).toBeVisible({ timeout: 20_000 }); - await expect(changesPanel).toHaveCount(0); + await page.clock.runFor(5500); + await expect(pluginPanel).toBeVisible(); + await finishPanelSwap(page, mockup, changesPanel); await expect(failingCheck).toHaveCount(0); // The second request reloads the plugin and the open panel lists the failing check. - await expect(failingCheck).toBeVisible({ timeout: 15_000 }); + await page.clock.runFor(6000); + await expect(failingCheck).toBeVisible(); await expect( mockup.getByText("paseo plugin reload release-radar", { exact: true }), ).toBeVisible(); diff --git a/packages/website/src/components/agent-route.tsx b/packages/website/src/components/agent-route.tsx index d7b636b7da..d48ab5852a 100644 --- a/packages/website/src/components/agent-route.tsx +++ b/packages/website/src/components/agent-route.tsx @@ -18,18 +18,14 @@ export function agentRouteOptions(slug: AgentPageSlug) { locale, }); }, - loader: async () => ({ pluginCount: await getPluginCount() }), + loader: () => ({ pluginCount: getPluginCount().catch(() => null) }), component: function AgentLandingPage() { const { t } = useTranslation(); - const data = useLoaderData({ strict: false }) as { pluginCount?: number | null } | undefined; + const { pluginCount } = useLoaderData({ strict: false }) as { + pluginCount: Promise; + }; const page = getAgentPage(slug, t); - return ( - - ); + return ; }, }; } diff --git a/packages/website/src/components/landing-page.tsx b/packages/website/src/components/landing-page.tsx index 596634dc94..158cf1594f 100644 --- a/packages/website/src/components/landing-page.tsx +++ b/packages/website/src/components/landing-page.tsx @@ -1,3 +1,4 @@ +import { Await } from "@tanstack/react-router"; import { PLUGINS_LINKED } from "~/plugins/launch"; import { categoryHref } from "~/plugins/links"; import type { CategorySlug } from "~/plugins/categories"; @@ -114,14 +115,14 @@ import "~/styles.css"; interface LandingPageProps { title: React.ReactNode; subtitle: React.ReactNode; - pluginCount?: number | null; + pluginCount: Promise; showHubEyebrow?: boolean; } export function LandingPage({ title, subtitle, - pluginCount = null, + pluginCount, showHubEyebrow = false, }: LandingPageProps) { return ( @@ -613,7 +614,7 @@ function ProductLead({ actions, }: { icon: LucideIcon; - title: string; + title: React.ReactNode; description?: string; actions?: React.ReactNode; }) { @@ -979,17 +980,23 @@ const PLUGIN_CLIENT_COMPONENTS = { ), }; -function ExtensibleSection({ pluginCount }: { pluginCount?: number | null }) { +function ExtensibleSection({ pluginCount }: { pluginCount: Promise }) { const { t } = useTranslation(); const pluginActions = React.useMemo(() => , []); const description = React.useMemo( () => , [], ); - const libraryTitle = - pluginCount && pluginCount > 0 - ? t("landing.plugins.libraryTitleCount", { count: pluginCount }) - : t("landing.plugins.libraryTitle"); + const libraryTitle = React.useMemo(() => { + const fallback = t("landing.plugins.libraryTitle"); + return ( + + {(count) => + count && count > 0 ? t("landing.plugins.libraryTitleCount", { count }) : fallback + } + + ); + }, [pluginCount, t]); return ( ({ pluginCount: await getPluginCount() }), + loader: () => ({ pluginCount: getPluginCount().catch(() => null) }), component: Home, }); diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index 0f268afe8a..6ebd01498d 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -15,15 +15,18 @@ Migrating an existing plugin? Follow the standalone [runtime-entry migration gui Local plugins are directory sources installed into one Paseo daemon. A plugin can contribute: - React Native screens and sidebar header and footer items to Paseo clients; +- a [sidebar view](/docs/plugins/sidebar-views) that replaces the sidebar list, and [badges](#workspace-row-badge-items) on workspace rows; - workspace and agent panels opened as workspace tabs; - [file panels](#file-panels) for viewing or editing matching files; - global, workspace, and agent actions in the Command Center; -- slash commands in the message composer; +- slash commands, [controls](#composer-items), pills, and searchable external resources in the message composer; +- [buttons](#header-buttons) in the workspace header and [fields](#new-workspace-items) on the New workspace screen; +- [settings screens](#settings-screens) and light and dark themes in Settings → Appearance; - transformed and daemon-pushed agent timeline rows; -- light and dark themes in Settings → Appearance; -- schema-validated RPC handlers running beside the daemon; -- normal Paseo operations through the TypeScript SDK; -- searchable external resources in the message composer. +- schema-validated RPC handlers and event streams running beside the daemon; +- [hooks](/docs/plugins/hooks) that change or observe workspace, worktree, and agent operations; +- [agent providers](/docs/plugins/providers), [usage sources](#usage-sources), and [worktree managers](#worktree-managers); +- normal Paseo operations through the TypeScript SDK. Plugin code is trusted and unsandboxed. Client surfaces run in the Paseo app. Backend contributions run in a subprocess with access to the daemon machine, including its files, processes, credentials, and network. @@ -401,7 +404,7 @@ Use `openSettings`, `openScreen`, and `openPanel` for your own registered contri ### Server runtime Paseo provides `@getpaseo/plugin`, `@getpaseo/plugin/server`, -`@getpaseo/plugin/server/provider`, `@getpaseo/plugin/server/acp`, and `zod` to server code. Backend +`@getpaseo/plugin/server/provider`, `@getpaseo/plugin/server/acp`, `@getpaseo/plugin/server/usage`, and `zod` to server code. Backend contributions run in a daemon subprocess with Node access to the host machine. Keep filesystem, process, credential, and other machine-local work under `server/`. A plugin without `index.server.ts` starts no subprocess. diff --git a/public-docs/plugins/reference.zh-CN.md b/public-docs/plugins/reference.zh-CN.md index e813b9f305..8fc3aad878 100644 --- a/public-docs/plugins/reference.zh-CN.md +++ b/public-docs/plugins/reference.zh-CN.md @@ -13,15 +13,18 @@ nav: 参考 本地插件是安装到某个 Paseo daemon 中的目录来源。插件可以贡献: - 为 Paseo 客户端添加 React Native 界面,以及侧边栏顶部和底部项; +- 替换侧边栏列表的[侧边栏视图](/docs/plugins/sidebar-views),以及工作区行上的[徽标](#workspace-row-badge-items); - 作为工作区标签页打开的工作区面板和 Agent 面板; - 用于查看或编辑匹配文件的[文件面板](#file-panels); - Command Center 中的全局、工作区和 Agent 操作; -- 消息 Composer 中的斜杠命令; +- 消息 Composer 中的斜杠命令、[控件](#composer-items)、胶囊和可搜索的外部资源; +- 工作区标题栏中的[按钮](#header-buttons),以及新建工作区界面上的[字段](#new-workspace-items); +- [设置界面](#settings-screens),以及 **设置 → 外观** 中的浅色和深色主题; - 经过转换的、以及由 daemon 推送的 Agent 时间线行; -- **设置 → 外观** 中的浅色和深色主题; -- 在 daemon 旁运行、经过 schema 校验的 RPC 处理函数; -- 通过 TypeScript SDK 执行的普通 Paseo 操作; -- 消息 Composer 中可搜索的外部资源。 +- 在 daemon 旁运行、经过 schema 校验的 RPC 处理函数和事件流; +- 修改或观察工作区、worktree 和 Agent 操作的[钩子](/docs/plugins/hooks); +- [Agent Provider](/docs/plugins/providers)、[用量来源](#usage-sources)和 [worktree 管理器](#worktree-managers); +- 通过 TypeScript SDK 执行的普通 Paseo 操作。 插件代码是受信任的,没有沙盒。客户端界面在 Paseo 应用中运行。后端贡献在一个子进程中运行,可以访问 daemon 所在的机器,包括它的文件、进程、凭据和网络。 @@ -349,7 +352,7 @@ openBrowser({ url, workspaceId: remoteWorkspaceId, serverId: remoteServerId }); ### 服务端运行时 {#server-runtime} -Paseo 为服务端代码提供 `@getpaseo/plugin`、`@getpaseo/plugin/server`、`@getpaseo/plugin/server/provider`、`@getpaseo/plugin/server/acp` 和 `zod`。后端贡献在 daemon 子进程中运行,可以通过 Node 访问宿主机器。请把文件系统、进程、凭据以及其他本机工作放在 `server/` 下。没有 `index.server.ts` 的插件不会启动子进程。 +Paseo 为服务端代码提供 `@getpaseo/plugin`、`@getpaseo/plugin/server`、`@getpaseo/plugin/server/provider`、`@getpaseo/plugin/server/acp`、`@getpaseo/plugin/server/usage` 和 `zod`。后端贡献在 daemon 子进程中运行,可以通过 Node 访问宿主机器。请把文件系统、进程、凭据以及其他本机工作放在 `server/` 下。没有 `index.server.ts` 的插件不会启动子进程。 ### Provider {#providers} diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 57e91a8af8..7b2a3baa94 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -256,6 +256,7 @@ test("PR routing declares stable behavior ownership", () => { "packages/plugin/**", "plugin-examples/**", "public-docs/plugins/**", + "skills/paseo-plugin/**", "packages/client/**", "packages/highlight/**", "packages/protocol/**", diff --git a/skills/paseo-plugin/SKILL.md b/skills/paseo-plugin/SKILL.md index 85030768d9..fd8711b782 100644 --- a/skills/paseo-plugin/SKILL.md +++ b/skills/paseo-plugin/SKILL.md @@ -1,86 +1,85 @@ --- name: paseo-plugin -description: Build and manage trusted local Paseo plugins. Use when the user asks to create, edit, install, reload, enable, disable, remove, or troubleshoot a Paseo plugin; add lifecycle hooks; transform agent configuration, environment, MCP servers, or workspace creation; automate permissions or turn follow-ups; add a screen, sidebar header or footer item, workspace panel, or file panel; add Command Center items or slash commands; add composer pills or attachment sources; transform, render, or append agent timeline items; contribute a theme; use Paseo from plugin code; or add plugin RPCs. +description: Build and manage trusted Paseo plugins. Use when the user asks to create, edit, install, reload, enable, disable, remove, publish, or troubleshoot a Paseo plugin, or to add a plugin contribution such as a screen, sidebar item, sidebar view, workspace row badge, workspace, agent, or file panel, Command Center item, slash command, header button, composer pill, composer control, attachment source, New workspace field, settings screen, theme, timeline item, lifecycle hook, system prompt instructions, agent tools, MCP servers, agent provider, usage source, worktree manager, plugin RPC or subscription, or Paseo SDK calls from plugin code. --- # Paseo plugins -Build or manage the requested plugin directly. Use the current public docs to catch contract changes, but keep working from this skill if the network is unavailable. +Build or manage the plugin that the user asked for. Do the work yourself. Do not send the user to the docs in place of the work. -Use the user's request and current conversation as input, including any arguments supplied with the skill invocation. +Use the user's request and the current conversation as input, including any arguments supplied with the skill invocation. -## Check current documentation +This skill gives the workflow, a map of every contribution, and the rules that break plugins most often. The public docs hold the complete contract of each contribution. -Fetch [https://paseo.sh/llms.txt](https://paseo.sh/llms.txt) first. Select and fetch the current plugin Markdown pages from that index before changing a plugin: +## Read the current contract -- [Plugin quickstart](https://paseo.sh/docs/plugins.md) ([browser page](https://paseo.sh/docs/plugins)) -- [Publishing](https://paseo.sh/docs/plugins/publishing.md): npm package contents, dependencies, Git preparation, and private registries. -- [Plugin reference](https://paseo.sh/docs/plugins/reference.md) ([browser page](https://paseo.sh/docs/plugins/reference)) +Before you write a contribution, read its section in the docs: -Use the deployed docs when they disagree with this skill. Do not send the user away to read them instead of completing the work. +- In a Paseo checkout, read the files in `public-docs/plugins/`. They describe the API of that checkout, including unreleased changes. +- Elsewhere, fetch [https://paseo.sh/llms.txt](https://paseo.sh/llms.txt), then fetch the plugin pages that it lists. +- If the network is not available, continue from this skill. -In the Paseo repository, use `public-docs/plugins/reference.md` for the checkout's API, including -unreleased changes. Use `docs/plugins.md` for maintainer guidance. Complete contracts belong in the -public docs; this skill indexes the references and examples. +| Page | Read it for | +| --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| [Quickstart](https://paseo.sh/docs/plugins.md) | A first plugin, installation, and reload | +| [Reference](https://paseo.sh/docs/plugins/reference.md) | Client contributions, host UI, the Paseo SDK, RPCs, usage sources, worktree managers, the CLI, and load failures | +| [Hooks](https://paseo.sh/docs/plugins/hooks.md) | Lifecycle hooks, payloads, ordering, agent tools, and MCP servers | +| [Provider plugins](https://paseo.sh/docs/plugins/providers.md) | Coding agents added as providers, direct or through ACP | +| [Sidebar views](https://paseo.sh/docs/plugins/sidebar-views.md) | Sidebar views and the ref queries that feed them | +| [Publishing](https://paseo.sh/docs/plugins/publishing.md) | The listing page, npm, Git, and the plugin registry | +| [Migration](https://paseo.sh/docs/plugins/migration.md) | Plugins written before 0.8 runtime entries, and renamed APIs | -## What a plugin can contribute +If the docs and this skill disagree, follow the docs. -Pick the contribution that matches the request. Each row names the registration, when it fits, and where the full contract lives. Most plugins combine several: a slash command that calls an RPC, which appends a timeline row, which a renderer draws. +## Choose the contributions -| Contribution | Registration | Use it when | Reference | -| ------------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| Screen and sidebar item | `addScreen` + `addSidebarHeaderItem`/`addSidebarFooterItem` | A full screen of plugin UI, or sidebar header or footer rows that open a screen or popover | reference.md → Screens and sidebar items | -| Workspace panel | `addWorkspacePanel` | UI that lives as a tab beside agents, terminals, files, and diffs; `locations: ["explorer"]` for the Explorer | reference.md → Workspace panels | -| File panel | `addFilePanel` | View or edit a matching file inside the file tab through its file handle | reference.md → File panels; `plugin-examples/pdf-panel`, `plugin-examples/markdown-panel` | -| Command Center item | `addCommandCenterItem` | A global, workspace, or agent action reachable from ⌘K | reference.md → Command Center items | -| Client slash command | `addSlashCommand` | A `/command args` in the composer that runs plugin code instead of prompting the agent | reference.md → Slash commands | -| Composer pill | `addComposerPill` | A per-agent button in the composer track bar next to Tasks and Subagents | reference.md → Composer pills | -| Timeline transformer | `addTimelineTransformer` + `addTimelineRenderer` | Replace, explode, or hide a built-in timeline item, including while it streams | reference.md → Timeline items; `plugin-examples/timeline-items`, `plugin-examples/inline-thinking` | -| Timeline row | `paseo.agents.ref(id).timeline.append(...)` | Push a plugin-owned row into an agent timeline from a server handler and update it later | reference.md → Append a timeline row from the daemon | -| Attachment source | `client.addAttachmentSource` + `server.handle` | Let the user attach a searchable external resource, such as an issue, to a prompt | reference.md → Add a composer attachment source; `plugin-examples/linear` | -| Theme | `addTheme` | A light or dark palette under Settings → Appearance | reference.md → Contribute a theme; `plugin-examples/catppuccin` | -| Plugin RPC | `defineRpc` + `server.handle` + `useRpc` | Daemon-side work that is not a normal Paseo operation: vendor APIs, credentials, local files | reference.md → Add plugin-specific backend behavior | -| Plugin subscription | `defineSubscription` + `server.handle` + `useSubscription` | A daemon handler that pushes events while a surface listens: watchers, tails, live media; a top-level `Uint8Array` rides as binary | reference.md → Stream events from the daemon; `plugin-examples/diff-watch`, `plugin-examples/media-stream` | -| Lifecycle events | `server.on` | Observe agent/workspace lifecycle, inspect ended turns, and answer permission requests | [Lifecycle hooks](https://paseo.sh/docs/plugins/reference.md#lifecycle-hooks) | -| Creation and launch hooks | `server.before` | `agent.create` edits saved config; `agent.session_open` contributes launch-only `env`, `tools`, `mcpServers` on every open; `workspace.create` chooses isolation | [Before hooks](https://paseo.sh/docs/plugins/reference.md#before-hooks) | -| Paseo SDK | `usePaseo()` / handler `{ paseo }` | Normal Paseo operations: workspaces, agents, providers, config | reference.md → Use the Paseo SDK | +A plugin usually combines several contributions. For example, a slash command calls an RPC, the RPC handler appends a timeline row, and a renderer draws the row. -| Lifecycle task | Example | -| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | -| Log all eleven hooks | [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | -| Follow-ups, permissions, environment, provider switching, worktrees | [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | -| Inject launch-only MCP servers and save Codex sandbox/approval options | [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | -| Attach a tool to selected agents | [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | +Build only on the registrations below. If no registration fits what the user wants, tell the user. Do not import Paseo internals or `@getpaseo/plugin/client/host`. -## Develop plugins in a local folder +### Client contributions -Develop a plugin in a local folder that you own, the same way you develop an npm package. Install -that folder by path. Paseo runs the plugin from that folder, `paseo plugin reload ` loads your -edits, and `paseo plugin update` does not change it. +Register these on `client` in `index.client.tsx`. Each returns a remover. `addHeaderButton` and `addComposerPill` return `{ update, remove }` instead. -Do not edit, build, or commit inside the installation of a Git or npm plugin. That folder is -Paseo's managed storage in the `plugins/` directory of the daemon home. `paseo plugin update` -replaces it, and `paseo plugin remove` deletes it. Both commands discard every edit and commit in -that folder. +| Registration | Use it for | Docs section | Example | +| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | ----------------------------------- | +| `addScreen` | A full page of plugin UI. Open it with `openScreen({ screenId, params })`. | Reference > Screens and sidebar items | `hosts` | +| `addSidebarHeaderItem`, `addSidebarFooterItem` | Sidebar rows, drawn with `SidebarRow`, that open a screen or a popover | Reference > Sidebar items | `hosts` | +| `addSidebarView` | A replacement for the sidebar list. The user selects it in Settings > Sidebar. | Sidebar views | `sidebar-views` | +| `addWorkspaceRowBadgeItem` | Badges under each workspace title, drawn with `WorkspaceRowBadge` | Reference > Workspace row badge items | `workspace-row-badges` | +| `addWorkspacePanel`, `addAgentPanel` | A tab beside agents, terminals, and files. Add `locations: ["explorer"]` to show it in the Explorer. | Reference > Workspace panels | `local-plugin` | +| `addFilePanel` | A view or editor for files that match `files: { extensions, filenames }` | Reference > File panels | `pdf-panel`, `markdown-panel` | +| `addCommandCenterItem` | A global, workspace, or agent action in the Command Center | Reference > Command Center items | `local-plugin` | +| `addSlashCommand` | A `/name args` command that runs plugin code and sends nothing to the agent | Reference > Slash commands | `translations` | +| `addHeaderButton` | An action, menu, or popover in the workspace header | Reference > Header buttons | `buttons` | +| `addComposerPill` | A button above the composer of one agent, beside Tasks and Subagents | Reference > Composer pills | `local-plugin` | +| `addComposerItem` | Composer controls that change the prompt, model, mode, provider options, or agent metadata through `useComposer()` | Reference > Composer items | `composer-controls` | +| `addNewWorkspaceItem` | A field on the New workspace screen that sets the branch, base, isolation, or workspace metadata through `useNewWorkspace()` | Reference > New workspace items | `new-workspace-issues` | +| `addAttachmentSource` | Outside resources, such as issues, that the user searches and attaches to a prompt | Reference > Add a composer attachment source | `linear` | +| `addSettingsScreen` | A settings tab for the plugin under Settings > Plugins | Reference > Settings screens | `settings` | +| `addTheme` | A light or dark palette under Settings > Appearance | Reference > Contribute a theme | `catppuccin` | +| `addTimelineTransformer`, `addTimelineRenderer` | Replacing, splitting, or hiding a built-in timeline item, also while it streams | Reference > Timeline items | `inline-thinking`, `timeline-items` | -Before you edit an installed plugin, run `paseo plugin ls ` and read the SOURCE column. A -`git:` source, an `npm:` source, or a registry source such as `/owner/slug` is a -managed installation. Its DIRECTORY column shows the managed folder. +Examples live in [`plugin-examples/`](https://github.com/getpaseo/paseo/tree/main/plugin-examples). -To develop a plugin that is installed from Git or npm: +The client context also has `paseo`, `rpc`, `subscribe`, `openScreen`, `openPanel`, `openSettings`, `composers`, `playAudio`, and `i18n`. Import hooks such as `usePaseo`, `useRpc`, `useSubscription`, `useSettings`, `useWorkspace`, `useAgent`, and `useTabState` from `@getpaseo/plugin/client`. -1. Clone the source repository of the plugin into a folder outside the daemon home. For an npm - plugin, find the repository in its `package.json`. -2. If SOURCE ends with `:`, use that subfolder of the clone as the plugin folder. -3. If the managed folder holds edits or commits, move them into the plugin folder. -4. In the plugin folder, install the dependencies and run the `build` commands from - `paseo-plugin.json`. Paseo runs `build` only for managed installations. -5. Ask the user before you remove the managed installation. `paseo plugin remove ` also - deletes the saved settings of the plugin. -6. Run `paseo plugin remove `. -7. Run `paseo plugin install /absolute/path/to/plugin-folder --id ` to keep the runtime ID. -8. Edit the plugin folder, and run `paseo plugin reload ` after each change. If a change needs - a `build` command, run that command before `reload`. +### Server contributions + +Register these on `server` in `index.server.ts`. + +| Registration | Use it for | Docs section | Example | +| --------------------------- | --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------- | +| `handle(contract, handler)` | Plugin RPCs from `defineRpc` and event streams from `defineSubscription` | Reference > Add plugin-specific backend behavior and Stream events from the daemon | `diff-watch` | +| `addHook(name, handler)` | Changing or observing workspace, worktree, and agent operations | Hooks | `lifecycle-actions`, `lifecycle-logger` | +| `registerSettings` | A persisted settings document from `defineSettings` that server code reads | Reference > Settings screens | `settings` | +| `registerProvider` | A coding agent as a Paseo provider. Use `runAcpProvider` from `/server/acp` for an ACP agent. | Provider plugins | `provider-direct`, `provider-acp-transformer` | +| `registerUsageSource` | Quota reports for the logins of a provider, with helpers from `/server/usage` | Reference > Usage sources | | +| `registerWorktreeManager` | An outside tool, such as Worktrunk, that creates, removes, and restores Git worktrees | Reference > Worktree managers | `worktrunk` | + +Server handlers and hooks receive `{ paseo }`. Call `paseo.agents.ref(id).timeline.append(item)` to put a plugin-owned row in an agent timeline. `@getpaseo/plugin/server` also exports `defineAgentTool`, `execCommand`, `spawnProcess`, and `terminateProcess`. + +Do not write `server.on` or `server.before`. They are deprecated aliases. When you edit a plugin that uses them, move each one to `addHook`. The Renamed hooks table in Hooks gives the new name for each old name. ## Create the project @@ -103,47 +102,52 @@ my-plugin/ index.client.tsx index.server.ts client/greeting.tsx + client/web.ts server/greeting.ts shared/greeting.ts ``` -The manifest supplies the default install ID and supported Paseo versions: +The manifest supplies the default installation ID and the supported Paseo versions: ```json { "id": "my-plugin", "requirements": { "paseo": ">=0.8.0" } } ``` -Keep `requirements.paseo` correct whenever creating or editing a plugin. `init` uses `>=` followed -by the CLI version. Raise the minimum when adopting newer APIs; add an upper bound when a later -Paseo release is incompatible. Use npm semver ranges and explicitly include beta versions when -targeting betas. Missing requirements mean `<0.8.0`; complete the 0.8 entry migration before adding -`>=0.8.0`. Verify compatibility with both the daemon and the app running client contributions. -See [requirements](https://paseo.sh/docs/plugins/reference#requirements). +Keep `requirements.paseo` correct each time you create or edit a plugin: -Each runtime has its own optional entry. A plugin must have at least one. Both entries accept -`.ts` or `.tsx`; use `.tsx` when an entry imports components. +- `init` writes `>=` followed by the CLI version. +- Raise the minimum when you use an API from a newer release. The reference names the release for each newer API. +- Add an upper bound when a later release breaks the plugin. +- A missing `requirements.paseo` means `<0.8.0`. Finish the [migration](https://paseo.sh/docs/plugins/migration.md) before you add `>=0.8.0`. -| Path | Runtime | -| -------------------------------- | ----------------- | -| `index.client.tsx` and `client/` | App | -| `index.server.ts` and `server/` | Daemon subprocess | -| `shared/` | Both | +The daemon and each app check the range separately. Make sure that the daemon and the app both satisfy it. -Do not put any other code modules in the plugin root. +Each runtime has its own entry. A plugin needs at least one entry. -A client import of `server/`, a server import of `client/`, and every `node:` import reachable from -client code is a compile error. A relative import to another code file in the plugin root is also a -compile error; move it into `client/`, `server/`, or `shared/`. Shared modules contain Zod contracts -and plain values; they do not import Node or React Native runtime APIs. +| Path | Runtime | +| -------------------------------- | ----------------------------------- | +| `index.client.tsx` and `client/` | The Paseo app, once for each client | +| `index.server.ts` and `server/` | A daemon subprocess | +| `shared/` | Both runtimes | -Default-export one contribution function from each entry and return cleanup: +Paseo compiles each entry into its own bundle and rejects imports across the boundary: + +- Client code cannot import `server/` or a `node:` module. +- Server code cannot import `client/`, React, or React Native. +- `shared/` holds Zod contracts and plain values only. +- Put every other code module in `client/`, `server/`, or `shared/`. A code module in the plugin root is a compile error. +- Import shared helpers such as `defineRpc` from `@getpaseo/plugin`, client contexts and hooks from `/client`, Paseo UI from `/client/ui`, and server contexts from `/server`. + +These rules apply to type imports and to transitive imports too. + +Each entry default-exports one function and returns cleanup: ```tsx // index.client.tsx import type { PluginClientContext } from "@getpaseo/plugin/client"; export default function contribute(client: PluginClientContext) { - // Register components and client callbacks here. + // Register client contributions here. return () => {}; } ``` @@ -153,23 +157,43 @@ export default function contribute(client: PluginClientContext) { import type { PluginServerContext } from "@getpaseo/plugin/server"; export default function contribute(server: PluginServerContext) { - // Register daemon-side RPC handlers here. + // Register handlers, hooks, and providers here. return () => {}; } ``` -Cleanup can be async. Use it for timers, watchers, sockets, subscriptions, and other resources -created by plugin code. Every client `add*` method returns an idempotent remover. Paseo calls the -entry cleanup first, removes registrations that remain, rejects pending RPCs, closes the plugin -session, and stops the subprocess when the plugin stops. +Cleanup can be async. Use it to release the timers, watchers, sockets, and subscriptions that your code created. When a plugin stops, Paseo runs the entry cleanup, removes the remaining registrations, and stops the subprocess. -## Add a workspace panel +## Write client UI that works on every platform -Workspace panels live beside agents, terminals, files, and diffs. Plugins run on desktop and -mobile, and Paseo has multiple themes. Every `Text` must take its color from `theme.colors`. -Use `layout.compact` for padding and stacking. Unstyled text is black and fails in dark themes. +Client code runs on desktop, in browsers, and on iOS and Android. A component that works in the browser and crashes on a phone is the most common plugin bug. + +- Use React Native primitives: `View`, `Text`, `Pressable`, `ScrollView`, and `TextInput`. +- Do not use HTML elements, `className`, CSS strings, `onClick`, or DOM globals. +- Do not add `"DOM"` to `tsconfig.json` or write `/// `. Put DOM code only in `client/web.ts`, gate each export on `Platform.OS === "web"`, and give native a fallback or a no-op. +- Take every color from `theme.colors`. Text without a color is black and cannot be read in dark themes. Use `foreground` for text, `foregroundMuted` for labels, and `surface0` for the root view. +- Use `layout.compact` for padding and stacking. It is true on phones and narrow windows. +- Set `icon` fields to a [Lucide](https://lucide.dev/icons/) name, an inline `{ svg }`, or a component. Do not import `lucide-react-native` or `react-native-svg`. + +Before you report a plugin done, run this audit on `client/`. A hit outside `client/web.ts` is a bug. + +```bash +rg -n "document\.|window\.|localStorage|navigator\.|<[a-z]+[ >]|className=|onClick=" client/ +``` + +Read and change data through the API that owns it: + +- Read cached workspace and agent state with `useWorkspace(id, selector)` and `useAgent(id, selector)`. Select only the fields you render. Do not add an RPC to find the active workspace or agent. +- Use `usePaseo()` for normal Paseo operations on projects, workspaces, agents, terminals, providers, and daemon configuration. It is the plugin's one client for the selected host. Do not create another client, and release the subscriptions that you open. +- Use a plugin RPC only for work that Paseo does not do: vendor APIs, credentials, local files, and shell commands. +- Use TanStack Query for request state, caching, and mutations. + +### Add a workspace panel + +A workspace panel opens as a tab beside agents, terminals, and files. This plugin also adds a Command Center item that opens it: ```tsx +// index.client.tsx import { type PluginClientContext, type PluginWorkspacePanelProps, @@ -185,7 +209,6 @@ function Overview({ theme, layout, workspaceId }: PluginWorkspacePanelProps) { screen: { flex: 1, padding: layout.compact ? 16 : 24, - gap: layout.compact ? 8 : 12, backgroundColor: theme.colors.surface0, }, title: { color: theme.colors.foreground, fontSize: layout.compact ? 20 : 24 }, @@ -204,7 +227,6 @@ export default function contribute(client: PluginClientContext) { id: "overview", title: "Workspace overview", icon: "PanelsTopLeft", - context: "workspace", Component: Overview, }); client.addCommandCenterItem({ @@ -220,52 +242,35 @@ export default function contribute(client: PluginClientContext) { } ``` -Use `useWorkspace(id, selector)` and `useAgent(id, selector)`. Selectors are required -and their results use shallow equality. Never select the whole snapshot or add an RPC to discover -the active workspace or agent. Command callbacks receive the selected host's `paseo`, typed -`rpc(contract, input)`, `openScreen({ screenId, params? })`, and contextual `openPanel(id)` -capabilities. +Register a panel that belongs to one agent with `addAgentPanel`, and read `params.agentId` in it. Command Center callbacks receive `paseo`, `rpc`, `openScreen`, and, in workspace and agent context, `openPanel`. -## Add a screen and a sidebar item +### Add a screen and a sidebar item -Plugin screens use React Native primitives and work across desktop, browser, iOS, and Android. A sidebar item, in the header or the footer, is a component: render one or more `SidebarRow`s from `@getpaseo/plugin/client/ui`, with `SidebarSeparator` between groups, and call `openScreen` or `openPopover` from them. A screen's `title` is a string or a function of its `params`; its component receives the `params` it was opened with. Color text from `theme.colors` and pad from `layout.compact`. +A sidebar item is a component. It renders one or more `SidebarRow`s and decides what a press does: ```tsx +// index.client.tsx import type { PluginClientContext, PluginScreenProps, PluginSidebarItemProps, } from "@getpaseo/plugin/client"; import { SidebarRow } from "@getpaseo/plugin/client/ui"; -import { useMemo, useState } from "react"; +import { useState } from "react"; import { Pressable, Text, View } from "react-native"; function Counter({ theme, layout }: PluginScreenProps) { const [count, setCount] = useState(0); - const styles = useMemo( - () => ({ - screen: { - flex: 1, - padding: layout.compact ? 16 : 24, - gap: 16, - backgroundColor: theme.colors.surface0, - }, - count: { color: theme.colors.foreground, fontSize: layout.compact ? 36 : 48 }, - button: { padding: 14, borderRadius: 10, backgroundColor: theme.colors.accent }, - buttonText: { color: theme.colors.accentForeground, textAlign: "center" as const }, - }), - [theme, layout.compact], - ); return ( - - {count} + setCount((value) => value + 1)} - style={styles.button} > - Count me in + Count: {count} ); @@ -288,83 +293,64 @@ export default function contribute(client: PluginClientContext) { } ``` -Icons are Lucide icon names, inline SVG (`{ svg }`), or components; see [Icons](https://paseo.sh/docs/plugins/reference.md#icons). `theme` is a typed `PluginTheme` on every screen and panel. Primary text uses `theme.colors.foreground`; labels use `theme.colors.foregroundMuted`; the root view uses `theme.colors.surface0`. `layout.compact` is true on mobile and narrow windows. Paseo owns the route, header, host picker, close action, error boundary, and per-installation query client. +Call `openPopover(Content)` from an item to open a popover instead of a screen. Paseo owns the route, the header, the host picker, and the error boundary of a screen. -Before writing imports, classify each module as shared, client, or server. Follow the -[SDK import boundaries](https://paseo.sh/docs/plugins/reference.md#runtime-modules), including -transitive and type dependencies. The root is shared-only; hooks and client contexts belong to -`@getpaseo/plugin/client`, server contexts to `/server`, and host UI to `/client/ui`. -Install dependencies locally for typechecking; Paseo supplies host runtime modules. JSX uses the -automatic runtime. Do not import `/client/host` from plugin code. +### Add a composer control -## Works on mobile - -Before reporting a plugin done: - -- Use React Native primitives only: `View`, `Text`, `Pressable`, `ScrollView`, and `TextInput`. -- Do not use HTML elements, `className`, CSS strings, or `onClick`. -- Do not put `"DOM"` in `tsconfig.json` or use `/// `. Put DOM globals only in - `client/web.ts`, declare only what that module uses, gate every export on `Platform.OS === "web"`, - and provide the native alternative or a no-op. -- Take colors from `theme.colors`. -- Check the compact layout. - -Run this audit on `client/`: - -```bash -rg -n "document\.|window\.|localStorage|navigator\.|<[a-z]+[ >]|className=|onClick=" client/ -``` - -A hit outside `client/web.ts` is a bug. - -## Choose the correct API - -Use the existing Paseo SDK for normal Paseo operations. Use plugin RPC only for plugin-specific backend behavior. - -### Call Paseo from a surface - -`usePaseo()` borrows the selected host's current connection. Never create another client inside a surface. It is the plugin's one client in every surface: release your subscriptions in your cleanup; plugin teardown ends the rest. +A composer item renders in the composer of a running agent, of a draft agent, and of the New workspace screen. `useComposer()` returns the composer that the item sits in: ```tsx -import { usePaseo } from "@getpaseo/plugin/client"; +// index.client.tsx +import { type PluginClientContext, useComposer } from "@getpaseo/plugin/client"; +import { Action, Toggle } from "@getpaseo/plugin/client/ui"; -function PullRequestAction() { - const paseo = usePaseo(); +function ReviewFlag() { + const composer = useComposer(); + return ( + + composer.setMetadata({ "review.needsReview": value ? true : null }) + } + /> + ); +} - async function createReviewWorkspace() { - const workspace = await paseo.workspaces.create({ - title: "Review PR 42", - source: { - kind: "worktree", - cwd: "/absolute/path/to/repository", - action: "checkout", - checkoutSource: { kind: "change_request", forge: "github", number: 42 }, - }, - }); - await workspace.agents.create({ - config: { provider: "codex/gpt-5.5" }, - prompt: "Review PR #42.", - }); - } +function Checklist() { + const composer = useComposer(); + return ( + { + composer.insertText("- [ ] Tests\n- [ ] Docs\n"); + await composer.focus(); + }} + /> + ); +} - // Wire createReviewWorkspace to a Pressable. - return null; +export default function contribute(client: PluginClientContext) { + client.addComposerItem({ id: "review-flag", Component: ReviewFlag }); + client.addComposerItem({ id: "checklist", Component: Checklist }); + return () => {}; } ``` -The API covers workspaces, agents, providers, and daemon config. It omits connection lifecycle because Paseo owns the connection. Consult the current [SDK reference](https://paseo.sh/docs/sdk/reference.md) for method details. +Paseo places each control inline when the composer has room, and in the overflow sheet when it does not. On a phone, controls are always in the sheet. Keep effects in an item safe to run twice, because the sheet mounts a second instance. To reach a composer from outside it, call `useComposers({ agentId })`, `useComposers({ focused: true })`, or `client.composers(selector)`. -### Add daemon-side behavior +## Add daemon-side behavior -Define one Zod contract in `shared/`, register its subprocess handler in `index.server.ts`, and -call it from client code with `useRpc()`: +Define one Zod contract in `shared/`, handle it in `index.server.ts`, and call it from client code with `useRpc()`. `paseo plugin init` generates this RPC with the same files and export names: ```ts // shared/greeting.ts import { defineRpc } from "@getpaseo/plugin"; import { z } from "zod"; -const greeting = defineRpc({ +export const greetingRpc = defineRpc({ name: "greeting.create", input: z.object({ name: z.string() }), output: z.object({ message: z.string() }), @@ -374,9 +360,9 @@ const greeting = defineRpc({ ```ts // server/greeting.ts import type { RpcInput } from "@getpaseo/plugin"; -import { greeting } from "../shared/greeting"; +import type { greetingRpc } from "../shared/greeting"; -export async function createGreeting({ name }: RpcInput) { +export async function createGreeting({ name }: RpcInput) { return { message: `Hello, ${name}!` }; } ``` @@ -385,413 +371,202 @@ export async function createGreeting({ name }: RpcInput) { // index.server.ts import type { PluginServerContext } from "@getpaseo/plugin/server"; import { createGreeting } from "./server/greeting"; -import { greeting } from "./shared/greeting"; +import { greetingRpc } from "./shared/greeting"; export default function contribute(server: PluginServerContext) { - server.handle(greeting, createGreeting); + server.handle(greetingRpc, createGreeting); return () => {}; } ``` ```tsx // client/greeting.tsx -import { useRpc } from "@getpaseo/plugin/client"; -import { greeting } from "../shared/greeting"; +import { type PluginScreenProps, useRpc } from "@getpaseo/plugin/client"; +import { useMutation } from "@tanstack/react-query"; +import { Pressable, Text, View } from "react-native"; +import { greetingRpc } from "../shared/greeting"; -function Greeting() { - const createGreeting = useRpc(greeting); - // Use createGreeting({ name: "Ada" }) in a query, mutation, or event. - return null; +export function GreetingScreen({ theme, layout }: PluginScreenProps) { + const createGreeting = useRpc(greetingRpc); + const greeting = useMutation({ mutationFn: createGreeting }); + return ( + + greeting.mutate({ name: "Ada" })}> + + {greeting.data?.message ?? "Ask the daemon for a greeting"} + + + + ); } ``` -Inputs and outputs are validated on both sides. A top-level `Uint8Array` input or output (declared `z.instanceof(Uint8Array)`) crosses as binary; a nested one fails validation. For a stream of events, use `defineSubscription` and `useSubscription`; see [subscriptions](https://paseo.sh/docs/plugins/reference.md#subscriptions). Backend handlers receive the same `PaseoApi` as `{ paseo }`; their IPC-backed daemon session lives exactly as long as the subprocess. Backend code can use Node APIs and installed dependencies. Keep credentials, filesystem access, shell commands, and vendor API calls in the handler rather than the client surface. +The generated `index.client.tsx` registers `GreetingScreen` as a screen and adds a Greeting sidebar item that opens it. Keep it to try the RPC from the app. -Use TanStack Query for async request state, caching, and mutations. +- Paseo validates the input and the output on both sides. A top-level `Uint8Array`, declared as `z.instanceof(Uint8Array)`, crosses as binary. A nested one fails validation. +- For a stream of events, use `defineSubscription`, `server.handle`, and `useSubscription`. +- Keep credentials, file access, shell commands, and vendor calls in the server handler. +- `console.log` and `console.error` in server code go to the plugin logs. Do not log credentials. -### Contribute tools and MCP servers at session open +## Hook into agent and workspace operations -Use `before("agent.session_open")` for per-agent tools and plugin-owned MCP servers. Add this -callback inside `contribute(server)`: - -```ts -server.before("agent.session_open", ({ request }) => { - if (request.provider !== "codex") return; - return { - ...request, - mcpServers: { - ...request.mcpServers, - company: { type: "http", url: "https://tools.example.com/mcp" }, - }, - }; -}); -``` - -`tools` and `mcpServers` start empty for each plugin and accumulate across its own callbacks. -They are launch-only. Use `agent.create` to edit configuration that should be saved with the agent. -See [Attach tools to agents](https://paseo.sh/docs/plugins/reference.md#attach-tools-to-agents) -for `defineAgentTool` and targeting, and -[Inject MCP servers](https://paseo.sh/docs/plugins/reference.md#inject-mcp-servers) for server configuration and collisions. - -Starting, stopping, or reloading a plugin with a session-open hook marks open agent sessions stale. -Each reopens before its next idle prompt without interrupting a running turn. -`await paseo.agents.ref(id).reload()` applies changes immediately and interrupts a running turn; -`refresh()` only reads the current snapshot. - -### Debug daemon-side behavior - -Backend contributions can use normal Node logging. `console.log()` writes to the plugin's stdout; -`console.error()` writes to stderr. Paseo captures both streams without interfering with plugin IPC. - -Inspect recent output after install, reload, an RPC failure, or a subprocess crash: - -```bash -paseo plugin logs my-plugin -paseo plugin logs my-plugin --json -paseo plugin logs my-plugin --host -``` - -The same tail is available from **Settings → Plugins → Logs**. It includes initialization, handler, -cleanup, and final crash output. Reload, disable, and process failure retain the tail. Removing the -plugin clears it; restarting the daemon clears the in-memory tail. Structured copies also go to the -daemon log. Never log credentials or other secrets. - -## Add a composer attachment source - -Define a search RPC and declarative source in `shared/`, handle it on the server, and register it on -the client: - -```ts -// shared/issues.ts -import { defineAttachmentSource, defineRpc } from "@getpaseo/plugin"; -import { z } from "zod"; - -const searchIssues = defineRpc({ - name: "issues.search", - input: z.object({ query: z.string() }), - output: z.object({ - items: z.array( - z.object({ - id: z.string(), - identifier: z.string(), - title: z.string(), - subtitle: z.string().optional(), - url: z.string().url(), - text: z.string(), - resourceType: z.string(), - }), - ), - }), -}); - -const issues = defineAttachmentSource({ - id: "issues", - title: "Acme issue", - icon: "CircleDot", - pickerTitle: "Attach Acme issue", - searchPlaceholder: "Search by identifier or title", - search: searchIssues, -}); -``` +Register an async handler with `server.addHook(name, handler)`. This plugin adds instructions and an MCP server each time a Codex agent opens: ```ts // index.server.ts import type { PluginServerContext } from "@getpaseo/plugin/server"; -import { searchIssues } from "./shared/issues"; export default function contribute(server: PluginServerContext) { - server.handle(searchIssues, ({ query }) => searchAcmeIssues(query)); - return () => {}; -} -``` - -```tsx -// index.client.tsx -import type { PluginClientContext } from "@getpaseo/plugin/client"; -import { issues } from "./shared/issues"; - -export default function contribute(client: PluginClientContext) { - client.addAttachmentSource(issues); - return () => {}; -} -``` - -Return complete text snapshots. Paseo owns the composer menu, picker, pills, drafts, and submission. Credentials and vendor calls stay in the daemon handler. - -## Add a client slash command - -A slash command runs plugin code in the app when the user submits `/name args`. Nothing is sent to the agent. `args` is the raw text after the command name, trimmed; parse it in the plugin. - -```ts -client.addSlashCommand({ - name: "review", - description: "Run the review bot", - argumentHint: "[scope]", - context: "agent", // or "workspace" so drafts get it too - async onSubmit({ args, agent, rpc, openPanel }) { - await rpc(startReview, { agentId: agent.id, scope: args }); - openPanel("review"); - }, -}); -``` - -The callback receives the same context as the matching Command Center item plus `args`. Paseo owns the autocomplete row, input clearing, and the error toast; put pending UI in a pill or panel. Precedence is built-in client commands, then plugin commands, then provider commands; a lower-precedence collision is dropped. Commands do not run while the composer has attachments. Server-side slash commands do not exist. - -## Add a composer pill - -A pill is a per-agent button in the composer track bar next to Tasks and Subagents. Add and remove pills from the client entry lifecycle. `addComposerPill` exists on `PluginClientContext`. - -```tsx -import type { PluginButtonRegistration, PluginClientContext } from "@getpaseo/plugin/client"; - -export function contributeClient(client: PluginClientContext) { - const pills = new Map(); - const lifetime = new AbortController(); - const register = (agent: { id: string; workspaceId?: string | null }) => { - if (lifetime.signal.aborted || !agent.workspaceId) return; - const agentId = agent.id; - const workspaceId = agent.workspaceId; - pills.get(agentId)?.remove(); - pills.set( - agentId, - client.addComposerPill({ - id: "review", - workspaceId, - agentId, - button: { - title: "Open review", - icon: "Scan", - label: "Review", - behavior: { - kind: "action", - onPress() { - client.openPanel("review", { workspaceId, agentId }); - }, - }, - }, - }), - ); - }; - const removeAll = () => { - for (const pill of pills.values()) pill.remove(); - pills.clear(); - }; - // An owned list subscription delivers existing agents, then updates, and a fresh snapshot after a reconnect. - void client.paseo.agents - .list({ subscribe: {}, signal: lifetime.signal }) - .then(({ subscription }) => { - subscription.subscribe({ - snapshot: ({ entries }) => { - removeAll(); - for (const { agent } of entries) register(agent); - }, - update: (message) => { - if (message.type !== "agent_update") return; - const update = message.payload; - if (update.kind === "upsert") return register(update.agent); - pills.get(update.agentId)?.remove(); - pills.delete(update.agentId); - }, - }); - return undefined; - }) - .catch((error) => { - if (!lifetime.signal.aborted) console.error("Agent observation failed", error); - }); - return () => { - lifetime.abort(); - removeAll(); - }; -} -``` - -Call `contributeClient(client)` from `index.client.tsx`, or move its body into that entry. The `button` descriptor sets the icon, label, and behavior; Paseo owns the pressable, chrome, pending state, error reporting, and placement. `addComposerPill` returns a registration with `update()` and `remove()`. `remove()` is idempotent, and Paseo removes every pill when the plugin, client entrypoint, or host connection is torn down. - -## Transform and render timeline items - -Timeline transformers and renderers are client contributions. A transformer selects one built-in `AgentTimelineItem.type`, inspects the item, and returns zero or more versioned plugin items. `undefined` keeps the source item, `items` replaces it, `[]` removes it. A renderer draws one `kind` and `version` after validating `data` with its Zod schema. - -```ts -client.addTimelineTransformer({ - id: "inline-thinking", - query: { itemType: "reasoning" }, - transform: ({ item, phase }) => ({ - items: [ - { type: "plugin", kind: "inline-thinking", version: 1, data: { text: item.text, phase } }, - ], - }), -}); -client.addTimelineRenderer({ - kind: "inline-thinking", - version: 1, - schema: z.object({ text: z.string(), phase: z.enum(["streaming", "complete"]) }), - Component: InlineThinking, -}); -``` - -Transformers run while the render model is built, on fetched history and on every live update, so `phase` is `"streaming"` for a loading thought or running tool call. Identity comes from the source item, so a streaming item keeps its mounted component; set an output `id` when one source explodes into several items. Transformers must be synchronous and deterministic, `data` must be JSON, and a transformer that throws is logged and skipped. Render `` from `@getpaseo/plugin/client/ui` for paced assistant text; use its `style` prop to customize text appearance. `plugin-examples/inline-thinking` replaces the thinking row with inline text; `plugin-examples/timeline-items` replaces a todo tool call with a task card. - -## Append a timeline row from the daemon - -A server handler can push a plugin-owned row into any agent timeline. The same renderer registration draws it. - -```ts -server.handle(publishReview, async ({ agentId, verdict }, { paseo }) => { - await paseo.agents.ref(agentId).timeline.append({ - type: "plugin", - id: "review", - kind: "review-result", - version: 1, - data: { verdict }, + server.addHook("agent.open.before", async ({ request }) => { + if (request.provider !== "codex" || request.background) return; + return { + ...request, + appendSystemPrompt: [ + ...(request.appendSystemPrompt ?? []), + "Follow the team engineering guide.", + ], + mcpServers: { + ...request.mcpServers, + company: { type: "http", url: "https://tools.example.com/mcp" }, + }, + }; }); - return {}; -}); + return () => {}; +} ``` -The daemon stamps `pluginId` from the plugin session, so only plugin code can call this. Re-appending with the same `id` replaces the earlier row live and on refetch, which is how a plugin updates a row. `data` is capped at 64 KiB serialized and rejected above that. Rows live in the daemon's in-memory timeline and survive scroll, refetch, and reconnect, but not a daemon restart. A row whose plugin is missing renders an unavailable placeholder. Hosts advertise support through `server_info.features.pluginTimelineItems`. +| Hook | Waits | Use it to | +| ---------------------------------------------------------------- | ----- | ----------------------------------------------------------------------------------------------- | +| `workspace.create.before` | Yes | Change the create request, such as the isolation | +| `worktree.create.before` | Yes | Change the branch, slug, or path of a new worktree | +| `worktree.create.after` | Yes | Prepare files in the worktree, or throw to stop creation | +| `agent.create.before` | Yes | Change the saved configuration, `env`, or `metadata` of a new agent | +| `agent.open.before` | Yes | Add launch-only `env`, `appendSystemPrompt`, `tools`, and `mcpServers` each time an agent opens | +| `workspace.create.after`, `workspace.archive.after` | No | Observe workspaces | +| `agent.create.after`, `agent.close.after`, `agent.archive.after` | No | Observe agents | +| `agent.turn.before`, `agent.turn.after` | No | Observe turns. Read the turn and send a follow-up through `paseo`. | +| `agent.permission.before`, `agent.permission.after` | No | Answer a pending permission through `paseo`, or observe its result | -## Contribute a theme - -`addTheme` takes a small light or dark palette; Paseo expands it into the full token set. Every color is a hex string. - -```ts -client.addTheme({ - id: "mocha", - name: "Catppuccin Mocha", - appearance: "dark", - colors: { - background: "#1e1e2e", - foreground: "#cdd6f4", - raised: "#313244", - control: "#45475a", - border: "#45475a", - accent: "#cba6f7", - mutedForeground: "#a6adc8", - ring: "#6c7086", - }, -}); -``` - -It appears under Settings → Appearance. A client that predates `addTheme` cannot evaluate the entry and reports `client.addTheme is not a function`; update the client. See `plugin-examples/catppuccin`. +- Every handler must be async. +- A waiting hook that throws, returns invalid data, or runs longer than 30 seconds fails the operation. +- A notification hook that fails only logs an error, and the operation continues. +- Return a complete replacement request, or `undefined` to keep the request. +- In `agent.open.before`, do not await a write to the agent that is opening, such as `setMetadata`. The write waits for the open, so the hook times out. Start the write without `await`. +- Put configuration that must be saved with the agent in `agent.create.before`. Changes from `agent.open.before` apply to one launch only. +- `tools` and `mcpServers` start empty for each plugin. Define tools with `defineAgentTool`. +- When a plugin with an `agent.open.before` hook starts, stops, or reloads, each open agent reopens before its next prompt. A running turn is not interrupted. ## Hosts and trust -Plugins are installed per daemon and are trusted, unsandboxed code. Backend code can access files, processes, credentials, and network services on the daemon machine. Client contributions run inside the Paseo app. Do not install a plugin the user has not authorized or source code you have not inspected. +Plugins are installed for each daemon. They are trusted code with no sandbox. Server code can use the files, processes, credentials, and network of the daemon machine. Client code runs inside the Paseo app. Do not install a plugin that the user has not authorized, or source code that you have not read. -### Check the global switch before installing +When several connected hosts have the same plugin, Paseo shows its screens and sidebar items once and adds a host picker. The selected host owns the bundle, SDK calls, RPCs, and query cache. Paseo does not fall back to another host when the selected host is offline. -Identify the target daemon and inspect its root `pluginsEnabled` value in `config.json`. For the local daemon, `paseo daemon status --json` reports its `home`; the file is `/config.json`. Treat a missing field as `false`. Do not infer the global value from a plugin's `disabled` status, because an individual plugin can also be disabled. +### Check the global switch before you install -If `pluginsEnabled` is already `true`, continue without asking the user to enable it. +1. Find the target daemon. For the local daemon, `paseo daemon status --json` reports its `home`. The configuration file is `/config.json`. +2. Read the root `pluginsEnabled` field. A missing field means `false`. Do not infer the switch from the status of one plugin, because each plugin can also be disabled. +3. If `pluginsEnabled` is `true`, continue. +4. If it is `false` or missing, stop. Ask the user for permission before you change anything, and include this warning: -If it is false or absent, stop and ask the user for explicit permission before editing or enabling anything. Include this warning in the request: + > Plugins are trusted, unsandboxed code. Backend plugin code can access your daemon machine, including files, processes, credentials, and network services. Client plugin code runs inside the Paseo app. May I enable plugins on this daemon? -> Plugins are trusted, unsandboxed code. Backend plugin code can access your daemon machine, including files, processes, credentials, and network services. Client plugin code runs inside the Paseo app. May I enable plugins on this daemon? +5. If the user does not agree, stop. +6. Set the root `pluginsEnabled` field to `true`, and keep the rest of `config.json`. +7. Run `paseo reload --json` against that daemon. +8. Make sure that `appliedPaths` contains `pluginsEnabled`. If `appliedPaths` is empty, read the file again and make sure that the plugin catalog is enabled. +9. After installation, run `paseo plugin ls` and make sure that the plugin reaches `running`. -Do not continue unless the user agrees. After permission: +To turn the switch off, set `pluginsEnabled` to `false`, run `paseo reload --json`, and make sure that the plugins report `disabled`. -1. Preserve the rest of `config.json` and set the root `pluginsEnabled` field to `true`. -2. Run `paseo reload --json` against that daemon. -3. Require `pluginsEnabled` in `appliedPaths`, or accept an empty `appliedPaths` only after re-reading the file and confirming the live plugin catalog is enabled. -4. Run `paseo plugin ls` and verify the intended plugin reaches `running` after installation. +If the daemon is remote, do not edit a local file. Edit the file on the daemon machine, or ask the user to use Settings > Plugins > Enable plugins. `paseo reload --host ` reloads the remote file but does not edit it. -If the user asks to disable the global switch, set `pluginsEnabled` to `false`, run `paseo reload --json`, and verify configured plugins report `disabled`. +## Develop in a local folder -Do not edit a local config when the target is a remote daemon. Perform the edit on the daemon machine, or ask the user to use **Settings → Plugins → Enable plugins**. `paseo reload --host ` reloads the remote daemon's own file but does not edit it. +Develop a plugin in a folder that you own and install that folder by path. Paseo runs the plugin from that folder, and `paseo plugin reload ` loads your edits. -When the same screen or sidebar item exists on several connected hosts, Paseo shows it once. The screen header has a host picker; a sidebar item uses the host of the screen on display, else the host last picked in one of the plugin's screens. The selected host owns the bundle, SDK calls, RPCs, and query cache. An offline selected host does not fall through to another host. Attachment sources stay scoped to the composer's host. +Do not edit, build, or commit inside the installation of a Git, npm, or registry plugin. That folder is managed storage in the `plugins/` directory of the daemon home. `paseo plugin update` replaces it, and `paseo plugin remove` deletes it, with every edit and commit inside it. -## Publishing a listing +Before you edit an installed plugin, run `paseo plugin ls ` and read the SOURCE column. A `git:`, `npm:`, or registry source such as `/owner/slug` is a managed installation. The DIRECTORY column shows its managed folder. -Write `OVERVIEW.md` beside `paseo-plugin.json` for the plugin page inside Paseo. -It helps someone decide whether to install your plugin; the install command is already at -the top of that page. A README assumes a GitHub audience and carries installation -instructions, technical details, and badges. Long, AI-generated READMEs make people read -past that material to understand what a plugin does. +To develop a plugin that is installed from Git, npm, or the registry: -`OVERVIEW.md` is required to list your plugin in the registry. Commit it beside -`paseo-plugin.json` in the source repository at the pinned commit. The registry resolves it -relative to the manifest, under `pluginPath` for monorepos. Include it in the published npm -package too; the scaffold's `files` list includes it. Replace the scaffold's guidance comment -with useful facts before publishing. +1. Clone the source repository of the plugin into a folder outside the daemon home. For an npm plugin, find the repository in its `package.json`. +2. If SOURCE ends with `:`, use that subfolder of the clone as the plugin folder. +3. If the managed folder has edits or commits, move them into the plugin folder. +4. In the plugin folder, install the dependencies and run the `build` commands from `paseo-plugin.json`. Paseo runs `build` only for managed installations. +5. Ask the user before you remove the managed installation. `paseo plugin remove ` also deletes the saved settings of the plugin. +6. Run `paseo plugin remove `. +7. Run `paseo plugin install /absolute/path/to/plugin-folder --id ` to keep the runtime ID. +8. Edit the plugin folder. After each change, run its `build` commands if the change needs them, then run `paseo plugin reload `. -The repository overview takes precedence over a registry import stopgap. Online validation -fails when the pinned commit has no `OVERVIEW.md`, except for unchanged imported records -that already carry `plugins//.md` in the registry repository. Every version bump -requires a repository overview and removes the stopgap in the same PR. A bump without the -repository overview fails validation. README files do not supply the overview. +## Install, reload, and debug -Author overviews and registry stopgaps follow the same content contract, in this order. -Choose headings only when they help; length follows complexity. A theme needs one paragraph. - -1. Explain what the plugin is and does in plain terms first. -2. Explain how it works only when that is not obvious. -3. Explain setup when needed: settings, accounts, tokens, providers, external tools, or other - plugins. Include applicable daemon version and operating system requirements. Setup - guidance is allowed; installation instructions are not. -4. Explain capabilities and settings worth understanding, what each option does, what the - plugin reads or sends and where, permissions, and known limits. - -Use sentence case and plain factual language, with no em dashes. Omit installation commands, -badges, changelog, contributing or license sections, marketing, and unsupported claims. -Avoid implementation filler such as empty cleanup functions, catalogs of theme-token fields, -or lists of absent features. Keep only what helps someone choose the plugin. - -If your plugin is an unchanged imported record, you can propose an author-written overview -to replace the registry stopgap. Do not add import credit to your own `OVERVIEW.md`. - -See [Your listing page](https://paseo.sh/docs/plugins/publishing.md#your-listing-page). - -## Typecheck and manage - -When editing a plugin, typecheck its source before install or reload: +Typecheck the plugin before each install or reload: ```bash npm run typecheck paseo plugin install /absolute/path/to/plugin paseo plugin install /absolute/path/to/plugin --id another-runtime-id -paseo plugin install npm:@acme/paseo-review +paseo plugin install acme/review paseo plugin install npm:@acme/paseo-review@1.2.0 -paseo plugin install github:owner/repository paseo plugin install github:owner/repository --ref main -paseo plugin update my-plugin paseo plugin ls paseo plugin reload my-plugin paseo plugin logs my-plugin +paseo plugin update my-plugin paseo plugin disable my-plugin paseo plugin enable my-plugin paseo plugin remove my-plugin ``` -For npm, ensure npm is on the daemon's `PATH`; use that host's registry configuration and credentials. Install selectors choose -content once; they do not pin updates. `install` and `add` are aliases. Follow the -[publishing guide](https://paseo.sh/docs/plugins/publishing.md) for Paseo's package contents and -preparation requirements; standard npm publishing commands apply. +- `install` and `add` are aliases. A bare `owner/slug` installs from the plugin registry. +- Put `--host ` before a command to manage a daemon other than the CLI default. +- Source edits need `paseo plugin reload `. A change to the global switch needs `paseo reload`. +- Do not restart the daemon to load changes. A restart can stop the agent that does the work. +- A failed reload stays failed. Read the load error in `paseo plugin ls` and the output in `paseo plugin logs `, fix the source, typecheck, and reload again. +- `paseo plugin logs ` shows the recent stdout and stderr of the subprocess, including initialization, handler, cleanup, and crash output. Settings > Plugins > Logs shows the same output. +- `remove` keeps a local folder and deletes a managed installation. +- Most plugins do not need `build`. Declare it in `paseo-plugin.json` only when the plugin must install a dependency or generate files after acquisition. Paseo skips npm lifecycle scripts, so an npm plugin that generates files declares `build` too. Reference: CLI reference describes the format, and Publishing > Plugins with a build step describes the npm rules. -Use `--host ` when managing a daemon other than the CLI default. A Git source that must install or generate something declares `build` in `paseo-plugin.json` as a list of argv arrays; Paseo runs them without a shell on install and update and keeps the old version if one fails. Plugin source edits require `paseo plugin reload`; config changes to the global switch require `paseo reload`. A failed plugin reload stays failed; inspect `paseo plugin ls` for the load error and `paseo plugin logs ` for subprocess output, fix the source, typecheck, and reload again. `remove` keeps local source directories and deletes managed Git/npm installations. +## Publish -Do not restart the daemon to load source changes. Restarting it can kill the agent performing the work. +Follow [Publishing](https://paseo.sh/docs/plugins/publishing.md) to publish on npm or Git and to submit to the registry. -For an old mixed entry, follow the standalone [runtime-entry migration guide](https://paseo.sh/docs/plugins/migration) mechanically. +To maintain the listing page yourself, put `OVERVIEW.md` beside `paseo-plugin.json` and include it in the npm package. Without it, the registry reviewer writes the page. Explain these points in order: + +1. What the plugin does. +2. How it works, if that is not obvious. +3. Setup: settings, accounts, tokens, external tools, and supported operating systems and Paseo versions. +4. Capabilities, settings, the data it reads and where it sends that data, permissions, and limits. + +Use plain facts and sentence case. Do not include installation commands. The validator rejects `paseo plugin add`, `npm install`, and `npm i` anywhere in the overview. Also leave out badges, changelogs, and marketing. ## Verify the outcome -After a change: +After each change: 1. Run `npm run typecheck`. 2. Install or reload the exact runtime ID. -3. Run `paseo plugin ls` and require `running` with no error. -4. Confirm the contribution on the intended host. Open the Command Center with **⌘K** (macOS) or **Ctrl+K** (Windows/Linux). Type `/` in the composer for slash commands. For timeline work, run an agent turn that produces the source item and watch it while it streams, not only after it completes. For UI work, check a wide desktop window and a compact/mobile client, and switch theme to confirm text still uses `foreground` / `foregroundMuted`. -5. Exercise the changed action or RPC, including its error state. +3. Run `paseo plugin ls` and make sure that the plugin is `running` with no error. +4. Find the contribution on the intended host. Open the Command Center with Cmd+K on macOS or Ctrl+K on Windows and Linux. Type `/` in the composer to see slash commands. For a sidebar view, select it in Settings > Sidebar. +5. For timeline work, run an agent turn that produces the source item and watch it while it streams. +6. For UI work, check a wide desktop window and a compact window, and switch to a dark theme. +7. Use the changed action, RPC, or hook, and check its error state. -Common failures: +If it fails, find the symptom: -- Missing sidebar item: wrong host, plugin not `running`, the item is hidden in Settings > Sidebar, or its component throws (a `SidebarRow` with an unknown Lucide name or unsafe SVG throws). -- Unavailable client module: client bundles can use only the host-provided modules listed above. -- RPC rejection: input or output failed its Zod schema, or the handler threw. Inspect `paseo plugin logs ` for handler output. -- Plugin exits or reload fails: inspect `paseo plugin ls` for status and `paseo plugin logs ` for initialization, cleanup, or crash output. -- Stale UI: source was edited without `paseo plugin reload `. -- Timeline item shows "Plugin timeline item unavailable": no renderer registered for that `kind` and `version`, the renderer schema rejected `data`, or the plugin is not running on that host. -- Transformer has no effect: `query.itemType` does not match the source type, the transform returned `undefined`, or it threw and was skipped; check the app console for `[Plugins] Timeline transformer failed`. -- Slash command not offered: name collides with a built-in or another plugin, the context is `agent` on a draft, or the composer has attachments. -- Append rejected: the caller is not a plugin session, `data` exceeds 64 KiB, or the host predates `features.pluginTimelineItems`. +| Symptom | Check | +| -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| A sidebar item is missing | The host, the `running` status, Settings > Sidebar, and whether the component throws. A `SidebarRow` with an unknown Lucide name throws. | +| A sidebar view does not show | The user must select it in Settings > Sidebar. Installation does not select it. | +| A client module is not available | Client bundles can import only `@getpaseo/plugin`, its `/client` and `/client/ui` entries, `react`, `react-native`, `@tanstack/react-query`, and `zod`. | +| An RPC rejects | The input or output failed its Zod schema, or the handler threw. Read `paseo plugin logs `. | +| A hook fails an operation | The handler threw, returned invalid data, or ran longer than 30 seconds. Read `paseo plugin logs `. | +| The UI shows old code | The source changed without `paseo plugin reload `. | +| A timeline item shows "Plugin timeline item unavailable" | No renderer matches its `kind` and `version`, the renderer schema rejected `data`, or the plugin is not running on that host. | +| A transformer has no effect | `query.itemType` does not match the source item, the transform returned `undefined`, or it threw. The app console shows `[Plugins] Timeline transformer failed`. | +| A slash command is not offered | Its name collides with a built-in or another plugin, its context is `agent` in a draft, or the composer has attachments. | +| A client registration is "not a function" | The app is older than the API. Update the app, or raise `requirements.paseo`. |