Author SHA1 Message Date
jackos1998andClaude Opus 5.5 d871d1a678 vcs/jujutsu: Report and update stale workspaces
A workspace goes stale when another one rewrites or abandons its @,
for example when a fetch abandons a merged commit. jj then refuses to
snapshot it, so the daemon's diffs failed.

Fall back to the repository's view of @ for snapshot reads, report
the stale state in the checkout status, and add an update-stale
action to the app and CLI. The update moves files under any agent
working there, so it only runs on request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:33:36 +00:00
jackos1998andClaude Opus 5.5 c8c883629c agent/compaction: Log skipped idle compactions at info
A skipped compaction was only logged at debug, so the daemon's info
log gave no hint why an idle agent wasn't compacted. Each agent is
judged once per idle period, so log skips at info, with the context
size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:33:27 +00:00
jackos1998andClaude Opus 5.5 caecb4e135 agent/compaction: Compact idle agents before the cache expires
An idle agent's next prompt resends its whole context uncached once
the provider's prompt cache expires. Compact large idle contexts
shortly before that, following Claude Code's own idle compaction:
at 90% of a one-hour cache lifetime, from 200,000 tokens of context,
and not when the sweep is more than a minute late.

Providers opt in by reporting their cache through
`getPromptCacheState()`. Claude reads the lifetime from each
request's `cache_creation` usage. The daemon runs `/compact` as its
own turn without recording a prompt, and restores the agent's
attention afterwards so it neither notifies nor changes unread
state. `agents.idleCompaction` in `config.json` turns it off or sets
the context threshold.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:49:57 +00:00
jackos1998andClaude Opus 5.5 21ebbce024 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-26 10:49:57 +00:00
jackos1998andClaude Opus 5.5 fe372a6abc 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-26 10:49:57 +00:00
jackos1998andClaude Opus 5.5 c801a40a05 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-26 10:49:57 +00:00
jackos1998andClaude Opus 5.5 2c927fe02d 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-26 10:49:57 +00:00
jackos1998andClaude Opus 5.5 643ca85844 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-26 10:49:57 +00:00
paseo-ai[bot] 55bafb24c5 fix: update lockfile signatures and Nix hash [skip ci]
(cherry picked from commit 17c08edccfb043a706e8b8e0b05c62f998e44504)
2026-11-26 10:49:57 +00:00
89 changed files with 5790 additions and 212 deletions

No files matched your search

@@ -0,0 +1,7 @@
{
"files": 252,
"coldMs": 2076.0937139999996,
"oneFileRefreshMs": 345.29472799999985,
"changedBodies": 1,
"highlightCalls": 1
}
+19
View File
@@ -241,6 +241,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' }}
@@ -286,6 +303,7 @@ jobs:
- *server_capacity
- *server_checkout
- *server_node
- *server_jj
- *server_fetch
- *server_install
- *server_agent_clis
@@ -309,6 +327,7 @@ jobs:
- *server_capacity
- *server_checkout
- *server_node
- *server_jj
- *server_fetch
- *server_install
- *server_agent_clis
+8
View File
@@ -53,6 +53,14 @@ host config to disable automatic collection. The host setting applies immediatel
apply on reload. Disabling invalidates pending safety checks and close admission. A close already
started finishes. Re-enabling keeps the existing idle timestamps.
Idle compaction runs `/compact` on an idle agent shortly before its provider's prompt cache
expires (`packages/server/src/server/agent/idle-compaction/`). Providers opt in with
`getPromptCacheState()`, which reports the time of the latest request and the cache lifetime;
Claude reads the lifetime from each request's `cache_creation` usage. The same daemon baseline as
collection must allow it, and agents with a pending wakeup or message delivery are skipped. The
compaction turn records no prompt and restores the attention the agent had before it. See
`agents.idleCompaction` in [configuration](../public-docs/configuration.md#idle-compaction).
Foreground runs, permissions and responses, queued deliveries, lifecycle operations, and working
managed or native descendants prevent collection. Outstanding local or remote finish subscriptions
also protect their caller, including registration, recovery and notification dispatch acknowledgment.
+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.
+167
View File
@@ -0,0 +1,167 @@
# 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`. |
| **Update stale workspace** | Appears when another workspace has rewritten this one's `@`, and runs `jj workspace update-stale`. See [stale workspaces](#stale-workspaces). |
| **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.
### Stale workspaces
A workspace goes stale when another workspace rewrites or abandons its `@`. A
common cause is a `jj git fetch` after a pull request is merged: the fetch
abandons the merged commit, and jj gives each workspace whose `@` it was a new
`@`. The files on disk still match the old one.
- **Reads:** a stale working copy can't be snapshotted. Diffs and the Changes
list fall back to the repository's view of `@`, and the checkout status
reports `jujutsu.stale`.
- **Update:** the "Update stale workspace" action (`paseo workspace jj
update-stale`) runs `jj workspace update-stale`. It moves the files on disk to
the new `@`. Edits jj hadn't snapshotted yet are kept in a separate change.
- **Not automatic:** the update rewrites files under any agent working there, so
it only runs when someone asks for it.
### 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. A last, independent commit adds idle compaction before
the prompt cache expires; see
[configuration](../public-docs/configuration.md#idle-compaction). 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 -1
View File
@@ -1 +1 @@
sha256-6XXAVBTH6rIdg5eQ9cUeUwV22ikVqTtdWo7i9DYO+/M=
sha256-B2hX/4xDGTtFC2LBRL/0US3YERfM/cDXvu8cjztpsd8=
+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 />
@@ -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,
+249
View File
@@ -0,0 +1,249 @@
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],
);
// Updating a stale workspace moves its change by design.
const stale = kind !== "update_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 === "update_stale" ? (
<Text style={styles.explanation}>
{t("workspace.git.jujutsu.updateStaleExplanation")}
</Text>
) : null}
{kind === "describe" || kind === "new" ? (
<FormTextInput
multiline
editable={!pending}
initialValue={description}
onChangeText={setDescription}
accessibilityLabel={t("workspace.git.jujutsu.description")}
placeholder={t("workspace.git.jujutsu.description")}
/>
) : null}
{kind === "publish" || kind === "create_pull_request" ? (
<FormTextInput
editable={!pending}
initialValue={bookmark}
onChangeText={setBookmark}
autoCapitalize="none"
accessibilityLabel={t("workspace.git.jujutsu.bookmark")}
placeholder={t("workspace.git.jujutsu.bookmark")}
/>
) : null}
{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 "update_stale":
return { 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 },
explanation: { color: theme.colors.foregroundMuted },
}));
@@ -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);
}
+78
View File
@@ -170,6 +170,12 @@ function createInput(
status: "idle",
handler: () => undefined,
},
"jj-update-stale": { disabled: false, 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,
};
@@ -1566,3 +1572,75 @@ describe("git-actions-policy", () => {
]);
});
});
describe("Jujutsu checkout actions", () => {
const allAvailable = {
"jj-update-stale": false,
"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",
]);
});
it("leads with updating a stale workspace", () => {
const actions = buildGitActions(
createInput({
isJujutsu: true,
jujutsu: {
hasDescription: false,
available: { ...allAvailable, "jj-update-stale": true },
},
}),
);
expect(actions.primary?.id).toBe("jj-update-stale");
expect(actions.secondary[0]?.id).toBe("jj-describe");
});
});
+79 -1
View File
@@ -25,7 +25,30 @@ export type GitActionId =
| "disable-pr-auto-merge"
| "merge-branch"
| "merge-from-base"
| "archive-workspace";
| "archive-workspace"
| JujutsuActionId;
export type JujutsuActionId =
| "jj-update-stale"
| "jj-describe"
| "jj-new"
| "jj-fetch"
| "jj-publish"
| "jj-pr";
export const JUJUTSU_ACTION_IDS: readonly JujutsuActionId[] = [
"jj-update-stale",
"jj-describe",
"jj-new",
"jj-fetch",
"jj-publish",
"jj-pr",
];
export interface JujutsuActionsInput {
hasDescription: boolean;
available: Record<JujutsuActionId, boolean>;
}
export interface GitAction {
id: GitActionId;
@@ -132,6 +155,9 @@ export function readSyncRemotes(
export interface BuildGitActionsInput extends SyncRemotes {
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;
@@ -375,6 +401,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;
@@ -927,3 +957,51 @@ function isPullRequestMergeMethodAllowed(
}
return capability.allowedMethods.includes(method);
}
const JUJUTSU_ACTION_LABEL_KEYS: Record<JujutsuActionId, string> = {
"jj-update-stale": "updateStale",
"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: updating a stale workspace
// first, then describe 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 (available.includes("jj-update-stale")) primaryId = "jj-update-stale";
else 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}
+137 -2
View File
@@ -21,8 +21,11 @@ import {
type GitAction,
type GitActions,
type GitUpstreamState,
type JujutsuActionsInput,
type SyncRemotes,
} 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";
@@ -167,6 +170,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,7 +185,8 @@ 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 {
@@ -254,10 +262,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 +372,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 +675,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,
@@ -696,6 +723,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,
@@ -813,9 +842,13 @@ export function useGitActions({ serverId, cwd, icons }: UseGitActionsInput): Use
icon: icons.archive,
handler: handleArchiveWorkspace,
},
...jujutsuRuntime,
},
};
}, [
status,
jujutsuInput,
jujutsuRuntime,
isGit,
hasPullRemote,
hasPushRemote,
@@ -935,6 +968,101 @@ function translateGitAction(
};
}
// Jujutsu: update-stale, 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-update-stale": jujutsuChange.stale ?? false,
"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: "update_stale" | "describe" | "new" | "publish" | "create_pull_request",
label: string,
) => ({
disabled,
status: "idle" as const,
handler: () => openJujutsuSheet({ serverId, cwd, kind, label }),
});
return {
"jj-update-stale": sheet("update_stale", t("workspace.git.jujutsu.updateStale")),
"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 +1174,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"),
+47
View File
@@ -506,6 +506,7 @@ export const ar: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "نسخ الإشارة أو معرّف التغيير",
scriptsAccessibility: "البرامج النصية Workspace",
copyPath: "نسخ المسار",
copyBranchName: "نسخ اسم الفرع",
@@ -838,6 +839,41 @@ 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: "تعارضات",
updateStale: "تحديث مساحة العمل القديمة",
updateStaleExplanation:
"أعادت مساحة عمل أخرى كتابة التغيير الحالي لهذه المساحة. يؤدي التحديث إلى مطابقة الملفات هنا مع التغيير الجديد. تُحفظ التعديلات التي لم يسجلها jj بعد في تغيير منفصل. إذا كان وكيل يعمل هنا، فانتظر حتى يصبح خاملًا.",
},
actions: {
moreOptions: "المزيد من الخيارات",
moreActions: "المزيد من الإجراءات",
@@ -1005,6 +1041,7 @@ export const ar: TranslationResources = {
refreshing: "منعش",
refresh: "ينعش",
refreshState: "تحديث حالة git و{{brand}}",
refreshJujutsuState: "تحديث حالة jj و{{brand}}",
failedRefresh: "فشل تحديث حالة git.",
seeUncommittedChanges: "عرض التغييرات غير الملتزم بها",
seeCommittedChanges: "عرض التغييرات الملتزم بها",
@@ -1410,12 +1447,15 @@ export const ar: TranslationResources = {
},
},
newWorkspace: {
defaultBase: "الفرع الافتراضي",
title: "مساحة عمل جديدة",
create: "يخلق",
isolation: {
jujutsu: "مساحة عمل jj جديدة",
local: "مجلد المشروع",
worktree: "شجرة عمل جديدة",
existing: "شجرة عمل موجودة",
existingJujutsu: "مساحة عمل jj موجودة",
label: "العزل",
},
fields: {
@@ -1441,9 +1481,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: "جارٍ البحث...",
@@ -1474,6 +1516,11 @@ export const ar: TranslationResources = {
searchPlaceholder: "ابحث في أشجار العمل",
empty: "لا توجد أشجار عمل مطابقة.",
},
jujutsuWorkspacePicker: {
title: "مساحة العمل",
searchPlaceholder: "البحث في مساحات عمل jj",
empty: "لا توجد مساحات عمل jj مطابقة.",
},
launch: {
title: "What to launch",
chat: "Chat",
+47
View File
@@ -505,6 +505,7 @@ export const en = {
},
},
hoverCard: {
copyChangeName: "Copy bookmark or change ID",
scriptsAccessibility: "Workspace scripts",
copyPath: "Copy path",
copyBranchName: "Copy branch name",
@@ -835,6 +836,41 @@ 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",
updateStale: "Update stale workspace",
updateStaleExplanation:
"Another workspace rewrote this workspace's current change. Updating moves the files here to match the new change. Edits jj hadn't recorded yet are kept in a separate change. If an agent is working here, wait until it is idle.",
},
actions: {
moreOptions: "More options",
moreActions: "More actions",
@@ -1016,6 +1052,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",
@@ -1421,12 +1458,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: {
@@ -1452,9 +1492,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...",
@@ -1485,6 +1527,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",
+48
View File
@@ -512,6 +512,7 @@ export const es: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "Copiar marcador o ID de cambio",
scriptsAccessibility: "GuionesWorkspace",
copyPath: "Copiar ruta",
copyBranchName: "Copiar nombre de rama",
@@ -846,6 +847,42 @@ 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",
updateStale: "Actualizar el espacio de trabajo obsoleto",
updateStaleExplanation:
"Otro espacio de trabajo reescribió el cambio actual de este. Al actualizar, los archivos de aquí pasan a coincidir con el nuevo cambio. Las ediciones que jj aún no había registrado se conservan en un cambio aparte. Si un agente está trabajando aquí, espera a que esté inactivo.",
},
actions: {
moreOptions: "Más opciones",
moreActions: "Más acciones",
@@ -1039,6 +1076,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",
@@ -1447,12 +1485,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: {
@@ -1478,9 +1519,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...",
@@ -1511,6 +1554,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",
+48
View File
@@ -511,6 +511,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",
@@ -847,6 +848,42 @@ 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",
updateStale: "Mettre à jour l'espace de travail obsolète",
updateStaleExplanation:
"Un autre espace de travail a réécrit le changement courant de celui-ci. La mise à jour aligne les fichiers d'ici sur le nouveau changement. Les modifications que jj n'avait pas encore enregistrées sont conservées dans un changement séparé. Si un agent travaille ici, attendez qu'il soit inactif.",
},
actions: {
moreOptions: "Plus d’options",
moreActions: "Plus d’actions",
@@ -1031,6 +1068,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",
@@ -1440,12 +1478,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: {
@@ -1471,9 +1512,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…",
@@ -1504,6 +1547,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",
+47
View File
@@ -512,6 +512,7 @@ export const ja: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "ブックマークまたは変更 ID をコピー",
scriptsAccessibility: "ワークスペーススクリプト",
copyPath: "パスをコピー",
copyBranchName: "ブランチ名をコピー",
@@ -842,6 +843,41 @@ 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: "競合",
updateStale: "古くなったワークスペースを更新",
updateStaleExplanation:
"別のワークスペースがこのワークスペースの現在の変更を書き換えました。更新すると、ここにあるファイルが新しい変更に合わせて変わります。jj がまだ記録していなかった編集は別の変更に保存されます。エージェントが作業中の場合は、アイドルになるまで待ってください。",
},
actions: {
moreOptions: "その他のオプション",
moreActions: "その他のアクション",
@@ -1019,6 +1055,7 @@ export const ja: TranslationResources = {
refreshing: "更新中",
refresh: "更新",
refreshState: "gitと{{brand}}の状態を更新",
refreshJujutsuState: "jjと{{brand}}の状態を更新",
failedRefresh: "gitの状態の更新に失敗しました。",
seeUncommittedChanges: "未コミットの変更を表示",
seeCommittedChanges: "コミット済みの変更を表示",
@@ -1425,12 +1462,15 @@ export const ja: TranslationResources = {
},
},
newWorkspace: {
defaultBase: "デフォルトブランチ",
title: "新しいワークスペース",
create: "作成",
isolation: {
jujutsu: "新しい jj ワークスペース",
local: "プロジェクトディレクトリ",
worktree: "新しいワークツリー",
existing: "既存のワークツリー",
existingJujutsu: "既存の jj ワークスペース",
label: "分離方法",
},
fields: {
@@ -1456,9 +1496,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: "検索中...",
@@ -1489,6 +1531,11 @@ export const ja: TranslationResources = {
searchPlaceholder: "ワークツリーを検索",
empty: "一致するワークツリーがありません。",
},
jujutsuWorkspacePicker: {
title: "ワークスペース",
searchPlaceholder: "jj ワークスペースを検索",
empty: "一致する jj ワークスペースはありません。",
},
launch: {
title: "What to launch",
chat: "Chat",
+47
View File
@@ -507,6 +507,7 @@ export const ko: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "북마크 또는 변경 ID 복사",
scriptsAccessibility: "워크스페이스 스크립트",
copyPath: "경로 복사",
copyBranchName: "브랜치 이름 복사",
@@ -838,6 +839,41 @@ 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: "충돌",
updateStale: "오래된 작업 공간 업데이트",
updateStaleExplanation:
"다른 작업 공간이 이 작업 공간의 현재 변경을 다시 작성했습니다. 업데이트하면 이곳의 파일이 새 변경에 맞게 바뀝니다. jj가 아직 기록하지 않은 편집은 별도의 변경에 보관됩니다. 에이전트가 작업 중이면 유휴 상태가 될 때까지 기다리세요.",
},
actions: {
moreOptions: "옵션 더 보기",
moreActions: "작업 더 보기",
@@ -1012,6 +1048,7 @@ export const ko: TranslationResources = {
refreshing: "새로고침 중",
refresh: "새로고침",
refreshState: "Git 및 {{brand}} 상태 새로고침",
refreshJujutsuState: "jj 및 {{brand}} 상태 새로고침",
failedRefresh: "Git 상태를 새로고침하지 못했습니다.",
seeUncommittedChanges: "커밋되지 않은 변경 사항 보기",
seeCommittedChanges: "커밋된 변경 사항 보기",
@@ -1417,12 +1454,15 @@ export const ko: TranslationResources = {
},
},
newWorkspace: {
defaultBase: "기본 브랜치",
title: "새 워크스페이스",
create: "생성",
isolation: {
jujutsu: "새 jj 작업 공간",
local: "프로젝트 디렉터리",
worktree: "새 워크트리",
existing: "기존 워크트리",
existingJujutsu: "기존 jj 작업 공간",
label: "격리",
},
fields: {
@@ -1448,9 +1488,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: "검색 중...",
@@ -1481,6 +1523,11 @@ export const ko: TranslationResources = {
searchPlaceholder: "워크트리 검색",
empty: "일치하는 워크트리가 없습니다.",
},
jujutsuWorkspacePicker: {
title: "작업 공간",
searchPlaceholder: "jj 작업 공간 검색",
empty: "일치하는 jj 작업 공간이 없습니다.",
},
launch: {
title: "What to launch",
chat: "Chat",
+48
View File
@@ -511,6 +511,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",
@@ -842,6 +843,42 @@ 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",
updateStale: "Atualizar o espaço de trabalho desatualizado",
updateStaleExplanation:
"Outro espaço de trabalho reescreveu a alteração atual deste. Atualizar faz os arquivos daqui corresponderem à nova alteração. As edições que o jj ainda não tinha registrado são mantidas em uma alteração separada. Se um agente estiver trabalhando aqui, espere até que fique ocioso.",
},
actions: {
moreOptions: "Mais opções",
moreActions: "Mais ações",
@@ -1029,6 +1066,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",
@@ -1437,12 +1475,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: {
@@ -1468,9 +1509,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...",
@@ -1501,6 +1544,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",
+47
View File
@@ -512,6 +512,7 @@ export const ru: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "Копировать закладку или ID изменения",
scriptsAccessibility: "Скрипты рабочего пространства",
copyPath: "Копировать путь",
copyBranchName: "Копировать имя ветки",
@@ -847,6 +848,41 @@ 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: "Конфликты",
updateStale: "Обновить устаревшее рабочее пространство",
updateStaleExplanation:
"Другое рабочее пространство переписало текущее изменение этого. Обновление приведёт файлы здесь в соответствие с новым изменением. Правки, которые jj ещё не записал, сохраняются в отдельном изменении. Если здесь работает агент, дождитесь, пока он освободится.",
},
actions: {
moreOptions: "Дополнительные параметры",
moreActions: "Дополнительные действия",
@@ -1024,6 +1060,7 @@ export const ru: TranslationResources = {
refreshing: "Обновление",
refresh: "Обновить",
refreshState: "Обновить состояние Git и {{brand}}",
refreshJujutsuState: "Обновить состояние jj и {{brand}}",
failedRefresh: "Не удалось обновить состояние Git.",
seeUncommittedChanges: "Показать незафиксированные изменения",
seeCommittedChanges: "Показать зафиксированные изменения",
@@ -1430,12 +1467,15 @@ export const ru: TranslationResources = {
},
},
newWorkspace: {
defaultBase: "Ветка по умолчанию",
title: "Новое рабочее пространство",
create: "Создать",
isolation: {
jujutsu: "Новое рабочее пространство jj",
local: "Папка проекта",
worktree: "Новый worktree",
existing: "Существующий worktree",
existingJujutsu: "Существующее рабочее пространство jj",
label: "Изоляция",
},
fields: {
@@ -1461,9 +1501,11 @@ export const ru: TranslationResources = {
isolation: "Выберите уровень изоляции",
startingRef: "Выберите, с чего начать",
worktree: "Выберите worktree для работы",
jujutsuWorkspace: "Выберите рабочее пространство jj",
launch: "Выберите, что запустить",
},
refPicker: {
searchBookmarks: "Поиск закладок",
startingRef: "Исходная точка",
intoBase: "в ветку {{baseRef}}",
searching: "Идет поиск...",
@@ -1494,6 +1536,11 @@ export const ru: TranslationResources = {
searchPlaceholder: "Поиск worktree",
empty: "Нет подходящих worktree.",
},
jujutsuWorkspacePicker: {
title: "Рабочее пространство",
searchPlaceholder: "Поиск рабочих пространств jj",
empty: "Нет подходящих рабочих пространств jj.",
},
launch: {
title: "Что запустить",
chat: "Чат",
+47
View File
@@ -506,6 +506,7 @@ export const zhCN: TranslationResources = {
},
},
hoverCard: {
copyChangeName: "复制书签或更改 ID",
scriptsAccessibility: "Workspace scripts",
copyPath: "复制路径",
copyBranchName: "复制分支名称",
@@ -834,6 +835,41 @@ 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: "冲突",
updateStale: "更新过时的工作区",
updateStaleExplanation:
"另一个工作区重写了此工作区的当前变更。更新会让这里的文件与新变更一致。jj 尚未记录的编辑会保留在单独的变更中。如果有代理正在这里工作,请等它空闲后再更新。",
},
actions: {
moreOptions: "更多选项",
moreActions: "更多操作",
@@ -997,6 +1033,7 @@ export const zhCN: TranslationResources = {
refreshing: "正在刷新",
refresh: "刷新",
refreshState: "刷新 git 和 {{brand}} 状态",
refreshJujutsuState: "刷新 jj 和 {{brand}} 状态",
failedRefresh: "刷新 git 状态失败。",
seeUncommittedChanges: "查看未 commit 的变更",
seeCommittedChanges: "查看已 commit 的变更",
@@ -1399,12 +1436,15 @@ export const zhCN: TranslationResources = {
},
},
newWorkspace: {
defaultBase: "默认分支",
title: "新建 workspace",
create: "创建",
isolation: {
jujutsu: "新的 jj 工作区",
local: "项目目录",
worktree: "新建 worktree",
existing: "已有 worktree",
existingJujutsu: "已有 jj 工作区",
label: "隔离",
},
fields: {
@@ -1430,9 +1470,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: "正在搜索...",
@@ -1463,6 +1505,11 @@ export const zhCN: TranslationResources = {
searchPlaceholder: "搜索 worktree",
empty: "没有匹配的 worktree。",
},
jujutsuWorkspacePicker: {
title: "工作区",
searchPlaceholder: "搜索 jj 工作区",
empty: "没有匹配的 jj 工作区。",
},
launch: {
title: "What to launch",
chat: "Chat",
@@ -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;
@@ -1626,6 +1632,7 @@ export function NewWorkspaceScreen({
onOpenChange: handleIsolationPickerOpenChange,
choice,
canCreateWorktree,
isJujutsu,
onSelect: setIsolation,
existingWorktrees,
existingWorktreePath,
@@ -1650,6 +1657,8 @@ export function NewWorkspaceScreen({
actionFor: refActionFor,
onActionChange: setup.chooseRefAction,
canChooseAction: supportsRefActions,
canChooseChangeRequest: allowsGitRefActions,
isJujutsu,
changeRequestContext,
},
launch: {
@@ -1748,11 +1757,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"];
@@ -1763,6 +1802,8 @@ function usePluginSetup(input: {
project,
worktrees,
supportsMultiplicity,
supportsRefActions,
isolatedWorkspaceSupported,
pendingAction,
isDraftHandoffActive,
updatePreferences,
@@ -1771,7 +1812,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;
@@ -1780,7 +1822,6 @@ function usePluginSetup(input: {
() => (projectId && projectName ? { id: projectId, name: projectName } : null),
[projectId, projectName],
);
const supportsRefActions = useHostFeature(serverId, "worktreeRefActions");
const inputs: SetupInputs = {
serverId,
locked,
@@ -94,6 +94,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[];
@@ -117,6 +119,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;
};
@@ -189,6 +194,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
@@ -200,10 +211,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.
@@ -222,8 +233,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 };
@@ -294,7 +305,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 }),
@@ -331,11 +343,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];
@@ -360,7 +376,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,
@@ -376,6 +392,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 {
@@ -423,6 +458,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
[host.selectedServerId],
);
const { choice } = isolation;
const worktreeText = useWorktreePickerText(isolation.isJujutsu);
const projectField = (
<FieldTrigger
@@ -489,8 +525,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}
@@ -583,15 +619,15 @@ 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}
restoreFocusRef={restoreFocusRef}
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"
@@ -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,81 @@
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",
"update-stale",
]),
)
.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.replaceAll("-", "_"),
});
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);
}
}
+27
View File
@@ -1,3 +1,4 @@
import type { JujutsuCheckoutAction } from "@getpaseo/protocol/messages";
import {
DiffStreamRouter,
DiffSubscriptionError,
@@ -5174,6 +5175,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,
@@ -5226,6 +5251,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">({
@@ -5235,6 +5261,7 @@ export class DaemonClient {
cwd,
sha,
path,
...(jujutsuOperationId ? { jujutsuOperationId } : {}),
},
timeout: 60000,
});
+131
View File
@@ -2598,6 +2598,48 @@ 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() }),
z.object({ kind: z.literal("update_stale") }),
]);
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(),
@@ -2663,6 +2705,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({
@@ -2682,6 +2738,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(),
});
@@ -3721,6 +3781,8 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
CheckoutPullRequestSchema,
CheckoutPushRequestSchema,
CheckoutRefreshRequestSchema,
JujutsuCheckoutActionRequestSchema,
JujutsuChangeSearchRequestSchema,
CheckoutDiscardChangesRequestSchema,
CheckoutPrCreateRequestSchema,
CheckoutPrMergeRequestSchema,
@@ -4226,6 +4288,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
@@ -4470,6 +4533,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();
@@ -5847,7 +5917,36 @@ 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(),
// Another workspace rewrote @; the files on disk still match the old change.
stale: 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(),
@@ -6157,6 +6256,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({
@@ -7889,6 +8018,8 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
CheckoutPullResponseSchema,
CheckoutPushResponseSchema,
CheckoutRefreshResponseSchema,
JujutsuCheckoutActionResponseSchema,
JujutsuChangeSearchResponseSchema,
CheckoutDiscardChangesResponseSchema,
CheckoutPrCreateResponseSchema,
CheckoutPrMergeResponseSchema,
+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/agent-configuration.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 src/server/plugins/agent-tools.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|changes the launch wrap\"",
"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/agent-configuration.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 src/server/plugins/agent-tools.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|changes the launch wrap\"",
"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",
@@ -16501,3 +16501,101 @@ test("a wrapped refresh passes a Windows script provider command to the wrapper
expect(manager.getAgent(created.id)?.lifecycle).not.toBe("error");
await manager.closeAgent(created.id);
});
class PromptCacheTestSession extends TestAgentSession {
readonly prompts: AgentPromptInput[] = [];
getPromptCacheState() {
return { lastRequestAt: 1_000, ttlMs: 60 * 60 * 1000 };
}
async startTurn(prompt?: AgentPromptInput): Promise<{ turnId: string }> {
if (prompt !== undefined) this.prompts.push(prompt);
return super.startTurn();
}
}
class PromptCacheTestClient extends TestAgentClient {
readonly sessions: PromptCacheTestSession[] = [];
async createSession(config: AgentSessionConfig): Promise<AgentSession> {
const session = new PromptCacheTestSession(config);
this.sessions.push(session);
return session;
}
}
test.each([
["unread", true],
["read", false],
])(
"an idle compaction sends /compact without a prompt and keeps the agent %s",
async (_case, unread) => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-idle-compaction-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const client = new PromptCacheTestClient();
const attentionReasons: string[] = [];
const manager = new AgentManager({
clients: { codex: client },
registry: storage,
logger,
onAgentAttention: ({ reason }) => attentionReasons.push(reason),
});
try {
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
await manager.runAgent(agent.id, "hello");
if (!unread) await manager.clearAgentAttention(agent.id);
const attentionBefore = manager.getAgent(agent.id)?.attention;
expect(attentionBefore?.requiresAttention).toBe(unread);
const [candidate] = manager.getIdleCompactionCandidates();
expect(candidate).toMatchObject({
agentId: agent.id,
cache: { lastRequestAt: 1_000, ttlMs: 60 * 60 * 1000 },
});
const idle = waitForAgentLifecycle(manager, agent.id, "idle");
await expect(candidate?.compact()).resolves.toBe(true);
await idle;
expect(client.sessions[0]?.prompts).toEqual(["hello", "/compact"]);
expect(manager.getAgent(agent.id)?.attention).toEqual(attentionBefore);
expect(attentionReasons).toEqual(["finished"]);
const timeline = manager.getTimeline(agent.id);
expect(timeline.filter((item) => item.type === "user_message")).toEqual([]);
expect(timeline).toContainEqual({
type: "notification",
level: "info",
message: "Compacting while idle, before the prompt cache expires",
});
} finally {
await storage.flush();
rmSync(workdir, { recursive: true, force: true });
}
},
);
test("a running agent is not an idle compaction candidate", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-idle-compaction-busy-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({
clients: { codex: new PromptCacheTestClient() },
registry: storage,
logger,
});
try {
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
workspaceId: undefined,
});
expect(manager.getIdleCompactionCandidates()).toHaveLength(1);
const run = manager.runAgent(agent.id, "hello");
expect(manager.getIdleCompactionCandidates()).toEqual([]);
await run;
expect(manager.getIdleCompactionCandidates()).toHaveLength(1);
} finally {
await storage.flush();
rmSync(workdir, { recursive: true, force: true });
}
});
@@ -6,6 +6,7 @@ import type {
import { LaunchWrapUnsupportedError, ProviderOptionsValidationError } from "./provider-options.js";
import type { AgentToolResult } from "@getpaseo/plugin/server";
import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js";
import type { IdleCompactionCandidate } from "./idle-compaction/index.js";
import { AgentNotFoundError, ensureAgentLoaded } from "./agent-loading.js";
import { AgentTurnChangedError } from "./agent-prompt.js";
import {
@@ -956,6 +957,8 @@ export class AgentManager {
{ readonly openedAt: number }
>();
private readonly collectingRuntimes = new Set<string>();
/** Agents running a daemon-started compaction, with the attention they had before it. */
private readonly idleCompactions = new Map<string, AttentionState>();
private readonly lifecycleMutationTails = new Map<string, Promise<void>>();
private readonly pendingCancellations = new Map<string, Promise<unknown>>();
private readonly agentStreamCoalescer: AgentStreamCoalescer;
@@ -2365,6 +2368,63 @@ export class AgentManager {
return candidates;
}
/** Idle agents whose provider reports a prompt cache and can compact before it expires. */
getIdleCompactionCandidates(): IdleCompactionCandidate[] {
const candidates: IdleCompactionCandidate[] = [];
for (const agent of this.agents.values()) {
if (!this.canStartIdleCompaction(agent)) continue;
const cache = agent.session.getPromptCacheState?.();
if (!cache) continue;
candidates.push({
agentId: agent.id,
provider: agent.provider,
cache,
contextTokens: agent.lastUsage?.contextWindowUsedTokens,
compact: async () => this.startIdleCompaction(agent),
});
}
return candidates;
}
private canStartIdleCompaction(agent: LiveManagedAgent): boolean {
return (
this.agents.get(agent.id) === agent &&
!this.historySessions.has(agent.session) &&
!this.collectingRuntimes.has(agent.id) &&
!agent.session.hasPendingWakeup?.() &&
this.runtimeHasNoPendingWork(agent)
);
}
// Runs `/compact` as a turn of its own. No prompt is recorded, and the agent keeps the
// attention it had, so a finished compaction neither notifies nor marks the agent unread.
private async startIdleCompaction(agent: LiveManagedAgent): Promise<boolean> {
if (!this.canStartIdleCompaction(agent)) return false;
const attention = agent.attention;
const events = this.streamAgent(agent.id, "/compact");
this.idleCompactions.set(agent.id, attention);
void (async () => {
try {
for await (const _event of events) {
// The manager records and broadcasts the turn's events itself.
}
} catch (error) {
this.logger.warn({ err: error, agentId: agent.id }, "idle_compaction_turn_failed");
} finally {
this.idleCompactions.delete(agent.id);
}
})();
await this.appendTimelineItem(agent.id, {
type: "notification",
level: "info",
message: "Compacting while idle, before the prompt cache expires",
});
return true;
}
private runtimeHasNoPendingWork(agent: LiveManagedAgent): boolean {
return (
agent.lifecycle === "idle" &&
@@ -6081,7 +6141,11 @@ export class AgentManager {
)
return;
this.touchUpdatedAt(agent);
if (item.type === "user_message") agent.lastUserMessageAt = new Date();
if (item.type === "user_message") {
agent.lastUserMessageAt = new Date();
// A prompt sent during an idle compaction continues that turn, so its result notifies.
this.idleCompactions.delete(agent.id);
}
this.recordAndDispatchTimelineItem(agent.id, item, agent.provider, options?.turnId, options);
}
@@ -6232,11 +6296,18 @@ export class AgentManager {
}
if (previousStatus !== "error" && currentStatus === "error") {
this.idleCompactions.delete(agent.id);
this.raiseErrorAttention(agent);
return;
}
const finished = previousStatus === "running" && currentStatus === "idle";
const idleCompactionAttention = this.idleCompactions.get(agent.id);
if (finished && idleCompactionAttention) {
this.idleCompactions.delete(agent.id);
agent.attention = idleCompactionAttention;
return;
}
if (agent.attention.requiresAttention) {
// The unread finish stays the same; the notifier knows whether the user was told about it.
if (finished && agent.attention.attentionReason === "finished") {
@@ -229,6 +229,14 @@ export interface SteerActiveTurnOptions extends AgentSteerOptions {
expectedTurnId: string;
}
/** The provider's prompt cache for the main conversation, as of its latest model request. */
export interface AgentPromptCacheState {
/** When the latest request was sent (epoch milliseconds). Each request renews the cache. */
lastRequestAt: number;
/** How long the cache lives after a request. */
ttlMs: number;
}
export interface AgentUsage {
inputTokens?: number;
cachedInputTokens?: number;
@@ -779,6 +787,12 @@ export interface AgentSession {
* background task that reports back when it ends. Recurring triggers do not count.
*/
hasPendingWakeup?(): boolean;
/**
* The prompt cache of the main conversation, or null while it is unknown. Sessions that
* implement this compact their context when sent `/compact` as a prompt, which lets the daemon
* compact an idle session before its cache expires.
*/
getPromptCacheState?(): AgentPromptCacheState | null;
/** Release live runtime resources without archiving or deleting the durable native session. */
close(): Promise<void>;
listCommands?(): Promise<AgentSlashCommand[]>;
@@ -0,0 +1,107 @@
import { expect, onTestFinished, test } from "vitest";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import {
createIdleCompaction,
resolveIdleCompactionConfig,
type IdleCompactionCandidate,
} from "./index.js";
const HOUR = 60 * 60 * 1000;
const FIRE_AT = 0.9 * HOUR;
class Agent {
lastRequestAt = 0;
ttlMs = HOUR;
contextTokens: number | undefined = 250_000;
idle = true;
compactions = 0;
candidate(): IdleCompactionCandidate {
return {
agentId: "agent",
provider: "claude",
cache: { lastRequestAt: this.lastRequestAt, ttlMs: this.ttlMs },
contextTokens: this.contextTokens,
compact: async () => {
this.compactions++;
return true;
},
};
}
}
function scenario(enabled = true) {
const agent = new Agent();
let time = 0;
const compaction = createIdleCompaction({
enabled,
minContextTokens: 200_000,
candidates: () => (agent.idle ? [agent.candidate()] : []),
logger: createTestLogger(),
now: () => time,
schedule: () => () => {},
});
onTestFinished(() => compaction.close());
return {
agent,
sweepAt: (at: number) => {
time = at;
return compaction.sweep();
},
};
}
test("compacts once at 90% of a one-hour cache lifetime", async () => {
const s = scenario();
expect(await s.sweepAt(FIRE_AT - 1)).toEqual([]);
expect(await s.sweepAt(FIRE_AT)).toEqual(["agent"]);
expect(await s.sweepAt(FIRE_AT + 15_000)).toEqual([]);
expect(s.agent.compactions).toBe(1);
});
test("a newer request moves the compaction", async () => {
const s = scenario();
s.agent.lastRequestAt = 10 * 60 * 1000;
expect(await s.sweepAt(FIRE_AT)).toEqual([]);
expect(await s.sweepAt(s.agent.lastRequestAt + FIRE_AT)).toEqual(["agent"]);
});
test.each([
["the cache lives five minutes", (agent: Agent) => (agent.ttlMs = 5 * 60 * 1000)],
["the context is small", (agent: Agent) => (agent.contextTokens = 199_999)],
["the context size is unknown", (agent: Agent) => (agent.contextTokens = undefined)],
])("leaves the agent alone when %s", async (_case, change) => {
const s = scenario();
change(s.agent);
expect(await s.sweepAt(HOUR - 1)).toEqual([]);
expect(s.agent.compactions).toBe(0);
});
test("a sweep more than a minute late leaves the cache to expire", async () => {
const s = scenario();
expect(await s.sweepAt(FIRE_AT + 60_001)).toEqual([]);
expect(await s.sweepAt(FIRE_AT + 60_002)).toEqual([]);
expect(s.agent.compactions).toBe(0);
});
test("an agent that is busy at the fire time is judged again when it is idle", async () => {
const s = scenario();
s.agent.idle = false;
expect(await s.sweepAt(FIRE_AT)).toEqual([]);
s.agent.idle = true;
expect(await s.sweepAt(FIRE_AT + 15_000)).toEqual(["agent"]);
});
test("does nothing when disabled", async () => {
const s = scenario(false);
expect(await s.sweepAt(FIRE_AT)).toEqual([]);
expect(s.agent.compactions).toBe(0);
});
test.each([
[undefined, { enabled: true, minContextTokens: 200_000 }],
[false, { enabled: false, minContextTokens: 200_000 }],
[{ minContextTokens: 100_000 }, { enabled: true, minContextTokens: 100_000 }],
])("resolves the config.json setting %j", (persisted, expected) => {
expect(resolveIdleCompactionConfig(persisted)).toEqual(expected);
});
@@ -0,0 +1,140 @@
import type { Logger } from "pino";
import type { AgentPromptCacheState } from "../agent-sdk-types.js";
/** An idle agent whose provider reports its prompt cache. */
export interface IdleCompactionCandidate {
readonly agentId: string;
readonly provider: string;
readonly cache: AgentPromptCacheState;
readonly contextTokens: number | undefined;
/** Starts `/compact` if the agent is still idle. Resolves false when it did not start. */
compact(): Promise<boolean>;
}
export interface IdleCompactionConfig {
enabled: boolean;
/** Smaller contexts are cheap to send again uncached, so they are left alone. */
minContextTokens: number;
}
// The rules follow Claude Code's own idle compaction: only a one-hour cache is worth keeping,
// compaction starts at 90% of its lifetime, and a sweep that runs too late leaves it, since the
// cache may already be gone and compacting would then resend the whole context uncached.
export const IDLE_COMPACTION_DEFAULT_MIN_CONTEXT_TOKENS = 200_000;
const MIN_CACHE_TTL_MS = 60 * 60 * 1000;
const FIRE_AT_FRACTION = 0.9;
const MAX_LATE_MS = 60_000;
const SWEEP_INTERVAL_MS = 15_000;
/** `agents.idleCompaction` in `config.json`: a switch, or the settings themselves. */
export function resolveIdleCompactionConfig(
persisted: boolean | { enabled?: boolean; minContextTokens?: number } | undefined,
): IdleCompactionConfig {
const settings = typeof persisted === "boolean" ? { enabled: persisted } : (persisted ?? {});
return {
enabled: settings.enabled ?? true,
minContextTokens: settings.minContextTokens ?? IDLE_COMPACTION_DEFAULT_MIN_CONTEXT_TOKENS,
};
}
interface Options extends IdleCompactionConfig {
candidates(): readonly IdleCompactionCandidate[];
logger: Pick<Logger, "debug" | "info" | "warn">;
now?: () => number;
schedule?: (tick: () => void, intervalMs: number) => () => void;
}
function scheduleInterval(tick: () => void, intervalMs: number): () => void {
const timer = setInterval(tick, intervalMs);
timer.unref?.();
return () => clearInterval(timer);
}
function skipReason(
candidate: IdleCompactionCandidate,
lateMs: number,
minContextTokens: number,
): string | null {
if (candidate.cache.ttlMs < MIN_CACHE_TTL_MS) return "short_ttl";
if (lateMs > MAX_LATE_MS) return "lapsed";
if ((candidate.contextTokens ?? 0) < minContextTokens) return "small";
return null;
}
/** Compacts idle agents shortly before their prompt cache expires. */
export function createIdleCompaction(options: Options) {
const now = options.now ?? Date.now;
const logger = options.logger;
// The request each agent's cache was last judged for, so an idle period compacts at most once.
const judged = new Map<string, number>();
let sweeping: Promise<string[]> | null = null;
async function sweepOnce(): Promise<string[]> {
const candidates = options.candidates();
const present = new Set(candidates.map((candidate) => candidate.agentId));
for (const agentId of judged.keys()) {
if (!present.has(agentId)) judged.delete(agentId);
}
const compacted: string[] = [];
for (const candidate of candidates) {
const { agentId, cache } = candidate;
if (judged.get(agentId) === cache.lastRequestAt) continue;
const fireAt = cache.lastRequestAt + cache.ttlMs * FIRE_AT_FRACTION;
const current = now();
if (cache.ttlMs >= MIN_CACHE_TTL_MS && current < fireAt) continue;
judged.set(agentId, cache.lastRequestAt);
const skip = skipReason(candidate, current - fireAt, options.minContextTokens);
if (skip) {
logger.info(
{
agentId,
provider: candidate.provider,
reason: skip,
contextTokens: candidate.contextTokens,
},
"idle_compaction_skipped",
);
continue;
}
try {
if (await candidate.compact()) {
compacted.push(agentId);
logger.info(
{ agentId, provider: candidate.provider, contextTokens: candidate.contextTokens },
"idle_compaction_started",
);
}
} catch (error) {
logger.warn(
{ err: error, agentId, provider: candidate.provider },
"idle_compaction_failed",
);
}
}
return compacted;
}
function sweep(): Promise<string[]> {
if (!options.enabled) return Promise.resolve([]);
sweeping ??= sweepOnce().finally(() => {
sweeping = null;
});
return sweeping;
}
const stop = options.enabled
? (options.schedule ?? scheduleInterval)(() => void sweep(), SWEEP_INTERVAL_MS)
: () => {};
return {
sweep,
async close(): Promise<void> {
stop();
await sweeping;
},
};
}
@@ -496,6 +496,7 @@ export function wrapSessionProvider(provider: AgentProvider, inner: AgentSession
close: () => inner.close(),
canStopRuntime: inner.canStopRuntime?.bind(inner),
hasPendingWakeup: inner.hasPendingWakeup?.bind(inner),
getPromptCacheState: inner.getPromptCacheState?.bind(inner),
listCommands: inner.listCommands?.bind(inner),
setModel: inner.setModel?.bind(inner),
setThinkingOption: inner.setThinkingOption?.bind(inner),
@@ -4063,6 +4063,52 @@ describe("ClaudeAgentSession context window usage", () => {
}
});
test.each([
[
"a one-hour write",
{ ephemeral_1h_input_tokens: 20, ephemeral_5m_input_tokens: 0 },
3_600_000,
],
[
"a five-minute write",
{ ephemeral_1h_input_tokens: 0, ephemeral_5m_input_tokens: 20 },
300_000,
],
])(
"message_start records the prompt cache lifetime of %s",
async (_case, cacheCreation, ttlMs) => {
const usage = {
input_tokens: 100,
cache_creation_input_tokens: 20,
cache_read_input_tokens: 30,
cache_creation: cacheCreation,
};
const readOnly = { ...usage, cache_creation_input_tokens: 0, cache_creation: {} };
const session = await createSessionForTurns([
[createInitMessage(), createMessageStartEvent(usage), createSuccessResult()],
[createInitMessage(), createMessageStartEvent(readOnly), createSuccessResult()],
]);
try {
expect(session.getPromptCacheState?.()).toBeNull();
const before = Date.now();
await collectStreamEvents(session);
expect(session.getPromptCacheState?.()).toEqual({
lastRequestAt: expect.any(Number),
ttlMs,
});
const first = session.getPromptCacheState?.()?.lastRequestAt ?? 0;
expect(first).toBeGreaterThanOrEqual(before);
await collectStreamEvents(session);
expect(session.getPromptCacheState?.()?.ttlMs).toBe(ttlMs);
expect(session.getPromptCacheState?.()?.lastRequestAt).toBeGreaterThanOrEqual(first);
} finally {
await session.close();
}
},
);
test("selected Claude models seed active context window usage with max tokens", async () => {
const session = await createSessionForTurns(
[[createInitMessage(), createMessageStartEvent(), createSuccessResult()]],
@@ -151,6 +151,7 @@ import {
type SteerResult,
type AgentStreamEvent,
type AgentTimelineItem,
type AgentPromptCacheState,
type AgentUsage,
type AgentRuntimeInfo,
type AgentClientInstallation,
@@ -2208,6 +2209,28 @@ function readStreamRequestInputUsage(
};
}
const PROMPT_CACHE_TTL_1H_MS = 60 * 60 * 1000;
const PROMPT_CACHE_TTL_5M_MS = 5 * 60 * 1000;
/**
* The cache lifetime a request wrote, from `message_start.usage.cache_creation`. A request that
* only read the cache writes nothing and keeps the lifetime of the prefix it read.
*/
function readPromptCacheWriteTtlMs(event: Record<string, unknown>): number | undefined {
const usage = toObjectRecord(toObjectRecord(event.message)?.usage);
const cacheCreation = usage ? toObjectRecord(usage.cache_creation) : undefined;
if (!cacheCreation) {
return undefined;
}
if ((readUsageCount(cacheCreation, "ephemeral_1h_input_tokens") ?? 0) > 0) {
return PROMPT_CACHE_TTL_1H_MS;
}
if ((readUsageCount(cacheCreation, "ephemeral_5m_input_tokens") ?? 0) > 0) {
return PROMPT_CACHE_TTL_5M_MS;
}
return undefined;
}
/**
* The input counters on `message_delta.usage` are cumulative whole-request totals and are
* optional. Mirror the Anthropic SDK's MessageStream: a counter present on the delta replaces
@@ -2567,6 +2590,7 @@ class ClaudeAgentSession implements AgentSession {
private readonly resultMeter = new ClaudeResultMeter();
private compacting = false;
private compactionMarkerOpen = false;
private promptCache: AgentPromptCacheState | null = null;
private queryPumpPromise: Promise<void> | null = null;
private queryRestartNeeded = false;
/** True from the moment a query's launch options are copied until the query exists. */
@@ -3329,6 +3353,20 @@ class ClaudeAgentSession implements AgentSession {
return this.persistence;
}
getPromptCacheState(): AgentPromptCacheState | null {
return this.promptCache;
}
// Main-thread stream events arrive only live, so `message_start` marks when a request was sent.
private observePromptCacheRequest(event: unknown): void {
const streamEvent = toObjectRecord(event);
if (!streamEvent || readTrimmedString(streamEvent.type) !== "message_start") {
return;
}
const ttlMs = readPromptCacheWriteTtlMs(streamEvent) ?? this.promptCache?.ttlMs;
this.promptCache = ttlMs === undefined ? null : { lastRequestAt: Date.now(), ttlMs };
}
hasPendingWakeup(): boolean {
// A delivered task notification opens its turn only with the next init.
return this.notificationTurnId !== null || this.runtimeSafety.hasPendingWakeup();
@@ -5399,6 +5437,7 @@ class ClaudeAgentSession implements AgentSession {
events: AgentStreamEvent[],
options: { suppressAssistantText?: boolean; suppressReasoning?: boolean } | undefined,
): Promise<void> {
this.observePromptCacheRequest(message.event);
const usageUpdatedEvent = this.contextUsage.buildStreamUsageEvent(message.event);
if (usageUpdatedEvent) {
events.push(usageUpdatedEvent);
@@ -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",
@@ -316,6 +318,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",
+17
View File
@@ -3,6 +3,11 @@ import { createRestartRecovery } from "./agent/restart-recovery/index.js";
import { sendPromptToAgent, unarchiveAgentState } from "./agent/agent-prompt.js";
import { createChangeRequestWatches } from "./agent/change-request-watches/index.js";
import { createIdleRuntimeCleanup } from "./agent/idle-runtime-cleanup/index.js";
import {
createIdleCompaction,
resolveIdleCompactionConfig,
type IdleCompactionConfig,
} from "./agent/idle-compaction/index.js";
import {
createFinishSubscriptions,
createFinishObservation,
@@ -429,6 +434,7 @@ export interface PaseoDaemonConfig {
downloadTokenTtlMs?: number;
agentProviderSettings?: AgentProviderRuntimeSettingsMap;
idleRuntimeCleanup?: boolean;
idleCompaction?: IdleCompactionConfig;
resumeOnStartup?: boolean;
resumePrompt?: string;
providerCatalogRefreshTimeoutMs?: number;
@@ -1566,6 +1572,16 @@ export async function createPaseoDaemon(
idleRuntimeCleanup,
);
const idleCompaction = createIdleCompaction({
...(config.idleCompaction ?? resolveIdleCompactionConfig(undefined)),
// A message about to be delivered starts a turn of its own.
candidates: () =>
agentManager
.getIdleCompactionCandidates()
.filter((candidate) => !(wsServer?.agentMessages.hasPending(candidate.agentId) ?? false)),
logger,
});
const createAgentToolHostDependencies = (
runtime: PaseoToolRuntimeContext,
): PaseoToolHostDependencies => ({
@@ -2048,6 +2064,7 @@ export async function createPaseoDaemon(
scriptHealthMonitor.stop();
unsubscribeIdleRuntimeCleanup();
await idleRuntimeCleanup.close();
await idleCompaction.close();
// Freeze both ingress and registration before taking the agent closure snapshot.
wsServer?.prepareForShutdown();
await changeRequestWatches.close();
@@ -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,
@@ -82,6 +96,8 @@ export function buildCheckoutStatusPayloadFromSnapshot({
return {
cwd,
jujutsu: snapshot.git.jujutsu,
vcs,
isGit: true,
repoRoot: snapshot.git.repoRoot,
mainRepoRoot: snapshot.git.mainRepoRoot,
+7
View File
@@ -13,6 +13,7 @@ import {
LogLevelSchema,
type PersistedConfig,
} from "./persisted-config.js";
import { resolveIdleCompactionConfig } from "./agent/idle-compaction/index.js";
import type { AgentProvider } from "./agent/agent-sdk-types.js";
import type {
AgentProviderRuntimeSettingsMap,
@@ -597,6 +598,7 @@ export type ResolvedDaemonSettings = Pick<
| "relayRequireProtectedSecurity"
| "appBaseUrl"
| "idleRuntimeCleanup"
| "idleCompaction"
| "resumeOnStartup"
| "resumePrompt"
| "providerCatalogRefreshTimeoutMs"
@@ -686,6 +688,7 @@ export function resolveReloadableConfig(
relayEnabled: relay.enabled,
relayRequireProtectedSecurity: relay.requireProtectedSecurity,
idleRuntimeCleanup: persisted.agents?.idleRuntimeCleanup ?? true,
idleCompaction: resolveIdleCompaction(persisted.agents),
...resolveRestartRecoveryConfig(persisted.agents),
providerCatalogRefreshTimeoutMs: persisted.agents?.catalogRefreshTimeoutMs,
metadataGeneration: persisted.agents?.metadataGeneration,
@@ -838,6 +841,10 @@ function resolveSpeechOverrideControlledPaths(
return paths;
}
function resolveIdleCompaction(agents: PersistedConfig["agents"]) {
return resolveIdleCompactionConfig(agents?.idleCompaction);
}
function resolveRestartRecoveryConfig(agents: PersistedConfig["agents"]) {
return {
resumeOnStartup: agents?.resumeOnStartup ?? false,
@@ -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,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;
@@ -370,6 +370,17 @@ export const PersistedConfigSchema = z
.object({
providers: z.preprocess(normalizeAgentProviders, ProviderOverridesSchema).optional(),
idleRuntimeCleanup: z.boolean().optional(),
idleCompaction: z
.union([
z.boolean(),
z
.object({
enabled: z.boolean().optional(),
minContextTokens: z.number().int().nonnegative().optional(),
})
.strict(),
])
.optional(),
resumeOnStartup: z.boolean().optional(),
resumePrompt: z.string().optional(),
catalogRefreshTimeoutMs: z.number().int().positive().max(2_147_483_647).optional(),
@@ -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(
+12
View File
@@ -3465,6 +3465,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":
@@ -6342,6 +6346,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,
},
}
: {}),
};
}
@@ -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) => ({
@@ -12,7 +12,7 @@ import {
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, test } from "vitest";
import { afterEach, describe, expect, test, vi } from "vitest";
import pino from "pino";
import { archivePersistedWorkspaceRecord } from "../../workspace-archive-service.js";
@@ -21,7 +21,12 @@ import {
readPaseoWorktreeMetadata,
writePaseoWorktreeMetadata,
} from "../../../utils/worktree-metadata.js";
import { createWorktree, deletePaseoWorktree } from "../../../utils/worktree.js";
import { getJujutsuState, getJujutsuWorkspaceName } from "../../../utils/checkout-jj.js";
import {
createWorktree,
deletePaseoWorktree,
rollbackCreatedPaseoWorktree,
} from "../../../utils/worktree.js";
import {
FileBackedProjectRegistry,
FileBackedWorkspaceRegistry,
@@ -852,3 +857,111 @@ describe("recovery approval ownership for shared archived history", () => {
expect(restored?.untrustedSource).toEqual(untrustedSource);
});
});
describe("Jujutsu workspace recovery", () => {
async function createFixture() {
const { tempDir, repoDir } = createGitRepository();
const config = join(tempDir, "jj.toml");
writeFileSync(config, '[user]\nname = "Paseo Test"\nemail = "test@example.com"\n');
vi.stubEnv("JJ_CONFIG", config);
vi.stubEnv("XDG_CONFIG_HOME", join(tempDir, "config"));
execFileSync("jj", ["git", "init", "--colocate"], { cwd: repoDir });
const paseoHome = join(tempDir, "paseo");
const created = await createWorktree({
cwd: repoDir,
paseoHome,
worktreeSlug: "recovery",
source: { kind: "branch-off", branchName: "recovery", baseBranch: "main" },
});
const workspace = createWorkspace({
cwd: created.worktreePath,
worktreeRoot: created.worktreePath,
mainRepoRoot: repoDir,
branch: null,
baseBranch: created.comparisonBaseRef,
archivedAt: null,
});
const registry = new FileBackedWorkspaceRegistry(
join(tempDir, "workspaces.json"),
pino({ level: "silent" }),
);
await registry.upsert(workspace);
const service = createWorkspaceRecoveryService({
paseoHome,
getWorkspace: (id) => registry.get(id),
getProject: async () => createProject({ rootPath: repoDir }),
isDirectory: async (path) => existsSync(path) && statSync(path).isDirectory(),
unarchiveWorkspace: async (record) => {
await registry.update(record.workspaceId, (value) => ({ ...value, archivedAt: null }));
},
});
return { repoDir, workspace, registry, service };
}
afterEach(() => vi.unstubAllEnvs());
test.each([
["an empty change", null],
["a change with disk edits", "unsnapshotted work\n"],
])("recreates the removed checkout for %s", async (_case, editedContent) => {
const { repoDir, workspace, registry, service } = await createFixture();
const file = join(workspace.cwd, "README.md");
const before = await getJujutsuState(workspace.cwd);
const metadata = await readPaseoWorktreeMetadata(workspace.cwd);
expect(metadata?.jujutsuBaseCommit).toMatch(/^[a-f0-9]{40}$/);
if (editedContent) writeFileSync(file, editedContent);
await archivePersistedWorkspaceRecord({
workspaceId: workspace.workspaceId,
workspaceRegistry: registry,
});
const saved = await registry.get(workspace.workspaceId);
const recoveryCommit = saved?.jujutsuRecoveryCommit;
if (!recoveryCommit) throw new Error("Missing Jujutsu recovery snapshot");
if (editedContent) expect(recoveryCommit).not.toBe(before.commitId);
else expect(recoveryCommit).toBe(before.commitId);
expect(saved?.jujutsuBaseCommit).toBe(metadata?.jujutsuBaseCommit);
await deletePaseoWorktree({
cwd: repoDir,
worktreePath: workspace.cwd,
registryProven: true,
teardownCwds: [],
jujutsuRecoveryCommit: recoveryCommit,
});
expect(existsSync(workspace.cwd)).toBe(false);
await expect(service.restore(workspace.workspaceId)).resolves.toEqual({
workspaceId: workspace.workspaceId,
action: "restore",
});
expect(readFileSync(file, "utf8")).toBe(editedContent ?? "initial\n");
expect(await readPaseoWorktreeMetadata(workspace.cwd)).toMatchObject({
jujutsuBaseCommit: saved?.jujutsuBaseCommit,
});
expect(await getJujutsuState(workspace.cwd)).toMatchObject({
changeId: before.changeId,
commitId: saved?.jujutsuRecoveryCommit,
});
expect((await registry.get(workspace.workspaceId))?.archivedAt).toBeNull();
expect(readFileSync(join(repoDir, "README.md"), "utf8")).toBe("initial\n");
});
test("rolls back both registrations after provisioning fails", async () => {
const { repoDir, workspace } = await createFixture();
const cause = new Error("provisioning failed");
await expect(
rollbackCreatedPaseoWorktree(
{
cwd: repoDir,
worktreePath: workspace.cwd,
teardownCwds: [],
},
cause,
),
).rejects.toBe(cause);
expect(existsSync(workspace.cwd)).toBe(false);
expect(await getJujutsuWorkspaceName(repoDir, workspace.cwd)).toBeNull();
expect(
execFileSync("git", ["worktree", "list", "--porcelain"], { cwd: repoDir, encoding: "utf8" }),
).not.toContain(workspace.cwd);
});
});
@@ -186,7 +186,14 @@ export function createWorkspaceRecoveryService(deps: {
): Promise<{ worktreePath: string; pluginId: string | null }> {
let source: WorktreeSource;
const checkout = parseWorkspaceHead(workspace);
if (checkout.kind === "branch") {
if (workspace.jujutsuRecoveryCommit) {
source = {
kind: "restore-jujutsu",
commit: workspace.jujutsuRecoveryCommit,
baseRef: workspace.baseBranch,
baseCommit: workspace.jujutsuBaseCommit,
};
} else if (checkout.kind === "branch") {
source = {
kind: "restore",
branchName: checkout.branch,
@@ -207,7 +214,9 @@ export function createWorkspaceRecoveryService(deps: {
}
try {
await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30_000 });
if (source.kind !== "restore-jujutsu") {
await runGitCommand(["worktree", "prune"], { cwd: sourceRepoRoot, timeout: 30_000 });
}
} catch {
// A stale worktree registration is not guaranteed; creation reports any real conflict.
}
@@ -290,7 +299,10 @@ export function createWorkspaceRecoveryService(deps: {
async function recreateWorktreeCheckout(options: {
workspace: PersistedWorkspaceRecord;
sourceRepoRoot: string;
source: Extract<WorktreeSource, { kind: "restore" | "restore-commit" | "restore-from-base" }>;
source: Extract<
WorktreeSource,
{ kind: "restore" | "restore-commit" | "restore-from-base" | "restore-jujutsu" }
>;
previousWorktreePath: string;
hasRecordedWorktreePath: boolean;
untrusted: boolean;
@@ -304,7 +316,12 @@ export function createWorkspaceRecoveryService(deps: {
untrusted,
} = options;
const managerPluginId = workspace.worktreeManagerPluginId;
if (managerPluginId && hasRecordedWorktreePath && deps.worktreeManagers) {
if (
source.kind !== "restore-jujutsu" &&
managerPluginId &&
hasRecordedWorktreePath &&
deps.worktreeManagers
) {
const adopted = await runPluginWorktreeManagerCheckout({
cwd: sourceRepoRoot,
source,
@@ -2292,6 +2292,7 @@ export class VoiceAssistantWebSocketServer {
fsEntryDuplicate: true,
// COMPAT(checkoutDiscardChanges): added in v0.3.0, remove gate after 2027-02-08.
checkoutDiscardChanges: true,
jujutsuCheckoutActions: true,
checkoutDiffAll: true,
// COMPAT(agentProfiles): added in v0.3.2, remove gate after 2027-02-11.
agentProfiles: true,
@@ -7,6 +7,7 @@ import { afterEach, describe, expect, test, vi } from "vitest";
import type { ForgeService } from "../services/forge-service.js";
import { createRealpathAwarePathMatcher } from "../utils/path.js";
import { getJujutsuWorkspaceName } from "../utils/checkout-jj.js";
import {
getPaseoWorktreeMetadataPath,
readPaseoWorktreeMetadata,
@@ -20,6 +21,7 @@ import type { WorkspaceGitService } from "./workspace-git-service.js";
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
import {
archiveByScope,
archivePersistedWorkspaceRecord,
unarchiveWorkspaceAgents,
type ActiveWorkspaceRef,
type ArchiveDependencies,
@@ -1750,3 +1752,127 @@ test.each(["outer", "inner"])(
expect(readFileSync(dirtyFile, "utf8")).toBe("keep-inner");
},
);
describe("Jujutsu workspace archive", () => {
async function createFixture(workspaceIds: string[]) {
const { tempDir, repoDir } = createGitRepo();
const config = path.join(tempDir, "jj.toml");
writeFileSync(config, '[user]\nname = "Test"\nemail = "test@example.invalid"\n');
vi.stubEnv("JJ_CONFIG", config);
vi.stubEnv("XDG_CONFIG_HOME", path.join(tempDir, "config"));
execFileSync("jj", ["git", "init", "--colocate"], { cwd: repoDir });
const paseoHome = path.join(tempDir, "paseo");
const { worktreePath: cwd } = await createPaseoOwnedWorktree(repoDir, paseoHome, "jj-archive");
const registry = new FileBackedWorkspaceRegistry(
path.join(tempDir, "workspaces.json"),
createLogger(),
);
const now = new Date().toISOString();
const workspaces = workspaceIds.map((workspaceId) =>
createPersistedWorkspaceRecord({
workspaceId,
projectId: repoDir,
cwd,
kind: "worktree",
worktreeRoot: cwd,
mainRepoRoot: repoDir,
isPaseoOwnedWorktree: true,
displayName: workspaceId,
createdAt: now,
updatedAt: now,
}),
);
for (const record of workspaces) await registry.upsert(record);
const dependencies = createArchiveDeps({ paseoHome, activeWorkspaces: workspaces });
dependencies.getWorkspace = (id) => registry.get(id);
dependencies.listActiveWorkspaces = () => registry.listActive();
dependencies.archiveWorkspaceRecord = async (workspaceId, archivedAt) => {
await archivePersistedWorkspaceRecord({
workspaceId,
archivedAt,
workspaceRegistry: registry,
});
};
return { repoDir, cwd, registry, dependencies };
}
afterEach(() => vi.unstubAllEnvs());
test("removes both registrations and the checkout after the last workspace is archived", async () => {
const { repoDir, cwd, dependencies, registry } = await createFixture(["first", "second"]);
writeFileSync(path.join(cwd, ".gitignore"), "scratch.log\n");
writeFileSync(path.join(cwd, "scratch.log"), "ignored file\n");
const first = await archiveByScope(dependencies, {
scope: { kind: "workspace", workspaceId: "first" },
requestId: "archive-first",
});
assertArchiveResult(first, { archivedWorkspaceIds: ["first"], removedDirectory: false });
expect(existsSync(path.join(cwd, "scratch.log"))).toBe(true);
expect(await getJujutsuWorkspaceName(repoDir, cwd)).toBeTruthy();
const second = await archiveByScope(dependencies, {
scope: { kind: "workspace", workspaceId: "second" },
requestId: "archive-second",
});
assertArchiveResult(second, { archivedWorkspaceIds: ["second"], removedDirectory: true });
expect(existsSync(cwd)).toBe(false);
expect(await getJujutsuWorkspaceName(repoDir, cwd)).toBeNull();
expect(
execFileSync("git", ["worktree", "list", "--porcelain"], { cwd: repoDir }).toString(),
).not.toContain("jj-archive");
for (const id of ["first", "second"]) {
expect((await registry.get(id))?.jujutsuRecoveryCommit).toMatch(/^[a-f0-9]{40}$/);
}
});
test("keeps a nested linked Git worktree from another repository on archive", async () => {
const { repoDir, cwd, dependencies, registry } = await createFixture(["jj-workspace"]);
const { repoDir: nestedRepo } = createGitRepo();
const nestedPath = path.join(cwd, "nested");
const dirtyFile = path.join(nestedPath, "uncommitted.txt");
writeFileSync(path.join(cwd, ".gitignore"), "nested/\n");
execFileSync("git", ["worktree", "add", "-b", "nested-task", nestedPath], {
cwd: nestedRepo,
stdio: "pipe",
});
writeFileSync(dirtyFile, "keep-inner");
const result = await archiveByScope(dependencies, {
scope: { kind: "workspace", workspaceId: "jj-workspace" },
requestId: "archive-nested-jj",
});
assertArchiveResult(result, {
archivedWorkspaceIds: ["jj-workspace"],
removedDirectory: false,
});
expect((await registry.get("jj-workspace"))?.jujutsuRecoveryCommit).toMatch(/^[a-f0-9]{40}$/);
expect(await getJujutsuWorkspaceName(repoDir, cwd)).toBeTruthy();
expect(readFileSync(dirtyFile, "utf8")).toBe("keep-inner");
const worktrees = execFileSync("git", ["worktree", "list", "--porcelain"], {
cwd: nestedRepo,
encoding: "utf8",
});
expect(worktrees).toContain("refs/heads/nested-task");
expect(worktrees).not.toContain("prunable");
});
test("retains the checkout if no Jujutsu recovery snapshot was recorded", async () => {
const { cwd, dependencies, registry } = await createFixture(["jj-workspace"]);
dependencies.archiveWorkspaceRecord = async (id, archivedAt) => {
await registry.archive(id, archivedAt);
};
const result = await archiveByScope(dependencies, {
scope: { kind: "workspace", workspaceId: "jj-workspace" },
requestId: "skip-jj-removal",
});
assertArchiveResult(result, {
archivedWorkspaceIds: ["jj-workspace"],
removedDirectory: false,
});
expect(existsSync(path.join(cwd, ".jj"))).toBe(true);
});
});
@@ -1,5 +1,6 @@
import { commandRunHook } from "./command-run-hook.js";
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
import { findJujutsuRoot, saveJujutsuRecoveryCommit } from "../utils/checkout-jj.js";
import { resolve } from "node:path";
import type { Logger } from "pino";
@@ -629,8 +630,13 @@ async function maybeRemoveDirectory(
// Last chance to keep the directory. Teardown commands already ran, so a cancel here restores
// a workspace whose teardown hooks fired; that beats deleting what the user asked to keep.
request.checkpoint();
try {
const jujutsuRecoveryCommit =
(await findJujutsuRoot(backing.path)) === resolve(backing.path)
? await getArchivedJujutsuRecoveryCommit(dependencies, backing.path, archivedWorkspaceIds)
: undefined;
request.checkpoint();
await deletePaseoWorktree({
cwd: backing.mainRepoRoot,
worktreePath: backing.path,
@@ -643,11 +649,13 @@ async function maybeRemoveDirectory(
worktreeManagerPluginId: backing.worktreeManagerPluginId,
removeReason: "archive",
untrusted: untrustedBacking,
jujutsuRecoveryCommit,
});
dependencies.workspaceGitService.invalidateWorktrees();
dependencies.github.invalidate({ cwd: backing.path });
return { removedDirectory: true };
} catch (error) {
if (error instanceof WorkspaceArchiveCanceledError) throw error;
dependencies.sessionLogger?.warn(
{ err: error, targetPath: backing.path, requestId: request.requestId },
"Worktree disk removal failed during archive; workspace already archived",
@@ -688,6 +696,23 @@ async function resolveCheckoutTeardownPlan(
};
}
async function getArchivedJujutsuRecoveryCommit(
dependencies: Pick<ArchiveDependencies, "getWorkspace">,
path: string,
archivedWorkspaceIds: string[],
): Promise<string | undefined> {
const matches = createRealpathAwarePathMatcher(path);
const records = await Promise.all(
archivedWorkspaceIds.map((id) => dependencies.getWorkspace?.(id)),
);
return records.find(
(record) =>
record?.archivedAt &&
record.jujutsuRecoveryCommit &&
matches(record.worktreeRoot ?? record.cwd),
)?.jujutsuRecoveryCommit;
}
async function filterAllowedTeardownTargets(
dependencies: ArchiveDependencies,
targets: Array<{ workspaceId: string; cwd: string }>,
@@ -899,13 +924,22 @@ export async function archivePersistedWorkspaceRecord(input: {
const archivedAt = input.archivedAt ?? new Date().toISOString();
let head: string | null = null;
let jujutsuRecoveryCommit: string | undefined;
let jujutsuBaseCommit: string | undefined;
if (existingWorkspace.kind === "worktree") {
const cwd = existingWorkspace.worktreeRoot ?? existingWorkspace.cwd;
head = await readWorktreeHeadReference(cwd);
if (existingWorkspace.isPaseoOwnedWorktree && (await findJujutsuRoot(cwd)) === resolve(cwd)) {
jujutsuRecoveryCommit = await saveJujutsuRecoveryCommit(cwd);
jujutsuBaseCommit = (await readPaseoWorktreeMetadata(cwd))?.jujutsuBaseCommit;
} else {
head = await readWorktreeHeadReference(cwd);
}
}
await input.workspaceRegistry.archive(input.workspaceId, archivedAt, {
...input.context,
...(head ? { head } : {}),
jujutsuRecoveryCommit,
jujutsuBaseCommit,
});
return existingWorkspace;
@@ -1,3 +1,4 @@
import { findJujutsuRoot } from "../utils/checkout-jj.js";
import { runGitCommand, type RunGitCommand } from "../utils/run-git-command.js";
export interface WorkspaceGitFetchResult {
@@ -21,6 +22,8 @@ export async function fetchWorkspaceGitRemote(
observer: WorkspaceGitFetchObserver,
run: RunGitCommand = runGitCommand,
): Promise<WorkspaceGitFetchResult> {
if (await findJujutsuRoot(cwd)) return { changes: [], error: null };
let before: Map<string, string> | null = null;
let after: Map<string, string> | null = null;
let error: unknown | null = null;
@@ -1,3 +1,5 @@
import { getJujutsuOperationHeads } from "../utils/checkout-jj.js";
import type { JujutsuState } from "../utils/checkout-jj.js";
import { createHash } from "node:crypto";
import { readFile, stat } from "node:fs/promises";
import { basename, dirname, join, resolve } from "node:path";
@@ -174,6 +176,7 @@ export const getWorkspaceGitSelfHealPhaseMs = getWorkspaceGitObservationReensure
export interface WorkspaceGitRuntimeSnapshot {
cwd: string;
git: {
jujutsu?: JujutsuState;
isGit: boolean;
repoRoot: string | null;
mainRepoRoot: string | null;
@@ -482,6 +485,7 @@ class WorkspaceGitWatcherSubscriptionTimeoutError extends Error {
}
interface WorkspaceGitTarget {
jujutsuSubscription?: FileObserverSubscription;
gitDirPaths: GitObservationPaths | null;
cwd: string;
listeners: Set<WorkspaceGitListener>;
@@ -1476,12 +1480,54 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
}
target.repoGitRoot = repoGitRoot;
await this.ensureRepoTarget(target);
if (facts.jujutsu) await this.setupJujutsuObservation(target);
if (this.isActiveObservedWorkspaceTarget(target)) {
target.observationSetupComplete = true;
this.refreshAfterWorkingTreeCoverage(target);
}
}
private releaseJujutsuObservation(target: WorkspaceGitTarget): void {
const subscription = target.jujutsuSubscription;
target.jujutsuSubscription = undefined;
if (!subscription) return;
void subscription.unsubscribe().catch((error) => {
this.logger.warn(
{ err: error, cwd: target.cwd },
"Failed to release Jujutsu metadata observation",
);
});
}
private async setupJujutsuObservation(target: WorkspaceGitTarget): Promise<void> {
if (target.jujutsuSubscription) return;
const heads = await getJujutsuOperationHeads(target.cwd);
if (!heads) return;
const subscription = await this.subscribeWithDeadline(
heads,
(error) => {
if (!this.isActiveObservedWorkspaceTarget(target)) return;
if (error) {
this.logger.warn({ err: error, cwd: target.cwd }, "Jujutsu metadata observation failed");
target.observationSetupComplete = false;
this.releaseJujutsuObservation(target);
}
this.scheduleWorkspaceRefresh(target, {
origin: "observation",
reason: "jujutsu-operation",
});
},
{},
() => {},
);
if (!this.isActiveObservedWorkspaceTarget(target)) {
await subscription.unsubscribe();
return;
}
target.jujutsuSubscription = subscription;
}
// Watchers report only changes made after they subscribe, and the initial
// snapshot is read in parallel with observation setup, so an edit or branch
// switch in between reaches no watcher. Read the checkout once more now that
@@ -3363,6 +3409,9 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
target: WorkspaceGitTarget,
): WorkspaceForgePrStatusPollTarget | null {
const git = target.latestGit;
if (git?.jujutsu && target.latestFacts?.isGit) {
return target.latestFacts.pullRequestLookupTarget;
}
if (!git?.currentBranch) {
return null;
}
@@ -3835,6 +3884,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
: (target.latestGit?.diffStat ?? null);
target.latestGit = {
...(checkoutStatus.jujutsu ? { jujutsu: checkoutStatus.jujutsu } : {}),
isGit: true,
repoRoot: checkoutStatus.repoRoot,
mainRepoRoot: checkoutStatus.mainRepoRoot,
@@ -3947,7 +3997,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
private getForgePrStatusPollKey(target: WorkspaceGitTarget): string | null {
const git = target.latestGit;
if (!git?.currentBranch || !git.remoteUrl) {
if (!git?.remoteUrl) {
return null;
}
@@ -4320,6 +4370,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
}
private stopWorkspaceObservation(target: WorkspaceGitTarget): void {
this.releaseJujutsuObservation(target);
if (target.workingTreeWatchTarget) {
this.removeWorkspaceWorkingTreeLink(target.workingTreeWatchTarget, target.cwd);
target.workingTreeWatchTarget = null;
@@ -73,6 +73,14 @@ const PersistedWorkspaceRecordSchema = z.object({
.optional()
.transform((value) => value ?? null),
head: z.string().optional(),
jujutsuRecoveryCommit: z
.string()
.regex(/^[a-f0-9]{40}$/)
.optional(),
jujutsuBaseCommit: z
.string()
.regex(/^[a-f0-9]{40}$/)
.optional(),
// Exact checkout/worktree root backing cwd. This differs from cwd when the
// selected project is a subdirectory inside a repository. Persist it so
// archive and recovery do not need the directory to still exist in order to
@@ -129,6 +137,8 @@ export interface WorkspaceMutationContext {
export interface WorkspaceArchiveContext {
autoArchivedChangeRequestUrl?: string;
head?: string;
jujutsuRecoveryCommit?: string;
jujutsuBaseCommit?: string;
}
export interface ProjectMutation {
@@ -590,6 +600,8 @@ export class FileBackedWorkspaceRegistry
updatedAt: archivedAt,
archivedAt,
head: context?.head,
jujutsuRecoveryCommit: context?.jujutsuRecoveryCommit ?? existing.jujutsuRecoveryCommit,
jujutsuBaseCommit: context?.jujutsuBaseCommit ?? existing.jujutsuBaseCommit,
...(context?.autoArchivedChangeRequestUrl
? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl }
: {}),
@@ -12,7 +12,7 @@ import {
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, test, afterEach } from "vitest";
import { describe, expect, test, afterEach, vi } from "vitest";
import type { ForgeService } from "../services/forge-service.js";
import { createGitLabService } from "../services/gitlab-service.js";
import {
@@ -435,6 +435,46 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
expect(existsSync(result.worktree.worktreePath)).toBe(true);
});
test("creates a Jujutsu workspace from @ with a Git worktree manager installed", async () => {
const { tempDir, repoDir, paseoHome } = createGitRepo();
cleanupPaths.push(tempDir);
const config = path.join(tempDir, "jj.toml");
writeFileSync(config, '[user]\nname = "Test"\nemail = "test@example.invalid"\n');
vi.stubEnv("JJ_CONFIG", config);
vi.stubEnv("XDG_CONFIG_HOME", path.join(tempDir, "config"));
try {
execFileSync("jj", ["git", "init", "--colocate"], { cwd: repoDir });
writeFileSync(path.join(repoDir, "uncommitted.txt"), "from source @");
const managerCreateWorktree = vi.fn(async () => null);
const result = await createCoreWorktree(
{
cwd: repoDir,
worktreeSlug: "jj-with-manager",
action: "branch-off",
refName: "@",
paseoHome,
},
{
...createCoreDeps(),
worktreeManagers: {
hasWorktreeManager: () => true,
createWorktree: managerCreateWorktree,
removeWorktree: async () => null,
},
},
);
expect(managerCreateWorktree).not.toHaveBeenCalled();
expect(existsSync(path.join(result.worktree.worktreePath, ".jj"))).toBe(true);
expect(
readFileSync(path.join(result.worktree.worktreePath, "uncommitted.txt"), "utf8"),
).toBe("from source @");
} finally {
vi.unstubAllEnvs();
}
});
test("keeps default placement suffixes when the default destination already exists", async () => {
const { tempDir, repoDir, paseoHome } = createGitRepo();
cleanupPaths.push(tempDir);
+66 -44
View File
@@ -2,6 +2,9 @@ import type {
PluginWorktreeCreateInput,
PluginWorktreeCreateRequest,
} from "@getpaseo/plugin/server";
import { resolveRepositoryDefaultBranch } from "../utils/checkout-git.js";
import { resolveCheckoutProvider } from "../utils/checkout-vcs.js";
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
import { createNameId } from "mnemonic-id";
@@ -75,6 +78,21 @@ export async function createWorktreeCore(
return runWithGitCommandPriority("high", () => createWorktreeCoreWithPriority(input, deps));
}
async function resolveJujutsuSource(input: CreateWorktreeCoreInput): Promise<string | null> {
const provider = await resolveCheckoutProvider(input.cwd);
const jujutsuRoot = provider.kind === "jujutsu" ? provider.root : null;
if (
jujutsuRoot &&
(input.action === "checkout" || input.checkoutSource || input.githubPrNumber !== undefined)
) {
throw new Error(
"Jujutsu workspaces support branching from a base revision; open existing changes as local workspaces.",
);
}
return jujutsuRoot;
}
async function createWorktreeCoreWithPriority(
input: CreateWorktreeCoreInput,
deps: CreateWorktreeCoreDeps,
@@ -90,48 +108,17 @@ async function createWorktreeAtRepositoryRoot(
deps: CreateWorktreeCoreDeps,
repoRoot: string,
): Promise<CreateWorktreeCoreResult> {
const jujutsuRoot = await resolveJujutsuSource(input);
const requestedWorktreeSlug = input.worktreeSlug
? normalizeWorktreeSlug(input.worktreeSlug)
: undefined;
const requestedBranchName = input.branchName?.trim();
let intentInput: ResolveWorktreeCreationIntentInput;
if (input.action === "checkout") {
intentInput = {
action: "checkout",
refName: input.refName,
checkoutSource: input.checkoutSource,
githubPrNumber: input.githubPrNumber,
worktreeSlug: requestedWorktreeSlug,
};
} else if (
input.action !== "branch-off" &&
(input.checkoutSource !== undefined || input.githubPrNumber !== undefined)
) {
// A change request with no action is checked out, as clients did before `action` existed.
intentInput = {
checkoutSource: input.checkoutSource,
githubPrNumber: input.githubPrNumber,
refName: input.refName,
worktreeSlug: requestedWorktreeSlug,
};
} else {
const worktreeSlug = requestedWorktreeSlug ?? normalizeWorktreeSlug(createNameId());
intentInput = {
action: "branch-off",
refName: input.refName,
checkoutSource: input.checkoutSource,
githubPrNumber: input.githubPrNumber,
branchName: requestedBranchName,
worktreeSlug,
};
}
const intentInput = describeCreationIntentInput(input, requestedWorktreeSlug);
const forge = await resolveForge(repoRoot, deps, intentInput);
let intent = await resolveWorktreeCreationIntent(intentInput, repoRoot, {
forge: forge.forge,
forgeService: forge.service,
resolveDefaultBranch: (root) => resolveDefaultBranch(root, deps),
resolveDefaultBranch: (root) => resolveDefaultBranch(root, deps, jujutsuRoot !== null),
fetchRef: ({ repoRoot: cwd, sources, destination }) =>
fetchFirstAvailableRef({ cwd, sources, destination }),
});
@@ -178,18 +165,23 @@ async function createWorktreeAtRepositoryRoot(
intent = creationIntentFromRequest(transformed, intent);
const untrustedSource = originalUntrustedSource ?? worktreeUntrustedSource(intent);
const { worktree: managedWorktree, preparedBranchOff } = await tryCreateWithWorktreeManager({
repoRoot,
transformed,
intent,
untrusted: Boolean(untrustedSource),
input,
deps,
});
// Worktree managers prepare and verify a Git branch, including before their callback.
const { worktree: managedWorktree, preparedBranchOff } = jujutsuRoot
? { worktree: null, preparedBranchOff: undefined }
: await tryCreateWithWorktreeManager({
repoRoot,
transformed,
intent,
untrusted: Boolean(untrustedSource),
input,
deps,
});
const createdWorktree =
managedWorktree ??
(await createWorktree({
cwd: repoRoot,
cwd: jujutsuRoot ?? sourceCheckout,
// Git worktrees have historically inherited root-level Paseo config from repoRoot.
configSourceCwd: jujutsuRoot ?? repoRoot,
worktreeSlug: normalizedSlug,
worktreePath: transformed.path,
source: intent,
@@ -209,6 +201,31 @@ async function createWorktreeAtRepositoryRoot(
};
}
function describeCreationIntentInput(
input: CreateWorktreeCoreInput,
worktreeSlug: string | undefined,
): ResolveWorktreeCreationIntentInput {
const { checkoutSource, githubPrNumber, refName } = input;
if (input.action === "checkout") {
return { action: "checkout", refName, checkoutSource, githubPrNumber, worktreeSlug };
}
if (
input.action !== "branch-off" &&
(checkoutSource !== undefined || githubPrNumber !== undefined)
) {
// A change request with no action is checked out, as clients did before `action` existed.
return { checkoutSource, githubPrNumber, refName, worktreeSlug };
}
return {
action: "branch-off",
refName,
checkoutSource,
githubPrNumber,
branchName: input.branchName?.trim(),
worktreeSlug: worktreeSlug ?? normalizeWorktreeSlug(createNameId()),
};
}
async function tryCreateWithWorktreeManager(options: {
repoRoot: string;
transformed: PluginWorktreeCreateRequest;
@@ -325,7 +342,12 @@ async function resolveForge(
async function resolveDefaultBranch(
repoRoot: string,
deps: CreateWorktreeCoreDeps,
isJujutsu: boolean,
): Promise<string> {
if (isJujutsu && !deps.resolveDefaultBranch) {
return (await resolveRepositoryDefaultBranch(repoRoot)) ?? "@";
}
const baseBranch = deps.resolveDefaultBranch
? await deps.resolveDefaultBranch(repoRoot)
: await deps.workspaceGitService?.resolveDefaultBranch(repoRoot);
@@ -1,3 +1,21 @@
import { runJujutsuCheckoutAction } from "./jujutsu-actions.js";
import { createWorktreeCore } from "../server/worktree-core.js";
import { createGitHubService } from "../services/github-service.js";
import {
WorkspaceGitServiceImpl,
type WorkspaceGitRuntimeSnapshot,
} from "../server/workspace-git-service.js";
import { listComparison } from "../server/diff/git.js";
import { deletePaseoWorktree } from "./worktree.js";
import {
findJujutsuRoot,
getJujutsuState,
getJujutsuDiff,
listJujutsuCommits,
saveJujutsuRecoveryCommit,
resolveJujutsuRevision,
searchJujutsuChanges,
} from "./checkout-jj.js";
import { describe, it, expect, beforeEach, afterEach, afterAll } from "vitest";
import { execFileSync, execSync, spawnSync } from "child_process";
import {
@@ -49,6 +67,7 @@ import {
isPaseoWorktreePath,
isDescendantPath,
warmCheckoutShortstatInBackground,
listCheckoutCommits,
} from "./checkout-git.js";
import { startGitCommandMetrics, stopGitCommandMetrics } from "./run-git-command.js";
import { createForgeResolver } from "../services/forge-resolver.js";
@@ -4836,3 +4855,723 @@ describe("discardChanges", () => {
}
});
});
describe("Jujutsu checkout inspection", () => {
let root: string;
let repo: string;
let config: string | undefined;
let cache: string | undefined;
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "paseo-jj-"));
repo = join(root, "repo");
config = process.env.JJ_CONFIG;
cache = process.env.XDG_CONFIG_HOME;
process.env.JJ_CONFIG = join(root, "jj.toml");
process.env.XDG_CONFIG_HOME = join(root, "config");
writeFileSync(process.env.JJ_CONFIG, '[user]\nname = "Test"\nemail = "test@example.invalid"\n');
execFileSync("jj", ["git", "init", "--colocate", repo]);
writeFileSync(join(repo, "file.txt"), "base\n");
execFileSync("jj", ["commit", "-m", "Base"], { cwd: repo });
execFileSync("jj", ["bookmark", "create", "main", "-r", "@-"], { cwd: repo });
});
afterEach(() => {
if (config === undefined) delete process.env.JJ_CONFIG;
else process.env.JJ_CONFIG = config;
if (cache === undefined) delete process.env.XDG_CONFIG_HOME;
else process.env.XDG_CONFIG_HOME = cache;
rmSync(root, { recursive: true, force: true });
});
it("detects a colocated checkout from subdirectories and respects nested Git roots", async () => {
const nested = join(repo, "nested");
mkdirSync(nested);
expect(await findJujutsuRoot(nested)).toBe(repo);
execFileSync("git", ["init", nested]);
expect(await findJujutsuRoot(nested)).toBeNull();
});
it("reads live changes without moving the operation head, @, or Git HEAD", async () => {
const before = await getJujutsuState(repo);
const operation = execFileSync(
"jj",
["--ignore-working-copy", "op", "log", "--no-graph", "--limit", "1", "-T", "id"],
{ cwd: repo },
).toString();
const head = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repo }).toString();
writeFileSync(join(repo, "file.txt"), "base\nlive edit\n");
writeFileSync(join(repo, "new file.txt"), "new content\n");
const diff = await getJujutsuDiff(repo, {});
expect(diff).toContain("+live edit");
expect(diff).toContain("+new content");
expect(await getJujutsuState(repo)).toEqual(before);
expect(
execFileSync(
"jj",
["--ignore-working-copy", "op", "log", "--no-graph", "--limit", "1", "-T", "id"],
{ cwd: repo },
).toString(),
).toBe(operation);
expect(execFileSync("git", ["rev-parse", "HEAD"], { cwd: repo }).toString()).toBe(head);
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("base\nlive edit\n");
});
it("reports jj identity, bookmarks and changes through checkout status", async () => {
writeFileSync(join(repo, "file.txt"), "base\nstatus edit\n");
execFileSync("jj", ["describe", "-m", "Current task"], { cwd: repo });
execFileSync("jj", ["bookmark", "create", "task"], { cwd: repo });
const status = await getCheckoutStatus(repo);
expect(status.isGit).toBe(true);
expect(status).toMatchObject({
isDirty: true,
jujutsu: { description: "Current task\n", bookmarks: ["task"], hasConflicts: false },
});
});
it("streams the current change including disk edits through the shared diff engine", async () => {
writeFileSync(join(repo, "file.txt"), "base\nrecorded edit\n");
execFileSync("jj", ["describe", "-m", "Task"], { cwd: repo });
writeFileSync(join(repo, "file.txt"), "base\nrecorded edit\nlive edit\n");
const comparison = await listComparison({
cwd: repo,
base: { kind: "rev", rev: "HEAD" },
head: { kind: "worktree" },
highlight: false,
});
try {
expect(comparison.files.map((file) => file.entry)).toEqual([
{
path: "file.txt",
oldPath: null,
change: "modified",
content: "text",
additions: 2,
deletions: 0,
body: true,
},
]);
const read = await comparison.read(comparison.files[0]);
expect(read.kind).toBe("ready");
expect(JSON.stringify(read)).toContain("recorded edit");
expect(JSON.stringify(read)).toContain("live edit");
} finally {
await comparison.close();
}
});
it("resolves Git remote-tracking names for any remote and leaves revsets alone", async () => {
const upstream = join(root, "upstream.git");
execFileSync("git", ["init", "--bare", upstream]);
execFileSync("git", ["remote", "add", "upstream", upstream], { cwd: repo });
execFileSync("jj", ["git", "push", "--remote", "upstream", "--bookmark", "main"], {
cwd: repo,
});
execFileSync("jj", ["bookmark", "create", "feature/x", "-r", "main"], { cwd: repo });
const main = execFileSync("git", ["rev-parse", "main"], { cwd: repo }).toString().trim();
expect(await resolveJujutsuRevision(repo, "upstream/main")).toBe(main);
expect(await resolveJujutsuRevision(repo, "refs/remotes/upstream/main")).toBe(main);
expect(await resolveJujutsuRevision(repo, "feature/x")).toBe("feature/x");
expect(await resolveJujutsuRevision(repo, "main@upstream")).toBe("main@upstream");
});
it("rejects Git mutations without altering a jj checkout", async () => {
writeFileSync(join(repo, "file.txt"), "keep this edit\n");
await expect(commitAll(repo, "Wrong VCS")).rejects.toThrow("uses Jujutsu");
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("keep this edit\n");
});
it("discards working-copy changes to the given paths with jj restore", async () => {
writeFileSync(join(repo, "file.txt"), "discard this\n");
writeFileSync(join(repo, "new file.txt"), "and this\n");
writeFileSync(join(repo, "other.txt"), "keep this\n");
await discardChanges(repo, ["file.txt", "new file.txt"]);
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("base\n");
expect(existsSync(join(repo, "new file.txt"))).toBe(false);
expect(readFileSync(join(repo, "other.txt"), "utf8")).toBe("keep this\n");
});
it("keeps a Jujutsu checkout when it has changed since the recovery snapshot", async () => {
const result = await createWorktreePrimitive({
cwd: repo,
paseoHome: join(root, "paseo"),
worktreeSlug: "parallel",
source: { kind: "branch-off", baseBranch: "main", branchName: "parallel" },
});
expect(existsSync(join(result.worktreePath, ".jj"))).toBe(true);
expect(existsSync(join(result.worktreePath, ".git"))).toBe(true);
expect(await findJujutsuRoot(result.worktreePath)).toBe(result.worktreePath);
const jujutsuRecoveryCommit = await saveJujutsuRecoveryCommit(result.worktreePath);
writeFileSync(join(result.worktreePath, "file.txt"), "agent edit\n");
writeFileSync(join(result.worktreePath, "scratch.log"), "keep scratch\n");
await expect(
deletePaseoWorktree({
cwd: repo,
worktreePath: result.worktreePath,
paseoHome: join(root, "paseo"),
jujutsuRecoveryCommit,
}),
).rejects.toThrow("changed after the archive snapshot");
expect(readFileSync(join(result.worktreePath, "file.txt"), "utf8")).toBe("agent edit\n");
expect(readFileSync(join(result.worktreePath, "scratch.log"), "utf8")).toBe("keep scratch\n");
expect((await getJujutsuState(repo)).bookmarks).toEqual([]);
});
it("branches from current work explicitly and keeps parallel edits isolated", async () => {
writeFileSync(join(repo, "file.txt"), "base\ncurrent work\n");
const first = await createWorktreePrimitive({
cwd: repo,
paseoHome: join(root, "paseo"),
worktreeSlug: "parallel",
source: { kind: "branch-off", baseBranch: "@", branchName: "parallel" },
});
const second = await createWorktreePrimitive({
cwd: repo,
paseoHome: join(root, "paseo"),
worktreeSlug: "parallel",
source: { kind: "branch-off", baseBranch: "@", branchName: "parallel" },
});
expect(readFileSync(join(first.worktreePath, "file.txt"), "utf8")).toBe("base\ncurrent work\n");
expect(readFileSync(join(second.worktreePath, "file.txt"), "utf8")).toBe(
"base\ncurrent work\n",
);
writeFileSync(join(first.worktreePath, "file.txt"), "first agent\n");
expect(readFileSync(join(second.worktreePath, "file.txt"), "utf8")).toBe(
"base\ncurrent work\n",
);
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("base\ncurrent work\n");
});
it("records the base by name and diffs from its fork point after it moves", async () => {
const named = await createWorktreePrimitive({
cwd: repo,
paseoHome: join(root, "paseo"),
worktreeSlug: "named",
source: { kind: "branch-off", baseBranch: "main", branchName: "named" },
});
expect(await readPaseoWorktreeMetadata(named.worktreePath)).toMatchObject({
baseRefName: "main",
baseRef: "main",
});
const current = await createWorktreePrimitive({
cwd: repo,
paseoHome: join(root, "paseo"),
worktreeSlug: "current",
source: { kind: "branch-off", baseBranch: "@", branchName: "current" },
});
const sourceChange = (await getJujutsuState(repo)).changeId;
const recorded = (await readPaseoWorktreeMetadata(current.worktreePath))?.baseRef;
expect(recorded && sourceChange.startsWith(recorded)).toBe(true);
// Move `main` on in the source workspace; the task diff must not show that as a revert.
writeFileSync(join(named.worktreePath, "task.txt"), "task\n");
writeFileSync(join(repo, "file.txt"), "base\nupstream\n");
execFileSync("jj", ["commit", "-m", "Upstream"], { cwd: repo });
execFileSync("jj", ["bookmark", "set", "main", "-r", "@-"], { cwd: repo });
const diff = await getJujutsuDiff(named.worktreePath, { baseRef: "main" });
expect(diff).toContain("+task");
expect(diff).not.toContain("upstream");
});
it("records an operation that includes commits imported from Git", async () => {
writeFileSync(join(repo, "file.txt"), "working copy edit\n");
const git = (args: string[]) =>
execFileSync("git", args, { cwd: repo, encoding: "utf8" }).trim();
const tree = git(["rev-parse", "HEAD^{tree}"]);
const imported = git([
"-c",
"user.name=Test",
"-c",
"user.email=test@example.invalid",
"commit-tree",
"-m",
"Imported",
tree,
]);
git(["branch", "imported", imported]);
const commits = await listJujutsuCommits(repo, "main", 5);
const operationId = commits.find((commit) => commit.jujutsu.isWorkingCopy)?.jujutsu.operationId;
expect(operationId).toMatch(/^[0-9a-f]+$/);
const output = execFileSync(
"jj",
["--at-operation", operationId!, "log", "--no-graph", "-r", imported, "-T", "commit_id"],
{ cwd: repo, encoding: "utf8" },
);
expect(output).toBe(imported);
});
it("keeps the selected comparison when the bookmark is deleted", async () => {
const paseoHome = join(root, "paseo");
const workspace = await createWorktreePrimitive({
cwd: repo,
paseoHome,
worktreeSlug: "missing-bookmark",
source: { kind: "branch-off", baseBranch: "refs/heads/main", branchName: "missing-bookmark" },
});
const cwd = workspace.worktreePath;
const context = { paseoHome };
writeFileSync(join(cwd, "file.txt"), "edit after base\n");
const compare = { mode: "base", baseRef: "refs/heads/main" } as const;
const before = await getCheckoutDiff(cwd, compare, context);
expect(before.diff).toContain("+edit after base");
execFileSync("jj", ["bookmark", "delete", "main"], { cwd: repo });
expect(await getCheckoutStatus(cwd, context)).toMatchObject({
jujutsu: { baseBookmarkMissing: true },
});
expect(await getCheckoutDiff(cwd, compare, context)).toEqual(before);
const { commits } = await listCheckoutCommits({ cwd, context });
expect(commits.find((commit) => commit.isOnBase)?.subject).toBe("Base");
expect(commits.find((commit) => commit.jujutsu?.isWorkingCopy)?.files).toEqual([
{ path: "file.txt", additions: 1, deletions: 1, status: "modified" },
]);
});
it("reports a workspace that another workspace made stale and updates it", async () => {
const other = join(root, "other");
execFileSync("jj", ["workspace", "add", "--name", "other", other], { cwd: repo });
writeFileSync(join(repo, "file.txt"), "merged elsewhere\n");
execFileSync("jj", ["describe", "-m", "Merged"], { cwd: repo });
writeFileSync(join(repo, "unsnapshotted.txt"), "not seen by jj yet\n");
execFileSync("jj", ["abandon", "default@"], { cwd: other });
const stale = await getJujutsuState(repo);
expect(stale.stale).toBe(true);
expect(await getJujutsuDiff(repo, {})).toBe("");
await runJujutsuCheckoutAction({
cwd: repo,
expectedChangeId: "moved",
action: { kind: "update_stale" },
resolveForge: async () => {
throw new Error("No forge configured");
},
});
expect((await getJujutsuState(repo)).stale).toBe(false);
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("base\n");
// The edit jj hadn't snapshotted is kept in a change of its own.
expect(
execFileSync(
"jj",
["file", "show", "-r", "description(substring:Merged) ~ @", "unsnapshotted.txt"],
{ cwd: repo },
).toString(),
).toBe("not seen by jj yet\n");
});
it("starts a change on an exact local ref even when its name starts with a remote", async () => {
execFileSync("jj", ["git", "remote", "add", "origin", join(root, "unused")], { cwd: repo });
execFileSync("jj", ["bookmark", "create", "-r", "main", "origin/topic"], { cwd: repo });
await runJujutsuCheckoutAction({
cwd: repo,
expectedChangeId: (await getJujutsuState(repo)).changeId,
action: { kind: "new", parent: "refs/heads/origin/topic" },
resolveForge: async () => {
throw new Error("No forge configured");
},
});
expect(
execFileSync("jj", ["log", "--no-graph", "-r", "@-", "-T", "commit_id"], {
cwd: repo,
}).toString(),
).toBe(
execFileSync("git", ["rev-parse", "refs/heads/origin/topic"], { cwd: repo })
.toString()
.trim(),
);
});
it("reports the nearest bookmark and starts a new change on a chosen bookmark", async () => {
// `main` is on @-, so it is the closest bookmark under the working copy.
expect((await getJujutsuState(repo)).nearestBookmark).toBe("main");
writeFileSync(join(repo, "file.txt"), "work in progress\n");
execFileSync("jj", ["describe", "-m", "WIP"], { cwd: repo });
const before = await getJujutsuState(repo);
await runJujutsuCheckoutAction({
cwd: repo,
expectedChangeId: before.changeId,
action: { kind: "new", parent: "main" },
resolveForge: async () => {
throw new Error("No forge configured");
},
});
const parent = execFileSync("jj", ["log", "--no-graph", "-r", "@-", "-T", "commit_id"], {
cwd: repo,
}).toString();
const main = execFileSync("jj", ["log", "--no-graph", "-r", "main", "-T", "commit_id"], {
cwd: repo,
}).toString();
expect(parent).toBe(main);
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("base\n");
// The previous change keeps its work.
expect(
execFileSync("jj", ["file", "show", "-r", before.changeId, "file.txt"], {
cwd: repo,
}).toString(),
).toBe("work in progress\n");
});
it("lists a workspace's jj changes since its base, then the base's history", async () => {
const workspace = await createWorktreePrimitive({
cwd: repo,
paseoHome: join(root, "paseo"),
worktreeSlug: "changes",
source: { kind: "branch-off", baseBranch: "main", branchName: "changes" },
});
const cwd = workspace.worktreePath;
writeFileSync(join(cwd, "first.txt"), "one\ntwo\n");
execFileSync("jj", ["commit", "-m", "First change"], { cwd });
writeFileSync(join(cwd, "file.txt"), "edited\n");
const { baseRef, commits } = await listCheckoutCommits({
cwd,
context: { paseoHome: join(root, "paseo") },
});
expect(baseRef).toBe("main");
const ahead = commits.filter((commit) => !commit.isOnBase);
// Newest first: the working copy (described or not), then the committed change.
expect(ahead.map((commit) => [commit.subject, commit.jujutsu?.isWorkingCopy])).toEqual([
["", true],
["First change", false],
]);
// The working copy's live edit is listed although nothing has snapshotted it.
expect(ahead[0].files).toEqual([
{ path: "file.txt", additions: 1, deletions: 1, status: "modified" },
]);
expect(ahead[1].files).toEqual([
{ path: "first.txt", additions: 2, deletions: 0, status: "added" },
]);
expect(ahead[1].shortSha).toBe(ahead[1].jujutsu?.changeId.slice(0, ahead[1].shortSha.length));
expect(commits.find((commit) => commit.isOnBase)?.subject).toBe("Base");
});
it("searches changes across the repository, not just the current line", async () => {
// A side branch off `main`, away from the working copy's line.
execFileSync("jj", ["new", "main", "-m", "Side experiment"], { cwd: repo });
writeFileSync(join(repo, "side.txt"), "side\n");
execFileSync("jj", ["new", "main"], { cwd: repo });
const side = execFileSync(
"jj",
["log", "--no-graph", "-r", 'description(exact:"Side experiment\n")', "-T", "change_id"],
{ cwd: repo },
).toString();
const all = await searchJujutsuChanges(repo, "");
expect(all.map((change) => change.changeId)).toContain(side);
expect((await searchJujutsuChanges(repo, "side EXPERIMENT")).map((c) => c.changeId)).toEqual([
side,
]);
expect((await searchJujutsuChanges(repo, side.slice(0, 6))).map((c) => c.changeId)).toEqual([
side,
]);
expect(
(await searchJujutsuChanges(repo, "main")).some((c) => c.bookmarks.includes("main")),
).toBe(true);
// Revset syntax in a query is only ever text to match.
await expect(searchJujutsuChanges(repo, '") | all() | ("')).resolves.toEqual([]);
});
it("fetches the selected upstream base even with an origin and a stale change ID", async () => {
const remote = join(root, "remote.git");
execFileSync("git", ["init", "--bare", remote]);
const origin = join(root, "origin.git");
execFileSync("git", ["init", "--bare", origin]);
execFileSync("jj", ["git", "remote", "add", "origin", origin], { cwd: repo });
execFileSync("jj", ["git", "remote", "add", "upstream", remote], { cwd: repo });
execFileSync("git", ["push", "upstream", "refs/heads/main:refs/heads/main"], { cwd: repo });
execFileSync("jj", ["git", "fetch", "--remote", "upstream"], { cwd: repo });
const workspace = await createWorktreePrimitive({
cwd: repo,
paseoHome: join(root, "paseo"),
worktreeSlug: "upstream-base",
source: {
kind: "branch-off",
baseBranch: "refs/remotes/upstream/main",
branchName: "upstream-base",
},
});
const other = join(root, "other");
execFileSync("git", ["clone", "-q", "-b", "main", remote, other]);
writeFileSync(join(other, "file.txt"), "from elsewhere\n");
execFileSync("git", ["-c", "user.name=T", "-c", "user.email=t@t", "commit", "-qam", "Remote"], {
cwd: other,
});
execFileSync("git", ["push", "-q", "origin", "HEAD:main"], { cwd: other });
const remoteHead = execFileSync("git", ["rev-parse", "HEAD"], { cwd: other }).toString().trim();
await runJujutsuCheckoutAction({
cwd: workspace.worktreePath,
expectedChangeId: "stale-change-id",
action: { kind: "fetch" },
resolveForge: async () => {
throw new Error("No forge configured");
},
});
expect(
execFileSync("jj", ["log", "--no-graph", "-r", "main@upstream", "-T", "commit_id"], {
cwd: repo,
}).toString(),
).toBe(remoteHead);
});
it("updates subscribed status when a jj operation changes the description", async () => {
const service = new WorkspaceGitServiceImpl({
logger: pino({ level: "silent" }),
paseoHome: join(root, "paseo"),
});
let latest: WorkspaceGitRuntimeSnapshot | undefined;
const subscription = service.registerWorkspace({ cwd: repo }, (snapshot) => {
latest = snapshot;
});
try {
await expect
.poll(() => service.getMetrics().fileObserver.activeObservationCount, { timeout: 10_000 })
.toBeGreaterThanOrEqual(3);
execFileSync("jj", ["describe", "-m", "Updated from terminal"], { cwd: repo });
await expect
.poll(() => latest?.git.jujutsu?.description, { timeout: 10_000 })
.toBe("Updated from terminal\n");
} finally {
subscription.unsubscribe();
await service.dispose();
}
}, 15_000);
it("identifies binary files in the shared diff stream", async () => {
writeFileSync(join(repo, "binary.dat"), Buffer.from([0, 1, 2, 3]));
const comparison = await listComparison({
cwd: repo,
base: { kind: "rev", rev: "HEAD" },
head: { kind: "worktree" },
});
try {
expect(comparison.files.map((file) => file.entry)).toEqual([
{
path: "binary.dat",
oldPath: null,
change: "added",
content: "binary",
additions: 0,
deletions: 0,
body: false,
},
]);
} finally {
await comparison.close();
}
});
it("reports conflicts and renders a task diff against an explicit base", async () => {
writeFileSync(join(repo, "file.txt"), "left\n");
execFileSync("jj", ["describe", "-m", "Left"], { cwd: repo });
execFileSync("jj", ["bookmark", "create", "left"], { cwd: repo });
execFileSync("jj", ["new", "main"], { cwd: repo });
writeFileSync(join(repo, "file.txt"), "right\n");
execFileSync("jj", ["describe", "-m", "Right"], { cwd: repo });
execFileSync("jj", ["new", "left", "@"], { cwd: repo });
expect((await getJujutsuState(repo)).hasConflicts).toBe(true);
const comparison = await listComparison({
cwd: repo,
base: { kind: "rev", rev: "main" },
head: { kind: "rev", rev: "HEAD" },
checkoutBase: { compare: { mode: "base", baseRef: "main" }, paseoHome: join(root, "paseo") },
});
try {
expect(comparison.files.map((file) => file.entry.path)).toEqual(["file.txt"]);
const contents = await comparison.read(comparison.files[0]);
expect(JSON.stringify(contents)).toContain("left");
expect(JSON.stringify(contents)).toContain("right");
} finally {
await comparison.close();
}
});
it("uses the selected Jujutsu workspace for @ and config seeding", async () => {
const service = new WorkspaceGitServiceImpl({
logger: pino({ level: "silent" }),
paseoHome: join(root, "paseo"),
});
try {
const first = await createWorktreeCore(
{ cwd: repo, paseoHome: join(root, "paseo"), worktreeSlug: "first", refName: "main" },
{
github: createGitHubService(),
workspaceGitService: service,
},
);
const source = first.worktree.worktreePath;
const sourceConfig = '{"worktree":{"setup":["echo selected workspace"]}}';
writeFileSync(join(source, "file.txt"), "selected source\n");
writeFileSync(join(source, ".gitignore"), "paseo.json\n");
writeFileSync(join(source, "paseo.json"), sourceConfig);
writeFileSync(join(repo, "paseo.json"), '{"worktree":{"setup":["echo main checkout"]}}');
const second = await createWorktreeCore(
{
cwd: source,
paseoHome: join(root, "paseo"),
worktreeSlug: "second",
refName: "@",
},
{
github: createGitHubService(),
workspaceGitService: service,
},
);
expect(readFileSync(join(second.worktree.worktreePath, "file.txt"), "utf8")).toBe(
"selected source\n",
);
expect(readFileSync(join(second.worktree.worktreePath, "paseo.json"), "utf8")).toBe(
sourceConfig,
);
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("base\n");
} finally {
await service.dispose();
}
});
it("describes the current change, starts a child, and rejects requests for a stale change", async () => {
const initial = await getJujutsuState(repo);
const run = (action: import("@getpaseo/protocol/messages").JujutsuCheckoutAction) =>
runJujutsuCheckoutAction({
cwd: repo,
expectedChangeId: initial.changeId,
action,
resolveForge: async () => {
throw new Error("No forge configured");
},
});
writeFileSync(join(repo, "file.txt"), "local edit\n");
await run({ kind: "describe", description: "Describe the patch" });
expect(await getJujutsuState(repo)).toMatchObject({
changeId: initial.changeId,
description: "Describe the patch\n",
});
await run({ kind: "new", description: "Follow-up" });
const current = await getJujutsuState(repo);
expect(current.changeId).not.toBe(initial.changeId);
expect(current.description).toBe("Follow-up\n");
expect(readFileSync(join(repo, "file.txt"), "utf8")).toBe("local edit\n");
await expect(run({ kind: "describe", description: "Stale request" })).rejects.toThrow(
"has moved",
);
expect(await getJujutsuState(repo)).toEqual(current);
});
it("publishes an exact bookmark and creates a pull request from that bookmark", async () => {
const remote = join(root, "remote.git");
execFileSync("git", ["init", "--bare", remote]);
execFileSync("jj", ["git", "remote", "add", "origin", remote], { cwd: repo });
writeFileSync(join(repo, "file.txt"), "published work\n");
execFileSync("jj", ["describe", "-m", "Publish task"], { cwd: repo });
const current = await getJujutsuState(repo);
let pullRequest: import("../services/forge-service.js").CreatePullRequestOptions | undefined;
const resolveForge = async () => ({
createPullRequest: async (
input: import("../services/forge-service.js").CreatePullRequestOptions,
) => {
pullRequest = input;
return { url: "https://example.invalid/pull/1", number: 1 };
},
invalidate: () => {},
});
await runJujutsuCheckoutAction({
cwd: repo,
expectedChangeId: current.changeId,
resolveForge,
action: { kind: "publish", bookmark: "task", create: true },
});
expect(
execFileSync("git", ["rev-parse", "refs/heads/task"], {
cwd: remote,
encoding: "utf8",
}).trim(),
).toBe(current.commitId);
expect(
execFileSync("git", ["for-each-ref", "--format=%(refname)", "refs/heads"], {
cwd: remote,
encoding: "utf8",
}).trim(),
).toBe("refs/heads/task");
expect(await getCheckoutSnapshotFacts(repo)).toMatchObject({
pullRequestLookupTarget: { headRef: "task", headSha: current.commitId },
});
await expect(
runJujutsuCheckoutAction({
cwd: repo,
expectedChangeId: current.changeId,
resolveForge,
action: {
kind: "create_pull_request",
bookmark: "task",
base: "main",
title: "Publish task",
},
}),
).resolves.toBe("https://example.invalid/pull/1");
expect(pullRequest).toMatchObject({ head: "task", base: "main", title: "Publish task" });
execFileSync("jj", ["bookmark", "delete", "task"], { cwd: repo });
await expect(
runJujutsuCheckoutAction({
cwd: repo,
expectedChangeId: current.changeId,
resolveForge,
action: { kind: "publish", bookmark: "task" },
}),
).rejects.toThrow("existing, unambiguous local bookmark");
expect(
execFileSync("git", ["rev-parse", "refs/heads/task"], {
cwd: remote,
encoding: "utf8",
}).trim(),
).toBe(current.commitId);
});
it("uses Git for the selected Git worktree and seeds config from the main checkout", async () => {
const gitOnly = join(root, "git-only");
execFileSync("git", ["worktree", "add", "--detach", gitOnly, "main"], { cwd: repo });
await writePaseoWorktreeMetadata(gitOnly, { baseRefName: "main" });
const mainConfig = '{"worktree":{"setup":["echo main checkout"]}}';
writeFileSync(join(repo, "paseo.json"), mainConfig);
writeFileSync(join(gitOnly, "paseo.json"), '{"worktree":{"setup":["echo linked checkout"]}}');
const service = new WorkspaceGitServiceImpl({
logger: pino({ level: "silent" }),
paseoHome: join(root, "paseo"),
});
try {
const result = await createWorktreeCore(
{
cwd: gitOnly,
paseoHome: join(root, "paseo"),
worktreeSlug: "git-only-child",
refName: "main",
branchName: "git-child",
},
{ github: createGitHubService(), workspaceGitService: service },
);
expect(result.repoRoot).toBe(repo);
expect(result.worktree.branchName).toBe("git-child");
expect(await findJujutsuRoot(result.worktree.worktreePath)).toBeNull();
expect(readFileSync(join(result.worktree.worktreePath, "paseo.json"), "utf8")).toBe(
mainConfig,
);
} finally {
await service.dispose();
}
});
});
+177 -21
View File
@@ -1,3 +1,16 @@
import { resolveCheckoutProvider } from "./checkout-vcs.js";
import {
findJujutsuRoot,
findJujutsuCommit,
resolveJujutsuComparisonBase,
resolveJujutsuRevision,
getJujutsuDiff,
listJujutsuCommits,
assertGitMutationAllowed,
restoreJujutsuPaths,
type JujutsuState,
parseJujutsuDiff,
} from "./checkout-jj.js";
import { MAX_RELAY_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit";
import { resolve, dirname, basename } from "path";
import {
@@ -523,6 +536,7 @@ export async function checkoutResolvedBranch(
input: CheckoutResolvedBranchInput,
): Promise<CheckoutExistingBranchResult> {
const { cwd, resolution } = input;
await assertGitMutationAllowed(cwd);
switch (resolution.kind) {
case "local": {
@@ -899,6 +913,7 @@ export interface CheckoutStatus {
}
export interface CheckoutStatusGitNonPaseo {
jujutsu?: JujutsuState;
isGit: true;
repoRoot: string;
mainRepoRoot: string | null;
@@ -929,6 +944,7 @@ export interface CheckoutStatusGitNonPaseo {
}
export interface CheckoutStatusGitPaseo {
jujutsu?: JujutsuState;
isGit: true;
repoRoot: string;
mainRepoRoot: string;
@@ -995,6 +1011,8 @@ export type CheckoutSnapshotFacts =
| {
isGit: true;
worktreeRoot: string;
jujutsu?: JujutsuState;
jujutsuBaseRevision?: string;
currentBranch: string | null;
remoteUrl: string | null;
absoluteGitDir: string | null;
@@ -1300,6 +1318,8 @@ export async function renameCurrentBranch(
cwd: string,
newName: string,
): Promise<{ previousBranch: string | null; currentBranch: string | null }> {
await assertGitMutationAllowed(cwd);
const worktreeRoot = await requireGitWorktreeRoot(cwd);
const previousBranch = await getCurrentBranch(cwd);
@@ -1398,7 +1418,14 @@ export async function setCheckoutBaseBranch(input: {
if (valid.exitCode !== 0 || !(await doesGitRefExist(input.cwd, candidate))) continue;
const worktreeRoot = await getWorktreeRoot(input.cwd);
if (!worktreeRoot) throw new NotGitRepoError(input.cwd);
await setPaseoWorktreeBaseRef({ worktreeRoot, baseRef: candidate });
let jujutsuBaseCommit: string | undefined;
if (await findJujutsuRoot(worktreeRoot)) {
const revision = await resolveJujutsuRevision(worktreeRoot, candidate);
const commit = await findJujutsuCommit(worktreeRoot, revision);
if (!commit) throw new Error(`Jujutsu base not found: ${candidate}`);
jujutsuBaseCommit = commit;
}
await setPaseoWorktreeBaseRef({ worktreeRoot, baseRef: candidate, jujutsuBaseCommit });
return candidate;
}
throw new Error(`Base branch not found: ${requested}`);
@@ -1420,6 +1447,33 @@ interface BaseRefResolution {
resolvedBaseRef: string | null;
}
// The same base the checkout facts compare a jj workspace against, without the rest of the
// facts (upstream status, pull request lookup).
async function resolveJujutsuBaseForCwd(
cwd: string,
context?: CheckoutContext,
): Promise<{ resolvedBaseRef: string | null; revision: string }> {
if (context?.facts?.isGit && context.facts.jujutsuBaseRevision) {
return {
resolvedBaseRef: context.facts.resolvedBaseRef,
revision: context.facts.jujutsuBaseRevision,
};
}
const ownership = await getPaseoWorktreeForCwd(cwd, { context });
const metadata = ownership.isPaseoOwnedWorktree
? await readPaseoWorktreeMetadata(ownership.worktreeRoot)
: null;
const resolvedBaseRef =
storedBaseRefFromMetadata(metadata) ?? (await resolveBaseRef(cwd, context));
const { revision } = await resolveJujutsuComparisonBase(
cwd,
resolvedBaseRef,
metadata?.jujutsuBaseCommit,
);
return { resolvedBaseRef, revision };
}
async function resolveBaseRefForCwd(
cwd: string,
context?: CheckoutContext,
@@ -1471,6 +1525,9 @@ function resolveOperationBaseRef(input: {
// Untracked files count whatever `status.showUntrackedFiles` says: archive warns from this before
// it removes a worktree, and a file nobody added yet is still work to lose.
async function isWorkingTreeDirty(cwd: string, context?: CheckoutContext): Promise<boolean> {
const jjRoot = await findJujutsuRoot(cwd);
if (jjRoot) return (await getJujutsuDiff(jjRoot, {})).length > 0;
const { stdout } = await getRunGitCommand(context)(
["status", "--porcelain", "--untracked-files=normal"],
{
@@ -2335,6 +2392,26 @@ async function resolveFactsPullRequestLookupTarget(input: {
return target;
}
async function resolveJujutsuPullRequestTarget(
cwd: string,
change: JujutsuState,
context?: CheckoutContext,
): Promise<PullRequestStatusLookupTarget | null> {
const { stdout } = await getRunGitCommand(context)(
["for-each-ref", "--format=%(refname)%00%(objectname)", "refs/remotes/origin/"],
{ cwd, envOverlay: READ_ONLY_GIT_ENV },
);
const candidates = stdout
.trim()
.split("\n")
.flatMap((line) => {
const [ref, headSha] = line.split("\0");
const headRef = ref.slice("refs/remotes/origin/".length);
return headSha && change.bookmarks.includes(headRef) ? [{ headRef, headSha }] : [];
});
return candidates.length === 1 ? candidates[0] : null;
}
export async function getCheckoutSnapshotFacts(
cwd: string,
context?: CheckoutContext,
@@ -2349,7 +2426,15 @@ async function collectCheckoutSnapshotFacts(
cwd: string,
context: CheckoutContext,
): Promise<CheckoutSnapshotFacts> {
const provider = await resolveCheckoutProvider(cwd);
let jujutsu = await provider.readChange();
const inspected = await inspectCheckoutContext(cwd, context, { includeAbsoluteGitDir: true });
if (provider.kind === "jujutsu" && !inspected) {
throw new Error(
"Paseo requires a colocated Jujutsu checkout. Enable colocation with jj git colocation enable.",
);
}
if (!inspected) {
return { isGit: false };
}
@@ -2402,27 +2487,41 @@ async function collectCheckoutSnapshotFacts(
context,
})
: null;
let pullRequestLookupTarget = await resolveFactsPullRequestLookupTarget({
cwd,
inspected,
metadata: paseoWorktreeMetadata,
branchRemoteName,
branchMergeRef,
branchRemoteUrl,
resolvedBaseRef,
context,
});
pullRequestLookupTarget = await addHeadShaToPullRequestLookupTarget(
cwd,
pullRequestLookupTarget,
context,
);
let pullRequestLookupTarget: PullRequestStatusLookupTarget | null;
let jujutsuBaseRevision: string | undefined;
if (jujutsu) {
const base = await resolveJujutsuComparisonBase(
cwd,
resolvedBaseRef,
paseoWorktreeMetadata?.jujutsuBaseCommit,
);
jujutsuBaseRevision = base.revision;
jujutsu = { ...jujutsu, baseBookmarkMissing: base.bookmarkMissing };
pullRequestLookupTarget = await resolveJujutsuPullRequestTarget(cwd, jujutsu, context);
} else {
pullRequestLookupTarget = await resolveFactsPullRequestLookupTarget({
cwd,
inspected,
metadata: paseoWorktreeMetadata,
branchRemoteName,
branchMergeRef,
branchRemoteUrl,
resolvedBaseRef,
context,
});
pullRequestLookupTarget = await addHeadShaToPullRequestLookupTarget(
cwd,
pullRequestLookupTarget,
context,
);
}
const upstreamStatus = resolveUpstreamStatus(
await upstreamTrackingPromise,
branchRemoteName !== null && branchMergeRef !== null,
);
return {
...(jujutsu ? { jujutsu, jujutsuBaseRevision } : {}),
isGit: true,
worktreeRoot: inspected.worktreeRoot,
currentBranch: inspected.currentBranch,
@@ -2682,6 +2781,7 @@ export async function getCheckoutStatus(
if (paseoWorktree.isPaseoOwnedWorktree && baseRef) {
return {
jujutsu: facts.jujutsu,
isGit: true,
repoRoot: worktreeRoot,
mainRepoRoot: mainRepoRoot ?? worktreeRoot,
@@ -2699,6 +2799,7 @@ export async function getCheckoutStatus(
}
return {
jujutsu: facts.jujutsu,
isGit: true,
repoRoot: worktreeRoot,
mainRepoRoot:
@@ -2943,6 +3044,14 @@ export async function listCheckoutCommits({
cwd: string;
context?: CheckoutContext;
}): Promise<CheckoutCommitsResult> {
// jj checkouts have no current branch; list their changes instead.
const jujutsuRoot = await findJujutsuRoot(cwd);
if (jujutsuRoot) {
const { resolvedBaseRef, revision } = await resolveJujutsuBaseForCwd(jujutsuRoot, context);
const commits = await listJujutsuCommits(jujutsuRoot, revision, CHECKOUT_BASE_COMMIT_LIMIT);
return { baseRef: resolvedBaseRef ? branchNameFromRef(resolvedBaseRef) : null, commits };
}
const currentBranch = await getCurrentBranch(cwd);
if (!currentBranch) {
return { baseRef: null, commits: [] };
@@ -3336,6 +3445,18 @@ export async function getCheckoutShortstat(
context?: CheckoutContext,
options?: CheckoutReadCacheOptions,
): Promise<CheckoutShortstat | null> {
const jjRoot = await findJujutsuRoot(cwd);
if (jjRoot) {
const files = parseJujutsuDiff(await getJujutsuDiff(jjRoot, {}));
return files.reduce(
(total, file) => ({
additions: total.additions + file.additions,
deletions: total.deletions + file.deletions,
}),
{ additions: 0, deletions: 0 },
);
}
return getOrLoadCheckoutShortstat(cwd, context, options);
}
@@ -3946,6 +4067,16 @@ export async function getCheckoutDiff(
compare: CheckoutDiffCompare,
context?: CheckoutContext,
signal?: AbortSignal,
): Promise<CheckoutDiffResult> {
const provider = await resolveCheckoutProvider(cwd);
return provider.readDiff(compare, context, signal);
}
export async function getGitCheckoutDiff(
cwd: string,
compare: CheckoutDiffCompare,
context?: CheckoutContext,
signal?: AbortSignal,
): Promise<CheckoutDiffResult> {
cwd = await requireGitWorktreeRoot(cwd);
@@ -4087,6 +4218,8 @@ export async function commitChanges(
cwd: string,
options: { message: string; addAll?: boolean },
): Promise<void> {
await assertGitMutationAllowed(cwd);
await requireGitRepo(cwd);
if (options.addAll ?? true) {
await runGitCommand(["add", "-A"], { cwd, timeout: 120_000 });
@@ -4102,6 +4235,12 @@ export async function commitAll(cwd: string, message: string): Promise<void> {
}
export async function discardChanges(cwd: string, pathspecs: string[]): Promise<void> {
const jujutsuRoot = await findJujutsuRoot(cwd);
if (jujutsuRoot) {
await restoreJujutsuPaths(jujutsuRoot, pathspecs);
return;
}
const worktreeRoot = await requireGitWorktreeRoot(cwd);
if (pathspecs.length === 0) {
return;
@@ -4232,6 +4371,8 @@ export async function mergeToBase(
options: MergeToBaseOptions = {},
context?: CheckoutContext,
): Promise<string> {
await assertGitMutationAllowed(cwd);
await requireGitRepo(cwd);
const currentBranch = await getCurrentBranch(cwd);
const { storedBaseRef, resolvedBaseRef } = await resolveBaseRefForCwd(cwd, context);
@@ -4304,6 +4445,8 @@ export async function mergeFromBase(
options: MergeFromBaseOptions = {},
context?: CheckoutContext,
): Promise<void> {
await assertGitMutationAllowed(cwd);
await requireGitRepo(cwd);
const currentBranch = await getCurrentBranch(cwd);
if (!currentBranch || currentBranch === "HEAD") {
@@ -4411,6 +4554,8 @@ async function detectAndThrowMergeFromBaseConflict(
}
export async function pullCurrentBranch(cwd: string, forgeService?: ForgeService): Promise<void> {
await assertGitMutationAllowed(cwd);
await requireGitRepo(cwd);
const currentBranch = await getCurrentBranch(cwd);
if (!currentBranch || currentBranch === "HEAD") {
@@ -4442,6 +4587,8 @@ export async function pushCurrentBranch(
forgeService?: ForgeService,
context?: CheckoutContext,
): Promise<void> {
await assertGitMutationAllowed(cwd);
await requireGitRepo(cwd);
const currentBranch = await getCurrentBranch(cwd);
if (!currentBranch || currentBranch === "HEAD") {
@@ -4809,6 +4956,8 @@ export async function createPullRequest(
forgeService: ForgeService = createGitHubService(),
context?: CheckoutContext,
): Promise<{ url: string; number: number }> {
await assertGitMutationAllowed(cwd);
await requireGitRepo(cwd);
const head = options.head ?? (await getCurrentBranch(cwd));
@@ -4851,10 +5000,17 @@ export async function getPullRequestStatus(
options?: CheckoutReadCacheOptions,
context?: CheckoutContext,
): Promise<PullRequestStatusResult> {
const [headSha, head] = await Promise.all([
getCurrentHeadSha(cwd, context),
context?.facts?.isGit ? context.facts.currentBranch : getCurrentBranch(cwd, context),
]);
const facts = context?.facts;
const jujutsu = facts?.isGit && facts.jujutsu;
const [headSha, head] = jujutsu
? [
facts.pullRequestLookupTarget?.headSha ?? null,
facts.pullRequestLookupTarget?.headRef ?? null,
]
: await Promise.all([
getCurrentHeadSha(cwd, context),
facts?.isGit ? facts.currentBranch : getCurrentBranch(cwd, context),
]);
const cacheKey = getPullRequestStatusCacheKey(cwd, head, headSha);
if (!options?.force) {
const cached = pullRequestStatusCache.get(cacheKey);
@@ -4950,7 +5106,7 @@ function getUnavailablePullRequestStatus(
}
if (
facts?.isGit === true &&
facts.paseoWorktree.isPaseoOwnedWorktree &&
(facts.paseoWorktree.isPaseoOwnedWorktree || facts.jujutsu) &&
facts.pullRequestLookupTarget === null
) {
return buildPullRequestStatusResult(null, "authenticated");
+621
View File
@@ -0,0 +1,621 @@
import { runGitCommand } from "./run-git-command.js";
import { parseDiff, type ParsedDiffFile } from "../server/utils/diff-highlighter.js";
import { unquoteGitPath } from "./git-quoted-path.js";
import { stat, readFile } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import pLimit from "p-limit";
import { z } from "zod";
import { execCommand } from "./spawn.js";
const commands = pLimit(2);
export interface JujutsuState {
changeId: string;
commitId: string;
description: string;
bookmarks: string[];
hasConflicts: boolean;
nearestBookmark: string | null;
baseBookmarkMissing?: boolean;
hasRemotes: boolean;
// Another workspace rewrote @ and this one's files no longer match it.
stale: boolean;
}
async function exists(path: string): Promise<boolean> {
try {
await stat(path);
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
throw error;
}
}
// Stop at the nearest checkout boundary, including a nested Git repository.
export async function findJujutsuRoot(cwd: string): Promise<string | null> {
let current = resolve(cwd);
while (true) {
if (await exists(join(current, ".jj"))) return current;
if (await exists(join(current, ".git"))) return null;
const parent = dirname(current);
if (parent === current) return null;
current = parent;
}
}
interface JujutsuCommandOptions {
snapshot?: boolean;
atOperation?: string;
write?: boolean;
signal?: AbortSignal;
timeout?: number;
nonInteractive?: boolean;
}
export async function runJujutsu(
cwd: string,
args: string[],
options?: JujutsuCommandOptions,
): Promise<string> {
return (await runJujutsuCommand(cwd, args, options)).stdout;
}
const STALE_WORKING_COPY = "The working copy is stale";
export function isJujutsuStaleError(error: unknown): boolean {
return error instanceof Error && error.message.includes(STALE_WORKING_COPY);
}
async function runJujutsuCommand(cwd: string, args: string[], options?: JujutsuCommandOptions) {
try {
return await execJujutsu(cwd, args, options);
} catch (error) {
// A stale working copy can't be snapshotted until `jj workspace update-stale`, so read
// the repository's view of it instead of failing.
if (!options?.snapshot || !isJujutsuStaleError(error)) throw error;
return execJujutsu(cwd, args, { ...options, snapshot: false });
}
}
function execJujutsu(cwd: string, args: string[], options?: JujutsuCommandOptions) {
let mode: string[] = [];
if (options?.atOperation) mode = ["--at-operation", options.atOperation];
else if (options?.snapshot) mode = ["--no-integrate-operation"];
else if (!options?.write) mode = ["--ignore-working-copy"];
return commands(() =>
execCommand("jj", ["--no-pager", "--color=never", ...mode, ...args], {
cwd,
signal: options?.signal,
timeout: options?.timeout ?? 30_000,
maxBuffer: 20 * 1024 * 1024,
...(options?.nonInteractive ? { envOverlay: { GIT_TERMINAL_PROMPT: "0" } } : {}),
}),
);
}
export async function getJujutsuState(cwd: string): Promise<JujutsuState> {
const [output, nearest, remotes, stale] = await Promise.all([
readJujutsuChange(cwd),
runJujutsu(cwd, [
"log",
"--no-graph",
"-r",
"heads(::@ & bookmarks())",
"-T",
'json(local_bookmarks.map(|b| b.name())) ++ "\\n"',
]),
exists(join(cwd, ".git")).then((colocated) => (colocated ? listJujutsuGitRemotes(cwd) : [])),
isJujutsuWorkingCopyStale(cwd),
]);
const nearestBookmark =
nearest
.trimEnd()
.split("\n")
.filter(Boolean)
.flatMap((line) => z.array(z.string()).parse(JSON.parse(line)))[0] ?? null;
const [changeId, commitId, description, bookmarks, hasConflicts] = output;
return {
changeId,
commitId,
description,
bookmarks,
hasConflicts,
nearestBookmark,
hasRemotes: remotes.length > 0,
stale,
};
}
// Only a command that snapshots the working copy notices that it is stale.
async function isJujutsuWorkingCopyStale(cwd: string): Promise<boolean> {
try {
await execJujutsu(cwd, ["log", "--no-graph", "-r", "@", "-T", '""'], { snapshot: true });
return false;
} catch (error) {
if (isJujutsuStaleError(error)) return true;
throw error;
}
}
// Updating moves the files on disk to the new @. Edits jj hadn't snapshotted yet are kept in
// a separate change rather than lost.
export async function updateStaleJujutsuWorkspace(cwd: string): Promise<void> {
await runJujutsu(cwd, ["workspace", "update-stale"], { write: true, timeout: 120_000 });
}
async function readJujutsuChange(cwd: string) {
const output = await runJujutsu(cwd, [
"log",
"--no-graph",
"-r",
"@",
"-T",
'json(change_id) ++ "\\n" ++ json(commit_id) ++ "\\n" ++ json(description) ++ "\\n" ++ json(local_bookmarks.map(|b| b.name())) ++ "\\n" ++ json(conflict)',
]);
return z
.tuple([z.string().min(1), z.string().min(1), z.string(), z.array(z.string()), z.boolean()])
.parse(
output
.trimEnd()
.split("\n")
.map((line) => JSON.parse(line)),
);
}
export async function getJujutsuDiff(
cwd: string,
options: { baseRef?: string; ignoreWhitespace?: boolean; signal?: AbortSignal },
): Promise<string> {
const baseRef = options.baseRef ? await resolveJujutsuRevision(cwd, options.baseRef) : undefined;
// Snapshot into an unintegrated operation: include disk edits without moving @,
// importing/exporting Git refs, or updating another agent's working copy. Comparing
// from the fork point keeps a base that has moved on (e.g. after a fetch) from
// showing its newer changes as reverted here.
return runJujutsu(
cwd,
[
"diff",
"--git",
...(baseRef ? ["--from", `fork_point((${baseRef}) | @)`, "--to", "@"] : ["-r", "@"]),
...(options.ignoreWhitespace ? ["--ignore-all-space"] : []),
],
{ snapshot: true, signal: options.signal },
);
}
// Discard puts files back as they are in the working-copy change's parent, as Git's discard
// restores them from HEAD.
export async function restoreJujutsuPaths(cwd: string, paths: string[]): Promise<void> {
if (paths.length === 0) return;
const filesets = paths.map((path) => `root-file:${JSON.stringify(path)}`);
await runJujutsu(cwd, ["restore", "--", ...filesets], { write: true, timeout: 60_000 });
}
export async function assertGitMutationAllowed(cwd: string): Promise<void> {
if (await findJujutsuRoot(cwd)) {
throw new Error(
"This checkout uses Jujutsu. Use jj to change revisions, describe changes, or publish bookmarks.",
);
}
}
export async function createJujutsuWorkspace(options: {
cwd: string;
path: string;
name: string;
base: string;
}): Promise<void> {
await runJujutsu(
options.cwd,
[
"workspace",
"add",
"--colocate",
"--name",
options.name,
"-r",
options.base,
"--",
options.path,
],
{ write: true, timeout: 120_000 },
);
}
export async function getJujutsuWorkspaceName(cwd: string, path: string): Promise<string | null> {
const output = await runJujutsu(cwd, [
"workspace",
"list",
"-T",
'json(name) ++ "\\n" ++ json(root) ++ "\\n"',
]);
const fields = output.trimEnd().split("\n");
for (let i = 0; i + 1 < fields.length; i += 2) {
const name = z.string().parse(JSON.parse(fields[i]));
const root = z
.string()
.nullable()
.parse(JSON.parse(fields[i + 1]));
if (root && resolve(root) === resolve(path)) return name;
}
return null;
}
export async function removeJujutsuWorkspace(cwd: string, path: string): Promise<boolean> {
const name = await getJujutsuWorkspaceName(cwd, path);
if (!name || resolve(cwd) === resolve(path)) return false;
await runJujutsu(dirname(path), ["-R", path, "workspace", "remove", "--", name], {
write: true,
timeout: 120_000,
});
return true;
}
export async function clearMissingJujutsuWorkspace(cwd: string, path: string): Promise<void> {
if (await exists(path)) throw new Error(`Cannot restore over an existing directory: ${path}`);
const name = await getJujutsuWorkspaceName(cwd, path);
if (name) await runJujutsu(cwd, ["workspace", "forget", "--", name]);
const { stdout } = await runGitCommand(["worktree", "list", "--porcelain", "-z"], { cwd });
if (
stdout
.split("\0")
.some((field) => field.startsWith("worktree ") && resolve(field.slice(9)) === resolve(path))
) {
if (await exists(path)) throw new Error(`Cannot restore over an existing directory: ${path}`);
await runGitCommand(["worktree", "remove", "--force", "--", path], { cwd });
}
}
export async function snapshotJujutsuWorkingCopy(cwd: string): Promise<string> {
const commit = (
await runJujutsu(cwd, ["log", "--no-graph", "-r", "@", "-T", "commit_id"], { write: true })
).trim();
if (!/^[a-f0-9]{40}$/.test(commit))
throw new Error("Jujutsu returned an invalid recovery commit");
return commit;
}
export async function saveJujutsuRecoveryCommit(cwd: string): Promise<string> {
// Archive integrates the snapshot so other workspaces can resolve it for restore.
const commit = await snapshotJujutsuWorkingCopy(cwd);
await runGitCommand(["update-ref", `refs/paseo/kept-commits/${commit}`, commit], { cwd });
return commit;
}
export async function getJujutsuOperationHeads(cwd: string): Promise<string | null> {
const root = await findJujutsuRoot(cwd);
if (!root) return null;
const repository = join(root, ".jj", "repo");
const info = await stat(repository);
if (info.isDirectory()) return join(repository, "op_heads", "heads");
if (info.size > 64 * 1024) throw new Error("Jujutsu repository pointer is too large");
const pointer = (await readFile(repository, "utf8")).trim();
return join(resolve(root, ".jj", pointer), "op_heads", "heads");
}
async function listJujutsuGitRemotes(cwd: string): Promise<string[]> {
const { stdout } = await runGitCommand(["remote"], { cwd });
return stdout.split("\n").filter(Boolean);
}
function findTrackingRemote(remotes: string[], trackingRef: string): string | null {
return (
remotes
.filter((remote) => trackingRef.startsWith(`${remote}/`))
.sort((a, b) => b.length - a.length)[0] ?? null
);
}
export async function findJujutsuRemoteForBase(cwd: string, base: string): Promise<string | null> {
const remotePrefix = "refs/remotes/";
if (base.startsWith("refs/") && !base.startsWith(remotePrefix)) return null;
const remotes = await listJujutsuGitRemotes(cwd);
if (base.startsWith(remotePrefix))
return findTrackingRemote(remotes, base.slice(remotePrefix.length));
const separator = base.lastIndexOf("@");
const nativeRemote = separator > 0 ? base.slice(separator + 1) : null;
if (nativeRemote && remotes.includes(nativeRemote)) return nativeRemote;
return findTrackingRemote(remotes, base);
}
// Convert Git-style remote refs at the boundary. Native jj revsets pass through unchanged.
export async function resolveJujutsuRevision(cwd: string, revision: string): Promise<string> {
const resolved = await findJujutsuRevision(cwd, revision);
if (!resolved) throw new Error(`Jujutsu revision not found: ${revision}`);
return resolved;
}
async function findJujutsuRevision(cwd: string, revision: string): Promise<string | null> {
let ref = revision.startsWith("refs/") ? revision : null;
if (
!ref &&
revision.includes("/") &&
findTrackingRemote(await listJujutsuGitRemotes(cwd), revision)
) {
ref = `refs/remotes/${revision}`;
}
if (!ref) return revision;
const result = await runGitCommand(
["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`],
{ cwd, acceptExitCodes: [0, 1] },
);
return result.exitCode === 0 ? result.stdout.trim() : null;
}
export async function findJujutsuCommit(cwd: string, revision: string): Promise<string | null> {
const output = await runJujutsu(cwd, [
"log",
"--no-graph",
"-r",
`present(${revision})`,
"--limit",
"2",
"-T",
'commit_id ++ "\\n"',
]);
const commits = output.trim().split("\n").filter(Boolean);
return commits.length === 1 ? commits[0] : null;
}
export async function resolveJujutsuComparisonBase(
cwd: string,
baseRef: string | null,
savedCommit?: string,
): Promise<{ revision: string; bookmarkMissing: boolean }> {
if (!baseRef) return { revision: "trunk()", bookmarkMissing: false };
const revision = await findJujutsuRevision(cwd, baseRef);
const commit = revision ? await findJujutsuCommit(cwd, revision) : null;
if (commit) return { revision: commit, bookmarkMissing: false };
const fallback = savedCommit ? await findJujutsuCommit(cwd, savedCommit) : null;
return { revision: fallback ?? "trunk()", bookmarkMissing: true };
}
export function parseJujutsuDiff(diff: string): Array<ParsedDiffFile & { oldPath: string | null }> {
const files: Array<ParsedDiffFile & { oldPath: string | null }> = [];
for (const section of diff.split(/(?=^diff --git )/m)) {
const rename = section.match(/^rename from (.*)$/m);
for (const file of parseDiff(section)) {
files.push({
...file,
oldPath: rename ? unquoteGitPath(rename[1]) : null,
...(/^Binary files .* differ$/m.test(section) ? { status: "binary" as const } : {}),
});
}
}
return files;
}
export interface JujutsuCommitRecord {
sha: string;
shortSha: string;
subject: string;
authorName: string;
authorDate: string;
isOnRemote: boolean;
isOnBase: boolean;
files: Array<{
path: string;
additions: number;
deletions: number;
status: "added" | "modified" | "deleted" | "renamed";
}>;
jujutsu: {
changeId: string;
bookmarks: string[];
isWorkingCopy: boolean;
isEmpty: boolean;
hasConflicts: boolean;
operationId?: string;
};
}
// One JSON array per change, so descriptions and paths need no further escaping.
const COMMIT_FIELDS = [
"json(commit_id)",
"json(change_id.short())",
"json(change_id)",
"json(description.first_line())",
"json(author.name())",
"json(author.timestamp())",
"json(local_bookmarks.map(|b| b.name()))",
"current_working_copy",
"empty",
"conflict",
'"[" ++ diff.stat().files().map(|e| "[" ++ json(e.path().display()) ++ "," ++ json(e.status()) ++ "," ++ e.lines_added() ++ "," ++ e.lines_removed() ++ "]").join(",") ++ "]"',
];
const COMMIT_TEMPLATE = `"[" ++ ${COMMIT_FIELDS.join(' ++ "," ++ ')} ++ "]\\n"`;
const CommitRowSchema = z.tuple([
z.string(),
z.string(),
z.string(),
z.string(),
z.string(),
z.string(),
z.array(z.string()),
z.boolean(),
z.boolean(),
z.boolean(),
z.array(z.tuple([z.string(), z.string(), z.number(), z.number()])),
]);
function fileStatus(status: string): JujutsuCommitRecord["files"][number]["status"] {
if (status === "removed") return "deleted";
if (status === "renamed") return "renamed";
if (status === "added" || status === "copied") return "added";
return "modified";
}
async function readCommits(cwd: string, revset: string, limit?: number) {
const { stdout, stderr } = await runJujutsuCommand(
cwd,
[
"log",
"--no-graph",
"-r",
revset,
...(limit ? ["--limit", String(limit)] : []),
"-T",
COMMIT_TEMPLATE,
],
{ snapshot: true },
);
const rows = stdout
.split("\n")
.filter(Boolean)
.map((line) => CommitRowSchema.parse(JSON.parse(line)));
return { rows, operationId: parseUncommittedOperationId(stderr) };
}
// A snapshot and a Git import each leave an unintegrated operation, the import on top of the
// snapshot. The last one printed is the one that can see every commit the command read.
function parseUncommittedOperationId(stderr: string): string | undefined {
const matches = stderr.matchAll(
/^(?:Snapshot o|O)peration left uncommitted because --no-integrate-operation was requested: ([0-9a-f]+)\r?$/gm,
);
return [...matches].at(-1)?.[1];
}
/**
* The jj counterpart of the Changes pane's commit list: this workspace's changes since the
* base (newest first, including the working copy), then the base's recent history.
*/
export async function listJujutsuCommits(
cwd: string,
baseRevision: string,
baseLimit: number,
): Promise<JujutsuCommitRecord[]> {
const forkPoint = `fork_point(${baseRevision} | @)`;
const task = `${forkPoint}..@`;
const history = `ancestors(${forkPoint}, ${baseLimit})`;
const [taskRows, historyRows, pushed] = await Promise.all([
readCommits(cwd, task),
readCommits(cwd, history, baseLimit),
runJujutsu(cwd, [
"log",
"--no-graph",
"-r",
`(${task} | ${history}) & ::remote_bookmarks()`,
"-T",
'commit_id ++ "\\n"',
]),
]);
const onRemote = new Set(pushed.split("\n").filter(Boolean));
const toRecord = (
row: z.infer<typeof CommitRowSchema>,
isOnBase: boolean,
operationId?: string,
) => {
const [sha, shortChange, changeId, subject, authorName, authorDate, bookmarks] = row;
const [, , , , , , , isWorkingCopy, isEmpty, hasConflicts, files] = row;
return {
sha,
shortSha: shortChange,
subject,
authorName,
authorDate,
isOnRemote: onRemote.has(sha),
isOnBase,
files: files.map(([path, status, additions, deletions]) => ({
path,
additions,
deletions,
status: fileStatus(status),
})),
jujutsu: { changeId, bookmarks, isWorkingCopy, isEmpty, hasConflicts, operationId },
};
};
return [
...taskRows.rows.map((row) => toRecord(row, false, taskRows.operationId)),
...historyRows.rows.map((row) => toRecord(row, true, historyRows.operationId)),
];
}
export interface JujutsuChangeSummary {
changeId: string;
commitId: string;
description: string;
bookmarks: string[];
workingCopies: string[];
isEmpty: boolean;
authorDate: string;
}
const SEARCH_TEMPLATE = `"[" ++ ${[
"json(change_id)",
"json(commit_id)",
"json(description.first_line())",
"json(local_bookmarks.map(|b| b.name()))",
"json(self.working_copies().map(|w| w.name()))",
"empty",
"json(author.timestamp())",
].join(' ++ "," ++ ')} ++ "]\\n"`;
const SearchRowSchema = z.tuple([
z.string(),
z.string(),
z.string(),
z.array(z.string()),
z.array(z.string()),
z.boolean(),
z.string(),
]);
/**
* Changes to start new work on, across the repository rather than this workspace's line:
* everything still mutable (every workspace's work and side branches), bookmarks, and recent
* trunk history. A query matches descriptions, bookmark names, and change or commit ID prefixes.
*/
export async function searchJujutsuChanges(
cwd: string,
query: string,
limit = 50,
): Promise<JujutsuChangeSummary[]> {
const scope = "(mutable() | bookmarks() | remote_bookmarks() | ancestors(trunk(), 20)) ~ root()";
// Build the filter from string literals only; the query never becomes revset syntax.
const text = [...query]
.filter((char) => char >= " " && char !== "\u007f")
.join("")
.trim();
let revset = scope;
if (text) {
const literal = JSON.stringify(text);
const terms = [`description(substring-i:${literal})`, `bookmarks(substring:${literal})`];
if (/^[k-z]+$/.test(text)) terms.push(`change_id(${text})`);
if (/^[0-9a-f]+$/.test(text)) terms.push(`commit_id(${text})`);
revset = `(${scope}) & (${terms.join(" | ")})`;
}
const output = await runJujutsu(cwd, [
"log",
"--no-graph",
"-r",
revset,
"--limit",
String(limit),
"-T",
SEARCH_TEMPLATE,
]);
return output
.split("\n")
.filter(Boolean)
.map((line) => {
const [changeId, commitId, description, bookmarks, workingCopies, isEmpty, authorDate] =
SearchRowSchema.parse(JSON.parse(line));
return { changeId, commitId, description, bookmarks, workingCopies, isEmpty, authorDate };
});
}
+100
View File
@@ -0,0 +1,100 @@
import type { CheckoutStatusResponse } from "@getpaseo/protocol/messages";
import {
getCheckoutSnapshotFacts,
getGitCheckoutDiff,
TOTAL_DIFF_MAX_BYTES,
type CheckoutContext,
type CheckoutDiffCompare,
type CheckoutDiffResult,
} from "./checkout-git.js";
import {
findJujutsuRoot,
getJujutsuDiff,
getJujutsuState,
parseJujutsuDiff,
type JujutsuState,
} from "./checkout-jj.js";
type CheckoutVcs = NonNullable<CheckoutStatusResponse["payload"]["vcs"]>;
type ReadDiff = (
compare: CheckoutDiffCompare,
context?: CheckoutContext,
signal?: AbortSignal,
) => Promise<CheckoutDiffResult>;
interface CheckoutProvider {
kind: "git" | "jujutsu";
root: string;
readDiff: ReadDiff;
readChange(): Promise<JujutsuState | undefined>;
}
export function describeCheckoutVcs(
kind: CheckoutVcs["kind"],
options?: { hasRemote: boolean; hasForge: boolean; hasFetchRemote?: boolean },
): CheckoutVcs {
return {
kind,
capabilities: {
isolatedWorkspace: kind !== "none",
gitMutations: kind === "git",
...(kind === "jujutsu"
? {
describe: true,
newChange: true,
publishBookmark: options?.hasRemote ?? false,
fetch: options?.hasFetchRemote ?? options?.hasRemote ?? false,
createPullRequest: options?.hasForge ?? false,
}
: {}),
},
};
}
export async function resolveCheckoutProvider(cwd: string): Promise<CheckoutProvider> {
const root = await findJujutsuRoot(cwd);
if (root) {
return {
kind: "jujutsu",
root,
readDiff: (compare, context, signal) => readJujutsuDiff(root, compare, context, signal),
readChange: () => getJujutsuState(root),
};
}
// The Git implementation also probes whether this is an ordinary directory.
return {
kind: "git",
root: cwd,
readDiff: (compare, context, signal) => getGitCheckoutDiff(cwd, compare, context, signal),
readChange: async () => undefined,
};
}
async function readJujutsuDiff(
root: string,
compare: CheckoutDiffCompare,
context?: CheckoutContext,
signal?: AbortSignal,
): Promise<CheckoutDiffResult> {
let baseRef: string | undefined;
if (compare.mode !== "uncommitted") {
const facts = await getCheckoutSnapshotFacts(root, context);
if (facts.isGit) {
baseRef =
!compare.baseRef || compare.baseRef === facts.resolvedBaseRef
? facts.jujutsuBaseRevision
: compare.baseRef;
}
}
const diff = await getJujutsuDiff(root, {
baseRef,
ignoreWhitespace: compare.ignoreWhitespace,
signal,
});
if (Buffer.byteLength(diff, "utf8") > TOTAL_DIFF_MAX_BYTES) {
return { diff: "", structured: [], diffTooLarge: true };
}
return { diff, ...(compare.includeStructured ? { structured: parseJujutsuDiff(diff) } : {}) };
}
@@ -0,0 +1,168 @@
import type { JujutsuCheckoutAction } from "@getpaseo/protocol/messages";
import type { ForgeService } from "../services/forge-service.js";
import { getCheckoutSnapshotFacts } from "./checkout-git.js";
import { runGitCommand } from "./run-git-command.js";
import {
findJujutsuCommit,
findJujutsuRemoteForBase,
getJujutsuOperationHeads,
getJujutsuState,
resolveJujutsuRevision,
runJujutsu,
updateStaleJujutsuWorkspace,
} from "./checkout-jj.js";
const pendingActions = new Map<string, Promise<unknown>>();
export async function runJujutsuCheckoutAction(options: {
cwd: string;
expectedChangeId: string;
action: JujutsuCheckoutAction;
resolveForge: () => Promise<Pick<ForgeService, "createPullRequest" | "invalidate">>;
}): Promise<string | null> {
const { cwd, expectedChangeId, action } = options;
const repository = await getJujutsuOperationHeads(cwd);
if (!repository) throw new Error("This checkout does not use Jujutsu.");
const operation = (pendingActions.get(repository) ?? Promise.resolve())
.catch(() => undefined)
.then(async () => {
if (action.kind === "fetch") {
const remote = action.remote ?? (await resolveFetchRemote(cwd));
await runJujutsu(
cwd,
["git", "fetch", ...(remote ? ["--remote", `exact:${remote}`] : [])],
{
write: true,
timeout: 120_000,
nonInteractive: true,
},
);
return null;
}
// The working-copy change has moved by definition, so don't compare it.
if (action.kind === "update_stale") {
await updateStaleJujutsuWorkspace(cwd);
return null;
}
const current = await getJujutsuState(cwd);
if (current.changeId !== expectedChangeId) {
throw new Error("The working-copy change has moved. Refresh and try again.");
}
switch (action.kind) {
case "describe":
await runJujutsu(cwd, ["describe", "-r", expectedChangeId, "-m", action.description], {
write: true,
});
return null;
case "new": {
const parent = action.parent ? await resolveSingleRevision(cwd, action.parent) : "@";
await runJujutsu(
cwd,
["new", parent, ...(action.description ? ["-m", action.description] : [])],
{ write: true },
);
return null;
}
case "publish":
await publishBookmark(
cwd,
action.bookmark,
action.remote ?? "origin",
action.create ?? false,
);
return null;
case "create_pull_request":
return createJujutsuPullRequest(cwd, action, await options.resolveForge());
default:
throw new Error("Unsupported Jujutsu checkout action");
}
});
pendingActions.set(repository, operation);
try {
return await operation;
} finally {
if (pendingActions.get(repository) === operation) pendingActions.delete(repository);
}
}
async function resolveFetchRemote(cwd: string): Promise<string | null> {
const facts = await getCheckoutSnapshotFacts(cwd);
if (!facts.isGit || !facts.resolvedBaseRef) return null;
return findJujutsuRemoteForBase(cwd, facts.resolvedBaseRef);
}
async function resolveSingleRevision(cwd: string, name: string): Promise<string> {
const revision = await resolveJujutsuRevision(cwd, name);
const commit = await findJujutsuCommit(cwd, revision);
if (!commit) throw new Error(`Choose one Jujutsu change: ${name}`);
return commit;
}
async function verifyBranchName(cwd: string, name: string): Promise<void> {
await runGitCommand(["check-ref-format", `refs/heads/${name}`], { cwd });
}
async function publishBookmark(
cwd: string,
bookmark: string,
remote: string,
create: boolean,
): Promise<void> {
await verifyBranchName(cwd, bookmark);
if (create) {
const current = await getJujutsuState(cwd);
if (!current.bookmarks.includes(bookmark)) {
// Create refuses to move a bookmark that already points to another change.
await runJujutsu(cwd, ["bookmark", "create", "-r", "@", "--", bookmark], { write: true });
}
}
const localCommit = await runJujutsu(cwd, [
"log",
"--no-graph",
"-r",
`bookmarks(exact:${JSON.stringify(bookmark)})`,
"-T",
'commit_id ++ "\\n"',
]);
if (localCommit.trim().split("\n").length !== 1 || !localCommit.trim()) {
throw new Error(`Choose an existing, unambiguous local bookmark: ${bookmark}`);
}
await runJujutsu(cwd, ["git", "push", "--remote", remote, "--bookmark", `exact:${bookmark}`], {
write: true,
timeout: 120_000,
nonInteractive: true,
});
}
async function createJujutsuPullRequest(
cwd: string,
action: Extract<JujutsuCheckoutAction, { kind: "create_pull_request" }>,
forge: Pick<ForgeService, "createPullRequest" | "invalidate">,
): Promise<string> {
if (action.bookmark === action.base) {
throw new Error("Choose different bookmarks for the head and base.");
}
await verifyBranchName(cwd, action.base);
await publishBookmark(cwd, action.bookmark, "origin", false);
try {
const result = await forge.createPullRequest({
cwd,
head: action.bookmark,
base: action.base,
title: action.title,
body: action.body,
});
return result.url;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Bookmark published to origin. Could not create the pull request: ${message}`, {
cause: error,
});
} finally {
forge.invalidate({ cwd });
}
}
@@ -28,6 +28,10 @@ const PaseoWorktreeMetadataV1Schema = z.object({
version: z.literal(1),
baseRefName: z.string().min(1),
baseRef: z.string().min(1).optional(),
jujutsuBaseCommit: z
.string()
.regex(/^[a-f0-9]{40}$/)
.optional(),
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
worktreeManagerPluginId: z.string().min(1).optional(),
untrustedSource: UntrustedWorktreeSourceSchema.optional(),
@@ -37,6 +41,10 @@ const PaseoWorktreeMetadataV2Schema = z.object({
version: z.literal(2),
baseRefName: z.string().min(1),
baseRef: z.string().min(1).optional(),
jujutsuBaseCommit: z
.string()
.regex(/^[a-f0-9]{40}$/)
.optional(),
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
worktreeManagerPluginId: z.string().min(1).optional(),
untrustedSource: UntrustedWorktreeSourceSchema.optional(),
@@ -254,6 +262,7 @@ export async function writePaseoWorktreeMetadata(
options: {
baseRefName: string;
baseRef?: string;
jujutsuBaseCommit?: string;
changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint;
worktreeManagerPluginId?: string;
untrustedSource?: PaseoWorktreeUntrustedSource;
@@ -271,6 +280,7 @@ export async function writePaseoWorktreeMetadata(
version: 1,
baseRefName,
...(baseRef ? { baseRef } : {}),
jujutsuBaseCommit: options.jujutsuBaseCommit,
...(options.changeRequestLookupTarget
? { changeRequestLookupTarget: options.changeRequestLookupTarget }
: {}),
@@ -315,6 +325,7 @@ export async function setPaseoWorktreeUntrustedSource(
export async function setPaseoWorktreeBaseRef(input: {
worktreeRoot: string;
baseRef: string;
jujutsuBaseCommit?: string;
}): Promise<void> {
return mutateMetadata(input.worktreeRoot, async (root) => {
const current = await readMetadataFile(root);
@@ -323,6 +334,7 @@ export async function setPaseoWorktreeBaseRef(input: {
...current,
baseRefName: branchNameFromRef(input.baseRef),
baseRef: input.baseRef,
jujutsuBaseCommit: input.jujutsuBaseCommit,
});
});
}
+154 -23
View File
@@ -1,3 +1,12 @@
import {
findJujutsuRoot,
createJujutsuWorkspace,
runJujutsu,
resolveJujutsuRevision,
clearMissingJujutsuWorkspace,
removeJujutsuWorkspace,
snapshotJujutsuWorkingCopy,
} from "./checkout-jj.js";
import { promisify } from "util";
import { constants as fsConstants, type Dirent, realpath } from "fs";
import { copyFile, mkdir, readdir, rm, stat } from "fs/promises";
@@ -273,6 +282,7 @@ export type WorktreeSource =
| { kind: "checkout-branch"; branchName: string }
| { kind: "restore"; branchName: string; baseRef: string | null }
| { kind: "restore-commit"; commit: string; baseRef: string }
| { kind: "restore-jujutsu"; commit: string; baseRef: string | null; baseCommit?: string }
| { kind: "restore-from-base"; baseRef: string; branchName: string }
| {
kind: "checkout-change-request";
@@ -307,6 +317,7 @@ export interface PreparedWorktreeBranchOff {
export interface CreateWorktreeOptions {
cwd: string;
configSourceCwd?: string;
worktreeSlug: string;
source: WorktreeSource;
preparedBranchOff?: PreparedWorktreeBranchOff;
@@ -1475,6 +1486,7 @@ export interface DeletePaseoWorktreeOptions {
removeReason?: "archive" | "rollback";
untrusted?: boolean;
signal?: AbortSignal;
jujutsuRecoveryCommit?: string;
}
// Project scoping for delete: a proof for some other repo's worktree must
@@ -1540,6 +1552,7 @@ async function deletePaseoWorktreeAtRepositoryRoot({
removeReason = "archive",
untrusted = false,
signal,
jujutsuRecoveryCommit,
}: DeletePaseoWorktreeOptions): Promise<void> {
if (!worktreePath && !worktreeSlug) {
throw new Error("worktreePath or worktreeSlug is required");
@@ -1580,10 +1593,20 @@ async function deletePaseoWorktreeAtRepositoryRoot({
}
if (await pathExists(resolvedWorktree)) {
for (const teardownCwd of teardownCwds ?? [resolvedWorktree]) {
await runWorktreeTeardownCommands({
worktreePath: resolvedWorktree,
teardownCwd,
});
}
if ((await findJujutsuRoot(resolvedWorktree)) === resolvedWorktree) {
await removeArchivedJujutsuWorktree(cwd, resolvedWorktree, jujutsuRecoveryCommit);
return;
}
const removedByPlugin = await prepareAndTryPluginWorktreeRemove({
cwd,
resolvedWorktree,
teardownCwds,
worktreeManagers,
worktreeManagerPluginId,
removeReason,
@@ -1664,7 +1687,6 @@ async function pruneWorktreesBestEffort(cwd: string | null): Promise<void> {
async function prepareAndTryPluginWorktreeRemove(options: {
cwd: string | null;
resolvedWorktree: string;
teardownCwds?: string[];
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
worktreeManagerPluginId?: string | null;
removeReason: "archive" | "rollback";
@@ -1674,19 +1696,12 @@ async function prepareAndTryPluginWorktreeRemove(options: {
const {
cwd,
resolvedWorktree,
teardownCwds,
worktreeManagers,
worktreeManagerPluginId,
removeReason,
untrusted,
signal,
} = options;
for (const teardownCwd of teardownCwds ?? [resolvedWorktree]) {
await runWorktreeTeardownCommands({
worktreePath: resolvedWorktree,
teardownCwd,
});
}
const effectiveManagerPluginId =
worktreeManagerPluginId !== undefined
? worktreeManagerPluginId
@@ -1729,13 +1744,48 @@ async function prepareAndTryPluginWorktreeRemove(options: {
return true;
}
async function removeArchivedJujutsuWorktree(
cwd: string | null,
worktreePath: string,
recoveryCommit?: string,
): Promise<void> {
if (!cwd || !recoveryCommit || !/^[a-f0-9]{40}$/.test(recoveryCommit)) {
throw new Error("Missing Jujutsu workspace recovery snapshot");
}
const { stdout } = await runGitCommand(
["rev-parse", "--verify", `refs/paseo/kept-commits/${recoveryCommit}^{commit}`],
{ cwd: worktreePath },
);
if (stdout.trim() !== recoveryCommit) throw new Error("Jujutsu recovery ref has changed");
// A teardown hook or editor may have changed files since the archive record was saved.
if ((await snapshotJujutsuWorkingCopy(worktreePath)) !== recoveryCommit) {
throw new Error("Jujutsu working copy changed after the archive snapshot");
}
await removeRegisteredJujutsuWorktree(cwd, worktreePath);
}
async function removeRegisteredJujutsuWorktree(cwd: string, worktreePath: string): Promise<void> {
await assertNoNestedLinkedWorktrees(worktreePath);
if (!(await removeJujutsuWorkspace(cwd, worktreePath))) {
throw new Error("Jujutsu workspace registration was not found");
}
}
export async function rollbackCreatedPaseoWorktree(
options: DeletePaseoWorktreeOptions,
cause: unknown,
): Promise<never> {
let cleanupError: unknown;
try {
await deletePaseoWorktree(options);
const path = options.worktreePath;
if (options.cwd && path && (await findJujutsuRoot(path)) === resolve(path)) {
await assertWorktreeBelongsToRepo(options.cwd, path);
await removeRegisteredJujutsuWorktree(options.cwd, path);
} else {
await deletePaseoWorktree(options);
}
} catch (error) {
cleanupError = error;
}
@@ -1811,7 +1861,7 @@ async function listLocalBranchNames(cwd: string): Promise<Set<string>> {
// ref may be rolled back when creation fails — never any other
// branch that appeared in the meantime; other creators own those.
function planCreatedLocalBranch(
source: WorktreeSource,
source: GitWorktreeSource,
sourcePlan: WorktreeSourcePlan,
): string | null {
switch (source.kind) {
@@ -1852,8 +1902,74 @@ export async function resolveDefaultWorktreePath(
return candidate;
}
async function createJujutsuWorktree({
cwd,
configSourceCwd = cwd,
source,
worktreeSlug,
paseoHome,
worktreesRoot,
worktreePath: explicitWorktreePath,
}: CreateWorktreeOptions): Promise<CreatedWorktree> {
if (source.kind !== "branch-off" && source.kind !== "restore-jujutsu") {
throw new Error(
"Jujutsu workspaces support branching from a base revision. Open existing changes as local workspaces.",
);
}
const worktreePath =
explicitWorktreePath ??
(await resolveDefaultWorktreePath({ cwd, paseoHome, worktreesRoot, worktreeSlug }));
await mkdir(dirname(worktreePath), { recursive: true });
const restoring = source.kind === "restore-jujutsu";
const revision = restoring ? source.commit : await resolveJujutsuRevision(cwd, source.baseBranch);
if (restoring) {
if (!/^[a-f0-9]{40}$/.test(revision)) throw new Error("Invalid Jujutsu recovery commit");
await runJujutsu(cwd, ["log", "--no-graph", "-r", revision, "-T", "commit_id"]);
await clearMissingJujutsuWorkspace(cwd, worktreePath);
}
const suffix = createHash("sha256").update(worktreePath).digest("hex").slice(0, 8);
await createJujutsuWorkspace({
cwd,
path: worktreePath,
name: `paseo-${worktreeSlug}-${suffix}`,
base: revision,
});
try {
if (restoring) await runJujutsu(worktreePath, ["edit", "-r", revision], { write: true });
let base = restoring ? source.baseRef : source.baseBranch;
let baseCommit = restoring ? source.baseCommit : undefined;
if (!restoring) {
const output = await runJujutsu(worktreePath, [
"log",
"--no-graph",
"-r",
"@-",
"-T",
'commit_id ++ " " ++ change_id ++ "\\n"',
]);
const parents = output.trim().split("\n");
if (parents.length !== 1) throw new Error("Choose one Jujutsu change as the workspace base");
const [commit, changeId] = parents[0].split(" ");
baseCommit = commit;
if (base === "@") base = changeId;
}
await writePaseoWorktreeMetadata(worktreePath, {
baseRefName: restoring ? (base ?? "Jujutsu") : source.baseBranch,
...(base ? { baseRef: base } : {}),
jujutsuBaseCommit: baseCommit,
});
await seedPaseoConfigFile({ sourceCwd: configSourceCwd, targetCwd: worktreePath });
return { branchName: "", worktreePath, comparisonBaseRef: base };
} catch (error) {
return rollbackCreatedPaseoWorktree({ cwd, worktreePath, teardownCwds: [] }, error);
}
}
/**
* Create a git worktree with proper naming conventions
* Create a worktree using the selected checkout's version control.
*/
export function createWorktree(
options: CreateWorktreeOptions & { source: Exclude<WorktreeSource, { kind: "restore-commit" }> },
@@ -1867,17 +1983,32 @@ export function createWorktree(
return runWithRepositoryRoot(options.cwd, () => createWorktreeAtRepositoryRoot(options));
}
async function createWorktreeAtRepositoryRoot({
async function createWorktreeAtRepositoryRoot(
options: CreateWorktreeOptions,
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }> {
const { source } = options;
if (source.kind === "restore-jujutsu" || source.kind === "branch-off") {
if (await findJujutsuRoot(options.cwd)) return createJujutsuWorktree(options);
if (source.kind === "restore-jujutsu") {
throw new Error("The source repository is no longer a Jujutsu checkout");
}
}
return createGitWorktree({ ...options, source });
}
type GitWorktreeSource = Exclude<WorktreeSource, { kind: "restore-jujutsu" }>;
async function createGitWorktree({
cwd,
configSourceCwd = cwd,
source,
preparedBranchOff,
worktreeSlug,
paseoHome,
worktreesRoot,
worktreePath: explicitWorktreePath,
}: CreateWorktreeOptions): Promise<
Omit<CreatedWorktree, "branchName"> & { branchName: string | null }
> {
}: CreateWorktreeOptions & { source: GitWorktreeSource }) {
const branchesBefore =
source.kind === "checkout-branch" ||
source.kind === "checkout-change-request" ||
@@ -1920,7 +2051,7 @@ async function createWorktreeAtRepositoryRoot({
: {}),
});
await seedPaseoConfigFile({ sourceCwd: cwd, targetCwd: worktreePath });
await seedPaseoConfigFile({ sourceCwd: configSourceCwd, targetCwd: worktreePath });
return {
branchName: sourcePlan.branchName,
@@ -1941,7 +2072,7 @@ async function createWorktreeAtRepositoryRoot({
interface AdoptPluginWorktreeOptions {
cwd: string;
source: WorktreeSource;
source: GitWorktreeSource;
worktreePath: string;
worktreeManagerPluginId: string;
/** Worktree paths that existed before creation; an overlap fails instead of hijacking user worktrees. */
@@ -1951,7 +2082,7 @@ interface AdoptPluginWorktreeOptions {
}
export interface RunPluginWorktreeManagerCheckoutOptions<
Source extends WorktreeSource = WorktreeSource,
Source extends GitWorktreeSource = GitWorktreeSource,
> {
cwd: string;
source: Source;
@@ -1976,7 +2107,7 @@ export interface RunPluginWorktreeManagerCheckoutOptions<
*/
export function runPluginWorktreeManagerCheckout(
options: RunPluginWorktreeManagerCheckoutOptions<
Exclude<WorktreeSource, { kind: "restore-commit" }>
Exclude<GitWorktreeSource, { kind: "restore-commit" }>
>,
): Promise<CreatedWorktree | null>;
export function runPluginWorktreeManagerCheckout(
@@ -2311,7 +2442,7 @@ async function verifyPluginChangeRequestHead(options: {
async function verifyPluginCheckoutTarget(options: {
cwd: string;
source: WorktreeSource;
source: GitWorktreeSource;
worktreePath: string;
branchName: string | null;
worktreeManagerPluginId: string;
@@ -2411,7 +2542,7 @@ function resolveChangeRequestMetadata(
*/
async function resolveWorktreeMetadata(options: {
cwd: string;
source: WorktreeSource;
source: GitWorktreeSource;
branchName: string | null;
resolvedBaseRef?: string;
}): Promise<ResolvedWorktreeMetadata> {
@@ -2461,7 +2592,7 @@ async function resolveWorktreeMetadata(options: {
interface ResolveWorktreeSourcePlanOptions {
cwd: string;
source: WorktreeSource;
source: GitWorktreeSource;
desiredSlug: string;
preparedBranchOff?: PreparedWorktreeBranchOff;
}
@@ -528,6 +528,27 @@
"idleRuntimeCleanup": {
"type": "boolean"
},
"idleCompaction": {
"anyOf": [
{
"type": "boolean"
},
{
"type": "object",
"properties": {
"enabled": {
"type": "boolean"
},
"minContextTokens": {
"type": "integer",
"minimum": 0,
"maximum": 9007199254740991
}
},
"additionalProperties": false
}
]
},
"resumeOnStartup": {
"type": "boolean"
},
+25
View File
@@ -113,6 +113,31 @@ period. Active work, descendants and pending finish notifications prevent cleanu
also retain runtimes with running ACP terminals, including silent ones; exited terminals do not
prevent cleanup. This check does not inspect processes launched internally by the provider.
## Idle compaction
An agent's next prompt is cheap and fast while the provider still holds its conversation in a
prompt cache. Claude keeps that cache for an hour after each request. When an idle Claude agent
has a large context, Paseo compacts it shortly before the cache expires, so the next prompt
sends a short summary instead of the whole conversation uncached. This follows Claude Code's own
idle compaction:
- It starts at 90% of a one-hour cache lifetime and is skipped for five-minute caches.
- It needs at least 200,000 tokens of context.
- It is skipped when the daemon misses that moment by more than a minute, since the cache may
already be gone.
- It runs `/compact` as a turn of its own. The chat shows a note and the compaction; no prompt is
added, and the agent keeps its read or unread state without a notification.
A prompt sent while it runs is handled as during a manual `/compact`. Turn it off, or change the
context threshold,
in `config.json`; changes apply when the daemon restarts:
```json
{ "agents": { "idleCompaction": { "enabled": true, "minContextTokens": 100000 } } }
```
`"idleCompaction": false` turns it off.
## Worktrees
New worktrees are created under `$PASEO_HOME/worktrees` by default. To place new worktrees somewhere else, set `worktrees.root`:
+86 -1
View File
@@ -45,7 +45,92 @@ When you create a workspace, **Isolation** sets the directory it works in:
- **New worktree** creates a git worktree with its own directory and branch. Use it when a task needs its own copy of the files.
- **Existing worktree** uses a git worktree that is already on disk, on the branch it has checked out. Use it to continue work on a branch without a second copy. The list shows every git worktree of the repository, including the ones that Paseo did not create.
The workspace is the product concept; a git worktree is one way to isolate its files. More than one workspace can use the same worktree. Paseo removes a worktree that it created after the last workspace that uses it is archived. Paseo does not remove a worktree that it did not create.
The workspace is the product concept; a git worktree is one way to isolate its files. More than one workspace can use the same worktree. Paseo removes a Git worktree or Jujutsu checkout that it created after the last active workspace using it is archived. User-created checkouts stay on disk.
## Jujutsu repositories
Use Jujutsu 0.46 or newer on the daemon host; this integration is tested with
0.47.1. Open a colocated checkout, which has both `.jj` and `.git`. To enable
colocation in an existing Jujutsu checkout, run `jj git colocation enable` there.
### Changes
Where a Git workspace shows its branch, a Jujutsu workspace shows its working-copy
change: its bookmark, or its short change ID when it has none. The sidebar and the
Changes header use the same label. Pick it in the Changes header to **start a new
change on** a bookmark or a change elsewhere in the repository (`jj new`). The search
covers mutable changes, bookmarked changes and recent trunk history. Search by
description, bookmark name or a change or commit ID prefix. The change you were on
keeps its work.
The diff shows **All changes** since the base, or just the **Working copy (@)**.
Both include edits on disk that Jujutsu hasn't recorded yet. Comparisons start at
the point where the workspace left its base, so a base that moves on (for example
after a fetch) doesn't show its newer changes as reverted. The **Changes** list
under the diff shows the workspace's changes since the base, newest first, with
their bookmarks and working-copy, empty and conflict markers; select one to see its
diff. In the **Working copy (@)** view, discarding a file runs `jj restore` on it,
putting it back as it is in the parent change.
### Actions
The workspace actions button offers the Jujutsu actions in place of commit, pull and
push. It leads with **Describe** until the current change has a description, then
with **Publish bookmark**.
- **Describe** edits the current change's description.
- **New change** starts a child of the current change.
- **Fetch** runs `jj git fetch`, updating remote bookmarks such as `main@origin`.
Fetch uses the base bookmark's remote when the base names one. Otherwise it uses
your Jujutsu fetch configuration. Paseo doesn't fetch in the background.
- **Publish bookmark** creates the named bookmark at the current change if needed
and pushes it to `origin`.
- **Create pull request** publishes the selected existing bookmark and opens a
request against the base you choose. It appears when the remote has a supported
forge. Paseo shows the request's status when one published bookmark identifies the
current change.
- **Archive** works as for any workspace (see below).
Use the terminal for operations such as rebase or squash.
### New Jujutsu workspaces
When the project uses Jujutsu, **New jj workspace** creates a colocated Jujutsu
workspace sharing the source repository. The app prefers the closest bookmark
under your working copy and falls back to the repository's default bookmark.
If there is no default bookmark, the base is **Current change (@)**, which
includes edits on disk. Pick another base to start from a different change. Paseo
records the base by the bookmark's name (or, for `@`, the change it pointed to).
If the bookmark disappears, Paseo marks it missing and compares against the saved
base commit while it is available. Choose a new bookmark to update the comparison.
Each isolated workspace has its own working-copy change. Opening an existing change
uses **Project directory** or **Existing jj workspace**; checking out a branch or pull
request into a new Jujutsu workspace is not supported yet.
### Archive and restore
Archiving stops the workspace sessions and saves the exact working-copy change,
including edits that Jujutsu can snapshot. Paseo removes its checkout and
Jujutsu registration when the last active workspace using the checkout is archived.
Paseo keeps the directory if it contains another linked Git worktree. Restore
reuses a checkout that stayed on disk or recreates it at the saved change.
Copy any ignored files you want to keep before archiving. Ignored files are
deleted with the checkout.
### CLI
The CLI exposes the same actions as `paseo workspace jj`. For example:
```bash
paseo workspace jj describe --description "Fix login"
paseo workspace jj new --parent main
paseo workspace jj fetch
paseo workspace jj publish --bookmark fix-login --create
paseo workspace jj create-pull-request --bookmark fix-login --base main --title "Fix login"
```
When creating a Jujutsu workspace with `paseo workspace create`, omitting
`--base` uses the repository's default bookmark if available and `@` otherwise.
## Creating a workspace