Compare commits

..
Author SHA1 Message Date
paseo-bot[bot]andKiraPC 404d08d24b Report failed terminal launches and remove early exits (#6792)
* fix(server): report a terminal whose command cannot start instead of leaving a dead tab

Opening a terminal profile whose command is not installed left a tab that could
never be closed. Two problems sat on the same path.

A terminal that dies during creation was resurrected by its own create. The
worker sends terminalCreated, the createTerminal response and terminalExit in
the same tick, so the parent drains all three before the awaiting create
continuation resumes; that continuation called registerRecord a second time and
put back a terminal the exit had just removed. Removal is owned solely by the
terminalExit event and that event never comes twice, so the record outlived
every close attempt: getTerminals kept listing it, capture returned nothing,
kill was a silent no-op that still reported success, and only a daemon restart
cleared it.

The parent now tracks the ids with a create in flight and keeps the finished
record when an exit removes one of them, so the create continuation returns the
exited session instead of registering a live one. Removal still happens exactly
once, in the terminalExit path.

With the stuck tab gone, a missing command produced nothing at all: no tab and
no message. node-pty spawns directly through execve on POSIX, with no shell, so
a command that does not exist fails inside the spawn helper and surfaces as exit
code 1 with no output -- exactly what `false` produces, so the exit carries no
usable signal. createTerminal now resolves the command before spawning and fails
the create when it cannot be found, so the daemon answers create_terminal with a
null terminal and "<command>: command not found", which the app already renders.
A command that starts and then exits non-zero still opens its tab.

That resolution has to match what execve will do in the child, or a working
profile is refused: it uses the terminal's own environment, built first so the
check sees the per-cwd registered PATH and the entries buildTerminalEnvironment
prepends, and it resolves a command containing a separator against the
terminal's cwd rather than through PATH. Windows keeps resolving inside
resolveTerminalSpawnCommand, which has its own shim handling and fallback.

* fix(terminal): check exact executable names and verify launch output

---------

Co-authored-by: KiraPC <pasqualecarmine.carbone@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-14 23:02:39 +02:00
paseo-bot[bot]and见安 6d43a8c5b0 Restore selected changes from subdirectory workspaces (#6777)
* fix(git): discard repository paths from the worktree root

* test(git): cover discard from nested workspaces through daemon RPC

* test(git): close the daemon before removing discard fixtures

Windows CI reaches the discard assertions but cannot remove the observed
repository while the test daemon is alive. Run fixture removal after the
daemon's afterEach cleanup, preserving all behavioral assertions.

Co-authored-by: 见安 <73627805+Mar-garet@users.noreply.github.com>

---------

Co-authored-by: 见安 <73627805+Mar-garet@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-14 20:02:03 +02:00
paseo-bot[bot] e1a5664d9b fix(app): keep malformed font settings from breaking the UI (#6695)
Unfinished CSS strings in font preferences consumed the shared theme stylesheet. Reject incomplete syntax at the settings boundary, recover persisted malformed values through the existing default path, and restore rejected edits in the font field.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-14 19:17:06 +02:00
paseo-bot[bot] b58af43a06 fix(app): render mixed HTML headings without literal tags (#6650)
Keep a matched heading together before splitting its image and text contents. Splitting first stranded the opening heading tag in a text slice without its closing tag.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-14 18:14:08 +02:00
truelecter 1bf3a57a1c fix(nix): raise Node heap for the desktop build (#6537)
Metro's transform worker runs out of heap on the generated ws-outbound.aot.js validator on machines where Node's default heap is 2 GB, such as the 7 GB macOS runner of the Nix workflow. Set NODE_OPTIONS=--max-old-space-size=4096 in the desktop derivation, as desktop-release.yml already does.

Closes #6535
2026-10-14 22:32:26 +07:00
56448842f0 Download files over the connected host (#6595)
* Let readFile callers disable the request timeout

readFile resolves only when FileEnd arrives, so the default 60 s request
timeout bounds the whole transfer. A large file over a slow relay fails
before it finishes even though every chunk is arriving. Thread an optional
timeout through requestFileExplorer; 0 disables the timer, as the
workspace.create request already does, and a dead connection still rejects
on disconnect.

The relay e2e case reads a 1 MiB file through a real daemon and a local
relay with timeout 0 and compares SHA-256 digests with the source.

* Reject a binary file transfer whose byte count differs from FileBegin.size

concatByteChunks allocated FileBegin.size bytes and copied the chunks in:
a short transfer resolved as a zero-padded file, and a long one threw a
RangeError inside the transport callback and left the request pending.
Count the received bytes at FileEnd and reject the read when they differ
from the announced size.

* Download files over the session socket when no direct connection is active

The download store only knew the HTTP token route and picked the first
directTcp connection in the host profile, whatever connection the host
runtime was using. A relay-only host has none, so every download ended in
"Download host is unavailable." (#543). SSH, socket and pipe hosts failed
the same way, and a stale directTcp entry won over a working relay (#3753).

Choose the transport from the active connection: directTcp keeps the HTTP
token download unchanged; anything else reads the file over the session
socket with the binary frames previews already use, then hands the bytes
to the browser's download manager on web and Electron or writes them to
the cache directory and offers the share sheet on native. Files over
64 MiB are refused before any byte moves, using the existing fileTooLarge
string, and a daemon response without content fails instead of saving an
empty file.

* fix(app): enforce the session download size limit during the read

The token size is sampled before the file is read. Pass the download byte budget through the actual read so a changed file cannot bypass the in-memory limit.

Co-authored-by: Michael Vandesompel <mv@droggol.be>
Co-authored-by: YASICJUNWOO <joonoo3@naver.com>
Co-authored-by: JrDw0 <JrDw0@users.noreply.github.com>

* test: verify TCP downloads and own relay fixture cleanup

---------

Co-authored-by: Michael Vandesompel <mv@droggol.be>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: YASICJUNWOO <joonoo3@naver.com>
Co-authored-by: JrDw0 <JrDw0@users.noreply.github.com>
2026-10-14 17:25:31 +02:00
paseo-bot[bot] 14e6384516 fix(desktop): keep running when launcher console pipes close (#6639)
Desktop logging reaches inherited stdout and stderr before the CLI guards run. A launcher that closes its output reader raised an uncaught EPIPE dialog. Handle closed console pipes at desktop startup while preserving console logging and surfacing other stream errors.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-14 15:27:12 +02:00
paseo-bot[bot]andRaisal P Wardana cafa04d3fb fix(app): traverse workspaces beyond nine (#6586)
Relative navigation shared the list capped for digit shortcuts, so it wrapped at the ninth workspace. Keep all sidebar targets and cap only numbered badges. Carry forward #4128 with keyboard-routing and browser regressions.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Raisal P Wardana <IEatCodeDaily@users.noreply.github.com>
2026-10-14 13:14:08 +02:00
paseo-bot[bot]and见安 938c4e2632 Show Git diffs for filenames with quotes and control characters (#6583)
* fix(diff): decode quoted Git patch paths

* fix(server): preserve Git paths in diff and commit listings

* refactor(diff): make quoted-path conversions explicit

* test(server): verify quoted filename diffs through daemon RPC

Keep the checkout and commit-file regression on the public client interface, and align the large-file command assertion with NUL-delimited statistics.

Co-authored-by: 见安 <73627805+Mar-garet@users.noreply.github.com>

* test(server): run filename RPC regression in integration checks

---------

Co-authored-by: 见安 <73627805+Mar-garet@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-14 12:09:47 +02:00
paseo-bot[bot] d57096a456 Start newly configured workspace services without restarting (#6542)
* fix(server): start newly configured workspace services without restarting

Extend the workspace port plan when paseo.json declares another service, preserving existing peer ports. Serialize extensions and roll back only their new reservations on failure.

* fix(server): serialize service restarts with port plan extensions

Keep concurrent restart and newly added service allocations in the same workspace update transaction so neither overwrites the other.

* fix(server): keep service port update failures scoped and release cancelled reservations

* test(hub): show creation errors in re-enrollment failures

Assert the error field along with success so failed CI reports include the reason agent creation was rejected.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-14 11:07:06 +02:00
paseo-bot[bot] ada7ba43f0 Keep long custom models removable in provider settings (#6507)
* fix(app): keep long custom models removable

Custom model labels and IDs could consume the row width and push Remove outside the sheet. Allow those text cells to shrink while preserving the button width and short-name alignment.

* test(app): wait for legacy agent creation before checking prompts

Agent-list membership includes initialization. Waiting for finish at that point can return on the initial idle transition before the initial prompt starts. Wait for the matching creation response before checking each completed turn, preserving the existing exact-once assertions.

* test(app): wait for directory search keyboard focus

The search page becomes visible before its deferred focus callback runs. Wait for the input to own keyboard focus so the journey types its query rather than dropping it during navigation.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-10-14 10:21:52 +02:00
48 changed files with 2522 additions and 198 deletions
+6
View File
@@ -86,6 +86,12 @@ buildNpmPackage {
# Expo's web build pulls in some pre-bundled assets; ensure it doesn't try
# to phone home during the build.
CI = "1";
# Metro's worker runs out of heap transforming the generated
# ws-outbound.aot.js validator (about 12 MB). Node's default heap limit is
# 2 GB on machines with less than 15 GB of memory, such as GitHub's 7 GB
# macOS runners, and 4 GB above that. 4096 MB is that 4 GB ceiling, so this
# only raises the limit on smaller builders, like desktop-release.yml does.
NODE_OPTIONS = "--max-old-space-size=4096";
};
buildPhase = ''
@@ -223,6 +223,7 @@ test.describe("Add Project command-center flow", () => {
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,
@@ -0,0 +1,48 @@
import { expect, test } from "../support/fixtures";
import type { Page } from "@playwright/test";
import { openSettingsSection } from "../support/helpers/settings";
async function openAppearance(page: Page) {
await page.goto("/settings");
await openSettingsSection(page, "appearance");
}
async function setFontFamily(page: Page, name: string, family: string) {
const input = page.getByRole("textbox", { name });
await input.fill(family);
await input.press("Tab");
}
for (const name of ["Code font family", "Interface font family"]) {
test(`keeps settings usable after an unfinished quote in ${name}`, async ({ page }, testInfo) => {
await openAppearance(page);
await setFontFamily(page, name, "'Fira Code', monospace");
await expect(page.getByRole("textbox", { name })).toHaveValue("'Fira Code', monospace");
await setFontFamily(page, name, "'foo");
await expect(page.getByRole("textbox", { name })).toHaveValue("'Fira Code', monospace");
await expect(page.getByRole("button", { name: "Appearance", exact: true })).toBeInViewport();
await expect(page.getByText("Theme", { exact: true }).first()).toHaveCSS("font-size", "12px");
await page.screenshot({ path: testInfo.outputPath("rejected-font.png") });
await page.reload();
await expect(page.getByRole("textbox", { name })).toHaveValue("'Fira Code', monospace");
await expect(page.getByRole("button", { name: "Appearance", exact: true })).toBeInViewport();
await setFontFamily(page, name, "");
await expect(page.getByRole("textbox", { name })).toHaveValue("");
});
}
test("opens settings with defaults when a malformed font was already saved", async ({ page }) => {
await page.addInitScript(() => {
localStorage.setItem(
"@paseo:app-settings",
JSON.stringify({ monoFontFamily: "'foo", uiFontFamily: '"foo' }),
);
});
await openAppearance(page);
await expect(page.getByRole("textbox", { name: "Code font family" })).toHaveValue("");
await expect(page.getByRole("textbox", { name: "Interface font family" })).toHaveValue("");
await expect(page.getByRole("button", { name: "Appearance", exact: true })).toBeInViewport();
await expect(page.getByText("Theme", { exact: true }).first()).toHaveCSS("font-size", "12px");
});
@@ -116,6 +116,7 @@ for (const version of ["0.2.5", "0.7.2", "0.8.0"]) {
);
expect(workspaces).toHaveLength(1);
gate.release();
await gate.waitForCreated();
await expect.poll(async () => (await client.fetchAgents()).entries.length).toBe(1);
const first = (await client.fetchAgents()).entries[0]!.agent;
await client.waitForFinish(first.id, 20_000);
@@ -128,6 +129,7 @@ for (const version of ["0.2.5", "0.7.2", "0.8.0"]) {
const secondPrompt = "Create another agent: emit 1 coalesced agent stream updates";
await fillComposerDraft(page, secondPrompt);
await pressSubmitBeforeTheNextRender(page, "Send message");
await gate.waitForCreated();
await expect.poll(async () => (await client.fetchAgents()).entries.length).toBe(2);
const second = (await client.fetchAgents()).entries.find(
({ agent }) => agent.id !== first.id,
@@ -206,21 +208,40 @@ for (const version of ["0.2.5", "0.7.2", "0.8.0"]) {
async function holdLegacyAgentCreation(page: Page, port: number) {
const readers = await loadSessionMessageReaders();
const arrived = Promise.withResolvers<void>();
let created = Promise.withResolvers<void>();
let createRequestId: string | undefined;
let release = () => {};
let holding = true;
await page.routeWebSocket(new RegExp(`:${port}/ws`), (browser) => {
const server = browser.connectToServer();
browser.onMessage((frame) => {
if (holding && readers.client(frame)?.type === "create_agent_request") {
const message = readers.client(frame);
if (message?.type === "create_agent_request") createRequestId = message.requestId;
if (holding && message?.type === "create_agent_request") {
holding = false;
release = () => server.send(frame);
arrived.resolve();
} else server.send(frame);
});
server.onMessage((frame) => browser.send(frame));
server.onMessage((frame) => {
const message = readers.server(frame);
if (
message?.type === "status" &&
message.payload.status === "agent_created" &&
message.payload.requestId === createRequestId
) {
created.resolve();
}
browser.send(frame);
});
});
return {
waitForRequest: () => arrived.promise,
async waitForCreated() {
// Agent-list membership includes initialization, before the initial prompt starts.
await created.promise;
created = Promise.withResolvers<void>();
},
release() {
const send = release;
release = () => {};
@@ -0,0 +1,29 @@
import { test } from "../support/fixtures";
import {
addCustomModel,
expectCustomModelRetained,
openCustomModels,
removeCustomModel,
} from "../support/helpers/custom-models";
const longModelId = "custom-model-with-a-long-name-".repeat(6);
const shortModelId = "custom-short";
for (const width of [1200, 390]) {
test(`removes a long custom model at ${width}px without removing another model`, async ({
page,
}) => {
await page.setViewportSize({ width: 1200, height: 1000 });
await openCustomModels(page);
await addCustomModel(page, shortModelId);
await addCustomModel(page, longModelId);
await test.step("remove the long model at the target width", async () => {
await page.setViewportSize({ width, height: 1000 });
await removeCustomModel(page, longModelId);
await expectCustomModelRetained(page, shortModelId);
});
await removeCustomModel(page, shortModelId);
});
}
@@ -2,10 +2,10 @@ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, type Page } from "@playwright/test";
import { test } from "../support/fixtures";
import { openFileExplorer } from "../support/helpers/file-explorer";
import { downloadFileFromExplorer, openFileExplorer } from "../support/helpers/file-explorer";
import { openChangesPanel } from "../support/helpers/workspace-tabs";
import { gotoWorkspace } from "../support/helpers/launcher";
import { daemonWsRoutePattern } from "../support/helpers/daemon-port";
import { daemonWsRoutePattern, getE2EDaemonPort } from "../support/helpers/daemon-port";
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
let workspace: SeededWorkspace;
@@ -444,3 +444,25 @@ test("hides unsupported file operations and revert actions", async ({ page }) =>
await expect(page.getByTestId("diff-file-0-duplicate")).toHaveCount(0);
await expect(page.getByTestId("diff-file-0-revert")).toHaveCount(0);
});
test("downloads a file over direct TCP with its original filename and bytes", async ({
page,
}, testInfo) => {
const fileName = "rapport données.bin";
const source = Buffer.from([0, 1, 2, 127, 128, 255, 10]);
await writeFile(path.join(workspace.workspaceDirectory, fileName), source);
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
const downloaded = await downloadFileFromExplorer(page, fileName);
const url = new URL(downloaded.url());
expect(url.protocol).toBe("http:");
expect(url.port).toBe(getE2EDaemonPort());
expect(url.pathname).toBe("/api/files/download");
expect(url.searchParams.get("token")).toBeTruthy();
expect(downloaded.suggestedFilename()).toBe(fileName);
const savedFile = testInfo.outputPath(fileName);
await downloaded.saveAs(savedFile);
expect(await downloaded.failure()).toBeNull();
expect(await readFile(savedFile)).toEqual(source);
});
@@ -241,32 +241,6 @@ test.describe("Plugin sidebar items", () => {
});
});
test("a plugin screen toggles the sidebar on a wide layout", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
const row = headerRow(page, SHOWCASE_PLUGIN_ID, "deploys");
await expect(row).toBeVisible({ timeout: 30_000 });
await row.click();
await expect(page.getByText("Deploys screen body", { exact: true })).toBeVisible();
await visibleTestId(page, "menu-button").click();
await expect(row).not.toBeVisible();
await visibleTestId(page, "menu-button").click();
await expect(row).toBeVisible();
await closeScreen(page);
// With the sidebar closed elsewhere, the screen's own toggle is the way back to it.
await visibleTestId(page, "menu-button").click();
await expect(row).not.toBeVisible();
await page.keyboard.press("Control+k");
const panel = page.getByTestId("command-center-panel");
await panel.getByTestId("command-center-input").fill("Open deploys");
await panel.getByRole("button", { name: "Open deploys", exact: true }).click();
await expect(page.getByText("Deploys screen body", { exact: true })).toBeVisible();
await visibleTestId(page, "menu-button").click();
await expect(row).toBeVisible();
});
test("a header row's shortcut hint presses the row", async ({ page }) => {
await page.setViewportSize(WIDE);
await gotoWorkspace(page, workspaceId);
@@ -0,0 +1,74 @@
import type { Page } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { seedWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
import {
expectSidebarWorkspaceSelected,
switchWorkspaceViaSidebar,
} from "../support/helpers/workspace-ui";
async function readVisibleWorkspaceOrder(page: Page): Promise<string[]> {
const rows = page.getByRole("button", { name: /^Workspace \d{2}$/ });
await expect(rows).toHaveCount(12);
return rows.evaluateAll(
(elements, prefix) =>
elements.map((element) => element.getAttribute("data-testid")!.slice(prefix.length)),
`sidebar-workspace-row-${getServerId()}:`,
);
}
async function navigateWorkspace(
page: Page,
direction: "next" | "previous",
workspaceId: string,
): Promise<void> {
await page.keyboard.press(direction === "next" ? "Alt+]" : "Alt+[");
await expectSidebarWorkspaceSelected({ page, serverId: getServerId(), workspaceId });
await expect(page).toHaveURL(new RegExp(`/workspace/${workspaceId}$`));
}
test("previous and next traverse every visible workspace while digit shortcuts stop at nine", async ({
page,
}) => {
test.setTimeout(120_000);
const project = await seedWorkspace({
repoPrefix: "relative-navigation-",
title: "Workspace 01",
});
try {
for (let index = 2; index <= 12; index += 1) {
const created = await project.client.createWorkspace({
source: { kind: "directory", path: project.repoPath },
title: `Workspace ${String(index).padStart(2, "0")}`,
});
expect(created.error).toBeNull();
}
await page.setViewportSize({ width: 1440, height: 1100 });
await gotoAppShell(page);
const order = await readVisibleWorkspaceOrder(page);
await test.step("next crosses the ninth workspace and previous returns to it", async () => {
await switchWorkspaceViaSidebar({ page, serverId: getServerId(), workspaceId: order[8] });
await navigateWorkspace(page, "next", order[9]);
await navigateWorkspace(page, "previous", order[8]);
});
await test.step("wrapping uses the true first and last visible workspace", async () => {
await switchWorkspaceViaSidebar({ page, serverId: getServerId(), workspaceId: order[0] });
await navigateWorkspace(page, "previous", order[11]);
await navigateWorkspace(page, "next", order[0]);
});
await test.step("the ninth digit shortcut still selects the ninth workspace", async () => {
await page.keyboard.press("Alt+9");
await expectSidebarWorkspaceSelected({
page,
serverId: getServerId(),
workspaceId: order[8],
});
});
} finally {
await project.cleanup();
}
});
@@ -0,0 +1,37 @@
import { expect, type Page } from "@playwright/test";
import { gotoAppShell, openSettings } from "./app";
import { openSettingsHostSection } from "./settings";
import { getServerId } from "./server-id";
export async function openCustomModels(page: Page): Promise<void> {
await gotoAppShell(page);
await openSettings(page);
await openSettingsHostSection(page, getServerId(), "providers");
await page.getByRole("button", { name: "Claude provider details", exact: true }).click();
await expect(page.getByRole("textbox", { name: "Search models" })).toBeVisible();
}
export async function addCustomModel(page: Page, id: string): Promise<void> {
await page.getByRole("button", { name: "Add model", exact: true }).click();
await page.getByPlaceholder("e.g. openai/gpt-5").fill(id);
await page
.getByTestId("add-custom-model-sheet")
.getByRole("button", { name: "Add", exact: true })
.click();
await expect(page.getByRole("button", { name: `Remove ${id}`, exact: true })).toHaveCount(1);
}
export async function removeCustomModel(page: Page, id: string): Promise<void> {
await page.getByRole("textbox", { name: "Search models" }).fill(id);
const remove = page.getByRole("button", { name: `Remove ${id}`, exact: true });
await expect(remove).toBeInViewport({ ratio: 1 });
await remove.click();
await expect(remove).toHaveCount(0);
}
export async function expectCustomModelRetained(page: Page, id: string): Promise<void> {
await page.getByRole("textbox", { name: "Search models" }).fill(id);
await expect(page.getByRole("button", { name: `Remove ${id}`, exact: true })).toBeInViewport({
ratio: 1,
});
}
@@ -1,4 +1,4 @@
import { expect, type Page } from "@playwright/test";
import { expect, type Download, type Page } from "@playwright/test";
import { openFilesPanel } from "./workspace-tabs";
function fileExplorerTree(page: Page) {
@@ -39,3 +39,10 @@ export async function expectFileTabOpen(page: Page, filePath: string): Promise<v
timeout: 30_000,
});
}
export async function downloadFileFromExplorer(page: Page, fileName: string): Promise<Download> {
await fileExplorerEntry(page, fileName).click({ button: "right" });
const downloaded = page.waitForEvent("download");
await page.getByRole("menuitem", { name: "Download", exact: true }).click();
return downloaded;
}
@@ -3,6 +3,71 @@ import { describe, expect, it } from "vitest";
import { normalizeHtmlishMarkdown, splitHtmlishMarkdown } from "./html-ish";
describe("splitHtmlishMarkdown", () => {
it("renders heading text beside a linked picture without literal heading tags", () => {
const source =
'<h2><a href="https://example.com/r"><picture><source srcset="https://example.com/d.svg"><img alt="Retrigger" src="https://example.com/l.svg"></picture></a>Confidence Score: 5/5</h2>';
expect(splitHtmlishMarkdown(source)).toEqual([
{
kind: "inlineImage",
alt: "Retrigger",
src: "https://example.com/l.svg",
href: "https://example.com/r",
flowsWithText: true,
},
{ kind: "markdown", text: "Confidence Score: 5/5" },
]);
});
it.each(["h1", "h2", "h3", "h4", "h5", "h6"])(
"keeps a mixed %s heading together after preceding markdown",
(heading) => {
const source = `Intro\n\n<${heading}><img alt="Icon" src="https://example.com/icon.svg">Caption</${heading}>\n\nOutro`;
expect(splitHtmlishMarkdown(source)).toEqual([
{ kind: "markdown", text: "Intro\n\n" },
{
kind: "inlineImage",
alt: "Icon",
src: "https://example.com/icon.svg",
flowsWithText: true,
},
{ kind: "markdown", text: "Caption\n\nOutro" },
]);
},
);
it("preserves formatted text before and after images in a details heading", () => {
const source =
'<details><summary>More</summary><h2><strong>Before</strong><img alt="Icon" src="https://example.com/icon.svg"><em>After</em></h2></details>';
expect(splitHtmlishMarkdown(source)).toEqual([
{
kind: "details",
summary: "More",
body: "**Before***After*",
bodyParts: [
{ kind: "markdown", text: "**Before**" },
{ kind: "inlineImage", alt: "Icon", src: "https://example.com/icon.svg" },
{ kind: "markdown", text: "*After*" },
],
},
]);
});
it("keeps mixed HTML headings literal in code examples", () => {
const heading = '<h2><img src="https://example.com/icon.svg">Caption</h2>';
const source = `Use \`${heading}\`\n\n\`\`\`html\n${heading}\n\`\`\``;
expect(splitHtmlishMarkdown(source)).toEqual([{ kind: "markdown", text: source }]);
});
it("preserves unknown wrappers around text-only headings", () => {
expect(splitHtmlishMarkdown("<section><h2>Heading</h2></section>")).toEqual([
{ kind: "markdown", text: "<section>Heading</section>" },
]);
});
const inlineImageBody = [
'<a href="#"><img alt="Priority" src="https://example.com/assets/priority.svg?v=9" align="top"></a> Spoofed browser User-Agent allows access control bypass',
"",
@@ -125,9 +125,20 @@ function splitHtmlishTokens(tokens: HtmlToken[]): MarkdownDisplayPart[] {
continue;
}
const nextDetailsIndex = findNextOpenTag(tokens, cursor + 1, "details");
const nextInlineImageIndex = findNextInlineImageIndex(tokens, cursor + 1);
const end = Math.min(nextDetailsIndex ?? tokens.length, nextInlineImageIndex ?? tokens.length);
if (isHeadingTag(token)) {
const closeIndex = findMixedHeadingClose(tokens, cursor);
if (closeIndex !== null) {
// Headings render as their contents. Split those contents together so an
// embedded image cannot strand the opening heading tag in a text slice.
for (const part of splitHtmlishTokens(tokens.slice(cursor + 1, closeIndex))) {
appendDisplayPart(parts, part);
}
cursor = closeIndex + 1;
continue;
}
}
const end = findNextDisplayPartIndex(tokens, cursor + 1) ?? tokens.length;
appendMarkdownPart(parts, renderInlineTokens(tokens.slice(cursor, end)));
cursor = end;
}
@@ -259,15 +270,44 @@ function flowsWithFollowingText(tokens: HtmlToken[], start: number, end: number)
return false;
}
function findNextInlineImageIndex(tokens: HtmlToken[], start: number): number | null {
function findNextDisplayPartIndex(tokens: HtmlToken[], start: number): number | null {
for (let index = start; index < tokens.length; index += 1) {
if (parseInlineImageAt(tokens, index)) {
if (
isOpenTag(tokens[index], "details") ||
findMixedHeadingClose(tokens, index) !== null ||
parseInlineImageAt(tokens, index)
) {
return index;
}
}
return null;
}
function findMixedHeadingClose(tokens: HtmlToken[], start: number): number | null {
const token = tokens[start];
if (!isHeadingTag(token)) {
return null;
}
const closeIndex = findMatchingClose(tokens, start, token.name);
if (closeIndex === null) {
return null;
}
for (let index = start + 1; index < closeIndex; index += 1) {
if (parseInlineImageAt(tokens, index)) {
return closeIndex;
}
}
return null;
}
function appendDisplayPart(parts: MarkdownDisplayPart[], part: MarkdownDisplayPart): void {
if (part.kind === "markdown") {
appendMarkdownPart(parts, part.text);
} else {
parts.push(part);
}
}
function appendMarkdownPart(parts: MarkdownDisplayPart[], text: string): void {
if (!text) {
return;
@@ -95,11 +95,11 @@ function CustomModelRow({
return (
<View style={sheetStyles.modelRow}>
<Text style={sheetStyles.modelTitle} numberOfLines={1}>
<Text style={[sheetStyles.modelTitle, sheetStyles.customModelText]} numberOfLines={1}>
{model.label}
</Text>
<Text
style={sheetStyles.monoHint}
style={[sheetStyles.monoHint, sheetStyles.customModelText]}
numberOfLines={1}
selectable
dataSet={CODE_SURFACE_DATASET}
@@ -762,6 +762,7 @@ const sheetStyles = StyleSheet.create((theme) => ({
iconButton: {
width: 28,
height: 28,
flexShrink: 0,
borderRadius: theme.borderRadius.full,
alignItems: "center",
justifyContent: "center",
@@ -807,6 +808,10 @@ const sheetStyles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.base,
flexShrink: 0,
},
customModelText: {
flexShrink: 1,
minWidth: 0,
},
modelRowFiller: {
flex: 1,
},
+15 -5
View File
@@ -1,5 +1,5 @@
import { useCallback, useMemo } from "react";
import { useHosts } from "@/runtime/host-runtime";
import { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime";
import { useDownloadStore } from "@/stores/download-store";
import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions";
@@ -12,8 +12,9 @@ interface UseFileDownloadParams {
/**
* Returns a stable callback that downloads a single workspace file by its
* workspace-relative path. Shared by the file explorer tree and the git diff
* pane so both surfaces download through the same host token + download-store
* pipeline instead of duplicating the plumbing.
* pane so both surfaces download through the same download-store pipeline instead
* of duplicating the plumbing: the HTTP token download over a direct TCP connection,
* the session socket over anything else.
*/
export function useFileDownload({
serverId,
@@ -30,7 +31,7 @@ export function useFileDownload({
() => workspaceId?.trim() || normalizedWorkspaceRoot,
[normalizedWorkspaceRoot, workspaceId],
);
const { requestFileDownloadToken } = useFileExplorerActions({
const { requestFileDownloadToken, requestFileBytes } = useFileExplorerActions({
serverId,
workspaceId,
workspaceRoot: normalizedWorkspaceRoot,
@@ -48,9 +49,18 @@ export function useFileDownload({
fileName,
path,
daemonProfile,
activeConnectionId: getHostRuntimeStore().getSnapshot(serverId)?.activeConnectionId ?? null,
requestFileDownloadToken: (targetPath) => requestFileDownloadToken(targetPath),
readFile: requestFileBytes,
});
},
[daemonProfile, requestFileDownloadToken, serverId, startDownload, workspaceScopeId],
[
daemonProfile,
requestFileBytes,
requestFileDownloadToken,
serverId,
startDownload,
workspaceScopeId,
],
);
}
@@ -253,6 +253,21 @@ export function useFileExplorerActions(params: { serverId: string } & FileExplor
[client, normalizedWorkspaceRoot, t],
);
const requestFileBytes = useCallback(
async (path: string, maxBytes: number) => {
if (!normalizedWorkspaceRoot) {
throw new Error(t("workspace.fileExplorer.states.unavailable"));
}
if (!client) {
throw new Error(t("workspace.terminal.hostDisconnected"));
}
// No request timeout: a large file over a slow relay legitimately takes longer than the
// 60 s default, and a dead connection still rejects on disconnect.
return client.readFile(normalizedWorkspaceRoot, path, undefined, maxBytes, 0);
},
[client, normalizedWorkspaceRoot, t],
);
const createEntry = useCallback(
async (input: { parentPath: string; name: string; kind: "file" | "directory" }) => {
if (!client || !normalizedWorkspaceRoot) {
@@ -342,6 +357,7 @@ export function useFileExplorerActions(params: { serverId: string } & FileExplor
requestDirectoryListing,
requestFilePreview,
requestFileDownloadToken,
requestFileBytes,
createEntry,
renameEntry,
duplicateEntry,
@@ -15,6 +15,7 @@ import {
parseClampedFontSize,
parseTerminalScrollbackLines,
resolveContentMaxWidth,
sanitizeFontFamily,
saveAppSettings,
type SettingsDeps,
} from "./storage";
@@ -1094,3 +1095,34 @@ describe("content max width", () => {
expect((await load("wide")).contentMaxWidth).toBeNull();
});
});
describe("font family CSS safety", () => {
it.each(["'foo", '"foo', "Menlo, 'foo", "foo\\", "foo/*", "foo(", "foo["])(
"rejects unfinished CSS syntax: %s",
(value) => expect(sanitizeFontFamily(value)).toBeNull(),
);
it.each([
"Menlo",
"'Fira Code', monospace",
'"Fira Code", monospace',
"'Font\\'s name'",
"Font\\ Name",
"'Font (Mono)'",
"'Font [Mono]'",
])("preserves complete font families: %s", (value) =>
expect(sanitizeFontFamily(value)).toBe(value),
);
it.each(["uiFontFamily", "monoFontFamily"])(
"recovers a persisted unmatched quote in %s",
async (field) => {
const deps = makeDeps({
storage: createInMemoryKeyValueStorage({
[APP_SETTINGS_KEY]: JSON.stringify({ [field]: "'foo" }),
}),
});
expect(await loadAppSettingsFromStorage(deps)).toMatchObject({ [field]: "" });
},
);
});
+18 -1
View File
@@ -522,7 +522,24 @@ export function sanitizeFontFamily(value: unknown): string | null {
if ([...trimmed].some((char) => char.charCodeAt(0) <= 0x1f)) {
return null; // control chars would corrupt the font-family string
}
return trimmed; // quotes/commas are legit in stacks
// Unistyles serializes theme values into one shared stylesheet. An unfinished
// string, escape, comment, or block consumes the declarations that follow.
let quote: string | null = null;
let escaped = false;
for (const char of trimmed) {
if (escaped) {
escaped = false;
} else if (char === "\\") {
escaped = true;
} else if (quote !== null) {
if (char === quote) quote = null;
} else if (char === "'" || char === '"') {
quote = char;
} else if (/[()[\]/*]/.test(char)) {
return null;
}
}
return quote === null && !escaped ? trimmed : null;
}
async function loadLegacyDesktopSettingsFromStorage(storage: KeyValueStorage): Promise<{
@@ -8,7 +8,6 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { HeaderIconBadge } from "@/components/headers/header-icon-badge";
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
import { CompactHeader } from "@/components/headers/compact-header";
import { SidebarMenuToggle } from "@/components/headers/sidebar-menu-toggle";
import { ScreenHeader } from "@/components/headers/screen-header";
import { ScreenTitle } from "@/components/headers/screen-title";
import { HostFilter } from "@/components/hosts/host-filter";
@@ -173,7 +172,6 @@ export function PluginSurfaceScreen() {
const headerLeft = useMemo(
() => (
<>
<SidebarMenuToggle />
{Icon ? (
<HeaderIconBadge>
<ThemedPluginHeaderIcon Icon={Icon} uniProps={mutedColorMapping} />
@@ -241,7 +241,7 @@ interface FontFamilyRowProps {
draft: string;
withBorder: boolean;
onChangeDraft: (value: string) => void;
onCommit: (value: string) => void;
onCommit: (value: string) => string;
}
function FontFamilyRow({
@@ -255,13 +255,16 @@ function FontFamilyRow({
onChangeDraft,
onCommit,
}: FontFamilyRowProps) {
const inputRef = useRef<EditingTextInputHandle>(null);
const handleCommit = useCallback(() => {
onCommit(draft);
const committed = onCommit(draft);
inputRef.current?.replaceText(committed);
}, [draft, onCommit]);
// Resync from the committed value when it changes elsewhere.
useEffect(() => {
onChangeDraft(value);
inputRef.current?.replaceText(value);
// Only resync on external value changes, not on local keystrokes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);
@@ -273,6 +276,7 @@ function FontFamilyRow({
<Text style={settingsStyles.rowHint}>{hint}</Text>
</View>
<TextInput
ref={inputRef}
initialValue={draft}
onChangeText={onChangeDraft}
onBlur={handleCommit}
@@ -533,12 +537,13 @@ export function AppearanceSection() {
const sanitized = sanitizeFontFamily(value);
if (sanitized === null) {
setUiFontDraft(settings.uiFontFamily);
return;
return settings.uiFontFamily;
}
setUiFontDraft(sanitized);
if (sanitized !== settings.uiFontFamily) {
void updateSettings({ uiFontFamily: sanitized });
}
return sanitized;
},
[settings.uiFontFamily, updateSettings],
);
@@ -548,12 +553,13 @@ export function AppearanceSection() {
const sanitized = sanitizeFontFamily(value);
if (sanitized === null) {
setMonoFontDraft(settings.monoFontFamily);
return;
return settings.monoFontFamily;
}
setMonoFontDraft(sanitized);
if (sanitized !== settings.monoFontFamily) {
void updateSettings({ monoFontFamily: sanitized });
}
return sanitized;
},
[settings.monoFontFamily, updateSettings],
);
@@ -0,0 +1,265 @@
import { beforeEach, describe, expect, it } from "vitest";
import { defaultHostAppearance } from "@/hosts/appearance";
import { i18n } from "@/i18n/i18next";
import {
MAX_SESSION_DOWNLOAD_BYTES,
useDownloadStore,
type Download,
type DownloadedBytes,
} from "@/stores/download-store";
import type {
DirectTcpHostConnection,
HostProfile,
RelayHostConnection,
} from "@/types/host-connection";
const FILE_BYTES = new TextEncoder().encode("relay download payload");
const FILE_PATH = "reports/données été.bin";
const FILE_NAME = "données été.bin";
const MIME_TYPE = "application/octet-stream";
const relayConnection: RelayHostConnection = {
id: "relay:relay.paseo.sh:443",
type: "relay",
relayEndpoint: "relay.paseo.sh:443",
daemonPublicKeyB64: "cHVibGljLWtleQ==",
};
// The #3753 shape: the relay hostname stored as a directTcp entry that nothing can reach.
const staleTcpConnection: DirectTcpHostConnection = {
id: "direct:relay.paseo.sh:443",
type: "directTcp",
endpoint: "relay.paseo.sh:443",
};
const localTcpConnection: DirectTcpHostConnection = {
id: "direct:localhost:6767",
type: "directTcp",
endpoint: "localhost:6767",
};
function profileWith(connections: HostProfile["connections"]): HostProfile {
return {
serverId: "srv_remote",
label: "Remote",
appearance: defaultHostAppearance(),
lifecycle: {},
connections,
preferredConnectionId: null,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
};
}
function createTokenRequest(size: number | null = FILE_BYTES.byteLength) {
const requested: string[] = [];
return {
requested,
request: async (path: string) => {
requested.push(path);
return { token: "tok", fileName: FILE_NAME, mimeType: MIME_TYPE, size, error: null };
},
};
}
function createFileReader(read: () => Promise<{ bytes: Uint8Array; size: number }>) {
const requested: string[] = [];
return {
requested,
read: async (path: string) => {
requested.push(path);
return read();
},
};
}
function createFileSaver() {
const savedFiles: DownloadedBytes[] = [];
return {
savedFiles,
save: async (file: DownloadedBytes) => {
savedFiles.push(file);
return null;
},
};
}
interface StartInput {
profile: HostProfile;
activeConnectionId: string | null;
token?: ReturnType<typeof createTokenRequest>;
reader?: ReturnType<typeof createFileReader>;
saver?: ReturnType<typeof createFileSaver>;
}
async function startDownload(input: StartInput): Promise<Download | undefined> {
const token = input.token ?? createTokenRequest();
const reader =
input.reader ??
createFileReader(async () => ({ bytes: FILE_BYTES, size: FILE_BYTES.byteLength }));
const saver = input.saver ?? createFileSaver();
await useDownloadStore.getState().startDownload({
serverId: "srv_remote",
scopeId: "workspace-1",
fileName: FILE_NAME,
path: FILE_PATH,
daemonProfile: input.profile,
activeConnectionId: input.activeConnectionId,
requestFileDownloadToken: token.request,
readFile: reader.read,
saveFile: saver.save,
});
const { activeDownloadId, downloads } = useDownloadStore.getState();
return activeDownloadId ? downloads.get(activeDownloadId) : undefined;
}
describe("download store transport selection", () => {
beforeEach(() => {
useDownloadStore.setState({ downloads: new Map(), activeDownloadId: null });
});
it("downloads over the session when the active connection is the relay", async () => {
const token = createTokenRequest();
const reader = createFileReader(async () => ({
bytes: FILE_BYTES,
size: FILE_BYTES.byteLength,
}));
const saver = createFileSaver();
const download = await startDownload({
profile: profileWith([relayConnection]),
activeConnectionId: relayConnection.id,
token,
reader,
saver,
});
expect(download).toMatchObject({ fileName: FILE_NAME, status: "complete" });
expect(token.requested).toEqual([FILE_PATH]);
expect(reader.requested).toEqual([FILE_PATH]);
expect(saver.savedFiles).toEqual([
{ bytes: FILE_BYTES, fileName: FILE_NAME, mimeType: MIME_TYPE },
]);
});
it("bounds the session read even when the token reports a smaller file", async () => {
const readRequests: Array<{ path: string; maxBytes: number }> = [];
const saver = createFileSaver();
await useDownloadStore.getState().startDownload({
serverId: "srv_remote",
scopeId: "workspace-1",
fileName: FILE_NAME,
path: FILE_PATH,
daemonProfile: profileWith([relayConnection]),
activeConnectionId: relayConnection.id,
requestFileDownloadToken: createTokenRequest(1).request,
readFile: async (path: string, maxBytes: number) => {
readRequests.push({ path, maxBytes });
return { bytes: FILE_BYTES, size: FILE_BYTES.byteLength };
},
saveFile: saver.save,
});
expect(readRequests).toEqual([{ path: FILE_PATH, maxBytes: MAX_SESSION_DOWNLOAD_BYTES }]);
expect(saver.savedFiles).toEqual([
{ bytes: FILE_BYTES, fileName: FILE_NAME, mimeType: MIME_TYPE },
]);
});
it("ignores a directTcp entry that is not the active connection", async () => {
const reader = createFileReader(async () => ({
bytes: FILE_BYTES,
size: FILE_BYTES.byteLength,
}));
const saver = createFileSaver();
const download = await startDownload({
profile: profileWith([staleTcpConnection, relayConnection]),
activeConnectionId: relayConnection.id,
reader,
saver,
});
expect(download).toMatchObject({ status: "complete" });
expect(reader.requested).toEqual([FILE_PATH]);
expect(saver.savedFiles).toHaveLength(1);
});
it("keeps the HTTP token download when the active connection is directTcp", async () => {
const reader = createFileReader(async () => ({
bytes: FILE_BYTES,
size: FILE_BYTES.byteLength,
}));
const saver = createFileSaver();
const download = await startDownload({
profile: profileWith([localTcpConnection, relayConnection]),
activeConnectionId: localTcpConnection.id,
reader,
saver,
});
expect(download).toMatchObject({ status: "complete" });
expect(reader.requested).toEqual([]);
expect(saver.savedFiles).toEqual([]);
});
it("fails the download and saves nothing when the session read fails", async () => {
const reader = createFileReader(async () => {
throw new Error("Connection lost");
});
const saver = createFileSaver();
const download = await startDownload({
profile: profileWith([relayConnection]),
activeConnectionId: relayConnection.id,
reader,
saver,
});
expect(download).toMatchObject({ status: "error", message: "Connection lost" });
expect(saver.savedFiles).toEqual([]);
});
it("refuses a file over the session size limit before reading it", async () => {
const token = createTokenRequest(MAX_SESSION_DOWNLOAD_BYTES + 1);
const reader = createFileReader(async () => ({
bytes: FILE_BYTES,
size: FILE_BYTES.byteLength,
}));
const saver = createFileSaver();
const download = await startDownload({
profile: profileWith([relayConnection]),
activeConnectionId: relayConnection.id,
token,
reader,
saver,
});
expect(download).toMatchObject({
status: "error",
message: i18n.t("composer.errors.fileTooLarge", { fileName: FILE_NAME, size: "64 MB" }),
});
expect(download?.message).toContain("64 MB");
expect(reader.requested).toEqual([]);
expect(saver.savedFiles).toEqual([]);
});
it("fails instead of saving an empty file when the daemon returns no content", async () => {
const reader = createFileReader(async () => ({ bytes: new Uint8Array(), size: 6 }));
const saver = createFileSaver();
const download = await startDownload({
profile: profileWith([relayConnection]),
activeConnectionId: relayConnection.id,
reader,
saver,
});
expect(download).toMatchObject({
status: "error",
message: "File transfer incomplete: expected 6 bytes, received 0.",
});
expect(saver.savedFiles).toEqual([]);
});
});
+105 -14
View File
@@ -16,6 +16,16 @@ interface DownloadProgress {
eta: number;
}
// The session path holds the file in memory two to three times over (client chunks, the
// concatenated result, then the Blob or native write). Lift once the client streams chunks to disk.
export const MAX_SESSION_DOWNLOAD_BYTES = 64 * 1024 * 1024;
export interface DownloadedBytes {
bytes: Uint8Array;
fileName: string;
mimeType: string | null;
}
export interface Download {
id: string;
serverId: string;
@@ -37,12 +47,18 @@ interface DownloadState {
fileName: string;
path: string;
daemonProfile: HostProfile | undefined;
/** Connection the host runtime is using right now; `null` while disconnected. */
activeConnectionId: string | null;
requestFileDownloadToken: (path: string) => Promise<{
token: string | null;
fileName: string | null;
mimeType: string | null;
size: number | null;
error: string | null;
}>;
/** Reads the whole file over the session socket; used when no direct HTTP endpoint is active. */
readFile: (path: string, maxBytes: number) => Promise<{ bytes: Uint8Array; size: number }>;
saveFile?: typeof saveDownloadedBytes;
}) => Promise<void>;
updateProgress: (id: string, progress: DownloadProgress) => void;
@@ -66,7 +82,10 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
fileName,
path,
daemonProfile,
activeConnectionId,
requestFileDownloadToken,
readFile,
saveFile = saveDownloadedBytes,
}) => {
const id = generateDownloadId();
const download: Download = {
@@ -89,12 +108,42 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
throw new Error(tokenResponse.error ?? i18n.t("downloads.requestTokenFailed"));
}
const downloadTarget = resolveDaemonDownloadTarget(daemonProfile);
const resolvedFileName = tokenResponse.fileName ?? fileName;
const downloadTarget = resolveDaemonDownloadTarget(daemonProfile, activeConnectionId);
if (!downloadTarget) {
// Relay, SSH, socket and pipe hosts have no HTTP endpoint: read the file over the
// session socket that is already connected (#543).
if (
typeof tokenResponse.size === "number" &&
tokenResponse.size > MAX_SESSION_DOWNLOAD_BYTES
) {
throw new Error(
i18n.t("composer.errors.fileTooLarge", { fileName: resolvedFileName, size: "64 MB" }),
);
}
const { bytes, size } = await readFile(path, MAX_SESSION_DOWNLOAD_BYTES);
// A daemon without a binary channel answers `encoding: "none"` for a binary file: no
// content, real size. Never save that as a complete download.
if (bytes.byteLength !== size) {
throw new Error(
`File transfer incomplete: expected ${size} bytes, received ${bytes.byteLength}.`,
);
}
const savedUri = await saveFile({
bytes,
fileName: resolvedFileName,
mimeType: tokenResponse.mimeType,
});
get().completeDownload(id);
if (savedUri !== null) {
await shareSavedFile(savedUri, tokenResponse.mimeType, resolvedFileName);
}
return;
}
if (!downloadTarget.baseUrl) {
throw new Error(i18n.t("downloads.hostUnavailable"));
}
const resolvedFileName = tokenResponse.fileName ?? fileName;
const downloadUrl = buildDownloadUrl(
downloadTarget.baseUrl,
tokenResponse.token,
@@ -146,14 +195,7 @@ export const useDownloadStore = create<DownloadState>()((set, get) => ({
get().completeDownload(id);
if (await Sharing.isAvailableAsync()) {
await Sharing.shareAsync(result.uri, {
mimeType: tokenResponse.mimeType ?? undefined,
dialogTitle: resolvedFileName
? i18n.t("downloads.shareFileNamed", { fileName: resolvedFileName })
: i18n.t("downloads.shareFile"),
});
}
await shareSavedFile(result.uri, tokenResponse.mimeType, resolvedFileName);
} catch (error) {
const message = error instanceof Error ? error.message : i18n.t("downloads.failed");
if (isWeb) {
@@ -244,10 +286,18 @@ interface DownloadTarget {
authCredentials: { username: string; password: string } | null;
}
function resolveDaemonDownloadTarget(daemon?: HostProfile): DownloadTarget {
const connection = daemon?.connections.find((conn) => conn.type === "directTcp") ?? null;
if (!connection) {
return { baseUrl: null, authHeader: null, authCredentials: null };
/**
* The HTTP download route is only reachable over a direct TCP connection. Returns `null` when
* the connection in use is anything else (relay, SSH, socket, pipe, or none yet), so the caller
* reads the file over the session socket instead.
*/
function resolveDaemonDownloadTarget(
daemon: HostProfile | undefined,
activeConnectionId: string | null,
): DownloadTarget | null {
const connection = daemon?.connections.find((conn) => conn.id === activeConnectionId);
if (connection?.type !== "directTcp") {
return null;
}
let parsed: URL;
@@ -299,6 +349,47 @@ function buildDownloadUrl(
return url.toString();
}
/**
* Saves bytes read over the session. Web and Electron hand them to the browser's download
* manager and return `null`; native writes the file and returns its URI for the share sheet.
*/
async function saveDownloadedBytes({
bytes,
fileName,
mimeType,
}: DownloadedBytes): Promise<string | null> {
if (isWeb) {
const buffer = new ArrayBuffer(bytes.byteLength);
new Uint8Array(buffer).set(bytes);
const url = URL.createObjectURL(
new Blob([buffer], { type: mimeType ?? "application/octet-stream" }),
);
triggerBrowserDownload(url, fileName);
// The browser may still be reading the blob while its save prompt is open.
setTimeout(() => URL.revokeObjectURL(url), 60_000);
return null;
}
// Resolve and write in one tick so two downloads of the same name cannot pick the same path.
const targetFile = resolveDownloadTargetFile(fileName);
targetFile.write(bytes);
return targetFile.uri;
}
async function shareSavedFile(
uri: string,
mimeType: string | null,
fileName: string,
): Promise<void> {
if (await Sharing.isAvailableAsync()) {
await Sharing.shareAsync(uri, {
mimeType: mimeType ?? undefined,
dialogTitle: fileName
? i18n.t("downloads.shareFileNamed", { fileName })
: i18n.t("downloads.shareFile"),
});
}
}
function triggerBrowserDownload(url: string, fileName: string) {
if (typeof document === "undefined") {
if (typeof window !== "undefined") {
@@ -5,6 +5,7 @@ import type {
SidebarWorkspaceEntry,
} from "@/hooks/use-sidebar-workspaces-list";
import { buildStatusGroups } from "@/hooks/sidebar-status-view-model";
import { routeKeyboardShortcut } from "@/keyboard/route-shortcut";
import {
buildSidebarShortcutModel,
@@ -65,6 +66,46 @@ function project(projectKey: string, workspaces: SidebarWorkspaceEntry[]): Sideb
}
describe("buildSidebarShortcutModel", () => {
it.each([
[9, 1, 10],
[10, -1, 9],
[12, 1, 1],
[1, -1, 12],
] as const)(
"navigates from workspace %i by %i to workspace %i across the full visible sidebar",
(current, delta, next) => {
const workspaces = Array.from({ length: 12 }, (_, index) =>
workspace({
serverId: "s",
workspaceId: `ws-${index + 1}`,
workspaceDirectory: `/repo/w${index + 1}`,
name: `w${index + 1}`,
}),
);
const model = buildSidebarShortcutModel({
projects: [project("p", workspaces)],
collapsedProjectKeys: new Set<string>(),
});
expect(
routeKeyboardShortcut(
{ action: "workspace.navigate.relative", payload: { delta } },
{
pathname: `/h/s/workspace/ws-${current}`,
isMobile: false,
sidebarShortcutTargets: model.shortcutTargets,
navigationActiveWorkspace: null,
commandCenterOpen: false,
shortcutsDialogOpen: false,
},
),
).toEqual({ kind: "navigate-workspace", serverId: "s", workspaceId: `ws-${next}` });
expect(model.shortcutIndexByWorkspaceKey.size).toBe(9);
expect(model.shortcutIndexByWorkspaceKey.get("s:ws-9")).toBe(9);
expect(model.shortcutIndexByWorkspaceKey.has("s:ws-10")).toBe(false);
},
);
it("builds shortcut targets in visual order and excludes collapsed projects", () => {
const projects = [
project("p1", [
@@ -111,7 +152,7 @@ describe("buildSidebarShortcutModel", () => {
expect(model.shortcutIndexByWorkspaceKey.get("s1:ws-repo2-main")).toBeUndefined();
});
it("limits shortcuts to 9", () => {
it("keeps all traversal targets while numbering only the first 9", () => {
const workspaces = Array.from({ length: 20 }, (_, index) =>
workspace({
serverId: "s",
@@ -127,9 +168,11 @@ describe("buildSidebarShortcutModel", () => {
collapsedProjectKeys: new Set<string>(),
});
expect(model.shortcutTargets).toHaveLength(9);
expect(model.shortcutTargets[0]).toEqual({ serverId: "s", workspaceId: "ws-1" });
expect(model.shortcutTargets).toHaveLength(20);
expect(model.shortcutTargets[8]).toEqual({ serverId: "s", workspaceId: "ws-9" });
expect(model.shortcutTargets[9]).toEqual({ serverId: "s", workspaceId: "ws-10" });
expect(model.shortcutIndexByWorkspaceKey.get("s:ws-9")).toBe(9);
expect(model.shortcutIndexByWorkspaceKey.get("s:ws-10")).toBeUndefined();
});
it("excludes a collapsed project's workspaces regardless of project kind", () => {
+3 -6
View File
@@ -70,13 +70,10 @@ export function buildSidebarShortcutSections(input: {
}
for (const workspace of section.workspaces) {
if (shortcutTargets.length >= maxShortcuts) {
break;
}
const shortcutNumber = shortcutTargets.length + 1;
shortcutTargets.push(createShortcutTarget(workspace));
shortcutIndexByWorkspaceKey.set(workspace.workspaceKey, shortcutNumber);
if (shortcutTargets.length <= maxShortcuts) {
shortcutIndexByWorkspaceKey.set(workspace.workspaceKey, shortcutTargets.length);
}
}
}
+96
View File
@@ -2801,6 +2801,102 @@ test("readFile drops an old daemon's over-budget binary chunks and reports the r
await expect(responsePromise).rejects.toThrow("File is too large to display");
});
async function connectFileClient(clientId: string) {
const mock = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId,
logger: createMockLogger(),
reconnect: { enabled: false },
transportFactory: () => mock.transport,
});
clients.push(client);
const connectPromise = client.connect();
mock.triggerOpen();
await connectPromise;
return { mock, client };
}
function sendBinaryFile(
mock: ReturnType<typeof createMockTransport>,
requestId: string,
announcedSize: number,
chunks: string[],
) {
mock.triggerMessage(
encodeFileTransferFrame({
opcode: FileTransferOpcode.FileBegin,
requestId,
metadata: {
mime: "application/octet-stream",
size: announcedSize,
encoding: "binary",
modifiedAt: "2026-05-02T00:00:00.000Z",
},
}),
);
for (const chunk of chunks) {
mock.triggerMessage(
encodeFileTransferFrame({
opcode: FileTransferOpcode.FileChunk,
requestId,
payload: new TextEncoder().encode(chunk),
}),
);
}
}
test("readFile with timeout 0 outlives the default request timeout", async () => {
useHeartbeatClock();
const { mock, client } = await connectFileClient("clsk_file_no_timeout");
const responsePromise = client.readFile("/tmp/project", "slow.bin", "req-slow", undefined, 0);
await vi.advanceTimersByTimeAsync(60_001);
sendBinaryFile(mock, "req-slow", 5, ["hello"]);
mock.triggerMessage(
encodeFileTransferFrame({ opcode: FileTransferOpcode.FileEnd, requestId: "req-slow" }),
);
const result = await responsePromise;
expect(result.size).toBe(5);
expect(new TextDecoder().decode(result.bytes)).toBe("hello");
});
test("readFile rejects a binary transfer that ends before the announced size", async () => {
const { mock, client } = await connectFileClient("clsk_file_short");
const responsePromise = client.readFile("/tmp/project", "short.bin", "req-short");
sendBinaryFile(mock, "req-short", 10, ["hello"]);
mock.triggerMessage(
encodeFileTransferFrame({ opcode: FileTransferOpcode.FileEnd, requestId: "req-short" }),
);
await expect(responsePromise).rejects.toThrow(
"File transfer incomplete: expected 10 bytes, received 5.",
);
});
test("readFile rejects a binary transfer that exceeds the announced size", async () => {
const { mock, client } = await connectFileClient("clsk_file_long");
const responsePromise = client.readFile("/tmp/project", "long.bin", "req-long");
const settled = responsePromise.then(
() => null,
(error: unknown) => error,
);
sendBinaryFile(mock, "req-long", 4, ["hello!"]);
expect(() =>
mock.triggerMessage(
encodeFileTransferFrame({ opcode: FileTransferOpcode.FileEnd, requestId: "req-long" }),
),
).not.toThrow();
expect(await settled).toMatchObject({
message: "File transfer incomplete: expected 4 bytes, received 6.",
});
});
test("uploadFile sends metadata request and file bytes as binary chunks", async () => {
const logger = createMockLogger();
const mock = createMockTransport();
+21
View File
@@ -4758,6 +4758,7 @@ export class DaemonClient {
requestId?: string,
acceptBinary = false,
maxBytes?: number,
timeout?: number,
): Promise<FileExplorerPayload> {
return this.sendCorrelatedSessionRequest({
requestId,
@@ -4770,6 +4771,7 @@ export class DaemonClient {
...(maxBytes ? { maxBytes } : {}),
},
responseType: "file_explorer_response",
timeout,
});
}
@@ -4788,11 +4790,17 @@ export class DaemonClient {
return payload.directory;
}
/**
* `timeout` bounds the whole transfer, not each frame. `0` disables the timer (as
* `workspace.create` does) for files that legitimately take longer than the default over a
* slow link; a dead connection still rejects on disconnect.
*/
async readFile(
cwd: string,
path: string,
requestId?: string,
maxBytes?: number,
timeout?: number,
): Promise<FileReadResult> {
const resolvedRequestId = this.createRequestId(requestId);
this.pendingBinaryFileReads.set(resolvedRequestId, { cwd, path, maxBytes });
@@ -4804,6 +4812,7 @@ export class DaemonClient {
resolvedRequestId,
true,
maxBytes,
timeout,
);
if (payload.error) {
throw new Error(payload.error);
@@ -6540,6 +6549,18 @@ export class DaemonClient {
return;
}
const received = transfer.chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
if (received !== transfer.size) {
this.activeBinaryFileTransfers.delete(frame.requestId);
this.rejectWaitersForRequestId(
frame.requestId,
new Error(
`File transfer incomplete: expected ${transfer.size} bytes, received ${received}.`,
),
);
return;
}
const bytes = concatByteChunks(transfer.chunks, transfer.size);
this.activeBinaryFileTransfers.delete(frame.requestId);
this.completedBinaryFileReads.set(frame.requestId, {
@@ -0,0 +1,88 @@
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
const modulePath = fileURLToPath(new URL("./console-streams.ts", import.meta.url));
type Output = "stdout" | "stderr";
async function writeToConsole(input: { closed?: Output; invalidStdout?: boolean } = {}) {
const child = spawn(
process.execPath,
[
"--import",
"tsx",
"-e",
`
const { protectConsoleStreams } = require(${JSON.stringify(modulePath)});
protectConsoleStreams();
process.send("ready");
process.once("message", () => {
if (${JSON.stringify(input.invalidStdout)}) require("node:fs").closeSync(1);
console.info("desktop info");
console.warn("desktop warning");
setImmediate(() => { process.send("alive"); process.disconnect(); });
});
`,
],
{
cwd: fileURLToPath(new URL(".", import.meta.url)),
stdio: ["ignore", "pipe", "pipe", "ipc"],
env: Object.fromEntries(Object.entries(process.env).filter(([key]) => key !== "FORCE_COLOR")),
},
);
let stdout = "";
let stderr = "";
let alive = false;
child.stdout.setEncoding("utf8").on("data", (text: string) => {
stdout += text;
});
child.stderr.setEncoding("utf8").on("data", (text: string) => {
stderr += text;
});
child.on("message", (message) => {
if (message === "ready") {
if (input.closed) child[input.closed].destroy();
child.send("write");
}
if (message === "alive") alive = true;
});
const code = await new Promise<number | null>((resolve, reject) => {
child.once("close", resolve);
child.once("error", reject);
});
return { code, stdout, stderr, alive };
}
describe("desktop console streams", () => {
for (const stream of ["stdout", "stderr"] as const) {
it(`keeps running when the launcher closes ${stream}`, async () => {
const result = await writeToConsole({ closed: stream });
expect(result.code, result.stderr).toBe(0);
expect(result.alive).toBe(true);
expect(result[stream === "stdout" ? "stderr" : "stdout"]).toBe(
stream === "stdout" ? "desktop warning\n" : "desktop info\n",
);
});
}
// Windows stdout uses a native handle rather than the POSIX fd closed here.
it.skipIf(process.platform === "win32")(
"does not suppress a console failure other than a closed pipe",
async () => {
const result = await writeToConsole({ invalidStdout: true });
expect(result.code).toBe(1);
expect(result.alive).toBe(false);
expect(result.stderr).toContain("EBADF");
},
);
it("preserves logging while the console has readers", async () => {
expect(await writeToConsole()).toEqual({
code: 0,
stdout: "desktop info\n",
stderr: "desktop warning\n",
alive: true,
});
});
});
@@ -0,0 +1,11 @@
function ignoreClosedConsole(error: NodeJS.ErrnoException): void {
if (error.code !== "EPIPE") {
throw error;
}
}
/** Keep desktop logging independent of the program that launched its console. */
export function protectConsoleStreams(): void {
process.stdout.on("error", ignoreClosedConsole);
process.stderr.on("error", ignoreClosedConsole);
}
+3
View File
@@ -1,3 +1,6 @@
import { protectConsoleStreams } from "./diagnostics/console-streams.js";
protectConsoleStreams();
process.emitWarning = (() => {}) as typeof process.emitWarning;
import log from "electron-log/main";
+1 -1
View File
@@ -89,7 +89,7 @@
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
"test": "npm run test:unit && npm run test:integration",
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
"test:integration": "vitest run --maxWorkers=1 src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts && vitest run --maxWorkers=1 src/server/daemon-e2e/git-operations.e2e.test.ts -t \"merges into\" && vitest run --maxWorkers=1 src/server/session.create-agent-worktree-autoarchive.e2e.test.ts -t \"creates a worktree and auto-archives both\" && vitest run --maxWorkers=1 src/server/agent/providers/opencode-bridge.local.e2e.test.ts -t \"versioned runtime\" && vitest run --maxWorkers=1 src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"oversized attachments\"",
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts && vitest run --maxWorkers=1 src/server/daemon-e2e/git-operations.e2e.test.ts -t \"merges into\" && vitest run --maxWorkers=1 src/server/session.create-agent-worktree-autoarchive.e2e.test.ts -t \"creates a worktree and auto-archives both\" && vitest run --maxWorkers=1 src/server/agent/providers/opencode-bridge.local.e2e.test.ts -t \"versioned runtime\" && vitest run --maxWorkers=1 src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"oversized attachments\"",
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
"test:integration:all": "npm run test:e2e",
"test:integration:real": "vitest run real.e2e.test.ts",
@@ -1,5 +1,6 @@
import { createRequire } from "node:module";
import { existsSync } from "node:fs";
import { delimiter, resolve } from "node:path";
import type { ProcessEnvRecord } from "../server/paseo-env.js";
import { execCommand } from "../utils/spawn.js";
import { windowsExecutableResolution } from "./windows.js";
@@ -120,6 +121,29 @@ export function executableExists(
return exists(executablePath) ? executablePath : null;
}
// PATH lookup that never runs the candidate, unlike findExecutable which probes
// each one with `--version`. A terminal spawn path cannot afford that probe: it
// would execute the profile command once before the terminal even opens.
// `path` overrides the PATH to search, so a caller can resolve against the
// environment its child process will actually get rather than the daemon's own.
export async function findExecutableWithoutProbing(
name: string,
options: { path?: string; cwd: string },
): Promise<string | null> {
if (!name) {
return null;
}
const path =
options.path === undefined
? undefined
: options.path
.split(delimiter)
.map((entry) => resolve(options.cwd, entry))
.join(delimiter);
const candidates = await enumerateCandidatesViaLibrary(name, { PATH: path });
return candidates[0] ?? null;
}
export interface ExecutableResolutionOptions {
probeTimeoutMs?: number;
env?: ProcessEnvRecord;
@@ -31,6 +31,81 @@ afterEach(async () => {
await ctx.cleanup();
}, 60000);
describe("checkout discard", () => {
test.each([".", "apps/web"])(
"discards selected Changes from the %s workspace without changing siblings",
async (workspacePath) => {
const cwd = tmpCwd();
function git(args: string[]): string {
return execFileSync("git", args, { cwd, encoding: "utf8", stdio: "pipe" });
}
try {
git(["init", "-b", "main"]);
git(["config", "user.name", "Paseo Test"]);
git(["config", "user.email", "test@getpaseo.local"]);
git(["config", "core.autocrlf", "false"]);
const nested = path.join(cwd, "apps", "web");
mkdirSync(nested, { recursive: true });
writeFileSync(path.join(nested, "target[ab].txt"), "target base\n");
writeFileSync(path.join(nested, "targeta.txt"), "sibling base\n");
writeFileSync(path.join(nested, "deleted.txt"), "deleted base\n");
git(["add", "."]);
git(["-c", "commit.gpgsign=false", "commit", "-m", "initial"]);
const creation = await ctx.client.createWorkspace({
source: { kind: "directory", path: path.join(cwd, workspacePath) },
title: "Discard regression",
});
const workspaceCwd = creation.workspace?.workspaceDirectory;
if (!workspaceCwd) {
throw new Error(creation.error ?? "Workspace creation failed");
}
writeFileSync(path.join(nested, "target[ab].txt"), "target edited\n");
writeFileSync(path.join(nested, "targeta.txt"), "sibling edited\n");
writeFileSync(path.join(nested, "staged.txt"), "staged new file\n");
writeFileSync(path.join(nested, "scratch.txt"), "untracked file\n");
git(["--literal-pathspecs", "add", "--", "apps/web/target[ab].txt", "apps/web/staged.txt"]);
git(["rm", "apps/web/deleted.txt"]);
const subscription = ctx.client.observeCheckoutDiff(workspaceCwd, { mode: "uncommitted" });
try {
const changes = await subscription.ready;
expect(changes.error).toBeNull();
expect(changes.files.map((file) => file.path).sort()).toEqual([
"apps/web/deleted.txt",
"apps/web/scratch.txt",
"apps/web/staged.txt",
"apps/web/target[ab].txt",
"apps/web/targeta.txt",
]);
const selectedPaths = changes.files
.filter((file) => file.path !== "apps/web/targeta.txt")
.map((file) => file.path);
const discarded = await ctx.client.checkoutDiscardChanges(workspaceCwd, {
paths: selectedPaths,
});
expect(discarded).toMatchObject({ success: true, error: null });
const target = await ctx.client.readFile(cwd, "apps/web/target[ab].txt");
expect(new TextDecoder().decode(target.bytes)).toBe("target base\n");
const restored = await ctx.client.readFile(cwd, "apps/web/deleted.txt");
expect(new TextDecoder().decode(restored.bytes)).toBe("deleted base\n");
const sibling = await ctx.client.readFile(cwd, "apps/web/targeta.txt");
expect(new TextDecoder().decode(sibling.bytes)).toBe("sibling edited\n");
await expect(ctx.client.readFile(cwd, "apps/web/staged.txt")).rejects.toThrow(/ENOENT/);
await expect(ctx.client.readFile(cwd, "apps/web/scratch.txt")).rejects.toThrow(/ENOENT/);
expect(git(["status", "--porcelain=v1", "-z"])).toBe(" M apps/web/targeta.txt\0");
} finally {
await subscription.release();
}
} finally {
// afterEach shuts down the daemon and its repository observers first.
onTestFinished(() => rmSync(cwd, { recursive: true, force: true }));
}
},
);
});
describe("file explorer", () => {
test.each(["..", "..."])(
"workspace suggestions resolve exact paths starting with %s",
@@ -8,9 +8,13 @@ import net from "node:net";
import path from "node:path";
import { spawn, type ChildProcess } from "node:child_process";
import { Buffer } from "node:buffer";
import { createHash, randomBytes } from "node:crypto";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import { generateLocalPairingOffer } from "../pairing-offer.js";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
import { FILE_EXPLORER_STREAM_CHUNK_BYTES } from "../file-explorer/service.js";
import { createClientChannel, type Transport } from "@getpaseo/relay/e2ee";
import {
deriveSharedKey,
@@ -75,6 +79,10 @@ function decodeOfferFromFragmentUrl(url: string): {
return { serverId: offer.serverId, daemonPublicKeyB64: offer.daemonPublicKeyB64 };
}
function sha256(bytes: Uint8Array): string {
return createHash("sha256").update(bytes).digest("hex");
}
function encodeCiphertext(ciphertext: ArrayBuffer): string {
return Buffer.from(new Uint8Array(ciphertext)).toString("base64");
}
@@ -860,4 +868,67 @@ async function waitForCapturedLog(
await stopRelay();
}
}, 90000);
test("reads a workspace file over the E2EE relay session byte-for-byte", async () => {
process.env.PASEO_PRIMARY_LAN_IP = "192.168.1.12";
const { logger, lines } = createCapturingLogger();
let daemon: Awaited<ReturnType<typeof createTestPaseoDaemon>> | null = null;
let workspaceDir: string | null = null;
const fileName = "rapport données.bin";
const source = randomBytes(4 * FILE_EXPLORER_STREAM_CHUNK_BYTES + 123);
let client: DaemonClient | null = null;
try {
await startRelay({ useLocalRelay: true });
daemon = await createTestPaseoDaemon({
listen: "127.0.0.1",
logger,
relayEnabled: true,
relayEndpoint: `127.0.0.1:${relayPort}`,
});
workspaceDir = await mkdtemp(path.join(os.tmpdir(), "paseo-relay-download-"));
await writeFile(path.join(workspaceDir, fileName), source);
const offerUrl = await getPairingOfferUrl({
paseoHome: daemon.paseoHome,
relayEnabled: daemon.config.relayEnabled,
relayEndpoint: daemon.config.relayEndpoint,
relayPublicEndpoint: daemon.config.relayPublicEndpoint,
appBaseUrl: daemon.config.appBaseUrl,
});
const { serverId, daemonPublicKeyB64 } = decodeOfferFromFragmentUrl(offerUrl);
client = new DaemonClient({
url: buildRelayWebSocketUrl({
endpoint: `127.0.0.1:${relayPort}`,
useTls: false,
serverId,
role: "client",
}),
clientType: "cli",
connectTimeoutMs: 30_000,
e2ee: { enabled: true, daemonPublicKeyB64 },
reconnect: { enabled: false },
});
await client.connect();
const result = await client.readFile(workspaceDir, fileName, undefined, undefined, 0);
expect(result.size).toBe(source.byteLength);
expect(result.bytes.byteLength).toBe(source.byteLength);
expect(sha256(result.bytes)).toBe(sha256(source));
} catch (err) {
const tail = lines.slice(-50).join("");
// eslint-disable-next-line no-console
console.error("daemon logs (tail):\n", tail);
throw err;
} finally {
await client?.close().catch(() => undefined);
await daemon?.close();
await stopRelay();
if (workspaceDir) {
await rm(workspaceDir, { recursive: true, force: true });
}
}
}, 90000);
});
@@ -244,3 +244,28 @@ async function observeScriptLifecycles(
await subscription.ready;
return lifecycles;
}
test.runIf(process.platform !== "win32")(
"a missing command fails creation without leaving a terminal listed",
async () => {
const workspaceId = await createWorkspace("Missing command");
await expect(
sdk.terminals.create({
workspaceId,
name: "Missing command",
command: "paseo-test-absent-terminal-command",
}),
).rejects.toThrow("paseo-test-absent-terminal-command: command not found");
expect((await sdk.terminals.list({ workspaceId })).entries).toEqual([]);
const control = await sdk.terminals.create({
workspaceId,
command: process.execPath,
args: ["-e", "process.stdin.resume()"],
});
expect((await sdk.terminals.list({ workspaceId })).entries.map((entry) => entry.id)).toEqual([
control.id,
]);
await control.kill();
expect((await sdk.terminals.list({ workspaceId })).entries).toEqual([]);
},
);
@@ -0,0 +1,62 @@
import { test, expect } from "vitest";
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createTestPaseoDaemon, DaemonClient } from "./test-utils/index.js";
test.skipIf(process.platform === "win32")(
"checkout and commit diffs preserve filenames that Git quotes",
async () => {
const cwd = mkdtempSync(join(tmpdir(), "git-filename-diffs-"));
const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
const names = [
'report "draft".txt',
"back\\slash.txt",
"tab\tname.txt",
"normal.txt",
"with spaces.txt",
];
const editLines = expect.arrayContaining([
expect.objectContaining({ type: "remove", content: "before" }),
expect.objectContaining({ type: "add", content: "after" }),
]);
const daemon = await createTestPaseoDaemon({ agentClients: {} });
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
try {
git("init", "-b", "main");
git("config", "user.name", "Test");
git("config", "user.email", "test@example.com");
git("config", "core.quotepath", "false");
for (const name of names) writeFileSync(join(cwd, name), "before\n");
git("add", ".");
git("-c", "commit.gpgsign=false", "commit", "-m", "initial");
for (const name of names) writeFileSync(join(cwd, name), "after\n");
await client.connect();
const checkout = await client.getCheckoutDiff(cwd, { mode: "uncommitted" });
expect(checkout.error).toBeNull();
expect(checkout.files.map((file) => file.path).sort()).toEqual([...names].sort());
for (const file of checkout.files) {
expect(file).toMatchObject({ status: "ok", additions: 1, deletions: 1 });
expect(file.hunks.flatMap((hunk) => hunk.lines)).toEqual(editLines);
}
git("add", ".");
git("-c", "commit.gpgsign=false", "commit", "-m", "edit");
const sha = git("rev-parse", "HEAD");
for (const name of names) {
const commit = await client.getCommitFileDiff(cwd, sha, name);
expect(commit.file).toMatchObject({ path: name, additions: 1, deletions: 1 });
expect(commit.file?.hunks.flatMap((hunk) => hunk.lines)).toEqual(editLines);
const file = await client.readFile(cwd, name);
expect(file.kind).toBe("text");
expect(new TextDecoder().decode(file.bytes)).toBe("after\n");
}
} finally {
await client.close();
await daemon.close();
rmSync(cwd, { recursive: true, force: true });
}
},
);
@@ -773,8 +773,12 @@ describe("Hub relationship", () => {
const second = await relationship.ownedCreateResult("second-create");
expect(relationship.relationshipFile()?.relationship.daemonId).toBe(daemonId);
expect(first).toMatchObject({ payload: { success: true, executionId: "first-execution" } });
expect(second).toMatchObject({ payload: { success: true, executionId: "second-execution" } });
expect(first).toMatchObject({
payload: { success: true, executionId: "first-execution", error: null },
});
expect(second).toMatchObject({
payload: { success: true, executionId: "second-execution", error: null },
});
expect(await relationship.durableOwnedAgentIds()).toHaveLength(2);
});
@@ -218,6 +218,85 @@ index 1234567..abcdefg 100644
},
);
it("decodes quoted Git patch paths before matching files", () => {
const files = parseDiff(
[
'diff --git "a/report \\"draft\\".txt" "b/report \\"draft\\".txt"',
"index 1234567..abcdefg 100644",
'--- "a/report \\"draft\\".txt"',
'+++ "b/report \\"draft\\".txt"',
"@@ -1 +1 @@",
"-before",
"+after",
"",
].join("\n"),
);
expect(files).toEqual([
{
path: 'report "draft".txt',
isNew: false,
isDeleted: false,
additions: 1,
deletions: 1,
hunks: [
{
oldStart: 1,
oldCount: 1,
newStart: 1,
newCount: 1,
lines: [
{ type: "header", content: "@@ -1 +1 @@" },
{ type: "remove", content: "before" },
{ type: "add", content: "after" },
],
},
],
},
]);
});
it.each([
["tab\\tname.txt", "tab\tname.txt"],
["line\\nname.txt", "line\nname.txt"],
["back\\\\slash.txt", "back\\slash.txt"],
["bell\\aname.txt", "bell\u0007name.txt"],
["vertical\\vname.txt", "vertical\u000bname.txt"],
["\\346\\265\\213\\350\\257\\225.txt", "测试.txt"],
['测试 \\"draft\\".txt', '测试 "draft".txt'],
])("decodes C-quoted path %s without changing its diff lines", (encoded, path) => {
const files = parseDiff(
[
'diff --git "a/' + encoded + '" "b/' + encoded + '"',
"index 1234567..abcdefg 100644",
'--- "a/' + encoded + '"',
'+++ "b/' + encoded + '"',
"@@ -1 +1 @@",
"-before",
"+after",
"",
].join("\n"),
);
expect(files).toHaveLength(1);
expect(files[0]).toMatchObject({ path, additions: 1, deletions: 1 });
expect(files[0].hunks[0].lines).toEqual([
{ type: "header", content: "@@ -1 +1 @@" },
{ type: "remove", content: "before" },
{ type: "add", content: "after" },
]);
});
it.each([
['"a/old \\"draft\\".txt" b/new with spaces.txt', "new with spaces.txt"],
['a/old with spaces.txt "b/new \\"draft\\".txt"', 'new "draft".txt'],
['"report \\"draft\\".txt" "report \\"draft\\".txt"', 'report "draft".txt'],
])("reads quoted paths from header-only patches: %s", (header, path) => {
expect(parseDiff("diff --git " + header + "\nsimilarity index 100%\n")).toEqual([
{ path, isNew: false, isDeleted: false, additions: 0, deletions: 0, hunks: [] },
]);
});
it("parses a simple diff with one hunk", () => {
const files = parseDiff(SIMPLE_DIFF);
@@ -1,6 +1,7 @@
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { highlightCode, isLanguageSupported, type HighlightToken } from "@getpaseo/highlight";
import { unquoteGitPath } from "../../utils/git-quoted-path.js";
const MAX_DIFF_HIGHLIGHT_LINE_CHARS = 10_000;
@@ -53,7 +54,7 @@ function extractPathFromMetadata(lines: string[], prefix: "--- " | "+++ "): stri
return null;
}
const path = line.slice(prefix.length).replace(/\t.*$/, "").trimEnd();
const path = unquoteGitPath(line.slice(prefix.length).replace(/\t.*$/, ""));
return path === "/dev/null" ? null : path;
}
@@ -64,6 +65,17 @@ function extractPathFromDiffHeader(lines: string[]): string {
return prefixedPathMatch[2];
}
const quotedPathMatch =
firstLine.match(/^("(?:\\.|[^"\\])*") (.+)$/) ?? firstLine.match(/^(.+) ("(?:\\.|[^"\\])*")$/);
if (quotedPathMatch) {
const oldPath = unquoteGitPath(quotedPathMatch[1]);
const newPath = unquoteGitPath(quotedPathMatch[2]);
if (usesDiffPathPrefixes(oldPath, newPath)) {
return newPath.slice(2);
}
return newPath;
}
const metadataPath =
extractPathFromMetadata(lines, "+++ ") ?? extractPathFromMetadata(lines, "--- ");
if (metadataPath) {
@@ -33,7 +33,7 @@ describe("ensureWorkspaceServicePortPlan", () => {
expect(allocatedServices).toEqual(["api", "web", "worker"]);
});
it("returns the existing plan without calling the allocator on later calls", async () => {
it("extends the existing plan with newly declared services without reallocating peers", async () => {
let allocationCount = 0;
const firstPlan = await ensureWorkspaceServicePortPlan({
@@ -54,9 +54,11 @@ describe("ensureWorkspaceServicePortPlan", () => {
},
});
expect(Array.from(secondPlan.entries())).toEqual(Array.from(firstPlan.entries()));
expect(secondPlan.has("new-service")).toBe(false);
expect(allocationCount).toBe(2);
expect(Array.from(secondPlan.entries())).toEqual([
...firstPlan.entries(),
["new-service", 4300],
]);
expect(allocationCount).toBe(3);
});
it("shares one first-plan build across concurrent callers", async () => {
@@ -101,6 +103,103 @@ describe("ensureWorkspaceServicePortPlan", () => {
expect(allocationCount).toBe(2);
});
it("extends a pending plan for a concurrent caller with another service", async () => {
const allocation = createDeferredPort();
const workspaceId = "registry-concurrent-extension-workspace";
const firstPlan = ensureWorkspaceServicePortPlan({
workspaceId,
services: [{ scriptName: "backend-dev" }],
allocatePort: async () => allocation.promise,
});
let allocations = 0;
const secondPlan = ensureWorkspaceServicePortPlan({
workspaceId,
services: [{ scriptName: "backend-dev" }, { scriptName: "web" }],
allocatePort: async () => {
allocations += 1;
return 6101;
},
});
allocation.resolve(6100);
expect(Array.from((await firstPlan).entries())).toEqual([["backend-dev", 6100]]);
expect(Array.from((await secondPlan).entries())).toEqual([
["backend-dev", 6100],
["web", 6101],
]);
expect(allocations).toBe(1);
releaseWorkspaceServicePortPlan(workspaceId);
});
it("keeps the previous plan and reservations when an extension fails", async () => {
const workspaceId = "registry-failed-extension-workspace";
await ensureWorkspaceServicePortPlan({
workspaceId,
services: [{ scriptName: "backend-dev" }],
allocatePort: async () => 6200,
});
let allocations = 0;
await expect(
ensureWorkspaceServicePortPlan({
workspaceId,
services: [{ scriptName: "backend-dev" }, { scriptName: "web" }, { scriptName: "worker" }],
allocatePort: async () => {
allocations += 1;
if (allocations === 1) return 6201;
throw new Error("Allocation failed");
},
}),
).rejects.toThrow("Allocation failed");
const priorPlan = await ensureWorkspaceServicePortPlan({
workspaceId,
services: [{ scriptName: "backend-dev" }],
allocatePort: async () => {
throw new Error("Existing port must survive");
},
});
expect(Array.from(priorPlan.entries())).toEqual([["backend-dev", 6200]]);
const otherWorkspace = "registry-failed-extension-other-workspace";
const reusedPlan = await ensureWorkspaceServicePortPlan({
workspaceId: otherWorkspace,
services: [{ scriptName: "web" }],
allocatePort: async ({ reservedPorts }) => {
expect(reservedPorts.has(6200)).toBe(true);
expect(reservedPorts.has(6201)).toBe(false);
return 6201;
},
});
expect(reusedPlan.get("web")).toBe(6201);
releaseWorkspaceServicePortPlan(workspaceId);
releaseWorkspaceServicePortPlan(otherWorkspace);
});
it("rejects a new explicit port that collides with an existing service", async () => {
const workspaceId = "registry-extension-explicit-collision-workspace";
await ensureWorkspaceServicePortPlan({
workspaceId,
services: [{ scriptName: "backend-dev" }],
allocatePort: async () => 6300,
});
await expect(
ensureWorkspaceServicePortPlan({
workspaceId,
services: [{ scriptName: "backend-dev" }, { scriptName: "web", port: 6300 }],
allocatePort: async () => 6301,
}),
).rejects.toThrow("Service 'web' has a duplicate port 6300");
const plan = await ensureWorkspaceServicePortPlan({
workspaceId,
services: [{ scriptName: "backend-dev" }, { scriptName: "web", port: 6301 }],
allocatePort: async () => {
throw new Error("No allocation needed");
},
});
expect(Array.from(plan.entries())).toEqual([
["backend-dev", 6300],
["web", 6301],
]);
releaseWorkspaceServicePortPlan(workspaceId);
});
it("uses explicit configured ports without calling the allocator", async () => {
let allocationCount = 0;
@@ -312,6 +411,123 @@ describe("refreshWorkspaceServicePort", () => {
]);
});
it("preserves a concurrent service addition while refreshing a stopped service", async () => {
const workspaceId = "registry-refresh-and-extend-workspace";
await ensureWorkspaceServicePortPlan({
workspaceId,
services: [{ scriptName: "backend-dev" }],
allocatePort: async () => 6400,
});
const allocation = createDeferredPort();
const refreshing = refreshWorkspaceServicePort({
workspaceId,
service: { scriptName: "backend-dev" },
allocatePort: async () => allocation.promise,
});
const extending = ensureWorkspaceServicePortPlan({
workspaceId,
services: [{ scriptName: "backend-dev" }, { scriptName: "web", port: 6402 }],
allocatePort: async () => {
throw new Error("Explicit addition needs no allocation");
},
});
allocation.resolve(6401);
expect(await refreshing).toBe(6401);
await extending;
const plan = await ensureWorkspaceServicePortPlan({
workspaceId,
services: [],
allocatePort: async () => {
throw new Error("No allocation needed");
},
});
expect(Array.from(plan.entries())).toEqual([
["backend-dev", 6401],
["web", 6402],
]);
releaseWorkspaceServicePortPlan(workspaceId);
});
it.each(["reused port", "allocation failure"])(
"cancels a pending refresh and its waiter after workspace release (%s)",
async (outcome) => {
const workspaceId = "registry-cancelled-refresh-workspace";
await ensureWorkspaceServicePortPlan({
workspaceId,
services: [{ scriptName: "api" }],
allocatePort: async () => 6500,
});
const allocation = createDeferredPort();
const refreshing = refreshWorkspaceServicePort({
workspaceId,
service: { scriptName: "api" },
allocatePort: async () => {
const port = await allocation.promise;
if (outcome === "allocation failure") throw new Error("Allocation failed");
return port;
},
});
const waiting = refreshWorkspaceServicePort({
workspaceId,
service: { scriptName: "web", port: 6501 },
allocatePort: async () => 6501,
});
const assertions = Promise.all([
expect(refreshing).rejects.toThrow("Workspace service port plan was released"),
expect(waiting).rejects.toThrow("Workspace service port plan was released"),
]);
releaseWorkspaceServicePortPlan(workspaceId);
allocation.resolve(6500);
await assertions;
const reusedPlan = await ensureWorkspaceServicePortPlan({
workspaceId: "registry-after-cancelled-refresh-workspace",
services: [{ scriptName: "api" }],
allocatePort: async () => 6500,
});
expect(reusedPlan.get("api")).toBe(6500);
releaseWorkspaceServicePortPlan("registry-after-cancelled-refresh-workspace");
},
);
it("lets a waiting service restart allocate after another service's restart fails", async () => {
const workspaceId = "registry-independent-refresh-failure-workspace";
await ensureWorkspaceServicePortPlan({
workspaceId,
services: [{ scriptName: "api" }, { scriptName: "web" }],
allocatePort: createSequentialPortAllocator(6600),
});
const allocation = createDeferredPort();
const failedRefresh = refreshWorkspaceServicePort({
workspaceId,
service: { scriptName: "api" },
allocatePort: async () => {
await allocation.promise;
throw new Error("API port script failed");
},
});
const failedAssertion = expect(failedRefresh).rejects.toThrow("API port script failed");
const waitingRefresh = refreshWorkspaceServicePort({
workspaceId,
service: { scriptName: "web" },
allocatePort: async () => 6602,
});
allocation.resolve(0);
await failedAssertion;
expect(await waitingRefresh).toBe(6602);
const plan = await ensureWorkspaceServicePortPlan({
workspaceId,
services: [],
allocatePort: async () => {
throw new Error("No allocation needed");
},
});
expect(Array.from(plan.entries())).toEqual([
["api", 6600],
["web", 6602],
]);
releaseWorkspaceServicePortPlan(workspaceId);
});
it("uses an explicit configured port without calling the allocator", async () => {
let allocationCount = 0;
@@ -24,6 +24,24 @@ interface PendingWorkspaceServicePortPlanToken {
isReleased: boolean;
}
class WorkspaceServicePortPlanReleasedError extends Error {
constructor(workspaceId: string) {
super(`Workspace service port plan was released while being created for '${workspaceId}'`);
}
}
async function waitForWorkspaceServicePortPlanUpdate(
pendingPlan: Promise<Map<string, number>>,
): Promise<void> {
try {
await pendingPlan;
} catch (error) {
// Allocation failure belongs to the original request. A waiting request
// retries against the rolled-back plan; workspace archival cancels both.
if (error instanceof WorkspaceServicePortPlanReleasedError) throw error;
}
}
const workspaceServicePortPlans = new Map<string, Map<string, number>>();
const pendingWorkspaceServicePortPlans = new Map<string, Promise<Map<string, number>>>();
const pendingWorkspaceServicePortPlanTokens = new Map<
@@ -37,25 +55,19 @@ const MAX_DYNAMIC_PORT_ALLOCATION_ATTEMPTS = 10;
export async function ensureWorkspaceServicePortPlan(
options: EnsureWorkspaceServicePortPlanOptions,
): Promise<ReadonlyMap<string, number>> {
const existingPlan = workspaceServicePortPlans.get(options.workspaceId);
if (existingPlan) {
const pendingPlan = pendingWorkspaceServicePortPlans.get(options.workspaceId);
if (pendingPlan) {
await waitForWorkspaceServicePortPlanUpdate(pendingPlan);
return ensureWorkspaceServicePortPlan(options);
}
const existingPlan =
workspaceServicePortPlans.get(options.workspaceId) ?? new Map<string, number>();
if (options.services.every((service) => existingPlan.has(service.scriptName))) {
return new Map(existingPlan);
}
let pendingPlan = pendingWorkspaceServicePortPlans.get(options.workspaceId);
if (!pendingPlan) {
const token: PendingWorkspaceServicePortPlanToken = { isReleased: false };
pendingPlan = createPendingWorkspaceServicePortPlan({
workspaceId: options.workspaceId,
services: options.services,
allocatePort: options.allocatePort,
token,
});
pendingWorkspaceServicePortPlans.set(options.workspaceId, pendingPlan);
pendingWorkspaceServicePortPlanTokens.set(options.workspaceId, token);
}
return new Map(await pendingPlan);
return new Map(await startWorkspaceServicePortPlanUpdate({ ...options, existingPlan }));
}
export function requirePlannedWorkspaceServicePort(
@@ -82,27 +94,62 @@ export function releaseWorkspaceServicePortPlan(workspaceId: string): void {
dynamicPortsByWorkspace.delete(workspaceId);
}
async function createPendingWorkspaceServicePortPlan(options: {
workspaceId: string;
services: readonly WorkspaceServicePortDeclaration[];
allocatePort: (request: WorkspaceServicePortAllocationRequest) => Promise<number>;
token: PendingWorkspaceServicePortPlanToken;
}): Promise<Map<string, number>> {
interface WorkspaceServicePortPlanUpdateOptions extends EnsureWorkspaceServicePortPlanOptions {
existingPlan: ReadonlyMap<string, number>;
refreshScriptName?: string;
}
function startWorkspaceServicePortPlanUpdate(
options: WorkspaceServicePortPlanUpdateOptions,
): Promise<Map<string, number>> {
const token: PendingWorkspaceServicePortPlanToken = { isReleased: false };
const plan = createPendingWorkspaceServicePortPlan({ ...options, token });
pendingWorkspaceServicePortPlans.set(options.workspaceId, plan);
pendingWorkspaceServicePortPlanTokens.set(options.workspaceId, token);
return plan;
}
async function createPendingWorkspaceServicePortPlan(
options: WorkspaceServicePortPlanUpdateOptions & { token: PendingWorkspaceServicePortPlanToken },
): Promise<Map<string, number>> {
const previousDynamicPorts = new Map(dynamicPortsByWorkspace.get(options.workspaceId));
const retainedPlan = new Map(options.existingPlan);
if (options.refreshScriptName !== undefined) retainedPlan.delete(options.refreshScriptName);
try {
const plan = await buildWorkspaceServicePortPlan({
const updatedPlan = await buildWorkspaceServicePortPlan({
workspaceId: options.workspaceId,
services: options.services,
allocatePort: options.allocatePort,
existingPlan: retainedPlan,
});
const plan = new Map(options.existingPlan);
for (const [scriptName, port] of updatedPlan) plan.set(scriptName, port);
if (options.token.isReleased) {
throw new Error(
`Workspace service port plan was released while being created for '${options.workspaceId}'`,
);
throw new WorkspaceServicePortPlanReleasedError(options.workspaceId);
}
for (const [scriptName, port] of previousDynamicPorts) {
if (plan.get(scriptName) !== port) {
releaseDynamicPort({ workspaceId: options.workspaceId, scriptName, port });
}
}
workspaceServicePortPlans.set(options.workspaceId, plan);
return plan;
} catch (error) {
releaseWorkspaceServicePortPlan(options.workspaceId);
const dynamicPorts = dynamicPortsByWorkspace.get(options.workspaceId);
if (dynamicPorts) {
for (const [scriptName, port] of dynamicPorts) {
if (options.token.isReleased || previousDynamicPorts.get(scriptName) !== port) {
releaseDynamicPort({ workspaceId: options.workspaceId, scriptName, port });
}
}
}
if (!options.token.isReleased) {
for (const [scriptName, port] of previousDynamicPorts) {
reserveDynamicPort({ workspaceId: options.workspaceId, scriptName, port });
}
}
if (options.token.isReleased)
throw new WorkspaceServicePortPlanReleasedError(options.workspaceId);
throw error;
} finally {
pendingWorkspaceServicePortPlans.delete(options.workspaceId);
@@ -111,12 +158,16 @@ async function createPendingWorkspaceServicePortPlan(options: {
}
async function buildWorkspaceServicePortPlan(options: {
existingPlan: ReadonlyMap<string, number>;
workspaceId: string;
services: readonly WorkspaceServicePortDeclaration[];
allocatePort: (request: WorkspaceServicePortAllocationRequest) => Promise<number>;
}): Promise<Map<string, number>> {
const explicitPortOwners = new Map<number, string>();
const explicitPortOwners = new Map<number, string>(
Array.from(options.existingPlan, ([scriptName, port]) => [port, scriptName]),
);
for (const service of options.services) {
if (options.existingPlan.has(service.scriptName)) continue;
if (service.port === undefined) continue;
if (explicitPortOwners.has(service.port)) {
throw new Error(`Service '${service.scriptName}' has a duplicate port ${service.port}`);
@@ -124,8 +175,9 @@ async function buildWorkspaceServicePortPlan(options: {
explicitPortOwners.set(service.port, service.scriptName);
}
const plan = new Map<string, number>();
const plan = new Map(options.existingPlan);
for (const service of options.services) {
if (plan.has(service.scriptName)) continue;
if (service.port !== undefined) {
plan.set(service.scriptName, service.port);
continue;
@@ -148,32 +200,20 @@ async function buildWorkspaceServicePortPlan(options: {
export async function refreshWorkspaceServicePort(
options: RefreshWorkspaceServicePortOptions,
): Promise<number> {
const plan = workspaceServicePortPlans.get(options.workspaceId) ?? new Map<string, number>();
const pendingPlan = pendingWorkspaceServicePortPlans.get(options.workspaceId);
if (pendingPlan) {
await waitForWorkspaceServicePortPlanUpdate(pendingPlan);
return refreshWorkspaceServicePort(options);
}
const reservedPorts = new Set(plan.values());
const previousPort = plan.get(options.service.scriptName);
if (previousPort !== undefined) {
reservedPorts.delete(previousPort);
}
const oldDynamicPort = dynamicPortsByWorkspace
.get(options.workspaceId)
?.get(options.service.scriptName);
const port = await resolveServicePort({
service: options.service,
const plan = await startWorkspaceServicePortPlanUpdate({
workspaceId: options.workspaceId,
services: [options.service],
allocatePort: options.allocatePort,
reservedPorts,
existingPlan: workspaceServicePortPlans.get(options.workspaceId) ?? new Map<string, number>(),
refreshScriptName: options.service.scriptName,
});
if (oldDynamicPort !== undefined && oldDynamicPort !== port) {
releaseDynamicPort({
workspaceId: options.workspaceId,
scriptName: options.service.scriptName,
port: oldDynamicPort,
});
}
plan.set(options.service.scriptName, port);
workspaceServicePortPlans.set(options.workspaceId, plan);
return port;
return requirePlannedWorkspaceServicePort(plan, options.service.scriptName);
}
async function resolveServicePort(options: {
@@ -837,6 +837,54 @@ describe("runAsyncWorktreeBootstrap", () => {
});
});
it("starts a service added to paseo.json without restarting the daemon", async () => {
const backend = {
type: "service" as const,
command: "uv run uvicorn app.main:app --reload --port $PASEO_PORT",
};
commitPaseoScripts({ "backend-dev": backend });
const serviceProxy = new ScriptRouteStore();
const runtimeStore = new WorkspaceScriptRuntimeStore();
const createTerminalCalls: CreateTerminalCall[] = [];
const terminalRecords: StubTerminalRecord[] = [];
const options = {
repoRoot: repoDir,
workspaceId: repoDir,
projectSlug: "repo",
branchName: "feature-added-service",
daemonPort: 6767,
serviceProxy,
runtimeStore,
terminalManager: createStubTerminalManager(createTerminalCalls, terminalRecords),
};
const backendResult = await spawnWorkspaceScript({ ...options, scriptName: "backend-dev" });
writeFileSync(
join(repoDir, "paseo.json"),
JSON.stringify({
scripts: {
"backend-dev": backend,
web: { type: "service", command: "pnpm run dev -- --port $PASEO_PORT" },
},
}),
);
const webResult = await spawnWorkspaceScript({ ...options, scriptName: "web" });
expect(webResult.port).toEqual(expect.any(Number));
expect(webResult.port).not.toBe(backendResult.port);
expect(terminalRecords[1]?.sentInputs).toEqual(["pnpm run dev -- --port $PASEO_PORT\r"]);
expect(createTerminalCalls[1]?.env?.PASEO_PORT).toBe(String(webResult.port));
expect(createTerminalCalls[1]?.env?.PASEO_SERVICE_BACKEND_DEV_PORT).toBe(
String(backendResult.port),
);
expect(serviceProxy.listRoutes()).toHaveLength(2);
expect(runtimeStore.get({ workspaceId: repoDir, scriptName: "backend-dev" })).toMatchObject({
lifecycle: "running",
terminalId: backendResult.terminalId,
});
});
it("spawns services with public aliases and public service URLs", async () => {
commitPaseoScripts(
{
+187 -1
View File
@@ -2,6 +2,7 @@ import { describe, it, expect, afterEach, vi } from "vitest";
import { isPlatform } from "../test-utils/platform.js";
import {
buildTerminalEnvironment,
assertTerminalCommandCanStart,
createTerminal,
ensureNodePtySpawnHelperExecutableForCurrentPlatform,
resolveDefaultTerminalShell,
@@ -26,7 +27,7 @@ import { spawnSync } from "node:child_process";
import * as pty from "node-pty";
import xterm from "@xterm/headless";
import { renderTerminalSnapshotToAnsi } from "@getpaseo/protocol/terminal-snapshot";
import { join } from "node:path";
import { delimiter, join } from "node:path";
import { tmpdir } from "node:os";
import { setImmediate as waitForImmediate, setTimeout as delay } from "node:timers/promises";
import { stripVTControlCharacters } from "node:util";
@@ -637,6 +638,151 @@ describe("createTerminal", () => {
expect(exitInfo.lastOutputLines.length).toBeGreaterThan(0);
expect(exitInfo.lastOutputLines[exitInfo.lastOutputLines.length - 1]).toBe("line-2999");
});
it.runIf(isPlatform("linux", "darwin"))(
"rejects a profile command that is not installed instead of opening a terminal",
async () => {
await expect(
createTerminal({
workspaceId: "ws-test",
cwd: realpathSync(tmpdir()),
name: "Codex",
command: "paseo-qa-absent-codex",
args: [],
}),
).rejects.toThrow("paseo-qa-absent-codex: command not found");
},
);
it.runIf(isPlatform("linux", "darwin"))(
"opens a command found only on the PATH carried by the env option",
async () => {
// execve resolves the command against the child's PATH, which carries the
// per-cwd registered environment. A version-manager shim lives there and
// not necessarily on the daemon's own PATH.
const binDir = mkdtempSync(join(tmpdir(), "terminal-envpath-bin-"));
temporaryDirs.push(binDir);
const toolPath = join(binDir, "paseo-qa-envpath-tool");
writeFileSync(toolPath, "#!/usr/bin/env bash\nprintf 'paseo-launch-ok\\n'\nsleep 30\n");
chmodSync(toolPath, 0o755);
const session = trackSession(
await createTerminal({
workspaceId: "ws-test",
cwd: realpathSync(tmpdir()),
name: "Shim",
command: "paseo-qa-envpath-tool",
args: [],
env: { PATH: `${binDir}${delimiter}${process.env.PATH ?? ""}` },
}),
);
await waitForLines(session, ["paseo-launch-ok"]);
expect(getLines(session.getState())[0]).toBe("paseo-launch-ok");
},
);
it.runIf(isPlatform("linux", "darwin"))(
"reports command not found when the command is on neither PATH",
async () => {
await expect(
createTerminal({
workspaceId: "ws-test",
cwd: realpathSync(tmpdir()),
name: "Codex",
command: "paseo-qa-absent-codex",
args: [],
env: { PATH: `/paseo-qa-empty${delimiter}${process.env.PATH ?? ""}` },
}),
).rejects.toThrow("paseo-qa-absent-codex: command not found");
},
);
it.runIf(isPlatform("linux", "darwin"))(
"opens a relative command path resolved against the terminal cwd",
async () => {
// execve resolves a path-ish command against the child's cwd, never the
// daemon's own working directory.
const projectDir = mkdtempSync(join(tmpdir(), "terminal-relative-cmd-"));
temporaryDirs.push(projectDir);
mkdirSync(join(projectDir, "scripts"));
const scriptPath = join(projectDir, "scripts", "dev.sh");
writeFileSync(scriptPath, "#!/usr/bin/env bash\nprintf 'paseo-launch-ok\\n'\nsleep 30\n");
chmodSync(scriptPath, 0o755);
const session = trackSession(
await createTerminal({
workspaceId: "ws-test",
cwd: realpathSync(projectDir),
name: "Dev script",
command: "./scripts/dev.sh",
args: [],
}),
);
await waitForLines(session, ["paseo-launch-ok"]);
expect(getLines(session.getState())[0]).toBe("paseo-launch-ok");
},
);
it.runIf(isPlatform("linux", "darwin"))("opens an absolute command path", async () => {
const projectDir = mkdtempSync(join(tmpdir(), "terminal-absolute-cmd-"));
temporaryDirs.push(projectDir);
const scriptPath = join(projectDir, "run.sh");
writeFileSync(scriptPath, "#!/usr/bin/env bash\nprintf 'paseo-launch-ok\\n'\nsleep 30\n");
chmodSync(scriptPath, 0o755);
const session = trackSession(
await createTerminal({
workspaceId: "ws-test",
cwd: realpathSync(tmpdir()),
name: "Absolute",
command: scriptPath,
args: [],
}),
);
await waitForLines(session, ["paseo-launch-ok"]);
expect(getLines(session.getState())[0]).toBe("paseo-launch-ok");
});
it("leaves the command check to the terminal itself on Windows", async () => {
// Windows resolves inside resolveTerminalSpawnCommand, which has its own
// shim handling and its own fallback for an unresolved command.
await expect(
assertTerminalCommandCanStart({
command: "paseo-qa-absent-codex",
cwd: realpathSync(tmpdir()),
env: { PATH: "/paseo-qa-empty" },
platform: "win32",
}),
).resolves.toBeUndefined();
});
it.runIf(isPlatform("linux", "darwin"))(
"still opens a terminal for an installed command that exits non-zero",
async () => {
// A profile running a failing test suite must keep opening a tab with its
// output. Only a command that cannot start at all is reported as an error,
// and "exited non-zero" does not distinguish the two: a missing binary and
// `false` both surface as exit code 1 from node-pty.
const session = trackSession(
await createTerminal({
workspaceId: "ws-test",
cwd: realpathSync(tmpdir()),
name: "Failing suite",
command: "false",
args: [],
}),
);
const exitInfo = await new Promise<{ exitCode: number | null }>((resolve) => {
session.onExit((info) => resolve({ exitCode: info.exitCode }));
});
expect(exitInfo).toEqual({ exitCode: 1 });
},
);
});
describe.skipIf(isPlatform("win32"))("send input", () => {
@@ -1388,3 +1534,43 @@ describe.runIf(isPlatform("win32"))(".cmd shim argv round-trip on Windows", () =
expect(await roundTrip("first\nsecond")).toEqual(["first second"]);
});
});
it.runIf(isPlatform("linux", "darwin"))(
"opens a profile command from a PATH entry relative to the terminal cwd",
async () => {
const projectDir = mkdtempSync(join(tmpdir(), "terminal-relative-path-"));
mkdirSync(join(projectDir, "bin"));
const script = join(projectDir, "bin", "paseo-relative-path-tool");
writeFileSync(script, "#!/bin/sh\nprintf 'paseo-launch-ok\\n'\nexec /bin/sleep 30\n");
chmodSync(script, 0o755);
let session: TerminalSession | undefined;
try {
session = await createTerminal({
workspaceId: "ws-test",
cwd: realpathSync(projectDir),
command: "paseo-relative-path-tool",
env: { PATH: "bin" },
});
await waitForLines(session, ["paseo-launch-ok"]);
expect(getLines(session.getState())[0]).toBe("paseo-launch-ok");
expect(session.cwd).toBe(realpathSync(projectDir));
expect(session.getExitInfo()).toBeNull();
} finally {
await session?.killAndWait({ gracefulTimeoutMs: 1000, forceTimeoutMs: 500 });
rmSync(projectDir, { recursive: true, force: true });
}
},
);
it.runIf(isPlatform("linux", "darwin"))(
"checks the exact command rather than accepting a trimmed executable name",
async () => {
await expect(
createTerminal({
workspaceId: "ws-test",
cwd: realpathSync(tmpdir()),
command: " node ",
}),
).rejects.toThrow(" node : command not found");
},
);
+95 -10
View File
@@ -1,14 +1,25 @@
import * as pty from "node-pty";
import xterm, { type Terminal as TerminalType } from "@xterm/headless";
import { randomUUID } from "crypto";
import { chmodSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
import {
accessSync,
chmodSync,
constants,
existsSync,
mkdirSync,
readFileSync,
statSync,
} from "node:fs";
import { tmpdir, userInfo } from "node:os";
import { basename, delimiter, dirname, extname, join, resolve as resolvePath } from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { createExternalProcessEnv } from "../server/paseo-env.js";
import { writePrivateFileAtomicSync } from "../server/private-files.js";
import { findExecutable } from "../executable-resolution/executable-resolution.js";
import {
findExecutable,
findExecutableWithoutProbing,
} from "../executable-resolution/executable-resolution.js";
import type { TerminalCell, TerminalState } from "@getpaseo/protocol/messages";
import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode";
import { TerminalActivityTracker } from "./activity/terminal-activity-tracker.js";
@@ -33,6 +44,20 @@ export interface TerminalExitInfo {
lastOutputLines: string[];
}
// The field is assigned explicitly rather than declared as a constructor
// parameter property: the terminal worker loads this module under
// --experimental-strip-types, which erases types but cannot emit the
// assignment a parameter property implies.
export class TerminalCommandNotFoundError extends Error {
readonly command: string;
constructor(command: string) {
super(`${command}: command not found`);
this.name = "TerminalCommandNotFoundError";
this.command = command;
}
}
export interface TerminalCommandFinishedInfo {
exitCode: number | null;
}
@@ -886,6 +911,62 @@ function extractLastOutputLinesFromText(text: string, limit: number): string[] {
return lines.slice(-limit);
}
function isExecutableFile(path: string): boolean {
try {
if (!statSync(path).isFile()) {
return false;
}
accessSync(path, constants.X_OK);
return true;
} catch {
return false;
}
}
export interface AssertTerminalCommandCanStartInput {
command: string | undefined;
// The terminal's own cwd and environment, not the daemon's: execve in the
// child resolves against those, so anything else produces false negatives.
cwd: string;
env: Record<string, string>;
platform?: NodeJS.Platform;
}
// node-pty spawns directly through execve on POSIX, with no shell, so a command
// that does not exist fails inside the spawn helper and surfaces as exit code 1
// with no output -- indistinguishable from `false` or any program that simply
// failed. Resolving it up front is the only signal that separates "cannot start"
// from "ran and exited non-zero", and it lets the create report the failure
// instead of handing back a terminal that dies immediately. Windows keeps
// resolving inside resolveTerminalSpawnCommand, which has its own shim handling
// and its own fallback for an unresolved command.
export async function assertTerminalCommandCanStart(
input: AssertTerminalCommandCanStartInput,
): Promise<void> {
const { command, cwd, env } = input;
const platform = input.platform ?? process.platform;
if (command === undefined || platform === "win32") {
return;
}
// A path-ish command is resolved by execve against the child's cwd, never
// through PATH and never against the daemon's working directory.
if (command.includes("/")) {
if (isExecutableFile(resolvePath(cwd, command))) {
return;
}
throw new TerminalCommandNotFoundError(command);
}
const resolved = await findExecutableWithoutProbing(command, {
path: env[getPathEnvKey(env)],
cwd,
});
if (!resolved) {
throw new TerminalCommandNotFoundError(command);
}
}
export async function createTerminal(options: CreateTerminalOptions): Promise<TerminalSession> {
const {
cwd,
@@ -945,19 +1026,23 @@ export async function createTerminal(options: CreateTerminalOptions): Promise<Te
const { command: spawnCommand, args: spawnArgs } = command
? await resolveTerminalSpawnCommand(command, args)
: { command: resolvedShell, args: [] as string[] };
const terminalEnv = buildTerminalEnvironment({
shell: spawnCommand,
env: {
...env,
...activityEnv,
PASEO_WORKSPACE_ID: workspaceId,
},
});
await assertTerminalCommandCanStart({ command, cwd, env: terminalEnv });
const ptyProcess = pty.spawn(spawnCommand, spawnArgs, {
name: "xterm-256color",
cols,
rows,
cwd,
env: buildTerminalEnvironment({
shell: spawnCommand,
env: {
...env,
...activityEnv,
PASEO_WORKSPACE_ID: workspaceId,
},
}),
env: terminalEnv,
});
function emitTitleChange(nextTitle: string | undefined): void {
@@ -968,3 +968,139 @@ it("removes a killed worker terminal from terminalExit without duplicate snapsho
},
]);
});
it("does not resurrect a terminal that exited before its create response was handled", async () => {
const worker = new FakeTerminalWorker();
manager = createWorkerTerminalManager({
requestTimeoutMs: 50,
forkWorker: () => worker,
});
const snapshots: Array<{ cwd: string; terminalIds: string[] }> = [];
manager.subscribeTerminalsChanged((event) => {
snapshots.push({ cwd: event.cwd, terminalIds: event.terminals.map((terminal) => terminal.id) });
});
const created = manager.createTerminal({
id: "terminal-a",
cwd: "/workspace",
workspaceId: "ws-test",
});
const request = worker.sentMessages.find((message) => message.type === "createTerminal");
if (!request) {
throw new Error("createTerminal request not sent");
}
// The worker delivers all three messages in one tick, so the awaiting
// createTerminal continuation resumes only after the exit was processed.
const terminal = {
id: "terminal-a",
name: "Shell",
cwd: "/workspace",
workspaceId: "ws-test",
activity: null,
};
const state = createTerminalState();
const exitInfo = { exitCode: 0, signal: null, lastOutputLines: [] };
worker.emitWorkerMessage({ type: "terminalCreated", terminal, state });
worker.emitWorkerMessage({
type: "response",
requestId: request.requestId,
ok: true,
result: { terminal, state },
});
worker.emitWorkerMessage({ type: "terminalExit", terminalId: "terminal-a", info: exitInfo });
const session = await created;
expect(manager.getTerminal("terminal-a")).toBeUndefined();
expect(await manager.getTerminals("/workspace")).toEqual([]);
expect(session.getExitInfo()).toEqual(exitInfo);
expect(snapshots).toEqual([
{ cwd: "/workspace", terminalIds: ["terminal-a"] },
{ cwd: "/workspace", terminalIds: [] },
]);
});
it("replays the exit to a listener attached after a create that lost the race", async () => {
const worker = new FakeTerminalWorker();
manager = createWorkerTerminalManager({
requestTimeoutMs: 50,
forkWorker: () => worker,
});
const created = manager.createTerminal({
id: "terminal-a",
cwd: "/workspace",
workspaceId: "ws-test",
});
const request = worker.sentMessages.find((message) => message.type === "createTerminal");
if (!request) {
throw new Error("createTerminal request not sent");
}
const terminal = {
id: "terminal-a",
name: "Shell",
cwd: "/workspace",
workspaceId: "ws-test",
activity: null,
};
const state = createTerminalState();
const exitInfo = { exitCode: 0, signal: null, lastOutputLines: [] };
worker.emitWorkerMessage({ type: "terminalCreated", terminal, state });
worker.emitWorkerMessage({
type: "response",
requestId: request.requestId,
ok: true,
result: { terminal, state },
});
worker.emitWorkerMessage({ type: "terminalExit", terminalId: "terminal-a", info: exitInfo });
const session = await created;
// The session controller subscribes only after createTerminal resolves; that
// subscription is what turns into a terminal_exit for the client.
const observedExits: Array<{ exitCode: number | null }> = [];
session.onExit((info) => {
observedExits.push({ exitCode: info.exitCode });
});
await new Promise((resolve) => setImmediate(resolve));
expect(observedExits).toEqual([{ exitCode: 0 }]);
});
it("rejects createTerminal and registers nothing when the worker cannot start the command", async () => {
const worker = new FakeTerminalWorker();
manager = createWorkerTerminalManager({
requestTimeoutMs: 50,
forkWorker: () => worker,
});
const snapshots: Array<{ cwd: string; terminalIds: string[] }> = [];
manager.subscribeTerminalsChanged((event) => {
snapshots.push({ cwd: event.cwd, terminalIds: event.terminals.map((terminal) => terminal.id) });
});
const created = manager.createTerminal({
id: "terminal-a",
cwd: "/workspace",
workspaceId: "ws-test",
command: "paseo-qa-absent-codex",
});
const request = worker.sentMessages.find((message) => message.type === "createTerminal");
if (!request) {
throw new Error("createTerminal request not sent");
}
worker.emitWorkerMessage({
type: "response",
requestId: request.requestId,
ok: false,
error: "paseo-qa-absent-codex: command not found",
});
await expect(created).rejects.toThrow("paseo-qa-absent-codex: command not found");
expect(manager.getTerminal("terminal-a")).toBeUndefined();
expect(await manager.getTerminals("/workspace")).toEqual([]);
expect(snapshots).toEqual([]);
});
@@ -156,6 +156,9 @@ export function createWorkerTerminalManager(
const recordsById = new Map<string, WorkerTerminalRecord>();
const terminalIdsByCwd = new Map<string, Set<string>>();
const terminalActivityTokenById = new Map<string, string>();
// Creation owns a reference to the session independently of the live-terminal
// index. Only terminalCreated registers it; terminalExit removes it permanently.
const pendingCreationsById = new Map<string, { session: TerminalSession | null }>();
const terminalsChangedListeners = new Set<TerminalsChangedListener>();
const terminalActivityListeners = new Set<TerminalActivityListener>();
const terminalWorkspaceContributionChangedListeners =
@@ -542,10 +545,14 @@ export function createWorkerTerminalManager(
function handleWorkerEvent(message: TerminalWorkerToParentMessage): void {
switch (message.type) {
case "terminalCreated": {
registerRecord({
const session = registerRecord({
info: asRequiredWorkerTerminalInfo(message.terminal),
state: message.state,
});
const pendingCreation = pendingCreationsById.get(message.terminal.id);
if (pendingCreation) {
pendingCreation.session = session;
}
emitTerminalsChanged({
cwd: message.terminal.cwd,
terminals: listTerminalItemsForCwd(message.terminal.cwd),
@@ -686,12 +693,10 @@ export function createWorkerTerminalManager(
const activityToken = createActivityToken();
const terminalActivityUrl = managerOptions.getTerminalActivityUrl?.() ?? null;
terminalActivityTokenById.set(terminalId, activityToken);
let result: {
terminal: RequiredWorkerTerminalInfo;
state: TerminalState;
};
const creation = { session: null as TerminalSession | null };
pendingCreationsById.set(terminalId, creation);
try {
result = (await sendRequest({
await sendRequest({
type: "createTerminal",
options: {
...options,
@@ -699,16 +704,17 @@ export function createWorkerTerminalManager(
activityToken,
activityUrl: terminalActivityUrl,
},
})) as {
terminal: RequiredWorkerTerminalInfo;
state: TerminalState;
};
});
if (!creation.session) {
throw new Error("Terminal worker completed creation without a terminalCreated event");
}
return creation.session;
} catch (error) {
terminalActivityTokenById.delete(terminalId);
throw error;
} finally {
pendingCreationsById.delete(terminalId);
}
const session = registerRecord({ info: result.terminal, state: result.state });
return session;
},
registerCwdEnv(options: { cwd: string; env: Record<string, string> }): void {
@@ -3,15 +3,218 @@ import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { getCheckoutDiff, getCommitFileDiff } from "./checkout-git.js";
import {
getCheckoutDiff,
getCheckoutShortstat,
getCommitFileDiff,
listCheckoutCommits,
} from "./checkout-git.js";
const repos: string[] = [];
const EDITED_TEXT_DIFF = {
isNew: false,
isDeleted: false,
additions: 1,
deletions: 1,
hunks: [
{
oldStart: 1,
oldCount: 1,
newStart: 1,
newCount: 1,
lines: [
{ type: "header", content: "@@ -1 +1 @@" },
{ type: "remove", content: "before" },
{ type: "add", content: "after" },
],
},
],
};
afterEach(() => {
vi.unstubAllEnvs();
for (const repo of repos.splice(0)) rmSync(repo, { recursive: true, force: true });
});
it.skipIf(process.platform === "win32")(
"returns a quoted filename and its uncommitted diff using its actual path",
async () => {
const cwd = createChangedRepo("core.quotepath=false");
const name = 'report "draft".txt';
writeFileSync(join(cwd, "file.txt"), "before\n");
writeFileSync(join(cwd, name), "before\n");
git(cwd, "add", "--", name);
git(cwd, "-c", "commit.gpgsign=false", "commit", "-m", "add quoted filename");
writeFileSync(join(cwd, name), "after\n");
const result = await getCheckoutDiff(cwd, { mode: "uncommitted", includeStructured: true });
expect(result.structured).toHaveLength(1);
expect(result.structured?.[0]).toMatchObject({
path: name,
status: "ok",
...EDITED_TEXT_DIFF,
});
},
);
describe.skipIf(process.platform === "win32")("quoted paths from real Git", () => {
const names = [
"normal.txt",
"with spaces.txt",
'report "draft".txt',
"back\\slash.txt",
"tab\tname.txt",
"line\nname.txt",
" leading and trailing .txt ",
'report "old => draft".txt',
];
function createQuotedPathsRepo(): string {
const cwd = createChangedRepo("core.quotepath=false");
writeFileSync(join(cwd, "file.txt"), "before\n");
for (const name of names) writeFileSync(join(cwd, name), "before\n");
git(cwd, "add", "--", ...names);
git(cwd, "-c", "commit.gpgsign=false", "commit", "-m", "add filenames");
git(cwd, "checkout", "-b", "feature");
for (const name of names) writeFileSync(join(cwd, name), "after\n");
return cwd;
}
it("preserves tracked and untracked paths, diff lines and summary counts", async () => {
const cwd = createQuotedPathsRepo();
const untrackedNames = names.map((name) => "untracked-" + name);
for (const name of untrackedNames) writeFileSync(join(cwd, name), "new file\n");
const result = await getCheckoutDiff(cwd, { mode: "uncommitted", includeStructured: true });
expect(result.structured?.map((file) => file.path).sort()).toEqual(
[...names, ...untrackedNames].sort(),
);
for (const name of names) {
expect(result.structured?.find((file) => file.path === name)).toMatchObject({
path: name,
status: "ok",
...EDITED_TEXT_DIFF,
});
}
for (const name of untrackedNames) {
expect(result.structured?.find((file) => file.path === name)).toMatchObject({
path: name,
status: "ok",
isNew: true,
isDeleted: false,
additions: 1,
deletions: 0,
hunks: [
{
oldStart: 0,
oldCount: 0,
newStart: 1,
newCount: 1,
lines: [
{ type: "header", content: "@@ -0,0 +1 @@" },
{ type: "add", content: "new file" },
],
},
],
});
}
expect(await getCheckoutShortstat(cwd)).toEqual({
additions: names.length + untrackedNames.length,
deletions: names.length,
});
});
it("opens base and commit diffs using the actual paths from the commit list", async () => {
const cwd = createQuotedPathsRepo();
git(cwd, "add", "--", ...names);
git(cwd, "-c", "commit.gpgsign=false", "commit", "-m", "edit filenames");
const sha = git(cwd, "rev-parse", "HEAD").trim();
const base = await getCheckoutDiff(cwd, {
mode: "base",
baseRef: "main",
includeStructured: true,
});
expect(base.structured?.map((file) => file.path).sort()).toEqual([...names].sort());
for (const name of names) {
expect(base.structured?.find((file) => file.path === name)).toMatchObject({
path: name,
status: "ok",
...EDITED_TEXT_DIFF,
});
}
const history = await listCheckoutCommits({ cwd });
const commit = history.commits[0];
expect(commit.sha).toBe(sha);
expect(commit.files).toEqual(
[...names].sort().map((name) => ({
path: name,
additions: 1,
deletions: 1,
status: "modified",
})),
);
for (const file of commit.files) {
expect(await getCommitFileDiff({ cwd, sha, path: file.path })).toMatchObject({
path: file.path,
...EDITED_TEXT_DIFF,
});
}
});
it("preserves quoted rename destinations and binary paths in diff and commit lists", async () => {
const cwd = createChangedRepo("core.quotepath=false");
const oldPath = 'old "draft".txt';
const newPath = 'new "draft".txt';
const binaryPath = "image\tdata.bin";
writeFileSync(join(cwd, "file.txt"), "before\n");
writeFileSync(join(cwd, oldPath), "unchanged\n");
writeFileSync(join(cwd, binaryPath), Buffer.from([0, 1, 2]));
git(cwd, "add", "--", oldPath, binaryPath);
git(cwd, "-c", "commit.gpgsign=false", "commit", "-m", "add rename and binary files");
git(cwd, "checkout", "-b", "feature");
git(cwd, "mv", "--", oldPath, newPath);
writeFileSync(join(cwd, binaryPath), Buffer.from([0, 3, 4]));
const result = await getCheckoutDiff(cwd, { mode: "uncommitted", includeStructured: true });
expect(
result.structured?.map(({ path, oldPath: sourcePath, status }) => ({
path,
oldPath: sourcePath,
status,
})),
).toEqual([
{ path: binaryPath, oldPath: undefined, status: "binary" },
{
path: newPath,
oldPath,
status: "ok",
},
]);
expect(result.structured?.[0]).toEqual({
path: binaryPath,
isNew: false,
isDeleted: false,
additions: 0,
deletions: 0,
hunks: [],
status: "binary",
});
git(cwd, "add", "--", binaryPath);
git(cwd, "-c", "commit.gpgsign=false", "commit", "-m", "rename file and edit binary");
const history = await listCheckoutCommits({ cwd });
expect(history.commits[0].files).toEqual([
{ path: binaryPath, additions: 0, deletions: 0, status: "modified" },
{ path: newPath, additions: 0, deletions: 0, status: "renamed" },
]);
});
});
it.each(["diff.mnemonicPrefix=true", "color.diff=always", "diff.noprefix=true"])(
"preserves batched paths, spaces and literal prefix directories with %s",
async (config) => {
@@ -1628,7 +1628,7 @@ const x = 1;
expect(diff.diff).toContain(`-export const value = "old";`);
expect(diff.diff).toContain(`+export const value = "new";`);
expect(commands).toContain(
"diff --no-ext-diff --no-color --src-prefix=a/ --dst-prefix=b/ --numstat HEAD",
"diff --no-ext-diff --no-color --src-prefix=a/ --dst-prefix=b/ -z --numstat HEAD",
);
expect(commands).toContain(
"diff --no-ext-diff --no-color --src-prefix=a/ --dst-prefix=b/ HEAD -- :(literal)generated.js :(literal)small.ts",
+36 -41
View File
@@ -32,6 +32,7 @@ import {
import { parseGitRevParsePath, resolveGitRevParsePath } from "./git-rev-parse-path.js";
import { runGitCommand, type RunGitCommand } from "./run-git-command.js";
import { readGitFileContents } from "./git-file-contents.js";
import { unquoteGitPath } from "./git-quoted-path.js";
import { isPaseoOwnedWorktreeCwd, resolvePaseoWorktreesBaseRoot } from "./worktree.js";
import {
branchNameFromRef,
@@ -515,22 +516,18 @@ async function listCheckoutFileChanges(
const { stdout: nameStatusOut } = await runGitCommand(
buildGitDiffArgs({
ignoreWhitespace,
extra: ["--name-status", ...getCheckoutDiffRefArgs(refs)],
extra: ["-z", "--name-status", ...getCheckoutDiffRefArgs(refs)],
}),
{ cwd, envOverlay: READ_ONLY_GIT_ENV },
);
for (const line of nameStatusOut
.split("\n")
.map((l) => l.trim())
.filter(Boolean)) {
// `--name-status` uses TAB separators, which preserves filenames with spaces.
const tabParts = line.split("\t");
const rawStatus = (tabParts[0] ?? "").trim();
const nameStatusFields = nameStatusOut.split("\0");
for (let index = 0; index < nameStatusFields.length; ) {
const rawStatus = nameStatusFields[index++];
if (!rawStatus) continue;
if (rawStatus.startsWith("R") || rawStatus.startsWith("C")) {
const oldPath = tabParts[1];
const newPath = tabParts[2];
const oldPath = nameStatusFields[index++];
const newPath = nameStatusFields[index++];
if (newPath) {
changes.push({
path: newPath,
@@ -543,7 +540,7 @@ async function listCheckoutFileChanges(
continue;
}
const path = tabParts[1];
const path = nameStatusFields[index++];
if (!path) continue;
const code = rawStatus[0];
changes.push({
@@ -556,16 +553,13 @@ async function listCheckoutFileChanges(
if (refs.includeUntracked) {
const { stdout: untrackedOut } = await runGitCommand(
["ls-files", "--others", "--exclude-standard"],
["ls-files", "-z", "--others", "--exclude-standard"],
{
cwd,
envOverlay: READ_ONLY_GIT_ENV,
},
);
for (const file of untrackedOut
.split("\n")
.map((l) => l.trim())
.filter(Boolean)) {
for (const file of untrackedOut.split("\0").filter(Boolean)) {
changes.push({
path: file,
status: "U",
@@ -623,18 +617,22 @@ async function tryResolveMergeBase(cwd: string, baseRef: string): Promise<string
type FileStat = { additions: number; deletions: number; isBinary: boolean } | null;
function normalizeNumstatPath(pathField: string): string {
if (/^"(?:\\.|[^"\\])*"$/.test(pathField)) {
return unquoteGitPath(pathField);
}
const braceRenameMatch = pathField.match(/^(.*)\{(.*) => (.*)\}(.*)$/);
if (braceRenameMatch) {
const [, prefix, , renamed, suffix] = braceRenameMatch;
return `${prefix}${renamed}${suffix}`;
return unquoteGitPath(`${prefix}${renamed}${suffix}`);
}
const inlineRenameMatch = pathField.match(/^(.*) => (.*)$/);
if (inlineRenameMatch) {
return inlineRenameMatch[2] ?? pathField;
return unquoteGitPath(inlineRenameMatch[2] ?? pathField);
}
return pathField;
return unquoteGitPath(pathField);
}
// Parsed patches need a stable wire format regardless of terminal presentation settings.
@@ -669,7 +667,7 @@ async function getTrackedNumstatByPath(
const result = await runGitCommand(
buildGitDiffArgs({
ignoreWhitespace,
extra: ["--numstat", ...getCheckoutDiffRefArgs(refs)],
extra: ["-z", "--numstat", ...getCheckoutDiffRefArgs(refs)],
}),
{
cwd,
@@ -680,21 +678,21 @@ async function getTrackedNumstatByPath(
);
const stats = new Map<string, FileStat>();
const lines = result.stdout
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
for (const line of lines) {
const parts = line.split("\t");
const records = result.stdout.split("\0");
for (let index = 0; index < records.length; index += 1) {
const parts = records[index].split("\t");
if (parts.length < 3) {
continue;
}
const additionsField = parts[0] ?? "";
const deletionsField = parts[1] ?? "";
const rawPath = parts.slice(2).join("\t");
const path = normalizeNumstatPath(rawPath);
let path = parts.slice(2).join("\t");
if (!path) {
// A rename has an empty path here, followed by separate old/new NUL fields.
path = records[index + 2];
index += 2;
}
if (!path) {
continue;
@@ -2424,7 +2422,7 @@ function parseRawStatusLine(line: string, statuses: Map<string, CheckoutCommitFi
if (!path) {
return;
}
statuses.set(path, status);
statuses.set(unquoteGitPath(path), status);
}
// A `--numstat` line: `<adds>\t<dels>\t<path>` (renames use `old => new`, binary
@@ -2738,16 +2736,13 @@ async function countUntrackedAdditions(
): Promise<number> {
try {
const { stdout } = await getRunGitCommand(context)(
["ls-files", "--others", "--exclude-standard"],
["ls-files", "-z", "--others", "--exclude-standard"],
{
cwd,
envOverlay: READ_ONLY_GIT_ENV,
},
);
const files = stdout
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
const files = stdout.split("\0").filter(Boolean);
let additions = 0;
for (const file of files.slice(0, UNTRACKED_SHORTSTAT_MAX_FILES)) {
@@ -3558,13 +3553,13 @@ export async function commitAll(cwd: string, message: string): Promise<void> {
}
export async function discardChanges(cwd: string, pathspecs: string[]): Promise<void> {
await requireGitRepo(cwd);
const worktreeRoot = await requireGitWorktreeRoot(cwd);
if (pathspecs.length === 0) {
return;
}
try {
await runGitCommand(["--literal-pathspecs", "reset", "-q", "HEAD", "--", ...pathspecs], {
cwd,
cwd: worktreeRoot,
timeout: DISCARD_CHANGES_TIMEOUT_MS,
});
} catch {
@@ -3572,7 +3567,7 @@ export async function discardChanges(cwd: string, pathspecs: string[]): Promise<
await runGitCommand(
["--literal-pathspecs", "rm", "--cached", "-r", "-q", "--ignore-unmatch", "--", ...pathspecs],
{
cwd,
cwd: worktreeRoot,
timeout: DISCARD_CHANGES_TIMEOUT_MS,
},
);
@@ -3584,7 +3579,7 @@ export async function discardChanges(cwd: string, pathspecs: string[]): Promise<
const status = await runGitCommand(
["--literal-pathspecs", "status", "--porcelain=v1", "-z", "--", ...pathspecs],
{
cwd,
cwd: worktreeRoot,
timeout: DISCARD_CHANGES_TIMEOUT_MS,
},
);
@@ -3610,13 +3605,13 @@ export async function discardChanges(cwd: string, pathspecs: string[]): Promise<
}
if (tracked.length > 0) {
await runGitCommand(["--literal-pathspecs", "checkout", "-q", "--", ...tracked], {
cwd,
cwd: worktreeRoot,
timeout: DISCARD_CHANGES_TIMEOUT_MS,
});
}
if (untracked.length > 0) {
await runGitCommand(["--literal-pathspecs", "clean", "-fd", "-q", "--", ...untracked], {
cwd,
cwd: worktreeRoot,
timeout: DISCARD_CHANGES_TIMEOUT_MS,
});
}
@@ -0,0 +1,34 @@
const GIT_PATH_ESCAPE_BYTES: Record<string, number> = {
a: 7,
b: 8,
t: 9,
n: 10,
v: 11,
f: 12,
r: 13,
'"': 34,
"\\": 92,
};
// core.quotepath=false still quotes control characters, double quotes and backslashes.
export function unquoteGitPath(value: string): string {
if (!value.startsWith('"') || !value.endsWith('"')) return value;
const encoded = value.slice(1, -1);
const parts: Buffer[] = [];
let offset = 0;
for (const match of encoded.matchAll(/\\([0-7]{1,3}|[abfnrtv"\\])/g)) {
parts.push(Buffer.from(encoded.slice(offset, match.index)));
const escape = match[1];
let byte: number;
if (/^[0-7]/.test(escape)) {
byte = Number.parseInt(escape, 8);
} else {
byte = GIT_PATH_ESCAPE_BYTES[escape];
}
parts.push(Buffer.from([byte]));
offset = match.index + match[0].length;
}
parts.push(Buffer.from(encoded.slice(offset)));
return Buffer.concat(parts).toString("utf8");
}