From 672f34ca0aa0e85fb52c04d167dc4ffa7a27c70b Mon Sep 17 00:00:00 2001 From: brennanb2025 Date: Mon, 29 Jun 2026 04:03:46 -0700 Subject: [PATCH 01/52] Add Git Graph view showing all branches and commit history MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a full-pane Git Graph tab that visualizes the whole repository — all local branches, remote-tracking branches, tags, merges, and HEAD — instead of only the current branch's linear history shown in the Source Control sidebar today. - Add an opt-in allRefs scope to the shared git-history loader so the graph query enumerates --branches --remotes --tags HEAD; the default current-branch path is unchanged. The flag is forwarded through the local IPC, SSH provider, and runtime RPC boundaries so it works in all environments. - New git-graph tab content type with a full-pane GitGraphPane that reuses the existing graph SVG/row components, virtualizes rows, and opens a commit's combined diff on click. Wired into the tab strip as a chip (activate/close/keyboard-cycle) mirroring the simulator pattern. - Entry point: an Open Git Graph button in the Source Control commits header (Cmd/Ctrl-click opens in a split). Closes #4521 Co-authored-by: Orca --- src/main/ipc/filesystem.test.ts | 28 ++++ src/main/ipc/filesystem.ts | 6 +- src/main/runtime/rpc/methods/git-params.ts | 3 +- src/main/runtime/rpc/methods/git.test.ts | 33 +++- src/main/runtime/rpc/methods/git.ts | 3 +- .../src/components/git-graph/GitGraphPane.tsx | 150 ++++++++++++++++++ .../git-graph/useGitGraphHistory.ts | 92 +++++++++++ .../right-sidebar/GitHistoryPanel.tsx | 134 +++++----------- .../right-sidebar/GitHistoryRow.tsx | 37 ++++- .../right-sidebar/SourceControl.tsx | 13 ++ .../right-sidebar/useGitHistoryPanelResize.ts | 108 +++++++++++++ .../tab-bar/TabBar.context-menu.test.ts | 49 ++++++ .../src/components/tab-bar/TabBar.tsx | 74 ++++++++- .../tab-bar/group-tab-order.test.ts | 34 ++++ .../src/components/tab-bar/group-tab-order.ts | 10 ++ .../tab-bar/reconcile-order.test.ts | 11 ++ .../src/components/tab-bar/reconcile-order.ts | 13 +- .../components/tab-group/TabGroupPanel.tsx | 20 ++- .../components/tab-group/useTabDragSplit.ts | 2 +- .../tab-group/useTabGroupWorkspaceModel.ts | 7 +- src/renderer/src/i18n/locales/en.json | 24 ++- src/renderer/src/i18n/locales/es.json | 24 ++- src/renderer/src/i18n/locales/ja.json | 24 ++- src/renderer/src/i18n/locales/ko.json | 24 ++- src/renderer/src/i18n/locales/zh.json | 24 ++- src/renderer/src/store/slices/tabs.test.ts | 78 +++++++++ src/renderer/src/store/slices/tabs.ts | 41 +++++ src/shared/git-history-graph.test.ts | 34 ++++ src/shared/git-history-types.ts | 3 + src/shared/git-history.test.ts | 60 +++++++ src/shared/git-history.ts | 35 ++++ src/shared/types.ts | 1 + 32 files changed, 1084 insertions(+), 115 deletions(-) create mode 100644 src/renderer/src/components/git-graph/GitGraphPane.tsx create mode 100644 src/renderer/src/components/git-graph/useGitGraphHistory.ts create mode 100644 src/renderer/src/components/right-sidebar/useGitHistoryPanelResize.ts diff --git a/src/main/ipc/filesystem.test.ts b/src/main/ipc/filesystem.test.ts index 2bad27ca47b2..4b8ad4372117 100644 --- a/src/main/ipc/filesystem.test.ts +++ b/src/main/ipc/filesystem.test.ts @@ -2245,4 +2245,32 @@ describe('registerFilesystemHandlers', () => { excludePaths: ['/home/user/repo/worktrees/feature'] }) }) + + // Guards the git:history handler's explicit `{ limit, baseRef, allRefs }` + // rebuild — it re-destructures rather than spreading, so a dropped allRefs + // would silently break the repo-wide Git Graph on the SSH path. + it('git:history forwards allRefs to the SSH git provider', async () => { + const getHistoryMock = vi.fn().mockResolvedValue({ + items: [], + hasIncomingChanges: false, + hasOutgoingChanges: false, + hasMore: false, + limit: 200 + }) + getSshGitProviderMock.mockReturnValue({ getHistory: getHistoryMock }) + + registerFilesystemHandlers(store as never) + + await handlers.get('git:history')!(null, { + worktreePath: '/remote/repo', + connectionId: 'conn-1', + limit: 200, + allRefs: true + }) + + expect(getHistoryMock).toHaveBeenCalledWith( + '/remote/repo', + expect.objectContaining({ limit: 200, allRefs: true }) + ) + }) }) diff --git a/src/main/ipc/filesystem.ts b/src/main/ipc/filesystem.ts index 188933d0a2e4..7865b25db8d6 100644 --- a/src/main/ipc/filesystem.ts +++ b/src/main/ipc/filesystem.ts @@ -1152,7 +1152,11 @@ export function registerFilesystemHandlers( _event, args: { worktreePath: string; connectionId?: string } & GitHistoryOptions ): Promise => { - const options: GitHistoryOptions = { limit: args.limit, baseRef: args.baseRef } + const options: GitHistoryOptions = { + limit: args.limit, + baseRef: args.baseRef, + allRefs: args.allRefs + } if (args.connectionId) { const provider = getSshGitProvider(args.connectionId) if (!provider) { diff --git a/src/main/runtime/rpc/methods/git-params.ts b/src/main/runtime/rpc/methods/git-params.ts index 8f9d511dfca6..19a1022cb02a 100644 --- a/src/main/runtime/rpc/methods/git-params.ts +++ b/src/main/runtime/rpc/methods/git-params.ts @@ -69,7 +69,8 @@ export const GitCommitCompare = WorktreeSelector.extend({ export const GitHistory = WorktreeSelector.extend({ limit: z.number().int().min(1).max(200).optional(), - baseRef: z.string().nullable().optional() + baseRef: z.string().nullable().optional(), + allRefs: z.boolean().optional() }) export const GitBranchDiff = GitFilePath.extend({ diff --git a/src/main/runtime/rpc/methods/git.test.ts b/src/main/runtime/rpc/methods/git.test.ts index 850276906a53..d67a5ec402d2 100644 --- a/src/main/runtime/rpc/methods/git.test.ts +++ b/src/main/runtime/rpc/methods/git.test.ts @@ -187,7 +187,38 @@ describe('git RPC methods', () => { expect(runtime.getRuntimeGitHistory).toHaveBeenCalledWith('id:wt-1', { limit: 25, - baseRef: 'origin/main' + baseRef: 'origin/main', + allRefs: undefined + }) + expect(response).toMatchObject({ ok: true, result: history }) + }) + + it('forwards allRefs to the runtime git history for the repo-wide graph', async () => { + const history = { + items: [], + hasIncomingChanges: false, + hasOutgoingChanges: false, + hasMore: false, + limit: 200 + } + const runtime = { + getRuntimeId: () => 'test-runtime', + getRuntimeGitHistory: vi.fn().mockResolvedValue(history) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: GIT_METHODS }) + + const response = await dispatcher.dispatch( + makeRequest('git.history', { + worktree: 'id:wt-1', + limit: 200, + allRefs: true + }) + ) + + expect(runtime.getRuntimeGitHistory).toHaveBeenCalledWith('id:wt-1', { + limit: 200, + baseRef: undefined, + allRefs: true }) expect(response).toMatchObject({ ok: true, result: history }) }) diff --git a/src/main/runtime/rpc/methods/git.ts b/src/main/runtime/rpc/methods/git.ts index 1e4923f672af..c440d2d07bd6 100644 --- a/src/main/runtime/rpc/methods/git.ts +++ b/src/main/runtime/rpc/methods/git.ts @@ -124,7 +124,8 @@ export const GIT_METHODS: RpcMethod[] = [ handler: async (params, { runtime }) => runtime.getRuntimeGitHistory(params.worktree, { limit: params.limit, - baseRef: params.baseRef + baseRef: params.baseRef, + allRefs: params.allRefs }) }), defineMethod({ diff --git a/src/renderer/src/components/git-graph/GitGraphPane.tsx b/src/renderer/src/components/git-graph/GitGraphPane.tsx new file mode 100644 index 000000000000..726d4343c99b --- /dev/null +++ b/src/renderer/src/components/git-graph/GitGraphPane.tsx @@ -0,0 +1,150 @@ +import React, { useCallback, useMemo, useRef } from 'react' +import { useVirtualizer } from '@tanstack/react-virtual' +import { Network, RefreshCw } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { cn } from '@/lib/utils' +import { + buildDefaultGitHistoryColorMap, + buildGitHistoryViewModels +} from '../../../../shared/git-history-graph' +import { GitHistoryRow } from '../right-sidebar/GitHistoryRow' +import { useGitHistoryCommitActions } from '../right-sidebar/useGitHistoryCommitActions' +import { translate } from '@/i18n/i18n' +import { useGitGraphHistory } from './useGitGraphHistory' + +// Why: each Git Graph row is a fixed-height GitHistoryRow (min-h-[26px]); a +// constant estimate keeps the virtualizer cheap for up to 200 rows. +const GIT_GRAPH_ROW_HEIGHT = 28 +const GIT_GRAPH_ROW_OVERSCAN = 12 + +function GitGraphPane({ worktreeId }: { worktreeId: string }): React.JSX.Element { + const { state, refresh, context } = useGitGraphHistory(worktreeId) + const result = state.result + const loading = state.status === 'loading' || state.status === 'refreshing' + + const viewModels = useMemo(() => { + if (!result) { + return [] + } + // All-refs mode has no incoming/outgoing or remote/base refs (the loader + // forks before computing them), so pass currentRef only. + return buildGitHistoryViewModels( + result.items, + buildDefaultGitHistoryColorMap(result), + result.currentRef, + undefined, + undefined + ) + }, [result]) + + // Full-pane tab opens commits in its own group; no split target to resolve. + const noSplitTarget = useCallback(() => undefined, []) + const { openHistoryCommitDiff } = useGitHistoryCommitActions({ + activeWorktreeId: worktreeId, + worktreePath: context?.worktreePath ?? null, + activeRepoSettings: context?.settings, + resolveSplitTargetGroupId: noSplitTarget + }) + + const scrollRef = useRef(null) + const virtualizer = useVirtualizer({ + count: viewModels.length, + getScrollElement: () => scrollRef.current, + estimateSize: () => GIT_GRAPH_ROW_HEIGHT, + overscan: GIT_GRAPH_ROW_OVERSCAN, + getItemKey: (index) => viewModels[index]?.historyItem.id ?? `missing:${index}` + }) + + const count = result?.items.length ?? 0 + const virtualItems = virtualizer.getVirtualItems() + + return ( +
+
+
+ + {result?.hasMore && ( +
+ {translate( + 'auto.components.git.graph.GitGraphPane.9a3f5c2e70', + 'Showing {{value0}} of many commits across all branches', + { value0: result.limit } + )} +
+ )} + + {state.status === 'error' && !result ? ( +
+ {state.error} + +
+ ) : (state.status === 'idle' || state.status === 'loading') && !result ? ( +
+ + + {translate('auto.components.git.graph.GitGraphPane.2c8b1f0a93', 'Loading graph...')} + +
+ ) : viewModels.length === 0 ? ( +
+ {translate('auto.components.git.graph.GitGraphPane.4e7d6a1c08', 'No commits yet')} +
+ ) : ( +
+
+ {virtualItems.map((virtualRow) => { + const viewModel = viewModels[virtualRow.index] + if (!viewModel) { + return null + } + return ( +
+ void openHistoryCommitDiff(item)} + /> +
+ ) + })} +
+
+ )} +
+ ) +} + +export default React.memo(GitGraphPane) diff --git a/src/renderer/src/components/git-graph/useGitGraphHistory.ts b/src/renderer/src/components/git-graph/useGitGraphHistory.ts new file mode 100644 index 000000000000..e4565fb9ff53 --- /dev/null +++ b/src/renderer/src/components/git-graph/useGitGraphHistory.ts @@ -0,0 +1,92 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useRepoById, useWorktreeById } from '@/store/selectors' +import { useAppStore } from '@/store' +import { getConnectionId } from '@/lib/connection-context' +import { getRepoOwnerRoutedSettings } from '@/lib/repo-runtime-owner' +import { getRuntimeGitHistory, type RuntimeGitContext } from '@/runtime/runtime-git-client' +import { GIT_HISTORY_MAX_LIMIT, type GitHistoryResult } from '../../../../shared/git-history' +import { translate } from '@/i18n/i18n' + +export type GitGraphHistoryState = + | { status: 'idle' | 'loading'; result?: GitHistoryResult; error?: string } + | { status: 'refreshing' | 'ready'; result: GitHistoryResult; error?: string } + | { status: 'error'; result?: GitHistoryResult; error: string } + +export type UseGitGraphHistory = { + state: GitGraphHistoryState + refresh: () => void + context: RuntimeGitContext | null +} + +// Loads the repo-wide (all refs) history for the Git Graph pane. Routes by the +// repo OWNER host like Source Control, and always requests the MAX limit so the +// graph isn't silently capped at the linear default. +export function useGitGraphHistory(worktreeId: string): UseGitGraphHistory { + const worktree = useWorktreeById(worktreeId) + const repo = useRepoById(worktree?.repoId ?? null) + const settings = useAppStore((s) => s.settings) + const worktreePath = worktree?.path ?? null + + const [state, setState] = useState({ status: 'idle' }) + // Bumped on Refresh; also re-runs the load when worktree/path changes. + const [reloadToken, setReloadToken] = useState(0) + const requestIdRef = useRef(0) + + // Why: memoize the routed context so its identity only changes when a routing + // input does. A fresh object each render would (a) re-fire the fetch effect on + // every render and (b) rebuild the consumer's commit-action callbacks, which + // depend on context.settings, on every render. + const context = useMemo(() => { + if (!worktreePath) { + return null + } + return { + settings: getRepoOwnerRoutedSettings(settings, repo ?? null), + worktreeId, + worktreePath, + connectionId: getConnectionId(worktreeId) ?? undefined + } + }, [repo, settings, worktreeId, worktreePath]) + + useEffect(() => { + const ctx = context + if (!ctx) { + setState({ status: 'idle' }) + return + } + const requestId = (requestIdRef.current += 1) + setState((prev) => + prev.status === 'ready' || prev.status === 'refreshing' + ? { status: 'refreshing', result: prev.result } + : { status: 'loading' } + ) + getRuntimeGitHistory(ctx, { allRefs: true, limit: GIT_HISTORY_MAX_LIMIT }) + .then((result) => { + if (requestId !== requestIdRef.current) { + return + } + setState({ status: 'ready', result }) + }) + .catch((error: unknown) => { + if (requestId !== requestIdRef.current) { + return + } + setState({ + status: 'error', + error: + error instanceof Error + ? error.message + : translate( + 'auto.components.git.graph.useGitGraphHistory.3d9c2e7b41', + 'Failed to load git graph' + ) + }) + }) + }, [context, reloadToken]) + + const refresh = useCallback(() => { + setReloadToken((token) => token + 1) + }, []) + + return { state, refresh, context } +} diff --git a/src/renderer/src/components/right-sidebar/GitHistoryPanel.tsx b/src/renderer/src/components/right-sidebar/GitHistoryPanel.tsx index bc60150cd773..fcaef9491a0b 100644 --- a/src/renderer/src/components/right-sidebar/GitHistoryPanel.tsx +++ b/src/renderer/src/components/right-sidebar/GitHistoryPanel.tsx @@ -1,5 +1,5 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' -import { ChevronDown, CircleHelp, RefreshCw } from 'lucide-react' +import { ChevronDown, CircleHelp, Network, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' @@ -17,6 +17,11 @@ import { type GitHistoryCommitAction } from './GitHistoryCommitContextMenu' import type { SourceControlRowOpenEvent } from './source-control-split-open' +import { + MAX_GIT_HISTORY_PANEL_HEIGHT, + MIN_GIT_HISTORY_PANEL_HEIGHT, + useGitHistoryPanelResize +} from './useGitHistoryPanelResize' import { translate } from '@/i18n/i18n' export type GitHistoryPanelState = @@ -24,27 +29,12 @@ export type GitHistoryPanelState = | { status: 'refreshing' | 'ready'; result: GitHistoryResult; error?: string } | { status: 'error'; result?: GitHistoryResult; error: string } -const DEFAULT_GIT_HISTORY_PANEL_HEIGHT = 256 -const MIN_GIT_HISTORY_PANEL_HEIGHT = 96 -const MAX_GIT_HISTORY_PANEL_HEIGHT = 520 -const MAX_GIT_HISTORY_PANEL_VIEWPORT_HEIGHT = '33vh' - -type GitHistoryResizeSession = { - startY: number - startHeight: number - previousCursor: string - previousUserSelect: string -} - -function clampGitHistoryPanelHeight(height: number): number { - return Math.min(MAX_GIT_HISTORY_PANEL_HEIGHT, Math.max(MIN_GIT_HISTORY_PANEL_HEIGHT, height)) -} - export function GitHistoryPanel({ state, collapsed, onToggle, onRefresh, + onOpenGraph, onOpenCommit, onLoadCommitFiles, onOpenCommitFile, @@ -54,6 +44,8 @@ export function GitHistoryPanel({ collapsed: boolean onToggle: () => void onRefresh: () => void + // Opens the repo-wide Git Graph full-pane tab; Cmd/Ctrl-click splits. + onOpenGraph?: (event: SourceControlRowOpenEvent) => void onOpenCommit?: (item: GitHistoryItem) => void onLoadCommitFiles?: (item: GitHistoryItem) => Promise onOpenCommitFile?: ( @@ -82,8 +74,8 @@ export function GitHistoryPanel({ const loading = state.status === 'loading' || state.status === 'refreshing' const count = result?.items.length ?? 0 - const [panelHeight, setPanelHeight] = useState(DEFAULT_GIT_HISTORY_PANEL_HEIGHT) - const resizeSessionRef = useRef(null) + const { panelHeight, startResize, handleResizeKeyDown, expandedBodyStyle } = + useGitHistoryPanelResize(collapsed) const [expanded, setExpanded] = useState>(() => new Set()) const [filesByCommit, setFilesByCommit] = useState>({}) @@ -141,78 +133,7 @@ export function GitHistoryPanel({ [expanded, onLoadCommitFiles] ) - const stopResize = useCallback((): void => { - const session = resizeSessionRef.current - if (!session) { - return - } - resizeSessionRef.current = null - document.body.style.cursor = session.previousCursor - document.body.style.userSelect = session.previousUserSelect - }, []) - - const handleResizePointerMove = useCallback((event: PointerEvent): void => { - const session = resizeSessionRef.current - if (!session) { - return - } - setPanelHeight(clampGitHistoryPanelHeight(session.startHeight + session.startY - event.clientY)) - }, []) - - useEffect(() => { - window.addEventListener('pointermove', handleResizePointerMove) - window.addEventListener('pointerup', stopResize) - window.addEventListener('pointercancel', stopResize) - window.addEventListener('blur', stopResize) - return () => { - window.removeEventListener('pointermove', handleResizePointerMove) - window.removeEventListener('pointerup', stopResize) - window.removeEventListener('pointercancel', stopResize) - window.removeEventListener('blur', stopResize) - stopResize() - } - }, [handleResizePointerMove, stopResize]) - - const startResize = useCallback( - (event: React.PointerEvent): void => { - if (collapsed) { - return - } - event.preventDefault() - resizeSessionRef.current = { - startY: event.clientY, - startHeight: panelHeight, - previousCursor: document.body.style.cursor, - previousUserSelect: document.body.style.userSelect - } - document.body.style.cursor = 'row-resize' - document.body.style.userSelect = 'none' - event.currentTarget.setPointerCapture(event.pointerId) - }, - [collapsed, panelHeight] - ) - - const handleResizeKeyDown = useCallback((event: React.KeyboardEvent): void => { - const step = event.shiftKey ? 32 : 16 - if (event.key === 'ArrowUp') { - event.preventDefault() - setPanelHeight((height) => clampGitHistoryPanelHeight(height + step)) - } else if (event.key === 'ArrowDown') { - event.preventDefault() - setPanelHeight((height) => clampGitHistoryPanelHeight(height - step)) - } else if (event.key === 'Home') { - event.preventDefault() - setPanelHeight(MIN_GIT_HISTORY_PANEL_HEIGHT) - } else if (event.key === 'End') { - event.preventDefault() - setPanelHeight(MAX_GIT_HISTORY_PANEL_HEIGHT) - } - }, []) - const expandedBodyClassName = 'overflow-y-auto scrollbar-sleek' - const expandedBodyStyle = { - height: `min(${panelHeight}px, ${MAX_GIT_HISTORY_PANEL_VIEWPORT_HEIGHT})` - } return (
@@ -274,6 +195,39 @@ export function GitHistoryPanel({ )} + {onOpenGraph && ( + + + + + + {translate( + 'auto.components.right.sidebar.GitHistoryPanel.4b8e2f1a06', + 'Open Git Graph' + )} + + + )}
+ )} {activeTab && activeTab.contentType !== 'terminal' && activeTab.contentType !== 'browser' && - activeTab.contentType !== 'simulator' && ( + activeTab.contentType !== 'simulator' && + activeTab.contentType !== 'git-graph' && (
{/* Why: split groups render editor content inside a plain relative pane body instead of the legacy flex column in Terminal.tsx. */} diff --git a/src/renderer/src/components/tab-group/useTabDragSplit.ts b/src/renderer/src/components/tab-group/useTabDragSplit.ts index 6d945d071455..588ef0ee5b1f 100644 --- a/src/renderer/src/components/tab-group/useTabDragSplit.ts +++ b/src/renderer/src/components/tab-group/useTabDragSplit.ts @@ -55,7 +55,7 @@ export type TabDragItemData = { groupId: string unifiedTabId: string visibleTabId: string - tabType: 'terminal' | 'editor' | 'browser' | 'simulator' + tabType: 'terminal' | 'editor' | 'browser' | 'simulator' | 'git-graph' /** Rendered by the DragOverlay ghost that follows the cursor across * groups. Source tab strips use overflow-hidden, so without the overlay * the dragged tab would be invisible once the cursor leaves its own diff --git a/src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.ts b/src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.ts index fe50561d270f..884eb791da7e 100644 --- a/src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.ts +++ b/src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.ts @@ -279,7 +279,9 @@ export function useTabGroupWorkspaceModel({ destroyWorkspaceWebviews(browserState.browserPagesByWorkspace, item.entityId) closeBrowserTab(item.entityId) closeUnifiedTab(item.id) - } else if (item.contentType === 'simulator') { + } else if (item.contentType === 'simulator' || item.contentType === 'git-graph') { + // git-graph (like simulator) has no backing OpenFile entity, so close + // the unified tab directly without touching openFiles. closeUnifiedTab(item.id) } else { const canCloseTab = closeEditorIfUnreferenced(item.entityId, item.id) @@ -344,7 +346,8 @@ export function useTabGroupWorkspaceModel({ closeUnifiedTab(item.id) } else if (item.contentType === 'terminal') { closeTab(item.entityId) - } else if (item.contentType === 'simulator') { + } else if (item.contentType === 'simulator' || item.contentType === 'git-graph') { + // git-graph (like simulator) has no backing OpenFile entity. closeUnifiedTab(item.id) } else { const canCloseTab = closeEditorIfUnreferenced(item.entityId, item.id) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index a0dffdb2cd2f..b1e816902667 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -255,6 +255,9 @@ }, "linear": { "37d36984d0": "Linear connection was superseded by a newer request." + }, + "tabs": { + "7c3f1a9e0d": "Git Graph" } } }, @@ -2531,7 +2534,8 @@ "1ff1c77616": "browser", "586d2ac445": "terminal", "addSplitPane": "Add split pane", - "closePaneColumn": "Close split pane" + "closePaneColumn": "Close split pane", + "6b2f0a1c9d": "Loading graph..." }, "AiVaultSessionDropLayer": { "dropOntoTerminalPane": "Drop onto a terminal pane to resume this session.", @@ -8647,7 +8651,8 @@ "62e685d5ec": "idle", "111e1d0db4": "error", "e5e81e59a6": "Resize commits", - "6d1e0a7c3b": "Failed to load commit files" + "6d1e0a7c3b": "Failed to load commit files", + "4b8e2f1a06": "Open Git Graph" }, "HostedReviewActions": { "4d5fb5a284": "Close", @@ -12086,6 +12091,21 @@ "contextMenu": { "copy": "Copy" } + }, + "git": { + "graph": { + "GitGraphPane": { + "6f0a2d1b84": "Git Graph", + "b71e9c4d22": "Refresh graph", + "9a3f5c2e70": "Showing {{value0}} of many commits across all branches", + "2c8b1f0a93": "Loading graph...", + "4e7d6a1c08": "No commits yet", + "5d2e9b7a14": "Retry" + }, + "useGitGraphHistory": { + "3d9c2e7b41": "Failed to load git graph" + } + } } }, "i18n": { diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index fca634a3a8fa..62e0dfe8acec 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -255,6 +255,9 @@ }, "linear": { "37d36984d0": "La conexión de Linear fue reemplazada por una solicitud más reciente." + }, + "tabs": { + "7c3f1a9e0d": "Git Graph" } } }, @@ -2531,7 +2534,8 @@ "1ff1c77616": "navegador", "586d2ac445": "terminal", "addSplitPane": "Agregar panel dividido", - "closePaneColumn": "Cerrar panel dividido" + "closePaneColumn": "Cerrar panel dividido", + "6b2f0a1c9d": "Loading graph..." }, "AiVaultSessionDropLayer": { "dropOntoTerminalPane": "Suelta sobre un panel de terminal para reanudar esta sesión.", @@ -8647,7 +8651,8 @@ "62e685d5ec": "idle", "111e1d0db4": "error", "e5e81e59a6": "Cambiar el tamaño de las commits", - "6d1e0a7c3b": "No se pudieron cargar los archivos del commit" + "6d1e0a7c3b": "No se pudieron cargar los archivos del commit", + "4b8e2f1a06": "Open Git Graph" }, "HostedReviewActions": { "4d5fb5a284": "Cerca", @@ -12086,6 +12091,21 @@ "contextMenu": { "copy": "Copy" } + }, + "git": { + "graph": { + "GitGraphPane": { + "6f0a2d1b84": "Git Graph", + "b71e9c4d22": "Refresh graph", + "9a3f5c2e70": "Showing {{value0}} of many commits across all branches", + "2c8b1f0a93": "Loading graph...", + "4e7d6a1c08": "No commits yet", + "5d2e9b7a14": "Retry" + }, + "useGitGraphHistory": { + "3d9c2e7b41": "Failed to load git graph" + } + } } }, "i18n": { diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 3d697e34e054..97482219af89 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -255,6 +255,9 @@ }, "linear": { "37d36984d0": "Linear 接続は新しいリクエストに置き換えられました。" + }, + "tabs": { + "7c3f1a9e0d": "Git Graph" } } }, @@ -2531,7 +2534,8 @@ "1ff1c77616": "ブラウザ", "586d2ac445": "ターミナル", "addSplitPane": "分割ペインを追加", - "closePaneColumn": "分割ペインを閉じる" + "closePaneColumn": "分割ペインを閉じる", + "6b2f0a1c9d": "Loading graph..." }, "AiVaultSessionDropLayer": { "dropOntoTerminalPane": "このセッションを再開するにはターミナルペインにドロップしてください。", @@ -8647,7 +8651,8 @@ "62e685d5ec": "idle", "111e1d0db4": "エラー", "e5e81e59a6": "commits のサイズ変更", - "6d1e0a7c3b": "commit ファイルを読み込めませんでした" + "6d1e0a7c3b": "commit ファイルを読み込めませんでした", + "4b8e2f1a06": "Open Git Graph" }, "HostedReviewActions": { "4d5fb5a284": "閉じる", @@ -12086,6 +12091,21 @@ "contextMenu": { "copy": "Copy" } + }, + "git": { + "graph": { + "GitGraphPane": { + "6f0a2d1b84": "Git Graph", + "b71e9c4d22": "Refresh graph", + "9a3f5c2e70": "Showing {{value0}} of many commits across all branches", + "2c8b1f0a93": "Loading graph...", + "4e7d6a1c08": "No commits yet", + "5d2e9b7a14": "Retry" + }, + "useGitGraphHistory": { + "3d9c2e7b41": "Failed to load git graph" + } + } } }, "i18n": { diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index e83d9dbd1d7d..36d0d8e4dfd6 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -255,6 +255,9 @@ }, "linear": { "37d36984d0": "더 새로운 요청이 있어 Linear 연결 요청을 건너뛰었습니다." + }, + "tabs": { + "7c3f1a9e0d": "Git Graph" } } }, @@ -2531,7 +2534,8 @@ "1ff1c77616": "브라우저", "586d2ac445": "터미널", "addSplitPane": "분할 창 추가", - "closePaneColumn": "분할 창 닫기" + "closePaneColumn": "분할 창 닫기", + "6b2f0a1c9d": "Loading graph..." }, "AiVaultSessionDropLayer": { "dropOntoTerminalPane": "이 세션을 재개하려면 terminal 창에 놓으세요.", @@ -8647,7 +8651,8 @@ "62e685d5ec": "idle", "111e1d0db4": "오류", "e5e81e59a6": "commits 크기 조정", - "6d1e0a7c3b": "commit 파일을 로드하지 못했습니다" + "6d1e0a7c3b": "commit 파일을 로드하지 못했습니다", + "4b8e2f1a06": "Open Git Graph" }, "HostedReviewActions": { "4d5fb5a284": "닫기", @@ -12086,6 +12091,21 @@ "contextMenu": { "copy": "Copy" } + }, + "git": { + "graph": { + "GitGraphPane": { + "6f0a2d1b84": "Git Graph", + "b71e9c4d22": "Refresh graph", + "9a3f5c2e70": "Showing {{value0}} of many commits across all branches", + "2c8b1f0a93": "Loading graph...", + "4e7d6a1c08": "No commits yet", + "5d2e9b7a14": "Retry" + }, + "useGitGraphHistory": { + "3d9c2e7b41": "Failed to load git graph" + } + } } }, "i18n": { diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 3c91ead991ac..c0749e4cea46 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -255,6 +255,9 @@ }, "linear": { "37d36984d0": "Linear 连接已被新的请求取代。" + }, + "tabs": { + "7c3f1a9e0d": "Git Graph" } } }, @@ -2531,7 +2534,8 @@ "1ff1c77616": "浏览器", "586d2ac445": "终端", "addSplitPane": "添加拆分窗格", - "closePaneColumn": "关闭拆分窗格" + "closePaneColumn": "关闭拆分窗格", + "6b2f0a1c9d": "Loading graph..." }, "AiVaultSessionDropLayer": { "dropOntoTerminalPane": "拖放到终端面板以恢复此会话。", @@ -8647,7 +8651,8 @@ "62e685d5ec": "idle", "111e1d0db4": "错误", "e5e81e59a6": "调整 commits 大小", - "6d1e0a7c3b": "无法加载提交文件" + "6d1e0a7c3b": "无法加载提交文件", + "4b8e2f1a06": "Open Git Graph" }, "HostedReviewActions": { "4d5fb5a284": "关闭", @@ -12086,6 +12091,21 @@ "contextMenu": { "copy": "Copy" } + }, + "git": { + "graph": { + "GitGraphPane": { + "6f0a2d1b84": "Git Graph", + "b71e9c4d22": "Refresh graph", + "9a3f5c2e70": "Showing {{value0}} of many commits across all branches", + "2c8b1f0a93": "Loading graph...", + "4e7d6a1c08": "No commits yet", + "5d2e9b7a14": "Retry" + }, + "useGitGraphHistory": { + "3d9c2e7b41": "Failed to load git graph" + } + } } }, "i18n": { diff --git a/src/renderer/src/store/slices/tabs.test.ts b/src/renderer/src/store/slices/tabs.test.ts index 4bbcc75cd2d2..289d0d9e182b 100644 --- a/src/renderer/src/store/slices/tabs.test.ts +++ b/src/renderer/src/store/slices/tabs.test.ts @@ -1847,7 +1847,85 @@ describe('TabsSlice', () => { }) }) + describe('openGitGraph', () => { + it('creates exactly one git-graph tab and re-activates it without duplicating', () => { + const first = store.getState().openGitGraph(WT) + expect(first).not.toBeNull() + expect(first!.contentType).toBe('git-graph') + expect(first!.entityId).toBe(`${WT}::git-graph`) + + // Activate a different tab, then reopen — must reuse the same tab. + store.getState().createUnifiedTab(WT, 'terminal') + const second = store.getState().openGitGraph(WT) + + expect(second!.id).toBe(first!.id) + const graphTabs = store + .getState() + .unifiedTabsByWorktree[WT].filter((tab) => tab.contentType === 'git-graph') + expect(graphTabs).toHaveLength(1) + expect(store.getState().getActiveTab(WT)?.id).toBe(first!.id) + }) + + it('re-homes the existing git-graph tab into a split target instead of duplicating', () => { + const created = store.getState().openGitGraph(WT) + const sourceGroupId = created!.groupId + const targetGroupId = store.getState().createEmptySplitGroup(WT, sourceGroupId, 'right') + expect(targetGroupId).not.toBeNull() + + const moved = store.getState().openGitGraph(WT, { targetGroupId: targetGroupId! }) + + expect(moved!.id).toBe(created!.id) + expect(moved!.groupId).toBe(targetGroupId) + const graphTabs = store + .getState() + .unifiedTabsByWorktree[WT].filter((tab) => tab.contentType === 'git-graph') + expect(graphTabs).toHaveLength(1) + }) + }) + describe('reconcileWorktreeTabModel', () => { + it('keeps git-graph tabs because they have no backing OpenFile entity', () => { + const groupId = 'g-graph' + store.setState({ + unifiedTabsByWorktree: { + [WT]: [ + { + id: 'git-graph-1', + entityId: `${WT}::git-graph`, + groupId, + worktreeId: WT, + contentType: 'git-graph', + label: 'Git Graph', + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + groupsByWorktree: { + [WT]: [ + { + id: groupId, + worktreeId: WT, + activeTabId: 'git-graph-1', + tabOrder: ['git-graph-1'] + } + ] + }, + activeGroupIdByWorktree: { [WT]: groupId }, + tabsByWorktree: { [WT]: [] } + }) + + const result = store.getState().reconcileWorktreeTabModel(WT) + + expect(result.renderableTabCount).toBe(1) + expect(result.activeRenderableTabId).toBe('git-graph-1') + expect(store.getState().unifiedTabsByWorktree[WT].map((tab) => tab.id)).toEqual([ + 'git-graph-1' + ]) + }) + it('drops unified tabs whose backing content no longer exists', () => { const groupId = 'g-1' store.setState({ diff --git a/src/renderer/src/store/slices/tabs.ts b/src/renderer/src/store/slices/tabs.ts index 00cf7fcc1c7d..40093d5bcafd 100644 --- a/src/renderer/src/store/slices/tabs.ts +++ b/src/renderer/src/store/slices/tabs.ts @@ -35,6 +35,7 @@ import { createBrowserUuid } from '@/lib/browser-uuid' import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { folderWorkspaceKey } from '../../../../shared/workspace-scope' +import { translate } from '@/i18n/i18n' export type TabSplitDirection = 'left' | 'right' | 'up' | 'down' @@ -173,6 +174,10 @@ export type TabsSlice = { activeRenderableTabId: string | null } hydrateTabsSession: (session: WorkspaceSessionState) => void + // Opens (or reuses) the single repo-wide Git Graph tab for a worktree. With a + // targetGroupId (Cmd/Ctrl-click split), re-homes the existing tab into that + // group rather than duplicating it — one git-graph tab per worktree. + openGitGraph: (worktreeId: string, options?: { targetGroupId?: string }) => Tab | null } // Why: keep the TerminalTab (tabsByWorktree) pin in sync with the unified-tab @@ -1899,6 +1904,11 @@ export const createTabsSlice: StateCreator = (set, if (tab.contentType === 'simulator') { return true } + // Repo-wide Git Graph has no backing OpenFile/entity (synthetic entityId), + // so it must survive reconcile like simulator or it is pruned each pass. + if (tab.contentType === 'git-graph') { + return true + } return liveEditorIds.has(tab.entityId) } @@ -2036,6 +2046,37 @@ export const createTabsSlice: StateCreator = (set, } }, + openGitGraph: (worktreeId, options) => { + const entityId = `${worktreeId}::git-graph` + const existing = + get().unifiedTabsByWorktree[worktreeId]?.find((tab) => tab.contentType === 'git-graph') ?? + null + + if (existing) { + // One git-graph tab per worktree: re-home it on Cmd/Ctrl-click split + // instead of duplicating the (repo-wide, group-independent) view. + if (options?.targetGroupId && existing.groupId !== options.targetGroupId) { + get().moveUnifiedTabToGroup(existing.id, options.targetGroupId, { activate: true }) + } + get().activateTab(existing.id) + const surfaced = get().getTab(existing.id) + if (surfaced) { + get().focusGroup(worktreeId, surfaced.groupId) + } + return surfaced + } + + const created = get().createUnifiedTab(worktreeId, 'git-graph', { + entityId, + label: translate('auto.store.slices.tabs.7c3f1a9e0d', 'Git Graph'), + ...(options?.targetGroupId ? { targetGroupId: options.targetGroupId } : {}), + activate: true + }) + get().activateTab(created.id) + get().focusGroup(worktreeId, created.groupId) + return created + }, + hydrateTabsSession: (session) => { const state = get() const validWorktreeIds = new Set( diff --git a/src/shared/git-history-graph.test.ts b/src/shared/git-history-graph.test.ts index 489b4a59ff31..2ce4745359e0 100644 --- a/src/shared/git-history-graph.test.ts +++ b/src/shared/git-history-graph.test.ts @@ -195,6 +195,40 @@ describe('git history graph model', () => { ) }) + it('keeps divergent multi-tip branches on separate lanes (repo-wide all-refs)', () => { + // Two branch tips with independent roots and no shared history — the shape an + // all-refs Git Graph query produces. The current branch lane must stay put + // while the second tip occupies its own lane, and both roots terminate cleanly. + const currentRef = branch('main', 'A1') + const otherRef = branch('experiment', 'B1') + const viewModels = buildGitHistoryViewModels( + [ + item('A1', ['A2'], [currentRef]), + item('B1', ['B2'], [otherRef]), + item('A2', []), + item('B2', []) + ], + buildDefaultGitHistoryColorMap({ currentRef }), + currentRef + ) + + // A1 is HEAD and feeds its parent into the first lane. + expect(viewModels[0]!.kind).toBe('HEAD') + expect(viewModels[0]!.outputSwimlanes).toEqual([{ id: 'A2', color: GIT_HISTORY_REF_COLOR }]) + // B1's parent joins as a distinct second lane that does not collide with A2's. + expect(viewModels[1]!.outputSwimlanes).toContainEqual({ + id: 'A2', + color: GIT_HISTORY_REF_COLOR + }) + const b2Lane = viewModels[1]!.outputSwimlanes.find((node) => node.id === 'B2') + expect(b2Lane).toBeDefined() + expect(b2Lane!.color).not.toBe(GIT_HISTORY_REF_COLOR) + // Each root has no parents, so its lane drains rather than continuing. + expect(viewModels[2]!.historyItem.parentIds).toEqual([]) + expect(viewModels[3]!.historyItem.parentIds).toEqual([]) + expect(viewModels[3]!.outputSwimlanes).toEqual([]) + }) + it('assigns stable colors to current, remote, and base refs', () => { const currentRef = branch('feature', 'A') const remoteRef = remote('origin/feature', 'R') diff --git a/src/shared/git-history-types.ts b/src/shared/git-history-types.ts index 4e99d4b2eb25..03ed533d3fe6 100644 --- a/src/shared/git-history-types.ts +++ b/src/shared/git-history-types.ts @@ -56,6 +56,9 @@ export type GitHistoryItem = { export type GitHistoryOptions = { limit?: number baseRef?: string | null + // When true, scope the log to all refs (local + remote + tags + HEAD) for the + // repo-wide Git Graph view instead of the active branch's linear history. + allRefs?: boolean } export type GitHistoryResult = { diff --git a/src/shared/git-history.test.ts b/src/shared/git-history.test.ts index ec926d5f0a7d..1dd071ca4045 100644 --- a/src/shared/git-history.test.ts +++ b/src/shared/git-history.test.ts @@ -244,6 +244,66 @@ describe('git history loader', () => { expect(result.hasMore).toBe(true) }) + it('scopes the log to all refs (branches/remotes/tags/HEAD) in allRefs mode', async () => { + const { executor, calls } = createHistoryExecutor() + + const result = await loadGitHistoryFromExecutor(executor, '/repo', { + limit: 50, + allRefs: true + }) + + const logCall = calls.find((args) => args[0] === 'log') + expect(logCall).toEqual( + expect.arrayContaining([ + `--format=${GIT_HISTORY_COMMIT_FORMAT}`, + '-z', + '--topo-order', + '--decorate=full', + '-n51', + '--branches', + '--remotes', + '--tags', + 'HEAD' + ]) + ) + // Must not fall back to the linear single-headOid scope. + expect(logCall).not.toContain(HEAD_OID) + expect(result.currentRef?.name).toBe('feature') + }) + + it('emits no incoming/outgoing boundary rows and no remote/base refs in allRefs mode', async () => { + const { executor, calls } = createHistoryExecutor() + + const result = await loadGitHistoryFromExecutor(executor, '/repo', { + limit: 50, + allRefs: true + }) + + expect(result.hasIncomingChanges).toBe(false) + expect(result.hasOutgoingChanges).toBe(false) + expect(result.remoteRef).toBeUndefined() + expect(result.baseRef).toBeUndefined() + expect(result.mergeBase).toBeUndefined() + // Forked early: no upstream/merge-base round-trips. + expect(calls.some((args) => args[0] === 'for-each-ref')).toBe(false) + expect(calls.some((args) => args[0] === 'merge-base')).toBe(false) + }) + + it('still clamps oversized limits in allRefs mode', async () => { + const { executor, calls } = createHistoryExecutor(GIT_HISTORY_MAX_LIMIT + 1) + + const result = await loadGitHistoryFromExecutor(executor, '/repo', { + limit: 500, + allRefs: true + }) + + const logCall = calls.find((args) => args[0] === 'log') + expect(logCall).toContain(`-n${GIT_HISTORY_MAX_LIMIT + 1}`) + expect(result.items).toHaveLength(GIT_HISTORY_MAX_LIMIT) + expect(result.limit).toBe(GIT_HISTORY_MAX_LIMIT) + expect(result.hasMore).toBe(true) + }) + it('returns an empty result for unborn repositories without running git log', async () => { const executor = vi.fn(async (args: string[]) => { if (args[0] === 'rev-parse') { diff --git a/src/shared/git-history.ts b/src/shared/git-history.ts index 9b5993fd367b..1c56b6483f2e 100644 --- a/src/shared/git-history.ts +++ b/src/shared/git-history.ts @@ -173,6 +173,41 @@ export async function loadGitHistoryFromExecutor( } const { currentRef, branchName } = await resolveCurrentRef(git, cwd, headOid) + + // Repo-wide Git Graph: fork early so the upstream/merge-base/incoming-outgoing + // computation (a "your branch vs upstream" sidebar affordance) never runs — it + // is meaningless across all refs. Still resolve currentRef above for the HEAD + // marker + color-map key. + if (options.allRefs) { + const { stdout } = await git( + [ + 'log', + `--format=${GIT_HISTORY_COMMIT_FORMAT}`, + '-z', + '--topo-order', + '--decorate=full', + `-n${limit + 1}`, + '--branches', + '--remotes', + '--tags', + 'HEAD' + ], + cwd + ) + const parsed = parseGitHistoryLog(stdout) + return { + items: parsed.slice(0, limit), + currentRef, + remoteRef: undefined, + baseRef: undefined, + mergeBase: undefined, + hasIncomingChanges: false, + hasOutgoingChanges: false, + hasMore: parsed.length > limit, + limit + } + } + const [remoteRef, rawBaseRef] = await Promise.all([ resolveUpstreamRef(git, cwd, branchName), resolveNamedRef(git, cwd, options.baseRef) diff --git a/src/shared/types.ts b/src/shared/types.ts index 789d651902c3..b5928793532f 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -766,6 +766,7 @@ export type TabContentType = | 'check-details' | 'browser' | 'simulator' + | 'git-graph' export type WorkspaceVisibleTabType = 'terminal' | 'editor' | 'browser' | 'simulator' export type CtrlTabOrderMode = 'mru' | 'sequential' From 37194db14c1e5efaed19299420ae2a33d8f3c542 Mon Sep 17 00:00:00 2001 From: brennanb2025 Date: Mon, 29 Jun 2026 04:33:21 -0700 Subject: [PATCH 02/52] Address review: virtual-tab guards, nav-order, truncation copy - Treat the Git Graph (and mobile emulator) tab chip as a virtual tab: add an isVirtual contract to EditorFileTab/EditorFileTabContextMenu so rename, copy-path, copy-relative-path, and reveal-in-finder are disabled for tabs whose filePath is a display label, not an on-disk path. Prevents a rename on the synthetic 'Git Graph' path running a real file operation. - Forward gitGraphIds through the legacy reconcileTabOrder fallback in getActiveTabNavOrder so keyboard tab navigation does not drop git-graph tabs when no split-group layout exists yet. - Make the truncation banner explicit: 'Showing first N commits across all branches' (was 'of many'), across all locales. - Tests: virtual-tab hides path actions; git-graph survives the legacy nav-order fallback. Co-authored-by: Orca --- .../src/components/git-graph/GitGraphPane.tsx | 2 +- .../src/components/tab-bar/EditorFileTab.tsx | 10 +- .../tab-bar/EditorFileTabContextMenu.test.tsx | 22 ++++- .../tab-bar/EditorFileTabContextMenu.tsx | 93 +++++++++++-------- .../src/components/tab-bar/TabBar.tsx | 2 + .../tab-bar/group-tab-order.test.ts | 17 ++++ .../src/components/tab-bar/group-tab-order.ts | 13 ++- src/renderer/src/i18n/locales/en.json | 2 +- src/renderer/src/i18n/locales/es.json | 2 +- src/renderer/src/i18n/locales/ja.json | 2 +- src/renderer/src/i18n/locales/ko.json | 2 +- src/renderer/src/i18n/locales/zh.json | 2 +- 12 files changed, 119 insertions(+), 50 deletions(-) diff --git a/src/renderer/src/components/git-graph/GitGraphPane.tsx b/src/renderer/src/components/git-graph/GitGraphPane.tsx index 726d4343c99b..8c23fd6dc3e9 100644 --- a/src/renderer/src/components/git-graph/GitGraphPane.tsx +++ b/src/renderer/src/components/git-graph/GitGraphPane.tsx @@ -94,7 +94,7 @@ function GitGraphPane({ worktreeId }: { worktreeId: string }): React.JSX.Element
{translate( 'auto.components.git.graph.GitGraphPane.9a3f5c2e70', - 'Showing {{value0}} of many commits across all branches', + 'Showing first {{value0}} commits across all branches', { value0: result.limit } )}
diff --git a/src/renderer/src/components/tab-bar/EditorFileTab.tsx b/src/renderer/src/components/tab-bar/EditorFileTab.tsx index 694d03b0b59c..976e2fe1c2e1 100644 --- a/src/renderer/src/components/tab-bar/EditorFileTab.tsx +++ b/src/renderer/src/components/tab-bar/EditorFileTab.tsx @@ -44,7 +44,8 @@ export default function EditorFileTab({ onTogglePin, dragData, dropIndicator, - includeTopTabBorder = true + includeTopTabBorder = true, + isVirtual = false }: { file: OpenFile & { tabId?: string } isActive: boolean @@ -60,6 +61,10 @@ export default function EditorFileTab({ dragData: TabDragItemData dropIndicator?: DropIndicator includeTopTabBorder?: boolean + // Why: callers reuse this tab chrome for synthetic, non-file tabs (Git Graph, + // mobile emulator) whose filePath is a display label, not an on-disk path. + // Such tabs must never expose rename/reveal/copy-path file operations. + isVirtual?: boolean }): React.JSX.Element { const worktree = useWorktreeById(file.worktreeId) const repo = useRepoById(worktree?.repoId ?? null) @@ -103,7 +108,7 @@ export default function EditorFileTab({ const renameCancelledRef = useRef(false) // Only on-disk edit tabs are renameable. Diff, conflict-review, and // combined/virtual views don't point at a single concrete file we can safely rename. - const canRename = file.mode === 'edit' && !file.diffSource && !file.conflict + const canRename = !isVirtual && file.mode === 'edit' && !file.diffSource && !file.conflict const openRenameInput = (): void => { if (!canRename) { @@ -386,6 +391,7 @@ export default function EditorFileTab({ isRenaming={isRenaming} hasTabsToRight={hasTabsToRight} canRename={canRename} + isVirtual={isVirtual} canShowMarkdownPreview={canShowMarkdownPreview} resolvedLanguage={resolvedLanguage} repoConnectionId={repo?.connectionId ?? null} diff --git a/src/renderer/src/components/tab-bar/EditorFileTabContextMenu.test.tsx b/src/renderer/src/components/tab-bar/EditorFileTabContextMenu.test.tsx index 8167bdbda5c1..f6835fb0b3d2 100644 --- a/src/renderer/src/components/tab-bar/EditorFileTabContextMenu.test.tsx +++ b/src/renderer/src/components/tab-bar/EditorFileTabContextMenu.test.tsx @@ -172,7 +172,7 @@ function extractText(node: unknown): string { return el.props && 'children' in el.props ? extractText(el.props.children) : '' } -async function renderMenu(): Promise { +async function renderMenu(overrides: Record = {}): Promise { const module = await import('./EditorFileTabContextMenu') return module.EditorFileTabContextMenu({ open: true, @@ -204,7 +204,8 @@ async function renderMenu(): Promise { onClose: vi.fn(), onCloseAll: vi.fn(), onCloseToRight: vi.fn(), - onOpenMarkdownPreview: vi.fn() + onOpenMarkdownPreview: vi.fn(), + ...overrides }) } @@ -261,6 +262,23 @@ describe('EditorFileTabContextMenu close-all shortcut', () => { expect(findElementsByType(tree, 'DropdownMenuShortcut')).toHaveLength(3) }) + it('hides path-based actions for a virtual (non-file) tab', async () => { + // A synthetic tab (Git Graph, mobile emulator) has a label, not an on-disk + // path, so Copy Path / Copy Relative Path / Reveal must not be offered. + const tree = expandNode(await renderMenu({ isVirtual: true, canRename: false })) + const labels = findElementsByType(tree, 'DropdownMenuItem').map((item) => + extractText(item.props.children) + ) + + expect(labels.some((label) => label.includes('Copy Path'))).toBe(false) + expect(labels.some((label) => label.includes('Copy Relative Path'))).toBe(false) + expect( + labels.some((label) => label.includes('Reveal') || label.includes('Open Containing')) + ).toBe(false) + // Tab-management actions remain available. + expect(labels.some((label) => label.includes('Close'))).toBe(true) + }) + it('hides the shortcut chip when close-all is unassigned', async () => { shortcutLabelMock.mockReturnValue(null) diff --git a/src/renderer/src/components/tab-bar/EditorFileTabContextMenu.tsx b/src/renderer/src/components/tab-bar/EditorFileTabContextMenu.tsx index 184c05d2d975..7bfece28ca8c 100644 --- a/src/renderer/src/components/tab-bar/EditorFileTabContextMenu.tsx +++ b/src/renderer/src/components/tab-bar/EditorFileTabContextMenu.tsx @@ -35,6 +35,9 @@ type EditorFileTabContextMenuProps = { isRenaming: boolean hasTabsToRight: boolean canRename: boolean + // Why: synthetic non-file tabs (Git Graph, mobile emulator) have a label, not + // an on-disk path, so path-based actions (copy path, reveal) must be hidden. + isVirtual?: boolean canShowMarkdownPreview: boolean resolvedLanguage: string repoConnectionId: string | null @@ -68,6 +71,7 @@ export function EditorFileTabContextMenu({ isRenaming, hasTabsToRight, canRename, + isVirtual = false, canShowMarkdownPreview, resolvedLanguage, repoConnectionId, @@ -147,7 +151,9 @@ export function EditorFileTabContextMenu({ 'Close Tabs To The Right' )} - + {/* Only separate the close actions from a section that actually follows; + a fully virtual tab has neither markdown preview nor path actions. */} + {canShowMarkdownPreview || !isVirtual ? : null} {canShowMarkdownPreview ? ( <> ) : null} - { - void window.api.ui.writeClipboardText(file.filePath) - }} - > - - {translate('auto.components.tab.bar.EditorFileTabContextMenu.5b85754786', 'Copy Path')} - - { - void window.api.ui.writeClipboardText(file.relativePath) - }} - > - - {translate( - 'auto.components.tab.bar.EditorFileTabContextMenu.52ce4f4605', - 'Copy Relative Path' - )} - - - { - if ( - shouldBlockEditorTabLocalOpen( - useAppStore.getState().settings, - file.runtimeEnvironmentId, - repoConnectionId - ) - ) { - showLocalPathOpenBlockedToast() - return - } - window.api.shell.openPath(file.filePath) - }} - > - - {revealLabel} - + {/* Path-based actions are meaningless for synthetic non-file tabs whose + filePath is a display label, not an on-disk path. */} + {!isVirtual ? ( + <> + { + void window.api.ui.writeClipboardText(file.filePath) + }} + > + + {translate( + 'auto.components.tab.bar.EditorFileTabContextMenu.5b85754786', + 'Copy Path' + )} + + { + void window.api.ui.writeClipboardText(file.relativePath) + }} + > + + {translate( + 'auto.components.tab.bar.EditorFileTabContextMenu.52ce4f4605', + 'Copy Relative Path' + )} + + + { + if ( + shouldBlockEditorTabLocalOpen( + useAppStore.getState().settings, + file.runtimeEnvironmentId, + repoConnectionId + ) + ) { + showLocalPathOpenBlockedToast() + return + } + window.api.shell.openPath(file.filePath) + }} + > + + {revealLabel} + + + ) : null} ) diff --git a/src/renderer/src/components/tab-bar/TabBar.tsx b/src/renderer/src/components/tab-bar/TabBar.tsx index 0919b4ac090e..b767c203edc0 100644 --- a/src/renderer/src/components/tab-bar/TabBar.tsx +++ b/src/renderer/src/components/tab-bar/TabBar.tsx @@ -1239,6 +1239,7 @@ function TabBarInner({ dragData={dragData} dropIndicator={dropIndicatorByVisibleId.get(item.id) ?? null} includeTopTabBorder={includeTopTabBorder} + isVirtual /> ) } @@ -1276,6 +1277,7 @@ function TabBarInner({ dragData={dragData} dropIndicator={dropIndicatorByVisibleId.get(item.id) ?? null} includeTopTabBorder={includeTopTabBorder} + isVirtual /> ) } diff --git a/src/renderer/src/components/tab-bar/group-tab-order.test.ts b/src/renderer/src/components/tab-bar/group-tab-order.test.ts index 823af9d0ed53..98f22e1e497e 100644 --- a/src/renderer/src/components/tab-bar/group-tab-order.test.ts +++ b/src/renderer/src/components/tab-bar/group-tab-order.test.ts @@ -337,4 +337,21 @@ describe('getActiveTabNavOrder', () => { { type: 'terminal', id: 'term-2' } ]) }) + + it('keeps git-graph tabs in the legacy reconciled order (no active group)', () => { + // Guards the legacy fallback path: without forwarding gitGraphIds the tab is + // dropped from keyboard nav, so it must surface as an editor-typed ref here. + const state = makeState({ + tabBarOrderByWorktree: { wt: ['term-1', 'tab-gg1'] }, + unifiedTabsByWorktree: { wt: [gitGraphTab('tab-gg1', 'g1', 1)] }, + tabsByWorktree: { + // @ts-expect-error — minimal shape + wt: [{ id: 'term-1' }] + } + }) + expect(getActiveTabNavOrder(state, 'wt')).toEqual([ + { type: 'terminal', id: 'term-1' }, + { type: 'editor', id: 'tab-gg1' } + ]) + }) }) diff --git a/src/renderer/src/components/tab-bar/group-tab-order.ts b/src/renderer/src/components/tab-bar/group-tab-order.ts index 6d18cb1e3145..29f3f6f01903 100644 --- a/src/renderer/src/components/tab-bar/group-tab-order.ts +++ b/src/renderer/src/components/tab-bar/group-tab-order.ts @@ -13,6 +13,7 @@ export type ActiveTabNavOrderIds = { editorIds?: string[] browserIds?: string[] simulatorIds?: string[] + gitGraphIds?: string[] } /** @@ -147,6 +148,11 @@ export function getActiveTabNavOrder( (state.unifiedTabsByWorktree[worktreeId] ?? []) .filter((tab) => tab.contentType === 'simulator') .map((tab) => tab.id) + const gitGraphIds = + ids.gitGraphIds ?? + (state.unifiedTabsByWorktree[worktreeId] ?? []) + .filter((tab) => tab.contentType === 'git-graph') + .map((tab) => tab.id) const activeGroupId = state.activeGroupIdByWorktree[worktreeId] const group = activeGroupId @@ -173,12 +179,14 @@ export function getActiveTabNavOrder( terminalIds, editorIds, browserIds, - simulatorIds + simulatorIds, + gitGraphIds ) const terminalIdSet = new Set(terminalIds) const editorIdSet = new Set(editorIds) const browserIdSet = new Set(browserIds) const simulatorIdSet = new Set(simulatorIds) + const gitGraphIdSet = new Set(gitGraphIds) const result: VisibleTabRef[] = [] for (const id of visibleIds) { if (terminalIdSet.has(id)) { @@ -189,6 +197,9 @@ export function getActiveTabNavOrder( result.push({ type: 'browser', id }) } else if (simulatorIdSet.has(id)) { result.push({ type: 'simulator', id }) + } else if (gitGraphIdSet.has(id)) { + // git-graph routes through the editor activation path keyed by tab id. + result.push({ type: 'editor', id }) } } return result diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index b1e816902667..49b97a449f82 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -12097,7 +12097,7 @@ "GitGraphPane": { "6f0a2d1b84": "Git Graph", "b71e9c4d22": "Refresh graph", - "9a3f5c2e70": "Showing {{value0}} of many commits across all branches", + "9a3f5c2e70": "Showing first {{value0}} commits across all branches", "2c8b1f0a93": "Loading graph...", "4e7d6a1c08": "No commits yet", "5d2e9b7a14": "Retry" diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 62e0dfe8acec..f5eb3efde7dd 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -12097,7 +12097,7 @@ "GitGraphPane": { "6f0a2d1b84": "Git Graph", "b71e9c4d22": "Refresh graph", - "9a3f5c2e70": "Showing {{value0}} of many commits across all branches", + "9a3f5c2e70": "Showing first {{value0}} commits across all branches", "2c8b1f0a93": "Loading graph...", "4e7d6a1c08": "No commits yet", "5d2e9b7a14": "Retry" diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 97482219af89..90252675b188 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -12097,7 +12097,7 @@ "GitGraphPane": { "6f0a2d1b84": "Git Graph", "b71e9c4d22": "Refresh graph", - "9a3f5c2e70": "Showing {{value0}} of many commits across all branches", + "9a3f5c2e70": "Showing first {{value0}} commits across all branches", "2c8b1f0a93": "Loading graph...", "4e7d6a1c08": "No commits yet", "5d2e9b7a14": "Retry" diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 36d0d8e4dfd6..4424883919bd 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -12097,7 +12097,7 @@ "GitGraphPane": { "6f0a2d1b84": "Git Graph", "b71e9c4d22": "Refresh graph", - "9a3f5c2e70": "Showing {{value0}} of many commits across all branches", + "9a3f5c2e70": "Showing first {{value0}} commits across all branches", "2c8b1f0a93": "Loading graph...", "4e7d6a1c08": "No commits yet", "5d2e9b7a14": "Retry" diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index c0749e4cea46..a90757b6ac15 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -12097,7 +12097,7 @@ "GitGraphPane": { "6f0a2d1b84": "Git Graph", "b71e9c4d22": "Refresh graph", - "9a3f5c2e70": "Showing {{value0}} of many commits across all branches", + "9a3f5c2e70": "Showing first {{value0}} commits across all branches", "2c8b1f0a93": "Loading graph...", "4e7d6a1c08": "No commits yet", "5d2e9b7a14": "Retry" From 7ebd5727916d95181089effb393d5338a1a73bf5 Mon Sep 17 00:00:00 2001 From: brennanb2025 Date: Mon, 29 Jun 2026 04:51:05 -0700 Subject: [PATCH 03/52] Forward allRefs over SSH relay and web runtime paths Two boundaries re-destructured git.history params and dropped the new allRefs flag, leaving the repo-wide Git Graph inert (linear default-branch history) for SSH and web-runtime worktrees: - src/relay/git-handler.ts: the relay host's git.history handler forwarded only { limit, baseRef }. Add allRefs so the SSH host enumerates all refs. Adds an end-to-end relay test (a feature-branch commit absent from linear history appears only when allRefs is forwarded). - src/renderer/src/web/web-preload-api.ts: the web preload history shim destructured only { worktreePath, limit, baseRef }. Forward allRefs. Also fix a request-id race in useGitGraphHistory: bump requestIdRef before the null-context early return so an in-flight fetch from a prior worktree can't resolve and overwrite the 'idle' state after the worktree clears. Co-authored-by: Orca --- src/relay/git-handler.test.ts | 27 +++++++++++++++++++ src/relay/git-handler.ts | 5 +++- .../git-graph/useGitGraphHistory.ts | 4 ++- src/renderer/src/web/web-preload-api.ts | 7 +++-- 4 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/relay/git-handler.test.ts b/src/relay/git-handler.test.ts index a88bdd2941ad..aa1c0d995ce9 100644 --- a/src/relay/git-handler.test.ts +++ b/src/relay/git-handler.test.ts @@ -351,6 +351,33 @@ describe('GitHandler', () => { expect(result.hasMore).toBe(false) expect(result.limit).toBe(10) }) + + it('forwards allRefs over the wire so the repo-wide graph spans all branches', async () => { + gitInit(tmpDir) + writeFileSync(path.join(tmpDir, 'file.txt'), 'base') + gitCommit(tmpDir, 'initial') + const baseBranch = currentBranch(tmpDir) + execFileSync('git', ['checkout', '-b', 'feature'], { cwd: tmpDir, stdio: 'pipe' }) + writeFileSync(path.join(tmpDir, 'feature.txt'), 'feature') + gitCommit(tmpDir, 'feature only') + // Return to the base branch so the feature commit is NOT in linear history. + execFileSync('git', ['checkout', baseBranch], { cwd: tmpDir, stdio: 'pipe' }) + + const linear = (await dispatcher.callRequest('git.history', { + worktreePath: tmpDir, + limit: 10 + })) as { items: { subject: string }[] } + expect(linear.items.map((item) => item.subject)).toEqual(['initial']) + + // Why: the relay handler must forward allRefs; otherwise this returns the + // same linear result and the SSH Git Graph silently shows one branch. + const allRefs = (await dispatcher.callRequest('git.history', { + worktreePath: tmpDir, + limit: 10, + allRefs: true + })) as { items: { subject: string }[] } + expect(allRefs.items.map((item) => item.subject)).toContain('feature only') + }) }) describe('status', () => { diff --git a/src/relay/git-handler.ts b/src/relay/git-handler.ts index 75732b34786c..6c1fdc57688e 100644 --- a/src/relay/git-handler.ts +++ b/src/relay/git-handler.ts @@ -347,7 +347,10 @@ export class GitHandler { const worktreePath = params.worktreePath as string return loadGitHistoryFromExecutor(this.git.bind(this), worktreePath, { limit: typeof params.limit === 'number' ? params.limit : undefined, - baseRef: typeof params.baseRef === 'string' ? params.baseRef : null + baseRef: typeof params.baseRef === 'string' ? params.baseRef : null, + // Why: the repo-wide Git Graph passes allRefs over the SSH wire; without + // forwarding it here the relay host silently runs current-branch history. + allRefs: typeof params.allRefs === 'boolean' ? params.allRefs : undefined }) } diff --git a/src/renderer/src/components/git-graph/useGitGraphHistory.ts b/src/renderer/src/components/git-graph/useGitGraphHistory.ts index e4565fb9ff53..1d34555b9c4b 100644 --- a/src/renderer/src/components/git-graph/useGitGraphHistory.ts +++ b/src/renderer/src/components/git-graph/useGitGraphHistory.ts @@ -49,12 +49,14 @@ export function useGitGraphHistory(worktreeId: string): UseGitGraphHistory { }, [repo, settings, worktreeId, worktreePath]) useEffect(() => { + // Bump before the null-check so a fetch still in flight from a prior + // worktree can't resolve and overwrite this 'idle' state once it clears. + const requestId = (requestIdRef.current += 1) const ctx = context if (!ctx) { setState({ status: 'idle' }) return } - const requestId = (requestIdRef.current += 1) setState((prev) => prev.status === 'ready' || prev.status === 'refreshing' ? { status: 'refreshing', result: prev.result } diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index e7d0c976b0a7..271d2367b816 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -1503,12 +1503,15 @@ function createGitApi(): NonNullable['git']> { // in the web runtime there's no offer, so return no candidates / no-op. findHugeFoldersToIgnore: async () => [], appendGitignore: async () => false, - history: async ({ worktreePath, limit, baseRef }) => { + history: async ({ worktreePath, limit, baseRef, allRefs }) => { const worktree = await resolveRuntimeWorktreeByPath(worktreePath) return callRuntimeResult('git.history', { worktree: toRuntimeWorktreeSelector(worktree.id), limit, - baseRef + baseRef, + // Why: forward the repo-wide Git Graph scope so the web runtime path + // enumerates all refs instead of silently falling back to linear history. + allRefs }) }, conflictOperation: async ({ worktreePath }) => { From 5c6e047e49b33de00063308a2b16da87452918e0 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 5 Nov 2026 19:32:12 -0800 Subject: [PATCH 04/52] Support filtered and pinned Git history MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolve branch and tag roots on the host, keep paging tied to the chosen revision set, and echo the applied filter across Git transports. Co-authored-by: Matheus Breguêz --- src/main/git/history.ts | 39 +++++- .../filesystem-git-history-handlers.ts | 54 ++++++++ .../filesystem-git-status-handlers.ts | 34 +---- src/main/providers/git-provider-contract.ts | 2 + src/main/providers/local-git-provider.ts | 3 +- .../integrations/git/orca-runtime-git.ts | 2 + .../git/runtime-git-command-surface.ts | 2 + .../git/runtime-git-status-commands.ts | 5 + src/main/runtime/rpc/methods/git.ts | 9 ++ src/preload/api/git-bridge.ts | 6 + src/preload/api/git-inspection-api.ts | 6 + .../src/runtime/runtime-git-status-client.ts | 20 +++ .../src/web/preload-api/web-git-api.ts | 12 +- .../web/preload-api/web-git-history-api.ts | 28 +++++ .../git/history/git-history-execution.ts | 118 ++++++++++++------ .../git-history-real-repository.test.ts | 102 ++++++++++++++- .../git/history/git-history-revisions.ts | 77 ++++++++++++ .../git/history/git-history-token-store.ts | 73 +++++++++++ src/shared/git/history/git-history-types.ts | 12 +- src/shared/rpc-contract/git-params.ts | 10 ++ .../rpc-params-catalog.generated.ts | 2 + .../runtime/git-graph-capabilities.ts | 2 + .../source-control-runtime-capabilities.ts | 3 + 23 files changed, 539 insertions(+), 82 deletions(-) create mode 100644 src/main/ipc/filesystem/filesystem-git-history-handlers.ts create mode 100644 src/renderer/src/web/preload-api/web-git-history-api.ts create mode 100644 src/shared/git/history/git-history-revisions.ts create mode 100644 src/shared/git/history/git-history-token-store.ts create mode 100644 src/shared/source-control/runtime/git-graph-capabilities.ts diff --git a/src/main/git/history.ts b/src/main/git/history.ts index 932c33ef83c4..50d2bd8292ef 100644 --- a/src/main/git/history.ts +++ b/src/main/git/history.ts @@ -1,3 +1,6 @@ +import { resolveWorktreeHostPath } from '../../shared/git/metadata/git-metadata-path' +import { parseWslUncPath } from '../../shared/wsl-paths' +import { loadGitHistoryRefs } from '../../shared/git/history/git-history-revisions' import type { GitHistoryOptions, GitHistoryResult @@ -12,8 +15,42 @@ export async function getHistory( options: GitHistoryOptions & GitRuntimeOptions = {} ): Promise { return loadGitHistoryFromExecutor( - (args, cwd) => gitExecFileAsync(args, gitOptionsForWorktree(cwd, options)), + (args, cwd, stdin) => + gitExecFileAsync(args, { + ...gitOptionsForWorktree(cwd, options), + ...(stdin !== undefined ? { stdin } : {}) + }), worktreePath, options ) } + +export async function getHistoryRefs( + worktreePath: string, + query?: string, + options: GitRuntimeOptions = {} +) { + return ( + await loadGitHistoryRefs( + (args, cwd, stdin) => + gitExecFileAsync(args, { + ...gitOptionsForWorktree(cwd, options), + ...(stdin !== undefined ? { stdin } : {}) + }), + worktreePath, + query + ) + ) + .slice(0, 1000) + .map((ref) => + ref.worktreePath + ? { + ...ref, + worktreePath: + resolveWorktreeHostPath(ref.worktreePath, { + wslDistro: parseWslUncPath(worktreePath)?.distro ?? options.wslDistro + }) ?? ref.worktreePath + } + : ref + ) +} diff --git a/src/main/ipc/filesystem/filesystem-git-history-handlers.ts b/src/main/ipc/filesystem/filesystem-git-history-handlers.ts new file mode 100644 index 000000000000..764ddf49a416 --- /dev/null +++ b/src/main/ipc/filesystem/filesystem-git-history-handlers.ts @@ -0,0 +1,54 @@ +import { ipcMain } from 'electron' +import type { + GitHistoryOptions, + GitHistoryResult +} from '../../../shared/git/history/git-history-types' +import { getHistory, getHistoryRefs } from '../../git/history' +import { getConnectionExecutionHostId } from '../../../shared/execution-host' +import { requireReachableGitRoute } from '../../providers/execution-host-provider-dispatch' +import { readWorktreeGitUnlessWslStopped } from './wsl-gated-worktree-git-read' +import type { FilesystemHandlerContext } from './filesystem-handler-context' + +export function registerFilesystemGitHistoryHandlers({ store }: FilesystemHandlerContext): void { + ipcMain.handle( + 'git:refs', + async (_event, args: { worktreePath: string; connectionId?: string; query?: string }) => { + requireReachableGitRoute(getConnectionExecutionHostId(args.connectionId)) + return readWorktreeGitUnlessWslStopped( + store, + args.worktreePath, + false, + (worktreePath, gitOptions) => getHistoryRefs(worktreePath, args.query, gitOptions) + ) + } + ) + + ipcMain.handle( + 'git:history', + async ( + _event, + args: { + worktreePath: string + connectionId?: string + /** Refresh: a user act that may start a stopped WSL distro. */ + wakeWslDistro?: boolean + } & GitHistoryOptions + ): Promise => { + const options: GitHistoryOptions = { + limit: args.limit, + baseRef: args.baseRef, + branchOnly: args.branchOnly, + refs: args.refs, + historyToken: args.historyToken, + skip: args.skip + } + requireReachableGitRoute(getConnectionExecutionHostId(args.connectionId)) + return readWorktreeGitUnlessWslStopped( + store, + args.worktreePath, + args.wakeWslDistro, + (worktreePath, gitOptions) => getHistory(worktreePath, { ...options, ...gitOptions }) + ) + } + ) +} diff --git a/src/main/ipc/filesystem/filesystem-git-status-handlers.ts b/src/main/ipc/filesystem/filesystem-git-status-handlers.ts index 7d20c9d7227c..e28b3bb6d8a6 100644 --- a/src/main/ipc/filesystem/filesystem-git-status-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-git-status-handlers.ts @@ -5,10 +5,6 @@ import type { GitStatusResult } from '../../../shared/git/status/git-status-types' import type { GitDiffResult } from '../../../shared/git/diff/git-diff-compare-types' -import type { - GitHistoryOptions, - GitHistoryResult -} from '../../../shared/git/history/git-history-types' import type { GitStatusRefBindingRequest as GitStatusUpstreamRefWatchRequest } from '../worktrees/git/worktree-git-status-ref-watch' import type { GitAdmissionTier } from '../../git/command-runner/git-exec-options' import { getStatus } from '../../git/source-control/status-read' @@ -19,7 +15,7 @@ import { detectConflictOperation } from '../../git/source-control/git-conflict-operation' import { getDiff } from '../../git/source-control/file-diff' -import { getHistory } from '../../git/history' +import { registerFilesystemGitHistoryHandlers } from './filesystem-git-history-handlers' import { isGitWorktreeMutationInFlight } from '../../git/command-runner/git-worktree-mutation-state' import type { GitMutationInFlight } from '../../../shared/git/commands/git-mutation-in-flight' import { checkIgnoredPaths } from '../../git/source-control/check-ignored-paths' @@ -49,6 +45,7 @@ import { export function registerFilesystemGitStatusHandlers(context: FilesystemHandlerContext): void { const { store, gitStatusCancellations } = context + registerFilesystemGitHistoryHandlers(context) ipcMain.handle( 'git:status', async ( @@ -190,33 +187,6 @@ export function registerFilesystemGitStatusHandlers(context: FilesystemHandlerCo } ) - ipcMain.handle( - 'git:history', - async ( - _event, - args: { - worktreePath: string - connectionId?: string - /** Refresh: a user act that may start a stopped WSL distro. */ - wakeWslDistro?: boolean - } & GitHistoryOptions - ): Promise => { - const options: GitHistoryOptions = { - limit: args.limit, - baseRef: args.baseRef, - branchOnly: args.branchOnly, - skip: args.skip - } - requireReachableGitRoute(getConnectionExecutionHostId(args.connectionId)) - return readWorktreeGitUnlessWslStopped( - store, - args.worktreePath, - args.wakeWslDistro, - (worktreePath, gitOptions) => getHistory(worktreePath, { ...options, ...gitOptions }) - ) - } - ) - // Filesystem probes clear inactive-worktree conflict badges without a full Git status. ipcMain.handle( 'git:conflictOperation', diff --git a/src/main/providers/git-provider-contract.ts b/src/main/providers/git-provider-contract.ts index f94f07decd33..8c0da6e2c85b 100644 --- a/src/main/providers/git-provider-contract.ts +++ b/src/main/providers/git-provider-contract.ts @@ -17,6 +17,7 @@ import type { GitStageWorktreeScope } from '../../shared/git/paths/git-stage-wor import type { RemoveWorktreeResult } from '../../shared/worktree/create-types' import type { GitPushTarget, GitWorktreeInfo } from '../../shared/worktree/types' import type { + GitHistoryItemRef, GitHistoryOptions, GitHistoryResult } from '../../shared/git/history/git-history-types' @@ -35,6 +36,7 @@ export type IGitProvider = { area?: GitStagingArea ): Promise checkIgnoredPaths(worktreePath: string, relativePaths: string[]): Promise + getHistoryRefs(worktreePath: string, query?: string): Promise getHistory(worktreePath: string, options?: GitHistoryOptions): Promise commit(worktreePath: string, message: string): Promise<{ success: boolean; error?: string }> completeMerge(worktreePath: string): Promise<{ success: boolean; error?: string }> diff --git a/src/main/providers/local-git-provider.ts b/src/main/providers/local-git-provider.ts index 4493b0ec0a0b..5a0b8b61f689 100644 --- a/src/main/providers/local-git-provider.ts +++ b/src/main/providers/local-git-provider.ts @@ -2,7 +2,7 @@ import { gitSyncForkDefaultBranch } from '../git/fork-sync' import type { GitRuntimeOptions } from '../git/git-runtime-options' import { checkIgnoredPaths } from '../git/source-control/check-ignored-paths' import { checkoutBranch, listLocalBranches } from '../git/checkout' -import { getHistory } from '../git/history' +import { getHistory, getHistoryRefs } from '../git/history' import { gitFastForward, gitFetch, gitPull, gitPullRebaseFromBase, gitPush } from '../git/remote' import { getRemoteCommitUrl, getRemoteFileUrl, isGitRepo } from '../git/repo' import { awaitWindowsHostGitEnvironmentReady, gitExecFileAsync } from '../git/runner' @@ -71,6 +71,7 @@ export function createLocalGitProvider(options: LocalGitProviderOptions = {}): L }), checkIgnoredPaths: (worktreePath, relativePaths) => checkIgnoredPaths(worktreePath, relativePaths, interactive), + getHistoryRefs: (worktreePath, query) => getHistoryRefs(worktreePath, query, interactive), getHistory: (worktreePath, historyOptions = {}) => getHistory(worktreePath, { ...historyOptions, ...interactive }), commit: (worktreePath, message) => commitChanges(worktreePath, message, interactive), diff --git a/src/main/runtime/integrations/git/orca-runtime-git.ts b/src/main/runtime/integrations/git/orca-runtime-git.ts index 900a15a5d5a1..666f9e9f58ca 100644 --- a/src/main/runtime/integrations/git/orca-runtime-git.ts +++ b/src/main/runtime/integrations/git/orca-runtime-git.ts @@ -9,6 +9,7 @@ export class RuntimeGitCommands { readonly getRuntimeGitStatus: RuntimeGitStatusCommands['getRuntimeGitStatus'] readonly getRuntimeGitSubmoduleStatus: RuntimeGitStatusCommands['getRuntimeGitSubmoduleStatus'] readonly checkRuntimeGitIgnoredPaths: RuntimeGitStatusCommands['checkRuntimeGitIgnoredPaths'] + readonly getRuntimeGitRefs: RuntimeGitStatusCommands['getRuntimeGitRefs'] readonly getRuntimeGitHistory: RuntimeGitStatusCommands['getRuntimeGitHistory'] readonly getRuntimeGitConflictOperation: RuntimeGitStatusCommands['getRuntimeGitConflictOperation'] readonly getRuntimeGitMutationInFlight: RuntimeGitStatusCommands['getRuntimeGitMutationInFlight'] @@ -55,6 +56,7 @@ export class RuntimeGitCommands { this.getRuntimeGitStatus = status.getRuntimeGitStatus.bind(status) this.getRuntimeGitSubmoduleStatus = status.getRuntimeGitSubmoduleStatus.bind(status) this.checkRuntimeGitIgnoredPaths = status.checkRuntimeGitIgnoredPaths.bind(status) + this.getRuntimeGitRefs = status.getRuntimeGitRefs.bind(status) this.getRuntimeGitHistory = status.getRuntimeGitHistory.bind(status) this.getRuntimeGitConflictOperation = status.getRuntimeGitConflictOperation.bind(status) this.getRuntimeGitMutationInFlight = status.getRuntimeGitMutationInFlight.bind(status) diff --git a/src/main/runtime/integrations/git/runtime-git-command-surface.ts b/src/main/runtime/integrations/git/runtime-git-command-surface.ts index 22f298f10ff4..52997e924529 100644 --- a/src/main/runtime/integrations/git/runtime-git-command-surface.ts +++ b/src/main/runtime/integrations/git/runtime-git-command-surface.ts @@ -4,6 +4,7 @@ type RuntimeGitCommandName = | 'getRuntimeGitStatus' | 'getRuntimeGitSubmoduleStatus' | 'checkRuntimeGitIgnoredPaths' + | 'getRuntimeGitRefs' | 'getRuntimeGitHistory' | 'getRuntimeGitConflictOperation' | 'getRuntimeGitMutationInFlight' @@ -50,6 +51,7 @@ export function installRuntimeGitCommandSurface( getRuntimeGitStatus: commands.getRuntimeGitStatus.bind(commands), getRuntimeGitSubmoduleStatus: commands.getRuntimeGitSubmoduleStatus.bind(commands), checkRuntimeGitIgnoredPaths: commands.checkRuntimeGitIgnoredPaths.bind(commands), + getRuntimeGitRefs: commands.getRuntimeGitRefs.bind(commands), getRuntimeGitHistory: commands.getRuntimeGitHistory.bind(commands), getRuntimeGitConflictOperation: commands.getRuntimeGitConflictOperation.bind(commands), getRuntimeGitMutationInFlight: commands.getRuntimeGitMutationInFlight.bind(commands), diff --git a/src/main/runtime/integrations/git/runtime-git-status-commands.ts b/src/main/runtime/integrations/git/runtime-git-status-commands.ts index 54e7e819f5b0..0bce6db747e8 100644 --- a/src/main/runtime/integrations/git/runtime-git-status-commands.ts +++ b/src/main/runtime/integrations/git/runtime-git-status-commands.ts @@ -69,6 +69,11 @@ export class RuntimeGitStatusCommands { return requireRuntimeGitProvider(target).checkIgnoredPaths(target.worktree.path, relativePaths) } + async getRuntimeGitRefs(worktreeSelector: string, query?: string) { + const target = await resolveGatedGitTarget(this.host, worktreeSelector) + return requireRuntimeGitProvider(target).getHistoryRefs(target.worktree.path, query) + } + async getRuntimeGitHistory( worktreeSelector: string, options: GitHistoryOptions = {} diff --git a/src/main/runtime/rpc/methods/git.ts b/src/main/runtime/rpc/methods/git.ts index 741fcb803b6a..3a2771e214be 100644 --- a/src/main/runtime/rpc/methods/git.ts +++ b/src/main/runtime/rpc/methods/git.ts @@ -13,6 +13,7 @@ import { GitResolveConflict, GitForkSync, GitHistory, + GitRefs, GitPush, GitRebaseFromBase, GitRemoteCommitUrl, @@ -74,6 +75,12 @@ export const GIT_METHODS = [ handler: async (params, { runtime }) => runtime.getRuntimeGitSubmoduleStatus(params.worktree, params.submodulePath, params.area) }), + defineMethod({ + name: 'git.refs', + permission: 'workspace', + params: GitRefs, + handler: async (params, { runtime }) => runtime.getRuntimeGitRefs(params.worktree, params.query) + }), defineMethod({ name: 'git.history', permission: 'workspace', @@ -83,6 +90,8 @@ export const GIT_METHODS = [ limit: params.limit, baseRef: params.baseRef, branchOnly: params.branchOnly, + refs: params.refs, + historyToken: params.historyToken, skip: params.skip }) }), diff --git a/src/preload/api/git-bridge.ts b/src/preload/api/git-bridge.ts index ffcfba9cf111..6cff7e288003 100644 --- a/src/preload/api/git-bridge.ts +++ b/src/preload/api/git-bridge.ts @@ -8,6 +8,7 @@ import type { ConflictResolution } from '../../shared/source-control/listing/sou import type { GitPushTarget } from '../../shared/worktree/types' import type { GitStageWorktreeScope } from '../../shared/git/paths/git-stage-worktree-scope' import type { + GitHistoryItemRef, GitHistoryOptions, GitHistoryResult } from '../../shared/git/history/git-history-types' @@ -49,6 +50,11 @@ export const gitApi = { ipcRenderer.invoke('git:findHugeFoldersToIgnore', args), appendGitignore: (args: { worktreePath: string; folderName: string }): Promise => ipcRenderer.invoke('git:appendGitignore', args), + refs: (args: { + worktreePath: string + connectionId?: string + query?: string + }): Promise => ipcRenderer.invoke('git:refs', args), history: ( args: { worktreePath: string diff --git a/src/preload/api/git-inspection-api.ts b/src/preload/api/git-inspection-api.ts index a7ee8ee5564e..7fa8d767a282 100644 --- a/src/preload/api/git-inspection-api.ts +++ b/src/preload/api/git-inspection-api.ts @@ -12,6 +12,7 @@ import type { } from '../../shared/git/status/git-status-types' import type { GitPushTarget } from '../../shared/worktree/types' import type { + GitHistoryItemRef, GitHistoryOptions, GitHistoryResult } from '../../shared/git/history/git-history-types' @@ -56,6 +57,11 @@ export type GitInspectionApi = { connectionId?: string }) => Promise findHugeFoldersToIgnore: (args: { worktreePath: string }) => Promise + refs: (args: { + worktreePath: string + connectionId?: string + query?: string + }) => Promise history: ( args: { worktreePath: string diff --git a/src/renderer/src/runtime/runtime-git-status-client.ts b/src/renderer/src/runtime/runtime-git-status-client.ts index e65d4b4c7df2..c6d397445d03 100644 --- a/src/renderer/src/runtime/runtime-git-status-client.ts +++ b/src/renderer/src/runtime/runtime-git-status-client.ts @@ -1,4 +1,5 @@ import type { + GitHistoryItemRef, GitHistoryOptions, GitHistoryResult } from '../../../shared/git/history/git-history-types' @@ -172,6 +173,25 @@ export async function getRuntimeGitIgnoredPaths( ) } +export async function getRuntimeGitRefs( + context: RuntimeGitContext, + query?: string +): Promise { + if (context.target.kind === 'local' || !context.worktreeId) { + return window.api.git.refs({ + worktreePath: resolveLocalWorktreePath(context), + connectionId: context.connectionId, + query + }) + } + return callRuntimeRpc( + context.target, + 'git.refs', + { worktree: toRuntimeWorktreeSelector(context.worktreeId), query }, + { timeoutMs: 15_000 } + ) +} + export async function getRuntimeGitHistory( context: RuntimeGitContext, /** `wakeWslDistro`: Refresh, a user act that may start a stopped WSL distro. Local only. */ diff --git a/src/renderer/src/web/preload-api/web-git-api.ts b/src/renderer/src/web/preload-api/web-git-api.ts index d5f0530ed6b0..b2a4f6010a90 100644 --- a/src/renderer/src/web/preload-api/web-git-api.ts +++ b/src/renderer/src/web/preload-api/web-git-api.ts @@ -1,3 +1,4 @@ +import { createGitHistoryApi } from './web-git-history-api' import type { PreloadApi } from '../../../../preload/api-types' import { callAbortableRuntimeEnvironment } from '../../runtime/abortable-runtime-environment-call' import { toRuntimeWorktreeSelector } from '../../runtime/runtime-worktree-selector' @@ -89,16 +90,7 @@ export function createGitApi(): NonNullable['git']> { // Why: the "add huge folder to .gitignore" flow is desktop-only; the web runtime makes no offer, so return no candidates. findHugeFoldersToIgnore: async () => [], appendGitignore: async () => false, - history: async ({ worktreePath, limit, baseRef, branchOnly, skip }) => { - const worktree = await resolveRuntimeWorktreeByPath(worktreePath) - return callRuntimeResult('git.history', { - worktree: toRuntimeWorktreeSelector(worktree.id), - limit, - baseRef, - branchOnly, - skip - }) - }, + ...createGitHistoryApi(), mutationInFlight: async ({ worktreePath }) => { const worktree = await resolveRuntimeWorktreeByPath(worktreePath) return callRuntimeResult('git.mutationInFlight', { diff --git a/src/renderer/src/web/preload-api/web-git-history-api.ts b/src/renderer/src/web/preload-api/web-git-history-api.ts new file mode 100644 index 000000000000..a98893b3da52 --- /dev/null +++ b/src/renderer/src/web/preload-api/web-git-history-api.ts @@ -0,0 +1,28 @@ +import type { PreloadApi } from '../../../../preload/api-types' +import { toRuntimeWorktreeSelector } from '../../runtime/runtime-worktree-selector' +import { resolveRuntimeWorktreeByPath } from './web-runtime-worktree-catalog' +import { callRuntimeResult } from './web-runtime-calls' + +export function createGitHistoryApi(): Pick { + return { + refs: async ({ worktreePath, query }) => { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + return callRuntimeResult('git.refs', { + worktree: toRuntimeWorktreeSelector(worktree.id), + query + }) + }, + history: async ({ worktreePath, limit, baseRef, branchOnly, skip, refs, historyToken }) => { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + return callRuntimeResult('git.history', { + worktree: toRuntimeWorktreeSelector(worktree.id), + limit, + baseRef, + branchOnly, + refs, + historyToken, + skip + }) + } + } +} diff --git a/src/shared/git/history/git-history-execution.ts b/src/shared/git/history/git-history-execution.ts index 49c962720e93..a76e0caef991 100644 --- a/src/shared/git/history/git-history-execution.ts +++ b/src/shared/git/history/git-history-execution.ts @@ -1,3 +1,5 @@ +import { loadGitHistoryRefs, validateHistoryRefs } from './git-history-revisions' +import { gitHistoryTokens } from './git-history-token-store' import { GIT_HISTORY_COMMIT_FORMAT, gitHistoryRefFromFullName, @@ -148,30 +150,41 @@ export async function loadGitHistoryFromExecutor( options: GitHistoryOptions = {} ): Promise { const limit = clampHistoryLimit(options.limit) - const headOid = await resolveCommit(git, cwd, 'HEAD') - if (!headOid) { - return { - items: [], - hasIncomingChanges: false, - hasOutgoingChanges: false, - hasMore: false, - limit - } + const refs = options.branchOnly ? 'head' : (options.refs ?? 'head') + validateHistoryRefs(refs) + const empty = { + items: [], + hasIncomingChanges: false, + hasOutgoingChanges: false, + hasMore: false, + limit, + refs, + resolvedRefs: [] } - - const { currentRef, branchName } = await resolveCurrentRef(git, cwd, headOid) + const requestedToken = options.branchOnly ? undefined : options.historyToken + const pinned = + requestedToken !== undefined ? gitHistoryTokens.get(requestedToken, cwd, refs) : undefined + if (requestedToken !== undefined && !pinned) { + return { ...empty, historyChanged: true } + } + const headOid = await resolveCommit(git, cwd, 'HEAD') + const current = headOid ? await resolveCurrentRef(git, cwd, headOid) : undefined + const currentRef = current?.currentRef + const branchName = current?.branchName ?? null const [remoteRef, rawBaseRef] = await Promise.all([ resolveUpstreamRef(git, cwd, branchName), resolveNamedRef(git, cwd, options.baseRef) ]) const baseRef = - rawBaseRef && rawBaseRef.id !== remoteRef?.id && rawBaseRef.id !== currentRef.id + rawBaseRef && rawBaseRef.id !== remoteRef?.id && rawBaseRef.id !== currentRef?.id ? rawBaseRef : undefined // The base may equal the upstream here (a branch tracking main), unlike the graph's comparison base. const branchBase = + headOid && + currentRef && options.branchOnly && rawBaseRef?.revision && !(await isBaseOfItself(git, cwd, rawBaseRef, currentRef)) @@ -179,37 +192,71 @@ export async function loadGitHistoryFromExecutor( : undefined // Keep upstream/base as comparison metadata so old workspaces do not gain fetched commits outside their HEAD history. - const historyRevisions = branchBase - ? [headOid, `^${branchBase.range.baseRef.revision}`] - : [headOid] + let historyRevisions = branchBase + ? [headOid!, `^${branchBase.range.baseRef.revision}`] + : headOid + ? [headOid] + : [] + let resolvedRefs: string[] = [] + if (pinned) { + historyRevisions = pinned.revisions + resolvedRefs = pinned.resolvedRefs + } else if (refs !== 'head') { + const catalog = await loadGitHistoryRefs(git, cwd) + const chosen = Array.isArray(refs) ? catalog.filter((ref) => refs.includes(ref.id)) : catalog + resolvedRefs = chosen.map((ref) => ref.id) + historyRevisions = [ + ...new Set([ + ...(refs === 'all' && headOid ? [headOid] : []), + ...chosen.flatMap((ref) => (ref.revision ? [ref.revision] : [])) + ]) + ] + } + const historyToken = + requestedToken ?? + (branchBase ? undefined : gitHistoryTokens.put(cwd, refs, historyRevisions, resolvedRefs)) + const echo = { refs, resolvedRefs, historyToken } + if (!historyRevisions.length) { + return { ...empty, ...echo } + } const skip = clampHistorySkip(options.skip) let mergeBase: string | undefined - if (remoteRef?.revision && currentRef.revision && remoteRef.revision !== currentRef.revision) { + if (remoteRef?.revision && currentRef?.revision && remoteRef.revision !== currentRef?.revision) { try { - const { stdout } = await git(['merge-base', currentRef.revision, remoteRef.revision], cwd) + const { stdout } = await git(['merge-base', currentRef?.revision, remoteRef.revision], cwd) mergeBase = stdout.trim() || undefined } catch { mergeBase = undefined } } - const { stdout } = await git( - [ - 'log', - '--no-show-signature', - '--no-color', - `--format=${GIT_HISTORY_COMMIT_FORMAT}`, - '-z', - '--topo-order', - '--decorate=full', - ...(branchBase ? ['--shortstat'] : []), - ...(skip > 0 ? [`--skip=${skip}`] : []), - `-n${limit + 1}`, - ...historyRevisions - ], - cwd - ) + let stdout: string + try { + const result = await git( + [ + 'log', + '--no-show-signature', + '--no-color', + `--format=${GIT_HISTORY_COMMIT_FORMAT}`, + '-z', + '--topo-order', + '--decorate=full', + ...(branchBase ? ['--shortstat'] : []), + ...(skip > 0 ? [`--skip=${skip}`] : []), + `-n${limit + 1}`, + ...(refs === 'head' && !pinned ? historyRevisions : ['--stdin']) + ], + cwd, + refs === 'head' && !pinned ? undefined : `${historyRevisions.join('\n')}\n` + ) + stdout = result.stdout + } catch (error) { + if (pinned && /bad object|unknown revision|invalid object|bad revision/i.test(String(error))) { + return { ...empty, ...echo, historyChanged: true } + } + throw error + } const parsed = parseGitHistoryLog(stdout) const items = parsed.slice(0, limit) if (branchBase) { @@ -220,11 +267,12 @@ export async function loadGitHistoryFromExecutor( const hasIncomingChanges = Boolean(remoteRef?.revision && mergeBase) && remoteRef?.revision !== mergeBase const hasOutgoingChanges = - Boolean(currentRef.revision && remoteRef?.revision && mergeBase) && - currentRef.revision !== mergeBase + Boolean(currentRef?.revision && remoteRef?.revision && mergeBase) && + currentRef?.revision !== mergeBase return { items, + ...echo, currentRef, remoteRef, baseRef, diff --git a/src/shared/git/history/git-history-real-repository.test.ts b/src/shared/git/history/git-history-real-repository.test.ts index 2bdfb2a22ea9..5fe7e067ece7 100644 --- a/src/shared/git/history/git-history-real-repository.test.ts +++ b/src/shared/git/history/git-history-real-repository.test.ts @@ -4,6 +4,9 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { runProcess } from '@orca/process-host' import { resolveExecutableCommand } from '../../node-cli-command-resolution' +import { GitHistory } from '../../rpc-contract/git-params' +import { gitHistoryTokens } from './git-history-token-store' +import { loadGitHistoryRefs } from './git-history-revisions' import { loadGitHistoryFromExecutor } from './git-history-execution' import { buildDefaultGitHistoryColorMap, buildGitHistoryViewModels } from './git-history-graph' @@ -30,7 +33,9 @@ async function createRepository(inheritedEnv: NodeJS.ProcessEnv = process.env) { Object.entries(inheritedEnv).filter(([key]) => !key.toUpperCase().startsWith('GIT_')) ) const git = async (args: string[], cwd = repo, date = '2000-01-04T00:00:00Z') => { + const usesStdin = args.includes('--stdin') || args[0] === 'cat-file' const result = await runProcess({ + ...(usesStdin ? { input: date } : {}), program: gitBinary, args, cwd, @@ -38,8 +43,8 @@ async function createRepository(inheritedEnv: NodeJS.ProcessEnv = process.env) { ...fixtureEnv, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: emptyConfig, - GIT_AUTHOR_DATE: date, - GIT_COMMITTER_DATE: date + GIT_AUTHOR_DATE: usesStdin ? '2000-01-04T00:00:00Z' : date, + GIT_COMMITTER_DATE: usesStdin ? '2000-01-04T00:00:00Z' : date }, timeoutMs: 10000, maxOutputBytes: 1024 * 1024 @@ -183,3 +188,96 @@ describe('real branch-only history', () => { expect(untracked.branch).toMatchObject({ ahead: 2, unpushed: 1 }) }) }) + +describe('filtered and pinned history', () => { + it('walks only branch, remote and commit-pointing tag roots, including unborn HEAD', async () => { + const { repo, git } = await createRepository() + await git(['checkout', '--quiet', '--detach']) + await git(['commit', '--quiet', '--allow-empty', '-m', 'remote only']) + await git(['update-ref', 'refs/remotes/origin/other', 'HEAD']) + await git(['commit', '--quiet', '--allow-empty', '-m', 'stash only']) + await git(['update-ref', 'refs/stash', 'HEAD']) + await git(['checkout', '--quiet', '--detach', 'first']) + await git(['commit', '--quiet', '--allow-empty', '-m', 'pull only']) + await git(['update-ref', 'refs/pull/1/head', 'HEAD']) + await git(['checkout', '--quiet', '--detach', 'first']) + await git(['commit', '--quiet', '--allow-empty', '-m', 'tag only']) + await git(['tag', '-a', 'inner', '-m', 'inner']) + await git(['tag', '-a', 'outer', 'inner', '-m', 'outer']) + await git(['tag', 'tree', 'HEAD^{tree}']) + await git(['symbolic-ref', 'refs/remotes/origin/alias', 'refs/remotes/origin/other']) + await git(['checkout', '--quiet', 'first']) + const refs = await loadGitHistoryRefs(git, repo) + expect(refs.map((ref) => ref.id)).toEqual([ + 'refs/heads/first', + 'refs/heads/unrelated', + 'refs/remotes/origin/other', + 'refs/tags/inner', + 'refs/tags/outer' + ]) + const all = await loadGitHistoryFromExecutor(git, repo, { refs: 'all' }) + expect(all.items.map((item) => item.subject).sort()).toEqual([ + 'A', + 'B', + 'V', + 'remote only', + 'tag only' + ]) + await git(['checkout', '--orphan', 'unborn']) + const unborn = await loadGitHistoryFromExecutor(git, repo, { refs: 'all' }) + expect(unborn.items.map((item) => item.subject).sort()).toEqual([ + 'A', + 'B', + 'V', + 'remote only', + 'tag only' + ]) + const chosen = await loadGitHistoryFromExecutor(git, repo, { refs: ['refs/heads/unrelated'] }) + expect(chosen.items.map((item) => item.subject)).toEqual(['V']) + expect(chosen.resolvedRefs).toEqual(['refs/heads/unrelated']) + const tag = await loadGitHistoryFromExecutor(git, repo, { + refs: ['refs/tags/outer', 'refs/tags/tree'] + }) + expect(tag.items.map((item) => item.subject)).toEqual(['tag only', 'A', 'B']) + expect(tag.resolvedRefs).toEqual(['refs/tags/outer']) + }) + + it('keeps page two exact across branch movement and reports lost tokens', async () => { + const { repo, git } = await createRepository() + await git(['checkout', '--quiet', 'first']) + const page = await loadGitHistoryFromExecutor(git, repo, { refs: 'all', limit: 1 }) + expect(page.items.map((item) => item.subject)).toEqual(['V']) + await git(['commit', '--quiet', '--allow-empty', '-m', 'new']) + const next = await loadGitHistoryFromExecutor(git, repo, { + refs: 'all', + historyToken: page.historyToken, + skip: 1, + limit: 2 + }) + expect(next.items.map((item) => item.subject)).toEqual(['A', 'B']) + const wrongFilter = await loadGitHistoryFromExecutor(git, repo, { + refs: 'head', + historyToken: page.historyToken + }) + expect(wrongFilter.historyChanged).toBe(true) + for (let index = 0; index < 32; index++) { + gitHistoryTokens.put(repo, 'all', [], []) + } + const evicted = await loadGitHistoryFromExecutor(git, repo, { + refs: 'all', + historyToken: page.historyToken + }) + expect(evicted).toMatchObject({ items: [], historyChanged: true }) + }) + + it.each(['refs/heads/bad\nname', '-refs/heads/main'])( + 'rejects unsafe ref names: %s', + async (name) => { + const { repo, git } = await createRepository() + expect(GitHistory.safeParse({ worktree: repo, refs: [name] }).success).toBe(false) + await expect(loadGitHistoryFromExecutor(git, repo, { refs: [name] })).rejects.toThrow( + 'Expected full branch or tag ref names' + ) + } + ) +}) diff --git a/src/shared/git/history/git-history-revisions.ts b/src/shared/git/history/git-history-revisions.ts new file mode 100644 index 000000000000..5c10e86e9d4c --- /dev/null +++ b/src/shared/git/history/git-history-revisions.ts @@ -0,0 +1,77 @@ +import type { GitHistoryExecutor, GitHistoryItemRef, GitHistoryRefs } from './git-history-types' +import { gitHistoryRefFromFullName } from './git-history-log-parser' + +export function isGitHistoryRefName(name: string): boolean { + return ( + /^refs\/(heads|remotes|tags)\/[^\s~^:?*[\\]+$/.test(name) && + [...name].every((character) => character.charCodeAt(0) > 32 && character.charCodeAt(0) !== 127) + ) +} + +export function validateHistoryRefs(refs: GitHistoryRefs): void { + if ( + Array.isArray(refs) && + (refs.length > 1000 || refs.some((name) => !isGitHistoryRefName(name))) + ) { + throw new Error('Expected full branch or tag ref names') + } +} + +export async function loadGitHistoryRefs( + git: GitHistoryExecutor, + cwd: string, + query?: string +): Promise { + const { stdout } = await git( + [ + 'for-each-ref', + '--format=%(objectname)%00%(objecttype)%00%(*objectname)%00%(*objecttype)%00%(symref)%00%(refname)%00%(worktreepath)', + 'refs/heads', + 'refs/remotes', + 'refs/tags' + ], + cwd + ) + const rows = stdout + .split('\n') + .filter(Boolean) + .map((line) => line.split('\0')) + const nested = rows.filter((row) => !row[4] && row[3] === 'tag') + const peeled = new Map() + if (nested.length) { + const result = await git( + ['cat-file', '--batch-check=%(objectname) %(objecttype)'], + cwd, + nested.map((row) => `${row[0]}^{commit}\n`).join('') + ) + result.stdout + .trimEnd() + .split('\n') + .forEach((line, index) => { + const [oid, type] = line.split(' ') + const name = nested[index]?.[5] + if (name && oid && type === 'commit') { + peeled.set(name, oid) + } + }) + } + const refs: GitHistoryItemRef[] = [] + for (const [oid, type, peeledOid, peeledType, symref, name, worktreePath] of rows) { + if (!name || symref) { + continue + } + const revision = + type === 'commit' ? oid : peeledType === 'commit' ? peeledOid : peeled.get(name) + if (!revision || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(revision)) { + continue + } + if (query && !name.toLowerCase().includes(query.toLowerCase())) { + continue + } + refs.push({ + ...gitHistoryRefFromFullName(name, name, revision), + ...(worktreePath ? { worktreePath } : {}) + }) + } + return refs +} diff --git a/src/shared/git/history/git-history-token-store.ts b/src/shared/git/history/git-history-token-store.ts new file mode 100644 index 000000000000..445bb6b9e20d --- /dev/null +++ b/src/shared/git/history/git-history-token-store.ts @@ -0,0 +1,73 @@ +import { randomUUID } from 'node:crypto' +import type { GitHistoryRefs } from './git-history-types' + +type PinnedHistory = { + key: string + revisions: string[] + resolvedRefs: string[] + touched: number + bytes: number +} +const MAX_BYTES = 8 * 1024 * 1024 +const IDLE_MS = 15 * 60 * 1000 + +// Host-owned: reconnects and single-request sockets must keep the same pinned revision set. +export class GitHistoryTokenStore { + private readonly entries = new Map() + private bytes = 0 + + private prune(now: number): void { + for (const [token, entry] of this.entries) { + if (now - entry.touched >= IDLE_MS) { + this.remove(token) + } + } + } + + private remove(token: string): void { + const entry = this.entries.get(token) + if (entry) { + this.bytes -= entry.bytes + } + this.entries.delete(token) + } + + private key(cwd: string, refs: GitHistoryRefs): string { + return JSON.stringify([cwd, Array.isArray(refs) ? [...new Set(refs)].sort() : refs]) + } + + get(token: string, cwd: string, refs: GitHistoryRefs): PinnedHistory | undefined { + const now = Date.now() + this.prune(now) + const entry = this.entries.get(token) + if (!entry || entry.key !== this.key(cwd, refs)) { + return undefined + } + entry.touched = now + this.entries.delete(token) + this.entries.set(token, entry) + return entry + } + + put(cwd: string, refs: GitHistoryRefs, revisions: string[], resolvedRefs: string[]): string { + this.prune(Date.now()) + const key = this.key(cwd, refs) + const bytes = 2 * (key.length + revisions.join('').length + resolvedRefs.join('').length) + if (bytes > MAX_BYTES) { + throw new Error('Git history revision set exceeds the host memory limit') + } + while (this.entries.size >= 32 || this.bytes + bytes > MAX_BYTES) { + const oldest = this.entries.keys().next().value + if (!oldest) { + break + } + this.remove(oldest) + } + const token = randomUUID() + this.entries.set(token, { key, revisions, resolvedRefs, bytes, touched: Date.now() }) + this.bytes += bytes + return token + } +} + +export const gitHistoryTokens = new GitHistoryTokenStore() diff --git a/src/shared/git/history/git-history-types.ts b/src/shared/git/history/git-history-types.ts index cd7273c117b9..4e8cd2c6684d 100644 --- a/src/shared/git/history/git-history-types.ts +++ b/src/shared/git/history/git-history-types.ts @@ -30,6 +30,7 @@ export type GitHistoryItemRef = { name: string revision?: string category?: GitHistoryRefCategory + worktreePath?: string description?: string color?: GitHistoryGraphColorId } @@ -56,7 +57,11 @@ export type GitHistoryItem = { pushed?: boolean } +export type GitHistoryRefs = 'head' | 'all' | string[] + export type GitHistoryOptions = { + refs?: GitHistoryRefs + historyToken?: string limit?: number baseRef?: string | null /** List only commits on HEAD that baseRef lacks, with statistics and pushed state. */ @@ -75,6 +80,10 @@ export type GitHistoryBranchRange = { } export type GitHistoryResult = { + refs?: GitHistoryRefs + resolvedRefs?: string[] + historyToken?: string + historyChanged?: boolean items: GitHistoryItem[] currentRef?: GitHistoryItemRef remoteRef?: GitHistoryItemRef @@ -92,5 +101,6 @@ export type GitHistoryResult = { export type GitHistoryExecutor = ( args: string[], - cwd: string + cwd: string, + stdin?: string ) => Promise<{ stdout: string; stderr?: string }> diff --git a/src/shared/rpc-contract/git-params.ts b/src/shared/rpc-contract/git-params.ts index 677727d35600..1880cef41c1e 100644 --- a/src/shared/rpc-contract/git-params.ts +++ b/src/shared/rpc-contract/git-params.ts @@ -1,3 +1,4 @@ +import { isGitHistoryRefName } from '../git/history/git-history-revisions' import { normalizeSourceControlAiActionDefaults } from '../source-control/ai/recipes/source-control-ai-actions' import { z } from 'zod' import { OptionalGitAdmissionTier } from './git-admission-tier-params' @@ -81,10 +82,19 @@ export const GitCommitCompare = WorktreeSelector.extend({ .pipe(FullGitObjectId) }) +export const GitHistoryRefName = z + .string() + .refine(isGitHistoryRefName, 'Expected full branch or tag ref names') +export const GitRefs = WorktreeSelector.extend({ query: z.string().max(1000).optional() }) + export const GitHistory = WorktreeSelector.extend({ limit: z.number().int().min(1).max(200).optional(), baseRef: z.string().nullable().optional(), branchOnly: z.boolean().optional(), + refs: z + .union([z.literal('head'), z.literal('all'), z.array(GitHistoryRefName).max(1000)]) + .optional(), + historyToken: z.string().max(100).optional(), skip: z.number().int().min(0).optional() }) diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index ddfcc68a076b..d60203200abc 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -278,6 +278,7 @@ import { GitHistory, GitPush, GitRebaseFromBase, + GitRefs, GitRemoteCommitUrl, GitRemoteFileUrl, GitResolveConflict, @@ -1075,6 +1076,7 @@ export const RPC_PARAMS_BY_METHOD = { 'git.pull': GitTargetedRemote, 'git.push': GitPush, 'git.rebaseFromBase': GitRebaseFromBase, + 'git.refs': GitRefs, 'git.remoteCommitUrl': GitRemoteCommitUrl, 'git.remoteFileUrl': GitRemoteFileUrl, 'git.resolveConflict': GitResolveConflict, diff --git a/src/shared/source-control/runtime/git-graph-capabilities.ts b/src/shared/source-control/runtime/git-graph-capabilities.ts new file mode 100644 index 000000000000..98b86e8edc15 --- /dev/null +++ b/src/shared/source-control/runtime/git-graph-capabilities.ts @@ -0,0 +1,2 @@ +export const GIT_HISTORY_REFS_CAPABILITY = 'git.history-refs.v1' as const +export const GIT_GRAPH_TAB_CAPABILITY = 'layout.git-graph-tab.v1' as const diff --git a/src/shared/source-control/runtime/source-control-runtime-capabilities.ts b/src/shared/source-control/runtime/source-control-runtime-capabilities.ts index aa903c3d2643..b6e46855a074 100644 --- a/src/shared/source-control/runtime/source-control-runtime-capabilities.ts +++ b/src/shared/source-control/runtime/source-control-runtime-capabilities.ts @@ -1,3 +1,4 @@ +import { GIT_HISTORY_REFS_CAPABILITY, GIT_GRAPH_TAB_CAPABILITY } from './git-graph-capabilities' export const GITHUB_COMPLETE_PR_CHECK_OBSERVATION_CAPABILITY = 'github.complete-pr-check-observation.v1' as const export const GITHUB_MARK_PR_READY_RUNTIME_CAPABILITY = 'github.markPRReadyForReview' as const @@ -20,6 +21,8 @@ export const ANTIGRAVITY_CONFIGURED_MODEL_RUNTIME_CAPABILITY = 'git.antigravity-configured-model.v1' as const export const SOURCE_CONTROL_RUNTIME_CAPABILITIES = [ + GIT_HISTORY_REFS_CAPABILITY, + GIT_GRAPH_TAB_CAPABILITY, GITHUB_COMPLETE_PR_CHECK_OBSERVATION_CAPABILITY, GITHUB_EXACT_WORK_ITEM_TARGET_RUNTIME_CAPABILITY, ANTIGRAVITY_CONFIGURED_MODEL_RUNTIME_CAPABILITY, From fe7fa0b64f0cf99a5c09f429c9a960a708a27fcf Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 5 Nov 2026 19:32:46 -0800 Subject: [PATCH 05/52] Add the Git Graph tab and commit details Open the all-branch view from Source Control or the command palette, preserve older clients' layouts, and keep the sidebar HEAD-only. --- .../desktop-renderer-runtime-capabilities.ts | 2 + .../applying-settings/ui-state-read.ts | 2 + .../applying-settings/ui-state-update.ts | 4 + .../normalize-loaded-ui-state.ts | 2 + .../repo-lifecycle-ui-residue.ts | 6 +- .../wsl-move-ui-routing-rewrite.ts | 10 + .../worktree-identity-migration.ts | 3 + .../rpc/git-graph-layout-projection.test.ts | 145 +++++++++++ .../rpc/git-graph-layout-projection.ts | 174 ++++++++++++++ .../rpc/methods/workspace-layout.test.ts | 17 +- .../runtime/rpc/methods/workspace-layout.ts | 27 ++- .../src/app-shell/use-persisted-ui-writer.ts | 1 + .../src/components/cmd-j/quick-actions.ts | 22 ++ .../src/components/editor/EditorContent.tsx | 5 + .../src/components/editor/editor-header.ts | 8 + .../src/components/editor/editor-labels.ts | 3 + .../editor/git-graph/git-graph-details.tsx | 103 ++++++++ .../editor/git-graph/git-graph-filter.tsx | 161 +++++++++++++ .../editor/git-graph/git-graph-ref-menu.tsx | 115 +++++++++ .../git-graph/git-graph-rendering.test.tsx | 103 ++++++++ .../editor/git-graph/git-graph-tab.tsx | 225 ++++++++++++++++++ .../editor/git-graph/use-git-graph-history.ts | 185 ++++++++++++++ .../commit/use-commit-action.ts | 2 + .../source-control/panel/panel-content.tsx | 1 + .../sync/git-graph-open-button.tsx | 56 +++++ .../sync/git-history-commit-files.tsx | 20 +- .../source-control/sync/git-history-panel.tsx | 153 ++++++------ .../source-control/sync/remote-refresh.ts | 1 + .../src/components/tab-bar/EditorFileTab.tsx | 2 +- .../components/tab-bar/RecentTabSwitcher.tsx | 3 +- ...use-worktree-jump-palette-quick-actions.ts | 55 ++++- ...worktree-jump-palette-selection-actions.ts | 3 + ...ktree-jump-palette-project-action-rows.tsx | 1 + src/renderer/src/i18n/locales/de.json | 24 ++ src/renderer/src/i18n/locales/en.json | 24 ++ src/renderer/src/i18n/locales/es.json | 24 ++ src/renderer/src/i18n/locales/fr.json | 24 ++ src/renderer/src/i18n/locales/ja.json | 24 ++ src/renderer/src/i18n/locales/ko.json | 24 ++ src/renderer/src/i18n/locales/pt.json | 24 ++ src/renderer/src/i18n/locales/ru.json | 24 ++ src/renderer/src/i18n/locales/tr.json | 24 ++ src/renderer/src/i18n/locales/zh-Hant.json | 24 ++ src/renderer/src/i18n/locales/zh.json | 24 ++ src/renderer/src/lib/git-graph-tab.ts | 102 ++++++++ .../src/runtime/mobile-session-tab-close.ts | 8 +- .../src/runtime/server-layout-frame-ids.ts | 1 + .../editor/git/git-status-reconciliation.ts | 6 +- .../editor/tabs/editor-tab-content-type.ts | 14 +- .../editor-tab-open-through-layout-owner.ts | 3 +- .../editor/tabs/open-file-layout-view.ts | 2 + .../editor/tabs/workspace-editor-item.ts | 14 +- .../store/slices/editor/types/open-file.ts | 2 +- .../slices/persisted-ui-write-baseline.ts | 5 + .../ui/ui-slice-contract-preferences.ts | 1 + .../slices/ui/ui-slice-hydration-actions.ts | 1 + .../slices/ui/ui-slice-preference-actions.ts | 1 + .../session/worktree-identity-rename-state.ts | 1 + .../teardown/remove-worktree-store-cleanup.ts | 1 + .../teardown/worktree-purge-state.ts | 1 + src/shared/editor-tab-view-types.ts | 1 + ...tron-remote-runtime-client-capabilities.ts | 2 + src/shared/git/history/git-graph-filters.ts | 22 ++ src/shared/persisted-ui-state-types.ts | 2 + src/shared/rpc-contract/client-ui-params.ts | 7 + .../workspace-layout-editor-file-params.ts | 3 +- .../rpc-contract/workspace-layout-params.ts | 2 +- src/shared/tab-types.ts | 1 + src/shared/web-runtime-client-capabilities.ts | 2 + .../old-client-session-tabs-projection.ts | 1 + .../saved-editor-tab-restore.ts | 5 +- src/shared/workspace-layout/tab-order.ts | 3 +- ...rkspace-layout-load-view-less-tabs.test.ts | 3 +- .../workspace-layout-workspace-move.ts | 3 +- .../workspace-session-tab-type-schema.ts | 1 + .../wsl-move/wsl-move-ui-dispositions.ts | 1 + 76 files changed, 1990 insertions(+), 116 deletions(-) create mode 100644 src/main/runtime/rpc/git-graph-layout-projection.test.ts create mode 100644 src/main/runtime/rpc/git-graph-layout-projection.ts create mode 100644 src/renderer/src/components/editor/git-graph/git-graph-details.tsx create mode 100644 src/renderer/src/components/editor/git-graph/git-graph-filter.tsx create mode 100644 src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx create mode 100644 src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx create mode 100644 src/renderer/src/components/editor/git-graph/git-graph-tab.tsx create mode 100644 src/renderer/src/components/editor/git-graph/use-git-graph-history.ts create mode 100644 src/renderer/src/components/right-sidebar/source-control/sync/git-graph-open-button.tsx create mode 100644 src/renderer/src/lib/git-graph-tab.ts create mode 100644 src/shared/git/history/git-graph-filters.ts diff --git a/src/main/ipc/desktop-renderer-runtime-capabilities.ts b/src/main/ipc/desktop-renderer-runtime-capabilities.ts index 0b5be95ddc55..6f4392173e2d 100644 --- a/src/main/ipc/desktop-renderer-runtime-capabilities.ts +++ b/src/main/ipc/desktop-renderer-runtime-capabilities.ts @@ -1,3 +1,4 @@ +import { GIT_GRAPH_TAB_CAPABILITY } from '../../shared/source-control/runtime/git-graph-capabilities' import { REPO_SEARCH_QUALIFIED_REFS_RUNTIME_CAPABILITY, type RuntimeCapability @@ -15,6 +16,7 @@ import { /** Curate one capability set for unary/streaming desktop calls; remote-only gates can alter local semantics even on the same build. */ export const DESKTOP_RENDERER_RUNTIME_CLIENT_CAPABILITIES: readonly RuntimeCapability[] = [ + GIT_GRAPH_TAB_CAPABILITY, ...STRUCTURED_AGENT_SESSION_RENDERER_CLIENT_CAPABILITIES, REPO_SEARCH_QUALIFIED_REFS_RUNTIME_CAPABILITY, // Agent-launch authorization requires this even for the same-build desktop renderer. diff --git a/src/main/persistence/applying-settings/ui-state-read.ts b/src/main/persistence/applying-settings/ui-state-read.ts index d95f8ee45598..7d91463a4751 100644 --- a/src/main/persistence/applying-settings/ui-state-read.ts +++ b/src/main/persistence/applying-settings/ui-state-read.ts @@ -1,3 +1,4 @@ +import { normalizeGitGraphFilters } from '../../../shared/git/history/git-graph-filters' import { normalizeExplorerDisplayRootByWorktree } from '../../../shared/file-explorer-display-root' import type { PersistedState } from '../../../shared/persisted-state-types' import { @@ -72,6 +73,7 @@ export function getPersistedUI( explorerDisplayRootByWorktree: normalizeExplorerDisplayRootByWorktree( state.ui?.explorerDisplayRootByWorktree ), + gitGraphFiltersByWorktree: normalizeGitGraphFilters(state.ui?.gitGraphFiltersByWorktree), showDotfilesByWorktree: normalizeShowDotfilesByWorktree(state.ui?.showDotfilesByWorktree), featureTipsSeenIds: normalizeFeatureTipIds(state.ui?.featureTipsSeenIds), contextualToursSeenIds: normalizeContextualTourIds(state.ui?.contextualToursSeenIds), diff --git a/src/main/persistence/applying-settings/ui-state-update.ts b/src/main/persistence/applying-settings/ui-state-update.ts index 7b456a14c383..da7f0275183a 100644 --- a/src/main/persistence/applying-settings/ui-state-update.ts +++ b/src/main/persistence/applying-settings/ui-state-update.ts @@ -1,3 +1,4 @@ +import { normalizeGitGraphFilters } from '../../../shared/git/history/git-graph-filters' import { normalizeExplorerDisplayRootByWorktree } from '../../../shared/file-explorer-display-root' import type { PersistedState } from '../../../shared/persisted-state-types' import { @@ -190,6 +191,9 @@ export function updatePersistedUI( : normalizeExplorerDisplayRootByWorktree( operations.state.ui?.explorerDisplayRootByWorktree ), + gitGraphFiltersByWorktree: normalizeGitGraphFilters( + sanitizedUpdates.gitGraphFiltersByWorktree ?? operations.state.ui?.gitGraphFiltersByWorktree + ), showDotfilesByWorktree: sanitizedUpdates.showDotfilesByWorktree !== undefined ? normalizeShowDotfilesByWorktree(sanitizedUpdates.showDotfilesByWorktree) diff --git a/src/main/persistence/loading-store/normalize-loaded-ui-state.ts b/src/main/persistence/loading-store/normalize-loaded-ui-state.ts index 5405a62971ea..edc2fda00e47 100644 --- a/src/main/persistence/loading-store/normalize-loaded-ui-state.ts +++ b/src/main/persistence/loading-store/normalize-loaded-ui-state.ts @@ -1,3 +1,4 @@ +import { normalizeGitGraphFilters } from '../../../shared/git/history/git-graph-filters' import { resolveStatusBarCompactChangeNoticeDismissed } from '../../../shared/status-bar-compact-change-notice' import { migrateExplorerDisplayRoots } from '../../../shared/file-explorer-display-root' import { @@ -222,6 +223,7 @@ export function normalizeLoadedUiState( sortBy: migrate ? ('smart' as const) : sort, _explorerDisplayRootMigrated: true, explorerDisplayRootByWorktree, + gitGraphFiltersByWorktree: normalizeGitGraphFilters(parsed.ui?.gitGraphFiltersByWorktree), showDotfilesByWorktree: normalizeShowDotfilesByWorktree(parsed.ui?.showDotfilesByWorktree), workspaceStatuses, _workspaceStatusesDefaultOrderMigrated: true, diff --git a/src/main/persistence/loading-store/repo-lifecycle-ui-residue.ts b/src/main/persistence/loading-store/repo-lifecycle-ui-residue.ts index 1bd943a6a1ef..2c67c68cdd77 100644 --- a/src/main/persistence/loading-store/repo-lifecycle-ui-residue.ts +++ b/src/main/persistence/loading-store/repo-lifecycle-ui-residue.ts @@ -14,7 +14,11 @@ export function pruneDeregisteredRepoUiResidue( ui.lastActiveWorktreeId = null } ui.filterRepoIds = ui.filterRepoIds?.filter((repoId) => !orphanRepoIds.has(repoId)) ?? [] - for (const record of [ui.explorerDisplayRootByWorktree, ui.showDotfilesByWorktree]) { + for (const record of [ + ui.explorerDisplayRootByWorktree, + ui.showDotfilesByWorktree, + ui.gitGraphFiltersByWorktree + ]) { for (const worktreeId of Object.keys(record ?? {})) { if (isOrphanWorktree(worktreeId)) { delete record?.[worktreeId] diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-ui-routing-rewrite.ts b/src/main/persistence/moving-wsl-projects/wsl-move-ui-routing-rewrite.ts index 99e456127fa8..0ac38bf50d08 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-ui-routing-rewrite.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-ui-routing-rewrite.ts @@ -28,6 +28,7 @@ export type WslMoveUiRoutingState = Pick< PersistedUIState, | 'lastActiveWorktreeId' | 'showDotfilesByWorktree' + | 'gitGraphFiltersByWorktree' | 'explorerDisplayRootByWorktree' | 'workspaceCleanup' | 'manualRepoOrder' @@ -61,6 +62,15 @@ export function rewriteWslMoveUiRouting( if (dotfiles) { updates.showDotfilesByWorktree = dotfiles } + const graphFilters = withHostKeys( + ui.gitGraphFiltersByWorktree, + hostWorktreeKey, + (value) => value, + scope.inScope + ) + if (graphFilters) { + updates.gitGraphFiltersByWorktree = graphFilters + } const roots = withHostKeys( ui.explorerDisplayRootByWorktree, hostWorktreeKey, diff --git a/src/main/persistence/tracking-repos/worktree-identity-migration.ts b/src/main/persistence/tracking-repos/worktree-identity-migration.ts index 045c0061f722..a26fbb07a961 100644 --- a/src/main/persistence/tracking-repos/worktree-identity-migration.ts +++ b/src/main/persistence/tracking-repos/worktree-identity-migration.ts @@ -280,6 +280,9 @@ export function migrateWorktreeIdentity( if (state.ui?.explorerDisplayRootByWorktree) { changed = moveKey(state.ui.explorerDisplayRootByWorktree) || changed } + if (state.ui?.gitGraphFiltersByWorktree) { + changed = moveKey(state.ui.gitGraphFiltersByWorktree) || changed + } const showDotfiles = state.ui?.showDotfilesByWorktree if (showDotfiles) { changed = moveKey(showDotfiles) || changed diff --git a/src/main/runtime/rpc/git-graph-layout-projection.test.ts b/src/main/runtime/rpc/git-graph-layout-projection.test.ts new file mode 100644 index 000000000000..5ef25c77fb27 --- /dev/null +++ b/src/main/runtime/rpc/git-graph-layout-projection.test.ts @@ -0,0 +1,145 @@ +import { expect, it } from 'vitest' +import { + createGitGraphFrameProjection, + projectGitGraphLayout, + translateGitGraphLayoutCommand +} from './git-graph-layout-projection' +import type { PublishedWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-published' +import { + diffPublishedLayouts, + indexPublishedLayout +} from '../../../shared/workspace-layout/workspace-layout-records' + +function layout(): PublishedWorkspaceLayout { + return { + worktreeId: 'w', + editorFiles: [], + browserTabs: [], + tabs: ['a', 'graph', 'b', 'c'].map((id) => ({ + id, + entityId: id, + kind: id === 'graph' ? 'git-graph' : 'editor', + executionHostId: 'local', + createdAt: 0, + customTitle: null, + color: null + })), + groups: [ + { id: 'g1', tabIds: ['a', 'graph', 'b'] }, + { id: 'g2', tabIds: ['c'] } + ], + groupLayout: { + type: 'split', + direction: 'horizontal', + ratio: 0.3, + first: { type: 'leaf', groupId: 'g1' }, + second: { type: 'leaf', groupId: 'g2' } + } + } +} + +it('hides graph tabs in snapshots and later record frames while preserving sequence', () => { + const original = layout() + const project = createGitGraphFrameProjection() + expect( + project({ type: 'snapshot', seq: 1, workspaces: [{ key: 'w', layout: original }] }) + ).toMatchObject({ + workspaces: [ + { + layout: { + groups: [ + { id: 'g1', tabIds: ['a', 'b'] }, + { id: 'g2', tabIds: ['c'] } + ] + } + } + ] + }) + const after = { + ...original, + groups: [ + { id: 'g1', tabIds: ['graph'] }, + { id: 'g2', tabIds: ['a', 'b', 'c'] } + ] + } + const change = diffPublishedLayouts( + 'w', + indexPublishedLayout(original), + indexPublishedLayout(after), + after + )! + const frame = project({ type: 'records', epoch: 'e', seq: 2, workspaces: [change] }) + expect(frame).toMatchObject({ + type: 'records', + epoch: 'e', + seq: 2, + workspaces: [ + { + workspace: { + groups: [{ id: 'g2', tabIds: ['a', 'b', 'c'] }], + groupLayout: { type: 'leaf', groupId: 'g2' } + } + } + ] + }) + expect(projectGitGraphLayout(after).tabs.map((tab) => tab.id)).toEqual(['a', 'b', 'c']) +}) + +it('preserves hidden tab slots during reorders and translates collapsed split paths', () => { + const original = layout() + expect( + translateGitGraphLayoutCommand( + { type: 'moveTab', workspace: 'w', tabId: 'b', toGroupId: 'g1', index: 0 }, + original + ) + ).toMatchObject({ index: 0 }) + expect( + translateGitGraphLayoutCommand( + { + type: 'moveTab', + workspace: 'w', + tabId: 'b', + toGroupId: 'g1', + index: 1, + afterTabId: 'gone' + }, + original + ) + ).toMatchObject({ index: 2 }) + const split: PublishedWorkspaceLayout = { + ...original, + groups: [ + { id: 'hidden', tabIds: ['graph'] }, + { id: 'g1', tabIds: ['a', 'b'] }, + { id: 'g2', tabIds: ['c'] } + ], + groupLayout: { + type: 'split', + direction: 'vertical', + ratio: 0.2, + first: { type: 'leaf', groupId: 'hidden' }, + second: original.groupLayout! + } + } + expect(projectGitGraphLayout(split).groupLayout).toEqual(original.groupLayout) + expect( + translateGitGraphLayoutCommand( + { + type: 'setGroupRatios', + workspace: 'w', + ratios: [ + { path: '', ratio: 0.7, split: { direction: 'horizontal', first: 'g1', second: 'g2' } } + ] + }, + split + ) + ).toEqual({ + type: 'setGroupRatios', + workspace: 'w', + groupLayout: undefined, + ratios: [ + { path: 'second', ratio: 0.7, split: { direction: 'horizontal', first: 'g1', second: 'g2' } } + ] + }) + expect(split.groupLayout).toMatchObject({ ratio: 0.2 }) +}) diff --git a/src/main/runtime/rpc/git-graph-layout-projection.ts b/src/main/runtime/rpc/git-graph-layout-projection.ts new file mode 100644 index 000000000000..b0462f789396 --- /dev/null +++ b/src/main/runtime/rpc/git-graph-layout-projection.ts @@ -0,0 +1,174 @@ +import { GIT_GRAPH_TAB_CAPABILITY } from '../../../shared/source-control/runtime/git-graph-capabilities' +import type { TabGroupLayoutNode } from '../../../shared/tab-types' +import type { PublishedWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-published' +import { + applyWorkspaceLayoutRecordChange, + diffPublishedLayouts, + indexPublishedLayout +} from '../../../shared/workspace-layout/workspace-layout-records' +import type { WorkspaceLayoutStreamFrame } from '../../../shared/workspace-layout/workspace-layout-stream-frames' +import type { WindowLayoutCommand } from '../terminal/layout/runtime-layout-apply' +import { + changedSplitRatios, + splitRatioIntentAt, + withGroupSplitRatios +} from '../../../shared/workspace-layout/split-ratio-intents' + +export function readsGitGraph(capabilities?: readonly string[]): boolean { + return capabilities?.includes(GIT_GRAPH_TAB_CAPABILITY) === true +} + +function projectedTree( + node: TabGroupLayoutNode | undefined, + groups: Set, + paths?: Map, + fullPath = '', + path = '' +): TabGroupLayoutNode | undefined { + if (!node) { + return undefined + } + if (node.type === 'leaf') { + return groups.has(node.groupId) ? node : undefined + } + const join = (base: string, side: string) => (base ? `${base}.${side}` : side) + const has = (child: TabGroupLayoutNode): boolean => + child.type === 'leaf' ? groups.has(child.groupId) : has(child.first) || has(child.second) + const firstVisible = has(node.first) + const secondVisible = has(node.second) + if (!firstVisible) { + return projectedTree(node.second, groups, paths, join(fullPath, 'second'), path) + } + if (!secondVisible) { + return projectedTree(node.first, groups, paths, join(fullPath, 'first'), path) + } + paths?.set(path, fullPath) + return { + ...node, + first: projectedTree(node.first, groups, paths, join(fullPath, 'first'), join(path, 'first'))!, + second: projectedTree( + node.second, + groups, + paths, + join(fullPath, 'second'), + join(path, 'second') + )! + } +} + +export function projectGitGraphLayout(layout: PublishedWorkspaceLayout): PublishedWorkspaceLayout { + const hidden = new Set(layout.tabs.filter((tab) => tab.kind === 'git-graph').map((tab) => tab.id)) + if (!hidden.size) { + return layout + } + const hiddenFiles = new Set( + layout.tabs.filter((tab) => hidden.has(tab.id)).map((tab) => tab.entityId) + ) + const groups = layout.groups + .map((group) => ({ ...group, tabIds: group.tabIds.filter((id) => !hidden.has(id)) })) + .filter((group) => group.tabIds.length) + return { + ...layout, + tabs: layout.tabs.filter((tab) => !hidden.has(tab.id)), + editorFiles: layout.editorFiles.filter((file) => !hiddenFiles.has(file.filePath)), + groups, + groupLayout: projectedTree(layout.groupLayout, new Set(groups.map((group) => group.id))) + } +} + +// Re-diff whole projected layouts: a delta alone may omit the group a hidden tab made empty. +export function createGitGraphFrameProjection() { + const layouts = new Map() + return (frame: WorkspaceLayoutStreamFrame): WorkspaceLayoutStreamFrame => { + switch (frame.type) { + case 'end': + return frame + case 'removed': + layouts.delete(frame.key) + return frame + case 'snapshot': + layouts.clear() + return { + ...frame, + workspaces: frame.workspaces.map(({ key, layout }) => { + layouts.set(key, layout) + return { key, layout: projectGitGraphLayout(layout) } + }) + } + case 'workspace': + layouts.set(frame.key, frame.layout) + return { ...frame, layout: projectGitGraphLayout(frame.layout) } + case 'records': + return { + ...frame, + workspaces: frame.workspaces.flatMap((change) => { + const before = layouts.get(change.key) + if (change.change === 'removed') { + layouts.delete(change.key) + return [change] + } + const after = applyWorkspaceLayoutRecordChange(before, change)! + layouts.set(change.key, after) + const projected = projectGitGraphLayout(after) + const diff = diffPublishedLayouts( + change.key, + before ? indexPublishedLayout(projectGitGraphLayout(before)) : null, + indexPublishedLayout(projected), + projected + ) + return diff ? [diff] : [] + }) + } + } + } +} + +export function translateGitGraphLayoutCommand( + command: WindowLayoutCommand, + layout: PublishedWorkspaceLayout +): WindowLayoutCommand { + const projected = projectGitGraphLayout(layout) + if (projected === layout) { + return command + } + if (command.type === 'moveTab') { + const fullOrder = + layout.groups + .find((group) => group.id === command.toGroupId) + ?.tabIds.filter((id) => id !== command.tabId) ?? [] + const visible = new Set(projected.tabs.map((tab) => tab.id)) + const visibleOrder = fullOrder.filter((id) => visible.has(id)) + const after = command.afterTabId ? visibleOrder.indexOf(command.afterTabId) : -1 + const at = command.afterTabId === null ? 0 : after !== -1 ? after + 1 : command.index + const next = visibleOrder[at] + return { + ...command, + afterTabId: undefined, + index: next ? fullOrder.indexOf(next) : fullOrder.length + } + } + if (command.type === 'setGroupRatios') { + const paths = new Map() + projectedTree(layout.groupLayout, new Set(projected.groups.map((group) => group.id)), paths) + const ratios = + command.ratios ?? + (projected.groupLayout && command.groupLayout + ? changedSplitRatios(projected.groupLayout, command.groupLayout) + : []) + if (!projected.groupLayout || !withGroupSplitRatios(projected.groupLayout, ratios)) { + throw new Error('Layout split changed; refresh and try again') + } + return { + ...command, + groupLayout: undefined, + ratios: ratios.map(({ path, ratio }) => { + const translated = paths.get(path) + if (translated === undefined) { + throw new Error('Layout split changed; refresh and try again') + } + return splitRatioIntentAt(layout.groupLayout!, translated, ratio)! + }) + } + } + return command +} diff --git a/src/main/runtime/rpc/methods/workspace-layout.test.ts b/src/main/runtime/rpc/methods/workspace-layout.test.ts index 76e451053c20..a3072a859974 100644 --- a/src/main/runtime/rpc/methods/workspace-layout.test.ts +++ b/src/main/runtime/rpc/methods/workspace-layout.test.ts @@ -27,8 +27,14 @@ function harness(epoch?: string) { publish = listener return { snapshot: [ - { key: 'a', layout: { worktreeId: 'a' } }, - { key: 'b', layout: { worktreeId: 'b' } } + { + key: 'a', + layout: { worktreeId: 'a', tabs: [], groups: [], editorFiles: [], browserTabs: [] } + }, + { + key: 'b', + layout: { worktreeId: 'b', tabs: [], groups: [], editorFiles: [], browserTabs: [] } + } ], seq: 4, ...(epoch ? { epoch } : {}), @@ -66,7 +72,12 @@ describe('layout.subscribe', () => { { type: 'snapshot', subscriptionId: expect.any(String), - workspaces: [{ key: 'b', layout: { worktreeId: 'b' } }], + workspaces: [ + { + key: 'b', + layout: { worktreeId: 'b', tabs: [], groups: [], editorFiles: [], browserTabs: [] } + } + ], seq: 4 } ]) diff --git a/src/main/runtime/rpc/methods/workspace-layout.ts b/src/main/runtime/rpc/methods/workspace-layout.ts index 20f5121a5db7..a956b724e364 100644 --- a/src/main/runtime/rpc/methods/workspace-layout.ts +++ b/src/main/runtime/rpc/methods/workspace-layout.ts @@ -1,3 +1,8 @@ +import { + readsGitGraph, + createGitGraphFrameProjection, + translateGitGraphLayoutCommand +} from '../git-graph-layout-projection' // Paired desktops use layout read/stream/apply only when the server offers layout.intents.v1; mobile is excluded. import { @@ -23,9 +28,11 @@ export const WORKSPACE_LAYOUT_METHODS = [ name: 'layout.subscribe', permission: 'workspace', params: LayoutSubscribeParams, - handler: async (params, { runtime, connectionId, signal }, emitFrame) => { + handler: async (params, { runtime, connectionId, signal, clientCapabilities }, emitFrame) => { // Keep emitted frames checked against the client contract. - const emit = (frame: WorkspaceLayoutStreamFrame): void => emitFrame(frame) + const project = createGitGraphFrameProjection() + const emit = (frame: WorkspaceLayoutStreamFrame): void => + emitFrame(readsGitGraph(clientCapabilities) ? frame : project(frame)) const keys = params?.workspaces const wanted = (key: string) => !Array.isArray(keys) || keys.includes(key) await new Promise((resolve) => { @@ -97,7 +104,21 @@ export const LAYOUT_APPLY_METHODS = [ name: 'layout.apply', permission: 'workspace', params: LayoutApplyParams, - handler: async (params, { runtime }) => runtime.applyLayoutCommand(params.command) + handler: async (params, { runtime, clientCapabilities }) => { + const command = params.command + if ( + readsGitGraph(clientCapabilities) || + (command.type !== 'moveTab' && command.type !== 'setGroupRatios') + ) { + return runtime.applyLayoutCommand(command) + } + const { snapshot, unsubscribe } = runtime.subscribeWorkspaceLayouts(() => {}) + unsubscribe() + const layout = snapshot.find((entry) => entry.key === command.workspace)?.layout + return runtime.applyLayoutCommand( + layout ? translateGitGraphLayoutCommand(params.command, layout) : params.command + ) + } }), // Reopen held panes; main's frames, not the reply, show their start. defineMethod({ diff --git a/src/renderer/src/app-shell/use-persisted-ui-writer.ts b/src/renderer/src/app-shell/use-persisted-ui-writer.ts index 7ab29dd0472f..c0c14a3fd59b 100644 --- a/src/renderer/src/app-shell/use-persisted-ui-writer.ts +++ b/src/renderer/src/app-shell/use-persisted-ui-writer.ts @@ -121,6 +121,7 @@ export function usePersistedUIWriter(): void { const activeView = useAppStore((s) => s.activeView) const ui = useAppStore( useShallow((s): PersistedUIWriteBaseline => ({ + gitGraphFiltersByWorktree: s.gitGraphFiltersByWorktree, sidebarWidth: s.sidebarWidth, sidebarOpen: s.sidebarOpen, rightSidebarOpen: s.rightSidebarOpen, diff --git a/src/renderer/src/components/cmd-j/quick-actions.ts b/src/renderer/src/components/cmd-j/quick-actions.ts index 1c10ebc4be53..2925bb5c6cbf 100644 --- a/src/renderer/src/components/cmd-j/quick-actions.ts +++ b/src/renderer/src/components/cmd-j/quick-actions.ts @@ -1,4 +1,6 @@ +import { gitGraphSupport, openGitGraph } from '@/lib/git-graph-tab' import { + GitGraph, FileText, FolderPlus, Globe, @@ -33,6 +35,7 @@ export type CmdJQuickAction = { icon: LucideIcon verbKeywords: string[] /** Query-bound actions must still match the live input when selected. */ + disabled?: boolean sourceQuery?: string isAvailable: (ctx: CmdJQuickActionContext) => CmdJQuickActionAvailability run: (ctx: CmdJQuickActionContext) => Promise @@ -78,6 +81,25 @@ export async function runBrowserWorkspaceAction( // Keep context-heavy imports in Settings, where explanatory UI and failure states fit. export const getCmdJQuickActions = createLocalizedCatalog((): CmdJQuickAction[] => [ + { + id: 'git-graph', + kind: 'action', + title: translate('gitGraph.title', 'Git Graph'), + description: '', + icon: GitGraph, + verbKeywords: ['git graph', 'commit history', 'branches'], + isAvailable: (ctx) => + ctx.activeWorktreeId && gitGraphSupport(ctx.activeWorktreeId) === true + ? { available: true } + : { available: false, reason: 'loading' }, + run: async (ctx) => { + if (!ctx.activeWorktreeId || gitGraphSupport(ctx.activeWorktreeId) !== true) { + return { status: 'unavailable', reason: 'loading' } + } + await openGitGraph(ctx.activeWorktreeId) + return { status: 'ok' } + } + }, { id: 'new-browser-tab', kind: 'action', diff --git a/src/renderer/src/components/editor/EditorContent.tsx b/src/renderer/src/components/editor/EditorContent.tsx index 2604ae5273ab..2bd9c1bcff88 100644 --- a/src/renderer/src/components/editor/EditorContent.tsx +++ b/src/renderer/src/components/editor/EditorContent.tsx @@ -1,3 +1,4 @@ +import { GitGraphTab } from './git-graph/git-graph-tab' import { useAppStore } from '@/store' import type { ActivePluginCustomEditor } from '@/store/plugin-custom-editors' import type { MarkdownViewMode, OpenFile, PendingEditorReveal } from '@/store/slices/editor' @@ -131,6 +132,10 @@ export function EditorContent({ activeFile.diffSource === 'combined-branch' || activeFile.diffSource === 'combined-commit') + if (activeFile.mode === 'git-graph') { + return + } + if (activeFile.mode === 'check-details') { const checkRunDetails = activeFile.checkRunDetails if (!checkRunDetails) { diff --git a/src/renderer/src/components/editor/editor-header.ts b/src/renderer/src/components/editor/editor-header.ts index b3bc21547f63..e6ef2c0454b9 100644 --- a/src/renderer/src/components/editor/editor-header.ts +++ b/src/renderer/src/components/editor/editor-header.ts @@ -34,6 +34,14 @@ export function getEditorHeaderCopyState(file: OpenFile): EditorHeaderCopyState } } + if (file.mode === 'git-graph') { + return { + copyText: null, + copyToastLabel: '', + pathLabel: translate('gitGraph.title', 'Git Graph'), + pathTitle: translate('gitGraph.title', 'Git Graph') + } + } if (file.mode === 'check-details') { const label = file.checkRunDetails?.check.name ?? diff --git a/src/renderer/src/components/editor/editor-labels.ts b/src/renderer/src/components/editor/editor-labels.ts index 53f885b1da26..1888ca6642a0 100644 --- a/src/renderer/src/components/editor/editor-labels.ts +++ b/src/renderer/src/components/editor/editor-labels.ts @@ -42,6 +42,9 @@ export function getEditorDisplayLabel( return translate('auto.components.editor.editorLabels.conflictReview', 'Conflict Review') } + if (file.mode === 'git-graph') { + return translate('gitGraph.title', 'Git Graph') + } if (file.mode === 'check-details') { return file.checkRunDetails?.check.name ?? getBaseLabel(file, variant) } diff --git a/src/renderer/src/components/editor/git-graph/git-graph-details.tsx b/src/renderer/src/components/editor/git-graph/git-graph-details.tsx new file mode 100644 index 000000000000..a0213b42d4ef --- /dev/null +++ b/src/renderer/src/components/editor/git-graph/git-graph-details.tsx @@ -0,0 +1,103 @@ +import { useEffect, useState } from 'react' +import { Copy } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { + GitHistoryCommitFiles, + type GitHistoryCommitFilesState +} from '@/components/right-sidebar/source-control/sync/git-history-commit-files' +import { formatGitHistoryTimestamp } from '@/components/right-sidebar/source-control/sync/git-history-format' +import type { useGitHistoryCommitActions } from '@/components/right-sidebar/source-control/sync/use-git-history-commit-actions' +import type { GitHistoryItem } from '../../../../../shared/git/history/git-history-types' +import { translate } from '@/i18n/i18n' + +export function GitGraphDetails({ + item, + actions, + onParent +}: { + item: GitHistoryItem + actions: ReturnType + onParent: (id: string) => void +}) { + const [files, setFiles] = useState({ status: 'loading' }) + const loadFiles = actions.loadCommitFiles + useEffect(() => { + let live = true + setFiles({ status: 'loading' }) + void loadFiles(item) + .then((entries) => { + if (live) { + setFiles({ status: 'ready', entries }) + } + }) + .catch((cause) => { + if (live) { + setFiles({ status: 'error', error: String(cause) }) + } + }) + return () => { + live = false + } + }, [item, loadFiles]) + const body = item.message.startsWith(item.subject) + ? item.message.slice(item.subject.length).trim() + : item.message + return ( +
+
+

{item.subject}

+ {body &&

{body}

} +
+
+ {item.author} + {item.authorEmail ? ` <${item.authorEmail}>` : ''} +
+
{formatGitHistoryTimestamp(item.timestamp)}
+
+
+ {item.id} + + + + + {translate('gitGraph.copyHash', 'Copy commit hash')} + +
+ {!!item.parentIds.length && ( +
+ + {translate('gitGraph.parents', 'Parents')} + + {item.parentIds.map((id) => ( + + ))} +
+ )} +
+
+ {translate('gitGraph.files', 'Files')} +
+ actions.openCommitFile(item, entry, event)} + onOpenAll={() => void actions.openHistoryCommitDiff(item)} + /> +
+ ) +} diff --git a/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx b/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx new file mode 100644 index 000000000000..7061ada1bc22 --- /dev/null +++ b/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx @@ -0,0 +1,161 @@ +import { useEffect, useState } from 'react' +import { Button } from '@/components/ui/button' +import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' +import { Input } from '@/components/ui/input' +import { Checkbox } from '@/components/ui/checkbox' +import { getRuntimeGitRefs } from '@/runtime/runtime-git-status-client' +import { runtimeEnvironmentSupportsCapability } from '@/runtime/runtime-rpc-client' +import { GIT_HISTORY_REFS_CAPABILITY } from '../../../../../shared/source-control/runtime/git-graph-capabilities' +import { gitGraphScope } from '@/lib/git-graph-tab' +import { getConnectionId } from '@/lib/connection-context' +import { translate } from '@/i18n/i18n' +import type { + GitHistoryItemRef, + GitHistoryRefs +} from '../../../../../shared/git/history/git-history-types' + +export function GitGraphFilter({ + worktreeId, + filter, + supported, + onChange +}: { + worktreeId: string + filter: GitHistoryRefs + supported: boolean | undefined + onChange: (refs: GitHistoryRefs) => void +}) { + const [open, setOpen] = useState(false) + const [query, setQuery] = useState('') + const [refs, setRefs] = useState([]) + const [probe, setProbe] = useState<{ owner: string | undefined; capable: boolean | null }>() + const [error, setError] = useState() + const owner = JSON.stringify(gitGraphScope(worktreeId)?.route) + const capable = probe?.owner === owner ? probe?.capable : null + useEffect(() => { + let live = true + setProbe({ owner, capable: null }) + const scope = gitGraphScope(worktreeId) + if (scope) { + void ( + scope.target.kind === 'local' + ? Promise.resolve(true) + : runtimeEnvironmentSupportsCapability( + scope.target.environmentId, + GIT_HISTORY_REFS_CAPABILITY + ) + ) + .then((value) => { + if (live) { + setProbe({ owner, capable: value }) + } + }) + .catch(() => {}) + } + return () => { + live = false + } + }, [worktreeId, owner]) + useEffect(() => { + if (!open || !capable) { + return + } + let live = true + const scope = gitGraphScope(worktreeId) + if (scope) { + void getRuntimeGitRefs( + { + target: scope.target, + worktreeId, + worktreePath: scope.worktree.path, + connectionId: getConnectionId(worktreeId) ?? undefined + }, + query + ) + .then((rows) => { + if (live) { + setRefs(rows) + setError(undefined) + } + }) + .catch((cause) => { + if (live) { + setError(String(cause)) + } + }) + } + return () => { + live = false + } + }, [worktreeId, owner, query, open, capable]) + return ( +
+ + + + + +
+ + +
+ setQuery(event.target.value)} + placeholder={translate('gitGraph.searchRefs', 'Search branches and tags')} + /> + {error &&

{error}

} +
+ {refs.map((ref) => ( + + ))} +
+
+
+ {capable === false || (supported === false && capable === true) ? ( + + {translate( + 'gitGraph.oldServer', + "This server's Orca version shows only the current branch" + )} + + ) : null} +
+ ) +} diff --git a/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx b/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx new file mode 100644 index 000000000000..a703418176a7 --- /dev/null +++ b/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx @@ -0,0 +1,115 @@ +import { normalizeRuntimePathForComparison } from '../../../../../shared/cross-platform-path' +import { useRef, useState } from 'react' +import { + ContextMenu, + ContextMenuContent, + ContextMenuItem, + ContextMenuTrigger +} from '@/components/ui/context-menu' +import { useAppStore } from '@/store' +import { selectWorktreesByRepo } from '@/store/workspace-record-selectors' +import { gitGraphScope } from '@/lib/git-graph-tab' +import { getRuntimeGitRefs } from '@/runtime/runtime-git-status-client' +import { getConnectionId } from '@/lib/connection-context' +import { translate } from '@/i18n/i18n' +import type { GitHistoryItemRef } from '../../../../../shared/git/history/git-history-types' +import { getWorktreeExecutionHostId } from '../../../../../shared/execution-host' +import type { Worktree } from '../../../../../shared/worktree/types' +import { cn } from '@/lib/utils' + +export function GitGraphRefMenu({ + itemRef, + worktreeId, + current +}: { + itemRef: GitHistoryItemRef + worktreeId: string + current: boolean +}) { + const [workspace, setWorkspace] = useState() + const generation = useRef(0) + const readWorkspace = async () => { + const request = ++generation.current + setWorkspace(undefined) + const scope = gitGraphScope(worktreeId) + if (!scope || !itemRef.id.startsWith('refs/heads/')) { + return + } + try { + const refs = await getRuntimeGitRefs( + { + target: scope.target, + worktreeId, + worktreePath: scope.worktree.path, + connectionId: getConnectionId(worktreeId) ?? undefined + }, + itemRef.id + ) + const path = refs.find((ref) => ref.id === itemRef.id)?.worktreePath + if (request !== generation.current) { + return + } + const state = useAppStore.getState() + const worktrees = Object.values(selectWorktreesByRepo(state)).flat() + setWorkspace( + worktrees.find( + (row) => + path !== undefined && + normalizeRuntimePathForComparison(row.path) === + normalizeRuntimePathForComparison(path) && + row.id !== worktreeId && + getWorktreeExecutionHostId( + row, + state.repos.find((repo) => repo.id === row.repoId) + ) === scope.route.executionHostId + ) + ) + } catch { + /* A failed refresh cannot offer navigation to a stale checkout. */ + } + } + return ( + { + if (open) { + void readWorkspace() + } else { + generation.current++ + } + }} + > + + + {itemRef.name} + + + + void window.api.ui.writeClipboardText(itemRef.name)}> + {translate('gitGraph.copyBranch', 'Copy branch name')} + + {workspace && ( + { + const state = useAppStore.getState() + state.setActiveWorktree( + workspace.id, + getWorktreeExecutionHostId( + workspace, + state.repos.find((repo) => repo.id === workspace.repoId) + ) + ) + }} + > + {translate('gitGraph.switchWorkspace', 'Switch to workspace')} + + )} + + + ) +} diff --git a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx new file mode 100644 index 000000000000..ad8ff5e296d2 --- /dev/null +++ b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx @@ -0,0 +1,103 @@ +// @vitest-environment happy-dom +import { act } from 'react' +import { createRoot } from 'react-dom/client' +import { afterEach, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { GitHistoryPanel } from '@/components/right-sidebar/source-control/sync/git-history-panel' +import { GitGraphFilter } from './git-graph-filter' +import { gitGraphFilterSupported } from './use-git-graph-history' +import type { GitHistoryResult } from '../../../../../shared/git/history/git-history-types' +import * as graph from '../../../../../shared/git/history/git-history-graph' + +vi.mock('@/lib/git-graph-tab', () => ({ gitGraphScope: () => ({ target: { kind: 'local' } }) })) +vi.mock('@tanstack/react-virtual', () => ({ + useVirtualizer: (options: { count: number }) => ({ + getTotalSize: () => options.count * 28, + getVirtualItems: () => + Array.from({ length: options.count }, (_, index) => ({ index, start: index * 28 })), + measureElement: () => {} + }) +})) +const container = document.createElement('div') +document.body.appendChild(container) +let root = createRoot(container) +afterEach(async () => { + await act(async () => root.unmount()) + root = createRoot(container) + vi.restoreAllMocks() +}) +const result: GitHistoryResult = { + items: [{ id: 'a', subject: 'subject', message: 'subject', parentIds: [] }], + hasMore: false, + hasIncomingChanges: false, + hasOutgoingChanges: false, + limit: 50 +} + +it('keeps view models on expand and resize, rebuilding when history changes', async () => { + const build = vi.spyOn(graph, 'buildGitHistoryViewModels') + const render = (history: GitHistoryResult) => ( + + {}} + onRefresh={() => {}} + onLoadCommitFiles={async () => []} + onOpenCommitFile={() => {}} + /> + + ) + await act(async () => root.render(render(result))) + expect(build).toHaveBeenCalledTimes(1) + await act(async () => + (container.querySelector('[data-testid="git-history-row"]') as HTMLButtonElement).click() + ) + await act(async () => + container + .querySelector('[role="separator"]')! + .dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowUp', bubbles: true })) + ) + expect(build).toHaveBeenCalledTimes(1) + await act(async () => + root.render( + render({ + ...result, + items: [...result.items, { id: 'b', subject: 'next', message: 'next', parentIds: [] }] + }) + ) + ) + expect(build).toHaveBeenCalledTimes(2) + expect( + container.querySelector('[data-testid="git-history-row"]')?.getAttribute('aria-expanded') + ).toBe('true') +}) + +it('disables the branch filter when an older host omits the refs echo', async () => { + await act(async () => + root.render( + + {}} + /> + + ) + ) + expect(container.querySelector('button')?.disabled).toBe(true) + await act(async () => + root.render( + + {}} + /> + + ) + ) + expect(container.querySelector('button')?.disabled).toBe(false) +}) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx b/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx new file mode 100644 index 000000000000..e7bfd940def3 --- /dev/null +++ b/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx @@ -0,0 +1,225 @@ +import { useLayoutEffect, useMemo, useRef, useState } from 'react' +import { useVirtualizer } from '@tanstack/react-virtual' +import { RefreshCw } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { ContextMenu, ContextMenuTrigger } from '@/components/ui/context-menu' +import { GitHistoryCommitContextMenu } from '@/components/right-sidebar/source-control/sync/git-history-commit-context-menu' +import { GitHistoryGraphSvg } from '@/components/right-sidebar/source-control/sync/git-history-graph-svg' +import { useGitHistoryCommitActions } from '@/components/right-sidebar/source-control/sync/use-git-history-commit-actions' +import { formatGitHistoryTimestamp } from '@/components/right-sidebar/source-control/sync/git-history-format' +import { + buildDefaultGitHistoryColorMap, + buildGitHistoryViewModels +} from '../../../../../shared/git/history/git-history-graph' +import { useGitGraphHistory, gitGraphFilterSupported } from './use-git-graph-history' +import { GitGraphFilter } from './git-graph-filter' +import { GitGraphDetails } from './git-graph-details' +import { GitGraphRefMenu } from './git-graph-ref-menu' +import { cn } from '@/lib/utils' +import { translate } from '@/i18n/i18n' + +const sameGroup = () => undefined + +export function GitGraphTab({ worktreeId }: { worktreeId: string }) { + const history = useGitGraphHistory(worktreeId) + const { result, scope } = history + const rows = useMemo( + () => + result + ? buildGitHistoryViewModels( + result.items, + buildDefaultGitHistoryColorMap(result), + result.currentRef + ) + : [], + [result] + ) + const graphWidth = useMemo( + () => + rows.reduce( + (width, row) => + Math.max( + width, + (Math.max(row.inputSwimlanes.length, row.outputSwimlanes.length) + 1) * 11 + ), + 44 + ), + [rows] + ) + const columns = `160px ${graphWidth}px minmax(200px,1fr) 120px 100px` + const scroll = useRef(null) + const virtualizer = useVirtualizer({ + count: rows.length, + getScrollElement: () => scroll.current, + estimateSize: () => 24, + overscan: 12, + getItemKey: (index) => rows[index]!.historyItem.id + }) + const [selectedId, setSelectedId] = useState() + if (!selectedId && result?.items[0]) { + setSelectedId(result.items[0].id) + } + const selected = result?.items.find((item) => item.id === selectedId) ?? result?.items[0] + const [revealId, setRevealId] = useState() + useLayoutEffect(() => { + if (!revealId) { + return + } + const index = rows.findIndex((row) => row.historyItem.id === revealId) + if (index !== -1) { + virtualizer.scrollToIndex(index) + setRevealId(undefined) + } + }, [rows, revealId, virtualizer]) + const actions = useGitHistoryCommitActions({ + activeWorktreeId: worktreeId, + worktreePath: scope?.worktree.path ?? null, + activeRepoTarget: scope?.target ?? null, + resolveSplitTargetGroupId: sameGroup + }) + const selectParent = async (id: string) => { + await history.reveal(id) + setSelectedId(id) + setRevealId(id) + } + return ( +
+
+ + + + + + {translate('gitGraph.refresh', 'Refresh commits')} + +
+ {history.error && ( +
{history.error}
+ )} +
+
+
+ {translate('gitGraph.branchTag', 'Branch / Tag')} + {translate('gitGraph.graph', 'Graph')} + {translate('gitGraph.message', 'Message')} + {translate('gitGraph.author', 'Author')} + {translate('gitGraph.date', 'Date')} +
+
{ + const element = scroll.current + if ( + element && + element.scrollHeight - element.scrollTop - element.clientHeight < 200 && + !history.loading + ) { + void history.loadMore() + } + }} + > +
+ {virtualizer.getVirtualItems().map((virtualRow) => { + const viewModel = rows[virtualRow.index]! + const item = viewModel.historyItem + return ( + + +
setSelectedId(item.id)} + > +
+ {item.references?.map((ref) => ( + + ))} +
+ + + {item.author} + + {formatGitHistoryTimestamp(item.timestamp)} + +
+
+ +
+ ) + })} +
+ {result?.hasMore && ( + + )} + {result && !result.items.length && ( +
+ {translate('gitGraph.noCommits', 'No commits yet')} +
+ )} +
+
+ +
+
+ ) +} diff --git a/src/renderer/src/components/editor/git-graph/use-git-graph-history.ts b/src/renderer/src/components/editor/git-graph/use-git-graph-history.ts new file mode 100644 index 000000000000..635deec9fbab --- /dev/null +++ b/src/renderer/src/components/editor/git-graph/use-git-graph-history.ts @@ -0,0 +1,185 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useAppStore } from '@/store' +import { getRuntimeGitHistory } from '@/runtime/runtime-git-status-client' +import { gitGraphScope } from '@/lib/git-graph-tab' +import { getConnectionId } from '@/lib/connection-context' +import { translate } from '@/i18n/i18n' +import type { + GitHistoryRefs, + GitHistoryResult +} from '../../../../../shared/git/history/git-history-types' + +export const GIT_GRAPH_REFRESH_EVENT = 'orca:git-graph-refresh' + +export function gitGraphFilterSupported(result?: GitHistoryResult): boolean | undefined { + return result ? result.refs !== undefined : undefined +} + +export function useGitGraphHistory(worktreeId: string) { + const filterKey = useAppStore((state) => + JSON.stringify(state.gitGraphFiltersByWorktree?.[worktreeId] ?? 'all') + ) + const filter = useMemo(() => JSON.parse(filterKey), [filterKey]) + const owner = useAppStore(() => JSON.stringify(gitGraphScope(worktreeId)?.route)) + const scope = useMemo(() => (owner ? gitGraphScope(worktreeId) : null), [worktreeId, owner]) + const [result, setResult] = useState() + const [error, setError] = useState() + const [loading, setLoading] = useState(false) + const state = useRef<{ + generation: number + result?: GitHistoryResult + pending: boolean + recovered: boolean + }>({ generation: 0, pending: false, recovered: false }) + const load = useCallback( + async (append = false): Promise => { + const current = state.current + if (append && (current.pending || !current.result?.hasMore)) { + return current.result + } + if (!append) { + current.generation++ + current.recovered = false + } + let generation = current.generation + const context = gitGraphScope(worktreeId) + if (JSON.stringify(context?.route) !== owner) { + return undefined + } + if (!context) { + return undefined + } + const previous = append ? current.result : undefined + current.pending = true + setLoading(true) + setError(undefined) + try { + const get = (token?: string, skip = 0) => + getRuntimeGitHistory( + { + target: context.target, + worktreeId, + worktreePath: context.worktree.path, + connectionId: getConnectionId(worktreeId) ?? undefined + }, + { refs: filter, limit: 50, historyToken: token, skip, wakeWslDistro: !append } + ) + let page = await get(previous?.historyToken, previous?.items.length ?? 0) + if (generation !== current.generation) { + return undefined + } + let base = previous + if (page.historyChanged) { + if (current.recovered) { + throw new Error( + translate( + 'gitGraph.historyChanged', + 'History changed again. Refresh the Git Graph to try again.' + ) + ) + } + current.generation++ + generation = current.generation + current.recovered = true + page = await get() + base = undefined + if (page.historyChanged) { + throw new Error( + translate( + 'gitGraph.historyChanged', + 'History changed again. Refresh the Git Graph to try again.' + ) + ) + } + } + if (generation !== current.generation) { + return undefined + } + const existingIds = new Set(base?.items.map((item) => item.id)) + const next = base + ? { + ...page, + items: [...base.items, ...page.items.filter((item) => !existingIds.has(item.id))] + } + : page + current.result = next + setResult(next) + if ( + Array.isArray(filter) && + page.resolvedRefs && + JSON.stringify(filter) !== JSON.stringify(page.resolvedRefs) + ) { + useAppStore.setState((store) => ({ + gitGraphFiltersByWorktree: { + ...store.gitGraphFiltersByWorktree, + [worktreeId]: page.resolvedRefs!.length ? page.resolvedRefs! : 'head' + } + })) + } + return next + } catch (cause) { + if (generation === current.generation) { + setError( + cause instanceof Error + ? cause.message + : translate('gitGraph.loadFailed', 'Failed to load Git history') + ) + } + return undefined + } finally { + if (generation === current.generation) { + current.pending = false + setLoading(false) + } + } + }, + [worktreeId, filter, owner] + ) + useEffect(() => { + const current = state.current + current.result = undefined + setResult(undefined) + void load() + const refresh = () => { + void load() + } + window.addEventListener(GIT_GRAPH_REFRESH_EVENT, refresh) + return () => { + current.generation++ + window.removeEventListener(GIT_GRAPH_REFRESH_EVENT, refresh) + } + }, [load]) + const changeFilter = (refs: GitHistoryRefs) => + useAppStore.setState((store) => ({ + gitGraphFiltersByWorktree: { ...store.gitGraphFiltersByWorktree, [worktreeId]: refs } + })) + const reveal = async (id: string) => { + const generation = state.current.generation + let page = state.current.result + while ( + page && + !page.items.some((item) => item.id === id) && + page.hasMore && + generation === state.current.generation && + !state.current.pending + ) { + const previous = page + page = await load(true) + if (page === previous) { + break + } + } + return page?.items.findIndex((item) => item.id === id) ?? -1 + } + return { + filter, + changeFilter, + result, + error, + loading, + refresh: () => load(), + loadMore: () => load(true), + reveal, + scope + } +} diff --git a/src/renderer/src/components/right-sidebar/source-control/commit/use-commit-action.ts b/src/renderer/src/components/right-sidebar/source-control/commit/use-commit-action.ts index 82d63f19b2f5..088d5ffa7096 100644 --- a/src/renderer/src/components/right-sidebar/source-control/commit/use-commit-action.ts +++ b/src/renderer/src/components/right-sidebar/source-control/commit/use-commit-action.ts @@ -124,6 +124,7 @@ export function useSourceControlCommitAction({ } if (!options?.target) { void refreshBranchCompareRef.current() + window.dispatchEvent(new Event('orca:git-graph-refresh')) void refreshGitHistoryRef.current() } return true @@ -201,6 +202,7 @@ export function useSourceControlCommitAction({ ) } void refreshBranchCompareRef.current() + window.dispatchEvent(new Event('orca:git-graph-refresh')) void refreshGitHistoryRef.current() }, [ activeRepoTarget, diff --git a/src/renderer/src/components/right-sidebar/source-control/panel/panel-content.tsx b/src/renderer/src/components/right-sidebar/source-control/panel/panel-content.tsx index 64f56ad9ed14..dd080ed40c42 100644 --- a/src/renderer/src/components/right-sidebar/source-control/panel/panel-content.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/panel/panel-content.tsx @@ -226,6 +226,7 @@ export function SourceControlPanelContent(props: SourceControlPanelReadyProps) { // Dock history as reference context while the rest of the pane scrolls.
toggleSection('history')} diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/git-graph-open-button.tsx b/src/renderer/src/components/right-sidebar/source-control/sync/git-graph-open-button.tsx new file mode 100644 index 000000000000..e6eaa3a13ec6 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/source-control/sync/git-graph-open-button.tsx @@ -0,0 +1,56 @@ +import { useEffect, useState } from 'react' +import { GitGraph } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { useAppStore } from '@/store' +import { + gitGraphScope, + gitGraphSupport, + gitGraphUpdateMessage, + openGitGraph, + probeGitGraphSupport +} from '@/lib/git-graph-tab' +import { translate } from '@/i18n/i18n' + +export function GitGraphOpenButton({ worktreeId }: { worktreeId: string }) { + const status = useAppStore((state) => state.runtimeStatusByEnvironmentId) + const owner = useAppStore(() => JSON.stringify([worktreeId, gitGraphScope(worktreeId)?.route])) + const [probe, setProbe] = useState<{ owner: string; support: boolean | null }>() + const support = probe?.owner === owner ? probe.support : null + useEffect(() => { + let current = true + setProbe({ owner, support: gitGraphSupport(worktreeId) }) + void probeGitGraphSupport(worktreeId) + .then((value) => { + if (current) { + setProbe({ owner, support: value }) + } + }) + .catch(() => {}) + return () => { + current = false + } + }, [worktreeId, owner, status]) + return ( + + + + + + + {support !== null && ( + + {support ? translate('gitGraph.title', 'Git Graph') : gitGraphUpdateMessage(worktreeId)} + + )} + + ) +} diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/git-history-commit-files.tsx b/src/renderer/src/components/right-sidebar/source-control/sync/git-history-commit-files.tsx index 5da2ab6de879..4f48f3d50196 100644 --- a/src/renderer/src/components/right-sidebar/source-control/sync/git-history-commit-files.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/sync/git-history-commit-files.tsx @@ -1,6 +1,6 @@ import { createElement } from 'react' import type React from 'react' -import { ArrowUpRight, RefreshCw } from 'lucide-react' +import { ArrowUpRight } from 'lucide-react' import { STATUS_COLORS } from '../../../../lib/git-path-decoration' import { STATUS_LABELS } from '../../../../../../shared/git/status/git-status-labels' import { @@ -50,6 +50,12 @@ function CommitFileRow({ {fileName} {dirPath && {dirPath}} + + {entry.added !== undefined ? `+${entry.added}` : ''} + + + {entry.removed !== undefined ? `−${entry.removed}` : ''} + void }): React.JSX.Element { if (state.status === 'loading') { - return ( -
- - - {translate( - 'auto.components.right.sidebar.GitHistoryCommitFiles.a1b2c3d4e5', - 'Loading files…' - )} - -
- ) + return
} if (state.status === 'error') { diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/git-history-panel.tsx b/src/renderer/src/components/right-sidebar/source-control/sync/git-history-panel.tsx index cd2071398d43..0089830db84d 100644 --- a/src/renderer/src/components/right-sidebar/source-control/sync/git-history-panel.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/sync/git-history-panel.tsx @@ -1,3 +1,5 @@ +import { useVirtualizer } from '@tanstack/react-virtual' +import { GitGraphOpenButton } from './git-graph-open-button' import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { ChevronDown, CircleHelp, RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' @@ -45,6 +47,7 @@ function clampGitHistoryPanelHeight(height: number): number { export function GitHistoryPanel({ state, + worktreeId, collapsed, onToggle, onRefresh, @@ -53,6 +56,7 @@ export function GitHistoryPanel({ onOpenCommitFile, onCommitAction }: { + worktreeId?: string state: GitHistoryPanelState collapsed: boolean onToggle: () => void @@ -90,20 +94,25 @@ export function GitHistoryPanel({ const [expanded, setExpanded] = useState>(() => new Set()) const [filesByCommit, setFilesByCommit] = useState>({}) - // Avoid duplicate/in-flight expansion fetches; clear errors to permit retry. - const loadedCommitsRef = useRef<{ - result: GitHistoryResult | undefined - ids: Set - }>(undefined!) - loadedCommitsRef.current ??= { result, ids: new Set() } - - // New history can replace rows; discard expansions and cached files to avoid stale associations. - const [historyResult, setHistoryResult] = useState(result) - if (historyResult !== result) { - setHistoryResult(result) - setExpanded(new Set()) - setFilesByCommit({}) + const loadedCommitsRef = useRef(new Set()) + const [previousResult, setPreviousResult] = useState(result) + if (result !== previousResult) { + setPreviousResult(result) + const ids = new Set(result?.items.map((item) => item.id)) + setExpanded(new Set([...expanded].filter((id) => ids.has(id)))) + setFilesByCommit( + Object.fromEntries(Object.entries(filesByCommit).filter(([id]) => ids.has(id))) + ) + loadedCommitsRef.current = new Set([...loadedCommitsRef.current].filter((id) => ids.has(id))) } + const scrollRef = useRef(null) + const virtualizer = useVirtualizer({ + count: collapsed ? 0 : viewModels.length, + getScrollElement: () => scrollRef.current, + estimateSize: () => 28, + overscan: 8, + getItemKey: (index) => `${viewModels[index]!.kind}:${viewModels[index]!.historyItem.id}` + }) const handleToggleExpand = useCallback( (item: GitHistoryItem): void => { @@ -118,23 +127,17 @@ export function GitHistoryPanel({ } return next }) - // Reset the in-flight lock in the click handler, not render; new results can reuse commit IDs with different files. - if (loadedCommitsRef.current.result !== result) { - loadedCommitsRef.current = { result, ids: new Set() } - } - if (!willExpand || !onLoadCommitFiles || loadedCommitsRef.current.ids.has(id)) { + if (!willExpand || !onLoadCommitFiles || loadedCommitsRef.current.has(id)) { return } - loadedCommitsRef.current.ids.add(id) + loadedCommitsRef.current.add(id) setFilesByCommit((prev) => ({ ...prev, [id]: { status: 'loading' } })) onLoadCommitFiles(item) .then((entries) => { setFilesByCommit((prev) => ({ ...prev, [id]: { status: 'ready', entries } })) }) .catch((error: unknown) => { - if (loadedCommitsRef.current.result === result) { - loadedCommitsRef.current.ids.delete(id) - } + loadedCommitsRef.current.delete(id) setFilesByCommit((prev) => ({ ...prev, [id]: { @@ -150,7 +153,7 @@ export function GitHistoryPanel({ })) }) }, - [expanded, onLoadCommitFiles, result] + [expanded, onLoadCommitFiles] ) const stopResize = useCallback((): void => { @@ -261,6 +264,7 @@ export function GitHistoryPanel({ {result && {count}} {result?.hasMore && +} + {worktreeId && }
+ }` + ) + + expect(reports.map((report) => report.text)).toEqual(['Retry the sync']) + }) + + it('ignores CSS and script bodies but still sees copy beside them', () => { + const reports = candidates( + 'Sample.tsx', + `export function Sample() { + return ( +
+ + +

Choose a workspace

+
+ ) + }` + ) + + expect(reports.map((report) => report.text)).toEqual(['Choose a workspace']) + }) + + it('ignores literals used as comparison operands', () => { + const reports = candidates( + 'Sample.tsx', + `export function Sample({ phase }) { + return {phase === 'workspace conflict' ? phase : null} + }` + ) + + expect(reports).toEqual([]) + }) + + it('sees static templates and every dynamic template part in visible calls', () => { + const reports = candidates( + 'Sample.ts', + 'confirm(`Retry the sync`); alert(`Reconnect ${host} after ${attempts} attempts`);' + ) + + expect(reports.map(({ text, dynamic }) => ({ text, dynamic }))).toEqual([ + { text: 'Retry the sync', dynamic: false }, + { text: 'Reconnect', dynamic: true }, + { text: 'after', dynamic: true }, + { text: 'attempts', dynamic: true } + ]) + }) + + it('ignores nested class properties and translations while seeing sibling copy', () => { + const reports = candidates( + 'Sample.tsx', + [ + 'const config = {', + ' className: { label: "Hidden class copy" },', + ' classNames: ["Hidden token", { title: "Hidden nested token" }],', + ' title: `Connect ${host}`,', + ' message: "Reconnect the host",', + ' description: t("connection.ready", "Ready now")', + '};', + 'export const view = {t("connection.banner", { label: "Connection banner" })};' + ].join('\n') + ) + + expect(reports.map(({ text, dynamic }) => ({ text, dynamic }))).toEqual([ + { text: 'Connect', dynamic: true }, + { text: 'Reconnect the host', dynamic: false } + ]) + }) + + it('keeps traversing calls and callbacks to find nested JSX attributes and text', () => { + const reports = candidates( + 'Sample.tsx', + `export function Sample() { + return
{select(true, () => )}
+ }` + ) + + expect(reports.map((report) => report.text)).toEqual(['Retry after reconnect', 'Reconnect now']) + }) +}) + +describe('localization coverage file skipping', () => { + function skipped(relativePath) { + return isSkippedFile(ROOT, `${ROOT}/${relativePath}`) + } + + it('skips test-only modules that sit beside their spec', () => { + expect(skipped('src/renderer/src/components/browser-pane/stream-test-harness.ts')).toBe(true) + expect(skipped('src/renderer/src/runtime/browser-tab-creation-test-rig.ts')).toBe(true) + expect(skipped('src/renderer/src/hooks/ipc-events-test-fixtures.ts')).toBe(true) + expect(skipped('src/renderer/src/lib/session-test-state.ts')).toBe(true) + expect(skipped('src/renderer/src/store/slices/routing-fixture.ts')).toBe(true) + expect(skipped('src/renderer/src/components/tab-bar/icon-stub.fixture.tsx')).toBe(true) + }) + + it('still scans shipped modules whose names merely mention a fixture concept', () => { + expect(skipped('src/renderer/src/components/browser-pane/fixture-picker.tsx')).toBe(false) + expect(skipped('src/renderer/src/components/settings/fixtures-panel.tsx')).toBe(false) + expect(skipped('src/renderer/src/components/browser-pane/BrowserPane.tsx')).toBe(false) + }) +}) diff --git a/config/scripts/localization/source-extraction/localization-extraction-call-syntax.test.mjs b/config/scripts/localization/source-extraction/localization-extraction-call-syntax.test.mjs index 4143c41e683c..6ae1f24be045 100644 --- a/config/scripts/localization/source-extraction/localization-extraction-call-syntax.test.mjs +++ b/config/scripts/localization/source-extraction/localization-extraction-call-syntax.test.mjs @@ -8,10 +8,52 @@ import { describe, expect, it } from 'vitest' const require = createRequire(import.meta.url) const commonJsFindKeys = require('i18next-cli').findKeys +const calls = { + normal: "translate('probe.normal', 'Normal')", + block: "translate /* comment */ ('probe.block', 'Block')", + line: "translate\n// comment\n('probe.line', 'Line')", + member: "i18n./* member */t /* call */ ('probe.member', 'Member')", + optional: "translate?. /* optional */ ('probe.optional', 'Optional')", + generic: "translate /* generic */ ('probe.generic', 'Generic')", + dollar: "$api.t /* member */ ('probe.dollar', 'Dollar')", + unicode: "transl\\u0061te('probe.unicode', 'Unicode')" +} + describe.each([ ['ES module', findKeys], ['CommonJS', commonJsFindKeys] ])('localization extraction through %s', (_name, extractKeys) => { + it('keeps keys in calls containing comments or escaped identifiers', async () => { + const directory = mkdtempSync(join(tmpdir(), 'orca-extraction-syntax-')) + try { + for (const [name, source] of Object.entries(calls)) { + writeFileSync(join(directory, `${name}.ts`), source) + } + const errors = [] + const result = await extractKeys( + { + locales: ['en'], + extract: { + input: [join(directory, '*.ts').replaceAll('\\', '/')], + defaultNS: false, + functions: ['t', '*.t', 'translate'], + disablePlurals: true + } + }, + undefined, + errors + ) + expect(errors).toEqual([]) + expect([...result.allKeys.values()].map((entry) => entry.key).sort()).toEqual( + Object.keys(calls) + .map((name) => `probe.${name}`) + .sort() + ) + } finally { + rmSync(directory, { recursive: true, force: true }) + } + }) + it('preserves cross-file namespaces, source locations and fresh plugin transformations', async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-extraction-passes-')) const file = join(directory, 'a-consumer.ts') diff --git a/config/scripts/mobile-web-app/preview/mobile-web-app-html-preview-render.test.mjs b/config/scripts/mobile-web-app/preview/mobile-web-app-html-preview-render.test.mjs index 8e57c3cb0f4c..d9e886c61eb8 100644 --- a/config/scripts/mobile-web-app/preview/mobile-web-app-html-preview-render.test.mjs +++ b/config/scripts/mobile-web-app/preview/mobile-web-app-html-preview-render.test.mjs @@ -5,7 +5,7 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { createServer } from 'node:http' import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' import * as esbuild from 'esbuild' import { chromium, webkit } from 'playwright-core' import { lucideBarrelPlugin } from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs' @@ -23,6 +23,7 @@ import { ENTRY_SOURCE, artifactScript } from './mobile-web-app-preview-artifact-fixture.mjs' +import { waitForRecordedNavigation } from './mobile-web-app-preview-frame-readiness.mjs' const mobileDir = fileURLToPath(new URL('../../../../mobile', import.meta.url)) @@ -192,6 +193,23 @@ for (const engine of ['chromium', 'webkit']) { return one } + it('paints the artifact under the policy the shell already ships', async (ctx) => { + const read = await open(browser(), { signal: ctx.signal }) + expect(read.frameCount).toBe(1) + // Read srcdoc/no-src attributes, not engine-dependent frame URL, to prove artifact is embedded rather than fetched. + expect(read.mountedSrcDoc).toContain('ARTIFACT_RENDERED') + expect(read.mountedSrc).toBeNull() + expect(read.mountedSandbox).toBe(read.declaredSandbox) + expect(read.mountedSandbox).toBe('allow-top-navigation-by-user-activation') + // Append report-uri only to shipped CSP; endpoint changes reporting, not enforcement. + const servedParts = (read.servedCsp ?? '').split('; report-uri ') + expect(servedParts[0]).toBe(shippedCsp) + expect(servedParts).toHaveLength(2) + expect(read.pixel).toBe(ARTIFACT_RGB) + // Embedder violation event does not cross frames: empty list proves parent clean only. Pixel and counting server measure inherited style/image/font policy. + expect(read.violations).toEqual([]) + }, 120_000) + it('does not run the artifact, behind two fences either of which would hold', async (ctx) => { const sealed = await open(browser(), { extra: { body: artifactScript(foreignOrigin) }, @@ -236,6 +254,18 @@ for (const engine of ['chromium', 'webkit']) { expect(sealed.reported.join(' ')).not.toContain('script-src') }, 180_000) + it('refuses the artifact cleartext subresources by scheme and its font by directive', async (ctx) => { + const sealed = await open(browser(), { signal: ctx.signal }) + expect(sealed.pixel).toBe(ARTIFACT_RGB) + expect(sealed.foreignHits).toEqual([]) + // Cleartext image refusal proves scheme gate; https control must remain because img-src now admits remote TLS images. font-src none denies either scheme. + const control = await open(browser(), { csp: null, signal: ctx.signal }) + expect(control.pixel).toBe(ARTIFACT_RGB) + expect(control.foreignHits).toEqual( + expect.arrayContaining(['/img.png', '/css-bg.png', '/probe.woff2']) + ) + }, 120_000) + it('loads the artifact https images the directive admits, and still refuses its font', async (ctx) => { // Await both images explicitly; bounded settle once observed background before element on loaded Chrome. const read = await open(browser(), { @@ -277,6 +307,22 @@ for (const engine of ['chromium', 'webkit']) { } }, 180_000) + it('asks to navigate the top frame to the shell itself, which the shell must refuse', async (ctx) => { + // Artifact / resolves to shell document and would reset bridge/page state; count actual navigation passed to native refusal delegate. + const root = await open(browser(), { + signal: ctx.signal, + expectNavigation: 'main-frame', + act: async ({ frame }) => { + await frame?.click('#rootlink', { timeout: 2000 }) + } + }) + expect(root.pixelBefore).toBe(ARTIFACT_RGB) + // Require tap landed before comparing navigation counters; missed click cannot prove refusal. + expect(root.actError).toBeNull() + expect(root.ownOriginTopNavigations).toBe(1) + expect(root.topNavigations).toBe(0) + }, 180_000) + // Without externalNavigation grant, older shells silently drop link taps; remove anchor/underline/focus affordance instead. // Compare painted granted/hidden arms and their own published click/style state. Granted-link navigation has separate case/budget: third shared arm once timed out after missed CI click. it('renders an artifact link as text against a shell that cannot open one', async (ctx) => { @@ -369,6 +415,39 @@ for (const engine of ['chromium', 'webkit']) { // srcdoc #fragment resolves against embedder base, triggering frame-src none instead of scrolling; Chromium can replace artifact with error page. // Granted control retains known bug (followup-html-preview-fragment-links.md) and proves navigation counters see it; hidden arm must remain inert. + it('taps a fragment link, which navigates this frame rather than scrolling it', async (ctx) => { + // Require overflow content so no-scroll assertion has meaningful alternative. + const tall = { body: '
spacer
' } + const tapFragment = async ({ frame }) => { + await frame?.click('#fraglink', { timeout: 2000 }) + } + + const shown = await open(browser(), { + signal: ctx.signal, + extra: tall, + act: tapFragment, + reportAfterAct: 'frame-src' + }) + expect(shown.actError).toBeNull() + // Require embedder base URL, which makes fragment target off-document. + expect(shown.inside?.baseUri ?? shown.mountedSrcDoc).toBeTruthy() + // Granted control must observe forbidden frame navigation absent in hidden arm. + expect(shown.reported).toContain('frame-src') + + const hidden = await open(browser(), { + signal: ctx.signal, + extra: tall, + grants: ['navigate', 'storage'], + act: tapFragment + }) + expect(hidden.actError).toBeNull() + expect(hidden.reported).not.toContain('frame-src') + expect(hidden.inside?.marker).toBe('ARTIFACT_RENDERED') + expect(hidden.inside?.fragmentHref).toBeNull() + expect(hidden.inside?.scrollY).toBe(0) + expect(hidden.topNavigations).toBe(0) + expect(hidden.popups).toBe(0) + }, 240_000) it("hands a user's tap on a link to the top frame, exactly once", async (ctx) => { const read = await open(browser(), { @@ -488,8 +567,78 @@ for (const engine of ['chromium', 'webkit']) { }, 180_000) // Force slow-arm diagnostic sampling branch; formerly unexecuted branch had out-of-scope name and no test/lint coverage. + it('reads the frame while a navigation it expects has not arrived', async (ctx) => { + void ctx + const page = await browser().newPage() + const printed = [] + const spy = vi.spyOn(console, 'error').mockImplementation((line) => { + printed.push(String(line)) + }) + const stop = new AbortController() + const timer = setTimeout(() => stop.abort(), 300) + await waitForRecordedNavigation( + page, + [], + () => false, + stop.signal, + { arm: 'arm sampling-probe', browserVersion: browser().version() }, + { sampleEveryMs: 25 } + ) + clearTimeout(timer) + spy.mockRestore() + await page.close() + expect(printed).toHaveLength(1) + expect(printed[0]).toContain('arm sampling-probe') + expect(printed[0]).toContain('frames [') + }, 60_000) // Force bounded navigation timeout after missed click; require useful diagnostic instead of exhausting whole case budget. + it('gives up on a navigation that is not coming, and names why', async (ctx) => { + void ctx + const page = await browser().newPage() + try { + const failed = await waitForRecordedNavigation( + page, + [], + () => false, + null, + { + arm: 'arm bound-probe', + browserVersion: browser().version(), + actError: 'locator.click: Timeout 2000ms exceeded' + }, + { boundMs: 50 } + ).catch((error) => String(error)) + // Diagnostic needs arm, elapsed wait, click outcome and last frame reading to explain CI timeout. + expect(failed).toContain('arm bound-probe') + expect(failed).toMatch(/waited \d+ms for the navigation it expects/) + expect(failed).toContain('Timeout 2000ms exceeded') + expect(failed).toContain('frames [') + } finally { + await page.close() + } + }, 60_000) + + it('keeps the Preview/Source toggle, and Source shows the source', async (ctx) => { + const read = await open(browser(), { + signal: ctx.signal, + act: async ({ page }) => { + await page.getByLabel('View HTML source').click({ timeout: 2000 }) + } + }) + // Read toggle labels/state from DOM before and after action, as assistive technology does. + expect(read.togglesBefore).toEqual([ + { label: 'Preview rendered HTML', selected: 'true' }, + { label: 'View HTML source', selected: 'false' } + ]) + expect(read.toggles).toEqual([ + { label: 'Preview rendered HTML', selected: 'false' }, + { label: 'View HTML source', selected: 'true' } + ]) + expect(read.body).toContain('SOURCE_TAB_RENDERED') + expect(read.frameCount).toBe(0) + expect(read.pixel).toBe(PAGE_RGB) + }, 120_000) }, 600_000 ) diff --git a/config/scripts/mobile-web/check-entry/mobile-test-change-scope.test.mjs b/config/scripts/mobile-web/check-entry/mobile-test-change-scope.test.mjs new file mode 100644 index 000000000000..d7febf0a1b43 --- /dev/null +++ b/config/scripts/mobile-web/check-entry/mobile-test-change-scope.test.mjs @@ -0,0 +1,13 @@ +import { expect, it } from 'vitest' +import { shouldRunMobileTests } from './mobile-test-change-scope.mjs' + +it('retains tests on missing evidence and a move out of the source tree', () => { + expect(shouldRunMobileTests([])).toBe(true) + expect(shouldRunMobileTests(['mobile/src/deleted.ts', 'mobile/docs/moved.ts'])).toBe(true) +}) + +it('retains unknown suite paths and noncanonical traversal evidence', () => { + expect(shouldRunMobileTests(['unknown/module.test.ts'])).toBe(true) + expect(shouldRunMobileTests(['src/unknown/module.test.ts'])).toBe(true) + expect(shouldRunMobileTests(['src/shared/../main/module.test.ts'])).toBe(true) +}) diff --git a/config/scripts/native-build/linux/verify-linux-glibc-floor.test.mjs b/config/scripts/native-build/linux/verify-linux-glibc-floor.test.mjs index 6a6dda74e86d..243787539cec 100644 --- a/config/scripts/native-build/linux/verify-linux-glibc-floor.test.mjs +++ b/config/scripts/native-build/linux/verify-linux-glibc-floor.test.mjs @@ -1,15 +1,209 @@ import { mkdtemp, mkdir, writeFile, symlink, rm } from 'node:fs/promises' import { createRequire } from 'node:module' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { dirname, join } from 'node:path' import { describe, expect, it } from 'vitest' const require = createRequire(import.meta.url) -const { collectNativeBinaries } = require('./verify-linux-glibc-floor.cjs') +const { + readElfMachine, + declaredArchFromPath, + findArchViolation, + parseGlibcVersion, + compareGlibcVersions, + parseVersionNeeds, + parseNeededLibraries, + parseImportedSymbols, + isVersionNodeAboveFloor, + findFloorViolations, + DESKTOP_GLIBC_FLOOR, + SERVER_SLOT_GLIBC_FLOOR, + COMPAT_SLOT_GLIBC_FLOOR, + findMissingProviderDeps, + collectNativeBinaries, + verifyLinuxGlibcFloor +} = require('./verify-linux-glibc-floor.cjs') // 0x7f 'E' 'L' 'F' + class/data/version padding — enough for the magic check. const ELF_HEADER = Buffer.from([0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00]) +// Model objdump -p version rows with weak 0x02 needs, symbol-less ABI marker and C++ requirement. +const OBJDUMP_P = [ + 'Dynamic Section:', + ' NEEDED libc.so.6', + '', + 'Version References:', + ' required from libc.so.6:', + ' 0x09691a75 0x00 06 GLIBC_2.2.5', + ' 0x069691b4 0x00 05 GLIBC_2.34', + ' 0x0d696914 0x02 04 GLIBC_2.18', + ' 0x00fd0e42 0x00 03 GLIBC_ABI_DT_RELR', + ' required from libstdc++.so.6:', + ' 0x0b481abc 0x00 07 GLIBCXX_3.4.29', + '' +].join('\n') + +describe('verify-linux-glibc-floor parsing', () => { + it('parses and compares numeric version tuples', () => { + expect(parseGlibcVersion('2.34')).toEqual([2, 34]) + expect(parseGlibcVersion('3.4.28')).toEqual([3, 4, 28]) + expect(compareGlibcVersions([2, 2, 5], [2, 14])).toBe(-1) + expect(compareGlibcVersions([2, 31], [2, 32])).toBe(-1) + expect(compareGlibcVersions([2, 34], [2, 31])).toBe(1) + expect(compareGlibcVersions([2, 31], [2, 31])).toBe(0) + expect(compareGlibcVersions([2, 31], [2, 31, 0])).toBe(0) + expect(compareGlibcVersions([3, 4, 29], [3, 4, 28])).toBe(1) + }) + + it('parses objdump -p Version References into per-library version needs', () => { + const needs = parseVersionNeeds(OBJDUMP_P) + expect(needs).toContainEqual({ library: 'libc.so.6', name: 'GLIBC_2.34', weak: false }) + expect(needs).toContainEqual({ library: 'libc.so.6', name: 'GLIBC_ABI_DT_RELR', weak: false }) + expect(needs).toContainEqual({ library: 'libc.so.6', name: 'GLIBC_2.18', weak: true }) + expect(needs).toContainEqual({ library: 'libstdc++.so.6', name: 'GLIBCXX_3.4.29', weak: false }) + }) + + it('classifies version nodes across glibc and libstdc++ families', () => { + expect(isVersionNodeAboveFloor('GLIBC_2.34')).toBe(true) + expect(isVersionNodeAboveFloor('GLIBC_2.31')).toBe(false) + expect(isVersionNodeAboveFloor('GLIBC_ABI_DT_RELR')).toBe(true) // Reject GLIBC_PRIVATE even if version node exists: private symbol may be absent on floor, like newer ABI marker. + expect(isVersionNodeAboveFloor('GLIBC_PRIVATE')).toBe(true) + expect(isVersionNodeAboveFloor('CXXABI_TM_1')).toBe(false) // named libstdc++ node on 20.04 + expect(isVersionNodeAboveFloor('GLIBCXX_3.4.29')).toBe(true) // GCC 11, above 20.04's 3.4.28 + expect(isVersionNodeAboveFloor('GLIBCXX_3.4.28')).toBe(false) + expect(isVersionNodeAboveFloor('CXXABI_1.3.13')).toBe(true) + expect(isVersionNodeAboveFloor('CXXABI_1.3.12')).toBe(false) + expect(isVersionNodeAboveFloor('GCC_3.0')).toBe(false) // family not gated + }) + + it('flags strong too-new glibc + libstdc++ needs, skipping weak and ungated families', () => { + const violations = findFloorViolations(parseVersionNeeds(OBJDUMP_P), '/opt/app/pty.node') + const names = violations.map((v) => v.name).sort() + // Reject strong too-new requirements; omit weak GLIBC_2.18 and supported GLIBC_2.2.5. + expect(names).toEqual(['GLIBCXX_3.4.29', 'GLIBC_2.34', 'GLIBC_ABI_DT_RELR'].sort()) + }) + + it('exempts sherpa-onnx from the libstdc++ floor but still gates its glibc', () => { + const needs = [ + { library: 'libstdc++.so.6', name: 'GLIBCXX_3.4.29', weak: false }, + { library: 'libc.so.6', name: 'GLIBC_2.34', weak: false } + ] + // A launch-critical module: both are violations. + expect( + findFloorViolations(needs, '/opt/app/node_modules/node-pty/pty.node').map((v) => v.name) + ).toEqual(['GLIBCXX_3.4.29', 'GLIBC_2.34']) + // sherpa: GLIBCXX exempt (lazy speech prebuilt), glibc still enforced. + expect( + findFloorViolations( + needs, + '/opt/app/node_modules/sherpa-onnx-linux-x64/sherpa-onnx.node' + ).map((v) => v.name) + ).toEqual(['GLIBC_2.34']) + }) + + it('reports no violations when every strong need is at or below the floor', () => { + const needs = parseVersionNeeds( + [ + 'Version References:', + ' required from libc.so.6:', + ' 0x00 0x00 02 GLIBC_2.2.5', + ' 0x00 0x00 03 GLIBC_2.28', + ' required from libstdc++.so.6:', + ' 0x00 0x00 04 GLIBCXX_3.4.22' + ].join('\n') + ) + expect(findFloorViolations(needs, '/opt/app/pty.node')).toEqual([]) + }) +}) + +describe('floor profiles', () => { + const needs = (...names) => names.map((name) => ({ library: 'libc.so.6', name, weak: false })) + const flagged = (list, floor) => + findFloorViolations(list, '/opt/orcad/pty.node', floor).map((v) => v.name) + + it('keeps the desktop default at Ubuntu 20.04', () => { + expect(DESKTOP_GLIBC_FLOOR.label).toContain('glibc 2.31') + expect(flagged(needs('GLIBC_2.31', 'GLIBC_2.32'))).toEqual(['GLIBC_2.32']) + expect(flagged(needs('GLIBC_2.31', 'GLIBC_2.32'), DESKTOP_GLIBC_FLOOR)).toEqual(['GLIBC_2.32']) + }) + + it('gates server slots at glibc 2.28 and GCC 8 libstdc++', () => { + expect( + flagged( + needs( + 'GLIBC_2.28', + 'GLIBC_2.29', + 'GLIBCXX_3.4.25', + 'GLIBCXX_3.4.26', + 'CXXABI_1.3.11', + 'CXXABI_1.3.12' + ), + SERVER_SLOT_GLIBC_FLOOR + ) + ).toEqual(['GLIBC_2.29', 'GLIBCXX_3.4.26', 'CXXABI_1.3.12']) + }) + + it('gates the compat slot at glibc 2.17 and GCC 4.8 libstdc++', () => { + expect( + flagged( + needs('GLIBC_2.17', 'GLIBC_2.18', 'GLIBCXX_3.4.19', 'GLIBCXX_3.4.20', 'CXXABI_1.3.8'), + COMPAT_SLOT_GLIBC_FLOOR + ) + ).toEqual(['GLIBC_2.18', 'GLIBCXX_3.4.20', 'CXXABI_1.3.8']) + }) + + it('still rejects non-numeric glibc nodes under every profile', () => { + for (const floor of [SERVER_SLOT_GLIBC_FLOOR, COMPAT_SLOT_GLIBC_FLOOR]) { + expect(flagged(needs('GLIBC_ABI_DT_RELR', 'GLIBC_PRIVATE'), floor)).toEqual([ + 'GLIBC_ABI_DT_RELR', + 'GLIBC_PRIVATE' + ]) + } + }) +}) + +describe('DT_NEEDED provider check', () => { + const OBJDUMP_P_DYNAMIC = [ + 'Dynamic Section:', + ' NEEDED libutil.so.1', + ' NEEDED libpthread.so.0', + ' NEEDED libc.so.6', + '', + 'Version References:', + ' required from libc.so.6:', + ' 0x0 0x00 02 GLIBC_2.2.5' + ].join('\n') + + it('parses DT_NEEDED shared libraries from objdump -p', () => { + const needed = parseNeededLibraries(OBJDUMP_P_DYNAMIC) + expect([...needed].sort()).toEqual(['libc.so.6', 'libpthread.so.0', 'libutil.so.1']) + }) + + it('parses undefined imported symbols from objdump -T, stripping @VERSION', () => { + const output = [ + '0000000000000000 DF *UND*\t0000000000000000 (GLIBC_2.2.5) openpty', + '0000000000000000 w DF *UND*\t0000000000000000 __cxa_finalize@GLIBC_2.2.5', + '0000000000000000 DF .text\t0000000000000000 defined_symbol' + ].join('\n') + const imported = parseImportedSymbols(output) + expect(imported.has('openpty')).toBe(true) + expect(imported.has('__cxa_finalize')).toBe(true) + expect(imported.has('defined_symbol')).toBe(false) // not *UND* + }) + + it('flags a binary that imports openpty/forkpty without libutil.so.1 in DT_NEEDED', () => { + const importsPty = new Set(['openpty', 'forkpty', 'free']) + // Missing libutil.so.1 -> the pinned symbols would not resolve on the floor. + expect( + findMissingProviderDeps(importsPty, new Set(['libc.so.6'])).map((m) => m.symbol) + ).toEqual(['openpty', 'forkpty']) + // With libutil.so.1 present, no violation. + expect(findMissingProviderDeps(importsPty, new Set(['libc.so.6', 'libutil.so.1']))).toEqual([]) + // A binary that doesn't import the relocated symbols is never flagged. + expect(findMissingProviderDeps(new Set(['free']), new Set(['libc.so.6']))).toEqual([]) + }) +}) + describe('collectNativeBinaries', () => { it('collects only ELF .node/.so/executable files, skipping non-ELF and symlinks', async () => { const root = await mkdtemp(join(tmpdir(), 'orca-glibc-collect-')) @@ -42,3 +236,239 @@ describe('collectNativeBinaries', () => { } }) }) + +describe.skipIf(process.platform === 'win32')('verifyLinuxGlibcFloor', () => { + // Stub objdump by basename to avoid random-temp collisions: -p needs, -T imports, fail exits nonzero, noutil omits libutil, pty imports openpty. + async function writeStubObjdump(dir) { + const stubPath = join(dir, 'objdump-stub.sh') + await writeFile( + stubPath, + [ + '#!/bin/sh', + 'if [ "$1" = "--version" ]; then echo "GNU objdump (stub)"; exit 0; fi', + 'f=$(basename "$2")', + 'case "$f" in', + ' *fail*) echo "objdump: $f: File format not recognized" >&2; exit 1 ;;', + 'esac', + 'if [ "$1" = "-T" ]; then', + ' case "$f" in', + ' *pty*) printf "0000 DF *UND* 0000 (GLIBC_2.2.5) openpty\\n" ;;', + ' esac', + ' exit 0', + 'fi', + 'printf "Dynamic Section:\\n NEEDED libc.so.6\\n"', + 'case "$f" in', + ' *noutil*) : ;;', + ' *) printf " NEEDED libutil.so.1\\n NEEDED libpthread.so.0\\n" ;;', + 'esac', + 'printf "\\nVersion References:\\n required from libc.so.6:\\n"', + 'case "$f" in', + ' *bad*) printf " 0x0 0x00 03 GLIBC_2.34\\n 0x0 0x00 04 GLIBC_2.2.5\\n" ;;', + ' *relr*) printf " 0x0 0x00 05 GLIBC_ABI_DT_RELR\\n 0x0 0x00 04 GLIBC_2.2.5\\n" ;;', + ' *weakonly*) printf " 0x0 0x02 06 GLIBC_2.32\\n 0x0 0x00 04 GLIBC_2.2.5\\n" ;;', + ' *cxx*|*sherpa*)', + ' printf " required from libstdc++.so.6:\\n 0x0 0x00 07 GLIBCXX_3.4.29\\n" ;;', + ' *) printf " 0x0 0x00 08 GLIBC_2.28\\n 0x0 0x00 04 GLIBC_2.2.5\\n" ;;', + 'esac', + 'exit 0' + ].join('\n'), + { mode: 0o755 } + ) + return stubPath + } + + it('throws listing binaries over the floor (glibc, DT_RELR marker, and libstdc++)', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-glibc-over-')) + try { + const objdumpPath = await writeStubObjdump(root) + await mkdir(join(root, 'app', 'resources'), { recursive: true }) + await writeFile(join(root, 'app', 'resources', 'bad-pty.node'), ELF_HEADER) + await writeFile(join(root, 'app', 'relr-exe.node'), ELF_HEADER) + await writeFile(join(root, 'app', 'cxx-addon.node'), ELF_HEADER) // launch-critical GLIBCXX_3.4.29 + await writeFile(join(root, 'app', 'good.so'), ELF_HEADER) + + let error + try { + verifyLinuxGlibcFloor(join(root, 'app'), { objdumpPath }) + } catch (e) { + error = e + } + expect(error).toBeDefined() + expect(error.message).toMatch(/bad-pty\.node needs GLIBC_2\.34/) + expect(error.message).toMatch(/relr-exe\.node needs GLIBC_ABI_DT_RELR/) + expect(error.message).toMatch(/cxx-addon\.node needs GLIBCXX_3\.4\.29/) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it('throws when a pinned binary imports openpty without libutil.so.1 in DT_NEEDED', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-glibc-noutil-')) + try { + const objdumpPath = await writeStubObjdump(root) + await mkdir(join(root, 'app'), { recursive: true }) + // Supported symbol version still fails without libutil.so.1 DT_NEEDED: openpty cannot resolve on Ubuntu20.04. + await writeFile(join(root, 'app', 'noutil-pty.node'), ELF_HEADER) + + expect(() => verifyLinuxGlibcFloor(join(root, 'app'), { objdumpPath })).toThrow( + /noutil-pty\.node imports openpty but libutil\.so\.1 is not in DT_NEEDED/ + ) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it('passes weak/at-floor needs and the exempt sherpa-onnx libstdc++ prebuilt', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-glibc-under-')) + try { + const objdumpPath = await writeStubObjdump(root) + const sherpaDir = join(root, 'app', 'node_modules', 'sherpa-onnx-linux-x64') + await mkdir(sherpaDir, { recursive: true }) + await writeFile(join(root, 'app', 'good-pty.node'), ELF_HEADER) + await writeFile(join(root, 'app', 'weakonly-lib.so'), ELF_HEADER) // weak GLIBC_2.32 → OK + await writeFile(join(root, 'app', 'orca-ide'), ELF_HEADER) + await writeFile(join(sherpaDir, 'sherpa-onnx.node'), ELF_HEADER) // GLIBCXX_3.4.29, exempt + + expect(() => verifyLinuxGlibcFloor(join(root, 'app'), { objdumpPath })).not.toThrow() + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it('applies the floor profile it is given and names it in the failure', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-glibc-profile-')) + try { + const objdumpPath = await writeStubObjdump(root) + await mkdir(join(root, 'app'), { recursive: true }) + await writeFile(join(root, 'app', 'good-pty.node'), ELF_HEADER) // GLIBC_2.28 + const verify = (glibcFloor) => + verifyLinuxGlibcFloor(join(root, 'app'), { objdumpPath, glibcFloor }) + + expect(() => verify(SERVER_SLOT_GLIBC_FLOOR)).not.toThrow() + expect(() => verify(COMPAT_SLOT_GLIBC_FLOOR)).toThrow( + /will not load on glibc 2\.17 \(CentOS 7[^\n]*\n\s+good-pty\.node needs GLIBC_2\.28/ + ) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it('fails closed when objdump cannot read a binary (non-zero exit)', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-glibc-closed-')) + try { + const objdumpPath = await writeStubObjdump(root) + await mkdir(join(root, 'app'), { recursive: true }) + await writeFile(join(root, 'app', 'unreadable-fail.node'), ELF_HEADER) + + expect(() => verifyLinuxGlibcFloor(join(root, 'app'), { objdumpPath })).toThrow( + /objdump -p failed/ + ) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it('is a no-op (no objdump needed) when there are no native binaries', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-glibc-empty-')) + try { + await mkdir(join(root, 'app'), { recursive: true }) + await writeFile(join(root, 'app', 'readme.txt'), 'no binaries here') + expect(() => + verifyLinuxGlibcFloor(join(root, 'app'), { objdumpPath: '/nonexistent/objdump' }) + ).not.toThrow() + } finally { + await rm(root, { recursive: true, force: true }) + } + }) +}) + +/** Minimal little-endian 64-bit ELF header with the given e_machine. */ +function elfHeader(machine) { + const header = Buffer.alloc(64) + header.write('\x7fELF', 0, 'latin1') + header[4] = 2 // ELFCLASS64 + header[5] = 1 // ELFDATA2LSB + header[6] = 1 // EV_CURRENT + header.writeUInt16LE(3, 16) // ET_DYN + header.writeUInt16LE(machine, 18) + return header +} + +describe('bundled native binary architecture', () => { + it('reads e_machine from a little-endian ELF', async () => { + const dir = await mkdtemp(join(tmpdir(), 'orca-elf-arch-')) + const file = join(dir, 'pty.node') + await writeFile(file, elfHeader(0xb7)) + expect(readElfMachine(file)).toBe(0xb7) + await rm(dir, { recursive: true, force: true }) + }) + + // Catch wrong-arch source build despite valid symbol floors; retain intentionally vendored foreign-arch watcher judged by its own path. + it('accepts a per-arch vendored package that matches its own path', async () => { + const dir = await mkdtemp(join(tmpdir(), 'orca-elf-arch-')) + const pkg = join(dir, '@parcel', 'watcher-linux-arm64-glibc') + await mkdir(pkg, { recursive: true }) + const file = join(pkg, 'watcher.node') + await writeFile(file, elfHeader(0xb7)) + expect(declaredArchFromPath(file)).toBe('arm64') + expect(findArchViolation(file, 'x64')).toBeNull() + await rm(dir, { recursive: true, force: true }) + }) + + // But a path that names an arch must actually hold it — this is the Pi 5 failure. + it('flags a binary that contradicts the architecture its own path names', async () => { + const dir = await mkdtemp(join(tmpdir(), 'orca-elf-arch-')) + const nested = join(dir, 'bin', 'linux-arm64-148') + await mkdir(nested, { recursive: true }) + const file = join(nested, 'node-pty.node') + await writeFile(file, elfHeader(0x3e)) + expect(findArchViolation(file, 'arm64')).toMatchObject({ actual: 'x64', expectedArch: 'arm64' }) + // Still caught even when the slice being built is x64. + expect(findArchViolation(file, 'x64')).toMatchObject({ actual: 'x64', expectedArch: 'arm64' }) + await rm(dir, { recursive: true, force: true }) + }) + + // Release arm64 slices live in `linux-arm64-unpacked`; bundled ripgrep ships linux-x64 beside it. + it('reads arch tokens only below the slice root', async () => { + const root = join(await mkdtemp(join(tmpdir(), 'orca-elf-arch-')), 'linux-arm64-unpacked') + const dir = join(root, 'resources', 'ripgrep', 'linux-x64') + await mkdir(dir, { recursive: true }) + const file = join(dir, 'rg') + await writeFile(file, elfHeader(0x3e)) + expect(findArchViolation(file, 'arm64', root)).toBeNull() + await rm(dirname(root), { recursive: true, force: true }) + }) + + it('flags an x86-64 binary in an arm64 slice', async () => { + const dir = await mkdtemp(join(tmpdir(), 'orca-elf-arch-')) + const file = join(dir, 'pty.node') + await writeFile(file, elfHeader(0x3e)) + expect(findArchViolation(file, 'arm64')).toMatchObject({ actual: 'x64' }) + await rm(dir, { recursive: true, force: true }) + }) + + it('accepts a matching architecture', async () => { + const dir = await mkdtemp(join(tmpdir(), 'orca-elf-arch-')) + const file = join(dir, 'pty.node') + await writeFile(file, elfHeader(0x3e)) + expect(findArchViolation(file, 'x64')).toBeNull() + await rm(dir, { recursive: true, force: true }) + }) + + it('stays silent when no target architecture is supplied', async () => { + const dir = await mkdtemp(join(tmpdir(), 'orca-elf-arch-')) + const file = join(dir, 'pty.node') + await writeFile(file, elfHeader(0x3e)) + expect(findArchViolation(file, undefined)).toBeNull() + await rm(dir, { recursive: true, force: true }) + }) + + it('ignores a file that is not a readable little-endian ELF', async () => { + const dir = await mkdtemp(join(tmpdir(), 'orca-elf-arch-')) + const file = join(dir, 'not-elf.node') + await writeFile(file, Buffer.from('not an elf at all')) + expect(readElfMachine(file)).toBeNull() + expect(findArchViolation(file, 'arm64')).toBeNull() + await rm(dir, { recursive: true, force: true }) + }) +}) diff --git a/config/scripts/native-build/linux/verify-linux-glibc-payloads.test.mjs b/config/scripts/native-build/linux/verify-linux-glibc-payloads.test.mjs new file mode 100644 index 000000000000..3a8ff4c6705e --- /dev/null +++ b/config/scripts/native-build/linux/verify-linux-glibc-payloads.test.mjs @@ -0,0 +1,128 @@ +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' + +const require = createRequire(import.meta.url) +const { verifyLinuxGlibcFloor } = require('./verify-linux-glibc-floor.cjs') +const roots = [] +const STATIC_HEADERS = 'Program Header:\n LOAD off 0x0000000000000000\n' +const MUSL_TARGET = 'orcad-template/targets/linux-arm64-musl/watcher.node' + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +async function writeObjdumpFixture( + headers, + { filename = 'browser', symbolTableError = false } = {} +) { + const root = await mkdtemp(join(tmpdir(), 'orca-glibc-payload-')) + roots.push(root) + const app = join(root, 'app') + const binary = join(app, ...filename.split('/')) + await mkdir(dirname(binary), { recursive: true }) + const elf = Buffer.alloc(64) + elf.write('\x7fELF', 0, 'latin1') + elf[4] = 2 + elf[5] = 1 + elf[6] = 1 + elf.writeUInt16LE(0xb7, 18) + await writeFile(binary, elf) + await writeFile(join(root, 'private-headers.txt'), headers) + const objdumpPath = join(root, 'objdump-stub.sh') + await writeFile( + objdumpPath, + [ + '#!/bin/sh', + 'case "$1" in', + ' --version) echo "GNU objdump (fixture)" ;;', + ' -p) cat "$(dirname "$0")/private-headers.txt" ;;', + symbolTableError + ? ' -T) echo "not a dynamic object" >&2; exit 1 ;;' + : ' -T) echo "0000 DF *UND* 0000 openpty" ;;', + 'esac' + ].join('\n'), + { mode: 0o755 } + ) + return () => verifyLinuxGlibcFloor(app, { objdumpPath, targetArch: 'arm64' }) +} + +describe.skipIf(process.platform === 'win32')('static ELF and remote musl payloads', () => { + it.each(['', '\nDynamic Section:\n'])( + 'accepts static LOAD segments with no dynamic imports (section suffix %j)', + async (suffix) => { + const verify = await writeObjdumpFixture(STATIC_HEADERS + suffix, { symbolTableError: true }) + expect(verify).not.toThrow() + } + ) + + it.each([ + ['missing program headers', 'Dynamic Section:\n'], + [ + 'version references without a dynamic segment', + `${STATIC_HEADERS}Version References:\n required from libc.so.6:\n 0x0 0x00 02 GLIBC_2.17\n` + ], + ['dynamic segment', `${STATIC_HEADERS} DYNAMIC off 0x0000000000001000\n`], + ['interpreter segment', `${STATIC_HEADERS} INTERP off 0x0000000000001000\n`], + ['dependency without a dynamic segment', `${STATIC_HEADERS} NEEDED libc.so.6\n`] + ])('preserves symbol-table failures for %s', async (_label, headers) => { + const verify = await writeObjdumpFixture(headers, { symbolTableError: true }) + expect(verify).toThrow(/objdump -T failed/) + }) + + it.each(['libc.so', 'libc.musl-aarch64.so.1'])( + 'does not apply Ubuntu C++ or libutil requirements to a remote payload linked to %s', + async (libc) => { + const verify = await writeObjdumpFixture( + `Dynamic Section:\n NEEDED ${libc}\n NEEDED libstdc++.so.6\n` + + 'Version References:\n required from libstdc++.so.6:\n 0x0 0x00 02 GLIBCXX_3.4.29\n', + { filename: MUSL_TARGET } + ) + expect(verify).not.toThrow() + } + ) + + it.each([ + ['desktop addon', 'watcher.node', 'libc.so'], + ['glibc target', 'orcad-template/targets/linux-arm64-glibc/watcher.node', 'libc.so'], + ['mislabeled glibc target', MUSL_TARGET, 'libc.so.6'], + ['mixed libc dependencies', MUSL_TARGET, 'libc.so\n NEEDED libc.so.6'] + ])('retains Ubuntu floor and provider checks for %s', async (_label, filename, libc) => { + const verify = await writeObjdumpFixture( + `Dynamic Section:\n NEEDED ${libc}\n NEEDED libstdc++.so.6\n` + + 'Version References:\n required from libstdc++.so.6:\n 0x0 0x00 02 GLIBCXX_3.4.29\n', + { filename } + ) + expect(verify).toThrow( + /needs GLIBCXX_3.4.29.*imports openpty but libutil.so.1 is not in DT_NEEDED/ + ) + }) + + it('still rejects too-new glibc version needs in a musl payload', async () => { + const verify = await writeObjdumpFixture( + 'Dynamic Section:\n NEEDED libc.so\nVersion References:\n' + + ' required from libc.so:\n 0x0 0x00 02 GLIBC_2.34\n', + { filename: MUSL_TARGET } + ) + expect(verify).toThrow(/needs GLIBC_2.34/) + }) + + it('retains the provider check when version references disclose a glibc dependency', async () => { + const verify = await writeObjdumpFixture( + 'Dynamic Section:\n NEEDED libc.so\nVersion References:\n' + + ' required from libc.so.6:\n 0x0 0x00 02 GLIBC_2.17\n', + { filename: MUSL_TARGET } + ) + expect(verify).toThrow(/imports openpty but libutil.so.1 is not in DT_NEEDED/) + }) + + it('preserves objdump failures for a musl-labeled file without proven musl dependencies', async () => { + const verify = await writeObjdumpFixture('Dynamic Section:\n', { + filename: MUSL_TARGET, + symbolTableError: true + }) + expect(verify).toThrow(/objdump -T failed/) + }) +}) diff --git a/config/scripts/native-build/node-addons/native-dependency-lock-digest.test.mjs b/config/scripts/native-build/node-addons/native-dependency-lock-digest.test.mjs new file mode 100644 index 000000000000..4cedcbf6dfa6 --- /dev/null +++ b/config/scripts/native-build/node-addons/native-dependency-lock-digest.test.mjs @@ -0,0 +1,75 @@ +import { describe, expect, it } from 'vitest' +import { nativeDependencyClosure } from './native-dependency-lock-digest.mjs' + +const lockfile = ({ + pty = 'node-pty@1.1.0(patch_hash=aa)', + addon = '7.1.1', + electron = '43.8.1' +}) => `--- +lockfileVersion: '9.0' +importers: + .: + packageManagerDependencies: + pnpm: {specifier: 12.14.0, version: 12.14.0} +--- +lockfileVersion: '9.0' +importers: + .: + devDependencies: + electron: {specifier: ${electron}, version: ${electron}(supports-color@7.2.0)} + native/addon: + dependencies: + node-addon-api: {specifier: ^8.5.0, version: 8.9.2} +snapshots: + ${pty}: + dependencies: + node-addon-api: ${addon} + node-addon-api@7.1.0: {} + node-addon-api@7.1.1: {} + node-addon-api@8.9.2: {} + electron@${electron}(supports-color@7.2.0): + dependencies: + got: 11.8.6 + got@11.8.6: {} + zustand@5.0.15: {} +` +const selection = { + packages: ['node-pty'], + versionOnly: ['electron'], + workspaces: ['native/addon'] +} + +describe('native dependency lock closure', () => { + it('pins native closures, workspace addons and the Electron release only', () => { + expect(nativeDependencyClosure(lockfile({}), selection)).toEqual([ + 'electron@43.8.1', + 'node-addon-api@7.1.1', + 'node-addon-api@8.9.2', + 'node-pty@1.1.0(patch_hash=aa)' + ]) + for (const change of [ + { pty: 'node-pty@1.1.0(patch_hash=bb)' }, + { addon: '7.1.0' }, + { electron: '43.9.0' } + ]) { + expect(nativeDependencyClosure(lockfile(change), selection)).not.toEqual( + nativeDependencyClosure(lockfile({}), selection) + ) + } + }) + + it('fails closed when a selected package or dependency is not locked', () => { + expect(() => nativeDependencyClosure(lockfile({}), { packages: ['missing'] })).toThrow( + /locks none of missing/ + ) + expect(() => + nativeDependencyClosure(lockfile({}), { ...selection, packages: ['node-pty', 'node-gyp'] }) + ).toThrow(/locks none of node-gyp$/) + expect(() => + nativeDependencyClosure(lockfile({}), { ...selection, versionOnly: ['electron', 'nw'] }) + ).toThrow(/locks none of nw$/) + expect(() => + nativeDependencyClosure(lockfile({ addon: '9.9.9' }), { packages: ['node-pty'] }) + ).toThrow(/no snapshot for node-addon-api@9.9.9/) + }) +}) diff --git a/config/scripts/native-build/windows/initialize-windows-native-toolchain.test.mjs b/config/scripts/native-build/windows/initialize-windows-native-toolchain.test.mjs new file mode 100644 index 000000000000..d9765d6523d4 --- /dev/null +++ b/config/scripts/native-build/windows/initialize-windows-native-toolchain.test.mjs @@ -0,0 +1,85 @@ +import { describe, expect, it, vi } from 'vitest' +import { + hasWindowsCompilerSelection, + mergeWindowsCompilerEnvironment, + parseWindowsCompilerEnvironment, + prepareWindowsNodeRuntime +} from './initialize-windows-native-toolchain.mjs' + +const receipt = [ + 'Developer Command Prompt banner, not an environment variable', + 'TOKEN=should-not-be-exported', + 'ORCA_WINDOWS_NATIVE_ENVIRONMENT', + 'VCINSTALLDIR=C:\\Visual Studio\\VC\\', + 'VSCMD_VER=18.10.12224.181', + 'WindowsSDKVersion=10.0.28000.0\\', + 'VSCMD_ARG_TGT_ARCH=arm64', + 'Path=C:\\工具;C:\\Program Files\\Visual Studio', + 'INCLUDE=C:\\SDK=Custom\\Include', + 'TOKEN=should-not-be-exported', + '=C:=C:\\', + '' +].join('\r\n') + +describe('Windows compiler environment receipt', () => { + it('keeps compiler paths and equals signs while excluding unrelated variables and banners', () => { + expect(parseWindowsCompilerEnvironment(receipt, 'arm64')).toEqual({ + VCINSTALLDIR: 'C:\\Visual Studio\\VC\\', + VSCMD_VER: '18.10.12224.181', + WindowsSDKVersion: '10.0.28000.0\\', + VSCMD_ARG_TGT_ARCH: 'arm64', + Path: 'C:\\工具;C:\\Program Files\\Visual Studio', + INCLUDE: 'C:\\SDK=Custom\\Include' + }) + }) + + it.each([ + receipt.replace('ORCA_WINDOWS_NATIVE_ENVIRONMENT', 'missing'), + receipt.replace('VCINSTALLDIR=', 'unrelated='), + receipt.replace('VSCMD_VER=', 'unrelated='), + receipt.replace('WindowsSDKVersion=', 'unrelated='), + receipt.replace('10.0.28000.0\\', 'unavailable'), + receipt.replace('18.10.12224.181', 'unavailable'), + receipt.replace('VSCMD_ARG_TGT_ARCH=arm64', 'VSCMD_ARG_TGT_ARCH=x64') + ])('rejects incomplete, invalid or wrong-architecture setup before use', (output) => { + expect(() => parseWindowsCompilerEnvironment(output, 'arm64')).toThrow() + }) +}) + +describe('Windows native compiler environment scope', () => { + it('replaces path keys case-insensitively without changing the parent environment', () => { + const original = { PATH: 'original-path', LIB: 'original-lib', TOKEN: 'unchanged' } + expect( + mergeWindowsCompilerEnvironment(original, { Path: 'compiler-path', Lib: 'compiler-lib' }) + ).toEqual({ Path: 'compiler-path', Lib: 'compiler-lib', TOKEN: 'unchanged' }) + expect(original).toEqual({ PATH: 'original-path', LIB: 'original-lib', TOKEN: 'unchanged' }) + }) + + it.each([ + 'VCINSTALLDIR', + 'GYP_MSVS_VERSION', + 'npm_config_msvs_version', + 'npm_package_config_node_gyp_msvs_version' + ])('retains an existing compiler selection through %s', (name) => { + expect(hasWindowsCompilerSelection({ [name.toLowerCase()]: 'requested' })).toBe(true) + expect(hasWindowsCompilerSelection({ [name]: '' })).toBe(false) + }) + + it('uses the original preparation and environment after a passing warm probe', () => { + const runProcess = vi.fn(() => ({ code: 0 })) + expect(prepareWindowsNodeRuntime(runProcess)).toBe(0) + expect(runProcess).toHaveBeenCalledTimes(2) + expect(runProcess).toHaveBeenLastCalledWith( + expect.objectContaining({ + args: [expect.stringContaining('ensure-native-runtime.mjs'), '--runtime=node'], + env: process.env, + stdio: 'inherit' + }) + ) + }) + + it('propagates native preparation failure after a passing warm probe', () => { + const runProcess = vi.fn().mockReturnValueOnce({ code: 0 }).mockReturnValueOnce({ code: 9 }) + expect(prepareWindowsNodeRuntime(runProcess)).toBe(9) + }) +}) diff --git a/config/scripts/native-build/windows/msbuild-file-tracking.test.mjs b/config/scripts/native-build/windows/msbuild-file-tracking.test.mjs new file mode 100644 index 000000000000..fdde02db25c4 --- /dev/null +++ b/config/scripts/native-build/windows/msbuild-file-tracking.test.mjs @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { disableMsbuildFileTrackingOnWindows } from './msbuild-file-tracking.mjs' + +describe('disableMsbuildFileTrackingOnWindows', () => { + it('turns tracking off on Windows when the caller left it unset', () => { + expect(disableMsbuildFileTrackingOnWindows({ PATH: 'x' }, 'win32')).toEqual({ + PATH: 'x', + TrackFileAccess: 'false' + }) + }) + + it.each(['TrackFileAccess', 'trackfileaccess', 'TRACKFILEACCESS', 'tRaCkFiLeAcCeSs'])( + 'preserves explicit %s values without adding a duplicate key', + (key) => { + for (const value of ['true', 'false', '']) { + const env = { [key]: value } + expect(disableMsbuildFileTrackingOnWindows(env, 'win32')).toBe(env) + expect(env).toEqual({ [key]: value }) + } + } + ) + + it.each(['linux', 'darwin'])('leaves %s hosts alone', (platform) => { + const env = { PATH: 'x' } + expect(disableMsbuildFileTrackingOnWindows(env, platform)).toBe(env) + expect(env).toEqual({ PATH: 'x' }) + }) +}) diff --git a/config/scripts/native-build/windows/windows-pe-imports.test.mjs b/config/scripts/native-build/windows/windows-pe-imports.test.mjs new file mode 100644 index 000000000000..11cfbbfc78e5 --- /dev/null +++ b/config/scripts/native-build/windows/windows-pe-imports.test.mjs @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest' +import { findDynamicVcRuntimeImports, readPeImportedDllNames } from './windows-pe-imports.mjs' + +// Smallest PE32+ image with one section holding an import directory for `dllNames`. +function peWithImports(dllNames) { + const peOffset = 0x40 + const optionalHeaderSize = 240 + const sectionHeader = peOffset + 24 + optionalHeaderSize + const rawOffset = 0x200 + const virtualAddress = 0x1000 + const descriptorsSize = (dllNames.length + 1) * 20 + const strings = dllNames.map((name) => Buffer.from(`${name}\0`, 'latin1')) + const sectionSize = descriptorsSize + strings.reduce((sum, item) => sum + item.length, 0) + const buffer = Buffer.alloc(rawOffset + sectionSize) + buffer.write('MZ', 0, 'latin1') + buffer.writeUInt32LE(peOffset, 0x3c) + buffer.write('PE\0\0', peOffset, 'latin1') + buffer.writeUInt16LE(0x8664, peOffset + 4) + buffer.writeUInt16LE(1, peOffset + 6) + buffer.writeUInt16LE(optionalHeaderSize, peOffset + 20) + buffer.writeUInt16LE(0x20b, peOffset + 24) + buffer.writeUInt32LE(virtualAddress, peOffset + 24 + 112 + 8) + buffer.writeUInt32LE(sectionSize, sectionHeader + 8) + buffer.writeUInt32LE(virtualAddress, sectionHeader + 12) + buffer.writeUInt32LE(sectionSize, sectionHeader + 16) + buffer.writeUInt32LE(rawOffset, sectionHeader + 20) + let stringRva = virtualAddress + descriptorsSize + strings.forEach((item, index) => { + buffer.writeUInt32LE(stringRva, rawOffset + index * 20 + 12) + item.copy(buffer, rawOffset + (stringRva - virtualAddress)) + stringRva += item.length + }) + return buffer +} + +describe('windows PE imports', () => { + it('reads every imported DLL name in order', () => { + const names = ['KERNEL32.dll', 'VCRUNTIME140.dll', 'api-ms-win-crt-runtime-l1-1-0.dll'] + expect(readPeImportedDllNames(peWithImports(names))).toEqual(names) + }) + + it('reads an image with no imports', () => { + expect(readPeImportedDllNames(peWithImports([]))).toEqual([]) + }) + + it('rejects a file that is not a PE image', () => { + const buffer = Buffer.alloc(0x80) + buffer.writeUInt32LE(0x40, 0x3c) + expect(() => readPeImportedDllNames(buffer)).toThrow('Not a PE image') + }) + + it('flags only the Visual C++ Redistributable DLLs', () => { + expect( + findDynamicVcRuntimeImports([ + 'KERNEL32.dll', + 'ntdll.dll', + 'VCRUNTIME140.dll', + 'vcruntime140_1.dll', + 'MSVCP140.dll', + 'msvcr120.dll', + 'api-ms-win-crt-heap-l1-1-0.dll', + 'ucrtbase.dll' + ]) + ).toEqual(['VCRUNTIME140.dll', 'vcruntime140_1.dll', 'MSVCP140.dll', 'msvcr120.dll']) + }) +}) diff --git a/config/scripts/native-build/windows/windows-pe-machine.test.mjs b/config/scripts/native-build/windows/windows-pe-machine.test.mjs new file mode 100644 index 000000000000..8ffb9767b82c --- /dev/null +++ b/config/scripts/native-build/windows/windows-pe-machine.test.mjs @@ -0,0 +1,80 @@ +import { mkdtempSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { peImage } from './windows-pe-image-fixture.mjs' + +const require = createRequire(import.meta.url) +const { PE_MACHINE, describePeMachine, readPeMachine } = require('./windows-pe-machine.cjs') + +const fixtureDir = mkdtempSync(join(tmpdir(), 'windows-pe-machine-')) + +function writeImage(name, build) { + const path = join(fixtureDir, name) + writeFileSync(path, build()) + return path +} + +const X64 = writeImage('x64.node', () => peImage({ machine: PE_MACHINE.x64 })) +const ARM64 = writeImage('arm64.node', () => peImage({ machine: PE_MACHINE.arm64 })) + +describe('PE_MACHINE', () => { + // Use independent numeric machine values or fixture headers and wrong table could agree by construction. + it('holds the IMAGE_FILE_MACHINE values Windows actually stamps', () => { + expect(PE_MACHINE).toEqual({ x64: 0x8664, arm64: 0xaa64 }) + }) +}) + +describe('readPeMachine', () => { + it.each([ + ['x64', X64, PE_MACHINE.x64], + ['arm64', ARM64, PE_MACHINE.arm64] + ])('reads the machine field of a %s image', (_case, path, expected) => { + expect(readPeMachine(path)).toBe(expected) + }) + + // External non-PE artifacts need classifiable null result, not exception. + it.each([ + ['a Mach-O or ELF binary', () => Buffer.alloc(0x200)], + ['a file too short to hold a DOS header', () => Buffer.from('MZ')], + [ + 'a DOS stub whose PE offset points nowhere', + () => peImage({ machine: 0x8664, peOffset: 0x8000 }).subarray(0, 0x88) + ], + ['a file with no PE signature', () => peImage({ machine: 0x8664, signature: 'XX\0\0' })] + ])('returns null for %s', (_case, build) => { + expect(readPeMachine(writeImage(`not-pe-${Math.random()}.bin`, build))).toBeNull() + }) + + it('respects the DOS header pointer rather than a fixed offset', () => { + const path = writeImage('shifted.node', () => + peImage({ machine: PE_MACHINE.arm64, peOffset: 0x120 }) + ) + expect(readPeMachine(path)).toBe(PE_MACHINE.arm64) + }) +}) + +describe('peImage fixture', () => { + // Reject unknown fixture arch instead of quietly stamping machine zero and hiding gate failures. + it('refuses to invent a machine value for an arch it has none for', () => { + expect(() => peImage({ arch: 'ia32' })).toThrow(/must not invent one/) + }) + + it('still takes an explicit machine, which is how the non-PE cases are built', () => { + expect(readPeMachine(writeImage('explicit.node', () => peImage({ machine: 0x1234 })))).toBe( + 0x1234 + ) + }) +}) + +describe('describePeMachine', () => { + // Distinguish non-PE artifact from wrong-arch build in caller’s error. + it('names a machine field it read', () => { + expect(describePeMachine(PE_MACHINE.arm64)).toBe('machine 0xaa64') + }) + + it('says so when there was none, rather than throwing on null', () => { + expect(describePeMachine(null)).toBe('not a PE image') + }) +}) diff --git a/config/scripts/native-build/windows/windows-process-tree-creation-time.test.mjs b/config/scripts/native-build/windows/windows-process-tree-creation-time.test.mjs new file mode 100644 index 000000000000..8bfbf17d7138 --- /dev/null +++ b/config/scripts/native-build/windows/windows-process-tree-creation-time.test.mjs @@ -0,0 +1,37 @@ +import { createRequire } from 'node:module' +import { expect, it } from 'vitest' + +const { assertWindowsProcessTreeCreationTime } = createRequire(import.meta.url)( + './windows-process-tree-creation-time.cjs' +) + +it('rejects a previously patched binary that has table creation times but no synchronous getter', () => { + expect(() => + assertWindowsProcessTreeCreationTime({ + platform: 'win32', + module: { supportedProcessDataFlags: 7 } + }) + ).toThrow('synchronous identity getter') +}) + +it('accepts the compiled capability only when both readers are available', () => { + expect(() => + assertWindowsProcessTreeCreationTime({ + platform: 'win32', + module: { supportedProcessDataFlags: 7, getProcessCreationTime: () => undefined } + }) + ).not.toThrow() +}) + +it('still rejects a binary without table creation-time support', () => { + expect(() => + assertWindowsProcessTreeCreationTime({ + platform: 'win32', + module: { getProcessCreationTime: () => undefined } + }) + ).toThrow('CreationTime support') +}) + +it('does not require Windows native capabilities on another platform', () => { + expect(() => assertWindowsProcessTreeCreationTime({ platform: 'darwin' })).not.toThrow() +}) diff --git a/config/scripts/node-resolution/ancestor-modules/store-ancestor-node-modules.test.mjs b/config/scripts/node-resolution/ancestor-modules/store-ancestor-node-modules.test.mjs new file mode 100644 index 000000000000..72ecaf993e29 --- /dev/null +++ b/config/scripts/node-resolution/ancestor-modules/store-ancestor-node-modules.test.mjs @@ -0,0 +1,51 @@ +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { nodeModulesAboveStore } from './store-ancestor-node-modules.mjs' + +const slot = join( + '/', + 'home', + 'dev', + 'pnpm', + 'store', + 'v11', + 'links', + '@', + 'zod', + '4.6.5', + 'h', + 'node_modules', + 'zod' +) + +describe('nodeModulesAboveStore', () => { + it('reports node_modules above the store root, not the slot-local ones', () => { + const present = new Set([ + join('/', 'home', 'dev', 'node_modules'), + join('/', 'home', 'node_modules'), + join( + '/', + 'home', + 'dev', + 'pnpm', + 'store', + 'v11', + 'links', + '@', + 'zod', + '4.6.5', + 'h', + 'node_modules' + ) + ]) + expect(nodeModulesAboveStore(slot, (path) => present.has(path))).toEqual([ + join('/', 'home', 'dev', 'node_modules'), + join('/', 'home', 'node_modules') + ]) + }) + + it('reports nothing for a clean store or a path outside any store', () => { + expect(nodeModulesAboveStore(slot, () => false)).toEqual([]) + expect(nodeModulesAboveStore(join('/', 'repo', 'node_modules', 'zod'), () => true)).toEqual([]) + }) +}) diff --git a/src/main/ipc/pty/provider/bind-listeners.ts b/src/main/ipc/pty/provider/bind-listeners.ts index b8813dba24e2..fadc255b33aa 100644 --- a/src/main/ipc/pty/provider/bind-listeners.ts +++ b/src/main/ipc/pty/provider/bind-listeners.ts @@ -30,7 +30,6 @@ export function bindProviderListeners(session: PtyIpcSession): void { localProvider.onWriteUnavailable?.((payload) => { // Before the window check: a headless host has no window, only remote streams. publishPtyEndpointLoss(payload.id) - session.runtime?.notePtyEndpointLoss(payload.id) if ( !session.mainWindow || session.mainWindow.isDestroyed() || diff --git a/src/main/ipc/pty/pty-write-ipc-validation.test.ts b/src/main/ipc/pty/pty-write-ipc-validation.test.ts index 32a27562a6b7..31ad95dd98ab 100644 --- a/src/main/ipc/pty/pty-write-ipc-validation.test.ts +++ b/src/main/ipc/pty/pty-write-ipc-validation.test.ts @@ -113,23 +113,6 @@ describe('registerPtyHandlers', () => { id: result.id }) }) - it('tells the runtime about a daemon endpoint loss even with no window', () => { - let fanout: ((payload: { id: string }) => void) | undefined - installDaemonTestProvider({ - onWriteUnavailable: vi.fn((callback: (payload: { id: string }) => void) => { - fanout = callback - return () => {} - }) - }) - const runtime = new OrcaRuntimeService() - const notePtyEndpointLoss = vi.spyOn(runtime, 'notePtyEndpointLoss') - registerPtyHandlers(mainWindow as never, runtime) - mainWindow.webContents.isDestroyed.mockReturnValue(true) - - fanout?.({ id: 'pane-1' }) - - expect(notePtyEndpointLoss).toHaveBeenCalledWith('pane-1') - }) it('rejects malformed and cross-window pty write IPC before provider writes', async () => { const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) diff --git a/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts b/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts index 77e13a45b904..b3e1a50123fe 100644 --- a/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts +++ b/src/main/runtime/terminal-subscriber-driven-daemon-attach.test.ts @@ -29,8 +29,6 @@ type RuntimeInternals = { worktrees: [], targetWorktreeId: string | null ) => Promise - // Optional so this suite still runs, and fails on behavior, against a runtime without it. - notePtyEndpointLoss?: (ptyId: string) => void } function internals(runtime: OrcaRuntimeService): RuntimeInternals { @@ -50,18 +48,10 @@ function createDaemonProviderModel(opts: { snapshotCapable: boolean }) { const sessions = new Map() const attachCalls: string[] = [] const resizeCalls: [string, number, number][] = [] - const writes: string[] = [] let nextAttachBarrier: { promise: Promise; result: boolean } | null = null let runtime: OrcaRuntimeService | null = null const controller = { - // The adapter refuses input to a session until this app attaches it again. - write: (ptyId: string, data: string) => { - if (!sessions.get(ptyId)?.attached) { - return false - } - writes.push(data) - return true - }, + write: () => true, kill: () => true, getForegroundProcess: async () => null, listProcesses: async () => @@ -120,13 +110,6 @@ function createDaemonProviderModel(opts: { snapshotCapable: boolean }) { sessions, attachCalls, resizeCalls, - writes, - /** Main's daemon link dropped and came back: the daemon released this app's attachments. */ - dropAttachments(): void { - for (const session of sessions.values()) { - session.attached = false - } - }, deferNextAttach(result: boolean): () => void { let release!: () => void const promise = new Promise((resolve) => { @@ -500,145 +483,3 @@ describe('subscriber-driven daemon attach (never-activated tab)', () => { expect(read.tail.join('\n')).not.toContain('stale provider frame') }) }) - -/** A session this app spawned and attached; then main's daemon link drops and returns. The daemon - * releases every attachment of the reconnecting client, and only a pane mounted in this window - * re-attaches on its own. Main must take back every other session's stream so background agents' - * records stay fresh and a paired client, phone or CLI send is not refused. */ -describe('re-attach after a daemon reconnect detached a spawned session', () => { - function setupSpawnedAttachedSession(): ReturnType { - const setup = setupNeverAttachedDaemonSession({ - snapshotCapable: true, - screen: 'agent screen\r\n' - }) - setup.runtime.onPtySpawned(PTY_ID, undefined, { awaitsRegistration: false }) - setup.model.sessions.get(PTY_ID)!.attached = true - return setup - } - - function loseEndpoint( - runtime: OrcaRuntimeService, - model: ReturnType - ): void { - model.dropAttachments() - // What the local provider's write-unavailable fan-out reports for every session it held. - internals(runtime).notePtyEndpointLoss?.(PTY_ID) - } - - it('takes back the stream of a session no view shows', async () => { - const { runtime, model, handle } = setupSpawnedAttachedSession() - - loseEndpoint(runtime, model) - - await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) - expect(model.emitData(PTY_ID, 'background agent output\r\n')).toBe(true) - await expect( - runtime.sendTerminal(handle, { text: 'typed' }, { inputKind: 'driving' }) - ).resolves.toMatchObject({ accepted: true }) - expect(model.writes).toEqual(['typed']) - }) - - it('holds input sent while the re-attach is in flight instead of refusing it', async () => { - const { runtime, model, handle } = setupSpawnedAttachedSession() - const releaseAttach = model.deferNextAttach(true) - - loseEndpoint(runtime, model) - await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) - const send = runtime.sendTerminal(handle, { text: 'early key' }, { inputKind: 'driving' }) - await Promise.resolve() - expect(model.writes).toEqual([]) - releaseAttach() - - await expect(send).resolves.toMatchObject({ accepted: true }) - expect(model.writes).toEqual(['early key']) - }) - - it('drops input cancelled while the re-attach is in flight', async () => { - const { runtime, model, handle } = setupSpawnedAttachedSession() - const releaseAttach = model.deferNextAttach(true) - loseEndpoint(runtime, model) - await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) - const cancel = new AbortController() - const send = runtime.sendTerminal( - handle, - { text: 'cancelled key' }, - { inputKind: 'driving', signal: cancel.signal } - ) - await Promise.resolve() - - cancel.abort() - releaseAttach() - - await expect(send).rejects.toThrow('request_aborted') - expect(model.writes).toEqual([]) - }) - - it('does not hand held input to a terminal that replaced the one it was sent to', async () => { - const { runtime, model, handle } = setupSpawnedAttachedSession() - const releaseAttach = model.deferNextAttach(true) - loseEndpoint(runtime, model) - await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) - const send = runtime.sendTerminal( - handle, - { text: 'for the old shell' }, - { inputKind: 'driving' } - ) - await Promise.resolve() - - await runtime.onPtyExit(PTY_ID, 0) - runtime.onPtySpawned(PTY_ID, undefined, { awaitsRegistration: false }) - model.sessions.get(PTY_ID)!.attached = true - releaseAttach() - - await expect(send).rejects.toThrow() - expect(model.writes).toEqual([]) - }) - - it('leaves a failed re-attach to the next view or inventory pass, not to each keystroke', async () => { - const { runtime, model, handle } = setupSpawnedAttachedSession() - const releaseAttach = model.deferNextAttach(false) - loseEndpoint(runtime, model) - releaseAttach() - await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) - - await runtime.sendTerminal(handle, { text: 'a' }, { inputKind: 'driving' }).catch(() => {}) - await runtime.sendTerminal(handle, { text: 'b' }, { inputKind: 'driving' }).catch(() => {}) - expect(model.attachCalls).toEqual([PTY_ID]) - - const harness = startMultiplex(runtime) - await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) - sendSubscribe(harness, 1, handle) - await waitForSubscribed(harness, 1) - await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID, PTY_ID])) - expect(model.emitData(PTY_ID, 'live again\r\n')).toBe(true) - }) - - it('redoes an earlier subscriber-driven attach that the loss undid', async () => { - // Never-attached session: the first remote subscribe attaches it (the restored-tab path). - const { runtime, model, handle } = setupNeverAttachedDaemonSession({ snapshotCapable: false }) - const harness = startMultiplex(runtime) - await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) - sendSubscribe(harness, 1, handle) - await waitForSubscribed(harness, 1) - await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) - - loseEndpoint(runtime, model) - - await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID, PTY_ID])) - expect(model.emitData(PTY_ID, 'second life\r\n')).toBe(true) - await vi.waitFor(() => expect(outputText(harness)).toContain('second life')) - }) - - it('attaches again when another loss lands while the re-attach is in flight', async () => { - const { runtime, model } = setupSpawnedAttachedSession() - const releaseFirst = model.deferNextAttach(true) - - loseEndpoint(runtime, model) - await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID])) - loseEndpoint(runtime, model) - releaseFirst() - - await vi.waitFor(() => expect(model.attachCalls).toEqual([PTY_ID, PTY_ID])) - expect(model.emitData(PTY_ID, 'after both\r\n')).toBe(true) - }) -}) diff --git a/src/main/runtime/terminal/input/terminal-input-dispatch.ts b/src/main/runtime/terminal/input/terminal-input-dispatch.ts index bd0ceb01f99d..8aede49dc600 100644 --- a/src/main/runtime/terminal/input/terminal-input-dispatch.ts +++ b/src/main/runtime/terminal/input/terminal-input-dispatch.ts @@ -125,13 +125,6 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim return probe } - /** The PTY a handle names right now, read without resolving or refusing the handle. */ - private handlePtyId(handle: string): string | undefined { - return ( - this.getLivePtyForHandle(handle)?.pty.ptyId ?? this.handles.get(handle)?.ptyId ?? undefined - ) - } - /** sendTerminal once plugin hooks decided (terminal-plugin-hooked-input.ts). */ protected async sendTerminalAfterPluginHooks( handle: string, @@ -146,8 +139,6 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim const target = await starting return { ...(await this.sendTerminalAfterPluginHooks(target, action, options)), handle } } - // Before resolving the target: a terminal closed or replaced during the wait is then refused, not written. - await this.waitForPtyEndpointReattach(this.handlePtyId(handle), options.signal) const pty = this.getLivePtyForHandle(handle) if (pty) { if (!pty.pty.connected) { @@ -253,10 +244,6 @@ export abstract class OrcaRuntimeWithControllerKnowsPtyIsLive extends OrcaRuntim const target = await starting return { ...(await this.sendAgentPromptAfterPluginHooks(target, prompt, options)), handle } } - await this.waitForPtyEndpointReattach( - this.handlePtyId(handle), - agentPromptObservationSignal(options) - ) const pty = this.getLivePtyForHandle(handle) if (pty) { if (!pty.pty.connected) { diff --git a/src/main/runtime/terminal/layout/terminal-view-presence.ts b/src/main/runtime/terminal/layout/terminal-view-presence.ts index 0c818d0c2985..290d7a169b8c 100644 --- a/src/main/runtime/terminal/layout/terminal-view-presence.ts +++ b/src/main/runtime/terminal/layout/terminal-view-presence.ts @@ -1,4 +1,3 @@ -import { setTimeout as delay } from 'node:timers/promises' import { OrcaRuntimeWithRecordAgentPromptLifecycleState } from '../output/terminal-output-generation' import type { TerminalOscLinkRange } from '../../../../shared/terminal/links/terminal-osc-link-ranges' import type { PtyProviderBufferSnapshot } from '../../../providers/pty-provider-contract' @@ -12,9 +11,6 @@ import type { RuntimeTerminalBufferSnapshot } from '../records/runtime-terminal- import { AUTHORITATIVE_TERMINAL_SNAPSHOT_TIMEOUT_MS } from '../output/provider-snapshot-budget' import { assertTerminalInputWithinLimitWithYield } from '../../terminal-send-payload' -// Covers a daemon reconnect plus the attach; past it the write proceeds and is refused as before. -const ENDPOINT_REATTACH_INPUT_WAIT_MS = 10_000 - export abstract class OrcaRuntimeWithNotifyRemoteTerminalViewPresenceChanged extends OrcaRuntimeWithRecordAgentPromptLifecycleState { protected abstract serializeTerminalBufferFromAvailableState( ptyId: string, @@ -73,60 +69,6 @@ export abstract class OrcaRuntimeWithNotifyRemoteTerminalViewPresenceChanged ext return this.mainDaemonAttachments.isKnownUnattachedLocal(ptyId) } - /** The local provider lost this PTY's endpoint; main re-attaches it so its output and input resume. */ - notePtyEndpointLoss(ptyId: string): void { - this.mainDaemonAttachments.noteEndpointLoss(ptyId) - } - - /** Input waits, bounded, for main's in-flight re-attach after an endpoint loss instead of being refused. */ - protected async waitForPtyEndpointReattach( - ptyId: string | undefined, - signal?: AbortSignal - ): Promise { - const reattach = - ptyId === undefined ? undefined : this.mainDaemonAttachments.pendingReattach(ptyId) - if (ptyId === undefined || !reattach) { - return - } - const generation = this.getPtyLifecycleGeneration(ptyId) - await this.settleEndpointReattach(ptyId, reattach, signal) - if (signal?.aborted) { - // A cancelled send must not be written once the terminal is back. - throw new Error('request_aborted') - } - // Input held for one process must not reach a process that replaced it under the same id. - if (this.getPtyLifecycleGeneration(ptyId) !== generation) { - throw new Error('terminal_handle_stale') - } - } - - private async settleEndpointReattach( - ptyId: string, - first: Promise, - signal?: AbortSignal - ): Promise { - const deadline = performance.now() + ENDPOINT_REATTACH_INPUT_WAIT_MS - // A further loss mid-attach starts another attempt; keep waiting within the same bound. - let reattach: Promise | undefined = first - while (reattach) { - const remainingMs = deadline - performance.now() - if (remainingMs <= 0) { - return - } - const stopWaiting = new AbortController() - const waitSignal = signal ? AbortSignal.any([signal, stopWaiting.signal]) : stopWaiting.signal - const settled = await Promise.race([ - reattach.then(() => true), - delay(remainingMs, false, { signal: waitSignal }).catch(() => false) - ]) - stopWaiting.abort() - if (!settled) { - return - } - reattach = this.mainDaemonAttachments.pendingReattach(ptyId) - } - } - /** Mark a raw-output viewer without transferring terminal query authority. */ registerRawTerminalViewSubscriber(ptyId: string): () => void { return this.terminalViewSubscribers.registerRaw(ptyId) diff --git a/src/main/runtime/terminal/lifecycle/main-daemon-attachments.ts b/src/main/runtime/terminal/lifecycle/main-daemon-attachments.ts index 2fe432a4aa94..a6cedb8379cb 100644 --- a/src/main/runtime/terminal/lifecycle/main-daemon-attachments.ts +++ b/src/main/runtime/terminal/lifecycle/main-daemon-attachments.ts @@ -1,8 +1,5 @@ type MainDaemonAttachmentDependencies = { - /** A live local daemon session main may attach now (no spawn admission in flight). */ - isAttachableLocalSession: (ptyId: string) => boolean - /** Main already holds this session's screen, so an attach began before this run's tracking. */ - hasMainTerminalState: (ptyId: string) => boolean + isUnattachedLocalCandidate: (ptyId: string) => boolean attachProvider: (ptyId: string) => Promise | null } @@ -16,41 +13,21 @@ export class MainDaemonAttachments { private readonly attaching = new Map>() private readonly queued: (() => void)[] = [] private running = 0 - // Endpoint losses per session while main owes it a re-attach; a count so a loss mid-attach is noticed. - private readonly endpointLosses = new Map() constructor(private readonly deps: MainDaemonAttachmentDependencies) {} markSpawnPublished(ptyId: string): void { this.attached.add(ptyId) - this.endpointLosses.delete(ptyId) } /** Exit or respawn ends the generation whose stream this described. */ forget(ptyId: string): void { this.attached.delete(ptyId) this.attaching.delete(ptyId) - this.endpointLosses.delete(ptyId) } isKnownUnattachedLocal(ptyId: string): boolean { - return ( - !this.attached.has(ptyId) && - this.deps.isAttachableLocalSession(ptyId) && - !this.deps.hasMainTerminalState(ptyId) - ) - } - - /** The daemon dropped this run's attachment, so main re-attaches like at adoption; a mounted pane alone would leave background sessions silent. */ - noteEndpointLoss(ptyId: string): void { - this.endpointLosses.set(ptyId, (this.endpointLosses.get(ptyId) ?? 0) + 1) - this.attached.delete(ptyId) - this.ensure(ptyId) - } - - /** Main's re-attach after an endpoint loss, while in flight; input waits on it instead of being refused. */ - pendingReattach(ptyId: string): Promise | undefined { - return this.endpointLosses.has(ptyId) ? this.attaching.get(ptyId) : undefined + return !this.attached.has(ptyId) && this.deps.isUnattachedLocalCandidate(ptyId) } /** Inventory proved the session live; attach it, or retry once an in-flight refusal settles. */ @@ -68,10 +45,9 @@ export class MainDaemonAttachments { } ensure(ptyId: string): void { - if (this.attaching.has(ptyId) || !this.isAttachOwed(ptyId)) { + if (this.attaching.has(ptyId) || !this.isKnownUnattachedLocal(ptyId)) { return } - const lossCount = this.endpointLosses.get(ptyId) const attempt: Promise = this.acquireSlot().then(() => this.attach(ptyId, attempt)) this.attaching.set(ptyId, attempt) void attempt.then((attached) => { @@ -79,25 +55,12 @@ export class MainDaemonAttachments { return } this.attaching.delete(ptyId) - if (this.endpointLosses.get(ptyId) !== lossCount) { - // A loss during the attempt can undo the attach it made. - this.ensure(ptyId) - return - } if (attached) { this.attached.add(ptyId) - this.endpointLosses.delete(ptyId) } }) } - // A lost session needs its stream back even though main still holds its screen. - private isAttachOwed(ptyId: string): boolean { - return this.endpointLosses.has(ptyId) - ? !this.attached.has(ptyId) && this.deps.isAttachableLocalSession(ptyId) - : this.isKnownUnattachedLocal(ptyId) - } - private acquireSlot(): Promise { if (this.running < MAX_CONCURRENT_ATTACHES) { this.running += 1 @@ -110,7 +73,7 @@ export class MainDaemonAttachments { private async attach(ptyId: string, attempt: Promise): Promise { try { // While this queued, an exit or respawn may have superseded it, or a pane may have attached. - if (this.attaching.get(ptyId) !== attempt || !this.isAttachOwed(ptyId)) { + if (this.attaching.get(ptyId) !== attempt || !this.isKnownUnattachedLocal(ptyId)) { return false } return (await this.deps.attachProvider(ptyId)) ?? false diff --git a/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts b/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts index f39353518e74..e08111d044fa 100644 --- a/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts +++ b/src/main/runtime/terminal/lifecycle/terminal-view-resources.ts @@ -195,15 +195,18 @@ export abstract class OrcaRuntimeWithFitOverrideListeners extends OrcaRuntimeWit >() protected readonly mainDaemonAttachments = new MainDaemonAttachments({ - isAttachableLocalSession: (ptyId) => { - if (this.pendingPtyRegistrationIncarnations.has(ptyId) || parseAppSshPtyId(ptyId)) { + isUnattachedLocalCandidate: (ptyId) => { + if ( + this.headlessTerminals.has(ptyId) || + this.providerSnapshotPreferredPtys.has(ptyId) || + this.pendingPtyRegistrationIncarnations.has(ptyId) || + parseAppSshPtyId(ptyId) + ) { return false } const pty = this.ptysById.get(ptyId) return pty !== undefined && pty.connectionId === null && pty.connected }, - hasMainTerminalState: (ptyId) => - this.headlessTerminals.has(ptyId) || this.providerSnapshotPreferredPtys.has(ptyId), attachProvider: (ptyId) => this.ptyController?.attach?.(ptyId) ?? null }) From e8979d11086a46966c564728ffc02f481fcbb7ce Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:04:28 -0800 Subject: [PATCH 07/52] Limit pinned history to explicit graph scopes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep All and HEAD snapshots free of redundant ref names, and filter ref searches before nested-tag peeling. Default history requests retain unpinned paging without evicting graph tokens. Co-authored-by: Matheus Breguêz --- src/shared/git/history/git-graph-filters.ts | 2 +- .../git/history/git-history-execution.ts | 15 +++++++++------ .../git-history-real-repository.test.ts | 18 ++++++++++++++++++ .../git/history/git-history-revisions.ts | 5 ++--- .../git/history/git-history-token-store.ts | 7 ++++--- 5 files changed, 34 insertions(+), 13 deletions(-) diff --git a/src/shared/git/history/git-graph-filters.ts b/src/shared/git/history/git-graph-filters.ts index e2a145523111..887b983652f1 100644 --- a/src/shared/git/history/git-graph-filters.ts +++ b/src/shared/git/history/git-graph-filters.ts @@ -12,7 +12,7 @@ export function normalizeGitGraphFilters(value: unknown): Record typeof ref === 'string')) { try { validateHistoryRefs(refs) - filters[key] = refs + filters[key] = [...new Set(refs)].sort() } catch { /* Discard an invalid saved choice. */ } diff --git a/src/shared/git/history/git-history-execution.ts b/src/shared/git/history/git-history-execution.ts index a76e0caef991..dcd01bed894c 100644 --- a/src/shared/git/history/git-history-execution.ts +++ b/src/shared/git/history/git-history-execution.ts @@ -159,7 +159,7 @@ export async function loadGitHistoryFromExecutor( hasMore: false, limit, refs, - resolvedRefs: [] + ...(Array.isArray(refs) ? { resolvedRefs: [] } : {}) } const requestedToken = options.branchOnly ? undefined : options.historyToken const pinned = @@ -197,14 +197,15 @@ export async function loadGitHistoryFromExecutor( : headOid ? [headOid] : [] - let resolvedRefs: string[] = [] + let resolvedRefs: string[] | undefined if (pinned) { historyRevisions = pinned.revisions resolvedRefs = pinned.resolvedRefs } else if (refs !== 'head') { const catalog = await loadGitHistoryRefs(git, cwd) - const chosen = Array.isArray(refs) ? catalog.filter((ref) => refs.includes(ref.id)) : catalog - resolvedRefs = chosen.map((ref) => ref.id) + const selected = Array.isArray(refs) ? new Set(refs) : undefined + const chosen = selected ? catalog.filter((ref) => selected.has(ref.id)) : catalog + resolvedRefs = selected ? chosen.map((ref) => ref.id).sort() : undefined historyRevisions = [ ...new Set([ ...(refs === 'all' && headOid ? [headOid] : []), @@ -214,8 +215,10 @@ export async function loadGitHistoryFromExecutor( } const historyToken = requestedToken ?? - (branchBase ? undefined : gitHistoryTokens.put(cwd, refs, historyRevisions, resolvedRefs)) - const echo = { refs, resolvedRefs, historyToken } + (options.refs !== undefined && !options.branchOnly + ? gitHistoryTokens.put(cwd, refs, historyRevisions, resolvedRefs) + : undefined) + const echo = { refs, ...(resolvedRefs ? { resolvedRefs } : {}), historyToken } if (!historyRevisions.length) { return { ...empty, ...echo } } diff --git a/src/shared/git/history/git-history-real-repository.test.ts b/src/shared/git/history/git-history-real-repository.test.ts index 5fe7e067ece7..dee46892fb6c 100644 --- a/src/shared/git/history/git-history-real-repository.test.ts +++ b/src/shared/git/history/git-history-real-repository.test.ts @@ -216,6 +216,8 @@ describe('filtered and pinned history', () => { 'refs/tags/outer' ]) const all = await loadGitHistoryFromExecutor(git, repo, { refs: 'all' }) + expect(all).not.toHaveProperty('resolvedRefs') + expect(all.historyToken).toEqual(expect.any(String)) expect(all.items.map((item) => item.subject).sort()).toEqual([ 'A', 'B', @@ -281,3 +283,19 @@ describe('filtered and pinned history', () => { } ) }) + +it('keeps default history unpinned without evicting an explicitly pinned graph', async () => { + const { repo, git } = await createRepository() + const graph = await loadGitHistoryFromExecutor(git, repo, { refs: 'head', limit: 1 }) + expect(graph.historyToken).toEqual(expect.any(String)) + for (let i = 0; i < 40; i++) { + const sidebar = await loadGitHistoryFromExecutor(git, repo) + expect(sidebar.historyToken).toBeUndefined() + } + const next = await loadGitHistoryFromExecutor(git, repo, { + refs: 'head', + historyToken: graph.historyToken, + skip: 1 + }) + expect(next.historyChanged).toBeUndefined() +}) diff --git a/src/shared/git/history/git-history-revisions.ts b/src/shared/git/history/git-history-revisions.ts index 5c10e86e9d4c..9f40bccb0b5b 100644 --- a/src/shared/git/history/git-history-revisions.ts +++ b/src/shared/git/history/git-history-revisions.ts @@ -32,10 +32,12 @@ export async function loadGitHistoryRefs( ], cwd ) + const search = query?.toLowerCase() const rows = stdout .split('\n') .filter(Boolean) .map((line) => line.split('\0')) + .filter((row) => !search || row[5]?.toLowerCase().includes(search)) const nested = rows.filter((row) => !row[4] && row[3] === 'tag') const peeled = new Map() if (nested.length) { @@ -65,9 +67,6 @@ export async function loadGitHistoryRefs( if (!revision || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(revision)) { continue } - if (query && !name.toLowerCase().includes(query.toLowerCase())) { - continue - } refs.push({ ...gitHistoryRefFromFullName(name, name, revision), ...(worktreePath ? { worktreePath } : {}) diff --git a/src/shared/git/history/git-history-token-store.ts b/src/shared/git/history/git-history-token-store.ts index 445bb6b9e20d..4fb76c0551bb 100644 --- a/src/shared/git/history/git-history-token-store.ts +++ b/src/shared/git/history/git-history-token-store.ts @@ -4,7 +4,7 @@ import type { GitHistoryRefs } from './git-history-types' type PinnedHistory = { key: string revisions: string[] - resolvedRefs: string[] + resolvedRefs?: string[] touched: number bytes: number } @@ -49,10 +49,11 @@ export class GitHistoryTokenStore { return entry } - put(cwd: string, refs: GitHistoryRefs, revisions: string[], resolvedRefs: string[]): string { + put(cwd: string, refs: GitHistoryRefs, revisions: string[], resolvedRefs?: string[]): string { this.prune(Date.now()) const key = this.key(cwd, refs) - const bytes = 2 * (key.length + revisions.join('').length + resolvedRefs.join('').length) + const bytes = + 2 * (key.length + revisions.join('').length + (resolvedRefs?.join('').length ?? 0)) if (bytes > MAX_BYTES) { throw new Error('Git history revision set exceeds the host memory limit') } From 2e748473fb1d45be04cef1cfdd24ea3b403d4d54 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:04:43 -0800 Subject: [PATCH 08/52] Preserve canonical placement for older graph clients Pass graph-free record deltas through without rebuilding layouts, retain existing empty groups, and translate content creation into canonical groups while preserving hidden graph tabs. --- .../rpc/git-graph-layout-projection.test.ts | 89 +++++++++++++++++++ .../rpc/git-graph-layout-projection.ts | 73 +++++++++++++-- .../runtime/rpc/methods/workspace-layout.ts | 8 +- .../workspace-layout-records.ts | 14 ++- 4 files changed, 171 insertions(+), 13 deletions(-) diff --git a/src/main/runtime/rpc/git-graph-layout-projection.test.ts b/src/main/runtime/rpc/git-graph-layout-projection.test.ts index 5ef25c77fb27..62669466a4e7 100644 --- a/src/main/runtime/rpc/git-graph-layout-projection.test.ts +++ b/src/main/runtime/rpc/git-graph-layout-projection.test.ts @@ -1,3 +1,4 @@ +import { applyLayoutCommand } from '../../../shared/workspace-layout/workspace-layout-commands' import { expect, it } from 'vitest' import { createGitGraphFrameProjection, @@ -143,3 +144,91 @@ it('preserves hidden tab slots during reorders and translates collapsed split pa }) expect(split.groupLayout).toMatchObject({ ratio: 0.2 }) }) + +it('passes graph-free record deltas through unchanged and preserves existing empty groups', () => { + const original = layout() + const graphFree = { ...original, tabs: original.tabs.filter((tab) => tab.kind !== 'git-graph') } + const project = createGitGraphFrameProjection() + project({ type: 'workspace', key: 'w', seq: 1, layout: graphFree }) + const change = { + key: 'w', + change: 'records' as const, + workspace: { ...graphFree, groups: [{ id: 'g1', tabIds: ['a', 'b', 'c'] }] } + } + const frame = project({ type: 'records', epoch: 'e', seq: 2, workspaces: [change] }) + expect(frame.type === 'records' && frame.workspaces[0]).toBe(change) + original.groups.push({ id: 'empty', tabIds: [] }) + expect(projectGitGraphLayout(original).groups).toContainEqual({ id: 'empty', tabIds: [] }) +}) + +it('opens files into the canonical group when the projected workspace is empty or targets a hidden group', () => { + const original = layout() + original.tabs = original.tabs.filter((tab) => tab.id === 'graph') + original.groups = [{ id: 'g2', tabIds: ['graph'] }] + original.groupLayout = { type: 'leaf', groupId: 'g2' } + const canonical = { + hostId: 'local' as const, + records: {}, + legacy: { terminalRowOwners: {} }, + workspaces: { + w: { + worktreeId: 'w', + tabs: original.tabs.map((tab) => ({ ...tab, kind: 'git-graph' as const })), + groups: [{ id: 'g2', tabOrder: ['graph'] }], + groupLayout: original.groupLayout + } + } + } + for (const groupId of ['older-client-group', 'g2', undefined]) { + const command = translateGitGraphLayoutCommand( + { + type: 'openEditorTab', + workspace: 'w', + contentType: 'editor', + fileId: '/file', + tabId: 'file', + groupId + }, + original + ) + if (command.type !== 'openEditorTab') { + throw new Error('Expected an editor open command') + } + const applied = applyLayoutCommand(canonical, command, { + mintId: () => 'id', + mintLeafId: () => 'leaf', + now: () => 0 + }) + expect(applied.ok).toBe(true) + if (applied.ok) { + expect(applied.model.workspaces.w.groups).toEqual([{ id: 'g2', tabOrder: ['graph', 'file'] }]) + } + } + const split = translateGitGraphLayoutCommand( + { + type: 'openEditorTab', + workspace: 'w', + contentType: 'editor', + fileId: '/file', + tabId: 'file', + groupId: 'new-group', + split: { besideGroupId: 'older-client-group', direction: 'right' } + }, + original + ) + if (split.type !== 'openEditorTab') { + throw new Error('Expected an editor open command') + } + const opened = applyLayoutCommand(canonical, split, { + mintId: () => 'id', + mintLeafId: () => 'leaf', + now: () => 0 + }) + expect(opened.ok).toBe(true) + if (opened.ok) { + expect(opened.model.workspaces.w.groups).toEqual([ + { id: 'g2', tabOrder: ['graph'] }, + { id: 'new-group', tabOrder: ['file'] } + ]) + } +}) diff --git a/src/main/runtime/rpc/git-graph-layout-projection.ts b/src/main/runtime/rpc/git-graph-layout-projection.ts index b0462f789396..c7b3f5ef6fce 100644 --- a/src/main/runtime/rpc/git-graph-layout-projection.ts +++ b/src/main/runtime/rpc/git-graph-layout-projection.ts @@ -2,7 +2,10 @@ import { GIT_GRAPH_TAB_CAPABILITY } from '../../../shared/source-control/runtime import type { TabGroupLayoutNode } from '../../../shared/tab-types' import type { PublishedWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-published' import { - applyWorkspaceLayoutRecordChange, + applyPublishedLayoutRecordChanges, + splitPublishedLayout, + joinPublishedLayout, + type PublishedLayoutRecords, diffPublishedLayouts, indexPublishedLayout } from '../../../shared/workspace-layout/workspace-layout-records' @@ -14,6 +17,18 @@ import { withGroupSplitRatios } from '../../../shared/workspace-layout/split-ratio-intents' +export const GIT_GRAPH_PLACEMENT_COMMANDS = new Set([ + 'moveTab', + 'setGroupRatios', + 'createTerminalTab', + 'openEditorTab', + 'openSimulatorTab', + 'openBrowserTab', + 'openAgentSessionTab', + 'movePaneToNewTab', + 'moveTabToWorkspace' +]) + export function readsGitGraph(capabilities?: readonly string[]): boolean { return capabilities?.includes(GIT_GRAPH_TAB_CAPABILITY) === true } @@ -65,8 +80,8 @@ export function projectGitGraphLayout(layout: PublishedWorkspaceLayout): Publish layout.tabs.filter((tab) => hidden.has(tab.id)).map((tab) => tab.entityId) ) const groups = layout.groups + .filter((group) => !group.tabIds.length || group.tabIds.some((id) => !hidden.has(id))) .map((group) => ({ ...group, tabIds: group.tabIds.filter((id) => !hidden.has(id)) })) - .filter((group) => group.tabIds.length) return { ...layout, tabs: layout.tabs.filter((tab) => !hidden.has(tab.id)), @@ -78,7 +93,7 @@ export function projectGitGraphLayout(layout: PublishedWorkspaceLayout): Publish // Re-diff whole projected layouts: a delta alone may omit the group a hidden tab made empty. export function createGitGraphFrameProjection() { - const layouts = new Map() + const layouts = new Map() return (frame: WorkspaceLayoutStreamFrame): WorkspaceLayoutStreamFrame => { switch (frame.type) { case 'end': @@ -91,12 +106,12 @@ export function createGitGraphFrameProjection() { return { ...frame, workspaces: frame.workspaces.map(({ key, layout }) => { - layouts.set(key, layout) + layouts.set(key, splitPublishedLayout(layout)) return { key, layout: projectGitGraphLayout(layout) } }) } case 'workspace': - layouts.set(frame.key, frame.layout) + layouts.set(frame.key, splitPublishedLayout(frame.layout)) return { ...frame, layout: projectGitGraphLayout(frame.layout) } case 'records': return { @@ -107,12 +122,24 @@ export function createGitGraphFrameProjection() { layouts.delete(change.key) return [change] } - const after = applyWorkspaceLayoutRecordChange(before, change)! + const after = + change.change === 'layout' + ? splitPublishedLayout(change.layout) + : applyPublishedLayoutRecordChanges(before!, change) layouts.set(change.key, after) - const projected = projectGitGraphLayout(after) + if ( + ![before, after].some((records) => + records?.tabs.some((tab) => tab.kind === 'git-graph') + ) + ) { + return [change] + } + const projected = projectGitGraphLayout(joinPublishedLayout(after)) const diff = diffPublishedLayouts( change.key, - before ? indexPublishedLayout(projectGitGraphLayout(before)) : null, + before + ? indexPublishedLayout(projectGitGraphLayout(joinPublishedLayout(before))) + : null, indexPublishedLayout(projected), projected ) @@ -131,6 +158,36 @@ export function translateGitGraphLayoutCommand( if (projected === layout) { return command } + if ( + command.type === 'createTerminalTab' || + command.type === 'openEditorTab' || + command.type === 'openSimulatorTab' || + command.type === 'openBrowserTab' || + command.type === 'openAgentSessionTab' || + command.type === 'movePaneToNewTab' || + command.type === 'moveTabToWorkspace' + ) { + const canonicalGroupId = projected.groups[0]?.id ?? layout.groups[0]?.id + if (canonicalGroupId && 'split' in command && command.split) { + const canonicalAnchor = (id: string) => + layout.groups.some((group) => group.id === id) ? id : canonicalGroupId + return { + ...command, + split: { + ...command.split, + besideGroupId: canonicalAnchor(command.split.besideGroupId), + ...(command.split.besideLastGroupId + ? { besideLastGroupId: canonicalAnchor(command.split.besideLastGroupId) } + : {}) + } + } + } + const groupId = 'groupId' in command ? command.groupId : undefined + if (canonicalGroupId && !projected.groups.some((group) => group.id === groupId)) { + return { ...command, groupId: canonicalGroupId } + } + } + if (command.type === 'moveTab') { const fullOrder = layout.groups diff --git a/src/main/runtime/rpc/methods/workspace-layout.ts b/src/main/runtime/rpc/methods/workspace-layout.ts index a956b724e364..d3691fbf8ed3 100644 --- a/src/main/runtime/rpc/methods/workspace-layout.ts +++ b/src/main/runtime/rpc/methods/workspace-layout.ts @@ -1,5 +1,6 @@ import { readsGitGraph, + GIT_GRAPH_PLACEMENT_COMMANDS, createGitGraphFrameProjection, translateGitGraphLayoutCommand } from '../git-graph-layout-projection' @@ -108,13 +109,16 @@ export const LAYOUT_APPLY_METHODS = [ const command = params.command if ( readsGitGraph(clientCapabilities) || - (command.type !== 'moveTab' && command.type !== 'setGroupRatios') + !GIT_GRAPH_PLACEMENT_COMMANDS.has(command.type) || + !('workspace' in command) ) { return runtime.applyLayoutCommand(command) } const { snapshot, unsubscribe } = runtime.subscribeWorkspaceLayouts(() => {}) unsubscribe() - const layout = snapshot.find((entry) => entry.key === command.workspace)?.layout + const workspace = + command.type === 'moveTabToWorkspace' ? command.toWorkspace : command.workspace + const layout = snapshot.find((entry) => entry.key === workspace)?.layout return runtime.applyLayoutCommand( layout ? translateGitGraphLayoutCommand(params.command, layout) : params.command ) diff --git a/src/shared/workspace-layout/workspace-layout-records.ts b/src/shared/workspace-layout/workspace-layout-records.ts index fc301b9d9d41..dd848cc37fa2 100644 --- a/src/shared/workspace-layout/workspace-layout-records.ts +++ b/src/shared/workspace-layout/workspace-layout-records.ts @@ -303,13 +303,21 @@ export function applyWorkspaceLayoutRecordChange( if (!before) { throw new Error(`layout records: a change for unknown workspace ${change.key}`) } - const records = splitPublishedLayout(before) - return joinPublishedLayout({ + return joinPublishedLayout( + applyPublishedLayoutRecordChanges(splitPublishedLayout(before), change) + ) +} + +export function applyPublishedLayoutRecordChanges( + records: PublishedLayoutRecords, + change: WorkspaceLayoutRecordChanges +): PublishedLayoutRecords { + return { workspace: change.workspace ?? records.workspace, tabs: applyKind(records.tabs, change.tabs, RECORD_KEYS.tabs, true), paneTrees: applyKind(records.paneTrees, change.paneTrees, RECORD_KEYS.paneTrees, false), bindings: applyKind(records.bindings, change.bindings, RECORD_KEYS.bindings, false), editorFiles: applyKind(records.editorFiles, change.editorFiles, RECORD_KEYS.editorFiles, true), browserTabs: applyKind(records.browserTabs, change.browserTabs, RECORD_KEYS.browserTabs, true) - }) + } } From d39179469a1a33b543b43cc46c6309f05c9af350 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:05:02 -0800 Subject: [PATCH 09/52] Retain Git Graph browsing state for the tab lifetime Own history retrieval, selection and scroll in one renderer controller that retires on close or owner/filter changes. Accumulate parent pages before publishing, share action-time workspace navigation, serialize ref searches, and scope refreshes to the workspace. --- .../applying-settings/ui-state-update.ts | 7 +- .../editor/git-graph/git-graph-filter.tsx | 100 +++++-- .../git-graph/git-graph-history-controller.ts | 272 ++++++++++++++++++ .../editor/git-graph/git-graph-ref-menu.tsx | 184 ++++++------ .../git-graph/git-graph-rendering.test.tsx | 150 +++++++++- .../editor/git-graph/git-graph-tab.tsx | 49 ++-- .../git-graph-workspace-navigation.ts | 70 +++++ .../editor/git-graph/use-git-graph-history.ts | 187 ++---------- .../retention/closed-editor-tab-controller.ts | 4 + .../commit/use-commit-action.ts | 7 +- .../sync/git-graph-open-button.tsx | 11 +- .../source-control/sync/remote-refresh.ts | 5 +- .../source-control/sync/use-conflict-abort.ts | 1 + .../sync/use-remote-action-runner.ts | 1 + .../src/components/tab-bar/EditorFileTab.tsx | 37 ++- .../components/tab-bar/RecentTabSwitcher.tsx | 8 +- ...use-worktree-jump-palette-quick-actions.ts | 10 +- src/renderer/src/lib/git-graph-tab.ts | 45 ++- .../slices/persisted-ui-write-baseline.ts | 2 +- 19 files changed, 804 insertions(+), 346 deletions(-) create mode 100644 src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts create mode 100644 src/renderer/src/components/editor/git-graph/git-graph-workspace-navigation.ts diff --git a/src/main/persistence/applying-settings/ui-state-update.ts b/src/main/persistence/applying-settings/ui-state-update.ts index da7f0275183a..b294f577524f 100644 --- a/src/main/persistence/applying-settings/ui-state-update.ts +++ b/src/main/persistence/applying-settings/ui-state-update.ts @@ -191,9 +191,10 @@ export function updatePersistedUI( : normalizeExplorerDisplayRootByWorktree( operations.state.ui?.explorerDisplayRootByWorktree ), - gitGraphFiltersByWorktree: normalizeGitGraphFilters( - sanitizedUpdates.gitGraphFiltersByWorktree ?? operations.state.ui?.gitGraphFiltersByWorktree - ), + gitGraphFiltersByWorktree: + sanitizedUpdates.gitGraphFiltersByWorktree !== undefined + ? normalizeGitGraphFilters(sanitizedUpdates.gitGraphFiltersByWorktree) + : operations.state.ui?.gitGraphFiltersByWorktree, showDotfilesByWorktree: sanitizedUpdates.showDotfilesByWorktree !== undefined ? normalizeShowDotfilesByWorktree(sanitizedUpdates.showDotfilesByWorktree) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx b/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx index 7061ada1bc22..f5127831d571 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { Button } from '@/components/ui/button' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Input } from '@/components/ui/input' @@ -6,7 +6,7 @@ import { Checkbox } from '@/components/ui/checkbox' import { getRuntimeGitRefs } from '@/runtime/runtime-git-status-client' import { runtimeEnvironmentSupportsCapability } from '@/runtime/runtime-rpc-client' import { GIT_HISTORY_REFS_CAPABILITY } from '../../../../../shared/source-control/runtime/git-graph-capabilities' -import { gitGraphScope } from '@/lib/git-graph-tab' +import { gitGraphScope, useGitGraphScope } from '@/lib/git-graph-tab' import { getConnectionId } from '@/lib/connection-context' import { translate } from '@/i18n/i18n' import type { @@ -25,12 +25,21 @@ export function GitGraphFilter({ supported: boolean | undefined onChange: (refs: GitHistoryRefs) => void }) { + const requests = useRef<{ running: boolean; pending?: () => Promise }>({ running: false }) const [open, setOpen] = useState(false) const [query, setQuery] = useState('') - const [refs, setRefs] = useState([]) + const [search, setSearch] = useState<{ + owner: string + query: string + refs?: GitHistoryItemRef[] + error?: string + }>() const [probe, setProbe] = useState<{ owner: string | undefined; capable: boolean | null }>() - const [error, setError] = useState() - const owner = JSON.stringify(gitGraphScope(worktreeId)?.route) + const scope = useGitGraphScope(worktreeId) + const owner = JSON.stringify([worktreeId, scope?.route, scope?.worktree.path]) + const refs = open && search?.owner === owner && search.query === query ? (search.refs ?? []) : [] + const error = open && search?.owner === owner && search.query === query ? search.error : undefined + const chosen = useMemo(() => new Set(Array.isArray(filter) ? filter : []), [filter]) const capable = probe?.owner === owner ? probe?.capable : null useEffect(() => { let live = true @@ -61,36 +70,66 @@ export function GitGraphFilter({ return } let live = true - const scope = gitGraphScope(worktreeId) - if (scope) { - void getRuntimeGitRefs( - { - target: scope.target, - worktreeId, - worktreePath: scope.worktree.path, - connectionId: getConnectionId(worktreeId) ?? undefined - }, - query - ) - .then((rows) => { + const queue = requests.current + const drain = async () => { + if (queue.running) { + return + } + queue.running = true + try { + while (queue.pending) { + const next = queue.pending + queue.pending = undefined + await next() + } + } finally { + queue.running = false + } + } + const timeout = setTimeout(() => { + queue.pending = async () => { + const scope = gitGraphScope(worktreeId) + if (!live || !scope) { + return + } + try { + const rows = await getRuntimeGitRefs( + { + target: scope.target, + worktreeId, + worktreePath: scope.worktree.path, + connectionId: getConnectionId(worktreeId) ?? undefined + }, + query + ) if (live) { - setRefs(rows) - setError(undefined) + setSearch({ owner, query, refs: rows }) } - }) - .catch((cause) => { + } catch (cause) { if (live) { - setError(String(cause)) + setSearch({ owner, query, error: String(cause) }) } - }) - } + } + } + void drain() + }, 150) return () => { live = false + queue.pending = undefined + clearTimeout(timeout) } }, [worktreeId, owner, query, open, capable]) return (
- + { + setOpen(next) + if (!next) { + setSearch(undefined) + } + }} + > + + + {translate('gitGraph.switchWorkspace', 'Switch to workspace')} + + + )} + + ) return ( { - if (open) { - void readWorkspace() - } else { - generation.current++ + if (!open) { + setMenuRef(undefined) } }} > - + {inline.map(badge)} + {references.length > inline.length && ( + + + + + {open && ( + + {references.filter((ref) => !inline.includes(ref)).map(badge)} + + )} + )} - title={itemRef.name} - > - {itemRef.name} - +
- - void window.api.ui.writeClipboardText(itemRef.name)}> - {translate('gitGraph.copyBranch', 'Copy branch name')} - - {workspace && ( - { - const state = useAppStore.getState() - state.setActiveWorktree( - workspace.id, - getWorktreeExecutionHostId( - workspace, - state.repos.find((repo) => repo.id === workspace.repoId) - ) - ) - }} - > - {translate('gitGraph.switchWorkspace', 'Switch to workspace')} + {menuRef && ( + + void window.api.ui.writeClipboardText(menuRef.name)}> + {translate('gitGraph.copyBranch', 'Copy branch name')} - )} - + {workspaces.has(menuRef.id) && ( + void onSwitch(menuRef.id)}> + {translate('gitGraph.switchWorkspace', 'Switch to workspace')} + + )} + + )} ) } diff --git a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx index ad8ff5e296d2..760e316e6f1e 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx @@ -1,15 +1,39 @@ // @vitest-environment happy-dom +import { useAppStore } from '@/store' +import { gitGraphHistoryForTab, disposeGitGraphHistory } from './git-graph-history-controller' +import { attachClosedEditorTabCleanup } from '../model-lifetime/retention/closed-editor-tab-controller' +import type { OpenFile } from '@/store/slices/editor/types/open-file' import { act } from 'react' import { createRoot } from 'react-dom/client' import { afterEach, expect, it, vi } from 'vitest' import { TooltipProvider } from '@/components/ui/tooltip' import { GitHistoryPanel } from '@/components/right-sidebar/source-control/sync/git-history-panel' +import { GitGraphTab } from './git-graph-tab' import { GitGraphFilter } from './git-graph-filter' -import { gitGraphFilterSupported } from './use-git-graph-history' +import { useGitGraphHistory, gitGraphFilterSupported } from './use-git-graph-history' import type { GitHistoryResult } from '../../../../../shared/git/history/git-history-types' import * as graph from '../../../../../shared/git/history/git-history-graph' -vi.mock('@/lib/git-graph-tab', () => ({ gitGraphScope: () => ({ target: { kind: 'local' } }) })) +const { scope, getHistory } = vi.hoisted(() => ({ + scope: { + target: { kind: 'local' }, + route: { executionHostId: 'local', runtimeEnvironmentId: null }, + worktree: { path: '/repo' } + }, + getHistory: vi.fn() +})) +vi.mock('@/lib/git-graph-tab', () => ({ + gitGraphScope: () => scope, + useGitGraphScope: () => scope, + gitGraphScopeInputs: () => ({}), + GIT_GRAPH_REFRESH_EVENT: 'orca:git-graph-refresh' +})) +vi.mock('@/runtime/runtime-git-status-client', async (original) => ({ + ...(await original()), + getRuntimeGitHistory: getHistory +})) +vi.mock('@/lib/connection-context', () => ({ getConnectionId: () => null })) +vi.mock('./git-graph-details', () => ({ GitGraphDetails: () => null })) vi.mock('@tanstack/react-virtual', () => ({ useVirtualizer: (options: { count: number }) => ({ getTotalSize: () => options.count * 28, @@ -24,6 +48,7 @@ let root = createRoot(container) afterEach(async () => { await act(async () => root.unmount()) root = createRoot(container) + disposeGitGraphHistory('w::git-graph') vi.restoreAllMocks() }) const result: GitHistoryResult = { @@ -101,3 +126,124 @@ it('disables the branch filter when an older host omits the refs echo', async () ) expect(container.querySelector('button')?.disabled).toBe(false) }) + +it('recovers silently after each later token expiry and ignores refreshes for other worktrees', async () => { + let history: ReturnType + function History() { + history = useGitGraphHistory('w') + return {history.error} + } + const page = { ...result, refs: 'all' as const, hasMore: true, historyToken: 'first' } + getHistory.mockReset().mockResolvedValueOnce(page) + await act(async () => root.render()) + const changed = { ...page, items: [], historyChanged: true } + getHistory + .mockResolvedValueOnce(changed) + .mockResolvedValueOnce({ ...page, historyToken: 'second' }) + await act(async () => { + await history!.loadMore() + }) + expect(history!.result?.historyToken).toBe('second') + getHistory + .mockResolvedValueOnce(changed) + .mockResolvedValueOnce({ ...page, historyToken: 'third' }) + await act(async () => { + await history!.loadMore() + }) + expect(history!.result?.historyToken).toBe('third') + expect(history!.error).toBeUndefined() + getHistory.mockResolvedValue({ ...page, historyToken: 'refreshed' }) + await act(async () => + window.dispatchEvent(new CustomEvent('orca:git-graph-refresh', { detail: 'other' })) + ) + expect(history!.result?.historyToken).toBe('third') + await act(async () => + window.dispatchEvent(new CustomEvent('orca:git-graph-refresh', { detail: 'w' })) + ) + expect(history!.result?.historyToken).toBe('refreshed') + expect(getHistory.mock.calls.at(-1)?.[1].wakeWslDistro).toBe(false) +}) + +it('retains history, selection and scroll across remounts, and drops them when a hidden tab closes', async () => { + const cleanup = attachClosedEditorTabCleanup(useAppStore) + const original = useAppStore.getState().openFiles + const file = { + id: 'w::git-graph', + worktreeId: 'w', + mode: 'git-graph', + filePath: 'w::git-graph' + } as OpenFile + useAppStore.setState({ openFiles: [...original, file] }) + const render = () => ( + + + + ) + const page = { + ...result, + items: [...result.items, { id: 'b', subject: 'second', message: 'second', parentIds: [] }], + refs: 'all' as const + } + getHistory.mockReset().mockResolvedValueOnce(page) + try { + await act(async () => root.render(render())) + await act(async () => { + const commit = Array.from(container.querySelectorAll('button')).find( + (button) => button.textContent === 'second' + )! + commit.click() + const scroll = container.querySelector('div.overflow-y-auto')! + scroll.scrollTop = 144 + scroll.dispatchEvent(new Event('scroll')) + }) + await act(async () => root.render(null)) + await act(async () => root.render(render())) + expect(container.querySelector('[data-current="true"]')?.textContent).toContain('second') + expect(container.querySelector('div.overflow-y-auto')?.scrollTop).toBe(144) + expect(getHistory).toHaveBeenCalledTimes(1) + await act(async () => root.render(null)) + useAppStore.setState({ openFiles: original }) + expect(gitGraphHistoryForTab('w').view.getState().result).toBeUndefined() + } finally { + cleanup() + useAppStore.setState({ openFiles: original }) + } +}) + +it('retrieves a distant parent in one operation without cutting off after ten pages', async () => { + let history: ReturnType + function History() { + history = useGitGraphHistory('w') + return null + } + const ids = ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'parent'] + getHistory.mockReset().mockResolvedValueOnce({ ...result, hasMore: true, historyToken: 'pinned' }) + await act(async () => root.render()) + for (const id of ids) { + getHistory.mockResolvedValueOnce({ + ...result, + items: [{ id, subject: id, message: id, parentIds: [] }], + hasMore: true, + historyToken: 'pinned' + }) + } + await act(async () => { + await history!.reveal('parent') + }) + expect(history!.selectedId).toBe('parent') + expect(history!.result?.items.map((item) => item.id)).toEqual([ + 'a', + 'b', + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i', + 'j', + 'k', + 'l', + 'parent' + ]) +}) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx b/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx index e7bfd940def3..747e25ab9abf 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx @@ -1,4 +1,4 @@ -import { useLayoutEffect, useMemo, useRef, useState } from 'react' +import { useLayoutEffect, useMemo, useRef } from 'react' import { useVirtualizer } from '@tanstack/react-virtual' import { RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' @@ -15,7 +15,7 @@ import { import { useGitGraphHistory, gitGraphFilterSupported } from './use-git-graph-history' import { GitGraphFilter } from './git-graph-filter' import { GitGraphDetails } from './git-graph-details' -import { GitGraphRefMenu } from './git-graph-ref-menu' +import { GitGraphRefs, useGitGraphWorkspaces } from './git-graph-ref-menu' import { cn } from '@/lib/utils' import { translate } from '@/i18n/i18n' @@ -24,6 +24,7 @@ const sameGroup = () => undefined export function GitGraphTab({ worktreeId }: { worktreeId: string }) { const history = useGitGraphHistory(worktreeId) const { result, scope } = history + const workspaces = useGitGraphWorkspaces(worktreeId) const rows = useMemo( () => result @@ -51,17 +52,19 @@ export function GitGraphTab({ worktreeId }: { worktreeId: string }) { const scroll = useRef(null) const virtualizer = useVirtualizer({ count: rows.length, + initialOffset: () => history.controller.scrollOffset, getScrollElement: () => scroll.current, estimateSize: () => 24, overscan: 12, getItemKey: (index) => rows[index]!.historyItem.id }) - const [selectedId, setSelectedId] = useState() - if (!selectedId && result?.items[0]) { - setSelectedId(result.items[0].id) - } + const { selectedId, revealId, controller } = history const selected = result?.items.find((item) => item.id === selectedId) ?? result?.items[0] - const [revealId, setRevealId] = useState() + useLayoutEffect(() => { + if (scroll.current) { + scroll.current.scrollTop = controller.scrollOffset + } + }, [controller]) useLayoutEffect(() => { if (!revealId) { return @@ -69,20 +72,15 @@ export function GitGraphTab({ worktreeId }: { worktreeId: string }) { const index = rows.findIndex((row) => row.historyItem.id === revealId) if (index !== -1) { virtualizer.scrollToIndex(index) - setRevealId(undefined) + controller.clearReveal() } - }, [rows, revealId, virtualizer]) + }, [rows, revealId, virtualizer, controller]) const actions = useGitHistoryCommitActions({ activeWorktreeId: worktreeId, worktreePath: scope?.worktree.path ?? null, activeRepoTarget: scope?.target ?? null, resolveSplitTargetGroupId: sameGroup }) - const selectParent = async (id: string) => { - await history.reveal(id) - setSelectedId(id) - setRevealId(id) - } return (
@@ -127,6 +125,9 @@ export function GitGraphTab({ worktreeId }: { worktreeId: string }) { className="min-h-0 flex-1 overflow-y-auto scrollbar-sleek" onScroll={() => { const element = scroll.current + if (element) { + controller.scrollOffset = element.scrollTop + } if ( element && element.scrollHeight - element.scrollTop - element.clientHeight < 200 && @@ -156,23 +157,21 @@ export function GitGraphTab({ worktreeId }: { worktreeId: string }) { gridTemplateColumns: columns }} data-current={selected?.id === item.id} - onClick={() => setSelectedId(item.id)} + onClick={() => controller.select(item.id)} >
- {item.references?.map((ref) => ( - - ))} +
-
@@ -183,7 +186,7 @@ export function GitGraphFilter({ } else { next.delete(ref.id) } - onChange(next.size ? [...next].sort() : 'all') + setDraft({ owner, refs: [...next].sort() }) }} /> {ref.name} diff --git a/src/renderer/src/lib/git-graph-tab.ts b/src/renderer/src/lib/git-graph-tab.ts index 1885c2a2475b..6a4a8caf54e0 100644 --- a/src/renderer/src/lib/git-graph-tab.ts +++ b/src/renderer/src/lib/git-graph-tab.ts @@ -10,6 +10,7 @@ import { import { selectWorktreesByRepo } from '@/store/workspace-record-selectors' import { resolveWorktreeOperationRoute, + resolveWorktreeOperationRouteForHost, type WorktreeOperationRouteState } from './worktree-operation-route' import { openWorkspaceEditorItem } from '@/store/slices/editor/tabs/workspace-editor-item' @@ -20,6 +21,10 @@ import { readCachedRuntimeEnvironmentCapability, runtimeEnvironmentSupportsCapability } from '@/runtime/runtime-rpc-client' +import { + getSshTargetIdForExecutionHost, + type ExecutionHostId +} from '../../../shared/execution-host' export const GIT_GRAPH_REFRESH_EVENT = 'orca:git-graph-refresh' @@ -43,14 +48,23 @@ export function gitGraphScopeInputs(state: ReturnType gitGraphScope(worktreeId, inputs), [worktreeId, inputs]) + return useMemo( + () => gitGraphScope(worktreeId, inputs, executionHostId), + [worktreeId, inputs, executionHostId] + ) } -export function gitGraphScope(worktreeId: string, state: ScopeState = useAppStore.getState()) { +export function gitGraphScope( + worktreeId: string, + state: ScopeState = useAppStore.getState(), + executionHostId?: ExecutionHostId +) { const worktrees = selectWorktreesByRepo(state) - const route = resolveWorktreeOperationRoute(state, worktreeId) + const route = executionHostId + ? resolveWorktreeOperationRouteForHost(state, worktreeId, executionHostId) + : resolveWorktreeOperationRoute(state, worktreeId) const worktree = route?.executionHostId ? findIndexedWorktreeOwnerForHost(worktrees, worktreeId, route.executionHostId) : findFirstIndexedWorktree(worktrees, worktreeId) @@ -59,7 +73,12 @@ export function gitGraphScope(worktreeId: string, state: ScopeState = useAppStor route?.executionHostId && findIndexedRepoOwnerForHost(state.repos, worktree.repoId, route.executionHostId) return worktree && route && repo?.kind !== 'folder' - ? { worktree, route, target: runtimeTargetForOwnerEnvironment(route.runtimeEnvironmentId) } + ? { + worktree, + route, + connectionId: getSshTargetIdForExecutionHost(route.executionHostId), + target: runtimeTargetForOwnerEnvironment(route.runtimeEnvironmentId) + } : null } From 2faebb00d580c5a3a18831b0f06eddf9e48c5176 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:38:08 -0800 Subject: [PATCH 11/52] Keep Git Graph navigation bound to its tab owner Retain the tab's qualified owner and Git connection across workspace focus changes. Newer selections and refreshes supersede pending parent navigation without losing fetched pages. Report stale workspace switches and let the commit menu handle empty space in the Branch / Tag cell. Cover twin-owner retention, superseded navigation and picker apply-on-close with renderer regressions. --- .../git-graph/git-graph-history-controller.ts | 42 ++- .../editor/git-graph/git-graph-ref-menu.tsx | 103 +++---- .../git-graph/git-graph-rendering.test.tsx | 259 +++++++++++++----- .../editor/git-graph/git-graph-tab.tsx | 5 +- .../git-graph-workspace-navigation.ts | 22 +- .../editor/git-graph/use-git-graph-history.ts | 2 +- .../sync/use-git-history-commit-actions.ts | 16 +- src/renderer/src/i18n/locales/de.json | 1 + src/renderer/src/i18n/locales/en.json | 1 + src/renderer/src/i18n/locales/es.json | 1 + src/renderer/src/i18n/locales/fr.json | 1 + src/renderer/src/i18n/locales/ja.json | 1 + src/renderer/src/i18n/locales/ko.json | 1 + src/renderer/src/i18n/locales/pt.json | 1 + src/renderer/src/i18n/locales/ru.json | 1 + src/renderer/src/i18n/locales/tr.json | 1 + src/renderer/src/i18n/locales/zh-Hant.json | 1 + src/renderer/src/i18n/locales/zh.json | 1 + 18 files changed, 320 insertions(+), 140 deletions(-) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts b/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts index 8c6bdf11d274..ace4547f1172 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts +++ b/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts @@ -4,12 +4,12 @@ import { shallow } from 'zustand/shallow' import { useAppStore } from '@/store' import { gitGraphScope, gitGraphScopeInputs, GIT_GRAPH_REFRESH_EVENT } from '@/lib/git-graph-tab' import { getRuntimeGitHistory } from '@/runtime/runtime-git-status-client' -import { getConnectionId } from '@/lib/connection-context' import { translate } from '@/i18n/i18n' import type { GitHistoryRefs, GitHistoryResult } from '../../../../../shared/git/history/git-history-types' +import type { ExecutionHostId } from '../../../../../shared/execution-host' type HistoryView = { result?: GitHistoryResult @@ -42,6 +42,8 @@ export class GitGraphHistoryController { scrollOffset = 0 private scope: ReturnType private filter: GitHistoryRefs + readonly executionHostId: ExecutionHostId | undefined + private navigation = 0 private generation = 0 private dirty = true private initial = true @@ -51,7 +53,13 @@ export class GitGraphHistoryController { private unsubscribe?: () => void constructor(readonly worktreeId: string) { - this.scope = gitGraphScope(worktreeId) + const state = useAppStore.getState() + const file = state.openFiles.find((file) => file.id === `${worktreeId}::git-graph`) + this.executionHostId = + file?.operationProvenance?.generation.route.executionHostId ?? + gitGraphScope(worktreeId, state)?.route.executionHostId ?? + undefined + this.scope = gitGraphScope(worktreeId, state, this.executionHostId) this.filter = filterFor(worktreeId) } @@ -80,7 +88,7 @@ export class GitGraphHistoryController { } private synchronize(): void { - const scope = gitGraphScope(this.worktreeId) + const scope = gitGraphScope(this.worktreeId, useAppStore.getState(), this.executionHostId) const filter = filterFor(this.worktreeId) if ( gitGraphOwnerKey(scope) === gitGraphOwnerKey(this.scope) && @@ -118,10 +126,11 @@ export class GitGraphHistoryController { } switchToWorkspace = (refId: string): Promise => - switchGitGraphWorkspace(this.worktreeId, refId, () => !this.disposed) + switchGitGraphWorkspace(this.scope, refId, () => !this.disposed) select = (selectedId: string): void => { - this.view.setState({ selectedId }) + this.navigation++ + this.view.setState({ selectedId, revealId: undefined }) } clearReveal = (): void => { this.view.setState({ revealId: undefined }) @@ -135,15 +144,19 @@ export class GitGraphHistoryController { reveal = async (id: string): Promise => { const generation = this.generation + const navigation = ++this.navigation + this.clearReveal() + const current = () => + !this.disposed && generation === this.generation && navigation === this.navigation await this.pending - if (this.disposed || generation !== this.generation) { + if (!current()) { return -1 } let result = this.view.getState().result if (!result?.items.some((item) => item.id === id) && result?.hasMore) { - result = await this.retrieve(true, false, id) + result = await this.retrieve(true, false, id, navigation) } - if (this.disposed || generation !== this.generation) { + if (!current()) { return -1 } const index = result?.items.findIndex((item) => item.id === id) ?? -1 @@ -156,7 +169,8 @@ export class GitGraphHistoryController { private retrieve( append = false, wakeWslDistro = false, - revealId?: string + revealId?: string, + navigation?: number ): Promise { if (this.disposed) { return Promise.resolve(undefined) @@ -191,7 +205,7 @@ export class GitGraphHistoryController { target: context.target, worktreeId: this.worktreeId, worktreePath: context.worktree.path, - connectionId: getConnectionId(this.worktreeId) ?? undefined + connectionId: context.connectionId ?? undefined }, { refs: filter, @@ -227,7 +241,13 @@ export class GitGraphHistoryController { } } accumulated = { ...page, items } - if (!revealId || ids.has(revealId) || !page.hasMore || items.length === count) { + if ( + !revealId || + navigation !== this.navigation || + ids.has(revealId) || + !page.hasMore || + items.length === count + ) { break } } while (current()) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx b/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx index 47df0f870fdc..536524e72a85 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx @@ -10,15 +10,14 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useAppStore } from '@/store' import { selectWorktreesByRepo } from '@/store/workspace-record-selectors' -import { useGitGraphScope } from '@/lib/git-graph-tab' +import type { gitGraphScope } from '@/lib/git-graph-tab' import { gitGraphWorkspaceCatalog } from './git-graph-workspace-navigation' import { translate } from '@/i18n/i18n' import type { GitHistoryItemRef } from '../../../../../shared/git/history/git-history-types' import type { Worktree } from '../../../../../shared/worktree/types' import { cn } from '@/lib/utils' -export function useGitGraphWorkspaces(worktreeId: string) { - const scope = useGitGraphScope(worktreeId) +export function useGitGraphWorkspaces(scope: ReturnType) { const worktrees = useAppStore(selectWorktreesByRepo) const repos = useAppStore((state) => state.repos) return useMemo( @@ -52,36 +51,40 @@ export function GitGraphRefs({ inline[1] = current } const badge = (ref: GitHistoryItemRef) => ( - setMenuRef(ref)} - className={cn( - 'inline-flex max-w-full items-center gap-1 rounded-full border px-1.5 text-2xs text-muted-foreground', - ref.id === currentRefId && 'bg-accent font-medium text-foreground' - )} - > - - {ref.name} + + { + event.stopPropagation() + setMenuRef(ref) + }} + className={cn( + 'inline-flex max-w-full items-center gap-1 rounded-full border px-1.5 text-2xs text-muted-foreground', + ref.id === currentRefId && 'bg-accent font-medium text-foreground' + )} + > + + {ref.name} + + {workspaces.has(ref.id) && ( + + + + + + {translate('gitGraph.switchWorkspace', 'Switch to workspace')} + + + )} - {workspaces.has(ref.id) && ( - - - - - - {translate('gitGraph.switchWorkspace', 'Switch to workspace')} - - - )} - + ) return ( - -
- {inline.map(badge)} - {references.length > inline.length && ( - - - - - {open && ( - - {references.filter((ref) => !inline.includes(ref)).map(badge)} - - )} - - )} -
-
+
+ {inline.map(badge)} + {references.length > inline.length && ( + + + + + {open && ( + + {references.filter((ref) => !inline.includes(ref)).map(badge)} + + )} + + )} +
{menuRef && ( void window.api.ui.writeClipboardText(menuRef.name)}> diff --git a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx index 760e316e6f1e..3b94826f62f2 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx @@ -2,10 +2,13 @@ import { useAppStore } from '@/store' import { gitGraphHistoryForTab, disposeGitGraphHistory } from './git-graph-history-controller' import { attachClosedEditorTabCleanup } from '../model-lifetime/retention/closed-editor-tab-controller' +import { gitGraphScope } from '@/lib/git-graph-tab' +import type { Worktree } from '../../../../../shared/worktree/types' +import type { Repo } from '../../../../../shared/repo-types' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { act } from 'react' import { createRoot } from 'react-dom/client' -import { afterEach, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { TooltipProvider } from '@/components/ui/tooltip' import { GitHistoryPanel } from '@/components/right-sidebar/source-control/sync/git-history-panel' import { GitGraphTab } from './git-graph-tab' @@ -14,25 +17,12 @@ import { useGitGraphHistory, gitGraphFilterSupported } from './use-git-graph-his import type { GitHistoryResult } from '../../../../../shared/git/history/git-history-types' import * as graph from '../../../../../shared/git/history/git-history-graph' -const { scope, getHistory } = vi.hoisted(() => ({ - scope: { - target: { kind: 'local' }, - route: { executionHostId: 'local', runtimeEnvironmentId: null }, - worktree: { path: '/repo' } - }, - getHistory: vi.fn() -})) -vi.mock('@/lib/git-graph-tab', () => ({ - gitGraphScope: () => scope, - useGitGraphScope: () => scope, - gitGraphScopeInputs: () => ({}), - GIT_GRAPH_REFRESH_EVENT: 'orca:git-graph-refresh' -})) +const { getHistory, getRefs } = vi.hoisted(() => ({ getHistory: vi.fn(), getRefs: vi.fn() })) vi.mock('@/runtime/runtime-git-status-client', async (original) => ({ ...(await original()), - getRuntimeGitHistory: getHistory + getRuntimeGitHistory: getHistory, + getRuntimeGitRefs: getRefs })) -vi.mock('@/lib/connection-context', () => ({ getConnectionId: () => null })) vi.mock('./git-graph-details', () => ({ GitGraphDetails: () => null })) vi.mock('@tanstack/react-virtual', () => ({ useVirtualizer: (options: { count: number }) => ({ @@ -45,10 +35,37 @@ vi.mock('@tanstack/react-virtual', () => ({ const container = document.createElement('div') document.body.appendChild(container) let root = createRoot(container) +const initialState = useAppStore.getState() +const workspaceId = 'r::/repo' +const local = { + id: workspaceId, + repoId: 'r', + path: '/repo', + branch: 'refs/heads/main', + hostId: 'local' +} as Worktree +const repo: Repo = { + id: 'r', + path: '/repo', + displayName: 'repo', + badgeColor: '', + addedAt: 0, + executionHostId: 'local' +} +beforeEach(() => { + useAppStore.setState({ + repos: [repo], + worktreesByRepo: { r: [local] }, + activeWorktreeId: workspaceId, + activeWorkspaceExecutionHostId: 'local', + gitGraphFiltersByWorktree: {} + }) +}) afterEach(async () => { await act(async () => root.unmount()) root = createRoot(container) - disposeGitGraphHistory('w::git-graph') + disposeGitGraphHistory(`${workspaceId}::git-graph`) + useAppStore.setState(initialState, true) vi.restoreAllMocks() }) const result: GitHistoryResult = { @@ -103,7 +120,7 @@ it('disables the branch filter when an older host omits the refs echo', async () root.render( {}} @@ -116,7 +133,7 @@ it('disables the branch filter when an older host omits the refs echo', async () root.render( {}} @@ -130,7 +147,7 @@ it('disables the branch filter when an older host omits the refs echo', async () it('recovers silently after each later token expiry and ignores refreshes for other worktrees', async () => { let history: ReturnType function History() { - history = useGitGraphHistory('w') + history = useGitGraphHistory(workspaceId) return {history.error} } const page = { ...result, refs: 'all' as const, hasMore: true, historyToken: 'first' } @@ -158,62 +175,90 @@ it('recovers silently after each later token expiry and ignores refreshes for ot ) expect(history!.result?.historyToken).toBe('third') await act(async () => - window.dispatchEvent(new CustomEvent('orca:git-graph-refresh', { detail: 'w' })) + window.dispatchEvent(new CustomEvent('orca:git-graph-refresh', { detail: workspaceId })) ) expect(history!.result?.historyToken).toBe('refreshed') expect(getHistory.mock.calls.at(-1)?.[1].wakeWslDistro).toBe(false) }) -it('retains history, selection and scroll across remounts, and drops them when a hidden tab closes', async () => { - const cleanup = attachClosedEditorTabCleanup(useAppStore) - const original = useAppStore.getState().openFiles - const file = { - id: 'w::git-graph', - worktreeId: 'w', - mode: 'git-graph', - filePath: 'w::git-graph' - } as OpenFile - useAppStore.setState({ openFiles: [...original, file] }) - const render = () => ( - - - - ) - const page = { - ...result, - items: [...result.items, { id: 'b', subject: 'second', message: 'second', parentIds: [] }], - refs: 'all' as const - } - getHistory.mockReset().mockResolvedValueOnce(page) - try { - await act(async () => root.render(render())) - await act(async () => { - const commit = Array.from(container.querySelectorAll('button')).find( - (button) => button.textContent === 'second' - )! - commit.click() - const scroll = container.querySelector('div.overflow-y-auto')! - scroll.scrollTop = 144 - scroll.dispatchEvent(new Event('scroll')) +it.each(['local', 'ssh:A'] as const)( + 'retains %s twin history across workspace switches, then clears it on owner removal or tab close', + async (hostId) => { + useAppStore.setState({ + repos: [ + ...useAppStore.getState().repos, + { ...repo, executionHostId: 'ssh:A', connectionId: 'A' } + ], + worktreesByRepo: { r: [local, { ...local, hostId: 'ssh:A' }] }, + activeWorkspaceExecutionHostId: hostId }) - await act(async () => root.render(null)) - await act(async () => root.render(render())) - expect(container.querySelector('[data-current="true"]')?.textContent).toContain('second') - expect(container.querySelector('div.overflow-y-auto')?.scrollTop).toBe(144) - expect(getHistory).toHaveBeenCalledTimes(1) - await act(async () => root.render(null)) - useAppStore.setState({ openFiles: original }) - expect(gitGraphHistoryForTab('w').view.getState().result).toBeUndefined() - } finally { - cleanup() - useAppStore.setState({ openFiles: original }) + const cleanup = attachClosedEditorTabCleanup(useAppStore) + const original = useAppStore.getState().openFiles + const file = { + id: `${workspaceId}::git-graph`, + worktreeId: workspaceId, + mode: 'git-graph', + filePath: `${workspaceId}::git-graph` + } as OpenFile + useAppStore.setState({ openFiles: [...original, file] }) + const render = () => ( + + + + ) + const page = { + ...result, + items: [...result.items, { id: 'b', subject: 'second', message: 'second', parentIds: [] }], + refs: 'all' as const + } + getHistory.mockReset().mockResolvedValueOnce(page) + try { + await act(async () => root.render(render())) + expect(getHistory.mock.calls[0]?.[0].connectionId).toBe(hostId === 'ssh:A' ? 'A' : undefined) + await act(async () => { + const commit = Array.from(container.querySelectorAll('button')).find( + (button) => button.textContent === 'second' + )! + commit.click() + const scroll = container.querySelector('div.overflow-y-auto')! + scroll.scrollTop = 144 + scroll.dispatchEvent(new Event('scroll')) + }) + await act(async () => root.render(null)) + await act(async () => + useAppStore.setState({ activeWorktreeId: 'other', activeWorkspaceExecutionHostId: 'local' }) + ) + expect(gitGraphScope(workspaceId)).toBeNull() + expect(gitGraphHistoryForTab(workspaceId).view.getState().selectedId).toBe('b') + await act(async () => + useAppStore.setState({ + activeWorktreeId: workspaceId, + activeWorkspaceExecutionHostId: hostId + }) + ) + await act(async () => root.render(render())) + expect(container.querySelector('[data-current="true"]')?.textContent).toContain('second') + expect(container.querySelector('div.overflow-y-auto')?.scrollTop).toBe(144) + expect(getHistory).toHaveBeenCalledTimes(1) + await act(async () => root.render(null)) + useAppStore.setState({ + worktreesByRepo: { r: [{ ...local, hostId: hostId === 'local' ? 'ssh:A' : 'local' }] } + }) + expect(gitGraphHistoryForTab(workspaceId).view.getState().result).toBeUndefined() + expect(gitGraphHistoryForTab(workspaceId).scrollOffset).toBe(0) + useAppStore.setState({ openFiles: original }) + expect(gitGraphHistoryForTab(workspaceId).view.getState().result).toBeUndefined() + } finally { + cleanup() + useAppStore.setState({ openFiles: original }) + } } -}) +) it('retrieves a distant parent in one operation without cutting off after ten pages', async () => { let history: ReturnType function History() { - history = useGitGraphHistory('w') + history = useGitGraphHistory(workspaceId) return null } const ids = ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'parent'] @@ -247,3 +292,85 @@ it('retrieves a distant parent in one operation without cutting off after ten pa 'parent' ]) }) + +it('keeps retrieved pages without revealing over a newer selection or parent navigation', async () => { + getHistory.mockReset().mockResolvedValueOnce({ ...result, hasMore: true }) + const controller = gitGraphHistoryForTab(workspaceId) + const detach = controller.attach() + await controller.loadMore() + let finish!: (page: GitHistoryResult) => void + getHistory.mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve + }) + ) + const revealing = controller.reveal('parent') + await Promise.resolve() + controller.select('a') + finish({ + ...result, + items: [{ id: 'parent', subject: 'parent', message: 'parent', parentIds: [] }], + hasMore: true + }) + expect(await revealing).toBe(-1) + expect(controller.view.getState().result?.items.map((item) => item.id)).toEqual(['a', 'parent']) + expect(controller.view.getState().selectedId).toBe('a') + expect(controller.view.getState().revealId).toBeUndefined() + + getHistory.mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve + }) + ) + const older = controller.reveal('older') + await Promise.resolve() + const newer = controller.reveal('a') + finish({ ...result, items: [{ id: 'older', subject: 'older', message: 'older', parentIds: [] }] }) + expect(await older).toBe(-1) + expect(await newer).toBe(0) + expect(controller.view.getState().selectedId).toBe('a') + expect(controller.view.getState().revealId).toBe('a') + detach() +}) + +it('applies checkbox choices once on picker close, with no choices returning to All', async () => { + const onChange = vi.fn() + getRefs.mockReset().mockResolvedValue([ + { id: 'refs/heads/b', name: 'b', type: 'head' }, + { id: 'refs/heads/a', name: 'a', type: 'head' } + ]) + const render = (filter: 'all' | string[]) => + root.render( + + + + ) + await act(async () => render('all')) + await act(async () => container.querySelector('button')!.click()) + await vi.waitFor(async () => { + await act(async () => {}) + expect(document.querySelectorAll('[role="checkbox"]')).toHaveLength(2) + }) + const checkboxes = Array.from(document.querySelectorAll('[role="checkbox"]')) + expect(checkboxes).toHaveLength(2) + await act(async () => checkboxes[0]!.click()) + await act(async () => checkboxes[1]!.click()) + expect(onChange).not.toHaveBeenCalled() + await act(async () => container.querySelector('button')!.click()) + expect(onChange.mock.calls).toEqual([[['refs/heads/a', 'refs/heads/b']]]) + + await act(async () => render(['refs/heads/a', 'refs/heads/b'])) + await act(async () => container.querySelector('button')!.click()) + await vi.waitFor(async () => { + await act(async () => {}) + expect(document.querySelectorAll('[role="checkbox"]')).toHaveLength(2) + }) + for (const checkbox of document.querySelectorAll('[role="checkbox"]')) { + await act(async () => checkbox.click()) + } + expect(onChange).toHaveBeenCalledTimes(1) + await act(async () => container.querySelector('button')!.click()) + expect(onChange.mock.calls.at(-1)).toEqual(['all']) +}) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx b/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx index 747e25ab9abf..ec5671206d63 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-tab.tsx @@ -24,7 +24,7 @@ const sameGroup = () => undefined export function GitGraphTab({ worktreeId }: { worktreeId: string }) { const history = useGitGraphHistory(worktreeId) const { result, scope } = history - const workspaces = useGitGraphWorkspaces(worktreeId) + const workspaces = useGitGraphWorkspaces(scope) const rows = useMemo( () => result @@ -79,6 +79,7 @@ export function GitGraphTab({ worktreeId }: { worktreeId: string }) { activeWorktreeId: worktreeId, worktreePath: scope?.worktree.path ?? null, activeRepoTarget: scope?.target ?? null, + ownerConnectionId: scope?.connectionId, resolveSplitTargetGroupId: sameGroup }) return ( @@ -86,6 +87,7 @@ export function GitGraphTab({ worktreeId }: { worktreeId: string }) {
void history.refresh()} > diff --git a/src/renderer/src/components/editor/git-graph/git-graph-workspace-navigation.ts b/src/renderer/src/components/editor/git-graph/git-graph-workspace-navigation.ts index e5a7a2b08ee3..b617cbe5fb40 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-workspace-navigation.ts +++ b/src/renderer/src/components/editor/git-graph/git-graph-workspace-navigation.ts @@ -1,3 +1,5 @@ +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' import { normalizeRuntimePathForComparison } from '../../../../../shared/cross-platform-path' import { getWorktreeExecutionHostId } from '../../../../../shared/execution-host' import { findIndexedRepoOwnerForHost } from '@/lib/worktree-runtime-owner-index' @@ -5,7 +7,6 @@ import { selectWorktreesByRepo } from '@/store/workspace-record-selectors' import { useAppStore } from '@/store' import { gitGraphScope } from '@/lib/git-graph-tab' import { getRuntimeGitRefs } from '@/runtime/runtime-git-status-client' -import { getConnectionId } from '@/lib/connection-context' export const gitGraphOwnerKey = (scope: ReturnType) => JSON.stringify([scope?.route, scope?.worktree.path]) @@ -32,26 +33,30 @@ export function gitGraphWorkspaceCatalog( } export async function switchGitGraphWorkspace( - worktreeId: string, + scope: ReturnType, refId: string, isLive: () => boolean ): Promise { - const scope = gitGraphScope(worktreeId) const hostId = scope?.route.executionHostId if (!scope || !hostId || !isLive()) { return } + const worktreeId = scope.worktree.id try { const refs = await getRuntimeGitRefs( { target: scope.target, worktreeId: worktreeId, worktreePath: scope.worktree.path, - connectionId: getConnectionId(worktreeId) ?? undefined + connectionId: scope.connectionId ?? undefined }, refId ) - if (!isLive() || gitGraphOwnerKey(scope) !== gitGraphOwnerKey(gitGraphScope(worktreeId))) { + if ( + !isLive() || + gitGraphOwnerKey(scope) !== + gitGraphOwnerKey(gitGraphScope(worktreeId, useAppStore.getState(), hostId)) + ) { return } const path = refs.find((ref) => ref.id === refId)?.worktreePath @@ -63,6 +68,13 @@ export async function switchGitGraphWorkspace( ) if (workspace) { useAppStore.getState().setActiveWorktree(workspace.id, hostId) + } else { + toast.message( + translate( + 'gitGraph.workspaceClosed', + "This branch isn't open in another workspace anymore." + ) + ) } } catch { /* A failed lookup cannot navigate to a stale checkout. */ diff --git a/src/renderer/src/components/editor/git-graph/use-git-graph-history.ts b/src/renderer/src/components/editor/git-graph/use-git-graph-history.ts index e794e7cf8b42..236877f4ba74 100644 --- a/src/renderer/src/components/editor/git-graph/use-git-graph-history.ts +++ b/src/renderer/src/components/editor/git-graph/use-git-graph-history.ts @@ -14,8 +14,8 @@ export function gitGraphFilterSupported(result?: GitHistoryResult): boolean | un export function useGitGraphHistory(worktreeId: string) { const filter = useAppStore((state) => state.gitGraphFiltersByWorktree?.[worktreeId] ?? 'all') - const scope = useGitGraphScope(worktreeId) const controller = gitGraphHistoryForTab(worktreeId) + const scope = useGitGraphScope(worktreeId, controller.executionHostId) const view = useStore(controller.view) useEffect(() => controller.attach(), [controller]) const changeFilter = (refs: GitHistoryRefs) => diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/use-git-history-commit-actions.ts b/src/renderer/src/components/right-sidebar/source-control/sync/use-git-history-commit-actions.ts index fc31d48e2a33..24be11f2a7f0 100644 --- a/src/renderer/src/components/right-sidebar/source-control/sync/use-git-history-commit-actions.ts +++ b/src/renderer/src/components/right-sidebar/source-control/sync/use-git-history-commit-actions.ts @@ -41,11 +41,13 @@ export function useGitHistoryCommitActions({ activeWorktreeId, worktreePath, activeRepoTarget, + ownerConnectionId, resolveSplitTargetGroupId }: { activeWorktreeId: string | null | undefined worktreePath: string | null activeRepoTarget: RuntimeClientTarget | null + ownerConnectionId?: string | null resolveSplitTargetGroupId: (event?: SourceControlRowOpenEvent) => string | undefined }): GitHistoryCommitActions { const openCommitAllDiffs = useAppStore((s) => s.openCommitAllDiffs) @@ -68,7 +70,10 @@ export function useGitHistoryCommitActions({ if (cached) { return cached.entries } - const connectionId = getConnectionId(activeWorktreeId) ?? undefined + const connectionId = + ownerConnectionId === undefined + ? (getConnectionId(activeWorktreeId) ?? undefined) + : (ownerConnectionId ?? undefined) const result = await getRuntimeGitCommitCompare( { // Compare on the repo owner, which may differ from the focused host. @@ -91,7 +96,7 @@ export function useGitHistoryCommitActions({ commitCompareCacheRef.current.set(item.id, result) return result.entries }, - [activeRepoTarget, activeWorktreeId, worktreePath] + [activeRepoTarget, activeWorktreeId, worktreePath, ownerConnectionId] ) const openHistoryCommitDiff = useCallback( @@ -191,7 +196,10 @@ export function useGitHistoryCommitActions({ target: requireGitOwnerTarget(activeRepoTarget), worktreeId: activeWorktreeId, worktreePath, - connectionId: getConnectionId(activeWorktreeId) ?? undefined + connectionId: + ownerConnectionId === undefined + ? (getConnectionId(activeWorktreeId) ?? undefined) + : (ownerConnectionId ?? undefined) }, { sha: item.id } ) @@ -243,7 +251,7 @@ export function useGitHistoryCommitActions({ } void explainCommitWithDefaultAgent(activeWorktreeId, item) }, - [activeRepoTarget, activeWorktreeId, copyCommitText, worktreePath] + [activeRepoTarget, activeWorktreeId, copyCommitText, worktreePath, ownerConnectionId] ) return { loadCommitFiles, openHistoryCommitDiff, openCommitFile, handleCommitAction } diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index affc8532a879..4480e6c2b9db 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -23232,6 +23232,7 @@ "oldServer": "Diese Orca-Version auf dem Server zeigt nur den aktuellen Branch", "copyBranch": "Branch-Namen kopieren", "switchWorkspace": "Zum Workspace wechseln", + "workspaceClosed": "Dieser Branch ist nicht mehr in einem anderen Workspace geöffnet.", "refresh": "Commits aktualisieren", "branchTag": "Branch / Tag", "graph": "Graph", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index ae6dadba44b2..8051c622c7e4 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -23950,6 +23950,7 @@ "oldServer": "This server's Orca version shows only the current branch", "copyBranch": "Copy branch name", "switchWorkspace": "Switch to workspace", + "workspaceClosed": "This branch isn't open in another workspace anymore.", "refresh": "Refresh commits", "branchTag": "Branch / Tag", "graph": "Graph", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 4e281b0e3d58..9f8ad69f3690 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -23639,6 +23639,7 @@ "oldServer": "Esta versión de Orca del servidor solo muestra la rama actual", "copyBranch": "Copiar nombre de rama", "switchWorkspace": "Cambiar al espacio de trabajo", + "workspaceClosed": "Esta rama ya no está abierta en otro espacio de trabajo.", "refresh": "Actualizar commits", "branchTag": "Rama / Etiqueta", "graph": "Grafo", diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 16c83a3549f8..b778b67594a9 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -23639,6 +23639,7 @@ "oldServer": "Cette version d’Orca sur le serveur affiche uniquement la branche actuelle", "copyBranch": "Copier le nom de la branche", "switchWorkspace": "Passer à l’espace de travail", + "workspaceClosed": "Cette branche n’est plus ouverte dans un autre espace de travail.", "refresh": "Actualiser les commits", "branchTag": "Branche / Tag", "graph": "Graphe", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 003c46afed11..6bed4231db45 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -22950,6 +22950,7 @@ "oldServer": "このサーバーのOrcaは現在のブランチのみ表示します", "copyBranch": "ブランチ名をコピー", "switchWorkspace": "ワークスペースに切り替え", + "workspaceClosed": "このブランチは別のワークスペースで開かれていません。", "refresh": "コミットを更新", "branchTag": "ブランチ / タグ", "graph": "グラフ", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 3d346f2938b8..568f78f2a32a 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -22950,6 +22950,7 @@ "oldServer": "이 서버의 Orca 버전은 현재 브랜치만 표시합니다", "copyBranch": "브랜치 이름 복사", "switchWorkspace": "워크스페이스로 전환", + "workspaceClosed": "이 브랜치는 더 이상 다른 작업 공간에 열려 있지 않습니다.", "refresh": "커밋 새로 고침", "branchTag": "브랜치 / 태그", "graph": "그래프", diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index b7f0bd1986c7..6d1827682e5f 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -23612,6 +23612,7 @@ "oldServer": "Esta versão do Orca no servidor mostra apenas a branch atual", "copyBranch": "Copiar nome da branch", "switchWorkspace": "Mudar para o espaço de trabalho", + "workspaceClosed": "Esta branch não está mais aberta em outro espaço de trabalho.", "refresh": "Atualizar commits", "branchTag": "Branch / Tag", "graph": "Grafo", diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index 9678b25af99b..6c0b46ad5153 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -23984,6 +23984,7 @@ "oldServer": "Эта версия Orca на сервере показывает только текущую ветку", "copyBranch": "Копировать имя ветки", "switchWorkspace": "Перейти в рабочее пространство", + "workspaceClosed": "Эта ветка больше не открыта в другом рабочем пространстве.", "refresh": "Обновить коммиты", "branchTag": "Ветка / Тег", "graph": "Граф", diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index b45731a18741..81d5497d2725 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -23215,6 +23215,7 @@ "oldServer": "Bu sunucunun Orca sürümü yalnızca geçerli dalı gösterir", "copyBranch": "Dal adını kopyala", "switchWorkspace": "Çalışma alanına geç", + "workspaceClosed": "Bu dal artık başka bir çalışma alanında açık değil.", "refresh": "Commitleri yenile", "branchTag": "Dal / Etiket", "graph": "Grafik", diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 99d16b9a74d4..9fab77f62ce5 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -22900,6 +22900,7 @@ "oldServer": "此伺服器的 Orca 版本僅顯示目前分支", "copyBranch": "複製分支名稱", "switchWorkspace": "切換至工作區", + "workspaceClosed": "此分支已不再於其他工作區中開啟。", "refresh": "重新整理提交", "branchTag": "分支 / 標籤", "graph": "圖", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 0e2f4903bbf3..62a7c68c3774 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -22951,6 +22951,7 @@ "oldServer": "此服务器的 Orca 版本仅显示当前分支", "copyBranch": "复制分支名称", "switchWorkspace": "切换到工作区", + "workspaceClosed": "此分支已不再在其他工作区中打开。", "refresh": "刷新提交", "branchTag": "分支 / 标签", "graph": "图", From 8092d3ff98b20d017b099b4ac5ea425fbe2757b3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 5 Nov 2026 22:51:32 -0800 Subject: [PATCH 12/52] Translate desktop layout commands against canonical state Resolve older desktops' visible groups, tab gaps and split paths inside the canonical mutation, including detach and cross-partition moves. Keep initial admission visibility-aware and cache graph presence for binding-only frames. --- .../cross-partition-tab-move.ts | 9 +- .../editor-tab-layout-apply.test.ts | 49 +- .../layout-command-commit.ts | 5 +- .../layout-command-persistence.ts | 10 +- .../terminal-layout-apply.test.ts | 71 +++ .../terminal-layout-pane-ops.test.ts | 41 ++ .../terminal-pane-admission.ts | 5 +- .../terminal-topology-commit.ts | 3 +- src/main/runtime/orca-runtime.ts | 2 +- .../rpc/git-graph-layout-projection.test.ts | 594 ++++++++++++++---- .../rpc/git-graph-layout-projection.ts | 161 +---- .../methods/workspace-layout-apply.test.ts | 8 +- .../runtime/rpc/methods/workspace-layout.ts | 24 +- .../terminal/layout/runtime-layout-apply.ts | 13 +- .../workspace-layout-client-command.ts | 177 ++++++ .../workspace-layout-client-visibility.ts | 74 +++ .../workspace-layout-command-steps.ts | 37 +- .../workspace-layout-command-types.ts | 2 + .../workspace-layout-commands.ts | 9 +- .../workspace-layout-content-commands.ts | 5 +- .../workspace-layout-group-commands.ts | 26 +- .../workspace-layout-initial-surface.ts | 8 +- .../workspace-layout-tab-commands.ts | 9 +- 23 files changed, 1028 insertions(+), 314 deletions(-) create mode 100644 src/shared/workspace-layout/workspace-layout-client-command.ts create mode 100644 src/shared/workspace-layout/workspace-layout-client-visibility.ts diff --git a/src/main/persistence/terminal-topology/cross-partition-tab-move.ts b/src/main/persistence/terminal-topology/cross-partition-tab-move.ts index beaa5b136e6c..5a96cc140ae9 100644 --- a/src/main/persistence/terminal-topology/cross-partition-tab-move.ts +++ b/src/main/persistence/terminal-topology/cross-partition-tab-move.ts @@ -1,5 +1,6 @@ // Main moves editor tabs across partitions and writes only changed records, retaining in-memory views. +import type { LayoutClientVisibility } from '../../../shared/workspace-layout/workspace-layout-client-visibility' import { randomUUID } from 'node:crypto' import type { ExecutionHostId } from '../../../shared/execution-host' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' @@ -17,7 +18,7 @@ import type { } from '../../../shared/workspace-layout/workspace-layout-model' import { patchStoredSession } from '../../../shared/workspace-layout/workspace-layout-record-patch' import { saveWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-save' -import { moveTabToWorkspace } from '../../../shared/workspace-layout/workspace-layout-workspace-move' +import { applyLayoutCommand } from '../../../shared/workspace-layout/workspace-layout-commands' import { editorViewsOfModel, type PartitionEditorViews } from '../loading-store/layout-editor-views' type PartitionSession = { @@ -72,7 +73,8 @@ function written( export function moveTabAcrossPartitions( from: PartitionSession, to: PartitionSession, - command: CommandOf<'moveTabToWorkspace'> + command: CommandOf<'moveTabToWorkspace'>, + visibility?: LayoutClientVisibility ): CrossPartitionTabMove { const loadedFrom = loadWorkspaceLayout(from.hostId, from.session, loadContext(from)) const loadedTo = loadWorkspaceLayout(to.hostId, to.session, loadContext(to)) @@ -88,7 +90,8 @@ export function moveTabAcrossPartitions( command.toWorkspace, loadedTo.layout.workspaces[command.toWorkspace] ) - const moved = moveTabToWorkspace(joined, command, { + const moved = applyLayoutCommand(joined, command, { + visibility, mintId: randomUUID, mintLeafId: randomUUID, now: Date.now diff --git a/src/main/persistence/terminal-topology/editor-tab-layout-apply.test.ts b/src/main/persistence/terminal-topology/editor-tab-layout-apply.test.ts index cfeae0bb69b2..b99d78f46590 100644 --- a/src/main/persistence/terminal-topology/editor-tab-layout-apply.test.ts +++ b/src/main/persistence/terminal-topology/editor-tab-layout-apply.test.ts @@ -1,3 +1,4 @@ +import { withoutGitGraph } from '../../../shared/workspace-layout/workspace-layout-client-visibility' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -172,21 +173,51 @@ describe('a window moveTabToWorkspace between a local and an SSH workspace', () routes[from]! ]) const newId = `editor:${to}:${path}` + const held = store.getWorkspaceSession(routes[to]).tabGroups?.[to]?.[0]?.id + await store.applyLayoutCommand( + { + type: 'openEditorTab', + workspace: to, + tabId: 'graph', + fileId: 'graph', + contentType: 'git-graph', + view: { + view: { mode: 'git-graph' }, + file: { filePath: 'graph', relativePath: 'graph', language: 'plaintext' } + }, + groupId: 'hidden', + ...(held ? { split: { besideGroupId: held, direction: 'right' as const } } : {}) + }, + [routes[to]!] + ) + const destination = held ?? 'hidden' await expect( - applyWindowLayoutCommand(store, hostIdsFor, { - type: 'moveTabToWorkspace', - workspace: from, - toWorkspace: to, - tabs: [{ tabId: 'e1', newTabId: 'e1', newEntityId: newId }], - groupId: `group-${to}`, - file: { filePath: path, relativePath: 'readme.md', language: 'markdown' } - }) - ).resolves.toEqual({ ok: true, result: { tabId: 'e1', groupId: `group-${to}` } }) + applyWindowLayoutCommand( + store, + hostIdsFor, + { + type: 'moveTabToWorkspace', + workspace: from, + toWorkspace: to, + tabs: [{ tabId: 'e1', newTabId: 'e1', newEntityId: newId }], + groupId: `group-${to}`, + file: { filePath: path, relativePath: 'readme.md', language: 'markdown' } + }, + undefined, + { visibility: withoutGitGraph } + ) + ).resolves.toEqual({ ok: true, result: { tabId: 'e1', groupId: destination } }) // Inspect before reload: this fixture lacks the SSH repo needed to retain its workspace. const source = store.getWorkspaceSession(routes[from]) const target = store.getWorkspaceSession(routes[to]) + expect(target.tabGroups?.[to]?.find((group) => group.id === destination)?.tabOrder).toEqual( + held ? [TAB, 'e1'] : ['graph', 'e1'] + ) + expect(target.unifiedTabs?.[to]?.find((tab) => tab.id === 'graph')?.contentType).toBe( + 'git-graph' + ) expect(source.unifiedTabs?.[from]?.some((tab) => tab.id === 'e1') ?? false).toBe(false) expect(source.openFilesByWorktree?.[from] ?? []).toEqual([]) expect(target.unifiedTabs?.[to]?.find((tab) => tab.id === 'e1')).toMatchObject({ diff --git a/src/main/persistence/terminal-topology/layout-command-commit.ts b/src/main/persistence/terminal-topology/layout-command-commit.ts index 6ec139127806..5d2ec6a31d36 100644 --- a/src/main/persistence/terminal-topology/layout-command-commit.ts +++ b/src/main/persistence/terminal-topology/layout-command-commit.ts @@ -46,7 +46,8 @@ export function keepFrozen( export function commitWindowPaneDetach( hostIds: readonly ExecutionHostId[], command: WindowPaneDetachCommand, - context: TerminalTopologyCommitContext + context: TerminalTopologyCommitContext, + run: LayoutCommandRun = {} ): DurableProfileStateMutation { const resolved = resolveWindowPaneDetach( context.hostIds().map((hostId) => ({ hostId, session: context.getSession(hostId) })), @@ -56,7 +57,7 @@ export function commitWindowPaneDetach( if (resolved && 'code' in resolved) { return { value: { ok: false, code: resolved.code }, persist: false } } - const committed = commitLayoutCommand(hostIds, resolved?.command ?? command, context) + const committed = commitLayoutCommand(hostIds, resolved?.command ?? command, context, run) if (!resolved || !committed.value.ok || committed.persist === false) { return committed } diff --git a/src/main/persistence/terminal-topology/layout-command-persistence.ts b/src/main/persistence/terminal-topology/layout-command-persistence.ts index 22a6b716cfee..ad359384af38 100644 --- a/src/main/persistence/terminal-topology/layout-command-persistence.ts +++ b/src/main/persistence/terminal-topology/layout-command-persistence.ts @@ -1,3 +1,4 @@ +import type { LayoutClientVisibility } from '../../../shared/workspace-layout/workspace-layout-client-visibility' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { CommandOf, @@ -82,6 +83,7 @@ export class LayoutCommandPersistence { run: { admit?: (partitions?: readonly WorkspaceSessionState[]) => boolean live?: LayoutLiveContext + visibility?: LayoutClientVisibility stopBeforeWrite?: (ptyIds: readonly string[]) => boolean onEffects?: (effects: LayoutEffects) => void } = {} @@ -94,7 +96,7 @@ export class LayoutCommandPersistence { resolved, (hostId) => context.sessions.getWorkspaceSession(hostId), applyLayout(resolved, command, topologyCommitContext(context), { - live: run.live, + live: { ...run.live, visibility: run.visibility }, stopBeforeWrite: run.stopBeforeWrite, noteEffects: (noted) => (effects = noted) }) @@ -161,7 +163,8 @@ export class LayoutCommandPersistence { moveTabToWorkspaceAcrossPartitions( command: CommandOf<'moveTabToWorkspace'>, fromHostId: string, - toHostId: string + toHostId: string, + run?: { visibility?: LayoutClientVisibility } ): Promise { const commit = topologyCommitContext(this[layoutCommandPersistenceContext]) const [from, to] = [resolveHostId(fromHostId), resolveHostId(toHostId)] @@ -174,7 +177,8 @@ export class LayoutCommandPersistence { views: partitionEditorViewsOf(runtime, from) }, { hostId: to, session: commit.getSession(to), views: partitionEditorViewsOf(runtime, to) }, - command + command, + run?.visibility ) if (!moved.sessions) { return { value: moved.value, persist: false } diff --git a/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts b/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts index c2d7af4bbee1..dc68ab7c110d 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts +++ b/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts @@ -1,3 +1,5 @@ +import { withoutGitGraph } from '../../../shared/workspace-layout/workspace-layout-client-visibility' +import type { LayoutEffects } from '../../../shared/workspace-layout/workspace-layout-command-types' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -180,3 +182,72 @@ describe('Store.applyLayoutCommand (layout.apply)', () => { expect(store.getWorkspaceSession()).toEqual(local) }) }) + +it('admits competing initial requests against visible tabs inside the durable mutation', async () => { + const { store } = await storeWithOneTab() + await store.applyLayoutCommand({ + type: 'closeTabs', + workspace: WORKTREE, + tabIds: [TAB], + force: true + }) + await store.applyLayoutCommand({ + type: 'openEditorTab', + workspace: WORKTREE, + tabId: 'graph', + fileId: 'graph', + contentType: 'git-graph', + view: { + view: { mode: 'git-graph' }, + file: { filePath: 'graph', relativePath: 'graph', language: 'plaintext' } + }, + groupId: 'hidden' + }) + const effects: LayoutEffects[] = [] + const run = { + visibility: withoutGitGraph, + onEffects: (effect: LayoutEffects) => effects.push(effect) + } + await expect( + store.applyLayoutCommand( + { type: 'createTerminalTab', workspace: WORKTREE, tabId: 'restored', initial: 'restore' }, + ['local'], + run + ) + ).resolves.toEqual({ ok: true, result: {} }) + const replies = await Promise.all([ + store.applyLayoutCommand( + { + type: 'createTerminalTab', + workspace: WORKTREE, + tabId: 'first', + leafId: LEAF, + groupId: 'old-root', + initial: 'activation' + }, + ['local'], + run + ), + store.applyLayoutCommand( + { + type: 'openAgentSessionTab', + workspace: WORKTREE, + tabId: 'second', + sessionId: 'session', + agent: 'codex', + initial: 'activation' + }, + ['local'], + run + ) + ]) + expect(replies).toMatchObject([ + { ok: true, result: { tabId: 'first' } }, + { ok: true, result: {} } + ]) + expect( + store.getWorkspaceSession().tabGroups?.[WORKTREE]?.map(({ id, tabOrder }) => ({ id, tabOrder })) + ).toEqual([{ id: 'hidden', tabOrder: ['graph', 'first'] }]) + expect(effects.flatMap((effect) => effect.startPaneKeys)).toEqual([`first:${LEAF}`]) + expect(effects.flatMap((effect) => effect.stopPtyIds)).toEqual([]) +}) diff --git a/src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts b/src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts index b2726ff36781..d45088fd844c 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts +++ b/src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts @@ -1,3 +1,4 @@ +import { withoutGitGraph } from '../../../shared/workspace-layout/workspace-layout-client-visibility' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -161,6 +162,46 @@ describe('Store.applyLayoutCommand pane operations', () => { return store } + it('keeps window-detach visibility and pane bindings through the atomic commit', async () => { + const store = await storeWithSplitTab(['local']) + const groupId = store.getWorkspaceSession().tabGroups?.[WORKTREE]?.[0]!.id + await store.applyLayoutCommand({ + type: 'openEditorTab', + workspace: WORKTREE, + tabId: 'graph', + fileId: 'graph', + contentType: 'git-graph', + view: { + view: { mode: 'git-graph' }, + file: { filePath: 'graph', relativePath: 'graph', language: 'plaintext' } + }, + groupId, + index: 0 + }) + const reply = await store.applyLayoutCommand( + { + type: 'movePaneToNewTab', + workspace: WORKTREE, + tabId: TAB, + leafId: LEAF_B, + groupId, + index: 0, + windowDetach: { ptyId: 'pty-b' } + }, + ['local'], + { visibility: withoutGitGraph } + ) + if (!reply.ok) { + throw new Error(reply.code) + } + const session = store.getWorkspaceSession() + expect(session.tabGroups?.[WORKTREE]?.[0]?.tabOrder).toEqual(['graph', reply.result.tabId, TAB]) + expect(session.terminalLayoutsByTabId[reply.result.tabId!]?.ptyIdsByLeafId).toEqual({ + [LEAF_B]: 'pty-b' + }) + expect(leafIds(session.terminalLayoutsByTabId[TAB]?.root)).toEqual([LEAF_A]) + }) + it('closes the pane in every partition holding the tab', async () => { const store = await storeWithSplitTab(['local', 'ssh:target-1']) diff --git a/src/main/persistence/terminal-topology/terminal-pane-admission.ts b/src/main/persistence/terminal-topology/terminal-pane-admission.ts index 08f4c4aed355..7650d86bfacf 100644 --- a/src/main/persistence/terminal-topology/terminal-pane-admission.ts +++ b/src/main/persistence/terminal-topology/terminal-pane-admission.ts @@ -50,7 +50,10 @@ export type PaneLayoutChange = { } /** Runtime facts unavailable from stored layout. */ -export type LayoutLiveContext = Pick +export type LayoutLiveContext = Pick< + LayoutContext, + 'isBindingLive' | 'retiresBinding' | 'visibility' +> export function admitPaneToSession( hostId: ExecutionHostId, diff --git a/src/main/persistence/terminal-topology/terminal-topology-commit.ts b/src/main/persistence/terminal-topology/terminal-topology-commit.ts index f09499cfaf88..fcd60494f9f4 100644 --- a/src/main/persistence/terminal-topology/terminal-topology-commit.ts +++ b/src/main/persistence/terminal-topology/terminal-topology-commit.ts @@ -156,7 +156,8 @@ export function applyLayout( ? commitWindowPaneDetach( hostIds, { ...command, windowDetach: command.windowDetach }, - context + context, + run ) : commitLayoutCommand(hostIds, command, context, run) ), diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index a00fa06d0e17..d84b74804a76 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -260,7 +260,7 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { /** Apply a window command to the partitions that hold its tab. */ async applyLayoutCommand( command: Layout.WindowLayoutCommand, - run?: Pick + run?: Pick ): Promise { // Wait for live terminal placement before creating the first workspace surface. const placing = this.livePlacementSettledFor(command) diff --git a/src/main/runtime/rpc/git-graph-layout-projection.test.ts b/src/main/runtime/rpc/git-graph-layout-projection.test.ts index 62669466a4e7..e3c7372a60e8 100644 --- a/src/main/runtime/rpc/git-graph-layout-projection.test.ts +++ b/src/main/runtime/rpc/git-graph-layout-projection.test.ts @@ -1,10 +1,13 @@ +import { publishWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-published' +import { withoutGitGraph } from '../../../shared/workspace-layout/workspace-layout-client-visibility' +import type { + CommandOf, + LayoutCommand +} from '../../../shared/workspace-layout/workspace-layout-command-types' +import type { WorkspaceLayoutModel } from '../../../shared/workspace-layout/workspace-layout-model' import { applyLayoutCommand } from '../../../shared/workspace-layout/workspace-layout-commands' import { expect, it } from 'vitest' -import { - createGitGraphFrameProjection, - projectGitGraphLayout, - translateGitGraphLayoutCommand -} from './git-graph-layout-projection' +import { createGitGraphFrameProjection, projectGitGraphLayout } from './git-graph-layout-projection' import type { PublishedWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-published' import { diffPublishedLayouts, @@ -86,65 +89,6 @@ it('hides graph tabs in snapshots and later record frames while preserving seque expect(projectGitGraphLayout(after).tabs.map((tab) => tab.id)).toEqual(['a', 'b', 'c']) }) -it('preserves hidden tab slots during reorders and translates collapsed split paths', () => { - const original = layout() - expect( - translateGitGraphLayoutCommand( - { type: 'moveTab', workspace: 'w', tabId: 'b', toGroupId: 'g1', index: 0 }, - original - ) - ).toMatchObject({ index: 0 }) - expect( - translateGitGraphLayoutCommand( - { - type: 'moveTab', - workspace: 'w', - tabId: 'b', - toGroupId: 'g1', - index: 1, - afterTabId: 'gone' - }, - original - ) - ).toMatchObject({ index: 2 }) - const split: PublishedWorkspaceLayout = { - ...original, - groups: [ - { id: 'hidden', tabIds: ['graph'] }, - { id: 'g1', tabIds: ['a', 'b'] }, - { id: 'g2', tabIds: ['c'] } - ], - groupLayout: { - type: 'split', - direction: 'vertical', - ratio: 0.2, - first: { type: 'leaf', groupId: 'hidden' }, - second: original.groupLayout! - } - } - expect(projectGitGraphLayout(split).groupLayout).toEqual(original.groupLayout) - expect( - translateGitGraphLayoutCommand( - { - type: 'setGroupRatios', - workspace: 'w', - ratios: [ - { path: '', ratio: 0.7, split: { direction: 'horizontal', first: 'g1', second: 'g2' } } - ] - }, - split - ) - ).toEqual({ - type: 'setGroupRatios', - workspace: 'w', - groupLayout: undefined, - ratios: [ - { path: 'second', ratio: 0.7, split: { direction: 'horizontal', first: 'g1', second: 'g2' } } - ] - }) - expect(split.groupLayout).toMatchObject({ ratio: 0.2 }) -}) - it('passes graph-free record deltas through unchanged and preserves existing empty groups', () => { const original = layout() const graphFree = { ...original, tabs: original.tabs.filter((tab) => tab.kind !== 'git-graph') } @@ -161,26 +105,207 @@ it('passes graph-free record deltas through unchanged and preserves existing emp expect(projectGitGraphLayout(original).groups).toContainEqual({ id: 'empty', tabIds: [] }) }) -it('opens files into the canonical group when the projected workspace is empty or targets a hidden group', () => { - const original = layout() - original.tabs = original.tabs.filter((tab) => tab.id === 'graph') - original.groups = [{ id: 'g2', tabIds: ['graph'] }] - original.groupLayout = { type: 'leaf', groupId: 'g2' } - const canonical = { - hostId: 'local' as const, +function canonical(original = layout()): WorkspaceLayoutModel { + return { + hostId: 'local', records: {}, legacy: { terminalRowOwners: {} }, workspaces: { w: { worktreeId: 'w', - tabs: original.tabs.map((tab) => ({ ...tab, kind: 'git-graph' as const })), - groups: [{ id: 'g2', tabOrder: ['graph'] }], + tabs: original.tabs.map(({ kind, ...tab }) => { + if (kind === 'terminal') { + throw new Error('Expected a content fixture') + } + return { ...tab, kind } + }), + groups: original.groups.map(({ id, tabIds }) => ({ id, tabOrder: tabIds })), groupLayout: original.groupLayout } } } - for (const groupId of ['older-client-group', 'g2', undefined]) { - const command = translateGitGraphLayoutCommand( +} + +function applyClient(command: LayoutCommand, model = canonical()) { + return applyLayoutCommand(model, command, { + visibility: withoutGitGraph, + mintId: () => 'minted', + mintLeafId: () => 'leaf', + now: () => 0 + }) +} + +const opens: CommandOf< + | 'openEditorTab' + | 'createTerminalTab' + | 'openSimulatorTab' + | 'openBrowserTab' + | 'openAgentSessionTab' +>[] = [ + { + type: 'openEditorTab', + workspace: 'w', + contentType: 'editor', + fileId: '/new', + tabId: 'new', + index: 1 + }, + { type: 'createTerminalTab', workspace: 'w', tabId: 'new', leafId: 'leaf', index: 1 }, + { type: 'openSimulatorTab', workspace: 'w', tabId: 'new', index: 1 }, + { type: 'openBrowserTab', workspace: 'w', tabId: 'new', index: 1 }, + { + type: 'openAgentSessionTab', + workspace: 'w', + tabId: 'new', + sessionId: 'session', + agent: 'codex', + index: 1 + } +] + +it.each(opens)( + '$type resolves a visible creation gap without moving the hidden graph', + (command) => { + const opened = applyClient({ ...command, groupId: 'g1' }) + expect(opened.ok).toBe(true) + if (!opened.ok) { + throw new Error(opened.code) + } + expect(opened.model.workspaces.w!.groups).toEqual([ + { id: 'g1', tabOrder: ['a', 'graph', 'new', 'b'] }, + { id: 'g2', tabOrder: ['c'] } + ]) + expect( + projectGitGraphLayout(publishWorkspaceLayout(opened.model.workspaces.w!, 'local')).groups + ).toEqual([ + { id: 'g1', tabIds: ['a', 'new', 'b'] }, + { id: 'g2', tabIds: ['c'] } + ]) + expect(opened.effects).toEqual({ + stopPtyIds: [], + startPaneKeys: command.type === 'createTerminalTab' ? ['new:leaf'] : [] + }) + expect(opened.model.workspaces.w!.tabs.find((tab) => tab.id === 'graph')).toMatchObject({ + kind: 'git-graph' + }) + } +) + +it('reopens at the visible index and accounts for preview replacement before placing', () => { + const model = canonical() + model.workspaces.w!.tabs.find((tab) => tab.id === 'a')!.isPreview = true + const opened = applyClient( + { + type: 'openEditorTab', + workspace: 'w', + contentType: 'editor', + fileId: '/new', + tabId: 'new', + preview: true, + groupId: 'g1', + index: 1 + }, + model + ) + expect(opened.ok && opened.model.workspaces.w!.groups[0]!.tabOrder).toEqual(['graph', 'b', 'new']) + model.workspaces.w!.tabs.find((tab) => tab.id === 'a')!.isPreview = false + model.workspaces.w!.tabs.find((tab) => tab.id === 'graph')!.isPreview = true + const hiddenPreview = applyClient( + { + type: 'openEditorTab', + workspace: 'w', + contentType: 'editor', + fileId: '/new', + tabId: 'new', + preview: true, + groupId: 'g1', + index: 1 + }, + model + ) + expect(hiddenPreview.ok && hiddenPreview.model.workspaces.w!.groups[0]!.tabOrder).toEqual([ + 'a', + 'graph', + 'new', + 'b' + ]) + const root = canonical() + root.workspaces.w!.groups = [{ id: 'g1', tabOrder: ['graph', 'a', 'b', 'c'] }] + root.workspaces.w!.groupLayout = { type: 'leaf', groupId: 'g1' } + const closed = applyClient({ type: 'closeTabs', workspace: 'w', tabIds: ['b'] }, root) + if (!closed.ok) { + throw new Error(closed.code) + } + const reopened = applyClient( + { + type: 'openEditorTab', + workspace: 'w', + contentType: 'editor', + fileId: 'b', + tabId: 'b', + groupId: 'g1', + index: 1 + }, + closed.model + ) + expect(reopened.ok && reopened.model.workspaces.w!.groups[0]!.tabOrder).toEqual([ + 'graph', + 'a', + 'b', + 'c' + ]) +}) + +it.each([ + { index: 0, afterTabId: 'a', expected: ['a', 'graph', 'b'] }, + { index: 1, afterTabId: null, expected: ['b', 'a', 'graph'] }, + { index: 1, afterTabId: 'gone', expected: ['a', 'graph', 'b'] } +])('moves using anchor precedence: $afterTabId', ({ index, afterTabId, expected }) => { + const moved = applyClient({ + type: 'moveTab', + workspace: 'w', + tabId: 'b', + toGroupId: 'g1', + index, + afterTabId + }) + expect(moved.ok && moved.model.workspaces.w!.groups[0]!.tabOrder).toEqual(expected) +}) + +it('gives creation indexes precedence over anchors and retains pin-aware omitted placement', () => { + const model = canonical() + model.workspaces.w!.tabs.find((tab) => tab.id === 'a')!.isPinned = true + const command = { + type: 'openSimulatorTab', + workspace: 'w', + tabId: 'new', + groupId: 'g1', + afterTabId: 'b' + } as const + const indexed = applyClient({ ...command, index: 0 }, model) + expect(indexed.ok && indexed.model.workspaces.w!.groups[0]!.tabOrder).toEqual([ + 'new', + 'a', + 'graph', + 'b' + ]) + const omitted = applyClient({ ...command, afterTabId: 'a' }, model) + expect(omitted.ok && omitted.model.workspaces.w!.groups[0]!.tabOrder).toEqual([ + 'a', + 'graph', + 'new', + 'b' + ]) +}) + +it.each([undefined, 'older-root', 'g2'])( + 'opens in a projected-empty workspace, requested group %s', + (groupId) => { + const model = canonical() + model.workspaces.w!.tabs = model.workspaces.w!.tabs.filter((tab) => tab.id === 'graph') + model.workspaces.w!.groups = [{ id: 'g2', tabOrder: ['graph'] }] + model.workspaces.w!.groupLayout = { type: 'leaf', groupId: 'g2' } + const opened = applyClient( { type: 'openEditorTab', workspace: 'w', @@ -189,46 +314,299 @@ it('opens files into the canonical group when the projected workspace is empty o tabId: 'file', groupId }, - original + model ) - if (command.type !== 'openEditorTab') { - throw new Error('Expected an editor open command') - } - const applied = applyLayoutCommand(canonical, command, { - mintId: () => 'id', - mintLeafId: () => 'leaf', - now: () => 0 - }) - expect(applied.ok).toBe(true) - if (applied.ok) { - expect(applied.model.workspaces.w.groups).toEqual([{ id: 'g2', tabOrder: ['graph', 'file'] }]) - } + expect(opened.ok && opened.model.workspaces.w!.groups).toEqual([ + { id: 'g2', tabOrder: ['graph', 'file'] } + ]) + const split = applyClient( + { + type: 'openEditorTab', + workspace: 'w', + contentType: 'editor', + fileId: '/file', + tabId: 'file', + groupId: 'new-group', + split: { besideGroupId: 'older-root', direction: 'right' } + }, + model + ) + expect(split.ok && split.model.workspaces.w!.groups).toEqual([ + { id: 'g2', tabOrder: ['graph'] }, + { id: 'new-group', tabOrder: ['file'] } + ]) + } +) + +it('uses visible groups for implicit opens and refuses stale split anchors', () => { + const model = canonical() + model.workspaces.w!.groups = [ + { id: 'hidden', tabOrder: ['graph'] }, + { id: 'g1', tabOrder: ['a', 'b', 'c'] } + ] + const implicit = applyClient( + { type: 'openEditorTab', workspace: 'w', contentType: 'editor', fileId: '/new', tabId: 'new' }, + model + ) + expect(implicit.ok && implicit.model.workspaces.w!.groups).toEqual([ + { id: 'hidden', tabOrder: ['graph'] }, + { id: 'g1', tabOrder: ['a', 'b', 'c', 'new'] } + ]) + const defaults = applyClient( + { type: 'applyDefaultTabs', workspace: 'w', tabs: [{ tabId: 'default', leafId: 'leaf' }] }, + model + ) + expect(defaults.ok && defaults.model.workspaces.w!.groups).toEqual([ + { id: 'hidden', tabOrder: ['graph'] }, + { id: 'g1', tabOrder: ['a', 'b', 'c', 'default'] } + ]) + expect(defaults.ok && defaults.effects).toEqual({ + stopPtyIds: [], + startPaneKeys: ['default:leaf'] + }) + expect( + applyClient( + { + type: 'openEditorTab', + workspace: 'w', + contentType: 'editor', + fileId: '/new', + tabId: 'new', + groupId: 'proposed', + split: { besideGroupId: 'stale', direction: 'right' } + }, + model + ) + ).toEqual({ ok: false, code: 'group_not_found' }) +}) + +it('translates split paths and identities together while retaining hidden branches', () => { + const model = canonical() + const workspace = model.workspaces.w! + workspace.groups = [ + { id: 'hidden', tabOrder: ['graph'] }, + { id: 'g1', tabOrder: ['a', 'b'] }, + { id: 'g2', tabOrder: ['c'] } + ] + workspace.groupLayout = { + type: 'split', + direction: 'vertical', + ratio: 0.2, + first: { type: 'leaf', groupId: 'hidden' }, + second: workspace.groupLayout! } - const split = translateGitGraphLayoutCommand( + const resized = applyClient( { - type: 'openEditorTab', + type: 'setGroupRatios', workspace: 'w', - contentType: 'editor', - fileId: '/file', - tabId: 'file', - groupId: 'new-group', - split: { besideGroupId: 'older-client-group', direction: 'right' } + ratios: [ + { path: '', ratio: 0.7, split: { direction: 'horizontal', first: 'g1', second: 'g2' } } + ] }, - original + model ) - if (split.type !== 'openEditorTab') { - throw new Error('Expected an editor open command') + expect(resized.ok && resized.model.workspaces.w!.groupLayout).toEqual({ + ...workspace.groupLayout, + second: { ...layout().groupLayout, ratio: 0.7 } + }) + workspace.groupLayout = { + type: 'split', + direction: 'horizontal', + ratio: 0.3, + first: { + type: 'split', + direction: 'vertical', + ratio: 0.2, + first: { type: 'leaf', groupId: 'hidden' }, + second: { type: 'leaf', groupId: 'g1' } + }, + second: { type: 'leaf', groupId: 'g2' } } - const opened = applyLayoutCommand(canonical, split, { - mintId: () => 'id', - mintLeafId: () => 'leaf', - now: () => 0 + const identities = applyClient( + { + type: 'setGroupRatios', + workspace: 'w', + ratios: [ + { path: '', ratio: 0.7, split: { direction: 'horizontal', first: 'g1', second: 'g2' } } + ] + }, + model + ) + expect(identities.ok && identities.model.workspaces.w!.groupLayout).toEqual({ + ...workspace.groupLayout, + ratio: 0.7 }) - expect(opened.ok).toBe(true) - if (opened.ok) { - expect(opened.model.workspaces.w.groups).toEqual([ - { id: 'g2', tabOrder: ['graph'] }, - { id: 'new-group', tabOrder: ['file'] } - ]) + expect( + applyClient( + { + type: 'setGroupRatios', + workspace: 'w', + ratios: [ + { path: '', ratio: 0.7, split: { direction: 'vertical', first: 'stale', second: 'g2' } } + ] + }, + model + ) + ).toEqual({ ok: false, code: 'group_set_changed' }) +}) + +it('splits a lone visible tab without moving its hidden sibling and refuses splitting it off itself', () => { + const model = canonical() + model.workspaces.w!.groups = [ + { id: 'g1', tabOrder: ['a', 'graph'] }, + { id: 'g2', tabOrder: ['b', 'c'] } + ] + expect( + applyClient( + { type: 'splitGroup', workspace: 'w', tabId: 'a', besideGroupId: 'g1', direction: 'right' }, + model + ) + ).toEqual({ ok: false, code: 'invalid_params' }) + const split = applyClient( + { type: 'splitGroup', workspace: 'w', tabId: 'a', besideGroupId: 'g2', direction: 'right' }, + model + ) + expect(split.ok && split.model.workspaces.w!.groups).toEqual([ + { id: 'g1', tabOrder: ['graph'] }, + { id: 'g2', tabOrder: ['b', 'c'] }, + { id: 'minted', tabOrder: ['a'] } + ]) +}) + +it('keeps identity commands addressed by stable tab ids', () => { + const renamed = applyClient({ + type: 'renameTab', + workspace: 'w', + tabId: 'b', + kind: 'custom', + title: 'Renamed' + }) + expect( + renamed.ok && renamed.model.workspaces.w!.tabs.find((tab) => tab.id === 'b')?.customTitle + ).toBe('Renamed') + const closed = applyClient({ type: 'closeTabs', workspace: 'w', tabIds: ['a', 'b'] }) + expect(closed.ok && closed.model.workspaces.w!.groups).toEqual([ + { id: 'g1', tabOrder: ['graph'] }, + { id: 'g2', tabOrder: ['c'] } + ]) +}) + +it('places a detached pane at a visible gap and leaves the hidden graph untouched', () => { + const model = canonical() + const workspace = model.workspaces.w! + workspace.tabs = workspace.tabs.filter((tab) => tab.id !== 'c') + workspace.tabs.push({ + id: 'c', + entityId: 'c', + kind: 'terminal', + createdAt: 0, + customTitle: null, + color: null, + terminal: { defaultTitle: 'Terminal 1' }, + panes: { + root: { + type: 'split', + direction: 'vertical', + first: { type: 'leaf', leafId: 'one' }, + second: { type: 'leaf', leafId: 'two' } + } + } + }) + const detached = applyClient( + { + type: 'movePaneToNewTab', + workspace: 'w', + tabId: 'c', + leafId: 'one', + groupId: 'g1', + index: 1 + }, + model + ) + expect(detached.ok && detached.model.workspaces.w!.groups).toEqual([ + { id: 'g1', tabOrder: ['a', 'graph', 'minted', 'b'] }, + { id: 'g2', tabOrder: ['c'] } + ]) + expect(detached.ok && detached.effects).toEqual({ stopPtyIds: [], startPaneKeys: [] }) + const implicit = applyClient( + { type: 'movePaneToNewTab', workspace: 'w', tabId: 'c', leafId: 'one' }, + model + ) + expect(implicit.ok && implicit.model.workspaces.w!.groups).toEqual([ + { id: 'g1', tabOrder: ['a', 'graph', 'b'] }, + { id: 'g2', tabOrder: ['c', 'minted'] } + ]) +}) + +it('projects graph add/remove around binding-only deltas without losing visible updates', () => { + const original = layout() + original.tabs = original.tabs.map((tab) => + tab.id === 'c' + ? { + ...tab, + kind: 'terminal', + terminal: { + defaultTitle: 'Terminal 1', + root: { type: 'leaf', leafId: 'one' }, + panes: [{ leafId: 'one', ptyId: 'initial' }] + } + } + : tab + ) + const graphFree = { + ...original, + tabs: original.tabs.filter((tab) => tab.id !== 'graph'), + groups: [ + { id: 'g1', tabIds: ['a', 'b'] }, + { id: 'g2', tabIds: ['c'] } + ] + } + const project = createGitGraphFrameProjection() + project({ type: 'workspace', key: 'w', seq: 1, layout: graphFree }) + const binding = { + key: 'w', + change: 'records' as const, + bindings: { set: [{ leafId: 'one', ptyId: 'pty' }] } } + const before = project({ type: 'records', epoch: 'e', seq: 2, workspaces: [binding] }) + expect(before.type === 'records' && before.workspaces[0]).toBe(binding) + const added = project({ + type: 'records', + epoch: 'e', + seq: 3, + workspaces: [ + diffPublishedLayouts( + 'w', + indexPublishedLayout(graphFree), + indexPublishedLayout(original), + original + )! + ] + }) + expect(added).toMatchObject({ workspaces: [] }) + const whileHidden = project({ + type: 'records', + epoch: 'e', + seq: 4, + workspaces: [{ ...binding, bindings: { set: [{ leafId: 'one', ptyId: 'next' }] } }] + }) + expect(whileHidden).toMatchObject({ + workspaces: [{ key: 'w', bindings: { set: [{ leafId: 'one', ptyId: 'next' }] } }] + }) + const removed = project({ + type: 'records', + epoch: 'e', + seq: 5, + workspaces: [ + diffPublishedLayouts( + 'w', + indexPublishedLayout(original), + indexPublishedLayout(graphFree), + graphFree + )! + ] + }) + expect(removed).toMatchObject({ workspaces: [] }) + const after = project({ type: 'records', epoch: 'e', seq: 6, workspaces: [binding] }) + expect(after.type === 'records' && after.workspaces[0]).toBe(binding) }) diff --git a/src/main/runtime/rpc/git-graph-layout-projection.ts b/src/main/runtime/rpc/git-graph-layout-projection.ts index c7b3f5ef6fce..4d4eaa45273a 100644 --- a/src/main/runtime/rpc/git-graph-layout-projection.ts +++ b/src/main/runtime/rpc/git-graph-layout-projection.ts @@ -1,5 +1,5 @@ import { GIT_GRAPH_TAB_CAPABILITY } from '../../../shared/source-control/runtime/git-graph-capabilities' -import type { TabGroupLayoutNode } from '../../../shared/tab-types' +import { visibleGroupTree } from '../../../shared/workspace-layout/workspace-layout-client-visibility' import type { PublishedWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-published' import { applyPublishedLayoutRecordChanges, @@ -10,67 +10,10 @@ import { indexPublishedLayout } from '../../../shared/workspace-layout/workspace-layout-records' import type { WorkspaceLayoutStreamFrame } from '../../../shared/workspace-layout/workspace-layout-stream-frames' -import type { WindowLayoutCommand } from '../terminal/layout/runtime-layout-apply' -import { - changedSplitRatios, - splitRatioIntentAt, - withGroupSplitRatios -} from '../../../shared/workspace-layout/split-ratio-intents' - -export const GIT_GRAPH_PLACEMENT_COMMANDS = new Set([ - 'moveTab', - 'setGroupRatios', - 'createTerminalTab', - 'openEditorTab', - 'openSimulatorTab', - 'openBrowserTab', - 'openAgentSessionTab', - 'movePaneToNewTab', - 'moveTabToWorkspace' -]) - export function readsGitGraph(capabilities?: readonly string[]): boolean { return capabilities?.includes(GIT_GRAPH_TAB_CAPABILITY) === true } -function projectedTree( - node: TabGroupLayoutNode | undefined, - groups: Set, - paths?: Map, - fullPath = '', - path = '' -): TabGroupLayoutNode | undefined { - if (!node) { - return undefined - } - if (node.type === 'leaf') { - return groups.has(node.groupId) ? node : undefined - } - const join = (base: string, side: string) => (base ? `${base}.${side}` : side) - const has = (child: TabGroupLayoutNode): boolean => - child.type === 'leaf' ? groups.has(child.groupId) : has(child.first) || has(child.second) - const firstVisible = has(node.first) - const secondVisible = has(node.second) - if (!firstVisible) { - return projectedTree(node.second, groups, paths, join(fullPath, 'second'), path) - } - if (!secondVisible) { - return projectedTree(node.first, groups, paths, join(fullPath, 'first'), path) - } - paths?.set(path, fullPath) - return { - ...node, - first: projectedTree(node.first, groups, paths, join(fullPath, 'first'), join(path, 'first'))!, - second: projectedTree( - node.second, - groups, - paths, - join(fullPath, 'second'), - join(path, 'second') - )! - } -} - export function projectGitGraphLayout(layout: PublishedWorkspaceLayout): PublishedWorkspaceLayout { const hidden = new Set(layout.tabs.filter((tab) => tab.kind === 'git-graph').map((tab) => tab.id)) if (!hidden.size) { @@ -87,16 +30,30 @@ export function projectGitGraphLayout(layout: PublishedWorkspaceLayout): Publish tabs: layout.tabs.filter((tab) => !hidden.has(tab.id)), editorFiles: layout.editorFiles.filter((file) => !hiddenFiles.has(file.filePath)), groups, - groupLayout: projectedTree(layout.groupLayout, new Set(groups.map((group) => group.id))) + groupLayout: visibleGroupTree(layout.groupLayout, new Set(groups.map((group) => group.id))) } } // Re-diff whole projected layouts: a delta alone may omit the group a hidden tab made empty. export function createGitGraphFrameProjection() { + const presence = new WeakMap() + const hasGraph = (records: PublishedLayoutRecords | undefined): boolean => { + if (!records) { + return false + } + const cached = presence.get(records.tabs) + if (cached !== undefined) { + return cached + } + const found = records.tabs.some((tab) => tab.kind === 'git-graph') + presence.set(records.tabs, found) + return found + } const layouts = new Map() return (frame: WorkspaceLayoutStreamFrame): WorkspaceLayoutStreamFrame => { switch (frame.type) { case 'end': + layouts.clear() return frame case 'removed': layouts.delete(frame.key) @@ -127,11 +84,7 @@ export function createGitGraphFrameProjection() { ? splitPublishedLayout(change.layout) : applyPublishedLayoutRecordChanges(before!, change) layouts.set(change.key, after) - if ( - ![before, after].some((records) => - records?.tabs.some((tab) => tab.kind === 'git-graph') - ) - ) { + if (!hasGraph(before) && !hasGraph(after)) { return [change] } const projected = projectGitGraphLayout(joinPublishedLayout(after)) @@ -149,83 +102,3 @@ export function createGitGraphFrameProjection() { } } } - -export function translateGitGraphLayoutCommand( - command: WindowLayoutCommand, - layout: PublishedWorkspaceLayout -): WindowLayoutCommand { - const projected = projectGitGraphLayout(layout) - if (projected === layout) { - return command - } - if ( - command.type === 'createTerminalTab' || - command.type === 'openEditorTab' || - command.type === 'openSimulatorTab' || - command.type === 'openBrowserTab' || - command.type === 'openAgentSessionTab' || - command.type === 'movePaneToNewTab' || - command.type === 'moveTabToWorkspace' - ) { - const canonicalGroupId = projected.groups[0]?.id ?? layout.groups[0]?.id - if (canonicalGroupId && 'split' in command && command.split) { - const canonicalAnchor = (id: string) => - layout.groups.some((group) => group.id === id) ? id : canonicalGroupId - return { - ...command, - split: { - ...command.split, - besideGroupId: canonicalAnchor(command.split.besideGroupId), - ...(command.split.besideLastGroupId - ? { besideLastGroupId: canonicalAnchor(command.split.besideLastGroupId) } - : {}) - } - } - } - const groupId = 'groupId' in command ? command.groupId : undefined - if (canonicalGroupId && !projected.groups.some((group) => group.id === groupId)) { - return { ...command, groupId: canonicalGroupId } - } - } - - if (command.type === 'moveTab') { - const fullOrder = - layout.groups - .find((group) => group.id === command.toGroupId) - ?.tabIds.filter((id) => id !== command.tabId) ?? [] - const visible = new Set(projected.tabs.map((tab) => tab.id)) - const visibleOrder = fullOrder.filter((id) => visible.has(id)) - const after = command.afterTabId ? visibleOrder.indexOf(command.afterTabId) : -1 - const at = command.afterTabId === null ? 0 : after !== -1 ? after + 1 : command.index - const next = visibleOrder[at] - return { - ...command, - afterTabId: undefined, - index: next ? fullOrder.indexOf(next) : fullOrder.length - } - } - if (command.type === 'setGroupRatios') { - const paths = new Map() - projectedTree(layout.groupLayout, new Set(projected.groups.map((group) => group.id)), paths) - const ratios = - command.ratios ?? - (projected.groupLayout && command.groupLayout - ? changedSplitRatios(projected.groupLayout, command.groupLayout) - : []) - if (!projected.groupLayout || !withGroupSplitRatios(projected.groupLayout, ratios)) { - throw new Error('Layout split changed; refresh and try again') - } - return { - ...command, - groupLayout: undefined, - ratios: ratios.map(({ path, ratio }) => { - const translated = paths.get(path) - if (translated === undefined) { - throw new Error('Layout split changed; refresh and try again') - } - return splitRatioIntentAt(layout.groupLayout!, translated, ratio)! - }) - } - } - return command -} diff --git a/src/main/runtime/rpc/methods/workspace-layout-apply.test.ts b/src/main/runtime/rpc/methods/workspace-layout-apply.test.ts index 717fe1c1b398..e259797e08bc 100644 --- a/src/main/runtime/rpc/methods/workspace-layout-apply.test.ts +++ b/src/main/runtime/rpc/methods/workspace-layout-apply.test.ts @@ -4,7 +4,7 @@ import type { ExecutionHostId } from '../../../../shared/execution-host' import type { LayoutApplyOutcome } from '../../../../shared/workspace-layout/workspace-layout-command-types' import type { Tab } from '../../../../shared/tab-types' import type { RuntimeStore } from '../../runtime-store-contract' -import { RUNTIME_CAPABILITIES } from '../../../../shared/protocol-version' +import { withoutGitGraph } from '../../../../shared/workspace-layout/workspace-layout-client-visibility' import { MOBILE_RPC_METHOD_ALLOWLIST } from '../server/runtime-rpc-mobile-method-allowlist' import { OrcaRuntimeService } from '../../orca-runtime' import { eraseRpcMethods, isStreamingMethod, type RpcContext } from '../core' @@ -90,7 +90,6 @@ describe('layout.apply', () => { for (const name of ['layout.apply', 'layout.reopenHeldPanes', 'layout.reportView']) { expect(names, name).not.toContain(name) } - expect(RUNTIME_CAPABILITIES.some((capability) => capability.startsWith('layout'))).toBe(false) expect(MOBILE_RPC_METHOD_ALLOWLIST.has('layout.apply')).toBe(false) }) @@ -110,7 +109,10 @@ describe('layout.apply', () => { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handler reads only runtime from its context. await apply.handler(params, { runtime } as RpcContext) - expect(applyLayoutCommand).toHaveBeenCalledWith({ ...SPLIT, newLeafId }) + expect(applyLayoutCommand).toHaveBeenCalledWith( + { ...SPLIT, newLeafId }, + { visibility: withoutGitGraph } + ) expect(apply.params?.parse({ command: { ...SPLIT, id: 'window-id' } })).toEqual({ command: SPLIT }) diff --git a/src/main/runtime/rpc/methods/workspace-layout.ts b/src/main/runtime/rpc/methods/workspace-layout.ts index d3691fbf8ed3..9b1634f48cbb 100644 --- a/src/main/runtime/rpc/methods/workspace-layout.ts +++ b/src/main/runtime/rpc/methods/workspace-layout.ts @@ -1,9 +1,5 @@ -import { - readsGitGraph, - GIT_GRAPH_PLACEMENT_COMMANDS, - createGitGraphFrameProjection, - translateGitGraphLayoutCommand -} from '../git-graph-layout-projection' +import { withoutGitGraph } from '../../../../shared/workspace-layout/workspace-layout-client-visibility' +import { readsGitGraph, createGitGraphFrameProjection } from '../git-graph-layout-projection' // Paired desktops use layout read/stream/apply only when the server offers layout.intents.v1; mobile is excluded. import { @@ -106,21 +102,9 @@ export const LAYOUT_APPLY_METHODS = [ permission: 'workspace', params: LayoutApplyParams, handler: async (params, { runtime, clientCapabilities }) => { - const command = params.command - if ( - readsGitGraph(clientCapabilities) || - !GIT_GRAPH_PLACEMENT_COMMANDS.has(command.type) || - !('workspace' in command) - ) { - return runtime.applyLayoutCommand(command) - } - const { snapshot, unsubscribe } = runtime.subscribeWorkspaceLayouts(() => {}) - unsubscribe() - const workspace = - command.type === 'moveTabToWorkspace' ? command.toWorkspace : command.workspace - const layout = snapshot.find((entry) => entry.key === workspace)?.layout return runtime.applyLayoutCommand( - layout ? translateGitGraphLayoutCommand(params.command, layout) : params.command + params.command, + readsGitGraph(clientCapabilities) ? undefined : { visibility: withoutGitGraph } ) } }), diff --git a/src/main/runtime/terminal/layout/runtime-layout-apply.ts b/src/main/runtime/terminal/layout/runtime-layout-apply.ts index 1eea06ee9a27..5427c6da54e7 100644 --- a/src/main/runtime/terminal/layout/runtime-layout-apply.ts +++ b/src/main/runtime/terminal/layout/runtime-layout-apply.ts @@ -52,7 +52,7 @@ export async function applyWindowLayoutCommand( return { ok: false, code: 'wsl_move_in_progress' } } if (command.type === 'moveTabToWorkspace') { - return moveTabToWorkspace(store, hostIdsFor, command) + return moveTabToWorkspace(store, hostIdsFor, command, run) } if (command.type === 'renameEditorFiles' && command.alsoIn) { return renameEditorFilesInWorkspaces(store, hostIdsFor, command) @@ -187,7 +187,8 @@ async function renameTabs( async function moveTabToWorkspace( store: RuntimeStore, hostIdsFor: (worktreeId: string, tabId: string | null) => ExecutionHostId[], - command: CommandOf<'moveTabToWorkspace'> + command: CommandOf<'moveTabToWorkspace'>, + run?: LayoutCommandRunOptions ): Promise { const [from] = hostIdsFor(command.workspace, null) const [to] = hostIdsFor(command.toWorkspace, null) @@ -202,12 +203,16 @@ async function moveTabToWorkspace( if (!store.moveTabToWorkspaceAcrossPartitions) { throw new Error('layout_store_unavailable') } - return store.moveTabToWorkspaceAcrossPartitions(command, from, to) + return run + ? store.moveTabToWorkspaceAcrossPartitions(command, from, to, run) + : store.moveTabToWorkspaceAcrossPartitions(command, from, to) } if (!store.applyLayoutCommand) { throw new Error('layout_store_unavailable') } - return store.applyLayoutCommand(command, [from]) + return run + ? store.applyLayoutCommand(command, [from], run) + : store.applyLayoutCommand(command, [from]) } /** Rename disk-move paths across partitions in one durable write; paired-server ownership refuses the whole operation. */ diff --git a/src/shared/workspace-layout/workspace-layout-client-command.ts b/src/shared/workspace-layout/workspace-layout-client-command.ts new file mode 100644 index 000000000000..93844ab2639e --- /dev/null +++ b/src/shared/workspace-layout/workspace-layout-client-command.ts @@ -0,0 +1,177 @@ +import type { TabGroupLayoutNode } from '../tab-types' +import { changedSplitRatios, splitRatioIntentAt, withGroupSplitRatios } from './split-ratio-intents' +import type { CommandOf, LayoutCommand, RenameTabsCommand } from './workspace-layout-command-types' +import { + visibleGroupTree, + visibleLayoutGroups, + type LayoutClientVisibility +} from './workspace-layout-client-visibility' +import type { WorkspaceLayout, WorkspaceLayoutModel } from './workspace-layout-model' + +type GroupPlacement = { + groupId?: string + split?: { besideGroupId: string; besideLastGroupId?: string } +} + +function placement( + workspace: WorkspaceLayout | undefined, + command: C, + visible: LayoutClientVisibility +): C { + if (!workspace || workspace.tabs.every(visible)) { + return command + } + const empty = !workspace.tabs.some(visible) + const groups = visibleLayoutGroups(workspace, visible) + const first = groups[0] ?? workspace.groups[0] + if (!first) { + return command + } + if (command.split) { + // Only an emptied projected root may stand in for a missing split anchor. + if (!empty) { + return command + } + const anchor = (id: string) => + workspace.groups.some((group) => group.id === id) ? id : first.id + return { + ...command, + split: { + ...command.split, + besideGroupId: anchor(command.split.besideGroupId), + ...(command.split.besideLastGroupId + ? { besideLastGroupId: anchor(command.split.besideLastGroupId) } + : {}) + } + } + } + if (command.groupId && workspace.groups.some((group) => group.id === command.groupId)) { + return command + } + // Unknown groups still refuse when the client has a nonempty layout. + return command.groupId && !empty ? command : { ...command, groupId: first.id } +} + +function sameGroupTree(left: TabGroupLayoutNode, right: TabGroupLayoutNode): boolean { + return left.type === 'leaf' || right.type === 'leaf' + ? left.type === 'leaf' && right.type === 'leaf' && left.groupId === right.groupId + : left.direction === right.direction && + sameGroupTree(left.first, right.first) && + sameGroupTree(left.second, right.second) +} + +function ratios( + workspace: WorkspaceLayout | undefined, + command: CommandOf<'setGroupRatios'>, + visible: LayoutClientVisibility +): CommandOf<'setGroupRatios'> { + if (!workspace || workspace.tabs.every(visible)) { + return command + } + const paths = new Map() + const current = + workspace?.groupLayout ?? + (workspace?.groups[0] && { type: 'leaf' as const, groupId: workspace.groups[0].id }) + const tree = visibleGroupTree( + current, + new Set(workspace ? visibleLayoutGroups(workspace, visible).map((group) => group.id) : []), + paths + ) + const changes = + command.ratios ?? + (tree && command.groupLayout && sameGroupTree(tree, command.groupLayout) + ? changedSplitRatios(tree, command.groupLayout) + : undefined) + if (!tree || !changes || !withGroupSplitRatios(tree, changes)) { + return { ...command, groupLayout: undefined, ratios: undefined } + } + const translated = changes.flatMap(({ path, ratio }) => { + const canonical = paths.get(path) + const intent = canonical === undefined ? null : splitRatioIntentAt(current!, canonical, ratio) + return intent ? [intent] : [] + }) + return translated.length === changes.length + ? { ...command, groupLayout: undefined, ratios: translated } + : { ...command, groupLayout: undefined, ratios: undefined } +} + +export function clientLayoutCommand( + model: WorkspaceLayoutModel, + command: LayoutCommand, + visible?: LayoutClientVisibility +): LayoutCommand +export function clientLayoutCommand( + model: WorkspaceLayoutModel, + command: LayoutCommand | RenameTabsCommand, + visible?: LayoutClientVisibility +): LayoutCommand | RenameTabsCommand +/** Classify every command; coordinates are resolved only against the model being mutated. */ +export function clientLayoutCommand( + model: WorkspaceLayoutModel, + command: LayoutCommand | RenameTabsCommand, + visible?: LayoutClientVisibility +): LayoutCommand | RenameTabsCommand { + if (!visible) { + return command + } + switch (command.type) { + case 'createTerminalTab': + case 'openEditorTab': + case 'openSimulatorTab': + case 'openBrowserTab': + case 'openAgentSessionTab': + return placement(model.workspaces[command.workspace], command, visible) + case 'movePaneToNewTab': { + const workspace = model.workspaces[command.workspace] + const groupId = + command.groupId ?? + workspace?.groups.find((group) => group.tabOrder.includes(command.tabId))?.id + return placement(workspace, { ...command, groupId }, visible) + } + case 'moveTabToWorkspace': + return placement(model.workspaces[command.toWorkspace], command, visible) + case 'moveTab': { + const resolved = placement( + model.workspaces[command.workspace], + { groupId: command.toGroupId }, + visible + ) + return { ...command, toGroupId: resolved.groupId! } + } + case 'setGroupRatios': + return ratios(model.workspaces[command.workspace], command, visible) + case 'splitGroup': + // The primitive evaluates visible cardinality without moving hidden siblings. + return command + case 'renameTabs': + case 'splitPane': + case 'closePane': + case 'closeTabs': + case 'setPaneRatios': + case 'movePane': + case 'equalizePanes': + case 'renameTab': + case 'renamePane': + case 'setPaneGrid': + case 'releasePaneTerminal': + case 'setTabProps': + case 'setChatPane': + case 'promotePreviewTab': + case 'renameEditorFiles': + case 'openBrowserPage': + case 'closeBrowserPage': + case 'replaceBrowserPage': + case 'setBrowserTabProfile': + case 'startPane': + case 'restartPane': + case 'sleep': + case 'wake': + case 'setDefaultTabsApplied': + case 'applyDefaultTabs': + return command + default: { + const exhaustive: never = command + return exhaustive + } + } +} diff --git a/src/shared/workspace-layout/workspace-layout-client-visibility.ts b/src/shared/workspace-layout/workspace-layout-client-visibility.ts new file mode 100644 index 000000000000..932ca27cb557 --- /dev/null +++ b/src/shared/workspace-layout/workspace-layout-client-visibility.ts @@ -0,0 +1,74 @@ +import type { TabGroupLayoutNode } from '../tab-types' +import type { LayoutTab, WorkspaceLayout } from './workspace-layout-model' + +export type LayoutClientVisibility = (tab: Pick) => boolean + +export const withoutGitGraph: LayoutClientVisibility = (tab) => tab.kind !== 'git-graph' + +export function visibleLayoutGroups(workspace: WorkspaceLayout, visible: LayoutClientVisibility) { + const ids = new Set(workspace.tabs.filter(visible).map((tab) => tab.id)) + return workspace.groups.filter( + (group) => !group.tabOrder.length || group.tabOrder.some((id) => ids.has(id)) + ) +} + +/** A visible gap is before its next visible neighbor, or at the canonical end. */ +export function canonicalTabGap( + order: readonly string[], + tabs: readonly LayoutTab[], + index: number, + visible?: LayoutClientVisibility, + replacingTabId?: string +): number { + if (!visible) { + return Math.max(0, Math.min(index, order.length)) + } + const ids = new Set(tabs.filter(visible).map((tab) => tab.id)) + const shown = order.filter((id) => id !== replacingTabId && ids.has(id)) + const next = shown[Math.max(0, Math.min(index, shown.length))] + return next === undefined ? order.length : order.indexOf(next) +} + +export function visibleGroupTree( + node: TabGroupLayoutNode | undefined, + groups: ReadonlySet, + paths?: Map, + fullPath = '', + path = '' +): TabGroupLayoutNode | undefined { + if (!node) { + return undefined + } + if (node.type === 'leaf') { + return groups.has(node.groupId) ? node : undefined + } + const join = (base: string, side: string) => (base ? `${base}.${side}` : side) + const has = (child: TabGroupLayoutNode): boolean => + child.type === 'leaf' ? groups.has(child.groupId) : has(child.first) || has(child.second) + const firstVisible = has(node.first) + const secondVisible = has(node.second) + if (!firstVisible) { + return visibleGroupTree(node.second, groups, paths, join(fullPath, 'second'), path) + } + if (!secondVisible) { + return visibleGroupTree(node.first, groups, paths, join(fullPath, 'first'), path) + } + paths?.set(path, fullPath) + return { + ...node, + first: visibleGroupTree( + node.first, + groups, + paths, + join(fullPath, 'first'), + join(path, 'first') + )!, + second: visibleGroupTree( + node.second, + groups, + paths, + join(fullPath, 'second'), + join(path, 'second') + )! + } +} diff --git a/src/shared/workspace-layout/workspace-layout-command-steps.ts b/src/shared/workspace-layout/workspace-layout-command-steps.ts index bea63ecf23c3..32beec09befb 100644 --- a/src/shared/workspace-layout/workspace-layout-command-steps.ts +++ b/src/shared/workspace-layout/workspace-layout-command-steps.ts @@ -1,3 +1,4 @@ +import { canonicalTabGap, visibleLayoutGroups } from './workspace-layout-client-visibility' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../layout-owner-switch' import { insertTabIdIntoOrder } from './tab-order' import { collectLayoutLeafIdsInOrder } from './terminal-pane-tree' @@ -125,7 +126,8 @@ export function placeNewTab( key: string, tab: LayoutTab, placement: TabPlacement, - context: LayoutContext + context: LayoutContext, + replacingTabId?: string ): WorkspaceLayout { const tabs = [...workspace.tabs, tab] const anchorGroup = placement.afterTabId @@ -134,6 +136,7 @@ export function placeNewTab( let group = workspace.groups.find((entry) => entry.id === placement.groupId) ?? anchorGroup ?? + (context.visibility ? visibleLayoutGroups(workspace, context.visibility)[0] : undefined) ?? workspace.groups[0] const groups = [...workspace.groups] if (!group) { @@ -143,10 +146,38 @@ export function placeNewTab( let tabOrder: string[] if (placement.index !== undefined) { tabOrder = group.tabOrder.filter((id) => id !== tab.id) - tabOrder.splice(Math.max(0, Math.min(placement.index, tabOrder.length)), 0, tab.id) + tabOrder.splice( + canonicalTabGap( + tabOrder, + workspace.tabs, + placement.index, + context.visibility, + replacingTabId + ), + 0, + tab.id + ) } else { const anchor = anchorGroup === group ? placement.afterTabId : undefined - tabOrder = insertTabIdIntoOrder(group.tabOrder, tabs, tab.id, tab.isPinned === true, anchor) + if (context.visibility) { + const visibleIds = new Set(workspace.tabs.filter(context.visibility).map((entry) => entry.id)) + const shown = group.tabOrder.filter((id) => id !== replacingTabId && visibleIds.has(id)) + const inserted = insertTabIdIntoOrder(shown, tabs, tab.id, tab.isPinned === true, anchor) + tabOrder = [...group.tabOrder] + tabOrder.splice( + canonicalTabGap( + tabOrder, + workspace.tabs, + inserted.indexOf(tab.id), + context.visibility, + replacingTabId + ), + 0, + tab.id + ) + } else { + tabOrder = insertTabIdIntoOrder(group.tabOrder, tabs, tab.id, tab.isPinned === true, anchor) + } } const placed = { ...group, tabOrder } return { diff --git a/src/shared/workspace-layout/workspace-layout-command-types.ts b/src/shared/workspace-layout/workspace-layout-command-types.ts index 4133ab37c816..5df293020ab2 100644 --- a/src/shared/workspace-layout/workspace-layout-command-types.ts +++ b/src/shared/workspace-layout/workspace-layout-command-types.ts @@ -1,5 +1,6 @@ // Pure commands change layout only; runtime owns catalog/path/host-support/liveness refusals requiring external facts. +import type { LayoutClientVisibility } from './workspace-layout-client-visibility' import type { LiveTerminalAdoption } from './workspace-layout-terminal-adoption' import type { SleepingAgentSessionRecord } from '../agent-session/lifecycle/agent-session-resume' import type { AgentType } from '../agent-status/contracts/agent-status-types' @@ -363,6 +364,7 @@ export type LayoutApplyReply = ( ) & { frameSeq?: number } export type LayoutContext = { + visibility?: LayoutClientVisibility mintId: () => string /** Pane ids must be UUIDs (pane keys and PTY env carry them). */ mintLeafId: () => string diff --git a/src/shared/workspace-layout/workspace-layout-commands.ts b/src/shared/workspace-layout/workspace-layout-commands.ts index b32295ae4417..3d4f1e8d72c3 100644 --- a/src/shared/workspace-layout/workspace-layout-commands.ts +++ b/src/shared/workspace-layout/workspace-layout-commands.ts @@ -1,5 +1,6 @@ // Apply pure layout commands synchronously so runtime arrival order remains authoritative. +import { clientLayoutCommand } from './workspace-layout-client-command' import { closeBrowserPage, openBrowserPage, @@ -76,7 +77,11 @@ export function applyLayoutCommand( command: LayoutCommand, context: LayoutContext ): Applied { - const result = applyCommand(model, command, context) + const result = applyCommand( + model, + clientLayoutCommand(model, command, context.visibility), + context + ) if (!result.ok) { return result } @@ -119,7 +124,7 @@ function applyCommand( case 'closeTabs': return closeTabs(model, command, context) case 'moveTab': - return moveTab(model, command) + return moveTab(model, command, context) case 'splitGroup': return splitGroup(model, command, context) case 'setGroupRatios': diff --git a/src/shared/workspace-layout/workspace-layout-content-commands.ts b/src/shared/workspace-layout/workspace-layout-content-commands.ts index 886770fb1f22..688263b050ba 100644 --- a/src/shared/workspace-layout/workspace-layout-content-commands.ts +++ b/src/shared/workspace-layout/workspace-layout-content-commands.ts @@ -204,7 +204,10 @@ export function openAgentSessionTab( command: CommandOf<'openAgentSessionTab'>, context: LayoutContext ): Applied { - if (command.initial && !admitsInitialSurface(model, command.workspace, command.initial)) { + if ( + command.initial && + !admitsInitialSurface(model, command.workspace, command.initial, context.visibility) + ) { return applied(model) } const drawn = drawnTabOpen( diff --git a/src/shared/workspace-layout/workspace-layout-group-commands.ts b/src/shared/workspace-layout/workspace-layout-group-commands.ts index 3dfbf2ed4ba7..3c925a829da2 100644 --- a/src/shared/workspace-layout/workspace-layout-group-commands.ts +++ b/src/shared/workspace-layout/workspace-layout-group-commands.ts @@ -1,5 +1,6 @@ // Share headless group moves with the runtime. Create each split group with its tab atomically; empty groups never persist. +import { canonicalTabGap } from './workspace-layout-client-visibility' import type { TabGroupLayoutNode } from '../tab-types' import { buildHeadlessTabGroupMove, buildHeadlessTabGroupSplit } from './tab-group-moves' import { moveGroupLeafBeside, moveGroupLeafBesideBranch } from './tab-group-layout-tree' @@ -31,7 +32,11 @@ function anchoredMoveIndex(targetOrder: readonly string[], command: CommandOf<'m return at === -1 ? command.index : at + 1 } -export function moveTab(model: WorkspaceLayoutModel, command: CommandOf<'moveTab'>): Applied { +export function moveTab( + model: WorkspaceLayoutModel, + command: CommandOf<'moveTab'>, + context: LayoutContext +): Applied { const workspace = model.workspaces[command.workspace]! const source = sourceGroupOf(workspace, command.tabId) if (!source) { @@ -41,9 +46,16 @@ export function moveTab(model: WorkspaceLayoutModel, command: CommandOf<'moveTab if (!target) { return refuse('group_not_found') } - const index = anchoredMoveIndex( - target.tabOrder.filter((id) => id !== command.tabId), - command + const order = target.tabOrder.filter((id) => id !== command.tabId) + const visibleIds = context.visibility + ? new Set(workspace.tabs.filter(context.visibility).map((tab) => tab.id)) + : undefined + const shown = visibleIds ? order.filter((id) => visibleIds.has(id)) : order + const index = canonicalTabGap( + order, + workspace.tabs, + anchoredMoveIndex(shown, command), + context.visibility ) if (source.id === command.toGroupId) { const tabOrder = source.tabOrder.filter((id) => id !== command.tabId) @@ -106,6 +118,12 @@ export function splitGroup( if (!workspace.groups.some((group) => group.id === command.besideGroupId)) { return refuse('group_not_found') } + if (context.visibility && source.id === command.besideGroupId) { + const visibleIds = new Set(workspace.tabs.filter(context.visibility).map((tab) => tab.id)) + if (source.tabOrder.filter((id) => visibleIds.has(id)).length === 1) { + return refuse('invalid_params') + } + } if (source.tabOrder.length === 1 && source.id !== command.besideGroupId) { // Moving a group’s sole tab beside another group preserves the source group ID. const groupLayout = moveGroupLeafBeside( diff --git a/src/shared/workspace-layout/workspace-layout-initial-surface.ts b/src/shared/workspace-layout/workspace-layout-initial-surface.ts index aab2faa906cd..070a3ae51b34 100644 --- a/src/shared/workspace-layout/workspace-layout-initial-surface.ts +++ b/src/shared/workspace-layout/workspace-layout-initial-surface.ts @@ -1,15 +1,17 @@ // Share initial-surface admission so concurrent window/runtime requests create one tab. +import type { LayoutClientVisibility } from './workspace-layout-client-visibility' import type { InitialSurfaceReason } from './workspace-layout-command-types' import type { WorkspaceLayoutModel } from './workspace-layout-model' -/** Require no tabs of any kind. On relaunch, a saved empty terminal row means closed; an entry for a workspace that never had terminals does not. */ +/** Require no client-visible tabs. On relaunch, a saved empty terminal row means closed; an entry for a workspace that never had terminals does not. */ export function admitsInitialSurface( model: WorkspaceLayoutModel, workspaceKey: string, - reason: InitialSurfaceReason + reason: InitialSurfaceReason, + visible?: LayoutClientVisibility ): boolean { - if ((model.workspaces[workspaceKey]?.tabs.length ?? 0) > 0) { + if (model.workspaces[workspaceKey]?.tabs.some((tab) => !visible || visible(tab))) { return false } return reason === 'activation' || !model.legacy.terminalRowOwners[workspaceKey] diff --git a/src/shared/workspace-layout/workspace-layout-tab-commands.ts b/src/shared/workspace-layout/workspace-layout-tab-commands.ts index 3fe5b48418c5..7f6a6a3a069b 100644 --- a/src/shared/workspace-layout/workspace-layout-tab-commands.ts +++ b/src/shared/workspace-layout/workspace-layout-tab-commands.ts @@ -42,7 +42,10 @@ export function createTerminalTab( command: CommandOf<'createTerminalTab'>, context: LayoutContext ): Applied { - if (command.initial && !admitsInitialSurface(model, command.workspace, command.initial)) { + if ( + command.initial && + !admitsInitialSurface(model, command.workspace, command.initial, context.visibility) + ) { return applied(model) } const held = command.adopt && appliedHeldAdoption(model, command.workspace, command.adopt) @@ -263,6 +266,7 @@ export function placeContentTab( ? workspace.tabs.find( (entry) => entry.isPreview && + (!context.visibility || context.visibility(entry)) && group?.tabOrder.includes(entry.id) && canReplacePreviewContentType(tab.kind, entry.kind) ) @@ -279,7 +283,8 @@ export function placeContentTab( afterTabId: placement.afterTabId, index: placement.index }, - context + context, + preview && !placement.dirtyTabIds?.includes(preview.id) ? preview.id : undefined ) ) if (!preview) { From 349dbd1efbecd11b27bd3bfe9b517ac51485ecfa Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 5 Nov 2026 23:17:24 -0800 Subject: [PATCH 13/52] Refine Git Graph picker and owner transitions Discard branch drafts on Escape or owner changes, follow updated tab ownership, and report workspace lookup failures for the current owner. Keep parent navigation queued behind pending history loads. --- .../editor/git-graph/git-graph-filter.tsx | 61 ++++++++----- .../git-graph/git-graph-history-controller.ts | 23 +++-- .../git-graph/git-graph-rendering.test.tsx | 90 +++++++++++++++++-- .../git-graph-workspace-navigation.ts | 19 ++-- src/renderer/src/i18n/locales/de.json | 1 + src/renderer/src/i18n/locales/en.json | 1 + src/renderer/src/i18n/locales/es.json | 1 + src/renderer/src/i18n/locales/fr.json | 1 + src/renderer/src/i18n/locales/ja.json | 1 + src/renderer/src/i18n/locales/ko.json | 1 + src/renderer/src/i18n/locales/pt.json | 1 + src/renderer/src/i18n/locales/ru.json | 1 + src/renderer/src/i18n/locales/tr.json | 1 + src/renderer/src/i18n/locales/zh-Hant.json | 1 + src/renderer/src/i18n/locales/zh.json | 1 + 15 files changed, 165 insertions(+), 39 deletions(-) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx b/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx index 5d8ac3b51635..931d32b5fad9 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef, useState } from 'react' +import { useEffect, useMemo, useRef, useState, type RefObject } from 'react' import { Button } from '@/components/ui/button' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Input } from '@/components/ui/input' @@ -14,22 +14,32 @@ import type { } from '../../../../../shared/git/history/git-history-types' import type { ExecutionHostId } from '../../../../../shared/execution-host' -export function GitGraphFilter({ - worktreeId, - executionHostId, - filter, - supported, - onChange -}: { +type GitGraphFilterProps = { worktreeId: string executionHostId?: ExecutionHostId filter: GitHistoryRefs supported: boolean | undefined onChange: (refs: GitHistoryRefs) => void -}) { - const requests = useRef<{ running: boolean; pending?: () => Promise }>({ running: false }) - const [open, setOpen] = useState(false) - const [draft, setDraft] = useState<{ owner: string; refs: GitHistoryRefs }>() +} +type RefRequests = { running: boolean; pending?: () => Promise } + +export function GitGraphFilter(props: GitGraphFilterProps) { + const requests = useRef({ running: false }) + const scope = useGitGraphScope(props.worktreeId, props.executionHostId) + const owner = JSON.stringify([props.worktreeId, scope?.route, scope?.worktree.path]) + return +} + +function GitGraphFilterForOwner({ + worktreeId, + executionHostId, + filter, + supported, + onChange, + owner, + requests +}: GitGraphFilterProps & { owner: string; requests: RefObject }) { + const [draft, setDraft] = useState() const [query, setQuery] = useState('') const [search, setSearch] = useState<{ owner: string @@ -38,10 +48,8 @@ export function GitGraphFilter({ error?: string }>() const [probe, setProbe] = useState<{ owner: string | undefined; capable: boolean | null }>() - const scope = useGitGraphScope(worktreeId, executionHostId) - const owner = JSON.stringify([worktreeId, scope?.route, scope?.worktree.path]) - const pickerOpen = open && draft?.owner === owner - const draftRefs = draft?.owner === owner ? draft.refs : filter + const pickerOpen = draft !== undefined + const draftRefs = draft ?? filter const refs = pickerOpen && search?.owner === owner && search.query === query ? (search.refs ?? []) : [] const error = @@ -125,13 +133,13 @@ export function GitGraphFilter({ queue.pending = undefined clearTimeout(timeout) } - }, [worktreeId, owner, query, pickerOpen, capable, executionHostId]) + }, [worktreeId, owner, query, pickerOpen, capable, executionHostId, requests]) const apply = (refs = draftRefs) => { const next = Array.isArray(refs) && !refs.length ? 'all' : refs - if (draft?.owner === owner && JSON.stringify(next) !== JSON.stringify(filter)) { + if (draft !== undefined && JSON.stringify(next) !== JSON.stringify(filter)) { onChange(next) } - setOpen(false) + setDraft(undefined) setSearch(undefined) } return ( @@ -140,8 +148,7 @@ export function GitGraphFilter({ open={pickerOpen} onOpenChange={(next) => { if (next) { - setDraft({ owner, refs: filter }) - setOpen(true) + setDraft(filter) } else { apply() } @@ -156,7 +163,15 @@ export function GitGraphFilter({ : translate('gitGraph.chosenBranches', 'Chosen branches')} - + { + event.preventDefault() + setDraft(undefined) + setSearch(undefined) + }} + >
))}
diff --git a/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx b/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx index 931d32b5fad9..bda613e2746a 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-filter.tsx @@ -164,7 +164,7 @@ function GitGraphFilterForOwner({ { event.preventDefault() @@ -172,41 +172,43 @@ function GitGraphFilterForOwner({ setSearch(undefined) }} > -
- - -
- setQuery(event.target.value)} - placeholder={translate('gitGraph.searchRefs', 'Search branches and tags')} - /> - {error &&

{error}

} -
- {refs.map((ref) => ( - - ))} +
+
+ + +
+ setQuery(event.target.value)} + placeholder={translate('gitGraph.searchRefs', 'Search branches and tags')} + /> + {error &&

{error}

} +
+ {refs.map((ref) => ( + + ))} +
diff --git a/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts b/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts index 44d83bf95aa4..a3dc716a3273 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts +++ b/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts @@ -118,7 +118,7 @@ export class GitGraphHistoryController { } private onRefresh = (event: Event): void => { - if ((event as CustomEvent).detail === this.worktreeId) { + if (event instanceof CustomEvent && event.detail === this.worktreeId) { this.invalidate() } } diff --git a/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx b/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx index 536524e72a85..6202da02d455 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx @@ -104,8 +104,10 @@ export function GitGraphRefs({ {open && ( - - {references.filter((ref) => !inline.includes(ref)).map(badge)} + +
+ {references.filter((ref) => !inline.includes(ref)).map(badge)} +
)} diff --git a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx index b185bc7c48e2..c42d61a66e50 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx @@ -38,13 +38,26 @@ document.body.appendChild(container) let root = createRoot(container) const initialState = useAppStore.getState() const workspaceId = 'r::/repo' -const local = { +const local: Worktree = { id: workspaceId, repoId: 'r', path: '/repo', branch: 'refs/heads/main', - hostId: 'local' -} as Worktree + hostId: 'local', + head: 'a', + isBare: false, + isMainWorktree: true, + displayName: 'repo', + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0 +} const repo: Repo = { id: 'r', path: '/repo', @@ -94,7 +107,7 @@ it('keeps view models on expand and resize, rebuilding when history changes', as await act(async () => root.render(render(result))) expect(build).toHaveBeenCalledTimes(1) await act(async () => - (container.querySelector('[data-testid="git-history-row"]') as HTMLButtonElement).click() + container.querySelector('[data-testid="git-history-row"]')!.click() ) await act(async () => container @@ -195,10 +208,13 @@ it.each(['local', 'ssh:A'] as const)( }) const cleanup = attachClosedEditorTabCleanup(useAppStore) const original = useAppStore.getState().openFiles - const file = { + const file: OpenFile = { id: `${workspaceId}::git-graph`, worktreeId: workspaceId, mode: 'git-graph', + relativePath: 'Git Graph', + language: 'plaintext', + isDirty: false, filePath: `${workspaceId}::git-graph`, operationProvenance: { ownershipProjection: 'explicit', @@ -207,7 +223,7 @@ it.each(['local', 'ssh:A'] as const)( runtimeEnvironmentId: null }) } - } as OpenFile + } useAppStore.setState({ openFiles: [...original, file] }) const render = () => ( diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/git-history-panel.tsx b/src/renderer/src/components/right-sidebar/source-control/sync/git-history-panel.tsx index 0089830db84d..18ec98bea4f4 100644 --- a/src/renderer/src/components/right-sidebar/source-control/sync/git-history-panel.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/sync/git-history-panel.tsx @@ -103,8 +103,11 @@ export function GitHistoryPanel({ setFilesByCommit( Object.fromEntries(Object.entries(filesByCommit).filter(([id]) => ids.has(id))) ) - loadedCommitsRef.current = new Set([...loadedCommitsRef.current].filter((id) => ids.has(id))) } + useEffect(() => { + const ids = new Set(result?.items.map((item) => item.id)) + loadedCommitsRef.current = new Set([...loadedCommitsRef.current].filter((id) => ids.has(id))) + }, [result]) const scrollRef = useRef(null) const virtualizer = useVirtualizer({ count: collapsed ? 0 : viewModels.length, From f1deb3e2f0d2c4c5347c25abdf623414bbbeac1a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 6 Nov 2026 01:06:25 -0800 Subject: [PATCH 16/52] Route Git Graph opening through the existing editor action Use workspace record selectors for stable owner inputs and remove two loading labels orphaned by the graph changes from all locale catalogs. --- src/renderer/src/i18n/locales/de.json | 2 - src/renderer/src/i18n/locales/en.json | 2 - src/renderer/src/i18n/locales/es.json | 2 - src/renderer/src/i18n/locales/fr.json | 2 - src/renderer/src/i18n/locales/ja.json | 2 - src/renderer/src/i18n/locales/ko.json | 2 - src/renderer/src/i18n/locales/pt.json | 2 - src/renderer/src/i18n/locales/ru.json | 2 - src/renderer/src/i18n/locales/tr.json | 2 - src/renderer/src/i18n/locales/zh-Hant.json | 2 - src/renderer/src/i18n/locales/zh.json | 2 - src/renderer/src/lib/git-graph-tab.ts | 49 +++++++++++----------- 12 files changed, 25 insertions(+), 46 deletions(-) diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 0ca8e6201c13..e12e6b057761 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -13504,7 +13504,6 @@ }, "GitHistoryPanel": { "cf7cad58d2": "Noch keine Commits", - "781a8bcf7b": "Graph wird geladen…", "d0fb0f4bf2": "Commits aktualisieren", "9f7535d22b": "Referenzen sind Branch- oder Tag-Namen, die genau auf diesen Commit verweisen. Sie erscheinen nur dort, wo Git eine benannte Referenz für den Commit hat.", "9289ba0cb9": "Was sind Referenzen?", @@ -14721,7 +14720,6 @@ "f8a2c4d1e0": "Suchmodus des Datei-Explorers" }, "GitHistoryCommitFiles": { - "a1b2c3d4e5": "Dateien werden geladen…", "b2c3d4e5f6": "Keine Dateiänderungen in diesem Commit", "c3d4e5f6a7": "Alle Änderungen gemeinsam öffnen" }, diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 579fad63fa41..0d462a558129 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -13872,7 +13872,6 @@ }, "GitHistoryPanel": { "cf7cad58d2": "No commits yet", - "781a8bcf7b": "Loading graph...", "d0fb0f4bf2": "Refresh commits", "9f7535d22b": "Refs are branch or tag names pointing at that exact commit. They only appear where Git has a named ref for the commit.", "9289ba0cb9": "What are refs?", @@ -15091,7 +15090,6 @@ "f8a2c4d1e0": "Explorer search mode" }, "GitHistoryCommitFiles": { - "a1b2c3d4e5": "Loading files…", "b2c3d4e5f6": "No file changes in this commit", "c3d4e5f6a7": "Open all changes together" }, diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 7c15f54c16b0..c7dd175ba9e7 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -13184,7 +13184,6 @@ }, "GitHistoryPanel": { "cf7cad58d2": "Aún no hay commits", - "781a8bcf7b": "Cargando gráfico…", "d0fb0f4bf2": "Actualizar commits", "9f7535d22b": "Las refs son nombres de ramas o tags que apuntan a ese commit exacto. Solo aparecen cuando Git tiene una ref con nombre para el commit.", "9289ba0cb9": "¿Qué son las refs?", @@ -14439,7 +14438,6 @@ "f8a2c4d1e0": "Modo de búsqueda del explorador" }, "GitHistoryCommitFiles": { - "a1b2c3d4e5": "Cargando archivos…", "b2c3d4e5f6": "No hay cambios de archivos en este commit", "c3d4e5f6a7": "Abrir todos los cambios juntos" }, diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 9372e6e07047..577b8678fd4b 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -13408,7 +13408,6 @@ }, "GitHistoryPanel": { "cf7cad58d2": "Aucun commit pour le moment", - "781a8bcf7b": "Chargement du graphe...", "d0fb0f4bf2": "Actualiser les commits", "9f7535d22b": "Les refs sont des noms de branche ou de tag pointant vers ce commit exact. Elles n'apparaissent que là où Git possède une ref nommée pour ce commit.", "9289ba0cb9": "Que sont les refs ?", @@ -14663,7 +14662,6 @@ "f8a2c4d1e0": "Mode de recherche de l'explorateur" }, "GitHistoryCommitFiles": { - "a1b2c3d4e5": "Chargement des fichiers…", "b2c3d4e5f6": "Aucune modification de fichier dans ce commit", "c3d4e5f6a7": "Ouvrir toutes les modifications ensemble" }, diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 6baaaeccba61..900e1ca2fbfc 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -12878,7 +12878,6 @@ }, "GitHistoryPanel": { "cf7cad58d2": "まだコミットはありません", - "781a8bcf7b": "グラフを読み込んでいます…", "d0fb0f4bf2": "コミットを更新する", "9f7535d22b": "Ref は、そのコミットそのものを指すブランチ名またはタグ名です。これらは、Git にコミットの名前付き参照がある場合にのみ表示されます。", "9289ba0cb9": "リファレンスとは何ですか?", @@ -14072,7 +14071,6 @@ "f8a2c4d1e0": "エクスプローラー検索モード" }, "GitHistoryCommitFiles": { - "a1b2c3d4e5": "ファイルを読み込み中…", "b2c3d4e5f6": "このコミットにはファイルの変更がありません", "c3d4e5f6a7": "すべての変更をまとめて開く" }, diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 67c6b3b7e769..df0bff8b18e0 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -12878,7 +12878,6 @@ }, "GitHistoryPanel": { "cf7cad58d2": "아직 commits이 없습니다", - "781a8bcf7b": "그래프 로드 중...", "d0fb0f4bf2": "commits 새로 고침", "9f7535d22b": "Refs는 정확한 commit을 가리키는 브랜치 또는 태그 이름입니다. Git에 commit에 대한 명명된 참조가 있는 경우에만 나타납니다.", "9289ba0cb9": "refs란 무엇인가요?", @@ -14072,7 +14071,6 @@ "f8a2c4d1e0": "탐색기 검색 모드" }, "GitHistoryCommitFiles": { - "a1b2c3d4e5": "파일 로드 중…", "b2c3d4e5f6": "이 commit에는 파일 변경 사항이 없습니다", "c3d4e5f6a7": "모든 변경 사항을 함께 열기" }, diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 6122d6ff134f..a9c35a265d6e 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -10909,7 +10909,6 @@ }, "GitHistoryPanel": { "cf7cad58d2": "Ainda sem commits", - "781a8bcf7b": "Carregando gráfico...", "d0fb0f4bf2": "Atualizar commits", "9f7535d22b": "Refs são nomes de branch ou tag que apontam para esse commit exato. Eles só aparecem onde o Git tem uma ref nomeada para o commit.", "9289ba0cb9": "O que são refs?", @@ -11111,7 +11110,6 @@ "f8a2c4d1e0": "Modo de busca do Explorador" }, "GitHistoryCommitFiles": { - "a1b2c3d4e5": "Carregando arquivos…", "b2c3d4e5f6": "Nenhuma alteração de arquivo neste commit", "c3d4e5f6a7": "Abrir todas as alterações juntas" }, diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index c430a194ff36..2a8597c23114 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -13870,7 +13870,6 @@ }, "GitHistoryPanel": { "cf7cad58d2": "Коммитов пока нет", - "781a8bcf7b": "Загрузка графа…", "d0fb0f4bf2": "Обновить коммиты", "9f7535d22b": "Ссылки — это имена веток или тегов, указывающих на конкретный коммит. Они отображаются только там, где у коммита есть именованная ссылка Git.", "9289ba0cb9": "Что такое ссылки?", @@ -15163,7 +15162,6 @@ "f8a2c4d1e0": "Режим поиска в проводнике" }, "GitHistoryCommitFiles": { - "a1b2c3d4e5": "Загрузка файлов…", "b2c3d4e5f6": "В этом коммите нет изменений файлов", "c3d4e5f6a7": "Открыть все изменения вместе" }, diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 2e061be5b1c2..83ccf6fd9dc5 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -13490,7 +13490,6 @@ }, "GitHistoryPanel": { "cf7cad58d2": "Henüz commit yok", - "781a8bcf7b": "Grafik yükleniyor...", "d0fb0f4bf2": "Commit'leri yenile", "9f7535d22b": "Ref'ler, tam olarak o commit'i işaret eden branch veya tag adlarıdır. Yalnızca Git'in commit için adlandırılmış bir ref'i olduğu yerlerde görünürler.", "9289ba0cb9": "Ref nedir?", @@ -14707,7 +14706,6 @@ "f8a2c4d1e0": "Gezgin arama modu" }, "GitHistoryCommitFiles": { - "a1b2c3d4e5": "Dosyalar yükleniyor…", "b2c3d4e5f6": "Bu commit'te dosya değişikliği yok", "c3d4e5f6a7": "Tüm değişiklikleri birlikte aç" }, diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 226cde18b5ab..b796c21f459c 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -13326,7 +13326,6 @@ }, "GitHistoryPanel": { "cf7cad58d2": "尚無提交", - "781a8bcf7b": "正在載入圖表...", "d0fb0f4bf2": "重新整理提交記錄", "9f7535d22b": "引用是指向該確切提交的分支或標籤名稱。它們僅出現在 Git 具有該提交的命名引用的位置。", "9289ba0cb9": "什麼是引用?", @@ -14520,7 +14519,6 @@ "f8a2c4d1e0": "檔案總管搜尋模式" }, "GitHistoryCommitFiles": { - "a1b2c3d4e5": "正在載入檔案…", "b2c3d4e5f6": "此提交沒有檔案變更", "c3d4e5f6a7": "一起開啟所有變更" }, diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index a1d24ccd6172..6b949aa6bcff 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -12878,7 +12878,6 @@ }, "GitHistoryPanel": { "cf7cad58d2": "尚无提交", - "781a8bcf7b": "正在加载图表...", "d0fb0f4bf2": "刷新提交记录", "9f7535d22b": "引用是指向该确切提交的分支或标签名称。它们仅出现在 Git 具有该提交的命名引用的位置。", "9289ba0cb9": "什么是参考文献?", @@ -14072,7 +14071,6 @@ "f8a2c4d1e0": "资源管理器搜索模式" }, "GitHistoryCommitFiles": { - "a1b2c3d4e5": "正在加载文件…", "b2c3d4e5f6": "此提交没有文件更改", "c3d4e5f6a7": "一起打开所有更改" }, diff --git a/src/renderer/src/lib/git-graph-tab.ts b/src/renderer/src/lib/git-graph-tab.ts index 6a4a8caf54e0..6b3dccdd13d8 100644 --- a/src/renderer/src/lib/git-graph-tab.ts +++ b/src/renderer/src/lib/git-graph-tab.ts @@ -7,7 +7,11 @@ import { findIndexedRepoOwnerForHost, findIndexedWorktreeOwnerForHost } from './worktree-runtime-owner-index' -import { selectWorktreesByRepo } from '@/store/workspace-record-selectors' +import { + selectDetectedWorktreesByRepo, + selectFolderWorkspaces, + selectWorktreesByRepo +} from '@/store/workspace-record-selectors' import { resolveWorktreeOperationRoute, resolveWorktreeOperationRouteForHost, @@ -35,8 +39,8 @@ export function gitGraphScopeInputs(state: ReturnType { ) const id = existing?.entityId ?? `${worktreeId}::git-graph` const label = translate('gitGraph.title', 'Git Graph') - if (!state.openFiles.some((file) => file.id === id)) { - useAppStore.setState({ - openFiles: [ - ...state.openFiles, - { - id, - filePath: id, - relativePath: label, - worktreeId, - runtimeEnvironmentId: scope.route.runtimeEnvironmentId, - language: 'plaintext', - isDirty: false, - operationProvenance: { - generation: captureWorktreeOperationGenerationSnapshot(scope.route), - ownershipProjection: 'explicit' - }, - mode: 'git-graph' - } - ] - }) + if (state.openFiles.some((file) => file.id === id)) { + openWorkspaceEditorItem(state, id, worktreeId, label, 'git-graph') + return } - openWorkspaceEditorItem(useAppStore.getState(), id, worktreeId, label, 'git-graph') + state.openFile( + { + filePath: id, + relativePath: label, + worktreeId, + runtimeEnvironmentId: scope.route.runtimeEnvironmentId, + language: 'plaintext', + operationProvenance: { + generation: captureWorktreeOperationGenerationSnapshot(scope.route), + ownershipProjection: 'explicit' + }, + mode: 'git-graph' + }, + { reopenId: id, preview: false } + ) } From 4e0f995a77ea6e3a6e4d216104c484e0a1bf39e1 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 6 Nov 2026 02:57:02 -0800 Subject: [PATCH 17/52] Preserve Git Graph selection and keep row content visible Refresh and token recovery retain loaded depth and selection in one accumulating operation. Keep the published view until it settles, and only fall back to the first commit after history is exhausted. Prioritize current and open-workspace refs, reserve their markers, clip wide graphs and retain filenames when long paths need truncation. --- .../git-graph/git-graph-history-controller.ts | 19 +++- .../editor/git-graph/git-graph-ref-menu.tsx | 26 +++-- .../git-graph/git-graph-rendering.test.tsx | 95 +++++++++++++++++++ .../editor/git-graph/git-graph-tab.tsx | 23 +++-- .../sync/git-history-commit-files.tsx | 15 ++- 5 files changed, 155 insertions(+), 23 deletions(-) diff --git a/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts b/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts index a3dc716a3273..147eb3fc2b62 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts +++ b/src/renderer/src/components/editor/git-graph/git-graph-history-controller.ts @@ -191,7 +191,7 @@ export class GitGraphHistoryController { if (this.pending) { return this.pending } - const previous = this.view.getState().result + const { result: previous, selectedId } = this.view.getState() if (append && !previous?.hasMore) { return Promise.resolve(previous) } @@ -200,6 +200,9 @@ export class GitGraphHistoryController { return Promise.resolve(undefined) } const generation = this.generation + const requestedNavigation = navigation ?? this.navigation + const targetId = revealId ?? selectedId + const targetDepth = previous?.items.length ?? 0 const filter = this.filter const current = () => !this.disposed && generation === this.generation this.initial = false @@ -255,9 +258,8 @@ export class GitGraphHistoryController { } accumulated = { ...page, items } if ( - !revealId || - navigation !== this.navigation || - ids.has(revealId) || + requestedNavigation !== this.navigation || + ((!targetId || ids.has(targetId)) && items.length >= targetDepth) || !page.hasMore || items.length === count ) { @@ -273,11 +275,18 @@ export class GitGraphHistoryController { if (!current()) { return undefined } + const selection = this.view.getState().selectedId ?? accumulated?.items[0]?.id + const selectionGone = + !error && + accumulated?.hasMore === false && + requestedNavigation === this.navigation && + selection !== undefined && + !ids.has(selection) this.view.setState({ result: accumulated ?? previous, error, loading: false, - selectedId: this.view.getState().selectedId ?? accumulated?.items[0]?.id + selectedId: selectionGone ? accumulated?.items[0]?.id : selection }) if ( Array.isArray(filter) && diff --git a/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx b/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx index 6202da02d455..e0cdd209c051 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-ref-menu.tsx @@ -45,10 +45,23 @@ export function GitGraphRefs({ }) { const [open, setOpen] = useState(false) const [menuRef, setMenuRef] = useState() - const inline = references.slice(0, 2) const current = references.find((ref) => ref.id === currentRefId) - if (current && !inline.includes(current)) { - inline[1] = current + const inline = current ? [current] : [] + for (const ref of references) { + if (inline.length === 2) { + break + } + if (workspaces.has(ref.id) && ref !== current) { + inline.push(ref) + } + } + for (const ref of references) { + if (inline.length === 2) { + break + } + if (!inline.includes(ref)) { + inline.push(ref) + } } const badge = (ref: GitHistoryItemRef) => ( @@ -58,17 +71,18 @@ export function GitGraphRefs({ setMenuRef(ref) }} className={cn( - 'inline-flex max-w-full items-center gap-1 rounded-full border px-1.5 text-2xs text-muted-foreground', + 'inline-flex min-w-0 max-w-full shrink items-center gap-1 rounded-full border px-1.5 text-2xs text-muted-foreground', ref.id === currentRefId && 'bg-accent font-medium text-foreground' )} > - + {ref.name} {workspaces.has(ref.id) && (