Reduce port and agent status polling churn (#2516)

This commit is contained in:
Neil
2026-05-21 12:48:49 -07:00
committed by GitHub
parent 708c87d218
commit a7b4e19b37
9 changed files with 442 additions and 164 deletions
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { useAppStore } from '@/store'
import { getHasAnyWorktreesFromState } from '@/store/selectors'
import { getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client'
import {
scanWorkspacePortsForTarget,
@@ -20,9 +21,7 @@ function makeUnavailableScan(reason: string): WorkspacePortScanResult {
export function WorkspacePortScanner(): null {
const settings = useAppStore((s) => s.settings)
const hasWorktrees = useAppStore((s) =>
Object.values(s.worktreesByRepo).some((worktrees) => worktrees.length > 0)
)
const hasWorktrees = useAppStore(getHasAnyWorktreesFromState)
const setWorkspacePortScan = useAppStore((s) => s.setWorkspacePortScan)
const setWorkspacePortScanRefreshing = useAppStore((s) => s.setWorkspacePortScanRefreshing)
const inFlightRef = useRef<Promise<void> | null>(null)
@@ -16,6 +16,7 @@ vi.mock('@/lib/worktree-activation', () => ({
import {
browserUrlForPort,
getLocalWorkspacePortSections,
killWorkspacePortForTarget,
openWorkspacePortInBrowser,
scanWorkspacePortsForTarget
@@ -95,6 +96,87 @@ describe('PortsPanel runtime routing', () => {
expect(runtimeEnvironmentCall).not.toHaveBeenCalled()
})
it('coalesces concurrent local scans for the same runtime target and repo', async () => {
let resolveScan: (scan: WorkspacePortScanResult) => void = () => {}
localScan.mockReturnValueOnce(
new Promise<WorkspacePortScanResult>((resolve) => {
resolveScan = resolve
})
)
const first = scanWorkspacePortsForTarget({ kind: 'local' }, 'repo')
const second = scanWorkspacePortsForTarget({ kind: 'local' }, 'repo')
expect(localScan).toHaveBeenCalledTimes(1)
expect(localScan).toHaveBeenCalledWith({ repoId: 'repo' })
resolveScan(emptyScan)
await expect(Promise.all([first, second])).resolves.toEqual([emptyScan, emptyScan])
})
it('keeps separate scan keys for different repos', async () => {
localScan.mockResolvedValue(emptyScan)
await Promise.all([
scanWorkspacePortsForTarget({ kind: 'local' }, 'repo-a'),
scanWorkspacePortsForTarget({ kind: 'local' }, 'repo-b')
])
expect(localScan).toHaveBeenCalledTimes(2)
expect(localScan).toHaveBeenNthCalledWith(1, { repoId: 'repo-a' })
expect(localScan).toHaveBeenNthCalledWith(2, { repoId: 'repo-b' })
})
it('keeps other repos visible as external when the panel consumes the shared scan', () => {
const sameRepoOtherWorktree: WorkspacePort = {
...workspacePort,
id: '127.0.0.1:5174:1235',
port: 5174,
pid: 1235,
owner: {
...workspacePort.owner,
worktreeId: 'repo::/workspace/other'
}
}
const otherRepoWorkspace: WorkspacePort = {
...workspacePort,
id: '127.0.0.1:5175:1236',
port: 5175,
pid: 1236,
owner: {
...workspacePort.owner,
repoId: 'other-repo',
worktreeId: 'other-repo::/workspace/other-repo',
displayName: 'other repo',
path: '/workspace/other-repo'
}
}
const unassignedPort: WorkspacePort = {
id: '127.0.0.1:5176:1237',
bindHost: '127.0.0.1',
connectHost: '127.0.0.1',
port: 5176,
pid: 1237,
processName: 'node',
protocol: 'unknown',
kind: 'external'
}
const sections = getLocalWorkspacePortSections(
{
...emptyScan,
ports: [workspacePort, sameRepoOtherWorktree, otherRepoWorkspace, unassignedPort]
},
'repo',
'repo::/workspace/app'
)
expect(sections.activePorts.map((port) => port.port)).toEqual([63468])
expect(sections.otherWorkspacePorts.map((port) => port.port)).toEqual([5174])
expect(sections.externalPorts.map((port) => port.port)).toEqual([5175, 5176])
expect(sections.externalPorts.map((port) => port.kind)).toEqual(['external', 'external'])
})
it('routes remote scans through runtime RPC and degrades on older runtimes', async () => {
runtimeEnvironmentCall.mockImplementation(({ method }: { method: string }) =>
Promise.resolve(
@@ -1,6 +1,6 @@
/* oxlint-disable max-lines -- Why: co-locates forwarded list, detected list, modal form, and
per-entry actions in one file to keep the data flow straightforward. */
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import React, { useCallback, useMemo, useState } from 'react'
import {
ExternalLink,
Copy,
@@ -44,7 +44,7 @@ import {
ContextMenuTrigger
} from '@/components/ui/context-menu'
import type { PortForwardEntry, DetectedPort } from '../../../../shared/ssh-types'
import type { WorkspacePort, WorkspacePortScanResult } from '../../../../shared/workspace-ports'
import type { WorkspacePort } from '../../../../shared/workspace-ports'
export {
browserUrlForPort,
@@ -53,7 +53,54 @@ export {
scanWorkspacePortsForTarget
} from '@/lib/workspace-port-actions'
const LOCAL_PORT_SCAN_INTERVAL_MS = 5_000
export function getLocalWorkspacePortSections(
scan: { ports: WorkspacePort[] } | null | undefined,
activeRepoId: string | null | undefined,
activeWorktreeId: string | null | undefined
): {
activePorts: WorkspacePort[]
otherWorkspacePorts: WorkspacePort[]
externalPorts: WorkspacePort[]
} {
const ports = scan?.ports ?? []
return {
activePorts: ports.filter(
(port) =>
port.kind === 'workspace' &&
port.owner.repoId === activeRepoId &&
port.owner.worktreeId === activeWorktreeId
),
otherWorkspacePorts: ports.filter(
(port) =>
port.kind === 'workspace' &&
port.owner.repoId === activeRepoId &&
port.owner.worktreeId !== activeWorktreeId
),
// Why: the old repo-scoped scan showed listeners from other repos as
// External, without workspace-only actions or cross-worktree activation.
// Keep that behavior now that the shared scan can attribute them globally.
externalPorts: ports.flatMap((port) => {
if (port.kind !== 'workspace') {
return [port]
}
return port.owner.repoId === activeRepoId ? [] : [workspacePortAsExternal(port)]
})
}
}
function workspacePortAsExternal(port: WorkspacePort & { kind: 'workspace' }): WorkspacePort {
return {
id: port.id,
bindHost: port.bindHost,
connectHost: port.connectHost,
port: port.port,
pid: port.pid,
processName: port.processName,
protocol: port.protocol,
kind: 'external'
}
}
const LOCAL_PORT_MENU_CONTENT_CLASS =
'!rounded-md !border-border/60 !bg-popover !text-popover-foreground !shadow-[0_10px_24px_rgba(0,0,0,0.18)] !backdrop-blur-none'
const LOCAL_PORT_MENU_ITEM_CLASS =
@@ -106,90 +153,42 @@ function LocalWorkspacePortsPanel({ isVisible }: { isVisible: boolean }): React.
const settings = useAppStore((s) => s.settings)
const createBrowserTab = useAppStore((s) => s.createBrowserTab)
const setRemoteBrowserPageHandle = useAppStore((s) => s.setRemoteBrowserPageHandle)
const [scan, setScan] = useState<{ key: string; result: WorkspacePortScanResult } | null>(null)
const [refreshing, setRefreshing] = useState(false)
const scan = useAppStore((s) => s.workspacePortScan)
const refreshing = useAppStore((s) => s.workspacePortScanRefreshing)
const setWorkspacePortScan = useAppStore((s) => s.setWorkspacePortScan)
const setWorkspacePortScanRefreshing = useAppStore((s) => s.setWorkspacePortScanRefreshing)
const [detailsPort, setDetailsPort] = useState<WorkspacePort | null>(null)
const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>({
other: true,
external: true
})
const inFlightScanRef = useRef<Promise<void> | null>(null)
const inFlightScanKeyRef = useRef<string | null>(null)
const scanGenerationRef = useRef(0)
const runtimeTarget = useMemo(() => getActiveRuntimeTarget(settings), [settings])
const scanKey = `${workspacePortRuntimeTargetKey(runtimeTarget)}:${activeRepo?.id ?? ''}`
const scanKey = `${workspacePortRuntimeTargetKey(runtimeTarget)}:all`
const refresh = useCallback(() => {
if (!activeRepo) {
setScan(null)
return Promise.resolve()
}
if (inFlightScanRef.current && inFlightScanKeyRef.current === scanKey) {
return inFlightScanRef.current
}
const generation = scanGenerationRef.current
setRefreshing(true)
const promise = scanWorkspacePortsForTarget(runtimeTarget, activeRepo.id)
setWorkspacePortScanRefreshing(true)
const promise = scanWorkspacePortsForTarget(runtimeTarget)
.then((nextScan) => {
if (generation === scanGenerationRef.current) {
setScan({ key: scanKey, result: nextScan })
}
setWorkspacePortScan({ key: scanKey, result: nextScan })
})
.catch((error) => {
const message = error instanceof Error ? error.message : String(error)
toast.error('Failed to refresh ports', {
description: message || 'Workspace port scan failed.'
})
})
.finally(() => {
if (inFlightScanRef.current === promise) {
inFlightScanRef.current = null
inFlightScanKeyRef.current = null
}
if (generation === scanGenerationRef.current) {
setRefreshing(false)
}
setWorkspacePortScanRefreshing(false)
})
inFlightScanRef.current = promise
inFlightScanKeyRef.current = scanKey
return promise
}, [activeRepo, runtimeTarget, scanKey])
useEffect(() => {
let cancelled = false
scanGenerationRef.current += 1
if (!isVisible) {
inFlightScanRef.current = null
inFlightScanKeyRef.current = null
setScan(null)
setRefreshing(false)
return () => {
cancelled = true
scanGenerationRef.current += 1
}
}
async function run(): Promise<void> {
try {
await refresh()
} catch {
// Why: a transient RPC failure must not halt the poll loop.
}
if (!cancelled) {
timeout = setTimeout(() => void run(), LOCAL_PORT_SCAN_INTERVAL_MS)
}
}
let timeout: ReturnType<typeof setTimeout> | null = null
setScan(null)
void run()
return () => {
cancelled = true
scanGenerationRef.current += 1
inFlightScanRef.current = null
inFlightScanKeyRef.current = null
if (timeout) {
clearTimeout(timeout)
}
}
}, [isVisible, refresh])
}, [activeRepo, runtimeTarget, scanKey, setWorkspacePortScan, setWorkspacePortScanRefreshing])
// Why: WorkspacePortScanner already owns the 5s all-worktree poll. The
// panel scopes that shared result instead of starting a second scan loop.
const displayScan = scan?.key === scanKey && isVisible ? scan.result : null
const toggleSection = useCallback((sectionId: string) => {
@@ -232,23 +231,9 @@ function LocalWorkspacePortsPanel({ isVisible }: { isVisible: boolean }): React.
[activeWorktree?.id, createBrowserTab, runtimeTarget, setRemoteBrowserPageHandle]
)
const activePorts = useMemo(
() =>
(displayScan?.ports ?? []).filter(
(port) => port.kind === 'workspace' && port.owner.worktreeId === activeWorktree?.id
),
[activeWorktree?.id, displayScan?.ports]
)
const otherWorkspacePorts = useMemo(
() =>
(displayScan?.ports ?? []).filter(
(port) => port.kind === 'workspace' && port.owner.worktreeId !== activeWorktree?.id
),
[activeWorktree?.id, displayScan?.ports]
)
const externalPorts = useMemo(
() => (displayScan?.ports ?? []).filter((port) => port.kind !== 'workspace'),
[displayScan?.ports]
const { activePorts, otherWorkspacePorts, externalPorts } = useMemo(
() => getLocalWorkspacePortSections(displayScan, activeRepo?.id, activeWorktree?.id),
[activeRepo?.id, activeWorktree?.id, displayScan]
)
if (!activeRepo) {
@@ -94,4 +94,36 @@ describe('useWorktreeActivityStatus', () => {
'<span>working</span>'
)
})
it('scopes cached agent summaries to the matching worktree', () => {
const firstWorktreeId = 'repo1::/path/wt1'
const secondWorktreeId = 'repo1::/path/wt2'
const firstPaneKey = makePaneKey('tab-1', LEAF_ID)
mockState = {
...mockState,
tabsByWorktree: {
[firstWorktreeId]: [makeTab('tab-1', firstWorktreeId)],
[secondWorktreeId]: [makeTab('tab-2', secondWorktreeId)]
},
ptyIdsByTabId: {
'tab-1': ['pty-1'],
'tab-2': []
},
agentStatusByPaneKey: {
[firstPaneKey]: makeAgentStatusEntry({ paneKey: firstPaneKey, state: 'working' })
},
retainedAgentsByPaneKey: {
'tab-2:0': {
worktreeId: secondWorktreeId
}
}
}
expect(renderToStaticMarkup(<StatusProbe worktreeId={firstWorktreeId} />)).toBe(
'<span>working</span>'
)
expect(renderToStaticMarkup(<StatusProbe worktreeId={secondWorktreeId} />)).toBe(
'<span>done</span>'
)
})
})
@@ -1,16 +1,13 @@
import { useMemo } from 'react'
import { useShallow } from 'zustand/react/shallow'
import { useAppStore } from '@/store'
import { isExplicitAgentStatusFresh } from '@/lib/agent-status'
import { migrationUnsupportedToAgentStatusEntry } from '@/lib/migration-unsupported-agent-entry'
import { resolveWorktreeStatus, type WorktreeStatus } from '@/lib/worktree-status'
import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-types'
import { parsePaneKey } from '../../../../shared/stable-pane-id'
import { EMPTY_BROWSER_TABS, EMPTY_TABS } from './WorktreeCardHelpers'
import {
selectLivePtyIdsForWorktree,
selectRuntimePaneTitlesForWorktree
} from './worktree-card-status-inputs'
import { selectWorktreeAgentActivitySummary } from './worktree-agent-activity-summary'
export function useWorktreeActivityStatus(worktreeId: string): WorktreeStatus {
const tabs = useAppStore((s) => s.tabsByWorktree[worktreeId] ?? EMPTY_TABS)
@@ -22,61 +19,7 @@ export function useWorktreeActivityStatus(worktreeId: string): WorktreeStatus {
useShallow((s) => selectLivePtyIdsForWorktree(s, worktreeId))
)
const { hasPermission, hasLiveWorking, hasLiveDone, hasRetainedDone } = useAppStore(
useShallow((s) => {
// Touch the epoch so this selector re-runs when a fresh hook entry
// crosses the stale boundary.
void s.agentStatusEpoch
const wtTabs = s.tabsByWorktree[worktreeId] ?? EMPTY_TABS
let perm = false
let working = false
let done = false
if (wtTabs.length > 0) {
const tabIds = new Set(wtTabs.map((tab) => tab.id))
const now = Date.now()
for (const [paneKey, entry] of Object.entries(s.agentStatusByPaneKey)) {
const tabId = getPaneKeyTabId(paneKey)
if (!tabId || !tabIds.has(tabId)) {
continue
}
if (!isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)) {
continue
}
if (entry.state === 'blocked' || entry.state === 'waiting') {
perm = true
} else if (entry.state === 'working') {
working = true
} else if (entry.state === 'done') {
done = true
}
}
// Why: focused hook tests and older hydrated snapshots may not carry
// this newer map yet; absence means there are no unsupported agents.
for (const unsupported of Object.values(s.migrationUnsupportedByPtyId ?? {})) {
const entry = migrationUnsupportedToAgentStatusEntry(unsupported)
if (!entry) {
continue
}
const tabId = getPaneKeyTabId(entry.paneKey)
if (tabId && tabIds.has(tabId)) {
perm = true
}
}
}
let retained = false
for (const agent of Object.values(s.retainedAgentsByPaneKey)) {
if (agent.worktreeId === worktreeId) {
retained = true
break
}
}
return {
hasPermission: perm,
hasLiveWorking: working,
hasLiveDone: done,
hasRetainedDone: retained
}
})
useShallow((s) => selectWorktreeAgentActivitySummary(s, worktreeId))
)
// Why: compact and detailed cards need the same status-dot semantics:
@@ -106,18 +49,3 @@ export function useWorktreeActivityStatus(worktreeId: string): WorktreeStatus {
]
)
}
function getPaneKeyTabId(paneKey: string): string | null {
const parsed = parsePaneKey(paneKey)
if (parsed) {
return parsed.tabId
}
// Why: restored snapshots and older test fixtures can still carry the
// pre-stable-pane-id `tabId:numericPaneId` key; status only needs tab scope.
const sepIdx = paneKey.indexOf(':')
if (sepIdx <= 0 || sepIdx !== paneKey.lastIndexOf(':') || sepIdx === paneKey.length - 1) {
return null
}
return paneKey.slice(0, sepIdx)
}
@@ -0,0 +1,55 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
import { makePaneKey } from '../../../../shared/stable-pane-id'
import { selectWorktreeAgentActivitySummary } from './worktree-agent-activity-summary'
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
function makeAgentStatusEntry(args: {
paneKey: string
state: AgentStatusEntry['state']
}): AgentStatusEntry {
return {
paneKey: args.paneKey,
state: args.state,
prompt: '',
updatedAt: 1_000,
stateStartedAt: 1_000,
stateHistory: []
}
}
describe('selectWorktreeAgentActivitySummary', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('builds one cached agent summary index for multiple worktree lookups', () => {
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(2_000)
const firstPaneKey = makePaneKey('tab-1', LEAF_ID)
const state = {
tabsByWorktree: {
'repo::/wt-1': [{ id: 'tab-1' }],
'repo::/wt-2': [{ id: 'tab-2' }]
},
agentStatusEpoch: 0,
agentStatusByPaneKey: {
[firstPaneKey]: makeAgentStatusEntry({ paneKey: firstPaneKey, state: 'working' })
},
migrationUnsupportedByPtyId: {},
retainedAgentsByPaneKey: {
'tab-2:0': { worktreeId: 'repo::/wt-2' }
}
}
expect(selectWorktreeAgentActivitySummary(state as never, 'repo::/wt-1')).toMatchObject({
hasLiveWorking: true,
hasRetainedDone: false
})
expect(selectWorktreeAgentActivitySummary(state as never, 'repo::/wt-2')).toMatchObject({
hasLiveWorking: false,
hasRetainedDone: true
})
expect(nowSpy).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,151 @@
import type { AppState } from '@/store'
import { isExplicitAgentStatusFresh } from '@/lib/agent-status'
import { migrationUnsupportedToAgentStatusEntry } from '@/lib/migration-unsupported-agent-entry'
import {
AGENT_STATUS_STALE_AFTER_MS,
type AgentStatusEntry
} from '../../../../shared/agent-status-types'
import { parsePaneKey } from '../../../../shared/stable-pane-id'
export type WorktreeAgentActivitySummary = {
hasPermission: boolean
hasLiveWorking: boolean
hasLiveDone: boolean
hasRetainedDone: boolean
}
const EMPTY_SUMMARY: WorktreeAgentActivitySummary = {
hasPermission: false,
hasLiveWorking: false,
hasLiveDone: false,
hasRetainedDone: false
}
type AgentActivityInput = Pick<
AppState,
| 'tabsByWorktree'
| 'agentStatusEpoch'
| 'agentStatusByPaneKey'
| 'migrationUnsupportedByPtyId'
| 'retainedAgentsByPaneKey'
>
type AgentActivityCache = {
tabsByWorktree: AppState['tabsByWorktree']
agentStatusEpoch: number
agentStatusByPaneKey: AppState['agentStatusByPaneKey']
migrationUnsupportedByPtyId: AppState['migrationUnsupportedByPtyId']
retainedAgentsByPaneKey: AppState['retainedAgentsByPaneKey']
summaries: Map<string, WorktreeAgentActivitySummary>
}
let agentActivityCache: AgentActivityCache | null = null
export function selectWorktreeAgentActivitySummary(
state: AgentActivityInput,
worktreeId: string
): WorktreeAgentActivitySummary {
return getWorktreeAgentActivitySummaries(state).get(worktreeId) ?? EMPTY_SUMMARY
}
function getWorktreeAgentActivitySummaries(
state: AgentActivityInput
): Map<string, WorktreeAgentActivitySummary> {
if (
agentActivityCache &&
agentActivityCache.tabsByWorktree === state.tabsByWorktree &&
agentActivityCache.agentStatusEpoch === state.agentStatusEpoch &&
agentActivityCache.agentStatusByPaneKey === state.agentStatusByPaneKey &&
agentActivityCache.migrationUnsupportedByPtyId === state.migrationUnsupportedByPtyId &&
agentActivityCache.retainedAgentsByPaneKey === state.retainedAgentsByPaneKey
) {
return agentActivityCache.summaries
}
// Why: status dots render once per visible worktree. Build the tab/worktree
// index once per store snapshot so agent pings are O(worktrees + agents),
// not O(worktrees * agents).
const tabIdToWorktreeId = new Map<string, string>()
for (const [worktreeId, tabs] of Object.entries(state.tabsByWorktree)) {
for (const tab of tabs) {
tabIdToWorktreeId.set(tab.id, worktreeId)
}
}
const summaries = new Map<string, WorktreeAgentActivitySummary>()
const summaryForWorktree = (worktreeId: string): WorktreeAgentActivitySummary => {
let summary = summaries.get(worktreeId)
if (!summary) {
summary = { ...EMPTY_SUMMARY }
summaries.set(worktreeId, summary)
}
return summary
}
const now = Date.now()
for (const [paneKey, entry] of Object.entries(state.agentStatusByPaneKey)) {
const worktreeId = worktreeIdForPaneKey(paneKey, tabIdToWorktreeId)
if (!worktreeId || !isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)) {
continue
}
applyLiveAgentState(summaryForWorktree(worktreeId), entry)
}
for (const unsupported of Object.values(state.migrationUnsupportedByPtyId ?? {})) {
const entry = migrationUnsupportedToAgentStatusEntry(unsupported)
const worktreeId = entry ? worktreeIdForPaneKey(entry.paneKey, tabIdToWorktreeId) : null
if (worktreeId) {
summaryForWorktree(worktreeId).hasPermission = true
}
}
for (const retained of Object.values(state.retainedAgentsByPaneKey)) {
summaryForWorktree(retained.worktreeId).hasRetainedDone = true
}
agentActivityCache = {
tabsByWorktree: state.tabsByWorktree,
agentStatusEpoch: state.agentStatusEpoch,
agentStatusByPaneKey: state.agentStatusByPaneKey,
migrationUnsupportedByPtyId: state.migrationUnsupportedByPtyId,
retainedAgentsByPaneKey: state.retainedAgentsByPaneKey,
summaries
}
return summaries
}
function applyLiveAgentState(
summary: WorktreeAgentActivitySummary,
entry: Pick<AgentStatusEntry, 'state'>
): void {
if (entry.state === 'blocked' || entry.state === 'waiting') {
summary.hasPermission = true
} else if (entry.state === 'working') {
summary.hasLiveWorking = true
} else if (entry.state === 'done') {
summary.hasLiveDone = true
}
}
function worktreeIdForPaneKey(
paneKey: string,
tabIdToWorktreeId: Map<string, string>
): string | null {
const tabId = getPaneKeyTabId(paneKey)
return tabId ? (tabIdToWorktreeId.get(tabId) ?? null) : null
}
function getPaneKeyTabId(paneKey: string): string | null {
const parsed = parsePaneKey(paneKey)
if (parsed) {
return parsed.tabId
}
// Why: restored snapshots and older test fixtures can still carry the
// pre-stable-pane-id `tabId:numericPaneId` key; status only needs tab scope.
const sepIdx = paneKey.indexOf(':')
if (sepIdx <= 0 || sepIdx !== paneKey.lastIndexOf(':') || sepIdx === paneKey.length - 1) {
return null
}
return paneKey.slice(0, sepIdx)
}
+29 -1
View File
@@ -84,7 +84,13 @@ export function workspacePortRuntimeTargetKey(target: RuntimeClientTarget): stri
return target.kind === 'local' ? 'local' : `environment:${target.environmentId}`
}
export async function scanWorkspacePortsForTarget(
const inFlightWorkspacePortScans = new Map<string, Promise<WorkspacePortScanResult>>()
function workspacePortScanRequestKey(target: RuntimeClientTarget, repoId?: string): string {
return JSON.stringify([workspacePortRuntimeTargetKey(target), repoId ?? null])
}
async function runWorkspacePortScanForTarget(
target: RuntimeClientTarget,
repoId?: string
): Promise<WorkspacePortScanResult> {
@@ -109,6 +115,28 @@ export async function scanWorkspacePortsForTarget(
}
}
export async function scanWorkspacePortsForTarget(
target: RuntimeClientTarget,
repoId?: string
): Promise<WorkspacePortScanResult> {
const key = workspacePortScanRequestKey(target, repoId)
const existing = inFlightWorkspacePortScans.get(key)
if (existing) {
return existing
}
// Why: visible surfaces can request the same scan on the same tick
// (focus refresh, status bar, side panel, stop refresh). Share it so one
// UI burst cannot fan out into duplicate lsof/netstat/RPC work.
const promise = runWorkspacePortScanForTarget(target, repoId).finally(() => {
if (inFlightWorkspacePortScans.get(key) === promise) {
inFlightWorkspacePortScans.delete(key)
}
})
inFlightWorkspacePortScans.set(key, promise)
return promise
}
export async function killWorkspacePortForTarget(
target: RuntimeClientTarget,
args: { repoId: string; pid: number; port: number }
+18
View File
@@ -15,6 +15,7 @@ type WorktreeSnapshot = {
// needs cross-render caching. WeakMap ties each snapshot to the store slice ref
// without pinning old test/dev instances in memory once that slice is replaced.
const worktreeSnapshotCache = new WeakMap<AppState['worktreesByRepo'], WorktreeSnapshot>()
const hasAnyWorktreesCache = new WeakMap<AppState['worktreesByRepo'], boolean>()
const repoMapCache = new WeakMap<AppState['repos'], Map<string, Repo>>()
function getWorktreeSnapshot(worktreesByRepo: AppState['worktreesByRepo']): WorktreeSnapshot {
@@ -50,6 +51,19 @@ function getCachedWorktreeMap(worktreesByRepo: AppState['worktreesByRepo']): Map
return getWorktreeSnapshot(worktreesByRepo).worktreeMap
}
function getCachedHasAnyWorktrees(worktreesByRepo: AppState['worktreesByRepo']): boolean {
const cached = hasAnyWorktreesCache.get(worktreesByRepo)
if (cached !== undefined) {
return cached
}
// Why: this selector sits in an always-mounted scanner. Cache by slice
// identity so unrelated store writes do not rescan every repo bucket.
const hasWorktrees = Object.values(worktreesByRepo).some((worktrees) => worktrees.length > 0)
hasAnyWorktreesCache.set(worktreesByRepo, hasWorktrees)
return hasWorktrees
}
function getCachedRepoMap(repos: AppState['repos']): Map<string, Repo> {
const cachedMap = repoMapCache.get(repos)
if (cachedMap) {
@@ -71,6 +85,10 @@ export function getWorktreeMapFromState(
return getCachedWorktreeMap(state.worktreesByRepo)
}
export function getHasAnyWorktreesFromState(state: Pick<AppState, 'worktreesByRepo'>): boolean {
return getCachedHasAnyWorktrees(state.worktreesByRepo)
}
export function getRepoMapFromState(state: Pick<AppState, 'repos'>): Map<string, Repo> {
return getCachedRepoMap(state.repos)
}