Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 7aaff3abcc feat(desktop): add automatic update modes and download progress
Give desktop users control over background updater network traffic with a persisted updates.mode setting (automatic, notify, off; default automatic).

Enforce off and notify behavior in the Electron main process as well as the renderer so automatic checks never leave the machine when opted out, quit-time installs only run in automatic mode, and explicit downloads stream live progress to both the OS window progress bar and the in-app UI.
2026-11-25 10:45:00 +01:00
78 changed files with 3818 additions and 3264 deletions
+207 -230
View File
@@ -5,26 +5,27 @@ import path from "node:path";
import { test, expect } from "../support/fixtures";
import {
addProjectFlow,
addProjectFlowHostTrigger,
addProjectFlowInput,
addProjectFlowSubmit,
chooseAddHostFromProjectFlow,
chooseAddProjectHost,
chooseAddProjectLocation,
chooseAddProjectTab,
expectAddProjectResultVisible,
expectAddProjectTab,
addProjectFlowBack,
addProjectFlowHost,
addProjectFlowInput,
addProjectFlowMethod,
chooseAddProjectMethod,
expectAddProjectPage,
expectNewWorkspaceForAddedProject,
expectAddProjectResultVisible,
navigateAddProjectResults,
navigateAndDismissAddProject,
openAddProjectFlow,
watchAddProjectRenderWarnings,
openAddProjectFlow,
openAddProjectHostSelection,
} from "../support/helpers/add-project-flow";
import { gotoAppShell } from "../support/helpers/app";
import {
addConnectedHostAndReload,
addOfflineHostAndReload,
disconnectAllHostsAndReload,
addConnectedHostAndReload,
addConnectedHostsAndReload,
addOfflineHostAndReload,
waitForConnectedHost,
} from "../support/helpers/hosts";
import {
@@ -35,8 +36,6 @@ import { expectOpenedProject } from "../support/helpers/project-picker-ui";
import { connectSeedClient } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
const MOD = process.platform === "darwin" ? "Meta" : "Control";
const SECONDARY_HOST_ID = "add-project-flow-secondary";
const SECONDARY_HOST_LABEL = "Secondary Host";
@@ -71,14 +70,13 @@ async function expectProjectHasNoWorkspaces(projectId: string): Promise<void> {
}
}
test.describe("Add project sheet", () => {
test.describe("Add Project command-center flow", () => {
test.describe.configure({ timeout: 180_000 });
test("Add host replaces the project sheet when no hosts are connected", async ({ page }) => {
test("Add host replaces the project dialog when no hosts are connected", async ({ page }) => {
await gotoAppShell(page);
await disconnectAllHostsAndReload(page);
await page.locator('[data-testid="sidebar-add-project"]:visible').click();
await expect(addProjectFlow(page)).toContainText("No connected hosts");
await openAddProjectHostSelection(page);
const originalUrl = page.url();
await chooseAddHostFromProjectFlow(page);
await expect(addProjectFlow(page)).toBeHidden();
@@ -88,36 +86,22 @@ test.describe("Add project sheet", () => {
await expect(page).toHaveURL(originalUrl);
});
test("opens on Existing, switches tabs with Mod+1/2/3, keeps each draft, and closes on Escape", async ({
test("method selection shows the daemon's available project sources without search", async ({
page,
}) => {
const renderWarnings = watchAddProjectRenderWarnings(page);
await gotoAppShell(page);
await openAddProjectFlow(page);
await page.keyboard.type("paseo");
await page.keyboard.press(`${MOD}+2`);
await expectAddProjectTab(page, "clone");
await expect(addProjectFlowInput(page)).toBeFocused();
await page.keyboard.type("getpaseo/");
await page.keyboard.press(`${MOD}+3`);
await expectAddProjectTab(page, "new-folder");
await expect(addProjectFlowSubmit(page)).toBeDisabled();
await page.keyboard.press(`${MOD}+1`);
await expectAddProjectTab(page, "existing");
await expect(addProjectFlowInput(page)).toHaveValue("paseo");
await chooseAddProjectTab(page, "clone");
await expect(addProjectFlowInput(page)).toHaveValue("getpaseo/");
await navigateAndDismissAddProject(page);
await expect(addProjectFlow(page)).not.toBeVisible();
expect(renderWarnings).toEqual([]);
await expect(addProjectFlowMethod(page, "directory-search")).toBeVisible();
await expect(addProjectFlowMethod(page, "github")).toContainText("Clone from GitHub");
await expect(addProjectFlowMethod(page, "new-directory")).toContainText("New directory");
await expect(addProjectFlowInput(page)).toHaveCount(0);
await expect(addProjectFlow(page).getByRole("textbox")).toHaveCount(0);
await expect(page.getByTestId("add-project-flow-page-host")).toHaveCount(0);
});
test("a single connected host shows no host picker, even with an offline host", async ({
page,
}) => {
test("an offline extra host neither appears nor forces host selection", async ({ page }) => {
await gotoAppShell(page);
await addOfflineHostAndReload(page, {
serverId: "add-project-flow-offline",
@@ -126,7 +110,8 @@ test.describe("Add project sheet", () => {
await openAddProjectFlow(page);
await expect(addProjectFlowHostTrigger(page)).toHaveCount(0);
await expect(addProjectFlowHost(page, "add-project-flow-offline")).toHaveCount(0);
await expect(addProjectFlowMethod(page, "directory-search")).toBeVisible();
});
test.describe("with two connected hosts", () => {
@@ -140,7 +125,73 @@ test.describe("Add project sheet", () => {
await secondaryHost?.close();
});
test("New folder creates a Project on the host chosen in the sheet", async ({ page }) => {
test("keyboard selection chooses the second host", async ({ page }) => {
await gotoAppShell(page);
await addConnectedHostAndReload(page, {
serverId: secondaryHost.serverId,
label: SECONDARY_HOST_LABEL,
port: secondaryHost.port,
});
await waitForConnectedHost(page, {
serverId: SECONDARY_HOST_ID,
endpoint: `localhost:${secondaryHost.port}`,
});
await openAddProjectHostSelection(page);
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "method");
await expect(addProjectFlow(page)).toContainText(SECONDARY_HOST_LABEL);
});
test("Escape and Back restore searchable page input before closing at the root", async ({
page,
}) => {
const renderWarnings = watchAddProjectRenderWarnings(page);
await gotoAppShell(page);
await addConnectedHostAndReload(page, {
serverId: secondaryHost.serverId,
label: SECONDARY_HOST_LABEL,
port: secondaryHost.port,
});
await waitForConnectedHost(page, {
serverId: SECONDARY_HOST_ID,
endpoint: `localhost:${secondaryHost.port}`,
});
await openAddProjectHostSelection(page);
await addProjectFlowInput(page).fill("o");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "method");
await chooseAddProjectMethod(page, "new-directory");
await expectAddProjectPage(page, "new-directory-parent");
await page.keyboard.press("Escape");
await expectAddProjectPage(page, "method");
await expect(addProjectFlowInput(page)).toHaveCount(0);
await chooseAddProjectMethod(page, "new-directory");
await expectAddProjectPage(page, "new-directory-parent");
await addProjectFlowBack(page).click();
await expectAddProjectPage(page, "method");
await addProjectFlowBack(page).click();
await expectAddProjectPage(page, "host");
await expect(addProjectFlowInput(page)).toHaveValue("o");
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "method");
await expect(addProjectFlow(page)).toContainText(SECONDARY_HOST_LABEL);
await page.keyboard.press("Escape");
await expectAddProjectPage(page, "host");
await navigateAndDismissAddProject(page);
await expect(addProjectFlow(page)).not.toBeVisible();
expect(renderWarnings).toEqual([]);
});
test("New directory creates a Project on the selected remote host", async ({ page }) => {
const parentDirectory = await mkdtemp(path.join(tmpdir(), "paseo-e2e-remote-project-"));
const directoryName = `remote-${randomUUID().slice(0, 8)}`;
const directoryPath = path.join(parentDirectory, directoryName);
@@ -156,15 +207,18 @@ test.describe("Add project sheet", () => {
serverId: SECONDARY_HOST_ID,
endpoint: `localhost:${secondaryHost.port}`,
});
await openAddProjectFlow(page);
await chooseAddProjectTab(page, "new-folder");
await addProjectFlowInput(page).fill(directoryName);
await openAddProjectHostSelection(page);
await addProjectFlowHost(page, SECONDARY_HOST_ID).click();
await expectAddProjectPage(page, "method");
await chooseAddProjectHost(page, SECONDARY_HOST_ID);
await expect(addProjectFlowHostTrigger(page)).toContainText(SECONDARY_HOST_LABEL);
await expect(addProjectFlowInput(page)).toHaveValue(directoryName);
await chooseAddProjectLocation(page, parentDirectory);
await addProjectFlowInput(page).focus();
await expect(addProjectFlowMethod(page, "new-directory")).toContainText(
`Create an empty directory on ${SECONDARY_HOST_LABEL}`,
);
await chooseAddProjectMethod(page, "new-directory");
await addProjectFlowInput(page).fill(parentDirectory);
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "new-directory-name");
await page.keyboard.type(directoryName);
await page.keyboard.press("Enter");
const projectId = await expectOpenedProject(page, directoryName);
@@ -182,35 +236,57 @@ test.describe("Add project sheet", () => {
});
});
test("a host that disconnects keeps its draft and blocks submit instead of moving it", async ({
page,
}) => {
const droppingHost = await startIsolatedHostDaemon("add-project-flow-dropping");
test("filtered hosts keep the keyboard-selected row visible", async ({ page }) => {
const hosts: IsolatedHostDaemon[] = [];
try {
for (let index = 1; index <= 3; index += 1) {
hosts.push(await startIsolatedHostDaemon(`scroll-host-${index}`));
}
await page.setViewportSize({ width: 1280, height: 360 });
await gotoAppShell(page);
await addConnectedHostAndReload(page, {
serverId: droppingHost.serverId,
label: "Dropping Host",
port: droppingHost.port,
});
await waitForConnectedHost(page, {
serverId: droppingHost.serverId,
endpoint: `localhost:${droppingHost.port}`,
});
await openAddProjectFlow(page);
await chooseAddProjectHost(page, droppingHost.serverId);
await addProjectFlowInput(page).fill(homedir());
await droppingHost.close();
await expect(page.getByTestId("add-project-flow-error")).toHaveText(
"Dropping Host is offline",
{ timeout: 30_000 },
await addConnectedHostsAndReload(
page,
hosts.map((host, index) => ({
serverId: host.serverId,
port: host.port,
label: index < 2 ? `Fleet 0${index + 1}` : "Other host",
})),
{ primaryLabel: "Fleet 00" },
);
await expect(addProjectFlowHostTrigger(page)).toContainText("Dropping Host");
await expect(addProjectFlowInput(page)).toHaveValue(homedir());
await expect(addProjectFlowSubmit(page)).toBeDisabled();
for (const host of hosts) {
await waitForConnectedHost(page, {
serverId: host.serverId,
endpoint: `localhost:${host.port}`,
});
}
await openAddProjectHostSelection(page);
await expect(
addProjectFlow(page).getByRole("button").filter({ hasText: "Other host" }),
).toBeVisible();
await addProjectFlowInput(page).fill("Fleet");
await expect(addProjectFlowHost(page, hosts[2]!.serverId)).toHaveCount(0);
await navigateAddProjectResults(page, "ArrowDown", 2);
await expectAddProjectResultVisible(page, "Fleet 02");
// Filtering out the first host moves retained rows to new positions.
await addProjectFlowInput(page).fill("scroll-host");
await expect(addProjectFlowHost(page, getServerId())).toHaveCount(0);
await expectAddProjectResultVisible(page, "Fleet 01");
await navigateAddProjectResults(page, "ArrowDown", 2);
await expectAddProjectResultVisible(page, "Other host");
await navigateAddProjectResults(page, "ArrowDown", 1);
await expectAddProjectResultVisible(page, "Fleet 01");
await addProjectFlowInput(page).fill("Fleet");
await expectAddProjectResultVisible(page, "Fleet 00");
await navigateAddProjectResults(page, "ArrowDown", 2);
await expectAddProjectResultVisible(page, "Fleet 02");
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "method");
await expect(addProjectFlow(page)).toContainText("Fleet 02");
} finally {
await droppingHost.close();
await Promise.all(hosts.map((host) => host.close()));
}
});
@@ -221,6 +297,9 @@ test.describe("Add project sheet", () => {
await gotoAppShell(page);
await openAddProjectFlow(page);
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "directory-search");
await expect(addProjectFlowInput(page)).toBeFocused();
await page.keyboard.type(projectPickerFixture.fuzzyQuery);
await expect(addProjectFlow(page)).toContainText(projectPickerFixture.projectName, {
timeout: 30_000,
@@ -244,32 +323,45 @@ test.describe("Add project sheet", () => {
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-scroll-"));
const rowPath = (index: number) =>
path.join(parentDirectory, `scroll-probe-${String(index).padStart(2, "0")}`);
const rowName = (index: number) => path.basename(rowPath(index));
let projectId: string | null = null;
try {
await Promise.all(Array.from({ length: 16 }, (_, index) => mkdir(rowPath(index))));
await gotoAppShell(page);
await openAddProjectFlow(page);
await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}/scroll-probe`);
await chooseAddProjectMethod(page, "directory-search");
await addProjectFlowInput(page).fill(path.basename(parentDirectory));
const results = page.getByTestId("add-project-flow-results");
await expect(results.getByRole("button", { name: /scroll-probe-/ })).toHaveCount(16, {
timeout: 30_000,
});
await navigateAddProjectResults(page, "ArrowDown", 11);
await expectAddProjectResultVisible(page, rowName(11));
await navigateAddProjectResults(page, "ArrowDown", 12);
await expectAddProjectResultVisible(page, rowPath(11));
await navigateAddProjectResults(page, "ArrowUp", 12);
await expectAddProjectResultVisible(page, rowName(15));
await expectAddProjectResultVisible(page, parentDirectory);
await navigateAddProjectResults(page, "ArrowUp", 1);
await expectAddProjectResultVisible(page, rowPath(15));
await navigateAddProjectResults(page, "ArrowDown", 1);
await expectAddProjectResultVisible(page, rowName(0));
await expectAddProjectResultVisible(page, parentDirectory);
await navigateAddProjectResults(page, "ArrowDown", 11);
await navigateAddProjectResults(page, "ArrowDown", 12);
await expectAddProjectResultVisible(page, rowPath(11));
await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}probe`);
await expect(results.getByRole("button")).toHaveCount(16);
await expectAddProjectResultVisible(page, rowPath(0));
await navigateAddProjectResults(page, "ArrowDown", 12);
await expectAddProjectResultVisible(page, rowPath(12));
await addProjectFlowInput(page).fill(path.basename(parentDirectory));
await expect(results.getByRole("button")).toHaveCount(17);
await expectAddProjectResultVisible(page, parentDirectory);
await navigateAddProjectResults(page, "ArrowDown", 12);
await expectAddProjectResultVisible(page, rowPath(11));
await page.keyboard.press("Enter");
projectId = await expectOpenedProject(page, rowName(11));
projectId = await expectOpenedProject(page, "scroll-probe-11");
await expectNewWorkspaceForAddedProject(page, {
serverId: getServerId(),
projectId,
projectName: rowName(11),
projectName: "scroll-probe-11",
projectPath: rowPath(11),
});
} finally {
@@ -278,146 +370,28 @@ test.describe("Add project sheet", () => {
}
});
test("Enter on a focused result adds that folder, not the one picked before", async ({
page,
}) => {
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-focus-"));
const firstPath = path.join(parentDirectory, "focus-probe-a");
const secondPath = path.join(parentDirectory, "focus-probe-b");
let projectId: string | null = null;
try {
await Promise.all([mkdir(firstPath), mkdir(secondPath)]);
await gotoAppShell(page);
await openAddProjectFlow(page);
await addProjectFlowInput(page).fill(`${path.basename(parentDirectory)}/focus-probe`);
const results = page.getByTestId("add-project-flow-results");
await expect(results.getByRole("button", { name: /focus-probe-/ })).toHaveCount(2, {
timeout: 30_000,
});
await results.getByRole("button", { name: /focus-probe-b/ }).focus();
await page.keyboard.press("Enter");
projectId = await expectOpenedProject(page, "focus-probe-b");
await expectNewWorkspaceForAddedProject(page, {
serverId: getServerId(),
projectId,
projectName: "focus-probe-b",
projectPath: secondPath,
});
} finally {
if (projectId) await removeCreatedProject(secondPath, projectId);
await rm(parentDirectory, { recursive: true, force: true });
}
});
test("Enter while a new search runs does not open a row from the previous search", async ({
page,
}) => {
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-stale-"));
try {
await mkdir(path.join(parentDirectory, "stale-probe-a"));
await gotoAppShell(page);
await openAddProjectFlow(page);
const prefix = path.basename(parentDirectory);
await addProjectFlowInput(page).fill(`${prefix}/stale-probe`);
const results = page.getByTestId("add-project-flow-results");
await expect(results.getByRole("button", { name: /stale-probe-a/ })).toBeVisible({
timeout: 30_000,
});
await addProjectFlowInput(page).fill(`${prefix}/no-such-folder`);
await page.keyboard.press("Enter");
await expect(addProjectFlow(page).getByText("No matching folders")).toBeVisible({
timeout: 30_000,
});
await expect(addProjectFlow(page)).toBeVisible();
await expect(addProjectFlowSubmit(page)).toBeDisabled();
} finally {
await rm(parentDirectory, { recursive: true, force: true });
}
});
test("a complete repository URL is cloneable without a GitHub search result", async ({
test("a complete repository URL remains selectable without a GitHub search result", async ({
page,
}) => {
await gotoAppShell(page);
await openAddProjectFlow(page);
await chooseAddProjectTab(page, "clone");
await chooseAddProjectMethod(page, "github");
const remote = "https://github.invalid/acme/manual.git";
await addProjectFlowInput(page).fill(remote);
await expect(addProjectFlow(page).getByText("manual", { exact: true })).toBeVisible();
await expect(page.getByTestId("add-project-flow-location")).toContainText("/manual");
await expect(addProjectFlowSubmit(page)).toBeEnabled();
});
test("Enter activates a focused button instead of the primary action", async ({ page }) => {
await gotoAppShell(page);
await openAddProjectFlow(page);
await chooseAddProjectTab(page, "clone");
await addProjectFlowInput(page).fill("https://github.invalid/acme/manual.git");
await expect(addProjectFlowSubmit(page)).toBeEnabled();
await addProjectFlow(page).getByRole("button", { name: "Close", exact: true }).focus();
await page.keyboard.press("Enter");
await expect(addProjectFlow(page)).toBeHidden();
await expectAddProjectPage(page, "github-location");
const title = addProjectFlow(page).getByTestId("add-project-flow-title");
await expect(title.getByText("Choose destination", { exact: true })).toBeVisible();
await expect(title.getByText("localhost", { exact: true })).toBeVisible();
await expect(title).not.toContainText("Where should Paseo create");
await addProjectFlowBack(page).click();
await expect(addProjectFlowInput(page)).toHaveValue(remote);
});
test("a row picked during a search is not replaced by the answer's first row", async ({
page,
}) => {
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-dropped-pick-"));
try {
await Promise.all([
mkdir(path.join(parentDirectory, "previous-probe")),
mkdir(path.join(parentDirectory, "incoming-probe")),
]);
await gotoAppShell(page);
await openAddProjectFlow(page);
const prefix = path.basename(parentDirectory);
const results = page.getByTestId("add-project-flow-results");
await addProjectFlowInput(page).fill(`${prefix}/previous-probe`);
await expect(results.getByRole("button", { name: /previous-probe/ })).toBeVisible({
timeout: 30_000,
});
await addProjectFlowInput(page).fill(`${prefix}/incoming-probe`);
await page.keyboard.press("ArrowDown");
await expect(results.getByRole("button", { name: /incoming-probe/ })).toBeVisible({
timeout: 30_000,
});
await expect(addProjectFlowSubmit(page)).toBeDisabled();
} finally {
await rm(parentDirectory, { recursive: true, force: true });
}
});
test("Enter in Location while a new search runs keeps the current location", async ({ page }) => {
const parentDirectory = await mkdtemp(path.join(homedir(), "paseo-e2e-stale-location-"));
try {
await mkdir(path.join(parentDirectory, "stale-probe-a"));
await gotoAppShell(page);
await openAddProjectFlow(page);
await chooseAddProjectTab(page, "new-folder");
const location = page.getByTestId("add-project-flow-location");
const locationBefore = await location.textContent();
await location.click();
const search = page.getByPlaceholder("Search folders or enter a path").last();
const prefix = path.basename(parentDirectory);
await search.fill(`${prefix}/stale-probe`);
await expect(page.getByText(/stale-probe-a/).last()).toBeVisible({ timeout: 30_000 });
await search.fill(`${prefix}/no-such-folder`);
await page.keyboard.press("Enter");
await expect(page.getByText("No matching folders")).toBeVisible({ timeout: 30_000 });
await expect(search).toBeVisible();
await expect(location).toHaveText(locationBefore ?? "");
} finally {
await rm(parentDirectory, { recursive: true, force: true });
}
});
test("New folder validates the name, then creates a Project in the chosen location", async ({
test("New directory validates the name, restores parent and name state, then creates a Project", async ({
page,
}) => {
const parentDirectory = await mkdtemp(path.join(tmpdir(), "paseo-e2e-new-project-"));
@@ -428,23 +402,27 @@ test.describe("Add project sheet", () => {
try {
await gotoAppShell(page);
await openAddProjectFlow(page);
await chooseAddProjectTab(page, "new-folder");
await chooseAddProjectLocation(page, parentDirectory);
await chooseAddProjectMethod(page, "new-directory");
await addProjectFlowInput(page).fill("../invalid");
const nameError = page.getByTestId("add-project-flow-name-field-error");
await expect(nameError).toHaveText("Use a name without slashes");
await expect(addProjectFlowSubmit(page)).toBeDisabled();
await page.keyboard.type(parentDirectory);
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "new-directory-name");
await page.keyboard.type("../invalid");
await page.keyboard.press("Enter");
await addProjectFlowInput(page).fill("C:repo");
await expect(nameError).toHaveText("Use a name without a drive letter");
await expect(addProjectFlowSubmit(page)).toBeDisabled();
const error = page.getByTestId("add-project-flow-error");
await expect(error).toBeVisible();
await expect(error).toContainText(/name|separator|directory/i);
await expectAddProjectPage(page, "new-directory-name");
await addProjectFlowInput(page).fill(directoryName);
await expect(nameError).toBeHidden();
await expect(addProjectFlowSubmit(page)).toBeEnabled();
await expect(page.getByTestId("add-project-flow-location")).toContainText(directoryName);
await addProjectFlowSubmit(page).click();
await addProjectFlowBack(page).click();
await expectAddProjectPage(page, "new-directory-parent");
await expect(addProjectFlowInput(page)).toHaveValue(parentDirectory);
await page.keyboard.press("Enter");
await expectAddProjectPage(page, "new-directory-name");
await expect(addProjectFlowInput(page)).toHaveValue(directoryName);
await page.keyboard.press("Enter");
projectId = await expectOpenedProject(page, directoryName);
await expectNewWorkspaceForAddedProject(page, {
@@ -483,11 +461,10 @@ test.describe("Compact Add project context", () => {
await gotoAppShell(page);
await page.getByRole("button", { name: "Open menu", exact: true }).click();
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "directory-search");
await addProjectFlowInput(page).fill(projectPickerFixture.fuzzyQuery);
await expect(
page.getByRole("button", { name: new RegExp(projectPickerFixture.projectName) }).first(),
).toBeVisible({ timeout: 30_000 });
await addProjectFlowSubmit(page).click();
await expect(addProjectFlow(page)).toContainText(projectPickerFixture.projectName);
await page.keyboard.press("Enter");
const projectId = await expectOpenedProject(page, projectPickerFixture.projectName);
projectPickerFixture.rememberProjectId(projectId);
await expectNewWorkspaceForAddedProject(page, {
@@ -4,9 +4,10 @@ import path from "node:path";
import { expect, test } from "../support/fixtures";
import {
addProjectFlow,
addProjectFlowBack,
addProjectFlowInput,
chooseAddProjectLocation,
chooseAddProjectTab,
chooseAddProjectMethod,
expectAddProjectPage,
expectNewWorkspaceForAddedProject,
openAddProjectFlow,
} from "../support/helpers/add-project-flow";
@@ -38,22 +39,28 @@ test.describe("Add Project GitHub flow", () => {
await gotoAppShell(page);
await openAddProjectFlow(page);
await chooseAddProjectTab(page, "clone");
await chooseAddProjectMethod(page, "github");
await addProjectFlowInput(page).fill("getpaseo/paseo");
await expect(addProjectFlow(page).getByText("getpaseo/paseo", { exact: true })).toBeVisible({
timeout: 30_000,
});
await addProjectFlowInput(page).fill(repository.fullName);
await addProjectFlowInput(page).fill("");
const repositoryRow = addProjectFlow(page).getByText(repository.fullName, { exact: true });
await expect(repositoryRow).toBeVisible({ timeout: 30_000 });
await repositoryRow.click();
await chooseAddProjectLocation(page, parentDirectory);
await expect(page.getByTestId("add-project-flow-location")).toContainText(
path.join(path.basename(parentDirectory), repository.name),
);
await addProjectFlowInput(page).focus();
await expectAddProjectPage(page, "github-location");
await addProjectFlowInput(page).fill(parentDirectory);
await expect(addProjectFlow(page)).toContainText(checkoutPath, { timeout: 30_000 });
await addProjectFlowBack(page).click();
await expectAddProjectPage(page, "github-search");
await expect(repositoryRow).toBeVisible();
await repositoryRow.click();
await expectAddProjectPage(page, "github-location");
await expect(addProjectFlowInput(page)).toHaveValue(parentDirectory);
await mkdir(checkoutPath);
await page.keyboard.press("Enter");
@@ -11,20 +11,13 @@ import {
expectModelRowProfileActionBesideRow,
expectModelRowSelected,
expectProfileEditIsPencilOnly,
expectProfileReachableByScrolling,
expectProfileSearchResult,
expectProfileVisibleForProvider,
openModelPicker,
openAgentProfilesFromEmptyPrompt,
searchModelPicker,
seedAgentProfiles,
selectModelRow,
} from "../support/helpers/agent-profiles";
import {
chooseCommandCenterAgentControl,
expectWorkspaceAgentConfiguration,
openCommandCenterForAgent,
} from "../support/helpers/command-center-agent-controls";
import { expectWorkspaceAgentConfiguration } from "../support/helpers/command-center-agent-controls";
import { expectComposerVisible } from "../support/helpers/composer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
@@ -155,83 +148,4 @@ test.describe("Agent profiles in the model picker", () => {
await seed.restore();
}
});
test("a profile is found by searching the model picker or the command center", async ({
page,
}) => {
const seed = await seedAgentProfiles([PROFILE]);
const workspace = await seedMockAgentWorkspace({
repoPrefix: "agent-profiles-search-",
title: "Agent profiles search",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await test.step("searching its name in the model picker lists only the profile", async () => {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await openModelPicker(page);
await searchModelPicker(page, "ui work");
await expectProfileSearchResult(page, { name: PROFILE.name });
});
await test.step("searching its model lists the profile above the model", async () => {
await searchModelPicker(page, "one minute");
await expectProfileSearchResult(page, {
name: PROFILE.name,
model: { provider: "mock", modelId: "one-minute-stream" },
});
await closeModelPicker(page);
});
await test.step("choosing it from the command center applies it", async () => {
await openCommandCenterForAgent(page, workspace);
await chooseCommandCenterAgentControl({
page,
query: "ui work",
choice: `Profile › ${PROFILE.name}`,
});
await expectComposerModel(page, "One minute stream");
await expectComposerMode(page, "Approval test");
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "one-minute-stream",
modeId: "approval-test",
});
});
} finally {
await workspace.cleanup();
await seed.restore();
}
});
test("profile-only search results scroll inside the picker", async ({ page }) => {
const profiles = Array.from({ length: 12 }, (_, index) => ({
id: `agent_profile_e2e_release_${index + 1}`,
name: `Release review ${String(index + 1).padStart(2, "0")}`,
provider: "mock",
model: "one-minute-stream",
}));
const seed = await seedAgentProfiles(profiles);
const workspace = await seedMockAgentWorkspace({
repoPrefix: "agent-profiles-search-scroll-",
title: "Agent profiles search scroll",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await openModelPicker(page);
await searchModelPicker(page, "release review");
await expectProfileSearchResult(page, { name: "Release review 01" });
await expectProfileReachableByScrolling(page, "Release review 12");
} finally {
await workspace.cleanup();
await seed.restore();
}
});
});
@@ -4,7 +4,7 @@ import { test, expect, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import {
addProjectFlowInput,
addProjectFlowSubmit,
chooseAddProjectMethod,
openAddProjectFlow,
} from "../support/helpers/add-project-flow";
import { expectOpenedProject } from "../support/helpers/project-picker-ui";
@@ -53,6 +53,7 @@ async function removeProjectFromSidebar(page: Page, projectViewKey: string): Pro
async function addProjectFromPicker(page: Page, projectPath: string): Promise<string> {
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "directory-search");
const input = addProjectFlowInput(page);
await input.fill(projectPath);
@@ -84,6 +85,7 @@ test.describe("Project picker search", () => {
await gotoAppShell(page);
await waitForSidebarProjectListReady(page);
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "directory-search");
const input = addProjectFlowInput(page);
await input.fill(projectPickerFixture.fuzzyQuery);
@@ -91,7 +93,6 @@ test.describe("Project picker search", () => {
const suggestion = page.getByText(projectPickerFixture.projectName, { exact: false }).first();
await expect(suggestion).toBeVisible({ timeout: 30_000 });
await suggestion.click();
await addProjectFlowSubmit(page).click();
const projectId = await expectOpenedProject(page, projectPickerFixture.projectName);
projectPickerFixture.rememberProjectId(projectId);
@@ -103,11 +104,13 @@ test.describe("Project picker search", () => {
await gotoAppShell(page);
await waitForSidebarProjectListReady(page);
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "directory-search");
const input = addProjectFlowInput(page);
await input.fill("paseo-loading-state-no-match");
await expect(page.getByText("Searching...", { exact: true })).toBeVisible();
await expect(page.getByText("Start typing a path", { exact: true })).toHaveCount(0);
await expect(page.getByText("Loading...", { exact: true })).toBeVisible();
});
});
@@ -55,7 +55,7 @@ import {
import { getServerId } from "../support/helpers/server-id";
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
import { expectAddProjectTab } from "../support/helpers/add-project-flow";
import { chooseAddProjectMethod, expectAddProjectPage } from "../support/helpers/add-project-flow";
import { seedSavedSettingsHosts } from "../support/helpers/settings";
import {
expectSidebarWorkspaceSelected,
@@ -291,7 +291,8 @@ test.describe("New workspace flow", () => {
await expect(addProject).toContainText(/(?:⌘|Ctrl\+)O/);
await addProject.click();
await expectAddProjectTab(page, "existing");
await expectAddProjectPage(page, "method");
await chooseAddProjectMethod(page, "directory-search");
} finally {
await repo.cleanup();
}
@@ -46,7 +46,11 @@ import {
} from "../support/helpers/project-settings";
import { gotoAppShell } from "../support/helpers/app";
import { openCompactSettings } from "../support/helpers/settings";
import { addProjectFlowInput, openAddProjectFlow } from "../support/helpers/add-project-flow";
import {
addProjectFlowInput,
chooseAddProjectMethod,
openAddProjectFlow,
} from "../support/helpers/add-project-flow";
import { createTempGitRepo } from "../support/helpers/workspace";
import {
buildOpenProjectRoute,
@@ -163,6 +167,7 @@ async function readProjectConfigFile(project: ProjectsSettingsProject): Promise<
async function addProjectFromSidebar(page: Page, projectPath: string): Promise<string> {
await openAddProjectFlow(page);
await chooseAddProjectMethod(page, "directory-search");
const input = addProjectFlowInput(page);
await input.fill(projectPath);
@@ -1,61 +1,73 @@
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
export type AddProjectTab = "existing" | "clone" | "new-folder";
export type AddProjectFlowPage =
| "host"
| "method"
| "directory-search"
| "github-search"
| "github-location"
| "new-directory-parent"
| "new-directory-name";
export type AddProjectMethod = "directory-search" | "browse" | "github" | "new-directory";
const METHOD_DESTINATIONS: Record<Exclude<AddProjectMethod, "browse">, AddProjectFlowPage> = {
"directory-search": "directory-search",
github: "github-search",
"new-directory": "new-directory-parent",
};
export function addProjectFlow(page: Page): Locator {
return page.getByTestId("add-project-flow");
}
/** The current tab's search or name field. */
export function addProjectFlowInput(page: Page): Locator {
return page.getByTestId("add-project-flow-input");
}
export function addProjectFlowTab(page: Page, tab: AddProjectTab): Locator {
return page.getByTestId(`add-project-flow-tab-${tab}`);
export function addProjectFlowBack(page: Page): Locator {
return page.getByTestId("add-project-flow-back");
}
export function addProjectFlowSubmit(page: Page): Locator {
return page.getByTestId("add-project-flow-submit");
export function addProjectFlowHost(page: Page, serverId: string): Locator {
return page.getByTestId(`add-project-flow-host-${serverId}`);
}
export function addProjectFlowHostTrigger(page: Page): Locator {
return page.getByTestId("add-project-flow-host-trigger");
export function addProjectFlowMethod(page: Page, method: AddProjectMethod): Locator {
return page.getByTestId(`add-project-flow-method-${method}`);
}
export async function expectAddProjectTab(page: Page, tab: AddProjectTab): Promise<void> {
await expect(addProjectFlowTab(page, tab)).toHaveAttribute("aria-selected", "true", {
timeout: 30_000,
});
export async function expectAddProjectPage(page: Page, kind: AddProjectFlowPage): Promise<Locator> {
const currentPage = page.getByTestId(`add-project-flow-page-${kind}`);
await expect(currentPage).toBeVisible({ timeout: 30_000 });
return currentPage;
}
/** Opens Add project from the sidebar; it starts on Existing with the search focused. */
export async function openAddProjectFlow(page: Page): Promise<void> {
async function openAddProjectFlowSurface(
page: Page,
expectedPage: "host" | "method",
): Promise<void> {
await page.locator('[data-testid="sidebar-add-project"]:visible').click();
await expect(addProjectFlow(page)).toBeVisible({ timeout: 30_000 });
await expectAddProjectTab(page, "existing");
await expectAddProjectPage(page, expectedPage);
}
export async function openAddProjectFlow(page: Page): Promise<void> {
await openAddProjectFlowSurface(page, "method");
}
export async function openAddProjectHostSelection(page: Page): Promise<void> {
await openAddProjectFlowSurface(page, "host");
await expect(addProjectFlowInput(page)).toBeFocused();
}
export async function chooseAddProjectTab(page: Page, tab: AddProjectTab): Promise<void> {
await addProjectFlowTab(page, tab).click();
await expectAddProjectTab(page, tab);
}
export async function chooseAddProjectHost(page: Page, serverId: string): Promise<void> {
await addProjectFlowHostTrigger(page).click();
await page.getByTestId(`add-project-flow-host-${serverId}`).click();
}
/** Types a parent directory into the Location picker and uses it as typed. */
export async function chooseAddProjectLocation(page: Page, location: string): Promise<void> {
await page.getByTestId("add-project-flow-location").click();
await page.getByPlaceholder("Search folders or enter a path").last().fill(location);
await page.getByText("Use this folder", { exact: true }).click();
await expect(page.getByTestId("add-project-flow-location")).toContainText(
path.basename(location),
);
export async function chooseAddProjectMethod(page: Page, method: AddProjectMethod): Promise<void> {
const option = addProjectFlowMethod(page, method);
await expect(option).toBeVisible();
await option.click();
if (method !== "browse") {
await expectAddProjectPage(page, METHOD_DESTINATIONS[method]);
}
}
export async function expectNewWorkspaceForAddedProject(
@@ -102,10 +114,8 @@ export async function expectAddProjectResultVisible(page: Page, text: string): P
.toBe(true);
}
/** Presses Enter on the focused Add host button, which the sheet's own Enter must not swallow. */
export async function chooseAddHostFromProjectFlow(page: Page): Promise<void> {
await addProjectFlow(page).getByRole("button", { name: "Add host", exact: true }).focus();
await page.keyboard.press("Enter");
await page.getByRole("button", { name: /Add host.*No connected hosts/ }).click();
}
export async function navigateAndDismissAddProject(page: Page): Promise<void> {
@@ -449,41 +449,6 @@ async function boxTop(locator: Locator): Promise<number> {
return box.y;
}
export async function searchModelPicker(page: Page, query: string): Promise<void> {
await pickerViewport(page).getByTestId("model-search-input").fill(query);
}
/** A search lists matching profiles first, then the matching models under their own heading. */
export async function expectProfileSearchResult(
page: Page,
input: { name: string; model?: { provider: string; modelId: string } },
): Promise<void> {
const viewport = pickerViewport(page);
const row = profilePickerRow(page, input.name);
await expect(row).toBeVisible({ timeout: 30_000 });
if (!input.model) {
await expect(viewport.getByText("Models", { exact: true })).toHaveCount(0);
return;
}
const matchedModel = modelRow(page, input.model);
await expect(viewport.getByText("Models", { exact: true })).toBeVisible();
await expect(matchedModel).toBeVisible();
expect(await boxTop(row)).toBeLessThan(await boxTop(matchedModel));
}
/** Wheel-scrolls the picker the way a pointer user would until the profile row is on screen. */
export async function expectProfileReachableByScrolling(page: Page, name: string): Promise<void> {
const row = profilePickerRow(page, name);
await expect(row).toBeAttached({ timeout: 30_000 });
const box = await pickerViewport(page).boundingBox();
if (!box) throw new Error("model picker has no layout box");
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await expect(async () => {
await page.mouse.wheel(0, 400);
await expect(row).toBeInViewport({ timeout: 500 });
}).toPass({ timeout: 15_000 });
}
export async function applyProfileFromPicker(page: Page, name: string): Promise<void> {
await profilePickerRow(page, name).click();
await expect(pickerViewport(page)).toHaveCount(0, { timeout: 30_000 });
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { expect, type Locator, type Page } from "@playwright/test";
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client";
import { addProjectFlow, addProjectFlowInput, expectAddProjectTab } from "./add-project-flow";
import { addProjectFlow, addProjectFlowInput, chooseAddProjectMethod } from "./add-project-flow";
import { connectDaemonClient } from "./daemon-client-loader";
import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry";
import { startIsolatedHostDaemon, type IsolatedHostDaemonOptions } from "./isolated-host-daemon";
@@ -122,7 +122,7 @@ export async function skipSetup(page: Page): Promise<void> {
export async function addProjectFromSetup(page: Page, projectPath: string): Promise<void> {
await setupModal(page).getByRole("button", { name: "Add project", exact: true }).click();
await expect(addProjectFlow(page)).toBeVisible({ timeout: 30_000 });
await expectAddProjectTab(page, "existing");
await chooseAddProjectMethod(page, "directory-search");
await addProjectFlowInput(page).fill(projectPath);
await page.keyboard.press("Enter");
await expect(addProjectFlow(page)).toHaveCount(0, { timeout: 30_000 });
@@ -1,204 +0,0 @@
import { useMemo } from "react";
import { View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { GitHubIcon } from "@/components/icons/github-icon";
import { FormTextInput } from "@/components/ui/form-field";
import { isWeb } from "@/constants/platform";
import type { Theme } from "@/styles/theme";
import { ICON_SIZE } from "@/styles/theme";
import type { AddProjectActions } from "./use-add-project-actions";
import type { AddProjectFlowState, AddProjectHost, GithubRepositoryChoice } from "./model";
import { LocationField } from "./location-field";
import {
buildManualGithubRepositoryChoices,
checkoutName,
joinDirectoryPath,
MANUAL_CHOICE_PREFIX,
} from "./options";
import { ResultList, type ResultRow } from "./result-list";
import { RESULTS_TEST_ID } from "./result-list-id";
import { useGithubRepositorySearch } from "./searches";
import { resolveActiveIndex, type AddProjectTabView } from "./tab-view";
const ThemedGitHubIcon = withUnistyles(GitHubIcon);
const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const githubIcon = <ThemedGitHubIcon size={ICON_SIZE.md} uniProps={mutedColor} />;
/**
* The project the query names comes first: the search result that matches it exactly, or else
* the pasted URL or owner/repo as typed.
*/
function buildCloneChoices(
query: string,
found: GithubRepositoryChoice[],
): GithubRepositoryChoice[] {
const normalized = query.trim().toLowerCase();
const isExact = (repository: GithubRepositoryChoice) =>
repository.nameWithOwner.toLowerCase() === normalized ||
repository.cloneUrl.toLowerCase() === normalized;
const exact = found.filter(isExact);
if (exact.length === 0) return [...buildManualGithubRepositoryChoices(query), ...found];
return [...exact, ...found.filter((repository) => !isExact(repository))];
}
/** A choice built from the typed URL or owner/repo rather than from a search answer. */
function isTypedChoice(choice: GithubRepositoryChoice | undefined): boolean {
return choice?.id.startsWith(MANUAL_CHOICE_PREFIX) === true;
}
function cloneEmptyText(host: AddProjectHost, query: string): string {
if (!host.canSearchGithubRepositories) return "Paste a Git URL or owner/repo";
return query.trim() ? "No matching projects" : "Search GitHub or paste a Git URL";
}
export interface CloneTabView extends AddProjectTabView {
location: string;
destination: string;
}
const CLONE_UNAVAILABLE = "Update the host to clone projects";
export function useCloneTab(input: {
state: AddProjectFlowState;
host: AddProjectHost | null;
defaultLocation: string;
actions: AddProjectActions;
}): CloneTabView {
const { state, host, defaultLocation, actions } = input;
const { query } = state.clone;
const canClone = host?.canCloneGithubRepositories === true;
const search = useGithubRepositorySearch({
hostId: state.hostId,
query,
enabled: state.tab === "clone" && canClone && host?.canSearchGithubRepositories === true,
});
const choices = useMemo(
() => (canClone ? buildCloneChoices(query, search.items) : []),
[canClone, query, search.items],
);
const rows = useMemo<ResultRow[]>(
() =>
choices.map((repository) => ({
id: repository.id,
title: repository.cloneProtocol
? `${repository.nameWithOwner} via ${repository.cloneProtocol.toUpperCase()}`
: repository.nameWithOwner,
subtitle: repository.description,
icon: GitHubIcon,
testID: `add-project-flow-repository-${repository.id}`,
})),
[choices],
);
// While the search for new text runs, the rows on screen answer the old text. None of them is
// picked until the new answer arrives or the user picks one, unless it is the typed URL.
const awaitingRows =
search.pending && state.clone.selectedId === null && !isTypedChoice(choices[0]);
const activeIndex = awaitingRows ? -1 : resolveActiveIndex(rows, state.clone.selectedId);
const repository = choices[activeIndex] ?? null;
const location = state.clone.location ?? defaultLocation;
const destination = repository
? joinDirectoryPath(location, checkoutName(repository.nameWithOwner))
: location;
return useMemo<CloneTabView>(() => {
const unavailable = host && canClone ? null : CLONE_UNAVAILABLE;
let notice: AddProjectTabView["notice"] = null;
if (!host || unavailable) notice = { kind: "empty", text: CLONE_UNAVAILABLE };
else if (search.error) notice = { kind: "error", text: search.error };
else if (search.pending) notice = { kind: "pending", text: "Searching..." };
else notice = { kind: "empty", text: cloneEmptyText(host, query) };
return {
rows,
activeIndex,
notice,
unavailable,
location,
destination,
primary: {
label: "Clone project",
submit: repository ? () => actions.clone(repository, location) : null,
},
};
}, [
actions,
activeIndex,
canClone,
destination,
host,
location,
query,
repository,
rows,
search.error,
search.pending,
]);
}
export function CloneTab({
view,
query,
hostId,
recommendedPaths,
disabled,
autoFocus,
onQueryChange,
onSelectRow,
onLocationChange,
}: {
view: CloneTabView;
query: string;
hostId: string | null;
recommendedPaths: string[];
disabled: boolean;
/** Focus the field on mount; only with a hardware keyboard, so touch keeps the list in view. */
autoFocus: boolean;
onQueryChange: (query: string) => void;
onSelectRow: (index: number) => void;
onLocationChange: (location: string) => void;
}) {
const editable = !disabled && !view.unavailable;
return (
<View style={styles.body}>
<FormTextInput
initialValue={query}
onChangeText={onQueryChange}
onSubmitEditing={isWeb ? undefined : (view.primary.submit ?? undefined)}
leading={githubIcon}
placeholder="Search GitHub or paste a Git URL"
accessibilityLabel="Search GitHub"
autoFocus={autoFocus}
autoCapitalize="none"
autoCorrect={false}
returnKeyType="go"
editable={editable}
testID="add-project-flow-input"
/>
<ResultList
rows={view.rows}
activeIndex={view.activeIndex}
notice={view.notice}
onSelect={onSelectRow}
disabled={disabled}
testID={RESULTS_TEST_ID}
/>
<LocationField
hostId={hostId}
location={view.location}
destination={view.destination}
recommendedPaths={recommendedPaths}
onChange={onLocationChange}
disabled={!editable}
testID="add-project-flow-location"
/>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
body: {
flex: 1,
minHeight: 0,
gap: theme.spacing[3],
},
}));
@@ -1,166 +0,0 @@
import { useMemo } from "react";
import { View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Folder, FolderOpen, Search } from "lucide-react-native";
import { buildProjectPickerOptions } from "@/components/project-picker-options";
import { Button } from "@/components/ui/button";
import { FormTextInput } from "@/components/ui/form-field";
import { isWeb } from "@/constants/platform";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { shortenPath } from "@/utils/shorten-path";
import type { AddProjectActions } from "./use-add-project-actions";
import type { AddProjectFlowState, AddProjectHost } from "./model";
import { pathBaseName } from "./options";
import { ResultList, type ResultRow } from "./result-list";
import { RESULTS_TEST_ID } from "./result-list-id";
import { useDirectorySearch } from "./searches";
import { resolveActiveIndex, type AddProjectTabView } from "./tab-view";
const ThemedSearch = withUnistyles(Search);
const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const searchIcon = <ThemedSearch size={ICON_SIZE.md} uniProps={mutedColor} />;
export function useExistingTab(input: {
state: AddProjectFlowState;
host: AddProjectHost | null;
recommendedPaths: string[];
actions: AddProjectActions;
}): AddProjectTabView {
const { state, host, recommendedPaths, actions } = input;
const { query } = state.existing;
const canAddProject = host?.canAddProject === true;
const search = useDirectorySearch({
hostId: state.hostId,
query,
// The host answers a blank query with nothing, so only search once there is text.
enabled: state.tab === "existing" && canAddProject && query.trim().length > 0,
});
const paths = useMemo(
() =>
canAddProject
? buildProjectPickerOptions({ recommendedPaths, serverPaths: search.items, query })
: [],
[canAddProject, query, recommendedPaths, search.items],
);
const rows = useMemo<ResultRow[]>(
() =>
paths.map((option) => {
const shortPath = shortenPath(option.path);
return {
id: option.path,
title: option.kind === "path" ? shortPath : pathBaseName(option.path),
subtitle: option.kind === "path" ? "Open this path" : shortPath,
icon: Folder,
testID: `add-project-flow-folder-${encodeURIComponent(option.path)}`,
};
}),
[paths],
);
// While the search for new text runs, the rows on screen answer the old text. None of them is
// picked until the new answer arrives or the user picks one, unless it is the typed path.
const awaitingRows =
search.pending && state.existing.selectedId === null && paths[0]?.kind !== "path";
const activeIndex = awaitingRows ? -1 : resolveActiveIndex(rows, state.existing.selectedId);
const activePath = paths[activeIndex]?.path ?? null;
return useMemo<AddProjectTabView>(() => {
const unavailable = canAddProject ? null : "Update the host to add projects";
let notice: AddProjectTabView["notice"] = null;
if (unavailable) notice = { kind: "empty", text: unavailable };
else if (search.error) notice = { kind: "error", text: search.error };
else if (search.pending) notice = { kind: "pending", text: "Searching..." };
else notice = { kind: "empty", text: query.trim() ? "No matching folders" : "No folders yet" };
return {
rows,
activeIndex,
notice,
unavailable,
primary: {
label: "Open project",
submit: activePath ? () => actions.openFolder(activePath) : null,
},
};
}, [actions, activeIndex, activePath, canAddProject, query, rows, search.error, search.pending]);
}
export function ExistingTab({
view,
query,
canBrowse,
disabled,
autoFocus,
onQueryChange,
onSelectRow,
onBrowse,
}: {
view: AddProjectTabView;
query: string;
canBrowse: boolean;
disabled: boolean;
/** Focus the field on mount; only with a hardware keyboard, so touch keeps the list in view. */
autoFocus: boolean;
onQueryChange: (query: string) => void;
onSelectRow: (index: number) => void;
onBrowse: () => void;
}) {
const editable = !disabled && !view.unavailable;
return (
<View style={styles.body}>
<View style={styles.searchRow}>
<View style={styles.searchField}>
<FormTextInput
initialValue={query}
onChangeText={onQueryChange}
onSubmitEditing={isWeb ? undefined : (view.primary.submit ?? undefined)}
leading={searchIcon}
placeholder="Search folders or enter a path"
accessibilityLabel="Search folders"
autoFocus={autoFocus}
autoCapitalize="none"
autoCorrect={false}
returnKeyType="go"
editable={editable}
testID="add-project-flow-input"
/>
</View>
{canBrowse ? (
<Button
variant="secondary"
leftIcon={FolderOpen}
onPress={onBrowse}
disabled={!editable}
testID="add-project-flow-browse"
>
Browse
</Button>
) : null}
</View>
<ResultList
rows={view.rows}
activeIndex={view.activeIndex}
notice={view.notice}
onSelect={onSelectRow}
disabled={disabled}
testID={RESULTS_TEST_ID}
/>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
body: {
flex: 1,
minHeight: 0,
gap: theme.spacing[3],
},
searchRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
searchField: {
flex: 1,
minWidth: 0,
},
}));
@@ -1,4 +0,0 @@
/** Native moves no focus to buttons from a hardware keyboard, so Enter always reaches the sheet. */
export function focusedControlOwnsEnter(): boolean {
return false;
}
@@ -1,16 +0,0 @@
import { RESULTS_TEST_ID } from "./result-list-id";
const ACTIVATES_ON_ENTER =
'button, a[href], [role="button"], [role="link"], [role="tab"], [role="combobox"], [role="menuitem"]';
/**
* Whether the focused element handles Enter itself, such as the Close button, a tab, or the
* Location field. Result rows are buttons too, but focusing a row picks it, so Enter on a row
* runs the primary action for that row.
*/
export function focusedControlOwnsEnter(): boolean {
const active = document.activeElement;
if (!(active instanceof HTMLElement)) return false;
if (active.closest(`[data-testid="${RESULTS_TEST_ID}"]`)) return false;
return active.matches(ACTIVATES_ON_ENTER);
}
-492
View File
@@ -1,492 +0,0 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Folder, FolderPlus, Plus } from "lucide-react-native";
import { AdaptiveModalSheet, type SheetKeyboard } from "@/components/adaptive-modal-sheet";
import { HostStatusDot } from "@/components/host-status-dot";
import { HostPicker } from "@/components/hosts/host-picker";
import { GitHubIcon } from "@/components/icons/github-icon";
import { Button } from "@/components/ui/button";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useAddHost } from "@/hosts/add-host";
import { useHardwareKeyboardPresent, type KeyboardInputEvent } from "@/keyboard";
import { Shortcut } from "@/components/ui/shortcut";
import { FieldTrigger } from "@/screens/new-workspace/form/field-trigger";
import {
useAddProjectFlowStore,
type AddProjectFlowRequest,
} from "@/stores/add-project-flow-store";
import { useRecommendedProjectPaths } from "@/stores/session-store-hooks";
import { formatShortcut } from "@/utils/format-shortcut";
import { getShortcutOs } from "@/utils/shortcut-platform";
import { CloneTab, useCloneTab } from "./clone-tab";
import { ExistingTab, useExistingTab } from "./existing-tab";
import { focusedControlOwnsEnter } from "./focused-control";
import {
ADD_PROJECT_KEYS,
addProjectFailure,
applyAvailableAddProjectHosts,
currentAddProjectHost,
selectableAddProjectHosts,
isAddProjectSubmitting,
moveAddProjectActiveIndex,
openAddProjectFlow,
resolveAddProjectKey,
selectAddProjectHost,
selectAddProjectRow,
selectAddProjectTab,
setAddProjectLocation,
setAddProjectQuery,
setNewFolderName,
type AddProjectTab,
} from "./model";
import { NewFolderTab, useNewFolderTab } from "./new-folder-tab";
import { defaultProjectLocation } from "./options";
import type { AddProjectTabView } from "./tab-view";
import { useAddProjectActions } from "./use-add-project-actions";
import { useAddProjectHosts } from "./use-add-project-hosts";
const SNAP_POINTS = ["90%"];
// Tall enough for a search field, six result rows, and the location field, so switching tabs
// never resizes the card.
const DESKTOP_HEIGHT = 560;
// Compact drops the segment icons so the three labels fit a phone's width.
const TABS: {
value: AddProjectTab;
label: string;
key: string;
icon: SegmentedControlOption<AddProjectTab>["icon"];
}[] = [
{
value: "existing",
label: "Existing",
key: "1",
icon: ({ color, size }) => <Folder color={color} size={size} />,
},
{
value: "clone",
label: "Clone",
key: "2",
icon: ({ color, size }) => <GitHubIcon color={color} size={size} />,
},
{
value: "new-folder",
label: "New folder",
key: "3",
icon: ({ color, size }) => <FolderPlus color={color} size={size} />,
},
];
/** `lockedTo` is the tab a running submission belongs to; the others are disabled until it ends. */
function buildTabOptions(
isMac: boolean,
withIcons: boolean,
lockedTo: AddProjectTab | null,
): SegmentedControlOption<AddProjectTab>[] {
const os = isMac ? "mac" : "non-mac";
return TABS.map(
(tab): SegmentedControlOption<AddProjectTab> => ({
value: tab.value,
label: tab.label,
icon: withIcons ? tab.icon : undefined,
tooltip: formatShortcut(["mod", tab.key], os),
testID: `add-project-flow-tab-${tab.value}`,
disabled: lockedTo !== null && tab.value !== lockedTo,
}),
);
}
interface AddProjectFlowProps {
request: AddProjectFlowRequest;
onClose: () => void;
}
/**
* Add project: one sheet with a tab per way to add one. The flow state lives in `./model`; this
* component wires it to the host, the searches, and the keys.
*/
export function AddProjectFlow({ request, onClose }: AddProjectFlowProps) {
const isCompact = useIsCompactFormFactor();
const isMac = getShortcutOs() === "mac";
const keyboardPresent = useHardwareKeyboardPresent();
const availableHosts = useAddProjectHosts();
const [state, setState] = useState(() =>
openAddProjectFlow({
hosts: availableHosts,
...(request.preferredHostId ? { preferredHostId: request.preferredHostId } : {}),
}),
);
useEffect(() => {
setState((current) => applyAvailableAddProjectHosts(current, availableHosts));
}, [availableHosts]);
const host = currentAddProjectHost(state);
const submitting = isAddProjectSubmitting(state);
const failure = addProjectFailure(state);
const recommendedPaths = useRecommendedProjectPaths(state.hostId);
const rememberedLocation = useAddProjectFlowStore((store) =>
state.hostId ? store.lastLocationByHost[state.hostId] : undefined,
);
const defaultLocation = defaultProjectLocation({
remembered: rememberedLocation,
projectPaths: recommendedPaths,
});
const actions = useAddProjectActions({ hostId: state.hostId, setState, onClose });
// An offline host keeps its drafts, but nothing submits until it is back or the user picks
// another host. Gated here, once, so the footer, Enter and the native Go key all agree.
const offline = host?.online === false;
const existing = blockSubmitWhen(
offline,
useExistingTab({ state, host, recommendedPaths, actions }),
);
const clone = blockSubmitWhen(offline, useCloneTab({ state, host, defaultLocation, actions }));
const newFolder = blockSubmitWhen(
offline,
useNewFolderTab({ state, host, defaultLocation, actions }),
);
const views: Record<AddProjectTab, AddProjectTabView> = {
existing,
clone,
"new-folder": newFolder,
};
const view = views[state.tab];
const selectTab = useCallback(
(tab: AddProjectTab) => setState((current) => selectAddProjectTab(current, tab)),
[],
);
const selectHost = useCallback(
(hostId: string) => setState((current) => selectAddProjectHost(current, hostId)),
[],
);
const changeQuery = useCallback(
(query: string) => setState((current) => setAddProjectQuery(current, query)),
[],
);
const changeLocation = useCallback(
(location: string) => setState((current) => setAddProjectLocation(current, location)),
[],
);
const changeName = useCallback(
(name: string) => setState((current) => setNewFolderName(current, name)),
[],
);
// The key handler reads the latest view without re-registering the overlay on every keystroke.
const viewRef = useRef(view);
viewRef.current = view;
const hasHostRef = useRef(host !== null);
hasHostRef.current = host !== null;
/** Picks the row at `index` of the current tab's list, remembered by its id. */
const selectRow = useCallback((index: number) => {
const row = viewRef.current.rows[index];
if (row) setState((current) => selectAddProjectRow(current, row.id));
}, []);
const keyboard = useMemo<SheetKeyboard>(
() => ({
keys: ADD_PROJECT_KEYS,
onKeyDown: (event: KeyboardInputEvent) => {
// With no host there is nothing to switch to or submit; Enter belongs to Add host.
if (!hasHostRef.current) return false;
const command = resolveAddProjectKey(event, isMac);
if (!command) return false;
const current = viewRef.current;
if (command.kind === "tab") {
selectTab(command.tab);
return true;
}
if (command.kind === "move") {
if (current.rows.length === 0) return false;
selectRow(
moveAddProjectActiveIndex(current.activeIndex, current.rows.length, command.direction),
);
return true;
}
if (!current.primary.submit || focusedControlOwnsEnter()) return false;
current.primary.submit();
return true;
},
}),
[isMac, selectRow, selectTab],
);
const lockedTab = submitting ? state.tab : null;
const tabOptions = useMemo(
() => buildTabOptions(isMac, !isCompact, lockedTab),
[isCompact, isMac, lockedTab],
);
const selectableHosts = useMemo(() => selectableAddProjectHosts(state), [state]);
const header = useMemo(
() => ({
title: "Add project",
titleTestID: "add-project-flow-title",
actions:
selectableHosts.length > 1 && state.hostId ? (
<HostPill
hosts={selectableHosts}
hostId={state.hostId}
onSelect={selectHost}
disabled={submitting}
/>
) : undefined,
}),
[selectHost, selectableHosts, state.hostId, submitting],
);
// On a pointer layout the failure sits left of the button; compact stacks it above a
// full-width button.
const problem = failure ?? (offline && host ? `${host.label} is offline` : null);
const failureLine = problem ? (
<Text style={styles.failure} numberOfLines={2} testID="add-project-flow-error">
{problem}
</Text>
) : null;
const footer = host ? (
<>
{failureLine ?? (isCompact ? null : <KeyHints canMove={view.rows.length > 0} />)}
<Button
variant="default"
onPress={view.primary.submit ?? undefined}
disabled={!view.primary.submit}
loading={submitting}
style={isCompact ? styles.primaryCompact : styles.primary}
testID="add-project-flow-submit"
>
{view.primary.label}
</Button>
</>
) : null;
let body: ReactNode;
if (!host) {
body = <NoHosts onClose={onClose} />;
} else if (state.tab === "existing") {
body = (
<ExistingTab
view={existing}
query={state.existing.query}
canBrowse={host.canBrowse && !offline}
disabled={submitting}
autoFocus={keyboardPresent}
onQueryChange={changeQuery}
onSelectRow={selectRow}
onBrowse={actions.browse}
/>
);
} else if (state.tab === "clone") {
body = (
<CloneTab
view={clone}
query={state.clone.query}
hostId={state.hostId}
recommendedPaths={recommendedPaths}
disabled={submitting}
autoFocus={keyboardPresent}
onQueryChange={changeQuery}
onSelectRow={selectRow}
onLocationChange={changeLocation}
/>
);
} else {
body = (
<NewFolderTab
view={newFolder}
name={state.newFolder.name}
hostId={state.hostId}
recommendedPaths={recommendedPaths}
disabled={submitting}
autoFocus={keyboardPresent}
onNameChange={changeName}
onLocationChange={changeLocation}
/>
);
}
return (
<AdaptiveModalSheet
visible
onClose={onClose}
header={header}
footer={footer}
footerContainerStyle={isCompact ? styles.footerContainerCompact : undefined}
snapPoints={SNAP_POINTS}
desktopHeight={DESKTOP_HEIGHT}
scrollable={false}
keyboard={keyboard}
contentStyle={styles.content}
testID="add-project-flow"
>
{host ? (
<SegmentedControl
options={tabOptions}
value={state.tab}
onValueChange={selectTab}
fill
testID="add-project-flow-tabs"
/>
) : null}
{/* Keyed by tab so each tab's input mounts with its own draft and takes focus. */}
<View key={host ? state.tab : "no-host"} style={styles.tabBody}>
{body}
</View>
</AdaptiveModalSheet>
);
}
function blockSubmitWhen<TabView extends AddProjectTabView>(
blocked: boolean,
view: TabView,
): TabView {
return blocked ? { ...view, primary: { ...view.primary, submit: null } } : view;
}
function hostOptionTestID(serverId: string): string {
return `add-project-flow-host-${serverId}`;
}
function HostPill({
hosts,
hostId,
onSelect,
disabled,
}: {
hosts: { serverId: string; label: string }[];
hostId: string;
onSelect: (hostId: string) => void;
disabled: boolean;
}) {
const anchorRef = useRef<View>(null);
const [open, setOpen] = useState(false);
const openPicker = useCallback(() => setOpen(true), []);
const label = hosts.find((host) => host.serverId === hostId)?.label ?? hostId;
const icon = useMemo(() => <HostStatusDot serverId={hostId} />, [hostId]);
return (
<HostPicker
hosts={hosts}
value={hostId}
onSelect={onSelect}
open={open}
onOpenChange={setOpen}
anchorRef={anchorRef}
searchable={false}
title="Host"
desktopPlacement="bottom-end"
desktopMinWidth={240}
hostOptionTestID={hostOptionTestID}
>
<FieldTrigger
ref={anchorRef}
variant="badge"
label="Host"
accessibilityLabel="Project host"
tooltip="Host"
icon={icon}
value={label}
onPress={openPicker}
disabled={disabled}
testID="add-project-flow-host-trigger"
/>
</HostPicker>
);
}
const MOVE_KEYS = ["↑↓"];
const TAB_KEYS = ["mod", "1–3"];
/** The keys that are not on any control: list movement and tab switching. */
function KeyHints({ canMove }: { canMove: boolean }) {
const keyboardPresent = useHardwareKeyboardPresent();
if (!keyboardPresent) return <View />;
return (
<View style={styles.hints}>
{canMove ? (
<View style={styles.hint}>
<Shortcut keys={MOVE_KEYS} />
<Text style={styles.hintText}>Move</Text>
</View>
) : null}
<View style={styles.hint}>
<Shortcut keys={TAB_KEYS} />
<Text style={styles.hintText}>Switch</Text>
</View>
</View>
);
}
function NoHosts({ onClose }: { onClose: () => void }) {
const addHost = useAddHost();
const handleAddHost = useCallback(() => {
// The project sheet must release its window before the add-host sheet opens.
onClose();
addHost();
}, [addHost, onClose]);
return (
<View style={styles.noHosts}>
<Text style={styles.noHostsText}>No connected hosts</Text>
<Button
variant="secondary"
leftIcon={Plus}
onPress={handleAddHost}
testID="add-project-flow-add-host"
>
Add host
</Button>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
content: {
flex: 1,
minHeight: 0,
},
tabBody: {
flex: 1,
minHeight: 0,
},
footerContainerCompact: {
flexDirection: "column",
alignItems: "stretch",
},
// The message wraps beside the button; the button keeps its width.
failure: {
flexShrink: 1,
minWidth: 0,
color: theme.colors.statusDanger,
fontSize: theme.fontSize.sm,
},
hints: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[4],
},
hint: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1.5],
},
hintText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
primary: {
flexShrink: 0,
},
primaryCompact: {
flexShrink: 0,
alignSelf: "stretch",
},
noHosts: {
flex: 1,
alignItems: "center",
justifyContent: "center",
gap: theme.spacing[3],
},
noHostsText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
}));
@@ -1,109 +0,0 @@
import { useCallback, useMemo, useRef, useState } from "react";
import type { View } from "react-native";
import { withUnistyles } from "react-native-unistyles";
import { HardDrive } from "lucide-react-native";
import { buildProjectPickerOptions } from "@/components/project-picker-options";
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
import { FieldTrigger } from "@/screens/new-workspace/form/field-trigger";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { shortenPath } from "@/utils/shorten-path";
import { buildSuggestedParentDirectories } from "./options";
import { useDirectorySearch } from "./searches";
const ThemedHardDrive = withUnistyles(HardDrive);
const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
const locationIcon = <ThemedHardDrive size={ICON_SIZE.md} uniProps={mutedColor} />;
interface LocationFieldProps {
hostId: string | null;
/** The parent directory the project goes into. */
location: string;
/** Where the project ends up, shown on the field so the user rarely needs to open it. */
destination: string;
recommendedPaths: string[];
onChange: (location: string) => void;
disabled: boolean;
testID: string;
}
/** Picks the parent directory for a new project: recent parents, a folder search, or a typed path. */
export function LocationField({
hostId,
location,
destination,
recommendedPaths,
onChange,
disabled,
testID,
}: LocationFieldProps) {
const anchorRef = useRef<View>(null);
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const search = useDirectorySearch({ hostId, query, enabled: open && query.trim().length > 0 });
// The same builder as the Existing tab: a typed path first, then matching suggestions and
// folders the host found.
const pickerOptions = useMemo(() => {
const suggestions = [
location,
...buildSuggestedParentDirectories(recommendedPaths).filter((path) => path !== location),
];
return buildProjectPickerOptions({
recommendedPaths: suggestions,
serverPaths: search.items,
query,
});
}, [location, query, recommendedPaths, search.items]);
const options = useMemo<ComboboxOption[]>(
() =>
pickerOptions.map(
(option): ComboboxOption => ({
id: option.path,
label: shortenPath(option.path),
description: option.kind === "path" ? "Use this folder" : undefined,
kind: "directory",
}),
),
[pickerOptions],
);
// Like the Existing tab: while a new search runs, only a typed path is picked for Enter.
const awaitingOptions = search.pending && pickerOptions[0]?.kind !== "path";
const handleOpen = useCallback(() => setOpen(true), []);
const handleOpenChange = useCallback((next: boolean) => {
setOpen(next);
if (!next) setQuery("");
}, []);
return (
<>
<FieldTrigger
ref={anchorRef}
variant="field"
label="Location"
accessibilityLabel="Project location"
icon={locationIcon}
value={shortenPath(destination)}
onPress={handleOpen}
disabled={disabled}
testID={testID}
/>
<Combobox
options={options}
value={location}
onSelect={onChange}
searchable
remoteSearch
remoteSearchPending={awaitingOptions}
onSearchQueryChange={setQuery}
searchPlaceholder="Search folders or enter a path"
emptyText={search.error ?? (search.pending ? "Searching..." : "No matching folders")}
title="Location"
open={open}
onOpenChange={handleOpenChange}
anchorRef={anchorRef}
desktopPlacement="bottom-start"
/>
</>
);
}
+152 -189
View File
@@ -1,194 +1,153 @@
import { describe, expect, it } from "vitest";
import {
applyAvailableAddProjectHosts,
selectableAddProjectHosts,
failAddProjectSubmission,
backAddProjectPage,
chooseAddProjectHost,
currentAddProjectPage,
moveAddProjectActiveIndex,
moveAddProjectSelection,
openAddProjectFlow,
resolveAddProjectKey,
selectAddProjectHost,
selectAddProjectRow,
selectAddProjectTab,
setAddProjectLocation,
setAddProjectQuery,
setNewFolderName,
startAddProjectSubmission,
openDirectorySearchPage,
openGithubLocationPage,
openNewDirectoryNamePage,
openNewDirectoryParentPage,
setAddProjectActiveIndex,
setAddProjectPageInput,
setNewDirectoryName,
type AddProjectHost,
} from "./model";
import {
addProjectMethodEmptyText,
buildAddProjectMethods,
buildCloneLocationOptions,
buildManualGithubRepositoryChoices,
checkoutName,
defaultProjectLocation,
joinDirectoryPath,
parentDirectory,
validateNewFolderName,
} from "./options";
import { resolveActiveIndex } from "./tab-view";
const HOST: AddProjectHost = {
serverId: "host-1",
label: "Local",
online: true,
canAddProject: true,
canBrowse: true,
canCloneGithubRepositories: true,
canSearchGithubRepositories: true,
canCreateDirectory: true,
};
const REMOTE: AddProjectHost = { ...HOST, serverId: "host-2", label: "Remote", canBrowse: false };
const REMOTE_OFFLINE: AddProjectHost = { ...REMOTE, online: false };
const KEY = { key: "", ctrlKey: false, metaKey: false, altKey: false, shiftKey: false };
describe("Add Project navigation", () => {
it("skips a single connected host without adding it to history", () => {
const state = openAddProjectFlow({ hosts: [HOST] });
describe("Add Project flow", () => {
it("opens on the Existing tab of the preferred host", () => {
const state = openAddProjectFlow({ hosts: [HOST, REMOTE], preferredHostId: "host-2" });
expect(state.tab).toBe("existing");
expect(state.hostId).toBe("host-2");
});
it("falls back to the first host, and to no host when none is connected", () => {
expect(openAddProjectFlow({ hosts: [HOST, REMOTE] }).hostId).toBe("host-1");
expect(openAddProjectFlow({ hosts: [] }).hostId).toBeNull();
});
it("keeps each tab's input when switching tabs", () => {
let state = openAddProjectFlow({ hosts: [HOST] });
state = setAddProjectQuery(state, "paseo");
state = selectAddProjectTab(state, "clone");
state = setAddProjectQuery(state, "getpaseo/");
state = selectAddProjectTab(state, "new-folder");
state = setNewFolderName(state, "acme-api");
state = selectAddProjectTab(state, "existing");
expect(state.existing.query).toBe("paseo");
expect(state.clone.query).toBe("getpaseo/");
expect(state.newFolder.name).toBe("acme-api");
});
it("switching host keeps typed input but drops host-specific locations and selection", () => {
let state = openAddProjectFlow({ hosts: [HOST, REMOTE] });
state = setAddProjectQuery(state, "paseo");
state = selectAddProjectRow(state, "/code/paseo");
state = selectAddProjectTab(state, "new-folder");
state = setNewFolderName(state, "acme-api");
state = setAddProjectLocation(state, "~/work");
state = selectAddProjectHost(state, "host-2");
expect(state.hostId).toBe("host-2");
expect(state.existing).toEqual({ query: "paseo", selectedId: null });
expect(state.newFolder).toEqual({ name: "acme-api", location: null });
});
it("locks tab and host while a submission runs, and unlocks with the failure", () => {
let state = openAddProjectFlow({ hosts: [HOST, REMOTE] });
state = selectAddProjectTab(state, "clone");
state = startAddProjectSubmission(state);
expect(selectAddProjectTab(state, "existing").tab).toBe("clone");
expect(selectAddProjectHost(state, "host-2").hostId).toBe("host-1");
expect(selectAddProjectRow(state, "acme/app")).toBe(state);
expect(startAddProjectSubmission(state)).toBe(state);
state = failAddProjectSubmission(state, "Unable to clone project");
expect(state.submission).toEqual({
status: "failed",
tab: "clone",
message: "Unable to clone project",
expect(currentAddProjectPage(state)).toEqual({
kind: "method",
hostId: "host-1",
activeIndex: 0,
error: null,
isSubmitting: false,
});
expect(selectAddProjectTab(state, "existing").submission).toEqual({ status: "idle" });
expect(backAddProjectPage(state)).toBeNull();
});
it("clears a failure once the user edits the input or picks another row", () => {
let state = openAddProjectFlow({ hosts: [HOST] });
state = startAddProjectSubmission(state);
state = failAddProjectSubmission(state, "Directory not found");
it("restores page input and selection after Back", () => {
const secondHost = { ...HOST, serverId: "host-2", label: "Remote" };
let state = openAddProjectFlow({ hosts: [HOST, secondHost] });
state = setAddProjectPageInput(state, "rem");
state = setAddProjectActiveIndex(state, 1);
state = chooseAddProjectHost(state, secondHost.serverId);
state = openDirectorySearchPage(state, secondHost.serverId);
expect(setAddProjectQuery(state, "~/dev").submission).toEqual({ status: "idle" });
expect(selectAddProjectRow(state, "/code/app").submission).toEqual({ status: "idle" });
state = backAddProjectPage(state) ?? state;
state = backAddProjectPage(state) ?? state;
expect(currentAddProjectPage(state)).toEqual({
kind: "host",
query: "rem",
activeIndex: 1,
error: null,
});
});
it("keeps the chosen host and its draft while it is offline, never moving them to another host", () => {
let state = openAddProjectFlow({ hosts: [HOST, REMOTE] });
state = selectAddProjectHost(state, "host-2");
state = setAddProjectQuery(state, "/srv/app");
const offline = applyAvailableAddProjectHosts(state, [HOST, REMOTE_OFFLINE]);
expect(offline.hostId).toBe("host-2");
expect(offline.existing.query).toBe("/srv/app");
expect(selectableAddProjectHosts(offline).map((host) => host.serverId)).toEqual([
"host-1",
"host-2",
]);
const back = applyAvailableAddProjectHosts(offline, [HOST, REMOTE]);
expect(back.hostId).toBe("host-2");
expect(back.existing.query).toBe("/srv/app");
expect(selectAddProjectHost(offline, "host-1").hostId).toBe("host-1");
});
it("picks only an online host, and another one when the chosen host is removed", () => {
expect(openAddProjectFlow({ hosts: [REMOTE_OFFLINE, HOST] }).hostId).toBe("host-1");
expect(
openAddProjectFlow({ hosts: [REMOTE_OFFLINE, HOST], preferredHostId: "host-2" }).hostId,
).toBe("host-1");
expect(openAddProjectFlow({ hosts: [REMOTE_OFFLINE] }).hostId).toBeNull();
expect(
selectAddProjectHost(openAddProjectFlow({ hosts: [HOST, REMOTE_OFFLINE] }), "host-2").hostId,
).toBe("host-1");
const state = selectAddProjectHost(openAddProjectFlow({ hosts: [HOST, REMOTE] }), "host-2");
expect(applyAvailableAddProjectHosts(state, [HOST]).hostId).toBe("host-1");
expect(applyAvailableAddProjectHosts(openAddProjectFlow({ hosts: [] }), [REMOTE]).hostId).toBe(
"host-2",
);
});
it("keeps the user's pick across a reorder and never swaps a dropped pick for another row", () => {
const rows = [{ id: "/code/beta" }, { id: "/code/alpha" }];
expect(resolveActiveIndex(rows, "/code/alpha")).toBe(1);
expect(resolveActiveIndex(rows, null)).toBe(0);
expect(resolveActiveIndex(rows, "/code/gone")).toBe(-1);
expect(resolveActiveIndex([], null)).toBe(-1);
});
it("wraps keyboard selection at both ends", () => {
it("wraps keyboard selection in both directions", () => {
expect(moveAddProjectActiveIndex(2, 3, "next")).toBe(0);
expect(moveAddProjectActiveIndex(0, 3, "previous")).toBe(2);
});
});
describe("Add Project keys", () => {
it("maps Mod+1/2/3 to tabs using the platform's modifier", () => {
expect(resolveAddProjectKey({ ...KEY, key: "2", metaKey: true }, true)).toEqual({
kind: "tab",
tab: "clone",
});
expect(resolveAddProjectKey({ ...KEY, key: "3", ctrlKey: true }, false)).toEqual({
kind: "tab",
tab: "new-folder",
});
expect(resolveAddProjectKey({ ...KEY, key: "1", ctrlKey: true }, true)).toBeNull();
expect(resolveAddProjectKey({ ...KEY, key: "1" }, true)).toBeNull();
expect(moveAddProjectSelection(0, [true, false, true], "next")).toBe(2);
});
it("maps arrows and Enter to list commands", () => {
expect(resolveAddProjectKey({ ...KEY, key: "ArrowDown" }, true)).toEqual({
kind: "move",
direction: "next",
it("restores a directory name after returning to and reselecting its parent", () => {
let state = openAddProjectFlow({ hosts: [HOST] });
state = openNewDirectoryParentPage(state, HOST.serverId);
state = openNewDirectoryNamePage(state, HOST.serverId, "~/dev");
state = setNewDirectoryName(state, "command-center");
state = backAddProjectPage(state) ?? state;
state = openNewDirectoryNamePage(state, HOST.serverId, "~/dev");
expect(currentAddProjectPage(state)).toMatchObject({
kind: "new-directory-name",
parentPath: "~/dev",
name: "command-center",
});
expect(resolveAddProjectKey({ ...KEY, key: "ArrowUp" }, true)).toEqual({
kind: "move",
direction: "previous",
});
it("restores the GitHub destination query and active parent when reopening a repository", () => {
const repository = {
id: "repo-1",
nameWithOwner: "getpaseo/paseo",
cloneUrl: "git@github.com:getpaseo/paseo.git",
description: null,
visibility: "public",
updatedAt: null,
};
let state = openAddProjectFlow({ hosts: [HOST] });
state = openGithubLocationPage(state, HOST.serverId, repository);
state = setAddProjectPageInput(state, "~/dev");
state = setAddProjectActiveIndex(state, 2);
state = backAddProjectPage(state) ?? state;
state = openGithubLocationPage(state, HOST.serverId, repository);
expect(currentAddProjectPage(state)).toMatchObject({
kind: "github-location",
query: "~/dev",
activeIndex: 2,
});
expect(resolveAddProjectKey({ ...KEY, key: "Enter" }, true)).toEqual({ kind: "submit" });
expect(resolveAddProjectKey({ ...KEY, key: "Enter", shiftKey: true }, true)).toBeNull();
});
});
describe("Add Project options", () => {
it("hides every mutating method when the host lacks stable project identity", () => {
const outdatedHost = { ...HOST, canAddProject: false };
expect(buildAddProjectMethods(outdatedHost)).toEqual([]);
expect(addProjectMethodEmptyText(outdatedHost)).toBe("Update the host to use Add Project.");
});
it("keeps host-upgrade methods discoverable while hiding local-only Browse", () => {
expect(
buildAddProjectMethods({
...HOST,
canBrowse: false,
canCloneGithubRepositories: false,
canSearchGithubRepositories: false,
canCreateDirectory: false,
}),
).toEqual([
{
id: "directory-search",
label: "Search for directory",
description: "Find a directory on Local",
},
{
id: "github",
label: "Clone from GitHub",
description: "Update this host to clone GitHub repositories",
disabled: true,
},
{
id: "new-directory",
label: "New directory",
description: "Update this host to create directories",
disabled: true,
},
]);
});
it("offers manual URL and protocol-specific owner/repo clone choices", () => {
expect(buildManualGithubRepositoryChoices("git@github.com:getpaseo/paseo.git")).toEqual([
expect.objectContaining({
@@ -204,42 +163,46 @@ describe("Add Project options", () => {
expect(buildManualGithubRepositoryChoices("paseo")).toEqual([]);
});
it("defaults the location to a folder that exists", () => {
expect(defaultProjectLocation({ remembered: undefined, projectPaths: [] })).toBe("~");
expect(defaultProjectLocation({ remembered: undefined, projectPaths: ["/code/app"] })).toBe(
"/code",
);
expect(defaultProjectLocation({ remembered: "~/work", projectPaths: ["/code/app"] })).toBe(
"~/work",
);
it("shows final clone paths while retaining parent paths as values", () => {
expect(
buildCloneLocationOptions({
parents: ["~/dev", "~/workspace"],
repositoryName: "paseo",
existingPaths: ["~/workspace/paseo"],
}),
).toEqual([
{
id: "~/dev",
path: "~/dev",
displayPath: "~/dev/paseo",
secondaryText: "Parent directory: ~/dev",
disabled: false,
},
{
id: "~/workspace",
path: "~/workspace",
displayPath: "~/workspace/paseo",
secondaryText: "Already exists",
disabled: true,
},
]);
});
it("keeps a drive or filesystem root when deriving and joining a location", () => {
expect(parentDirectory("C:\\repo")).toBe("C:\\");
expect(parentDirectory("/repo")).toBe("/");
expect(parentDirectory("\\\\nas\\work")).toBeNull();
expect(parentDirectory("\\\\nas\\work\\app")).toBe("\\\\nas\\work");
expect(defaultProjectLocation({ remembered: undefined, projectPaths: ["\\\\nas\\work"] })).toBe(
"~",
);
expect(parentDirectory("/code/app")).toBe("/code");
expect(joinDirectoryPath("C:\\", "new-project")).toBe("C:\\new-project");
expect(joinDirectoryPath("/", "new-project")).toBe("/new-project");
expect(defaultProjectLocation({ remembered: undefined, projectPaths: ["C:\\repo"] })).toBe(
"C:\\",
);
});
it("names the checkout the way the host does", () => {
expect(checkoutName("acme/app.git")).toBe("app");
expect(checkoutName("acme/app")).toBe("app");
});
it("rejects folder names that are empty or leave the location", () => {
expect(validateNewFolderName("")).toBe("Enter a folder name");
expect(validateNewFolderName("..")).toBe("Enter a folder name");
expect(validateNewFolderName("../invalid")).toBe("Use a name without slashes");
expect(validateNewFolderName("C:repo")).toBe("Use a name without a drive letter");
expect(validateNewFolderName(" acme-api ")).toBeNull();
it("shows equivalent absolute-home and tilde destinations only once", () => {
expect(
buildCloneLocationOptions({
parents: ["/Users/moboudra/dev", "~/dev"],
repositoryName: "dotfiles",
existingPaths: [],
}),
).toEqual([
{
id: "/Users/moboudra/dev",
path: "/Users/moboudra/dev",
displayPath: "/Users/moboudra/dev/dotfiles",
secondaryText: "Parent directory: /Users/moboudra/dev",
disabled: false,
},
]);
});
});
+212 -164
View File
@@ -1,7 +1,6 @@
export interface AddProjectHost {
serverId: string;
label: string;
online: boolean;
canAddProject: boolean;
canBrowse: boolean;
canCloneGithubRepositories: boolean;
@@ -18,42 +17,42 @@ export interface GithubRepositoryChoice {
updatedAt: string | null;
}
/** The three ways to add a project, in the order the segmented control and Mod+1/2/3 walk them. */
export const ADD_PROJECT_TABS = ["existing", "clone", "new-folder"] as const;
export type AddProjectTab = (typeof ADD_PROJECT_TABS)[number];
interface PageState {
activeIndex: number;
error: string | null;
}
interface ListDraft {
interface SearchPageState extends PageState {
query: string;
/**
* The row the user picked, by id, so it stays picked when a search refresh reorders the rows.
* `null`, or an id no longer listed, means the first row.
*/
selectedId: string | null;
}
/** `location: null` means the default parent directory for the current host. */
interface CloneDraft extends ListDraft {
location: string | null;
}
interface NewFolderDraft {
name: string;
location: string | null;
}
export type AddProjectSubmission =
| { status: "idle" }
| { status: "submitting"; tab: AddProjectTab }
| { status: "failed"; tab: AddProjectTab; message: string };
export type AddProjectPage =
| ({ kind: "host" } & SearchPageState)
| ({ kind: "method"; hostId: string; isSubmitting: boolean } & PageState)
| ({ kind: "directory-search"; hostId: string; isSubmitting: boolean } & SearchPageState)
| ({ kind: "github-search"; hostId: string } & SearchPageState)
| ({
kind: "github-location";
hostId: string;
repository: GithubRepositoryChoice;
isSubmitting: boolean;
} & SearchPageState)
| ({ kind: "new-directory-parent"; hostId: string } & SearchPageState)
| {
kind: "new-directory-name";
hostId: string;
parentPath: string;
name: string;
activeIndex: number;
error: string | null;
isSubmitting: boolean;
};
export interface AddProjectFlowState {
hosts: AddProjectHost[];
hostId: string | null;
tab: AddProjectTab;
existing: ListDraft;
clone: CloneDraft;
newFolder: NewFolderDraft;
submission: AddProjectSubmission;
pages: AddProjectPage[];
newDirectoryNameDrafts: Record<string, string>;
githubLocationDrafts: Record<string, { query: string; activeIndex: number }>;
}
export interface OpenAddProjectFlowInput {
@@ -61,144 +60,214 @@ export interface OpenAddProjectFlowInput {
preferredHostId?: string;
}
const IDLE: AddProjectSubmission = { status: "idle" };
type SearchPageKind = Extract<AddProjectPage, { query: string }>["kind"];
function pickHostId(hosts: AddProjectHost[], preferredHostId?: string | null): string | null {
const online = hosts.filter((host) => host.online);
const preferred = preferredHostId
? online.find((host) => host.serverId === preferredHostId)
: undefined;
return (preferred ?? online[0])?.serverId ?? null;
function searchPage<TKind extends SearchPageKind>(kind: TKind) {
return { kind, query: "", activeIndex: 0, error: null } as const;
}
function methodPage(hostId: string): AddProjectPage {
return { kind: "method", hostId, activeIndex: 0, error: null, isSubmitting: false };
}
export function openAddProjectFlow(input: OpenAddProjectFlowInput): AddProjectFlowState {
const preferredHost = input.preferredHostId
? input.hosts.find((host) => host.serverId === input.preferredHostId)
: null;
const onlyHost = input.hosts.length === 1 ? input.hosts[0] : null;
const initialHost = preferredHost ?? onlyHost;
return {
hosts: input.hosts,
hostId: pickHostId(input.hosts, input.preferredHostId),
tab: "existing",
existing: { query: "", selectedId: null },
clone: { query: "", selectedId: null, location: null },
newFolder: { name: "", location: null },
submission: IDLE,
pages: initialHost ? [methodPage(initialHost.serverId)] : [searchPage("host")],
newDirectoryNameDrafts: {},
githubLocationDrafts: {},
};
}
export function currentAddProjectHost(state: AddProjectFlowState): AddProjectHost | null {
return state.hosts.find((host) => host.serverId === state.hostId) ?? null;
}
export function isAddProjectSubmitting(state: AddProjectFlowState): boolean {
return state.submission.status === "submitting";
}
/** The failure to show on the current tab, if the last submission there failed. */
export function addProjectFailure(state: AddProjectFlowState): string | null {
const { submission } = state;
return submission.status === "failed" && submission.tab === state.tab ? submission.message : null;
}
/** The hosts the user can switch to: every online host, plus the current one even while offline. */
export function selectableAddProjectHosts(state: AddProjectFlowState): AddProjectHost[] {
return state.hosts.filter((host) => host.online || host.serverId === state.hostId);
}
/**
* The chosen host stays chosen while it is offline, with its drafts, so a disconnect never sends
* them to another host. A host is picked only when none is chosen or the chosen one was removed.
*/
export function applyAvailableAddProjectHosts(
state: AddProjectFlowState,
hosts: AddProjectHost[],
preferredHostId?: string,
): AddProjectFlowState {
const stillListed = hosts.some((host) => host.serverId === state.hostId);
if (stillListed) return { ...state, hosts };
return withHost({ ...state, hosts }, pickHostId(hosts));
}
function withHost(state: AddProjectFlowState, hostId: string | null): AddProjectFlowState {
const current = currentAddProjectPage(state);
if (state.pages.length !== 1 || current.kind !== "host") {
return { ...state, hosts };
}
const preferredHost = preferredHostId
? hosts.find((host) => host.serverId === preferredHostId)
: null;
const onlyHost = hosts.length === 1 ? hosts[0] : null;
const initialHost = preferredHost ?? onlyHost;
return {
...state,
hostId,
existing: { ...state.existing, selectedId: null },
clone: { ...state.clone, selectedId: null, location: null },
newFolder: { ...state.newFolder, location: null },
submission: IDLE,
hosts,
pages: initialHost ? [methodPage(initialHost.serverId)] : state.pages,
};
}
export function selectAddProjectHost(
export function currentAddProjectPage(state: AddProjectFlowState): AddProjectPage {
const page = state.pages[state.pages.length - 1];
if (!page) {
throw new Error("Add Project flow must always contain a page");
}
return page;
}
export function updateCurrentAddProjectPage(
state: AddProjectFlowState,
update: (page: AddProjectPage) => AddProjectPage,
): AddProjectFlowState {
const index = state.pages.length - 1;
return {
...state,
pages: state.pages.map((page, pageIndex) => (pageIndex === index ? update(page) : page)),
};
}
export function pushAddProjectPage(
state: AddProjectFlowState,
page: AddProjectPage,
): AddProjectFlowState {
return { ...state, pages: [...state.pages, page] };
}
export function backAddProjectPage(state: AddProjectFlowState): AddProjectFlowState | null {
if (state.pages.length === 1) {
return null;
}
return { ...state, pages: state.pages.slice(0, -1) };
}
export function chooseAddProjectHost(
state: AddProjectFlowState,
hostId: string,
): AddProjectFlowState {
if (isAddProjectSubmitting(state) || hostId === state.hostId) return state;
if (!state.hosts.some((host) => host.serverId === hostId && host.online)) return state;
return withHost(state, hostId);
return pushAddProjectPage(state, methodPage(hostId));
}
export function selectAddProjectTab(
export function openDirectorySearchPage(
state: AddProjectFlowState,
tab: AddProjectTab,
hostId: string,
): AddProjectFlowState {
if (isAddProjectSubmitting(state) || tab === state.tab) return state;
return { ...state, tab, submission: IDLE };
return pushAddProjectPage(state, {
...searchPage("directory-search"),
hostId,
isSubmitting: false,
});
}
/** Sets the search text of the current list tab. */
export function setAddProjectQuery(state: AddProjectFlowState, query: string): AddProjectFlowState {
if (state.tab === "existing") {
return { ...state, existing: { query, selectedId: null }, submission: IDLE };
}
if (state.tab === "clone") {
return { ...state, clone: { ...state.clone, query, selectedId: null }, submission: IDLE };
}
return state;
}
export function setNewFolderName(state: AddProjectFlowState, name: string): AddProjectFlowState {
return { ...state, newFolder: { ...state.newFolder, name }, submission: IDLE };
}
/** Sets the parent directory of the current tab that creates a folder. */
export function setAddProjectLocation(
export function openGithubSearchPage(
state: AddProjectFlowState,
location: string,
hostId: string,
): AddProjectFlowState {
if (state.tab === "clone") {
return { ...state, clone: { ...state.clone, location }, submission: IDLE };
}
if (state.tab === "new-folder") {
return { ...state, newFolder: { ...state.newFolder, location }, submission: IDLE };
}
return state;
return pushAddProjectPage(state, { ...searchPage("github-search"), hostId });
}
export function selectAddProjectRow(
export function openGithubLocationPage(
state: AddProjectFlowState,
selectedId: string,
hostId: string,
repository: GithubRepositoryChoice,
): AddProjectFlowState {
// The row being added stays put until its submission ends; choosing another clears the
// failure of the last one.
if (isAddProjectSubmitting(state)) return state;
if (state.tab === "existing") {
return { ...state, existing: { ...state.existing, selectedId }, submission: IDLE };
}
if (state.tab === "clone") {
return { ...state, clone: { ...state.clone, selectedId }, submission: IDLE };
}
return state;
const draft = state.githubLocationDrafts[githubLocationDraftKey(hostId, repository.id)];
return pushAddProjectPage(state, {
kind: "github-location",
query: draft?.query ?? "",
activeIndex: draft?.activeIndex ?? 0,
error: null,
hostId,
repository,
isSubmitting: false,
});
}
export function startAddProjectSubmission(state: AddProjectFlowState): AddProjectFlowState {
if (isAddProjectSubmitting(state)) return state;
return { ...state, submission: { status: "submitting", tab: state.tab } };
}
export function failAddProjectSubmission(
export function openNewDirectoryParentPage(
state: AddProjectFlowState,
message: string,
hostId: string,
): AddProjectFlowState {
if (state.submission.status !== "submitting") return state;
return { ...state, submission: { status: "failed", tab: state.submission.tab, message } };
return pushAddProjectPage(state, { ...searchPage("new-directory-parent"), hostId });
}
export function openNewDirectoryNamePage(
state: AddProjectFlowState,
hostId: string,
parentPath: string,
): AddProjectFlowState {
const draftKey = newDirectoryDraftKey(hostId, parentPath);
return pushAddProjectPage(state, {
kind: "new-directory-name",
hostId,
parentPath,
name: state.newDirectoryNameDrafts[draftKey] ?? "",
activeIndex: 0,
error: null,
isSubmitting: false,
});
}
export function setAddProjectPageInput(
state: AddProjectFlowState,
value: string,
): AddProjectFlowState {
const page = currentAddProjectPage(state);
const updated = updateCurrentAddProjectPage(state, (current) => {
if (current.kind === "new-directory-name") {
return { ...current, name: value, activeIndex: 0, error: null };
}
if (current.kind === "method") return current;
return { ...current, query: value, activeIndex: 0, error: null };
});
if (page.kind !== "github-location") return updated;
const draftKey = githubLocationDraftKey(page.hostId, page.repository.id);
return {
...updated,
githubLocationDrafts: {
...updated.githubLocationDrafts,
[draftKey]: { query: value, activeIndex: 0 },
},
};
}
export function setNewDirectoryName(
state: AddProjectFlowState,
value: string,
): AddProjectFlowState {
const page = currentAddProjectPage(state);
if (page.kind !== "new-directory-name") return state;
const draftKey = newDirectoryDraftKey(page.hostId, page.parentPath);
const updated = setAddProjectPageInput(state, value);
return {
...updated,
newDirectoryNameDrafts: {
...updated.newDirectoryNameDrafts,
[draftKey]: value,
},
};
}
function newDirectoryDraftKey(hostId: string, parentPath: string): string {
return `${hostId}\u0000${parentPath}`;
}
function githubLocationDraftKey(hostId: string, repositoryId: string): string {
return `${hostId}\u0000${repositoryId}`;
}
export function setAddProjectActiveIndex(
state: AddProjectFlowState,
activeIndex: number,
): AddProjectFlowState {
const page = currentAddProjectPage(state);
const updated = updateCurrentAddProjectPage(state, (current) => ({ ...current, activeIndex }));
if (page.kind !== "github-location") return updated;
const draftKey = githubLocationDraftKey(page.hostId, page.repository.id);
return {
...updated,
githubLocationDrafts: {
...updated.githubLocationDrafts,
[draftKey]: { query: page.query, activeIndex },
},
};
}
export function moveAddProjectActiveIndex(
@@ -214,37 +283,16 @@ export function moveAddProjectActiveIndex(
return next;
}
export interface AddProjectKeyInput {
key: string;
metaKey: boolean;
ctrlKey: boolean;
altKey: boolean;
shiftKey: boolean;
}
export type AddProjectKeyCommand =
| { kind: "tab"; tab: AddProjectTab }
| { kind: "move"; direction: "next" | "previous" }
| { kind: "submit" };
/** Keys the sheet claims besides Escape. Digits only act with the platform's Mod key. */
export const ADD_PROJECT_KEYS = ["Enter", "ArrowUp", "ArrowDown", "1", "2", "3"] as const;
export function resolveAddProjectKey(
input: AddProjectKeyInput,
isMac: boolean,
): AddProjectKeyCommand | null {
const modOnly =
(isMac ? input.metaKey && !input.ctrlKey : input.ctrlKey && !input.metaKey) &&
!input.altKey &&
!input.shiftKey;
const plain = !input.metaKey && !input.ctrlKey && !input.altKey && !input.shiftKey;
const tabIndex = ["1", "2", "3"].indexOf(input.key);
const tab = ADD_PROJECT_TABS[tabIndex];
if (tab && modOnly) return { kind: "tab", tab };
if (!plain) return null;
if (input.key === "ArrowDown") return { kind: "move", direction: "next" };
if (input.key === "ArrowUp") return { kind: "move", direction: "previous" };
if (input.key === "Enter") return { kind: "submit" };
return null;
export function moveAddProjectSelection(
activeIndex: number,
selectable: readonly boolean[],
direction: "next" | "previous",
): number {
if (!selectable.some(Boolean)) return 0;
let next = activeIndex;
for (let count = 0; count < selectable.length; count += 1) {
next = moveAddProjectActiveIndex(next, selectable.length, direction);
if (selectable[next]) return next;
}
return activeIndex;
}
@@ -1,114 +0,0 @@
import { useMemo } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Field, FormTextInput } from "@/components/ui/form-field";
import { isWeb } from "@/constants/platform";
import type { AddProjectActions } from "./use-add-project-actions";
import type { AddProjectFlowState, AddProjectHost } from "./model";
import { LocationField } from "./location-field";
import { joinDirectoryPath, validateNewFolderName } from "./options";
import type { AddProjectTabView } from "./tab-view";
export interface NewFolderTabView extends AddProjectTabView {
location: string;
destination: string;
/** Why the typed name cannot be a folder; null while empty or valid. */
nameError: string | null;
}
export function useNewFolderTab(input: {
state: AddProjectFlowState;
host: AddProjectHost | null;
defaultLocation: string;
actions: AddProjectActions;
}): NewFolderTabView {
const { state, host, defaultLocation, actions } = input;
const { name } = state.newFolder;
const location = state.newFolder.location ?? defaultLocation;
const trimmed = name.trim();
const nameError = trimmed ? validateNewFolderName(name) : null;
// Preview and create only a name that can be created, so the field never shows a path that
// escapes the location.
const previewName = trimmed && !nameError ? trimmed : null;
const canCreate = host?.canCreateDirectory === true;
return useMemo<NewFolderTabView>(
() => ({
rows: [],
activeIndex: 0,
notice: null,
location,
destination: previewName ? joinDirectoryPath(location, previewName) : location,
unavailable: canCreate ? null : "Update the host to create folders",
nameError,
primary: {
label: "Create project",
submit: canCreate && previewName ? () => actions.createFolder(name, location) : null,
},
}),
[actions, canCreate, location, name, nameError, previewName],
);
}
export function NewFolderTab({
view,
name,
hostId,
recommendedPaths,
disabled,
autoFocus,
onNameChange,
onLocationChange,
}: {
view: NewFolderTabView;
name: string;
hostId: string | null;
recommendedPaths: string[];
disabled: boolean;
/** Focus the field on mount; only with a hardware keyboard, so touch keeps the list in view. */
autoFocus: boolean;
onNameChange: (name: string) => void;
onLocationChange: (location: string) => void;
}) {
const editable = !disabled && !view.unavailable;
return (
<View style={styles.body}>
<Field
label="Name"
hint={view.unavailable ?? undefined}
error={view.nameError}
testID="add-project-flow-name-field"
>
<FormTextInput
initialValue={name}
onChangeText={onNameChange}
onSubmitEditing={isWeb ? undefined : (view.primary.submit ?? undefined)}
placeholder="my-project"
accessibilityLabel="Folder name"
autoFocus={autoFocus}
autoCapitalize="none"
autoCorrect={false}
returnKeyType="go"
editable={editable}
invalid={Boolean(view.nameError)}
testID="add-project-flow-input"
/>
</Field>
<LocationField
hostId={hostId}
location={view.location}
destination={view.destination}
recommendedPaths={recommendedPaths}
onChange={onLocationChange}
disabled={!editable}
testID="add-project-flow-location"
/>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
body: {
gap: theme.spacing[4],
},
}));
+112 -39
View File
@@ -3,7 +3,83 @@ import {
parseGitHubRemoteUrl,
parseGitRemoteLocation,
} from "@getpaseo/protocol/git-remote";
import type { GithubRepositoryChoice } from "./model";
import { shortenPath } from "@/utils/shorten-path";
import type { AddProjectHost, GithubRepositoryChoice } from "./model";
export type AddProjectMethodId = "directory-search" | "browse" | "github" | "new-directory";
export interface AddProjectMethodOption {
id: AddProjectMethodId;
label: string;
description: string;
disabled?: boolean;
}
export interface AddProjectPathOption {
id: string;
path: string;
displayPath: string;
secondaryText: string | null;
disabled: boolean;
}
export function filterAddProjectHosts(hosts: AddProjectHost[], query: string): AddProjectHost[] {
const normalized = query.trim().toLowerCase();
if (!normalized) return hosts;
return hosts.filter(
(host) =>
host.label.toLowerCase().includes(normalized) ||
host.serverId.toLowerCase().includes(normalized),
);
}
export function buildAddProjectMethods(host: AddProjectHost): AddProjectMethodOption[] {
if (!host.canAddProject) return [];
const options: AddProjectMethodOption[] = [];
options.push({
id: "directory-search",
label: "Search for directory",
description: `Find a directory on ${host.label}`,
});
if (host.canBrowse) {
options.push({
id: "browse",
label: "Browse",
description: "Choose or create a directory in Finder",
});
}
options.push({
id: "github",
label: "Clone from GitHub",
description: githubMethodDescription(host),
disabled: !host.canCloneGithubRepositories,
});
options.push({
id: "new-directory",
label: "New directory",
description: host.canCreateDirectory
? `Create an empty directory on ${host.label}`
: "Update this host to create directories",
disabled: !host.canCreateDirectory,
});
return options;
}
export function addProjectMethodEmptyText(host: AddProjectHost | null): string {
return host?.canAddProject === false
? "Update the host to use Add Project."
: "No matching options";
}
function githubMethodDescription(host: AddProjectHost): string {
if (!host.canCloneGithubRepositories) {
return "Update this host to clone GitHub repositories";
}
if (host.canSearchGithubRepositories) {
return "Search projects available to your GitHub account";
}
return "Enter a GitHub URL or owner/repo";
}
export function pathBaseName(path: string): string {
const trimmed = path.replace(/[\\/]+$/, "");
@@ -11,9 +87,6 @@ export function pathBaseName(path: string): string {
return parts[parts.length - 1] ?? trimmed;
}
/** Starts the id of every choice built from what the user typed. */
export const MANUAL_CHOICE_PREFIX = "manual:";
export function buildManualGithubRepositoryChoices(query: string): GithubRepositoryChoice[] {
const repo = query.trim();
if (!repo) return [];
@@ -24,7 +97,7 @@ export function buildManualGithubRepositoryChoices(query: string): GithubReposit
const remoteName = location ? pathBaseName(location.path).replace(/\.git$/u, "") : repo;
return [
{
id: `${MANUAL_CHOICE_PREFIX}${repo}`,
id: `manual:${repo}`,
nameWithOwner: identity?.repo ?? remoteName,
cloneUrl: repo,
description: "Clone this repository URL",
@@ -37,7 +110,7 @@ export function buildManualGithubRepositoryChoices(query: string): GithubReposit
if (!shorthand) return [];
const nameWithOwner = `${shorthand[1]}/${shorthand[2]}`;
return (["https", "ssh"] as const).map((cloneProtocol) => ({
id: `${MANUAL_CHOICE_PREFIX}${cloneProtocol}:${nameWithOwner}`,
id: `manual:${cloneProtocol}:${nameWithOwner}`,
nameWithOwner,
cloneUrl: nameWithOwner,
cloneProtocol,
@@ -46,21 +119,18 @@ export function buildManualGithubRepositoryChoices(query: string): GithubReposit
}));
}
/** The folder that holds `path`. A root keeps its separator: `C:\repo` gives `C:\`, not `C:`. */
export function parentDirectory(path: string): string | null {
const trimmed = path.replace(/[\\/]+$/, "");
// A share root (\\server\share) has no parent folder; `\\server` alone is not a directory.
if (/^[\\/]{2}[^\\/]+[\\/][^\\/]+$/u.test(trimmed)) return null;
const index = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
if (index < 0) return null;
const parent = trimmed.slice(0, index);
const isRoot = parent === "" || /^[A-Za-z]:$/u.test(parent);
return isRoot ? trimmed.slice(0, index + 1) : parent;
if (index === 0) return trimmed.slice(0, 1);
return trimmed.slice(0, index);
}
export function joinDirectoryPath(parent: string, name: string): string {
const separator = parent.includes("\\") && !parent.includes("/") ? "\\" : "/";
return `${parent.replace(/[\\/]+$/, "")}${separator}${name}`;
const trimmedParent = parent.replace(/[\\/]+$/, "");
const separator = trimmedParent.includes("\\") && !trimmedParent.includes("/") ? "\\" : "/";
return `${trimmedParent}${separator}${name}`;
}
export function buildSuggestedParentDirectories(projectPaths: string[]): string[] {
@@ -79,31 +149,34 @@ export function buildSuggestedParentDirectories(projectPaths: string[]): string[
return [...new Set(values)];
}
/**
* Where a new folder or clone goes when the user has not picked a location on this host: the last
* one used, else the parent of a recent project, else home. Only folders known to exist qualify;
* guesses like `~/dev` stay suggestions in the Location picker.
*/
export function defaultProjectLocation(input: {
remembered: string | undefined;
projectPaths: string[];
}): string {
const projectParent = input.projectPaths
.map(parentDirectory)
.find((parent): parent is string => parent !== null);
return input.remembered ?? projectParent ?? "~";
export function buildCloneLocationOptions(input: {
parents: string[];
repositoryName: string;
existingPaths: string[];
}): AddProjectPathOption[] {
const existing = new Set(input.existingPaths.map(pathIdentity));
const seen = new Set<string>();
return input.parents.flatMap((parent) => {
const path = joinDirectoryPath(parent, input.repositoryName);
const identity = pathIdentity(path);
if (seen.has(identity)) return [];
seen.add(identity);
const pathExists = existing.has(identity);
return [
{
id: parent,
path: parent,
displayPath: path,
secondaryText: pathExists ? "Already exists" : `Parent directory: ${parent}`,
disabled: pathExists,
},
];
});
}
/** The folder a clone of `nameWithOwner` checks out into; the host drops a trailing `.git`. */
export function checkoutName(nameWithOwner: string): string {
return pathBaseName(nameWithOwner).replace(/\.git$/u, "");
}
export function validateNewFolderName(name: string): string | null {
const trimmed = name.trim();
if (!trimmed || trimmed === "." || trimmed === "..") return "Enter a folder name";
if (/[\\/]/.test(trimmed)) return "Use a name without slashes";
// The host rejects a drive prefix on every platform.
if (/^[A-Za-z]:/u.test(trimmed)) return "Use a name without a drive letter";
return null;
function pathIdentity(path: string): string {
const normalized = shortenPath(path.trim()).replace(/\\/g, "/").replace(/\/+$/u, "");
return /^[A-Za-z]:\//u.test(normalized) || normalized.startsWith("//")
? normalized.toLowerCase()
: normalized;
}
@@ -1,2 +0,0 @@
/** The result list's test ID, which the web Enter check also uses to recognise a focused row. */
export const RESULTS_TEST_ID = "add-project-flow-results";
@@ -1,243 +0,0 @@
import { useCallback, useMemo, useRef, type ComponentType, type RefObject } from "react";
import { Check } from "lucide-react-native";
import { Text, View, type ScrollView as NativeScrollView } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { PressHighlight } from "@/components/ui/press-highlight";
import { ScrollView } from "@/components/ui/scroll-view";
import { useRevealActiveItem } from "@/components/ui/scroll-reveal";
import { Shortcut } from "@/components/ui/shortcut";
import { useHardwareKeyboardPresent } from "@/keyboard";
import { settingsStyles } from "@/styles/settings";
import type { Theme } from "@/styles/theme";
type RowIcon = ComponentType<{ size?: number; color?: string }>;
export interface ResultRow {
id: string;
title: string;
subtitle: string | null;
icon: RowIcon;
testID: string;
}
/** What the list says when it has no rows to show. */
export type ResultListNotice =
| { kind: "pending"; text: string }
| { kind: "empty"; text: string }
| { kind: "error"; text: string };
interface ResultListProps {
rows: ResultRow[];
activeIndex: number;
/** Shown in place of the rows when there are none, or above them for an error. */
notice: ResultListNotice | null;
onSelect: (index: number) => void;
disabled?: boolean;
testID: string;
}
const ENTER_KEYS = ["Enter"];
// Fixed line heights make a two-line row the same height on every platform.
const TITLE_LINE_HEIGHT = 18;
const SUBTITLE_LINE_HEIGHT = 16;
function RowGlyph({ icon: Icon, size, color }: { icon: RowIcon; size: number; color?: string }) {
return <Icon size={size} color={color} />;
}
const MutedRowGlyph = withUnistyles(RowGlyph, (theme: Theme) => ({
color: theme.colors.foregroundMuted,
}));
const AccentCheck = withUnistyles(Check, (theme: Theme) => ({ color: theme.colors.accent }));
const ThemedSpinner = withUnistyles(LoadingSpinner, (theme: Theme) => ({
color: theme.colors.foregroundMuted,
}));
/** Enter commits the active row when there is a keyboard; on touch, a check marks the choice. */
function ActiveMark() {
const keyboardPresent = useHardwareKeyboardPresent();
return keyboardPresent ? <Shortcut keys={ENTER_KEYS} /> : <AccentCheck size={16} />;
}
function ResultRowView({
row,
index,
active,
disabled,
activeItemRef,
onActiveLayout,
onSelect,
}: {
row: ResultRow;
index: number;
active: boolean;
disabled: boolean;
activeItemRef: RefObject<View | null>;
onActiveLayout: () => void;
onSelect: (index: number) => void;
}) {
const handlePress = useCallback(() => onSelect(index), [index, onSelect]);
const style = useMemo(
() => [
settingsStyles.row,
styles.row,
index > 0 && settingsStyles.rowBorder,
active && styles.rowActive,
],
[active, index],
);
const accessibilityState = useMemo(() => ({ selected: active, disabled }), [active, disabled]);
return (
<PressHighlight
ref={active ? activeItemRef : undefined}
onLayout={active ? onActiveLayout : undefined}
accessibilityRole="button"
accessibilityState={accessibilityState}
disabled={disabled}
onPress={handlePress}
// Tabbing to a row picks it, so Enter commits the row that has focus.
onFocus={handlePress}
style={style}
highlightStyle={styles.rowActive}
testID={row.testID}
>
<View style={styles.iconSlot}>
<MutedRowGlyph icon={row.icon} size={16} />
</View>
<View style={styles.rowText}>
<Text style={[settingsStyles.rowTitle, styles.rowTitle]} numberOfLines={1}>
{row.title}
</Text>
{row.subtitle ? (
<Text style={styles.rowSubtitle} numberOfLines={1}>
{row.subtitle}
</Text>
) : null}
</View>
{/* Reserved on every row so the active row's mark never shifts its text. */}
<View style={styles.trailingSlot}>{active ? <ActiveMark /> : null}</View>
</PressHighlight>
);
}
/**
* A card of choices with one active row. Arrow keys, taps, and keyboard focus move the active
* row; the sheet's primary action commits it. The list keeps the active row scrolled into view.
*/
export function ResultList({
rows,
activeIndex,
notice,
onSelect,
disabled = false,
testID,
}: ResultListProps) {
const scrollRef = useRef<NativeScrollView>(null);
const listKey = useMemo(() => rows.map((row) => row.id).join("\u0000"), [rows]);
const { activeItemRef, contentRef, onItemLayout, onViewportLayout, onScroll } =
useRevealActiveItem({ activeIndex, listKey, scrollRef });
const showNotice = notice && (rows.length === 0 || notice.kind === "error");
return (
<View style={styles.frame}>
{showNotice ? (
<View style={[settingsStyles.card, styles.noticeCard]} testID={`${testID}-notice`}>
{notice.kind === "pending" ? <ThemedSpinner size={14} /> : null}
<Text
style={notice.kind === "error" ? styles.noticeError : styles.noticeText}
numberOfLines={2}
>
{notice.text}
</Text>
</View>
) : null}
{rows.length > 0 ? (
<View style={[settingsStyles.card, styles.listCard]}>
<ScrollView
ref={scrollRef}
keyboardShouldPersistTaps="always"
onLayout={onViewportLayout}
onScroll={onScroll}
scrollEventThrottle={16}
showsVerticalScrollIndicator={false}
testID={testID}
>
<View ref={contentRef} collapsable={false}>
{rows.map((row, index) => (
<ResultRowView
key={row.id}
row={row}
index={index}
active={index === activeIndex}
disabled={disabled}
activeItemRef={activeItemRef}
onActiveLayout={onItemLayout}
onSelect={onSelect}
/>
))}
</View>
</ScrollView>
</View>
) : null}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
frame: {
flex: 1,
minHeight: 0,
gap: theme.spacing[3],
},
listCard: {
flexShrink: 1,
minHeight: 0,
},
// Every row is as tall as a two-line row, so rows without a subtitle do not break the rhythm.
row: {
minHeight: theme.spacing[3] * 2 + TITLE_LINE_HEIGHT + SUBTITLE_LINE_HEIGHT,
paddingVertical: theme.spacing[3],
justifyContent: "flex-start",
gap: theme.spacing[3],
},
rowActive: {
backgroundColor: theme.colors.surface2,
},
iconSlot: {
width: 16,
alignItems: "center",
},
rowText: {
flex: 1,
minWidth: 0,
},
rowTitle: {
lineHeight: TITLE_LINE_HEIGHT,
},
rowSubtitle: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
lineHeight: SUBTITLE_LINE_HEIGHT,
},
trailingSlot: {
minWidth: theme.spacing[6],
alignItems: "flex-end",
},
noticeCard: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
paddingHorizontal: theme.spacing[4],
paddingVertical: theme.spacing[4],
},
noticeText: {
flex: 1,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
noticeError: {
flex: 1,
color: theme.colors.statusDanger,
fontSize: theme.fontSize.base,
},
}));
@@ -1,70 +0,0 @@
import { describe, expect, it } from "vitest";
import { resolveSearch, type SearchAnswer } from "./search-result";
const EMPTY: string[] = [];
function answer(overrides: Partial<SearchAnswer<string>> = {}): SearchAnswer<string> {
return { hostId: "host-1", query: "app", items: ["/code/app"], error: null, ...overrides };
}
function resolve(overrides: Partial<Parameters<typeof resolveSearch<string>>[0]> = {}) {
return resolveSearch<string>({
enabled: true,
hostId: "host-1",
query: "app",
debouncedQuery: "app",
data: answer(),
failed: null,
empty: EMPTY,
...overrides,
});
}
describe("resolveSearch", () => {
it("shows the answer for the current query", () => {
expect(resolve()).toEqual({ items: ["/code/app"], pending: false, error: null });
});
it("keeps the last items while the next query is pending", () => {
expect(resolve({ query: "apps", debouncedQuery: "apps" })).toEqual({
items: ["/code/app"],
pending: true,
error: null,
});
});
it("never shows another host's answer, even for the same query", () => {
expect(resolve({ hostId: "host-2" })).toEqual({ items: [], pending: true, error: null });
});
it("drops the last query's error while the next query is pending", () => {
const failedAnswer = answer({ items: [], error: "Rate limited" });
expect(resolve({ data: failedAnswer })).toEqual({
items: [],
pending: false,
error: "Rate limited",
});
expect(resolve({ data: failedAnswer, query: "apps" })).toEqual({
items: [],
pending: true,
error: null,
});
});
it("shows a failed request only once the user stops typing", () => {
expect(resolve({ data: undefined, failed: "Unable to search" })).toEqual({
items: [],
pending: false,
error: "Unable to search",
});
expect(resolve({ data: undefined, failed: "Unable to search", query: "apps" })).toEqual({
items: [],
pending: true,
error: null,
});
});
it("is idle when disabled", () => {
expect(resolve({ enabled: false })).toEqual({ items: [], pending: false, error: null });
});
});
@@ -1,47 +0,0 @@
/**
* What a search shows while the user types. `items` keep the last results until the current
* query's results arrive, so rows do not flash away on every keystroke.
*/
export interface SearchResult<T> {
items: T[];
/** Results for the current query have not arrived yet. */
pending: boolean;
error: string | null;
}
/** One answer from the host: what it found for `query`, or why it could not search. */
export interface SearchAnswer<T> {
hostId: string | null;
query: string;
items: T[];
error: string | null;
}
/**
* Decides what to show for `query` on `hostId`. An answer from another host never shows. While
* the current query is pending the last items stay, but an old error does not.
*/
export function resolveSearch<T>(input: {
enabled: boolean;
hostId: string | null;
/** What the user typed. */
query: string;
/** The query the last request was sent for; it trails `query` while the user types. */
debouncedQuery: string;
/** The latest answer, which may be for an earlier query or another host. */
data: SearchAnswer<T> | undefined;
/** Why the request for `debouncedQuery` failed, if it did. */
failed: string | null;
empty: T[];
}): SearchResult<T> {
const { enabled, hostId, query, debouncedQuery, data, failed, empty } = input;
if (!enabled) return { items: empty, pending: false, error: null };
if (failed) {
return query === debouncedQuery
? { items: empty, pending: false, error: failed }
: { items: empty, pending: true, error: null };
}
const answer = data?.hostId === hostId ? data : undefined;
if (answer?.query === query) return { items: answer.items, pending: false, error: answer.error };
return { items: answer && !answer.error ? answer.items : empty, pending: true, error: null };
}
@@ -1,102 +0,0 @@
import { useMemo } from "react";
import { useFetchQuery } from "@/data/query";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { useHostRuntimeClient } from "@/runtime/host-runtime";
import type { GithubRepositoryChoice } from "./model";
import { resolveSearch, type SearchResult } from "./search-result";
export type { SearchResult } from "./search-result";
const SEARCH_DEBOUNCE_MS = 250;
const EMPTY_PATHS: string[] = [];
const EMPTY_REPOSITORIES: GithubRepositoryChoice[] = [];
/** Directories on the host matching `query`, debounced while the user types. */
export function useDirectorySearch(input: {
hostId: string | null;
query: string;
enabled: boolean;
}): SearchResult<string> {
const { hostId } = input;
const client = useHostRuntimeClient(hostId ?? "");
const debouncedQuery = useDebouncedValue(input.query, SEARCH_DEBOUNCE_MS);
const enabled = Boolean(client && input.enabled);
const search = useFetchQuery({
queryKey: ["add-project-flow-directories", hostId, debouncedQuery],
queryFn: async () => {
if (!client) throw new Error("Host is unavailable");
const payload = await client.getDirectorySuggestions({
query: debouncedQuery,
includeDirectories: true,
includeFiles: false,
limit: 30,
});
const items =
payload.entries?.flatMap((entry) => (entry.kind === "directory" ? [entry.path] : [])) ?? [];
return { hostId, query: debouncedQuery, items, error: payload.error ?? null };
},
enabled,
dataShape: "list",
retry: false,
staleTimeMs: 15_000,
});
const failed = search.isError ? "Unable to search folders" : null;
return useMemo(
() =>
resolveSearch({
enabled,
hostId,
query: input.query,
debouncedQuery,
data: search.data,
failed,
empty: EMPTY_PATHS,
}),
[debouncedQuery, enabled, failed, hostId, input.query, search.data],
);
}
/** GitHub repositories the host's account can see, matching `query`. */
export function useGithubRepositorySearch(input: {
hostId: string | null;
query: string;
enabled: boolean;
}): SearchResult<GithubRepositoryChoice> {
const { hostId } = input;
const client = useHostRuntimeClient(hostId ?? "");
const debouncedQuery = useDebouncedValue(input.query, SEARCH_DEBOUNCE_MS);
const enabled = Boolean(client && input.enabled);
const search = useFetchQuery({
queryKey: ["add-project-flow-github", hostId, debouncedQuery],
queryFn: async () => {
if (!client) throw new Error("Host is unavailable");
const payload = await client.searchGithubRepositories({ query: debouncedQuery, limit: 30 });
let error: string | null = payload.error ?? null;
if (!error && payload.available === false) error = "GitHub search is unavailable";
return {
hostId,
query: debouncedQuery,
items: error ? EMPTY_REPOSITORIES : payload.repositories,
error,
};
},
enabled,
dataShape: "list",
retry: false,
staleTimeMs: 15_000,
});
const failed = search.isError ? "Unable to search GitHub" : null;
return useMemo(
() =>
resolveSearch({
enabled,
hostId,
query: input.query,
debouncedQuery,
data: search.data,
failed,
empty: EMPTY_REPOSITORIES,
}),
[debouncedQuery, enabled, failed, hostId, input.query, search.data],
);
}
@@ -1,29 +0,0 @@
import type { ResultListNotice, ResultRow } from "./result-list";
/** What the sheet needs from the current tab to drive its keys and its primary button. */
export interface AddProjectTabView {
/** The rows Up and Down walk; empty for a tab without a list. */
rows: ResultRow[];
/** The active row, or -1 when none is: an older search's rows, or a pick the new answer dropped. */
activeIndex: number;
notice: ResultListNotice | null;
/** Why this host cannot do what the tab offers; the tab's fields are read-only while set. */
unavailable: string | null;
primary: {
label: string;
/** Absent when there is nothing to commit yet. */
submit: (() => void) | null;
};
}
/**
* Where the user's pick sits in `rows`. Without a pick, the first row is the default. A pick that
* a new answer dropped is not swapped for another row: nothing is active until the user picks again.
*/
export function resolveActiveIndex(
rows: readonly { id: string }[],
selectedId: string | null,
): number {
if (selectedId === null) return rows.length > 0 ? 0 : -1;
return rows.findIndex((row) => row.id === selectedId);
}
@@ -1,182 +0,0 @@
import { useCallback, useEffect, useRef, type Dispatch, type SetStateAction } from "react";
import { router } from "expo-router";
import type { WorkspaceProjectDescriptorPayload } from "@getpaseo/protocol/messages";
import { pickDirectory } from "@/desktop/pick-directory";
import { getOpenProjectFailureReason, registerProjectDescriptor } from "@/hooks/open-project";
import { useCloneGithubProject, useOpenProject } from "@/hooks/use-open-project";
import { getHostRuntimeStore, useHostRuntimeClient } from "@/runtime/host-runtime";
import { useAddProjectFlowStore } from "@/stores/add-project-flow-store";
import { usePanelStore } from "@/stores/panel-store";
import { useSessionStore } from "@/stores/session-store";
import { buildNewWorkspaceRoute } from "@/utils/host-routes";
import {
failAddProjectSubmission,
startAddProjectSubmission,
type AddProjectFlowState,
type GithubRepositoryChoice,
} from "./model";
/** A failure found before any work starts, shown the same way as one the host reports. */
function rejectSubmission(state: AddProjectFlowState, message: string): AddProjectFlowState {
return failAddProjectSubmission(startAddProjectSubmission(state), message);
}
export interface AddProjectActions {
openFolder: (path: string) => void;
browse: () => void;
clone: (repository: GithubRepositoryChoice, location: string) => void;
/** Expects a name that passed `validateNewFolderName`; the New folder tab only offers those. */
createFolder: (name: string, location: string) => void;
}
/** What a submission's work reports: the project to open, or why it failed. */
type SubmissionOutcome =
| { ok: true; project: WorkspaceProjectDescriptorPayload }
| { ok: false; error: string };
/**
* The three ways a project gets added. Each one records its progress and failure in the flow
* state and, on success, closes the flow and opens a new workspace for the project.
*/
export function useAddProjectActions(input: {
hostId: string | null;
setState: Dispatch<SetStateAction<AddProjectFlowState>>;
onClose: () => void;
}): AddProjectActions {
const { hostId, setState, onClose } = input;
const client = useHostRuntimeClient(hostId ?? "");
const openProject = useOpenProject(hostId);
const cloneGithubProject = useCloneGithubProject(hostId);
const setHasHydratedWorkspaces = useSessionStore((store) => store.setHasHydratedWorkspaces);
const rememberLocation = useAddProjectFlowStore((store) => store.rememberLocation);
// The running submission, if any. It belongs to the open sheet and the host it started on:
// closing the sheet or losing that host abandons it, so a late result neither navigates nor
// blocks the next submission.
const submissionRef = useRef<symbol | null>(null);
useEffect(
() => () => {
submissionRef.current = null;
},
[hostId],
);
/** Runs one submission at a time and opens a new workspace for the project it adds. */
const run = useCallback(
async (serverId: string, work: () => Promise<SubmissionOutcome>, fallbackError: string) => {
if (submissionRef.current) return;
const submission = Symbol("add-project-submission");
submissionRef.current = submission;
const isCurrent = () => submissionRef.current === submission;
setState(startAddProjectSubmission);
let outcome: SubmissionOutcome;
try {
outcome = await work();
} catch (error) {
const message = error instanceof Error && error.message ? error.message : fallbackError;
outcome = { ok: false, error: message };
}
if (!isCurrent()) return;
submissionRef.current = null;
if (!outcome.ok) {
setState((state) => failAddProjectSubmission(state, outcome.error));
return;
}
onClose();
usePanelStore.getState().showMobileAgent();
router.push(
buildNewWorkspaceRoute({
serverId,
projectId: outcome.project.projectId,
sourceDirectory: outcome.project.projectRootPath,
displayName: outcome.project.projectDisplayName,
}),
);
},
[onClose, setState],
);
const openFolder = useCallback(
(path: string) => {
if (!hostId) return;
void run(
hostId,
async () => {
const result = await openProject(path);
if (result.ok) return { ok: true, project: result.project };
if (getOpenProjectFailureReason(result) === "directory_not_found") {
return { ok: false, error: "Folder not found" };
}
return { ok: false, error: result.error ?? "Unable to add project" };
},
"Unable to add project",
);
},
[hostId, openProject, run],
);
// The desktop folder dialog is modal to the window, so nothing else can start while it is open.
const browse = useCallback(() => {
if (!hostId || submissionRef.current) return;
void (async () => {
try {
const path = await pickDirectory();
if (path) openFolder(path);
} catch {
setState((state) => rejectSubmission(state, "Unable to browse for a folder"));
}
})();
}, [hostId, openFolder, setState]);
const clone = useCallback(
(repository: GithubRepositoryChoice, location: string) => {
if (!hostId) return;
void run(
hostId,
async () => {
const result = await cloneGithubProject(
repository.cloneUrl,
location,
repository.cloneProtocol,
);
if (!result.ok) return { ok: false, error: result.error ?? "Unable to clone project" };
rememberLocation(hostId, location);
return { ok: true, project: result.project };
},
"Unable to clone project",
);
},
[cloneGithubProject, hostId, rememberLocation, run],
);
const createFolder = useCallback(
(name: string, location: string) => {
if (!hostId) return;
void run(
hostId,
async () => {
if (!client) return { ok: false, error: "Unable to create folder" };
const payload = await client.createProjectDirectory({
parentPath: location,
name: name.trim(),
});
if (payload.error || !payload.project) {
return { ok: false, error: payload.error ?? "Unable to create folder" };
}
registerProjectDescriptor({
serverId: hostId,
project: payload.project,
upsertProject: (serverId, project) =>
getHostRuntimeStore().acceptProjectSnapshot(serverId, project),
setHasHydratedWorkspaces,
});
rememberLocation(hostId, location);
return { ok: true, project: payload.project };
},
"Unable to create folder",
);
},
[client, hostId, rememberLocation, run, setHasHydratedWorkspaces],
);
return { openFolder, browse, clone, createFolder };
}
@@ -1,51 +0,0 @@
import { useMemo } from "react";
import { getIsElectronRuntime } from "@/constants/layout";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { useHosts, useHostRuntimeConnectionStatuses } from "@/runtime/host-runtime";
import { useHostFeatureMap } from "@/runtime/host-features";
import { orderHostsLocalFirst } from "@/types/host-connection";
import type { AddProjectHost } from "./model";
/** Every host, whether it is online, and what each can do in Add project, the local host first. */
export function useAddProjectHosts(): AddProjectHost[] {
const hosts = useHosts();
const hostIds = useMemo(() => hosts.map((host) => host.serverId), [hosts]);
const connectionStatuses = useHostRuntimeConnectionStatuses(hostIds);
const projectAddByHost = useHostFeatureMap(hostIds, "projectAdd");
// COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15.
const stableProjectIdentityByHost = useHostFeatureMap(hostIds, "stableProjectIdentity");
// COMPAT(projectGithubClone): added in v0.1.108, remove gate after 2027-01-15.
const githubCloneByHost = useHostFeatureMap(hostIds, "projectGithubClone");
// COMPAT(workspaceGithubRepositorySearch): added in v0.1.108, remove gate after 2027-01-15.
const githubSearchByHost = useHostFeatureMap(hostIds, "workspaceGithubRepositorySearch");
// COMPAT(projectCreateDirectory): added in v0.1.108, remove gate after 2027-01-15.
const createDirectoryByHost = useHostFeatureMap(hostIds, "projectCreateDirectory");
const localServerId = useLocalDaemonServerId();
return useMemo<AddProjectHost[]>(() => {
return orderHostsLocalFirst(hosts, localServerId).map((host) => {
const canAddProject =
projectAddByHost.get(host.serverId) === true &&
stableProjectIdentityByHost.get(host.serverId) === true;
return {
serverId: host.serverId,
label: host.label,
online: connectionStatuses.get(host.serverId) === "online",
canAddProject,
canBrowse: canAddProject && getIsElectronRuntime() && localServerId === host.serverId,
canCloneGithubRepositories: githubCloneByHost.get(host.serverId) === true,
canSearchGithubRepositories: githubSearchByHost.get(host.serverId) === true,
canCreateDirectory: createDirectoryByHost.get(host.serverId) === true,
};
});
}, [
connectionStatuses,
createDirectoryByHost,
githubCloneByHost,
githubSearchByHost,
hosts,
localServerId,
projectAddByHost,
stableProjectIdentityByHost,
]);
}
+2 -3
View File
@@ -8,9 +8,8 @@
* rules, the icon registry, the row and modal chrome) is internal; import from
* `@/agent-profiles`, never a path inside it.
*
* `useAgentProfilePicker` deliberately hands the picker — and the Command Center,
* which offers the same rows — a flat row view model and one `applyProfile(id)`
* callback rather than the profiles themselves: what
* `useAgentProfilePicker` deliberately hands the picker a flat row view model
* and one `applyProfile(id)` callback rather than the profiles themselves: what
* a profile contains, and how it reaches a live agent versus a draft, stays in
* here.
*/
@@ -1,21 +0,0 @@
import { describe, expect, it } from "vitest";
import type { AgentProfile } from "@getpaseo/protocol/messages";
import { selectApplicableProfiles } from "./applicable-profiles";
function profile(id: string, provider: string, name = id): AgentProfile {
return { id, name, provider };
}
describe("selectApplicableProfiles", () => {
it("keeps only profiles naming a provider the composer can run", () => {
const claude = profile("a", "claude");
const codex = profile("b", "codex");
expect(selectApplicableProfiles([claude, codex], ["claude"])).toEqual([claude]);
});
it("keeps the first profile when a stored config repeats an id", () => {
const first = profile("same", "claude", "First");
const second = profile("same", "claude", "Second");
expect(selectApplicableProfiles([first, second], ["claude"])).toEqual([first]);
});
});
@@ -1,22 +0,0 @@
import type { AgentProfile } from "@getpaseo/protocol/messages";
/**
* The profiles a composer can offer: those naming a provider it can run, one
* per id. The daemon stores whatever list it is given, so a hand-edited config
* can repeat an id; the first entry wins, which is also the one `applyProfile`
* resolves, and every surface that keys on the id stays unique.
*/
export function selectApplicableProfiles(
profiles: readonly AgentProfile[],
availableProviders: readonly string[],
): AgentProfile[] {
const available = new Set(availableProviders);
const seenIds = new Set<string>();
const applicable: AgentProfile[] = [];
for (const profile of profiles) {
if (!available.has(profile.provider) || seenIds.has(profile.id)) continue;
seenIds.add(profile.id);
applicable.push(profile);
}
return applicable;
}
@@ -13,7 +13,6 @@ import {
toAgentConfigApply,
type MaterializedAgentProfile,
} from "./materialize-profile";
import { selectApplicableProfiles } from "./applicable-profiles";
import { buildAgentProfileTags } from "./profile-summary";
import { useAgentProfiles } from "./use-agent-profiles";
@@ -81,7 +80,8 @@ export function useAgentProfilePicker(
if (!isSupported || !profiles) {
return [];
}
return selectApplicableProfiles(profiles, availableProviders);
const available = new Set(availableProviders);
return profiles.filter((profile) => available.has(profile.provider));
}, [availableProviders, isSupported, profiles]);
const formatFeatureCount = useCallback(
@@ -16,7 +16,6 @@ function TestIcon() {
}
const LABELS: AgentControlContributionSource["labels"] = {
profile: "Profile",
model: "Model",
thinking: "Thinking",
mode: "Mode",
@@ -24,7 +23,6 @@ const LABELS: AgentControlContributionSource["labels"] = {
fast: "Fast",
on: "On",
off: "Off",
profileKeywords: "profile preset",
modelKeywords: "model switch",
thinkingKeywords: "reasoning effort",
modeKeywords: "access permission",
@@ -33,7 +31,6 @@ const LABELS: AgentControlContributionSource["labels"] = {
};
const ICONS: AgentControlContributionSource["icons"] = {
profile: () => TestIcon,
provider: () => TestIcon,
thinking: TestIcon,
planMode: TestIcon,
@@ -137,43 +134,6 @@ const CLAUDE_MODES: AgentMode[] = [
];
describe("Command Center agent-control contributions", () => {
it("offers each profile as a choice that applies it, searchable by its summary", () => {
const applied: string[] = [];
const contributions = buildAgentControlContributions({
...makeSource({ provider: null }),
profiles: {
rows: [
{
id: "reviewer",
name: "Reviewer",
summary: "Claude Code · Opus 5 · Plan",
icon: "eye",
color: "blue",
},
],
apply: (profileId) => {
applied.push(profileId);
},
},
}).filter((contribution) => contribution.group === "profiles");
expect(contributions).toHaveLength(1);
expect(contributions[0]).toMatchObject({
id: "profiles:reviewer",
groupRank: 0.9,
keywords: ["profile preset", "Claude Code · Opus 5 · Plan"],
presentation: {
kind: "choice",
path: ["Profile", "Reviewer"],
selected: false,
testId: "command-center-profile-host:agent:reviewer",
},
});
contributions[0].run();
contributions[0].run();
expect(applied).toEqual(["reviewer", "reviewer"]);
});
it("omits mode-derived choices when no mode control is available", () => {
const contributions = buildAgentControlContributions({
...makeSource({
@@ -16,7 +16,6 @@ import {
import type { CommandCenterContribution, CommandCenterIcon } from "./contributions";
const GROUP_RANK = {
profiles: 0.9,
models: 1,
thinking: 1.1,
modes: 1.2,
@@ -25,7 +24,6 @@ const GROUP_RANK = {
} as const;
export interface AgentControlContributionLabels {
profile: string;
model: string;
thinking: string;
mode: string;
@@ -33,7 +31,6 @@ export interface AgentControlContributionLabels {
fast: string;
on: string;
off: string;
profileKeywords: string;
modelKeywords: string;
thinkingKeywords: string;
modeKeywords: string;
@@ -45,7 +42,6 @@ export function buildAgentControlContributionLabels(
t: (key: string) => string,
): AgentControlContributionLabels {
return {
profile: t("shell.commandCenter.profileGroupLabel"),
model: t("shell.commandCenter.modelGroupLabel"),
thinking: t("shell.commandCenter.thinkingGroupLabel"),
mode: t("shell.commandCenter.modeGroupLabel"),
@@ -53,7 +49,6 @@ export function buildAgentControlContributionLabels(
fast: t("shell.commandCenter.fastModeGroupLabel"),
on: t("shell.commandCenter.settingOn"),
off: t("shell.commandCenter.settingOff"),
profileKeywords: t("shell.commandCenter.profileSearchKeywords"),
modelKeywords: t("shell.commandCenter.modelSearchKeywords"),
thinkingKeywords: t("shell.commandCenter.thinkingSearchKeywords"),
modeKeywords: t("shell.commandCenter.modeSearchKeywords"),
@@ -63,7 +58,6 @@ export function buildAgentControlContributionLabels(
}
export interface AgentControlContributionIcons {
profile(profile: AgentControlProfile): CommandCenterIcon;
provider(provider: AgentProvider): CommandCenterIcon;
thinking: CommandCenterIcon;
planMode: CommandCenterIcon;
@@ -89,27 +83,12 @@ interface CommandCenterChoiceGroup {
choices: readonly CommandCenterChoice[];
}
/** A profile as the command center offers it: applied in one step, never "selected". */
export interface AgentControlProfile {
id: string;
name: string;
/** "Claude Code · Opus 5 · Plan · Think hard" */
summary: string;
icon: string;
color: string;
}
export interface AgentControlContributionSource {
serverId: string;
ownerKey: string;
provider: string | null;
labels: AgentControlContributionLabels;
icons: AgentControlContributionIcons;
/** Absent when the host has no profiles to offer this surface. */
profiles?: {
rows: readonly AgentControlProfile[];
apply(profileId: string): void;
};
models: {
providers: readonly ProviderSelectorProvider[];
selectedProvider: string | null;
@@ -159,30 +138,6 @@ function buildContributions(
return contributions;
}
function buildProfileGroup(source: AgentControlContributionSource): CommandCenterChoiceGroup {
const profiles = source.profiles;
const choices = (profiles?.rows ?? []).map(
(profile): CommandCenterChoice => ({
id: profile.id,
path: [profile.name],
keywords: [profile.summary],
icon: source.icons.profile(profile),
// Applying a profile writes its values and leaves nothing bound to it,
// so no profile is ever the current choice.
selected: false,
testId: `command-center-profile-${source.serverId}:${source.ownerKey}:${profile.id}`,
select: () => profiles?.apply(profile.id),
}),
);
return {
id: "profiles",
rank: GROUP_RANK.profiles,
label: source.labels.profile,
keywords: [source.labels.profileKeywords],
choices,
};
}
function buildModelGroup(source: AgentControlContributionSource): CommandCenterChoiceGroup {
const choices: CommandCenterChoice[] = [];
for (const provider of source.models.providers) {
@@ -351,7 +306,7 @@ function buildFastModeGroup(source: AgentControlContributionSource): CommandCent
export function buildAgentControlContributions(
source: AgentControlContributionSource,
): CommandCenterContribution[] {
const groups = [buildProfileGroup(source), buildModelGroup(source)];
const groups = [buildModelGroup(source)];
if (source.provider) {
groups.push(
buildThinkingGroup(source),
@@ -8,7 +8,6 @@ import {
PlanModeIcon,
ThinkingIcon,
} from "@/agent-controls/icons";
import { AgentProfileGlyph, type AgentProfilePicker } from "@/agent-profiles";
import { useProviderIcons } from "@/components/provider-icons";
import type { ComposerOptionControls } from "@/agent-controls/option-controls";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
@@ -16,9 +15,7 @@ import {
buildAgentControlContributions,
buildAgentControlContributionLabels,
type AgentControlContributionSource,
type AgentControlProfile,
} from "./agent-control-contributions";
import type { CommandCenterIcon, CommandCenterIconProps } from "./contributions";
import { getCommandCenterIcon } from "./icon";
import { useCommandCenterActions } from "./provider";
@@ -27,8 +24,6 @@ export interface AgentControlCommandCenterSource {
ownerKey: string;
provider: string | null | undefined;
providerDefinitions: AgentProviderDefinition[];
/** The same profiles the model picker offers this composer; `null` when the host has none. */
profiles: AgentProfilePicker | null;
models: {
providers: readonly ProviderSelectorProvider[];
selectedProvider: string | null | undefined;
@@ -49,27 +44,6 @@ export interface AgentControlCommandCenterSource {
optionControls: ComposerOptionControls | null;
}
const profileIcons = new Map<string, CommandCenterIcon>();
/** One stable component per icon and colour, so results don't remount on every rebuild. */
function getProfileCommandCenterIcon(profile: AgentControlProfile): CommandCenterIcon {
const key = `${profile.icon}:${profile.color}`;
const cached = profileIcons.get(key);
if (cached) return cached;
function ProfileCommandCenterIcon({ size }: CommandCenterIconProps) {
return <AgentProfileGlyph icon={profile.icon} color={profile.color} size={size} />;
}
profileIcons.set(key, ProfileCommandCenterIcon);
return ProfileCommandCenterIcon;
}
function buildProfileContributionSource(
profiles: AgentProfilePicker | null,
): Pick<AgentControlContributionSource, "profiles"> {
if (!profiles) return {};
return { profiles: { rows: profiles.rows, apply: profiles.applyProfile } };
}
const NO_OPTION_CONTROLS: ComposerOptionControls = {
controls: [],
options: {},
@@ -109,7 +83,7 @@ export function useAgentControlCommandCenterActions(input: {
}): void {
const { t } = useTranslation();
const { controls } = input;
const { optionControls, models, modes, profiles, thinking } = controls;
const { optionControls, models, modes, thinking } = controls;
const getProviderIcon = useProviderIcons(controls.serverId);
const actions = useMemo(
() =>
@@ -119,7 +93,6 @@ export function useAgentControlCommandCenterActions(input: {
provider: controls.provider ?? null,
labels: buildAgentControlContributionLabels(t),
icons: {
profile: getProfileCommandCenterIcon,
provider: (provider) => getCommandCenterIcon(getProviderIcon(provider)),
thinking: getCommandCenterIcon(ThinkingIcon),
planMode: getCommandCenterIcon(PlanModeIcon),
@@ -135,7 +108,6 @@ export function useAgentControlCommandCenterActions(input: {
selectedModelId: models.selectedModelId ?? null,
select: models.select,
},
...buildProfileContributionSource(profiles),
thinking: {
options: thinking.options ?? [],
selectedId: thinking.selectedId ?? null,
@@ -163,7 +135,6 @@ export function useAgentControlCommandCenterActions(input: {
modes?.options,
modes?.select,
modes?.selectedId,
profiles,
thinking.options,
thinking.select,
thinking.selectedId,
@@ -597,16 +597,6 @@ export interface AdaptiveModalSheetProps {
contentStyle?: StyleProp<ViewStyle>;
/** Re-establishes caller-owned contexts inside the native or compact sheet portal. */
contextBridge?: ContextBridge | null;
/**
* Keys the body handles while the sheet is the top overlay, such as list navigation. Escape
* always closes the sheet. Return true from `onKeyDown` to claim the key.
*/
keyboard?: SheetKeyboard;
}
export interface SheetKeyboard {
keys: readonly string[];
onKeyDown: (event: KeyboardInputEvent) => boolean;
}
/**
@@ -706,7 +696,6 @@ export function AdaptiveModalSheet({
contentStyle,
bodyStyle,
contextBridge = null,
keyboard,
}: AdaptiveModalSheetProps) {
const { t } = useTranslation();
const isMobile = useIsCompactFormFactor();
@@ -765,21 +754,16 @@ export function AdaptiveModalSheet({
const handleOverlayKeyDown = useCallback(
(event: KeyboardInputEvent) => {
if (event.key !== "Escape") {
if (!keyboard?.onKeyDown(event)) return false;
event.preventDefault();
return true;
}
if (event.key !== "Escape") return false;
event.preventDefault();
event.stopPropagation();
onClose();
return true;
},
[keyboard, onClose],
[onClose],
);
const overlayKeys = useMemo(() => ["Escape", ...(keyboard?.keys ?? [])], [keyboard?.keys]);
const setOverlayScope = useOverlayRegistration({
keys: overlayKeys,
keys: ["Escape"],
active: visible,
layer: modalLayer,
onKeyDown: handleOverlayKeyDown,
@@ -1,4 +1,4 @@
import { AddProjectFlow } from "@/add-project-flow";
import { AddProjectFlow } from "@/components/add-project-flow";
import { useAddProjectFlowStore } from "@/stores/add-project-flow-store";
export function AddProjectFlowHost() {
File diff suppressed because it is too large Load Diff
@@ -6,7 +6,6 @@ import type {
import {
resolveInitialModelBrowserView,
resolveModelBrowserAllView,
filterAndRankProfileRows,
groupProfilesByProviderModel,
resolveModelBrowserScrolling,
} from "./model-browser-view";
@@ -156,12 +155,7 @@ describe("model browser all view", () => {
it("browses providers while the query is empty", () => {
expect(
resolveModelBrowserAllView({
providers,
profiles: [],
normalizedQuery: "",
isSearchFocused: false,
}),
resolveModelBrowserAllView({ providers, normalizedQuery: "", isSearchFocused: false }),
).toEqual({
kind: "browse",
});
@@ -170,7 +164,6 @@ describe("model browser all view", () => {
it("shows every searchable model as soon as empty search receives focus", () => {
const view = resolveModelBrowserAllView({
providers,
profiles: [],
normalizedQuery: "",
isSearchFocused: true,
});
@@ -187,7 +180,6 @@ describe("model browser all view", () => {
it("ranks the same model label across every provider that offers it", () => {
const view = resolveModelBrowserAllView({
providers,
profiles: [],
normalizedQuery: "opus",
isSearchFocused: true,
});
@@ -202,7 +194,6 @@ describe("model browser all view", () => {
it("matches models by their provider label", () => {
const view = resolveModelBrowserAllView({
providers,
profiles: [],
normalizedQuery: "codex",
isSearchFocused: true,
});
@@ -216,7 +207,6 @@ describe("model browser all view", () => {
expect(
resolveModelBrowserAllView({
providers,
profiles: [],
normalizedQuery: "zzzz",
isSearchFocused: true,
}),
@@ -238,48 +228,9 @@ describe("model browser all view", () => {
expect(
resolveModelBrowserAllView({
providers: [loading, failed],
profiles: [],
normalizedQuery: "opus",
isSearchFocused: true,
}),
).toEqual({ kind: "noSearchMatches" });
});
});
describe("model browser profile search", () => {
const claude = provider("claude", "Claude Code", [
modelRow("claude", "Claude Code", "opus-5", "Opus 5"),
]);
const reviewer = { id: "reviewer", name: "Reviewer", summary: "Claude Code · Opus 5 · Plan" };
const quick = { id: "quick", name: "Quick fix", summary: "Codex · GPT-5.4" };
const profiles = [reviewer, quick];
it("offers profiles whose name matches the query", () => {
const view = resolveModelBrowserAllView({
providers: [claude],
profiles,
normalizedQuery: "review",
isSearchFocused: true,
});
expect(view).toEqual({ kind: "searchResults", profiles: [reviewer], rows: [] });
});
it("offers profiles whose summary names the queried model next to the model itself", () => {
const view = resolveModelBrowserAllView({
providers: [claude],
profiles,
normalizedQuery: "opus",
isSearchFocused: true,
});
expect(view.kind === "searchResults" ? view.profiles : []).toEqual([reviewer]);
expect(view.kind === "searchResults" ? view.rows.map((row) => row.modelId) : []).toEqual([
"opus-5",
]);
});
it("lists every profile while the focused query is empty", () => {
expect(filterAndRankProfileRows(profiles, "")).toEqual(profiles);
});
});
@@ -1,4 +1,3 @@
import { compareMatchScores, scoreTextFields } from "@getpaseo/protocol/search/text-match";
import {
filterAndRankModelRows,
getAllProviderModelRows,
@@ -50,55 +49,30 @@ export function groupProfilesByProviderModel<T extends ModelProfileRef>(
return lookup;
}
/** What a profile row offers search: its name and its "Claude Code · Opus 5 · Plan" summary. */
export interface SearchableProfileRow {
name: string;
summary: string;
}
/** Profiles matching the query, best first. An empty query keeps every profile in order. */
export function filterAndRankProfileRows<T extends SearchableProfileRow>(
rows: readonly T[],
normalizedQuery: string,
): T[] {
if (!normalizedQuery) return [...rows];
return rows
.map((row) => ({ row, score: scoreTextFields(normalizedQuery, [row.name, row.summary]) }))
.filter((entry): entry is { row: T; score: NonNullable<typeof entry.score> } =>
Boolean(entry.score),
)
.sort((a, b) => compareMatchScores(a.score, b.score) || a.row.name.localeCompare(b.row.name))
.map((entry) => entry.row);
}
/** What the root view shows: the provider drill-down, or ranked cross-provider results. */
export type ModelBrowserAllView<T extends SearchableProfileRow> =
export type ModelBrowserAllView =
| { kind: "browse" }
| { kind: "searchResults"; profiles: T[]; rows: ProviderSelectionModelRow[] }
| { kind: "searchResults"; rows: ProviderSelectionModelRow[] }
| { kind: "noSearchMatches" };
export function resolveModelBrowserAllView<T extends SearchableProfileRow>({
export function resolveModelBrowserAllView({
providers,
profiles,
normalizedQuery,
isSearchFocused,
}: {
providers: ProviderSelectorProvider[];
/** Profiles the search may offer; empty when the surface shows none. */
profiles: readonly T[];
normalizedQuery: string;
isSearchFocused: boolean;
}): ModelBrowserAllView<T> {
}): ModelBrowserAllView {
if (!normalizedQuery && !isSearchFocused) {
return { kind: "browse" };
}
const allRows = getAllProviderModelRows(providers);
const rows = normalizedQuery ? filterAndRankModelRows(allRows, normalizedQuery) : allRows;
const matchedProfiles = filterAndRankProfileRows(profiles, normalizedQuery);
if (rows.length === 0 && matchedProfiles.length === 0) {
if (rows.length === 0) {
return { kind: "noSearchMatches" };
}
return { kind: "searchResults", profiles: matchedProfiles, rows };
return { kind: "searchResults", rows };
}
/** Where the picker lands when it opens. A sole provider skips the redundant root view. */
+16 -83
View File
@@ -56,7 +56,6 @@ import { useProviderSettingsStore } from "@/stores/provider-settings-store";
import { useCurrentOverlayLayer } from "@/lib/overlay-root";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import {
filterAndRankProfileRows,
groupProfilesByProviderModel,
resolveInitialModelBrowserView,
resolveModelBrowserAllView,
@@ -985,38 +984,6 @@ function AgentProfilesPickerContent({
);
}
/**
* Profiles that match a search, above the matching models. The models get their
* own heading so they don't read as part of the profiles section.
*/
function ProfileSearchResultsHeader({
rows,
hasModelRows,
onApplyProfile,
onEditProfiles,
}: {
rows: AgentProfilePickerRowModel[];
hasModelRows: boolean;
onApplyProfile?: (profileId: string) => void;
onEditProfiles?: () => void;
}) {
const { t } = useTranslation();
return (
<View>
<AgentProfilesPickerSection
rows={rows}
onApplyProfile={onApplyProfile}
onEditProfiles={onEditProfiles}
/>
{hasModelRows ? (
<View style={styles.sectionHeading}>
<Text style={styles.sectionHeadingText}>{t("modelSelector.models")}</Text>
</View>
) : null}
</View>
);
}
function GroupProviderButton({
provider,
serverId,
@@ -1353,39 +1320,24 @@ function ProviderModelBrowserContent({
() => profiles?.rows.filter((row) => row.provider === view.providerId) ?? [],
[profiles, view.providerId],
);
const matchedProfileRows = useMemo(
() => filterAndRankProfileRows(providerProfileRows, normalizedQuery),
[normalizedQuery, providerProfileRows],
);
const profileHeader = useMemo(() => {
if (!showProfilesSection || !profiles) return undefined;
if (normalizedQuery.length === 0) {
return (
const profileHeader = useMemo(
() =>
normalizedQuery.length === 0 && showProfilesSection && profiles ? (
<AgentProfilesPickerContent
rows={providerProfileRows}
onApplyProfile={onApplyProfile}
onEditProfiles={onEditProfiles}
/>
);
}
return matchedProfileRows.length > 0 ? (
<ProfileSearchResultsHeader
rows={matchedProfileRows}
hasModelRows={visibleRows.length > 0}
onApplyProfile={onApplyProfile}
onEditProfiles={onEditProfiles}
/>
) : undefined;
}, [
matchedProfileRows,
normalizedQuery,
onApplyProfile,
onEditProfiles,
profiles,
providerProfileRows,
showProfilesSection,
visibleRows.length,
]);
) : undefined,
[
normalizedQuery,
onApplyProfile,
onEditProfiles,
profiles,
providerProfileRows,
showProfilesSection,
],
);
if (!provider) return <ModelSearchEmptyState />;
const selection = provider.modelSelection;
@@ -1409,9 +1361,8 @@ function ProviderModelBrowserContent({
/>
);
}
// Profile-only results still go through the list: it owns scrolling.
if (visibleRows.length === 0 && !profileHeader) {
return <ModelSearchEmptyState />;
if (visibleRows.length === 0) {
return profileHeader ?? <ModelSearchEmptyState />;
}
return (
<ModelRowList
@@ -1465,33 +1416,16 @@ function ModelBrowserContent({
: null,
[providers, view],
);
const searchableProfileRows = useMemo(
() => (showProfilesSection ? (profiles?.rows ?? []) : []),
[profiles, showProfilesSection],
);
const allView = useMemo(
() =>
resolveModelBrowserAllView({
providers,
profiles: searchableProfileRows,
normalizedQuery,
isSearchFocused: searchAllOnFocus && isSearchFocused,
}),
[isSearchFocused, normalizedQuery, providers, searchAllOnFocus, searchableProfileRows],
[isSearchFocused, normalizedQuery, providers, searchAllOnFocus],
);
const hasResults = profiles !== null || providers.length > 0 || rootBrowseContent != null;
const searchResultsHeader = useMemo(
() =>
allView.kind === "searchResults" && allView.profiles.length > 0 ? (
<ProfileSearchResultsHeader
rows={allView.profiles}
hasModelRows={allView.rows.length > 0}
onApplyProfile={onApplyProfile}
onEditProfiles={onEditProfiles}
/>
) : undefined,
[allView, onApplyProfile, onEditProfiles],
);
if (view.kind === "provider") {
return (
@@ -1537,7 +1471,6 @@ function ModelBrowserContent({
selectedModel={selectedModel}
onSelect={onSelect}
showProviderLabel
header={searchResultsHeader}
scrolling={scrolling}
profiledLookup={profiledLookup}
onCreateProfile={onCreateProfile}
+9 -24
View File
@@ -78,7 +78,7 @@ const FOCUSED_COMBOBOX_ACTION_SELECTOR =
'[data-combobox-trailing-action] button, [data-combobox-trailing-action] [role="button"], [data-combobox-footer] button, [data-combobox-footer] [role="button"]';
export type ComboboxOption = ComboboxOptionModel;
export type ComboboxDesktopPlacement = "top-start" | "bottom-start" | "bottom-end";
export type ComboboxDesktopPlacement = "top-start" | "bottom-start";
export interface ComboboxProps {
options: ComboboxOption[];
@@ -94,11 +94,6 @@ export interface ComboboxProps {
searchable?: boolean;
/** The caller answers the search query itself, so the options are shown as given. */
remoteSearch?: boolean;
/**
* With `remoteSearch`, the options still answer an earlier query. No option is picked until
* the user moves to one, so Enter cannot confirm a row the new query may not match.
*/
remoteSearchPending?: boolean;
placeholder?: string;
searchPlaceholder?: string;
emptyText?: string;
@@ -615,7 +610,6 @@ interface DesktopKeyHandlerInput {
isOpen: boolean;
orderedVisibleOptions: ComboboxOption[];
activeIndex: number;
remoteSearchPending: boolean;
setActiveIndex: React.Dispatch<React.SetStateAction<number>>;
handleSelect: (id: string) => void;
handleClose: () => void;
@@ -628,9 +622,7 @@ function handleDesktopArrowKey(input: DesktopKeyHandlerInput, key: "ArrowDown" |
function handleDesktopEnterKey(input: DesktopKeyHandlerInput) {
if (input.orderedVisibleOptions.length === 0) return;
const { activeIndex, orderedVisibleOptions } = input;
const picked = activeIndex >= 0 && activeIndex < orderedVisibleOptions.length;
if (!picked && input.remoteSearchPending) return;
const index = picked ? activeIndex : 0;
const index = activeIndex >= 0 && activeIndex < orderedVisibleOptions.length ? activeIndex : 0;
input.handleSelect(orderedVisibleOptions[index].id);
}
@@ -686,21 +678,18 @@ function useActiveIndexSync(
effectiveOptionsPosition: "below-search" | "above-search",
normalizedSearch: string,
value: string,
remoteSearchPending: boolean,
setActiveIndex: React.Dispatch<React.SetStateAction<number>>,
) {
useEffect(() => {
if (!isOpen) return;
if (!IS_WEB && isMobile) return;
setActiveIndex(
remoteSearchPending
? -1
: resolveInitialActiveIndex(
orderedVisibleOptions,
effectiveOptionsPosition,
normalizedSearch,
value,
),
resolveInitialActiveIndex(
orderedVisibleOptions,
effectiveOptionsPosition,
normalizedSearch,
value,
),
);
}, [
effectiveOptionsPosition,
@@ -709,7 +698,6 @@ function useActiveIndexSync(
normalizedSearch,
value,
orderedVisibleOptions,
remoteSearchPending,
setActiveIndex,
]);
}
@@ -1410,7 +1398,6 @@ export function Combobox({
onSearchQueryChange,
searchable = true,
remoteSearch,
remoteSearchPending,
placeholder,
searchPlaceholder,
emptyText,
@@ -1629,7 +1616,6 @@ export function Combobox({
effectiveOptionsPosition,
normalizedSearch,
value,
remoteSearchPending === true,
setActiveIndex,
);
@@ -1677,7 +1663,6 @@ export function Combobox({
isOpen,
orderedVisibleOptions,
activeIndex,
remoteSearchPending: remoteSearchPending === true,
setActiveIndex,
handleSelect,
handleClose,
@@ -1686,7 +1671,7 @@ export function Combobox({
event,
);
},
[activeIndex, handleClose, handleSelect, isOpen, orderedVisibleOptions, remoteSearchPending],
[activeIndex, handleClose, handleSelect, isOpen, orderedVisibleOptions],
);
useDismissKeyboardOnOpen(isOpen, isMobile);
+2 -22
View File
@@ -75,10 +75,6 @@ export function Field({ label, children, trailing, hint, error, testID }: FieldP
type FormTextInputProps = AdaptiveTextInputProps & {
size?: ControlSize;
/** A glyph inside the field before the text, such as a search icon. */
leading?: ReactNode;
/** The value is rejected; the border and focus ring turn to the danger color. */
invalid?: boolean;
};
type FlatFormTextInputStyle = ViewStyle & TextStyle;
@@ -170,10 +166,7 @@ function assignTextInputRef(
}
export const FormTextInput = forwardRef<EditingTextInputHandle, FormTextInputProps>(
function FormTextInput(
{ size: sizeProp, leading, invalid = false, style, onFocus, onBlur, editable, ...props },
ref,
) {
function FormTextInput({ size: sizeProp, style, onFocus, onBlur, editable, ...props }, ref) {
const [focused, setFocused] = useState(false);
const containedSize = useContainedControlSize();
const size = sizeProp ?? containedSize ?? "md";
@@ -209,7 +202,6 @@ export const FormTextInput = forwardRef<EditingTextInputHandle, FormTextInputPro
({ hovered = false }: PressableStateCallbackType & { hovered?: boolean }) => [
formInputStyles.chrome,
chromeSizeStyle,
leading ? formInputStyles.chromeWithLeading : null,
resolveControlInteractionStyles(
{
controlRest: formInputStyles.controlRest,
@@ -223,15 +215,13 @@ export const FormTextInput = forwardRef<EditingTextInputHandle, FormTextInputPro
disabled: isDisabled,
},
),
invalid ? formInputStyles.controlInvalid : null,
splitStyle.chromeStyle,
],
[chromeSizeStyle, focused, invalid, isDisabled, leading, splitStyle.chromeStyle],
[chromeSizeStyle, focused, isDisabled, splitStyle.chromeStyle],
);
return (
<Pressable disabled={isDisabled} style={chromeStyle}>
{leading}
<AdaptiveTextInput
ref={setInputRef}
editable={editable}
@@ -281,11 +271,6 @@ const formInputStyles = StyleSheet.create((theme) => {
chrome: {
backgroundColor: theme.colors.surface2,
},
chromeWithLeading: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
chromeSm: {
...geometry.fieldControlSm,
},
@@ -304,11 +289,6 @@ const formInputStyles = StyleSheet.create((theme) => {
controlDisabled: {
...geometry.controlDisabled,
},
// Matches the inline error under the field (docs/design.md, Errors).
controlInvalid: {
borderColor: theme.colors.palette.red[300],
outlineColor: theme.colors.palette.red[300],
},
input: {
flex: 1,
minWidth: 0,
@@ -29,8 +29,6 @@ interface SegmentedControlProps<T extends string> {
onValueChange: (value: T) => void;
size?: ControlSize;
hideLabels?: boolean;
/** Share the container's width equally between the segments, for a control that heads a surface. */
fill?: boolean;
style?: StyleProp<ViewStyle>;
testID?: string;
}
@@ -56,7 +54,6 @@ export function SegmentedControl<T extends string>({
onValueChange,
size: sizeProp,
hideLabels = false,
fill = false,
style,
testID,
}: SegmentedControlProps<T>) {
@@ -88,7 +85,6 @@ export function SegmentedControl<T extends string>({
isSelected={isSelected}
iconSize={iconSize}
hideLabels={hideLabels}
fill={fill}
segmentSizeStyle={segmentSizeStyle}
labelSizeStyle={labelSizeStyle}
currentValue={value}
@@ -105,7 +101,6 @@ function SegmentItem<T extends string>({
isSelected,
iconSize,
hideLabels,
fill,
segmentSizeStyle,
labelSizeStyle,
currentValue,
@@ -115,7 +110,6 @@ function SegmentItem<T extends string>({
isSelected: boolean;
iconSize: number;
hideLabels: boolean;
fill: boolean;
segmentSizeStyle: StyleProp<ViewStyle>;
labelSizeStyle: StyleProp<TextStyle>;
currentValue: T | null;
@@ -134,13 +128,12 @@ function SegmentItem<T extends string>({
({ hovered, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
styles.segment,
segmentSizeStyle,
fill && styles.segmentFill,
isSelected && styles.segmentSelected,
Boolean(hovered) && !isSelected && styles.segmentHover,
pressed && !isSelected && styles.segmentPressed,
option.disabled && styles.segmentDisabled,
],
[fill, isSelected, option.disabled, segmentSizeStyle],
[isSelected, option.disabled, segmentSizeStyle],
);
const accessibilityState = useMemo(
() => ({ selected: isSelected, disabled: option.disabled }),
@@ -210,12 +203,6 @@ const styles = StyleSheet.create((theme) => {
segmentMd: {
...geometry.segmentedSegmentMd,
},
segmentFill: {
flexGrow: 1,
flexBasis: 0,
flexShrink: 1,
minWidth: 0,
},
segmentSelected: {
backgroundColor: theme.colors.surface3,
},
@@ -1209,7 +1209,6 @@ export const AgentControls = memo(function AgentControls({
ownerKey: agentId,
provider: agentProvider,
providerDefinitions: modeProviderDefinitions,
profiles: agentProfiles,
models: {
providers: agentModelSelectorProviders,
selectedProvider: agentProvider,
@@ -1227,7 +1226,6 @@ export const AgentControls = memo(function AgentControls({
[
activeModelId,
agentOptionControls,
agentProfiles,
client,
agentId,
agentModelSelectorProviders,
@@ -1450,7 +1448,6 @@ export function DraftAgentControls({
ownerKey: draftId,
provider: selectedProvider,
providerDefinitions,
profiles: agentProfiles,
models: {
providers: modelSelectorProviders,
selectedProvider,
@@ -1472,7 +1469,6 @@ export function DraftAgentControls({
draftId,
selectedProvider,
providerDefinitions,
agentProfiles,
modelSelectorProviders,
effectiveModelId,
onSelectProviderAndModel,
@@ -161,10 +161,10 @@ const CATALOG_DATA = [
id: "factory-droid",
title: "Factory Droid",
description: "Factory Droid - AI coding agent powered by Factory AI",
version: "1.20.0",
version: "0.249.0",
iconId: "factory-droid",
installLink: "https://factory.ai/product/cli",
command: ["npx", "-y", "droid@1.20.0", "exec", "--output-format", "acp-daemon"],
command: ["npx", "-y", "droid@0.249.0", "exec", "--output-format", "acp-daemon"],
env: {
DROID_DISABLE_AUTO_UPDATE: "true",
FACTORY_DROID_AUTO_UPDATE_ENABLED: "false",
@@ -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,26 @@ 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("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 +519,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;
@@ -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,
});
@@ -307,10 +384,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 +416,7 @@ export function createDesktopAppUpdater(deps: DesktopAppUpdaterDeps): DesktopApp
commit({
...state,
status: "error",
downloadProgress: null,
errorMessage: message,
isInstalling: false,
});
@@ -341,6 +432,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,
},
}));
@@ -4,11 +4,13 @@ import {
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,
@@ -22,9 +24,12 @@ export type { DesktopAppUpdateStatus };
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,8 +43,9 @@ 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 = useMemo(
@@ -84,13 +90,40 @@ export function useDesktopAppUpdater(): UseDesktopAppUpdaterReturn {
useEffect(() => {
if (!isDesktopApp) {
return undefined;
}
let active = true;
let unlisten: (() => void) | null = null;
void subscribeDesktopAppUpdateDownloadProgress((progress) => {
if (active) {
updater.setDownloadProgress(progress);
}
})
.then((cleanup) => {
if (active) {
unlisten = cleanup;
} else {
cleanup();
}
return undefined;
})
.catch(() => undefined);
return () => {
active = false;
unlisten?.();
};
}, [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 +134,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 },
},
+36 -3
View File
@@ -116,8 +116,6 @@ export const ar: TranslationResources = {
groupByProject: "تجميع حسب المشروع",
groupByStatus: "تجميع حسب الحالة",
copyBrowserHostName: "نسخ اسم مضيف المتصفح",
profileGroupLabel: "الملف الشخصي",
profileSearchKeywords: "ملف شخصي تطبيق ملف شخصي ملف الوكيل إعداد مسبق",
modelGroupLabel: "النموذج",
modelSearchKeywords: "تبديل النموذج تغيير النموذج تعيين النموذج اختيار النموذج",
thinkingGroupLabel: "التفكير",
@@ -1541,6 +1539,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 +1548,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 +1566,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: "ستؤدي ترقية التطبيق إلى إيقاف تشغيل الوكلاء وإغلاق الجلسات الطرفية.",
@@ -1808,7 +1823,6 @@ export const ar: TranslationResources = {
defaultModel: "تقصير",
profiles: "الملفات الشخصية",
providers: "المزودون",
models: "النماذج",
model: "النموذج",
editProfiles: "تحرير",
editProfilesLabel: "تحرير ملفات الوكيل",
@@ -2643,9 +2657,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: "تثبيت التحديث",
+36 -3
View File
@@ -114,8 +114,6 @@ export const en = {
groupByProject: "Group by project",
groupByStatus: "Group by status",
copyBrowserHostName: "Copy browser host name",
profileGroupLabel: "Profile",
profileSearchKeywords: "profile apply profile agent profile preset",
modelGroupLabel: "Model",
modelSearchKeywords: "switch model change model set model select model",
thinkingGroupLabel: "Thinking",
@@ -1568,6 +1566,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 +1576,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 +1594,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.",
@@ -1837,7 +1852,6 @@ export const en = {
defaultModel: "Default",
profiles: "Profiles",
providers: "Providers",
models: "Models",
model: "Model",
editProfiles: "Edit",
editProfilesLabel: "Edit agent profiles",
@@ -2739,9 +2753,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",
+38 -3
View File
@@ -117,8 +117,6 @@ export const es: TranslationResources = {
groupByProject: "Agrupar por proyecto",
groupByStatus: "Agrupar por estado",
copyBrowserHostName: "Copiar el nombre del host del navegador",
profileGroupLabel: "Perfil",
profileSearchKeywords: "perfil aplicar perfil perfil de agente preajuste",
modelGroupLabel: "Modelo",
modelSearchKeywords: "cambiar modelo modificar modelo establecer modelo seleccionar modelo",
thinkingGroupLabel: "Razonamiento",
@@ -1578,6 +1576,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 +1586,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 +1608,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:
@@ -1856,7 +1873,6 @@ export const es: TranslationResources = {
defaultModel: "Por defecto",
profiles: "Perfiles",
providers: "Proveedores",
models: "Modelos",
model: "Modelo",
editProfiles: "Editar",
editProfilesLabel: "Editar perfiles de agente",
@@ -2664,9 +2680,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",
+38 -3
View File
@@ -117,8 +117,6 @@ export const fr: TranslationResources = {
groupByProject: "Grouper par projet",
groupByStatus: "Grouper par statut",
copyBrowserHostName: "Copier le nom de l’hôte du navigateur",
profileGroupLabel: "Profil",
profileSearchKeywords: "profil appliquer un profil profil d'agent préréglage",
modelGroupLabel: "Modèle",
modelSearchKeywords:
"changer de modèle modifier le modèle définir le modèle sélectionner le modèle model",
@@ -1571,6 +1569,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 +1579,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 +1601,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:
@@ -1854,7 +1871,6 @@ export const fr: TranslationResources = {
defaultModel: "Par défaut",
profiles: "Profils",
providers: "Fournisseurs",
models: "Modèles",
model: "Modèle",
editProfiles: "Modifier",
editProfilesLabel: "Modifier les profils d’agent",
@@ -2664,9 +2680,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",
+37 -3
View File
@@ -117,8 +117,6 @@ export const ja: TranslationResources = {
groupByProject: "プロジェクトでグループ化",
groupByStatus: "ステータスでグループ化",
copyBrowserHostName: "ブラウザホスト名をコピー",
profileGroupLabel: "プロファイル",
profileSearchKeywords: "プロファイル プロファイルを適用 エージェントプロファイル プリセット",
modelGroupLabel: "モデル",
modelSearchKeywords: "モデルを切り替え モデルを変更 モデルを設定 モデルを選択",
thinkingGroupLabel: "思考",
@@ -1556,6 +1554,8 @@ export const ja: TranslationResources = {
status: {
checking: "アプリの更新を確認中...",
installing: "アプリの更新をインストール中...",
downloadingVersionProgress: "{{version}} をダウンロード中... {{percent}}%",
downloadingProgress: "アプリの更新をダウンロード中... {{percent}}%",
upToDate: "アプリは最新です。",
upToDateWithLastChecked: "最新の状態です。最終確認: {{time}}。",
pending: "更新の準備ができたらお知らせします。",
@@ -1563,6 +1563,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 +1583,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:
@@ -1828,7 +1844,6 @@ export const ja: TranslationResources = {
defaultModel: "デフォルト",
profiles: "プロファイル",
providers: "プロバイダー",
models: "モデル",
model: "モデル",
editProfiles: "編集",
editProfilesLabel: "エージェントプロファイルを編集",
@@ -2631,9 +2646,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: "更新をインストール",
+37 -3
View File
@@ -116,8 +116,6 @@ export const ko: TranslationResources = {
groupByProject: "프로젝트별 그룹화",
groupByStatus: "상태별 그룹화",
copyBrowserHostName: "브라우저 호스트 이름 복사",
profileGroupLabel: "프로필",
profileSearchKeywords: "프로필 프로필 적용 에이전트 프로필 프리셋",
modelGroupLabel: "모델",
modelSearchKeywords: "모델 전환 모델 변경 모델 설정 모델 선택",
thinkingGroupLabel: "추론",
@@ -1547,6 +1545,8 @@ export const ko: TranslationResources = {
status: {
checking: "앱 업데이트 확인 중...",
installing: "앱 업데이트 설치 중...",
downloadingVersionProgress: "{{version}} 다운로드 중... {{percent}}%",
downloadingProgress: "앱 업데이트 다운로드 중... {{percent}}%",
upToDate: "앱이 최신 상태입니다.",
upToDateWithLastChecked: "최신 상태입니다. 마지막 확인: {{time}}.",
pending: "업데이트가 준비되면 알려드리겠습니다.",
@@ -1555,6 +1555,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 +1576,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: "앱을 업그레이드하면 실행 중인 에이전트가 중지되고 터미널 세션이 닫힙니다.",
@@ -1819,7 +1835,6 @@ export const ko: TranslationResources = {
defaultModel: "기본값",
profiles: "프로필",
providers: "제공자",
models: "모델",
model: "모델",
editProfiles: "편집",
editProfilesLabel: "에이전트 프로필 편집",
@@ -2621,9 +2636,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: "업데이트 설치",
+37 -3
View File
@@ -117,8 +117,6 @@ export const ptBR: TranslationResources = {
groupByProject: "Agrupar por projeto",
groupByStatus: "Agrupar por status",
copyBrowserHostName: "Copiar o nome do host do navegador",
profileGroupLabel: "Perfil",
profileSearchKeywords: "perfil aplicar perfil perfil do agente predefinição",
modelGroupLabel: "Modelo",
modelSearchKeywords: "trocar modelo mudar modelo definir modelo selecionar modelo",
thinkingGroupLabel: "Raciocínio",
@@ -1568,6 +1566,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 +1576,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 +1597,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:
@@ -1841,7 +1857,6 @@ export const ptBR: TranslationResources = {
defaultModel: "Padrão",
profiles: "Perfis",
providers: "Provedores",
models: "Modelos",
model: "Modelo",
editProfiles: "Editar",
editProfilesLabel: "Editar perfis de agente",
@@ -2646,9 +2661,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",
+37 -3
View File
@@ -117,8 +117,6 @@ export const ru: TranslationResources = {
groupByProject: "Группировать по проекту",
groupByStatus: "Группировать по статусу",
copyBrowserHostName: "Скопировать имя хоста браузера",
profileGroupLabel: "Профиль",
profileSearchKeywords: "профиль применить профиль профиль агента пресет",
modelGroupLabel: "Модель",
modelSearchKeywords: "Сменить, изменить, выбрать или установить модель",
thinkingGroupLabel: "Мышление",
@@ -1562,6 +1560,8 @@ export const ru: TranslationResources = {
status: {
checking: "Проверка обновлений приложения...",
installing: "Установка обновления приложения...",
downloadingVersionProgress: "Загрузка {{version}}... {{percent}}%",
downloadingProgress: "Загрузка обновления приложения... {{percent}}%",
upToDate: "Установлена последняя версия приложения.",
upToDateWithLastChecked:
"Установлена последняя версия приложения. Последняя проверка: {{time}}.",
@@ -1571,6 +1571,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 +1592,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:
@@ -1841,7 +1857,6 @@ export const ru: TranslationResources = {
defaultModel: "По умолчанию",
profiles: "Профили",
providers: "Провайдеры",
models: "Модели",
model: "Модель",
editProfiles: "Изменить",
editProfilesLabel: "Изменить профили агентов",
@@ -2653,9 +2668,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: "Установить обновление",
+36 -3
View File
@@ -116,8 +116,6 @@ export const zhCN: TranslationResources = {
groupByProject: "按项目分组",
groupByStatus: "按状态分组",
copyBrowserHostName: "复制浏览器宿主名称",
profileGroupLabel: "配置文件",
profileSearchKeywords: "配置文件 应用配置文件 代理配置文件 预设",
modelGroupLabel: "模型",
modelSearchKeywords: "切换模型 更改模型 设置模型 选择模型",
thinkingGroupLabel: "思考",
@@ -1528,6 +1526,8 @@ export const zhCN: TranslationResources = {
status: {
checking: "正在检查 app 更新...",
installing: "正在安装 app 更新...",
downloadingVersionProgress: "正在下载 {{version}}... {{percent}}%",
downloadingProgress: "正在下载 app 更新... {{percent}}%",
upToDate: "App 已是最新版本。",
upToDateWithLastChecked: "已是最新版本。上次检查时间:{{time}}。",
pending: "更新准备好后会通知你。",
@@ -1535,6 +1535,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 +1553,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 会话。",
@@ -1790,7 +1805,6 @@ export const zhCN: TranslationResources = {
defaultModel: "默认",
profiles: "配置文件",
providers: "提供方",
models: "模型",
model: "模型",
editProfiles: "编辑",
editProfilesLabel: "编辑智能体配置文件",
@@ -2580,9 +2594,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: "安装更新",
+135 -19
View File
@@ -83,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";
@@ -609,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,
@@ -637,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(() => {
@@ -666,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;
@@ -691,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;
@@ -715,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>
@@ -726,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}>
@@ -739,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>
@@ -1506,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",
@@ -7,18 +7,14 @@ export interface AddProjectFlowRequest {
interface AddProjectFlowStoreState {
request: AddProjectFlowRequest | null;
/** The parent directory last used to clone or create a project, per host, for this session. */
lastLocationByHost: Record<string, string>;
open: (preferredHostId?: string) => void;
close: () => void;
rememberLocation: (hostId: string, location: string) => void;
}
let nextRequestId = 1;
export const useAddProjectFlowStore = create<AddProjectFlowStoreState>((set) => ({
request: null,
lastLocationByHost: {},
open: (preferredHostId) => {
set({
request: {
@@ -28,6 +24,4 @@ export const useAddProjectFlowStore = create<AddProjectFlowStoreState>((set) =>
});
},
close: () => set({ request: null }),
rememberLocation: (hostId, location) =>
set((state) => ({ lastLocationByHost: { ...state.lastLocationByHost, [hostId]: location } })),
}));
+109 -34
View File
@@ -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) {
+41
View File
@@ -91,6 +91,47 @@ 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.describe("Desktop daemon management", () => {
@@ -15,12 +15,20 @@ import {
const mocks = vi.hoisted(() => ({
paseoHome: "",
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 +49,7 @@ vi.mock("electron", () => ({
getVersion: vi.fn(() => "1.2.3"),
isPackaged: true,
},
BrowserWindow: { getAllWindows: vi.fn(() => []) },
ipcMain: { handle: vi.fn() },
powerMonitor: { getSystemIdleTime: vi.fn(() => 0) },
}));
@@ -79,6 +88,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 +108,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 +199,69 @@ describe("daemon-manager commands", () => {
writeFileSync(lockPath, JSON.stringify({ ...lock, desktopManaged: false }));
expect(await handler({ listen: "localhost:6799" })).toBeNull();
});
it("blocks automatic update checks when updates.mode is off", async () => {
mocks.settings = {
...DEFAULT_DESKTOP_SETTINGS,
updates: { mode: "off" },
};
const result = await createDaemonCommandHandlers().check_app_update({
intent: "automatic",
});
expect(mocks.checkForAppUpdate).not.toHaveBeenCalled();
expect(result).toEqual({
hasUpdate: false,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.3",
body: null,
date: null,
errorMessage: null,
});
});
it("checks without auto-downloading when updates.mode is notify or manual in off mode", async () => {
mocks.checkForAppUpdate.mockResolvedValue({
hasUpdate: true,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.4",
body: null,
date: null,
errorMessage: null,
});
mocks.settings = { ...DEFAULT_DESKTOP_SETTINGS, updates: { mode: "notify" } };
await createDaemonCommandHandlers().check_app_update({ intent: "automatic" });
expect(mocks.checkForAppUpdate).toHaveBeenLastCalledWith({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
autoDownload: false,
});
mocks.settings = { ...DEFAULT_DESKTOP_SETTINGS, updates: { mode: "off" } };
await createDaemonCommandHandlers().check_app_update({ intent: "manual" });
expect(mocks.checkForAppUpdate).toHaveBeenLastCalledWith({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "manual",
autoDownload: false,
});
mocks.settings = { ...DEFAULT_DESKTOP_SETTINGS, updates: { mode: "automatic" } };
await createDaemonCommandHandlers().check_app_update({ intent: "automatic" });
expect(mocks.checkForAppUpdate).toHaveBeenLastCalledWith({
currentVersion: "1.2.3",
releaseChannel: "stable",
intent: "automatic",
autoDownload: true,
});
});
});
describe("desktop stops and terminals", () => {
+18 -2
View File
@@ -541,10 +541,26 @@ export function createDaemonCommandHandlers(): Record<string, DesktopCommandHand
},
check_app_update: async (args) => {
const currentVersion = resolveDesktopAppVersion();
const settings = await getDesktopSettingsStore().get();
const intent = parseAppUpdateCheckIntent(args);
const updateMode = settings.updates.mode;
if (intent === "automatic" && updateMode === "off") {
return {
hasUpdate: false,
readyToInstall: false,
downloading: false,
currentVersion,
latestVersion: currentVersion,
body: null,
date: null,
errorMessage: null,
};
}
return checkForAppUpdate({
currentVersion,
releaseChannel: await resolveRequestedReleaseChannel(args),
intent: parseAppUpdateCheckIntent(args),
releaseChannel: parseReleaseChannel(args) ?? settings.releaseChannel,
intent,
autoDownload: updateMode === "automatic",
});
},
install_app_update: async (args) => {
@@ -2,9 +2,12 @@ import { describe, expect, it } from "vitest";
import {
createAppUpdateService,
type AppUpdateDownloadProgress,
type AppUpdateInstallRequest,
type AppUpdateRuntime,
type AppUpdateRuntimeConfiguration,
type RuntimeDownloadProgressInfo,
type RuntimeUpdateCheckResult,
type RuntimeUpdateInfo,
} from "./app-update-service";
@@ -26,6 +29,7 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
resolve(): void;
reject(error: Error): void;
} | null = null;
lastAutoDownload: boolean | null = null;
checkCount = 0;
downloadCallCount = 0;
requestedDownloadVersions: string[] = [];
@@ -35,9 +39,14 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
configure(input: AppUpdateRuntimeConfiguration): void {
this.configuration = input;
this.lastAutoDownload = input.autoDownload;
this.gate = input.shouldAdmitUpdate;
}
emitDownloadProgress(progress: RuntimeDownloadProgressInfo): void {
this.configuration?.onDownloadProgress(progress);
}
nextCheck(result: { isUpdateAvailable: boolean; updateInfo: RuntimeUpdateInfo } | null): void {
this.checks.push(result);
}
@@ -151,13 +160,18 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
}
}
function createService(input?: { now?: () => number; bucket?: () => Promise<number> }) {
function createService(input?: {
now?: () => number;
bucket?: () => Promise<number>;
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),
onDownloadProgress: input?.onDownloadProgress,
});
return { runtime, service };
}
@@ -182,6 +196,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 +218,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 +347,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 +378,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 +587,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 +609,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 +640,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 +670,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 +713,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 +744,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 +763,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 +827,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 +860,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 +868,246 @@ 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,
});
});
});
@@ -5,9 +5,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 +28,7 @@ export interface AppUpdateInstallResult {
installed: boolean;
version: string | null;
message: string;
errorMessage?: string | null;
}
export interface RuntimeUpdateInfo {
@@ -28,6 +38,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 +52,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;
}
@@ -59,6 +78,7 @@ export interface AppUpdateService {
currentVersion: string;
releaseChannel: AppReleaseChannel;
intent: AppUpdateCheckIntent;
autoDownload?: boolean;
}): Promise<AppUpdateCheckResult>;
downloadAndInstallUpdate(
input: {
@@ -79,6 +99,7 @@ export interface AppUpdateServiceDeps {
isPackaged(): boolean;
now(): number;
bucket(): Promise<number>;
onDownloadProgress?(progress: AppUpdateDownloadProgress | null): void;
reportCheckError?(error: unknown): void;
reportRuntimeError?(error: unknown): void;
reportInstallError?(message: string): void;
@@ -88,14 +109,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,
@@ -145,6 +175,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 +187,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
downloadedUpdateVersion = null;
preparationError = null;
preparingUpdateVersion = null;
deps.onDownloadProgress?.(null);
}
function buildPreviouslyAdmittedUpdateResult(
@@ -167,23 +199,31 @@ 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 {
function configureRuntime(
releaseChannel: AppReleaseChannel,
intent: AppUpdateCheckIntent,
autoDownload: boolean,
): void {
if (configuredReleaseChannel !== releaseChannel) {
clearUpdateState();
configuredReleaseChannel = releaseChannel;
}
currentAutoDownload = autoDownload;
deps.runtime.configure({
releaseChannel,
autoDownload,
shouldAdmitUpdate: async (info) => {
const parsed = rolloutManifestSchema.parse(info);
return shouldAdmitAppUpdate({
@@ -199,10 +239,22 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
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 +266,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
if (preparationError?.version === info.version) {
preparationError = null;
}
deps.onDownloadProgress?.(null);
},
onError(error) {
if (preparingUpdateVersion) {
@@ -223,6 +276,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
};
preparingUpdateVersion = null;
}
deps.onDownloadProgress?.(null);
deps.reportRuntimeError?.(error);
},
});
@@ -241,10 +295,12 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
currentVersion,
releaseChannel,
intent,
autoDownload = true,
}: {
currentVersion: string;
releaseChannel: AppReleaseChannel;
intent: AppUpdateCheckIntent;
autoDownload?: boolean;
}): Promise<AppUpdateCheckResult> {
if (!deps.isPackaged()) {
return buildCheckResult({
@@ -255,7 +311,10 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
}
return runCheckExclusively(async () => {
configureRuntime(releaseChannel, intent);
if (intent === "manual") {
preparationError = null;
}
configureRuntime(releaseChannel, intent, autoDownload);
try {
const result = await deps.runtime.checkForUpdates();
@@ -291,15 +350,23 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
if (hasUpdate) {
cachedUpdateInfo = info;
const readyToInstall = isReadyToInstallVersion(latestVersion);
const errorMessage =
preparationError?.version === latestVersion ? preparationError.message : null;
if (!errorMessage) {
preparationError = null;
}
if (!readyToInstall && !errorMessage && autoDownload && preparingUpdateVersion === null) {
preparingUpdateVersion = latestVersion;
}
return buildCheckResult({
currentVersion,
hasUpdate: true,
readyToInstall: isReadyToInstallVersion(latestVersion),
readyToInstall,
downloading:
!readyToInstall &&
!errorMessage &&
(autoDownload || preparingUpdateVersion === latestVersion),
info,
errorMessage,
});
@@ -345,18 +412,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 +455,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 +473,7 @@ 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);
}
}
@@ -454,12 +542,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,
};
}
}
@@ -4,9 +4,10 @@ import path from "node:path";
import { UUID } from "builder-util-runtime";
import { describe, expect, it, vi } from "vitest";
const { autoUpdaterMock } = vi.hoisted(() => {
const { autoUpdaterMock, getAllWindowsMock } = vi.hoisted(() => {
const handlers = new Map<string, (value: unknown) => void>();
return {
getAllWindowsMock: vi.fn<() => unknown[]>(() => []),
autoUpdaterMock: {
handlers,
logger: {
@@ -30,6 +31,9 @@ vi.mock("electron", () => ({
getPath: vi.fn(),
isPackaged: true,
},
BrowserWindow: {
getAllWindows: getAllWindowsMock,
},
}));
vi.mock("electron-updater", () => ({
@@ -67,6 +71,7 @@ describe("checkForAppUpdate", () => {
expect(result).toEqual({
hasUpdate: false,
readyToInstall: false,
downloading: false,
currentVersion: "1.2.3",
latestVersion: "1.2.3",
body: null,
@@ -97,6 +102,104 @@ 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("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("logs the update handoff with current and selected target versions", () => {
const info = vi.fn();
const lifecycleLog = createAppUpdateLifecycleLogger({ info });
+48 -6
View File
@@ -1,17 +1,19 @@
import { randomBytes } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { app } from "electron";
import { app, BrowserWindow } from "electron";
import { UUID } from "builder-util-runtime";
import log from "electron-log/main";
import { autoUpdater } from "electron-updater";
import {
createAppUpdateService,
type AppUpdateCheckResult,
type AppUpdateDownloadProgress,
type AppUpdateInstallRequest,
type AppUpdateInstallResult,
type AppUpdateRuntime,
type AppUpdateRuntimeConfiguration,
type RuntimeDownloadProgressInfo,
type RuntimeUpdateCheckResult,
type RuntimeUpdateInfo,
} from "./app-update-service.js";
@@ -30,6 +32,7 @@ export {
type AppReleaseChannel,
type AppUpdateCheckIntent,
type AppUpdateCheckResult,
type AppUpdateDownloadProgress,
type AppUpdateInstallResult,
};
@@ -140,11 +143,42 @@ 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 {
if (typeof BrowserWindow?.getAllWindows !== "function") {
return;
}
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.
}
}
}
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 +189,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,16 +213,19 @@ 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);
});
}
@@ -212,6 +249,7 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
}
quitAndInstall({ targetVersion, isSilent, isForceRunAfter }: AppUpdateInstallRequest): void {
broadcastDownloadProgress(null);
autoUpdater.autoRunAppAfterInstall = isForceRunAfter;
updateLifecycleLog.quitAndInstallRequested({
targetVersion,
@@ -227,6 +265,7 @@ const appUpdateService = createAppUpdateService({
isPackaged: () => app.isPackaged,
now: () => Date.now(),
bucket: async () => bucketFromStagingUserId(await getStagingUserId()),
onDownloadProgress: broadcastDownloadProgress,
reportCheckError: (error) => {
console.error("[auto-updater] Failed to check for updates:", error);
},
@@ -246,16 +285,19 @@ export async function checkForAppUpdate({
currentVersion,
releaseChannel,
intent,
autoDownload = true,
}: {
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,
+3
View File
@@ -1059,6 +1059,9 @@ const quitLifecycle = createQuitLifecycle({
}),
installAppUpdateOnQuit: async (signal) => {
const settings = await getDesktopSettingsStore().get();
if (settings.updates.mode !== "automatic") {
return false;
}
return installAppUpdateOnQuit({
currentVersion: app.getVersion(),
releaseChannel: settings.releaseChannel,
@@ -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,32 @@ 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("defaults notification sounds on for existing settings documents", async () => {
const userDataPath = await createTempUserDataDir();
directories.add(userDataPath);
@@ -270,6 +299,7 @@ describe("desktop-settings", () => {
expect(migrated).toEqual({
releaseChannel: "beta",
updates: { mode: "automatic" },
notifications: { playSound: true },
daemon: {
manageBuiltInDaemon: false,
@@ -315,6 +345,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 },
};