Follow the active terminal's worktree in the Checks panel (#6799)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -22,6 +22,7 @@ import {
|
||||
} from '@/store/slices/github'
|
||||
import { getGitHubPRCacheKey, getGitHubRepoCacheKey } from '@/store/slices/github-cache-key'
|
||||
import { useActiveWorktree, useRepoById } from '@/store/selectors'
|
||||
import { useChecksPanelTerminalWorktree } from './use-checks-panel-terminal-worktree'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { openHttpLink } from '@/lib/http-link-routing'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -366,8 +367,22 @@ async function resolveGitLabMRDiscussionForChecks(args: {
|
||||
}
|
||||
|
||||
export default function ChecksPanel(): React.JSX.Element {
|
||||
const activeWorktree = useActiveWorktree()
|
||||
const activeWorktreeId = useAppStore((s) => s.activeWorktreeId)
|
||||
// Why: the sidebar stays mounted when closed (for performance). Gate
|
||||
// polling on visibility so we don't fetch checks/comments — or poll the
|
||||
// terminal cwd — in the background when the panel isn't visible.
|
||||
const rightSidebarOpen = useAppStore((s) => s.rightSidebarOpen)
|
||||
const rightSidebarTab = useAppStore((s) => s.rightSidebarTab)
|
||||
const isPanelVisible = rightSidebarOpen && rightSidebarTab === 'checks'
|
||||
|
||||
// Follow the active terminal's cwd so linked-PR/checks state tracks the
|
||||
// worktree the terminal is actually operating in (e.g. across a stack),
|
||||
// falling back to the sidebar's selected worktree.
|
||||
const defaultActiveWorktree = useActiveWorktree()
|
||||
const { worktree: activeWorktree } = useChecksPanelTerminalWorktree({
|
||||
defaultActiveWorktree,
|
||||
isPanelVisible
|
||||
})
|
||||
const activeWorktreeId = activeWorktree?.id ?? null
|
||||
const repo = useRepoById(activeWorktree?.repoId ?? null)
|
||||
const activeConnectionId = activeWorktreeId
|
||||
? (getConnectionId(activeWorktreeId) ?? repo?.connectionId ?? null)
|
||||
@@ -402,13 +417,6 @@ export default function ChecksPanel(): React.JSX.Element {
|
||||
const updateWorktreeGitIdentity = useAppStore((s) => s.updateWorktreeGitIdentity)
|
||||
const openModal = useAppStore((s) => s.openModal)
|
||||
|
||||
// Why: the sidebar stays mounted when closed (for performance). Gate
|
||||
// polling on visibility so we don't fetch checks/comments in the background
|
||||
// when the panel isn't visible to the user.
|
||||
const rightSidebarOpen = useAppStore((s) => s.rightSidebarOpen)
|
||||
const rightSidebarTab = useAppStore((s) => s.rightSidebarTab)
|
||||
const isPanelVisible = rightSidebarOpen && rightSidebarTab === 'checks'
|
||||
|
||||
const fetchPRChecks = useAppStore((s) => s.fetchPRChecks)
|
||||
const fetchPRCheckDetails = useAppStore((s) => s.fetchPRCheckDetails)
|
||||
const fetchPRComments = useAppStore((s) => s.fetchPRComments)
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { Worktree } from '../../../../shared/types'
|
||||
import {
|
||||
resolveChecksPanelTerminalPtyId,
|
||||
resolveChecksPanelWorktreeFromTerminalCwd
|
||||
} from './checks-panel-terminal-worktree'
|
||||
|
||||
function worktree(overrides: Partial<Worktree>): Worktree {
|
||||
return {
|
||||
id: overrides.id ?? `repo-1::${overrides.path ?? '/repo'}`,
|
||||
repoId: overrides.repoId ?? 'repo-1',
|
||||
path: overrides.path ?? '/repo',
|
||||
displayName: overrides.displayName ?? 'Repo',
|
||||
priorWorktreeIds: overrides.priorWorktreeIds,
|
||||
isArchived: overrides.isArchived ?? false
|
||||
} as Worktree
|
||||
}
|
||||
|
||||
describe('resolveChecksPanelTerminalPtyId', () => {
|
||||
it('uses the active split-pane leaf when it has a live PTY', () => {
|
||||
expect(
|
||||
resolveChecksPanelTerminalPtyId({
|
||||
activeTabId: 'tab-1',
|
||||
ptyIdsByTabId: { 'tab-1': ['pty-left', 'pty-right'] },
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-1': {
|
||||
root: null,
|
||||
activeLeafId: 'leaf-right',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: {
|
||||
'leaf-left': 'pty-left',
|
||||
'leaf-right': 'pty-right'
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
).toBe('pty-right')
|
||||
})
|
||||
|
||||
it('falls back to a live layout PTY before using the last live tab PTY', () => {
|
||||
expect(
|
||||
resolveChecksPanelTerminalPtyId({
|
||||
activeTabId: 'tab-1',
|
||||
ptyIdsByTabId: { 'tab-1': ['pty-live', 'pty-other'] },
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-1': {
|
||||
root: null,
|
||||
activeLeafId: 'leaf-stale',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: {
|
||||
'leaf-stale': 'pty-stale',
|
||||
'leaf-live': 'pty-live'
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
).toBe('pty-live')
|
||||
})
|
||||
|
||||
it('falls back to the last live tab PTY when the layout has no live PTY', () => {
|
||||
expect(
|
||||
resolveChecksPanelTerminalPtyId({
|
||||
activeTabId: 'tab-1',
|
||||
ptyIdsByTabId: { 'tab-1': ['pty-left', 'pty-right'] },
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-1': {
|
||||
root: null,
|
||||
activeLeafId: 'leaf-stale',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: {
|
||||
'leaf-stale': 'pty-stale'
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
).toBe('pty-right')
|
||||
})
|
||||
|
||||
it('returns null when the active tab has no live PTY', () => {
|
||||
expect(
|
||||
resolveChecksPanelTerminalPtyId({
|
||||
activeTabId: 'tab-1',
|
||||
ptyIdsByTabId: { 'tab-1': [] },
|
||||
terminalLayoutsByTabId: {}
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveChecksPanelWorktreeFromTerminalCwd', () => {
|
||||
it('matches the deepest worktree that contains the terminal cwd', () => {
|
||||
const parent = worktree({ id: 'repo-1::/repo', path: '/repo', displayName: 'Parent' })
|
||||
const child = worktree({
|
||||
id: 'repo-1::/repo/packages/app',
|
||||
path: '/repo/packages/app',
|
||||
displayName: 'Child'
|
||||
})
|
||||
|
||||
expect(
|
||||
resolveChecksPanelWorktreeFromTerminalCwd('/repo/packages/app/src', [parent, child])
|
||||
).toBe(child)
|
||||
})
|
||||
|
||||
it('does not match a sibling whose path is a string prefix of the cwd', () => {
|
||||
const app = worktree({ id: 'repo-1::/repo/app', path: '/repo/app', displayName: 'App' })
|
||||
const application = worktree({
|
||||
id: 'repo-1::/repo/application',
|
||||
path: '/repo/application',
|
||||
displayName: 'Application'
|
||||
})
|
||||
|
||||
// `/repo/application` starts with `/repo/app` as a string, but the
|
||||
// separator boundary must keep the cwd from matching the shorter sibling.
|
||||
expect(
|
||||
resolveChecksPanelWorktreeFromTerminalCwd('/repo/application/src', [app, application])
|
||||
).toBe(application)
|
||||
})
|
||||
|
||||
it('matches prior worktree paths after a path-derived id changes', () => {
|
||||
const renamed = worktree({
|
||||
id: 'repo-1::/new/path',
|
||||
path: '/new/path',
|
||||
priorWorktreeIds: ['repo-1::/old/path']
|
||||
})
|
||||
|
||||
expect(resolveChecksPanelWorktreeFromTerminalCwd('/old/path/src', [renamed])).toBe(renamed)
|
||||
})
|
||||
|
||||
it('matches Linux cwd under a WSL UNC worktree path', () => {
|
||||
const wsl = worktree({
|
||||
id: 'repo-1:://wsl.localhost/Ubuntu/home/me/project',
|
||||
path: '//wsl.localhost/Ubuntu/home/me/project'
|
||||
})
|
||||
|
||||
expect(resolveChecksPanelWorktreeFromTerminalCwd('/home/me/project/src', [wsl])).toBe(wsl)
|
||||
})
|
||||
|
||||
it('does not match relative or empty cwd values', () => {
|
||||
const target = worktree({ path: '/repo' })
|
||||
|
||||
expect(resolveChecksPanelWorktreeFromTerminalCwd('repo/src', [target])).toBeNull()
|
||||
expect(resolveChecksPanelWorktreeFromTerminalCwd('', [target])).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,108 @@
|
||||
import { parseWslUncPath } from '../../../../shared/wsl-paths'
|
||||
import { splitWorktreeIdForFilesystem } from '../../../../shared/worktree-id'
|
||||
import {
|
||||
isPathInsideOrEqual,
|
||||
isRuntimePathAbsolute,
|
||||
normalizeRuntimePathForComparison
|
||||
} from '../../../../shared/cross-platform-path'
|
||||
import type { TerminalLayoutSnapshot, Worktree } from '../../../../shared/types'
|
||||
|
||||
type TerminalPtyContext = {
|
||||
activeTabId: string | null
|
||||
ptyIdsByTabId: Record<string, readonly string[] | undefined>
|
||||
terminalLayoutsByTabId: Record<string, TerminalLayoutSnapshot | undefined>
|
||||
}
|
||||
|
||||
type WorktreeCandidate = {
|
||||
worktree: Worktree
|
||||
path: string
|
||||
source: 'current-path' | 'prior-path'
|
||||
}
|
||||
|
||||
/** Resolve the active terminal PTY that should provide Checks panel cwd context. */
|
||||
export function resolveChecksPanelTerminalPtyId(context: TerminalPtyContext): string | null {
|
||||
if (!context.activeTabId) {
|
||||
return null
|
||||
}
|
||||
|
||||
const livePtyIds = context.ptyIdsByTabId[context.activeTabId] ?? []
|
||||
if (livePtyIds.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const layout = context.terminalLayoutsByTabId[context.activeTabId]
|
||||
const activeLeafPtyId = layout?.activeLeafId ? layout.ptyIdsByLeafId?.[layout.activeLeafId] : null
|
||||
if (activeLeafPtyId && livePtyIds.includes(activeLeafPtyId)) {
|
||||
return activeLeafPtyId
|
||||
}
|
||||
|
||||
const firstLiveLayoutPtyId = Object.values(layout?.ptyIdsByLeafId ?? {}).find((ptyId) =>
|
||||
livePtyIds.includes(ptyId)
|
||||
)
|
||||
// Last tab PTY is the newest terminal when the split-pane layout is stale or unavailable.
|
||||
return firstLiveLayoutPtyId ?? livePtyIds.at(-1) ?? null
|
||||
}
|
||||
|
||||
/** Resolve the worktree whose current or prior path contains the terminal cwd. */
|
||||
export function resolveChecksPanelWorktreeFromTerminalCwd(
|
||||
cwd: string | null,
|
||||
worktrees: readonly Worktree[]
|
||||
): Worktree | null {
|
||||
const terminalCwd = cwd?.trim()
|
||||
if (!terminalCwd || !isRuntimePathAbsolute(terminalCwd)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const best = buildWorktreeCandidates(worktrees)
|
||||
.filter((candidate) => isTerminalCwdInsideWorktree(candidate.path, terminalCwd))
|
||||
.sort(compareWorktreeCandidates)[0]
|
||||
|
||||
return best?.worktree ?? null
|
||||
}
|
||||
|
||||
function buildWorktreeCandidates(worktrees: readonly Worktree[]): WorktreeCandidate[] {
|
||||
const candidates: WorktreeCandidate[] = []
|
||||
for (const worktree of worktrees) {
|
||||
if (hasUsablePath(worktree.path)) {
|
||||
candidates.push({ worktree, path: worktree.path, source: 'current-path' })
|
||||
}
|
||||
|
||||
for (const priorWorktreeId of worktree.priorWorktreeIds ?? []) {
|
||||
const parsed = splitWorktreeIdForFilesystem(priorWorktreeId)
|
||||
if (!parsed || parsed.repoId !== worktree.repoId || !hasUsablePath(parsed.worktreePath)) {
|
||||
continue
|
||||
}
|
||||
candidates.push({ worktree, path: parsed.worktreePath, source: 'prior-path' })
|
||||
}
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
function hasUsablePath(pathValue: string): boolean {
|
||||
const trimmed = pathValue.trim()
|
||||
return Boolean(trimmed && isRuntimePathAbsolute(trimmed))
|
||||
}
|
||||
|
||||
function isTerminalCwdInsideWorktree(worktreePath: string, terminalCwd: string): boolean {
|
||||
if (isPathInsideOrEqual(worktreePath, terminalCwd)) {
|
||||
return true
|
||||
}
|
||||
|
||||
// Windows hosts store WSL worktrees as UNC paths, while the terminal reports Linux paths.
|
||||
const wslPath = parseWslUncPath(worktreePath)
|
||||
return wslPath ? isPathInsideOrEqual(wslPath.linuxPath, terminalCwd) : false
|
||||
}
|
||||
|
||||
function compareWorktreeCandidates(left: WorktreeCandidate, right: WorktreeCandidate): number {
|
||||
const lengthDifference =
|
||||
normalizeRuntimePathForComparison(right.path).length -
|
||||
normalizeRuntimePathForComparison(left.path).length
|
||||
if (lengthDifference !== 0) {
|
||||
return lengthDifference
|
||||
}
|
||||
if (left.source === right.source) {
|
||||
return 0
|
||||
}
|
||||
// Prefer the current path when a renamed worktree still has a matching prior path.
|
||||
return left.source === 'current-path' ? -1 : 1
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, createElement } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Repo, Worktree } from '../../../../shared/types'
|
||||
import { useAppStore } from '@/store'
|
||||
import type { AppState } from '@/store/types'
|
||||
import { makeWorktree, TEST_REPO } from '@/store/slices/store-test-helpers'
|
||||
import { useChecksPanelTerminalWorktree } from './use-checks-panel-terminal-worktree'
|
||||
|
||||
const initialAppState = useAppStore.getInitialState()
|
||||
|
||||
const REPO_ID = 'repo1'
|
||||
const PARENT_PATH = '/repo1'
|
||||
const CHILD_PATH = '/repo1/packages/app'
|
||||
const PARENT_ID = `${REPO_ID}::${PARENT_PATH}`
|
||||
const CHILD_ID = `${REPO_ID}::${CHILD_PATH}`
|
||||
|
||||
const repo: Repo = { ...TEST_REPO, kind: 'git', connectionId: null }
|
||||
const parentWorktree: Worktree = makeWorktree({ id: PARENT_ID, repoId: REPO_ID, path: PARENT_PATH })
|
||||
const childWorktree: Worktree = makeWorktree({ id: CHILD_ID, repoId: REPO_ID, path: CHILD_PATH })
|
||||
|
||||
const getCwdMock = vi.fn<(id: string) => Promise<string>>()
|
||||
|
||||
const roots: Root[] = []
|
||||
let latest: ReturnType<typeof useChecksPanelTerminalWorktree> | null = null
|
||||
|
||||
function HookProbe(props: {
|
||||
defaultActiveWorktree: Worktree | null
|
||||
isPanelVisible: boolean
|
||||
}): null {
|
||||
latest = useChecksPanelTerminalWorktree({
|
||||
defaultActiveWorktree: props.defaultActiveWorktree,
|
||||
isPanelVisible: props.isPanelVisible
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
async function renderHook(
|
||||
defaultActiveWorktree: Worktree | null,
|
||||
isPanelVisible = true
|
||||
): Promise<void> {
|
||||
const container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
const root = createRoot(container)
|
||||
roots.push(root)
|
||||
await act(async () => {
|
||||
root.render(createElement(HookProbe, { defaultActiveWorktree, isPanelVisible }))
|
||||
})
|
||||
}
|
||||
|
||||
async function flushMicrotasks(): Promise<void> {
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
getCwdMock.mockReset().mockResolvedValue('')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- test-only window.api shim
|
||||
;(window as any).api = { pty: { getCwd: getCwdMock } }
|
||||
|
||||
useAppStore.setState(initialAppState, true)
|
||||
useAppStore.setState({
|
||||
activeWorktreeId: PARENT_ID,
|
||||
worktreesByRepo: { [REPO_ID]: [parentWorktree, childWorktree] },
|
||||
repos: [repo],
|
||||
activeTabId: 'tab-1',
|
||||
ptyIdsByTabId: { 'tab-1': ['pty-1'] }
|
||||
} as Partial<AppState>)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
roots.splice(0).forEach((root) => act(() => root.unmount()))
|
||||
document.body.replaceChildren()
|
||||
useAppStore.setState(initialAppState, true)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('useChecksPanelTerminalWorktree', () => {
|
||||
it('follows the active terminal cwd to the deepest matching worktree', async () => {
|
||||
getCwdMock.mockResolvedValue(`${CHILD_PATH}/src`)
|
||||
|
||||
await renderHook(parentWorktree)
|
||||
await flushMicrotasks()
|
||||
|
||||
expect(getCwdMock).toHaveBeenCalledWith('pty-1')
|
||||
expect(latest?.worktree).toBe(childWorktree)
|
||||
})
|
||||
|
||||
it('returns the default worktree (no blank flicker) while the cwd is unresolved', async () => {
|
||||
// getCwd stays pending: the panel must keep showing the sidebar worktree.
|
||||
getCwdMock.mockReturnValue(new Promise<string>(() => {}))
|
||||
|
||||
await renderHook(parentWorktree)
|
||||
await flushMicrotasks()
|
||||
|
||||
expect(latest?.worktree).toBe(parentWorktree)
|
||||
})
|
||||
|
||||
it('does not poll when the panel is hidden, and uses the default worktree', async () => {
|
||||
getCwdMock.mockResolvedValue(`${CHILD_PATH}/src`)
|
||||
|
||||
await renderHook(parentWorktree, false)
|
||||
await flushMicrotasks()
|
||||
|
||||
expect(getCwdMock).not.toHaveBeenCalled()
|
||||
expect(latest?.worktree).toBe(parentWorktree)
|
||||
})
|
||||
|
||||
it('does not poll remote-runtime terminals', async () => {
|
||||
useAppStore.setState({ ptyIdsByTabId: { 'tab-1': ['remote:host:pty-1'] } } as Partial<AppState>)
|
||||
|
||||
await renderHook(parentWorktree)
|
||||
await flushMicrotasks()
|
||||
|
||||
expect(getCwdMock).not.toHaveBeenCalled()
|
||||
expect(latest?.worktree).toBe(parentWorktree)
|
||||
})
|
||||
|
||||
it('keeps the default worktree when the cwd is outside every worktree', async () => {
|
||||
getCwdMock.mockResolvedValue('/tmp/scratch')
|
||||
|
||||
await renderHook(parentWorktree)
|
||||
await flushMicrotasks()
|
||||
|
||||
expect(latest?.worktree).toBe(parentWorktree)
|
||||
})
|
||||
|
||||
it('does not poll an SSH terminal (its cwd is on the relay host)', async () => {
|
||||
useAppStore.setState({
|
||||
ptyIdsByTabId: { 'tab-1': ['ssh:target-1@@pty-9'] }
|
||||
} as Partial<AppState>)
|
||||
|
||||
await renderHook(parentWorktree)
|
||||
await flushMicrotasks()
|
||||
|
||||
expect(getCwdMock).not.toHaveBeenCalled()
|
||||
expect(latest?.worktree).toBe(parentWorktree)
|
||||
})
|
||||
|
||||
it('follows a local-host worktree that overrides its runtime repo host', async () => {
|
||||
const RUNTIME_REPO_ID = 'runtimeRepo'
|
||||
const runtimeRepo: Repo = {
|
||||
...TEST_REPO,
|
||||
id: RUNTIME_REPO_ID,
|
||||
path: '/runtime-repo',
|
||||
kind: 'git',
|
||||
connectionId: null,
|
||||
executionHostId: 'runtime:env-1'
|
||||
}
|
||||
// hostId 'local' overrides the runtime repo owner for this worktree.
|
||||
const localOnRuntime = makeWorktree({
|
||||
id: `${RUNTIME_REPO_ID}::/runtime-repo/app`,
|
||||
repoId: RUNTIME_REPO_ID,
|
||||
path: '/runtime-repo/app',
|
||||
hostId: 'local'
|
||||
})
|
||||
useAppStore.setState({
|
||||
worktreesByRepo: { [REPO_ID]: [parentWorktree], [RUNTIME_REPO_ID]: [localOnRuntime] },
|
||||
repos: [repo, runtimeRepo]
|
||||
} as Partial<AppState>)
|
||||
getCwdMock.mockResolvedValue('/runtime-repo/app/src')
|
||||
|
||||
await renderHook(parentWorktree)
|
||||
await flushMicrotasks()
|
||||
|
||||
expect(latest?.worktree).toBe(localOnRuntime)
|
||||
})
|
||||
|
||||
it('does not match an SSH worktree that shares the local cwd path', async () => {
|
||||
// A local PTY cwd must never resolve to a same-path remote worktree — that
|
||||
// would surface the wrong host's linked PR. The ONLY worktree at this path
|
||||
// is the SSH one, so a correct host filter must fall back to the default
|
||||
// (and this assertion fails if host scoping is removed).
|
||||
const SSH_REPO_ID = 'sshRepo'
|
||||
const SSH_PATH = '/shared/project'
|
||||
const sshRepo: Repo = {
|
||||
...TEST_REPO,
|
||||
id: SSH_REPO_ID,
|
||||
path: SSH_PATH,
|
||||
kind: 'git',
|
||||
connectionId: 'ssh-target-1'
|
||||
}
|
||||
const sshWorktree = makeWorktree({
|
||||
id: `${SSH_REPO_ID}::${SSH_PATH}`,
|
||||
repoId: SSH_REPO_ID,
|
||||
path: SSH_PATH
|
||||
})
|
||||
useAppStore.setState({
|
||||
worktreesByRepo: { [REPO_ID]: [parentWorktree, childWorktree], [SSH_REPO_ID]: [sshWorktree] },
|
||||
repos: [repo, sshRepo]
|
||||
} as Partial<AppState>)
|
||||
getCwdMock.mockResolvedValue(`${SSH_PATH}/src`)
|
||||
|
||||
await renderHook(parentWorktree)
|
||||
await flushMicrotasks()
|
||||
|
||||
// The SSH worktree is filtered out; nothing local matches → default.
|
||||
expect(latest?.worktree).toBe(parentWorktree)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useShallow } from 'zustand/react/shallow'
|
||||
import { useAppStore } from '@/store'
|
||||
import { useAllWorktrees, useRepoMap } from '@/store/selectors'
|
||||
import { isRemoteRuntimePtyId } from '@/runtime/runtime-terminal-inspection'
|
||||
import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id'
|
||||
import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host'
|
||||
import type { Worktree } from '../../../../shared/types'
|
||||
import {
|
||||
resolveChecksPanelTerminalPtyId,
|
||||
resolveChecksPanelWorktreeFromTerminalCwd
|
||||
} from './checks-panel-terminal-worktree'
|
||||
|
||||
// Why poll past the main-side cache: getCwd coalesces and caches per-pid for
|
||||
// 1.5s, and on macOS a cache miss shells out to `lsof`. Polling slower than
|
||||
// that TTL keeps this from spawning a subprocess on every tick while still
|
||||
// noticing a plain `cd`.
|
||||
const TERMINAL_CWD_POLL_MS = 4000
|
||||
|
||||
type ChecksPanelTerminalWorktree = {
|
||||
/** Worktree the active terminal is operating in, or the caller's fallback. */
|
||||
worktree: Worktree | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the worktree the active terminal is working in so the Checks panel
|
||||
* can follow the terminal's cwd across a stack of worktrees.
|
||||
*
|
||||
* Reads the cwd authoritatively from the local PTY's process (getCwd) rather
|
||||
* than the shell-reported OSC 7 cwd: a local terminal running `ssh`/tmux emits
|
||||
* the *remote* shell's OSC 7 path, which must not resolve a local worktree.
|
||||
* getCwd reads the local shell pid, so it is correct for that case. Remote
|
||||
* runtime PTYs are skipped (their cwd lives on the relay host). Polling is
|
||||
* gated on panel visibility, so a hidden panel does no background work and the
|
||||
* caller's fallback worktree is used.
|
||||
*
|
||||
* Resolution is scoped to locally-executing worktrees: the cwd comes from a
|
||||
* local PTY, and worktree paths are not unique across hosts (an SSH worktree
|
||||
* can share `/home/me/project` with a local one), so matching across hosts
|
||||
* could surface the wrong host's linked PR.
|
||||
*/
|
||||
export function useChecksPanelTerminalWorktree(args: {
|
||||
defaultActiveWorktree: Worktree | null
|
||||
isPanelVisible: boolean
|
||||
}): ChecksPanelTerminalWorktree {
|
||||
const { defaultActiveWorktree, isPanelVisible } = args
|
||||
const allWorktrees = useAllWorktrees()
|
||||
const repoMap = useRepoMap()
|
||||
const localWorktrees = useMemo(
|
||||
() =>
|
||||
allWorktrees.filter((worktree) => {
|
||||
// Why hostId first: a worktree can override its repo's execution host
|
||||
// (e.g. a local-host worktree under a runtime repo). Mirrors the
|
||||
// resolution in worktree-parent-candidates.ts.
|
||||
const repo = repoMap.get(worktree.repoId)
|
||||
const hostId = worktree.hostId ?? (repo ? getRepoExecutionHostId(repo) : null)
|
||||
return hostId === LOCAL_EXECUTION_HOST_ID
|
||||
}),
|
||||
[allWorktrees, repoMap]
|
||||
)
|
||||
|
||||
const activeTerminalPtyId = useAppStore(
|
||||
useShallow((s) =>
|
||||
resolveChecksPanelTerminalPtyId({
|
||||
activeTabId: s.activeTabId,
|
||||
ptyIdsByTabId: s.ptyIdsByTabId,
|
||||
terminalLayoutsByTabId: s.terminalLayoutsByTabId
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
// Only poll local PTYs. Remote-runtime (`remote:`) and SSH (`ssh:`) PTYs
|
||||
// report a cwd on their relay host, which must not resolve a local worktree.
|
||||
const isLocalTerminalPty =
|
||||
activeTerminalPtyId !== null &&
|
||||
!isRemoteRuntimePtyId(activeTerminalPtyId) &&
|
||||
parseAppSshPtyId(activeTerminalPtyId) === null
|
||||
const shouldPollCwd = isPanelVisible && isLocalTerminalPty
|
||||
|
||||
const [polledCwd, setPolledCwd] = useState<{ ptyId: string; cwd: string | null } | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!shouldPollCwd || activeTerminalPtyId === null) {
|
||||
setPolledCwd(null)
|
||||
return
|
||||
}
|
||||
|
||||
let disposed = false
|
||||
const commit = (cwd: string | null): void => {
|
||||
if (disposed) {
|
||||
return
|
||||
}
|
||||
// Keep the prior state object when nothing changed so an unchanged cwd
|
||||
// doesn't re-render the (large) Checks panel every poll tick.
|
||||
setPolledCwd((prev) =>
|
||||
prev?.ptyId === activeTerminalPtyId && prev.cwd === cwd
|
||||
? prev
|
||||
: { ptyId: activeTerminalPtyId, cwd }
|
||||
)
|
||||
}
|
||||
const refresh = async (): Promise<void> => {
|
||||
try {
|
||||
const cwd = (await window.api.pty.getCwd(activeTerminalPtyId)).trim()
|
||||
commit(cwd || null)
|
||||
} catch {
|
||||
commit(null)
|
||||
}
|
||||
}
|
||||
|
||||
void refresh()
|
||||
const interval = window.setInterval(refresh, TERMINAL_CWD_POLL_MS)
|
||||
return () => {
|
||||
disposed = true
|
||||
window.clearInterval(interval)
|
||||
}
|
||||
}, [activeTerminalPtyId, shouldPollCwd])
|
||||
|
||||
// Ignore a stale result captured for a previously-active PTY.
|
||||
const terminalCwd = polledCwd?.ptyId === activeTerminalPtyId ? polledCwd.cwd : null
|
||||
|
||||
const terminalCwdWorktree = useMemo(
|
||||
() => resolveChecksPanelWorktreeFromTerminalCwd(terminalCwd, localWorktrees),
|
||||
[localWorktrees, terminalCwd]
|
||||
)
|
||||
|
||||
// Fall back to the sidebar's active worktree (never blank) while the terminal
|
||||
// cwd is still resolving or maps to no known worktree.
|
||||
return { worktree: terminalCwdWorktree ?? defaultActiveWorktree }
|
||||
}
|
||||
Reference in New Issue
Block a user