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>
This commit is contained in:
jackos1998andClaude Opus 5.5 committed 2026-11-27 14:33:36 +00:00
1 parent c8c883629c
commit d871d1a678
19 files changed
+175 -12

No files matched your search

+17
View File
@@ -29,6 +29,7 @@ see in Paseo.
| **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
@@ -73,6 +74,22 @@ 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
+13 -3
View File
@@ -113,7 +113,8 @@ function JujutsuActionForm({
() => buildAction(kind, { description, bookmark, base, title, body }),
[kind, description, bookmark, base, title, body],
);
const stale = expectedChangeId !== changeId;
// 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(() => {
@@ -140,6 +141,11 @@ function JujutsuActionForm({
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
@@ -149,7 +155,8 @@ function JujutsuActionForm({
accessibilityLabel={t("workspace.git.jujutsu.description")}
placeholder={t("workspace.git.jujutsu.description")}
/>
) : (
) : null}
{kind === "publish" || kind === "create_pull_request" ? (
<FormTextInput
editable={!pending}
initialValue={bookmark}
@@ -158,7 +165,7 @@ function JujutsuActionForm({
accessibilityLabel={t("workspace.git.jujutsu.bookmark")}
placeholder={t("workspace.git.jujutsu.bookmark")}
/>
)}
) : null}
{kind === "create_pull_request" ? (
<>
<FormTextInput
@@ -219,6 +226,8 @@ function buildAction(
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":
@@ -236,4 +245,5 @@ function buildAction(
const styles = StyleSheet.create((theme) => ({
form: { gap: theme.spacing[3], padding: theme.spacing[4] },
error: { color: theme.colors.destructive },
explanation: { color: theme.colors.foregroundMuted },
}));
+16
View File
@@ -170,6 +170,7 @@ 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 },
@@ -1574,6 +1575,7 @@ describe("git-actions-policy", () => {
describe("Jujutsu checkout actions", () => {
const allAvailable = {
"jj-update-stale": false,
"jj-describe": true,
"jj-new": true,
"jj-fetch": true,
@@ -1627,4 +1629,18 @@ describe("Jujutsu checkout actions", () => {
"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");
});
});
+14 -4
View File
@@ -28,9 +28,16 @@ export type GitActionId =
| "archive-workspace"
| JujutsuActionId;
export type JujutsuActionId = "jj-describe" | "jj-new" | "jj-fetch" | "jj-publish" | "jj-pr";
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",
@@ -952,6 +959,7 @@ function isPullRequestMergeMethodAllowed(
}
const JUJUTSU_ACTION_LABEL_KEYS: Record<JujutsuActionId, string> = {
"jj-update-stale": "updateStale",
"jj-describe": "describe",
"jj-new": "newChange",
"jj-fetch": "fetch",
@@ -959,8 +967,9 @@ const JUJUTSU_ACTION_LABEL_KEYS: Record<JujutsuActionId, string> = {
"jj-pr": "createPullRequest",
};
// Jujutsu actions take the place of the Git ones in the same button: describe first when the
// change has no description yet, otherwise publish, and the rest (then archive) in the menu.
// 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]);
@@ -986,7 +995,8 @@ function buildJujutsuActions(input: BuildGitActionsInput, archive: GitAction): G
});
let primaryId: JujutsuActionId | null = null;
if (!jj?.hasDescription && available.includes("jj-describe")) primaryId = "jj-describe";
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;
+4 -2
View File
@@ -968,7 +968,7 @@ function translateGitAction(
};
}
// Jujutsu: describe, new change, publish and PR open a form; fetch runs directly.
// Jujutsu: update-stale, describe, new change, publish and PR open a form; fetch runs directly.
function useJujutsuActions({
serverId,
cwd,
@@ -1015,6 +1015,7 @@ function useJujutsuActions({
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,
@@ -1027,7 +1028,7 @@ function useJujutsuActions({
const jujutsuRuntime = useMemo(() => {
const disabled = !jujutsuClient || !jujutsuChange;
const sheet = (
kind: "describe" | "new" | "publish" | "create_pull_request",
kind: "update_stale" | "describe" | "new" | "publish" | "create_pull_request",
label: string,
) => ({
disabled,
@@ -1035,6 +1036,7 @@ function useJujutsuActions({
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")),
+3
View File
@@ -870,6 +870,9 @@ export const ar: TranslationResources = {
currentChange: "التغيير الحالي",
noDescription: "(بدون وصف)",
conflicts: "تعارضات",
updateStale: "تحديث مساحة العمل القديمة",
updateStaleExplanation:
"أعادت مساحة عمل أخرى كتابة التغيير الحالي لهذه المساحة. يؤدي التحديث إلى مطابقة الملفات هنا مع التغيير الجديد. تُحفظ التعديلات التي لم يسجلها jj بعد في تغيير منفصل. إذا كان وكيل يعمل هنا، فانتظر حتى يصبح خاملًا.",
},
actions: {
moreOptions: "المزيد من الخيارات",
+3
View File
@@ -867,6 +867,9 @@ export const en = {
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",
+3
View File
@@ -879,6 +879,9 @@ export const es: TranslationResources = {
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",
+3
View File
@@ -880,6 +880,9 @@ export const fr: TranslationResources = {
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",
+3
View File
@@ -874,6 +874,9 @@ export const ja: TranslationResources = {
currentChange: "現在の変更",
noDescription: "(説明なし)",
conflicts: "競合",
updateStale: "古くなったワークスペースを更新",
updateStaleExplanation:
"別のワークスペースがこのワークスペースの現在の変更を書き換えました。更新すると、ここにあるファイルが新しい変更に合わせて変わります。jj がまだ記録していなかった編集は別の変更に保存されます。エージェントが作業中の場合は、アイドルになるまで待ってください。",
},
actions: {
moreOptions: "その他のオプション",
+3
View File
@@ -870,6 +870,9 @@ export const ko: TranslationResources = {
currentChange: "현재 변경 사항",
noDescription: "(설명 없음)",
conflicts: "충돌",
updateStale: "오래된 작업 공간 업데이트",
updateStaleExplanation:
"다른 작업 공간이 이 작업 공간의 현재 변경을 다시 작성했습니다. 업데이트하면 이곳의 파일이 새 변경에 맞게 바뀝니다. jj가 아직 기록하지 않은 편집은 별도의 변경에 보관됩니다. 에이전트가 작업 중이면 유휴 상태가 될 때까지 기다리세요.",
},
actions: {
moreOptions: "옵션 더 보기",
+3
View File
@@ -875,6 +875,9 @@ export const ptBR: TranslationResources = {
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",
+3
View File
@@ -879,6 +879,9 @@ export const ru: TranslationResources = {
currentChange: "Текущее изменение",
noDescription: "(без описания)",
conflicts: "Конфликты",
updateStale: "Обновить устаревшее рабочее пространство",
updateStaleExplanation:
"Другое рабочее пространство переписало текущее изменение этого. Обновление приведёт файлы здесь в соответствие с новым изменением. Правки, которые jj ещё не записал, сохраняются в отдельном изменении. Если здесь работает агент, дождитесь, пока он освободится.",
},
actions: {
moreOptions: "Дополнительные параметры",
+3
View File
@@ -866,6 +866,9 @@ export const zhCN: TranslationResources = {
currentChange: "当前变更",
noDescription: "(无描述)",
conflicts: "冲突",
updateStale: "更新过时的工作区",
updateStaleExplanation:
"另一个工作区重写了此工作区的当前变更。更新会让这里的文件与新变更一致。jj 尚未记录的编辑会保留在单独的变更中。如果有代理正在这里工作,请等它空闲后再更新。",
},
actions: {
moreOptions: "更多选项",
@@ -41,6 +41,7 @@ export function createJujutsuCommand(): Command {
"fetch",
"publish",
"create-pull-request",
"update-stale",
]),
)
.option("--path <path>", "Checkout directory (default: current directory)")
@@ -62,7 +63,7 @@ async function runJujutsuCommand(
): Promise<SingleResult<{ action: string; url: string | null }>> {
const action = JujutsuCheckoutActionSchema.parse({
...options,
kind: name === "create-pull-request" ? "create_pull_request" : name,
kind: name.replaceAll("-", "_"),
});
const target = options.daemonTarget;
const cwd = resolveRepositoryDirectory({ cwd: options.path, daemonTarget: target });
+3
View File
@@ -2621,6 +2621,7 @@ export const JujutsuCheckoutActionSchema = z.discriminatedUnion("kind", [
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>;
@@ -5926,6 +5927,8 @@ export const JujutsuStateSchema = z.object({
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({
@@ -5137,6 +5137,39 @@ describe("Jujutsu checkout inspection", () => {
]);
});
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 });
+40 -2
View File
@@ -18,6 +18,8 @@ export interface JujutsuState {
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> {
@@ -60,7 +62,24 @@ export async function runJujutsu(
return (await runJujutsuCommand(cwd, args, options)).stdout;
}
function runJujutsuCommand(cwd: string, args: string[], options?: JujutsuCommandOptions) {
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"];
@@ -78,7 +97,7 @@ function runJujutsuCommand(cwd: string, args: string[], options?: JujutsuCommand
}
export async function getJujutsuState(cwd: string): Promise<JujutsuState> {
const [output, nearest, remotes] = await Promise.all([
const [output, nearest, remotes, stale] = await Promise.all([
readJujutsuChange(cwd),
runJujutsu(cwd, [
"log",
@@ -89,6 +108,7 @@ export async function getJujutsuState(cwd: string): Promise<JujutsuState> {
'json(local_bookmarks.map(|b| b.name())) ++ "\\n"',
]),
exists(join(cwd, ".git")).then((colocated) => (colocated ? listJujutsuGitRemotes(cwd) : [])),
isJujutsuWorkingCopyStale(cwd),
]);
const nearestBookmark =
nearest
@@ -106,9 +126,27 @@ export async function getJujutsuState(cwd: string): Promise<JujutsuState> {
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",
@@ -9,6 +9,7 @@ import {
getJujutsuState,
resolveJujutsuRevision,
runJujutsu,
updateStaleJujutsuWorkspace,
} from "./checkout-jj.js";
const pendingActions = new Map<string, Promise<unknown>>();
@@ -39,6 +40,11 @@ export async function runJujutsuCheckoutAction(options: {
);
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) {