From ab06482f76c19979181a004413637a74b84ac8d8 Mon Sep 17 00:00:00 2001 From: Neil Date: Fri, 26 Jun 2026 11:14:05 -0700 Subject: [PATCH 1/5] Show Source Control for folder workspaces --- src/main/ipc/repos-remote.test.ts | 92 +++- src/main/ipc/repos.ts | 44 +- src/preload/api-types.ts | 16 +- src/preload/index.ts | 18 +- ...FolderWorkspaceSourceControlPanel.test.tsx | 317 ++++++++++++++ .../FolderWorkspaceSourceControlPanel.tsx | 408 +++++++++++++++++ .../SourceControl.preview-open.test.tsx | 189 +++++++- .../right-sidebar/SourceControl.tsx | 342 +++++++++++---- .../right-sidebar/activity-bar-buttons.tsx | 2 + ...r-workspace-source-control-refresh.test.ts | 412 ++++++++++++++++++ ...folder-workspace-source-control-refresh.ts | 298 +++++++++++++ .../src/components/right-sidebar/index.tsx | 3 +- .../right-sidebar-activity-visibility.test.ts | 18 +- .../right-sidebar-activity-visibility.ts | 2 +- .../right-sidebar-panel-content.tsx | 11 +- .../useGitHistoryCommitActions.ts | 52 ++- .../src/components/settings/BaseRefPicker.tsx | 27 +- src/renderer/src/i18n/locales/en.json | 16 + src/renderer/src/i18n/locales/es.json | 16 + src/renderer/src/i18n/locales/ja.json | 16 + src/renderer/src/i18n/locales/ko.json | 16 + src/renderer/src/i18n/locales/zh.json | 16 + .../src/runtime/runtime-repo-client.ts | 36 +- 23 files changed, 2242 insertions(+), 125 deletions(-) create mode 100644 src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.test.tsx create mode 100644 src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.tsx create mode 100644 src/renderer/src/components/right-sidebar/folder-workspace-source-control-refresh.test.ts create mode 100644 src/renderer/src/components/right-sidebar/folder-workspace-source-control-refresh.ts diff --git a/src/main/ipc/repos-remote.test.ts b/src/main/ipc/repos-remote.test.ts index 8ee9a0ea8c6b..bea8ff348ca1 100644 --- a/src/main/ipc/repos-remote.test.ts +++ b/src/main/ipc/repos-remote.test.ts @@ -11,7 +11,7 @@ import { tmpdir } from 'os' import { join } from 'path' import type * as RepoModule from '../git/repo' import { DEFAULT_REPO_BADGE_COLOR } from '../../shared/constants' -import { isGitRepo } from '../git/repo' +import { getBaseRefDefault, isGitRepo } from '../git/repo' const { handleMock, @@ -2226,6 +2226,30 @@ describe('repos:getBaseRefDefault envelope', () => { expect(result.remoteCount).toBe(1) }) + it('uses repoPath to disambiguate duplicate repo ids for local defaults', async () => { + const selectedRepo = { + id: 'r1', + path: '/selected/repo', + kind: 'git' + } + mockStore.getRepo.mockReturnValue({ + id: 'r1', + path: '/wrong/repo', + kind: 'git' + }) + mockStore.getRepos.mockReturnValue([ + { id: 'r1', path: '/wrong/repo', kind: 'git' }, + selectedRepo + ]) + + await handlers.get('repos:getBaseRefDefault')!(null, { + repoId: 'r1', + repoPath: selectedRepo.path + }) + + expect(getBaseRefDefault).toHaveBeenLastCalledWith(selectedRepo.path) + }) + // Why: the SSH handler resolves default-ref and remote-count in parallel // (Promise.all) so the order of calls into provider.exec is not stable. // Dispatch on argv instead of `mockResolvedValueOnce` chains so tests remain @@ -2283,6 +2307,39 @@ describe('repos:getBaseRefDefault envelope', () => { expect(result.remoteCount).toBe(2) }) + it('uses repoPath to disambiguate duplicate repo ids for SSH defaults', async () => { + mockGitProvider.exec = vi.fn().mockImplementation( + dispatchExec([ + { + match: isSymbolicRef, + respond: () => Promise.resolve({ stdout: 'refs/remotes/origin/main\n', stderr: '' }) + }, + { + match: isRemoteList, + respond: () => Promise.resolve({ stdout: 'origin\n', stderr: '' }) + } + ]) + ) + mockStore.getRepo.mockReturnValue({ + id: 'r1', + path: '/wrong/repo', + kind: 'git' + }) + mockStore.getRepos.mockReturnValue([ + { id: 'r1', path: '/wrong/repo', kind: 'git' }, + { id: 'r1', path: '/remote/selected', connectionId: 'wrong-conn', kind: 'git' }, + { id: 'r1', path: '/remote/selected', connectionId: 'conn-1', kind: 'git' } + ]) + + await handlers.get('repos:getBaseRefDefault')!(null, { + repoId: 'r1', + repoPath: '/remote/selected', + executionHostId: 'ssh:conn-1' + }) + + expect(mockGitProvider.exec).toHaveBeenCalledWith(expect.any(Array), '/remote/selected') + }) + it('returns defaultBaseRef even when remote-count lookup fails', async () => { mockGitProvider.exec = vi.fn().mockImplementation( dispatchExec([ @@ -2427,6 +2484,39 @@ describe('repos:searchBaseRefs SSH relay', () => { expect(argv).toContain('refs/remotes/**/**/**') }) + it('uses repoPath to disambiguate duplicate repo ids for SSH searches', async () => { + mockGitProvider.exec = vi.fn().mockImplementation((argv: string[]) => { + if (argv[0] === 'remote') { + return Promise.resolve({ stdout: 'origin\n', stderr: '' }) + } + return Promise.resolve({ + stdout: 'refs/remotes/origin/main\0origin/main', + stderr: '' + }) + }) + mockStore.getRepo.mockReturnValue({ + id: 'r1', + path: '/wrong/repo', + kind: 'git' + }) + mockStore.getRepos.mockReturnValue([ + { id: 'r1', path: '/wrong/repo', kind: 'git' }, + { id: 'r1', path: '/remote/selected', connectionId: 'wrong-conn', kind: 'git' }, + { id: 'r1', path: '/remote/selected', connectionId: 'conn-1', kind: 'git' } + ]) + + const result = await handlers.get('repos:searchBaseRefs')!(null, { + repoId: 'r1', + repoPath: '/remote/selected', + executionHostId: 'ssh:conn-1', + query: 'main' + }) + + expect(result).toEqual(['origin/main']) + expect(mockGitProvider.exec).toHaveBeenCalledWith(['remote'], '/remote/selected') + expect(mockGitProvider.exec).toHaveBeenCalledWith(expect.any(Array), '/remote/selected') + }) + it('sanitizes glob metacharacter-only queries into the empty-query branch list', async () => { mockGitProvider.exec = vi.fn().mockResolvedValue({ stdout: '', stderr: '' }) mockStore.getRepo.mockReturnValue({ diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index b2c008071bfb..b5203d0d817a 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -83,7 +83,11 @@ import type { RepoMethod } from '../../shared/telemetry-events' import { detectRepoIconAndUpstream } from '../repo-icon-autodetect' import { enrichMissingRepoGitRemoteIdentities } from '../repo-git-remote-identity-enrichment' import { getProjectHostSetupForRepo } from '../../shared/project-host-setup-projection' -import { normalizeExecutionHostId, parseExecutionHostId } from '../../shared/execution-host' +import { + getRepoExecutionHostId, + normalizeExecutionHostId, + parseExecutionHostId +} from '../../shared/execution-host' import { joinRemotePath } from '../ssh/ssh-remote-platform' import { assertFolderWorkspacePathUsable, @@ -2325,8 +2329,8 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v ipcMain.handle( 'repos:getBaseRefDefault', - async (_event, args: { repoId: string }): Promise => { - const repo = store.getRepo(args.repoId) + async (_event, args: BaseRefRepoLookupArgs): Promise => { + const repo = resolveBaseRefRepo(store, args) if (!repo || isFolderRepo(repo)) { // Why: folder-mode repos have no git state to resolve a base ref from. // Return null + 0 so the renderer can decline to use a fabricated default @@ -2417,9 +2421,9 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v async function searchBaseRefDetailsForRepo( store: Store, - args: { repoId: string; query: string; limit?: number } + args: BaseRefSearchArgs ): Promise { - const repo = store.getRepo(args.repoId) + const repo = resolveBaseRefRepo(store, args) if (!repo || isFolderRepo(repo)) { return [] } @@ -2496,6 +2500,36 @@ async function searchBaseRefDetailsForRepo( return searchBaseRefDetails(repo.path, args.query, limit) } +type BaseRefRepoLookupArgs = { + repoId: string + repoPath?: string + executionHostId?: string | null +} + +type BaseRefSearchArgs = BaseRefRepoLookupArgs & { + query: string + limit?: number +} + +function resolveBaseRefRepo(store: Store, args: BaseRefRepoLookupArgs): Repo | undefined { + const repoPath = args.repoPath?.trim() + const executionHostId = args.executionHostId?.trim() + if (!repoPath && !executionHostId) { + return store.getRepo(args.repoId) + } + // Why: folder-workspace Source Control can render duplicate repo ids across + // hosts, sometimes with identical checkout paths. Match every supplied + // discriminator so local/SSH IPC base-ref lookups stay on the embedded child. + return store + .getRepos() + .find( + (repo) => + repo.id === args.repoId && + (!repoPath || repo.path === repoPath) && + (!executionHostId || getRepoExecutionHostId(repo) === executionHostId) + ) +} + function notifyReposChanged(mainWindow: BrowserWindow): void { if (!mainWindow.isDestroyed()) { mainWindow.webContents.send('repos:changed') diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 79d80adb8f2f..3f361212c8d4 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -823,10 +823,22 @@ export type PreloadApi = { getDefaultCreateProjectParent: () => Promise onCloneProgress: (callback: (data: { phase: string; percent: number }) => void) => () => void getGitUsername: (args: { repoId: string }) => Promise - getBaseRefDefault: (args: { repoId: string }) => Promise - searchBaseRefs: (args: { repoId: string; query: string; limit?: number }) => Promise + getBaseRefDefault: (args: { + repoId: string + repoPath?: string + executionHostId?: string | null + }) => Promise + searchBaseRefs: (args: { + repoId: string + repoPath?: string + executionHostId?: string | null + query: string + limit?: number + }) => Promise searchBaseRefDetails: (args: { repoId: string + repoPath?: string + executionHostId?: string | null query: string limit?: number }) => Promise diff --git a/src/preload/index.ts b/src/preload/index.ts index 08e31cab0067..f2d3f5325268 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -517,14 +517,24 @@ const api = { getGitUsername: (args: { repoId: string }): Promise => ipcRenderer.invoke('repos:getGitUsername', args), - getBaseRefDefault: (args: { repoId: string }): Promise => - ipcRenderer.invoke('repos:getBaseRefDefault', args), + getBaseRefDefault: (args: { + repoId: string + repoPath?: string + executionHostId?: string | null + }): Promise => ipcRenderer.invoke('repos:getBaseRefDefault', args), - searchBaseRefs: (args: { repoId: string; query: string; limit?: number }): Promise => - ipcRenderer.invoke('repos:searchBaseRefs', args), + searchBaseRefs: (args: { + repoId: string + repoPath?: string + executionHostId?: string | null + query: string + limit?: number + }): Promise => ipcRenderer.invoke('repos:searchBaseRefs', args), searchBaseRefDetails: (args: { repoId: string + repoPath?: string + executionHostId?: string | null query: string limit?: number }): Promise => ipcRenderer.invoke('repos:searchBaseRefDetails', args), diff --git a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.test.tsx b/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.test.tsx new file mode 100644 index 000000000000..ebf513530d65 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.test.tsx @@ -0,0 +1,317 @@ +// @vitest-environment happy-dom + +import { act, type ReactNode } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { Repo, Worktree, WorkspaceLineage } from '../../../../shared/types' +import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../../shared/workspace-scope' +import { TooltipProvider } from '@/components/ui/tooltip' +import FolderWorkspaceSourceControlPanel from './FolderWorkspaceSourceControlPanel' + +type MockStoreState = { + activeWorktreeId: string | null + activeWorkspaceKey: string | null + folderWorkspaces: { id: string; name: string; folderPath: string }[] + workspaceLineageByChildKey: Record + worktreeLineageById: Record + worktreesByRepo: Record + repos: Repo[] + gitStatusByWorktree: Record + sshConnectionStates: Map + setGitStatus: () => void + updateWorktreeGitIdentity: () => void + setUpstreamStatus: () => void + fetchUpstreamStatus: () => Promise +} + +const panelMocks = vi.hoisted(() => ({ + store: {} as MockStoreState, + sourceControlProps: [] as { worktreeId?: string; embedded?: boolean }[], + refreshCalls: [] as unknown[], + invalidatedWorktreeIds: [] as string[], + keepRefreshPending: false +})) + +vi.mock('@/store', () => { + const useAppStore = Object.assign( + (selector: (state: MockStoreState) => T): T => selector(panelMocks.store), + { getState: () => panelMocks.store } + ) + return { useAppStore } +}) + +vi.mock('@/i18n/i18n', () => ({ + translate: (_key: string, fallback: string, values?: Record) => + values ? fallback.replace('{{value0}}', String(values.value0)) : fallback +})) + +vi.mock('./SourceControl', () => ({ + default: (props: { worktreeId?: string; embedded?: boolean }) => { + panelMocks.sourceControlProps.push(props) + return ( +
+ SourceControl {props.worktreeId} +
+ ) + } +})) + +vi.mock('./folder-workspace-source-control-refresh', async (importOriginal) => { + const actual = await importOriginal>() + return { + ...actual, + invalidateFolderSourceControlRefreshGeneration: ( + generationMap: Map, + worktreeIds: Iterable + ) => { + const ids = [...worktreeIds] + panelMocks.invalidatedWorktreeIds.push(...ids) + const invalidate = actual.invalidateFolderSourceControlRefreshGeneration as ( + generationMap: Map, + worktreeIds: Iterable + ) => void + invalidate(generationMap, ids) + }, + runLimitedFolderSourceControlRefreshes: (args: unknown) => { + panelMocks.refreshCalls.push(args) + if (panelMocks.keepRefreshPending) { + const refreshArgs = args as { + candidates: { worktree: Worktree }[] + inFlightWorktreeIds?: Map + } + for (const candidate of refreshArgs.candidates) { + refreshArgs.inFlightWorktreeIds?.set(candidate.worktree.id, 1) + } + return new Promise(() => undefined) + } + return Promise.resolve() + } + } +}) + +let container: HTMLDivElement +let root: Root + +function makeRepo(overrides: Partial = {}): Repo { + return { + id: 'repo-1', + path: '/repo', + displayName: 'Repo', + badgeColor: '#fff', + addedAt: 1, + ...overrides + } +} + +function makeWorktree(overrides: Partial & { id: string }): Worktree { + return { + path: `/worktrees/${overrides.id}`, + head: 'abc', + branch: 'refs/heads/feature', + isBare: false, + isMainWorktree: false, + repoId: 'repo-1', + displayName: overrides.id, + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + linkedGitLabMR: null, + linkedGitLabIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + ...overrides + } +} + +function makeWorkspaceLineage(child: Worktree, parentFolderId = 'folder-1'): WorkspaceLineage { + return { + childWorkspaceKey: worktreeWorkspaceKey(child.id), + childInstanceId: child.instanceId ?? null, + parentWorkspaceKey: folderWorkspaceKey(parentFolderId), + parentInstanceId: null, + origin: 'cli', + capture: { source: 'env-workspace', confidence: 'inferred' }, + createdAt: 1 + } +} + +function renderPanel(children?: ReactNode): void { + act(() => { + root.render( + {children ?? } + ) + }) +} + +describe('FolderWorkspaceSourceControlPanel', () => { + beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + panelMocks.sourceControlProps = [] + panelMocks.refreshCalls = [] + panelMocks.invalidatedWorktreeIds = [] + panelMocks.keepRefreshPending = false + panelMocks.store = { + activeWorktreeId: folderWorkspaceKey('folder-1'), + activeWorkspaceKey: folderWorkspaceKey('folder-1'), + folderWorkspaces: [{ id: 'folder-1', name: 'Platform folder', folderPath: '/platform' }], + workspaceLineageByChildKey: {}, + worktreeLineageById: {}, + worktreesByRepo: {}, + repos: [makeRepo()], + gitStatusByWorktree: {}, + sshConnectionStates: new Map(), + setGitStatus: vi.fn(), + updateWorktreeGitIdentity: vi.fn(), + setUpstreamStatus: vi.fn(), + fetchUpstreamStatus: vi.fn().mockResolvedValue(null) + } + }) + + afterEach(() => { + act(() => root.unmount()) + container.remove() + }) + + it('shows unavailable copy outside folder workspaces', () => { + panelMocks.store.activeWorktreeId = 'repo-1::/current' + panelMocks.store.activeWorkspaceKey = 'repo-1::/current' + + renderPanel() + + expect(container.textContent).toContain( + 'Source Control is only shown for folder workspaces with attached worktrees.' + ) + expect(panelMocks.sourceControlProps).toEqual([]) + }) + + it('shows an empty state for a folder workspace with no attached worktrees', () => { + renderPanel() + + expect(container.textContent).toContain('Platform folder') + expect(container.textContent).toContain('No attached worktrees yet') + expect(panelMocks.sourceControlProps).toEqual([]) + }) + + it('mounts SourceControl only for expanded sections and scopes it to the child worktree', () => { + const first = makeWorktree({ + id: 'repo-1::/first', + displayName: 'First child', + instanceId: 'first', + lastActivityAt: 20 + }) + const second = makeWorktree({ + id: 'repo-1::/second', + displayName: 'Second child', + instanceId: 'second', + lastActivityAt: 10 + }) + panelMocks.store.worktreesByRepo = { 'repo-1': [first, second] } + panelMocks.store.workspaceLineageByChildKey = { + [first.id]: makeWorkspaceLineage(first), + [second.id]: makeWorkspaceLineage(second) + } + panelMocks.store.gitStatusByWorktree = { + [first.id]: [{ path: 'a.ts' }], + [second.id]: [{ path: 'b.ts' }, { path: 'c.ts' }] + } + + renderPanel() + + expect(container.textContent).toContain('2 attached worktrees') + expect(container.textContent).toContain('First child') + expect(container.textContent).toContain('Second child') + expect(container.textContent).toContain('1 cached') + expect(container.textContent).toContain('2 cached') + expect(panelMocks.sourceControlProps).toEqual([{ worktreeId: first.id, embedded: true }]) + + const secondButton = [...container.querySelectorAll('button')].find( + (button) => button.textContent?.includes('Second child') + ) + expect(secondButton).not.toBeNull() + act(() => { + secondButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + + expect(panelMocks.sourceControlProps).toContainEqual({ + worktreeId: second.id, + embedded: true + }) + expect(container.querySelectorAll('[data-testid="scoped-source-control"]')).toHaveLength(2) + }) + + it('invalidates pending refresh generations when the panel unmounts', () => { + const child = makeWorktree({ + id: 'repo-1::/first', + displayName: 'First child', + instanceId: 'first', + lastActivityAt: 20 + }) + panelMocks.store.worktreesByRepo = { 'repo-1': [child] } + panelMocks.store.workspaceLineageByChildKey = { + [child.id]: makeWorkspaceLineage(child) + } + + renderPanel() + expect(panelMocks.refreshCalls.length).toBeGreaterThan(0) + + renderPanel(
) + + expect(panelMocks.invalidatedWorktreeIds).toContain(child.id) + }) + + it('releases cancelled refresh reservations so dependency reruns can retry', () => { + const child = makeWorktree({ + id: 'repo-1::/first', + displayName: 'First child', + instanceId: 'first', + lastActivityAt: 20 + }) + panelMocks.keepRefreshPending = true + panelMocks.store.worktreesByRepo = { 'repo-1': [child] } + panelMocks.store.workspaceLineageByChildKey = { + [child.id]: makeWorkspaceLineage(child) + } + + renderPanel() + const initialCallCount = panelMocks.refreshCalls.length + + panelMocks.store.sshConnectionStates = new Map([['ssh-target', { status: 'connected' }]]) + renderPanel() + + expect(panelMocks.invalidatedWorktreeIds).toContain(child.id) + expect(panelMocks.refreshCalls.length).toBeGreaterThan(initialCallCount) + }) + + it('uses the host-matching repo name for duplicate repo ids', () => { + const child = makeWorktree({ + id: 'repo-1::/ssh-child', + displayName: 'SSH child', + hostId: 'ssh:ssh-target', + instanceId: 'ssh-child', + lastActivityAt: 20 + }) + panelMocks.store.repos = [ + makeRepo({ displayName: 'Local Repo', executionHostId: 'local' }), + makeRepo({ + displayName: 'SSH Repo', + connectionId: 'ssh-target', + executionHostId: 'ssh:ssh-target' + }) + ] + panelMocks.store.worktreesByRepo = { 'repo-1': [child] } + panelMocks.store.workspaceLineageByChildKey = { + [child.id]: makeWorkspaceLineage(child) + } + + renderPanel() + + expect(container.textContent).toContain('SSH Repo') + }) +}) diff --git a/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.tsx b/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.tsx new file mode 100644 index 000000000000..d7886a63b5cb --- /dev/null +++ b/src/renderer/src/components/right-sidebar/FolderWorkspaceSourceControlPanel.tsx @@ -0,0 +1,408 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { ChevronDown, RefreshCw } from 'lucide-react' +import { useAppStore } from '@/store' +import { Button } from '@/components/ui/button' +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { cn } from '@/lib/utils' +import { translate } from '@/i18n/i18n' +import type { Worktree } from '../../../../shared/types' +import { getAttachedWorktreesForFolderWorkspace } from './folder-workspace-attached-worktrees' +import SourceControl from './SourceControl' +import { + getFolderSourceControlRefreshCandidates, + invalidateFolderSourceControlRefreshGeneration, + resolveFolderSourceControlRepo, + runLimitedFolderSourceControlRefreshes, + type FolderSourceControlRefreshReservations, + type FolderSourceControlRefreshOutcome +} from './folder-workspace-source-control-refresh' + +export default function FolderWorkspaceSourceControlPanel(): React.JSX.Element { + const activeWorktreeId = useAppStore((s) => s.activeWorktreeId) + const activeWorkspaceKey = useAppStore((s) => s.activeWorkspaceKey) + const folderWorkspaces = useAppStore((s) => s.folderWorkspaces) + const workspaceLineageByChildKey = useAppStore((s) => s.workspaceLineageByChildKey) + const worktreeLineageById = useAppStore((s) => s.worktreeLineageById) + const worktreesByRepo = useAppStore((s) => s.worktreesByRepo) + const repos = useAppStore((s) => s.repos) + const gitStatusByWorktree = useAppStore((s) => s.gitStatusByWorktree) + const sshConnectionStates = useAppStore((s) => s.sshConnectionStates) + const setGitStatus = useAppStore((s) => s.setGitStatus) + const updateWorktreeGitIdentity = useAppStore((s) => s.updateWorktreeGitIdentity) + const setUpstreamStatus = useAppStore((s) => s.setUpstreamStatus) + const fetchUpstreamStatus = useAppStore((s) => s.fetchUpstreamStatus) + const [expandedWorktreeIds, setExpandedWorktreeIds] = useState>( + () => new Set() + ) + const [refreshOutcomes, setRefreshOutcomes] = useState< + ReadonlyMap + >(() => new Map()) + const [manualRefreshGeneration, setManualRefreshGeneration] = useState(0) + const lastManualGenerationRef = useRef(0) + const inFlightRefreshWorktreeIdsRef = useRef(new Map()) + const refreshGenerationByWorktreeRef = useRef>(new Map()) + + const { folderWorkspace, childWorktrees } = useMemo( + () => + getAttachedWorktreesForFolderWorkspace({ + activeWorkspaceKey, + activeWorktreeId, + folderWorkspaces, + workspaceLineageByChildKey, + worktreeLineageById, + worktreesByRepo + }), + [ + activeWorkspaceKey, + activeWorktreeId, + folderWorkspaces, + workspaceLineageByChildKey, + worktreeLineageById, + worktreesByRepo + ] + ) + + useEffect(() => { + setExpandedWorktreeIds((current) => { + const validIds = new Set(childWorktrees.map((worktree) => worktree.id)) + const next = new Set([...current].filter((id) => validIds.has(id))) + if (next.size === 0 && childWorktrees[0]) { + next.add(childWorktrees[0].id) + } + return setsEqual(current, next) ? current : next + }) + }, [childWorktrees]) + + const manualWorktreeIds = useMemo(() => { + if (manualRefreshGeneration <= lastManualGenerationRef.current) { + return new Set() + } + return new Set(childWorktrees.map((worktree) => worktree.id)) + }, [childWorktrees, manualRefreshGeneration]) + + const refreshCandidates = useMemo( + () => + getFolderSourceControlRefreshCandidates({ + worktrees: childWorktrees, + repos, + expandedWorktreeIds, + manualWorktreeIds + }), + [childWorktrees, expandedWorktreeIds, manualWorktreeIds, repos] + ) + const refreshCandidateSignature = useMemo( + () => + refreshCandidates + .map((candidate) => + [ + candidate.worktree.id, + candidate.worktree.path, + candidate.repo.connectionId ?? '', + candidate.repo.executionHostId ?? '', + candidate.expanded ? 'expanded' : 'collapsed', + candidate.manual ? 'manual' : 'auto' + ].join('|') + ) + .join(';;'), + [refreshCandidates] + ) + + useEffect(() => { + if (!folderWorkspace || childWorktrees.length === 0 || refreshCandidates.length === 0) { + return + } + const refreshWorktreeIds = refreshCandidates.map((candidate) => candidate.worktree.id) + const refreshGenerations = refreshGenerationByWorktreeRef.current + const inFlightRefreshes = inFlightRefreshWorktreeIdsRef.current + if (manualRefreshGeneration > lastManualGenerationRef.current) { + lastManualGenerationRef.current = manualRefreshGeneration + } + let cancelled = false + void runLimitedFolderSourceControlRefreshes({ + candidates: refreshCandidates, + concurrency: 3, + deps: { + setGitStatus, + updateWorktreeGitIdentity, + setUpstreamStatus, + fetchUpstreamStatus + }, + sshConnectionStates, + inFlightWorktreeIds: inFlightRefreshes, + refreshGenerationByWorktree: refreshGenerations, + onOutcome: (worktreeId, outcome) => { + if (cancelled) { + return + } + setRefreshOutcomes((current) => new Map(current).set(worktreeId, outcome)) + } + }) + return () => { + cancelled = true + invalidateFolderSourceControlRefreshGeneration(refreshGenerations, refreshWorktreeIds) + for (const worktreeId of refreshWorktreeIds) { + inFlightRefreshes.delete(worktreeId) + } + } + }, [ + childWorktrees.length, + fetchUpstreamStatus, + folderWorkspace, + manualRefreshGeneration, + refreshCandidateSignature, + refreshCandidates, + setGitStatus, + setUpstreamStatus, + sshConnectionStates, + updateWorktreeGitIdentity + ]) + + const currentChildWorktreeIds = useMemo( + () => new Set(childWorktrees.map((worktree) => worktree.id)), + [childWorktrees] + ) + const isRefreshing = [...refreshOutcomes.entries()].some( + ([worktreeId, outcome]) => currentChildWorktreeIds.has(worktreeId) && outcome.kind === 'loading' + ) + const repoNameByWorktreeId = useMemo( + () => + new Map( + childWorktrees.map((worktree) => [ + worktree.id, + resolveFolderSourceControlRepo(worktree, repos)?.displayName ?? null + ]) + ), + [childWorktrees, repos] + ) + + const toggleWorktree = useCallback((worktreeId: string): void => { + setExpandedWorktreeIds((current) => { + const next = new Set(current) + if (next.has(worktreeId)) { + next.delete(worktreeId) + } else { + next.add(worktreeId) + } + return next + }) + }, []) + + if (!folderWorkspace) { + return ( +
+ {translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.unavailable', + 'Source Control is only shown for folder workspaces with attached worktrees.' + )} +
+ ) + } + + return ( +
+
+
+
+
+ {folderWorkspace.name} +
+
+ {formatAttachedWorktreeCount(childWorktrees.length)} +
+
+ + + + + + {translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.refresh', + 'Refresh source control' + )} + + +
+
+ + {childWorktrees.length === 0 ? ( +
+
+ {translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.emptyTitle', + 'No attached worktrees yet' + )} +
+
+ {translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.emptyCopy', + 'Source Control sections will appear here after worktrees are attached to this folder workspace.' + )} +
+
+ ) : ( +
+
+ {childWorktrees.map((worktree) => { + const expanded = expandedWorktreeIds.has(worktree.id) + return ( + toggleWorktree(worktree.id)} + /> + ) + })} +
+
+ )} +
+ ) +} + +function FolderWorkspaceSourceControlSection({ + worktree, + repoName, + expanded, + statusEntries, + refreshOutcome, + onToggle +}: { + worktree: Worktree + repoName: string | null + expanded: boolean + statusEntries: ReturnType['gitStatusByWorktree'][string] | undefined + refreshOutcome: FolderSourceControlRefreshOutcome | null + onToggle: () => void +}): React.JSX.Element { + return ( + +
+ + + + +
+ {expanded ? : null} +
+
+
+
+ ) +} + +function formatAttachedWorktreeCount(count: number): string { + return count === 1 + ? translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.countOne', + '1 attached worktree' + ) + : translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.countMany', + '{{value0}} attached worktrees', + { value0: count } + ) +} + +function formatStatusSummary( + entries: readonly unknown[] | undefined, + refreshOutcome: FolderSourceControlRefreshOutcome | null +): string { + if (refreshOutcome?.kind === 'loading') { + return translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.loading', + 'Refreshing' + ) + } + if (refreshOutcome?.kind === 'unavailable') { + return translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.unavailableStatus', + 'Unavailable' + ) + } + if (refreshOutcome?.kind === 'failed') { + return entries + ? translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.staleAfterFailed', + '{{value0}} stale', + { value0: entries.length } + ) + : translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.failed', + 'Refresh failed' + ) + } + if (refreshOutcome?.kind === 'fresh') { + return formatFreshChangeCount(entries?.length ?? 0) + } + if (entries) { + return translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.cached', + '{{value0}} cached', + { value0: entries.length } + ) + } + return translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.pending', + 'Status pending' + ) +} + +function formatFreshChangeCount(count: number): string { + return count === 1 + ? translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.changeOne', + '1 change' + ) + : translate( + 'auto.components.rightSidebar.FolderWorkspaceSourceControlPanel.changeMany', + '{{value0}} changes', + { value0: count } + ) +} + +function setsEqual(left: ReadonlySet, right: ReadonlySet): boolean { + if (left.size !== right.size) { + return false + } + for (const value of left) { + if (!right.has(value)) { + return false + } + } + return true +} diff --git a/src/renderer/src/components/right-sidebar/SourceControl.preview-open.test.tsx b/src/renderer/src/components/right-sidebar/SourceControl.preview-open.test.tsx index 857d043174d0..a7236b7bb771 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.preview-open.test.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.preview-open.test.tsx @@ -44,8 +44,12 @@ const mocks = vi.hoisted(() => { openDiff: vi.fn(), openFile: vi.fn(), openConflictFile: vi.fn(), + openConflictReview: vi.fn(), openBranchDiff: vi.fn(), + openAllDiffs: vi.fn(), + openBranchAllDiffs: vi.fn(), createEmptySplitGroup: vi.fn(), + activateAndRevealWorktree: vi.fn(), discardRuntimeGitPath: vi.fn(), refreshGitStatusForWorktree: vi.fn(), requestEditorSaveQuiesce: vi.fn(), @@ -94,6 +98,10 @@ vi.mock('@/components/editor/editor-autosave', () => ({ notifyEditorExternalFileChange: mocks.calls.notifyEditorExternalFileChange })) +vi.mock('@/lib/worktree-activation', () => ({ + activateAndRevealWorktree: mocks.calls.activateAndRevealWorktree +})) + vi.mock('./git-status-refresh', () => ({ refreshGitStatusForWorktree: mocks.calls.refreshGitStatusForWorktree })) @@ -144,6 +152,9 @@ function resetState(overrides: Partial> = {}): void { mocks.calls.requestEditorSaveQuiesce.mockResolvedValue(undefined) mocks.state = { activeWorktreeId: mocks.activeWorktree.id, + getKnownWorktreeById: vi.fn((worktreeId: string) => + worktreeId === mocks.activeWorktree.id ? mocks.activeWorktree : null + ), activeGroupIdByWorktree: { [mocks.activeWorktree.id]: 'group-1' }, groupsByWorktree: { [mocks.activeWorktree.id]: [{ id: 'group-1', activeTabId: null }] }, repos: [mocks.activeRepo], @@ -193,11 +204,11 @@ function resetState(overrides: Partial> = {}): void { setMarkdownViewMode: vi.fn(), setPendingEditorReveal: vi.fn(), openConflictFile: mocks.calls.openConflictFile, - openConflictReview: vi.fn(), + openConflictReview: mocks.calls.openConflictReview, openBranchDiff: mocks.calls.openBranchDiff, createEmptySplitGroup: mocks.calls.createEmptySplitGroup, - openAllDiffs: vi.fn(), - openBranchAllDiffs: vi.fn(), + openAllDiffs: mocks.calls.openAllDiffs, + openBranchAllDiffs: mocks.calls.openBranchAllDiffs, openCommitAllDiffs: vi.fn(), deleteDiffComment: noopAsync(true), clearDiffComments: noopAsync(true), @@ -233,11 +244,11 @@ afterEach(() => { container.remove() }) -function renderSourceControl(): void { +function renderSourceControl(props: React.ComponentProps = {}): void { act(() => { root.render( - + ) }) @@ -270,6 +281,16 @@ function clickBranchRow(init: MouseEventInit = {}): void { }) } +function clickViewAllButton(): void { + const button = [...container.querySelectorAll('button')].find( + (candidate) => candidate.textContent?.trim() === 'View all' + ) + expect(button).not.toBeNull() + act(() => { + button?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) +} + describe('SourceControl preview row opens', () => { it('passes preview=true when plain uncommitted row clicks open diff tabs', () => { resetState({ @@ -420,6 +441,91 @@ describe('SourceControl preview row opens', () => { }) }) + it('routes embedded git mutations through the scoped worktree host owner', async () => { + const hostedWorktree = { ...mocks.activeWorktree, hostId: 'runtime:worktree-env' } + resetState({ + activeWorktreeId: 'folder:folder-1', + settings: { activeRuntimeEnvironmentId: 'focused-env' }, + getKnownWorktreeById: vi.fn((worktreeId: string) => + worktreeId === hostedWorktree.id ? hostedWorktree : null + ), + worktreesByRepo: { [mocks.activeRepo.id]: [hostedWorktree] }, + gitStatusByWorktree: { [hostedWorktree.id]: [gitEntry({ path: 'src/file.ts' })] } + }) + renderSourceControl({ worktreeId: hostedWorktree.id, embedded: true }) + + const row = container.querySelector('[data-source-control-path="src/file.ts"]') + const discardButton = row?.querySelector( + 'button[aria-label="Discard changes"]' + ) + expect(discardButton).not.toBeNull() + act(() => { + discardButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + + const confirmButton = [...document.body.querySelectorAll('button')].find( + (button) => button.textContent?.trim() === 'Discard' + ) + expect(confirmButton).not.toBeNull() + await act(async () => { + confirmButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + await Promise.resolve() + }) + + expect(mocks.calls.discardRuntimeGitPath).toHaveBeenCalledWith( + expect.objectContaining({ + settings: expect.objectContaining({ activeRuntimeEnvironmentId: 'worktree-env' }), + worktreeId: hostedWorktree.id + }), + 'src/file.ts' + ) + }) + + it('does not inherit an SSH connection from a duplicate repo on another host', async () => { + const sshRepo = { + ...mocks.activeRepo, + connectionId: 'ssh-target', + executionHostId: 'ssh:ssh-target' + } + const localRepo = { ...mocks.activeRepo, connectionId: null, executionHostId: 'local' } + const localWorktree = { ...mocks.activeWorktree, hostId: 'local' } + resetState({ + repos: [sshRepo, localRepo], + worktreesByRepo: { [mocks.activeRepo.id]: [localWorktree] }, + getKnownWorktreeById: vi.fn((worktreeId: string) => + worktreeId === localWorktree.id ? localWorktree : null + ), + gitStatusByWorktree: { [localWorktree.id]: [gitEntry({ path: 'src/file.ts' })] } + }) + renderSourceControl({ worktreeId: localWorktree.id, embedded: true }) + + const row = container.querySelector('[data-source-control-path="src/file.ts"]') + const discardButton = row?.querySelector( + 'button[aria-label="Discard changes"]' + ) + expect(discardButton).not.toBeNull() + act(() => { + discardButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + + const confirmButton = [...document.body.querySelectorAll('button')].find( + (button) => button.textContent?.trim() === 'Discard' + ) + expect(confirmButton).not.toBeNull() + await act(async () => { + confirmButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + await Promise.resolve() + }) + + expect(mocks.calls.discardRuntimeGitPath).toHaveBeenCalledWith( + expect.objectContaining({ + connectionId: undefined, + worktreeId: localWorktree.id + }), + 'src/file.ts' + ) + }) + it('keeps nested-only submodule rows non-stageable from the parent repo', () => { resetState({ gitStatusByWorktree: { @@ -463,4 +569,77 @@ describe('SourceControl preview row opens', () => { { targetGroupId: undefined, preview: true } ) }) + + it('activates the scoped child worktree before embedded uncommitted View all opens', () => { + resetState({ + activeWorktreeId: 'folder:folder-1', + gitStatusByWorktree: { + [mocks.activeWorktree.id]: [gitEntry({ path: 'src/file.ts' })], + 'folder:folder-1': [gitEntry({ path: 'wrong.ts' })] + } + }) + renderSourceControl({ worktreeId: mocks.activeWorktree.id, embedded: true }) + + clickViewAllButton() + + expect(mocks.calls.activateAndRevealWorktree).toHaveBeenCalledWith(mocks.activeWorktree.id, { + revealInSidebar: false, + notifyHostRuntime: false + }) + expect(mocks.calls.openAllDiffs).toHaveBeenCalledWith( + mocks.activeWorktree.id, + '/repo/wt', + undefined, + 'unstaged', + [expect.objectContaining({ path: 'src/file.ts' })] + ) + }) + + it('activates the scoped child worktree before embedded branch View all opens', () => { + resetState({ + activeWorktreeId: 'folder:folder-1', + gitBranchChangesByWorktree: { [mocks.activeWorktree.id]: [branchEntry()] }, + gitBranchCompareSummaryByWorktree: { [mocks.activeWorktree.id]: branchSummary() } + }) + renderSourceControl({ worktreeId: mocks.activeWorktree.id, embedded: true }) + + clickViewAllButton() + + expect(mocks.calls.activateAndRevealWorktree).toHaveBeenCalledWith(mocks.activeWorktree.id, { + revealInSidebar: false, + notifyHostRuntime: false + }) + expect(mocks.calls.openBranchAllDiffs).toHaveBeenCalledWith( + mocks.activeWorktree.id, + '/repo/wt', + expect.objectContaining({ status: 'ready' }) + ) + }) + + it('activates the scoped child worktree before embedded row opens', () => { + resetState({ + activeWorktreeId: 'folder:folder-1', + gitStatusByWorktree: { + [mocks.activeWorktree.id]: [gitEntry({ path: 'src/file.ts' })], + 'folder:folder-1': [gitEntry({ path: 'wrong.ts' })] + } + }) + renderSourceControl({ worktreeId: mocks.activeWorktree.id, embedded: true }) + + clickUncommitted('src/file.ts', { ctrlKey: true }) + + expect(mocks.calls.activateAndRevealWorktree).toHaveBeenCalledWith(mocks.activeWorktree.id, { + revealInSidebar: false, + notifyHostRuntime: false + }) + expect(mocks.calls.createEmptySplitGroup).not.toHaveBeenCalled() + expect(mocks.calls.openDiff).toHaveBeenCalledWith( + mocks.activeWorktree.id, + '/repo/wt/src/file.ts', + 'src/file.ts', + 'typescript', + false, + { targetGroupId: undefined, preview: true } + ) + }) }) diff --git a/src/renderer/src/components/right-sidebar/SourceControl.tsx b/src/renderer/src/components/right-sidebar/SourceControl.tsx index 74fa804f48bc..c782bfeb0abe 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.tsx @@ -33,7 +33,7 @@ import { } from 'lucide-react' import { useAppStore } from '@/store' import { resolveRemoteOperationErrorMessage } from '@/lib/source-control-remote-error' -import { useActiveWorktree, useRepoById, useWorktreeMap } from '@/store/selectors' +import { useWorktreeMap } from '@/store/selectors' import { getHostedReviewCacheKey } from '@/store/slices/hosted-review' import { getGitHubPRCacheKey } from '@/store/slices/github-cache-key' import { detectLanguage } from '@/lib/language-detect' @@ -144,7 +144,6 @@ import { requestEditorSaveQuiesce } from '@/components/editor/editor-autosave' import { getConnectionId } from '@/lib/connection-context' -import { getRepoOwnerRoutedSettings } from '@/lib/repo-runtime-owner' import { abortRuntimeGitMerge, abortRuntimeGitRebase, @@ -200,6 +199,7 @@ import type { SourceControlAiWriteTarget } from '../../../../shared/source-contr import { getWorktreeGitIdentityDisplay } from '@/lib/worktree-git-identity-display' import { resolveSourceControlLaunchPlatform } from '@/lib/source-control-launch-platform' import { getLocalProjectExecutionRuntimeContext } from '@/lib/local-preflight-context' +import { activateAndRevealWorktree } from '@/lib/worktree-activation' import { loadSessionCommitDrafts, saveSessionCommitDrafts @@ -234,6 +234,11 @@ import { localizedHostedReviewCopy, resolveSupportedHostedReviewCopyProvider } from '@/i18n/hosted-review-localized-copy' +import { + getExecutionHostIdForWorktree, + getSettingsForWorktreeRuntimeOwner +} from '@/lib/worktree-runtime-owner' +import { getRepoExecutionHostId } from '../../../../shared/execution-host' import { createCreatePrIntentRunToken, createPrIntentCurrentTargetConflictsWithToken, @@ -726,7 +731,15 @@ export function clearRemoteActionErrorsForCompletedConflictOperations({ return next ?? remoteActionErrors } -function SourceControlInner(): React.JSX.Element { +export type SourceControlProps = { + worktreeId?: string + embedded?: boolean +} + +function SourceControlInner({ + worktreeId: scopedWorktreeId, + embedded = false +}: SourceControlProps): React.JSX.Element { const sourceControlRef = useRef(null) const isMac = useMemo(() => navigator.userAgent.includes('Mac'), []) const pendingCommentEditorRevealFrameIdsRef = useRef([]) @@ -735,14 +748,40 @@ function SourceControlInner(): React.JSX.Element { // state re-renders. A ref flipped synchronously at the start of // handleCommit gives us a true single-flight lock. const commitInFlightRef = useRef>({}) - const activeWorktree = useActiveWorktree() - const activeWorktreeId = useAppStore((s) => s.activeWorktreeId) + const globalActiveWorktreeId = useAppStore((s) => s.activeWorktreeId) + const activeWorktreeId = scopedWorktreeId ?? globalActiveWorktreeId + const activeWorktree = useAppStore((s) => { + if (!activeWorktreeId) { + return null + } + return ( + s.getKnownWorktreeById?.(activeWorktreeId) ?? + Object.values(s.worktreesByRepo) + .flat() + .find((worktree) => worktree.id === activeWorktreeId) ?? + null + ) + }) const activeGroupId = useAppStore((s) => - activeWorktreeId ? s.activeGroupIdByWorktree[activeWorktreeId] : undefined + !embedded && activeWorktreeId ? s.activeGroupIdByWorktree[activeWorktreeId] : undefined ) const worktreeMap = useWorktreeMap() const rightSidebarTab = useAppStore((s) => s.rightSidebarTab) - const activeRepo = useRepoById(activeWorktree?.repoId ?? null) + const activeRepo = useAppStore((s) => { + if (!activeWorktree?.repoId) { + return null + } + const matchingRepos = s.repos.filter((repo) => repo.id === activeWorktree.repoId) + if (matchingRepos.length <= 1 || !activeWorktreeId) { + return matchingRepos[0] ?? null + } + const worktreeHostId = getExecutionHostIdForWorktree(s, activeWorktreeId) + return ( + matchingRepos.find((repo) => getRepoExecutionHostId(repo) === worktreeHostId) ?? + matchingRepos[0] ?? + null + ) + }) const entries = useAppStore((s) => activeWorktreeId ? (s.gitStatusByWorktree[activeWorktreeId] ?? EMPTY_GIT_STATUS_ENTRIES) @@ -774,11 +813,30 @@ function SourceControlInner(): React.JSX.Element { const isRemoteOperationActive = useAppStore((s) => s.isRemoteOperationActive) const inFlightRemoteOpKind = useAppStore((s) => s.inFlightRemoteOpKind) const settings = useAppStore((s) => s.settings) - // Why: git/file mutations and repo metadata requests belong to the repo - // OWNER host, not the currently focused host in the sidebar. - const activeRepoSettings = useMemo( - () => getRepoOwnerRoutedSettings(settings, activeRepo ?? null), - [activeRepo, settings] + const activeRepoSettings = useMemo(() => { + if (!settings) { + return settings + } + const ownerSettings = activeWorktreeId + ? getSettingsForWorktreeRuntimeOwner(useAppStore.getState(), activeWorktreeId) + : { activeRuntimeEnvironmentId: null } + return { ...settings, activeRuntimeEnvironmentId: ownerSettings.activeRuntimeEnvironmentId } + }, [activeWorktreeId, settings]) + const getScopedConnectionId = useCallback( + (worktreeId: string | null | undefined): string | undefined => { + if (!worktreeId) { + return undefined + } + if (worktreeId === activeWorktreeId && activeRepo) { + const hostId = getExecutionHostIdForWorktree(useAppStore.getState(), worktreeId) + const repoHostId = getRepoExecutionHostId(activeRepo) + if (hostId === repoHostId) { + return activeRepo.connectionId ?? undefined + } + } + return getConnectionId(worktreeId) ?? undefined + }, + [activeRepo, activeWorktreeId] ) const updateSettings = useAppStore((s) => s.updateSettings) const openSettingsTarget = useAppStore((s) => s.openSettingsTarget) @@ -828,6 +886,19 @@ function SourceControlInner(): React.JSX.Element { const setScrollToDiffCommentId = useAppStore((s) => s.setScrollToDiffCommentId) const setRightSidebarOpen = useAppStore((s) => s.setRightSidebarOpen) const setRightSidebarTab = useAppStore((s) => s.setRightSidebarTab) + const activateEmbeddedWorktreeForEditorOpen = useCallback((): boolean => { + if (!embedded || !activeWorktreeId) { + return true + } + // Why: editor groups are worktree-scoped today; embedded folder sections + // must activate the child before opening files/diffs so tabs land visibly. + return ( + activateAndRevealWorktree(activeWorktreeId, { + revealInSidebar: false, + notifyHostRuntime: false + }) !== false + ) + }, [activeWorktreeId, embedded]) // Why: pass activeWorktreeId directly (even when null/undefined) so the // slice's getDiffComments returns its stable EMPTY_COMMENTS sentinel. An // inline `[]` fallback would allocate a new array each store update, break @@ -1035,10 +1106,10 @@ function SourceControlInner(): React.JSX.Element { settings: activeRepoSettings, worktreeId: token.worktreeId, worktreePath: token.worktreePath, - connectionId: getConnectionId(token.worktreeId) ?? undefined, + connectionId: getScopedConnectionId(token.worktreeId), pushTarget: worktreeMap.get(token.worktreeId)?.pushTarget }), - [activeRepoSettings, worktreeMap] + [activeRepoSettings, getScopedConnectionId, worktreeMap] ) const prGenerationRecords = useAppStore((s) => s.pullRequestGenerationRecords) const allocatePullRequestGenerationRequestId = useAppStore( @@ -1099,9 +1170,7 @@ function SourceControlInner(): React.JSX.Element { (generateInFlightByWorktree[activeWorktreeId ?? ''] ?? false) const generateError = activeCommitMessageGenerationRecord?.error ?? generateErrors[activeWorktreeId ?? ''] ?? null - const activeConnectionId = activeWorktreeId - ? (getConnectionId(activeWorktreeId) ?? activeRepo?.connectionId ?? null) - : null + const activeConnectionId = getScopedConnectionId(activeWorktreeId) ?? null const activeSourceControlLaunchPlatform = resolveSourceControlLaunchPlatform({ connectionId: activeConnectionId, worktreePath, @@ -1136,13 +1205,16 @@ function SourceControlInner(): React.JSX.Element { // The sidebar now stays mounted when closed (for performance), so without // this guard the branchCompare interval and PR fetch would keep running // with no visible consumer, wasting git process spawns and API calls. - const isBranchVisible = rightSidebarTab === 'source-control' && rightSidebarOpen + const isBranchVisible = + rightSidebarTab === 'source-control' && + rightSidebarOpen && + (!embedded || Boolean(activeWorktreeId)) const refreshActiveGitStatus = useCallback(async (): Promise => { if (!activeWorktreeId || !worktreePath || isFolder) { return } - const connectionId = getConnectionId(activeWorktreeId) ?? undefined + const connectionId = activeConnectionId ?? undefined await refreshGitStatusForWorktree({ // Why: route git status by the repo OWNER host, not the focused runtime. settings: activeRepoSettings, @@ -1159,6 +1231,7 @@ function SourceControlInner(): React.JSX.Element { }) }, [ activeRepoSettings, + activeConnectionId, activeWorktreeId, activeWorktree?.pushTarget, fetchUpstreamStatus, @@ -1275,7 +1348,10 @@ function SourceControlInner(): React.JSX.Element { setDefaultBaseRef(null) let stale = false - void getRuntimeRepoBaseRefDefault(activeRepoSettings, activeRepo.id) + void getRuntimeRepoBaseRefDefault(activeRepoSettings, activeRepo.id, { + repoPath: activeRepo.path, + executionHostId: getRepoExecutionHostId(activeRepo) + }) .then((result) => { if (!stale) { // Why: IPC now returns a `{ defaultBaseRef, remoteCount }` envelope; @@ -1304,9 +1380,11 @@ function SourceControlInner(): React.JSX.Element { const baseRefOwnedByWorktree = normalizedWorktreeBaseRef !== null const pinnedBaseRef = normalizedWorktreeBaseRef ?? normalizedRepoBaseRef const hasUncommittedEntries = entries.length > 0 + const hostedReviewSurfaceEnabled = !embedded const hostedReviewCreation = hostedReviewCreationState && + hostedReviewSurfaceEnabled && activeRepo?.id === hostedReviewCreationState.repoId && activeWorktreeId === hostedReviewCreationState.worktreeId && branchName === hostedReviewCreationState.branch @@ -1317,7 +1395,7 @@ function SourceControlInner(): React.JSX.Element { ) const hostedReviewCreateCopy = localizedHostedReviewCopy(hostedReviewCreateProvider) const hostedReviewCacheKey = - activeRepo && branchName + hostedReviewSurfaceEnabled && activeRepo && branchName ? getHostedReviewCacheKey( activeRepo.path, branchName, @@ -1331,7 +1409,7 @@ function SourceControlInner(): React.JSX.Element { ? hostedReviewCache[hostedReviewCacheKey] : undefined const activePrCacheKey = - activeRepo && branchName + hostedReviewSurfaceEnabled && activeRepo && branchName ? getGitHubPRCacheKey( activeRepo.path, activeRepo.id, @@ -1379,6 +1457,7 @@ function SourceControlInner(): React.JSX.Element { const linkedAzureDevOpsPR = activeWorktree?.linkedAzureDevOpsPR ?? null const linkedGiteaPR = activeWorktree?.linkedGiteaPR ?? null const shouldResolveHostedReviewCreation = + hostedReviewSurfaceEnabled && isBranchVisible && Boolean(activeRepo) && !isFolder && @@ -1501,6 +1580,7 @@ function SourceControlInner(): React.JSX.Element { !isBranchVisible || !activeRepo || isFolder || + !hostedReviewSurfaceEnabled || !branchName || branchName === 'HEAD' || !activeWorktreeId @@ -1530,6 +1610,7 @@ function SourceControlInner(): React.JSX.Element { branchName, enqueueGitHubPRRefresh, fetchHostedReviewForBranch, + hostedReviewSurfaceEnabled, isBranchVisible, isFolder, linkedGitHubPR, @@ -1719,9 +1800,10 @@ function SourceControlInner(): React.JSX.Element { openSettingsTarget, openSettingsPage }) + const scopedSourceControlAiActionsVisible = !embedded && sourceControlAiActionsVisible useEffect(() => { - if (sourceControlAiActionsVisible) { + if (scopedSourceControlAiActionsVisible) { return } setResolveConflictsComposerOpen(false) @@ -1731,7 +1813,7 @@ function SourceControlInner(): React.JSX.Element { setCommitGenerationDialogOpen, setPullRequestGenerationDialogOpen, setResolveConflictsComposerOpen, - sourceControlAiActionsVisible + scopedSourceControlAiActionsVisible ]) // Why: orphaned draft/error/in-flight entries accumulate when worktrees are @@ -1851,7 +1933,7 @@ function SourceControlInner(): React.JSX.Element { settings: activeRepoSettings, worktreeId: activeWorktreeId, worktreePath, - connectionId: getConnectionId(activeWorktreeId) ?? undefined, + connectionId: activeConnectionId ?? undefined, pushTarget: activeWorktree?.pushTarget } : null) @@ -1951,6 +2033,7 @@ function SourceControlInner(): React.JSX.Element { }, [ activeRepoSettings, + activeConnectionId, activeWorktree?.pushTarget, activeWorktreeId, beginGitBranchCompareRequest, @@ -1994,7 +2077,7 @@ function SourceControlInner(): React.JSX.Element { generateInFlightRef.current[activeWorktreeId] = true const requestId = allocateCommitMessageGenerationRequestId() - const connectionId = getConnectionId(activeWorktreeId) ?? undefined + const connectionId = activeConnectionId ?? undefined setCommitMessageGenerationRecord( activeCommitMessageGenerationKey, createRunningCommitMessageGenerationRecord({ @@ -2087,6 +2170,7 @@ function SourceControlInner(): React.JSX.Element { }, [ activeCommitMessageGenerationKey, + activeConnectionId, activeRepoSettings, activeWorktreeId, allocateCommitMessageGenerationRequestId, @@ -2099,7 +2183,7 @@ function SourceControlInner(): React.JSX.Element { ) const handleGenerateCommitMessageClick = useCallback((): void => { - if (!sourceControlAiActionsVisible) { + if (!scopedSourceControlAiActionsVisible) { return } if ( @@ -2116,7 +2200,7 @@ function SourceControlInner(): React.JSX.Element { openCommitGenerationDialog, resolvedCommitMessageAi, settings, - sourceControlAiActionsVisible + scopedSourceControlAiActionsVisible ]) const generateCommitMessageForCreatePrIntent = useCallback( @@ -2185,7 +2269,7 @@ function SourceControlInner(): React.JSX.Element { updateCommitMessageGenerationRecord(activeCommitMessageGenerationKey, (record) => resolveCommitMessageGenerationCancel(record) ) - const connectionId = getConnectionId(activeWorktreeId) ?? undefined + const connectionId = activeConnectionId ?? undefined // Why: fire-and-forget — the in-flight generateCommitMessage promise // resolves with `{canceled: true}` once the kill propagates, which is // where the spinner is cleared. Awaiting here would just delay UI feedback. @@ -2198,6 +2282,7 @@ function SourceControlInner(): React.JSX.Element { }) }, [ activeCommitMessageGenerationKey, + activeConnectionId, activeRepoSettings, activeWorktreeId, updateCommitMessageGenerationRecord, @@ -2232,7 +2317,7 @@ function SourceControlInner(): React.JSX.Element { settings: activeRepoSettings, worktreeId: activeWorktreeId, worktreePath, - connectionId: getConnectionId(activeWorktreeId) ?? undefined, + connectionId: activeConnectionId ?? undefined, pushTarget: activeWorktree?.pushTarget } : null) @@ -2364,6 +2449,7 @@ function SourceControlInner(): React.JSX.Element { }, [ activeRepoSettings, + activeConnectionId, activeWorktree?.pushTarget, activeWorktreeId, fetchBranch, @@ -2406,7 +2492,7 @@ function SourceControlInner(): React.JSX.Element { return } - const connectionId = getConnectionId(activeWorktreeId) ?? undefined + const connectionId = activeConnectionId ?? undefined setAbortOperationInFlightByWorktree((prev) => ({ ...prev, [activeWorktreeId]: true })) setRemoteActionErrors((prev) => ({ ...prev, [activeWorktreeId]: null })) try { @@ -2444,6 +2530,7 @@ function SourceControlInner(): React.JSX.Element { }, [ activeRepoSettings, + activeConnectionId, activeWorktreeId, confirmAction, conflictOperation, @@ -2628,7 +2715,7 @@ function SourceControlInner(): React.JSX.Element { const context: PullRequestGenerationContext = { worktreeId: activeWorktreeId, worktreePath, - connectionId: getConnectionId(activeWorktreeId) ?? undefined, + connectionId: activeConnectionId ?? undefined, requestId, repoId: activeRepo.id, branch: branchName, @@ -2703,6 +2790,7 @@ function SourceControlInner(): React.JSX.Element { }, [ activePullRequestGenerationKey, + activeConnectionId, activeRepo, activeRepoSettings, activeWorktreeId, @@ -2805,7 +2893,7 @@ function SourceControlInner(): React.JSX.Element { settings: activeRepoSettings, submitting: isCreatingPr, prCreationDefaults: resolvedPrCreationDefaults, - sourceControlAiActionsVisible, + sourceControlAiActionsVisible: scopedSourceControlAiActionsVisible, onBranchChangedByGeneration: handleBranchChangedByPullRequestGeneration, generation: { generating: activePullRequestGenerationRecord?.status === 'running', @@ -2822,7 +2910,7 @@ function SourceControlInner(): React.JSX.Element { }) const handleGeneratePullRequestFieldsClick = useCallback((): void => { - if (!sourceControlAiActionsVisible) { + if (!scopedSourceControlAiActionsVisible) { return } if ( @@ -2841,7 +2929,7 @@ function SourceControlInner(): React.JSX.Element { handleGeneratePullRequestFields, openPullRequestGenerationDialog, settings, - sourceControlAiActionsVisible + scopedSourceControlAiActionsVisible ]) useEffect(() => { @@ -2921,7 +3009,14 @@ function SourceControlInner(): React.JSX.Element { ]) useEffect(() => { - if (!isBranchVisible || !activeRepo || isFolder || !branchName || !activeWorktreeId) { + if ( + !isBranchVisible || + !activeRepo || + isFolder || + !hostedReviewSurfaceEnabled || + !branchName || + !activeWorktreeId + ) { setHostedReviewCreationState(null) setHostedReviewCreationRequestState(null) return @@ -2990,6 +3085,7 @@ function SourceControlInner(): React.JSX.Element { effectiveBaseRef, getHostedReviewCreationEligibility, hasUncommittedEntries, + hostedReviewSurfaceEnabled, setHostedReviewCreationRequestState, isBranchVisible, isCreatingPr, @@ -3015,6 +3111,7 @@ function SourceControlInner(): React.JSX.Element { !activeWorktreeId || !worktreePath || !hostedReviewCreation || + !hostedReviewSurfaceEnabled || prGenerating || createPrInFlightRef.current[activeWorktreeId] ) { @@ -3157,6 +3254,7 @@ function SourceControlInner(): React.JSX.Element { hostedReviewCreateCopy.reviewLabel, hostedReviewCreateCopy.titleLabel, hostedReviewCreateProvider, + hostedReviewSurfaceEnabled, prBase, prBody, prDraft, @@ -3173,7 +3271,7 @@ function SourceControlInner(): React.JSX.Element { token: CreatePrIntentRunToken, eligibility: HostedReviewCreationEligibility ): Promise => { - if (!activeRepo || !token.branch || !eligibility.canCreate) { + if (!activeRepo || !token.branch || !eligibility.canCreate || !hostedReviewSurfaceEnabled) { return false } @@ -3369,6 +3467,7 @@ function SourceControlInner(): React.JSX.Element { getCreatePrIntentOperationTarget, handlePullRequestCreated, hostedReviewCreateCopy.reviewLabel, + hostedReviewSurfaceEnabled, prBase, prBody, resolvedPrCreationDefaults.draft, @@ -3394,14 +3493,19 @@ function SourceControlInner(): React.JSX.Element { settings: activeRepoSettings, worktreeId: token.worktreeId, worktreePath: token.worktreePath, - connectionId: getConnectionId(token.worktreeId) ?? undefined + connectionId: getScopedConnectionId(token.worktreeId) }, baseRef ) setGitBranchCompareResult(token.worktreeId, requestKey, result) return result.summary.status === 'ready' ? (result.summary.commitsAhead ?? 0) : undefined }, - [activeRepoSettings, beginGitBranchCompareRequest, setGitBranchCompareResult] + [ + activeRepoSettings, + beginGitBranchCompareRequest, + getScopedConnectionId, + setGitBranchCompareResult + ] ) const readHostedReviewCreationEligibilityForIntent = useCallback( @@ -3414,7 +3518,7 @@ function SourceControlInner(): React.JSX.Element { hasUncommittedChanges: boolean upstreamStatus?: NonNullable }): Promise => { - if (!activeRepo || !token.branch) { + if (!activeRepo || !token.branch || !hostedReviewSurfaceEnabled) { return null } const result = await getHostedReviewCreationEligibility({ @@ -3446,6 +3550,7 @@ function SourceControlInner(): React.JSX.Element { activeRepo, fallbackGitHubPRNumber, getHostedReviewCreationEligibility, + hostedReviewSurfaceEnabled, linkedAzureDevOpsPR, linkedBitbucketPR, linkedGiteaPR, @@ -3489,6 +3594,7 @@ function SourceControlInner(): React.JSX.Element { !activeRepo || !activeWorktreeId || !worktreePath || + !hostedReviewSurfaceEnabled || !branchName || isExecutingBulk || isCommitting || @@ -3812,6 +3918,7 @@ function SourceControlInner(): React.JSX.Element { generateCommitMessageForCreatePrIntent, getCreatePrIntentOperationTarget, handleCommit, + hostedReviewSurfaceEnabled, isCommitting, isCreatingPr, isExecutingBulk, @@ -4065,7 +4172,12 @@ function SourceControlInner(): React.JSX.Element { // selected Source Control file in a fresh split to the right. const resolveSplitTargetGroupId = useCallback( (event?: SourceControlRowOpenEvent): string | undefined => { - if (!event || !activeWorktreeId || !isSourceControlSplitOpenModifier(event, isMac)) { + if ( + embedded || + !event || + !activeWorktreeId || + !isSourceControlSplitOpenModifier(event, isMac) + ) { return undefined } const sourceGroupId = @@ -4075,7 +4187,14 @@ function SourceControlInner(): React.JSX.Element { } return createEmptySplitGroup(activeWorktreeId, sourceGroupId, 'right') ?? undefined }, - [activeGroupIdByWorktree, activeWorktreeId, createEmptySplitGroup, groupsByWorktree, isMac] + [ + activeGroupIdByWorktree, + activeWorktreeId, + createEmptySplitGroup, + embedded, + groupsByWorktree, + isMac + ] ) // Why: a stable string signature keeps this selector referentially stable so @@ -4120,6 +4239,9 @@ function SourceControlInner(): React.JSX.Element { if (!activeWorktreeId || !worktreePath) { return } + if (!activateEmbeddedWorktreeForEditorOpen()) { + return + } const targetGroupId = resolveSplitTargetGroupId(event) const openAsPreview = shouldOpenSourceControlRowAsPreview(event, targetGroupId) if (entry.conflictKind && entry.conflictStatus) { @@ -4169,7 +4291,8 @@ function SourceControlInner(): React.JSX.Element { openConflictFile, openDiff, openFile, - setEditorViewMode + setEditorViewMode, + activateEmbeddedWorktreeForEditorOpen ] ) @@ -4235,7 +4358,7 @@ function SourceControlInner(): React.JSX.Element { } setIsExecutingBulk(true) try { - const connectionId = getConnectionId(activeWorktreeId ?? null) ?? undefined + const connectionId = activeConnectionId ?? undefined await bulkStageRuntimeGitPaths( { // Why: route staging by the repo OWNER host, not the focused runtime. @@ -4253,6 +4376,7 @@ function SourceControlInner(): React.JSX.Element { } }, [ activeRepoSettings, + activeConnectionId, worktreePath, bulkStagePaths, clearSelection, @@ -4266,7 +4390,7 @@ function SourceControlInner(): React.JSX.Element { } setIsExecutingBulk(true) try { - const connectionId = getConnectionId(activeWorktreeId ?? null) ?? undefined + const connectionId = activeConnectionId ?? undefined await bulkUnstageRuntimeGitPaths( { // Why: route unstaging by the repo OWNER host, not the focused runtime. @@ -4284,6 +4408,7 @@ function SourceControlInner(): React.JSX.Element { } }, [ activeRepoSettings, + activeConnectionId, worktreePath, bulkUnstagePaths, clearSelection, @@ -4298,7 +4423,7 @@ function SourceControlInner(): React.JSX.Element { } setIsExecutingBulk(true) try { - const connectionId = getConnectionId(activeWorktreeId ?? null) ?? undefined + const connectionId = activeConnectionId ?? undefined await bulkStageRuntimeGitPaths( { // Why: route staging by the repo OWNER host, not the focused runtime. @@ -4317,6 +4442,7 @@ function SourceControlInner(): React.JSX.Element { }, [ activeRepoSettings, + activeConnectionId, activeWorktreeId, clearSelection, isExecutingBulk, @@ -4332,7 +4458,7 @@ function SourceControlInner(): React.JSX.Element { } setIsExecutingBulk(true) try { - const connectionId = getConnectionId(activeWorktreeId ?? null) ?? undefined + const connectionId = activeConnectionId ?? undefined await bulkUnstageRuntimeGitPaths( { // Why: route unstaging by the repo OWNER host, not the focused runtime. @@ -4351,6 +4477,7 @@ function SourceControlInner(): React.JSX.Element { }, [ activeRepoSettings, + activeConnectionId, activeWorktreeId, clearSelection, isExecutingBulk, @@ -4376,7 +4503,7 @@ function SourceControlInner(): React.JSX.Element { } setIsExecutingBulk(true) try { - const connectionId = getConnectionId(activeWorktreeId ?? null) ?? undefined + const connectionId = activeConnectionId ?? undefined await bulkStageRuntimeGitPaths( { // Why: route staging by the repo OWNER host, not the focused runtime. @@ -4394,6 +4521,7 @@ function SourceControlInner(): React.JSX.Element { } }, [ activeRepoSettings, + activeConnectionId, worktreePath, isExecutingBulk, grouped, @@ -4473,7 +4601,7 @@ function SourceControlInner(): React.JSX.Element { } try { - const connectionId = getConnectionId(activeWorktreeId ?? null) ?? undefined + const connectionId = activeConnectionId ?? undefined const result = await getRuntimeGitBranchCompare( { // Why: route the branch compare by the repo OWNER host, not the focused runtime. @@ -4502,6 +4630,7 @@ function SourceControlInner(): React.JSX.Element { } }, [ activeRepoSettings, + activeConnectionId, activeWorktreeId, beginGitBranchCompareRequest, branchName, @@ -4572,7 +4701,7 @@ function SourceControlInner(): React.JSX.Element { }) try { - const connectionId = getConnectionId(worktreeId) ?? undefined + const connectionId = getScopedConnectionId(worktreeId) const result = await getRuntimeGitHistory( { // Why: route the history read by the repo OWNER host, not the focused runtime. @@ -4606,6 +4735,7 @@ function SourceControlInner(): React.JSX.Element { activeRepoSettings, activeWorktreeId, effectiveBaseRef, + getScopedConnectionId, isBranchVisible, isFolder, isGitHistoryExpanded, @@ -4679,7 +4809,7 @@ function SourceControlInner(): React.JSX.Element { if (!activeWorktreeId || !worktreePath || isFolder || !isBranchVisible) { return } - const connectionId = getConnectionId(activeWorktreeId) ?? undefined + const connectionId = activeConnectionId ?? undefined void fetchUpstreamStatus( activeWorktreeId, worktreePath, @@ -4689,6 +4819,7 @@ function SourceControlInner(): React.JSX.Element { ) }, [ activeRepoSettings, + activeConnectionId, activeWorktree?.pushTarget, activeWorktreeId, fetchUpstreamStatus, @@ -4731,6 +4862,9 @@ function SourceControlInner(): React.JSX.Element { ) { return } + if (!activateEmbeddedWorktreeForEditorOpen()) { + return + } const targetGroupId = resolveSplitTargetGroupId(event) openBranchDiff( activeWorktreeId, @@ -4741,7 +4875,14 @@ function SourceControlInner(): React.JSX.Element { { targetGroupId, preview: shouldOpenSourceControlRowAsPreview(event, targetGroupId) } ) }, - [activeWorktreeId, branchSummary, openBranchDiff, resolveSplitTargetGroupId, worktreePath] + [ + activeWorktreeId, + branchSummary, + openBranchDiff, + resolveSplitTargetGroupId, + worktreePath, + activateEmbeddedWorktreeForEditorOpen + ] ) const { loadCommitFiles, openHistoryCommitDiff, openCommitFile, handleCommitAction } = @@ -4749,7 +4890,9 @@ function SourceControlInner(): React.JSX.Element { activeWorktreeId, worktreePath, activeRepoSettings, - resolveSplitTargetGroupId + resolveSplitTargetGroupId, + getConnectionIdForWorktree: getScopedConnectionId, + activateWorktreeForEditorOpen: activateEmbeddedWorktreeForEditorOpen }) // Why: a note's filePath is the same relative path used by GitStatusEntry / @@ -4768,6 +4911,9 @@ function SourceControlInner(): React.JSX.Element { if (!activeWorktreeId || !worktreePath) { return } + if (!activateEmbeddedWorktreeForEditorOpen()) { + return + } const filePath = comment.filePath const commentId = comment.id // Defensively clear any dangling prior scroll request before routing @@ -4853,7 +4999,8 @@ function SourceControlInner(): React.JSX.Element { setScrollToDiffCommentId, setMarkdownViewMode, setPendingEditorReveal, - worktreePath + worktreePath, + activateEmbeddedWorktreeForEditorOpen ] ) @@ -4863,7 +5010,7 @@ function SourceControlInner(): React.JSX.Element { return } try { - const connectionId = getConnectionId(activeWorktreeId ?? null) ?? undefined + const connectionId = activeConnectionId ?? undefined await stageRuntimeGitPath( { // Why: route staging by the repo OWNER host, not the focused runtime. @@ -4879,7 +5026,13 @@ function SourceControlInner(): React.JSX.Element { // git operation failed silently } }, - [activeRepoSettings, worktreePath, activeWorktreeId, refreshActiveGitStatusAfterMutation] + [ + activeRepoSettings, + activeConnectionId, + worktreePath, + activeWorktreeId, + refreshActiveGitStatusAfterMutation + ] ) const handleUnstage = useCallback( @@ -4888,7 +5041,7 @@ function SourceControlInner(): React.JSX.Element { return } try { - const connectionId = getConnectionId(activeWorktreeId ?? null) ?? undefined + const connectionId = activeConnectionId ?? undefined await unstageRuntimeGitPath( { // Why: route unstaging by the repo OWNER host, not the focused runtime. @@ -4904,7 +5057,13 @@ function SourceControlInner(): React.JSX.Element { // git operation failed silently } }, - [activeRepoSettings, worktreePath, activeWorktreeId, refreshActiveGitStatusAfterMutation] + [ + activeRepoSettings, + activeConnectionId, + worktreePath, + activeWorktreeId, + refreshActiveGitStatusAfterMutation + ] ) // Why: split into two variants — `discardSingle` throws so bulk callers can @@ -4916,8 +5075,7 @@ function SourceControlInner(): React.JSX.Element { if (!worktreePath || !activeWorktreeId) { return } - const runtimeEnvironmentId = - useAppStore.getState().settings?.activeRuntimeEnvironmentId?.trim() || null + const runtimeEnvironmentId = activeRepoSettings?.activeRuntimeEnvironmentId?.trim() || null // Why: git discard replaces the working tree version of this file. Any // pending editor autosave must be quiesced first so it cannot recreate // the discarded edits after git restores the file. @@ -4927,7 +5085,7 @@ function SourceControlInner(): React.JSX.Element { relativePath: filePath, runtimeEnvironmentId }) - const connectionId = getConnectionId(activeWorktreeId ?? null) ?? undefined + const connectionId = activeConnectionId ?? undefined await discardRuntimeGitPath( { // Why: route the discard by the repo OWNER host, not the focused runtime. @@ -4945,7 +5103,7 @@ function SourceControlInner(): React.JSX.Element { runtimeEnvironmentId }) }, - [activeRepoSettings, activeWorktreeId, worktreePath] + [activeRepoSettings, activeConnectionId, activeWorktreeId, worktreePath] ) const discardMany = useCallback( @@ -4953,8 +5111,7 @@ function SourceControlInner(): React.JSX.Element { if (!worktreePath || !activeWorktreeId) { return } - const runtimeEnvironmentId = - useAppStore.getState().settings?.activeRuntimeEnvironmentId?.trim() || null + const runtimeEnvironmentId = activeRepoSettings?.activeRuntimeEnvironmentId?.trim() || null // Why: bulk discard replaces many working-tree files at once. Quiesce // any matching editor autosaves before git mutates the files so a delayed // save cannot recreate edits after the restore. @@ -4968,7 +5125,7 @@ function SourceControlInner(): React.JSX.Element { }) ) ) - const connectionId = getConnectionId(activeWorktreeId) ?? undefined + const connectionId = activeConnectionId ?? undefined await bulkDiscardRuntimeGitPaths( { // Why: route the discard by the repo OWNER host, not the focused runtime. @@ -4988,7 +5145,7 @@ function SourceControlInner(): React.JSX.Element { }) } }, - [activeRepoSettings, activeWorktreeId, worktreePath] + [activeRepoSettings, activeConnectionId, activeWorktreeId, worktreePath] ) const handleDiscard = useCallback( @@ -5024,7 +5181,7 @@ function SourceControlInner(): React.JSX.Element { } setIsExecutingBulk(true) try { - const connectionId = getConnectionId(activeWorktreeId) ?? undefined + const connectionId = activeConnectionId ?? undefined // Why: `onError` fires once per failure — both for the bulk-unstage // pre-step and for each per-file discard failure. Aggregate into one // toast after the sequence completes so a partial failure across N @@ -5093,6 +5250,7 @@ function SourceControlInner(): React.JSX.Element { }, [ activeRepoSettings, + activeConnectionId, worktreePath, activeWorktreeId, grouped, @@ -5249,12 +5407,14 @@ function SourceControlInner(): React.JSX.Element { )}
- + {!embedded && ( + + )} {diffCommentCount > 0 && ( @@ -5356,7 +5516,7 @@ function SourceControlInner(): React.JSX.Element { { e.stopPropagation() if (activeWorktreeId && worktreePath && branchSummary) { + if (!activateEmbeddedWorktreeForEditorOpen()) { + return + } openBranchAllDiffs(activeWorktreeId, worktreePath, branchSummary) } }} @@ -5936,9 +6107,14 @@ function SourceControlInner(): React.JSX.Element {
{ - if (baseRefOwnedByWorktree && activeWorktreeId) { + // Why: embedded folder sections can share repo ids across hosts; + // worktree-scoped refs avoid updating the wrong host's repo row. + if ((embedded || baseRefOwnedByWorktree) && activeWorktreeId) { void updateWorktreeMeta(activeWorktreeId, { baseRef: ref }) } else { void updateRepo(activeRepo.id, { worktreeBaseRef: ref }) @@ -5947,7 +6123,9 @@ function SourceControlInner(): React.JSX.Element { window.setTimeout(() => void refreshBranchCompare(), 0) }} onUsePrimary={() => { - if (baseRefOwnedByWorktree && activeWorktreeId) { + // Why: embedded folder sections can share repo ids across hosts; + // worktree-scoped refs avoid updating the wrong host's repo row. + if ((embedded || baseRefOwnedByWorktree) && activeWorktreeId) { void updateWorktreeMeta(activeWorktreeId, { baseRef: undefined }) } else { void updateRepo(activeRepo.id, { worktreeBaseRef: undefined }) @@ -5960,7 +6138,7 @@ function SourceControlInner(): React.JSX.Element {