diff --git a/docs/jujutsu-fork.md b/docs/jujutsu-fork.md index 12453e95e..db6992373 100644 --- a/docs/jujutsu-fork.md +++ b/docs/jujutsu-fork.md @@ -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 diff --git a/packages/app/src/git/jujutsu-actions.tsx b/packages/app/src/git/jujutsu-actions.tsx index 942f3ebba..f57479b4c 100644 --- a/packages/app/src/git/jujutsu-actions.tsx +++ b/packages/app/src/git/jujutsu-actions.tsx @@ -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 ( + {kind === "update_stale" ? ( + + {t("workspace.git.jujutsu.updateStaleExplanation")} + + ) : null} {kind === "describe" || kind === "new" ? ( - ) : ( + ) : null} + {kind === "publish" || kind === "create_pull_request" ? ( - )} + ) : null} {kind === "create_pull_request" ? ( <> ({ form: { gap: theme.spacing[3], padding: theme.spacing[4] }, error: { color: theme.colors.destructive }, + explanation: { color: theme.colors.foregroundMuted }, })); diff --git a/packages/app/src/git/policy.test.ts b/packages/app/src/git/policy.test.ts index 0ffda9565..63d8581a3 100644 --- a/packages/app/src/git/policy.test.ts +++ b/packages/app/src/git/policy.test.ts @@ -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"); + }); }); diff --git a/packages/app/src/git/policy.ts b/packages/app/src/git/policy.ts index c7a23204c..aaf7f5488 100644 --- a/packages/app/src/git/policy.ts +++ b/packages/app/src/git/policy.ts @@ -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 = { + "jj-update-stale": "updateStale", "jj-describe": "describe", "jj-new": "newChange", "jj-fetch": "fetch", @@ -959,8 +967,9 @@ const JUJUTSU_ACTION_LABEL_KEYS: Record = { "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; diff --git a/packages/app/src/git/use-actions.tsx b/packages/app/src/git/use-actions.tsx index f43372e83..d2012b91b 100644 --- a/packages/app/src/git/use-actions.tsx +++ b/packages/app/src/git/use-actions.tsx @@ -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")), diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 41c28dc93..815d16628 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -870,6 +870,9 @@ export const ar: TranslationResources = { currentChange: "التغيير الحالي", noDescription: "(بدون وصف)", conflicts: "تعارضات", + updateStale: "تحديث مساحة العمل القديمة", + updateStaleExplanation: + "أعادت مساحة عمل أخرى كتابة التغيير الحالي لهذه المساحة. يؤدي التحديث إلى مطابقة الملفات هنا مع التغيير الجديد. تُحفظ التعديلات التي لم يسجلها jj بعد في تغيير منفصل. إذا كان وكيل يعمل هنا، فانتظر حتى يصبح خاملًا.", }, actions: { moreOptions: "المزيد من الخيارات", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 8d18db837..ca2f6e741 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -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", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index bcce44287..d84d9a4e8 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -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", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 09d043a75..f41ecbcdb 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -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", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 445d890f0..49bc49c04 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -874,6 +874,9 @@ export const ja: TranslationResources = { currentChange: "現在の変更", noDescription: "(説明なし)", conflicts: "競合", + updateStale: "古くなったワークスペースを更新", + updateStaleExplanation: + "別のワークスペースがこのワークスペースの現在の変更を書き換えました。更新すると、ここにあるファイルが新しい変更に合わせて変わります。jj がまだ記録していなかった編集は別の変更に保存されます。エージェントが作業中の場合は、アイドルになるまで待ってください。", }, actions: { moreOptions: "その他のオプション", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index f0cd87f8a..503add712 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -870,6 +870,9 @@ export const ko: TranslationResources = { currentChange: "현재 변경 사항", noDescription: "(설명 없음)", conflicts: "충돌", + updateStale: "오래된 작업 공간 업데이트", + updateStaleExplanation: + "다른 작업 공간이 이 작업 공간의 현재 변경을 다시 작성했습니다. 업데이트하면 이곳의 파일이 새 변경에 맞게 바뀝니다. jj가 아직 기록하지 않은 편집은 별도의 변경에 보관됩니다. 에이전트가 작업 중이면 유휴 상태가 될 때까지 기다리세요.", }, actions: { moreOptions: "옵션 더 보기", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index 1d04bb774..40f2393ae 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -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", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index fed1f783e..0d747f316 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -879,6 +879,9 @@ export const ru: TranslationResources = { currentChange: "Текущее изменение", noDescription: "(без описания)", conflicts: "Конфликты", + updateStale: "Обновить устаревшее рабочее пространство", + updateStaleExplanation: + "Другое рабочее пространство переписало текущее изменение этого. Обновление приведёт файлы здесь в соответствие с новым изменением. Правки, которые jj ещё не записал, сохраняются в отдельном изменении. Если здесь работает агент, дождитесь, пока он освободится.", }, actions: { moreOptions: "Дополнительные параметры", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index d2892c6d4..384c60dfa 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -866,6 +866,9 @@ export const zhCN: TranslationResources = { currentChange: "当前变更", noDescription: "(无描述)", conflicts: "冲突", + updateStale: "更新过时的工作区", + updateStaleExplanation: + "另一个工作区重写了此工作区的当前变更。更新会让这里的文件与新变更一致。jj 尚未记录的编辑会保留在单独的变更中。如果有代理正在这里工作,请等它空闲后再更新。", }, actions: { moreOptions: "更多选项", diff --git a/packages/cli/src/commands/workspace/jujutsu.ts b/packages/cli/src/commands/workspace/jujutsu.ts index 4e32cb926..cca6c2d74 100644 --- a/packages/cli/src/commands/workspace/jujutsu.ts +++ b/packages/cli/src/commands/workspace/jujutsu.ts @@ -41,6 +41,7 @@ export function createJujutsuCommand(): Command { "fetch", "publish", "create-pull-request", + "update-stale", ]), ) .option("--path ", "Checkout directory (default: current directory)") @@ -62,7 +63,7 @@ async function runJujutsuCommand( ): Promise> { 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 }); diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 4db35367b..c46c69043 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -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; @@ -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({ diff --git a/packages/server/src/utils/checkout-git.test.ts b/packages/server/src/utils/checkout-git.test.ts index f22eee15e..5f5f19288 100644 --- a/packages/server/src/utils/checkout-git.test.ts +++ b/packages/server/src/utils/checkout-git.test.ts @@ -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 }); diff --git a/packages/server/src/utils/checkout-jj.ts b/packages/server/src/utils/checkout-jj.ts index 8b4dd780b..a22eba0da 100644 --- a/packages/server/src/utils/checkout-jj.ts +++ b/packages/server/src/utils/checkout-jj.ts @@ -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 { @@ -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 { - 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 { '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 { 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 { + 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 { + await runJujutsu(cwd, ["workspace", "update-stale"], { write: true, timeout: 120_000 }); +} + async function readJujutsuChange(cwd: string) { const output = await runJujutsu(cwd, [ "log", diff --git a/packages/server/src/utils/jujutsu-actions.ts b/packages/server/src/utils/jujutsu-actions.ts index 8ca47e161..fcfecb989 100644 --- a/packages/server/src/utils/jujutsu-actions.ts +++ b/packages/server/src/utils/jujutsu-actions.ts @@ -9,6 +9,7 @@ import { getJujutsuState, resolveJujutsuRevision, runJujutsu, + updateStaleJujutsuWorkspace, } from "./checkout-jj.js"; const pendingActions = new Map>(); @@ -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) {