Compare commits

..
Author SHA1 Message Date
paseo-bot[bot]andMohamed Boudra ad20814ec8 Restore stopped Claude background subagents as canceled after reopening (#9013)
* fix(claude): restore stopped background subagents as canceled

Resolve task-only replay notifications through the parent launch identity so stopped children keep their recorded outcome after reopening. Preserve transcript order across task and tool notifications.

* test(claude): name replay notification fixture options

* fix(claude): restore all children in grouped task notifications

A session-end notification can contain several task IDs. Apply its outcome to each linked child during transcript replay so every stopped child restores as canceled.

* fix(claude): keep quoted notices from changing replayed child status

Claude marks delivered task notifications with an origin. Require that origin for user records and require a standalone notice for queue records so prompts that quote a notice do not override a recorded outcome.

* fix(claude): keep replay task links tied to subagent results

Ignore unrelated tool results when collecting task identities so echoed launch logs cannot overwrite the link used to restore a stopped child.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-25 08:30:08 +07:00
Maarten den BraberandMohamed Boudra 0688ae83fe fix(server): send Claude MCP servers over stdin to keep tokens out of argv (#10698)
* Keep MCP server headers off the Claude Code command line

The Claude Agent SDK defaults to sending MCP servers in one --mcp-config
flag, so the Paseo MCP server's bearer token (and any user MCP server
headers or env) was readable by every local account through ps or
/proc/<pid>/cmdline. Anyone who read it could call the daemon's agent MCP
endpoint.

Set mcpServersDelivery: "initialize" so the SDK sends the servers over
stdin in the initialize request. The SDK only supports that with the
Claude Code bundled with it (2.1.326) or newer, so an older Claude Code,
or a wrapper command that reports no version, keeps the command-line
delivery and the daemon logs a warning once.

A spawn test feeds Paseo's options to the real SDK and checks that the
token reaches stdin and not the launch arguments.

* fix(server): warn about MCP argv delivery only with configured servers

An empty session used the client's one-time warning before any MCP server headers would be passed to the provider. Warn on the first session that configures a server.

* fix(server): detect MCP delivery support on each provider launch

A running daemon kept selecting command-line delivery after the installed provider gained stdin support. Resolve the installed version when building SDK options for a launch with MCP servers.

* fix(server): probe MCP delivery support in the launch environment

Version-selecting wrappers can run a different binary in the workspace. Use the session working directory and environment when probing the configured command.

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-25 08:30:01 +07:00
paseo-bot[bot] 311728a780 test(plugins): give npm installation cases separate deadlines (#10726)
Install and reload, reviewed updates, and staging cleanup each run against a fresh service. Their npm subprocesses no longer draw from one test's deadline.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-25 00:23:46 +00:00
cf1a5a9e73 Stop idle plugin sessions from pinging the daemon (#9363)
* fix(server): stop liveness pings on plugin sessions

Every DaemonClient pings its daemon every 10 s to notice a silently dead socket. A plugin's
session runs over its IPC channel (or an in-process queue for built-in plugins), whose loss is
reported directly, and the daemon already exempts plugin sockets from the application lease those
pings renew. The pings only woke both processes: about 2 wakeups a second in an idle daemon with
nine plugins and the built-ins.

DaemonClient gets a livenessHeartbeat option (default on); the plugin host turns it off.
Explicit verification (ensureConnected({ verify: true })) still pings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(server): exit a plugin process when its daemon's channel closes

A plugin host only noticed that its daemon worker had died through the liveness ping: about 11 s
later the ping failed and the process exited with code 1. With the pings off it would not notice
at all and kept running as an orphan.

The plugin process now exits as soon as the IPC channel closes without the plugin closing it
itself. A normal shutdown still closes the channel from the plugin side and lets work in flight
(a provider connection that resolves late) finish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Brandon Elliott <923787+Brandon168@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-24 15:51:30 +00:00
Mohamed BoudraandTaras Kornichuk e06bfbb94c Redesign host picker with configurable auto-detected icons, connection type, and latency (#10702)
Supersedes #5787.

- Add best-effort daemon hardware detection (macOS ioreg/sysctl, Linux containers, WSL, device-tree boards, cloud/VM DMI, SMBIOS chassis) exposed as optional `machineKind` on `server_info` and `/api/status`.
- Add configurable per-host icons in Host Settings -> Appearance (`Auto` plus 9 icons across all 9 locales), keeping `icon` omitted while untouched for rollback compatibility and preserving unknown future icons on disk.
- Redesign `HostPicker` and `HostChooserModal` with resolved host icons, connection type (`Local`, `Tailscale`, `Relay`, `SSH`, `Direct`, `Via`) + endpoint, on-demand round-trip latency, aligned leading and content rails, and full keyboard navigation.
- Update the website host mockup to match.

Co-authored-by: Taras Kornichuk <dread9ko@gmail.com>
2026-11-24 21:52:39 +07:00
paseo-bot[bot] 7bcd598f09 test(terminal): speed up history setup for pressure recovery (#10683)
Windows timed out while the fixture printed 12,050 rows before signaling readiness. Batch the initial writes and keep the live burst and replay assertions.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-24 12:01:34 +00:00
Mohamed Boudra c626bf3707 Skip worktree teardown commands for unapproved cross-repository checkouts (#10694)
* fix(server): skip teardown commands when archiving unapproved checkouts

`archiveByScope` previously treated `assertWorkspaceAutomationAllowed` as optional and did not skip `runWorktreeTeardownCommands` when `untrustedBacking` was already true or when archiving an unrecorded worktree directory. Four callers (`CreateAgentLifecycleDispatch`, `archiveIfSafe`, `paseo-tools` `archive_workspace`, and `handlePaseoWorktreeArchiveRequest`) also omitted `assertWorkspaceAutomationAllowed`, letting `paseo.json` teardown commands run during failed agent creation cleanup, first-turn auto-archive, auto-archive on merge, MCP workspace archive, and worktree archive RPCs.

Make `assertWorkspaceAutomationAllowed` and `isCheckoutUntrusted` required on `ArchiveDependencies`, skip teardown whenever the backing checkout is untrusted, any workspace on the checkout is blocked, or no active workspace record exists, and wire the guard through all archive callers.

* fix(server): scope archive teardown check to active checkout workspaces

`isCheckoutUntrusted` scans all workspace records by path, including previously archived records, so gating teardown on it suppressed `paseo.json` teardown for a fresh approved worktree that reused a previously archived unapproved slug path.

Keep teardown approval scoped to the active workspaces sharing the backing checkout at archive start (the records being archived plus active siblings), drop the null-workspace fallback target for unrecorded worktree-scope archives so they never run teardown or flip `untrustedBacking`, and verify caller wiring reaches `assertWorkspaceAutomationAllowed` directly.

* fix(server): inherit untrustedSource when unarchiving onto an active unapproved checkout

Unarchiving a previously approved workspace onto an existing directory that currently holds an active unapproved checkout left the restored workspace without `untrustedSource`. If the unapproved sibling was archived first, the directory remained on disk and archiving the restored workspace could run teardown commands.

Inherit `untrustedSource` from active workspaces sharing the checkout root in `ensureWorkspaceRecordUnarchived`, while ignoring already-archived historical records so restoring an approved checkout onto a reused path stays approved.

* fix(server): bind automation approval state to checkout worktree metadata

Keeping `untrustedSource` only on workspace records meant a retained unapproved worktree directory could lose its teardown block if its last unapproved workspace was archived and an older approved workspace was unarchived onto that path, while scanning archived records by path blocked fresh worktrees that reused a deleted slug.

Persist `untrustedSource` on the checkout itself in `paseo/worktree.json` when creating or restoring an unapproved worktree, clear it in `clearWorkspaceAutomationBlock` when setup is approved, and read it in both `workspace-archive-service` and `workspace-provisioning-service`. Deleting the worktree removes its metadata automatically, so fresh worktrees reusing the path start clean while retained checkouts keep their block across workspace archives and restores.

* fix(server): backfill worktree metadata when archiving retained unapproved checkouts

Unapproved checkouts created before `paseo/worktree.json` stored `untrustedSource` carry their block only in the workspace record. If archive keeps the directory on disk (such as a retained sibling or nested worktree), backfilling `untrustedSource` into `paseo/worktree.json` before removal ensures the retained checkout keeps its block even after its unapproved workspace record is archived.

* fix(server): never propagate archived untrustedSource onto fresh checkouts

Both archive metadata backfill and directory workspace creation previously consulted already-archived records matching a path, allowing an old archived unapproved record to copy `untrustedSource` onto a fresh approved worktree that reused the same slug path.

Ignore `untrustedSource` on already-archived records during archive target resolution and metadata backfill (only backfill when active workspaces are being archived), and share one `resolveCheckoutUntrustedSource` rule across `createWorkspaceForDirectory` and `ensureWorkspaceRecordUnarchived` that checks `paseo/worktree.json` first and falls back only to active workspaces.

* fix(server): align unarchived workspace approval state with the live checkout

Unarchiving an old unapproved workspace onto a path already owned by an active approved checkout kept the old record's stale `untrustedSource`, causing a later re-archive of that workspace to backfill the block onto the fresh checkout's metadata.

Align `ensureWorkspaceRecordUnarchived` symmetrically with the live checkout: adopt `untrustedSource` from `paseo/worktree.json` or active workspaces on the checkout when present, and drop stale `untrustedSource` when live active workspaces own an approved checkout at that path.

* fix(server): preserve block when opening a pre-upgrade retained checkout

Opening a pre-upgrade retained checkout directory whose last unapproved workspace was already archived before this change has no active workspace on the path and no `untrustedSource` in `paseo/worktree.json`.

In `resolveCheckoutUntrustedSource`, prefer `paseo/worktree.json`, then active workspaces on the checkout when any exist (so a fresh approved worktree at a reused path stays approved), and only when zero active workspaces exist on the directory fall back to the most recently archived record for that path.

* fix(server): share one checkout approval lookup across open and unarchive

* fix(server): resolve checkout approval state only from metadata and active workspaces

* fix(server): keep archive read-only on worktree approval metadata

* fix(server): serialize setup approval with archive checkout lock and backfill retained metadata

* fix(server): fail setup approval before clearing records when worktree metadata write fails
2026-11-24 17:46:23 +07:00
Mohamed Boudra 8b2e14f3d2 Run resolved forge CLI executables directly (#10685)
* fix(server): run resolved forge CLI executables directly

The GitHub, GitLab, and Gitea adapters resolved gh, glab, and tea with findExecutable, then discarded the resolved path and spawned the bare command name. On Windows, spawning an extensionless bare name routes through cmd.exe, which resolves commands against cwd first, expands %VAR% references, and truncates multiline arguments such as gh api graphql queries.

Forward the resolved executablePath from each forge adapter and auth probe into the shared runner, resolve bare binary names inside createForgeCliRunner when omitted, and restrict bare-name PATH discovery in findExecutable to absolute PATH directories.

* fix(server): re-resolve cached forge CLI paths if the binary disappears

Cached CLI path resolvers now support targeted invalidation, and forge adapters plus createForgeCliRunner invalidate and retry once when a previously resolved executable disappears at launch time (ENOENT, or a missing Windows batch launcher). This preserves cached lookups on normal runs while recovering automatically when a user uninstalls or relocates an installation while another copy remains on PATH.

* fix(server): refresh cached forge CLI path on any unlaunchable spawn error

Match executable-resolution's unlaunchable spawn error set (ENOENT, EACCES, ENOEXEC, UNKNOWN) when deciding whether to invalidate and re-resolve a cached forge CLI path, so losing execute permission falls back to another working copy on PATH.
2026-11-24 14:37:28 +07:00
Mohamed Boudra da74f7de1f Offer Push and Pull for a branch whose remote is not named origin (#10679)
* fix(git): offer Push and Pull for a branch whose remote is not origin

A checkout whose only remote has another name, with main tracking that
remote's main, got no Push, Pull or Pull and push. The app gated all three
on hasRemote, which is true only when origin is configured, and the
daemon's pull refused to run without origin.

Neither action needs origin. The daemon now reports where each one goes for
the current branch (pullRemote, pushRemote) and the app offers the actions
from those. One resolver picks the push destination for both the status and
the push, so the offer and the push cannot disagree.

Without origin, Push follows the upstream only when the upstream branch has
the branch's own name and git pushes the branch to that remote. A branch
such as feature tracking upstream/main can be pulled and is not pushed.
With origin, every push goes where it went before.

firstPushRemote stays on the wire for apps that predate pushRemote.

* fix(git): follow Git's own push destination when origin is missing

Without origin, Push compared the upstream's remote with the remote Git
pushes the branch to. That missed a push refspec: with
remote.<upstream>.push set, plain `git push` updates another branch, and
Paseo still updated the upstream. A regular checkout with a push refspec on
branch.<name>.pushRemote was pushed there and stayed ahead of its upstream.

Push now asks Git where `git push` sends the branch (%(push)) and follows
the upstream only when that is the upstream. This also covers
push.default. A Paseo worktree keeps the push refspec Paseo configures for
a PR checkout.

Pull no longer requires a configured upstream before it runs. Git decides,
so a branch with no upstream in a single-branch clone pulls again.

* fix(git): compare the push remote by name when origin is missing

Push compared Git's push destination with the upstream as remote-tracking
refs. Two remotes whose fetch refspecs map onto the same tracking namespace
give the same ref for different repositories, so a branch Git pushes to one
remote was sent to the other. The remote Git pushes to is now compared by
name as well.

* fix(git): leave a matching-mode push to the user when origin is missing

Under push.default=matching, git push sends a branch only when the remote still has it. The checkout's remote-tracking ref can outlive a branch deleted on the remote, so the daemon cannot tell from local metadata that the push would go to the upstream, and its explicit push would recreate the branch. Without origin, Push is now refused in that mode.
2026-11-24 14:37:23 +07:00
Mohamed Boudra 767c1efa03 Show OpenCode Go usage from the login store the installed OpenCode uses (#10678)
* fix(usage): read OpenCode Go logins from the store the installed OpenCode uses

The source treated a `credential` table in opencode.db as proof of OpenCode 2
and then ignored auth.json. OpenCode 1.17.5 and newer creates that table too
and leaves it empty, and OpenCode 2 fills it once when it opens the same data
directory. In both cases the Go key in auth.json was dropped and the source
disappeared.

The source no longer reads OpenCode's database. It asks the installed OpenCode
for its version. OpenCode 2 lists its own logins with
`opencode auth export --standalone`, with its own choice of the active one per
integration. OpenCode 1 keeps logins in auth.json. A failed OpenCode 2 listing
throws, so it never reads as "no login". An auth.json key is not used when
OpenCode 2 is installed, because OpenCode 2 never reads that file after its
one-time import.

`--standalone` matters: without it the command starts OpenCode's background
service and leaves it running.

* chore(usage): request a review of the resolved threads

* fix(usage): keep the OpenCode Go card when the version check is cut off

A version check that reached its timeout was read as OpenCode 1. Discovery then
read auth.json, and a login that only OpenCode 2 has was reported as removed.
A check that is cut off does not show which store OpenCode uses, so discovery
now fails and the daemon keeps the account it already knew.

A missing OpenCode, or one that exits with an error, still reads auth.json:
that file is the only store when OpenCode is not installed.

* fix(usage): recognize OpenCode 2 when the daemon's environment forces colors

With FORCE_COLOR set, OpenCode 2 writes its version with ANSI codes even into
a pipe. The version did not parse, the source took OpenCode for version 1, and
a login that only OpenCode 2 has disappeared. The source now runs OpenCode with
NO_COLOR, which gives plain output for the version and the login listing.

* fix(usage): read the auth.json Go key when OpenCode 2 has no Go login

OpenCode 2 imports auth.json only once. A Go key that is saved in the file
after that import is in no other place, so the card was still missing for
the state in #10659 when the installed OpenCode is 2.x: the credential
listing holds only an unrelated login and the Go key is in auth.json.

The order is now: a login OpenCode 2 can serve Go with wins, so a stale key
in the file never replaces it. Without one, the auth.json key is used. A
failed listing still throws, because it does not show that OpenCode 2 has
no Go login.

* fix(usage): read the auth.json Go key behind an OpenCode 2 login without Go

The auth.json fallback applied only when OpenCode 2 listed neither an
`opencode` nor an `opencode-go` login. With an `opencode` login whose
Console workspace has no Go, the card reported "No active OpenCode Go
subscription" while a working Go key was in auth.json.

The file's key now stands in for a missing `opencode-go` login. The
existing order then decides: the `opencode` login is asked first, and the
Go key is asked only when the Console refuses that login. A temporary
failure still keeps the card on the `opencode` login.
2026-11-24 14:37:18 +07:00
109 changed files with 6997 additions and 1589 deletions
-2
View File
@@ -422,7 +422,6 @@
"packages/app/src/components/headers/back-header.tsx",
"packages/app/src/components/headers/screen-header.tsx",
"packages/app/src/components/host-status-dot.tsx",
"packages/app/src/components/hosts/host-picker.tsx",
"packages/app/src/components/icons/paseo-logo.tsx",
"packages/app/src/components/left-sidebar.tsx",
"packages/app/src/components/plan-card.tsx",
@@ -554,7 +553,6 @@
"packages/app/src/components/headers/back-header.tsx",
"packages/app/src/components/highlighted-code-block.tsx",
"packages/app/src/components/hosts/host-filter.tsx",
"packages/app/src/components/hosts/host-picker.tsx",
"packages/app/src/components/import-session-sheet.tsx",
"packages/app/src/components/left-sidebar.tsx",
"packages/app/src/components/markdown/fence/mermaid/host.native.tsx",
@@ -1,4 +1,5 @@
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { type Locator, type Page } from "@playwright/test";
@@ -498,6 +499,56 @@ test("Changes offers Push for a branch that was never pushed and the push sets i
});
});
test("Changes pushes and pulls a branch whose only remote is not named origin", async ({
page,
}) => {
const workspace = await createWorkspaceWithRemote((repoPath) => {
execFileSync("git", ["remote", "rename", "origin", "doras-mono"], { cwd: repoPath });
// git pull stops on a branch that is both ahead and behind until it is told how to combine them.
execFileSync("git", ["config", "pull.rebase", "false"], { cwd: repoPath });
});
await openWorkspaceChangesSurface(page, workspace);
const primary = page.getByTestId("changes-primary-cta");
await test.step("a branch that is ahead offers Push and the push updates the remote", async () => {
await expect(primary).toHaveAccessibleName("Commit", { timeout: 30_000 });
commitAllWithGit(workspace.repoPath, "Local work");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1]");
await expect(primary).toHaveAccessibleName("Push", { timeout: 30_000 });
await primary.click();
await expectInSyncWithRemote(workspace);
expect(remoteBranchSubjects(workspace, "main")).toContain("Local work");
await expectNoGitActionLeft(page);
});
await test.step("a branch that is behind offers Pull and the pull brings the commits in", async () => {
pushTeammateCommits(workspace, ["Teammate one", "Teammate two"]);
fetchRemote(workspace, "doras-mono");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [behind 2]");
await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 });
await primary.click();
await expectInSyncWithRemote(workspace);
expect(localBranchSubjects(workspace)).toEqual(
expect.arrayContaining(["Local work", "Teammate one", "Teammate two"]),
);
await expectNoGitActionLeft(page);
});
await test.step("a branch that is ahead and behind pulls and then pushes", async () => {
await writeFile(path.join(workspace.repoPath, "tracked.ts"), "export const tracked = 3;\n");
commitAllWithGit(workspace.repoPath, "More local work");
pushTeammateCommits(workspace, ["Teammate three", "Teammate four"]);
fetchRemote(workspace, "doras-mono");
expect(trackingStatus(workspace)).toBe("## main...doras-mono/main [ahead 1, behind 2]");
await expect(primary).toHaveAccessibleName("Pull", { timeout: 30_000 });
await page.getByTestId("changes-primary-cta-caret").click();
await page.getByTestId("changes-menu-pull-and-push").click();
await expectInSyncWithRemote(workspace);
expect(remoteBranchSubjects(workspace, "main")).toEqual(
expect.arrayContaining(["More local work", "Teammate three", "Teammate four"]),
);
await expectNoGitActionLeft(page);
});
});
test("Changes selects exact local and remote bases and retains the selection after reload", async ({
page,
}, testInfo) => {
@@ -2202,6 +2253,79 @@ function remoteBranchHead(workspace: RemoteWorkspace, branch: string): string |
return line ? (line.split("\t")[0] ?? null) : null;
}
// The branch line of `git status -sb`, such as "## main...origin/main [ahead 1, behind 2]".
function trackingStatus(workspace: RemoteWorkspace): string {
const status = execFileSync("git", ["status", "-sb"], {
cwd: workspace.repoPath,
encoding: "utf8",
});
return status.split("\n")[0] ?? "";
}
// Neither ahead nor behind, which a push reaches only after the remote accepted it.
async function expectInSyncWithRemote(workspace: RemoteWorkspace): Promise<void> {
await expect
.poll(() => trackingStatus(workspace), { timeout: 30_000 })
.toMatch(/^## [^ ]+\.\.\.[^ ]+$/);
}
// A clean main that is in sync with its remote has no git action, so the button is gone.
async function expectNoGitActionLeft(page: Page): Promise<void> {
await expect(page.getByTestId("changes-primary-cta")).toBeHidden({ timeout: 30_000 });
}
function localBranchSubjects(workspace: RemoteWorkspace): string[] {
return commitSubjects(workspace.repoPath, "HEAD");
}
function remoteBranchSubjects(workspace: RemoteWorkspace, branch: string): string[] {
return commitSubjects(workspace.remotePath, branch);
}
function commitSubjects(repoPath: string, revision: string): string[] {
const log = execFileSync("git", ["log", "--format=%s", revision], {
cwd: repoPath,
encoding: "utf8",
});
return log.trim().split("\n");
}
// Paseo fetches only origin in the background, so the checkout learns about another remote's
// commits when the user fetches it.
function fetchRemote(workspace: RemoteWorkspace, remoteName: string): void {
execFileSync("git", ["fetch", "--quiet", remoteName], { cwd: workspace.repoPath });
}
// Lands commits on the remote's main from a second clone, as a teammate's push does.
function pushTeammateCommits(workspace: RemoteWorkspace, subjects: string[]): void {
const clonePath = mkdtempSync(path.join(path.dirname(workspace.repoPath), "changes-teammate-"));
try {
execFileSync("git", ["clone", "--quiet", workspace.remotePath, clonePath]);
for (const subject of subjects) {
execFileSync(
"git",
[
"-c",
"user.name=Teammate",
"-c",
"user.email=teammate@paseo.test",
"-c",
"commit.gpgsign=false",
"commit",
"--quiet",
"--allow-empty",
"-m",
subject,
],
{ cwd: clonePath },
);
}
execFileSync("git", ["push", "--quiet", "origin", "HEAD:main"], { cwd: clonePath });
} finally {
rmSync(clonePath, { recursive: true, force: true });
}
}
// Empty until the branch has an upstream.
function branchUpstream(workspace: RemoteWorkspace, branch: string): string {
return execFileSync(
@@ -4,6 +4,7 @@ import {
addConnectedHostAndReload,
chooseHostBadgeDisplay,
chooseHostColor,
chooseHostIcon,
expectHostAppearancePreview,
expectHostBadgeIconOnly,
expectHostBadgeName,
@@ -115,12 +116,21 @@ test("customizes a host badge and preserves its appearance after reload", async
expect(widths.content).toBeLessThanOrEqual(widths.client);
});
await test.step("preview a color and apply it to the sidebar badge", async () => {
await test.step("preview a color and icon and apply them to the sidebar badge and host popover", async () => {
await openHostAppearanceSettings(page, badge.serverId);
await chooseHostColor(page, "Teal");
await chooseHostIcon(page, "Laptop");
await expectHostAppearancePreview(page, { serverId: badge.serverId, hostName, color: "teal" });
await leaveHostAppearanceSettings(page);
await expectHostBadgeTinted(page, { ...badge, hostName, color: "teal" });
await page.getByTestId("sidebar-hosts-trigger").click();
const hostRow = page.getByTestId(`sidebar-host-row-${badge.serverId}`);
await expect(hostRow).toBeVisible();
await expect(hostRow).toContainText("Direct");
await expect(hostRow).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/);
await expect(hostRow).not.toContainText(/agents?/i);
await page.keyboard.press("Escape");
});
await test.step("keep the icon-only preference through reload", async () => {
@@ -145,3 +155,30 @@ test("customizes a host badge and preserves its appearance after reload", async
});
});
});
base(
"activates Add host from the sidebar host picker via focus+Enter and Arrow+Enter",
async ({ page }) => {
await gotoAppShell(page);
const trigger = page.getByTestId("sidebar-hosts-trigger");
await expect(trigger).toBeVisible();
// Focus + Enter on Add host must open the Add connection dialog rather than selecting the active host.
const addConnectionDialog = page.getByRole("dialog").filter({ hasText: "Add connection" });
await trigger.click();
const addHostButton = page.getByRole("button", { name: "Add host", exact: true });
await expect(addHostButton).toBeVisible();
await addHostButton.focus();
await page.keyboard.press("Enter");
await expect(addConnectionDialog).toBeVisible();
await page.keyboard.press("Escape");
await expect(addConnectionDialog).toBeHidden();
// ArrowDown + Enter must also reach Add host from the host list.
await trigger.click();
await expect(addHostButton).toBeVisible();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await expect(addConnectionDialog).toBeVisible();
},
);
@@ -65,8 +65,7 @@ import {
openSettingsHostSection,
removeCurrentHostFromSettings,
openSidebarHostPicker,
sidebarHostSettingsButton,
expectStandaloneSidebarHostSettingsButton,
sidebarHostRowButton,
activateSidebarHostSettingsWithKeyboard,
bindCommandCenterToEnter,
} from "../support/helpers/settings";
@@ -192,17 +191,16 @@ test.describe("Settings sidebar scroll position", () => {
});
test.describe("Settings sidebar navigation", () => {
test("the sidebar host gear opens Overview in one click", async ({ page, withWorkspace }) => {
test("the sidebar host row opens Overview in one click", async ({ page, withWorkspace }) => {
const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" });
await openWorkspace(page, workspace);
await openSidebarHostPicker(page);
await expectStandaloneSidebarHostSettingsButton(page);
await sidebarHostSettingsButton(page).click();
await sidebarHostRowButton(page).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
});
test("Enter opens the focused sidebar host gear", async ({ page, withWorkspace }) => {
test("Enter opens the active sidebar host row", async ({ page, withWorkspace }) => {
await bindCommandCenterToEnter(page);
const workspace = await withWorkspace({ prefix: "keyboard-host-settings-" });
await openWorkspace(page, workspace);
@@ -566,7 +564,7 @@ test.describe("Settings — compact master-detail", () => {
await openWorkspace(page, workspace);
await page.getByRole("button", { name: "Open menu", exact: true }).click();
await page.getByTestId("sidebar-hosts-trigger").click();
await page.getByRole("button", { name: /Open .* settings/ }).click();
await sidebarHostRowButton(page).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
await expect(page.getByText("Overview", { exact: true })).toBeVisible();
+10 -1
View File
@@ -132,7 +132,10 @@ export async function waitForConnectedHost(
): Promise<void> {
await page.getByTestId("sidebar-hosts-trigger").click();
const host = page.getByTestId(`sidebar-host-row-${input.serverId}`);
await expect(host).toContainText(input.endpoint, { timeout: 30_000 });
const escapedEndpoint = input.endpoint.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// Local daemons render "Local" without repeating localhost:<port>; remote hosts render the endpoint.
await expect(host).toContainText(new RegExp(`${escapedEndpoint}|Local`), { timeout: 30_000 });
await expect(host).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/, { timeout: 30_000 });
await page.keyboard.press("Escape");
await expect(host).not.toBeVisible();
}
@@ -195,6 +198,12 @@ export async function chooseHostColor(page: Page, colorName: string): Promise<vo
await expect(page.getByRole("button", { name: `Color, ${colorName}` })).toBeVisible();
}
export async function chooseHostIcon(page: Page, iconName: string): Promise<void> {
await page.getByTestId("host-appearance-icon").click();
await page.getByRole("menuitem", { name: iconName, exact: true }).click();
await expect(page.getByRole("button", { name: `Icon, ${iconName}` })).toBeVisible();
}
export async function chooseHostBadgeDisplay(
page: Page,
option: "Name" | "Icon only" | "Hidden",
+4 -14
View File
@@ -16,8 +16,8 @@ export async function openSidebarHostPicker(page: Page) {
await page.getByRole("button", { name: "Hosts", exact: true }).click();
}
export function sidebarHostSettingsButton(page: Page) {
return page.getByRole("button", { name: `Open ${TEST_HOST_LABEL} settings`, exact: true });
export function sidebarHostRowButton(page: Page) {
return page.getByTestId(`sidebar-host-row-${getServerId()}`);
}
export async function bindCommandCenterToEnter(page: Page) {
@@ -32,20 +32,10 @@ export async function bindCommandCenterToEnter(page: Page) {
});
}
export async function expectStandaloneSidebarHostSettingsButton(page: Page) {
const gear = sidebarHostSettingsButton(page);
await expect(gear).toBeVisible();
expect(await gear.evaluate((button) => button.parentElement?.closest("button") === null)).toBe(
true,
);
}
export async function activateSidebarHostSettingsWithKeyboard(page: Page) {
const host = page.getByRole("button", { name: TEST_HOST_LABEL, exact: true });
const host = sidebarHostRowButton(page);
await expect(host).toBeVisible();
await expect(host).toBeFocused();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Tab");
await expect(sidebarHostSettingsButton(page)).toBeFocused();
await page.keyboard.press("Enter");
}
+304 -136
View File
@@ -1,11 +1,28 @@
import { useCallback, useMemo, type ReactElement, type ReactNode } from "react";
import { Pressable, View } from "react-native";
import { Plus, Server, Settings } from "lucide-react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import {
useCallback,
useEffect,
useMemo,
useState,
type ReactElement,
type ReactNode,
} from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { Check, Plus, Server } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { HostStatusDot } from "@/components/host-status-dot";
import { Combobox, ComboboxItem, type ComboboxProps } from "@/components/ui/combobox";
import { Combobox, type ComboboxProps } from "@/components/ui/combobox";
import { PressHighlight } from "@/components/ui/press-highlight";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { useHostRuntimeSnapshot, type ActiveConnection } from "@/runtime/host-runtime";
import { defaultHostAppearance, resolveHostIcon, type HostAppearance } from "@/hosts/appearance";
import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon";
import {
getHostRuntimeStore,
useHostRuntimeConnectionStatus,
useHosts,
} from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { orderHostsLocalFirst } from "@/types/host-connection";
import {
ADD_HOST_OPTION_ID,
@@ -22,7 +39,16 @@ export {
};
const SEARCHABLE_THRESHOLD = 10;
const DEFAULT_DESKTOP_MIN_WIDTH = 328;
const LEADING_RAIL_SIZE = 16;
const HOST_ROW_ICON_SIZE = 14;
type RenderHostOption = NonNullable<ComboboxProps["renderOption"]>;
const ThemedCheck = withUnistyles(Check);
const ThemedPlus = withUnistyles(Plus);
const ThemedServer = withUnistyles(Server);
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
export interface HostPickerHost {
serverId: string;
label: string;
@@ -36,122 +62,166 @@ export function HostStatusDotSlot({ serverId }: { serverId: string }): ReactElem
);
}
// Standard secure/plain web ports carry no information in the host display, so
// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept.
function formatConnectionEndpoint(endpoint: string): string {
return endpoint.replace(/:(?:443|80)$/, "");
}
// Socket/pipe transports have no host:port — their endpoint is a filesystem
// path, so they read as "Local". TCP and relay show the address being used.
function formatActiveConnectionLabel(connection: ActiveConnection): string {
if (connection.type === "directSocket" || connection.type === "directPipe") {
return "Local";
}
return formatConnectionEndpoint(connection.endpoint);
}
export interface HostPickerOptionProps {
serverId: string;
label: string;
showActiveConnection: boolean;
appearance: HostAppearance;
selected?: boolean;
active: boolean;
onPress: () => void;
onOpenHostSettings?: (serverId: string) => void;
testID?: string;
}
export function HostPickerOption({
serverId,
label,
showActiveConnection,
appearance,
selected,
active,
onPress,
onOpenHostSettings,
testID,
}: HostPickerOptionProps): ReactElement {
const { theme } = useUnistyles();
const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null;
const connectionLabel =
showActiveConnection && activeConnection
? formatActiveConnectionLabel(activeConnection)
: undefined;
const leadingSlot = useMemo(() => <HostStatusDotSlot serverId={serverId} />, [serverId]);
const handleSettingsPress = useCallback(() => {
onOpenHostSettings?.(serverId);
}, [onOpenHostSettings, serverId]);
const trailingAction = useMemo(() => {
if (!onOpenHostSettings) return undefined;
return (
<Pressable
onPress={handleSettingsPress}
style={styles.settingsAction}
accessibilityRole="button"
accessibilityLabel={`Open ${label} settings`}
>
<Settings size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
</Pressable>
);
}, [
handleSettingsPress,
label,
onOpenHostSettings,
theme.colors.foregroundMuted,
theme.iconSize.sm,
]);
const status = useHostRuntimeConnectionStatus(serverId);
const detectedMachineKind = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.machineKind ?? null,
);
const resolvedIcon = resolveHostIcon({ appearance, detectedMachineKind });
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const isOffline = status === "offline" || status === "error";
return (
<ComboboxItem
label={label}
description={connectionLabel}
leadingSlot={leadingSlot}
trailingAction={trailingAction}
selected={selected}
active={active}
onPress={onPress}
testID={testID}
/>
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.hostRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
<HostStatusDot serverId={serverId} />
</View>
<View style={styles.hostBody}>
<View style={styles.hostHeaderRow}>
<HostIconGlyph
icon={resolvedIcon}
color={appearance.color}
size={HOST_ROW_ICON_SIZE}
style={styles.hostGlyph}
/>
<Text style={[styles.hostName, isOffline && styles.hostNameMuted]} numberOfLines={1}>
{label}
</Text>
</View>
<HostConnectionLine serverId={serverId} />
</View>
<View style={styles.hostTrailing}>
<HostLatencyLabel serverId={serverId} />
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
</View>
</PressHighlight>
</View>
);
}
const SYSTEM_HOST_PICKER_OPTION_LABELS: Record<"add" | "all" | "enableBuiltInDaemon", string> = {
add: "Add host",
all: "All hosts",
enableBuiltInDaemon: "Enable built-in daemon",
};
function SystemHostPickerOption({
function AllHostsOption({
active,
selected,
onPress,
kind,
testID,
}: {
active: boolean;
selected?: boolean;
onPress: () => void;
kind: "add" | "all" | "enableBuiltInDaemon";
testID?: string;
}): ReactElement {
const { theme } = useUnistyles();
const Icon = kind === "add" ? Plus : Server;
const label = SYSTEM_HOST_PICKER_OPTION_LABELS[kind];
const leadingSlot = useMemo(
() => <Icon size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />,
[Icon, theme.colors.foregroundMuted, theme.iconSize.sm],
);
const { t } = useTranslation();
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const label = t("sidebar.display.hostFilter.all");
return (
<ComboboxItem
label={label}
leadingSlot={leadingSlot}
selected={selected}
active={active}
onPress={onPress}
testID={testID}
/>
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
</View>
<Text style={styles.actionLabel} numberOfLines={1}>
{label}
</Text>
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
</PressHighlight>
</View>
);
}
function ActionOptionRow({
kind,
active,
showDivider,
onPress,
testID,
}: {
kind: "add" | "enableBuiltInDaemon";
active: boolean;
showDivider: boolean;
onPress: () => void;
testID?: string;
}): ReactElement {
const { t } = useTranslation();
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const label = kind === "add" ? t("settings.addHost") : t("settings.enableBuiltInDaemon");
return (
<View>
{showDivider ? <View style={styles.actionSectionDivider} /> : null}
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
{kind === "add" ? (
<ThemedPlus size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
) : (
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
)}
</View>
<Text style={styles.actionLabel} numberOfLines={1}>
{label}
</Text>
</PressHighlight>
</View>
</View>
);
}
@@ -168,7 +238,6 @@ export interface HostPickerProps {
includeEnableBuiltInDaemon?: boolean;
onEnableBuiltInDaemon?: () => void;
showActiveConnection?: boolean;
onOpenHostSettings?: (serverId: string) => void;
searchable?: boolean;
title?: string;
desktopPlacement?: ComboboxProps["desktopPlacement"];
@@ -190,74 +259,85 @@ export function HostPicker({
onAddHost,
includeEnableBuiltInDaemon,
onEnableBuiltInDaemon,
showActiveConnection,
onOpenHostSettings,
searchable,
title,
desktopPlacement = "bottom-start",
desktopMinWidth,
desktopMinWidth = DEFAULT_DESKTOP_MIN_WIDTH,
addHostTestID,
hostOptionTestID,
children,
}: HostPickerProps): ReactElement {
const { t } = useTranslation();
const localServerId = useLocalDaemonServerId();
const allHostProfiles = useHosts();
const orderedHosts = useMemo(
() => orderHostsLocalFirst(hosts, localServerId),
[hosts, localServerId],
);
const appearanceByServerId = useMemo(() => {
const map = new Map<string, HostAppearance>();
for (const profile of allHostProfiles) {
map.set(profile.serverId, profile.appearance);
}
return map;
}, [allHostProfiles]);
useEffect(() => {
if (!open) return;
getHostRuntimeStore().refreshActiveLatencies(orderedHosts.map((host) => host.serverId));
}, [open, orderedHosts]);
const options = useMemo(() => {
const hostOptions = orderedHosts.map((host) => ({ id: host.serverId, label: host.label }));
if (includeAllHost) hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: "All hosts" });
if (includeAddHost) hostOptions.push({ id: ADD_HOST_OPTION_ID, label: "Add host" });
if (includeEnableBuiltInDaemon)
if (includeAllHost) {
hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: t("sidebar.display.hostFilter.all") });
}
if (includeAddHost) {
hostOptions.push({ id: ADD_HOST_OPTION_ID, label: t("settings.addHost") });
}
if (includeEnableBuiltInDaemon) {
hostOptions.push({
id: ENABLE_BUILT_IN_DAEMON_OPTION_ID,
label: "Enable built-in daemon",
label: t("settings.enableBuiltInDaemon"),
});
}
return hostOptions;
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon]);
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon, t]);
let firstActionOptionId: string | null = null;
if (includeAddHost) {
firstActionOptionId = ADD_HOST_OPTION_ID;
} else if (includeEnableBuiltInDaemon) {
firstActionOptionId = ENABLE_BUILT_IN_DAEMON_OPTION_ID;
}
const isSearchable = searchable === true && orderedHosts.length > SEARCHABLE_THRESHOLD;
const resolvedTitle = title ?? t("sidebar.actions.hosts");
const handleSelect = useCallback(
(id: string) => {
if (id === ADD_HOST_OPTION_ID) {
onOpenChange(false);
onAddHost?.();
} else if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
onEnableBuiltInDaemon?.();
} else {
onSelect(id);
return;
}
if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
onOpenChange(false);
onEnableBuiltInDaemon?.();
return;
}
onSelect(id);
onOpenChange(false);
},
[onAddHost, onEnableBuiltInDaemon, onOpenChange, onSelect],
);
const handleOpenHostSettings = useCallback(
(serverId: string) => {
onOpenHostSettings?.(serverId);
onOpenChange(false);
},
[onOpenHostSettings, onOpenChange],
);
const renderOption = useCallback<RenderHostOption>(
({ option, selected, active, onPress }) => {
if (option.id === ADD_HOST_OPTION_ID) {
return (
<SystemHostPickerOption
kind="add"
active={active}
onPress={onPress}
testID={addHostTestID}
/>
);
}
if (option.id === ALL_HOSTS_OPTION_ID) {
return (
<SystemHostPickerOption
kind="all"
<AllHostsOption
active={active}
selected={selected}
onPress={onPress}
@@ -265,30 +345,48 @@ export function HostPicker({
/>
);
}
if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
if (option.id === ADD_HOST_OPTION_ID) {
return (
<SystemHostPickerOption kind="enableBuiltInDaemon" active={active} onPress={onPress} />
<ActionOptionRow
kind="add"
active={active}
showDivider={firstActionOptionId === ADD_HOST_OPTION_ID && orderedHosts.length > 0}
onPress={onPress}
testID={addHostTestID}
/>
);
}
if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
return (
<ActionOptionRow
kind="enableBuiltInDaemon"
active={active}
showDivider={
firstActionOptionId === ENABLE_BUILT_IN_DAEMON_OPTION_ID && orderedHosts.length > 0
}
onPress={onPress}
/>
);
}
const appearance = appearanceByServerId.get(option.id) ?? defaultHostAppearance();
return (
<HostPickerOption
serverId={option.id}
label={option.label}
showActiveConnection={showActiveConnection === true}
appearance={appearance}
selected={selected}
active={active}
onPress={onPress}
onOpenHostSettings={onOpenHostSettings ? handleOpenHostSettings : undefined}
testID={hostOptionTestID?.(option.id)}
/>
);
},
[
addHostTestID,
appearanceByServerId,
firstActionOptionId,
hostOptionTestID,
onOpenHostSettings,
showActiveConnection,
handleOpenHostSettings,
orderedHosts.length,
],
);
@@ -301,8 +399,8 @@ export function HostPicker({
onSelect={handleSelect}
renderOption={renderOption}
searchable={isSearchable}
searchPlaceholder="Search hosts"
title={title ?? "Host"}
searchPlaceholder={t("sidebar.host.searchPlaceholder")}
title={resolvedTitle}
open={open}
onOpenChange={onOpenChange}
anchorRef={anchorRef}
@@ -314,16 +412,86 @@ export function HostPicker({
}
const styles = StyleSheet.create((theme) => ({
settingsAction: {
flex: 1,
justifyContent: "center",
paddingLeft: theme.spacing[1],
paddingRight: theme.spacing[3],
},
statusDotSlot: {
width: theme.iconSize.sm,
height: theme.iconSize.sm,
alignItems: "center",
justifyContent: "center",
},
rowEnvelope: {
position: "relative",
},
// Shared leading rail: the status dot on host rows and the '+' / All hosts glyph share one
// centered 16px column aligned to the first line's 18px line-height.
leadingRailSlot: {
width: LEADING_RAIL_SIZE,
height: 18,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
hostRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[2],
marginHorizontal: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
paddingVertical: theme.spacing[2],
borderRadius: theme.borderRadius.md,
},
rowHighlighted: {
backgroundColor: theme.colors.surface1,
},
hostBody: {
flex: 1,
minWidth: 0,
gap: 2,
},
hostHeaderRow: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
hostGlyph: {
flexShrink: 0,
},
hostName: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.base,
lineHeight: 18,
color: theme.colors.foreground,
},
hostNameMuted: {
color: theme.colors.foregroundMuted,
},
hostTrailing: {
flexDirection: "row",
alignItems: "center",
height: 18,
gap: theme.spacing[2],
flexShrink: 0,
},
actionSectionDivider: {
height: theme.borderWidth[1],
backgroundColor: theme.colors.border,
marginVertical: theme.spacing[1],
},
actionRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
marginHorizontal: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
paddingVertical: theme.spacing[2],
borderRadius: theme.borderRadius.md,
},
actionLabel: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.base,
lineHeight: 18,
color: theme.colors.foreground,
},
}));
@@ -0,0 +1,32 @@
import Svg, { Circle } from "react-native-svg";
const TAILSCALE_DOTS = [3, 12, 21].flatMap((cy, row) =>
[3, 12, 21].map((cx, column) => ({
cx,
cy,
// The Tailscale mark is a 3x3 dot grid with a solid T (middle row + bottom center).
solid: row === 1 || (row === 2 && column === 1),
})),
);
export interface TailscaleIconProps {
size?: number;
color?: string;
}
export function TailscaleIcon({ size = 12, color = "currentColor" }: TailscaleIconProps) {
return (
<Svg width={size} height={size} viewBox="0 0 24 24" fill={color}>
{TAILSCALE_DOTS.map((dot) => (
<Circle
key={`${dot.cx}:${dot.cy}`}
cx={dot.cx}
cy={dot.cy}
r={3}
fill={color}
opacity={dot.solid ? 1 : 0.3}
/>
))}
</Svg>
);
}
+2 -2
View File
@@ -388,10 +388,10 @@ function SidebarHostPicker({
includeAddHost
onAddHost={onAddHost}
showActiveConnection
onOpenHostSettings={onOpenHostSettings}
searchable
title={label}
desktopPlacement="top-start"
desktopMinWidth={240}
desktopMinWidth={328}
addHostTestID="sidebar-host-add"
hostOptionTestID={sidebarHostOptionTestID}
>
+60 -14
View File
@@ -73,6 +73,9 @@ export { buildDesktopFrameStyle } from "./combobox-frame-style";
const IS_WEB = isWeb;
const TRAILING_ACTION_DATASET = { comboboxTrailingAction: true };
const FOOTER_DATASET = { comboboxFooter: true };
const FOCUSED_COMBOBOX_ACTION_SELECTOR =
'[data-combobox-trailing-action] button, [data-combobox-trailing-action] [role="button"], [data-combobox-footer] button, [data-combobox-footer] [role="button"]';
export type ComboboxOption = ComboboxOptionModel;
export type ComboboxDesktopPlacement = "top-start" | "bottom-start";
@@ -402,6 +405,7 @@ export function ComboboxEmpty({ children }: { children: ReactNode }): ReactEleme
type RenderOptionFn = NonNullable<ComboboxProps["renderOption"]>;
interface OptionRowProps {
index: number;
option: ComboboxOption;
selected: boolean;
active: boolean;
@@ -409,20 +413,27 @@ interface OptionRowProps {
renderOption: RenderOptionFn | undefined;
}
function OptionRow({ option, selected, active, onSelect, renderOption }: OptionRowProps) {
function OptionRow({ index, option, selected, active, onSelect, renderOption }: OptionRowProps) {
const handlePress = useCallback(() => onSelect(option.id), [onSelect, option.id]);
const optionDataset = useMemo(() => ({ comboboxOptionIndex: String(index) }), [index]);
if (renderOption) {
return <View>{renderOption({ option, selected, active, onPress: handlePress })}</View>;
return (
<View dataSet={optionDataset}>
{renderOption({ option, selected, active, onPress: handlePress })}
</View>
);
}
return (
<ComboboxItem
label={option.label}
description={option.description}
kind={option.kind}
selected={selected}
active={active}
onPress={handlePress}
/>
<View dataSet={optionDataset}>
<ComboboxItem
label={option.label}
description={option.description}
kind={option.kind}
selected={selected}
active={active}
onPress={handlePress}
/>
</View>
);
}
@@ -451,6 +462,7 @@ function OptionsList({
{options.map((opt, index) => (
<OptionRow
key={opt.id}
index={index}
option={opt}
selected={opt.id === value}
active={index === activeIndex}
@@ -952,8 +964,9 @@ function dispatchDesktopKey(
return true;
}
if (key === "Enter") {
// Consume the shortcut but keep the browser's default button activation.
if (isWeb && document.activeElement?.matches("[data-combobox-trailing-action] button")) {
// Consume the shortcut but keep the browser's default button activation when the user moved
// keyboard focus onto a trailing action or footer button inside the combobox.
if (isWeb && document.activeElement?.matches(FOCUSED_COMBOBOX_ACTION_SELECTOR)) {
return true;
}
if (input.orderedVisibleOptions.length === 0) return false;
@@ -1127,7 +1140,12 @@ function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children
[safeAreaBottom],
);
const footerView = useMemo(
() => (footer ? <View style={footerStyle}>{footer}</View> : undefined),
() =>
footer ? (
<View style={footerStyle} dataSet={FOOTER_DATASET}>
{footer}
</View>
) : undefined,
[footer, footerStyle],
);
return (
@@ -1341,7 +1359,11 @@ function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null {
renderOption={props.renderOption}
/>
)}
{props.footer ? <View style={styles.footer}>{props.footer}</View> : null}
{props.footer ? (
<View style={styles.footer} dataSet={FOOTER_DATASET}>
{props.footer}
</View>
) : null}
</FloatingSurface>
</View>
</OverlayLayerProvider>
@@ -1597,6 +1619,30 @@ export function Combobox({
setActiveIndex,
);
// Keep activeIndex aligned when a keyboard user Tabs onto a specific option button on web.
useEffect(() => {
if (!IS_WEB || !isOpen || isMobile) return;
const handleFocusIn = (event: FocusEvent) => {
const target = event.target;
if (!(target instanceof Element)) return;
const optionEl = target.closest("[data-combobox-option-index]");
if (!optionEl) return;
const nextIndex = Number.parseInt(
optionEl.getAttribute("data-combobox-option-index") ?? "",
10,
);
if (
Number.isInteger(nextIndex) &&
nextIndex >= 0 &&
nextIndex < orderedVisibleOptions.length
) {
setActiveIndex(nextIndex);
}
};
document.addEventListener("focusin", handleFocusIn);
return () => document.removeEventListener("focusin", handleFocusIn);
}, [isMobile, isOpen, orderedVisibleOptions.length]);
const handleSelect = useCallback(
(id: string) => {
onSelect(id);
+142 -6
View File
@@ -7,6 +7,7 @@ import {
buildGitActions,
isCurrentBranchBase,
canMergeIntoLocalBase,
readSyncRemotes,
readUpstreamState,
type BuildGitActionsInput,
} from "./policy";
@@ -60,9 +61,11 @@ function githubStatus(overrides: Partial<GithubMergeFactsFixture> = {}): GithubM
function createInput(
overrides: Partial<Omit<BuildGitActionsInput, "mergeCapability">> & {
pullRequestGithub?: unknown;
// Shorthand for a branch that both Pull and Push have a remote for.
hasRemote?: boolean;
} = {},
): BuildGitActionsInput {
const { pullRequestGithub = null, ...rest } = overrides;
const { pullRequestGithub = null, hasRemote = false, ...rest } = overrides;
return {
isGit: true,
githubFeaturesEnabled: true,
@@ -76,8 +79,8 @@ function createInput(
pullRequestIsMerged: false,
pullRequestMergeable: "UNKNOWN",
mergeCapability: deriveMergeCapability(pullRequestGithub),
hasRemote: false,
hasFirstPushRemote: rest.hasRemote ?? false,
hasPullRemote: hasRemote,
hasPushRemote: hasRemote,
upstream: "tracked",
isPaseoOwnedWorktree: false,
isOnBaseBranch: true,
@@ -176,6 +179,10 @@ function pushActionOf(actions: ReturnType<typeof buildGitActions>) {
return actions.secondary.find((action) => action.id === "push");
}
function pullAndPushActionOf(actions: ReturnType<typeof buildGitActions>) {
return actions.secondary.find((action) => action.id === "pull-and-push");
}
describe("git-actions-policy", () => {
afterEach(async () => {
await i18n.changeLanguage("en");
@@ -433,7 +440,7 @@ describe("git-actions-policy", () => {
});
it("does not offer Push when Git pushes the branch to another remote", () => {
const actions = buildGitActions(createInput({ ...neverPushed, hasFirstPushRemote: false }));
const actions = buildGitActions(createInput({ ...neverPushed, hasPushRemote: false }));
const pushAction = pushActionOf(actions);
expect(actions.primary?.id).not.toBe("push");
@@ -441,13 +448,142 @@ describe("git-actions-policy", () => {
"Push isn't available here because this branch is not connected to a remote yet",
);
});
});
it("keeps offering Push in a Paseo worktree when Git pushes the branch to another remote", () => {
// The daemon reports where Pull and Push go for the branch, so the remote's name never matters.
describe("a branch that tracks a remote other than origin", () => {
const tracksDorasMono = readSyncRemotes({
hasRemote: false,
pullRemote: "doras-mono",
pushRemote: "doras-mono",
upstreamState: "tracked",
aheadOfOrigin: 1,
isPaseoOwnedWorktree: false,
});
it("offers Push when the branch is ahead", () => {
const actions = buildGitActions(
createInput({ ...neverPushed, hasFirstPushRemote: false, isPaseoOwnedWorktree: true }),
createInput({ ...tracksDorasMono, aheadOfOrigin: 1, behindOfOrigin: 0 }),
);
expect(actions.primary).toMatchObject({ id: "push", label: "Push" });
expect(pushActionOf(actions)).toMatchObject({
disabled: false,
unavailableMessage: undefined,
});
});
it("offers Pull when the branch is behind", () => {
const actions = buildGitActions(
createInput({ ...tracksDorasMono, aheadOfOrigin: 0, behindOfOrigin: 2 }),
);
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
});
it("offers Pull first and Pull and push when the branch is ahead and behind", () => {
const actions = buildGitActions(
createInput({ ...tracksDorasMono, aheadOfOrigin: 1, behindOfOrigin: 2 }),
);
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
expect(pullAndPushActionOf(actions)).toMatchObject({
disabled: false,
unavailableMessage: undefined,
});
expect(pushActionOf(actions)?.unavailableMessage).toBe(
"Push isn't available yet because there are newer changes to bring in first",
);
});
// `feature` tracking `upstream/main`: the daemon reports a pull remote and no push remote.
const pullOnly = readSyncRemotes({
hasRemote: false,
pullRemote: "upstream",
pushRemote: null,
upstreamState: "tracked",
aheadOfOrigin: 1,
isPaseoOwnedWorktree: false,
});
it("does not offer Push when it would land on a differently named upstream branch", () => {
const actions = buildGitActions(
createInput({ ...pullOnly, aheadOfOrigin: 1, behindOfOrigin: 0 }),
);
expect(actions.primary?.id).not.toBe("push");
expect(pushActionOf(actions)?.unavailableMessage).toBe(
"Push isn't available here because this branch is not connected to a remote yet",
);
});
it("still offers Pull for that branch, and not Pull and push", () => {
const actions = buildGitActions(
createInput({ ...pullOnly, aheadOfOrigin: 1, behindOfOrigin: 2 }),
);
expect(actions.primary).toMatchObject({ id: "pull", label: "Pull" });
expect(pullAndPushActionOf(actions)?.unavailableMessage).toBe(
"Pull and push isn't available here because this branch is not connected to a remote yet",
);
});
});
describe("readSyncRemotes", () => {
it("uses the remotes the daemon reports", () => {
expect(
readSyncRemotes({
hasRemote: true,
pullRemote: null,
pushRemote: "origin",
upstreamState: "none",
aheadOfOrigin: null,
isPaseoOwnedWorktree: false,
}),
).toEqual({ hasPullRemote: false, hasPushRemote: true });
});
// The rest covers a daemon that predates pullRemote and pushRemote.
const tracked = {
upstreamState: "tracked",
aheadOfOrigin: 1,
isPaseoOwnedWorktree: false,
} as const;
const neverPushed = {
upstreamState: "none",
aheadOfOrigin: null,
isPaseoOwnedWorktree: false,
} as const;
it("pulls and pushes a tracked branch on an older daemon only when the checkout has origin", () => {
expect(readSyncRemotes({ ...tracked, hasRemote: true })).toEqual({
hasPullRemote: true,
hasPushRemote: true,
});
expect(readSyncRemotes({ ...tracked, hasRemote: false })).toEqual({
hasPullRemote: false,
hasPushRemote: false,
});
});
it("makes a regular checkout's first push only where an older daemon confirmed it", () => {
expect(
readSyncRemotes({ ...neverPushed, hasRemote: true, firstPushRemote: "origin" }),
).toMatchObject({ hasPushRemote: true });
expect(
readSyncRemotes({ ...neverPushed, hasRemote: true, firstPushRemote: null }),
).toMatchObject({ hasPushRemote: false });
});
it("keeps a Paseo worktree's first push on an older daemon that reports no first push remote", () => {
expect(
readSyncRemotes({
...neverPushed,
hasRemote: true,
firstPushRemote: null,
isPaseoOwnedWorktree: true,
}),
).toMatchObject({ hasPushRemote: true });
});
});
+41 -15
View File
@@ -96,7 +96,41 @@ export function readUpstreamState(
return status.isPaseoOwnedWorktree ? "none" : "unknown";
}
export interface BuildGitActionsInput {
export interface SyncRemotes {
/** Pull has a remote to fetch the branch from. Not limited to origin. */
hasPullRemote: boolean;
/** Push has a remote to send the branch to. Not limited to origin. */
hasPushRemote: boolean;
}
export function readSyncRemotes(
status: Pick<
CheckoutStatusPayload,
| "pullRemote"
| "pushRemote"
| "hasRemote"
| "firstPushRemote"
| "upstreamState"
| "aheadOfOrigin"
| "isPaseoOwnedWorktree"
>,
): SyncRemotes {
if (status.pullRemote !== undefined && status.pushRemote !== undefined) {
return { hasPullRemote: status.pullRemote !== null, hasPushRemote: status.pushRemote !== null };
}
// COMPAT(checkoutSyncRemotes): added in v0.17.5, remove after 2027-05-24 once the daemon floor
// reports pullRemote and pushRemote. Older daemons pull and push only in checkouts that have
// origin. They make a first push from a Paseo worktree, and from a regular checkout only where
// they report firstPushRemote.
const isFirstPush = readUpstreamState(status) === "none";
const canFirstPush = status.isPaseoOwnedWorktree || (status.firstPushRemote ?? null) !== null;
return {
hasPullRemote: status.hasRemote,
hasPushRemote: status.hasRemote && (!isFirstPush || canFirstPush),
};
}
export interface BuildGitActionsInput extends SyncRemotes {
isGit: boolean;
githubFeaturesEnabled: boolean;
/** Forge brand label (e.g. "GitHub", "GitLab") for forge-neutral unavailable copy. */
@@ -111,9 +145,6 @@ export interface BuildGitActionsInput {
pullRequestIsMerged: boolean;
pullRequestMergeable: PullRequestMergeable;
mergeCapability: MergeCapability | null;
hasRemote: boolean;
/** The daemon confirmed where a first push publishes the branch. */
hasFirstPushRemote: boolean;
upstream: GitUpstreamState;
isPaseoOwnedWorktree: boolean;
isOnBaseBranch: boolean;
@@ -572,11 +603,11 @@ function getEnablePullRequestAutoMergeActionLabel(id: PullRequestAutoMergeEnable
}
function canPull(input: BuildGitActionsInput): boolean {
return input.hasRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0;
return input.hasPullRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0;
}
function canPush(input: BuildGitActionsInput): boolean {
return input.hasRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0;
return input.hasPushRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0;
}
function hasPushableCommits(input: BuildGitActionsInput): boolean {
@@ -585,9 +616,7 @@ function hasPushableCommits(input: BuildGitActionsInput): boolean {
return (input.aheadOfOrigin ?? 0) > 0;
case "none":
// A first push, which sets the upstream. The commits to send are the ones ahead of the base.
// Paseo worktrees always publish to origin. A regular checkout publishes only where the
// daemon confirmed Git would push the branch too, so a fork setup is not sent to origin.
return input.aheadCount > 0 && (input.isPaseoOwnedWorktree || input.hasFirstPushRemote);
return input.aheadCount > 0;
case "gone":
case "unknown":
// The branch has an upstream that is deleted or unreadable, so nothing counts the commits
@@ -678,7 +707,7 @@ function hasEnabledPrAutoMerge(input: BuildGitActionsInput): boolean {
}
function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasRemote) {
if (!input.hasPullRemote) {
return i18n.t("workspace.git.actions.unavailable.pullNoRemote");
}
if (input.hasUncommittedChanges) {
@@ -694,7 +723,7 @@ function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefi
}
function getPushUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasRemote) {
if (!input.hasPushRemote) {
return i18n.t("workspace.git.actions.unavailable.pushNoRemote");
}
if ((input.behindOfOrigin ?? 0) > 0) {
@@ -706,14 +735,11 @@ function getPushUnavailableMessage(input: BuildGitActionsInput): string | undefi
if (input.upstream === "gone") {
return i18n.t("workspace.git.actions.unavailable.pushUpstreamGone");
}
if (input.upstream === "none" && input.aheadCount > 0) {
return i18n.t("workspace.git.actions.unavailable.pushNoRemote");
}
return i18n.t("workspace.git.actions.unavailable.pushNothing");
}
function getPullAndPushUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasRemote) {
if (!input.hasPullRemote || !input.hasPushRemote) {
return i18n.t("workspace.git.actions.unavailable.pullAndPushNoRemote");
}
if (input.hasUncommittedChanges) {
+12 -11
View File
@@ -15,11 +15,13 @@ import {
isCurrentBranchBase,
canMergeIntoLocalBase,
narrowPullRequestState,
readSyncRemotes,
readUpstreamState,
type BuildGitActionsInput,
type GitAction,
type GitActions,
type GitUpstreamState,
type SyncRemotes,
} from "@/git/policy";
import { deriveMergeCapability } from "@/git/merge-capability";
import type { CheckoutPrMergeMethod } from "@getpaseo/protocol/messages";
@@ -123,15 +125,15 @@ interface DeriveGitActionsStateArgs {
baseRef: string | undefined;
}
interface DerivedGitActionsState {
const NO_SYNC_REMOTES: SyncRemotes = { hasPullRemote: false, hasPushRemote: false };
interface DerivedGitActionsState extends SyncRemotes {
actionsDisabled: boolean;
aheadCount: number;
behindBaseCount: number;
aheadOfOrigin: number | null;
behindOfOrigin: number | null;
hasPullRequest: boolean;
hasRemote: boolean;
hasFirstPushRemote: boolean;
upstream: GitUpstreamState;
isPaseoOwnedWorktree: boolean;
isOnBaseBranch: boolean;
@@ -183,8 +185,7 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
actionsDisabled,
...extractGitCommitCounts(gitStatus),
hasPullRequest: Boolean(prStatus?.url),
hasRemote: gitStatus?.hasRemote ?? false,
hasFirstPushRemote: (gitStatus?.firstPushRemote ?? null) !== null,
...(gitStatus ? readSyncRemotes(gitStatus) : NO_SYNC_REMOTES),
upstream: gitStatus ? readUpstreamState(gitStatus) : "unknown",
isPaseoOwnedWorktree,
isOnBaseBranch: isCurrentBranchBase(gitStatus?.currentBranch, baseRef),
@@ -673,8 +674,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
aheadOfOrigin,
behindOfOrigin,
hasPullRequest,
hasRemote,
hasFirstPushRemote,
hasPullRemote,
hasPushRemote,
upstream,
isPaseoOwnedWorktree,
isOnBaseBranch,
@@ -706,8 +707,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
pullRequestIsMerged: prStatus?.isMerged ?? false,
pullRequestMergeable: prStatus?.mergeable ?? "UNKNOWN",
mergeCapability: deriveMergeCapability(prStatus?.forgeSpecific, prStatus?.github),
hasRemote,
hasFirstPushRemote,
hasPullRemote,
hasPushRemote,
upstream,
isPaseoOwnedWorktree,
isOnBaseBranch,
@@ -816,8 +817,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
};
}, [
isGit,
hasRemote,
hasFirstPushRemote,
hasPullRemote,
hasPushRemote,
upstream,
hasPullRequest,
prStatus?.url,
+94 -8
View File
@@ -4,6 +4,7 @@ import {
defaultHostAppearance,
normalizeStoredHostAppearance,
resolveHostBadgeDisplay,
resolveHostIcon,
selectHostBadges,
} from "@/hosts/appearance";
@@ -16,7 +17,7 @@ function host(
}
describe("normalizeStoredHostAppearance", () => {
it("defaults when the stored registry predates the field or holds junk", () => {
it("defaults without writing an icon field so untouched records stay downgrade-safe", () => {
const expected = { color: "none", badgeDisplay: null };
expect(normalizeStoredHostAppearance(undefined)).toEqual(expected);
expect(normalizeStoredHostAppearance(null)).toEqual(expected);
@@ -24,13 +25,79 @@ describe("normalizeStoredHostAppearance", () => {
expect(normalizeStoredHostAppearance({})).toEqual(expected);
expect(normalizeStoredHostAppearance({ color: "chartreuse" })).toEqual(expected);
expect(normalizeStoredHostAppearance({ badgeDisplay: "loud" })).toEqual(expected);
expect("icon" in defaultHostAppearance()).toBe(false);
});
it("round-trips a value the user actually chose", () => {
expect(normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" })).toEqual({
it("preserves an unknown stored icon on disk while falling back at render time", () => {
const normalized = normalizeStoredHostAppearance({
color: "teal",
icon: "spaceship",
badgeDisplay: "icon",
});
expect(normalized).toEqual({
color: "teal",
icon: "spaceship",
badgeDisplay: "icon",
});
expect(resolveHostIcon({ appearance: normalized })).toBe("server");
expect(resolveHostIcon({ appearance: normalized, detectedMachineKind: "laptop" })).toBe(
"laptop",
);
});
it("keeps icon absent on stored entries that predate host icons", () => {
const normalized = normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" });
expect(normalized).toEqual({
color: "teal",
badgeDisplay: "icon",
});
expect("icon" in normalized).toBe(false);
});
it("round-trips a value the user actually chose", () => {
expect(
normalizeStoredHostAppearance({ color: "teal", icon: "laptop", badgeDisplay: "icon" }),
).toEqual({
color: "teal",
icon: "laptop",
badgeDisplay: "icon",
});
});
});
describe("resolveHostIcon", () => {
it("prefers an explicit user icon over daemon auto-detection", () => {
expect(
resolveHostIcon({
appearance: { color: "none", icon: "workstation", badgeDisplay: null },
detectedMachineKind: "laptop",
}),
).toBe("workstation");
});
it("uses the daemon-detected machine kind while the user icon is auto (null)", () => {
expect(
resolveHostIcon({
appearance: defaultHostAppearance(),
detectedMachineKind: "laptop",
}),
).toBe("laptop");
expect(
resolveHostIcon({
appearance: defaultHostAppearance(),
detectedMachineKind: "container",
}),
).toBe("container");
});
it("falls back to server when the detected machine kind is absent or unknown", () => {
expect(resolveHostIcon({ appearance: defaultHostAppearance() })).toBe("server");
expect(
resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: null }),
).toBe("server");
expect(
resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: "future-kind" }),
).toBe("server");
});
});
@@ -50,13 +117,13 @@ describe("resolveHostBadgeDisplay", () => {
it("prefers an explicit choice over either default", () => {
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", badgeDisplay: "icon" },
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
isLocalHost: true,
}),
).toBe("icon");
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", badgeDisplay: "hidden" },
appearance: { color: "none", icon: "server", badgeDisplay: "hidden" },
isLocalHost: false,
}),
).toBe("hidden");
@@ -72,7 +139,7 @@ describe("resolveHostBadgeDisplay", () => {
).toBeNull();
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", badgeDisplay: "icon" },
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
isLocalHost: false,
localHostResolutionPending: true,
}),
@@ -93,7 +160,7 @@ describe("selectHostBadges", () => {
it("omits a host the user hid and keeps its sibling", () => {
const badges = selectHostBadges({
hosts: [
host("alpha", "Alpha", { color: "none", badgeDisplay: "hidden" }),
host("alpha", "Alpha", { color: "none", icon: "server", badgeDisplay: "hidden" }),
host("beta", "Beta"),
],
localServerId: null,
@@ -104,13 +171,14 @@ describe("selectHostBadges", () => {
serverId: "beta",
label: "Beta",
color: "none",
icon: "server",
showLabel: true,
});
});
it("keeps an icon-only host in the map without its label", () => {
const badges = selectHostBadges({
hosts: [host("alpha", "Alpha", { color: "teal", badgeDisplay: "icon" })],
hosts: [host("alpha", "Alpha", { color: "teal", icon: "mini", badgeDisplay: "icon" })],
localServerId: null,
enabled: true,
});
@@ -118,6 +186,7 @@ describe("selectHostBadges", () => {
serverId: "alpha",
label: "Alpha",
color: "teal",
icon: "mini",
showLabel: false,
});
});
@@ -150,4 +219,21 @@ describe("selectHostBadges", () => {
});
expect(badges.size).toBe(0);
});
it("applies daemon-detected machine kind for auto icons while respecting explicit overrides", () => {
const badges = selectHostBadges({
hosts: [
host("alpha", "Alpha"),
host("beta", "Beta", { color: "sky", icon: "workstation", badgeDisplay: "name" }),
],
localServerId: null,
detectedMachineKindByServerId: new Map([
["alpha", "laptop"],
["beta", "cloud"],
]),
enabled: true,
});
expect(badges.get("alpha")?.icon).toBe("laptop");
expect(badges.get("beta")?.icon).toBe("workstation");
});
});
+65 -4
View File
@@ -6,25 +6,69 @@ export type HostColor = "none" | IdentityColorName;
export const HOST_COLORS: readonly HostColor[] = ["none", ...IDENTITY_COLOR_NAMES];
export const HOST_ICONS = [
"server",
"laptop",
"desktop",
"mini",
"workstation",
"cloud",
"container",
"board",
"terminal",
] as const;
export type HostIcon = (typeof HOST_ICONS)[number];
export const DEFAULT_HOST_ICON: HostIcon = "server";
const HOST_ICON_SET = new Set<string>(HOST_ICONS);
export function normalizeDetectedHostIcon(value: string | null | undefined): HostIcon | null {
const trimmed = value?.trim();
if (trimmed && HOST_ICON_SET.has(trimmed)) {
return trimmed as HostIcon;
}
return null;
}
export type HostBadgeDisplay = "name" | "icon" | "hidden";
export const HOST_BADGE_DISPLAYS: readonly HostBadgeDisplay[] = ["name", "icon", "hidden"];
/**
* Per-device host presentation. `badgeDisplay` is null while the user has not chosen,
* because the default differs by host (local hides, remote shows) and local-ness is only
* knowable from a desktop-only async query — never at parse time.
* Per-device host presentation.
* - `icon` is omitted while untouched ("Auto") so existing records stay byte-for-byte compatible
* with older builds whose stored appearance schema is strict. An unknown icon string written by
* a newer build is preserved on disk and falls back at render time via `resolveHostIcon`.
* - `badgeDisplay` is null while untouched so runtime defaults apply (hidden for local / name for
* remote) without baking runtime facts at parse time.
*/
export interface HostAppearance {
color: HostColor;
icon?: string;
badgeDisplay: HostBadgeDisplay | null;
}
export const HostAppearanceSchema: z.ZodType<HostAppearance> = z.strictObject({
const StoredHostAppearanceSchema = z.strictObject({
color: z.enum(["none", ...IDENTITY_COLOR_NAMES]),
// Optional loose string on disk so untouched hosts stay readable after a downgrade and an icon
// added by a newer build survives read/write instead of being dropped or overwritten.
icon: z.string().nullable().optional(),
badgeDisplay: z.enum(["name", "icon", "hidden"]).nullable(),
});
export const HostAppearanceSchema = StoredHostAppearanceSchema.transform(
(value): HostAppearance => {
const icon = value.icon?.trim();
return {
color: value.color,
...(icon ? { icon } : {}),
badgeDisplay: value.badgeDisplay,
};
},
);
export function defaultHostAppearance(): HostAppearance {
return { color: "none", badgeDisplay: null };
}
@@ -34,6 +78,17 @@ export function normalizeStoredHostAppearance(value: unknown): HostAppearance {
return result.success ? result.data : defaultHostAppearance();
}
export function resolveHostIcon(input: {
appearance: HostAppearance;
detectedMachineKind?: string | null;
}): HostIcon {
return (
normalizeDetectedHostIcon(input.appearance.icon) ??
normalizeDetectedHostIcon(input.detectedMachineKind) ??
DEFAULT_HOST_ICON
);
}
export function resolveHostBadgeDisplay(input: {
appearance: HostAppearance;
isLocalHost: boolean;
@@ -52,6 +107,7 @@ export interface HostBadgeModel {
serverId: string;
label: string;
color: HostColor;
icon: HostIcon;
showLabel: boolean;
}
@@ -66,6 +122,7 @@ export function selectHostBadges(input: {
hosts: readonly HostAppearanceSource[];
localServerId: string | null;
localHostResolutionPending?: boolean;
detectedMachineKindByServerId?: ReadonlyMap<string, string | null>;
enabled: boolean;
}): ReadonlyMap<string, HostBadgeModel> {
const badges = new Map<string, HostBadgeModel>();
@@ -85,6 +142,10 @@ export function selectHostBadges(input: {
serverId: host.serverId,
label: host.label.trim() || host.serverId,
color: host.appearance.color,
icon: resolveHostIcon({
appearance: host.appearance,
detectedMachineKind: input.detectedMachineKindByServerId?.get(host.serverId) ?? null,
}),
showLabel: display === "name",
});
}
@@ -0,0 +1,134 @@
import { describe, expect, it } from "vitest";
import {
describeActiveConnection,
describeHostConnection,
formatConnectionEndpoint,
isTailscaleEndpoint,
} from "./connection-display";
describe("isTailscaleEndpoint", () => {
it("recognizes MagicDNS .ts.net hostnames with or without ports", () => {
expect(isTailscaleEndpoint("mac-mini.tail123.ts.net:6767")).toBe(true);
expect(isTailscaleEndpoint("Mac-Mini.Tail123.TS.NET:443")).toBe(true);
expect(isTailscaleEndpoint("devbox.tailnet.ts.net")).toBe(true);
expect(isTailscaleEndpoint(".ts.net")).toBe(false);
});
it("recognizes Tailscale IPv4 CGNAT (100.64.0.0/10) and IPv6 ULA addresses", () => {
expect(isTailscaleEndpoint("100.64.0.1:6767")).toBe(true);
expect(isTailscaleEndpoint("100.100.42.9:6767")).toBe(true);
expect(isTailscaleEndpoint("100.127.255.254:6767")).toBe(true);
expect(isTailscaleEndpoint("100.63.255.255:6767")).toBe(false);
expect(isTailscaleEndpoint("100.128.0.1:6767")).toBe(false);
expect(isTailscaleEndpoint("[fd7a:115c:a1e0::1]:6767")).toBe(true);
});
it("does not misclassify LAN, localhost, or ordinary domains", () => {
expect(isTailscaleEndpoint("localhost:6767")).toBe(false);
expect(isTailscaleEndpoint("127.0.0.1:6767")).toBe(false);
expect(isTailscaleEndpoint("192.168.1.25:6767")).toBe(false);
expect(isTailscaleEndpoint("relay.paseo.sh:443")).toBe(false);
expect(isTailscaleEndpoint("not-ts.net.example.com:6767")).toBe(false);
});
});
describe("describeActiveConnection", () => {
it("describes local socket and pipe connections without exposing paths", () => {
expect(
describeActiveConnection({
type: "directSocket",
endpoint: "/tmp/paseo.sock",
display: "socket",
}),
).toEqual({ kind: "local" });
expect(
describeActiveConnection({
type: "directPipe",
endpoint: "\\\\.\\pipe\\paseo",
display: "pipe",
}),
).toEqual({ kind: "local" });
});
it("describes loopback TCP on the local host as local, and remote loopback as direct", () => {
const loopback = {
type: "directTcp",
endpoint: "localhost:6767",
display: "localhost:6767",
} as const;
expect(describeActiveConnection(loopback, { isLocalHost: true })).toEqual({ kind: "local" });
expect(describeActiveConnection(loopback, { isLocalHost: false })).toEqual({
kind: "direct",
endpoint: "localhost:6767",
});
});
it("strips standard web ports on relay, tailscale, and direct connections", () => {
expect(
describeActiveConnection({ type: "relay", endpoint: "relay.paseo.sh:443", display: "relay" }),
).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" });
expect(
describeActiveConnection({
type: "directTcp",
endpoint: "mac-mini.tail123.ts.net:6767",
display: "mac-mini.tail123.ts.net:6767",
}),
).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" });
expect(
describeActiveConnection({
type: "directTcp",
endpoint: "devbox.example.com:443",
display: "devbox.example.com:443",
}),
).toEqual({ kind: "direct", endpoint: "devbox.example.com" });
});
it("preserves SSH and routed targets", () => {
expect(
describeActiveConnection({
type: "remoteSsh",
endpoint: "mo@workstation",
display: "mo@workstation",
}),
).toEqual({ kind: "ssh", endpoint: "mo@workstation" });
expect(
describeActiveConnection({
type: "routed",
endpoint: "srv_origin",
display: "via srv_origin",
}),
).toEqual({ kind: "routed", endpoint: "srv_origin" });
});
it("strips default HTTP/HTTPS ports only", () => {
expect(formatConnectionEndpoint("relay.paseo.sh:443")).toBe("relay.paseo.sh");
expect(formatConnectionEndpoint("example.com:80")).toBe("example.com");
expect(formatConnectionEndpoint("127.0.0.1:6767")).toBe("127.0.0.1:6767");
});
it("describes configured host connections before an active connection is online", () => {
expect(
describeHostConnection({
id: "direct:mac-mini.tail123.ts.net:6767",
type: "directTcp",
endpoint: "mac-mini.tail123.ts.net:6767",
}),
).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" });
expect(
describeHostConnection({
id: "relay:wss:relay.paseo.sh:443",
type: "relay",
relayEndpoint: "relay.paseo.sh:443",
useTls: true,
daemonPublicKeyB64: "key",
}),
).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" });
expect(
describeHostConnection({
id: "ssh:mo%40workstation::",
type: "remoteSsh",
host: "mo@workstation",
}),
).toEqual({ kind: "ssh", endpoint: "mo@workstation" });
});
});
@@ -0,0 +1,120 @@
import type { ActiveConnection } from "@/runtime/host-runtime";
import type { HostConnection } from "@/types/host-connection";
export type HostConnectionKind = "local" | "relay" | "tailscale" | "ssh" | "direct" | "routed";
export interface HostConnectionDisplay {
kind: HostConnectionKind;
/** Address shown beside the connection kind. Omitted for local transports. */
endpoint?: string;
}
// Standard secure/plain web ports carry no information in the host display, so
// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept.
export function formatConnectionEndpoint(endpoint: string): string {
return endpoint.replace(/:(?:443|80)$/, "");
}
function extractEndpointHost(endpoint: string): string {
const trimmed = endpoint.trim().toLowerCase();
if (!trimmed) return "";
const withoutScheme = trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\//, "");
const authority = withoutScheme.split("/")[0] ?? "";
const hostPort = authority.includes("@")
? authority.slice(authority.lastIndexOf("@") + 1)
: authority;
if (hostPort.startsWith("[")) {
const closeBracket = hostPort.indexOf("]");
return closeBracket > 1 ? hostPort.slice(1, closeBracket) : hostPort;
}
const firstColon = hostPort.indexOf(":");
const lastColon = hostPort.lastIndexOf(":");
if (firstColon !== -1 && firstColon === lastColon) {
return hostPort.slice(0, firstColon);
}
return hostPort;
}
function isTailscaleIpv4(host: string): boolean {
const parts = host.split(".");
if (parts.length !== 4) return false;
const octets = parts.map((part) => (/^\d+$/.test(part) ? Number(part) : Number.NaN));
if (octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {
return false;
}
// Tailscale assigns addresses from the RFC 6598 CGNAT range 100.64.0.0/10.
return octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127;
}
function isTailscaleIpv6(host: string): boolean {
return host.startsWith("fd7a:115c:a1e0:");
}
export function isTailscaleEndpoint(endpoint: string): boolean {
const host = extractEndpointHost(endpoint);
if (!host) return false;
if (host.endsWith(".ts.net") && host.length > ".ts.net".length) {
return true;
}
return isTailscaleIpv4(host) || isTailscaleIpv6(host);
}
export function isLoopbackEndpoint(endpoint: string): boolean {
const host = extractEndpointHost(endpoint);
return host === "localhost" || host === "127.0.0.1" || host === "::1";
}
export function describeActiveConnection(
connection: ActiveConnection,
options?: { isLocalHost?: boolean },
): HostConnectionDisplay {
switch (connection.type) {
case "directSocket":
case "directPipe":
return { kind: "local" };
case "relay":
return { kind: "relay", endpoint: formatConnectionEndpoint(connection.endpoint) };
case "remoteSsh":
return { kind: "ssh", endpoint: connection.endpoint };
case "routed":
return { kind: "routed", endpoint: connection.endpoint };
case "directTcp": {
if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) {
return { kind: "local" };
}
if (isTailscaleEndpoint(connection.endpoint)) {
return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
}
}
export function describeHostConnection(
connection: HostConnection,
options?: { isLocalHost?: boolean },
): HostConnectionDisplay {
switch (connection.type) {
case "directSocket":
case "directPipe":
return { kind: "local" };
case "relay":
return { kind: "relay", endpoint: formatConnectionEndpoint(connection.relayEndpoint) };
case "remoteSsh":
return { kind: "ssh", endpoint: connection.host };
case "routed":
return { kind: "routed", endpoint: connection.originServerId };
case "directTcp": {
if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) {
return { kind: "local" };
}
if (isTailscaleEndpoint(connection.endpoint)) {
return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
}
}
+8 -29
View File
@@ -1,9 +1,8 @@
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Server } from "lucide-react-native";
import { HOST_COLORS, type HostBadgeModel, type HostColor } from "@/hosts/appearance";
import { StyleSheet } from "react-native-unistyles";
import { type HostBadgeModel, type HostColor } from "@/hosts/appearance";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { identityForeground } from "@/styles/identity-colors";
import type { Theme } from "@/styles/theme";
/**
* The glyph size the badge draws at. Rows that place the badge alongside their own glyphs
@@ -11,30 +10,9 @@ import type { Theme } from "@/styles/theme";
*/
export const HOST_BADGE_ICON_SIZE = 12;
const ThemedServer = withUnistyles(Server);
const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
// One stable mapping per host color for the life of the module — a fresh `uniProps` identity
// on every render makes withUnistyles re-subscribe each pass. The scheme is read inside the
// mapping rather than baked in, so a theme change repaints the glyph without a React render.
//
// Glyph and label share one color, so a badge reads as one object rather than a colored icon
// with an unrelated grey word beside it.
const HOST_ICON_MAPPINGS: Record<HostColor, (theme: Theme) => { color: string }> = (() => {
const byColor = {} as Record<HostColor, (theme: Theme) => { color: string }>;
for (const color of HOST_COLORS) {
byColor[color] =
color === "none"
? mutedMapping
: (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) });
}
return byColor;
})();
/**
* Which machine something lives on, drawn the same way everywhere it appears: a server glyph
* and, when the host is configured to show one, its name — both in the host's identity color.
* Which machine something lives on, drawn the same way everywhere it appears: the host's device
* glyph and, when the host is configured to show one, its name — both in the host's identity color.
*
* A hostname is the least interesting thing on any line that carries it and the only one whose
* length nobody chose, so the badge yields space before its neighbours rather than alongside
@@ -47,10 +25,11 @@ export function HostBadge({ badge }: { badge: HostBadgeModel }) {
testID={`host-badge-${badge.serverId}`}
accessibilityLabel={badge.label}
>
<ThemedServer
<HostIconGlyph
icon={badge.icon}
color={badge.color}
size={HOST_BADGE_ICON_SIZE}
style={styles.icon}
uniProps={HOST_ICON_MAPPINGS[badge.color]}
/>
{badge.showLabel ? (
<Text style={[styles.label, labelColorStyle(badge.color)]} numberOfLines={1}>
+66 -27
View File
@@ -7,14 +7,16 @@ import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
} from "@/components/ui/text-input";
import { Server } from "lucide-react-native";
import { create } from "zustand";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { HostStatusDotSlot } from "@/components/hosts/host-picker";
import { HostStatusDot } from "@/components/host-status-dot";
import { isWeb } from "@/constants/platform";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { resolveHostIcon } from "@/hosts/appearance";
import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon";
import { OverlayLayerProvider, useGlobalOverlayLayer } from "@/lib/overlay-root";
import { useHosts } from "@/runtime/host-runtime";
import { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { orderHostsLocalFirst, type HostProfile } from "@/types/host-connection";
type HostFilter = (host: HostProfile) => boolean;
@@ -101,36 +103,52 @@ function HostChooserRow({
active: boolean;
onChooseHost: (serverId: string) => void;
}) {
const { theme } = useUnistyles();
const detectedMachineKind = useSessionStore(
(state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null,
);
const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind });
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const handlePress = useCallback(() => onChooseHost(host.serverId), [host.serverId, onChooseHost]);
const rowStyle = useCallback(
({ hovered = false, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
({ pressed }: PressableStateCallbackType) => [
styles.row,
(active || hovered || pressed) && styles.rowActive,
],
[active],
[active, hovered],
);
return (
<Pressable
accessibilityRole="button"
onPress={handlePress}
style={rowStyle}
testID={`host-chooser-row-${host.serverId}`}
>
<View style={styles.rowIconSlot}>
<HostStatusDotSlot serverId={host.serverId} />
</View>
<View style={styles.rowText}>
<Text style={styles.rowTitle} numberOfLines={1}>
{host.label}
</Text>
<Text style={styles.rowSubtitle} numberOfLines={1}>
{host.serverId}
</Text>
</View>
<Server size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
</Pressable>
<View onPointerEnter={handlePointerEnter} onPointerLeave={handlePointerLeave}>
<Pressable
accessibilityRole="button"
onPress={handlePress}
style={rowStyle}
testID={`host-chooser-row-${host.serverId}`}
>
<View style={styles.rowIconSlot}>
<HostStatusDot serverId={host.serverId} />
</View>
<View style={styles.rowText}>
<View style={styles.rowHeader}>
<HostIconGlyph
icon={resolvedIcon}
color={host.appearance.color}
size={14}
style={styles.rowGlyph}
/>
<Text style={styles.rowTitle} numberOfLines={1}>
{host.label}
</Text>
</View>
<HostConnectionLine serverId={host.serverId} />
</View>
<View style={styles.rowTrailing}>
<HostLatencyLabel serverId={host.serverId} />
</View>
</Pressable>
</View>
);
}
@@ -161,6 +179,7 @@ export function HostChooserModal() {
useEffect(() => {
if (!request) return;
getHostRuntimeStore().refreshActiveLatencies(request.serverIds);
inputRef.current?.replaceText("");
setQuery("");
setActiveIndex(0);
@@ -328,7 +347,7 @@ const styles = StyleSheet.create((theme) => ({
},
row: {
flexDirection: "row",
alignItems: "center",
alignItems: "flex-start",
gap: theme.spacing[3],
minHeight: 56,
paddingHorizontal: theme.spacing[4],
@@ -337,19 +356,39 @@ const styles = StyleSheet.create((theme) => ({
rowActive: {
backgroundColor: theme.colors.surface1,
},
rowTrailing: {
flexDirection: "row",
alignItems: "center",
height: 20,
flexShrink: 0,
},
rowIconSlot: {
width: 18,
width: 16,
height: 20,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
rowText: {
flex: 1,
minWidth: 0,
gap: theme.spacing[1],
},
rowHeader: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
rowGlyph: {
flexShrink: 0,
},
rowTitle: {
flex: 1,
minWidth: 0,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
lineHeight: 20,
},
rowSubtitle: {
color: theme.colors.foregroundMuted,
@@ -0,0 +1,77 @@
import type { ReactElement } from "react";
import type { StyleProp, ViewStyle } from "react-native";
import {
Cloud,
Computer,
Container,
Cpu,
Laptop,
Monitor,
PcCase,
Server,
Terminal,
} from "lucide-react-native";
import { withUnistyles } from "react-native-unistyles";
import { DEFAULT_HOST_ICON, HOST_COLORS, type HostColor, type HostIcon } from "@/hosts/appearance";
import { identityForeground } from "@/styles/identity-colors";
import type { Theme } from "@/styles/theme";
const ThemedServer = withUnistyles(Server);
const ThemedLaptop = withUnistyles(Laptop);
const ThemedMonitor = withUnistyles(Monitor);
const ThemedComputer = withUnistyles(Computer);
const ThemedPcCase = withUnistyles(PcCase);
const ThemedCloud = withUnistyles(Cloud);
const ThemedContainer = withUnistyles(Container);
const ThemedCpu = withUnistyles(Cpu);
const ThemedTerminal = withUnistyles(Terminal);
const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
// One stable uniProps mapping per host color for the life of the module — a fresh identity on
// every render makes withUnistyles re-subscribe each pass. Reading `theme.colorScheme` inside the
// mapping keeps theme switches off React's render path.
const HOST_ICON_MAPPINGS: Record<HostColor, (theme: Theme) => { color: string }> = (() => {
const byColor = {} as Record<HostColor, (theme: Theme) => { color: string }>;
for (const color of HOST_COLORS) {
byColor[color] =
color === "none"
? mutedMapping
: (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) });
}
return byColor;
})();
export function HostIconGlyph({
icon = DEFAULT_HOST_ICON,
color = "none",
size = 16,
style,
}: {
icon?: HostIcon;
color?: HostColor;
size?: number;
style?: StyleProp<ViewStyle>;
}): ReactElement {
const uniProps = HOST_ICON_MAPPINGS[color];
switch (icon) {
case "laptop":
return <ThemedLaptop size={size} style={style} uniProps={uniProps} />;
case "desktop":
return <ThemedMonitor size={size} style={style} uniProps={uniProps} />;
case "mini":
return <ThemedComputer size={size} style={style} uniProps={uniProps} />;
case "workstation":
return <ThemedPcCase size={size} style={style} uniProps={uniProps} />;
case "cloud":
return <ThemedCloud size={size} style={style} uniProps={uniProps} />;
case "container":
return <ThemedContainer size={size} style={style} uniProps={uniProps} />;
case "board":
return <ThemedCpu size={size} style={style} uniProps={uniProps} />;
case "terminal":
return <ThemedTerminal size={size} style={style} uniProps={uniProps} />;
case "server":
return <ThemedServer size={size} style={style} uniProps={uniProps} />;
}
}
+215
View File
@@ -0,0 +1,215 @@
import { useMemo, type ReactElement } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { Globe, Monitor, Network, Terminal, Waypoints } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { TailscaleIcon } from "@/components/icons/tailscale-icon";
import {
describeActiveConnection,
describeHostConnection,
type HostConnectionKind,
} from "@/hosts/connection-display";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
import type { Theme } from "@/styles/theme";
import type { HostProfile } from "@/types/host-connection";
import { formatLatency } from "@/utils/latency";
export { HostIconGlyph };
const CONNECTION_GLYPH_SIZE = 11;
const ThemedMonitor = withUnistyles(Monitor);
const ThemedTerminal = withUnistyles(Terminal);
const ThemedGlobe = withUnistyles(Globe);
const ThemedNetwork = withUnistyles(Network);
const ThemedWaypoints = withUnistyles(Waypoints);
const ThemedTailscale = withUnistyles(TailscaleIcon);
const extraMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundExtraMuted });
function ConnectionKindGlyph({ kind }: { kind: HostConnectionKind }): ReactElement {
switch (kind) {
case "local":
return (
<ThemedMonitor
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "relay":
return (
<ThemedGlobe
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "tailscale":
return <ThemedTailscale size={CONNECTION_GLYPH_SIZE} uniProps={extraMutedMapping} />;
case "ssh":
return (
<ThemedTerminal
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "routed":
return (
<ThemedWaypoints
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "direct":
return (
<ThemedNetwork
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
}
}
function resolvePreferredConnection(host: HostProfile | undefined) {
if (!host || host.connections.length === 0) return null;
if (host.preferredConnectionId) {
const preferred = host.connections.find(
(connection) => connection.id === host.preferredConnectionId,
);
if (preferred) return preferred;
}
return host.connections[0] ?? null;
}
export function HostConnectionLine({ serverId }: { serverId: string }): ReactElement | null {
const { t } = useTranslation();
const snapshot = useHostRuntimeSnapshot(serverId);
const localServerId = useLocalDaemonServerId();
const hosts = useHosts();
const activeConnection = snapshot?.activeConnection ?? null;
const hostProfile = useMemo(
() => hosts.find((candidate) => candidate.serverId === serverId),
[hosts, serverId],
);
const fallbackConnection = useMemo(
() => (activeConnection ? null : resolvePreferredConnection(hostProfile)),
[activeConnection, hostProfile],
);
const described = useMemo(() => {
const options = { isLocalHost: serverId === localServerId };
if (activeConnection) {
return describeActiveConnection(activeConnection, options);
}
if (fallbackConnection) {
return describeHostConnection(fallbackConnection, options);
}
return null;
}, [activeConnection, fallbackConnection, localServerId, serverId]);
if (!described) {
return null;
}
const endpoint =
described.kind === "routed" && described.endpoint
? (hosts.find((host) => host.serverId === described.endpoint)?.label ?? described.endpoint)
: described.endpoint;
return (
<View style={styles.connectionRow}>
<View style={styles.linkIconSlot}>
<ConnectionKindGlyph kind={described.kind} />
</View>
<Text style={styles.connectionKind} numberOfLines={1}>
{t(`settings.host.connectionKinds.${described.kind}`)}
</Text>
{endpoint ? (
<Text style={styles.connectionEndpoint} numberOfLines={1}>
{endpoint}
</Text>
) : null}
</View>
);
}
export function HostLatencyLabel({ serverId }: { serverId: string }): ReactElement | null {
const { t } = useTranslation();
const snapshot = useHostRuntimeSnapshot(serverId);
const status = snapshot?.connectionStatus;
const activeConnectionId = snapshot?.activeConnectionId;
const activeProbe = activeConnectionId
? snapshot?.probeByConnectionId.get(activeConnectionId)
: undefined;
const latencyMs =
status === "online" && activeProbe?.status === "available" ? activeProbe.latencyMs : null;
if (latencyMs !== null) {
return (
<Text style={styles.latency} numberOfLines={1}>
{formatLatency(latencyMs)}
</Text>
);
}
if (status === "offline" || status === "error") {
return (
<Text style={styles.statusText} numberOfLines={1}>
{t("common.connectionStatus.offline")}
</Text>
);
}
return null;
}
const styles = StyleSheet.create((theme) => ({
connectionRow: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
// Matches the 14px host icon width on the row above so connection text aligns on the same rail.
linkIconSlot: {
width: 14,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
linkIcon: {
flexShrink: 0,
},
connectionKind: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundMuted,
flexShrink: 0,
},
connectionEndpoint: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundExtraMuted,
flexShrink: 1,
minWidth: 0,
},
latency: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundMuted,
fontVariant: ["tabular-nums"],
flexShrink: 0,
},
statusText: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundExtraMuted,
flexShrink: 0,
},
}));
+24 -11
View File
@@ -1,11 +1,13 @@
import { useMemo } from "react";
import { useShallow } from "zustand/react/shallow";
import { useHosts } from "@/runtime/host-runtime";
import { useLocalDaemonServerId, useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon";
import { selectHostBadges, type HostBadgeModel } from "@/hosts/appearance";
import { useSessionStore } from "@/stores/session-store";
/**
* Every host's badge, resolved from the three things that decide one: the host registry, which
* host is local, and each host's own appearance. `enabled` is the caller's own "off" — a surface
* Every host's badge, resolved from the host registry, local-host detection, daemon-reported
* machine kind, and each host's own appearance. `enabled` is the caller's own "off" — a surface
* that has its own reason to hide badges passes false rather than filtering the result, so the
* per-host setting stays the only thing that decides name vs icon vs hidden.
*/
@@ -17,14 +19,25 @@ export function useHostBadges({
const hosts = useHosts();
const localServerId = useLocalDaemonServerId();
const localDaemon = useLocalDaemonServerIdState();
return useMemo(
() =>
selectHostBadges({
hosts,
localServerId,
localHostResolutionPending: localDaemon.status !== "resolved",
enabled,
}),
[hosts, localDaemon.status, localServerId, enabled],
const detectedMachineKinds = useSessionStore(
useShallow((state) => {
const result: Record<string, string | null> = {};
for (const host of hosts) {
result[host.serverId] = state.sessions[host.serverId]?.serverInfo?.machineKind ?? null;
}
return result;
}),
);
return useMemo(() => {
const detectedMachineKindByServerId = new Map<string, string | null>(
Object.entries(detectedMachineKinds),
);
return selectHostBadges({
hosts,
localServerId,
localHostResolutionPending: localDaemon.status !== "resolved",
detectedMachineKindByServerId,
enabled,
});
}, [hosts, localDaemon.status, localServerId, detectedMachineKinds, enabled]);
}
+25
View File
@@ -2841,6 +2841,23 @@ export const ar: TranslationResources = {
name: {
label: "الاسم",
},
icon: {
label: "الأيقونة",
accessibilityLabel: "الأيقونة، {{value}}",
auto: "تلقائي",
autoDetected: "تلقائي ({{icon}})",
options: {
server: "خادم",
laptop: "حاسوب محمول",
desktop: "حاسوب مكتبي",
mini: "حاسوب مصغّر",
workstation: "محطة عمل",
cloud: "سحابي",
container: "حاوية",
board: "حاسوب أحادي اللوحة",
terminal: "طرفية",
},
},
color: {
label: "اللون",
accessibilityLabel: "اللون، {{value}}",
@@ -2877,6 +2894,14 @@ export const ar: TranslationResources = {
local: "محلي",
remoteSsh: "SSH عن بُعد",
},
connectionKinds: {
local: "محلي",
relay: "تتابع",
tailscale: "Tailscale",
ssh: "SSH",
direct: "مباشر",
routed: "عبر",
},
connections: {
title: "اتصالات",
removeTitle: "إزالة الاتصال",
+25
View File
@@ -2936,6 +2936,23 @@ export const en = {
name: {
label: "Name",
},
icon: {
label: "Icon",
accessibilityLabel: "Icon, {{value}}",
auto: "Auto",
autoDetected: "Auto ({{icon}})",
options: {
server: "Server",
laptop: "Laptop",
desktop: "Desktop",
mini: "Mini",
workstation: "Workstation",
cloud: "Cloud",
container: "Container",
board: "Single-board PC",
terminal: "Terminal",
},
},
color: {
label: "Color",
accessibilityLabel: "Color, {{value}}",
@@ -2972,6 +2989,14 @@ export const en = {
local: "Local",
remoteSsh: "Remote SSH",
},
connectionKinds: {
local: "Local",
relay: "Relay",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direct",
routed: "Via",
},
connections: {
title: "Connections",
removeTitle: "Remove connection",
+25
View File
@@ -2865,6 +2865,23 @@ export const es: TranslationResources = {
name: {
label: "Nombre",
},
icon: {
label: "Icono",
accessibilityLabel: "Icono, {{value}}",
auto: "Automático",
autoDetected: "Automático ({{icon}})",
options: {
server: "Servidor",
laptop: "Portátil",
desktop: "Escritorio",
mini: "Mini",
workstation: "Estación de trabajo",
cloud: "Nube",
container: "Contenedor",
board: "PC de placa única",
terminal: "Terminal",
},
},
color: {
label: "Color",
accessibilityLabel: "Color, {{value}}",
@@ -2901,6 +2918,14 @@ export const es: TranslationResources = {
local: "Local",
remoteSsh: "SSH remoto",
},
connectionKinds: {
local: "Local",
relay: "Relé",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Directo",
routed: "Vía",
},
connections: {
title: "Conexiones",
removeTitle: "Quitar conexión",
+25
View File
@@ -2867,6 +2867,23 @@ export const fr: TranslationResources = {
name: {
label: "Nom",
},
icon: {
label: "Icône",
accessibilityLabel: "Icône, {{value}}",
auto: "Auto",
autoDetected: "Auto ({{icon}})",
options: {
server: "Serveur",
laptop: "Portable",
desktop: "Bureau",
mini: "Mini",
workstation: "Station de travail",
cloud: "Cloud",
container: "Conteneur",
board: "Ordinateur monocarte",
terminal: "Terminal",
},
},
color: {
label: "Couleur",
accessibilityLabel: "Couleur, {{value}}",
@@ -2903,6 +2920,14 @@ export const fr: TranslationResources = {
local: "Local",
remoteSsh: "SSH distant",
},
connectionKinds: {
local: "Local",
relay: "Relais",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direct",
routed: "Via",
},
connections: {
title: "Connexions",
removeTitle: "Supprimer la connexion",
+25
View File
@@ -2833,6 +2833,23 @@ export const ja: TranslationResources = {
name: {
label: "名前",
},
icon: {
label: "アイコン",
accessibilityLabel: "アイコン、{{value}}",
auto: "自動",
autoDetected: "自動 ({{icon}})",
options: {
server: "サーバー",
laptop: "ノート PC",
desktop: "デスクトップ",
mini: "ミニ PC",
workstation: "ワークステーション",
cloud: "クラウド",
container: "コンテナ",
board: "シングルボード PC",
terminal: "ターミナル",
},
},
color: {
label: "色",
accessibilityLabel: "色、{{value}}",
@@ -2869,6 +2886,14 @@ export const ja: TranslationResources = {
local: "ローカル",
remoteSsh: "リモート SSH",
},
connectionKinds: {
local: "ローカル",
relay: "リレー",
tailscale: "Tailscale",
ssh: "SSH",
direct: "ダイレクト",
routed: "経由",
},
connections: {
title: "接続",
removeTitle: "接続を削除",
+25
View File
@@ -2819,6 +2819,23 @@ export const ko: TranslationResources = {
name: {
label: "이름",
},
icon: {
label: "아이콘",
accessibilityLabel: "아이콘, {{value}}",
auto: "자동",
autoDetected: "자동 ({{icon}})",
options: {
server: "서버",
laptop: "노트북",
desktop: "데스크톱",
mini: "미니",
workstation: "워크스테이션",
cloud: "클라우드",
container: "컨테이너",
board: "싱글보드 PC",
terminal: "터미널",
},
},
color: {
label: "색상",
accessibilityLabel: "색상, {{value}}",
@@ -2855,6 +2872,14 @@ export const ko: TranslationResources = {
local: "로컬",
remoteSsh: "원격 SSH",
},
connectionKinds: {
local: "로컬",
relay: "릴레이",
tailscale: "Tailscale",
ssh: "SSH",
direct: "직접 연결",
routed: "경유",
},
connections: {
title: "연결",
removeTitle: "연결 제거",
+25
View File
@@ -2846,6 +2846,23 @@ export const ptBR: TranslationResources = {
name: {
label: "Nome",
},
icon: {
label: "Ícone",
accessibilityLabel: "Ícone, {{value}}",
auto: "Automático",
autoDetected: "Automático ({{icon}})",
options: {
server: "Servidor",
laptop: "Notebook",
desktop: "Desktop",
mini: "Mini",
workstation: "Estação de trabalho",
cloud: "Nuvem",
container: "Contêiner",
board: "PC de placa única",
terminal: "Terminal",
},
},
color: {
label: "Cor",
accessibilityLabel: "Cor, {{value}}",
@@ -2882,6 +2899,14 @@ export const ptBR: TranslationResources = {
local: "Local",
remoteSsh: "SSH remoto",
},
connectionKinds: {
local: "Local",
relay: "Relay",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direto",
routed: "Via",
},
connections: {
title: "Conexões",
removeTitle: "Remover conexão",
+25
View File
@@ -2854,6 +2854,23 @@ export const ru: TranslationResources = {
name: {
label: "Имя",
},
icon: {
label: "Значок",
accessibilityLabel: "Значок, {{value}}",
auto: "Авто",
autoDetected: "Авто ({{icon}})",
options: {
server: "Сервер",
laptop: "Ноутбук",
desktop: "Компьютер",
mini: "Мини-ПК",
workstation: "Рабочая станция",
cloud: "Облако",
container: "Контейнер",
board: "Одноплатный ПК",
terminal: "Терминал",
},
},
color: {
label: "Цвет",
accessibilityLabel: "Цвет, {{value}}",
@@ -2890,6 +2907,14 @@ export const ru: TranslationResources = {
local: "Локальный",
remoteSsh: "Удалённый SSH",
},
connectionKinds: {
local: "Локальный",
relay: "Ретранслятор",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Прямой",
routed: "Через",
},
connections: {
title: "Подключения",
removeTitle: "Удалить подключение",
+25
View File
@@ -2775,6 +2775,23 @@ export const zhCN: TranslationResources = {
name: {
label: "名称",
},
icon: {
label: "图标",
accessibilityLabel: "图标,{{value}}",
auto: "自动",
autoDetected: "自动 ({{icon}})",
options: {
server: "服务器",
laptop: "笔记本电脑",
desktop: "台式机",
mini: "迷你主机",
workstation: "工作站",
cloud: "云端",
container: "容器",
board: "单板机",
terminal: "终端",
},
},
color: {
label: "颜色",
accessibilityLabel: "颜色,{{value}}",
@@ -2811,6 +2828,14 @@ export const zhCN: TranslationResources = {
local: "本地",
remoteSsh: "远程 SSH",
},
connectionKinds: {
local: "本地",
relay: "中继",
tailscale: "Tailscale",
ssh: "SSH",
direct: "直连",
routed: "经由",
},
connections: {
title: "连接",
removeTitle: "移除连接",
+175 -6
View File
@@ -1114,6 +1114,106 @@ describe("HostRuntimeController", () => {
expect(activeClient.latencyMeasurements()).toEqual([]);
});
it("measures active latency on demand when an online host has no sample yet", async () => {
useHostRuntimeClock();
const initialClient = new FakeDaemonClient();
initialClient.setConnectionState({ status: "connected" });
initialClient.ping = async () => ({ rttMs: 14 });
const controller = new HostRuntimeController({
host: makeHost({
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
preferredConnectionId: "direct:lan:6767",
}),
deps: makeDeps({ "direct:lan:6767": 14 }, []),
});
await controller.start({
autoProbe: false,
initialConnection: {
connectionId: "direct:lan:6767",
existingClient: initialClient as unknown as DaemonClient,
},
});
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "pending",
latencyMs: null,
});
await controller.refreshActiveLatency();
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
});
it("keeps an on-demand active latency sample when a slower probe on another connection finishes", async () => {
useHostRuntimeClock();
const initialClient = new FakeDaemonClient();
initialClient.setConnectionState({ status: "connected" });
initialClient.ping = async () => ({ rttMs: 14 });
const relayProbeStarted = createDeferred<void>();
const slowRelayProbe = createDeferred<{
client: DaemonClient;
serverId: string;
hostname: string | null;
}>();
const relayClient = new FakeDaemonClient();
relayClient.setConnectionState({ status: "connected" });
relayClient.ping = async () => ({ rttMs: 90 });
const controller = new HostRuntimeController({
host: makeHost(),
deps: {
...makeDeps({}, []),
connectToDaemon: async ({ host, connection }) => {
if (connection.id === "relay:relay.paseo.sh:443") {
relayProbeStarted.resolve();
return slowRelayProbe.promise;
}
return {
client: initialClient as unknown as DaemonClient,
serverId: host.serverId,
hostname: null,
};
},
},
});
// Startup runs the first probe cycle immediately; wait until the slower relay probe is in
// flight, then measure active latency on demand before the relay probe resolves.
const startPromise = controller.start({
autoProbe: false,
initialConnection: {
connectionId: "direct:lan:6767",
existingClient: initialClient as unknown as DaemonClient,
},
});
await relayProbeStarted.promise;
await controller.refreshActiveLatency();
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
slowRelayProbe.resolve({
client: relayClient as unknown as DaemonClient,
serverId: "srv_test",
hostname: null,
});
await startPromise;
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
expect(controller.getSnapshot().probeByConnectionId.get("relay:relay.paseo.sh:443")).toEqual({
status: "available",
latencyMs: 90,
});
});
it.each([12, null])(
"falls back to relay when the direct client disconnects with heartbeat RTT %s",
async (heartbeatRtt) => {
@@ -3366,7 +3466,11 @@ describe("HostRuntimeStore", () => {
store.boot();
await registryLoaded;
expect(store.getHosts()[0]?.appearance).toEqual({ color: "none", badgeDisplay: null });
expect(store.getHosts()[0]?.appearance).toEqual({
color: "none",
badgeDisplay: null,
});
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
store.syncHosts([]);
});
@@ -3391,6 +3495,7 @@ describe("HostRuntimeStore", () => {
const updated = store.getHosts()[0];
expect(updated?.appearance).toEqual({ color: "teal", badgeDisplay: null });
expect("icon" in (updated?.appearance ?? {})).toBe(false);
expect(updated?.updatedAt).not.toBe(host.updatedAt);
const persisted = await storage.getItem("@paseo:daemon-registry");
@@ -3402,10 +3507,60 @@ describe("HostRuntimeStore", () => {
store.syncHosts([]);
});
it("records a chosen host icon and resets to auto without disturbing color or badge display", async () => {
const host = makeHost({
serverId: "srv_appearance",
appearance: { color: "violet", badgeDisplay: "icon" },
});
const storage = createMemoryHostRuntimeStorage();
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
await storage.setItem("@paseo:e2e", "1");
const store = createAppearanceStore(storage);
const registryLoaded = onceHostListMatches(store, () => store.isHostRegistryLoaded());
store.boot();
await registryLoaded;
const hostListChanged = onceHostListMatches(
store,
() => store.getHosts()[0]?.appearance.icon === "laptop",
);
await store.setHostIcon("srv_appearance", "laptop");
await hostListChanged;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "violet",
icon: "laptop",
badgeDisplay: "icon",
});
const persisted = await storage.getItem("@paseo:daemon-registry");
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
color: "violet",
icon: "laptop",
badgeDisplay: "icon",
});
const resetToAuto = onceHostListMatches(
store,
() => store.getHosts()[0]?.appearance.icon === undefined,
);
await store.setHostIcon("srv_appearance", null);
await resetToAuto;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "violet",
badgeDisplay: "icon",
});
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
store.syncHosts([]);
});
it("records a chosen badge display without disturbing the color", async () => {
const host = makeHost({
serverId: "srv_appearance",
appearance: { color: "amber", badgeDisplay: null },
appearance: { color: "amber", icon: "server", badgeDisplay: null },
});
const storage = createMemoryHostRuntimeStorage();
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
@@ -3423,11 +3578,16 @@ describe("HostRuntimeStore", () => {
await store.setHostBadgeDisplay("srv_appearance", "icon");
await hostListChanged;
expect(store.getHosts()[0]?.appearance).toEqual({ color: "amber", badgeDisplay: "icon" });
expect(store.getHosts()[0]?.appearance).toEqual({
color: "amber",
icon: "server",
badgeDisplay: "icon",
});
const persisted = await storage.getItem("@paseo:daemon-registry");
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
color: "amber",
icon: "server",
badgeDisplay: "icon",
});
@@ -3476,16 +3636,25 @@ describe("HostRuntimeStore", () => {
};
const color = store.setHostColor("srv_appearance", "teal");
const icon = store.setHostIcon("srv_appearance", "mini");
const display = store.setHostBadgeDisplay("srv_appearance", "icon");
await Promise.resolve();
expect(writeCount).toBe(1);
firstWrite.resolve();
await Promise.all([color, display]);
await Promise.all([color, icon, display]);
expect(store.getHosts()[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
expect(store.getHosts()[0]?.appearance).toEqual({
color: "teal",
icon: "mini",
badgeDisplay: "icon",
});
const persistedHosts = JSON.parse((await storage.getItem("@paseo:daemon-registry")) ?? "[]");
expect(persistedHosts[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
expect(persistedHosts[0]?.appearance).toEqual({
color: "teal",
icon: "mini",
badgeDisplay: "icon",
});
store.syncHosts([]);
});
+91 -15
View File
@@ -28,7 +28,12 @@ import {
type HostProfile,
type UnreadableHostEntries,
} from "@/types/host-connection";
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
import {
defaultHostAppearance,
type HostBadgeDisplay,
type HostColor,
type HostIcon,
} from "@/hosts/appearance";
import {
buildDaemonWebSocketUrl,
buildRelayWebSocketUrl,
@@ -945,6 +950,56 @@ export class HostRuntimeController {
await this.switchToConnection(input);
}
/**
* Measures the active connection's round-trip time when the host is online and no sample has
* landed yet (for example right after connecting, before the first heartbeat interval fires).
*/
async refreshActiveLatency(): Promise<void> {
const activeConnectionId = this.snapshot.activeConnectionId;
const activeClient = this.snapshot.client;
if (
this.snapshot.connectionStatus !== "online" ||
!activeConnectionId ||
!activeClient ||
activeClient.getConnectionState().status !== "connected"
) {
return;
}
const existing = this.snapshot.probeByConnectionId.get(activeConnectionId);
if (existing?.status === "available") {
return;
}
const existingRtt = activeClient.getLastLivenessRttMs();
if (existingRtt !== null) {
this.recordActiveLatencySample(activeConnectionId, existingRtt);
return;
}
try {
const rttMs = await activeClient.measureLatency({ timeoutMs: 3_000 });
if (
this.snapshot.activeConnectionId !== activeConnectionId ||
this.snapshot.client !== activeClient ||
this.snapshot.connectionStatus !== "online"
) {
return;
}
this.recordActiveLatencySample(activeConnectionId, rttMs);
} catch {
// A latency probe never drives teardown; the heartbeat owns liveness.
}
}
private setConnectionProbe(connectionId: string, probe: ConnectionProbeState): void {
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
probeByConnectionId.set(connectionId, probe);
this.updateSnapshot({ probeByConnectionId });
}
private recordActiveLatencySample(connectionId: string, rttMs: number): void {
this.recordActiveRttSample(rttMs, performance.now());
this.setConnectionProbe(connectionId, { status: "available", latencyMs: rttMs });
}
async runProbeCycleNow(): Promise<void> {
if (this.probeCycleInFlight) {
return this.probeCycleInFlight;
@@ -1001,30 +1056,32 @@ export class HostRuntimeController {
return;
}
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
const initialProbes = new Map(this.snapshot.probeByConnectionId);
for (const connection of connectionsToProbe) {
this.connectionLastProbedAt.set(connection.id, performance.now());
const existingProbe = probeByConnectionId.get(connection.id);
const existingProbe = initialProbes.get(connection.id);
const shouldPreserveActiveLatency =
isOnline && connection.id === activeConnectionId && existingProbe?.status === "available";
if (!shouldPreserveActiveLatency) {
probeByConnectionId.set(connection.id, {
initialProbes.set(connection.id, {
status: "pending",
latencyMs: null,
});
}
}
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
this.updateSnapshot({ probeByConnectionId: initialProbes });
let remaining = connectionsToProbe.length;
let probeAuthFailure: "password_required" | "incorrect_password" | null = null;
let activationLock: Promise<void> | null = null;
const publishProbeState = (): void => {
// Merge each connection result into the live snapshot map so a slow probe on another
// connection cannot overwrite a fresher sample (e.g. from refreshActiveLatency) on the active one.
const publishConnectionProbe = (connectionId: string, probe: ConnectionProbeState): void => {
if (!this.isCurrentProbeRequest(requestVersion)) {
return;
}
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
this.setConnectionProbe(connectionId, probe);
};
const maybeActivateFirstAvailable = async (
@@ -1053,6 +1110,7 @@ export class HostRuntimeController {
return;
}
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
const currentActiveConnectionId = this.snapshot.activeConnectionId;
if (currentActiveConnectionId) {
this.reconcileActiveProbeWithClient(currentActiveConnectionId, probeByConnectionId);
@@ -1208,11 +1266,10 @@ export class HostRuntimeController {
if (activeClient) {
if (activeClient.getConnectionState().status !== "connected") {
probeByConnectionId.set(connection.id, {
publishConnectionProbe(connection.id, {
status: "unavailable",
latencyMs: null,
});
publishProbeState();
return;
}
const rttMs = activeClient.getLastLivenessRttMs();
@@ -1221,11 +1278,10 @@ export class HostRuntimeController {
}
if (rttMs !== null) {
this.recordActiveRttSample(rttMs, performance.now());
probeByConnectionId.set(connection.id, {
publishConnectionProbe(connection.id, {
status: "available",
latencyMs: rttMs,
});
publishProbeState();
}
return;
}
@@ -1235,11 +1291,10 @@ export class HostRuntimeController {
return;
}
probeByConnectionId.set(connection.id, {
publishConnectionProbe(connection.id, {
status: "available",
latencyMs: rttMs,
});
publishProbeState();
} catch (error) {
if (this.isCurrentProbeRequest(requestVersion)) {
const authFailure = getConnectionAuthFailureReason(error);
@@ -1247,11 +1302,10 @@ export class HostRuntimeController {
this.authRejectedConnectionIds.add(connection.id);
probeAuthFailure = authFailure;
}
probeByConnectionId.set(connection.id, {
publishConnectionProbe(connection.id, {
status: "unavailable",
latencyMs: null,
});
publishProbeState();
}
} finally {
if (connectedClient && shouldCloseClient) {
@@ -2436,6 +2490,16 @@ export class HostRuntimeStore {
}));
}
async setHostIcon(serverId: string, icon: HostIcon | null): Promise<void> {
await this.updateHostAppearance(serverId, (host) => {
const { icon: _previousIcon, ...rest } = host.appearance;
return {
...host,
appearance: icon ? { ...rest, icon } : rest,
};
});
}
async setHostBadgeDisplay(serverId: string, badgeDisplay: HostBadgeDisplay): Promise<void> {
await this.updateHostAppearance(serverId, (host) => ({
...host,
@@ -2443,6 +2507,16 @@ export class HostRuntimeStore {
}));
}
refreshActiveLatencies(serverIds?: readonly string[]): void {
const targets = serverIds ?? this.hosts.map((host) => host.serverId);
for (const serverId of targets) {
const controller = this.controllers.get(serverId);
if (controller) {
void controller.refreshActiveLatency();
}
}
}
private updateHostAppearance(
serverId: string,
apply: (host: HostProfile) => HostProfile,
@@ -3296,6 +3370,7 @@ export interface HostMutations {
beginLinkPairing: () => LinkPairing;
renameHost: (serverId: string, label: string) => Promise<void>;
setHostColor: (serverId: string, color: HostColor) => Promise<void>;
setHostIcon: (serverId: string, icon: HostIcon | null) => Promise<void>;
setHostBadgeDisplay: (serverId: string, badgeDisplay: HostBadgeDisplay) => Promise<void>;
removeHost: (serverId: string) => Promise<void>;
removeConnection: (serverId: string, connectionId: string) => Promise<void>;
@@ -3311,6 +3386,7 @@ export function useHostMutations(): HostMutations {
beginLinkPairing: () => store.beginLinkPairing(),
renameHost: (serverId, label) => store.renameHost(serverId, label),
setHostColor: (serverId, color) => store.setHostColor(serverId, color),
setHostIcon: (serverId, icon) => store.setHostIcon(serverId, icon),
setHostBadgeDisplay: (serverId, badgeDisplay) =>
store.setHostBadgeDisplay(serverId, badgeDisplay),
removeHost: (serverId) => store.removeHost(serverId),
@@ -438,7 +438,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
searchable={false}
title={t("newWorkspace.fields.host")}
desktopPlacement="bottom-start"
desktopMinWidth={200}
desktopMinWidth={320}
hostOptionTestID={hostOptionTestID}
>
<FieldTrigger
+1 -1
View File
@@ -907,7 +907,7 @@ function HostPicker({
showActiveConnection
searchable={false}
title={t("settings.hostPicker.switchHost")}
desktopMinWidth={240}
desktopMinWidth={328}
addHostTestID="settings-add-host"
hostOptionTestID={hostOptionTestID}
>
@@ -4,7 +4,12 @@ import { useTranslation } from "react-i18next";
import { Pressable, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Pencil } from "lucide-react-native";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
import { AdaptiveRenameModal } from "@/components/rename-modal";
import { WorkspaceMetaRow } from "@/components/sidebar/workspace-meta-row";
@@ -13,12 +18,18 @@ import { SettingsSection } from "@/components/settings/headings/settings-section
import {
HOST_BADGE_DISPLAYS,
HOST_COLORS,
HOST_ICONS,
normalizeDetectedHostIcon,
resolveHostBadgeDisplay,
resolveHostIcon,
type HostBadgeDisplay,
type HostColor,
type HostIcon,
} from "@/hosts/appearance";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon";
import { useHostMutations } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { identityColor } from "@/styles/identity-colors";
import { settingsStyles } from "@/styles/settings";
import { ICON_SIZE, type Theme } from "@/styles/theme";
@@ -76,10 +87,112 @@ function colorLabel(t: TFunction, color: HostColor): string {
return t(`settings.host.appearance.color.options.${color}`);
}
function iconLabel(t: TFunction, icon: HostIcon): string {
return t(`settings.host.appearance.icon.options.${icon}`);
}
function autoIconLabel(t: TFunction, detectedIcon: HostIcon | null): string {
if (detectedIcon) {
return t("settings.host.appearance.icon.autoDetected", {
icon: iconLabel(t, detectedIcon),
});
}
return t("settings.host.appearance.icon.auto");
}
function badgeDisplayLabel(t: TFunction, display: HostBadgeDisplay): string {
return t(`settings.host.appearance.badge.options.${display}`);
}
function IconMenuItem({
icon,
color,
selected,
onChange,
}: {
icon: HostIcon;
color: HostColor;
selected: boolean;
onChange: (icon: HostIcon | null) => void;
}) {
const { t } = useTranslation();
const handleSelect = useCallback(() => onChange(icon), [icon, onChange]);
const leading = useMemo(
() => <HostIconGlyph icon={icon} color={color} size={ICON_SIZE.sm} />,
[color, icon],
);
return (
<DropdownMenuItem selected={selected} onSelect={handleSelect} leading={leading}>
{iconLabel(t, icon)}
</DropdownMenuItem>
);
}
function IconRow({
icon,
detectedIcon,
resolvedIcon,
color,
onChange,
}: {
icon: HostIcon | null;
detectedIcon: HostIcon | null;
resolvedIcon: HostIcon;
color: HostColor;
onChange: (icon: HostIcon | null) => void;
}) {
const { t } = useTranslation();
const autoLabel = autoIconLabel(t, detectedIcon);
const selectedLabel = icon ? iconLabel(t, icon) : autoLabel;
const handleSelectAuto = useCallback(() => onChange(null), [onChange]);
const triggerLeading = useMemo(
() => <HostIconGlyph icon={resolvedIcon} color={color} size={ICON_SIZE.sm} />,
[color, resolvedIcon],
);
const autoLeading = useMemo(
() => <HostIconGlyph icon={detectedIcon ?? "server"} color={color} size={ICON_SIZE.sm} />,
[color, detectedIcon],
);
return (
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.host.appearance.icon.label")}</Text>
</View>
<DropdownMenu>
<DropdownTrigger
testID="host-appearance-icon"
accessibilityRole="button"
accessibilityLabel={t("settings.host.appearance.icon.accessibilityLabel", {
value: selectedLabel,
})}
leading={triggerLeading}
>
{selectedLabel}
</DropdownTrigger>
<DropdownMenuContent side="bottom" align="end" width={220}>
<DropdownMenuItem
selected={icon === null}
onSelect={handleSelectAuto}
leading={autoLeading}
>
{autoLabel}
</DropdownMenuItem>
<DropdownMenuSeparator />
{HOST_ICONS.map((option) => (
<IconMenuItem
key={option}
icon={option}
color={color}
selected={option === icon}
onChange={onChange}
/>
))}
</DropdownMenuContent>
</DropdownMenu>
</View>
);
}
function ColorSwatch({ color }: { color: HostColor }) {
const swatchStyle = useMemo(
() => [styles.swatch, color === "none" ? null : { backgroundColor: identityColor(color) }],
@@ -205,9 +318,11 @@ function BadgeDisplayMenuItem({
*/
function BadgePreview({
host,
resolvedIcon,
badgeDisplay,
}: {
host: HostProfile;
resolvedIcon: HostIcon;
badgeDisplay: HostBadgeDisplay;
}) {
const { t } = useTranslation();
@@ -219,9 +334,10 @@ function BadgePreview({
serverId: host.serverId,
label: host.label,
color: host.appearance.color,
icon: resolvedIcon,
showLabel: badgeDisplay === "name",
},
[badgeDisplay, host.serverId, host.label, host.appearance.color],
[badgeDisplay, host.serverId, host.label, host.appearance.color, resolvedIcon],
);
// The real sidebar row, so the preview can't drift from what the setting actually does.
return (
@@ -244,8 +360,14 @@ function BadgePreview({
export function HostAppearanceSection({ host }: { host: HostProfile }) {
const { t } = useTranslation();
const toast = useToast();
const { setHostColor, setHostBadgeDisplay } = useHostMutations();
const { setHostColor, setHostIcon, setHostBadgeDisplay } = useHostMutations();
const localDaemon = useLocalDaemonServerIdState();
const detectedMachineKind = useSessionStore(
(state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null,
);
const detectedIcon = normalizeDetectedHostIcon(detectedMachineKind);
const selectedIcon = normalizeDetectedHostIcon(host.appearance.icon);
const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind });
const isLocalHost = localDaemon.status === "resolved" && localDaemon.serverId === host.serverId;
const badgeDisplay = resolveHostBadgeDisplay({
appearance: host.appearance,
@@ -263,6 +385,16 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) {
},
[host.serverId, setHostColor, t, toast],
);
const handleIconChange = useCallback(
async (icon: HostIcon | null) => {
try {
await setHostIcon(host.serverId, icon);
} catch {
toast.error(t("errors.unableToSave"));
}
},
[host.serverId, setHostIcon, t, toast],
);
const handleBadgeDisplayChange = useCallback(
async (next: HostBadgeDisplay) => {
try {
@@ -288,11 +420,18 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) {
<HostRenameButton host={host} />
</View>
</View>
<IconRow
icon={selectedIcon}
detectedIcon={detectedIcon}
resolvedIcon={resolvedIcon}
color={host.appearance.color}
onChange={handleIconChange}
/>
<ColorRow color={host.appearance.color} onChange={handleColorChange} />
{badgeDisplay === null ? null : (
<>
<BadgeDisplayRow badgeDisplay={badgeDisplay} onChange={handleBadgeDisplayChange} />
<BadgePreview host={host} badgeDisplay={badgeDisplay} />
<BadgePreview host={host} resolvedIcon={resolvedIcon} badgeDisplay={badgeDisplay} />
</>
)}
</View>
+9
View File
@@ -293,6 +293,7 @@ export interface DaemonServerInfo {
serverId: string;
hostname: string | null;
version: string | null;
machineKind?: string | null;
desktopManaged?: boolean;
capabilities?: ServerCapabilities;
features?: ServerInfoStatusPayload["features"];
@@ -303,6 +304,7 @@ export function toDaemonServerInfo(serverInfo: ServerInfoStatusPayload): DaemonS
serverId: serverInfo.serverId,
hostname: serverInfo.hostname ?? null,
version: serverInfo.version ?? null,
...(serverInfo.machineKind !== undefined ? { machineKind: serverInfo.machineKind } : {}),
...(serverInfo.desktopManaged !== undefined
? { desktopManaged: serverInfo.desktopManaged }
: {}),
@@ -786,6 +788,7 @@ function isSessionServerInfoUnchanged(input: {
currentServerInfo: SessionState["serverInfo"] | undefined;
nextHostname: string | null;
nextVersion: string | null;
nextMachineKind: string | null;
nextDesktopManaged: boolean | undefined;
nextCapabilities: ServerCapabilities | undefined;
nextFeatures: ServerInfoStatusPayload["features"] | undefined;
@@ -795,16 +798,19 @@ function isSessionServerInfoUnchanged(input: {
currentServerInfo,
nextHostname,
nextVersion,
nextMachineKind,
nextDesktopManaged,
nextCapabilities,
nextFeatures,
} = input;
const prevHostname = currentServerInfo?.hostname?.trim() || null;
const prevVersion = currentServerInfo?.version?.trim() || null;
const prevMachineKind = currentServerInfo?.machineKind?.trim() || null;
return (
currentServerInfo?.serverId === input.nextServerId &&
prevHostname === nextHostname &&
prevVersion === nextVersion &&
prevMachineKind === nextMachineKind &&
currentServerInfo?.desktopManaged === nextDesktopManaged &&
areServerCapabilitiesEqual(currentServerInfo?.capabilities, nextCapabilities) &&
areServerInfoFeaturesEqual(currentServerInfo?.features, nextFeatures)
@@ -942,6 +948,7 @@ export const useSessionStore = create<SessionStore>()(
const nextHostname = info.hostname?.trim() || null;
const nextVersion = info.version?.trim() || null;
const nextMachineKind = info.machineKind?.trim() || null;
const nextDesktopManaged = info.desktopManaged;
const nextCapabilities = info.capabilities;
const nextFeatures = info.features;
@@ -951,6 +958,7 @@ export const useSessionStore = create<SessionStore>()(
currentServerInfo: session.serverInfo,
nextHostname,
nextVersion,
nextMachineKind,
nextDesktopManaged,
nextCapabilities,
nextFeatures,
@@ -970,6 +978,7 @@ export const useSessionStore = create<SessionStore>()(
serverId: info.serverId,
hostname: nextHostname,
version: nextVersion,
...(nextMachineKind !== null ? { machineKind: nextMachineKind } : {}),
...(nextDesktopManaged !== undefined
? { desktopManaged: nextDesktopManaged }
: {}),
+27 -5
View File
@@ -152,7 +152,7 @@ describe("normalizeStoredHostProfile", () => {
});
});
it("gives a host stored before appearance existed the default appearance", () => {
it("gives a host stored before appearance existed the default appearance without an icon key", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_old",
connections: [
@@ -161,18 +161,35 @@ describe("normalizeStoredHostProfile", () => {
});
expect(profile?.appearance).toEqual({ color: "none", badgeDisplay: null });
expect(profile && "icon" in profile.appearance).toBe(false);
});
it("loads a stored appearance the user chose", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_new",
appearance: { color: "teal", badgeDisplay: "icon" },
appearance: { color: "teal", icon: "laptop", badgeDisplay: "icon" },
connections: [
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
],
});
expect(profile?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
expect(profile?.appearance).toEqual({ color: "teal", icon: "laptop", badgeDisplay: "icon" });
});
it("preserves an unknown stored icon intact without dropping the saved host", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_future_icon",
appearance: { color: "violet", icon: "future-device", badgeDisplay: "name" },
connections: [
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
],
});
expect(profile?.appearance).toEqual({
color: "violet",
icon: "future-device",
badgeDisplay: "name",
});
});
it("normalizes stored Remote SSH connection parameters", () => {
@@ -340,12 +357,13 @@ describe("upsertHostConnectionInProfiles", () => {
});
expect(profile.appearance).toEqual({ color: "none", badgeDisplay: null });
expect("icon" in profile.appearance).toBe(false);
});
it("keeps the appearance the user chose when the host reconnects", () => {
const existing: HostProfile = {
...makeHost("srv_known"),
appearance: { color: "amber", badgeDisplay: "hidden" },
appearance: { color: "amber", icon: "workstation", badgeDisplay: "hidden" },
connections: [],
};
@@ -355,7 +373,11 @@ describe("upsertHostConnectionInProfiles", () => {
connection,
});
expect(profile.appearance).toEqual({ color: "amber", badgeDisplay: "hidden" });
expect(profile.appearance).toEqual({
color: "amber",
icon: "workstation",
badgeDisplay: "hidden",
});
});
it("replaces a direct connection when its settings change", () => {
@@ -143,3 +143,11 @@ export const Minimize = StubIcon;
export const Rows2 = StubIcon;
export const Gauge = StubIcon;
export const GripVertical = StubIcon;
export const Cloud = StubIcon;
export const Computer = StubIcon;
export const Container = StubIcon;
export const Cpu = StubIcon;
export const Laptop = StubIcon;
export const Network = StubIcon;
export const PcCase = StubIcon;
export const Waypoints = StubIcon;
+14 -1
View File
@@ -754,13 +754,14 @@ class DaemonClientSession {
private readonly daemon = new FakeDaemon();
private readonly client: DaemonClient;
constructor() {
constructor(options: { livenessHeartbeat?: boolean } = {}) {
this.client = new DaemonClient({
url: "ws://test",
clientId: "clsk_heartbeat_test",
logger: noopLogger,
reconnect: { enabled: false },
transportFactory: () => this.daemon.transport,
...options,
});
clients.push(this.client);
}
@@ -3395,6 +3396,18 @@ test("starts pinging one interval after connecting and holds the cadence", async
expect(session.pingTimestamps()).toEqual(["10s", "20s", "30s"]);
});
test("a client with the liveness heartbeat off never pings on its own", async () => {
useHeartbeatClock();
const session = new DaemonClientSession({ livenessHeartbeat: false });
session.daemonAnswersPingsAfter("fast");
await session.connect();
await session.advance(60_000);
expect(session.state()).toEqual({ status: "connected" });
expect(session.pingTimestamps()).toEqual([]);
});
test("stops pinging once the connection is gone", async () => {
useHeartbeatClock();
const session = new DaemonClientSession();
+12 -1
View File
@@ -473,6 +473,13 @@ export interface DaemonClientConfig {
runtimeMetricsWindowMs?: number;
trace?: DaemonClientTrace;
capabilities?: Partial<Record<ClientCapability, unknown>>;
/**
* Ping the daemon every 10 s and reconnect after missed replies (default true). Turn it off
* only where the transport reports its own loss (a plugin's IPC channel, an in-process
* channel): there a ping cannot find a dead link the channel would not, and it costs both
* processes a wakeup per client every 10 s.
*/
livenessHeartbeat?: boolean;
}
export interface DaemonClientTrace {
@@ -2742,7 +2749,11 @@ export class DaemonClient {
}
private scheduleNextLivenessHeartbeat(): void {
if (this.connectionState.status !== "connected" || this.livenessHeartbeatTimer) {
if (
this.config.livenessHeartbeat === false ||
this.connectionState.status !== "connected" ||
this.livenessHeartbeatTimer
) {
return;
}
this.livenessHeartbeatTimer = setTimeout(() => {
@@ -5,7 +5,6 @@ import {
ClientSideConnection,
CLIENT_METHODS,
PROTOCOL_VERSION,
RequestError,
ndJsonStream,
type Client,
type AgentCapabilities,
@@ -650,7 +649,7 @@ class AcpRuntime {
}
this.modes = response.modes ?? null;
this.configOptions = response.configOptions ?? [];
await this.applyInitialConfig(input.config, Boolean(nativeSessionId));
await this.applyInitialConfig(input.config);
const sessionCapabilities = connectionCapabilities.filter(
(capability) =>
capability !== "session.configure" ||
@@ -1080,10 +1079,7 @@ class AcpRuntime {
}
}
private async applyInitialConfig(
config: ProviderSessionConfig,
resuming: boolean,
): Promise<void> {
private async applyInitialConfig(config: ProviderSessionConfig): Promise<void> {
const requested: AcpConfigChange[] = [];
if (config.model) requested.push({ target: "model", value: config.model });
const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
@@ -1101,9 +1097,7 @@ class AcpRuntime {
for (const [id, value] of Object.entries(settings)) {
requested.push({ target: "setting", id, value });
}
for (const change of this.inAgentOrder(requested)) {
await this.applyConfigChange(change, resuming);
}
for (const change of this.inAgentOrder(requested)) await this.applyConfigChange(change);
}
private offersMode(mode: string | undefined): boolean {
@@ -1144,7 +1138,7 @@ class AcpRuntime {
return modeOption(this.configOptions)?.id;
}
private async applyConfigChange(change: AcpConfigChange, resuming = false): Promise<void> {
private async applyConfigChange(change: AcpConfigChange): Promise<void> {
const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
if (
change.target === "mode" &&
@@ -1173,40 +1167,9 @@ class AcpRuntime {
return;
}
}
if (resuming && change.target === "model" && change.value) {
await this.restoreNativeModel(change.value);
return;
}
await this.applyNativeConfigChange(change);
}
private async restoreNativeModel(requested: string): Promise<void> {
try {
await this.applyNativeConfigChange({ target: "model", value: requested });
} catch (error) {
if (!(error instanceof RequestError) || error.code !== -32602) throw error;
const option = modelOption(this.configOptions);
const current = selectedValue(option);
if (
!current ||
current === requested ||
selectOptions(option).some(({ value }) => value === requested)
) {
throw error;
}
this.emit({
type: "session.notice",
sessionId: this.options.boundarySessionId,
notice: {
id: "acp:saved-model-unavailable",
severity: "warning",
title: "Saved model unavailable",
description: `The provider no longer offers ${requested}. This chat reopened with ${current}.`,
},
});
}
}
private async applyNativeConfigChange(change: AcpConfigChange): Promise<void> {
if (change.target === "mode" && this.modes && !modeOption(this.configOptions)) {
if (!change.value) {
+17 -4
View File
@@ -3970,6 +3970,9 @@ export const ServerInfoStatusPayloadSchema = z
serverId: z.string().trim().min(1),
hostname: ServerInfoHostnameSchema.optional(),
version: ServerInfoVersionSchema.optional(),
// Best-effort machine kind detected by the daemon (e.g. "laptop", "mini", "cloud").
// Loose string so unknown future kinds stay parseable across versions.
machineKind: z.string().nullable().optional(),
// Authenticated producer for host registration ownership, separate from admission authority.
sourceId: z.string().optional(),
// COMPAT(sessionPermissions): optional while clients support older daemons.
@@ -5824,10 +5827,20 @@ const CheckoutStatusCommonSchema = z.object({
// as when the clone keeps no remote-tracking ref for the upstream). Absent from daemons that
// predate it, which report all but "tracked" as a null upstreamRef.
upstreamState: z.enum(["tracked", "none", "gone", "unknown"]).optional(),
// The remote a first push publishes currentBranch to, when the daemon can confirm git would
// push the branch there too. Null when there is no such remote, as when origin is missing or
// git is set to push the branch to another remote (branch.<name>.pushRemote,
// remote.pushDefault). Absent from daemons that predate it.
// The remote Pull fetches currentBranch from, as git names it: the remote of the branch's
// configured upstream, which is not necessarily origin, or "." when the upstream is a local
// branch. Null when the branch has no upstream. Absent from daemons that predate it, which
// pull only in checkouts that have origin (hasRemote).
pullRemote: z.string().nullable().optional(),
// The remote Push sends currentBranch to, resolved as the daemon's push resolves it. It is not
// necessarily origin. Null when Push has nowhere to send the branch, as when it has no upstream
// and origin is missing, or git is set to push it to another remote (branch.<name>.pushRemote,
// remote.pushDefault). Absent from daemons that predate it, which push only in checkouts that
// have origin (hasRemote).
pushRemote: z.string().nullable().optional(),
// "origin" when Push sends currentBranch to origin, and null otherwise. Clients that predate
// pushRemote read it to offer a first push; newer clients read pushRemote instead. Absent from
// daemons that predate it.
firstPushRemote: z.string().nullable().optional(),
forgeWeb: ForgeWebSchema.optional(),
});
@@ -72,6 +72,41 @@ test("base selection RPCs are correlated while older checkout and branch message
expect(WorkspaceBaseBranchSetResponseSchema.parse(response)).toEqual(response);
});
test("checkout status stays valid without pull and push remotes and retains them when sent", () => {
const olderDaemonPayload = {
cwd: "/repo",
requestId: "status",
error: null,
isGit: true,
isPaseoOwnedWorktree: false,
repoRoot: "/repo",
currentBranch: "main",
isDirty: false,
baseRef: "main",
aheadBehind: null,
aheadOfOrigin: 1,
behindOfOrigin: 2,
hasRemote: false,
remoteUrl: null,
upstreamRef: "refs/remotes/doras-mono/main",
upstreamState: "tracked",
firstPushRemote: null,
};
const parse = (payload: Record<string, unknown>) =>
CheckoutStatusResponseSchema.parse({ type: "checkout_status_response", payload }).payload;
const older = parse(olderDaemonPayload);
expect(older.pullRemote).toBeUndefined();
expect(older.pushRemote).toBeUndefined();
expect(
parse({ ...olderDaemonPayload, pullRemote: "doras-mono", pushRemote: "doras-mono" }),
).toMatchObject({ pullRemote: "doras-mono", pushRemote: "doras-mono" });
expect(parse({ ...olderDaemonPayload, pullRemote: "upstream", pushRemote: null })).toMatchObject({
pullRemote: "upstream",
pushRemote: null,
});
});
test("terminal listings accept older rows and retain new per-terminal directories", () => {
const response = {
type: "list_terminals_response",
@@ -201,6 +236,34 @@ describe("wire schema compatibility", () => {
});
});
test("server info accepts optional machineKind and older clients drop it cleanly", () => {
const legacyServerInfo = z.object({
status: z.literal("server_info"),
serverId: z.string().trim().min(1),
hostname: z.string().nullable().optional(),
version: z.string().nullable().optional(),
});
const withKind = {
status: "server_info",
serverId: "macbook-server",
hostname: "mbp.local",
version: "0.9.5",
machineKind: "laptop",
};
expect(ServerInfoStatusPayloadSchema.parse(withKind).machineKind).toBe("laptop");
expect(
ServerInfoStatusPayloadSchema.parse({ ...withKind, machineKind: null }).machineKind,
).toBeNull();
expect(
ServerInfoStatusPayloadSchema.parse({
status: "server_info",
serverId: "older-server",
}).machineKind,
).toBeUndefined();
expect(legacyServerInfo.parse(withKind)).not.toHaveProperty("machineKind");
});
test("assistant timeline message ids are optional on the wire", () => {
expect(
AgentTimelineItemPayloadSchema.parse({
@@ -74,6 +74,19 @@ describe("findExecutable", () => {
await expect(findExecutable("foo")).resolves.toBe(executable);
});
test("ignores relative PATH entries when resolving a bare command name", async () => {
const dir = makeTempDir();
const previousCwd = process.cwd();
writeExecutable(path.join(dir, "rel-only-cmd"), "#!/bin/sh\necho 0.1\n");
process.chdir(dir);
try {
process.env.PATH = [".", originalEnv.PATH].filter(Boolean).join(path.delimiter);
await expect(findExecutable("rel-only-cmd")).resolves.toBeNull();
} finally {
process.chdir(previousCwd);
}
});
});
describe.runIf(isPlatform("win32"))("Windows", () => {
@@ -142,6 +155,21 @@ describe("findExecutable", () => {
process.env.LOCALAPPDATA = originalLocalAppData;
}
});
test("ignores commands in the current working directory when not explicitly on PATH", async () => {
const repoDir = makeTempDir();
const emptyPathDir = makeTempDir();
const previousCwd = process.cwd();
process.env.PATHEXT = [".EXE", ".CMD"].join(path.delimiter);
writeExecutable(path.join(repoDir, "cwd-only-cmd.cmd"), "@echo off\r\necho 0.1\r\n");
process.chdir(repoDir);
try {
process.env.PATH = emptyPathDir;
await expect(findExecutable("cwd-only-cmd")).resolves.toBeNull();
} finally {
process.chdir(previousCwd);
}
});
});
test("returns an invokable absolute path", async () => {
@@ -1,5 +1,5 @@
import { existsSync } from "node:fs";
import { delimiter, resolve } from "node:path";
import { delimiter, dirname, isAbsolute, resolve } from "node:path";
import type { ProcessEnvRecord } from "../server/paseo-env.js";
import { execCommand } from "../utils/spawn.js";
import which from "which";
@@ -11,11 +11,46 @@ function hasPathSeparator(value: string): boolean {
return value.includes("/") || value.includes("\\");
}
async function enumerateCandidates(name: string, env?: ProcessEnvRecord): Promise<string[]> {
if (process.platform !== "win32" && existsSync("/usr/bin/which")) {
return enumerateCandidatesViaSystemWhich(name, env);
function stripWindowsPathQuotes(entry: string): string {
return process.platform === "win32" &&
entry.length >= 2 &&
entry.startsWith('"') &&
entry.endsWith('"')
? entry.slice(1, -1)
: entry;
}
function normalizeDirectory(dir: string): string {
const resolved = resolve(dir);
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
}
function extractAbsolutePathDirs(rawPath: string | undefined): string[] {
if (!rawPath) {
return [];
}
return enumerateCandidatesViaLibrary(name, env);
return rawPath
.split(delimiter)
.map(stripWindowsPathQuotes)
.filter((entry) => entry.length > 0 && isAbsolute(entry));
}
async function enumerateCandidates(name: string, env?: ProcessEnvRecord): Promise<string[]> {
const rawPath = env?.PATH !== undefined ? env.PATH : process.env.PATH;
const absolutePathDirs = extractAbsolutePathDirs(rawPath);
if (absolutePathDirs.length === 0) {
return [];
}
const filteredEnv: ProcessEnvRecord = {
...(env ?? process.env),
PATH: absolutePathDirs.join(delimiter),
};
const allowedDirs = new Set(absolutePathDirs.map(normalizeDirectory));
const candidates =
process.platform !== "win32" && existsSync("/usr/bin/which")
? await enumerateCandidatesViaSystemWhich(name, filteredEnv)
: await enumerateCandidatesViaLibrary(name, filteredEnv);
return candidates.filter((candidate) => allowedDirs.has(normalizeDirectory(dirname(candidate))));
}
async function enumerateCandidatesViaSystemWhich(
@@ -1,7 +1,29 @@
import { expect, test } from "vitest";
import { execFileSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pino from "pino";
import { afterEach, expect, test, vi } from "vitest";
import type { AgentManagerEvent, AgentSubscriber } from "./agent-manager.js";
import { registerAgentAutoArchive } from "./create-agent-lifecycle-dispatch.js";
import type { ForgeService } from "../../services/forge-service.js";
import { createWorktree } from "../../utils/worktree.js";
import { WorkspaceAutomationBlockedError } from "../workspace-automation-gate.js";
import type { WorkspaceGitService } from "../workspace-git-service.js";
import type { PersistedWorkspaceRecord } from "../workspace-registry.js";
import type { AgentManager, AgentManagerEvent, AgentSubscriber } from "./agent-manager.js";
import type { AgentStorage } from "./agent-storage.js";
import {
CreateAgentLifecycleDispatch,
registerAgentAutoArchive,
} from "./create-agent-lifecycle-dispatch.js";
const cleanupPaths: string[] = [];
afterEach(() => {
for (const target of cleanupPaths.splice(0)) {
rmSync(target, { recursive: true, force: true });
}
});
class AgentLifecycleEvents {
private readonly listeners = new Set<AgentSubscriber>();
@@ -25,6 +47,109 @@ class AgentLifecycleEvents {
}
}
async function createUntrustedWorktreeFixture(slug: string, markerName: string) {
const tempDir = mkdtempSync(path.join(tmpdir(), "lifecycle-dispatch-"));
cleanupPaths.push(tempDir);
const repoDir = path.join(tempDir, "repo");
const paseoHome = path.join(tempDir, ".paseo");
mkdirSync(repoDir, { recursive: true });
execFileSync("git", ["init", "-b", "main"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
cwd: repoDir,
stdio: "pipe",
});
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: repoDir, stdio: "pipe" });
writeFileSync(
path.join(repoDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: [
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
],
},
}),
);
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "init"], {
cwd: repoDir,
stdio: "pipe",
});
const worktree = await createWorktree({
cwd: repoDir,
worktreeSlug: slug,
source: { kind: "branch-off", baseBranch: "main", branchName: slug },
paseoHome,
});
const workspace: PersistedWorkspaceRecord = {
workspaceId: `ws-${slug}`,
projectId: "proj-1",
cwd: worktree.worktreePath,
kind: "worktree",
worktreeRoot: worktree.worktreePath,
isPaseoOwnedWorktree: true,
mainRepoRoot: repoDir,
createdAt: "2026-11-24T00:00:00.000Z",
updatedAt: "2026-11-24T00:00:00.000Z",
};
const blockedSource = {
kind: "change_request" as const,
forge: "github",
number: 99,
headRepository: "contributor/paseo",
};
const assertWorkspaceAutomationAllowed = vi.fn(async (id: string) => {
if (id === workspace.workspaceId) {
throw new WorkspaceAutomationBlockedError(blockedSource);
}
});
const activeWorkspaces = [workspace];
const archived = new Set<string>();
const events = new AgentLifecycleEvents();
const agentManager = {
subscribe: (cb: AgentSubscriber) => events.subscribe(cb),
listAgents: () => [],
getAgent: () => null,
archiveAgent: vi.fn(async () => ({ archivedAt: new Date().toISOString() })),
archiveSnapshot: vi.fn(async () => ({})),
} as unknown as AgentManager;
const dispatch = new CreateAgentLifecycleDispatch({
paseoHome,
getWorkspace: async (id) => (id === workspace.workspaceId ? workspace : null),
assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: async () => false,
agentManager,
agentStorage: { listByWorkspace: async () => [] } as unknown as AgentStorage,
github: { invalidate: () => {} } as unknown as ForgeService,
workspaceGitService: {
getSnapshot: vi.fn(async () => null),
invalidateWorktrees: () => {},
} as unknown as WorkspaceGitService,
createPaseoWorktreeWorkflow: vi.fn(),
archiveAgentForClose: vi.fn(async () => undefined),
findWorkspaceIdForCwd: async () => workspace.workspaceId,
listActiveWorkspaces: async () => activeWorkspaces.filter((w) => !archived.has(w.workspaceId)),
archiveWorkspaceRecord: async (id) => {
archived.add(id);
},
emit: vi.fn(),
emitAgentRemove: vi.fn(async () => undefined),
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => undefined),
logger: pino({ level: "silent" }),
});
return {
dispatch,
events,
marker: path.join(repoDir, markerName),
createdWorktree: { worktree, workspace },
archived,
assertWorkspaceAutomationAllowed,
};
}
test("auto-archive self-releases once and later cancellation waits harmlessly", async () => {
const agentId = "4a7e2521-286d-4ad5-af35-e091c55302e3";
const agents = new AgentLifecycleEvents();
@@ -45,3 +170,41 @@ test("auto-archive self-releases once and later cancellation waits harmlessly",
expect(archiveCount).toBe(1);
expect(agents.listenerCount()).toBe(0);
});
test("failed create cleanup skips teardown commands for an unapproved cross-repository checkout", async () => {
const { dispatch, marker, createdWorktree, archived, assertWorkspaceAutomationAllowed } =
await createUntrustedWorktreeFixture("failed-create-untrusted", "failed-create-teardown.log");
await dispatch.cleanupCreatedWorktreeAfterFailedAgentCreate({
createdWorktree,
createdAgentId: null,
});
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(
createdWorktree.workspace.workspaceId,
);
expect(archived.has(createdWorktree.workspace.workspaceId)).toBe(true);
expect(existsSync(createdWorktree.worktree.worktreePath)).toBe(false);
expect(existsSync(marker)).toBe(false);
});
test("first-turn auto-archive skips teardown commands for an unapproved cross-repository checkout", async () => {
const { dispatch, events, marker, createdWorktree, archived, assertWorkspaceAutomationAllowed } =
await createUntrustedWorktreeFixture("auto-archive-untrusted", "auto-archive-teardown.log");
const agentId = "agent-auto-archive-untrusted";
const registration = dispatch.registerAutoArchiveIfRequested({
autoArchive: true,
agentId,
createdWorktree,
});
events.completeTurn(agentId);
await registration.cancel();
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(
createdWorktree.workspace.workspaceId,
);
expect(archived.has(createdWorktree.workspace.workspaceId)).toBe(true);
expect(existsSync(createdWorktree.worktree.worktreePath)).toBe(false);
expect(existsSync(marker)).toBe(false);
});
@@ -29,7 +29,8 @@ interface CreateAgentLifecycleDispatchDependencies {
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
assertWorkspaceAutomationAllowed: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
isCheckoutUntrusted: ArchiveDependencies["isCheckoutUntrusted"];
agentManager: AgentManager;
agentStorage: AgentStorage;
github: ForgeService;
@@ -201,6 +202,7 @@ export class CreateAgentLifecycleDispatch {
agentStorage: this.dependencies.agentStorage,
findWorkspaceIdForCwd: this.dependencies.findWorkspaceIdForCwd,
getWorkspace: this.dependencies.getWorkspace,
assertWorkspaceAutomationAllowed: this.dependencies.assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: this.dependencies.isCheckoutUntrusted,
listActiveWorkspaces: this.dependencies.listActiveWorkspaces,
archiveWorkspaceRecord: this.dependencies.archiveWorkspaceRecord,
@@ -2527,6 +2527,8 @@ describe("create_agent MCP tool", () => {
emitWorkspaceUpdatesForWorkspaceIds,
markWorkspaceArchiving,
clearWorkspaceArchiving,
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
github: createGitHubServiceStub(),
logger,
});
@@ -2643,6 +2645,8 @@ describe("create_agent MCP tool", () => {
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
github: createGitHubServiceStub(),
logger,
});
@@ -2675,6 +2679,117 @@ describe("create_agent MCP tool", () => {
}
});
it("skips teardown commands when archiving a worktree with blocked repository automation", async () => {
const { agentManager, agentStorage } = createTestDeps();
const tempDir = realpathSync.native(
await mkdtemp(join(tmpdir(), "paseo-mcp-archive-worktree-blocked-")),
);
const repoDir = join(tempDir, "repo");
const paseoHome = join(tempDir, ".paseo");
const markerName = "mcp-blocked-teardown.log";
const markerPath = join(repoDir, markerName);
try {
execFileSync("git", ["init", repoDir], { stdio: "pipe" });
execFileSync("git", ["config", "user.email", "test@example.com"], {
cwd: repoDir,
stdio: "pipe",
});
execFileSync("git", ["config", "user.name", "Test"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["config", "commit.gpgsign", "false"], {
cwd: repoDir,
stdio: "pipe",
});
await writeFile(
join(repoDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: [
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
],
},
}),
);
execFileSync("git", ["add", "paseo.json"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["commit", "-m", "init"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["branch", "-M", "main"], { cwd: repoDir, stdio: "pipe" });
const workspaceGitService = {
getSnapshot: vi.fn(async () => null),
listWorktrees: vi.fn(async () => []),
resolveRepoRoot: vi.fn(async () => repoDir),
invalidateWorktrees: vi.fn(),
};
const archivedWorkspaceIds: string[] = [];
const activeWorkspaces: Array<{
workspaceId: string;
cwd: string;
kind: "worktree" | "local_checkout" | "directory";
}> = [];
const listActiveWorkspaces = vi.fn(async () => activeWorkspaces);
const archiveWorkspaceRecord = createArchiveWorkspaceRecordMutator(
activeWorkspaces,
archivedWorkspaceIds,
);
const { WorkspaceAutomationBlockedError } = await import("../workspace-automation-gate.js");
const server = await createAgentMcpServer({
agentManager,
agentStorage,
providerSnapshotManager: createOpenCodeManager().manager,
paseoHome,
createPaseoWorktree: createPaseoWorktreeForMcpTest({ paseoHome, broadcasts: [] }),
workspaceGitService: workspaceGitService as unknown as Pick<
WorkspaceGitService,
"getSnapshot" | "listWorktrees" | "resolveRepoRoot" | "invalidateWorktrees"
>,
findWorkspaceIdForCwd: vi.fn(async () => "ws-mcp-blocked"),
listActiveWorkspaces,
archiveWorkspaceRecord,
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
assertWorkspaceAutomationAllowed: async () => {
throw new WorkspaceAutomationBlockedError({
kind: "change_request",
forge: "github",
number: 77,
headRepository: "contributor/repo",
});
},
isCheckoutUntrusted: async () => false,
github: createGitHubServiceStub(),
logger,
});
const createTool = registeredTool(server, "create_workspace");
const archiveTool = registeredTool(server, "archive_workspace");
const created = await createTool.handler({
isolation: "worktree",
path: repoDir,
worktreeSlug: "archive-blocked-worktree",
baseBranch: "main",
});
const worktreePath = z.string().parse(created.structuredContent.cwd);
activeWorkspaces.push({
workspaceId: "ws-mcp-blocked",
cwd: worktreePath,
kind: "worktree",
});
const archived = await archiveTool.handler({
workspaceId: "ws-mcp-blocked",
});
expect(archived.structuredContent).toMatchObject({
workspaceId: "ws-mcp-blocked",
removedDirectory: true,
});
await expect(access(worktreePath)).rejects.toThrow();
await expect(access(markerPath)).rejects.toThrow();
} finally {
await removeTempDir(tempDir);
}
});
it("does not expose worktree path or slug operations", async () => {
const { agentManager, agentStorage } = createTestDeps();
const tempDir = realpathSync.native(
@@ -1,9 +1,12 @@
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import type { ChildProcess } from "node:child_process";
import type {
Options,
Query,
SpawnOptions as ClaudeSpawnOptions,
import {
query as sdkQuery,
type Options,
type Query,
type SpawnOptions as ClaudeSpawnOptions,
type SpawnedProcess,
} from "@anthropic-ai/claude-agent-sdk";
import { afterEach, describe, expect, test, vi } from "vitest";
@@ -102,4 +105,72 @@ describe("Claude spawn override", () => {
const spawnOptions = claudeSpawnCall?.[2];
expect(spawnOptions?.shell).toBe(false);
});
test("keeps the Paseo MCP bearer token off the Claude Code command line", async () => {
let capturedOptions: Options | undefined;
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
capturedOptions = options;
return createQueryMock([]);
});
const client = new ClaudeAgentClient({
logger: createTestLogger(),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => "2.1.326",
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
mcpServers: {
paseo: {
type: "http",
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
headers: { Authorization: "Bearer secret-token" },
},
},
});
await (session as unknown as { ensureQuery(): Promise<unknown> }).ensureQuery();
await session.close();
if (!capturedOptions) {
throw new Error("Claude query options were not captured");
}
// Feed Paseo's options to the real SDK and record the argv it would launch with.
let launchArgs: string[] | undefined;
let stdinText = "";
const stdin = new PassThrough();
stdin.on("data", (chunk: Buffer) => {
stdinText += chunk.toString("utf8");
});
const abortController = new AbortController();
const sdk = sdkQuery({
prompt: "hello",
options: {
...capturedOptions,
abortController,
spawnClaudeCodeProcess: (spawnOptions: ClaudeSpawnOptions): SpawnedProcess => {
launchArgs = spawnOptions.args;
const child = new EventEmitter() as EventEmitter & SpawnedProcess;
Object.assign(child, {
stdin,
stdout: new PassThrough(),
killed: false,
exitCode: null,
kill: () => true,
});
return child;
},
},
});
// The fake process never answers, so the first message never arrives; only the launch matters.
void sdk.next().catch(() => undefined);
await vi.waitFor(() => {
expect(stdinText).toContain("secret-token");
});
abortController.abort();
expect(launchArgs).toBeDefined();
expect(launchArgs?.join(" ")).not.toContain("secret-token");
expect(launchArgs).not.toContain("--mcp-config");
});
});
@@ -449,12 +449,12 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
describe("a background subagent", () => {
// Shapes recorded from Claude Code 2.1.x: the launch returns at once with an async result,
// and a child stopped by an interrupt ends on the interrupt placeholder, not an end_turn.
function backgroundLaunch(): string[] {
function backgroundLaunch({ toolUseId = TOOL_USE_ID, agentId = AGENT_ID } = {}): string[] {
return [
parentEntry([
{
type: "tool_use",
id: TOOL_USE_ID,
id: toolUseId,
name: "Agent",
input: {
subagent_type: "general-purpose",
@@ -472,17 +472,17 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
content: [
{
type: "tool_result",
tool_use_id: TOOL_USE_ID,
tool_use_id: toolUseId,
content: [
{
type: "text",
text: `Async agent launched successfully.\nagentId: ${AGENT_ID}`,
text: `Async agent launched successfully.\nagentId: ${agentId}`,
},
],
},
],
},
toolUseResult: { isAsync: true, status: "async_launched", agentId: AGENT_ID },
toolUseResult: { isAsync: true, status: "async_launched", agentId },
}),
];
}
@@ -607,17 +607,35 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
expect(statuses).toContain("running");
});
function taskNotification(status: string, form = "user"): string {
const text = `<task-notification>\n<task-id>${AGENT_ID}</task-id>\n<tool-use-id>${TOOL_USE_ID}</tool-use-id>\n<status>${status}</status>\n<summary>Background task ended</summary>\n</task-notification>`;
function taskNotification({
status,
form = "user",
includeToolUseId = true,
taskIds = [AGENT_ID],
quoted = false,
}: {
status: string;
form?: string;
includeToolUseId?: boolean;
taskIds?: string[];
quoted?: boolean;
}): string {
const toolUseTag = includeToolUseId ? `<tool-use-id>${TOOL_USE_ID}</tool-use-id>\n` : "";
const taskTags = taskIds.map((id) => `<task-id>${id}</task-id>`).join("\n");
const notification = `<task-notification>\n${taskTags}\n${toolUseTag}<status>${status}</status>\n<summary>Background task ended</summary>\n</task-notification>`;
const text = quoted ? `Explain this log.\n${notification}` : notification;
const records = {
user: { message: { role: "user", content: [{ type: "text", text }] } },
user: {
...(quoted ? {} : { origin: { kind: "task-notification" } }),
message: { role: "user", content: [{ type: "text", text }] },
},
system: {
subtype: "task_notification",
task_id: AGENT_ID,
tool_use_id: TOOL_USE_ID,
...(includeToolUseId ? { tool_use_id: TOOL_USE_ID } : {}),
status,
},
"queue-operation": { operation: "enqueue", content: text },
"queue-operation": { operation: quoted ? "remove" : "enqueue", content: text },
};
return JSON.stringify({
type: form,
@@ -636,7 +654,7 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
`restores a %s task notification from ${form} when the child stop_reason is null`,
async (status, expected) => {
writeSession({
parentLines: [...backgroundLaunch(), taskNotification(status, form)],
parentLines: [...backgroundLaunch(), taskNotification({ status, form })],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: null })],
});
@@ -648,9 +666,160 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
);
}
for (const form of ["user", "system", "queue-operation"]) {
test.each([
["completed", "completed"],
["failed", "failed"],
["stopped", "canceled"],
["unknown", "running"],
])(`restores a task-id-only %s notification from ${form}`, async (status, expected) => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status, form, includeToolUseId: false }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({
id: TOOL_USE_ID,
status: expected,
});
});
}
test.each([
["user", false, "canceled"],
["queue-operation", false, "canceled"],
["user", true, "running"],
])(
"restores a shared %s notification with explicit tool-use ID present = %s",
async (form, includeToolUseId, secondStatus) => {
const secondAgentId = "a2222222222222222";
const secondToolUseId = "toolu_second";
const subagentDir = writeParentSession([
...backgroundLaunch(),
...backgroundLaunch({ agentId: secondAgentId, toolUseId: secondToolUseId }),
taskNotification({
status: "stopped",
form,
includeToolUseId,
taskIds: [AGENT_ID, "unrelated-task", secondAgentId],
}),
]);
writeSubagent({
subagentDir,
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
writeSubagent({
subagentDir,
agentId: secondAgentId,
sidechainLines: [sidechainEntry({ agentId: secondAgentId, stopReason: "tool_use" })],
});
const statuses = new Map();
for (const { id, status } of upserts(await replayDescriptors())) {
statuses.set(id, status);
}
expect(statuses).toEqual(
new Map([
[TOOL_USE_ID, "canceled"],
[secondToolUseId, secondStatus],
]),
);
},
);
test("keeps the latest outcome across task-only and tool-linked notifications", async () => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status: "stopped", form: "queue-operation", includeToolUseId: false }),
taskNotification({ status: "stopped", form: "user", includeToolUseId: false }),
taskNotification({ status: "completed" }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "completed" });
});
test("honors a later task-only stopped notification after a tool-linked completion", async () => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status: "completed" }),
taskNotification({ status: "stopped", form: "user", includeToolUseId: false }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "canceled" });
});
test.each(["user", "queue-operation"])(
"keeps a completed child when a later %s record quotes a stopped notification",
async (form) => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status: "completed" }),
taskNotification({ status: "stopped", form, includeToolUseId: false, quoted: true }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "completed" });
},
);
test("does not apply an unrelated task's stopped outcome to a child", async () => {
writeSession({
parentLines: [
...backgroundLaunch(),
taskNotification({ status: "stopped", form: "user", includeToolUseId: false }).replace(
AGENT_ID,
"unrelated-task",
),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({ status: "running" });
});
test("restores a stopped child after a Bash result echoes its launch log", async () => {
const bashToolUseId = "toolu_bash";
writeSession({
parentLines: [
...backgroundLaunch(),
parentEntry([{ type: "tool_use", id: bashToolUseId, name: "Bash", input: {} }]),
JSON.stringify({
type: "user",
message: {
content: [
{
type: "tool_result",
tool_use_id: bashToolUseId,
content: `Async agent launched successfully.\nagentId: ${AGENT_ID}`,
},
],
},
}),
taskNotification({ status: "stopped", includeToolUseId: false }),
],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "tool_use" })],
});
expect(upserts(await replayDescriptors()).at(-1)).toMatchObject({
id: TOOL_USE_ID,
status: "canceled",
});
});
test("prefers a stopped notification over the child's end_turn", async () => {
writeSession({
parentLines: [...backgroundLaunch(), taskNotification("stopped")],
parentLines: [...backgroundLaunch(), taskNotification({ status: "stopped" })],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: "end_turn" })],
});
@@ -659,7 +828,7 @@ describe("ClaudeAgentSession persisted subagent replay", () => {
test("does not invent an outcome for an unknown notification status", async () => {
writeSession({
parentLines: [...backgroundLaunch(), taskNotification("unknown")],
parentLines: [...backgroundLaunch(), taskNotification({ status: "unknown" })],
meta: JSON.stringify({ toolUseId: TOOL_USE_ID }),
sidechainLines: [sidechainEntry({ stopReason: null })],
});
@@ -1094,6 +1094,153 @@ describe("ClaudeAgentSession features", () => {
await session.close();
});
test.each([
{ claudeCodeVersion: "2.1.326", expected: "initialize" },
{ claudeCodeVersion: "2.2.0", expected: "initialize" },
{ claudeCodeVersion: "2.1.325", expected: "argv" },
{ claudeCodeVersion: undefined, expected: "argv" },
])(
"delivers MCP servers by $expected for Claude Code $claudeCodeVersion",
async ({ claudeCodeVersion, expected }) => {
const { queryFactory } = createQueryMock();
const client = new ClaudeAgentClient({
logger,
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => {
if (claudeCodeVersion === undefined) {
throw new Error("Unable to parse Claude Code version from --version output");
}
return claudeCodeVersion;
},
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
mcpServers: {
paseo: {
type: "http",
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
headers: { Authorization: "Bearer secret-token" },
},
},
});
await (session as unknown as { ensureQuery(): Promise<unknown> }).ensureQuery();
expect(queryFactory.mock.calls[0]?.[0].options.mcpServersDelivery).toBe(expected);
await session.close();
},
);
test("probes the configured Claude command in the workspace with the session environment", async () => {
const { queryFactory, launches } = createQueryMock();
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "claude-mcp-workspace-"));
const versionProbe = `
const workspace = process.cwd().endsWith(${JSON.stringify(path.basename(cwd))});
const selected = workspace && process.env.TEST_CLAUDE_WORKSPACE_VERSION;
console.log((selected || "2.1.326") + " (Claude Code)");
`;
const client = new ClaudeAgentClient({
logger,
queryFactory,
runtimeSettings: {
command: { mode: "replace", argv: [process.execPath, "-e", versionProbe, "--"] },
},
});
try {
const session = await client.createSession(
{
provider: "claude",
cwd,
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
},
{ env: { TEST_CLAUDE_WORKSPACE_VERSION: "2.1.325" } },
);
try {
await session.setModel?.("claude-sonnet-4-6");
expect(launches.map(({ options }) => options.mcpServersDelivery)).toEqual(["argv"]);
} finally {
await session.close();
}
} finally {
await fs.rm(cwd, { recursive: true, force: true });
}
});
test("uses stdin on new launches and relaunches after Claude Code upgrades", async () => {
const { queryFactory, launches } = createQueryMock();
let version = "2.1.325";
const client = new ClaudeAgentClient({
logger,
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => version,
});
const config = {
provider: "claude",
cwd: process.cwd(),
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
} as const;
const existing = await client.createSession(config);
try {
await existing.setModel?.("claude-sonnet-4-6");
expect(launches.map(({ options }) => options.mcpServersDelivery)).toEqual(["argv"]);
version = "2.1.326";
const fresh = await client.createSession(config);
try {
await fresh.setModel?.("claude-sonnet-4-6");
await existing.setThinkingOption?.("high");
await existing.setModel?.("claude-sonnet-4-6");
expect(launches.map(({ options }) => options.mcpServersDelivery)).toEqual([
"argv",
"initialize",
"initialize",
]);
} finally {
await fresh.close();
}
} finally {
await existing.close();
}
});
test("warns about argv delivery only on launches with MCP servers", async () => {
const messages: string[] = [];
const { queryFactory } = createQueryMock();
const client = new ClaudeAgentClient({
logger: pino({}, { write: (message: string) => messages.push(JSON.parse(message).msg) }),
queryFactory,
resolveBinary: async () => "/test/claude/bin",
resolveVersion: async () => "2.1.325",
});
const warnings = () => messages.filter((message) => message.includes("MCP server headers"));
const config = { provider: "claude", cwd: process.cwd() } as const;
const launch = async (sessionConfig: Parameters<typeof client.createSession>[0]) => {
const session = await client.createSession(sessionConfig);
try {
await session.setModel?.("claude-sonnet-4-6");
} finally {
await session.close();
}
};
await launch(config);
await launch({ ...config, mcpServers: {} });
expect(warnings()).toEqual([]);
const withMcp = {
...config,
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
} as const;
await launch(withMcp);
await launch(withMcp);
expect(warnings()).toEqual([
"Claude Code is too old or reports no version; MCP server headers go on its command line",
]);
});
test("passes extra Claude Code CLI arguments to the SDK", async () => {
const { queryFactory, launches } = createQueryMock();
const client = new ClaudeAgentClient({
@@ -39,7 +39,7 @@ import {
mapTaskNotificationSystemRecordToToolCall,
mapTaskNotificationUserContentToToolCall,
readTaskNotificationToolUseIdFromHistoryRecord,
readTaskNotificationFromHistoryRecord,
readTaskNotificationOutcomeFromHistoryRecord,
} from "./task-notification-tool-call.js";
import { isClaudeInterruptPlaceholderText } from "./interrupt-placeholder.js";
import {
@@ -54,6 +54,7 @@ import {
claudeManifestModelSupportsUltracode,
parseClaudeCodeVersion,
resolveClaudeDisabledThinkingForModel,
supportsClaudeMcpServersViaInitialize,
supportsIndependentClaudeUltracode,
} from "./model-manifest.js";
import { expandTilde } from "../../../../utils/path.js";
@@ -88,7 +89,13 @@ import {
} from "./options.js";
import { renderPromptAttachmentAsText } from "../../prompt-attachments.js";
import { discoverClaudeModels, killExitingClaudeModelDiscoveries } from "./model-discovery.js";
import { claudeQuery, type ClaudeOptions, type ClaudeQueryFactory } from "./query.js";
import {
claudeQuery,
probeClaudeLaunchVersion,
type ClaudeLaunchVersionProbe,
type ClaudeOptions,
type ClaudeQueryFactory,
} from "./query.js";
import {
findSteeredMessageParent,
realClaudeRewindSdk,
@@ -513,9 +520,14 @@ interface ClaudeAgentSessionOptions {
queryFactory?: ClaudeQueryFactory;
resolveBinary: () => Promise<string>;
independentUltracode: boolean;
resolveMcpServersDelivery: (
launch: ClaudeLaunchVersionProbe,
) => Promise<ClaudeMcpServersDelivery>;
rewindSdk?: ClaudeRewindSdk;
}
type ClaudeMcpServersDelivery = NonNullable<ClaudeOptions["mcpServersDelivery"]>;
type ClaudeThinkingEffort = "low" | "medium" | "high" | "xhigh" | "max";
type ClaudeThinkingOption =
| ClaudeThinkingEffort
@@ -1646,7 +1658,11 @@ export class ClaudeAgentClient implements AgentClient {
private readonly queryFactory?: ClaudeQueryFactory;
private readonly resolveBinary: () => Promise<string>;
private readonly resolveVersion: (signal?: AbortSignal) => Promise<string>;
private readonly resolveLaunchVersion: (
launch: ClaudeLaunchVersionProbe,
) => Promise<string | null>;
private version: Promise<string | undefined> | undefined;
private warnedMcpServersOnArgv = false;
private readonly lookupLatestRelease: LatestReleaseLookup;
private readonly rewindSdk: ClaudeRewindSdk;
private readonly scheduleImportDescriptors = createImportDescriptorScheduler(
@@ -1669,6 +1685,9 @@ export class ClaudeAgentClient implements AgentClient {
this.resolveVersion =
options.resolveVersion ??
((signal) => resolveClaudeCodeVersion(this.runtimeSettings, signal));
this.resolveLaunchVersion = options.resolveVersion
? () => this.resolveVersion()
: async (launch) => parseReportedClaudeVersion(await probeClaudeLaunchVersion(launch));
this.lookupLatestRelease =
options.lookupLatestRelease ??
((input) =>
@@ -1699,6 +1718,7 @@ export class ClaudeAgentClient implements AgentClient {
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
resolveMcpServersDelivery: (launch) => this.resolveMcpServersDelivery(launch),
rewindSdk: this.rewindSdk,
});
}
@@ -1729,6 +1749,7 @@ export class ClaudeAgentClient implements AgentClient {
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
resolveMcpServersDelivery: (launch) => this.resolveMcpServersDelivery(launch),
rewindSdk: this.rewindSdk,
});
await session.ensureHistoryReady();
@@ -1826,6 +1847,25 @@ export class ClaudeAgentClient implements AgentClient {
return supportsIndependentClaudeUltracode(await this.version);
}
private async resolveMcpServersDelivery(
launch: ClaudeLaunchVersionProbe,
): Promise<ClaudeMcpServersDelivery> {
// The installed version can change between SDK launches in the same session.
const version = (await this.resolveLaunchVersion(launch).catch(() => null)) ?? undefined;
if (supportsClaudeMcpServersViaInitialize(version)) {
return "initialize";
}
if (this.warnedMcpServersOnArgv) {
return "argv";
}
this.warnedMcpServersOnArgv = true;
this.logger.warn(
{ claudeCodeVersion: version ?? null },
"Claude Code is too old or reports no version; MCP server headers go on its command line",
);
return "argv";
}
async listImportableSessions(
options?: ListImportableSessionsOptions & { signal?: AbortSignal },
): Promise<ImportableProviderSession[]> {
@@ -2059,22 +2099,23 @@ async function readClaudeCodeVersion(
const installed = await resolveInstalledClaude(runtimeSettings);
if (!installed) return { status: "not_installed" };
const { executable } = installed;
const { stdout, stderr } = await execCommand(executable, [...installed.args, "--version"], {
const output = await execCommand(executable, [...installed.args, "--version"], {
...createProviderEnvSpec({ runtimeSettings }),
timeout: 5_000,
signal,
});
// A wrapper command (the `command` provider setting) prints its own version here
return { status: "installed", version: parseReportedClaudeVersion(output) };
}
function parseReportedClaudeVersion({ stdout, stderr }: { stdout: string; stderr: string }) {
// A wrapper command (the `command` provider setting) may print its own version here
// instead of Claude Code's. Only trust output that identifies itself as Claude Code,
// so a wrapper's version can't mis-gate models behind a minimumClaudeCodeVersion.
const rawVersionOutput = `${stdout}\n${stderr}`;
const version = /\d+\.\d+\.\d+\s+\(Claude Code\)/i.test(rawVersionOutput)
? parseClaudeCodeVersion(rawVersionOutput)
: null;
return {
status: "installed",
version: version ? version.join(".") : null,
};
return version ? version.join(".") : null;
}
async function resolveClaudeAuth(
@@ -2424,6 +2465,7 @@ class ClaudeAgentSession implements AgentSession {
private readonly queryFactory?: ClaudeQueryFactory;
private readonly resolveBinary: () => Promise<string>;
private readonly independentUltracode: boolean;
private readonly resolveMcpServersDelivery: ClaudeAgentSessionOptions["resolveMcpServersDelivery"];
private query: Query | null = null;
private readonly runtimeSafety = new ClaudeRuntimeSafety();
private readonly backgroundStops = new Map<string, (outcome: string) => void>();
@@ -2563,6 +2605,7 @@ class ClaudeAgentSession implements AgentSession {
this.queryFactory = options.queryFactory;
this.resolveBinary = options.resolveBinary;
this.independentUltracode = options.independentUltracode;
this.resolveMcpServersDelivery = options.resolveMcpServersDelivery;
this.rewindSdk = options.rewindSdk ?? realClaudeRewindSdk;
this.contextUsage = new ClaudeContextUsageState(
getClaudeContextWindowMaxTokens(this.config.model),
@@ -4048,6 +4091,15 @@ class ClaudeAgentSession implements AgentSession {
if (this.config.mcpServers) {
base.mcpServers = this.normalizeMcpServers(this.config.mcpServers);
if (Object.keys(base.mcpServers).length > 0) {
base.mcpServersDelivery = await this.resolveMcpServersDelivery({
executable: claudeBinary,
cwd: this.config.cwd,
env: sdkEnv,
runtimeSettings: this.runtimeSettings,
launchEnv: this.launchEnv,
});
}
}
if (this.config.model) {
@@ -6769,10 +6821,8 @@ async function readClaudeReplayParentFacts(
const linksByAgentId = new Map<string, { toolCallId: string }>();
const outcomes: Map<string, { status: ProviderSubagentStatus }> = new Map();
for await (const entry of entries) {
const notification = readTaskNotificationFromHistoryRecord(entry);
const status = mapTaskStatus(notification?.status ?? undefined);
if (notification?.toolUseId && status) {
outcomes.set(notification.toolUseId, { status });
for (const notificationOutcome of readClaudeReplayNotificationOutcomes(entry, linksByAgentId)) {
outcomes.set(notificationOutcome.toolCallId, { status: notificationOutcome.status });
}
const content = toObjectRecord(entry.message)?.content;
if (!Array.isArray(content)) continue;
@@ -6790,6 +6840,7 @@ async function readClaudeReplayParentFacts(
outcomes.set(block.tool_use_id, {
status: block.is_error === true ? "failed" : "completed",
});
if (!toolCalls.has(block.tool_use_id)) continue;
const agentId = readLegacyClaudeSubagentId(block.content);
if (agentId)
linksByAgentId.set(agentId, {
@@ -6804,6 +6855,26 @@ async function readClaudeReplayParentFacts(
};
}
function* readClaudeReplayNotificationOutcomes(
entry: ClaudeHistoryEntry,
linksByAgentId: ReadonlyMap<string, { toolCallId: string }>,
): Generator<{ toolCallId: string; status: ProviderSubagentStatus }> {
const notification = readTaskNotificationOutcomeFromHistoryRecord(entry);
if (!notification) return;
const status = mapTaskStatus(notification.status ?? undefined);
if (!status) return;
if (notification.toolUseId) {
yield { toolCallId: notification.toolUseId, status };
return;
}
// Stopped tasks can omit tool-use-id; their launch results already link the native IDs.
for (const taskId of notification.taskIds) {
const link = linksByAgentId.get(taskId);
if (link) yield { toolCallId: link.toolCallId, status };
}
}
function readClaudeReplayTaskDeclaration(
entryType: unknown,
block: Record<string, unknown> | undefined,
@@ -347,6 +347,27 @@ export function supportsIndependentClaudeUltracode(version: string | undefined):
return version === undefined || compareVersions(version, "2.1.284") >= 0;
}
/**
* The Claude Code version bundled with the Agent SDK release that documents
* `mcpServersDelivery: "initialize"`. The SDK only guarantees that delivery for
* the bundled Claude Code or newer: an older binary exits on an unknown flag or
* has its session ended by the SDK.
*/
export const CLAUDE_MCP_SERVERS_VIA_INITIALIZE_MIN_VERSION = "2.1.326";
/**
* Whether MCP servers can reach Claude Code over stdin instead of `--mcp-config`
* on its command line, where any local user can read their headers and env.
* An unknown version (a wrapper command) stays on the command line so the
* session still starts.
*/
export function supportsClaudeMcpServersViaInitialize(version: string | undefined): boolean {
return (
version !== undefined &&
compareVersions(version, CLAUDE_MCP_SERVERS_VIA_INITIALIZE_MIN_VERSION) >= 0
);
}
export interface ClaudeDisabledThinkingResolution {
supported: boolean;
fallbackThinkingOptionId: string | undefined;
@@ -6,7 +6,7 @@ import {
type ProviderRuntimeSettings,
} from "../../provider-launch-config.js";
import { buildSelfNodeCommand, createExternalProcessEnv } from "../../../paseo-env.js";
import { spawnProcess } from "../../../../utils/spawn.js";
import { execCommand, spawnProcess } from "../../../../utils/spawn.js";
// Keep the raw SDK query import in this module only. Claude process launch behavior
// must stay shared between production and tests so Windows .cmd/.bat handling cannot
@@ -29,7 +29,7 @@ function isChildProcessWithStreams(child: ChildProcess): child is ChildProcessWi
}
function resolveClaudeSpawnCommand(
spawnOptions: SpawnOptions,
spawnOptions: Pick<SpawnOptions, "command" | "args">,
runtimeSettings?: ProviderRuntimeSettings,
): { command: string; args: string[] } {
const commandConfig = runtimeSettings?.command;
@@ -53,11 +53,44 @@ function resolveClaudeSpawnCommand(
};
}
type ClaudeLaunchEnvironment = Pick<ClaudeQueryContext, "runtimeSettings" | "launchEnv">;
function createClaudeSpawnEnvSpec(
baseEnv: SpawnOptions["env"],
{ runtimeSettings, launchEnv }: ClaudeLaunchEnvironment,
) {
const spec = createProviderEnvSpec({ baseEnv, runtimeSettings, overlays: [launchEnv] });
// Session-open hooks may supply a client identity. Clear inherited SDK/parent identities.
spec.envOverlay.CLAUDE_CODE_ENTRYPOINT = launchEnv?.CLAUDE_CODE_ENTRYPOINT;
return spec;
}
export interface ClaudeLaunchVersionProbe extends ClaudeLaunchEnvironment {
executable: string;
cwd: string;
env: SpawnOptions["env"];
}
export function probeClaudeLaunchVersion(
launch: ClaudeLaunchVersionProbe,
): Promise<{ stdout: string; stderr: string }> {
const { command, args } = resolveClaudeSpawnCommand(
{ command: launch.executable, args: ["--version"] },
launch.runtimeSettings,
);
return execCommand(command, args, {
...createClaudeSpawnEnvSpec(launch.env, launch),
cwd: launch.cwd,
shell: false,
timeout: 5_000,
});
}
function applyRuntimeSettingsToClaudeOptions(
options: ClaudeOptions,
context: ClaudeQueryContext,
): ClaudeOptions {
const { runtimeSettings, launchEnv, onChildProcess } = context;
const { runtimeSettings, onChildProcess } = context;
return {
...options,
spawnClaudeCodeProcess: (spawnOptions) => {
@@ -68,14 +101,7 @@ function applyRuntimeSettingsToClaudeOptions(
// When the SDK passes a native binary path (from pathToClaudeCodeExecutable)
// or the user overrides the command via runtime settings, use that directly.
const isDefaultRuntime = resolved.command === "node" || resolved.command === "bun";
const providerEnvSpec = createProviderEnvSpec({
baseEnv: spawnOptions.env,
runtimeSettings,
overlays: [launchEnv],
});
// Session-open hooks may explicitly supply a client identity. Keep inherited
// SDK/parent identities cleared while honoring this launch-only contribution.
providerEnvSpec.envOverlay.CLAUDE_CODE_ENTRYPOINT = launchEnv?.CLAUDE_CODE_ENTRYPOINT;
const providerEnvSpec = createClaudeSpawnEnvSpec(spawnOptions.env, context);
const providerEnv = createExternalProcessEnv(spawnOptions.env, providerEnvSpec.envOverlay);
const selfNodeCommand = isDefaultRuntime
? buildSelfNodeCommand(resolved.args, providerEnv)
@@ -14,7 +14,7 @@ const OptionalNonEmptyTrimmedStringSchema = z.preprocess(
const TaskNotificationEnvelopeSchema = z.object({
notificationId: z.string().optional(),
messageId: z.string().nullable(),
taskId: z.string().nullable(),
taskIds: z.array(z.string()),
toolUseId: z.string().nullable(),
status: z.string().nullable(),
summary: z.string().nullable(),
@@ -44,6 +44,10 @@ const TaskNotificationHistoryRecordSchema = z
message_id: z.string().optional(),
task_id: z.string().optional(),
tool_use_id: z.string().optional(),
origin: z
.object({ kind: z.literal("task-notification") })
.optional()
.catch(undefined),
status: z.string().optional(),
summary: z.string().optional(),
output_file: z.string().optional(),
@@ -145,6 +149,19 @@ function readTaskNotificationTagValue(input: ReadTaskNotificationTagInput): stri
return toNonEmptyString(match[1]);
}
function readTaskNotificationTaskIds(rawText: string | null, structuredTaskId?: string): string[] {
const taskIds = [];
const taskId = toNonEmptyString(structuredTaskId);
if (taskId) taskIds.push(taskId);
if (rawText) {
for (const match of rawText.matchAll(/<task-id>([\s\S]*?)<\/task-id>/gi)) {
const taggedTaskId = toNonEmptyString(match[1]);
if (taggedTaskId) taskIds.push(taggedTaskId);
}
}
return [...new Set(taskIds)];
}
function parseTaskNotificationFromUserContent(
input: MapTaskNotificationUserContentToToolCallInput,
): TaskNotificationEnvelope | null {
@@ -161,7 +178,7 @@ function parseTaskNotificationFromUserContent(
return TaskNotificationEnvelopeSchema.parse({
notificationId: parsedInput.data.notificationId,
messageId: toNonEmptyString(parsedInput.data.messageId),
taskId: readTaskNotificationTagValue({ text: rawText, tagName: "task-id" }),
taskIds: readTaskNotificationTaskIds(rawText),
toolUseId:
readTaskNotificationTagValue({ text: rawText, tagName: "tool-use-id" }) ??
readTaskNotificationTagValue({ text: rawText, tagName: "tool_use_id" }),
@@ -193,9 +210,7 @@ function parseTaskNotificationFromSystemRecord(record: unknown): TaskNotificatio
return TaskNotificationEnvelopeSchema.parse({
notificationId: systemRecord.notificationId,
messageId: toNonEmptyString(systemRecord.uuid) ?? toNonEmptyString(systemRecord.message_id),
taskId:
toNonEmptyString(systemRecord.task_id) ??
(rawText ? readTaskNotificationTagValue({ text: rawText, tagName: "task-id" }) : null),
taskIds: readTaskNotificationTaskIds(rawText, systemRecord.task_id),
toolUseId:
toNonEmptyString(systemRecord.tool_use_id) ??
(rawText
@@ -236,7 +251,7 @@ export async function* assignTaskNotificationReplayIds<T>(
data.type === "user"
? parseTaskNotificationFromUserContent({ content: data.message?.content })
: parseTaskNotificationFromSystemRecord(data);
if (!envelope?.taskId || !data.type) {
if (!envelope?.taskIds.length || !data.type) {
yield entry;
continue;
}
@@ -263,7 +278,7 @@ function taskNotificationReplaySignature(envelope: TaskNotificationEnvelope): st
return createHash("sha1")
.update(
JSON.stringify([
envelope.taskId,
envelope.taskIds.length > 1 ? envelope.taskIds : (envelope.taskIds[0] ?? null),
envelope.toolUseId,
envelope.status,
envelope.summary,
@@ -286,9 +301,8 @@ function buildTaskNotificationCallId(envelope: TaskNotificationEnvelope): string
: null;
if (messageSegment) return `task_notification_${messageSegment}`;
const taskSegment = envelope.taskId
? normalizeTaskNotificationCallIdSegment(envelope.taskId)
: null;
const [taskId] = envelope.taskIds;
const taskSegment = taskId ? normalizeTaskNotificationCallIdSegment(taskId) : null;
if (taskSegment) return `task_notification_${taskSegment}`;
const seed =
@@ -334,10 +348,11 @@ function toTaskNotificationToolCall(
});
const label = buildTaskNotificationLabel(envelope);
const detailText = envelope.rawText ?? envelope.summary ?? undefined;
const [taskId] = envelope.taskIds;
const metadata: Record<string, unknown> = {
synthetic: true,
source: "claude_task_notification",
...(envelope.taskId ? { taskId: envelope.taskId } : {}),
...(taskId ? { taskId } : {}),
...(envelope.toolUseId ? { toolUseId: envelope.toolUseId } : {}),
...(envelope.status ? { status: envelope.status } : {}),
...(envelope.outputFile ? { outputFile: envelope.outputFile } : {}),
@@ -407,18 +422,38 @@ export function mapTaskNotificationSystemRecordToToolCall(
}
export function readTaskNotificationToolUseIdFromHistoryRecord(record: unknown): string | null {
return readTaskNotificationFromHistoryRecord(record)?.toolUseId ?? null;
const parsedRecord = TaskNotificationHistoryRecordSchema.safeParse(record);
return parsedRecord.success
? (parseTaskNotificationHistoryRecord(parsedRecord.data)?.toolUseId ?? null)
: null;
}
export function readTaskNotificationFromHistoryRecord(
export function readTaskNotificationOutcomeFromHistoryRecord(
record: unknown,
): TaskNotificationEnvelope | null {
const parsedRecord = TaskNotificationHistoryRecordSchema.safeParse(record);
if (!parsedRecord.success) return null;
if (parsedRecord.data.type === "user" && parsedRecord.data.message) {
const entry = parsedRecord.data;
if (entry.type === "user" && entry.origin?.kind !== "task-notification") return null;
if (entry.type === "queue-operation") {
const content = entry.content?.trim();
if (
!content?.startsWith(TASK_NOTIFICATION_MARKER) ||
!content.endsWith("</task-notification>")
) {
return null;
}
}
return parseTaskNotificationHistoryRecord(entry);
}
function parseTaskNotificationHistoryRecord(
record: TaskNotificationHistoryRecord,
): TaskNotificationEnvelope | null {
if (record.type === "user" && record.message) {
return parseTaskNotificationFromUserContent({
content: parsedRecord.data.message.content,
messageId: parsedRecord.data.uuid ?? parsedRecord.data.message_id,
content: record.message.content,
messageId: record.uuid ?? record.message_id,
});
}
return parseTaskNotificationFromSystemRecord(record);
@@ -442,11 +477,12 @@ export function coerceTaskNotificationHistoryRecordToSystemMessage(
status = "completed";
}
const [taskId] = parsed.taskIds;
return {
type: "system",
subtype: "task_notification",
...(parsed.messageId ? { uuid: parsed.messageId } : {}),
...(parsed.taskId ? { task_id: parsed.taskId } : {}),
...(taskId ? { task_id: taskId } : {}),
status,
...(parsed.summary ? { summary: parsed.summary } : {}),
...(parsed.outputFile ? { output_file: parsed.outputFile } : {}),
@@ -145,6 +145,7 @@ export interface PaseoToolHostDependencies {
findWorkspaceIdForCwd?: ArchiveDependencies["findWorkspaceIdForCwd"];
worktreeManagers?: ArchiveDependencies["worktreeManagers"];
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
assertWorkspaceAutomationAllowed?: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
listActiveWorkspaces?: ArchiveDependencies["listActiveWorkspaces"];
archiveWorkspaceRecord?: ArchiveDependencies["archiveWorkspaceRecord"];
@@ -3427,11 +3428,18 @@ function archiveWorktreeDependencies(
if (!options.clearWorkspaceArchiving) {
throw new Error("Workspace archiving clearer is required to archive worktrees");
}
if (!options.assertWorkspaceAutomationAllowed) {
throw new Error("Workspace automation gate is required to archive worktrees");
}
if (!options.isCheckoutUntrusted) {
throw new Error("Checkout trust lookup is required to archive worktrees");
}
return {
paseoHome: options.paseoHome,
paseoWorktreesBaseRoot: options.worktreesRoot,
worktreeManagers: options.worktreeManagers,
workspaceArchiveOperations: options.workspaceArchiveOperations,
assertWorkspaceAutomationAllowed: options.assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: options.isCheckoutUntrusted,
github: options.github,
workspaceGitService: options.workspaceGitService,
@@ -111,6 +111,8 @@ function createHarness(overrides?: {
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(),
assertWorkspaceAutomationAllowed: vi.fn(async () => undefined),
isCheckoutUntrusted: vi.fn(async () => false),
};
const archiveByScope = vi.fn(
overrides?.archiveByScope ??
@@ -328,6 +330,8 @@ function createRealOutcomeHarness(input: {
},
markWorkspaceArchiving: () => {},
clearWorkspaceArchiving: () => {},
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(),
};
@@ -628,4 +632,68 @@ describe("archiveIfSafe", () => {
expect(archivedWorkspaceIds.has(workspace.workspaceId)).toBe(false);
expect(existsSync(worktree.worktreePath)).toBe(true);
});
test("real outcome: skips teardown commands for an unapproved cross-repository checkout", async () => {
const { tempDir, repoDir } = createGitRepo();
const markerName = "auto-archive-merge-teardown.log";
const marker = path.join(repoDir, markerName);
const fs = await import("node:fs");
fs.writeFileSync(
path.join(repoDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: [
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
],
},
}),
);
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "teardown"], {
cwd: repoDir,
stdio: "pipe",
});
const paseoHome = path.join(tempDir, ".paseo");
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, "merged-untrusted");
const workspaceId = "ws-merged-untrusted";
const archivedWorkspaceIds = new Set<string>();
const harness = createRealOutcomeHarness({
paseoHome,
repoDir,
worktreePath: worktree.worktreePath,
activeWorkspaces: [
{
workspaceId,
cwd: worktree.worktreePath,
kind: "worktree",
worktreeRoot: worktree.worktreePath,
isPaseoOwnedWorktree: true,
mainRepoRoot: repoDir,
},
],
archivedWorkspaceIds,
});
const { WorkspaceAutomationBlockedError } = await import("../workspace-automation-gate.js");
const assertWorkspaceAutomationAllowed = vi.fn(async () => {
throw new WorkspaceAutomationBlockedError({
kind: "change_request",
forge: "github",
number: 123,
headRepository: "contributor/repo",
});
});
harness.options.assertWorkspaceAutomationAllowed = assertWorkspaceAutomationAllowed;
await archiveIfSafe({
workspaceId,
snapshot: { ...createSnapshot(), cwd: worktree.worktreePath },
options: harness.options,
log: harness.log,
});
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(workspaceId);
expect(archivedWorkspaceIds.has(workspaceId)).toBe(true);
expect(existsSync(worktree.worktreePath)).toBe(false);
expect(existsSync(marker)).toBe(false);
});
});
@@ -25,7 +25,8 @@ export interface AutoArchiveArchiveOptions {
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
assertWorkspaceAutomationAllowed: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
isCheckoutUntrusted: ArchiveDependencies["isCheckoutUntrusted"];
daemonConfigStore: DaemonConfigStore;
workspaceGitService: WorkspaceGitServiceImpl;
github: ForgeService;
@@ -113,6 +114,7 @@ export async function archiveIfSafe(input: {
agentStorage: options.agentStorage,
findWorkspaceIdForCwd: options.findWorkspaceIdForCwd,
getWorkspace: options.getWorkspace,
assertWorkspaceAutomationAllowed: options.assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: options.isCheckoutUntrusted,
listActiveWorkspaces: options.listActiveWorkspaces,
archiveWorkspaceRecord: (workspaceIdToArchive, archivedAt) =>
+26 -1
View File
@@ -16,6 +16,7 @@ import { createServer as createHTTPServer, type IncomingMessage, type ServerResp
import { constants, existsSync, unlinkSync } from "fs";
import { open, rm, stat } from "fs/promises";
import { randomUUID } from "node:crypto";
import { getCachedHostMachineKind, primeHostMachineKind } from "./host-machine-kind.js";
import { getHostName } from "./host-name.js";
import path from "node:path";
import { createMcpHandler } from "@modelcontextprotocol/server";
@@ -636,6 +637,9 @@ export async function createPaseoDaemon(
rootLogger: Logger,
dependencies: PaseoDaemonDependencies = {},
): Promise<PaseoDaemon> {
// Start hardware detection at the beginning of bootstrap so it overlaps with disk/registry init
// and does not hold up the listener when probes are slow.
const hostMachineKindReady = primeHostMachineKind();
configureGitProcessPolicy(config.git ?? resolveGitProcessPolicy({ env: process.env }));
const logger = rootLogger.child({ module: "bootstrap" });
const obsoleteTimelineDirectory = path.join(config.paseoHome, "agent-timelines");
@@ -874,11 +878,13 @@ export async function createPaseoDaemon(
});
app.get("/api/status", (_req, res) => {
const machineKind = getCachedHostMachineKind();
res.json({
status: "server_info",
serverId,
hostname: getHostName(),
version: daemonVersion,
...(machineKind ? { machineKind } : {}),
listen: formatListenTarget(boundListenTarget ?? listenTarget),
});
});
@@ -1246,6 +1252,8 @@ export async function createPaseoDaemon(
logger,
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
listActiveWorkspaces: listActiveWorkspacesExternal,
getAutoArchivedChangeRequestUrl: async (workspaceId) =>
@@ -1358,6 +1366,8 @@ export async function createPaseoDaemon(
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
agentManager,
agentStorage,
@@ -1611,6 +1621,8 @@ export async function createPaseoDaemon(
workspaceGitService,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
listActiveWorkspaces: listActiveWorkspacesExternal,
@@ -1803,7 +1815,20 @@ export async function createPaseoDaemon(
const start = async () => {
let mainStarted = false;
try {
localCredential = await writeLocalCredential(config.paseoHome);
let machineKindTimeout: ReturnType<typeof setTimeout> | null = null;
const [nextLocalCredential] = await Promise.all([
writeLocalCredential(config.paseoHome),
Promise.race([
hostMachineKindReady,
new Promise<void>((resolve) => {
machineKindTimeout = setTimeout(resolve, 150);
machineKindTimeout.unref();
}),
]).finally(() => {
if (machineKindTimeout) clearTimeout(machineKindTimeout);
}),
]);
localCredential = nextLocalCredential;
if (serviceProxyListenTarget) {
const boundServiceProxyTarget = await serviceProxy.startStandalone({
listenTarget: serviceProxyListenTarget,
@@ -69,6 +69,8 @@ export function buildCheckoutStatusPayloadFromSnapshot({
behindOfOrigin: snapshot.git.behindOfOrigin ?? null,
upstreamState: snapshot.git.upstreamState,
hasRemote: snapshot.git.hasRemote,
pullRemote: snapshot.git.pullRemote,
pushRemote: snapshot.git.pushRemote,
firstPushRemote: snapshot.git.firstPushRemote,
remoteUrl: snapshot.git.remoteUrl,
...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}),
@@ -94,6 +96,8 @@ export function buildCheckoutStatusPayloadFromSnapshot({
behindOfOrigin: snapshot.git.behindOfOrigin ?? null,
upstreamState: snapshot.git.upstreamState,
hasRemote: snapshot.git.hasRemote,
pullRemote: snapshot.git.pullRemote,
pushRemote: snapshot.git.pushRemote,
firstPushRemote: snapshot.git.firstPushRemote,
remoteUrl: snapshot.git.remoteUrl,
...(snapshot.forgeWeb ? { forgeWeb: snapshot.forgeWeb } : {}),
@@ -1,74 +0,0 @@
// ACP peer that stops offering a model between daemon runs.
const readline = require("node:readline");
const sessionId = "antigravity-model-resume";
const models = process.env.AGY_TEST_RETIRED ? ["current-model", "other-model"] : ["old-model"];
let model = models[0];
const modes = {
currentModeId: "default",
availableModes: [{ id: "default", name: "Default" }],
};
function configOptions() {
return [
{
id: "model",
name: "Model",
category: "model",
type: "select",
currentValue: model,
options: models.map((value) => ({ name: value, value })),
},
];
}
function send(message) {
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n");
}
function notify(update) {
send({ method: "session/update", params: { sessionId, update } });
}
readline.createInterface({ input: process.stdin }).on("line", (line) => {
const { id, method, params } = JSON.parse(line);
switch (method) {
case "initialize":
send({
id,
result: {
protocolVersion: 1,
agentCapabilities: { loadSession: true, sessionCapabilities: { close: {} } },
},
});
break;
case "session/load":
notify({
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "A saved Antigravity reply" },
});
// Fall through to send the same selectors as session/new.
case "session/new":
notify({ sessionUpdate: "available_commands_update", availableCommands: [] });
send({ id, result: { sessionId, modes, configOptions: configOptions() } });
break;
case "session/set_config_option":
if (params.configId !== "model" || !models.includes(params.value)) {
send({
id,
error: { code: -32602, message: `Unknown model ID: ${params.value}` },
});
break;
}
model = params.value;
send({ id, result: { configOptions: configOptions() } });
break;
case "session/close":
send({ id, result: {} });
break;
default:
if (id !== undefined) {
send({ id, error: { code: -32601, message: "Method not found" } });
}
}
});
@@ -165,96 +165,6 @@ test("Antigravity creates an agent and answers a prompt with real agy", async ({
}
}, 120000);
test.each(["timeline", "reload", "resume"] as const)(
"reopens a saved Antigravity chat after model retirement through %s",
async (action) => {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-antigravity-model-resume-"));
const start = async (retired: boolean) => {
const daemon = await createTestPaseoDaemon({
paseoHomeRoot: root,
staticDir: path.join(root, "static"),
cleanup: false,
agentClients: {},
mcpEnabled: false,
builtinPlugins: new BuiltinPluginLoader(undefined, ["antigravity-provider"]),
providerOverrides: {
antigravity: {
command: [
process.execPath,
path.join(import.meta.dirname, "antigravity-model-resume-fixture.cjs"),
],
env: { AGY_TEST_RETIRED: retired ? "1" : "" },
paseoTools: { enabled: false },
},
},
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.16.0",
});
return {
client,
close: async () => {
await client.close();
await daemon.close();
},
};
};
try {
const before = await start(false);
let agent;
try {
await before.client.connect();
agent = await before.client.createAgent({
provider: "antigravity",
cwd: root,
model: "old-model",
});
expect(agent.model).toBe("old-model");
} finally {
await before.close();
}
const { client, close } = await start(true);
try {
await client.connect();
let agentId = agent.id;
if (action === "resume") {
const handle = agent.persistence;
if (!handle) throw new Error("Antigravity did not return a persistence handle");
agentId = (await client.resumeAgent(handle)).id;
} else if (action === "reload") {
await client.refreshAgent(agentId);
}
const timeline = await client.fetchAgentTimeline(agentId, { limit: 100 });
expect(timeline.entries.map(({ item }) => item)).toContainEqual(
expect.objectContaining({ type: "assistant_message", text: "A saved Antigravity reply" }),
);
expect(timeline.entries.map(({ item }) => item)).toContainEqual({
type: "notification",
level: "warning",
message:
"Saved model unavailable\nThe provider no longer offers old-model. This chat reopened with current-model.",
});
expect((await client.fetchAgent(agentId))?.agent).toMatchObject({
model: "old-model",
runtimeInfo: { model: "current-model" },
});
await expect(client.setAgentModel(agentId, "old-model")).rejects.toThrow(/old-model/);
await client.setAgentModel(agentId, "other-model");
expect((await client.fetchAgent(agentId))?.agent.model).toBe("other-model");
} finally {
await close();
}
} finally {
await rm(root, { recursive: true, force: true });
}
},
60_000,
);
test("bundled fx requires a config entry and lists models instead of its providers", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-fx-optin-"));
const record = path.join(root, "launches.txt");
@@ -0,0 +1,94 @@
import { describe, expect, it } from "vitest";
import {
classifyLinuxMachine,
classifyMacModel,
parseMacIoregProductName,
type LinuxMachineProbeInput,
} from "./host-machine-kind";
function linuxProbe(overrides: Partial<LinuxMachineProbeInput> = {}): LinuxMachineProbeInput {
return {
hasContainerMarker: false,
procVersion: null,
deviceTreeModel: null,
sysVendor: null,
productName: null,
biosVendor: null,
boardVendor: null,
chassisType: null,
...overrides,
};
}
describe("classifyMacModel", () => {
it.each([
["MacBookPro18,3", "laptop"],
["MacBookAir10,1", "laptop"],
["Macmini9,1", "mini"],
["iMac21,1", "desktop"],
["MacStudio1,1", "workstation"],
["MacPro7,1", "workstation"],
["Mac15,6", null],
["", null],
[null, null],
] as const)("maps %s to %s", (model, expected) => {
expect(classifyMacModel(model)).toBe(expected);
});
it("extracts Apple Silicon product-name from ioreg output", () => {
const ioreg = `
"model" = <"Mac15,6">
"product-name" = <"MacBook Pro">
`;
expect(classifyMacModel(parseMacIoregProductName(ioreg))).toBe("laptop");
});
});
describe("classifyLinuxMachine", () => {
it("detects containers before VM or chassis markers", () => {
expect(
classifyLinuxMachine(
linuxProbe({ hasContainerMarker: true, sysVendor: "Hetzner", chassisType: "17" }),
),
).toBe("container");
});
it("detects WSL as desktop", () => {
expect(
classifyLinuxMachine(
linuxProbe({ procVersion: "Linux version 5.15.153.1-microsoft-standard-WSL2" }),
),
).toBe("desktop");
});
it("detects single-board PCs from device-tree model", () => {
expect(
classifyLinuxMachine(linuxProbe({ deviceTreeModel: "Raspberry Pi 5 Model B Rev 1.0" })),
).toBe("board");
});
it("detects cloud VMs and hypervisors from DMI metadata", () => {
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Hetzner", productName: "vServer" }))).toBe(
"cloud",
);
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Amazon EC2" }))).toBe("cloud");
expect(classifyLinuxMachine(linuxProbe({ biosVendor: "QEMU" }))).toBe("cloud");
});
it("classifies bare-metal Linux machines by SMBIOS chassis type", () => {
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "LENOVO", chassisType: "10" }))).toBe(
"laptop",
);
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "ASUS", chassisType: "35" }))).toBe("mini");
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Dell Inc.", chassisType: "3" }))).toBe(
"desktop",
);
expect(classifyLinuxMachine(linuxProbe({ sysVendor: "Supermicro", chassisType: "23" }))).toBe(
"server",
);
});
it("returns null when no marker matches", () => {
expect(classifyLinuxMachine(linuxProbe())).toBeNull();
});
});
@@ -0,0 +1,251 @@
import { execFile } from "node:child_process";
import { access, readFile } from "node:fs/promises";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
export type HostMachineKind =
| "laptop"
| "desktop"
| "mini"
| "workstation"
| "cloud"
| "container"
| "board"
| "server";
const PROBE_TIMEOUT_MS = 1_500;
export function classifyMacModel(model: string | null | undefined): HostMachineKind | null {
const normalized = model?.trim().toLowerCase() ?? "";
if (!normalized) return null;
if (normalized.includes("macbook")) return "laptop";
if (normalized.includes("macmini") || normalized.includes("mac mini")) return "mini";
if (normalized.includes("imac")) return "desktop";
if (
normalized.includes("macstudio") ||
normalized.includes("mac studio") ||
normalized.includes("macpro") ||
normalized.includes("mac pro")
) {
return "workstation";
}
return null;
}
export interface LinuxMachineProbeInput {
hasContainerMarker: boolean;
procVersion: string | null;
deviceTreeModel: string | null;
sysVendor: string | null;
productName: string | null;
biosVendor: string | null;
boardVendor: string | null;
chassisType: string | null;
}
const BOARD_PATTERNS = [
"raspberry pi",
"orange pi",
"banana pi",
"rock pi",
"jetson",
"beaglebone",
"odroid",
"pine64",
"radxa",
] as const;
const CLOUD_OR_VM_MARKERS = [
"amazon",
"aws",
"ec2",
"google",
"gce",
"digitalocean",
"hetzner",
"linode",
"akamai",
"vultr",
"ovh",
"scaleway",
"oracle",
"qemu",
"kvm",
"vmware",
"virtualbox",
"xen",
"bochs",
"parallels",
"proxmox",
"hyper-v",
"virtual machine",
"openstack",
"upcloud",
"fly.io",
] as const;
const LAPTOP_CHASSIS_TYPES = new Set([8, 9, 10, 11, 14, 30, 31, 32]);
const DESKTOP_CHASSIS_TYPES = new Set([3, 4, 5, 6, 7, 13, 15, 16]);
const SERVER_CHASSIS_TYPES = new Set([17, 23, 25, 28, 29]);
export function classifyLinuxMachine(input: LinuxMachineProbeInput): HostMachineKind | null {
if (input.hasContainerMarker) {
return "container";
}
const procVersion = input.procVersion?.toLowerCase() ?? "";
if (procVersion.includes("microsoft") || procVersion.includes("wsl")) {
return "desktop";
}
const deviceTree = input.deviceTreeModel?.toLowerCase() ?? "";
if (deviceTree && BOARD_PATTERNS.some((pattern) => deviceTree.includes(pattern))) {
return "board";
}
const dmiText = [input.sysVendor, input.productName, input.biosVendor, input.boardVendor]
.filter((value): value is string => Boolean(value))
.join(" ")
.toLowerCase();
if (dmiText && CLOUD_OR_VM_MARKERS.some((marker) => dmiText.includes(marker))) {
return "cloud";
}
const chassis = Number.parseInt(input.chassisType?.trim() ?? "", 10);
if (Number.isInteger(chassis)) {
if (LAPTOP_CHASSIS_TYPES.has(chassis)) return "laptop";
if (chassis === 35) return "mini";
if (DESKTOP_CHASSIS_TYPES.has(chassis)) return "desktop";
if (SERVER_CHASSIS_TYPES.has(chassis)) return "server";
}
return null;
}
async function fileExists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch {
return false;
}
}
async function readTrimmedFile(path: string): Promise<string | null> {
try {
const content = (await readFile(path, "utf8")).replaceAll("\u0000", "").trim();
return content.length > 0 ? content : null;
} catch {
return null;
}
}
export function parseMacIoregProductName(output: string): string | null {
const productMatch = output.match(/"product-name"\s*=\s*<"([^"]+)">/i);
if (productMatch?.[1]?.trim()) {
return productMatch[1].trim();
}
const modelMatch = output.match(/"model"\s*=\s*<"([^"]+)">/i);
return modelMatch?.[1]?.trim() ?? null;
}
async function readMacModel(): Promise<string | null> {
// Apple Silicon Macs report generic "Mac15,6" in sysctl hw.model, while IOPlatformExpertDevice
// exposes the human product name ("MacBook Pro", "Mac mini", "Mac Studio", etc.).
try {
const { stdout } = await execFileAsync(
"/usr/sbin/ioreg",
["-rd1", "-c", "IOPlatformExpertDevice"],
{
encoding: "utf8",
timeout: PROBE_TIMEOUT_MS,
},
);
const parsed = parseMacIoregProductName(stdout);
if (parsed && classifyMacModel(parsed)) {
return parsed;
}
} catch {
// Fall back to sysctl below.
}
try {
const { stdout } = await execFileAsync("/usr/sbin/sysctl", ["-n", "hw.model"], {
encoding: "utf8",
timeout: PROBE_TIMEOUT_MS,
});
const trimmed = stdout.trim();
return trimmed || null;
} catch {
return null;
}
}
export async function detectHostMachineKind(
platform: NodeJS.Platform = process.platform,
): Promise<HostMachineKind | null> {
if (platform === "darwin") {
return classifyMacModel(await readMacModel());
}
if (platform === "linux") {
const [
hasDockerEnv,
hasContainerEnv,
procVersion,
deviceTreeModel,
sysVendor,
productName,
biosVendor,
boardVendor,
chassisType,
] = await Promise.all([
fileExists("/.dockerenv"),
fileExists("/run/.containerenv"),
readTrimmedFile("/proc/version"),
readTrimmedFile("/proc/device-tree/model"),
readTrimmedFile("/sys/class/dmi/id/sys_vendor"),
readTrimmedFile("/sys/class/dmi/id/product_name"),
readTrimmedFile("/sys/class/dmi/id/bios_vendor"),
readTrimmedFile("/sys/class/dmi/id/board_vendor"),
readTrimmedFile("/sys/class/dmi/id/chassis_type"),
]);
return classifyLinuxMachine({
hasContainerMarker: hasDockerEnv || hasContainerEnv,
procVersion,
deviceTreeModel,
sysVendor,
productName,
biosVendor,
boardVendor,
chassisType,
});
}
return null;
}
let cachedMachineKind: HostMachineKind | null | undefined;
let pendingMachineKind: Promise<HostMachineKind | null> | null = null;
export function primeHostMachineKind(): Promise<HostMachineKind | null> {
if (cachedMachineKind !== undefined) {
return Promise.resolve(cachedMachineKind);
}
if (!pendingMachineKind) {
pendingMachineKind = detectHostMachineKind()
.then((kind) => {
cachedMachineKind = kind;
return kind;
})
.catch(() => {
cachedMachineKind = null;
return null;
});
}
return pendingMachineKind;
}
export function getCachedHostMachineKind(): HostMachineKind | null {
return cachedMachineKind ?? null;
}
@@ -16,7 +16,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import pino from "pino";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { DaemonConfigStore } from "../daemon-config-store.js";
import { PluginService } from "./index.js";
import { BuiltinPluginLoader } from "./builtin/index.js";
@@ -1905,210 +1905,229 @@ export default function contribute() {
]);
}, 120_000);
it("preserves dependencies and metadata, and reloads without npm", async () => {
const home = await mkdtemp(path.join(tmpdir(), "paseo-npm-service-"));
roots.push(home);
const previousConfig = process.env.npm_config_userconfig;
const previousPath = process.env.PATH;
let home: string;
let service: PluginService;
let openService: () => PluginService;
let previousConfig: string | undefined;
let previousPath: string | undefined;
beforeEach(async () => {
home = await mkdtemp(path.join(tmpdir(), "paseo-npm-service-"));
previousConfig = process.env.npm_config_userconfig;
previousPath = process.env.PATH;
process.env.npm_config_userconfig = registry.userconfig;
const store = createStore(home);
const open = () =>
openService = () =>
bindTestSessionHost(
new PluginService(pino({ level: "silent" }), store, "0.8.0", {
managedSources: new ManagedPluginSources(home),
}),
);
let service = open();
try {
await service.start();
const installed = await service.installSource({ source: "npm:paseo-fixture-plugin@^1.0.0" });
expect(installed).toMatchObject({
id: "npm-review",
status: "running",
installation: {
identity: { kind: "npm", packageName: "paseo-fixture-plugin", pluginPath: "." },
currentRevision: "1.1.0",
},
});
expect(installed.commit).toBeUndefined();
expect(installed.remote).toBeUndefined();
expect(
service
.getLogs("npm-review")
.map((entry) => entry.message)
.join("\n"),
).toContain("dependency loaded");
const installRoot = path.dirname(path.dirname(installed.path));
expect(
JSON.parse(await readFile(path.join(home, "plugins", "sources.json"), "utf8"))[
"npm-review"
],
).toEqual({ kind: "npm" });
expect(
JSON.parse(await readFile(path.join(installRoot, "package-lock.json"), "utf8")).packages[
"node_modules/paseo-fixture-dependency"
].version,
).toBe("1.0.0");
for (const [source, id, version] of [
["npm:paseo-fixture-plugin@1.0.0", "exact", "1.0.0"],
["paseo-fixture-plugin@stable", "tag", "1.0.0"],
["npm:@paseo-fixture/review", "scoped", "2.0.0"],
]) {
expect(await service.installSource({ source, id })).toMatchObject({
id,
service = openService();
await service.start();
});
afterEach(async () => {
if (previousPath === undefined) delete process.env.PATH;
else process.env.PATH = previousPath;
if (previousConfig === undefined) delete process.env.npm_config_userconfig;
else process.env.npm_config_userconfig = previousConfig;
registry.setTag("paseo-fixture-plugin", "latest", "1.1.0");
await service.stopAllPlugins();
await rm(home, { recursive: true, force: true });
});
afterAll(async () => {
await registry?.close();
});
it("preserves dependencies and metadata, and reloads without npm", async () => {
const installed = await service.installSource({ source: "npm:paseo-fixture-plugin@^1.0.0" });
expect(installed).toMatchObject({
id: "npm-review",
status: "running",
installation: {
identity: { kind: "npm", packageName: "paseo-fixture-plugin", pluginPath: "." },
currentRevision: "1.1.0",
},
});
expect(installed.commit).toBeUndefined();
expect(installed.remote).toBeUndefined();
expect(
service
.getLogs("npm-review")
.map((entry) => entry.message)
.join("\n"),
).toContain("dependency loaded");
const installRoot = path.dirname(path.dirname(installed.path));
expect(
JSON.parse(await readFile(path.join(home, "plugins", "sources.json"), "utf8"))["npm-review"],
).toEqual({ kind: "npm" });
expect(
JSON.parse(await readFile(path.join(installRoot, "package-lock.json"), "utf8")).packages[
"node_modules/paseo-fixture-dependency"
].version,
).toBe("1.0.0");
expect(
await service.installSource({ source: "npm:@paseo-fixture/review", id: "scoped" }),
).toMatchObject({
id: "scoped",
status: "running",
installation: { currentRevision: "2.0.0" },
});
expect(registry.requests).not.toContain("/@getpaseo/plugin");
await expect(service.installSource({ source: "npm:paseo-fixture-plugin" })).rejects.toThrow(
"already configured",
);
expect(await readdir(path.join(home, "plugins", ".staging"))).toEqual([]);
await service.disablePlugin("scoped");
await service.stopAllPlugins();
const recordsPath = path.join(home, "plugins", "sources.json");
const oldRecords = JSON.parse(await readFile(recordsPath, "utf8"));
Object.assign(oldRecords["npm-review"], {
requestedSpec: "0.0.1",
version: "0.0.1",
packageName: "obsolete",
installRoot: "/obsolete",
integrity: "obsolete",
});
await writeFile(recordsPath, JSON.stringify(oldRecords));
process.env.PATH = path.join(home, "no-executables");
service = openService();
await service.start();
expect(await service.listPlugins()).toMatchObject(
expect.arrayContaining([
expect.objectContaining({
id: "npm-review",
status: "running",
installation: { currentRevision: version },
});
}
const [preview] = await service.previewUpdates({ pluginId: "exact" });
expect(preview).toMatchObject({
outcome: "update",
current: { currentRevision: "1.0.0" },
target: { version: "1.1.0" },
});
const before = (await service.listPlugins()).find((item) => item.id === "exact")!;
await service.disablePlugin("exact");
registry.setTag("paseo-fixture-plugin", "latest", "2.0.0");
const results = await service.applyUpdates([
{ ...preview!.proposal!, id: "missing-plugin" },
preview!.proposal!,
]);
expect(results).toMatchObject([
{ outcome: "error" },
{
outcome: "updated",
plugin: { enabled: false, installation: { currentRevision: "1.1.0" } },
},
]);
expect(results[1]?.plugin?.installation?.identity).toEqual(before.installation?.identity);
registry.setTag("paseo-fixture-plugin", "latest", "1.1.0");
expect(await service.applyUpdates([preview!.proposal!])).toMatchObject([
{ outcome: "error", error: expect.stringContaining("changed since review") },
]);
await service.enablePlugin("exact");
const [future] = await service.previewUpdates({
pluginId: "exact",
target: { kind: "npm", version: "future" },
});
expect(await service.applyUpdates([future!.proposal!])).toMatchObject([
{ outcome: "updated", plugin: { installation: { currentRevision: "2.0.0" } } },
]);
const [newer] = await service.previewUpdates({ pluginId: "exact" });
expect(newer).toMatchObject({
outcome: "installed-newer",
current: { currentRevision: "2.0.0" },
target: { version: "1.1.0" },
});
expect(newer?.proposal).toBeUndefined();
const [downgrade] = await service.previewUpdates({
pluginId: "exact",
target: { kind: "npm", version: "1.0.0" },
});
const wrongArtifact = {
...downgrade!.proposal!,
target: { ...downgrade!.proposal!.target, integrity: "sha512-invalid" },
};
expect(await service.applyUpdates([wrongArtifact])).toMatchObject([{ outcome: "error" }]);
expect(await service.applyUpdates([downgrade!.proposal!])).toMatchObject([
{ outcome: "updated", plugin: { installation: { currentRevision: "1.0.0" } } },
]);
expect((await service.previewUpdates({ pluginId: "exact" }))[0]?.outcome).toBe("update");
await expect(service.updateSources("exact")).rejects.toThrow("Update the client");
const prepared = await service.installSource({
source: "npm:paseo-prepared-plugin@1.0.0:nested",
});
expect(prepared).toMatchObject({ id: "prepared", status: "running" });
expect(await readFile(path.join(prepared.path, "server/generated.js"), "utf8")).toBe(
"export default 42;",
);
expect(prepared.installation).toMatchObject({ identity: { pluginPath: "nested" } });
await service.removePlugin("prepared");
expect(registry.requests).not.toContain("/@getpaseo/plugin");
await expect(service.installSource({ source: "npm:missing-plugin" })).rejects.toThrow();
await expect(
service.installSource({ source: "npm:paseo-fixture-plugin", ref: "main" }),
).rejects.toThrow("--ref is only valid for Git");
await expect(service.installSource({ source: "npm:paseo-fixture-plugin" })).rejects.toThrow(
"already configured",
);
installation: installed.installation,
}),
expect.objectContaining({ id: "scoped", enabled: false, status: "disabled" }),
]),
);
expect(await service.reloadPlugin("npm-review")).toMatchObject({
status: "running",
installation: installed.installation,
});
await expect(
service.installSource({ source: "npm:paseo-fixture-plugin", id: "missing-npm" }),
).rejects.toThrow("npm is required on the daemon host");
expect(await readdir(path.join(home, "plugins", ".staging"))).toEqual([]);
const packagePath = path.join(installed.path, "package.json");
const packageJson = await readFile(packagePath, "utf8");
await writeFile(packagePath, JSON.stringify({ ...JSON.parse(packageJson), version: "99.0.0" }));
const corrupt = (await service.listPlugins()).find((plugin) => plugin.id === "npm-review")!;
expect(corrupt.status).toBe("running");
expect(corrupt.installation).toEqual({ identity: installed.installation!.identity });
expect((await service.previewUpdates({ pluginId: "npm-review" }))[0]).toMatchObject({
outcome: "error",
error: expect.stringContaining("Installed revision is unavailable"),
});
expect(await service.reloadPlugin("npm-review")).toMatchObject({ status: "running" });
await writeFile(packagePath, packageJson);
await service.removePlugin("npm-review");
await expect(stat(installRoot)).rejects.toMatchObject({ code: "ENOENT" });
expect(
JSON.parse(await readFile(path.join(home, "plugins", "sources.json"), "utf8"))["npm-review"],
).toBeUndefined();
}, 120_000);
it("applies reviewed npm updates and downgrades", async () => {
expect(
await service.installSource({ source: "npm:paseo-fixture-plugin@1.0.0", id: "exact" }),
).toMatchObject({
id: "exact",
status: "running",
installation: { currentRevision: "1.0.0" },
});
const [preview] = await service.previewUpdates({ pluginId: "exact" });
expect(preview).toMatchObject({
outcome: "update",
current: { currentRevision: "1.0.0" },
target: { version: "1.1.0" },
});
const before = (await service.listPlugins()).find((item) => item.id === "exact")!;
await service.disablePlugin("exact");
registry.setTag("paseo-fixture-plugin", "latest", "2.0.0");
const results = await service.applyUpdates([
{ ...preview!.proposal!, id: "missing-plugin" },
preview!.proposal!,
]);
expect(results).toMatchObject([
{ outcome: "error" },
{
outcome: "updated",
plugin: { enabled: false, installation: { currentRevision: "1.1.0" } },
},
]);
expect(results[1]?.plugin?.installation?.identity).toEqual(before.installation?.identity);
registry.setTag("paseo-fixture-plugin", "latest", "1.1.0");
expect(await service.applyUpdates([preview!.proposal!])).toMatchObject([
{ outcome: "error", error: expect.stringContaining("changed since review") },
]);
await service.enablePlugin("exact");
const [future] = await service.previewUpdates({
pluginId: "exact",
target: { kind: "npm", version: "future" },
});
expect(await service.applyUpdates([future!.proposal!])).toMatchObject([
{ outcome: "updated", plugin: { installation: { currentRevision: "2.0.0" } } },
]);
const [newer] = await service.previewUpdates({ pluginId: "exact" });
expect(newer).toMatchObject({
outcome: "installed-newer",
current: { currentRevision: "2.0.0" },
target: { version: "1.1.0" },
});
expect(newer?.proposal).toBeUndefined();
const [downgrade] = await service.previewUpdates({
pluginId: "exact",
target: { kind: "npm", version: "1.0.0" },
});
const wrongArtifact = {
...downgrade!.proposal!,
target: { ...downgrade!.proposal!.target, integrity: "sha512-invalid" },
};
expect(await service.applyUpdates([wrongArtifact])).toMatchObject([{ outcome: "error" }]);
expect(await service.applyUpdates([downgrade!.proposal!])).toMatchObject([
{ outcome: "updated", plugin: { installation: { currentRevision: "1.0.0" } } },
]);
expect((await service.previewUpdates({ pluginId: "exact" }))[0]?.outcome).toBe("update");
await expect(service.updateSources("exact")).rejects.toThrow("Update the client");
}, 120_000);
it("prepares npm plugins and cleans up rejected installations", async () => {
expect(
await service.installSource({ source: "paseo-fixture-plugin@stable", id: "tag" }),
).toMatchObject({
id: "tag",
status: "running",
installation: { currentRevision: "1.0.0" },
});
const prepared = await service.installSource({
source: "npm:paseo-prepared-plugin@1.0.0:nested",
});
expect(prepared).toMatchObject({ id: "prepared", status: "running" });
expect(await readFile(path.join(prepared.path, "server/generated.js"), "utf8")).toBe(
"export default 42;",
);
expect(prepared.installation).toMatchObject({ identity: { pluginPath: "nested" } });
await service.removePlugin("prepared");
await expect(service.installSource({ source: "npm:missing-plugin" })).rejects.toThrow();
await expect(
service.installSource({ source: "npm:paseo-fixture-plugin", ref: "main" }),
).rejects.toThrow("--ref is only valid for Git");
expect(await readdir(path.join(home, "plugins", ".staging"))).toEqual([]);
for (const name of [
"bad-manifest",
"bad-build",
"bad-requirements",
"bad-code",
"bad-activation",
]) {
await expect(service.installSource({ source: `npm:${name}`, id: name })).rejects.toThrow();
expect((await service.listPlugins()).map((plugin) => plugin.id)).toEqual(["tag"]);
expect(await readdir(path.join(home, "plugins", ".staging"))).toEqual([]);
for (const name of [
"bad-manifest",
"bad-build",
"bad-requirements",
"bad-code",
"bad-activation",
]) {
await expect(service.installSource({ source: `npm:${name}`, id: name })).rejects.toThrow();
expect((await service.listPlugins()).map((plugin) => plugin.id)).toEqual([
"exact",
"npm-review",
"scoped",
"tag",
]);
expect(await readdir(path.join(home, "plugins", ".staging"))).toEqual([]);
}
await service.disablePlugin("scoped");
await service.stopAllPlugins();
const recordsPath = path.join(home, "plugins", "sources.json");
const oldRecords = JSON.parse(await readFile(recordsPath, "utf8"));
Object.assign(oldRecords["npm-review"], {
requestedSpec: "0.0.1",
version: "0.0.1",
packageName: "obsolete",
installRoot: "/obsolete",
integrity: "obsolete",
});
await writeFile(recordsPath, JSON.stringify(oldRecords));
process.env.PATH = path.join(home, "no-executables");
service = open();
await service.start();
expect(await service.listPlugins()).toMatchObject(
expect.arrayContaining([
expect.objectContaining({
id: "npm-review",
status: "running",
installation: installed.installation,
}),
expect.objectContaining({ id: "scoped", enabled: false, status: "disabled" }),
]),
);
expect(await service.reloadPlugin("npm-review")).toMatchObject({
status: "running",
installation: installed.installation,
});
await expect(
service.installSource({ source: "npm:paseo-fixture-plugin", id: "missing-npm" }),
).rejects.toThrow("npm is required on the daemon host");
expect(await readdir(path.join(home, "plugins", ".staging"))).toEqual([]);
const packagePath = path.join(installed.path, "package.json");
const packageJson = await readFile(packagePath, "utf8");
await writeFile(
packagePath,
JSON.stringify({ ...JSON.parse(packageJson), version: "99.0.0" }),
);
const corrupt = (await service.listPlugins()).find((plugin) => plugin.id === "npm-review")!;
expect(corrupt.status).toBe("running");
expect(corrupt.installation).toEqual({ identity: installed.installation!.identity });
expect((await service.previewUpdates({ pluginId: "npm-review" }))[0]).toMatchObject({
outcome: "error",
error: expect.stringContaining("Installed revision is unavailable"),
});
expect(await service.reloadPlugin("npm-review")).toMatchObject({ status: "running" });
await writeFile(packagePath, packageJson);
await service.removePlugin("npm-review");
await expect(stat(installRoot)).rejects.toMatchObject({ code: "ENOENT" });
expect(
JSON.parse(await readFile(path.join(home, "plugins", "sources.json"), "utf8"))[
"npm-review"
],
).toBeUndefined();
} finally {
process.env.PATH = previousPath;
if (previousConfig === undefined) delete process.env.npm_config_userconfig;
else process.env.npm_config_userconfig = previousConfig;
await service.stopAllPlugins();
await registry.close();
}
}, 120_000);
});
@@ -466,6 +466,9 @@ export function createPluginWorker(options: {
// The runtime re-attaches a session when the daemon drops this socket.
reconnect: { enabled: true },
transportFactory,
// The channel is a pipe to the daemon (or an in-process queue for built-in plugins); its
// loss is reported directly, so a 10 s ping would only wake both sides.
livenessHeartbeat: false,
});
paseo = createPaseoApi(daemonClient);
await daemonClient.connect();
@@ -913,6 +916,7 @@ export function createPluginWorker(options: {
if (process.argv[1] === fileURLToPath(import.meta.url)) {
let worker: ReturnType<typeof createPluginWorker> | null = null;
let closedByShutdown = false;
const handlers = new Set<(message: PluginProcessRequest) => void>();
const channel: PluginWorkerChannel = {
send(message, callback) {
@@ -926,9 +930,17 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
};
},
disconnect() {
closedByShutdown = true;
process.disconnect();
},
};
// The daemon worker owns this process through the IPC channel. When the channel closes without
// this process closing it (the worker crashed or was killed), nothing can reach the plugin any
// more, so exit instead of running on as an orphan. A normal shutdown closes the channel itself
// and lets work still in flight finish.
process.once("disconnect", () => {
if (!closedByShutdown) process.exit(0);
});
process.on("message", (raw) => {
const parsed = PluginProcessRequestSchema.safeParse(raw);
if (!worker && parsed.success && parsed.data.type === "initialize") {
@@ -7,7 +7,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import pino from "pino";
import type { ProviderEvent, ProviderRegistration } from "@getpaseo/plugin/server/provider";
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
import type { AgentStreamEvent } from "../agent/agent-sdk-types.js";
import { PluginAgentClientRegistry } from "../agent/plugin-provider.js";
import { PluginRuntime } from "./runtime.js";
@@ -1982,6 +1982,40 @@ export default function contribute(plugin: any) {
);
});
it("exits a plugin process when its channel to the daemon closes without a shutdown", async () => {
const directory = await createPlugin(
"orphaned",
// A timer keeps the process alive the way a polling plugin does.
`export default function contribute(plugin: unknown) {
void plugin;
const timer = setInterval(() => undefined, 1_000);
return () => clearInterval(timer);
}`,
);
const spawned: Array<ReturnType<typeof spawnObservedPluginProcess>> = [];
const exits: Array<Promise<number | null>> = [];
const runtime = createTestRuntime({
spawnChild: () => {
const child = spawnObservedPluginProcess(() => undefined);
exits.push(new Promise((resolve) => child.once("exit", resolve)));
spawned.push(child);
return child;
},
});
// If the process never exits (the failure this test catches), do not leave it running.
onTestFinished(() => {
for (const child of spawned) if (child.exitCode === null) child.kill("SIGKILL");
});
await runtime.startPlugin("orphaned", directory);
expect(spawned).toHaveLength(1);
// What the plugin sees when its daemon worker dies: the IPC channel closes, no shutdown request.
spawned[0]!.disconnect();
// In a real crash the daemon side is gone, so there is no runtime state left to stop here.
await expect(exits[0]).resolves.toBe(0);
});
it("reports and removes a plugin it terminated for an invalid message", async () => {
const directory = await createPlugin(
"invalid-message",
@@ -171,6 +171,8 @@ function createScheduleService(options: TestScheduleServiceOptions): ScheduleSer
markWorkspaceArchiving: () => {},
clearWorkspaceArchiving: () => {},
killTerminalsForWorkspace: async () => {},
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: options.logger,
},
{
@@ -276,6 +278,8 @@ async function createRegistryBackedScheduleWorkspaceDeps(rootDir: string): Promi
markWorkspaceArchiving: () => {},
clearWorkspaceArchiving: () => {},
killTerminalsForWorkspace: async () => {},
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: logger,
},
{
+19 -4
View File
@@ -1301,6 +1301,8 @@ export class Session {
worktreeManagers: this.pluginRuntime,
workspaceArchiveOperations: this.workspaceArchiveOperations,
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
assertWorkspaceAutomationAllowed: (workspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
isCheckoutUntrusted: (checkoutPath) =>
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
agentManager: this.agentManager,
@@ -5850,6 +5852,8 @@ export class Session {
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
killTerminalsForWorkspace: (workspaceId) =>
this.terminalController.killTerminalsForWorkspace(workspaceId),
assertWorkspaceAutomationAllowed: (workspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
isCheckoutUntrusted: (checkoutPath) =>
isCheckoutUntrusted(this.workspaceRegistry, checkoutPath),
sessionLogger: this.sessionLogger,
@@ -6557,16 +6561,19 @@ export class Session {
};
}
private async withWorkspaceCheckout<T>(workspaceId: string, run: () => Promise<T>): Promise<T> {
private async withWorkspaceCheckout<T>(
workspaceId: string,
run: (checkoutPath: string | null) => Promise<T>,
): Promise<T> {
const workspace = await this.workspaceRegistry.get(workspaceId);
if (!workspace) {
return run();
return run(null);
}
const checkoutPath = await resolveWorkspaceBackingPath(workspace, {
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
});
return this.workspaceArchiveOperations.withCheckout(checkoutPath, run);
return this.workspaceArchiveOperations.withCheckout(checkoutPath, () => run(checkoutPath));
}
private async withCheckoutForDirectory<T>(cwd: string, run: () => Promise<T>): Promise<T> {
@@ -8209,7 +8216,15 @@ export class Session {
{
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
clearAutomationBlock: (workspaceId) =>
clearWorkspaceAutomationBlock(this.workspaceRegistry, workspaceId),
this.withWorkspaceCheckout(workspaceId, async (checkoutPath) => {
const current = await this.workspaceRegistry.get(workspaceId);
if (!current || current.archivedAt) {
throw new Error(`Workspace not found: ${workspaceId}`);
}
return clearWorkspaceAutomationBlock(this.workspaceRegistry, workspaceId, {
checkoutPath,
});
}),
startWorkspaceSetup: (workspaceId, operation) =>
this.workspaceSetupRuntime.start(workspaceId, operation),
paseoHome: this.paseoHome,
@@ -10050,7 +10050,7 @@ test("workspace PR status survives session cleanup and reconnect", async () => {
branchRemoteName: "origin",
branchMergeRef: "refs/heads/feature",
upstreamStatus: { state: "none" },
firstPushRemote: null,
pushTarget: null,
pullRequestLookupTarget: { headRef: "feature" },
};
const githubStub = {
@@ -1,8 +1,9 @@
import { execFileSync } from "node:child_process";
import os from "node:os";
import path from "node:path";
import { mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync } from "node:fs";
import { afterEach, beforeEach, expect, test } from "vitest";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { getCheckoutStatus } from "../../../utils/checkout-git.js";
import {
@@ -1168,3 +1169,149 @@ test("a failed workspace unarchive write keeps agents archived and permits retry
expect((await registry.get(workspace.workspaceId))?.archivedAt).toBeNull();
expect(agentArchived).toBe(false);
});
describe("checkout approval state on open and unarchive", () => {
const sampleUntrustedSource = (number: number) => ({
kind: "change_request" as const,
forge: "github",
number,
headRepository: "contributor/repo",
});
function createCheckoutDirs(name: string) {
const sourceCwd = path.join(tmpDir, `repo-${name}`);
const worktreePath = path.join(tmpDir, `worktree-${name}`);
mkdirSync(sourceCwd, { recursive: true });
mkdirSync(worktreePath, { recursive: true });
gitRoots.add(sourceCwd);
gitRoots.add(worktreePath);
return { sourceCwd, worktreePath };
}
function addWorktreeRecord(
dirs: { sourceCwd: string; worktreePath: string },
branch: string,
untrustedSource?: ReturnType<typeof sampleUntrustedSource>,
) {
return provisioning.createWorkspaceForWorktree({
sourceCwd: dirs.sourceCwd,
repoRoot: dirs.sourceCwd,
cwd: dirs.worktreePath,
worktreeRoot: dirs.worktreePath,
branch,
baseBranch: "main",
title: null,
...(untrustedSource ? { untrustedSource } : {}),
});
}
test("unarchiving an approved workspace onto an active unapproved checkout inherits untrustedSource", async () => {
const dirs = createCheckoutDirs("unarchive-inherit");
const original = await addWorktreeRecord(dirs, "feature/approved");
await workspaceRegistry.archive(original.workspaceId, ARCHIVED_AT);
const archivedOriginal = (await workspaceRegistry.get(original.workspaceId))!;
const untrustedSource = sampleUntrustedSource(55);
await addWorktreeRecord(dirs, "contributor/pr-55", untrustedSource);
const restored = await provisioning.ensureWorkspaceRecordUnarchived(archivedOriginal);
expect(restored.archivedAt).toBeNull();
expect(restored.untrustedSource).toEqual(untrustedSource);
expect((await workspaceRegistry.get(original.workspaceId))?.untrustedSource).toEqual(
untrustedSource,
);
});
test("unarchiving an approved workspace ignores archived unapproved records on the same path", async () => {
const dirs = createCheckoutDirs("unarchive-historical");
const oldUntrusted = await addWorktreeRecord(
dirs,
"contributor/pr-56",
sampleUntrustedSource(56),
);
await workspaceRegistry.archive(oldUntrusted.workspaceId, "2026-04-01T00:00:00.000Z");
const approved = await addWorktreeRecord(dirs, "feature/fresh");
await workspaceRegistry.archive(approved.workspaceId, "2026-04-02T00:00:00.000Z");
const restored = await provisioning.ensureWorkspaceRecordUnarchived(
(await workspaceRegistry.get(approved.workspaceId))!,
);
expect(restored.archivedAt).toBeNull();
expect(restored.untrustedSource).toBeUndefined();
});
test("unarchiving an approved workspace onto a retained unapproved checkout inherits untrustedSource from checkout metadata", async () => {
const sourceCwd = path.join(tmpDir, "repo-retained-metadata");
mkdirSync(sourceCwd, { recursive: true });
execFileSync("git", ["init", "-b", "main"], { cwd: sourceCwd, stdio: "pipe" });
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
cwd: sourceCwd,
stdio: "pipe",
});
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: sourceCwd, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", "init"], {
cwd: sourceCwd,
stdio: "pipe",
});
const worktreePath = path.join(tmpDir, "worktree-retained-metadata");
execFileSync("git", ["worktree", "add", "-b", "retained-pr", worktreePath, "main"], {
cwd: sourceCwd,
stdio: "pipe",
});
const untrustedSource = sampleUntrustedSource(57);
await writePaseoWorktreeMetadata(worktreePath, {
baseRefName: "main",
untrustedSource,
});
gitRoots.add(sourceCwd);
gitRoots.add(worktreePath);
const approved = await addWorktreeRecord({ sourceCwd, worktreePath }, "feature/approved");
await workspaceRegistry.archive(approved.workspaceId, ARCHIVED_AT);
const restored = await provisioning.ensureWorkspaceRecordUnarchived(
(await workspaceRegistry.get(approved.workspaceId))!,
);
expect(restored.archivedAt).toBeNull();
expect(restored.untrustedSource).toEqual(untrustedSource);
});
test("creating a directory workspace ignores archived unapproved records on the same path", async () => {
const dirs = createCheckoutDirs("dir-reused-path");
const oldUntrusted = await addWorktreeRecord(
dirs,
"contributor/pr-58",
sampleUntrustedSource(58),
);
await workspaceRegistry.archive(oldUntrusted.workspaceId, ARCHIVED_AT);
const opened = await provisioning.createWorkspaceForDirectory(dirs.worktreePath);
expect(opened.untrustedSource).toBeUndefined();
});
test("unarchiving an old unapproved workspace onto a live approved checkout drops its stale untrustedSource", async () => {
const dirs = createCheckoutDirs("unarchive-stale-block");
const oldUntrusted = await addWorktreeRecord(
dirs,
"contributor/pr-59",
sampleUntrustedSource(59),
);
await workspaceRegistry.archive(oldUntrusted.workspaceId, ARCHIVED_AT);
const archivedOldUntrusted = (await workspaceRegistry.get(oldUntrusted.workspaceId))!;
await addWorktreeRecord(dirs, "feature/fresh-approved");
const unarchived = await provisioning.ensureWorkspaceRecordUnarchived(archivedOldUntrusted);
expect(unarchived.archivedAt).toBeNull();
expect(unarchived.untrustedSource).toBeUndefined();
expect(
(await workspaceRegistry.get(oldUntrusted.workspaceId))?.untrustedSource,
).toBeUndefined();
});
});
@@ -275,12 +275,10 @@ export function createWorkspaceProvisioningService(deps: {
? await readPaseoWorktreeMetadata(checkout.worktreeRoot ?? normalizedCwd)
: null;
const checkoutRoot = checkout.worktreeRoot ?? normalizedCwd;
const matchesCheckout = createRealpathAwarePathMatcher(checkoutRoot);
const inheritedUntrustedSource = (await workspaceRegistry.listAll()).find(
(candidate) =>
Boolean(candidate.untrustedSource) &&
matchesCheckout(candidate.worktreeRoot ?? candidate.cwd),
)?.untrustedSource;
const { untrustedSource: inheritedUntrustedSource } = await resolveCheckoutUntrustedSource(
checkoutRoot,
baseMetadata?.untrustedSource,
);
const timestamp = new Date().toISOString();
const workspace = createPersistedWorkspaceRecord({
workspaceId: context?.workspaceId ?? generateWorkspaceId(),
@@ -429,6 +427,49 @@ export function createWorkspaceProvisioningService(deps: {
).workspaceId;
}
async function resolveCheckoutUntrustedSource(
checkoutRoot: string,
knownMetadataUntrustedSource?: UntrustedWorkspaceSource,
): Promise<{ hasEvidence: boolean; untrustedSource: UntrustedWorkspaceSource | undefined }> {
const metadataUntrustedSource =
knownMetadataUntrustedSource ??
(await readPaseoWorktreeMetadata(checkoutRoot).catch(() => null))?.untrustedSource;
if (metadataUntrustedSource) {
return { hasEvidence: true, untrustedSource: metadataUntrustedSource };
}
const matchesCheckout = createRealpathAwarePathMatcher(checkoutRoot);
const active = (await workspaceRegistry.listActive()).filter((candidate) =>
matchesCheckout(candidate.worktreeRoot ?? candidate.cwd),
);
if (active.length === 0) {
return { hasEvidence: false, untrustedSource: undefined };
}
return {
hasEvidence: true,
untrustedSource: active.find((candidate) => Boolean(candidate.untrustedSource))
?.untrustedSource,
};
}
async function syncUnarchivedCheckoutUntrustedSource(
workspace: PersistedWorkspaceRecord,
): Promise<PersistedWorkspaceRecord> {
const resolved = await resolveCheckoutUntrustedSource(workspace.worktreeRoot ?? workspace.cwd);
if (!resolved.hasEvidence) {
return workspace;
}
if (resolved.untrustedSource) {
return workspace.untrustedSource
? workspace
: { ...workspace, untrustedSource: resolved.untrustedSource };
}
if (!workspace.untrustedSource) {
return workspace;
}
const { untrustedSource: _stale, ...approved } = workspace;
return approved;
}
async function resolveRestoredAutoArchiveChangeRequestUrl(
workspace: PersistedWorkspaceRecord,
): Promise<string | null> {
@@ -466,7 +507,7 @@ export function createWorkspaceProvisioningService(deps: {
updatedAt: timestamp,
});
next = {
...(placementUpdate?.workspace ?? workspace),
...(await syncUnarchivedCheckoutUntrustedSource(placementUpdate?.workspace ?? workspace)),
archivedAt: null,
autoArchivedChangeRequestUrl,
updatedAt: timestamp,
@@ -23,12 +23,14 @@ import {
} from "../../../utils/worktree-metadata.js";
import { createWorktree, deletePaseoWorktree } from "../../../utils/worktree.js";
import {
FileBackedProjectRegistry,
FileBackedWorkspaceRegistry,
createPersistedProjectRecord,
createPersistedWorkspaceRecord,
type PersistedProjectRecord,
type PersistedWorkspaceRecord,
} from "../../workspace-registry.js";
import { createWorkspaceProvisioningService } from "../workspace-provisioning/workspace-provisioning-service.js";
import { createWorkspaceRecoveryService } from "./workspace-recovery-service.js";
const NOW = "2026-07-11T10:12:30.752Z";
@@ -719,3 +721,134 @@ test("restores a user-created worktree at its recorded path outside Paseo's root
).toBe("external-feature");
expect(unarchived).toEqual([workspace.workspaceId]);
});
describe("recovery approval ownership for shared archived history", () => {
async function setupSlugReuseHistory(options: { keepLatestCheckoutOnDisk: boolean }) {
const { tempDir, repoDir } = createGitRepository();
const paseoHome = join(tempDir, "paseo-home");
const workspaceRegistry = new FileBackedWorkspaceRegistry(
join(paseoHome, "workspaces.json"),
pino({ level: "silent" }),
);
const projectRegistry = new FileBackedProjectRegistry(
join(paseoHome, "projects.json"),
pino({ level: "silent" }),
);
const provisioning = createWorkspaceProvisioningService({
unarchiveWorkspaceAgents: async () => {},
workspaceRegistry,
projectRegistry,
workspaceGitService: {
getCheckout: async (cwd) => getCheckoutStatus(cwd),
getSnapshot: async () => ({
checkout: null,
forge: { pullRequest: null, checkedAt: null, error: null },
}),
},
isDirectory: async (target) => existsSync(target) && statSync(target).isDirectory(),
logger: pino({ level: "silent" }),
});
const firstWorktree = await createWorktree({
cwd: repoDir,
worktreeSlug: "shared-slug",
source: { kind: "branch-off", branchName: "feature/older-approved", baseBranch: "main" },
paseoHome,
});
const olderApproved = await provisioning.createWorkspaceForWorktree({
sourceCwd: repoDir,
repoRoot: repoDir,
cwd: firstWorktree.worktreePath,
worktreeRoot: firstWorktree.worktreePath,
branch: firstWorktree.branchName,
baseBranch: firstWorktree.baseRef,
title: null,
isPaseoOwnedWorktree: true,
});
await workspaceRegistry.archive(olderApproved.workspaceId, "2026-04-01T00:00:00.000Z");
await deletePaseoWorktree({
cwd: repoDir,
worktreePath: firstWorktree.worktreePath,
paseoHome,
});
const untrustedSource = {
kind: "change_request" as const,
forge: "github",
number: 72,
headRepository: "contributor/repo",
};
const secondWorktree = await createWorktree({
cwd: repoDir,
worktreeSlug: "shared-slug",
source: { kind: "branch-off", branchName: "contributor/pr-72", baseBranch: "main" },
paseoHome,
});
await writePaseoWorktreeMetadata(secondWorktree.worktreePath, {
baseRefName: "main",
untrustedSource,
});
const laterUntrusted = await provisioning.createWorkspaceForWorktree({
sourceCwd: repoDir,
repoRoot: repoDir,
cwd: secondWorktree.worktreePath,
worktreeRoot: secondWorktree.worktreePath,
branch: secondWorktree.branchName,
baseBranch: secondWorktree.baseRef,
title: null,
isPaseoOwnedWorktree: true,
untrustedSource,
});
await workspaceRegistry.archive(laterUntrusted.workspaceId, "2026-04-02T00:00:00.000Z");
if (!options.keepLatestCheckoutOnDisk) {
await deletePaseoWorktree({
cwd: repoDir,
worktreePath: secondWorktree.worktreePath,
paseoHome,
});
}
const recovery = createWorkspaceRecoveryService({
paseoHome,
getWorkspace: (id) => workspaceRegistry.get(id),
getProject: (id) => projectRegistry.get(id),
isDirectory: async (target) => existsSync(target) && statSync(target).isDirectory(),
unarchiveWorkspace: async (workspace) => {
await provisioning.ensureWorkspaceRecordUnarchived(workspace);
},
});
return {
olderApproved,
untrustedSource,
worktreePath: firstWorktree.worktreePath,
workspaceRegistry,
recovery,
};
}
test("restoring a deleted approved workspace after slug reuse keeps the recreated worktree approved", async () => {
const { olderApproved, worktreePath, workspaceRegistry, recovery } =
await setupSlugReuseHistory({ keepLatestCheckoutOnDisk: false });
const result = await recovery.restore(olderApproved.workspaceId);
expect(result).toEqual({ workspaceId: olderApproved.workspaceId, action: "restore" });
const restored = await workspaceRegistry.get(olderApproved.workspaceId);
expect(restored?.archivedAt).toBeNull();
expect(restored?.untrustedSource).toBeUndefined();
expect((await readPaseoWorktreeMetadata(worktreePath))?.untrustedSource).toBeUndefined();
});
test("unarchiving onto a retained unapproved checkout inherits untrustedSource from worktree metadata", async () => {
const { olderApproved, untrustedSource, workspaceRegistry, recovery } =
await setupSlugReuseHistory({ keepLatestCheckoutOnDisk: true });
const result = await recovery.restore(olderApproved.workspaceId);
expect(result).toEqual({ workspaceId: olderApproved.workspaceId, action: "unarchive" });
const restored = await workspaceRegistry.get(olderApproved.workspaceId);
expect(restored?.archivedAt).toBeNull();
expect(restored?.untrustedSource).toEqual(untrustedSource);
});
});
@@ -5,6 +5,7 @@ import { resolveRepositoryDefaultBranch } from "../../../utils/checkout-git.js";
import { runWithRepositoryRoot } from "../../../utils/git-repository-discovery.js";
import { createRealpathAwarePathMatcher } from "../../../utils/path.js";
import { runGitCommand } from "../../../utils/run-git-command.js";
import { setPaseoWorktreeUntrustedSource } from "../../../utils/worktree-metadata.js";
import {
createWorktree,
isPaseoOwnedWorktreeCwd,
@@ -280,6 +281,9 @@ export function createWorkspaceRecoveryService(deps: {
error,
);
}
if (workspace.untrustedSource) {
await setPaseoWorktreeUntrustedSource(recreatedWorktreePath, workspace.untrustedSource);
}
return { worktreePath: recreatedWorktreePath, pluginId: restoredByPluginId };
}
@@ -26,6 +26,7 @@ import { MessageReceipts } from "./message-receipts/index.js";
import { WebSocket, WebSocketServer } from "ws";
import type { IncomingMessage, Server as HTTPServer } from "http";
import { join } from "path";
import { getCachedHostMachineKind } from "./host-machine-kind.js";
import { getHostName } from "./host-name.js";
import { randomUUID } from "node:crypto";
import { monitorEventLoopDelay } from "node:perf_hooks";
@@ -248,6 +249,8 @@ function createFallbackWorkspaceGitSnapshot(cwd: string): WorkspaceGitRuntimeSna
behindOfOrigin: null,
upstreamState: "none",
hasRemote: false,
pullRemote: null,
pushRemote: null,
firstPushRemote: null,
diffStat: null,
},
@@ -2058,12 +2061,14 @@ export class VoiceAssistantWebSocketServer {
}
private buildServerInfoStatusPayload(session: Session): ServerInfoStatusPayload {
const machineKind = getCachedHostMachineKind();
return {
status: "server_info",
protocolVersion: WS_PROTOCOL_VERSION,
serverId: this.serverId,
hostname: getHostName(),
version: this.daemonVersion,
...(machineKind ? { machineKind } : {}),
sourceId: session.getHostSourceId(),
permissions: session.getPermissions(),
// COMPAT(desktopManaged): added in v0.1.X, remove optional parsing after 2027-01-16.
@@ -7,12 +7,17 @@ import { afterEach, describe, expect, test, vi } from "vitest";
import type { ForgeService } from "../services/forge-service.js";
import { createRealpathAwarePathMatcher } from "../utils/path.js";
import { getPaseoWorktreeMetadataPath } from "../utils/worktree-metadata.js";
import {
getPaseoWorktreeMetadataPath,
readPaseoWorktreeMetadata,
setPaseoWorktreeUntrustedSource,
} from "../utils/worktree-metadata.js";
import { archiveCommand } from "./worktree/commands.js";
import { createWorktree, listPaseoWorktrees, type WorktreeConfig } from "../utils/worktree.js";
import type { ManagedAgent } from "./agent/agent-manager.js";
import type { AgentStorage, StoredAgentRecord } from "./agent/agent-storage.js";
import type { WorkspaceGitService } from "./workspace-git-service.js";
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
import {
archiveByScope,
unarchiveWorkspaceAgents,
@@ -22,7 +27,16 @@ import {
resolveWorkspaceIdAtPath,
WorkspaceArchiveCanceledError,
} from "./workspace-archive-service.js";
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
import {
assertWorkspaceAutomationAllowedForWorkspace,
clearWorkspaceAutomationBlock,
isCheckoutUntrusted,
WorkspaceAutomationBlockedError,
} from "./workspace-automation-gate.js";
import {
createPersistedWorkspaceRecord,
FileBackedWorkspaceRegistry,
} from "./workspace-registry.js";
const cleanupPaths: string[] = [];
@@ -175,6 +189,8 @@ function createArchiveDeps(input: ArchiveDepsInput): ArchiveTestDependencies {
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => {}),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: createLogger(),
activeWorkspaces: active,
archivedAgentIds,
@@ -480,6 +496,394 @@ describe("archiveByScope", () => {
expect(existsSync(marker)).toBe(false);
});
describe("teardown approval gating", () => {
const sampleBlockedSource = (number = 42) => ({
kind: "change_request" as const,
forge: "github",
number,
headRepository: "contributor/paseo",
});
async function createTeardownWorktree(slug: string, options?: { nestedRelative?: string }) {
const { tempDir, repoDir } = createGitRepo();
const markerName = `${slug}-teardown.log`;
const marker = path.join(repoDir, markerName);
const configDir = options?.nestedRelative
? path.join(repoDir, options.nestedRelative)
: repoDir;
mkdirSync(configDir, { recursive: true });
writeFileSync(
path.join(configDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: [
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
],
},
}),
);
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", `teardown ${slug}`], {
cwd: repoDir,
stdio: "pipe",
});
const paseoHome = path.join(tempDir, ".paseo");
const worktree = await createPaseoOwnedWorktree(repoDir, paseoHome, slug);
return { repoDir, paseoHome, worktreePath: worktree.worktreePath, marker };
}
function makeWorktreeWorkspace(
workspaceId: string,
fixture: { repoDir: string; worktreePath: string },
overrides: Partial<ActiveWorkspaceRef> = {},
): ActiveWorkspaceRef {
return {
workspaceId,
cwd: fixture.worktreePath,
kind: "worktree",
worktreeRoot: fixture.worktreePath,
isPaseoOwnedWorktree: true,
mainRepoRoot: fixture.repoDir,
...overrides,
};
}
test("workspace scope skips teardown when the workspace record carries untrustedSource", async () => {
const fixture = await createTeardownWorktree("untrusted-record");
const workspaceId = "ws-untrusted-record";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [
makeWorktreeWorkspace(workspaceId, fixture, { untrustedSource: sampleBlockedSource() }),
],
});
const result = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId },
requestId: "req-untrusted-record",
});
expect(result.archivedWorkspaceIds).toEqual([workspaceId]);
expect(result.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(existsSync(fixture.marker)).toBe(false);
});
test("workspace scope runs teardown for a fresh worktree reusing the path of an archived unapproved checkout", async () => {
const fixture = await createTeardownWorktree("reused-slug");
const workspaceId = "ws-fresh-reused-slug";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [makeWorktreeWorkspace(workspaceId, fixture)],
});
// Simulates an earlier archived unapproved workspace that previously used the same path.
deps.isCheckoutUntrusted = async () => true;
const result = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId },
requestId: "req-fresh-reused-slug",
});
expect(result.archivedWorkspaceIds).toEqual([workspaceId]);
expect(result.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(readFileSync(fixture.marker, "utf8")).toBe("ran");
});
test("retrying archive on an already-archived unapproved workspace does not mark a fresh worktree at the same path", async () => {
const fixture = await createTeardownWorktree("reused-after-retry");
const oldArchivedId = "ws-old-archived-unapproved";
const freshWorkspaceId = "ws-fresh-approved";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [makeWorktreeWorkspace(freshWorkspaceId, fixture)],
});
deps.getWorkspace = async (workspaceId) =>
workspaceId === oldArchivedId
? {
...makeWorktreeWorkspace(oldArchivedId, fixture, {
untrustedSource: sampleBlockedSource(),
}),
projectId: "proj-1",
archivedAt: "2026-11-24T00:00:00.000Z",
createdAt: "2026-11-24T00:00:00.000Z",
updatedAt: "2026-11-24T00:00:00.000Z",
}
: null;
deps.isCheckoutUntrusted = async () => true;
const retry = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: oldArchivedId },
requestId: "req-retry-archived",
});
expect(retry.archivedWorkspaceIds).toEqual([]);
expect(retry.removedDirectory).toBe(false);
expect(
(await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource,
).toBeUndefined();
const fresh = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: freshWorkspaceId },
requestId: "req-archive-fresh",
});
expect(fresh.archivedWorkspaceIds).toEqual([freshWorkspaceId]);
expect(fresh.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(readFileSync(fixture.marker, "utf8")).toBe("ran");
});
test("workspace scope skips teardown when retained checkout metadata carries untrustedSource", async () => {
const fixture = await createTeardownWorktree("retained-metadata");
await setPaseoWorktreeUntrustedSource(fixture.worktreePath, sampleBlockedSource(88));
const workspaceId = "ws-reopened-on-retained";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [makeWorktreeWorkspace(workspaceId, fixture)],
});
const result = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId },
requestId: "req-retained-metadata",
});
expect(result.archivedWorkspaceIds).toEqual([workspaceId]);
expect(result.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(existsSync(fixture.marker)).toBe(false);
});
test("workspace scope backfills checkout metadata when archiving a pre-upgrade unapproved worktree whose directory stays on disk", async () => {
const fixture = await createTeardownWorktree("pre-upgrade-retained");
expect(
(await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource,
).toBeUndefined();
const untrustedSource = sampleBlockedSource(91);
const blockedWorkspaceId = "ws-pre-upgrade-blocked";
const keptSiblingId = "ws-pre-upgrade-sibling";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [
makeWorktreeWorkspace(blockedWorkspaceId, fixture, { untrustedSource }),
makeWorktreeWorkspace(keptSiblingId, fixture),
],
});
const first = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: blockedWorkspaceId },
requestId: "req-pre-upgrade-first",
});
expect(first.removedDirectory).toBe(false);
expect(existsSync(fixture.marker)).toBe(false);
expect((await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource).toEqual(
untrustedSource,
);
const second = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: keptSiblingId },
requestId: "req-pre-upgrade-second",
});
expect(second.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(existsSync(fixture.marker)).toBe(false);
});
test.each(["approval-first", "archive-first"] as const)(
"serializing archive and setup approval through withCheckout preserves completed approval (%s)",
async (order) => {
const fixture = await createTeardownWorktree(`serialized-${order}`);
const untrustedSource = sampleBlockedSource(92);
const registry = new FileBackedWorkspaceRegistry(
path.join(fixture.paseoHome, "workspaces.json"),
createLogger(),
);
const operations = new WorkspaceArchiveOperations();
const now = "2026-11-24T00:00:00.000Z";
const ws1 = createPersistedWorkspaceRecord({
workspaceId: "ws-archive-target",
projectId: "proj-1",
displayName: "ws-archive-target",
cwd: fixture.worktreePath,
kind: "worktree",
worktreeRoot: fixture.worktreePath,
isPaseoOwnedWorktree: true,
mainRepoRoot: fixture.repoDir,
untrustedSource,
createdAt: now,
updatedAt: now,
});
const ws2 = createPersistedWorkspaceRecord({
workspaceId: "ws-approve-sibling",
projectId: "proj-1",
displayName: "ws-approve-sibling",
cwd: fixture.worktreePath,
kind: "worktree",
worktreeRoot: fixture.worktreePath,
isPaseoOwnedWorktree: true,
mainRepoRoot: fixture.repoDir,
untrustedSource,
createdAt: now,
updatedAt: now,
});
await registry.upsert(ws1);
await registry.upsert(ws2);
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [],
});
deps.workspaceArchiveOperations = operations;
deps.getWorkspace = (id) => registry.get(id);
deps.listActiveWorkspaces = () => registry.listActive();
deps.archiveWorkspaceRecord = async (id, archivedAt) => {
await registry.archive(id, archivedAt);
};
deps.assertWorkspaceAutomationAllowed = (id) =>
assertWorkspaceAutomationAllowedForWorkspace(registry, id);
deps.isCheckoutUntrusted = (checkoutPath) => isCheckoutUntrusted(registry, checkoutPath);
async function clearInsideCheckoutLock() {
return clearWorkspaceAutomationBlock(registry, ws2.workspaceId, {
checkoutPath: fixture.worktreePath,
});
}
if (order === "approval-first") {
const [cleared, archived] = await Promise.all([
operations.withCheckout(fixture.worktreePath, clearInsideCheckoutLock),
archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: ws1.workspaceId },
requestId: `req-${order}-ws1`,
}),
]);
expect(cleared).toBe(true);
expect(archived.removedDirectory).toBe(false);
} else {
// Pause archive mid-flight (after resolving targets, before backfill) while Run setup
// queues on the same checkout lock, ensuring approval runs after backfill and wins.
let enteredStop!: () => void;
let releaseStop!: () => void;
const stopEntered = new Promise<void>((resolve) => {
enteredStop = resolve;
});
const stopGate = new Promise<void>((resolve) => {
releaseStop = resolve;
});
deps.stopWorkspaceSetup = async () => {
enteredStop();
await stopGate;
};
const archivePromise = archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: ws1.workspaceId },
requestId: `req-${order}-ws1`,
});
await stopEntered;
const approvalPromise = operations.withCheckout(
fixture.worktreePath,
clearInsideCheckoutLock,
);
releaseStop();
const [archived, cleared] = await Promise.all([archivePromise, approvalPromise]);
expect(archived.removedDirectory).toBe(false);
expect(cleared).toBe(true);
deps.stopWorkspaceSetup = undefined;
}
expect(
(await readPaseoWorktreeMetadata(fixture.worktreePath))?.untrustedSource,
).toBeUndefined();
expect((await registry.get(ws2.workspaceId))?.untrustedSource).toBeUndefined();
const finalArchive = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: ws2.workspaceId },
requestId: `req-${order}-ws2`,
});
expect(finalArchive.removedDirectory).toBe(true);
expect(readFileSync(fixture.marker, "utf8")).toBe("ran");
},
);
test("workspace scope skips teardown when an active sibling on the same checkout is blocked", async () => {
const nestedRelative = path.join("packages", "app");
const fixture = await createTeardownWorktree("shared-blocked-sibling", { nestedRelative });
const blockedRootId = "ws-shared-blocked-root";
const nestedWorkspaceId = "ws-shared-nested";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [
makeWorktreeWorkspace(blockedRootId, fixture),
makeWorktreeWorkspace(nestedWorkspaceId, fixture, {
cwd: path.join(fixture.worktreePath, nestedRelative),
}),
],
});
deps.assertWorkspaceAutomationAllowed = async (workspaceId) => {
if (workspaceId === blockedRootId) {
throw new WorkspaceAutomationBlockedError(sampleBlockedSource());
}
};
const result = await archiveByScope(deps, {
scope: { kind: "workspace", workspaceId: nestedWorkspaceId },
requestId: "req-shared-blocked-sibling",
});
expect(result.archivedWorkspaceIds).toEqual([nestedWorkspaceId]);
expect(result.removedDirectory).toBe(false);
expect(existsSync(fixture.worktreePath)).toBe(true);
expect(existsSync(fixture.marker)).toBe(false);
});
test("worktree scope skips teardown when archiving an unrecorded worktree directory", async () => {
const fixture = await createTeardownWorktree("unrecorded-worktree");
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [],
});
const result = await archiveByScope(deps, {
scope: { kind: "worktree", targetPath: fixture.worktreePath },
requestId: "req-unrecorded-worktree",
});
expect(result.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(existsSync(fixture.marker)).toBe(false);
});
test("worktree scope skips teardown for nested siblings when any workspace on the checkout is blocked", async () => {
const nestedRelative = path.join("packages", "app");
const fixture = await createTeardownWorktree("blocked-sibling", { nestedRelative });
const rootWorkspaceId = "ws-blocked-root";
const nestedWorkspaceId = "ws-nested-sibling";
const deps = createArchiveDeps({
paseoHome: fixture.paseoHome,
activeWorkspaces: [
makeWorktreeWorkspace(rootWorkspaceId, fixture),
makeWorktreeWorkspace(nestedWorkspaceId, fixture, {
cwd: path.join(fixture.worktreePath, nestedRelative),
}),
],
});
deps.assertWorkspaceAutomationAllowed = async (workspaceId) => {
if (workspaceId === rootWorkspaceId) {
throw new WorkspaceAutomationBlockedError(sampleBlockedSource());
}
};
const result = await archiveByScope(deps, {
scope: { kind: "worktree", targetPath: fixture.worktreePath },
requestId: "req-blocked-sibling",
});
expect(result.archivedWorkspaceIds).toEqual(
expect.arrayContaining([rootWorkspaceId, nestedWorkspaceId]),
);
expect(result.removedDirectory).toBe(true);
expect(existsSync(fixture.worktreePath)).toBe(false);
expect(existsSync(fixture.marker)).toBe(false);
});
});
test("workspace scope keeps a worktree for an active workspace in a subdirectory", async () => {
const { tempDir, repoDir } = createGitRepo();
const paseoHome = path.join(tempDir, ".paseo");
@@ -21,7 +21,14 @@ import type {
} from "./workspace-registry.js";
import { createRealpathAwarePathMatcher, isRealpathInsideRoot } from "../utils/path.js";
import { runWithGitCommandPriority } from "../utils/run-git-command.js";
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
import {
readPaseoWorktreeMetadata,
setPaseoWorktreeUntrustedSource,
} from "../utils/worktree-metadata.js";
import {
WorkspaceAutomationBlockedError,
type UntrustedWorkspaceSource,
} from "./workspace-automation-gate.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
import type { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
@@ -59,8 +66,8 @@ export interface ArchiveDependencies {
clearWorkspaceArchiving: (workspaceIds: Iterable<string>) => void;
killTerminalsForWorkspace: (workspaceId: string) => Promise<void>;
stopWorkspaceSetup?: (workspaceId: string) => Promise<void>;
assertWorkspaceAutomationAllowed?: (workspaceId: string) => Promise<void>;
isCheckoutUntrusted?: (checkoutPath: string) => Promise<boolean>;
assertWorkspaceAutomationAllowed: (workspaceId: string) => Promise<void>;
isCheckoutUntrusted: (checkoutPath: string) => Promise<boolean>;
sessionLogger?: Logger;
}
@@ -128,12 +135,17 @@ interface BackingDirectory {
mainRepoRoot: string | null;
paseoWorktreesRoot: string | null;
worktreeManagerPluginId: string | null;
untrusted: boolean;
untrustedSource: UntrustedWorkspaceSource | null;
}
interface ArchiveTarget {
backing: BackingDirectory | null;
teardownTargets: Array<{ workspaceId: string | null; cwd: string }>;
teardownTargets: Array<{ workspaceId: string; cwd: string }>;
// Active workspaces sharing the resolved backing checkout when archive starts
// (including the records being archived and any active siblings). Keeps
// teardown approval scoped to the live checkout rather than historical
// archived records that previously occupied the same path.
checkoutWorkspaceIds: string[];
setupWorkspaceIds: string[];
workspaceIds: string[];
}
@@ -275,6 +287,33 @@ async function resolveArchiveCheckoutPath(
return (await resolveBackingDirectory(scope.targetPath, dependencies)).path;
}
async function listActiveWorkspacesOnBacking(
activeWorkspaces: ActiveWorkspaceRef[],
backingPath: string,
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
): Promise<ActiveWorkspaceRef[]> {
const matchesBackingDirectory = createRealpathAwarePathMatcher(backingPath);
return (
await Promise.all(
activeWorkspaces.map(async (workspace) => {
const backingDirectory = await resolveWorkspaceBackingDirectory(workspace, dependencies);
return matchesBackingDirectory(backingDirectory.path) ? workspace : null;
}),
)
).filter((workspace): workspace is ActiveWorkspaceRef => workspace !== null);
}
function firstUntrustedSource(
primary: UntrustedWorkspaceSource | null,
workspaces: ActiveWorkspaceRef[],
): UntrustedWorkspaceSource | null {
return (
primary ??
workspaces.find((workspace) => Boolean(workspace.untrustedSource))?.untrustedSource ??
null
);
}
async function resolveArchiveTarget(
dependencies: ArchiveDependencies,
scope: ArchiveScope,
@@ -291,12 +330,37 @@ async function resolveArchiveTarget(
{ workspaceId },
"Workspace not found for archive-by-scope; skipping",
);
return { backing: null, teardownTargets: [], setupWorkspaceIds: [], workspaceIds: [] };
return {
backing: null,
teardownTargets: [],
checkoutWorkspaceIds: [],
setupWorkspaceIds: [],
workspaceIds: [],
};
}
const isArchived = "archivedAt" in record && Boolean(record.archivedAt);
const backing = await resolveWorkspaceBackingDirectory(record, dependencies);
const activeOnCheckout = await listActiveWorkspacesOnBacking(
activeWorkspaces,
backing.path,
dependencies,
);
const checkoutWorkspaceIds = Array.from(
new Set([
...(isArchived ? [] : [workspaceId]),
...activeOnCheckout.map((workspace) => workspace.workspaceId),
]),
);
return {
backing: await resolveWorkspaceBackingDirectory(record, dependencies),
backing: {
...backing,
untrustedSource: firstUntrustedSource(
isArchived ? null : backing.untrustedSource,
activeOnCheckout,
),
},
teardownTargets: isArchived ? [] : [{ workspaceId, cwd: record.cwd }],
checkoutWorkspaceIds,
setupWorkspaceIds: [workspaceId],
workspaceIds: isArchived ? [] : [workspaceId],
};
@@ -304,14 +368,11 @@ async function resolveArchiveTarget(
const backing = await resolveBackingDirectory(scope.targetPath, dependencies);
const matchesBackingDirectory = createRealpathAwarePathMatcher(backing.path);
const targetWorkspaces = (
await Promise.all(
activeWorkspaces.map(async (workspace) => {
const backingDirectory = await resolveWorkspaceBackingDirectory(workspace, dependencies);
return matchesBackingDirectory(backingDirectory.path) ? workspace : null;
}),
)
).filter((workspace): workspace is ActiveWorkspaceRef => workspace !== null);
const targetWorkspaces = await listActiveWorkspacesOnBacking(
activeWorkspaces,
backing.path,
dependencies,
);
const recordedId = await dependencies.findWorkspaceIdForCwd(backing.path);
const recorded = recordedId ? await dependencies.getWorkspace?.(recordedId) : null;
const record =
@@ -320,15 +381,19 @@ async function resolveArchiveTarget(
? recorded
: null) ??
targetWorkspaces[0];
const resolvedBacking = record
? await resolveWorkspaceBackingDirectory(record, dependencies)
: backing;
return {
backing: record ? await resolveWorkspaceBackingDirectory(record, dependencies) : backing,
teardownTargets:
targetWorkspaces.length > 0
? targetWorkspaces.map((workspace) => ({
workspaceId: workspace.workspaceId,
cwd: workspace.cwd,
}))
: [{ workspaceId: null, cwd: scope.targetPath }],
backing: {
...resolvedBacking,
untrustedSource: firstUntrustedSource(null, targetWorkspaces),
},
teardownTargets: targetWorkspaces.map((workspace) => ({
workspaceId: workspace.workspaceId,
cwd: workspace.cwd,
})),
checkoutWorkspaceIds: targetWorkspaces.map((workspace) => workspace.workspaceId),
setupWorkspaceIds: targetWorkspaces.map((workspace) => workspace.workspaceId),
workspaceIds: targetWorkspaces.map((workspace) => workspace.workspaceId),
};
@@ -360,7 +425,7 @@ async function resolveWorkspaceBackingDirectory(
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
): Promise<BackingDirectory> {
const worktreeManagerPluginId = workspace.worktreeManagerPluginId ?? null;
const untrusted = Boolean(workspace.untrustedSource);
const untrustedSource = workspace.untrustedSource ?? null;
if (workspace.isPaseoOwnedWorktree === false) {
return {
path: resolve(workspace.worktreeRoot ?? workspace.cwd),
@@ -370,7 +435,7 @@ async function resolveWorkspaceBackingDirectory(
mainRepoRoot: workspace.mainRepoRoot ?? null,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
untrustedSource,
};
}
if (workspace.isPaseoOwnedWorktree && workspace.worktreeRoot && workspace.mainRepoRoot) {
@@ -382,7 +447,7 @@ async function resolveWorkspaceBackingDirectory(
mainRepoRoot: workspace.mainRepoRoot,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
untrustedSource,
};
}
if (workspace.kind !== "worktree") {
@@ -394,7 +459,7 @@ async function resolveWorkspaceBackingDirectory(
mainRepoRoot: workspace.mainRepoRoot ?? null,
paseoWorktreesRoot: null,
worktreeManagerPluginId,
untrusted,
untrustedSource,
};
}
@@ -408,7 +473,7 @@ async function resolveWorkspaceBackingDirectory(
...backing,
mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot,
worktreeManagerPluginId: worktreeManagerPluginId ?? backing.worktreeManagerPluginId,
untrusted: untrusted || backing.untrusted,
untrustedSource: untrustedSource ?? backing.untrustedSource,
};
}
@@ -429,7 +494,7 @@ async function resolveBackingDirectory(
mainRepoRoot: ownership.repoRoot ?? null,
paseoWorktreesRoot: ownership.worktreeRoot ?? null,
worktreeManagerPluginId: null,
untrusted: false,
untrustedSource: null,
};
}
@@ -509,22 +574,20 @@ async function maybeRemoveDirectory(
}
const archivedWorkspaceIdSet = new Set(archivedWorkspaceIds);
const teardownTargets = target.teardownTargets.filter(
(teardownTarget) =>
teardownTarget.workspaceId === null || archivedWorkspaceIdSet.has(teardownTarget.workspaceId),
const teardownTargets = target.teardownTargets.filter((teardownTarget) =>
archivedWorkspaceIdSet.has(teardownTarget.workspaceId),
);
const teardownPlan = await resolveCheckoutTeardownPlan(
dependencies,
backing,
teardownTargets,
target.checkoutWorkspaceIds,
);
let untrustedBacking =
backing.untrusted || Boolean(await dependencies.isCheckoutUntrusted?.(backing.path));
teardownPlan.untrustedBacking || Boolean(await dependencies.isCheckoutUntrusted(backing.path));
try {
const allowedTeardownTargets = await filterAllowedTeardownTargets(
dependencies,
teardownTargets,
);
if (allowedTeardownTargets.length < teardownTargets.length) {
untrustedBacking = true;
}
for (const teardownTarget of uniqueTeardownTargets(allowedTeardownTargets)) {
for (const teardownTarget of uniqueTeardownTargets(teardownPlan.allowedTargets)) {
request.checkpoint();
await runWorktreeTeardownCommands({
worktreePath: backing.path,
@@ -584,25 +647,66 @@ async function maybeRemoveDirectory(
}
}
async function resolveCheckoutTeardownPlan(
dependencies: ArchiveDependencies,
backing: BackingDirectory,
teardownTargets: Array<{ workspaceId: string; cwd: string }>,
checkoutWorkspaceIds: string[],
): Promise<{
allowedTargets: Array<{ workspaceId: string; cwd: string }>;
untrustedBacking: boolean;
}> {
const metadataUntrustedSource =
(await readPaseoWorktreeMetadata(backing.path).catch(() => null))?.untrustedSource ?? null;
const checkoutUntrusted = Boolean(backing.untrustedSource || metadataUntrustedSource);
const teardownGate = checkoutUntrusted
? { allowed: [] as Array<{ workspaceId: string; cwd: string }>, blockedSource: null }
: await filterAllowedTeardownTargets(dependencies, teardownTargets, checkoutWorkspaceIds);
const untrustedSourceToPersist =
teardownTargets.length === 0 || metadataUntrustedSource
? null
: (backing.untrustedSource ?? teardownGate.blockedSource);
if (untrustedSourceToPersist) {
// Runs inside workspaceArchiveOperations.withCheckout alongside Run setup approval,
// so retained pre-upgrade checkouts keep their block without racing approval clears.
await setPaseoWorktreeUntrustedSource(backing.path, untrustedSourceToPersist).catch(
() => false,
);
}
return {
allowedTargets: teardownGate.allowed,
untrustedBacking: checkoutUntrusted || teardownGate.allowed.length < teardownTargets.length,
};
}
async function filterAllowedTeardownTargets(
dependencies: ArchiveDependencies,
targets: Array<{ workspaceId: string | null; cwd: string }>,
): Promise<Array<{ workspaceId: string | null; cwd: string }>> {
const allowed: Array<{ workspaceId: string | null; cwd: string }> = [];
const blockedCwds: string[] = [];
for (const target of targets) {
targets: Array<{ workspaceId: string; cwd: string }>,
checkoutWorkspaceIds: string[],
): Promise<{
allowed: Array<{ workspaceId: string; cwd: string }>;
blockedSource: UntrustedWorkspaceSource | null;
}> {
if (targets.length === 0) {
return { allowed: [], blockedSource: null };
}
if (typeof dependencies.assertWorkspaceAutomationAllowed !== "function") {
return { allowed: [], blockedSource: null };
}
const workspaceIdsToCheck = Array.from(
new Set([...targets.map((target) => target.workspaceId), ...checkoutWorkspaceIds]),
);
for (const workspaceId of workspaceIdsToCheck) {
try {
if (target.workspaceId)
await dependencies.assertWorkspaceAutomationAllowed?.(target.workspaceId);
allowed.push(target);
await dependencies.assertWorkspaceAutomationAllowed(workspaceId);
} catch (error) {
if (!(error instanceof WorkspaceAutomationBlockedError)) throw error;
blockedCwds.push(target.cwd);
// Every workspace in checkoutWorkspaceIds shares the same backing checkout;
// if any active workspace on it is blocked, skip teardown for the checkout.
return { allowed: [], blockedSource: error.source };
}
}
return allowed.filter(
(target) => !blockedCwds.some((cwd) => createRealpathAwarePathMatcher(cwd)(target.cwd)),
);
return { allowed: targets, blockedSource: null };
}
function uniqueTeardownTargets<T extends { cwd: string }>(targets: T[]): T[] {
@@ -1,9 +1,28 @@
import { describe, expect, it } from "vitest";
import { execFileSync } from "node:child_process";
import { chmodSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
getPaseoWorktreeMetadataPath,
readPaseoWorktreeMetadata,
writePaseoWorktreeMetadata,
} from "../utils/worktree-metadata.js";
import {
WorkspaceAutomationBlockedError,
assertWorkspaceAutomationAllowed,
clearWorkspaceAutomationBlock,
formatWorkspaceAutomationBlockedMessage,
} from "./workspace-automation-gate.js";
import type { PersistedWorkspaceRecord } from "./workspace-registry.js";
const cleanupPaths: string[] = [];
afterEach(() => {
for (const target of cleanupPaths.splice(0)) {
rmSync(target, { recursive: true, force: true });
}
});
describe("workspace automation gate", () => {
it("refuses executable repository automation for a cross-repository change request", () => {
@@ -43,4 +62,96 @@ describe("workspace automation gate", () => {
}),
).toBe(`Scripts are blocked for ${noun} #42 from contributor/paseo. Run setup to allow them.`);
});
async function createUntrustedWorktreeFixture(number: number) {
const tempDir = mkdtempSync(path.join(tmpdir(), `automation-gate-${number}-`));
cleanupPaths.push(tempDir);
const repoDir = path.join(tempDir, "repo");
const worktreeDir = path.join(tempDir, "wt");
mkdirSync(repoDir, { recursive: true });
execFileSync("git", ["init", "-b", "main"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
cwd: repoDir,
stdio: "pipe",
});
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "--allow-empty", "-m", "init"], {
cwd: repoDir,
stdio: "pipe",
});
execFileSync("git", ["worktree", "add", "-b", `pr-${number}`, worktreeDir, "main"], {
cwd: repoDir,
stdio: "pipe",
});
const source = {
kind: "change_request" as const,
forge: "github",
number,
headRepository: "contributor/paseo",
};
await writePaseoWorktreeMetadata(worktreeDir, { baseRefName: "main", untrustedSource: source });
const records = new Map<string, PersistedWorkspaceRecord>([
[
"ws-1",
{
workspaceId: "ws-1",
projectId: "proj-1",
cwd: worktreeDir,
kind: "worktree",
worktreeRoot: worktreeDir,
isPaseoOwnedWorktree: true,
mainRepoRoot: repoDir,
untrustedSource: source,
createdAt: "2026-11-24T00:00:00.000Z",
updatedAt: "2026-11-24T00:00:00.000Z",
},
],
]);
const registry = {
listAll: async () => Array.from(records.values()),
update: async (
id: string,
updater: (record: PersistedWorkspaceRecord) => PersistedWorkspaceRecord,
) => {
const current = records.get(id);
if (!current) return null;
const next = updater(current);
records.set(id, next);
return next;
},
};
return { worktreeDir, source, records, registry };
}
it("clears untrustedSource from both workspace records and worktree metadata", async () => {
const { worktreeDir, records, registry } = await createUntrustedWorktreeFixture(42);
const cleared = await clearWorkspaceAutomationBlock(registry, "ws-1");
expect(cleared).toBe(true);
expect(records.get("ws-1")?.untrustedSource).toBeUndefined();
expect((await readPaseoWorktreeMetadata(worktreeDir))?.untrustedSource).toBeUndefined();
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"fails without clearing workspace records when worktree metadata cannot be written",
async () => {
const { worktreeDir, source, records, registry } = await createUntrustedWorktreeFixture(43);
const metadataDir = path.dirname(await getPaseoWorktreeMetadataPath(worktreeDir));
chmodSync(metadataDir, 0o555);
try {
await expect(clearWorkspaceAutomationBlock(registry, "ws-1")).rejects.toThrow();
expect(records.get("ws-1")?.untrustedSource).toEqual(source);
expect((await readPaseoWorktreeMetadata(worktreeDir))?.untrustedSource).toEqual(source);
} finally {
chmodSync(metadataDir, 0o755);
}
const retried = await clearWorkspaceAutomationBlock(registry, "ws-1");
expect(retried).toBe(true);
expect(records.get("ws-1")?.untrustedSource).toBeUndefined();
expect((await readPaseoWorktreeMetadata(worktreeDir))?.untrustedSource).toBeUndefined();
},
);
});
@@ -1,4 +1,5 @@
import { createRealpathAwarePathMatcher } from "../utils/path.js";
import { setPaseoWorktreeUntrustedSource } from "../utils/worktree-metadata.js";
import type { WorkspaceRegistry } from "./workspace-registry.js";
export interface UntrustedWorkspaceSource {
@@ -51,23 +52,26 @@ export async function isCheckoutUntrusted(
export async function clearWorkspaceAutomationBlock(
registry: Pick<WorkspaceRegistry, "update" | "listAll">,
workspaceId: string,
options?: { checkoutPath?: string | null },
): Promise<boolean> {
let cleared = false;
const allWorkspaces = await registry.listAll();
const target = allWorkspaces.find((record) => record.workspaceId === workspaceId);
if (!target) throw new Error(`Workspace not found: ${workspaceId}`);
const checkoutPath = options?.checkoutPath ?? target.worktreeRoot ?? target.cwd;
// Clear checkout metadata before mutating workspace records so a failed metadata
// write surfaces an error and leaves workspace records intact to retry approval.
let cleared = await setPaseoWorktreeUntrustedSource(checkoutPath, null);
const timestamp = new Date().toISOString();
const workspace = await registry.update(workspaceId, (record) => {
if (!record.untrustedSource) return record;
cleared = true;
const { untrustedSource: _removed, ...trusted } = record;
return { ...trusted, updatedAt: timestamp };
});
if (!workspace) throw new Error(`Workspace not found: ${workspaceId}`);
const checkoutPath = workspace.worktreeRoot ?? workspace.cwd;
const matchesCheckout = createRealpathAwarePathMatcher(checkoutPath);
const siblings = await registry.listAll();
for (const sibling of siblings) {
if (sibling.workspaceId === workspaceId || !sibling.untrustedSource) continue;
if (!matchesCheckout(sibling.worktreeRoot ?? sibling.cwd)) continue;
await registry.update(sibling.workspaceId, (record) => {
for (const candidate of allWorkspaces) {
if (!candidate.untrustedSource) continue;
if (
candidate.workspaceId !== workspaceId &&
!matchesCheckout(candidate.worktreeRoot ?? candidate.cwd)
) {
continue;
}
await registry.update(candidate.workspaceId, (record) => {
if (!record.untrustedSource) return record;
cleared = true;
const { untrustedSource: _removed, ...trusted } = record;
@@ -42,7 +42,7 @@ function createFacts(cwd: string): CheckoutSnapshotFacts {
branchRemoteName: null,
branchMergeRef: null,
upstreamStatus: { state: "none" },
firstPushRemote: null,
pushTarget: null,
pullRequestLookupTarget: { headRef: "main" },
};
}
@@ -73,7 +73,7 @@ function createCheckoutFacts(cwd: string): CheckoutSnapshotFacts {
branchRemoteName: null,
branchMergeRef: null,
upstreamStatus: { state: "none" },
firstPushRemote: null,
pushTarget: null,
pullRequestLookupTarget: { headRef: "main" },
};
}
@@ -1020,7 +1020,7 @@ describe("WorkspaceGitService checkout observation", () => {
branchRemoteName: null,
branchMergeRef: null,
upstreamStatus: { state: "none" },
firstPushRemote: null,
pushTarget: null,
};
});
const runGitFetch = vi.fn(async () => ({
@@ -1164,7 +1164,7 @@ describe("WorkspaceGitService checkout observation", () => {
branchRemoteName: "origin",
branchMergeRef: `refs/heads/${branch}`,
upstreamStatus: { state: "none" },
firstPushRemote: null,
pushTarget: null,
} satisfies CheckoutSnapshotFacts;
});
const getCheckoutStatus = vi.fn(async (cwd: string) =>
@@ -81,7 +81,7 @@ function createCheckoutFacts(
branchRemoteName: null,
branchMergeRef: null,
upstreamStatus: { state: "none" },
firstPushRemote: null,
pushTarget: null,
pullRequestLookupTarget: { headRef: "main" },
...overrides,
};
@@ -172,7 +172,7 @@ function createCheckoutSnapshotFacts(cwd: string): CheckoutSnapshotFacts {
branchRemoteName: "origin",
branchMergeRef: "refs/heads/main",
upstreamStatus: { state: "none" },
firstPushRemote: null,
pushTarget: null,
pullRequestLookupTarget: { headRef: "main" },
};
}
@@ -185,6 +185,8 @@ export interface WorkspaceGitRuntimeSnapshot {
behindOfOrigin: number | null;
upstreamState: UpstreamState;
hasRemote: boolean;
pullRemote: string | null;
pushRemote: string | null;
firstPushRemote: string | null;
diffStat: { additions: number; deletions: number } | null;
};
@@ -3785,6 +3787,8 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
behindOfOrigin: checkoutStatus.behindOfOrigin,
upstreamState: checkoutStatus.upstreamState,
hasRemote: checkoutStatus.hasRemote,
pullRemote: checkoutStatus.pullRemote,
pushRemote: checkoutStatus.pushRemote,
firstPushRemote: checkoutStatus.firstPushRemote,
diffStat,
};
@@ -4442,6 +4446,8 @@ function buildNotGitSnapshot(cwd: string): WorkspaceGitRuntimeSnapshot {
behindOfOrigin: null,
upstreamState: "none",
hasRemote: false,
pullRemote: null,
pushRemote: null,
firstPushRemote: null,
diffStat: null,
},
+10 -13
View File
@@ -29,6 +29,7 @@ import type { ChangeRequestCheckoutSource, FirstAgentContext } from "@getpaseo/p
import type { WorkspaceGitService } from "./workspace-git-service.js";
import { runWithRepositoryRoot } from "../utils/git-repository-discovery.js";
import { runGitCommand, runWithGitCommandPriority } from "../utils/run-git-command.js";
import { setPaseoWorktreeUntrustedSource } from "../utils/worktree-metadata.js";
import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
@@ -185,18 +186,9 @@ async function createWorktreeAtRepositoryRoot(
input,
deps,
});
if (managedWorktree) {
return {
worktree: managedWorktree,
intent,
untrustedSource,
repoRoot,
created: true,
};
}
return {
worktree: await createWorktree({
const createdWorktree =
managedWorktree ??
(await createWorktree({
cwd: repoRoot,
worktreeSlug: normalizedSlug,
worktreePath: transformed.path,
@@ -204,7 +196,12 @@ async function createWorktreeAtRepositoryRoot(
preparedBranchOff,
paseoHome: input.paseoHome,
worktreesRoot: input.worktreesRoot,
}),
}));
if (untrustedSource) {
await setPaseoWorktreeUntrustedSource(createdWorktree.worktreePath, untrustedSource);
}
return {
worktree: createdWorktree,
intent,
untrustedSource,
repoRoot,
@@ -1756,6 +1756,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => {}),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: createLogger(),
},
{
@@ -1832,6 +1834,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => {}),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: createLogger(),
},
{
@@ -1909,6 +1913,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => {}),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: createLogger(),
},
{
@@ -1982,6 +1988,8 @@ describe("handlePaseoWorktreeArchiveRequest worktree scope", () => {
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => {}),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: createLogger(),
};
@@ -1,6 +1,6 @@
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { delimiter, join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
createCachedCliPathResolver,
@@ -70,6 +70,44 @@ exit 1
}),
).resolves.toBe(false);
});
it("invokes the resolved executable path instead of re-searching PATH by bare name", async () => {
const originalPath = process.env.PATH;
const earlierDir = join(tempDir, "earlier-bin");
const workingDir = join(tempDir, "working-bin");
mkdirSync(earlierDir);
mkdirSync(workingDir);
const shadowingCli = join(earlierDir, "forge-probe-cli");
const workingCli = join(workingDir, "forge-probe-cli");
writeFileSync(
workingCli,
`#!/bin/sh
if [ "$1" = "--version" ]; then
printf '#!/bin/sh\\nexit 1\\n' > "${shadowingCli}"
chmod 755 "${shadowingCli}"
exit 0
fi
if [ "$1" = "auth" ] && [ "$2" = "status" ] && [ "$3" = "--hostname" ] && [ "$4" = "git.acme.internal" ]; then
exit 0
fi
exit 1
`,
);
chmodSync(workingCli, 0o755);
process.env.PATH = [earlierDir, workingDir, originalPath].filter(Boolean).join(delimiter);
try {
await expect(
probeHostViaCliAuthStatus({
cli: "forge-probe-cli",
host: "git.acme.internal",
}),
).resolves.toBe(true);
} finally {
process.env.PATH = originalPath;
}
});
});
describe.skipIf(isPlatform("win32"))("createForgeCliRunner", () => {
@@ -138,6 +176,264 @@ describe.skipIf(isPlatform("win32"))("createForgeCliRunner", () => {
expect(normalized).toBeInstanceOf(FakeCommandError);
expect((normalized as FakeCommandError).stderr).toMatch(/timed out after 100ms/);
});
it("executes the provided executablePath instead of re-resolving binary from PATH", async () => {
const originalPath = process.env.PATH;
const pathDir = join(tempDir, "path-bin");
const resolvedDir = join(tempDir, "resolved-bin");
mkdirSync(pathDir);
mkdirSync(resolvedDir);
const pathCli = join(pathDir, "forge-cli-test");
writeFileSync(pathCli, "#!/bin/sh\necho from-path\n");
chmodSync(pathCli, 0o755);
const resolvedCli = join(resolvedDir, "forge-cli-test");
writeFileSync(resolvedCli, "#!/bin/sh\necho from-resolved\n");
chmodSync(resolvedCli, 0o755);
const runner = createForgeCliRunner({
binary: "forge-cli-test",
envOverlay: {},
timeoutMs: 2_000,
isAuthFailureText: () => false,
errorClasses: {
isAlreadyClassified: () => false,
isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError,
createAuthError: (stderr) => new Error(`auth: ${stderr}`),
createMissingError: () => new Error("missing"),
createCommandError: (params) => new FakeCommandError(params),
},
});
process.env.PATH = [pathDir, originalPath].filter(Boolean).join(delimiter);
try {
const result = await runner.run(["status"], {
cwd: tempDir,
executablePath: resolvedCli,
});
expect(result.stdout.trim()).toBe("from-resolved");
} finally {
process.env.PATH = originalPath;
}
});
it("resolves a bare binary via resolveExecutablePath when executablePath is omitted", async () => {
const originalPath = process.env.PATH;
const pathDir = join(tempDir, "path-bin");
const resolvedDir = join(tempDir, "resolved-bin");
mkdirSync(pathDir);
mkdirSync(resolvedDir);
const pathCli = join(pathDir, "forge-cli-default");
writeFileSync(pathCli, "#!/bin/sh\necho from-path\n");
chmodSync(pathCli, 0o755);
const resolvedCli = join(resolvedDir, "forge-cli-default");
writeFileSync(resolvedCli, "#!/bin/sh\necho from-resolver\n");
chmodSync(resolvedCli, 0o755);
const runner = createForgeCliRunner({
binary: "forge-cli-default",
envOverlay: {},
timeoutMs: 2_000,
isAuthFailureText: () => false,
resolveExecutablePath: async () => resolvedCli,
errorClasses: {
isAlreadyClassified: () => false,
isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError,
createAuthError: (stderr) => new Error(`auth: ${stderr}`),
createMissingError: () => new Error("missing"),
createCommandError: (params) => new FakeCommandError(params),
},
});
process.env.PATH = [pathDir, originalPath].filter(Boolean).join(delimiter);
try {
const result = await runner.run(["status"], { cwd: tempDir });
expect(result.stdout.trim()).toBe("from-resolver");
} finally {
process.env.PATH = originalPath;
}
});
it("throws createMissingError when a bare binary cannot be resolved", async () => {
const runner = createForgeCliRunner({
binary: "forge-cli-uninstalled",
envOverlay: {},
timeoutMs: 2_000,
isAuthFailureText: () => false,
resolveExecutablePath: async () => null,
errorClasses: {
isAlreadyClassified: () => false,
isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError,
createAuthError: (stderr) => new Error(`auth: ${stderr}`),
createMissingError: () => new Error("forge-cli-missing"),
createCommandError: (params) => new FakeCommandError(params),
},
});
await expect(runner.run(["status"], { cwd: tempDir })).rejects.toThrow("forge-cli-missing");
});
it("re-resolves and retries once when the cached executable is removed from PATH", async () => {
const originalPath = process.env.PATH;
const firstDir = join(tempDir, "first-bin");
const secondDir = join(tempDir, "second-bin");
mkdirSync(firstDir);
mkdirSync(secondDir);
const firstCli = join(firstDir, "forge-cli-fallback");
writeFileSync(firstCli, "#!/bin/sh\necho from-first\n");
chmodSync(firstCli, 0o755);
const secondCli = join(secondDir, "forge-cli-fallback");
writeFileSync(secondCli, "#!/bin/sh\necho from-second\n");
chmodSync(secondCli, 0o755);
const runner = createForgeCliRunner({
binary: "forge-cli-fallback",
envOverlay: {},
timeoutMs: 2_000,
isAuthFailureText: () => false,
errorClasses: {
isAlreadyClassified: () => false,
isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError,
createAuthError: (stderr) => new Error(`auth: ${stderr}`),
createMissingError: () => new Error("missing"),
createCommandError: (params) => new FakeCommandError(params),
},
});
process.env.PATH = [firstDir, secondDir, originalPath].filter(Boolean).join(delimiter);
try {
await expect(runner.run(["status"], { cwd: tempDir })).resolves.toMatchObject({
stdout: "from-first\n",
});
rmSync(firstCli);
await expect(runner.run(["status"], { cwd: tempDir })).resolves.toMatchObject({
stdout: "from-second\n",
});
} finally {
process.env.PATH = originalPath;
}
});
it("re-resolves and retries once when the cached executable loses execute permission", async () => {
const originalPath = process.env.PATH;
const firstDir = join(tempDir, "first-perm-bin");
const secondDir = join(tempDir, "second-perm-bin");
mkdirSync(firstDir);
mkdirSync(secondDir);
const firstCli = join(firstDir, "forge-cli-perm");
writeFileSync(firstCli, "#!/bin/sh\necho from-first\n");
chmodSync(firstCli, 0o755);
const secondCli = join(secondDir, "forge-cli-perm");
writeFileSync(secondCli, "#!/bin/sh\necho from-second\n");
chmodSync(secondCli, 0o755);
const runner = createForgeCliRunner({
binary: "forge-cli-perm",
envOverlay: {},
timeoutMs: 2_000,
isAuthFailureText: () => false,
errorClasses: {
isAlreadyClassified: () => false,
isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError,
createAuthError: (stderr) => new Error(`auth: ${stderr}`),
createMissingError: () => new Error("missing"),
createCommandError: (params) => new FakeCommandError(params),
},
});
process.env.PATH = [firstDir, secondDir, originalPath].filter(Boolean).join(delimiter);
try {
await expect(runner.run(["status"], { cwd: tempDir })).resolves.toMatchObject({
stdout: "from-first\n",
});
chmodSync(firstCli, 0o644);
await expect(runner.run(["status"], { cwd: tempDir })).resolves.toMatchObject({
stdout: "from-second\n",
});
} finally {
process.env.PATH = originalPath;
}
});
});
describe.runIf(isPlatform("win32"))("createForgeCliRunner (Windows)", () => {
let tempDir: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "forge-cli-win-"));
});
afterEach(() => {
rmSync(tempDir, { recursive: true, force: true });
});
class FakeCommandError extends Error {
readonly stderr: string;
constructor(params: { stderr: string }) {
super("command failed");
this.stderr = params.stderr;
}
}
it("runs the resolved executable instead of a cwd-local script and preserves percent-delimited args", async () => {
const originalPath = process.env.PATH;
const originalVar = process.env.PASEO_FORGE_ARG_LITERAL;
const binDir = join(tempDir, "bin");
const repoDir = join(tempDir, "repo");
mkdirSync(binDir);
mkdirSync(repoDir);
const installedExe = join(binDir, "forge-win-cli.exe");
copyFileSync(process.execPath, installedExe);
writeFileSync(join(repoDir, "forge-win-cli.cmd"), "@echo off\r\necho from-cwd\r\n");
const runner = createForgeCliRunner({
binary: "forge-win-cli",
envOverlay: {},
timeoutMs: 5_000,
isAuthFailureText: () => false,
errorClasses: {
isAlreadyClassified: () => false,
isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError,
createAuthError: (stderr) => new Error(`auth: ${stderr}`),
createMissingError: () => new Error("missing"),
createCommandError: (params) => new FakeCommandError(params),
},
});
process.env.PATH = [binDir, originalPath].filter(Boolean).join(delimiter);
process.env.PASEO_FORGE_ARG_LITERAL = "expanded-env-value";
try {
const result = await runner.run(
[
"-e",
"process.stdout.write(JSON.stringify(process.argv.slice(1)))",
"--",
"%PASEO_FORGE_ARG_LITERAL%",
"query=query Test {\n viewer { login }\n}",
],
{ cwd: repoDir },
);
expect(JSON.parse(result.stdout)).toEqual([
"%PASEO_FORGE_ARG_LITERAL%",
"query=query Test {\n viewer { login }\n}",
]);
} finally {
process.env.PATH = originalPath;
if (originalVar === undefined) {
delete process.env.PASEO_FORGE_ARG_LITERAL;
} else {
process.env.PASEO_FORGE_ARG_LITERAL = originalVar;
}
}
});
});
describe("createCachedCliPathResolver", () => {
@@ -175,4 +471,21 @@ describe("createCachedCliPathResolver", () => {
await Promise.all([resolveCliPath(), resolveCliPath(), resolveCliPath()]);
expect(calls).toBe(1);
});
it("re-resolves after invalidate matches the cached path and ignores mismatched paths", async () => {
let calls = 0;
const resolveCliPath = createCachedCliPathResolver(async () => {
calls += 1;
return calls === 1 ? "/first/bin/forge-cli" : "/second/bin/forge-cli";
});
await expect(resolveCliPath()).resolves.toBe("/first/bin/forge-cli");
resolveCliPath.invalidate("/other/bin/forge-cli");
await expect(resolveCliPath()).resolves.toBe("/first/bin/forge-cli");
expect(calls).toBe(1);
resolveCliPath.invalidate("/first/bin/forge-cli");
await expect(resolveCliPath()).resolves.toBe("/second/bin/forge-cli");
expect(calls).toBe(2);
});
});
+135 -11
View File
@@ -1,3 +1,4 @@
import { access } from "node:fs/promises";
import { z } from "zod";
import { findExecutable } from "../executable-resolution/executable-resolution.js";
import { runGitCommand } from "../utils/run-git-command.js";
@@ -59,6 +60,7 @@ interface ProbeHostViaCliAuthStatusOptions {
export interface ForgeCliRunnerOptions {
cwd: string;
envOverlay?: Record<string, string>;
executablePath?: string;
}
export interface ForgeCliRunnerResult {
@@ -85,6 +87,7 @@ export interface CreateForgeCliRunnerOptions {
timeoutMs: number;
isAuthFailureText: (text: string) => boolean;
errorClasses: ForgeCliRunnerErrorClasses;
resolveExecutablePath?: () => Promise<string | null>;
}
export interface ForgeCliRunnerFactory {
@@ -95,6 +98,48 @@ export interface ForgeCliRunnerFactory {
) => Error;
}
function hasPathSeparator(value: string): boolean {
return value.includes("/") || value.includes("\\");
}
const UNLAUNCHABLE_EXECUTABLE_ERROR_CODES = new Set<unknown>([
"ENOENT",
"EACCES",
"ENOEXEC",
"UNKNOWN",
]);
function isWindowsBatchScript(executablePath: string): boolean {
if (process.platform !== "win32") {
return false;
}
const lower = executablePath.toLowerCase();
return lower.endsWith(".cmd") || lower.endsWith(".bat");
}
async function isUnlaunchableExecutableError(
error: unknown,
executablePath: string,
): Promise<boolean> {
if (
typeof error === "object" &&
error !== null &&
"code" in error &&
UNLAUNCHABLE_EXECUTABLE_ERROR_CODES.has((error as { code?: unknown }).code)
) {
return true;
}
if (!isWindowsBatchScript(executablePath)) {
return false;
}
try {
await access(executablePath);
return false;
} catch {
return true;
}
}
/**
* Shared shape behind the gh/glab/tea CLI adapters: an exec wrapper (10MB
* maxBuffer, per-call env overlay merged over the binary's defaults, a
@@ -102,13 +147,41 @@ export interface ForgeCliRunnerFactory {
* trio. The three adapters differ only in the params passed here.
*/
export function createForgeCliRunner(options: CreateForgeCliRunnerOptions): ForgeCliRunnerFactory {
const run: ForgeCliRunner = (args, runOptions) =>
execCommand(options.binary, args, {
const resolveBinaryPath = createCachedCliPathResolver(
options.resolveExecutablePath ?? (() => findExecutable(options.binary)),
);
function execResolved(
command: string,
args: string[],
runOptions: ForgeCliRunnerOptions,
): Promise<ForgeCliRunnerResult> {
return execCommand(command, args, {
cwd: runOptions.cwd,
envOverlay: { ...options.envOverlay, ...runOptions.envOverlay },
maxBuffer: 10 * 1024 * 1024,
timeout: options.timeoutMs,
});
}
const run: ForgeCliRunner = async (args, runOptions) => {
const candidate = runOptions.executablePath ?? options.binary;
if (hasPathSeparator(candidate)) {
return execResolved(candidate, args, runOptions);
}
if (candidate === options.binary) {
return runWithResolvedCliPath({
resolvePath: resolveBinaryPath,
createMissingError: options.errorClasses.createMissingError,
run: (command) => execResolved(command, args, runOptions),
});
}
const resolved = await findExecutable(candidate);
if (!resolved) {
throw options.errorClasses.createMissingError();
}
return execResolved(resolved, args, runOptions);
};
function normalizeError(
error: unknown,
@@ -179,37 +252,88 @@ export class ForgeCommandError extends Error {
}
}
export interface CachedCliPathResolver {
(): Promise<string | null>;
invalidate(expectedPath?: string): void;
}
/**
* Memoize a CLI path resolver (`findExecutable`) for the lifetime of a service
* instance. A found path is cached permanently; a miss (or a rejected probe)
* evicts the cache so a CLI installed after the daemon started is picked up
* on the next call instead of requiring a restart. Concurrent callers during
* resolution share the same in-flight promise.
* instance. A found path stays cached until invalidated (for example, when the
* binary disappears at launch time); a miss or rejected probe evicts the cache
* so a CLI installed after the daemon started is picked up on the next call.
* Concurrent callers during resolution share the same in-flight promise.
*/
export function createCachedCliPathResolver(
resolve: () => Promise<string | null>,
): () => Promise<string | null> {
): CachedCliPathResolver {
let pending: Promise<string | null> | null = null;
return function resolveCliPath(): Promise<string | null> {
let resolvedPath: string | null = null;
const resolveCliPath = function resolveCliPath(): Promise<string | null> {
if (pending) {
return pending;
}
const current: Promise<string | null> = resolve()
.then((path) => {
if (path === null && pending === current) {
pending = null;
if (pending === current) {
resolvedPath = path;
if (path === null) {
pending = null;
}
}
return path;
})
.catch((error: unknown) => {
if (pending === current) {
resolvedPath = null;
pending = null;
}
throw error;
});
pending = current;
return current;
} as CachedCliPathResolver;
resolveCliPath.invalidate = (expectedPath?: string) => {
if (expectedPath === undefined || resolvedPath === expectedPath) {
resolvedPath = null;
pending = null;
}
};
return resolveCliPath;
}
/**
* Execute an operation with a cached CLI executable path, invalidating and
* re-resolving once if the previously resolved executable disappeared from disk.
*/
export async function runWithResolvedCliPath<T>(options: {
resolvePath: CachedCliPathResolver;
createMissingError: () => Error;
run: (executablePath: string) => Promise<T>;
}): Promise<T> {
const executablePath = await options.resolvePath();
if (!executablePath) {
throw options.createMissingError();
}
try {
return await options.run(executablePath);
} catch (error) {
if (!(await isUnlaunchableExecutableError(error, executablePath))) {
throw error;
}
options.resolvePath.invalidate(executablePath);
const refreshedPath = await options.resolvePath();
if (!refreshedPath) {
throw options.createMissingError();
}
if (refreshedPath === executablePath) {
throw error;
}
return options.run(refreshedPath);
}
}
export function bufferOrStringToString(value: unknown): string {
@@ -304,7 +428,7 @@ export async function probeHostViaCliAuthStatus(
return false;
}
try {
await execCommand(options.cli, ["auth", "status", "--hostname", options.host], {
await execCommand(cliPath, ["auth", "status", "--hostname", options.host], {
envOverlay: options.envOverlay,
timeout: CLI_AUTH_PROBE_TIMEOUT_MS,
});
@@ -1,3 +1,6 @@
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { delimiter, join } from "node:path";
import { describe, expect, it } from "vitest";
import type { PullRequestCommandStatus, PullRequestTimelineItem } from "./forge-service.js";
@@ -5,11 +8,13 @@ import {
type CreateGiteaServiceOptions,
createGiteaService,
detectGiteaFamilySoftware,
probeGiteaHost,
TeaAuthenticationError,
TeaCommandError,
type TeaCommandResult,
type TeaCommandRunner,
} from "./gitea-service.js";
import { isPlatform } from "../test-utils/platform.js";
type Responder = (args: string[]) => TeaCommandResult | Promise<TeaCommandResult>;
@@ -3304,3 +3309,95 @@ describe("detectGiteaFamilySoftware", () => {
expect(software).toBe("gitea");
});
});
describe("Gitea CLI executable resolution", () => {
it("forwards the resolved tea executablePath to the command runner", async () => {
const seenExecutablePaths: Array<string | undefined> = [];
const service = createGiteaService({
resolveTeaPath: async () => "/opt/tea-cli/bin/tea",
resolveRemoteUrl: async () => "https://gitea.com/example-user/sample-repo.git",
runner: async (_args, options) => {
seenExecutablePaths.push(options.executablePath);
return ok("[]");
},
});
await service.searchIssuesAndPrs({ cwd: "/repo", query: "sample", kinds: ["github-pr"] });
expect(seenExecutablePaths).toEqual(["/opt/tea-cli/bin/tea"]);
});
it("re-resolves tea and retries when the previously cached executable disappears", async () => {
let availablePath = "/first/bin/tea";
const seenExecutablePaths: Array<string | undefined> = [];
const service = createGiteaService({
resolveTeaPath: async () => availablePath,
resolveRemoteUrl: async () => "https://gitea.com/example-user/sample-repo.git",
runner: async (_args, options) => {
seenExecutablePaths.push(options.executablePath);
if (options.executablePath !== availablePath) {
const error = new Error("spawn ENOENT") as NodeJS.ErrnoException;
error.code = "ENOENT";
throw error;
}
return ok("[]");
},
});
await service.searchIssuesAndPrs({ cwd: "/repo", query: "first", kinds: ["github-pr"] });
availablePath = "/second/bin/tea";
const secondResult = await service.searchIssuesAndPrs({
cwd: "/repo",
query: "second",
kinds: ["github-pr"],
});
expect(secondResult.featuresEnabled).toBe(true);
expect(seenExecutablePaths).toEqual(["/first/bin/tea", "/first/bin/tea", "/second/bin/tea"]);
});
it.skipIf(isPlatform("win32"))(
"probeGiteaHost and detectGiteaFamilySoftware invoke the resolved tea executable",
async () => {
const originalPath = process.env.PATH;
const tempDir = mkdtempSync(join(tmpdir(), "gitea-probe-cli-"));
const earlierDir = join(tempDir, "earlier-bin");
const workingDir = join(tempDir, "working-bin");
mkdirSync(earlierDir);
mkdirSync(workingDir);
const shadowingTea = join(earlierDir, "tea");
const workingTea = join(workingDir, "tea");
writeFileSync(
workingTea,
`#!/bin/sh
if [ "$1" = "--version" ]; then
printf '#!/bin/sh\\nexit 1\\n' > "${shadowingTea}"
chmod 755 "${shadowingTea}"
exit 0
fi
if [ "$1" = "login" ] && [ "$2" = "list" ]; then
printf '[{"name":"forge.acme.it","url":"https://forge.acme.it"}]'
exit 0
fi
if [ "$1" = "api" ]; then
printf '{"version":"1.0+gitea"}'
printf 'HTTP/1.1 200 OK\\n' >&2
exit 0
fi
exit 1
`,
);
chmodSync(workingTea, 0o755);
process.env.PATH = [earlierDir, workingDir, originalPath].filter(Boolean).join(delimiter);
try {
await expect(probeGiteaHost("forge.acme.it")).resolves.toBe(true);
rmSync(shadowingTea, { force: true });
await expect(detectGiteaFamilySoftware("forge.acme.it")).resolves.toBe("forgejo");
} finally {
process.env.PATH = originalPath;
rmSync(tempDir, { recursive: true, force: true });
}
},
);
});
+22 -13
View File
@@ -18,6 +18,7 @@ import {
CLI_AUTH_PROBE_TIMEOUT_MS,
defaultResolveRemoteUrl,
parseCliJsonOutput,
runWithResolvedCliPath,
ForgeCommandError,
type ForgeCommandFailureParams,
} from "./forge-cli-command.js";
@@ -137,6 +138,7 @@ export class TeaCommandError extends ForgeCommandError {
export interface TeaCommandRunnerOptions {
cwd: string;
envOverlay?: Record<string, string>;
executablePath?: string;
}
export interface TeaCommandResult {
@@ -1030,7 +1032,7 @@ export async function probeGiteaHost(host: string): Promise<boolean> {
return false;
}
try {
const { stdout } = await execCommand("tea", ["login", "list", "-o", "json"], {
const { stdout } = await execCommand(teaPath, ["login", "list", "-o", "json"], {
envOverlay: TEA_ENV,
timeout: CLI_AUTH_PROBE_TIMEOUT_MS,
});
@@ -1061,12 +1063,19 @@ export interface DetectGiteaFamilyOptions {
runTea?: TeaApiRunner;
}
async function defaultRunTea(args: string[]): Promise<{ stdout: string; stderr: string }> {
const { stdout, stderr } = await execCommand("tea", args, {
envOverlay: TEA_ENV,
timeout: GITEA_SOFTWARE_PROBE_TIMEOUT_MS,
});
return { stdout, stderr };
function createDefaultRunTea(): TeaApiRunner {
const resolveTea = createCachedCliPathResolver(resolveTeaPath);
return async (args: string[]): Promise<{ stdout: string; stderr: string }> => {
const teaPath = await resolveTea();
if (!teaPath) {
throw new TeaCliMissingError();
}
const { stdout, stderr } = await execCommand(teaPath, args, {
envOverlay: TEA_ENV,
timeout: GITEA_SOFTWARE_PROBE_TIMEOUT_MS,
});
return { stdout, stderr };
};
}
const HTTP_STATUS_LINE = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/m;
@@ -1129,7 +1138,7 @@ export async function detectGiteaFamilySoftware(
host: string,
options: DetectGiteaFamilyOptions = {},
): Promise<GiteaFamilySoftware> {
const runTea = options.runTea ?? defaultRunTea;
const runTea = options.runTea ?? createDefaultRunTea();
const viaTea = await probeForgejoNamespaceByTea(host, runTea);
if (viaTea !== null) {
@@ -1208,12 +1217,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
args: string[],
runOptions: TeaCommandRunnerOptions,
): Promise<TeaCommandResult> {
const teaPath = await resolveTea();
if (!teaPath) {
throw new TeaCliMissingError();
}
try {
return await runner(args, runOptions);
return await runWithResolvedCliPath({
resolvePath: resolveTea,
createMissingError: () => new TeaCliMissingError(),
run: (teaPath) => runner(args, { ...runOptions, executablePath: teaPath }),
});
} catch (error) {
throw teaCliRunner.normalizeError(error, { args: redactTeaArgs(args), cwd: runOptions.cwd });
}
@@ -66,11 +66,11 @@ describe("GitHub repository search", () => {
"--limit",
"8",
],
options: { cwd: "/tmp" },
options: { cwd: "/tmp", executablePath: "/usr/bin/gh" },
},
{
args: ["config", "get", "git_protocol", "--host", "github.com"],
options: { cwd: "/tmp" },
options: { cwd: "/tmp", executablePath: "/usr/bin/gh" },
},
]);
});
@@ -123,11 +123,11 @@ describe("GitHub repository search", () => {
"--order",
"desc",
],
options: { cwd: "/tmp" },
options: { cwd: "/tmp", executablePath: "/usr/bin/gh" },
},
{
args: ["config", "get", "git_protocol", "--host", "github.com"],
options: { cwd: "/tmp" },
options: { cwd: "/tmp", executablePath: "/usr/bin/gh" },
},
]);
});
@@ -5341,3 +5341,47 @@ it("skips pagination after the last exact observer releases its PR", async () =>
vi.useRealTimers();
}
});
it("forwards the resolved gh executablePath to the command runner", async () => {
const seenExecutablePaths: Array<string | undefined> = [];
const service = createGitHubService({
resolveGhPath: async () => "/opt/github-cli/bin/gh",
resolveRepoHost: async () => null,
runner: async (_args, options) => {
seenExecutablePaths.push(options.executablePath);
return { stdout: "[]", stderr: "" };
},
});
await service.searchIssuesAndPrs({ cwd: "/repo", query: "test", kinds: ["github-issue"] });
expect(seenExecutablePaths).toEqual(["/opt/github-cli/bin/gh"]);
});
it("re-resolves gh and retries when the previously cached executable disappears", async () => {
let availablePath = "/first/bin/gh";
const seenExecutablePaths: Array<string | undefined> = [];
const service = createGitHubService({
resolveGhPath: async () => availablePath,
resolveRepoHost: async () => null,
runner: async (_args, options) => {
seenExecutablePaths.push(options.executablePath);
if (options.executablePath !== availablePath) {
const error = new Error("spawn ENOENT") as NodeJS.ErrnoException;
error.code = "ENOENT";
throw error;
}
return { stdout: "[]", stderr: "" };
},
});
await service.searchIssuesAndPrs({ cwd: "/repo", query: "first", kinds: ["github-issue"] });
availablePath = "/second/bin/gh";
const secondResult = await service.searchIssuesAndPrs({
cwd: "/repo",
query: "second",
kinds: ["github-issue"],
});
expect(secondResult.featuresEnabled).toBe(true);
expect(seenExecutablePaths).toEqual(["/first/bin/gh", "/first/bin/gh", "/second/bin/gh"]);
});
+16 -7
View File
@@ -22,12 +22,15 @@ import {
import { execCommand } from "../utils/spawn.js";
import { resolveSshHostname } from "../utils/ssh-hostname.js";
import {
type CachedCliPathResolver,
CLI_AUTH_PROBE_TIMEOUT_MS,
createCachedCliPathResolver,
createForgeCliRunner,
ForgeAuthenticationError,
ForgeCliMissingError,
parseCliJsonOutput,
probeHostViaCliAuthStatus,
runWithResolvedCliPath,
ForgeCommandError,
type ForgeCommandFailureParams,
} from "./forge-cli-command.js";
@@ -966,7 +969,7 @@ interface CacheEntry {
interface GitHubServiceDependencies {
runner: GitHubCommandRunner;
resolveGhPath: () => Promise<string | null>;
resolveGhPath: CachedCliPathResolver;
now: () => number;
/**
* GitHub Enterprise host for a workspace, or null for github.com (where `gh`
@@ -991,6 +994,7 @@ interface GitHubServiceDependencies {
export interface GitHubCommandRunnerOptions {
cwd: string;
envOverlay?: Record<string, string>;
executablePath?: string;
}
export interface GitHubCommandResult {
@@ -1148,7 +1152,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
const ttlMs = options.ttlMs ?? DEFAULT_GITHUB_CACHE_TTL_MS;
const deps: GitHubServiceDependencies = {
runner: options.runner ?? runGhCommand,
resolveGhPath: options.resolveGhPath ?? resolveGhPath,
resolveGhPath: createCachedCliPathResolver(options.resolveGhPath ?? resolveGhPath),
now: options.now ?? Date.now,
resolveRepoHost: options.resolveRepoHost ?? resolveGitHubEnterpriseHost,
resolveRepoSlug: options.resolveRepoSlug ?? resolveGitHubSlugFromOrigin,
@@ -1367,8 +1371,8 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
runOptions: GitHubCommandRunnerOptions,
explicitHost?: string,
): Promise<string> {
const ghPath = await deps.resolveGhPath();
if (!ghPath) {
const initialGhPath = await deps.resolveGhPath();
if (!initialGhPath) {
throw new GitHubCliMissingError();
}
// Route every gh invocation to the workspace's host. `gh api`/`graphql`
@@ -1376,11 +1380,15 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G
// which silently queries the wrong server on GitHub Enterprise. GH_HOST is
// safe even for auto-routing subcommands because it matches the repo's host.
const host = explicitHost ?? (await resolveRepoHostCached(runOptions.cwd));
const effectiveOptions: GitHubCommandRunnerOptions = host
const baseOptions: GitHubCommandRunnerOptions = host
? { ...runOptions, envOverlay: { ...runOptions.envOverlay, GH_HOST: host } }
: runOptions;
try {
const result = await deps.runner(args, effectiveOptions);
const result = await runWithResolvedCliPath({
resolvePath: deps.resolveGhPath,
createMissingError: () => new GitHubCliMissingError(),
run: (ghPath) => deps.runner(args, { ...baseOptions, executablePath: ghPath }),
});
return result.stdout.trim();
} catch (error) {
throw githubCliRunner.normalizeError(error, {
@@ -3169,7 +3177,8 @@ const githubCliRunner = createForgeCliRunner({
timeoutMs: GITHUB_COMMAND_TIMEOUT_MS,
isAuthFailureText,
errorClasses: {
isAlreadyClassified: (candidate) => candidate instanceof GitHubAuthenticationError,
isAlreadyClassified: (candidate) =>
candidate instanceof GitHubAuthenticationError || candidate instanceof GitHubCliMissingError,
isCommandError: (candidate): candidate is GitHubCommandError =>
candidate instanceof GitHubCommandError,
createAuthError: (stderr) => new GitHubAuthenticationError({ stderr }),
@@ -1654,4 +1654,49 @@ describe("createGitLabService", () => {
GlabCommandError,
);
});
it("forwards the resolved glab executablePath to the command runner", async () => {
const seenExecutablePaths: Array<string | undefined> = [];
const service = createGitLabService({
resolveGlabPath: async () => "/opt/gitlab-cli/bin/glab",
resolveRemoteUrl: async () => "git@gitlab.example.com:example-group/example-project.git",
runner: async (_args, options) => {
seenExecutablePaths.push(options.executablePath);
return ok("[]");
},
});
await expect(service.isAuthenticated({ cwd: "/repo" })).resolves.toBe(true);
await service.searchIssuesAndPrs({ cwd: "/repo", query: "release", kinds: ["github-pr"] });
expect(seenExecutablePaths).toEqual(["/opt/gitlab-cli/bin/glab", "/opt/gitlab-cli/bin/glab"]);
});
it("re-resolves glab and retries when the previously cached executable disappears", async () => {
let availablePath = "/first/bin/glab";
const seenExecutablePaths: Array<string | undefined> = [];
const service = createGitLabService({
resolveGlabPath: async () => availablePath,
resolveRemoteUrl: async () => "git@gitlab.example.com:example-group/example-project.git",
runner: async (_args, options) => {
seenExecutablePaths.push(options.executablePath);
if (options.executablePath !== availablePath) {
const error = new Error("spawn ENOENT") as NodeJS.ErrnoException;
error.code = "ENOENT";
throw error;
}
return ok("[]");
},
});
await service.searchIssuesAndPrs({ cwd: "/repo", query: "first", kinds: ["github-pr"] });
availablePath = "/second/bin/glab";
const secondResult = await service.searchIssuesAndPrs({
cwd: "/repo",
query: "second",
kinds: ["github-pr"],
});
expect(secondResult.featuresEnabled).toBe(true);
expect(seenExecutablePaths).toEqual(["/first/bin/glab", "/first/bin/glab", "/second/bin/glab"]);
});
});
+16 -6
View File
@@ -9,6 +9,7 @@ import {
defaultResolveRemoteUrl,
parseCliJsonOutput,
probeHostViaCliAuthStatus,
runWithResolvedCliPath,
ForgeCommandError,
type ForgeCommandFailureParams,
} from "./forge-cli-command.js";
@@ -97,6 +98,7 @@ export class GlabCommandError extends ForgeCommandError {
export interface GlabCommandRunnerOptions {
cwd: string;
envOverlay?: Record<string, string>;
executablePath?: string;
}
export interface GlabCommandResult {
@@ -933,12 +935,12 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
args: string[],
runOptions: GlabCommandRunnerOptions,
): Promise<GlabCommandResult> {
const glabPath = await resolveGlab();
if (!glabPath) {
throw new GlabCliMissingError();
}
try {
return await runner(args, runOptions);
return await runWithResolvedCliPath({
resolvePath: resolveGlab,
createMissingError: () => new GlabCliMissingError(),
run: (glabPath) => runner(args, { ...runOptions, executablePath: glabPath }),
});
} catch (error) {
throw glabCliRunner.normalizeError(error, { args, cwd: runOptions.cwd });
}
@@ -1191,7 +1193,15 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
return false;
}
try {
await runner(["auth", "status", "--hostname", host], { cwd: input.cwd });
await runWithResolvedCliPath({
resolvePath: resolveGlab,
createMissingError: () => new GlabCliMissingError(),
run: (resolvedPath) =>
runner(["auth", "status", "--hostname", host], {
cwd: input.cwd,
executablePath: resolvedPath,
}),
});
return true;
} catch {
return false;
@@ -2594,14 +2594,20 @@ it.each([false, true])(
...nodeTerminalCommand(`
process.stdin.setRawMode(true);
let row = 0;
function print(count) {
for(let i=0;i<count;i++,row++) process.stdout.write("\\x1b[31mrow-" + String(row).padStart(5,"0") + " 界é🙂 " + "log ".repeat(20) + "\\x1b[0m\\r\\n");
function nextRow() {
return "\\x1b[31mrow-" + String(row++).padStart(5,"0") + " 界é🙂 " + "log ".repeat(20) + "\\x1b[0m\\r\\n";
}
// Fill the initial history in batches to avoid a TTY write for every row.
for (let start = 0; start < 12050; start += 256) {
const count = Math.min(256, 12050 - start);
process.stdout.write(Array.from({ length: count }, nextRow).join(""));
}
print(12050);
process.stdout.write("READY\\r\\n");
process.stdin.on("data", data => {
if(data.toString().includes("BURST")) { print(4000); process.stdout.write("BURST-DONE\\r\\n"); }
else process.stdout.write("ECHO:" + data.toString() + "\\r\\n");
if(data.toString().includes("BURST")) {
for (let i = 0; i < 4000; i++) process.stdout.write(nextRow());
process.stdout.write("BURST-DONE\\r\\n");
} else process.stdout.write("ECHO:" + data.toString() + "\\r\\n");
});
setInterval(()=>{},1000);
`),
@@ -67,7 +67,7 @@ function seedFeatureCheckout(): {
ref: "refs/remotes/origin/main",
aheadBehind: { ahead: 0, behind: 0 },
},
firstPushRemote: "origin",
pushTarget: { kind: "upstream", remoteName: "origin", headRef: "main" },
pullRequestLookupTarget: { headRef: "feature" },
},
};
@@ -111,7 +111,7 @@ function seedMainCheckout(): {
ref: "refs/remotes/origin/main",
aheadBehind: { ahead: 1, behind: 0 },
},
firstPushRemote: "origin",
pushTarget: { kind: "upstream", remoteName: "origin", headRef: "main" },
pullRequestLookupTarget: { headRef: "main" },
},
};
+264 -3
View File
@@ -251,12 +251,13 @@ function getBranchUpstream(cwd: string): string | null {
function setupRemoteTrackingMain(
repoDir: string,
tempDir: string,
remoteName = "origin",
): { remoteDir: string; cloneDir: string } {
const remoteDir = join(tempDir, "remote.git");
const cloneDir = join(tempDir, "upstream-clone");
execFileSync("git", ["init", "--bare", "-b", "main", remoteDir]);
execFileSync("git", ["remote", "add", "origin", remoteDir], { cwd: repoDir });
execFileSync("git", ["push", "-u", "origin", "main"], { cwd: repoDir });
execFileSync("git", ["remote", "add", remoteName, remoteDir], { cwd: repoDir });
execFileSync("git", ["push", "-u", remoteName, "main"], { cwd: repoDir });
execFileSync("git", ["clone", remoteDir, cloneDir]);
execFileSync("git", ["config", "user.email", "test@test.com"], { cwd: cloneDir });
execFileSync("git", ["config", "user.name", "Test"], { cwd: cloneDir });
@@ -1028,6 +1029,7 @@ const x = 1;
return;
}
expect(status.upstreamRef).toBe("refs/remotes/origin/other-name");
expect(status).toMatchObject({ pullRemote: "origin", pushRemote: "origin" });
});
it("reports the upstream when the repo's only remote is not origin", async () => {
@@ -1054,7 +1056,31 @@ const x = 1;
const status = await getCheckoutStatus(repoDir);
expect(status).toMatchObject({ upstreamState: "none", firstPushRemote: "origin" });
expect(status).toMatchObject({
upstreamState: "none",
pullRemote: null,
pushRemote: "origin",
firstPushRemote: "origin",
});
});
// Apps that predate pushRemote offer a regular checkout's first push from firstPushRemote.
it("reports origin as the first push remote when a push refspec names the branch on origin", async () => {
setupRemoteTrackingMain(repoDir, tempDir);
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
execFileSync("git", ["config", "branch.feature.pushRemote", "origin"], { cwd: repoDir });
execFileSync("git", ["config", "remote.origin.push", "HEAD:refs/heads/published"], {
cwd: repoDir,
});
commitFile(repoDir, "feature.txt", "feature\n", "feature commit");
const status = await getCheckoutStatus(repoDir);
expect(status).toMatchObject({
upstreamState: "none",
pushRemote: "origin",
firstPushRemote: "origin",
});
});
// The daemon's first push goes to origin. When git would send the branch to a fork instead,
@@ -1079,6 +1105,7 @@ const x = 1;
expect(status).toMatchObject({
upstreamState: "none",
hasRemote: true,
pushRemote: null,
firstPushRemote: null,
});
const originBranches = execFileSync("git", ["--git-dir", remoteDir, "branch", "--list"])
@@ -1092,8 +1119,10 @@ const x = 1;
execFileSync("git", ["checkout", "-b", "feature", "--track", "main"], { cwd: repoDir });
commitFile(repoDir, "feature.txt", "feature\n", "feature commit");
const status = await getCheckoutStatus(repoDir);
await pushCurrentBranch(repoDir);
expect(status).toMatchObject({ pullRemote: ".", pushRemote: "origin" });
const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoDir })
.toString()
.trim();
@@ -1195,8 +1224,11 @@ const x = 1;
const worktreeDir = worktree.worktreePath;
commitFile(worktreeDir, "feature.txt", "feature\n", "feature commit");
const status = await getCheckoutStatus(worktreeDir, { paseoHome });
await pushCurrentBranch(worktreeDir, undefined, { paseoHome });
expect(status).toMatchObject({ upstreamState: "none", pushRemote: "origin" });
const localHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: worktreeDir })
.toString()
.trim();
@@ -1225,9 +1257,238 @@ const x = 1;
isGit: true,
upstreamState: "none",
hasRemote: false,
pullRemote: null,
pushRemote: null,
firstPushRemote: null,
});
await expect(pushCurrentBranch(repoDir)).rejects.toThrow("Remote 'origin' is not configured.");
await expect(pullCurrentBranch(repoDir)).rejects.toThrow(
"There is no tracking information for the current branch.",
);
});
// Git decides whether a pull has something to pull. In a single-branch clone it pulls the one
// fetched branch into a branch that has no upstream.
it("pulls a branch with no upstream where git itself can pull", async () => {
const { remoteDir, cloneDir } = setupRemoteTrackingMain(repoDir, tempDir);
const singleBranchDir = join(tempDir, "single-branch");
execFileSync("git", [
"clone",
"--single-branch",
"--branch",
"main",
remoteDir,
singleBranchDir,
]);
execFileSync("git", ["checkout", "-b", "local"], { cwd: singleBranchDir });
commitFile(cloneDir, "remote.txt", "remote\n", "remote commit");
execFileSync("git", ["push"], { cwd: cloneDir });
const status = await getCheckoutStatus(singleBranchDir);
await pullCurrentBranch(singleBranchDir);
expect(status).toMatchObject({ upstreamState: "none", pullRemote: null });
const pulledHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: singleBranchDir });
const remoteHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: cloneDir });
expect(pulledHead.toString()).toBe(remoteHead.toString());
});
// A checkout does not need a remote named origin. Pull and Push follow the branch's upstream.
describe("a checkout whose only remote is not origin", () => {
function headOf(cwd: string, ref = "HEAD"): string {
return execFileSync("git", ["rev-parse", ref], { cwd }).toString().trim();
}
function branchesOf(gitDir: string): string {
return execFileSync("git", ["--git-dir", gitDir, "branch", "--list"]).toString().trim();
}
function pushRemoteCommits(cloneDir: string, count: number): void {
for (let index = 1; index <= count; index += 1) {
commitFile(cloneDir, `remote-${index}.txt`, "remote\n", `remote commit ${index}`);
}
execFileSync("git", ["push"], { cwd: cloneDir });
}
it("pushes a branch that is ahead to its upstream", async () => {
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir, "doras-mono");
commitFile(repoDir, "local.txt", "local\n", "local commit");
const status = await getCheckoutStatus(repoDir);
await pushCurrentBranch(repoDir);
expect(status).toMatchObject({
upstreamRef: "refs/remotes/doras-mono/main",
upstreamState: "tracked",
aheadOfOrigin: 1,
behindOfOrigin: 0,
hasRemote: false,
pullRemote: "doras-mono",
pushRemote: "doras-mono",
});
expect(headOf(remoteDir, "refs/heads/main")).toBe(headOf(repoDir));
});
it("pulls a branch that is behind from its upstream", async () => {
const { cloneDir } = setupRemoteTrackingMain(repoDir, tempDir, "doras-mono");
pushRemoteCommits(cloneDir, 2);
execFileSync("git", ["fetch", "doras-mono"], { cwd: repoDir });
const status = await getCheckoutStatus(repoDir);
await pullCurrentBranch(repoDir);
expect(status).toMatchObject({
upstreamState: "tracked",
aheadOfOrigin: 0,
behindOfOrigin: 2,
pullRemote: "doras-mono",
});
expect(headOf(repoDir)).toBe(headOf(cloneDir));
});
it("pulls and then pushes a branch that is both ahead and behind", async () => {
const { remoteDir, cloneDir } = setupRemoteTrackingMain(repoDir, tempDir, "doras-mono");
// Git refuses to pull a diverged branch until it is told how to reconcile it.
execFileSync("git", ["config", "pull.rebase", "false"], { cwd: repoDir });
pushRemoteCommits(cloneDir, 2);
commitFile(repoDir, "local.txt", "local\n", "local commit");
const localCommit = headOf(repoDir);
execFileSync("git", ["fetch", "doras-mono"], { cwd: repoDir });
const status = await getCheckoutStatus(repoDir);
await pullCurrentBranch(repoDir);
await pushCurrentBranch(repoDir);
expect(status).toMatchObject({
upstreamState: "tracked",
aheadOfOrigin: 1,
behindOfOrigin: 2,
pullRemote: "doras-mono",
pushRemote: "doras-mono",
});
expect(headOf(remoteDir, "refs/heads/main")).toBe(headOf(repoDir));
execFileSync("git", ["merge-base", "--is-ancestor", localCommit, "refs/heads/main"], {
cwd: remoteDir,
});
execFileSync("git", ["merge-base", "--is-ancestor", headOf(cloneDir), "refs/heads/main"], {
cwd: remoteDir,
});
expect(await getCheckoutStatus(repoDir)).toMatchObject({
aheadOfOrigin: 0,
behindOfOrigin: 0,
});
});
// Git's default refuses this push. In a checkout that has origin Paseo has always made it,
// which is how a PR checkout reaches the contributor's branch. It is not extended to
// checkouts without origin, where the upstream is often a shared base branch.
it("does not push a branch to a differently named upstream branch", async () => {
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir, "upstream");
execFileSync("git", ["checkout", "-b", "feature", "--track", "upstream/main"], {
cwd: repoDir,
});
const remoteMainBefore = headOf(remoteDir, "refs/heads/main");
commitFile(repoDir, "feature.txt", "feature\n", "feature commit");
const status = await getCheckoutStatus(repoDir);
await expect(pushCurrentBranch(repoDir)).rejects.toThrow(
"Push did not send 'feature' to 'upstream/main'",
);
expect(status).toMatchObject({
upstreamState: "tracked",
aheadOfOrigin: 1,
pullRemote: "upstream",
pushRemote: null,
});
expect(headOf(remoteDir, "refs/heads/main")).toBe(remoteMainBefore);
});
// Push follows the upstream only when `git push` would update it too.
it.each([
{
name: "the branch's pushRemote names a fork",
config: [["branch.main.pushRemote", "fork"]],
},
{ name: "remote.pushDefault names a fork", config: [["remote.pushDefault", "fork"]] },
{
name: "the branch's pushRemote has a push refspec",
config: [
["branch.main.pushRemote", "fork"],
["remote.fork.push", "HEAD:refs/heads/published"],
],
},
{
name: "the upstream remote has a push refspec",
config: [["remote.upstream.push", "HEAD:refs/heads/other"]],
},
{
name: "the push remote shares the upstream's remote-tracking refs",
config: [
["branch.main.pushRemote", "fork"],
["remote.fork.fetch", "+refs/heads/*:refs/remotes/upstream/*"],
],
},
{ name: "push.default is nothing", config: [["push.default", "nothing"]] },
// Matching mode sends a branch only when the remote still has it, which the checkout
// cannot know.
{ name: "push.default is matching", config: [["push.default", "matching"]] },
])("does not push when $name", async ({ config }) => {
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir, "upstream");
const forkDir = join(tempDir, "fork.git");
execFileSync("git", ["init", "--bare", "-b", "main", forkDir]);
execFileSync("git", ["remote", "add", "fork", forkDir], { cwd: repoDir });
for (const [key, value] of config) {
execFileSync("git", ["config", key, value], { cwd: repoDir });
}
const remoteMainBefore = headOf(remoteDir, "refs/heads/main");
commitFile(repoDir, "local.txt", "local\n", "local commit");
const status = await getCheckoutStatus(repoDir);
await expect(pushCurrentBranch(repoDir)).rejects.toThrow(
"Push did not send 'main' to 'upstream/main' because Git's push settings do not confirm",
);
expect(status).toMatchObject({
upstreamState: "tracked",
aheadOfOrigin: 1,
pullRemote: "upstream",
pushRemote: null,
});
expect(branchesOf(remoteDir)).toBe("* main");
expect(headOf(remoteDir, "refs/heads/main")).toBe(remoteMainBefore);
expect(branchesOf(forkDir)).toBe("");
});
// Paseo writes this configuration for a PR checkout, so that its push reaches the
// contributor's branch.
it("pushes a Paseo worktree to the push refspec Paseo configured for it", async () => {
setupRemoteTrackingMain(repoDir, tempDir, "upstream");
const prRemoteDir = join(tempDir, "pr-remote.git");
execFileSync("git", ["init", "--bare", "-b", "main", prRemoteDir]);
const worktree = await createLegacyWorktreeForTest({
branchName: "contributor/feature",
cwd: repoDir,
baseBranch: "main",
worktreeSlug: "contributor-feature",
paseoHome,
});
const worktreeDir = worktree.worktreePath;
execFileSync("git", ["remote", "add", "paseo-pr-7", prRemoteDir], { cwd: worktreeDir });
execFileSync("git", ["config", "branch.contributor/feature.pushRemote", "paseo-pr-7"], {
cwd: worktreeDir,
});
execFileSync("git", ["config", "remote.paseo-pr-7.push", "HEAD:refs/heads/feature"], {
cwd: worktreeDir,
});
commitFile(worktreeDir, "feature.txt", "feature\n", "feature commit");
const status = await getCheckoutStatus(worktreeDir, { paseoHome });
await pushCurrentBranch(worktreeDir, undefined, { paseoHome });
expect(status).toMatchObject({ hasRemote: false, pushRemote: "paseo-pr-7" });
expect(headOf(prRemoteDir, "refs/heads/feature")).toBe(headOf(worktreeDir));
});
});
// A legal local branch named "origin/main" shadows the short form "origin/main" in git's
+244 -100
View File
@@ -909,7 +909,14 @@ export interface CheckoutStatusGitNonPaseo {
aheadOfOrigin: number | null;
behindOfOrigin: number | null;
upstreamState: UpstreamState;
// Whether origin is configured. Pull and Push do not need it; see pullRemote and pushRemote.
hasRemote: boolean;
// The remote Pull fetches currentBranch from, as git names it: the remote of the branch's
// configured upstream, or "." when the upstream is a local branch. Null without an upstream.
pullRemote: string | null;
// The remote Push sends currentBranch to, resolved as pushCurrentBranch resolves it. Null when
// Push has nowhere to send the branch.
pushRemote: string | null;
firstPushRemote: string | null;
remoteUrl: string | null;
isPaseoOwnedWorktree: false;
@@ -930,6 +937,8 @@ export interface CheckoutStatusGitPaseo {
behindOfOrigin: number | null;
upstreamState: UpstreamState;
hasRemote: boolean;
pullRemote: string | null;
pushRemote: string | null;
firstPushRemote: string | null;
remoteUrl: string | null;
isPaseoOwnedWorktree: true;
@@ -967,6 +976,9 @@ export interface CheckoutContext {
logger?: Pick<Logger, "trace" | "warn">;
facts?: CheckoutSnapshotFacts | null;
runGitCommand?: RunGitCommand;
// `git config --get` results shared by the lookups of one snapshot, keyed by config key.
// Several lookups read the same keys; this keeps each to one process.
gitConfigReads?: Map<string, Promise<string | null>>;
}
export type CheckoutSnapshotFacts =
@@ -988,7 +1000,8 @@ export type CheckoutSnapshotFacts =
branchRemoteName: string | null;
branchMergeRef: string | null;
upstreamStatus: UpstreamStatus;
firstPushRemote: string | null;
// Where Push sends the current branch. Null when Push has nowhere to send it.
pushTarget: PushTarget | null;
pullRequestLookupTarget: PullRequestStatusLookupTarget | null;
};
@@ -1441,16 +1454,7 @@ export async function getOriginRemoteUrl(
cwd: string,
context?: CheckoutContext,
): Promise<string | null> {
try {
const { stdout } = await getRunGitCommand(context)(["config", "--get", "remote.origin.url"], {
cwd,
envOverlay: READ_ONLY_GIT_ENV,
});
const url = stdout.trim();
return url.length > 0 ? url : null;
} catch {
return null;
}
return getGitConfigValue(cwd, "remote.origin.url", context);
}
export async function hasOriginRemote(cwd: string): Promise<boolean> {
@@ -1462,6 +1466,23 @@ async function getGitConfigValue(
cwd: string,
key: string,
context?: CheckoutContext,
): Promise<string | null> {
const reads = context?.gitConfigReads;
if (!reads) {
return readGitConfigValue(cwd, key, context);
}
let read = reads.get(key);
if (!read) {
read = readGitConfigValue(cwd, key, context);
reads.set(key, read);
}
return read;
}
async function readGitConfigValue(
cwd: string,
key: string,
context?: CheckoutContext,
): Promise<string | null> {
try {
const { stdout } = await getRunGitCommand(context)(["config", "--get", key], {
@@ -2029,32 +2050,6 @@ async function readGitPushRemote(input: {
return branchPushRemote ?? pushDefault ?? input.branchRemoteName ?? "origin";
}
// pushCurrentBranch publishes a branch with no upstream here.
const FIRST_PUSH_REMOTE = "origin";
// Where a first push publishes the branch, when the daemon can confirm git would push it there
// too. When git picks another remote, as in a fork setup, this is null so that clients do not
// offer a first push that lands in a different repository than `git push` would use.
async function readFirstPushRemote(input: {
cwd: string;
storedBranchName: string | null;
branchRemoteName: string | null;
hasOrigin: boolean;
context?: CheckoutContext;
}): Promise<string | null> {
const { cwd, storedBranchName, branchRemoteName, context } = input;
if (!storedBranchName || !input.hasOrigin) {
return null;
}
const gitPushRemote = await readGitPushRemote({
cwd,
storedBranchName,
branchRemoteName,
context,
});
return gitPushRemote === FIRST_PUSH_REMOTE ? FIRST_PUSH_REMOTE : null;
}
interface CheckoutInspectionContext {
worktreeRoot: string;
currentBranch: string | null;
@@ -2314,7 +2309,13 @@ export async function getCheckoutSnapshotFacts(
if (context?.facts) {
return context.facts;
}
return collectCheckoutSnapshotFacts(cwd, { ...context, gitConfigReads: new Map() });
}
async function collectCheckoutSnapshotFacts(
cwd: string,
context: CheckoutContext,
): Promise<CheckoutSnapshotFacts> {
const inspected = await inspectCheckoutContext(cwd, context);
if (!inspected) {
return { isGit: false };
@@ -2360,13 +2361,14 @@ export async function getCheckoutSnapshotFacts(
]);
}
}
const firstPushRemotePromise = readFirstPushRemote({
cwd,
storedBranchName,
branchRemoteName,
hasOrigin: inspected.remoteUrl !== null,
context,
});
const pushTargetPromise = storedBranchName
? resolvePushTarget({
cwd,
storedBranchName,
paseoWorktree: inspected.paseoWorktree,
context,
})
: null;
let pullRequestLookupTarget = await resolveFactsPullRequestLookupTarget({
cwd,
inspected,
@@ -2402,7 +2404,7 @@ export async function getCheckoutSnapshotFacts(
branchRemoteName,
branchMergeRef,
upstreamStatus,
firstPushRemote: await firstPushRemotePromise,
pushTarget: pushTargetOrNull(await pushTargetPromise),
pullRequestLookupTarget,
};
}
@@ -2580,6 +2582,16 @@ export async function getCheckoutStatus(
// comparisons and actions read it.
const displayBaseRef = baseRef ? branchNameFromRef(baseRef) : null;
const upstream = projectUpstreamStatus(facts.upstreamStatus);
const pushRemote = facts.pushTarget?.remoteName ?? null;
const remotes = {
hasRemote,
pullRemote: resolvePullRemote(facts.branchRemoteName, facts.branchMergeRef),
pushRemote,
// COMPAT(checkoutFirstPushRemote): added in v0.17.5, remove after 2027-05-24 once the app
// floor reads pushRemote. v0.17.4 apps offer a regular checkout's first push only when this
// is set, and the daemon they shipped with set it when the push went to origin.
firstPushRemote: pushRemote === PUBLISH_REMOTE ? pushRemote : null,
};
if (paseoWorktree.isPaseoOwnedWorktree && baseRef) {
return {
@@ -2593,8 +2605,7 @@ export async function getCheckoutStatus(
comparisonBaseRef,
aheadBehind,
...upstream,
hasRemote,
firstPushRemote: facts.firstPushRemote,
...remotes,
remoteUrl,
isPaseoOwnedWorktree: true,
};
@@ -2612,8 +2623,7 @@ export async function getCheckoutStatus(
comparisonBaseRef,
aheadBehind,
...upstream,
hasRemote,
firstPushRemote: facts.firstPushRemote,
...remotes,
remoteUrl,
isPaseoOwnedWorktree: false,
};
@@ -4319,10 +4329,8 @@ export async function pullCurrentBranch(cwd: string, forgeService?: ForgeService
if (!currentBranch || currentBranch === "HEAD") {
throw new Error("Unable to determine current branch for pull");
}
const hasRemote = await hasOriginRemote(cwd);
if (!hasRemote) {
throw new Error("Remote 'origin' is not configured.");
}
// Git decides whether there is something to pull from. It does not need origin, and it can
// pull some branches that have no upstream, as in a single-branch clone.
try {
await runGitCommand(["pull"], { cwd, timeout: 120_000 });
forgeService?.invalidate({ cwd });
@@ -4332,6 +4340,16 @@ export async function pullCurrentBranch(cwd: string, forgeService?: ForgeService
}
}
// The remote `git pull` fetches a branch from when the branch has a configured upstream, which
// git names "." when the upstream is a local branch. Checkout status reports it so that clients
// offer Pull for any upstream, not only one on origin.
function resolvePullRemote(
branchRemoteName: string | null,
branchMergeRef: string | null,
): string | null {
return branchMergeRef === null ? null : branchRemoteName;
}
export async function pushCurrentBranch(
cwd: string,
forgeService?: ForgeService,
@@ -4343,55 +4361,175 @@ export async function pushCurrentBranch(
throw new Error("Unable to determine current branch for push");
}
const storedBranchName = await readStoredBranchName(cwd, currentBranch, context);
const configuredPushTarget = await getCurrentBranchConfiguredPushTarget(cwd, storedBranchName);
if (configuredPushTarget) {
await runGitCommand(
["push", configuredPushTarget.remoteName, `HEAD:refs/heads/${configuredPushTarget.headRef}`],
{ cwd, timeout: 120_000 },
);
await refreshCurrentBranchTrackedRefAfterPush(cwd, storedBranchName, configuredPushTarget);
forgeService?.invalidate({ cwd });
return;
// The status a client acted on can be older than the git configuration, so the destination is
// resolved again before anything is sent.
const target = await resolvePushTarget({ cwd, storedBranchName, context });
switch (target.kind) {
case "refused":
throw new Error(target.reason);
case "configured":
await runGitCommand(["push", target.remoteName, `HEAD:refs/heads/${target.headRef}`], {
cwd,
timeout: 120_000,
});
await refreshCurrentBranchTrackedRefAfterPush(cwd, storedBranchName, target);
break;
case "upstream":
await runGitCommand(["push", "-u", target.remoteName, `HEAD:refs/heads/${target.headRef}`], {
cwd,
timeout: 120_000,
});
break;
case "publish":
await runGitCommand(["push", "-u", target.remoteName, currentBranch], {
cwd,
timeout: 120_000,
});
break;
}
const upstreamTarget = await getCurrentBranchUpstreamPushTarget(cwd, storedBranchName);
if (upstreamTarget) {
await runGitCommand(
["push", "-u", upstreamTarget.remoteName, `HEAD:refs/heads/${upstreamTarget.headRef}`],
{ cwd, timeout: 120_000 },
);
forgeService?.invalidate({ cwd });
return;
}
const hasRemote = await hasOriginRemote(cwd);
if (!hasRemote) {
throw new Error("Remote 'origin' is not configured.");
}
await requireFirstPushAgreesWithGit(cwd, storedBranchName, context);
await runGitCommand(["push", "-u", FIRST_PUSH_REMOTE, currentBranch], { cwd, timeout: 120_000 });
forgeService?.invalidate({ cwd });
}
// The status a client acted on can be older than the git configuration, so a first push checks
// the destination again before it sends anything. Paseo worktrees always publish to origin.
async function requireFirstPushAgreesWithGit(
cwd: string,
storedBranchName: string,
context?: CheckoutContext,
): Promise<void> {
// A branch with no upstream on a remote is published here.
const PUBLISH_REMOTE = "origin";
// Where Push sends the current branch. In a checkout that has origin, in order: the branch's push
// remote with a HEAD push refspec, then its upstream, then origin under the branch's own name,
// which sets the upstream. Without origin, see resolvePushWithoutOrigin. Checkout status reports
// the remote of this target, so the Push offer and the push cannot disagree.
export type PushTarget =
| { kind: "configured"; remoteName: string; headRef: string }
| { kind: "upstream"; remoteName: string; headRef: string }
| { kind: "publish"; remoteName: typeof PUBLISH_REMOTE };
// Push has nowhere to send the branch. The reason is written for the user.
interface PushRefusal {
kind: "refused";
reason: string;
}
function pushTargetOrNull(resolved: PushTarget | PushRefusal | null): PushTarget | null {
return resolved === null || resolved.kind === "refused" ? null : resolved;
}
interface ResolvePushTargetInput {
cwd: string;
storedBranchName: string;
// Known by the caller. Looked up when absent.
paseoWorktree?: PaseoWorktreeForCwd;
context?: CheckoutContext;
}
async function resolvePushTarget(input: ResolvePushTargetInput): Promise<PushTarget | PushRefusal> {
const { cwd, storedBranchName, context } = input;
if ((await getOriginRemoteUrl(cwd, context)) === null) {
return resolvePushWithoutOrigin(input);
}
const configured = await getCurrentBranchConfiguredPushTarget(cwd, storedBranchName, context);
if (configured) {
return { kind: "configured", ...configured };
}
// In a checkout that has origin, Push has always followed the upstream, whatever the upstream
// branch is called.
const upstream = await getCurrentBranchUpstreamPushTarget(cwd, storedBranchName, context);
if (upstream) {
return { kind: "upstream", ...upstream };
}
return resolvePublish(input);
}
// Without origin, Push follows the upstream only when the upstream branch has the branch's own
// name and plain `git push` would update that same branch. A differently named upstream is often
// a shared base branch, as with `feature` tracking `upstream/main`. Git's own push settings
// (branch.<name>.pushRemote, remote.pushDefault, remote.<name>.push, push.default) can send the
// branch elsewhere, and then the push is left to the user.
async function resolvePushWithoutOrigin(
input: ResolvePushTargetInput,
): Promise<PushTarget | PushRefusal> {
const { cwd, storedBranchName, context } = input;
const paseoWorktree = input.paseoWorktree ?? (await getPaseoWorktreeForCwd(cwd, { context }));
if (paseoWorktree.isPaseoOwnedWorktree) {
// Paseo writes this configuration for a PR checkout, so its push reaches the PR's branch.
const configured = await getCurrentBranchConfiguredPushTarget(cwd, storedBranchName, context);
if (configured) {
return { kind: "configured", ...configured };
}
}
const upstream = await getCurrentBranchUpstreamPushTarget(cwd, storedBranchName, context);
if (!upstream) {
return { kind: "refused", reason: `Remote '${PUBLISH_REMOTE}' is not configured.` };
}
const upstreamName = `${upstream.remoteName}/${upstream.headRef}`;
if (upstream.headRef !== storedBranchName) {
return {
kind: "refused",
reason: `Push did not send '${storedBranchName}' to '${upstreamName}' because the branch names differ. Push it from a terminal instead.`,
};
}
const gitPushUpdatesUpstream = await doesGitPushUpdateUpstream({
cwd,
storedBranchName,
upstreamRemoteName: upstream.remoteName,
context,
});
if (!gitPushUpdatesUpstream) {
return {
kind: "refused",
reason: `Push did not send '${storedBranchName}' to '${upstreamName}' because Git's push settings do not confirm that destination. Push it from a terminal instead.`,
};
}
return { kind: "upstream", ...upstream };
}
// Whether plain `git push` on this branch updates the branch's upstream. Git resolves its push
// destination from its own settings and reports none when it cannot name a single one. The
// remote is compared by name as well, because two remotes can map onto one remote-tracking ref.
// Matching mode is left to the user: Git then sends the branch only when the remote still has
// it, and the checkout's remote-tracking refs can outlive a branch deleted on the remote.
async function doesGitPushUpdateUpstream(input: {
cwd: string;
storedBranchName: string;
upstreamRemoteName: string;
context?: CheckoutContext;
}): Promise<boolean> {
if ((await getGitConfigValue(input.cwd, "push.default", input.context)) === "matching") {
return false;
}
try {
const { stdout } = await getRunGitCommand(input.context)(
[
"for-each-ref",
"--format=%(push:remotename)%00%(push)%00%(upstream)",
`refs/heads/${input.storedBranchName}`,
],
{ cwd: input.cwd, envOverlay: READ_ONLY_GIT_ENV },
);
const [pushRemoteName, pushRef, upstreamRef] = stdout.trim().split("\0");
return (
pushRemoteName === input.upstreamRemoteName && Boolean(pushRef) && pushRef === upstreamRef
);
} catch {
return false;
}
}
// Publishing sends the branch to origin. A regular checkout needs git to push the branch there
// too, so that a fork setup is not published to origin. Paseo worktrees always publish to origin.
async function resolvePublish(input: ResolvePushTargetInput): Promise<PushTarget | PushRefusal> {
const { cwd, storedBranchName, context } = input;
const publish: PushTarget = { kind: "publish", remoteName: PUBLISH_REMOTE };
const [branchRemoteName, branchMergeRef] = await Promise.all([
getGitConfigValue(cwd, `branch.${storedBranchName}.remote`, context),
getGitConfigValue(cwd, `branch.${storedBranchName}.merge`, context),
]);
// A branch with a configured upstream gets here when that upstream is not a remote branch, as
// when it tracks a local branch. That is not a first push, and it goes to origin as before.
// when it tracks a local branch. It goes to origin as before.
if (branchRemoteName !== null && branchMergeRef !== null) {
return;
return publish;
}
const paseoWorktree = await getPaseoWorktreeForCwd(cwd, { context });
const paseoWorktree = input.paseoWorktree ?? (await getPaseoWorktreeForCwd(cwd, { context }));
if (paseoWorktree.isPaseoOwnedWorktree) {
return;
return publish;
}
const gitPushRemote = await readGitPushRemote({
cwd,
@@ -4399,24 +4537,29 @@ async function requireFirstPushAgreesWithGit(
branchRemoteName,
context,
});
if (gitPushRemote !== FIRST_PUSH_REMOTE) {
throw new Error(
`Git is set to push this branch to '${gitPushRemote}', so Push did not publish it to '${FIRST_PUSH_REMOTE}'. Push it from a terminal instead.`,
);
if (gitPushRemote !== PUBLISH_REMOTE) {
return {
kind: "refused",
reason: `Git is set to push this branch to '${gitPushRemote}', so Push did not publish it to '${PUBLISH_REMOTE}'. Push it from a terminal instead.`,
};
}
return publish;
}
async function getCurrentBranchConfiguredPushTarget(
cwd: string,
currentBranch: string,
context?: CheckoutContext,
): Promise<{ remoteName: string; headRef: string } | null> {
const remoteName = await getGitConfigValue(cwd, `branch.${currentBranch}.pushRemote`);
const pushRefspec = remoteName ? await getGitConfigValue(cwd, `remote.${remoteName}.push`) : null;
const remoteName = await getGitConfigValue(cwd, `branch.${currentBranch}.pushRemote`, context);
const pushRefspec = remoteName
? await getGitConfigValue(cwd, `remote.${remoteName}.push`, context)
: null;
const headRef = parseHeadPushRefspec(pushRefspec);
if (!remoteName || !headRef) {
return null;
}
const remoteUrl = await getGitConfigValue(cwd, `remote.${remoteName}.url`);
const remoteUrl = await getGitConfigValue(cwd, `remote.${remoteName}.url`, context);
return remoteUrl ? { remoteName, headRef } : null;
}
@@ -4483,16 +4626,17 @@ async function updateRemoteTrackingRef(
async function getCurrentBranchUpstreamPushTarget(
cwd: string,
currentBranch: string,
context?: CheckoutContext,
): Promise<{ remoteName: string; headRef: string } | null> {
const remoteName = await getGitConfigValue(cwd, `branch.${currentBranch}.remote`);
const remoteName = await getGitConfigValue(cwd, `branch.${currentBranch}.remote`, context);
const mergeRef = remoteName
? await getGitConfigValue(cwd, `branch.${currentBranch}.merge`)
? await getGitConfigValue(cwd, `branch.${currentBranch}.merge`, context)
: null;
const headRef = parseBranchMergeHeadRef(mergeRef);
if (!remoteName || !headRef) {
return null;
}
const remoteUrl = await getGitConfigValue(cwd, `remote.${remoteName}.url`);
const remoteUrl = await getGitConfigValue(cwd, `remote.${remoteName}.url`, context);
return remoteUrl ? { remoteName, headRef } : null;
}

Some files were not shown because too many files have changed in this diff Show More