mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
30e7a68742 | ||
|
|
6f12818b69 | ||
|
|
81be69e25b | ||
|
|
bebcec4e51 | ||
|
|
b4a0226bb0 | ||
|
|
16f3a79c8f |
@@ -56,7 +56,6 @@ sdk:
|
||||
- "packages/plugin/**"
|
||||
- "plugin-examples/**"
|
||||
- "public-docs/plugins/**"
|
||||
- "skills/paseo-plugin/**"
|
||||
- "packages/client/**"
|
||||
- "packages/highlight/**"
|
||||
- "packages/protocol/**"
|
||||
|
||||
@@ -464,10 +464,6 @@ registry property, independent of position. The [hooks reference](../public-docs
|
||||
owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved
|
||||
configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on
|
||||
every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
|
||||
`packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to
|
||||
each live session. A plugin start, stop, or reload reruns only that plugin's callback per session,
|
||||
swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes
|
||||
the provider process, so a reload must not reopen agents the plugin does not change.
|
||||
|
||||
Worktree placement is resolved before Git source planning, so a hook can change the branch and base
|
||||
without undoing fetched refs. Restores use the recorded destination and bypass creation hooks.
|
||||
|
||||
@@ -2,10 +2,8 @@ import { expect, test } from "../support/fixtures";
|
||||
import {
|
||||
applyProfileFromPicker,
|
||||
closeModelPicker,
|
||||
expectAgentProfileNameDraft,
|
||||
expectComposerDoesNotName,
|
||||
expectAgentProfilesEmptyPrompt,
|
||||
expectHostAgentProfiles,
|
||||
expectProfileEditTooltip,
|
||||
expectComposerMode,
|
||||
expectCreateProfileFromModelRow,
|
||||
@@ -16,11 +14,8 @@ import {
|
||||
expectProfileReachableByScrolling,
|
||||
expectProfileSearchResult,
|
||||
expectProfileVisibleForProvider,
|
||||
fillAgentProfileName,
|
||||
openEditProfileFromModelRow,
|
||||
openModelPicker,
|
||||
openAgentProfilesFromEmptyPrompt,
|
||||
removeOpenModalAgentProfileWithConfirm,
|
||||
searchModelPicker,
|
||||
seedAgentProfiles,
|
||||
selectModelRow,
|
||||
@@ -151,10 +146,10 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
await openModelPicker(page);
|
||||
await expectModelRowProfileActionBesideRow(page, oneMinute);
|
||||
await expectCreateProfileFromModelRow(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");
|
||||
await openModelPicker(page);
|
||||
await selectModelRow(page, oneMinute);
|
||||
await expectComposerModel(page, oneMinute.modelLabel);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await seed.restore();
|
||||
@@ -239,44 +234,4 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("canceling Remove in the composer profile editor keeps the editor and draft open", async ({
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([PROFILE]);
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "agent-profiles-remove-cancel-",
|
||||
title: "Agent profiles remove cancel",
|
||||
model: "ten-second-stream",
|
||||
modeId: "load-test",
|
||||
});
|
||||
|
||||
try {
|
||||
await openAgentRoute(page, workspace);
|
||||
await expectComposerVisible(page);
|
||||
await openModelPicker(page);
|
||||
await openEditProfileFromModelRow(page, {
|
||||
provider: "mock",
|
||||
modelId: "one-minute-stream",
|
||||
});
|
||||
await fillAgentProfileName(page, "Draft name");
|
||||
|
||||
await test.step("canceling Remove keeps the modal and draft intact", async () => {
|
||||
await removeOpenModalAgentProfileWithConfirm(page, "dismiss");
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
|
||||
await expectAgentProfileNameDraft(page, "Draft name");
|
||||
});
|
||||
|
||||
await test.step("confirming Remove deletes the profile and closes the modal", async () => {
|
||||
await removeOpenModalAgentProfileWithConfirm(page, "accept");
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expectHostAgentProfiles([]);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,32 +1,19 @@
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { 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";
|
||||
@@ -138,252 +125,4 @@ test.describe("Agent profiles settings", () => {
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("remounting the profile form keeps draft text across resize and collapsible toggles", async ({
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([
|
||||
{
|
||||
id: "agent_profile_e2e_remount",
|
||||
name: "Original profile",
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
notes: "Original note",
|
||||
},
|
||||
]);
|
||||
|
||||
try {
|
||||
await page.setViewportSize({ width: 1680, height: 900 });
|
||||
await openAgentProfileSettings(page);
|
||||
|
||||
await test.step("drawer-to-modal and compact resizes keep the edited name and save it", async () => {
|
||||
await openAgentProfileEditor(page, "Original profile");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
await fillAgentProfileName(page, "Draft rename");
|
||||
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
|
||||
await expectAgentProfileNameDraft(page, "Draft rename");
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
|
||||
await expectAgentProfileNameDraft(page, "Draft rename");
|
||||
|
||||
await saveOpenAgentProfile(page);
|
||||
await expectAgentProfile(page, {
|
||||
name: "Draft rename",
|
||||
tags: [MOCK_PROVIDER_LABEL, "One minute stream"],
|
||||
notes: "Original note",
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("collapsing and reopening advanced settings keeps the draft note", async () => {
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
await openCreateAgentProfileEditor(page);
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
|
||||
await toggleAgentProfileCustomize(page);
|
||||
await fillAgentProfileNotes(page, "Draft routing note");
|
||||
await toggleAgentProfileCustomize(page);
|
||||
await toggleAgentProfileCustomize(page);
|
||||
await expectAgentProfileNotesDraft(page, "Draft routing note");
|
||||
});
|
||||
} finally {
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("duplicating while editing asks before discarding unsaved changes", async ({ page }) => {
|
||||
const seed = await seedAgentProfiles([
|
||||
{
|
||||
id: "agent_profile_e2e_duplicate",
|
||||
name: "UI work",
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
},
|
||||
]);
|
||||
|
||||
try {
|
||||
await page.setViewportSize({ width: 1680, height: 900 });
|
||||
await openAgentProfileSettings(page);
|
||||
await openAgentProfileEditor(page, "UI work");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
await fillAgentProfileName(page, "Draft name");
|
||||
|
||||
await test.step("dismissing the prompt keeps the draft and does not create a copy", async () => {
|
||||
await duplicateOpenAgentProfileWithConfirm(page, "dismiss");
|
||||
await expectAgentProfileNameDraft(page, "Draft name");
|
||||
await expectAgentProfileOrder(page, ["UI work"]);
|
||||
});
|
||||
|
||||
await test.step("accepting the prompt creates and opens the copy", async () => {
|
||||
await duplicateOpenAgentProfileWithConfirm(page, "accept");
|
||||
await expectAgentProfileOrder(page, ["UI work", "UI work (copy)"]);
|
||||
await expectAgentProfileNameDraft(page, "UI work (copy)");
|
||||
});
|
||||
} finally {
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("docked drawer allows roster search and section switches ask before discarding a draft", async ({
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([
|
||||
{
|
||||
id: "agent_profile_e2e_docked_1",
|
||||
name: "UI work",
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
},
|
||||
{
|
||||
id: "agent_profile_e2e_docked_2",
|
||||
name: "Deep review",
|
||||
provider: "mock",
|
||||
model: "five-minute-stream",
|
||||
},
|
||||
]);
|
||||
|
||||
try {
|
||||
await page.setViewportSize({ width: 1680, height: 900 });
|
||||
await openAgentProfileSettings(page);
|
||||
await openAgentProfileEditor(page, "UI work");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
|
||||
await test.step("typing in roster search works while the docked drawer is open", async () => {
|
||||
const searchInput = page.getByTestId("agent-profiles-search-input");
|
||||
await searchInput.click();
|
||||
await page.keyboard.type("Deep");
|
||||
await expect(searchInput).toHaveValue("Deep");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
await expectAgentProfileOrder(page, ["Deep review"]);
|
||||
await page.getByTestId("agent-profiles-search-clear").click();
|
||||
});
|
||||
|
||||
await test.step("browser Back asks before discarding a draft and canceling keeps route and draft", async () => {
|
||||
await fillAgentProfileName(page, "Unsaved browser back edit");
|
||||
const profilesUrl = page.url();
|
||||
|
||||
await browserBackWithConfirm(page, "dismiss");
|
||||
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
await expectAgentProfileNameDraft(page, "Unsaved browser back edit");
|
||||
});
|
||||
|
||||
await test.step("switching Settings sections asks before discarding an edited draft", async () => {
|
||||
await fillAgentProfileName(page, "Unsaved sidebar edit");
|
||||
|
||||
await switchSettingsSectionWithConfirm(page, "Agents", "dismiss");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
await expectAgentProfileNameDraft(page, "Unsaved sidebar edit");
|
||||
|
||||
await switchSettingsSectionWithConfirm(page, "Agents", "accept");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
|
||||
await expect(page.getByTestId("settings-detail-header-title")).toHaveText("Agents");
|
||||
});
|
||||
|
||||
await test.step("confirming browser Back leaves Agent profiles and discards the draft", async () => {
|
||||
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
|
||||
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||
await openAgentProfileEditor(page, "UI work");
|
||||
await fillAgentProfileName(page, "Discard on browser back");
|
||||
const profilesUrl = page.url();
|
||||
|
||||
await browserBackWithConfirm(page, "accept");
|
||||
await expect(page).not.toHaveURL(profilesUrl, { timeout: 15_000 });
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
|
||||
});
|
||||
} finally {
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("canceling a multi-step Back jump keeps intervening browser history and confirming reaches the destination", async ({
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([
|
||||
{
|
||||
id: "agent_profile_e2e_multistep",
|
||||
name: "UI work",
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
},
|
||||
]);
|
||||
|
||||
try {
|
||||
// Narrow viewport pushes Open project -> Settings -> Agent profiles onto history.
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await openCompactAgentProfileSettings(page);
|
||||
const profilesUrl = page.url();
|
||||
|
||||
await openAgentProfileEditor(page, "UI work");
|
||||
await fillAgentProfileName(page, "Unsaved multi-step edit");
|
||||
|
||||
await test.step("canceling a two-step Back jump keeps Agent profiles, draft, and Settings in history", async () => {
|
||||
await browserHistoryJumpWithConfirm(page, -2, "dismiss");
|
||||
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
|
||||
await expectAgentProfileNameDraft(page, "Unsaved multi-step edit");
|
||||
});
|
||||
|
||||
await test.step("canceling a two-step Back jump after reload still restores the Agent profiles URL", async () => {
|
||||
await page.reload();
|
||||
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||
await openAgentProfileEditor(page, "UI work");
|
||||
await fillAgentProfileName(page, "Post-reload draft");
|
||||
|
||||
await browserHistoryJumpWithConfirm(page, -2, "dismiss");
|
||||
await expect(page).toHaveURL(profilesUrl, { timeout: 15_000 });
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible();
|
||||
await expectAgentProfileNameDraft(page, "Post-reload draft");
|
||||
});
|
||||
|
||||
await test.step("confirming a two-step Back jump lands directly on the selected destination", async () => {
|
||||
await browserHistoryJumpWithConfirm(page, -2, "accept");
|
||||
await expect(page).toHaveURL(/\/open-project/, { timeout: 15_000 });
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toHaveCount(0, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("forward navigation confirms the intervening Settings entry survived", async () => {
|
||||
await page.goForward();
|
||||
await expect(page).toHaveURL(/\/settings(?:\?|$)/, { timeout: 15_000 });
|
||||
});
|
||||
} finally {
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("canceling an untouched provider-and-model-only profile closes without a discard prompt", async ({
|
||||
page,
|
||||
}) => {
|
||||
const seed = await seedAgentProfiles([
|
||||
{
|
||||
id: "legacy_favorite:mock:one-minute-stream",
|
||||
name: "One minute stream",
|
||||
provider: "mock",
|
||||
model: "one-minute-stream",
|
||||
},
|
||||
]);
|
||||
|
||||
let dialogTriggered = false;
|
||||
const onDialog = async (dialog: { dismiss: () => Promise<void> }) => {
|
||||
dialogTriggered = true;
|
||||
await dialog.dismiss();
|
||||
};
|
||||
page.on("dialog", onDialog);
|
||||
|
||||
try {
|
||||
await page.setViewportSize({ width: 1680, height: 900 });
|
||||
await openAgentProfileSettings(page);
|
||||
await openAgentProfileEditor(page, "One minute stream");
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toBeVisible();
|
||||
await page.getByTestId("agent-profile-cancel-button").click();
|
||||
await expect(page.getByTestId("agent-profile-drawer")).toHaveCount(0, { timeout: 30_000 });
|
||||
expect(dialogTriggered).toBe(false);
|
||||
} finally {
|
||||
page.off("dialog", onDialog);
|
||||
await seed.restore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -372,25 +372,6 @@ test.describe("Plugin sidebar items", () => {
|
||||
await expect(page.getByText("Plugin failed", { exact: false })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("a plugin screen keeps the sidebar toggle before its title", async ({ page }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
await expect(headerRow(page, SHOWCASE_PLUGIN_ID, "deploys")).toBeVisible({ timeout: 30_000 });
|
||||
await runCommand(page, "Open plugin workspaces");
|
||||
await expect(screenTitle(page)).toHaveText("Workspaces");
|
||||
await page.keyboard.press("ControlOrMeta+b");
|
||||
await expect(page.getByTestId("sidebar-global-new-workspace")).not.toBeVisible();
|
||||
|
||||
await expect(visibleTestId(page, "menu-button")).toBeVisible();
|
||||
const toggle = await boxOf(visibleTestId(page, "menu-button"));
|
||||
const title = await boxOf(screenTitle(page));
|
||||
expect(toggle.x + toggle.width).toBeLessThanOrEqual(title.x);
|
||||
await qaScreenshot(page, "plugin-screen-sidebar-collapsed");
|
||||
|
||||
await visibleTestId(page, "menu-button").click();
|
||||
await expect(page.getByTestId("sidebar-global-new-workspace")).toBeVisible();
|
||||
});
|
||||
|
||||
test("a header row's shortcut hint presses the row", async ({ page }) => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
|
||||
@@ -15,8 +15,8 @@ press "id=\"model-provider-${PROVIDER_ID}\""
|
||||
wait "id=\"compact-model-list\"" 3000
|
||||
# The row's profile action sits inside Android's independent scroll viewport.
|
||||
press "id=\"model-create-profile-${PROVIDER_ID}-${PROFILE_MODEL_ID}\""
|
||||
wait "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
|
||||
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
|
||||
close
|
||||
|
||||
@@ -142,22 +142,8 @@ export async function openAgentProfileSettings(page: Page): Promise<void> {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, serverId);
|
||||
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agent-profiles"));
|
||||
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
/** Reach agent profiles on a compact viewport so Open project -> Settings -> Agent profiles are pushed. */
|
||||
export async function openCompactAgentProfileSettings(page: Page): Promise<void> {
|
||||
const serverId = getServerId();
|
||||
await gotoAppShell(page);
|
||||
await page.getByRole("button", { name: "Open menu", exact: true }).click();
|
||||
const settingsButton = page.locator('[data-testid="sidebar-settings"]:visible').first();
|
||||
await expect(settingsButton).toBeVisible({ timeout: 30_000 });
|
||||
await settingsButton.click();
|
||||
await expect(page).toHaveURL(/\/settings(?:\?|$)/, { timeout: 30_000 });
|
||||
await page.getByRole("button", { name: "Agent profiles", exact: true }).click();
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agent-profiles"));
|
||||
await page.getByRole("button", { name: "Agents", exact: true }).click();
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "agents"));
|
||||
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
@@ -170,9 +156,7 @@ export async function expectNoAgentProfiles(page: Page): Promise<void> {
|
||||
// ─── Settings: the profile list ────────────────────────────────────────────
|
||||
|
||||
export function agentProfileRow(page: Page, name: string): Locator {
|
||||
return page
|
||||
.locator('[data-testid^="agent-profile-row-"]')
|
||||
.filter({ has: page.getByText(name, { exact: true }) });
|
||||
return page.locator('[data-testid^="agent-profile-row-"]').filter({ hasText: name });
|
||||
}
|
||||
|
||||
export async function expectAgentProfile(
|
||||
@@ -181,9 +165,7 @@ export async function expectAgentProfile(
|
||||
): Promise<void> {
|
||||
const row = agentProfileRow(page, expected.name);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
for (const tag of expected.tags) {
|
||||
await expect(row).toContainText(tag);
|
||||
}
|
||||
await expect(row.getByText(expected.tags.join(" · "), { exact: true })).toBeVisible();
|
||||
if (expected.notes !== undefined) {
|
||||
await expect(row.getByText(expected.notes, { exact: true })).toBeVisible();
|
||||
}
|
||||
@@ -195,7 +177,7 @@ export async function expectAgentProfileTagsGone(
|
||||
): Promise<void> {
|
||||
const row = agentProfileRow(page, input.name);
|
||||
for (const tag of input.tags) {
|
||||
await expect(row).not.toContainText(tag);
|
||||
await expect(row.getByText(tag, { exact: true })).toHaveCount(0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,22 +196,12 @@ export async function expectAgentProfileOrder(page: Page, names: string[]): Prom
|
||||
.toEqual(names);
|
||||
}
|
||||
|
||||
async function openRowActionMenu(page: Page, name: string): Promise<void> {
|
||||
const row = agentProfileRow(page, name);
|
||||
await row.hover();
|
||||
const trigger = row.locator('[data-testid^="agent-profile-menu-"]');
|
||||
await expect(trigger).toBeVisible({ timeout: 15_000 });
|
||||
await trigger.click();
|
||||
}
|
||||
|
||||
export async function moveAgentProfileUp(page: Page, name: string): Promise<void> {
|
||||
await openRowActionMenu(page, name);
|
||||
await page.getByRole("menuitem", { name: "Move up", exact: true }).click();
|
||||
await agentProfileRow(page, name).getByRole("button", { name: "Move up", exact: true }).click();
|
||||
}
|
||||
|
||||
export async function moveAgentProfileDown(page: Page, name: string): Promise<void> {
|
||||
await openRowActionMenu(page, name);
|
||||
await page.getByRole("menuitem", { name: "Move down", exact: true }).click();
|
||||
await agentProfileRow(page, name).getByRole("button", { name: "Move down", exact: true }).click();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -243,13 +215,12 @@ export async function removeAgentProfile(page: Page, name: string): Promise<void
|
||||
await dialog.accept();
|
||||
return message;
|
||||
});
|
||||
await openRowActionMenu(page, name);
|
||||
await page.getByRole("menuitem", { name: "Remove", exact: true }).click();
|
||||
await agentProfileRow(page, name).getByRole("button", { name: "Remove", exact: true }).click();
|
||||
expect(await dialogMessage).toContain(`Remove "${name}"?`);
|
||||
await expect(agentProfileRow(page, name)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
// ─── Settings: the inspector drawer / edit sheet ───────────────────────────
|
||||
// ─── Settings: the edit modal ──────────────────────────────────────────────
|
||||
|
||||
export interface AgentProfileDraft {
|
||||
name?: string;
|
||||
@@ -260,96 +231,62 @@ export interface AgentProfileDraft {
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
function editSurface(page: Page): Locator {
|
||||
return page.locator(
|
||||
'[data-testid="agent-profile-drawer"], [data-testid="agent-profile-edit-modal"]',
|
||||
);
|
||||
function editModal(page: Page): Locator {
|
||||
return page.getByTestId("agent-profile-edit-modal");
|
||||
}
|
||||
|
||||
async function chooseSelectFieldOption(
|
||||
page: Page,
|
||||
input: { field: "model" | "mode" | "thinking"; option: string },
|
||||
input: { field: "provider" | "model" | "mode" | "thinking"; option: string },
|
||||
): Promise<void> {
|
||||
await editSurface(page).getByTestId(`agent-profile-${input.field}-trigger`).click();
|
||||
await editModal(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 });
|
||||
}
|
||||
|
||||
async function ensureCustomizeExpanded(surface: Locator): Promise<void> {
|
||||
const toggle = surface.getByTestId("agent-profile-customize-toggle");
|
||||
if ((await toggle.count()) > 0 && (await toggle.isVisible())) {
|
||||
await toggle.click();
|
||||
}
|
||||
}
|
||||
|
||||
async function chooseProfileModel(
|
||||
page: Page,
|
||||
input: { provider?: string; model?: string },
|
||||
): Promise<void> {
|
||||
await editSurface(page).getByTestId("agent-profile-model-trigger").click();
|
||||
const container = page.getByTestId("combobox-desktop-container");
|
||||
await expect(container).toBeVisible({ timeout: 30_000 });
|
||||
if (input.provider) {
|
||||
const providerRow = container.getByRole("button", {
|
||||
name: new RegExp(escapeForRegex(input.provider)),
|
||||
});
|
||||
if ((await providerRow.count()) > 0 && (await providerRow.first().isVisible())) {
|
||||
await providerRow.first().click();
|
||||
}
|
||||
}
|
||||
const targetLabel = input.model ?? input.provider;
|
||||
if (targetLabel) {
|
||||
const option = container
|
||||
.getByRole("button", { name: new RegExp(escapeForRegex(targetLabel)) })
|
||||
.first();
|
||||
await expect(option).toBeVisible({ timeout: 30_000 });
|
||||
await option.click();
|
||||
}
|
||||
function capitalize(value: string): string {
|
||||
return value.charAt(0).toUpperCase() + value.slice(1);
|
||||
}
|
||||
|
||||
async function fillAgentProfileForm(page: Page, draft: AgentProfileDraft): Promise<void> {
|
||||
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 });
|
||||
}
|
||||
const modal = editModal(page);
|
||||
if (draft.name !== undefined) {
|
||||
await surface.getByRole("textbox", { name: "Name", exact: true }).fill(draft.name);
|
||||
await modal.getByRole("textbox", { name: "Name", exact: true }).fill(draft.name);
|
||||
}
|
||||
if (draft.thinking !== undefined || draft.mode !== undefined || draft.notes !== undefined) {
|
||||
await ensureCustomizeExpanded(surface);
|
||||
// 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.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 surface.getByRole("textbox", { name: "When to use", exact: true }).fill(draft.notes);
|
||||
await modal.getByRole("textbox", { name: "When to use", exact: true }).fill(draft.notes);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveAgentProfile(page: Page): Promise<void> {
|
||||
await page.getByTestId("agent-profile-save-button").click();
|
||||
await expect(editSurface(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
await editModal(page).getByRole("button", { name: "Save", exact: true }).click();
|
||||
await expect(editModal(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function createAgentProfile(page: Page, draft: AgentProfileDraft): Promise<void> {
|
||||
await page.getByTestId("agent-profiles-add-button").click();
|
||||
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||
await page.getByRole("button", { name: "Add agent profile", exact: true }).click();
|
||||
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
|
||||
await fillAgentProfileForm(page, draft);
|
||||
await saveAgentProfile(page);
|
||||
}
|
||||
@@ -362,7 +299,7 @@ export async function createAgentProfileFromEmptyState(
|
||||
.getByTestId("agent-profiles-card")
|
||||
.getByRole("button", { name: "New profile", exact: true })
|
||||
.click();
|
||||
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
|
||||
await fillAgentProfileForm(page, draft);
|
||||
await saveAgentProfile(page);
|
||||
}
|
||||
@@ -372,183 +309,46 @@ export async function editAgentProfile(
|
||||
name: string,
|
||||
changes: AgentProfileDraft,
|
||||
): Promise<void> {
|
||||
await agentProfileRow(page, name).click();
|
||||
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||
await agentProfileRow(page, name)
|
||||
.getByRole("button", { name: "Edit profile", exact: true })
|
||||
.click();
|
||||
await expect(editModal(page)).toBeVisible({ timeout: 30_000 });
|
||||
await fillAgentProfileForm(page, changes);
|
||||
await saveAgentProfile(page);
|
||||
}
|
||||
|
||||
export async function openAgentProfileEditor(page: Page, name: string): Promise<void> {
|
||||
await agentProfileRow(page, name).click();
|
||||
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function openCreateAgentProfileEditor(page: Page): Promise<void> {
|
||||
await page.getByTestId("agent-profiles-add-button").click();
|
||||
await expect(editSurface(page)).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function fillAgentProfileName(page: Page, name: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "Name", exact: true }).fill(name);
|
||||
}
|
||||
|
||||
export async function expectAgentProfileNameDraft(page: Page, name: string): Promise<void> {
|
||||
await expect(page.getByRole("textbox", { name: "Name", exact: true })).toHaveValue(name);
|
||||
}
|
||||
|
||||
export async function toggleAgentProfileCustomize(page: Page): Promise<void> {
|
||||
await page.getByTestId("agent-profile-customize-toggle").click();
|
||||
}
|
||||
|
||||
export async function fillAgentProfileNotes(page: Page, notes: string): Promise<void> {
|
||||
await page.getByRole("textbox", { name: "When to use", exact: true }).fill(notes);
|
||||
}
|
||||
|
||||
export async function expectAgentProfileNotesDraft(page: Page, notes: string): Promise<void> {
|
||||
await expect(page.getByRole("textbox", { name: "When to use", exact: true })).toHaveValue(notes);
|
||||
}
|
||||
|
||||
export async function saveOpenAgentProfile(page: Page): Promise<void> {
|
||||
await saveAgentProfile(page);
|
||||
}
|
||||
|
||||
export async function duplicateOpenAgentProfileWithConfirm(
|
||||
page: Page,
|
||||
decision: "accept" | "dismiss",
|
||||
): Promise<void> {
|
||||
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||
const message = dialog.message();
|
||||
if (decision === "accept") {
|
||||
await dialog.accept();
|
||||
} else {
|
||||
await dialog.dismiss();
|
||||
}
|
||||
return message;
|
||||
});
|
||||
await page.getByTestId("agent-profile-drawer-more").click();
|
||||
await page.getByTestId("agent-profile-drawer-duplicate").click();
|
||||
expect(await dialogMessage).toMatch(/discard|unsaved/i);
|
||||
}
|
||||
|
||||
export async function openEditProfileFromModelRow(
|
||||
page: Page,
|
||||
input: { provider: string; modelId: string },
|
||||
): Promise<void> {
|
||||
const row = modelRow(page, input);
|
||||
await row.hover();
|
||||
const editButton = pickerViewport(page).getByTestId(
|
||||
`model-edit-profile-${input.provider}-${input.modelId}`,
|
||||
);
|
||||
await expect(editButton).toBeVisible({ timeout: 30_000 });
|
||||
await editButton.click();
|
||||
await expect(page.getByTestId("agent-profile-edit-modal")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function removeOpenModalAgentProfileWithConfirm(
|
||||
page: Page,
|
||||
decision: "accept" | "dismiss",
|
||||
): Promise<void> {
|
||||
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||
const message = dialog.message();
|
||||
if (decision === "accept") {
|
||||
await dialog.accept();
|
||||
} else {
|
||||
await dialog.dismiss();
|
||||
}
|
||||
return message;
|
||||
});
|
||||
await page.getByTestId("agent-profile-modal-remove-button").click();
|
||||
expect(await dialogMessage).toMatch(/remove/i);
|
||||
}
|
||||
|
||||
export async function switchSettingsSectionWithConfirm(
|
||||
page: Page,
|
||||
sectionName: string,
|
||||
decision: "accept" | "dismiss",
|
||||
): Promise<void> {
|
||||
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||
const message = dialog.message();
|
||||
if (decision === "accept") {
|
||||
await dialog.accept();
|
||||
} else {
|
||||
await dialog.dismiss();
|
||||
}
|
||||
return message;
|
||||
});
|
||||
await page.getByRole("button", { name: sectionName, exact: true }).click();
|
||||
expect(await dialogMessage).toMatch(/discard|unsaved/i);
|
||||
}
|
||||
|
||||
export async function browserBackWithConfirm(
|
||||
page: Page,
|
||||
decision: "accept" | "dismiss",
|
||||
): Promise<void> {
|
||||
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||
const message = dialog.message();
|
||||
if (decision === "accept") {
|
||||
await dialog.accept();
|
||||
} else {
|
||||
await dialog.dismiss();
|
||||
}
|
||||
return message;
|
||||
});
|
||||
await page.goBack();
|
||||
expect(await dialogMessage).toMatch(/discard|unsaved/i);
|
||||
}
|
||||
|
||||
export async function browserHistoryJumpWithConfirm(
|
||||
page: Page,
|
||||
delta: number,
|
||||
decision: "accept" | "dismiss",
|
||||
): Promise<void> {
|
||||
const dialogMessage = page.waitForEvent("dialog").then(async (dialog) => {
|
||||
const message = dialog.message();
|
||||
if (decision === "accept") {
|
||||
await dialog.accept();
|
||||
} else {
|
||||
await dialog.dismiss();
|
||||
}
|
||||
return message;
|
||||
});
|
||||
await page.evaluate((step) => window.history.go(step), delta);
|
||||
expect(await dialogMessage).toMatch(/discard|unsaved/i);
|
||||
}
|
||||
|
||||
/** Opens the inspector for a profile purely to read back what it stored. */
|
||||
/** Opens the modal for a profile purely to read back what it stored. */
|
||||
export async function expectAgentProfileForm(
|
||||
page: Page,
|
||||
name: string,
|
||||
expected: { provider?: string; model?: string; mode?: string; notes?: string },
|
||||
): Promise<void> {
|
||||
await agentProfileRow(page, name).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");
|
||||
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.",
|
||||
);
|
||||
expect(await notesHint.evaluate((element) => getComputedStyle(element).webkitLineClamp)).not.toBe(
|
||||
"1",
|
||||
);
|
||||
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,
|
||||
);
|
||||
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.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 });
|
||||
await modal.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(editModal(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
// ─── The model picker ──────────────────────────────────────────────────────
|
||||
@@ -735,10 +535,7 @@ export async function expectModelRowProfileActionBesideRow(
|
||||
await expect(row.getByRole("button")).toHaveCount(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/** The hover-revealed plus on an unprofiled model row opens a seeded profile form. */
|
||||
export async function expectCreateProfileFromModelRow(
|
||||
page: Page,
|
||||
input: { provider: string; modelId: string; modelLabel: string },
|
||||
@@ -751,14 +548,14 @@ export async function expectCreateProfileFromModelRow(
|
||||
await modelRow(page, input).hover();
|
||||
await expect(action).toHaveCSS("pointer-events", "auto");
|
||||
await action.click();
|
||||
|
||||
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 });
|
||||
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 });
|
||||
}
|
||||
|
||||
export async function selectModelRow(
|
||||
|
||||
@@ -1,76 +1,11 @@
|
||||
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 { useCallback, useMemo, useState, type ReactElement } from "react";
|
||||
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 {
|
||||
buildInstantAgentProfile,
|
||||
type AgentProfileSeed,
|
||||
type AgentProfileValue,
|
||||
} from "./internal/profile-form-model";
|
||||
import { removeAgentProfileById, useAgentProfiles } from "./internal/use-agent-profiles";
|
||||
|
||||
const PROFILE_SAVED_TOAST_DURATION_MS = 6000;
|
||||
|
||||
function ProfileSavedToastContent({
|
||||
name,
|
||||
onEdit,
|
||||
onUndo,
|
||||
}: {
|
||||
name: string;
|
||||
onEdit: () => void;
|
||||
onUndo: () => void;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.toastRow}>
|
||||
<Text style={styles.toastText} numberOfLines={1}>
|
||||
{t("modelSelector.profileSaved", { name })}
|
||||
</Text>
|
||||
<View style={styles.toastActions}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onPress={onEdit}
|
||||
accessibilityLabel={t("modelSelector.editProfileLabel", { name })}
|
||||
testID="model-profile-created-edit"
|
||||
>
|
||||
{t("modelSelector.editProfiles")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onPress={onUndo}
|
||||
accessibilityLabel={t("modelSelector.undoProfileSave")}
|
||||
testID="model-profile-created-undo"
|
||||
>
|
||||
{t("modelSelector.undo")}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function createProfileSavedToast(input: {
|
||||
name: string;
|
||||
onEdit: () => void;
|
||||
onUndo: () => void;
|
||||
}): ReactElement {
|
||||
return <ProfileSavedToastContent name={input.name} onEdit={input.onEdit} onUndo={input.onUndo} />;
|
||||
}
|
||||
import type { AgentProfileSeed, AgentProfileValue } from "./internal/profile-form-model";
|
||||
import { useAgentProfiles } from "./internal/use-agent-profiles";
|
||||
|
||||
export interface AgentProfileEditorControls {
|
||||
/** Save a profile immediately from a model row with defaults and show an Edit/Undo toast. */
|
||||
quickCreateFromModel: (seed: AgentProfileSeed) => Promise<AgentProfile | null>;
|
||||
/** Undo an instant creation without a confirmation prompt. */
|
||||
undoCreate: (profileId: string) => Promise<void>;
|
||||
/** Open the create form pre-filled with provider, model, and suggested name. */
|
||||
openCreateFromModel: (seed: AgentProfileSeed) => void;
|
||||
/** Open the edit form for one profile. */
|
||||
@@ -88,78 +23,8 @@ type EditorRequest =
|
||||
* never see `saveProfiles` or construct profile records themselves.
|
||||
*/
|
||||
export function useAgentProfileEditor(serverId: string | null): AgentProfileEditorControls {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const { profiles, mutateProfiles } = useAgentProfiles(serverId);
|
||||
const { entries } = useProvidersSnapshot(serverId, { cwd: null });
|
||||
const { profiles, saveProfiles } = useAgentProfiles(serverId);
|
||||
const [request, setRequest] = useState<EditorRequest | null>(null);
|
||||
const mountedRef = useRef(true);
|
||||
const dismissSavedToastRef = useRef<(() => void) | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
dismissSavedToastRef.current?.();
|
||||
dismissSavedToastRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const undoCreate = useCallback(
|
||||
async (profileId: string): Promise<void> => {
|
||||
try {
|
||||
await mutateProfiles((current) => removeAgentProfileById(current, profileId));
|
||||
} catch (error) {
|
||||
toast.error(toErrorMessage(error));
|
||||
}
|
||||
},
|
||||
[mutateProfiles, toast],
|
||||
);
|
||||
|
||||
const quickCreateFromModel = useCallback(
|
||||
async (seed: AgentProfileSeed): Promise<AgentProfile | null> => {
|
||||
const value = buildInstantAgentProfile({ seed, entries });
|
||||
const created: AgentProfile = { id: generateAgentProfileId(), ...value };
|
||||
try {
|
||||
const written = await mutateProfiles((current) => [...current, created]);
|
||||
if (!written || !mountedRef.current) {
|
||||
return written ? created : null;
|
||||
}
|
||||
dismissSavedToastRef.current?.();
|
||||
let dismiss: (() => void) | null = null;
|
||||
const clearToast = () => {
|
||||
dismiss?.();
|
||||
if (dismissSavedToastRef.current === dismiss) {
|
||||
dismissSavedToastRef.current = null;
|
||||
}
|
||||
};
|
||||
dismiss = toast.show(
|
||||
createProfileSavedToast({
|
||||
name: created.name,
|
||||
onEdit: () => {
|
||||
clearToast();
|
||||
setRequest({ mode: "edit", profile: created });
|
||||
},
|
||||
onUndo: () => {
|
||||
clearToast();
|
||||
void undoCreate(created.id);
|
||||
},
|
||||
}),
|
||||
{
|
||||
variant: "success",
|
||||
durationMs: PROFILE_SAVED_TOAST_DURATION_MS,
|
||||
testID: "model-profile-created-toast",
|
||||
},
|
||||
);
|
||||
dismissSavedToastRef.current = dismiss;
|
||||
return created;
|
||||
} catch (error) {
|
||||
toast.error(toErrorMessage(error));
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[entries, mutateProfiles, toast, undoCreate],
|
||||
);
|
||||
|
||||
const openCreateFromModel = useCallback((seed: AgentProfileSeed) => {
|
||||
setRequest({ mode: "create", seed });
|
||||
@@ -180,59 +45,15 @@ export function useAgentProfileEditor(serverId: string | null): AgentProfileEdit
|
||||
|
||||
const handleSave = useCallback(
|
||||
async (value: AgentProfileValue) => {
|
||||
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));
|
||||
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);
|
||||
},
|
||||
[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],
|
||||
[profiles, request, saveProfiles],
|
||||
);
|
||||
|
||||
const element = useMemo(
|
||||
@@ -245,34 +66,13 @@ export function useAgentProfileEditor(serverId: string | null): AgentProfileEdit
|
||||
{...(request?.mode === "create" && request.seed ? { seed: request.seed } : {})}
|
||||
onClose={close}
|
||||
onSave={handleSave}
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
),
|
||||
[close, handleRemove, handleSave, request, serverId],
|
||||
[close, handleSave, request, serverId],
|
||||
);
|
||||
|
||||
return useMemo(
|
||||
() => ({ quickCreateFromModel, undoCreate, openCreateFromModel, openEdit, element }),
|
||||
[element, openCreateFromModel, openEdit, quickCreateFromModel, undoCreate],
|
||||
() => ({ openCreateFromModel, openEdit, element }),
|
||||
[openCreateFromModel, openEdit, element],
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
toastRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[3],
|
||||
maxWidth: "100%",
|
||||
},
|
||||
toastText: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
toastActions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1.5],
|
||||
flexShrink: 0,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -27,7 +27,4 @@ export {
|
||||
type DraftAgentProfileControls,
|
||||
} from "./internal/use-agent-profile-picker";
|
||||
export { AgentProfileGlyph } from "./internal/agent-profile-glyph";
|
||||
export {
|
||||
AgentProfilesPage,
|
||||
type AgentProfilesBeforeLeaveGuard,
|
||||
} from "./settings/agent-profiles-section";
|
||||
export { AgentProfilesSection } from "./settings/agent-profiles-section";
|
||||
|
||||
@@ -31,7 +31,6 @@ 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 {
|
||||
@@ -109,57 +108,21 @@ export function agentProfileColorMapping(
|
||||
return COLOR_MAPPINGS[color];
|
||||
}
|
||||
|
||||
function ProviderFallbackIcon({
|
||||
provider,
|
||||
serverId,
|
||||
size,
|
||||
color = "",
|
||||
}: {
|
||||
provider: string;
|
||||
serverId?: string | null;
|
||||
size: number;
|
||||
color?: string;
|
||||
}) {
|
||||
const Icon = useProviderIcon(provider, serverId);
|
||||
return <Icon size={size} color={color} />;
|
||||
}
|
||||
|
||||
const ThemedProviderFallbackIcon = withUnistyles(ProviderFallbackIcon);
|
||||
|
||||
/**
|
||||
* How a profile is drawn everywhere it appears — settings 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.
|
||||
* 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.
|
||||
*/
|
||||
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)];
|
||||
if (iconKey) {
|
||||
const Icon = THEMED_ICONS[iconKey];
|
||||
return <Icon size={size} uniProps={mapping} />;
|
||||
}
|
||||
if (provider) {
|
||||
return (
|
||||
<ThemedProviderFallbackIcon
|
||||
provider={provider}
|
||||
serverId={serverId}
|
||||
size={size}
|
||||
uniProps={mapping}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <ThemedDefaultIcon size={size} uniProps={mapping} />;
|
||||
const Icon = iconKey ? THEMED_ICONS[iconKey] : ThemedDefaultIcon;
|
||||
return <Icon size={size} uniProps={mapping} />;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildControlsRequestKey,
|
||||
buildInstantAgentProfile,
|
||||
openAgentProfileForm,
|
||||
type AgentProfileFormModel,
|
||||
} from "./profile-form-model";
|
||||
@@ -71,10 +70,6 @@ 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 },
|
||||
@@ -533,71 +528,16 @@ describe("openAgentProfileForm", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps previous provider controls mounted while another model's answer is pending to prevent layout jank", () => {
|
||||
it("draws no controls for the previous model while another model's answer is pending", () => {
|
||||
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 });
|
||||
@@ -703,36 +643,6 @@ 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", () => {
|
||||
@@ -747,55 +657,3 @@ describe("buildControlsRequestKey", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildInstantAgentProfile", () => {
|
||||
it("builds a concrete profile with provider defaults from a model seed", () => {
|
||||
expect(
|
||||
buildInstantAgentProfile({
|
||||
seed: { provider: "claude", modelId: "claude-opus-5", name: "Opus 5" },
|
||||
entries: ENTRIES,
|
||||
}),
|
||||
).toEqual({
|
||||
name: "Opus 5",
|
||||
provider: "claude",
|
||||
model: "claude-opus-5",
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "think",
|
||||
options: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps compatible preferred mode and thinking levels and ignores incompatible ones", () => {
|
||||
expect(
|
||||
buildInstantAgentProfile({
|
||||
seed: { provider: "claude", modelId: "claude-opus-5" },
|
||||
entries: ENTRIES,
|
||||
preferredModeId: "accept-edits",
|
||||
preferredThinkingOptionId: "think-hard",
|
||||
}),
|
||||
).toEqual({
|
||||
name: "Opus 5",
|
||||
provider: "claude",
|
||||
model: "claude-opus-5",
|
||||
modeId: "accept-edits",
|
||||
thinkingOptionId: "think-hard",
|
||||
options: {},
|
||||
});
|
||||
|
||||
expect(
|
||||
buildInstantAgentProfile({
|
||||
seed: { provider: "claude", modelId: "claude-haiku-4-5" },
|
||||
entries: ENTRIES,
|
||||
preferredModeId: "unknown-mode",
|
||||
preferredThinkingOptionId: "think-hard",
|
||||
}),
|
||||
).toEqual({
|
||||
name: "Haiku 4.5",
|
||||
provider: "claude",
|
||||
model: "claude-haiku-4-5",
|
||||
modeId: "plan",
|
||||
thinkingOptionId: "think",
|
||||
options: {},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -41,16 +41,6 @@ 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.
|
||||
@@ -65,8 +55,6 @@ 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[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,7 +97,6 @@ export interface AgentProfileFormState {
|
||||
optionEdits: ProviderOptions;
|
||||
|
||||
providerOptions: AgentProfileFormOption[];
|
||||
unifiedModelOptions: AgentProfileUnifiedModelOption[];
|
||||
modelOptions: AgentProfileFormOption[];
|
||||
modeOptions: AgentProfileFormOption[];
|
||||
thinkingOptions: AgentProfileFormOption[];
|
||||
@@ -128,14 +115,10 @@ 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;
|
||||
@@ -159,11 +142,6 @@ 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;
|
||||
@@ -246,53 +224,6 @@ 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({
|
||||
@@ -454,28 +385,6 @@ 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();
|
||||
@@ -537,7 +446,6 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
||||
options: { ...profile.options },
|
||||
optionEdits: {},
|
||||
providerOptions: [],
|
||||
unifiedModelOptions: [],
|
||||
modelOptions: [],
|
||||
modeOptions: [],
|
||||
thinkingOptions: [],
|
||||
@@ -551,7 +459,6 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
||||
thinkingDisplay: seedDisplay(profile.thinkingOptionId),
|
||||
catalogResolution: "idle",
|
||||
controlsResolution: "idle",
|
||||
controlsPending: false,
|
||||
controlsRequest: null,
|
||||
controlsRequestKey: null,
|
||||
disclosure: {
|
||||
@@ -560,8 +467,6 @@ function buildInitialState(snapshot: AgentProfileFormSnapshot): AgentProfileForm
|
||||
showThinkingField: false,
|
||||
showControlsField: false,
|
||||
},
|
||||
isDirty: false,
|
||||
draftRevision: 0,
|
||||
isSubmitting: false,
|
||||
submitError: null,
|
||||
canSubmit: false,
|
||||
@@ -569,118 +474,17 @@ 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[] = snapshot.entries ? [...snapshot.entries] : [];
|
||||
let catalogResolution: AgentProfileResolutionStatus = snapshot.entries ? "complete" : "idle";
|
||||
let entries: readonly ProviderSnapshotEntry[] = [];
|
||||
let catalogResolution: AgentProfileResolutionStatus = "idle";
|
||||
let resolvedControlsKey: string | null = null;
|
||||
let resolvedScopeKey: string | null = null;
|
||||
let resolvedProvider: string | null = null;
|
||||
let resolvedControls: AgentOptionControl[] = [];
|
||||
let resolvedOptions: ProviderOptions = {};
|
||||
let drawnKeys: ReadonlySet<string> = new Set();
|
||||
let answeredKeys: ReadonlySet<string> = new Set();
|
||||
let listeners = new Set<() => void>();
|
||||
let closed = false;
|
||||
let hasUserEdited = false;
|
||||
let draftRevision = 0;
|
||||
let baselineFingerprint = "";
|
||||
let autoSuggestedName: string | null =
|
||||
snapshot.mode === "create" ? (snapshot.seed?.name ?? null) : null;
|
||||
|
||||
function derive(incoming: AgentProfileFormState): AgentProfileFormState {
|
||||
const models = resolveModels(entries, incoming.provider);
|
||||
@@ -698,21 +502,24 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
const controlsRequest = buildControlsRequest(next);
|
||||
const controlsRequestKey = buildControlsRequestKey(controlsRequest);
|
||||
const controlsScopeKey = buildControlsScopeKey(controlsRequest);
|
||||
const { controls, controlOptions, controlsResolution } = resolveControlsSlice({
|
||||
next,
|
||||
controlsRequestKey,
|
||||
controlsScopeKey,
|
||||
resolvedControlsKey,
|
||||
resolvedScopeKey,
|
||||
resolvedProvider,
|
||||
resolvedControls,
|
||||
resolvedOptions,
|
||||
});
|
||||
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 withOptions: AgentProfileFormState = {
|
||||
...next,
|
||||
providerOptions: buildProviderOptions(entries),
|
||||
unifiedModelOptions: buildUnifiedModelOptions(entries),
|
||||
modelOptions: buildModelOptions(models),
|
||||
modeOptions: buildModeOptions(modes),
|
||||
thinkingOptions: buildThinkingOptions(thinking),
|
||||
@@ -731,16 +538,21 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
modeDisplay: refineDisplay(
|
||||
next.modeDisplay,
|
||||
next.modeId,
|
||||
resolveModeLabel(modes, next.modeId),
|
||||
(() => {
|
||||
const mode = modes.find((entry) => entry.id === next.modeId);
|
||||
return mode ? formatAgentModeLabel(mode) : null;
|
||||
})(),
|
||||
),
|
||||
thinkingDisplay: refineDisplay(
|
||||
next.thinkingDisplay,
|
||||
next.thinkingOptionId,
|
||||
resolveThinkingLabel(thinking, next.thinkingOptionId),
|
||||
(() => {
|
||||
const option = thinking.find((entry) => entry.id === next.thinkingOptionId);
|
||||
return option ? formatThinkingOptionLabel(option) : null;
|
||||
})(),
|
||||
),
|
||||
catalogResolution,
|
||||
controlsResolution,
|
||||
controlsPending: controlsResolution === "pending",
|
||||
controlsRequest,
|
||||
controlsRequestKey,
|
||||
};
|
||||
@@ -760,40 +572,16 @@ export function openAgentProfileForm(snapshot: AgentProfileFormSnapshot): AgentP
|
||||
withOptions.provider.length > 0 &&
|
||||
!withOptions.isSubmitting;
|
||||
const resolved: AgentProfileFormState = { ...withOptions, disclosure, canSubmit };
|
||||
const submitValue = canSubmit ? buildSubmitValue(resolved) : null;
|
||||
const isDirty =
|
||||
baselineFingerprint.length > 0 && formDraftFingerprint(resolved) !== baselineFingerprint;
|
||||
return { ...resolved, isDirty, draftRevision, submitValue };
|
||||
return { ...resolved, submitValue: canSubmit ? buildSubmitValue(resolved) : null };
|
||||
}
|
||||
|
||||
let state: AgentProfileFormState = derive(buildInitialState(snapshot));
|
||||
baselineFingerprint = formDraftFingerprint(state);
|
||||
|
||||
function publish(
|
||||
mutate: (current: AgentProfileFormState) => AgentProfileFormState,
|
||||
options?: { userEdit?: boolean },
|
||||
): void {
|
||||
function publish(mutate: (current: AgentProfileFormState) => AgentProfileFormState): void {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
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;
|
||||
state = derive(mutate(state));
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
@@ -822,7 +610,6 @@ 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));
|
||||
@@ -835,149 +622,66 @@ 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) => {
|
||||
if (value !== autoSuggestedName) {
|
||||
autoSuggestedName = null;
|
||||
}
|
||||
return { ...current, name: value };
|
||||
},
|
||||
{ userEdit: true },
|
||||
),
|
||||
setName: (value) => publish((current) => ({ ...current, name: value })),
|
||||
setAppearance: (value) =>
|
||||
publish((current) => ({ ...current, icon: value.icon, color: value.color }), {
|
||||
userEdit: true,
|
||||
}),
|
||||
setNotes: (value) => publish((current) => ({ ...current, notes: value }), { userEdit: true }),
|
||||
publish((current) => ({ ...current, icon: value.icon, color: value.color })),
|
||||
setNotes: (value) => publish((current) => ({ ...current, notes: value })),
|
||||
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();
|
||||
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,
|
||||
};
|
||||
},
|
||||
{ userEdit: true },
|
||||
),
|
||||
setMode: (modeId, display) =>
|
||||
publish((current) => ({ ...current, modeId, modeDisplay: display }), { userEdit: true }),
|
||||
setThinking: (thinkingOptionId, display) =>
|
||||
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display }), {
|
||||
userEdit: true,
|
||||
}),
|
||||
setOption: (key, value) =>
|
||||
publish(
|
||||
(current) => ({
|
||||
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,
|
||||
optionEdits: { ...current.optionEdits, [key]: value },
|
||||
}),
|
||||
{ userEdit: true },
|
||||
),
|
||||
provider: providerId,
|
||||
providerDisplay: display,
|
||||
modelId: "",
|
||||
modelDisplay: null,
|
||||
modeId: "",
|
||||
modeDisplay: null,
|
||||
thinkingOptionId: "",
|
||||
thinkingDisplay: null,
|
||||
options: {},
|
||||
optionEdits: {},
|
||||
};
|
||||
}),
|
||||
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,
|
||||
};
|
||||
}),
|
||||
setMode: (modeId, display) =>
|
||||
publish((current) => ({ ...current, modeId, modeDisplay: display })),
|
||||
setThinking: (thinkingOptionId, display) =>
|
||||
publish((current) => ({ ...current, thinkingOptionId, thinkingDisplay: display })),
|
||||
setOption: (key, value) =>
|
||||
publish((current) => ({
|
||||
...current,
|
||||
optionEdits: { ...current.optionEdits, [key]: value },
|
||||
})),
|
||||
setSubmitting: (value) => publish((current) => ({ ...current, isSubmitting: value })),
|
||||
setSubmitError: (value) => publish((current) => ({ ...current, submitError: value })),
|
||||
};
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ProviderSnapshotEntry } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { buildAgentProfileRosterSummary, formatShortModelLabel } from "./profile-summary";
|
||||
|
||||
const formatFeatureCount = (count: number) => `${count} option${count === 1 ? "" : "s"}`;
|
||||
|
||||
describe("formatShortModelLabel", () => {
|
||||
it("keeps plain model names intact with no prefix", () => {
|
||||
expect(formatShortModelLabel("Claude Opus 4.6")).toEqual({
|
||||
prefix: null,
|
||||
name: "Claude Opus 4.6",
|
||||
});
|
||||
});
|
||||
|
||||
it("splits slash-qualified router model ids into prefix and short name", () => {
|
||||
expect(formatShortModelLabel("openrouter/moonshotai/kimi-k3.1-pro")).toEqual({
|
||||
prefix: "openrouter/moonshotai/",
|
||||
name: "kimi-k3.1-pro",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores leading or trailing slashes", () => {
|
||||
expect(formatShortModelLabel("/leading")).toEqual({ prefix: null, name: "/leading" });
|
||||
expect(formatShortModelLabel("trailing/")).toEqual({ prefix: null, name: "trailing/" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAgentProfileRosterSummary", () => {
|
||||
const entries: ProviderSnapshotEntry[] = [
|
||||
{
|
||||
provider: "opencode",
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
label: "OpenCode",
|
||||
models: [
|
||||
{
|
||||
provider: "opencode",
|
||||
id: "openrouter/moonshotai/kimi-k3.1-pro",
|
||||
label: "openrouter/moonshotai/kimi-k3.1-pro",
|
||||
},
|
||||
],
|
||||
modes: [{ id: "build", label: "Build" }],
|
||||
},
|
||||
];
|
||||
|
||||
it("separates short model label from provider/mode/thinking/option details", () => {
|
||||
const profile: AgentProfile = {
|
||||
id: "p1",
|
||||
name: "Kimi fast",
|
||||
provider: "opencode",
|
||||
model: "openrouter/moonshotai/kimi-k3.1-pro",
|
||||
modeId: "build",
|
||||
thinkingOptionId: "high",
|
||||
options: { fast_mode: true },
|
||||
};
|
||||
|
||||
const summary = buildAgentProfileRosterSummary({ profile, entries, formatFeatureCount });
|
||||
|
||||
expect(summary.providerLabel).toBe("OpenCode");
|
||||
expect(summary.modelLabel).toBe("kimi-k3.1-pro");
|
||||
expect(summary.modelPrefix).toBe("openrouter/moonshotai/");
|
||||
expect(summary.runtimeDetails).toEqual(["OpenCode", "Build", "High", "1 option"]);
|
||||
});
|
||||
|
||||
it("falls back to stored provider id when catalog is unavailable", () => {
|
||||
const profile: AgentProfile = {
|
||||
id: "p2",
|
||||
name: "Offline profile",
|
||||
provider: "custom-agent",
|
||||
};
|
||||
|
||||
const summary = buildAgentProfileRosterSummary({
|
||||
profile,
|
||||
entries: undefined,
|
||||
formatFeatureCount,
|
||||
});
|
||||
|
||||
expect(summary.providerLabel).toBe("custom-agent");
|
||||
expect(summary.modelLabel).toBeNull();
|
||||
expect(summary.runtimeDetails).toEqual(["custom-agent"]);
|
||||
});
|
||||
});
|
||||
@@ -7,55 +7,6 @@ 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,
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createAgentProfileWriteQueue } from "./profile-write-queue";
|
||||
|
||||
function profile(id: string, name = id): AgentProfile {
|
||||
return { id, name, provider: "claude", model: "claude-opus-5" };
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
describe("createAgentProfileWriteQueue", () => {
|
||||
it("serializes overlapping appends on the same host so both profiles persist", async () => {
|
||||
const queue = createAgentProfileWriteQueue();
|
||||
let stored: AgentProfile[] = [profile("p0")];
|
||||
const firstGate = deferred<void>();
|
||||
const writes: string[][] = [];
|
||||
|
||||
const write = async (next: AgentProfile[]) => {
|
||||
writes.push(next.map((entry) => entry.id));
|
||||
if (writes.length === 1) {
|
||||
await firstGate.promise;
|
||||
}
|
||||
stored = next;
|
||||
return stored;
|
||||
};
|
||||
|
||||
const first = queue.enqueue("host-a", {
|
||||
readCurrent: () => stored,
|
||||
write,
|
||||
updater: (current) => [...current, profile("p1")],
|
||||
});
|
||||
const second = queue.enqueue("host-a", {
|
||||
readCurrent: () => stored,
|
||||
write,
|
||||
updater: (current) => [...current, profile("p2")],
|
||||
});
|
||||
|
||||
// Wait a microtask so the first write is in flight before releasing it.
|
||||
await Promise.resolve();
|
||||
expect(writes).toEqual([["p0", "p1"]]);
|
||||
|
||||
firstGate.resolve();
|
||||
await expect(first).resolves.toEqual([profile("p0"), profile("p1")]);
|
||||
await expect(second).resolves.toEqual([profile("p0"), profile("p1"), profile("p2")]);
|
||||
expect(writes).toEqual([
|
||||
["p0", "p1"],
|
||||
["p0", "p1", "p2"],
|
||||
]);
|
||||
expect(stored.map((entry) => entry.id)).toEqual(["p0", "p1", "p2"]);
|
||||
});
|
||||
|
||||
it("removes only the undone profile when Undo overlaps another in-flight save", async () => {
|
||||
const queue = createAgentProfileWriteQueue();
|
||||
let stored: AgentProfile[] = [profile("p0"), profile("p1")];
|
||||
const saveGate = deferred<void>();
|
||||
|
||||
const appendSecond = queue.enqueue("host-a", {
|
||||
readCurrent: () => stored,
|
||||
write: async (next) => {
|
||||
await saveGate.promise;
|
||||
stored = next;
|
||||
return stored;
|
||||
},
|
||||
updater: (current) => [...current, profile("p2")],
|
||||
});
|
||||
|
||||
const undoFirst = queue.enqueue("host-a", {
|
||||
readCurrent: () => stored,
|
||||
write: async (next) => {
|
||||
stored = next;
|
||||
return stored;
|
||||
},
|
||||
updater: (current) => current.filter((entry) => entry.id !== "p1"),
|
||||
});
|
||||
|
||||
saveGate.resolve();
|
||||
await appendSecond;
|
||||
await undoFirst;
|
||||
|
||||
expect(stored.map((entry) => entry.id)).toEqual(["p0", "p2"]);
|
||||
});
|
||||
|
||||
it("recovers after a rejected write so subsequent mutations still run", async () => {
|
||||
const queue = createAgentProfileWriteQueue();
|
||||
let stored: AgentProfile[] = [profile("p0")];
|
||||
|
||||
const failing = queue.enqueue("host-a", {
|
||||
readCurrent: () => stored,
|
||||
write: async () => {
|
||||
throw new Error("network blip");
|
||||
},
|
||||
updater: (current) => [...current, profile("p1")],
|
||||
});
|
||||
|
||||
const succeeding = queue.enqueue("host-a", {
|
||||
readCurrent: () => stored,
|
||||
write: async (next) => {
|
||||
stored = next;
|
||||
return stored;
|
||||
},
|
||||
updater: (current) => [...current, profile("p2")],
|
||||
});
|
||||
|
||||
await expect(failing).rejects.toThrow("network blip");
|
||||
await expect(succeeding).resolves.toEqual([profile("p0"), profile("p2")]);
|
||||
});
|
||||
|
||||
it("skips writing when current profiles are unloaded or the updater returns null", async () => {
|
||||
const queue = createAgentProfileWriteQueue();
|
||||
let writeCalls = 0;
|
||||
|
||||
const unloaded = await queue.enqueue("host-a", {
|
||||
readCurrent: () => null,
|
||||
write: async (next) => {
|
||||
writeCalls += 1;
|
||||
return next;
|
||||
},
|
||||
updater: (current) => [...current, profile("p1")],
|
||||
});
|
||||
expect(unloaded).toBeNull();
|
||||
|
||||
const noop = await queue.enqueue("host-a", {
|
||||
readCurrent: () => [profile("p0")],
|
||||
write: async (next) => {
|
||||
writeCalls += 1;
|
||||
return next;
|
||||
},
|
||||
updater: () => null,
|
||||
});
|
||||
expect(noop).toBeNull();
|
||||
expect(writeCalls).toBe(0);
|
||||
});
|
||||
|
||||
it("does not block writes to a different host", async () => {
|
||||
const queue = createAgentProfileWriteQueue();
|
||||
const hostAGate = deferred<void>();
|
||||
let hostA: AgentProfile[] = [];
|
||||
let hostB: AgentProfile[] = [];
|
||||
|
||||
const writeA = queue.enqueue("host-a", {
|
||||
readCurrent: () => hostA,
|
||||
write: async (next) => {
|
||||
await hostAGate.promise;
|
||||
hostA = next;
|
||||
return hostA;
|
||||
},
|
||||
updater: (current) => [...current, profile("a1")],
|
||||
});
|
||||
|
||||
const writeB = await queue.enqueue("host-b", {
|
||||
readCurrent: () => hostB,
|
||||
write: async (next) => {
|
||||
hostB = next;
|
||||
return hostB;
|
||||
},
|
||||
updater: (current) => [...current, profile("b1")],
|
||||
});
|
||||
|
||||
expect(writeB).toEqual([profile("b1")]);
|
||||
hostAGate.resolve();
|
||||
await expect(writeA).resolves.toEqual([profile("a1")]);
|
||||
});
|
||||
});
|
||||
@@ -1,65 +0,0 @@
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
|
||||
export type AgentProfileListUpdater = (current: readonly AgentProfile[]) => AgentProfile[] | null;
|
||||
|
||||
export interface AgentProfileWriteStep {
|
||||
readCurrent: () => readonly AgentProfile[] | null;
|
||||
write: (next: AgentProfile[]) => Promise<AgentProfile[]>;
|
||||
updater: AgentProfileListUpdater;
|
||||
}
|
||||
|
||||
export interface AgentProfileWriteQueue {
|
||||
enqueue(serverId: string, step: AgentProfileWriteStep): Promise<AgentProfile[] | null>;
|
||||
}
|
||||
|
||||
/** Removes one profile by id, returning `null` if it is already absent so callers skip no-op writes. */
|
||||
export function removeAgentProfileById(
|
||||
current: readonly AgentProfile[],
|
||||
profileId: string,
|
||||
): AgentProfile[] | null {
|
||||
const next = current.filter((entry) => entry.id !== profileId);
|
||||
return next.length === current.length ? null : next;
|
||||
}
|
||||
|
||||
async function runQueuedWrite(
|
||||
previous: Promise<void>,
|
||||
step: AgentProfileWriteStep,
|
||||
): Promise<AgentProfile[] | null> {
|
||||
await previous;
|
||||
const current = step.readCurrent();
|
||||
if (current === null) {
|
||||
return null;
|
||||
}
|
||||
const next = step.updater(current);
|
||||
if (next === null) {
|
||||
return null;
|
||||
}
|
||||
return step.write(next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes profile list writes per host so overlapping mutations (rapid composer
|
||||
* `+` saves, Undo while another save is in flight, split-pane composers) each compute
|
||||
* their update against the result of the previous write instead of overwriting it.
|
||||
*/
|
||||
export function createAgentProfileWriteQueue(): AgentProfileWriteQueue {
|
||||
const tails = new Map<string, Promise<void>>();
|
||||
|
||||
return {
|
||||
enqueue(serverId, step) {
|
||||
const previous = tails.get(serverId) ?? Promise.resolve();
|
||||
const result = runQueuedWrite(previous, step);
|
||||
const tail = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
tails.set(serverId, tail);
|
||||
void tail.finally(() => {
|
||||
if (tails.get(serverId) === tail) {
|
||||
tails.delete(serverId);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,21 +1,8 @@
|
||||
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 { useCallback } from "react";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
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. */
|
||||
@@ -24,56 +11,24 @@ export interface UseAgentProfilesResult {
|
||||
isSupported: boolean;
|
||||
/** Writes the whole list; there is no per-profile RPC. */
|
||||
saveProfiles: (next: AgentProfile[]) => Promise<void>;
|
||||
/**
|
||||
* Applies a serialized mutation against the latest host profile list so
|
||||
* overlapping writes compose instead of overwriting each other.
|
||||
*/
|
||||
mutateProfiles: (updater: AgentProfileListUpdater) => Promise<AgentProfile[] | null>;
|
||||
}
|
||||
|
||||
export function useAgentProfiles(serverId: string | null): UseAgentProfilesResult {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const { config, patchConfig } = useDaemonConfig(serverId);
|
||||
const queryKey = useMemo(() => daemonConfigQueryKey(serverId), [serverId]);
|
||||
const isSupported = useSessionStore((state) => {
|
||||
return supportsAgentProfiles(state.sessions[serverId ?? ""]?.serverInfo?.features);
|
||||
});
|
||||
|
||||
const mutateProfiles = useCallback(
|
||||
async (updater: AgentProfileListUpdater): Promise<AgentProfile[] | null> => {
|
||||
if (!serverId) {
|
||||
return null;
|
||||
}
|
||||
return sharedProfileWriteQueue.enqueue(serverId, {
|
||||
readCurrent: () => {
|
||||
const cached = queryClient.getQueryData<MutableDaemonConfig>(queryKey);
|
||||
return cached ? (cached.agentProfiles ?? []) : null;
|
||||
},
|
||||
write: async (next) => {
|
||||
const updated = await patchConfig({ agentProfiles: next });
|
||||
if (!updated) {
|
||||
throw new Error(t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
return updated.agentProfiles ?? next;
|
||||
},
|
||||
updater,
|
||||
});
|
||||
},
|
||||
[patchConfig, queryClient, queryKey, serverId, t],
|
||||
);
|
||||
|
||||
const saveProfiles = useCallback(
|
||||
async (next: AgentProfile[]) => {
|
||||
await mutateProfiles(() => next);
|
||||
await patchConfig({ agentProfiles: next });
|
||||
},
|
||||
[mutateProfiles],
|
||||
[patchConfig],
|
||||
);
|
||||
|
||||
return {
|
||||
profiles: config ? (config.agentProfiles ?? []) : null,
|
||||
isSupported,
|
||||
saveProfiles,
|
||||
mutateProfiles,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,20 +1,14 @@
|
||||
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 { useEffect, useState, useSyncExternalStore } from "react";
|
||||
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 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.
|
||||
* 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.
|
||||
*/
|
||||
export function useAgentProfileFormModel(
|
||||
snapshot: AgentProfileFormSnapshot,
|
||||
@@ -33,78 +27,3 @@ export function useAgentProfileFormModel(
|
||||
export function useAgentProfileFormState(model: AgentProfileFormModel): AgentProfileFormState {
|
||||
return useSyncExternalStore(model.subscribe, model.getState, model.getState);
|
||||
}
|
||||
|
||||
export interface AgentProfileFormSession {
|
||||
model: AgentProfileFormModel;
|
||||
state: AgentProfileFormState;
|
||||
isDirty: boolean;
|
||||
save: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared form session used by both the desktop inspector drawer and the modal sheet.
|
||||
* Lifting this above drawer/modal framing lets responsive switches preserve unsaved edits.
|
||||
*/
|
||||
export function useAgentProfileFormSession({
|
||||
serverId,
|
||||
mode,
|
||||
profile,
|
||||
seed,
|
||||
onSave,
|
||||
onSaved,
|
||||
}: {
|
||||
serverId: string;
|
||||
mode: "create" | "edit";
|
||||
profile?: AgentProfile;
|
||||
seed?: AgentProfileSeed;
|
||||
onSave: (value: AgentProfileValue) => Promise<void>;
|
||||
onSaved: () => void;
|
||||
}): AgentProfileFormSession {
|
||||
const { entries } = useProvidersSnapshot(serverId, { cwd: null });
|
||||
const snapshot = useMemo<AgentProfileFormSnapshot>(
|
||||
() => ({
|
||||
mode,
|
||||
...(profile ? { profile } : {}),
|
||||
...(seed ? { seed } : {}),
|
||||
...(entries ? { entries } : {}),
|
||||
}),
|
||||
[entries, mode, profile, seed],
|
||||
);
|
||||
const model = useAgentProfileFormModel(snapshot);
|
||||
const state = useAgentProfileFormState(model);
|
||||
useAgentProfileFormCatalog({ serverId, model });
|
||||
useAgentProfileFormControls({ serverId, model, state });
|
||||
const mountedRef = useRef(true);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const save = useCallback(async (): Promise<boolean> => {
|
||||
const value = model.getState().submitValue;
|
||||
if (!value) {
|
||||
return false;
|
||||
}
|
||||
model.setSubmitError(null);
|
||||
model.setSubmitting(true);
|
||||
try {
|
||||
await onSave(value);
|
||||
// Only notify completion while this session is still active; switching profiles
|
||||
// mid-save unmounts this session and must not close the next editor's draft.
|
||||
if (mountedRef.current) {
|
||||
onSaved();
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
model.setSubmitError(toErrorMessage(error));
|
||||
return false;
|
||||
} finally {
|
||||
model.setSubmitting(false);
|
||||
}
|
||||
}, [model, onSave, onSaved]);
|
||||
|
||||
return useMemo(() => ({ model, state, isDirty: state.isDirty, save }), [model, save, state]);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
import { useCallback, useMemo, useRef, useState, type ReactElement } from "react";
|
||||
import { View, type PressableStateCallbackType } from "react-native";
|
||||
import { Pressable, 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 { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { Field } from "@/components/ui/form-field";
|
||||
import { identityForeground } from "@/styles/identity-colors";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
|
||||
@@ -40,6 +37,7 @@ 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 });
|
||||
|
||||
/**
|
||||
@@ -58,43 +56,39 @@ 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 }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
styles.cell,
|
||||
Boolean(hovered) && styles.cellHovered,
|
||||
pressed && styles.cellPressed,
|
||||
selected && styles.cellSelected,
|
||||
],
|
||||
[selected],
|
||||
);
|
||||
return (
|
||||
<PressHighlight
|
||||
<Pressable
|
||||
onPress={handlePress}
|
||||
style={cellStyle}
|
||||
highlightStyle={styles.cellPressed}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={accessibilityState}
|
||||
accessibilityLabel={iconKey ?? "default"}
|
||||
testID={`agent-profile-icon-cell-${iconKey ?? "default"}`}
|
||||
>
|
||||
<AgentProfileGlyph
|
||||
{...(iconKey ? { icon: iconKey } : { provider, serverId })}
|
||||
{...(iconKey ? { icon: iconKey } : {})}
|
||||
color={color}
|
||||
size={ICON_SIZE.lg}
|
||||
/>
|
||||
</PressHighlight>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -110,54 +104,58 @@ 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 (
|
||||
<PressHighlight
|
||||
<Pressable
|
||||
onPress={handlePress}
|
||||
style={styles.colorCell}
|
||||
highlightStyle={styles.cellPressed}
|
||||
style={cellStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={accessibilityState}
|
||||
accessibilityLabel={colorLabel(t, color)}
|
||||
testID={`agent-profile-color-cell-${color}`}
|
||||
>
|
||||
<View style={[styles.swatch, color === "none" ? styles.swatchNone : identitySwatch(color)]}>
|
||||
<View style={swatchStyle}>
|
||||
{selected ? (
|
||||
<ThemedCheck
|
||||
size={ICON_SIZE.sm}
|
||||
uniProps={color === "none" ? mutedIconColorMapping : onIdentityMapping}
|
||||
uniProps={color === "none" ? foregroundMutedMapping : onIdentityMapping}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</PressHighlight>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
export function AgentProfileIconButton({
|
||||
export function AgentProfileAppearanceField({
|
||||
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();
|
||||
@@ -190,10 +188,8 @@ export function AgentProfileIconButton({
|
||||
const triggerStyle = useCallback(
|
||||
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
|
||||
styles.trigger,
|
||||
variant === "hero" && styles.triggerHero,
|
||||
variant !== "hero" && size === "sm" && styles.triggerSm,
|
||||
variant !== "hero" && size !== "sm" && styles.triggerMd,
|
||||
variant === "field" && styles.triggerIconOnly,
|
||||
size === "sm" ? styles.triggerSm : styles.triggerMd,
|
||||
styles.triggerIconOnly,
|
||||
resolveControlInteractionStyles(
|
||||
{
|
||||
controlRest: styles.controlRest,
|
||||
@@ -204,36 +200,29 @@ export function AgentProfileIconButton({
|
||||
{ hovered: Boolean(hovered), active: pressed || open, disabled },
|
||||
),
|
||||
],
|
||||
[disabled, open, size, variant],
|
||||
[disabled, open, size],
|
||||
);
|
||||
|
||||
const header = useMemo(() => ({ title: label }), [label]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Field label={label} testID={testID}>
|
||||
<View ref={anchorRef} collapsable={false}>
|
||||
<PressHighlight
|
||||
<Pressable
|
||||
onPress={handleTriggerPress}
|
||||
disabled={disabled}
|
||||
style={triggerStyle}
|
||||
highlightStyle={styles.triggerPressed}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`${label} (${colorLabel(t, selectedColor)})`}
|
||||
testID={triggerTestID}
|
||||
>
|
||||
<AgentProfileGlyph
|
||||
{...(selectedIcon ? { icon: selectedIcon } : { provider, serverId })}
|
||||
{...(selectedIcon ? { icon: selectedIcon } : {})}
|
||||
color={selectedColor}
|
||||
size={variant === "hero" ? ICON_SIZE.lg : ICON_SIZE.md}
|
||||
size={ICON_SIZE.md}
|
||||
/>
|
||||
{variant === "hero" ? (
|
||||
<View style={styles.heroCaretBadge}>
|
||||
<ThemedChevronDown size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
</View>
|
||||
) : (
|
||||
<ThemedChevronDown size={ICON_SIZE.xs} uniProps={mutedIconColorMapping} />
|
||||
)}
|
||||
</PressHighlight>
|
||||
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
||||
</Pressable>
|
||||
</View>
|
||||
<Combobox
|
||||
options={EMPTY_COMBOBOX_OPTIONS}
|
||||
@@ -262,8 +251,6 @@ export function AgentProfileIconButton({
|
||||
iconKey={null}
|
||||
selected={selectedIcon === null}
|
||||
color={selectedColor}
|
||||
provider={provider}
|
||||
serverId={serverId}
|
||||
onSelect={handleIconSelect}
|
||||
/>
|
||||
{AGENT_PROFILE_ICON_KEYS.map((key) => (
|
||||
@@ -278,7 +265,7 @@ export function AgentProfileIconButton({
|
||||
</View>
|
||||
</View>
|
||||
</Combobox>
|
||||
</>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -292,8 +279,6 @@ function identitySwatch(color: Exclude<AgentProfileColor, "none">) {
|
||||
return styles[IDENTITY_SWATCH_STYLE_KEYS[color]];
|
||||
}
|
||||
|
||||
const HERO_BUTTON_SIZE = bySizing({ touch: TOUCH_TARGET, pointer: 40 });
|
||||
|
||||
const styles = StyleSheet.create((theme) => {
|
||||
const geometry = createControlGeometry(theme);
|
||||
|
||||
@@ -307,29 +292,6 @@ 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: {
|
||||
@@ -377,7 +339,7 @@ const styles = StyleSheet.create((theme) => {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
cellPressed: {
|
||||
opacity: theme.opacity[50],
|
||||
opacity: 0.7,
|
||||
},
|
||||
cellSelected: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
|
||||
@@ -1,503 +0,0 @@
|
||||
import { useCallback, useMemo, type ReactElement } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ArrowDown, ArrowUp, Copy, MoreVertical, Trash2, X } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { AgentProfile } from "@getpaseo/protocol/messages";
|
||||
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DismissBackdrop } from "@/components/ui/dismiss-backdrop";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { ToolbarButton } from "@/components/ui/pane-content-toolbar";
|
||||
import { ScrollView } from "@/components/ui/scroll-view";
|
||||
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { OverlayLayerProvider, useOverlayLayer } from "@/lib/overlay-root";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { WindowChromeRegion, WindowChromeSafeArea } from "@/utils/desktop-window";
|
||||
import type { AgentProfileSeed, AgentProfileValue } from "../internal/profile-form-model";
|
||||
import {
|
||||
useAgentProfileFormSession,
|
||||
type AgentProfileFormSession,
|
||||
} from "../internal/use-profile-form-model";
|
||||
import { AgentProfileIconButton } from "./agent-profile-appearance-field";
|
||||
import { AgentProfileFormFields } from "./agent-profile-form-fields";
|
||||
|
||||
export const AGENT_PROFILE_DRAWER_WIDTH = 440;
|
||||
|
||||
const ThemedArrowUp = withUnistyles(ArrowUp);
|
||||
const ThemedArrowDown = withUnistyles(ArrowDown);
|
||||
const ThemedMoreVertical = withUnistyles(MoreVertical);
|
||||
const ThemedCopy = withUnistyles(Copy);
|
||||
const ThemedTrash2 = withUnistyles(Trash2);
|
||||
const ThemedX = withUnistyles(X);
|
||||
const destructiveIconColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||
|
||||
const duplicateMenuIcon = <ThemedCopy size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||
const removeMenuIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveIconColorMapping} />;
|
||||
|
||||
export interface AgentProfileDrawerProps {
|
||||
serverId: string;
|
||||
mode: "create" | "edit";
|
||||
profile?: AgentProfile;
|
||||
seed?: AgentProfileSeed;
|
||||
/** Optional pre-owned session so resizing between drawer and modal preserves unsaved edits. */
|
||||
session?: AgentProfileFormSession;
|
||||
/** Renders as an absolute right-edge slide-over instead of reflowing the roster beside it. */
|
||||
overlay?: boolean;
|
||||
canStepPrev?: boolean;
|
||||
canStepNext?: boolean;
|
||||
onStepPrev?: () => void;
|
||||
onStepNext?: () => void;
|
||||
onClose: () => void;
|
||||
onSave: (value: AgentProfileValue) => Promise<void>;
|
||||
onDuplicate?: (profileId: string) => void;
|
||||
onRemove?: (profileId: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Full-height right inspector drawer for creating and editing agent profiles.
|
||||
* Pinned header + independent scroll + pinned footer prevent vertical re-centering
|
||||
* when async provider options resolve.
|
||||
*/
|
||||
export function AgentProfileDrawer(props: AgentProfileDrawerProps): ReactElement {
|
||||
if (props.session) {
|
||||
return <AgentProfileDrawerContent {...props} session={props.session} />;
|
||||
}
|
||||
const key =
|
||||
props.mode === "edit"
|
||||
? `drawer-edit:${props.profile?.id ?? ""}`
|
||||
: `drawer-create:${props.seed?.provider ?? ""}:${props.seed?.modelId ?? ""}`;
|
||||
return <StandaloneAgentProfileDrawer key={key} {...props} />;
|
||||
}
|
||||
|
||||
function StandaloneAgentProfileDrawer(props: AgentProfileDrawerProps): ReactElement {
|
||||
const session = useAgentProfileFormSession({
|
||||
serverId: props.serverId,
|
||||
mode: props.mode,
|
||||
profile: props.profile,
|
||||
seed: props.seed,
|
||||
onSave: props.onSave,
|
||||
onSaved: props.onClose,
|
||||
});
|
||||
return <AgentProfileDrawerContent {...props} session={session} />;
|
||||
}
|
||||
|
||||
function DrawerOverflowMenu({
|
||||
profileName,
|
||||
disabled,
|
||||
onDuplicate,
|
||||
onRemove,
|
||||
}: {
|
||||
profileName: string;
|
||||
disabled: boolean;
|
||||
onDuplicate?: () => void;
|
||||
onRemove?: () => void;
|
||||
}): ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
if (!onDuplicate && !onRemove) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<DropdownMenu compactMode="sheet">
|
||||
<ToolbarButton
|
||||
kind="menu"
|
||||
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
|
||||
disabled={disabled}
|
||||
testID="agent-profile-drawer-more"
|
||||
>
|
||||
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
<DropdownMenuContent side="bottom" align="end" width={180}>
|
||||
{onDuplicate ? (
|
||||
<DropdownMenuItem
|
||||
leading={duplicateMenuIcon}
|
||||
onSelect={onDuplicate}
|
||||
testID="agent-profile-drawer-duplicate"
|
||||
>
|
||||
{t("settings.host.agentProfiles.duplicate")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{onDuplicate && onRemove ? <DropdownMenuSeparator /> : null}
|
||||
{onRemove ? (
|
||||
<DropdownMenuItem
|
||||
destructive
|
||||
leading={removeMenuIcon}
|
||||
onSelect={onRemove}
|
||||
testID="agent-profile-drawer-remove"
|
||||
>
|
||||
{t("settings.host.agentProfiles.remove")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function DrawerHeader({
|
||||
serverId,
|
||||
mode,
|
||||
state,
|
||||
canStepPrev,
|
||||
canStepNext,
|
||||
onStepPrev,
|
||||
onStepNext,
|
||||
onDuplicate,
|
||||
onRemove,
|
||||
onAppearanceChange,
|
||||
onClose,
|
||||
}: {
|
||||
serverId: string;
|
||||
mode: "create" | "edit";
|
||||
state: AgentProfileFormSession["state"];
|
||||
canStepPrev: boolean;
|
||||
canStepNext: boolean;
|
||||
onStepPrev?: () => void;
|
||||
onStepNext?: () => void;
|
||||
onDuplicate?: () => void;
|
||||
onRemove?: () => void;
|
||||
onAppearanceChange: (value: { icon: string; color: string }) => void;
|
||||
onClose: () => void;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const fallbackTitle =
|
||||
mode === "edit"
|
||||
? t("settings.host.agentProfiles.editProfileTitle")
|
||||
: t("settings.host.agentProfiles.addProfileTitle");
|
||||
const title = state.name.trim() || fallbackTitle;
|
||||
const parts = [state.providerDisplay?.label, state.modelDisplay?.label].filter(Boolean);
|
||||
const subtitle =
|
||||
parts.length > 0 ? parts.join(" · ") : t("settings.host.agentProfiles.chooseModelPlaceholder");
|
||||
const showSteppers = mode === "edit" && Boolean(onStepPrev && onStepNext);
|
||||
|
||||
return (
|
||||
<View style={styles.headerChrome}>
|
||||
<TitlebarDragRegion />
|
||||
<WindowChromeSafeArea placement="below" />
|
||||
<View style={styles.header}>
|
||||
<View style={styles.headerIdentity}>
|
||||
<AgentProfileIconButton
|
||||
label={t("settings.host.agentProfiles.iconLabel")}
|
||||
icon={state.icon}
|
||||
color={state.color}
|
||||
provider={state.provider || undefined}
|
||||
serverId={serverId}
|
||||
onChange={onAppearanceChange}
|
||||
variant="hero"
|
||||
disabled={state.isSubmitting}
|
||||
triggerTestID="agent-profile-icon-trigger"
|
||||
/>
|
||||
<View style={styles.headerText}>
|
||||
<Text style={styles.headerTitle} numberOfLines={1} testID="agent-profile-drawer-title">
|
||||
{title}
|
||||
</Text>
|
||||
<Text style={styles.headerSubtitle} numberOfLines={1}>
|
||||
{subtitle}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.headerActions}>
|
||||
{showSteppers && onStepPrev && onStepNext ? (
|
||||
<>
|
||||
<ToolbarButton
|
||||
label={t("settings.host.agentProfiles.previousProfile")}
|
||||
onPress={onStepPrev}
|
||||
disabled={!canStepPrev || state.isSubmitting}
|
||||
testID="agent-profile-drawer-prev"
|
||||
>
|
||||
<ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
<ToolbarButton
|
||||
label={t("settings.host.agentProfiles.nextProfile")}
|
||||
onPress={onStepNext}
|
||||
disabled={!canStepNext || state.isSubmitting}
|
||||
testID="agent-profile-drawer-next"
|
||||
>
|
||||
<ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
</>
|
||||
) : null}
|
||||
{mode === "edit" ? (
|
||||
<DrawerOverflowMenu
|
||||
profileName={title}
|
||||
disabled={state.isSubmitting}
|
||||
onDuplicate={onDuplicate}
|
||||
onRemove={onRemove}
|
||||
/>
|
||||
) : null}
|
||||
<ToolbarButton
|
||||
label={t("common.actions.close")}
|
||||
onPress={onClose}
|
||||
disabled={state.isSubmitting}
|
||||
testID="agent-profile-drawer-close"
|
||||
>
|
||||
<ThemedX size={ICON_SIZE.md} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function DrawerFooter({
|
||||
canSubmit,
|
||||
isSubmitting,
|
||||
onClose,
|
||||
onSave,
|
||||
}: {
|
||||
canSubmit: boolean;
|
||||
isSubmitting: boolean;
|
||||
onClose: () => void;
|
||||
onSave: () => void;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.footer}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onPress={onClose}
|
||||
disabled={isSubmitting}
|
||||
testID="agent-profile-cancel-button"
|
||||
>
|
||||
{t("common.actions.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="default"
|
||||
onPress={onSave}
|
||||
disabled={!canSubmit}
|
||||
loading={isSubmitting}
|
||||
testID="agent-profile-save-button"
|
||||
>
|
||||
{t("settings.host.agentProfiles.save")}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentProfileDrawerContent({
|
||||
serverId,
|
||||
mode,
|
||||
profile,
|
||||
session,
|
||||
overlay = false,
|
||||
canStepPrev = false,
|
||||
canStepNext = false,
|
||||
onStepPrev,
|
||||
onStepNext,
|
||||
onClose,
|
||||
onDuplicate,
|
||||
onRemove,
|
||||
}: AgentProfileDrawerProps & { session: AgentProfileFormSession }): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const { model, state, save } = session;
|
||||
const drawerLayer = useOverlayLayer("floating");
|
||||
|
||||
const handleOverlayKeyDown = useCallback(
|
||||
(event: KeyboardInputEvent) => {
|
||||
if (event.key !== "Escape") {
|
||||
return false;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!state.isSubmitting) {
|
||||
onClose();
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[onClose, state.isSubmitting],
|
||||
);
|
||||
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
keys: ["Escape"],
|
||||
active: true,
|
||||
layer: drawerLayer,
|
||||
// Only trap focus in slide-over overlay mode; a docked drawer sits beside the
|
||||
// interactive roster and must let users click and type in roster search.
|
||||
manageFocus: overlay,
|
||||
onKeyDown: handleOverlayKeyDown,
|
||||
});
|
||||
|
||||
const handleAppearanceChange = useCallback(
|
||||
(value: { icon: string; color: string }) => model.setAppearance(value),
|
||||
[model],
|
||||
);
|
||||
|
||||
const handleSavePress = useCallback(() => {
|
||||
void save();
|
||||
}, [save]);
|
||||
|
||||
const handleDuplicate = useCallback(() => {
|
||||
if (profile && onDuplicate) {
|
||||
onDuplicate(profile.id);
|
||||
}
|
||||
}, [onDuplicate, profile]);
|
||||
|
||||
const handleRemove = useCallback(() => {
|
||||
if (profile && onRemove) {
|
||||
onRemove(profile.id);
|
||||
}
|
||||
}, [onRemove, profile]);
|
||||
|
||||
const handleBackdropPress = useCallback(() => {
|
||||
if (!state.isSubmitting) {
|
||||
onClose();
|
||||
}
|
||||
}, [onClose, state.isSubmitting]);
|
||||
|
||||
const drawerStyle = useMemo(
|
||||
() => [styles.drawer, overlay && styles.drawerOverlay, overlay && { zIndex: drawerLayer }],
|
||||
[drawerLayer, overlay],
|
||||
);
|
||||
const overlayHostStyle = useMemo(
|
||||
() => [styles.overlayHost, { zIndex: drawerLayer }],
|
||||
[drawerLayer],
|
||||
);
|
||||
|
||||
const drawerPanel = (
|
||||
<WindowChromeRegion corners="top-right">
|
||||
<OverlayLayerProvider layer={drawerLayer}>
|
||||
<View ref={setOverlayScope} style={drawerStyle} testID="agent-profile-drawer">
|
||||
<DrawerHeader
|
||||
serverId={serverId}
|
||||
mode={mode}
|
||||
state={state}
|
||||
canStepPrev={canStepPrev}
|
||||
canStepNext={canStepNext}
|
||||
onStepPrev={onStepPrev}
|
||||
onStepNext={onStepNext}
|
||||
onDuplicate={profile && onDuplicate ? handleDuplicate : undefined}
|
||||
onRemove={profile && onRemove ? handleRemove : undefined}
|
||||
onAppearanceChange={handleAppearanceChange}
|
||||
onClose={onClose}
|
||||
/>
|
||||
|
||||
<ScrollView style={styles.scroll} keyboardShouldPersistTaps="handled">
|
||||
<View style={styles.scrollContent}>
|
||||
<AgentProfileFormFields
|
||||
serverId={serverId}
|
||||
model={model}
|
||||
state={state}
|
||||
showInlineIcon={false}
|
||||
collapsibleDefaults={false}
|
||||
/>
|
||||
</View>
|
||||
</ScrollView>
|
||||
|
||||
<DrawerFooter
|
||||
canSubmit={state.canSubmit}
|
||||
isSubmitting={state.isSubmitting}
|
||||
onClose={onClose}
|
||||
onSave={handleSavePress}
|
||||
/>
|
||||
</View>
|
||||
</OverlayLayerProvider>
|
||||
</WindowChromeRegion>
|
||||
);
|
||||
|
||||
if (!overlay) {
|
||||
return drawerPanel;
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={overlayHostStyle} pointerEvents="box-none">
|
||||
<View style={styles.overlayBackdrop} pointerEvents="none" />
|
||||
<DismissBackdrop label={t("common.actions.close")} onPress={handleBackdropPress} />
|
||||
{drawerPanel}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
overlayHost: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
flexDirection: "row",
|
||||
justifyContent: "flex-end",
|
||||
},
|
||||
overlayBackdrop: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
backgroundColor: theme.colors.background,
|
||||
opacity: theme.opacity[50],
|
||||
},
|
||||
drawer: {
|
||||
width: AGENT_PROFILE_DRAWER_WIDTH,
|
||||
flexShrink: 0,
|
||||
backgroundColor: theme.colors.surface0,
|
||||
borderLeftWidth: theme.borderWidth[1],
|
||||
borderLeftColor: theme.colors.borderAccent,
|
||||
},
|
||||
drawerOverlay: {
|
||||
height: "100%",
|
||||
...theme.shadow.lg,
|
||||
},
|
||||
headerChrome: {
|
||||
position: "relative",
|
||||
borderBottomWidth: theme.borderWidth[1],
|
||||
borderBottomColor: theme.colors.border,
|
||||
},
|
||||
header: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: theme.spacing[3],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingVertical: theme.spacing[4],
|
||||
},
|
||||
headerIdentity: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
headerText: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
gap: theme.spacing[0.5],
|
||||
},
|
||||
headerTitle: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
headerSubtitle: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
headerActions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
flexShrink: 0,
|
||||
},
|
||||
scroll: {
|
||||
flex: 1,
|
||||
},
|
||||
scrollContent: {
|
||||
padding: theme.spacing[4],
|
||||
paddingBottom: theme.spacing[8],
|
||||
},
|
||||
footer: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "flex-end",
|
||||
gap: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingVertical: theme.spacing[3],
|
||||
borderTopWidth: theme.borderWidth[1],
|
||||
borderTopColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface0,
|
||||
},
|
||||
}));
|
||||
@@ -1,16 +1,36 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactElement } from "react";
|
||||
import { View } from "react-native";
|
||||
import { Text, 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 { AgentProfileSeed, AgentProfileValue } from "../internal/profile-form-model";
|
||||
import { type ControlSize } from "@/components/ui/control-geometry";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import {
|
||||
useAgentProfileFormSession,
|
||||
type AgentProfileFormSession,
|
||||
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,
|
||||
} from "../internal/use-profile-form-model";
|
||||
import { AgentProfileFormFields } from "./agent-profile-form-fields";
|
||||
|
||||
export interface AgentProfileEditModalProps {
|
||||
serverId: string;
|
||||
@@ -18,15 +38,16 @@ export interface AgentProfileEditModalProps {
|
||||
mode: "create" | "edit";
|
||||
profile?: AgentProfile;
|
||||
seed?: AgentProfileSeed;
|
||||
/** Optional pre-owned session so resizing between drawer and modal preserves unsaved edits. */
|
||||
session?: AgentProfileFormSession;
|
||||
/** Starts create mode with Mode, Thinking, Notes & Options collapsed behind a summary row. */
|
||||
collapsibleDefaults?: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (value: AgentProfileValue) => Promise<void>;
|
||||
onRemove?: (profileId: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Only reachable before the catalog lands. Every select is seeded to a concrete
|
||||
* id as soon as one exists, and none of them offer an "unset" row.
|
||||
*/
|
||||
const UNSET_VALUE = "";
|
||||
|
||||
function openKey(props: AgentProfileEditModalProps): string {
|
||||
if (props.mode === "edit") {
|
||||
return `edit:${props.profile?.id ?? ""}`;
|
||||
@@ -36,11 +57,7 @@ function openKey(props: AgentProfileEditModalProps): string {
|
||||
|
||||
/**
|
||||
* Create and edit never share a mounted instance: the body is keyed on mode plus
|
||||
* 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.
|
||||
* profile id, so every open constructs a form model seeded from that record.
|
||||
*/
|
||||
export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactElement | null {
|
||||
const [renderedProps, setRenderedProps] = useState<AgentProfileEditModalProps | null>(() =>
|
||||
@@ -84,24 +101,10 @@ export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactE
|
||||
return null;
|
||||
}
|
||||
|
||||
const activeProps = props.visible ? props : renderedProps;
|
||||
|
||||
if (activeProps.session) {
|
||||
return (
|
||||
<AgentProfileEditModalContent
|
||||
{...activeProps}
|
||||
session={activeProps.session}
|
||||
visible={sheetVisible}
|
||||
onClose={requestClose}
|
||||
onDismiss={handleDismiss}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<StandaloneAgentProfileEditModal
|
||||
key={openKey(activeProps)}
|
||||
{...activeProps}
|
||||
<OpenAgentProfileEditModal
|
||||
key={openKey(renderedProps)}
|
||||
{...renderedProps}
|
||||
visible={sheetVisible}
|
||||
onClose={requestClose}
|
||||
onDismiss={handleDismiss}
|
||||
@@ -109,36 +112,36 @@ export function AgentProfileEditModal(props: AgentProfileEditModalProps): ReactE
|
||||
);
|
||||
}
|
||||
|
||||
function StandaloneAgentProfileEditModal(
|
||||
props: AgentProfileEditModalProps & { onDismiss: () => void },
|
||||
): ReactElement {
|
||||
const session = useAgentProfileFormSession({
|
||||
serverId: props.serverId,
|
||||
mode: props.mode,
|
||||
profile: props.profile,
|
||||
seed: props.seed,
|
||||
onSave: props.onSave,
|
||||
onSaved: props.onClose,
|
||||
});
|
||||
return <AgentProfileEditModalContent {...props} session={session} />;
|
||||
function toSelectOptions(options: AgentProfileFormOption[]): SelectFieldOption<string>[] {
|
||||
return options.map((option) => ({
|
||||
id: option.id,
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
...(option.description ? { description: option.description } : {}),
|
||||
testID: option.testID,
|
||||
}));
|
||||
}
|
||||
|
||||
function AgentProfileEditModalContent({
|
||||
function OpenAgentProfileEditModal({
|
||||
serverId,
|
||||
visible,
|
||||
mode,
|
||||
profile,
|
||||
session,
|
||||
collapsibleDefaults,
|
||||
seed,
|
||||
onClose,
|
||||
onDismiss,
|
||||
onRemove,
|
||||
}: AgentProfileEditModalProps & {
|
||||
session: AgentProfileFormSession;
|
||||
onDismiss: () => void;
|
||||
}): ReactElement {
|
||||
onSave,
|
||||
}: AgentProfileEditModalProps & { onDismiss: () => void }): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const { model, state, save } = session;
|
||||
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 sheetHeader = useMemo<SheetHeader>(
|
||||
() => ({
|
||||
@@ -150,9 +153,59 @@ function AgentProfileEditModalContent({
|
||||
[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 save();
|
||||
}, [save]);
|
||||
void handleSave();
|
||||
}, [handleSave]);
|
||||
|
||||
const handleCancel = useCallback(() => {
|
||||
if (state.isSubmitting) {
|
||||
@@ -161,31 +214,170 @@ function AgentProfileEditModalContent({
|
||||
onClose();
|
||||
}, [onClose, state.isSubmitting]);
|
||||
|
||||
const handleRemove = useCallback(() => {
|
||||
if (!profile || !onRemove) {
|
||||
return;
|
||||
}
|
||||
onRemove(profile.id);
|
||||
}, [onRemove, profile]);
|
||||
|
||||
const footer = useMemo(
|
||||
() => (
|
||||
<View style={styles.footer}>
|
||||
<View style={styles.footerStart}>
|
||||
{mode === "edit" && profile && onRemove ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onPress={handleRemove}
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
visible={visible}
|
||||
header={sheetHeader}
|
||||
onClose={handleCancel}
|
||||
onDismiss={onDismiss}
|
||||
desktopMaxWidth={520}
|
||||
testID="agent-profile-edit-modal"
|
||||
>
|
||||
<View style={styles.body}>
|
||||
<View style={styles.nameRow}>
|
||||
<View style={styles.iconField}>
|
||||
<AgentProfileAppearanceField
|
||||
label={t("settings.host.agentProfiles.iconLabel")}
|
||||
icon={state.icon}
|
||||
color={state.color}
|
||||
onChange={handleAppearanceChange}
|
||||
disabled={state.isSubmitting}
|
||||
testID="agent-profile-modal-remove-button"
|
||||
size={controlSize}
|
||||
testID="agent-profile-icon-field"
|
||||
triggerTestID="agent-profile-icon-trigger"
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.nameField}>
|
||||
<Field
|
||||
label={t("settings.host.agentProfiles.nameLabel")}
|
||||
testID="agent-profile-name-field"
|
||||
>
|
||||
{t("settings.host.agentProfiles.remove")}
|
||||
</Button>
|
||||
) : null}
|
||||
<FormTextInput
|
||||
initialValue={seed?.name ?? profile?.name ?? ""}
|
||||
onChangeText={model.setName}
|
||||
placeholder={t("settings.host.agentProfiles.namePlaceholder")}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
editable={!state.isSubmitting}
|
||||
size={controlSize}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.nameLabel")}
|
||||
testID="agent-profile-name-input"
|
||||
/>
|
||||
</Field>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.footerEnd}>
|
||||
|
||||
<SelectField
|
||||
label={t("settings.host.agentProfiles.providerLabel")}
|
||||
value={state.provider || null}
|
||||
selectedDisplay={state.providerDisplay}
|
||||
options={providerOptions}
|
||||
onChange={handleProviderChange}
|
||||
placeholder={t("settings.host.agentProfiles.providerPlaceholder")}
|
||||
emptyText={t("settings.host.agentProfiles.noProviders")}
|
||||
loading={state.catalogResolution !== "complete"}
|
||||
disabled={state.isSubmitting}
|
||||
searchable={providerOptions.length > 6}
|
||||
title={t("settings.host.agentProfiles.providerLabel")}
|
||||
size={controlSize}
|
||||
testID="agent-profile-provider-field"
|
||||
triggerTestID="agent-profile-provider-trigger"
|
||||
/>
|
||||
|
||||
{state.disclosure.showModelField ? (
|
||||
<SelectField
|
||||
label={t("settings.host.agentProfiles.modelLabel")}
|
||||
value={state.modelId || UNSET_VALUE}
|
||||
selectedDisplay={state.modelDisplay}
|
||||
options={modelOptions}
|
||||
onChange={handleModelChange}
|
||||
placeholder={t("settings.host.agentProfiles.modelLabel")}
|
||||
emptyText={t("settings.host.agentProfiles.noModels")}
|
||||
disabled={state.isSubmitting}
|
||||
searchable={modelOptions.length > 6}
|
||||
title={t("settings.host.agentProfiles.modelLabel")}
|
||||
size={controlSize}
|
||||
testID="agent-profile-model-field"
|
||||
triggerTestID="agent-profile-model-trigger"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{state.disclosure.showModeField ? (
|
||||
<SelectField
|
||||
label={t("settings.host.agentProfiles.modeLabel")}
|
||||
value={state.modeId || UNSET_VALUE}
|
||||
selectedDisplay={state.modeDisplay}
|
||||
options={modeOptions}
|
||||
onChange={handleModeChange}
|
||||
placeholder={t("settings.host.agentProfiles.modeLabel")}
|
||||
emptyText={t("settings.host.agentProfiles.noModes")}
|
||||
disabled={state.isSubmitting}
|
||||
searchable={modeOptions.length > 6}
|
||||
title={t("settings.host.agentProfiles.modeLabel")}
|
||||
size={controlSize}
|
||||
testID="agent-profile-mode-field"
|
||||
triggerTestID="agent-profile-mode-trigger"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{state.disclosure.showThinkingField ? (
|
||||
<SelectField
|
||||
label={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
value={state.thinkingOptionId || UNSET_VALUE}
|
||||
selectedDisplay={state.thinkingDisplay}
|
||||
options={thinkingOptions}
|
||||
onChange={handleThinkingChange}
|
||||
placeholder={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
emptyText={t("settings.host.agentProfiles.noThinkingOptions")}
|
||||
disabled={state.isSubmitting}
|
||||
searchable={thinkingOptions.length > 6}
|
||||
title={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
size={controlSize}
|
||||
testID="agent-profile-thinking-field"
|
||||
triggerTestID="agent-profile-thinking-trigger"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{state.disclosure.showControlsField ? (
|
||||
<Field
|
||||
label={t("settings.host.agentProfiles.featuresLabel")}
|
||||
testID="agent-profile-features-field"
|
||||
>
|
||||
<View style={styles.featureCard} testID="agent-profile-features-card">
|
||||
{state.controls.map((control, index) => (
|
||||
<AgentProfileControlRow
|
||||
key={control.key}
|
||||
control={control}
|
||||
options={state.controlOptions}
|
||||
isFirst={index === 0}
|
||||
disabled={state.isSubmitting}
|
||||
size={controlSize}
|
||||
model={model}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</Field>
|
||||
) : null}
|
||||
|
||||
<Field
|
||||
label={t("settings.host.agentProfiles.notesLabel")}
|
||||
hint={t("settings.host.agentProfiles.notesHint")}
|
||||
testID="agent-profile-notes-field"
|
||||
>
|
||||
<FormTextInput
|
||||
initialValue={profile?.notes ?? ""}
|
||||
onChangeText={model.setNotes}
|
||||
placeholder={t("settings.host.agentProfiles.notesPlaceholder")}
|
||||
multiline
|
||||
numberOfLines={4}
|
||||
style={styles.notesInput}
|
||||
editable={!state.isSubmitting}
|
||||
size={controlSize}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.notesLabel")}
|
||||
testID="agent-profile-notes-input"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
{state.submitError ? (
|
||||
<Text style={styles.submitError} testID="agent-profile-submit-error">
|
||||
{state.submitError}
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
style={styles.actionButton}
|
||||
onPress={handleCancel}
|
||||
disabled={state.isSubmitting}
|
||||
testID="agent-profile-cancel-button"
|
||||
@@ -194,65 +386,177 @@ function AgentProfileEditModalContent({
|
||||
</Button>
|
||||
<Button
|
||||
variant="default"
|
||||
style={styles.actionButton}
|
||||
onPress={handleSavePress}
|
||||
disabled={!state.canSubmit}
|
||||
loading={state.isSubmitting}
|
||||
testID="agent-profile-save-button"
|
||||
>
|
||||
{t("settings.host.agentProfiles.save")}
|
||||
{state.isSubmitting
|
||||
? t("settings.host.agentProfiles.saving")
|
||||
: t("settings.host.agentProfiles.save")}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
),
|
||||
[
|
||||
handleCancel,
|
||||
handleRemove,
|
||||
handleSavePress,
|
||||
mode,
|
||||
onRemove,
|
||||
profile,
|
||||
state.canSubmit,
|
||||
state.isSubmitting,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
visible={visible}
|
||||
header={sheetHeader}
|
||||
footer={footer}
|
||||
onClose={handleCancel}
|
||||
onDismiss={onDismiss}
|
||||
desktopMaxWidth={500}
|
||||
testID="agent-profile-edit-modal"
|
||||
>
|
||||
<AgentProfileFormFields
|
||||
serverId={serverId}
|
||||
model={model}
|
||||
state={state}
|
||||
collapsibleDefaults={collapsibleDefaults ?? mode === "create"}
|
||||
/>
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentProfileControlRow({
|
||||
control,
|
||||
options,
|
||||
isFirst,
|
||||
disabled,
|
||||
size,
|
||||
model,
|
||||
}: {
|
||||
control: AgentOptionControl;
|
||||
options: ProviderOptions;
|
||||
isFirst: boolean;
|
||||
disabled: boolean;
|
||||
size: ControlSize;
|
||||
model: AgentProfileFormModel;
|
||||
}): ReactElement {
|
||||
const rowStyle = useMemo(
|
||||
() => [styles.featureRow, isFirst ? null : styles.featureRowBorder],
|
||||
[isFirst],
|
||||
);
|
||||
const handleToggle = useCallback(
|
||||
(value: boolean) => model.setOption(control.key, value),
|
||||
[control.key, model],
|
||||
);
|
||||
const handleSelect = useCallback(
|
||||
(value: string) => model.setOption(control.key, value),
|
||||
[control.key, model],
|
||||
);
|
||||
const selectOptions = useMemo<SelectFieldOption<string>[]>(
|
||||
() =>
|
||||
control.type === "select"
|
||||
? control.choices.map((choice) => ({
|
||||
id: choice.value,
|
||||
value: choice.value,
|
||||
label: choice.label,
|
||||
...(choice.description ? { description: choice.description } : {}),
|
||||
testID: `agent-profile-feature-option-${control.key}-${choice.value}`,
|
||||
}))
|
||||
: [],
|
||||
[control],
|
||||
);
|
||||
const selectedValue = control.type === "select" ? readSelectOption(control, options) : null;
|
||||
const selectedDisplay = useMemo<SelectFieldDisplay | null>(() => {
|
||||
if (control.type !== "select" || !selectedValue) {
|
||||
return null;
|
||||
}
|
||||
const choice = control.choices.find((candidate) => candidate.value === selectedValue);
|
||||
return { label: choice?.label ?? selectedValue };
|
||||
}, [control, selectedValue]);
|
||||
|
||||
if (control.type === "select") {
|
||||
return (
|
||||
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
|
||||
<SelectField
|
||||
label={control.label}
|
||||
value={selectedValue}
|
||||
selectedDisplay={selectedDisplay}
|
||||
options={selectOptions}
|
||||
onChange={handleSelect}
|
||||
placeholder={control.label}
|
||||
emptyText={control.label}
|
||||
disabled={disabled}
|
||||
{...(control.description ? { hint: control.description } : {})}
|
||||
title={control.label}
|
||||
size={size}
|
||||
testID={`agent-profile-feature-field-${control.key}`}
|
||||
triggerTestID={`agent-profile-feature-trigger-${control.key}`}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={rowStyle} testID={`agent-profile-feature-row-${control.key}`}>
|
||||
<View style={styles.featureMeta}>
|
||||
<Text style={styles.featureLabel} numberOfLines={1}>
|
||||
{control.label}
|
||||
</Text>
|
||||
{control.description ? (
|
||||
<Text style={styles.featureDescription} numberOfLines={2}>
|
||||
{control.description}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Switch
|
||||
value={readToggleOption(control, options)}
|
||||
onValueChange={handleToggle}
|
||||
disabled={disabled}
|
||||
accessibilityLabel={control.label}
|
||||
testID={`agent-profile-feature-switch-${control.key}`}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
footer: {
|
||||
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: {
|
||||
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[2],
|
||||
gap: theme.spacing[3],
|
||||
paddingVertical: theme.spacing[3],
|
||||
},
|
||||
footerStart: {
|
||||
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: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
marginTop: theme.spacing[2],
|
||||
},
|
||||
footerEnd: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
actionButton: {
|
||||
flex: 1,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,567 +0,0 @@
|
||||
import { useCallback, useMemo, useRef, type ReactElement, type ReactNode } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type {
|
||||
AgentOptionControl,
|
||||
AgentProvider,
|
||||
ProviderOptions,
|
||||
} from "@getpaseo/protocol/agent-types";
|
||||
import { readSelectOption, readToggleOption } from "@/agent-controls/option-controls";
|
||||
import { CombinedModelSelector } from "@/components/combined-model-selector";
|
||||
import {
|
||||
SettingsCard,
|
||||
SettingsCollapsibleRow,
|
||||
SettingsSelect,
|
||||
SettingsSwitch,
|
||||
} from "@/components/settings";
|
||||
import type { ControlSize } from "@/components/ui/control-geometry";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import {
|
||||
SelectField,
|
||||
SelectFieldTrigger,
|
||||
type SelectFieldDisplay,
|
||||
type SelectFieldOption,
|
||||
} from "@/components/ui/select-field";
|
||||
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
|
||||
import { buildSelectableProviderSelectorProviders } from "@/provider-selection/provider-selection";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
|
||||
import type {
|
||||
AgentProfileFormModel,
|
||||
AgentProfileFormOption,
|
||||
AgentProfileFormState,
|
||||
} from "../internal/profile-form-model";
|
||||
import { AgentProfileIconButton } from "./agent-profile-appearance-field";
|
||||
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
|
||||
const UNSET_VALUE = "";
|
||||
|
||||
function toSelectOptions(options: AgentProfileFormOption[]): SelectFieldOption<string>[] {
|
||||
return options.map((option) => ({
|
||||
id: option.id,
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
...(option.description ? { description: option.description } : {}),
|
||||
testID: option.testID,
|
||||
}));
|
||||
}
|
||||
|
||||
function canUseSegmentedThinking(options: readonly AgentProfileFormOption[]): boolean {
|
||||
return (
|
||||
options.length >= 2 &&
|
||||
options.length <= 4 &&
|
||||
options.every((option) => option.label.trim().length <= 12)
|
||||
);
|
||||
}
|
||||
|
||||
export interface AgentProfileFormFieldsProps {
|
||||
serverId: string;
|
||||
model: AgentProfileFormModel;
|
||||
state: AgentProfileFormState;
|
||||
controlSize?: ControlSize;
|
||||
/** Embeds the icon+color picker beside the Name input (used in sheets; drawer places it in its hero). */
|
||||
showInlineIcon?: boolean;
|
||||
/** Collapses Mode, Thinking, Notes, and Options behind a SettingsCollapsibleRow until expanded. */
|
||||
collapsibleDefaults?: boolean;
|
||||
}
|
||||
|
||||
function ThinkingField({
|
||||
state,
|
||||
controlSize,
|
||||
onSelectChange,
|
||||
onSegmentChange,
|
||||
}: {
|
||||
state: AgentProfileFormState;
|
||||
controlSize: ControlSize;
|
||||
onSelectChange: (value: string, display: SelectFieldDisplay) => void;
|
||||
onSegmentChange: (value: string) => void;
|
||||
}): ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
const thinkingOptions = useMemo(
|
||||
() => toSelectOptions(state.thinkingOptions),
|
||||
[state.thinkingOptions],
|
||||
);
|
||||
const segmentedThinkingOptions = useMemo<SegmentedControlOption<string>[]>(
|
||||
() =>
|
||||
state.thinkingOptions.map((option) => ({
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
disabled: state.isSubmitting,
|
||||
testID: option.testID,
|
||||
})),
|
||||
[state.isSubmitting, state.thinkingOptions],
|
||||
);
|
||||
if (!state.disclosure.showThinkingField) {
|
||||
return null;
|
||||
}
|
||||
if (canUseSegmentedThinking(state.thinkingOptions)) {
|
||||
return (
|
||||
<Field
|
||||
label={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
testID="agent-profile-thinking-field"
|
||||
>
|
||||
<SegmentedControl
|
||||
options={segmentedThinkingOptions}
|
||||
value={state.thinkingOptionId || null}
|
||||
onValueChange={onSegmentChange}
|
||||
size={controlSize}
|
||||
testID="agent-profile-thinking-trigger"
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<SelectField
|
||||
label={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
value={state.thinkingOptionId || UNSET_VALUE}
|
||||
selectedDisplay={state.thinkingDisplay}
|
||||
options={thinkingOptions}
|
||||
onChange={onSelectChange}
|
||||
placeholder={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
emptyText={t("settings.host.agentProfiles.noThinkingOptions")}
|
||||
disabled={state.isSubmitting}
|
||||
searchable={thinkingOptions.length > 6}
|
||||
title={t("settings.host.agentProfiles.thinkingLabel")}
|
||||
size={controlSize}
|
||||
testID="agent-profile-thinking-field"
|
||||
triggerTestID="agent-profile-thinking-trigger"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentProfileControlRow({
|
||||
control,
|
||||
options,
|
||||
disabled,
|
||||
model,
|
||||
}: {
|
||||
control: AgentOptionControl;
|
||||
options: ProviderOptions;
|
||||
disabled: boolean;
|
||||
model: AgentProfileFormModel;
|
||||
}): ReactElement {
|
||||
const handleToggle = useCallback(
|
||||
(value: boolean) => model.setOption(control.key, value),
|
||||
[control.key, model],
|
||||
);
|
||||
const handleSelect = useCallback(
|
||||
(value: string) => model.setOption(control.key, value),
|
||||
[control.key, model],
|
||||
);
|
||||
const selectOptions = useMemo(
|
||||
() =>
|
||||
control.type === "select"
|
||||
? control.choices.map((choice) => ({ label: choice.label, value: choice.value }))
|
||||
: [],
|
||||
[control],
|
||||
);
|
||||
|
||||
if (control.type === "select") {
|
||||
const selectedValue = readSelectOption(control, options) ?? control.choices[0]?.value ?? "";
|
||||
return (
|
||||
<SettingsSelect
|
||||
label={control.label}
|
||||
hint={control.description}
|
||||
value={selectedValue}
|
||||
options={selectOptions}
|
||||
onValueChange={handleSelect}
|
||||
disabled={disabled}
|
||||
testID={`agent-profile-feature-row-${control.key}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsSwitch
|
||||
label={control.label}
|
||||
hint={control.description}
|
||||
value={readToggleOption(control, options)}
|
||||
onValueChange={handleToggle}
|
||||
disabled={disabled}
|
||||
testID={`agent-profile-feature-row-${control.key}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentProfileAdvancedFields({
|
||||
model,
|
||||
state,
|
||||
controlSize,
|
||||
onModeChange,
|
||||
onThinkingSelectChange,
|
||||
onThinkingSegmentChange,
|
||||
}: {
|
||||
model: AgentProfileFormModel;
|
||||
state: AgentProfileFormState;
|
||||
controlSize: ControlSize;
|
||||
onModeChange: (value: string, display: SelectFieldDisplay) => void;
|
||||
onThinkingSelectChange: (value: string, display: SelectFieldDisplay) => void;
|
||||
onThinkingSegmentChange: (value: string) => void;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const modeOptions = useMemo(() => toSelectOptions(state.modeOptions), [state.modeOptions]);
|
||||
const providerOptionsTitle = state.providerDisplay?.label
|
||||
? t("settings.host.agentProfiles.providerOptionsLabel", {
|
||||
provider: state.providerDisplay.label,
|
||||
})
|
||||
: t("settings.host.agentProfiles.featuresLabel");
|
||||
const optionsPendingSpinner = useMemo(
|
||||
() =>
|
||||
state.controlsPending ? (
|
||||
<ThemedLoadingSpinner size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
) : null,
|
||||
[state.controlsPending],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{state.disclosure.showModeField ? (
|
||||
<SelectField
|
||||
label={t("settings.host.agentProfiles.modeLabel")}
|
||||
value={state.modeId || UNSET_VALUE}
|
||||
selectedDisplay={state.modeDisplay}
|
||||
options={modeOptions}
|
||||
onChange={onModeChange}
|
||||
placeholder={t("settings.host.agentProfiles.modeLabel")}
|
||||
emptyText={t("settings.host.agentProfiles.noModes")}
|
||||
disabled={state.isSubmitting}
|
||||
searchable={modeOptions.length > 6}
|
||||
title={t("settings.host.agentProfiles.modeLabel")}
|
||||
size={controlSize}
|
||||
testID="agent-profile-mode-field"
|
||||
triggerTestID="agent-profile-mode-trigger"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<ThinkingField
|
||||
state={state}
|
||||
controlSize={controlSize}
|
||||
onSelectChange={onThinkingSelectChange}
|
||||
onSegmentChange={onThinkingSegmentChange}
|
||||
/>
|
||||
|
||||
<Field
|
||||
label={t("settings.host.agentProfiles.notesLabel")}
|
||||
hint={t("settings.host.agentProfiles.notesHint")}
|
||||
testID="agent-profile-notes-field"
|
||||
>
|
||||
<FormTextInput
|
||||
initialValue={state.notes}
|
||||
onChangeText={model.setNotes}
|
||||
placeholder={t("settings.host.agentProfiles.notesPlaceholder")}
|
||||
multiline
|
||||
numberOfLines={3}
|
||||
style={styles.notesInput}
|
||||
editable={!state.isSubmitting}
|
||||
size={controlSize}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.notesLabel")}
|
||||
testID="agent-profile-notes-input"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
{state.disclosure.showControlsField ? (
|
||||
<Field
|
||||
label={providerOptionsTitle}
|
||||
trailing={optionsPendingSpinner}
|
||||
testID="agent-profile-features-field"
|
||||
>
|
||||
<View style={state.controlsPending ? styles.featureCardPending : undefined}>
|
||||
<SettingsCard testID="agent-profile-features-card">
|
||||
{state.controls.map((control) => (
|
||||
<AgentProfileControlRow
|
||||
key={control.key}
|
||||
control={control}
|
||||
options={state.controlOptions}
|
||||
disabled={state.isSubmitting || state.controlsPending}
|
||||
model={model}
|
||||
/>
|
||||
))}
|
||||
</SettingsCard>
|
||||
</View>
|
||||
</Field>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared profile form body used by both the desktop inspector drawer and the modal sheet.
|
||||
*
|
||||
* Layout order keeps inputs above async provider options: Model first (using Paseo's
|
||||
* shared CombinedModelSelector), Name + icon second, Mode & Thinking, "When to use",
|
||||
* and provider options last so loading options never shift controls above them.
|
||||
*/
|
||||
export function AgentProfileFormFields({
|
||||
serverId,
|
||||
model,
|
||||
state,
|
||||
controlSize = "md",
|
||||
showInlineIcon = true,
|
||||
collapsibleDefaults = false,
|
||||
}: AgentProfileFormFieldsProps): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const nameInputRef = useRef<EditingTextInputHandle>(null);
|
||||
const { entries, isLoading, isFetching, isRefreshing, refresh } = useProvidersSnapshot(serverId, {
|
||||
cwd: null,
|
||||
});
|
||||
|
||||
const modelSelectorProviders = useMemo(
|
||||
() =>
|
||||
buildSelectableProviderSelectorProviders(entries, {
|
||||
selectedProvider: state.provider || null,
|
||||
}),
|
||||
[entries, state.provider],
|
||||
);
|
||||
|
||||
const modelTriggerLeading = useMemo(
|
||||
() =>
|
||||
state.provider ? (
|
||||
<AgentProfileGlyph provider={state.provider} serverId={serverId} size={ICON_SIZE.sm} />
|
||||
) : null,
|
||||
[serverId, state.provider],
|
||||
);
|
||||
|
||||
const renderModelTrigger = useCallback(
|
||||
({
|
||||
selectedModelLabel,
|
||||
disabled,
|
||||
isOpen,
|
||||
hovered,
|
||||
pressed,
|
||||
}: {
|
||||
selectedModelLabel: string;
|
||||
onPress: () => void;
|
||||
disabled: boolean;
|
||||
isOpen: boolean;
|
||||
hovered: boolean;
|
||||
pressed: boolean;
|
||||
}): ReactNode => {
|
||||
const displayLabel =
|
||||
state.modelDisplay?.label ?? state.providerDisplay?.label ?? selectedModelLabel;
|
||||
return (
|
||||
<SelectFieldTrigger
|
||||
label={displayLabel}
|
||||
isPlaceholder={!state.provider}
|
||||
placeholder={t("settings.host.agentProfiles.chooseModelPlaceholder")}
|
||||
leading={modelTriggerLeading}
|
||||
disabled={disabled}
|
||||
active={hovered || pressed || isOpen}
|
||||
size={controlSize}
|
||||
testID="agent-profile-model-trigger"
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
controlSize,
|
||||
modelTriggerLeading,
|
||||
state.modelDisplay?.label,
|
||||
state.provider,
|
||||
state.providerDisplay?.label,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
const handleAppearanceChange = useCallback(
|
||||
(value: { icon: string; color: string }) => model.setAppearance(value),
|
||||
[model],
|
||||
);
|
||||
|
||||
const handleModelSelect = useCallback(
|
||||
(provider: AgentProvider, modelId: string) => {
|
||||
const previousName = model.getState().name;
|
||||
const entry = entries?.find((candidate) => candidate.provider === provider);
|
||||
const modelDef = entry?.models?.find((candidate) => candidate.id === modelId);
|
||||
model.setProviderModel(provider, modelId, {
|
||||
provider: { label: entry?.label ?? provider },
|
||||
model: modelId ? { label: modelDef?.label ?? modelId } : null,
|
||||
});
|
||||
const suggestedName = model.getState().name;
|
||||
if (suggestedName !== previousName) {
|
||||
nameInputRef.current?.replaceText(suggestedName);
|
||||
}
|
||||
},
|
||||
[entries, model],
|
||||
);
|
||||
|
||||
const handleRetryProvider = useCallback(
|
||||
(provider: AgentProvider) => {
|
||||
void refresh([provider]);
|
||||
},
|
||||
[refresh],
|
||||
);
|
||||
|
||||
const handleModeChange = useCallback(
|
||||
(value: string, display: SelectFieldDisplay) => model.setMode(value, value ? display : null),
|
||||
[model],
|
||||
);
|
||||
|
||||
const handleThinkingSelectChange = useCallback(
|
||||
(value: string, display: SelectFieldDisplay) =>
|
||||
model.setThinking(value, value ? display : null),
|
||||
[model],
|
||||
);
|
||||
|
||||
const handleThinkingSegmentChange = useCallback(
|
||||
(value: string) => {
|
||||
const option = state.thinkingOptions.find((candidate) => candidate.value === value);
|
||||
model.setThinking(value, option ? { label: option.label } : null);
|
||||
},
|
||||
[model, state.thinkingOptions],
|
||||
);
|
||||
|
||||
const hasRuntimeDefaults =
|
||||
state.disclosure.showModeField ||
|
||||
state.disclosure.showThinkingField ||
|
||||
state.disclosure.showControlsField;
|
||||
|
||||
const defaultsSummary = useMemo(() => {
|
||||
const parts: string[] = [];
|
||||
if (state.modeDisplay?.label) {
|
||||
parts.push(state.modeDisplay.label);
|
||||
}
|
||||
if (state.thinkingDisplay?.label) {
|
||||
parts.push(state.thinkingDisplay.label);
|
||||
}
|
||||
if (state.controls.length > 0) {
|
||||
parts.push(
|
||||
state.controls.length === 1
|
||||
? t("settings.host.agentProfiles.featureCountOne", { count: state.controls.length })
|
||||
: t("settings.host.agentProfiles.featureCount", { count: state.controls.length }),
|
||||
);
|
||||
}
|
||||
if (!state.notes.trim() && hasRuntimeDefaults) {
|
||||
parts.push(t("settings.host.agentProfiles.addRoutingNoteShort"));
|
||||
}
|
||||
return parts.join(" · ");
|
||||
}, [
|
||||
hasRuntimeDefaults,
|
||||
state.controls.length,
|
||||
state.modeDisplay?.label,
|
||||
state.notes,
|
||||
state.thinkingDisplay?.label,
|
||||
t,
|
||||
]);
|
||||
|
||||
const collapsibleLabel = hasRuntimeDefaults
|
||||
? t("settings.host.agentProfiles.customizeSettings")
|
||||
: t("settings.host.agentProfiles.addRoutingNoteShort");
|
||||
|
||||
const advancedFields = (
|
||||
<AgentProfileAdvancedFields
|
||||
model={model}
|
||||
state={state}
|
||||
controlSize={controlSize}
|
||||
onModeChange={handleModeChange}
|
||||
onThinkingSelectChange={handleThinkingSelectChange}
|
||||
onThinkingSegmentChange={handleThinkingSegmentChange}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={styles.body}>
|
||||
<Field label={t("settings.host.agentProfiles.modelLabel")} testID="agent-profile-model-field">
|
||||
<CombinedModelSelector
|
||||
providers={modelSelectorProviders}
|
||||
selectedProvider={state.provider}
|
||||
selectedModel={state.modelId}
|
||||
onSelect={handleModelSelect}
|
||||
isLoading={isLoading || isFetching}
|
||||
renderTrigger={renderModelTrigger}
|
||||
triggerFill
|
||||
serverId={serverId}
|
||||
disabled={state.isSubmitting}
|
||||
onRetryProvider={handleRetryProvider}
|
||||
isRetryingProvider={isRefreshing}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field label={t("settings.host.agentProfiles.nameLabel")} testID="agent-profile-name-field">
|
||||
<View style={styles.nameRow}>
|
||||
{showInlineIcon ? (
|
||||
<AgentProfileIconButton
|
||||
label={t("settings.host.agentProfiles.iconLabel")}
|
||||
icon={state.icon}
|
||||
color={state.color}
|
||||
provider={state.provider || undefined}
|
||||
serverId={serverId}
|
||||
onChange={handleAppearanceChange}
|
||||
disabled={state.isSubmitting}
|
||||
size={controlSize}
|
||||
triggerTestID="agent-profile-icon-trigger"
|
||||
/>
|
||||
) : null}
|
||||
<View style={styles.nameInputWrap}>
|
||||
<FormTextInput
|
||||
ref={nameInputRef}
|
||||
initialValue={state.name}
|
||||
onChangeText={model.setName}
|
||||
placeholder={t("settings.host.agentProfiles.namePlaceholder")}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
editable={!state.isSubmitting}
|
||||
size={controlSize}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.nameLabel")}
|
||||
testID="agent-profile-name-input"
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</Field>
|
||||
|
||||
{collapsibleDefaults ? (
|
||||
<SettingsCard>
|
||||
<SettingsCollapsibleRow
|
||||
label={collapsibleLabel}
|
||||
summary={defaultsSummary || undefined}
|
||||
testID="agent-profile-customize"
|
||||
>
|
||||
<View style={styles.collapsibleFields}>{advancedFields}</View>
|
||||
</SettingsCollapsibleRow>
|
||||
</SettingsCard>
|
||||
) : (
|
||||
advancedFields
|
||||
)}
|
||||
|
||||
{state.submitError ? (
|
||||
<Text style={styles.submitError} testID="agent-profile-submit-error">
|
||||
{state.submitError}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
body: {
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
nameRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
nameInputWrap: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
collapsibleFields: {
|
||||
padding: theme.spacing[4],
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
featureCardPending: {
|
||||
opacity: theme.opacity[50],
|
||||
},
|
||||
notesInput: {
|
||||
minHeight: theme.spacing[20],
|
||||
textAlignVertical: "top",
|
||||
},
|
||||
submitError: {
|
||||
color: theme.colors.palette.red[300],
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
}));
|
||||
@@ -1,342 +1,57 @@
|
||||
import { useCallback, useMemo, useState, type ReactElement } from "react";
|
||||
import { useCallback, useMemo, type ReactElement } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
ArrowUpToLine,
|
||||
ChevronRight,
|
||||
Copy,
|
||||
GripVertical,
|
||||
MoreVertical,
|
||||
Pencil,
|
||||
Trash2,
|
||||
} from "lucide-react-native";
|
||||
import { ArrowDown, ArrowUp, FileText, 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 { 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 { Button } from "@/components/ui/button";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { AgentProfileGlyph } from "../internal/agent-profile-glyph";
|
||||
import { buildAgentProfileRosterSummary } from "../internal/profile-summary";
|
||||
import { buildAgentProfileTags } 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 ThemedArrowUpToLine = withUnistyles(ArrowUpToLine);
|
||||
const ThemedPencil = withUnistyles(Pencil);
|
||||
const ThemedTrash2 = withUnistyles(Trash2);
|
||||
const ThemedFileText = withUnistyles(FileText);
|
||||
|
||||
const destructiveIconColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||
const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
const destructiveColorMapping = (theme: Theme) => ({ color: theme.colors.destructive });
|
||||
|
||||
const editMenuIcon = <ThemedPencil size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||
const duplicateMenuIcon = <ThemedCopy size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||
const moveUpMenuIcon = <ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||
const moveDownMenuIcon = <ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />;
|
||||
const moveTopMenuIcon = (
|
||||
<ThemedArrowUpToLine size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
);
|
||||
const removeMenuIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveIconColorMapping} />;
|
||||
|
||||
const HIDDEN_FROM_ASSISTIVE_TECH = {
|
||||
accessibilityElementsHidden: true,
|
||||
importantForAccessibility: "no-hide-descendants",
|
||||
"aria-hidden": true,
|
||||
} as const;
|
||||
const moveUpIcon = <ThemedArrowUp size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
|
||||
const moveDownIcon = <ThemedArrowDown size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
|
||||
const editIcon = <ThemedPencil size={ICON_SIZE.sm} uniProps={mutedColorMapping} />;
|
||||
const removeIcon = <ThemedTrash2 size={ICON_SIZE.sm} uniProps={destructiveColorMapping} />;
|
||||
|
||||
export interface AgentProfileRowProps {
|
||||
serverId: string;
|
||||
profile: AgentProfile;
|
||||
entries: readonly ProviderSnapshotEntry[] | undefined;
|
||||
isFirst: boolean;
|
||||
isLast: boolean;
|
||||
selected?: boolean;
|
||||
dragging?: boolean;
|
||||
/** Stacked layout when narrow or on compact form factors. */
|
||||
compactLayout?: boolean;
|
||||
/** Hides the drag handle when showing filtered search results while preserving the rail. */
|
||||
reorderable?: boolean;
|
||||
onEdit: (id: string) => void;
|
||||
onDuplicate: (id: string) => void;
|
||||
onRemove: (id: string) => void;
|
||||
onMoveUp: (id: string) => void;
|
||||
onMoveDown: (id: string) => void;
|
||||
onMoveToTop: (id: string) => void;
|
||||
}
|
||||
|
||||
function AgentProfileRowMenu({
|
||||
profileId,
|
||||
profileName,
|
||||
isFirst,
|
||||
isLast,
|
||||
reorderable,
|
||||
menuProps,
|
||||
onEdit,
|
||||
onDuplicate,
|
||||
onMoveUp,
|
||||
onMoveDown,
|
||||
onMoveToTop,
|
||||
onRemove,
|
||||
}: {
|
||||
profileId: string;
|
||||
profileName: string;
|
||||
isFirst: boolean;
|
||||
isLast: boolean;
|
||||
reorderable: boolean;
|
||||
menuProps: { open: boolean; onOpenChange: (open: boolean) => void };
|
||||
onEdit: () => void;
|
||||
onDuplicate: () => void;
|
||||
onMoveUp: () => void;
|
||||
onMoveDown: () => void;
|
||||
onMoveToTop: () => void;
|
||||
onRemove: () => void;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const showReorderItems = reorderable && (!isFirst || !isLast);
|
||||
return (
|
||||
<DropdownMenu {...menuProps} compactMode="sheet">
|
||||
<ToolbarButton
|
||||
kind="menu"
|
||||
label={t("settings.host.agentProfiles.profileActions", { name: profileName })}
|
||||
testID={`agent-profile-menu-${profileId}`}
|
||||
>
|
||||
<ThemedMoreVertical size={ICON_SIZE.sm} uniProps={mutedIconColorMapping} />
|
||||
</ToolbarButton>
|
||||
<DropdownMenuContent side="bottom" align="end" width={180}>
|
||||
<DropdownMenuItem
|
||||
leading={editMenuIcon}
|
||||
onSelect={onEdit}
|
||||
testID={`agent-profile-edit-${profileId}`}
|
||||
>
|
||||
{t("settings.host.agentProfiles.editProfile")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
leading={duplicateMenuIcon}
|
||||
onSelect={onDuplicate}
|
||||
testID={`agent-profile-duplicate-${profileId}`}
|
||||
>
|
||||
{t("settings.host.agentProfiles.duplicate")}
|
||||
</DropdownMenuItem>
|
||||
{showReorderItems ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
{!isFirst ? (
|
||||
<DropdownMenuItem
|
||||
leading={moveUpMenuIcon}
|
||||
onSelect={onMoveUp}
|
||||
testID={`agent-profile-move-up-${profileId}`}
|
||||
>
|
||||
{t("settings.host.agentProfiles.moveUp")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{!isLast ? (
|
||||
<DropdownMenuItem
|
||||
leading={moveDownMenuIcon}
|
||||
onSelect={onMoveDown}
|
||||
testID={`agent-profile-move-down-${profileId}`}
|
||||
>
|
||||
{t("settings.host.agentProfiles.moveDown")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{!isFirst ? (
|
||||
<DropdownMenuItem
|
||||
leading={moveTopMenuIcon}
|
||||
onSelect={onMoveToTop}
|
||||
testID={`agent-profile-move-top-${profileId}`}
|
||||
>
|
||||
{t("settings.host.agentProfiles.moveToTop")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
destructive
|
||||
leading={removeMenuIcon}
|
||||
onSelect={onRemove}
|
||||
testID={`agent-profile-remove-${profileId}`}
|
||||
>
|
||||
{t("settings.host.agentProfiles.remove")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentProfileRowContent({
|
||||
serverId,
|
||||
profile,
|
||||
modelLabel,
|
||||
providerLabel,
|
||||
runtimeSubline,
|
||||
fullSummary,
|
||||
isStacked,
|
||||
}: {
|
||||
serverId: string;
|
||||
profile: AgentProfile;
|
||||
modelLabel: string | null;
|
||||
providerLabel: string;
|
||||
runtimeSubline: string;
|
||||
fullSummary: string;
|
||||
isStacked: boolean;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const iconTile = (
|
||||
<View style={styles.iconTile}>
|
||||
<AgentProfileGlyph
|
||||
icon={profile.icon}
|
||||
color={profile.color}
|
||||
provider={profile.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.sm}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
|
||||
if (isStacked) {
|
||||
return (
|
||||
<View style={[styles.stackedMain, styles.passThrough]}>
|
||||
{iconTile}
|
||||
<View style={styles.stackedContent}>
|
||||
<Text style={styles.nameText} numberOfLines={1}>
|
||||
{profile.name}
|
||||
</Text>
|
||||
<View style={styles.stackedSpecLine}>
|
||||
<AgentProfileGlyph
|
||||
provider={profile.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.xs}
|
||||
/>
|
||||
<Text style={styles.stackedSpecText} numberOfLines={1}>
|
||||
{fullSummary}
|
||||
</Text>
|
||||
</View>
|
||||
{profile.notes ? (
|
||||
<Text
|
||||
style={styles.stackedNotesText}
|
||||
numberOfLines={2}
|
||||
testID={`agent-profile-notes-${profile.id}`}
|
||||
>
|
||||
{profile.notes}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={[styles.columns, styles.passThrough]}>
|
||||
<View style={styles.colProfile}>
|
||||
{iconTile}
|
||||
<Text style={styles.nameText} numberOfLines={1}>
|
||||
{profile.name}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.colRuntime}>
|
||||
<View style={styles.modelLine}>
|
||||
<AgentProfileGlyph provider={profile.provider} serverId={serverId} size={ICON_SIZE.xs} />
|
||||
<Text style={styles.modelText} numberOfLines={1}>
|
||||
{modelLabel ?? providerLabel}
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={styles.runtimeSubtext} numberOfLines={1}>
|
||||
{runtimeSubline}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.colNotes}>
|
||||
{profile.notes ? (
|
||||
<Text
|
||||
style={styles.notesText}
|
||||
numberOfLines={2}
|
||||
testID={`agent-profile-notes-${profile.id}`}
|
||||
>
|
||||
{profile.notes}
|
||||
</Text>
|
||||
) : (
|
||||
<Text style={styles.notesEmptyText} numberOfLines={1}>
|
||||
{t("settings.host.agentProfiles.noRoutingNote")}
|
||||
</Text>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wide roster row (Profile | Model & runtime | When to use) that stacks on narrow panes.
|
||||
*
|
||||
* Follows docs/hover.md: hover lives on the outer plain View, tap lives on an
|
||||
* underlying PressHighlight, and the kebab menu's open state is lifted via
|
||||
* `useOpenKebabMenuVisibility` so losing hover never unmounts an open menu.
|
||||
*/
|
||||
export function AgentProfileRow({
|
||||
serverId,
|
||||
profile,
|
||||
entries,
|
||||
isFirst,
|
||||
isLast,
|
||||
selected = false,
|
||||
dragging = false,
|
||||
compactLayout = false,
|
||||
reorderable = true,
|
||||
onEdit,
|
||||
onDuplicate,
|
||||
onRemove,
|
||||
onMoveUp,
|
||||
onMoveDown,
|
||||
onMoveToTop,
|
||||
}: AgentProfileRowProps): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const isCompactFormFactor = useIsCompactFormFactor();
|
||||
const { finePointer, touchScreen } = usePointerCapabilities();
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
|
||||
const alwaysShowAffordances = !finePointer || touchScreen || isCompactFormFactor;
|
||||
const { showKebab, menuProps } = useOpenKebabMenuVisibility(
|
||||
isHovered || dragging || alwaysShowAffordances,
|
||||
);
|
||||
const showRowAffordances = showKebab;
|
||||
|
||||
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
|
||||
const handlePointerLeave = useCallback(() => setIsHovered(false), []);
|
||||
|
||||
const handleEdit = useCallback(() => onEdit(profile.id), [onEdit, profile.id]);
|
||||
const handleDuplicate = useCallback(() => onDuplicate(profile.id), [onDuplicate, profile.id]);
|
||||
const handleRemove = useCallback(() => onRemove(profile.id), [onRemove, profile.id]);
|
||||
const handleMoveUp = useCallback(() => onMoveUp(profile.id), [onMoveUp, profile.id]);
|
||||
const handleMoveDown = useCallback(() => onMoveDown(profile.id), [onMoveDown, profile.id]);
|
||||
const handleMoveToTop = useCallback(() => onMoveToTop(profile.id), [onMoveToTop, profile.id]);
|
||||
|
||||
const formatFeatureCount = useCallback(
|
||||
(count: number) =>
|
||||
@@ -345,276 +60,125 @@ export function AgentProfileRow({
|
||||
: t("settings.host.agentProfiles.featureCount", { count }),
|
||||
[t],
|
||||
);
|
||||
|
||||
const rosterSummary = useMemo(
|
||||
() => buildAgentProfileRosterSummary({ profile, entries, formatFeatureCount }),
|
||||
const tags = useMemo(
|
||||
() => buildAgentProfileTags({ profile, entries, formatFeatureCount }),
|
||||
[entries, formatFeatureCount, profile],
|
||||
);
|
||||
const fullSummary = useMemo(
|
||||
() => rosterSummary.allTags.map((tag) => tag.label).join(" · "),
|
||||
[rosterSummary.allTags],
|
||||
);
|
||||
const runtimeSubline = useMemo(
|
||||
() => rosterSummary.runtimeDetails.join(" · "),
|
||||
[rosterSummary.runtimeDetails],
|
||||
);
|
||||
const summary = useMemo(() => tags.map((tag) => tag.label).join(" · "), [tags]);
|
||||
|
||||
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],
|
||||
const rowStyle = useMemo(
|
||||
() => [settingsStyles.row, isFirst ? null : settingsStyles.rowBorder, styles.row],
|
||||
[isFirst],
|
||||
);
|
||||
|
||||
return (
|
||||
<View
|
||||
style={rowContainerStyle}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
testID={`agent-profile-row-${profile.id}`}
|
||||
>
|
||||
<PressHighlight
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`${profile.name}, ${fullSummary}`}
|
||||
onPress={handleEdit}
|
||||
style={styles.pressTarget}
|
||||
highlightStyle={styles.rowPressed}
|
||||
testID={`agent-profile-row-press-${profile.id}`}
|
||||
/>
|
||||
|
||||
{selected ? <View style={styles.selectedIndicator} pointerEvents="none" /> : null}
|
||||
|
||||
{reorderable ? (
|
||||
<View style={gripVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
|
||||
<DraggableListHandle
|
||||
accessibilityLabel={t("settings.host.agentProfiles.reorderProfile", {
|
||||
name: profile.name,
|
||||
})}
|
||||
style={styles.gripHandle}
|
||||
testID={`agent-profile-drag-${profile.id}`}
|
||||
>
|
||||
<ThemedGripVertical size={ICON_SIZE.sm} uniProps={extraMutedIconColorMapping} />
|
||||
</DraggableListHandle>
|
||||
<View style={rowStyle} testID={`agent-profile-row-${profile.id}`}>
|
||||
<View style={styles.rowMain}>
|
||||
<View style={styles.iconWrapper}>
|
||||
<AgentProfileGlyph icon={profile.icon} color={profile.color} size={ICON_SIZE.md} />
|
||||
</View>
|
||||
) : (
|
||||
<View style={isStacked ? styles.gripSpacerCompact : styles.gripSlot} />
|
||||
)}
|
||||
|
||||
<AgentProfileRowContent
|
||||
serverId={serverId}
|
||||
profile={profile}
|
||||
modelLabel={rosterSummary.modelLabel}
|
||||
providerLabel={rosterSummary.providerLabel}
|
||||
runtimeSubline={runtimeSubline}
|
||||
fullSummary={fullSummary}
|
||||
isStacked={isStacked}
|
||||
/>
|
||||
|
||||
<View style={styles.trailing}>
|
||||
<View style={kebabVisibilityStyle} pointerEvents={showRowAffordances ? "auto" : "none"}>
|
||||
<AgentProfileRowMenu
|
||||
profileId={profile.id}
|
||||
profileName={profile.name}
|
||||
isFirst={isFirst}
|
||||
isLast={isLast}
|
||||
reorderable={reorderable}
|
||||
menuProps={menuProps}
|
||||
onEdit={handleEdit}
|
||||
onDuplicate={handleDuplicate}
|
||||
onMoveUp={handleMoveUp}
|
||||
onMoveDown={handleMoveDown}
|
||||
onMoveToTop={handleMoveToTop}
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
</View>
|
||||
<View style={[styles.chevron, styles.passThrough]} {...HIDDEN_FROM_ASSISTIVE_TECH}>
|
||||
<ThemedChevronRight
|
||||
size={ICON_SIZE.sm}
|
||||
uniProps={isHovered || selected ? foregroundIconColorMapping : mutedIconColorMapping}
|
||||
/>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<View style={styles.titleLine}>
|
||||
<Text style={settingsStyles.rowTitle} numberOfLines={1}>
|
||||
{profile.name}
|
||||
</Text>
|
||||
<Text style={styles.summary} numberOfLines={1}>
|
||||
{summary}
|
||||
</Text>
|
||||
</View>
|
||||
{profile.notes ? (
|
||||
<View style={styles.notes}>
|
||||
<ThemedFileText size={ICON_SIZE.xs} uniProps={mutedColorMapping} />
|
||||
<Text
|
||||
style={styles.notesText}
|
||||
numberOfLines={2}
|
||||
testID={`agent-profile-notes-${profile.id}`}
|
||||
>
|
||||
{profile.notes}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.rowActions}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
leftIcon={moveUpIcon}
|
||||
onPress={handleMoveUp}
|
||||
disabled={isFirst}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.moveUp")}
|
||||
testID={`agent-profile-move-up-${profile.id}`}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
leftIcon={moveDownIcon}
|
||||
onPress={handleMoveDown}
|
||||
disabled={isLast}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.moveDown")}
|
||||
testID={`agent-profile-move-down-${profile.id}`}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
leftIcon={editIcon}
|
||||
onPress={handleEdit}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.editProfile")}
|
||||
testID={`agent-profile-edit-${profile.id}`}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
leftIcon={removeIcon}
|
||||
onPress={handleRemove}
|
||||
accessibilityLabel={t("settings.host.agentProfiles.remove")}
|
||||
testID={`agent-profile-remove-${profile.id}`}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
row: {
|
||||
position: "relative",
|
||||
flexDirection: "row",
|
||||
gap: theme.spacing[2],
|
||||
minHeight: 56,
|
||||
alignItems: "center",
|
||||
minHeight: ROW_MIN_HEIGHT,
|
||||
paddingVertical: theme.spacing[3],
|
||||
paddingLeft: theme.spacing[2],
|
||||
paddingRight: theme.spacing[4],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
rowHovered: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
rowSelected: {
|
||||
backgroundColor: theme.colors.surface3,
|
||||
},
|
||||
selectedIndicator: {
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
top: theme.spacing[2],
|
||||
bottom: theme.spacing[2],
|
||||
width: theme.borderWidth[2],
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
rowPressed: {
|
||||
backgroundColor: theme.colors.surface3,
|
||||
},
|
||||
rowDragging: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
pressTarget: {
|
||||
...StyleSheet.absoluteFill,
|
||||
},
|
||||
passThrough: {
|
||||
pointerEvents: "none",
|
||||
},
|
||||
gripSlot: {
|
||||
width: ROSTER_GRIP_WIDTH,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
},
|
||||
gripSpacerCompact: {
|
||||
width: theme.spacing[2],
|
||||
flexShrink: 0,
|
||||
},
|
||||
gripHandle: {
|
||||
width: ROSTER_GRIP_WIDTH,
|
||||
height: GRIP_HANDLE_HEIGHT,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
affordanceHidden: {
|
||||
opacity: 0,
|
||||
},
|
||||
iconTile: {
|
||||
width: theme.spacing[7],
|
||||
height: theme.spacing[7],
|
||||
borderRadius: theme.borderRadius.md,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
},
|
||||
columns: {
|
||||
rowMain: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
colProfile: {
|
||||
width: ROSTER_COL_PROFILE_WIDTH,
|
||||
flexShrink: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
minWidth: 0,
|
||||
},
|
||||
colRuntime: {
|
||||
width: ROSTER_COL_RUNTIME_WIDTH,
|
||||
flexShrink: 0,
|
||||
gap: theme.spacing[0.5],
|
||||
minWidth: 0,
|
||||
},
|
||||
colNotes: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
nameText: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
modelLine: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1.5],
|
||||
minWidth: 0,
|
||||
},
|
||||
modelText: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
runtimeSubtext: {
|
||||
color: theme.colors.foregroundExtraMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
notesText: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
notesEmptyText: {
|
||||
color: theme.colors.foregroundExtraMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
stackedMain: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
gap: theme.spacing[3],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
stackedContent: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
gap: theme.spacing[0.5],
|
||||
},
|
||||
stackedSpecLine: {
|
||||
flexDirection: "row",
|
||||
iconWrapper: {
|
||||
width: theme.iconSize.md,
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1.5],
|
||||
justifyContent: "center",
|
||||
marginTop: 1,
|
||||
},
|
||||
titleLine: {
|
||||
flexDirection: "row",
|
||||
alignItems: "baseline",
|
||||
gap: theme.spacing[2],
|
||||
minWidth: 0,
|
||||
},
|
||||
stackedSpecText: {
|
||||
summary: {
|
||||
flexShrink: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
stackedNotesText: {
|
||||
color: theme.colors.foregroundExtraMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
marginTop: theme.spacing[0.5],
|
||||
notes: {
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
gap: theme.spacing[1],
|
||||
marginTop: theme.spacing[1],
|
||||
},
|
||||
trailing: {
|
||||
width: ROSTER_TRAILING_WIDTH,
|
||||
notesText: {
|
||||
flex: 1,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
rowActions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "flex-end",
|
||||
gap: theme.spacing[1],
|
||||
flexShrink: 0,
|
||||
},
|
||||
kebabSlot: {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
// Optical: matches SettingsRowHeader so the chevron sits on the card's trailing rail.
|
||||
chevron: {
|
||||
marginRight: -theme.spacing[1],
|
||||
},
|
||||
}));
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,7 +3,7 @@ import { Pressable, Text, View, type PressableStateCallbackType } from "react-na
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfile, AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||
import type { AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { Combobox, type ComboboxOption, type ComboboxProps } from "@/components/ui/combobox";
|
||||
@@ -40,7 +40,7 @@ interface CombinedModelSelectorProps {
|
||||
profiles?: AgentProfilePicker | null;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
renderTrigger?: (input: {
|
||||
selectedModelLabel: string;
|
||||
@@ -195,17 +195,12 @@ 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);
|
||||
void onCreateProfile?.(seed);
|
||||
onCreateProfile?.(seed);
|
||||
},
|
||||
[handleOpenChange, onCreateProfile, onSelect],
|
||||
[handleOpenChange, onCreateProfile],
|
||||
);
|
||||
|
||||
const handleEditProfile = useCallback(
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import {
|
||||
AgentProfileGlyph,
|
||||
type AgentProfile,
|
||||
type AgentProfilePicker,
|
||||
type AgentProfilePickerRow as AgentProfilePickerRowModel,
|
||||
type AgentProfileSeed,
|
||||
@@ -222,7 +221,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) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onRetryProvider?: (provider: AgentProvider) => void;
|
||||
isRetryingProvider?: boolean;
|
||||
@@ -696,7 +695,7 @@ function ModelRow({
|
||||
showProviderLabel?: boolean;
|
||||
onPress: () => void;
|
||||
profiledRows: AgentProfilePickerRowModel[];
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -759,13 +758,7 @@ function ModelRow({
|
||||
label={t("modelSelector.editProfileLabel", { name: primary.name })}
|
||||
testID={`model-edit-profile-${row.provider}-${row.modelId}`}
|
||||
>
|
||||
<AgentProfileGlyph
|
||||
icon={primary.icon}
|
||||
color={primary.color}
|
||||
provider={primary.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.xs}
|
||||
/>
|
||||
<AgentProfileGlyph icon={primary.icon} color={primary.color} size={ICON_SIZE.xs} />
|
||||
</ModelRowProfileAction>
|
||||
);
|
||||
}
|
||||
@@ -779,13 +772,7 @@ function ModelRow({
|
||||
label={t("modelSelector.editProfilesCount", { count: profiledRows.length })}
|
||||
testID={`model-edit-profiles-${row.provider}-${row.modelId}`}
|
||||
>
|
||||
<AgentProfileGlyph
|
||||
icon={primary.icon}
|
||||
color={primary.color}
|
||||
provider={primary.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.xs}
|
||||
/>
|
||||
<AgentProfileGlyph icon={primary.icon} color={primary.color} size={ICON_SIZE.xs} />
|
||||
</ModelRowProfileAction>
|
||||
);
|
||||
}, [
|
||||
@@ -800,7 +787,6 @@ function ModelRow({
|
||||
profiledRows,
|
||||
row.modelId,
|
||||
row.provider,
|
||||
serverId,
|
||||
t,
|
||||
]);
|
||||
|
||||
@@ -875,7 +861,7 @@ function SelectableModelRow({
|
||||
showProviderLabel?: boolean;
|
||||
onSelect: (provider: string, modelId: string) => void;
|
||||
profiledRows: AgentProfilePickerRowModel[];
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -899,25 +885,15 @@ function SelectableModelRow({
|
||||
|
||||
function AgentProfilePickerRowView({
|
||||
row,
|
||||
serverId,
|
||||
onApply,
|
||||
}: {
|
||||
row: AgentProfilePickerRowModel;
|
||||
serverId: string | null;
|
||||
onApply: (profileId: string) => void;
|
||||
}) {
|
||||
const handlePress = useCallback(() => onApply(row.id), [onApply, row.id]);
|
||||
const leadingSlot = useMemo(
|
||||
() => (
|
||||
<AgentProfileGlyph
|
||||
icon={row.icon}
|
||||
color={row.color}
|
||||
provider={row.provider}
|
||||
serverId={serverId}
|
||||
size={ICON_SIZE.sm}
|
||||
/>
|
||||
),
|
||||
[row.color, row.icon, row.provider, serverId],
|
||||
() => <AgentProfileGlyph icon={row.icon} color={row.color} size={ICON_SIZE.sm} />,
|
||||
[row.color, row.icon],
|
||||
);
|
||||
return (
|
||||
<ModelBrowserRow
|
||||
@@ -938,12 +914,10 @@ function AgentProfilePickerRowView({
|
||||
*/
|
||||
function AgentProfilesPickerSection({
|
||||
rows,
|
||||
serverId,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
}: {
|
||||
rows: AgentProfilePickerRowModel[];
|
||||
serverId: string | null;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -963,12 +937,7 @@ function AgentProfilesPickerSection({
|
||||
) : null}
|
||||
</View>
|
||||
{rows.map((row) => (
|
||||
<AgentProfilePickerRowView
|
||||
key={row.id}
|
||||
row={row}
|
||||
serverId={serverId}
|
||||
onApply={handleApply}
|
||||
/>
|
||||
<AgentProfilePickerRowView key={row.id} row={row} onApply={handleApply} />
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
@@ -997,12 +966,10 @@ function CreateAgentProfileRow({ onPress }: { onPress: () => void }) {
|
||||
|
||||
function AgentProfilesPickerContent({
|
||||
rows,
|
||||
serverId,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
}: {
|
||||
rows: AgentProfilePickerRowModel[];
|
||||
serverId: string | null;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -1012,7 +979,6 @@ function AgentProfilesPickerContent({
|
||||
return (
|
||||
<AgentProfilesPickerSection
|
||||
rows={rows}
|
||||
serverId={serverId}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
@@ -1025,13 +991,11 @@ function AgentProfilesPickerContent({
|
||||
*/
|
||||
function ProfileSearchResultsHeader({
|
||||
rows,
|
||||
serverId,
|
||||
hasModelRows,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
}: {
|
||||
rows: AgentProfilePickerRowModel[];
|
||||
serverId: string | null;
|
||||
hasModelRows: boolean;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
@@ -1041,7 +1005,6 @@ function ProfileSearchResultsHeader({
|
||||
<View>
|
||||
<AgentProfilesPickerSection
|
||||
rows={rows}
|
||||
serverId={serverId}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
@@ -1244,7 +1207,7 @@ function ModelRowList({
|
||||
header?: React.ReactElement;
|
||||
scrolling: "sheet" | "independent";
|
||||
profiledLookup: Map<string, AgentProfilePickerRowModel[]>;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
}) {
|
||||
@@ -1373,7 +1336,7 @@ function ProviderModelBrowserContent({
|
||||
onSelect: (provider: string, modelId: string) => void;
|
||||
onApplyProfile?: (profileId: string) => void;
|
||||
onEditProfiles?: () => void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
profiledLookup: Map<string, AgentProfilePickerRowModel[]>;
|
||||
showProfilesSection?: boolean;
|
||||
@@ -1400,7 +1363,6 @@ function ProviderModelBrowserContent({
|
||||
return (
|
||||
<AgentProfilesPickerContent
|
||||
rows={providerProfileRows}
|
||||
serverId={serverId}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
@@ -1409,7 +1371,6 @@ function ProviderModelBrowserContent({
|
||||
return matchedProfileRows.length > 0 ? (
|
||||
<ProfileSearchResultsHeader
|
||||
rows={matchedProfileRows}
|
||||
serverId={serverId}
|
||||
hasModelRows={visibleRows.length > 0}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
@@ -1422,7 +1383,6 @@ function ProviderModelBrowserContent({
|
||||
onEditProfiles,
|
||||
profiles,
|
||||
providerProfileRows,
|
||||
serverId,
|
||||
showProfilesSection,
|
||||
visibleRows.length,
|
||||
]);
|
||||
@@ -1525,13 +1485,12 @@ function ModelBrowserContent({
|
||||
allView.kind === "searchResults" && allView.profiles.length > 0 ? (
|
||||
<ProfileSearchResultsHeader
|
||||
rows={allView.profiles}
|
||||
serverId={serverId}
|
||||
hasModelRows={allView.rows.length > 0}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
) : undefined,
|
||||
[allView, onApplyProfile, onEditProfiles, serverId],
|
||||
[allView, onApplyProfile, onEditProfiles],
|
||||
);
|
||||
|
||||
if (view.kind === "provider") {
|
||||
@@ -1593,7 +1552,6 @@ function ModelBrowserContent({
|
||||
{showProfilesSection && profiles ? (
|
||||
<AgentProfilesPickerContent
|
||||
rows={profiles.rows}
|
||||
serverId={serverId}
|
||||
onApplyProfile={onApplyProfile}
|
||||
onEditProfiles={onEditProfiles}
|
||||
/>
|
||||
|
||||
@@ -96,7 +96,6 @@ import {
|
||||
import {
|
||||
useAgentProfileEditor,
|
||||
useAgentProfilePicker,
|
||||
type AgentProfile,
|
||||
type AgentProfileApplyTarget,
|
||||
type AgentProfileEditorControls,
|
||||
type AgentProfilePicker,
|
||||
@@ -128,7 +127,7 @@ interface ControlledAgentControlsProps {
|
||||
agentProfiles?: AgentProfilePicker | null;
|
||||
onApplyAgentProfile?: (profileId: string) => void;
|
||||
onEditAgentProfiles?: () => void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditAgentProfile?: (profileId: string) => void;
|
||||
optionControls?: ComposerOptionControls;
|
||||
onDropdownClose?: () => void;
|
||||
@@ -270,7 +269,7 @@ function useEditAgentProfilesNavigation(
|
||||
): (() => void) | undefined {
|
||||
const handleEdit = useCallback(() => {
|
||||
if (!serverId) return;
|
||||
router.push(buildSettingsHostSectionRoute(serverId, "agent-profiles"));
|
||||
router.push(buildSettingsHostSectionRoute(serverId, "agents"));
|
||||
}, [serverId]);
|
||||
return serverId && isSupported ? handleEdit : undefined;
|
||||
}
|
||||
@@ -279,14 +278,14 @@ function resolveAgentProfileEditorActions(
|
||||
isSupported: boolean,
|
||||
editor: AgentProfileEditorControls,
|
||||
): {
|
||||
create?: (seed: AgentProfileSeed) => Promise<AgentProfile | null>;
|
||||
create?: (seed: AgentProfileSeed) => void;
|
||||
edit?: (profileId: string) => void;
|
||||
} {
|
||||
if (!isSupported) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
create: editor.quickCreateFromModel,
|
||||
create: editor.openCreateFromModel,
|
||||
edit: editor.openEdit,
|
||||
};
|
||||
}
|
||||
@@ -733,7 +732,7 @@ interface AgentControlsContentProps {
|
||||
featureItems: ComposerControlItem[];
|
||||
onApplyAgentProfile?: (profileId: string) => void;
|
||||
onEditAgentProfiles?: () => void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => Promise<AgentProfile | null> | void;
|
||||
onCreateAgentProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditAgentProfile?: (profileId: string) => void;
|
||||
onDropdownClose?: () => void;
|
||||
onModelSelectorOpen?: () => void;
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfile, AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||
import type { 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) => Promise<AgentProfile | null> | void;
|
||||
onCreateProfile?: (seed: AgentProfileSeed) => void;
|
||||
onEditProfile?: (profileId: string) => void;
|
||||
onOpen?: () => void;
|
||||
onClose?: () => void;
|
||||
@@ -74,9 +74,8 @@ interface CompactModelSheetProps {
|
||||
}
|
||||
|
||||
function resolveModelSheetProfileActions(
|
||||
onCreateProfile: ((seed: AgentProfileSeed) => Promise<AgentProfile | null> | void) | undefined,
|
||||
onCreateProfile: ((seed: AgentProfileSeed) => void) | undefined,
|
||||
onEditProfile: ((profileId: string) => void) | undefined,
|
||||
onSelect: (provider: string, modelId: string) => void,
|
||||
close: () => void,
|
||||
): {
|
||||
create?: (seed: AgentProfileSeed) => void;
|
||||
@@ -85,11 +84,8 @@ function resolveModelSheetProfileActions(
|
||||
return {
|
||||
create: onCreateProfile
|
||||
? (seed: AgentProfileSeed) => {
|
||||
if (seed.modelId) {
|
||||
onSelect(seed.provider, seed.modelId);
|
||||
}
|
||||
close();
|
||||
void onCreateProfile(seed);
|
||||
onCreateProfile(seed);
|
||||
}
|
||||
: undefined,
|
||||
edit: onEditProfile
|
||||
@@ -285,12 +281,7 @@ export function CompactModelSheet({
|
||||
onEditProfiles?.();
|
||||
}, [close, onEditProfiles]);
|
||||
|
||||
const profileActions = resolveModelSheetProfileActions(
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
onSelect,
|
||||
close,
|
||||
);
|
||||
const profileActions = resolveModelSheetProfileActions(onCreateProfile, onEditProfile, close);
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
if (isOpen) {
|
||||
|
||||
@@ -11,8 +11,13 @@ import { i18n } from "@/i18n/i18next";
|
||||
|
||||
const DESKTOP_SETTINGS_QUERY_KEY = ["desktop-settings"] as const;
|
||||
|
||||
export type DesktopUpdateMode = "automatic" | "notify" | "off";
|
||||
|
||||
export interface DesktopSettings {
|
||||
releaseChannel: ReleaseChannel;
|
||||
updates: {
|
||||
mode: DesktopUpdateMode;
|
||||
};
|
||||
notifications: {
|
||||
playSound: boolean;
|
||||
};
|
||||
@@ -24,12 +29,16 @@ export interface DesktopSettings {
|
||||
|
||||
export interface DesktopSettingsPatch {
|
||||
releaseChannel?: ReleaseChannel;
|
||||
updates?: Partial<DesktopSettings["updates"]>;
|
||||
notifications?: Partial<DesktopSettings["notifications"]>;
|
||||
daemon?: Partial<DesktopSettings["daemon"]>;
|
||||
}
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
releaseChannel: "stable",
|
||||
updates: {
|
||||
mode: "automatic",
|
||||
},
|
||||
notifications: {
|
||||
playSound: true,
|
||||
},
|
||||
@@ -149,13 +158,24 @@ export async function migrateLegacyDesktopSettings(input: {
|
||||
await invokeDesktopCommand("migrate_legacy_desktop_settings", input);
|
||||
}
|
||||
|
||||
function parseUpdateMode(value: unknown): DesktopUpdateMode {
|
||||
if (value === "automatic" || value === "notify" || value === "off") {
|
||||
return value;
|
||||
}
|
||||
return DEFAULT_DESKTOP_SETTINGS.updates.mode;
|
||||
}
|
||||
|
||||
function parseDesktopSettings(raw: unknown): DesktopSettings {
|
||||
const record = isRecord(raw) ? raw : {};
|
||||
const updates = isRecord(record.updates) ? record.updates : {};
|
||||
const notifications = isRecord(record.notifications) ? record.notifications : {};
|
||||
const daemon = isRecord(record.daemon) ? record.daemon : {};
|
||||
|
||||
return {
|
||||
releaseChannel: record.releaseChannel === "beta" ? "beta" : "stable",
|
||||
updates: {
|
||||
mode: parseUpdateMode(updates.mode),
|
||||
},
|
||||
notifications: {
|
||||
playSound:
|
||||
typeof notifications.playSound === "boolean"
|
||||
@@ -181,6 +201,10 @@ function mergeDesktopSettings(
|
||||
): DesktopSettings {
|
||||
return {
|
||||
releaseChannel: updates.releaseChannel ?? current.releaseChannel,
|
||||
updates: {
|
||||
...current.updates,
|
||||
...updates.updates,
|
||||
},
|
||||
notifications: {
|
||||
...current.notifications,
|
||||
...updates.notifications,
|
||||
@@ -195,6 +219,7 @@ function mergeDesktopSettings(
|
||||
function normalizePatch(updates: DesktopSettingsPatch): Record<string, unknown> {
|
||||
return {
|
||||
...(updates.releaseChannel ? { releaseChannel: updates.releaseChannel } : {}),
|
||||
...(updates.updates ? { updates: updates.updates } : {}),
|
||||
...(updates.notifications ? { notifications: updates.notifications } : {}),
|
||||
...(updates.daemon ? { daemon: updates.daemon } : {}),
|
||||
};
|
||||
|
||||
@@ -128,6 +128,43 @@ describe("desktop app updater — check", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reports 'available' when an update is available to download without auto-downloading", async () => {
|
||||
const { updater, port } = createUpdater({ now: () => 42 });
|
||||
port.nextCheckResult(
|
||||
buildFakeCheckResult({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.3",
|
||||
}),
|
||||
);
|
||||
|
||||
await updater.checkForUpdates({ releaseChannel: "stable" });
|
||||
|
||||
expect(updater.getSnapshot()).toMatchObject({
|
||||
status: "available",
|
||||
availableUpdate: { latestVersion: "1.2.3", readyToInstall: false, downloading: false },
|
||||
lastCheckedAt: 42,
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks download progress updates and clears them once install completes", async () => {
|
||||
const { updater, port } = createUpdater();
|
||||
port.nextInstallResult(buildFakeInstallResult({ installed: true }));
|
||||
|
||||
updater.setDownloadProgress({
|
||||
version: "1.2.3",
|
||||
percent: 42.4,
|
||||
transferred: 42,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
});
|
||||
expect(updater.getSnapshot().downloadProgress?.percent).toBe(42.4);
|
||||
|
||||
await updater.installUpdate({ releaseChannel: "stable" });
|
||||
expect(updater.getSnapshot().downloadProgress).toBeNull();
|
||||
});
|
||||
|
||||
it("reports 'up-to-date' when the check resolves with no update", async () => {
|
||||
const { updater, port } = createUpdater();
|
||||
port.nextCheckResult(buildFakeCheckResult({ hasUpdate: false, readyToInstall: false }));
|
||||
@@ -340,6 +377,55 @@ describe("desktop app updater — install", () => {
|
||||
expect(updater.getSnapshot().status).toBe("up-to-date");
|
||||
});
|
||||
|
||||
it("moves to 'error' instead of 'up-to-date' when the install returns an errorMessage", async () => {
|
||||
const { updater, port } = createUpdater();
|
||||
port.nextInstallResult(
|
||||
buildFakeInstallResult({
|
||||
installed: false,
|
||||
message: "Update failed: ECONNRESET",
|
||||
errorMessage: "ECONNRESET",
|
||||
}),
|
||||
);
|
||||
|
||||
await updater.installUpdate({ releaseChannel: "stable" });
|
||||
|
||||
expect(updater.getSnapshot()).toMatchObject({
|
||||
status: "error",
|
||||
errorMessage: "ECONNRESET",
|
||||
downloadProgress: null,
|
||||
isInstalling: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores duplicate install requests and silent checks while an install is in progress", async () => {
|
||||
const { updater, port } = createUpdater();
|
||||
let resolveInstall!: (result: ReturnType<typeof buildFakeInstallResult>) => void;
|
||||
port.installDesktopAppUpdate = async (input) => {
|
||||
port.recordedInstalls.push(input);
|
||||
return new Promise((resolve) => {
|
||||
resolveInstall = resolve;
|
||||
});
|
||||
};
|
||||
|
||||
const firstInstall = updater.installUpdate({ releaseChannel: "stable" });
|
||||
const secondInstall = await updater.installUpdate({ releaseChannel: "stable" });
|
||||
const silentCheck = await updater.checkForUpdates({
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
silent: true,
|
||||
});
|
||||
|
||||
expect(secondInstall).toBeNull();
|
||||
expect(silentCheck).toBeNull();
|
||||
expect(port.recordedInstalls).toHaveLength(1);
|
||||
expect(port.recordedChecks).toHaveLength(0);
|
||||
expect(updater.getSnapshot().status).toBe("installing");
|
||||
|
||||
resolveInstall(buildFakeInstallResult({ installed: true }));
|
||||
await firstInstall;
|
||||
expect(updater.getSnapshot().status).toBe("installed");
|
||||
});
|
||||
|
||||
it("reports the install error and moves to 'error' when the install throws", async () => {
|
||||
const { updater, port, reportedInstallErrors } = createUpdater();
|
||||
const error = new Error("install failed");
|
||||
@@ -462,6 +548,47 @@ describe("formatStatusText", () => {
|
||||
).toBe("Restart now");
|
||||
});
|
||||
|
||||
it("formats download-available and live download progress status text", () => {
|
||||
expect(
|
||||
formatStatusText({
|
||||
status: "available",
|
||||
availableUpdate: buildFakeCheckResult({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.3",
|
||||
}),
|
||||
installMessage: null,
|
||||
lastCheckedAt: 42,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
}),
|
||||
).toBe("Update available: v1.2.3. Last checked at time-42.");
|
||||
|
||||
expect(
|
||||
formatStatusText({
|
||||
status: "installing",
|
||||
availableUpdate: buildFakeCheckResult({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.3",
|
||||
}),
|
||||
downloadProgress: {
|
||||
version: "1.2.3",
|
||||
percent: 64.6,
|
||||
transferred: 65,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
},
|
||||
installMessage: null,
|
||||
lastCheckedAt: null,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
}),
|
||||
).toBe("Downloading v1.2.3... 65%");
|
||||
});
|
||||
|
||||
it("uses the active app language for local status wrappers", async () => {
|
||||
await i18n.changeLanguage("zh-CN");
|
||||
try {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
DesktopAppUpdateCheckResult,
|
||||
DesktopAppUpdateCheckIntent,
|
||||
DesktopAppUpdateDownloadProgress,
|
||||
DesktopAppUpdateInstallResult,
|
||||
DesktopReleaseChannel,
|
||||
} from "@/desktop/updates/desktop-updates";
|
||||
@@ -21,6 +22,7 @@ export const PENDING_RECHECK_MS = 10_000;
|
||||
export interface DesktopAppUpdaterSnapshot {
|
||||
status: DesktopAppUpdateStatus;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
errorMessage: string | null;
|
||||
installMessage: string | null;
|
||||
lastCheckedAt: number | null;
|
||||
@@ -53,6 +55,7 @@ export interface DesktopAppUpdaterDeps {
|
||||
export interface DesktopAppUpdater {
|
||||
getSnapshot(): DesktopAppUpdaterSnapshot;
|
||||
subscribe(listener: () => void): () => void;
|
||||
setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void;
|
||||
checkForUpdates(options?: {
|
||||
releaseChannel: DesktopReleaseChannel;
|
||||
intent?: DesktopAppUpdateCheckIntent;
|
||||
@@ -66,6 +69,7 @@ export interface DesktopAppUpdater {
|
||||
interface InternalState {
|
||||
status: DesktopAppUpdateStatus;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
errorMessage: string | null;
|
||||
installMessage: string | null;
|
||||
lastCheckedAt: number | null;
|
||||
@@ -76,6 +80,7 @@ interface InternalState {
|
||||
const INITIAL_STATE: InternalState = {
|
||||
status: "idle",
|
||||
availableUpdate: null,
|
||||
downloadProgress: null,
|
||||
errorMessage: null,
|
||||
installMessage: null,
|
||||
lastCheckedAt: null,
|
||||
@@ -87,6 +92,7 @@ function buildSnapshot(state: InternalState): DesktopAppUpdaterSnapshot {
|
||||
return {
|
||||
status: state.status,
|
||||
availableUpdate: state.availableUpdate,
|
||||
downloadProgress: state.downloadProgress,
|
||||
errorMessage: state.errorMessage,
|
||||
installMessage: state.installMessage,
|
||||
lastCheckedAt: state.lastCheckedAt,
|
||||
@@ -102,9 +108,113 @@ function getErrorMessage(error: unknown): string {
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function formatInstallingStatusText(input: {
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
formatVersion: (version: string | null | undefined) => string;
|
||||
}): string {
|
||||
const { availableUpdate, downloadProgress, formatVersion } = input;
|
||||
if (downloadProgress == null) {
|
||||
return i18n.t("desktop.updates.status.installing");
|
||||
}
|
||||
const percent = Math.round(downloadProgress.percent);
|
||||
const version = downloadProgress.version ?? availableUpdate?.latestVersion;
|
||||
if (version) {
|
||||
return i18n.t("desktop.updates.status.downloadingVersionProgress", {
|
||||
version: formatVersion(version),
|
||||
percent,
|
||||
});
|
||||
}
|
||||
return i18n.t("desktop.updates.status.downloadingProgress", { percent });
|
||||
}
|
||||
|
||||
function formatPendingStatusText(input: {
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
lastCheckedAt: number | null;
|
||||
formatVersion: (version: string | null | undefined) => string;
|
||||
formatLastCheckedAt: (timestamp: number) => string;
|
||||
}): string {
|
||||
const { availableUpdate, downloadProgress, lastCheckedAt, formatVersion, formatLastCheckedAt } =
|
||||
input;
|
||||
const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined;
|
||||
if (availableUpdate?.latestVersion) {
|
||||
const version = formatVersion(availableUpdate.latestVersion);
|
||||
if (downloadProgress != null) {
|
||||
return i18n.t(
|
||||
time !== undefined
|
||||
? "desktop.updates.status.pendingWithVersionProgressAndLastChecked"
|
||||
: "desktop.updates.status.pendingWithVersionProgress",
|
||||
{ version, percent: Math.round(downloadProgress.percent), time },
|
||||
);
|
||||
}
|
||||
return i18n.t(
|
||||
time !== undefined
|
||||
? "desktop.updates.status.pendingWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.pendingWithVersion",
|
||||
{ version, time },
|
||||
);
|
||||
}
|
||||
if (time !== undefined) {
|
||||
return i18n.t("desktop.updates.status.pendingWithLastChecked", { time });
|
||||
}
|
||||
return i18n.t("desktop.updates.status.pending");
|
||||
}
|
||||
|
||||
function formatAvailableStatusText(input: {
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
lastCheckedAt: number | null;
|
||||
formatVersion: (version: string | null | undefined) => string;
|
||||
formatLastCheckedAt: (timestamp: number) => string;
|
||||
}): string {
|
||||
const { availableUpdate, lastCheckedAt, formatVersion, formatLastCheckedAt } = input;
|
||||
const time = lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined;
|
||||
const isDownloadRequired =
|
||||
availableUpdate?.hasUpdate === true && availableUpdate.readyToInstall === false;
|
||||
if (availableUpdate?.latestVersion) {
|
||||
const version = formatVersion(availableUpdate.latestVersion);
|
||||
if (isDownloadRequired) {
|
||||
return i18n.t(
|
||||
time !== undefined
|
||||
? "desktop.updates.status.downloadAvailableWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.downloadAvailableWithVersion",
|
||||
{ version, time },
|
||||
);
|
||||
}
|
||||
return i18n.t(
|
||||
time !== undefined
|
||||
? "desktop.updates.status.availableWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.availableWithVersion",
|
||||
{ version, time },
|
||||
);
|
||||
}
|
||||
if (isDownloadRequired) {
|
||||
return time !== undefined
|
||||
? i18n.t("desktop.updates.status.downloadAvailableWithLastChecked", { time })
|
||||
: i18n.t("desktop.updates.status.downloadAvailable");
|
||||
}
|
||||
return time !== undefined
|
||||
? i18n.t("desktop.updates.status.availableWithLastChecked", { time })
|
||||
: i18n.t("desktop.updates.status.available");
|
||||
}
|
||||
|
||||
function resolveCheckOutcome(result: DesktopAppUpdateCheckResult): {
|
||||
status: DesktopAppUpdateStatus;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
} {
|
||||
if (result.readyToInstall || (result.hasUpdate && !result.downloading)) {
|
||||
return { status: "available", availableUpdate: result };
|
||||
}
|
||||
if (result.hasUpdate) {
|
||||
return { status: "pending", availableUpdate: result };
|
||||
}
|
||||
return { status: "up-to-date", availableUpdate: null };
|
||||
}
|
||||
|
||||
export function formatStatusText(input: {
|
||||
status: DesktopAppUpdateStatus;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress?: DesktopAppUpdateDownloadProgress | null;
|
||||
installMessage: string | null;
|
||||
lastCheckedAt: number | null;
|
||||
formatVersion: (version: string | null | undefined) => string;
|
||||
@@ -113,79 +223,45 @@ export function formatStatusText(input: {
|
||||
const {
|
||||
status,
|
||||
availableUpdate,
|
||||
downloadProgress = null,
|
||||
installMessage,
|
||||
lastCheckedAt,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
} = input;
|
||||
|
||||
if (status === "checking") {
|
||||
return i18n.t("desktop.updates.status.checking");
|
||||
}
|
||||
|
||||
if (status === "checking") return i18n.t("desktop.updates.status.checking");
|
||||
if (status === "installing") {
|
||||
return i18n.t("desktop.updates.status.installing");
|
||||
return formatInstallingStatusText({ availableUpdate, downloadProgress, formatVersion });
|
||||
}
|
||||
|
||||
if (status === "up-to-date") {
|
||||
if (lastCheckedAt != null) {
|
||||
return i18n.t("desktop.updates.status.upToDateWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
});
|
||||
}
|
||||
return i18n.t("desktop.updates.status.upToDate");
|
||||
return lastCheckedAt != null
|
||||
? i18n.t("desktop.updates.status.upToDateWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
})
|
||||
: i18n.t("desktop.updates.status.upToDate");
|
||||
}
|
||||
|
||||
if (status === "pending") {
|
||||
if (availableUpdate?.latestVersion) {
|
||||
return i18n.t(
|
||||
lastCheckedAt != null
|
||||
? "desktop.updates.status.pendingWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.pendingWithVersion",
|
||||
{
|
||||
version: formatVersion(availableUpdate.latestVersion),
|
||||
time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (lastCheckedAt != null) {
|
||||
return i18n.t("desktop.updates.status.pendingWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
});
|
||||
}
|
||||
return i18n.t("desktop.updates.status.pending");
|
||||
return formatPendingStatusText({
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
lastCheckedAt,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
});
|
||||
}
|
||||
|
||||
if (status === "available") {
|
||||
if (availableUpdate?.latestVersion) {
|
||||
return i18n.t(
|
||||
lastCheckedAt != null
|
||||
? "desktop.updates.status.availableWithVersionAndLastChecked"
|
||||
: "desktop.updates.status.availableWithVersion",
|
||||
{
|
||||
version: formatVersion(availableUpdate.latestVersion),
|
||||
time: lastCheckedAt != null ? formatLastCheckedAt(lastCheckedAt) : undefined,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (lastCheckedAt != null) {
|
||||
return i18n.t("desktop.updates.status.availableWithLastChecked", {
|
||||
time: formatLastCheckedAt(lastCheckedAt),
|
||||
});
|
||||
}
|
||||
return i18n.t("desktop.updates.status.available");
|
||||
return formatAvailableStatusText({
|
||||
availableUpdate,
|
||||
lastCheckedAt,
|
||||
formatVersion,
|
||||
formatLastCheckedAt,
|
||||
});
|
||||
}
|
||||
|
||||
if (status === "installed") {
|
||||
return installMessage ?? i18n.t("desktop.updates.status.installed");
|
||||
}
|
||||
|
||||
if (status === "error") {
|
||||
return i18n.t("desktop.updates.status.failed");
|
||||
}
|
||||
|
||||
if (status === "error") return i18n.t("desktop.updates.status.failed");
|
||||
return i18n.t("desktop.updates.status.idle");
|
||||
}
|
||||
|
||||
@@ -202,6 +278,16 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
}
|
||||
}
|
||||
|
||||
function setDownloadProgress(progress: DesktopAppUpdateDownloadProgress | null): void {
|
||||
if (progress === null && state.downloadProgress === null) {
|
||||
return;
|
||||
}
|
||||
commit({
|
||||
...state,
|
||||
downloadProgress: progress,
|
||||
});
|
||||
}
|
||||
|
||||
async function checkForUpdates(options?: {
|
||||
releaseChannel: DesktopReleaseChannel;
|
||||
intent?: DesktopAppUpdateCheckIntent;
|
||||
@@ -211,7 +297,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
return null;
|
||||
}
|
||||
const { releaseChannel, intent = "manual", silent = false } = options;
|
||||
if (silent && state.status === "checking") {
|
||||
if (silent && (state.status === "checking" || state.isInstalling)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -241,6 +327,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
...state,
|
||||
status: "error",
|
||||
availableUpdate: null,
|
||||
downloadProgress: null,
|
||||
errorMessage: result.errorMessage,
|
||||
installMessage: null,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
@@ -248,24 +335,13 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
return result;
|
||||
}
|
||||
|
||||
let nextStatus: DesktopAppUpdateStatus;
|
||||
let nextAvailable: DesktopAppUpdateCheckResult | null;
|
||||
|
||||
if (result.readyToInstall) {
|
||||
nextStatus = "available";
|
||||
nextAvailable = result;
|
||||
} else if (result.hasUpdate) {
|
||||
nextStatus = "pending";
|
||||
nextAvailable = result;
|
||||
} else {
|
||||
nextStatus = "up-to-date";
|
||||
nextAvailable = null;
|
||||
}
|
||||
const outcome = resolveCheckOutcome(result);
|
||||
|
||||
commit({
|
||||
...state,
|
||||
status: nextStatus,
|
||||
availableUpdate: nextAvailable,
|
||||
status: outcome.status,
|
||||
availableUpdate: outcome.availableUpdate,
|
||||
downloadProgress: outcome.status === "pending" ? state.downloadProgress : null,
|
||||
errorMessage: null,
|
||||
installMessage: null,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
@@ -284,6 +360,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
commit({
|
||||
...state,
|
||||
status: "error",
|
||||
downloadProgress: null,
|
||||
errorMessage: message,
|
||||
lastCheckedAt: intent === "manual" ? deps.now() : state.lastCheckedAt,
|
||||
});
|
||||
@@ -295,6 +372,10 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
async function installUpdate(options: {
|
||||
releaseChannel: DesktopReleaseChannel;
|
||||
}): Promise<DesktopAppUpdateInstallResult | null> {
|
||||
if (state.isInstalling) {
|
||||
return null;
|
||||
}
|
||||
|
||||
commit({
|
||||
...state,
|
||||
status: "installing",
|
||||
@@ -307,10 +388,23 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
releaseChannel: options.releaseChannel,
|
||||
});
|
||||
const nextLastCheckedAt = deps.now();
|
||||
if (!result.installed && result.errorMessage) {
|
||||
commit({
|
||||
...state,
|
||||
status: "error",
|
||||
downloadProgress: null,
|
||||
errorMessage: result.errorMessage,
|
||||
installMessage: null,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
isInstalling: false,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
commit({
|
||||
...state,
|
||||
status: result.installed ? "installed" : "up-to-date",
|
||||
availableUpdate: null,
|
||||
downloadProgress: null,
|
||||
installMessage: result.message,
|
||||
lastCheckedAt: nextLastCheckedAt,
|
||||
isInstalling: false,
|
||||
@@ -326,6 +420,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
commit({
|
||||
...state,
|
||||
status: "error",
|
||||
downloadProgress: null,
|
||||
errorMessage: message,
|
||||
isInstalling: false,
|
||||
});
|
||||
@@ -341,6 +436,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
setDownloadProgress,
|
||||
checkForUpdates,
|
||||
installUpdate,
|
||||
};
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
import { isElectronRuntime } from "@/desktop/host";
|
||||
import { listenToDesktopEvent, type DesktopEventUnlisten } from "@/desktop/electron/events";
|
||||
import { invokeDesktopCommand } from "@/desktop/electron/invoke";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
export interface DesktopAppUpdateDownloadProgress {
|
||||
version: string | null;
|
||||
percent: number;
|
||||
transferred: number;
|
||||
total: number;
|
||||
bytesPerSecond: number;
|
||||
}
|
||||
|
||||
export interface DesktopAppUpdateCheckResult {
|
||||
hasUpdate: boolean;
|
||||
readyToInstall: boolean;
|
||||
downloading: boolean;
|
||||
currentVersion: string | null;
|
||||
latestVersion: string | null;
|
||||
body: string | null;
|
||||
@@ -17,6 +27,7 @@ export interface DesktopAppUpdateInstallResult {
|
||||
installed: boolean;
|
||||
version: string | null;
|
||||
message: string;
|
||||
errorMessage?: string | null;
|
||||
}
|
||||
|
||||
export interface DesktopRuntimeInfo {
|
||||
@@ -115,9 +126,13 @@ export async function checkDesktopAppUpdate({
|
||||
throw new Error("Unexpected response while checking desktop updates.");
|
||||
}
|
||||
|
||||
const hasUpdate = result.hasUpdate === true;
|
||||
const readyToInstall = result.readyToInstall === true;
|
||||
return {
|
||||
hasUpdate: result.hasUpdate === true,
|
||||
readyToInstall: result.readyToInstall === true,
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading:
|
||||
typeof result.downloading === "boolean" ? result.downloading : hasUpdate && !readyToInstall,
|
||||
currentVersion: toStringOrNull(result.currentVersion),
|
||||
latestVersion: toStringOrNull(result.latestVersion),
|
||||
body: toStringOrNull(result.body),
|
||||
@@ -126,6 +141,36 @@ export async function checkDesktopAppUpdate({
|
||||
};
|
||||
}
|
||||
|
||||
export function parseDesktopAppUpdateDownloadProgress(
|
||||
raw: unknown,
|
||||
): DesktopAppUpdateDownloadProgress | null {
|
||||
if (!isRecord(raw)) {
|
||||
return null;
|
||||
}
|
||||
const percent = toNumberOr(Number.NaN, raw.percent);
|
||||
if (!Number.isFinite(percent)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
version: toStringOrNull(raw.version),
|
||||
percent: Math.max(0, Math.min(100, percent)),
|
||||
transferred: toNumberOr(0, raw.transferred),
|
||||
total: toNumberOr(0, raw.total),
|
||||
bytesPerSecond: toNumberOr(0, raw.bytesPerSecond),
|
||||
};
|
||||
}
|
||||
|
||||
export async function subscribeDesktopAppUpdateDownloadProgress(
|
||||
handler: (progress: DesktopAppUpdateDownloadProgress | null) => void,
|
||||
): Promise<DesktopEventUnlisten> {
|
||||
if (!shouldShowDesktopUpdateSection()) {
|
||||
return () => {};
|
||||
}
|
||||
return listenToDesktopEvent<unknown>("app-update-download-progress", (payload) => {
|
||||
handler(payload === null ? null : parseDesktopAppUpdateDownloadProgress(payload));
|
||||
});
|
||||
}
|
||||
|
||||
export async function installDesktopAppUpdate({
|
||||
releaseChannel,
|
||||
}: {
|
||||
@@ -136,10 +181,12 @@ export async function installDesktopAppUpdate({
|
||||
throw new Error("Unexpected response while installing desktop update.");
|
||||
}
|
||||
|
||||
const errorMessage = toStringOrNull(result.errorMessage);
|
||||
return {
|
||||
installed: result.installed === true,
|
||||
version: toStringOrNull(result.version),
|
||||
message: toStringOrNull(result.message) ?? i18n.t("desktop.updates.status.installed"),
|
||||
...(errorMessage ? { errorMessage } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,50 @@ describe("resolveUpdateCalloutDescriptor", () => {
|
||||
expect(descriptor?.dismissalKey).toBe("desktop-update:installing:1.2.3");
|
||||
});
|
||||
|
||||
it("labels the callout as Download when the update has not been downloaded yet", () => {
|
||||
const descriptor = resolveUpdateCalloutDescriptor(
|
||||
input({ availableUpdate: { latestVersion: "1.2.3", readyToInstall: false } }),
|
||||
);
|
||||
|
||||
expect(descriptor?.title).toBe("Update available");
|
||||
expect(descriptor?.body).toEqual({
|
||||
kind: "available",
|
||||
versionLabel: "v1.2.3",
|
||||
readyToInstall: false,
|
||||
});
|
||||
expect(descriptor?.actions).toEqual([
|
||||
{ role: "changelog", label: "What's new" },
|
||||
{ role: "install", label: "Download", variant: "primary", disabled: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows download progress while downloading an update", () => {
|
||||
const descriptor = resolveUpdateCalloutDescriptor(
|
||||
input({
|
||||
status: "installing",
|
||||
isInstalling: true,
|
||||
downloadProgress: {
|
||||
version: "1.2.3",
|
||||
percent: 42.2,
|
||||
transferred: 42,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(descriptor?.title).toBe("Downloading update");
|
||||
expect(descriptor?.body).toEqual({
|
||||
kind: "downloading",
|
||||
versionLabel: "v1.2.3",
|
||||
percent: 42,
|
||||
});
|
||||
expect(descriptor?.actions).toEqual([
|
||||
{ role: "changelog", label: "What's new" },
|
||||
{ role: "install", label: "Downloading...", variant: "primary", disabled: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows a retry action and surfaces the error message on error", () => {
|
||||
const descriptor = resolveUpdateCalloutDescriptor(
|
||||
input({ status: "error", errorMessage: "Download failed", availableUpdate: null }),
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { DesktopAppUpdateStatus } from "@/desktop/updates/use-desktop-app-updater";
|
||||
import type { DesktopAppUpdateDownloadProgress } from "@/desktop/updates/desktop-updates";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
export type UpdateCalloutBody =
|
||||
| { kind: "available"; versionLabel: string | null }
|
||||
| { kind: "available"; versionLabel: string | null; readyToInstall?: boolean }
|
||||
| { kind: "downloading"; versionLabel: string | null; percent: number }
|
||||
| { kind: "installing" }
|
||||
| { kind: "error"; message: string };
|
||||
|
||||
@@ -31,7 +33,8 @@ export interface ResolveUpdateCalloutInput {
|
||||
isDesktopApp: boolean;
|
||||
status: DesktopAppUpdateStatus;
|
||||
isInstalling: boolean;
|
||||
availableUpdate: { latestVersion?: string | null } | null;
|
||||
availableUpdate: { latestVersion?: string | null; readyToInstall?: boolean } | null;
|
||||
downloadProgress?: DesktopAppUpdateDownloadProgress | null;
|
||||
errorMessage: string | null;
|
||||
}
|
||||
|
||||
@@ -40,6 +43,59 @@ function formatVersionLabel(latestVersion: string | null | undefined): string |
|
||||
return `v${latestVersion.replace(/^v/i, "")}`;
|
||||
}
|
||||
|
||||
function resolveCalloutPresentation(input: {
|
||||
isError: boolean;
|
||||
isInstalling: boolean;
|
||||
readyToInstall: boolean;
|
||||
latestVersion: string | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null | undefined;
|
||||
errorMessage: string | null;
|
||||
}): { title: string; body: UpdateCalloutBody } {
|
||||
if (input.isInstalling && input.downloadProgress != null) {
|
||||
return {
|
||||
title: i18n.t("desktop.updates.callout.downloadingTitle"),
|
||||
body: {
|
||||
kind: "downloading",
|
||||
versionLabel: formatVersionLabel(input.latestVersion),
|
||||
percent: Math.round(input.downloadProgress.percent),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (input.isInstalling) {
|
||||
return {
|
||||
title: i18n.t("desktop.updates.callout.installingTitle"),
|
||||
body: { kind: "installing" },
|
||||
};
|
||||
}
|
||||
if (input.isError) {
|
||||
return {
|
||||
title: i18n.t("desktop.updates.callout.failedTitle"),
|
||||
body: {
|
||||
kind: "error",
|
||||
message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"),
|
||||
},
|
||||
};
|
||||
}
|
||||
const versionLabel = formatVersionLabel(input.latestVersion);
|
||||
return {
|
||||
title: i18n.t("desktop.updates.callout.availableTitle"),
|
||||
body: input.readyToInstall
|
||||
? { kind: "available", versionLabel }
|
||||
: { kind: "available", versionLabel, readyToInstall: false },
|
||||
};
|
||||
}
|
||||
|
||||
function resolveInstallActionLabel(input: {
|
||||
isDownloading: boolean;
|
||||
isInstalling: boolean;
|
||||
readyToInstall: boolean;
|
||||
}): string {
|
||||
if (input.isDownloading) return i18n.t("desktop.updates.callout.downloadingAction");
|
||||
if (input.isInstalling) return i18n.t("desktop.updates.callout.installingAction");
|
||||
if (input.readyToInstall) return i18n.t("desktop.updates.callout.installAndRestart");
|
||||
return i18n.t("desktop.updates.callout.downloadAndRestart");
|
||||
}
|
||||
|
||||
export function resolveUpdateCalloutDescriptor(
|
||||
input: ResolveUpdateCalloutInput,
|
||||
): UpdateCalloutDescriptor | null {
|
||||
@@ -50,26 +106,22 @@ export function resolveUpdateCalloutDescriptor(
|
||||
|
||||
const isError = input.status === "error";
|
||||
const isInstalling = input.isInstalling;
|
||||
const isDownloading = isInstalling && input.downloadProgress != null;
|
||||
const isAvailable = !isInstalling && !isError;
|
||||
const readyToInstall = input.availableUpdate?.readyToInstall !== false;
|
||||
|
||||
const latestVersion = input.availableUpdate?.latestVersion ?? null;
|
||||
const latestVersion =
|
||||
input.availableUpdate?.latestVersion ?? input.downloadProgress?.version ?? null;
|
||||
const dismissalKey = `desktop-update:${input.status}:${latestVersion ?? "unknown"}`;
|
||||
|
||||
let title: string;
|
||||
let body: UpdateCalloutBody;
|
||||
if (isInstalling) {
|
||||
title = i18n.t("desktop.updates.callout.installingTitle");
|
||||
body = { kind: "installing" };
|
||||
} else if (isError) {
|
||||
title = i18n.t("desktop.updates.callout.failedTitle");
|
||||
body = {
|
||||
kind: "error",
|
||||
message: input.errorMessage ?? i18n.t("desktop.updates.callout.genericError"),
|
||||
};
|
||||
} else {
|
||||
title = i18n.t("desktop.updates.callout.availableTitle");
|
||||
body = { kind: "available", versionLabel: formatVersionLabel(latestVersion) };
|
||||
}
|
||||
const { title, body } = resolveCalloutPresentation({
|
||||
isError,
|
||||
isInstalling,
|
||||
readyToInstall,
|
||||
latestVersion,
|
||||
downloadProgress: input.downloadProgress,
|
||||
errorMessage: input.errorMessage,
|
||||
});
|
||||
|
||||
const actions: UpdateCalloutActionDescriptor[] = [
|
||||
{ role: "changelog", label: i18n.t("desktop.updates.callout.whatsNew") },
|
||||
@@ -79,9 +131,7 @@ export function resolveUpdateCalloutDescriptor(
|
||||
} else {
|
||||
actions.push({
|
||||
role: "install",
|
||||
label: isInstalling
|
||||
? i18n.t("desktop.updates.callout.installingAction")
|
||||
: i18n.t("desktop.updates.callout.installAndRestart"),
|
||||
label: resolveInstallActionLabel({ isDownloading, isInstalling, readyToInstall }),
|
||||
variant: "primary",
|
||||
disabled: isInstalling,
|
||||
});
|
||||
|
||||
@@ -34,9 +34,12 @@ type InstallOutcome =
|
||||
function buildCheckResult(
|
||||
overrides: Partial<DesktopAppUpdateCheckResult> = {},
|
||||
): DesktopAppUpdateCheckResult {
|
||||
const hasUpdate = overrides.hasUpdate ?? false;
|
||||
const readyToInstall = overrides.readyToInstall ?? false;
|
||||
return {
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading: overrides.downloading ?? (hasUpdate && !readyToInstall),
|
||||
currentVersion: null,
|
||||
latestVersion: null,
|
||||
body: null,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Gift } from "lucide-react-native";
|
||||
import { type ReactNode, useEffect, useRef } from "react";
|
||||
import { type ReactNode, useEffect, useMemo, useRef } from "react";
|
||||
import { View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useUnistyles } from "react-native-unistyles";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
type SidebarCalloutAction,
|
||||
SidebarCalloutDescriptionText,
|
||||
@@ -19,9 +20,24 @@ import { openChangelog } from "@/changelog";
|
||||
const CHECK_INTERVAL_MS = 30 * 60 * 1000;
|
||||
|
||||
function renderBody(body: UpdateCalloutBody, t: ReturnType<typeof useTranslation>["t"]): ReactNode {
|
||||
if (body.kind === "downloading") {
|
||||
return (
|
||||
<UpdateDownloadingDescription
|
||||
versionLabel={body.versionLabel ?? undefined}
|
||||
percent={body.percent}
|
||||
t={t}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (body.kind === "installing") return t("desktop.updates.callout.installingDescription");
|
||||
if (body.kind === "error") return body.message;
|
||||
return <UpdateAvailableDescription versionLabel={body.versionLabel ?? undefined} t={t} />;
|
||||
return (
|
||||
<UpdateAvailableDescription
|
||||
versionLabel={body.versionLabel ?? undefined}
|
||||
readyToInstall={body.readyToInstall !== false}
|
||||
t={t}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function materializeActions(
|
||||
@@ -42,8 +58,11 @@ export function UpdateCalloutSource() {
|
||||
const { theme } = useUnistyles();
|
||||
const {
|
||||
isDesktopApp,
|
||||
updateMode,
|
||||
isLoadingSettings,
|
||||
status,
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
checkForUpdates,
|
||||
installUpdate,
|
||||
@@ -58,7 +77,7 @@ export function UpdateCalloutSource() {
|
||||
void checkForUpdates();
|
||||
});
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp) return;
|
||||
if (!isDesktopApp || isLoadingSettings || updateMode === "off") return;
|
||||
|
||||
void checkForUpdates({ intent: "automatic", silent: true });
|
||||
|
||||
@@ -71,7 +90,7 @@ export function UpdateCalloutSource() {
|
||||
clearInterval(intervalRef.current);
|
||||
}
|
||||
};
|
||||
}, [isDesktopApp, checkForUpdates]);
|
||||
}, [isDesktopApp, isLoadingSettings, updateMode, checkForUpdates]);
|
||||
|
||||
useEffect(() => {
|
||||
const descriptor = resolveUpdateCalloutDescriptor({
|
||||
@@ -79,6 +98,7 @@ export function UpdateCalloutSource() {
|
||||
status,
|
||||
isInstalling,
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
});
|
||||
if (!descriptor) return;
|
||||
@@ -103,6 +123,7 @@ export function UpdateCalloutSource() {
|
||||
}, [
|
||||
availableUpdate,
|
||||
callouts,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
install,
|
||||
isDesktopApp,
|
||||
@@ -117,23 +138,94 @@ export function UpdateCalloutSource() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function formatAvailableSummary(
|
||||
t: ReturnType<typeof useTranslation>["t"],
|
||||
versionLabel: string | undefined,
|
||||
readyToInstall: boolean,
|
||||
): string {
|
||||
if (readyToInstall) {
|
||||
return versionLabel
|
||||
? t("desktop.updates.callout.versionReady", { version: versionLabel })
|
||||
: t("desktop.updates.callout.newVersionReady");
|
||||
}
|
||||
return versionLabel
|
||||
? t("desktop.updates.callout.versionAvailable", { version: versionLabel })
|
||||
: t("desktop.updates.callout.newVersionAvailable");
|
||||
}
|
||||
|
||||
function UpdateAvailableDescription({
|
||||
versionLabel,
|
||||
readyToInstall,
|
||||
t,
|
||||
}: {
|
||||
versionLabel?: string;
|
||||
readyToInstall: boolean;
|
||||
t: ReturnType<typeof useTranslation>["t"];
|
||||
}) {
|
||||
const summary = formatAvailableSummary(t, versionLabel, readyToInstall);
|
||||
|
||||
return (
|
||||
<>
|
||||
<SidebarCalloutDescriptionText>
|
||||
{versionLabel
|
||||
? t("desktop.updates.callout.versionReady", { version: versionLabel })
|
||||
: t("desktop.updates.callout.newVersionReady")}
|
||||
</SidebarCalloutDescriptionText>
|
||||
<SidebarCalloutDescriptionText>{summary}</SidebarCalloutDescriptionText>
|
||||
<SidebarCalloutDescriptionText>
|
||||
{t("desktop.updates.callout.restartWarning")}
|
||||
</SidebarCalloutDescriptionText>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function UpdateDownloadingDescription({
|
||||
versionLabel,
|
||||
percent,
|
||||
t,
|
||||
}: {
|
||||
versionLabel?: string;
|
||||
percent: number;
|
||||
t: ReturnType<typeof useTranslation>["t"];
|
||||
}) {
|
||||
const clampedPercent = Math.max(0, Math.min(100, percent));
|
||||
const accessibilityValue = useMemo(
|
||||
() => ({ min: 0, max: 100, now: clampedPercent }),
|
||||
[clampedPercent],
|
||||
);
|
||||
const progressFillStyle = useMemo(
|
||||
() => [styles.progressFill, { width: `${clampedPercent}%` as const }],
|
||||
[clampedPercent],
|
||||
);
|
||||
return (
|
||||
<View style={styles.progressContainer}>
|
||||
<SidebarCalloutDescriptionText>
|
||||
{versionLabel
|
||||
? t("desktop.updates.callout.downloadingVersionDescription", {
|
||||
version: versionLabel,
|
||||
percent: clampedPercent,
|
||||
})
|
||||
: t("desktop.updates.callout.downloadingDescription", { percent: clampedPercent })}
|
||||
</SidebarCalloutDescriptionText>
|
||||
<View
|
||||
style={styles.progressTrack}
|
||||
accessibilityRole="progressbar"
|
||||
accessibilityValue={accessibilityValue}
|
||||
>
|
||||
<View style={progressFillStyle} />
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
progressContainer: {
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
progressTrack: {
|
||||
height: 4,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.surface3,
|
||||
overflow: "hidden",
|
||||
},
|
||||
progressFill: {
|
||||
height: "100%",
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,30 +1,94 @@
|
||||
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
import {
|
||||
checkDesktopAppUpdate,
|
||||
formatVersionWithPrefix,
|
||||
installDesktopAppUpdate,
|
||||
shouldShowDesktopUpdateSection,
|
||||
subscribeDesktopAppUpdateDownloadProgress,
|
||||
type DesktopAppUpdateCheckResult,
|
||||
type DesktopAppUpdateCheckIntent,
|
||||
type DesktopAppUpdateDownloadProgress,
|
||||
type DesktopAppUpdateInstallResult,
|
||||
} from "@/desktop/updates/desktop-updates";
|
||||
import { useDesktopSettings } from "@/desktop/settings/desktop-settings";
|
||||
import { useDesktopSettings, type DesktopUpdateMode } from "@/desktop/settings/desktop-settings";
|
||||
import { useDesktopIpcErrorReporter } from "@/desktop/hooks/desktop-ipc-error";
|
||||
import {
|
||||
PENDING_RECHECK_MS,
|
||||
createDesktopAppUpdater,
|
||||
formatStatusText,
|
||||
type DesktopAppUpdater,
|
||||
type DesktopAppUpdaterErrorReport,
|
||||
type DesktopAppUpdateStatus,
|
||||
} from "@/desktop/updates/desktop-app-updater";
|
||||
import { formatMessageTimestamp } from "@/utils/time";
|
||||
|
||||
export type { DesktopAppUpdateStatus };
|
||||
|
||||
let activeInstallErrorReporter: ((report: DesktopAppUpdaterErrorReport) => void) | null = null;
|
||||
let sharedDesktopAppUpdater: DesktopAppUpdater | null = null;
|
||||
let progressSubscriptionCount = 0;
|
||||
let progressUnsubscribe: (() => void) | null = null;
|
||||
|
||||
function getSharedDesktopAppUpdater(): DesktopAppUpdater {
|
||||
if (!sharedDesktopAppUpdater) {
|
||||
sharedDesktopAppUpdater = createDesktopAppUpdater({
|
||||
port: {
|
||||
checkDesktopAppUpdate,
|
||||
installDesktopAppUpdate,
|
||||
},
|
||||
now: () => Date.now(),
|
||||
reportInstallError: (report) => {
|
||||
activeInstallErrorReporter?.(report);
|
||||
},
|
||||
});
|
||||
}
|
||||
return sharedDesktopAppUpdater;
|
||||
}
|
||||
|
||||
function retainDownloadProgressSubscription(updater: DesktopAppUpdater): () => void {
|
||||
progressSubscriptionCount += 1;
|
||||
if (progressSubscriptionCount === 1) {
|
||||
let active = true;
|
||||
const teardown = () => {
|
||||
active = false;
|
||||
};
|
||||
progressUnsubscribe = teardown;
|
||||
void subscribeDesktopAppUpdateDownloadProgress((progress) => {
|
||||
if (active) {
|
||||
updater.setDownloadProgress(progress);
|
||||
}
|
||||
})
|
||||
.then((cleanup) => {
|
||||
if (active) {
|
||||
progressUnsubscribe = () => {
|
||||
active = false;
|
||||
cleanup();
|
||||
};
|
||||
} else {
|
||||
cleanup();
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
return () => {
|
||||
progressSubscriptionCount = Math.max(0, progressSubscriptionCount - 1);
|
||||
if (progressSubscriptionCount === 0) {
|
||||
progressUnsubscribe?.();
|
||||
progressUnsubscribe = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export interface UseDesktopAppUpdaterReturn {
|
||||
isDesktopApp: boolean;
|
||||
updateMode: DesktopUpdateMode;
|
||||
isLoadingSettings: boolean;
|
||||
status: DesktopAppUpdateStatus;
|
||||
statusText: string;
|
||||
availableUpdate: DesktopAppUpdateCheckResult | null;
|
||||
downloadProgress: DesktopAppUpdateDownloadProgress | null;
|
||||
errorMessage: string | null;
|
||||
lastCheckedAt: number | null;
|
||||
isChecking: boolean;
|
||||
@@ -38,22 +102,15 @@ export interface UseDesktopAppUpdaterReturn {
|
||||
|
||||
export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
||||
const isDesktopApp = shouldShowDesktopUpdateSection();
|
||||
const { settings: desktopSettings } = useDesktopSettings();
|
||||
const { settings: desktopSettings, isLoading: isLoadingSettings } = useDesktopSettings();
|
||||
const releaseChannel = desktopSettings.releaseChannel;
|
||||
const updateMode = desktopSettings.updates.mode;
|
||||
const reportError = useDesktopIpcErrorReporter();
|
||||
const updater = getSharedDesktopAppUpdater();
|
||||
|
||||
const updater = useMemo(
|
||||
() =>
|
||||
createDesktopAppUpdater({
|
||||
port: {
|
||||
checkDesktopAppUpdate,
|
||||
installDesktopAppUpdate,
|
||||
},
|
||||
now: () => Date.now(),
|
||||
reportInstallError: reportError,
|
||||
}),
|
||||
[reportError],
|
||||
);
|
||||
useEffect(() => {
|
||||
activeInstallErrorReporter = reportError;
|
||||
}, [reportError]);
|
||||
|
||||
const snapshot = useSyncExternalStore(
|
||||
updater.subscribe,
|
||||
@@ -84,13 +141,20 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp) {
|
||||
return undefined;
|
||||
}
|
||||
return retainDownloadProgressSubscription(updater);
|
||||
}, [isDesktopApp, updater]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp || isLoadingSettings || updateMode === "off") {
|
||||
return;
|
||||
}
|
||||
void checkForUpdates({ intent: "automatic", silent: true });
|
||||
}, [checkForUpdates, isDesktopApp]);
|
||||
}, [checkForUpdates, isDesktopApp, isLoadingSettings, updateMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isDesktopApp || snapshot.status !== "pending") {
|
||||
if (!isDesktopApp || snapshot.status !== "pending" || updateMode === "off") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -101,20 +165,24 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
|
||||
return () => {
|
||||
clearInterval(intervalId);
|
||||
};
|
||||
}, [checkForUpdates, isDesktopApp, snapshot.status]);
|
||||
}, [checkForUpdates, isDesktopApp, snapshot.status, updateMode]);
|
||||
|
||||
return {
|
||||
isDesktopApp,
|
||||
updateMode,
|
||||
isLoadingSettings,
|
||||
status: snapshot.status,
|
||||
statusText: formatStatusText({
|
||||
status: snapshot.status,
|
||||
availableUpdate: snapshot.availableUpdate,
|
||||
downloadProgress: snapshot.downloadProgress,
|
||||
installMessage: snapshot.installMessage,
|
||||
lastCheckedAt: snapshot.lastCheckedAt,
|
||||
formatVersion: formatVersionWithPrefix,
|
||||
formatLastCheckedAt: (timestamp) => formatMessageTimestamp(new Date(timestamp)),
|
||||
}),
|
||||
availableUpdate: snapshot.availableUpdate,
|
||||
downloadProgress: snapshot.downloadProgress,
|
||||
errorMessage: snapshot.errorMessage,
|
||||
lastCheckedAt: snapshot.lastCheckedAt,
|
||||
isChecking: snapshot.isChecking,
|
||||
|
||||
@@ -32,6 +32,9 @@ export interface FakeDesktopBridge extends DesktopSettingsBridge {
|
||||
|
||||
const DEFAULT_DESKTOP: DesktopSettings = {
|
||||
releaseChannel: "stable",
|
||||
updates: {
|
||||
mode: "automatic",
|
||||
},
|
||||
notifications: {
|
||||
playSound: true,
|
||||
},
|
||||
|
||||
@@ -656,6 +656,7 @@ describe("loadSettingsFromStorage", () => {
|
||||
isElectron: true,
|
||||
settings: {
|
||||
releaseChannel: "beta",
|
||||
updates: { mode: "automatic" },
|
||||
notifications: { playSound: true },
|
||||
daemon: { manageBuiltInDaemon: false, keepRunningAfterQuit: true },
|
||||
},
|
||||
|
||||
@@ -1541,6 +1541,8 @@ export const ar: TranslationResources = {
|
||||
status: {
|
||||
checking: "جارٍ التحقق من وجود تحديثات للتطبيق...",
|
||||
installing: "جارٍ تثبيت تحديث التطبيق...",
|
||||
downloadingVersionProgress: "جارٍ تنزيل {{version}}... {{percent}}%",
|
||||
downloadingProgress: "جارٍ تنزيل تحديث التطبيق... {{percent}}%",
|
||||
upToDate: "التطبيق محدث.",
|
||||
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
|
||||
pending: "سنخبرك عندما يصبح التحديث جاهزًا.",
|
||||
@@ -1548,6 +1550,14 @@ export const ar: TranslationResources = {
|
||||
pendingWithVersion: "تم العثور على تحديث: {{version}}. جارٍ التنزيل...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"تم العثور على تحديث: {{version}}. جارٍ التنزيل... آخر فحص في {{time}}.",
|
||||
pendingWithVersionProgress: "تم العثور على تحديث: {{version}}. جارٍ التنزيل... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"تم العثور على تحديث: {{version}}. جارٍ التنزيل... {{percent}}% آخر فحص في {{time}}.",
|
||||
downloadAvailableWithVersion: "التحديث متاح: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"التحديث متاح: {{version}}. آخر فحص في {{time}}.",
|
||||
downloadAvailable: "يتوفر تحديث للتطبيق.",
|
||||
downloadAvailableWithLastChecked: "يتوفر تحديث للتطبيق. آخر فحص في {{time}}.",
|
||||
availableWithVersion: "التحديث جاهز:{{version}}",
|
||||
availableWithVersionAndLastChecked: "التحديث جاهز:{{version}}. آخر فحص في {{time}}.",
|
||||
available: "تحديث التطبيق جاهز للتثبيت.",
|
||||
@@ -1558,14 +1568,21 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
installError: "غير قادر على تثبيت تحديث تطبيق سطح المكتب.",
|
||||
callout: {
|
||||
downloadingTitle: "جارٍ تنزيل التحديث",
|
||||
installingTitle: "تثبيت التحديث",
|
||||
failedTitle: "فشل التحديث",
|
||||
availableTitle: "التحديث متاح",
|
||||
genericError: "حدث خطأ ما.",
|
||||
whatsNew: "ما هو الجديد",
|
||||
downloadingAction: "جارٍ التنزيل...",
|
||||
installingAction: "جارٍ التثبيت...",
|
||||
downloadAndRestart: "تنزيل",
|
||||
installAndRestart: "التثبيت وإعادة التشغيل",
|
||||
downloadingVersionDescription: "جارٍ تنزيل {{version}}... {{percent}}%",
|
||||
downloadingDescription: "جارٍ تنزيل التحديث... {{percent}}%",
|
||||
installingDescription: "التثبيت وإعادة التشغيل...",
|
||||
versionAvailable: "{{version}} متاح للتنزيل.",
|
||||
newVersionAvailable: "يتوفر إصدار جديد للتنزيل.",
|
||||
versionReady: "{{version}}جاهز للتثبيت.",
|
||||
newVersionReady: "إصدار جديد جاهز للتثبيت.",
|
||||
restartWarning: "ستؤدي ترقية التطبيق إلى إيقاف تشغيل الوكلاء وإغلاق الجلسات الطرفية.",
|
||||
@@ -1814,9 +1831,6 @@ export const ar: TranslationResources = {
|
||||
editProfilesLabel: "تحرير ملفات الوكيل",
|
||||
createProfile: "إنشاء ملف شخصي",
|
||||
createProfileFromModel: "إنشاء ملف شخصي من هذا النموذج",
|
||||
profileSaved: 'تم حفظ "{{name}}"',
|
||||
undo: "تراجع",
|
||||
undoProfileSave: "التراجع عن حفظ الملف الشخصي",
|
||||
editProfileLabel: "تحرير {{name}}",
|
||||
editProfilesCount: "تحرير الملفات الشخصية ({{count}})",
|
||||
modelCount: "{{count}} نموذج",
|
||||
@@ -2433,7 +2447,6 @@ export const ar: TranslationResources = {
|
||||
projects: "المشاريع",
|
||||
connections: "اتصالات",
|
||||
agents: "Agents",
|
||||
agentProfiles: "ملفات الوكيل",
|
||||
metadata: "البيانات الوصفية",
|
||||
voice: "الصوت",
|
||||
workspaces: "Workspaces",
|
||||
@@ -2647,9 +2660,28 @@ export const ar: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "التحديثات التلقائية",
|
||||
options: {
|
||||
automatic: "تلقائي",
|
||||
notify: "إشعار",
|
||||
off: "إيقاف",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "التحقق من التحديثات وتنزيلها في الخلفية",
|
||||
notify: "التحقق من التحديثات وتنزيلها فقط عند اختيارك",
|
||||
off: "عدم التحقق تلقائيًا. يتم التحقق فقط عند النقر على فحص",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "تحديثات التطبيق",
|
||||
readyToInstall: "جاهز للتثبيت:{{version}}",
|
||||
downloadTitle: "تنزيل تحديث سطح المكتب",
|
||||
downloadMessage: "سيؤدي هذا إلى تنزيل تحديث Paseo وتثبيته على هذا الكمبيوتر",
|
||||
downloadConfirm: "تنزيل وتثبيت",
|
||||
download: "تنزيل",
|
||||
downloadTo: "تنزيل {{version}}",
|
||||
downloading: "جارٍ التنزيل...",
|
||||
installTitle: "تثبيت تحديث سطح المكتب",
|
||||
installMessage: "يؤدي هذا إلى تحديث Paseo على هذا الكمبيوتر",
|
||||
installConfirm: "تثبيت التحديث",
|
||||
@@ -3061,31 +3093,6 @@ 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: {
|
||||
|
||||
@@ -1568,6 +1568,8 @@ export const en = {
|
||||
status: {
|
||||
checking: "Checking for app updates...",
|
||||
installing: "Installing app update...",
|
||||
downloadingVersionProgress: "Downloading {{version}}... {{percent}}%",
|
||||
downloadingProgress: "Downloading app update... {{percent}}%",
|
||||
upToDate: "App is up to date.",
|
||||
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
|
||||
pending: "We'll let you know when the update is ready.",
|
||||
@@ -1576,6 +1578,14 @@ export const en = {
|
||||
pendingWithVersion: "Update found: {{version}}. Downloading...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Update found: {{version}}. Downloading... Last checked at {{time}}.",
|
||||
pendingWithVersionProgress: "Update found: {{version}}. Downloading... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Update found: {{version}}. Downloading... {{percent}}% Last checked at {{time}}.",
|
||||
downloadAvailableWithVersion: "Update available: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Update available: {{version}}. Last checked at {{time}}.",
|
||||
downloadAvailable: "An app update is available.",
|
||||
downloadAvailableWithLastChecked: "An app update is available. Last checked at {{time}}.",
|
||||
availableWithVersion: "Update ready: {{version}}",
|
||||
availableWithVersionAndLastChecked: "Update ready: {{version}}. Last checked at {{time}}.",
|
||||
available: "An app update is ready to install.",
|
||||
@@ -1586,14 +1596,21 @@ export const en = {
|
||||
},
|
||||
installError: "Unable to install the desktop app update.",
|
||||
callout: {
|
||||
downloadingTitle: "Downloading update",
|
||||
installingTitle: "Installing update",
|
||||
failedTitle: "Update failed",
|
||||
availableTitle: "Update available",
|
||||
genericError: "Something went wrong.",
|
||||
whatsNew: "What's new",
|
||||
downloadingAction: "Downloading...",
|
||||
installingAction: "Installing...",
|
||||
downloadAndRestart: "Download",
|
||||
installAndRestart: "Install & restart",
|
||||
downloadingVersionDescription: "Downloading {{version}}... {{percent}}%",
|
||||
downloadingDescription: "Downloading update... {{percent}}%",
|
||||
installingDescription: "Installing and restarting...",
|
||||
versionAvailable: "{{version}} is available to download.",
|
||||
newVersionAvailable: "A new version is available to download.",
|
||||
versionReady: "{{version}} is ready to install.",
|
||||
newVersionReady: "A new version is ready to install.",
|
||||
restartWarning: "Upgrading the app will stop running agents and close terminal sessions.",
|
||||
@@ -1843,9 +1860,6 @@ 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",
|
||||
@@ -2464,7 +2478,6 @@ export const en = {
|
||||
projects: "Projects",
|
||||
connections: "Connections",
|
||||
agents: "Agents",
|
||||
agentProfiles: "Agent profiles",
|
||||
metadata: "Metadata",
|
||||
voice: "Voice",
|
||||
workspaces: "Workspaces",
|
||||
@@ -2743,9 +2756,28 @@ export const en = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Automatic updates",
|
||||
options: {
|
||||
automatic: "Auto",
|
||||
notify: "Notify",
|
||||
off: "Off",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Check and download updates in the background",
|
||||
notify: "Check for updates, but only download when you choose",
|
||||
off: "Never check automatically. Only check when you click Check",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "App updates",
|
||||
readyToInstall: "Ready to install: {{version}}",
|
||||
downloadTitle: "Download desktop update",
|
||||
downloadMessage: "This downloads and installs the Paseo update on this computer",
|
||||
downloadConfirm: "Download & install",
|
||||
download: "Download",
|
||||
downloadTo: "Download {{version}}",
|
||||
downloading: "Downloading...",
|
||||
installTitle: "Install desktop update",
|
||||
installMessage: "This updates Paseo on this computer",
|
||||
installConfirm: "Install update",
|
||||
@@ -3151,7 +3183,7 @@ export const en = {
|
||||
featureCountOne: "{{count}} feature",
|
||||
notesLabel: "When to use",
|
||||
notesPlaceholder: "Use for UI work — components, layout and design tokens.",
|
||||
notesHint: "Tells agents when to pick this profile",
|
||||
notesHint: "Helps agents choose this profile when starting another agent.",
|
||||
save: "Save",
|
||||
saving: "Saving...",
|
||||
remove: "Remove",
|
||||
@@ -3159,31 +3191,6 @@ 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: {
|
||||
|
||||
@@ -1578,6 +1578,8 @@ export const es: TranslationResources = {
|
||||
status: {
|
||||
checking: "Buscando actualizaciones de la aplicación...",
|
||||
installing: "Instalando actualización de la aplicación...",
|
||||
downloadingVersionProgress: "Descargando {{version}}... {{percent}}%",
|
||||
downloadingProgress: "Descargando actualización de la aplicación... {{percent}}%",
|
||||
upToDate: "La aplicación está actualizada.",
|
||||
upToDateWithLastChecked: "Up to date. Last checked at {{time}}.",
|
||||
pending: "Le avisaremos cuando la actualización esté lista.",
|
||||
@@ -1586,6 +1588,16 @@ export const es: TranslationResources = {
|
||||
pendingWithVersion: "Actualización encontrada: {{version}}. Descargando...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Actualización encontrada: {{version}}. Descargando... Última comprobación a las {{time}}.",
|
||||
pendingWithVersionProgress:
|
||||
"Actualización encontrada: {{version}}. Descargando... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Actualización encontrada: {{version}}. Descargando... {{percent}}% Última comprobación a las {{time}}.",
|
||||
downloadAvailableWithVersion: "Actualización disponible: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Actualización disponible: {{version}}. Última comprobación a las {{time}}.",
|
||||
downloadAvailable: "Hay una actualización de la aplicación disponible.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"Hay una actualización de la aplicación disponible. Última comprobación a las {{time}}.",
|
||||
availableWithVersion: "Actualización lista:{{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"Actualización lista:{{version}}. Última comprobación a las {{time}}.",
|
||||
@@ -1598,14 +1610,21 @@ export const es: TranslationResources = {
|
||||
},
|
||||
installError: "No se puede instalar la actualización de la aplicación de escritorio.",
|
||||
callout: {
|
||||
downloadingTitle: "Descargando actualización",
|
||||
installingTitle: "Instalando actualización",
|
||||
failedTitle: "La actualización falló",
|
||||
availableTitle: "Actualización disponible",
|
||||
genericError: "Algo salió mal.",
|
||||
whatsNew: "Qué hay de nuevo",
|
||||
downloadingAction: "Descargando...",
|
||||
installingAction: "Instalando...",
|
||||
downloadAndRestart: "Descargar",
|
||||
installAndRestart: "Instalar y reiniciar",
|
||||
downloadingVersionDescription: "Descargando {{version}}... {{percent}}%",
|
||||
downloadingDescription: "Descargando actualización... {{percent}}%",
|
||||
installingDescription: "Instalando y reiniciando...",
|
||||
versionAvailable: "{{version}} está disponible para descargar.",
|
||||
newVersionAvailable: "Una nueva versión está disponible para descargar.",
|
||||
versionReady: "{{version}}está listo para instalar.",
|
||||
newVersionReady: "Una nueva versión está lista para instalar.",
|
||||
restartWarning:
|
||||
@@ -1862,9 +1881,6 @@ 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",
|
||||
@@ -2447,7 +2463,6 @@ export const es: TranslationResources = {
|
||||
projects: "Proyectos",
|
||||
connections: "Conexiones",
|
||||
agents: "Agents",
|
||||
agentProfiles: "Perfiles de agente",
|
||||
metadata: "Metadatos",
|
||||
voice: "Voz",
|
||||
workspaces: "Workspaces",
|
||||
@@ -2668,9 +2683,28 @@ export const es: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Actualizaciones automáticas",
|
||||
options: {
|
||||
automatic: "Auto",
|
||||
notify: "Notificar",
|
||||
off: "Desactivado",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Buscar y descargar actualizaciones en segundo plano",
|
||||
notify: "Buscar actualizaciones, pero descargar solo cuando lo elijas",
|
||||
off: "No buscar automáticamente. Solo buscar al hacer clic en Comprobar",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "Actualizaciones de aplicaciones",
|
||||
readyToInstall: "Listo para instalar:{{version}}",
|
||||
downloadTitle: "Descargar actualización de escritorio",
|
||||
downloadMessage: "Esto descarga e instala la actualización de Paseo en esta computadora.",
|
||||
downloadConfirm: "Descargar e instalar",
|
||||
download: "Descargar",
|
||||
downloadTo: "Descargar {{version}}",
|
||||
downloading: "Descargando...",
|
||||
installTitle: "Instalar actualización de escritorio",
|
||||
installMessage: "Esto actualizaPaseoen esta computadora.",
|
||||
installConfirm: "Instalar actualización",
|
||||
@@ -3087,31 +3121,6 @@ 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: {
|
||||
|
||||
@@ -1571,6 +1571,8 @@ export const fr: TranslationResources = {
|
||||
status: {
|
||||
checking: "Recherche de mises à jour de l’application…",
|
||||
installing: "Installation de la mise à jour de l’application…",
|
||||
downloadingVersionProgress: "Téléchargement de {{version}}… {{percent}} %",
|
||||
downloadingProgress: "Téléchargement de la mise à jour… {{percent}} %",
|
||||
upToDate: "L’application est à jour.",
|
||||
upToDateWithLastChecked: "À jour. Dernière vérification à {{time}}.",
|
||||
pending: "Nous vous préviendrons quand la mise à jour sera prête.",
|
||||
@@ -1579,6 +1581,16 @@ export const fr: TranslationResources = {
|
||||
pendingWithVersion: "Mise à jour trouvée : {{version}}. Téléchargement…",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Mise à jour trouvée : {{version}}. Téléchargement… Dernière vérification à {{time}}.",
|
||||
pendingWithVersionProgress:
|
||||
"Mise à jour trouvée : {{version}}. Téléchargement… {{percent}} %",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Mise à jour trouvée : {{version}}. Téléchargement… {{percent}} % Dernière vérification à {{time}}.",
|
||||
downloadAvailableWithVersion: "Mise à jour disponible : {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Mise à jour disponible : {{version}}. Dernière vérification à {{time}}.",
|
||||
downloadAvailable: "Une mise à jour de l’application est disponible.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"Une mise à jour de l’application est disponible. Dernière vérification à {{time}}.",
|
||||
availableWithVersion: "Mise à jour prête : {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"Mise à jour prête : {{version}}. Dernière vérification à {{time}}.",
|
||||
@@ -1591,14 +1603,21 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
installError: "Impossible d’installer la mise à jour de l’application de bureau.",
|
||||
callout: {
|
||||
downloadingTitle: "Téléchargement de la mise à jour",
|
||||
installingTitle: "Installation de la mise à jour",
|
||||
failedTitle: "Échec de la mise à jour",
|
||||
availableTitle: "Mise à jour disponible",
|
||||
genericError: "Une erreur s’est produite.",
|
||||
whatsNew: "Nouveautés",
|
||||
downloadingAction: "Téléchargement…",
|
||||
installingAction: "Installation…",
|
||||
downloadAndRestart: "Télécharger",
|
||||
installAndRestart: "Installer et redémarrer",
|
||||
downloadingVersionDescription: "Téléchargement de {{version}}… {{percent}} %",
|
||||
downloadingDescription: "Téléchargement de la mise à jour… {{percent}} %",
|
||||
installingDescription: "Installation et redémarrage…",
|
||||
versionAvailable: "La version {{version}} est disponible au téléchargement.",
|
||||
newVersionAvailable: "Une nouvelle version est disponible au téléchargement.",
|
||||
versionReady: "La version {{version}} est prête à être installée.",
|
||||
newVersionReady: "Une nouvelle version est prête à être installée.",
|
||||
restartWarning:
|
||||
@@ -1860,9 +1879,6 @@ 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",
|
||||
@@ -2447,7 +2463,6 @@ export const fr: TranslationResources = {
|
||||
projects: "Projets",
|
||||
connections: "Connexions",
|
||||
agents: "Agents",
|
||||
agentProfiles: "Profils d’agent",
|
||||
metadata: "Métadonnées",
|
||||
voice: "Voix",
|
||||
workspaces: "Espaces de travail",
|
||||
@@ -2668,9 +2683,28 @@ export const fr: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Bêta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Mises à jour automatiques",
|
||||
options: {
|
||||
automatic: "Auto",
|
||||
notify: "Notifier",
|
||||
off: "Désactivé",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Vérifier et télécharger les mises à jour en arrière-plan",
|
||||
notify: "Vérifier les mises à jour, mais ne télécharger que lorsque vous choisissez",
|
||||
off: "Ne jamais vérifier automatiquement. Vérifier uniquement sur clic sur Vérifier",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "Mises à jour de l’application",
|
||||
readyToInstall: "Prête à installer : {{version}}",
|
||||
downloadTitle: "Télécharger la mise à jour de l’app de bureau",
|
||||
downloadMessage: "La mise à jour de Paseo sera téléchargée et installée sur cet ordinateur",
|
||||
downloadConfirm: "Télécharger et installer",
|
||||
download: "Télécharger",
|
||||
downloadTo: "Télécharger {{version}}",
|
||||
downloading: "Téléchargement…",
|
||||
installTitle: "Installer la mise à jour de l’app de bureau",
|
||||
installMessage: "Paseo sera mis à jour sur cet ordinateur",
|
||||
installConfirm: "Installer la mise à jour",
|
||||
@@ -3091,31 +3125,6 @@ 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: {
|
||||
|
||||
@@ -1556,6 +1556,8 @@ export const ja: TranslationResources = {
|
||||
status: {
|
||||
checking: "アプリの更新を確認中...",
|
||||
installing: "アプリの更新をインストール中...",
|
||||
downloadingVersionProgress: "{{version}} をダウンロード中... {{percent}}%",
|
||||
downloadingProgress: "アプリの更新をダウンロード中... {{percent}}%",
|
||||
upToDate: "アプリは最新です。",
|
||||
upToDateWithLastChecked: "最新の状態です。最終確認: {{time}}。",
|
||||
pending: "更新の準備ができたらお知らせします。",
|
||||
@@ -1563,6 +1565,15 @@ export const ja: TranslationResources = {
|
||||
pendingWithVersion: "更新が見つかりました: {{version}}。ダウンロード中...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"更新が見つかりました: {{version}}。ダウンロード中... 最終確認: {{time}}。",
|
||||
pendingWithVersionProgress:
|
||||
"更新が見つかりました: {{version}}。ダウンロード中... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"更新が見つかりました: {{version}}。ダウンロード中... {{percent}}% 最終確認: {{time}}。",
|
||||
downloadAvailableWithVersion: "利用可能な更新: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"利用可能な更新: {{version}}。最終確認: {{time}}。",
|
||||
downloadAvailable: "アプリの更新が利用可能です。",
|
||||
downloadAvailableWithLastChecked: "アプリの更新が利用可能です。最終確認: {{time}}。",
|
||||
availableWithVersion: "更新の準備ができました: {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"更新の準備ができました: {{version}}。最終確認: {{time}}。",
|
||||
@@ -1574,14 +1585,21 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
installError: "デスクトップアプリの更新をインストールできません。",
|
||||
callout: {
|
||||
downloadingTitle: "更新をダウンロード中",
|
||||
installingTitle: "更新をインストール中",
|
||||
failedTitle: "更新に失敗しました",
|
||||
availableTitle: "更新が利用可能",
|
||||
genericError: "問題が発生しました。",
|
||||
whatsNew: "新機能",
|
||||
downloadingAction: "ダウンロード中...",
|
||||
installingAction: "インストール中...",
|
||||
downloadAndRestart: "ダウンロード",
|
||||
installAndRestart: "インストールして再起動",
|
||||
downloadingVersionDescription: "{{version}} をダウンロード中... {{percent}}%",
|
||||
downloadingDescription: "更新をダウンロード中... {{percent}}%",
|
||||
installingDescription: "インストールして再起動中...",
|
||||
versionAvailable: "{{version}} をダウンロードできます。",
|
||||
newVersionAvailable: "新しいバージョンをダウンロードできます。",
|
||||
versionReady: "{{version}}のインストール準備ができました。",
|
||||
newVersionReady: "新しいバージョンのインストール準備ができました。",
|
||||
restartWarning:
|
||||
@@ -1834,9 +1852,6 @@ export const ja: TranslationResources = {
|
||||
editProfilesLabel: "エージェントプロファイルを編集",
|
||||
createProfile: "プロファイルを作成",
|
||||
createProfileFromModel: "このモデルからプロファイルを作成",
|
||||
profileSaved: "「{{name}}」を保存しました",
|
||||
undo: "元に戻す",
|
||||
undoProfileSave: "プロファイル保存を取り消す",
|
||||
editProfileLabel: "{{name}}を編集",
|
||||
editProfilesCount: "プロファイルを編集({{count}})",
|
||||
modelCount: "{{count}}つのモデル",
|
||||
@@ -2421,7 +2436,6 @@ export const ja: TranslationResources = {
|
||||
projects: "プロジェクト",
|
||||
connections: "接続",
|
||||
agents: "エージェント",
|
||||
agentProfiles: "エージェントプロファイル",
|
||||
metadata: "メタデータ",
|
||||
voice: "音声",
|
||||
workspaces: "ワークスペース",
|
||||
@@ -2635,9 +2649,28 @@ export const ja: TranslationResources = {
|
||||
stable: "安定版",
|
||||
beta: "ベータ",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "自動更新",
|
||||
options: {
|
||||
automatic: "自動",
|
||||
notify: "通知のみ",
|
||||
off: "オフ",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "バックグラウンドで更新を確認してダウンロードします",
|
||||
notify: "更新を確認しますが、選択したときだけダウンロードします",
|
||||
off: "自動で更新を確認しません。「確認」をクリックしたときだけ確認します",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "アプリの更新",
|
||||
readyToInstall: "インストール準備完了: {{version}}",
|
||||
downloadTitle: "デスクトップの更新をダウンロード",
|
||||
downloadMessage: "このコンピューターにPaseoの更新をダウンロードしてインストールします",
|
||||
downloadConfirm: "ダウンロードしてインストール",
|
||||
download: "ダウンロード",
|
||||
downloadTo: "{{version}}をダウンロード",
|
||||
downloading: "ダウンロード中...",
|
||||
installTitle: "デスクトップの更新をインストール",
|
||||
installMessage: "このコンピューターのPaseoを更新します",
|
||||
installConfirm: "更新をインストール",
|
||||
@@ -3056,31 +3089,6 @@ 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: {
|
||||
|
||||
@@ -1547,6 +1547,8 @@ export const ko: TranslationResources = {
|
||||
status: {
|
||||
checking: "앱 업데이트 확인 중...",
|
||||
installing: "앱 업데이트 설치 중...",
|
||||
downloadingVersionProgress: "{{version}} 다운로드 중... {{percent}}%",
|
||||
downloadingProgress: "앱 업데이트 다운로드 중... {{percent}}%",
|
||||
upToDate: "앱이 최신 상태입니다.",
|
||||
upToDateWithLastChecked: "최신 상태입니다. 마지막 확인: {{time}}.",
|
||||
pending: "업데이트가 준비되면 알려드리겠습니다.",
|
||||
@@ -1555,6 +1557,15 @@ export const ko: TranslationResources = {
|
||||
pendingWithVersion: "업데이트 발견: {{version}}. 다운로드 중...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"업데이트 발견: {{version}}. 다운로드 중... {{time}}에서 마지막으로 확인했습니다.",
|
||||
pendingWithVersionProgress: "업데이트 발견: {{version}}. 다운로드 중... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"업데이트 발견: {{version}}. 다운로드 중... {{percent}}% {{time}}에서 마지막으로 확인했습니다.",
|
||||
downloadAvailableWithVersion: "사용 가능한 업데이트: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"사용 가능한 업데이트: {{version}}. {{time}}에서 마지막으로 확인했습니다.",
|
||||
downloadAvailable: "사용 가능한 앱 업데이트가 있습니다.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"사용 가능한 앱 업데이트가 있습니다. {{time}}에서 마지막으로 확인했습니다.",
|
||||
availableWithVersion: "업데이트 준비됨: {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"업데이트 준비됨: {{version}}. {{time}}에서 마지막으로 확인했습니다.",
|
||||
@@ -1567,14 +1578,21 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
installError: "데스크톱 앱 업데이트를 설치할 수 없습니다.",
|
||||
callout: {
|
||||
downloadingTitle: "업데이트 다운로드 중",
|
||||
installingTitle: "업데이트 설치 중",
|
||||
failedTitle: "업데이트 실패",
|
||||
availableTitle: "업데이트 사용 가능",
|
||||
genericError: "문제가 발생했습니다.",
|
||||
whatsNew: "새로운 기능",
|
||||
downloadingAction: "다운로드 중...",
|
||||
installingAction: "설치 중...",
|
||||
downloadAndRestart: "다운로드",
|
||||
installAndRestart: "설치 후 재시작",
|
||||
downloadingVersionDescription: "{{version}} 다운로드 중... {{percent}}%",
|
||||
downloadingDescription: "업데이트 다운로드 중... {{percent}}%",
|
||||
installingDescription: "설치 후 재시작 중...",
|
||||
versionAvailable: "{{version}} 버전을 다운로드할 수 있습니다.",
|
||||
newVersionAvailable: "새 버전을 다운로드할 수 있습니다.",
|
||||
versionReady: "{{version}} 설치가 준비되었습니다.",
|
||||
newVersionReady: "새 버전 설치가 준비되었습니다.",
|
||||
restartWarning: "앱을 업그레이드하면 실행 중인 에이전트가 중지되고 터미널 세션이 닫힙니다.",
|
||||
@@ -1825,9 +1843,6 @@ export const ko: TranslationResources = {
|
||||
editProfilesLabel: "에이전트 프로필 편집",
|
||||
createProfile: "프로필 만들기",
|
||||
createProfileFromModel: "이 모델에서 프로필 만들기",
|
||||
profileSaved: '"{{name}}" 저장됨',
|
||||
undo: "실행 취소",
|
||||
undoProfileSave: "프로필 저장 취소",
|
||||
editProfileLabel: "{{name}} 편집",
|
||||
editProfilesCount: "프로필 편집 ({{count}})",
|
||||
modelCount: "모델 {{count}}개",
|
||||
@@ -2408,7 +2423,6 @@ export const ko: TranslationResources = {
|
||||
projects: "프로젝트",
|
||||
connections: "연결",
|
||||
agents: "에이전트",
|
||||
agentProfiles: "에이전트 프로필",
|
||||
metadata: "메타데이터",
|
||||
voice: "음성",
|
||||
workspaces: "워크스페이스",
|
||||
@@ -2625,9 +2639,28 @@ export const ko: TranslationResources = {
|
||||
stable: "안정",
|
||||
beta: "베타",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "자동 업데이트",
|
||||
options: {
|
||||
automatic: "자동",
|
||||
notify: "알림만",
|
||||
off: "끄기",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "백그라운드에서 업데이트를 확인하고 다운로드합니다",
|
||||
notify: "업데이트를 확인하지만 선택할 때만 다운로드합니다",
|
||||
off: "자동으로 확인하지 않습니다. 확인 버튼을 누를 때만 확인합니다",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "앱 업데이트",
|
||||
readyToInstall: "설치 준비됨: {{version}}",
|
||||
downloadTitle: "데스크톱 업데이트 다운로드",
|
||||
downloadMessage: "이 컴퓨터에 Paseo 업데이트를 다운로드하고 설치합니다",
|
||||
downloadConfirm: "다운로드 및 설치",
|
||||
download: "다운로드",
|
||||
downloadTo: "{{version}} 다운로드",
|
||||
downloading: "다운로드 중...",
|
||||
installTitle: "데스크톱 업데이트 설치",
|
||||
installMessage: "이 컴퓨터의 Paseo를 업데이트합니다",
|
||||
installConfirm: "업데이트 설치",
|
||||
@@ -3040,31 +3073,6 @@ 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: {
|
||||
|
||||
@@ -1568,6 +1568,8 @@ export const ptBR: TranslationResources = {
|
||||
status: {
|
||||
checking: "Verificando atualizações do app...",
|
||||
installing: "Instalando atualização do app...",
|
||||
downloadingVersionProgress: "Baixando {{version}}... {{percent}}%",
|
||||
downloadingProgress: "Baixando atualização do app... {{percent}}%",
|
||||
upToDate: "O app está atualizado.",
|
||||
upToDateWithLastChecked: "Atualizado. Última verificação às {{time}}.",
|
||||
pending: "Avisaremos quando a atualização estiver pronta.",
|
||||
@@ -1576,6 +1578,15 @@ export const ptBR: TranslationResources = {
|
||||
pendingWithVersion: "Atualização encontrada: {{version}}. Baixando...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Atualização encontrada: {{version}}. Baixando... Última verificação às {{time}}.",
|
||||
pendingWithVersionProgress: "Atualização encontrada: {{version}}. Baixando... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Atualização encontrada: {{version}}. Baixando... {{percent}}% Última verificação às {{time}}.",
|
||||
downloadAvailableWithVersion: "Atualização disponível: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Atualização disponível: {{version}}. Última verificação às {{time}}.",
|
||||
downloadAvailable: "Há uma atualização do app disponível.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"Há uma atualização do app disponível. Última verificação às {{time}}.",
|
||||
availableWithVersion: "Atualização pronta: {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"Atualização pronta: {{version}}. Última verificação às {{time}}.",
|
||||
@@ -1588,14 +1599,21 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
installError: "Não foi possível instalar a atualização do app desktop.",
|
||||
callout: {
|
||||
downloadingTitle: "Baixando atualização",
|
||||
installingTitle: "Instalando atualização",
|
||||
failedTitle: "Falha na atualização",
|
||||
availableTitle: "Atualização disponível",
|
||||
genericError: "Algo deu errado.",
|
||||
whatsNew: "Novidades",
|
||||
downloadingAction: "Baixando...",
|
||||
installingAction: "Instalando...",
|
||||
downloadAndRestart: "Baixar",
|
||||
installAndRestart: "Instalar e reiniciar",
|
||||
downloadingVersionDescription: "Baixando {{version}}... {{percent}}%",
|
||||
downloadingDescription: "Baixando atualização... {{percent}}%",
|
||||
installingDescription: "Instalando e reiniciando...",
|
||||
versionAvailable: "{{version}} está disponível para download.",
|
||||
newVersionAvailable: "Uma nova versão está disponível para download.",
|
||||
versionReady: "{{version}} está pronta para instalar.",
|
||||
newVersionReady: "Uma nova versão está pronta para instalar.",
|
||||
restartWarning:
|
||||
@@ -1847,9 +1865,6 @@ 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",
|
||||
@@ -2432,7 +2447,6 @@ export const ptBR: TranslationResources = {
|
||||
projects: "Projetos",
|
||||
connections: "Conexões",
|
||||
agents: "Agentes",
|
||||
agentProfiles: "Perfis de agente",
|
||||
metadata: "Metadados",
|
||||
voice: "Voz",
|
||||
workspaces: "Workspaces",
|
||||
@@ -2650,9 +2664,28 @@ export const ptBR: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Atualizações automáticas",
|
||||
options: {
|
||||
automatic: "Auto",
|
||||
notify: "Notificar",
|
||||
off: "Desativado",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Verificar e baixar atualizações em segundo plano",
|
||||
notify: "Verificar atualizações, mas baixar apenas quando você escolher",
|
||||
off: "Nunca verificar automaticamente. Verificar apenas ao clicar em Verificar",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "Atualizações do app",
|
||||
readyToInstall: "Pronta para instalar: {{version}}",
|
||||
downloadTitle: "Baixar atualização desktop",
|
||||
downloadMessage: "Isso baixa e instala a atualização do Paseo neste computador",
|
||||
downloadConfirm: "Baixar e instalar",
|
||||
download: "Baixar",
|
||||
downloadTo: "Baixar {{version}}",
|
||||
downloading: "Baixando...",
|
||||
installTitle: "Instalar atualização desktop",
|
||||
installMessage: "Isso atualiza o Paseo neste computador",
|
||||
installConfirm: "Instalar atualização",
|
||||
@@ -3069,31 +3102,6 @@ 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: {
|
||||
|
||||
@@ -1562,6 +1562,8 @@ export const ru: TranslationResources = {
|
||||
status: {
|
||||
checking: "Проверка обновлений приложения...",
|
||||
installing: "Установка обновления приложения...",
|
||||
downloadingVersionProgress: "Загрузка {{version}}... {{percent}}%",
|
||||
downloadingProgress: "Загрузка обновления приложения... {{percent}}%",
|
||||
upToDate: "Установлена последняя версия приложения.",
|
||||
upToDateWithLastChecked:
|
||||
"Установлена последняя версия приложения. Последняя проверка: {{time}}.",
|
||||
@@ -1571,6 +1573,15 @@ export const ru: TranslationResources = {
|
||||
pendingWithVersion: "Найдено обновление: {{version}}. Загрузка...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"Найдено обновление: {{version}}. Загрузка... Последняя проверка в {{time}}.",
|
||||
pendingWithVersionProgress: "Найдено обновление: {{version}}. Загрузка... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"Найдено обновление: {{version}}. Загрузка... {{percent}}% Последняя проверка в {{time}}.",
|
||||
downloadAvailableWithVersion: "Доступно обновление: {{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"Доступно обновление: {{version}}. Последняя проверка: {{time}}.",
|
||||
downloadAvailable: "Доступно обновление приложения.",
|
||||
downloadAvailableWithLastChecked:
|
||||
"Доступно обновление приложения. Последняя проверка: {{time}}.",
|
||||
availableWithVersion: "Обновление готово: {{version}}",
|
||||
availableWithVersionAndLastChecked:
|
||||
"Обновление готово: {{version}}. Последняя проверка: {{time}}.",
|
||||
@@ -1583,14 +1594,21 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
installError: "Не удалось установить обновление настольного приложения.",
|
||||
callout: {
|
||||
downloadingTitle: "Загрузка обновления",
|
||||
installingTitle: "Установка обновления",
|
||||
failedTitle: "Обновление не выполнено",
|
||||
availableTitle: "Доступно обновление",
|
||||
genericError: "Что-то пошло не так.",
|
||||
whatsNew: "Что нового",
|
||||
downloadingAction: "Загрузка...",
|
||||
installingAction: "Установка...",
|
||||
downloadAndRestart: "Скачать",
|
||||
installAndRestart: "Установить и перезапустить",
|
||||
downloadingVersionDescription: "Загрузка {{version}}... {{percent}}%",
|
||||
downloadingDescription: "Загрузка обновления... {{percent}}%",
|
||||
installingDescription: "Установка и перезапуск...",
|
||||
versionAvailable: "Версия {{version}} доступна для загрузки.",
|
||||
newVersionAvailable: "Новая версия доступна для загрузки.",
|
||||
versionReady: "Версия {{version}} готова к установке.",
|
||||
newVersionReady: "Новая версия готова к установке.",
|
||||
restartWarning:
|
||||
@@ -1847,9 +1865,6 @@ export const ru: TranslationResources = {
|
||||
editProfilesLabel: "Изменить профили агентов",
|
||||
createProfile: "Создать профиль",
|
||||
createProfileFromModel: "Создать профиль из этой модели",
|
||||
profileSaved: "Сохранено: «{{name}}»",
|
||||
undo: "Отменить",
|
||||
undoProfileSave: "Отменить сохранение профиля",
|
||||
editProfileLabel: "Изменить {{name}}",
|
||||
editProfilesCount: "Изменить профили ({{count}})",
|
||||
modelCount: "{{count}} модель",
|
||||
@@ -2434,7 +2449,6 @@ export const ru: TranslationResources = {
|
||||
projects: "Проекты",
|
||||
connections: "Подключения",
|
||||
agents: "Агенты",
|
||||
agentProfiles: "Профили агентов",
|
||||
metadata: "Метаданные",
|
||||
voice: "Голос",
|
||||
workspaces: "Рабочие пространства",
|
||||
@@ -2657,9 +2671,28 @@ export const ru: TranslationResources = {
|
||||
stable: "Стабильный",
|
||||
beta: "Бета",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "Автообновления",
|
||||
options: {
|
||||
automatic: "Авто",
|
||||
notify: "Уведомлять",
|
||||
off: "Выкл.",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "Проверять и загружать обновления в фоновом режиме",
|
||||
notify: "Проверять обновления, но загружать только по вашему выбору",
|
||||
off: "Не проверять автоматически. Проверять только по нажатию кнопки Проверить",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "Обновления приложения",
|
||||
readyToInstall: "Версия {{version}} готова к установке",
|
||||
downloadTitle: "Загрузить обновление настольного приложения",
|
||||
downloadMessage: "Это загрузит и установит обновление Paseo на этом компьютере.",
|
||||
downloadConfirm: "Загрузить и установить",
|
||||
download: "Загрузить",
|
||||
downloadTo: "Загрузить {{version}}",
|
||||
downloading: "Загрузка...",
|
||||
installTitle: "Установить обновление настольного приложения",
|
||||
installMessage: "Это обновит Paseo на этом компьютере.",
|
||||
installConfirm: "Установить обновление",
|
||||
@@ -3080,31 +3113,6 @@ 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: {
|
||||
|
||||
@@ -1528,6 +1528,8 @@ export const zhCN: TranslationResources = {
|
||||
status: {
|
||||
checking: "正在检查 app 更新...",
|
||||
installing: "正在安装 app 更新...",
|
||||
downloadingVersionProgress: "正在下载 {{version}}... {{percent}}%",
|
||||
downloadingProgress: "正在下载 app 更新... {{percent}}%",
|
||||
upToDate: "App 已是最新版本。",
|
||||
upToDateWithLastChecked: "已是最新版本。上次检查时间:{{time}}。",
|
||||
pending: "更新准备好后会通知你。",
|
||||
@@ -1535,6 +1537,14 @@ export const zhCN: TranslationResources = {
|
||||
pendingWithVersion: "发现更新:{{version}}。正在下载...",
|
||||
pendingWithVersionAndLastChecked:
|
||||
"发现更新:{{version}}。正在下载... 上次检查时间:{{time}}。",
|
||||
pendingWithVersionProgress: "发现更新:{{version}}。正在下载... {{percent}}%",
|
||||
pendingWithVersionProgressAndLastChecked:
|
||||
"发现更新:{{version}}。正在下载... {{percent}}% 上次检查时间:{{time}}。",
|
||||
downloadAvailableWithVersion: "有可用更新:{{version}}",
|
||||
downloadAvailableWithVersionAndLastChecked:
|
||||
"有可用更新:{{version}}。上次检查时间:{{time}}。",
|
||||
downloadAvailable: "有 app 更新可用。",
|
||||
downloadAvailableWithLastChecked: "有 app 更新可用。上次检查时间:{{time}}。",
|
||||
availableWithVersion: "更新已就绪:{{version}}",
|
||||
availableWithVersionAndLastChecked: "更新已就绪:{{version}}。上次检查时间:{{time}}。",
|
||||
available: "有 app 更新可安装。",
|
||||
@@ -1545,14 +1555,21 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
installError: "无法安装 desktop app 更新。",
|
||||
callout: {
|
||||
downloadingTitle: "正在下载更新",
|
||||
installingTitle: "正在安装更新",
|
||||
failedTitle: "更新失败",
|
||||
availableTitle: "有可用更新",
|
||||
genericError: "出了点问题。",
|
||||
whatsNew: "更新内容",
|
||||
downloadingAction: "正在下载...",
|
||||
installingAction: "正在安装...",
|
||||
downloadAndRestart: "下载",
|
||||
installAndRestart: "安装并重启",
|
||||
downloadingVersionDescription: "正在下载 {{version}}... {{percent}}%",
|
||||
downloadingDescription: "正在下载更新... {{percent}}%",
|
||||
installingDescription: "正在安装并重启...",
|
||||
versionAvailable: "{{version}} 可供下载。",
|
||||
newVersionAvailable: "有新版本可供下载。",
|
||||
versionReady: "{{version}} 已准备好安装。",
|
||||
newVersionReady: "新版本已准备好安装。",
|
||||
restartWarning: "升级 app 会停止正在运行的 agents,并关闭 terminal 会话。",
|
||||
@@ -1796,9 +1813,6 @@ export const zhCN: TranslationResources = {
|
||||
editProfilesLabel: "编辑智能体配置文件",
|
||||
createProfile: "创建配置文件",
|
||||
createProfileFromModel: "从此模型创建配置文件",
|
||||
profileSaved: "已保存“{{name}}”",
|
||||
undo: "撤销",
|
||||
undoProfileSave: "撤销保存配置文件",
|
||||
editProfileLabel: "编辑 {{name}}",
|
||||
editProfilesCount: "编辑配置文件 ({{count}})",
|
||||
modelCount: "{{count}} 个模型",
|
||||
@@ -2374,7 +2388,6 @@ export const zhCN: TranslationResources = {
|
||||
projects: "项目",
|
||||
connections: "连接",
|
||||
agents: "Agents",
|
||||
agentProfiles: "智能体配置文件",
|
||||
metadata: "元数据",
|
||||
voice: "语音",
|
||||
workspaces: "Workspaces",
|
||||
@@ -2584,9 +2597,28 @@ export const zhCN: TranslationResources = {
|
||||
stable: "Stable",
|
||||
beta: "Beta",
|
||||
},
|
||||
autoUpdate: {
|
||||
label: "自动更新",
|
||||
options: {
|
||||
automatic: "自动",
|
||||
notify: "仅通知",
|
||||
off: "关闭",
|
||||
},
|
||||
descriptions: {
|
||||
automatic: "在后台检查并下载更新",
|
||||
notify: "检查更新,但仅在你选择时才下载",
|
||||
off: "从不自动检查,仅在点击检查时检查更新",
|
||||
},
|
||||
},
|
||||
updates: {
|
||||
label: "应用更新",
|
||||
readyToInstall: "可安装:{{version}}",
|
||||
downloadTitle: "下载桌面版更新",
|
||||
downloadMessage: "这会在此电脑上下载并安装 Paseo 更新",
|
||||
downloadConfirm: "下载并安装",
|
||||
download: "下载",
|
||||
downloadTo: "下载 {{version}}",
|
||||
downloading: "正在下载...",
|
||||
installTitle: "安装桌面版更新",
|
||||
installMessage: "这会更新此电脑上的 Paseo",
|
||||
installConfirm: "安装更新",
|
||||
@@ -2995,31 +3027,6 @@ 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: {
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
export interface RouteLeaveGuard {
|
||||
isDirty: () => boolean;
|
||||
confirmDiscard: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the web browser history (`popstate`) guard before Expo Router mounts
|
||||
* its own `popstate` listener. No-op on native, where React Navigation's
|
||||
* `beforeRemove` owns swipe-back and hardware Back interception.
|
||||
*/
|
||||
export function installRouteLeavePopStateGuard(): void {
|
||||
// Native platforms handle back navigation through React Navigation's beforeRemove event.
|
||||
}
|
||||
|
||||
/** Registers the active screen's leave guard for browser Back/Forward interception. */
|
||||
export function registerRouteLeaveGuard(_guard: RouteLeaveGuard | null): () => void {
|
||||
return () => {};
|
||||
}
|
||||
@@ -1,268 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createWebPopStateGuard,
|
||||
type PopStateStorageLike,
|
||||
type PopStateWindowLike,
|
||||
} from "./index.web";
|
||||
|
||||
interface FakeHistoryEntry {
|
||||
state: unknown;
|
||||
path: string;
|
||||
}
|
||||
|
||||
function createMemoryStorage(): PopStateStorageLike {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
store.set(key, value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createFakeWindow(
|
||||
initialEntries: FakeHistoryEntry[],
|
||||
options?: { index?: number; sessionStorage?: PopStateStorageLike },
|
||||
) {
|
||||
let entries: FakeHistoryEntry[] = [...initialEntries];
|
||||
let index = options?.index ?? entries.length - 1;
|
||||
const listeners: Array<(event: PopStateEvent) => void> = [];
|
||||
|
||||
const current = () => entries[index] ?? { state: null, path: "/" };
|
||||
|
||||
const dispatchPopState = (state: unknown) => {
|
||||
let stopped = false;
|
||||
const event = {
|
||||
state,
|
||||
stopImmediatePropagation() {
|
||||
stopped = true;
|
||||
},
|
||||
} as unknown as PopStateEvent;
|
||||
for (const listener of listeners.slice()) {
|
||||
if (stopped) {
|
||||
break;
|
||||
}
|
||||
listener(event);
|
||||
}
|
||||
return { stopped };
|
||||
};
|
||||
|
||||
const win: PopStateWindowLike = {
|
||||
...(options?.sessionStorage ? { sessionStorage: options.sessionStorage } : {}),
|
||||
history: {
|
||||
get state() {
|
||||
return current().state;
|
||||
},
|
||||
pushState(state, _unused, url) {
|
||||
const path = typeof url === "string" ? url : String(url ?? "/");
|
||||
entries = entries.slice(0, index + 1);
|
||||
entries.push({ state, path });
|
||||
index = entries.length - 1;
|
||||
},
|
||||
replaceState(state, _unused, url) {
|
||||
const path = typeof url === "string" ? url : String(url ?? "/");
|
||||
entries[index] = { state, path };
|
||||
},
|
||||
go(delta = 0) {
|
||||
const nextIndex = index + delta;
|
||||
if (nextIndex < 0 || nextIndex >= entries.length || nextIndex === index) {
|
||||
return;
|
||||
}
|
||||
index = nextIndex;
|
||||
dispatchPopState(current().state);
|
||||
},
|
||||
},
|
||||
addEventListener(_type, listener) {
|
||||
listeners.push(listener);
|
||||
},
|
||||
removeEventListener(_type, listener) {
|
||||
const idx = listeners.indexOf(listener);
|
||||
if (idx >= 0) {
|
||||
listeners.splice(idx, 1);
|
||||
}
|
||||
},
|
||||
dispatchEvent(event) {
|
||||
const popEvent = event as PopStateEvent;
|
||||
dispatchPopState(popEvent.state);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
win,
|
||||
getPath: () => current().path,
|
||||
getEntries: () => entries.map((entry) => entry.path),
|
||||
getIndex: () => index,
|
||||
simulateHistoryJump: (delta: number) => {
|
||||
const nextIndex = index + delta;
|
||||
index = Math.max(0, Math.min(entries.length - 1, nextIndex));
|
||||
return dispatchPopState(current().state);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("createWebPopStateGuard", () => {
|
||||
it("preserves intervening history entries when canceling a two-step Back jump", async () => {
|
||||
const fake = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }], {
|
||||
sessionStorage: createMemoryStorage(),
|
||||
});
|
||||
const guard = createWebPopStateGuard(fake.win);
|
||||
guard.install();
|
||||
|
||||
const routerSeenPaths: string[] = [];
|
||||
fake.win.addEventListener("popstate", () => {
|
||||
routerSeenPaths.push(fake.getPath());
|
||||
});
|
||||
|
||||
fake.win.history.pushState({ id: "id-1" }, "", "/settings");
|
||||
fake.win.history.pushState({ id: "id-2" }, "", "/settings/hosts/srv/agent-profiles");
|
||||
|
||||
let dirty = true;
|
||||
guard.register({
|
||||
isDirty: () => dirty,
|
||||
confirmDiscard: async () => false,
|
||||
});
|
||||
|
||||
// Jump straight from Agent profiles back two entries to Open project and cancel.
|
||||
const { stopped } = fake.simulateHistoryJump(-2);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(stopped).toBe(true);
|
||||
expect(routerSeenPaths).toEqual([]);
|
||||
expect(fake.getPath()).toBe("/settings/hosts/srv/agent-profiles");
|
||||
expect(fake.getEntries()).toEqual([
|
||||
"/open-project",
|
||||
"/settings",
|
||||
"/settings/hosts/srv/agent-profiles",
|
||||
]);
|
||||
expect(fake.getIndex()).toBe(2);
|
||||
|
||||
// After closing the editor, a normal one-step Back still reaches Settings.
|
||||
dirty = false;
|
||||
fake.simulateHistoryJump(-1);
|
||||
expect(fake.getPath()).toBe("/settings");
|
||||
expect(routerSeenPaths).toEqual(["/settings"]);
|
||||
});
|
||||
|
||||
it("restores the editor URL on a two-step Back jump after a reload (with sessionStorage)", async () => {
|
||||
const storage = createMemoryStorage();
|
||||
const beforeReload = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }], {
|
||||
sessionStorage: storage,
|
||||
});
|
||||
const firstGuard = createWebPopStateGuard(beforeReload.win);
|
||||
firstGuard.install();
|
||||
beforeReload.win.history.pushState({ id: "id-1" }, "", "/settings");
|
||||
beforeReload.win.history.pushState({ id: "id-2" }, "", "/settings/hosts/srv/agent-profiles");
|
||||
firstGuard.dispose();
|
||||
|
||||
// Simulate reload on Agent profiles with the same browser history and tab sessionStorage.
|
||||
const afterReload = createFakeWindow(
|
||||
[
|
||||
{ state: { id: "id-0" }, path: "/open-project" },
|
||||
{ state: { id: "id-1" }, path: "/settings" },
|
||||
{ state: { id: "id-2" }, path: "/settings/hosts/srv/agent-profiles" },
|
||||
],
|
||||
{ index: 2, sessionStorage: storage },
|
||||
);
|
||||
const guard = createWebPopStateGuard(afterReload.win);
|
||||
guard.install();
|
||||
guard.register({
|
||||
isDirty: () => true,
|
||||
confirmDiscard: async () => false,
|
||||
});
|
||||
|
||||
afterReload.simulateHistoryJump(-2);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(afterReload.getPath()).toBe("/settings/hosts/srv/agent-profiles");
|
||||
expect(afterReload.getIndex()).toBe(2);
|
||||
});
|
||||
|
||||
it("steps back to the exact editor entry after a reload even without sessionStorage", async () => {
|
||||
const afterReload = createFakeWindow(
|
||||
[
|
||||
{ state: { id: "id-0" }, path: "/open-project" },
|
||||
{ state: { id: "id-1" }, path: "/settings" },
|
||||
{ state: { id: "id-2" }, path: "/settings/hosts/srv/agent-profiles" },
|
||||
],
|
||||
{ index: 2 },
|
||||
);
|
||||
const guard = createWebPopStateGuard(afterReload.win);
|
||||
guard.install();
|
||||
|
||||
const routerSeenPaths: string[] = [];
|
||||
afterReload.win.addEventListener("popstate", () => {
|
||||
routerSeenPaths.push(afterReload.getPath());
|
||||
});
|
||||
|
||||
guard.register({
|
||||
isDirty: () => true,
|
||||
confirmDiscard: async () => false,
|
||||
});
|
||||
|
||||
afterReload.simulateHistoryJump(-2);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(routerSeenPaths).toEqual([]);
|
||||
expect(afterReload.getPath()).toBe("/settings/hosts/srv/agent-profiles");
|
||||
expect(afterReload.getIndex()).toBe(2);
|
||||
});
|
||||
|
||||
it("reaches the exact two-step destination when confirming a multi-step Back jump", async () => {
|
||||
const fake = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }], {
|
||||
sessionStorage: createMemoryStorage(),
|
||||
});
|
||||
const guard = createWebPopStateGuard(fake.win);
|
||||
guard.install();
|
||||
|
||||
const routerSeenPaths: string[] = [];
|
||||
fake.win.addEventListener("popstate", () => {
|
||||
routerSeenPaths.push(fake.getPath());
|
||||
});
|
||||
|
||||
fake.win.history.pushState({ id: "id-1" }, "", "/settings");
|
||||
fake.win.history.pushState({ id: "id-2" }, "", "/settings/hosts/srv/agent-profiles");
|
||||
|
||||
let dirty = true;
|
||||
guard.register({
|
||||
isDirty: () => dirty,
|
||||
confirmDiscard: async () => {
|
||||
dirty = false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
fake.simulateHistoryJump(-2);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(routerSeenPaths).toEqual(["/open-project"]);
|
||||
expect(fake.getPath()).toBe("/open-project");
|
||||
expect(fake.getIndex()).toBe(0);
|
||||
});
|
||||
|
||||
it("passes browser Back straight through when the guard is not dirty", () => {
|
||||
const fake = createFakeWindow([{ state: { id: "id-0" }, path: "/open-project" }]);
|
||||
const guard = createWebPopStateGuard(fake.win);
|
||||
guard.install();
|
||||
|
||||
let routerSawPopState = 0;
|
||||
fake.win.addEventListener("popstate", () => {
|
||||
routerSawPopState += 1;
|
||||
});
|
||||
|
||||
fake.win.history.pushState({ id: "id-1" }, "", "/settings/hosts/srv/agent-profiles");
|
||||
|
||||
guard.register({
|
||||
isDirty: () => false,
|
||||
confirmDiscard: async () => {
|
||||
throw new Error("should not prompt when clean");
|
||||
},
|
||||
});
|
||||
|
||||
const { stopped } = fake.simulateHistoryJump(-1);
|
||||
|
||||
expect(stopped).toBe(false);
|
||||
expect(routerSawPopState).toBe(1);
|
||||
expect(fake.getPath()).toBe("/open-project");
|
||||
});
|
||||
});
|
||||
@@ -1,307 +0,0 @@
|
||||
import type { RouteLeaveGuard } from "./index";
|
||||
|
||||
export type { RouteLeaveGuard } from "./index";
|
||||
|
||||
const HISTORY_STORAGE_KEY = "@paseo:route-leave-history:v1";
|
||||
const MAX_REVERT_STEPS = 20;
|
||||
const REVERT_TIMEOUT_MS = 400;
|
||||
|
||||
export interface PopStateStorageLike {
|
||||
getItem(key: string): string | null;
|
||||
setItem(key: string, value: string): void;
|
||||
}
|
||||
|
||||
export interface PopStateWindowLike {
|
||||
history: {
|
||||
readonly state: unknown;
|
||||
pushState(data: unknown, unused: string, url?: string | URL | null): void;
|
||||
replaceState(data: unknown, unused: string, url?: string | URL | null): void;
|
||||
go(delta?: number): void;
|
||||
};
|
||||
sessionStorage?: PopStateStorageLike;
|
||||
addEventListener(type: "popstate", listener: (event: PopStateEvent) => void): void;
|
||||
removeEventListener(type: "popstate", listener: (event: PopStateEvent) => void): void;
|
||||
dispatchEvent(event: Event): boolean;
|
||||
}
|
||||
|
||||
export interface WebPopStateGuardController {
|
||||
install(): void;
|
||||
register(guard: RouteLeaveGuard | null): () => void;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
function readHistoryStateId(state: unknown): string | null {
|
||||
if (typeof state === "object" && state !== null && "id" in state) {
|
||||
const id = (state as { id?: unknown }).id;
|
||||
return typeof id === "string" && id.length > 0 ? id : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function createPopStateEvent(state: unknown): PopStateEvent {
|
||||
if (typeof PopStateEvent === "function") {
|
||||
return new PopStateEvent("popstate", { state });
|
||||
}
|
||||
const event = new Event("popstate") as PopStateEvent;
|
||||
Object.defineProperty(event, "state", { value: state });
|
||||
return event;
|
||||
}
|
||||
|
||||
function loadStoredEntryIds(storage: PopStateStorageLike | undefined): Array<string | null> | null {
|
||||
if (!storage) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const raw = storage.getItem(HISTORY_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (!Array.isArray(parsed)) {
|
||||
return null;
|
||||
}
|
||||
if (!parsed.every((item) => item === null || typeof item === "string")) {
|
||||
return null;
|
||||
}
|
||||
return parsed as Array<string | null>;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function persistEntryIds(
|
||||
storage: PopStateStorageLike | undefined,
|
||||
entryIds: readonly (string | null)[],
|
||||
): void {
|
||||
if (!storage) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
storage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(entryIds));
|
||||
} catch {
|
||||
// Ignore storage quota or private-mode restrictions; fallback stepping still works.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Intercepts browser Back/Forward (`popstate`) before Expo Router's
|
||||
* `createMemoryHistory` listener runs.
|
||||
*
|
||||
* Tracks the ordered history entry IDs written by Expo Router (persisted in
|
||||
* `sessionStorage` so reloads keep the tab's full index). Canceling any
|
||||
* traversal reverts via `history.go(delta)` without calling `pushState` or
|
||||
* truncating intervening entries — and verifies it landed back on the saved
|
||||
* entry ID (stepping forward if pre-reload history was unknown). Confirming
|
||||
* replays `popstate` at the browser's exact selected destination.
|
||||
*/
|
||||
export function createWebPopStateGuard(win: PopStateWindowLike): WebPopStateGuardController {
|
||||
let installed = false;
|
||||
let activeGuard: RouteLeaveGuard | null = null;
|
||||
let confirmInFlight = false;
|
||||
let isReverting = false;
|
||||
let revertingTargetId: string | null = null;
|
||||
let revertStepDirection: 1 | -1 = 1;
|
||||
let revertStepsRemaining = 0;
|
||||
let isReplaying = false;
|
||||
let revertResetTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let entryIds: Array<string | null> = [];
|
||||
let currentIdx = 0;
|
||||
|
||||
let origPushState: PopStateWindowLike["history"]["pushState"] | null = null;
|
||||
let origReplaceState: PopStateWindowLike["history"]["replaceState"] | null = null;
|
||||
|
||||
const clearRevertState = () => {
|
||||
isReverting = false;
|
||||
revertingTargetId = null;
|
||||
revertStepsRemaining = 0;
|
||||
if (revertResetTimer !== null) {
|
||||
clearTimeout(revertResetTimer);
|
||||
revertResetTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const armRevertTimer = () => {
|
||||
if (revertResetTimer !== null) {
|
||||
clearTimeout(revertResetTimer);
|
||||
}
|
||||
revertResetTimer = setTimeout(() => {
|
||||
clearRevertState();
|
||||
}, REVERT_TIMEOUT_MS);
|
||||
};
|
||||
|
||||
const revertToSavedEntry = (savedId: string | null, returnDelta: number) => {
|
||||
isReverting = true;
|
||||
revertingTargetId = savedId;
|
||||
revertStepDirection = returnDelta >= 0 ? 1 : -1;
|
||||
revertStepsRemaining = MAX_REVERT_STEPS;
|
||||
armRevertTimer();
|
||||
win.history.go(returnDelta);
|
||||
};
|
||||
|
||||
const resolveTargetIndex = (state: unknown): number => {
|
||||
const targetId = readHistoryStateId(state);
|
||||
if (!targetId) {
|
||||
return -1;
|
||||
}
|
||||
return entryIds.indexOf(targetId);
|
||||
};
|
||||
|
||||
const handleRevertPopState = (event: PopStateEvent) => {
|
||||
event.stopImmediatePropagation();
|
||||
const landedId = readHistoryStateId(event.state);
|
||||
if (revertingTargetId !== null && landedId !== revertingTargetId && revertStepsRemaining > 0) {
|
||||
revertStepsRemaining -= 1;
|
||||
armRevertTimer();
|
||||
win.history.go(revertStepDirection);
|
||||
return;
|
||||
}
|
||||
const landedIdx = resolveTargetIndex(event.state);
|
||||
if (landedIdx >= 0) {
|
||||
currentIdx = landedIdx;
|
||||
}
|
||||
clearRevertState();
|
||||
};
|
||||
|
||||
const handlePopState = (event: PopStateEvent) => {
|
||||
if (isReverting) {
|
||||
handleRevertPopState(event);
|
||||
return;
|
||||
}
|
||||
|
||||
const targetIdx = resolveTargetIndex(event.state);
|
||||
|
||||
if (isReplaying) {
|
||||
isReplaying = false;
|
||||
if (targetIdx >= 0) {
|
||||
currentIdx = targetIdx;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const guard = activeGuard;
|
||||
if (!guard?.isDirty()) {
|
||||
if (targetIdx >= 0) {
|
||||
currentIdx = targetIdx;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
event.stopImmediatePropagation();
|
||||
const savedId = entryIds[currentIdx] ?? null;
|
||||
const returnDelta = targetIdx >= 0 ? currentIdx - targetIdx : 1;
|
||||
|
||||
if (confirmInFlight) {
|
||||
if (returnDelta !== 0) {
|
||||
revertToSavedEntry(savedId, returnDelta);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
confirmInFlight = true;
|
||||
const confirmAndResolve = async () => {
|
||||
try {
|
||||
const confirmed = await guard.confirmDiscard();
|
||||
if (confirmed) {
|
||||
isReplaying = true;
|
||||
win.dispatchEvent(createPopStateEvent(event.state));
|
||||
} else if (returnDelta !== 0) {
|
||||
revertToSavedEntry(savedId, returnDelta);
|
||||
}
|
||||
} finally {
|
||||
confirmInFlight = false;
|
||||
}
|
||||
};
|
||||
void confirmAndResolve();
|
||||
};
|
||||
|
||||
return {
|
||||
install() {
|
||||
if (installed) {
|
||||
return;
|
||||
}
|
||||
installed = true;
|
||||
const initialId = readHistoryStateId(win.history.state);
|
||||
const stored = loadStoredEntryIds(win.sessionStorage);
|
||||
const storedIdx = stored && initialId ? stored.indexOf(initialId) : -1;
|
||||
if (stored && storedIdx >= 0) {
|
||||
entryIds = stored;
|
||||
currentIdx = storedIdx;
|
||||
} else {
|
||||
entryIds = [initialId];
|
||||
currentIdx = 0;
|
||||
persistEntryIds(win.sessionStorage, entryIds);
|
||||
}
|
||||
|
||||
origPushState = win.history.pushState;
|
||||
origReplaceState = win.history.replaceState;
|
||||
|
||||
win.history.pushState = (data, unused, url) => {
|
||||
origPushState?.call(win.history, data, unused, url);
|
||||
entryIds = entryIds.slice(0, currentIdx + 1);
|
||||
entryIds.push(readHistoryStateId(data));
|
||||
currentIdx = entryIds.length - 1;
|
||||
persistEntryIds(win.sessionStorage, entryIds);
|
||||
};
|
||||
|
||||
win.history.replaceState = (data, unused, url) => {
|
||||
origReplaceState?.call(win.history, data, unused, url);
|
||||
entryIds[currentIdx] = readHistoryStateId(data);
|
||||
persistEntryIds(win.sessionStorage, entryIds);
|
||||
};
|
||||
|
||||
win.addEventListener("popstate", handlePopState);
|
||||
},
|
||||
register(guard) {
|
||||
activeGuard = guard;
|
||||
return () => {
|
||||
if (activeGuard === guard) {
|
||||
activeGuard = null;
|
||||
}
|
||||
};
|
||||
},
|
||||
dispose() {
|
||||
if (!installed) {
|
||||
return;
|
||||
}
|
||||
installed = false;
|
||||
activeGuard = null;
|
||||
confirmInFlight = false;
|
||||
isReplaying = false;
|
||||
clearRevertState();
|
||||
win.removeEventListener("popstate", handlePopState);
|
||||
if (origPushState) {
|
||||
win.history.pushState = origPushState;
|
||||
origPushState = null;
|
||||
}
|
||||
if (origReplaceState) {
|
||||
win.history.replaceState = origReplaceState;
|
||||
origReplaceState = null;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let sharedController: WebPopStateGuardController | null = null;
|
||||
|
||||
function getSharedController(): WebPopStateGuardController | null {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
if (!sharedController) {
|
||||
sharedController = createWebPopStateGuard(window);
|
||||
}
|
||||
return sharedController;
|
||||
}
|
||||
|
||||
export function installRouteLeavePopStateGuard(): void {
|
||||
getSharedController()?.install();
|
||||
}
|
||||
|
||||
export function registerRouteLeaveGuard(guard: RouteLeaveGuard | null): () => void {
|
||||
const controller = getSharedController();
|
||||
if (!controller) {
|
||||
return () => {};
|
||||
}
|
||||
controller.install();
|
||||
return controller.register(guard);
|
||||
}
|
||||
@@ -10,7 +10,6 @@ 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";
|
||||
@@ -200,7 +199,6 @@ export function PluginSurfaceScreen() {
|
||||
const headerLeft = useMemo(
|
||||
() => (
|
||||
<>
|
||||
<SidebarMenuToggle />
|
||||
{icon ? (
|
||||
<HeaderIconBadge>
|
||||
<ThemedPluginHeaderIcon icon={icon} uniProps={mutedColorMapping} />
|
||||
|
||||
@@ -6,7 +6,6 @@ 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.
|
||||
@@ -23,11 +22,6 @@ export function RootApp() {
|
||||
}
|
||||
|
||||
export function RootRouter({ context: routes }: Pick<ComponentProps<typeof ExpoRoot>, "context">) {
|
||||
// Attach the web popstate guard before ExpoRoot's effect registers its history listener.
|
||||
useState(() => {
|
||||
installRouteLeavePopStateGuard();
|
||||
return true;
|
||||
});
|
||||
const [generation, setGeneration] = useState(0);
|
||||
const reload = useCallback(() => setGeneration((value) => value + 1), []);
|
||||
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
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, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { Alert, Pressable, ScrollView, View, type PressableStateCallbackType } from "react-native";
|
||||
import { useNavigation, useRouter } from "expo-router";
|
||||
import { useFocusEffect, usePreventRemove } from "expo-router/react-navigation";
|
||||
import { useRouter } from "expo-router";
|
||||
import { useFocusEffect } 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";
|
||||
@@ -41,7 +40,6 @@ import {
|
||||
PanelLeft,
|
||||
MessageSquare,
|
||||
ChevronRight,
|
||||
Layers,
|
||||
} from "lucide-react-native";
|
||||
import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
|
||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||
@@ -85,6 +83,7 @@ import { DesktopNotificationsSection } from "@/desktop/components/desktop-notifi
|
||||
import { BrowserDataSection } from "@/desktop/browser/settings/browser-data-section";
|
||||
import { IntegrationsSection } from "@/desktop/components/integrations-section";
|
||||
import { isElectronRuntime } from "@/desktop/host";
|
||||
import { useDesktopSettings, type DesktopUpdateMode } from "@/desktop/settings/desktop-settings";
|
||||
import { useDesktopAppUpdater } from "@/desktop/updates/use-desktop-app-updater";
|
||||
import { formatVersionWithPrefix } from "@/desktop/updates/desktop-updates";
|
||||
import { resolveAppVersion } from "@/utils/app-version";
|
||||
@@ -104,7 +103,6 @@ import {
|
||||
HostConnectionsPage,
|
||||
HostPairDevicePage,
|
||||
HostAgentsPage,
|
||||
HostAgentProfilesPage,
|
||||
HostSettingsPage,
|
||||
HostProvidersPage,
|
||||
HostUsagePage,
|
||||
@@ -252,7 +250,6 @@ 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 },
|
||||
@@ -275,9 +272,6 @@ function renderHostSettingsContent(
|
||||
return <HostPairDevicePage serverId={view.serverId} />;
|
||||
case "agents":
|
||||
return <HostAgentsPage serverId={view.serverId} />;
|
||||
case "agent-profiles":
|
||||
// Rendered directly in SettingsScreen so AgentProfilesPage owns its wide PageLayout + drawer split.
|
||||
return null;
|
||||
case "metadata":
|
||||
return <MetadataGenerationPage serverId={view.serverId} />;
|
||||
case "voice":
|
||||
@@ -616,25 +610,92 @@ function HostVersionRow({
|
||||
|
||||
function getUpdateButtonLabel(
|
||||
t: TFunction,
|
||||
isInstalling: boolean,
|
||||
latestVersion: string | null | undefined,
|
||||
input: {
|
||||
isInstalling: boolean;
|
||||
isDownloading: boolean;
|
||||
isActionable: boolean;
|
||||
readyToInstall: boolean;
|
||||
latestVersion: string | null | undefined;
|
||||
},
|
||||
): string {
|
||||
if (isInstalling) return t("settings.about.updates.installing");
|
||||
if (latestVersion) {
|
||||
if (input.isInstalling) {
|
||||
return input.isDownloading
|
||||
? t("settings.about.updates.downloading")
|
||||
: t("settings.about.updates.installing");
|
||||
}
|
||||
if (input.isActionable && !input.readyToInstall) {
|
||||
if (input.latestVersion) {
|
||||
return t("settings.about.updates.downloadTo", {
|
||||
version: formatVersionWithPrefix(input.latestVersion),
|
||||
});
|
||||
}
|
||||
return t("settings.about.updates.download");
|
||||
}
|
||||
if (input.latestVersion) {
|
||||
return t("settings.about.updates.updateTo", {
|
||||
version: formatVersionWithPrefix(latestVersion),
|
||||
version: formatVersionWithPrefix(input.latestVersion),
|
||||
});
|
||||
}
|
||||
return t("settings.about.updates.update");
|
||||
}
|
||||
|
||||
function getUpdateModeDescription(t: TFunction, mode: DesktopUpdateMode): string {
|
||||
if (mode === "off") return t("settings.about.autoUpdate.descriptions.off");
|
||||
if (mode === "notify") return t("settings.about.autoUpdate.descriptions.notify");
|
||||
return t("settings.about.autoUpdate.descriptions.automatic");
|
||||
}
|
||||
|
||||
function getUpdateConfirmDialogCopy(t: TFunction, isUpdateReady: boolean) {
|
||||
if (isUpdateReady) {
|
||||
return {
|
||||
title: t("settings.about.updates.installTitle"),
|
||||
message: t("settings.about.updates.installMessage"),
|
||||
confirmLabel: t("settings.about.updates.installConfirm"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: t("settings.about.updates.downloadTitle"),
|
||||
message: t("settings.about.updates.downloadMessage"),
|
||||
confirmLabel: t("settings.about.updates.downloadConfirm"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
};
|
||||
}
|
||||
|
||||
function DesktopUpdateProgressBar({ percent }: { percent: number }) {
|
||||
const accessibilityValue = useMemo(() => ({ min: 0, max: 100, now: percent }), [percent]);
|
||||
const fillStyle = useMemo(
|
||||
() => [styles.aboutUpdateProgressFill, { width: `${percent}%` as const }],
|
||||
[percent],
|
||||
);
|
||||
|
||||
return (
|
||||
<View
|
||||
style={styles.aboutUpdateProgressTrack}
|
||||
accessibilityRole="progressbar"
|
||||
accessibilityValue={accessibilityValue}
|
||||
testID="settings-about-update-progress"
|
||||
>
|
||||
<View style={fillStyle} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopAppUpdateRow() {
|
||||
const { t } = useTranslation();
|
||||
const { settings, updateSettings } = useSettings();
|
||||
const {
|
||||
settings: desktopSettings,
|
||||
isLoading: isLoadingDesktopSettings,
|
||||
updateSettings: updateDesktopSettings,
|
||||
} = useDesktopSettings();
|
||||
const updateMode = desktopSettings.updates.mode;
|
||||
const {
|
||||
isDesktopApp,
|
||||
status,
|
||||
statusText,
|
||||
availableUpdate,
|
||||
downloadProgress,
|
||||
errorMessage,
|
||||
isChecking,
|
||||
isInstalling,
|
||||
@@ -644,12 +705,12 @@ function DesktopAppUpdateRow() {
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (!isDesktopApp) {
|
||||
if (!isDesktopApp || isLoadingDesktopSettings || updateMode === "off") {
|
||||
return undefined;
|
||||
}
|
||||
void checkForUpdates({ intent: "automatic", silent: true });
|
||||
return undefined;
|
||||
}, [checkForUpdates, isDesktopApp]),
|
||||
}, [checkForUpdates, isDesktopApp, isLoadingDesktopSettings, updateMode]),
|
||||
);
|
||||
|
||||
const handleCheckForUpdates = useCallback(() => {
|
||||
@@ -673,17 +734,36 @@ function DesktopAppUpdateRow() {
|
||||
[t],
|
||||
);
|
||||
|
||||
const handleUpdateModeChange = useCallback(
|
||||
(mode: DesktopUpdateMode) => {
|
||||
void updateDesktopSettings({ updates: { mode } });
|
||||
},
|
||||
[updateDesktopSettings],
|
||||
);
|
||||
const updateModeOptions = useMemo(
|
||||
() => [
|
||||
{ value: "automatic" as const, label: t("settings.about.autoUpdate.options.automatic") },
|
||||
{ value: "notify" as const, label: t("settings.about.autoUpdate.options.notify") },
|
||||
{ value: "off" as const, label: t("settings.about.autoUpdate.options.off") },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
const isUpdateReady = availableUpdate?.readyToInstall === true;
|
||||
const isUpdateActionable = status === "available" && availableUpdate?.hasUpdate === true;
|
||||
const readyUpdateVersion = isUpdateReady ? availableUpdate?.latestVersion : null;
|
||||
const actionableVersion = isUpdateActionable ? availableUpdate?.latestVersion : null;
|
||||
const downloadPercent =
|
||||
(isInstalling || status === "pending") && downloadProgress
|
||||
? Math.max(0, Math.min(100, Math.round(downloadProgress.percent)))
|
||||
: null;
|
||||
|
||||
const handleInstallUpdate = useCallback(() => {
|
||||
if (!isDesktopApp) {
|
||||
return;
|
||||
}
|
||||
|
||||
void confirmDialog({
|
||||
title: t("settings.about.updates.installTitle"),
|
||||
message: t("settings.about.updates.installMessage"),
|
||||
confirmLabel: t("settings.about.updates.installConfirm"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
})
|
||||
void confirmDialog(getUpdateConfirmDialogCopy(t, isUpdateReady))
|
||||
.then((confirmed) => {
|
||||
if (!confirmed) {
|
||||
return;
|
||||
@@ -698,10 +778,7 @@ function DesktopAppUpdateRow() {
|
||||
t("settings.about.updates.alertMessage"),
|
||||
);
|
||||
});
|
||||
}, [installUpdate, isDesktopApp, t]);
|
||||
|
||||
const isUpdateReady = availableUpdate?.readyToInstall === true;
|
||||
const readyUpdateVersion = isUpdateReady ? availableUpdate?.latestVersion : null;
|
||||
}, [installUpdate, isDesktopApp, isUpdateReady, t]);
|
||||
|
||||
if (!isDesktopApp) {
|
||||
return null;
|
||||
@@ -722,6 +799,18 @@ function DesktopAppUpdateRow() {
|
||||
options={releaseChannelOptions}
|
||||
/>
|
||||
</View>
|
||||
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowTitle}>{t("settings.about.autoUpdate.label")}</Text>
|
||||
<Text style={settingsStyles.rowHint}>{getUpdateModeDescription(t, updateMode)}</Text>
|
||||
</View>
|
||||
<SegmentedControl
|
||||
value={updateMode}
|
||||
onValueChange={handleUpdateModeChange}
|
||||
options={updateModeOptions}
|
||||
testID="settings-about-update-mode"
|
||||
/>
|
||||
</View>
|
||||
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
|
||||
<View style={settingsStyles.rowContent}>
|
||||
<Text style={settingsStyles.rowTitle}>{t("settings.about.updates.label")}</Text>
|
||||
@@ -733,6 +822,7 @@ function DesktopAppUpdateRow() {
|
||||
})}
|
||||
</Text>
|
||||
) : null}
|
||||
{downloadPercent !== null ? <DesktopUpdateProgressBar percent={downloadPercent} /> : null}
|
||||
{errorMessage ? <Text style={styles.aboutErrorText}>{errorMessage}</Text> : null}
|
||||
</View>
|
||||
<View style={styles.aboutUpdateActions}>
|
||||
@@ -746,9 +836,15 @@ function DesktopAppUpdateRow() {
|
||||
<Button
|
||||
variant="default"
|
||||
onPress={handleInstallUpdate}
|
||||
disabled={isChecking || isInstalling || !isUpdateReady}
|
||||
disabled={isChecking || isInstalling || !isUpdateActionable}
|
||||
>
|
||||
{getUpdateButtonLabel(t, isInstalling, readyUpdateVersion)}
|
||||
{getUpdateButtonLabel(t, {
|
||||
isInstalling,
|
||||
isDownloading: isInstalling && downloadProgress != null,
|
||||
isActionable: isUpdateActionable,
|
||||
readyToInstall: isUpdateReady,
|
||||
latestVersion: actionableVersion,
|
||||
})}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
@@ -1111,139 +1207,6 @@ function SettingsSidebar({
|
||||
);
|
||||
}
|
||||
|
||||
interface SettingsBeforeLeaveGuard {
|
||||
isDirty: () => boolean;
|
||||
confirmDiscard: () => Promise<boolean>;
|
||||
subscribeDirty?: (listener: () => void) => () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets an active Settings editor (such as Agent profiles) veto both in-app
|
||||
* section switches and route-boundary exits (browser Back, native swipe-back,
|
||||
* hardware Back) with a single discard confirmation.
|
||||
*
|
||||
* Uses `usePreventRemove` so native stacks set `preventNativeDismiss` before
|
||||
* iOS can interactively dismiss the screen on a back swipe.
|
||||
*/
|
||||
function useSettingsBeforeLeaveGuard() {
|
||||
const navigation = useNavigation();
|
||||
const beforeLeaveRef = useRef<SettingsBeforeLeaveGuard | null>(null);
|
||||
const dirtyUnsubRef = useRef<(() => void) | null>(null);
|
||||
const [preventRemove, setPreventRemove] = useState(false);
|
||||
|
||||
const registerBeforeLeave = useCallback((guard: SettingsBeforeLeaveGuard | null) => {
|
||||
dirtyUnsubRef.current?.();
|
||||
dirtyUnsubRef.current = null;
|
||||
beforeLeaveRef.current = guard;
|
||||
const syncDirty = () => {
|
||||
setPreventRemove(Boolean(beforeLeaveRef.current?.isDirty()));
|
||||
};
|
||||
syncDirty();
|
||||
if (guard?.subscribeDirty) {
|
||||
dirtyUnsubRef.current = guard.subscribeDirty(syncDirty);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
dirtyUnsubRef.current?.();
|
||||
dirtyUnsubRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return registerRouteLeaveGuard({
|
||||
isDirty: () => Boolean(beforeLeaveRef.current?.isDirty()),
|
||||
confirmDiscard: async () => (await beforeLeaveRef.current?.confirmDiscard()) ?? true,
|
||||
});
|
||||
}, []);
|
||||
|
||||
usePreventRemove(preventRemove, ({ data }) => {
|
||||
const guard = beforeLeaveRef.current;
|
||||
if (!guard?.isDirty()) {
|
||||
navigation.dispatch(data.action);
|
||||
return;
|
||||
}
|
||||
const confirmAndLeave = async () => {
|
||||
if (await guard.confirmDiscard()) {
|
||||
navigation.dispatch(data.action);
|
||||
}
|
||||
};
|
||||
void confirmAndLeave();
|
||||
});
|
||||
|
||||
const guardNavigation = useCallback((navigate: () => void) => {
|
||||
const guard = beforeLeaveRef.current;
|
||||
if (!guard?.isDirty()) {
|
||||
navigate();
|
||||
return;
|
||||
}
|
||||
const run = async () => {
|
||||
if (await guard.confirmDiscard()) {
|
||||
navigate();
|
||||
}
|
||||
};
|
||||
void run();
|
||||
}, []);
|
||||
|
||||
return { registerBeforeLeave, guardNavigation };
|
||||
}
|
||||
|
||||
function SettingsDetailPane({
|
||||
view,
|
||||
isCompactLayout,
|
||||
detailTitle,
|
||||
detailActions,
|
||||
detailWidth,
|
||||
onBack,
|
||||
onRegisterBeforeLeave,
|
||||
content,
|
||||
}: {
|
||||
view: SettingsView;
|
||||
isCompactLayout: boolean;
|
||||
detailTitle: string | undefined;
|
||||
detailActions: React.ReactNode;
|
||||
detailWidth: React.ComponentProps<typeof PageLayout>["width"];
|
||||
onBack: () => void;
|
||||
onRegisterBeforeLeave: (guard: SettingsBeforeLeaveGuard | null) => void;
|
||||
content: React.ReactNode;
|
||||
}) {
|
||||
const isStandaloneAgentProfilesView = view.kind === "host" && view.section === "agent-profiles";
|
||||
const pageTitle =
|
||||
!isCompactLayout && (view.kind === "project" || view.kind === "provider")
|
||||
? undefined
|
||||
: detailTitle;
|
||||
|
||||
return (
|
||||
<WindowChromeRegion corners={isCompactLayout ? "both" : "top-right"}>
|
||||
<View
|
||||
style={isCompactLayout ? desktopStyles.compactContentPane : desktopStyles.contentPane}
|
||||
testID={isCompactLayout ? undefined : "settings-detail-pane"}
|
||||
>
|
||||
{isStandaloneAgentProfilesView ? (
|
||||
<HostAgentProfilesPage
|
||||
serverId={view.serverId}
|
||||
onBack={isCompactLayout ? onBack : undefined}
|
||||
onRegisterBeforeLeave={onRegisterBeforeLeave}
|
||||
/>
|
||||
) : (
|
||||
<PageLayout
|
||||
// A project or provider page draws its own title on desktop, naming the list it came from.
|
||||
title={pageTitle}
|
||||
onBack={isCompactLayout ? onBack : undefined}
|
||||
actions={detailActions}
|
||||
width={detailWidth}
|
||||
titleTestID={isCompactLayout ? undefined : "settings-detail-header-title"}
|
||||
testID={isCompactLayout ? undefined : "settings-detail-scroll-body"}
|
||||
>
|
||||
{content}
|
||||
</PageLayout>
|
||||
)}
|
||||
</View>
|
||||
</WindowChromeRegion>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main screen
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1341,10 +1304,10 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
|
||||
);
|
||||
|
||||
const handleAddHost = useAddHost({ onAdded: handleHostAdded });
|
||||
const { registerBeforeLeave, guardNavigation } = useSettingsBeforeLeaveGuard();
|
||||
|
||||
const navigateRoute = useCallback(
|
||||
(target: Parameters<typeof router.push>[0]) => {
|
||||
const handleSelectSection = useCallback(
|
||||
(section: SettingsSectionSlug) => {
|
||||
const target = buildSettingsSectionRoute(section);
|
||||
if (isCompactLayout) {
|
||||
router.push(target);
|
||||
} else {
|
||||
@@ -1354,62 +1317,51 @@ 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) => {
|
||||
if (view.kind === "host" && view.serverId === serverId) {
|
||||
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);
|
||||
}
|
||||
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;
|
||||
}
|
||||
if (view.kind === "host") {
|
||||
navigateRoute(buildSettingsHostSectionRoute(serverId, view.section));
|
||||
}
|
||||
};
|
||||
guardNavigation(applySelection);
|
||||
if (view.kind !== "host") {
|
||||
return;
|
||||
}
|
||||
const target = buildSettingsHostSectionRoute(serverId, view.section);
|
||||
if (isCompactLayout) {
|
||||
router.push(target);
|
||||
} else {
|
||||
router.replace(target);
|
||||
}
|
||||
},
|
||||
[guardNavigation, navigateRoute, view],
|
||||
[isCompactLayout, router, view],
|
||||
);
|
||||
|
||||
const handleSelectHostSection = useCallback(
|
||||
(section: HostSectionSlug) => {
|
||||
if (!activeHostServerId) {
|
||||
guardNavigation(handleAddHost);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
view.kind === "host" &&
|
||||
view.serverId === activeHostServerId &&
|
||||
view.section === section
|
||||
) {
|
||||
handleAddHost();
|
||||
return;
|
||||
}
|
||||
const target = buildSettingsHostSectionRoute(activeHostServerId, section);
|
||||
guardNavigation(() => navigateRoute(target));
|
||||
if (isCompactLayout) {
|
||||
router.push(target);
|
||||
} else {
|
||||
router.replace(target);
|
||||
}
|
||||
},
|
||||
[activeHostServerId, guardNavigation, handleAddHost, navigateRoute, view],
|
||||
[activeHostServerId, handleAddHost, isCompactLayout, router],
|
||||
);
|
||||
|
||||
const handleHostRemoved = useCallback(() => {
|
||||
@@ -1422,12 +1374,12 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
|
||||
}, [isCompactLayout, router]);
|
||||
|
||||
const handleBackFromDetail = useCallback(() => {
|
||||
guardNavigation(() => returnFromSettings(view));
|
||||
}, [guardNavigation, view]);
|
||||
returnFromSettings(view);
|
||||
}, [view]);
|
||||
|
||||
const handleBackToWorkspace = useCallback(() => {
|
||||
guardNavigation(() => returnFromSettings({ kind: "root" }));
|
||||
}, [guardNavigation]);
|
||||
returnFromSettings({ kind: "root" });
|
||||
}, []);
|
||||
|
||||
// A plugin's page draws its own header; the compact back header names the plugin.
|
||||
const pluginPage = useMemo((): { serverId: string; subject: PluginPageSubject } | null => {
|
||||
@@ -1563,36 +1515,53 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
|
||||
);
|
||||
}
|
||||
|
||||
// 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).
|
||||
if (isCompactLayout) {
|
||||
return (
|
||||
<View style={styles.container} onLayout={onContentLayout}>
|
||||
<PageLayout
|
||||
title={detailTitle}
|
||||
onBack={handleBackFromDetail}
|
||||
actions={detailActions}
|
||||
width={detailWidth}
|
||||
>
|
||||
{content}
|
||||
</PageLayout>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
// Desktop split view — mirrors AppContainer: sidebar owns the titlebar drag
|
||||
// region + traffic-light padding; detail pane renders whatever header the
|
||||
// selected section provides.
|
||||
return (
|
||||
<View style={styles.container} onLayout={onContentLayout}>
|
||||
<View style={desktopStyles.row}>
|
||||
{isCompactLayout ? null : (
|
||||
<WindowChromeRegion corners="top-left">
|
||||
<SettingsSidebar
|
||||
view={view}
|
||||
onSelectSection={handleSelectSection}
|
||||
onSelectHostSection={handleSelectHostSection}
|
||||
onSelectHost={handleSelectHost}
|
||||
onAddHost={handleAddHost}
|
||||
onBackToWorkspace={handleBackToWorkspace}
|
||||
activeHostServerId={activeHostServerId}
|
||||
layout="desktop"
|
||||
/>
|
||||
</WindowChromeRegion>
|
||||
)}
|
||||
<SettingsDetailPane
|
||||
view={view}
|
||||
isCompactLayout={isCompactLayout}
|
||||
detailTitle={detailTitle}
|
||||
detailActions={detailActions}
|
||||
detailWidth={detailWidth}
|
||||
onBack={handleBackFromDetail}
|
||||
onRegisterBeforeLeave={registerBeforeLeave}
|
||||
content={content}
|
||||
/>
|
||||
<WindowChromeRegion corners="top-left">
|
||||
<SettingsSidebar
|
||||
view={view}
|
||||
onSelectSection={handleSelectSection}
|
||||
onSelectHostSection={handleSelectHostSection}
|
||||
onSelectHost={handleSelectHost}
|
||||
onAddHost={handleAddHost}
|
||||
onBackToWorkspace={handleBackToWorkspace}
|
||||
activeHostServerId={activeHostServerId}
|
||||
layout="desktop"
|
||||
/>
|
||||
</WindowChromeRegion>
|
||||
<WindowChromeRegion corners="top-right">
|
||||
<View style={desktopStyles.contentPane} testID="settings-detail-pane">
|
||||
<PageLayout
|
||||
// A project or provider page draws its own title, which names the list it came from.
|
||||
title={view.kind === "project" || view.kind === "provider" ? undefined : detailTitle}
|
||||
actions={detailActions}
|
||||
width={detailWidth}
|
||||
titleTestID="settings-detail-header-title"
|
||||
testID="settings-detail-scroll-body"
|
||||
>
|
||||
{content}
|
||||
</PageLayout>
|
||||
</View>
|
||||
</WindowChromeRegion>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
@@ -1640,6 +1609,19 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
aboutUpdateProgressTrack: {
|
||||
marginTop: theme.spacing[2],
|
||||
height: 4,
|
||||
maxWidth: 260,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.surface3,
|
||||
overflow: "hidden",
|
||||
},
|
||||
aboutUpdateProgressFill: {
|
||||
height: "100%",
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
placeholder: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
@@ -1661,10 +1643,6 @@ const desktopStyles = StyleSheet.create({
|
||||
flex: 1,
|
||||
minWidth: SETTINGS_DESKTOP_DETAIL_MIN_WIDTH,
|
||||
},
|
||||
compactContentPane: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const sidebarStyles = StyleSheet.create((theme) => ({
|
||||
@@ -1686,10 +1664,8 @@ 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: {
|
||||
marginVertical: theme.spacing[2],
|
||||
paddingVertical: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
gap: { xs: theme.spacing[1], md: theme.spacing[0.5] },
|
||||
},
|
||||
|
||||
@@ -21,10 +21,9 @@ import {
|
||||
getTerminalProfileIcon,
|
||||
DEFAULT_TERMINAL_PROFILES,
|
||||
} from "@getpaseo/protocol/terminal-profiles";
|
||||
import { AgentProfilesPage, type AgentProfilesBeforeLeaveGuard } from "@/agent-profiles";
|
||||
import { AgentProfilesSection } 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";
|
||||
@@ -305,43 +304,11 @@ export function HostAgentsPage({ serverId }: { serverId: string }) {
|
||||
</View>
|
||||
)}
|
||||
<AgentSkillsSection serverId={serverId} />
|
||||
<AgentProfilesSection serverId={serverId} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function HostAgentProfilesPage({
|
||||
serverId,
|
||||
onBack,
|
||||
onRegisterBeforeLeave,
|
||||
}: {
|
||||
serverId: string;
|
||||
onBack?: () => void;
|
||||
onRegisterBeforeLeave?: (guard: AgentProfilesBeforeLeaveGuard | null) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const host = useHostProfile(serverId);
|
||||
|
||||
if (!host) {
|
||||
return (
|
||||
<PageLayout
|
||||
title={t("settings.host.agentProfiles.sectionTitle")}
|
||||
onBack={onBack}
|
||||
titleTestID="settings-detail-header-title"
|
||||
>
|
||||
<HostNotFound />
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AgentProfilesPage
|
||||
serverId={serverId}
|
||||
onBack={onBack}
|
||||
onRegisterBeforeLeave={onRegisterBeforeLeave}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function HostWorkspacesPage({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const host = useHostProfile(serverId);
|
||||
|
||||
@@ -517,7 +517,6 @@ export const HOST_SECTION_SLUGS = [
|
||||
"connections",
|
||||
"pair-device",
|
||||
"agents",
|
||||
"agent-profiles",
|
||||
"metadata",
|
||||
"voice",
|
||||
"workspaces",
|
||||
|
||||
@@ -55,9 +55,12 @@ export async function loadRealDaemonState(): Promise<RealDaemonState> {
|
||||
|
||||
export interface DesktopRuntimeConfig {
|
||||
serverId: string;
|
||||
updateMode?: "automatic" | "notify" | "off";
|
||||
updateAvailable?: boolean;
|
||||
latestVersion?: string;
|
||||
updateReadyToInstall?: boolean;
|
||||
updateDownloading?: boolean;
|
||||
downloadProgressSteps?: number[];
|
||||
manualUpdateBypassesRollout?: boolean;
|
||||
slowInstall?: boolean;
|
||||
/** Initial PID reported by desktop_daemon_status. Defaults to null. */
|
||||
@@ -110,6 +113,7 @@ declare global {
|
||||
interface Window {
|
||||
__capturedDialogCall: ConfirmDialogCall | undefined;
|
||||
__capturedDialogOpenCalls: Array<Record<string, unknown> | undefined>;
|
||||
__capturedUpdateChecks?: Array<{ intent: unknown; releaseChannel: unknown }>;
|
||||
__recordDesktopEditorOpen?: (input: DesktopEditorOpenRecord) => Promise<void>;
|
||||
__desktopDaemonStartRequested?: boolean;
|
||||
}
|
||||
@@ -140,11 +144,22 @@ export async function installDesktopRuntime(
|
||||
await page.addInitScript((cfg) => {
|
||||
// Mutable state shared across IPC calls within this page
|
||||
let manageDaemon = cfg.manageBuiltInDaemon ?? false;
|
||||
let updateMode = cfg.updateMode ?? "automatic";
|
||||
let daemonRunning = true;
|
||||
let currentPid: number | null = cfg.daemonPid ?? null;
|
||||
let ownedByDesktop = cfg.ownedByDesktop ?? false;
|
||||
let manualUpdateAdmitted = false;
|
||||
const eventListeners = new Map<string, Set<(payload: unknown) => void>>();
|
||||
window.__desktopDaemonStartRequested = false;
|
||||
window.__capturedUpdateChecks = [];
|
||||
|
||||
function emitDesktopEvent(event: string, payload: unknown) {
|
||||
const listeners = eventListeners.get(event);
|
||||
if (!listeners) return;
|
||||
for (const listener of listeners) {
|
||||
listener(payload);
|
||||
}
|
||||
}
|
||||
|
||||
function buildDaemonStatus() {
|
||||
return {
|
||||
@@ -182,10 +197,15 @@ export async function installDesktopRuntime(
|
||||
}
|
||||
}
|
||||
|
||||
function buildAppUpdateCheckResult(hasUpdate: boolean, readyToInstall: boolean) {
|
||||
function buildAppUpdateCheckResult(
|
||||
hasUpdate: boolean,
|
||||
readyToInstall: boolean,
|
||||
downloading = hasUpdate && !readyToInstall,
|
||||
) {
|
||||
return {
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading,
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: hasUpdate ? (cfg.latestVersion ?? "1.2.3") : null,
|
||||
body: null,
|
||||
@@ -194,19 +214,78 @@ export async function installDesktopRuntime(
|
||||
}
|
||||
|
||||
function checkAppUpdate(intent: unknown) {
|
||||
if (intent === "automatic" && updateMode === "off") {
|
||||
return buildAppUpdateCheckResult(false, false, false);
|
||||
}
|
||||
if (!cfg.manualUpdateBypassesRollout) {
|
||||
return buildAppUpdateCheckResult(
|
||||
cfg.updateAvailable === true,
|
||||
cfg.updateAvailable === true && (cfg.updateReadyToInstall ?? true),
|
||||
);
|
||||
const hasUpdate = cfg.updateAvailable === true;
|
||||
const readyToInstall =
|
||||
hasUpdate && (cfg.updateReadyToInstall ?? updateMode === "automatic");
|
||||
const downloading =
|
||||
cfg.updateDownloading ?? (hasUpdate && !readyToInstall && updateMode === "automatic");
|
||||
return buildAppUpdateCheckResult(hasUpdate, readyToInstall, downloading);
|
||||
}
|
||||
|
||||
if (intent === "manual") {
|
||||
manualUpdateAdmitted = true;
|
||||
return buildAppUpdateCheckResult(true, false);
|
||||
return buildAppUpdateCheckResult(true, false, updateMode === "automatic");
|
||||
}
|
||||
|
||||
return buildAppUpdateCheckResult(manualUpdateAdmitted, manualUpdateAdmitted);
|
||||
return buildAppUpdateCheckResult(manualUpdateAdmitted, manualUpdateAdmitted, false);
|
||||
}
|
||||
|
||||
async function installAppUpdate() {
|
||||
if (cfg.downloadProgressSteps?.length) {
|
||||
for (const percent of cfg.downloadProgressSteps) {
|
||||
emitDesktopEvent("app-update-download-progress", {
|
||||
version: cfg.latestVersion ?? "1.2.3",
|
||||
percent,
|
||||
transferred: percent * 1_000_000,
|
||||
total: 100_000_000,
|
||||
bytesPerSecond: 5_000_000,
|
||||
});
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 600));
|
||||
}
|
||||
}
|
||||
if (cfg.slowInstall) {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 3000));
|
||||
}
|
||||
emitDesktopEvent("app-update-download-progress", null);
|
||||
return {
|
||||
installed: true,
|
||||
version: cfg.latestVersion ?? "1.2.3",
|
||||
message: "App update installed. Restart required.",
|
||||
};
|
||||
}
|
||||
|
||||
function buildDesktopSettings() {
|
||||
return {
|
||||
releaseChannel: "stable",
|
||||
updates: { mode: updateMode },
|
||||
daemon: { manageBuiltInDaemon: manageDaemon, keepRunningAfterQuit: true },
|
||||
};
|
||||
}
|
||||
|
||||
function patchDesktopSettings(args?: Record<string, unknown>) {
|
||||
const updates = args?.updates;
|
||||
if (
|
||||
updates !== null &&
|
||||
typeof updates === "object" &&
|
||||
"mode" in updates &&
|
||||
(updates.mode === "automatic" || updates.mode === "notify" || updates.mode === "off")
|
||||
) {
|
||||
updateMode = updates.mode;
|
||||
}
|
||||
const daemon = args?.daemon;
|
||||
if (
|
||||
daemon !== null &&
|
||||
typeof daemon === "object" &&
|
||||
"manageBuiltInDaemon" in daemon &&
|
||||
typeof daemon.manageBuiltInDaemon === "boolean"
|
||||
) {
|
||||
manageDaemon = daemon.manageBuiltInDaemon;
|
||||
}
|
||||
return buildDesktopSettings();
|
||||
}
|
||||
|
||||
const desktopBridge: {
|
||||
@@ -217,7 +296,9 @@ export async function installDesktopRuntime(
|
||||
open: (options?: Record<string, unknown>) => Promise<string | string[] | null>;
|
||||
};
|
||||
getPendingOpenProject: () => Promise<string | null>;
|
||||
events: { on: () => Promise<() => void> };
|
||||
events: {
|
||||
on: (event: string, handler: (payload: unknown) => void) => Promise<() => void>;
|
||||
};
|
||||
editor?: {
|
||||
listTargets: () => Promise<DesktopEditorTargetConfig[]>;
|
||||
openTarget: (input: DesktopEditorOpenRecord) => Promise<void>;
|
||||
@@ -226,18 +307,15 @@ export async function installDesktopRuntime(
|
||||
platform: "darwin",
|
||||
invoke: async (command: string, args?: Record<string, unknown>) => {
|
||||
if (command === "check_app_update") {
|
||||
window.__capturedUpdateChecks?.push({
|
||||
intent: args?.intent,
|
||||
releaseChannel: args?.releaseChannel,
|
||||
});
|
||||
return checkAppUpdate(args?.intent);
|
||||
}
|
||||
|
||||
if (command === "install_app_update") {
|
||||
if (cfg.slowInstall) {
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 3000));
|
||||
}
|
||||
return {
|
||||
installed: true,
|
||||
version: cfg.latestVersion ?? "1.2.3",
|
||||
message: "App update installed. Restart required.",
|
||||
};
|
||||
return installAppUpdate();
|
||||
}
|
||||
|
||||
if (command === "desktop_daemon_status") {
|
||||
@@ -250,26 +328,11 @@ export async function installDesktopRuntime(
|
||||
|
||||
if (command === "get_desktop_settings") {
|
||||
await waitForDesktopSettingsResponse();
|
||||
return {
|
||||
releaseChannel: "stable",
|
||||
daemon: { manageBuiltInDaemon: manageDaemon, keepRunningAfterQuit: true },
|
||||
};
|
||||
return buildDesktopSettings();
|
||||
}
|
||||
|
||||
if (command === "patch_desktop_settings") {
|
||||
const daemon = args?.daemon;
|
||||
if (
|
||||
daemon !== null &&
|
||||
typeof daemon === "object" &&
|
||||
"manageBuiltInDaemon" in daemon &&
|
||||
typeof daemon.manageBuiltInDaemon === "boolean"
|
||||
) {
|
||||
manageDaemon = daemon.manageBuiltInDaemon;
|
||||
}
|
||||
return {
|
||||
releaseChannel: "stable",
|
||||
daemon: { manageBuiltInDaemon: manageDaemon, keepRunningAfterQuit: true },
|
||||
};
|
||||
return patchDesktopSettings(args);
|
||||
}
|
||||
|
||||
if (command === "stop_desktop_daemon") {
|
||||
@@ -299,7 +362,19 @@ export async function installDesktopRuntime(
|
||||
},
|
||||
},
|
||||
getPendingOpenProject: async () => null,
|
||||
events: { on: async () => () => undefined },
|
||||
events: {
|
||||
on: async (event: string, handler: (payload: unknown) => void) => {
|
||||
let listeners = eventListeners.get(event);
|
||||
if (!listeners) {
|
||||
listeners = new Set();
|
||||
eventListeners.set(event, listeners);
|
||||
}
|
||||
listeners.add(handler);
|
||||
return () => {
|
||||
listeners?.delete(handler);
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
if (cfg.editorTargets) {
|
||||
|
||||
@@ -91,6 +91,74 @@ test.describe("Desktop updates", () => {
|
||||
await expectPendingUpdateCheckResult(page, "1.2.3");
|
||||
await expectReadyUpdateCheckResult(page, "1.2.3");
|
||||
});
|
||||
|
||||
test("off mode skips automatic update checks until Check is clicked", async ({ page }) => {
|
||||
await installDesktopRuntime(page, {
|
||||
serverId: getServerId(),
|
||||
updateMode: "off",
|
||||
updateAvailable: true,
|
||||
latestVersion: "1.2.3",
|
||||
});
|
||||
await gotoAppShell(page);
|
||||
await openDesktopAboutSettings(page);
|
||||
|
||||
await expect(
|
||||
page.getByText("Never check automatically. Only check when you click Check"),
|
||||
).toBeVisible();
|
||||
await expect(page.getByTestId("update-callout")).toHaveCount(0);
|
||||
const automaticChecks = await page.evaluate(() => window.__capturedUpdateChecks ?? []);
|
||||
expect(automaticChecks).toEqual([]);
|
||||
|
||||
await clickCheckForUpdates(page);
|
||||
await expect(page.getByText(/Update available: v1\.2\.3/)).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Download v1.2.3" })).toBeEnabled();
|
||||
});
|
||||
|
||||
test("notify mode shows Download and live download progress", async ({ page }) => {
|
||||
await installDesktopRuntime(page, {
|
||||
serverId: getServerId(),
|
||||
updateMode: "notify",
|
||||
updateAvailable: true,
|
||||
latestVersion: "1.2.3",
|
||||
downloadProgressSteps: [42, 78],
|
||||
slowInstall: true,
|
||||
});
|
||||
await gotoAppShell(page);
|
||||
|
||||
const callout = page.getByTestId("update-callout");
|
||||
await expect(callout).toBeVisible({ timeout: 15_000 });
|
||||
await expect(callout).toContainText("v1.2.3 is available to download.");
|
||||
await page.getByRole("button", { name: "Download", exact: true }).click();
|
||||
await expect(callout).toContainText("Downloading v1.2.3... 42%");
|
||||
await expect(callout.getByRole("progressbar")).toBeVisible();
|
||||
});
|
||||
|
||||
test("starting download in About updates the sidebar callout and disables its action", async ({
|
||||
page,
|
||||
}) => {
|
||||
await installDesktopRuntime(page, {
|
||||
serverId: getServerId(),
|
||||
updateMode: "notify",
|
||||
updateAvailable: true,
|
||||
latestVersion: "1.2.3",
|
||||
downloadProgressSteps: [55],
|
||||
slowInstall: true,
|
||||
confirmShouldAccept: true,
|
||||
});
|
||||
await gotoAppShell(page);
|
||||
await expect(page.getByTestId("update-callout")).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
await openDesktopAboutSettings(page);
|
||||
await page.getByRole("button", { name: "Download v1.2.3" }).click();
|
||||
await expect(
|
||||
page.getByTestId("settings-detail-scroll-body").getByText("Downloading v1.2.3... 55%"),
|
||||
).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "Back" }).click();
|
||||
const callout = page.getByTestId("update-callout");
|
||||
await expect(callout).toContainText("Downloading v1.2.3... 55%");
|
||||
await expect(callout.getByRole("button", { name: "Downloading..." })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("Desktop daemon management", () => {
|
||||
|
||||
@@ -14,13 +14,22 @@ import {
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
paseoHome: "",
|
||||
settingsError: null as Error | null,
|
||||
settings: {
|
||||
releaseChannel: "stable",
|
||||
releaseChannel: "stable" as "stable" | "beta",
|
||||
updates: {
|
||||
mode: "automatic" as "automatic" | "notify" | "off",
|
||||
},
|
||||
notifications: {
|
||||
playSound: true,
|
||||
},
|
||||
daemon: {
|
||||
manageBuiltInDaemon: true,
|
||||
keepRunningAfterQuit: true,
|
||||
},
|
||||
},
|
||||
checkForAppUpdate: vi.fn(),
|
||||
downloadAndInstallUpdate: vi.fn(),
|
||||
runExternalCliJsonCommand: vi.fn(),
|
||||
runExternalCliTextCommand: vi.fn(),
|
||||
createNodeEntrypointInvocation: vi.fn(() => ({
|
||||
@@ -41,6 +50,8 @@ vi.mock("electron", () => ({
|
||||
getVersion: vi.fn(() => "1.2.3"),
|
||||
isPackaged: true,
|
||||
},
|
||||
autoUpdater: undefined,
|
||||
BrowserWindow: { getAllWindows: vi.fn(() => []) },
|
||||
ipcMain: { handle: vi.fn() },
|
||||
powerMonitor: { getSystemIdleTime: vi.fn(() => 0) },
|
||||
}));
|
||||
@@ -65,7 +76,12 @@ vi.mock("@getpaseo/server/daemon-control", async (importOriginal) => ({
|
||||
|
||||
vi.mock("../settings/desktop-settings-electron.js", () => ({
|
||||
getDesktopSettingsStore: () => ({
|
||||
get: async () => mocks.settings,
|
||||
get: async () => {
|
||||
if (mocks.settingsError) {
|
||||
throw mocks.settingsError;
|
||||
}
|
||||
return mocks.settings;
|
||||
},
|
||||
patch: vi.fn(),
|
||||
migrateLegacyRendererSettings: vi.fn(),
|
||||
}),
|
||||
@@ -79,6 +95,12 @@ vi.mock("./runtime-paths.js", () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../features/auto-updater.js", async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
checkForAppUpdate: mocks.checkForAppUpdate,
|
||||
downloadAndInstallUpdate: mocks.downloadAndInstallUpdate,
|
||||
}));
|
||||
|
||||
vi.mock("./cli/external.js", async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
runExternalCliJsonCommand: mocks.runExternalCliJsonCommand,
|
||||
@@ -93,6 +115,8 @@ describe("daemon-manager commands", () => {
|
||||
mocks.paseoHome = path.join(fixtureRoot, "home");
|
||||
mocks.appLogPath = path.join(fixtureRoot, "main.log");
|
||||
mocks.settings = DEFAULT_DESKTOP_SETTINGS;
|
||||
mocks.checkForAppUpdate.mockReset();
|
||||
mocks.downloadAndInstallUpdate.mockReset();
|
||||
mocks.runExternalCliJsonCommand.mockReset();
|
||||
mocks.runExternalCliTextCommand.mockReset();
|
||||
mocks.createNodeEntrypointInvocation.mockReset();
|
||||
@@ -182,6 +206,54 @@ describe("daemon-manager commands", () => {
|
||||
writeFileSync(lockPath, JSON.stringify({ ...lock, desktopManaged: false }));
|
||||
expect(await handler({ listen: "localhost:6799" })).toBeNull();
|
||||
});
|
||||
|
||||
it("delegates update checks to checkForAppUpdate even when desktop-settings.json cannot be read", async () => {
|
||||
const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
mocks.checkForAppUpdate.mockResolvedValue({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.4",
|
||||
body: null,
|
||||
date: null,
|
||||
errorMessage: null,
|
||||
});
|
||||
mocks.downloadAndInstallUpdate.mockResolvedValue({
|
||||
installed: true,
|
||||
version: "1.2.4",
|
||||
message: "Update downloaded.",
|
||||
});
|
||||
|
||||
mocks.settingsError = new SyntaxError("Unexpected token } in JSON");
|
||||
try {
|
||||
await createDaemonCommandHandlers().check_app_update({
|
||||
intent: "manual",
|
||||
releaseChannel: "beta",
|
||||
});
|
||||
expect(mocks.checkForAppUpdate).toHaveBeenLastCalledWith({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "beta",
|
||||
intent: "manual",
|
||||
});
|
||||
|
||||
await createDaemonCommandHandlers().check_app_update({ intent: "automatic" });
|
||||
expect(mocks.checkForAppUpdate).toHaveBeenLastCalledWith({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
|
||||
await createDaemonCommandHandlers().install_app_update({});
|
||||
expect(mocks.downloadAndInstallUpdate).toHaveBeenLastCalledWith(
|
||||
{ currentVersion: "1.2.3", releaseChannel: "stable" },
|
||||
expect.any(Function),
|
||||
);
|
||||
} finally {
|
||||
mocks.settingsError = null;
|
||||
consoleWarn.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("desktop stops and terminals", () => {
|
||||
|
||||
@@ -481,7 +481,17 @@ async function getLocalDaemonVersion(): Promise<{ version: string | null; error:
|
||||
async function resolveRequestedReleaseChannel(
|
||||
args: Record<string, unknown> | undefined,
|
||||
): Promise<AppReleaseChannel> {
|
||||
return parseReleaseChannel(args) ?? (await getDesktopSettingsStore().get()).releaseChannel;
|
||||
const explicit = parseReleaseChannel(args);
|
||||
if (explicit) return explicit;
|
||||
try {
|
||||
return (await getDesktopSettingsStore().get()).releaseChannel;
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
"[auto-updater] Failed to read release channel from desktop settings, defaulting to stable:",
|
||||
error,
|
||||
);
|
||||
return "stable";
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -541,10 +551,12 @@ export function createDaemonCommandHandlers(): Record<string, DesktopCommandHand
|
||||
},
|
||||
check_app_update: async (args) => {
|
||||
const currentVersion = resolveDesktopAppVersion();
|
||||
const releaseChannel = await resolveRequestedReleaseChannel(args);
|
||||
const intent = parseAppUpdateCheckIntent(args);
|
||||
return checkForAppUpdate({
|
||||
currentVersion,
|
||||
releaseChannel: await resolveRequestedReleaseChannel(args),
|
||||
intent: parseAppUpdateCheckIntent(args),
|
||||
releaseChannel,
|
||||
intent,
|
||||
});
|
||||
},
|
||||
install_app_update: async (args) => {
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { DesktopUpdateMode } from "../settings/desktop-settings";
|
||||
|
||||
import {
|
||||
createAppUpdateService,
|
||||
type AppUpdateDownloadProgress,
|
||||
type AppUpdateInstallRequest,
|
||||
type AppUpdateRuntime,
|
||||
type AppUpdateRuntimeConfiguration,
|
||||
type RuntimeDownloadProgressInfo,
|
||||
type RuntimeUpdateCheckResult,
|
||||
type RuntimeUpdateInfo,
|
||||
} from "./app-update-service";
|
||||
|
||||
@@ -26,6 +30,8 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
|
||||
resolve(): void;
|
||||
reject(error: Error): void;
|
||||
} | null = null;
|
||||
lastAutoDownload: boolean | null = null;
|
||||
nextQuitAndInstallResult: { started: boolean; errorMessage?: string } | null = null;
|
||||
checkCount = 0;
|
||||
downloadCallCount = 0;
|
||||
requestedDownloadVersions: string[] = [];
|
||||
@@ -35,9 +41,18 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
|
||||
|
||||
configure(input: AppUpdateRuntimeConfiguration): void {
|
||||
this.configuration = input;
|
||||
this.lastAutoDownload = input.autoDownload;
|
||||
this.gate = input.shouldAdmitUpdate;
|
||||
}
|
||||
|
||||
setAutoDownload(enabled: boolean): void {
|
||||
this.lastAutoDownload = enabled;
|
||||
}
|
||||
|
||||
emitDownloadProgress(progress: RuntimeDownloadProgressInfo): void {
|
||||
this.configuration?.onDownloadProgress(progress);
|
||||
}
|
||||
|
||||
nextCheck(result: { isUpdateAvailable: boolean; updateInfo: RuntimeUpdateInfo } | null): void {
|
||||
this.checks.push(result);
|
||||
}
|
||||
@@ -143,21 +158,36 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest): void {
|
||||
quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest) {
|
||||
if (this.nextQuitAndInstallResult) {
|
||||
const outcome = this.nextQuitAndInstallResult;
|
||||
this.nextQuitAndInstallResult = null;
|
||||
return outcome;
|
||||
}
|
||||
if (this.downloadedUpdate) {
|
||||
this.installedVersions.push(this.downloadedUpdate.version);
|
||||
this.installModes.push({ targetVersion, isSilent, isForceRunAfter });
|
||||
}
|
||||
return { started: true };
|
||||
}
|
||||
}
|
||||
|
||||
function createService(input?: { now?: () => number; bucket?: () => Promise<number> }) {
|
||||
function createService(input?: {
|
||||
now?: () => number;
|
||||
bucket?: () => Promise<number>;
|
||||
updateMode?: () => DesktopUpdateMode | Promise<DesktopUpdateMode>;
|
||||
reportSettingsError?: (error: unknown) => void;
|
||||
onDownloadProgress?: (progress: AppUpdateDownloadProgress | null) => void;
|
||||
}) {
|
||||
const runtime = new FakeAppUpdateRuntime();
|
||||
const service = createAppUpdateService({
|
||||
runtime,
|
||||
isPackaged: () => true,
|
||||
now: input?.now ?? (() => Date.parse("2026-04-28T12:00:00.000Z")),
|
||||
bucket: input?.bucket ?? (async () => 0.99),
|
||||
updateMode: input?.updateMode,
|
||||
reportSettingsError: input?.reportSettingsError,
|
||||
onDownloadProgress: input?.onDownloadProgress,
|
||||
});
|
||||
return { runtime, service };
|
||||
}
|
||||
@@ -182,6 +212,7 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -203,6 +234,7 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.4",
|
||||
body: null,
|
||||
@@ -331,6 +363,7 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.5",
|
||||
body: null,
|
||||
@@ -361,6 +394,7 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.5",
|
||||
body: null,
|
||||
@@ -569,6 +603,7 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -590,6 +625,7 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -620,6 +656,7 @@ describe("app update service", () => {
|
||||
expect(retryResult).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -649,6 +686,7 @@ describe("app update service", () => {
|
||||
expect(automaticResult).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -691,6 +729,7 @@ describe("app update service", () => {
|
||||
expect(automaticResult).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -721,6 +760,7 @@ describe("app update service", () => {
|
||||
expect(failedPreparation).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.4",
|
||||
body: null,
|
||||
@@ -739,6 +779,7 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.5",
|
||||
body: null,
|
||||
@@ -802,6 +843,7 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.5",
|
||||
body: null,
|
||||
@@ -834,6 +876,7 @@ describe("app update service", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: true,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.4",
|
||||
body: null,
|
||||
@@ -841,4 +884,422 @@ describe("app update service", () => {
|
||||
errorMessage: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an available update without downloading when autoDownload is false", async () => {
|
||||
const progressEvents: Array<AppUpdateDownloadProgress | null> = [];
|
||||
const { runtime, service } = createService({
|
||||
bucket: async () => 0,
|
||||
onDownloadProgress: (progress) => progressEvents.push(progress),
|
||||
});
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
|
||||
const result = await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: false,
|
||||
});
|
||||
|
||||
expect(runtime.lastAutoDownload).toBe(false);
|
||||
expect(result).toEqual({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.4",
|
||||
body: null,
|
||||
date: "2026-04-28T00:00:00.000Z",
|
||||
errorMessage: null,
|
||||
});
|
||||
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const activeDownload = runtime.beginUpdateDownload(rolledOutUpdate);
|
||||
const installPending = service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
await Promise.resolve();
|
||||
runtime.emitDownloadProgress({
|
||||
percent: 45,
|
||||
transferred: 45,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
});
|
||||
activeDownload.resolve();
|
||||
const installResult = await installPending;
|
||||
|
||||
expect(installResult.installed).toBe(true);
|
||||
expect(progressEvents).toContainEqual({
|
||||
version: "1.2.4",
|
||||
percent: 45,
|
||||
transferred: 45,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
});
|
||||
expect(progressEvents[progressEvents.length - 1]).toBeNull();
|
||||
});
|
||||
|
||||
it("allows retrying the same version after a transient download failure in notify/off mode", async () => {
|
||||
const progressEvents: Array<AppUpdateDownloadProgress | null> = [];
|
||||
const { runtime, service } = createService({
|
||||
bucket: async () => 0,
|
||||
onDownloadProgress: (progress) => progressEvents.push(progress),
|
||||
});
|
||||
|
||||
// 1. Discover v1.2.4 without auto-downloading.
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const discovered = await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "manual",
|
||||
autoDownload: false,
|
||||
});
|
||||
expect(discovered).toMatchObject({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.4",
|
||||
});
|
||||
|
||||
// 2. First explicit download fails transiently mid-transfer.
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const failingDownload = runtime.beginUpdateDownload(rolledOutUpdate);
|
||||
const failedInstallPromise = service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(runtime.downloadCallCount).toBe(1);
|
||||
runtime.emitDownloadProgress({
|
||||
percent: 37,
|
||||
transferred: 37,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
});
|
||||
failingDownload.reject(new Error("ECONNRESET"));
|
||||
const failedInstall = await failedInstallPromise;
|
||||
|
||||
expect(failedInstall).toMatchObject({
|
||||
installed: false,
|
||||
errorMessage: "ECONNRESET",
|
||||
});
|
||||
expect(progressEvents[progressEvents.length - 1]).toBeNull();
|
||||
|
||||
// 3. User retries manual Check for the SAME version (v1.2.4) — must not be stranded on stale error!
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const retryCheck = await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "manual",
|
||||
autoDownload: false,
|
||||
});
|
||||
expect(retryCheck).toMatchObject({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.4",
|
||||
errorMessage: null,
|
||||
});
|
||||
|
||||
// 4. Second explicit download succeeds and installs cleanly.
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const retryInstall = await service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
expect(retryInstall.installed).toBe(true);
|
||||
expect(runtime.installedVersions).toEqual(["1.2.4"]);
|
||||
});
|
||||
|
||||
it("downloads and installs a newer release if one ships after notify discovery", async () => {
|
||||
const { runtime, service } = createService({ bucket: async () => 0 });
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: false,
|
||||
});
|
||||
|
||||
const newerUpdate = { ...rolledOutUpdate, version: "1.2.5" };
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: newerUpdate });
|
||||
const result = await service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
|
||||
expect(result.installed).toBe(true);
|
||||
expect(runtime.installedVersions).toEqual(["1.2.5"]);
|
||||
});
|
||||
|
||||
it("reuses an already-downloaded update when installing manually after switching to notify/off", async () => {
|
||||
const { runtime, service } = createService({ bucket: async () => 0 });
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: true,
|
||||
});
|
||||
runtime.finishUpdateDownload(rolledOutUpdate);
|
||||
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const result = await service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
|
||||
expect(result.installed).toBe(true);
|
||||
expect(runtime.downloadCallCount).toBe(0);
|
||||
expect(runtime.installedVersions).toEqual(["1.2.4"]);
|
||||
});
|
||||
|
||||
it("transitions cleanly from notify discovery to automatic background download", async () => {
|
||||
const { runtime, service } = createService({ bucket: async () => 0 });
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const notifyCheck = await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: false,
|
||||
});
|
||||
expect(notifyCheck).toMatchObject({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
});
|
||||
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const autoCheck = await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: true,
|
||||
});
|
||||
expect(runtime.lastAutoDownload).toBe(true);
|
||||
expect(autoCheck).toMatchObject({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("clamps NaN and out-of-range download progress values safely", async () => {
|
||||
const progressEvents: Array<AppUpdateDownloadProgress | null> = [];
|
||||
const { runtime, service } = createService({
|
||||
bucket: async () => 0,
|
||||
onDownloadProgress: (progress) => progressEvents.push(progress),
|
||||
});
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: true,
|
||||
});
|
||||
|
||||
runtime.emitDownloadProgress({
|
||||
percent: Number.NaN,
|
||||
transferred: Number.NaN,
|
||||
total: Number.POSITIVE_INFINITY,
|
||||
bytesPerSecond: Number.NaN,
|
||||
});
|
||||
runtime.emitDownloadProgress({
|
||||
percent: 140,
|
||||
transferred: 200,
|
||||
total: 100,
|
||||
bytesPerSecond: 50,
|
||||
});
|
||||
|
||||
expect(progressEvents).toContainEqual({
|
||||
version: "1.2.4",
|
||||
percent: 0,
|
||||
transferred: 0,
|
||||
total: 0,
|
||||
bytesPerSecond: 0,
|
||||
});
|
||||
expect(progressEvents).toContainEqual({
|
||||
version: "1.2.4",
|
||||
percent: 100,
|
||||
transferred: 200,
|
||||
total: 100,
|
||||
bytesPerSecond: 50,
|
||||
});
|
||||
});
|
||||
|
||||
it("applies updated updateMode after rollout bucket lookup before authorizing download", async () => {
|
||||
let mode: DesktopUpdateMode = "automatic";
|
||||
let resolveBucket!: (value: number) => void;
|
||||
const { runtime, service } = createService({
|
||||
bucket: () =>
|
||||
new Promise<number>((resolve) => {
|
||||
resolveBucket = resolve;
|
||||
}),
|
||||
updateMode: async () => mode,
|
||||
});
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const check = service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(resolveBucket).toBeDefined();
|
||||
});
|
||||
mode = "notify";
|
||||
resolveBucket(0);
|
||||
const result = await check;
|
||||
|
||||
expect(runtime.lastAutoDownload).toBe(false);
|
||||
expect(result).toMatchObject({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.4",
|
||||
});
|
||||
});
|
||||
|
||||
it("skips a queued automatic check after Off is saved while an earlier check is in flight", async () => {
|
||||
let mode: DesktopUpdateMode = "automatic";
|
||||
const { runtime, service } = createService({
|
||||
bucket: async () => 0,
|
||||
updateMode: async () => mode,
|
||||
});
|
||||
const firstCheck = runtime.deferNextCheck();
|
||||
|
||||
const firstPending = service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
const queuedPending = service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(runtime.checkCount).toBe(1);
|
||||
});
|
||||
mode = "off";
|
||||
firstCheck.resolve({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
|
||||
const [firstResult, queuedResult] = await Promise.all([firstPending, queuedPending]);
|
||||
expect(runtime.checkCount).toBe(1);
|
||||
expect(firstResult.hasUpdate).toBe(false);
|
||||
expect(queuedResult.hasUpdate).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to automatic mode when reading updateMode fails so updates are never stranded", async () => {
|
||||
const settingsErrors: unknown[] = [];
|
||||
const { runtime, service } = createService({
|
||||
bucket: async () => 0,
|
||||
updateMode: async () => {
|
||||
throw new SyntaxError("Unexpected token } in JSON");
|
||||
},
|
||||
reportSettingsError: (error) => settingsErrors.push(error),
|
||||
});
|
||||
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const autoResult = await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
expect(autoResult).toMatchObject({
|
||||
hasUpdate: true,
|
||||
downloading: true,
|
||||
latestVersion: "1.2.4",
|
||||
errorMessage: null,
|
||||
});
|
||||
|
||||
runtime.finishUpdateDownload(rolledOutUpdate);
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
const installedOnQuit = await service.installUpdateOnQuit({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
expect(installedOnQuit).toBe(true);
|
||||
expect(settingsErrors.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("skips installUpdateOnQuit when updateMode is notify or off", async () => {
|
||||
let mode: DesktopUpdateMode = "automatic";
|
||||
const { runtime, service } = createService({
|
||||
bucket: async () => 0,
|
||||
updateMode: async () => mode,
|
||||
});
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
runtime.finishUpdateDownload(rolledOutUpdate);
|
||||
|
||||
mode = "notify";
|
||||
expect(
|
||||
await service.installUpdateOnQuit({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
mode = "off";
|
||||
expect(
|
||||
await service.installUpdateOnQuit({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
expect(runtime.installedVersions).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports installer launch failures instead of success on both cached and downloaded paths", async () => {
|
||||
const { runtime, service } = createService({ bucket: async () => 0 });
|
||||
|
||||
// Path 1: already downloaded, installer fails to launch
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
await service.checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: true,
|
||||
});
|
||||
runtime.finishUpdateDownload(rolledOutUpdate);
|
||||
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
|
||||
runtime.nextQuitAndInstallResult = {
|
||||
started: false,
|
||||
errorMessage: "EROFS: read-only file system",
|
||||
};
|
||||
const cachedFailure = await service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
expect(cachedFailure).toMatchObject({
|
||||
installed: false,
|
||||
errorMessage: "EROFS: read-only file system",
|
||||
});
|
||||
|
||||
// Path 2: fresh download, installer fails to launch
|
||||
const newerUpdate = { ...rolledOutUpdate, version: "1.2.5" };
|
||||
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: newerUpdate });
|
||||
runtime.nextQuitAndInstallResult = {
|
||||
started: false,
|
||||
errorMessage: "Neither dpkg nor apt command found",
|
||||
};
|
||||
const freshFailure = await service.downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
expect(freshFailure).toMatchObject({
|
||||
installed: false,
|
||||
errorMessage: "Neither dpkg nor apt command found",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { DesktopUpdateMode } from "../settings/desktop-settings.js";
|
||||
import {
|
||||
rolloutManifestSchema,
|
||||
shouldAdmitAppUpdate,
|
||||
@@ -5,9 +6,18 @@ import {
|
||||
type AppUpdateCheckIntent,
|
||||
} from "./app-update-rollout.js";
|
||||
|
||||
export interface AppUpdateDownloadProgress {
|
||||
version: string | null;
|
||||
percent: number;
|
||||
transferred: number;
|
||||
total: number;
|
||||
bytesPerSecond: number;
|
||||
}
|
||||
|
||||
export interface AppUpdateCheckResult {
|
||||
hasUpdate: boolean;
|
||||
readyToInstall: boolean;
|
||||
downloading: boolean;
|
||||
currentVersion: string;
|
||||
latestVersion: string;
|
||||
body: string | null;
|
||||
@@ -19,6 +29,7 @@ export interface AppUpdateInstallResult {
|
||||
installed: boolean;
|
||||
version: string | null;
|
||||
message: string;
|
||||
errorMessage?: string | null;
|
||||
}
|
||||
|
||||
export interface RuntimeUpdateInfo {
|
||||
@@ -28,6 +39,13 @@ export interface RuntimeUpdateInfo {
|
||||
rolloutHours?: unknown;
|
||||
}
|
||||
|
||||
export interface RuntimeDownloadProgressInfo {
|
||||
percent: number;
|
||||
transferred: number;
|
||||
total: number;
|
||||
bytesPerSecond: number;
|
||||
}
|
||||
|
||||
export interface RuntimeUpdateCheckResult {
|
||||
isUpdateAvailable: boolean;
|
||||
updateInfo: RuntimeUpdateInfo;
|
||||
@@ -35,8 +53,10 @@ export interface RuntimeUpdateCheckResult {
|
||||
|
||||
export interface AppUpdateRuntimeConfiguration {
|
||||
releaseChannel: AppReleaseChannel;
|
||||
autoDownload: boolean;
|
||||
shouldAdmitUpdate(info: RuntimeUpdateInfo): boolean | Promise<boolean>;
|
||||
onUpdateAvailable(info: RuntimeUpdateInfo): void;
|
||||
onDownloadProgress(progress: RuntimeDownloadProgressInfo): void;
|
||||
onUpdateDownloaded(info: RuntimeUpdateInfo): void;
|
||||
onError(error: unknown): void;
|
||||
}
|
||||
@@ -47,11 +67,19 @@ export interface AppUpdateInstallRequest {
|
||||
isForceRunAfter: boolean;
|
||||
}
|
||||
|
||||
export interface AppUpdateInstallLaunchResult {
|
||||
started: boolean;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
export interface AppUpdateRuntime {
|
||||
configure(input: AppUpdateRuntimeConfiguration): void;
|
||||
setAutoDownload?(enabled: boolean): void;
|
||||
checkForUpdates(): Promise<RuntimeUpdateCheckResult | null>;
|
||||
downloadUpdate(targetVersion: string): Promise<unknown>;
|
||||
quitAndInstall(input: AppUpdateInstallRequest): void;
|
||||
quitAndInstall(
|
||||
input: AppUpdateInstallRequest,
|
||||
): Promise<AppUpdateInstallLaunchResult> | AppUpdateInstallLaunchResult;
|
||||
}
|
||||
|
||||
export interface AppUpdateService {
|
||||
@@ -59,6 +87,7 @@ export interface AppUpdateService {
|
||||
currentVersion: string;
|
||||
releaseChannel: AppReleaseChannel;
|
||||
intent: AppUpdateCheckIntent;
|
||||
autoDownload?: boolean;
|
||||
}): Promise<AppUpdateCheckResult>;
|
||||
downloadAndInstallUpdate(
|
||||
input: {
|
||||
@@ -79,6 +108,9 @@ export interface AppUpdateServiceDeps {
|
||||
isPackaged(): boolean;
|
||||
now(): number;
|
||||
bucket(): Promise<number>;
|
||||
updateMode?: () => DesktopUpdateMode | Promise<DesktopUpdateMode>;
|
||||
onDownloadProgress?(progress: AppUpdateDownloadProgress | null): void;
|
||||
reportSettingsError?(error: unknown): void;
|
||||
reportCheckError?(error: unknown): void;
|
||||
reportRuntimeError?(error: unknown): void;
|
||||
reportInstallError?(message: string): void;
|
||||
@@ -88,14 +120,23 @@ function buildCheckResult(input: {
|
||||
currentVersion: string;
|
||||
hasUpdate: boolean;
|
||||
readyToInstall: boolean;
|
||||
downloading?: boolean;
|
||||
info?: RuntimeUpdateInfo | null;
|
||||
errorMessage?: string | null;
|
||||
}): AppUpdateCheckResult {
|
||||
const { currentVersion, hasUpdate, readyToInstall, info, errorMessage = null } = input;
|
||||
const {
|
||||
currentVersion,
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading = false,
|
||||
info,
|
||||
errorMessage = null,
|
||||
} = input;
|
||||
|
||||
return {
|
||||
hasUpdate,
|
||||
readyToInstall,
|
||||
downloading,
|
||||
currentVersion,
|
||||
latestVersion: info?.version ?? currentVersion,
|
||||
body: typeof info?.releaseNotes === "string" ? info.releaseNotes : null,
|
||||
@@ -117,11 +158,14 @@ async function performQuitAndInstall(
|
||||
},
|
||||
): Promise<void> {
|
||||
if (onBeforeQuit) await onBeforeQuit();
|
||||
runtime.quitAndInstall({
|
||||
const launch = await runtime.quitAndInstall({
|
||||
targetVersion,
|
||||
isSilent: !restart,
|
||||
isForceRunAfter: restart,
|
||||
});
|
||||
if (!launch.started) {
|
||||
throw new Error(launch.errorMessage ?? "Failed to launch update installer.");
|
||||
}
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown): string {
|
||||
@@ -145,6 +189,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
let configuredReleaseChannel: AppReleaseChannel | null = null;
|
||||
let preparationError: { version: string; message: string } | null = null;
|
||||
let preparingUpdateVersion: string | null = null;
|
||||
let currentAutoDownload = true;
|
||||
let checkQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
function isReadyToInstallVersion(version: string): boolean {
|
||||
@@ -156,6 +201,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
downloadedUpdateVersion = null;
|
||||
preparationError = null;
|
||||
preparingUpdateVersion = null;
|
||||
deps.onDownloadProgress?.(null);
|
||||
}
|
||||
|
||||
function buildPreviouslyAdmittedUpdateResult(
|
||||
@@ -167,42 +213,89 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
return null;
|
||||
}
|
||||
|
||||
const readyToInstall = isReadyToInstallVersion(info.version);
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: true,
|
||||
readyToInstall: isReadyToInstallVersion(info.version),
|
||||
readyToInstall,
|
||||
downloading: !readyToInstall && preparingUpdateVersion === info.version,
|
||||
info,
|
||||
errorMessage: preparationError?.version === info.version ? preparationError.message : null,
|
||||
});
|
||||
}
|
||||
|
||||
function configureRuntime(releaseChannel: AppReleaseChannel, intent: AppUpdateCheckIntent): void {
|
||||
async function resolveUpdateMode(): Promise<DesktopUpdateMode> {
|
||||
if (!deps.updateMode) {
|
||||
return "automatic";
|
||||
}
|
||||
try {
|
||||
return await deps.updateMode();
|
||||
} catch (error) {
|
||||
deps.reportSettingsError?.(error);
|
||||
return "automatic";
|
||||
}
|
||||
}
|
||||
|
||||
function resolveAutoDownload(mode: DesktopUpdateMode, override: boolean | undefined): boolean {
|
||||
return override ?? mode === "automatic";
|
||||
}
|
||||
|
||||
function configureRuntime(
|
||||
releaseChannel: AppReleaseChannel,
|
||||
intent: AppUpdateCheckIntent,
|
||||
initialAutoDownload: boolean,
|
||||
autoDownloadOverride: boolean | undefined,
|
||||
): void {
|
||||
if (configuredReleaseChannel !== releaseChannel) {
|
||||
clearUpdateState();
|
||||
configuredReleaseChannel = releaseChannel;
|
||||
}
|
||||
currentAutoDownload = initialAutoDownload;
|
||||
|
||||
deps.runtime.configure({
|
||||
releaseChannel,
|
||||
autoDownload: initialAutoDownload,
|
||||
shouldAdmitUpdate: async (info) => {
|
||||
const parsed = rolloutManifestSchema.parse(info);
|
||||
return shouldAdmitAppUpdate({
|
||||
const bucket = await deps.bucket();
|
||||
const liveMode = await resolveUpdateMode();
|
||||
if (intent === "automatic" && liveMode === "off") {
|
||||
return false;
|
||||
}
|
||||
const admitted = shouldAdmitAppUpdate({
|
||||
channel: releaseChannel,
|
||||
intent,
|
||||
rolloutHours: parsed.rolloutHours,
|
||||
releaseDate: parsed.releaseDate,
|
||||
now: deps.now(),
|
||||
bucket: await deps.bucket(),
|
||||
bucket,
|
||||
});
|
||||
if (admitted) {
|
||||
currentAutoDownload = resolveAutoDownload(liveMode, autoDownloadOverride);
|
||||
deps.runtime.setAutoDownload?.(currentAutoDownload);
|
||||
}
|
||||
return admitted;
|
||||
},
|
||||
onUpdateAvailable(info) {
|
||||
const alreadyReady = downloadedUpdateVersion === info.version;
|
||||
cachedUpdateInfo = info;
|
||||
downloadedUpdateVersion = alreadyReady ? info.version : null;
|
||||
if (!alreadyReady && preparingUpdateVersion === null) {
|
||||
if (!alreadyReady && currentAutoDownload && preparingUpdateVersion === null) {
|
||||
preparingUpdateVersion = info.version;
|
||||
}
|
||||
},
|
||||
onDownloadProgress(progress) {
|
||||
const percent = Number.isFinite(progress.percent)
|
||||
? Math.max(0, Math.min(100, progress.percent))
|
||||
: 0;
|
||||
deps.onDownloadProgress?.({
|
||||
version: preparingUpdateVersion ?? cachedUpdateInfo?.version ?? null,
|
||||
percent,
|
||||
transferred: Number.isFinite(progress.transferred) ? progress.transferred : 0,
|
||||
total: Number.isFinite(progress.total) ? progress.total : 0,
|
||||
bytesPerSecond: Number.isFinite(progress.bytesPerSecond) ? progress.bytesPerSecond : 0,
|
||||
});
|
||||
},
|
||||
onUpdateDownloaded(info) {
|
||||
// A superseded download can finish after a newer manifest check. Keep
|
||||
// the validated manifest as the install target in that case.
|
||||
@@ -214,6 +307,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
if (preparationError?.version === info.version) {
|
||||
preparationError = null;
|
||||
}
|
||||
deps.onDownloadProgress?.(null);
|
||||
},
|
||||
onError(error) {
|
||||
if (preparingUpdateVersion) {
|
||||
@@ -223,6 +317,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
};
|
||||
preparingUpdateVersion = null;
|
||||
}
|
||||
deps.onDownloadProgress?.(null);
|
||||
deps.reportRuntimeError?.(error);
|
||||
},
|
||||
});
|
||||
@@ -237,14 +332,58 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
return result;
|
||||
}
|
||||
|
||||
function resolveAvailableUpdateResult(
|
||||
currentVersion: string,
|
||||
info: RuntimeUpdateInfo,
|
||||
): AppUpdateCheckResult {
|
||||
const latestVersion = info.version;
|
||||
if (latestVersion === currentVersion) {
|
||||
clearUpdateState();
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
});
|
||||
}
|
||||
|
||||
cachedUpdateInfo = info;
|
||||
const readyToInstall = isReadyToInstallVersion(latestVersion);
|
||||
const errorMessage =
|
||||
preparationError?.version === latestVersion ? preparationError.message : null;
|
||||
if (!errorMessage) {
|
||||
preparationError = null;
|
||||
}
|
||||
if (
|
||||
!readyToInstall &&
|
||||
!errorMessage &&
|
||||
currentAutoDownload &&
|
||||
preparingUpdateVersion === null
|
||||
) {
|
||||
preparingUpdateVersion = latestVersion;
|
||||
}
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: true,
|
||||
readyToInstall,
|
||||
downloading:
|
||||
!readyToInstall &&
|
||||
!errorMessage &&
|
||||
(currentAutoDownload || preparingUpdateVersion === latestVersion),
|
||||
info,
|
||||
errorMessage,
|
||||
});
|
||||
}
|
||||
|
||||
async function checkForAppUpdate({
|
||||
currentVersion,
|
||||
releaseChannel,
|
||||
intent,
|
||||
autoDownload,
|
||||
}: {
|
||||
currentVersion: string;
|
||||
releaseChannel: AppReleaseChannel;
|
||||
intent: AppUpdateCheckIntent;
|
||||
autoDownload?: boolean;
|
||||
}): Promise<AppUpdateCheckResult> {
|
||||
if (!deps.isPackaged()) {
|
||||
return buildCheckResult({
|
||||
@@ -255,10 +394,33 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
}
|
||||
|
||||
return runCheckExclusively(async () => {
|
||||
configureRuntime(releaseChannel, intent);
|
||||
const mode = deps.updateMode ? await resolveUpdateMode() : "automatic";
|
||||
if (intent === "automatic" && mode === "off") {
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
});
|
||||
}
|
||||
if (intent === "manual") {
|
||||
preparationError = null;
|
||||
}
|
||||
configureRuntime(
|
||||
releaseChannel,
|
||||
intent,
|
||||
resolveAutoDownload(mode, autoDownload),
|
||||
autoDownload,
|
||||
);
|
||||
|
||||
try {
|
||||
const result = await deps.runtime.checkForUpdates();
|
||||
if (intent === "automatic" && deps.updateMode && (await resolveUpdateMode()) === "off") {
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
});
|
||||
}
|
||||
if (!result || !result.updateInfo) {
|
||||
clearUpdateState();
|
||||
return buildCheckResult({
|
||||
@@ -285,32 +447,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
});
|
||||
}
|
||||
|
||||
const info = result.updateInfo;
|
||||
const latestVersion = info.version;
|
||||
const hasUpdate = latestVersion !== currentVersion;
|
||||
|
||||
if (hasUpdate) {
|
||||
cachedUpdateInfo = info;
|
||||
const errorMessage =
|
||||
preparationError?.version === latestVersion ? preparationError.message : null;
|
||||
if (!errorMessage) {
|
||||
preparationError = null;
|
||||
}
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: true,
|
||||
readyToInstall: isReadyToInstallVersion(latestVersion),
|
||||
info,
|
||||
errorMessage,
|
||||
});
|
||||
}
|
||||
|
||||
clearUpdateState();
|
||||
return buildCheckResult({
|
||||
currentVersion,
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
});
|
||||
return resolveAvailableUpdateResult(currentVersion, result.updateInfo);
|
||||
} catch (error) {
|
||||
deps.reportCheckError?.(error);
|
||||
return buildCheckResult({
|
||||
@@ -345,18 +482,39 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
currentVersion,
|
||||
releaseChannel,
|
||||
intent: "manual",
|
||||
autoDownload: false,
|
||||
});
|
||||
if (!check.hasUpdate) {
|
||||
return {
|
||||
installed: false,
|
||||
version: currentVersion,
|
||||
message: check.errorMessage ?? "No update available.",
|
||||
...(check.errorMessage ? { errorMessage: check.errorMessage } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
return installCachedUpdate(currentVersion, { onBeforeQuit, restart: true });
|
||||
}
|
||||
|
||||
function clearPreparingVersion(version: string): void {
|
||||
if (preparingUpdateVersion === version) {
|
||||
preparingUpdateVersion = null;
|
||||
}
|
||||
deps.onDownloadProgress?.(null);
|
||||
}
|
||||
|
||||
function shouldRetryStaleDownloadError(
|
||||
attemptedVersion: string,
|
||||
readyVersion: string,
|
||||
signal?: AbortSignal,
|
||||
): boolean {
|
||||
return (
|
||||
attemptedVersion !== readyVersion &&
|
||||
cachedUpdateInfo?.version === readyVersion &&
|
||||
!signal?.aborted
|
||||
);
|
||||
}
|
||||
|
||||
async function ensureUpdateDownloaded(
|
||||
readyVersion: string,
|
||||
signal?: AbortSignal,
|
||||
@@ -367,14 +525,14 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
|
||||
const attemptedVersion: string = preparingUpdateVersion ?? readyVersion;
|
||||
preparingUpdateVersion ??= readyVersion;
|
||||
if (preparationError?.version === attemptedVersion) {
|
||||
preparationError = null;
|
||||
}
|
||||
try {
|
||||
await deps.runtime.downloadUpdate(attemptedVersion);
|
||||
} catch (error) {
|
||||
if (
|
||||
attemptedVersion !== readyVersion &&
|
||||
cachedUpdateInfo?.version === readyVersion &&
|
||||
!signal?.aborted
|
||||
) {
|
||||
clearPreparingVersion(attemptedVersion);
|
||||
if (shouldRetryStaleDownloadError(attemptedVersion, readyVersion, signal)) {
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
@@ -385,7 +543,9 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
// validated release instead of treating the stale artifact as ready.
|
||||
if (attemptedVersion === readyVersion && !isReadyToInstallVersion(readyVersion)) {
|
||||
downloadedUpdateVersion = readyVersion;
|
||||
preparingUpdateVersion = null;
|
||||
clearPreparingVersion(readyVersion);
|
||||
} else if (preparingUpdateVersion === attemptedVersion) {
|
||||
clearPreparingVersion(attemptedVersion);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -417,30 +577,19 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
return buildDeferredInstallResult(currentVersion);
|
||||
}
|
||||
|
||||
if (isReadyToInstallVersion(readyVersion)) {
|
||||
await performQuitAndInstall(deps.runtime, {
|
||||
targetVersion: readyVersion,
|
||||
onBeforeQuit,
|
||||
restart,
|
||||
});
|
||||
return {
|
||||
installed: true,
|
||||
version: readyVersion,
|
||||
message: "Update downloaded. The app will restart shortly.",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const preparation = await ensureUpdateDownloaded(readyVersion, signal);
|
||||
if (preparation === "aborted") {
|
||||
return buildDeferredInstallResult(currentVersion);
|
||||
}
|
||||
if (preparation === "superseded") {
|
||||
return {
|
||||
installed: false,
|
||||
version: currentVersion,
|
||||
message: "A newer update was found and will be installed later.",
|
||||
};
|
||||
if (!isReadyToInstallVersion(readyVersion)) {
|
||||
const preparation = await ensureUpdateDownloaded(readyVersion, signal);
|
||||
if (preparation === "aborted") {
|
||||
return buildDeferredInstallResult(currentVersion);
|
||||
}
|
||||
if (preparation === "superseded") {
|
||||
return {
|
||||
installed: false,
|
||||
version: currentVersion,
|
||||
message: "A newer update was found and will be installed later.",
|
||||
};
|
||||
}
|
||||
}
|
||||
await performQuitAndInstall(deps.runtime, {
|
||||
targetVersion: readyVersion,
|
||||
@@ -454,12 +603,14 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
message: "Update downloaded. The app will restart shortly.",
|
||||
};
|
||||
} catch (error) {
|
||||
deps.onDownloadProgress?.(null);
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
deps.reportInstallError?.(message);
|
||||
return {
|
||||
installed: false,
|
||||
version: currentVersion,
|
||||
message: `Update failed: ${message}`,
|
||||
errorMessage: message,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -476,6 +627,9 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
|
||||
if (!deps.isPackaged() || !downloadedUpdateVersion) {
|
||||
return false;
|
||||
}
|
||||
if ((await resolveUpdateMode()) !== "automatic") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const check = await checkForAppUpdate({
|
||||
currentVersion,
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { UUID } from "builder-util-runtime";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { autoUpdaterMock } = vi.hoisted(() => {
|
||||
const handlers = new Map<string, (value: unknown) => void>();
|
||||
const { autoUpdaterMock, getAllWindowsMock, desktopSettingsMock } = vi.hoisted(() => {
|
||||
const handlers = new Map<string, Set<(value: unknown) => void>>();
|
||||
return {
|
||||
getAllWindowsMock: vi.fn<() => unknown[]>(() => []),
|
||||
desktopSettingsMock: {
|
||||
mode: "automatic" as "automatic" | "notify" | "off",
|
||||
error: null as Error | null,
|
||||
},
|
||||
autoUpdaterMock: {
|
||||
handlers,
|
||||
handlers: {
|
||||
get: (event: string) => (value: unknown) => {
|
||||
for (const listener of handlers.get(event) ?? []) {
|
||||
listener(value);
|
||||
}
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
error: vi.fn((message: unknown) => console.error(message)),
|
||||
@@ -18,7 +30,15 @@ const { autoUpdaterMock } = vi.hoisted(() => {
|
||||
checkForUpdates: vi.fn(),
|
||||
downloadUpdate: vi.fn(),
|
||||
on: vi.fn((event: string, handler: (value: unknown) => void) => {
|
||||
handlers.set(event, handler);
|
||||
let set = handlers.get(event);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
handlers.set(event, set);
|
||||
}
|
||||
set.add(handler);
|
||||
}),
|
||||
removeListener: vi.fn((event: string, handler: (value: unknown) => void) => {
|
||||
handlers.get(event)?.delete(handler);
|
||||
}),
|
||||
quitAndInstall: vi.fn(),
|
||||
},
|
||||
@@ -30,6 +50,26 @@ vi.mock("electron", () => ({
|
||||
getPath: vi.fn(),
|
||||
isPackaged: true,
|
||||
},
|
||||
autoUpdater: undefined,
|
||||
BrowserWindow: {
|
||||
getAllWindows: getAllWindowsMock,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../settings/desktop-settings-electron.js", () => ({
|
||||
getDesktopSettingsStore: () => ({
|
||||
get: async () => {
|
||||
if (desktopSettingsMock.error) {
|
||||
throw desktopSettingsMock.error;
|
||||
}
|
||||
return {
|
||||
releaseChannel: "stable",
|
||||
updates: { mode: desktopSettingsMock.mode },
|
||||
notifications: { playSound: true },
|
||||
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true },
|
||||
};
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("electron-updater", () => ({
|
||||
@@ -40,8 +80,10 @@ import {
|
||||
bucketFromStagingUserId,
|
||||
checkForAppUpdate,
|
||||
createAppUpdateLifecycleLogger,
|
||||
downloadAndInstallUpdate,
|
||||
resolveStagingUserId,
|
||||
rolloutManifestSchema,
|
||||
runElectronQuitAndInstall,
|
||||
shouldAdmitToRollout,
|
||||
shouldInstallAppUpdateOnQuit,
|
||||
} from "./auto-updater";
|
||||
@@ -67,6 +109,7 @@ describe("checkForAppUpdate", () => {
|
||||
expect(result).toEqual({
|
||||
hasUpdate: false,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
currentVersion: "1.2.3",
|
||||
latestVersion: "1.2.3",
|
||||
body: null,
|
||||
@@ -97,6 +140,248 @@ describe("checkForAppUpdate", () => {
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it("configures electron-updater autoDownload from checkForAppUpdate options", async () => {
|
||||
autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({
|
||||
isUpdateAvailable: true,
|
||||
updateInfo: { version: "1.2.5" },
|
||||
});
|
||||
|
||||
const result = await checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: false,
|
||||
});
|
||||
|
||||
expect((autoUpdaterMock as unknown as { autoDownload?: boolean }).autoDownload).toBe(false);
|
||||
expect(result).toMatchObject({
|
||||
hasUpdate: true,
|
||||
readyToInstall: false,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.5",
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards download-progress to window progress bars and renderer events", async () => {
|
||||
const setProgressBar = vi.fn();
|
||||
const send = vi.fn();
|
||||
getAllWindowsMock.mockReturnValue([
|
||||
{ isDestroyed: () => false, setProgressBar, webContents: { send } },
|
||||
]);
|
||||
autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({
|
||||
isUpdateAvailable: true,
|
||||
updateInfo: { version: "1.2.6" },
|
||||
});
|
||||
|
||||
await checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: true,
|
||||
});
|
||||
autoUpdaterMock.handlers.get("download-progress")?.({
|
||||
percent: 42,
|
||||
transferred: 420,
|
||||
total: 1000,
|
||||
bytesPerSecond: 100,
|
||||
});
|
||||
|
||||
expect(setProgressBar).toHaveBeenCalledWith(0.42);
|
||||
expect(send).toHaveBeenCalledWith("paseo:event:app-update-download-progress", {
|
||||
version: "1.2.6",
|
||||
percent: 42,
|
||||
transferred: 420,
|
||||
total: 1000,
|
||||
bytesPerSecond: 100,
|
||||
});
|
||||
|
||||
autoUpdaterMock.handlers.get("update-downloaded")?.({ version: "1.2.6" });
|
||||
expect(setProgressBar).toHaveBeenLastCalledWith(-1);
|
||||
expect(send).toHaveBeenLastCalledWith("paseo:event:app-update-download-progress", null);
|
||||
getAllWindowsMock.mockReturnValue([]);
|
||||
});
|
||||
|
||||
it("gates automatic checks and autoDownload from desktop settings and falls back to automatic on read failure", async () => {
|
||||
const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
||||
try {
|
||||
autoUpdaterMock.checkForUpdates.mockClear();
|
||||
desktopSettingsMock.mode = "off";
|
||||
const offAuto = await checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
expect(offAuto.hasUpdate).toBe(false);
|
||||
expect(autoUpdaterMock.checkForUpdates).not.toHaveBeenCalled();
|
||||
|
||||
autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({
|
||||
isUpdateAvailable: true,
|
||||
updateInfo: { version: "1.2.9" },
|
||||
});
|
||||
const offManual = await checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "manual",
|
||||
});
|
||||
expect(offManual).toMatchObject({
|
||||
hasUpdate: true,
|
||||
downloading: false,
|
||||
latestVersion: "1.2.9",
|
||||
});
|
||||
|
||||
desktopSettingsMock.mode = "automatic";
|
||||
desktopSettingsMock.error = new SyntaxError("Unexpected token } in JSON");
|
||||
autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({
|
||||
isUpdateAvailable: true,
|
||||
updateInfo: { version: "1.2.10" },
|
||||
});
|
||||
const fallbackResult = await checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
});
|
||||
expect(fallbackResult).toMatchObject({
|
||||
hasUpdate: true,
|
||||
downloading: true,
|
||||
latestVersion: "1.2.10",
|
||||
});
|
||||
expect(consoleWarn).toHaveBeenCalled();
|
||||
autoUpdaterMock.handlers.get("update-downloaded")?.({ version: "1.2.10" });
|
||||
} finally {
|
||||
desktopSettingsMock.mode = "automatic";
|
||||
desktopSettingsMock.error = null;
|
||||
consoleWarn.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not fail update events when setProgressBar throws", async () => {
|
||||
const send = vi.fn();
|
||||
getAllWindowsMock.mockReturnValue([
|
||||
{
|
||||
isDestroyed: () => false,
|
||||
setProgressBar: () => {
|
||||
throw new Error("unsupported desktop environment");
|
||||
},
|
||||
webContents: { send },
|
||||
},
|
||||
]);
|
||||
autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({
|
||||
isUpdateAvailable: true,
|
||||
updateInfo: { version: "1.2.7" },
|
||||
});
|
||||
|
||||
await checkForAppUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
intent: "automatic",
|
||||
autoDownload: true,
|
||||
});
|
||||
expect(() => {
|
||||
autoUpdaterMock.handlers.get("download-progress")?.({
|
||||
percent: 50,
|
||||
transferred: 50,
|
||||
total: 100,
|
||||
bytesPerSecond: 10,
|
||||
});
|
||||
}).not.toThrow();
|
||||
expect(send).toHaveBeenCalledWith(
|
||||
"paseo:event:app-update-download-progress",
|
||||
expect.objectContaining({ version: "1.2.7", percent: 50 }),
|
||||
);
|
||||
getAllWindowsMock.mockReturnValue([]);
|
||||
});
|
||||
|
||||
it("reports a failure when quitAndInstall emits an installer error and returns normally", async () => {
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
autoUpdaterMock.checkForUpdates.mockResolvedValueOnce({
|
||||
isUpdateAvailable: true,
|
||||
updateInfo: { version: "1.2.8" },
|
||||
});
|
||||
autoUpdaterMock.downloadUpdate.mockResolvedValueOnce(undefined);
|
||||
autoUpdaterMock.quitAndInstall.mockImplementationOnce(() => {
|
||||
autoUpdaterMock.handlers.get("error")?.(new Error("EROFS: read-only file system"));
|
||||
});
|
||||
|
||||
const result = await downloadAndInstallUpdate({
|
||||
currentVersion: "1.2.3",
|
||||
releaseChannel: "stable",
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
installed: false,
|
||||
errorMessage: "EROFS: read-only file system",
|
||||
});
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it("waits on macOS explicit installs until Squirrel reports an error or signals quit, while returning immediately on quit-time handoff", async () => {
|
||||
const updater = Object.assign(new EventEmitter(), {
|
||||
quitAndInstall: vi.fn(),
|
||||
});
|
||||
const nativeUpdater = new EventEmitter();
|
||||
|
||||
const failedInstall = runElectronQuitAndInstall({
|
||||
platform: "darwin",
|
||||
updater,
|
||||
nativeUpdater,
|
||||
isSilent: false,
|
||||
isForceRunAfter: true,
|
||||
});
|
||||
expect(
|
||||
await Promise.race([failedInstall.then(() => "settled"), Promise.resolve("pending")]),
|
||||
).toBe("pending");
|
||||
|
||||
nativeUpdater.emit("error", new Error("Code signature invalid"));
|
||||
await expect(failedInstall).resolves.toEqual({
|
||||
started: false,
|
||||
errorMessage: "Code signature invalid",
|
||||
});
|
||||
expect(updater.listenerCount("error")).toBe(0);
|
||||
expect(nativeUpdater.listenerCount("error")).toBe(0);
|
||||
expect(nativeUpdater.listenerCount("before-quit-for-update")).toBe(0);
|
||||
|
||||
const restartInstall = runElectronQuitAndInstall({
|
||||
platform: "darwin",
|
||||
updater,
|
||||
nativeUpdater,
|
||||
isSilent: false,
|
||||
isForceRunAfter: true,
|
||||
});
|
||||
nativeUpdater.emit("before-quit-for-update");
|
||||
await expect(restartInstall).resolves.toEqual({ started: true });
|
||||
|
||||
// Quit-time install (isForceRunAfter: false) returns immediately so
|
||||
// quit-lifecycle owns its separate handoff deadline.
|
||||
await expect(
|
||||
runElectronQuitAndInstall({
|
||||
platform: "darwin",
|
||||
updater,
|
||||
nativeUpdater,
|
||||
isSilent: true,
|
||||
isForceRunAfter: false,
|
||||
}),
|
||||
).resolves.toEqual({ started: true });
|
||||
expect(nativeUpdater.listenerCount("before-quit-for-update")).toBe(0);
|
||||
|
||||
// Explicit install times out cleanly instead of hanging forever if Squirrel never emits.
|
||||
await expect(
|
||||
runElectronQuitAndInstall({
|
||||
platform: "darwin",
|
||||
updater,
|
||||
nativeUpdater,
|
||||
isSilent: false,
|
||||
isForceRunAfter: true,
|
||||
timeoutMs: 10,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
started: false,
|
||||
errorMessage: "Timed out waiting for the update installer to start.",
|
||||
});
|
||||
expect(updater.listenerCount("error")).toBe(0);
|
||||
expect(nativeUpdater.listenerCount("error")).toBe(0);
|
||||
expect(nativeUpdater.listenerCount("before-quit-for-update")).toBe(0);
|
||||
});
|
||||
|
||||
it("logs the update handoff with current and selected target versions", () => {
|
||||
const info = vi.fn();
|
||||
const lifecycleLog = createAppUpdateLifecycleLogger({ info });
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { app } from "electron";
|
||||
import { app, autoUpdater as electronAutoUpdater, BrowserWindow } from "electron";
|
||||
import { UUID } from "builder-util-runtime";
|
||||
import log from "electron-log/main";
|
||||
import { autoUpdater } from "electron-updater";
|
||||
import { getDesktopSettingsStore } from "../settings/desktop-settings-electron.js";
|
||||
import {
|
||||
createAppUpdateService,
|
||||
type AppUpdateCheckResult,
|
||||
type AppUpdateDownloadProgress,
|
||||
type AppUpdateInstallLaunchResult,
|
||||
type AppUpdateInstallRequest,
|
||||
type AppUpdateInstallResult,
|
||||
type AppUpdateRuntime,
|
||||
type AppUpdateRuntimeConfiguration,
|
||||
type RuntimeDownloadProgressInfo,
|
||||
type RuntimeUpdateCheckResult,
|
||||
type RuntimeUpdateInfo,
|
||||
} from "./app-update-service.js";
|
||||
@@ -30,6 +34,7 @@ export {
|
||||
type AppReleaseChannel,
|
||||
type AppUpdateCheckIntent,
|
||||
type AppUpdateCheckResult,
|
||||
type AppUpdateDownloadProgress,
|
||||
type AppUpdateInstallResult,
|
||||
};
|
||||
|
||||
@@ -140,11 +145,143 @@ export function shouldInstallAppUpdateOnQuit(input: {
|
||||
return !(input.platform === "linux" && input.isAppImage);
|
||||
}
|
||||
|
||||
const APP_UPDATE_DOWNLOAD_PROGRESS_EVENT = "paseo:event:app-update-download-progress";
|
||||
|
||||
function resolveProgressBarValue(progress: AppUpdateDownloadProgress | null): number {
|
||||
if (progress === null) return -1;
|
||||
if (!Number.isFinite(progress.percent)) return 0;
|
||||
return Math.max(0, Math.min(1, progress.percent / 100));
|
||||
}
|
||||
|
||||
function broadcastDownloadProgress(progress: AppUpdateDownloadProgress | null): void {
|
||||
const normalizedBar = resolveProgressBarValue(progress);
|
||||
for (const win of BrowserWindow.getAllWindows()) {
|
||||
if (win.isDestroyed()) continue;
|
||||
try {
|
||||
win.setProgressBar(normalizedBar);
|
||||
} catch {
|
||||
// Progress bar support is optional across desktop environments.
|
||||
}
|
||||
try {
|
||||
win.webContents.send(APP_UPDATE_DOWNLOAD_PROGRESS_EVENT, progress);
|
||||
} catch {
|
||||
// Window may be tearing down during quitAndInstall.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const MACOS_INSTALL_HANDOFF_TIMEOUT_MS = 2 * 60 * 1000;
|
||||
|
||||
export interface QuitAndInstallEventSource {
|
||||
on(event: string, listener: (...args: unknown[]) => void): unknown;
|
||||
removeListener?(event: string, listener: (...args: unknown[]) => void): unknown;
|
||||
}
|
||||
|
||||
function formatLaunchError(error: unknown): string {
|
||||
return error instanceof Error && typeof error.message === "string"
|
||||
? error.message
|
||||
: String(error);
|
||||
}
|
||||
|
||||
export function runElectronQuitAndInstall({
|
||||
platform,
|
||||
updater,
|
||||
nativeUpdater,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
timeoutMs = MACOS_INSTALL_HANDOFF_TIMEOUT_MS,
|
||||
}: {
|
||||
platform: NodeJS.Platform;
|
||||
updater: QuitAndInstallEventSource & {
|
||||
quitAndInstall(isSilent?: boolean, isForceRunAfter?: boolean): void;
|
||||
};
|
||||
nativeUpdater?: QuitAndInstallEventSource;
|
||||
isSilent: boolean;
|
||||
isForceRunAfter: boolean;
|
||||
timeoutMs?: number;
|
||||
}): Promise<AppUpdateInstallLaunchResult> {
|
||||
// Only await macOS Squirrel preparation for explicit Download / Restart Now
|
||||
// installs (isForceRunAfter === true). Quit-time installs (isForceRunAfter === false)
|
||||
// return immediately so quit-lifecycle owns its separate handoff deadline.
|
||||
if (platform !== "darwin" || !isForceRunAfter || typeof nativeUpdater?.on !== "function") {
|
||||
let launchError: unknown = null;
|
||||
const captureLaunchError = (error: unknown) => {
|
||||
launchError ??= error;
|
||||
};
|
||||
updater.on("error", captureLaunchError);
|
||||
try {
|
||||
updater.quitAndInstall(isSilent, isForceRunAfter);
|
||||
} catch (error) {
|
||||
launchError ??= error;
|
||||
} finally {
|
||||
updater.removeListener?.("error", captureLaunchError);
|
||||
}
|
||||
if (launchError !== null) {
|
||||
return Promise.resolve({ started: false, errorMessage: formatLaunchError(launchError) });
|
||||
}
|
||||
return Promise.resolve({ started: true });
|
||||
}
|
||||
|
||||
// With autoInstallOnAppQuit disabled, electron-updater's MacUpdater starts
|
||||
// native Squirrel preparation asynchronously inside quitAndInstall(). Keep
|
||||
// the explicit install promise pending until Squirrel hands off to quit, fails,
|
||||
// or hits the safety timeout.
|
||||
return new Promise<AppUpdateInstallLaunchResult>((resolve) => {
|
||||
let settled = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const cleanup = () => {
|
||||
if (timer !== undefined) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
updater.removeListener?.("error", handleError);
|
||||
nativeUpdater.removeListener?.("error", handleError);
|
||||
nativeUpdater.removeListener?.("update-not-available", handleNotAvailable);
|
||||
nativeUpdater.removeListener?.("before-quit-for-update", handleQuitStarted);
|
||||
};
|
||||
const finish = (result: AppUpdateInstallLaunchResult) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
cleanup();
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
const handleError = (error: unknown) => {
|
||||
finish({ started: false, errorMessage: formatLaunchError(error) });
|
||||
};
|
||||
const handleNotAvailable = () => {
|
||||
finish({ started: false, errorMessage: "Update could not be prepared for installation." });
|
||||
};
|
||||
const handleQuitStarted = () => {
|
||||
finish({ started: true });
|
||||
};
|
||||
|
||||
timer = setTimeout(() => {
|
||||
finish({
|
||||
started: false,
|
||||
errorMessage: "Timed out waiting for the update installer to start.",
|
||||
});
|
||||
}, timeoutMs);
|
||||
|
||||
updater.on("error", handleError);
|
||||
nativeUpdater.on("error", handleError);
|
||||
nativeUpdater.on("update-not-available", handleNotAvailable);
|
||||
nativeUpdater.on("before-quit-for-update", handleQuitStarted);
|
||||
|
||||
try {
|
||||
updater.quitAndInstall(isSilent, isForceRunAfter);
|
||||
} catch (error) {
|
||||
handleError(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
class ElectronAppUpdateRuntime implements AppUpdateRuntime {
|
||||
private configured = false;
|
||||
private configuration: AppUpdateRuntimeConfiguration | null = null;
|
||||
|
||||
configure(input: AppUpdateRuntimeConfiguration): void {
|
||||
autoUpdater.autoDownload = true;
|
||||
this.configuration = input;
|
||||
autoUpdater.autoDownload = input.autoDownload;
|
||||
autoUpdater.autoRunAppAfterInstall = true;
|
||||
// Paseo revalidates the current manifest before explicitly installing on quit.
|
||||
// Electron's built-in handler would install an older download without checking
|
||||
@@ -155,7 +292,7 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
|
||||
autoUpdater.allowDowngrade = false;
|
||||
autoUpdater.isUserWithinRollout = async (info) => {
|
||||
try {
|
||||
return await input.shouldAdmitUpdate(info as RuntimeUpdateInfo);
|
||||
return await (this.configuration?.shouldAdmitUpdate(info as RuntimeUpdateInfo) ?? true);
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
@@ -179,19 +316,26 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
|
||||
autoUpdater.on("update-available", (info) => {
|
||||
const updateInfo = info as RuntimeUpdateInfo;
|
||||
updateLifecycleLog.updateAvailable(updateInfo.version);
|
||||
input.onUpdateAvailable(updateInfo);
|
||||
this.configuration?.onUpdateAvailable(updateInfo);
|
||||
});
|
||||
autoUpdater.on("download-progress", (progress) => {
|
||||
this.configuration?.onDownloadProgress(progress as RuntimeDownloadProgressInfo);
|
||||
});
|
||||
autoUpdater.on("update-downloaded", (info) => {
|
||||
const updateInfo = info as RuntimeUpdateInfo;
|
||||
updateLifecycleLog.updateDownloaded(updateInfo.version);
|
||||
input.onUpdateDownloaded(updateInfo);
|
||||
this.configuration?.onUpdateDownloaded(updateInfo);
|
||||
});
|
||||
autoUpdater.on("error", (error) => {
|
||||
if (isUpdateChannelNotPublished(error)) return;
|
||||
input.onError(error);
|
||||
this.configuration?.onError(error);
|
||||
});
|
||||
}
|
||||
|
||||
setAutoDownload(enabled: boolean): void {
|
||||
autoUpdater.autoDownload = enabled;
|
||||
}
|
||||
|
||||
async checkForUpdates(): Promise<RuntimeUpdateCheckResult | null> {
|
||||
try {
|
||||
const result = await autoUpdater.checkForUpdates();
|
||||
@@ -211,14 +355,25 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
|
||||
return autoUpdater.downloadUpdate();
|
||||
}
|
||||
|
||||
quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest): void {
|
||||
quitAndInstall({
|
||||
targetVersion,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
}: AppUpdateInstallRequest): Promise<AppUpdateInstallLaunchResult> {
|
||||
broadcastDownloadProgress(null);
|
||||
autoUpdater.autoRunAppAfterInstall = isForceRunAfter;
|
||||
updateLifecycleLog.quitAndInstallRequested({
|
||||
targetVersion,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
});
|
||||
autoUpdater.quitAndInstall(isSilent, isForceRunAfter);
|
||||
return runElectronQuitAndInstall({
|
||||
platform: process.platform,
|
||||
updater: autoUpdater,
|
||||
nativeUpdater: electronAutoUpdater,
|
||||
isSilent,
|
||||
isForceRunAfter,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,6 +382,14 @@ const appUpdateService = createAppUpdateService({
|
||||
isPackaged: () => app.isPackaged,
|
||||
now: () => Date.now(),
|
||||
bucket: async () => bucketFromStagingUserId(await getStagingUserId()),
|
||||
updateMode: async () => (await getDesktopSettingsStore().get()).updates.mode,
|
||||
onDownloadProgress: broadcastDownloadProgress,
|
||||
reportSettingsError: (error) => {
|
||||
console.warn(
|
||||
"[auto-updater] Failed to read desktop update mode, defaulting to automatic:",
|
||||
error,
|
||||
);
|
||||
},
|
||||
reportCheckError: (error) => {
|
||||
console.error("[auto-updater] Failed to check for updates:", error);
|
||||
},
|
||||
@@ -246,16 +409,19 @@ export async function checkForAppUpdate({
|
||||
currentVersion,
|
||||
releaseChannel,
|
||||
intent,
|
||||
autoDownload,
|
||||
}: {
|
||||
currentVersion: string;
|
||||
releaseChannel: AppReleaseChannel;
|
||||
intent: AppUpdateCheckIntent;
|
||||
autoDownload?: boolean;
|
||||
}): Promise<AppUpdateCheckResult> {
|
||||
updateLifecycleLog.checkStarted({ currentVersion, releaseChannel, intent });
|
||||
const result = await appUpdateService.checkForAppUpdate({
|
||||
currentVersion,
|
||||
releaseChannel,
|
||||
intent,
|
||||
autoDownload,
|
||||
});
|
||||
updateLifecycleLog.checkCompleted({
|
||||
currentVersion,
|
||||
|
||||
@@ -1058,10 +1058,18 @@ const quitLifecycle = createQuitLifecycle({
|
||||
showShutdownFeedback: showDaemonShutdownDialog,
|
||||
}),
|
||||
installAppUpdateOnQuit: async (signal) => {
|
||||
const settings = await getDesktopSettingsStore().get();
|
||||
let releaseChannel: "stable" | "beta" = "stable";
|
||||
try {
|
||||
releaseChannel = (await getDesktopSettingsStore().get()).releaseChannel;
|
||||
} catch (error) {
|
||||
log.warn(
|
||||
"[auto-updater] Failed to read desktop settings on quit, defaulting to stable:",
|
||||
error,
|
||||
);
|
||||
}
|
||||
return installAppUpdateOnQuit({
|
||||
currentVersion: app.getVersion(),
|
||||
releaseChannel: settings.releaseChannel,
|
||||
releaseChannel,
|
||||
signal,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -81,6 +81,7 @@ describe("desktop-settings", () => {
|
||||
|
||||
expect(settings).toEqual({
|
||||
releaseChannel: "stable",
|
||||
updates: { mode: "automatic" },
|
||||
notifications: { playSound: true },
|
||||
daemon: {
|
||||
manageBuiltInDaemon: true,
|
||||
@@ -97,12 +98,14 @@ describe("desktop-settings", () => {
|
||||
await store.get();
|
||||
const next = await store.patch({
|
||||
releaseChannel: "beta",
|
||||
updates: { mode: "notify" },
|
||||
daemon: { keepRunningAfterQuit: false },
|
||||
});
|
||||
const files = await readdir(userDataPath);
|
||||
|
||||
expect(next).toEqual({
|
||||
releaseChannel: "beta",
|
||||
updates: { mode: "notify" },
|
||||
notifications: { playSound: true },
|
||||
daemon: {
|
||||
manageBuiltInDaemon: true,
|
||||
@@ -112,6 +115,65 @@ describe("desktop-settings", () => {
|
||||
expect(files).toEqual(["desktop-settings.json"]);
|
||||
});
|
||||
|
||||
it("defaults updates.mode to automatic and persists explicit choices across restarts", async () => {
|
||||
const userDataPath = await createTempUserDataDir();
|
||||
directories.add(userDataPath);
|
||||
await writeFile(
|
||||
settingsFilePath(userDataPath),
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
settings: {
|
||||
releaseChannel: "stable",
|
||||
updates: { mode: "invalid" },
|
||||
},
|
||||
migrations: {
|
||||
legacyRendererSettingsImported: true,
|
||||
daemonStopOnQuitDefaultApplied: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const defaulted = await createDesktopSettingsStore({ userDataPath }).get();
|
||||
expect(defaulted.updates.mode).toBe("automatic");
|
||||
|
||||
await createDesktopSettingsStore({ userDataPath }).patch({ updates: { mode: "off" } });
|
||||
const persisted = await createDesktopSettingsStore({ userDataPath }).get();
|
||||
expect(persisted.updates.mode).toBe("off");
|
||||
});
|
||||
|
||||
it("serializes overlapping patches so neither update mode nor release channel is lost", async () => {
|
||||
const userDataPath = await createTempUserDataDir();
|
||||
directories.add(userDataPath);
|
||||
const store = createDesktopSettingsStore({ userDataPath });
|
||||
|
||||
const [offResult, betaResult] = await Promise.all([
|
||||
store.patch({ updates: { mode: "off" } }),
|
||||
store.patch({ releaseChannel: "beta" }),
|
||||
]);
|
||||
|
||||
expect(offResult.updates.mode).toBe("off");
|
||||
expect(betaResult.updates.mode).toBe("off");
|
||||
expect(betaResult.releaseChannel).toBe("beta");
|
||||
|
||||
const reloaded = await createDesktopSettingsStore({ userDataPath }).get();
|
||||
expect(reloaded.updates.mode).toBe("off");
|
||||
expect(reloaded.releaseChannel).toBe("beta");
|
||||
});
|
||||
|
||||
it("waits for an in-flight patch before resolving get() from cache", async () => {
|
||||
const userDataPath = await createTempUserDataDir();
|
||||
directories.add(userDataPath);
|
||||
const store = createDesktopSettingsStore({ userDataPath });
|
||||
|
||||
await store.patch({ updates: { mode: "off" } });
|
||||
const patchPromise = store.patch({ updates: { mode: "automatic" } });
|
||||
const readDuringPatch = store.get();
|
||||
|
||||
const [patched, read] = await Promise.all([patchPromise, readDuringPatch]);
|
||||
expect(patched.updates.mode).toBe("automatic");
|
||||
expect(read.updates.mode).toBe("automatic");
|
||||
});
|
||||
|
||||
it("defaults notification sounds on for existing settings documents", async () => {
|
||||
const userDataPath = await createTempUserDataDir();
|
||||
directories.add(userDataPath);
|
||||
@@ -270,6 +332,7 @@ describe("desktop-settings", () => {
|
||||
|
||||
expect(migrated).toEqual({
|
||||
releaseChannel: "beta",
|
||||
updates: { mode: "automatic" },
|
||||
notifications: { playSound: true },
|
||||
daemon: {
|
||||
manageBuiltInDaemon: false,
|
||||
@@ -315,6 +378,7 @@ describe("desktop-settings", () => {
|
||||
expect(persisted.settings.releaseChannel).toBe("beta");
|
||||
expect(next).toEqual({
|
||||
releaseChannel: "beta",
|
||||
updates: { mode: "automatic" },
|
||||
notifications: { playSound: false },
|
||||
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: false },
|
||||
});
|
||||
|
||||
@@ -6,8 +6,13 @@ import { z } from "zod";
|
||||
|
||||
import type { AppReleaseChannel } from "../features/auto-updater.js";
|
||||
|
||||
export type DesktopUpdateMode = "automatic" | "notify" | "off";
|
||||
|
||||
export interface DesktopSettings {
|
||||
releaseChannel: AppReleaseChannel;
|
||||
updates: {
|
||||
mode: DesktopUpdateMode;
|
||||
};
|
||||
notifications: {
|
||||
playSound: boolean;
|
||||
};
|
||||
@@ -19,6 +24,7 @@ export interface DesktopSettings {
|
||||
|
||||
interface DesktopSettingsPatch {
|
||||
releaseChannel?: AppReleaseChannel;
|
||||
updates?: Partial<DesktopSettings["updates"]>;
|
||||
notifications?: Partial<DesktopSettings["notifications"]>;
|
||||
daemon?: Partial<DesktopSettings["daemon"]>;
|
||||
}
|
||||
@@ -31,6 +37,9 @@ export interface DesktopSettingsStore {
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
releaseChannel: "stable",
|
||||
updates: {
|
||||
mode: "automatic",
|
||||
},
|
||||
notifications: {
|
||||
playSound: true,
|
||||
},
|
||||
@@ -43,6 +52,13 @@ export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
const DESKTOP_SETTINGS_FILENAME = "desktop-settings.json";
|
||||
|
||||
const ReleaseChannelSchema = z.enum(["stable", "beta"]);
|
||||
const UpdateModeSchema = z.enum(["automatic", "notify", "off"]);
|
||||
|
||||
const UpdatesSchema = z
|
||||
.looseObject({
|
||||
mode: UpdateModeSchema.catch(DEFAULT_DESKTOP_SETTINGS.updates.mode),
|
||||
})
|
||||
.catch(() => ({ ...DEFAULT_DESKTOP_SETTINGS.updates }));
|
||||
|
||||
const NotificationsSchema = z
|
||||
.looseObject({
|
||||
@@ -60,6 +76,7 @@ const DaemonSchema = z
|
||||
const DesktopSettingsSchema = z
|
||||
.looseObject({
|
||||
releaseChannel: ReleaseChannelSchema.catch(DEFAULT_DESKTOP_SETTINGS.releaseChannel),
|
||||
updates: UpdatesSchema,
|
||||
notifications: NotificationsSchema,
|
||||
daemon: DaemonSchema,
|
||||
})
|
||||
@@ -95,6 +112,11 @@ function coerceReleaseChannel(value: unknown): AppReleaseChannel | null {
|
||||
return result.success ? result.data : null;
|
||||
}
|
||||
|
||||
function coerceUpdateMode(value: unknown): DesktopUpdateMode | null {
|
||||
const result = UpdateModeSchema.safeParse(value);
|
||||
return result.success ? result.data : null;
|
||||
}
|
||||
|
||||
function coerceBoolean(value: unknown): boolean | null {
|
||||
return typeof value === "boolean" ? value : null;
|
||||
}
|
||||
@@ -106,6 +128,7 @@ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
|
||||
function buildDefaultSettings(): StoredDesktopSettings {
|
||||
return {
|
||||
releaseChannel: DEFAULT_DESKTOP_SETTINGS.releaseChannel,
|
||||
updates: { ...DEFAULT_DESKTOP_SETTINGS.updates },
|
||||
notifications: { ...DEFAULT_DESKTOP_SETTINGS.notifications },
|
||||
daemon: { ...DEFAULT_DESKTOP_SETTINGS.daemon },
|
||||
};
|
||||
@@ -125,6 +148,7 @@ function buildDefaultDocument(): PersistedDesktopSettingsDocument {
|
||||
function toDesktopSettings(stored: StoredDesktopSettings): DesktopSettings {
|
||||
return {
|
||||
releaseChannel: stored.releaseChannel,
|
||||
updates: { mode: stored.updates.mode },
|
||||
notifications: { playSound: stored.notifications.playSound },
|
||||
daemon: {
|
||||
manageBuiltInDaemon: stored.daemon.manageBuiltInDaemon,
|
||||
@@ -144,6 +168,13 @@ function coerceDesktopSettingsPatch(input: unknown): DesktopSettingsPatch {
|
||||
patch.releaseChannel = releaseChannel;
|
||||
}
|
||||
|
||||
if (isRecord(input.updates)) {
|
||||
const mode = coerceUpdateMode(input.updates.mode);
|
||||
if (mode) {
|
||||
patch.updates = { mode };
|
||||
}
|
||||
}
|
||||
|
||||
if (isRecord(input.notifications)) {
|
||||
const playSound = coerceBoolean(input.notifications.playSound);
|
||||
if (playSound !== null) {
|
||||
@@ -197,6 +228,7 @@ function mergeDesktopSettings(
|
||||
return {
|
||||
...current,
|
||||
releaseChannel: patch.releaseChannel ?? current.releaseChannel,
|
||||
updates: { ...current.updates, ...patch.updates },
|
||||
notifications: { ...current.notifications, ...patch.notifications },
|
||||
daemon: { ...current.daemon, ...patch.daemon },
|
||||
};
|
||||
@@ -232,22 +264,26 @@ export function createDesktopSettingsStore({
|
||||
}): DesktopSettingsStore {
|
||||
const filePath = path.join(userDataPath, DESKTOP_SETTINGS_FILENAME);
|
||||
let cachedDocument: PersistedDesktopSettingsDocument | null = null;
|
||||
let persistQueue: Promise<void> = Promise.resolve();
|
||||
let operationQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
async function persistDocument(document: PersistedDesktopSettingsDocument): Promise<void> {
|
||||
const write = async () => {
|
||||
await mkdir(userDataPath, { recursive: true });
|
||||
const tempFilePath = `${filePath}.tmp.${process.pid}.${randomUUID()}`;
|
||||
await writeFile(tempFilePath, `${JSON.stringify(document, null, 2)}\n`, "utf8");
|
||||
await rename(tempFilePath, filePath);
|
||||
cachedDocument = document;
|
||||
};
|
||||
const queued = persistQueue.then(write, write);
|
||||
persistQueue = queued.catch(() => undefined);
|
||||
await queued;
|
||||
function enqueueOperation<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const result = operationQueue.then(operation, operation);
|
||||
operationQueue = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
async function loadDocument(): Promise<PersistedDesktopSettingsDocument> {
|
||||
async function writeDocument(document: PersistedDesktopSettingsDocument): Promise<void> {
|
||||
await mkdir(userDataPath, { recursive: true });
|
||||
const tempFilePath = `${filePath}.tmp.${process.pid}.${randomUUID()}`;
|
||||
await writeFile(tempFilePath, `${JSON.stringify(document, null, 2)}\n`, "utf8");
|
||||
await rename(tempFilePath, filePath);
|
||||
cachedDocument = document;
|
||||
}
|
||||
|
||||
async function loadDocumentUnlocked(): Promise<PersistedDesktopSettingsDocument> {
|
||||
if (cachedDocument) {
|
||||
return cachedDocument;
|
||||
}
|
||||
@@ -260,7 +296,7 @@ export function createDesktopSettingsStore({
|
||||
throw error;
|
||||
}
|
||||
const document = buildDefaultDocument();
|
||||
await persistDocument(document);
|
||||
await writeDocument(document);
|
||||
return document;
|
||||
}
|
||||
const document = coerceDocument(JSON.parse(raw));
|
||||
@@ -268,58 +304,67 @@ export function createDesktopSettingsStore({
|
||||
return document;
|
||||
}
|
||||
|
||||
async function initializeLegacyRendererMigration(): Promise<PersistedDesktopSettingsDocument> {
|
||||
async function initializeLegacyRendererMigrationUnlocked(): Promise<PersistedDesktopSettingsDocument> {
|
||||
try {
|
||||
return await loadDocument();
|
||||
return await loadDocumentUnlocked();
|
||||
} catch {
|
||||
const document = buildDefaultDocument();
|
||||
await persistDocument(document);
|
||||
await writeDocument(document);
|
||||
return document;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async get(): Promise<DesktopSettings> {
|
||||
const document = await loadDocument();
|
||||
const document = await enqueueOperation(async () => {
|
||||
if (cachedDocument) {
|
||||
return cachedDocument;
|
||||
}
|
||||
return loadDocumentUnlocked();
|
||||
});
|
||||
return toDesktopSettings(document.settings);
|
||||
},
|
||||
|
||||
async patch(patch: unknown): Promise<DesktopSettings> {
|
||||
const current = await loadDocument();
|
||||
const coercedPatch = coerceDesktopSettingsPatch(patch);
|
||||
const next = mergeDesktopSettings(current.settings, coercedPatch);
|
||||
await persistDocument({
|
||||
...current,
|
||||
settings: next,
|
||||
migrations: {
|
||||
...current.migrations,
|
||||
legacyRendererSettingsImported:
|
||||
current.migrations.legacyRendererSettingsImported ||
|
||||
hasLegacyRendererOwnedPatch(coercedPatch),
|
||||
},
|
||||
return enqueueOperation(async () => {
|
||||
const current = await loadDocumentUnlocked();
|
||||
const coercedPatch = coerceDesktopSettingsPatch(patch);
|
||||
const next = mergeDesktopSettings(current.settings, coercedPatch);
|
||||
await writeDocument({
|
||||
...current,
|
||||
settings: next,
|
||||
migrations: {
|
||||
...current.migrations,
|
||||
legacyRendererSettingsImported:
|
||||
current.migrations.legacyRendererSettingsImported ||
|
||||
hasLegacyRendererOwnedPatch(coercedPatch),
|
||||
},
|
||||
});
|
||||
return toDesktopSettings(next);
|
||||
});
|
||||
return toDesktopSettings(next);
|
||||
},
|
||||
|
||||
async migrateLegacyRendererSettings(legacySettings: unknown): Promise<DesktopSettings> {
|
||||
const current = await initializeLegacyRendererMigration();
|
||||
if (current.migrations.legacyRendererSettingsImported) {
|
||||
return toDesktopSettings(current.settings);
|
||||
}
|
||||
return enqueueOperation(async () => {
|
||||
const current = await initializeLegacyRendererMigrationUnlocked();
|
||||
if (current.migrations.legacyRendererSettingsImported) {
|
||||
return toDesktopSettings(current.settings);
|
||||
}
|
||||
|
||||
const next = mergeDesktopSettings(
|
||||
current.settings,
|
||||
pickDesktopSettingsFromLegacyRendererSettings(legacySettings),
|
||||
);
|
||||
await persistDocument({
|
||||
...current,
|
||||
settings: next,
|
||||
migrations: {
|
||||
...current.migrations,
|
||||
legacyRendererSettingsImported: true,
|
||||
},
|
||||
const next = mergeDesktopSettings(
|
||||
current.settings,
|
||||
pickDesktopSettingsFromLegacyRendererSettings(legacySettings),
|
||||
);
|
||||
await writeDocument({
|
||||
...current,
|
||||
settings: next,
|
||||
migrations: {
|
||||
...current.migrations,
|
||||
legacyRendererSettingsImported: true,
|
||||
},
|
||||
});
|
||||
return toDesktopSettings(next);
|
||||
});
|
||||
return toDesktopSettings(next);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -6,84 +6,43 @@ 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");
|
||||
|
||||
interface SkillExample {
|
||||
heading: string;
|
||||
files: Record<string, string>;
|
||||
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;
|
||||
}
|
||||
|
||||
// Groups every ts and tsx block under its nearest heading. Each block starts with a `// <path>`
|
||||
// comment that places it in a plugin, so the blocks of one heading form one plugin.
|
||||
function skillExamples(): SkillExample[] {
|
||||
const examples: SkillExample[] = [];
|
||||
let heading = "";
|
||||
for (const match of skill.matchAll(/^(#{1,6}) (.+)$|^```(tsx?)\n([\s\S]*?)\n```$/gm)) {
|
||||
if (match[2]) {
|
||||
heading = match[2];
|
||||
continue;
|
||||
}
|
||||
const code = match[4] ?? "";
|
||||
const file = /^\/\/ ([\w./-]+\.tsx?)\n/.exec(code)?.[1];
|
||||
if (!file)
|
||||
throw new Error(`A ${match[3]} block under "${heading}" does not start with // <path>`);
|
||||
let example = examples.at(-1);
|
||||
if (example?.heading !== heading) {
|
||||
example = { heading, files: {} };
|
||||
examples.push(example);
|
||||
}
|
||||
if (example.files[file]) throw new Error(`"${heading}" has two blocks for ${file}`);
|
||||
example.files[file] = code;
|
||||
}
|
||||
return examples;
|
||||
}
|
||||
|
||||
// Checks plugin files, keyed by path in the plugin, with the same options as the plugin examples.
|
||||
function typeErrors(files: Record<string, string>): string[] {
|
||||
// Checks the example as a plugin client file, with the same options as the plugin examples.
|
||||
function typeErrors(code: string): string[] {
|
||||
const configPath = path.join(repository, "packages/plugin/tsconfig.examples.json");
|
||||
const { config } = ts.readConfigFile(configPath, ts.sys.readFile);
|
||||
const { options } = ts.parseJsonConfigFileContent(config, ts.sys, path.dirname(configPath));
|
||||
const sources = new Map(
|
||||
Object.entries(files).map(([file, code]) => [path.join(pluginRoot, file), code]),
|
||||
);
|
||||
const file = path.join(repository, "plugin-examples/skill-example/client/example.tsx");
|
||||
const host = ts.createCompilerHost(options);
|
||||
const getSourceFile = host.getSourceFile;
|
||||
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);
|
||||
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);
|
||||
return ts
|
||||
.getPreEmitDiagnostics(program)
|
||||
.map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
|
||||
}
|
||||
|
||||
describe("paseo-plugin skill examples", () => {
|
||||
const examples = skillExamples();
|
||||
|
||||
it("has examples", () => {
|
||||
expect(examples.length).toBeGreaterThan(0);
|
||||
it("composer pill example typechecks against the plugin SDK", () => {
|
||||
expect(typeErrors(sectionCode("Add a composer pill"))).toEqual([]);
|
||||
});
|
||||
|
||||
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({
|
||||
"client/example.tsx": `
|
||||
typeErrors(`
|
||||
import { defineTranslations, useTranslation, type PluginClientContext } from "@getpaseo/plugin/client";
|
||||
import en from "../../translations/client/locales/en.json";
|
||||
const json = defineTranslations({ resources: { en } });
|
||||
@@ -108,16 +67,14 @@ 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({
|
||||
"client/example.tsx": `
|
||||
typeErrors(`
|
||||
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";
|
||||
@@ -153,7 +110,6 @@ 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([]);
|
||||
});
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { PluginSessionsRuntime } from "../plugins/agent-tools.js";
|
||||
import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js";
|
||||
import {
|
||||
prepareAgentMessage,
|
||||
@@ -680,24 +679,6 @@ async function startAndSteerThroughManager(
|
||||
return { manager, agentId: agent.id, workdir };
|
||||
}
|
||||
|
||||
/** Plugin sessions whose only plugin appends the given instructions to every open. */
|
||||
function instructionPluginSessions(instructions: () => string[]): PluginSessionsRuntime {
|
||||
return {
|
||||
openSession: async (request) => ({
|
||||
...request,
|
||||
appendSystemPrompt: instructions(),
|
||||
tools: [],
|
||||
mcpServerOwners: {},
|
||||
}),
|
||||
sessionLaunched: () => {},
|
||||
sessionLaunchFailed: () => {},
|
||||
refreshSession: async () => ({ stale: false }),
|
||||
sessionTools: () => [],
|
||||
closeSession: () => {},
|
||||
callTool: async () => ({ isError: true, text: "No plugin tools" }),
|
||||
};
|
||||
}
|
||||
|
||||
test("OpenCode persistence excludes launch-only instructions from storage and clients", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-persistence-"));
|
||||
const harness = new V2Harness();
|
||||
@@ -709,7 +690,13 @@ test("OpenCode persistence excludes launch-only instructions from storage and cl
|
||||
registry: storage,
|
||||
logger,
|
||||
appendSystemPrompt: "Daemon instruction",
|
||||
pluginSessions: instructionPluginSessions(() => ["Plugin instruction"]),
|
||||
pluginLifecycle: {
|
||||
emit: () => {},
|
||||
before: async (name, request) =>
|
||||
name === "agent.open.before"
|
||||
? { ...request, appendSystemPrompt: ["Plugin instruction"] }
|
||||
: request,
|
||||
},
|
||||
});
|
||||
const agent = await manager.createAgent({ provider: "opencode", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
@@ -16157,7 +16144,11 @@ test("plugin instructions are recomputed for each launch without changing saved
|
||||
registry: storage,
|
||||
logger,
|
||||
appendSystemPrompt: "Daemon",
|
||||
pluginSessions: instructionPluginSessions(() => additions),
|
||||
pluginLifecycle: {
|
||||
emit: () => {},
|
||||
before: async (name, request) =>
|
||||
name === "agent.open.before" ? { ...request, appendSystemPrompt: additions } : request,
|
||||
},
|
||||
});
|
||||
const snapshot = await manager.createAgent(
|
||||
{ provider: "codex", cwd: workdir, systemPrompt: "Saved" },
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import type {
|
||||
AttachedAgentTool,
|
||||
PluginSessionsRuntime,
|
||||
SessionOpenAgentFacts,
|
||||
} from "../plugins/agent-tools.js";
|
||||
import type { AttachedAgentTool, PluginAgentToolsRuntime } from "../plugins/agent-tools.js";
|
||||
import { ProviderOptionsValidationError } from "./provider-options.js";
|
||||
import type { AgentToolResult } from "@getpaseo/plugin/server";
|
||||
import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js";
|
||||
@@ -207,26 +203,6 @@ async function assertUsableWorkingDirectory(cwd: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
interface ResumeAgentOptions {
|
||||
createdAt?: Date;
|
||||
updatedAt?: Date;
|
||||
lastUserMessageAt?: Date | null;
|
||||
labels?: Record<string, string>;
|
||||
metadata?: AgentMetadata;
|
||||
workspaceId?: string;
|
||||
owner?: AgentOwner;
|
||||
background?: boolean;
|
||||
attention?: AttentionState;
|
||||
}
|
||||
|
||||
interface PluginToolCall {
|
||||
pluginId: string;
|
||||
toolName: string;
|
||||
agentId: string;
|
||||
input: unknown;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
interface StopAgentBackgroundWorkOptions {
|
||||
agentId: string;
|
||||
itemId: string;
|
||||
@@ -423,7 +399,7 @@ export interface AgentManagerOptions {
|
||||
terminalManager?: TerminalManager | null;
|
||||
mcpBaseUrl?: string;
|
||||
mcpAuthToken?: string;
|
||||
pluginSessions?: PluginSessionsRuntime;
|
||||
pluginAgentTools?: PluginAgentToolsRuntime;
|
||||
paseoToolsEnabled?: boolean;
|
||||
paseoToolCatalogFactory?: PaseoToolCatalogFactory;
|
||||
resolvePaseoToolPolicy?: (provider: AgentProvider) => ProviderPaseoToolsPolicy | undefined;
|
||||
@@ -961,7 +937,10 @@ export class AgentManager {
|
||||
private readonly agentStreamCoalescer: AgentStreamCoalescer;
|
||||
private mcpBaseUrl: string | null;
|
||||
private readonly mcpAuthToken: string | null;
|
||||
private readonly pluginSessions: PluginSessionsRuntime | undefined;
|
||||
private sessionOpenGeneration = 0;
|
||||
private readonly sessionOpenGenerations = new Map<string, number>();
|
||||
private readonly attachedPluginTools = new Map<string, AttachedAgentTool[]>();
|
||||
private readonly pluginAgentTools: PluginAgentToolsRuntime | undefined;
|
||||
private paseoToolsEnabled = true;
|
||||
private paseoToolCatalogFactory: PaseoToolCatalogFactory | null = null;
|
||||
private readonly paseoToolPolicies = new Map<string, ProviderPaseoToolsPolicy | undefined>();
|
||||
@@ -979,7 +958,7 @@ export class AgentManager {
|
||||
|
||||
constructor(options: AgentManagerOptions) {
|
||||
this.pluginLifecycle = options.pluginLifecycle;
|
||||
this.pluginSessions = options.pluginSessions;
|
||||
this.pluginAgentTools = options.pluginAgentTools;
|
||||
this.timelineStore = options.timelineStore ?? new InMemoryAgentTimelineStore();
|
||||
this.idFactory = options.idFactory ?? (() => randomUUID());
|
||||
this.registry = options?.registry;
|
||||
@@ -1084,75 +1063,47 @@ export class AgentManager {
|
||||
this.paseoToolCatalogFactory = factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reopens an idle agent whose plugin attachment changed in a way the running provider session cannot pick up:
|
||||
* env, instructions, MCP servers, or tool definitions. A plugin change that leaves the agent's launch as it was
|
||||
* keeps the session, with its background work and subagents.
|
||||
*/
|
||||
invalidatePluginSessions(): void {
|
||||
this.sessionOpenGeneration++;
|
||||
}
|
||||
|
||||
async reloadStalePluginSession(agentId: string): Promise<void> {
|
||||
if (!(await this.needsPluginSessionReload(agentId))) return;
|
||||
if (!this.needsPluginSessionReload(agentId)) return;
|
||||
await this.trackAgentRegistrationOperation(
|
||||
this.runLifecycleMutation(agentId, async () => {
|
||||
if (!(await this.needsPluginSessionReload(agentId))) return;
|
||||
if (!this.needsPluginSessionReload(agentId)) return;
|
||||
await this.reloadAgentSessionInternal(agentId);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private async needsPluginSessionReload(agentId: string): Promise<boolean> {
|
||||
private needsPluginSessionReload(agentId: string): boolean {
|
||||
const agent = this.getAgent(agentId);
|
||||
if (!agent || agent.lifecycle === "closed" || this.hasInFlightRun(agentId)) return false;
|
||||
return (await this.refreshPluginTools(agentId)).stale;
|
||||
return (
|
||||
agent !== null &&
|
||||
agent.lifecycle !== "closed" &&
|
||||
this.sessionOpenGenerations.get(agentId) !== this.sessionOpenGeneration &&
|
||||
!this.hasInFlightRun(agentId)
|
||||
);
|
||||
}
|
||||
|
||||
getPluginTools(agentId: string): readonly AttachedAgentTool[] {
|
||||
return this.pluginSessions?.sessionTools(agentId) ?? [];
|
||||
return (this.attachedPluginTools.get(agentId) ?? []).filter((tool) =>
|
||||
this.pluginAgentTools?.isToolPluginAvailable(tool.pluginId, tool.pluginInstanceId),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings a live session's plugin tools up to date with the running plugins. A plugin restart gives it a new
|
||||
* instance; only that plugin's open is rerun for the session, without reopening it or interrupting its turn.
|
||||
*/
|
||||
async refreshPluginTools(agentId: string): Promise<{ stale: boolean }> {
|
||||
if (!this.pluginSessions) return { stale: false };
|
||||
return this.pluginSessions.refreshSession(agentId, {
|
||||
reservedToolNames: () => this.reservedAgentToolNames(agentId),
|
||||
agentFacts: () => this.pluginOpenAgentFacts(agentId),
|
||||
});
|
||||
}
|
||||
|
||||
/** The agent fields a reopen would put in its plugin open request. */
|
||||
private async pluginOpenAgentFacts(agentId: string): Promise<SessionOpenAgentFacts> {
|
||||
const agent = this.requireAgent(agentId);
|
||||
return {
|
||||
workspaceId: agent.workspaceId ?? null,
|
||||
title: await this.resolveInitialPersistedTitle(agentId, agent.config, null),
|
||||
background: agent.background === true,
|
||||
...agentEntityData(agent),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the plugin's current instance of the tool at call time, so a launch-time catalog reaches a restarted
|
||||
* plugin and never a different plugin that took the name.
|
||||
*/
|
||||
async executePluginTool({
|
||||
pluginId,
|
||||
toolName,
|
||||
agentId,
|
||||
input,
|
||||
signal,
|
||||
}: PluginToolCall): Promise<AgentToolResult> {
|
||||
async executePluginTool(
|
||||
tool: AttachedAgentTool,
|
||||
agentId: string,
|
||||
input: unknown,
|
||||
signal?: AbortSignal,
|
||||
): Promise<AgentToolResult> {
|
||||
const agent = this.getAgent(agentId);
|
||||
if (!agent || agent.lifecycle === "closed") throw new Error(`Agent is not live: ${agentId}`);
|
||||
if (!this.pluginSessions) throw new Error("Plugin tools are unavailable");
|
||||
await this.refreshPluginTools(agentId);
|
||||
const tool = this.getPluginTools(agentId).find(
|
||||
(entry) => entry.pluginId === pluginId && entry.name === toolName,
|
||||
);
|
||||
if (!tool) return { isError: true, text: `Plugin tool is not available: ${toolName}` };
|
||||
if (!this.pluginAgentTools) throw new Error("Plugin tools are unavailable");
|
||||
const record = await this.registry?.get(agentId);
|
||||
return this.pluginSessions.callTool(
|
||||
return this.pluginAgentTools.callTool(
|
||||
tool.pluginId,
|
||||
tool.pluginInstanceId,
|
||||
describeHookAgent({ ...agent, title: record?.title ?? agent.config.title }),
|
||||
@@ -1162,22 +1113,10 @@ export class AgentManager {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Paseo's own tool names for the agent, including the ones its provider disables. The catalog also lists the
|
||||
* agent's plugin tools; the plugin session owner settles those names between plugins itself.
|
||||
*/
|
||||
private async reservedAgentToolNames(agentId: string): Promise<ReadonlySet<string>> {
|
||||
if (!this.paseoToolCatalogFactory) return new Set();
|
||||
const pluginToolNames = new Set(this.getPluginTools(agentId).map((tool) => tool.name));
|
||||
const catalog = await this.paseoToolCatalogFactory({
|
||||
callerAgentId: agentId,
|
||||
paseoToolPolicy: {},
|
||||
});
|
||||
return new Set([...catalog.tools.keys()].filter((name) => !pluginToolNames.has(name)));
|
||||
}
|
||||
|
||||
private detachPluginTools(agentId: string): void {
|
||||
this.pluginSessions?.closeSession(agentId);
|
||||
this.attachedPluginTools.delete(agentId);
|
||||
this.sessionOpenGenerations.delete(agentId);
|
||||
this.pluginAgentTools?.detachTools(agentId);
|
||||
}
|
||||
|
||||
getPaseoToolPolicy(agentId: string): ProviderPaseoToolsPolicy | undefined {
|
||||
@@ -1698,17 +1637,7 @@ export class AgentManager {
|
||||
);
|
||||
}
|
||||
|
||||
private createAgentInternal(
|
||||
config: AgentSessionConfig,
|
||||
resolvedAgentId: string,
|
||||
options: CreateAgentOptions,
|
||||
): Promise<ManagedAgent> {
|
||||
return this.launchAgent(resolvedAgentId, () =>
|
||||
this.createAgentSession(config, resolvedAgentId, options),
|
||||
);
|
||||
}
|
||||
|
||||
private async createAgentSession(
|
||||
private async createAgentInternal(
|
||||
config: AgentSessionConfig,
|
||||
resolvedAgentId: string,
|
||||
options: CreateAgentOptions,
|
||||
@@ -1829,19 +1758,7 @@ export class AgentManager {
|
||||
);
|
||||
}
|
||||
|
||||
private resumeAgentFromPersistenceInternal(
|
||||
handle: AgentPersistenceHandle,
|
||||
overrides: Partial<AgentSessionConfig> | undefined,
|
||||
agentId: string,
|
||||
options?: ResumeAgentOptions,
|
||||
resumeOptions?: AgentResumeSessionOptions,
|
||||
): Promise<ManagedAgent> {
|
||||
return this.launchAgent(agentId, () =>
|
||||
this.resumeAgentSession(handle, overrides, agentId, options, resumeOptions),
|
||||
);
|
||||
}
|
||||
|
||||
private async resumeAgentSession(
|
||||
private async resumeAgentFromPersistenceInternal(
|
||||
handle: AgentPersistenceHandle,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
agentId?: string,
|
||||
@@ -1947,23 +1864,18 @@ export class AgentManager {
|
||||
workspaceId: string;
|
||||
labels?: Record<string, string>;
|
||||
}): Promise<ManagedAgent> {
|
||||
const resolvedAgentId = validateAgentId(this.idFactory(), "importProviderSession");
|
||||
return this.trackAgentRegistrationOperation(
|
||||
this.launchAgent(resolvedAgentId, () => this.importAgentSession(input, resolvedAgentId)),
|
||||
);
|
||||
return this.trackAgentRegistrationOperation(this.importProviderSessionInternal(input));
|
||||
}
|
||||
|
||||
private async importAgentSession(
|
||||
input: {
|
||||
provider: AgentProvider;
|
||||
providerHandleId: string;
|
||||
cwd: string;
|
||||
workspaceId: string;
|
||||
labels?: Record<string, string>;
|
||||
},
|
||||
resolvedAgentId: string,
|
||||
): Promise<ManagedAgent> {
|
||||
private async importProviderSessionInternal(input: {
|
||||
provider: AgentProvider;
|
||||
providerHandleId: string;
|
||||
cwd: string;
|
||||
workspaceId: string;
|
||||
labels?: Record<string, string>;
|
||||
}): Promise<ManagedAgent> {
|
||||
this.assertAcceptingAgentRegistrations();
|
||||
const resolvedAgentId = validateAgentId(this.idFactory(), "importProviderSession");
|
||||
this.requireEnabledProvider(input.provider);
|
||||
|
||||
const client = await this.requireAvailableClient({ provider: input.provider });
|
||||
@@ -2059,29 +1971,7 @@ export class AgentManager {
|
||||
);
|
||||
}
|
||||
|
||||
private reloadAgentSessionInternal(
|
||||
agentId: string,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
options?: { rehydrateFromDisk?: boolean },
|
||||
): Promise<ManagedAgent> {
|
||||
return this.launchAgent(agentId, () => this.reopenAgentSession(agentId, overrides, options));
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one provider launch: create, resume, import, or reopen. Its plugin open takes over the session once
|
||||
* `registerSession` admits the agent. A launch that fails before then discards that open, so a session still
|
||||
* running keeps its plugin tools.
|
||||
*/
|
||||
private async launchAgent<T>(agentId: string, launch: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await launch();
|
||||
} catch (error) {
|
||||
this.pluginSessions?.sessionLaunchFailed(agentId);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async reopenAgentSession(
|
||||
private async reloadAgentSessionInternal(
|
||||
agentId: string,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
options?: { rehydrateFromDisk?: boolean },
|
||||
@@ -2129,11 +2019,13 @@ export class AgentManager {
|
||||
metadata: existing.metadata,
|
||||
},
|
||||
);
|
||||
const providerLaunchConfig = this.resolveReloadLaunchConfig(
|
||||
existing,
|
||||
launchConfig,
|
||||
launchContext,
|
||||
);
|
||||
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
|
||||
if (
|
||||
Object.keys(stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {}).length > 0 &&
|
||||
existing.session.capabilities.supportsMcpServers !== true
|
||||
) {
|
||||
throw this.unsupportedMcpError(providerLaunchConfig, launchContext);
|
||||
}
|
||||
|
||||
let session: AgentSession | undefined;
|
||||
let closedExisting: ManagedAgentClosed | undefined;
|
||||
@@ -2197,8 +2089,7 @@ export class AgentManager {
|
||||
throw error;
|
||||
} finally {
|
||||
if (!handedToRegistration) {
|
||||
// The closed agent drops its plugin record; a launch that never closed it leaves the rollback to launchAgent.
|
||||
if (closedExisting) this.detachPluginTools(agentId);
|
||||
this.detachPluginTools(agentId);
|
||||
if (hadPreviousPaseoToolPolicy) {
|
||||
this.paseoToolPolicies.set(agentId, previousPaseoToolPolicy);
|
||||
} else {
|
||||
@@ -2211,23 +2102,6 @@ export class AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** Validates a reload's launch before it closes the running session. */
|
||||
private resolveReloadLaunchConfig(
|
||||
existing: ActiveManagedAgent,
|
||||
launchConfig: AgentSessionConfig,
|
||||
launchContext: AgentLaunchContext,
|
||||
): AgentSessionConfig {
|
||||
const providerLaunchConfig = this.resolveProviderLaunchConfig(launchConfig, launchContext);
|
||||
const mcpServers = stripInternalPaseoMcpServer(providerLaunchConfig).mcpServers ?? {};
|
||||
if (
|
||||
Object.keys(mcpServers).length > 0 &&
|
||||
existing.session.capabilities.supportsMcpServers !== true
|
||||
) {
|
||||
throw this.unsupportedMcpError(providerLaunchConfig, launchContext);
|
||||
}
|
||||
return providerLaunchConfig;
|
||||
}
|
||||
|
||||
private async closeReloadedSession(session: AgentSession, agentId: string): Promise<void> {
|
||||
let operation = this.reloadedSessionCloses.get(session);
|
||||
if (!operation) {
|
||||
@@ -4745,8 +4619,6 @@ export class AgentManager {
|
||||
this.runtimeCleanupIdentities.set(session, Object.freeze({ openedAt: Date.now() }));
|
||||
this.agents.set(resolvedAgentId, managed);
|
||||
registered = true;
|
||||
// The agent now runs this launch, so its plugin open describes the running session.
|
||||
this.pluginSessions?.sessionLaunched(resolvedAgentId);
|
||||
// Initialize previousStatus to track transitions
|
||||
this.previousStatuses.set(resolvedAgentId, managed.lifecycle);
|
||||
if (session.initialTimeline?.length) {
|
||||
@@ -6641,10 +6513,13 @@ export class AgentManager {
|
||||
metadata?: AgentMetadata;
|
||||
},
|
||||
): Promise<AgentLaunchContext> {
|
||||
// A plugin changing during this open must still make the resulting session stale.
|
||||
const generation = this.sessionOpenGeneration;
|
||||
this.detachPluginTools(agentId);
|
||||
let appendSystemPrompt: string[] | undefined;
|
||||
let mcpServers: AgentSessionConfig["mcpServers"];
|
||||
let mcpServerOwners: Record<string, string> | undefined;
|
||||
if (this.pluginSessions) {
|
||||
if (this.pluginLifecycle) {
|
||||
const request = {
|
||||
agentId,
|
||||
provider: client.provider,
|
||||
@@ -6659,9 +6534,10 @@ export class AgentManager {
|
||||
tools: [],
|
||||
mcpServers: {},
|
||||
};
|
||||
const transformed = await this.pluginSessions.openSession(request);
|
||||
const transformed = await this.pluginLifecycle.before("agent.open.before", request);
|
||||
env = transformed.env;
|
||||
if (request.purpose === "interactive") {
|
||||
this.attachedPluginTools.set(agentId, transformed.tools as AttachedAgentTool[]);
|
||||
appendSystemPrompt = transformed.appendSystemPrompt;
|
||||
mcpServers = transformed.mcpServers;
|
||||
mcpServerOwners = transformed.mcpServerOwners;
|
||||
@@ -6685,13 +6561,18 @@ export class AgentManager {
|
||||
this.paseoToolCatalogFactory &&
|
||||
(useNativeTools || this.getPluginTools(agentId).length > 0)
|
||||
) {
|
||||
// Building the catalog checks the plugin tools against Paseo's own names.
|
||||
const catalog = await this.paseoToolCatalogFactory({
|
||||
callerAgentId: agentId,
|
||||
paseoToolPolicy,
|
||||
});
|
||||
if (useNativeTools) context.paseoTools = catalog;
|
||||
try {
|
||||
const catalog = await this.paseoToolCatalogFactory({
|
||||
callerAgentId: agentId,
|
||||
paseoToolPolicy,
|
||||
});
|
||||
if (useNativeTools) context.paseoTools = catalog;
|
||||
} catch (error) {
|
||||
this.detachPluginTools(agentId);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
this.sessionOpenGenerations.set(agentId, generation);
|
||||
return context;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
import { once } from "node:events";
|
||||
import { createServer } from "node:http";
|
||||
import type { FormInfo, ModelInfo, SessionInfo, SessionMessageInfo } from "@opencode/client";
|
||||
import type { FormInfo, ModelInfo, 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(
|
||||
@@ -760,124 +756,6 @@ 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);
|
||||
|
||||
@@ -4,7 +4,6 @@ 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();
|
||||
@@ -36,204 +35,7 @@ function setup() {
|
||||
return { children, child, upserts };
|
||||
}
|
||||
|
||||
function setupTree() {
|
||||
const harness = new V2Harness();
|
||||
const sessions = new Map<string, SessionInfo>(
|
||||
[
|
||||
{ ...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");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { V2Timeline } from "./timeline.js";
|
||||
|
||||
import { isSessionNotFoundError, type SessionInfo } from "@opencode/client";
|
||||
import type { SessionInfo } from "@opencode/client";
|
||||
|
||||
import type { AgentStreamEvent } from "../../../agent-sdk-types.js";
|
||||
|
||||
@@ -15,34 +15,18 @@ interface ChildrenOptions {
|
||||
id: string;
|
||||
emit(event: AgentStreamEvent): void;
|
||||
reconcilePermissions(id: string): Promise<void>;
|
||||
/** Prepares a descendant session for the current connection. */
|
||||
/** Prepares a newly seen descendant session. */
|
||||
adoptChild?: (id: string) => Promise<void>;
|
||||
}
|
||||
interface Child {
|
||||
parentID: string;
|
||||
timeline: V2Timeline;
|
||||
signature?: string;
|
||||
}
|
||||
export class SessionChildren {
|
||||
private readonly children = new Map<string, Child>();
|
||||
private readonly children = new Map<string, V2Timeline>();
|
||||
private readonly childStates = new Map<string, string>();
|
||||
constructor(private readonly options: ChildrenOptions) {}
|
||||
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);
|
||||
}
|
||||
}
|
||||
/** Every descendant session seen so far. */
|
||||
ids(): string[] {
|
||||
return [...this.children.keys()];
|
||||
}
|
||||
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 &&
|
||||
@@ -50,18 +34,17 @@ export class SessionChildren {
|
||||
) {
|
||||
await this.reconcile(event.data.parentID);
|
||||
}
|
||||
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,
|
||||
);
|
||||
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 }),
|
||||
);
|
||||
}
|
||||
}
|
||||
async reconcile(parentID: string) {
|
||||
const previous = [...this.children].filter(([, child]) => child.parentID === parentID);
|
||||
const seen = new Set<string>();
|
||||
let cursor: string | undefined;
|
||||
do {
|
||||
const page = await this.options.client().session.list({
|
||||
@@ -69,45 +52,19 @@ export class SessionChildren {
|
||||
limit: 100,
|
||||
});
|
||||
for (const child of page.data) {
|
||||
seen.add(child.id);
|
||||
await this.reconcileChild(child, parentID);
|
||||
await this.reconcileChild(child);
|
||||
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 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) {
|
||||
private async reconcileChild(info: SessionInfo) {
|
||||
await this.options.reconcilePermissions(info.id);
|
||||
let child = this.children.get(info.id);
|
||||
if (!child) {
|
||||
let timeline = this.children.get(info.id);
|
||||
if (!timeline) {
|
||||
await this.options.adoptChild?.(info.id);
|
||||
child = this.children.get(info.id) ?? { parentID, timeline: new V2Timeline() };
|
||||
this.children.set(info.id, child);
|
||||
timeline = this.children.get(info.id) ?? new V2Timeline();
|
||||
this.children.set(info.id, timeline);
|
||||
}
|
||||
const active = await this.options.client().session.active();
|
||||
let status: "running" | "failed" | "canceled" | "completed" = "completed";
|
||||
@@ -136,11 +93,11 @@ export class SessionChildren {
|
||||
timestamp: new Date(info.time.updated).toISOString(),
|
||||
};
|
||||
const signature = JSON.stringify(presentation);
|
||||
if (child.signature !== signature) {
|
||||
child.signature = signature;
|
||||
if (this.childStates.get(info.id) !== signature) {
|
||||
this.childStates.set(info.id, signature);
|
||||
this.options.emit({ type: "provider_subagent", provider: "opencode", event: presentation });
|
||||
}
|
||||
await child.timeline.messages(await messages(this.options.client(), info.id), (event) => {
|
||||
await timeline.messages(await messages(this.options.client(), info.id), (event) => {
|
||||
if (event.type === "timeline")
|
||||
this.options.emit({
|
||||
type: "provider_subagent",
|
||||
|
||||
@@ -4,7 +4,6 @@ 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";
|
||||
|
||||
@@ -102,51 +101,6 @@ 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: "<html>Not found</html>" },
|
||||
{ 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") {
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import { isSessionNotFoundError } from "@opencode/client";
|
||||
import { OpenCodeHttpError } from "../http-error.js";
|
||||
|
||||
export async function validateOpenCodeResponse(
|
||||
request: RequestInfo | URL,
|
||||
response: Response,
|
||||
): Promise<Response> {
|
||||
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);
|
||||
}
|
||||
@@ -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 { validateOpenCodeResponse } from "./http-response.js";
|
||||
import { OpenCodeHttpError } from "../http-error.js";
|
||||
import { raceProviderRefreshAbort } from "../../../provider-refresh-deadline.js";
|
||||
import { resolveExternalOpenCodeServer, type ExternalOpenCodeServer } from "./external-server.js";
|
||||
import {
|
||||
@@ -316,7 +316,12 @@ export class V2Runtime {
|
||||
? AbortSignal.any([init.signal, processAbort.signal])
|
||||
: processAbort.signal;
|
||||
const response = await fetch(request, { ...init, signal });
|
||||
return validateOpenCodeResponse(request, response);
|
||||
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;
|
||||
},
|
||||
});
|
||||
await client.server.info({ signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())) });
|
||||
|
||||
@@ -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 });
|
||||
await this.children.restoreAdoptions();
|
||||
for (const id of this.children.ids()) await this.adoptDescendant(id);
|
||||
await this.reconcile();
|
||||
await this.children.reconcile(this.id);
|
||||
await this.turns.reconcile();
|
||||
|
||||
@@ -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 { validateOpenCodeResponse } from "./http-response.js";
|
||||
import { OpenCodeHttpError } from "../http-error.js";
|
||||
import { resolveOpenCodeHomeDir } from "../paths.js";
|
||||
import { openCodeConfigDirectory, provisionLocalBridge } from "./bridge-provisioning.js";
|
||||
import { awaitPaseoPlugin } from "./readiness.js";
|
||||
@@ -61,7 +61,12 @@ export async function connectSharedService(
|
||||
if (isConnectionRefused(error)) markExited(error);
|
||||
throw error;
|
||||
}
|
||||
return validateOpenCodeResponse(request, response);
|
||||
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;
|
||||
},
|
||||
});
|
||||
const markExited = (cause: unknown) => {
|
||||
|
||||
@@ -28,13 +28,7 @@ export function registerPluginTools(options: {
|
||||
description: tool.description,
|
||||
inputSchema: z.fromJSONSchema(tool.inputSchema),
|
||||
async handler(input, { signal }) {
|
||||
const result = await agentManager.executePluginTool({
|
||||
pluginId: tool.pluginId,
|
||||
toolName: tool.name,
|
||||
agentId: callerAgentId,
|
||||
input,
|
||||
signal,
|
||||
});
|
||||
const result = await agentManager.executePluginTool(tool, callerAgentId, input, signal);
|
||||
return addModelVisibleStructuredContent({
|
||||
content: result.text === undefined ? [] : [{ type: "text", text: result.text }],
|
||||
structuredContent: result.structuredContent,
|
||||
|
||||
@@ -1047,7 +1047,7 @@ export async function createPaseoDaemon(
|
||||
const initialAgentManagerState = providerSnapshotManager.getAgentManagerProviderState();
|
||||
const agentManager = new AgentManager({
|
||||
pluginLifecycle: pluginRuntime,
|
||||
pluginSessions: pluginRuntime,
|
||||
pluginAgentTools: pluginRuntime,
|
||||
clients: initialAgentManagerState.clients,
|
||||
providerDefinitions: initialAgentManagerState.providerDefinitions,
|
||||
registry: agentStorage,
|
||||
@@ -1068,6 +1068,10 @@ export async function createPaseoDaemon(
|
||||
const unsubscribePluginProviders =
|
||||
pluginRuntime.subscribeProviderRegistrations(syncPluginProviders);
|
||||
|
||||
const unsubscribePluginSessionChanges = pluginRuntime.subscribeSessionOpenChanges(() => {
|
||||
agentManager.invalidatePluginSessions();
|
||||
});
|
||||
|
||||
const detachAgentStoragePersistence = attachAgentStoragePersistence(
|
||||
logger,
|
||||
agentManager,
|
||||
@@ -1696,7 +1700,6 @@ export async function createPaseoDaemon(
|
||||
// state is retained between requests, matching the previous
|
||||
// `sessionIdGenerator: undefined` transport.
|
||||
const createAgentMcpSession = async (callerAgentId?: string) => {
|
||||
if (callerAgentId) await agentManager.refreshPluginTools(callerAgentId);
|
||||
const agentMcpServer = await createAgentMcpServer(
|
||||
createAgentToolHostDependencies({
|
||||
callerAgentId,
|
||||
@@ -2042,6 +2045,7 @@ export async function createPaseoDaemon(
|
||||
localCredential = null;
|
||||
await deleteLocalCredential(config.paseoHome);
|
||||
unsubscribePluginProviders();
|
||||
unsubscribePluginSessionChanges();
|
||||
await pluginRuntime.stopAllPlugins().catch(() => undefined);
|
||||
await serviceProxy.stopStandalone().catch(() => undefined);
|
||||
await agentProviderRuntime.shutdown().catch(() => undefined);
|
||||
@@ -2063,6 +2067,7 @@ export async function createPaseoDaemon(
|
||||
// that is still open. Plugins themselves are stopped once every session
|
||||
// they serve has been closed, further down.
|
||||
unsubscribePluginProviders();
|
||||
unsubscribePluginSessionChanges();
|
||||
await hubRelationships.stop();
|
||||
workspaceReconciliation.dispose();
|
||||
scriptHealthMonitor.stop();
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -477,31 +476,20 @@ test("structured tool results get model-visible text when text is omitted", asyn
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("reloading a plugin retires its old attachments, and both the agent MCP and the launch-time catalog reach the new instance", async () => {
|
||||
test("reloading a plugin retires its old attachments before an agent reopens", async () => {
|
||||
const h = await setup(true);
|
||||
try {
|
||||
const a = await h.create({ x: "y" });
|
||||
const mcp = await h.mcp(a.id);
|
||||
const launchCatalog = h.launches.at(-1)!.context!.paseoTools!;
|
||||
const oldCatalog = h.launches.at(-1)!.context!.paseoTools!;
|
||||
expect((await mcp.listTools()).tools.map((tool) => tool.name)).toContain("plugin_echo");
|
||||
expect((await launchCatalog.executeTool("plugin_echo", { text: "before" })).isError).not.toBe(
|
||||
true,
|
||||
);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect((await mcp.listTools()).tools.map((tool) => tool.name)).not.toContain("plugin_echo");
|
||||
expect(h.daemon.daemon.agentManager.getPluginTools(a.id)).toEqual([]);
|
||||
// A native provider keeps the catalog it launched with. Its call reaches the restarted plugin, whose own call
|
||||
// count starts again.
|
||||
const result = await launchCatalog.executeTool("plugin_echo", { text: "after restart" });
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(JSON.parse((result.content as { text: string }[])[0].text)).toMatchObject({
|
||||
input: { text: "after restart" },
|
||||
calls: 1,
|
||||
expect(await oldCatalog.executeTool("plugin_echo", { text: "retired" })).toMatchObject({
|
||||
isError: true,
|
||||
content: [{ type: "text", text: expect.stringContaining("not available") }],
|
||||
});
|
||||
expect((await mcp.listTools()).tools.map((tool) => tool.name)).toContain("plugin_echo");
|
||||
expect(h.daemon.daemon.agentManager.getPluginTools(a.id).map((tool) => tool.name)).toEqual([
|
||||
"plugin_echo",
|
||||
]);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
@@ -623,673 +611,6 @@ test("a busy agent is steered after plugin reload and reopens only at its next i
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const openCounterSource = `
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
let opens = 0;
|
||||
const tool = defineAgentTool({
|
||||
name: "other_opens", description: "How often this plugin saw the session open",
|
||||
input: z.object({}),
|
||||
async execute() { return { text: String(opens) }; },
|
||||
});
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
opens++;
|
||||
return { ...request, tools: [...request.tools, tool] };
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a busy agent's MCP lists and calls a restarted plugin's tools without reopening", async () => {
|
||||
let release!: () => void;
|
||||
const blocked = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const h = await setup(false, pluginSource, undefined, {
|
||||
beforeTurnComplete: async () => blocked,
|
||||
});
|
||||
try {
|
||||
await h.install("other-hook", openCounterSource);
|
||||
const a = await h.create({ x: "y" });
|
||||
await h.client.sendMessage(a.id, "busy prompt", { activeTurnBehavior: "steer" });
|
||||
await expect.poll(() => h.daemon.daemon.agentManager.hasInFlightRun(a.id)).toBe(true);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
await h.client.sendMessage(a.id, "message while busy", { activeTurnBehavior: "steer" });
|
||||
expect(h.daemon.daemon.agentManager.hasInFlightRun(a.id)).toBe(true);
|
||||
|
||||
const mcp = await h.mcp(a.id);
|
||||
const names = (await mcp.listTools()).tools.map((tool) => tool.name);
|
||||
expect(names).toContain("plugin_echo");
|
||||
expect(names).toContain("other_opens");
|
||||
const result = await mcp.callTool({
|
||||
name: "plugin_echo",
|
||||
arguments: { text: "after restart" },
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
// The restarted plugin answers: its own call count starts again.
|
||||
expect(JSON.parse((result.content as { text: string }[])[0].text)).toMatchObject({
|
||||
agent: { id: a.id },
|
||||
input: { text: "after restart" },
|
||||
calls: 1,
|
||||
});
|
||||
// Only the restarted plugin saw the replayed open.
|
||||
expect(await mcp.callTool({ name: "other_opens", arguments: {} })).toMatchObject({
|
||||
content: [{ type: "text", text: "1" }],
|
||||
});
|
||||
expect(h.launches).toHaveLength(1);
|
||||
expect(h.events.interrupts).toBe(0);
|
||||
|
||||
// The plugin's env records the open reason, and the replay's `refresh` differs from the create, so the session
|
||||
// reopens at its next idle prompt to apply it.
|
||||
release();
|
||||
await expect.poll(() => h.daemon.daemon.agentManager.hasInFlightRun(a.id)).toBe(false);
|
||||
await sendAndFinish(h, a.id, "idle prompt");
|
||||
expect(h.launches).toHaveLength(2);
|
||||
} finally {
|
||||
release();
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
function subagentStatuses(h: Awaited<ReturnType<typeof setup>>, agentId: string) {
|
||||
return h.daemon.daemon.agentManager
|
||||
.listProviderSubagentActivity()
|
||||
.filter((subagent) => subagent.parentAgentId === agentId)
|
||||
.map((subagent) => subagent.status);
|
||||
}
|
||||
|
||||
test("reloading a plugin keeps an agent it does not target on its provider session, with its subagents running", async () => {
|
||||
const h = await setup();
|
||||
try {
|
||||
const b = await h.create();
|
||||
await sendAndFinish(h, b.id, "Emit a provider child");
|
||||
expect(subagentStatuses(h, b.id)).toEqual(["running"]);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
await sendAndFinish(h, b.id, "after reload");
|
||||
expect(h.launches).toHaveLength(1);
|
||||
expect(subagentStatuses(h, b.id)).toEqual(["running"]);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("a restarted plugin that attaches the same tools keeps the agent's session, and the new instance answers", async () => {
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
const a = await h.create();
|
||||
await sendAndFinish(h, a.id, "Emit a provider child");
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
await sendAndFinish(h, a.id, "after reload");
|
||||
expect(h.launches).toHaveLength(1);
|
||||
expect(subagentStatuses(h, a.id)).toEqual(["running"]);
|
||||
// The restarted instance counts the one replayed open.
|
||||
const mcp = await h.mcp(a.id);
|
||||
expect(await mcp.callTool({ name: "other_opens", arguments: {} })).toMatchObject({
|
||||
content: [{ type: "text", text: "1" }],
|
||||
});
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("reverting a plugin's tool edit lets the agent keep its session, with its subagents running", async () => {
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
const a = await h.create();
|
||||
await sendAndFinish(h, a.id, "Emit a provider child");
|
||||
const description = async () =>
|
||||
(await (await h.mcp(a.id)).listTools()).tools.find((tool) => tool.name === "other_opens")
|
||||
?.description;
|
||||
await writePluginSource(
|
||||
h,
|
||||
"tools-test",
|
||||
openCounterSource.replace("How often this plugin saw the session open", "Edited"),
|
||||
);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect(await description()).toBe("Edited");
|
||||
await writePluginSource(h, "tools-test", openCounterSource);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect(await description()).toBe("How often this plugin saw the session open");
|
||||
await sendAndFinish(h, a.id, "after revert");
|
||||
expect(h.launches).toHaveLength(1);
|
||||
expect(subagentStatuses(h, a.id)).toEqual(["running"]);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const breakableSource = (arm: string) => `
|
||||
import { existsSync } from "node:fs";
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
const tool = defineAgentTool({
|
||||
name: "breakable_ping", description: "Ping",
|
||||
input: z.object({}),
|
||||
async execute() { return { text: "pong" }; },
|
||||
});
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
if (existsSync(${JSON.stringify(arm)})) throw new Error("broken edit");
|
||||
return { ...request, tools: [...request.tools, tool] };
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a reopen that a broken plugin fails keeps the running session's plugin tools, and fixing the plugin restores its own", async () => {
|
||||
const scratch = await mkdtemp(path.join(tmpdir(), "paseo-breakable-"));
|
||||
const arm = path.join(scratch, "arm");
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
await h.install("breakable", breakableSource(arm));
|
||||
const a = await h.create();
|
||||
await writeFile(arm, "");
|
||||
await h.client.reloadPlugin("breakable");
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow("broken edit");
|
||||
expect(h.launches).toHaveLength(1);
|
||||
const broken = await h.mcp(a.id);
|
||||
expect(await listedToolNames(broken)).not.toContain("breakable_ping");
|
||||
expect(await broken.callTool({ name: "other_opens", arguments: {} })).toMatchObject({
|
||||
content: [{ type: "text", text: "2" }],
|
||||
});
|
||||
|
||||
await rm(arm);
|
||||
await h.client.reloadPlugin("breakable");
|
||||
const fixed = await h.mcp(a.id);
|
||||
expect(await fixed.callTool({ name: "breakable_ping", arguments: {} })).toMatchObject({
|
||||
content: [{ type: "text", text: "pong" }],
|
||||
});
|
||||
// The fixed plugin attaches what the running session launched with, so no reopen is due.
|
||||
await manager.reloadStalePluginSession(a.id);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const paseoNameClashSource = openCounterSource.replace(
|
||||
"tools: [...request.tools, tool]",
|
||||
'tools: [...request.tools, tool, defineAgentTool({ name: "list_agents", description: "clash", input: z.object({}), async execute() { return { text: "clash" }; } })]',
|
||||
);
|
||||
|
||||
test("a reopen that a plugin's Paseo tool name fails is retried, keeps the running session's plugin tools, and fixing the plugin restores its own", async () => {
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
await h.install("unrelated", breakableSource(path.join(h.directory, "never-armed")));
|
||||
const a = await h.create();
|
||||
await writePluginSource(h, "tools-test", paseoNameClashSource);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
const collision = /list_agents from plugin tools-test collides with Paseo tool/;
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(collision);
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(collision);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
const broken = await h.mcp(a.id);
|
||||
expect(await listedToolNames(broken)).not.toContain("other_opens");
|
||||
expect(await broken.callTool({ name: "breakable_ping", arguments: {} })).toMatchObject({
|
||||
content: [{ type: "text", text: "pong" }],
|
||||
});
|
||||
|
||||
await writePluginSource(h, "tools-test", openCounterSource);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect(
|
||||
await (await h.mcp(a.id)).callTool({ name: "other_opens", arguments: {} }),
|
||||
).toMatchObject({ content: [{ type: "text", text: "1" }] });
|
||||
await manager.reloadStalePluginSession(a.id);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const claimsOtherOpensSource = `
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
const tool = defineAgentTool({
|
||||
name: "other_opens", description: "clash",
|
||||
input: z.object({}),
|
||||
async execute() { return { text: "clash" }; },
|
||||
});
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => ({ ...request, tools: [...request.tools, tool] }));
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("after a rejected reopen, a tool name stays with the plugin that had it, even when the claimant sorts first", async () => {
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
await h.install("a-claimant", breakableSource(path.join(h.directory, "never-armed")));
|
||||
const a = await h.create();
|
||||
await writePluginSource(h, "a-claimant", claimsOtherOpensSource);
|
||||
await h.client.reloadPlugin("a-claimant");
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(
|
||||
/other_opens from plugin tools-test collides with plugin a-claimant/,
|
||||
);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
const result = await (await h.mcp(a.id)).callTool({ name: "other_opens", arguments: {} });
|
||||
expect(result.content).not.toEqual([{ type: "text", text: "clash" }]);
|
||||
expect(manager.getPluginTools(a.id).map((tool) => tool.pluginId)).toEqual(["tools-test"]);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const metadataGatedSource = openCounterSource.replace(
|
||||
"opens++;",
|
||||
'opens++;\n if (request.metadata.tools !== "on") return;',
|
||||
);
|
||||
|
||||
test("a plugin reload reruns its callback with the agent's current metadata", async () => {
|
||||
const h = await setup(false, metadataGatedSource);
|
||||
try {
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
const a = await h.create();
|
||||
expect(await listedToolNames(await h.mcp(a.id))).not.toContain("other_opens");
|
||||
await manager.setMetadata(a.id, { tools: "on" });
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect(await listedToolNames(await h.mcp(a.id))).toContain("other_opens");
|
||||
// The session launched without the tool, so it reopens at the next idle prompt.
|
||||
await sendAndFinish(h, a.id, "after metadata");
|
||||
expect(h.launches).toHaveLength(2);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const setsXSource = `
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => ({ ...request, env: { ...request.env, X: "yes" } }));
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
const needsXSource = `
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
if (request.env.X !== "yes") return;
|
||||
return { ...request, env: { ...request.env, Y: "yes" } };
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a plugin reruns when an earlier plugin changes what it receives, and the session reopens with the composed launch", async () => {
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
await h.install("a-sets-x", setsXSource);
|
||||
const a = await h.create();
|
||||
expect(h.launches.at(-1)!.context!.env).toMatchObject({ X: "yes" });
|
||||
await h.client.disablePlugin("a-sets-x");
|
||||
await h.install("b-needs-x", needsXSource);
|
||||
await listedToolNames(await h.mcp(a.id));
|
||||
await h.client.enablePlugin("a-sets-x");
|
||||
await listedToolNames(await h.mcp(a.id));
|
||||
// b-needs-x now sees X and adds Y, which the running session never launched with.
|
||||
await sendAndFinish(h, a.id, "after re-enable");
|
||||
expect(h.launches).toHaveLength(2);
|
||||
expect(h.launches.at(-1)!.context!.env).toMatchObject({ X: "yes", Y: "yes" });
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const hintSource = (hint: string) => `
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => ({ ...request, env: { ...request.env, HINT: ${JSON.stringify(hint)} } }));
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
const hintReaderSource = `
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
const { HINT: hint, ...env } = request.env;
|
||||
const tool = defineAgentTool({
|
||||
name: "read_tool_hint", description: "The hint from the plugin before",
|
||||
input: z.object({}),
|
||||
async execute() { return { text: String(hint) }; },
|
||||
});
|
||||
return { ...request, env, tools: [...request.tools, tool] };
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a later plugin rerun by an earlier plugin's edit keeps its own tool, and the session keeps running", async () => {
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
await h.install("a-hint", hintSource("red"));
|
||||
await h.install("b-hint-reader", hintReaderSource);
|
||||
const a = await h.create();
|
||||
await writePluginSource(h, "a-hint", hintSource("green"));
|
||||
await h.client.reloadPlugin("a-hint");
|
||||
expect(
|
||||
await (await h.mcp(a.id)).callTool({ name: "read_tool_hint", arguments: {} }),
|
||||
).toMatchObject({ content: [{ type: "text", text: "green" }] });
|
||||
// b-hint-reader removes the hint, so the launch is unchanged.
|
||||
await sendAndFinish(h, a.id, "after hint change");
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
// The tool waits for the gate file while it answers the first hint.
|
||||
const slowHintReaderSource = (entered: string, gate: string) => `
|
||||
import { existsSync, writeFileSync } from "node:fs";
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
const { HINT: hint, ...env } = request.env;
|
||||
const tool = defineAgentTool({
|
||||
name: "read_tool_hint", description: "The hint from the plugin before",
|
||||
input: z.object({}),
|
||||
async execute() {
|
||||
if (hint === "red") {
|
||||
writeFileSync(${JSON.stringify(entered)}, "");
|
||||
while (!existsSync(${JSON.stringify(gate)})) await new Promise((r) => setTimeout(r, 20));
|
||||
}
|
||||
return { text: String(hint) };
|
||||
},
|
||||
});
|
||||
return { ...request, env, tools: [...request.tools, tool] };
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a refresh that reruns a plugin lets that plugin's running tool call finish", async () => {
|
||||
const scratch = await mkdtemp(path.join(tmpdir(), "paseo-running-call-"));
|
||||
const entered = path.join(scratch, "entered");
|
||||
const gate = path.join(scratch, "gate");
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
await h.install("a-hint", hintSource("red"));
|
||||
await h.install("b-hint-reader", slowHintReaderSource(entered, gate));
|
||||
const a = await h.create();
|
||||
const running = (await h.mcp(a.id)).callTool({ name: "read_tool_hint", arguments: {} });
|
||||
await expect.poll(() => existsSync(entered)).toBe(true);
|
||||
await writePluginSource(h, "a-hint", hintSource("green"));
|
||||
await h.client.reloadPlugin("a-hint");
|
||||
expect(
|
||||
await (await h.mcp(a.id)).callTool({ name: "read_tool_hint", arguments: {} }),
|
||||
).toMatchObject({ content: [{ type: "text", text: "green" }] });
|
||||
await writeFile(gate, "");
|
||||
expect(await running).toMatchObject({ content: [{ type: "text", text: "red" }] });
|
||||
} finally {
|
||||
await h.close();
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
// Once armed, the module waits for the gate file before it loads, which holds a restart between stop and start.
|
||||
const gatedStartSource = (arm: string, entered: string, gate: string) =>
|
||||
openCounterSource.replace(
|
||||
'import { z } from "zod";',
|
||||
`import { existsSync, writeFileSync } from "node:fs";
|
||||
import { z } from "zod";
|
||||
if (existsSync(${JSON.stringify(arm)})) {
|
||||
writeFileSync(${JSON.stringify(entered)}, "");
|
||||
const pause = new Int32Array(new SharedArrayBuffer(4));
|
||||
while (!existsSync(${JSON.stringify(gate)})) Atomics.wait(pause, 0, 0, 20);
|
||||
}`,
|
||||
);
|
||||
|
||||
test("an idle prompt during a plugin restart keeps the agent's session, with its subagents running", async () => {
|
||||
const scratch = await mkdtemp(path.join(tmpdir(), "paseo-restart-gap-"));
|
||||
const arm = path.join(scratch, "arm");
|
||||
const entered = path.join(scratch, "entered");
|
||||
const gate = path.join(scratch, "gate");
|
||||
const h = await setup(false, gatedStartSource(arm, entered, gate));
|
||||
try {
|
||||
const a = await h.create();
|
||||
await sendAndFinish(h, a.id, "Emit a provider child");
|
||||
await writeFile(arm, "");
|
||||
const reloading = h.client.reloadPlugin("tools-test");
|
||||
await expect.poll(() => existsSync(entered)).toBe(true);
|
||||
const prompting = sendAndFinish(h, a.id, "during restart");
|
||||
// Room for a prompt that does not wait for the restart to reopen the session first.
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
await writeFile(gate, "");
|
||||
await reloading;
|
||||
await prompting;
|
||||
expect(h.launches).toHaveLength(1);
|
||||
expect(subagentStatuses(h, a.id)).toEqual(["running"]);
|
||||
expect(
|
||||
await (await h.mcp(a.id)).callTool({ name: "other_opens", arguments: {} }),
|
||||
).toMatchObject({ content: [{ type: "text", text: "1" }] });
|
||||
} finally {
|
||||
await h.close();
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const impostorSource = `
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
const tool = defineAgentTool({
|
||||
name: "plugin_echo", description: "Not the echo the agent was shown",
|
||||
input: z.object({ text: z.string() }),
|
||||
async execute() { return { text: "impostor" }; },
|
||||
});
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => ({ ...request, tools: [...request.tools, tool] }));
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a launch-time catalog never runs another plugin's tool that took the name", async () => {
|
||||
const h = await setup(true);
|
||||
try {
|
||||
await h.create({ x: "y" });
|
||||
const launchCatalog = h.launches.at(-1)!.context!.paseoTools!;
|
||||
await h.client.disablePlugin("tools-test");
|
||||
await h.install("impostor", impostorSource);
|
||||
expect(await launchCatalog.executeTool("plugin_echo", { text: "hi" })).toMatchObject({
|
||||
isError: true,
|
||||
content: [{ type: "text", text: "Plugin tool is not available: plugin_echo" }],
|
||||
});
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
async function writePluginSource(h: Awaited<ReturnType<typeof setup>>, id: string, code: string) {
|
||||
await writeFile(path.join(h.directory, id, "index.server.ts"), code);
|
||||
}
|
||||
|
||||
async function listedToolNames(mcp: Client) {
|
||||
return (await mcp.listTools()).tools.map((tool) => tool.name);
|
||||
}
|
||||
|
||||
test("an agent MCP request while a plugin is stopped keeps its tools eligible for the restart", async () => {
|
||||
const h = await setup();
|
||||
try {
|
||||
const a = await h.create({ x: "y" });
|
||||
await h.client.disablePlugin("tools-test");
|
||||
expect(await listedToolNames(await h.mcp(a.id))).not.toContain("plugin_echo");
|
||||
await h.client.enablePlugin("tools-test");
|
||||
expect(await listedToolNames(await h.mcp(a.id))).toContain("plugin_echo");
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
// Each open names its tool after its count. Once armed, a process's first open marks that it started and waits
|
||||
// for the gate file.
|
||||
const gatedOpenSource = (arm: string, entered: string, gate: string) => `
|
||||
import { existsSync, writeFileSync } from "node:fs";
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
let opens = 0;
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
const open = ++opens;
|
||||
if (open === 1 && existsSync(${JSON.stringify(arm)})) {
|
||||
writeFileSync(${JSON.stringify(entered)}, "");
|
||||
while (!existsSync(${JSON.stringify(gate)})) await new Promise((r) => setTimeout(r, 20));
|
||||
}
|
||||
const tool = defineAgentTool({
|
||||
name: "which_open", description: "open " + open,
|
||||
input: z.object({}),
|
||||
async execute() { return { text: "open " + open }; },
|
||||
});
|
||||
return { ...request, tools: [...request.tools, tool] };
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a reopen during a tool replay keeps the reopen's tool definitions in the plugin", async () => {
|
||||
const h = await setup();
|
||||
const arm = path.join(h.directory, "replay-arm");
|
||||
const entered = path.join(h.directory, "replay-entered");
|
||||
const gate = path.join(h.directory, "replay-gate");
|
||||
try {
|
||||
await h.install("gated", gatedOpenSource(arm, entered, gate));
|
||||
const a = await h.create();
|
||||
await writeFile(arm, "");
|
||||
await h.client.reloadPlugin("gated");
|
||||
// The restarted process counts from zero, so its first open is the replay. Hold it at the gate.
|
||||
const replaying = h.mcp(a.id);
|
||||
await expect.poll(() => existsSync(entered)).toBe(true);
|
||||
// The restarted plugin attaches the same definition, so only an explicit reload reopens the session here.
|
||||
const reopening = h.daemon.daemon.agentManager.reloadAgentSession(a.id);
|
||||
// Room for an unguarded reopen to reach the plugin first. A guarded one waits, so this cannot change the result.
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
await writeFile(gate, "");
|
||||
const mcp = await replaying;
|
||||
await reopening;
|
||||
expect(h.launches).toHaveLength(2);
|
||||
const mcpAfter = await h.mcp(a.id);
|
||||
expect((await mcpAfter.listTools()).tools.find((t) => t.name === "which_open")).toMatchObject({
|
||||
description: "open 2",
|
||||
});
|
||||
expect(await mcpAfter.callTool({ name: "which_open", arguments: {} })).toMatchObject({
|
||||
content: [{ type: "text", text: "open 2" }],
|
||||
});
|
||||
await mcp.close();
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const failingReplaySource = (arm: string, opens: string) =>
|
||||
pluginSource
|
||||
.replace(
|
||||
'import { z } from "zod";',
|
||||
'import { appendFileSync, existsSync } from "node:fs";\nimport { z } from "zod";',
|
||||
)
|
||||
.replace(
|
||||
'if (request.labels.x !== "y") return;',
|
||||
`if (request.labels.x !== "y") return;
|
||||
appendFileSync(${JSON.stringify(opens)}, "o");
|
||||
if (existsSync(${JSON.stringify(arm)})) throw new Error("replay failed");`,
|
||||
);
|
||||
|
||||
test("a failed tool replay is not repeated for the same plugin instance, and the next restart replays again", async () => {
|
||||
const scratch = await mkdtemp(path.join(tmpdir(), "paseo-replay-arm-"));
|
||||
const arm = path.join(scratch, "arm");
|
||||
const opens = path.join(scratch, "opens");
|
||||
const openCount = async () => (await readFile(opens, "utf8")).length;
|
||||
const h = await setup(false, failingReplaySource(arm, opens));
|
||||
try {
|
||||
const a = await h.create({ x: "y" });
|
||||
expect(await openCount()).toBe(1);
|
||||
await writeFile(arm, "");
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
// Connecting and listing send several agent MCP requests. Only the first one replays the open.
|
||||
const mcp = await h.mcp(a.id);
|
||||
expect(await listedToolNames(mcp)).toContain("list_agents");
|
||||
expect(await listedToolNames(mcp)).not.toContain("plugin_echo");
|
||||
expect(await openCount()).toBe(2);
|
||||
await mcp.close();
|
||||
|
||||
await rm(arm);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect(await listedToolNames(await h.mcp(a.id))).toContain("plugin_echo");
|
||||
expect(await openCount()).toBe(3);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
await rm(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const openReasonSource = `
|
||||
import { z } from "zod";
|
||||
import { defineAgentTool } from "@getpaseo/plugin/server";
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => ({
|
||||
...request,
|
||||
tools: [...request.tools, defineAgentTool({ name: "open_reason", description: request.reason, input: z.object({}), async execute() { return { text: request.reason }; } })],
|
||||
}));
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a tool replay reaches the restarted plugin with reason refresh", async () => {
|
||||
const h = await setup(false, openReasonSource);
|
||||
try {
|
||||
const a = await h.create();
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
const mcp = await h.mcp(a.id);
|
||||
expect((await mcp.listTools()).tools.find((t) => t.name === "open_reason")).toMatchObject({
|
||||
description: "refresh",
|
||||
});
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const nameClashSource = (name: string) =>
|
||||
pluginSource.replace(
|
||||
"tools: [...request.tools, tool]",
|
||||
`tools: [...request.tools, tool, defineAgentTool({ name: ${JSON.stringify(name)}, description: "clash", input: z.object({}), async execute() { return { text: "clash" }; } })]`,
|
||||
);
|
||||
|
||||
test.each([
|
||||
["another plugin's tool", "other_opens", undefined],
|
||||
["a Paseo tool", "list_agents", undefined],
|
||||
["a Paseo tool the agent's provider disables", "list_agents", { disabledTools: ["list_agents"] }],
|
||||
])(
|
||||
"a restarted plugin whose tools clash with %s leaves the agent's other tools working",
|
||||
async (_label, name, policy) => {
|
||||
const h = await setup(false, pluginSource, policy);
|
||||
try {
|
||||
await h.install("other-hook", openCounterSource);
|
||||
const a = await h.create({ x: "y" });
|
||||
await writePluginSource(h, "tools-test", nameClashSource(name));
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
const mcp = await h.mcp(a.id);
|
||||
const names = await listedToolNames(mcp);
|
||||
expect(names).toContain("other_opens");
|
||||
expect(names.includes("list_agents")).toBe(policy === undefined);
|
||||
expect(names).toContain("get_agent_status");
|
||||
expect(names).not.toContain("plugin_echo");
|
||||
expect(await mcp.callTool({ name: "other_opens", arguments: {} })).toMatchObject({
|
||||
content: [{ type: "text", text: "1" }],
|
||||
});
|
||||
expect(h.daemon.daemon.agentManager.getPluginTools(a.id).map((t) => t.pluginId)).toEqual([
|
||||
"other-hook",
|
||||
]);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
|
||||
const reloadRpcSource = pluginSource
|
||||
.replace("import { z }", 'import { defineRpc } from "@getpaseo/plugin";\nimport { z }')
|
||||
.replace(
|
||||
@@ -1537,7 +858,7 @@ test("installing and disabling an MCP plugin reopens idle sessions before their
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("installing and disabling an MCP plugin during a running turn neither interrupts it nor reopens the session", async () => {
|
||||
test("installing and disabling an MCP plugin never interrupts a running turn", async () => {
|
||||
let release!: () => void;
|
||||
const blocked = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
@@ -1563,9 +884,8 @@ test("installing and disabling an MCP plugin during a running turn neither inter
|
||||
expect(h.events.interrupts).toBe(0);
|
||||
release();
|
||||
await expect.poll(() => manager.hasInFlightRun(a.id)).toBe(false);
|
||||
// The plugin came and went before the session saw it, so the launch is unchanged.
|
||||
await sendAndFinish(h, a.id, "idle");
|
||||
expect(h.launches).toHaveLength(1);
|
||||
expect(h.launches).toHaveLength(2);
|
||||
expect(h.launches.at(-1)!.config.mcpServers?.company).toBeUndefined();
|
||||
} finally {
|
||||
release();
|
||||
@@ -1652,118 +972,6 @@ test("session-open MCP servers fail on unsupported providers and leave saved con
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const mcpWithToolSource = openCounterSource.replace(
|
||||
"return { ...request, tools: [...request.tools, tool] };",
|
||||
`return { ...request, tools: [...request.tools, tool], mcpServers: { ...request.mcpServers, company: ${JSON.stringify(companyServer)} } };`,
|
||||
);
|
||||
|
||||
test("a create that fails the MCP check leaves no plugin tools behind for its agent id", async () => {
|
||||
const h = await setup(false, mcpWithToolSource, undefined, { supportsMcpServers: false });
|
||||
try {
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
const agentId = "00000000-0000-4000-8000-000000009493";
|
||||
await expect(
|
||||
manager.createAgent({ provider: "codex", cwd: h.directory }, agentId, {}),
|
||||
).rejects.toThrow(/does not support MCP servers.*plugin tools-test/);
|
||||
expect(manager.getPluginTools(agentId)).toEqual([]);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("switching a native tool to an equivalent plugin under another id reopens the session, so its catalog reaches the replacement", async () => {
|
||||
const h = await setup(true, openCounterSource);
|
||||
try {
|
||||
const a = await h.create();
|
||||
await h.client.disablePlugin("tools-test");
|
||||
await h.install("replacement", openCounterSource);
|
||||
await sendAndFinish(h, a.id, "after replacement");
|
||||
expect(h.launches).toHaveLength(2);
|
||||
// The replacement answers: it saw the refresh and the reopen.
|
||||
expect(
|
||||
await h.launches.at(-1)!.context!.paseoTools!.executeTool("other_opens", {}),
|
||||
).toMatchObject({ content: [{ type: "text", text: "2" }] });
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
const mcpOnlySource = `
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => ({ ...request, mcpServers: { ...request.mcpServers, company: ${JSON.stringify(companyServer)} } }));
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
test("a plugin that adds an MCP server name another plugin already uses makes the reopen report the collision", async () => {
|
||||
const h = await setup(false, mcpOnlySource);
|
||||
try {
|
||||
const a = await h.create();
|
||||
await h.install("duplicate-mcp", mcpOnlySource);
|
||||
await expect(h.daemon.daemon.agentManager.reloadStalePluginSession(a.id)).rejects.toThrow(
|
||||
/MCP server company from plugin tools-test collides with plugin duplicate-mcp/,
|
||||
);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("a reopen that fails the MCP check is retried, and the running session keeps its plugin tools", async () => {
|
||||
const h = await setup(false, mcpSource, undefined, { supportsMcpServers: false });
|
||||
try {
|
||||
await h.client.disablePlugin("tools-test");
|
||||
await h.install("unrelated", breakableSource(path.join(h.directory, "never-armed")));
|
||||
const a = await h.create();
|
||||
await h.client.enablePlugin("tools-test");
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(/does not support MCP/);
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(/does not support MCP/);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
expect(
|
||||
await (await h.mcp(a.id)).callTool({ name: "breakable_ping", arguments: {} }),
|
||||
).toMatchObject({ content: [{ type: "text", text: "pong" }] });
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("a reopen whose plugin MCP server takes a saved server name is retried, and reverting the plugin restores its tools", async () => {
|
||||
const h = await setup(false, openCounterSource);
|
||||
try {
|
||||
const manager = h.daemon.daemon.agentManager;
|
||||
const a = await manager.createAgent(
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: h.directory,
|
||||
mcpServers: { company: companyServer },
|
||||
},
|
||||
undefined,
|
||||
{},
|
||||
);
|
||||
await writePluginSource(
|
||||
h,
|
||||
"tools-test",
|
||||
openCounterSource.replace(
|
||||
"return { ...request, tools: [...request.tools, tool] };",
|
||||
`return { ...request, tools: [...request.tools, tool], mcpServers: { company: ${JSON.stringify(companyServer)} } };`,
|
||||
),
|
||||
);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
const collision = /MCP server 'company' from plugin tools-test collides with agent saved/;
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(collision);
|
||||
await expect(manager.reloadStalePluginSession(a.id)).rejects.toThrow(collision);
|
||||
|
||||
await writePluginSource(h, "tools-test", openCounterSource);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
expect(await listedToolNames(await h.mcp(a.id))).toContain("other_opens");
|
||||
await manager.reloadStalePluginSession(a.id);
|
||||
expect(h.launches).toHaveLength(1);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("history opens ignore session-open MCP servers", async () => {
|
||||
const h = await setup(true, mcpSource);
|
||||
try {
|
||||
|
||||
@@ -27,46 +27,9 @@ export type SessionOpenWireRequest = Omit<PluginSessionOpenRequest, "tools"> & {
|
||||
tools: AgentToolMetadata[];
|
||||
};
|
||||
|
||||
export type PluginSessionOpenResult = SessionOpenWireRequest & {
|
||||
tools: AttachedAgentTool[];
|
||||
mcpServerOwners: Record<string, string>;
|
||||
};
|
||||
|
||||
/** What an open request says about the agent that can change while its session runs. Plugins cannot change it. */
|
||||
export type SessionOpenAgentFacts = Pick<
|
||||
SessionOpenWireRequest,
|
||||
"workspaceId" | "title" | "background" | "labels" | "metadata"
|
||||
>;
|
||||
|
||||
export interface PluginSessionRefreshOptions {
|
||||
/** Tool names a refreshed plugin tool must not take, beyond the tools other plugins attached. */
|
||||
reservedToolNames(): Promise<ReadonlySet<string>>;
|
||||
/** The agent as it is now, so a rerun callback sees what a reopen would show it. */
|
||||
agentFacts(): Promise<SessionOpenAgentFacts>;
|
||||
}
|
||||
|
||||
/** What the agent manager asks of plugins about a session: its open, its attached tools, and their calls. */
|
||||
export interface PluginSessionsRuntime {
|
||||
/**
|
||||
* Runs every `agent.open.before` callback for a session open and records what each plugin attached. The result
|
||||
* replaces the running session's record once `sessionLaunched` reports that its provider launch took over.
|
||||
*/
|
||||
openSession(request: SessionOpenWireRequest): Promise<PluginSessionOpenResult>;
|
||||
/** The provider session launched with the last open's result. */
|
||||
sessionLaunched(agentId: string): void;
|
||||
/** The last open's result did not launch; the session still running keeps its tools. */
|
||||
sessionLaunchFailed(agentId: string): void;
|
||||
/**
|
||||
* Reruns the open of only the plugins that changed since the session opened, swaps in their tools, and reports
|
||||
* whether the session must reopen to apply the rest.
|
||||
*/
|
||||
refreshSession(
|
||||
agentId: string,
|
||||
options: PluginSessionRefreshOptions,
|
||||
): Promise<{ stale: boolean }>;
|
||||
/** The session's tools from running plugin instances. */
|
||||
sessionTools(agentId: string): readonly AttachedAgentTool[];
|
||||
closeSession(agentId: string): void;
|
||||
export interface PluginAgentToolsRuntime {
|
||||
isToolPluginAvailable(pluginId: string, pluginInstanceId: string): boolean;
|
||||
detachTools(agentId: string): void;
|
||||
callTool(
|
||||
pluginId: string,
|
||||
pluginInstanceId: string,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { PluginSessionsRuntime } from "./agent-tools.js";
|
||||
import type { PluginAgentToolsRuntime } from "./agent-tools.js";
|
||||
import type { PluginLifecycle } from "./lifecycle/index.js";
|
||||
import path from "node:path";
|
||||
import { stat, rm } from "node:fs/promises";
|
||||
@@ -42,9 +42,10 @@ import type { PluginUsageSourceMetadata } from "./plugin-process-protocol.js";
|
||||
const BUILTIN_PROVIDER_ID_SET: ReadonlySet<string> = new Set(BUILTIN_PROVIDER_IDS);
|
||||
|
||||
interface PluginRuntimePort {
|
||||
sessionAttachments?: PluginRuntime["sessionAttachments"];
|
||||
subscribeSessionOpenChanges?: PluginRuntime["subscribeSessionOpenChanges"];
|
||||
isToolPluginAvailable?: PluginRuntime["isToolPluginAvailable"];
|
||||
callTool?: PluginRuntime["callTool"];
|
||||
detachTools?: PluginRuntime["detachTools"];
|
||||
emit?: PluginLifecycle["emit"];
|
||||
drainEvents?: PluginRuntime["drainEvents"];
|
||||
before?: PluginLifecycle["before"];
|
||||
@@ -101,11 +102,6 @@ export class PluginService {
|
||||
private readonly builtinPlugins: BuiltinPluginLoader;
|
||||
private readonly logger: pino.Logger;
|
||||
private readonly errors = new Map<string, string>();
|
||||
/**
|
||||
* Restarts in progress. A restart stops the plugin before its replacement starts; a session refresh waits for it,
|
||||
* so the gap never reads as the plugin's removal. A restart that fails to start reads as one.
|
||||
*/
|
||||
private readonly restarts = new Set<Promise<void>>();
|
||||
private readonly listeners = new Set<(pluginId: string) => void>();
|
||||
private readonly providers = new Map<string, ProviderRegistration>();
|
||||
private readonly usageSources: UsageSourceRegistry;
|
||||
@@ -157,33 +153,22 @@ export class PluginService {
|
||||
this.runtime.emit?.(name, event);
|
||||
};
|
||||
|
||||
readonly openSession: PluginSessionsRuntime["openSession"] = async (request) => {
|
||||
if (this.runtime.sessionAttachments) return this.runtime.sessionAttachments.open(request);
|
||||
return { ...request, tools: [], mcpServers: {}, mcpServerOwners: {} };
|
||||
subscribeSessionOpenChanges(listener: () => void): () => void {
|
||||
return this.runtime.subscribeSessionOpenChanges?.(listener) ?? (() => {});
|
||||
}
|
||||
|
||||
readonly isToolPluginAvailable: PluginAgentToolsRuntime["isToolPluginAvailable"] = (
|
||||
pluginId,
|
||||
pluginInstanceId,
|
||||
) => {
|
||||
return this.runtime.isToolPluginAvailable?.(pluginId, pluginInstanceId) ?? false;
|
||||
};
|
||||
|
||||
readonly sessionLaunched: PluginSessionsRuntime["sessionLaunched"] = (agentId) => {
|
||||
this.runtime.sessionAttachments?.launched(agentId);
|
||||
readonly detachTools: PluginAgentToolsRuntime["detachTools"] = (agentId) => {
|
||||
this.runtime.detachTools?.(agentId);
|
||||
};
|
||||
|
||||
readonly sessionLaunchFailed: PluginSessionsRuntime["sessionLaunchFailed"] = (agentId) => {
|
||||
this.runtime.sessionAttachments?.launchFailed(agentId);
|
||||
};
|
||||
|
||||
readonly refreshSession: PluginSessionsRuntime["refreshSession"] = async (agentId, options) => {
|
||||
while (this.restarts.size > 0) await Promise.all(this.restarts);
|
||||
return (await this.runtime.sessionAttachments?.refresh(agentId, options)) ?? { stale: false };
|
||||
};
|
||||
|
||||
readonly sessionTools: PluginSessionsRuntime["sessionTools"] = (agentId) => {
|
||||
return this.runtime.sessionAttachments?.tools(agentId) ?? [];
|
||||
};
|
||||
|
||||
readonly closeSession: PluginSessionsRuntime["closeSession"] = (agentId) => {
|
||||
this.runtime.sessionAttachments?.close(agentId);
|
||||
};
|
||||
|
||||
readonly callTool: PluginSessionsRuntime["callTool"] = async (
|
||||
readonly callTool: PluginAgentToolsRuntime["callTool"] = async (
|
||||
pluginId,
|
||||
pluginInstanceId,
|
||||
agent,
|
||||
@@ -191,7 +176,7 @@ export class PluginService {
|
||||
input,
|
||||
signal,
|
||||
) => {
|
||||
if (!this.runtime.isToolPluginAvailable?.(pluginId, pluginInstanceId) || !this.runtime.callTool)
|
||||
if (!this.isToolPluginAvailable(pluginId, pluginInstanceId) || !this.runtime.callTool)
|
||||
return { isError: true, text: `Plugin is not available: ${pluginId}` };
|
||||
return this.runtime.callTool(pluginId, pluginInstanceId, agent, name, input, signal);
|
||||
};
|
||||
@@ -528,10 +513,8 @@ export class PluginService {
|
||||
throw new Error("Plugins are globally disabled");
|
||||
}
|
||||
this.errors.delete(pluginId);
|
||||
await this.restart(async () => {
|
||||
await this.stopPlugin(pluginId);
|
||||
await this.startExplicit(pluginId, source.path);
|
||||
});
|
||||
await this.stopPlugin(pluginId);
|
||||
await this.startExplicit(pluginId, source.path);
|
||||
this.notify(pluginId);
|
||||
return this.requireItem(pluginId);
|
||||
});
|
||||
@@ -874,17 +857,6 @@ export class PluginService {
|
||||
for (const listener of this.providerListeners) listener();
|
||||
}
|
||||
|
||||
private async restart(run: () => Promise<void>): Promise<void> {
|
||||
const restart = run();
|
||||
const settled = restart.catch(() => {});
|
||||
this.restarts.add(settled);
|
||||
try {
|
||||
await restart;
|
||||
} finally {
|
||||
this.restarts.delete(settled);
|
||||
}
|
||||
}
|
||||
|
||||
private enqueue<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const result = this.lifecycle.then(operation, operation);
|
||||
this.lifecycle = result.then(
|
||||
@@ -925,30 +897,28 @@ export class PluginService {
|
||||
const shouldActivate =
|
||||
current.enabled !== false && this.configStore.get().pluginsEnabled === true;
|
||||
if (shouldActivate) {
|
||||
await this.restart(async () => {
|
||||
if (isRunning) await this.stopPlugin(pluginId);
|
||||
if (isRunning) await this.stopPlugin(pluginId);
|
||||
try {
|
||||
await this.startExplicit(pluginId, candidate.directory);
|
||||
} catch (error) {
|
||||
let recoveryError: unknown;
|
||||
try {
|
||||
await this.startExplicit(pluginId, candidate.directory);
|
||||
} catch (error) {
|
||||
let recoveryError: unknown;
|
||||
try {
|
||||
this.errors.delete(pluginId);
|
||||
if (isRunning && this.canPublish(pluginId))
|
||||
await this.startExplicit(pluginId, source.path);
|
||||
} catch (restoreError) {
|
||||
recoveryError = restoreError;
|
||||
} finally {
|
||||
await managedSources.discard(candidate);
|
||||
this.notify(pluginId);
|
||||
}
|
||||
if (recoveryError)
|
||||
throw new Error(
|
||||
`Update failed: ${error instanceof Error ? error.message : String(error)}; restoring previous plugin also failed: ${recoveryError instanceof Error ? recoveryError.message : String(recoveryError)}`,
|
||||
{ cause: error },
|
||||
);
|
||||
throw error;
|
||||
this.errors.delete(pluginId);
|
||||
if (isRunning && this.canPublish(pluginId))
|
||||
await this.startExplicit(pluginId, source.path);
|
||||
} catch (restoreError) {
|
||||
recoveryError = restoreError;
|
||||
} finally {
|
||||
await managedSources.discard(candidate);
|
||||
this.notify(pluginId);
|
||||
}
|
||||
});
|
||||
if (recoveryError)
|
||||
throw new Error(
|
||||
`Update failed: ${error instanceof Error ? error.message : String(error)}; restoring previous plugin also failed: ${recoveryError instanceof Error ? recoveryError.message : String(recoveryError)}`,
|
||||
{ cause: error },
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const activatedSource = this.configStore.get().plugins?.[pluginId];
|
||||
if (!activatedSource) {
|
||||
|
||||
@@ -34,11 +34,10 @@ export type PluginWireBeforeRequests = Omit<PluginHookRequests, "agent.open.befo
|
||||
"agent.open.before": SessionOpenWireRequest;
|
||||
};
|
||||
|
||||
/** Session opens run through the plugin runtime's session attachments, which record each plugin's contribution. */
|
||||
export type PluginLifecycleBeforeName = Exclude<
|
||||
keyof PluginWireBeforeRequests,
|
||||
"agent.open.before"
|
||||
>;
|
||||
/** Daemon-only results; ownership never crosses the plugin process boundary. */
|
||||
export type PluginBeforeResults = PluginWireBeforeRequests & {
|
||||
"agent.open.before": SessionOpenWireRequest & { mcpServerOwners?: Record<string, string> };
|
||||
};
|
||||
|
||||
const worktreeRequestFields = {
|
||||
repoRoot: z.string(),
|
||||
@@ -145,10 +144,10 @@ export interface PluginLifecycle {
|
||||
payload: PluginHookPayload<"worktree.create.after">,
|
||||
): Promise<void>;
|
||||
emit<Name extends keyof PluginHookEvents>(name: Name, event: PluginHookEvents[Name]): void;
|
||||
before<Name extends PluginLifecycleBeforeName>(
|
||||
before<Name extends keyof PluginWireBeforeRequests>(
|
||||
name: Name,
|
||||
request: PluginWireBeforeRequests[Name],
|
||||
): Promise<PluginWireBeforeRequests[Name]>;
|
||||
): Promise<PluginBeforeResults[Name]>;
|
||||
}
|
||||
|
||||
export function validateBeforeRequest<Name extends keyof PluginWireBeforeRequests>(
|
||||
@@ -391,8 +390,7 @@ export class PluginHookHandlers implements PluginLifecycleRegistration {
|
||||
context: PluginHookContext,
|
||||
): Promise<SessionOpenWireRequest> {
|
||||
let request = validateBeforeRequest("agent.open.before", input);
|
||||
// Attaching replaces the session's definitions for later calls; calls already running finish. The daemon detaches
|
||||
// the session before an open that replaces the provider session.
|
||||
this.agentTools?.detach(request.agentId);
|
||||
let tools: AgentToolDefinition[] = [];
|
||||
for (const handler of this.handlers.get("agent.open.before") ?? []) {
|
||||
context.signal.throwIfAborted();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { validateWorktreePath } from "../../utils/worktree-path.js";
|
||||
import type { PluginHookPayload } from "@getpaseo/plugin/server";
|
||||
import type { PluginLifecycleBeforeName, PluginWireBeforeRequests } from "./lifecycle/index.js";
|
||||
import { SessionAttachments, type SessionOpenPlugin } from "./session-attachments.js";
|
||||
import type { PluginWireBeforeRequests, PluginBeforeResults } from "./lifecycle/index.js";
|
||||
import type { SessionOpenWireRequest, AttachedAgentTool } from "./agent-tools.js";
|
||||
import type { UsageScope } from "@getpaseo/plugin/server/usage";
|
||||
import {
|
||||
ProviderInspectionSchema,
|
||||
@@ -374,8 +374,7 @@ export class PluginRuntime {
|
||||
private readonly spawnChild: () => PluginChild;
|
||||
private sessionHost: PluginPaseoSessionHost | null;
|
||||
private readonly listeners = new Set<(pluginId: string, error?: string) => void>();
|
||||
/** What `agent.open.before` plugins attached to each live session. */
|
||||
readonly sessionAttachments: SessionAttachments;
|
||||
private readonly sessionOpenListeners = new Set<() => void>();
|
||||
|
||||
constructor(
|
||||
logger: pino.Logger,
|
||||
@@ -385,13 +384,6 @@ export class PluginRuntime {
|
||||
this.logger = logger.child({ module: "plugins" });
|
||||
this.spawnChild = dependencies.spawnChild ?? spawnPluginChild;
|
||||
this.sessionHost = dependencies.sessionHost ?? null;
|
||||
this.sessionAttachments = new SessionAttachments(
|
||||
{
|
||||
sessionOpenPlugins: () => this.sessionOpenPlugins(),
|
||||
detachEverywhere: (agentId) => this.detachTools(agentId),
|
||||
},
|
||||
this.logger,
|
||||
);
|
||||
}
|
||||
|
||||
bindPaseoSessionHost(sessionHost: PluginPaseoSessionHost): void {
|
||||
@@ -405,6 +397,16 @@ export class PluginRuntime {
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
subscribeSessionOpenChanges(listener: () => void): () => void {
|
||||
this.sessionOpenListeners.add(listener);
|
||||
return () => this.sessionOpenListeners.delete(listener);
|
||||
}
|
||||
|
||||
private notifySessionOpenChange(loaded: LoadedPlugin): void {
|
||||
if (!loaded.hooks.includes("agent.open.before")) return;
|
||||
for (const listener of this.sessionOpenListeners) listener();
|
||||
}
|
||||
|
||||
async startPlugin(
|
||||
pluginId: string,
|
||||
configuredPath: string,
|
||||
@@ -427,6 +429,7 @@ export class PluginRuntime {
|
||||
throw new Error(`Plugin start cancelled: ${pluginId}`);
|
||||
}
|
||||
this.plugins.set(pluginId, loaded);
|
||||
this.notifySessionOpenChange(loaded);
|
||||
this.appendLog(pluginId, "stdout", "[paseo] Plugin ready");
|
||||
}
|
||||
|
||||
@@ -446,6 +449,7 @@ export class PluginRuntime {
|
||||
clientBundle: bundles.clientBundle ?? "",
|
||||
});
|
||||
this.plugins.set(input.id, loaded);
|
||||
this.notifySessionOpenChange(loaded);
|
||||
this.appendLog(input.id, "stdout", "[paseo] Plugin ready");
|
||||
}
|
||||
|
||||
@@ -457,6 +461,7 @@ export class PluginRuntime {
|
||||
const loaded = this.plugins.get(pluginId);
|
||||
if (!loaded) return false;
|
||||
this.plugins.delete(pluginId);
|
||||
this.notifySessionOpenChange(loaded);
|
||||
this.rejectPending(loaded, `Plugin stopped: ${pluginId}`);
|
||||
await this.stopPlugin(loaded);
|
||||
return true;
|
||||
@@ -747,14 +752,17 @@ export class PluginRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
async before<Name extends PluginLifecycleBeforeName>(
|
||||
async before<Name extends keyof PluginWireBeforeRequests>(
|
||||
name: Name,
|
||||
input: PluginWireBeforeRequests[Name],
|
||||
): Promise<PluginWireBeforeRequests[Name]> {
|
||||
): Promise<PluginBeforeResults[Name]> {
|
||||
let request = validateBeforeRequest(name, input);
|
||||
const plugins = [...this.plugins.values()].sort((left, right) => {
|
||||
return left.id.localeCompare(right.id);
|
||||
});
|
||||
const attached: AttachedAgentTool[] = [];
|
||||
const mcpServers: SessionOpenWireRequest["mcpServers"] = {};
|
||||
const mcpServerOwners: Record<string, string> = {};
|
||||
for (const loaded of plugins) {
|
||||
if (!loaded.hooks.includes(name)) {
|
||||
continue;
|
||||
@@ -764,7 +772,7 @@ export class PluginRuntime {
|
||||
type: "hook",
|
||||
requestId: randomUUID(),
|
||||
name,
|
||||
input: request,
|
||||
input: name === "agent.open.before" ? { ...request, tools: [], mcpServers: {} } : request,
|
||||
});
|
||||
request = await validateBeforeResult(name, request, output);
|
||||
if (name === "worktree.create.before") {
|
||||
@@ -774,12 +782,27 @@ export class PluginRuntime {
|
||||
repoPath: worktree.repoRoot,
|
||||
});
|
||||
}
|
||||
if (name === "agent.open.before") {
|
||||
const opened = request as SessionOpenWireRequest;
|
||||
this.collectMcpServers(mcpServers, mcpServerOwners, loaded, opened.mcpServers);
|
||||
this.collectAgentTools(attached, loaded, opened.tools);
|
||||
}
|
||||
} catch (error) {
|
||||
if (name === "agent.open.before")
|
||||
this.detachTools((request as SessionOpenWireRequest).agentId);
|
||||
throw new Error(`Plugin ${loaded.id} ${name} failed: ${describeError(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (name === "agent.open.before") {
|
||||
return {
|
||||
...request,
|
||||
tools: attached,
|
||||
mcpServers,
|
||||
mcpServerOwners,
|
||||
} as PluginBeforeResults[Name];
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
@@ -904,34 +927,43 @@ export class PluginRuntime {
|
||||
return output;
|
||||
}
|
||||
|
||||
private collectMcpServers(
|
||||
servers: SessionOpenWireRequest["mcpServers"],
|
||||
owners: Record<string, string>,
|
||||
loaded: LoadedPlugin,
|
||||
contributions: SessionOpenWireRequest["mcpServers"],
|
||||
): void {
|
||||
for (const [name, server] of Object.entries(contributions)) {
|
||||
if (Object.hasOwn(servers, name)) {
|
||||
throw new Error(
|
||||
`MCP server ${name} from plugin ${loaded.id} collides with plugin ${owners[name]}`,
|
||||
);
|
||||
}
|
||||
servers[name] = server;
|
||||
owners[name] = loaded.id;
|
||||
}
|
||||
}
|
||||
|
||||
private collectAgentTools(
|
||||
attached: AttachedAgentTool[],
|
||||
loaded: LoadedPlugin,
|
||||
tools: SessionOpenWireRequest["tools"],
|
||||
): void {
|
||||
for (const tool of tools) {
|
||||
const collision = attached.find((entry) => entry.name === tool.name);
|
||||
if (collision)
|
||||
throw new Error(
|
||||
`Agent tool ${tool.name} from plugin ${loaded.id} collides with plugin ${collision.pluginId}`,
|
||||
);
|
||||
attached.push({ ...tool, pluginId: loaded.id, pluginInstanceId: loaded.instanceId });
|
||||
}
|
||||
}
|
||||
|
||||
isToolPluginAvailable(pluginId: string, pluginInstanceId: string): boolean {
|
||||
return this.plugins.get(pluginId)?.instanceId === pluginInstanceId;
|
||||
}
|
||||
|
||||
private sessionOpenPlugins(): SessionOpenPlugin[] {
|
||||
return [...this.plugins.values()]
|
||||
.filter((loaded) => loaded.child && loaded.hooks.includes("agent.open.before"))
|
||||
.sort((left, right) => left.id.localeCompare(right.id))
|
||||
.map((loaded) => ({
|
||||
id: loaded.id,
|
||||
instanceId: loaded.instanceId,
|
||||
open: async (input) => {
|
||||
const output = await this.request(loaded, {
|
||||
type: "hook",
|
||||
requestId: randomUUID(),
|
||||
name: "agent.open.before",
|
||||
input,
|
||||
});
|
||||
return validateBeforeResult("agent.open.before", input, output);
|
||||
},
|
||||
detach: (agentId) => {
|
||||
if (loaded.child)
|
||||
void send(loaded.child, { type: "tools.detach", agentId }).catch(() => {});
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
private detachTools(agentId: string): void {
|
||||
detachTools(agentId: string): void {
|
||||
for (const loaded of this.plugins.values()) {
|
||||
if (loaded.child) void send(loaded.child, { type: "tools.detach", agentId }).catch(() => {});
|
||||
}
|
||||
@@ -1037,6 +1069,7 @@ export class PluginRuntime {
|
||||
const loaded = [...this.plugins.values()];
|
||||
this.plugins.clear();
|
||||
for (const plugin of loaded) {
|
||||
this.notifySessionOpenChange(plugin);
|
||||
this.rejectPending(plugin, `Plugin stopped: ${plugin.id}`);
|
||||
}
|
||||
await Promise.all(loaded.map((plugin) => this.stopPlugin(plugin)));
|
||||
@@ -1277,7 +1310,14 @@ export class PluginRuntime {
|
||||
|
||||
private handleChildMessage(loaded: LoadedPlugin, message: PluginProcessMessage): void {
|
||||
if (message.type === "hooks.changed") {
|
||||
const hadSessionOpen = loaded.hooks.includes("agent.open.before");
|
||||
loaded.hooks = message.hooks;
|
||||
if (
|
||||
this.plugins.get(loaded.id) === loaded &&
|
||||
hadSessionOpen !== loaded.hooks.includes("agent.open.before")
|
||||
) {
|
||||
for (const listener of this.sessionOpenListeners) listener();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (message.type === "worktree_manager.changed") {
|
||||
@@ -1609,6 +1649,7 @@ export class PluginRuntime {
|
||||
const wasPublished = this.plugins.get(loaded.id) === loaded;
|
||||
if (wasPublished) {
|
||||
this.plugins.delete(loaded.id);
|
||||
this.notifySessionOpenChange(loaded);
|
||||
}
|
||||
this.rejectPending(loaded, `Plugin process exited: ${loaded.id}`);
|
||||
for (const state of loaded.providerConnections.values()) {
|
||||
|
||||
@@ -1,472 +0,0 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import type pino from "pino";
|
||||
import type {
|
||||
AttachedAgentTool,
|
||||
PluginSessionOpenResult,
|
||||
PluginSessionRefreshOptions,
|
||||
SessionOpenAgentFacts,
|
||||
SessionOpenWireRequest,
|
||||
} from "./agent-tools.js";
|
||||
|
||||
/** A running plugin that declares `agent.open.before`. */
|
||||
export interface SessionOpenPlugin {
|
||||
id: string;
|
||||
instanceId: string;
|
||||
/** Runs this plugin's `agent.open.before` callback and returns its validated result. */
|
||||
open(input: SessionOpenWireRequest): Promise<SessionOpenWireRequest>;
|
||||
/** Drops the agent's tool definitions inside this plugin's process. */
|
||||
detach(agentId: string): void;
|
||||
}
|
||||
|
||||
export interface SessionAttachmentPlugins {
|
||||
/** The running plugins that declare `agent.open.before`, in the order a session open runs them. */
|
||||
sessionOpenPlugins(): SessionOpenPlugin[];
|
||||
/** Every running plugin process, so a closed session leaves no tool definitions behind. */
|
||||
detachEverywhere(agentId: string): void;
|
||||
}
|
||||
|
||||
/** What one plugin's `agent.open.before` callback was handed and returned for a session. */
|
||||
interface Contribution {
|
||||
pluginId: string;
|
||||
pluginInstanceId: string;
|
||||
input: SessionOpenWireRequest;
|
||||
output: SessionOpenWireRequest;
|
||||
tools: AttachedAgentTool[];
|
||||
/** The plugin process holds this contribution's tool definitions for the session. */
|
||||
synced: boolean;
|
||||
/** Its rerun failed or its tools collided, so its tools stay off until the reopen reports why. */
|
||||
failed: boolean;
|
||||
}
|
||||
|
||||
interface Attachment {
|
||||
base: SessionOpenWireRequest;
|
||||
/** What each plugin contributed to the provider launch the session is running. */
|
||||
launched: readonly Contribution[];
|
||||
/** What each plugin contributes now, after the refreshes since that launch. */
|
||||
contributions: Contribution[];
|
||||
/** A reopen now would launch the provider differently from the running session. */
|
||||
stale: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns what `agent.open.before` plugins attached to each live session: the tools Paseo serves to the agent, and the
|
||||
* record of each plugin's contribution that decides whether a plugin change needs the session to reopen.
|
||||
*
|
||||
* A plugin restart gives it a new instance id. `refresh` reruns the open of only the plugins that changed for the
|
||||
* session, swaps in their tools at once, and marks the session stale only when the provider launch would differ from
|
||||
* the one it runs. An open becomes the baseline only once its provider launch takes over the session, so a failed open
|
||||
* or launch leaves the running launch as the baseline. Opens and refreshes of one session run one at a time.
|
||||
*/
|
||||
export class SessionAttachments {
|
||||
private readonly attachments = new Map<string, Attachment>();
|
||||
/** Interactive opens whose provider launch has not taken over the session yet. */
|
||||
private readonly pending = new Map<string, Attachment>();
|
||||
private readonly tails = new Map<string, Promise<unknown>>();
|
||||
|
||||
constructor(
|
||||
private readonly plugins: SessionAttachmentPlugins,
|
||||
private readonly logger: pino.Logger,
|
||||
) {}
|
||||
|
||||
async open(request: SessionOpenWireRequest): Promise<PluginSessionOpenResult> {
|
||||
return this.serialize(request.agentId, async () => {
|
||||
// Each plugin attaches its tools again below, and a plugin that left the chain keeps none. Until the launch
|
||||
// takes over, the running session's record stays, and its plugins attach again on its next refresh if the
|
||||
// launch fails.
|
||||
this.plugins.detachEverywhere(request.agentId);
|
||||
for (const contribution of this.attachments.get(request.agentId)?.contributions ?? []) {
|
||||
contribution.synced = false;
|
||||
}
|
||||
const base: SessionOpenWireRequest = { ...request, tools: [], mcpServers: {} };
|
||||
const contributions: Contribution[] = [];
|
||||
let current = base;
|
||||
for (const plugin of this.plugins.sessionOpenPlugins()) {
|
||||
const input: SessionOpenWireRequest = { ...current, tools: [], mcpServers: {} };
|
||||
try {
|
||||
const output = await plugin.open(input);
|
||||
const tools = stampTools(plugin, output.tools);
|
||||
assertNoToolCollision(contributions, plugin.id, tools);
|
||||
contributions.push({
|
||||
pluginId: plugin.id,
|
||||
pluginInstanceId: plugin.instanceId,
|
||||
input,
|
||||
output,
|
||||
tools,
|
||||
synced: true,
|
||||
failed: false,
|
||||
});
|
||||
current = output;
|
||||
} catch (error) {
|
||||
this.plugins.detachEverywhere(request.agentId);
|
||||
throw new Error(`Plugin ${plugin.id} agent.open.before failed: ${describeError(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
let launch: PluginSessionOpenResult;
|
||||
try {
|
||||
launch = composeLaunch(base, contributions);
|
||||
} catch (error) {
|
||||
this.plugins.detachEverywhere(request.agentId);
|
||||
throw error;
|
||||
}
|
||||
if (request.purpose === "interactive") {
|
||||
this.pending.set(request.agentId, {
|
||||
base,
|
||||
launched: contributions,
|
||||
contributions: [...contributions],
|
||||
stale: false,
|
||||
});
|
||||
}
|
||||
return launch;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings a live session's tools up to date with the running plugins and reports whether the session must reopen
|
||||
* to apply the rest. Plugins that did not change since the session opened are not called.
|
||||
*/
|
||||
async refresh(
|
||||
agentId: string,
|
||||
options: PluginSessionRefreshOptions,
|
||||
): Promise<{ stale: boolean }> {
|
||||
const attachment = this.attachments.get(agentId);
|
||||
// A launch in progress attaches its own tools and takes over once it succeeds.
|
||||
if (!attachment || this.pending.has(agentId)) return { stale: false };
|
||||
if (this.isCurrent(attachment)) return { stale: attachment.stale };
|
||||
return this.serialize(agentId, () => this.reconcile(agentId, options));
|
||||
}
|
||||
|
||||
/** The provider session launched with the last open's result and now runs it. */
|
||||
launched(agentId: string): void {
|
||||
const opened = this.pending.get(agentId);
|
||||
if (!opened) return;
|
||||
this.pending.delete(agentId);
|
||||
this.attachments.set(agentId, opened);
|
||||
}
|
||||
|
||||
/** The last open's result never launched. The session that is still running keeps its record. */
|
||||
launchFailed(agentId: string): void {
|
||||
// Nothing is pending once a launch took over; its later failures close the session instead.
|
||||
if (!this.pending.delete(agentId)) return;
|
||||
this.plugins.detachEverywhere(agentId);
|
||||
}
|
||||
|
||||
/** The session's tools from running plugin instances. */
|
||||
tools(agentId: string): AttachedAgentTool[] {
|
||||
const running = new Map(
|
||||
this.plugins.sessionOpenPlugins().map((plugin) => [plugin.id, plugin.instanceId]),
|
||||
);
|
||||
const attachment = this.pending.get(agentId) ?? this.attachments.get(agentId);
|
||||
return (attachment?.contributions ?? [])
|
||||
.filter(
|
||||
(contribution) =>
|
||||
contribution.synced &&
|
||||
running.get(contribution.pluginId) === contribution.pluginInstanceId,
|
||||
)
|
||||
.flatMap((contribution) => contribution.tools);
|
||||
}
|
||||
|
||||
close(agentId: string): void {
|
||||
this.pending.delete(agentId);
|
||||
this.attachments.delete(agentId);
|
||||
this.plugins.detachEverywhere(agentId);
|
||||
}
|
||||
|
||||
private isCurrent(attachment: Attachment): boolean {
|
||||
const running = this.plugins.sessionOpenPlugins();
|
||||
return (
|
||||
running.length === attachment.contributions.length &&
|
||||
running.every((plugin, index) => {
|
||||
const contribution = attachment.contributions[index];
|
||||
return (
|
||||
contribution.synced &&
|
||||
contribution.pluginId === plugin.id &&
|
||||
contribution.pluginInstanceId === plugin.instanceId
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private async reconcile(
|
||||
agentId: string,
|
||||
options: PluginSessionRefreshOptions,
|
||||
): Promise<{ stale: boolean }> {
|
||||
const attachment = this.attachments.get(agentId);
|
||||
if (!attachment || this.pending.has(agentId)) return { stale: false };
|
||||
if (this.isCurrent(attachment)) return { stale: attachment.stale };
|
||||
const recorded = new Map(
|
||||
attachment.contributions.map((contribution) => [contribution.pluginId, contribution]),
|
||||
);
|
||||
// The running plugins in open order, as a reopen would run them. A stopped plugin, or one that no longer declares
|
||||
// the callback, drops out, and the plugins after it see the chain without it.
|
||||
let previous = attachment.base;
|
||||
const contributions: Contribution[] = [];
|
||||
const replayed: { contribution: Contribution; plugin: SessionOpenPlugin }[] = [];
|
||||
let facts: SessionOpenAgentFacts | undefined;
|
||||
for (const plugin of this.plugins.sessionOpenPlugins()) {
|
||||
const before = recorded.get(plugin.id);
|
||||
if (before && isReusable(before, plugin, previous)) {
|
||||
contributions.push(before);
|
||||
previous = before.output;
|
||||
continue;
|
||||
}
|
||||
facts ??= await options.agentFacts();
|
||||
const contribution = await this.replay(plugin, {
|
||||
...previous,
|
||||
...facts,
|
||||
tools: [],
|
||||
mcpServers: {},
|
||||
});
|
||||
contributions.push(contribution);
|
||||
replayed.push({ contribution, plugin });
|
||||
previous = contribution.output;
|
||||
}
|
||||
await this.dropCollidingTools({
|
||||
agentId,
|
||||
owners: toolOwners(attachment.contributions),
|
||||
contributions,
|
||||
replayed,
|
||||
options,
|
||||
});
|
||||
if (this.attachments.get(agentId) !== attachment) {
|
||||
// The session closed during the replay. Its close detached every plugin before the replay attached again.
|
||||
for (const { plugin } of replayed) plugin.detach(agentId);
|
||||
return { stale: false };
|
||||
}
|
||||
attachment.contributions = contributions;
|
||||
attachment.stale =
|
||||
contributions.some((contribution) => contribution.failed) ||
|
||||
!launchesMatch(attachment.base, attachment.launched, contributions);
|
||||
return { stale: attachment.stale };
|
||||
}
|
||||
|
||||
/** Reruns one plugin's open for a live session, as the reopen the same change would cause. */
|
||||
private async replay(
|
||||
plugin: SessionOpenPlugin,
|
||||
input: SessionOpenWireRequest,
|
||||
): Promise<Contribution> {
|
||||
const contribution = (output: SessionOpenWireRequest, failed: boolean): Contribution => ({
|
||||
pluginId: plugin.id,
|
||||
pluginInstanceId: plugin.instanceId,
|
||||
input,
|
||||
output,
|
||||
tools: stampTools(plugin, output.tools),
|
||||
synced: true,
|
||||
failed,
|
||||
});
|
||||
try {
|
||||
return contribution(await plugin.open({ ...input, reason: "refresh" }), false);
|
||||
} catch (error) {
|
||||
// Recorded under the new instance with no tools, so later requests do not wait on it again. The reopen
|
||||
// reruns the callback and reports its error.
|
||||
this.logger.warn(
|
||||
{ err: error, pluginId: plugin.id, agentId: input.agentId },
|
||||
"Plugin session refresh failed",
|
||||
);
|
||||
return contribution(input, true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A replayed plugin whose tool takes a name already in use keeps no tools; the reopen reports the collision. A name
|
||||
* stays with the plugin that has it in the session's record, whatever the plugin order.
|
||||
*/
|
||||
private async dropCollidingTools({
|
||||
agentId,
|
||||
owners,
|
||||
contributions,
|
||||
replayed,
|
||||
options,
|
||||
}: CollisionCheck): Promise<void> {
|
||||
if (replayed.every(({ contribution }) => contribution.tools.length === 0)) return;
|
||||
const changed = new Set(replayed.map(({ contribution }) => contribution));
|
||||
const taken = new Set(await options.reservedToolNames());
|
||||
for (const contribution of contributions) {
|
||||
if (!changed.has(contribution)) for (const tool of contribution.tools) taken.add(tool.name);
|
||||
}
|
||||
// The previous owner keeps a name only while it still returns that tool.
|
||||
const ownedElsewhere = (contribution: Contribution, name: string) => {
|
||||
const owner = owners.get(name);
|
||||
if (owner === undefined || owner === contribution.pluginId) return false;
|
||||
return contributions.some(
|
||||
(other) => other.pluginId === owner && other.tools.some((tool) => tool.name === name),
|
||||
);
|
||||
};
|
||||
for (const contribution of changed) {
|
||||
const conflict = contribution.tools.find(
|
||||
(tool) => taken.has(tool.name) || ownedElsewhere(contribution, tool.name),
|
||||
);
|
||||
if (conflict) {
|
||||
this.logger.warn(
|
||||
{ agentId, pluginId: contribution.pluginId, tool: conflict.name },
|
||||
"Refreshed plugin tool collides with another agent tool",
|
||||
);
|
||||
contribution.tools = [];
|
||||
contribution.failed = true;
|
||||
continue;
|
||||
}
|
||||
for (const tool of contribution.tools) taken.add(tool.name);
|
||||
}
|
||||
}
|
||||
|
||||
private serialize<T>(agentId: string, run: () => Promise<T>): Promise<T> {
|
||||
const previous = this.tails.get(agentId) ?? Promise.resolve();
|
||||
const next = previous.then(run, run);
|
||||
const settled = next.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
this.tails.set(agentId, settled);
|
||||
void settled.finally(() => {
|
||||
if (this.tails.get(agentId) === settled) this.tails.delete(agentId);
|
||||
});
|
||||
return next;
|
||||
}
|
||||
}
|
||||
|
||||
interface CollisionCheck {
|
||||
agentId: string;
|
||||
/** Which plugin has each tool name in the session's record before this refresh. */
|
||||
owners: ReadonlyMap<string, string>;
|
||||
contributions: Contribution[];
|
||||
replayed: { contribution: Contribution }[];
|
||||
options: PluginSessionRefreshOptions;
|
||||
}
|
||||
|
||||
function toolOwners(contributions: readonly Contribution[]): Map<string, string> {
|
||||
return new Map(
|
||||
contributions.flatMap((contribution) =>
|
||||
contribution.tools.map((tool) => [tool.name, contribution.pluginId] as const),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A recorded contribution stands for the plugin's callback in a reopen while the plugin runs the same instance, holds
|
||||
* the tools in its process, and would receive the same env and instructions from the plugins before it.
|
||||
*/
|
||||
function isReusable(
|
||||
contribution: Contribution,
|
||||
plugin: SessionOpenPlugin,
|
||||
incoming: SessionOpenWireRequest,
|
||||
): boolean {
|
||||
return (
|
||||
contribution.synced &&
|
||||
contribution.pluginInstanceId === plugin.instanceId &&
|
||||
isDeepStrictEqual(chainedFields(contribution.input), chainedFields(incoming))
|
||||
);
|
||||
}
|
||||
|
||||
/** The fields one plugin's callback passes on to the next. Tools and MCP servers are collected per plugin instead. */
|
||||
function chainedFields(request: SessionOpenWireRequest) {
|
||||
return { env: request.env, appendSystemPrompt: request.appendSystemPrompt ?? [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* What the provider launches with when the session opens with these contributions, in open order. Throws when two
|
||||
* plugins return the same MCP server name.
|
||||
*/
|
||||
function composeLaunch(
|
||||
base: SessionOpenWireRequest,
|
||||
contributions: readonly Contribution[],
|
||||
): PluginSessionOpenResult {
|
||||
const mcpServers: SessionOpenWireRequest["mcpServers"] = {};
|
||||
const mcpServerOwners: Record<string, string> = {};
|
||||
for (const contribution of contributions) {
|
||||
collectMcpServers(
|
||||
mcpServers,
|
||||
mcpServerOwners,
|
||||
contribution.pluginId,
|
||||
contribution.output.mcpServers,
|
||||
);
|
||||
}
|
||||
return {
|
||||
...(contributions.at(-1)?.output ?? base),
|
||||
tools: contributions.flatMap((contribution) => contribution.tools),
|
||||
mcpServers,
|
||||
mcpServerOwners,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the proposed contributions launch the session as it runs now. A tool's plugin counts, since native-tool
|
||||
* catalogs dispatch to it; its instance does not. A launch the open would reject never matches, so the reopen
|
||||
* reports it.
|
||||
*/
|
||||
function launchesMatch(
|
||||
base: SessionOpenWireRequest,
|
||||
launched: readonly Contribution[],
|
||||
proposed: readonly Contribution[],
|
||||
): boolean {
|
||||
let next: PluginSessionOpenResult;
|
||||
try {
|
||||
next = composeLaunch(base, proposed);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return isDeepStrictEqual(launchContract(composeLaunch(base, launched)), launchContract(next));
|
||||
}
|
||||
|
||||
function launchContract(launch: PluginSessionOpenResult) {
|
||||
return {
|
||||
...chainedFields(launch),
|
||||
mcpServers: launch.mcpServers,
|
||||
tools: launch.tools.map(({ pluginId, name, title, description, inputSchema }) => ({
|
||||
pluginId,
|
||||
name,
|
||||
title,
|
||||
description,
|
||||
inputSchema,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function stampTools(
|
||||
plugin: SessionOpenPlugin,
|
||||
tools: SessionOpenWireRequest["tools"],
|
||||
): AttachedAgentTool[] {
|
||||
return tools.map((tool) => ({
|
||||
...tool,
|
||||
pluginId: plugin.id,
|
||||
pluginInstanceId: plugin.instanceId,
|
||||
}));
|
||||
}
|
||||
|
||||
function assertNoToolCollision(
|
||||
contributions: readonly Contribution[],
|
||||
pluginId: string,
|
||||
tools: readonly AttachedAgentTool[],
|
||||
): void {
|
||||
for (const tool of tools) {
|
||||
const owner = contributions.find((contribution) =>
|
||||
contribution.tools.some((entry) => entry.name === tool.name),
|
||||
);
|
||||
if (owner) {
|
||||
throw new Error(
|
||||
`Agent tool ${tool.name} from plugin ${pluginId} collides with plugin ${owner.pluginId}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function collectMcpServers(
|
||||
servers: SessionOpenWireRequest["mcpServers"],
|
||||
owners: Record<string, string>,
|
||||
pluginId: string,
|
||||
contributions: SessionOpenWireRequest["mcpServers"],
|
||||
): void {
|
||||
for (const [name, server] of Object.entries(contributions)) {
|
||||
if (Object.hasOwn(servers, name)) {
|
||||
throw new Error(
|
||||
`Plugin ${pluginId} agent.open.before failed: MCP server ${name} from plugin ${pluginId} collides with plugin ${owners[name]}`,
|
||||
);
|
||||
}
|
||||
servers[name] = server;
|
||||
owners[name] = pluginId;
|
||||
}
|
||||
}
|
||||
|
||||
function describeError(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
@@ -9,23 +9,19 @@ async function chooseLanguage(page: Page, language: string) {
|
||||
await page.getByRole("menuitemradio", { name: language }).click();
|
||||
}
|
||||
|
||||
async function withRequestsHeld(
|
||||
page: Page,
|
||||
pattern: string,
|
||||
run: (release: () => void) => Promise<void>,
|
||||
) {
|
||||
let releaseRequests!: () => void;
|
||||
const requestsReleased = new Promise<void>((resolve) => {
|
||||
releaseRequests = resolve;
|
||||
async function withPageScriptsHeld(page: Page, run: (release: () => void) => Promise<void>) {
|
||||
let releaseScripts!: () => void;
|
||||
const scriptsReleased = new Promise<void>((resolve) => {
|
||||
releaseScripts = resolve;
|
||||
});
|
||||
await page.route(pattern, async (route) => {
|
||||
await requestsReleased;
|
||||
await page.route("**/*.js", async (route) => {
|
||||
await scriptsReleased;
|
||||
await route.continue();
|
||||
});
|
||||
try {
|
||||
await run(releaseRequests);
|
||||
await run(releaseScripts);
|
||||
} finally {
|
||||
releaseRequests();
|
||||
releaseScripts();
|
||||
await page.unrouteAll({ behavior: "wait" });
|
||||
}
|
||||
}
|
||||
@@ -202,17 +198,13 @@ 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");
|
||||
|
||||
// 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();
|
||||
});
|
||||
await expect(page).toHaveURL(/\/zh-CN$/);
|
||||
await expect(languageButton(page)).toHaveText("ZH");
|
||||
await expect(languageButton(page)).toBeFocused();
|
||||
});
|
||||
|
||||
test.describe("on a phone", () => {
|
||||
@@ -268,7 +260,7 @@ test("shows the changelog in Chinese", async ({ page }) => {
|
||||
});
|
||||
|
||||
test("waits for scripts before enabling the language menu", async ({ page }) => {
|
||||
await withRequestsHeld(page, "**/*.js", async (releaseScripts) => {
|
||||
await withPageScriptsHeld(page, async (releaseScripts) => {
|
||||
await page.goto("/docs/cli#running-agents", { waitUntil: "commit" });
|
||||
await expect(languageButton(page)).toBeVisible();
|
||||
await expect(languageButton(page)).toBeDisabled();
|
||||
|
||||
@@ -10,37 +10,6 @@ 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();
|
||||
}
|
||||
@@ -141,7 +110,12 @@ 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,
|
||||
}) => {
|
||||
await openHomepageWithSceneClock(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));
|
||||
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);
|
||||
@@ -167,34 +141,30 @@ 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 openHomepageWithSceneClock(page);
|
||||
await openHomepage(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.clock.runFor(4500);
|
||||
await page.waitForTimeout(4500);
|
||||
await expect(request).toHaveCount(0);
|
||||
|
||||
await centerMockup(mockup);
|
||||
await expect(mockup).toBeInViewport({ ratio: 0.6 });
|
||||
await page.clock.runFor(4500);
|
||||
await expect(request).toBeVisible();
|
||||
await mockup.scrollIntoViewIfNeeded();
|
||||
await expect(request).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
|
||||
test("the opening scene starts in a window shorter than most of the mockup", async ({ page }) => {
|
||||
await openHomepageWithSceneClock(page, { width: 1400, height: 320 });
|
||||
await openHomepage(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 centerMockup(mockup);
|
||||
await expect(mockup).toBeInViewport();
|
||||
await mockup.scrollIntoViewIfNeeded();
|
||||
await expect(mockup).not.toBeInViewport({ ratio: 0.6 });
|
||||
await page.clock.runFor(4500);
|
||||
await expect(request).toBeVisible();
|
||||
await expect(request).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
|
||||
test("the plugins scene installs the panel, then changes it on request", async ({ page }) => {
|
||||
await openHomepageWithSceneClock(page);
|
||||
await openHomepage(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 });
|
||||
@@ -204,14 +174,12 @@ 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 page.clock.runFor(5500);
|
||||
await expect(pluginPanel).toBeVisible();
|
||||
await finishPanelSwap(page, mockup, changesPanel);
|
||||
await expect(pluginPanel).toBeVisible({ timeout: 20_000 });
|
||||
await expect(changesPanel).toHaveCount(0);
|
||||
await expect(failingCheck).toHaveCount(0);
|
||||
|
||||
// The second request reloads the plugin and the open panel lists the failing check.
|
||||
await page.clock.runFor(6000);
|
||||
await expect(failingCheck).toBeVisible();
|
||||
await expect(failingCheck).toBeVisible({ timeout: 15_000 });
|
||||
await expect(
|
||||
mockup.getByText("paseo plugin reload release-radar", { exact: true }),
|
||||
).toBeVisible();
|
||||
|
||||
@@ -18,14 +18,18 @@ export function agentRouteOptions(slug: AgentPageSlug) {
|
||||
locale,
|
||||
});
|
||||
},
|
||||
loader: () => ({ pluginCount: getPluginCount().catch(() => null) }),
|
||||
loader: async () => ({ pluginCount: await getPluginCount() }),
|
||||
component: function AgentLandingPage() {
|
||||
const { t } = useTranslation();
|
||||
const { pluginCount } = useLoaderData({ strict: false }) as {
|
||||
pluginCount: Promise<number | null>;
|
||||
};
|
||||
const data = useLoaderData({ strict: false }) as { pluginCount?: number | null } | undefined;
|
||||
const page = getAgentPage(slug, t);
|
||||
return <LandingPage title={page.title} subtitle={page.subtitle} pluginCount={pluginCount} />;
|
||||
return (
|
||||
<LandingPage
|
||||
title={page.title}
|
||||
subtitle={page.subtitle}
|
||||
pluginCount={data?.pluginCount ?? null}
|
||||
/>
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { Await } from "@tanstack/react-router";
|
||||
import { PLUGINS_LINKED } from "~/plugins/launch";
|
||||
import { categoryHref } from "~/plugins/links";
|
||||
import type { CategorySlug } from "~/plugins/categories";
|
||||
@@ -115,14 +114,14 @@ import "~/styles.css";
|
||||
interface LandingPageProps {
|
||||
title: React.ReactNode;
|
||||
subtitle: React.ReactNode;
|
||||
pluginCount: Promise<number | null>;
|
||||
pluginCount?: number | null;
|
||||
showHubEyebrow?: boolean;
|
||||
}
|
||||
|
||||
export function LandingPage({
|
||||
title,
|
||||
subtitle,
|
||||
pluginCount,
|
||||
pluginCount = null,
|
||||
showHubEyebrow = false,
|
||||
}: LandingPageProps) {
|
||||
return (
|
||||
@@ -614,7 +613,7 @@ function ProductLead({
|
||||
actions,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
title: React.ReactNode;
|
||||
title: string;
|
||||
description?: string;
|
||||
actions?: React.ReactNode;
|
||||
}) {
|
||||
@@ -980,23 +979,17 @@ const PLUGIN_CLIENT_COMPONENTS = {
|
||||
),
|
||||
};
|
||||
|
||||
function ExtensibleSection({ pluginCount }: { pluginCount: Promise<number | null> }) {
|
||||
function ExtensibleSection({ pluginCount }: { pluginCount?: number | null }) {
|
||||
const { t } = useTranslation();
|
||||
const pluginActions = React.useMemo(() => <PluginActions />, []);
|
||||
const description = React.useMemo(
|
||||
() => <Trans i18nKey="landing.plugins.description" components={PLUGIN_CLIENT_COMPONENTS} />,
|
||||
[],
|
||||
);
|
||||
const libraryTitle = React.useMemo(() => {
|
||||
const fallback = t("landing.plugins.libraryTitle");
|
||||
return (
|
||||
<Await promise={pluginCount} fallback={fallback}>
|
||||
{(count) =>
|
||||
count && count > 0 ? t("landing.plugins.libraryTitleCount", { count }) : fallback
|
||||
}
|
||||
</Await>
|
||||
);
|
||||
}, [pluginCount, t]);
|
||||
const libraryTitle =
|
||||
pluginCount && pluginCount > 0
|
||||
? t("landing.plugins.libraryTitleCount", { count: pluginCount })
|
||||
: t("landing.plugins.libraryTitle");
|
||||
return (
|
||||
<FeatureSection
|
||||
eyebrow={t("landing.eyebrows.plugins")}
|
||||
|
||||
@@ -16,7 +16,7 @@ export const Route = createFileRoute("/{-$locale}/")({
|
||||
locale,
|
||||
});
|
||||
},
|
||||
loader: () => ({ pluginCount: getPluginCount().catch(() => null) }),
|
||||
loader: async () => ({ pluginCount: await getPluginCount() }),
|
||||
component: Home,
|
||||
});
|
||||
|
||||
|
||||
@@ -498,42 +498,12 @@ target are unaffected.
|
||||
|
||||
| Change | When the agent receives it |
|
||||
| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Start, stop, or reload a plugin declaring `agent.open.before` | Before the session's next agent tool call or prompt, as described below. |
|
||||
| Start, stop, or reload a plugin declaring `agent.open.before` | Open sessions become stale. Each reopens before its next idle prompt; a running turn continues without interruption. The next prompt after that reopen reuses the session. |
|
||||
| Change which agents the callback targets | Run `paseo plugin reload agent-tools` after editing this example, then send the agent a prompt when it is idle. |
|
||||
| Apply immediately | Call `await paseo.agents.ref(id).reload({ requestId: "reload-notes" })`. `requestId` is optional. This reopens the provider session, reruns hooks with `reason: "refresh"`, and interrupts a running turn. |
|
||||
| Read the current snapshot | Call `await paseo.agents.ref(id).refresh()`. This reads state without reopening the session. |
|
||||
|
||||
When a plugin declaring `agent.open.before` starts, stops, or reloads, Paseo reruns that plugin's
|
||||
callback for each open session, before the session's next agent tool call or prompt. The callback
|
||||
gets the request it saw at the session's last open, with `reason: "refresh"` and the agent's current
|
||||
title, workspace, labels, and metadata. A later plugin in the chain also reruns when the env or
|
||||
instructions it receives change. Other callbacks do not run.
|
||||
|
||||
A reload counts as one change. A tool call or prompt during the reload waits for the plugin to
|
||||
start, so the session does not lose the plugin's tools in between. If the plugin fails to start,
|
||||
the session continues as if the plugin stopped.
|
||||
|
||||
- The tools the callback returns replace its old tools at once, also during a running turn. The new
|
||||
plugin instance answers the calls.
|
||||
- If the env, instructions, MCP servers, tool definitions, or the plugin that provides a tool
|
||||
differ from what the session launched with, the session reopens before its next idle prompt. A running turn continues without interruption.
|
||||
A callback whose result depends on `reason` always differs from a `create` open. Reverting the
|
||||
change before that prompt cancels the reopen.
|
||||
- If nothing differs, the session keeps running with its background work and subagents. A plugin
|
||||
that does not target the agent leaves it as it is.
|
||||
- If the callback throws or times out, its tools stay off, and the session reopens before its next
|
||||
idle prompt. Paseo does not rerun it for the same plugin instance.
|
||||
- If a returned tool collides with a Paseo tool or another plugin's tool, that plugin's tools stay
|
||||
off, and the session reopens before its next idle prompt.
|
||||
- If two plugins return the same MCP server name, both plugins keep their agent tools, but the reopen
|
||||
before the next idle prompt fails with the collision error.
|
||||
|
||||
Agents that receive Paseo tools natively (OpenCode with the bridge, OMP) keep the tool list they
|
||||
launched with until the reopen. Their calls to a listed tool reach the new instance of the plugin
|
||||
that attached it, and fail if that plugin no longer attaches it.
|
||||
|
||||
If an automatic reopen fails, the triggering prompt fails with that error. The session keeps
|
||||
running with the tools it had, and each later idle prompt tries the reopen again. See the
|
||||
If an automatic reopen fails, the triggering prompt fails with that error. See the
|
||||
[complete agent-tools example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools).
|
||||
|
||||
## agent.close.after
|
||||
|
||||
@@ -15,18 +15,15 @@ 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, [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;
|
||||
- slash commands in the message composer;
|
||||
- transformed and daemon-pushed agent timeline rows;
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -404,7 +401,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`, `@getpaseo/plugin/server/usage`, and `zod` to server code. Backend
|
||||
`@getpaseo/plugin/server/provider`, `@getpaseo/plugin/server/acp`, 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.
|
||||
|
||||
@@ -13,18 +13,15 @@ nav: 参考
|
||||
本地插件是安装到某个 Paseo daemon 中的目录来源。插件可以贡献:
|
||||
|
||||
- 为 Paseo 客户端添加 React Native 界面,以及侧边栏顶部和底部项;
|
||||
- 替换侧边栏列表的[侧边栏视图](/docs/plugins/sidebar-views),以及工作区行上的[徽标](#workspace-row-badge-items);
|
||||
- 作为工作区标签页打开的工作区面板和 Agent 面板;
|
||||
- 用于查看或编辑匹配文件的[文件面板](#file-panels);
|
||||
- Command Center 中的全局、工作区和 Agent 操作;
|
||||
- 消息 Composer 中的斜杠命令、[控件](#composer-items)、胶囊和可搜索的外部资源;
|
||||
- 工作区标题栏中的[按钮](#header-buttons),以及新建工作区界面上的[字段](#new-workspace-items);
|
||||
- [设置界面](#settings-screens),以及 **设置 → 外观** 中的浅色和深色主题;
|
||||
- 消息 Composer 中的斜杠命令;
|
||||
- 经过转换的、以及由 daemon 推送的 Agent 时间线行;
|
||||
- 在 daemon 旁运行、经过 schema 校验的 RPC 处理函数和事件流;
|
||||
- 修改或观察工作区、worktree 和 Agent 操作的[钩子](/docs/plugins/hooks);
|
||||
- [Agent Provider](/docs/plugins/providers)、[用量来源](#usage-sources)和 [worktree 管理器](#worktree-managers);
|
||||
- 通过 TypeScript SDK 执行的普通 Paseo 操作。
|
||||
- **设置 → 外观** 中的浅色和深色主题;
|
||||
- 在 daemon 旁运行、经过 schema 校验的 RPC 处理函数;
|
||||
- 通过 TypeScript SDK 执行的普通 Paseo 操作;
|
||||
- 消息 Composer 中可搜索的外部资源。
|
||||
|
||||
插件代码是受信任的,没有沙盒。客户端界面在 Paseo 应用中运行。后端贡献在一个子进程中运行,可以访问 daemon 所在的机器,包括它的文件、进程、凭据和网络。
|
||||
|
||||
@@ -352,7 +349,7 @@ openBrowser({ url, workspaceId: remoteWorkspaceId, serverId: remoteServerId });
|
||||
|
||||
### 服务端运行时 {#server-runtime}
|
||||
|
||||
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` 的插件不会启动子进程。
|
||||
Paseo 为服务端代码提供 `@getpaseo/plugin`、`@getpaseo/plugin/server`、`@getpaseo/plugin/server/provider`、`@getpaseo/plugin/server/acp` 和 `zod`。后端贡献在 daemon 子进程中运行,可以通过 Node 访问宿主机器。请把文件系统、进程、凭据以及其他本机工作放在 `server/` 下。没有 `index.server.ts` 的插件不会启动子进程。
|
||||
|
||||
### Provider {#providers}
|
||||
|
||||
|
||||
@@ -256,7 +256,6 @@ test("PR routing declares stable behavior ownership", () => {
|
||||
"packages/plugin/**",
|
||||
"plugin-examples/**",
|
||||
"public-docs/plugins/**",
|
||||
"skills/paseo-plugin/**",
|
||||
"packages/client/**",
|
||||
"packages/highlight/**",
|
||||
"packages/protocol/**",
|
||||
|
||||
+520
-295
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user