Author SHA1 Message Date
jackos1998andClaude Opus 5.5 b9518180f0 docs/jujutsu: Explain the fork and its workflows
Describe the controls, the commands behind them and the source
files to consult. Record the fork update process and the remaining
trial checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 22:56:42 +00:00
jackos1998andClaude Opus 5.5 db0fa03514 app/workspaces: Add Jujutsu controls and change views
Use bookmark and change labels and show Jujutsu actions where the
daemon advertises support. Add the repository change picker and
workspace base selection while reusing existing diff and archive UI.
Select the current change when there is no bookmark to use as a base.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 22:56:42 +00:00
jackos1998andClaude Opus 5.5 cac41e8889 cli/workspace: Expose Jujutsu checkout actions
Route `paseo workspace jj` through the daemon for describe, new,
fetch, bookmark publication and pull request creation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 22:56:42 +00:00
jackos1998andClaude Opus 5.5 1b4905f32c vcs/jujutsu: Support colocated checkouts in the daemon
Use Git for checkout placement and forge integration, and route
revision reads, diffs and mutations through Jujutsu. Compare at
the fork point and attach the unintegrated operation to change rows.

Create colocated workspaces from a selected checkout, preserve
recovery snapshots, and remove owned checkouts at final archive.
Use the source working-copy change when no default bookmark exists.
Expose capabilities, change search and native actions to clients.

Run the Jujutsu daemon cases in the integration job alongside
the Jujutsu checkout and recovery unit coverage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 22:56:42 +00:00
jackos1998andClaude Opus 5.5 f329a061f0 app/workspaces: Show the real base on a detached HEAD
With no current branch, the new-workspace base picker selected nothing
and its button fell back to a hardcoded "main", while the daemon
created the workspace from the repository's actual default branch
(`master` in some repositories). Default to the base the daemon
reports instead, and label an empty selection "Default branch" rather
than inventing a branch name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 22:54:28 +00:00
Mohamed Boudra 2b3559b107 docs: include first-push fix in v0.17.4 notes
Deploy App / deploy (push) Canceled after 0s
Desktop Release / create-release (push) Canceled after 0s
Desktop Release / publish-macos (arm64, 4096, macos-latest) (push) Canceled after 0s
Desktop Release / publish-macos (x64, 8192, macos-26-intel) (push) Canceled after 0s
Desktop Release / publish-linux (push) Canceled after 0s
Desktop Release / publish-windows (push) Canceled after 0s
Desktop Release / finalize-rollout (push) Canceled after 0s
Release Notes Sync / sync-release-notes (push) Canceled after 0s
Android APK Release / ensure-release (push) Canceled after 0s
Android APK Release / publish-android-apk (push) Canceled after 0s
2026-11-23 22:12:58 +01:00
Mohamed Boudra 1474a527e4 chore(release): sync v0.17.4 Nix dependency hash 2026-11-23 22:12:16 +01:00
Mohamed Boudra 5c372eb179 chore(release): cut 0.17.4 2026-11-23 22:12:16 +01:00
Mohamed Boudra 34d4dae0e3 docs: prepare v0.17.4 changelog 2026-11-23 22:12:16 +01:00
145 changed files with 6119 additions and 6364 deletions

No files matched your search

+19
View File
@@ -222,6 +222,23 @@ jobs:
node-version: "22"
cache: "npm"
- &server_jj
name: Install Jujutsu for checkout tests
shell: bash
run: |
if [[ "$RUNNER_OS" == Windows ]]; then
asset=jj-v0.47.1-x86_64-pc-windows-msvc.zip
checksum=72f9f80bc99d07a7f48d5f219cf5bab91f7e906e4b53f6c827948e646cd1152f
else
asset=jj-v0.47.1-x86_64-unknown-linux-musl.tar.gz
checksum=d4b657f622ee50929c8916466dfa3d6a6c17a0a32b50e7b2c793707ec9ebcad7
fi
curl --fail --location --retry 3 "https://github.com/jj-vcs/jj/releases/download/v0.47.1/$asset" -o "$RUNNER_TEMP/$asset"
echo "$checksum $RUNNER_TEMP/$asset" | sha256sum --check
mkdir -p "$RUNNER_TEMP/jj"
tar -xf "$RUNNER_TEMP/$asset" -C "$RUNNER_TEMP/jj"
echo "$RUNNER_TEMP/jj" >> "$GITHUB_PATH"
- &server_fetch
name: Fetch origin/main (worktree tests)
if: ${{ needs.changes.outputs.full != 'false' || needs.changes.outputs.server != 'false' }}
@@ -267,6 +284,7 @@ jobs:
- *server_capacity
- *server_checkout
- *server_node
- *server_jj
- *server_fetch
- *server_install
- *server_agent_clis
@@ -290,6 +308,7 @@ jobs:
- *server_capacity
- *server_checkout
- *server_node
- *server_jj
- *server_fetch
- *server_install
- *server_agent_clis
+2
View File
@@ -422,6 +422,7 @@
"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",
@@ -553,6 +554,7 @@
"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",
+50
View File
@@ -77,6 +77,56 @@ server to capability-aware sessions. It deliberately does not use the broad recu
watcher or the per-session Git observer: those are checkout/status mechanisms and intentionally do
not retain non-Git directories.
See [Maintaining the Paseo Jujutsu fork](jujutsu-fork.md) for a feature and source guide.
Colocated Jujutsu checkouts reuse Git checkout placement and ownership, with Jujutsu
providing revision facts and working-copy diffs. Checkout providers dispatch
those reads, and status advertises the actions available for the detected VCS.
Existing `isGit` payload variants still describe the underlying Git checkout, so a
Jujutsu checkout reports `currentBranch: null` (Git sees a detached HEAD) and carries
its identity separately: checkout status has `jujutsu` (change and commit IDs,
description, bookmarks, conflicts, and the nearest bookmark under `@`), workspace
descriptors carry `gitRuntime.jujutsu` (change ID and bookmarks), and commit list
entries carry `jujutsu` with `shortSha` holding the short change ID. All are optional
fields, so older clients ignore them. Git mutation guards run on the daemon for
clients that lack VCS capabilities; discard is the exception and runs `jj restore` on
the given paths.
Paseo serializes Jujutsu actions per repository and checks the expected change
ID before applying change-specific actions. Fetch uses the configured base remote
when the base names one and otherwise follows Jujutsu's default or configured remotes.
`new` may name a parent bookmark or change, which must resolve to exactly one commit.
Publication passes an exact bookmark to `jj`. Forge adapters receive bookmark names
and published commit IDs, since colocated Git HEAD usually points to the parent of
the working-copy change. Change search (`checkout.jujutsu.changes`) runs a fixed
revset over mutable changes, bookmarks and recent trunk history; the user's query
only reaches `jj` as string literals or ID prefixes, never as revset syntax.
A Jujutsu workspace records its base by name: the bookmark or remote bookmark it
was created from, or the source change's ID when created from `@`. The base commit
recorded on creation or base selection provides a fallback if that name no longer
resolves. Diffs and the
commit list compare from `fork_point(base | @)`, the counterpart of Git's merge
base, so a base that moves after a fetch doesn't appear reverted.
Jujutsu metadata reads use `--ignore-working-copy`. Diff and commit-list reads use
`--no-integrate-operation`: they snapshot into an unintegrated operation to include
edits on disk without advancing the shared operation head or updating working-copy
files or Git refs. These reads still write objects and unintegrated operations;
normal Jujutsu garbage collection reclaims them. A row from an unintegrated snapshot
carries its operation ID so file diffs can reopen the same revision with `jj --at-op`.
When the read also imports Git refs, jj prints a second operation on top of the
snapshot; Paseo keeps the last one, which sees both.
Using Jujutsu for the file read keeps merge and conflict diffs consistent with the list.
Observe the shared repository's
`op_heads/heads` directory, not its object store, to avoid refresh feedback loops.
Jujutsu archive snapshots the working-copy change and records the exact revision
for recovery. A Git retention ref protects it from Git garbage collection. After
the last active workspace is archived, Paseo verifies the saved snapshot before
using `jj workspace remove` to release both registrations and remove the directory.
Restore recreates the checkout at the saved revision. Files excluded from the
Jujutsu snapshot, such as ignored scratch files, are lost when the directory is removed.
Workspace git and forge runtime data belongs to one daemon-level, directory-keyed store.
Workspace descriptors, checkout diff subscriptions, and script metadata read the last known
snapshot from that store, so reconnecting clients receive it before refresh completes.
+148
View File
@@ -0,0 +1,148 @@
# Maintaining the Paseo Jujutsu fork
Start with the [workspace guide](../public-docs/workspaces.md#jujutsu-repositories)
for the controls you can use in Paseo. This page explains what those controls do
behind the scenes, where to look when something breaks and how to carry the
changes forward.
## Two meanings of workspace
A **Paseo workspace** is a task with a directory and tabs for agents, terminals and
other tools. A **Jujutsu workspace** is a directory with its own working-copy
change, called `@`, in a shared Jujutsu repository. Several Paseo tasks can use
the same directory. Several Jujutsu directories can share the same history and
bookmarks while each has its own `@`.
The daemon expects a colocated checkout with both `.jj` and `.git`. Use Jujutsu
0.47.1, the version used in the trial and CI. Paseo uses Git for repository
location, worktree discovery and forge integration. It uses `jj` for changes,
diffs and checkout mutations. Git often sees a detached HEAD in these directories.
That is expected, and Git's HEAD commonly points at the parent of the change you
see in Paseo.
## What the fork adds
| In Paseo | What happens on the daemon host |
| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **New jj workspace** | Runs `jj workspace add --colocate` and creates a fresh working-copy change on the selected base. Pick `@` to include current work. **Existing jj workspace** opens a directory already registered in the repository. |
| **All changes** and **Working copy (@)** | Shows task changes since the fork point or only the current change. Discard in the working-copy view restores the chosen file to its parent content. For a merge, Jujutsu computes the merged parent content. |
| **Changes** list and **Start new change on…** | The list shows task history and a slice of base history. The picker searches beyond the active workspace. Selecting a result creates a child of that change and leaves the previous change in the repository. |
| **Describe**, **New change** and **Fetch** | Runs `jj describe`, `jj new` and `jj git fetch`. Fetch follows the base's remote when applicable. The terminal remains the place for rebase, squash and other general Jujutsu operations. |
| **Publish bookmark** and **Create pull request** | Pushes the named bookmark through `jj` and uses the existing forge adapter for the pull request. The app publishes to `origin`. The CLI can publish to a named remote with `--remote`. |
| **Archive** and **Restore** | Saves the exact change before removing a Paseo-created checkout. Restore reopens that change at the same path. Save any ignored files separately before archiving. |
## How the pieces fit together
The **daemon** is the background server on the box with your files. The **app**
and **CLI** send it requests through a WebSocket. The **protocol** defines the
shape of each request and reply, and the **client** package provides functions
the app and CLI can call. For example, **Describe** sends the checkout path,
the expected change ID and the new description. The daemon checks the change ID,
runs `jj describe`, and schedules a refresh.
| Start here | What you find there |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| [Checkout provider](../packages/server/src/utils/checkout-vcs.ts) and [Jujutsu commands](../packages/server/src/utils/checkout-jj.ts) | Detect the VCS and translate checkout reads into Git or Jujutsu commands. Detection stops at a nested repository boundary. |
| [Checkout session](../packages/server/src/server/session/checkout/checkout-session.ts), [protocol](../packages/protocol/src/messages.ts) and [client](../packages/client/src/daemon-client.ts) | Request handling and the data passed between the daemon and its clients. Search the files for `checkout.jujutsu`. |
| [Actions and publication](../packages/server/src/utils/jujutsu-actions.ts) and [CLI commands](../packages/cli/src/commands/workspace/jujutsu.ts) | The daemon's implementation of Describe, New, Fetch and Publish, the hand-off to the forge, and the CLI flags. |
| [Action policy](../packages/app/src/git/policy.ts), [action forms](../packages/app/src/git/jujutsu-actions.tsx) and [change picker](../packages/app/src/git/jujutsu-change-switcher.tsx) | The menu rules, text fields and search UI. TypeScript files ending in `.tsx` contain UI components. |
| [New workspace picker](../packages/app/src/screens/new-workspace-picker-item.ts), [creation service](../packages/server/src/server/worktree-core.ts) and [worktree utilities](../packages/server/src/utils/worktree.ts) | How the app picks a base, how the daemon chooses a directory and where it splits into Git worktree or Jujutsu workspace creation. |
| [Archive service](../packages/server/src/server/workspace-archive-service.ts) and [recovery service](../packages/server/src/server/session/workspace-recovery/workspace-recovery-service.ts) | When a checkout can be removed, what is kept in the persisted workspace record and how it is used on restore. |
### Bases, diffs and change IDs
A bookmark can move. Paseo saves its name so the comparison follows it, along
with the commit it pointed to when the base was selected as a fallback. When
starting from `@`, Paseo records the source change ID, which survives ordinary
rewrites. The comparison uses `fork_point(base | @)`. If your base moves forward
after a fetch, the diff still starts at the shared history and shows your work
without listing the upstream changes as removals.
A change ID follows a logical change as it is edited. A commit ID identifies one
version of it. The change picker uses an exact ref or commit ID so it can select
one result even when a Jujutsu change has diverged into multiple versions. The
picker searches mutable changes, bookmarked changes and recent trunk history,
with a bounded result list.
To include unrecorded edits, a diff or Changes list asks `jj` to snapshot in an
unintegrated operation. The command can see those edits without advancing the
repository's shared operation head. The operation ID on a Changes row lets Paseo
reopen the exact snapshot when you click a file. If that command also imports Git
refs, Paseo uses the final operation, which sees both the snapshot and the
imported commits. Open Changes again if garbage collection has removed the old
operation. See [daemon architecture](architecture.md#packagesserver--the-daemon)
for more about checkout observation and protocol compatibility.
### Config inheritance and recovery
`paseo.json` can configure setup commands and terminals. A new checkout keeps
its own copy if its selected revision includes one. When that file is absent, a
Git worktree tries the original repository first and then the selected checkout.
A Jujutsu workspace copies from the selected checkout only. This lets a task
based on one Jujutsu workspace inherit the local config from that workspace.
For archive, the daemon integrates a snapshot, saves its commit ID in the
Paseo workspace record and creates a Git ref under `refs/paseo/kept-commits/` to
keep the commit available for recovery. It checks ownership, active references
and whether tracked content has changed since the snapshot before asking
`jj workspace remove` to remove the directory and its registrations. It also
uses the upstream linked-worktree check to keep the directory if it contains a
nested linked Git worktree. User-created checkouts stay on disk. If the saved
checkout is missing, restore adds a workspace and edits the exact saved commit.
Retention refs accumulate, as they do for Git worktrees.
## Carrying the fork forward
The local series has a standalone fix for the detached-HEAD base picker, followed
by the Jujutsu daemon and protocol support, the CLI commands, the app controls
and the documentation. The daemon commit keeps creation, diff semantics and
archive safety together because they share the same checkout and persistence
code. The app and CLI both call that interface.
Keep a record of the upstream commit your fork starts from. For a new upstream
release, create an update branch and replay the fork on the chosen upstream
revision. For example, with full upstream history available:
```bash
git branch fork/jujutsu-update fork/jujutsu
git rebase --onto <new-upstream-revision> <old-upstream-base> fork/jujutsu-update
git range-diff <old-upstream-base>..fork/jujutsu <new-upstream-revision>..fork/jujutsu-update
```
The likely conflict points are the shared workspace lifecycle, checkout
status and diff data, and the new-workspace screen. Keep Git's behavior at those
boundaries and follow the new upstream call path before resolving a conflict.
The worktree manager plugin API introduced in Paseo 0.17 prepares and validates
Git targets. Route Jujutsu creation and recovery directly through the built-in
Jujutsu paths so a configured Git manager can coexist with checkout from `@`.
Both use the daemon's shared archive and restore coordination.
Build the protocol and client before typechecking the daemon, app or CLI so they
all see the new request types. For example:
```bash
npm run build:client
npm run typecheck --workspace=@getpaseo/server
npm run typecheck --workspace=@getpaseo/app
npm run typecheck --workspace=@getpaseo/cli
npm exec --workspace=@getpaseo/server -- vitest run --maxWorkers=1 \
src/server/daemon-e2e/git-operations.e2e.test.ts -t 'Jujutsu'
```
## Review findings and trial checks
- Open the web UI against a trial daemon with its own Paseo home. Create a Jujutsu
workspace, select another change in the picker, open a file diff, discard a
disposable edit, then archive and restore the workspace. Repeat creation and
archive in a plain Git repository.
- Test **Publish bookmark** and **Create pull request** against a disposable repo
on the forge you actually use. The trial's local bare Git remote can exercise
pushes. Live forge creation and status still need an interactive pass.
- Use an `origin` remote for the app's publication and pull request workflow.
Fetch can choose a different base remote, and the CLI can explicitly publish
to one. Pull request status looks for a single matching published bookmark on
`origin`.
- If a long fetch or push repeatedly delays diffs in unrelated repositories,
inspect the two-command daemon-wide limit in
[checkout-jj.ts](../packages/server/src/utils/checkout-jj.ts). Reproduce any
contention before changing how the daemon schedules Jujutsu commands.
@@ -1,5 +1,4 @@
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";
@@ -499,56 +498,6 @@ 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) => {
@@ -2253,79 +2202,6 @@ 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,7 +4,6 @@ import {
addConnectedHostAndReload,
chooseHostBadgeDisplay,
chooseHostColor,
chooseHostIcon,
expectHostAppearancePreview,
expectHostBadgeIconOnly,
expectHostBadgeName,
@@ -116,21 +115,12 @@ 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 icon and apply them to the sidebar badge and host popover", async () => {
await test.step("preview a color and apply it to the sidebar badge", 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 () => {
@@ -155,30 +145,3 @@ 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,7 +65,8 @@ import {
openSettingsHostSection,
removeCurrentHostFromSettings,
openSidebarHostPicker,
sidebarHostRowButton,
sidebarHostSettingsButton,
expectStandaloneSidebarHostSettingsButton,
activateSidebarHostSettingsWithKeyboard,
bindCommandCenterToEnter,
} from "../support/helpers/settings";
@@ -191,16 +192,17 @@ test.describe("Settings sidebar scroll position", () => {
});
test.describe("Settings sidebar navigation", () => {
test("the sidebar host row opens Overview in one click", async ({ page, withWorkspace }) => {
test("the sidebar host gear opens Overview in one click", async ({ page, withWorkspace }) => {
const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" });
await openWorkspace(page, workspace);
await openSidebarHostPicker(page);
await sidebarHostRowButton(page).click();
await expectStandaloneSidebarHostSettingsButton(page);
await sidebarHostSettingsButton(page).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
});
test("Enter opens the active sidebar host row", async ({ page, withWorkspace }) => {
test("Enter opens the focused sidebar host gear", async ({ page, withWorkspace }) => {
await bindCommandCenterToEnter(page);
const workspace = await withWorkspace({ prefix: "keyboard-host-settings-" });
await openWorkspace(page, workspace);
@@ -564,7 +566,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 sidebarHostRowButton(page).click();
await page.getByRole("button", { name: /Open .* settings/ }).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
await expect(page.getByText("Overview", { exact: true })).toBeVisible();
+1 -10
View File
@@ -132,10 +132,7 @@ export async function waitForConnectedHost(
): Promise<void> {
await page.getByTestId("sidebar-hosts-trigger").click();
const host = page.getByTestId(`sidebar-host-row-${input.serverId}`);
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 expect(host).toContainText(input.endpoint, { timeout: 30_000 });
await page.keyboard.press("Escape");
await expect(host).not.toBeVisible();
}
@@ -198,12 +195,6 @@ 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",
+14 -4
View File
@@ -16,8 +16,8 @@ export async function openSidebarHostPicker(page: Page) {
await page.getByRole("button", { name: "Hosts", exact: true }).click();
}
export function sidebarHostRowButton(page: Page) {
return page.getByTestId(`sidebar-host-row-${getServerId()}`);
export function sidebarHostSettingsButton(page: Page) {
return page.getByRole("button", { name: `Open ${TEST_HOST_LABEL} settings`, exact: true });
}
export async function bindCommandCenterToEnter(page: Page) {
@@ -32,10 +32,20 @@ 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 = sidebarHostRowButton(page);
await expect(host).toBeVisible();
const host = page.getByRole("button", { name: TEST_HOST_LABEL, exact: true });
await expect(host).toBeFocused();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Tab");
await expect(sidebarHostSettingsButton(page)).toBeFocused();
await page.keyboard.press("Enter");
}
+2
View File
@@ -56,6 +56,7 @@ import { SidebarModelProvider } from "@/components/sidebar/sidebar-model";
import { WorkspacePinShortcutHandler } from "@/components/workspace-pin-shortcut-handler";
import { WorkspaceArchiveShortcutHandler } from "@/components/workspace-archive-shortcut-handler";
import { WorkspaceRenameHost } from "@/components/workspace-rename-host";
import { JujutsuActionSheetHost } from "@/git/jujutsu-actions";
import { WorkspaceArchiveUndoShortcutHost } from "@/workspace/archive-undo";
import { WorkspaceExplorerOpenGesture } from "@/mobile-panels/explorer-open-gesture";
import { ProviderSettingsHost } from "@/components/provider-settings-host";
@@ -571,6 +572,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
<PluginCommandCenterActions />
<WorkspacePinShortcutHandler />
<WorkspaceRenameHost />
<JujutsuActionSheetHost />
<WorkspaceArchiveUndoShortcutHost />
<CommandCenter />
<AddProjectFlowHost />
+133 -301
View File
@@ -1,28 +1,11 @@
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 { 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 { HostStatusDot } from "@/components/host-status-dot";
import { Combobox, type ComboboxProps } from "@/components/ui/combobox";
import { PressHighlight } from "@/components/ui/press-highlight";
import { Combobox, ComboboxItem, type ComboboxProps } from "@/components/ui/combobox";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
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 { useHostRuntimeSnapshot, type ActiveConnection } from "@/runtime/host-runtime";
import { orderHostsLocalFirst } from "@/types/host-connection";
import {
ADD_HOST_OPTION_ID,
@@ -39,16 +22,7 @@ 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;
@@ -62,166 +36,122 @@ 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;
appearance: HostAppearance;
showActiveConnection: boolean;
selected?: boolean;
active: boolean;
onPress: () => void;
onOpenHostSettings?: (serverId: string) => void;
testID?: string;
}
export function HostPickerOption({
serverId,
label,
appearance,
showActiveConnection,
selected,
active,
onPress,
onOpenHostSettings,
testID,
}: HostPickerOptionProps): ReactElement {
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";
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,
]);
return (
<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>
<ComboboxItem
label={label}
description={connectionLabel}
leadingSlot={leadingSlot}
trailingAction={trailingAction}
selected={selected}
active={active}
onPress={onPress}
testID={testID}
/>
);
}
function AllHostsOption({
const SYSTEM_HOST_PICKER_OPTION_LABELS: Record<"add" | "all" | "enableBuiltInDaemon", string> = {
add: "Add host",
all: "All hosts",
enableBuiltInDaemon: "Enable built-in daemon",
};
function SystemHostPickerOption({
active,
selected,
onPress,
kind,
testID,
}: {
active: boolean;
selected?: boolean;
onPress: () => void;
kind: "add" | "all" | "enableBuiltInDaemon";
testID?: string;
}): ReactElement {
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 (
<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>
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],
);
}
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>
<ComboboxItem
label={label}
leadingSlot={leadingSlot}
selected={selected}
active={active}
onPress={onPress}
testID={testID}
/>
);
}
@@ -238,6 +168,7 @@ export interface HostPickerProps {
includeEnableBuiltInDaemon?: boolean;
onEnableBuiltInDaemon?: () => void;
showActiveConnection?: boolean;
onOpenHostSettings?: (serverId: string) => void;
searchable?: boolean;
title?: string;
desktopPlacement?: ComboboxProps["desktopPlacement"];
@@ -259,85 +190,74 @@ export function HostPicker({
onAddHost,
includeEnableBuiltInDaemon,
onEnableBuiltInDaemon,
showActiveConnection,
onOpenHostSettings,
searchable,
title,
desktopPlacement = "bottom-start",
desktopMinWidth = DEFAULT_DESKTOP_MIN_WIDTH,
desktopMinWidth,
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: t("sidebar.display.hostFilter.all") });
}
if (includeAddHost) {
hostOptions.push({ id: ADD_HOST_OPTION_ID, label: t("settings.addHost") });
}
if (includeEnableBuiltInDaemon) {
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)
hostOptions.push({
id: ENABLE_BUILT_IN_DAEMON_OPTION_ID,
label: t("settings.enableBuiltInDaemon"),
label: "Enable built-in daemon",
});
}
return hostOptions;
}, [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;
}
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon]);
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?.();
return;
}
if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
onOpenChange(false);
} else if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
onEnableBuiltInDaemon?.();
return;
} else {
onSelect(id);
}
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 (
<AllHostsOption
<SystemHostPickerOption
kind="all"
active={active}
selected={selected}
onPress={onPress}
@@ -345,48 +265,30 @@ export function HostPicker({
/>
);
}
if (option.id === ADD_HOST_OPTION_ID) {
return (
<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}
/>
<SystemHostPickerOption kind="enableBuiltInDaemon" active={active} onPress={onPress} />
);
}
const appearance = appearanceByServerId.get(option.id) ?? defaultHostAppearance();
return (
<HostPickerOption
serverId={option.id}
label={option.label}
appearance={appearance}
showActiveConnection={showActiveConnection === true}
selected={selected}
active={active}
onPress={onPress}
onOpenHostSettings={onOpenHostSettings ? handleOpenHostSettings : undefined}
testID={hostOptionTestID?.(option.id)}
/>
);
},
[
addHostTestID,
appearanceByServerId,
firstActionOptionId,
hostOptionTestID,
orderedHosts.length,
onOpenHostSettings,
showActiveConnection,
handleOpenHostSettings,
],
);
@@ -399,8 +301,8 @@ export function HostPicker({
onSelect={handleSelect}
renderOption={renderOption}
searchable={isSearchable}
searchPlaceholder={t("sidebar.host.searchPlaceholder")}
title={resolvedTitle}
searchPlaceholder="Search hosts"
title={title ?? "Host"}
open={open}
onOpenChange={onOpenChange}
anchorRef={anchorRef}
@@ -412,86 +314,16 @@ 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,
},
}));
@@ -1,32 +0,0 @@
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={328}
desktopMinWidth={240}
addHostTestID="sidebar-host-add"
hostOptionTestID={sidebarHostOptionTestID}
>
+14 -60
View File
@@ -73,9 +73,6 @@ 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";
@@ -405,7 +402,6 @@ export function ComboboxEmpty({ children }: { children: ReactNode }): ReactEleme
type RenderOptionFn = NonNullable<ComboboxProps["renderOption"]>;
interface OptionRowProps {
index: number;
option: ComboboxOption;
selected: boolean;
active: boolean;
@@ -413,27 +409,20 @@ interface OptionRowProps {
renderOption: RenderOptionFn | undefined;
}
function OptionRow({ index, option, selected, active, onSelect, renderOption }: OptionRowProps) {
function OptionRow({ 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 dataSet={optionDataset}>
{renderOption({ option, selected, active, onPress: handlePress })}
</View>
);
return <View>{renderOption({ option, selected, active, onPress: handlePress })}</View>;
}
return (
<View dataSet={optionDataset}>
<ComboboxItem
label={option.label}
description={option.description}
kind={option.kind}
selected={selected}
active={active}
onPress={handlePress}
/>
</View>
<ComboboxItem
label={option.label}
description={option.description}
kind={option.kind}
selected={selected}
active={active}
onPress={handlePress}
/>
);
}
@@ -462,7 +451,6 @@ function OptionsList({
{options.map((opt, index) => (
<OptionRow
key={opt.id}
index={index}
option={opt}
selected={opt.id === value}
active={index === activeIndex}
@@ -964,9 +952,8 @@ function dispatchDesktopKey(
return true;
}
if (key === "Enter") {
// 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)) {
// Consume the shortcut but keep the browser's default button activation.
if (isWeb && document.activeElement?.matches("[data-combobox-trailing-action] button")) {
return true;
}
if (input.orderedVisibleOptions.length === 0) return false;
@@ -1140,12 +1127,7 @@ function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children
[safeAreaBottom],
);
const footerView = useMemo(
() =>
footer ? (
<View style={footerStyle} dataSet={FOOTER_DATASET}>
{footer}
</View>
) : undefined,
() => (footer ? <View style={footerStyle}>{footer}</View> : undefined),
[footer, footerStyle],
);
return (
@@ -1359,11 +1341,7 @@ function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null {
renderOption={props.renderOption}
/>
)}
{props.footer ? (
<View style={styles.footer} dataSet={FOOTER_DATASET}>
{props.footer}
</View>
) : null}
{props.footer ? <View style={styles.footer}>{props.footer}</View> : null}
</FloatingSurface>
</View>
</OverlayLayerProvider>
@@ -1619,30 +1597,6 @@ 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);
@@ -110,7 +110,11 @@ function WorkspaceHoverCardContent({
icon={ThemedGitBranch}
value={workspace.currentBranch}
copyValue={workspace.currentBranch}
copyLabel={t("workspace.hoverCard.copyBranchName")}
copyLabel={
workspace.isJujutsu
? t("workspace.hoverCard.copyChangeName")
: t("workspace.hoverCard.copyBranchName")
}
testID="hover-card-workspace-branch"
/>
) : null}
@@ -1,5 +1,5 @@
import { QueryClient, QueryObserver } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { fetchQueryOptions } from "@/data/query";
import { commitFileDiffQueryOptions } from "./commit-file-diff-query";
@@ -43,6 +43,28 @@ describe("commit file diff fetching", () => {
}
});
it("reopens a Jujutsu file at the operation returned with its change", async () => {
const getCommitFileDiff = vi.fn(async () => ({ file }));
const options = commitFileDiffQueryOptions({
serverId: "host",
cwd: "/repo",
sha: "abc",
path: "a.ts",
jujutsuOperationId: "012345abcdef",
enabled: true,
client: { getCommitFileDiff },
});
await expect(options.queryFn()).resolves.toEqual({ file });
expect(getCommitFileDiff).toHaveBeenCalledWith(
"/repo",
"abc",
"a.ts",
undefined,
"012345abcdef",
);
});
it("retries a cached null result when reopened", async () => {
const queryClient = new QueryClient();
const options = fetchQueryOptions(
@@ -7,6 +7,7 @@ export function commitFileDiffQueryOptions(input: {
cwd: string;
sha: string;
path: string;
jujutsuOperationId?: string;
client: Pick<DaemonClient, "getCommitFileDiff"> | null;
enabled: boolean;
}) {
@@ -14,7 +15,10 @@ export function commitFileDiffQueryOptions(input: {
queryKey: checkoutCommitFileDiffQueryKey(input.serverId, input.cwd, input.sha, input.path),
queryFn: () => {
if (!input.client) throw new Error("Host disconnected");
return input.client.getCommitFileDiff(input.cwd, input.sha, input.path);
const args = [input.cwd, input.sha, input.path] as const;
return input.jujutsuOperationId
? input.client.getCommitFileDiff(...args, undefined, input.jujutsuOperationId)
: input.client.getCommitFileDiff(...args);
},
enabled: input.enabled,
gcTime: COMMIT_FILE_DIFF_STALE_TIME,
@@ -1,6 +1,7 @@
import { memo, useCallback } from "react";
import { Pressable, Text, View, type PressableStateCallbackType } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import { ThemedChevron, chevronColorMapping } from "@/git/themed-chevron";
import type { ClassifiedCheckoutCommit } from "@/git/use-commits-query";
import { CODE_SURFACE_DATASET } from "@/styles/code-surface";
@@ -27,10 +28,24 @@ export const CommitRow = memo(function CommitRow({
isLast,
onCommitPress,
}: CommitRowProps) {
const { t } = useTranslation();
const handlePress = useCallback(() => {
onCommitPress(commit.sha);
}, [commit.sha, onCommitPress]);
// jj changes may have no description yet, and are marked like `jj log` marks them.
const change = commit.jujutsu;
const subject = change
? `${change.isWorkingCopy ? "@ " : ""}${commit.subject || t("workspace.git.jujutsu.noDescription")}`
: commit.subject;
const annotations = change
? [
...change.bookmarks,
...(change.hasConflicts ? [t("workspace.git.jujutsu.conflicts")] : []),
...(change.isEmpty ? [t("workspace.git.jujutsu.empty")] : []),
].join(" · ")
: "";
return (
<Pressable
accessibilityRole="button"
@@ -44,8 +59,13 @@ export const CommitRow = memo(function CommitRow({
{commit.shortSha}
</Text>
<Text style={styles.subject} numberOfLines={1}>
{commit.subject}
{subject}
</Text>
{annotations ? (
<Text style={styles.annotations} numberOfLines={1}>
{annotations}
</Text>
) : null}
</View>
<CommitTimestamp authorDate={commit.authorDate} />
<View style={styles.caret}>
@@ -92,6 +112,12 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.base,
color: theme.colors.foreground,
},
annotations: {
flexShrink: 1,
maxWidth: "40%",
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
},
timestamp: {
flexShrink: 0,
fontSize: theme.fontSize.sm,
@@ -3,7 +3,11 @@ import { Pressable, Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useTranslation } from "react-i18next";
import { useCheckoutCommitsQuery, type CheckoutCommitsQueryResult } from "@/git/use-commits-query";
import {
useCheckoutCommitsQuery,
type CheckoutCommitsQueryResult,
type ClassifiedCheckoutCommit,
} from "@/git/use-commits-query";
import { ThemedChevron, chevronColorMapping } from "@/git/themed-chevron";
import { treeRowPaddingLeft } from "@/components/tree-primitives";
import { normalizeBranchOptionName } from "@/utils/branch-suggestions";
@@ -12,6 +16,8 @@ import { CommitRow } from "./commit-row";
interface CommitsSectionProps {
serverId: string;
cwd: string;
/** List jj changes: an untouched working-copy change isn't work yet, so it is left out. */
isJujutsu?: boolean;
onCommitPress: (sha: string) => void;
collapsed?: boolean;
onCollapsedChange?: (collapsed: boolean) => void;
@@ -37,11 +43,24 @@ function CommitsSectionSkeleton() {
);
}
function workspaceEntries(
commits: readonly ClassifiedCheckoutCommit[],
isJujutsu: boolean,
): ClassifiedCheckoutCommit[] {
return commits.filter(
(commit) =>
!commit.isOnBase &&
!(isJujutsu && commit.jujutsu?.isWorkingCopy && commit.jujutsu.isEmpty && !commit.subject),
);
}
function CommitsSectionContent({
query,
isJujutsu,
onCommitPress,
}: {
query: Exclude<CheckoutCommitsQueryResult, { status: "unsupported" }>;
isJujutsu: boolean;
onCommitPress: (sha: string) => void;
}) {
const { t } = useTranslation();
@@ -55,13 +74,15 @@ function CommitsSectionContent({
if (query.status !== "loaded") {
return <CommitsSectionSkeleton />;
}
const workspaceCommits = query.data.commits.filter((commit) => !commit.isOnBase);
const workspaceCommits = workspaceEntries(query.data.commits, isJujutsu);
const baseRef = normalizeBranchOptionName(query.data.baseRef) ?? t("workspace.git.diff.base");
if (workspaceCommits.length === 0) {
return (
<View style={styles.noWorkspaceCommitsRow} testID="commits-section-no-workspace-commits">
<Text style={styles.noWorkspaceCommitsText}>
{t("workspace.git.diff.commits.noneAhead", { baseRef })}
{isJujutsu
? t("workspace.git.jujutsu.changes.noneAhead", { baseRef })
: t("workspace.git.diff.commits.noneAhead", { baseRef })}
</Text>
</View>
);
@@ -84,6 +105,7 @@ function CommitsSectionContent({
export function CommitsSection({
serverId,
cwd,
isJujutsu = false,
onCommitPress,
collapsed = true,
onCollapsedChange,
@@ -113,9 +135,7 @@ export function CommitsSection({
return null;
}
const commitCount =
query.status === "loaded"
? query.data.commits.filter((commit) => !commit.isOnBase).length
: null;
query.status === "loaded" ? workspaceEntries(query.data.commits, isJujutsu).length : null;
return (
<View style={containerStyle}>
@@ -128,21 +148,30 @@ export function CommitsSection({
<View style={headerChevronStyle}>
<ThemedChevron size={14} uniProps={chevronColorMapping} />
</View>
<Text style={styles.title}>{t("workspace.git.diff.commits.title")}</Text>
<Text style={styles.title}>
{isJujutsu
? t("workspace.git.jujutsu.changes.title")
: t("workspace.git.diff.commits.title")}
</Text>
{commitCount === null ? (
<View style={styles.countSpacer} />
) : (
<Text
style={styles.count}
accessibilityLabel={t("workspace.git.diff.commits.countLabel", {
count: commitCount,
})}
accessibilityLabel={t(
isJujutsu
? "workspace.git.jujutsu.changes.countLabel"
: "workspace.git.diff.commits.countLabel",
{ count: commitCount },
)}
>
{commitCount}
</Text>
)}
</Pressable>
{collapsed ? null : <CommitsSectionContent query={query} onCommitPress={onCommitPress} />}
{collapsed ? null : (
<CommitsSectionContent query={query} isJujutsu={isJujutsu} onCommitPress={onCommitPress} />
)}
</View>
);
}
+77 -21
View File
@@ -1,3 +1,4 @@
import type { CheckoutStatusResponse } from "@getpaseo/protocol/messages";
import type { DiffFileHeader } from "@/git/diff-snapshot";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { floatingActionsClearance } from "@/components/ui/floating-action-button";
@@ -64,6 +65,7 @@ import type { GitActions } from "@/git/policy";
import { BranchSwitcher } from "@/components/branch-switcher";
import { useGitActions } from "@/git/use-actions";
import { WorkspaceBaseBranchPicker } from "@/git/workspace-base-branch-picker";
import { JujutsuChangeSwitcher } from "@/git/jujutsu-change-switcher";
import { GIT_ACTION_ICONS } from "@/git/action-icons";
import { buildForgeSignInCommand, getForgePresentation, type Forge } from "@/git/forge";
import { parseGitRemoteLocation } from "@getpaseo/protocol/git-remote";
@@ -96,7 +98,7 @@ import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
import { isWeb } from "@/constants/platform";
import { usePublishWorkingDiffAttachment, useWorkingDiff } from "@/git/use-working-diff";
import type { CheckoutStatusPayload } from "@/git/use-status-query";
import { type CheckoutStatusPayload, useCheckoutStatusQuery } from "@/git/use-status-query";
import { DiffTooLargeState } from "@/git/diff-too-large-state";
import { openDesktopTarget, useDesktopOpenTargets } from "@/workspace/desktop-open-targets";
import { PullRequestStateIcon } from "@/git/pull-request-state-icon";
@@ -285,6 +287,7 @@ export function DiffLayoutToggle({
}
interface DiffModeMenuProps {
isJujutsu?: boolean;
diffMode: "uncommitted" | "base" | "all";
committedDescription?: string;
testIDPrefix?: string;
@@ -294,6 +297,7 @@ interface DiffModeMenuProps {
}
export function DiffModeMenu({
isJujutsu = false,
diffMode,
committedDescription,
testIDPrefix = "changes-diff",
@@ -302,9 +306,13 @@ export function DiffModeMenu({
onSelectAll,
}: DiffModeMenuProps) {
const { t } = useTranslation();
const uncommittedLabel = t("workspace.git.diff.uncommitted");
const committedLabel = t("workspace.git.diff.committed");
// jj has no staging split: "All changes" means the same as for Git, and the working-copy
// change (@) stands in for uncommitted changes.
const uncommittedLabel = isJujutsu
? t("workspace.git.jujutsu.workingCopy")
: t("workspace.git.diff.uncommitted");
const allLabel = t("workspace.git.diff.all");
const committedLabel = isJujutsu ? allLabel : t("workspace.git.diff.committed");
return (
<DropdownMenu>
<DropdownMenuTrigger
@@ -330,7 +338,7 @@ export function DiffModeMenu({
<DropdownMenuContent align="start" width={260} testID={`${testIDPrefix}-status-menu`}>
<DropdownMenuItem
testID={`${testIDPrefix}-mode-all`}
selected={diffMode === "all"}
selected={diffMode === "all" || (isJujutsu && diffMode === "base")}
onSelect={onSelectAll}
>
{allLabel}
@@ -343,15 +351,19 @@ export function DiffModeMenu({
>
{uncommittedLabel}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
testID={`${testIDPrefix}-mode-committed`}
selected={diffMode === "base"}
description={committedDescription}
onSelect={onSelectBase}
>
{committedLabel}
</DropdownMenuItem>
{!isJujutsu ? (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
testID={`${testIDPrefix}-mode-committed`}
selected={diffMode === "base"}
description={committedDescription}
onSelect={onSelectBase}
>
{committedLabel}
</DropdownMenuItem>
</>
) : null}
</DropdownMenuContent>
</DropdownMenu>
);
@@ -473,7 +485,11 @@ interface ChangesPullRequestLinkModel extends Pick<PrHint, "forge" | "number" |
onOpen: () => void;
}
type JujutsuState = NonNullable<CheckoutStatusResponse["payload"]["jujutsu"]>;
interface ChangesRepositoryToolbarModel {
canSwitchBranch: boolean;
jujutsu: JujutsuState | null;
baseRef: string | null;
isWorktree: boolean;
branchName: string | null;
@@ -485,6 +501,7 @@ interface ChangesRepositoryToolbarModel {
}
interface ChangesComparisonToolbarModel {
isJujutsu?: boolean;
committedDescription?: string;
diffMode: "uncommitted" | "base" | "all";
mode: ChangesToolbarMode;
@@ -502,6 +519,7 @@ interface ChangesHeaderProps {
}
interface BuildChangesHeaderModelInput {
status?: CheckoutStatusResponse["payload"] | null;
baseRef: string | null;
isWorktree: boolean;
branchName: string | null;
@@ -527,6 +545,8 @@ function buildChangesHeaderModel(input: BuildChangesHeaderModelInput): {
} {
return {
repository: {
canSwitchBranch: input.status?.vcs?.capabilities.gitMutations ?? !input.status?.jujutsu,
jujutsu: input.status?.jujutsu ?? null,
baseRef: input.baseRef,
isWorktree: input.isWorktree,
branchName: input.branchName,
@@ -539,6 +559,7 @@ function buildChangesHeaderModel(input: BuildChangesHeaderModelInput): {
workspaceId: input.workspaceId,
},
comparison: {
isJujutsu: Boolean(input.status?.jujutsu),
committedDescription: input.committedDescription,
diffMode: input.diffMode,
mode: input.mode,
@@ -660,14 +681,19 @@ function ChangesRepositoryToolbar({
trailing={model.gitActions ? "framed" : "glyph"}
>
<ChangesToolbarLeading>
<BranchSwitcher
currentBranchName={model.branchName}
serverId={model.serverId}
workspaceId={model.workspaceId ?? model.cwd}
workspaceDirectory={model.cwd}
isGitCheckout
testID="changes-branch-switcher"
/>
{model.jujutsu ? (
<JujutsuChangeSwitcher serverId={model.serverId} cwd={model.cwd} change={model.jujutsu} />
) : null}
{model.canSwitchBranch ? (
<BranchSwitcher
currentBranchName={model.branchName}
serverId={model.serverId}
workspaceId={model.workspaceId ?? model.cwd}
workspaceDirectory={model.cwd}
isGitCheckout
testID="changes-branch-switcher"
/>
) : null}
{model.baseRef && model.isWorktree ? (
<>
<ThemedArrowRight size={14} uniProps={extraMutedIconColorMapping} />
@@ -676,6 +702,8 @@ function ChangesRepositoryToolbar({
workspaceId={model.workspaceId}
cwd={model.cwd}
baseRef={model.baseRef}
isJujutsu={Boolean(model.jujutsu)}
baseBookmarkMissing={model.jujutsu?.baseBookmarkMissing}
/>
</>
) : null}
@@ -772,6 +800,7 @@ function ChangesComparisonToolbar({
>
<ChangesToolbarLeading>
<DiffModeMenu
isJujutsu={model.isJujutsu}
diffMode={model.diffMode}
committedDescription={model.committedDescription}
onSelectUncommitted={model.onSelectUncommitted}
@@ -1423,11 +1452,14 @@ function ChangesCommits({
onCommitPress: (sha: string) => void;
onCollapsedChange: (collapsed: boolean) => void;
}) {
const { status } = useCheckoutStatusQuery({ serverId, cwd });
const isJujutsu = Boolean(status?.jujutsu);
if (presentation === "diff") return null;
return (
<CommitsSection
serverId={serverId}
cwd={cwd}
isJujutsu={isJujutsu}
onCommitPress={onCommitPress}
collapsed={collapsed}
onCollapsedChange={onCollapsedChange}
@@ -1941,6 +1973,7 @@ export function ChangesSurface({
const changesHeaderModel = useMemo(
() =>
buildChangesHeaderModel({
status,
baseRef: baseRef ?? null,
isWorktree: isManagedWorktree(status),
branchName: currentBranchName,
@@ -1997,6 +2030,8 @@ export function ChangesSurface({
/>
) : null}
<JujutsuCheckoutSummary status={status} />
{forgeSetupMessage ? (
<View style={styles.forgeSetupCallout} testID="forge-setup-callout">
<Text style={styles.forgeSetupCalloutText}>{forgeSetupMessage}</Text>
@@ -2031,6 +2066,27 @@ export function ChangesSurface({
);
}
function JujutsuCheckoutSummary({ status }: { status: CheckoutStatusResponse["payload"] | null }) {
const { t } = useTranslation();
const state = status?.jujutsu;
if (!state) return null;
return (
<View style={styles.forgeSetupCallout} testID="jujutsu-checkout">
<Text style={styles.forgeSetupCalloutText}>{`Jujutsu · ${state.changeId.slice(0, 12)}`}</Text>
<Text style={styles.forgeSetupCalloutText}>
{state.description.split("\n")[0] || t("workspace.git.jujutsu.noDescription")}
</Text>
{state.hasConflicts ? (
<Text style={styles.forgeSetupCalloutText}>{t("workspace.git.jujutsu.conflicts")}</Text>
) : null}
{state.bookmarks.length ? (
<Text style={styles.forgeSetupCalloutText}>{state.bookmarks.join(", ")}</Text>
) : null}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
container: {
flex: 1,
+239
View File
@@ -0,0 +1,239 @@
import { useCallback, useMemo, useState } from "react";
import { View, Text } from "react-native";
import { create } from "zustand";
import { StyleSheet } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import type { JujutsuCheckoutAction } from "@getpaseo/protocol/messages";
import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet";
import { Button } from "@/components/ui/button";
import { FormTextInput } from "@/components/ui/form-field";
import { useToast } from "@/contexts/toast-context";
import { useSessionStore } from "@/stores/session-store";
import { openExternalUrl } from "@/utils/open-external-url";
import { useCheckoutStatusQuery } from "./use-status-query";
type ActionKind = Exclude<JujutsuCheckoutAction["kind"], "fetch">;
type SubmitAction = (
changeId: string,
action: JujutsuCheckoutAction,
) => Promise<{
url: string | null;
error: { message: string } | null;
}>;
const SNAP_POINTS = ["55%", "85%"];
interface JujutsuActionRequest {
serverId: string;
cwd: string;
kind: ActionKind;
label: string;
}
/** The workspace actions button opens these forms; one host renders whichever is open. */
export const useJujutsuActionSheetStore = create<{
request: JujutsuActionRequest | null;
open: (request: JujutsuActionRequest) => void;
close: () => void;
}>((set) => ({
request: null,
open: (request) => set({ request }),
close: () => set({ request: null }),
}));
export function JujutsuActionSheetHost() {
const request = useJujutsuActionSheetStore((state) => state.request);
if (!request) return null;
return (
<JujutsuActionSheet
key={`${request.serverId}:${request.cwd}:${request.kind}`}
request={request}
/>
);
}
function JujutsuActionSheet({ request }: { request: JujutsuActionRequest }) {
const { serverId, cwd, kind, label } = request;
const client = useSessionStore((state) => state.sessions[serverId]?.client);
const close = useJujutsuActionSheetStore((state) => state.close);
const { status } = useCheckoutStatusQuery({ serverId, cwd });
const change = status?.jujutsu;
const submit = useCallback<SubmitAction>(
(changeId, action) => {
if (!client) throw new Error("Host disconnected");
return client.checkoutJujutsuAction(cwd, changeId, action);
},
[client, cwd],
);
if (!client || !change) return null;
return (
<JujutsuActionForm
kind={kind}
label={label}
changeId={change.changeId}
defaultBookmark={change.bookmarks.length === 1 ? change.bookmarks[0] : ""}
defaultDescription={change.description}
onClose={close}
submit={submit}
/>
);
}
function JujutsuActionForm({
kind,
label,
changeId,
defaultBookmark,
defaultDescription,
onClose,
submit,
}: {
kind: ActionKind;
label: string;
changeId: string;
defaultBookmark: string;
defaultDescription: string;
onClose: () => void;
submit: SubmitAction;
}) {
const { t } = useTranslation();
const toast = useToast();
const [expectedChangeId] = useState(changeId);
const [description, setDescription] = useState(
kind === "describe" ? defaultDescription.trim() : "",
);
const [bookmark, setBookmark] = useState(defaultBookmark);
const [base, setBase] = useState("");
const [title, setTitle] = useState(defaultDescription.trim().split("\n")[0]);
const [body, setBody] = useState("");
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
const action = useMemo(
() => buildAction(kind, { description, bookmark, base, title, body }),
[kind, description, bookmark, base, title, body],
);
const stale = expectedChangeId !== changeId;
const header = useMemo(() => ({ title: label }), [label]);
const close = useCallback(() => {
if (!pending) onClose();
}, [pending, onClose]);
const handleSubmit = useCallback(async () => {
if (!action || pending || stale) return;
setPending(true);
setError(null);
try {
const result = await submit(expectedChangeId, action);
if (result.error) throw new Error(result.error.message);
toast.show(t("workspace.git.jujutsu.actionComplete"), { variant: "success" });
onClose();
if (result.url) void openExternalUrl(result.url);
} catch (failure) {
setError(failure instanceof Error ? failure.message : String(failure));
} finally {
setPending(false);
}
}, [action, pending, stale, submit, expectedChangeId, toast, t, onClose]);
return (
<AdaptiveModalSheet visible={true} header={header} onClose={close} snapPoints={SNAP_POINTS}>
<View style={styles.form}>
{kind === "describe" || kind === "new" ? (
<FormTextInput
multiline
editable={!pending}
initialValue={description}
onChangeText={setDescription}
accessibilityLabel={t("workspace.git.jujutsu.description")}
placeholder={t("workspace.git.jujutsu.description")}
/>
) : (
<FormTextInput
editable={!pending}
initialValue={bookmark}
onChangeText={setBookmark}
autoCapitalize="none"
accessibilityLabel={t("workspace.git.jujutsu.bookmark")}
placeholder={t("workspace.git.jujutsu.bookmark")}
/>
)}
{kind === "create_pull_request" ? (
<>
<FormTextInput
editable={!pending}
initialValue={base}
onChangeText={setBase}
autoCapitalize="none"
accessibilityLabel={t("workspace.git.jujutsu.base")}
placeholder={t("workspace.git.jujutsu.base")}
/>
<FormTextInput
editable={!pending}
initialValue={title}
onChangeText={setTitle}
accessibilityLabel={t("workspace.git.jujutsu.title")}
placeholder={t("workspace.git.jujutsu.title")}
/>
<FormTextInput
multiline
editable={!pending}
initialValue={body}
onChangeText={setBody}
accessibilityLabel={t("workspace.git.jujutsu.description")}
placeholder={t("workspace.git.jujutsu.description")}
/>
</>
) : null}
{stale ? (
<Text accessibilityRole="alert" style={styles.error}>
{t("workspace.git.jujutsu.changeMoved")}
</Text>
) : null}
{error ? (
<Text accessibilityRole="alert" style={styles.error}>
{error}
</Text>
) : null}
<Button disabled={!action || pending || stale} loading={pending} onPress={handleSubmit}>
{label}
</Button>
</View>
</AdaptiveModalSheet>
);
}
function buildAction(
kind: ActionKind,
input: {
description: string;
bookmark: string;
base: string;
title: string;
body: string;
},
): JujutsuCheckoutAction | null {
const description = input.description.trim();
const bookmark = input.bookmark.trim();
const base = input.base.trim();
const title = input.title.trim();
switch (kind) {
case "describe":
return description ? { kind, description } : null;
case "new":
return { kind, description: description || undefined };
case "publish":
return bookmark ? { kind, bookmark, create: true } : null;
case "create_pull_request":
return bookmark && base && title
? { kind, bookmark, base, title, body: input.body.trim() }
: null;
}
return null;
}
const styles = StyleSheet.create((theme) => ({
form: { gap: theme.spacing[3], padding: theme.spacing[4] },
error: { color: theme.colors.destructive },
}));
@@ -0,0 +1,214 @@
import { useCallback, useMemo, useRef, useState } from "react";
import { Text, View } from "react-native";
import { GitBranch } from "lucide-react-native";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { CheckoutStatusResponse } from "@getpaseo/protocol/messages";
import type { Theme } from "@/styles/theme";
import { useFetchQuery } from "@/data/query";
import { Combobox, ComboboxItem, type ComboboxProps } from "@/components/ui/combobox";
import { ToolbarLabelSelectTrigger } from "@/components/ui/toolbar-label-trigger";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { invalidateCheckoutGitQueriesForClient } from "./query-keys";
import { jujutsuChangeLabel } from "./jujutsu-label";
type JujutsuState = NonNullable<CheckoutStatusResponse["payload"]["jujutsu"]>;
interface Props {
serverId: string;
cwd: string;
change: JujutsuState;
}
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const ThemedGitBranch = withUnistyles(GitBranch);
const mutedColor = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
function refLabel(ref: string): string {
return ref.replace(/^refs\/(heads|remotes)\//, "");
}
// Options are bookmarks (Git refs) or changes; changes carry this prefix and their exact commit ID.
const CHANGE_OPTION_PREFIX = "change:";
/**
* Where Git shows the current branch and switches it, show the working-copy change and start
* a new one on a chosen bookmark (`jj new <bookmark>`). The old change stays where it was.
*/
export function JujutsuChangeSwitcher({ serverId, cwd, change }: Props) {
const { t } = useTranslation();
const client = useHostRuntimeClient(serverId);
const connected = useHostRuntimeIsConnected(serverId);
const supported = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.features?.jujutsuCheckoutActions === true,
);
const queryClient = useQueryClient();
const anchorRef = useRef<View>(null);
const [open, setOpen] = useState(false);
const [search, setSearch] = useState("");
const query = useDebouncedValue(search, 200);
const label = jujutsuChangeLabel(change);
const title = t("workspace.git.jujutsu.startNewChangeOn");
const bookmarks = useFetchQuery({
queryKey: ["jujutsuParentBookmarks", serverId, cwd, query],
queryFn: async () => {
if (!client) throw new Error(t("common.errors.daemonClientUnavailable"));
const result = await client.getBranchSuggestions({
cwd,
refMode: "exact",
query,
limit: 200,
});
if (result.error) throw new Error(result.error);
return result.branches;
},
enabled: open && connected && Boolean(client),
retry: false,
dataShape: "value",
staleTimeMs: 0,
});
// Changes from across the repository: every workspace's work, side branches and bookmarks.
const changes = useFetchQuery({
queryKey: ["jujutsuChangeSearch", serverId, cwd, query],
queryFn: async () => {
if (!client) throw new Error(t("common.errors.daemonClientUnavailable"));
const result = await client.searchJujutsuChanges(cwd, query);
if (result.error) throw new Error(result.error.message);
return result.changes;
},
enabled: open && supported && connected && Boolean(client),
retry: false,
dataShape: "value",
staleTimeMs: 0,
});
const mutation = useMutation({
mutationFn: async (optionId: string) => {
if (!client) throw new Error(t("common.errors.daemonClientUnavailable"));
const parent = optionId.startsWith(CHANGE_OPTION_PREFIX)
? optionId.slice(CHANGE_OPTION_PREFIX.length)
: optionId;
const result = await client.checkoutJujutsuAction(cwd, change.changeId, {
kind: "new",
parent,
});
if (result.error) throw new Error(result.error.message);
},
onSuccess: async () => {
setOpen(false);
await invalidateCheckoutGitQueriesForClient(queryClient, { serverId, cwd });
},
});
const options = useMemo(() => {
const refs = (bookmarks.data ?? []).map((ref) => ({ id: ref, label: refLabel(ref) }));
const found = (changes.data ?? []).flatMap((entry) => {
// Untouched working copies (every workspace has one) aren't anything to build on.
if (entry.isEmpty && !entry.description && entry.workingCopies.length > 0) return [];
const owner = entry.workingCopies.map((name) => `${name}@`).join(" ");
const optionLabel = [
entry.changeId.slice(0, 8),
entry.description || t("workspace.git.jujutsu.noDescription"),
owner,
]
.filter(Boolean)
.join(" ");
return [{ id: `${CHANGE_OPTION_PREFIX}${entry.commitId}`, label: optionLabel }];
});
return [...refs, ...found];
}, [bookmarks.data, changes.data, t]);
const { reset, mutate, isPending } = mutation;
const error = mutation.error ?? bookmarks.error ?? changes.error;
const handleOpen = useCallback(() => {
reset();
setSearch("");
setOpen(true);
}, [reset]);
const handleSelect = useCallback(
(ref: string) => {
if (!isPending) mutate(ref);
},
[isPending, mutate],
);
const branchIcon = useMemo(() => <ThemedGitBranch size={14} uniProps={mutedColor} />, []);
const renderOption = useCallback<NonNullable<ComboboxProps["renderOption"]>>(
({ option, selected, active, onPress }) => (
<ComboboxItem
label={option.label}
leadingSlot={branchIcon}
selected={selected}
active={active}
onPress={onPress}
disabled={isPending}
/>
),
[isPending, branchIcon],
);
const footer = useMemo(
() => (
<View style={styles.footer}>
{isPending ? <ThemedLoadingSpinner size="small" uniProps={mutedColor} /> : null}
{error ? (
<Text accessibilityRole="alert" style={styles.error}>
{error.message}
</Text>
) : null}
</View>
),
[isPending, error],
);
if (!supported) return <Text style={styles.text}>{label}</Text>;
return (
<View ref={anchorRef} collapsable={false} style={styles.anchor}>
<ToolbarLabelSelectTrigger
testID="jujutsu-change-switcher-trigger"
label={label}
open={open}
disabled={!connected || isPending}
accessibilityRole="button"
accessibilityLabel={title}
onPress={handleOpen}
/>
<Combobox
options={options}
value={change.bookmarks[0] ? `refs/heads/${change.bookmarks[0]}` : ""}
onSelect={handleSelect}
keepOpenOnSelect
searchable
onSearchQueryChange={setSearch}
searchPlaceholder={t("workspace.git.jujutsu.filterBookmarksAndChanges")}
emptyText={
bookmarks.isFetching || changes.isFetching
? t("common.states.loading")
: t("workspace.git.jujutsu.noMatches")
}
title={title}
open={open}
onOpenChange={setOpen}
anchorRef={anchorRef}
desktopPlacement="bottom-start"
desktopPreventInitialFlash
desktopMinWidth={300}
renderOption={renderOption}
footer={error || isPending ? footer : undefined}
/>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
anchor: { flexShrink: 1, minWidth: 0, maxWidth: "40%" },
footer: { padding: theme.spacing[3], gap: theme.spacing[2] },
text: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm },
error: { color: theme.colors.destructive, fontSize: theme.fontSize.sm },
}));
+7
View File
@@ -0,0 +1,7 @@
/** How a Jujutsu change is named where Git would show a branch: its bookmark, else its change ID. */
export function jujutsuChangeLabel(change: {
changeId: string;
bookmarks: readonly string[];
}): string {
return change.bookmarks[0] ?? change.changeId.slice(0, 8);
}
+68 -142
View File
@@ -7,7 +7,6 @@ import {
buildGitActions,
isCurrentBranchBase,
canMergeIntoLocalBase,
readSyncRemotes,
readUpstreamState,
type BuildGitActionsInput,
} from "./policy";
@@ -61,11 +60,9 @@ 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, hasRemote = false, ...rest } = overrides;
const { pullRequestGithub = null, ...rest } = overrides;
return {
isGit: true,
githubFeaturesEnabled: true,
@@ -79,8 +76,8 @@ function createInput(
pullRequestIsMerged: false,
pullRequestMergeable: "UNKNOWN",
mergeCapability: deriveMergeCapability(pullRequestGithub),
hasPullRemote: hasRemote,
hasPushRemote: hasRemote,
hasRemote: false,
hasFirstPushRemote: rest.hasRemote ?? false,
upstream: "tracked",
isPaseoOwnedWorktree: false,
isOnBaseBranch: true,
@@ -170,6 +167,11 @@ function createInput(
status: "idle",
handler: () => undefined,
},
"jj-describe": { disabled: false, status: "idle", handler: () => undefined },
"jj-new": { disabled: false, status: "idle", handler: () => undefined },
"jj-fetch": { disabled: false, status: "idle", handler: () => undefined },
"jj-publish": { disabled: false, status: "idle", handler: () => undefined },
"jj-pr": { disabled: false, status: "idle", handler: () => undefined },
},
...rest,
};
@@ -179,10 +181,6 @@ 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");
@@ -440,7 +438,7 @@ describe("git-actions-policy", () => {
});
it("does not offer Push when Git pushes the branch to another remote", () => {
const actions = buildGitActions(createInput({ ...neverPushed, hasPushRemote: false }));
const actions = buildGitActions(createInput({ ...neverPushed, hasFirstPushRemote: false }));
const pushAction = pushActionOf(actions);
expect(actions.primary?.id).not.toBe("push");
@@ -448,142 +446,13 @@ describe("git-actions-policy", () => {
"Push isn't available here because this branch is not connected to a remote yet",
);
});
});
// 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", () => {
it("keeps offering Push in a Paseo worktree when Git pushes the branch to another remote", () => {
const actions = buildGitActions(
createInput({ ...tracksDorasMono, aheadOfOrigin: 1, behindOfOrigin: 0 }),
createInput({ ...neverPushed, hasFirstPushRemote: false, isPaseoOwnedWorktree: true }),
);
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 });
});
});
@@ -1566,3 +1435,60 @@ describe("git-actions-policy", () => {
]);
});
});
describe("Jujutsu checkout actions", () => {
const allAvailable = {
"jj-describe": true,
"jj-new": true,
"jj-fetch": true,
"jj-publish": true,
"jj-pr": false,
};
it("keeps archive drawable while hiding Git mutation actions", () => {
const actions = buildGitActions(
createInput({
isJujutsu: true,
isPaseoOwnedWorktree: true,
hasUncommittedChanges: true,
}),
);
// The split button only draws secondary actions beside a primary one.
expect(actions.primary?.id).toBe("archive-workspace");
expect(actions.secondary).toEqual([]);
expect(actions.menu).toEqual([]);
});
it("leads with describe until the change has a description", () => {
const actions = buildGitActions(
createInput({
isJujutsu: true,
jujutsu: { hasDescription: false, available: allAvailable },
}),
);
expect(actions.primary?.id).toBe("jj-describe");
expect(actions.secondary.map((action) => action.id)).toEqual([
"jj-new",
"jj-fetch",
"jj-publish",
"archive-workspace",
]);
});
it("leads with publish once the change is described", () => {
const actions = buildGitActions(
createInput({
isJujutsu: true,
jujutsu: { hasDescription: true, available: { ...allAvailable, "jj-pr": true } },
}),
);
expect(actions.primary?.id).toBe("jj-publish");
expect(actions.secondary.map((action) => action.id)).toEqual([
"jj-describe",
"jj-new",
"jj-fetch",
"jj-pr",
"archive-workspace",
]);
});
});
+84 -42
View File
@@ -25,7 +25,23 @@ export type GitActionId =
| "disable-pr-auto-merge"
| "merge-branch"
| "merge-from-base"
| "archive-workspace";
| "archive-workspace"
| JujutsuActionId;
export type JujutsuActionId = "jj-describe" | "jj-new" | "jj-fetch" | "jj-publish" | "jj-pr";
export const JUJUTSU_ACTION_IDS: readonly JujutsuActionId[] = [
"jj-describe",
"jj-new",
"jj-fetch",
"jj-publish",
"jj-pr",
];
export interface JujutsuActionsInput {
hasDescription: boolean;
available: Record<JujutsuActionId, boolean>;
}
export interface GitAction {
id: GitActionId;
@@ -96,42 +112,11 @@ export function readUpstreamState(
return status.isPaseoOwnedWorktree ? "none" : "unknown";
}
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 {
export interface BuildGitActionsInput {
isGit: boolean;
isJujutsu?: boolean;
/** Present for Jujutsu checkouts, whose actions replace the Git ones. */
jujutsu?: JujutsuActionsInput;
githubFeaturesEnabled: boolean;
/** Forge brand label (e.g. "GitHub", "GitLab") for forge-neutral unavailable copy. */
forgeBrandLabel: string;
@@ -145,6 +130,9 @@ export interface BuildGitActionsInput extends SyncRemotes {
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;
@@ -375,6 +363,10 @@ export function buildGitActions(input: BuildGitActionsInput): GitActions {
handler: input.runtime["archive-workspace"].handler,
});
if (input.isJujutsu) {
return buildJujutsuActions(input, allActions.get("archive-workspace")!);
}
const primaryActionId = getPrimaryActionId(input);
const primary = primaryActionId ? (allActions.get(primaryActionId) ?? null) : null;
@@ -603,11 +595,11 @@ function getEnablePullRequestAutoMergeActionLabel(id: PullRequestAutoMergeEnable
}
function canPull(input: BuildGitActionsInput): boolean {
return input.hasPullRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0;
return input.hasRemote && !input.hasUncommittedChanges && (input.behindOfOrigin ?? 0) > 0;
}
function canPush(input: BuildGitActionsInput): boolean {
return input.hasPushRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0;
return input.hasRemote && hasPushableCommits(input) && (input.behindOfOrigin ?? 0) === 0;
}
function hasPushableCommits(input: BuildGitActionsInput): boolean {
@@ -616,7 +608,9 @@ 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.
return input.aheadCount > 0;
// 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);
case "gone":
case "unknown":
// The branch has an upstream that is deleted or unreadable, so nothing counts the commits
@@ -707,7 +701,7 @@ function hasEnabledPrAutoMerge(input: BuildGitActionsInput): boolean {
}
function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasPullRemote) {
if (!input.hasRemote) {
return i18n.t("workspace.git.actions.unavailable.pullNoRemote");
}
if (input.hasUncommittedChanges) {
@@ -723,7 +717,7 @@ function getPullUnavailableMessage(input: BuildGitActionsInput): string | undefi
}
function getPushUnavailableMessage(input: BuildGitActionsInput): string | undefined {
if (!input.hasPushRemote) {
if (!input.hasRemote) {
return i18n.t("workspace.git.actions.unavailable.pushNoRemote");
}
if ((input.behindOfOrigin ?? 0) > 0) {
@@ -735,11 +729,14 @@ 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.hasPullRemote || !input.hasPushRemote) {
if (!input.hasRemote) {
return i18n.t("workspace.git.actions.unavailable.pullAndPushNoRemote");
}
if (input.hasUncommittedChanges) {
@@ -927,3 +924,48 @@ function isPullRequestMergeMethodAllowed(
}
return capability.allowedMethods.includes(method);
}
const JUJUTSU_ACTION_LABEL_KEYS: Record<JujutsuActionId, string> = {
"jj-describe": "describe",
"jj-new": "newChange",
"jj-fetch": "fetch",
"jj-publish": "publish",
"jj-pr": "createPullRequest",
};
// Jujutsu actions take the place of the Git ones in the same button: describe first when the
// change has no description yet, otherwise publish, and the rest (then archive) in the menu.
function buildJujutsuActions(input: BuildGitActionsInput, archive: GitAction): GitActions {
const jj = input.jujutsu;
const available = JUJUTSU_ACTION_IDS.filter((id) => jj?.available[id]);
const actions = available.map((id): GitAction => {
const key = JUJUTSU_ACTION_LABEL_KEYS[id];
return {
id,
label: i18n.t(`workspace.git.jujutsu.${key}`),
pendingLabel:
id === "jj-fetch"
? i18n.t("workspace.git.jujutsu.fetching")
: i18n.t(`workspace.git.jujutsu.${key}`),
successLabel:
id === "jj-fetch"
? i18n.t("workspace.git.jujutsu.fetched")
: i18n.t(`workspace.git.jujutsu.${key}`),
disabled: input.runtime[id].disabled,
status: input.runtime[id].status,
icon: input.runtime[id].icon,
startsGroup: false,
handler: input.runtime[id].handler,
};
});
let primaryId: JujutsuActionId | null = null;
if (!jj?.hasDescription && available.includes("jj-describe")) primaryId = "jj-describe";
else if (available.includes("jj-publish")) primaryId = "jj-publish";
else primaryId = available[0] ?? null;
const primary = actions.find((action) => action.id === primaryId) ?? null;
const secondary = actions.filter((action) => action !== primary);
if (!primary) return { primary: archive, secondary: [], menu: [] };
return { primary, secondary: [...secondary, archive], menu: [] };
}
@@ -18,6 +18,7 @@ import {
import type { PressableStateCallbackType } from "react-native";
import { useTranslation } from "react-i18next";
import { openExternalUrl } from "@/utils/open-external-url";
import { useCheckoutStatusCacheOnly } from "@/git/use-status-query";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { StatusBadge } from "@/components/ui/status-badge";
@@ -186,6 +187,15 @@ function removeLoadingCheck(current: ReadonlySet<string>, checkKey: string): Rea
return next;
}
/** Names the version control system the refresh button reloads alongside the forge. */
function useRefreshStateLabel(input: { serverId: string; cwd: string; brand: string }): string {
const { t } = useTranslation();
const { data: status } = useCheckoutStatusCacheOnly(input);
return status?.jujutsu
? t("workspace.git.diff.refreshJujutsuState", { brand: input.brand })
: t("workspace.git.diff.refreshState", { brand: input.brand });
}
export function PullRequestPane({
serverId,
cwd,
@@ -456,6 +466,11 @@ export function PullRequestPane({
const statePresentation = PR_STATE_PRESENTATION[data.state];
const StateIcon = statePresentation.Icon;
const forgePresentation = getForgePresentation(data.forge);
const refreshStateLabel = useRefreshStateLabel({
serverId,
cwd,
brand: forgePresentation.brandLabel,
});
const repoIdentity =
data.projectPath ??
(data.repoOwner && data.repoName ? `${data.repoOwner}/${data.repoName}` : null);
@@ -498,11 +513,7 @@ export function PullRequestPane({
<Pressable
accessibilityRole="button"
accessibilityLabel={
isRefreshing
? t("workspace.git.diff.refreshing")
: t("workspace.git.diff.refreshState", {
brand: forgePresentation.brandLabel,
})
isRefreshing ? t("workspace.git.diff.refreshing") : refreshStateLabel
}
testID="pr-pane-refresh"
style={toolbarRefreshButtonStyle}
+146 -14
View File
@@ -15,14 +15,15 @@ import {
isCurrentBranchBase,
canMergeIntoLocalBase,
narrowPullRequestState,
readSyncRemotes,
readUpstreamState,
type BuildGitActionsInput,
type GitAction,
type GitActions,
type GitUpstreamState,
type SyncRemotes,
type JujutsuActionsInput,
} from "@/git/policy";
import { useJujutsuActionSheetStore } from "@/git/jujutsu-actions";
import { jujutsuChangeLabel } from "@/git/jujutsu-label";
import { deriveMergeCapability } from "@/git/merge-capability";
import type { CheckoutPrMergeMethod } from "@getpaseo/protocol/messages";
import { openExternalUrl } from "@/utils/open-external-url";
@@ -125,15 +126,15 @@ interface DeriveGitActionsStateArgs {
baseRef: string | undefined;
}
const NO_SYNC_REMOTES: SyncRemotes = { hasPullRemote: false, hasPushRemote: false };
interface DerivedGitActionsState extends SyncRemotes {
interface DerivedGitActionsState {
actionsDisabled: boolean;
aheadCount: number;
behindBaseCount: number;
aheadOfOrigin: number | null;
behindOfOrigin: number | null;
hasPullRequest: boolean;
hasRemote: boolean;
hasFirstPushRemote: boolean;
upstream: GitUpstreamState;
isPaseoOwnedWorktree: boolean;
isOnBaseBranch: boolean;
@@ -167,6 +168,10 @@ function computeShouldPromoteArchive(input: {
);
}
function canUseGitMutations(status: CheckoutStatusPayload | null): boolean {
return status?.vcs?.capabilities.gitMutations ?? !status?.jujutsu;
}
function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActionsState {
const {
isGit,
@@ -178,14 +183,16 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
isStatusLoading,
baseRef,
} = args;
const actionsDisabled = !isGit || Boolean(status?.error) || isStatusLoading;
const actionsDisabled =
!isGit || !canUseGitMutations(status) || Boolean(status?.error) || isStatusLoading;
const isPaseoOwnedWorktree = gitStatus?.isPaseoOwnedWorktree ?? false;
const isMergedPullRequest = Boolean(prStatus?.isMerged);
return {
actionsDisabled,
...extractGitCommitCounts(gitStatus),
hasPullRequest: Boolean(prStatus?.url),
...(gitStatus ? readSyncRemotes(gitStatus) : NO_SYNC_REMOTES),
hasRemote: gitStatus?.hasRemote ?? false,
hasFirstPushRemote: (gitStatus?.firstPushRemote ?? null) !== null,
upstream: gitStatus ? readUpstreamState(gitStatus) : "unknown",
isPaseoOwnedWorktree,
isOnBaseBranch: isCurrentBranchBase(gitStatus?.currentBranch, baseRef),
@@ -254,10 +261,20 @@ function resolveArchiveWorkspaceDescriptor(input: {
return null;
}
// jj checkouts have no branch; name their working-copy change instead.
function currentBranchOrChange(status: CheckoutStatusPayload | null): string | null | undefined {
if (status?.jujutsu) return jujutsuChangeLabel(status.jujutsu);
return status?.isGit ? status.currentBranch : undefined;
}
function resolveWorkspaceArchiveRisk(
workspace: WorkspaceDescriptor | null,
gitStatus: CheckoutStatusPayload | null,
): { isDirty: boolean | null | undefined; aheadOfOrigin: number | null | undefined } {
// Archiving a jj workspace snapshots its working-copy change before removing the checkout.
if (gitStatus?.jujutsu || workspace?.gitRuntime?.jujutsu) {
return { isDirty: false, aheadOfOrigin: null };
}
return {
isDirty: gitStatus?.isDirty ?? workspace?.gitRuntime?.isDirty,
aheadOfOrigin: gitStatus?.aheadOfOrigin ?? workspace?.gitRuntime?.aheadOfOrigin,
@@ -354,7 +371,7 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
[baseRef, t],
);
const branchLabel = resolveBranchLabel({
currentBranch: gitStatus?.currentBranch,
currentBranch: currentBranchOrChange(status),
notGit,
notRepositoryLabel: t("workspace.git.diff.notRepository"),
unknownLabel: t("workspace.git.diff.branchUnknown"),
@@ -657,6 +674,15 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
archiveController.archive();
}, [archiveController]);
const { jujutsuInput, jujutsuRuntime } = useJujutsuActions({
serverId,
cwd,
status,
fetchIcon: icons.pull,
toastActionError,
toastActionSuccess,
});
const derived = deriveGitActionsState({
isGit,
status,
@@ -674,8 +700,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
aheadOfOrigin,
behindOfOrigin,
hasPullRequest,
hasPullRemote,
hasPushRemote,
hasRemote,
hasFirstPushRemote,
upstream,
isPaseoOwnedWorktree,
isOnBaseBranch,
@@ -696,6 +722,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
const presentation = getForgePresentation(forge);
return {
isGit,
isJujutsu: !canUseGitMutations(status),
jujutsu: jujutsuInput,
githubFeaturesEnabled,
forgeBrandLabel: presentation.brandLabel,
forgeChangeRequestNoun: presentation.changeRequestAbbrev,
@@ -707,8 +735,8 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
pullRequestIsMerged: prStatus?.isMerged ?? false,
pullRequestMergeable: prStatus?.mergeable ?? "UNKNOWN",
mergeCapability: deriveMergeCapability(prStatus?.forgeSpecific, prStatus?.github),
hasPullRemote,
hasPushRemote,
hasRemote,
hasFirstPushRemote,
upstream,
isPaseoOwnedWorktree,
isOnBaseBranch,
@@ -813,12 +841,16 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
icon: icons.archive,
handler: handleArchiveWorkspace,
},
...jujutsuRuntime,
},
};
}, [
status,
jujutsuInput,
jujutsuRuntime,
isGit,
hasPullRemote,
hasPushRemote,
hasRemote,
hasFirstPushRemote,
upstream,
hasPullRequest,
prStatus?.url,
@@ -935,6 +967,99 @@ function translateGitAction(
};
}
// Jujutsu: describe, new change, publish and PR open a form; fetch runs directly.
function useJujutsuActions({
serverId,
cwd,
status,
fetchIcon,
toastActionError,
toastActionSuccess,
}: {
serverId: string;
cwd: string;
status: CheckoutStatusPayload | null;
fetchIcon: ReactElement | undefined;
toastActionError: (error: unknown, fallback: string) => void;
toastActionSuccess: (message: string) => void;
}) {
const { t } = useTranslation();
const jujutsuChange = status?.jujutsu;
const jujutsuCapabilities = status?.vcs?.capabilities;
const jujutsuClient = useSessionStore((s) => s.sessions[serverId]?.client);
const jujutsuSupported = useSessionStore(
(s) => s.sessions[serverId]?.serverInfo?.features?.jujutsuCheckoutActions === true,
);
const openJujutsuSheet = useJujutsuActionSheetStore((s) => s.open);
const [jujutsuFetchPending, setJujutsuFetchPending] = useState(false);
const handleJujutsuFetch = useCallback(() => {
if (!jujutsuClient || !jujutsuChange) return;
setJujutsuFetchPending(true);
void jujutsuClient
.checkoutJujutsuAction(cwd, jujutsuChange.changeId, { kind: "fetch" })
.then((result) => {
if (result.error) throw new Error(result.error.message);
toastActionSuccess(t("workspace.git.jujutsu.fetched"));
return;
})
.catch((err) => {
toastActionError(err, t("workspace.git.jujutsu.fetchFailed"));
})
.finally(() => setJujutsuFetchPending(false));
}, [cwd, jujutsuChange, jujutsuClient, t, toastActionError, toastActionSuccess]);
const jujutsuInput = useMemo<JujutsuActionsInput | undefined>(() => {
if (!jujutsuSupported || !jujutsuChange || !jujutsuCapabilities) return undefined;
return {
hasDescription: jujutsuChange.description.trim().length > 0,
available: {
"jj-describe": jujutsuCapabilities.describe ?? false,
"jj-new": jujutsuCapabilities.newChange ?? false,
"jj-fetch": jujutsuCapabilities.fetch ?? false,
"jj-publish": jujutsuCapabilities.publishBookmark ?? false,
"jj-pr": jujutsuCapabilities.createPullRequest ?? false,
},
};
}, [jujutsuCapabilities, jujutsuChange, jujutsuSupported]);
const jujutsuRuntime = useMemo(() => {
const disabled = !jujutsuClient || !jujutsuChange;
const sheet = (
kind: "describe" | "new" | "publish" | "create_pull_request",
label: string,
) => ({
disabled,
status: "idle" as const,
handler: () => openJujutsuSheet({ serverId, cwd, kind, label }),
});
return {
"jj-describe": sheet("describe", t("workspace.git.jujutsu.describe")),
"jj-new": sheet("new", t("workspace.git.jujutsu.newChange")),
"jj-publish": sheet("publish", t("workspace.git.jujutsu.publish")),
"jj-pr": sheet("create_pull_request", t("workspace.git.jujutsu.createPullRequest")),
"jj-fetch": {
disabled: disabled || jujutsuFetchPending,
status: jujutsuFetchPending ? ("pending" as const) : ("idle" as const),
icon: fetchIcon,
handler: handleJujutsuFetch,
},
};
}, [
cwd,
handleJujutsuFetch,
fetchIcon,
jujutsuChange,
jujutsuClient,
jujutsuFetchPending,
openJujutsuSheet,
serverId,
t,
]);
return { jujutsuInput, jujutsuRuntime };
}
function getTranslatedGitActionLabels(
action: GitAction,
{
@@ -1046,6 +1171,13 @@ function getTranslatedGitActionLabels(
pendingLabel: t("workspace.git.actions.archive.pending"),
successLabel: t("workspace.git.actions.archive.success"),
};
// Jujutsu actions are labelled when they are built.
default:
return {
label: action.label,
pendingLabel: action.pendingLabel,
successLabel: action.successLabel,
};
}
}
+6 -6
View File
@@ -56,6 +56,8 @@ export function resolveCommitDiffFiles(
});
}
const EMPTY_COMMIT_FILES: CheckoutCommitFile[] = [];
export function useCommitDiffFiles(ctx: CommitDiffFilesContext): CommitDiffFilesResult {
const { serverId, cwd, sha, enabled = true } = ctx;
const retainedPanelActive = useRetainedPanelActive();
@@ -64,12 +66,9 @@ export function useCommitDiffFiles(ctx: CommitDiffFilesContext): CommitDiffFiles
const isConnected = useHostRuntimeIsConnected(serverId);
const commitsQuery = useCheckoutCommitsQuery({ serverId, cwd, enabled: queryEnabled });
const commitsData = commitsQuery.status === "loaded" ? commitsQuery.data : null;
const commitFiles = useMemo(() => {
if (!sha || !commitsData) {
return [];
}
return commitsData.commits.find((commit) => commit.sha === sha)?.files ?? [];
}, [commitsData, sha]);
const commit =
sha && commitsData ? commitsData.commits.find((candidate) => candidate.sha === sha) : undefined;
const commitFiles = commit?.files ?? EMPTY_COMMIT_FILES;
const fileDiffsEnabled =
queryEnabled &&
@@ -85,6 +84,7 @@ export function useCommitDiffFiles(ctx: CommitDiffFilesContext): CommitDiffFiles
cwd,
sha,
path: file.path,
jujutsuOperationId: commit?.jujutsu?.operationId,
client,
enabled: fileDiffsEnabled,
}),
@@ -20,6 +20,9 @@ interface Props {
workspaceId?: string | null;
cwd: string;
baseRef: string;
/** The checkout uses jj: refs are bookmarks, and remote ones read `name@remote`. */
isJujutsu?: boolean;
baseBookmarkMissing?: boolean;
}
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
@@ -30,7 +33,19 @@ function refLabel(ref: string): string {
return ref.replace(/^refs\/(heads|remotes)\//, "");
}
export function WorkspaceBaseBranchPicker({ serverId, workspaceId, cwd, baseRef }: Props) {
function bookmarkLabel(ref: string): string {
const remote = /^refs\/remotes\/([^/]+)\/(.+)$/.exec(ref);
return remote ? `${remote[2]}@${remote[1]}` : refLabel(ref);
}
export function WorkspaceBaseBranchPicker({
serverId,
workspaceId,
cwd,
baseRef,
isJujutsu = false,
baseBookmarkMissing = false,
}: Props) {
const { t } = useTranslation();
const client = useHostRuntimeClient(serverId);
const connected = useHostRuntimeIsConnected(serverId);
@@ -72,12 +87,22 @@ export function WorkspaceBaseBranchPicker({ serverId, workspaceId, cwd, baseRef
},
});
const options = useMemo(
() => (branches.data ?? []).map((ref) => ({ id: ref, label: refLabel(ref) })),
[branches.data],
() =>
(branches.data ?? []).map((ref) => ({
id: ref,
label: isJujutsu ? bookmarkLabel(ref) : refLabel(ref),
})),
[branches.data, isJujutsu],
);
const error = mutation.error ?? branches.error;
const title = t("workspace.git.diff.baseBranch.title");
const label = refLabel(baseRef).replace(/^origin\//, "");
const displayBase = isJujutsu
? bookmarkLabel(baseRef)
: refLabel(baseRef).replace(/^origin\//, "");
const label = baseBookmarkMissing
? t("workspace.git.jujutsu.missingBaseBookmark", { bookmark: displayBase })
: displayBase;
const emptyLabel = isJujutsu ? t("workspace.git.jujutsu.noBookmarks") : t("branchSwitcher.empty");
const { reset, mutate, isPending } = mutation;
const { refetch, isError } = branches;
@@ -148,8 +173,12 @@ export function WorkspaceBaseBranchPicker({ serverId, workspaceId, cwd, baseRef
keepOpenOnSelect
searchable
onSearchQueryChange={setSearch}
searchPlaceholder={t("branchSwitcher.searchPlaceholder")}
emptyText={branches.isFetching ? t("common.states.loading") : t("branchSwitcher.empty")}
searchPlaceholder={
isJujutsu
? t("workspace.git.jujutsu.filterBookmarks")
: t("branchSwitcher.searchPlaceholder")
}
emptyText={branches.isFetching ? t("common.states.loading") : emptyLabel}
title={title}
open={open}
onOpenChange={setOpen}
@@ -62,6 +62,8 @@ export async function readWorktreeArchiveRisk(
if (status.error) {
throw new Error(status.error.message);
}
// Archiving a jj workspace snapshots its working-copy change before removing the checkout.
if (status.jujutsu) return { isDirty: false, aheadOfOrigin: null };
return { isDirty: status.isDirty ?? false, aheadOfOrigin: status.aheadOfOrigin };
}
@@ -1,4 +1,5 @@
import { deriveEffectiveWorkspaceStatus } from "@/workspace-status";
import { jujutsuChangeLabel } from "@/git/jujutsu-label";
import equal from "fast-deep-equal";
import type { PrHint } from "@/git/pr-hint";
import { selectPrHintFromStatus } from "@/git/pr-hint";
@@ -46,12 +47,15 @@ export interface SidebarWorkspaceEntry extends SidebarStatusWorkspacePlacement {
title: string | null;
pinnedAt?: string | null;
labels?: string[];
// Checkout branch (null when not a git checkout or detached HEAD).
// Checkout branch, or for Jujutsu the bookmark or short change ID (null when not a git
// checkout or on a detached HEAD).
currentBranch: string | null;
archivingAt: string | null;
diffStat: { additions: number; deletions: number } | null;
prHint: PrHint | null;
archiveHasUncommittedChanges: boolean | null;
// currentBranch then holds the change's bookmark or short change ID.
isJujutsu?: boolean;
archiveUnpushedCommitCount: number | null;
scripts: WorkspaceDescriptor["scripts"];
hasRunningScripts: boolean;
@@ -167,7 +171,11 @@ export function createSidebarWorkspaceEntry(input: {
title: input.workspace.title ?? null,
pinnedAt: input.workspace.pinnedAt,
labels: input.workspace.labels ?? EMPTY_WORKSPACE_LABELS,
currentBranch: normalizeCurrentBranch(input.workspace.gitRuntime?.currentBranch),
currentBranch:
normalizeCurrentBranch(input.workspace.gitRuntime?.currentBranch) ??
(input.workspace.gitRuntime?.jujutsu
? jujutsuChangeLabel(input.workspace.gitRuntime.jujutsu)
: null),
statusBucket: effectiveStatus.status,
statusEnteredAt: effectiveStatus.enteredAt,
archivingAt: input.workspace.archivingAt,
@@ -176,7 +184,11 @@ export function createSidebarWorkspaceEntry(input: {
input.workspace.githubRuntime?.pullRequest,
input.workspace.forge,
),
archiveHasUncommittedChanges: input.workspace.gitRuntime?.isDirty ?? null,
// Archiving a jj workspace keeps its checkout and records its change, so nothing is lost.
archiveHasUncommittedChanges: input.workspace.gitRuntime?.jujutsu
? false
: (input.workspace.gitRuntime?.isDirty ?? null),
isJujutsu: Boolean(input.workspace.gitRuntime?.jujutsu),
archiveUnpushedCommitCount: input.workspace.gitRuntime?.aheadOfOrigin ?? null,
scripts: input.workspace.scripts,
hasRunningScripts: input.workspace.scripts.some((script) => script.lifecycle === "running"),
+7 -93
View File
@@ -4,7 +4,6 @@ import {
defaultHostAppearance,
normalizeStoredHostAppearance,
resolveHostBadgeDisplay,
resolveHostIcon,
selectHostBadges,
} from "@/hosts/appearance";
@@ -17,7 +16,7 @@ function host(
}
describe("normalizeStoredHostAppearance", () => {
it("defaults without writing an icon field so untouched records stay downgrade-safe", () => {
it("defaults when the stored registry predates the field or holds junk", () => {
const expected = { color: "none", badgeDisplay: null };
expect(normalizeStoredHostAppearance(undefined)).toEqual(expected);
expect(normalizeStoredHostAppearance(null)).toEqual(expected);
@@ -25,82 +24,16 @@ 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("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({
expect(normalizeStoredHostAppearance({ color: "teal", 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");
});
});
describe("resolveHostBadgeDisplay", () => {
it("hides the badge for the local host until the user chooses", () => {
expect(
@@ -117,13 +50,13 @@ describe("resolveHostBadgeDisplay", () => {
it("prefers an explicit choice over either default", () => {
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
appearance: { color: "none", badgeDisplay: "icon" },
isLocalHost: true,
}),
).toBe("icon");
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", icon: "server", badgeDisplay: "hidden" },
appearance: { color: "none", badgeDisplay: "hidden" },
isLocalHost: false,
}),
).toBe("hidden");
@@ -139,7 +72,7 @@ describe("resolveHostBadgeDisplay", () => {
).toBeNull();
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
appearance: { color: "none", badgeDisplay: "icon" },
isLocalHost: false,
localHostResolutionPending: true,
}),
@@ -160,7 +93,7 @@ describe("selectHostBadges", () => {
it("omits a host the user hid and keeps its sibling", () => {
const badges = selectHostBadges({
hosts: [
host("alpha", "Alpha", { color: "none", icon: "server", badgeDisplay: "hidden" }),
host("alpha", "Alpha", { color: "none", badgeDisplay: "hidden" }),
host("beta", "Beta"),
],
localServerId: null,
@@ -171,14 +104,13 @@ 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", icon: "mini", badgeDisplay: "icon" })],
hosts: [host("alpha", "Alpha", { color: "teal", badgeDisplay: "icon" })],
localServerId: null,
enabled: true,
});
@@ -186,7 +118,6 @@ describe("selectHostBadges", () => {
serverId: "alpha",
label: "Alpha",
color: "teal",
icon: "mini",
showLabel: false,
});
});
@@ -219,21 +150,4 @@ 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");
});
});
+4 -65
View File
@@ -6,69 +6,25 @@ 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.
* - `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.
* 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.
*/
export interface HostAppearance {
color: HostColor;
icon?: string;
badgeDisplay: HostBadgeDisplay | null;
}
const StoredHostAppearanceSchema = z.strictObject({
export const HostAppearanceSchema: z.ZodType<HostAppearance> = 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 };
}
@@ -78,17 +34,6 @@ 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;
@@ -107,7 +52,6 @@ export interface HostBadgeModel {
serverId: string;
label: string;
color: HostColor;
icon: HostIcon;
showLabel: boolean;
}
@@ -122,7 +66,6 @@ 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>();
@@ -142,10 +85,6 @@ 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",
});
}
@@ -1,134 +0,0 @@
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" });
});
});
@@ -1,120 +0,0 @@
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) };
}
}
}
+29 -8
View File
@@ -1,8 +1,9 @@
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { type HostBadgeModel, type HostColor } from "@/hosts/appearance";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Server } from "lucide-react-native";
import { HOST_COLORS, type HostBadgeModel, type HostColor } from "@/hosts/appearance";
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
@@ -10,9 +11,30 @@ import { identityForeground } from "@/styles/identity-colors";
*/
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: the host's device
* 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: a server 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
@@ -25,11 +47,10 @@ export function HostBadge({ badge }: { badge: HostBadgeModel }) {
testID={`host-badge-${badge.serverId}`}
accessibilityLabel={badge.label}
>
<HostIconGlyph
icon={badge.icon}
color={badge.color}
<ThemedServer
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}>
+27 -66
View File
@@ -7,16 +7,14 @@ 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 { HostStatusDot } from "@/components/host-status-dot";
import { HostStatusDotSlot } from "@/components/hosts/host-picker";
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 { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { useHosts } from "@/runtime/host-runtime";
import { orderHostsLocalFirst, type HostProfile } from "@/types/host-connection";
type HostFilter = (host: HostProfile) => boolean;
@@ -103,52 +101,36 @@ function HostChooserRow({
active: boolean;
onChooseHost: (serverId: string) => void;
}) {
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 { theme } = useUnistyles();
const handlePress = useCallback(() => onChooseHost(host.serverId), [host.serverId, onChooseHost]);
const rowStyle = useCallback(
({ pressed }: PressableStateCallbackType) => [
({ hovered = false, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
styles.row,
(active || hovered || pressed) && styles.rowActive,
],
[active, hovered],
[active],
);
return (
<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>
<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>
);
}
@@ -179,7 +161,6 @@ export function HostChooserModal() {
useEffect(() => {
if (!request) return;
getHostRuntimeStore().refreshActiveLatencies(request.serverIds);
inputRef.current?.replaceText("");
setQuery("");
setActiveIndex(0);
@@ -347,7 +328,7 @@ const styles = StyleSheet.create((theme) => ({
},
row: {
flexDirection: "row",
alignItems: "flex-start",
alignItems: "center",
gap: theme.spacing[3],
minHeight: 56,
paddingHorizontal: theme.spacing[4],
@@ -356,39 +337,19 @@ const styles = StyleSheet.create((theme) => ({
rowActive: {
backgroundColor: theme.colors.surface1,
},
rowTrailing: {
flexDirection: "row",
alignItems: "center",
height: 20,
flexShrink: 0,
},
rowIconSlot: {
width: 16,
height: 20,
width: 18,
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,
@@ -1,77 +0,0 @@
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
@@ -1,215 +0,0 @@
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,
},
}));
+11 -24
View File
@@ -1,13 +1,11 @@
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 host registry, local-host detection, daemon-reported
* machine kind, and each host's own appearance. `enabled` is the caller's own "off" — a surface
* 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
* 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.
*/
@@ -19,25 +17,14 @@ export function useHostBadges({
const hosts = useHosts();
const localServerId = useLocalDaemonServerId();
const localDaemon = useLocalDaemonServerIdState();
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(
() =>
selectHostBadges({
hosts,
localServerId,
localHostResolutionPending: localDaemon.status !== "resolved",
enabled,
}),
[hosts, localDaemon.status, localServerId, enabled],
);
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]);
}
+44 -25
View File
@@ -503,6 +503,7 @@ export const ar: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "نسخ الإشارة أو معرّف التغيير",
scriptsAccessibility: "البرامج النصية Workspace",
copyPath: "نسخ المسار",
copyBranchName: "نسخ اسم الفرع",
@@ -835,6 +836,38 @@ export const ar: TranslationResources = {
hideFolderTree: "إخفاء شجرة المجلدات",
},
git: {
jujutsu: {
filterBookmarks: "تصفية الإشارات…",
noBookmarks: "لم يتم العثور على إشارات.",
missingBaseBookmark: "{{bookmark}} (مفقودة)",
empty: "فارغ",
filterBookmarksAndChanges: "تصفية الإشارات والتغييرات",
noMatches: "لا توجد إشارات أو تغييرات مطابقة",
changes: {
title: "التغييرات",
countLabel: "{{count}} تغييرات في مساحة العمل",
noneAhead: "لا توجد تغييرات منذ {{baseRef}} بعد",
},
workingCopy: "نسخة العمل (@)",
startNewChangeOn: "بدء تغيير جديد على…",
fetch: "جلب",
fetching: "جارٍ الجلب…",
fetched: "تم الجلب من المستودع البعيد.",
fetchFailed: "تعذّر الجلب من المستودع البعيد.",
describe: "وصف",
newChange: "تغيير جديد",
publish: "نشر الإشارة المرجعية",
createPullRequest: "إنشاء طلب سحب",
description: "الوصف",
bookmark: "إشارة مرجعية",
base: "الإشارة المرجعية الأساسية",
title: "العنوان",
actionComplete: "اكتمل إجراء Jujutsu.",
changeMoved: "تغيّر تعديل نسخة العمل. أغلق النموذج وأعد المحاولة.",
currentChange: "التغيير الحالي",
noDescription: "(بدون وصف)",
conflicts: "تعارضات",
},
actions: {
moreOptions: "المزيد من الخيارات",
moreActions: "المزيد من الإجراءات",
@@ -1000,6 +1033,7 @@ export const ar: TranslationResources = {
refreshing: "منعش",
refresh: "ينعش",
refreshState: "تحديث حالة git و{{brand}}",
refreshJujutsuState: "تحديث حالة jj و{{brand}}",
failedRefresh: "فشل تحديث حالة git.",
seeUncommittedChanges: "عرض التغييرات غير الملتزم بها",
seeCommittedChanges: "عرض التغييرات الملتزم بها",
@@ -1398,12 +1432,15 @@ export const ar: TranslationResources = {
},
},
newWorkspace: {
defaultBase: "الفرع الافتراضي",
title: "مساحة عمل جديدة",
create: "يخلق",
isolation: {
jujutsu: "مساحة عمل jj جديدة",
local: "مجلد المشروع",
worktree: "شجرة عمل جديدة",
existing: "شجرة عمل موجودة",
existingJujutsu: "مساحة عمل jj موجودة",
label: "العزل",
},
fields: {
@@ -1429,9 +1466,11 @@ export const ar: TranslationResources = {
isolation: "Choose the isolation level",
startingRef: "اختر من أين تبدأ",
worktree: "اختر شجرة العمل التي تعمل فيها",
jujutsuWorkspace: "اختر مساحة عمل jj للعمل فيها",
launch: "Choose what to launch",
},
refPicker: {
searchBookmarks: "البحث في الإشارات",
startingRef: "بدء المرجع",
intoBase: "إلى {{baseRef}}",
searching: "جارٍ البحث...",
@@ -1462,6 +1501,11 @@ export const ar: TranslationResources = {
searchPlaceholder: "ابحث في أشجار العمل",
empty: "لا توجد أشجار عمل مطابقة.",
},
jujutsuWorkspacePicker: {
title: "مساحة العمل",
searchPlaceholder: "البحث في مساحات عمل jj",
empty: "لا توجد مساحات عمل jj مطابقة.",
},
launch: {
title: "What to launch",
chat: "Chat",
@@ -2841,23 +2885,6 @@ 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}}",
@@ -2894,14 +2921,6 @@ export const ar: TranslationResources = {
local: "محلي",
remoteSsh: "SSH عن بُعد",
},
connectionKinds: {
local: "محلي",
relay: "تتابع",
tailscale: "Tailscale",
ssh: "SSH",
direct: "مباشر",
routed: "عبر",
},
connections: {
title: "اتصالات",
removeTitle: "إزالة الاتصال",
+44 -25
View File
@@ -502,6 +502,7 @@ export const en = {
},
},
hoverCard: {
copyChangeName: "Copy bookmark or change ID",
scriptsAccessibility: "Workspace scripts",
copyPath: "Copy path",
copyBranchName: "Copy branch name",
@@ -832,6 +833,38 @@ export const en = {
hideFolderTree: "Hide folder tree",
},
git: {
jujutsu: {
filterBookmarks: "Filter bookmarks…",
noBookmarks: "No bookmarks found.",
missingBaseBookmark: "{{bookmark}} (missing)",
empty: "empty",
filterBookmarksAndChanges: "Filter bookmarks and changes",
noMatches: "No matching bookmarks or changes",
changes: {
title: "Changes",
countLabel: "{{count}} workspace changes",
noneAhead: "No changes since {{baseRef}} yet",
},
workingCopy: "Working copy (@)",
startNewChangeOn: "Start new change on…",
fetch: "Fetch",
fetching: "Fetching…",
fetched: "Fetched from the remote.",
fetchFailed: "Couldn't fetch from the remote.",
describe: "Describe",
newChange: "New change",
publish: "Publish bookmark",
createPullRequest: "Create pull request",
description: "Description",
bookmark: "Bookmark",
base: "Base bookmark",
title: "Title",
actionComplete: "Jujutsu action completed.",
changeMoved: "The working-copy change moved. Close this form and try again.",
currentChange: "Current change",
noDescription: "(no description)",
conflicts: "Conflicts",
},
actions: {
moreOptions: "More options",
moreActions: "More actions",
@@ -1011,6 +1044,7 @@ export const en = {
refreshing: "Refreshing",
refresh: "Refresh",
refreshState: "Refresh git and {{brand}} state",
refreshJujutsuState: "Refresh jj and {{brand}} state",
failedRefresh: "Failed to refresh git state.",
seeUncommittedChanges: "See uncommitted changes",
seeCommittedChanges: "See committed changes",
@@ -1409,12 +1443,15 @@ export const en = {
},
},
newWorkspace: {
defaultBase: "Default branch",
title: "New workspace",
create: "Create",
isolation: {
jujutsu: "New jj workspace",
local: "Project directory",
worktree: "New worktree",
existing: "Existing worktree",
existingJujutsu: "Existing jj workspace",
label: "Isolation",
},
fields: {
@@ -1440,9 +1477,11 @@ export const en = {
isolation: "Choose the isolation level",
startingRef: "Choose where to start from",
worktree: "Choose the worktree to work in",
jujutsuWorkspace: "Choose the jj workspace to work in",
launch: "Choose what to launch",
},
refPicker: {
searchBookmarks: "Search bookmarks",
startingRef: "Starting ref",
intoBase: "into {{baseRef}}",
searching: "Searching...",
@@ -1473,6 +1512,11 @@ export const en = {
searchPlaceholder: "Search worktrees",
empty: "No matching worktrees.",
},
jujutsuWorkspacePicker: {
title: "Workspace",
searchPlaceholder: "Search jj workspaces",
empty: "No matching jj workspaces.",
},
launch: {
title: "What to launch",
chat: "Chat",
@@ -2936,23 +2980,6 @@ 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}}",
@@ -2989,14 +3016,6 @@ 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",
+45 -25
View File
@@ -509,6 +509,7 @@ export const es: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "Copiar marcador o ID de cambio",
scriptsAccessibility: "GuionesWorkspace",
copyPath: "Copiar ruta",
copyBranchName: "Copiar nombre de rama",
@@ -843,6 +844,39 @@ export const es: TranslationResources = {
hideFolderTree: "Ocultar árbol de carpetas",
},
git: {
jujutsu: {
filterBookmarks: "Filtrar marcadores…",
noBookmarks: "No se encontraron marcadores.",
missingBaseBookmark: "{{bookmark}} (no disponible)",
empty: "vacío",
filterBookmarksAndChanges: "Filtrar marcadores y cambios",
noMatches: "No hay marcadores ni cambios que coincidan",
changes: {
title: "Cambios",
countLabel: "{{count}} cambios del espacio de trabajo",
noneAhead: "Aún no hay cambios desde {{baseRef}}",
},
workingCopy: "Copia de trabajo (@)",
startNewChangeOn: "Iniciar un cambio nuevo en…",
fetch: "Obtener",
fetching: "Obteniendo…",
fetched: "Cambios obtenidos del remoto.",
fetchFailed: "No se pudo obtener del remoto.",
describe: "Describir",
newChange: "Nuevo cambio",
publish: "Publicar marcador",
createPullRequest: "Crear solicitud de cambios",
description: "Descripción",
bookmark: "Marcador",
base: "Marcador base",
title: "Título",
actionComplete: "Acción de Jujutsu completada.",
changeMoved:
"El cambio de la copia de trabajo se movió. Cierra el formulario y vuelve a intentarlo.",
currentChange: "Cambio actual",
noDescription: "(sin descripción)",
conflicts: "Conflictos",
},
actions: {
moreOptions: "Más opciones",
moreActions: "Más acciones",
@@ -1034,6 +1068,7 @@ export const es: TranslationResources = {
refreshing: "Refrescante",
refresh: "Refrescar",
refreshState: "Actualizar el estado de git y {{brand}}",
refreshJujutsuState: "Actualizar el estado de jj y {{brand}}",
failedRefresh: "No se pudo actualizar el estado de git.",
seeUncommittedChanges: "Ver cambios no confirmados",
seeCommittedChanges: "Ver cambios confirmados",
@@ -1435,12 +1470,15 @@ export const es: TranslationResources = {
},
},
newWorkspace: {
defaultBase: "Rama predeterminada",
title: "Nuevo espacio de trabajo",
create: "Crear",
isolation: {
jujutsu: "Nuevo espacio de trabajo jj",
local: "Directorio del proyecto",
worktree: "Nuevo worktree",
existing: "Worktree existente",
existingJujutsu: "Espacio de trabajo jj existente",
label: "Aislamiento",
},
fields: {
@@ -1466,9 +1504,11 @@ export const es: TranslationResources = {
isolation: "Choose the isolation level",
startingRef: "Elige por dónde empezar",
worktree: "Elige el worktree en el que trabajar",
jujutsuWorkspace: "Elige el espacio de trabajo jj en el que trabajar",
launch: "Choose what to launch",
},
refPicker: {
searchBookmarks: "Buscar marcadores",
startingRef: "Árbitro inicial",
intoBase: "en {{baseRef}}",
searching: "Búsqueda...",
@@ -1499,6 +1539,11 @@ export const es: TranslationResources = {
searchPlaceholder: "Buscar worktrees",
empty: "No hay worktrees que coincidan.",
},
jujutsuWorkspacePicker: {
title: "Espacio de trabajo",
searchPlaceholder: "Buscar espacios de trabajo jj",
empty: "No hay espacios de trabajo jj que coincidan.",
},
launch: {
title: "What to launch",
chat: "Chat",
@@ -2865,23 +2910,6 @@ 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}}",
@@ -2918,14 +2946,6 @@ 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",
+45 -25
View File
@@ -508,6 +508,7 @@ export const fr: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "Copier le signet ou l'ID du changement",
scriptsAccessibility: "Scripts de l’espace de travail",
copyPath: "Copier le chemin",
copyBranchName: "Copier le nom de la branche",
@@ -844,6 +845,39 @@ export const fr: TranslationResources = {
hideFolderTree: "Masquer l’arborescence des dossiers",
},
git: {
jujutsu: {
filterBookmarks: "Filtrer les signets…",
noBookmarks: "Aucun signet trouvé.",
missingBaseBookmark: "{{bookmark}} (introuvable)",
empty: "vide",
filterBookmarksAndChanges: "Filtrer les signets et les changements",
noMatches: "Aucun signet ni changement correspondant",
changes: {
title: "Changements",
countLabel: "{{count}} changements de l'espace de travail",
noneAhead: "Aucun changement depuis {{baseRef}} pour l'instant",
},
workingCopy: "Copie de travail (@)",
startNewChangeOn: "Commencer un nouveau changement sur…",
fetch: "Récupérer",
fetching: "Récupération…",
fetched: "Récupéré depuis le dépôt distant.",
fetchFailed: "Impossible de récupérer depuis le dépôt distant.",
describe: "Décrire",
newChange: "Nouveau changement",
publish: "Publier le signet",
createPullRequest: "Créer une demande de fusion",
description: "Description",
bookmark: "Signet",
base: "Signet de base",
title: "Titre",
actionComplete: "Action Jujutsu terminée.",
changeMoved:
"Le changement de la copie de travail a évolué. Fermez le formulaire et réessayez.",
currentChange: "Changement actuel",
noDescription: "(sans description)",
conflicts: "Conflits",
},
actions: {
moreOptions: "Plus d’options",
moreActions: "Plus d’actions",
@@ -1026,6 +1060,7 @@ export const fr: TranslationResources = {
refreshing: "Actualisation…",
refresh: "Actualiser",
refreshState: "Actualiser l’état de git et de {{brand}}",
refreshJujutsuState: "Actualiser l’état de jj et de {{brand}}",
failedRefresh: "Impossible d’actualiser l’état git.",
seeUncommittedChanges: "Voir les modifications non commitées",
seeCommittedChanges: "Voir les modifications commitées",
@@ -1428,12 +1463,15 @@ export const fr: TranslationResources = {
},
},
newWorkspace: {
defaultBase: "Branche par défaut",
title: "Nouvel espace de travail",
create: "Créer",
isolation: {
jujutsu: "Nouvel espace de travail jj",
local: "Répertoire du projet",
worktree: "Nouveau worktree",
existing: "Worktree existant",
existingJujutsu: "Espace de travail jj existant",
label: "Isolation",
},
fields: {
@@ -1459,9 +1497,11 @@ export const fr: TranslationResources = {
isolation: "Choisir le niveau d’isolation",
startingRef: "Choisir le point de départ",
worktree: "Choisir le worktree où travailler",
jujutsuWorkspace: "Choisir l’espace de travail jj où travailler",
launch: "Choisir quoi lancer",
},
refPicker: {
searchBookmarks: "Rechercher des signets",
startingRef: "Réf. de départ",
intoBase: "vers {{baseRef}}",
searching: "Recherche…",
@@ -1492,6 +1532,11 @@ export const fr: TranslationResources = {
searchPlaceholder: "Rechercher des worktrees",
empty: "Aucun worktree correspondant.",
},
jujutsuWorkspacePicker: {
title: "Espace de travail",
searchPlaceholder: "Rechercher des espaces de travail jj",
empty: "Aucun espace de travail jj correspondant.",
},
launch: {
title: "Que lancer ?",
chat: "Chat",
@@ -2867,23 +2912,6 @@ 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}}",
@@ -2920,14 +2948,6 @@ 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",
+44 -25
View File
@@ -509,6 +509,7 @@ export const ja: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "ブックマークまたは変更 ID をコピー",
scriptsAccessibility: "ワークスペーススクリプト",
copyPath: "パスをコピー",
copyBranchName: "ブランチ名をコピー",
@@ -839,6 +840,38 @@ export const ja: TranslationResources = {
hideFolderTree: "フォルダツリーを非表示",
},
git: {
jujutsu: {
filterBookmarks: "ブックマークを絞り込む…",
noBookmarks: "ブックマークが見つかりません。",
missingBaseBookmark: "{{bookmark}}(見つかりません)",
empty: "空",
filterBookmarksAndChanges: "ブックマークと変更を絞り込む",
noMatches: "一致するブックマークや変更はありません",
changes: {
title: "変更",
countLabel: "ワークスペースの変更 {{count}} 件",
noneAhead: "{{baseRef}} 以降の変更はまだありません",
},
workingCopy: "作業コピー (@)",
startNewChangeOn: "新しい変更を開始する場所…",
fetch: "フェッチ",
fetching: "フェッチ中…",
fetched: "リモートからフェッチしました。",
fetchFailed: "リモートからフェッチできませんでした。",
describe: "説明を設定",
newChange: "新しい変更",
publish: "ブックマークを公開",
createPullRequest: "プルリクエストを作成",
description: "説明",
bookmark: "ブックマーク",
base: "ベースのブックマーク",
title: "タイトル",
actionComplete: "Jujutsu の操作が完了しました。",
changeMoved: "作業コピーの変更が移動しました。フォームを閉じて再試行してください。",
currentChange: "現在の変更",
noDescription: "(説明なし)",
conflicts: "競合",
},
actions: {
moreOptions: "その他のオプション",
moreActions: "その他のアクション",
@@ -1014,6 +1047,7 @@ export const ja: TranslationResources = {
refreshing: "更新中",
refresh: "更新",
refreshState: "gitと{{brand}}の状態を更新",
refreshJujutsuState: "jjと{{brand}}の状態を更新",
failedRefresh: "gitの状態の更新に失敗しました。",
seeUncommittedChanges: "未コミットの変更を表示",
seeCommittedChanges: "コミット済みの変更を表示",
@@ -1413,12 +1447,15 @@ export const ja: TranslationResources = {
},
},
newWorkspace: {
defaultBase: "デフォルトブランチ",
title: "新しいワークスペース",
create: "作成",
isolation: {
jujutsu: "新しい jj ワークスペース",
local: "プロジェクトディレクトリ",
worktree: "新しいワークツリー",
existing: "既存のワークツリー",
existingJujutsu: "既存の jj ワークスペース",
label: "分離方法",
},
fields: {
@@ -1444,9 +1481,11 @@ export const ja: TranslationResources = {
isolation: "Choose the isolation level",
startingRef: "開始点を選択",
worktree: "作業するワークツリーを選択",
jujutsuWorkspace: "作業する jj ワークスペースを選択",
launch: "Choose what to launch",
},
refPicker: {
searchBookmarks: "ブックマークを検索",
startingRef: "開始Ref",
intoBase: "{{baseRef}}に",
searching: "検索中...",
@@ -1477,6 +1516,11 @@ export const ja: TranslationResources = {
searchPlaceholder: "ワークツリーを検索",
empty: "一致するワークツリーがありません。",
},
jujutsuWorkspacePicker: {
title: "ワークスペース",
searchPlaceholder: "jj ワークスペースを検索",
empty: "一致する jj ワークスペースはありません。",
},
launch: {
title: "What to launch",
chat: "Chat",
@@ -2833,23 +2877,6 @@ 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}}",
@@ -2886,14 +2913,6 @@ export const ja: TranslationResources = {
local: "ローカル",
remoteSsh: "リモート SSH",
},
connectionKinds: {
local: "ローカル",
relay: "リレー",
tailscale: "Tailscale",
ssh: "SSH",
direct: "ダイレクト",
routed: "経由",
},
connections: {
title: "接続",
removeTitle: "接続を削除",
+44 -25
View File
@@ -504,6 +504,7 @@ export const ko: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "북마크 또는 변경 ID 복사",
scriptsAccessibility: "워크스페이스 스크립트",
copyPath: "경로 복사",
copyBranchName: "브랜치 이름 복사",
@@ -835,6 +836,38 @@ export const ko: TranslationResources = {
hideFolderTree: "폴더 트리 숨기기",
},
git: {
jujutsu: {
filterBookmarks: "북마크 필터…",
noBookmarks: "북마크를 찾을 수 없습니다.",
missingBaseBookmark: "{{bookmark}} (없음)",
empty: "비어 있음",
filterBookmarksAndChanges: "북마크 및 변경 필터",
noMatches: "일치하는 북마크나 변경이 없습니다",
changes: {
title: "변경",
countLabel: "작업 공간 변경 {{count}}개",
noneAhead: "아직 {{baseRef}} 이후 변경이 없습니다",
},
workingCopy: "작업 사본 (@)",
startNewChangeOn: "새 변경을 시작할 위치…",
fetch: "가져오기",
fetching: "가져오는 중…",
fetched: "원격에서 가져왔습니다.",
fetchFailed: "원격에서 가져오지 못했습니다.",
describe: "설명 작성",
newChange: "새 변경",
publish: "북마크 게시",
createPullRequest: "풀 리퀘스트 생성",
description: "설명",
bookmark: "북마크",
base: "기준 북마크",
title: "제목",
actionComplete: "Jujutsu 작업이 완료되었습니다.",
changeMoved: "작업 복사본의 변경이 이동했습니다. 양식을 닫고 다시 시도하세요.",
currentChange: "현재 변경 사항",
noDescription: "(설명 없음)",
conflicts: "충돌",
},
actions: {
moreOptions: "옵션 더 보기",
moreActions: "작업 더 보기",
@@ -1007,6 +1040,7 @@ export const ko: TranslationResources = {
refreshing: "새로고침 중",
refresh: "새로고침",
refreshState: "Git 및 {{brand}} 상태 새로고침",
refreshJujutsuState: "jj 및 {{brand}} 상태 새로고침",
failedRefresh: "Git 상태를 새로고침하지 못했습니다.",
seeUncommittedChanges: "커밋되지 않은 변경 사항 보기",
seeCommittedChanges: "커밋된 변경 사항 보기",
@@ -1405,12 +1439,15 @@ export const ko: TranslationResources = {
},
},
newWorkspace: {
defaultBase: "기본 브랜치",
title: "새 워크스페이스",
create: "생성",
isolation: {
jujutsu: "새 jj 작업 공간",
local: "프로젝트 디렉터리",
worktree: "새 워크트리",
existing: "기존 워크트리",
existingJujutsu: "기존 jj 작업 공간",
label: "격리",
},
fields: {
@@ -1436,9 +1473,11 @@ export const ko: TranslationResources = {
isolation: "Choose the isolation level",
startingRef: "시작 위치를 선택하세요",
worktree: "작업할 워크트리를 선택하세요",
jujutsuWorkspace: "작업할 jj 작업 공간 선택",
launch: "Choose what to launch",
},
refPicker: {
searchBookmarks: "북마크 검색",
startingRef: "시작 ref",
intoBase: "{{baseRef}}(으)로",
searching: "검색 중...",
@@ -1469,6 +1508,11 @@ export const ko: TranslationResources = {
searchPlaceholder: "워크트리 검색",
empty: "일치하는 워크트리가 없습니다.",
},
jujutsuWorkspacePicker: {
title: "작업 공간",
searchPlaceholder: "jj 작업 공간 검색",
empty: "일치하는 jj 작업 공간이 없습니다.",
},
launch: {
title: "What to launch",
chat: "Chat",
@@ -2819,23 +2863,6 @@ 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}}",
@@ -2872,14 +2899,6 @@ export const ko: TranslationResources = {
local: "로컬",
remoteSsh: "원격 SSH",
},
connectionKinds: {
local: "로컬",
relay: "릴레이",
tailscale: "Tailscale",
ssh: "SSH",
direct: "직접 연결",
routed: "경유",
},
connections: {
title: "연결",
removeTitle: "연결 제거",
+45 -25
View File
@@ -508,6 +508,7 @@ export const ptBR: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "Copiar marcador ou ID da alteração",
scriptsAccessibility: "Scripts do workspace",
copyPath: "Copiar caminho",
copyBranchName: "Copiar nome da branch",
@@ -839,6 +840,39 @@ export const ptBR: TranslationResources = {
hideFolderTree: "Ocultar árvore de pastas",
},
git: {
jujutsu: {
filterBookmarks: "Filtrar marcadores…",
noBookmarks: "Nenhum marcador encontrado.",
missingBaseBookmark: "{{bookmark}} (ausente)",
empty: "vazia",
filterBookmarksAndChanges: "Filtrar marcadores e alterações",
noMatches: "Nenhum marcador ou alteração correspondente",
changes: {
title: "Alterações",
countLabel: "{{count}} alterações do espaço de trabalho",
noneAhead: "Nenhuma alteração desde {{baseRef}} ainda",
},
workingCopy: "Cópia de trabalho (@)",
startNewChangeOn: "Iniciar nova alteração em…",
fetch: "Buscar",
fetching: "Buscando…",
fetched: "Buscado do remoto.",
fetchFailed: "Não foi possível buscar do remoto.",
describe: "Descrever",
newChange: "Nova alteração",
publish: "Publicar marcador",
createPullRequest: "Criar solicitação de pull",
description: "Descrição",
bookmark: "Marcador",
base: "Marcador base",
title: "Título",
actionComplete: "Ação do Jujutsu concluída.",
changeMoved:
"A alteração da cópia de trabalho mudou. Feche o formulário e tente novamente.",
currentChange: "Alteração atual",
noDescription: "(sem descrição)",
conflicts: "Conflitos",
},
actions: {
moreOptions: "Mais opções",
moreActions: "Mais ações",
@@ -1024,6 +1058,7 @@ export const ptBR: TranslationResources = {
refreshing: "Atualizando",
refresh: "Atualizar",
refreshState: "Atualizar estado do git e do {{brand}}",
refreshJujutsuState: "Atualizar estado do jj e do {{brand}}",
failedRefresh: "Falha ao atualizar estado do git.",
seeUncommittedChanges: "Ver alterações sem commit",
seeCommittedChanges: "Ver alterações com commit",
@@ -1425,12 +1460,15 @@ export const ptBR: TranslationResources = {
},
},
newWorkspace: {
defaultBase: "Branch padrão",
title: "Novo workspace",
create: "Criar",
isolation: {
jujutsu: "Novo espaço de trabalho jj",
local: "Diretório do projeto",
worktree: "Novo worktree",
existing: "Worktree existente",
existingJujutsu: "Espaço de trabalho jj existente",
label: "Isolamento",
},
fields: {
@@ -1456,9 +1494,11 @@ export const ptBR: TranslationResources = {
isolation: "Choose the isolation level",
startingRef: "Escolha de onde começar",
worktree: "Escolha o worktree em que trabalhar",
jujutsuWorkspace: "Escolha o espaço de trabalho jj em que trabalhar",
launch: "Choose what to launch",
},
refPicker: {
searchBookmarks: "Buscar marcadores",
startingRef: "Ref inicial",
intoBase: "em {{baseRef}}",
searching: "Buscando...",
@@ -1489,6 +1529,11 @@ export const ptBR: TranslationResources = {
searchPlaceholder: "Buscar worktrees",
empty: "Nenhum worktree correspondente.",
},
jujutsuWorkspacePicker: {
title: "Espaço de trabalho",
searchPlaceholder: "Pesquisar espaços de trabalho jj",
empty: "Nenhum espaço de trabalho jj correspondente.",
},
launch: {
title: "What to launch",
chat: "Chat",
@@ -2846,23 +2891,6 @@ 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}}",
@@ -2899,14 +2927,6 @@ 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",
+44 -25
View File
@@ -509,6 +509,7 @@ export const ru: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "Копировать закладку или ID изменения",
scriptsAccessibility: "Скрипты рабочего пространства",
copyPath: "Копировать путь",
copyBranchName: "Копировать имя ветки",
@@ -844,6 +845,38 @@ export const ru: TranslationResources = {
hideFolderTree: "Скрыть дерево папок",
},
git: {
jujutsu: {
filterBookmarks: "Фильтр закладок…",
noBookmarks: "Закладки не найдены.",
missingBaseBookmark: "{{bookmark}} (отсутствует)",
empty: "пусто",
filterBookmarksAndChanges: "Фильтр закладок и изменений",
noMatches: "Нет подходящих закладок или изменений",
changes: {
title: "Изменения",
countLabel: "Изменений в рабочем пространстве: {{count}}",
noneAhead: "Пока нет изменений после {{baseRef}}",
},
workingCopy: "Рабочая копия (@)",
startNewChangeOn: "Начать новое изменение на…",
fetch: "Получить",
fetching: "Получение…",
fetched: "Изменения получены с удалённого репозитория.",
fetchFailed: "Не удалось получить изменения с удалённого репозитория.",
describe: "Добавить описание",
newChange: "Новое изменение",
publish: "Опубликовать закладку",
createPullRequest: "Создать запрос на слияние",
description: "Описание",
bookmark: "Закладка",
base: "Базовая закладка",
title: "Заголовок",
actionComplete: "Действие Jujutsu выполнено.",
changeMoved: "Изменение рабочей копии переместилось. Закройте форму и повторите попытку.",
currentChange: "Текущее изменение",
noDescription: "(без описания)",
conflicts: "Конфликты",
},
actions: {
moreOptions: "Дополнительные параметры",
moreActions: "Дополнительные действия",
@@ -1019,6 +1052,7 @@ export const ru: TranslationResources = {
refreshing: "Обновление",
refresh: "Обновить",
refreshState: "Обновить состояние Git и {{brand}}",
refreshJujutsuState: "Обновить состояние jj и {{brand}}",
failedRefresh: "Не удалось обновить состояние Git.",
seeUncommittedChanges: "Показать незафиксированные изменения",
seeCommittedChanges: "Показать зафиксированные изменения",
@@ -1418,12 +1452,15 @@ export const ru: TranslationResources = {
},
},
newWorkspace: {
defaultBase: "Ветка по умолчанию",
title: "Новое рабочее пространство",
create: "Создать",
isolation: {
jujutsu: "Новое рабочее пространство jj",
local: "Папка проекта",
worktree: "Новый worktree",
existing: "Существующий worktree",
existingJujutsu: "Существующее рабочее пространство jj",
label: "Изоляция",
},
fields: {
@@ -1449,9 +1486,11 @@ export const ru: TranslationResources = {
isolation: "Выберите уровень изоляции",
startingRef: "Выберите, с чего начать",
worktree: "Выберите worktree для работы",
jujutsuWorkspace: "Выберите рабочее пространство jj",
launch: "Выберите, что запустить",
},
refPicker: {
searchBookmarks: "Поиск закладок",
startingRef: "Исходная точка",
intoBase: "в ветку {{baseRef}}",
searching: "Идет поиск...",
@@ -1482,6 +1521,11 @@ export const ru: TranslationResources = {
searchPlaceholder: "Поиск worktree",
empty: "Нет подходящих worktree.",
},
jujutsuWorkspacePicker: {
title: "Рабочее пространство",
searchPlaceholder: "Поиск рабочих пространств jj",
empty: "Нет подходящих рабочих пространств jj.",
},
launch: {
title: "Что запустить",
chat: "Чат",
@@ -2854,23 +2898,6 @@ 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}}",
@@ -2907,14 +2934,6 @@ export const ru: TranslationResources = {
local: "Локальный",
remoteSsh: "Удалённый SSH",
},
connectionKinds: {
local: "Локальный",
relay: "Ретранслятор",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Прямой",
routed: "Через",
},
connections: {
title: "Подключения",
removeTitle: "Удалить подключение",
+44 -25
View File
@@ -503,6 +503,7 @@ export const zhCN: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "复制书签或更改 ID",
scriptsAccessibility: "Workspace scripts",
copyPath: "复制路径",
copyBranchName: "复制分支名称",
@@ -831,6 +832,38 @@ export const zhCN: TranslationResources = {
hideFolderTree: "隐藏文件夹树",
},
git: {
jujutsu: {
filterBookmarks: "筛选书签…",
noBookmarks: "未找到书签。",
missingBaseBookmark: "{{bookmark}}(已丢失)",
empty: "空",
filterBookmarksAndChanges: "筛选书签和更改",
noMatches: "没有匹配的书签或更改",
changes: {
title: "更改",
countLabel: "{{count}} 个工作区更改",
noneAhead: "自 {{baseRef}} 以来尚无更改",
},
workingCopy: "工作副本 (@)",
startNewChangeOn: "在…上开始新更改",
fetch: "获取",
fetching: "正在获取…",
fetched: "已从远程获取。",
fetchFailed: "无法从远程获取。",
describe: "设置描述",
newChange: "新建变更",
publish: "发布书签",
createPullRequest: "创建拉取请求",
description: "描述",
bookmark: "书签",
base: "基准书签",
title: "标题",
actionComplete: "Jujutsu 操作已完成。",
changeMoved: "工作副本的变更已移动。关闭表单后重试。",
currentChange: "当前变更",
noDescription: "(无描述)",
conflicts: "冲突",
},
actions: {
moreOptions: "更多选项",
moreActions: "更多操作",
@@ -992,6 +1025,7 @@ export const zhCN: TranslationResources = {
refreshing: "正在刷新",
refresh: "刷新",
refreshState: "刷新 git 和 {{brand}} 状态",
refreshJujutsuState: "刷新 jj 和 {{brand}} 状态",
failedRefresh: "刷新 git 状态失败。",
seeUncommittedChanges: "查看未 commit 的变更",
seeCommittedChanges: "查看已 commit 的变更",
@@ -1387,12 +1421,15 @@ export const zhCN: TranslationResources = {
},
},
newWorkspace: {
defaultBase: "默认分支",
title: "新建 workspace",
create: "创建",
isolation: {
jujutsu: "新的 jj 工作区",
local: "项目目录",
worktree: "新建 worktree",
existing: "已有 worktree",
existingJujutsu: "已有 jj 工作区",
label: "隔离",
},
fields: {
@@ -1418,9 +1455,11 @@ export const zhCN: TranslationResources = {
isolation: "Choose the isolation level",
startingRef: "选择起始位置",
worktree: "选择要工作的 worktree",
jujutsuWorkspace: "选择要使用的 jj 工作区",
launch: "Choose what to launch",
},
refPicker: {
searchBookmarks: "搜索书签",
startingRef: "起始 ref",
intoBase: "进入 {{baseRef}}",
searching: "正在搜索...",
@@ -1451,6 +1490,11 @@ export const zhCN: TranslationResources = {
searchPlaceholder: "搜索 worktree",
empty: "没有匹配的 worktree。",
},
jujutsuWorkspacePicker: {
title: "工作区",
searchPlaceholder: "搜索 jj 工作区",
empty: "没有匹配的 jj 工作区。",
},
launch: {
title: "What to launch",
chat: "Chat",
@@ -2775,23 +2819,6 @@ 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}}",
@@ -2828,14 +2855,6 @@ export const zhCN: TranslationResources = {
local: "本地",
remoteSsh: "远程 SSH",
},
connectionKinds: {
local: "本地",
relay: "中继",
tailscale: "Tailscale",
ssh: "SSH",
direct: "直连",
routed: "经由",
},
connections: {
title: "连接",
removeTitle: "移除连接",
+6 -175
View File
@@ -1114,106 +1114,6 @@ 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) => {
@@ -3466,11 +3366,7 @@ describe("HostRuntimeStore", () => {
store.boot();
await registryLoaded;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "none",
badgeDisplay: null,
});
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
expect(store.getHosts()[0]?.appearance).toEqual({ color: "none", badgeDisplay: null });
store.syncHosts([]);
});
@@ -3495,7 +3391,6 @@ 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");
@@ -3507,60 +3402,10 @@ 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", icon: "server", badgeDisplay: null },
appearance: { color: "amber", badgeDisplay: null },
});
const storage = createMemoryHostRuntimeStorage();
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
@@ -3578,16 +3423,11 @@ describe("HostRuntimeStore", () => {
await store.setHostBadgeDisplay("srv_appearance", "icon");
await hostListChanged;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "amber",
icon: "server",
badgeDisplay: "icon",
});
expect(store.getHosts()[0]?.appearance).toEqual({ color: "amber", badgeDisplay: "icon" });
const persisted = await storage.getItem("@paseo:daemon-registry");
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
color: "amber",
icon: "server",
badgeDisplay: "icon",
});
@@ -3636,25 +3476,16 @@ 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, icon, display]);
await Promise.all([color, display]);
expect(store.getHosts()[0]?.appearance).toEqual({
color: "teal",
icon: "mini",
badgeDisplay: "icon",
});
expect(store.getHosts()[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
const persistedHosts = JSON.parse((await storage.getItem("@paseo:daemon-registry")) ?? "[]");
expect(persistedHosts[0]?.appearance).toEqual({
color: "teal",
icon: "mini",
badgeDisplay: "icon",
});
expect(persistedHosts[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
store.syncHosts([]);
});
+15 -91
View File
@@ -28,12 +28,7 @@ import {
type HostProfile,
type UnreadableHostEntries,
} from "@/types/host-connection";
import {
defaultHostAppearance,
type HostBadgeDisplay,
type HostColor,
type HostIcon,
} from "@/hosts/appearance";
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
import {
buildDaemonWebSocketUrl,
buildRelayWebSocketUrl,
@@ -950,56 +945,6 @@ 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;
@@ -1056,32 +1001,30 @@ export class HostRuntimeController {
return;
}
const initialProbes = new Map(this.snapshot.probeByConnectionId);
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
for (const connection of connectionsToProbe) {
this.connectionLastProbedAt.set(connection.id, performance.now());
const existingProbe = initialProbes.get(connection.id);
const existingProbe = probeByConnectionId.get(connection.id);
const shouldPreserveActiveLatency =
isOnline && connection.id === activeConnectionId && existingProbe?.status === "available";
if (!shouldPreserveActiveLatency) {
initialProbes.set(connection.id, {
probeByConnectionId.set(connection.id, {
status: "pending",
latencyMs: null,
});
}
}
this.updateSnapshot({ probeByConnectionId: initialProbes });
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
let remaining = connectionsToProbe.length;
let probeAuthFailure: "password_required" | "incorrect_password" | null = null;
let activationLock: Promise<void> | null = null;
// 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 => {
const publishProbeState = (): void => {
if (!this.isCurrentProbeRequest(requestVersion)) {
return;
}
this.setConnectionProbe(connectionId, probe);
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
};
const maybeActivateFirstAvailable = async (
@@ -1110,7 +1053,6 @@ export class HostRuntimeController {
return;
}
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
const currentActiveConnectionId = this.snapshot.activeConnectionId;
if (currentActiveConnectionId) {
this.reconcileActiveProbeWithClient(currentActiveConnectionId, probeByConnectionId);
@@ -1266,10 +1208,11 @@ export class HostRuntimeController {
if (activeClient) {
if (activeClient.getConnectionState().status !== "connected") {
publishConnectionProbe(connection.id, {
probeByConnectionId.set(connection.id, {
status: "unavailable",
latencyMs: null,
});
publishProbeState();
return;
}
const rttMs = activeClient.getLastLivenessRttMs();
@@ -1278,10 +1221,11 @@ export class HostRuntimeController {
}
if (rttMs !== null) {
this.recordActiveRttSample(rttMs, performance.now());
publishConnectionProbe(connection.id, {
probeByConnectionId.set(connection.id, {
status: "available",
latencyMs: rttMs,
});
publishProbeState();
}
return;
}
@@ -1291,10 +1235,11 @@ export class HostRuntimeController {
return;
}
publishConnectionProbe(connection.id, {
probeByConnectionId.set(connection.id, {
status: "available",
latencyMs: rttMs,
});
publishProbeState();
} catch (error) {
if (this.isCurrentProbeRequest(requestVersion)) {
const authFailure = getConnectionAuthFailureReason(error);
@@ -1302,10 +1247,11 @@ export class HostRuntimeController {
this.authRejectedConnectionIds.add(connection.id);
probeAuthFailure = authFailure;
}
publishConnectionProbe(connection.id, {
probeByConnectionId.set(connection.id, {
status: "unavailable",
latencyMs: null,
});
publishProbeState();
}
} finally {
if (connectedClient && shouldCloseClient) {
@@ -2490,16 +2436,6 @@ 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,
@@ -2507,16 +2443,6 @@ 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,
@@ -3370,7 +3296,6 @@ 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>;
@@ -3386,7 +3311,6 @@ 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),
@@ -303,6 +303,7 @@ const WorkspaceGitRuntimeSchema = z
aheadBehind: z.strictObject({ ahead: z.number(), behind: z.number() }).nullable().optional(),
aheadOfOrigin: z.number().nullable().optional(),
behindOfOrigin: z.number().nullable().optional(),
jujutsu: z.strictObject({ changeId: z.string(), bookmarks: z.array(z.string()) }).optional(),
})
.nullable()
.optional();
@@ -9,6 +9,7 @@ import {
defaultBasePickerItem,
pickerItemToCheckoutRequest,
refListOptions,
selectWorkspaceBase,
startsNewBranch,
type PickerItem,
} from "./new-workspace-picker-item";
@@ -405,9 +406,19 @@ describe("defaultBasePickerItem", () => {
});
});
it("has no default for detached HEAD", () => {
it("has no default for detached HEAD without a repository base", () => {
expect(defaultBasePickerItem({ currentBranch: null })).toBeNull();
});
it("names the repository's base on a detached HEAD instead of guessing", () => {
expect(
defaultBasePickerItem({
currentBranch: null,
baseRef: "master",
baseRefExact: "refs/remotes/origin/master",
}),
).toMatchObject({ kind: "branch", name: "master", refName: "refs/remotes/origin/master" });
});
});
describe("starting-ref search", () => {
@@ -480,3 +491,119 @@ describe("startsNewBranch", () => {
).toBe(true);
});
});
describe("Jujutsu workspace bases", () => {
it("offers the current change as an explicit branch-off target", () => {
const { options, itemById } = buildPickerOptionData({
branchDetails: [{ name: "main", committerDate: 1, hasLocal: true }],
prItems: [],
baseItem: null,
currentChangeLabel: "Current change",
});
expect(options[0]).toEqual({ id: branchPickerOptionId("@"), label: "Current change (@)" });
expect(pickerItemToCheckoutRequest(itemById.get(options[0].id) ?? null)).toEqual({
action: "branch-off",
refName: "@",
});
});
it("uses a Jujutsu base when switching from a selected pull request", () => {
const selected: PickerItem = { kind: "github-pr", item: prItem };
const base = selectWorkspaceBase(selected, {
cwd: "/repo",
requestId: "status",
error: null,
isGit: true,
isPaseoOwnedWorktree: false,
repoRoot: "/repo",
mainRepoRoot: null,
currentBranch: null,
isDirty: false,
baseRef: "main",
baseRefExact: "refs/remotes/origin/main",
aheadBehind: null,
upstreamRef: null,
aheadOfOrigin: null,
behindOfOrigin: null,
hasRemote: true,
remoteUrl: "https://example.com/repo",
vcs: { kind: "jujutsu", capabilities: { isolatedWorkspace: true, gitMutations: false } },
});
expect(pickerItemToCheckoutRequest(base)).toEqual({
action: "branch-off",
refName: "refs/remotes/origin/main",
});
});
it("defaults a Jujutsu base to the nearest bookmark under the working copy", () => {
const base = selectWorkspaceBase(null, {
cwd: "/repo",
requestId: "status",
error: null,
isGit: true,
isPaseoOwnedWorktree: false,
repoRoot: "/repo",
mainRepoRoot: null,
currentBranch: null,
isDirty: false,
baseRef: "main",
baseRefExact: "refs/remotes/origin/main",
aheadBehind: null,
upstreamRef: null,
aheadOfOrigin: null,
behindOfOrigin: null,
hasRemote: true,
remoteUrl: "https://example.com/repo",
vcs: { kind: "jujutsu", capabilities: { isolatedWorkspace: true, gitMutations: false } },
jujutsu: {
changeId: "kzzsnoxqotrt",
commitId: "d89b0034",
description: "",
bookmarks: [],
hasConflicts: false,
nearestBookmark: "feature",
},
});
expect(pickerItemToCheckoutRequest(base)).toEqual({
action: "branch-off",
refName: "refs/heads/feature",
});
});
it("defaults to the current Jujutsu change when there is no bookmark", () => {
const base = selectWorkspaceBase(null, {
cwd: "/repo",
requestId: "status",
error: null,
isGit: true,
isPaseoOwnedWorktree: false,
repoRoot: "/repo",
mainRepoRoot: null,
currentBranch: null,
isDirty: false,
baseRef: null,
aheadBehind: null,
upstreamRef: null,
aheadOfOrigin: null,
behindOfOrigin: null,
hasRemote: false,
remoteUrl: null,
vcs: { kind: "jujutsu", capabilities: { isolatedWorkspace: true, gitMutations: false } },
});
const { itemById, selectedOptionId } = buildPickerOptionData({
branchDetails: [],
prItems: [],
baseItem: base,
currentChangeLabel: "Current change",
});
expect(itemById.get(selectedOptionId)).toMatchObject({
kind: "branch",
name: "Current change (@)",
});
expect(pickerItemToCheckoutRequest(base)).toEqual({ action: "branch-off", refName: "@" });
});
});
@@ -1,5 +1,5 @@
import type { CreatePaseoWorktreeInput } from "@getpaseo/client/internal/daemon-client";
import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
import type { CheckoutStatusResponse, ForgeSearchItem } from "@getpaseo/protocol/messages";
import type { ComboboxOptionModel } from "@/components/ui/combobox-options";
import { getForgePresentation } from "@/git/forge";
@@ -137,6 +137,9 @@ export function buildBranchPickerItems(details: readonly BranchPickerDetail[]):
export interface BaseRefCheckoutStatus {
currentBranch: string | null;
upstreamRef?: string | null;
baseRef?: string | null;
baseRefExact?: string | null;
comparisonBaseRef?: string | null;
}
// Display only. The exact ref is what every request carries; this is just how a ref reads in
@@ -162,6 +165,38 @@ function refQualifier(refName: string): string | null {
return null;
}
function repositoryBasePickerItem(status: BaseRefCheckoutStatus): PickerItem | null {
const refName = status.baseRefExact ?? status.comparisonBaseRef ?? status.baseRef;
if (!refName) return null;
const name = branchNameFromRef(refName);
return { kind: "branch", name, refName, accessibilityLabel: name };
}
export function selectWorkspaceBase(
selected: PickerItem | null,
status: CheckoutStatusResponse["payload"] | null,
): PickerItem | null {
if (status?.jujutsu || status?.vcs?.kind === "jujutsu") {
if (selected?.kind === "branch") return selected;
// Like Git's current branch: the closest bookmark under the working copy, leaving the
// working copy's own unfinished edits behind.
const name = status.jujutsu?.nearestBookmark;
// Colocated checkouts export bookmarks as branches, so this matches the branch list's row.
if (name) {
return { kind: "branch", name, refName: `refs/heads/${name}`, accessibilityLabel: name };
}
return (
repositoryBasePickerItem(status) ?? {
kind: "branch",
name: "@",
refName: "@",
accessibilityLabel: "@",
}
);
}
return selected ?? (status ? defaultBasePickerItem(status) : null);
}
// The one owner of "what do we branch off when the user picked nothing". The checkmarked
// row, the trigger label, and the created ref all read this; computing it twice is how the
// picker once showed local main while branching off something else.
@@ -171,7 +206,9 @@ function refQualifier(refName: string): string | null {
// than a remote name, so a fork tracking upstream/main branches from upstream/main.
export function defaultBasePickerItem(status: BaseRefCheckoutStatus): PickerItem | null {
const currentBranch = status.currentBranch;
if (!currentBranch) return null;
// On a detached HEAD there is no branch to follow; name the base the daemon would use
// anyway, so the picker shows what will actually be created from.
if (!currentBranch) return repositoryBasePickerItem(status);
// COMPAT(checkoutUpstreamRef): added in v0.2.6, remove after 2027-02-01 once the daemon
// floor sends upstreamRef. Daemons that predate it omit the field, which lands on the
// local ref — the base those daemons always used.
@@ -294,6 +331,7 @@ export function buildPickerOptionData(input: {
branchDetails: readonly BranchPickerDetail[];
prItems: readonly ForgeSearchItem[];
baseItem: PickerItem | null;
currentChangeLabel?: string;
}): PickerOptionData {
const itemById = new Map<string, PickerItem>();
const timedOptions: TimedOption[] = [];
@@ -308,6 +346,13 @@ export function buildPickerOptionData(input: {
});
}
if (input.currentChangeLabel) {
const id = branchPickerOptionId("@");
const name = `${input.currentChangeLabel} (@)`;
itemById.set(id, { kind: "branch", name, refName: "@", accessibilityLabel: name });
timedOptions.push({ option: { id, label: name }, timestamp: Infinity });
}
for (const pr of input.prItems) {
if (!pr.headRefName) continue;
const id = prPickerOptionId(pr.number);
@@ -89,7 +89,7 @@ import {
} from "./new-workspace-fork-context";
import {
buildPickerOptionData,
defaultBasePickerItem,
selectWorkspaceBase,
pickerItemLabel,
startsNewBranch,
type BranchPickerDetail,
@@ -1078,11 +1078,28 @@ export function NewWorkspaceScreen({
cwd: selectedSourceDirectory,
enabled: supportsWorktreeList && isConnected,
});
const {
checkoutStatus,
supportsRefActions,
allowsGitRefActions,
isolatedWorkspaceSupported,
isJujutsu,
pickerQueryEnabled,
changeRequestSearchEnabled,
} = useWorkspaceCheckoutCapabilities({
serverId: selectedServerId,
sourceDirectory: selectedSourceDirectory,
pickerOpen,
isConnected,
hasClient: Boolean(client),
});
const { setup, pluginProject, canCreateWorktree, isPending } = usePluginSetup({
serverId: selectedServerId,
project: selectedProject,
worktrees: projectWorktrees,
supportsMultiplicity: supportsWorkspaceMultiplicity,
supportsRefActions,
isolatedWorkspaceSupported,
pendingAction,
isDraftHandoffActive,
updatePreferences: updateFormPreferences,
@@ -1091,7 +1108,6 @@ export function NewWorkspaceScreen({
const dispatchPickerSelection = setup.dispatchPicker;
const setupState = useNewWorkspaceSetupState(setup);
const selectedItem = setupState.pickerSelection.selectedItem;
const supportsRefActions = useHostFeature(selectedServerId, "worktreeRefActions");
const { refActions } = setupState;
const refActionFor = useMemo(
() => ({
@@ -1124,15 +1140,6 @@ export function NewWorkspaceScreen({
return connectedClient;
}, [selectedServerId, t]);
const clientReady = isConnected && Boolean(client);
const hasSelectedSourceDirectory = selectedSourceDirectory !== null;
const pickerQueryEnabled = pickerOpen && clientReady && hasSelectedSourceDirectory;
const { status: checkoutStatus } = useCheckoutStatusQuery({
serverId: selectedServerId,
cwd: selectedSourceDirectory ?? "",
});
const {
effectiveIsolation,
setIsolation,
@@ -1173,7 +1180,7 @@ export function NewWorkspaceScreen({
const changeRequestContext = useChangeRequestContext({
serverId: selectedServerId,
cwd: selectedSourceDirectory,
pickerOpen: pickerQueryEnabled,
pickerOpen: changeRequestSearchEnabled,
selectedItem,
});
@@ -1184,7 +1191,7 @@ export function NewWorkspaceScreen({
query: debouncedPickerSearchQuery,
kinds: ["change_request"],
supportsForgeSearch,
enabled: pickerQueryEnabled,
enabled: changeRequestSearchEnabled,
});
const branchDetails = useMemo(
@@ -1194,12 +1201,12 @@ export function NewWorkspaceScreen({
const forgeSearchAuthenticated =
!githubPrSearchQuery.data || githubPrSearchQuery.data.authState === "authenticated";
const prItems: ForgeSearchItem[] = useMemo(() => {
if (!forgeSearchAuthenticated) return [];
if (!allowsGitRefActions || !forgeSearchAuthenticated) return [];
return githubPrSearchQuery.data?.items ?? [];
}, [forgeSearchAuthenticated, githubPrSearchQuery.data?.items]);
}, [allowsGitRefActions, forgeSearchAuthenticated, githubPrSearchQuery.data?.items]);
const baseItem = useMemo(
() => selectedItem ?? (checkoutStatus ? defaultBasePickerItem(checkoutStatus) : null),
() => selectWorkspaceBase(selectedItem, checkoutStatus),
[checkoutStatus, selectedItem],
);
const { options, itemById, selectedOptionId }: PickerOptionData = useMemo(
@@ -1208,13 +1215,14 @@ export function NewWorkspaceScreen({
branchDetails,
prItems,
baseItem,
currentChangeLabel: isJujutsu ? t("workspace.git.jujutsu.currentChange") : undefined,
}),
[baseItem, branchDetails, prItems],
[baseItem, branchDetails, isJujutsu, prItems, t],
);
const triggerLabel = useMemo(() => {
const displayItem = itemById.get(selectedOptionId);
return displayItem ? pickerItemLabel(displayItem) : "main";
}, [itemById, selectedOptionId]);
return displayItem ? pickerItemLabel(displayItem) : t("newWorkspace.defaultBase");
}, [itemById, selectedOptionId, t]);
const selectPickerItem = useCallback(
(item: PickerItem) => {
setup.chooseRef(item);
@@ -1355,9 +1363,7 @@ export function NewWorkspaceScreen({
const checkoutRequest = checkoutStatusForCreate
? checkoutRequestOrExplain(
() =>
setup.checkoutRequestFor(
selectedItem ?? defaultBasePickerItem(checkoutStatusForCreate),
),
setup.checkoutRequestFor(selectWorkspaceBase(selectedItem, checkoutStatusForCreate)),
t,
)
: undefined;
@@ -1617,6 +1623,7 @@ export function NewWorkspaceScreen({
onOpenChange: handleIsolationPickerOpenChange,
choice,
canCreateWorktree,
isJujutsu,
onSelect: setIsolation,
existingWorktrees,
existingWorktreePath,
@@ -1641,6 +1648,8 @@ export function NewWorkspaceScreen({
actionFor: refActionFor,
onActionChange: setup.chooseRefAction,
canChooseAction: supportsRefActions,
canChooseChangeRequest: allowsGitRefActions,
isJujutsu,
changeRequestContext,
},
launch: {
@@ -1737,11 +1746,41 @@ export function NewWorkspaceScreen({
* The setup model, built with what the screen has this render so a plugin item's mount effect can
* already run commands, and kept current on every commit.
*/
function useWorkspaceCheckoutCapabilities(input: {
serverId: string;
sourceDirectory: string | null;
pickerOpen: boolean;
isConnected: boolean;
hasClient: boolean;
}) {
const { status: checkoutStatus } = useCheckoutStatusQuery({
serverId: input.serverId,
cwd: input.sourceDirectory ?? "",
});
const supportsRefActions = useHostFeature(input.serverId, "worktreeRefActions");
const isJujutsu = checkoutStatus?.vcs?.kind === "jujutsu" || Boolean(checkoutStatus?.jujutsu);
const capabilities = checkoutStatus?.vcs?.capabilities;
const allowsGitRefActions = capabilities?.gitMutations ?? !isJujutsu;
const pickerQueryEnabled =
input.pickerOpen && input.isConnected && input.hasClient && input.sourceDirectory !== null;
return {
checkoutStatus,
isJujutsu,
allowsGitRefActions,
isolatedWorkspaceSupported: capabilities?.isolatedWorkspace,
supportsRefActions: supportsRefActions && allowsGitRefActions,
pickerQueryEnabled,
changeRequestSearchEnabled: pickerQueryEnabled && allowsGitRefActions,
};
}
function usePluginSetup(input: {
serverId: string;
project: Parameters<typeof getHostProjectId>[0] | null;
worktrees: SetupInputs["worktrees"];
supportsMultiplicity: boolean;
supportsRefActions: boolean;
isolatedWorkspaceSupported: boolean | undefined;
pendingAction: Parameters<typeof isNewWorkspacePending>[0]["pendingAction"];
isDraftHandoffActive: boolean;
updatePreferences: ReturnType<typeof useFormPreferences>["updatePreferences"];
@@ -1752,6 +1791,8 @@ function usePluginSetup(input: {
project,
worktrees,
supportsMultiplicity,
supportsRefActions,
isolatedWorkspaceSupported,
pendingAction,
isDraftHandoffActive,
updatePreferences,
@@ -1760,7 +1801,8 @@ function usePluginSetup(input: {
const worktreeSupport = project
? getWorktreeSupportForHostProject({ project, serverId })
: "unsupported";
const canCreateWorktree = supportsMultiplicity && worktreeSupport !== "unsupported";
const canCreateWorktree =
supportsMultiplicity && (isolatedWorkspaceSupported ?? worktreeSupport !== "unsupported");
const locked = isNewWorkspacePending({ pendingAction, isDraftHandoffActive });
const supportsMetadata = useHostFeature(serverId, "entityMetadata");
const projectId = project ? getHostProjectId(project, serverId) : null;
@@ -1769,7 +1811,6 @@ function usePluginSetup(input: {
() => (projectId && projectName ? { id: projectId, name: projectName } : null),
[projectId, projectName],
);
const supportsRefActions = useHostFeature(serverId, "worktreeRefActions");
const inputs: SetupInputs = {
serverId,
locked,
@@ -89,6 +89,8 @@ export interface NewWorkspaceFormProps {
isolation: PickerControl & {
choice: IsolationChoice;
canCreateWorktree: boolean;
/** The source is a Jujutsu checkout, so a new isolated workspace is a jj workspace. */
isJujutsu?: boolean;
onSelect: (isolation: Isolation) => void;
/** The project's worktrees other than its own directory, newest first. */
existingWorktrees: readonly ExistingWorktree[];
@@ -112,6 +114,9 @@ export interface NewWorkspaceFormProps {
onActionChange: (list: RefList, action: RefAction) => void;
/** Whether the host lets the user pick the action; otherwise each list keeps its default. */
canChooseAction: boolean;
canChooseChangeRequest: boolean;
/** The source uses jj, so the branch list is its bookmarks. */
isJujutsu?: boolean;
/** Selects the forge's change-request words, such as "Merge requests" on GitLab. */
changeRequestContext: "mr" | undefined;
};
@@ -184,6 +189,12 @@ function useIsolationPicker(input: {
const { t } = useTranslation();
const { isolation, projectDirectory, isPending } = input;
const { canCreateWorktree, choice, existingWorktrees, onSelect, onOpenChange } = isolation;
const newLabel = isolation.isJujutsu
? t("newWorkspace.isolation.jujutsu")
: t("newWorkspace.isolation.worktree");
const existingLabel = isolation.isJujutsu
? t("newWorkspace.isolation.existingJujutsu")
: t("newWorkspace.isolation.existing");
const { existingWorktreePath, onChooseExistingWorktree } = isolation;
const newestWorktree = existingWorktrees[0];
// The worktree options are omitted entirely (not disabled) when they cannot apply: a project
@@ -195,10 +206,10 @@ function useIsolationPicker(input: {
description: projectDirectory ? shortenPath(projectDirectory) : undefined,
};
if (!canCreateWorktree) return [local];
const worktree = { id: "worktree", label: t("newWorkspace.isolation.worktree") };
const worktree = { id: "worktree", label: newLabel };
if (!newestWorktree) return [local, worktree];
return [local, worktree, { id: "existing", label: t("newWorkspace.isolation.existing") }];
}, [canCreateWorktree, newestWorktree, projectDirectory, t]);
return [local, worktree, { id: "existing", label: existingLabel }];
}, [canCreateWorktree, existingLabel, newLabel, newestWorktree, projectDirectory, t]);
const handleSelect = useCallback(
(id: string) => {
// The newest worktree is the likeliest one to return to, so it is the first pick.
@@ -217,8 +228,8 @@ function useIsolationPicker(input: {
);
const value = {
local: t("newWorkspace.isolation.local"),
worktree: t("newWorkspace.isolation.worktree"),
existing: t("newWorkspace.isolation.existing"),
worktree: newLabel,
existing: existingLabel,
}[choice];
const icon = { local: folderIcon, worktree: branchIcon, existing: existingWorktreeIcon }[choice];
return { value, icon, options, onSelect: handleSelect, renderOption };
@@ -289,7 +300,8 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) {
const { options: allOptions, itemById, selectedItem, selectedOptionId, worktrees } = base;
const { open: openPicker, onSelect, actionFor, onActionChange } = base;
const context = base.changeRequestContext;
const [list, setList] = useState<RefList>("branch");
const [requestedList, setList] = useState<RefList>("branch");
const list = base.canChooseChangeRequest ? requestedList : "branch";
const action = actionFor[list];
const options = useMemo(
() => refListOptions({ options: allOptions, itemById, selectedOptionId, kind: list, action }),
@@ -326,11 +338,15 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) {
action={action}
onActionChange={handleActionChange}
canChooseAction={base.canChooseAction}
canChooseChangeRequest={base.canChooseChangeRequest}
changeRequestContext={context}
/>
),
[action, base.canChooseAction, context, handleActionChange, list],
[action, base.canChooseAction, base.canChooseChangeRequest, context, handleActionChange, list],
);
const branchSearchPlaceholder = base.isJujutsu
? t("newWorkspace.refPicker.searchBookmarks")
: t("newWorkspace.refPicker.searchBranches");
const shown = itemById.get(selectedOptionId);
const shownList = refListOf(shown);
const shownAction = actionFor[shownList];
@@ -355,7 +371,7 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) {
searchPlaceholder:
list === "github-pr"
? t("newWorkspace.refPicker.searchPullRequests", { context })
: t("newWorkspace.refPicker.searchBranches"),
: branchSearchPlaceholder,
trigger: {
...trigger,
icon,
@@ -371,6 +387,25 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) {
* that does not apply to the selected project is left out. Host always shows, even with one host, so
* its Add host action keeps multi-host discoverable.
*/
/** The Existing worktree picker's text; jj projects list their workspaces. */
function useWorktreePickerText(isJujutsu?: boolean) {
const { t } = useTranslation();
if (isJujutsu) {
return {
title: t("newWorkspace.jujutsuWorkspacePicker.title"),
tooltip: t("newWorkspace.tooltips.jujutsuWorkspace"),
searchPlaceholder: t("newWorkspace.jujutsuWorkspacePicker.searchPlaceholder"),
empty: t("newWorkspace.jujutsuWorkspacePicker.empty"),
};
}
return {
title: t("newWorkspace.worktreePicker.title"),
tooltip: t("newWorkspace.tooltips.worktree"),
searchPlaceholder: t("newWorkspace.worktreePicker.searchPlaceholder"),
empty: t("newWorkspace.worktreePicker.empty"),
};
}
export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement {
const { t } = useTranslation();
const { isCompact, isPending, pluginItems, project, host, isolation, base, launch } = props;
@@ -408,6 +443,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
[host.selectedServerId],
);
const { choice } = isolation;
const worktreeText = useWorktreePickerText(isolation.isJujutsu);
const projectField = (
<FieldTrigger
@@ -438,7 +474,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
searchable={false}
title={t("newWorkspace.fields.host")}
desktopPlacement="bottom-start"
desktopMinWidth={320}
desktopMinWidth={200}
hostOptionTestID={hostOptionTestID}
>
<FieldTrigger
@@ -473,8 +509,8 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
<FieldTrigger
ref={worktreePicker.anchorRef}
variant={variant}
label={t("newWorkspace.worktreePicker.title")}
tooltip={t("newWorkspace.tooltips.worktree")}
label={worktreeText.title}
tooltip={worktreeText.tooltip}
icon={branchIcon}
value={worktreePicker.selected.name}
onPress={worktreePicker.open}
@@ -564,14 +600,14 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
value={worktreePicker.selected?.path ?? ""}
onSelect={worktreePicker.onSelect}
searchable
searchPlaceholder={t("newWorkspace.worktreePicker.searchPlaceholder")}
title={t("newWorkspace.worktreePicker.title")}
searchPlaceholder={worktreeText.searchPlaceholder}
title={worktreeText.title}
open={worktreePicker.openState}
onOpenChange={worktreePicker.onOpenChange}
desktopPlacement="bottom-start"
desktopMinWidth={360}
anchorRef={worktreePicker.anchorRef}
emptyText={t("newWorkspace.worktreePicker.empty")}
emptyText={worktreeText.empty}
renderOption={worktreePicker.renderOption}
/>
</>
@@ -21,6 +21,7 @@ export function RefPickerToolbar({
action,
onActionChange,
canChooseAction,
canChooseChangeRequest,
changeRequestContext: context,
}: {
list: RefList;
@@ -28,6 +29,7 @@ export function RefPickerToolbar({
action: RefAction;
onActionChange: (action: RefAction) => void;
canChooseAction: boolean;
canChooseChangeRequest: boolean;
changeRequestContext: "mr" | undefined;
}): ReactElement {
const { t } = useTranslation();
@@ -68,13 +70,15 @@ export function RefPickerToolbar({
);
return (
<>
<SegmentedControl
size="sm"
options={listOptions}
value={list}
onValueChange={onListChange}
testID="new-workspace-ref-picker-tabs"
/>
{canChooseChangeRequest ? (
<SegmentedControl
size="sm"
options={listOptions}
value={list}
onValueChange={onListChange}
testID="new-workspace-ref-picker-tabs"
/>
) : null}
{canChooseAction ? (
<SegmentedControl
size="sm"
+1 -1
View File
@@ -907,7 +907,7 @@ function HostPicker({
showActiveConnection
searchable={false}
title={t("settings.hostPicker.switchHost")}
desktopMinWidth={328}
desktopMinWidth={240}
addHostTestID="settings-add-host"
hostOptionTestID={hostOptionTestID}
>
@@ -4,12 +4,7 @@ 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,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } 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";
@@ -18,18 +13,12 @@ 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";
@@ -87,112 +76,10 @@ 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) }],
@@ -318,11 +205,9 @@ function BadgeDisplayMenuItem({
*/
function BadgePreview({
host,
resolvedIcon,
badgeDisplay,
}: {
host: HostProfile;
resolvedIcon: HostIcon;
badgeDisplay: HostBadgeDisplay;
}) {
const { t } = useTranslation();
@@ -334,10 +219,9 @@ 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, resolvedIcon],
[badgeDisplay, host.serverId, host.label, host.appearance.color],
);
// The real sidebar row, so the preview can't drift from what the setting actually does.
return (
@@ -360,14 +244,8 @@ function BadgePreview({
export function HostAppearanceSection({ host }: { host: HostProfile }) {
const { t } = useTranslation();
const toast = useToast();
const { setHostColor, setHostIcon, setHostBadgeDisplay } = useHostMutations();
const { setHostColor, 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,
@@ -385,16 +263,6 @@ 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 {
@@ -420,18 +288,11 @@ 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} resolvedIcon={resolvedIcon} badgeDisplay={badgeDisplay} />
<BadgePreview host={host} badgeDisplay={badgeDisplay} />
</>
)}
</View>
-9
View File
@@ -293,7 +293,6 @@ export interface DaemonServerInfo {
serverId: string;
hostname: string | null;
version: string | null;
machineKind?: string | null;
desktopManaged?: boolean;
capabilities?: ServerCapabilities;
features?: ServerInfoStatusPayload["features"];
@@ -304,7 +303,6 @@ 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 }
: {}),
@@ -788,7 +786,6 @@ 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;
@@ -798,19 +795,16 @@ 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)
@@ -948,7 +942,6 @@ 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;
@@ -958,7 +951,6 @@ export const useSessionStore = create<SessionStore>()(
currentServerInfo: session.serverInfo,
nextHostname,
nextVersion,
nextMachineKind,
nextDesktopManaged,
nextCapabilities,
nextFeatures,
@@ -978,7 +970,6 @@ export const useSessionStore = create<SessionStore>()(
serverId: info.serverId,
hostname: nextHostname,
version: nextVersion,
...(nextMachineKind !== null ? { machineKind: nextMachineKind } : {}),
...(nextDesktopManaged !== undefined
? { desktopManaged: nextDesktopManaged }
: {}),
+5 -27
View File
@@ -152,7 +152,7 @@ describe("normalizeStoredHostProfile", () => {
});
});
it("gives a host stored before appearance existed the default appearance without an icon key", () => {
it("gives a host stored before appearance existed the default appearance", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_old",
connections: [
@@ -161,35 +161,18 @@ 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", icon: "laptop", badgeDisplay: "icon" },
appearance: { color: "teal", badgeDisplay: "icon" },
connections: [
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
],
});
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",
});
expect(profile?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
});
it("normalizes stored Remote SSH connection parameters", () => {
@@ -357,13 +340,12 @@ 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", icon: "workstation", badgeDisplay: "hidden" },
appearance: { color: "amber", badgeDisplay: "hidden" },
connections: [],
};
@@ -373,11 +355,7 @@ describe("upsertHostConnectionInProfiles", () => {
connection,
});
expect(profile.appearance).toEqual({
color: "amber",
icon: "workstation",
badgeDisplay: "hidden",
});
expect(profile.appearance).toEqual({ color: "amber", badgeDisplay: "hidden" });
});
it("replaces a direct connection when its settings change", () => {
@@ -143,11 +143,3 @@ 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;
@@ -5,6 +5,7 @@ import { runArchiveCommand } from "./archive.js";
import { runCreateCommand } from "./create.js";
import { runLsCommand } from "./ls.js";
import { runRenameCommand } from "./rename.js";
import { createJujutsuCommand } from "./jujutsu.js";
import { runSetupCommand } from "./setup.js";
export function createWorkspaceCommand(): Command {
@@ -65,5 +66,6 @@ export function createWorkspaceCommand(): Command {
.argument("<workspace-id>", "Workspace id"),
).action(withOutput(runArchiveCommand));
workspace.addCommand(createJujutsuCommand());
return workspace;
}
@@ -0,0 +1,80 @@
import { Argument, Command } from "commander";
import { JujutsuCheckoutActionSchema } from "@getpaseo/protocol/messages";
import {
withOutput,
type CommandOptions,
type OutputSchema,
type SingleResult,
} from "../../output/index.js";
import { connectToDaemon } from "../../utils/client.js";
import { addJsonAndDaemonHostOptions } from "../../utils/command-options.js";
import { resolveRepositoryDirectory } from "../worktree/repository-directory.js";
interface JujutsuCommandOptions extends CommandOptions {
path?: string;
description?: string;
bookmark?: string;
remote?: string;
base?: string;
title?: string;
body?: string;
create?: boolean;
parent?: string;
}
const outputSchema: OutputSchema<{ action: string; url: string | null }> = {
idField: "action",
columns: [
{ header: "ACTION", field: "action" },
{ header: "URL", field: "url" },
],
};
export function createJujutsuCommand(): Command {
return addJsonAndDaemonHostOptions(
new Command("jj")
.description("Run a Jujutsu checkout action")
.addArgument(
new Argument("<action>").choices([
"describe",
"new",
"fetch",
"publish",
"create-pull-request",
]),
)
.option("--path <path>", "Checkout directory (default: current directory)")
.option("--description <text>", "Change description for describe or new")
.option("--parent <bookmark-or-change>", "Start new on this instead of the current change")
.option("--bookmark <name>", "Head bookmark for publish or create-pull-request")
.option("--create", "Create the bookmark at the current change before publishing")
.option("--remote <name>", "Remote for fetch or publish")
.option("--base <name>", "Base bookmark for create-pull-request")
.option("--title <text>", "Pull request title")
.option("--body <text>", "Pull request body"),
).action(withOutput(runJujutsuCommand));
}
async function runJujutsuCommand(
name: string,
options: JujutsuCommandOptions,
_command: Command,
): Promise<SingleResult<{ action: string; url: string | null }>> {
const action = JujutsuCheckoutActionSchema.parse({
...options,
kind: name === "create-pull-request" ? "create_pull_request" : name,
});
const target = options.daemonTarget;
const cwd = resolveRepositoryDirectory({ cwd: options.path, daemonTarget: target });
const client = await connectToDaemon({ target });
try {
const status = await client.getCheckoutStatus(cwd);
if (status.error) throw new Error(status.error.message);
if (!status.jujutsu) throw new Error("The selected checkout does not use Jujutsu.");
const response = await client.checkoutJujutsuAction(cwd, status.jujutsu.changeId, action);
if (response.error) throw new Error(response.error.message);
return { type: "single", data: { action: name, url: response.url }, schema: outputSchema };
} finally {
await client.close().catch(() => undefined);
}
}
+1 -14
View File
@@ -754,14 +754,13 @@ class DaemonClientSession {
private readonly daemon = new FakeDaemon();
private readonly client: DaemonClient;
constructor(options: { livenessHeartbeat?: boolean } = {}) {
constructor() {
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);
}
@@ -3396,18 +3395,6 @@ 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();
+28 -12
View File
@@ -1,3 +1,4 @@
import type { JujutsuCheckoutAction } from "@getpaseo/protocol/messages";
import {
DiffStreamRouter,
DiffSubscriptionError,
@@ -473,13 +474,6 @@ 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 {
@@ -2749,11 +2743,7 @@ export class DaemonClient {
}
private scheduleNextLivenessHeartbeat(): void {
if (
this.config.livenessHeartbeat === false ||
this.connectionState.status !== "connected" ||
this.livenessHeartbeatTimer
) {
if (this.connectionState.status !== "connected" || this.livenessHeartbeatTimer) {
return;
}
this.livenessHeartbeatTimer = setTimeout(() => {
@@ -5169,6 +5159,30 @@ export class DaemonClient {
});
}
async searchJujutsuChanges(cwd: string, query: string) {
if (!this.getLastServerInfoMessage()?.features?.jujutsuCheckoutActions) {
throw new Error("Update the host to use Jujutsu actions.");
}
return this.sendNamespacedCorrelatedSessionRequest<"checkout.jujutsu.changes.response">({
message: { type: "checkout.jujutsu.changes.request", cwd, query },
timeout: 30_000,
});
}
async checkoutJujutsuAction(
cwd: string,
expectedChangeId: string,
action: JujutsuCheckoutAction,
) {
if (!this.getLastServerInfoMessage()?.features?.jujutsuCheckoutActions) {
throw new Error("Update the host to use Jujutsu actions.");
}
return this.sendNamespacedCorrelatedSessionRequest<"checkout.jujutsu.action.response">({
message: { type: "checkout.jujutsu.action.request", cwd, expectedChangeId, action },
timeout: 180_000,
});
}
async checkoutRefresh(cwd: string, requestId?: string): Promise<CheckoutRefreshPayload> {
return this.sendCorrelatedSessionRequest({
requestId,
@@ -5221,6 +5235,7 @@ export class DaemonClient {
sha: string,
path: string,
requestId?: string,
jujutsuOperationId?: string,
): Promise<{ file: ParsedDiffFile | null }> {
const payload =
await this.sendNamespacedCorrelatedSessionRequest<"checkout.commits.file_diff.response">({
@@ -5230,6 +5245,7 @@ export class DaemonClient {
cwd,
sha,
path,
...(jujutsuOperationId ? { jujutsuOperationId } : {}),
},
timeout: 60000,
});
+132 -17
View File
@@ -2589,6 +2589,47 @@ export const CheckoutPushRequestSchema = z.object({
requestId: z.string(),
});
const JujutsuBookmarkNameSchema = z.string().trim().min(1).max(255);
export const JujutsuCheckoutActionSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("describe"), description: z.string().trim().min(1).max(65536) }),
z.object({
kind: z.literal("new"),
description: z.string().trim().min(1).max(65536).optional(),
// Start the new change on this bookmark instead of on the current change.
parent: JujutsuBookmarkNameSchema.optional(),
}),
z.object({
kind: z.literal("publish"),
bookmark: JujutsuBookmarkNameSchema,
remote: z.string().trim().min(1).max(255).optional(),
create: z.boolean().optional(),
}),
z.object({
kind: z.literal("create_pull_request"),
bookmark: JujutsuBookmarkNameSchema,
base: JujutsuBookmarkNameSchema,
title: z.string().trim().min(1).max(512),
body: z.string().max(65536).optional(),
}),
z.object({ kind: z.literal("fetch"), remote: z.string().min(1).optional() }),
]);
export type JujutsuCheckoutAction = z.infer<typeof JujutsuCheckoutActionSchema>;
export const JujutsuChangeSearchRequestSchema = z.object({
type: z.literal("checkout.jujutsu.changes.request"),
cwd: z.string(),
query: z.string().max(200),
requestId: z.string(),
});
export const JujutsuCheckoutActionRequestSchema = z.object({
type: z.literal("checkout.jujutsu.action.request"),
cwd: z.string(),
expectedChangeId: z.string().min(1),
action: JujutsuCheckoutActionSchema,
requestId: z.string(),
});
export const CheckoutRefreshRequestSchema = z.object({
type: z.literal("checkout.refresh.request"),
cwd: z.string(),
@@ -2654,6 +2695,20 @@ const CheckoutCommitSchema = z.object({
// COMPAT(commitBaseClassification): added in v0.2.0, remove optional after 2027-01-23.
isOnBase: z.boolean().optional(),
files: z.array(CheckoutCommitFileSchema),
// Jujutsu checkouts list changes; shortSha then holds the short change ID.
jujutsu: z
.object({
changeId: z.string(),
bookmarks: z.array(z.string()),
isWorkingCopy: z.boolean(),
isEmpty: z.boolean(),
hasConflicts: z.boolean(),
operationId: z
.string()
.regex(/^[a-f0-9]{12,128}$/)
.optional(),
})
.optional(),
});
export const CheckoutCommitsListRequestSchema = z.object({
@@ -2673,6 +2728,10 @@ export const CheckoutCommitFileDiffRequestSchema = z.object({
cwd: z.string(),
sha: z.string(),
path: z.string(),
jujutsuOperationId: z
.string()
.regex(/^[a-f0-9]{12,128}$/)
.optional(),
requestId: z.string(),
});
@@ -3711,6 +3770,8 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
CheckoutPullRequestSchema,
CheckoutPushRequestSchema,
CheckoutRefreshRequestSchema,
JujutsuCheckoutActionRequestSchema,
JujutsuChangeSearchRequestSchema,
CheckoutDiscardChangesRequestSchema,
CheckoutPrCreateRequestSchema,
CheckoutPrMergeRequestSchema,
@@ -3970,9 +4031,6 @@ 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.
@@ -4215,6 +4273,7 @@ export const ServerInfoStatusPayloadSchema = z
// COMPAT(checkoutDiscardChanges): added in v0.3.0, remove gate after 2027-02-08.
checkoutDiscardChanges: z.boolean().optional(),
checkoutDiffAll: z.boolean().optional(),
jujutsuCheckoutActions: z.boolean().optional(),
// COMPAT(agentProfiles): added in v0.3.2, remove gate after 2027-02-11.
// An older daemon parses its persisted config strictly, so writing
// agentProfiles to one is silently dropped. The client hides the feature
@@ -4459,6 +4518,13 @@ const WorkspaceGitRuntimePayloadSchema = z
.optional(),
aheadOfOrigin: z.number().nullable().optional(),
behindOfOrigin: z.number().nullable().optional(),
// Jujutsu checkouts have no current branch; clients label them by bookmark or change.
jujutsu: z
.object({
changeId: z.string(),
bookmarks: z.array(z.string()),
})
.optional(),
})
.optional()
.nullable();
@@ -5808,7 +5874,34 @@ const AheadBehindSchema = z.object({
behind: z.number(),
});
export const JujutsuStateSchema = z.object({
changeId: z.string(),
commitId: z.string(),
description: z.string(),
bookmarks: z.array(z.string()),
hasConflicts: z.boolean(),
// The closest local bookmark on @'s ancestry; the default base for a new workspace.
nearestBookmark: z.string().nullable().optional(),
baseBookmarkMissing: z.boolean().optional(),
hasRemotes: z.boolean().optional(),
});
const CheckoutStatusCommonSchema = z.object({
vcs: z
.object({
kind: z.enum(["git", "jujutsu", "none"]),
capabilities: z.object({
isolatedWorkspace: z.boolean(),
gitMutations: z.boolean(),
describe: z.boolean().optional(),
newChange: z.boolean().optional(),
publishBookmark: z.boolean().optional(),
createPullRequest: z.boolean().optional(),
fetch: z.boolean().optional(),
}),
})
.optional(),
jujutsu: JujutsuStateSchema.optional(),
cwd: z.string(),
error: CheckoutErrorSchema.nullable(),
requestId: z.string(),
@@ -5827,20 +5920,10 @@ 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 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.
// 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.
firstPushRemote: z.string().nullable().optional(),
forgeWeb: ForgeWebSchema.optional(),
});
@@ -6118,6 +6201,36 @@ export const CheckoutPushResponseSchema = z.object({
}),
});
export const JujutsuChangeSummarySchema = z.object({
changeId: z.string(),
commitId: z.string(),
description: z.string(),
bookmarks: z.array(z.string()),
workingCopies: z.array(z.string()),
isEmpty: z.boolean(),
authorDate: z.string(),
});
export const JujutsuChangeSearchResponseSchema = z.object({
type: z.literal("checkout.jujutsu.changes.response"),
payload: z.object({
cwd: z.string(),
changes: z.array(JujutsuChangeSummarySchema),
error: CheckoutErrorSchema.nullable(),
requestId: z.string(),
}),
});
export const JujutsuCheckoutActionResponseSchema = z.object({
type: z.literal("checkout.jujutsu.action.response"),
payload: z.object({
cwd: z.string(),
url: z.string().nullable(),
error: CheckoutErrorSchema.nullable(),
requestId: z.string(),
}),
});
export const CheckoutRefreshResponseSchema = z.object({
type: z.literal("checkout.refresh.response"),
payload: z.object({
@@ -7849,6 +7962,8 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
CheckoutPullResponseSchema,
CheckoutPushResponseSchema,
CheckoutRefreshResponseSchema,
JujutsuCheckoutActionResponseSchema,
JujutsuChangeSearchResponseSchema,
CheckoutDiscardChangesResponseSchema,
CheckoutPrCreateResponseSchema,
CheckoutPrMergeResponseSchema,
@@ -72,41 +72,6 @@ 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",
@@ -236,34 +201,6 @@ 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({
+1 -1
View File
@@ -90,7 +90,7 @@
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
"test": "npm run test:unit && npm run test:integration",
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|Jujutsu|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
"test:integration:all": "npm run test:e2e",
"test:integration:real": "vitest run real.e2e.test.ts",
@@ -74,19 +74,6 @@ 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", () => {
@@ -155,21 +142,6 @@ 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, dirname, isAbsolute, resolve } from "node:path";
import { delimiter, resolve } from "node:path";
import type { ProcessEnvRecord } from "../server/paseo-env.js";
import { execCommand } from "../utils/spawn.js";
import which from "which";
@@ -11,46 +11,11 @@ function hasPathSeparator(value: string): boolean {
return value.includes("/") || value.includes("\\");
}
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 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 [];
if (process.platform !== "win32" && existsSync("/usr/bin/which")) {
return enumerateCandidatesViaSystemWhich(name, env);
}
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))));
return enumerateCandidatesViaLibrary(name, env);
}
async function enumerateCandidatesViaSystemWhich(
@@ -1,29 +1,7 @@
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 { expect, test } from "vitest";
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 });
}
});
import type { AgentManagerEvent, AgentSubscriber } from "./agent-manager.js";
import { registerAgentAutoArchive } from "./create-agent-lifecycle-dispatch.js";
class AgentLifecycleEvents {
private readonly listeners = new Set<AgentSubscriber>();
@@ -47,109 +25,6 @@ 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();
@@ -170,41 +45,3 @@ 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,8 +29,7 @@ interface CreateAgentLifecycleDispatchDependencies {
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
assertWorkspaceAutomationAllowed: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
isCheckoutUntrusted: ArchiveDependencies["isCheckoutUntrusted"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
agentManager: AgentManager;
agentStorage: AgentStorage;
github: ForgeService;
@@ -202,7 +201,6 @@ 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,8 +2527,6 @@ describe("create_agent MCP tool", () => {
emitWorkspaceUpdatesForWorkspaceIds,
markWorkspaceArchiving,
clearWorkspaceArchiving,
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
github: createGitHubServiceStub(),
logger,
});
@@ -2645,8 +2643,6 @@ describe("create_agent MCP tool", () => {
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
github: createGitHubServiceStub(),
logger,
});
@@ -2679,117 +2675,6 @@ 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(
@@ -145,7 +145,6 @@ export interface PaseoToolHostDependencies {
findWorkspaceIdForCwd?: ArchiveDependencies["findWorkspaceIdForCwd"];
worktreeManagers?: ArchiveDependencies["worktreeManagers"];
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
assertWorkspaceAutomationAllowed?: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
listActiveWorkspaces?: ArchiveDependencies["listActiveWorkspaces"];
archiveWorkspaceRecord?: ArchiveDependencies["archiveWorkspaceRecord"];
@@ -3428,18 +3427,11 @@ 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,
@@ -59,6 +59,8 @@ const INBOUND_PERMISSION = {
"checkout.forge.set_auto_merge.request": "workspace.write",
"checkout.github.get_check_details.request": "workspace.read",
"checkout.github.set_auto_merge.request": "workspace.write",
"checkout.jujutsu.action.request": "workspace.write",
"checkout.jujutsu.changes.request": "workspace.read",
"checkout.refresh.request": "workspace.read",
"checkout.rename_branch.request": "workspace.write",
checkout_commit_request: "workspace.write",
@@ -315,6 +317,8 @@ const OUTBOUND_PERMISSION = {
"checkout.forge.set_auto_merge.response": "workspace.write",
"checkout.github.get_check_details.response": "workspace.read",
"checkout.github.set_auto_merge.response": "workspace.write",
"checkout.jujutsu.action.response": "workspace.write",
"checkout.jujutsu.changes.response": "workspace.read",
"checkout.refresh.response": "workspace.read",
"checkout.rename_branch.response": "workspace.write",
checkout_commit_response: "workspace.write",
@@ -111,8 +111,6 @@ 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 ??
@@ -330,8 +328,6 @@ function createRealOutcomeHarness(input: {
},
markWorkspaceArchiving: () => {},
clearWorkspaceArchiving: () => {},
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(),
};
@@ -632,68 +628,4 @@ 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,8 +25,7 @@ export interface AutoArchiveArchiveOptions {
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
assertWorkspaceAutomationAllowed: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
isCheckoutUntrusted: ArchiveDependencies["isCheckoutUntrusted"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
daemonConfigStore: DaemonConfigStore;
workspaceGitService: WorkspaceGitServiceImpl;
github: ForgeService;
@@ -114,7 +113,6 @@ 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) =>
+1 -26
View File
@@ -16,7 +16,6 @@ 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";
@@ -637,9 +636,6 @@ 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");
@@ -878,13 +874,11 @@ 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),
});
});
@@ -1252,8 +1246,6 @@ 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) =>
@@ -1366,8 +1358,6 @@ export async function createPaseoDaemon(
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
agentManager,
agentStorage,
@@ -1621,8 +1611,6 @@ export async function createPaseoDaemon(
workspaceGitService,
worktreeManagers: pluginRuntime,
workspaceArchiveOperations,
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
listActiveWorkspaces: listActiveWorkspacesExternal,
@@ -1815,20 +1803,7 @@ export async function createPaseoDaemon(
const start = async () => {
let mainStarted = false;
try {
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;
localCredential = await writeLocalCredential(config.paseoHome);
if (serviceProxyListenTarget) {
const boundServiceProxyTarget = await serviceProxy.startStandalone({
listenTarget: serviceProxyListenTarget,
@@ -13,6 +13,13 @@ describe("checkout status projection", () => {
const snapshot: WorkspaceGitRuntimeSnapshot = {
cwd: "/repo",
git: {
jujutsu: {
changeId: "abcdefghijkl",
commitId: "a".repeat(40),
description: "Task\n",
bookmarks: [],
hasConflicts: true,
},
isGit: true,
repoRoot: "/repo",
mainRepoRoot: null,
@@ -38,6 +45,23 @@ describe("checkout status projection", () => {
snapshot,
});
expect(payload.jujutsu).toEqual(snapshot.git.jujutsu);
expect(payload.vcs).toEqual({
kind: "jujutsu",
capabilities: {
isolatedWorkspace: true,
gitMutations: false,
describe: true,
newChange: true,
publishBookmark: true,
createPullRequest: true,
fetch: true,
},
});
expect(
CheckoutStatusResponseSchema.parse({ type: "checkout_status_response", payload }).payload
.jujutsu,
).toEqual(snapshot.git.jujutsu);
expect(payload.forgeWeb).toEqual({
host: "github.com",
referenceRepository: "main-owner/repo",
@@ -1,3 +1,4 @@
import { describeCheckoutVcs } from "../../utils/checkout-vcs.js";
import type {
CheckoutPrStatusResponse,
CheckoutStatusResponse,
@@ -15,6 +16,15 @@ type CheckoutPrStatusWireStatus = Omit<CheckoutPrStatusPayloadStatus, "forge"> &
forge?: string;
};
function checkoutVcsFromSnapshot(snapshot: WorkspaceGitRuntimeSnapshot) {
if (!snapshot.git.isGit) return describeCheckoutVcs("none");
return describeCheckoutVcs(snapshot.git.jujutsu ? "jujutsu" : "git", {
hasRemote: snapshot.git.hasRemote,
hasFetchRemote: snapshot.git.jujutsu?.hasRemotes,
hasForge: Boolean(snapshot.forge.forge ?? snapshot.forgeWeb) || snapshot.forge.featuresEnabled,
});
}
export function buildCheckoutStatusPayloadFromSnapshot({
cwd,
requestId,
@@ -24,10 +34,12 @@ export function buildCheckoutStatusPayloadFromSnapshot({
requestId: string;
snapshot: WorkspaceGitRuntimeSnapshot;
}): CheckoutStatusResponse["payload"] {
const vcs = checkoutVcsFromSnapshot(snapshot);
if (!snapshot.git.isGit) {
return {
cwd,
isGit: false,
vcs,
repoRoot: null,
currentBranch: null,
isDirty: null,
@@ -55,6 +67,8 @@ export function buildCheckoutStatusPayloadFromSnapshot({
return {
cwd,
jujutsu: snapshot.git.jujutsu,
vcs,
isGit: true,
repoRoot: snapshot.git.repoRoot,
mainRepoRoot: snapshot.git.mainRepoRoot,
@@ -69,8 +83,6 @@ 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 } : {}),
@@ -82,6 +94,8 @@ export function buildCheckoutStatusPayloadFromSnapshot({
return {
cwd,
jujutsu: snapshot.git.jujutsu,
vcs,
isGit: true,
repoRoot: snapshot.git.repoRoot,
mainRepoRoot: snapshot.git.mainRepoRoot,
@@ -96,8 +110,6 @@ 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 } : {}),
@@ -314,8 +314,6 @@ test("streams whole-file batches and answers a same-socket ping before the revis
).join("\n") + "\n";
writeFileSync(join(cwd, `${file}.ts`), content);
}
// Stage the fixture so Git reads the added files in bulk. They are still new relative to HEAD.
git(cwd, "add", ".");
expect(ctx.client.getLastServerInfoMessage()).toMatchObject({
features: { diffSubscription: true },
});
@@ -1,4 +1,4 @@
import { test, expect, beforeEach, afterEach } from "vitest";
import { test, expect, beforeEach, afterEach, vi } from "vitest";
import {
mkdtempSync,
writeFileSync,
@@ -726,3 +726,174 @@ async function waitForWorkspaceSetup(workspaceId: string, status: "completed" |
if (!snapshot) throw new Error("Expected workspace setup snapshot");
return snapshot;
}
test("runs a Jujutsu describe and new through the daemon protocol", async () => {
const directory = tmpCwd();
const repo = path.join(directory, "repo");
const configuration = path.join(directory, "jj.toml");
writeFileSync(configuration, '[user]\nname = "Paseo Test"\nemail = "test@paseo.local"\n');
vi.stubEnv("JJ_CONFIG", configuration);
vi.stubEnv("XDG_CONFIG_HOME", path.join(directory, "config"));
try {
execFileSync("jj", ["git", "init", "--colocate", repo]);
writeFileSync(path.join(repo, "task.txt"), "working copy edit\n");
const first = await ctx.client.getCheckoutStatus(repo);
const changeId = first.jujutsu?.changeId ?? "";
expect(first.vcs).toMatchObject({
kind: "jujutsu",
capabilities: { describe: true, newChange: true },
});
const described = await ctx.client.checkoutJujutsuAction(repo, changeId, {
kind: "describe",
description: "Review this task",
});
expect(described.error).toBeNull();
const created = await ctx.client.checkoutJujutsuAction(repo, changeId, {
kind: "new",
description: "Follow-up",
});
expect(created.error).toBeNull();
const stale = await ctx.client.checkoutJujutsuAction(repo, changeId, {
kind: "describe",
description: "Wrong change",
});
expect(stale.error?.message).toContain("working-copy change has moved");
expect(readFileSync(path.join(repo, "task.txt"), "utf8")).toBe("working copy edit\n");
} finally {
vi.unstubAllEnvs();
rmSync(directory, { recursive: true, force: true });
}
});
test("creates a Jujutsu workspace from the working copy when there is no default bookmark", async () => {
const directory = tmpCwd();
const repo = path.join(directory, "repo");
const config = path.join(directory, "jj.toml");
writeFileSync(config, '[user]\nname = "Paseo Test"\nemail = "test@paseo.local"\n');
vi.stubEnv("JJ_CONFIG", config);
vi.stubEnv("XDG_CONFIG_HOME", path.join(directory, "config"));
try {
execFileSync("jj", ["git", "init", "--colocate", repo]);
writeFileSync(path.join(repo, "task.txt"), "unrecorded working-copy edit\n");
const created = await ctx.client.createWorkspace({
source: { kind: "worktree", cwd: repo, action: "branch-off" },
});
if (!created.workspace) throw new Error(created.error ?? "Workspace creation failed");
const { workspaceDirectory } = created.workspace;
expect(readFileSync(path.join(workspaceDirectory, "task.txt"), "utf8")).toBe(
"unrecorded working-copy edit\n",
);
const readChangeId = (cwd: string, revision: string) =>
execFileSync(
"jj",
["--ignore-working-copy", "log", "--no-graph", "-r", revision, "-T", "change_id"],
{ cwd, encoding: "utf8" },
);
const sourceChange = readChangeId(repo, "@");
expect(readChangeId(workspaceDirectory, "@-")).toBe(sourceChange);
expect(readChangeId(workspaceDirectory, "@")).not.toBe(sourceChange);
} finally {
vi.unstubAllEnvs();
rmSync(directory, { recursive: true, force: true });
}
});
test("opens a file in the unintegrated working-copy merge shown in Jujutsu Changes", async () => {
const directory = tmpCwd();
const repo = path.join(directory, "repo");
const config = path.join(directory, "jj.toml");
writeFileSync(config, '[user]\nname = "Paseo Test"\nemail = "test@paseo.local"\n');
vi.stubEnv("JJ_CONFIG", config);
vi.stubEnv("XDG_CONFIG_HOME", path.join(directory, "config"));
try {
execFileSync("jj", ["git", "init", "--colocate", repo]);
const jj = (...args: string[]) => execFileSync("jj", args, { cwd: repo }).toString();
writeFileSync(path.join(repo, "base.txt"), "base\n");
jj("commit", "-m", "Base");
jj("bookmark", "create", "-r", "@-", "main");
writeFileSync(path.join(repo, "left.txt"), "from first parent\n");
jj("bookmark", "create", "left");
jj("new", "main");
writeFileSync(path.join(repo, "project [right].txt"), "from second parent\n");
jj("bookmark", "create", "right");
jj("new", "left", "right");
rmSync(path.join(repo, "project [right].txt"));
const { commits } = await ctx.client.listCheckoutCommits(repo);
const merge = commits.find((commit) => commit.jujutsu?.isWorkingCopy);
expect(merge?.files).toContainEqual({
path: "project [right].txt",
status: "deleted",
additions: 0,
deletions: 1,
});
if (!merge?.jujutsu?.operationId) throw new Error("Missing Jujutsu snapshot operation");
writeFileSync(path.join(repo, "project [right].txt"), "later edit\n");
const { file } = await ctx.client.getCommitFileDiff(
repo,
merge.sha,
"project [right].txt",
undefined,
merge.jujutsu.operationId,
);
expect(file).toMatchObject({ isDeleted: true, deletions: 1 });
expect(JSON.stringify(file?.hunks)).toContain("from second parent");
} finally {
vi.unstubAllEnvs();
rmSync(directory, { recursive: true, force: true });
}
});
test("archives and restores a Jujutsu worktree through the daemon", async () => {
const directory = tmpCwd();
const repo = path.join(directory, "repo");
const config = path.join(directory, "jj.toml");
writeFileSync(config, '[user]\nname = "Paseo Test"\nemail = "test@paseo.local"\n');
vi.stubEnv("JJ_CONFIG", config);
vi.stubEnv("XDG_CONFIG_HOME", path.join(directory, "config"));
try {
execFileSync("jj", ["git", "init", "--colocate", repo]);
writeFileSync(path.join(repo, ".gitignore"), "scratch.log\n");
writeFileSync(path.join(repo, "task.txt"), "base\n");
execFileSync("jj", ["commit", "-m", "Base"], { cwd: repo });
execFileSync("jj", ["bookmark", "create", "-r", "@-", "main"], { cwd: repo });
const added = await ctx.client.addProject(repo);
if (!added.project) throw new Error(added.error ?? "Project creation failed");
const created = await ctx.client.createWorkspace({
source: {
kind: "worktree",
projectId: added.project.projectId,
action: "branch-off",
baseBranch: "main",
worktreeSlug: "jj-archive",
},
});
if (!created.workspace) throw new Error(created.error ?? "Workspace creation failed");
const { id, workspaceDirectory: cwd } = created.workspace;
const original = await ctx.client.getCheckoutStatus(cwd);
expect(original.jujutsu?.changeId).toBeTruthy();
writeFileSync(path.join(cwd, "task.txt"), "working-copy edit\n");
writeFileSync(path.join(cwd, "scratch.log"), "ignored file\n");
const archived = await ctx.client.archiveWorkspace(id);
expect(archived.error).toBeNull();
expect(archived.archivedAt).toBeTruthy();
expect(existsSync(cwd)).toBe(false);
await ctx.client.restoreWorkspace(id);
const restored = await ctx.client.getCheckoutStatus(cwd);
expect(restored.jujutsu?.changeId).toBe(original.jujutsu?.changeId);
expect(readFileSync(path.join(cwd, "task.txt"), "utf8")).toBe("working-copy edit\n");
expect(existsSync(path.join(cwd, "scratch.log"))).toBe(false);
} finally {
vi.unstubAllEnvs();
rmSync(directory, { recursive: true, force: true });
}
});
@@ -1,3 +1,4 @@
import { getJujutsuOperationHeads } from "../../utils/checkout-jj.js";
import { resolve, relative } from "node:path";
import type { Logger } from "pino";
import { runGitCommand } from "../../utils/run-git-command.js";
@@ -100,6 +101,10 @@ export class DiffDependencyObserver {
),
);
}
const jujutsuHeads = await getJujutsuOperationHeads(input.cwd);
if (jujutsuHeads) {
metadata.push(await this.observeMetadata(jujutsuHeads, null, () => changed("endpoints")));
}
const workingTree = await this.workspaceGit.requestWorkingTreeWatch(input.cwd, () =>
changed(input.worktree ? "endpoints" : "interpretation"),
);
+10
View File
@@ -1,3 +1,5 @@
import { resolveCheckoutProvider } from "../../utils/checkout-vcs.js";
import { listJujutsuComparison } from "./jj.js";
import { parseGitRevParsePath } from "../../utils/git-rev-parse-path.js";
import { readGitInputs } from "./inputs.js";
import { Patches } from "./patches.js";
@@ -158,6 +160,14 @@ export async function listComparison(
compare: Compare,
revisions?: ComparisonRevisions,
): Promise<Comparison> {
if (compare.head.kind === "worktree" || compare.checkoutBase) {
const provider = await resolveCheckoutProvider(compare.cwd);
if (provider.kind === "jujutsu") {
validateCompare(compare);
return listJujutsuComparison({ ...compare, cwd: provider.root });
}
}
if (compare.checkoutBase) {
if (revisions) revisions.checkoutBase = null;
const selected = await resolveCheckoutDiffBase(compare.cwd, compare.checkoutBase.compare, {
+6 -1
View File
@@ -2,6 +2,8 @@ import type { Logger } from "pino";
import { TOTAL_DIFF_MAX_BYTES } from "../../utils/checkout-git.js";
import { DEFAULT_MAX_OUTPUT_BYTES, runGitCommand } from "../../utils/run-git-command.js";
import { expandTilde, createRealpathAwarePathMatcher } from "../../utils/path.js";
import { findJujutsuRoot } from "../../utils/checkout-jj.js";
import { readJujutsuCommitFile } from "./jj.js";
import { packBodies } from "./batches.js";
import { setImmediate } from "node:timers/promises";
import {
@@ -64,7 +66,7 @@ interface Target {
}
export interface CommitFileRead extends Pick<
CheckoutCommitFileDiffRequest,
"cwd" | "sha" | "path"
"cwd" | "sha" | "path" | "jujutsuOperationId"
> {
signal?: AbortSignal;
}
@@ -96,6 +98,9 @@ export class DiffSubscriptions {
}
async readCommitFile(input: CommitFileRead): Promise<ParsedDiffFile | null> {
input.signal?.throwIfAborted();
const jujutsuRoot = await findJujutsuRoot(expandTilde(input.cwd));
if (jujutsuRoot) return readJujutsuCommitFile({ ...input, cwd: jujutsuRoot });
const cwd = await worktreeRoot(expandTilde(input.cwd));
const result = await runGitCommand(
["rev-list", "--parents", "--max-count=1", "--end-of-options", input.sha],
+108
View File
@@ -0,0 +1,108 @@
import { materializeDiffFile, type DiffEntry } from "@getpaseo/protocol/binary-frames/index";
import { createHash } from "node:crypto";
import type { Comparison, Compare, ListedFile } from "./git.js";
import { getCheckoutDiff, PER_FILE_DIFF_MAX_BYTES } from "../../utils/checkout-git.js";
import {
getJujutsuDiff,
getJujutsuState,
parseJujutsuDiff,
runJujutsu,
} from "../../utils/checkout-jj.js";
export async function listJujutsuComparison(compare: Compare): Promise<Comparison> {
if (compare.base.kind === "index") {
throw new Error("Jujutsu does not use Git's staging area. Compare the current change instead.");
}
const state = await getJujutsuState(compare.cwd);
let baseRef: string | undefined;
if (compare.base.kind === "empty") baseRef = "root()";
else if (compare.base.kind === "rev" && compare.base.rev !== "HEAD") baseRef = compare.base.rev;
let diff: string;
if (compare.checkoutBase) {
const result = await getCheckoutDiff(compare.cwd, {
...compare.checkoutBase.compare,
includeStructured: false,
});
if (result.diffTooLarge) throw new Error("Jujutsu diff exceeds the supported size");
diff = result.diff;
} else {
diff = await getJujutsuDiff(compare.cwd, {
baseRef,
ignoreWhitespace: compare.ignoreWhitespace,
});
}
const parsed = new Map(parseJujutsuDiff(diff).map((file) => [file.path, file]));
const files: ListedFile[] = [...parsed.values()].map((file) => ({
entry: jujutsuDiffEntry(file),
identity: createHash("sha256").update(JSON.stringify(file)).digest("hex"),
source: { kind: "tracked" },
}));
files.sort((a, b) => a.entry.path.localeCompare(b.entry.path));
return {
baseSha: "",
headSha: state.commitId,
mergeBaseSha: "",
files,
metrics: { highlightCalls: 0 },
close: async () => {},
selectBodies: () => {},
hasInterpretationChanged: async () => false,
async read(file, budget = {}) {
const contents = parsed.get(file.entry.path);
if (!contents) throw new Error(`Missing Jujutsu diff for ${file.entry.path}`);
const body = { path: file.entry.path, hunks: contents.hunks };
const bytes = Buffer.byteLength(JSON.stringify(body));
if (
bytes > (budget.maxPatchBytes ?? PER_FILE_DIFF_MAX_BYTES) ||
bytes > (budget.remainingBytes ?? Infinity)
) {
return { kind: "too_large" };
}
return { kind: "ready", body, bytes };
},
};
}
type JujutsuDiffFile = ReturnType<typeof parseJujutsuDiff>[number];
function jujutsuDiffEntry(file: JujutsuDiffFile): DiffEntry {
let change: DiffEntry["change"] = "modified";
if (file.isNew) change = "added";
else if (file.isDeleted) change = "deleted";
else if (file.oldPath) change = "renamed";
const binary = file.status === "binary";
return {
path: file.path,
oldPath: file.oldPath,
change,
content: binary ? "binary" : "text",
additions: file.additions,
deletions: file.deletions,
body: !binary,
};
}
export async function readJujutsuCommitFile(input: {
cwd: string;
sha: string;
path: string;
jujutsuOperationId?: string;
signal?: AbortSignal;
}) {
const { cwd, sha, path, jujutsuOperationId, signal } = input;
if (!/^[a-f0-9]{40}$/.test(sha)) throw new Error(`Invalid Jujutsu commit ID: ${sha}`);
const diff = await runJujutsu(
cwd,
["diff", "--git", "-r", sha, "--", `root-file:${JSON.stringify(path)}`],
{ atOperation: jujutsuOperationId, signal },
);
signal?.throwIfAborted();
const file = parseJujutsuDiff(diff).find((candidate) => candidate.path === path);
if (!file || file.status === "binary") return null;
const tooLarge = Buffer.byteLength(diff) > PER_FILE_DIFF_MAX_BYTES;
const body = tooLarge ? null : { path, hunks: file.hunks };
return materializeDiffFile(jujutsuDiffEntry(file), body, tooLarge);
}
@@ -1,94 +0,0 @@
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();
});
});
@@ -1,251 +0,0 @@
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;
}
@@ -1,3 +1,4 @@
import { findJujutsuRoot } from "../utils/checkout-jj.js";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
@@ -191,6 +192,10 @@ export async function attemptFirstAgentBranchAutoName(options: {
renameCurrentBranch?: typeof renameCurrentBranch;
localBranchExists?: typeof localBranchExists;
}): Promise<AttemptFirstAgentBranchAutoNameResult> {
if (await findJujutsuRoot(options.cwd)) {
return { attempted: false, renamed: false, branchName: null };
}
const firstAgentContext = options.firstAgentContext;
if (!firstAgentContext || !buildAgentBranchNameSeed(firstAgentContext)) {
return { attempted: false, renamed: false, branchName: null };
@@ -282,6 +287,8 @@ async function maybeMarkFirstAgentBranchAutoNameEligible(options: {
createdWorktree: Awaited<ReturnType<typeof createWorktreeCore>>;
input: Pick<CreatePaseoWorktreeInput, "branchName">;
}): Promise<void> {
if (await findJujutsuRoot(options.createdWorktree.worktree.worktreePath)) return;
const { createdWorktree, input } = options;
if (!createdWorktree.created || createdWorktree.intent.kind !== "branch-off") {
return;
@@ -466,9 +466,6 @@ 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();
@@ -916,7 +913,6 @@ 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) {
@@ -930,17 +926,9 @@ 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, onTestFinished, vi } from "vitest";
import { afterEach, describe, expect, it, 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,40 +1982,6 @@ 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",
@@ -4,7 +4,7 @@ import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
export type WorktreeCreationIntent = Exclude<
WorktreeSource,
{ kind: "restore" | "restore-from-base" | "restore-commit" }
{ kind: "restore" | "restore-from-base" | "restore-commit" | "restore-jujutsu" }
> & { untrustedSource?: UntrustedWorkspaceSource };
export function worktreeUntrustedSource(
@@ -171,8 +171,6 @@ function createScheduleService(options: TestScheduleServiceOptions): ScheduleSer
markWorkspaceArchiving: () => {},
clearWorkspaceArchiving: () => {},
killTerminalsForWorkspace: async () => {},
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: options.logger,
},
{
@@ -278,8 +276,6 @@ async function createRegistryBackedScheduleWorkspaceDeps(rootDir: string): Promi
markWorkspaceArchiving: () => {},
clearWorkspaceArchiving: () => {},
killTerminalsForWorkspace: async () => {},
assertWorkspaceAutomationAllowed: async () => {},
isCheckoutUntrusted: async () => false,
sessionLogger: logger,
},
{
+16 -19
View File
@@ -1301,8 +1301,6 @@ 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,
@@ -3436,6 +3434,10 @@ export class Session {
return this.checkoutSession.handleCheckoutPullRequest(msg);
case "checkout_push_request":
return this.checkoutSession.handleCheckoutPushRequest(msg);
case "checkout.jujutsu.action.request":
return this.checkoutSession.handleJujutsuActionRequest(msg);
case "checkout.jujutsu.changes.request":
return this.checkoutSession.handleJujutsuChangesRequest(msg);
case "checkout.refresh.request":
return this.checkoutSession.handleRefreshRequest(msg);
case "checkout.discard_changes.request":
@@ -5852,8 +5854,6 @@ 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,
@@ -6312,6 +6312,14 @@ export class Session {
aheadBehind: snapshot.git.aheadBehind,
aheadOfOrigin: snapshot.git.aheadOfOrigin,
behindOfOrigin: snapshot.git.behindOfOrigin,
...(snapshot.git.jujutsu
? {
jujutsu: {
changeId: snapshot.git.jujutsu.changeId,
bookmarks: snapshot.git.jujutsu.bookmarks,
},
}
: {}),
};
}
@@ -6561,19 +6569,16 @@ export class Session {
};
}
private async withWorkspaceCheckout<T>(
workspaceId: string,
run: (checkoutPath: string | null) => Promise<T>,
): Promise<T> {
private async withWorkspaceCheckout<T>(workspaceId: string, run: () => Promise<T>): Promise<T> {
const workspace = await this.workspaceRegistry.get(workspaceId);
if (!workspace) {
return run(null);
return run();
}
const checkoutPath = await resolveWorkspaceBackingPath(workspace, {
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
});
return this.workspaceArchiveOperations.withCheckout(checkoutPath, () => run(checkoutPath));
return this.workspaceArchiveOperations.withCheckout(checkoutPath, run);
}
private async withCheckoutForDirectory<T>(cwd: string, run: () => Promise<T>): Promise<T> {
@@ -8216,15 +8221,7 @@ export class Session {
{
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
clearAutomationBlock: (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,
});
}),
clearWorkspaceAutomationBlock(this.workspaceRegistry, workspaceId),
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" },
pushTarget: null,
firstPushRemote: null,
pullRequestLookupTarget: { headRef: "feature" },
};
const githubStub = {
@@ -1,3 +1,9 @@
import { runJujutsuCheckoutAction } from "../../../utils/jujutsu-actions.js";
import {
assertGitMutationAllowed,
findJujutsuRoot,
searchJujutsuChanges,
} from "../../../utils/checkout-jj.js";
import type pino from "pino";
import type { SessionDelivery } from "../owned-subscriptions/index.js";
import { isAbsolute } from "node:path";
@@ -313,7 +319,7 @@ export class CheckoutSession {
msg: CheckoutCommitFileDiffRequest,
signal: AbortSignal,
): Promise<void> {
const { cwd, sha, path, requestId } = msg;
const { cwd, sha, path, requestId, jujutsuOperationId } = msg;
try {
assertSafeGitRef(sha, "commit");
@@ -324,6 +330,7 @@ export class CheckoutSession {
cwd: expandTilde(cwd),
sha,
path,
...(jujutsuOperationId ? { jujutsuOperationId } : {}),
signal,
});
this.host.emit({
@@ -507,6 +514,52 @@ export class CheckoutSession {
await ownership.release(msg.subscriptionId);
}
async handleJujutsuActionRequest(
msg: Extract<SessionInboundMessage, { type: "checkout.jujutsu.action.request" }>,
): Promise<void> {
const { cwd, requestId, expectedChangeId, action } = msg;
try {
const resolvedCwd = expandTilde(cwd);
const url = await runJujutsuCheckoutAction({
cwd: resolvedCwd,
expectedChangeId,
action,
resolveForge: async () => (await this.requireForgeService(resolvedCwd)).service,
});
this.workspaceGitService.onWorkspaceStateMayHaveChanged(resolvedCwd);
await this.scheduleDiffRefresh(resolvedCwd);
this.host.emit({
type: "checkout.jujutsu.action.response",
payload: { cwd, requestId, url, error: null },
});
} catch (error) {
this.host.emit({
type: "checkout.jujutsu.action.response",
payload: { cwd, requestId, url: null, error: toCheckoutError(error) },
});
}
}
async handleJujutsuChangesRequest(
msg: Extract<SessionInboundMessage, { type: "checkout.jujutsu.changes.request" }>,
): Promise<void> {
const { cwd, requestId, query } = msg;
try {
const root = await findJujutsuRoot(expandTilde(cwd));
if (!root) throw new Error("This checkout does not use Jujutsu.");
const changes = await searchJujutsuChanges(root, query);
this.host.emit({
type: "checkout.jujutsu.changes.response",
payload: { cwd, requestId, changes, error: null },
});
} catch (error) {
this.host.emit({
type: "checkout.jujutsu.changes.response",
payload: { cwd, requestId, changes: [], error: toCheckoutError(error) },
});
}
}
async handleRefreshRequest(msg: CheckoutRefreshRequest): Promise<void> {
const { cwd, requestId } = msg;
const resolvedCwd = expandTilde(cwd);
@@ -703,6 +756,7 @@ export class CheckoutSession {
): Promise<void> {
const { cwd, requestId } = msg;
try {
await assertGitMutationAllowed(cwd);
const branchLabel = msg.branch?.trim() ?? "";
const message = branchLabel
? `${CheckoutSession.PASEO_STASH_PREFIX} ${branchLabel}`
@@ -730,6 +784,7 @@ export class CheckoutSession {
): Promise<void> {
const { cwd, stashIndex, requestId } = msg;
try {
await assertGitMutationAllowed(cwd);
await runGitCommand(["stash", "pop", `stash@{${stashIndex}}`], {
cwd,
timeout: 120_000,
@@ -1,3 +1,4 @@
import { assertGitMutationAllowed } from "../../../utils/checkout-jj.js";
import type pino from "pino";
import { getErrorMessage } from "@getpaseo/protocol/error-utils";
import {
@@ -64,6 +65,7 @@ export function createGitMutationService(deps: {
}
async function ensureCleanWorkingTree(cwd: string): Promise<void> {
await assertGitMutationAllowed(cwd);
const dirty = await isWorkingTreeDirty(cwd);
if (dirty) {
throw new Error(
@@ -76,6 +76,7 @@ export function createWorkspaceBaseBranchService(deps: Dependencies) {
await setPaseoWorktreeBaseRef({
worktreeRoot: root,
baseRef: metadata.baseRef ?? metadata.baseRefName,
jujutsuBaseCommit: metadata.jujutsuBaseCommit,
});
for (const record of matching) {
await deps.workspaceRegistry.update(record.workspaceId, (latest) => ({
@@ -1,9 +1,8 @@
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, describe, expect, test } from "vitest";
import { afterEach, beforeEach, expect, test } from "vitest";
import { getCheckoutStatus } from "../../../utils/checkout-git.js";
import {
@@ -1169,149 +1168,3 @@ 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();
});
});
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff. Show more