From db0fa035147a2c4e28bbe339b82d4a4fa5d82b6a Mon Sep 17 00:00:00 2001 From: Jack O'Sullivan Date: Sat, 21 Nov 2026 22:18:51 +0000 Subject: [PATCH] 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 --- packages/app/src/app/_layout.tsx | 2 + .../src/components/workspace-hover-card.tsx | 6 +- .../src/git/commit-file-diff-query.test.ts | 24 +- .../app/src/git/commit-file-diff-query.ts | 6 +- .../src/git/commits-section/commit-row.tsx | 28 +- .../git/commits-section/commits-section.tsx | 51 +++- packages/app/src/git/diff-pane.tsx | 98 +++++-- packages/app/src/git/jujutsu-actions.tsx | 239 ++++++++++++++++++ .../app/src/git/jujutsu-change-switcher.tsx | 214 ++++++++++++++++ packages/app/src/git/jujutsu-label.ts | 7 + packages/app/src/git/policy.test.ts | 62 +++++ packages/app/src/git/policy.ts | 70 ++++- .../app/src/git/pull-request-panel/pane.tsx | 21 +- packages/app/src/git/use-actions.tsx | 137 +++++++++- packages/app/src/git/use-diff-files.ts | 12 +- .../src/git/workspace-base-branch-picker.tsx | 41 ++- .../app/src/git/worktree-archive-warning.ts | 2 + .../hooks/sidebar-workspaces-view-model.ts | 18 +- packages/app/src/i18n/resources/ar.ts | 43 ++++ packages/app/src/i18n/resources/en.ts | 43 ++++ packages/app/src/i18n/resources/es.ts | 44 ++++ packages/app/src/i18n/resources/fr.ts | 44 ++++ packages/app/src/i18n/resources/ja.ts | 43 ++++ packages/app/src/i18n/resources/ko.ts | 43 ++++ packages/app/src/i18n/resources/pt-BR.ts | 44 ++++ packages/app/src/i18n/resources/ru.ts | 43 ++++ packages/app/src/i18n/resources/zh-CN.ts | 43 ++++ .../app/src/runtime/replica-cache/index.ts | 1 + .../screens/new-workspace-picker-item.test.ts | 117 +++++++++ .../src/screens/new-workspace-picker-item.ts | 35 ++- .../app/src/screens/new-workspace-screen.tsx | 85 +++++-- .../src/screens/new-workspace/form/index.tsx | 62 ++++- .../new-workspace/form/ref-picker-toolbar.tsx | 18 +- 33 files changed, 1644 insertions(+), 102 deletions(-) create mode 100644 packages/app/src/git/jujutsu-actions.tsx create mode 100644 packages/app/src/git/jujutsu-change-switcher.tsx create mode 100644 packages/app/src/git/jujutsu-label.ts diff --git a/packages/app/src/app/_layout.tsx b/packages/app/src/app/_layout.tsx index bc4b84c4b..77fdd953b 100644 --- a/packages/app/src/app/_layout.tsx +++ b/packages/app/src/app/_layout.tsx @@ -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 + diff --git a/packages/app/src/components/workspace-hover-card.tsx b/packages/app/src/components/workspace-hover-card.tsx index 039fec3be..808f45d94 100644 --- a/packages/app/src/components/workspace-hover-card.tsx +++ b/packages/app/src/components/workspace-hover-card.tsx @@ -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} diff --git a/packages/app/src/git/commit-file-diff-query.test.ts b/packages/app/src/git/commit-file-diff-query.test.ts index 173592639..9db80090c 100644 --- a/packages/app/src/git/commit-file-diff-query.test.ts +++ b/packages/app/src/git/commit-file-diff-query.test.ts @@ -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( diff --git a/packages/app/src/git/commit-file-diff-query.ts b/packages/app/src/git/commit-file-diff-query.ts index 527755123..6c145cfea 100644 --- a/packages/app/src/git/commit-file-diff-query.ts +++ b/packages/app/src/git/commit-file-diff-query.ts @@ -7,6 +7,7 @@ export function commitFileDiffQueryOptions(input: { cwd: string; sha: string; path: string; + jujutsuOperationId?: string; client: Pick | 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, diff --git a/packages/app/src/git/commits-section/commit-row.tsx b/packages/app/src/git/commits-section/commit-row.tsx index aab76da3d..a85c77ef9 100644 --- a/packages/app/src/git/commits-section/commit-row.tsx +++ b/packages/app/src/git/commits-section/commit-row.tsx @@ -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 ( - {commit.subject} + {subject} + {annotations ? ( + + {annotations} + + ) : null} @@ -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, diff --git a/packages/app/src/git/commits-section/commits-section.tsx b/packages/app/src/git/commits-section/commits-section.tsx index a7b32c777..0fc5b8ee4 100644 --- a/packages/app/src/git/commits-section/commits-section.tsx +++ b/packages/app/src/git/commits-section/commits-section.tsx @@ -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; + isJujutsu: boolean; onCommitPress: (sha: string) => void; }) { const { t } = useTranslation(); @@ -55,13 +74,15 @@ function CommitsSectionContent({ if (query.status !== "loaded") { return ; } - 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 ( - {t("workspace.git.diff.commits.noneAhead", { baseRef })} + {isJujutsu + ? t("workspace.git.jujutsu.changes.noneAhead", { baseRef }) + : t("workspace.git.diff.commits.noneAhead", { baseRef })} ); @@ -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 ( @@ -128,21 +148,30 @@ export function CommitsSection({ - {t("workspace.git.diff.commits.title")} + + {isJujutsu + ? t("workspace.git.jujutsu.changes.title") + : t("workspace.git.diff.commits.title")} + {commitCount === null ? ( ) : ( {commitCount} )} - {collapsed ? null : } + {collapsed ? null : ( + + )} ); } diff --git a/packages/app/src/git/diff-pane.tsx b/packages/app/src/git/diff-pane.tsx index 358116698..9c3b2ef69 100644 --- a/packages/app/src/git/diff-pane.tsx +++ b/packages/app/src/git/diff-pane.tsx @@ -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 ( {allLabel} @@ -343,15 +351,19 @@ export function DiffModeMenu({ > {uncommittedLabel} - - - {committedLabel} - + {!isJujutsu ? ( + <> + + + {committedLabel} + + + ) : null} ); @@ -473,7 +485,11 @@ interface ChangesPullRequestLinkModel extends Pick void; } +type JujutsuState = NonNullable; + 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"} > - + {model.jujutsu ? ( + + ) : null} + {model.canSwitchBranch ? ( + + ) : null} {model.baseRef && model.isWorktree ? ( <> @@ -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({ > void; onCollapsedChange: (collapsed: boolean) => void; }) { + const { status } = useCheckoutStatusQuery({ serverId, cwd }); + const isJujutsu = Boolean(status?.jujutsu); if (presentation === "diff") return null; return ( buildChangesHeaderModel({ + status, baseRef: baseRef ?? null, isWorktree: isManagedWorktree(status), branchName: currentBranchName, @@ -1997,6 +2030,8 @@ export function ChangesSurface({ /> ) : null} + + {forgeSetupMessage ? ( {forgeSetupMessage} @@ -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 ( + + {`Jujutsu · ${state.changeId.slice(0, 12)}`} + + {state.description.split("\n")[0] || t("workspace.git.jujutsu.noDescription")} + + {state.hasConflicts ? ( + {t("workspace.git.jujutsu.conflicts")} + ) : null} + {state.bookmarks.length ? ( + {state.bookmarks.join(", ")} + ) : null} + + ); +} + const styles = StyleSheet.create((theme) => ({ container: { flex: 1, diff --git a/packages/app/src/git/jujutsu-actions.tsx b/packages/app/src/git/jujutsu-actions.tsx new file mode 100644 index 000000000..942f3ebba --- /dev/null +++ b/packages/app/src/git/jujutsu-actions.tsx @@ -0,0 +1,239 @@ +import { useCallback, useMemo, useState } from "react"; +import { View, Text } from "react-native"; +import { create } from "zustand"; +import { StyleSheet } from "react-native-unistyles"; +import { useTranslation } from "react-i18next"; +import type { JujutsuCheckoutAction } from "@getpaseo/protocol/messages"; +import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet"; +import { Button } from "@/components/ui/button"; +import { FormTextInput } from "@/components/ui/form-field"; +import { useToast } from "@/contexts/toast-context"; +import { useSessionStore } from "@/stores/session-store"; +import { openExternalUrl } from "@/utils/open-external-url"; +import { useCheckoutStatusQuery } from "./use-status-query"; + +type ActionKind = Exclude; +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 ( + + ); +} + +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( + (changeId, action) => { + if (!client) throw new Error("Host disconnected"); + return client.checkoutJujutsuAction(cwd, changeId, action); + }, + [client, cwd], + ); + if (!client || !change) return null; + + return ( + + ); +} + +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(null); + const action = useMemo( + () => buildAction(kind, { description, bookmark, base, title, body }), + [kind, description, bookmark, base, title, body], + ); + const stale = expectedChangeId !== changeId; + + const header = useMemo(() => ({ title: label }), [label]); + const close = useCallback(() => { + if (!pending) onClose(); + }, [pending, onClose]); + + const handleSubmit = useCallback(async () => { + if (!action || pending || stale) return; + setPending(true); + setError(null); + try { + const result = await submit(expectedChangeId, action); + if (result.error) throw new Error(result.error.message); + toast.show(t("workspace.git.jujutsu.actionComplete"), { variant: "success" }); + onClose(); + if (result.url) void openExternalUrl(result.url); + } catch (failure) { + setError(failure instanceof Error ? failure.message : String(failure)); + } finally { + setPending(false); + } + }, [action, pending, stale, submit, expectedChangeId, toast, t, onClose]); + + return ( + + + {kind === "describe" || kind === "new" ? ( + + ) : ( + + )} + {kind === "create_pull_request" ? ( + <> + + + + + ) : null} + {stale ? ( + + {t("workspace.git.jujutsu.changeMoved")} + + ) : null} + {error ? ( + + {error} + + ) : null} + + + + ); +} + +function buildAction( + kind: ActionKind, + input: { + description: string; + bookmark: string; + base: string; + title: string; + body: string; + }, +): JujutsuCheckoutAction | null { + const description = input.description.trim(); + const bookmark = input.bookmark.trim(); + const base = input.base.trim(); + const title = input.title.trim(); + switch (kind) { + case "describe": + return description ? { kind, description } : null; + case "new": + return { kind, description: description || undefined }; + case "publish": + return bookmark ? { kind, bookmark, create: true } : null; + case "create_pull_request": + return bookmark && base && title + ? { kind, bookmark, base, title, body: input.body.trim() } + : null; + } + return null; +} + +const styles = StyleSheet.create((theme) => ({ + form: { gap: theme.spacing[3], padding: theme.spacing[4] }, + error: { color: theme.colors.destructive }, +})); diff --git a/packages/app/src/git/jujutsu-change-switcher.tsx b/packages/app/src/git/jujutsu-change-switcher.tsx new file mode 100644 index 000000000..7f50de005 --- /dev/null +++ b/packages/app/src/git/jujutsu-change-switcher.tsx @@ -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; + +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 `). 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(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(() => , []); + const renderOption = useCallback>( + ({ option, selected, active, onPress }) => ( + + ), + [isPending, branchIcon], + ); + const footer = useMemo( + () => ( + + {isPending ? : null} + {error ? ( + + {error.message} + + ) : null} + + ), + [isPending, error], + ); + + if (!supported) return {label}; + + return ( + + + + + ); +} + +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 }, +})); diff --git a/packages/app/src/git/jujutsu-label.ts b/packages/app/src/git/jujutsu-label.ts new file mode 100644 index 000000000..580345aa6 --- /dev/null +++ b/packages/app/src/git/jujutsu-label.ts @@ -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); +} diff --git a/packages/app/src/git/policy.test.ts b/packages/app/src/git/policy.test.ts index c49d55a39..a948c886d 100644 --- a/packages/app/src/git/policy.test.ts +++ b/packages/app/src/git/policy.test.ts @@ -167,6 +167,11 @@ function createInput( status: "idle", handler: () => undefined, }, + "jj-describe": { disabled: false, status: "idle", handler: () => undefined }, + "jj-new": { disabled: false, status: "idle", handler: () => undefined }, + "jj-fetch": { disabled: false, status: "idle", handler: () => undefined }, + "jj-publish": { disabled: false, status: "idle", handler: () => undefined }, + "jj-pr": { disabled: false, status: "idle", handler: () => undefined }, }, ...rest, }; @@ -1430,3 +1435,60 @@ describe("git-actions-policy", () => { ]); }); }); + +describe("Jujutsu checkout actions", () => { + const allAvailable = { + "jj-describe": true, + "jj-new": true, + "jj-fetch": true, + "jj-publish": true, + "jj-pr": false, + }; + + it("keeps archive drawable while hiding Git mutation actions", () => { + const actions = buildGitActions( + createInput({ + isJujutsu: true, + isPaseoOwnedWorktree: true, + hasUncommittedChanges: true, + }), + ); + // The split button only draws secondary actions beside a primary one. + expect(actions.primary?.id).toBe("archive-workspace"); + expect(actions.secondary).toEqual([]); + expect(actions.menu).toEqual([]); + }); + + it("leads with describe until the change has a description", () => { + const actions = buildGitActions( + createInput({ + isJujutsu: true, + jujutsu: { hasDescription: false, available: allAvailable }, + }), + ); + expect(actions.primary?.id).toBe("jj-describe"); + expect(actions.secondary.map((action) => action.id)).toEqual([ + "jj-new", + "jj-fetch", + "jj-publish", + "archive-workspace", + ]); + }); + + it("leads with publish once the change is described", () => { + const actions = buildGitActions( + createInput({ + isJujutsu: true, + jujutsu: { hasDescription: true, available: { ...allAvailable, "jj-pr": true } }, + }), + ); + expect(actions.primary?.id).toBe("jj-publish"); + expect(actions.secondary.map((action) => action.id)).toEqual([ + "jj-describe", + "jj-new", + "jj-fetch", + "jj-pr", + "archive-workspace", + ]); + }); +}); diff --git a/packages/app/src/git/policy.ts b/packages/app/src/git/policy.ts index 37f898c0e..abf18d8ca 100644 --- a/packages/app/src/git/policy.ts +++ b/packages/app/src/git/policy.ts @@ -25,7 +25,23 @@ export type GitActionId = | "disable-pr-auto-merge" | "merge-branch" | "merge-from-base" - | "archive-workspace"; + | "archive-workspace" + | JujutsuActionId; + +export type JujutsuActionId = "jj-describe" | "jj-new" | "jj-fetch" | "jj-publish" | "jj-pr"; + +export const JUJUTSU_ACTION_IDS: readonly JujutsuActionId[] = [ + "jj-describe", + "jj-new", + "jj-fetch", + "jj-publish", + "jj-pr", +]; + +export interface JujutsuActionsInput { + hasDescription: boolean; + available: Record; +} export interface GitAction { id: GitActionId; @@ -98,6 +114,9 @@ export function readUpstreamState( export interface BuildGitActionsInput { isGit: boolean; + isJujutsu?: boolean; + /** Present for Jujutsu checkouts, whose actions replace the Git ones. */ + jujutsu?: JujutsuActionsInput; githubFeaturesEnabled: boolean; /** Forge brand label (e.g. "GitHub", "GitLab") for forge-neutral unavailable copy. */ forgeBrandLabel: string; @@ -344,6 +363,10 @@ export function buildGitActions(input: BuildGitActionsInput): GitActions { handler: input.runtime["archive-workspace"].handler, }); + if (input.isJujutsu) { + return buildJujutsuActions(input, allActions.get("archive-workspace")!); + } + const primaryActionId = getPrimaryActionId(input); const primary = primaryActionId ? (allActions.get(primaryActionId) ?? null) : null; @@ -901,3 +924,48 @@ function isPullRequestMergeMethodAllowed( } return capability.allowedMethods.includes(method); } + +const JUJUTSU_ACTION_LABEL_KEYS: Record = { + "jj-describe": "describe", + "jj-new": "newChange", + "jj-fetch": "fetch", + "jj-publish": "publish", + "jj-pr": "createPullRequest", +}; + +// Jujutsu actions take the place of the Git ones in the same button: describe first when the +// change has no description yet, otherwise publish, and the rest (then archive) in the menu. +function buildJujutsuActions(input: BuildGitActionsInput, archive: GitAction): GitActions { + const jj = input.jujutsu; + const available = JUJUTSU_ACTION_IDS.filter((id) => jj?.available[id]); + const actions = available.map((id): GitAction => { + const key = JUJUTSU_ACTION_LABEL_KEYS[id]; + return { + id, + label: i18n.t(`workspace.git.jujutsu.${key}`), + pendingLabel: + id === "jj-fetch" + ? i18n.t("workspace.git.jujutsu.fetching") + : i18n.t(`workspace.git.jujutsu.${key}`), + successLabel: + id === "jj-fetch" + ? i18n.t("workspace.git.jujutsu.fetched") + : i18n.t(`workspace.git.jujutsu.${key}`), + disabled: input.runtime[id].disabled, + status: input.runtime[id].status, + icon: input.runtime[id].icon, + startsGroup: false, + handler: input.runtime[id].handler, + }; + }); + + let primaryId: JujutsuActionId | null = null; + if (!jj?.hasDescription && available.includes("jj-describe")) primaryId = "jj-describe"; + else if (available.includes("jj-publish")) primaryId = "jj-publish"; + else primaryId = available[0] ?? null; + + const primary = actions.find((action) => action.id === primaryId) ?? null; + const secondary = actions.filter((action) => action !== primary); + if (!primary) return { primary: archive, secondary: [], menu: [] }; + return { primary, secondary: [...secondary, archive], menu: [] }; +} diff --git a/packages/app/src/git/pull-request-panel/pane.tsx b/packages/app/src/git/pull-request-panel/pane.tsx index ff2b9c868..c69236d58 100644 --- a/packages/app/src/git/pull-request-panel/pane.tsx +++ b/packages/app/src/git/pull-request-panel/pane.tsx @@ -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, 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({ 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(() => { + if (!jujutsuSupported || !jujutsuChange || !jujutsuCapabilities) return undefined; + return { + hasDescription: jujutsuChange.description.trim().length > 0, + available: { + "jj-describe": jujutsuCapabilities.describe ?? false, + "jj-new": jujutsuCapabilities.newChange ?? false, + "jj-fetch": jujutsuCapabilities.fetch ?? false, + "jj-publish": jujutsuCapabilities.publishBookmark ?? false, + "jj-pr": jujutsuCapabilities.createPullRequest ?? false, + }, + }; + }, [jujutsuCapabilities, jujutsuChange, jujutsuSupported]); + + const jujutsuRuntime = useMemo(() => { + const disabled = !jujutsuClient || !jujutsuChange; + const sheet = ( + kind: "describe" | "new" | "publish" | "create_pull_request", + label: string, + ) => ({ + disabled, + status: "idle" as const, + handler: () => openJujutsuSheet({ serverId, cwd, kind, label }), + }); + return { + "jj-describe": sheet("describe", t("workspace.git.jujutsu.describe")), + "jj-new": sheet("new", t("workspace.git.jujutsu.newChange")), + "jj-publish": sheet("publish", t("workspace.git.jujutsu.publish")), + "jj-pr": sheet("create_pull_request", t("workspace.git.jujutsu.createPullRequest")), + "jj-fetch": { + disabled: disabled || jujutsuFetchPending, + status: jujutsuFetchPending ? ("pending" as const) : ("idle" as const), + icon: fetchIcon, + handler: handleJujutsuFetch, + }, + }; + }, [ + cwd, + handleJujutsuFetch, + fetchIcon, + jujutsuChange, + jujutsuClient, + jujutsuFetchPending, + openJujutsuSheet, + serverId, + t, + ]); + + return { jujutsuInput, jujutsuRuntime }; +} + function getTranslatedGitActionLabels( action: GitAction, { @@ -1045,6 +1171,13 @@ function getTranslatedGitActionLabels( pendingLabel: t("workspace.git.actions.archive.pending"), successLabel: t("workspace.git.actions.archive.success"), }; + // Jujutsu actions are labelled when they are built. + default: + return { + label: action.label, + pendingLabel: action.pendingLabel, + successLabel: action.successLabel, + }; } } diff --git a/packages/app/src/git/use-diff-files.ts b/packages/app/src/git/use-diff-files.ts index 9623a3117..d3a7c9dda 100644 --- a/packages/app/src/git/use-diff-files.ts +++ b/packages/app/src/git/use-diff-files.ts @@ -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, }), diff --git a/packages/app/src/git/workspace-base-branch-picker.tsx b/packages/app/src/git/workspace-base-branch-picker.tsx index abc4fbee8..f2f39922a 100644 --- a/packages/app/src/git/workspace-base-branch-picker.tsx +++ b/packages/app/src/git/workspace-base-branch-picker.tsx @@ -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} diff --git a/packages/app/src/git/worktree-archive-warning.ts b/packages/app/src/git/worktree-archive-warning.ts index 3935eef3c..b23151949 100644 --- a/packages/app/src/git/worktree-archive-warning.ts +++ b/packages/app/src/git/worktree-archive-warning.ts @@ -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 }; } diff --git a/packages/app/src/hooks/sidebar-workspaces-view-model.ts b/packages/app/src/hooks/sidebar-workspaces-view-model.ts index da1086da4..795d4d5b8 100644 --- a/packages/app/src/hooks/sidebar-workspaces-view-model.ts +++ b/packages/app/src/hooks/sidebar-workspaces-view-model.ts @@ -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"), diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index be9e83199..10183feb2 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -503,6 +503,7 @@ export const ar: TranslationResources = { }, }, hoverCard: { + copyChangeName: "نسخ الإشارة أو معرّف التغيير", scriptsAccessibility: "البرامج النصية Workspace", copyPath: "نسخ المسار", copyBranchName: "نسخ اسم الفرع", @@ -835,6 +836,38 @@ export const ar: TranslationResources = { hideFolderTree: "إخفاء شجرة المجلدات", }, git: { + jujutsu: { + filterBookmarks: "تصفية الإشارات…", + noBookmarks: "لم يتم العثور على إشارات.", + missingBaseBookmark: "{{bookmark}} (مفقودة)", + empty: "فارغ", + filterBookmarksAndChanges: "تصفية الإشارات والتغييرات", + noMatches: "لا توجد إشارات أو تغييرات مطابقة", + changes: { + title: "التغييرات", + countLabel: "{{count}} تغييرات في مساحة العمل", + noneAhead: "لا توجد تغييرات منذ {{baseRef}} بعد", + }, + workingCopy: "نسخة العمل (@)", + startNewChangeOn: "بدء تغيير جديد على…", + fetch: "جلب", + fetching: "جارٍ الجلب…", + fetched: "تم الجلب من المستودع البعيد.", + fetchFailed: "تعذّر الجلب من المستودع البعيد.", + describe: "وصف", + newChange: "تغيير جديد", + publish: "نشر الإشارة المرجعية", + createPullRequest: "إنشاء طلب سحب", + description: "الوصف", + bookmark: "إشارة مرجعية", + base: "الإشارة المرجعية الأساسية", + title: "العنوان", + actionComplete: "اكتمل إجراء Jujutsu.", + changeMoved: "تغيّر تعديل نسخة العمل. أغلق النموذج وأعد المحاولة.", + currentChange: "التغيير الحالي", + noDescription: "(بدون وصف)", + conflicts: "تعارضات", + }, actions: { moreOptions: "المزيد من الخيارات", moreActions: "المزيد من الإجراءات", @@ -1000,6 +1033,7 @@ export const ar: TranslationResources = { refreshing: "منعش", refresh: "ينعش", refreshState: "تحديث حالة git و{{brand}}", + refreshJujutsuState: "تحديث حالة jj و{{brand}}", failedRefresh: "فشل تحديث حالة git.", seeUncommittedChanges: "عرض التغييرات غير الملتزم بها", seeCommittedChanges: "عرض التغييرات الملتزم بها", @@ -1402,9 +1436,11 @@ export const ar: TranslationResources = { title: "مساحة عمل جديدة", create: "يخلق", isolation: { + jujutsu: "مساحة عمل jj جديدة", local: "مجلد المشروع", worktree: "شجرة عمل جديدة", existing: "شجرة عمل موجودة", + existingJujutsu: "مساحة عمل jj موجودة", label: "العزل", }, fields: { @@ -1430,9 +1466,11 @@ export const ar: TranslationResources = { isolation: "Choose the isolation level", startingRef: "اختر من أين تبدأ", worktree: "اختر شجرة العمل التي تعمل فيها", + jujutsuWorkspace: "اختر مساحة عمل jj للعمل فيها", launch: "Choose what to launch", }, refPicker: { + searchBookmarks: "البحث في الإشارات", startingRef: "بدء المرجع", intoBase: "إلى {{baseRef}}", searching: "جارٍ البحث...", @@ -1463,6 +1501,11 @@ export const ar: TranslationResources = { searchPlaceholder: "ابحث في أشجار العمل", empty: "لا توجد أشجار عمل مطابقة.", }, + jujutsuWorkspacePicker: { + title: "مساحة العمل", + searchPlaceholder: "البحث في مساحات عمل jj", + empty: "لا توجد مساحات عمل jj مطابقة.", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index b758b170b..ca3fe7d81 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -502,6 +502,7 @@ export const en = { }, }, hoverCard: { + copyChangeName: "Copy bookmark or change ID", scriptsAccessibility: "Workspace scripts", copyPath: "Copy path", copyBranchName: "Copy branch name", @@ -832,6 +833,38 @@ export const en = { hideFolderTree: "Hide folder tree", }, git: { + jujutsu: { + filterBookmarks: "Filter bookmarks…", + noBookmarks: "No bookmarks found.", + missingBaseBookmark: "{{bookmark}} (missing)", + empty: "empty", + filterBookmarksAndChanges: "Filter bookmarks and changes", + noMatches: "No matching bookmarks or changes", + changes: { + title: "Changes", + countLabel: "{{count}} workspace changes", + noneAhead: "No changes since {{baseRef}} yet", + }, + workingCopy: "Working copy (@)", + startNewChangeOn: "Start new change on…", + fetch: "Fetch", + fetching: "Fetching…", + fetched: "Fetched from the remote.", + fetchFailed: "Couldn't fetch from the remote.", + describe: "Describe", + newChange: "New change", + publish: "Publish bookmark", + createPullRequest: "Create pull request", + description: "Description", + bookmark: "Bookmark", + base: "Base bookmark", + title: "Title", + actionComplete: "Jujutsu action completed.", + changeMoved: "The working-copy change moved. Close this form and try again.", + currentChange: "Current change", + noDescription: "(no description)", + conflicts: "Conflicts", + }, actions: { moreOptions: "More options", moreActions: "More actions", @@ -1011,6 +1044,7 @@ export const en = { refreshing: "Refreshing", refresh: "Refresh", refreshState: "Refresh git and {{brand}} state", + refreshJujutsuState: "Refresh jj and {{brand}} state", failedRefresh: "Failed to refresh git state.", seeUncommittedChanges: "See uncommitted changes", seeCommittedChanges: "See committed changes", @@ -1413,9 +1447,11 @@ export const en = { 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: { @@ -1441,9 +1477,11 @@ export const en = { isolation: "Choose the isolation level", startingRef: "Choose where to start from", worktree: "Choose the worktree to work in", + jujutsuWorkspace: "Choose the jj workspace to work in", launch: "Choose what to launch", }, refPicker: { + searchBookmarks: "Search bookmarks", startingRef: "Starting ref", intoBase: "into {{baseRef}}", searching: "Searching...", @@ -1474,6 +1512,11 @@ export const en = { searchPlaceholder: "Search worktrees", empty: "No matching worktrees.", }, + jujutsuWorkspacePicker: { + title: "Workspace", + searchPlaceholder: "Search jj workspaces", + empty: "No matching jj workspaces.", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index 8e709cbbc..97c941fec 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -509,6 +509,7 @@ export const es: TranslationResources = { }, }, hoverCard: { + copyChangeName: "Copiar marcador o ID de cambio", scriptsAccessibility: "GuionesWorkspace", copyPath: "Copiar ruta", copyBranchName: "Copiar nombre de rama", @@ -843,6 +844,39 @@ export const es: TranslationResources = { hideFolderTree: "Ocultar árbol de carpetas", }, git: { + jujutsu: { + filterBookmarks: "Filtrar marcadores…", + noBookmarks: "No se encontraron marcadores.", + missingBaseBookmark: "{{bookmark}} (no disponible)", + empty: "vacío", + filterBookmarksAndChanges: "Filtrar marcadores y cambios", + noMatches: "No hay marcadores ni cambios que coincidan", + changes: { + title: "Cambios", + countLabel: "{{count}} cambios del espacio de trabajo", + noneAhead: "Aún no hay cambios desde {{baseRef}}", + }, + workingCopy: "Copia de trabajo (@)", + startNewChangeOn: "Iniciar un cambio nuevo en…", + fetch: "Obtener", + fetching: "Obteniendo…", + fetched: "Cambios obtenidos del remoto.", + fetchFailed: "No se pudo obtener del remoto.", + describe: "Describir", + newChange: "Nuevo cambio", + publish: "Publicar marcador", + createPullRequest: "Crear solicitud de cambios", + description: "Descripción", + bookmark: "Marcador", + base: "Marcador base", + title: "Título", + actionComplete: "Acción de Jujutsu completada.", + changeMoved: + "El cambio de la copia de trabajo se movió. Cierra el formulario y vuelve a intentarlo.", + currentChange: "Cambio actual", + noDescription: "(sin descripción)", + conflicts: "Conflictos", + }, actions: { moreOptions: "Más opciones", moreActions: "Más acciones", @@ -1034,6 +1068,7 @@ export const es: TranslationResources = { refreshing: "Refrescante", refresh: "Refrescar", refreshState: "Actualizar el estado de git y {{brand}}", + refreshJujutsuState: "Actualizar el estado de jj y {{brand}}", failedRefresh: "No se pudo actualizar el estado de git.", seeUncommittedChanges: "Ver cambios no confirmados", seeCommittedChanges: "Ver cambios confirmados", @@ -1439,9 +1474,11 @@ export const es: TranslationResources = { 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: { @@ -1467,9 +1504,11 @@ export const es: TranslationResources = { isolation: "Choose the isolation level", startingRef: "Elige por dónde empezar", worktree: "Elige el worktree en el que trabajar", + jujutsuWorkspace: "Elige el espacio de trabajo jj en el que trabajar", launch: "Choose what to launch", }, refPicker: { + searchBookmarks: "Buscar marcadores", startingRef: "Árbitro inicial", intoBase: "en {{baseRef}}", searching: "Búsqueda...", @@ -1500,6 +1539,11 @@ export const es: TranslationResources = { searchPlaceholder: "Buscar worktrees", empty: "No hay worktrees que coincidan.", }, + jujutsuWorkspacePicker: { + title: "Espacio de trabajo", + searchPlaceholder: "Buscar espacios de trabajo jj", + empty: "No hay espacios de trabajo jj que coincidan.", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index df0f83763..47d078e04 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -508,6 +508,7 @@ export const fr: TranslationResources = { }, }, hoverCard: { + copyChangeName: "Copier le signet ou l'ID du changement", scriptsAccessibility: "Scripts de l’espace de travail", copyPath: "Copier le chemin", copyBranchName: "Copier le nom de la branche", @@ -844,6 +845,39 @@ export const fr: TranslationResources = { hideFolderTree: "Masquer l’arborescence des dossiers", }, git: { + jujutsu: { + filterBookmarks: "Filtrer les signets…", + noBookmarks: "Aucun signet trouvé.", + missingBaseBookmark: "{{bookmark}} (introuvable)", + empty: "vide", + filterBookmarksAndChanges: "Filtrer les signets et les changements", + noMatches: "Aucun signet ni changement correspondant", + changes: { + title: "Changements", + countLabel: "{{count}} changements de l'espace de travail", + noneAhead: "Aucun changement depuis {{baseRef}} pour l'instant", + }, + workingCopy: "Copie de travail (@)", + startNewChangeOn: "Commencer un nouveau changement sur…", + fetch: "Récupérer", + fetching: "Récupération…", + fetched: "Récupéré depuis le dépôt distant.", + fetchFailed: "Impossible de récupérer depuis le dépôt distant.", + describe: "Décrire", + newChange: "Nouveau changement", + publish: "Publier le signet", + createPullRequest: "Créer une demande de fusion", + description: "Description", + bookmark: "Signet", + base: "Signet de base", + title: "Titre", + actionComplete: "Action Jujutsu terminée.", + changeMoved: + "Le changement de la copie de travail a évolué. Fermez le formulaire et réessayez.", + currentChange: "Changement actuel", + noDescription: "(sans description)", + conflicts: "Conflits", + }, actions: { moreOptions: "Plus d’options", moreActions: "Plus d’actions", @@ -1026,6 +1060,7 @@ export const fr: TranslationResources = { refreshing: "Actualisation…", refresh: "Actualiser", refreshState: "Actualiser l’état de git et de {{brand}}", + refreshJujutsuState: "Actualiser l’état de jj et de {{brand}}", failedRefresh: "Impossible d’actualiser l’état git.", seeUncommittedChanges: "Voir les modifications non commitées", seeCommittedChanges: "Voir les modifications commitées", @@ -1432,9 +1467,11 @@ export const fr: TranslationResources = { 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: { @@ -1460,9 +1497,11 @@ export const fr: TranslationResources = { isolation: "Choisir le niveau d’isolation", startingRef: "Choisir le point de départ", worktree: "Choisir le worktree où travailler", + jujutsuWorkspace: "Choisir l’espace de travail jj où travailler", launch: "Choisir quoi lancer", }, refPicker: { + searchBookmarks: "Rechercher des signets", startingRef: "Réf. de départ", intoBase: "vers {{baseRef}}", searching: "Recherche…", @@ -1493,6 +1532,11 @@ export const fr: TranslationResources = { searchPlaceholder: "Rechercher des worktrees", empty: "Aucun worktree correspondant.", }, + jujutsuWorkspacePicker: { + title: "Espace de travail", + searchPlaceholder: "Rechercher des espaces de travail jj", + empty: "Aucun espace de travail jj correspondant.", + }, launch: { title: "Que lancer ?", chat: "Chat", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index b36cb380b..fba77beb9 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -509,6 +509,7 @@ export const ja: TranslationResources = { }, }, hoverCard: { + copyChangeName: "ブックマークまたは変更 ID をコピー", scriptsAccessibility: "ワークスペーススクリプト", copyPath: "パスをコピー", copyBranchName: "ブランチ名をコピー", @@ -839,6 +840,38 @@ export const ja: TranslationResources = { hideFolderTree: "フォルダツリーを非表示", }, git: { + jujutsu: { + filterBookmarks: "ブックマークを絞り込む…", + noBookmarks: "ブックマークが見つかりません。", + missingBaseBookmark: "{{bookmark}}(見つかりません)", + empty: "空", + filterBookmarksAndChanges: "ブックマークと変更を絞り込む", + noMatches: "一致するブックマークや変更はありません", + changes: { + title: "変更", + countLabel: "ワークスペースの変更 {{count}} 件", + noneAhead: "{{baseRef}} 以降の変更はまだありません", + }, + workingCopy: "作業コピー (@)", + startNewChangeOn: "新しい変更を開始する場所…", + fetch: "フェッチ", + fetching: "フェッチ中…", + fetched: "リモートからフェッチしました。", + fetchFailed: "リモートからフェッチできませんでした。", + describe: "説明を設定", + newChange: "新しい変更", + publish: "ブックマークを公開", + createPullRequest: "プルリクエストを作成", + description: "説明", + bookmark: "ブックマーク", + base: "ベースのブックマーク", + title: "タイトル", + actionComplete: "Jujutsu の操作が完了しました。", + changeMoved: "作業コピーの変更が移動しました。フォームを閉じて再試行してください。", + currentChange: "現在の変更", + noDescription: "(説明なし)", + conflicts: "競合", + }, actions: { moreOptions: "その他のオプション", moreActions: "その他のアクション", @@ -1014,6 +1047,7 @@ export const ja: TranslationResources = { refreshing: "更新中", refresh: "更新", refreshState: "gitと{{brand}}の状態を更新", + refreshJujutsuState: "jjと{{brand}}の状態を更新", failedRefresh: "gitの状態の更新に失敗しました。", seeUncommittedChanges: "未コミットの変更を表示", seeCommittedChanges: "コミット済みの変更を表示", @@ -1417,9 +1451,11 @@ export const ja: TranslationResources = { title: "新しいワークスペース", create: "作成", isolation: { + jujutsu: "新しい jj ワークスペース", local: "プロジェクトディレクトリ", worktree: "新しいワークツリー", existing: "既存のワークツリー", + existingJujutsu: "既存の jj ワークスペース", label: "分離方法", }, fields: { @@ -1445,9 +1481,11 @@ export const ja: TranslationResources = { isolation: "Choose the isolation level", startingRef: "開始点を選択", worktree: "作業するワークツリーを選択", + jujutsuWorkspace: "作業する jj ワークスペースを選択", launch: "Choose what to launch", }, refPicker: { + searchBookmarks: "ブックマークを検索", startingRef: "開始Ref", intoBase: "{{baseRef}}に", searching: "検索中...", @@ -1478,6 +1516,11 @@ export const ja: TranslationResources = { searchPlaceholder: "ワークツリーを検索", empty: "一致するワークツリーがありません。", }, + jujutsuWorkspacePicker: { + title: "ワークスペース", + searchPlaceholder: "jj ワークスペースを検索", + empty: "一致する jj ワークスペースはありません。", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/i18n/resources/ko.ts b/packages/app/src/i18n/resources/ko.ts index 3ec77e0b3..1d263a557 100644 --- a/packages/app/src/i18n/resources/ko.ts +++ b/packages/app/src/i18n/resources/ko.ts @@ -504,6 +504,7 @@ export const ko: TranslationResources = { }, }, hoverCard: { + copyChangeName: "북마크 또는 변경 ID 복사", scriptsAccessibility: "워크스페이스 스크립트", copyPath: "경로 복사", copyBranchName: "브랜치 이름 복사", @@ -835,6 +836,38 @@ export const ko: TranslationResources = { hideFolderTree: "폴더 트리 숨기기", }, git: { + jujutsu: { + filterBookmarks: "북마크 필터…", + noBookmarks: "북마크를 찾을 수 없습니다.", + missingBaseBookmark: "{{bookmark}} (없음)", + empty: "비어 있음", + filterBookmarksAndChanges: "북마크 및 변경 필터", + noMatches: "일치하는 북마크나 변경이 없습니다", + changes: { + title: "변경", + countLabel: "작업 공간 변경 {{count}}개", + noneAhead: "아직 {{baseRef}} 이후 변경이 없습니다", + }, + workingCopy: "작업 사본 (@)", + startNewChangeOn: "새 변경을 시작할 위치…", + fetch: "가져오기", + fetching: "가져오는 중…", + fetched: "원격에서 가져왔습니다.", + fetchFailed: "원격에서 가져오지 못했습니다.", + describe: "설명 작성", + newChange: "새 변경", + publish: "북마크 게시", + createPullRequest: "풀 리퀘스트 생성", + description: "설명", + bookmark: "북마크", + base: "기준 북마크", + title: "제목", + actionComplete: "Jujutsu 작업이 완료되었습니다.", + changeMoved: "작업 복사본의 변경이 이동했습니다. 양식을 닫고 다시 시도하세요.", + currentChange: "현재 변경 사항", + noDescription: "(설명 없음)", + conflicts: "충돌", + }, actions: { moreOptions: "옵션 더 보기", moreActions: "작업 더 보기", @@ -1007,6 +1040,7 @@ export const ko: TranslationResources = { refreshing: "새로고침 중", refresh: "새로고침", refreshState: "Git 및 {{brand}} 상태 새로고침", + refreshJujutsuState: "jj 및 {{brand}} 상태 새로고침", failedRefresh: "Git 상태를 새로고침하지 못했습니다.", seeUncommittedChanges: "커밋되지 않은 변경 사항 보기", seeCommittedChanges: "커밋된 변경 사항 보기", @@ -1409,9 +1443,11 @@ export const ko: TranslationResources = { title: "새 워크스페이스", create: "생성", isolation: { + jujutsu: "새 jj 작업 공간", local: "프로젝트 디렉터리", worktree: "새 워크트리", existing: "기존 워크트리", + existingJujutsu: "기존 jj 작업 공간", label: "격리", }, fields: { @@ -1437,9 +1473,11 @@ export const ko: TranslationResources = { isolation: "Choose the isolation level", startingRef: "시작 위치를 선택하세요", worktree: "작업할 워크트리를 선택하세요", + jujutsuWorkspace: "작업할 jj 작업 공간 선택", launch: "Choose what to launch", }, refPicker: { + searchBookmarks: "북마크 검색", startingRef: "시작 ref", intoBase: "{{baseRef}}(으)로", searching: "검색 중...", @@ -1470,6 +1508,11 @@ export const ko: TranslationResources = { searchPlaceholder: "워크트리 검색", empty: "일치하는 워크트리가 없습니다.", }, + jujutsuWorkspacePicker: { + title: "작업 공간", + searchPlaceholder: "jj 작업 공간 검색", + empty: "일치하는 jj 작업 공간이 없습니다.", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index a6fdb9baf..2c623ff45 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -508,6 +508,7 @@ export const ptBR: TranslationResources = { }, }, hoverCard: { + copyChangeName: "Copiar marcador ou ID da alteração", scriptsAccessibility: "Scripts do workspace", copyPath: "Copiar caminho", copyBranchName: "Copiar nome da branch", @@ -839,6 +840,39 @@ export const ptBR: TranslationResources = { hideFolderTree: "Ocultar árvore de pastas", }, git: { + jujutsu: { + filterBookmarks: "Filtrar marcadores…", + noBookmarks: "Nenhum marcador encontrado.", + missingBaseBookmark: "{{bookmark}} (ausente)", + empty: "vazia", + filterBookmarksAndChanges: "Filtrar marcadores e alterações", + noMatches: "Nenhum marcador ou alteração correspondente", + changes: { + title: "Alterações", + countLabel: "{{count}} alterações do espaço de trabalho", + noneAhead: "Nenhuma alteração desde {{baseRef}} ainda", + }, + workingCopy: "Cópia de trabalho (@)", + startNewChangeOn: "Iniciar nova alteração em…", + fetch: "Buscar", + fetching: "Buscando…", + fetched: "Buscado do remoto.", + fetchFailed: "Não foi possível buscar do remoto.", + describe: "Descrever", + newChange: "Nova alteração", + publish: "Publicar marcador", + createPullRequest: "Criar solicitação de pull", + description: "Descrição", + bookmark: "Marcador", + base: "Marcador base", + title: "Título", + actionComplete: "Ação do Jujutsu concluída.", + changeMoved: + "A alteração da cópia de trabalho mudou. Feche o formulário e tente novamente.", + currentChange: "Alteração atual", + noDescription: "(sem descrição)", + conflicts: "Conflitos", + }, actions: { moreOptions: "Mais opções", moreActions: "Mais ações", @@ -1024,6 +1058,7 @@ export const ptBR: TranslationResources = { refreshing: "Atualizando", refresh: "Atualizar", refreshState: "Atualizar estado do git e do {{brand}}", + refreshJujutsuState: "Atualizar estado do jj e do {{brand}}", failedRefresh: "Falha ao atualizar estado do git.", seeUncommittedChanges: "Ver alterações sem commit", seeCommittedChanges: "Ver alterações com commit", @@ -1429,9 +1464,11 @@ export const ptBR: TranslationResources = { 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: { @@ -1457,9 +1494,11 @@ export const ptBR: TranslationResources = { isolation: "Choose the isolation level", startingRef: "Escolha de onde começar", worktree: "Escolha o worktree em que trabalhar", + jujutsuWorkspace: "Escolha o espaço de trabalho jj em que trabalhar", launch: "Choose what to launch", }, refPicker: { + searchBookmarks: "Buscar marcadores", startingRef: "Ref inicial", intoBase: "em {{baseRef}}", searching: "Buscando...", @@ -1490,6 +1529,11 @@ export const ptBR: TranslationResources = { searchPlaceholder: "Buscar worktrees", empty: "Nenhum worktree correspondente.", }, + jujutsuWorkspacePicker: { + title: "Espaço de trabalho", + searchPlaceholder: "Pesquisar espaços de trabalho jj", + empty: "Nenhum espaço de trabalho jj correspondente.", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index c90551edd..b434aa0d3 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -509,6 +509,7 @@ export const ru: TranslationResources = { }, }, hoverCard: { + copyChangeName: "Копировать закладку или ID изменения", scriptsAccessibility: "Скрипты рабочего пространства", copyPath: "Копировать путь", copyBranchName: "Копировать имя ветки", @@ -844,6 +845,38 @@ export const ru: TranslationResources = { hideFolderTree: "Скрыть дерево папок", }, git: { + jujutsu: { + filterBookmarks: "Фильтр закладок…", + noBookmarks: "Закладки не найдены.", + missingBaseBookmark: "{{bookmark}} (отсутствует)", + empty: "пусто", + filterBookmarksAndChanges: "Фильтр закладок и изменений", + noMatches: "Нет подходящих закладок или изменений", + changes: { + title: "Изменения", + countLabel: "Изменений в рабочем пространстве: {{count}}", + noneAhead: "Пока нет изменений после {{baseRef}}", + }, + workingCopy: "Рабочая копия (@)", + startNewChangeOn: "Начать новое изменение на…", + fetch: "Получить", + fetching: "Получение…", + fetched: "Изменения получены с удалённого репозитория.", + fetchFailed: "Не удалось получить изменения с удалённого репозитория.", + describe: "Добавить описание", + newChange: "Новое изменение", + publish: "Опубликовать закладку", + createPullRequest: "Создать запрос на слияние", + description: "Описание", + bookmark: "Закладка", + base: "Базовая закладка", + title: "Заголовок", + actionComplete: "Действие Jujutsu выполнено.", + changeMoved: "Изменение рабочей копии переместилось. Закройте форму и повторите попытку.", + currentChange: "Текущее изменение", + noDescription: "(без описания)", + conflicts: "Конфликты", + }, actions: { moreOptions: "Дополнительные параметры", moreActions: "Дополнительные действия", @@ -1019,6 +1052,7 @@ export const ru: TranslationResources = { refreshing: "Обновление", refresh: "Обновить", refreshState: "Обновить состояние Git и {{brand}}", + refreshJujutsuState: "Обновить состояние jj и {{brand}}", failedRefresh: "Не удалось обновить состояние Git.", seeUncommittedChanges: "Показать незафиксированные изменения", seeCommittedChanges: "Показать зафиксированные изменения", @@ -1422,9 +1456,11 @@ export const ru: TranslationResources = { title: "Новое рабочее пространство", create: "Создать", isolation: { + jujutsu: "Новое рабочее пространство jj", local: "Папка проекта", worktree: "Новый worktree", existing: "Существующий worktree", + existingJujutsu: "Существующее рабочее пространство jj", label: "Изоляция", }, fields: { @@ -1450,9 +1486,11 @@ export const ru: TranslationResources = { isolation: "Выберите уровень изоляции", startingRef: "Выберите, с чего начать", worktree: "Выберите worktree для работы", + jujutsuWorkspace: "Выберите рабочее пространство jj", launch: "Выберите, что запустить", }, refPicker: { + searchBookmarks: "Поиск закладок", startingRef: "Исходная точка", intoBase: "в ветку {{baseRef}}", searching: "Идет поиск...", @@ -1483,6 +1521,11 @@ export const ru: TranslationResources = { searchPlaceholder: "Поиск worktree", empty: "Нет подходящих worktree.", }, + jujutsuWorkspacePicker: { + title: "Рабочее пространство", + searchPlaceholder: "Поиск рабочих пространств jj", + empty: "Нет подходящих рабочих пространств jj.", + }, launch: { title: "Что запустить", chat: "Чат", diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index c4442a589..7f44b92b7 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -503,6 +503,7 @@ export const zhCN: TranslationResources = { }, }, hoverCard: { + copyChangeName: "复制书签或更改 ID", scriptsAccessibility: "Workspace scripts", copyPath: "复制路径", copyBranchName: "复制分支名称", @@ -831,6 +832,38 @@ export const zhCN: TranslationResources = { hideFolderTree: "隐藏文件夹树", }, git: { + jujutsu: { + filterBookmarks: "筛选书签…", + noBookmarks: "未找到书签。", + missingBaseBookmark: "{{bookmark}}(已丢失)", + empty: "空", + filterBookmarksAndChanges: "筛选书签和更改", + noMatches: "没有匹配的书签或更改", + changes: { + title: "更改", + countLabel: "{{count}} 个工作区更改", + noneAhead: "自 {{baseRef}} 以来尚无更改", + }, + workingCopy: "工作副本 (@)", + startNewChangeOn: "在…上开始新更改", + fetch: "获取", + fetching: "正在获取…", + fetched: "已从远程获取。", + fetchFailed: "无法从远程获取。", + describe: "设置描述", + newChange: "新建变更", + publish: "发布书签", + createPullRequest: "创建拉取请求", + description: "描述", + bookmark: "书签", + base: "基准书签", + title: "标题", + actionComplete: "Jujutsu 操作已完成。", + changeMoved: "工作副本的变更已移动。关闭表单后重试。", + currentChange: "当前变更", + noDescription: "(无描述)", + conflicts: "冲突", + }, actions: { moreOptions: "更多选项", moreActions: "更多操作", @@ -992,6 +1025,7 @@ export const zhCN: TranslationResources = { refreshing: "正在刷新", refresh: "刷新", refreshState: "刷新 git 和 {{brand}} 状态", + refreshJujutsuState: "刷新 jj 和 {{brand}} 状态", failedRefresh: "刷新 git 状态失败。", seeUncommittedChanges: "查看未 commit 的变更", seeCommittedChanges: "查看已 commit 的变更", @@ -1391,9 +1425,11 @@ export const zhCN: TranslationResources = { title: "新建 workspace", create: "创建", isolation: { + jujutsu: "新的 jj 工作区", local: "项目目录", worktree: "新建 worktree", existing: "已有 worktree", + existingJujutsu: "已有 jj 工作区", label: "隔离", }, fields: { @@ -1419,9 +1455,11 @@ export const zhCN: TranslationResources = { isolation: "Choose the isolation level", startingRef: "选择起始位置", worktree: "选择要工作的 worktree", + jujutsuWorkspace: "选择要使用的 jj 工作区", launch: "Choose what to launch", }, refPicker: { + searchBookmarks: "搜索书签", startingRef: "起始 ref", intoBase: "进入 {{baseRef}}", searching: "正在搜索...", @@ -1452,6 +1490,11 @@ export const zhCN: TranslationResources = { searchPlaceholder: "搜索 worktree", empty: "没有匹配的 worktree。", }, + jujutsuWorkspacePicker: { + title: "工作区", + searchPlaceholder: "搜索 jj 工作区", + empty: "没有匹配的 jj 工作区。", + }, launch: { title: "What to launch", chat: "Chat", diff --git a/packages/app/src/runtime/replica-cache/index.ts b/packages/app/src/runtime/replica-cache/index.ts index dcae14550..8a5db3dc4 100644 --- a/packages/app/src/runtime/replica-cache/index.ts +++ b/packages/app/src/runtime/replica-cache/index.ts @@ -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(); diff --git a/packages/app/src/screens/new-workspace-picker-item.test.ts b/packages/app/src/screens/new-workspace-picker-item.test.ts index 2d67c7067..ab39d2f73 100644 --- a/packages/app/src/screens/new-workspace-picker-item.test.ts +++ b/packages/app/src/screens/new-workspace-picker-item.test.ts @@ -9,6 +9,7 @@ import { defaultBasePickerItem, pickerItemToCheckoutRequest, refListOptions, + selectWorkspaceBase, startsNewBranch, type PickerItem, } from "./new-workspace-picker-item"; @@ -490,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: "@" }); + }); +}); diff --git a/packages/app/src/screens/new-workspace-picker-item.ts b/packages/app/src/screens/new-workspace-picker-item.ts index 3b577803c..d5569a116 100644 --- a/packages/app/src/screens/new-workspace-picker-item.ts +++ b/packages/app/src/screens/new-workspace-picker-item.ts @@ -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"; @@ -172,6 +172,31 @@ function repositoryBasePickerItem(status: BaseRefCheckoutStatus): PickerItem | n 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. @@ -306,6 +331,7 @@ export function buildPickerOptionData(input: { branchDetails: readonly BranchPickerDetail[]; prItems: readonly ForgeSearchItem[]; baseItem: PickerItem | null; + currentChangeLabel?: string; }): PickerOptionData { const itemById = new Map(); const timedOptions: TimedOption[] = []; @@ -320,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); diff --git a/packages/app/src/screens/new-workspace-screen.tsx b/packages/app/src/screens/new-workspace-screen.tsx index 05c1dcc92..35bd9b9e7 100644 --- a/packages/app/src/screens/new-workspace-screen.tsx +++ b/packages/app/src/screens/new-workspace-screen.tsx @@ -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,8 +1215,9 @@ 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); @@ -1355,9 +1363,7 @@ export function NewWorkspaceScreen({ const checkoutRequest = checkoutStatusForCreate ? checkoutRequestOrExplain( () => - setup.checkoutRequestFor( - selectedItem ?? defaultBasePickerItem(checkoutStatusForCreate), - ), + setup.checkoutRequestFor(selectWorkspaceBase(selectedItem, checkoutStatusForCreate)), t, ) : undefined; @@ -1617,6 +1623,7 @@ export function NewWorkspaceScreen({ onOpenChange: handleIsolationPickerOpenChange, choice, canCreateWorktree, + isJujutsu, onSelect: setIsolation, existingWorktrees, existingWorktreePath, @@ -1641,6 +1648,8 @@ export function NewWorkspaceScreen({ actionFor: refActionFor, onActionChange: setup.chooseRefAction, canChooseAction: supportsRefActions, + canChooseChangeRequest: allowsGitRefActions, + isJujutsu, changeRequestContext, }, launch: { @@ -1737,11 +1746,41 @@ export function NewWorkspaceScreen({ * The setup model, built with what the screen has this render so a plugin item's mount effect can * already run commands, and kept current on every commit. */ +function useWorkspaceCheckoutCapabilities(input: { + serverId: string; + sourceDirectory: string | null; + pickerOpen: boolean; + isConnected: boolean; + hasClient: boolean; +}) { + const { status: checkoutStatus } = useCheckoutStatusQuery({ + serverId: input.serverId, + cwd: input.sourceDirectory ?? "", + }); + const supportsRefActions = useHostFeature(input.serverId, "worktreeRefActions"); + const isJujutsu = checkoutStatus?.vcs?.kind === "jujutsu" || Boolean(checkoutStatus?.jujutsu); + const capabilities = checkoutStatus?.vcs?.capabilities; + const allowsGitRefActions = capabilities?.gitMutations ?? !isJujutsu; + const pickerQueryEnabled = + input.pickerOpen && input.isConnected && input.hasClient && input.sourceDirectory !== null; + return { + checkoutStatus, + isJujutsu, + allowsGitRefActions, + isolatedWorkspaceSupported: capabilities?.isolatedWorkspace, + supportsRefActions: supportsRefActions && allowsGitRefActions, + pickerQueryEnabled, + changeRequestSearchEnabled: pickerQueryEnabled && allowsGitRefActions, + }; +} + function usePluginSetup(input: { serverId: string; project: Parameters[0] | null; worktrees: SetupInputs["worktrees"]; supportsMultiplicity: boolean; + supportsRefActions: boolean; + isolatedWorkspaceSupported: boolean | undefined; pendingAction: Parameters[0]["pendingAction"]; isDraftHandoffActive: boolean; updatePreferences: ReturnType["updatePreferences"]; @@ -1752,6 +1791,8 @@ function usePluginSetup(input: { project, worktrees, supportsMultiplicity, + supportsRefActions, + isolatedWorkspaceSupported, pendingAction, isDraftHandoffActive, updatePreferences, @@ -1760,7 +1801,8 @@ function usePluginSetup(input: { const worktreeSupport = project ? getWorktreeSupportForHostProject({ project, serverId }) : "unsupported"; - const canCreateWorktree = supportsMultiplicity && worktreeSupport !== "unsupported"; + const canCreateWorktree = + supportsMultiplicity && (isolatedWorkspaceSupported ?? worktreeSupport !== "unsupported"); const locked = isNewWorkspacePending({ pendingAction, isDraftHandoffActive }); const supportsMetadata = useHostFeature(serverId, "entityMetadata"); const projectId = project ? getHostProjectId(project, serverId) : null; @@ -1769,7 +1811,6 @@ function usePluginSetup(input: { () => (projectId && projectName ? { id: projectId, name: projectName } : null), [projectId, projectName], ); - const supportsRefActions = useHostFeature(serverId, "worktreeRefActions"); const inputs: SetupInputs = { serverId, locked, diff --git a/packages/app/src/screens/new-workspace/form/index.tsx b/packages/app/src/screens/new-workspace/form/index.tsx index 2bb097b2a..d7c02766d 100644 --- a/packages/app/src/screens/new-workspace/form/index.tsx +++ b/packages/app/src/screens/new-workspace/form/index.tsx @@ -89,6 +89,8 @@ export interface NewWorkspaceFormProps { isolation: PickerControl & { choice: IsolationChoice; canCreateWorktree: boolean; + /** The source is a Jujutsu checkout, so a new isolated workspace is a jj workspace. */ + isJujutsu?: boolean; onSelect: (isolation: Isolation) => void; /** The project's worktrees other than its own directory, newest first. */ existingWorktrees: readonly ExistingWorktree[]; @@ -112,6 +114,9 @@ export interface NewWorkspaceFormProps { onActionChange: (list: RefList, action: RefAction) => void; /** Whether the host lets the user pick the action; otherwise each list keeps its default. */ canChooseAction: boolean; + canChooseChangeRequest: boolean; + /** The source uses jj, so the branch list is its bookmarks. */ + isJujutsu?: boolean; /** Selects the forge's change-request words, such as "Merge requests" on GitLab. */ changeRequestContext: "mr" | undefined; }; @@ -184,6 +189,12 @@ function useIsolationPicker(input: { const { t } = useTranslation(); const { isolation, projectDirectory, isPending } = input; const { canCreateWorktree, choice, existingWorktrees, onSelect, onOpenChange } = isolation; + const newLabel = isolation.isJujutsu + ? t("newWorkspace.isolation.jujutsu") + : t("newWorkspace.isolation.worktree"); + const existingLabel = isolation.isJujutsu + ? t("newWorkspace.isolation.existingJujutsu") + : t("newWorkspace.isolation.existing"); const { existingWorktreePath, onChooseExistingWorktree } = isolation; const newestWorktree = existingWorktrees[0]; // The worktree options are omitted entirely (not disabled) when they cannot apply: a project @@ -195,10 +206,10 @@ function useIsolationPicker(input: { description: projectDirectory ? shortenPath(projectDirectory) : undefined, }; if (!canCreateWorktree) return [local]; - const worktree = { id: "worktree", label: t("newWorkspace.isolation.worktree") }; + const worktree = { id: "worktree", label: newLabel }; if (!newestWorktree) return [local, worktree]; - return [local, worktree, { id: "existing", label: t("newWorkspace.isolation.existing") }]; - }, [canCreateWorktree, newestWorktree, projectDirectory, t]); + return [local, worktree, { id: "existing", label: existingLabel }]; + }, [canCreateWorktree, existingLabel, newLabel, newestWorktree, projectDirectory, t]); const handleSelect = useCallback( (id: string) => { // The newest worktree is the likeliest one to return to, so it is the first pick. @@ -217,8 +228,8 @@ function useIsolationPicker(input: { ); const value = { local: t("newWorkspace.isolation.local"), - worktree: t("newWorkspace.isolation.worktree"), - existing: t("newWorkspace.isolation.existing"), + worktree: newLabel, + existing: existingLabel, }[choice]; const icon = { local: folderIcon, worktree: branchIcon, existing: existingWorktreeIcon }[choice]; return { value, icon, options, onSelect: handleSelect, renderOption }; @@ -289,7 +300,8 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) { const { options: allOptions, itemById, selectedItem, selectedOptionId, worktrees } = base; const { open: openPicker, onSelect, actionFor, onActionChange } = base; const context = base.changeRequestContext; - const [list, setList] = useState("branch"); + const [requestedList, setList] = useState("branch"); + const list = base.canChooseChangeRequest ? requestedList : "branch"; const action = actionFor[list]; const options = useMemo( () => refListOptions({ options: allOptions, itemById, selectedOptionId, kind: list, action }), @@ -326,11 +338,15 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) { action={action} onActionChange={handleActionChange} canChooseAction={base.canChooseAction} + canChooseChangeRequest={base.canChooseChangeRequest} changeRequestContext={context} /> ), - [action, base.canChooseAction, context, handleActionChange, list], + [action, base.canChooseAction, base.canChooseChangeRequest, context, handleActionChange, list], ); + const branchSearchPlaceholder = base.isJujutsu + ? t("newWorkspace.refPicker.searchBookmarks") + : t("newWorkspace.refPicker.searchBranches"); const shown = itemById.get(selectedOptionId); const shownList = refListOf(shown); const shownAction = actionFor[shownList]; @@ -355,7 +371,7 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) { searchPlaceholder: list === "github-pr" ? t("newWorkspace.refPicker.searchPullRequests", { context }) - : t("newWorkspace.refPicker.searchBranches"), + : branchSearchPlaceholder, trigger: { ...trigger, icon, @@ -371,6 +387,25 @@ function useRefPicker(base: NewWorkspaceFormProps["base"], isPending: boolean) { * that does not apply to the selected project is left out. Host always shows, even with one host, so * its Add host action keeps multi-host discoverable. */ +/** The Existing worktree picker's text; jj projects list their workspaces. */ +function useWorktreePickerText(isJujutsu?: boolean) { + const { t } = useTranslation(); + if (isJujutsu) { + return { + title: t("newWorkspace.jujutsuWorkspacePicker.title"), + tooltip: t("newWorkspace.tooltips.jujutsuWorkspace"), + searchPlaceholder: t("newWorkspace.jujutsuWorkspacePicker.searchPlaceholder"), + empty: t("newWorkspace.jujutsuWorkspacePicker.empty"), + }; + } + return { + title: t("newWorkspace.worktreePicker.title"), + tooltip: t("newWorkspace.tooltips.worktree"), + searchPlaceholder: t("newWorkspace.worktreePicker.searchPlaceholder"), + empty: t("newWorkspace.worktreePicker.empty"), + }; +} + export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement { const { t } = useTranslation(); const { isCompact, isPending, pluginItems, project, host, isolation, base, launch } = props; @@ -408,6 +443,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement [host.selectedServerId], ); const { choice } = isolation; + const worktreeText = useWorktreePickerText(isolation.isJujutsu); const projectField = ( diff --git a/packages/app/src/screens/new-workspace/form/ref-picker-toolbar.tsx b/packages/app/src/screens/new-workspace/form/ref-picker-toolbar.tsx index 5af8bcb94..880305895 100644 --- a/packages/app/src/screens/new-workspace/form/ref-picker-toolbar.tsx +++ b/packages/app/src/screens/new-workspace/form/ref-picker-toolbar.tsx @@ -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 ( <> - + {canChooseChangeRequest ? ( + + ) : null} {canChooseAction ? (